hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f34791f6d0f0984d98a815c94b9e7f4e60f8a4e4 | 8,919 | lua | Lua | Modules/Server/Ragdoll/RagdollRigtypes.lua | EKKBull/NevermoreEngine | 2ceeb41beee18a85ccc4faa8d06f9bc4cf5c1d12 | [
"MIT"
] | null | null | null | Modules/Server/Ragdoll/RagdollRigtypes.lua | EKKBull/NevermoreEngine | 2ceeb41beee18a85ccc4faa8d06f9bc4cf5c1d12 | [
"MIT"
] | null | null | null | Modules/Server/Ragdoll/RagdollRigtypes.lua | EKKBull/NevermoreEngine | 2ceeb41beee18a85ccc4faa8d06f9bc4cf5c1d12 | [
"MIT"
] | null | null | null | --- Rig types and data for ragdolling R15
-- @module RagdollRigtypes
local RagdollRigtypes = {}
local HEAD_LIMITS = {
UpperAngle = 60;
TwistLowerAngle = -60;
TwistUpperAngle = 60;
}
local LOWER_TORSO_LIMITS = {
UpperAngle = 5;
TwistLowerAngle = -30;
TwistUpperAngle = 60;
}
local HAND_FOOT_LIMITS = {
UpperAngle = 15;
TwistLowerAngle = -5;
TwistUpperAngle = 5;
}
local ELBOW_LIMITS = {
UpperAngle = 5;
TwistLowerAngle = 0;
TwistUpperAngle = 120;
}
local KNEE_LIMITS = {
UpperAngle = 5;
TwistLowerAngle = -120;
TwistUpperAngle = 0;
}
local SHOULDER_LIMITS = {
UpperAngle = 60;
TwistLowerAngle = -60;
TwistUpperAngle = 175;
}
local HIP_LIMITS = {
UpperAngle = 40;
TwistLowerAngle = -5;
TwistUpperAngle = 150;
}
local R6_HEAD_LIMITS = {
UpperAngle = 30;
TwistLowerAngle = -60;
TwistUpperAngle = 60;
}
local R6_SHOULDER_LIMITS = {
UpperAngle = 90;
TwistLowerAngle = -30;
TwistUpperAngle = 175;
}
local R6_HIP_LIMITS = {
UpperAngle = 60;
TwistLowerAngle = -5;
TwistUpperAngle = 120;
}
local function createJointData(attach0, attach1, limits)
assert(attach0)
assert(attach1)
assert(limits)
assert(limits.UpperAngle >= 0)
assert(limits.TwistLowerAngle <= limits.TwistUpperAngle)
return {
attachment0 = attach0,
attachment1 = attach1,
limits = limits
}
end
local function find(model)
return function(first, second, limits)
local part0 = model:FindFirstChild(first[1])
local part1 = model:FindFirstChild(second[1])
if part0 and part1 then
local attach0 = part0:FindFirstChild(first[2])
local attach1 = part1:FindFirstChild(second[2])
if attach0 and attach1 and attach0:IsA("Attachment") and attach1:IsA("Attachment") then
return createJointData(attach0, attach1, limits)
end
end
end
end
function RagdollRigtypes.getNoCollisions(model, rigType)
if rigType == Enum.HumanoidRigType.R6 then
return RagdollRigtypes.getR6NoCollisions(model)
elseif rigType == Enum.HumanoidRigType.R15 then
return RagdollRigtypes.getR15NoCollisions(model)
else
warn("[RagdollRigtypes.getAttachments] - UnknownRigType")
return {}
end
end
-- Get list of attachments to make ballsocketconstraints between:
function RagdollRigtypes.getAttachments(model, rigType)
if rigType == Enum.HumanoidRigType.R6 then
return RagdollRigtypes.getR6Attachments(model)
elseif rigType == Enum.HumanoidRigType.R15 then
return RagdollRigtypes.getR15Attachments(model)
else
warn("[RagdollRigtypes.getAttachments] - UnknownRigType")
return {}
end
end
function RagdollRigtypes.getR6Attachments(model)
local rightLegAttachment = Instance.new("Attachment")
rightLegAttachment.Name = "RagdollRightLegAttachment"
rightLegAttachment.Position = Vector3.new(0, 1, 0)
rightLegAttachment.Parent = model:FindFirstChild("Right Leg")
local leftLegAttachment = Instance.new("Attachment")
leftLegAttachment.Name = "RagdollLeftLegAttachment"
leftLegAttachment.Position = Vector3.new(0, 1, 0)
leftLegAttachment.Parent = model:FindFirstChild("Left Leg")
local torsoLeftAttachment = Instance.new("Attachment")
torsoLeftAttachment.Name = "RagdollTorsoLeftAttachment"
torsoLeftAttachment.Position = Vector3.new(-0.5, -1, 0)
torsoLeftAttachment.Parent = model:FindFirstChild("Torso")
local torsoRightAttachment = Instance.new("Attachment")
torsoRightAttachment.Name = "RagdollTorsoRightAttachment"
torsoRightAttachment.Position = Vector3.new(0.5, -1, 0)
torsoRightAttachment.Parent = model:FindFirstChild("Torso")
local headAttachment = Instance.new("Attachment")
headAttachment.Name = "RagdollHeadAttachment"
headAttachment.Position = Vector3.new(0, -0.5, 0)
headAttachment.Parent = model:FindFirstChild("Head")
local leftArmAttachment = Instance.new("Attachment")
leftArmAttachment.Name = "RagdollLeftArmAttachment"
leftArmAttachment.Position = Vector3.new(0.5, 1, 0)
leftArmAttachment.Parent = model:FindFirstChild("Left Arm")
local ragdollRightArmAttachment = Instance.new("Attachment")
ragdollRightArmAttachment.Name = "RagdollRightArmAttachment"
ragdollRightArmAttachment.Position = Vector3.new(-0.5, 1, 0)
ragdollRightArmAttachment.Parent = model:FindFirstChild("Right Arm")
local query = find(model)
return {
Head = query(
{"Torso", "NeckAttachment"},
{"Head", "RagdollHeadAttachment"},
R6_HEAD_LIMITS),
["Left Arm"] = query(
{"Torso", "LeftCollarAttachment"},
{"Left Arm", "RagdollLeftArmAttachment"},
R6_SHOULDER_LIMITS),
["Right Arm"] = query(
{"Torso", "RightCollarAttachment"},
{"Right Arm", "RagdollRightArmAttachment"},
R6_SHOULDER_LIMITS),
["Left Leg"] = createJointData(torsoLeftAttachment, leftLegAttachment, R6_HIP_LIMITS),
["Right Leg"] = createJointData(torsoRightAttachment, rightLegAttachment, R6_HIP_LIMITS),
}
end
function RagdollRigtypes.getR15Attachments(model)
local query = find(model)
return {
Head = query(
{"UpperTorso", "NeckRigAttachment"},
{"Head", "NeckRigAttachment"},
HEAD_LIMITS),
LowerTorso = query(
{"UpperTorso", "WaistRigAttachment"},
{"LowerTorso", "RootRigAttachment"},
LOWER_TORSO_LIMITS),
LeftUpperArm = query(
{"UpperTorso", "LeftShoulderRigAttachment"},
{"LeftUpperArm", "LeftShoulderRigAttachment"},
SHOULDER_LIMITS),
LeftLowerArm = query(
{"LeftUpperArm", "LeftElbowRigAttachment"},
{"LeftLowerArm", "LeftElbowRigAttachment"},
ELBOW_LIMITS),
LeftHand = query(
{"LeftLowerArm", "LeftWristRigAttachment"},
{"LeftHand", "LeftWristRigAttachment"},
HAND_FOOT_LIMITS),
RightUpperArm = query(
{"UpperTorso", "RightShoulderRigAttachment"},
{"RightUpperArm", "RightShoulderRigAttachment"},
SHOULDER_LIMITS),
RightLowerArm = query(
{"RightUpperArm", "RightElbowRigAttachment"},
{"RightLowerArm", "RightElbowRigAttachment"},
ELBOW_LIMITS),
RightHand = query(
{"RightLowerArm", "RightWristRigAttachment"},
{"RightHand", "RightWristRigAttachment"},
HAND_FOOT_LIMITS),
LeftUpperLeg = query(
{"LowerTorso", "LeftHipRigAttachment"},
{"LeftUpperLeg", "LeftHipRigAttachment"},
HIP_LIMITS),
LeftLowerLeg = query(
{"LeftUpperLeg", "LeftKneeRigAttachment"},
{"LeftLowerLeg", "LeftKneeRigAttachment"},
KNEE_LIMITS),
LeftFoot = query(
{"LeftLowerLeg", "LeftAnkleRigAttachment"},
{"LeftFoot", "LeftAnkleRigAttachment"},
HAND_FOOT_LIMITS),
RightUpperLeg = query(
{"LowerTorso", "RightHipRigAttachment"},
{"RightUpperLeg", "RightHipRigAttachment"},
HIP_LIMITS),
RightLowerLeg = query(
{"RightUpperLeg", "RightKneeRigAttachment"},
{"RightLowerLeg", "RightKneeRigAttachment"},
KNEE_LIMITS),
RightFoot = query(
{"RightLowerLeg", "RightAnkleRigAttachment"},
{"RightFoot", "RightAnkleRigAttachment"},
HAND_FOOT_LIMITS),
}
end
function RagdollRigtypes.getR6NoCollisions(model)
local list = {}
local function addPair(pair)
local part0 = model:FindFirstChild(pair[1])
local part1 = model:FindFirstChild(pair[2])
if part0 and part1 then
table.insert(list, {part0, part1})
end
end
addPair({"Head", "Torso"})
addPair({"Left Arm", "Torso"})
addPair({"Right Arm", "Torso"})
addPair({"Left Leg", "Torso"})
addPair({"Right Leg", "Torso"})
addPair({"Left Leg", "Right Leg"})
return list
end
function RagdollRigtypes.getR15NoCollisions(model)
local list = {}
local function addPair(pair)
local part0 = model:FindFirstChild(pair[1])
local part1 = model:FindFirstChild(pair[2])
if part0 and part1 then
table.insert(list, {part0, part1})
end
end
addPair({"Head", "UpperTorso"})
addPair({"UpperTorso", "LowerTorso"})
addPair({"UpperTorso", "LeftUpperArm"})
addPair({"LowerTorso", "LeftUpperArm"})
addPair({"LeftUpperArm", "LeftLowerArm"})
addPair({"LeftLowerArm", "LeftHand"})
addPair({"LeftUpperArm", "LeftHand"})
addPair({"UpperTorso", "RightUpperArm"})
addPair({"LowerTorso", "RightUpperArm"})
addPair({"RightUpperArm", "RightLowerArm"})
addPair({"RightLowerArm", "RightHand"})
addPair({"RightUpperArm", "RightHand"})
addPair({"LeftUpperLeg", "RightUpperLeg"})
addPair({"UpperTorso", "RightUpperLeg"})
addPair({"LowerTorso", "RightUpperLeg"})
addPair({"RightUpperLeg", "RightLowerLeg"})
addPair({"RightLowerLeg", "RightFoot"})
addPair({"RightUpperLeg", "RightFoot"})
addPair({"UpperTorso", "LeftUpperLeg"})
addPair({"LowerTorso", "LeftUpperLeg"})
addPair({"LeftUpperLeg", "LeftLowerLeg"})
addPair({"LeftLowerLeg", "LeftFoot"})
addPair({"LeftUpperLeg", "LeftFoot"})
-- Support weird R15 rigs
addPair({"UpperTorso", "LeftLowerLeg"})
addPair({"UpperTorso", "RightLowerLeg"})
addPair({"LowerTorso", "LeftLowerLeg"})
addPair({"LowerTorso", "RightLowerLeg"})
addPair({"UpperTorso", "LeftLowerArm"})
addPair({"UpperTorso", "RightLowerArm"})
local upperTorso = model:FindFirstChild("UpperTorso")
if upperTorso and upperTorso.Size.x <= 1.5 then
addPair({"Head", "LeftUpperArm"})
addPair({"Head", "RightUpperArm"})
end
return list
end
return RagdollRigtypes | 27.443077 | 91 | 0.734163 |
a9ba0203e5c39a2b1777026661dc209437f62948 | 817 | html | HTML | src/pages/lista-iconos/lista-iconos.html | gusespinoza/onGroup | 61931ea5eb4906971914b817200cd2174884d883 | [
"MIT"
] | null | null | null | src/pages/lista-iconos/lista-iconos.html | gusespinoza/onGroup | 61931ea5eb4906971914b817200cd2174884d883 | [
"MIT"
] | null | null | null | src/pages/lista-iconos/lista-iconos.html | gusespinoza/onGroup | 61931ea5eb4906971914b817200cd2174884d883 | [
"MIT"
] | null | null | null | <!--
Generated template for the ListaIconosPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-content class="transparent" >
<ion-card >
<div class="icon-card">
<ion-card-content text-center>
<ion-list lines>
<ion-list-header>
<ion-icon name="pin" item-start></ion-icon><h1 class="text-bigsize">Pin en el Mapa</h1>
<hr>
</ion-list-header>
<button ion-item (click)="salvaIcono(icono, i)" *ngFor="let icono of listaIconos; let i = index">
<ion-thumbnail item-start>
<img class="foo04" [src]="urlIco(icono.icono)">
</ion-thumbnail>
<h2 class="text-baloo">{{icono.nombre}}</h2>
</button>
</ion-list>
</ion-card-content>
</div>
</ion-card>
</ion-content>
| 25.53125 | 102 | 0.624235 |
400f795ffac8eb07f4ec6d725b2d5628c194ee10 | 4,362 | py | Python | src/web/modules/install/modules/search/install.py | unkyulee/elastic-cms | 3ccf4476c3523d4fefc0d8d9dee0196815b81489 | [
"MIT"
] | 2 | 2017-04-30T07:29:23.000Z | 2017-04-30T07:36:27.000Z | src/web/modules/install/modules/search/install.py | unkyulee/elastic-cms | 3ccf4476c3523d4fefc0d8d9dee0196815b81489 | [
"MIT"
] | null | null | null | src/web/modules/install/modules/search/install.py | unkyulee/elastic-cms | 3ccf4476c3523d4fefc0d8d9dee0196815b81489 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import glob, os
from lib import config # config.py
import lib.es as es
from lib.read import readfile
import web.util.tools as tools
def install(host, base_dir):
# check if search site exists
sites = es.list(host, 'core_nav', 'site', "name:'search'")
if not sites:
# create a site
site = {
'name' : 'search',
'display_name' : 'Search Engine'
}
es.create(host, 'core_nav', 'site', 'search', site)
# create a navigation
navigation = {
"site_id": 'search',
"module_id": '10',
"order_key": 100,
"is_displayed": '1',
"name" : 'search',
"display_name" : 'Search Engine',
"new_window" : '0'
}
es.create(host, 'core_nav', 'navigation', 'searchnav', navigation)
# set up the site
config = {
'name': 'index',
'value': 'everything'
}
es.create( host, 'core_nav', 'config', 'searchnav_{}'.format(config['name']), config)
config = {
'name': 'host',
'value': 'http://localhost:9200'
}
es.create( host, 'core_nav', 'config', 'searchnav_{}'.format(config['name']), config)
config = {
'name': 'search_item_template',
'value': """
{% extends "post/search/base.html" %}
{% macro default(post) %}
<table class="table">
<tr><th class="bg-success">
<!-- Type -->
<span class="label label-info">{{ post._index }}</span>
<!-- Title -->
<span>
{% if post.url %}
<a href="{{post.url}}" target=_blank>
{% else %}
<a href="/search/redirect?index={{post._index}}&id={{post.id}}">
{% endif %}
<b>{{post.highlight.title|first|safe}}</b>
</a>
</span>
</th></tr>
<tbody>
{% if p.field_list|length > 0 %}
<tr><td>
{% for field in p.field_list
if field.id != "title"
and field.id != "description"
and post[field.id] %}
<div class="col-lg-6 col-md-6">
<label class="col-lg-4 col-md-4 control-label">{{field.name}}</label>
<div class="col-lg-8 col-md-8">
{% if field.list_tpl %}
{{ field.list_tpl|render(p, post)|safe }}
{% elif field.handler == "file" %}
<a href="{{p.url}}/file/view/{{post[field.id]}}?id={{post.id}}" target=_blank>
download
</a>
{% elif field.handler == "multiple" %}
{% for v in post[field.id]|getlist %}
{% if field.is_filter == "1" %}<a href="{{p.url}}?{{field.name}}={{v|strip}}">{% endif %}
{{v|strip}}
{% if field.is_filter == "1" %}</a>{% endif %}
{%- if not loop.last %}, {% endif %}
{% endfor %}
{% else %}
{% if field.is_filter == "1" %}<a href="{{p.url}}?{{field.name}}={{ post[field.id] }}">{% endif %}
{{ post[field.id] }}
{% if field.is_filter == "1" %}</a>{% endif %}
{%endif%}
</div>
</div>
{%endfor%}
</td></tr>
{% endif %}
{% if post.highlight.description or post.highlight.content %}
<tr><td>
{{post.highlight.description|first|safe}}
{{post.highlight.content|first|safe}}
</td></tr>
{% endif %}
<tr><td>
{% if post.url %}
<a href="{{post.url}}" target=_blank>{{post.url}}</a> -
{% endif %}
<small>{{post.created|dt}}</small>
</td></tr>
</tbody>
</table>
<br>
{% endmacro %}
{% block search_result %}
{% include "post/search/part/summary.html" %}
{% include "post/search/part/didyoumean.html" %}
{% for post in p.post_list %}
{{ default(post) }}
{% endfor %}
{% include "post/search/part/pagination.html" %}
{# display create icon when post/create is allowed #}
{% if 'post/create' in p.allowed_operation %}
<div class="col-lg-12 text-right">
<a href="{{p.url}}/post/create" title="new">
<button type="button" class="btn btn-xs btn-danger">
<span class="glyphicon glyphicon-plus"></span> New
</button>
</a>
</div>
{% endif %}
{% endblock %}
"""
}
es.create( host, 'search', 'config', config['name'], config)
| 26.925926 | 112 | 0.49083 |
b33ce85babf06d5c32ddb18a496ee22d5e102bb5 | 173 | sql | SQL | docker/mssql/test/database.sql | nax2uk/nhs-virtual-visit-deploy | 2da53cb24ce4887809bae275a6cd9007207a79cc | [
"MIT"
] | 17 | 2020-04-25T11:35:34.000Z | 2022-01-18T02:39:19.000Z | docker/mssql/test/database.sql | nax2uk/nhs-virtual-visit-deploy | 2da53cb24ce4887809bae275a6cd9007207a79cc | [
"MIT"
] | 243 | 2020-04-27T16:44:04.000Z | 2022-03-29T03:05:57.000Z | docker/mssql/test/database.sql | AlexHerbertMadeTech/nhs-virtual-visit | 4a5a95feb4801a6348e5539c7c90ca03fabf0a0b | [
"MIT"
] | 13 | 2020-04-25T11:35:52.000Z | 2021-08-05T09:11:49.000Z | IF EXISTS (SELECT * FROM sys.databases WHERE name = 'nhs_virtual_visit_test')
BEGIN
DROP DATABASE nhs_virtual_visit_test;
END;
CREATE DATABASE nhs_virtual_visit_test;
GO | 28.833333 | 77 | 0.815029 |
f068e622315d78d7e6f6aa0f79a8a89885c43c1b | 554 | sql | SQL | web/sql/SugerirPlaza.sql | mayuelcuarto/planilla_symfony | 7e7e233c85817d6baaea1f4463cd69eba0fceed5 | [
"MIT"
] | 1 | 2018-03-07T10:20:17.000Z | 2018-03-07T10:20:17.000Z | web/sql/SugerirPlaza.sql | mayuelcuarto/planilla_symfony | 7e7e233c85817d6baaea1f4463cd69eba0fceed5 | [
"MIT"
] | null | null | null | web/sql/SugerirPlaza.sql | mayuelcuarto/planilla_symfony | 7e7e233c85817d6baaea1f4463cd69eba0fceed5 | [
"MIT"
] | null | null | null | CREATE DEFINER=`root`@`localhost` FUNCTION `SugerirPlaza`(tipoPlanilla INT) RETURNS char(6) CHARSET latin1
BEGIN
DECLARE aux INT;
DECLARE aux2 CHAR(6);
SET aux = (SELECT MAX(p.num_plaza) FROM plaza p WHERE p.tipo_planilla = tipoPlanilla) + 1;
IF aux >= 100000 THEN
SET aux2 = aux;
ELSEIF aux >= 10000 THEN
SET aux2 = CONCAT('0',aux);
ELSEIF aux >= 1000 THEN
SET aux2 = CONCAT('00',aux);
ELSEIF aux >= 100 THEN
SET aux2 = CONCAT('000',aux);
ELSEIF aux >= 10 THEN
SET aux2 = CONCAT('0000',aux);
ELSE
SET aux2 = CONCAT('00000',aux);
END IF;
RETURN aux2;
END | 27.7 | 106 | 0.712996 |
16706d85ab4a6452fd5f56bddafe3585f99c56a3 | 1,344 | h | C | Tudat/SimulationSetup/EstimationSetup/createLightTimeCorrectionPartials.h | sebranchett/tudat | 24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44 | [
"BSD-3-Clause"
] | null | null | null | Tudat/SimulationSetup/EstimationSetup/createLightTimeCorrectionPartials.h | sebranchett/tudat | 24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44 | [
"BSD-3-Clause"
] | null | null | null | Tudat/SimulationSetup/EstimationSetup/createLightTimeCorrectionPartials.h | sebranchett/tudat | 24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#ifndef TUDAT_CREATELIGHTTIMECORRECTIONPARTIALS_H
#define TUDAT_CREATELIGHTTIMECORRECTIONPARTIALS_H
#include "Tudat/Astrodynamics/ObservationModels/ObservableCorrections/lightTimeCorrection.h"
#include "Tudat/Astrodynamics/OrbitDetermination/LightTimeCorrectionPartials/lightTimeCorrectionPartial.h"
namespace tudat
{
namespace observation_partials
{
//! Function to create a partial objects from list of light time corrections.
/*!
* Function to create a partial objects from list of light time corrections.
* \param lightTimeCorrectionList List of light time corrections.
* \return List of light-time correction partial objects
*/
std::vector< std::shared_ptr< LightTimeCorrectionPartial > > createLightTimeCorrectionPartials(
const std::vector< std::shared_ptr< observation_models::LightTimeCorrection > >& lightTimeCorrectionList );
}
}
#endif // TUDAT_CREATELIGHTTIMECORRECTIONPARTIALS_H
| 35.368421 | 115 | 0.786458 |
98b4c51b9e831057be830542d1028c98ec39103c | 2,423 | dart | Dart | lib/onboarding/type2/onboard_page_two.dart | reasonpun/ContraFlutterKit | df9a22250aac9aaa298de904b69df67ba21293d4 | [
"Apache-2.0"
] | 1 | 2022-03-11T12:10:48.000Z | 2022-03-11T12:10:48.000Z | lib/onboarding/type2/onboard_page_two.dart | reasonpun/ContraFlutterKit | df9a22250aac9aaa298de904b69df67ba21293d4 | [
"Apache-2.0"
] | null | null | null | lib/onboarding/type2/onboard_page_two.dart | reasonpun/ContraFlutterKit | df9a22250aac9aaa298de904b69df67ba21293d4 | [
"Apache-2.0"
] | null | null | null | import 'package:contra_flutter_kit/onboarding/onboard_data.dart';
import 'package:contra_flutter_kit/utils/colors.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
class OnboardPageTypeTwo extends StatelessWidget {
final OnboardData data;
const OnboardPageTypeTwo({required this.data});
@override
Widget build(BuildContext context) {
return Material(
child: Container(
color: white,
child: Column(
children: <Widget>[
Expanded(
flex: 4,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
SizedBox(
height: 40,
),
Center(
child: SvgPicture.asset(
data.placeHolder,
height: 370,
width: 310,
),
),
],
),
),
),
Expanded(
flex: 2,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
left: 24.0, right: 24.0, top: 12.0, bottom: 12.0),
child: Text(
data.title,
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 36,
color: wood_smoke,
fontWeight: FontWeight.w800),
),
),
Padding(
padding: const EdgeInsets.only(
left: 24.0, right: 24.0, top: 12.0, bottom: 12.0),
child: Text(
data.description,
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 21,
color: trout,
fontWeight: FontWeight.w500),
),
),
],
),
),
],
),
),
);
}
}
| 31.467532 | 74 | 0.411473 |
2a54821967966be574e679272adf80f372769bfe | 257 | java | Java | app/src/main/java/org/elastos/wallet/ela/ui/common/viewdata/CommmonStringListViewData.java | chunshulimao/Elastos.App.UnionSquare.Android | 5ce2f327a938ae7554c6f3d53c1850a46f250304 | [
"MIT"
] | null | null | null | app/src/main/java/org/elastos/wallet/ela/ui/common/viewdata/CommmonStringListViewData.java | chunshulimao/Elastos.App.UnionSquare.Android | 5ce2f327a938ae7554c6f3d53c1850a46f250304 | [
"MIT"
] | null | null | null | app/src/main/java/org/elastos/wallet/ela/ui/common/viewdata/CommmonStringListViewData.java | chunshulimao/Elastos.App.UnionSquare.Android | 5ce2f327a938ae7554c6f3d53c1850a46f250304 | [
"MIT"
] | null | null | null | package org.elastos.wallet.ela.ui.common.viewdata;
import org.elastos.wallet.ela.rxjavahelp.BaseViewData;
import java.util.List;
public interface CommmonStringListViewData extends BaseViewData {
void onGetStringListCommonData( List<String> data);
}
| 23.363636 | 65 | 0.81323 |
f1ecc121c82f4e4a022a708ad3d3e6052dac69e4 | 76,469 | swift | Swift | Products/pb_instance_swift/c110_cmd.pb.swift | iwown/BLEMidAutumn_Swift | 215d38c80b4ccfc5797e2e2101d28d95749f1cdf | [
"BSD-3-Clause"
] | null | null | null | Products/pb_instance_swift/c110_cmd.pb.swift | iwown/BLEMidAutumn_Swift | 215d38c80b4ccfc5797e2e2101d28d95749f1cdf | [
"BSD-3-Clause"
] | 1 | 2020-04-13T20:01:03.000Z | 2020-04-13T20:01:03.000Z | Products/pb_instance_swift/c110_cmd.pb.swift | iwown/BLEMidAutumn_Swift | 215d38c80b4ccfc5797e2e2101d28d95749f1cdf | [
"BSD-3-Clause"
] | 1 | 2021-01-07T11:57:17.000Z | 2021-01-07T11:57:17.000Z | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: c110_cmd.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
enum C110Operation: SwiftProtobuf.Enum {
typealias RawValue = Int
case read // = 0
case write // = 1
init() {
self = .read
}
init?(rawValue: Int) {
switch rawValue {
case 0: self = .read
case 1: self = .write
default: return nil
}
}
var rawValue: Int {
switch self {
case .read: return 0
case .write: return 1
}
}
}
#if swift(>=4.2)
extension C110Operation: CaseIterable {
// Support synthesized by the compiler.
}
#endif // swift(>=4.2)
enum C110AQI: SwiftProtobuf.Enum {
typealias RawValue = Int
case good // = 0
case normal // = 1
case bad // = 2
case worst // = 3
init() {
self = .good
}
init?(rawValue: Int) {
switch rawValue {
case 0: self = .good
case 1: self = .normal
case 2: self = .bad
case 3: self = .worst
default: return nil
}
}
var rawValue: Int {
switch self {
case .good: return 0
case .normal: return 1
case .bad: return 2
case .worst: return 3
}
}
}
#if swift(>=4.2)
extension C110AQI: CaseIterable {
// Support synthesized by the compiler.
}
#endif // swift(>=4.2)
enum C110EcgSymptom: SwiftProtobuf.Enum {
typealias RawValue = Int
case sinusRhythm // = 0
case sinusArhythmia // = 1
case sinusTachycardia // = 2
case sinusBradycardia // = 3
case atrialFibrillation // = 4
case atrialFlutter // = 5
case atrialPrematureBeats // = 6
case ventricularPrematureBeats // = 7
case leftVentricularHypertrophy // = 8
case rightBundleBranchBlock // = 9
case leftBundleBranchBlock // = 10
init() {
self = .sinusRhythm
}
init?(rawValue: Int) {
switch rawValue {
case 0: self = .sinusRhythm
case 1: self = .sinusArhythmia
case 2: self = .sinusTachycardia
case 3: self = .sinusBradycardia
case 4: self = .atrialFibrillation
case 5: self = .atrialFlutter
case 6: self = .atrialPrematureBeats
case 7: self = .ventricularPrematureBeats
case 8: self = .leftVentricularHypertrophy
case 9: self = .rightBundleBranchBlock
case 10: self = .leftBundleBranchBlock
default: return nil
}
}
var rawValue: Int {
switch self {
case .sinusRhythm: return 0
case .sinusArhythmia: return 1
case .sinusTachycardia: return 2
case .sinusBradycardia: return 3
case .atrialFibrillation: return 4
case .atrialFlutter: return 5
case .atrialPrematureBeats: return 6
case .ventricularPrematureBeats: return 7
case .leftVentricularHypertrophy: return 8
case .rightBundleBranchBlock: return 9
case .leftBundleBranchBlock: return 10
}
}
}
#if swift(>=4.2)
extension C110EcgSymptom: CaseIterable {
// Support synthesized by the compiler.
}
#endif // swift(>=4.2)
struct C110BodyData {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
///0.0 - 99.9
var bmi: Float {
get {return _bmi ?? 0}
set {_bmi = newValue}
}
/// Returns true if `bmi` has been explicitly set.
var hasBmi: Bool {return self._bmi != nil}
/// Clears the value of `bmi`. Subsequent reads from it will return its default value.
mutating func clearBmi() {self._bmi = nil}
///0.0 - 9999.9
var bmr: Float {
get {return _bmr ?? 0}
set {_bmr = newValue}
}
/// Returns true if `bmr` has been explicitly set.
var hasBmr: Bool {return self._bmr != nil}
/// Clears the value of `bmr`. Subsequent reads from it will return its default value.
mutating func clearBmr() {self._bmr = nil}
///0.0% - 99.9
var bodyFat: Float {
get {return _bodyFat ?? 0}
set {_bodyFat = newValue}
}
/// Returns true if `bodyFat` has been explicitly set.
var hasBodyFat: Bool {return self._bodyFat != nil}
/// Clears the value of `bodyFat`. Subsequent reads from it will return its default value.
mutating func clearBodyFat() {self._bodyFat = nil}
///0.0 - 99.9
var visceralFatLevel: Float {
get {return _visceralFatLevel ?? 0}
set {_visceralFatLevel = newValue}
}
/// Returns true if `visceralFatLevel` has been explicitly set.
var hasVisceralFatLevel: Bool {return self._visceralFatLevel != nil}
/// Clears the value of `visceralFatLevel`. Subsequent reads from it will return its default value.
mutating func clearVisceralFatLevel() {self._visceralFatLevel = nil}
///0.0 - 99.9
var muscleMass: Float {
get {return _muscleMass ?? 0}
set {_muscleMass = newValue}
}
/// Returns true if `muscleMass` has been explicitly set.
var hasMuscleMass: Bool {return self._muscleMass != nil}
/// Clears the value of `muscleMass`. Subsequent reads from it will return its default value.
mutating func clearMuscleMass() {self._muscleMass = nil}
///0.0 - 99.9
var boneMass: Float {
get {return _boneMass ?? 0}
set {_boneMass = newValue}
}
/// Returns true if `boneMass` has been explicitly set.
var hasBoneMass: Bool {return self._boneMass != nil}
/// Clears the value of `boneMass`. Subsequent reads from it will return its default value.
mutating func clearBoneMass() {self._boneMass = nil}
///0.0 - 999.9
var weight: Float {
get {return _weight ?? 0}
set {_weight = newValue}
}
/// Returns true if `weight` has been explicitly set.
var hasWeight: Bool {return self._weight != nil}
/// Clears the value of `weight`. Subsequent reads from it will return its default value.
mutating func clearWeight() {self._weight = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _bmi: Float? = nil
fileprivate var _bmr: Float? = nil
fileprivate var _bodyFat: Float? = nil
fileprivate var _visceralFatLevel: Float? = nil
fileprivate var _muscleMass: Float? = nil
fileprivate var _boneMass: Float? = nil
fileprivate var _weight: Float? = nil
}
struct LifeQualityData {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var wellNessValue: UInt32 {
get {return _storage._wellNessValue ?? 0}
set {_uniqueStorage()._wellNessValue = newValue}
}
/// Returns true if `wellNessValue` has been explicitly set.
var hasWellNessValue: Bool {return _storage._wellNessValue != nil}
/// Clears the value of `wellNessValue`. Subsequent reads from it will return its default value.
mutating func clearWellNessValue() {_uniqueStorage()._wellNessValue = nil}
var activityValue: UInt32 {
get {return _storage._activityValue ?? 0}
set {_uniqueStorage()._activityValue = newValue}
}
/// Returns true if `activityValue` has been explicitly set.
var hasActivityValue: Bool {return _storage._activityValue != nil}
/// Clears the value of `activityValue`. Subsequent reads from it will return its default value.
mutating func clearActivityValue() {_uniqueStorage()._activityValue = nil}
var moodSwingsValue: UInt32 {
get {return _storage._moodSwingsValue ?? 0}
set {_uniqueStorage()._moodSwingsValue = newValue}
}
/// Returns true if `moodSwingsValue` has been explicitly set.
var hasMoodSwingsValue: Bool {return _storage._moodSwingsValue != nil}
/// Clears the value of `moodSwingsValue`. Subsequent reads from it will return its default value.
mutating func clearMoodSwingsValue() {_uniqueStorage()._moodSwingsValue = nil}
var lifestyleIndexValue: UInt32 {
get {return _storage._lifestyleIndexValue ?? 0}
set {_uniqueStorage()._lifestyleIndexValue = newValue}
}
/// Returns true if `lifestyleIndexValue` has been explicitly set.
var hasLifestyleIndexValue: Bool {return _storage._lifestyleIndexValue != nil}
/// Clears the value of `lifestyleIndexValue`. Subsequent reads from it will return its default value.
mutating func clearLifestyleIndexValue() {_uniqueStorage()._lifestyleIndexValue = nil}
var time: RtTime {
get {return _storage._time ?? RtTime()}
set {_uniqueStorage()._time = newValue}
}
/// Returns true if `time` has been explicitly set.
var hasTime: Bool {return _storage._time != nil}
/// Clears the value of `time`. Subsequent reads from it will return its default value.
mutating func clearTime() {_uniqueStorage()._time = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
struct DailyMeasure {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var timeStamp: DateTime {
get {return _storage._timeStamp ?? DateTime()}
set {_uniqueStorage()._timeStamp = newValue}
}
/// Returns true if `timeStamp` has been explicitly set.
var hasTimeStamp: Bool {return _storage._timeStamp != nil}
/// Clears the value of `timeStamp`. Subsequent reads from it will return its default value.
mutating func clearTimeStamp() {_uniqueStorage()._timeStamp = nil}
var measures: UInt32 {
get {return _storage._measures ?? 0}
set {_uniqueStorage()._measures = newValue}
}
/// Returns true if `measures` has been explicitly set.
var hasMeasures: Bool {return _storage._measures != nil}
/// Clears the value of `measures`. Subsequent reads from it will return its default value.
mutating func clearMeasures() {_uniqueStorage()._measures = nil}
var blocks: UInt32 {
get {return _storage._blocks ?? 0}
set {_uniqueStorage()._blocks = newValue}
}
/// Returns true if `blocks` has been explicitly set.
var hasBlocks: Bool {return _storage._blocks != nil}
/// Clears the value of `blocks`. Subsequent reads from it will return its default value.
mutating func clearBlocks() {_uniqueStorage()._blocks = nil}
var rewards: UInt32 {
get {return _storage._rewards ?? 0}
set {_uniqueStorage()._rewards = newValue}
}
/// Returns true if `rewards` has been explicitly set.
var hasRewards: Bool {return _storage._rewards != nil}
/// Clears the value of `rewards`. Subsequent reads from it will return its default value.
mutating func clearRewards() {_uniqueStorage()._rewards = nil}
var tokens: UInt32 {
get {return _storage._tokens ?? 0}
set {_uniqueStorage()._tokens = newValue}
}
/// Returns true if `tokens` has been explicitly set.
var hasTokens: Bool {return _storage._tokens != nil}
/// Clears the value of `tokens`. Subsequent reads from it will return its default value.
mutating func clearTokens() {_uniqueStorage()._tokens = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
struct VyvoWallet {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var totalMeasures: UInt32 {
get {return _totalMeasures ?? 0}
set {_totalMeasures = newValue}
}
/// Returns true if `totalMeasures` has been explicitly set.
var hasTotalMeasures: Bool {return self._totalMeasures != nil}
/// Clears the value of `totalMeasures`. Subsequent reads from it will return its default value.
mutating func clearTotalMeasures() {self._totalMeasures = nil}
var totalBlocks: UInt32 {
get {return _totalBlocks ?? 0}
set {_totalBlocks = newValue}
}
/// Returns true if `totalBlocks` has been explicitly set.
var hasTotalBlocks: Bool {return self._totalBlocks != nil}
/// Clears the value of `totalBlocks`. Subsequent reads from it will return its default value.
mutating func clearTotalBlocks() {self._totalBlocks = nil}
var totalRewards: UInt32 {
get {return _totalRewards ?? 0}
set {_totalRewards = newValue}
}
/// Returns true if `totalRewards` has been explicitly set.
var hasTotalRewards: Bool {return self._totalRewards != nil}
/// Clears the value of `totalRewards`. Subsequent reads from it will return its default value.
mutating func clearTotalRewards() {self._totalRewards = nil}
var totalTokens: UInt32 {
get {return _totalTokens ?? 0}
set {_totalTokens = newValue}
}
/// Returns true if `totalTokens` has been explicitly set.
var hasTotalTokens: Bool {return self._totalTokens != nil}
/// Clears the value of `totalTokens`. Subsequent reads from it will return its default value.
mutating func clearTotalTokens() {self._totalTokens = nil}
var dailyMeasure: [DailyMeasure] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _totalMeasures: UInt32? = nil
fileprivate var _totalBlocks: UInt32? = nil
fileprivate var _totalRewards: UInt32? = nil
fileprivate var _totalTokens: UInt32? = nil
}
struct SOSAlarm {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var ret: UInt32 {
get {return _ret ?? 0}
set {_ret = newValue}
}
/// Returns true if `ret` has been explicitly set.
var hasRet: Bool {return self._ret != nil}
/// Clears the value of `ret`. Subsequent reads from it will return its default value.
mutating func clearRet() {self._ret = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _ret: UInt32? = nil
}
struct HrAlarm {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var hr: UInt32 {
get {return _hr ?? 0}
set {_hr = newValue}
}
/// Returns true if `hr` has been explicitly set.
var hasHr: Bool {return self._hr != nil}
/// Clears the value of `hr`. Subsequent reads from it will return its default value.
mutating func clearHr() {self._hr = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _hr: UInt32? = nil
}
struct BreathAlarm {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var breath: UInt32 {
get {return _breath ?? 0}
set {_breath = newValue}
}
/// Returns true if `breath` has been explicitly set.
var hasBreath: Bool {return self._breath != nil}
/// Clears the value of `breath`. Subsequent reads from it will return its default value.
mutating func clearBreath() {self._breath = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _breath: UInt32? = nil
}
struct BpAlarm {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var sbp: UInt32 {
get {return _sbp ?? 0}
set {_sbp = newValue}
}
/// Returns true if `sbp` has been explicitly set.
var hasSbp: Bool {return self._sbp != nil}
/// Clears the value of `sbp`. Subsequent reads from it will return its default value.
mutating func clearSbp() {self._sbp = nil}
var dbp: UInt32 {
get {return _dbp ?? 0}
set {_dbp = newValue}
}
/// Returns true if `dbp` has been explicitly set.
var hasDbp: Bool {return self._dbp != nil}
/// Clears the value of `dbp`. Subsequent reads from it will return its default value.
mutating func clearDbp() {self._dbp = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _sbp: UInt32? = nil
fileprivate var _dbp: UInt32? = nil
}
struct Spo2Alarm {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var spo2: UInt32 {
get {return _spo2 ?? 0}
set {_spo2 = newValue}
}
/// Returns true if `spo2` has been explicitly set.
var hasSpo2: Bool {return self._spo2 != nil}
/// Clears the value of `spo2`. Subsequent reads from it will return its default value.
mutating func clearSpo2() {self._spo2 = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _spo2: UInt32? = nil
}
struct HealthAlarm {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var alarmSos: SOSAlarm {
get {return _storage._alarmSos ?? SOSAlarm()}
set {_uniqueStorage()._alarmSos = newValue}
}
/// Returns true if `alarmSos` has been explicitly set.
var hasAlarmSos: Bool {return _storage._alarmSos != nil}
/// Clears the value of `alarmSos`. Subsequent reads from it will return its default value.
mutating func clearAlarmSos() {_uniqueStorage()._alarmSos = nil}
var alarmHr: HrAlarm {
get {return _storage._alarmHr ?? HrAlarm()}
set {_uniqueStorage()._alarmHr = newValue}
}
/// Returns true if `alarmHr` has been explicitly set.
var hasAlarmHr: Bool {return _storage._alarmHr != nil}
/// Clears the value of `alarmHr`. Subsequent reads from it will return its default value.
mutating func clearAlarmHr() {_uniqueStorage()._alarmHr = nil}
var alarmBreath: BreathAlarm {
get {return _storage._alarmBreath ?? BreathAlarm()}
set {_uniqueStorage()._alarmBreath = newValue}
}
/// Returns true if `alarmBreath` has been explicitly set.
var hasAlarmBreath: Bool {return _storage._alarmBreath != nil}
/// Clears the value of `alarmBreath`. Subsequent reads from it will return its default value.
mutating func clearAlarmBreath() {_uniqueStorage()._alarmBreath = nil}
var alarmBp: BpAlarm {
get {return _storage._alarmBp ?? BpAlarm()}
set {_uniqueStorage()._alarmBp = newValue}
}
/// Returns true if `alarmBp` has been explicitly set.
var hasAlarmBp: Bool {return _storage._alarmBp != nil}
/// Clears the value of `alarmBp`. Subsequent reads from it will return its default value.
mutating func clearAlarmBp() {_uniqueStorage()._alarmBp = nil}
var alarmSpo2: Spo2Alarm {
get {return _storage._alarmSpo2 ?? Spo2Alarm()}
set {_uniqueStorage()._alarmSpo2 = newValue}
}
/// Returns true if `alarmSpo2` has been explicitly set.
var hasAlarmSpo2: Bool {return _storage._alarmSpo2 != nil}
/// Clears the value of `alarmSpo2`. Subsequent reads from it will return its default value.
mutating func clearAlarmSpo2() {_uniqueStorage()._alarmSpo2 = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
struct HeartrateAlarmConf {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var hrHigh: UInt32 {
get {return _hrHigh ?? 0}
set {_hrHigh = newValue}
}
/// Returns true if `hrHigh` has been explicitly set.
var hasHrHigh: Bool {return self._hrHigh != nil}
/// Clears the value of `hrHigh`. Subsequent reads from it will return its default value.
mutating func clearHrHigh() {self._hrHigh = nil}
var hrBelow: UInt32 {
get {return _hrBelow ?? 0}
set {_hrBelow = newValue}
}
/// Returns true if `hrBelow` has been explicitly set.
var hasHrBelow: Bool {return self._hrBelow != nil}
/// Clears the value of `hrBelow`. Subsequent reads from it will return its default value.
mutating func clearHrBelow() {self._hrBelow = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _hrHigh: UInt32? = nil
fileprivate var _hrBelow: UInt32? = nil
}
struct BreathAlarmConf {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var breathHigh: UInt32 {
get {return _breathHigh ?? 0}
set {_breathHigh = newValue}
}
/// Returns true if `breathHigh` has been explicitly set.
var hasBreathHigh: Bool {return self._breathHigh != nil}
/// Clears the value of `breathHigh`. Subsequent reads from it will return its default value.
mutating func clearBreathHigh() {self._breathHigh = nil}
var breathBelow: UInt32 {
get {return _breathBelow ?? 0}
set {_breathBelow = newValue}
}
/// Returns true if `breathBelow` has been explicitly set.
var hasBreathBelow: Bool {return self._breathBelow != nil}
/// Clears the value of `breathBelow`. Subsequent reads from it will return its default value.
mutating func clearBreathBelow() {self._breathBelow = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _breathHigh: UInt32? = nil
fileprivate var _breathBelow: UInt32? = nil
}
struct BpAlarmConf {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var sbpHigh: UInt32 {
get {return _sbpHigh ?? 0}
set {_sbpHigh = newValue}
}
/// Returns true if `sbpHigh` has been explicitly set.
var hasSbpHigh: Bool {return self._sbpHigh != nil}
/// Clears the value of `sbpHigh`. Subsequent reads from it will return its default value.
mutating func clearSbpHigh() {self._sbpHigh = nil}
var sbpBelow: UInt32 {
get {return _sbpBelow ?? 0}
set {_sbpBelow = newValue}
}
/// Returns true if `sbpBelow` has been explicitly set.
var hasSbpBelow: Bool {return self._sbpBelow != nil}
/// Clears the value of `sbpBelow`. Subsequent reads from it will return its default value.
mutating func clearSbpBelow() {self._sbpBelow = nil}
var dbpHigh: UInt32 {
get {return _dbpHigh ?? 0}
set {_dbpHigh = newValue}
}
/// Returns true if `dbpHigh` has been explicitly set.
var hasDbpHigh: Bool {return self._dbpHigh != nil}
/// Clears the value of `dbpHigh`. Subsequent reads from it will return its default value.
mutating func clearDbpHigh() {self._dbpHigh = nil}
var dbpBelow: UInt32 {
get {return _dbpBelow ?? 0}
set {_dbpBelow = newValue}
}
/// Returns true if `dbpBelow` has been explicitly set.
var hasDbpBelow: Bool {return self._dbpBelow != nil}
/// Clears the value of `dbpBelow`. Subsequent reads from it will return its default value.
mutating func clearDbpBelow() {self._dbpBelow = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _sbpHigh: UInt32? = nil
fileprivate var _sbpBelow: UInt32? = nil
fileprivate var _dbpHigh: UInt32? = nil
fileprivate var _dbpBelow: UInt32? = nil
}
struct Spo2AlarmConf {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var spo2Below: UInt32 {
get {return _spo2Below ?? 0}
set {_spo2Below = newValue}
}
/// Returns true if `spo2Below` has been explicitly set.
var hasSpo2Below: Bool {return self._spo2Below != nil}
/// Clears the value of `spo2Below`. Subsequent reads from it will return its default value.
mutating func clearSpo2Below() {self._spo2Below = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _spo2Below: UInt32? = nil
}
struct HealthAlarmConf {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var confHr: HeartrateAlarmConf {
get {return _storage._confHr ?? HeartrateAlarmConf()}
set {_uniqueStorage()._confHr = newValue}
}
/// Returns true if `confHr` has been explicitly set.
var hasConfHr: Bool {return _storage._confHr != nil}
/// Clears the value of `confHr`. Subsequent reads from it will return its default value.
mutating func clearConfHr() {_uniqueStorage()._confHr = nil}
var confBreath: BreathAlarmConf {
get {return _storage._confBreath ?? BreathAlarmConf()}
set {_uniqueStorage()._confBreath = newValue}
}
/// Returns true if `confBreath` has been explicitly set.
var hasConfBreath: Bool {return _storage._confBreath != nil}
/// Clears the value of `confBreath`. Subsequent reads from it will return its default value.
mutating func clearConfBreath() {_uniqueStorage()._confBreath = nil}
var confBp: BpAlarmConf {
get {return _storage._confBp ?? BpAlarmConf()}
set {_uniqueStorage()._confBp = newValue}
}
/// Returns true if `confBp` has been explicitly set.
var hasConfBp: Bool {return _storage._confBp != nil}
/// Clears the value of `confBp`. Subsequent reads from it will return its default value.
mutating func clearConfBp() {_uniqueStorage()._confBp = nil}
var confSpo2: Spo2AlarmConf {
get {return _storage._confSpo2 ?? Spo2AlarmConf()}
set {_uniqueStorage()._confSpo2 = newValue}
}
/// Returns true if `confSpo2` has been explicitly set.
var hasConfSpo2: Bool {return _storage._confSpo2 != nil}
/// Clears the value of `confSpo2`. Subsequent reads from it will return its default value.
mutating func clearConfSpo2() {_uniqueStorage()._confSpo2 = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
struct C110Data {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var bodyData: C110BodyData {
get {return _storage._bodyData ?? C110BodyData()}
set {_uniqueStorage()._bodyData = newValue}
}
/// Returns true if `bodyData` has been explicitly set.
var hasBodyData: Bool {return _storage._bodyData != nil}
/// Clears the value of `bodyData`. Subsequent reads from it will return its default value.
mutating func clearBodyData() {_uniqueStorage()._bodyData = nil}
var aqiValue: C110AQI {
get {return _storage._aqiValue ?? .good}
set {_uniqueStorage()._aqiValue = newValue}
}
/// Returns true if `aqiValue` has been explicitly set.
var hasAqiValue: Bool {return _storage._aqiValue != nil}
/// Clears the value of `aqiValue`. Subsequent reads from it will return its default value.
mutating func clearAqiValue() {_uniqueStorage()._aqiValue = nil}
var symptoms: [C110EcgSymptom] {
get {return _storage._symptoms}
set {_uniqueStorage()._symptoms = newValue}
}
var lifeQuality: LifeQualityData {
get {return _storage._lifeQuality ?? LifeQualityData()}
set {_uniqueStorage()._lifeQuality = newValue}
}
/// Returns true if `lifeQuality` has been explicitly set.
var hasLifeQuality: Bool {return _storage._lifeQuality != nil}
/// Clears the value of `lifeQuality`. Subsequent reads from it will return its default value.
mutating func clearLifeQuality() {_uniqueStorage()._lifeQuality = nil}
var wallet: VyvoWallet {
get {return _storage._wallet ?? VyvoWallet()}
set {_uniqueStorage()._wallet = newValue}
}
/// Returns true if `wallet` has been explicitly set.
var hasWallet: Bool {return _storage._wallet != nil}
/// Clears the value of `wallet`. Subsequent reads from it will return its default value.
mutating func clearWallet() {_uniqueStorage()._wallet = nil}
var conf: HealthAlarmConf {
get {return _storage._conf ?? HealthAlarmConf()}
set {_uniqueStorage()._conf = newValue}
}
/// Returns true if `conf` has been explicitly set.
var hasConf: Bool {return _storage._conf != nil}
/// Clears the value of `conf`. Subsequent reads from it will return its default value.
mutating func clearConf() {_uniqueStorage()._conf = nil}
var sosRet: Bool {
get {return _storage._sosRet ?? false}
set {_uniqueStorage()._sosRet = newValue}
}
/// Returns true if `sosRet` has been explicitly set.
var hasSosRet: Bool {return _storage._sosRet != nil}
/// Clears the value of `sosRet`. Subsequent reads from it will return its default value.
mutating func clearSosRet() {_uniqueStorage()._sosRet = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
struct C110Command {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var operation: C110Operation {
get {return _storage._operation ?? .read}
set {_uniqueStorage()._operation = newValue}
}
/// Returns true if `operation` has been explicitly set.
var hasOperation: Bool {return _storage._operation != nil}
/// Clears the value of `operation`. Subsequent reads from it will return its default value.
mutating func clearOperation() {_uniqueStorage()._operation = nil}
var data: C110Data {
get {return _storage._data ?? C110Data()}
set {_uniqueStorage()._data = newValue}
}
/// Returns true if `data` has been explicitly set.
var hasData: Bool {return _storage._data != nil}
/// Clears the value of `data`. Subsequent reads from it will return its default value.
mutating func clearData() {_uniqueStorage()._data = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
struct C110Response {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var operation: C110Operation {
get {return _storage._operation ?? .read}
set {_uniqueStorage()._operation = newValue}
}
/// Returns true if `operation` has been explicitly set.
var hasOperation: Bool {return _storage._operation != nil}
/// Clears the value of `operation`. Subsequent reads from it will return its default value.
mutating func clearOperation() {_uniqueStorage()._operation = nil}
var params: OneOf_Params? {
get {return _storage._params}
set {_uniqueStorage()._params = newValue}
}
var ret: Bool {
get {
if case .ret(let v)? = _storage._params {return v}
return false
}
set {_uniqueStorage()._params = .ret(newValue)}
}
var data: C110Data {
get {
if case .data(let v)? = _storage._params {return v}
return C110Data()
}
set {_uniqueStorage()._params = .data(newValue)}
}
var alarm: HealthAlarm {
get {
if case .alarm(let v)? = _storage._params {return v}
return HealthAlarm()
}
set {_uniqueStorage()._params = .alarm(newValue)}
}
var unknownFields = SwiftProtobuf.UnknownStorage()
enum OneOf_Params: Equatable {
case ret(Bool)
case data(C110Data)
case alarm(HealthAlarm)
#if !swift(>=4.1)
static func ==(lhs: C110Response.OneOf_Params, rhs: C110Response.OneOf_Params) -> Bool {
switch (lhs, rhs) {
case (.ret(let l), .ret(let r)): return l == r
case (.data(let l), .data(let r)): return l == r
case (.alarm(let l), .alarm(let r)): return l == r
default: return false
}
}
#endif
}
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
extension C110Operation: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "READ"),
1: .same(proto: "WRITE"),
]
}
extension C110AQI: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "GOOD"),
1: .same(proto: "NORMAL"),
2: .same(proto: "BAD"),
3: .same(proto: "WORST"),
]
}
extension C110EcgSymptom: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "Sinus_rhythm"),
1: .same(proto: "Sinus_arhythmia"),
2: .same(proto: "Sinus_tachycardia"),
3: .same(proto: "Sinus_bradycardia"),
4: .same(proto: "Atrial_fibrillation"),
5: .same(proto: "Atrial_flutter"),
6: .same(proto: "Atrial_premature_beats"),
7: .same(proto: "Ventricular_premature_beats"),
8: .same(proto: "Left_ventricular_hypertrophy"),
9: .same(proto: "Right_bundle_branch_block"),
10: .same(proto: "Left_bundle_branch_block"),
]
}
extension C110BodyData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "C110BodyData"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "BMI"),
2: .same(proto: "BMR"),
3: .same(proto: "BodyFat"),
4: .same(proto: "VisceralFatLevel"),
5: .same(proto: "MuscleMass"),
6: .same(proto: "BoneMass"),
7: .same(proto: "Weight"),
]
public var isInitialized: Bool {
if self._bmi == nil {return false}
if self._bmr == nil {return false}
if self._bodyFat == nil {return false}
if self._visceralFatLevel == nil {return false}
if self._muscleMass == nil {return false}
if self._boneMass == nil {return false}
if self._weight == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFloatField(value: &self._bmi)
case 2: try decoder.decodeSingularFloatField(value: &self._bmr)
case 3: try decoder.decodeSingularFloatField(value: &self._bodyFat)
case 4: try decoder.decodeSingularFloatField(value: &self._visceralFatLevel)
case 5: try decoder.decodeSingularFloatField(value: &self._muscleMass)
case 6: try decoder.decodeSingularFloatField(value: &self._boneMass)
case 7: try decoder.decodeSingularFloatField(value: &self._weight)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._bmi {
try visitor.visitSingularFloatField(value: v, fieldNumber: 1)
}
if let v = self._bmr {
try visitor.visitSingularFloatField(value: v, fieldNumber: 2)
}
if let v = self._bodyFat {
try visitor.visitSingularFloatField(value: v, fieldNumber: 3)
}
if let v = self._visceralFatLevel {
try visitor.visitSingularFloatField(value: v, fieldNumber: 4)
}
if let v = self._muscleMass {
try visitor.visitSingularFloatField(value: v, fieldNumber: 5)
}
if let v = self._boneMass {
try visitor.visitSingularFloatField(value: v, fieldNumber: 6)
}
if let v = self._weight {
try visitor.visitSingularFloatField(value: v, fieldNumber: 7)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: C110BodyData, rhs: C110BodyData) -> Bool {
if lhs._bmi != rhs._bmi {return false}
if lhs._bmr != rhs._bmr {return false}
if lhs._bodyFat != rhs._bodyFat {return false}
if lhs._visceralFatLevel != rhs._visceralFatLevel {return false}
if lhs._muscleMass != rhs._muscleMass {return false}
if lhs._boneMass != rhs._boneMass {return false}
if lhs._weight != rhs._weight {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension LifeQualityData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "LifeQualityData"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "wellNessValue"),
2: .same(proto: "activityValue"),
3: .same(proto: "moodSwingsValue"),
4: .same(proto: "lifestyleIndexValue"),
5: .same(proto: "time"),
]
fileprivate class _StorageClass {
var _wellNessValue: UInt32? = nil
var _activityValue: UInt32? = nil
var _moodSwingsValue: UInt32? = nil
var _lifestyleIndexValue: UInt32? = nil
var _time: RtTime? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_wellNessValue = source._wellNessValue
_activityValue = source._activityValue
_moodSwingsValue = source._moodSwingsValue
_lifestyleIndexValue = source._lifestyleIndexValue
_time = source._time
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
return withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._time, !v.isInitialized {return false}
return true
}
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &_storage._wellNessValue)
case 2: try decoder.decodeSingularFixed32Field(value: &_storage._activityValue)
case 3: try decoder.decodeSingularFixed32Field(value: &_storage._moodSwingsValue)
case 4: try decoder.decodeSingularFixed32Field(value: &_storage._lifestyleIndexValue)
case 5: try decoder.decodeSingularMessageField(value: &_storage._time)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._wellNessValue {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
if let v = _storage._activityValue {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 2)
}
if let v = _storage._moodSwingsValue {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 3)
}
if let v = _storage._lifestyleIndexValue {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 4)
}
if let v = _storage._time {
try visitor.visitSingularMessageField(value: v, fieldNumber: 5)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: LifeQualityData, rhs: LifeQualityData) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._wellNessValue != rhs_storage._wellNessValue {return false}
if _storage._activityValue != rhs_storage._activityValue {return false}
if _storage._moodSwingsValue != rhs_storage._moodSwingsValue {return false}
if _storage._lifestyleIndexValue != rhs_storage._lifestyleIndexValue {return false}
if _storage._time != rhs_storage._time {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension DailyMeasure: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "DailyMeasure"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "time_stamp"),
2: .same(proto: "measures"),
3: .same(proto: "blocks"),
4: .same(proto: "rewards"),
5: .same(proto: "tokens"),
]
fileprivate class _StorageClass {
var _timeStamp: DateTime? = nil
var _measures: UInt32? = nil
var _blocks: UInt32? = nil
var _rewards: UInt32? = nil
var _tokens: UInt32? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_timeStamp = source._timeStamp
_measures = source._measures
_blocks = source._blocks
_rewards = source._rewards
_tokens = source._tokens
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
return withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if _storage._timeStamp == nil {return false}
if _storage._measures == nil {return false}
if _storage._blocks == nil {return false}
if _storage._rewards == nil {return false}
if _storage._tokens == nil {return false}
if let v = _storage._timeStamp, !v.isInitialized {return false}
return true
}
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &_storage._timeStamp)
case 2: try decoder.decodeSingularFixed32Field(value: &_storage._measures)
case 3: try decoder.decodeSingularFixed32Field(value: &_storage._blocks)
case 4: try decoder.decodeSingularFixed32Field(value: &_storage._rewards)
case 5: try decoder.decodeSingularFixed32Field(value: &_storage._tokens)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._timeStamp {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if let v = _storage._measures {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 2)
}
if let v = _storage._blocks {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 3)
}
if let v = _storage._rewards {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 4)
}
if let v = _storage._tokens {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 5)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: DailyMeasure, rhs: DailyMeasure) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._timeStamp != rhs_storage._timeStamp {return false}
if _storage._measures != rhs_storage._measures {return false}
if _storage._blocks != rhs_storage._blocks {return false}
if _storage._rewards != rhs_storage._rewards {return false}
if _storage._tokens != rhs_storage._tokens {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension VyvoWallet: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "VyvoWallet"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "total_measures"),
2: .standard(proto: "total_blocks"),
3: .standard(proto: "total_rewards"),
4: .standard(proto: "total_tokens"),
5: .standard(proto: "daily_measure"),
]
public var isInitialized: Bool {
if !SwiftProtobuf.Internal.areAllInitialized(self.dailyMeasure) {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &self._totalMeasures)
case 2: try decoder.decodeSingularFixed32Field(value: &self._totalBlocks)
case 3: try decoder.decodeSingularFixed32Field(value: &self._totalRewards)
case 4: try decoder.decodeSingularFixed32Field(value: &self._totalTokens)
case 5: try decoder.decodeRepeatedMessageField(value: &self.dailyMeasure)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._totalMeasures {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
if let v = self._totalBlocks {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 2)
}
if let v = self._totalRewards {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 3)
}
if let v = self._totalTokens {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 4)
}
if !self.dailyMeasure.isEmpty {
try visitor.visitRepeatedMessageField(value: self.dailyMeasure, fieldNumber: 5)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: VyvoWallet, rhs: VyvoWallet) -> Bool {
if lhs._totalMeasures != rhs._totalMeasures {return false}
if lhs._totalBlocks != rhs._totalBlocks {return false}
if lhs._totalRewards != rhs._totalRewards {return false}
if lhs._totalTokens != rhs._totalTokens {return false}
if lhs.dailyMeasure != rhs.dailyMeasure {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension SOSAlarm: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "SOSAlarm"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ret"),
]
public var isInitialized: Bool {
if self._ret == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &self._ret)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._ret {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: SOSAlarm, rhs: SOSAlarm) -> Bool {
if lhs._ret != rhs._ret {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension HrAlarm: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "HrAlarm"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "hr"),
]
public var isInitialized: Bool {
if self._hr == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &self._hr)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._hr {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: HrAlarm, rhs: HrAlarm) -> Bool {
if lhs._hr != rhs._hr {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension BreathAlarm: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "BreathAlarm"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "breath"),
]
public var isInitialized: Bool {
if self._breath == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &self._breath)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._breath {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: BreathAlarm, rhs: BreathAlarm) -> Bool {
if lhs._breath != rhs._breath {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension BpAlarm: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "BpAlarm"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "sbp"),
2: .same(proto: "dbp"),
]
public var isInitialized: Bool {
if self._sbp == nil {return false}
if self._dbp == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &self._sbp)
case 2: try decoder.decodeSingularFixed32Field(value: &self._dbp)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._sbp {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
if let v = self._dbp {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: BpAlarm, rhs: BpAlarm) -> Bool {
if lhs._sbp != rhs._sbp {return false}
if lhs._dbp != rhs._dbp {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Spo2Alarm: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "Spo2Alarm"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "spo2"),
]
public var isInitialized: Bool {
if self._spo2 == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &self._spo2)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._spo2 {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Spo2Alarm, rhs: Spo2Alarm) -> Bool {
if lhs._spo2 != rhs._spo2 {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension HealthAlarm: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "HealthAlarm"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "alarm_sos"),
2: .standard(proto: "alarm_hr"),
3: .standard(proto: "alarm_breath"),
4: .standard(proto: "alarm_bp"),
5: .standard(proto: "alarm_spo2"),
]
fileprivate class _StorageClass {
var _alarmSos: SOSAlarm? = nil
var _alarmHr: HrAlarm? = nil
var _alarmBreath: BreathAlarm? = nil
var _alarmBp: BpAlarm? = nil
var _alarmSpo2: Spo2Alarm? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_alarmSos = source._alarmSos
_alarmHr = source._alarmHr
_alarmBreath = source._alarmBreath
_alarmBp = source._alarmBp
_alarmSpo2 = source._alarmSpo2
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
return withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._alarmSos, !v.isInitialized {return false}
if let v = _storage._alarmHr, !v.isInitialized {return false}
if let v = _storage._alarmBreath, !v.isInitialized {return false}
if let v = _storage._alarmBp, !v.isInitialized {return false}
if let v = _storage._alarmSpo2, !v.isInitialized {return false}
return true
}
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &_storage._alarmSos)
case 2: try decoder.decodeSingularMessageField(value: &_storage._alarmHr)
case 3: try decoder.decodeSingularMessageField(value: &_storage._alarmBreath)
case 4: try decoder.decodeSingularMessageField(value: &_storage._alarmBp)
case 5: try decoder.decodeSingularMessageField(value: &_storage._alarmSpo2)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._alarmSos {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if let v = _storage._alarmHr {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
}
if let v = _storage._alarmBreath {
try visitor.visitSingularMessageField(value: v, fieldNumber: 3)
}
if let v = _storage._alarmBp {
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
}
if let v = _storage._alarmSpo2 {
try visitor.visitSingularMessageField(value: v, fieldNumber: 5)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: HealthAlarm, rhs: HealthAlarm) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._alarmSos != rhs_storage._alarmSos {return false}
if _storage._alarmHr != rhs_storage._alarmHr {return false}
if _storage._alarmBreath != rhs_storage._alarmBreath {return false}
if _storage._alarmBp != rhs_storage._alarmBp {return false}
if _storage._alarmSpo2 != rhs_storage._alarmSpo2 {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension HeartrateAlarmConf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "HeartrateAlarmConf"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "hr_high"),
2: .standard(proto: "hr_below"),
]
public var isInitialized: Bool {
if self._hrHigh == nil {return false}
if self._hrBelow == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &self._hrHigh)
case 2: try decoder.decodeSingularFixed32Field(value: &self._hrBelow)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._hrHigh {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
if let v = self._hrBelow {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: HeartrateAlarmConf, rhs: HeartrateAlarmConf) -> Bool {
if lhs._hrHigh != rhs._hrHigh {return false}
if lhs._hrBelow != rhs._hrBelow {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension BreathAlarmConf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "BreathAlarmConf"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "breath_high"),
2: .standard(proto: "breath_below"),
]
public var isInitialized: Bool {
if self._breathHigh == nil {return false}
if self._breathBelow == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &self._breathHigh)
case 2: try decoder.decodeSingularFixed32Field(value: &self._breathBelow)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._breathHigh {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
if let v = self._breathBelow {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: BreathAlarmConf, rhs: BreathAlarmConf) -> Bool {
if lhs._breathHigh != rhs._breathHigh {return false}
if lhs._breathBelow != rhs._breathBelow {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension BpAlarmConf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "BpAlarmConf"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "sbp_high"),
2: .standard(proto: "sbp_below"),
3: .standard(proto: "dbp_high"),
4: .standard(proto: "dbp_below"),
]
public var isInitialized: Bool {
if self._sbpHigh == nil {return false}
if self._sbpBelow == nil {return false}
if self._dbpHigh == nil {return false}
if self._dbpBelow == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &self._sbpHigh)
case 2: try decoder.decodeSingularFixed32Field(value: &self._sbpBelow)
case 3: try decoder.decodeSingularFixed32Field(value: &self._dbpHigh)
case 4: try decoder.decodeSingularFixed32Field(value: &self._dbpBelow)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._sbpHigh {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
if let v = self._sbpBelow {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 2)
}
if let v = self._dbpHigh {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 3)
}
if let v = self._dbpBelow {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: BpAlarmConf, rhs: BpAlarmConf) -> Bool {
if lhs._sbpHigh != rhs._sbpHigh {return false}
if lhs._sbpBelow != rhs._sbpBelow {return false}
if lhs._dbpHigh != rhs._dbpHigh {return false}
if lhs._dbpBelow != rhs._dbpBelow {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Spo2AlarmConf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "Spo2AlarmConf"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "spo2_below"),
]
public var isInitialized: Bool {
if self._spo2Below == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularFixed32Field(value: &self._spo2Below)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._spo2Below {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Spo2AlarmConf, rhs: Spo2AlarmConf) -> Bool {
if lhs._spo2Below != rhs._spo2Below {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension HealthAlarmConf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "HealthAlarmConf"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "conf_hr"),
2: .standard(proto: "conf_breath"),
3: .standard(proto: "conf_bp"),
4: .standard(proto: "conf_spo2"),
]
fileprivate class _StorageClass {
var _confHr: HeartrateAlarmConf? = nil
var _confBreath: BreathAlarmConf? = nil
var _confBp: BpAlarmConf? = nil
var _confSpo2: Spo2AlarmConf? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_confHr = source._confHr
_confBreath = source._confBreath
_confBp = source._confBp
_confSpo2 = source._confSpo2
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
return withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._confHr, !v.isInitialized {return false}
if let v = _storage._confBreath, !v.isInitialized {return false}
if let v = _storage._confBp, !v.isInitialized {return false}
if let v = _storage._confSpo2, !v.isInitialized {return false}
return true
}
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &_storage._confHr)
case 2: try decoder.decodeSingularMessageField(value: &_storage._confBreath)
case 3: try decoder.decodeSingularMessageField(value: &_storage._confBp)
case 4: try decoder.decodeSingularMessageField(value: &_storage._confSpo2)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._confHr {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if let v = _storage._confBreath {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
}
if let v = _storage._confBp {
try visitor.visitSingularMessageField(value: v, fieldNumber: 3)
}
if let v = _storage._confSpo2 {
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: HealthAlarmConf, rhs: HealthAlarmConf) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._confHr != rhs_storage._confHr {return false}
if _storage._confBreath != rhs_storage._confBreath {return false}
if _storage._confBp != rhs_storage._confBp {return false}
if _storage._confSpo2 != rhs_storage._confSpo2 {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension C110Data: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "C110Data"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "body_data"),
2: .standard(proto: "aqi_value"),
3: .same(proto: "symptoms"),
4: .same(proto: "lifeQuality"),
5: .same(proto: "wallet"),
6: .same(proto: "conf"),
7: .standard(proto: "sos_ret"),
]
fileprivate class _StorageClass {
var _bodyData: C110BodyData? = nil
var _aqiValue: C110AQI? = nil
var _symptoms: [C110EcgSymptom] = []
var _lifeQuality: LifeQualityData? = nil
var _wallet: VyvoWallet? = nil
var _conf: HealthAlarmConf? = nil
var _sosRet: Bool? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_bodyData = source._bodyData
_aqiValue = source._aqiValue
_symptoms = source._symptoms
_lifeQuality = source._lifeQuality
_wallet = source._wallet
_conf = source._conf
_sosRet = source._sosRet
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
return withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._bodyData, !v.isInitialized {return false}
if let v = _storage._lifeQuality, !v.isInitialized {return false}
if let v = _storage._wallet, !v.isInitialized {return false}
if let v = _storage._conf, !v.isInitialized {return false}
return true
}
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &_storage._bodyData)
case 2: try decoder.decodeSingularEnumField(value: &_storage._aqiValue)
case 3: try decoder.decodeRepeatedEnumField(value: &_storage._symptoms)
case 4: try decoder.decodeSingularMessageField(value: &_storage._lifeQuality)
case 5: try decoder.decodeSingularMessageField(value: &_storage._wallet)
case 6: try decoder.decodeSingularMessageField(value: &_storage._conf)
case 7: try decoder.decodeSingularBoolField(value: &_storage._sosRet)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._bodyData {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if let v = _storage._aqiValue {
try visitor.visitSingularEnumField(value: v, fieldNumber: 2)
}
if !_storage._symptoms.isEmpty {
try visitor.visitRepeatedEnumField(value: _storage._symptoms, fieldNumber: 3)
}
if let v = _storage._lifeQuality {
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
}
if let v = _storage._wallet {
try visitor.visitSingularMessageField(value: v, fieldNumber: 5)
}
if let v = _storage._conf {
try visitor.visitSingularMessageField(value: v, fieldNumber: 6)
}
if let v = _storage._sosRet {
try visitor.visitSingularBoolField(value: v, fieldNumber: 7)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: C110Data, rhs: C110Data) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._bodyData != rhs_storage._bodyData {return false}
if _storage._aqiValue != rhs_storage._aqiValue {return false}
if _storage._symptoms != rhs_storage._symptoms {return false}
if _storage._lifeQuality != rhs_storage._lifeQuality {return false}
if _storage._wallet != rhs_storage._wallet {return false}
if _storage._conf != rhs_storage._conf {return false}
if _storage._sosRet != rhs_storage._sosRet {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension C110Command: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "C110Command"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "operation"),
2: .same(proto: "data"),
]
fileprivate class _StorageClass {
var _operation: C110Operation? = nil
var _data: C110Data? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_operation = source._operation
_data = source._data
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
return withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if _storage._operation == nil {return false}
if let v = _storage._data, !v.isInitialized {return false}
return true
}
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularEnumField(value: &_storage._operation)
case 2: try decoder.decodeSingularMessageField(value: &_storage._data)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._operation {
try visitor.visitSingularEnumField(value: v, fieldNumber: 1)
}
if let v = _storage._data {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: C110Command, rhs: C110Command) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._operation != rhs_storage._operation {return false}
if _storage._data != rhs_storage._data {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension C110Response: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "C110Response"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "operation"),
2: .same(proto: "ret"),
3: .same(proto: "data"),
4: .same(proto: "alarm"),
]
fileprivate class _StorageClass {
var _operation: C110Operation? = nil
var _params: C110Response.OneOf_Params?
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_operation = source._operation
_params = source._params
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
return withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if _storage._operation == nil {return false}
switch _storage._params {
case .data(let v)?: if !v.isInitialized {return false}
case .alarm(let v)?: if !v.isInitialized {return false}
default: break
}
return true
}
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularEnumField(value: &_storage._operation)
case 2:
if _storage._params != nil {try decoder.handleConflictingOneOf()}
var v: Bool?
try decoder.decodeSingularBoolField(value: &v)
if let v = v {_storage._params = .ret(v)}
case 3:
var v: C110Data?
if let current = _storage._params {
try decoder.handleConflictingOneOf()
if case .data(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {_storage._params = .data(v)}
case 4:
var v: HealthAlarm?
if let current = _storage._params {
try decoder.handleConflictingOneOf()
if case .alarm(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {_storage._params = .alarm(v)}
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._operation {
try visitor.visitSingularEnumField(value: v, fieldNumber: 1)
}
switch _storage._params {
case .ret(let v)?:
try visitor.visitSingularBoolField(value: v, fieldNumber: 2)
case .data(let v)?:
try visitor.visitSingularMessageField(value: v, fieldNumber: 3)
case .alarm(let v)?:
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
case nil: break
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: C110Response, rhs: C110Response) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._operation != rhs_storage._operation {return false}
if _storage._params != rhs_storage._params {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 35.435125 | 130 | 0.697041 |
4c16089614cee00e305f51cfeb1584c2a7a24a17 | 90 | php | PHP | tests/auth/GroupsModelTest.php | lonnieezell/simple-forums | 9fdf9deeec292ee23a9478d922a97381cc8dae02 | [
"MIT"
] | 37 | 2017-06-28T06:51:54.000Z | 2021-12-20T11:34:34.000Z | tests/auth/GroupsModelTest.php | lonnieezell/simple-forums | 9fdf9deeec292ee23a9478d922a97381cc8dae02 | [
"MIT"
] | null | null | null | tests/auth/GroupsModelTest.php | lonnieezell/simple-forums | 9fdf9deeec292ee23a9478d922a97381cc8dae02 | [
"MIT"
] | 7 | 2017-07-19T16:12:52.000Z | 2020-12-30T04:47:01.000Z | <?php
class GroupsModelTest extends CIDatabaseTestCase
{
protected $refresh = true;
}
| 10 | 48 | 0.755556 |
475d31969c7f91f5222e9ac27b43f561d8d502b3 | 5,935 | html | HTML | src/main/resources/templates/user/my_shipments.html | JuliaBorovets/DeliveryService | b4c7f035f02f63d1cdbfc83635e02c5c4540e637 | [
"Unlicense"
] | 2 | 2020-07-15T15:48:01.000Z | 2020-07-15T15:48:29.000Z | src/main/resources/templates/user/my_shipments.html | JuliaBorovets/FinalProject | b4c7f035f02f63d1cdbfc83635e02c5c4540e637 | [
"Unlicense"
] | 26 | 2020-06-08T09:41:59.000Z | 2021-03-31T22:14:31.000Z | src/main/resources/templates/user/my_shipments.html | JuliaBorovets/FinalProject | b4c7f035f02f63d1cdbfc83635e02c5c4540e637 | [
"Unlicense"
] | null | null | null | <!DOCTYPE HTML>
<!--suppress HtmlUnknownAttribute -->
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>My shipments</title>
<link rel="shortcut icon" href="../../static/images/favicon.ico">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<base href="/">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div th:include="fragments/header :: header_user_admin" th:remove="tag"></div>
<br>
<section class="jumbotron2 text-center">
<div class="container">
<div class="btn-group mr-2" role="group" aria-label="First group">
<a class="btn btn-outline-primary" th:href="@{/shipments/show/1/all}"> Show all </a>
<a class="btn btn-outline-primary" th:href="@{/shipments/show/1/not_paid}"> Show not paid </a>
<a class="btn btn-outline-primary" th:href="@{/shipments/show/1/delivered}"> Show delivered </a>
<a class="btn btn-outline-primary" th:href="@{/shipments/show/1/archived}"> Show archived </a>
</div>
</div>
</section>
<br>
<div>
<form th:object="${orderDto}" th:action="@{/shipments/find_order}" method="get">
<div class="jumbotron2 text-center">
<div class="container" id="dataTable_filter">
<label>
<input type="number" min="0" class="form-control form-control-sm" th:field="*{id}"
aria-controls="dataTable" placeholder="Search by id">
</label>
<button type="submit" class="btn btn-default" style="display: none;">Search</button>
</div>
<br>
<div th:if="${error}" style="color: red">
<h3>Order not found</h3>
</div>
</div>
</form>
<div class="container py-5" th:each="order : ${orders}">
<div class="row" >
<div class="col-lg-7 mx-auto">
<div class="bg-white rounded-lg shadow-sm p-5" >
<ul class="nav bg-light nav-pills rounded-pill nav-fill mb-3">
<li class="nav-item">
<b>
<h4 data-toggle="pill" th:text="${order.id}">Credit Card</h4>
</b>
</li>
</ul>
<div class="tab-content">
<div id="nav-tab-card" class="tab-pane fade show active">
<div class="form-group" >
<div th:text="#{order.status} + ' : ' + ${order.status}">{Order status}</div>
</div>
<div class="form-group" >
<div th:text="#{order.type} + ' : ' + ${order.orderType.name}">{Order name}</div>
</div>
<div class="form-group" >
<div th:text="#{order.weight} + ' : ' + ${order.weight}">{Order weight}</div>
</div>
<div class="form-group" >
<div th:text="#{order.destination} + ' : ' + ${order.destination.cityFrom} + ' - ' + ${order.destination.cityTo}">
{Order destination}</div>
</div>
<div class="form-group" >
<div th:text="#{order.shipping.date} + ' : ' + ${order.shippingDate}">{Order
shippingDate}</div>
</div>
<div class="form-group" >
<div th:unless="${order.deliveryDate} == null" th:text="#{order.delivery.date} + ' : ' + ${order.deliveryDate}">{Order
deliveryDate}</div>
</div>
<div class="form-group" >
<div th:text="#{order.shipment.price} + ' : ' + ${order.shippingPriceInCents} + #{enter}">
{Order shippingPrice}</div>
</div>
<div class="form-group text-center" >
<a class="button" th:if="${order.check} == null"
th:href="@{/bank/pay/{id}(id=${order.id})}" th:text="#{to.pay}" th:size="14px">
</a>
</div>
<div class="form-group text-center" >
<a class="button" th:if="${order.check} != null"
th:href="@{/bank/show_check/{orderId}(orderId=${order.check.id})}" th:size="14px"> Show check
</a>
</div>
<div class="form-group text-center" >
<a class="button" th:if="${order.status.name() == 'RECEIVED'}"
th:href="@{/shipments/archive_order/{orderId}(orderId=${order.id})}" th:size="14px"> Archive
</a>
</div>
<div class="form-group text-center" >
<a class="button" th:if="${order.status.name() == 'NOT_PAID'}"
th:href="@{/shipments/delete/{orderId}(orderId=${order.id})}" th:size="14px"> Delete
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
</div>
</div>
<div th:include="fragments/footer :: footer" th:remove="tag"></div>
</body>
</html> | 41.503497 | 152 | 0.427633 |
0e613cd37ccce39aefc9f971457587134deee72f | 6,183 | asm | Assembly | Transynther/x86/_processed/NONE/_zr_/i9-9900K_12_0xa0.log_21829_250.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/NONE/_zr_/i9-9900K_12_0xa0.log_21829_250.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/NONE/_zr_/i9-9900K_12_0xa0.log_21829_250.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r15
push %r8
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0xda16, %rsi
lea addresses_UC_ht+0x1911a, %rdi
add $25119, %r10
mov $92, %rcx
rep movsb
add $28325, %r8
lea addresses_WC_ht+0x19a9a, %r15
nop
dec %rax
mov $0x6162636465666768, %rsi
movq %rsi, (%r15)
nop
sub %rax, %rax
lea addresses_WT_ht+0x15d6, %rsi
lea addresses_normal_ht+0x1a0da, %rdi
nop
nop
and $21041, %rbp
mov $111, %rcx
rep movsb
nop
nop
nop
nop
inc %r10
lea addresses_WT_ht+0x1009a, %rsi
lea addresses_D_ht+0x18f9a, %rdi
nop
nop
nop
lfence
mov $83, %rcx
rep movsq
nop
nop
nop
dec %r8
lea addresses_WC_ht+0x9b9a, %rax
nop
nop
nop
nop
inc %r15
mov $0x6162636465666768, %rdi
movq %rdi, (%rax)
nop
nop
nop
nop
nop
xor $31879, %rdi
lea addresses_WC_ht+0x787e, %r10
nop
nop
nop
nop
sub %rax, %rax
movb $0x61, (%r10)
nop
nop
nop
nop
nop
and %r10, %r10
lea addresses_A_ht+0x999a, %rsi
nop
and %r10, %r10
mov $0x6162636465666768, %rdi
movq %rdi, %xmm5
and $0xffffffffffffffc0, %rsi
vmovaps %ymm5, (%rsi)
nop
nop
nop
nop
inc %rdi
lea addresses_UC_ht+0x12642, %rbp
cmp %r8, %r8
movw $0x6162, (%rbp)
nop
cmp %rcx, %rcx
lea addresses_WT_ht+0x1d69a, %rax
nop
nop
inc %rcx
mov $0x6162636465666768, %r10
movq %r10, %xmm5
vmovups %ymm5, (%rax)
xor $26243, %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r8
pop %r15
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r14
push %r8
push %r9
push %rsi
// Faulty Load
lea addresses_A+0x9b9a, %r9
add %r14, %r14
mov (%r9), %esi
lea oracles, %r14
and $0xff, %rsi
shlq $12, %rsi
mov (%r14,%rsi,1), %rsi
pop %rsi
pop %r9
pop %r8
pop %r14
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_A', 'AVXalign': True, 'size': 16}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_A', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'same': False, 'congruent': 2, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'same': True, 'congruent': 6, 'type': 'addresses_UC_ht'}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8}}
{'src': {'same': False, 'congruent': 1, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': True, 'congruent': 5, 'type': 'addresses_normal_ht'}}
{'src': {'same': True, 'congruent': 8, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_WC_ht', 'AVXalign': True, 'size': 8}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 2, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 1}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_A_ht', 'AVXalign': True, 'size': 32}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 32}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
| 40.677632 | 2,999 | 0.661329 |
e53664a1ab79935811c9547f7d49f42b6c26d748 | 47,812 | ts | TypeScript | community_detect_frontpage/src/app/process-graph/process-graph.component.ts | sqhtech/GraphHack2019 | 2422a4a1738b841586e6cf08414938dd225cf4ef | [
"Apache-2.0"
] | 1 | 2021-01-25T07:29:11.000Z | 2021-01-25T07:29:11.000Z | community_detect_frontpage/src/app/process-graph/process-graph.component.ts | sqhtech/GraphHack2019 | 2422a4a1738b841586e6cf08414938dd225cf4ef | [
"Apache-2.0"
] | null | null | null | community_detect_frontpage/src/app/process-graph/process-graph.component.ts | sqhtech/GraphHack2019 | 2422a4a1738b841586e6cf08414938dd225cf4ef | [
"Apache-2.0"
] | 2 | 2020-04-30T06:34:05.000Z | 2021-05-19T04:36:30.000Z | import {AfterViewInit, Component, ElementRef, OnInit, Renderer2, ViewChild} from '@angular/core';
import * as PIXI from 'pixi.js';
import * as d3 from 'd3';
import {Viewport} from 'pixi-viewport';
import {GlowFilter} from 'pixi-filters';
import {ProcessGraphService} from './process-graph.service';
import {CommunityDetectionRequest} from './community-detection-request';
@Component({
selector: 'app-process-graph',
templateUrl: './process-graph.component.html',
styleUrls: ['./process-graph.component.css']
})
export class ProcessGraphComponent implements OnInit, AfterViewInit {
@ViewChild('graphDivGrivanNewman', {static: true})
graphDivGrivanNewman: ElementRef;
@ViewChild('graphDivModularityMaximization', {static: true})
graphDivModularityMaximization: ElementRef;
@ViewChild('graphDivSpectrialPartition', {static: true})
graphDivSpectrialPartition: ElementRef;
@ViewChild('graphDivLouvain', {static: true})
graphDivLouvain: ElementRef;
@ViewChild('graphDivWalktrap', {static: true})
graphDivWalktrap: ElementRef;
@ViewChild('graphDivLpa', {static: true})
graphDivLpa: ElementRef;
@ViewChild('chartDiv', {static: true})
chartDiv: ElementRef;
svg: d3.Selection; // 模块度折线图
cur: d3.Selection; // 模块度折线图,当前指针
y: any;
x: any;
TYPE = 'WebGL';
RESOLUTION = 1; // 分辨率,设为1可以默认显示全部节点,可以设置为 window.devicePixelRatio * 2
FORCE_LAYOUT_NODE_REPULSION_STRENGTH = 250;
FORCE_LAYOUT_ITERATIONS = 300;
NODE_RADIUS = 15;
NODE_HIT_RADIUS = this.NODE_RADIUS + 5;
ICON_FONT_FAMILY = 'Material Icons'; // 节点图标字体
ICON_FONT_SIZE = this.NODE_RADIUS / Math.SQRT2 * 2;
ICON_TEXT = 'person';
LABEL_FONT_FAMILY = 'Helvetica'; // 节点标签字体
LABEL_FONT_SIZE = 12;
LABEL_X_PADDING = 2;
LABEL_Y_PADDING = 1;
LINE_ALPHA = 0.6;
app = {}; // PIXI.Application;
viewport = {}; // Viewport;
nodeContainer = {}; // PIXI.ParticleContainer;
graphData = {
nodes: [
{id: 'Myriel', group: 0},
{id: 'Napoleon', group: 0},
{id: 'Mlle.Baptistine', group: 0},
{id: 'Mme.Magloire', group: 0},
{id: 'CountessdeLo', group: 0},
{id: 'Geborand', group: 0},
{id: 'Champtercier', group: 0},
{id: 'Cravatte', group: 0},
{id: 'Count', group: 0},
{id: 'OldMan', group: 0},
{id: 'Labarre', group: 0},
{id: 'Valjean', group: 0},
{id: 'Marguerite', group: 0},
{id: 'Mme.deR', group: 0},
{id: 'Isabeau', group: 0},
{id: 'Gervais', group: 0},
{id: 'Tholomyes', group: 0},
{id: 'Listolier', group: 0},
{id: 'Fameuil', group: 0},
{id: 'Blacheville', group: 0},
{id: 'Favourite', group: 0},
{id: 'Dahlia', group: 0},
{id: 'Zephine', group: 0},
{id: 'Fantine', group: 0},
{id: 'Mme.Thenardier', group: 0},
{id: 'Thenardier', group: 0},
{id: 'Cosette', group: 0},
{id: 'Javert', group: 0},
{id: 'Fauchelevent', group: 0},
{id: 'Bamatabois', group: 0},
{id: 'Perpetue', group: 0},
{id: 'Simplice', group: 0},
{id: 'Scaufflaire', group: 0},
{id: 'Woman1', group: 0},
{id: 'Judge', group: 0},
{id: 'Champmathieu', group: 0},
{id: 'Brevet', group: 0},
{id: 'Chenildieu', group: 0},
{id: 'Cochepaille', group: 0},
{id: 'Pontmercy', group: 0},
{id: 'Boulatruelle', group: 0},
{id: 'Eponine', group: 0},
{id: 'Anzelma', group: 0},
{id: 'Woman2', group: 0},
{id: 'MotherInnocent', group: 0},
{id: 'Gribier', group: 0},
{id: 'Jondrette', group: 0},
{id: 'Mme.Burgon', group: 0},
{id: 'Gavroche', group: 0},
{id: 'Gillenormand', group: 0},
{id: 'Magnon', group: 0},
{id: 'Mlle.Gillenormand', group: 0},
{id: 'Mme.Pontmercy', group: 0},
{id: 'Mlle.Vaubois', group: 0},
{id: 'Lt.Gillenormand', group: 0},
{id: 'Marius', group: 0},
{id: 'BaronessT', group: 0},
{id: 'Mabeuf', group: 0},
{id: 'Enjolras', group: 0},
{id: 'Combeferre', group: 0},
{id: 'Prouvaire', group: 0},
{id: 'Feuilly', group: 0},
{id: 'Courfeyrac', group: 0},
{id: 'Bahorel', group: 0},
{id: 'Bossuet', group: 0},
{id: 'Joly', group: 0},
{id: 'Grantaire', group: 0},
{id: 'MotherPlutarch', group: 0},
{id: 'Gueulemer', group: 0},
{id: 'Babet', group: 0},
{id: 'Claquesous', group: 0},
{id: 'Montparnasse', group: 0},
{id: 'Toussaint', group: 0},
{id: 'Child1', group: 0},
{id: 'Child2', group: 0},
{id: 'Brujon', group: 0},
{id: 'Mme.Hucheloup', group: 0}
],
links: [
{source: 'Napoleon', target: 'Myriel', value: 1},
{source: 'Mlle.Baptistine', target: 'Myriel', value: 8},
{source: 'Mme.Magloire', target: 'Myriel', value: 10},
{source: 'Mme.Magloire', target: 'Mlle.Baptistine', value: 6},
{source: 'CountessdeLo', target: 'Myriel', value: 1},
{source: 'Geborand', target: 'Myriel', value: 1},
{source: 'Champtercier', target: 'Myriel', value: 1},
{source: 'Cravatte', target: 'Myriel', value: 1},
{source: 'Count', target: 'Myriel', value: 2},
{source: 'OldMan', target: 'Myriel', value: 1},
{source: 'Valjean', target: 'Labarre', value: 1},
{source: 'Valjean', target: 'Mme.Magloire', value: 3},
{source: 'Valjean', target: 'Mlle.Baptistine', value: 3},
{source: 'Valjean', target: 'Myriel', value: 5},
{source: 'Marguerite', target: 'Valjean', value: 1},
{source: 'Mme.deR', target: 'Valjean', value: 1},
{source: 'Isabeau', target: 'Valjean', value: 1},
{source: 'Gervais', target: 'Valjean', value: 1},
{source: 'Listolier', target: 'Tholomyes', value: 4},
{source: 'Fameuil', target: 'Tholomyes', value: 4},
{source: 'Fameuil', target: 'Listolier', value: 4},
{source: 'Blacheville', target: 'Tholomyes', value: 4},
{source: 'Blacheville', target: 'Listolier', value: 4},
{source: 'Blacheville', target: 'Fameuil', value: 4},
{source: 'Favourite', target: 'Tholomyes', value: 3},
{source: 'Favourite', target: 'Listolier', value: 3},
{source: 'Favourite', target: 'Fameuil', value: 3},
{source: 'Favourite', target: 'Blacheville', value: 4},
{source: 'Dahlia', target: 'Tholomyes', value: 3},
{source: 'Dahlia', target: 'Listolier', value: 3},
{source: 'Dahlia', target: 'Fameuil', value: 3},
{source: 'Dahlia', target: 'Blacheville', value: 3},
{source: 'Dahlia', target: 'Favourite', value: 5},
{source: 'Zephine', target: 'Tholomyes', value: 3},
{source: 'Zephine', target: 'Listolier', value: 3},
{source: 'Zephine', target: 'Fameuil', value: 3},
{source: 'Zephine', target: 'Blacheville', value: 3},
{source: 'Zephine', target: 'Favourite', value: 4},
{source: 'Zephine', target: 'Dahlia', value: 4},
{source: 'Fantine', target: 'Tholomyes', value: 3},
{source: 'Fantine', target: 'Listolier', value: 3},
{source: 'Fantine', target: 'Fameuil', value: 3},
{source: 'Fantine', target: 'Blacheville', value: 3},
{source: 'Fantine', target: 'Favourite', value: 4},
{source: 'Fantine', target: 'Dahlia', value: 4},
{source: 'Fantine', target: 'Zephine', value: 4},
{source: 'Fantine', target: 'Marguerite', value: 2},
{source: 'Fantine', target: 'Valjean', value: 9},
{source: 'Mme.Thenardier', target: 'Fantine', value: 2},
{source: 'Mme.Thenardier', target: 'Valjean', value: 7},
{source: 'Thenardier', target: 'Mme.Thenardier', value: 13},
{source: 'Thenardier', target: 'Fantine', value: 1},
{source: 'Thenardier', target: 'Valjean', value: 12},
{source: 'Cosette', target: 'Mme.Thenardier', value: 4},
{source: 'Cosette', target: 'Valjean', value: 31},
{source: 'Cosette', target: 'Tholomyes', value: 1},
{source: 'Cosette', target: 'Thenardier', value: 1},
{source: 'Javert', target: 'Valjean', value: 17},
{source: 'Javert', target: 'Fantine', value: 5},
{source: 'Javert', target: 'Thenardier', value: 5},
{source: 'Javert', target: 'Mme.Thenardier', value: 1},
{source: 'Javert', target: 'Cosette', value: 1},
{source: 'Fauchelevent', target: 'Valjean', value: 8},
{source: 'Fauchelevent', target: 'Javert', value: 1},
{source: 'Bamatabois', target: 'Fantine', value: 1},
{source: 'Bamatabois', target: 'Javert', value: 1},
{source: 'Bamatabois', target: 'Valjean', value: 2},
{source: 'Perpetue', target: 'Fantine', value: 1},
{source: 'Simplice', target: 'Perpetue', value: 2},
{source: 'Simplice', target: 'Valjean', value: 3},
{source: 'Simplice', target: 'Fantine', value: 2},
{source: 'Simplice', target: 'Javert', value: 1},
{source: 'Scaufflaire', target: 'Valjean', value: 1},
{source: 'Woman1', target: 'Valjean', value: 2},
{source: 'Woman1', target: 'Javert', value: 1},
{source: 'Judge', target: 'Valjean', value: 3},
{source: 'Judge', target: 'Bamatabois', value: 2},
{source: 'Champmathieu', target: 'Valjean', value: 3},
{source: 'Champmathieu', target: 'Judge', value: 3},
{source: 'Champmathieu', target: 'Bamatabois', value: 2},
{source: 'Brevet', target: 'Judge', value: 2},
{source: 'Brevet', target: 'Champmathieu', value: 2},
{source: 'Brevet', target: 'Valjean', value: 2},
{source: 'Brevet', target: 'Bamatabois', value: 1},
{source: 'Chenildieu', target: 'Judge', value: 2},
{source: 'Chenildieu', target: 'Champmathieu', value: 2},
{source: 'Chenildieu', target: 'Brevet', value: 2},
{source: 'Chenildieu', target: 'Valjean', value: 2},
{source: 'Chenildieu', target: 'Bamatabois', value: 1},
{source: 'Cochepaille', target: 'Judge', value: 2},
{source: 'Cochepaille', target: 'Champmathieu', value: 2},
{source: 'Cochepaille', target: 'Brevet', value: 2},
{source: 'Cochepaille', target: 'Chenildieu', value: 2},
{source: 'Cochepaille', target: 'Valjean', value: 2},
{source: 'Cochepaille', target: 'Bamatabois', value: 1},
{source: 'Pontmercy', target: 'Thenardier', value: 1},
{source: 'Boulatruelle', target: 'Thenardier', value: 1},
{source: 'Eponine', target: 'Mme.Thenardier', value: 2},
{source: 'Eponine', target: 'Thenardier', value: 3},
{source: 'Anzelma', target: 'Eponine', value: 2},
{source: 'Anzelma', target: 'Thenardier', value: 2},
{source: 'Anzelma', target: 'Mme.Thenardier', value: 1},
{source: 'Woman2', target: 'Valjean', value: 3},
{source: 'Woman2', target: 'Cosette', value: 1},
{source: 'Woman2', target: 'Javert', value: 1},
{source: 'MotherInnocent', target: 'Fauchelevent', value: 3},
{source: 'MotherInnocent', target: 'Valjean', value: 1},
{source: 'Gribier', target: 'Fauchelevent', value: 2},
{source: 'Mme.Burgon', target: 'Jondrette', value: 1},
{source: 'Gavroche', target: 'Mme.Burgon', value: 2},
{source: 'Gavroche', target: 'Thenardier', value: 1},
{source: 'Gavroche', target: 'Javert', value: 1},
{source: 'Gavroche', target: 'Valjean', value: 1},
{source: 'Gillenormand', target: 'Cosette', value: 3},
{source: 'Gillenormand', target: 'Valjean', value: 2},
{source: 'Magnon', target: 'Gillenormand', value: 1},
{source: 'Magnon', target: 'Mme.Thenardier', value: 1},
{source: 'Mlle.Gillenormand', target: 'Gillenormand', value: 9},
{source: 'Mlle.Gillenormand', target: 'Cosette', value: 2},
{source: 'Mlle.Gillenormand', target: 'Valjean', value: 2},
{source: 'Mme.Pontmercy', target: 'Mlle.Gillenormand', value: 1},
{source: 'Mme.Pontmercy', target: 'Pontmercy', value: 1},
{source: 'Mlle.Vaubois', target: 'Mlle.Gillenormand', value: 1},
{source: 'Lt.Gillenormand', target: 'Mlle.Gillenormand', value: 2},
{source: 'Lt.Gillenormand', target: 'Gillenormand', value: 1},
{source: 'Lt.Gillenormand', target: 'Cosette', value: 1},
{source: 'Marius', target: 'Mlle.Gillenormand', value: 6},
{source: 'Marius', target: 'Gillenormand', value: 12},
{source: 'Marius', target: 'Pontmercy', value: 1},
{source: 'Marius', target: 'Lt.Gillenormand', value: 1},
{source: 'Marius', target: 'Cosette', value: 21},
{source: 'Marius', target: 'Valjean', value: 19},
{source: 'Marius', target: 'Tholomyes', value: 1},
{source: 'Marius', target: 'Thenardier', value: 2},
{source: 'Marius', target: 'Eponine', value: 5},
{source: 'Marius', target: 'Gavroche', value: 4},
{source: 'BaronessT', target: 'Gillenormand', value: 1},
{source: 'BaronessT', target: 'Marius', value: 1},
{source: 'Mabeuf', target: 'Marius', value: 1},
{source: 'Mabeuf', target: 'Eponine', value: 1},
{source: 'Mabeuf', target: 'Gavroche', value: 1},
{source: 'Enjolras', target: 'Marius', value: 7},
{source: 'Enjolras', target: 'Gavroche', value: 7},
{source: 'Enjolras', target: 'Javert', value: 6},
{source: 'Enjolras', target: 'Mabeuf', value: 1},
{source: 'Enjolras', target: 'Valjean', value: 4},
{source: 'Combeferre', target: 'Enjolras', value: 15},
{source: 'Combeferre', target: 'Marius', value: 5},
{source: 'Combeferre', target: 'Gavroche', value: 6},
{source: 'Combeferre', target: 'Mabeuf', value: 2},
{source: 'Prouvaire', target: 'Gavroche', value: 1},
{source: 'Prouvaire', target: 'Enjolras', value: 4},
{source: 'Prouvaire', target: 'Combeferre', value: 2},
{source: 'Feuilly', target: 'Gavroche', value: 2},
{source: 'Feuilly', target: 'Enjolras', value: 6},
{source: 'Feuilly', target: 'Prouvaire', value: 2},
{source: 'Feuilly', target: 'Combeferre', value: 5},
{source: 'Feuilly', target: 'Mabeuf', value: 1},
{source: 'Feuilly', target: 'Marius', value: 1},
{source: 'Courfeyrac', target: 'Marius', value: 9},
{source: 'Courfeyrac', target: 'Enjolras', value: 17},
{source: 'Courfeyrac', target: 'Combeferre', value: 13},
{source: 'Courfeyrac', target: 'Gavroche', value: 7},
{source: 'Courfeyrac', target: 'Mabeuf', value: 2},
{source: 'Courfeyrac', target: 'Eponine', value: 1},
{source: 'Courfeyrac', target: 'Feuilly', value: 6},
{source: 'Courfeyrac', target: 'Prouvaire', value: 3},
{source: 'Bahorel', target: 'Combeferre', value: 5},
{source: 'Bahorel', target: 'Gavroche', value: 5},
{source: 'Bahorel', target: 'Courfeyrac', value: 6},
{source: 'Bahorel', target: 'Mabeuf', value: 2},
{source: 'Bahorel', target: 'Enjolras', value: 4},
{source: 'Bahorel', target: 'Feuilly', value: 3},
{source: 'Bahorel', target: 'Prouvaire', value: 2},
{source: 'Bahorel', target: 'Marius', value: 1},
{source: 'Bossuet', target: 'Marius', value: 5},
{source: 'Bossuet', target: 'Courfeyrac', value: 12},
{source: 'Bossuet', target: 'Gavroche', value: 5},
{source: 'Bossuet', target: 'Bahorel', value: 4},
{source: 'Bossuet', target: 'Enjolras', value: 10},
{source: 'Bossuet', target: 'Feuilly', value: 6},
{source: 'Bossuet', target: 'Prouvaire', value: 2},
{source: 'Bossuet', target: 'Combeferre', value: 9},
{source: 'Bossuet', target: 'Mabeuf', value: 1},
{source: 'Bossuet', target: 'Valjean', value: 1},
{source: 'Joly', target: 'Bahorel', value: 5},
{source: 'Joly', target: 'Bossuet', value: 7},
{source: 'Joly', target: 'Gavroche', value: 3},
{source: 'Joly', target: 'Courfeyrac', value: 5},
{source: 'Joly', target: 'Enjolras', value: 5},
{source: 'Joly', target: 'Feuilly', value: 5},
{source: 'Joly', target: 'Prouvaire', value: 2},
{source: 'Joly', target: 'Combeferre', value: 5},
{source: 'Joly', target: 'Mabeuf', value: 1},
{source: 'Joly', target: 'Marius', value: 2},
{source: 'Grantaire', target: 'Bossuet', value: 3},
{source: 'Grantaire', target: 'Enjolras', value: 3},
{source: 'Grantaire', target: 'Combeferre', value: 1},
{source: 'Grantaire', target: 'Courfeyrac', value: 2},
{source: 'Grantaire', target: 'Joly', value: 2},
{source: 'Grantaire', target: 'Gavroche', value: 1},
{source: 'Grantaire', target: 'Bahorel', value: 1},
{source: 'Grantaire', target: 'Feuilly', value: 1},
{source: 'Grantaire', target: 'Prouvaire', value: 1},
{source: 'MotherPlutarch', target: 'Mabeuf', value: 3},
{source: 'Gueulemer', target: 'Thenardier', value: 5},
{source: 'Gueulemer', target: 'Valjean', value: 1},
{source: 'Gueulemer', target: 'Mme.Thenardier', value: 1},
{source: 'Gueulemer', target: 'Javert', value: 1},
{source: 'Gueulemer', target: 'Gavroche', value: 1},
{source: 'Gueulemer', target: 'Eponine', value: 1},
{source: 'Babet', target: 'Thenardier', value: 6},
{source: 'Babet', target: 'Gueulemer', value: 6},
{source: 'Babet', target: 'Valjean', value: 1},
{source: 'Babet', target: 'Mme.Thenardier', value: 1},
{source: 'Babet', target: 'Javert', value: 2},
{source: 'Babet', target: 'Gavroche', value: 1},
{source: 'Babet', target: 'Eponine', value: 1},
{source: 'Claquesous', target: 'Thenardier', value: 4},
{source: 'Claquesous', target: 'Babet', value: 4},
{source: 'Claquesous', target: 'Gueulemer', value: 4},
{source: 'Claquesous', target: 'Valjean', value: 1},
{source: 'Claquesous', target: 'Mme.Thenardier', value: 1},
{source: 'Claquesous', target: 'Javert', value: 1},
{source: 'Claquesous', target: 'Eponine', value: 1},
{source: 'Claquesous', target: 'Enjolras', value: 1},
{source: 'Montparnasse', target: 'Javert', value: 1},
{source: 'Montparnasse', target: 'Babet', value: 2},
{source: 'Montparnasse', target: 'Gueulemer', value: 2},
{source: 'Montparnasse', target: 'Claquesous', value: 2},
{source: 'Montparnasse', target: 'Valjean', value: 1},
{source: 'Montparnasse', target: 'Gavroche', value: 1},
{source: 'Montparnasse', target: 'Eponine', value: 1},
{source: 'Montparnasse', target: 'Thenardier', value: 1},
{source: 'Toussaint', target: 'Cosette', value: 2},
{source: 'Toussaint', target: 'Javert', value: 1},
{source: 'Toussaint', target: 'Valjean', value: 1},
{source: 'Child1', target: 'Gavroche', value: 2},
{source: 'Child2', target: 'Gavroche', value: 2},
{source: 'Child2', target: 'Child1', value: 3},
{source: 'Brujon', target: 'Babet', value: 3},
{source: 'Brujon', target: 'Gueulemer', value: 3},
{source: 'Brujon', target: 'Thenardier', value: 3},
{source: 'Brujon', target: 'Gavroche', value: 1},
{source: 'Brujon', target: 'Eponine', value: 1},
{source: 'Brujon', target: 'Claquesous', value: 1},
{source: 'Brujon', target: 'Montparnasse', value: 1},
{source: 'Mme.Hucheloup', target: 'Bossuet', value: 1},
{source: 'Mme.Hucheloup', target: 'Joly', value: 1},
{source: 'Mme.Hucheloup', target: 'Grantaire', value: 1},
{source: 'Mme.Hucheloup', target: 'Bahorel', value: 1},
{source: 'Mme.Hucheloup', target: 'Courfeyrac', value: 1},
{source: 'Mme.Hucheloup', target: 'Gavroche', value: 1},
{source: 'Mme.Hucheloup', target: 'Enjolras', value: 1}
]
};
nodes = {}; // Set<any>;
links = {}; // Set<any>;
renderRequestId = {};
colorScale = d3.scaleOrdinal(d3.schemeTableau10);
// linksLayer = new PIXI.Graphics();
linksLayer = {}; // new PIXI.Container();
// 显示: links, nodes, labels, front
nodesLayer = {}; // new PIXI.Container();
labelsLayer = {}; // new PIXI.Container();
frontLayer = {}; // new PIXI.Container();
// 状态
nodeDataToNodeGfx = {}; // new WeakMap();
nodeGfxToNodeData = {}; // new WeakMap();
nodeDataToLabelGfx = {}; // new WeakMap();
labelGfxToNodeData = {}; // new WeakMap();
nodeDataToCircle = {}; // new WeakMap();
circleToNodeData = {}; // new WeakMap();
indexToNodeData = {}; // new Map();
linkDataToLineGfx = {}; // new WeakMap();
lineGfxToLinkData = {}; // new WeakMap();
lineGfxToFilter = {}; // new WeakMap();
linkDataToLine = {}; // new WeakMap();
lineToLinkData = {}; // new WeakMap();
indexToLinkData = {}; // new Map();
hoveredNodeData = {};
hoveredNodeGfxOriginalChildren = {};
hoveredLabelGfxOriginalChildren = {};
clickedAlgorithm;
clickedNodeData = {};
clickedLineData = {};
resultData = {}; // [];
chartData = [
{iteration: 1, modularity: -2.2134193212463565e-17},
{iteration: 100, modularity: 1},
];
CHART_SCREEN_WIDTH = 800; // 默认值,会在initConfig()函数中被修改
CHART_SCREEN_HEIGHT = 600; // 默认值,会在initConfig()函数中被修改
constructor(private elementRef: ElementRef,
private renderer: Renderer2,
public processGraphService: ProcessGraphService
) {
if (!PIXI.utils.isWebGLSupported()) {
this.TYPE = 'canvas';
}
PIXI.utils.sayHello(this.TYPE);
}
LABEL_TEXT = nodeData => nodeData.id;
ngOnInit() {
}
ngAfterViewInit() {
// this.renderer.setStyle(this.graphDivGrivanNewman.nativeElement, 'background-color', '#2d3035');
this.initConfig();
// 'girvan_newman' | 'modularity_max_maximization' | 'spectral_partition' | 'louvain' | 'walktrap' | 'lpa'
this.initGraphics('girvan_newman', this.graphDivGrivanNewman.nativeElement);
this.initData('girvan_newman');
this.initGraphics('modularity_maximization', this.graphDivModularityMaximization.nativeElement);
this.initData('modularity_maximization');
this.initGraphics('spectral_partition', this.graphDivSpectrialPartition.nativeElement);
this.initData('spectral_partition', 3);
this.initGraphics('louvain', this.graphDivLouvain.nativeElement);
this.initData('louvain');
this.initGraphics('walktrap', this.graphDivWalktrap.nativeElement);
this.initData('walktrap');
this.initGraphics('lpa', this.graphDivLpa.nativeElement);
this.initData('lpa');
}
initConfig() {
this.CHART_SCREEN_WIDTH = this.chartDiv.nativeElement.offsetWidth;
this.CHART_SCREEN_HEIGHT = this.chartDiv.nativeElement.offsetHeight;
}
/**
* 初始化图表
*/
initGraphics(algorithm, nativeElement) {
const GRAPH_SCREEN_WIDTH = nativeElement.offsetWidth;
const GRAPH_SCREEN_HEIGHT = nativeElement.offsetHeight;
const GRAPH_WORLD_WIDTH = GRAPH_SCREEN_WIDTH * 2;
const GRAPH_WORLD_HEIGHT = GRAPH_SCREEN_WIDTH * 2;
this.app[algorithm] = new PIXI.Application({
width: GRAPH_SCREEN_WIDTH,
height: GRAPH_SCREEN_HEIGHT,
resolution: this.RESOLUTION,
transparent: true,
antialias: true,
autoStart: false, // 不通过ticker进行绘制,仅在需要时手动进行绘制
forceCanvas: false,
// resizeTo: this.graphDivGrivanNewman.nativeElement
});
// TODO
this.renderer.appendChild(nativeElement, this.app[algorithm].view);
// 修改画布颜色、大小
// this.app.renderer.backgroundColor = 0xFFFFFF;
// this.app.renderer.resize(512, 512);
// 让画布占据整个窗口
// this.app.renderer.view.style.position = 'absolute';
// this.app.renderer.view.style.display = 'block';
// this.app.renderer.resize(window.innerWidth, window.innerHeight);
this.nodeContainer[algorithm] = new PIXI.ParticleContainer();
this.app[algorithm].stage.addChild(this.nodeContainer[algorithm]);
this.initForceLayout(algorithm, this.graphData, {
iterations: this.FORCE_LAYOUT_ITERATIONS,
nodeRepulsionStrength: this.FORCE_LAYOUT_NODE_REPULSION_STRENGTH,
});
this.nodes[algorithm].forEach(nodeData => {
nodeData.x += GRAPH_WORLD_WIDTH / 2;
nodeData.y += GRAPH_WORLD_HEIGHT / 2;
});
this.viewport[algorithm] = new Viewport({
screenWidth: GRAPH_SCREEN_WIDTH,
screenHeight: GRAPH_SCREEN_HEIGHT,
worldWidth: GRAPH_WORLD_WIDTH,
worldHeight: GRAPH_WORLD_HEIGHT,
interaction: this.app[algorithm].renderer.plugins.interaction
});
const zoomIn = () => {
this.viewport[algorithm].zoom(-GRAPH_WORLD_WIDTH / 10, true);
};
const zoomOut = () => {
this.viewport[algorithm].zoom(GRAPH_WORLD_WIDTH / 10, true);
};
const resetViewport = () => {
this.viewport[algorithm].center = new PIXI.Point(GRAPH_WORLD_WIDTH / 2, GRAPH_WORLD_HEIGHT / 2);
this.viewport[algorithm].setZoom(0.5, true);
};
this.app[algorithm].stage.addChild(this.viewport[algorithm]);
this.viewport[algorithm]
.drag()
.pinch()
.wheel()
.decelerate();
// Viewport 框架中主动声明的事件类型中并没有 frame-end
// @ts-ignore
this.viewport[algorithm].on('frame-end', () => {
if (this.viewport[algorithm].dirty) {
this.requestRender(algorithm);
this.viewport[algorithm].dirty = false;
}
});
this.linksLayer[algorithm] = new PIXI.Container();
this.nodesLayer[algorithm] = new PIXI.Container();
this.labelsLayer[algorithm] = new PIXI.Container();
this.frontLayer[algorithm] = new PIXI.Container();
this.viewport[algorithm].addChild(this.linksLayer[algorithm]);
this.viewport[algorithm].addChild(this.nodesLayer[algorithm]);
this.viewport[algorithm].addChild(this.labelsLayer[algorithm]);
this.viewport[algorithm].addChild(this.frontLayer[algorithm]);
// 绘制节点
const nodeDataGfxPairs = [];
this.nodes[algorithm].forEach((nodeData) => {
const nodeGfx = new PIXI.Container();
nodeGfx.x = nodeData.x;
nodeGfx.y = nodeData.y;
nodeGfx.interactive = true;
nodeGfx.buttonMode = true;
nodeGfx.hitArea = new PIXI.Circle(0, 0, this.NODE_HIT_RADIUS);
nodeGfx.on('mouseover', event => this.hoverNodeStart(algorithm, this.nodeGfxToNodeData[algorithm].get(event.currentTarget)));
nodeGfx.on('mouseout', event => this.hoverNodeEnd(algorithm, this.nodeGfxToNodeData[algorithm].get(event.currentTarget)));
nodeGfx.on('mousedown', event => this.clickNodeStart(algorithm, this.nodeGfxToNodeData[algorithm].get(event.currentTarget)));
nodeGfx.on('mouseup', () => this.clickNodeEnd(algorithm));
nodeGfx.on('mouseupoutside', () => this.clickNodeEnd(algorithm));
const circle = new PIXI.Graphics();
circle.x = 0;
circle.y = 0;
circle.beginFill(this.colorToNumber(this.color(nodeData)));
circle.drawCircle(0, 0, this.NODE_RADIUS);
nodeGfx.addChild(circle);
const circleBorder = new PIXI.Graphics();
circle.x = 0;
circle.y = 0;
circleBorder.lineStyle(1.5, 0xffffff);
circleBorder.drawCircle(0, 0, this.NODE_RADIUS);
nodeGfx.addChild(circleBorder);
// 绘制节点图标
// const icon = new PIXI.Text(this.ICON_TEXT, {
// fontFamily: this.ICON_FONT_FAMILY,
// fontSize: this.ICON_FONT_SIZE,
// fill: 0xffffff
// });
// icon.x = 0;
// icon.y = 0;
// icon.anchor.set(0.5);
// nodeGfx.addChild(icon);
const labelGfx = new PIXI.Container();
labelGfx.x = nodeData.x;
labelGfx.y = nodeData.y;
labelGfx.interactive = true;
labelGfx.buttonMode = true;
labelGfx.on('mouseover', event => this.hoverNodeStart(algorithm, this.labelGfxToNodeData[algorithm].get(event.currentTarget)));
labelGfx.on('mouseout', event => this.hoverNodeEnd(algorithm, this.labelGfxToNodeData[algorithm].get(event.currentTarget)));
labelGfx.on('mousedown', event => this.clickNodeStart(algorithm, this.labelGfxToNodeData[algorithm].get(event.currentTarget)));
labelGfx.on('mouseup', () => this.clickNodeEnd(algorithm));
labelGfx.on('mouseupoutside', () => this.clickNodeEnd(algorithm));
const labelText = new PIXI.Text(this.LABEL_TEXT(nodeData), {
fontFamily: this.LABEL_FONT_FAMILY,
fontSize: this.LABEL_FONT_SIZE,
fill: 0x333333
});
labelText.x = 0;
labelText.y = this.NODE_HIT_RADIUS + this.LABEL_Y_PADDING;
labelText.anchor.set(0.5, 0);
const labelBackground = new PIXI.Sprite(PIXI.Texture.WHITE);
labelBackground.x = -(labelText.width + this.LABEL_X_PADDING * 2) / 2;
labelBackground.y = this.NODE_HIT_RADIUS;
labelBackground.width = labelText.width + this.LABEL_X_PADDING * 2;
labelBackground.height = labelText.height + this.LABEL_Y_PADDING * 2;
labelBackground.tint = 0xffffff;
labelBackground.alpha = 0.5;
labelGfx.addChild(labelBackground);
labelGfx.addChild(labelText);
this.nodesLayer[algorithm].addChild(nodeGfx);
this.labelsLayer[algorithm].addChild(labelGfx);
nodeDataGfxPairs.push([nodeData, nodeGfx, labelGfx, circle]);
});
// 绘制边
const linkDataGfxPairs = [];
this.links[algorithm].forEach(linkData => {
const lineWidth = Math.sqrt(linkData.value);
const [deltaX, deltaY] = this.deltaXY(linkData.source.x, linkData.source.y, linkData.target.x, linkData.target.y, lineWidth);
const lineGfx = new PIXI.Container();
lineGfx.interactive = true;
lineGfx.buttonMode = true;
lineGfx.hitArea = new PIXI.Polygon([
new PIXI.Point(linkData.source.x - deltaX, linkData.source.y + deltaY),
new PIXI.Point(linkData.target.x - deltaX, linkData.target.y + deltaY),
new PIXI.Point(linkData.target.x + deltaX, linkData.target.y - deltaY),
new PIXI.Point(linkData.source.x + deltaX, linkData.source.y - deltaY)
]);
lineGfx.on('mousedown', event => this.clickLineStart(algorithm, this.lineGfxToLinkData[algorithm].get(event.currentTarget)));
lineGfx.on('mouseup', () => this.clickLineEnd(algorithm));
lineGfx.on('mouseupoutside', () => this.clickLineEnd(algorithm));
const line = new PIXI.Graphics();
line.alpha = this.LINE_ALPHA;
line.lineStyle(lineWidth, 0x999999);
line.moveTo(linkData.source.x, linkData.source.y);
line.lineTo(linkData.target.x, linkData.target.y);
lineGfx.addChild(line);
this.linksLayer[algorithm].addChild(lineGfx);
linkDataGfxPairs.push([linkData, lineGfx, line, linkData.source.index.toString() + '_' + linkData.target.index.toString()]);
});
// 索引
this.nodeDataToNodeGfx[algorithm] = new WeakMap(nodeDataGfxPairs.map(([nodeData, nodeGfx, labelGfx, circle]) => [nodeData, nodeGfx]));
this.nodeGfxToNodeData[algorithm] = new WeakMap(nodeDataGfxPairs.map(([nodeData, nodeGfx, labelGfx, circle]) => [nodeGfx, nodeData]));
this.nodeDataToLabelGfx[algorithm] = new WeakMap(nodeDataGfxPairs.map(([nodeData, nodeGfx, labelGfx, circle]) => [nodeData, labelGfx]));
this.labelGfxToNodeData[algorithm] = new WeakMap(nodeDataGfxPairs.map(([nodeData, nodeGfx, labelGfx, circle]) => [labelGfx, nodeData]));
this.nodeDataToCircle[algorithm] = new WeakMap(nodeDataGfxPairs.map(([nodeData, nodeGfx, labelGfx, circle]) => [nodeData, circle]));
this.circleToNodeData[algorithm] = new WeakMap(nodeDataGfxPairs.map(([nodeData, nodeGfx, labelGfx, circle]) => [circle, nodeData]));
this.indexToNodeData[algorithm] = new Map(nodeDataGfxPairs.map(([nodeData, nodeGfx, labelGfx, circle]) => [nodeData.index, nodeData]));
this.linkDataToLineGfx[algorithm] = new WeakMap(linkDataGfxPairs.map(([linkData, lineGfx, line]) => [linkData, lineGfx]));
this.lineGfxToLinkData[algorithm] = new WeakMap(linkDataGfxPairs.map(([linkData, lineGfx, line]) => [lineGfx, linkData]));
this.linkDataToLine[algorithm] = new WeakMap(linkDataGfxPairs.map(([linkData, lineGfx, line]) => [linkData, line]));
this.lineToLinkData[algorithm] = new WeakMap(linkDataGfxPairs.map(([linkData, lineGfx, line]) => [line, linkData]));
this.indexToLinkData[algorithm] = new Map(
linkDataGfxPairs.map(([linkData, lineGfx, line, key]) => [key, linkData]));
// 初始化可视区域
resetViewport();
this.update(algorithm);
// 阻止默认鼠标滚动行为
this.app[algorithm].view.addEventListener('wheel', event => {
event.preventDefault();
});
}
/**
* 请求社群发现的数据
*/
initData(algorithm, level?: number): Promise<any> {
this.chartData = [];
const requestData = new CommunityDetectionRequest();
requestData.num_nodes = this.nodes[algorithm].size;
requestData.method = algorithm;
if (level) {
requestData.level = level;
} else {
requestData.level = 2;
}
requestData.edges = [];
this.links[algorithm].forEach(linkData => {
requestData.edges.push({source: linkData.source.index, target: linkData.target.index});
});
return this.processGraphService.requestCommunityDetection(requestData)
.then(responseData => {
this.resultData[algorithm] = responseData;
if (algorithm === 'girvan_newman') {
this.resultData[algorithm].forEach(data => {
this.chartData.push({iteration: data.iteration, modularity: data.modularity});
});
this.initChart();
this.startAnimation(algorithm);
} else {
this.resultData[algorithm].forEach(node => {
const nodeData = this.indexToNodeData[algorithm].get(node.node);
if (nodeData) {
if (nodeData.group !== node.community) {
nodeData.group = node.community;
this.refreshColor(algorithm, nodeData);
}
}
});
this.requestRender(algorithm);
}
});
}
/**
* 初始化力学模拟器
* @param data 数据
* @param options 参数
*/
initForceLayout(algorithm, data, options: any) {
this.nodes[algorithm] = new Set<any>(data.nodes);
this.links[algorithm] = new Set<any>(data.links);
const iterations = options.iterations;
const nodeRepulsionStrength = options.nodeRepulsionStrength;
d3.forceSimulation(data.nodes)
// 链接力
.force('link', d3.forceLink(data.links).id(linkData => linkData.id))
// 万有引力
.force('charge', d3.forceManyBody().strength(-nodeRepulsionStrength))
// 向心力
.force('center', d3.forceCenter())
.stop()
.tick(iterations);
}
initChart() {
const selection = d3.select(this.chartDiv.nativeElement);
const margin = ({top: 20, right: 30, bottom: 30, left: 40});
this.y = d3.scaleLinear()
.domain([0, d3.max(this.chartData, d => d.modularity)]).nice()
.range([this.CHART_SCREEN_HEIGHT - margin.bottom, margin.top]);
this.x = d3.scaleLinear()
.domain(d3.extent(this.chartData, d => d.iteration))
.range([margin.left, this.CHART_SCREEN_WIDTH - margin.right]);
const line = d3.line()
.defined(d => !isNaN(d.modularity))
.x(d => this.x(d.iteration))
.y(d => this.y(d.modularity));
const yAxis = g => {
g.attr('transform', `translate(${margin.left},0)`)
.call(d3.axisLeft(this.y))
.call(g1 => g1.select('.domain').remove())
.call(g2 => {
g2.select('.tick:last-of-type text').clone()
.attr('x', 3)
.attr('text-anchor', 'start')
.attr('font-weight', 'bold')
.text('模块度');
}
);
};
const xAxis = g => g
.attr('transform', `translate(0,${this.CHART_SCREEN_HEIGHT - margin.bottom})`)
.call(d3.axisBottom(this.x).ticks(this.CHART_SCREEN_WIDTH / 80).tickSizeOuter(0))
.call(g1 => g1.append('text')
.attr('x', this.CHART_SCREEN_WIDTH - margin.right)
.attr('y', -4)
.attr('fill', '#8a8d93')
.attr('font-weight', 'bold')
.attr('text-anchor', 'end')
.text('迭代次数'));
this.svg = selection
.append('svg')
.attr('viewBox', [0, 0, this.CHART_SCREEN_WIDTH, this.CHART_SCREEN_HEIGHT])
.style('border', '1px dashed #ccc');
this.svg.append('g')
.call(xAxis);
this.svg.append('g')
.call(yAxis);
this.svg.append('path')
.datum(this.chartData)
.attr('fill', 'none')
.attr('stroke', 'steelblue')
.attr('stroke-width', 1.5)
.attr('stroke-linejoin', 'round')
.attr('stroke-linecap', 'round')
.attr('d', line);
this.cur = this.svg.append('circle')
.classed('c', true)
.attr('r', 6)
.attr('fill', 'orangered');
}
startAnimation(algorithm) {
if (!this.resultData[algorithm] || this.resultData[algorithm].length === 0) {
return;
}
let i = 0;
let maxModularity = Number.MIN_VALUE;
let maxModularityIndex = 0;
for (i = 0; i < this.resultData[algorithm].length; i++) {
if (maxModularity < this.resultData[algorithm][i].modularity) {
maxModularity = this.resultData[algorithm][i].modularity;
maxModularityIndex = i;
}
}
i = 0;
const mainInterval = setInterval(() => {
if (i <= maxModularityIndex) {
const retData = this.resultData[algorithm][i];
this.cur
.attr('cx', this.x(i))
.attr('cy', this.y(this.resultData[algorithm][i].modularity));
let linkData = this.indexToLinkData[algorithm].get(retData.cut.source + '_' + retData.cut.target);
if (!linkData) {
linkData = this.indexToLinkData[algorithm].get(retData.cut.target + '_' + retData.cut.source);
}
if (linkData) {
// this.deleteLink(linkData);
this.startDeleteLine(algorithm, linkData);
}
retData.communities.forEach(node => {
const nodeData = this.indexToNodeData[algorithm].get(node.node);
if (nodeData) {
if (nodeData.group !== node.community) {
nodeData.group = node.community;
this.refreshColor(algorithm, nodeData);
}
}
});
i++;
} else {
clearInterval(mainInterval);
}
this.requestRender(algorithm);
}, 100);
}
startDeleteLine(algorithm, linkData) {
const lineGfx = this.linkDataToLineGfx[algorithm].get(linkData);
if (!lineGfx) {
return;
}
if (!this.lineGfxToFilter[algorithm]) {
this.lineGfxToFilter[algorithm] = new WeakMap();
}
let filter: GlowFilter = this.lineGfxToFilter[algorithm].get(lineGfx);
if (!filter) {
// filter = new GlowFilter(15, 2, 1, 0xff9999, 0.5);
filter = new GlowFilter(1, 1, 1, 0xADD8E6, 0.5);
lineGfx.filters = [filter];
}
let i = 0;
const interval = setInterval(() => {
filter.distance = 10 * (Math.sin(i) + 2);
filter.outerStrength = 2 * (Math.sin(i) + 1);
filter.innerStrength = Math.sin(i) + 1;
i += 18;
if (i > 360) {
clearInterval(interval);
this.deleteLink(algorithm, linkData);
}
this.requestRender(algorithm);
}, 100);
}
// addCircle(i,delay){
// .append("circle")
// .classed("c",true)
// .attr("r",6)
// .attr("fill","orangered")
// .attr("transform","translate("+points.source.x+","+points.source.y+")");
// circle.transition()
// .ease("in")
// .delay(delay||0)
// .duration(Math.random()*500+1000)
// .attrTween("transform",function(d,i,a){
// var l = path.getTotalLength();
// return function(t){
// var p = path.getPointAtLength(t * l)
// return "translate("+ p.x+","+ p.y+")"
// }
// })
// .each("end",function(){
// d3.select(this).remove();
// addCircle(i,Math.random()*500);
// });
//
// }
/**
* 获得节点的颜色
* @param nodeData 节点
*/
color(nodeData): string {
return this.colorScale(nodeData.group);
}
/**
* 返回16进制的颜色
* @param color 颜色
*/
colorToNumber(color): number {
return parseInt(color.slice(1), 16);
}
/**
* 根据线条的起点、终点、宽度,计算生成方形区域所需的坐标偏移量
* @param x1 起点 X
* @param y1 起点 Y
* @param x2 终点 X
* @param y2 终点 Y
* @param width 区域宽度
*/
deltaXY(x1, y1, x2, y2, width) {
const widthDiv2 = width / 2;
if (x1 === x2) {
return [widthDiv2, 0];
} else {
const tanT = (y2 - y1) / (x2 - x1);
const sinT = Math.sin(Math.atan(tanT));
const cosT = Math.sqrt(1 - sinT * sinT);
return [widthDiv2 * sinT, widthDiv2 * cosT];
}
}
/**
* 删除边
* @param linkData 边
*/
deleteLink(algorithm, linkData) {
this.links[algorithm].delete(linkData);
const lineGfx = this.linkDataToLineGfx[algorithm].get(linkData);
const line = this.linkDataToLine[algorithm].get(linkData);
this.linkDataToLineGfx[algorithm].delete(linkData);
this.linkDataToLine[algorithm].delete(linkData);
this.lineGfxToLinkData[algorithm].delete(lineGfx);
this.lineToLinkData[algorithm].delete(line);
this.linksLayer[algorithm].removeChild(lineGfx);
}
refreshColor(algorithm, nodeData) {
const circle = this.nodeDataToCircle[algorithm].get(nodeData);
circle.clear();
const color = this.color(nodeData);
circle.beginFill(this.colorToNumber(color));
circle.drawCircle(circle.x, circle.y, this.NODE_RADIUS);
}
/**
* 渲染画布
*/
requestRender(algorithm) {
if (this.renderRequestId[algorithm]) {
return;
}
this.renderRequestId[algorithm] = window.requestAnimationFrame(() => {
this.app[algorithm].render();
this.renderRequestId[algorithm] = undefined;
});
}
/**
* 更新画布元素,并请求渲染画布
*/
update(algorithm) {
// 如果1:对于只在一个PIXI.Graphics中绘制线条:
// this.linksLayer.clear();
// this.linksLayer.alpha = 0.6;
// this.links.forEach(linkData => {
// this.linksLayer.lineStyle(Math.sqrt(linkData.value), 0x999999);
// this.linksLayer.moveTo(linkData.source.x, linkData.source.y);
// this.linksLayer.lineTo(linkData.target.x, linkData.target.y);
// });
// this.linksLayer.endFill();
// 如果2:对于每个线条创建一个PIXI.Graphics,并增加事件响应区域:
this.links[algorithm].forEach(linkData => {
const lineWidth = Math.sqrt(linkData.value);
const [deltaX, deltaY] = this.deltaXY(linkData.source.x, linkData.source.y, linkData.target.x, linkData.target.y, lineWidth);
const lineGfx = this.linkDataToLineGfx[algorithm].get(linkData);
lineGfx.hitArea = new PIXI.Polygon([
new PIXI.Point(linkData.source.x - deltaX, linkData.source.y + deltaY),
new PIXI.Point(linkData.target.x - deltaX, linkData.target.y + deltaY),
new PIXI.Point(linkData.target.x + deltaX, linkData.target.y - deltaY),
new PIXI.Point(linkData.source.x + deltaX, linkData.source.y - deltaY)
]);
const line = this.linkDataToLine[algorithm].get(linkData);
line.clear();
line.alpha = this.LINE_ALPHA;
line.lineStyle(lineWidth, 0x999999);
line.moveTo(linkData.source.x, linkData.source.y);
line.lineTo(linkData.target.x, linkData.target.y);
line.endFill();
});
this.nodes[algorithm].forEach(nodeData => {
const nodeGfx = this.nodeDataToNodeGfx[algorithm].get(nodeData);
const labelGfx = this.nodeDataToLabelGfx[algorithm].get(nodeData);
nodeGfx.position = new PIXI.Point(nodeData.x, nodeData.y);
labelGfx.position = new PIXI.Point(nodeData.x, nodeData.y);
});
this.requestRender(algorithm);
}
/**
* 鼠标悬停效果
* @param nodeData 节点
*/
hoverNodeStart(algorithm, nodeData) {
if (this.clickedNodeData[algorithm]) {
return;
}
if (this.hoveredNodeData[algorithm] === nodeData) {
return;
}
this.hoveredNodeData[algorithm] = nodeData;
const nodeGfx = this.nodeDataToNodeGfx[algorithm].get(nodeData);
const labelGfx = this.nodeDataToLabelGfx[algorithm].get(nodeData);
// 移动至顶层
this.nodesLayer[algorithm].removeChild(nodeGfx);
this.frontLayer[algorithm].addChild(nodeGfx);
this.labelsLayer[algorithm].removeChild(labelGfx);
this.frontLayer[algorithm].addChild(labelGfx);
// 鼠标悬停
this.hoveredNodeGfxOriginalChildren[algorithm] = [...nodeGfx.children];
this.hoveredLabelGfxOriginalChildren[algorithm] = [...labelGfx.children];
// 节点圆圈边界
const circleBorder = new PIXI.Graphics();
circleBorder.x = 0;
circleBorder.y = 0;
circleBorder.lineStyle(1.5, 0x000000);
circleBorder.drawCircle(0, 0, this.NODE_RADIUS);
nodeGfx.addChild(circleBorder);
// 标签 & 背景
const labelText = new PIXI.Text(this.LABEL_TEXT(nodeData), {
fontFamily: this.LABEL_FONT_FAMILY,
fontSize: this.LABEL_FONT_SIZE,
fill: 0x333333
});
labelText.x = 0;
labelText.y = this.NODE_HIT_RADIUS + this.LABEL_Y_PADDING;
labelText.anchor.set(0.5, 0);
const labelBackground = new PIXI.Sprite(PIXI.Texture.WHITE);
labelBackground.x = -(labelText.width + this.LABEL_X_PADDING * 2) / 2;
labelBackground.y = this.NODE_HIT_RADIUS;
labelBackground.width = labelText.width + this.LABEL_X_PADDING * 2;
labelBackground.height = labelText.height + this.LABEL_Y_PADDING * 2;
labelBackground.tint = 0xEEEEEE;
labelGfx.addChild(labelBackground);
labelGfx.addChild(labelText);
this.requestRender(algorithm);
}
/**
* 移除鼠标悬停效果
* @param nodeData 节点
*/
hoverNodeEnd(algorithm, nodeData) {
if (this.clickedNodeData[algorithm]) {
return;
}
if (this.hoveredNodeData[algorithm] !== nodeData) {
return;
}
this.hoveredNodeData[algorithm] = undefined;
const nodeGfx = this.nodeDataToNodeGfx[algorithm].get(nodeData);
const labelGfx = this.nodeDataToLabelGfx[algorithm].get(nodeData);
// move back from front layer
this.frontLayer[algorithm].removeChild(nodeGfx);
this.nodesLayer[algorithm].addChild(nodeGfx);
this.frontLayer[algorithm].removeChild(labelGfx);
this.labelsLayer[algorithm].addChild(labelGfx);
// clear hover effect
const nodeGfxChildren = [...nodeGfx.children];
for (const child of nodeGfxChildren) {
if (!this.hoveredNodeGfxOriginalChildren[algorithm].includes(child)) {
nodeGfx.removeChild(child);
}
}
this.hoveredNodeGfxOriginalChildren[algorithm] = undefined;
const labelGfxChildren = [...labelGfx.children];
for (const child of labelGfxChildren) {
if (!this.hoveredLabelGfxOriginalChildren[algorithm].includes(child)) {
labelGfx.removeChild(child);
}
}
this.hoveredLabelGfxOriginalChildren[algorithm] = undefined;
this.requestRender(algorithm);
}
/**
* 移动节点
* @param nodeData 节点
* @param point 位置
*/
moveNode(algorithm, nodeData, point) {
nodeData.x = point.x;
nodeData.y = point.y;
this.update(algorithm);
}
/**
* 鼠标移动
* @param event 事件
*/
appMouseMove(event) {
if (!this.clickedAlgorithm || !this.clickedNodeData[this.clickedAlgorithm]) {
return;
}
this.moveNode(this.clickedAlgorithm, this.clickedNodeData[this.clickedAlgorithm],
this.viewport[this.clickedAlgorithm].toWorld(event.data.global));
}
/**
* 节点点击效果
* @param nodeData 节点
*/
clickNodeStart(algorithm, nodeData) {
console.log(nodeData);
this.clickedAlgorithm = algorithm;
this.clickedNodeData[algorithm] = nodeData;
// 启动节点拖拽
this.app[algorithm].renderer.plugins.interaction.on('mousemove', this.appMouseMove, this);
// 禁用视窗拖拽
this.viewport[algorithm].pause = true;
}
/**
* 节点松开点击效果
*/
clickNodeEnd(algorithm) {
this.clickedAlgorithm = undefined;
this.clickedNodeData[algorithm] = undefined;
// 禁用节点拖拽
this.app[algorithm].renderer.plugins.interaction.off('mousemove', this.appMouseMove, this);
// 启用视窗拖拽
this.viewport[algorithm].pause = false;
}
/**
* 边点击效果
* @param linkData 边
*/
clickLineStart(algorithm, linkData) {
this.clickedLineData[algorithm] = linkData;
}
/**
* 边松开点击效果
*/
clickLineEnd(algorithm) {
this.clickedLineData[algorithm] = undefined;
this.update(algorithm);
}
}
| 39.843333 | 140 | 0.622082 |
855f2a21c44046a870d4affe2dbe40d29d356ab9 | 115 | rs | Rust | crates/ruma-client-api/src/to_device.rs | stoically/ruma | 713f20c852d2f34638fdaaf36253127997fefa6d | [
"MIT"
] | 1,549 | 2015-11-29T11:03:31.000Z | 2022-03-31T19:48:58.000Z | crates/ruma-client-api/src/to_device.rs | stoically/ruma | 713f20c852d2f34638fdaaf36253127997fefa6d | [
"MIT"
] | 966 | 2016-04-22T00:29:58.000Z | 2022-03-30T16:56:55.000Z | crates/ruma-client-api/src/to_device.rs | stoically/ruma | 713f20c852d2f34638fdaaf36253127997fefa6d | [
"MIT"
] | 162 | 2015-11-30T21:24:19.000Z | 2022-03-22T10:29:20.000Z | //! Endpoints for client devices to exchange information not persisted in room DAG.
pub mod send_event_to_device;
| 28.75 | 83 | 0.808696 |
fa6c74f7eb2ce7e508bd47fb8c86d00ae31a2135 | 1,273 | dart | Dart | lib/design_patterns/creational/prototype.dart | KhizhniakovM/flutter_cs | 2bffc77e7e136cc62564e4385ecb742b31bb6085 | [
"MIT"
] | 1 | 2021-04-16T18:56:27.000Z | 2021-04-16T18:56:27.000Z | lib/design_patterns/creational/prototype.dart | KhizhniakovM/flutter_cs | 2bffc77e7e136cc62564e4385ecb742b31bb6085 | [
"MIT"
] | null | null | null | lib/design_patterns/creational/prototype.dart | KhizhniakovM/flutter_cs | 2bffc77e7e136cc62564e4385ecb742b31bb6085 | [
"MIT"
] | null | null | null | // You can use it when you need to make a copy
// of the object with it special complicated state
// Prototype is a general interface
mixin Prototype<T> {
// MARK: - Methods
T clone();
}
// Immutable class
class Point {
// MARK: - Properties
final int x;
final int y;
// MARK: - Initializers
const Point(this.x, this.y);
}
// NOTE: - Implementation with extension methods
extension SuperPoint on Point {
Point clone() => Point(x, y);
}
// NOTE: - Implementation with mixin
// ```
// class SuperPoint extends Point with Prototype<SuperPoint> {
// // MARK: - Initializers
// SuperPoint(int x, int y) : super(x, y);
// // MARK: - Methods
// SuperPoint clone() => SuperPoint(x, y);
// }
// ```
// or we can add this methods directly in the main class
// ```
// class Point {
// // MARK: - Properties
// final int x;
// final int y;
// // MARK: - Initializers
// const Point(this.x, this.y);
// // MARK: - Methods
// Point clone() => Point(x, y);
// }
// ```
// or make cool initializer
// ```
// class Point {
// // MARK: - Properties
// late int x;
// late int y;
// // MARK: - Initializers
// Point(this.x, this.y);
// Point.clone(Point point) {
// this.x = point.x;
// this.y = point.y;
// }
// }
// ``` | 19.584615 | 62 | 0.585232 |
526c255d43cab3c5a6b689f6eb23f21adc3de0d4 | 775 | sql | SQL | dominio/tutela/queries/painel_personagens.sql | MinisterioPublicoRJ/api-cadg | a8998c4c234a65192f1dca8ea9a17a1d4a496556 | [
"MIT"
] | 6 | 2020-02-11T18:45:58.000Z | 2020-05-26T12:37:28.000Z | dominio/tutela/queries/painel_personagens.sql | MinisterioPublicoRJ/api-cadg | a8998c4c234a65192f1dca8ea9a17a1d4a496556 | [
"MIT"
] | 120 | 2019-07-01T14:45:32.000Z | 2022-01-25T19:10:16.000Z | dominio/tutela/queries/painel_personagens.sql | MinisterioPublicoRJ/apimpmapas | 196ad25a4922448b8ae7a66012a2843c7b7194ad | [
"MIT"
] | null | null | null | select
pr.PERS_DK,
ps.pess_dk,
ps.pess_nm_pessoa nome,
tpr.tppe_descricao papel,
ps.pess_in_tp_pessoa tipo_pessoa,
count(pr2.PERS_DK) as qtd
from
mcpr_personagem pr
left join mcpr_personagem pr2 on (
pr.pers_pess_dk = pr2.pers_pess_dk
and pr.PERS_DK <> pr2.PERS_DK
and (
pr2.pers_dt_fim is null
or sysdate < pr2.pers_dt_fim
))
JOIN mcpr_tp_personagem tpr ON pr.pers_tppe_dk = tpr.tppe_dk
JOIN mcpr_pessoa ps ON pr.pers_pess_dk = ps.pess_dk
where
pr.pers_docu_dk = :dk
and (
pr.pers_dt_fim is null
or sysdate < pr.pers_dt_fim
)
group by
pr.PERS_DK,
ps.pess_dk,
ps.pess_nm_pessoa,
ps.pess_in_tp_pessoa,
tpr.tppe_descricao
order by 3, 2 | 25 | 64 | 0.652903 |
e2e69dd556f85f24ffdcb1110f64e478096cdee6 | 1,463 | sql | SQL | trunk/sql/Tables/dbo.Activity.sql | tue65786/MedLog | 2ff87f0dcea581a6363c8955b9f73c787d0ba66d | [
"Apache-2.0"
] | 2 | 2016-09-10T16:29:48.000Z | 2016-09-19T19:25:14.000Z | trunk/sql/Tables/dbo.Activity.sql | tue65786/MedLogDB | 2ff87f0dcea581a6363c8955b9f73c787d0ba66d | [
"Apache-2.0"
] | 3 | 2016-10-09T17:57:48.000Z | 2016-12-11T01:59:40.000Z | trunk/sql/Tables/dbo.Activity.sql | tue65786/MedLog | 2ff87f0dcea581a6363c8955b9f73c787d0ba66d | [
"Apache-2.0"
] | null | null | null | SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[Activity] (
[ExerciseID] [int] IDENTITY(1, 1) NOT NULL,
[PatientID] [int] NOT NULL,
[ExerciseTypeID] [int] NOT NULL,
[Calories] [decimal](10, 2) NULL,
[Steps] [int] NULL,
[Distance] [decimal](10, 2) NULL,
[Floors] [int] NULL,
[Date] [date] NULL,
[start_time] [datetime] NULL,
[end_time] [time](7) NULL,
[minutes_peak_hr] [int] NULL,
[minutes_target_hr] [int] NULL,
[minutes_cardio_hr] [int] NULL,
[ActivityMetaData] [xml] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Activity]
ADD
CONSTRAINT [PK_Exercise]
PRIMARY KEY
CLUSTERED
([ExerciseID])
ON [PRIMARY]
GO
ALTER TABLE [dbo].[Activity]
WITH CHECK
ADD CONSTRAINT [FK_Activity_ActivityType1]
FOREIGN KEY ([ExerciseTypeID]) REFERENCES [dbo].[ActivityType] ([ActivityTypeID])
ON DELETE CASCADE
ALTER TABLE [dbo].[Activity]
CHECK CONSTRAINT [FK_Activity_ActivityType1]
GO
ALTER TABLE [dbo].[Activity]
WITH CHECK
ADD CONSTRAINT [FK_Activity_Patient]
FOREIGN KEY ([PatientID]) REFERENCES [dbo].[Patient] ([PatientID])
ON DELETE CASCADE
ALTER TABLE [dbo].[Activity]
CHECK CONSTRAINT [FK_Activity_Patient]
GO
ALTER TABLE [dbo].[Activity] SET (LOCK_ESCALATION = TABLE)
GO
| 29.26 | 83 | 0.626794 |
f06e460c939f7ca739d389122382d4b13d1f8d29 | 3,856 | py | Python | app.py | samstruthers35/sqlalchemy-challenge | 0022e7459fc59a7bee85489f8d264a8aee9c01c8 | [
"ADSL"
] | null | null | null | app.py | samstruthers35/sqlalchemy-challenge | 0022e7459fc59a7bee85489f8d264a8aee9c01c8 | [
"ADSL"
] | null | null | null | app.py | samstruthers35/sqlalchemy-challenge | 0022e7459fc59a7bee85489f8d264a8aee9c01c8 | [
"ADSL"
] | null | null | null | import datetime as dt
import numpy as np
import pandas as pd
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify, render_template
engine = create_engine('sqlite:///hawaii.sqlite')
Base = automap_base()
Base.prepare(engine, reflect=True)
Station = Base.classes.station
Measurement = Base.classes.measurement
session = Session(engine)
app = Flask(__name__)
@app.route("/")
def index():
return(
"Welcome to the Climate App!<br />"
"Available Routes:<br />"
"/api/v1.0/precipitation<br />"
"/api/v1.0/stations<br />"
"/api/v1.0/tobs<br />"
"/api/v1.0/<start> ENTER START DATE AT END OF URL <br /> "
"/api/v1.0/<start><end> ENTER START DATE/END DATE AT END OF URL<br />"
)
@app.route("/api/v1.0/precipitation")
def precipitation():
todays_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()
twelve_months = dt.date(2017, 8, 23) - dt.timedelta(days=365)
precipitation = session.query(Measurement.date, Measurement.prcp).\
filter(Measurement.date > twelve_months)
rain = []
for rains in precipitation:
row = {}
row["date"] = rains[0]
row["prcp"] = rains[1]
rain.append(row)
return jsonify(rain)
@app.route("/api/v1.0/stations")
def stations():
station_names = session.query(Station.station, Station.name).group_by(Station.station).all()
names_dict = []
for names in station_names:
row_names = {}
row_names["station name"] = names[0]
names_dict.append(row_names)
return jsonify(names_dict)
@app.route("/api/v1.0/tobs")
def tobs():
todays_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()
twelve_months = dt.date(2017, 8, 23) - dt.timedelta(days=365)
tobs_session = session.query(Measurement.date, Measurement.tobs).\
filter(Measurement.date > twelve_months)
temperature = []
for degrees in tobs_session:
row_tobs = {}
row_tobs["date"] = degrees[0]
row_tobs["tobs"] = degrees[1]
temperature.append(row_tobs)
return jsonify(temperature)
@app.route("/api/v1.0/<start>")
def starting(start):
start_date = dt.datetime.strptime(start, '%Y-%m-%d')
starting_date = session.query(func.max(Measurement.tobs),func.min(Measurement.tobs),func.avg(Measurement.tobs)).\
filter(Measurement.date >= start_date)
date_tobs = []
for tobs in starting_date:
tobs_json = {}
tobs_json["AVERAGE TEMPERATURE"] = tobs[2]
tobs_json["MAXIMUM TEMPERATURE"] = tobs[0]
tobs_json["MINIMUM TEMPERATURE"] = tobs[1]
date_tobs.append(tobs_json)
return jsonify(date_tobs)
@app.route("/api/v1.0/<start>/<end>")
def range(start,end):
start_range = dt.datetime.strptime(start, '%Y-%m-%d')
end_range = dt.datetime.strptime(end, '%Y-%m-%d')
date_range = session.query(func.max(Measurement.tobs),func.min(Measurement.tobs),func.avg(Measurement.tobs)).\
filter(Measurement.date >= start_range, Measurement.date <= end_range)
date_range_tobs = []
for tobs_range in date_range:
tobs_json_range = {}
tobs_json_range["AVERAGE TEMPERATURE"] = tobs_range[2]
tobs_json_range["MAXIMUM TEMPERATURE"] = tobs_range[0]
tobs_json_range["MINIMUM TEMPERATURE"] = tobs_range[1]
date_range_tobs.append(tobs_json_range)
return jsonify(date_range_tobs)
if __name__ == "__main__":
app.run(debug=True) | 33.824561 | 117 | 0.625778 |
169250865257bbb39beb12b4a1e262e7f413aff4 | 1,737 | ts | TypeScript | ModelViewerEditor/ClientApp/src/app/home/home.component.ts | museumsvictoria/model-viewer-editor | b16ba462979121f47a823a8c8352fc0ffd5eb760 | [
"Apache-2.0"
] | null | null | null | ModelViewerEditor/ClientApp/src/app/home/home.component.ts | museumsvictoria/model-viewer-editor | b16ba462979121f47a823a8c8352fc0ffd5eb760 | [
"Apache-2.0"
] | null | null | null | ModelViewerEditor/ClientApp/src/app/home/home.component.ts | museumsvictoria/model-viewer-editor | b16ba462979121f47a823a8c8352fc0ffd5eb760 | [
"Apache-2.0"
] | null | null | null | import {
AfterContentChecked,
AfterViewInit,
Component,
OnInit,
} from "@angular/core";
import { DataService } from "../shared/services/data.service";
import { ProjectModel } from "../shared/models/projectModel";
import { MatDialog } from "@angular/material/dialog";
import { NewProjectDialogComponent } from "../new-project-dialog/new-project-dialog.component";
import { first } from "rxjs/operators";
import { AppHeadingService } from "../shared/services/app-heading.service";
import { MatSelectionListChange } from "@angular/material/list";
import { Router } from "@angular/router";
@Component({
selector: "app-home",
templateUrl: "./home.component.html",
styleUrls: ["./home.component.scss"],
})
export class HomeComponent implements OnInit {
constructor(
private dataService: DataService,
private _router: Router,
private appHeadingService: AppHeadingService,
private dialog: MatDialog
) {}
projects: ProjectModel[];
ngOnInit() {
setTimeout(
() =>
this.appHeadingService.setBreadcrumbs([
{ routerLink: [], text: "Projects" },
]),
0
);
this.dataService
.getProjects()
.pipe(first())
.subscribe((x) => (this.projects = x));
}
on_SelectionChange($event: MatSelectionListChange) {
let id = $event.options[0].value;
this._router.navigate(["project", id]);
}
onNewProject_click() {
const dialogRef = this.dialog.open(NewProjectDialogComponent, {
height: "400px",
width: "600px",
});
dialogRef.afterClosed().subscribe((result) => {
this.dataService.getProjects().subscribe((x) => (this.projects = x));
});
}
ngAfterViewInit(): void {}
ngAfterContentChecked(): void {}
}
| 27.140625 | 95 | 0.663788 |
ad9b5a8f2ca694722dabcaba4e97f72f4edc70b6 | 700 | asm | Assembly | oeis/140/A140413.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/140/A140413.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/140/A140413.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A140413: a(2n) = A000045(6n) + 1, a(2n+1) = A000045(6n+3) - 1.
; Submitted by Jamie Morken(s4)
; 1,1,9,33,145,609,2585,10945,46369,196417,832041,3524577,14930353,63245985,267914297,1134903169,4807526977,20365011073,86267571273,365435296161,1548008755921,6557470319841,27777890035289,117669030460993,498454011879265,2111485077978049,8944394323791465,37889062373143905,160500643816367089,679891637638612257,2880067194370816121,12200160415121876737,51680708854858323073,218922995834555169025,927372692193078999177,3928413764606871165729,16641027750620563662097,70492524767089125814113
mov $1,1
lpb $0
sub $0,1
mov $2,$3
mul $3,4
add $3,$1
mov $1,$2
lpe
mov $0,$3
div $0,2
mul $0,4
add $0,1
| 41.176471 | 486 | 0.804286 |
48f2d70e598fe00f363cf8ea28245b6e64dbe2c3 | 758 | asm | Assembly | 1/1-2.asm | winderica/GoodbyeASM | 6836c0e954f6295e92b9f4619195238bb6ad2f7d | [
"MIT"
] | null | null | null | 1/1-2.asm | winderica/GoodbyeASM | 6836c0e954f6295e92b9f4619195238bb6ad2f7d | [
"MIT"
] | null | null | null | 1/1-2.asm | winderica/GoodbyeASM | 6836c0e954f6295e92b9f4619195238bb6ad2f7d | [
"MIT"
] | null | null | null | .386
STACK SEGMENT USE16 STACK
DB 200 DUP(0)
STACK ENDS
DATA SEGMENT USE16
BUF1 DB 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
BUF2 DB 10 DUP(0)
BUF3 DB 10 DUP(0)
BUF4 DB 10 DUP(0)
DATA ENDS
CODE SEGMENT USE16
ASSUME CS: CODE, DS: DATA, SS: STACK
START: MOV AX, DATA
MOV DS, AX
MOV SI, OFFSET BUF1
MOV DI, OFFSET BUF2
MOV BX, OFFSET BUF3
MOV BP, OFFSET BUF4
MOV CX, 10
LOPA: MOV AL, [SI]
MOV [DI], AL
INC AL
MOV [BX], AL
ADD AL, 3
MOV DS:[BP], AL
INC SI
INC DI
INC BP
INC BX
DEC CX
JNZ LOPA
MOV AH, 4CH
INT 21H
CODE ENDS
END START | 21.657143 | 45 | 0.468338 |
52d201213fafef2faeb4d6adc8021f676c2edd29 | 847 | kt | Kotlin | src/main/kotlin/com/tsarev/fiotcher/dflt/DefaultPublisherPool.kt | darkMechanicum/fiotcher | ca6ef9675a8b1088a0a7cc17ee472ad216b2caa5 | [
"MIT"
] | null | null | null | src/main/kotlin/com/tsarev/fiotcher/dflt/DefaultPublisherPool.kt | darkMechanicum/fiotcher | ca6ef9675a8b1088a0a7cc17ee472ad216b2caa5 | [
"MIT"
] | null | null | null | src/main/kotlin/com/tsarev/fiotcher/dflt/DefaultPublisherPool.kt | darkMechanicum/fiotcher | ca6ef9675a8b1088a0a7cc17ee472ad216b2caa5 | [
"MIT"
] | null | null | null | package com.tsarev.fiotcher.dflt
import com.tsarev.fiotcher.internal.pool.PublisherPool
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executor
import java.util.concurrent.SubmissionPublisher
/**
* Simple [SubmissionPublisher] grouping class.
*/
class DefaultPublisherPool<EventT : Any>(
private val executor: Executor,
private val maxCapacity: Int
) : PublisherPool<EventT> {
private val publishers = ConcurrentHashMap<String, SubmissionPublisher<EventT>>()
override fun getPublisher(key: String): SubmissionPublisher<EventT> {
return publishers.computeIfAbsent(key) { SubmissionPublisher<EventT>(executor, maxCapacity) }
}
override fun clear() {
val oldPublishers = publishers.toMap()
publishers.clear()
oldPublishers.values.forEach { it.close() }
}
} | 31.37037 | 101 | 0.744982 |
f57ffd4200e44c2cccdb60894d73f9c06b32562b | 1,868 | lua | Lua | libs/xmllib.lua | Seniru/pewpew | 56c4590637c5977949531a7eebd517ed076ab79b | [
"Apache-2.0"
] | 3 | 2020-09-25T06:35:39.000Z | 2021-02-18T14:46:43.000Z | libs/xmllib.lua | Seniru/pewpew | 56c4590637c5977949531a7eebd517ed076ab79b | [
"Apache-2.0"
] | 22 | 2020-09-12T10:22:13.000Z | 2021-12-11T12:33:51.000Z | libs/xmllib.lua | Seniru/pewpew | 56c4590637c5977949531a7eebd517ed076ab79b | [
"Apache-2.0"
] | 4 | 2020-09-25T06:35:41.000Z | 2021-07-25T08:52:25.000Z | --[[ Makinit's XML library ]]--
local a="Makinit's XML library"local b="[%a_:][%w%.%-_:]*"function parseXml(c,d)if not d then c=string.gsub(c,"<!%[CDATA%[(.-)%]%]>",xmlEscape)c=string.gsub(c,"<%?.-%?>","")c=string.gsub(c,"<!%-%-.-%-%->","")c=string.gsub(c,"<!.->","")end;local e={}local f={}local g=e;for h,i,j,k,l in string.gmatch(c,"<(/?)("..b..")(.-)(/?)>%s*([^<]*)%s*")do if h=="/"then local m=f[g]if m and i==g.name then g=m end else local n={name=i,attribute={}}table.insert(g,n)f[n]=g;if k~="/"then g=n end;for i,o in string.gmatch(j,"("..b..")%s*=%s*\"(.-)\"")do n.attribute[i]=d and o or xmlUnescape(o)end end;if l~=""then local n={text=d and l or xmlUnescape(l)}table.insert(g,n)f[n]=g end end;return e[1]end;function generateXml(g,d)if g.name then local c="<"..g.name;for i,o in pairs(g.attribute)do c=c.." "..i.."=\""..(d and tostring(o)or xmlEscape(tostring(o))).."\""end;if#g==0 then c=c.." />"else c=c..">"for p,n in ipairs(g)do c=c..generateXml(n,d)end;c=c.."</"..g.name..">"end;return c elseif g.text then return d and tostring(g.text)or xmlEscape(tostring(g.text))end end;function path(q,...)q={q}for p,i in ipairs(arg)do local r={}for p,s in ipairs(q)do for p,n in ipairs(s)do if n.name==i then table.insert(r,n)end end end;q=r end;return q end;local t={}function xmlEscape(u)local v=t[u]if not v then local w=string.gsub;v=w(u,"&","&")v=w(v,"\"",""")v=w(v,"'","'")v=w(v,"<","<")v=w(v,">",">")t[u]=v end;return v end;local x={}function xmlUnescape(u)local v=x[u]if not v then local w=string.gsub;v=w(u,""","\"")v=w(v,"'","'")v=w(v,"<","<")v=w(v,">",">")v=w(v,"&#(%d%d?%d?%d?);",dec2char)v=w(v,"&#x(%x%x?%x?%x?);",hex2char)v=w(v,"&","&")x[u]=v end;return v end;function dec2char(y)y=tonumber(y)return string.char(y>255 and 0 or y)end;function hex2char(y)y=tonumber(y,16)return string.char(y>255 and 0 or y)end
| 622.666667 | 1,835 | 0.603854 |
599be28852a192a48ec845c8ebf10429fa2a317d | 61 | sql | SQL | migrations/1540809497_fix_item_default_season.up.sql | tanel/wardrobe-organizer | b49271d22b73446c5a4e5b383be290b2a0192700 | [
"MIT"
] | 3 | 2019-03-27T12:25:42.000Z | 2021-12-24T23:41:03.000Z | migrations/1540809497_fix_item_default_season.up.sql | tanel/wardrobe-manager-app | b49271d22b73446c5a4e5b383be290b2a0192700 | [
"MIT"
] | 53 | 2017-12-09T00:21:26.000Z | 2018-03-02T22:29:33.000Z | migrations/1540809497_fix_item_default_season.up.sql | tanel/wardrobe-manager-app | b49271d22b73446c5a4e5b383be290b2a0192700 | [
"MIT"
] | null | null | null | ALTER TABLE items ALTER COLUMN season SET DEFAULT 'all-year'; | 61 | 61 | 0.803279 |
6e42508b36aaa3d436dcd66632c0b294d9d8d80f | 65 | sql | SQL | db/sql/10-6-select.sql | Terfno/mysql-onDocker | d3f1847f6635fe4a465fb637d824aad2ddd7a66a | [
"MIT"
] | null | null | null | db/sql/10-6-select.sql | Terfno/mysql-onDocker | d3f1847f6635fe4a465fb637d824aad2ddd7a66a | [
"MIT"
] | null | null | null | db/sql/10-6-select.sql | Terfno/mysql-onDocker | d3f1847f6635fe4a465fb637d824aad2ddd7a66a | [
"MIT"
] | null | null | null | select 名前 from ken2015 where 名前 not in (select 都道府県 from kosen);
| 32.5 | 64 | 0.769231 |
9081aadb4c6b5769978ce82042dcee67043cc4c7 | 11,329 | py | Python | processor/local_process_unit.py | cyber00rn/ICTD | ace5122fdc9ff77c064549c59905233ee0589027 | [
"MIT"
] | null | null | null | processor/local_process_unit.py | cyber00rn/ICTD | ace5122fdc9ff77c064549c59905233ee0589027 | [
"MIT"
] | null | null | null | processor/local_process_unit.py | cyber00rn/ICTD | ace5122fdc9ff77c064549c59905233ee0589027 | [
"MIT"
] | null | null | null | import dpkt
from multiprocessing import Queue
import socket
from dpkt.compat import compat_ord
from utils.print_log import Printer
import logging
import hashlib
class LocalProcessUnit():
"""Queue size"""
QUEUE_SIZE = 20000
alive = True
def __init__(self, db_queue: Queue, queue_size=QUEUE_SIZE):
self.dbq = db_queue
self.lpu = Queue(queue_size)
self.printer = Printer()
def mac_addr(self, address):
"""Convert a MAC address to a readable/printable string
Args:
address (str): a MAC address in hex form (e.g. '\x01\x02\x03\x04\x05\x06')
Returns:
str: Printable/readable MAC address
"""
return ':'.join('%02x' % compat_ord(b) for b in address)
def parse_packet(self, timestamp, pkt):
eth=dpkt.ethernet.Ethernet(pkt)
res = {}
if eth.type == dpkt.ethernet.ETH_TYPE_IP:
res = self.parse_ipv4(eth.data)
res['packet_type'] = 'ipv4'
res['eth_data_len'] = eth.data.len
elif eth.type == dpkt.ethernet.ETH_TYPE_IP6:
res = self.parse_ipv6(eth.data)
res['packet_type'] = 'ipv6'
elif eth.type == dpkt.ethernet.ETH_TYPE_ARP:
# address resolution protocol
res = self.parse_arp(eth.data)
res['packet_type'] = 'arp'
elif eth.type == dpkt.ethernet.ETH_TYPE_REVARP:
# reverse addr resolution protocol
res['packet_type'] = 'revarp'
elif eth.type == dpkt.ethernet.ETH_TYPE_PPPoE:
res['packet_type'] = 'PPPoE'
elif eth.type == dpkt.ethernet.ETH_TYPE_EDP:
# Extreme Networks Discovery Protocol
res['packet_type'] = 'EDP'
elif eth.type == dpkt.ethernet.ETH_TYPE_PUP:
# PUP protocol
res['packet_type'] = 'PUP'
elif eth.type == dpkt.ethernet.ETH_TYPE_AOE:
# AoE protocol
res['packet_type'] = 'AoE'
elif eth.type == dpkt.ethernet.ETH_TYPE_CDP:
# Cisco Discovery Protocol
res['packet_type'] = 'CDP'
elif eth.type == dpkt.ethernet.ETH_TYPE_DTP:
# Cisco Dynamic Trunking Protocol
res['packet_type'] = 'DTP'
elif eth.type == dpkt.ethernet.ETH_TYPE_8021Q:
# IEEE 802.1Q VLAN tagging
res['packet_type'] = '802.1Q'
elif eth.type == dpkt.ethernet.ETH_TYPE_8021AD:
# IEEE 802.1ad
res['packet_type'] = '802.1ad'
elif eth.type == dpkt.ethernet.ETH_TYPE_QINQ1:
# Legacy QinQ
res['packet_type'] = 'QinQ1'
elif eth.type == dpkt.ethernet.ETH_TYPE_QINQ2:
# Legacy QinQ
res['packet_type'] = 'QinQ2'
elif eth.type == dpkt.ethernet.ETH_TYPE_IPX:
res['packet_type'] = 'IPX'
elif eth.type == dpkt.ethernet.ETH_TYPE_PPP:
res['packet_type'] = 'PPP'
elif eth.type == dpkt.ethernet.ETH_TYPE_MPLS:
res['packet_type'] = 'MPLS'
elif eth.type == dpkt.ethernet.ETH_TYPE_MPLS_MCAST:
res['packet_type'] = 'MPLS_MCAST'
elif eth.type == dpkt.ethernet.ETH_TYPE_PPPoE_DISC:
res['packet_type'] = 'PPPoE_DISC'
elif eth.type == dpkt.ethernet.ETH_TYPE_LLDP:
# Link Layer Discovery Protocol
res['packet_type'] = 'LLDP'
elif eth.type == dpkt.ethernet.ETH_TYPE_TEB:
res['packet_type'] = 'TEB'
else:
res['packet_type'] = 'Unkown'
if res.get('src_mac') == None:
res['src_mac'] = self.mac_addr(eth.src)
if res.get('dst_mac') == None:
res['dst_mac'] = self.mac_addr(eth.dst)
sql = "INSERT INTO aidata2 (time, packet_type, protocol, src_mac, src_ip, src_port, dst_mac, dst_ip, dest_port, tcp_flags, size, \"offset\", ttl) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);"
sql_val = (timestamp, res.get('packet_type'), res.get('protocol'), res.get('src_mac'), res.get('src_ip'), res.get('src_port'), res.get('dst_mac'), res.get('dst_ip'), res.get('dest_port'), res.get('tcp_flags'), res.get('len'), res.get('offset'), res.get('ttl'))
debug_val = (str(timestamp), res.get('packet_type', ""), res.get('protocol', ""), res.get('src_mac', ""), res.get('src_ip', ""), str(res.get('src_port', "")), res.get('dst_mac', ""), res.get('dst_ip', ""), str(res.get('dest_port', "")), res.get('tcp_flags', ""), str(res.get('len', "")), str(res.get('offset', "")), str(res.get('ttl', "")))
self.dbq.put({'sql': sql, 'sql_val': sql_val, 'debug_val': debug_val})
m = hashlib.sha256()
data = res.get('src_mac', "") + '+' + str(timestamp)
m.update(data.encode("utf-8"))
hashed = m.hexdigest()
sql = "INSERT INTO event (flow_id, src_ip, dest_ip, timestamp, protocol) VALUES (%s, %s, %s, %s, %s);"
sql_val = (hashed, res.get('src_ip'), res.get('dst_ip'), timestamp, res.get('protocol'))
debug_val = (hashed, res.get('src_ip', ""), res.get('dst_ip', ""), str(timestamp), res.get('protocol', ""))
self.dbq.put({'sql': sql, 'sql_val': sql_val, 'debug_val': debug_val})
sql = "INSERT INTO event_detail (flow_id, packet_type, src_mac, src_port, dest_mac, dest_port, tcp_flag, size, \"offset\", ttl) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);"
sql_val = (hashed, res.get('packet_type'), res.get('src_mac'), res.get('src_port'), res.get('dst_mac'), res.get('dest_port'), res.get('tcp_flags'), res.get('len'), res.get('offset'), res.get('ttl'))
debug_val = (hashed, res.get('packet_type', ""), res.get('src_mac', ""), str(res.get('src_port', "")), res.get('dst_mac', ""), str(res.get('dest_port', "")), res.get('tcp_flags', ""), str(res.get('len', "")), str(res.get('offset', "")), str(res.get('ttl', "")))
self.dbq.put({'sql': sql, 'sql_val': sql_val, 'debug_val': debug_val})
if res.get('protocol', "") == 'TCP':
sql = "INSERT INTO tcp_event_detail (flow_id, ack, len, windows_size, hdr_len, checksum) VALUES (%s, %s, %s, %s, %s, %s);"
sql_val = (hashed, res.get('tcp_ack'), res.get('tcp_len'), res.get('tcp_window_size'), res.get('tcp_hdr_len'), res.get('tcp_checksum'))
debug_val = (hashed, str(res.get('tcp_ack', "")), str(res.get('tcp_len', "")), str(res.get('tcp_window_size', "")), str(res.get('tcp_hdr_len', "")), str(res.get('tcp_checksum', "")))
self.dbq.put({'sql': sql, 'sql_val': sql_val, 'debug_val': debug_val})
if res.get('src_port') == 502 or res.get('dest_port') == 502:
sql = "INSERT INTO tcp_data (flow_id, ics_protocol_type, content) VALUES (%s, %s, %s);"
sql_val = (hashed, 'modbus', res.get('tcp_content'))
debug_val = (hashed, 'modbus', str(res.get('tcp_content', "")))
self.dbq.put({'sql': sql, 'sql_val': sql_val, 'debug_val': debug_val})
elif res.get('src_port') == 44818 or res.get('dest_port') == 44818:
sql = "INSERT INTO tcp_data (flow_id, ics_protocol_type, content) VALUES (%s, %s, %s);"
sql_val = (hashed, 'EtherNet/IP', res.get('tcp_content'))
debug_val = (hashed, 'EtherNet/IP', str(res.get('tcp_content', "")))
self.dbq.put({'sql': sql, 'sql_val': sql_val, 'debug_val': debug_val})
def get_packet(self):
while self.alive:
pkt = self.lpu.get()
self.parse_packet(pkt.get('packet_time'), pkt.get('raw_data'))
def parse_ipv4(self, ipv4):
res = {}
res['len'] = ipv4.len
res['offset'] = ipv4.offset
res['ttl'] = ipv4.ttl
res['src_ip'] = socket.inet_ntoa(ipv4.src)
res['dst_ip'] = socket.inet_ntoa(ipv4.dst)
src_port = ''
dest_port = ''
tcp_flags = ''
protocol = ''
if ipv4.p==dpkt.ip.IP_PROTO_TCP:
res['protocol'] = 'TCP'
tcp = ipv4.data
res['tcp_flags'] = "{0:b}".format(tcp.flags)
try:
res['src_port'] = tcp.sport
res['dest_port'] = tcp.dport
except Exception as e:
self.printer.error("Occur error " + str(e))
res['tcp_hdr_len'] = tcp.__hdr_len__
res['tcp_window_size'] = tcp.win
res['tcp_ack'] = tcp.ack
res['tcp_checksum'] = tcp.sum
res['tcp_len'] = ipv4.len
if tcp.sport == 502 or tcp.dport == 502 or tcp.sport == 44818 or tcp.dport == 44818:
res['tcp_content'] = tcp.data
elif ipv4.p==dpkt.ip.IP_PROTO_UDP:
res['protocol'] = 'UDP'
udp = ipv4.data
try:
res['src_port'] = udp.sport
res['dest_port'] = udp.dport
except Exception as e:
self.printer.error("Occur error " + str(e))
elif ipv4.p==dpkt.ip.IP_PROTO_IGMP:
res['protocol'] = 'IGMP'
igmp = ipv4.data
elif ipv4.p==dpkt.ip.IP_PROTO_ICMP:
res['protocol'] = 'ICMP'
icmp = ipv4.data
return res
def parse_ipv6(self, ipv6):
res = {}
self.printer.debug('parse ipv6:', ipv6)
res['len'] = ipv6.plen
res['src_ip'] = socket.inet_ntop(socket.AF_INET6, ipv6.src)
res['dst_ip'] = socket.inet_ntop(socket.AF_INET6, ipv6.dst)
if ipv6.nxt==dpkt.ip.IP_PROTO_TCP:
res['protocol'] = 'TCP'
tcp = ipv6.data
res['tcp_flags'] = "{0:b}".format(tcp.flags)
res['src_port'] = tcp.sport
res['dest_port'] = tcp.dport
elif ipv6.nxt==dpkt.ip.IP_PROTO_UDP:
res['protocol'] = 'UDP'
udp = ipv6.data
res['src_port'] = udp.sport
res['dest_port'] = udp.dport
elif ipv6.nxt==dpkt.ip.IP_PROTO_ICMP6:
res['protocol'] = 'ICMPv6'
icmp6 = ipv6.data
elif ipv6.nxt==dpkt.ip.IP_PROTO_SCTP:
res['protocol'] = 'SCTP'
sctp = ipv6.data
elif ipv6.nxt==dpkt.ip.IP_PROTO_HOPOPTS:
res['protocol'] = 'HOPOPT'
hop = ipv6.data
else:
res['protocol'] = 'SomethingWrong:'+str(ipv6.nxt)
other = ipv6.data
return res
def parse_arp(self, arp):
res = {}
self.printer.debug('parse arp:', arp)
self.printer.debug('arp.__hdr__: ', arp.__hdr__)
self.printer.debug('arp.hrd: ', arp.hrd)
self.printer.debug('arp.pro: ', arp.pro)
self.printer.debug('arp.hln: ', arp.hln)
self.printer.debug('arp.pln: ', arp.pln)
self.printer.debug('arp.op: ', arp.op)
self.printer.debug('arp.sha: ', arp.sha, 'conv: ', self.mac_addr(arp.sha))
self.printer.debug('arp.spa: ', arp.spa, 'conv: ', socket.inet_ntoa(arp.spa))
self.printer.debug('arp.tha: ', arp.tha, 'conv: ', self.mac_addr(arp.tha))
self.printer.debug('arp.tpa: ', arp.tpa, 'conv: ', socket.inet_ntoa(arp.tpa))
res['src_mac'] = self.mac_addr(arp.sha)
res['dst_mac'] = self.mac_addr(arp.tha)
res['src_ip'] = socket.inet_ntoa(arp.spa)
res['dst_ip'] = socket.inet_ntoa(arp.tpa)
return res
def exit(self):
self.alive = False | 44.081712 | 348 | 0.557596 |
6cbdf493b2cd2382466e5a96817da5da7f6295eb | 893 | go | Go | collections/comparers.go | ah-its-andy/downton | 5f555b69042cc0c1f24fb1f6a77145658843395f | [
"Apache-2.0"
] | null | null | null | collections/comparers.go | ah-its-andy/downton | 5f555b69042cc0c1f24fb1f6a77145658843395f | [
"Apache-2.0"
] | null | null | null | collections/comparers.go | ah-its-andy/downton | 5f555b69042cc0c1f24fb1f6a77145658843395f | [
"Apache-2.0"
] | null | null | null | package collections
import (
"reflect"
"strings"
)
var StringComparison BinarySearchComparer = func(a, b any) int {
return strings.Compare(a.(string), b.(string))
}
var IntComparison BinarySearchComparer = func(a, b any) int {
v := int(a.(int64) - b.(int64))
if v == 0 {
return 0
} else if v < 0 {
return -1
} else {
return 1
}
}
var FloatComparison BinarySearchComparer = func(a, b any) int {
v := a.(float64) - b.(float64)
if v == 0 {
return 0
} else if v < 0 {
return -1
} else {
return 1
}
}
var PtrComparison BinarySearchComparer = func(a, b any) int {
t := reflect.TypeOf(a)
if t.Kind() == reflect.Ptr {
if a == b {
return 0
} else {
return 1
}
} else {
if &a == &b {
return 0
} else {
return 1
}
}
}
var BoolComparison BinarySearchComparer = func(a, b any) int {
if a.(bool) == b.(bool) {
return 0
} else {
return 1
}
}
| 15.396552 | 64 | 0.599104 |
af6c0516bb0b4b5fd3c31d5c419c8b65ed902cb1 | 552 | rb | Ruby | posts/convert_tmbl.rb | dictav/dictav.github.com.bak | fff722d333979e021513892f0506be230d1ae033 | [
"MIT"
] | null | null | null | posts/convert_tmbl.rb | dictav/dictav.github.com.bak | fff722d333979e021513892f0506be230d1ae033 | [
"MIT"
] | null | null | null | posts/convert_tmbl.rb | dictav/dictav.github.com.bak | fff722d333979e021513892f0506be230d1ae033 | [
"MIT"
] | null | null | null | #! /usr/bin/env ruby
# coding:utf-8
require 'json'
list = []
Dir['tumblr_files/*'].each{|file|
list.push *JSON.parse(File.read file)
}
puts list.size
format = <<FORMAT
---
layout: post
title: %{title}
date: %{date}
categories: %{tags}
---
%{body}
FORMAT
list.each do |a|
if a['title'].empty?
a['title'] = a['body'][0,8]
end
if a['tags']
a['tags'] = a['tags'].join ' '
end
f_name = "#{a['date'][0,10]}-#{a['title'].gsub(/\s/,'+')}.markdown"
File.open(f_name,'w'){|f| f.write( format % Hash[a.map{|(k,v)| [k.to_sym,v]}] ) }
end
| 17.806452 | 84 | 0.565217 |
8eff5e25a242304231ac7fc3228b75bd0525605d | 6,391 | kt | Kotlin | bokehlib/src/main/java/link/k3n/bokeh/BokehLayout.kt | k3nsuk3/Bokeh | 587c75eabf94bf99b26918a3549982266f2306b8 | [
"MIT"
] | null | null | null | bokehlib/src/main/java/link/k3n/bokeh/BokehLayout.kt | k3nsuk3/Bokeh | 587c75eabf94bf99b26918a3549982266f2306b8 | [
"MIT"
] | null | null | null | bokehlib/src/main/java/link/k3n/bokeh/BokehLayout.kt | k3nsuk3/Bokeh | 587c75eabf94bf99b26918a3549982266f2306b8 | [
"MIT"
] | null | null | null | package link.k3n.bokeh
import android.animation.Animator
import android.animation.TimeInterpolator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.view.animation.LinearInterpolator
import android.widget.RelativeLayout
import java.util.*
/**
* Created by k3nsuk3 on 2017/07/29.
*/
class BokehLayout : RelativeLayout {
companion object {
val INTERP_LINEAR = 0
val INTERP_ACCELERATE = 1
val INTERP_DECELERATE = 2
val INTERP_ACCELERATE_DECELERATE = 3
val DEFAULT_COUNT = 20
val DEFAULT_COLOR = Color.argb(150, 100, 100, 100)
val DEFAULT_DURATION: Long = 100000
val DEFAULT_INTERPOLATOR = INTERP_LINEAR
private fun createInterpolator(type: Int): TimeInterpolator {
when(type) {
INTERP_ACCELERATE -> return AccelerateInterpolator()
INTERP_DECELERATE -> return DecelerateInterpolator()
INTERP_ACCELERATE_DECELERATE -> return AccelerateDecelerateInterpolator()
else -> return LinearInterpolator()
}
}
}
private var mCount = DEFAULT_COUNT
private var mDuration = DEFAULT_DURATION
private var mColor = DEFAULT_COLOR
private var mInterpolator = DEFAULT_INTERPOLATOR
private val mBokehList: MutableList<BokehView> = mutableListOf()
private var mIsStarted = false
private var mCenterX = 0f
private var mCenterY = 0f
private var mRadius = 0f
private val mPaint = Paint()
private val mRandom = Random()
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
// Create Paint
mPaint.isAntiAlias = true
mPaint.style = Paint.Style.FILL
mPaint.color = mColor
build()
}
@Synchronized fun start() {
if (mIsStarted) return
if (mBokehList.size <= 0) build()
for (i in mBokehList.indices) {
val delay = i * mDuration / mCount
mBokehList[i].animate().setStartDelay(delay).start()
}
}
@Synchronized fun stop() {
if (mBokehList.size <= 0 || !mIsStarted) return
mBokehList.forEach { it.animate().cancel() }
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val width = MeasureSpec.getSize(widthMeasureSpec) - paddingLeft - paddingRight
val height = MeasureSpec.getSize(heightMeasureSpec) - paddingTop - paddingBottom
mCenterX = width * 0.5f
mCenterY = height * 0.5f
mRadius = Math.min(width, height) * 0.5f
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
private fun clear() {
stop()
mBokehList.forEach { removeView(it) }
mBokehList.clear()
}
private fun build() {
val layoutParams = LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT
)
for (i in 1..mCount) {
// Setup View
val bokehView = BokehView(context)
bokehView.scaleX = bokehView.mScale
bokehView.scaleY = bokehView.mScale
bokehView.x = mRandom.nextFloat() * 500f * (if(mRandom.nextBoolean()) 1 else -1)
bokehView.y = mRandom.nextFloat() * 500f * (if(mRandom.nextBoolean()) 1 else -1)
bokehView.alpha = 0f
addView(bokehView, 0, layoutParams)
val delay = i * mDuration / mCount
val animator = bokehView.animate()
animator.startDelay = delay
animator.x(mRandom.nextFloat() * 500f * (if(mRandom.nextBoolean()) 1 else -1))
animator.y(mRandom.nextFloat() * 500f * (if(mRandom.nextBoolean()) 1 else -1))
animator.alpha(mRandom.nextFloat())
animator.duration = mDuration
animator.interpolator = createInterpolator(mInterpolator)
animator.setListener(mAnimatorListener)
mBokehList.add(bokehView)
}
}
private fun reset() {
clear()
build()
if (mIsStarted) start()
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
mBokehList.forEach { it.animate().cancel() }
}
inner class BokehView(context: Context) : View(context) {
var mScale: Float = 0.5f
init {
mScale = mRandom.nextFloat() * 0.5f
}
override fun onDraw(canvas: Canvas?) {
canvas?.drawCircle(mCenterX, mCenterY, mRadius, mPaint)
}
}
private val mAnimatorListener = object: Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator?) {
Log.e("Bokeh", "onAnimationStart")
mIsStarted = true
}
override fun onAnimationEnd(animation: Animator?) {
Log.e("Bokeh", "onAnimationEnd")
if (mBokehList.size <= 0) return
val bokehView = mBokehList.removeAt(0)
//TODO: Bokeh が画面外に移動した際の処理を記述
val topEdge = top + paddingTop
val leftEdge = left + paddingLeft
val rightEdge = right - paddingRight
val bottomEdge = bottom - paddingBottom
val animator = bokehView.animate()
animator.x(mRandom.nextFloat() * 500f * (if(mRandom.nextBoolean()) 1 else -1))
animator.y(mRandom.nextFloat() * 500f * (if(mRandom.nextBoolean()) 1 else -1))
animator.alpha(mRandom.nextFloat())
animator.duration = mDuration
animator.interpolator = createInterpolator(mInterpolator)
animator.setListener(this)
mBokehList.add(bokehView)
animator.start()
}
override fun onAnimationCancel(animation: Animator?) {
mIsStarted = false
}
override fun onAnimationRepeat(animation: Animator?) {
mIsStarted = false
}
}
}
| 31.328431 | 114 | 0.629166 |
cf99371dcc2f69d7746d492e32b57d74af01733e | 1,236 | css | CSS | css/colorfightforcancer.css | ColorFightForCancer/ColorFightForCancer.github.io | 7108a9206f40a67adece71657abbc54dcbdbe0ca | [
"MIT"
] | null | null | null | css/colorfightforcancer.css | ColorFightForCancer/ColorFightForCancer.github.io | 7108a9206f40a67adece71657abbc54dcbdbe0ca | [
"MIT"
] | null | null | null | css/colorfightforcancer.css | ColorFightForCancer/ColorFightForCancer.github.io | 7108a9206f40a67adece71657abbc54dcbdbe0ca | [
"MIT"
] | null | null | null | /*!
* Start Bootstrap - The Big Picture (http://startbootstrap.com/)
* Copyright 2013-2016 Start Bootstrap
* Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE)
*/
body {
margin-top: 50px;
margin-bottom: 50px;
background: none;
}
/*.full {
background: url(/images/ColorForCancer2.png) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}*/
.buttonrow {
margin-bottom:10px;
}
.embed-responsive-4by3 {
padding-bottom: 60%;
}
video#bgvid {
position: fixed;
top: 50%;
left: 50%;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -100;
-ms-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
@media screen and (max-device-width: 800px) {
#bgvid {
display: none;
}
#bgvidDiv {
display: none;
}
}
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
// Usage as a mixin
.element {
.center-block();
}
| 19.619048 | 96 | 0.642395 |
56debb94020ae174c84a4e31d5317ac98e4f2607 | 259 | tsx | TypeScript | src/TestComponent/TestComponent.stories.tsx | bitcreative-studios/proped-up | 0af08a68c6e1f49a5f6f8e77d6438c54085d0d73 | [
"MIT"
] | null | null | null | src/TestComponent/TestComponent.stories.tsx | bitcreative-studios/proped-up | 0af08a68c6e1f49a5f6f8e77d6438c54085d0d73 | [
"MIT"
] | null | null | null | src/TestComponent/TestComponent.stories.tsx | bitcreative-studios/proped-up | 0af08a68c6e1f49a5f6f8e77d6438c54085d0d73 | [
"MIT"
] | null | null | null | import React from 'react'
import TestComponent from './TestComponent'
export default {
title: 'TestComponent',
}
export const Primary = () => <TestComponent text="primary" />
export const Secondary = () => <TestComponent text="secondary" color="#333" />
| 23.545455 | 78 | 0.706564 |
e98ebab44a169ff6db0e0b733cdd46bddd38d770 | 3,393 | lua | Lua | packages/soundstreamer/soundstreamer_s.lua | AliLogic/orp-game | 28c4b07ca1382455dadb4860d61feefe508cd1ce | [
"BSD-2-Clause"
] | 4 | 2020-07-09T13:14:36.000Z | 2021-05-05T17:50:31.000Z | packages/soundstreamer/soundstreamer_s.lua | AliLogic/orp-game | 28c4b07ca1382455dadb4860d61feefe508cd1ce | [
"BSD-2-Clause"
] | null | null | null | packages/soundstreamer/soundstreamer_s.lua | AliLogic/orp-game | 28c4b07ca1382455dadb4860d61feefe508cd1ce | [
"BSD-2-Clause"
] | null | null | null | --[[
Copyright (C) 2020 Blue Mountains GmbH
This program is free software: you can redistribute it and/or modify it under the terms of the Onset
Open Source License as published by Blue Mountains GmbH.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the Onset Open Source License for more details.
You should have received a copy of the Onset Open Source License along with this program. If not,
see https://bluemountains.io/Onset_OpenSourceSoftware_License.txt
]]--
local StreamedSounds = { }
AddEvent("OnPackageStop", function()
for k, v in pairs(StreamedSounds) do
DestroyObject(k)
end
StreamedSounds = nil
end)
AddFunctionExport("CreateSound3D", function (sound_file, x, y, z, radius, volume, pitch)
radius = radius or 2500.0
volume = volume or 1.0
pitch = pitch or 1.0
-- Create a dummy object that will help us streaming the sound
local object = CreateObject(1, x, y, z)
SetObjectPropertyValue(object, "_soundStream", sound_file)
SetObjectPropertyValue(object, "_soundStreamRadius", radius)
SetObjectPropertyValue(object, "_soundStreamVolume", volume)
SetObjectPropertyValue(object, "_soundStreamPitch", pitch)
SetObjectStreamDistance(object, radius)
StreamedSounds[object] = { }
StreamedSounds[object].sound_file = sound_file
StreamedSounds[object].radius = radius
StreamedSounds[object].volume = volume
StreamedSounds[object].pitch = pitch
return object
end)
AddFunctionExport("DestroySound3D", function (object)
if StreamedSounds[object] == nil then
return false
end
StreamedSounds[object] = nil
return DestroyObject(object)
end)
AddFunctionExport("IsValidSound3D", function (object)
return StreamedSounds[object] ~= nil
end)
AddFunctionExport("SetSound3DVolume", function (object, volume)
volume = volume or 1.0
if StreamedSounds[object] == nil then
return false
end
SetObjectPropertyValue(object, "_soundStreamVolume", volume)
return true
end)
AddFunctionExport("SetSound3DPitch", function (object, pitch)
pitch = pitch or 1.0
if StreamedSounds[object] == nil then
return false
end
SetObjectPropertyValue(object, "_soundStreamPitch", pitch)
return true
end)
AddFunctionExport("SetSound3DDimension", function (object, dimension)
if StreamedSounds[object] == nil then
return false
end
SetObjectDimension(object, dimension)
return true
end)
AddFunctionExport("GetSound3DDimension", function (object)
if StreamedSounds[object] == nil then
return false
end
return GetObjectDimension(object)
end)
AddFunctionExport("SetSound3DLocation", function (object, x, y, z)
if StreamedSounds[object] == nil then
return false
end
-- We need to notify the client about the loction change with a remote event.
-- Because SetObjectLocation does not trigger a stream event on the client if the location is within the stream radius.
for _, v in pairs(GetAllPlayers()) do
if IsObjectStreamedIn(v, object) then
CallRemoteEvent(v, "SetStreamedSound3DLocation", object, x, y, z)
end
end
-- Will trigger client stream in/out events if necessary
SetObjectLocation(object, x, y, z)
return true
end)
AddFunctionExport("GetSound3DLocation", function (object)
if StreamedSounds[object] == nil then
return false
end
local x, y, z = GetObjectLocation(object)
return x, y, z
end) | 28.041322 | 120 | 0.773062 |
04b8aa9b73dcd6a64055a2326c4f44577b9efa07 | 1,633 | html | HTML | start.html | Humbedooh/modlua.org | 05f3702f22522c938ce2ba35b1232e145179a720 | [
"Apache-2.0"
] | 9 | 2015-10-07T15:15:02.000Z | 2021-06-07T18:02:53.000Z | start.html | Humbedooh/modlua.org | 05f3702f22522c938ce2ba35b1232e145179a720 | [
"Apache-2.0"
] | 3 | 2015-01-18T20:29:24.000Z | 2017-02-14T12:03:24.000Z | start.html | Humbedooh/modlua.org | 05f3702f22522c938ce2ba35b1232e145179a720 | [
"Apache-2.0"
] | 1 | 2019-10-10T02:56:40.000Z | 2019-10-10T02:56:40.000Z | Welcome!
<h2>Welcome to modlua.org</h2>
<p>
This site aims to support the official <a href="http://httpd.apache.org/docs/trunk/mod/mod_lua.html">mod_lua documentation</a> by expanding on various topics.
</p>
<p>
<a href="/gs/intro" class="btn btn-large btn-primary">Introduction to mod_lua</a>
<a href="http://httpd.apache.org/download.cgi#apache24" class="btn btn-large btn-success">Download mod_lua (httpd 2.4.7)</a>
<a href="/gs/news" class="btn btn-large btn-warning">What's new in mod_lua??</a>
</p>
<h3> Site news: </h3>
<p>
<strong>24th of March, 2014:</strong> 2.4.9 is here! Check out the <a href="/gs/news">new features</a> available in this new release.<br/><br/>
<strong>8th of January, 2014:</strong> An experimental version of <a href="http://www.colorroulette.com/">Doodlepad</a> using mod_lua as a backend is available to demo on our site. More to follow :)<br/><br/>
<strong>10th of December, 2013:</strong> An <a href="/api/database#odbc">ODBC Quick-guide</a> is available for Windows users struggling with mod_lua and databases.<br/><br/>
<strong>9th of December, 2013:</strong> <a href="https://github.com/Humbedooh/IRCGateway">IRCGateway</a>, a mod_lua-driven IRC client using <a href="/api/websocket">WebSockets</a>, is now available for perusing.<br/><br/>
<strong>29th of November, 2013:</strong> httpd 2.4.7 released with new <a href="/api/websocket">WebSocket</a>, <a href="/hooks/logging">logging hook</a> and <a href="/recipes/cookies">cookie</a> features for mod_lua<br/><br/>
<strong>27th of October, 2013:</strong> After some downtime, we're back again, yay!
</p>
| 58.321429 | 225 | 0.706675 |
8dfbcaca14e588ab653b03be1a456d9f7e372885 | 4,968 | swift | Swift | Source/Services/CLLocationManager/LocationManager.swift | madhusudhanivy/common | 6680346c988a287b7ab1f3012b8f7b5a99c268f1 | [
"MIT"
] | null | null | null | Source/Services/CLLocationManager/LocationManager.swift | madhusudhanivy/common | 6680346c988a287b7ab1f3012b8f7b5a99c268f1 | [
"MIT"
] | null | null | null | Source/Services/CLLocationManager/LocationManager.swift | madhusudhanivy/common | 6680346c988a287b7ab1f3012b8f7b5a99c268f1 | [
"MIT"
] | null | null | null | //
// LocationManager.swift
// Melu
//
// Created by apple on 07/07/20.
// Copyright © 2020 Inrisoft. All rights reserved.
//
import Foundation
import CoreLocation
import MapKit
protocol LocationManagerDelegate {
func getCurrentLocationDetails(currentLocationCoodinates: CLLocationCoordinate2D)
}
internal final class LocationManager: NSObject {
var delegate: LocationManagerDelegate!
static let shared = LocationManager()
lazy var locationManager : CLLocationManager = {
let newLocationmanager = CLLocationManager()
newLocationmanager.requestWhenInUseAuthorization()
newLocationmanager.requestAlwaysAuthorization()
newLocationmanager.desiredAccuracy = kCLLocationAccuracyBest
return newLocationmanager
}()
var mapCenterLocationAddress : LocationAdress!
var deviceLocation : CLLocation!
func startUpdateLocation() {
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
}
extension LocationManager : CLLocationManagerDelegate {
// MARK: - Location Details delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
debugPrint(locations.last!.coordinate)
deviceLocation = locations.last!
manager.stopUpdatingLocation()
manager.stopUpdatingLocation()
if delegate != nil {
delegate.getCurrentLocationDetails(currentLocationCoodinates: locations.last!.coordinate)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
debugPrint(error.localizedDescription)
}
func setLocationInCenter(mapViewObj: MKMapView, location: CLLocationCoordinate2D) {
// Do any additional setup after loading the view.
mapViewObj.setCenter(location.self, animated: false)
let region = MKCoordinateRegion( center: location.self, latitudinalMeters: CLLocationDistance(exactly: 5000)!, longitudinalMeters: CLLocationDistance(exactly: 5000)!)
mapViewObj.setRegion(mapViewObj.regionThatFits(region), animated: false)
}
func getCenterLocationAddress(_ locationCoordinate: CLLocation, completionHandler: @escaping (_ data: Any) -> Void) {
CLGeocoder().reverseGeocodeLocation(locationCoordinate, completionHandler: {(placemarks, error) -> Void in
if error != nil {
debugPrint("Reverse geocoder failed with error" + (error?.localizedDescription)!)
return
}
if (placemarks?.count)! > 0 {
let pm = placemarks?[0]
self.mapCenterLocationAddress = LocationAdress()
self.mapCenterLocationAddress.location = locationCoordinate
self.mapCenterLocationAddress.thoroughfare = pm!.thoroughfare ?? ""
self.mapCenterLocationAddress.locality = pm!.locality ?? ""
self.mapCenterLocationAddress.administrativeArea = pm!.administrativeArea ?? ""
self.mapCenterLocationAddress.country = pm!.country ?? ""
self.mapCenterLocationAddress.subLocality = pm!.subLocality ?? ""
self.mapCenterLocationAddress.district = pm!.subAdministrativeArea ?? ""
self.mapCenterLocationAddress.postalCode = pm!.postalCode ?? ""
self.mapCenterLocationAddress.fullAddress = ""
/* ------- full address ---------- */
if let subLocality = pm!.subLocality {
self.mapCenterLocationAddress.fullAddress = subLocality
}
if let locality = pm!.locality {
self.mapCenterLocationAddress.fullAddress = self.mapCenterLocationAddress.fullAddress! + ", " + locality
}
if let administrativeArea = pm!.administrativeArea {
self.mapCenterLocationAddress.fullAddress = self.mapCenterLocationAddress.fullAddress! + ", " + administrativeArea
}
if let country = pm!.country {
self.mapCenterLocationAddress.fullAddress = self.mapCenterLocationAddress.fullAddress! + ", " + country
}
if let postalCode = pm!.postalCode {
self.mapCenterLocationAddress.fullAddress = self.mapCenterLocationAddress.fullAddress! + " - " + postalCode
}
DispatchQueue.main.async {
completionHandler(self.mapCenterLocationAddress as Any)
}
}
else {
#if DEBUG
debugPrint("Problem with the data received from geocoder")
#endif
}
})
}
}
| 38.215385 | 174 | 0.61876 |
1312fb94782e68b5fba1d0836e711126853ca48b | 14,809 | h | C | LNote/Dependencies/mruby/src/encoding.h | lriki/LNote | a009cb44f7ac7ede3be7237fe7fca52d4c70f393 | [
"MIT"
] | null | null | null | LNote/Dependencies/mruby/src/encoding.h | lriki/LNote | a009cb44f7ac7ede3be7237fe7fca52d4c70f393 | [
"MIT"
] | null | null | null | LNote/Dependencies/mruby/src/encoding.h | lriki/LNote | a009cb44f7ac7ede3be7237fe7fca52d4c70f393 | [
"MIT"
] | null | null | null | /*
** encoding.h - Encoding class
**
** See Copyright Notice in mruby.h
*/
#ifndef RUBY_ENCODING_H
#define RUBY_ENCODING_H 1
#if defined(__cplusplus)
extern "C" {
#endif
#include <stdarg.h>
#include "oniguruma.h"
#include "mruby/data.h"
int mrb_tolower(int c);
int mrb_toupper(int c);
#define TOUPPER(c) mrb_toupper((unsigned char)(c))
#define TOLOWER(c) mrb_tolower((unsigned char)(c))
#define FL_USHIFT 12
#define FL_USER0 (((int)1)<<(FL_USHIFT+0))
#define FL_USER1 (((int)1)<<(FL_USHIFT+1))
#define FL_USER2 (((int)1)<<(FL_USHIFT+2))
#define FL_USER3 (((int)1)<<(FL_USHIFT+3))
#define FL_USER4 (((int)1)<<(FL_USHIFT+4))
#define FL_USER5 (((int)1)<<(FL_USHIFT+5))
#define FL_USER6 (((int)1)<<(FL_USHIFT+6))
#define FL_USER7 (((int)1)<<(FL_USHIFT+7))
#define FL_USER8 (((int)1)<<(FL_USHIFT+8))
#define FL_USER9 (((int)1)<<(FL_USHIFT+9))
#define ENCODING_INLINE_MAX 1023
/* 1023 = 0x03FF */
/*#define ENCODING_SHIFT (FL_USHIFT+10)*/
#define ENCODING_SHIFT (10)
#define ENCODING_MASK (((unsigned int)ENCODING_INLINE_MAX)<<ENCODING_SHIFT)
#define ENCODING_SET_INLINED(obj,i) do {\
RBASIC(obj)->flags &= ~ENCODING_MASK;\
RBASIC(obj)->flags |= (unsigned int)(i) << ENCODING_SHIFT;\
} while (0)
#define ENCODING_SET(mrb, obj,i) do {\
mrb_value mrb_encoding_set_obj = (obj); \
int encoding_set_enc_index = (i); \
if (encoding_set_enc_index < ENCODING_INLINE_MAX) \
ENCODING_SET_INLINED(mrb_encoding_set_obj, encoding_set_enc_index); \
else \
mrb_enc_set_index(mrb, mrb_encoding_set_obj, encoding_set_enc_index); \
} while (0)
#define ENCODING_GET_INLINED(obj) (unsigned int)((RSTRING(obj)->flags & ENCODING_MASK)>>ENCODING_SHIFT)
#define ENCODING_GET(mrb, obj) \
(ENCODING_GET_INLINED(obj) != ENCODING_INLINE_MAX ? \
ENCODING_GET_INLINED(obj) : \
mrb_enc_get_index(mrb, obj))
#define ENCODING_IS_ASCII8BIT(obj) (ENCODING_GET_INLINED(obj) == 0)
#define ENCODING_MAXNAMELEN 42
#define ENC_CODERANGE_MASK ((int)(FL_USER8|FL_USER9))
#define ENC_CODERANGE_UNKNOWN 0
#define ENC_CODERANGE_7BIT ((int)FL_USER8)
#define ENC_CODERANGE_VALID ((int)FL_USER9)
#define ENC_CODERANGE_BROKEN ((int)(FL_USER8|FL_USER9))
#define ENC_CODERANGE(obj) ((int)(RSTRING(obj)->flags & ENC_CODERANGE_MASK))
#define ENC_CODERANGE_ASCIIONLY(obj) (ENC_CODERANGE(obj) == ENC_CODERANGE_7BIT)
#ifdef INCLUDE_ENCODING
#define ENC_CODERANGE_SET(obj,cr) (RSTRING(obj)->flags = \
(RSTRING(obj)->flags & ~ENC_CODERANGE_MASK) | (cr))
#else
#define ENC_CODERANGE_SET(obj,cr)
#endif //INCLUDE_ENCODING
#define ENC_CODERANGE_CLEAR(obj) ENC_CODERANGE_SET(obj,0)
/* assumed ASCII compatibility */
#define ENC_CODERANGE_AND(a, b) \
(a == ENC_CODERANGE_7BIT ? b : \
a == ENC_CODERANGE_VALID ? (b == ENC_CODERANGE_7BIT ? ENC_CODERANGE_VALID : b) : \
ENC_CODERANGE_UNKNOWN)
#define ENCODING_CODERANGE_SET(mrb, obj, encindex, cr) \
do { \
mrb_value mrb_encoding_coderange_obj = (obj); \
ENCODING_SET(mrb, mrb_encoding_coderange_obj, (encindex)); \
ENC_CODERANGE_SET(mrb_encoding_coderange_obj, (cr)); \
} while (0)
typedef OnigEncodingType mrb_encoding;
/* mrb_encoding * -> name */
#define mrb_enc_name(enc) (enc)->name
int mrb_enc_get_index(mrb_state *mrb, mrb_value obj);
int mrb_enc_replicate(mrb_state *, const char *, mrb_encoding *);
int mrb_define_dummy_encoding(mrb_state *mrb, const char *);
#define mrb_enc_to_index(enc) ((enc) ? ENC_TO_ENCINDEX(enc) : 0)
void mrb_enc_set_index(mrb_state *mrb, mrb_value obj, int encindex);
int mrb_enc_find_index(mrb_state *mrb, const char *name);
int mrb_to_encoding_index(mrb_state *mrb, mrb_value);
mrb_encoding* mrb_to_encoding(mrb_state *mrb, mrb_value);
mrb_encoding* mrb_enc_get(mrb_state *, mrb_value);
mrb_encoding* mrb_enc_compatible(mrb_state *, mrb_value, mrb_value);
mrb_encoding* mrb_enc_check(mrb_state *, mrb_value, mrb_value);
mrb_value mrb_enc_associate_index(mrb_state *mrb, mrb_value, int);
#ifdef INCLUDE_ENCODING
mrb_value mrb_enc_associate(mrb_state *mrb, mrb_value, mrb_encoding*);
#else
#define mrb_enc_associate(mrb,value,enc)
#endif //INCLUDE_ENCODING
void mrb_enc_copy(mrb_state *mrb, mrb_value dst, mrb_value src);
mrb_value mrb_enc_reg_new(const char*, long, mrb_encoding*, int);
//PRINTF_ARGS(mrb_value rb_enc_sprintf(mrb_encoding *, const char*, ...), 2, 3);
mrb_value mrb_enc_vsprintf(mrb_encoding *, const char*, va_list);
long mrb_enc_strlen(const char*, const char*, mrb_encoding*);
char* mrb_enc_nth(mrb_state *, const char*, const char*, long, mrb_encoding*);
mrb_value mrb_obj_encoding(mrb_state *, mrb_value);
mrb_value mrb_enc_str_buf_cat(mrb_state *mrb, mrb_value str, const char *ptr, long len, mrb_encoding *enc);
mrb_value rb_enc_uint_chr(mrb_state *mrb, unsigned int code, mrb_encoding *enc);
mrb_value mrb_external_str_new_with_enc(mrb_state *mrb, const char *ptr, long len, mrb_encoding *);
mrb_value mrb_str_export_to_enc(mrb_value, mrb_encoding *);
/* index -> mrb_encoding */
mrb_encoding* mrb_enc_from_index(mrb_state *mrb, int idx);
/* name -> mrb_encoding */
mrb_encoding * mrb_enc_find(mrb_state *mrb, const char *name);
/* mrb_encoding * -> name */
#define mrb_enc_name(enc) (enc)->name
/* mrb_encoding * -> minlen/maxlen */
#define mrb_enc_mbminlen(enc) (enc)->min_enc_len
#define mrb_enc_mbmaxlen(enc) (enc)->max_enc_len
/* -> mbclen (no error notification: 0 < ret <= e-p, no exception) */
int mrb_enc_mbclen(const char *p, const char *e, mrb_encoding *enc);
/* -> mbclen (only for valid encoding) */
int mrb_enc_fast_mbclen(const char *p, const char *e, mrb_encoding *enc);
/* -> chlen, invalid or needmore */
int mrb_enc_precise_mbclen(const char *p, const char *e, mrb_encoding *enc);
#define MBCLEN_CHARFOUND_P(ret) ONIGENC_MBCLEN_CHARFOUND_P(ret)
#define MBCLEN_CHARFOUND_LEN(ret) ONIGENC_MBCLEN_CHARFOUND_LEN(ret)
#define MBCLEN_INVALID_P(ret) ONIGENC_MBCLEN_INVALID_P(ret)
#define MBCLEN_NEEDMORE_P(ret) ONIGENC_MBCLEN_NEEDMORE_P(ret)
#define MBCLEN_NEEDMORE_LEN(ret) ONIGENC_MBCLEN_NEEDMORE_LEN(ret)
/* -> 0x00..0x7f, -1 */
int mrb_enc_ascget(mrb_state *mrb, const char *p, const char *e, int *len, mrb_encoding *enc);
/* -> code (and len) or raise exception */
unsigned int mrb_enc_codepoint_len(mrb_state *mrb, const char *p, const char *e, int *len, mrb_encoding *enc);
/* prototype for obsolete function */
unsigned int mrb_enc_codepoint(mrb_state *mrb, const char *p, const char *e, mrb_encoding *enc);
/* overriding macro */
#define mrb_enc_codepoint(mrb,p,e,enc) mrb_enc_codepoint_len((mrb),(p),(e),0,(enc))
#define mrb_enc_mbc_to_codepoint(p, e, enc) ONIGENC_MBC_TO_CODE(enc,(UChar*)(p),(UChar*)(e))
/* -> codelen>0 or raise exception */
#ifdef INCLUDE_ENCODING
int mrb_enc_codelen(mrb_state *mrb, int code, mrb_encoding *enc);
#else
#define mrb_enc_codelen(mrb,code,enc) 1
#endif //INCLUDE_ENCODING
/* code,ptr,encoding -> write buf */
#define mrb_enc_mbcput(c,buf,enc) ((*(buf) = (char)(c)),1)
/* start, ptr, end, encoding -> prev_char */
#define mrb_enc_prev_char(s,p,e,enc) (char *)onigenc_get_prev_char_head(enc,(UChar*)(s),(UChar*)(p),(UChar*)(e))
/* start, ptr, end, encoding -> next_char */
#define mrb_enc_left_char_head(s,p,e,enc) (char *)onigenc_get_left_adjust_char_head(enc,(UChar*)(s),(UChar*)(p),(UChar*)(e))
#define mrb_enc_right_char_head(s,p,e,enc) (char *)onigenc_get_right_adjust_char_head(enc,(UChar*)(s),(UChar*)(p),(UChar*)(e))
/* ptr, ptr, encoding -> newline_or_not */
#define mrb_enc_is_newline(p,end,enc) ONIGENC_IS_MBC_NEWLINE(enc,(UChar*)(p),(UChar*)(end))
#define mrb_enc_isctype(c,t,enc) ONIGENC_IS_CODE_CTYPE(enc,c,t)
#define mrb_enc_isascii(c,enc) ONIGENC_IS_CODE_ASCII(c)
#define mrb_enc_isalpha(c,enc) ONIGENC_IS_CODE_ALPHA(enc,c)
#define mrb_enc_islower(c,enc) ONIGENC_IS_CODE_LOWER(enc,c)
#define mrb_enc_isupper(c,enc) ONIGENC_IS_CODE_UPPER(enc,c)
#define mrb_enc_ispunct(c,enc) ONIGENC_IS_CODE_PUNCT(enc,c)
#define mrb_enc_isalnum(c,enc) ONIGENC_IS_CODE_ALNUM(enc,c)
#define mrb_enc_isprint(c,enc) ONIGENC_IS_CODE_PRINT(enc,c)
#define mrb_enc_isspace(c,enc) ONIGENC_IS_CODE_SPACE(enc,c)
#define mrb_enc_isdigit(c,enc) ONIGENC_IS_CODE_DIGIT(enc,c)
#define mrb_enc_asciicompat(mrb, enc) (mrb_enc_mbminlen(enc)==1 && !mrb_enc_dummy_p(enc))
int mrb_enc_casefold(char *to, const char *p, const char *e, mrb_encoding *enc);
int mrb_enc_toupper(int c, mrb_encoding *enc);
int mrb_enc_tolower(int c, mrb_encoding *enc);
//ID mrb_intern3(const char*, long, mrb_encoding*);
//ID mrb_interned_id_p(const char *, long, mrb_encoding *);
int mrb_enc_symname_p(const char*, mrb_encoding*);
int mrb_enc_symname2_p(const char*, long, mrb_encoding*);
int mrb_enc_str_coderange(mrb_state *mrb, mrb_value);
long mrb_str_coderange_scan_restartable(const char*, const char*, mrb_encoding*, int*);
int mrb_enc_str_asciionly_p(mrb_state *mrb, mrb_value);
#define mrb_enc_str_asciicompat_p(mrb, str) mrb_enc_asciicompat(mrb, mrb_enc_get(mrb, str))
mrb_value mrb_enc_from_encoding(mrb_state *mrb, mrb_encoding *enc);
int mrb_enc_unicode_p(mrb_encoding *enc);
mrb_encoding *mrb_ascii8bit_encoding(mrb_state *mrb);
mrb_encoding *mrb_utf8_encoding(mrb_state *mrb);
mrb_encoding *mrb_usascii_encoding(mrb_state *mrb);
mrb_encoding *mrb_locale_encoding(mrb_state *mrb);
mrb_encoding *mrb_filesystem_encoding(mrb_state *mrb);
mrb_encoding *mrb_default_external_encoding(mrb_state *mrb);
mrb_encoding *mrb_default_internal_encoding(mrb_state *mrb);
int mrb_ascii8bit_encindex(void);
int mrb_utf8_encindex(void);
int mrb_usascii_encindex(void);
int mrb_locale_encindex(mrb_state *mrb);
int mrb_filesystem_encindex(void);
mrb_value mrb_enc_default_external(mrb_state *mrb);
mrb_value mrb_enc_default_internal(mrb_state *mrb);
void mrb_enc_set_default_external(mrb_state *mrb, mrb_value encoding);
void mrb_enc_set_default_internal(mrb_state *mrb, mrb_value encoding);
mrb_value mrb_locale_charmap(mrb_state *mrb, mrb_value klass);
mrb_value mrb_usascii_str_new_cstr(mrb_state *mrb, const char *ptr);
int mrb_str_buf_cat_escaped_char(mrb_state *mrb, mrb_value result, unsigned int c, int unicode_p);
#define ENC_DUMMY_FLAG (1<<24)
#define ENC_INDEX_MASK (~(~0U<<24))
#define ENC_TO_ENCINDEX(enc) (int)((enc)->ruby_encoding_index & ENC_INDEX_MASK)
#define ENC_DUMMY_P(enc) ((enc)->ruby_encoding_index & ENC_DUMMY_FLAG)
#define ENC_SET_DUMMY(enc) ((enc)->ruby_encoding_index |= ENC_DUMMY_FLAG)
static inline int
mrb_enc_dummy_p(mrb_encoding *enc)
{
return ENC_DUMMY_P(enc) != 0;
}
/* econv stuff */
typedef enum {
econv_invalid_byte_sequence,
econv_undefined_conversion,
econv_destination_buffer_full,
econv_source_buffer_empty,
econv_finished,
econv_after_output,
econv_incomplete_input
} mrb_econv_result_t;
typedef struct mrb_econv_t mrb_econv_t;
mrb_value mrb_str_encode(mrb_state *mrb, mrb_value str, mrb_value to, int ecflags, mrb_value ecopts);
int mrb_econv_has_convpath_p(mrb_state *mrb, const char* from_encoding, const char* to_encoding);
int mrb_econv_prepare_opts(mrb_state *mrb, mrb_value opthash, mrb_value *ecopts);
mrb_econv_t *mrb_econv_open(mrb_state *mrb, const char *source_encoding, const char *destination_encoding, int ecflags);
mrb_econv_t *mrb_econv_open_opts(mrb_state *mrb, const char *source_encoding, const char *destination_encoding, int ecflags, mrb_value ecopts);
mrb_econv_result_t mrb_econv_convert(mrb_state *mrb, mrb_econv_t *ec,
const unsigned char **source_buffer_ptr, const unsigned char *source_buffer_end,
unsigned char **destination_buffer_ptr, unsigned char *destination_buffer_end,
int flags);
void mrb_econv_close(mrb_econv_t *ec);
/* result: 0:success -1:failure */
int mrb_econv_set_replacement(mrb_state *mrb, mrb_econv_t *ec, const unsigned char *str, size_t len, const char *encname);
/* result: 0:success -1:failure */
int mrb_econv_decorate_at_first(mrb_state *mrb, mrb_econv_t *ec, const char *decorator_name);
int mrb_econv_decorate_at_last(mrb_state *mrb, mrb_econv_t *ec, const char *decorator_name);
mrb_value mrb_econv_open_exc(mrb_state *mrb, const char *senc, const char *denc, int ecflags);
/* result: 0:success -1:failure */
int mrb_econv_insert_output(mrb_state *mrb, mrb_econv_t *ec,
const unsigned char *str, size_t len, const char *str_encoding);
/* encoding that mrb_econv_insert_output doesn't need conversion */
const char *mrb_econv_encoding_to_insert_output(mrb_econv_t *ec);
/* raise an error if the last mrb_econv_convert is error */
void mrb_econv_check_error(mrb_state *mrb, mrb_econv_t *ec);
/* returns an exception object or nil */
mrb_value mrb_econv_make_exception(mrb_state *mrb, mrb_econv_t *ec);
int mrb_econv_putbackable(mrb_econv_t *ec);
void mrb_econv_putback(mrb_econv_t *ec, unsigned char *p, int n);
/* returns the corresponding ASCII compatible encoding for encname,
* or NULL if encname is not ASCII incompatible encoding. */
const char *mrb_econv_asciicompat_encoding(const char *encname);
mrb_value mrb_econv_str_convert(mrb_state *mrb, mrb_econv_t *ec, mrb_value src, int flags);
mrb_value mrb_econv_substr_convert(mrb_state *mrb, mrb_econv_t *ec, mrb_value src, long byteoff, long bytesize, int flags);
mrb_value mrb_econv_str_append(mrb_state *mrb, mrb_econv_t *ec, mrb_value src, mrb_value dst, int flags);
mrb_value mrb_econv_substr_append(mrb_state *mrb, mrb_econv_t *ec, mrb_value src, long byteoff, long bytesize, mrb_value dst, int flags);
void mrb_econv_binmode(mrb_econv_t *ec);
/* flags for mrb_econv_open */
#define ECONV_ERROR_HANDLER_MASK 0x000000ff
#define ECONV_INVALID_MASK 0x0000000f
#define ECONV_INVALID_REPLACE 0x00000002
#define ECONV_UNDEF_MASK 0x000000f0
#define ECONV_UNDEF_REPLACE 0x00000020
#define ECONV_UNDEF_HEX_CHARREF 0x00000030
#define ECONV_DECORATOR_MASK 0x0000ff00
#define ECONV_UNIVERSAL_NEWLINE_DECORATOR 0x00000100
#define ECONV_CRLF_NEWLINE_DECORATOR 0x00001000
#define ECONV_CR_NEWLINE_DECORATOR 0x00002000
#define ECONV_XML_TEXT_DECORATOR 0x00004000
#define ECONV_XML_ATTR_CONTENT_DECORATOR 0x00008000
#define ECONV_STATEFUL_DECORATOR_MASK 0x00f00000
#define ECONV_XML_ATTR_QUOTE_DECORATOR 0x00100000
/* end of flags for mrb_econv_open */
/* flags for mrb_econv_convert */
#define ECONV_PARTIAL_INPUT 0x00010000
#define ECONV_AFTER_OUTPUT 0x00020000
/* end of flags for mrb_econv_convert */
int mrb_isspace(int c);
#define ENCODE_CLASS (mrb_class_obj_get(mrb, "Encoding"))
#define CONVERTER_CLASS (mrb_class_obj_get(mrb, "Converter"))
#if defined(__cplusplus)
} /* extern "C" { */
#endif
#endif /* RUBY_ENCODING_H */
| 42.190883 | 143 | 0.756432 |
8754ebb5ab3fa115ccd84337e1cd06c8aa7ee324 | 12,884 | html | HTML | src/assets/Category Sets/Fine Arts/Fine Arts47.html | Holy-Spirit-Scholar-Bowl/practice | 898c2e15ddb3eb859a1d38332b9a99a7954b80ce | [
"Unlicense"
] | null | null | null | src/assets/Category Sets/Fine Arts/Fine Arts47.html | Holy-Spirit-Scholar-Bowl/practice | 898c2e15ddb3eb859a1d38332b9a99a7954b80ce | [
"Unlicense"
] | null | null | null | src/assets/Category Sets/Fine Arts/Fine Arts47.html | Holy-Spirit-Scholar-Bowl/practice | 898c2e15ddb3eb859a1d38332b9a99a7954b80ce | [
"Unlicense"
] | null | null | null | 1. Fine Arts/Music (LIST (Ladue Invitational Spring Tournament) 2014)<br><strong>One of this composer's pieces consists of six movements, each named after a verse from the Song of Solomon. This composer of Flos Campi included "Song of the Exposition" as the first movement to a work based on Leaves of Grass. Another of his symphonies incorporates music from a movie featuring Robert Scott's expedition. A </strong> George Meredith poem inspired a work by this composer that uses ascending scales to depict the action of the title bird. This composer of A Sea Symphony named another piece after the composer of Spem in alium. For ten points, name this English composer of Sinfonia Antarctica, The Lark Ascending, and Fantasia on a Theme by Thomas Tallis.<br>ANSWER: Ralph <u>Vaughan Williams</u><br><br>2. Fine Arts/All (Chitin 2008)<br>This painter depicted a mustachioed man behind two white-clad women holding closed-up umbrellas in one work, and the green shoes of a trapeze artist in the upper-left in another. In one of his works, a reclining nude accepts a bunch of flowers from a black servant, while three figures lounge near a blue tablecloth and some food while a nude woman bathes herself in a creek in the background in another. For 10 points, name this painter of The Balcony, A Bar at the Foiles-Bergeres, Olympia, and Luncheon on the Grass.<br>ANSWER: Edouard <u>Manet</u><br><br>3. Fine Arts/All (HSAPQ 4Q1 2009)<br>This artist painted a man in anachronistic armor standing next to the red robed title figure in his Disrobing of Christ. This painter depicted naked souls receiving golden robes of salvation in his Opening of the Fifth Seal. This artist painted a stormy view of his adopted home land in View of Toledo. This painter was originally named Domenikos Theotokopoulos, and he painted the ascent of a nobleman to heaven in The Burial of Count Orgaz. For 10 points name this Spanish painter usually named for his country of origin.<br>ANSWER: <u>El Greco</u> [or Domenikos Theotokopoulos before mentioned]<br><br>4. Fine Arts/Auditory (NTSS 2013)<br>Literary works by this composer include his Theory of Harmony and Brahms, the Progressive. He wrote a cantata based on poems by Jens Peter Jacobsen and he created a work which ends with a group of Jews singing the "Shema Yisroel". This composer of the Gurre Lieder [GUR-uh "leader"] and A Survivor From Warsaw composed a string sextet inspired by a Richard Dehmel poem. Poems by Albert Giraud [zhee-roh] serve as the basis for another work by this man in which the narrator speaks in the "Sprechstimme" [SPREK-shtee-muh] style. Name this proponent of the twelve-tone system who composed Transfigured Night and Pierrot Lunaire [pyair-oh loo-nair].<br>ANSWER: Arnold Schoenberg<br><br>5. Fine Arts/All (Fall Novice 2009)<br>This artist created the dream sequence for Hitchcock's Spellbound and collaborated with Luis Bunuel on the film Un Chien Andalou. This creator of Lobster Telephone also painted the “disintegration” of another of his works. That work features yellow cliffs in the upper right and ants swarming on a pocket watch in the bottom left. For 10 points, name this Spanish surrealist who painted three melting clocks in The Persistence of Memory.<br>ANSWER: Salvador <u>Dali</u><br><br>6. Fine Arts/All (HSAPQ ACF 1 2008)<br>This artist depicted a yellow cat on a sill looking at the Eiffel Tower in his painting Paris Through the Window. He painted a series of Tales from the Arabian Nights, as well as a work where he gestures toward a painting of a red goat and displays an oddly-shaped left hand, Self-Portrait With Seven Fingers. Another of his paintings portrays upside-down houses, a crescent moon, and a sheep looking at a green peasant. For 10 points, name this Russian painter of I and the Village.<br>ANSWER: Marc Chagall<br><br>7. Fine Arts/All (Maryland Spring Classic 2007)<br><strong>Commissioned by Pope Julius II to replace a depiction of gold stars over a blue sky, it resulted in the design of a new plaster formula known as intonaco. The genealogy of Christ is traced out in the vertical areas above each </strong> window, while five sybils and seven prophets appear on the pendentives supporting the main vault. In the center are three groups of stories from Genesis, including the legendary Creation of Adam scene. FTP, where can you find this 1512 Michelangelo fresco?<br>ANSWER: on the <u>ceiling</u> of the <u>Sistine Chapel</u><br><br>8. Fine Arts/Auditory (BISB 2013)<br>This composer created a ballet inspired by Nosferatu about a sorcerer who resurrects zombies solely for his own enjoyment. Another piece by this composer of Grohg has its melody derived from the song "Bonyparte." The fourth movement of his third symphony is a reworking of another of his works for brass and percussion. Another of his works uses "Camptown Races" and features narration from the Gettysburg Address. This composer of "Fanfare for the Common Man" and Lincoln Portrait included the Shaker tune "Simple Gifts" in his most famous work, a ballet choreographed by Martha Graham. For 10 points, name this composer of Rodeo and Appalachian Spring.<br>ANSWER: Aaron Copland<br><br>9. Fine Arts/All (QuAC I 2008)<br>The Giulianiad was devoted to it, and Tarrega transcribed many pieces for it. This instrument is depicted by a saxophone in Ravel's orchestration of Pictures at an Exhibition, and the dovetail and Spanish method are both employed in its construction. Its jazz practitioners include the creator of Gone, Just Like a Train, Bill Frisell, nad the creator of Gypsy Jazz, Django Reinhardt. John Williams and Andres Segovia play, for 10 points, what instrument featured in the Concierto de Aranjuez which has six strings and a fretboard.<br>ANSWER: <u>guitar</u><br><br>10. Fine Arts/Visual (LIST (Ladue Invitational Spring Tournament) 2014)<br><strong>One of this man's sculptures shows a monkey grasping the shin of a writhing figure. This man designed the Laurentian Library for the Basilica of San Lorenzo. The biblical subject of one of his sculptures is notable for having horns. This man, who created Dying Slave and Moses for the tomb of </strong> Pope Julius II, drew himself in the flayed skin of St. Bartholomew in one fresco. Another of his frescoes shows a man stretching his arm to touch God's finger. This painter of The Creation of Adam and The Last Judgement also sculpted a male nude with a slingshot over his shoulder. For ten points, identify this Italian artist who sculpted a marble David and painted the ceiling of the Sistine Chapel.<br>ANSWER: <u>Michelangelo</u> di Lodovico Buonarroti Simoni [accept either underlined name]<br><br>11. Fine Arts/All (BHSAT 2011)<br>The texture of ragged hair matches the texture of the ragged dress in this artist's wooden sculpture, Magdalene Penitent. The tomb of Antipope John XXIII was co-designed by him with his mentor, Michelozzo. This artist designed marble statues of St. John and St. Mark to stand in the exterior niches of the Orsanmichele. His equestrian statue of the condotierro Erasmo da Narni stands in the Piazza del Santo in Padua. He depicted the title biblical figure naked except for a helmet, with a down-pointed sword, and a foot on Goliath's head. For 10 points, this is what Renaissance sculptor of Gattamaleta and a bronze David?<br>ANSWER: <u>Donatello</u> [or Donato di Niccolò di Betto <u>Bardi</u>]<br><br>12. Fine Arts/All (HSAPQ VHSL Regular Season 2011)<br>He’s not Jacque Louis-David (dah-VEED), but this man painted some men taking an oath by crossing their swords with a one-eyed Batavian chieftain in his The Conspiracy of Claudius Civilis. He also painted a Babylonian king watching as a disembodied hand writes illuminated Hebrew letters upon a wall. Other works by this painter of Belshazzar’s Feast show a cadaver being cut open by Dr. Nicolaes Tulp and the shooting company of Captain Frans Banning Cocq. For 10 points, name this Dutchman who painted The Anatomy Lesson and The Night Watch.<br>ANSWER: <u>Rembrandt</u> Harmenszoon van Rijn [accept either underlined name]<br><br>13. Fine Arts/All (PACE NSC 1998)<br>“Great Grandad”, “Git Along, Little Dogies”, and “Old Paint” are some authentic cowboy tunes orchestrated by this famous composer. Born in New York in 1900, he was educated in Paris by Nadia Boulanger. Billy the Kid and Rodeo pale in comparison, however, to the popularity of \-- for 10 patriotic points -- whose tremendously famous Appalachian Spring and Fanfare for the Common Man?<br>ANSWER: Aaron <u>Copland</u><br><br>14. Fine Arts/Visual (SCOP Novice 2013)<br><strong>In one of this man's works, a path zigzags its way up to a roofed cave where a blue-caped Virgin Mary gazes at her son. This artist of Mystic Nativity painted an orange grove where Mercury pokes some clouds with his caduceus and a ghostly </strong> Zephyr turns Chloris into Flora. In another of his works, Zephyr blows a naked goddess to land on an enormous seashell. For 10 points, name this Italian painter of Primavera and The Birth of Venus.<br>ANSWER: Sandro Botticelli<br><br>15. Fine Arts/All (Prison Bowl 2009)<br>In this work, Giovanna is asked to “safely guard this tender blossom” in “Veglia, o donnma, questo fiore”, but that character, being in love with a man she knows as Gualtier Maldé, sings “Caro nome che il mio cor” after his “E il sol dell' anima, la vita e amore”. Marullo, Ceprano, and Borsa give a blindfolded man a ladder so they can kidnap his supposed lover, acting out Count Monterone's curse. The kidnapped Gilda is actually that blindfolded man's daughter, and Gualtier turns out to be the Duke of Mantua. For 10 points, name this opera with a canzone about the fickleness of women, “La donna è mobile”, in which Sarafucile is hired to kill the Duke by the titular hunchbacked jester, a work by Guiseppe Verdi.<br>ANSWER: Rigoletto [KK]<br><br>16. Fine Arts/All (Fall Novice 2010)<br>This man created a pair of statues, one crouching and the other in an unfinished state of agony called the Rebellious and Dying Slaves. Those two works were commissioned for the tomb of his patron Pope Julius II. A mistranslation of the Old Testament led to a pair of horns on his Moses. This artist also carved a notably young-looking Virgin Mary and a notably uncircumcised biblical hero about to fire his sling. For 10 points, identify this sculptor of a notable David.<br>ANSWER: <u>Michelangelo</u> Buonarotti<br><br>17. Fine Arts/Visual (LIST (Ladue Invitational Spring Tournament) 2014)<br><strong>This artist made several depictions of a rock formation called the "White Place" near the town of Abiquiu. Another painting by this artist shows a New York skyscraper during the night and is titled Radiator Building. This artist lined another work with columns of red on both sides and portrayed a </strong> cow's skull in the middle. She painted several landscapes in her home in New Mexico and was the subject of several photographs taken by her husband, Alfred Stieglitz. For ten points, identify this American artist known for her various depictions of flowers.<br>ANSWER: Georgia Totto <u>O\'Keeffe</u><br><br>18. Fine Arts/All (BHSAT 2014)<br>One posthumously published piano piece by this composer opens with a G-sharp octave in the left hand and features persistent four-against-three rhythms in its C-sharp minor outer sections. The nickname of another work by this composer is due to the repeated A-flats that continue through most of the piece. The poetry of his countryman Adam Mickiewicz is said to have inspired his four ballades, and this composer wrote Fantaisie-Impromptu and the "Raindrop" Prelude. The dance music of his home country inspired his mazurkas and polonaises. For 10 points, name this Polish composer of many waltzes and nocturnes for piano.<br>ANSWER: Frédéric François <u>Chopin</u><br><br>19. Fine Arts/All (HSAPQ Colonia 2 2011)<br>A self portrait of this artist wearing a cross on his black tunic and holding a palette can be seen in one of his paintings. He included a cupid holding a mirror in his Rokeby Venus and painted the results of the siege of a Dutch town in The Surrender of Breda. This artist painted a girl stepping on a dog and a dwarf in a dress as the title attendants of the Infanta Margarita as court painter for Philip IV of Spain. For 20 points, name this Spanish painter of Las Meninas.<br>ANSWER: Diego <u>Velazquez</u><br><br>20. Fine Arts/All (Bulldog High School Academic Tournament (BHSAT) 2008)<br>Sure they don’t always look realistic, but let’s see if you can name these Picasso masterpieces anyway. A. This pivotal 1907 Picasso work depicts 5 prostitutes, some juxtaposed with African-style masks. It was one of the artist’s first large scale cubist painting, and is now at the Museum of Modern Art in New York.<br>ANSWER: Les <u>Demoiselles d’Avignon</u> or The <u>Young Ladies of Avignon</u><br><br> | 12,884 | 12,884 | 0.791214 |
2dc0e08c4f1bfa5be39a9fda308feef314787376 | 769 | html | HTML | src/PinkPoint.MobileApp/src/app/climbing-site/climbing-site.page.html | lehmamic/PinkPoint | 76af073c60f1be0874637c4ee5466a327caaa1e9 | [
"MIT"
] | null | null | null | src/PinkPoint.MobileApp/src/app/climbing-site/climbing-site.page.html | lehmamic/PinkPoint | 76af073c60f1be0874637c4ee5466a327caaa1e9 | [
"MIT"
] | 15 | 2021-03-09T19:16:28.000Z | 2022-03-02T05:58:58.000Z | src/PinkPoint.MobileApp/src/app/climbing-site/climbing-site.page.html | lehmamic/PinkPoint | 76af073c60f1be0874637c4ee5466a327caaa1e9 | [
"MIT"
] | 1 | 2020-06-06T01:29:37.000Z | 2020-06-06T01:29:37.000Z | <ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button></ion-back-button>
</ion-buttons>
<ion-title>{{ (climbingSite$ | async).name }}</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<div class="climbing-site-info">
<h1>{{ (climbingSite$ | async).name }}</h1>
<p>
{{ (climbingSite$ | async).address.street }} <br />
{{ (climbingSite$ | async).address.postCode + ' ' + (climbingSite$ | async).address.city }} <br />
{{ (climbingSite$ | async).address.state }}
</p>
</div>
<ion-list>
<ion-item [routerLink]="['/climbing-sites', (climbingSite$ | async).id, 'climbing-routes']">
<ion-label>
<h2>Routes</h2>
</ion-label>
</ion-item>
</ion-list>
</ion-content>
| 26.517241 | 104 | 0.56827 |
403d63802f60fbabff0544a634ff588c446e501a | 1,247 | py | Python | python_profile/benchmark.py | JiaLei123/PythonCamp_PY3 | f8f9df0b33a6942bf11330c097b0f71b5524d666 | [
"Apache-2.0"
] | null | null | null | python_profile/benchmark.py | JiaLei123/PythonCamp_PY3 | f8f9df0b33a6942bf11330c097b0f71b5524d666 | [
"Apache-2.0"
] | null | null | null | python_profile/benchmark.py | JiaLei123/PythonCamp_PY3 | f8f9df0b33a6942bf11330c097b0f71b5524d666 | [
"Apache-2.0"
] | null | null | null | import time
def primise(n):
if n == 2:
return [2]
elif n < 2:
return []
s = []
for i in range(3, n + 1):
if i % 2 != 0:
s.append(i)
mroot = n ** 0.5
half = (n + 1) / 2 - 1
i = 0
m = 3
while m <= mroot:
if s[i]:
j = int((m * m - 3) / 2)
s[j] = 0
while j < half:
s[j - 1] = 0
j += m
i = i + 1
m = 2 * i + 3
l = [2]
for x in s:
if x:
l.append(x)
return l
def primise2(n):
if n == 2:
return [2]
elif n < 2:
return []
s = list(range(3, n + 1, 2))
mroot = n ** 0.5
half = (n + 1) / 2 - 1
i = 0
m = 3
while m <= mroot:
if s[i]:
j = int((m * m - 3) / 2)
s[j] = 0
while j < half:
s[j - 1] = 0
j += m
i = i + 1
m = 2 * i + 3
l = [2] + [x for x in s if x]
return l
def benchmark():
start = time.time()
for _ in range(40):
count = len(primise(10000))
end = time.time()
print("benchmark duration: %r seconds" % (end - start))
print(count)
if __name__=="__main__":
benchmark()
| 18.61194 | 59 | 0.360866 |
9f9db6c8de413a3f982ed965b6411093e126e058 | 916 | dart | Dart | lib/src/nav_bar/nav_item.dart | RookiePlayers/ruki_nav_bar | dc70c69a53e6705524d21beca418b9ccb2f185d4 | [
"MIT"
] | null | null | null | lib/src/nav_bar/nav_item.dart | RookiePlayers/ruki_nav_bar | dc70c69a53e6705524d21beca418b9ccb2f185d4 | [
"MIT"
] | null | null | null | lib/src/nav_bar/nav_item.dart | RookiePlayers/ruki_nav_bar | dc70c69a53e6705524d21beca418b9ccb2f185d4 | [
"MIT"
] | null | null | null | import 'package:flutter/material.dart';
class NavItem{
final String label;
final String? path;
TextStyle? labelStyle;
VoidCallback onTap;
final int relativeIndex; // the relative item index in the list of nav items
bool? minimized; // whether to only show icon or label also
final Color? activeColor;
final Color? activeTextColor;
final IconData? icon;
final double? iconSize;
final bool disableHoverPageIndicator;
final Color? splashColor;
final BorderRadius? splashRadius;
final Color? hoverColor;
final double? width;
final double? height;
NavItem({required this.onTap, required this.relativeIndex,this.iconSize, this.width, this.height, required this.label,this.disableHoverPageIndicator = false, this.splashRadius,this.splashColor = Colors.transparent,this.hoverColor,this.activeTextColor, this.path, this.activeColor, this.icon, this.minimized = false,this.labelStyle});
} | 39.826087 | 336 | 0.775109 |
20d8376fdb5f7f19d6908e10cf37ab7be1310e5b | 144 | asm | Assembly | other.7z/NEWS.7z/NEWS/テープリストア/NEWS_05/NEWS_05.tar/home/kimura/kart/risc.lzh/risc/join/Record.asm | prismotizm/gigaleak | d082854866186a05fec4e2fdf1def0199e7f3098 | [
"MIT"
] | null | null | null | other.7z/NEWS.7z/NEWS/テープリストア/NEWS_05/NEWS_05.tar/home/kimura/kart/risc.lzh/risc/join/Record.asm | prismotizm/gigaleak | d082854866186a05fec4e2fdf1def0199e7f3098 | [
"MIT"
] | null | null | null | other.7z/NEWS.7z/NEWS/テープリストア/NEWS_05/NEWS_05.tar/home/kimura/kart/risc.lzh/risc/join/Record.asm | prismotizm/gigaleak | d082854866186a05fec4e2fdf1def0199e7f3098 | [
"MIT"
] | null | null | null | Name: Record.asm
Type: file
Size: 21845
Last-Modified: '1992-11-18T01:48:25Z'
SHA-1: ACB93820E148D4AC914691A450DDA083D89C3592
Description: null
| 20.571429 | 47 | 0.8125 |
4378de5320f0c8baeba6f2c6e7149255befae55e | 2,996 | kt | Kotlin | libnavui-maneuver/src/main/java/com/mapbox/navigation/ui/maneuver/model/LaneIndicator.kt | bikemap/mapbox-navigation-android | 5de9c3c9484466b641ab8907ce9ed316598bad56 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | libnavui-maneuver/src/main/java/com/mapbox/navigation/ui/maneuver/model/LaneIndicator.kt | bikemap/mapbox-navigation-android | 5de9c3c9484466b641ab8907ce9ed316598bad56 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | libnavui-maneuver/src/main/java/com/mapbox/navigation/ui/maneuver/model/LaneIndicator.kt | bikemap/mapbox-navigation-android | 5de9c3c9484466b641ab8907ce9ed316598bad56 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 1 | 2021-07-15T16:29:31.000Z | 2021-07-15T16:29:31.000Z | package com.mapbox.navigation.ui.maneuver.model
import com.mapbox.api.directions.v5.models.BannerComponents
/**
* "sub": {
* "components": [
* {
* "active_direction": "left",
* "active": true,
* "directions": [
* "left"
* ],
* "type": "lane",
* "text": ""
* },
* {
* "active": false,
* "directions": [
* "left"
* ],
* "type": "lane",
* "text": ""
* }
* ],
* "text": ""
* }
*
* A simplified data structure containing [BannerComponents.active] and list of [BannerComponents.directions].
* @property isActive Boolean informs whether the lane is active.
* @property directions List<String> informs about all the possible directions a particular lane can take.
*/
class LaneIndicator private constructor(
val isActive: Boolean,
val directions: List<String>
) {
/**
* Regenerate whenever a change is made
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LaneIndicator
if (isActive != other.isActive) return false
if (directions != other.directions) return false
return true
}
/**
* Regenerate whenever a change is made
*/
override fun hashCode(): Int {
var result = isActive.hashCode()
result = 31 * result + directions.hashCode()
return result
}
/**
* Returns a string representation of the object.
*/
override fun toString(): String {
return "LaneIndicator(isActive=$isActive, directions=$directions)"
}
/**
* @return builder matching the one used to create this instance
*/
fun toBuilder(): Builder {
return Builder()
.isActive(isActive)
.directions(directions)
}
/**
* Build a new [LaneIndicator]
* @property isActive Boolean
* @property directions List<String>
*/
class Builder {
private var isActive: Boolean = false
private var directions: List<String> = listOf()
/**
* apply isActive to the Builder.
* @param isActive String
* @return Builder
*/
fun isActive(isActive: Boolean): Builder =
apply { this.isActive = isActive }
/**
* apply directions to the Builder.
* @param directions List<String>
* @return Builder
*/
fun directions(directions: List<String>): Builder =
apply { this.directions = directions }
/**
* Build the [LaneIndicator]
* @return LaneIndicator
*/
fun build(): LaneIndicator {
return LaneIndicator(
isActive,
directions
)
}
}
}
| 25.827586 | 110 | 0.530374 |
3b9bbde569122712af75f1b1cb8821817f6f2d99 | 1,944 | sql | SQL | test/sql_querys/13 - Creacion y Set informacion - Autoridades.sql | floreacosta/losCedrosTapiales | 612ce71c1de60d5027021fa169e394157af34da8 | [
"MIT"
] | null | null | null | test/sql_querys/13 - Creacion y Set informacion - Autoridades.sql | floreacosta/losCedrosTapiales | 612ce71c1de60d5027021fa169e394157af34da8 | [
"MIT"
] | null | null | null | test/sql_querys/13 - Creacion y Set informacion - Autoridades.sql | floreacosta/losCedrosTapiales | 612ce71c1de60d5027021fa169e394157af34da8 | [
"MIT"
] | null | null | null | INSERT INTO autoridades (nombre, cargo, imagen, cv) VALUES
(1, "Dr. Rodríguez Cetran", "Director General", "", ""),
(2, "Dr. Horacio Pampin", "Director Medico", "", ""),
(3, "Sr. Alejandro Hafez", "Director Administrativo", "", ""),
(4, "Lic. Vilma di Pascua", "Jefa de Recursos Humanos", "", ""),
(5, "Dr. Hugo D. Tedesco", "Gerencia Médica", "", ""),
(6, "Dra. Marisa Flores", "Coordinación General", "", ""),
(7, "Dr. Nicolas D’Agostino", "Coordinación de Terapia Intensiva", "", ""),
(8, "Dra. Jannet Chacon", "Jefa de Servicio de Emergencias", "", ""),
(9, "Dr. Alejandro García Escudero", "Jefe de Servicio de Hemodinamia", "", ""),
(10, "Dr. Luis Frank", "Jefe de Servicio de Cirugía Cardiovascular", "", ""),
(11, "Dr. Alberto Marani", "Jefe De Servicio de Cardiología", "", ""),
(12, "Dr. Guillermo Benchetrit", "Jefe de Servicio de Infectologia", "", ""),
(13, "Dr. Maximo Zimerman", "Jefe de Servicio de Rehabilitación", "", ""),
(14, "Dra. Mariana Pampin", "Jefe de Servicio de Ginecologia y Obstetricia", "", ""),
(15, "Dr. Juan D. Bonello", "Jefe de Servicio de Pediatria", "", ""),
(16, "Dr. Jorge Borkowsky", "Jefe de Servicio de Hemoterapia", "", ""),
(17, "", "Jefe de Servicio de Neurología", "", ""),
(18, "", "Jefe de Servicio de Neurocirugía", "", ""),
(19, "", "Jefe de Servicio de Cirugía", "", ""),
(20, "", "Jefe de Servicio de Neumonología", "", ""),
(21, "", "Jefe de Servicio de Diagnostico por Imagen", "", ""),
(22, "", "Jefe de Servicio de Urologia", "", ""),
(23, "", "Jefe de Servicio de Traumatología", "", ""),
(24, "", "Jefe de Cirugía de Torax", "", ""),
(25, "Dra. Amelia Galli", "Jefe de Servicio de Laboratorio", "", ""),
(26, "", "Jefe de Servicio de Bacteriología", "", ""),
(27, "", "Jefe de Servicio de Endoscopia Digestiva", "", ""),
(28, "", "Jefe de Servicio de Oncologia", "", ""),
(29, "", "Jefe de Servicio de Fibrobroncoscopia", "", ""),
(30, "", "Jefe de Servicio de Kinesiologia", "", "");
| 60.75 | 85 | 0.598765 |
267046defaa0026dc8cc5501b7c9d47a67aa6da9 | 1,408 | java | Java | test/src/main/java/pub/carzy/services/controller/FileController.java | Dylan-lijl/web_utils | 88d3f793f605d4f4ea6cff452f59bde71e560e48 | [
"MIT"
] | 4 | 2022-01-13T07:43:25.000Z | 2022-01-19T02:04:08.000Z | test/src/main/java/pub/carzy/services/controller/FileController.java | Dylan-lijl/web_utils | 88d3f793f605d4f4ea6cff452f59bde71e560e48 | [
"MIT"
] | null | null | null | test/src/main/java/pub/carzy/services/controller/FileController.java | Dylan-lijl/web_utils | 88d3f793f605d4f4ea6cff452f59bde71e560e48 | [
"MIT"
] | null | null | null | package pub.carzy.services.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pub.carzy.api.CommonResult;
import pub.carzy.services.dto.request.DownloadRequest;
import pub.carzy.services.dto.request.UploadRequest;
import pub.carzy.services.dto.response.UploadResponse;
import pub.carzy.services.service.FileService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
/**
* @author admin
*/
@RequestMapping("/file")
@Controller
@Api(tags = "文件管理器", description = "文件管理器")
public class FileController {
@Resource
private FileService fileService;
@GetMapping()
@ApiOperation("获取文件")
public void download(@Valid DownloadRequest request, HttpServletResponse response) {
fileService.download(request, response);
}
@PostMapping()
@ApiOperation("上传文件")
@ResponseBody
public CommonResult<UploadResponse> upload(@Valid UploadRequest request) {
UploadResponse response = fileService.upload(request);
return CommonResult.success(response);
}
}
| 32 | 88 | 0.78196 |
afa2eb4d92a195630c6bd8b47ab4f360728451fc | 317 | kt | Kotlin | notification/src/main/java/com/rembertime/notification/data/provider/FileNameProvider.kt | rembertime/downloadd-notification-android | ca058e00ee9518bf27b7f8d5e2afc01530f20aff | [
"MIT"
] | 1 | 2021-07-10T18:07:03.000Z | 2021-07-10T18:07:03.000Z | notification/src/main/java/com/rembertime/notification/data/provider/FileNameProvider.kt | rembertime/downloadd-notification-android | ca058e00ee9518bf27b7f8d5e2afc01530f20aff | [
"MIT"
] | 3 | 2021-07-05T00:14:24.000Z | 2021-07-10T18:06:17.000Z | notification/src/main/java/com/rembertime/notification/data/provider/FileNameProvider.kt | rembertime/downloadd-notification-android | ca058e00ee9518bf27b7f8d5e2afc01530f20aff | [
"MIT"
] | null | null | null | package com.rembertime.notification.data.provider
/**
* This class tries to get the file name based on a path
* input "http://www.domain.com/file.txt"
* output "file.txt"
*/
internal class FileNameProvider {
fun find(path: String): String {
return path.substring(path.lastIndexOf("/").inc())
}
} | 24.384615 | 58 | 0.681388 |
292083ac7c9f357a31cbb1a7aee9a69fe5228351 | 603 | py | Python | genetic-tuner/config.py | windstrip/Genetic-Algorithm-PID-Controller-Tuner | 7e4c4febcc6e4d7c116d570a0d6a5f975a237007 | [
"Apache-2.0"
] | 39 | 2015-02-14T01:39:30.000Z | 2022-03-13T21:57:56.000Z | genetic-tuner/config.py | windstrip/Genetic-Algorithm-PID-Controller-Tuner | 7e4c4febcc6e4d7c116d570a0d6a5f975a237007 | [
"Apache-2.0"
] | null | null | null | genetic-tuner/config.py | windstrip/Genetic-Algorithm-PID-Controller-Tuner | 7e4c4febcc6e4d7c116d570a0d6a5f975a237007 | [
"Apache-2.0"
] | 18 | 2015-06-18T18:16:52.000Z | 2022-01-28T13:19:23.000Z | config = {
'population_size' : 100,
'mutation_probability' : .1,
'crossover_rate' : .9,
# maximum simulation runs before finishing
'max_runs' : 100,
# maximum timesteps per simulation
'max_timesteps' : 150,
# smoothness value of the line in [0, 1]
'line_smoothness' : .4,
# Bound for our gain parameters (p, i, d)
'max_gain_value' : 3,
# when set to 1, we create a new map this run. When set to 0, loads a new map
'new_map' : True,
'runs_per_screenshot' : 10,
'data_directory' : '/home/monk/genetic_pid_data',
'map_filename' : 'map.csv'
}
| 31.736842 | 81 | 0.631841 |
6cd58c64311582d36e9bb925d619c8c25d708851 | 949 | go | Go | dataframe/benchmark_test.go | davidnotplay/godf | 460a440db914c569faf6f770516ed5099cf8a1ab | [
"MIT"
] | 1 | 2019-03-10T12:50:14.000Z | 2019-03-10T12:50:14.000Z | dataframe/benchmark_test.go | davidnotplay/godf | 460a440db914c569faf6f770516ed5099cf8a1ab | [
"MIT"
] | null | null | null | dataframe/benchmark_test.go | davidnotplay/godf | 460a440db914c569faf6f770516ed5099cf8a1ab | [
"MIT"
] | null | null | null | package dataframe
import (
"fmt"
"testing"
)
type benchmarDFStruct struct {
I int `colName:"integer"`
F float64 `colName:"float"`
C complex128 `colName:"complex"`
S string `colName:"str"`
}
func genData(number int) *[]benchmarDFStruct{
var data []benchmarDFStruct
for i:= 0; i < number; i++ {
f := float64(i)
row := benchmarDFStruct{
i, f + (0.1*f), complex(f, f), fmt.Sprintf("test%d", i),
}
data = append(data, row)
}
return &data
}
func benchmarkNewDataFrame(rows int, b *testing.B) {
data := genData(rows)
for n := 0; n < b.N; n++ {
NewDataFrameFromStruct(data)
}
}
func BenchmarkNewDataFrame100(b *testing.B) {
benchmarkNewDataFrame(100, b)
}
func BenchmarkNewDataFrame1000(b *testing.B) {
benchmarkNewDataFrame(1000, b)
}
func BenchmarkNewDataFrame10000(b *testing.B) {
benchmarkNewDataFrame(10000, b)
}
func BenchmarkNewDataFrame100000(b *testing.B) {
benchmarkNewDataFrame(100000, b)
}
| 17.574074 | 59 | 0.680717 |
c8070f188e2c3e5b9e512cbedf620b70f6211e72 | 3,243 | sql | SQL | portal_college.sql | karabomaboka/Enrollment-System | 52b47d30c3386bcd74790d0b54e3c5133891466d | [
"Apache-2.0"
] | 2 | 2021-08-05T16:23:48.000Z | 2022-02-05T02:20:30.000Z | portal_college.sql | karabomaboka/Enrollment-System | 52b47d30c3386bcd74790d0b54e3c5133891466d | [
"Apache-2.0"
] | 1 | 2020-10-30T04:12:19.000Z | 2020-10-30T04:12:19.000Z | portal_college.sql | karabomaboka/Enrollment-System | 52b47d30c3386bcd74790d0b54e3c5133891466d | [
"Apache-2.0"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Sep 15, 2018 at 04:38 PM
-- Server version: 10.1.35-MariaDB
-- PHP Version: 7.2.9
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `portal_college`
--
-- --------------------------------------------------------
--
-- Table structure for table `student`
--
CREATE TABLE `student` (
`student_id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`date_of_birth` date NOT NULL,
`Gender` varchar(10) NOT NULL,
`photo` varchar(100) NOT NULL,
`address` varchar(50) NOT NULL,
`course_type` varchar(50) NOT NULL DEFAULT 'Bsc. IT'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `student`
--
INSERT INTO `student` (`student_id`, `name`, `email`, `password`, `date_of_birth`, `Gender`, `photo`, `address`, `course_type`) VALUES
(1, 'Indra Bahadur Oli', 'indraoli429@gmail.com', 'indra1234', '1997-02-26', 'Male', 'unlimited youTH.PNG', 'Balaju', 'Computing'),
(2, 'Swaraj Agrawal', 'swaraj@gmail.com', 'swaraj123', '1997-02-26', 'Male', 'Screenshot from 2018-09-14 22-16-47.png', 'Rato Bridge', 'Networking');
-- --------------------------------------------------------
--
-- Table structure for table `teacher`
--
CREATE TABLE `teacher` (
`teacher_id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`address` varchar(50) NOT NULL,
`Date_of_birth` date NOT NULL,
`gender` varchar(10) NOT NULL,
`photo` varchar(100) NOT NULL,
`salary` double NOT NULL,
`department` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `teacher`
--
INSERT INTO `teacher` (`teacher_id`, `name`, `email`, `password`, `address`, `Date_of_birth`, `gender`, `photo`, `salary`, `department`) VALUES
(1, 'Saroj', 'saroj@gmail.com', 'saroj2345', 'Kamalpokhari', '1992-02-26', 'Male', 'Screenshot from 2018-09-14 22-12-51.png', 50000, 'ING'),
(2, 'Bhim Sir', 'bhim@gmail.com', 'bhim12345', 'Kathmandu', '1990-02-26', 'Male', 'Screenshot from 2018-09-14 22-12-51.png', 50000, 'IT');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `student`
--
ALTER TABLE `student`
ADD PRIMARY KEY (`student_id`);
--
-- Indexes for table `teacher`
--
ALTER TABLE `teacher`
ADD PRIMARY KEY (`teacher_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `student`
--
ALTER TABLE `student`
MODIFY `student_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `teacher`
--
ALTER TABLE `teacher`
MODIFY `teacher_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 28.447368 | 149 | 0.665742 |
290856475e810b21bcc547989d14e51c999c556a | 761 | py | Python | mini-apps/tic-tac-toe-full/tic_tac_toe_module.py | CrtomirJuren/python-delavnica | db96470d2cb1870390545cfbe511552a9ef08720 | [
"MIT"
] | null | null | null | mini-apps/tic-tac-toe-full/tic_tac_toe_module.py | CrtomirJuren/python-delavnica | db96470d2cb1870390545cfbe511552a9ef08720 | [
"MIT"
] | null | null | null | mini-apps/tic-tac-toe-full/tic_tac_toe_module.py | CrtomirJuren/python-delavnica | db96470d2cb1870390545cfbe511552a9ef08720 | [
"MIT"
] | null | null | null | import random
# def generate_board():
# """
# funkcija ki generira naključno tic tac toe board - igralno ploščo
# vzorci = ['X','O']
# nakljucen_vzorec = random.choice(vzorci)
# """
# return board
# def print_board(board):
# """ funkcija za lepši terminal print board """
# pass
# def display_board():
# pass
# def check_win_condition(board, player):
# """ """
# return win
# def check_tie_condition(board):
# """ """
# return tie
# def check_rows(board, player):
# """ """
# return win
# def check_columns(board, player):
# """ """
# return win
# def check_diagonals(board, player):
# """ """
# return win
# testiraj funkcijo
# print_board(generate_random_board()) | 15.854167 | 71 | 0.584757 |
f5cb766fea84f45996bd653b13592a16d8d3c9d5 | 2,732 | sql | SQL | db/PE.CustomProcedures/StoredProcedures/pe_NL_LOD.sql | PracticeEngine/GLIntegration | 0681812f445af40d8ec970a10d8cea164c6d432b | [
"Apache-2.0"
] | null | null | null | db/PE.CustomProcedures/StoredProcedures/pe_NL_LOD.sql | PracticeEngine/GLIntegration | 0681812f445af40d8ec970a10d8cea164c6d432b | [
"Apache-2.0"
] | 5 | 2018-04-19T13:40:18.000Z | 2021-09-08T15:26:15.000Z | db/PE.CustomProcedures/StoredProcedures/pe_NL_LOD.sql | PracticeEngine/GLIntegration | 0681812f445af40d8ec970a10d8cea164c6d432b | [
"Apache-2.0"
] | 1 | 2018-06-28T13:21:05.000Z | 2018-06-28T13:21:05.000Z | /*
CUSTOM: This Stored Procedure should be customized for your environment
This StoredProcedure Creates the Nominal Ledger in bulk from the Lodgement (Bank Deposits) Transactions in PE
*/
CREATE PROCEDURE [dbo].[pe_NL_LOD]
@Result int OUTPUT
AS
DECLARE @MonthEnd datetime
DECLARE @PeriodIdx int
SET @MonthEnd = (Select PracPeriodEnd From tblControl Where PracID = 1)
IF @MonthEnd IS NULL GOTO TRAN_ABORT
SET @PeriodIdx = (Select PeriodIndex From tblControlPeriods WHERE PeriodEndDate = @MonthEnd)
BEGIN TRAN
EXEC pe_NL_Lodge_Update
IF @@ERROR <> 0 GOTO TRAN_ABORT
DECLARE @LodInd int
DECLARE @LodDrs int
DECLARE csr_Trans CURSOR DYNAMIC
FOR SELECT L.LodgeDetIndex, L.LodgeDebtor
FROM tblTranNominalBank NB INNER JOIN tblLodgementDetails L ON NB.LodgeIndex = L.LodgeIndex
WHERE NB.LodgePosted = 0
OPEN csr_Trans
FETCH csr_Trans INTO @LodInd, @LodDrs
WHILE (@@FETCH_STATUS=0)
BEGIN
--/Credit Bank Control (B/S)
INSERT INTO tblTranNominal ( NLPeriodIndex, NLDate, NLOrg, NLSource, NLSection, NLAccount, Office, TransTypeIndex, ContIndex, TransRefAlpha, Amount, NLNarrative, RefMin, RefMax )
SELECT NLPeriodIndex = CASE WHEN NB.LodgeDate > @MonthEnd THEN 0 ELSE @PeriodIdx END, NB.LodgeDate, NB.LodgePrac,
'LOD' AS NLSource, 'BS' AS NLSection, 'BNKCON' AS TranType, TB.BankOffice, '9' AS TransTypeIndex, L.ContIndex, L.LodgeIndex,
L.LodgeAmount*-1, L.LodgePayor, L.LodgeDetIndex, L.LodgeDetIndex
FROM tblTranNominalBank NB INNER JOIN tblLodgementDetails L ON NB.LodgeIndex = L.LodgeIndex INNER JOIN tblTranBank TB ON NB.LodgeBank = TB.BankIndex
WHERE L.LodgeDetIndex = @LodInd
IF @@ERROR <> 0 GOTO TRAN_ABORT
--/Debit Bank (B/S)
INSERT INTO tblTranNominal ( NLPeriodIndex, NLDate, NLOrg, NLSource, NLSection, NLAccount, Office, TransTypeIndex, ContIndex, TransRefAlpha, Amount, NLNarrative, RefMin, RefMax )
SELECT NLPeriodIndex = CASE WHEN NB.LodgeDate > @MonthEnd THEN 0 ELSE @PeriodIdx END, NB.LodgeDate, NB.LodgePrac,
'LOD' AS NLSource, 'BS' AS NLSection, 'BANK'+Cast(NB.LodgeBank AS Varchar(2)) AS NLAccount, TB.BankOffice, '9' AS TransTypeIndex, L.ContIndex, L.LodgeIndex,
L.LodgeAmount, L.LodgePayor, L.LodgeDetIndex, L.LodgeDetIndex
FROM tblTranNominalBank NB INNER JOIN tblLodgementDetails L ON NB.LodgeIndex = L.LodgeIndex INNER JOIN tblTranBank TB ON NB.LodgeBank = TB.BankIndex
WHERE L.LodgeDetIndex = @LodInd
IF @@ERROR <> 0 GOTO TRAN_ABORT
FETCH csr_Trans INTO @LodInd, @LodDrs
END
CLOSE csr_Trans
DEALLOCATE csr_Trans
UPDATE tblTranNominalBank
SET LodgePosted = 1
WHERE LodgePosted = 0
IF @@ERROR <> 0 GOTO TRAN_ABORT
COMMIT TRAN
SET @Result = 0
GOTO FINISH
TRAN_ABORT:
ROLLBACK TRAN
SET @Result = 1
FINISH: | 33.317073 | 180 | 0.759883 |
d2bd247294fa3acdda8a56d7717a9a9f302acc48 | 4,507 | php | PHP | app/Models/Date.php | sgkekais/swb8 | 6c20913fa1bcf0c59539835e6d3997f38bafd0ec | [
"MIT"
] | null | null | null | app/Models/Date.php | sgkekais/swb8 | 6c20913fa1bcf0c59539835e6d3997f38bafd0ec | [
"MIT"
] | null | null | null | app/Models/Date.php | sgkekais/swb8 | 6c20913fa1bcf0c59539835e6d3997f38bafd0ec | [
"MIT"
] | null | null | null | <?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
class Date extends Model
{
use HasFactory;
use LogsActivity;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'dates';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'date_type_id',
'location_id',
'datetime',
'title',
'description',
'note',
'published',
'cancelled',
'poll_begins',
'poll_ends',
'poll_is_open'
];
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'published' => false,
'cancelled' => false,
'poll_is_open' => false
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'published' => 'boolean',
'cancelled' => 'boolean',
'poll_is_open' => 'boolean',
'datetime' => 'datetime:Y-m-d\TH:i',
'poll_begins' => 'date:Y-m-d',
'poll_ends' => 'date:Y-m-d'
];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
// 'datetime',
// 'poll_begins',
// 'poll_ends'
];
/**
* The attributes that should be logged.
*
* @var array
*/
protected static $logFillable = true;
protected static $logOnlyDirty = true;
/*
* --------------------------------------------------------------------------
* ACCESSORS
* --------------------------------------------------------------------------
*/
/**
* Format the datetime attribute to a DATE string, for easy display in the date table TODO: accessors don't work in livewiredatatable
* @param $value
* @return mixed
*/
public function getDateAttribute($value)
{
return $this->datetime ? $this->datetime->toDateString() : null;
}
/**
* Format the datetime attribute to a TIME string, for easy display in the date table
* @param $value
* @return null
*/
public function getTimeAttribute($value)
{
return $this->datetime ? $this->datetime->toTimeString() : null;
}
/*
* --------------------------------------------------------------------------
* SCOPES
* --------------------------------------------------------------------------
*/
/**
* Scope a query to only include dates that are published
* @param $query
* @param bool $true
* @return mixed
*/
public function scopePublished($query, $true = true)
{
return $query->where('published', $true);
}
/**
* Scope a query to only include dates that are cancelled
* @param $query
* @param bool $true
* @return mixed
*/
public function scopeCancelled($query, $true = true)
{
return $query->where('cancelled', $true);
}
/*
* --------------------------------------------------------------------------
* RELATIONSHIPS
* --------------------------------------------------------------------------
*/
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function dateType()
{
return $this->belongsTo('App\Models\DateType');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function dateOptions()
{
return $this->hasMany('App\Models\DateOption');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function location()
{
return $this->belongsTo('App\Models\Location');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function match()
{
return $this->hasOne('App\Models\Match');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function tournament()
{
return $this->hasOne('App\Models\Tournament');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function clubs()
{
return $this->belongsToMany('App\Models\Club')->withTimestamps();
}
}
| 23.352332 | 137 | 0.49767 |
412b2effcb7b00afdd7460fc6cf0044f53ca2343 | 513 | c | C | 0x00-hello_world/6-size.c | johncoleman83/bootcampschool-low_level_programming | fbe8798f6c27ff62c1781fadb297f220955db234 | [
"MIT"
] | 4 | 2017-02-09T19:17:21.000Z | 2018-01-17T11:53:54.000Z | 0x00-hello_world/6-size.c | johncoleman83/bootcampschool-low_level_programming | fbe8798f6c27ff62c1781fadb297f220955db234 | [
"MIT"
] | null | null | null | 0x00-hello_world/6-size.c | johncoleman83/bootcampschool-low_level_programming | fbe8798f6c27ff62c1781fadb297f220955db234 | [
"MIT"
] | 6 | 2017-03-24T04:08:42.000Z | 2020-06-28T17:10:40.000Z | #include <stdio.h>
/**
* main - Entry point
*
* Return: Always 0 (Success)
*/
int main(void)
{
char acharacter;
int ainteger;
long along;
long long alonglong;
float afloat;
printf("Size of a char: %lu byte(s)\n", sizeof(acharacter));
printf("Size of an int: %lu byte(s)\n", sizeof(ainteger));
printf("Size of a long int: %lu byte(s)\n", sizeof(along));
printf("Size of a long long int: %lu byte(s)\n", sizeof(alonglong));
printf("Size of a float: %lu byte(s)\n", sizeof(afloat));
return (0);
}
| 20.52 | 69 | 0.645224 |
4186f27ea89872e93c9e791d17a31e44b4f80612 | 105 | c | C | csie/10computer-networks/2a/test3.c | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | csie/10computer-networks/2a/test3.c | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | csie/10computer-networks/2a/test3.c | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | #include<stdio.h>
#include<fcntl.h>
main() {
int fd = open("test4", O_RDONLY);
printf("%d\n", fd);
}
| 15 | 35 | 0.590476 |
893d098c4715148cd5ddbdfb8ec5956c7c3fd04d | 1,368 | kt | Kotlin | app/src/main/java/com/smobile/premierleague/repository/StandingsRepository.kt | stevan-milovanovic/premier-league | 682d3d7d1a65605b4d1d3efc08fa6932762b6653 | [
"Apache-2.0"
] | 4 | 2020-06-02T14:12:11.000Z | 2020-06-05T11:52:18.000Z | app/src/main/java/com/smobile/premierleague/repository/StandingsRepository.kt | stevan-milovanovic/premier-league | 682d3d7d1a65605b4d1d3efc08fa6932762b6653 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/smobile/premierleague/repository/StandingsRepository.kt | stevan-milovanovic/premier-league | 682d3d7d1a65605b4d1d3efc08fa6932762b6653 | [
"Apache-2.0"
] | 1 | 2020-06-02T15:59:53.000Z | 2020-06-02T15:59:53.000Z | package com.smobile.premierleague.repository
import androidx.lifecycle.LiveData
import com.smobile.premierleague.AppExecutors
import com.smobile.premierleague.api.LeagueService
import com.smobile.premierleague.api.StandingsNetworkResponse
import com.smobile.premierleague.db.StandingDao
import com.smobile.premierleague.model.Standing
import com.smobile.premierleague.model.base.Resource
import com.smobile.premierleague.testing.OpenForTesting
import javax.inject.Inject
import javax.inject.Singleton
/**
* Repository that handles Standing instances
*/
@Singleton
@OpenForTesting
class StandingsRepository @Inject constructor(
private val appExecutors: AppExecutors,
private val standingDao: StandingDao,
private val leagueService: LeagueService
) {
fun loadStandings(leagueId: Int): LiveData<Resource<List<Standing>>> {
return object :
NetworkBoundResource<List<Standing>, StandingsNetworkResponse>(appExecutors) {
override fun saveCallResult(item: StandingsNetworkResponse) {
standingDao.insert(item.api.standings[0])
}
override fun shouldFetch(data: List<Standing>?) = data == null || data.isEmpty()
override fun loadFromDb() = standingDao.getAll()
override fun createCall() = leagueService.getStandings(leagueId)
}.asLiveData()
}
} | 34.2 | 92 | 0.750731 |
c4b3d3ae93f3bfc9a77a4ba27de33948b4fa1356 | 772 | asm | Assembly | oeis/172/A172061.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/172/A172061.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/172/A172061.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A172061: Expansion of (2/(3*sqrt(1-4*z)-1+4*z))*((1-sqrt(1-4*z))/(2*z))^k with k=4.
; Submitted by Christian Krause
; 1,5,22,91,367,1461,5776,22748,89402,350974,1377174,5403193,21201211,83211277,326703424,1283211208,5042294926,19822108582,77958648604,306739666198,1207433301046,4754874514690,18732340230592,73827134976216,291074880228892,1148026377788456,4529509677475238,17877080676546325,70580084564713299,278741872200951613,1101162071961821440,4351350203250301648,17199491236276765718,68001920803974873838,268928143450399049556,1063791517970705910714,4208990110276101809698,16656989889757989152246
mov $3,$0
mov $5,$0
add $5,1
lpb $5
mov $0,$3
mov $2,$1
sub $5,1
sub $0,$5
add $2,$3
add $0,$2
bin $0,$2
mov $1,4
mul $4,-1
add $4,$0
lpe
mov $0,$4
| 36.761905 | 484 | 0.770725 |
5f1926590f3a2d70ce34edb5551795f912bc6922 | 9,292 | dart | Dart | example/lib/main.dart | wenchaosong/CityPicker | ff8cf8f9cf4ddd79a4ba39f55270b33452a6fd65 | [
"BSD-2-Clause"
] | 14 | 2021-03-13T07:07:51.000Z | 2022-03-24T03:19:58.000Z | example/lib/main.dart | wenchaosong/CityPicker | ff8cf8f9cf4ddd79a4ba39f55270b33452a6fd65 | [
"BSD-2-Clause"
] | 7 | 2021-03-16T02:23:11.000Z | 2022-03-25T01:05:52.000Z | example/lib/main.dart | wenchaosong/CityPicker | ff8cf8f9cf4ddd79a4ba39f55270b33452a6fd65 | [
"BSD-2-Clause"
] | 5 | 2021-06-08T11:26:44.000Z | 2022-02-10T23:48:19.000Z | import 'dart:async';
import 'package:city_picker_example/http/http_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_city_picker/city_picker.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:provider/provider.dart';
import 'provider/theme_provider.dart';
import 'view/item_text.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: ThemeProvider()),
],
child: Consumer<ThemeProvider>(
builder: (context, themeProvider, _) {
Color color = themeProvider.themeColor;
return MaterialApp(
title: 'CityPickerExample',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: color,
dialogBackgroundColor: Colors.white,
),
home: HomeWidget(),
);
},
),
);
}
}
class HomeWidget extends StatefulWidget {
@override
HomeWidgetState createState() => HomeWidgetState();
}
class HomeWidgetState extends State<HomeWidget> implements CityPickerListener {
String _address = "请选择地区";
Color _themeColor = Colors.blue;
Color _backgroundColor = Colors.white;
double _height = 400.0;
double _opacity = 0.5;
double _corner = 20;
bool _dismissible = true;
bool _showTabIndicator = true;
@override
void initState() {
super.initState();
}
void show() {
CityPicker.show(
context: context,
theme: ThemeData(
dialogBackgroundColor: _backgroundColor,
),
duration: 200,
opacity: _opacity,
dismissible: _dismissible,
height: _height,
titleHeight: 50,
corner: _corner,
paddingLeft: 15,
titleWidget: Container(
padding: EdgeInsets.only(left: 15),
child: Text(
'请选择地址',
style: TextStyle(
color: Colors.black54,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
closeWidget: Icon(Icons.close),
tabHeight: 40,
showTabIndicator: _showTabIndicator,
tabIndicatorColor: Theme.of(context).primaryColor,
tabIndicatorHeight: 2,
labelTextSize: 15,
selectedLabelColor: Theme.of(context).primaryColor,
unselectedLabelColor: Colors.black54,
itemHeadHeight: 30,
itemHeadLineColor: Colors.black,
itemHeadLineHeight: 0.1,
itemHeadTextStyle: TextStyle(fontSize: 15, color: Colors.black),
itemHeight: 40,
indexBarWidth: 28,
indexBarItemHeight: 20,
indexBarBackgroundColor: Colors.black12,
indexBarTextStyle: TextStyle(fontSize: 14, color: Colors.black54),
itemSelectedIconWidget:
Icon(Icons.done, color: Theme.of(context).primaryColor, size: 16),
itemSelectedTextStyle: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Theme.of(context).primaryColor),
itemUnSelectedTextStyle: TextStyle(fontSize: 14, color: Colors.black54),
cityPickerListener: this,
);
}
Widget _buildTheme() {
return InkWell(
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('选择颜色'),
content: SingleChildScrollView(
child: BlockPicker(
pickerColor: _themeColor,
onColorChanged: (color) {
setState(() {
_themeColor = color;
});
Provider.of<ThemeProvider>(context, listen: false)
.setTheme(color);
},
),
),
);
},
);
},
child: Container(
color: _themeColor,
width: double.infinity,
padding: EdgeInsets.all(10),
margin: EdgeInsets.fromLTRB(80, 10, 80, 10),
),
);
}
Widget _buildColor() {
return InkWell(
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('选择颜色'),
content: SingleChildScrollView(
child: BlockPicker(
pickerColor: _backgroundColor,
onColorChanged: (color) {
setState(() {
_backgroundColor = color;
});
},
),
),
);
},
);
},
child: Container(
color: _backgroundColor,
width: double.infinity,
padding: EdgeInsets.all(10),
margin: EdgeInsets.fromLTRB(80, 10, 80, 10),
),
);
}
Widget _buildOpacity() {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: Slider(
value: _opacity,
min: 0.01,
max: 1.0,
divisions: 100,
activeColor: Theme.of(context).primaryColor,
inactiveColor: Colors.grey,
onChanged: (double) {
setState(() {
_opacity = double.toDouble();
});
},
),
),
Text("${_opacity.toStringAsFixed(2)}")
],
);
}
Widget _buildDismissible() {
return Container(
alignment: Alignment.centerRight,
child: Switch(
value: _dismissible,
activeColor: Theme.of(context).primaryColor,
onChanged: (bool val) {
setState(() {
_dismissible = !_dismissible;
});
},
));
}
Widget _buildHeight() {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: Slider(
value: _height,
min: 200,
max: 500,
divisions: 100,
activeColor: Theme.of(context).primaryColor,
inactiveColor: Colors.grey,
onChanged: (double) {
setState(() {
_height = double.toDouble();
});
},
),
),
Text("${_height.toStringAsFixed(2)}")
],
);
}
Widget _buildCorner() {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: Slider(
value: _corner,
min: 0.0,
max: 30,
divisions: 100,
activeColor: Theme.of(context).primaryColor,
inactiveColor: Colors.grey,
onChanged: (double) {
setState(() {
_corner = double.toDouble();
});
},
),
),
Text("${_corner.toStringAsFixed(2)}")
],
);
}
Widget _buildIndicator() {
return Container(
alignment: Alignment.centerRight,
child: Switch(
value: _showTabIndicator,
activeColor: Theme.of(context).primaryColor,
onChanged: (bool val) {
setState(() {
_showTabIndicator = !_showTabIndicator;
});
},
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('城市选择器'),
backgroundColor: Theme.of(context).primaryColor,
),
body: SingleChildScrollView(
child: Column(
children: [
ItemTextWidget(
title: '选择城市',
subWidget: InkWell(
onTap: () => show(),
child: Padding(
padding: EdgeInsets.fromLTRB(0, 15, 0, 15),
child: Text(_address),
),
),
),
ItemTextWidget(title: '主题颜色', subWidget: _buildTheme()),
ItemTextWidget(title: '透明度', subWidget: _buildOpacity()),
ItemTextWidget(title: '外部点击消失', subWidget: _buildDismissible()),
ItemTextWidget(title: '弹窗背景颜色', subWidget: _buildColor()),
ItemTextWidget(title: '弹窗高度', subWidget: _buildHeight()),
ItemTextWidget(title: '顶部圆角', subWidget: _buildCorner()),
ItemTextWidget(title: '显示 Indicator', subWidget: _buildIndicator()),
],
),
),
);
}
@override
Future<List<City>> loadProvinceData() async {
print("loadProvinceData");
return HttpUtils.getCityData("");
}
@override
Future<List<City>> onProvinceSelected(
String? provinceCode, String? provinceName) async {
print("onProvinceSelected --- provinceName: $provinceName");
return HttpUtils.getCityData(provinceName!);
}
@override
Future<List<City>> onCitySelected(String? cityCode, String? cityName) async {
print("onCitySelected --- cityName: $cityName");
return HttpUtils.getCityData(cityName!);
}
@override
void onFinish(String? provinceCode, String? provinceName, String? cityCode,
String? cityName, String? districtCode, String? districtName) {
print("onFinish");
setState(() {
_address = provinceName! + " " + cityName! + " " + districtName!;
});
}
}
| 27.654762 | 80 | 0.543048 |
31b39b8c35eb16e012347910786940a7af8febcc | 312 | swift | Swift | Hackatrix/View/Cell/InteractionCell.swift | belatrix/BelatrixEventsIOS | b7f52f752704555e88874b732c4b2cf1f8d33ec6 | [
"Apache-2.0"
] | 1 | 2017-05-23T18:20:54.000Z | 2017-05-23T18:20:54.000Z | Hackatrix/View/Cell/InteractionCell.swift | belatrix/BelatrixEventsIOS | b7f52f752704555e88874b732c4b2cf1f8d33ec6 | [
"Apache-2.0"
] | 2 | 2018-04-11T18:14:55.000Z | 2018-04-24T13:37:20.000Z | Hackatrix/View/Cell/InteractionCell.swift | belatrix/BelatrixEventsIOS | b7f52f752704555e88874b732c4b2cf1f8d33ec6 | [
"Apache-2.0"
] | null | null | null | //
// InteractionCell.swift
// Hackatrix
//
// Created by Erik Fernando Flores Quispe on 11/05/17.
// Copyright © 2017 Belatrix. All rights reserved.
//
import UIKit
class InteractionCell: UITableViewCell {
@IBOutlet weak var nameProject: UILabel!
@IBOutlet weak var numberOfVote: UILabel!
}
| 18.352941 | 55 | 0.708333 |
39ee94c1b9d066ef47b6b173046065a152ea1bc2 | 2,505 | java | Java | examples/com/theprogrammingturkey/nhlapi/ShotLocationExample.java | SirAlexJz/NHLStatsAPI-Java | 8859f254d561568dab06c610789f3d59dcb9b424 | [
"MIT"
] | 2 | 2018-11-29T14:32:27.000Z | 2019-03-07T06:03:10.000Z | examples/com/theprogrammingturkey/nhlapi/ShotLocationExample.java | Turkey2349/NHLStatsAPI-Java | 1e5f8a057b7d2344500b7016a1ef964261aace49 | [
"MIT"
] | null | null | null | examples/com/theprogrammingturkey/nhlapi/ShotLocationExample.java | Turkey2349/NHLStatsAPI-Java | 1e5f8a057b7d2344500b7016a1ef964261aace49 | [
"MIT"
] | 1 | 2021-01-26T02:44:01.000Z | 2021-01-26T02:44:01.000Z | package com.theprogrammingturkey.nhlapi;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.theprogrammingturkey.nhlapi.criteria.SerchCriteria;
import com.theprogrammingturkey.nhlapi.data.GameData;
import com.theprogrammingturkey.nhlapi.data.PlayData;
import com.theprogrammingturkey.nhlapi.managers.GameManager;
public class ShotLocationExample extends JPanel
{
private static final long serialVersionUID = 1L;
private static Map<String, Integer> locations = new HashMap<>();
private static int max = 0;
private static BufferedImage image;
public static void main(String[] args) throws IOException
{
NHLAPI.DEBUG = true;
image = ImageIO.read(new File("examples/res/rink.png"));
SerchCriteria criteria = new SerchCriteria();
criteria.setStartDate("2017-10-02");
criteria.setEndDate("2018-02-11");
System.out.println("Collecting game data...");
List<GameData> games = GameManager.getGames(criteria);
System.out.println("Parsing game data...");
for(GameData game : games)
{
for(PlayData play : game.plays)
{
if(play.event.equalsIgnoreCase("shot"))
{
int x = play.xCoord;
int y = play.yCoord;
if(x < 0)
{
x = Math.abs(x);
y *= -1;
}
String key = x + "," + y;
int count = 1;
if(locations.containsKey(key))
count = locations.get(key) + 1;
if(count > max)
max = count;
locations.put(key, count);
}
}
}
JFrame f = new JFrame("Shot chart");
f.setLayout(null);
f.setSize(800, 800);
JPanel panel = new ShotLocationExample();
panel.setSize(800, 800);
panel.setBounds(0, 0, 800, 800);
panel.setVisible(true);
panel.setBackground(Color.GREEN);
f.add(panel);
f.setVisible(true);
}
// X: -99-99
// Y: -41-42
public void paintComponent(Graphics g)
{
// super.paintComponents(g);
// TODO: Needs some tweaking of positions
g.drawImage(image, 0, 0, null);
for(String pos : locations.keySet())
{
int x = Integer.parseInt(pos.substring(0, pos.indexOf(",")));
int y = Integer.parseInt(pos.substring(pos.indexOf(",") + 1));
int alpha = (int) (((double) locations.get(pos) / max) * 255);
g.setColor(new Color(alpha, 255 - alpha, 0, 100));
g.fillRect((x * 8) + 350, (y * 8), 8, 8);
}
}
}
| 25.05 | 65 | 0.677046 |
4081c32fe5ca1b8512fab470fbc16a9a0353a934 | 2,017 | py | Python | scripts/data_handeling/calculate_areas_from_json.py | dekelmeirom/pathologylab | 262b0bd9cb9233bc960671c2d674cf895b228f39 | [
"MIT"
] | null | null | null | scripts/data_handeling/calculate_areas_from_json.py | dekelmeirom/pathologylab | 262b0bd9cb9233bc960671c2d674cf895b228f39 | [
"MIT"
] | null | null | null | scripts/data_handeling/calculate_areas_from_json.py | dekelmeirom/pathologylab | 262b0bd9cb9233bc960671c2d674cf895b228f39 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import json
import numpy as np
import os
import csv
import argparse
def poly_area(x, y, absoluteValue = True):
result = 0.5 * np.abs(np.dot(x[:-1], y[1:]) + x[-1]*y[0] - np.dot(y[:-1], x[1:]) - y[-1]*x[0])
if absoluteValue:
return abs(result)
else:
return result
def calculate_areas_from_json(json_path, output_path):
with open(json_path) as json_file:
json_data = json.load(json_file)
images = json_data["_via_img_metadata"]
images_names = list(images.keys())
with open(os.path.join(output_path, "PDL_areas.csv"), mode='w', newline='') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',')
csv_writer.writerow(["image_name", "positive area", "negative area"])
for image_name in images_names:
image = images[image_name]
positive_area = 0
negative_area = 0
for region in image['regions']:
area = poly_area(region["shape_attributes"]["all_points_x"], region["shape_attributes"]["all_points_y"])
if region['region_attributes']['type'] == '2':
negative_area += area
elif region['region_attributes']['type'] == '3':
positive_area += area
csv_writer.writerow([image_name, positive_area, negative_area])
def main():
parser = argparse.ArgumentParser(description='This script is ...'
, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("--input", "-i", default="./CCD_Project.json",
help="Path to where the json file is saved. default='./CCD_Project.json'")
parser.add_argument("--output", "-o", default="./output",
help="Directory name where the result csv file will be saved. default='./output'")
args = parser.parse_args()
calculate_areas_from_json(args.input, args.output)
return
if __name__ == "__main__":
main()
| 38.056604 | 120 | 0.60585 |
ffe0fcd0b445d013809c89db9f9e20e70c01a452 | 864 | html | HTML | web/app/themes/trendsinhr/styleguide/build/components/render/hero-whitepaper.html | tommyseijkens/trendsinhr_composer | 3d4f64d0cdb54b5c35dfe4b0affa45d13a3be40e | [
"MIT"
] | null | null | null | web/app/themes/trendsinhr/styleguide/build/components/render/hero-whitepaper.html | tommyseijkens/trendsinhr_composer | 3d4f64d0cdb54b5c35dfe4b0affa45d13a3be40e | [
"MIT"
] | null | null | null | web/app/themes/trendsinhr/styleguide/build/components/render/hero-whitepaper.html | tommyseijkens/trendsinhr_composer | 3d4f64d0cdb54b5c35dfe4b0affa45d13a3be40e | [
"MIT"
] | null | null | null |
<div class="page-header page-header--whitepaper">
<div class="page-header__image">
<div class="page-header__background-image" style="background-image: url('https://assets.driessengroep.nl/sampledata/trendsinhr/cover.png');"></div>
<div class="page-header__background-image" style="background-image: url('https://assets.driessengroep.nl/sampledata/trendsinhr/cover.png');"></div>
</div>
<div class="container d-flex flex-column justify-content-end h-100">
<div class="row">
<div class="container-content">
<div>
<div class="labels">
<div class="label">Whitepaper</div>
</div>
<h1 class="display-2">Het wordt een mooie dag</h1>
</div>
</div>
</div>
</div>
</div>
</div>
| 36 | 155 | 0.560185 |
cba01fddf3240e923ff46443e78cff725b1f3398 | 2,306 | go | Go | p2p/infra/mem/peer_repository.go | hea9549/engine | 6f6b59046cd14d9282992007cf918bf5770872e4 | [
"Apache-2.0"
] | null | null | null | p2p/infra/mem/peer_repository.go | hea9549/engine | 6f6b59046cd14d9282992007cf918bf5770872e4 | [
"Apache-2.0"
] | null | null | null | p2p/infra/mem/peer_repository.go | hea9549/engine | 6f6b59046cd14d9282992007cf918bf5770872e4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 It-chain
*
* 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
*
* https://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 mem
import (
"errors"
"sync"
"github.com/it-chain/engine/p2p"
)
var ErrPeerExists = errors.New("peer already exists")
type PeerRepository struct {
mux sync.RWMutex
pLTable p2p.PLTable
}
func NewPeerReopository() PeerRepository {
return PeerRepository{
mux: sync.RWMutex{},
pLTable: *p2p.NewPLTable(p2p.Leader{p2p.LeaderId{""}}, make(map[string]p2p.Peer)),
}
}
func (pr *PeerRepository) GetPLTable() (p2p.PLTable, error) {
pr.mux.Lock()
defer pr.mux.Unlock()
return pr.pLTable, nil
}
func (pr *PeerRepository) GetLeader() (p2p.Leader, error) {
return pr.pLTable.Leader, nil
}
func (pr *PeerRepository) FindPeerById(peerId p2p.PeerId) (p2p.Peer, error) {
pr.mux.Lock()
defer pr.mux.Unlock()
v, exist := pr.pLTable.PeerTable[peerId.Id]
if peerId.Id == "" {
return v, p2p.ErrEmptyPeerId
}
//no matching id
if !exist {
return v, p2p.ErrNoMatchingPeerId
}
return v, nil
}
func (pr *PeerRepository) FindPeerByAddress(ipAddress string) (p2p.Peer, error) {
pr.mux.Lock()
defer pr.mux.Unlock()
for _, peer := range pr.pLTable.PeerTable {
if peer.IpAddress == ipAddress {
return peer, nil
}
}
return p2p.Peer{}, nil
}
func (pr *PeerRepository) Save(peer p2p.Peer) error {
pr.mux.Lock()
defer pr.mux.Unlock()
_, exist := pr.pLTable.PeerTable[peer.PeerId.Id]
if exist {
return ErrPeerExists
}
pr.pLTable.PeerTable[peer.PeerId.Id] = peer
return nil
}
func (pr *PeerRepository) SetLeader(leader p2p.Leader) error {
pr.mux.Lock()
defer pr.mux.Unlock()
pr.pLTable.Leader = leader
return nil
}
func (pr *PeerRepository) Remove(id string) error {
pr.mux.Lock()
defer pr.mux.Unlock()
delete(pr.pLTable.PeerTable, id)
return nil
}
| 19.216667 | 84 | 0.70425 |
b9b37c9eba5c81dbf70a073cf7afd57e37c98e59 | 535 | sql | SQL | sql-scripts/for-json-path.sql | dotnetthailand/orchardcore-blog | 3f9570c1100c5cdd6a09065cb3d47202eca00a40 | [
"MIT"
] | 1 | 2021-11-20T05:14:09.000Z | 2021-11-20T05:14:09.000Z | sql-scripts/for-json-path.sql | dotnetthailand/orchard-core-blog-example | 3f9570c1100c5cdd6a09065cb3d47202eca00a40 | [
"MIT"
] | null | null | null | sql-scripts/for-json-path.sql | dotnetthailand/orchard-core-blog-example | 3f9570c1100c5cdd6a09065cb3d47202eca00a40 | [
"MIT"
] | 1 | 2022-01-07T14:08:37.000Z | 2022-01-07T14:08:37.000Z | -- Nested object
SELECT
t.ContentItemId,
t.Title as 'TitlePart.Title',
m.Markdown as 'MarkdownBodyPart.Html'
FROM TitlePart t
INNER join MarkdownBodyPart m
ON t.ContentItemId = m.ContentItemId
FOR JSON PATH;
-- With root option
SELECT
t.ContentItemId,
t.Title as 'TitlePart.Title',
m.Markdown as 'MarkdownBodyPart.Html'
FROM TitlePart t
INNER join MarkdownBodyPart m
ON t.ContentItemId = m.ContentItemId
FOR JSON PATH, ROOT('BlogPosts');
-- Auto
SELECT
t.ContentItemId,
t.Title
FROM TitlePart t
FOR JSON AUTO
| 19.814815 | 39 | 0.751402 |
61bc6a25004ccf935d94a28940b6ef7b8555c931 | 348 | asm | Assembly | programs/oeis/173/A173674.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/173/A173674.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/173/A173674.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A173674: a(n) = ceiling(A003269(n)/2).
; 0,1,1,1,1,1,2,2,3,4,5,7,10,13,18,25,35,48,66,91,125,173,238,329,454,626,864,1193,1646,2272,3136,4329,5975,8247,11383,15711,21686,29932,41315,57026,78711,108643,149958,206983,285694,394337,544295,751278,1036972
seq $0,3269 ; a(n) = a(n-1) + a(n-4) with a(0) = 0, a(1) = a(2) = a(3) = 1.
add $0,1
div $0,2
| 49.714286 | 211 | 0.649425 |
85ab03ad646a63c666ef22f0c3adc7bcf0bcddab | 1,205 | js | JavaScript | bin/validate-dependents.js | boneskull/adhoc-validate-dependents | d35d284a48de607b7a2c18680fbb0dc769f9a99c | [
"Apache-2.0"
] | null | null | null | bin/validate-dependents.js | boneskull/adhoc-validate-dependents | d35d284a48de607b7a2c18680fbb0dc769f9a99c | [
"Apache-2.0"
] | 1 | 2021-08-31T17:59:19.000Z | 2021-08-31T17:59:19.000Z | bin/validate-dependents.js | boneskull/adhoc-validate-dependents | d35d284a48de607b7a2c18680fbb0dc769f9a99c | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env node
import {
validateDependents,
getDownloadCounts
} from '../src/validate-dependents.js';
import {promisify} from 'util';
import {createRequire} from 'module';
const require = createRequire(import.meta.url);
const stringify = require('csv-stringify');
const dayjs = require('dayjs');
(async () => {
const stringifyAsync = promisify(stringify);
const [dependencyName, csvFilepath] = process.argv.slice(2);
if (!dependencyName && csvFilepath) {
console.error('Usage: validate-dependents.js <dependency-name> <path-to.csv>');
process.exitCode = 1;
return;
}
const startDate = dayjs()
.subtract(1, 'month')
.toDate();
const data = await validateDependents(dependencyName, csvFilepath, {
startDate
});
const dependencyDownloadCount = await getDownloadCounts(
dependencyName,
startDate
);
data.unshift({
name: dependencyName,
downloadCount: dependencyDownloadCount,
description: 'DOWNLOAD COUNT FOR DEPENDENCY'
});
const output = await stringifyAsync(data, {
header: true,
columns: [
'name',
{key: 'downloadCount', header: 'downloads'},
'description'
]
});
console.log(output);
})();
| 25.104167 | 83 | 0.678008 |
a110f4c263ca3096ad879cfa79d597c682b01c91 | 84 | swift | Swift | Day 13/Variables and constants.playground/Contents.swift | PetroOnishchuk/100-Days-Of-SwiftUI | 21d16e893bedc3b1bfa87bd61d54e10b0eaea0ef | [
"MIT"
] | 55 | 2020-01-13T13:34:06.000Z | 2022-03-14T22:01:33.000Z | Day 13/Variables and constants.playground/Contents.swift | PetroOnishchuk/100-Days-Of-SwiftUI | 21d16e893bedc3b1bfa87bd61d54e10b0eaea0ef | [
"MIT"
] | 1 | 2020-04-09T12:24:04.000Z | 2020-04-09T12:25:33.000Z | Day 13/Variables and constants.playground/Contents.swift | PetroOnishchuk/100-Days-Of-SwiftUI | 21d16e893bedc3b1bfa87bd61d54e10b0eaea0ef | [
"MIT"
] | 7 | 2020-06-29T11:07:45.000Z | 2022-03-18T17:14:24.000Z | import UIKit
// Variables and constants
var name = "Tim McGraw"
name = "Romeo"
| 8.4 | 26 | 0.678571 |
ddd8fa602d4f103181bcf68bee76fc04657f0adb | 748 | dart | Dart | lib/config/firebase_config.dart | drinkbarleyalex/flutter-template-1a | 03e2720ded5eb012392a9088ac417f057173fe0f | [
"MIT"
] | null | null | null | lib/config/firebase_config.dart | drinkbarleyalex/flutter-template-1a | 03e2720ded5eb012392a9088ac417f057173fe0f | [
"MIT"
] | null | null | null | lib/config/firebase_config.dart | drinkbarleyalex/flutter-template-1a | 03e2720ded5eb012392a9088ac417f057173fe0f | [
"MIT"
] | null | null | null | import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_template/config/flavor_config.dart';
//todo decide when you need firebase in your project
bool shouldConfigureFirebase() =>
FlavorConfig.isInitialized() &&
(FlavorConfig.isStaging() || FlavorConfig.isProduction());
Future<void> configureFirebase() async {
if (!shouldConfigureFirebase()) {
return;
}
await Firebase.initializeApp();
await FirebaseCrashlytics.instance
.setCrashlyticsCollectionEnabled(kDebugMode ? false : true); //todo crashlytics in debug mode?
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
}
| 37.4 | 100 | 0.783422 |
b346e673cab3116f804b3deabf73c1f26994da86 | 3,210 | asm | Assembly | Transynther/x86/_processed/P/_zr_/i7-7700_9_0x48_notsx.log_14_1854.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/P/_zr_/i7-7700_9_0x48_notsx.log_14_1854.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/P/_zr_/i7-7700_9_0x48_notsx.log_14_1854.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r14
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x465f, %rax
nop
nop
nop
nop
and %r14, %r14
movw $0x6162, (%rax)
nop
nop
nop
add %rcx, %rcx
lea addresses_D_ht+0x18ed3, %rbx
clflush (%rbx)
nop
nop
nop
xor %rcx, %rcx
vmovups (%rbx), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $1, %xmm3, %rsi
nop
nop
add $51473, %r11
lea addresses_A_ht+0x1b3df, %rsi
lea addresses_WC_ht+0x10e1f, %rdi
dec %r12
mov $102, %rcx
rep movsw
nop
nop
nop
nop
nop
inc %rsi
lea addresses_D_ht+0x13b37, %rdi
clflush (%rdi)
nop
and %rcx, %rcx
mov (%rdi), %si
add $26564, %rdi
lea addresses_A_ht+0x165df, %r11
nop
nop
nop
sub $42775, %rdi
mov (%r11), %r14w
nop
nop
nop
nop
xor $145, %rsi
lea addresses_A_ht+0x1e75f, %rcx
nop
nop
nop
nop
nop
dec %rax
mov $0x6162636465666768, %rsi
movq %rsi, %xmm7
movups %xmm7, (%rcx)
nop
nop
nop
dec %rdi
lea addresses_D_ht+0xbd13, %rax
nop
nop
nop
nop
nop
dec %rsi
mov $0x6162636465666768, %rdi
movq %rdi, %xmm7
vmovups %ymm7, (%rax)
nop
nop
cmp %rcx, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r14
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r14
push %r8
push %rax
push %rbp
push %rdx
// Load
lea addresses_D+0xc19f, %rbp
nop
nop
nop
nop
and %r10, %r10
mov (%rbp), %r14d
xor %r10, %r10
// Store
lea addresses_D+0x12e1f, %r14
nop
cmp %rdx, %rdx
mov $0x5152535455565758, %r11
movq %r11, %xmm1
vmovups %ymm1, (%r14)
nop
nop
nop
lfence
// Faulty Load
mov $0x61f, %rax
nop
nop
nop
nop
and $42687, %r8
mov (%rax), %bp
lea oracles, %r10
and $0xff, %rbp
shlq $12, %rbp
mov (%r10,%rbp,1), %rbp
pop %rdx
pop %rbp
pop %rax
pop %r8
pop %r14
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_P', 'congruent': 0}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_D', 'congruent': 5}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_D', 'congruent': 9}, 'OP': 'STOR'}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_P', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_A_ht', 'congruent': 6}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_D_ht', 'congruent': 0}}
{'dst': {'same': False, 'congruent': 11, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_A_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 2, 'type': 'addresses_D_ht', 'congruent': 1}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_A_ht', 'congruent': 6}}
{'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_A_ht', 'congruent': 6}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_D_ht', 'congruent': 1}, 'OP': 'STOR'}
{'00': 14}
00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
| 18.77193 | 148 | 0.645171 |
402226f59cbd484dbe01bb6fc1a1a095314d903d | 301 | py | Python | bindings/python/setup.py | wangjia3015/marisa-trie | da2924831c1e8f90dae7223cfe7a2bc1bd8b5132 | [
"BSD-2-Clause"
] | 388 | 2016-01-28T15:16:43.000Z | 2022-03-28T08:18:07.000Z | bindings/python/setup.py | wangjia3015/marisa-trie | da2924831c1e8f90dae7223cfe7a2bc1bd8b5132 | [
"BSD-2-Clause"
] | 38 | 2016-02-12T14:51:12.000Z | 2022-02-12T09:10:25.000Z | bindings/python/setup.py | wangjia3015/marisa-trie | da2924831c1e8f90dae7223cfe7a2bc1bd8b5132 | [
"BSD-2-Clause"
] | 79 | 2016-03-16T15:47:50.000Z | 2022-03-15T22:21:08.000Z | from distutils.core import setup, Extension
marisa_module = Extension("_marisa",
sources=["marisa-swig_wrap.cxx", "marisa-swig.cxx"],
libraries=["marisa"])
setup(name = "marisa",
ext_modules = [marisa_module],
py_modules = ["marisa"])
| 30.1 | 78 | 0.578073 |
4006ccf8f0bb2d326fae0e66b44388e3d4178066 | 4,111 | swift | Swift | FormsExample/RegisterViewController.swift | stuaustin/FormsExample | a6c7b23b4c587dd62f528ad8c6b74547ff8a3e28 | [
"MIT"
] | null | null | null | FormsExample/RegisterViewController.swift | stuaustin/FormsExample | a6c7b23b4c587dd62f528ad8c6b74547ff8a3e28 | [
"MIT"
] | null | null | null | FormsExample/RegisterViewController.swift | stuaustin/FormsExample | a6c7b23b4c587dd62f528ad8c6b74547ff8a3e28 | [
"MIT"
] | null | null | null | //
// RegisterViewController.swift
//
// Copyright (c) 2019 Stuart Austin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
final class RegisterViewController: UIViewController {
let viewModel: RegisterViewModel
private lazy var registerView = RegisterView(frame: UIScreen.main.bounds)
// MARK: - Notifications
private let keyboardHandler = ScrollViewKeyboardHandler()
// MARK: - Initialization
init(viewModel: RegisterViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
viewModel.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View lifecycle
override func loadView() {
view = registerView
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Create Account"
keyboardHandler.scrollView = registerView.scrollView
registerView.firstNameItem.textField.addTarget(self, action: #selector(textFieldEditingChanged), for: .editingChanged)
registerView.lastNameItem.textField.addTarget(self, action: #selector(textFieldEditingChanged), for: .editingChanged)
registerView.emailItem.textField.addTarget(self, action: #selector(textFieldEditingChanged), for: .editingChanged)
registerView.passwordItem.textField.addTarget(self, action: #selector(textFieldEditingChanged), for: .editingChanged)
registerView.termsItem.addTarget(self, action: #selector(checkboxItemValueChanged(sender:)), for: .valueChanged)
registerView.privacyItem.addTarget(self, action: #selector(checkboxItemValueChanged(sender:)), for: .valueChanged)
registerView.createAccountButton.isEnabled = viewModel.isRegisterButtonEnabled
}
}
// MARK: - UIControl events
extension RegisterViewController {
@objc private func textFieldEditingChanged(sender: UITextField) {
if sender === registerView.firstNameItem.textField {
viewModel.formInformation.firstName = sender.text ?? ""
} else if sender === registerView.lastNameItem.textField {
viewModel.formInformation.lastName = sender.text ?? ""
} else if sender === registerView.emailItem.textField {
viewModel.formInformation.email = sender.text ?? ""
} else if sender === registerView.passwordItem.textField {
viewModel.formInformation.password = sender.text ?? ""
}
}
@objc private func checkboxItemValueChanged(sender: CheckboxItemView) {
if sender == registerView.termsItem {
viewModel.formInformation.acceptTerms = sender.isSelected
} else if sender == registerView.privacyItem {
viewModel.formInformation.acceptPrivacy = sender.isSelected
}
}
}
// MARK: - RegisterViewModelDelegate
extension RegisterViewController: RegisterViewModelDelegate {
func isRegisterButtonEnabledDidChange() {
registerView.createAccountButton.isEnabled = viewModel.isRegisterButtonEnabled
}
}
| 39.528846 | 126 | 0.721965 |
be18d3efab6d4887f4a4cc15f3d7bad40111e705 | 83,544 | rs | Rust | contracts/tg4-stake/src/contract.rs | confio/poe-contracts | c320b857d2514fa0c68a929a42fca86f7f2e4b93 | [
"RSA-MD"
] | 4 | 2022-01-17T10:29:39.000Z | 2022-03-31T16:43:24.000Z | contracts/tg4-stake/src/contract.rs | confio/poe-contracts | c320b857d2514fa0c68a929a42fca86f7f2e4b93 | [
"RSA-MD"
] | 75 | 2022-01-17T14:06:02.000Z | 2022-03-31T06:57:39.000Z | contracts/tg4-stake/src/contract.rs | confio/poe-contracts | c320b857d2514fa0c68a929a42fca86f7f2e4b93 | [
"RSA-MD"
] | null | null | null | #[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{
coin, coins, to_binary, Addr, BankMsg, Binary, Coin, CustomQuery, Decimal, Deps, DepsMut,
Empty, Env, MessageInfo, Order, StdResult, Storage, Uint128,
};
use std::cmp::min;
use std::ops::Sub;
use cw2::set_contract_version;
use cw_storage_plus::Bound;
use cw_utils::maybe_addr;
use tg4::{
HooksResponse, Member, MemberChangedHookMsg, MemberDiff, MemberInfo, MemberListResponse,
MemberResponse,
};
use tg_bindings::{
request_privileges, Privilege, PrivilegeChangeMsg, TgradeMsg, TgradeQuery, TgradeSudoMsg,
};
use tg_utils::{
ensure_from_older_version, members, validate_portion, Duration, ADMIN, HOOKS, PREAUTH_HOOKS,
PREAUTH_SLASHING, SLASHERS, TOTAL,
};
use crate::error::ContractError;
use crate::msg::{
ClaimsResponse, ExecuteMsg, InstantiateMsg, PreauthResponse, QueryMsg, StakedResponse,
TotalPointsResponse, UnbondingPeriodResponse,
};
use crate::state::{claims, Config, CONFIG, STAKE, STAKE_VESTING};
pub type Response = cosmwasm_std::Response<TgradeMsg>;
pub type SubMsg = cosmwasm_std::SubMsg<TgradeMsg>;
// version info for migration info
const CONTRACT_NAME: &str = "crates.io:tg4-stake";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
// Note, you can use StdResult in some functions where you do not
// make use of the custom errors
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
mut deps: DepsMut<TgradeQuery>,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
let api = deps.api;
ADMIN.set(deps.branch(), maybe_addr(api, msg.admin)?)?;
PREAUTH_HOOKS.set_auth(deps.storage, msg.preauths_hooks)?;
PREAUTH_SLASHING.set_auth(deps.storage, msg.preauths_slashing)?;
// min_bond is at least 1, so 0 stake -> non-membership
let min_bond = if msg.min_bond == Uint128::zero() {
Uint128::new(1)
} else {
msg.min_bond
};
let config = Config {
denom: msg.denom,
tokens_per_point: msg.tokens_per_point,
min_bond,
unbonding_period: Duration::new(msg.unbonding_period),
auto_return_limit: msg.auto_return_limit,
};
CONFIG.save(deps.storage, &config)?;
TOTAL.save(deps.storage, &0)?;
SLASHERS.instantiate(deps.storage)?;
Ok(Response::default())
}
// And declare a custom Error variant for the ones where you will want to make use of it
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut<TgradeQuery>,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
let api = deps.api;
match msg {
ExecuteMsg::UpdateAdmin { admin } => ADMIN
.execute_update_admin(deps, info, maybe_addr(api, admin)?)
.map_err(Into::into),
ExecuteMsg::AddHook { addr } => execute_add_hook(deps, info, addr),
ExecuteMsg::RemoveHook { addr } => execute_remove_hook(deps, info, addr),
ExecuteMsg::Bond { vesting_tokens } => execute_bond(deps, env, info, vesting_tokens),
ExecuteMsg::Unbond {
tokens: Coin { amount, denom },
} => execute_unbond(deps, env, info, amount, denom),
ExecuteMsg::Claim {} => execute_claim(deps, env, info),
ExecuteMsg::AddSlasher { addr } => execute_add_slasher(deps, info, addr),
ExecuteMsg::RemoveSlasher { addr } => execute_remove_slasher(deps, info, addr),
ExecuteMsg::Slash { addr, portion } => execute_slash(deps, env, info, addr, portion),
}
}
pub fn execute_add_hook<Q: CustomQuery>(
deps: DepsMut<Q>,
info: MessageInfo,
hook: String,
) -> Result<Response, ContractError> {
// custom guard: using a preauth OR being admin
if !ADMIN.is_admin(deps.as_ref(), &info.sender)? {
PREAUTH_HOOKS.use_auth(deps.storage)?;
}
// add the hook
HOOKS.add_hook(deps.storage, deps.api.addr_validate(&hook)?)?;
// response
let res = Response::new()
.add_attribute("action", "add_hook")
.add_attribute("hook", hook)
.add_attribute("sender", info.sender);
Ok(res)
}
pub fn execute_remove_hook<Q: CustomQuery>(
deps: DepsMut<Q>,
info: MessageInfo,
hook: String,
) -> Result<Response, ContractError> {
// custom guard: self-removal OR being admin
let hook_addr = deps.api.addr_validate(&hook)?;
if info.sender != hook_addr && !ADMIN.is_admin(deps.as_ref(), &info.sender)? {
return Err(ContractError::Unauthorized(
"Hook address is not same as sender's and sender is not an admin".to_owned(),
));
}
// remove the hook
HOOKS.remove_hook(deps.storage, hook_addr)?;
// response
let res = Response::new()
.add_attribute("action", "remove_hook")
.add_attribute("hook", hook)
.add_attribute("sender", info.sender);
Ok(res)
}
pub fn execute_bond<Q: CustomQuery>(
deps: DepsMut<Q>,
env: Env,
info: MessageInfo,
vesting_tokens: Option<Coin>,
) -> Result<Response, ContractError> {
let cfg = CONFIG.load(deps.storage)?;
let amount = validate_funds(&info.funds, &cfg.denom)?;
let vesting_amount = vesting_tokens
.map(|v| validate_funds(&[v], &cfg.denom))
.transpose()?
.unwrap_or_default();
if amount + vesting_amount == Uint128::zero() {
return Err(ContractError::NoFunds {});
}
// update the sender's stake
let new_stake = STAKE.update(deps.storage, &info.sender, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default() + amount)
})?;
let mut res = Response::new()
.add_attribute("action", "bond")
.add_attribute("amount", amount)
.add_attribute("sender", &info.sender);
// Update the sender's vesting stake
let new_vesting_stake =
STAKE_VESTING.update(deps.storage, &info.sender, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default() + vesting_amount)
})?;
// Delegate (stake to contract) to sender's vesting account
if vesting_amount > Uint128::zero() {
let msg = TgradeMsg::Delegate {
funds: coin(vesting_amount.into(), cfg.denom.clone()),
staker: info.sender.to_string(),
};
res = res
.add_message(msg)
.add_attribute("vesting_amount", vesting_amount);
}
// Update membership messages
res = res.add_submessages(update_membership(
deps.storage,
info.sender,
new_stake + new_vesting_stake,
&cfg,
env.block.height,
)?);
Ok(res)
}
pub fn execute_unbond<Q: CustomQuery>(
deps: DepsMut<Q>,
env: Env,
info: MessageInfo,
amount: Uint128,
denom: String,
) -> Result<Response, ContractError> {
// provide them a claim
let cfg = CONFIG.load(deps.storage)?;
if cfg.denom != denom {
return Err(ContractError::InvalidDenom(denom));
}
// Load stake first for comparison
let stake = STAKE
.may_load(deps.storage, &info.sender)?
.unwrap_or_default();
// Reduce the sender's stake - saturating if insufficient
let new_stake = STAKE.update(deps.storage, &info.sender, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default().saturating_sub(amount))
})?;
let mut res = Response::new()
.add_attribute("action", "unbond")
.add_attribute("amount", amount)
.add_attribute("denom", &denom)
.add_attribute("sender", &info.sender);
// Reduce the sender's vesting stake - aborting if insufficient
let vesting_amount = amount.saturating_sub(stake);
let new_vesting_stake =
STAKE_VESTING.update(deps.storage, &info.sender, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default().checked_sub(vesting_amount)?)
})?;
// Undelegate (unstake from contract) to sender's vesting account
if vesting_amount > Uint128::zero() {
let msg = TgradeMsg::Undelegate {
funds: coin(vesting_amount.into(), cfg.denom.clone()),
recipient: info.sender.to_string(),
};
res = res
.add_message(msg)
.add_attribute("vesting_amount", vesting_amount);
}
// Create claim for unbonded liquid amount
let completion = cfg.unbonding_period.after(&env.block);
claims().create_claim(
deps.storage,
info.sender.clone(),
min(stake, amount),
completion,
env.block.height,
)?;
res = res.add_attribute("completion_time", completion.time().nanos().to_string());
// Update membership messages
res = res.add_submessages(update_membership(
deps.storage,
info.sender,
new_stake + new_vesting_stake,
&cfg,
env.block.height,
)?);
Ok(res)
}
pub fn execute_add_slasher<Q: CustomQuery>(
deps: DepsMut<Q>,
info: MessageInfo,
slasher: String,
) -> Result<Response, ContractError> {
// custom guard: using a preauth OR being admin
if !ADMIN.is_admin(deps.as_ref(), &info.sender)? {
PREAUTH_SLASHING.use_auth(deps.storage)?;
}
// add the slasher
SLASHERS.add_slasher(deps.storage, deps.api.addr_validate(&slasher)?)?;
// response
let res = Response::new()
.add_attribute("action", "add_slasher")
.add_attribute("slasher", slasher)
.add_attribute("sender", info.sender);
Ok(res)
}
pub fn execute_remove_slasher<Q: CustomQuery>(
deps: DepsMut<Q>,
info: MessageInfo,
slasher: String,
) -> Result<Response, ContractError> {
// custom guard: self-removal OR being admin
let slasher_addr = Addr::unchecked(&slasher);
if info.sender != slasher_addr && !ADMIN.is_admin(deps.as_ref(), &info.sender)? {
return Err(ContractError::Unauthorized(
"Only slasher might remove himself and sender is not an admin".to_owned(),
));
}
// remove the slasher
SLASHERS.remove_slasher(deps.storage, slasher_addr)?;
// response
let res = Response::new()
.add_attribute("action", "remove_slasher")
.add_attribute("slasher", slasher)
.add_attribute("sender", info.sender);
Ok(res)
}
pub fn execute_slash<Q: CustomQuery>(
deps: DepsMut<Q>,
env: Env,
info: MessageInfo,
addr: String,
portion: Decimal,
) -> Result<Response, ContractError> {
if !SLASHERS.is_slasher(deps.storage, &info.sender)? {
return Err(ContractError::Unauthorized(
"Sender is not on slashers list".to_owned(),
));
}
validate_portion(portion)?;
let cfg = CONFIG.load(deps.storage)?;
let addr = deps.api.addr_validate(&addr)?;
let liquid_stake = STAKE.may_load(deps.storage, &addr)?;
let vesting_stake = STAKE_VESTING.may_load(deps.storage, &addr)?;
// If address doesn't match anyone, leave early
if liquid_stake.is_none() && vesting_stake.is_none() {
return Ok(Response::new());
}
// response
let mut res = Response::new()
.add_attribute("action", "slash")
.add_attribute("addr", &addr)
.add_attribute("sender", info.sender);
// slash the liquid stake, if any
let mut new_liquid_stake = Uint128::zero();
if let Some(liquid_stake) = liquid_stake {
let mut liquid_slashed = liquid_stake * portion;
new_liquid_stake = STAKE.update(deps.storage, &addr, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default().sub(liquid_slashed))
})?;
// slash the claims
liquid_slashed += claims().slash_claims_for_addr(deps.storage, addr.clone(), portion)?;
// burn the liquid slashed tokens
if liquid_slashed > Uint128::zero() {
let burn_liquid_msg = BankMsg::Burn {
amount: coins(liquid_slashed.u128(), &cfg.denom),
};
res = res.add_message(burn_liquid_msg);
}
}
// slash the vesting stake, if any
let mut new_vesting_stake = Uint128::zero();
if let Some(vesting_stake) = vesting_stake {
let vesting_slashed = vesting_stake * portion;
new_vesting_stake = STAKE_VESTING.update(deps.storage, &addr, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default().sub(vesting_slashed))
})?;
// burn the vesting slashed tokens
if vesting_slashed > Uint128::zero() {
let burn_vesting_msg = BankMsg::Burn {
amount: coins(vesting_slashed.u128(), &cfg.denom),
};
res = res.add_message(burn_vesting_msg);
}
}
res.messages.extend(update_membership(
deps.storage,
addr,
new_liquid_stake + new_vesting_stake,
&cfg,
env.block.height,
)?);
Ok(res)
}
/// Validates funds sent with the message, that they are containing only a single denom. Returns
/// amount of funds sent, or error if:
/// * More than a single denom is sent (`ExtraDenoms` error)
/// * Invalid single denom is sent (`MissingDenom` error)
/// Note that no funds (or a coin of the right denom but zero amount) is a valid option here.
pub fn validate_funds(funds: &[Coin], stake_denom: &str) -> Result<Uint128, ContractError> {
match funds {
[] => Ok(Uint128::zero()),
[Coin { denom, amount }] if denom == stake_denom => Ok(*amount),
[_] => Err(ContractError::MissingDenom(stake_denom.to_string())),
_ => Err(ContractError::ExtraDenoms(stake_denom.to_string())),
}
}
fn update_membership(
storage: &mut dyn Storage,
sender: Addr,
new_stake: Uint128,
cfg: &Config,
height: u64,
) -> StdResult<Vec<SubMsg>> {
// update their membership points
let new = calc_points(new_stake, cfg);
let old = members().may_load(storage, &sender)?.map(|mi| mi.points);
// short-circuit if no change
if new == old {
return Ok(vec![]);
}
// otherwise, record change of points
match new.as_ref() {
Some(&p) => members().save(storage, &sender, &MemberInfo::new(p), height),
None => members().remove(storage, &sender, height),
}?;
// update total
TOTAL.update(storage, |total| -> StdResult<_> {
Ok(total + new.unwrap_or_default() - old.unwrap_or_default())
})?;
// alert the hooks
let diff = MemberDiff::new(sender, old, new);
HOOKS.prepare_hooks(storage, |h| {
MemberChangedHookMsg::one(diff.clone())
.into_cosmos_msg(h)
.map(SubMsg::new)
})
}
fn calc_points(stake: Uint128, cfg: &Config) -> Option<u64> {
if stake < cfg.min_bond {
None
} else {
let w = stake.u128() / (cfg.tokens_per_point.u128());
Some(w as u64)
}
}
pub fn execute_claim<Q: CustomQuery>(
deps: DepsMut<Q>,
env: Env,
info: MessageInfo,
) -> Result<Response, ContractError> {
let release = claims().claim_addr(deps.storage, &info.sender, &env.block, None)?;
if release.is_zero() {
return Err(ContractError::NothingToClaim {});
}
let config = CONFIG.load(deps.storage)?;
let amount = coins(release.into(), config.denom);
let res = Response::new()
.add_attribute("action", "claim")
.add_attribute("tokens", coins_to_string(&amount))
.add_attribute("sender", &info.sender)
.add_message(BankMsg::Send {
to_address: info.sender.into(),
amount,
});
Ok(res)
}
// TODO: put in cosmwasm-std
fn coins_to_string(coins: &[Coin]) -> String {
let strings: Vec<_> = coins
.iter()
.map(|c| format!("{}{}", c.amount, c.denom))
.collect();
strings.join(",")
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn sudo(
deps: DepsMut<TgradeQuery>,
env: Env,
msg: TgradeSudoMsg,
) -> Result<Response, ContractError> {
match msg {
TgradeSudoMsg::PrivilegeChange(PrivilegeChangeMsg::Promoted {}) => privilege_promote(deps),
TgradeSudoMsg::EndBlock {} => end_block(deps, env),
_ => Err(ContractError::UnknownSudoMsg {}),
}
}
fn privilege_promote<Q: CustomQuery>(deps: DepsMut<Q>) -> Result<Response, ContractError> {
let config = CONFIG.load(deps.storage)?;
let mut res = Response::new();
if config.auto_return_limit > 0 {
let msgs = request_privileges(&[Privilege::EndBlocker]);
res = res.add_submessages(msgs);
}
let msgs = request_privileges(&[Privilege::Delegator]);
res = res.add_submessages(msgs);
Ok(res)
}
fn end_block<Q: CustomQuery>(deps: DepsMut<Q>, env: Env) -> Result<Response, ContractError> {
let mut resp = Response::new();
let config = CONFIG.load(deps.storage)?;
if config.auto_return_limit > 0 {
let sub_msgs = release_expired_claims(deps, env, config)?;
resp = resp.add_submessages(sub_msgs);
}
Ok(resp)
}
fn release_expired_claims<Q: CustomQuery>(
deps: DepsMut<Q>,
env: Env,
config: Config,
) -> Result<Vec<SubMsg>, ContractError> {
let releases = claims().claim_expired(deps.storage, &env.block, config.auto_return_limit)?;
releases
.into_iter()
.map(|(addr, amount)| {
let amount = coins(amount.into(), config.denom.clone());
Ok(SubMsg::new(BankMsg::Send {
to_address: addr.into(),
amount,
}))
})
.collect()
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps<TgradeQuery>, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
use QueryMsg::*;
match msg {
Configuration {} => to_binary(&CONFIG.load(deps.storage)?),
Member {
addr,
at_height: height,
} => to_binary(&query_member(deps, addr, height)?),
ListMembers { start_after, limit } => to_binary(&list_members(deps, start_after, limit)?),
ListMembersByPoints { start_after, limit } => {
to_binary(&list_members_by_points(deps, start_after, limit)?)
}
TotalPoints {} => to_binary(&query_total_points(deps)?),
Claims {
address,
limit,
start_after,
} => to_binary(&ClaimsResponse {
claims: claims().query_claims(
deps,
deps.api.addr_validate(&address)?,
limit,
start_after,
)?,
}),
Staked { address } => to_binary(&query_staked(deps, address)?),
Admin {} => to_binary(&ADMIN.query_admin(deps)?),
Hooks {} => {
let hooks = HOOKS.list_hooks(deps.storage)?;
to_binary(&HooksResponse { hooks })
}
Preauths {} => {
let preauths_hooks = PREAUTH_HOOKS.get_auth(deps.storage)?;
to_binary(&PreauthResponse { preauths_hooks })
}
UnbondingPeriod {} => {
let Config {
unbonding_period, ..
} = CONFIG.load(deps.storage)?;
to_binary(&UnbondingPeriodResponse { unbonding_period })
}
IsSlasher { addr } => {
let addr = deps.api.addr_validate(&addr)?;
to_binary(&SLASHERS.is_slasher(deps.storage, &addr)?)
}
ListSlashers {} => to_binary(&SLASHERS.list_slashers(deps.storage)?),
}
}
fn query_total_points<Q: CustomQuery>(deps: Deps<Q>) -> StdResult<TotalPointsResponse> {
let points = TOTAL.load(deps.storage)?;
let denom = CONFIG.load(deps.storage)?.denom;
Ok(TotalPointsResponse { points, denom })
}
pub fn query_staked<Q: CustomQuery>(deps: Deps<Q>, addr: String) -> StdResult<StakedResponse> {
let addr = deps.api.addr_validate(&addr)?;
let stake = STAKE.may_load(deps.storage, &addr)?.unwrap_or_default();
let vesting = STAKE_VESTING
.may_load(deps.storage, &addr)?
.unwrap_or_default();
let config = CONFIG.load(deps.storage)?;
Ok(StakedResponse {
liquid: coin(stake.u128(), config.denom.clone()),
vesting: coin(vesting.u128(), config.denom),
})
}
fn query_member<Q: CustomQuery>(
deps: Deps<Q>,
addr: String,
height: Option<u64>,
) -> StdResult<MemberResponse> {
let addr = deps.api.addr_validate(&addr)?;
let mi = match height {
Some(h) => members().may_load_at_height(deps.storage, &addr, h),
None => members().may_load(deps.storage, &addr),
}?;
Ok(mi.into())
}
// settings for pagination
const MAX_LIMIT: u32 = 100;
const DEFAULT_LIMIT: u32 = 30;
fn list_members<Q: CustomQuery>(
deps: Deps<Q>,
start_after: Option<String>,
limit: Option<u32>,
) -> StdResult<MemberListResponse> {
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
let addr = maybe_addr(deps.api, start_after)?;
let start = addr.as_ref().map(Bound::exclusive);
let members: StdResult<Vec<_>> = members()
.range(deps.storage, start, None, Order::Ascending)
.take(limit)
.map(|item| {
let (
addr,
MemberInfo {
points,
start_height,
},
) = item?;
Ok(Member {
addr: addr.into(),
points,
start_height,
})
})
.collect();
Ok(MemberListResponse { members: members? })
}
fn list_members_by_points<Q: CustomQuery>(
deps: Deps<Q>,
start_after: Option<Member>,
limit: Option<u32>,
) -> StdResult<MemberListResponse> {
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
let start = start_after
.map(|m| {
deps.api
.addr_validate(&m.addr)
.map(|addr| Bound::exclusive((m.points, addr)))
})
.transpose()?;
let members: StdResult<Vec<_>> = members()
.idx
.points
.range(deps.storage, None, start, Order::Descending)
.take(limit)
.map(|item| {
let (
addr,
MemberInfo {
points,
start_height,
},
) = item?;
Ok(Member {
addr: addr.into(),
points,
start_height,
})
})
.collect();
Ok(MemberListResponse { members: members? })
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(
deps: DepsMut<TgradeQuery>,
_env: Env,
_msg: Empty,
) -> Result<Response, ContractError> {
ensure_from_older_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
Ok(Response::new())
}
#[cfg(test)]
mod tests {
use crate::claim::Claim;
use cosmwasm_std::testing::{mock_env, mock_info};
use cosmwasm_std::{
from_slice, CosmosMsg, OverflowError, OverflowOperation, StdError, Storage,
};
use tg4::{member_key, TOTAL_KEY};
use tg_utils::{Expiration, HookError, PreauthError, SlasherError};
use crate::error::ContractError;
use super::*;
use tg_bindings_test::mock_deps_tgrade;
const INIT_ADMIN: &str = "juan";
const USER1: &str = "user1";
const USER2: &str = "user2";
const USER3: &str = "user3";
const DENOM: &str = "stake";
const TOKENS_PER_POINT: Uint128 = Uint128::new(1_000);
const MIN_BOND: Uint128 = Uint128::new(5_000);
const UNBONDING_DURATION: u64 = 100;
fn default_instantiate(deps: DepsMut<TgradeQuery>) {
do_instantiate(deps, TOKENS_PER_POINT, MIN_BOND, UNBONDING_DURATION, 0)
}
fn do_instantiate(
deps: DepsMut<TgradeQuery>,
tokens_per_point: Uint128,
min_bond: Uint128,
unbonding_period: u64,
auto_return_limit: u64,
) {
let msg = InstantiateMsg {
denom: "stake".to_owned(),
tokens_per_point,
min_bond,
unbonding_period,
admin: Some(INIT_ADMIN.into()),
preauths_hooks: 1,
preauths_slashing: 1,
auto_return_limit,
};
let info = mock_info("creator", &[]);
instantiate(deps, mock_env(), info, msg).unwrap();
}
// Helper for staking only liquid assets
fn bond_liquid(
deps: DepsMut<TgradeQuery>,
user1: u128,
user2: u128,
user3: u128,
height_delta: u64,
) {
bond(deps, (user1, 0), (user2, 0), (user3, 0), height_delta);
}
// Helper for staking only illiquid assets
fn bond_vesting(
deps: DepsMut<TgradeQuery>,
user1: u128,
user2: u128,
user3: u128,
height_delta: u64,
) {
bond(deps, (0, user1), (0, user2), (0, user3), height_delta);
}
// Full stake is composed of `(liquid, illiquid (vesting))` amounts
fn bond(
mut deps: DepsMut<TgradeQuery>,
user1_stake: (u128, u128),
user2_stake: (u128, u128),
user3_stake: (u128, u128),
height_delta: u64,
) {
let mut env = mock_env();
env.block.height += height_delta;
for (addr, stake) in &[
(USER1, user1_stake),
(USER2, user2_stake),
(USER3, user3_stake),
] {
if stake.0 != 0 || stake.1 != 0 {
let vesting_tokens = if stake.1 != 0 {
Some(coin(stake.1, DENOM))
} else {
None
};
let msg = ExecuteMsg::Bond { vesting_tokens };
let info = mock_info(addr, &coins(stake.0, DENOM));
execute(deps.branch(), env.clone(), info, msg).unwrap();
}
}
}
fn unbond(
mut deps: DepsMut<TgradeQuery>,
user1: u128,
user2: u128,
user3: u128,
height_delta: u64,
time_delta: u64,
) {
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(time_delta);
for (addr, stake) in &[(USER1, user1), (USER2, user2), (USER3, user3)] {
if *stake != 0 {
let msg = ExecuteMsg::Unbond {
tokens: coin(*stake, DENOM),
};
let info = mock_info(addr, &[]);
execute(deps.branch(), env.clone(), info, msg).unwrap();
}
}
}
#[test]
fn proper_instantiation() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
// it worked, let's query the state
let res = ADMIN.query_admin(deps.as_ref()).unwrap();
assert_eq!(Some(INIT_ADMIN.into()), res.admin);
let res = query_total_points(deps.as_ref()).unwrap();
assert_eq!(0, res.points);
assert_eq!("stake".to_owned(), res.denom);
let raw = query(deps.as_ref(), mock_env(), QueryMsg::Configuration {}).unwrap();
let res: Config = from_slice(&raw).unwrap();
assert_eq!(
res,
Config {
denom: "stake".to_owned(),
tokens_per_point: TOKENS_PER_POINT,
min_bond: MIN_BOND,
unbonding_period: Duration::new(UNBONDING_DURATION),
auto_return_limit: 0,
}
);
}
#[test]
fn unbonding_period_query_works() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let raw = query(deps.as_ref(), mock_env(), QueryMsg::UnbondingPeriod {}).unwrap();
let res: UnbondingPeriodResponse = from_slice(&raw).unwrap();
assert_eq!(res.unbonding_period, Duration::new(UNBONDING_DURATION));
}
fn get_member(deps: Deps<TgradeQuery>, addr: String, at_height: Option<u64>) -> Option<u64> {
let raw = query(deps, mock_env(), QueryMsg::Member { addr, at_height }).unwrap();
let res: MemberResponse = from_slice(&raw).unwrap();
res.points
}
// this tests the member queries
#[track_caller]
fn assert_users(
deps: Deps<TgradeQuery>,
user1_points: Option<u64>,
user2_points: Option<u64>,
user3_points: Option<u64>,
height: Option<u64>,
) {
let member1 = get_member(deps, USER1.into(), height);
assert_eq!(member1, user1_points);
let member2 = get_member(deps, USER2.into(), height);
assert_eq!(member2, user2_points);
let member3 = get_member(deps, USER3.into(), height);
assert_eq!(member3, user3_points);
// this is only valid if we are not doing a historical query
if height.is_none() {
// compute expected metrics
let points = vec![user1_points, user2_points, user3_points];
let sum: u64 = points.iter().map(|x| x.unwrap_or_default()).sum();
let count = points.iter().filter(|x| x.is_some()).count();
// TODO: more detailed compare?
let msg = QueryMsg::ListMembers {
start_after: None,
limit: None,
};
let raw = query(deps, mock_env(), msg).unwrap();
let members: MemberListResponse = from_slice(&raw).unwrap();
assert_eq!(count, members.members.len());
let raw = query(deps, mock_env(), QueryMsg::TotalPoints {}).unwrap();
let total: TotalPointsResponse = from_slice(&raw).unwrap();
assert_eq!(sum, total.points); // 17 - 11 + 15 = 21
}
}
// this tests the member queries of liquid amounts
#[track_caller]
fn assert_stake_liquid(deps: Deps<TgradeQuery>, user1: u128, user2: u128, user3: u128) {
let stake1 = query_staked(deps, USER1.into()).unwrap();
assert_eq!(stake1.liquid, coin(user1, DENOM));
let stake2 = query_staked(deps, USER2.into()).unwrap();
assert_eq!(stake2.liquid, coin(user2, DENOM));
let stake3 = query_staked(deps, USER3.into()).unwrap();
assert_eq!(stake3.liquid, coin(user3, DENOM));
}
// this tests the member queries of illiquid amounts
#[track_caller]
fn assert_stake_vesting(deps: Deps<TgradeQuery>, user1: u128, user2: u128, user3: u128) {
let stake1 = query_staked(deps, USER1.into()).unwrap();
assert_eq!(stake1.vesting, coin(user1, DENOM));
let stake2 = query_staked(deps, USER2.into()).unwrap();
assert_eq!(stake2.vesting, coin(user2, DENOM));
let stake3 = query_staked(deps, USER3.into()).unwrap();
assert_eq!(stake3.vesting, coin(user3, DENOM));
}
#[test]
fn bond_stake_liquid_adds_membership() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let height = mock_env().block.height;
// Assert original points
assert_users(deps.as_ref(), None, None, None, None);
// ensure it rounds down, and respects cut-off
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
// Assert updated points
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
assert_users(deps.as_ref(), Some(12), Some(7), None, None);
// add some more, ensure the sum is properly respected (7.5 + 7.6 = 15 not 14)
bond_liquid(deps.as_mut(), 0, 7_600, 1_200, 2);
// Assert updated points
assert_stake_liquid(deps.as_ref(), 12_000, 15_100, 5_200);
assert_users(deps.as_ref(), Some(12), Some(15), Some(5), None);
// check historical queries all work
assert_users(deps.as_ref(), None, None, None, Some(height + 1)); // before first stake
assert_users(deps.as_ref(), Some(12), Some(7), None, Some(height + 2)); // after first stake
assert_users(deps.as_ref(), Some(12), Some(15), Some(5), Some(height + 3));
// after second stake
}
#[test]
fn bond_stake_vesting_adds_membership() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let height = mock_env().block.height;
// Assert original points
assert_users(deps.as_ref(), None, None, None, None);
// ensure it rounds down, and respects cut-off
bond_vesting(deps.as_mut(), 12_000, 7_500, 4_000, 1);
// Assert updated points
assert_stake_vesting(deps.as_ref(), 12_000, 7_500, 4_000);
assert_users(deps.as_ref(), Some(12), Some(7), None, None);
// add some more, ensure the sum is properly respected (7.5 + 7.6 = 15 not 14)
bond_vesting(deps.as_mut(), 0, 7_600, 1_200, 2);
// Assert updated points
assert_stake_vesting(deps.as_ref(), 12_000, 15_100, 5_200);
assert_users(deps.as_ref(), Some(12), Some(15), Some(5), None);
// check historical queries all work
assert_users(deps.as_ref(), None, None, None, Some(height + 1)); // before first stake
assert_users(deps.as_ref(), Some(12), Some(7), None, Some(height + 2)); // after first stake
assert_users(deps.as_ref(), Some(12), Some(15), Some(5), Some(height + 3));
// after second stake
}
#[test]
fn bond_mixed_stake_adds_membership() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let height = mock_env().block.height;
// Assert original points
assert_users(deps.as_ref(), None, None, None, None);
// ensure it rounds down, and respects cut-off
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
// Assert updated points
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
assert_users(deps.as_ref(), Some(12), Some(7), None, None);
// add some more, ensure the sum is properly respected (7.5 + 7.6 = 15 not 14)
bond_vesting(deps.as_mut(), 0, 7_600, 1_200, 2);
// Assert updated points
assert_stake_vesting(deps.as_ref(), 0, 7_600, 1_200);
assert_users(deps.as_ref(), Some(12), Some(15), Some(5), None);
// check historical queries all work
assert_users(deps.as_ref(), None, None, None, Some(height + 1)); // before first stake
assert_users(deps.as_ref(), Some(12), Some(7), None, Some(height + 2)); // after first stake
assert_users(deps.as_ref(), Some(12), Some(15), Some(5), Some(height + 3));
// after second stake
}
#[test]
fn try_member_queries() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
bond(deps.as_mut(), (12_000, 0), (7_400, 100), (0, 4_000), 1);
let member1 = query_member(deps.as_ref(), USER1.into(), None).unwrap();
assert_eq!(member1.points, Some(12));
let member2 = query_member(deps.as_ref(), USER2.into(), None).unwrap();
assert_eq!(member2.points, Some(7));
let member3 = query_member(deps.as_ref(), USER3.into(), None).unwrap();
assert_eq!(member3.points, None);
let members = list_members(deps.as_ref(), None, None).unwrap().members;
assert_eq!(members.len(), 2);
// Assert the set is proper
assert_eq!(
members,
vec![
Member {
addr: USER1.into(),
points: 12,
start_height: None
},
Member {
addr: USER2.into(),
points: 7,
start_height: None
},
]
);
// Test pagination / limits
let members = list_members(deps.as_ref(), None, Some(1)).unwrap().members;
assert_eq!(members.len(), 1);
// Assert the set is proper
assert_eq!(
members,
vec![Member {
addr: USER1.into(),
points: 12,
start_height: None
},]
);
// Next page
let start_after = Some(members[0].addr.clone());
let members = list_members(deps.as_ref(), start_after, Some(1))
.unwrap()
.members;
assert_eq!(members.len(), 1);
// Assert the set is proper
assert_eq!(
members,
vec![Member {
addr: USER2.into(),
points: 7,
start_height: None
},]
);
// Assert there's no more
let start_after = Some(members[0].addr.clone());
let members = list_members(deps.as_ref(), start_after, Some(1))
.unwrap()
.members;
assert_eq!(members.len(), 0);
}
#[test]
fn try_list_members_by_points() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
bond(deps.as_mut(), (10_000, 1_000), (6_500, 0), (0, 5_000), 1);
let members = list_members_by_points(deps.as_ref(), None, None)
.unwrap()
.members;
assert_eq!(members.len(), 3);
// Assert the set is sorted by (descending) points
assert_eq!(
members,
vec![
Member {
addr: USER1.into(),
points: 11,
start_height: None
},
Member {
addr: USER2.into(),
points: 6,
start_height: None
},
Member {
addr: USER3.into(),
points: 5,
start_height: None
}
]
);
// Test pagination / limits
let members = list_members_by_points(deps.as_ref(), None, Some(1))
.unwrap()
.members;
assert_eq!(members.len(), 1);
// Assert the set is proper
assert_eq!(
members,
vec![Member {
addr: USER1.into(),
points: 11,
start_height: None
},]
);
// Next page
let last = members.last().unwrap();
let start_after = Some(last.clone());
let members = list_members_by_points(deps.as_ref(), start_after, None)
.unwrap()
.members;
assert_eq!(members.len(), 2);
// Assert the set is proper
assert_eq!(
members,
vec![
Member {
addr: USER2.into(),
points: 6,
start_height: None
},
Member {
addr: USER3.into(),
points: 5,
start_height: None
}
]
);
// Assert there's no more
let last = members.last().unwrap();
let start_after = Some(last.clone());
let members = list_members_by_points(deps.as_ref(), start_after, Some(1))
.unwrap()
.members;
assert_eq!(members.len(), 0);
}
#[test]
fn unbond_stake_update_membership() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let height = mock_env().block.height;
// ensure it rounds down, and respects cut-off
bond(deps.as_mut(), (0, 12_000), (500, 7_000), (3_000, 3_000), 1);
assert_users(deps.as_ref(), Some(12), Some(7), Some(6), None);
unbond(deps.as_mut(), 4_500, 2_600, 1_000, 2, 0);
// Assert updated points
assert_stake_liquid(deps.as_ref(), 0, 0, 2000);
assert_stake_vesting(deps.as_ref(), 7_500, 4_900, 3000);
assert_users(deps.as_ref(), Some(7), None, Some(5), None);
// Adding a little more returns points
bond(deps.as_mut(), (500, 100), (100, 0), (0, 2_222), 3);
// Assert updated points
assert_stake_liquid(deps.as_ref(), 500, 100, 2000);
assert_stake_vesting(deps.as_ref(), 7_600, 4_900, 5_222);
assert_users(deps.as_ref(), Some(8), Some(5), Some(7), None);
// check historical queries all work
assert_users(deps.as_ref(), None, None, None, Some(height + 1)); // before first stake
assert_users(deps.as_ref(), Some(12), Some(7), Some(6), Some(height + 2)); // after first bond
assert_users(deps.as_ref(), Some(7), None, Some(5), Some(height + 3)); // after first unbond
assert_users(deps.as_ref(), Some(8), Some(5), Some(7), Some(height + 4)); // after second bond
// error if try to unbond more than stake (USER2 has 5000 staked)
let msg = ExecuteMsg::Unbond {
tokens: coin(5100, DENOM),
};
let mut env = mock_env();
env.block.height += 5;
let info = mock_info(USER2, &[]);
let err = execute(deps.as_mut(), env, info, msg).unwrap_err();
assert_eq!(
err,
ContractError::Std(StdError::overflow(OverflowError::new(
OverflowOperation::Sub,
4900,
5000
)))
);
}
#[test]
fn raw_queries_work() {
// add will over-write and remove have no effect
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
// Set values as (11, 6, None)
bond(deps.as_mut(), (1_000, 10_000), (6_000, 0), (0, 0), 1);
// get total from raw key
let total_raw = deps.storage.get(TOTAL_KEY.as_bytes()).unwrap();
let total: u64 = from_slice(&total_raw).unwrap();
assert_eq!(17, total);
// get member votes from raw key
let member2_raw = deps.storage.get(&member_key(USER2)).unwrap();
let member2: MemberInfo = from_slice(&member2_raw).unwrap();
assert_eq!(6, member2.points);
// and execute misses
let member3_raw = deps.storage.get(&member_key(USER3));
assert_eq!(None, member3_raw);
}
#[track_caller]
fn get_claims(
deps: Deps<TgradeQuery>,
addr: Addr,
limit: Option<u32>,
start_after: Option<Expiration>,
) -> Vec<Claim> {
claims()
.query_claims(deps, addr, limit, start_after)
.unwrap()
}
#[test]
fn unbond_claim_workflow() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
// create some data
bond(deps.as_mut(), (4_000, 7_500), (7_500, 0), (3_000, 1_000), 1);
let height_delta = 2;
// Only 4_000 (liquid) will be claimed for USER1
unbond(deps.as_mut(), 4_500, 2_600, 0, height_delta, 0);
let mut env = mock_env();
env.block.height += height_delta;
// check the claims for each user
let expires = Duration::new(UNBONDING_DURATION).after(&env.block);
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER1), None, None),
vec![Claim::new(
Addr::unchecked(USER1),
4_000,
expires,
env.block.height
)]
);
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER2), None, None),
vec![Claim::new(
Addr::unchecked(USER2),
2_600,
expires,
env.block.height
)]
);
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER3), None, None),
vec![]
);
// do another unbond later on
let mut env2 = mock_env();
let height_delta = 22;
env2.block.height += height_delta;
let time_delta = 50;
unbond(deps.as_mut(), 0, 1_345, 1_500, height_delta, time_delta);
// with updated claims
let expires2 = Duration::new(UNBONDING_DURATION + time_delta).after(&env2.block);
assert_ne!(expires, expires2);
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER1), None, None),
vec![Claim::new(
Addr::unchecked(USER1),
4_000,
expires,
env.block.height
)]
);
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER2), None, None),
vec![
Claim::new(Addr::unchecked(USER2), 2_600, expires, env.block.height),
Claim::new(Addr::unchecked(USER2), 1_345, expires2, env2.block.height)
]
);
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER3), None, None),
vec![Claim::new(
Addr::unchecked(USER3),
1_500,
expires2,
env2.block.height
)]
);
// nothing can be withdrawn yet
let err = execute(
deps.as_mut(),
env,
mock_info(USER1, &[]),
ExecuteMsg::Claim {},
)
.unwrap_err();
assert_eq!(err, ContractError::NothingToClaim {});
// now mature first section, withdraw that
let mut env3 = mock_env();
env3.block.time = env3.block.time.plus_seconds(UNBONDING_DURATION);
// first one can now release
let res = execute(
deps.as_mut(),
env3.clone(),
mock_info(USER1, &[]),
ExecuteMsg::Claim {},
)
.unwrap();
assert_eq!(
res.messages,
vec![SubMsg::new(BankMsg::Send {
to_address: USER1.into(),
amount: coins(4_000, DENOM),
})]
);
// second releases partially
let res = execute(
deps.as_mut(),
env3.clone(),
mock_info(USER2, &[]),
ExecuteMsg::Claim {},
)
.unwrap();
assert_eq!(
res.messages,
vec![SubMsg::new(BankMsg::Send {
to_address: USER2.into(),
amount: coins(2_600, DENOM),
})]
);
// but the third one cannot release
let err = execute(
deps.as_mut(),
env3,
mock_info(USER3, &[]),
ExecuteMsg::Claim {},
)
.unwrap_err();
assert_eq!(err, ContractError::NothingToClaim {});
// claims updated properly
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER1), None, None),
vec![]
);
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER2), None, None),
vec![Claim::new(
Addr::unchecked(USER2),
1_345,
expires2,
env2.block.height
)]
);
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER3), None, None),
vec![Claim::new(
Addr::unchecked(USER3),
1_500,
expires2,
env2.block.height
)]
);
// add another few claims for 2
unbond(deps.as_mut(), 0, 600, 0, 30, 0);
unbond(deps.as_mut(), 0, 1_005, 0, 50, 0);
// ensure second can claim all tokens at once
let mut env4 = mock_env();
env4.block.time = env4
.block
.time
.plus_seconds(UNBONDING_DURATION + time_delta);
let res = execute(
deps.as_mut(),
env4,
mock_info(USER2, &[]),
ExecuteMsg::Claim {},
)
.unwrap();
assert_eq!(
res.messages,
vec![SubMsg::new(BankMsg::Send {
to_address: USER2.into(),
// 1_345 + 600 + 1_005
amount: coins(2_950, DENOM),
})]
);
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER2), None, None),
vec![]
);
}
#[test]
fn add_remove_hooks() {
// add will over-write and remove have no effect
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let hooks = HOOKS.list_hooks(&deps.storage).unwrap();
assert!(hooks.is_empty());
let contract1 = String::from("hook1");
let contract2 = String::from("hook2");
let add_msg = ExecuteMsg::AddHook {
addr: contract1.clone(),
};
// anyone can add the first one, until preauth is consume
assert_eq!(1, PREAUTH_HOOKS.get_auth(&deps.storage).unwrap());
let user_info = mock_info(USER1, &[]);
let _ = execute(deps.as_mut(), mock_env(), user_info, add_msg.clone()).unwrap();
let hooks = HOOKS.list_hooks(&deps.storage).unwrap();
assert_eq!(hooks, vec![contract1.clone()]);
// non-admin cannot add hook without preauth
assert_eq!(0, PREAUTH_HOOKS.get_auth(&deps.storage).unwrap());
let user_info = mock_info(USER1, &[]);
let err = execute(
deps.as_mut(),
mock_env(),
user_info.clone(),
add_msg.clone(),
)
.unwrap_err();
assert_eq!(err, PreauthError::NoPreauth {}.into());
// cannot remove a non-registered contract
let admin_info = mock_info(INIT_ADMIN, &[]);
let remove_msg = ExecuteMsg::RemoveHook {
addr: contract2.clone(),
};
let err = execute(deps.as_mut(), mock_env(), admin_info.clone(), remove_msg).unwrap_err();
assert_eq!(err, HookError::HookNotRegistered {}.into());
// admin can second contract, and it appears in the query
let add_msg2 = ExecuteMsg::AddHook {
addr: contract2.clone(),
};
execute(deps.as_mut(), mock_env(), admin_info.clone(), add_msg2).unwrap();
let hooks = HOOKS.list_hooks(&deps.storage).unwrap();
assert_eq!(hooks, vec![contract1.clone(), contract2.clone()]);
// cannot re-add an existing contract
let err = execute(deps.as_mut(), mock_env(), admin_info.clone(), add_msg).unwrap_err();
assert_eq!(err, HookError::HookAlreadyRegistered {}.into());
// non-admin cannot remove
let remove_msg = ExecuteMsg::RemoveHook { addr: contract1 };
let err = execute(deps.as_mut(), mock_env(), user_info, remove_msg.clone()).unwrap_err();
assert_eq!(
err,
ContractError::Unauthorized(
"Hook address is not same as sender's and sender is not an admin".to_owned()
)
);
// remove the original
execute(deps.as_mut(), mock_env(), admin_info, remove_msg).unwrap();
let hooks = HOOKS.list_hooks(&deps.storage).unwrap();
assert_eq!(hooks, vec![contract2.clone()]);
// contract can self-remove
let contract_info = mock_info(&contract2, &[]);
let remove_msg2 = ExecuteMsg::RemoveHook { addr: contract2 };
execute(deps.as_mut(), mock_env(), contract_info, remove_msg2).unwrap();
let hooks = HOOKS.list_hooks(&deps.storage).unwrap();
assert_eq!(hooks, Vec::<String>::new());
}
mod slash {
use super::*;
fn query_is_slasher(deps: Deps<TgradeQuery>, env: Env, addr: String) -> StdResult<bool> {
let msg = QueryMsg::IsSlasher { addr };
let raw = query(deps, env, msg)?;
let is_slasher: bool = from_slice(&raw)?;
Ok(is_slasher)
}
fn query_list_slashers(deps: Deps<TgradeQuery>, env: Env) -> StdResult<Vec<String>> {
let msg = QueryMsg::ListSlashers {};
let raw = query(deps, env, msg)?;
let slashers: Vec<String> = from_slice(&raw)?;
Ok(slashers)
}
fn add_slasher(deps: DepsMut<TgradeQuery>) -> String {
let slasher = String::from("slasher");
let add_msg = ExecuteMsg::AddSlasher {
addr: slasher.clone(),
};
let user_info = mock_info(USER1, &[]);
execute(deps, mock_env(), user_info, add_msg).unwrap();
slasher
}
fn remove_slasher(deps: DepsMut<TgradeQuery>, slasher: &str) {
let add_msg = ExecuteMsg::RemoveSlasher {
addr: slasher.to_string(),
};
let user_info = mock_info(INIT_ADMIN, &[]);
execute(deps, mock_env(), user_info, add_msg).unwrap();
}
fn slash(
deps: DepsMut<TgradeQuery>,
slasher: &str,
addr: &str,
portion: Decimal,
) -> Result<Response, ContractError> {
let msg = ExecuteMsg::Slash {
addr: addr.to_string(),
portion,
};
let slasher_info = mock_info(slasher, &[]);
execute(deps, mock_env(), slasher_info, msg)
}
fn assert_burned(res: Response, expected_liquid: &[Coin], expected_vesting: &[Coin]) {
// Args checks for robustness
assert!(expected_liquid.len() <= 1);
assert!(expected_vesting.len() <= 1);
// Find all instances of BankMsg::Burn in the response and extract the burned amounts
let burned_amounts: Vec<_> = res
.messages
.iter()
.filter_map(|sub_msg| match &sub_msg.msg {
CosmosMsg::Bank(BankMsg::Burn { amount }) => Some(amount),
_ => None,
})
.collect();
assert!(
burned_amounts.len() == 1 || burned_amounts.len() == 2,
"Expected exactly 1 or 2 Bank::Burn message, got {}",
burned_amounts.len()
);
let mut index = 0;
if !expected_liquid.is_empty() {
assert_eq!(
burned_amounts[index], &expected_liquid,
"Expected to burn {} liquid, burned {}",
expected_liquid[0], burned_amounts[index][0]
);
index += 1;
}
if !expected_vesting.is_empty() {
assert_eq!(
burned_amounts[index], &expected_vesting,
"Expected to burn {} vesting, burned {}",
expected_liquid[0], burned_amounts[index][0]
);
}
}
#[test]
fn add_remove_slashers() {
let mut deps = mock_deps_tgrade();
let env = mock_env();
default_instantiate(deps.as_mut());
let slashers = query_list_slashers(deps.as_ref(), env.clone()).unwrap();
assert!(slashers.is_empty());
let contract1 = String::from("slasher1");
let contract2 = String::from("slasher2");
let add_msg = ExecuteMsg::AddSlasher {
addr: contract1.clone(),
};
// anyone can add the first one, until preauth is consumed
assert_eq!(1, PREAUTH_SLASHING.get_auth(&deps.storage).unwrap());
let user_info = mock_info(USER1, &[]);
let _ = execute(deps.as_mut(), mock_env(), user_info, add_msg.clone()).unwrap();
let slashers = query_list_slashers(deps.as_ref(), env.clone()).unwrap();
assert_eq!(slashers, vec![contract1.clone()]);
// non-admin cannot add slasher without preauth
assert_eq!(0, PREAUTH_SLASHING.get_auth(&deps.storage).unwrap());
let user_info = mock_info(USER1, &[]);
let err = execute(
deps.as_mut(),
mock_env(),
user_info.clone(),
add_msg.clone(),
)
.unwrap_err();
assert_eq!(err, PreauthError::NoPreauth {}.into());
// cannot remove a non-registered slasher
let admin_info = mock_info(INIT_ADMIN, &[]);
let remove_msg = ExecuteMsg::RemoveSlasher {
addr: contract2.clone(),
};
let err =
execute(deps.as_mut(), mock_env(), admin_info.clone(), remove_msg).unwrap_err();
assert_eq!(
err,
ContractError::Slasher(SlasherError::SlasherNotRegistered(contract2.clone()))
);
// admin can add a second slasher, and it appears in the query
let add_msg2 = ExecuteMsg::AddSlasher {
addr: contract2.clone(),
};
execute(deps.as_mut(), mock_env(), admin_info.clone(), add_msg2).unwrap();
let slashers = query_list_slashers(deps.as_ref(), env.clone()).unwrap();
assert_eq!(slashers, vec![contract1.clone(), contract2.clone()]);
// cannot re-add an existing contract
let err = execute(deps.as_mut(), mock_env(), admin_info.clone(), add_msg).unwrap_err();
assert_eq!(
err,
ContractError::Slasher(SlasherError::SlasherAlreadyRegistered(contract1.clone()))
);
// non-admin cannot remove
let remove_msg = ExecuteMsg::RemoveSlasher { addr: contract1 };
let err =
execute(deps.as_mut(), mock_env(), user_info, remove_msg.clone()).unwrap_err();
assert_eq!(
err,
ContractError::Unauthorized(
"Only slasher might remove himself and sender is not an admin".to_owned()
)
);
// remove the original
execute(deps.as_mut(), mock_env(), admin_info, remove_msg).unwrap();
let slashers = query_list_slashers(deps.as_ref(), env.clone()).unwrap();
assert_eq!(slashers, vec![contract2.clone()]);
// contract can self-remove
let contract_info = mock_info(&contract2, &[]);
let remove_msg2 = ExecuteMsg::RemoveSlasher { addr: contract2 };
execute(deps.as_mut(), mock_env(), contract_info, remove_msg2).unwrap();
let slashers = query_list_slashers(deps.as_ref(), env).unwrap();
assert_eq!(slashers, Vec::<String>::new());
}
#[test]
fn slashing_nonexisting_member() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
// confirm address doesn't return true on slasher query
assert!(!query_is_slasher(deps.as_ref(), mock_env(), "slasher".to_owned()).unwrap());
let slasher = add_slasher(deps.as_mut());
assert!(query_is_slasher(deps.as_ref(), mock_env(), slasher.clone()).unwrap());
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
// Trying to slash nonexisting user will result in no-op
let res = slash(deps.as_mut(), &slasher, "nonexisting", Decimal::percent(20)).unwrap();
assert_eq!(res, Response::new());
}
#[test]
fn slashing_bonded_liquid_tokens_works() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let cfg = CONFIG.load(&deps.storage).unwrap();
let slasher = add_slasher(deps.as_mut());
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
// The slasher we added can slash
let res1 = slash(deps.as_mut(), &slasher, USER1, Decimal::percent(20)).unwrap();
let res2 = slash(deps.as_mut(), &slasher, USER3, Decimal::percent(50)).unwrap();
assert_stake_liquid(deps.as_ref(), 9_600, 7_500, 2_000);
// Tokens are burned
assert_burned(res1, &coins(2_400, &cfg.denom), &[]);
assert_burned(res2, &coins(2_000, &cfg.denom), &[]);
}
#[test]
fn slashing_bonded_vesting_tokens_works() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let cfg = CONFIG.load(&deps.storage).unwrap();
let slasher = add_slasher(deps.as_mut());
bond_vesting(deps.as_mut(), 12_000, 7_500, 4_000, 1);
assert_stake_vesting(deps.as_ref(), 12_000, 7_500, 4_000);
// The slasher we added can slash
let res1 = slash(deps.as_mut(), &slasher, USER1, Decimal::percent(20)).unwrap();
let res2 = slash(deps.as_mut(), &slasher, USER3, Decimal::percent(50)).unwrap();
assert_stake_vesting(deps.as_ref(), 9_600, 7_500, 2_000);
// Tokens are burned
assert_burned(res1, &[], &coins(2_400, &cfg.denom));
assert_burned(res2, &[], &coins(2_000, &cfg.denom));
}
#[test]
fn slashing_bonded_mixed_tokens_works() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let cfg = CONFIG.load(&deps.storage).unwrap();
let slasher = add_slasher(deps.as_mut());
bond_liquid(deps.as_mut(), 12_000, 1_500, 0, 1);
assert_stake_liquid(deps.as_ref(), 12_000, 1_500, 0);
bond_vesting(deps.as_mut(), 0, 6_000, 4_000, 1);
assert_stake_vesting(deps.as_ref(), 0, 6_000, 4_000);
// The slasher we added can slash
let res1 = slash(deps.as_mut(), &slasher, USER1, Decimal::percent(20)).unwrap();
let res2 = slash(deps.as_mut(), &slasher, USER3, Decimal::percent(50)).unwrap();
let res3 = slash(deps.as_mut(), &slasher, USER2, Decimal::percent(10)).unwrap();
assert_stake_liquid(deps.as_ref(), 9_600, 1_350, 0);
assert_stake_vesting(deps.as_ref(), 0, 5_400, 2_000);
// Tokens are burned
assert_burned(res1, &coins(2_400, &cfg.denom), &[]);
assert_burned(res2, &[], &coins(2_000, &cfg.denom));
assert_burned(res3, &coins(150, &cfg.denom), &coins(600, &cfg.denom));
}
#[test]
fn slashing_stake_update_membership() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let slasher = add_slasher(deps.as_mut());
// ensure it rounds down, and respects cut-off
bond(deps.as_mut(), (0, 12_000), (7_000, 0), (3_000, 4_000), 1);
assert_users(deps.as_ref(), Some(12), Some(7), Some(7), None);
slash(deps.as_mut(), &slasher, USER1, Decimal::percent(50)).unwrap();
slash(deps.as_mut(), &slasher, USER2, Decimal::percent(10)).unwrap();
slash(deps.as_mut(), &slasher, USER3, Decimal::percent(20)).unwrap();
// Assert updated points
assert_stake_liquid(deps.as_ref(), 0, 6_300, 2_400);
assert_stake_vesting(deps.as_ref(), 6_000, 0, 3_200);
assert_users(deps.as_ref(), Some(6), Some(6), Some(5), None);
}
#[test]
fn slashing_claims_works() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let cfg = CONFIG.load(&deps.storage).unwrap();
let slasher = add_slasher(deps.as_mut());
// create some data
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
let height_delta = 2;
unbond(deps.as_mut(), 12_000, 2_600, 0, height_delta, 0);
let mut env = mock_env();
env.block.height += height_delta;
// check the claims for each user
let expires = Duration::new(UNBONDING_DURATION).after(&env.block);
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER1), None, None),
vec![Claim::new(
Addr::unchecked(USER1),
12_000,
expires,
env.block.height
)]
);
let res = slash(deps.as_mut(), &slasher, USER1, Decimal::percent(20)).unwrap();
assert_eq!(
get_claims(deps.as_ref(), Addr::unchecked(USER1), None, None),
vec![Claim::new(
Addr::unchecked(USER1),
9_600,
expires,
env.block.height
)]
);
assert_burned(res, &coins(2_400, &cfg.denom), &[]);
}
#[test]
fn random_user_cannot_slash() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let _slasher = add_slasher(deps.as_mut());
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
let res = slash(deps.as_mut(), USER2, USER1, Decimal::percent(20));
assert_eq!(
res,
Err(ContractError::Unauthorized(
"Sender is not on slashers list".to_owned()
))
);
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
}
#[test]
fn admin_cannot_slash() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let _slasher = add_slasher(deps.as_mut());
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
let res = slash(deps.as_mut(), INIT_ADMIN, USER1, Decimal::percent(20));
assert_eq!(
res,
Err(ContractError::Unauthorized(
"Sender is not on slashers list".to_owned()
))
);
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
}
#[test]
fn removed_slasher_cannot_slash() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
// Add, then remove a slasher
let slasher = add_slasher(deps.as_mut());
remove_slasher(deps.as_mut(), &slasher);
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
let res = slash(deps.as_mut(), &slasher, USER1, Decimal::percent(20));
assert_eq!(
res,
Err(ContractError::Unauthorized(
"Sender is not on slashers list".to_owned()
))
);
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
}
}
#[test]
fn hooks_fire() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let hooks = HOOKS.list_hooks(&deps.storage).unwrap();
assert!(hooks.is_empty());
let contract1 = String::from("hook1");
let contract2 = String::from("hook2");
// register 2 hooks
let admin_info = mock_info(INIT_ADMIN, &[]);
let add_msg = ExecuteMsg::AddHook {
addr: contract1.clone(),
};
let add_msg2 = ExecuteMsg::AddHook {
addr: contract2.clone(),
};
for msg in vec![add_msg, add_msg2] {
let _ = execute(deps.as_mut(), mock_env(), admin_info.clone(), msg).unwrap();
}
// check firing on bond
assert_users(deps.as_ref(), None, None, None, None);
let info = mock_info(USER1, &coins(13_800, DENOM));
let res = execute(
deps.as_mut(),
mock_env(),
info,
ExecuteMsg::Bond {
vesting_tokens: None,
},
)
.unwrap();
assert_users(deps.as_ref(), Some(13), None, None, None);
// ensure messages for each of the 2 hooks
assert_eq!(res.messages.len(), 2);
let diff = MemberDiff::new(USER1, None, Some(13));
let hook_msg = MemberChangedHookMsg::one(diff);
let msg1 = hook_msg
.clone()
.into_cosmos_msg(contract1.clone())
.map(SubMsg::new)
.unwrap();
let msg2 = hook_msg
.into_cosmos_msg(contract2.clone())
.map(SubMsg::new)
.unwrap();
assert_eq!(res.messages, vec![msg1, msg2]);
// check firing on unbond
let msg = ExecuteMsg::Unbond {
tokens: coin(7_300, DENOM),
};
let info = mock_info(USER1, &[]);
let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap();
assert_users(deps.as_ref(), Some(6), None, None, None);
// ensure messages for each of the 2 hooks
assert_eq!(res.messages.len(), 2);
let diff = MemberDiff::new(USER1, Some(13), Some(6));
let hook_msg = MemberChangedHookMsg::one(diff);
let msg1 = hook_msg
.clone()
.into_cosmos_msg(contract1)
.map(SubMsg::new)
.unwrap();
let msg2 = hook_msg
.into_cosmos_msg(contract2)
.map(SubMsg::new)
.unwrap();
assert_eq!(res.messages, vec![msg1, msg2]);
}
#[test]
fn only_bond_valid_coins() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
// cannot bond with 0 coins
let info = mock_info(USER1, &[]);
let err = execute(
deps.as_mut(),
mock_env(),
info,
ExecuteMsg::Bond {
vesting_tokens: None,
},
)
.unwrap_err();
assert_eq!(err, ContractError::NoFunds {});
// cannot bond with incorrect denom
let info = mock_info(USER1, &[coin(500, "FOO")]);
let err = execute(
deps.as_mut(),
mock_env(),
info,
ExecuteMsg::Bond {
vesting_tokens: None,
},
)
.unwrap_err();
assert_eq!(err, ContractError::MissingDenom(DENOM.to_string()));
// cannot bond with 2 coins (even if one is correct)
let info = mock_info(USER1, &[coin(1234, DENOM), coin(5000, "BAR")]);
let err = execute(
deps.as_mut(),
mock_env(),
info,
ExecuteMsg::Bond {
vesting_tokens: None,
},
)
.unwrap_err();
assert_eq!(err, ContractError::ExtraDenoms(DENOM.to_string()));
// can bond with just the proper denom
// cannot bond with incorrect denom
let info = mock_info(USER1, &[coin(500, DENOM)]);
execute(
deps.as_mut(),
mock_env(),
info,
ExecuteMsg::Bond {
vesting_tokens: None,
},
)
.unwrap();
}
#[test]
fn ensure_bonding_edge_cases() {
// use min_bond 0, tokens_per_points 500
let mut deps = mock_deps_tgrade();
do_instantiate(deps.as_mut(), Uint128::new(100), Uint128::zero(), 5, 0);
// setting 50 tokens, gives us Some(0) points
// even setting to 1 token
bond_liquid(deps.as_mut(), 50, 1, 102, 1);
assert_users(deps.as_ref(), Some(0), Some(0), Some(1), None);
// reducing to 0 token makes us None even with min_bond 0
unbond(deps.as_mut(), 49, 1, 102, 2, 0);
assert_users(deps.as_ref(), Some(0), None, None, None);
}
#[test]
fn paginated_claim_query() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
// create some data
let mut env = mock_env();
let msg = ExecuteMsg::Bond {
vesting_tokens: None,
};
let info = mock_info(USER1, &coins(500, DENOM));
execute(deps.as_mut(), env.clone(), info, msg).unwrap();
let info = mock_info(USER1, &[]);
for _ in 0..10 {
env.block.time = env.block.time.plus_seconds(10);
let msg = ExecuteMsg::Unbond {
tokens: coin(10, DENOM),
};
execute(deps.as_mut(), env.clone(), info.clone(), msg).unwrap();
}
// check is number of claims is properly limited
let claims = get_claims(deps.as_ref(), Addr::unchecked(USER1), Some(6), None);
assert_eq!(claims.len(), 6);
// check if rest is equal to remainder
let next = get_claims(
deps.as_ref(),
Addr::unchecked(USER1),
None,
Some(claims[5].release_at),
);
assert_eq!(next.len(), 4);
// check if joining and sorting both vectors equal number from start
let mut all_claims = get_claims(deps.as_ref(), Addr::unchecked(USER1), None, None);
all_claims.sort_by_key(|claim| claim.addr.clone());
let mut concatenated = [claims, next].concat();
concatenated.sort_by_key(|claim| claim.addr.clone());
assert_eq!(concatenated, all_claims);
}
mod auto_release_claims {
// Because of tests framework limitations at the point of implementing this test, it is
// difficult to actually test reaction for tgrade sudo messages. Instead to check the
// auto-release functionality, there are assumptions made:
// * Registration to sudo events is correct
// * Auto-releasing claims occurs on sudo EndBlock message, and the message is purely
// calling the `end_block` function - calling this function in test is simulating actual
// end block
use cosmwasm_std::CosmosMsg;
use super::*;
fn do_instantiate(deps: DepsMut<TgradeQuery>, limit: u64) {
super::do_instantiate(deps, TOKENS_PER_POINT, MIN_BOND, UNBONDING_DURATION, limit)
}
/// Helper for asserting if expected transfers occurred in response. Panics if any non
/// `BankMsg::Send` occurred, or transfers are different than expected.
///
/// Transfers are passed in form of pairs `(addr, amount)`, as for all test in this module
/// expected denom is fixed
#[track_caller]
fn assert_transfers(response: Response, mut expected_transfers: Vec<(&str, u128)>) {
let mut sends: Vec<_> = response
.messages
.into_iter()
.map(|msg| match msg.msg {
// Trick is used here - bank send messages are filtered out, and mapped to tripple
// `(addr, amount_sum, msg)` - `addr` and `amount_sum` would be used only to
// properly sort messages, then they would be discarded. As in expected messages
// always only one coin is expected for all send messages, taking sum for sorting
// is good enough - in case of multiple of invalid denoms it would be visible on
// comparison.
//
// Possibly in future it would be possible for another messages to occur - in such
// case instead of returning err and panicking from this function, such messages
// should be filtered out.
CosmosMsg::Bank(BankMsg::Send { to_address, amount }) => Ok((
to_address.clone(),
amount.iter().map(|c| c.amount).sum::<Uint128>(),
BankMsg::Send { to_address, amount },
)),
msg => Err(format!(
"Unexpected message on response, expected only bank send messages: {:?}",
msg
)),
})
.collect::<Result<_, _>>()
.unwrap();
sends.sort_by_key(|(addr, amount_sum, _)| (addr.clone(), *amount_sum));
// Drop addr and amount_sum for comparison
let sends: Vec<_> = sends.into_iter().map(|(_, _, msg)| msg).collect();
// Tuples are sorted simply first by addresses, then by amount
expected_transfers.sort_unstable();
// Build messages for comparison
let expected_transfers: Vec<_> = expected_transfers
.into_iter()
.map(|(addr, amount)| BankMsg::Send {
to_address: addr.to_owned(),
amount: coins(amount, DENOM),
})
.collect();
assert_eq!(sends, expected_transfers);
}
#[test]
fn single_claim() {
let mut deps = mock_deps_tgrade();
do_instantiate(deps.as_mut(), 2);
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
let height_delta = 2;
unbond(deps.as_mut(), 1000, 0, 0, height_delta, 0);
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(UNBONDING_DURATION);
let resp = end_block(deps.as_mut(), env).unwrap();
assert_transfers(resp, vec![(USER1, 1000)]);
}
#[test]
fn multiple_users_claims() {
let mut deps = mock_deps_tgrade();
do_instantiate(deps.as_mut(), 4);
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
let height_delta = 2;
unbond(deps.as_mut(), 1000, 500, 0, height_delta, 0);
unbond(deps.as_mut(), 0, 0, 200, height_delta, 1);
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(UNBONDING_DURATION + 1);
let resp = end_block(deps.as_mut(), env).unwrap();
assert_transfers(resp, vec![(USER1, 1000), (USER2, 500), (USER3, 200)]);
}
#[test]
fn single_user_multiple_claims() {
let mut deps = mock_deps_tgrade();
do_instantiate(deps.as_mut(), 3);
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
let height_delta = 2;
unbond(deps.as_mut(), 1000, 0, 0, height_delta, 0);
unbond(deps.as_mut(), 500, 0, 0, height_delta, 1);
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(UNBONDING_DURATION + 1);
let resp = end_block(deps.as_mut(), env).unwrap();
assert_transfers(resp, vec![(USER1, 1500)]);
}
#[test]
fn only_expired_claims() {
let mut deps = mock_deps_tgrade();
do_instantiate(deps.as_mut(), 3);
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
let height_delta = 2;
// Claims to be returned
unbond(deps.as_mut(), 1000, 0, 0, height_delta, 0);
unbond(deps.as_mut(), 500, 600, 0, height_delta, 1);
// Clams not yet expired
unbond(deps.as_mut(), 200, 300, 400, height_delta, 2);
unbond(deps.as_mut(), 700, 0, 0, height_delta, 3);
unbond(deps.as_mut(), 0, 100, 50, height_delta, 4);
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(UNBONDING_DURATION + 1);
let resp = end_block(deps.as_mut(), env).unwrap();
assert_transfers(resp, vec![(USER1, 1500), (USER2, 600)]);
}
#[test]
fn claim_returned_once() {
let mut deps = mock_deps_tgrade();
do_instantiate(deps.as_mut(), 5);
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
let height_delta = 2;
// Claims to be returned
unbond(deps.as_mut(), 1000, 0, 0, height_delta, 0);
unbond(deps.as_mut(), 500, 600, 0, height_delta, 1);
// Clams not yet expired
unbond(deps.as_mut(), 200, 300, 400, height_delta, 2);
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(UNBONDING_DURATION + 1);
let resp = end_block(deps.as_mut(), env).unwrap();
assert_transfers(resp, vec![(USER1, 1500), (USER2, 600)]);
// Some additional claims
unbond(deps.as_mut(), 700, 0, 0, height_delta, 3);
unbond(deps.as_mut(), 0, 100, 50, height_delta, 4);
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(UNBONDING_DURATION + 3);
// Expected that claims at time offset 2 and 3 are returned (0 and 1 are already
// returned, 4 is not yet expired)
let resp = end_block(deps.as_mut(), env).unwrap();
assert_transfers(resp, vec![(USER1, 900), (USER2, 300), (USER3, 400)]);
}
#[test]
fn up_to_limit_claims_returned() {
let mut deps = mock_deps_tgrade();
do_instantiate(deps.as_mut(), 2);
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
let height_delta = 2;
// Claims to be returned
unbond(deps.as_mut(), 1000, 500, 0, height_delta, 0);
unbond(deps.as_mut(), 0, 600, 0, height_delta, 1);
unbond(deps.as_mut(), 200, 0, 0, height_delta, 2);
unbond(deps.as_mut(), 0, 0, 300, height_delta, 3);
// Even if all claims are already expired, only two of them (time offset 0) should be
// returned
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(UNBONDING_DURATION + 3);
let resp = end_block(deps.as_mut(), env).unwrap();
assert_transfers(resp, vec![(USER1, 1000), (USER2, 500)]);
// Then on next block next batch is returned (time offset 1 and 2)
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(UNBONDING_DURATION + 4);
let resp = end_block(deps.as_mut(), env).unwrap();
assert_transfers(resp, vec![(USER1, 200), (USER2, 600)]);
// Some additional claims
unbond(deps.as_mut(), 700, 0, 0, height_delta, 5);
unbond(deps.as_mut(), 0, 100, 50, height_delta, 6);
// Claims are returned in batches
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(UNBONDING_DURATION + 6);
// offset 3 and 5
let resp = end_block(deps.as_mut(), env).unwrap();
assert_transfers(resp, vec![(USER1, 700), (USER3, 300)]);
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(UNBONDING_DURATION + 6);
// offset 6
let resp = end_block(deps.as_mut(), env).unwrap();
assert_transfers(resp, vec![(USER2, 100), (USER3, 50)]);
}
#[test]
fn unbound_with_invalid_denom_fails() {
let mut deps = mock_deps_tgrade();
do_instantiate(deps.as_mut(), 2);
bond_liquid(deps.as_mut(), 5_000, 0, 0, 1);
let height_delta = 2;
let mut env = mock_env();
env.block.height += height_delta;
let msg = ExecuteMsg::Unbond {
tokens: coin(5_000, "invalid"),
};
let info = mock_info(USER1, &[]);
let err = execute(deps.as_mut(), env, info, msg).unwrap_err();
assert_eq!(ContractError::InvalidDenom("invalid".to_owned()), err);
}
}
}
| 35.340102 | 102 | 0.559322 |
9be5bfded5466fe20801a7e03493f897bc673906 | 44 | js | JavaScript | resources/js/pages/Informes/FlotaRenta/InformePendientes/index.js | williamcastrov/gimcloud | baa0040a0fe282a3280350d3d9ec1c157c3ba81f | [
"MIT"
] | null | null | null | resources/js/pages/Informes/FlotaRenta/InformePendientes/index.js | williamcastrov/gimcloud | baa0040a0fe282a3280350d3d9ec1c157c3ba81f | [
"MIT"
] | null | null | null | resources/js/pages/Informes/FlotaRenta/InformePendientes/index.js | williamcastrov/gimcloud | baa0040a0fe282a3280350d3d9ec1c157c3ba81f | [
"MIT"
] | null | null | null | export {default} from "./InformePendientes"; | 44 | 44 | 0.772727 |
9426fcb7ea440643804eb35858c7da04b7cabdff | 216 | asm | Assembly | src/commands/DoAdd.asm | jhm-ciberman/calculator-asm | f5305f345d7efdd616b34a485f7460f6789f4d9c | [
"MIT"
] | 2 | 2019-08-03T17:09:30.000Z | 2021-04-01T22:17:09.000Z | src/commands/DoAdd.asm | jhm-ciberman/calculator-asm | f5305f345d7efdd616b34a485f7460f6789f4d9c | [
"MIT"
] | null | null | null | src/commands/DoAdd.asm | jhm-ciberman/calculator-asm | f5305f345d7efdd616b34a485f7460f6789f4d9c | [
"MIT"
] | 1 | 2019-08-04T21:26:32.000Z | 2019-08-04T21:26:32.000Z | proc DoAdd uses r14
fastcall ArrayListPop, [_lg_stack]
mov r14, rax
fastcall ArrayListPop, [_lg_stack]
add r14, rax
fastcall ArrayListPush, [_lg_stack], r14
ret
endp | 18 | 45 | 0.611111 |
72ea7a1b29263d7d28820b37c99b83166ab3488b | 15,384 | html | HTML | _volume_pages/0446.html | jcmundy/italy-handbook-for-travellers-test1 | 4941ba70b48cb53c5f5381e915d156b6f3e42b40 | [
"MIT"
] | null | null | null | _volume_pages/0446.html | jcmundy/italy-handbook-for-travellers-test1 | 4941ba70b48cb53c5f5381e915d156b6f3e42b40 | [
"MIT"
] | null | null | null | _volume_pages/0446.html | jcmundy/italy-handbook-for-travellers-test1 | 4941ba70b48cb53c5f5381e915d156b6f3e42b40 | [
"MIT"
] | null | null | null | ---
sort_order: 446
tei_id: p.idp190689488
annotation_count: 0
images:
small-thumbnail: https://testreadux.ecds.emory.edu/books/emory:bnjdz/pages/emory:ksn3j/mini-thumbnail/
json: https://testreadux.ecds.emory.edu/books/emory:bnjdz/pages/emory:ksn3j/info/
full: https://testreadux.ecds.emory.edu/books/emory:bnjdz/pages/emory:ksn3j/fs/
page: https://testreadux.ecds.emory.edu/books/emory:bnjdz/pages/emory:ksn3j/single-page/
thumbnail: https://testreadux.ecds.emory.edu/books/emory:bnjdz/pages/emory:ksn3j/thumbnail/
title: Page 445
number: 445
permalink: "/pages/445/"
---
<div class="ocr-line ocrtext" style="left:19.39%;top:4.45%;width:65.33%;height:1.86%;text-align:left;font-size:18.63px" data-vhfontsize="1.86">
<span>{% raw %}Pal. Pubblico. BOLOGNA. 47. Route. 309{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:16.27%;top:8.42%;width:68.68%;height:1.41%;text-align:left;font-size:14.14px" data-vhfontsize="1.41">
<span></span>
</div>
<div class="ocr-line ocrtext" style="left:16.27%;top:8.42%;width:68.68%;height:1.41%;text-align:left;font-size:14.14px" data-vhfontsize="1.41">
<span>{% raw %}of S. Onofrio were executed by Jacopo della Quercia of Siena, one of the{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:16.27%;top:9.8%;width:68.73%;height:1.41%;text-align:left;font-size:14.14px" data-vhfontsize="1.41">
<span>{% raw %}founders of Renaissance sculpture; and even Michael Angelo, when a{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:16.08%;top:11.14%;width:68.77%;height:1.38%;text-align:left;font-size:13.8px" data-vhfontsize="1.38">
<span>{% raw %}fugitive from Florence after the banishment of the Medici (1494), found{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:16.04%;top:12.56%;width:68.82%;height:1.31%;text-align:left;font-size:13.11px" data-vhfontsize="1.31">
<span>{% raw %}occupation in the church of S. Domenico. Tribolo was likewise employed{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.94%;top:13.87%;width:68.77%;height:1.38%;text-align:left;font-size:13.8px" data-vhfontsize="1.38">
<span>{% raw %}here. Of the Upper Italian masters, who are well represented at Bologna,{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.99%;top:15.28%;width:68.73%;height:1.35%;text-align:left;font-size:13.45px" data-vhfontsize="1.35">
<span>{% raw %}Alfonso Lombardi, or properly Cittadella of Lucca (1488-1537), holds the{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.85%;top:16.63%;width:68.87%;height:1.35%;text-align:left;font-size:13.45px" data-vhfontsize="1.35">
<span>{% raw %}highest rank. Bologna was also the birthplace of Properzia de"Rossi (1490-{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:16.08%;top:17.97%;width:68.49%;height:1.35%;text-align:left;font-size:13.45px" data-vhfontsize="1.35">
<span>{% raw %}1530), one of the few women who have devoted themselves to sculpture.{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:19.76%;top:19.35%;width:64.95%;height:1.28%;text-align:left;font-size:12.76px" data-vhfontsize="1.28">
<span>{% raw %}In the province of Painting the first master who attained more than{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:16.08%;top:20.73%;width:68.63%;height:1.35%;text-align:left;font-size:13.45px" data-vhfontsize="1.35">
<span>{% raw %}a local reputation was Francesco Francia (1450-1517), the goldsmith, a{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.9%;top:22.08%;width:68.82%;height:1.31%;text-align:left;font-size:13.11px" data-vhfontsize="1.31">
<span>{% raw %}pupil of Zoppo of Ferrara. In the devotion and gracefulness of his female{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.9%;top:23.46%;width:68.82%;height:1.24%;text-align:left;font-size:12.42px" data-vhfontsize="1.24">
<span>{% raw %}figures he almost rivals Perugino. His son Giacomo Francia was influenced{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.85%;top:24.84%;width:68.92%;height:1.28%;text-align:left;font-size:12.76px" data-vhfontsize="1.28">
<span>{% raw %}by the Venetian school, while at the same time the school of Raphael{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.9%;top:26.18%;width:68.77%;height:1.28%;text-align:left;font-size:12.76px" data-vhfontsize="1.28">
<span>{% raw %}gained ground at Bologna. The chief adherents of the latter were Bartol.{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.85%;top:27.46%;width:68.77%;height:1.45%;text-align:left;font-size:14.49px" data-vhfontsize="1.45">
<span>{% raw %}Ramenghi, surnamed Bagnacavallo (d. 1542), and Innocenzo da Imbla (d.{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.85%;top:28.84%;width:68.87%;height:1.35%;text-align:left;font-size:13.45px" data-vhfontsize="1.35">
<span>{% raw %}1550?). Bologna attained its greatest importance at the close of the 16th{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.8%;top:30.29%;width:68.92%;height:1.31%;text-align:left;font-size:13.11px" data-vhfontsize="1.31">
<span>{% raw %}century. The mannerism into which Italian painting had gradually lapsed,{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.75%;top:31.67%;width:69.01%;height:1.24%;text-align:left;font-size:12.42px" data-vhfontsize="1.24">
<span>{% raw %}was resisted by the Eclectics, whose style was mainly introduced by{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.75%;top:32.94%;width:69.01%;height:1.38%;text-align:left;font-size:13.8px" data-vhfontsize="1.38">
<span>{% raw %}Lodovico Carracci (1555-1619). In teaching at his academy he inculcated a{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.8%;top:34.36%;width:68.92%;height:1.31%;text-align:left;font-size:13.11px" data-vhfontsize="1.31">
<span>{% raw %}thorough mastery of the elements of art, a comprehensive education, and{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.8%;top:35.74%;width:68.77%;height:1.28%;text-align:left;font-size:12.76px" data-vhfontsize="1.28">
<span>{% raw %}a careful study of the great masters. The school was afterwards carried{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.75%;top:37.01%;width:68.96%;height:1.38%;text-align:left;font-size:13.8px" data-vhfontsize="1.38">
<span>{% raw %}on by his cousins Agostino (1558-1601) and Annibale Carracci (1560-1609),{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.8%;top:38.46%;width:69.01%;height:1.31%;text-align:left;font-size:13.11px" data-vhfontsize="1.31">
<span>{% raw %}the last of whom in particular possessed a refined sense of colour, devel¬{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.75%;top:39.81%;width:69.06%;height:1.31%;text-align:left;font-size:13.11px" data-vhfontsize="1.31">
<span>{% raw %}oped by the study of Correggio. To this school belonged also Guido{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.8%;top:41.12%;width:68.96%;height:1.35%;text-align:left;font-size:13.45px" data-vhfontsize="1.35">
<span>{% raw %}Reni (1574-1642), Domenichino (Domenico Zampieri; 1581-1641), and Albani{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.85%;top:42.5%;width:68.92%;height:1.35%;text-align:left;font-size:13.45px" data-vhfontsize="1.35">
<span>{% raw %}(1578-1660), who exercised a great influence on Italian art in the 17th{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.9%;top:43.88%;width:68.63%;height:1.31%;text-align:left;font-size:13.11px" data-vhfontsize="1.31">
<span>{% raw %}cent., and. effected a temporary revival of good taste. They afterwards{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.85%;top:45.22%;width:68.87%;height:1.35%;text-align:left;font-size:13.45px" data-vhfontsize="1.35">
<span>{% raw %}came into collision with the naturalists, chiefly at Rome and Naples, but{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.9%;top:46.64%;width:35.99%;height:1.28%;text-align:left;font-size:12.76px" data-vhfontsize="1.28">
<span>{% raw %}at Bologna their sway was undisputed.{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:19.58%;top:48.4%;width:65.05%;height:1.79%;text-align:left;font-size:17.94px" data-vhfontsize="1.79">
<span></span>
</div>
<div class="ocr-line ocrtext" style="left:19.58%;top:48.4%;width:65.05%;height:1.79%;text-align:left;font-size:17.94px" data-vhfontsize="1.79">
<span>{% raw %}The *Piazza Vittorio Emmanuele (PI. E, 4, 5), formerly Piazza{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.9%;top:50.29%;width:68.73%;height:1.62%;text-align:left;font-size:16.21px" data-vhfontsize="1.62">
<span>{% raw %}Maggiore , in the centre of the town, the medieval 'forum' of Bo¬{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.8%;top:52.16%;width:68.82%;height:1.55%;text-align:left;font-size:15.52px" data-vhfontsize="1.55">
<span>{% raw %}logna , is one of the most interesting in Italy. It is adorned with{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.8%;top:53.95%;width:68.82%;height:1.55%;text-align:left;font-size:15.52px" data-vhfontsize="1.55">
<span>{% raw %}a Fountain by Laureti; the bronze statue of Neptune, executed by{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.99%;top:55.64%;width:68.68%;height:1.86%;text-align:left;font-size:18.63px" data-vhfontsize="1.86">
<span>{% raw %}Giov. da Bologna (born 1524 at Douay in Flanders) in 1564, is{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.8%;top:57.47%;width:68.77%;height:1.72%;text-align:left;font-size:17.25px" data-vhfontsize="1.72">
<span>{% raw %}said to weigh 10 tons, and to have cost 70,000 ducats. The{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.75%;top:59.43%;width:68.77%;height:1.52%;text-align:left;font-size:15.18px" data-vhfontsize="1.52">
<span>{% raw %}smaller part of the Piazza on the N. side is sometimes called{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.75%;top:61.23%;width:19.62%;height:1.24%;text-align:left;font-size:12.42px" data-vhfontsize="1.24">
<span>{% raw %}Piazza del Nettuno.{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:19.43%;top:63.02%;width:65.05%;height:1.45%;text-align:left;font-size:14.49px" data-vhfontsize="1.45">
<span>{% raw %}In the Piazza Vitt. Emmanuele is situated the Palazzo Pubblico,{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.66%;top:64.75%;width:68.87%;height:1.76%;text-align:left;font-size:17.59px" data-vhfontsize="1.76">
<span>{% raw %}or del Governo (PI. D, 4, 5), formerly Pal. Apostolico, begun in{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.85%;top:66.54%;width:68.58%;height:1.69%;text-align:left;font-size:16.9px" data-vhfontsize="1.69">
<span>{% raw %}1290, adorned with a Madonna on the facade by Niccolo delV Area{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.71%;top:68.37%;width:68.82%;height:1.79%;text-align:left;font-size:17.94px" data-vhfontsize="1.79">
<span>{% raw %}(d. 1494) and a bronze statue of Pope Gregory XIII. (Buoncompagni{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.71%;top:70.13%;width:68.68%;height:1.79%;text-align:left;font-size:17.94px" data-vhfontsize="1.79">
<span>{% raw %}of Bologna) by Menganti, which was transformed in 1796 into a sta¬{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.66%;top:72.09%;width:68.77%;height:1.52%;text-align:left;font-size:15.18px" data-vhfontsize="1.52">
<span>{% raw %}tue of St. Petronius. The grand staircase in the interior was de¬{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.75%;top:73.75%;width:68.68%;height:1.76%;text-align:left;font-size:17.59px" data-vhfontsize="1.76">
<span>{% raw %}signed by Bramante (1509); the galleries and halls are decorated{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.66%;top:75.61%;width:68.73%;height:1.76%;text-align:left;font-size:17.59px" data-vhfontsize="1.76">
<span>{% raw %}with frescoes; a colossal sitting figure of Hercules (in plaster) in{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.66%;top:77.47%;width:68.73%;height:1.62%;text-align:left;font-size:16.21px" data-vhfontsize="1.62">
<span>{% raw %}the hall of that name, by Alfonso Lombardi; in the Sala Farnese a{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.85%;top:79.37%;width:23.58%;height:1.48%;text-align:left;font-size:14.83px" data-vhfontsize="1.48">
<span>{% raw %}statue of Paul III., etc.{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:19.48%;top:81.03%;width:64.86%;height:1.31%;text-align:left;font-size:13.11px" data-vhfontsize="1.31">
<span>{% raw %}In the Via delle Asse, which opens to the S. of the Palazzo Pub¬{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.71%;top:82.34%;width:68.44%;height:1.45%;text-align:left;font-size:14.49px" data-vhfontsize="1.45">
<span>{% raw %}blico, on the right, is the Palazzo Marescalchi (PL D, 4), erected by Dom.{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.85%;top:83.75%;width:68.3%;height:1.31%;text-align:left;font-size:13.11px" data-vhfontsize="1.31">
<span>{% raw %}Tibaldi, and containing some frescoes by Lod. Carracci and Guido Reni.{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.8%;top:85.03%;width:68.54%;height:1.35%;text-align:left;font-size:13.45px" data-vhfontsize="1.35">
<span>{% raw %}— The handsome neighbouring church of S. Salvatore (PL 34; E, 4) was{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.8%;top:86.34%;width:68.44%;height:1.41%;text-align:left;font-size:14.14px" data-vhfontsize="1.41">
<span>{% raw %}built by Magenta in 1603. 1st chapel to the left, Garofalo, Zacharias, St.{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.75%;top:87.72%;width:68.49%;height:1.45%;text-align:left;font-size:14.49px" data-vhfontsize="1.45">
<span>{% raw %}John, and saints; 3rd chapel (1.) Inn. da Imola, Christ and four saints;{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.66%;top:89.1%;width:68.58%;height:1.38%;text-align:left;font-size:13.8px" data-vhfontsize="1.38">
<span>{% raw %}left transept, Tiarini, Nativity. — S. Francesco (PL 12), now a military{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:15.66%;top:90.44%;width:42.03%;height:1.38%;text-align:left;font-size:13.8px" data-vhfontsize="1.38">
<span>{% raw %}magazine, contains a handsome altar of 1388.{% endraw %}</span>
</div>
<div class="ocr-line ocrtext" style="left:19.43%;top:91.86%;width:64.53%;height:1.72%;text-align:left;font-size:17.25px" data-vhfontsize="1.72">
<span>{% raw %}On the N. side of the Piazza is the Palazzo del Podesta (PI.{% endraw %}</span>
</div>
| 79.298969 | 144 | 0.693513 |
d5aa1befd7686b7926c25542f5add036d6cbf354 | 2,221 | swift | Swift | ExifTests/ExifTests.swift | kichikuchi/Exif | 499bbadde9e7ba05ff80c610efc9919c0698ce5b | [
"MIT"
] | 22 | 2017-01-08T10:57:41.000Z | 2021-07-09T01:43:59.000Z | ExifTests/ExifTests.swift | kichikuchi/Exif | 499bbadde9e7ba05ff80c610efc9919c0698ce5b | [
"MIT"
] | null | null | null | ExifTests/ExifTests.swift | kichikuchi/Exif | 499bbadde9e7ba05ff80c610efc9919c0698ce5b | [
"MIT"
] | 4 | 2019-05-22T07:12:42.000Z | 2021-04-06T08:41:12.000Z | //
// ExifTests.swift
// ExifTests
//
// Created by Kazunori Kikuchi on 2019/02/09.
// Copyright © 2019 kazunori kikuchi. All rights reserved.
//
import XCTest
@testable import Exif
class ExifTests: XCTestCase {
func testExif() {
guard let exif = Exif(forResource: "test", ofType: "jpg", bundle: Bundle(for: type(of: self))) else { return }
XCTAssertNotNil(exif)
XCTAssertEqual(exif.pixelWidth, 756)
XCTAssertEqual(exif.pixelHeight, 1008)
XCTAssertEqual(exif.area, [2015, 1511, 2217, 1330])
XCTAssertEqual(exif.lensMaker, "Apple")
XCTAssertEqual(exif.lensModel, "iPhone X back dual camera 4mm f/1.8")
XCTAssertEqual(exif.lensSpecification, [4, 6, 1.8, 2.4])
XCTAssertEqual(exif.focalIn35mmFilm, 28)
XCTAssertEqual(exif.focalLength, 4)
XCTAssertEqual(exif.whiteBalance, 0)
XCTAssertEqual(exif.brightness, 7.082936129647283)
XCTAssertEqual(exif.aperture, 1.695993715632365)
XCTAssertEqual(exif.shutterSpeed, 7.549755301794454)
XCTAssertEqual(exif.isoSpeed, [20])
XCTAssertEqual(exif.sensingMethod, 2)
XCTAssertEqual(exif.fNumber, 1.8)
XCTAssertEqual(exif.exposureProgram, 2)
XCTAssertEqual(exif.exposureMode, 0)
XCTAssertEqual(exif.exposureBias, 0)
XCTAssertEqual(exif.exposureTime, 0.0053475935828877)
XCTAssertEqual(exif.meteringMode, 5)
XCTAssertEqual(exif.flash, 16)
XCTAssertEqual(exif.flashVersion, [1, 0])
XCTAssertEqual(exif.subsecondTimeOriginal, 790)
XCTAssertEqual(exif.subsecondTimeDigitized, 790)
XCTAssertEqual(exif.sceneType, 1)
XCTAssertEqual(exif.sceneCaptureType, 0)
XCTAssertEqual(exif.componentsConfiguration, [1, 2, 3, 0])
XCTAssertEqual(exif.version, [2, 2, 1])
XCTAssertNil(exif.colorSpace)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy:MM:dd HH:mm:ss"
formatter.locale = Locale(identifier: "ja_JP")
let date = formatter.date(from: "2017:11:12 16:21:06")
XCTAssertEqual(exif.dateTimeOriginal, date)
XCTAssertEqual(exif.dateTimeDigitized, date)
}
}
| 39.660714 | 118 | 0.67222 |
68ae5247d0d2dd3f37f72ff1b08a42fb261e7a57 | 731 | sql | SQL | openGaussBase/testcase/KEYWORDS/types/Opengauss_Function_Keyword_Types_Case0021.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | openGaussBase/testcase/KEYWORDS/types/Opengauss_Function_Keyword_Types_Case0021.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | openGaussBase/testcase/KEYWORDS/types/Opengauss_Function_Keyword_Types_Case0021.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | -- @testpoint: opengauss关键字types(非保留),作为函数名,部分测试点合理报错
--关键字不带引号-成功
drop function if exists types;
create function types(i integer)
returns integer
as $$
begin
return i+1;
end;
$$ language plpgsql;
/
drop function if exists types;
--关键字带双引号-成功
drop function if exists "types";
create function "types"(i integer)
returns integer
as $$
begin
return i+1;
end;
$$ language plpgsql;
/
drop function if exists "types";
--关键字带单引号-合理报错
drop function if exists 'types';
create function 'types'(i integer)
returns integer
as $$
begin
return i+1;
end;
$$ language plpgsql;
/
--关键字带反引号-合理报错
drop function if exists `types`;
create function `types`(i integer)
returns integer
as $$
begin
return i+1;
end;
$$ language plpgsql;
/
| 16.244444 | 53 | 0.723666 |
fa9665536f2500479220157996c3e27d9092dc29 | 7,105 | sql | SQL | sql_change.sql | firesWu/eos_sql_db_plugin | 4c99ddc321ef4a2592b94888203aba4722c1ca1a | [
"MIT"
] | 1 | 2019-03-18T06:28:24.000Z | 2019-03-18T06:28:24.000Z | sql_change.sql | firesWu/eos_sql_db_plugin | 4c99ddc321ef4a2592b94888203aba4722c1ca1a | [
"MIT"
] | null | null | null | sql_change.sql | firesWu/eos_sql_db_plugin | 4c99ddc321ef4a2592b94888203aba4722c1ca1a | [
"MIT"
] | null | null | null | USE eos;
ALTER TABLE accounts_keys DROP FOREIGN KEY accounts_keys_ibfk_1;
ALTER TABLE actions DROP FOREIGN KEY actions_ibfk_1;
ALTER TABLE actions DROP FOREIGN KEY actions_ibfk_2;
ALTER TABLE actions_accounts DROP FOREIGN KEY actions_accounts_ibfk_1;
ALTER TABLE actions_accounts DROP FOREIGN KEY actions_accounts_ibfk_2;
ALTER TABLE blocks DROP FOREIGN KEY blocks_ibfk_1;
ALTER TABLE stakes DROP FOREIGN KEY stakes_ibfk_1;
ALTER TABLE tokens DROP FOREIGN KEY tokens_ibfk_1;
ALTER TABLE transactions DROP FOREIGN KEY transactions_ibfk_1;
ALTER TABLE votes DROP FOREIGN KEY votes_ibfk_1;
ALTER TABLE `tokens` CHANGE `amount` `amount` double(64,4) NOT NULL DEFAULT 0.0000;
ALTER TABLE `accounts_keys` CHANGE COLUMN `public_key` `public_key` varchar(64) NOT NULL DEFAULT '';
ALTER TABLE `actions` ADD COLUMN `eosto` varchar(12) GENERATED ALWAYS AS (`data` ->> '$.to');
ALTER TABLE `actions` ADD COLUMN `eosfrom` varchar(12) GENERATED ALWAYS AS (`data` ->> '$.from');
ALTER TABLE `actions` ADD COLUMN `receiver` varchar(12) GENERATED ALWAYS AS (`data` ->> '$.receiver');
ALTER TABLE `actions` ADD COLUMN `payer` varchar(12) GENERATED ALWAYS AS (`data` ->> '$.payer');
ALTER TABLE `actions` ADD COLUMN `newaccount` varchar(12) GENERATED ALWAYS AS (`data` ->> '$.name');
ALTER TABLE `actions` ADD INDEX `idx_actions_name` (`name`);
ALTER TABLE `actions` ADD INDEX `idx_actions_eosto` (`eosto`);
ALTER TABLE `actions` ADD INDEX `idx_actions_eosfrom` (`eosfrom`);
ALTER TABLE `actions` ADD INDEX `idx_actions_receiver` (`receiver`);
ALTER TABLE `actions` ADD INDEX `idx_actions_payer` (`payer`);
ALTER TABLE `actions` ADD INDEX `idx_actions_newaccount` (`newaccount`);
ALTER TABLE `accounts` DROP PRIMARY KEY;
ALTER TABLE `accounts` ADD COLUMN `id` bigint(20) NOT NULL primary key auto_increment first;
ALTER TABLE `accounts` ADD INDEX `idx_accounts_name`(`name`);
ALTER TABLE `accounts` CHANGE COLUMN `name` `name` varchar(12) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `accounts` CHANGE COLUMN `created_at` `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE `accounts` CHANGE COLUMN `updated_at` `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
ALTER TABLE `accounts_keys` ADD COLUMN `id` bigint(20) NOT NULL primary key auto_increment first;
ALTER TABLE `accounts_keys` CHANGE COLUMN `account` `account` varchar(16) NOT NULL DEFAULT '';
ALTER TABLE `accounts_keys` CHANGE COLUMN `permission` `permission` varchar(16) NOT NULL DEFAULT '';
ALTER TABLE `actions` CHANGE COLUMN `id` `id` bigint(20) NOT NULL auto_increment first;
ALTER TABLE `actions` CHANGE COLUMN `account` `account` varchar(16) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `actions` CHANGE COLUMN `transaction_id` `transaction_id` varchar(64) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `actions` CHANGE COLUMN `seq` `seq` smallint(6) NOT NULL DEFAULT 0;
ALTER TABLE `actions` CHANGE COLUMN `parent` `parent` bigint(20) NOT NULL DEFAULT 0;
ALTER TABLE `actions` CHANGE COLUMN `name` `name` varchar(12) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `actions` CHANGE COLUMN `created_at` `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE `actions_accounts` ADD COLUMN `id` bigint(20) NOT NULL primary key auto_increment first;
ALTER TABLE `actions_accounts` CHANGE COLUMN `actor` `actor` varchar(16) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `actions_accounts` CHANGE COLUMN `permission` `permission` varchar(16) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `actions_accounts` CHANGE COLUMN `action_id` `action_id` bigint(20) NOT NULL DEFAULT 0;
ALTER TABLE `blocks` CHANGE COLUMN `block_number` `block_number` bigint(20) NOT NULL AUTO_INCREMENT;
ALTER TABLE `blocks` CHANGE COLUMN `id` `id` varchar(64) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `blocks` CHANGE COLUMN `prev_block_id` `prev_block_id` varchar(64) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `blocks` CHANGE COLUMN `irreversible` `irreversible` tinyint(1) NOT NULL DEFAULT '0';
ALTER TABLE `blocks` CHANGE COLUMN `timestamp` `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE `blocks` CHANGE COLUMN `transaction_merkle_root` `transaction_merkle_root` varchar(64) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `blocks` CHANGE COLUMN `action_merkle_root` `action_merkle_root` varchar(64) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `blocks` CHANGE COLUMN `producer` `producer` varchar(12) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `blocks` CHANGE COLUMN `version` `version` bigint(20) NOT NULL DEFAULT '0';
ALTER TABLE `blocks` CHANGE COLUMN `num_transactions` `num_transactions` bigint(20) NOT NULL DEFAULT '0';
ALTER TABLE `blocks` CHANGE COLUMN `confirmed` `confirmed` bigint(20) NOT NULL DEFAULT '0';
ALTER TABLE `stakes` DROP PRIMARY KEY;
ALTER TABLE `stakes` ADD COLUMN `id` bigint(20) NOT NULL primary key auto_increment first;
ALTER TABLE `stakes` ADD UNIQUE INDEX `idx_stakes_account` (`account`);
ALTER TABLE `stakes` CHANGE COLUMN `account` `account` varchar(16) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `stakes` CHANGE COLUMN `cpu` `cpu` double(14,4) NOT NULL DEFAULT 0.0000;
ALTER TABLE `stakes` CHANGE COLUMN `net` `net` double(14,4) NOT NULL DEFAULT 0.0000;
ALTER TABLE `tokens` ADD COLUMN `id` bigint(20) NOT NULL primary key auto_increment first;
ALTER TABLE `tokens` CHANGE COLUMN `account` `account` varchar(16) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `tokens` CHANGE COLUMN `symbol` `symbol` varchar(16) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
ALTER TABLE `tokens` CHANGE COLUMN `amount` `amount` double(64,4) NOT NULL DEFAULT 0.0000;
ALTER TABLE `transactions` DROP PRIMARY KEY;
ALTER TABLE `transactions` ADD COLUMN `tx_id` bigint(20) NOT NULL primary key auto_increment first;
ALTER TABLE `transactions` ADD UNIQUE INDEX `idx_transactions_id` (`id`);
ALTER TABLE `transactions` CHANGE COLUMN `block_id` `block_id` bigint(20) NOT NULL DEFAULT '0';
ALTER TABLE `transactions` CHANGE COLUMN `ref_block_num` `ref_block_num` bigint(20) NOT NULL DEFAULT '0';
ALTER TABLE `transactions` CHANGE COLUMN `ref_block_prefix` `ref_block_prefix` bigint(20) NOT NULL DEFAULT '0';
ALTER TABLE `transactions` CHANGE COLUMN `expiration` `expiration` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE `transactions` CHANGE COLUMN `pending` `pending` tinyint(1) NOT NULL DEFAULT '0';
ALTER TABLE `transactions` CHANGE COLUMN `created_at` `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE `transactions` CHANGE COLUMN `num_actions` `num_actions` bigint(20) DEFAULT '0';
ALTER TABLE `transactions` CHANGE COLUMN `updated_at` `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE `votes` DROP PRIMARY KEY;
ALTER TABLE `votes` ADD COLUMN `id` bigint(20) NOT NULL primary key auto_increment first;
ALTER TABLE `votes` CHANGE COLUMN `account` `account` varchar(16) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '';
| 76.397849 | 146 | 0.781562 |
268878f51f0eac2767efe9a49c3d412a4691dcd4 | 994 | java | Java | summerframework-lock/platform-lock-core/src/main/java/com/bkjk/platform/lock/LockHandler.java | WangSZ/summerframework | 03f3cae8128c013324a3e961056ae5d1d64f57be | [
"Apache-2.0"
] | null | null | null | summerframework-lock/platform-lock-core/src/main/java/com/bkjk/platform/lock/LockHandler.java | WangSZ/summerframework | 03f3cae8128c013324a3e961056ae5d1d64f57be | [
"Apache-2.0"
] | null | null | null | summerframework-lock/platform-lock-core/src/main/java/com/bkjk/platform/lock/LockHandler.java | WangSZ/summerframework | 03f3cae8128c013324a3e961056ae5d1d64f57be | [
"Apache-2.0"
] | null | null | null | package com.bkjk.platform.lock;
import com.bkjk.platform.lock.exception.LockFailedException;
import java.util.concurrent.TimeUnit;
/**
* @Program: summerframework2
* @Description:
* @Author: shaoze.wang
* @Create: 2019/5/6 10:16
**/
public interface LockHandler {
/**
* 获取锁超时
* @param lockInstance
*
* @return null表示最终返回returnObject;返回回任意值表是用该值代替returnObject。
*/
default Object onLockFailed(LockInstance lockInstance){
// throw
throw new LockFailedException(String.format("LockInstance: %s", lockInstance.toString()),lockInstance.getLockFailed());
};
/**
* 加锁
* @return
*/
default boolean doLock(LockInstance lockInstance) throws InterruptedException {
return lockInstance.getLock().tryLock(lockInstance.getTimeoutMillis(), TimeUnit.MILLISECONDS);
};
/**
* 解锁
* @return
*/
default void doUnlock(LockInstance lockInstance){
lockInstance.getLock().unlock();
};
}
| 23.116279 | 127 | 0.667002 |
062317cf604e40865708f0f234e45075ebb7d5f5 | 1,922 | kt | Kotlin | base_library/src/main/java/com/example/base_library/base_utils/ExceptionHandle.kt | jiwenjie/Graduation_App | a3730f1758f8fe8d13cdd1d53045fa229f7e166d | [
"Apache-2.0"
] | 11 | 2018-12-27T04:49:24.000Z | 2022-03-03T11:44:47.000Z | base_library/src/main/java/com/example/base_library/base_utils/ExceptionHandle.kt | jiwenjie/Graduation_App | a3730f1758f8fe8d13cdd1d53045fa229f7e166d | [
"Apache-2.0"
] | null | null | null | base_library/src/main/java/com/example/base_library/base_utils/ExceptionHandle.kt | jiwenjie/Graduation_App | a3730f1758f8fe8d13cdd1d53045fa229f7e166d | [
"Apache-2.0"
] | 4 | 2019-07-03T02:29:40.000Z | 2021-10-13T03:29:06.000Z | package com.example.base_library.base_utils
import com.google.gson.JsonParseException
import org.json.JSONException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.text.ParseException
/**
* author:Jiwenjie
* email:278630464@qq.com
* time:2019/01/07
* desc:异常处理类
* version:1.0
*/
class ExceptionHandle {
companion object {
var errorCode = ErrorStatus.UNKNOWN_ERROR
var errorMsg = "请求失败,请稍后再试"
fun handleException(e: Throwable): String {
e.printStackTrace()
if (e is SocketTimeoutException) { // connect timeout
LogUtils.e("网络连接异常:" + e.message)
errorMsg = "网络连接异常"
errorCode = ErrorStatus.NETWORK_ERROR
} else if (e is ConnectException) {
// 视为网络错误
LogUtils.e("网络连接异常:" + e.message)
errorMsg = "网络连接异常"
errorCode = ErrorStatus.NETWORK_ERROR
} else if (e is JsonParseException
|| e is JSONException
|| e is ParseException) {
// parse error
LogUtils.e("数据解析异常:" + e.message)
errorCode = ErrorStatus.SERVER_ERROR
errorMsg = "数据解析异常"
} else if (e is UnknownHostException) {
LogUtils.e("网络连接异常:" + e.message)
errorCode = ErrorStatus.NETWORK_ERROR
errorMsg = "网络连接异常"
} else if (e is IllegalArgumentException) {
errorMsg = "参数错误"
errorCode = ErrorStatus.SERVER_ERROR
} else {
// 未知错误
try {
LogUtils.e("错误:" + e.message)
} catch (e: Exception) {
LogUtils.e("未知错误 Debug 调试")
}
errorMsg = "未知错误,可能抛锚了吧"
errorCode = ErrorStatus.UNKNOWN_ERROR
}
return errorMsg
}
}
}
| 20.446809 | 62 | 0.566077 |
3f8829ee24fe62a0895604c9624f607fbcd081b7 | 7,501 | dart | Dart | lib/flutter_windowmanager.dart | adaptant-labs/flutter_windowmanager | 17810c502e067c2811c2e180950ab2a59df5d2f8 | [
"Apache-2.0"
] | 30 | 2019-10-24T16:04:21.000Z | 2022-02-25T05:43:13.000Z | lib/flutter_windowmanager.dart | adaptant-labs/flutter_windowmanager | 17810c502e067c2811c2e180950ab2a59df5d2f8 | [
"Apache-2.0"
] | 21 | 2020-01-28T07:07:42.000Z | 2022-02-15T08:35:28.000Z | lib/flutter_windowmanager.dart | adaptant-labs/flutter_windowmanager | 17810c502e067c2811c2e180950ab2a59df5d2f8 | [
"Apache-2.0"
] | 15 | 2019-10-25T12:14:16.000Z | 2021-11-04T08:35:01.000Z | import 'dart:async';
import 'package:flutter/services.dart';
/// A base class for manipulating Android WindowManager.LayoutParams.
///
/// The class does not need to be instantiated directly, as it provides all
/// static flags and methods.
class FlutterWindowManager {
// Flags for WindowManager.LayoutParams, as per
// https://developer.android.com/reference/android/view/WindowManager.LayoutParams.html
/// Window flag: as long as this window is visible to the user, allow the lock screen to activate while the screen is on.
static const int FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001;
/// Window flag: when set, inverts the input method focusability of the window.
static const int FLAG_ALT_FOCUSABLE_IM = 0x00020000;
/// Window flag: everything behind this window will be dimmed.
static const int FLAG_DIM_BEHIND = 0x00000002;
/// This constant was deprecated in API level 30. This value became API "by accident", and shouldn't be used by 3rd party applications.
static const int FLAG_FORCE_NOT_FULLSCREEN = 0x00000800;
/// This constant was deprecated in API level 30. Use WindowInsetsController#hide(int) with Type#statusBars() instead.
static const int FLAG_FULLSCREEN = 0x00000400;
/// Indicates whether this window should be hardware accelerated.
static const int FLAG_HARDWARE_ACCELERATED = 0x01000000;
/// Window flag: intended for windows that will often be used when the user is holding the screen against their face, it will aggressively filter the event stream to prevent unintended presses in this situation that may not be desired for a particular window, when such an event stream is detected, the application will receive a CANCEL motion event to indicate this so applications can handle this accordingly by taking no action on the event until the finger is released.
static const int FLAG_IGNORE_CHEEK_PRESSES = 0x00008000;
/// Window flag: as long as this window is visible to the user, keep the device's screen turned on and bright.
static const int FLAG_KEEP_SCREEN_ON = 0x00000080;
/// This constant was deprecated in API level 30. Insets will always be delivered to your application.
static const int FLAG_LAYOUT_INSET_DECOR = 0x00010000;
/// Window flag for attached windows: Place the window within the entire screen, ignoring any constraints from the parent window.
static const int FLAG_LAYOUT_IN_SCREEN = 0x00000100;
/// Window flag: allow window to extend outside of the screen.
static const int FLAG_LAYOUT_NO_LIMITS = 0x00000200;
/// Window flag: this window won't ever get key input focus, so the user can not send key or other button events to it.
static const int FLAG_NOT_FOCUSABLE = 0x00000008;
/// Window flag: this window can never receive touch events.
static const int FLAG_NOT_TOUCHABLE = 0x00000010;
/// Window flag: even when this window is focusable (its FLAG_NOT_FOCUSABLE is not set), allow any pointer events outside of the window to be sent to the windows behind it.
static const int FLAG_NOT_TOUCH_MODAL = 0x00000020;
/// Window flag: a special mode where the layout parameters are used to perform scaling of the surface when it is composited to the screen.
static const int FLAG_SCALED = 0x00004000;
/// Window flag: treat the content of the window as secure, preventing it from appearing in screenshots or from being viewed on non-secure displays.
static const int FLAG_SECURE = 0x00002000;
/// Window flag: ask that the system wallpaper be shown behind your window.
static const int FLAG_SHOW_WALLPAPER = 0x00100000;
/// Window flag: when set the window will accept for touch events outside of its bounds to be sent to other windows that also support split touch.
static const int FLAG_SPLIT_TOUCH = 0x00800000;
/// Window flag: if you have set FLAG_NOT_TOUCH_MODAL, you can set this flag to receive a single special MotionEvent with the action MotionEvent.ACTION_OUTSIDE for touches that occur outside of your window.
static const int FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000;
/// Window flag: enable blur behind for this window.
static const int FLAG_BLUR_BEHIND = 0x00000004;
/// This constant was deprecated in API level 26. Use FLAG_SHOW_WHEN_LOCKED or KeyguardManager#requestDismissKeyguard instead. Since keyguard was dismissed all the time as long as an activity with this flag on its window was focused, keyguard couldn't guard against unintentional touches on the screen, which isn't desired.
static const int FLAG_DISMISS_KEYGUARD = 0x00400000;
/// This constant was deprecated in API level 17. This flag is no longer used.
static const int FLAG_DITHER = 0x00001000;
/// Flag indicating that this Window is responsible for drawing the background for the system bars.
static const int FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS = 0x80000000;
/// Window flag: When requesting layout with an attached window, the attached window may overlap with the screen decorations of the parent window such as the navigation bar. By including this flag, the window manager will layout the attached window within the decor frame of the parent window such that it doesn't overlap with screen decorations.
static const int FLAG_LAYOUT_ATTACHED_IN_DECOR = 0x40000000;
/// Window flag: allow window contents to extend in to the screen's overscan area, if there is one. The window should still correctly position its contents to take the overscan area into account.
static const int FLAG_LAYOUT_IN_OVERSCAN = 0x02000000;
/// Flag for a window in local focus mode.
static const int FLAG_LOCAL_FOCUS_MODE = 0x10000000;
/// Window flag: special flag to let windows be shown when the screen is locked. This will let application windows take precedence over key guard or any other lock screens. Can be used with FLAG_KEEP_SCREEN_ON to turn screen on and display windows directly before showing the key guard window. Can be used with FLAG_DISMISS_KEYGUARD to automatically fully dismisss non-secure keyguards. This flag only applies to the top-most full-screen window.
static const int FLAG_SHOW_WHEN_LOCKED = 0x00080000;
/// Window flag: when set, if the device is asleep when the touch screen is pressed, you will receive this first touch event. Usually the first touch event is consumed by the system since the user can not see what they are pressing on.
static const int FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040;
/// Window flag: request a translucent navigation bar with minimal system-provided background protection.
static const int FLAG_TRANSLUCENT_NAVIGATION = 0x08000000;
/// Window flag: request a translucent status bar with minimal system-provided background protection.
static const int FLAG_TRANSLUCENT_STATUS = 0x04000000;
/// Window flag: when set as a window is being added or made visible, once the window has been shown then the system will poke the power manager's user activity (as if the user had woken up the device) to turn the screen on.
static const int FLAG_TURN_SCREEN_ON = 0x00200000;
static const MethodChannel _channel =
const MethodChannel('flutter_windowmanager');
/// Adds flags [flags] to the WindowManager.LayoutParams
static Future<bool> addFlags(int flags) async {
return await _channel.invokeMethod("addFlags", {
"flags": flags,
});
}
/// Clears flags [flags] from the WindowManager.LayoutParams
static Future<bool> clearFlags(int flags) async {
return await _channel.invokeMethod("clearFlags", {
"flags": flags,
});
}
}
| 60.98374 | 475 | 0.779363 |
65aca0e54a52b16244a4cdcdab9113ee779d04b6 | 1,121 | swift | Swift | VisionDemoApp/TheSoundAnalysis.playground/Pages/SpeechSynthesis.xcplaygroundpage/Contents.swift | ktustanowski/visiondemo | cc921bfcd9c73932e9467ed92a840ac56dbd8275 | [
"MIT"
] | 14 | 2021-09-18T17:02:22.000Z | 2022-03-25T04:53:18.000Z | VisionDemoApp/TheSoundAnalysis.playground/Pages/SpeechSynthesis.xcplaygroundpage/Contents.swift | ktustanowski/visiondemo | cc921bfcd9c73932e9467ed92a840ac56dbd8275 | [
"MIT"
] | 1 | 2021-10-21T18:47:28.000Z | 2022-01-09T17:58:53.000Z | VisionDemoApp/TheSoundAnalysis.playground/Pages/SpeechSynthesis.xcplaygroundpage/Contents.swift | ktustanowski/visiondemo | cc921bfcd9c73932e9467ed92a840ac56dbd8275 | [
"MIT"
] | 1 | 2022-02-22T19:07:48.000Z | 2022-02-22T19:07:48.000Z | //: [Previous](@previous)
import AVFoundation
print(AVSpeechSynthesisVoice.speechVoices())
let englishUtterance = AVSpeechUtterance(string: "Bake the chicken in the oven for fifteen minutes")
englishUtterance.prefersAssistiveTechnologySettings = true
// You can experiment to hear the difference
//englishUtterance.rate = 0.8
//englishUtterance.pitchMultiplier = 0.1
//englishUtterance.postUtteranceDelay = 0.2
//englishUtterance.preUtteranceDelay = 0.2
//englishUtterance.volume = 1.0
//let englishVoice = AVSpeechSynthesisVoice(language: "en-US")
//englishUtterance.voice = englishVoice
let synthesizer = AVSpeechSynthesizer()
synthesizer.usesApplicationAudioSession = false
synthesizer.speak(englishUtterance)
let polishUtterance = AVSpeechUtterance(string: "Piecz kurczaka w piekarniku przez piętnaście minut")
polishUtterance.prefersAssistiveTechnologySettings = true
let polishVoice = AVSpeechSynthesisVoice(language: "pl-PL")
polishUtterance.voice = polishVoice
//let synthesizer = AVSpeechSynthesizer()
synthesizer.usesApplicationAudioSession = false
synthesizer.speak(polishUtterance)
//: [Next](@next)
| 32.970588 | 101 | 0.817128 |
1b8f8656befc82b46706bb495d73f014d33f2d6a | 1,764 | swift | Swift | Spica/Extensions/UserDefaults.swift | devAgam/Spica-iOS | 196e6af5433c95f1d5d7e78c777207ecd227ddbf | [
"MIT"
] | 6 | 2020-07-19T12:49:22.000Z | 2020-07-30T05:25:08.000Z | Spica/Extensions/UserDefaults.swift | rainloreley/Spica-iOS | 06eedc7ad7a9f308ffa30605c36f444bccd79c21 | [
"MIT"
] | 3 | 2020-12-03T15:46:28.000Z | 2020-12-17T18:51:35.000Z | Spica/Extensions/UserDefaults.swift | rainloreley/Spica-iOS | 06eedc7ad7a9f308ffa30605c36f444bccd79c21 | [
"MIT"
] | 3 | 2020-12-03T04:52:15.000Z | 2020-12-17T17:16:25.000Z | //
// Spica for iOS (Spica)
// File created by Lea Baumgart on 10.10.20.
//
// Licensed under the MIT License
// Copyright © 2020 Lea Baumgart. All rights reserved.
//
// https://github.com/SpicaApp/Spica-iOS
//
import Foundation
import UIKit
// Colors
extension UserDefaults {
func colorForKey(key: String) -> UIColor? {
var color: UIColor?
if let colorData = data(forKey: key) {
color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
}
return color
}
func setColor(color: UIColor?, forKey key: String) {
var colorData: NSData?
if let color = color {
colorData = NSKeyedArchiver.archivedData(withRootObject: color) as NSData?
}
set(colorData, forKey: key)
}
}
// Structs
extension UserDefaults {
open func setStruct<T: Codable>(_ value: T?, forKey defaultName: String) {
let data = try? JSONEncoder().encode(value)
set(data, forKey: defaultName)
}
open func structData<T>(_ type: T.Type, forKey defaultName: String) -> T? where T: Decodable {
guard let encodedData = data(forKey: defaultName) else {
return nil
}
return try! JSONDecoder().decode(type, from: encodedData)
}
open func setStructArray<T: Codable>(_ value: [T], forKey defaultName: String) {
let data = value.map { try? JSONEncoder().encode($0) }
set(data, forKey: defaultName)
}
open func structArrayData<T>(_ type: T.Type, forKey defaultName: String) -> [T] where T: Decodable {
guard let encodedData = array(forKey: defaultName) as? [Data] else {
return []
}
return encodedData.map { try! JSONDecoder().decode(type, from: $0) }
}
}
| 28.451613 | 104 | 0.624717 |
85eed57b8e5b2d156a69eb928ba2ac4330278e88 | 1,645 | rs | Rust | src/board/iter.rs | JarredAllen/chess-website | b7655ec9112d937875bada15e10cc830f0b5a412 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/board/iter.rs | JarredAllen/chess-website | b7655ec9112d937875bada15e10cc830f0b5a412 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/board/iter.rs | JarredAllen/chess-website | b7655ec9112d937875bada15e10cc830f0b5a412 | [
"Apache-2.0",
"MIT"
] | null | null | null | use super::Board;
/// An iterator which iterates over the possible moves for the given
/// board
pub struct MoveIter<'a> {
board: &'a Board,
ir: u8,
ic: u8,
fr: u8,
fc: u8,
}
impl<'a> MoveIter<'a> {
pub fn new(board: &'a Board) -> MoveIter<'a> {
MoveIter { board, ir: 0, ic: 0, fr: 0, fc: 0 }
}
}
impl Iterator for MoveIter<'_> {
type Item = ((u8, u8), (u8, u8));
fn next(&mut self) -> Option<Self::Item> {
// TODO Optimize this, so it doesn't have to try all 4096 pairs
// of tiles
loop {
if self.ir >= 8 {
// We've iterated through the entire solution space
return None
}
if self.board.get_pos(self.ir, self.ic).get_side() == self.board.turn {
if let Some(value) = loop {
if self.fr >= 8 {
self.fr = 0;
self.fc = 0;
break None;
}
let out = ((self.ir, self.ic), (self.fr, self.fc));
self.fc += 1;
if self.fc >= 8 {
self.fc = 0;
self.fr += 1;
}
if self.board.is_valid_move((out.0).0, (out.0).1, (out.1).0, (out.1).1) {
break Some(out);
}
} {
return Some(value);
}
}
self.ic += 1;
if self.ic >= 8 {
self.ic = 0;
self.ir += 1;
}
}
}
}
| 26.532258 | 93 | 0.383587 |
b97542d4c1adc0081a6f7f9f4397f66d63339963 | 21,394 | c | C | src/kernel/src/kernel/async_signal.c | GrieferAtWork/KOS | 5376a813854b35e3a3532a6e3b8dbb168478b40f | [
"Zlib"
] | 2 | 2017-02-24T17:14:19.000Z | 2017-10-12T19:26:13.000Z | src/kernel/src/kernel/async_signal.c | GrieferAtWork/KOS | 5376a813854b35e3a3532a6e3b8dbb168478b40f | [
"Zlib"
] | 1 | 2019-11-02T10:21:11.000Z | 2019-11-02T10:21:11.000Z | src/kernel/src/kernel/async_signal.c | GabrielRavier/KOSmk3 | 5376a813854b35e3a3532a6e3b8dbb168478b40f | [
"Zlib"
] | 1 | 2019-11-02T10:20:19.000Z | 2019-11-02T10:20:19.000Z | /* Copyright (c) 2018 Griefer@Work *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
*/
#ifndef GUARD_KERNEL_SRC_SCHED_ASYNC_SIGNAL_C
#define GUARD_KERNEL_SRC_SCHED_ASYNC_SIGNAL_C 1
#define _KOS_SOURCE 1
#include <hybrid/compiler.h>
#include <hybrid/atomic.h>
#include <kos/types.h>
#include <sched/task.h>
#include <sched/async_signal.h>
#include <kernel/debug.h>
#include <dev/wall.h>
#include <assert.h>
#include <except.h>
DECL_BEGIN
#if 1
/* [0..1][lock(THIS_TASK)] Chain of asynchronous connections active in the thread. */
PRIVATE ATTR_PERTASK struct async_task_connection *async_connections = NULL;
/* Connect to an async-safe signal.
* WARNING: This function is _NOT_ async-safe. Only `async_sig_broadcast()' is!
* @throw: E_WOULDBLOCK: Preemption has been disabled and a lock couldn't be acquired immediately. */
PUBLIC void KCALL
task_connect_async(struct async_task_connection *__restrict connection,
struct async_sig *__restrict signal) {
connection->atc_delivered = ASYNC_SIG_STATUS_WAITING;
connection->atc_thread = THIS_TASK;
connection->atc_signal = signal;
COMPILER_WRITE_BARRIER();
if (ATOMIC_CMPXCH(signal->as_ptr,NULL,connection)) {
/* Primary connection (finish initialization as such). */
connection->atc_thrnext = PERTASK_XCH(async_connections,connection);
COMPILER_WRITE_BARRIER();
} else {
/* Secondary connection (connect to the regular signal). */
task_connect(&signal->as_sig);
}
}
PRIVATE struct async_sig *KCALL
task_disconnect_async1(struct async_task_connection *__restrict connection) {
struct async_sig *result = NULL;
struct async_sig *signal = connection->atc_signal;
if (ATOMIC_CMPXCH(signal->as_ptr,connection,NULL)) {
/* Disconnected prematurely. */
} else {
/* Wait until the signal got delivered. */
while (ATOMIC_READ(connection->atc_delivered) == ASYNC_SIG_STATUS_WAITING)
task_yield();
/* The signal was sent. */
result = signal;
}
/* Always wake all the other threads.
* If the signal got send, they must be notified as well.
* If it wasn't, then this is just another sporadic wakeup. */
sig_broadcast(&signal->as_sig);
return result;
}
/* Disconnect all currently connected async-safe signals.
* @throw: E_WOULDBLOCK: Preemption has been disabled and a lock couldn't be acquired immediately.
* @return: * : Randomly, one of the signals that were delivered.
* @return: NULL: No signals were sent. */
PUBLIC struct sig *KCALL task_disconnect_async(void) {
struct async_sig *temp,*result = NULL;
struct async_task_connection *chain;
chain = PERTASK_XCH(async_connections,NULL);
for (; chain; chain = chain->atc_thrnext) {
temp = task_disconnect_async1(chain);
if (!result) result = temp;
}
temp = (struct async_sig *)task_disconnect();
if (!result) result = temp;
return (struct sig *)result;
}
INTDEF ATTR_PERTASK struct task_connections my_connections;
/* Wait for async-signals to be boardcast and disconnect all remaining connections.
* @throw: * : This error was thrown by an RPC function call.
* @throw: E_INTERRUPT: The calling thread was interrupted.
* @throw: E_WOULDBLOCK: Preemption has been disabled and a lock couldn't be acquired immediately.
* @return: * : Randomly, one of the signals that were delivered.
* @return: NULL: The given timeout has expired. */
PUBLIC struct sig *KCALL
task_waitfor_async(jtime_t abs_timeout) {
struct task_connections *mycon;
struct async_task_connection *chain;
struct sig *EXCEPT_VAR COMPILER_IGNORE_UNINITIALIZED(result);
struct sig *EXCEPT_VAR new_result;
bool sleep_ok;
mycon = &PERTASK(my_connections);
TRY {
/* We require that the caller have preemption enable. */
if (!PREEMPTION_ENABLED())
error_throw(E_WOULDBLOCK);
for (;;) {
/* Disable preemption to ensure that no task
* for the current CPU could send the signal.
* Additionally, no other CPU will be able to
* interrupt us while we check for signals, meaning
* that any task_wake IPIs will only be received once
* `task_sleep()' gets around to re-enable interrupts. */
PREEMPTION_DISABLE();
COMPILER_READ_BARRIER();
/* Check for synchronous signals. */
result = mycon->tcs_sig;
if (result) { PREEMPTION_ENABLE(); break; }
/* Check for asynchronous signals. */
chain = PERTASK_GET(async_connections);
for (; chain; chain = chain->atc_thrnext) {
if (ATOMIC_READ(chain->atc_delivered) != ASYNC_SIG_STATUS_WAITING) {
result = (struct sig *)chain->atc_signal;
PREEMPTION_ENABLE();
goto got_signal;
}
}
/* Serve RPC functions. */
if (task_serve()) continue;
/* Sleep for a bit, or until we're interrupted. */
sleep_ok = task_sleep(abs_timeout);
COMPILER_READ_BARRIER();
result = mycon->tcs_sig;
/* A signal was received in the mean time. */
if (result) break;
if (!sleep_ok) break; /* Timeout */
/* Continue spinning */
}
got_signal:;
} FINALLY {
/* Always disconnect all connected signals (synchronous + asynchronous). */
new_result = (struct sig *)task_disconnect_async();
if (!result) result = new_result;
}
return result;
}
PUBLIC ATTR_RETNONNULL struct sig *KCALL task_wait_async(void) {
return task_waitfor_async(JTIME_INFINITE);
}
/* Wait for async-signals to be boardcast and disconnect all remaining connections.
* @throw: * : This error was thrown by an RPC function call.
* @throw: E_INTERRUPT: The calling thread was interrupted.
* @throw: E_WOULDBLOCK: Preemption has been disabled and a lock couldn't be acquired immediately.
* @return: * : Randomly, one of the signals that were delivered.
* @return: NULL: The given timeout has expired. */
PUBLIC struct sig *KCALL
task_waitfor_async_noserve(jtime_t abs_timeout) {
struct task_connections *mycon;
struct async_task_connection *chain;
struct sig *EXCEPT_VAR COMPILER_IGNORE_UNINITIALIZED(result);
struct sig *EXCEPT_VAR new_result;
bool sleep_ok;
mycon = &PERTASK(my_connections);
TRY {
/* We require that the caller have preemption enable. */
if (!PREEMPTION_ENABLED())
error_throw(E_WOULDBLOCK);
for (;;) {
/* Disable preemption to ensure that no task
* for the current CPU could send the signal.
* Additionally, no other CPU will be able to
* interrupt us while we check for signals, meaning
* that any task_wake IPIs will only be received once
* `task_sleep()' gets around to re-enable interrupts. */
PREEMPTION_DISABLE();
COMPILER_READ_BARRIER();
/* Check for synchronous signals. */
result = mycon->tcs_sig;
if (result) { PREEMPTION_ENABLE(); break; }
/* Check for asynchronous signals. */
chain = PERTASK_GET(async_connections);
for (; chain; chain = chain->atc_thrnext) {
if (ATOMIC_READ(chain->atc_delivered) != ASYNC_SIG_STATUS_WAITING) {
result = (struct sig *)chain->atc_signal;
PREEMPTION_ENABLE();
goto got_signal;
}
}
/* Sleep for a bit, or until we're interrupted. */
sleep_ok = task_sleep(abs_timeout);
COMPILER_READ_BARRIER();
result = mycon->tcs_sig;
/* A signal was received in the mean time. */
if (result) break;
if (!sleep_ok) break; /* Timeout */
/* Continue spinning */
}
got_signal:;
} FINALLY {
/* Always disconnect all connected signals (synchronous + asynchronous). */
new_result = (struct sig *)task_disconnect_async();
if (!result) result = new_result;
}
return result;
}
PUBLIC ATTR_RETNONNULL struct sig *KCALL task_wait_async_noserve(void) {
return task_waitfor_async_noserve(JTIME_INFINITE);
}
/* Wake a task waiting for the given async-signal.
* NOTE: This function is ASYNC-SAFE, meaning it can safely be used from interrupt handlers.
* Also note that the requirement of an async-safe signal-broadcast function
* was the only reason why async-safe signals had to be implemented.
* Most notably is their use by keyboard input buffers,
* which are then filled by interrupt handlers.
* @return: true: A task was waiting for the signal. - That task may wake other waiters.
* @return: false: No task was waiting for the signal. */
PUBLIC ASYNCSAFE bool KCALL
async_sig_broadcast(struct async_sig *__restrict signal) {
struct async_task_connection *primary;
primary = ATOMIC_XCH(signal->as_ptr,NULL);
if (!primary) return false;
task_wake(primary->atc_thread);
ATOMIC_WRITE(primary->atc_delivered,ASYNC_SIG_STATUS_DELIVERED);
return true;
}
#else
/* [0..1][lock(THIS_TASK)] Chain of asynchronous connections active in the thread. */
PRIVATE ATTR_PERTASK struct async_task_connection *async_connections = NULL;
DEFINE_PERTASK_CLEANUP(task_cleanup_async_connections);
INTERN void KCALL task_cleanup_async_connections(void) {
/* Because we serve RPC calls before waiting for async signals,
* we must make sure to disconnect all of them if such an RPC
* call terminates the thread. */
task_disconnect_async();
}
/* Connect to an async-safe signal.
* WARNING: This function is _NOT_ async-safe. Only `async_sig_broadcast()' is! */
PUBLIC void KCALL
task_connect_async(struct async_task_connection *__restrict connection,
struct async_sig *__restrict signal) {
/* Initialize the connection state. */
connection->atc_thread = THIS_TASK;
connection->atc_sig = signal;
connection->atc_delivered = ASYNC_SIG_STATUS_WAITING;
connection->atc_thrnext = PERTASK(async_connections);
PERTASK(async_connections) = connection;
read_signal_pointer:
connection->atc_secondary.cs_next = signal->as_ptr;
COMPILER_READ_BARRIER();
if (connection->atc_secondary.cs_next) {
struct async_task_connection *next;
/* Special state: The signal is currently being delivered. */
if (connection->atc_secondary.cs_next == (struct async_task_connection *)-1) {
task_yield();
goto read_signal_pointer;
}
/* Other connections already exist.
* Use the secondary-connections route and add ourself to that chain.
* NOTE: By acquiring this lock, we ensure that the currently connect
* task is in a consistent state. */
atomic_rwlock_write(&signal->as_lock);
COMPILER_READ_BARRIER();
connection->atc_secondary.cs_next = signal->as_ptr;
/* Deal with the race condition of the previously connected task having disconnected. */
if unlikely(!connection->atc_secondary.cs_next) {
atomic_rwlock_endwrite(&signal->as_lock);
goto set_primary_connection;
}
/* Walk the chain of secondary connections. */
next = connection->atc_secondary.cs_next;
while (next->atc_secondary.cs_next)
next = next->atc_secondary.cs_next;
/* Append the new connection at the end. */
connection->atc_secondary.cs_next = NULL;
connection->atc_secondary.cs_pself = &next->atc_secondary.cs_next;
next->atc_secondary.cs_next = connection;
/* Release the signal, allowing the connection to be broadcast. */
atomic_rwlock_endwrite(&signal->as_lock);
} else {
set_primary_connection:
connection->atc_secondary.cs_pself = NULL;
/* Atomically connect to the signal. */
if (!ATOMIC_CMPXCH(signal->as_ptr,NULL,connection))
goto read_signal_pointer;
}
}
/* Wake a task waiting for the given async-signal.
* @return: true: A task was waiting for the signal. - That task may wake other waiters.
* @return: false: No task was waiting for the signal. */
PUBLIC ASYNCSAFE bool KCALL
async_sig_broadcast(struct async_sig *__restrict signal) {
struct async_task_connection *target;
struct task *target_task;
debug_printf("BROADCAST... ");
target = ATOMIC_XCH(signal->as_ptr,(struct async_task_connection *)-1);
if (!target)
goto no_target; /* No waiters. */
if (target == (struct async_task_connection *)-1)
goto no_target; /* No waiters. */
/* NOTE: The race condition between extracting the target and waking
* it is solved by `task_disconnect1_async()' checking if it
* is matching the signal's primary connection, and waiting
* for `target->atc_thread' to become `NULL', as we do below. */
/* Wake the task.
* NOTE: This may fail, but even if it does, we can still be sure
* that the thread will receive the signal before it just
* hasn't started sleeping, yet. */
target_task = target->atc_thread;
/* Indicate to the thread that it is being signaled. */
ATOMIC_WRITE(target->atc_delivered,ASYNC_SIG_STATUS_DELIVERING);
/* With the target's state set, we can ~unlock~ (in a sense) the signal. */
ATOMIC_WRITE(signal->as_ptr,NULL);
/* NOTE: Having set `ASYNC_SIG_STATUS_DELIVERING' guaranties that the
* thread will wait for async signal delivery to complete. */
task_wake(target_task);
ATOMIC_WRITE(target->atc_delivered,ASYNC_SIG_STATUS_DELIVERED);
debug_printf("Woken\n");
return true;
no_target:
debug_printf("No target\n");
ATOMIC_WRITE(signal->as_ptr,NULL);
return false;
}
/* Disconnect the given async-task connection. */
PRIVATE struct async_sig *KCALL
task_disconnect1_async(struct async_task_connection *__restrict connection) {
struct async_task_connection *next;
struct async_task_connection *oldcon;
struct async_sig *sig;
struct task *next_thread;
uintptr_t state;
sig = connection->atc_sig;
again:
atomic_rwlock_write(&sig->as_lock);
next = connection->atc_secondary.cs_next;
state = ATOMIC_READ(connection->atc_delivered);
if (state != ASYNC_SIG_STATUS_WAITING) {
/* Connection has already been delivered / is being delivered. */
if (state == ASYNC_SIG_STATUS_DELIVERING)
goto unlock_yield_and_try_again; /* Wait for delivery to complete if it's happening right now. */
} else if ((oldcon = ATOMIC_CMPXCH_VAL(sig->as_ptr,connection,next)) == connection) {
/* Deleted the primary connection before it could be sent. */
debug_printf("next = %p\n",next);
atomic_rwlock_endwrite(&sig->as_lock);
return NULL;
} else if (oldcon == (struct async_task_connection *)-1) {
/* Special case: The signal is currently being delivered. */
unlock_yield_and_try_again:
atomic_rwlock_endwrite(&sig->as_lock);
task_yield();
goto again;
#if 1 /* Optimization when the signal was delivered with no new waiters having appeared since. */
} else if (!oldcon) {
/* No existing connections. --> The signal had to be sent at some point. */
#endif
} else {
/* We know we're not the primary connection.
* If our signal got sent at some point, but some other thread was
* notified, we'll be getting notified by it once the time comes. */
atomic_rwlock_endwrite(&sig->as_lock);
return NULL;
}
if (!next) {
/* No secondary connections (remaining) */
atomic_rwlock_endwrite(&sig->as_lock);
return sig;
}
/* Wake the next thread in the chain of waiters. */
next_thread = next->atc_thread;
task_incref(next_thread);
if (next->atc_delivered == ASYNC_SIG_STATUS_WAITING) {
/* Indicate to all waiting tasks that the signal was delivered. */
for (; next; next = next->atc_secondary.cs_next)
ATOMIC_WRITE(next->atc_delivered,ASYNC_SIG_STATUS_DELIVERED);
}
atomic_rwlock_endwrite(&sig->as_lock);
assertef(task_wake(next_thread),"Thread with active async-signals has terminated");
task_decref(next_thread);
return sig;
}
/* Disconnect all currently connected async-safe signals.
* @return: * : Randomly, one of the signals that were delivered.
* @return: NULL: No signals were sent. */
PUBLIC struct async_sig *KCALL
task_disconnect_async(void) {
struct async_sig *temp,*result = NULL;
struct async_task_connection *con;
con = XCH(PERTASK(async_connections),NULL);
for (; con; con = con->atc_thrnext) {
temp = task_disconnect1_async(con);
if (!result) result = temp;
}
return result;
}
/* Wait for async-signals to be boardcast.
* @return: * : The signal that was delivered.
* @return: NULL: The given timeout has expired. */
PUBLIC struct async_sig *KCALL
task_waitfor_async(jtime_t abs_timeout) {
struct async_sig *EXCEPT_VAR result;
struct async_task_connection *chain;
chain = PERTASK(async_connections);
TRY {
/* We require that the caller have preemption enable. */
if (!PREEMPTION_ENABLED())
error_throw(E_WOULDBLOCK);
check_delivery:
/* Disable preemption, so we can safely check
* if any async-signal has already been delivered. */
PREEMPTION_DISABLE();
COMPILER_BARRIER();
for (; chain; chain = chain->atc_thrnext) {
if (ATOMIC_READ(chain->atc_delivered) != ASYNC_SIG_STATUS_WAITING) {
result = chain->atc_sig;
PREEMPTION_ENABLE();
task_disconnect_async();
return result;
}
}
/* Serve RPC function calls before starting to wait. */
if (task_serve())
goto check_delivery;
/* Wait for signals to be delivered */
if (task_sleep(abs_timeout))
goto check_delivery;
assert(abs_timeout != JTIME_INFINITE);
} FINALLY {
/* Disconnect all signals. */
result = task_disconnect_async();
}
return result;
}
PUBLIC ATTR_RETNONNULL struct async_sig *
KCALL task_wait_async(void) {
return task_waitfor_async(JTIME_INFINITE);
}
/* Wait for any kind of signal and disconnect all before returning.
* @return: * : A pointer to a `struct async_sig' or `struct sig' that was sent.
* @return: NULL: The given `abs_timeout' has expired. */
PUBLIC ATTR_RETNONNULL void *KCALL task_uwait(void) {
return task_uwaitfor(JTIME_INFINITE);
}
INTDEF ATTR_PERTASK struct task_connections my_connections;
PUBLIC void *KCALL task_uwaitfor(jtime_t abs_timeout) {
struct task_connections *mycon;
struct async_task_connection *chain;
void *EXCEPT_VAR result;
void *EXCEPT_VAR new_result;
bool sleep_ok;
mycon = &PERTASK(my_connections);
TRY {
/* We require that the caller have preemption enable. */
if (!PREEMPTION_ENABLED())
error_throw(E_WOULDBLOCK);
for (;;) {
/* Disable preemption to ensure that no task
* for the current CPU could send the signal.
* Additionally, no other CPU will be able to
* interrupt us while we check for signals, meaning
* that any task_wake IPIs will only be received once
* `task_sleep()' gets around to re-enable interrupts. */
PREEMPTION_DISABLE();
COMPILER_READ_BARRIER();
/* Check for synchronous signals. */
result = mycon->tcs_sig;
if (result) { PREEMPTION_ENABLE(); break; }
/* Check for asynchronous signals. */
chain = PERTASK(async_connections);
for (; chain; chain = chain->atc_thrnext) {
if (ATOMIC_READ(chain->atc_delivered) != ASYNC_SIG_STATUS_WAITING) {
result = chain->atc_sig;
PREEMPTION_ENABLE();
goto got_signal;
}
}
/* Serve RPC functions. */
if (task_serve()) continue;
/* Sleep for a bit, or until we're interrupted. */
sleep_ok = task_sleep(abs_timeout);
COMPILER_READ_BARRIER();
result = mycon->tcs_sig;
/* A signal was received in the mean time. */
if (result) break;
if (!sleep_ok) break; /* Timeout */
/* Continue spinning */
}
got_signal:;
} FINALLY {
/* Always disconnect all connected signals (synchronous + asynchronous). */
new_result = task_disconnect_async();
if (!result) result = new_result;
new_result = task_disconnect();
if (!result) result = new_result;
}
return result;
}
/* Disconnect any kind of signal.
* @return: * : A pointer to a `struct async_sig' or `struct sig' that was sent.
* @return: NULL: No signals were sent, or have been connected. */
PUBLIC void *KCALL task_udisconnect(void) {
void *result,*new_result;
/* Disconnect asynchronous signals, as well as regular signals. */
result = task_disconnect_async();
new_result = task_disconnect();
if (!result) result = new_result;
return result;
}
PUBLIC void *KCALL
task_waitfor_tmrel(USER CHECKED struct timespec const *rel_timeout) {
return task_uwaitfor(jiffies + jiffies_from_timespec(*rel_timeout));
}
PUBLIC void *KCALL
task_uwaitfor_tmabs(USER CHECKED struct timespec const *abs_timeout) {
struct timespec diff = *abs_timeout;
struct timespec wall = wall_gettime(&wall_kernel);
if (TIMESPEC_LOWER(diff,wall))
return task_udisconnect();
TIMESPEC_SUB(diff,wall);
return task_uwaitfor(jiffies + jiffies_from_timespec(diff));
}
#endif
DECL_END
#endif /* !GUARD_KERNEL_SRC_SCHED_ASYNC_SIGNAL_C */
| 37.07799 | 103 | 0.711321 |
c49f185b32f0e779e29d7d9560e39ebd80c629bd | 8,419 | asm | Assembly | Transynther/x86/_processed/NONE/_xt_sm_/i9-9900K_12_0xa0.log_21829_1244.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/NONE/_xt_sm_/i9-9900K_12_0xa0.log_21829_1244.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/NONE/_xt_sm_/i9-9900K_12_0xa0.log_21829_1244.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r13
push %r14
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0x18f64, %rbx
clflush (%rbx)
nop
nop
add %rdi, %rdi
movw $0x6162, (%rbx)
nop
and $40942, %r10
lea addresses_A_ht+0x46ec, %r13
xor %r14, %r14
movl $0x61626364, (%r13)
nop
nop
nop
nop
nop
cmp %rdi, %rdi
lea addresses_D_ht+0x1bfe4, %rsi
lea addresses_UC_ht+0xd5e4, %rdi
nop
nop
nop
add %r10, %r10
mov $69, %rcx
rep movsq
nop
sub $36471, %r14
lea addresses_D_ht+0x18fe4, %rdi
nop
sub $50357, %r10
movups (%rdi), %xmm6
vpextrq $1, %xmm6, %rsi
nop
nop
nop
nop
inc %r11
lea addresses_D_ht+0x451f, %rsi
lea addresses_WT_ht+0x13534, %rdi
nop
add %r11, %r11
mov $73, %rcx
rep movsb
nop
nop
nop
nop
nop
cmp %rbx, %rbx
lea addresses_WC_ht+0x174e4, %rdi
nop
nop
nop
cmp %rsi, %rsi
mov (%rdi), %rbx
nop
nop
nop
xor %rsi, %rsi
lea addresses_WT_ht+0x4458, %rdi
clflush (%rdi)
nop
nop
nop
cmp %r11, %r11
movb (%rdi), %al
nop
nop
nop
nop
nop
sub $34, %r13
lea addresses_WC_ht+0xc0c4, %r14
nop
xor $27056, %rdi
mov $0x6162636465666768, %r11
movq %r11, (%r14)
nop
nop
nop
cmp $6826, %rax
lea addresses_UC_ht+0xf164, %rax
and $35833, %r13
movups (%rax), %xmm4
vpextrq $0, %xmm4, %rsi
cmp $5739, %rdi
lea addresses_normal_ht+0x16ae2, %rbx
nop
nop
nop
nop
sub $45485, %r11
and $0xffffffffffffffc0, %rbx
movaps (%rbx), %xmm4
vpextrq $1, %xmm4, %r13
nop
nop
and %rax, %rax
lea addresses_WT_ht+0x185e4, %r10
nop
nop
add %rdi, %rdi
movl $0x61626364, (%r10)
nop
nop
nop
nop
nop
and $49768, %r11
lea addresses_A_ht+0x1bca4, %r14
nop
sub %rdi, %rdi
movb (%r14), %r11b
nop
nop
nop
nop
xor $22593, %rax
lea addresses_A_ht+0xf744, %r14
clflush (%r14)
nop
sub %rdi, %rdi
movb $0x61, (%r14)
nop
xor %r14, %r14
lea addresses_D_ht+0x8b64, %rdi
nop
nop
nop
nop
nop
and %r13, %r13
movups (%rdi), %xmm7
vpextrq $0, %xmm7, %r14
nop
cmp $23562, %r10
lea addresses_UC_ht+0x8564, %r11
nop
nop
dec %rcx
movups (%r11), %xmm7
vpextrq $1, %xmm7, %rdi
nop
nop
nop
xor $37922, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r14
pop %r13
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r8
push %r9
push %rax
push %rbx
push %rdx
push %rsi
// Store
lea addresses_WT+0x17684, %rsi
nop
nop
nop
nop
xor $62608, %rax
movb $0x51, (%rsi)
add %rsi, %rsi
// Store
lea addresses_WT+0x13fe4, %rdx
nop
nop
nop
nop
nop
cmp $17693, %r10
movw $0x5152, (%rdx)
nop
nop
nop
nop
and %r8, %r8
// Store
lea addresses_US+0x54c4, %rax
clflush (%rax)
nop
nop
nop
nop
nop
and %r9, %r9
mov $0x5152535455565758, %rbx
movq %rbx, %xmm2
vmovntdq %ymm2, (%rax)
nop
cmp %r9, %r9
// Faulty Load
lea addresses_WT+0x13fe4, %rbx
nop
cmp $9011, %r10
mov (%rbx), %r8d
lea oracles, %rax
and $0xff, %r8
shlq $12, %r8
mov (%rax,%r8,1), %r8
pop %rsi
pop %rdx
pop %rbx
pop %rax
pop %r9
pop %r8
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_WT', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WT', 'AVXalign': False, 'size': 1}}
{'OP': 'STOR', 'dst': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_WT', 'AVXalign': False, 'size': 2}}
{'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 4, 'type': 'addresses_US', 'AVXalign': False, 'size': 32}}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_WT', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 3, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 3, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 4}}
{'src': {'same': False, 'congruent': 11, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 0, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_WT_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8}}
{'src': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_normal_ht', 'AVXalign': True, 'size': 16}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4}}
{'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 5, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1}}
{'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'52': 21829}
52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52
*/
| 31.769811 | 2,999 | 0.65079 |
a1d7794770d02708c7806d4c7c5dd450a8d674cb | 10,106 | h | C | test/tests/libcxx/support/test_iterators.h | asidorov95/momo | ebede4ba210ac1fa614bb2571a526e7591a92b56 | [
"MIT"
] | 9 | 2016-07-05T08:46:52.000Z | 2019-04-22T21:16:36.000Z | test/tests/libcxx/support/test_iterators.h | asidorov95/momo | ebede4ba210ac1fa614bb2571a526e7591a92b56 | [
"MIT"
] | 3 | 2019-01-07T15:54:30.000Z | 2019-12-09T06:44:02.000Z | test/tests/libcxx/support/test_iterators.h | asidorov95/momo | ebede4ba210ac1fa614bb2571a526e7591a92b56 | [
"MIT"
] | 2 | 2018-10-28T09:14:16.000Z | 2019-12-12T12:10:08.000Z | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef ITERATORS_H
#define ITERATORS_H
#include <iterator>
#include <cassert>
#ifndef _LIBCPP_HAS_NO_DELETED_FUNCTIONS
#define DELETE_FUNCTION = delete
#else
#define DELETE_FUNCTION
#endif
template <class It>
class output_iterator
{
It it_;
template <class U> friend class output_iterator;
public:
typedef std::output_iterator_tag iterator_category;
typedef void value_type;
typedef typename std::iterator_traits<It>::difference_type difference_type;
typedef It pointer;
typedef typename std::iterator_traits<It>::reference reference;
It base() const {return it_;}
output_iterator () {}
explicit output_iterator(It it) : it_(it) {}
template <class U>
output_iterator(const output_iterator<U>& u) :it_(u.it_) {}
reference operator*() const {return *it_;}
output_iterator& operator++() {++it_; return *this;}
output_iterator operator++(int)
{output_iterator tmp(*this); ++(*this); return tmp;}
//template <class T>
//void operator,(T const &) DELETE_FUNCTION;
};
template <class It>
class input_iterator
{
It it_;
template <class U> friend class input_iterator;
public:
typedef std::input_iterator_tag iterator_category;
typedef typename std::iterator_traits<It>::value_type value_type;
typedef typename std::iterator_traits<It>::difference_type difference_type;
typedef It pointer;
typedef typename std::iterator_traits<It>::reference reference;
It base() const {return it_;}
input_iterator() : it_() {}
explicit input_iterator(It it) : it_(it) {}
template <class U>
input_iterator(const input_iterator<U>& u) :it_(u.it_) {}
reference operator*() const {return *it_;}
pointer operator->() const {return it_;}
input_iterator& operator++() {++it_; return *this;}
input_iterator operator++(int)
{input_iterator tmp(*this); ++(*this); return tmp;}
friend bool operator==(const input_iterator& x, const input_iterator& y)
{return x.it_ == y.it_;}
friend bool operator!=(const input_iterator& x, const input_iterator& y)
{return !(x == y);}
//template <class T>
//void operator,(T const &) DELETE_FUNCTION;
};
template <class T, class U>
inline
bool
operator==(const input_iterator<T>& x, const input_iterator<U>& y)
{
return x.base() == y.base();
}
template <class T, class U>
inline
bool
operator!=(const input_iterator<T>& x, const input_iterator<U>& y)
{
return !(x == y);
}
template <class It>
class forward_iterator
{
It it_;
template <class U> friend class forward_iterator;
public:
typedef std::forward_iterator_tag iterator_category;
typedef typename std::iterator_traits<It>::value_type value_type;
typedef typename std::iterator_traits<It>::difference_type difference_type;
typedef It pointer;
typedef typename std::iterator_traits<It>::reference reference;
It base() const {return it_;}
forward_iterator() : it_() {}
explicit forward_iterator(It it) : it_(it) {}
template <class U>
forward_iterator(const forward_iterator<U>& u) :it_(u.it_) {}
reference operator*() const {return *it_;}
pointer operator->() const {return it_;}
forward_iterator& operator++() {++it_; return *this;}
forward_iterator operator++(int)
{forward_iterator tmp(*this); ++(*this); return tmp;}
friend bool operator==(const forward_iterator& x, const forward_iterator& y)
{return x.it_ == y.it_;}
friend bool operator!=(const forward_iterator& x, const forward_iterator& y)
{return !(x == y);}
//template <class T>
//void operator,(T const &) DELETE_FUNCTION;
};
template <class T, class U>
inline
bool
operator==(const forward_iterator<T>& x, const forward_iterator<U>& y)
{
return x.base() == y.base();
}
template <class T, class U>
inline
bool
operator!=(const forward_iterator<T>& x, const forward_iterator<U>& y)
{
return !(x == y);
}
template <class It>
class bidirectional_iterator
{
It it_;
template <class U> friend class bidirectional_iterator;
public:
typedef std::bidirectional_iterator_tag iterator_category;
typedef typename std::iterator_traits<It>::value_type value_type;
typedef typename std::iterator_traits<It>::difference_type difference_type;
typedef It pointer;
typedef typename std::iterator_traits<It>::reference reference;
It base() const {return it_;}
bidirectional_iterator() : it_() {}
explicit bidirectional_iterator(It it) : it_(it) {}
template <class U>
bidirectional_iterator(const bidirectional_iterator<U>& u) :it_(u.it_) {}
reference operator*() const {return *it_;}
pointer operator->() const {return it_;}
bidirectional_iterator& operator++() {++it_; return *this;}
bidirectional_iterator operator++(int)
{bidirectional_iterator tmp(*this); ++(*this); return tmp;}
bidirectional_iterator& operator--() {--it_; return *this;}
bidirectional_iterator operator--(int)
{bidirectional_iterator tmp(*this); --(*this); return tmp;}
//template <class T>
//void operator,(T const &) DELETE_FUNCTION;
};
template <class T, class U>
inline
bool
operator==(const bidirectional_iterator<T>& x, const bidirectional_iterator<U>& y)
{
return x.base() == y.base();
}
template <class T, class U>
inline
bool
operator!=(const bidirectional_iterator<T>& x, const bidirectional_iterator<U>& y)
{
return !(x == y);
}
template <class It>
class random_access_iterator
{
It it_;
template <class U> friend class random_access_iterator;
public:
typedef std::random_access_iterator_tag iterator_category;
typedef typename std::iterator_traits<It>::value_type value_type;
typedef typename std::iterator_traits<It>::difference_type difference_type;
typedef It pointer;
typedef typename std::iterator_traits<It>::reference reference;
It base() const {return it_;}
random_access_iterator() : it_() {}
explicit random_access_iterator(It it) : it_(it) {}
template <class U>
random_access_iterator(const random_access_iterator<U>& u) :it_(u.it_) {}
reference operator*() const {return *it_;}
pointer operator->() const {return it_;}
random_access_iterator& operator++() {++it_; return *this;}
random_access_iterator operator++(int)
{random_access_iterator tmp(*this); ++(*this); return tmp;}
random_access_iterator& operator--() {--it_; return *this;}
random_access_iterator operator--(int)
{random_access_iterator tmp(*this); --(*this); return tmp;}
random_access_iterator& operator+=(difference_type n) {it_ += n; return *this;}
random_access_iterator operator+(difference_type n) const
{random_access_iterator tmp(*this); tmp += n; return tmp;}
friend random_access_iterator operator+(difference_type n, random_access_iterator x)
{x += n; return x;}
random_access_iterator& operator-=(difference_type n) {return *this += -n;}
random_access_iterator operator-(difference_type n) const
{random_access_iterator tmp(*this); tmp -= n; return tmp;}
reference operator[](difference_type n) const {return it_[n];}
//template <class T>
//void operator,(T const &) DELETE_FUNCTION;
};
template <class T, class U>
inline
bool
operator==(const random_access_iterator<T>& x, const random_access_iterator<U>& y)
{
return x.base() == y.base();
}
template <class T, class U>
inline
bool
operator!=(const random_access_iterator<T>& x, const random_access_iterator<U>& y)
{
return !(x == y);
}
template <class T, class U>
inline
bool
operator<(const random_access_iterator<T>& x, const random_access_iterator<U>& y)
{
return x.base() < y.base();
}
template <class T, class U>
inline
bool
operator<=(const random_access_iterator<T>& x, const random_access_iterator<U>& y)
{
return !(y < x);
}
template <class T, class U>
inline
bool
operator>(const random_access_iterator<T>& x, const random_access_iterator<U>& y)
{
return y < x;
}
template <class T, class U>
inline
bool
operator>=(const random_access_iterator<T>& x, const random_access_iterator<U>& y)
{
return !(x < y);
}
template <class T, class U>
inline
typename std::iterator_traits<T>::difference_type
operator-(const random_access_iterator<T>& x, const random_access_iterator<U>& y)
{
return x.base() - y.base();
}
template <class Iter>
inline Iter base(output_iterator<Iter> i) { return i.base(); }
template <class Iter>
inline Iter base(input_iterator<Iter> i) { return i.base(); }
template <class Iter>
inline Iter base(forward_iterator<Iter> i) { return i.base(); }
template <class Iter>
inline Iter base(bidirectional_iterator<Iter> i) { return i.base(); }
template <class Iter>
inline Iter base(random_access_iterator<Iter> i) { return i.base(); }
template <class Iter> // everything else
inline Iter base(Iter i) { return i; }
#undef DELETE_FUNCTION
#endif // ITERATORS_H
| 30.624242 | 89 | 0.631308 |
bccc20bf659f4a9016d0c7539171e7392506ac39 | 3,787 | js | JavaScript | public/settings/Settings.js | thrandale/Connect-4 | 1466e9b5ddc4237c88fc4ef253ccd6d61a44b168 | [
"MIT"
] | 1 | 2022-01-11T00:58:48.000Z | 2022-01-11T00:58:48.000Z | public/settings/Settings.js | thrandale/Connect-4 | 1466e9b5ddc4237c88fc4ef253ccd6d61a44b168 | [
"MIT"
] | 11 | 2022-02-10T03:59:47.000Z | 2022-03-31T18:56:25.000Z | public/settings/Settings.js | thrandale/Connect-4 | 1466e9b5ddc4237c88fc4ef253ccd6d61a44b168 | [
"MIT"
] | null | null | null | class Settings {
constructor(xIn, yIn, widthIn, heightIn) {
this.x = xIn;
this.y = yIn;
this.width = widthIn;
this.height = heightIn;
this.t1 = new Toggle(this.x + this.width / 2, this.y + this.height / 13, this.width / 8 * 3, this.height / (13 / 2), "Human", "AI", "Blue", 1);
this.t2 = new Toggle(this.x + this.width / 2, this.y + this.height / 13 * 4, this.width / 8 * 3, this.height / (13 / 2), "Human", "AI", "Red", 0);
this.startToggle = new Toggle(this.x + this.width / 2, this.y + this.height / 13 * 7, this.width / 8 * 3, this.height / (13 / 2), "Blue", "Red", "Start", 1);
this.resetW = this.width / 8 * 3;
this.resetH = this.height / (13 / 2);
this.resetX = this.x + this.width / 2 - this.width / 8 * 3 / 2;
this.resetY = this.y + this.height / 13 * 10;
this.reviewW = this.width / 2;
this.reviewH = this.height / 5;
this.reviewX = width - this.reviewW - width / 20;
this.reviewY = height - this.reviewH - height / 20;
}
draw() {
// draw reveal button
if (currentScene == "win") {
background(COLOR_BACKGROUND);
textAlign(CENTER, CENTER);
noStroke();
fill(COLOR_HIGHLIGHT);
textSize(width / 10);
text(winner == "tie" ? "It's a tie!" : (winner == "red" ? "Red" : "Blue") + " player wins!", width / 2, height / 8);
fill(COLOR_HIGHLIGHT);
stroke(COLOR_GRAY);
strokeWeight(5);
rect(this.reviewX, this.reviewY, this.reviewW, this.reviewH, 10, 10);
fill(COLOR_BACKGROUND);
textSize(this.reviewH / 2.83);
noStroke();
text("Hold to review\nlast game", this.reviewX + this.reviewW / 2, this.reviewY + this.reviewH / 2);
}
fill(COLOR_BACKGROUND);
strokeWeight(5);
stroke(COLOR_HIGHLIGHT);
if (currentScene == "win") {
noStroke();
}
rect(this.x, this.y, this.width, this.height, 10, 10);
this.t1.draw();
this.t2.draw();
this.startToggle.draw();
// draw reset button
// stroke(0);
fill(COLOR_HIGHLIGHT);
stroke(COLOR_GRAY);
strokeWeight(5);
rect(this.resetX, this.resetY, this.resetW, this.resetH, 10, 10);
noStroke();
fill(COLOR_BACKGROUND);
textAlign(CENTER, CENTER);
textSize(this.resetH / 2.1);
text("New Game", this.resetX + this.resetW / 2, this.resetY + this.resetH / 2);
}
onClick() {
if (this.t1.contains(mouseX, mouseY)) {
this.t1.swap();
} else if (this.t2.contains(mouseX, mouseY)) {
this.t2.swap();
} else if (this.startToggle.contains(mouseX, mouseY)) {
this.startToggle.swap();
} else if (mouseX > this.resetX && mouseX < this.resetX + this.resetW && mouseY > this.resetY && mouseY < this.resetY + this.resetH) {
board.reset();
if (currentScene == "win") {
this.setPos(width / 2, topBarHeight, width / 2, height / 2);
}
currentScene = "play";
}
}
contains(x, y) {
return (x > this.x && x < this.x + this.width && y > this.y && y < this.y + this.height);
}
setPos(x, y) {
this.x = x;
this.y = y;
this.t1.setPos(this.x + this.width / 2, this.y + this.height / 13);
this.t2.setPos(this.x + this.width / 2, this.y + this.height / 13 * 4);
this.startToggle.setPos(this.x + this.width / 2, this.y + this.height / 13 * 7);
this.resetX = this.x + this.width / 2 - this.width / 8 * 3 / 2;
this.resetY = this.y + this.height / 13 * 10;
}
}
| 36.76699 | 165 | 0.524954 |
6e1d430cf429c3f39760fd86dcd63fa8d93763db | 163,173 | htm | HTML | htm_data/91207.htm | ArnabBir/InterHall_DA_Competition_2017 | 62c34f1105a0c6a370c8e1c68ce36ae2886a6515 | [
"Apache-2.0"
] | null | null | null | htm_data/91207.htm | ArnabBir/InterHall_DA_Competition_2017 | 62c34f1105a0c6a370c8e1c68ce36ae2886a6515 | [
"Apache-2.0"
] | null | null | null | htm_data/91207.htm | ArnabBir/InterHall_DA_Competition_2017 | 62c34f1105a0c6a370c8e1c68ce36ae2886a6515 | [
"Apache-2.0"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ZIP Code 91207 Map, Housing Stats, More for Glendale, CA</title>
<meta name="description" content="Interactive and printable 91207 ZIP code maps, population demographics, Glendale CA real estate costs, rental prices, and home values.">
<link rel="stylesheet" href="/automin/d8c0ee6cb173812108ee72a43aea775d4ab7eac5.automin.cache_extend.1483653703.css" type="text/css">
<!-- Responsive Ad code here since it isn't supported in external stylesheets -->
<style type="text/css">
.banner-ad-unit {
height:250px;
width: 300px;
}
.banner-ad-container {
text-align: center;
margin: 15px 0;
}
/* sm */
@media(min-width:768px){
.banner-ad-unit {
height:60px;
width:468px;
}
}
/* md */
@media(min-width:992px){
}
/* lg */
@media(min-width:1200px){
.banner-ad-unit {
height:90px;
width:728px;
}
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyA11LGixNdjBOJIKIgJM51_8JL11Ow7NXw&sensor=false&libraries=places"></script>
<style>
.D3ChartOuterContainer {
max-width: 1200px;
}
.D3ChartContainer {
position: relative;
width: 100%;
margin: 0 auto;
padding-bottom: 70%;
height: 0;
}
@media(min-width:768px){
.D3ChartContainer {
padding-bottom: 40%;
}
}
.D3SizingContainer {
position: absolute;
left: 0;
width: 100%;
height: 100%;
}
.D3ChartContainer SVG {
width: 100%;
height: 100%;
}
</style>
<link href="//cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.css" rel="stylesheet" crossorigin="anonymous"/>
<style>
.NVD3ChartIcon {
font-family: FontAwesome;
font-size: 18px;
fill: #CCCCCC;
visibility: hidden;
}
.NVD3ChartIcon:HOVER {
fill: #000000;
cursor: pointer;
}
@media(min-width:768px){
.NVD3ChartIcon {
visibility: visible;
}
}
.NVD3ChartFooter {
font-size: 11px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
}
.NVD3ChartFooter A {
text-decoration: underline;
}
</style><script>
geojson = {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"fillOpacity":0,"strokeColor":"#FF0000","strokeOpacity":0.5},"geometry":{"type":"Polygon","coordinates":[[[-118.257613,34.17585],[-118.257707,34.175974],[-118.25777,34.176034],[-118.257909,34.176133],[-118.257765,34.17644],[-118.25776,34.176626],[-118.257779,34.176678],[-118.257844,34.176853],[-118.257966,34.176981],[-118.258013,34.177009],[-118.258251,34.177151],[-118.258532,34.177269],[-118.258558,34.17728],[-118.258865,34.177348],[-118.259275,34.177327],[-118.259635,34.177353],[-118.259942,34.177446],[-118.260396,34.177557],[-118.26088,34.177613],[-118.261356,34.17765],[-118.261659,34.177711],[-118.261787,34.177774],[-118.261951,34.177971],[-118.261543,34.178151],[-118.261256,34.178285],[-118.261116,34.178442],[-118.260958,34.178644],[-118.26088,34.178719],[-118.260809,34.178736],[-118.26057,34.178801],[-118.26051,34.178851],[-118.260485,34.178908],[-118.260482,34.178942],[-118.260498,34.17895],[-118.260523,34.178963],[-118.260564,34.17896],[-118.260703,34.178928],[-118.260905,34.178931],[-118.261008,34.178927],[-118.261077,34.178912],[-118.261208,34.178828],[-118.261513,34.178672],[-118.261678,34.178589],[-118.261775,34.178585],[-118.261918,34.178584],[-118.262072,34.178579],[-118.262229,34.178571],[-118.262368,34.178548],[-118.262457,34.178545],[-118.262452,34.178484],[-118.262482,34.178452],[-118.262542,34.178392],[-118.262744,34.178358],[-118.263089,34.178288],[-118.263286,34.178213],[-118.263418,34.178123],[-118.263536,34.178069],[-118.263611,34.178035],[-118.263889,34.177998],[-118.264061,34.178015],[-118.264217,34.178035],[-118.264316,34.178028],[-118.264445,34.177967],[-118.264669,34.177891],[-118.264977,34.17786],[-118.265304,34.177837],[-118.265517,34.177807],[-118.265669,34.177751],[-118.265755,34.177643],[-118.265784,34.177541],[-118.265797,34.177436],[-118.26585,34.177385],[-118.265937,34.177324],[-118.265985,34.17721],[-118.26601,34.177133],[-118.266176,34.177046],[-118.266233,34.177004],[-118.266236,34.176935],[-118.266261,34.176846],[-118.266298,34.176773],[-118.266387,34.176724],[-118.266503,34.176683],[-118.266623,34.176589],[-118.266755,34.176492],[-118.26679,34.176539],[-118.266791,34.176622],[-118.266728,34.176702],[-118.266618,34.176772],[-118.26655,34.176821],[-118.266544,34.17689],[-118.266538,34.177027],[-118.266536,34.177166],[-118.266466,34.177287],[-118.266348,34.17757],[-118.266321,34.1777],[-118.266298,34.177815],[-118.266296,34.177884],[-118.266304,34.177919],[-118.26635,34.177925],[-118.266403,34.177924],[-118.266456,34.177902],[-118.266512,34.177803],[-118.266767,34.177517],[-118.267027,34.177202],[-118.267202,34.177052],[-118.267324,34.177132],[-118.267375,34.177157],[-118.267437,34.177156],[-118.267575,34.177123],[-118.267806,34.177027],[-118.268075,34.176941],[-118.268335,34.176945],[-118.268463,34.176992],[-118.268518,34.177039],[-118.268542,34.177097],[-118.268544,34.177238],[-118.268498,34.177512],[-118.268428,34.177741],[-118.268402,34.17786],[-118.268404,34.177995],[-118.268351,34.178021],[-118.269309,34.178306],[-118.269809,34.178306],[-118.269896,34.178697],[-118.270009,34.179206],[-118.268609,34.180706],[-118.269009,34.182105],[-118.269109,34.183905],[-118.271409,34.182305],[-118.271609,34.181105],[-118.273456,34.180213],[-118.27387,34.179814],[-118.275097,34.179718],[-118.27511,34.18022],[-118.276845,34.180315],[-118.276954,34.180209],[-118.277053,34.180326],[-118.277136,34.180404],[-118.277708,34.180819],[-118.278223,34.181193],[-118.278595,34.181467],[-118.278682,34.181534],[-118.278972,34.181744],[-118.277828,34.183703],[-118.277594,34.18429],[-118.276509,34.187008],[-118.279146,34.18935],[-118.279192,34.189391],[-118.279286,34.189474],[-118.27951,34.189673],[-118.27996,34.190456],[-118.279961,34.190554],[-118.279965,34.190791],[-118.279978,34.191702],[-118.280066,34.197773],[-118.280135,34.202153],[-118.280209,34.207004],[-118.280209,34.207104],[-118.28021,34.207161],[-118.282719,34.210469],[-118.28333,34.211273],[-118.285575,34.21423],[-118.286993,34.216096],[-118.288282,34.217792],[-118.28701,34.217604],[-118.28322,34.215185],[-118.282309,34.214604],[-118.279609,34.213304],[-118.278032,34.212299],[-118.272709,34.208904],[-118.271548,34.20801],[-118.26972,34.206602],[-118.267074,34.204564],[-118.266558,34.204168],[-118.266382,34.204032],[-118.266205,34.203897],[-118.265686,34.203499],[-118.260434,34.199469],[-118.259176,34.198503],[-118.258932,34.198061],[-118.258743,34.197719],[-118.25825,34.196825],[-118.257544,34.195545],[-118.25745,34.195374],[-118.25741,34.195302],[-118.255754,34.192301],[-118.254528,34.191503],[-118.250835,34.189099],[-118.249396,34.186453],[-118.249027,34.185774],[-118.248774,34.185308],[-118.246992,34.182032],[-118.246201,34.180576],[-118.246101,34.180397],[-118.245249,34.18005],[-118.24343,34.17931],[-118.241775,34.178636],[-118.241421,34.178492],[-118.240827,34.17825],[-118.240799,34.178239],[-118.240483,34.17811],[-118.239722,34.177416],[-118.239578,34.177339],[-118.239152,34.17722],[-118.2388,34.177129],[-118.238635,34.177036],[-118.238525,34.176906],[-118.238463,34.176743],[-118.238404,34.176427],[-118.238356,34.17621],[-118.238315,34.1761],[-118.23822,34.17599],[-118.23808,34.175867],[-118.23793,34.175734],[-118.237775,34.175641],[-118.237606,34.175585],[-118.237374,34.175551],[-118.237176,34.175549],[-118.237038,34.175571],[-118.236896,34.175617],[-118.236753,34.175693],[-118.236732,34.175712],[-118.236544,34.175883],[-118.236119,34.176321],[-118.236003,34.176409],[-118.235887,34.176461],[-118.235718,34.176506],[-118.235592,34.17651],[-118.235366,34.176458],[-118.23516,34.17636],[-118.234932,34.176203],[-118.234796,34.176136],[-118.234635,34.176101],[-118.234401,34.176104],[-118.234123,34.176139],[-118.233949,34.176141],[-118.233801,34.176103],[-118.233687,34.176039],[-118.233612,34.175924],[-118.23358,34.175841],[-118.233565,34.175697],[-118.233552,34.175383],[-118.233541,34.175239],[-118.233487,34.175091],[-118.23322,34.174739],[-118.232893,34.174289],[-118.232748,34.174171],[-118.232613,34.1741],[-118.232443,34.17408],[-118.232282,34.174068],[-118.232157,34.174098],[-118.232026,34.17417],[-118.231958,34.174208],[-118.231661,34.174384],[-118.231611,34.174399],[-118.231536,34.174422],[-118.231306,34.174435],[-118.230806,34.1744],[-118.230584,34.174391],[-118.230319,34.17438],[-118.229811,34.174374],[-118.229783,34.173856],[-118.229779,34.173395],[-118.229778,34.173286],[-118.229743,34.17271],[-118.229719,34.172512],[-118.229663,34.172351],[-118.229552,34.172177],[-118.229463,34.17206],[-118.229329,34.171947],[-118.229216,34.171846],[-118.229026,34.171841],[-118.229063,34.171555],[-118.229195,34.170682],[-118.229186,34.170335],[-118.22914,34.17003],[-118.229117,34.169897],[-118.229254,34.169661],[-118.229433,34.169393],[-118.22959,34.169157],[-118.230096,34.168398],[-118.230391,34.168107],[-118.230511,34.167988],[-118.230592,34.167908],[-118.232628,34.166215],[-118.232962,34.165794],[-118.233064,34.165664],[-118.234077,34.164367],[-118.235347,34.162992],[-118.236001,34.162243],[-118.238124,34.160941],[-118.238575,34.160734],[-118.239931,34.160262],[-118.240889,34.159923],[-118.242949,34.159193],[-118.24395,34.158846],[-118.244853,34.158486],[-118.245481,34.158183],[-118.245916,34.157963],[-118.246336,34.157823],[-118.246811,34.157739],[-118.246983,34.157709],[-118.247077,34.157698],[-118.247485,34.15765],[-118.248248,34.157642],[-118.248945,34.157622],[-118.249933,34.157601],[-118.250265,34.157622],[-118.250571,34.157642],[-118.250901,34.157667],[-118.25187,34.157844],[-118.252683,34.158066],[-118.25382,34.158376],[-118.253885,34.158394],[-118.254345,34.15852],[-118.254987,34.158664],[-118.255068,34.158682],[-118.255148,34.158701],[-118.255147,34.158783],[-118.255144,34.158994],[-118.25514,34.159204],[-118.255135,34.159394],[-118.255129,34.159829],[-118.254992,34.159829],[-118.254999,34.160251],[-118.255018,34.161435],[-118.255026,34.161931],[-118.255023,34.162453],[-118.255019,34.163671],[-118.254895,34.16367],[-118.253835,34.163666],[-118.253858,34.16521],[-118.254904,34.165213],[-118.255029,34.165214],[-118.255161,34.165214],[-118.255153,34.166741],[-118.25505,34.166741],[-118.253872,34.166751],[-118.253875,34.16759],[-118.253907,34.167665],[-118.25397,34.167708],[-118.254068,34.167733],[-118.254146,34.167748],[-118.254193,34.167789],[-118.254226,34.168079],[-118.255067,34.168088],[-118.255165,34.168091],[-118.255219,34.168097],[-118.255516,34.168117],[-118.255927,34.168212],[-118.255781,34.168451],[-118.255573,34.168781],[-118.255579,34.168875],[-118.255289,34.169092],[-118.254979,34.169452],[-118.25491,34.169534],[-118.254773,34.169696],[-118.254433,34.169946],[-118.254068,34.170132],[-118.25389,34.17038],[-118.253766,34.170691],[-118.253716,34.17083],[-118.253751,34.172214],[-118.256002,34.172234],[-118.25782,34.173923],[-118.257824,34.175656],[-118.257613,34.17585]]]}}]};
bounds = new google.maps.LatLngBounds(new google.maps.LatLng(34.157601,-118.288282), new google.maps.LatLng(34.217792,-118.229026));
</script></head>
<body>
<div class="container">
<div class="container_bg">
<div id="header" class="row">
<div class="col-xs-12 col-sm-4 logo-container">
<a href="/"><img src="/images/logo.cache_extend.1483653703.png" class="img-responsive"></a>
</div>
<div class="col-xs-12 col-sm-5 social-media-row">
<ul style="list-style: none; padding: 0; font-size: 12px; font-weight: normal; ">
<li style="display: inline-block; padding: 0; margin: 3px; font-weight: bold" class="hidden-xs">Share:</li>
<li style="background-color: #306199; display: inline-block; margin: 3px; text-align: center; padding: 3px; border-radius: 4px; width: 24px;">
<a href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fwww.unitedstateszipcodes.org&t=U.S.+ZIP+Codes%3A+Free+ZIP+code+map+and+zip+code+lookup" target="_blank" title="Share on Facebook" style="color: #FFFFFF; text-decoration: none"><i class="fa fa-facebook"></i></a>
</li>
<li style="background-color: #26c4f1; display: inline-block; margin: 3px; text-align: center; padding: 3px; border-radius: 4px; width: 24px;">
<a href="https://twitter.com/intent/tweet?url=http%3A%2F%2Fwww.unitedstateszipcodes.org&text=U.S.+ZIP+Codes%3A+Free+ZIP+code+map+and+zip+code+lookup&via=" target="_blank" title="Tweet" style="color: #FFFFFF; text-decoration: none"><i class="fa fa-twitter"></i></a>
</li>
<li style="background-color: #007bb6; display: inline-block; margin: 3px; text-align: center; padding: 3px; border-radius: 4px; width: 24px;">
<a href="https://www.linkedin.com/shareArticle?mini=true&url=http%3A%2F%2Fwww.unitedstateszipcodes.org&title=U.S.+ZIP+Codes%3A+Free+ZIP+code+map+and+zip+code+lookup&summary=Find+the+ZIP+for+an+address%2C+see+ZIP+maps%2C+compare+shipping+options%2C+demographics%2C+and+spreadsheet+download.&source=http%3A%2F%2Fwww.unitedstateszipcodes.org" target="_blank" title="Share on LinkedIn" style="color: #FFFFFF; text-decoration: none"><i class="fa fa-linkedin"></i></a>
</li>
<li style="background-color: #444444; display: inline-block; margin: 3px; text-align: center; padding: 3px; border-radius: 4px; width: 24px;">
<a href="mailto:?subject=U.S.%20ZIP%20Codes%3A%20Free%20ZIP%20code%20map%20and%20zip%20code%20lookup&body=Find%20the%20ZIP%20for%20an%20address%2C%20see%20ZIP%20maps%2C%20compare%20shipping%20options%2C%20demographics%2C%20and%20spreadsheet%20download.%0A%0Ahttp%3A%2F%2Fwww.unitedstateszipcodes.org" target="_blank" title="Email" style="color: #FFFFFF; text-decoration: none"><i class="fa fa-envelope"></i></a>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="col-sm-8 col-sm-push-4">
<div id="blue-bar">
<a href="/">Home</a>
<a href="/printable-zip-code-maps/">Printable Maps</a>
<a href="/shipping-calculator/">Shipping Calculator</a>
<a href="/zip-code-database/">ZIP Code Database</a>
</div>
</div>
</div>
<div class="navbar navbar-inverse" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/printable-zip-code-maps/">Printable Maps</a></li>
<li><a href="/shipping-calculator/">Shipping Calculator</a></li>
<li><a href="/zip-code-database/">ZIP Code Database</a></li>
</ul>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<form role="form" id="q_form" action="/" method="post">
<div class="row" id="search-forms">
<div class="col-xs-12 col-lg-5">
<h2>Search by ZIP, address, city, or county:</h2>
</div>
<div class="col-xs-12 col-lg-7">
<div class="input-group has-error twitter-typeahead-append-input-group">
<input type="text" name="q" id="q" class="form-control" placeholder="Enter a location" value="91207">
<span class="input-group-btn">
<button type="submit" class="btn btn-danger"><i class="fa fa-search" aria-hidden="true"></i> <span class="hidden-xs">Search</span></button>
</span>
</div>
</div>
</div>
</form>
<div class="row" id="mainrow">
<div class="col-xs-12 col-md-7 col-lg-8">
<div id="map_canvas"></div> <div class="banner-ad-container">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Responsive ad unit -->
<ins class="adsbygoogle banner-ad-unit"
style="display:inline-block;"
data-ad-client="ca-pub-0709341197255740"
data-ad-slot="9012842496"
data-ad-format="horizontal"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<script>
map_control_html = '<i class="fa fa-print" aria-hidden="true"></i> Print Map';
map_control_onclick = function () {
updateBounds();
$('#printModal').modal('show');
return false;
}
</script>
<script>
function updateBounds() {
var b = map.getBounds();
$('#ne').val(b.getNorthEast().toString());
$('#sw').val(b.getSouthWest().toString());
}
</script>
<!-- Modal -->
<div class="modal fade" id="printModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form role="form" action="/print_this_map.php" method="post" target="_blank">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Print Map</h4>
</div>
<div class="modal-body">
<p>Please make sure you have panned and zoomed to the area that you
would like to have printed using the map on the page. After it shows
the area that you are interested in, select from the options below
to print your map.</p>
<div class="row">
<div class="col-xs-12">
<input type="hidden" name="ne" id="ne">
<input type="hidden" name="sw" id="sw">
<div class="row">
<div class="col-xs-12 col-sm-4">
<label for="print_state" class="">State</label>
</div>
<div class="col-xs-12 col-sm-8">
<select class="form-control" name="state" id="print_state">
<option value="AL" >Alabama</option>
<option value="AK" >Alaska</option>
<option value="AZ" >Arizona</option>
<option value="AR" >Arkansas</option>
<option value="CA" selected>California</option>
<option value="CO" >Colorado</option>
<option value="CT" >Connecticut</option>
<option value="DE" >Delaware</option>
<option value="FL" >Florida</option>
<option value="GA" >Georgia</option>
<option value="HI" >Hawaii</option>
<option value="ID" >Idaho</option>
<option value="IL" >Illinois</option>
<option value="IN" >Indiana</option>
<option value="IA" >Iowa</option>
<option value="KS" >Kansas</option>
<option value="KY" >Kentucky</option>
<option value="LA" >Louisiana</option>
<option value="ME" >Maine</option>
<option value="MD" >Maryland</option>
<option value="MA" >Massachusetts</option>
<option value="MI" >Michigan</option>
<option value="MN" >Minnesota</option>
<option value="MS" >Mississippi</option>
<option value="MO" >Missouri</option>
<option value="MT" >Montana</option>
<option value="NE" >Nebraska</option>
<option value="NV" >Nevada</option>
<option value="NH" >New Hampshire</option>
<option value="NJ" >New Jersey</option>
<option value="NM" >New Mexico</option>
<option value="NY" >New York</option>
<option value="NC" >North Carolina</option>
<option value="ND" >North Dakota</option>
<option value="OH" >Ohio</option>
<option value="OK" >Oklahoma</option>
<option value="OR" >Oregon</option>
<option value="PA" >Pennsylvania</option>
<option value="PR" >Puerto Rico</option>
<option value="RI" >Rhode Island</option>
<option value="SC" >South Carolina</option>
<option value="SD" >South Dakota</option>
<option value="TN" >Tennessee</option>
<option value="TX" >Texas</option>
<option value="UT" >Utah</option>
<option value="VT" >Vermont</option>
<option value="VA" >Virginia</option>
<option value="WA" >Washington</option>
<option value="DC" >Washington, DC</option>
<option value="WV" >West Virginia</option>
<option value="WI" >Wisconsin</option>
<option value="WY" >Wyoming</option>
</select>
</div>
</div>
<h3>Page Orientation</h3>
<div class="radio">
<label>
<input type="radio" name="orientation" value="portrait" checked>
<span>Portrait</span>
<div class="thumb"><img src="/images/portrait.cache_extend.1483653703.png"></div>
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="orientation" value="landscape">
<span>Landscape</span>
<div class="thumb"><img src="/images/landscape.cache_extend.1483653703.png"></div>
</label>
</div>
<div class="radio disabled">
<label>
<input type="radio" name="orientation" value="current view only">
<span>Current View Only</span>
<div class="thumb"><img src="/images/current-view-only.cache_extend.1483653703.png"></div>
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Print</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-md-5 col-lg-4" id="map-info">
<h1 style='text-align: center; margin-top: 10px'>ZIP Code 91207</h1><div style='text-align: center; padding: 4px 0; margin-bottom: 5px; background-color: #a2aebb; border-radius: 4px'><a href="#stats" class="btn btn-default"><i class="fa fa-users" aria-hidden="true"></i> Population</a><a href="#real-estate" class="btn btn-default"><i class="fa fa-home" aria-hidden="true"></i> Real Estate</a><span class='visible-md visible-lg'></span><a href="#employment" class="btn btn-default"><i class="fa fa-usd" aria-hidden="true"></i> Employment</a><a href="#schools" class="btn btn-default"><i class="fa fa-graduation-cap" aria-hidden="true"></i> Schools</a></div> <table class="table table-condensed table-striped" style="margin-bottom: 5px">
<tbody>
<tr><th>Primary City:</th><td>Glendale, CA (<a href="#cities">View All Cities</a>)</td></tr><tr><th>Neighborhood: </th><td>Royal Canyon|Hillside</td></tr><tr><th>County: </th><td>Los Angeles County</td></tr><tr><th>Timezone: </th><td>Pacific (1:04pm)</td></tr><tr><th>Area code: </th><td>818 (<a href="http://www.allareacodes.com/818" target=_blank>Area Code Map</a>)</td></tr><tr><th>Coordinates:</th><td>34.17, -118.24<br>ZIP (~1 mile radius)</td></tr></td></tr>
</tbody>
</table>
<div style="margin-right: -3px">
<div class="banner-ad-container">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 300x250, general purpose for url channels created 1/20/11 -->
<ins class="adsbygoogle"
style="display:inline-block;width:300px;height:250px"
data-ad-client="ca-pub-0709341197255740"
data-ad-slot="2396333505"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</div>
</div>
</div>
<a name=cities></a><h2>Cities in ZIP code 91207</h2><p>The cities below are at least partially located in ZIP code 91207. In addition to the primary city for a ZIP code,
USPS also publishes a list of other acceptable cities that can be used with ZIP code 91207. However, if you are mailing something
to ZIP code 91207, you should not use any of the cities listed as unacceptable. Choose from the primary or acceptable cities when mailing
your package or letter.</p> <dl class="dl-horizontal">
<dt>Primary city:</dt>
<dd>Glendale, CA</dd>
</dl>
<a name=stats></a><h2>Stats and Demographics for the 91207 ZIP Code</h2><p>ZIP code 91207 is located in south <a href="/ca/">California</a> and covers a slightly less than average land area compared to other ZIP codes in the United States. It also has a slightly higher than average population density. </p><p>The people living in ZIP code 91207 are primarily white. The number of middle aged adults is extremely large while the number of seniors is large. There are also a slightly higher than average number of families and a slightly less than average number of single parents. The percentage of children under 18 living in the 91207 ZIP code is small compared to other areas of the country. </p>
<div class="row">
<div class="col-xs-12 col-sm-6">
<table class="table table-hover">
<tbody>
<tr>
<th>Population</th>
<td class="text-right">10,506</td>
<td style="width: 106px;"></td>
</tr>
<tr>
<th>Population Density</th>
<td class="text-right">2,312</td>
<td style="text-align: right; white-space: nowrap;"><small>people per sq mi</small></td>
</tr>
<tr>
<th>Housing Units</th>
<td class="text-right">4,283</td>
<td></td>
</tr>
<tr>
<th>Median Home Value</th>
<td class="text-right">$782,700</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-12 col-sm-6">
<table class="table table-hover">
<tbody>
<tr>
<th>Land Area</th>
<td class="text-right">4.54</td>
<td style="width: 106px;"><small>sq mi</small></td>
</tr>
<tr>
<th>Water Area</th>
<td class="text-right">0.03</td>
<td><small>sq mi</small></td>
</tr>
<tr>
<th>Occupied Housing Units</th>
<td class="text-right">4,097</td>
<td></td>
</tr>
<tr>
<th>Median Household Income</th>
<td class="text-right">$91,005</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-12">
<div class="banner-ad-container">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Responsive ad unit -->
<ins class="adsbygoogle banner-ad-unit"
style="display:inline-block;"
data-ad-client="ca-pub-0709341197255740"
data-ad-slot="9012842496"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<h3>Estimated Population over Time</h3>
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="LineChart0" class="LineChart"></svg></div></div></div> </div>
<div class="well well-sm chart-section">
<h3>Total Population by Age</h3>
<center><table cellspacing=0 class=slightly_padded style="font-weight: bold; margin: 0 auto" align=center><tr><td>Median Age: </td><td align=right>46</td><td width=50></td><td>Male Median Age: </td><td align=right>45</td><td width=50></td><td>Female Median Age: </td><td align=right>46</td><td width=50></td></tr></table></center><br><div style="text-align:center;"><div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="LineChart1" class="LineChart"></svg></div></div></div></div> <div class="too-wide">
<table cellspacing=0 class=lined style="font-size: 11px; width: 100%"><tr class=header_row><td></td><td align=right>Under 5</td><td align=right>5-9</td><td align=right>10-14</td><td align=right>15-19</td><td align=right>20-24</td><td align=right>25-29</td><td align=right>30-34</td><td align=right>35-39</td><td align=right>40-44</td><td align=right>45-49</td><td align=right>50-54</td><td align=right>55-59</td><td align=right>60-64</td><td align=right>65-69</td><td align=right>70-74</td><td align=right>75-79</td><td align=right>80-84</td><td align=right>85 Plus</td></tr><tr><td>Male</td><td align=right>276</td><td align=right>267</td><td align=right>246</td><td align=right>225</td><td align=right>240</td><td align=right>280</td><td align=right>274</td><td align=right>282</td><td align=right>352</td><td align=right>448</td><td align=right>410</td><td align=right>372</td><td align=right>357</td><td align=right>259</td><td align=right>207</td><td align=right>197</td><td align=right>121</td><td align=right>111</td></tr><tr><td>Female</td><td align=right>278</td><td align=right>269</td><td align=right>240</td><td align=right>230</td><td align=right>264</td><td align=right>328</td><td align=right>334</td><td align=right>349</td><td align=right>420</td><td align=right>443</td><td align=right>435</td><td align=right>428</td><td align=right>400</td><td align=right>313</td><td align=right>264</td><td align=right>211</td><td align=right>177</td><td align=right>199</td></tr><tr><td>Total</td><td align=right>554</td><td align=right>536</td><td align=right>486</td><td align=right>455</td><td align=right>504</td><td align=right>608</td><td align=right>608</td><td align=right>631</td><td align=right>772</td><td align=right>891</td><td align=right>845</td><td align=right>800</td><td align=right>757</td><td align=right>572</td><td align=right>471</td><td align=right>408</td><td align=right>298</td><td align=right>310</td></tr></table> </div>
</div>
<div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Gender</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart0" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">Male</span></th>
<td class="text-right"><span class="value">4,924</span></td>
<td class="text-right">47%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Female</span></th>
<td class="text-right"><span class="value">5,582</span></td>
<td class="text-right">53%</td>
</tr>
</tbody>
<caption>Gender</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Race</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart1" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">White</span></th>
<td class="text-right"><span class="value">8,465</span></td>
<td class="text-right">80.6%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Black Or African American</span></th>
<td class="text-right"><span class="value">82</span></td>
<td class="text-right">0.8%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">American Indian Or Alaskan Native</span></th>
<td class="text-right"><span class="value">21</span></td>
<td class="text-right">0.2%</td>
</tr>
<tr>
<th data-color="#ffbb78"><span class="legend-color" style="background-color: #ffbb78;"></span> <span class="legend-label">Asian</span></th>
<td class="text-right"><span class="value">1,233</span></td>
<td class="text-right">11.7%</td>
</tr>
<tr>
<th data-color="#2ca02c"><span class="legend-color" style="background-color: #2ca02c;"></span> <span class="legend-label">Native Hawaiian & Other Pacific Islander</span></th>
<td class="text-right"><span class="value">2</span></td>
<td class="text-right">0.0%</td>
</tr>
<tr>
<th data-color="#98df8a"><span class="legend-color" style="background-color: #98df8a;"></span> <span class="legend-label">Other Race</span></th>
<td class="text-right"><span class="value">289</span></td>
<td class="text-right">2.8%</td>
</tr>
<tr>
<th data-color="#d62728"><span class="legend-color" style="background-color: #d62728;"></span> <span class="legend-label">Two Or More Races</span></th>
<td class="text-right"><span class="value">414</span></td>
<td class="text-right">3.9%</td>
</tr>
</tbody>
<caption>Race</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<h3>Head of Household by Age</h3>
<div style="text-align:center;"><div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="LineChart2" class="LineChart"></svg></div></div></div></div> <div class="too-wide">
<table cellspacing=0 class=lined style="font-size: 11px; width: 100%"><tr class=header_row><td></td><td align=right>15-24</td><td align=right>25-34</td><td align=right>35-44</td><td align=right>45-54</td><td align=right>55-64</td><td align=right>65-74</td><td align=right>75-84</td><td align=right>85 Plus</td></tr><tr><td>Owner</td><td align=right>11</td><td align=right>117</td><td align=right>371</td><td align=right>620</td><td align=right>623</td><td align=right>419</td><td align=right>322</td><td align=right>129</td></tr><tr><td>Renter</td><td align=right>34</td><td align=right>277</td><td align=right>283</td><td align=right>318</td><td align=right>214</td><td align=right>166</td><td align=right>109</td><td align=right>84</td></tr><tr><td>Total</td><td align=right>45</td><td align=right>394</td><td align=right>654</td><td align=right>938</td><td align=right>837</td><td align=right>585</td><td align=right>431</td><td align=right>213</td></tr></table> </div>
</div>
<div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Families vs Singles</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart2" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">Husband Wife Family Households</span></th>
<td class="text-right"><span class="value">2,346</span></td>
<td class="text-right">57%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Single Guardian</span></th>
<td class="text-right"><span class="value">557</span></td>
<td class="text-right">14%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">Singles</span></th>
<td class="text-right"><span class="value">978</span></td>
<td class="text-right">24%</td>
</tr>
<tr>
<th data-color="#ffbb78"><span class="legend-color" style="background-color: #ffbb78;"></span> <span class="legend-label">Singles With Roommate</span></th>
<td class="text-right"><span class="value">216</span></td>
<td class="text-right">5%</td>
</tr>
</tbody>
<caption>Families vs Singles</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Households with Kids</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart3" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<thead>
<tr>
<th colspan="3">
Average Household Size: 3 </th>
</tr>
</thead>
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">Households without Kids</span></th>
<td class="text-right"><span class="value">2,972</span></td>
<td class="text-right">73%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Households with Kids</span></th>
<td class="text-right"><span class="value">1,125</span></td>
<td class="text-right">27%</td>
</tr>
</tbody>
<caption>Households with Kids</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<h3>Children by Age</h3>
<div style="text-align:center;"><div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="LineChart3" class="LineChart"></svg></div></div></div></div> <div class="too-wide">
<table cellspacing=0 class=lined style="font-size: 11px; width: 100%"><tr class=header_row><td></td><td align=right>1</td><td align=right>2</td><td align=right>3</td><td align=right>4</td><td align=right>5</td><td align=right>6</td><td align=right>7</td><td align=right>8</td><td align=right>9</td><td align=right>10</td><td align=right>11</td><td align=right>12</td><td align=right>13</td><td align=right>14</td><td align=right>15</td><td align=right>16</td><td align=right>17</td><td align=right>18</td><td align=right>19</td><td align=right>20</td></tr><tr><td>Male</td><td align=right>49</td><td align=right>55</td><td align=right>65</td><td align=right>49</td><td align=right>56</td><td align=right>67</td><td align=right>46</td><td align=right>50</td><td align=right>48</td><td align=right>46</td><td align=right>63</td><td align=right>45</td><td align=right>44</td><td align=right>48</td><td align=right>54</td><td align=right>51</td><td align=right>38</td><td align=right>41</td><td align=right>41</td><td align=right>58</td></tr><tr><td>Female</td><td align=right>50</td><td align=right>55</td><td align=right>65</td><td align=right>57</td><td align=right>56</td><td align=right>54</td><td align=right>54</td><td align=right>53</td><td align=right>52</td><td align=right>45</td><td align=right>42</td><td align=right>41</td><td align=right>60</td><td align=right>52</td><td align=right>50</td><td align=right>41</td><td align=right>50</td><td align=right>51</td><td align=right>38</td><td align=right>52</td></tr><tr><td>Total</td><td align=right>99</td><td align=right>110</td><td align=right>130</td><td align=right>106</td><td align=right>112</td><td align=right>121</td><td align=right>100</td><td align=right>103</td><td align=right>100</td><td align=right>91</td><td align=right>105</td><td align=right>86</td><td align=right>104</td><td align=right>100</td><td align=right>104</td><td align=right>92</td><td align=right>88</td><td align=right>92</td><td align=right>79</td><td align=right>110</td></tr></table> </div>
</div>
<h2 id="real-estate">Real Estate and Housing</h2>
<p>ZIP code 91207 has a small percentage of vacancies. </p><p>The majority of household are owned or have a mortgage. Homes in ZIP code 91207 were primarily built in 1939 or earlier. Looking at 91207 real estate data, the median home value of $782,700 is extremely high compared to the rest of the country. It is also high compared to nearby ZIP codes. So you are less likely to find inexpensive homes in 91207. Rentals in 91207 are most commonly 2 bedrooms. The rent for 2 bedrooms is normally $1,000+/month including utilities. 1 bedrooms are also common and rent for $1,000+/month. Prices for rental property include ZIP code 91207 apartments, townhouses, and homes that are primary residences. </p> <div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Housing Type</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart4" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">In Occupied Housing Units</span></th>
<td class="text-right"><span class="value">10,494</span></td>
<td class="text-right">99.9%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Correctional Facility For Adults</span></th>
<td class="text-right"><span class="value">0</span></td>
<td class="text-right">0.0%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">Juvenile Facilities</span></th>
<td class="text-right"><span class="value">0</span></td>
<td class="text-right">0.0%</td>
</tr>
<tr>
<th data-color="#ffbb78"><span class="legend-color" style="background-color: #ffbb78;"></span> <span class="legend-label">Nursing Facilities</span></th>
<td class="text-right"><span class="value">0</span></td>
<td class="text-right">0.0%</td>
</tr>
<tr>
<th data-color="#2ca02c"><span class="legend-color" style="background-color: #2ca02c;"></span> <span class="legend-label">Other Institutional</span></th>
<td class="text-right"><span class="value">0</span></td>
<td class="text-right">0.0%</td>
</tr>
<tr>
<th data-color="#98df8a"><span class="legend-color" style="background-color: #98df8a;"></span> <span class="legend-label">College Student Housing</span></th>
<td class="text-right"><span class="value">0</span></td>
<td class="text-right">0.0%</td>
</tr>
<tr>
<th data-color="#d62728"><span class="legend-color" style="background-color: #d62728;"></span> <span class="legend-label">Military Quarters</span></th>
<td class="text-right"><span class="value">0</span></td>
<td class="text-right">0.0%</td>
</tr>
<tr>
<th data-color="#ff9896"><span class="legend-color" style="background-color: #ff9896;"></span> <span class="legend-label">Other Noninstitutional</span></th>
<td class="text-right"><span class="value">12</span></td>
<td class="text-right">0.1%</td>
</tr>
</tbody>
<caption>Housing Type</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<h3>Year Housing was Built</h3>
<div style="text-align:center;">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart0" class="BarChart"></svg></div></div></div> </div>
</div>
<div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Housing Occupancy</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart5" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">Owned Households With A Mortgage</span></th>
<td class="text-right"><span class="value">2,009</span></td>
<td class="text-right">47%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Owned Households Free & Clear</span></th>
<td class="text-right"><span class="value">603</span></td>
<td class="text-right">14%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">Renter Occupied Households</span></th>
<td class="text-right"><span class="value">1,485</span></td>
<td class="text-right">35%</td>
</tr>
<tr>
<th data-color="#ffbb78"><span class="legend-color" style="background-color: #ffbb78;"></span> <span class="legend-label">Households Vacant</span></th>
<td class="text-right"><span class="value">186</span></td>
<td class="text-right">4%</td>
</tr>
</tbody>
<caption>Housing Occupancy</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Vacancy Reasons</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart6" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">For Rent</span></th>
<td class="text-right"><span class="value">129</span></td>
<td class="text-right">69.4%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Rented & Unoccupied</span></th>
<td class="text-right"><span class="value">1</span></td>
<td class="text-right">0.5%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">For Sale Only</span></th>
<td class="text-right"><span class="value">19</span></td>
<td class="text-right">10.2%</td>
</tr>
<tr>
<th data-color="#ffbb78"><span class="legend-color" style="background-color: #ffbb78;"></span> <span class="legend-label">Sold & Unoccupied</span></th>
<td class="text-right"><span class="value">7</span></td>
<td class="text-right">3.8%</td>
</tr>
<tr>
<th data-color="#2ca02c"><span class="legend-color" style="background-color: #2ca02c;"></span> <span class="legend-label">For Season Recreational Or Occasional Use</span></th>
<td class="text-right"><span class="value">6</span></td>
<td class="text-right">3.2%</td>
</tr>
<tr>
<th data-color="#98df8a"><span class="legend-color" style="background-color: #98df8a;"></span> <span class="legend-label">For Migrant Workers</span></th>
<td class="text-right"><span class="value">0</span></td>
<td class="text-right">0.0%</td>
</tr>
<tr>
<th data-color="#d62728"><span class="legend-color" style="background-color: #d62728;"></span> <span class="legend-label">Vacant For Other Reasons</span></th>
<td class="text-right"><span class="value">24</span></td>
<td class="text-right">12.9%</td>
</tr>
</tbody>
<caption>Vacancy Reasons</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<h3>Owner Occupied Home Values</h3>
<div style="text-align:center;">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart1" class="BarChart"></svg></div></div></div> </div>
</div>
<div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Rental Properties by Number of Rooms</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart7" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">Studio Apartment</span></th>
<td class="text-right"><span class="value">0</span></td>
<td class="text-right">0%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">1 Bedroom</span></th>
<td class="text-right"><span class="value">641</span></td>
<td class="text-right">44%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">2 Bedroom</span></th>
<td class="text-right"><span class="value">652</span></td>
<td class="text-right">44%</td>
</tr>
<tr>
<th data-color="#ffbb78"><span class="legend-color" style="background-color: #ffbb78;"></span> <span class="legend-label">3+ Bedroom</span></th>
<td class="text-right"><span class="value">173</span></td>
<td class="text-right">12%</td>
</tr>
</tbody>
<caption>Rental Properties by Number of Rooms</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<h3>Cost of Monthly Rent Including Utilities</h3>
<div class="row">
<div class="col-xs-12 col-md-6" style="text-align:center;">
<h4>Cost of a Studio Apartment</h4><div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart2" class="BarChart"></svg></div></div></div> </div>
<div class="col-xs-12 col-md-6" style="text-align:center;">
<h4>Cost of a 1 Bedroom</h4><div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart3" class="BarChart"></svg></div></div></div> </div>
<div class="col-xs-12 col-md-6" style="text-align:center;">
<h4>Cost of a 2 Bedroom</h4><div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart4" class="BarChart"></svg></div></div></div> </div>
<div class="col-xs-12 col-md-6" style="text-align:center;">
<h4>Cost of a 3+ Bedroom</h4><div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart5" class="BarChart"></svg></div></div></div> </div>
</div>
</div>
<h2 id="employment">Employment, Income, Earnings, and Work</h2>
<p>The median household income of $91,005 is compared to the rest of the country. It is also compared to nearby ZIP codes. So 91207 is likely to be one of the nicer parts of town with a more affluent demographic. </p><p>As with most parts of the country, vehicles are the most common form of transportation to places of employment. In most parts of the country, the majority of commuters get to work in under half an hour. A slightly higher than average number of commuters in 91207 can expect to fall in that range. There are a slightly smaller percentage of employees that have to travel over 45 minutes to reach their place of employment. </p> <div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Employment Status</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart8" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">Worked Full-time with Earnings</span></th>
<td class="text-right"><span class="value">3,494</span></td>
<td class="text-right">39%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Worked Part-time with Earnings</span></th>
<td class="text-right"><span class="value">2,347</span></td>
<td class="text-right">27%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">No Earnings</span></th>
<td class="text-right"><span class="value">3,006</span></td>
<td class="text-right">34%</td>
</tr>
</tbody>
<caption>Employment Status</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<h3>Average Household Income over Time</h3>
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="LineChart4" class="LineChart"></svg></div></div></div> </div>
<div class="well well-sm chart-section">
<h3>Household Income</h3>
<div style="text-align:center;">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart6" class="BarChart"></svg></div></div></div> </div>
</div>
<div class="well well-sm chart-section">
<h3>Annual Individual Earnings</h3>
<div style="text-align:center;">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart7" class="BarChart"></svg></div></div></div> </div>
</div>
<div class="well well-sm chart-section">
<h3>Sources of Household Income</h3>
<div class="row">
<div class="col-xs-12 col-md-6">
<h4>Percent of Households Receiving Income</h4>
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart8" class="BarChart"></svg></div></div></div> </div>
<div class="col-xs-12 col-md-6">
<h4>Average Income per Household by Income Source</h4>
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart9" class="BarChart"></svg></div></div></div> </div>
</div>
<p>* Only taxable income is reported.</p>
</div>
<div class="well well-sm chart-section">
<h3>Household Investment Income</h3>
<div class="row">
<div class="col-xs-12 col-md-6">
<h4>Percent of Households Receiving Investment Income</h4>
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart10" class="BarChart"></svg></div></div></div> </div>
<div class="col-xs-12 col-md-6">
<h4>Average Income per Household by Income Source</h4>
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart11" class="BarChart"></svg></div></div></div> </div>
</div>
<p>* Only taxable income is reported.</p>
</div>
<div class="well well-sm chart-section">
<h3>Household Retirement Income</h3>
<div class="row">
<div class="col-xs-12 col-md-6">
<h4>Percent of Households Receiving Retirement Income</h4>
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart12" class="BarChart"></svg></div></div></div> </div>
<div class="col-xs-12 col-md-6">
<h4>Average Income per Household by Income Source</h4>
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart13" class="BarChart"></svg></div></div></div> </div>
</div>
<p>* Only taxable income is reported.</p>
</div>
<div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Source of Earnings</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart9" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">Worked Full-time with Earnings</span></th>
<td class="text-right"><span class="value">3,494</span></td>
<td class="text-right">39%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Worked Part-time with Earnings</span></th>
<td class="text-right"><span class="value">2,347</span></td>
<td class="text-right">27%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">No Earnings</span></th>
<td class="text-right"><span class="value">3,006</span></td>
<td class="text-right">34%</td>
</tr>
</tbody>
<caption>Source of Earnings</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Means Of Transportation To Work for Workers 16 and Over</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart10" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">Car, truck, or van</span></th>
<td class="text-right"><span class="value">4,112</span></td>
<td class="text-right">81.6%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Public transportation</span></th>
<td class="text-right"><span class="value">73</span></td>
<td class="text-right">1.4%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">Taxicab</span></th>
<td class="text-right"><span class="value">0</span></td>
<td class="text-right">0.0%</td>
</tr>
<tr>
<th data-color="#ffbb78"><span class="legend-color" style="background-color: #ffbb78;"></span> <span class="legend-label">Motorcycle</span></th>
<td class="text-right"><span class="value">14</span></td>
<td class="text-right">0.3%</td>
</tr>
<tr>
<th data-color="#2ca02c"><span class="legend-color" style="background-color: #2ca02c;"></span> <span class="legend-label">Bicycle, Walked, or Other Means</span></th>
<td class="text-right"><span class="value">443</span></td>
<td class="text-right">8.8%</td>
</tr>
<tr>
<th data-color="#98df8a"><span class="legend-color" style="background-color: #98df8a;"></span> <span class="legend-label">Worked at Home</span></th>
<td class="text-right"><span class="value">400</span></td>
<td class="text-right">7.9%</td>
</tr>
</tbody>
<caption>Means Of Transportation To Work for Workers 16 and Over</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<h3>Travel Time to Work (In Minutes)</h3>
<div style="text-align:center;">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer"><div class="D3SizingContainer"><svg id="BarChart14" class="BarChart"></svg></div></div></div> </div>
</div>
<h2 id="schools">Schools and Education</h2>
The area has some of the highest percentages of people who attended college of any ZIP. <div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>Educational Attainment For The Population 25 Years And Over</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart11" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">Less than High School Diploma</span></th>
<td class="text-right"><span class="value">350</span></td>
<td class="text-right">9%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">High School Graduate</span></th>
<td class="text-right"><span class="value">1,069</span></td>
<td class="text-right">27%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">Associate's degree</span></th>
<td class="text-right"><span class="value">339</span></td>
<td class="text-right">9%</td>
</tr>
<tr>
<th data-color="#ffbb78"><span class="legend-color" style="background-color: #ffbb78;"></span> <span class="legend-label">Bachelor's degree</span></th>
<td class="text-right"><span class="value">1,074</span></td>
<td class="text-right">28%</td>
</tr>
<tr>
<th data-color="#2ca02c"><span class="legend-color" style="background-color: #2ca02c;"></span> <span class="legend-label">Master's degree</span></th>
<td class="text-right"><span class="value">479</span></td>
<td class="text-right">12%</td>
</tr>
<tr>
<th data-color="#98df8a"><span class="legend-color" style="background-color: #98df8a;"></span> <span class="legend-label">Professional school degree</span></th>
<td class="text-right"><span class="value">469</span></td>
<td class="text-right">12%</td>
</tr>
<tr>
<th data-color="#d62728"><span class="legend-color" style="background-color: #d62728;"></span> <span class="legend-label">Doctorate degree</span></th>
<td class="text-right"><span class="value">119</span></td>
<td class="text-right">3%</td>
</tr>
</tbody>
<caption>Educational Attainment For The Population 25 Years And Over</caption>
</table>
</div>
</div>
</div>
<div class="well well-sm chart-section">
<div class="row">
<div class="col-xs-12">
<h3>School Enrollment (Ages 3 to 17)</h3>
</div>
</div>
<div class="row pie-chart-section">
<div class="col-xs-12 col-sm-4 text-center">
<div class="pie-chart text-center">
<div class="D3ChartOuterContainer"><div class="D3ChartContainer" style='padding-bottom: 100%'><div class="D3SizingContainer"><svg id="PieChart12" class="PieChart"></svg></div></div></div> </div>
</div>
<div class="col-xs-12 col-sm-8">
<table class="chart-legend table table-striped table-hover table-condensed">
<tbody>
<tr>
<th data-color="#1f77b4"><span class="legend-color" style="background-color: #1f77b4;"></span> <span class="legend-label">Enrolled in Public School</span></th>
<td class="text-right"><span class="value">919</span></td>
<td class="text-right">63.0%</td>
</tr>
<tr>
<th data-color="#aec7e8"><span class="legend-color" style="background-color: #aec7e8;"></span> <span class="legend-label">Enrolled in Private School</span></th>
<td class="text-right"><span class="value">384</span></td>
<td class="text-right">26.3%</td>
</tr>
<tr>
<th data-color="#ff7f0e"><span class="legend-color" style="background-color: #ff7f0e;"></span> <span class="legend-label">Not Enrolled in School</span></th>
<td class="text-right"><span class="value">156</span></td>
<td class="text-right">10.7%</td>
</tr>
</tbody>
<caption>School Enrollment (Ages 3 to 17)</caption>
</table>
</div>
</div>
</div>
<h2>Schools in ZIP Code 91207</h2>
<p>ZIP Code 91207 is in the Glendale Unf School District. There are 1 different elementary schools and high schools with mailing addresses in ZIP code 91207. </p>
<div class="row" style="margin-bottom: 1em;">
<div class="col-xs-12 col-sm-6 col-md-4 col-md-offset-2">
<a href="http://high-schools.com/data-request.html" target="_blank" class="btn btn-primary">Download a List of High Schools</a>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<a href="http://elementaryschools.org/data-request.html" target="_blank" class="btn btn-primary">Download a List of Elementary Schools</a>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="nearby-school">
<strong><a href="//high-schools.com/directory/ca/cities/glendale/college-view/61524001930/" target="_blank">College View</a></strong><br />
1700 East Mountain St<br />
Glendale, CA 91207<br />
Grade Level: Other/Combined or Ungraded<br />
District: Glendale Unf School District </div>
</div>
</div>
<div class="nearby-zips-list">
<a name="nearby_zips"></a>
<h2>Nearby ZIP Codes</h2>
<ul class="list-unstyled nearby-zips-links clearfix">
<li>
<div>
<a href="/91011/">ZIP Code 91011</a><br />
La Canada Flintridge, CA<br />
Type: Standard<br />
</div>
</li>
<li>
<div>
<a href="/91020/">ZIP Code 91020</a><br />
Montrose, CA<br />
Type: Standard<br />
</div>
</li>
<li>
<div>
<a href="/91046/">ZIP Code 91046</a><br />
Verdugo City, CA<br />
Type: PO BOX<br />
</div>
</li>
<li>
<div>
<a href="/91201/">ZIP Code 91201</a><br />
Glendale, CA<br />
Type: Standard<br />
</div>
</li>
<li>
<div>
<a href="/91202/">ZIP Code 91202</a><br />
Glendale, CA<br />
Type: Standard<br />
</div>
</li>
<li>
<div>
<a href="/91203/">ZIP Code 91203</a><br />
Glendale, CA<br />
Type: Standard<br />
</div>
</li>
<li>
<div>
<a href="/91206/">ZIP Code 91206</a><br />
Glendale, CA<br />
Type: Standard<br />
</div>
</li>
<li>
<div>
<a href="/91208/">ZIP Code 91208</a><br />
Glendale, CA<br />
Type: Standard<br />
</div>
</li>
<li>
<div>
<a href="/91214/">ZIP Code 91214</a><br />
La Crescenta, CA<br />
Type: Standard<br />
</div>
</li>
<li>
<div>
<a href="/91501/">ZIP Code 91501</a><br />
Burbank, CA<br />
Type: Standard<br />
</div>
</li>
</ul>
</div>
<div class="state-list">
<a name="by_state"></a>
<h2>Zip Codes by State</h2>
<ul class="list-unstyled state-links">
<li><a href="/al/">Alabama</a></li>
<li><a href="/ak/">Alaska</a></li>
<li><a href="/az/">Arizona</a></li>
<li><a href="/ar/">Arkansas</a></li>
<li><a href="/ca/">California</a></li>
<li><a href="/co/">Colorado</a></li>
<li><a href="/ct/">Connecticut</a></li>
<li><a href="/de/">Delaware</a></li>
<li><a href="/fl/">Florida</a></li>
<li><a href="/ga/">Georgia</a></li>
<li><a href="/hi/">Hawaii</a></li>
<li><a href="/id/">Idaho</a></li>
<li><a href="/il/">Illinois</a></li>
<li><a href="/in/">Indiana</a></li>
<li><a href="/ia/">Iowa</a></li>
<li><a href="/ks/">Kansas</a></li>
<li><a href="/ky/">Kentucky</a></li>
<li><a href="/la/">Louisiana</a></li>
<li><a href="/me/">Maine</a></li>
<li><a href="/md/">Maryland</a></li>
<li><a href="/ma/">Massachusetts</a></li>
<li><a href="/mi/">Michigan</a></li>
<li><a href="/mn/">Minnesota</a></li>
<li><a href="/ms/">Mississippi</a></li>
<li><a href="/mo/">Missouri</a></li>
<li><a href="/mt/">Montana</a></li>
<li><a href="/ne/">Nebraska</a></li>
<li><a href="/nv/">Nevada</a></li>
<li><a href="/nh/">New Hampshire</a></li>
<li><a href="/nj/">New Jersey</a></li>
<li><a href="/nm/">New Mexico</a></li>
<li><a href="/ny/">New York</a></li>
<li><a href="/nc/">North Carolina</a></li>
<li><a href="/nd/">North Dakota</a></li>
<li><a href="/oh/">Ohio</a></li>
<li><a href="/ok/">Oklahoma</a></li>
<li><a href="/or/">Oregon</a></li>
<li><a href="/pa/">Pennsylvania</a></li>
<li><a href="/pr/">Puerto Rico</a></li>
<li><a href="/ri/">Rhode Island</a></li>
<li><a href="/sc/">South Carolina</a></li>
<li><a href="/sd/">South Dakota</a></li>
<li><a href="/tn/">Tennessee</a></li>
<li><a href="/tx/">Texas</a></li>
<li><a href="/ut/">Utah</a></li>
<li><a href="/vt/">Vermont</a></li>
<li><a href="/va/">Virginia</a></li>
<li><a href="/wa/">Washington</a></li>
<li><a href="/dc/">Washington, DC</a></li>
<li><a href="/wv/">West Virginia</a></li>
<li><a href="/wi/">Wisconsin</a></li>
<li><a href="/wy/">Wyoming</a></li>
</ul>
</div>
</div>
</div>
<div class="row footer">
<div class="col-xs-12">
<div style="border-top: 1px solid #000000; margin-bottom: 15px"></div>
<ul class="footer-nav">
<li><a href="/">Home</a></li>
<li><a href="http://www.allareacodes.com">Area Codes</a></li>
<li><a href="/policies.php">Terms of Use & Privacy Policy</a></li>
<li><a href="/contact.php">Contact</a></li>
</ul>
<p>
Data sources include the United States Postal Service, U.S. Census Bureau, Yahoo, Google, FedEx, and UPS.
</p>
<p>
© 2014 UnitedStatesZipCodes.org
</p>
</div>
</div>
</div>
</div>
<script src="/automin/c3e760580df33376710a33d338a84718ec31efd1.automin.cache_extend.1484767208.js"></script>
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<!-- Piwik -->
<script type="text/javascript">
var _paq = _paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u=(("https:" == document.location.protocol) ? "https" : "http") + "://aatrk.com/stats/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', 29]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript';
g.defer=true; g.async=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><p><img src="http://aatrk.com/stats/piwik.php?idsite=29" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
<script src="/shared-assets/d3-3.5.9.min.cache_extend.1484595097.js" charset="utf-8"></script>
<script src="/shared-assets/nv.d3-1.8.1.min.cache_extend.1484595097.js"></script>
<script>
var LineChart0_data;
var LineChart0_chart;
var LineChart0_svg;
var LineChart0_x_annotations;
var LineChart0_y_annotations;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":2005,"y":9332},{"x":2006,"y":8977},{"x":2007,"y":9362},{"x":2008,"y":9110},{"x":2009,"y":9133},{"x":2010,"y":9318},{"x":2011,"y":9371},{"x":2012,"y":9210},{"x":2013,"y":9190},{"x":2014,"y":9210}]}];
var chart = nv.models.lineChart()
.useInteractiveGuideline(true);
var svg = d3.select('#LineChart0');
var x_annotations = [];
var y_annotations = [];
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
chart.dispatch.on('renderEnd.alignAnnotations', function () {
});
LineChart0_data = data;
LineChart0_chart = chart;
LineChart0_svg = svg;
LineChart0_x_annotations = x_annotations;
LineChart0_y_annotations = y_annotations;
return chart;
}, function() {
});
</script>
<script>
var LineChart1_data;
var LineChart1_chart;
var LineChart1_svg;
var LineChart1_x_annotations;
var LineChart1_y_annotations;
nv.addGraph(function() {
var data = [{"key":"Male","values":[{"x":0,"y":276},{"x":1,"y":267},{"x":2,"y":246},{"x":3,"y":225},{"x":4,"y":240},{"x":5,"y":280},{"x":6,"y":274},{"x":7,"y":282},{"x":8,"y":352},{"x":9,"y":448},{"x":10,"y":410},{"x":11,"y":372},{"x":12,"y":357},{"x":13,"y":259},{"x":14,"y":207},{"x":15,"y":197},{"x":16,"y":121},{"x":17,"y":111}]},{"key":"Female","values":[{"x":0,"y":278},{"x":1,"y":269},{"x":2,"y":240},{"x":3,"y":230},{"x":4,"y":264},{"x":5,"y":328},{"x":6,"y":334},{"x":7,"y":349},{"x":8,"y":420},{"x":9,"y":443},{"x":10,"y":435},{"x":11,"y":428},{"x":12,"y":400},{"x":13,"y":313},{"x":14,"y":264},{"x":15,"y":211},{"x":16,"y":177},{"x":17,"y":199}]},{"key":"Total","color":"#000000","values":[{"x":0,"y":554},{"x":1,"y":536},{"x":2,"y":486},{"x":3,"y":455},{"x":4,"y":504},{"x":5,"y":608},{"x":6,"y":608},{"x":7,"y":631},{"x":8,"y":772},{"x":9,"y":891},{"x":10,"y":845},{"x":11,"y":800},{"x":12,"y":757},{"x":13,"y":572},{"x":14,"y":471},{"x":15,"y":408},{"x":16,"y":298},{"x":17,"y":310}]}];
var chart = nv.models.lineChart()
.useInteractiveGuideline(true);
var svg = d3.select('#LineChart1');
var x_annotations = [];
var y_annotations = [];
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.forceY(0);
if (data.length > 2 && parseInt(svg.style('width')) < 768/2) {
chart.showLegend(false);
}
var x_discreet_labels = ["Under 5","5-9","10-14","15-19","20-24","25-29","30-34","35-39","40-44","45-49","50-54","55-59","60-64","65-69","70-74","75-79","80-84","85 Plus"];
chart.xAxis.tickFormat( function (d) {
return x_discreet_labels[d];
});
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
chart.dispatch.on('renderEnd.alignAnnotations', function () {
});
LineChart1_data = data;
LineChart1_chart = chart;
LineChart1_svg = svg;
LineChart1_x_annotations = x_annotations;
LineChart1_y_annotations = y_annotations;
return chart;
}, function() {
});
</script>
<script>
var PieChart0_data;
var PieChart0_chart;
var PieChart0_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Male","y":4924},{"x":"Female","y":5582}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart0');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart0_data = data;
PieChart0_chart = chart;
PieChart0_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var PieChart1_data;
var PieChart1_chart;
var PieChart1_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"White","y":8465},{"x":"Black Or African American","y":82},{"x":"American Indian Or Alaskan Native","y":21},{"x":"Asian","y":1233},{"x":"Native Hawaiian & Other Pacific Islander","y":2},{"x":"Other Race","y":289},{"x":"Two Or More Races","y":414}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart1');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart1_data = data;
PieChart1_chart = chart;
PieChart1_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var LineChart2_data;
var LineChart2_chart;
var LineChart2_svg;
var LineChart2_x_annotations;
var LineChart2_y_annotations;
nv.addGraph(function() {
var data = [{"key":"Owner","values":[{"x":0,"y":11},{"x":1,"y":117},{"x":2,"y":371},{"x":3,"y":620},{"x":4,"y":623},{"x":5,"y":419},{"x":6,"y":322},{"x":7,"y":129}]},{"key":"Renter","values":[{"x":0,"y":34},{"x":1,"y":277},{"x":2,"y":283},{"x":3,"y":318},{"x":4,"y":214},{"x":5,"y":166},{"x":6,"y":109},{"x":7,"y":84}]},{"key":"Total","color":"#000000","values":[{"x":0,"y":45},{"x":1,"y":394},{"x":2,"y":654},{"x":3,"y":938},{"x":4,"y":837},{"x":5,"y":585},{"x":6,"y":431},{"x":7,"y":213}]}];
var chart = nv.models.lineChart()
.useInteractiveGuideline(true);
var svg = d3.select('#LineChart2');
var x_annotations = [];
var y_annotations = [];
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.forceY(0);
if (data.length > 2 && parseInt(svg.style('width')) < 768/2) {
chart.showLegend(false);
}
var x_discreet_labels = ["15-24","25-34","35-44","45-54","55-64","65-74","75-84","85 Plus"];
chart.xAxis.tickFormat( function (d) {
return x_discreet_labels[d];
});
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
chart.dispatch.on('renderEnd.alignAnnotations', function () {
});
LineChart2_data = data;
LineChart2_chart = chart;
LineChart2_svg = svg;
LineChart2_x_annotations = x_annotations;
LineChart2_y_annotations = y_annotations;
return chart;
}, function() {
});
</script>
<script>
var PieChart2_data;
var PieChart2_chart;
var PieChart2_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Husband Wife Family Households","y":2346},{"x":"Single Guardian","y":557},{"x":"Singles","y":978},{"x":"Singles With Roommate","y":216}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart2');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e","#ffbb78"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart2_data = data;
PieChart2_chart = chart;
PieChart2_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var PieChart3_data;
var PieChart3_chart;
var PieChart3_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Households Without Kids","y":2972},{"x":"Households With Kids","y":1125}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart3');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart3_data = data;
PieChart3_chart = chart;
PieChart3_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var LineChart3_data;
var LineChart3_chart;
var LineChart3_svg;
var LineChart3_x_annotations;
var LineChart3_y_annotations;
nv.addGraph(function() {
var data = [{"key":"Male","values":[{"x":0,"y":49},{"x":1,"y":55},{"x":2,"y":65},{"x":3,"y":49},{"x":4,"y":56},{"x":5,"y":67},{"x":6,"y":46},{"x":7,"y":50},{"x":8,"y":48},{"x":9,"y":46},{"x":10,"y":63},{"x":11,"y":45},{"x":12,"y":44},{"x":13,"y":48},{"x":14,"y":54},{"x":15,"y":51},{"x":16,"y":38},{"x":17,"y":41},{"x":18,"y":41},{"x":19,"y":58}]},{"key":"Female","values":[{"x":0,"y":50},{"x":1,"y":55},{"x":2,"y":65},{"x":3,"y":57},{"x":4,"y":56},{"x":5,"y":54},{"x":6,"y":54},{"x":7,"y":53},{"x":8,"y":52},{"x":9,"y":45},{"x":10,"y":42},{"x":11,"y":41},{"x":12,"y":60},{"x":13,"y":52},{"x":14,"y":50},{"x":15,"y":41},{"x":16,"y":50},{"x":17,"y":51},{"x":18,"y":38},{"x":19,"y":52}]},{"key":"Total","color":"#000000","values":[{"x":0,"y":99},{"x":1,"y":110},{"x":2,"y":130},{"x":3,"y":106},{"x":4,"y":112},{"x":5,"y":121},{"x":6,"y":100},{"x":7,"y":103},{"x":8,"y":100},{"x":9,"y":91},{"x":10,"y":105},{"x":11,"y":86},{"x":12,"y":104},{"x":13,"y":100},{"x":14,"y":104},{"x":15,"y":92},{"x":16,"y":88},{"x":17,"y":92},{"x":18,"y":79},{"x":19,"y":110}]}];
var chart = nv.models.lineChart()
.useInteractiveGuideline(true);
var svg = d3.select('#LineChart3');
var x_annotations = [];
var y_annotations = [];
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.forceY(0);
if (data.length > 2 && parseInt(svg.style('width')) < 768/2) {
chart.showLegend(false);
}
var x_discreet_labels = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"];
chart.xAxis.tickFormat( function (d) {
return x_discreet_labels[d];
});
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
chart.dispatch.on('renderEnd.alignAnnotations', function () {
});
LineChart3_data = data;
LineChart3_chart = chart;
LineChart3_svg = svg;
LineChart3_x_annotations = x_annotations;
LineChart3_y_annotations = y_annotations;
return chart;
}, function() {
});
</script>
<script>
var PieChart4_data;
var PieChart4_chart;
var PieChart4_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"In Occupied Housing Units","y":10494},{"x":"Correctional Facility For Adults","y":0},{"x":"Juvenile Facilities","y":0},{"x":"Nursing Facilities","y":0},{"x":"Other Institutional","y":0},{"x":"College Student Housing","y":0},{"x":"Military Quarters","y":0},{"x":"Other Noninstitutional","y":12}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart4');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart4_data = data;
PieChart4_chart = chart;
PieChart4_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart0_data;
var BarChart0_chart;
var BarChart0_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"1939 Or Earlier","y":1409},{"x":"1940s","y":180},{"x":"1950s","y":310},{"x":"1960s","y":869},{"x":"1970s","y":557},{"x":"1980s","y":423},{"x":"1990s","y":272},{"x":"2000s","y":89},{"x":"2010 Or Later","y":0}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart0');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart0_data = data;
BarChart0_chart = chart;
BarChart0_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var PieChart5_data;
var PieChart5_chart;
var PieChart5_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Owned Households With A Mortgage","y":2009},{"x":"Owned Households Free & Clear","y":603},{"x":"Renter Occupied Households","y":1485},{"x":"Households Vacant","y":186}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart5');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e","#ffbb78"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart5_data = data;
PieChart5_chart = chart;
PieChart5_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var PieChart6_data;
var PieChart6_chart;
var PieChart6_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"For Rent","y":129},{"x":"Rented & Unoccupied","y":1},{"x":"For Sale Only","y":19},{"x":"Sold & Unoccupied","y":7},{"x":"For Season Recreational Or Occasional Use","y":6},{"x":"For Migrant Workers","y":0},{"x":"Vacant For Other Reasons","y":24}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart6');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart6_data = data;
PieChart6_chart = chart;
PieChart6_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart1_data;
var BarChart1_chart;
var BarChart1_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"$1-$24,999","y":16},{"x":"$25,000-$49,999","y":11},{"x":"$50,000-$99,999","y":11},{"x":"$100,000-$149,999","y":12},{"x":"$150,000-$199,999","y":0},{"x":"$200,000-$399,999","y":209},{"x":"$400,000-$749,999","y":854},{"x":"$750,000+","y":1328}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart1');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart1_data = data;
BarChart1_chart = chart;
BarChart1_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var PieChart7_data;
var PieChart7_chart;
var PieChart7_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Studio Apartment","y":0},{"x":"1 Bedroom","y":641},{"x":"2 Bedroom","y":652},{"x":"3+ Bedroom","y":173}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart7');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e","#ffbb78"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart7_data = data;
PieChart7_chart = chart;
PieChart7_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart2_data;
var BarChart2_chart;
var BarChart2_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"< $200","y":0},{"x":"$200-$299","y":0},{"x":"$300-$499","y":0},{"x":"$500-$749","y":0},{"x":"$750-$999","y":0},{"x":"$1,000+","y":0}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart2');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart2_data = data;
BarChart2_chart = chart;
BarChart2_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart3_data;
var BarChart3_chart;
var BarChart3_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"< $200","y":0},{"x":"$200-$299","y":0},{"x":"$300-$499","y":0},{"x":"$500-$749","y":0},{"x":"$750-$999","y":97},{"x":"$1,000+","y":488}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart3');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart3_data = data;
BarChart3_chart = chart;
BarChart3_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart4_data;
var BarChart4_chart;
var BarChart4_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"< $200","y":0},{"x":"$200-$299","y":0},{"x":"$300-$499","y":0},{"x":"$500-$749","y":0},{"x":"$750-$999","y":21},{"x":"$1,000+","y":631}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart4');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart4_data = data;
BarChart4_chart = chart;
BarChart4_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart5_data;
var BarChart5_chart;
var BarChart5_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"< $200","y":0},{"x":"$200-$299","y":0},{"x":"$300-$499","y":0},{"x":"$500-$749","y":0},{"x":"$750-$999","y":0},{"x":"$1,000+","y":155}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart5');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart5_data = data;
BarChart5_chart = chart;
BarChart5_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var PieChart8_data;
var PieChart8_chart;
var PieChart8_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Worked Full-time With Earnings","y":3494},{"x":"Worked Part-time With Earnings","y":2347},{"x":"No Earnings","y":3006}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart8');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart8_data = data;
PieChart8_chart = chart;
PieChart8_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var LineChart4_data;
var LineChart4_chart;
var LineChart4_svg;
var LineChart4_x_annotations;
var LineChart4_y_annotations;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":2005,"y":95202.3314},{"x":2006,"y":99620.3008},{"x":2007,"y":100802.0399},{"x":2008,"y":100820.1074},{"x":2009,"y":96253.4865},{"x":2010,"y":102796.1285},{"x":2011,"y":110183.4052},{"x":2012,"y":119197.9123},{"x":2013,"y":120235.1464},{"x":2014,"y":122605.4167}]}];
var chart = nv.models.lineChart()
.useInteractiveGuideline(true);
var svg = d3.select('#LineChart4');
var x_annotations = [];
var y_annotations = [];
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.margin().left += 10;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format('$,.0f')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format('$,.0f')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format('$,.0f'));
}
if (typeof chart.yAxis != 'undefined') {
chart.yAxis.tickFormat(function(d){
return d3.format('$,.0f')(d);
});
}
chart.forceY(0);
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
chart.dispatch.on('renderEnd.alignAnnotations', function () {
});
LineChart4_data = data;
LineChart4_chart = chart;
LineChart4_svg = svg;
LineChart4_x_annotations = x_annotations;
LineChart4_y_annotations = y_annotations;
return chart;
}, function() {
});
</script>
<script>
var BarChart6_data;
var BarChart6_chart;
var BarChart6_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"< $25,000","y":623},{"x":"$25,000-$44,999","y":339},{"x":"$45,000-$59,999","y":400},{"x":"$60,000-$99,999","y":775},{"x":"$100,000-$149,999","y":636},{"x":"$150,000-$199,999","y":421},{"x":"$200,000+","y":713}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart6');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart6_data = data;
BarChart6_chart = chart;
BarChart6_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart7_data;
var BarChart7_chart;
var BarChart7_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"< $10,000","y":779},{"x":"$10,000-$19,999","y":755},{"x":"$20,000-$29,999","y":547},{"x":"$30,000-$39,999","y":552},{"x":"$40,000-$49,999","y":416},{"x":"$50,000-$64,999","y":719},{"x":"$65,000-$74,999","y":354},{"x":"$75,000-$99,999","y":575},{"x":"$100,000+","y":1144}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart7');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart7_data = data;
BarChart7_chart = chart;
BarChart7_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart8_data;
var BarChart8_chart;
var BarChart8_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Wages","y":76.25},{"x":"Business","y":28.5417},{"x":"Partnership","y":17.5},{"x":"Unemployment","y":7.0833}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart8');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
chart.margin().left += 10;
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',.0f')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',.0f')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(',.0f'));
}
if (typeof chart.yAxis != 'undefined') {
chart.yAxis.tickFormat(function(d){
return d3.format(',.0f')(d) + '%';
});
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart8_data = data;
BarChart8_chart = chart;
BarChart8_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart9_data;
var BarChart9_chart;
var BarChart9_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Wages","y":87358.7432},{"x":"Business","y":20247.4453},{"x":"Partnership","y":124561.9048},{"x":"Unemployment","y":5011.7647}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart9');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.margin().left += 10;
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format('$,.0f')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format('$,.0f')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format('$,.0f'));
}
if (typeof chart.yAxis != 'undefined') {
chart.yAxis.tickFormat(function(d){
return d3.format('$,.0f')(d);
});
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart9_data = data;
BarChart9_chart = chart;
BarChart9_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart10_data;
var BarChart10_chart;
var BarChart10_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Interest","y":47.7083},{"x":"Ordinary Dividends","y":30.4167},{"x":"Qualified Dividends","y":28.3333},{"x":"Capital Gains","y":30.2083}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart10');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
chart.margin().left += 10;
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',.0f')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',.0f')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(',.0f'));
}
if (typeof chart.yAxis != 'undefined') {
chart.yAxis.tickFormat(function(d){
return d3.format(',.0f')(d) + '%';
});
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart10_data = data;
BarChart10_chart = chart;
BarChart10_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart11_data;
var BarChart11_chart;
var BarChart11_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Interest","y":2646.7249},{"x":"Ordinary Dividends","y":9984.9315},{"x":"Qualified Dividends","y":7917.6471},{"x":"Capital Gains","y":20866.8966}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart11');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.margin().left += 10;
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format('$,.0f')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format('$,.0f')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format('$,.0f'));
}
if (typeof chart.yAxis != 'undefined') {
chart.yAxis.tickFormat(function(d){
return d3.format('$,.0f')(d);
});
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart11_data = data;
BarChart11_chart = chart;
BarChart11_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart12_data;
var BarChart12_chart;
var BarChart12_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"IRA Distributions","y":11.0417},{"x":"Pensions\/annuities","y":16.6667},{"x":"Social Security","y":16.0417}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart12');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
chart.margin().left += 10;
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',.0f')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',.0f')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(',.0f'));
}
if (typeof chart.yAxis != 'undefined') {
chart.yAxis.tickFormat(function(d){
return d3.format(',.0f')(d) + '%';
});
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart12_data = data;
BarChart12_chart = chart;
BarChart12_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart13_data;
var BarChart13_chart;
var BarChart13_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"IRA Distributions","y":21079.2453},{"x":"Pensions\/annuities","y":31145},{"x":"Social Security","y":16987.013}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart13');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.margin().left += 10;
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format('$,.0f')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format('$,.0f')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format('$,.0f'));
}
if (typeof chart.yAxis != 'undefined') {
chart.yAxis.tickFormat(function(d){
return d3.format('$,.0f')(d);
});
}
chart.staggerLabels(true);
chart.margin().bottom += 15;
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart13_data = data;
BarChart13_chart = chart;
BarChart13_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var PieChart9_data;
var PieChart9_chart;
var PieChart9_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Worked Full-time With Earnings","y":3494},{"x":"Worked Part-time With Earnings","y":2347},{"x":"No Earnings","y":3006}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart9');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart9_data = data;
PieChart9_chart = chart;
PieChart9_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var PieChart10_data;
var PieChart10_chart;
var PieChart10_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Car, Truck, Or Van","y":4112},{"x":"Public Transportation","y":73},{"x":"Taxicab","y":0},{"x":"Motorcycle","y":14},{"x":"Bicycle, Walked, Or Other Means","y":443},{"x":"Worked At Home","y":400}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart10');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart10_data = data;
PieChart10_chart = chart;
PieChart10_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var BarChart14_data;
var BarChart14_chart;
var BarChart14_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"< 10","y":757},{"x":"10-19","y":1538},{"x":"20-29","y":789},{"x":"30-39","y":754},{"x":"40-44","y":129},{"x":"45-59","y":318},{"x":"60-89","y":266},{"x":"90+","y":91}]}];
var chart = nv.models.discreteBarChart();
var svg = d3.select('#BarChart14');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.legend != 'undefined') {
chart.legend.vers('furious');
}
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
if (parseInt(svg.style('width')) < 768/2) {
chart.staggerLabels(true);
chart.margin().bottom += 15;
}
svg.datum(data)
.call(chart);
nv.utils.windowResize(function() { chart.update() });
BarChart14_data = data;
BarChart14_chart = chart;
BarChart14_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var PieChart11_data;
var PieChart11_chart;
var PieChart11_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Less Than High School Diploma","y":350},{"x":"High School Graduate","y":1069},{"x":"Associate's Degree","y":339},{"x":"Bachelor's Degree","y":1074},{"x":"Master's Degree","y":479},{"x":"Professional School Degree","y":469},{"x":"Doctorate Degree","y":119}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart11');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart11_data = data;
PieChart11_chart = chart;
PieChart11_svg = svg;
return chart;
}, function() {
});
</script>
<script>
var PieChart12_data;
var PieChart12_chart;
var PieChart12_svg;
nv.addGraph(function() {
var data = [{"key":"Data","values":[{"x":"Enrolled In Public School","y":919},{"x":"Enrolled In Private School","y":384},{"x":"Not Enrolled In School","y":156}]}];
var total = 0;
data[0].values.forEach(function (d) {
total = total + d.y;
});
var chart = nv.models.pieChart();
var svg = d3.select('#PieChart12');
chart.margin({ top: 30, right: 20, bottom: 20, left: 50 })
if (typeof chart.legend != 'undefined') chart.legend.margin().right -= 30;
if (typeof chart.yScale != 'undefined') {
chart.margin().left -= 3*8;
}
chart.showLegend(false);
var y_window_formats = 0;
nv.utils.windowResize(function() {
y_window_formats = 0;
});
if (typeof chart.dispatch.stateChange != 'undefined') {
// some charts (including bar charts) don't have state changes
chart.dispatch.on('stateChange.y_window_formats', function () {
y_window_formats = 0;
});
}
if (typeof chart.yAxis != 'undefined') {
// some charts (including pie charts) don't have a y axis
chart.yAxis.tickFormat(function (d) {
if (chart.yScale().domain()[1] < 10) {
return d3.format(',')(d);
} else {
// tooltip via https://github.com/novus/nvd3/issues/428
if (this === window) {
if (y_window_formats >= 2) {
return d3.format(',')(d);
}
y_window_formats++;
}
// axis
return d3.format(',.0f')(d);;
}
});
}
if (typeof chart.valueFormat == 'function') {
// over bar
chart.valueFormat(d3.format(','));
}
chart.color(["#1f77b4","#aec7e8","#ff7f0e"]);
chart.margin({top: 5, right: 5, bottom: 5, left: 5});
chart.tooltip.valueFormatter(function (d) {
return (d/total*100).toFixed() + ' %<br><span style="font-weight: normal; font-size: 75%">' + d3.format(',')(d) + ' of ' + d3.format(',')(total) + '</span>';
});
chart.showLabels(false);
chart.growOnHover(false);
if (!chart.labelsOutside()) {
// the current nvd3 version makes the following adjustment even if growOnHover is turned off
// need to undo it
// the result is a pie chart that doesn't fill the entire container
//d.outer = (d.outer - d.outer / 5)
var arcs = chart.arcsRadius();
var new_arcs = [];
if (arcs.length === 0) {
data[0].values.forEach(function (d) {
new_arcs.push({ outer: 1.25, inner: 0 });
});
} else {
arcs.forEach(function (d) {
new_arcs.push({ outer: d.outer*1.25, inner: d.inner*1.25 });
});
}
chart.arcsRadius(new_arcs);
}
// note that a pie chart uses a different data format
svg.datum(data[0].values)
.call(chart);
nv.utils.windowResize(function() { chart.update(); });
PieChart12_data = data;
PieChart12_chart = chart;
PieChart12_svg = svg;
return chart;
}, function() {
});
</script></body>
</html>
| 37.771528 | 8,916 | 0.583675 |
1f94d68ee33bbca4ee09f42e0f8984bbb4cff850 | 2,114 | html | HTML | teaching.html | MichalYem/MichalYem.github.io | 440892c1418b88d1ca3c3d0c21a547ecdd7f1a68 | [
"Apache-2.0"
] | null | null | null | teaching.html | MichalYem/MichalYem.github.io | 440892c1418b88d1ca3c3d0c21a547ecdd7f1a68 | [
"Apache-2.0"
] | null | null | null | teaching.html | MichalYem/MichalYem.github.io | 440892c1418b88d1ca3c3d0c21a547ecdd7f1a68 | [
"Apache-2.0"
] | null | null | null | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta name="generator" content="jemdoc, see http://jemdoc.jaboc.net/" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="stylesheet" href="jemdoc.css" type="text/css" />
<title>Teaching
</title>
</head>
<body>
<table summary="Table for page layout." id="tlayout">
<tr valign="top">
<td id="layout-menu">
<div class="menu-category">Menu</div>
<div class="menu-item"><a href="index.html">About</a></div>
<div class="menu-item"><a href="publications.html">Publications</a></div>
<div class="menu-item"><a href="awards.html">Awards</a></div>
<div class="menu-item"><a href="teaching.html" class="current">Teaching</a></div>
<div class="menu-item"><a href="cv.html">Curriculum Vitae</a></div>
<div class="menu-category">Links</div>
<div class="menu-item"><a href="https://scholar.google.com/citations?user=eTXCI5EAAAAJ&hl=en&authuser=1">Google Scholar</a></div>
<div class="menu-item"><a href="https://dblp.org/pid/142/2496.html">DBLP</a></div>
<div class="menu-item"><a href="https://il.linkedin.com/in/michal-yemini-b4a447122">LinkedIn</a></div>
<div class="menu-category">jemdoc links</div>
<div class="menu-item"><a href="http://jemdoc.jaboc.net/">jemdoc</a></div>
<div class="menu-item"><a href="https://github.com/wsshin/jemdoc_mathjax">jemdoc+MathJax</a></div>
</td>
<td id="layout-content">
<div id="toptitle">
<h1>Teaching
</h1>
<div id="subtitle">
</div>
</div>
<ul>
<li><p>2014-2017 Information Theory.
</p>
</li>
<li><p>2013-2016 Statistical Signal Processing 2 - detection and estimation theory.
</p>
</li>
<li><p>2014-2017 Random Processes (homework grader).
</p>
</li>
<li><p>2013 Signals and Systems.
</p>
</li>
<li><p>2012-2013 Microcontroller Laboratory.
</p>
</li>
<li><p>2012 Microprocessors and assembly language</p>
</li>
</ul>
<div id="footer">
<div id="footer-text">
</div>
</div>
</td>
</tr>
</table>
</body>
</html>
| 34.655738 | 135 | 0.657994 |
98da558690bd8768ae836c8a58276639c134eb31 | 581 | swift | Swift | OctocatKit/OCKCommitsQueryBuilder.swift | unixzii/Octocat | 3dcafea5ac840f715acd564834717c8cf9a9355b | [
"MIT"
] | 1 | 2019-06-10T23:00:52.000Z | 2019-06-10T23:00:52.000Z | OctocatKit/OCKCommitsQueryBuilder.swift | unixzii/Octocat | 3dcafea5ac840f715acd564834717c8cf9a9355b | [
"MIT"
] | null | null | null | OctocatKit/OCKCommitsQueryBuilder.swift | unixzii/Octocat | 3dcafea5ac840f715acd564834717c8cf9a9355b | [
"MIT"
] | null | null | null | //
// OCKCommitsQueryBuilder.swift
// Octocat
//
// Created by 杨弘宇 on 2016/10/24.
// Copyright © 2016年 杨弘宇. All rights reserved.
//
import Foundation
public class OCKCommitsQueryBuilder: OCKPagedQueryBuilder {
public var fullname: String!
public var page: Int = 1
public init() {}
public var queryURL: URL {
let urlString: String = "https://api.github.com/repos/\(fullname!)/commits"
return URL(string: urlString + "?page=\(page)")!
}
public var needAuthorization: Bool {
return false
}
}
| 20.034483 | 83 | 0.614458 |
288c6c6111240271b5a11dac50caac5c4cd819d6 | 11,160 | kt | Kotlin | app/src/main/java/team16/easytracker/ProfileFragment.kt | zogmat555/Team_16 | 9360ff0a4ea34d719780a94fbe2808968c955044 | [
"MIT"
] | null | null | null | app/src/main/java/team16/easytracker/ProfileFragment.kt | zogmat555/Team_16 | 9360ff0a4ea34d719780a94fbe2808968c955044 | [
"MIT"
] | 40 | 2021-03-23T14:25:44.000Z | 2021-06-10T19:45:03.000Z | app/src/main/java/team16/easytracker/ProfileFragment.kt | zogmat555/Team_16 | 9360ff0a4ea34d719780a94fbe2808968c955044 | [
"MIT"
] | 10 | 2021-04-14T06:17:13.000Z | 2021-05-06T16:49:22.000Z | package team16.easytracker
import android.app.AlertDialog
import android.os.Bundle
import android.text.Editable
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import team16.easytracker.database.DbHelper
import team16.easytracker.model.Address
import team16.easytracker.model.Worker
import team16.easytracker.utils.Validator
class ProfileFragment : Fragment(R.layout.fragment_profile) {
// TODO: Rename and change types of parameters
lateinit var etTitleSetting : EditText
lateinit var etFirstNameSetting : EditText
lateinit var etLastNameSetting : EditText
//lateinit var etPhonePrefixSetting : EditText
lateinit var etPhoneNumberSetting : EditText
lateinit var etPostCodeSetting : EditText
lateinit var etCitySetting : EditText
lateinit var etStreetSetting : EditText
lateinit var tvErrorGenderSetting : TextView
lateinit var tvErrorTitleSetting : TextView
lateinit var tvErrorFirstNameSetting : TextView
lateinit var tvErrorLastNameSetting : TextView
lateinit var tvErrorPhonePrefixSetting : TextView
lateinit var tvErrorPhoneNumberSetting : TextView
lateinit var tvErrorPostCodeSetting : TextView
lateinit var tvErrorCitySetting : TextView
lateinit var tvErrorStreetSetting : TextView
lateinit var btnSaveChangesSetting : Button
lateinit var btnChangePassword : Button
lateinit var etOldPassword : EditText
lateinit var etNewPassword : EditText
lateinit var tvErrorOldPassword : TextView
lateinit var currentWorker : Worker
lateinit var helper: DbHelper
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val languageSpinner = view.findViewById<Spinner>(R.id.spLanguageSetting)
MyApplication.initLanguageSpinner(languageSpinner, requireActivity())
etTitleSetting = view.findViewById(R.id.etTitleSetting)
etFirstNameSetting = view.findViewById(R.id.etFirstNameSetting)
etLastNameSetting = view.findViewById(R.id.etLastNameSetting)
//etPhonePrefixSetting = view.findViewById(R.id.etPhonePrefixSetting)
etPhoneNumberSetting = view.findViewById(R.id.etPhoneNumberSetting)
etPostCodeSetting = view.findViewById(R.id.etPostCodeSetting)
etCitySetting = view.findViewById(R.id.etCitySetting)
etStreetSetting = view.findViewById(R.id.etStreetSetting)
tvErrorGenderSetting = view.findViewById(R.id.tvErrorGenderSetting)
tvErrorTitleSetting = view.findViewById(R.id.tvErrorTitleSetting)
tvErrorFirstNameSetting = view.findViewById(R.id.tvErrorFirstNameSetting)
tvErrorLastNameSetting = view.findViewById(R.id.tvErrorLastNameSetting)
tvErrorPhonePrefixSetting = view.findViewById(R.id.tvErrorPhonePrefixSetting)
tvErrorPhoneNumberSetting = view.findViewById(R.id.tvErrorPhoneNumberSetting)
tvErrorPostCodeSetting = view.findViewById(R.id.tvErrorPostCodeSetting)
tvErrorCitySetting = view.findViewById(R.id.tvErrorCitySetting)
tvErrorStreetSetting = view.findViewById(R.id.tvErrorStreetSetting)
btnSaveChangesSetting = view.findViewById(R.id.btnSaveChangesSetting)
btnChangePassword = view.findViewById(R.id.btnChangePassword)
btnSaveChangesSetting.setOnClickListener { updateProfile() }
btnChangePassword.setOnClickListener { changePassword() }
helper = DbHelper.getInstance()
val workerId = MyApplication.loggedInWorker!!.getId()
currentWorker = helper.loadWorker(workerId)!!
val address : Address = helper.loadAddress(currentWorker.addressId)!!
etTitleSetting.text = Editable.Factory.getInstance().newEditable(currentWorker.title)
etFirstNameSetting.text = Editable.Factory.getInstance().newEditable(currentWorker.firstName)
etLastNameSetting.text = Editable.Factory.getInstance().newEditable(currentWorker.lastName)
//etPhonePrefixSetting.text = Editable.Factory.getInstance().newEditable(currentWorker.phoneNumber?.substring(0, 1))
etPhoneNumberSetting.text = Editable.Factory.getInstance().newEditable(currentWorker.phoneNumber)//?.substring(2))
etPostCodeSetting.text = Editable.Factory.getInstance().newEditable(address.zipCode)
etCitySetting.text = Editable.Factory.getInstance().newEditable(address.city)
etStreetSetting.text = Editable.Factory.getInstance().newEditable(address.street)
}
fun updateProfile() {
val titleSetting = etTitleSetting.text.toString()
val firstNameSetting = etFirstNameSetting.text.toString()
val lastNameSetting = etLastNameSetting.text.toString()
//val phonePrefixSetting = etPhonePrefixSetting.text.toString()
val phoneNumberSetting = etPhoneNumberSetting.text.toString()
val postCodeSetting = etPostCodeSetting.text.toString()
val citySetting = etCitySetting.text.toString()
val streetSetting = etStreetSetting.text.toString()
val validTitleSetting = validateTitleSetting(titleSetting)
val validFirstNameSetting = validateFirstNameSetting(firstNameSetting)
val validLastNameSetting = validateLastNameSetting(lastNameSetting)
//val validPhonePrefixSetting = validatePhonePrefixSetting(phonePrefixSetting)
val validPhoneNumberSetting = validatePhoneNumberSetting(phoneNumberSetting)
val validPostCodeSetting = validatePostCodeSetting(postCodeSetting)
val validCitySetting = validateCitySetting(citySetting)
val validStreetSetting = validateStreetSetting(streetSetting)
if(validTitleSetting && validFirstNameSetting && validLastNameSetting && /*validPhonePrefixSetting &&*/ validPhoneNumberSetting
&& validPostCodeSetting && validCitySetting && validStreetSetting)
{
val workerId = MyApplication.loggedInWorker!!.getId()
if(helper.updateWorker(workerId, firstNameSetting, lastNameSetting,
currentWorker.dateOfBirth, titleSetting, currentWorker.email,
/*phonePrefixSetting + */phoneNumberSetting, currentWorker.createdAt,
helper.saveAddress(streetSetting, postCodeSetting, citySetting)))
{
Snackbar.make(view!!, R.string.update_settings_succeeded, BaseTransientBottomBar.LENGTH_LONG).show()
}
}
}
fun changePassword()
{
val builder = AlertDialog.Builder(activity)
builder.setTitle(getString(R.string.change_password))
builder.setCancelable(true)
val promptView = layoutInflater.inflate(R.layout.dialog_change_password, null)
etOldPassword = promptView.findViewById(R.id.etOldPassword)
etNewPassword = promptView.findViewById(R.id.etNewPassword)
tvErrorOldPassword = promptView.findViewById<EditText>(R.id.tvErrorOldPassword)
builder.setView(promptView)
.setPositiveButton(getString(R.string.change_password)) { _, _ ->
val success = validatePasswordChange()
if (success) {
Snackbar.make(view!!, R.string.update_password_succeeded, BaseTransientBottomBar.LENGTH_LONG).show()
Log.d("Settings", "changed password of logged in worker")
}
else{
Snackbar.make(view!!, R.string.failed_update_password, BaseTransientBottomBar.LENGTH_LONG).show()
}
}
.setNegativeButton(getString(R.string.cancel)) { _, _ ->
Log.d("Settings", "change password of logged in worker failed")
}
builder.show()
}
fun validateTitleSetting(titleSetting: String) : Boolean {
val errorTitleSetting = Validator.validateTitle(titleSetting, resources)
if (errorTitleSetting != "") {
tvErrorTitleSetting.text = errorTitleSetting
tvErrorTitleSetting.visibility = View.VISIBLE
tvErrorGenderSetting.visibility = View.VISIBLE
return false
}
return true
}
fun validateFirstNameSetting(firstNameSetting: String) : Boolean {
val errorFirstNameSetting = Validator.validateFirstName(firstNameSetting, resources)
if (errorFirstNameSetting != "") {
tvErrorFirstNameSetting.text = errorFirstNameSetting
tvErrorFirstNameSetting.visibility = View.VISIBLE
return false
}
return true
}
fun validateLastNameSetting(lastNameSetting: String) : Boolean {
val errorLastNameSetting = Validator.validateLastName(lastNameSetting, resources)
if (errorLastNameSetting != "") {
tvErrorLastNameSetting.text = errorLastNameSetting
tvErrorLastNameSetting.visibility = View.VISIBLE
return false
}
return true
}
fun validatePhoneNumberSetting(phoneNumberSetting: String) : Boolean {
val errorPhoneNumberSetting = Validator.validatePhoneNumber(phoneNumberSetting, resources)
if (errorPhoneNumberSetting != "") {
tvErrorPhoneNumberSetting.text = errorPhoneNumberSetting
tvErrorPhoneNumberSetting.visibility = View.VISIBLE
tvErrorPhonePrefixSetting.visibility = View.VISIBLE
return false
}
return true
}
fun validatePostCodeSetting(postCodeSetting: String) : Boolean {
val errorPostCodeSetting = Validator.validatePostCode(postCodeSetting, resources)
if (errorPostCodeSetting != "") {
tvErrorPostCodeSetting.text = errorPostCodeSetting
tvErrorPostCodeSetting.visibility = View.VISIBLE
return false
}
return true
}
fun validateCitySetting(citySetting: String) : Boolean {
val errorCitySetting = Validator.validateCity(citySetting, resources)
if (errorCitySetting != "") {
tvErrorCitySetting.text = errorCitySetting
tvErrorCitySetting.visibility = View.VISIBLE
tvErrorPostCodeSetting.visibility = View.VISIBLE
return false
}
return true
}
fun validateStreetSetting(streetSetting: String) : Boolean {
val errorStreetSetting = Validator.validateStreet(streetSetting, resources)
if (errorStreetSetting != "") {
tvErrorStreetSetting.text = errorStreetSetting
tvErrorStreetSetting.visibility = View.VISIBLE
return false
}
return true
}
fun validatePasswordChange() : Boolean {
if(Validator.validatePassword(etNewPassword.text.toString(), resources) != "")
{
return false
}
if(helper.updateWorkerPassword(MyApplication.loggedInWorker!!.getId(), etOldPassword.text.toString(), etNewPassword.text.toString()))
{
return true
}
return false
}
}
| 45 | 141 | 0.716667 |
39fb24dd305769757980cb4941f1ef7c76b20562 | 1,204 | java | Java | core/kernel/source/jetbrains/mps/persistence/ModelCannotBeCreatedException.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | core/kernel/source/jetbrains/mps/persistence/ModelCannotBeCreatedException.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | core/kernel/source/jetbrains/mps/persistence/ModelCannotBeCreatedException.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2003-2016 JetBrains s.r.o.
*
* 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 jetbrains.mps.persistence;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
/**
* Base class for the whole hierarchy of the variety of problems which
* could arise during the model creation
*
* @see DefaultModelRoot#createModel
*
* Created by apyshkin on 12/23/16.
*/
public class ModelCannotBeCreatedException extends Exception {
public ModelCannotBeCreatedException() {
}
public ModelCannotBeCreatedException(Exception e) {
super("Due to exception", e);
}
public ModelCannotBeCreatedException(@NotNull String message) {
super(message);
}
}
| 28.666667 | 75 | 0.747508 |
1370c1293f3b9609ff2038255dc41e8a5085db57 | 2,902 | h | C | src/uterm_vt.h | sjnewbury/kmscon | 0fc6ec4e7d9e6cf26d0508d2a684a9f0ddccbffa | [
"MIT"
] | 262 | 2015-01-01T02:17:03.000Z | 2022-03-30T21:11:14.000Z | src/uterm_vt.h | sjnewbury/kmscon | 0fc6ec4e7d9e6cf26d0508d2a684a9f0ddccbffa | [
"MIT"
] | 35 | 2018-05-28T02:07:23.000Z | 2022-02-22T23:53:35.000Z | src/uterm_vt.h | sjnewbury/kmscon | 0fc6ec4e7d9e6cf26d0508d2a684a9f0ddccbffa | [
"MIT"
] | 50 | 2015-04-16T03:06:19.000Z | 2022-02-27T19:16:55.000Z | /*
* uterm - Linux User-Space Terminal VT API
*
* Copyright (c) 2011-2013 David Herrmann <dh.herrmann@googlemail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* Virtual Terminals
* Virtual terminals allow controlling multiple virtual terminals on one real
* terminal. It is multi-seat capable and fully asynchronous.
*/
#ifndef UTERM_UTERM_VT_H
#define UTERM_UTERM_VT_H
#include <eloop.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdlib.h>
#include <uterm_input.h>
struct uterm_vt;
struct uterm_vt_master;
enum uterm_vt_action {
UTERM_VT_ACTIVATE,
UTERM_VT_DEACTIVATE,
UTERM_VT_HUP,
};
enum uterm_vt_flags {
UTERM_VT_FORCE = 0x01,
};
struct uterm_vt_event {
unsigned int action;
unsigned int flags;
int target;
};
enum uterm_vt_type {
UTERM_VT_REAL = 0x01,
UTERM_VT_FAKE = 0x02,
};
typedef int (*uterm_vt_cb) (struct uterm_vt *vt, struct uterm_vt_event *ev,
void *data);
int uterm_vt_master_new(struct uterm_vt_master **out,
struct ev_eloop *eloop);
void uterm_vt_master_ref(struct uterm_vt_master *vtm);
void uterm_vt_master_unref(struct uterm_vt_master *vtm);
int uterm_vt_master_activate_all(struct uterm_vt_master *vtm);
int uterm_vt_master_deactivate_all(struct uterm_vt_master *vtm);
int uterm_vt_allocate(struct uterm_vt_master *vt, struct uterm_vt **out,
unsigned int allowed_types,
const char *seat, struct uterm_input *input,
const char *vt_name, uterm_vt_cb cb, void *data);
void uterm_vt_deallocate(struct uterm_vt *vt);
void uterm_vt_ref(struct uterm_vt *vt);
void uterm_vt_unref(struct uterm_vt *vt);
int uterm_vt_activate(struct uterm_vt *vt);
int uterm_vt_deactivate(struct uterm_vt *vt);
void uterm_vt_retry(struct uterm_vt *vt);
unsigned int uterm_vt_get_type(struct uterm_vt *vt);
unsigned int uterm_vt_get_num(struct uterm_vt *vt);
#endif /* UTERM_UTERM_VT_H */
| 31.89011 | 77 | 0.768436 |
95805991ecdbec493b4fda13f4c5f758502e5bbd | 2,725 | css | CSS | website/main.css | daphne-yang/spotify-visualizations | 0932aa467526a1c83755d692473db5737c0dcff3 | [
"MIT"
] | null | null | null | website/main.css | daphne-yang/spotify-visualizations | 0932aa467526a1c83755d692473db5737c0dcff3 | [
"MIT"
] | null | null | null | website/main.css | daphne-yang/spotify-visualizations | 0932aa467526a1c83755d692473db5737c0dcff3 | [
"MIT"
] | null | null | null | .tableauPlaceholder {
width: 500px;
height: auto;
}
.explanation {
font-family: "Times New Roman", Times, serif;
font-size: large;
}
/*
*
* ==========================================
* CUSTOM UTIL CLASSES
* ==========================================
*
*/
.navbar {
transition: all 0.4s;
}
.navbar .nav-link {
color: #fff;
}
.navbar .nav-link:hover,
.navbar .nav-link:focus {
color: #fff;
text-decoration: none;
}
.navbar .navbar-brand {
color: #fff;
}
/* Change navbar styling on scroll */
.navbar.active {
background: #64b85d;
box-shadow: 1px 2px 10px rgba(0, 0, 0, 0.1);
}
.navbar.active .nav-link {
color: rgb(255, 255, 255);
}
.navbar.active .nav-link:hover,
.navbar.active .nav-link:focus {
color: #555;
text-decoration: none;
}
.navbar.active .navbar-brand {
color: #555;
}
/* Change navbar styling on small viewports */
@media (max-width: 991.98px) {
.navbar {
background: #fff;
}
.navbar .navbar-brand,
.navbar .nav-link {
color: #555;
}
}
/*
*
* ==========================================
* FOR DEMO PURPOSES
* ==========================================
*
*/
.center {
margin-left: auto;
margin-right: auto;
width: 75%;
height: auto;
/* padding: 10 px; */
text-align: center;
}
.text-small {
font-size: 0.9rem !important;
}
body {
min-height: 110vh;
background-color: #1d1d1d;
/* background-image: linear-gradient(135deg, #000000 0%, #c4e0e5 100%); */
}
.display-4 {
color: #64b85d;
}
.display-3 {
color: #fff;
font-weight: bold;
}
.vis-header {
display: inline;
}
.guide-icons {
float: inline-end;
vertical-align: text-bottom;
}
.card-text {
background-color: #1d1d1d;
color: #fff;
font-size: 1.25em;
}
.card-title {
color: #64b85d;
font-size: 1.5em;
font-weight: normal;
}
.container {
max-width: 100em;
}
/* about the team */
.profile {
border-radius: 50%;
}
.welcome {
border-radius: 25px;
background-color: #2d2f35;
}
.secondary-text {
color: #e0e0e0;
}
.btn-welcome {
color: #e0e0e0;
background-color: #2d2f35;
border-color: #2d2f35;
border-radius: 25px;
font-size: 120%;
}
.btn-welcome:hover {
color: #e0e0e0;
background-color: #474747;
font-weight: bold;
}
.container-fluid {
width: 95%;
}
.cover {
background-image: url("img/background-2.jpeg");
background-size: cover;
background-repeat: no-repeat;
image-rendering: -webkit-optimize-contrast;
z-index: -1;
backdrop-filter: blur(3px);
}
.name-card-title {
color: #e0e0e0;
font-size: 40px;
}
/* Secondary Color: Lighter Dark Grey - #2d2f35, 474747, e0e0e0 */
| 15.935673 | 78 | 0.561468 |
eaed3a5e68038137f7345a8325a0f6b1b2ade199 | 10,342 | lua | Lua | AzurLaneData/zh-CN/sharecfg/enemy_data_statistics_sublist/enemy_data_statistics_257.lua | FlandreCirno/AzurLaneWikiUtilitiesManual | b525fd9086dd716bb65848a8cd0635b261ab6fdf | [
"MIT"
] | null | null | null | AzurLaneData/zh-CN/sharecfg/enemy_data_statistics_sublist/enemy_data_statistics_257.lua | FlandreCirno/AzurLaneWikiUtilitiesManual | b525fd9086dd716bb65848a8cd0635b261ab6fdf | [
"MIT"
] | null | null | null | AzurLaneData/zh-CN/sharecfg/enemy_data_statistics_sublist/enemy_data_statistics_257.lua | FlandreCirno/AzurLaneWikiUtilitiesManual | b525fd9086dd716bb65848a8cd0635b261ab6fdf | [
"MIT"
] | null | null | null | pg = pg or {}
pg.enemy_data_statistics_257 = {
[13300356] = {
cannon = 45,
reload = 150,
speed_growth = 0,
cannon_growth = 640,
rarity = 4,
air = 0,
torpedo = 135,
dodge = 28,
durability_growth = 23600,
antiaircraft = 125,
luck = 0,
reload_growth = 0,
dodge_growth = 450,
hit_growth = 350,
star = 4,
hit = 30,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 50,
base = 423,
durability = 4340,
armor_growth = 0,
torpedo_growth = 5200,
luck_growth = 0,
speed = 36,
armor = 0,
id = 13300356,
antiaircraft_growth = 3000,
antisub = 0,
equipment_list = {
1002103,
1002108,
1002113
}
},
[13300357] = {
cannon = 74,
reload = 150,
speed_growth = 0,
cannon_growth = 936,
rarity = 4,
air = 0,
torpedo = 112,
dodge = 11,
durability_growth = 33600,
antiaircraft = 255,
luck = 0,
reload_growth = 0,
dodge_growth = 162,
hit_growth = 210,
star = 4,
hit = 14,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 55,
base = 424,
durability = 5270,
armor_growth = 0,
torpedo_growth = 3366,
luck_growth = 0,
speed = 24,
armor = 0,
id = 13300357,
antiaircraft_growth = 3744,
antisub = 0,
equipment_list = {
1002118,
1002123,
1002128,
1002133
}
},
[13300358] = {
cannon = 102,
reload = 150,
speed_growth = 0,
cannon_growth = 1750,
rarity = 4,
air = 0,
torpedo = 84,
dodge = 17,
durability_growth = 43200,
antiaircraft = 192,
luck = 0,
reload_growth = 0,
dodge_growth = 170,
hit_growth = 350,
star = 4,
hit = 30,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 60,
base = 425,
durability = 6040,
armor_growth = 0,
torpedo_growth = 3200,
luck_growth = 0,
speed = 18,
armor = 0,
id = 13300358,
antiaircraft_growth = 3880,
antisub = 0,
equipment_list = {
1002138,
1002143,
1002148,
1002153
}
},
[13300359] = {
cannon = 120,
reload = 150,
speed_growth = 0,
cannon_growth = 3600,
rarity = 3,
air = 0,
torpedo = 0,
dodge = 17,
durability_growth = 68000,
antiaircraft = 212,
luck = 0,
reload_growth = 0,
dodge_growth = 170,
hit_growth = 350,
star = 4,
hit = 30,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 65,
base = 426,
durability = 9010,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 14,
armor = 0,
id = 13300359,
antiaircraft_growth = 4680,
antisub = 0,
equipment_list = {
1002158,
1002163,
1002168,
1002173
},
buff_list = {
{
ID = 50510,
LV = 3
}
}
},
[13300360] = {
cannon = 86,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
rarity = 3,
air = 145,
torpedo = 0,
dodge = 15,
durability_growth = 59600,
antiaircraft = 230,
luck = 0,
reload_growth = 0,
dodge_growth = 120,
hit_growth = 350,
star = 4,
hit = 30,
antisub_growth = 0,
air_growth = 4500,
battle_unit_type = 70,
base = 427,
durability = 7820,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 16,
armor = 0,
id = 13300360,
antiaircraft_growth = 5280,
antisub = 0,
equipment_list = {
1002178,
1002183,
1002188,
1002193
}
},
[13300361] = {
cannon = 5,
reload = 150,
speed_growth = 0,
cannon_growth = 300,
pilot_ai_template_id = 10002,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 24,
durability_growth = 3800,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 120,
star = 2,
hit = 8,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 65,
base = 439,
durability = 180,
armor_growth = 0,
torpedo_growth = 2200,
luck_growth = 0,
speed = 15,
luck = 0,
id = 13300361,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
equipment_list = {
1100697,
1100712
}
},
[13300363] = {
cannon = 60,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 80000,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 120,
durability_growth = 2550,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 1200,
star = 1,
hit = 81,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 15,
base = 422,
durability = 80,
armor_growth = 0,
torpedo_growth = 900,
luck_growth = 0,
speed = 30,
luck = 0,
id = 13300363,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
1000867,
1000877
}
},
[13300401] = {
cannon = 7,
reload = 150,
speed_growth = 0,
cannon_growth = 560,
rarity = 2,
air = 0,
torpedo = 33,
dodge = 0,
durability_growth = 10000,
antiaircraft = 60,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 25,
base = 429,
durability = 300,
armor_growth = 0,
torpedo_growth = 3250,
luck_growth = 0,
speed = 15,
armor = 0,
id = 13300401,
antiaircraft_growth = 1000,
antisub = 0,
equipment_list = {
1001004,
1001009,
1001014
}
},
[13300402] = {
cannon = 16,
reload = 150,
speed_growth = 0,
cannon_growth = 880,
rarity = 2,
air = 0,
torpedo = 26,
dodge = 0,
durability_growth = 19200,
antiaircraft = 120,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 30,
base = 430,
durability = 510,
armor_growth = 0,
torpedo_growth = 2250,
luck_growth = 0,
speed = 15,
armor = 0,
id = 13300402,
antiaircraft_growth = 2250,
antisub = 0,
equipment_list = {
1001019,
1001024
}
},
[13300403] = {
cannon = 18,
reload = 150,
speed_growth = 0,
cannon_growth = 1800,
rarity = 2,
air = 0,
torpedo = 17,
dodge = 0,
durability_growth = 35200,
antiaircraft = 95,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 35,
base = 431,
durability = 1190,
armor_growth = 0,
torpedo_growth = 1250,
luck_growth = 0,
speed = 15,
armor = 0,
id = 13300403,
antiaircraft_growth = 1400,
antisub = 0,
equipment_list = {
1001029,
1001034,
1001039
}
},
[13300404] = {
cannon = 43,
reload = 150,
speed_growth = 0,
cannon_growth = 2200,
rarity = 2,
air = 0,
torpedo = 0,
dodge = 0,
durability_growth = 70400,
antiaircraft = 105,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 60,
base = 432,
durability = 4930,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 15,
armor = 0,
id = 13300404,
antiaircraft_growth = 1400,
antisub = 0,
equipment_list = {
1001044,
1001049,
1001054
}
},
[13300405] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
rarity = 2,
air = 48,
torpedo = 0,
dodge = 0,
durability_growth = 65600,
antiaircraft = 115,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 2000,
battle_unit_type = 65,
base = 433,
durability = 4420,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 15,
armor = 0,
id = 13300405,
antiaircraft_growth = 1800,
antisub = 0,
bound_bone = {
cannon = {
{
1.8,
1.14,
0
}
},
torpedo = {
{
1.07,
0.24,
0
}
},
antiaircraft = {
{
1.8,
1.14,
0
}
},
plane = {
{
1.8,
1.14,
0
}
}
},
equipment_list = {
1001059,
1001064,
1001069,
1001074
}
},
[13300406] = {
cannon = 22,
reload = 150,
speed_growth = 0,
cannon_growth = 626,
rarity = 4,
air = 0,
torpedo = 94,
dodge = 22,
durability_growth = 21600,
antiaircraft = 72,
luck = 0,
reload_growth = 0,
dodge_growth = 360,
hit_growth = 280,
star = 4,
hit = 25,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 50,
base = 273,
durability = 3060,
armor_growth = 0,
torpedo_growth = 5200,
luck_growth = 0,
speed = 36,
armor = 0,
id = 13300406,
antiaircraft_growth = 3000,
antisub = 0,
equipment_list = {
1001104,
1001109,
1001114
}
},
[13300407] = {
cannon = 38,
reload = 150,
speed_growth = 0,
cannon_growth = 936,
rarity = 4,
air = 0,
torpedo = 76,
dodge = 11,
durability_growth = 30400,
antiaircraft = 156,
luck = 0,
reload_growth = 0,
dodge_growth = 162,
hit_growth = 210,
star = 4,
hit = 14,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 55,
base = 274,
durability = 3570,
armor_growth = 0,
torpedo_growth = 3366,
luck_growth = 0,
speed = 25,
armor = 0,
id = 13300407,
antiaircraft_growth = 3744,
antisub = 0,
equipment_list = {
1001119,
1001124,
1001129,
1001134
}
},
[13300408] = {
cannon = 54,
reload = 150,
speed_growth = 0,
cannon_growth = 1500,
rarity = 4,
air = 0,
torpedo = 58,
dodge = 11,
durability_growth = 41600,
antiaircraft = 88,
luck = 0,
reload_growth = 0,
dodge_growth = 136,
hit_growth = 280,
star = 4,
hit = 25,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 60,
base = 275,
durability = 4420,
armor_growth = 0,
torpedo_growth = 2800,
luck_growth = 0,
speed = 18,
armor = 0,
id = 13300408,
antiaircraft_growth = 3380,
antisub = 0,
equipment_list = {
1001139,
1001144,
1001149,
1001154
}
},
[13300409] = {
cannon = 78,
reload = 150,
speed_growth = 0,
cannon_growth = 3400,
rarity = 3,
air = 0,
torpedo = 0,
dodge = 11,
durability_growth = 65600,
antiaircraft = 106,
luck = 0,
reload_growth = 0,
dodge_growth = 136,
hit_growth = 280,
star = 4,
hit = 25,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 65,
base = 276,
durability = 6630,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 14,
armor = 0,
id = 13300409,
antiaircraft_growth = 4680,
antisub = 0,
equipment_list = {
1001159,
1001164,
1001169,
1001174
},
buff_list = {
{
ID = 50510,
LV = 4
}
}
}
}
return
| 16.312303 | 32 | 0.594372 |
b3c2dfd2c9aae3da9d463b2415f198a9b667a79f | 191 | kt | Kotlin | src/main/java/com/masahirosaito/spigot/mscore/utils/FileUtil.kt | MasahiroSaito/MSCore | 543b6b2f9f8550cd5bc801d31f3afe3a8a3a30bf | [
"Apache-2.0"
] | null | null | null | src/main/java/com/masahirosaito/spigot/mscore/utils/FileUtil.kt | MasahiroSaito/MSCore | 543b6b2f9f8550cd5bc801d31f3afe3a8a3a30bf | [
"Apache-2.0"
] | null | null | null | src/main/java/com/masahirosaito/spigot/mscore/utils/FileUtil.kt | MasahiroSaito/MSCore | 543b6b2f9f8550cd5bc801d31f3afe3a8a3a30bf | [
"Apache-2.0"
] | null | null | null | package com.masahirosaito.spigot.mscore.utils
import java.io.File
fun File.load(): File = this.apply {
if (!parentFile.exists()) parentFile.mkdirs()
if (!exists()) createNewFile()
} | 23.875 | 49 | 0.706806 |
dda3e546645bf8dd86695920b163015ddf55ebda | 591 | go | Go | file-to-byte/file-to-byte.go | msm1992/product-apim-tooling | 3a8259c3f0d67b674a86ce4544086832255f83da | [
"Apache-2.0"
] | 39 | 2017-12-01T13:13:41.000Z | 2022-03-14T14:11:54.000Z | file-to-byte/file-to-byte.go | Chamindu36/product-apim-tooling | 917ae80827ffc38ec7c0fafda6cabf10c003cdd7 | [
"Apache-2.0"
] | 469 | 2017-09-15T06:35:13.000Z | 2022-03-29T08:40:38.000Z | file-to-byte/file-to-byte.go | Chamindu36/product-apim-tooling | 917ae80827ffc38ec7c0fafda6cabf10c003cdd7 | [
"Apache-2.0"
] | 122 | 2017-08-15T11:43:56.000Z | 2022-03-22T11:45:11.000Z | package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
)
func main() {
filePath := flag.String("file", "N/A", "file path to be processed")
flag.Parse()
if *filePath == "N/A" {
println("Please specify the file path to be processed using the '-file' flag.")
println()
println(" example: file-to-byte -f /somewhere/over/the/rainbow/file.out")
os.Exit(0)
}
filedata, err := ioutil.ReadFile(*filePath)
if err != nil {
panic(err)
}
fmt.Print("var filedata = []byte{")
for i, v := range filedata {
if i > 0 {
fmt.Print(", ")
}
fmt.Print(v)
}
fmt.Println("}")
}
| 16.416667 | 81 | 0.605753 |
e50ee28e4fad39653cf3e839a20b3e4d4723c27f | 2,662 | tsx | TypeScript | src/common/fileList/FileList.tsx | City-of-Helsinki/berth-reservations-admin | e4f23c4e9495bbc1b173485521cd66bd6a365164 | [
"MIT"
] | 1 | 2020-06-03T12:01:19.000Z | 2020-06-03T12:01:19.000Z | src/common/fileList/FileList.tsx | City-of-Helsinki/berth-reservations-admin | e4f23c4e9495bbc1b173485521cd66bd6a365164 | [
"MIT"
] | 215 | 2019-10-15T07:44:22.000Z | 2022-03-15T21:04:19.000Z | src/common/fileList/FileList.tsx | City-of-Helsinki/berth-reservations-admin | e4f23c4e9495bbc1b173485521cd66bd6a365164 | [
"MIT"
] | 4 | 2019-10-04T10:50:40.000Z | 2020-09-09T09:08:44.000Z | import React from 'react';
import classNames from 'classnames';
import { IconCross } from 'hds-react';
import List from '../list/List';
import styles from './fileList.module.scss';
import Text from '../text/Text';
import InputWrapper, { InputWrapperProps } from '../inputWrapper/InputWrapper';
import IconWrapper from '../iconWrapper/IconWrapper';
export type PersistedFile = {
id: string;
name: string;
markedForDeletion?: boolean;
};
type SharedProps = InputWrapperProps & {
allowDelete?: boolean;
invalid?: boolean;
willBeOverwritten?: boolean;
};
interface SingleModeProps extends SharedProps {
multiple?: false;
onChange: (value: undefined | PersistedFile) => void;
value: undefined | PersistedFile;
}
interface MultipleModeProps extends SharedProps {
multiple: true;
onChange: (value: PersistedFile[]) => void;
value: PersistedFile[];
}
export type FileListProps = SingleModeProps | MultipleModeProps;
const FileList = (props: FileListProps) => {
const { allowDelete = true, helperText, id, invalid = false, label, value, willBeOverwritten = false } = props;
if (value === undefined) return null;
const handleDelete = (targetFile: PersistedFile) => {
if (props.multiple) {
return props.onChange(
props.value.reduce<PersistedFile[]>((acc, file) => {
if (file !== targetFile) return acc.concat(file);
return acc.concat({
...file,
markedForDeletion: !file.markedForDeletion,
});
}, [])
);
}
// single
return props.onChange({
...targetFile,
markedForDeletion: !targetFile.markedForDeletion,
});
};
const valueList = Array.isArray(value) ? value : [value];
return (
<InputWrapper id={id} invalid={invalid} helperText={helperText} label={label}>
<List noBullets>
{valueList.map((file) => {
return (
<li key={file.id} className={styles.fileListItem}>
<Text
color="brand"
className={classNames({
[styles.fileName]: true,
[styles.markedForDeletion]: willBeOverwritten || file.markedForDeletion,
})}
>
{`${file.name}`}
</Text>
{allowDelete && (
<button className={styles.delete} type="button" onClick={() => handleDelete(file)}>
<IconWrapper icon={IconCross} color={file.markedForDeletion ? 'disabled' : 'critical'} />
</button>
)}
</li>
);
})}
</List>
</InputWrapper>
);
};
export default FileList;
| 28.319149 | 113 | 0.600676 |
577f2b78ec9fd2f325a1273d5d30cab6637f41cb | 2,711 | c | C | src/Activations.c | seandburke99/SNN | 74aa7d557e4483eab63c9b44aa6de020319c1882 | [
"MIT"
] | null | null | null | src/Activations.c | seandburke99/SNN | 74aa7d557e4483eab63c9b44aa6de020319c1882 | [
"MIT"
] | null | null | null | src/Activations.c | seandburke99/SNN | 74aa7d557e4483eab63c9b44aa6de020319c1882 | [
"MIT"
] | null | null | null | #include <SNN/Activations.h>
#include <stdio.h>
#include <math.h>
static const int16_t sigmoid_table_uint16[384] = {
64,64,64,65,65,66,66,67,67,67,68,68,69,69,70,70,
71,71,71,72,72,73,73,74,74,74,75,75,76,76,77,77,
77,78,78,79,79,79,80,80,81,81,82,82,82,83,83,84,
84,84,85,85,85,86,86,87,87,87,88,88,89,89,89,90,
90,90,91,91,91,92,92,92,93,93,94,94,94,95,95,95,
96,96,96,97,97,97,97,98,98,98,99,99,99,100,100,100,
101,101,101,101,102,102,102,102,103,103,103,104,104,104,104,105,
105,105,105,106,106,106,106,107,107,107,107,108,108,108,108,108,
109,109,109,109,109,110,110,110,110,111,111,111,111,111,111,112,
112,112,112,112,113,113,113,113,113,113,114,114,114,114,114,114,
115,115,115,115,115,115,115,116,116,116,116,116,116,116,117,117,
117,117,117,117,117,117,118,118,118,118,118,118,118,118,119,119,
119,119,119,119,119,119,119,119,120,120,120,120,120,120,120,120,
120,120,120,121,121,121,121,121,121,121,121,121,121,121,121,122,
122,122,122,122,122,122,122,122,122,122,122,122,122,122,123,123,
123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,
123,124,124,124,124,124,124,124,124,124,124,124,124,124,124,124,
124,124,124,124,124,124,124,124,124,124,125,125,125,125,125,125,
125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,
125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,126,
126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,
126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,
126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,
126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,127
};
void act_relu(SNNFTYPE *data, size_t size){
for(int i=0;i<size;i++){
if(data[i]<0) data[i]=0; // x<=0: y=x, x>0:y=x
}
}
void act_sigmoid(SNNFTYPE *data, size_t size){
for(int i=0;i<size;i++){
data[i] = 255.0/(1.0+exp(-data[i]/255.0));
}
}
void act_tanh(SNNFTYPE* data, size_t size){
for(int i=0;i<size;i++){
data[i] = (SNNFTYPE)(tanh_lut_lookup(data[i]));
}
printf("\n");
}
int32_t sigmoid_lut_lookup(int32_t value) {
value /= 38;
if(abs(value)>=384){
if(value<0) return 0;
else return 127;
}
if(value < 0){
value *= -1;
return 128 - sigmoid_table_uint16[value];
}
return sigmoid_table_uint16[value];
}
int32_t tanh_lut_lookup(int32_t value) {
value = value/38;
if(value < 0){
if(value <= -384) return -127;
int index = value*-1;
return -2*sigmoid_table_uint16[index] + 128;
}else{
if(value >= 384) return 127;
return 2*sigmoid_table_uint16[value] - 128;
}
} | 36.635135 | 68 | 0.635559 |
5f19b874b15099979d4e2d0b4b32ad2e80986a5e | 3,085 | tsx | TypeScript | src/paterns/header.tsx | henrisama/Meetflix | b57fe9e759ca2a5cbcff530caff61e86093600b6 | [
"MIT"
] | null | null | null | src/paterns/header.tsx | henrisama/Meetflix | b57fe9e759ca2a5cbcff530caff61e86093600b6 | [
"MIT"
] | null | null | null | src/paterns/header.tsx | henrisama/Meetflix | b57fe9e759ca2a5cbcff530caff61e86093600b6 | [
"MIT"
] | null | null | null | import Link from 'next/link';
import React from 'react';
import { FcSearch } from 'react-icons/fc';
import { FaUser } from 'react-icons/fa';
import styled from 'styled-components';
import { Container } from '../components/container';
import { FiLogOut } from 'react-icons/fi';
const CustomDiv = styled.div`
height: 100%;
display: flex;
align-items: center;
justify-content: space-between;
//tablet
@media(max-width: 1100px){
}
//mobile
@media(max-width: 700px){
}
`;
const HeaderTitle = styled.h3`
padding: 0px 30px 0px 10px;
font-size: 40pt;
cursor: pointer;
//tablet
@media(max-width: 1100px){
font-size: 20pt;
}
//mobile
@media(max-width: 700px){
}
`;
const HeaderLink = styled.a`
padding: 0px 10px;
font-size: 15pt;
text-decoration: none;
color: white;
//tablet
@media(max-width: 1100px){
font-size: 12pt;
}
//mobile
@media(max-width: 700px){
}
`;
const HeaderSearch = styled.div`
display: flex;
align-items: center;
input{
height: 30px;
width: 300px;
padding: 0px 10px 0px 40px;
color: white;
font-size: 14pt;
border: none;
border-radius: 10px;
background-color: #7c1e1e;
}
`;
const Header: React.FC = () => {
const logoutHandler = async() => {
const response = await fetch(
'https://meetflix.vercel.app/api/user/logout',
{
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
}
).then((value: Response) => {
return value.json();
});
if(response.success){
//window.location.pathname = '/login';
alert('logging out');
}else{
alert('Error when logging out');
}
};
const searchHandler = (event: any) => {
if(event.keyCode === 13){
window.location.href = '/browser/1&search='+event.target.value;
}
};
return (
<Container backgroundColor='#e63535' height='75px'>
<CustomDiv>
{/* Title and Links */}
<Container
display='flex'
height='auto'
width='auto'
alignItems='center'
>
<HeaderLink href='/browser/1'>
<HeaderTitle>
Meetflix
</HeaderTitle>
</HeaderLink>
<HeaderLink href='/browser/wish'>
Wish
</HeaderLink>
<HeaderLink href='/browser/watched'>
Watched
</HeaderLink>
<Link href='/profile' passHref>
<HeaderLink>
Profiles
</HeaderLink>
</Link>
<HeaderLink href='/explore'>
Explore
</HeaderLink>
</Container>
{/* Search */}
<Container
height='auto'
width='auto'
display='flex'
alignItems='center'
>
<HeaderSearch>
<FcSearch
size={25}
cursor='pointer'
style={{transform: 'translateX(30px)'}}
/>
<input
type="text"
name=""
id="header-search-bar"
onKeyUpCapture={searchHandler}
/>
</HeaderSearch>
<Container
padding='0px 10px 0px 30px'
>
<FiLogOut
size={40}
cursor='pointer'
onClick={logoutHandler}/>
</Container>
</Container>
</CustomDiv>
</Container>
);
};
export default Header; | 17.729885 | 66 | 0.591248 |
0109ecb72add0b49ae796e54c843b0eef07c5e89 | 5,399 | rs | Rust | src/day_16.rs | misfits42/advent_of_code_2017 | a4643ea31cd77abe955a01f79aa3ed6b4c8b6f97 | [
"MIT"
] | null | null | null | src/day_16.rs | misfits42/advent_of_code_2017 | a4643ea31cd77abe955a01f79aa3ed6b4c8b6f97 | [
"MIT"
] | null | null | null | src/day_16.rs | misfits42/advent_of_code_2017 | a4643ea31cd77abe955a01f79aa3ed6b4c8b6f97 | [
"MIT"
] | null | null | null | use std::collections::HashMap;
use std::collections::VecDeque;
use regex::Regex;
enum DanceMove {
Spin { shift: u64 },
Exchange { pos_1: usize, pos_2: usize },
Partner { prog_1: String, prog_2: String },
}
#[aoc_generator(day16)]
fn generate_input(input: &str) -> Vec<DanceMove> {
let input = input.trim();
// Create regexes to match and extract fields from raw dance move inputs
let spin_regex = Regex::new(r"s(\d+)").unwrap();
let exchange_regex = Regex::new(r"x(\d+)/(\d+)").unwrap();
let partner_regex = Regex::new(r"p([a-p])/([a-p])").unwrap();
let mut dance_moves = Vec::<DanceMove>::new();
for move_raw in input.split(",") {
if move_raw.starts_with("s") {
// Found a spin move
for capture in spin_regex.captures_iter(move_raw) {
let shift = capture[1].parse::<u64>().unwrap();
let spin_move = DanceMove::Spin { shift: shift };
dance_moves.push(spin_move);
}
} else if move_raw.starts_with("x") {
// Found an exchange move
for capture in exchange_regex.captures_iter(move_raw) {
let pos_1 = capture[1].parse::<usize>().unwrap();
let pos_2 = capture[2].parse::<usize>().unwrap();
let exchange_move = DanceMove::Exchange {
pos_1: pos_1,
pos_2: pos_2,
};
dance_moves.push(exchange_move);
}
} else if move_raw.starts_with("p") {
// Found a partner move
for capture in partner_regex.captures_iter(move_raw) {
let prog_1 = capture[1].to_string();
let prog_2 = capture[2].to_string();
let partner_move = DanceMove::Partner {
prog_1: prog_1,
prog_2: prog_2,
};
dance_moves.push(partner_move);
}
}
}
return dance_moves;
}
#[aoc(day16, part1)]
fn solve_part_1(input: &Vec<DanceMove>) -> String {
// Initialise the programs in the starting order
let mut programs = get_initial_programs();
// Process each dance move
conduct_dance_round(input, &mut programs);
// Generate representation of final order of programs after all dance moves executed
return generate_programs_to_string(&programs);
}
/// Solves AoC 2017 Day 16, Part 2.
#[aoc(day16, part2)]
fn solve_part_2(input: &Vec<DanceMove>) -> String {
// Generate initial ordering of programs
let mut programs = get_initial_programs();
let mut output_store = HashMap::<u64, String>::new();
// Program ordering after dance round repeats with cycle of duration 60 rounds
for round in 1..=60 {
conduct_dance_round(input, &mut programs);
let program_order = generate_programs_to_string(&programs);
output_store.insert(round, program_order);
}
// Determine which of the program orders will be present after the one billionth dance round
let index: u64 = 1000000000 % 60;
return output_store.get(&index).unwrap().to_string();
}
/// Generates representation of order of programs.
fn generate_programs_to_string(programs: &VecDeque<String>) -> String {
let mut output = String::from("");
for program in programs {
output += &program;
}
return output;
}
/// Conducts a single round of dancing, using the specified dance moves to change the order of the
/// programs.
fn conduct_dance_round(dance_moves: &Vec<DanceMove>, programs: &mut VecDeque<String>) {
// Process each dance move
for dance_move in dance_moves {
match dance_move {
// Remove program from end and add to front for "shift" number of times
DanceMove::Spin{shift} => {
for _ in 0..*shift {
let popped = programs.pop_back().unwrap();
programs.push_front(popped);
}
},
// Swap the programs in the two positions specified
DanceMove::Exchange{pos_1, pos_2} => {
programs.swap(*pos_1, *pos_2);
},
// Swap the location of the two specified programs
DanceMove::Partner{prog_1, prog_2} => {
let pos_1 = programs.iter().position(|x| x == prog_1).unwrap();
let pos_2 = programs.iter().position(|x| x == prog_2).unwrap();
programs.swap(pos_1, pos_2);
}
}
}
}
/// Generates the initial order of programs before executing any dance moves.
fn get_initial_programs() -> VecDeque<String> {
// Initialise the programs in the starting order
let programs = VecDeque::from(
"abcdefghijklmnop"
.chars()
.map(|x| x.to_string())
.collect::<Vec<String>>(),
);
return programs;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_d16_p1_proper() {
let input = generate_input(&std::fs::read_to_string("./input/2017/day16.txt").unwrap());
let result = solve_part_1(&input);
assert_eq!("pkgnhomelfdibjac", result);
}
#[test]
fn test_d16_p2_proper() {
let input = generate_input(&std::fs::read_to_string("./input/2017/day16.txt").unwrap());
let result = solve_part_2(&input);
assert_eq!("pogbjfihclkemadn", result);
}
}
| 36.47973 | 98 | 0.592702 |
19548c7c638d3b7707193f4452a24b14328a3608 | 8,842 | swift | Swift | Tests/iOS/Specs/CoreSpec.swift | davidvpe/halo-ios | b27e8be9a0d13b396575887061cb8c0fc38f8ffb | [
"Apache-2.0"
] | 1 | 2019-03-08T16:09:22.000Z | 2019-03-08T16:09:22.000Z | Tests/iOS/Specs/CoreSpec.swift | davidvpe/halo-ios | b27e8be9a0d13b396575887061cb8c0fc38f8ffb | [
"Apache-2.0"
] | 1 | 2017-11-20T08:47:25.000Z | 2017-11-20T08:47:25.000Z | Tests/iOS/Specs/CoreSpec.swift | davidvpe/halo-ios | b27e8be9a0d13b396575887061cb8c0fc38f8ffb | [
"Apache-2.0"
] | 6 | 2017-08-24T15:39:20.000Z | 2021-06-16T12:08:51.000Z | //
// HaloCoreTests.swift
// HaloCoreTests
//
// Created by Borja Santos-Díez on 17/06/15.
// Copyright (c) 2015 MOBGEN Technology. All rights reserved.
//
import Quick
import Nimble
import OHHTTPStubs
@testable import Halo
class CoreSpec: BaseSpec {
override func spec() {
let mgr = Halo.Manager.core
describe("The core manager") {
beforeEach {
mgr.appCredentials = Credentials(clientId: "halotestappclient", clientSecret: "halotestapppass")
mgr.logLevel = .info
}
context("when setting a .none defaultOfflinePolicy") {
beforeEach {
mgr.defaultOfflinePolicy = .none
}
it("set DataProviderManager.online as the dataProvider") {
expect(mgr.dataProvider).to(be(DataProviderManager.online))
}
}
context("when setting a .loadAndStoreLocalData defaultOfflinePolicy") {
beforeEach {
mgr.defaultOfflinePolicy = .loadAndStoreLocalData
}
afterEach {
mgr.defaultOfflinePolicy = .none
}
it("set DataProviderManager.onlineOffline as the dataProvider") {
expect(mgr.dataProvider).to(be(DataProviderManager.onlineOffline))
}
}
context("when setting a .returnLocalDataDontLoad defaultOfflinePolicy") {
beforeEach {
mgr.defaultOfflinePolicy = .returnLocalDataDontLoad
}
afterEach {
mgr.defaultOfflinePolicy = .none
}
it("set DataProviderManager.offline as the dataProvider") {
expect(mgr.dataProvider).to(be(DataProviderManager.offline))
}
}
context("when the startup process succeeds") {
beforeEach {
stub(condition: pathStartsWith("/api/segmentation/appuser")) { _ in
let filePath = OHPathForFile("segmentation_appuser_success.json", type(of: self))
return fixture(filePath: filePath!, status: 200, headers: ["Content-Type": "application/json"])
}.name = "Successful appuser stub"
waitUntil { done in
mgr.startup(UIApplication()) { success in
done()
}
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
Router.appToken = nil
Router.userToken = nil
}
it("has been initialised properly") {
expect(mgr).toNot(beNil())
}
it("starts properly") {
expect(mgr.device).toNot(beNil())
}
}
context("when the authentication returns a 401 error") {
beforeEach {
stub(condition: pathStartsWith("/api/oauth/token")) { _ in
let filePath = OHPathForFile("oauth_failure.json", type(of: self))
return fixture(filePath: filePath!, status: 401, headers: ["Content-Type": "application/json"])
}.name = "Failed oauth stub"
mgr.startup(UIApplication())
}
afterEach {
OHHTTPStubs.removeAllStubs()
Router.appToken = nil
Router.userToken = nil
}
it("returns an error") {
var res: Result<Token>?
waitUntil { done in
mgr.authenticate(authMode: .app) { (response, result) in
res = result
done()
}
}
expect(res).toNot(beNil())
switch res! {
case .success(_, _):
XCTFail("Expected Failure, got<\(String(describing: res))")
break
default:
break
}
}
}
context("when saving the user fails") {
beforeEach {
stub(condition: pathStartsWith("/api/segmentation/appuser")) { _ in
let filePath = OHPathForFile("segmentation_appuser_failure.json", type(of: self))
return fixture(filePath: filePath!, status: 400, headers: ["Content-Type": "application/json"])
}.name = "Failed appuser stub"
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("user has not changed") {
let oldDevice = mgr.device
waitUntil { done in
mgr.saveDevice { _ in
done()
}
}
expect(mgr.device).to(be(oldDevice))
}
}
}
describe("Framework version") {
it("is correct") {
expect(mgr.frameworkVersion).to(equal("2.2.0"))
}
}
describe("Registering an addon") {
var addon: HaloAddon?
beforeEach {
addon = DummyAddon()
mgr.registerAddon(addon: addon!)
}
it("succeeds") {
expect(mgr.addons.count).to(equal(1))
expect(mgr.addons.first).to(be(addon))
}
}
describe("The oauth process") {
beforeEach {
Halo.Router.appToken = nil
Halo.Router.userToken = nil
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
context("with the right credentials") {
beforeEach {
stub(condition: isPath("/api/oauth/token")) { _ in
let stubPath = OHPathForFile("oauth_success.json", type(of: self))
return fixture(filePath: stubPath!, status: 200, headers: ["Content-Type":"application/json"])
}.name = "Successful OAuth stub"
waitUntil { done in
Halo.Manager.network.authenticate(mode: .app) { _ in
done()
}
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("succeeds") {
expect(Halo.Router.appToken).toNot(beNil())
}
it("retrieves a valid token") {
expect(Halo.Router.appToken?.isValid()).to(beTrue())
expect(Halo.Router.appToken?.isExpired()).to(beFalse())
}
}
context("with the wrong credentials") {
beforeEach {
stub(condition: isPath("/api/oauth/token")) { _ in
let stubPath = OHPathForFile("oauth_failure.json", type(of: self))
return fixture(filePath: stubPath!, status: 401, headers: ["Content-Type":"application/json"])
}.name = "Failed OAuth stub"
waitUntil { done in
Halo.Manager.network.authenticate(mode: .app) { _ in
done()
}
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("fails") {
expect(Halo.Router.appToken).to(beNil())
}
}
}
}
}
| 35.227092 | 119 | 0.404999 |