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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f43c34207510abc0c3fa06ae73862d1080f2c4d3
| 1,551
|
ts
|
TypeScript
|
test/TestUnexposedProperties.ts
|
avivcarmis/smoke-screen-server
|
ded85510ca1c8c8b06f4060fb5f6a4da3f8192cc
|
[
"MIT"
] | null | null | null |
test/TestUnexposedProperties.ts
|
avivcarmis/smoke-screen-server
|
ded85510ca1c8c8b06f4060fb5f6a4da3f8192cc
|
[
"MIT"
] | null | null | null |
test/TestUnexposedProperties.ts
|
avivcarmis/smoke-screen-server
|
ded85510ca1c8c8b06f4060fb5f6a4da3f8192cc
|
[
"MIT"
] | null | null | null |
import "mocha";
import {expect} from "chai";
import {exposed} from "../src/Exposed";
import {SmokeScreen} from "../src/SmokeScreen";
describe("Test unexposed properties", () => {
class Test {
@exposed()
exposed: string;
unexposed: string;
}
const smokeScreen = new SmokeScreen();
it("Test toObject", () => {
const test = new Test();
test.exposed = "exposed";
test.unexposed = "unexposed";
const exposure = smokeScreen.toObject(test);
expect(exposure.exposed).to.equal("exposed");
expect(exposure).to.not.haveOwnProperty("unexposed");
});
it("Test fromObject", () => {
const exposure = {exposed: "exposed", unexposed: "unexposed"};
const test = smokeScreen.fromObject(exposure, Test);
expect(test.exposed).to.equal("exposed");
expect(test).to.not.haveOwnProperty("unexposed");
});
it("Test toJSON", () => {
const test = new Test();
test.exposed = "exposed";
test.unexposed = "unexposed";
const exposure = JSON.parse(smokeScreen.toJSON(test));
expect(exposure.exposed).to.equal("exposed");
expect(exposure).to.not.haveOwnProperty("unexposed");
});
it("Test fromJSON", () => {
const exposure = {exposed: "exposed", unexposed: "unexposed"};
const test = smokeScreen.fromJSON(JSON.stringify(exposure), Test);
expect(test.exposed).to.equal("exposed");
expect(test).to.not.haveOwnProperty("unexposed");
});
});
| 25.85
| 74
| 0.597034
|
664ffef782860b15cb2f82900081a3097e48b4db
| 7,546
|
py
|
Python
|
src/py42/clients/orgs.py
|
unparalleled-js/py42
|
8c6b054ddd8c2bfea92bf77b0d648af76f1efcf1
|
[
"MIT"
] | 1
|
2020-08-18T22:00:22.000Z
|
2020-08-18T22:00:22.000Z
|
src/py42/clients/orgs.py
|
unparalleled-js/py42
|
8c6b054ddd8c2bfea92bf77b0d648af76f1efcf1
|
[
"MIT"
] | null | null | null |
src/py42/clients/orgs.py
|
unparalleled-js/py42
|
8c6b054ddd8c2bfea92bf77b0d648af76f1efcf1
|
[
"MIT"
] | 1
|
2021-05-10T23:33:34.000Z
|
2021-05-10T23:33:34.000Z
|
import json
from py42 import settings
from py42.clients import BaseClient
from py42.clients.util import get_all_pages
class OrgClient(BaseClient):
"""A client for interacting with Code42 organization APIs.
Use the OrgClient to create and retrieve organizations. You can also use it to block and
deactivate organizations.
"""
def create_org(self, org_name, org_ext_ref=None, notes=None, parent_org_uid=None):
"""Creates a new organization.
`REST Documentation <https://console.us.code42.com/apidocviewer/#Org-post>`__
Args:
org_name (str): The name of the new organization.
org_ext_ref (str, optional): External reference information,
such as a serial number, asset tag, employee ID, or help desk issue ID. Defaults to
None.
notes (str, optional): Descriptive information about the organization. Defaults to None.
parent_org_uid (int, optional): The org UID for the parent organization. Defaults to
None.
Returns:
:class:`py42.response.Py42Response`
"""
uri = u"/api/Org/"
data = {
u"orgName": org_name,
u"orgExtRef": org_ext_ref,
u"notes": notes,
u"parentOrgUid": parent_org_uid,
}
return self._session.post(uri, data=json.dumps(data))
def get_by_id(self, org_id, **kwargs):
"""Gets the organization with the given ID.
`REST Documentation <https://console.us.code42.com/apidocviewer/#Org-get>`__
Args:
org_id (int): An ID for an organization.
Returns:
:class:`py42.response.Py42Response`: A response containing the organization.
"""
uri = u"/api/Org/{}".format(org_id)
return self._session.get(uri, params=kwargs)
def get_by_uid(self, org_uid, **kwargs):
"""Gets the organization with the given UID.
`REST Documentation <https://console.us.code42.com/apidocviewer/#Org-get>`__
Args:
org_uid (str): A UID for an organization.
Returns:
:class:`py42.response.Py42Response`: A response containing the organization.
"""
uri = u"/api/Org/{}".format(org_uid)
params = dict(idType=u"orgUid", **kwargs)
return self._session.get(uri, params=params)
def get_page(self, page_num, page_size=None, **kwargs):
"""Gets an individual page of organizations.
`REST Documentation <https://console.us.code42.com/apidocviewer/#Org-get>`__
Args:
page_num (int): The page number to request.
page_size (int, optional): The number of organizations to return per page.
Defaults to `py42.settings.items_per_page`.
kwargs (dict, optional): Additional advanced-user arguments. Defaults to None.
Returns:
:class:`py42.response.Py42Response`
"""
page_size = page_size or settings.items_per_page
uri = u"/api/Org"
params = dict(pgNum=page_num, pgSize=page_size, **kwargs)
return self._session.get(uri, params=params)
def get_all(self, **kwargs):
"""Gets all organizations.
`REST Documentation <https://console.us.code42.com/apidocviewer/#Org-get>`__
Returns:
generator: An object that iterates over :class:`py42.response.Py42Response` objects
that each contain a page of organizations.
"""
return get_all_pages(self.get_page, u"orgs", **kwargs)
def block(self, org_id):
"""Blocks the organization with the given org ID as well as its child organizations. A
blocked organization will not allow any of its users or devices to log in. New
registrations will be rejected and all currently logged in clients will be logged out.
Backups continue for any devices that are still active.
`Rest Documentation <https://console.us.code42.com/apidocviewer/#OrgBlock-put>`__
Args:
org_id (int): An ID for an organization.
Returns:
:class:`py42.response.Py42Response`
"""
uri = u"/api/OrgBlock/{}".format(org_id)
return self._session.put(uri)
def unblock(self, org_id):
"""Removes a block, if one exists, on an organization and its descendants with the given
ID. All users in the organization remain blocked until they are unblocked individually.
`REST Documentation <https://console.us.code42.com/apidocviewer/#OrgBlock-delete>`__
Args:
org_id (int): An ID for an organization.
Returns:
:class:`py42.response.Py42Response`
"""
uri = u"/api/OrgBlock/{}".format(org_id)
return self._session.delete(uri)
def deactivate(self, org_id):
"""Deactivates the organization with the given ID, including all users, plans, and
devices. Backups stop and archives move to cold storage.
`REST Documentation <https://console.us.code42.com/apidocviewer/#OrgDeactivation-put>`__
Args:
org_id (int): An ID for an organization.
Returns:
:class:`py42.response.Py42Response`
"""
uri = u"/api/OrgDeactivation/{}".format(org_id)
return self._session.put(uri)
def reactivate(self, org_id):
"""Reactivates the organization with the given ID. Backups are *not* restarted
automatically.
`REST Documentation <https://console.us.code42.com/apidocviewer/#OrgDeactivation-delete>`__
Args:
org_id (int): An ID for an organization.
Returns:
:class:`py42.response.Py42Response`
"""
uri = u"/api/OrgDeactivation/{}".format(org_id)
return self._session.delete(uri)
def get_current(self, **kwargs):
"""Gets the organization for the currently signed-in user.
`REST Documentation <https://console.us.code42.com/apidocviewer/#Org-get>`__
Returns:
:class:`py42.response.Py42Response`: A response containing the organization for the
currently signed-in user.
"""
uri = u"/api/Org/my"
return self._session.get(uri, params=kwargs)
def get_agent_state(self, orgId, property_name):
"""Gets the agent state of the devices in the org.
`REST Documentation <https://console.us.code42.com/swagger/index.html?urls.primaryName=v14#/agent-state/AgentState_ViewByDeviceGuid>`__
Args:
orgId (str): The org's identifier.
property_name (str): The name of the property to retrieve (e.g. `fullDiskAccess`).
Returns:
:class:`py42.response.Py42Response`: A response containing settings information.
"""
uri = u"/api/v14/agent-state/view-by-organization-id"
params = {u"orgId": orgId, u"propertyName": property_name}
return self._session.get(uri, params=params)
def get_agent_full_disk_access_states(self, guid):
"""Gets the full disk access status for devices in an org.
`REST Documentation <https://console.us.code42.com/swagger/index.html?urls.primaryName=v14#/agent-state/AgentState_ViewByDeviceGuid>`__
Args:
orgId (str): The org's identifier.
Returns:
:class:`py42.response.Py42Response`: A response containing settings information.
"""
return self.get_agent_state(guid, u"fullDiskAccess")
| 39.715789
| 147
| 0.633978
|
158faadbb61117a734fb6c683f3f0d85e5596c7b
| 834
|
rb
|
Ruby
|
spec/statsdserver/math_spec.rb
|
fetep/ruby-statsdserver
|
820534229a009ee9caf5c014e8da209061bbbef4
|
[
"Apache-2.0"
] | 6
|
2015-10-12T12:03:48.000Z
|
2021-11-30T03:28:45.000Z
|
spec/statsdserver/math_spec.rb
|
fetep/ruby-statsdserver
|
820534229a009ee9caf5c014e8da209061bbbef4
|
[
"Apache-2.0"
] | 1
|
2021-07-09T00:13:18.000Z
|
2021-07-09T00:13:18.000Z
|
spec/statsdserver/math_spec.rb
|
fetep/ruby-statsdserver
|
820534229a009ee9caf5c014e8da209061bbbef4
|
[
"Apache-2.0"
] | 1
|
2016-05-02T22:00:04.000Z
|
2016-05-02T22:00:04.000Z
|
require "rubygems"
require "bundler/setup"
require "rspec/autorun"
require "spec_helper"
require "statsdserver/math"
describe StatsdServer::Math do
describe ".summarize" do
it "should calculate min" do
values = [ 1, 5, 0 ]
res = StatsdServer::Math.summarize(values)
res[:min].should eq(0)
end
it "should calculate max" do
values = [ 1, 5, 0 ]
res = StatsdServer::Math.summarize(values)
res[:max].should eq(5)
end
it "should calculate mean" do
values = [ 1, 5, 0 ]
res = StatsdServer::Math.summarize(values)
res[:mean].should eq(2)
end
it "should calculate 90th percentile by default" do
values = [ 2, 10, 7, 4, 1, 3, 9, 4, 5, 6 ]
res = StatsdServer::Math.summarize(values)
res[:max_at_threshold].should eq(9)
end
end
end
| 23.828571
| 55
| 0.623501
|
478521842affde7f4fc3f4fe677a14769827f1f6
| 9,374
|
rb
|
Ruby
|
spec/atlas/edge_spec.rb
|
quintel/atlas
|
517fbd2736034fd442bf41c24d21b2a2a8015807
|
[
"MIT"
] | 2
|
2017-03-21T15:57:02.000Z
|
2017-12-20T15:22:11.000Z
|
spec/atlas/edge_spec.rb
|
quintel/atlas
|
517fbd2736034fd442bf41c24d21b2a2a8015807
|
[
"MIT"
] | 100
|
2015-01-08T15:49:41.000Z
|
2021-05-21T07:26:06.000Z
|
spec/atlas/edge_spec.rb
|
quintel/atlas
|
517fbd2736034fd442bf41c24d21b2a2a8015807
|
[
"MIT"
] | 2
|
2016-01-21T06:10:10.000Z
|
2020-10-16T23:37:58.000Z
|
require 'spec_helper'
module Atlas
describe Edge do
let(:node_class) do
Class.new do
include Atlas::Node
def self.name
'TestNode'
end
end
end
let(:klass) do
Class.new do
include Atlas::Edge
def self.graph_config
GraphConfig::Config.new(:test, self, TestNode)
end
def self.name
'TestEdge'
end
end
end
before { stub_const('TestNode', node_class) }
it 'must have a consumer' do
expect(klass.new(key: 'a-b@gas').errors_on(:consumer)).to include('does not exist')
end
it 'must have a supplier' do
expect(klass.new(key: 'a-b@gas').errors_on(:supplier)).to include('does not exist')
end
describe 'type' do
valid_types = [ :share, :flexible, :constant,
:inversed_flexible, :dependent ]
valid_types.each do |type|
it "is permitted to be #{ type.inspect }" do
edge = klass.new(key: 'a-b@gas', type: type)
expect(edge.errors_on(:type).length).to eq(0)
end
end
it 'may not be blank' do
edge = klass.new(key: 'a-b@gas', type: nil)
expect(edge.errors_on(:type).length).to eq(1)
end
it 'may not be any other value' do
edge = klass.new(key: 'a-b@gas', type: :nope)
expect(edge.errors_on(:type).length).to eq(1)
end
end
describe 'when creating a new Edge' do
let(:edge) { klass.new(path: 'left-right@gas.ad') }
it 'sets the consumer from the filename' do
expect(edge.consumer).to eq(:right)
end
it 'sets the supplier from the filename' do
expect(edge.supplier).to eq(:left)
end
it 'sets the carrier from the filename' do
expect(edge.carrier).to eq(:gas)
end
it 'sets the edge key' do
expect(edge.key).to eq(:'left-right@gas')
end
it 'sets the filename' do
expect(edge.path.to_s).to match(%r{left-right@gas\.ad$})
end
end
context 'creating an edge with supplier, consumer, and carrier' do
let(:edge) do
klass.new(supplier: 'here', consumer: 'there',
carrier: 'talk', ns: 'listen')
end
it 'sets the supplier' do
expect(edge.supplier).to eq(:here)
end
it 'sets the consumer' do
expect(edge.consumer).to eq(:there)
end
it 'sets the carrier' do
expect(edge.carrier).to eq(:talk)
end
it 'sets the key' do
expect(edge.key).to eq(:'here-there@talk')
end
it 'sets the path' do
expect(edge.path.to_s).to match(%r{/listen/here-there@talk\.ad$})
end
end
context 'validation of associated documents' do
it 'has an error when the carrier does not exist' do
edge = klass.new(key: 'a-b@nope').tap(&:valid?)
expect(edge.errors[:carrier]).to include('does not exist')
end
it 'has an error when the supplier does not exist' do
edge = klass.new(key: 'a-b@nope').tap(&:valid?)
expect(edge.errors[:supplier]).to include('does not exist')
end
it 'has an error when the consumer does not exist' do
edge = klass.new(key: 'a-b@nope').tap(&:valid?)
expect(edge.errors[:consumer]).to include('does not exist')
end
end
describe 'creating an Edge with an invalid key' do
it 'does not raise an error when the key is nil' do
expect { klass.new(key: nil) }.not_to raise_error
end
it 'raises an error when the key is blank' do
expect { klass.new(key: '') }.to raise_error(InvalidKeyError)
end
it 'raises an error when the key has only one edge' do
expect { klass.new(key: 'left@gas') }.to raise_error(InvalidKeyError)
end
it 'raises an error when one edge key is blank' do
expect { klass.new(key: 'left-@gas') }.to raise_error(InvalidKeyError)
end
it 'raises an error when omitting the carrier' do
expect { klass.new(key: 'one-two') }.to raise_error(InvalidKeyError)
end
it 'raises an error when providing only the carrier' do
expect { klass.new(key: '@gas') }.to raise_error(InvalidKeyError)
end
end
describe 'changing the key on an Edge' do
let(:edge) { klass.new(key: 'left-right@gas') }
context 'changing the supplier node only' do
before { edge.key = 'left-other@gas' }
it { expect(edge.key).to eq(:'left-other@gas') }
it { expect(edge.supplier).to eq(:left) }
it { expect(edge.consumer).to eq(:other) }
it { expect(edge.carrier).to eq(:gas) }
it { expect(edge.path.to_s).
to match(%{left-other@gas\.ad$}) }
end
context 'changing the consumer node only' do
before { edge.key = 'other-right@gas' }
it { expect(edge.key).to eq(:'other-right@gas') }
it { expect(edge.supplier).to eq(:other) }
it { expect(edge.consumer).to eq(:right) }
it { expect(edge.path.to_s).to match(%{other-right@gas\.ad$}) }
end
context 'changing the carrier only' do
before { edge.key = 'left-right@electricity' }
it { expect(edge.key).to eq(:'left-right@electricity') }
it { expect(edge.supplier).to eq(:left) }
it { expect(edge.consumer).to eq(:right) }
it { expect(edge.carrier).to eq(:electricity) }
it { expect(edge.path.to_s).
to match(%{left-right@electricity\.ad$}) }
end
context 'changing both nodes with a string' do
before { edge.key = 'one-two@electricity' }
it { expect(edge.key).to eq(:'one-two@electricity') }
it { expect(edge.supplier).to eq(:one) }
it { expect(edge.consumer).to eq(:two) }
it { expect(edge.carrier).to eq(:electricity) }
it { expect(edge.path.to_s).
to match(%{one-two@electricity\.ad$}) }
end
context 'changing both nodes using a symbol' do
before { edge.key = :'one-two@gas' }
it { expect(edge.key).to eq(:'one-two@gas') }
it { expect(edge.supplier).to eq(:one) }
it { expect(edge.consumer).to eq(:two) }
it { expect(edge.carrier).to eq(:gas) }
it { expect(edge.path.to_s).to match(%{one-two@gas\.ad$}) }
end
context 'changing one of the key components' do
before { edge.supplier = :nine }
it { expect(edge.key).to eq(:'nine-right@gas') }
it { expect(edge.supplier).to eq(:nine) }
it { expect(edge.path.to_s).to match(%{nine-right@gas\.ad$}) }
end
it 'raises an error when omitting the supplier key' do
expect { edge.key = 'left-@gas' }.to raise_error(InvalidKeyError)
end
it 'raises an error when omitting the producer key' do
expect { edge.key = '-right@gas' }.to raise_error(InvalidKeyError)
end
it 'raises an error when providing only one node key' do
expect { edge.key = 'one@gas' }.to raise_error(InvalidKeyError)
end
it 'raises an error when omitting the carrier' do
expect { edge.key = 'one-two' }.to raise_error(InvalidKeyError)
end
it 'raises an error when providing only the carrier' do
expect { edge.key = '@gas' }.to raise_error(InvalidKeyError)
end
it 'raises an error if the key is blank' do
expect { edge.key = '' }.to raise_error(InvalidKeyError)
end
it 'raises an error if the key is nil' do
expect { edge.key = nil }.to raise_error(InvalidKeyError)
end
end
describe 'changing the filename' do
let(:edge) { klass.new(key: 'left-right@gas') }
before { edge.path = 'no-yes@electricity.ad' }
it 'updates the file path' do
expect(edge.path.to_s).to match(/no-yes@electricity\.ad$/)
end
it 'updates the supplier node' do
expect(edge.supplier).to eq(:no)
end
it 'updates the consumer node' do
expect(edge.consumer).to eq(:yes)
end
it 'updates the carrier' do
expect(edge.carrier).to eq(:electricity)
end
it 'updates the key' do
expect(edge.key).to eq(:'no-yes@electricity')
end
end
describe 'parsing an AD file' do
before do
FileUtils.mkdir_p(klass.directory)
File.write(klass.directory.join('a-b@c.ad'), content)
end
let(:content) do
<<~DOC
- type = share
- parent_share = 0.5
DOC
end
let(:edge) { klass.find('a-b@c') }
it 'sets the supplier' do
expect(edge.supplier).to eq(:a)
end
it 'sets the consumer' do
expect(edge.consumer).to eq(:b)
end
it 'sets the carrier' do
expect(edge.carrier).to eq(:c)
end
it 'sets the type' do
expect(edge.type).to eq(:share)
end
it 'sets attributes' do
expect(edge.parent_share).to eq(0.5)
end
context 'when a query is present' do
let(:content) do
<<~DOC
- type = share
~ parent_share = SHARE(cars, gasoline)
DOC
end
it 'sets the query when one is present' do
expect(klass.find('a-b@c').queries[:parent_share]).to eq('SHARE(cars, gasoline)')
end
end
end
end
end
| 29.021672
| 91
| 0.579475
|
57f245230dbccf7f7642bc6db7a943e3fa48814c
| 2,093
|
swift
|
Swift
|
UserDefaultDemo/RUserDefault.swift
|
chaopengCoder/UserDefaultDemo
|
be539c33e96bb259821b041ff0ca536701406f7e
|
[
"MIT"
] | null | null | null |
UserDefaultDemo/RUserDefault.swift
|
chaopengCoder/UserDefaultDemo
|
be539c33e96bb259821b041ff0ca536701406f7e
|
[
"MIT"
] | null | null | null |
UserDefaultDemo/RUserDefault.swift
|
chaopengCoder/UserDefaultDemo
|
be539c33e96bb259821b041ff0ca536701406f7e
|
[
"MIT"
] | null | null | null |
//
// RUserDefault.swift
// UserDefaultDemo
//
// Created by JingZhao_R on 2019/9/26.
// Copyright © 2019 JingZhao_R. All rights reserved.
//
import Foundation
/// 注意所有的属性需要 用@objc 标记
class RUserDefault: NSObject {
static let shared = RUserDefault()
/// 登录用户名, 退出登录或者token失效可以选择不清除
@objc var userName: String {
get {
return UserDefaults.standard.string(forKey: "userName") ?? ""
}
set {
UserDefaults.standard.set(newValue, forKey: "userName")
}
}
/// 登录状态
@objc var isLogin: Bool {
get {
return UserDefaults.standard.bool(forKey: "isLogin")
}
set {
UserDefaults.standard.set(newValue, forKey: "isLogin")
}
}
/// 用户基本信息
@objc var userBaseInfo: [String: Any] {
get {
return UserDefaults.standard.dictionary(forKey: "userBaseInfo") ?? [:]
}
set {
UserDefaults.standard.set(newValue, forKey: "userBaseInfo")
}
}
/// 清空用户
public func removeUser() {
let prppertys = getPropertieNames(cls: RUserDefault.self)
for property in prppertys {
/// 不需要清除的在这里判断一下
if property == "userName" {
} else {
/// 清空UserDefaultsz中对应的object
UserDefaults.standard.removeObject(forKey: property)
}
}
}
/// 获取属性列表
///
/// - Returns: [属性字符串列表]
fileprivate func getPropertieNames(cls: AnyClass) -> [String] {
var propertys:[String] = []
var outCount:UInt32 = 0
guard let peopers = class_copyPropertyList(cls, &outCount) else { return [] }
let count:Int = Int(outCount);
for i in 0...(count-1) {
let aPro: objc_property_t = peopers[i]
let proName = String(cString: property_getName(aPro))
propertys.append(proName)
}
return propertys
}
}
| 24.337209
| 85
| 0.522217
|
248472d94f5dfe0244edf2b12c3aa740b7125bea
| 2,589
|
php
|
PHP
|
App/Controllers/Movies.php
|
dbond762/movies_from_scratch
|
6663a85a59bbda2570cddee5390dd0cf8a95da24
|
[
"MIT"
] | null | null | null |
App/Controllers/Movies.php
|
dbond762/movies_from_scratch
|
6663a85a59bbda2570cddee5390dd0cf8a95da24
|
[
"MIT"
] | null | null | null |
App/Controllers/Movies.php
|
dbond762/movies_from_scratch
|
6663a85a59bbda2570cddee5390dd0cf8a95da24
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Controllers;
use Lib\Response\Response;
use App\Models\Movies as MoviesModel;
use Lib\Router\Router;
class Movies {
/**
* @var MoviesModel
*/
private $movies_model;
public function __construct() {
$this->movies_model = new MoviesModel();
}
public function movies_list($ctx) {
$data['movies'] = $this->movies_model->get_movies_list();
Response::view('movies/list', $data);
}
public function add_view($ctx) {
Response::view('movies/add');
}
public function add($ctx) {
$name = htmlentities($_POST['name']);
$year = htmlentities($_POST['year']);
$format = htmlentities($_POST['format']);
$this->movies_model->add($name, $year, $format);
Response::redirect('/movies/list');
}
public function delete($ctx) {
$id = htmlentities($ctx['params']['id']);
$this->movies_model->delete($id);
Response::redirect('/movies/list');
}
public function detail($ctx) {
$id = htmlentities($ctx['params']['id']);
$data['movie'] = $this->movies_model->get($id);
Response::view('movies/detail', $data);
}
public function search($ctx) {
$query = htmlentities($_GET['q']);
$data['search_query'] = $query;
$data['movies'] = $this->movies_model->search($query);
Response::view('movies/list', $data);
}
public function import($ctx) {
$file = $_FILES['file'];
if ($file['type'] !== 'text/plain') {
Response::redirect('/movies/list');
}
$get_value = function ($val) {
return trim(explode(':', htmlentities($val))[1]);
};
$fd = fopen($file['tmp_name'], 'r') or die("не удалось открыть файл");
while (!feof($fd)) {
$title = $get_value(fgets($fd));
$year = $get_value(fgets($fd));
$format = $get_value(fgets($fd));
$actors = explode(',', $get_value(fgets($fd)));
$actors = array_map('trim', $actors);
$movie_id = $this->movies_model->add($title, $year, $format);
foreach ($actors as $actor) {
$actor_names = explode(' ', $actor);
$actor_id = $this->movies_model->add_actor($actor_names[0], $actor_names[1]);
$this->movies_model->add_actor_to_movie($movie_id, $actor_id);
}
if (!feof($fd)) {
fgets($fd);
}
}
fclose($fd);
Response::redirect('/movies/list');
}
}
| 29.420455
| 93
| 0.531866
|
ac8cc822dba1ef6c7551af7bf5f953f7421aba04
| 2,165
|
asm
|
Assembly
|
programs/oeis/013/A013959.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 22
|
2018-02-06T19:19:31.000Z
|
2022-01-17T21:53:31.000Z
|
programs/oeis/013/A013959.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 41
|
2021-02-22T19:00:34.000Z
|
2021-08-28T10:47:47.000Z
|
programs/oeis/013/A013959.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 5
|
2021-02-24T21:14:16.000Z
|
2021-08-09T19:48:05.000Z
|
; A013959: a(n) = sigma_11(n), the sum of the 11th powers of the divisors of n.
; 1,2049,177148,4196353,48828126,362976252,1977326744,8594130945,31381236757,100048830174,285311670612,743375541244,1792160394038,4051542498456,8649804864648,17600780175361,34271896307634,64300154115093,116490258898220,204900053024478,350279478046112,584603613083988,952809757913928,1522433108644860,2384185839843751,3672136647383862,5559091947792280,8297561014164632,12200509765705830,17723450167663752,25408476896404832,36046397799139329,50542391825574576,70223115534342066,96549159399201744,131686747008947221,177917621779460414,238688540482452780,317477629483043624,419635308642959070,550329031716248442,717722650516483488,929293739471222708,1197268484907678036,1532286982406627382,1952307193965638472,2472159215084012304,3117943006504850428,3909821050560314793,4885196785839845799,6071197887104747832,7520537646002543414,9269035929372191598,11390579401026381720,13931234201913233112,16993404958986493080,20636016383301876560,24998844509931245670,30155888444737842660,36297634593180228744,43513917611435838662,52061969160733500768,62050958699411929208,73823022692637345793,87507833532297112788,103561360850602306224,122130132904968017084,143816974886228858802,168788342994936517344,197829227608964373456,231122292121701565272,269694457905705145365,313726685568359708378,364553207026114388286,422353753156640802148,488834247398322191660,564154396676426447328,650511662810756385576,747993810527520928880,859413112100829003486,984776461275559025161,1127624185986593057658,1287831418538085836268,1469896338537236229536,1673432471168087713884,1904122872176535328692,2161295903975256372840,2452005857376236288340,2775173073766990340490,3139656026951179505718,3543686676668915552272,3998326086051385504584,4501060865244323179136,5065454231707141210896,5688001039254907335720,6385547277321933853692,7153014030880804126754,8011223332598085010857,8953433085010371085284,10004885401585844040103
add $0,1
mov $2,$0
mov $3,8
lpb $0
pow $3,11
add $1,$3
mov $3,$2
mov $4,$0
cmp $4,0
add $0,$4
dif $3,$0
cmp $3,$2
cmp $3,0
mul $3,$0
sub $0,1
lpe
sub $1,8589934591
mov $0,$1
| 98.409091
| 1,887
| 0.89515
|
cd4b3b5366818ae63875a5824168a184c0301f93
| 3,511
|
cs
|
C#
|
Proyecto Final/Morelac/Proyecto_Web/Vistas/Private/Pruebas/Composicion.aspx.designer.cs
|
CarlosOrtiz/Caliada-Leche
|
44335476d07dc8b67f0db8c293705969821b4eec
|
[
"MIT"
] | null | null | null |
Proyecto Final/Morelac/Proyecto_Web/Vistas/Private/Pruebas/Composicion.aspx.designer.cs
|
CarlosOrtiz/Caliada-Leche
|
44335476d07dc8b67f0db8c293705969821b4eec
|
[
"MIT"
] | null | null | null |
Proyecto Final/Morelac/Proyecto_Web/Vistas/Private/Pruebas/Composicion.aspx.designer.cs
|
CarlosOrtiz/Caliada-Leche
|
44335476d07dc8b67f0db8c293705969821b4eec
|
[
"MIT"
] | null | null | null |
//------------------------------------------------------------------------------
// <generado automáticamente>
// Este código fue generado por una herramienta.
//
// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
// se vuelve a generar el código.
// </generado automáticamente>
//------------------------------------------------------------------------------
namespace Proyecto_Web.Vistas.Private.Pruebas {
public partial class Composicion {
/// <summary>
/// Control TB_Cantidad.
/// </summary>
/// <remarks>
/// Campo generado automáticamente.
/// Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox TB_Cantidad;
/// <summary>
/// Control TB_Grasa.
/// </summary>
/// <remarks>
/// Campo generado automáticamente.
/// Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox TB_Grasa;
/// <summary>
/// Control Drop_Vitaminas.
/// </summary>
/// <remarks>
/// Campo generado automáticamente.
/// Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList Drop_Vitaminas;
/// <summary>
/// Control Drop_Mineerales.
/// </summary>
/// <remarks>
/// Campo generado automáticamente.
/// Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList Drop_Mineerales;
/// <summary>
/// Control Fecha_Prueba.
/// </summary>
/// <remarks>
/// Campo generado automáticamente.
/// Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Fecha_Prueba;
/// <summary>
/// Control TB_Observacion.
/// </summary>
/// <remarks>
/// Campo generado automáticamente.
/// Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox TB_Observacion;
/// <summary>
/// Control Btn_Save_Prueba.
/// </summary>
/// <remarks>
/// Campo generado automáticamente.
/// Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton Btn_Save_Prueba;
/// <summary>
/// Control Btn_Cerrar.
/// </summary>
/// <remarks>
/// Campo generado automáticamente.
/// Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton Btn_Cerrar;
}
}
| 39.897727
| 119
| 0.581886
|
8ca51996ac34aa5a2bd131d85bef85e23b1c61c0
| 753
|
go
|
Go
|
src/common/logger/logger.go
|
Asymmetric-Effort/asymmetric-toolkit
|
64dab0a64b274ade31f14e1d8c0be0a58b33726c
|
[
"MIT"
] | 1
|
2021-01-28T19:44:02.000Z
|
2021-01-28T19:44:02.000Z
|
src/common/logger/logger.go
|
Asymmetric-Effort/asymmetric-toolkit
|
64dab0a64b274ade31f14e1d8c0be0a58b33726c
|
[
"MIT"
] | null | null | null |
src/common/logger/logger.go
|
Asymmetric-Effort/asymmetric-toolkit
|
64dab0a64b274ade31f14e1d8c0be0a58b33726c
|
[
"MIT"
] | 1
|
2021-01-30T02:42:09.000Z
|
2021-01-30T02:42:09.000Z
|
package logger
/*
Logger is a struct at the highest level of the log management facilities.
This structure contains the configured state of the application for logging, as
established by the Logger::Setup() method.
*/
const (
maxLogMessageStringLength = 512
)
type Logger struct {
Level Level // The current Log level (Critical, Error, Warning, Info, Debug) as a numeric value.
Destination Destination // The numeric identifier of the log target (protocol) where logs will ship.
Settings *LogSettings // arbitrary log settings map pointer when a logging subsystem requires more parameters.
Writer func(*string) // Payload log writer function (configured as per Destination.
// Private properties
tags TagTracker
}
| 34.227273
| 115
| 0.749004
|
405a99826c56108709138db7072b58b3d2538898
| 985
|
ts
|
TypeScript
|
src/api/index.ts
|
John2509/IoTCoffeePotAPI
|
641c4af93debabbffb5b8b83a436c1b1af71aa64
|
[
"MIT"
] | null | null | null |
src/api/index.ts
|
John2509/IoTCoffeePotAPI
|
641c4af93debabbffb5b8b83a436c1b1af71aa64
|
[
"MIT"
] | null | null | null |
src/api/index.ts
|
John2509/IoTCoffeePotAPI
|
641c4af93debabbffb5b8b83a436c1b1af71aa64
|
[
"MIT"
] | null | null | null |
import { AppController, IAppRequest } from "../controller";
const Routes = (app: any) => {
app.get("/waterLevel", (req: { query: IAppRequest }, res: any) => {
console.log("Check Water Level: ", req.query);
if (req && req.query && req.query.coffeeMaker_ID) {
AppController.checkWaterLevel(req.query, (msg: string) => res.json({msg}));
} else {
res.sendStatus(400);
}
});
app.get("/coffee", (req: { query: IAppRequest }, res: any) => {
console.log("Make Coffee: ", req.query);
if (req && req.query && req.query.coffeeMaker_ID) {
AppController.makeCoffee(req.query, (msg: string) => res.json({msg}));
} else {
res.sendStatus(400);
}
});
app.get("/filter", (req: { query: IAppRequest }, res: any) => {
console.log("Clean Filter: ", req.query);
if (req && req.query && req.query.coffeeMaker_ID) {
AppController.cleanFilter(req.query, (msg: string) => res.json({msg}));
} else {
res.sendStatus(400);
}
});
};
export { Routes as routes };
| 28.970588
| 78
| 0.616244
|
da4dd97d8605b7f6fd366ff990f41a9de4fe2fc7
| 2,899
|
ts
|
TypeScript
|
projects/ids-enterprise-ng/src/lib/breadcrumb/soho-breadcrumb.spec.ts
|
crlang44/enterprise-ng
|
5dd1ed2cca4e4b45f918f23d1351bf14e8fd8fff
|
[
"Apache-2.0"
] | null | null | null |
projects/ids-enterprise-ng/src/lib/breadcrumb/soho-breadcrumb.spec.ts
|
crlang44/enterprise-ng
|
5dd1ed2cca4e4b45f918f23d1351bf14e8fd8fff
|
[
"Apache-2.0"
] | null | null | null |
projects/ids-enterprise-ng/src/lib/breadcrumb/soho-breadcrumb.spec.ts
|
crlang44/enterprise-ng
|
5dd1ed2cca4e4b45f918f23d1351bf14e8fd8fff
|
[
"Apache-2.0"
] | null | null | null |
/// <reference path="soho-breadcrumb.d.ts" />
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Component, DebugElement, EventEmitter, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SohoBreadcrumbModule } from './soho-breadcrumb.module';
import { SohoBreadcrumbComponent } from './soho-breadcrumb.component';
import { TestHelper } from '../utils';
const STANDARD_DATA = [
{
content: 'Home',
id: 'test-breadcrumb-home',
href: '#'
},
{
content: 'Second Item',
id: 'test-breadcrumb-second',
href: '#'
},
{
content: 'Third Item',
id: 'test-breadcrumb-third',
href: '#'
},
{
content: 'Fourth Item',
current: true,
id: 'test-breadcrumb-fourth',
href: '#'
}
];
@Component({
template: `
<div class="row">
<div class="twelve columns">
<nav soho-breadcrumb class="breadcrumb"></nav>
</div>
</div>`
})
class SohoBreadcrumbTestComponent {
@ViewChild(SohoBreadcrumbComponent, { static: true }) breadcrumb: SohoBreadcrumbComponent;
constructor() {}
}
describe('Soho Breadcrumb Unit Tests', () => {
let breadcrumb: SohoBreadcrumbComponent;
let component: SohoBreadcrumbTestComponent;
let fixture: ComponentFixture<SohoBreadcrumbTestComponent>;
let de: DebugElement;
let el: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SohoBreadcrumbTestComponent],
imports: [SohoBreadcrumbModule]
});
fixture = TestBed.createComponent(SohoBreadcrumbTestComponent);
component = fixture.componentInstance;
breadcrumb = component.breadcrumb;
de = fixture.debugElement;
el = de.nativeElement;
// Set the breadcrumbs via the input
breadcrumb.breadcrumbs = STANDARD_DATA;
fixture.detectChanges();
});
it('is created', () => {
expect(component).toBeTruthy();
expect(breadcrumb.breadcrumbs).toBeDefined();
expect(breadcrumb.breadcrumbs.length).toEqual(4);
});
it('can add breadcrumbs', () => {
breadcrumb.add({
id: 'fifth-item',
content: 'Fifth Item',
href: '#'
});
const fifth = breadcrumb.breadcrumbAPIs[4];
expect(breadcrumb.breadcrumbAPIs.length).toEqual(5);
expect(fifth.settings.id).toEqual('fifth-item');
});
it('can remove a breadcrumb using its Index', () => {
breadcrumb.remove(0, true);
expect(breadcrumb.breadcrumbAPIs.length).toEqual(3);
expect(breadcrumb.breadcrumbAPIs[0].settings.content).toEqual('Second Item');
});
it('can remove a breadcrumb uisng its IDS Breadcrumb API', () => {
const api1 = breadcrumb.getBreadcrumbItem(0).api;
breadcrumb.remove(api1, true);
expect(breadcrumb.breadcrumbAPIs.length).toEqual(3);
expect(breadcrumb.breadcrumbAPIs[0].settings.content).toEqual('Second Item');
});
});
| 27.349057
| 92
| 0.672646
|
e77c8c3f5a08b7ef2962a40021d9b2f62580a930
| 18,291
|
php
|
PHP
|
resources/views/product/product.blade.php
|
usman-tech147/laravel_jwt
|
ba402bb1efd0e5c1488581b4455cd8c5e3f10d0d
|
[
"MIT"
] | null | null | null |
resources/views/product/product.blade.php
|
usman-tech147/laravel_jwt
|
ba402bb1efd0e5c1488581b4455cd8c5e3f10d0d
|
[
"MIT"
] | null | null | null |
resources/views/product/product.blade.php
|
usman-tech147/laravel_jwt
|
ba402bb1efd0e5c1488581b4455cd8c5e3f10d0d
|
[
"MIT"
] | null | null | null |
@extends('index')
@section('css')
<style>
label {
font-weight: bolder;
}
legend {
font-weight: bolder;
}
</style>
@endsection
@section('content')
<div class="container-fluid mt-3">
{{--<form id="{{isset($product) ? "updateProduct" : "createProduct"}}"--}}
<form method="post" action="{{!isset($product) ? route('store') : route('edit',[$product[0]->id])}}"
enctype="multipart/form-data">
@csrf
<div class="row">
<div class="col-md-9">
@if(Session::has('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Success!</strong> {{Session::get('success')}}
</div>
@endif
<div class="form-row">
<div class="col-md-4 mb-3">
<input type="hidden" name="product_id"
value="{{isset($product[0]->id) ? $product[0]->id : "" }}">
<label for="category">Category</label>
<select id="category" class="form-control" onchange="getSubcategories(this.value)"
name="category">
<option selected>Select Category</option>
@foreach($categories as $category)
<option {{(isset($product[0]->subcategory) &&
$product[0]->subcategory->category->id == $category->id)
? 'selected' : '' }}
value={{$category->id}}
{{old('category') == $category->id ? 'selected':""}}>
{{$category->name}}
</option>
@endforeach
</select>
</div>
<div class="col-md-4 mb-3">
<label for="subcategory">Subcategory</label>
<select id="subcategory" class="form-control" name="subcategory">
{{--old not working for dynamically create dropdown--}}
<option value="{{isset($product[0]->subcategory) ?
$product[0]->subcategory->id: old('subcategory') }}">
{{isset($product[0]->subcategory) ?
$product[0]->subcategory->name: 'Select Subcategory'}}
</option>
</select>
</div>
<div class="col-md-4 mb-3">
<label for="pro_name">Product Name</label>
<input type="text" class="form-control" id="pro_name" placeholder="Product Name"
value="{{isset($product[0]->name) ? $product[0]->name : old('pro_name')}}"
name="pro_name">
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="sale_date_before">Sale Date Before</label>
<input type="date" class="form-control" id="sale_date_before"
value="{{isset($product[0]->sale_date_before) ?
$product[0]->sale_date_before : old('sale_date_before')}}" name="sale_date_before">
</div>
<div class="col-md-4 mb-3">
<label for="pro_price">Product Price</label>
<input type="range" min=100 max=1000 step="10" class="custom-range" id="pro_price"
value="{{isset($product[0]->price) ? $product[0]->price : ""}}">
</div>
<div class="col-md-4 mt-4">
<input type="text" id="showPrice" name="pro_price"
value="{{isset($product[0]->price) ? $product[0]->price : old('pro_price')}}"
readonly class="form-control">
</div>
</div>
<div class="form-row">
<div class="col-md-6">
<label for="pro_description">Product Description</label>
<textarea class="form-control" id="pro_description" rows="3" name="pro_description"
style="resize: none;">
{{isset($product[0]->description) ? $product[0]->description : old('pro_description')}}
</textarea>
</div>
<div class="col-md-4 mb-3">
<label for="File1">Choose File 1</label>
<input type="file" class="form-control-file"
onchange="previewImage(this)"
name="pro_image"
id="File1">
</div>
<div class="col-md-2 mb-3">
<img src="{{isset($product[0]->image) ?
asset('/images/'.$product[0]->image) : asset('/images/nophoto.png')}}"
id="imagePreview" alt="Product Image"
height="80px" width="100px">
</div>
</div>
<div class="form-row mt-2">
<div class="col-md-6 mb-3">
<fieldset class="form-group row">
<legend class="col-form-label col-md-4 float-md-left pt-0">Product Colors</legend>
<div class="col-md-8" id="pro_colors">
<div class="row">
@foreach($colors as $colorChuncks)
<div class="col-md-4">
@foreach($colorChuncks as $color)
<div class="form-check">
<input class="form-check-input enable-color-quantity"
type="checkbox" name="colors[]"
{{isset($product[0]->colors) &&
$product[0]->colors->contains($color->id)
? 'checked' : ''}}
{{!isset($product[0]->colors) ?
(is_array(old('colors')) &&
in_array($color->id, old('colors')) ? 'checked' : '')
: '' }}
value="{{$color->id}}">
<span class="form-check-label">
{{$color->name}}
</span>
<input id="qty-{{$color->id}}"
type="text" name="color-quantity-[{{$color->id}}]"
class="form-control color-quantity"
disabled
style="height: 25px">
</div>
@endforeach
</div>
@endforeach
</div>
</div>
</fieldset>
</div>
<div class="col-md-6 mb-3">
<fieldset class="form-group row">
<legend class="col-form-label col-sm-4 float-sm-left pt-0">Product Sizes</legend>
<div class="col-sm-8">
@foreach($sizes as $size)
<div class="form-check">
<input class="form-check-input" type="checkbox" name="sizes[]"
id="{{$size->id}}"
@if(isset($product[0]->sizes) &&
$product[0]->sizes->contains($size->id))
checked
@elseif(!isset($product[0]->sizes) &&
is_array(old('sizes')) && in_array($size->id, old('sizes')))
checked
@endif
value="{{$size->id}}">
<span class="form-check-label" for="small">
{{$size->name}}
</span>
</div>
@endforeach
</div>
</fieldset>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<fieldset class="form-group row">
<legend class="col-form-label col-sm-4 float-sm-left pt-0">Product Quality</legend>
<div class="col-sm-8">
@foreach($qualities as $quality)
<div class="form-check">
<input class="form-check-input" type="radio" name="pro_quality"
id="{{$quality->id}}"
@if(isset($product[0]->quality) &&
$product[0]->quality->id == $quality->id)
checked
@elseif(!isset($product[0]->quality) &&
(old('pro_quality') == $quality->id))
checked
@endif
value="{{$quality->id}}">
<span class="form-check-label" for="high">
{{$quality->name}}
</span>
</div>
@endforeach
</div>
</fieldset>
</div>
<div class="col-md-6 mb-3">
<fieldset class="form-group row">
<legend class="col-form-label col-sm-4 float-sm-left pt-0">Product Fabric</legend>
<div class="col-sm-8">
<div class="row">
@foreach ($fabrics as $fabricChunks)
<div class="col-md-4">
@foreach($fabricChunks as $fabric)
<div class="form-check">
<input class="form-check-input" type="radio" name="pro_fabric"
id="{{$fabric->id}}"
@if(isset($product[0]->fabric) &&
$product[0]->fabric->id == $fabric->id)
checked
@elseif(!isset($product[0]->fabric) &&
(old('pro_fabric') == $fabric->id))
checked
@endif
value="{{$fabric->id}}">
<span class="form-check-label" for="cotton">
{{$fabric->name}}
</span>
</div>
@endforeach
</div>
@endforeach
</div>
</div>
</fieldset>
</div>
</div>
<div>
@if(isset($product))
<button class="btn btn-warning" type="submit">Update Product</button>
@else
<button class="btn btn-primary" type="submit">Create Product</button>
@endif
</div>
</div>
<div class="col-md-3">
@if(Session::has('failed'))
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Failed!</strong> {{Session::get('failed')}}
</div>
@endif
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
</div>
</div>
</form>
</div>
</div>
@endsection
@section('js')
<script>
$(document).ready(function () {
});
function getSubcategories(category_id) {
$.ajax({
type: 'GET',
url: '{{ route('subcategories') }}',
data: {
'id': category_id
},
success: function (response) {
let data = response.data[0].subcategories;
let template = '<option value="default">Select Subcategory</option>';
for (let i = 0; i < data.length; i++) {
template += '<option value="' + data[i].id + '" id="' + data[i].id + '"> ' +
data[i].name + '</option>';
}
$('#subcategory').html(template);
},
});
}
$('.enable-color-quantity').on('click',function () {
let id = $(this).val();
let enabled = $(this).is(':checked');
$('#qty-'+id).attr('disabled',!enabled);
$('#qty-'+id).val(null)
// alert(enabled);
});
$('#pro_price').on('input', function () {
$('#showPrice').val($(this).val())
});
function previewImage(input) {
let file = $("input[type=file]").get(0).files[0];
if (file) {
let reader = new FileReader();
reader.onload = function () {
$('#imagePreview').attr('src', reader.result)
};
reader.readAsDataURL(file);
}
}
$('#createProduct').submit(function (e) {
e.preventDefault();
let formData = new FormData(this);
$.ajax({
url: '/product/store',
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
dataType: 'json',
success: function (response) {
console.log(response.data)
window.location.href = "{{route('index')}}"
}
});
});
$('#updateProduct').submit(function (e) {
e.preventDefault();
let formData = new FormData(this);
$.ajax({
url: '/product/update',
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
dataType: 'json',
success: function (response) {
console.log(response);
window.location.href = "{{route('index')}}"
}
});
});
</script>
@endsection
| 53.482456
| 119
| 0.318299
|
7788502099c52713597324fbda26e878533b00d0
| 7,981
|
swift
|
Swift
|
TKNetworkEyeModule/Classes/Core/DBManager.swift
|
zhuamaodeyu/TKNetworkEyeModule
|
196b1ba1c46a5e392708701b64597a468adf787e
|
[
"MIT"
] | null | null | null |
TKNetworkEyeModule/Classes/Core/DBManager.swift
|
zhuamaodeyu/TKNetworkEyeModule
|
196b1ba1c46a5e392708701b64597a468adf787e
|
[
"MIT"
] | null | null | null |
TKNetworkEyeModule/Classes/Core/DBManager.swift
|
zhuamaodeyu/TKNetworkEyeModule
|
196b1ba1c46a5e392708701b64597a468adf787e
|
[
"MIT"
] | null | null | null |
//
// DBManager.swift
// TKNetworkEyeModule
//
// Created by 聂子 on 2019/1/24.
//
import Foundation
import Foundation
import SQLite
let id = Expression<Int64>("id")
let host = Expression<String?>("host")
let debug = Expression<Bool>("debug")
let path = Expression<String?>("path")
let length = Expression<Int64>("length")
let httpMethod = Expression<String?>("method")
let requestLineLength = Expression<Int64>("request_line_length")
let requestHeaderLength = Expression<Int64>("request_header_length")
let requestBodyLength = Expression<Int64>("request_body_length")
let responseLineLength = Expression<Int64>("response_line_length")
let responseHeaderLength = Expression<Int64>("response_header_length")
let responseBodyLength = Expression<Int64>("response_body_length")
let mimeType = Expression<String?>("mime_type")
let statusCode = Expression<Int>("status_code")
let startTime = Expression<TimeInterval>("start_time")
let endTime = Expression<TimeInterval>("end_time")
let redirectCount = Expression<Int>("redirect_count")
let protocolName = Expression<String?>("protocol_name")
let proxyConnection = Expression<Bool>("proxy_connection")
let dnsStartTime = Expression<TimeInterval>("dns_start_time")
let dnsEndTime = Expression<TimeInterval>("dns_end_time")
let tcpStartTime = Expression<TimeInterval>("tcp_start_time")
let tcpEndTime = Expression<TimeInterval>("tcp_end_time")
let requestStartTime = Expression<TimeInterval>("request_start_time")
let requestEndTime = Expression<TimeInterval>("request_end_time")
let responseStartTime = Expression<TimeInterval>("response_start_time")
let responseEndTime = Expression<TimeInterval>("response_end_time")
let isUpload = Expression<Bool>("is_upload")
class DBManager: NSObject {
static let sharedInstance = DBManager.init()
private var db: Connection?
private var thread: Thread?
private var table: Table?
private var queue:[NetworkEyeModel] = []
private var column:[String:Any] = [String:Any]()
private var database: String = "TKNetworkEye"
private override init() {
super.init()
}
}
extension DBManager {
private func initConnection(){
self.db = try? Connection("\(DBManager.dbPath())/\(database).sqlite3")
self.db?.busyTimeout = 5
self.db?.busyHandler({ (tries) -> Bool in
if tries >= 3{
return false
}
return true
})
}
private func initTable() {
self.table = Table("t_table")
_ = try? db?.run(table?.create(block: { (b ) in
b.column(id, primaryKey: PrimaryKey.autoincrement)
b.column(host)
b.column(debug)
b.column(path)
b.column(length)
b.column(httpMethod)
b.column(requestLineLength)
b.column(requestHeaderLength)
b.column(requestBodyLength)
b.column(responseLineLength)
b.column(responseHeaderLength)
b.column(responseBodyLength)
b.column(mimeType)
b.column(statusCode)
b.column(startTime)
b.column(endTime)
b.column(redirectCount)
b.column(protocolName)
b.column(proxyConnection)
b.column(dnsStartTime)
b.column(dnsEndTime)
b.column(tcpStartTime)
b.column(tcpEndTime)
b.column(requestStartTime)
b.column(requestEndTime)
b.column(responseStartTime)
b.column(responseEndTime)
b.column(isUpload)
}) ?? "")
}
private func initThread() {
self.thread = Thread.init(target: self, selector: #selector(startRunloop), object: nil)
self.thread?.name = "update_db_eye"
self.thread?.start()
}
}
// MARK: - Action
extension DBManager {
@objc private func startRunloop() {
autoreleasepool {
let runloop = RunLoop.current
runloop.add(NSMachPort.init(), forMode: .commonModes)
runloop.run()
}
}
@objc private func threadAction() {
while queue.count > 0 {
do {
if let db = self.db,let table = self.table,let model = queue.first {
try db.run(table.insert(
host <- model.host,
debug <- model.debug,
path <- model.path,
length <- model.length,
httpMethod <- model.httpMethod,
requestLineLength <- model.request_line_length,
requestHeaderLength <- model.request_header_length,
requestBodyLength <- model.request_body_length,
responseLineLength <- model.response_line_length,
responseHeaderLength <- model.response_header_length,
responseBodyLength <- model.response_body_length,
mimeType <- model.mime_type,
statusCode <- model.status_code,
startTime <- model.start_time,
endTime <- model.end_time,
redirectCount <- model.redirect_count,
protocolName <- model.protocol_name,
proxyConnection <- model.proxy_connection,
dnsStartTime <- model.dns_start_time,
dnsEndTime <- model.dns_end_time,
tcpStartTime <- model.tcp_start_time,
tcpEndTime <- model.tcp_end_time,
requestStartTime <- model.request_start_time,
requestEndTime <- model.request_end_time,
responseStartTime <- model.response_start_time,
responseEndTime <- model.response_end_time,
isUpload <- model.is_upload
))
queue.removeFirst()
}else {
queue.removeAll()
}
}catch let error{
print("insert id: \(error)")
}
}
}
}
// MARK: - Other
extension DBManager {
private static func dbPath() -> String {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
return path ?? ""
}
}
extension DBManager {
func removeData(for type: CleanupStrategyType) {
guard let db = self.db, let table = self.table else {
return
}
do {
switch type {
case .never:
break
case .oneDay:
let alice = table.filter(startTime > 24 * 60 * 1000)
try db.run(alice.delete())
break
case .oneWeek:
let alice = table.filter(startTime > 7 * 24 * 60 * 1000)
try db.run(alice.delete())
break
case .oneMonth:
let alice = table.filter(startTime > 30 * 24 * 60 * 1000)
try db.run(alice.delete())
break
case .notUpload:
let alice = table.filter(isUpload == true)
try db.run(alice.delete())
break
case .restart:
fallthrough
default:
try db.run(table.delete())
break
}
} catch let error {
print("\(error)")
}
}
func save(model: NetworkEyeModel) {
self.queue.append(model)
if let t = self.thread {
self.perform(#selector(threadAction), on: t, with: nil, waitUntilDone: false)
}
}
}
extension DBManager {
func connection(database: String? = nil) {
if let d = database {
self.database = d
}
initConnection()
initTable()
initThread()
}
}
| 34.253219
| 103
| 0.569102
|
93a5c31dbb5ece4dca29ad4267bbb8bdc8d6b361
| 610
|
cs
|
C#
|
src/NetStandard/Collections/Collections/src/Collections/Generic/CovariantKeyValuePair{KeyType,ValueType}.cs
|
DawidIzydor/Teronis.DotNet
|
65770b28b6a34b0553a116fe46815bffeed1b183
|
[
"MIT"
] | null | null | null |
src/NetStandard/Collections/Collections/src/Collections/Generic/CovariantKeyValuePair{KeyType,ValueType}.cs
|
DawidIzydor/Teronis.DotNet
|
65770b28b6a34b0553a116fe46815bffeed1b183
|
[
"MIT"
] | null | null | null |
src/NetStandard/Collections/Collections/src/Collections/Generic/CovariantKeyValuePair{KeyType,ValueType}.cs
|
DawidIzydor/Teronis.DotNet
|
65770b28b6a34b0553a116fe46815bffeed1b183
|
[
"MIT"
] | null | null | null |
using System.Diagnostics.CodeAnalysis;
namespace Teronis.Collections.Generic
{
public struct CovariantKeyValuePair<KeyType, ValueType> : ICovariantKeyValuePair<KeyType, ValueType>
{
public CovariantKeyValuePair(KeyType key, [AllowNull] ValueType value)
{
Key = key;
Value = value;
}
public KeyType Key { get; }
[MaybeNull, AllowNull]
public ValueType Value { get; }
public void Deconstruct(out KeyType key, [MaybeNull] out ValueType value)
{
key = Key;
value = Value;
}
}
}
| 25.416667
| 104
| 0.601639
|
e2a2f7e7a11875ed2aadb5258de28b87bb340ab3
| 244
|
py
|
Python
|
curso-python/cursoemvideo/ex41aula12.py
|
RoSapia/Python-curso-em-video
|
a691aefa879d55af3a084e78f0a3c8ad8490fc22
|
[
"MIT"
] | null | null | null |
curso-python/cursoemvideo/ex41aula12.py
|
RoSapia/Python-curso-em-video
|
a691aefa879d55af3a084e78f0a3c8ad8490fc22
|
[
"MIT"
] | null | null | null |
curso-python/cursoemvideo/ex41aula12.py
|
RoSapia/Python-curso-em-video
|
a691aefa879d55af3a084e78f0a3c8ad8490fc22
|
[
"MIT"
] | null | null | null |
'''A confederação nacional de natacao precisa de um programa que leia o ano de nascimento de um atleta
e mostre sua categoria, de acordo com a idade
até 9 anos> MIRIM
até 14 anos: INFANTIL
até 19 anos JUNIOR
até 20 anos SENIOR
acima: MASTER'''
| 34.857143
| 102
| 0.77459
|
a3c82e39059b764de08951ef8f79a76204556d55
| 3,625
|
java
|
Java
|
src/main/java/com/bbn/openmap/layer/vpf/VPFGraphicWarehouse.java
|
d2fn/passage
|
2085183f1b085ac344198bd674024fe715bd4fca
|
[
"MIT"
] | 1
|
2020-04-10T09:43:49.000Z
|
2020-04-10T09:43:49.000Z
|
src/main/java/com/bbn/openmap/layer/vpf/VPFGraphicWarehouse.java
|
d2fn/passage
|
2085183f1b085ac344198bd674024fe715bd4fca
|
[
"MIT"
] | null | null | null |
src/main/java/com/bbn/openmap/layer/vpf/VPFGraphicWarehouse.java
|
d2fn/passage
|
2085183f1b085ac344198bd674024fe715bd4fca
|
[
"MIT"
] | 3
|
2015-05-01T20:36:49.000Z
|
2022-03-09T22:47:04.000Z
|
// **********************************************************************
//
// <copyright>
//
// BBN Technologies
// 10 Moulton Street
// Cambridge, MA 02138
// (617) 873-8000
//
// Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFGraphicWarehouse.java,v $
// $RCSfile: VPFGraphicWarehouse.java,v $
// $Revision: 1.6 $
// $Date: 2009/01/21 01:24:41 $
// $Author: dietrick $
//
// **********************************************************************
package com.bbn.openmap.layer.vpf;
import java.util.List;
import com.bbn.openmap.proj.coords.LatLonPoint;
/**
* Define an interface for a Graphic Factory for graphics read from
* VPF.
*/
public interface VPFGraphicWarehouse extends VPFWarehouse {
/**
* Method called by the VPF reader code to construct an area
* feature.
*
* @param c the coverage table for this area
* @param a the areatable being parsed
* @param l the record read from the area table
* @param dpplat threshold for latitude thinning (passed to
* warehouse)
* @param dpplon threshold for longitude thinngin (passed to
* warehouse)
* @param ll1 upperleft of selection region (passed to warehouse)
* @param ll2 lowerright of selection region (passed to warehouse)
*/
public void createArea(CoverageTable c, AreaTable a, List<Object> l,
LatLonPoint ll1, LatLonPoint ll2, double dpplat,
double dpplon);
/**
* Method called by the VPF reader code to construct an edge
* feature.
*
* @param c the coverage table for this edge
* @param e the edgetable being parsed
* @param l the record read from the edge table
* @param dpplat threshold for latitude thinning (passed to
* warehouse)
* @param dpplon threshold for longitude thinngin (passed to
* warehouse)
* @param ll1 upperleft of selection region (passed to warehouse)
* @param ll2 lowerright of selection region (passed to warehouse)
*/
public void createEdge(CoverageTable c, EdgeTable e, List<Object> l,
LatLonPoint ll1, LatLonPoint ll2, double dpplat,
double dpplon, CoordFloatString coords);
/**
* Method called by the VPF reader code to construct a text
* feature.
*
* @param c the coverage table for this text
* @param t the texttable being parsed
* @param textprim the record read from the text table
* @param latitude the latitude of the text
* @param longitude the longitude of the text
* @param text the text string
*/
public void createText(CoverageTable c, TextTable t, List<Object> textprim,
double latitude, double longitude, String text);
/**
* Method called by the VPF reader code to construct a node
* feature.
*
* @param c the coverage table for this node
* @param t the nodetable being parsed
* @param nodeprim the record read from the node table
* @param latitude the latitude of the node
* @param longitude the longitude of the node
* @param isEntityNode true if we are reading entity notes, false
* if we are reading connected nodes
*/
public void createNode(CoverageTable c, NodeTable t, List<Object> nodeprim,
double latitude, double longitude, boolean isEntityNode);
}
| 36.989796
| 100
| 0.606069
|
ddcdf7b737a09f9da8d38d253657956bc445efd0
| 33,092
|
java
|
Java
|
src/main/java/org/dasein/cloud/test/network/StatefulStaticIPTests.java
|
mariapavlova/dasein-cloud-test
|
b26869b85e8de7c1c161e6c02c4e6c0d827717a6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/dasein/cloud/test/network/StatefulStaticIPTests.java
|
mariapavlova/dasein-cloud-test
|
b26869b85e8de7c1c161e6c02c4e6c0d827717a6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/dasein/cloud/test/network/StatefulStaticIPTests.java
|
mariapavlova/dasein-cloud-test
|
b26869b85e8de7c1c161e6c02c4e6c0d827717a6
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright (C) 2009-2014 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.dasein.cloud.test.network;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.OperationNotSupportedException;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.compute.VMLaunchOptions;
import org.dasein.cloud.compute.VirtualMachine;
import org.dasein.cloud.compute.VirtualMachineSupport;
import org.dasein.cloud.compute.VmState;
import org.dasein.cloud.dc.DataCenter;
import org.dasein.cloud.network.IPVersion;
import org.dasein.cloud.network.IpAddress;
import org.dasein.cloud.network.IpAddressSupport;
import org.dasein.cloud.network.IpForwardingRule;
import org.dasein.cloud.network.NetworkServices;
import org.dasein.cloud.network.Protocol;
import org.dasein.cloud.network.Subnet;
import org.dasein.cloud.network.VLAN;
import org.dasein.cloud.network.VLANSupport;
import org.dasein.cloud.test.DaseinTestManager;
import org.dasein.cloud.test.compute.ComputeResources;
import org.dasein.util.CalendarWrapper;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import javax.annotation.Nonnull;
import java.util.Random;
import java.util.UUID;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
/**
* Tests verifying the various stateful capabilities of static IP support in Dasein Cloud.
* <p>Created by George Reese: 2/23/13 10:22 PM</p>
* @author George Reese
* @version 2013.04 initial version
* @since 2013.04
*/
public class StatefulStaticIPTests {
static private final Random random = new Random();
// TODO: add a test for assigning at launch
static private DaseinTestManager tm;
@BeforeClass
static public void configure() {
tm = new DaseinTestManager(StatefulStaticIPTests.class);
}
@AfterClass
static public void cleanUp() {
if( tm != null ) {
tm.close();
}
}
@Rule
public final TestName name = new TestName();
private String testIpAddressId;
private String testRuleId;
private String testVlanId;
private String testVMId;
private boolean inVlan;
public StatefulStaticIPTests() { }
@Before
public void before() {
tm.begin(name.getMethodName());
assumeTrue(!tm.isTestSkipped());
testVlanId = tm.getTestVLANId(DaseinTestManager.STATEFUL, true, null);
if( testVlanId != null ) {
NetworkServices services = tm.getProvider().getNetworkServices();
if( services != null ) {
VLANSupport support = services.getVlanSupport();
try {
if( support != null && support.getCapabilities().supportsInternetGatewayCreation() && !support.isConnectedViaInternetGateway(testVlanId) ) {
support.createInternetGateway(testVlanId);
}
}
catch( Throwable ignore ) {
// ignore
}
}
}
if( name.getMethodName().equals("releaseFromPool") ) {
testIpAddressId = tm.getTestStaticIpId(DaseinTestManager.REMOVED, true, null, false, null);
if( testIpAddressId == null ) {
testIpAddressId = tm.getTestStaticIpId(DaseinTestManager.REMOVED, true, null, true, testVlanId);
}
}
else if( name.getMethodName().startsWith("forward") ) {
testIpAddressId = tm.getTestStaticIpId(DaseinTestManager.STATEFUL, true, null, false, null);
if( testIpAddressId == null ) {
testIpAddressId = tm.getTestStaticIpId(DaseinTestManager.STATEFUL, true, null, true, testVlanId);
}
testVMId = tm.getTestVMId(DaseinTestManager.STATEFUL, VmState.RUNNING, true, null);
}
else if( name.getMethodName().startsWith("stopForward") ) {
testIpAddressId = tm.getTestStaticIpId(DaseinTestManager.STATEFUL, true, null, false, null);
if( testIpAddressId == null ) {
testIpAddressId = tm.getTestStaticIpId(DaseinTestManager.STATEFUL, true, null, true, testVlanId);
}
testVMId = tm.getTestVMId(DaseinTestManager.STATEFUL, VmState.RUNNING, true, null);
if( testIpAddressId != null && testVMId != null ) {
NetworkServices services = tm.getProvider().getNetworkServices();
if( services != null ) {
IpAddressSupport support = services.getIpAddressSupport();
try {
IPVersion version = (name.getMethodName().contains("IPv6") ? IPVersion.IPV6 : IPVersion.IPV4);
if( support != null && support.getCapabilities().isForwarding(version) ) {
testRuleId = support.forward(testIpAddressId, 8000, Protocol.TCP, 9000, testVMId);
}
}
catch( Throwable ignore ) {
// ignore
}
}
}
}
else if( name.getMethodName().equals("releaseFromVirtualMachine") ) {
testIpAddressId = tm.getTestStaticIpId(DaseinTestManager.STATEFUL, true, null, false, null);
if( testIpAddressId == null ) {
testIpAddressId = tm.getTestStaticIpId(DaseinTestManager.STATEFUL, true, null, true, testVlanId);
}
testVMId = tm.getTestVMId(DaseinTestManager.STATEFUL, VmState.RUNNING, true, null);
if( testVMId != null ) {
NetworkServices services = tm.getProvider().getNetworkServices();
if( services != null ) {
IpAddressSupport support = services.getIpAddressSupport();
if( support != null ) {
try {
support.assign(testIpAddressId, testVMId);
}
catch( Throwable ignore ) {
// ignore
}
}
}
}
}
else if( name.getMethodName().startsWith("assignPost") || name.getMethodName().startsWith("forward") || name.getMethodName().equals("releaseFromServer") ) {
IPVersion version = IPVersion.IPV4;
if( name.getMethodName().contains("IPv6") ) {
version = IPVersion.IPV6;
}
if( !name.getMethodName().endsWith("InVLAN") ) {
testVMId = tm.getTestVMId(DaseinTestManager.STATEFUL, VmState.RUNNING, true, null);
if( testVMId != null ) {
VirtualMachine vm = null;
try {
//noinspection ConstantConditions
vm = tm.getProvider().getComputeServices().getVirtualMachineSupport().getVirtualMachine(testVMId);
}
catch( Throwable ignore ) {
// ignore
}
if( vm != null && vm.getProviderVlanId() != null ) {
inVlan = true;
testVMId = null;
}
else if( vm != null ) {
testIpAddressId = tm.getTestStaticIpId(DaseinTestManager.STATEFUL, true, version, false, null);
}
}
}
else if( testVlanId != null ) {
String productId = tm.getTestVMProductId();
String imageId = tm.getTestImageId(DaseinTestManager.STATELESS, false);
if( productId != null && imageId != null ) {
VMLaunchOptions options = VMLaunchOptions.getInstance(productId, imageId, "dsnnetl" + (System.currentTimeMillis()%10000), "Dasein Network Launch " + System.currentTimeMillis(), "Test launch for a VM in a network");
String subnetId = tm.getTestSubnetId(DaseinTestManager.STATEFUL, true, testVlanId, null);
String dataCenterId = null;
if( subnetId == null ) {
try {
@SuppressWarnings("ConstantConditions") VLAN vlan = tm.getProvider().getNetworkServices().getVlanSupport().getVlan(testVlanId);
if( vlan != null ) {
dataCenterId = vlan.getProviderDataCenterId();
}
}
catch( Throwable ignore ) {
// ignore
}
}
else {
try {
@SuppressWarnings("ConstantConditions") Subnet subnet = tm.getProvider().getNetworkServices().getVlanSupport().getSubnet(subnetId);
if( subnet != null ) {
dataCenterId = subnet.getProviderDataCenterId();
}
}
catch( Throwable ignore ) {
// ignore
}
}
if( dataCenterId == null ) {
try {
for( DataCenter dc : tm.getProvider().getDataCenterServices().listDataCenters(tm.getContext().getRegionId()) ) {
if( dc.isActive() && dc.isAvailable() ) {
dataCenterId = dc.getProviderDataCenterId();
break;
}
}
}
catch( Throwable ignore ) {
// ignore
}
}
assert dataCenterId != null;
options.inDataCenter(dataCenterId);
options.inSubnet(null, dataCenterId, testVlanId, subnetId);
ComputeResources compute = DaseinTestManager.getComputeResources();
if( compute != null ) {
try {
//noinspection ConstantConditions
testVMId = compute.provisionVM(tm.getProvider().getComputeServices().getVirtualMachineSupport(), DaseinTestManager.STATEFUL + "vlan", options, dataCenterId);
}
catch( Throwable t ) {
tm.warn("Unable to provision test VM with VLAN=" + testVlanId + ", subnet=" + subnetId + " in " + dataCenterId);
}
}
}
if( testVMId != null ) {
try {
VirtualMachine vm = tm.getProvider().getComputeServices().getVirtualMachineSupport().getVirtualMachine(testVMId);
testVlanId = vm.getProviderVlanId();
testIpAddressId = tm.getTestStaticIpId(DaseinTestManager.STATEFUL + testVlanId, true, version, true, testVlanId);
}
catch( Throwable ignore ) {
// ignore
}
}
}
}
}
@After
public void after() {
try {
testVlanId = null;
testVMId = null;
NetworkServices services = tm.getProvider().getNetworkServices();
if( services != null ) {
IpAddressSupport support = services.getIpAddressSupport();
if( support != null ) {
if( testRuleId != null ) {
try {
support.stopForward(testRuleId);
}
catch( Throwable ignore ) {
// ignore
}
}
if( testIpAddressId != null ) {
try {
support.releaseFromServer(testIpAddressId);
}
catch( Throwable ignore ) {
// ignore
}
}
}
}
testIpAddressId = null;
testRuleId = null;
}
finally {
tm.end();
}
}
private void request(@Nonnull IPVersion version, boolean forVLAN) throws CloudException, InternalException {
NetworkServices services = tm.getProvider().getNetworkServices();
if( services == null ) {
tm.ok("Network services are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
IpAddressSupport support = services.getIpAddressSupport();
if( support == null ) {
tm.ok("Static IP addresses are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
NetworkResources network = DaseinTestManager.getNetworkResources();
assertNotNull("Testing failed to initialize properly as there are no network resources", network);
if( !support.isSubscribed() ) {
try {
network.provisionAddress(support, "provision", version, null);
fail("The account is supposedly not subscribed to IP address support, but a request operation completed");
}
catch( CloudException expected ) {
tm.ok("Caught a cloud exception attempting to request an address of type " + version + " in an account where there is no subscription");
}
}
else if( support.getCapabilities().isRequestable(version) && (!forVLAN || support.getCapabilities().supportsVLANAddresses(version)) ) {
String addressId;
if( !forVLAN ) {
addressId = network.provisionAddress(support, "provision", version, null);
}
else {
addressId = network.provisionAddress(support, "provision", version, testVlanId);
}
tm.out("New " + version + " Address", addressId);
assertNotNull("Requesting a new IP address may not result in a null address ID", addressId);
}
else {
try {
if( !forVLAN ) {
network.provisionAddress(support, "provision", version, null);
}
else {
network.provisionAddress(support, "provision", version, UUID.randomUUID().toString());
}
fail("Requesting addresses of " + version + " is supposedly not supported, but the operation completed");
}
catch( OperationNotSupportedException expected ) {
tm.ok("Caught OperationNotSupportedException when attempting to request an IP address of version " + version);
}
}
}
@Test
public void requestIPv4() throws CloudException, InternalException {
request(IPVersion.IPV4, false);
}
@Test
public void requestIPv6() throws CloudException, InternalException {
request(IPVersion.IPV6, false);
}
@Test
public void requestIPv4InVLAN() throws CloudException, InternalException {
request(IPVersion.IPV4, true);
}
@Test
public void requestIPv6inVLAN() throws CloudException, InternalException {
request(IPVersion.IPV6, true);
}
private void assignPostLaunch(@Nonnull IPVersion version) throws CloudException, InternalException {
NetworkServices services = tm.getProvider().getNetworkServices();
if( services == null ) {
tm.ok("Network services are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
IpAddressSupport support = services.getIpAddressSupport();
if( support == null ) {
tm.ok("Static IP addresses are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
if( testIpAddressId == null ) {
if( !support.isSubscribed() ) {
tm.ok("No IP address subscription exists for this account in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName() + ", so this test is invalid");
}
else if( !support.getCapabilities().isAssignablePostLaunch(version) ) {
tm.ok("Unable to assign new IP addresses in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
}
else if( !support.getCapabilities().isRequestable(version) ) {
tm.warn("Unable to provision new IP addresses in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName() + ", so this test is invalid");
}
else {
if( name.getMethodName().contains("VLAN") && !support.getCapabilities().supportsVLANAddresses(version) ) {
tm.ok("No VLAN IP addresses are supported");
}
else {
fail(String.format("Unable to get a test %s address for running the test %s", version == IPVersion.IPV4?"IPv4":"IPv6", name.getMethodName()));
}
}
return;
}
if( testVMId == null ) {
fail("Unable to get a test VM for running the test " + name.getMethodName());
}
if( support.getCapabilities().isAssignablePostLaunch(version) ) {
@SuppressWarnings("ConstantConditions") VirtualMachineSupport vmSupport = tm.getProvider().getComputeServices().getVirtualMachineSupport();
IpAddress address = support.getIpAddress(testIpAddressId);
assertNotNull("The test IP address has gone away", address);
assertNotNull("No virtual machine support exists in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName(), vmSupport);
VirtualMachine vm = vmSupport.getVirtualMachine(testVMId);
assertNotNull("The test virtual machine disappeared before the test could run", vm);
tm.out("VM Before", address.getServerId());
tm.out("Address Before", vm.getProviderAssignedIpAddressId());
assertTrue("The current assignment to the test virtual machine is the test IP address, cannot reasonably tests this", !testIpAddressId.equals(vm.getProviderAssignedIpAddressId()));
support.assign(testIpAddressId, testVMId);
long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*10L);
while( System.currentTimeMillis() < timeout ) {
try { vm = vmSupport.getVirtualMachine(testVMId); }
catch( Throwable ignore ) { }
assertNotNull("Virtual machine disappeared post-assignment", vm);
try { address = support.getIpAddress(testIpAddressId); }
catch( Throwable ignore ) { }
assertNotNull("IP address disappeared post-assignment", address);
if( address.getServerId() != null && vm.getProviderAssignedIpAddressId() != null ) {
break;
}
try { Thread.sleep(10000L); }
catch( InterruptedException ignore ) { }
}
tm.out("VM After", address.getServerId());
tm.out("Address After", vm.getProviderAssignedIpAddressId());
assertEquals("The IP address assigned to the virtual machine does not match the test IP address", testIpAddressId, vm.getProviderAssignedIpAddressId());
assertEquals("The virtual machine associated with the IP address does not match the test VM", testVMId, address.getServerId());
}
else {
try {
support.assign(testIpAddressId, testVMId);
fail("Assigning an IP address post-launch succeeded even though meta-data suggests it should not have");
}
catch( OperationNotSupportedException expected ) {
tm.ok("Caught OperationNotSupportedException when attempting to assign an IP to a VM post-launch when such assignments are not allowed");
}
}
}
@Test
public void assignPostLaunchIPv4() throws CloudException, InternalException {
if( inVlan ) {
tm.ok("VM is still launched in VLAN, skipping the test "+name.getMethodName());
tm.skip();
} else {
assignPostLaunch(IPVersion.IPV4);
}
}
@Test
public void assignPostLaunchIPv6() throws CloudException, InternalException {
if( inVlan ) {
tm.ok("VM is still launched in VLAN, skipping the test "+name.getMethodName());
tm.skip();
} else {
assignPostLaunch(IPVersion.IPV6);
}
}
@Test
public void assignPostLaunchIPv4InVLAN() throws CloudException, InternalException {
if( !inVlan ) {
tm.ok("VM is launched outside VLAN, skipping the test "+name.getMethodName());
tm.skip();
}
else {
assignPostLaunch(IPVersion.IPV4);
}
}
@Test
public void assignPostLaunchIPv6inVLAN() throws CloudException, InternalException {
if( !inVlan ) {
tm.ok("VM is launched outside VLAN, skipping the test "+name.getMethodName());
tm.skip();
}
else {
assignPostLaunch(IPVersion.IPV6);
}
}
@Test
public void releaseFromPool() throws CloudException, InternalException {
NetworkServices services = tm.getProvider().getNetworkServices();
if( services == null ) {
tm.ok("Network services are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
IpAddressSupport support = services.getIpAddressSupport();
if( support == null ) {
tm.ok("Static IP addresses are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
if( testIpAddressId == null ) {
if( !support.getCapabilities().isRequestable(IPVersion.IPV4) && !support.getCapabilities().isRequestable(IPVersion.IPV6) ) {
tm.ok("Requesting/releasing addresses is not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
}
else {
fail("There is no test IP address to use in verifying the ability to release addresses from the pool");
}
}
else {
IpAddress address = support.getIpAddress(testIpAddressId);
assertNotNull("Test IP addresss " + testIpAddressId + " does not exist", address);
support.releaseFromPool(testIpAddressId);
address = support.getIpAddress(testIpAddressId);
tm.out("Result", address);
assertNull("The test IP address " + testIpAddressId + " still exists in the IP address pool", address);
}
}
@Test
public void releaseFromVirtualMachine() throws CloudException, InternalException {
NetworkServices services = tm.getProvider().getNetworkServices();
if( services == null ) {
tm.ok("Network services are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
IpAddressSupport support = services.getIpAddressSupport();
if( support == null ) {
tm.ok("Static IP addresses are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
if( testIpAddressId == null ) {
if( !support.getCapabilities().isRequestable(IPVersion.IPV4) && !support.getCapabilities().isRequestable(IPVersion.IPV6) ) {
tm.ok("Requesting/releasing addresses is not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
}
else {
fail("There is no test IP address to use in verifying the ability to release addresses from a virtual machine");
}
}
else {
IpAddress address = support.getIpAddress(testIpAddressId);
assertNotNull("Test IP addresss " + address + " does not exist", address);
if( address.getServerId() != null ) {
@SuppressWarnings("ConstantConditions") VirtualMachineSupport vmSupport = tm.getProvider().getComputeServices().getVirtualMachineSupport();
assertNotNull("No virtual machine support", vmSupport);
VirtualMachine vm = vmSupport.getVirtualMachine(testVMId);
assertNotNull("Test virtual machine does not exist", vm);
tm.out("VM Before", vm.getProviderAssignedIpAddressId());
tm.out("Address Before", address.getServerId());
support.releaseFromServer(testIpAddressId);
long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*10L);
while( System.currentTimeMillis() < timeout ) {
try { vm = vmSupport.getVirtualMachine(testVMId); }
catch( Throwable ignore ) { }
assertNotNull("Virtual machine disappeared post-assignment", vm);
try { address = support.getIpAddress(testIpAddressId); }
catch( Throwable ignore ) { }
assertNotNull("IP address disappeared post-assignment", address);
if( address.getServerId() == null && vm.getProviderAssignedIpAddressId() == null ) {
break;
}
try { Thread.sleep(10000L); }
catch( InterruptedException ignore ) { }
}
tm.out("VM After", vm.getProviderAssignedIpAddressId());
tm.out("Address After", address.getServerId());
assertNull("The IP address assigned to the virtual machine is still set", vm.getProviderAssignedIpAddressId());
assertNull("The virtual machine associated with the IP address is still set", address.getServerId());
}
else {
if( !support.getCapabilities().isAssignablePostLaunch(address.getVersion()) ) {
tm.ok("Dynamic IP address assignment is not supported");
}
else {
fail("IP address is not assigned to a virtual machine and thus this test cannot run");
}
}
}
}
private void forward(@Nonnull IPVersion version) throws CloudException, InternalException {
NetworkServices services = tm.getProvider().getNetworkServices();
if( services == null ) {
tm.ok("Network services are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
IpAddressSupport support = services.getIpAddressSupport();
if( support == null ) {
tm.ok("Static IP addresses are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
if( support.getCapabilities().isForwarding(version) ) {
if( testIpAddressId != null ) {
assertNotNull("Test VM is null", testVMId);
int ext = 8000 + random.nextInt(1000);
int prv = 9000 + random.nextInt(1000);
testRuleId = support.forward(testIpAddressId, ext, Protocol.TCP, prv, testVMId);
tm.out("New Rule", testRuleId);
assertNotNull("Forwarding must provide a rule ID", testRuleId);
boolean found = false;
for( IpForwardingRule rule : support.listRules(testIpAddressId) ) {
if( testRuleId.equals(rule.getProviderRuleId()) ) {
assertTrue("Matching rule does not match address", testIpAddressId.equals(rule.getAddressId()));
assertTrue("Matching rule does not match virtual machine", testVMId.equals(rule.getServerId()));
assertTrue("Public ports do not match", rule.getPublicPort() == ext);
assertTrue("Private ports do not match", rule.getPrivatePort() == prv);
assertTrue("Protocols do not match", Protocol.TCP.equals(rule.getProtocol()));
found = true;
}
}
assertTrue("Did not find the newly created rule", found);
}
else {
if( !support.getCapabilities().isRequestable(version) ) {
tm.warn("Could not run this test because IP addresses cannot be request and the test does not use existing IPs");
}
else {
fail("No test IP address was established for this test");
}
}
}
else {
tm.ok("IP address forwarding is not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
}
}
@Test
public void forwardIPv4() throws CloudException, InternalException {
forward(IPVersion.IPV4);
}
@Test
public void forwardIPv6() throws CloudException, InternalException {
forward(IPVersion.IPV6);
}
private void stopForward(IPVersion version) throws CloudException, InternalException {
NetworkServices services = tm.getProvider().getNetworkServices();
if( services == null ) {
tm.ok("Network services are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
IpAddressSupport support = services.getIpAddressSupport();
if( support == null ) {
tm.ok("Static IP addresses are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
if( support.getCapabilities().isForwarding(version) ) {
if( testRuleId != null ) {
support.stopForward(testRuleId);
long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*10L);
boolean exists = true;
while( timeout > System.currentTimeMillis() ) {
boolean found = false;
for( IpForwardingRule rule : support.listRules(testIpAddressId) ) {
if( testRuleId.equals(rule.getProviderRuleId()) ) {
found = true;
}
}
exists = found;
if( !exists ) {
break;
}
try { Thread.sleep(10000L); }
catch( InterruptedException ignore ) { }
}
tm.out("Rule Exists", exists);
assertNotNull("The target rule still exists among the forwarding rules", exists);
}
else {
if( !support.getCapabilities().isRequestable(version) ) {
tm.warn("Could not run this test because IP addresses cannot be request and the test does not use existing IPs");
}
else {
fail("No test IP address was established for this test");
}
}
}
else {
tm.ok("IP address forwarding is not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
}
}
@Test
public void stopForwardIPv4() throws CloudException, InternalException {
stopForward(IPVersion.IPV4);
}
@Test
public void stopForwardIPv6() throws CloudException, InternalException {
stopForward(IPVersion.IPV6);
}
}
| 44.240642
| 234
| 0.561193
|
0aaaaf04d1071ef78abc14cb1693449fa741211c
| 2,285
|
cs
|
C#
|
OBDIIDashboard/ODBII.Simulator/Extensions/XamlSupportClass.cs
|
alex-doe/obdii-dashboard
|
0628d7efba100fef1333a2c3c226797940021617
|
[
"MIT"
] | null | null | null |
OBDIIDashboard/ODBII.Simulator/Extensions/XamlSupportClass.cs
|
alex-doe/obdii-dashboard
|
0628d7efba100fef1333a2c3c226797940021617
|
[
"MIT"
] | null | null | null |
OBDIIDashboard/ODBII.Simulator/Extensions/XamlSupportClass.cs
|
alex-doe/obdii-dashboard
|
0628d7efba100fef1333a2c3c226797940021617
|
[
"MIT"
] | null | null | null |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace ODBII.Simulator.Extensions {
internal class XamlSupportClass {
}
public sealed class MyBooleanToVisibilityConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
var flag = false;
if (value is bool) {
flag = (bool)value;
}
if (parameter != null) {
if (bool.Parse((string)parameter) == (bool)value) {
flag = true;
} else {
flag = false;
}
}
if (flag) {
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
var back = ((value is Visibility) && (((Visibility)value) == Visibility.Visible));
if (parameter != null) {
if ((bool)parameter) {
back = !back;
}
}
return back;
}
}
[ValueConversion(typeof(bool), typeof(bool))]
public class InvertBoolConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
bool booleanValue = (bool)value;
return !booleanValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
bool booleanValue = (bool)value;
return !booleanValue;
}
}
public class BrushColorConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if ((bool)value) {
{
return new SolidColorBrush(Colors.GreenYellow);
}
}
return new SolidColorBrush(Colors.Red);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
}
| 34.104478
| 105
| 0.564551
|
cc1a6f56dd9c9314a66bcaeab513e7269b8cc78a
| 389
|
rb
|
Ruby
|
vendor/gems/skala/lib/skala/common_attributes.rb
|
ubpb/katalog
|
70a3bfdb24505499181102452d94938c45fcbafa
|
[
"MIT"
] | null | null | null |
vendor/gems/skala/lib/skala/common_attributes.rb
|
ubpb/katalog
|
70a3bfdb24505499181102452d94938c45fcbafa
|
[
"MIT"
] | 20
|
2015-04-28T10:27:57.000Z
|
2022-03-30T21:55:58.000Z
|
vendor/gems/skala/lib/skala/common_attributes.rb
|
ubpb/katalog
|
70a3bfdb24505499181102452d94938c45fcbafa
|
[
"MIT"
] | null | null | null |
require_relative "../skala"
module Skala::CommonAttributes
include Virtus.model
attribute :ils_record_id
attribute :search_engine_record_id
attribute :contributor
attribute :created
attribute :creator
attribute :creation_date
attribute :edition
attribute :language
attribute :place_of_publication
attribute :publisher
attribute :signature
attribute :title
end
| 19.45
| 36
| 0.794344
|
1b04a58b5fdee5d180ecba141ba8f4e833e9aabe
| 5,934
|
rake
|
Ruby
|
lib/tasks/learn_to_rank.rake
|
uk-gov-mirror/alphagov.search-api
|
1ada3290c49d748bf8ab48ac73331134ed65a4e5
|
[
"MIT"
] | 20
|
2019-02-25T12:50:38.000Z
|
2022-02-18T21:08:36.000Z
|
lib/tasks/learn_to_rank.rake
|
uk-gov-mirror/alphagov.search-api
|
1ada3290c49d748bf8ab48ac73331134ed65a4e5
|
[
"MIT"
] | 393
|
2015-01-12T16:25:53.000Z
|
2019-04-05T11:15:12.000Z
|
lib/tasks/learn_to_rank.rake
|
alphagov-mirror/search-api
|
339220141d28d3496af85ab5e40c3fe457c4051d
|
[
"MIT"
] | 9
|
2015-06-25T12:28:50.000Z
|
2019-02-13T11:33:12.000Z
|
require "base64"
require "csv"
require "fileutils"
require "json"
require "rummager"
require "zip"
require "analytics/popular_queries"
require "relevancy/load_judgements"
namespace :learn_to_rank do
desc "Fetch data from BigQuery. This costs money!"
task :fetch_bigquery_export, [:output, :viewcount] do |_, args|
raise 'set $ENABLE_LTR to "true" to use learn_to_rank' unless Search::RelevanceHelpers.ltr_enabled?
raise 'Base64 encoded environment variable "BIGQUERY_CREDENTIALS" is required' unless ENV.key? "BIGQUERY_CREDENTIALS"
data = LearnToRank::DataPipeline::Bigquery.fetch(JSON.parse(Base64.decode64(ENV["BIGQUERY_CREDENTIALS"])), viewcount: args.viewcount || 10)
CSV.open("tmp/#{args[:output]}.csv", "wb") do |csv|
csv << data.first.keys
data.each do |row|
csv << row.values
end
while data.next?
data = data.next
data.each do |row|
csv << row.values
end
end
end
end
desc "Export a CSV of relevancy judgements generated from CTR on popular queries"
task :generate_relevancy_judgements, [:queries, :output] do |_, args|
raise 'set $ENABLE_LTR to "true" to use learn_to_rank' unless Search::RelevanceHelpers.ltr_enabled?
queries = LearnToRank::DataPipeline::LoadSearchQueries.from_csv(args.queries)
generator = LearnToRank::DataPipeline::RelevancyJudgements.new(queries: queries)
judgements = generator.relevancy_judgements
data = judgements.force
CSV.open("tmp/#{args.output}.csv", "wb") do |csv|
csv << data.first.keys
data.each do |row|
csv << row.values
end
end
end
desc "Export a CSV of SVM-formatted relevancy judgements for training a model"
task :generate_training_dataset, [:judgements, :output_dir] do |_, args|
raise 'set $ENABLE_LTR to "true" to use learn_to_rank' unless Search::RelevanceHelpers.ltr_enabled?
csv = args.judgements || "tmp/autogenerated_relevancy_judgements.csv"
svm_dir = args.output_dir || "tmp/ltr_data"
FileUtils.mkdir_p svm_dir
judgements_data = Relevancy::LoadJudgements.from_csv(csv)
judgements = LearnToRank::DataPipeline::EmbedFeatures.new(judgements_data).augmented_judgements
svm = LearnToRank::DataPipeline::JudgementsToSvm.new(judgements).svm_format_grouped_by_query
File.open("#{svm_dir}/train.txt", "wb") do |train|
File.open("#{svm_dir}/validate.txt", "wb") do |validate|
File.open("#{svm_dir}/test.txt", "wb") do |test|
files = [train, train, train, train, train, train, train, test, test, validate].shuffle
svm.each_with_index do |query_set, index|
# 70% in train 20% in test, 10% in validate
file = files[index % 10]
query_set.each { |row| file.puts(row) }
end
end
end
end
end
namespace :reranker do
desc "Train a reranker model with relevancy judgements"
task :train, [:svm_dir, :model_dir] do |_, args|
raise 'set $ENABLE_LTR to "true" to use learn_to_rank' unless Search::RelevanceHelpers.ltr_enabled?
model_dir = args.model_dir || "tmp/libsvm"
svm_dir = args.svm_dir || "tmp/ltr_data"
sh "env OUTPUT_DIR=#{model_dir} TRAIN=#{svm_dir}/train.txt VALI=#{svm_dir}/validate.txt TEST=#{svm_dir}/test.txt ./ltr/scripts/train.sh"
end
desc "Serves a trained model"
task :serve, [:model_dir] do |_, args|
raise 'set $ENABLE_LTR to "true" to use learn_to_rank' unless Search::RelevanceHelpers.ltr_enabled?
model_dir = args.model_dir || "tmp/libsvm"
sh "env EXPORT_PATH=#{__dir__}/../../#{model_dir} ./ltr/scripts/serve.sh"
end
desc "Evaluate search performance using nDCG with and without the model"
task :evaluate, [:relevancy_judgements] do |_, args|
raise 'set $ENABLE_LTR to "true" to use learn_to_rank' unless Search::RelevanceHelpers.ltr_enabled?
ndcg_at = "10"
csv = args.datafile || begin
bucket_name = ENV["AWS_S3_RELEVANCY_BUCKET_NAME"]
raise "Missing required AWS_S3_RELEVANCY_BUCKET_NAME envvar" if bucket_name.nil?
csv = Tempfile.open(["judgements", ".csv"])
o = Aws::S3::Object.new(bucket_name: bucket_name, key: "autogenerated_judgements.csv")
o.get(response_target: csv.path)
csv.path
end
rounds = ["relevance:disable", nil]
begin
results, results_with_model = rounds.map do |ab_test_round|
judgements = Relevancy::LoadJudgements.from_csv(csv)
evaluator = Evaluate::Ndcg.new(judgements, ab_test_round)
evaluator.compute_ndcg
end
ensure
if csv.is_a?(Tempfile)
csv.close
csv.unlink
end
end
merged = results.keys.each_with_object({}) do |query, hsh|
hsh[query] = {
without: results[query],
with_model: results_with_model[query],
}
end
maxlen = results.keys.map { |query, _| query.length }.max
score_maxlen = results.values.map { |score, _| score[ndcg_at].to_s.length }.max
merged.map do |(query, scores)|
winning = scores[:without][ndcg_at] <= scores[:with_model][ndcg_at] ? "√" : "x"
justified_query = "#{query}:".ljust(maxlen + 1)
justified_score = scores[:without][ndcg_at].to_s.ljust(score_maxlen + 1)
puts "#{winning} #{justified_query} #{justified_score} #{scores[:with_model][ndcg_at]}"
end
winning = merged.dig("average_ndcg", :without, ndcg_at) <= merged.dig("average_ndcg", :with_model, ndcg_at)
puts "---"
puts "without model score: #{merged['average_ndcg'][:without][ndcg_at]}"
puts "with model score: #{merged['average_ndcg'][:with_model][ndcg_at]}"
puts "Without model: #{merged['average_ndcg'][:without]}"
puts "With model: #{merged['average_ndcg'][:with_model]}"
puts "The model has a #{winning ? 'good' : 'bad'} score"
end
end
end
| 39.039474
| 143
| 0.666161
|
257ca6aebe60d9065d03d4056457d1148feaef59
| 125
|
cs
|
C#
|
Models/QnAContext.cs
|
johnataylor/RemoteDialog
|
bf35452ef52ff6ee7739f87e6f12d552818cc7b4
|
[
"MIT"
] | 1
|
2020-07-09T12:50:26.000Z
|
2020-07-09T12:50:26.000Z
|
Models/QnAContext.cs
|
johnataylor/RemoteDialog
|
bf35452ef52ff6ee7739f87e6f12d552818cc7b4
|
[
"MIT"
] | null | null | null |
Models/QnAContext.cs
|
johnataylor/RemoteDialog
|
bf35452ef52ff6ee7739f87e6f12d552818cc7b4
|
[
"MIT"
] | 1
|
2019-04-10T12:30:43.000Z
|
2019-04-10T12:30:43.000Z
|
namespace RemoteDialog.Models
{
public class QnAContext
{
public QnAPrompts[] Prompts { get; set; }
}
}
| 15.625
| 49
| 0.616
|
40a7bf6b2bc83f57b58dc03cd74431d372fc7621
| 156
|
rb
|
Ruby
|
mod-picker/db/migrate/20160921193300_allow_null_usernames_for_invitations.rb
|
matortheeternal/mod-picker
|
a8a9d093c8bf644520837b47088b4ad3eca63ee3
|
[
"MIT"
] | 9
|
2020-06-30T23:55:57.000Z
|
2021-12-01T02:47:56.000Z
|
mod-picker/db/migrate/20160921193300_allow_null_usernames_for_invitations.rb
|
matortheeternal/mod-picker
|
a8a9d093c8bf644520837b47088b4ad3eca63ee3
|
[
"MIT"
] | null | null | null |
mod-picker/db/migrate/20160921193300_allow_null_usernames_for_invitations.rb
|
matortheeternal/mod-picker
|
a8a9d093c8bf644520837b47088b4ad3eca63ee3
|
[
"MIT"
] | null | null | null |
class AllowNullUsernamesForInvitations < ActiveRecord::Migration
def change
change_column :users, :username, :string, limit: 32, null: true
end
end
| 26
| 67
| 0.769231
|
33c3acf12c3870a6d5129a943e745ae3fa12e430
| 4,684
|
h
|
C
|
data_structure/graph/adjacency_list_graph.h
|
knguyenc/algorithms
|
4f61d692c986f6200eb1a52de022366a172aaa6f
|
[
"MIT"
] | null | null | null |
data_structure/graph/adjacency_list_graph.h
|
knguyenc/algorithms
|
4f61d692c986f6200eb1a52de022366a172aaa6f
|
[
"MIT"
] | null | null | null |
data_structure/graph/adjacency_list_graph.h
|
knguyenc/algorithms
|
4f61d692c986f6200eb1a52de022366a172aaa6f
|
[
"MIT"
] | null | null | null |
#ifndef ALGORITHM_DATA_STRUCTURE_ADJACENCY_LIST_GRAPH_H_
#define ALGORITHM_DATA_STRUCTURE_ADJACENCY_LIST_GRAPH_H_
#include <algorithm>
#include <iostream>
#include <vector>
namespace data_structure {
namespace graph {
template <class T>
class AdjacencyListGraph {
public:
class Vertex {
protected:
std::vector<Vertex *> adjacent_vertices_;
public:
T data_;
friend class AdjacencyListGraph;
explicit Vertex(const T &data) : data_(data) {}
protected:
void InsertAdjacentVertex(Vertex *dst) {
for (Vertex *v : adjacent_vertices_)
if (v->data_ == dst->data_)
throw std::runtime_error("The edge is already exist");
adjacent_vertices_.push_back(dst);
}
T RemoveAdjacentVertex(T dst_data) {
for (unsigned long i = 0; i < adjacent_vertices_.size(); i++) {
if (adjacent_vertices_[i]->data_ == dst_data) {
adjacent_vertices_.erase(adjacent_vertices_.begin() + i);
return dst_data;
}
}
throw std::runtime_error("The edge is not exist");
}
};
public:
AdjacencyListGraph();
~AdjacencyListGraph();
int Size() const;
bool IsEmpty() const;
void InsertEdge(const T &src, const T &dst);
T RemoveEdge(const T &src, const T &dst);
friend std::ostream &operator<<(std::ostream &out,
const AdjacencyListGraph &graph) {
if (graph.IsEmpty())
out << "Empty graph";
else {
out << "Breadth first traversal: ";
graph.BreadthFirst(out);
out << std::endl;
out << "Depth first traversal: ";
graph.DepthFirst(out);
}
return out;
}
protected:
void BreadthFirst(std::ostream &out) const;
void DepthFirst(std::ostream &out) const;
void DepthFirstRecursive(std::ostream &out, Vertex *v,
std::vector<T> &visited) const;
private:
std::vector<Vertex *> vertices_;
};
template <class T>
AdjacencyListGraph<T>::AdjacencyListGraph() {}
template <class T>
AdjacencyListGraph<T>::~AdjacencyListGraph() {
for (unsigned long i = 0; i < vertices_.size(); i++) delete vertices_[i];
}
template <class T>
int AdjacencyListGraph<T>::Size() const {
return vertices_.size();
}
template <class T>
bool AdjacencyListGraph<T>::IsEmpty() const {
return Size() == 0;
}
template <class T>
void AdjacencyListGraph<T>::InsertEdge(const T &src, const T &dst) {
Vertex *src_vertex = NULL, *dst_vertex = NULL;
for (unsigned long i = 0; i < vertices_.size(); i++) {
if (vertices_[i]->data_ == src) src_vertex = vertices_[i];
if (vertices_[i]->data_ == dst) dst_vertex = vertices_[i];
if (src_vertex != NULL && dst_vertex != NULL) break;
}
if (src_vertex == NULL) {
src_vertex = new Vertex(src);
vertices_.push_back(src_vertex);
}
if (dst_vertex == NULL) {
dst_vertex = new Vertex(dst);
vertices_.push_back(dst_vertex);
}
src_vertex->InsertAdjacentVertex(dst_vertex);
}
template <class T>
T AdjacencyListGraph<T>::RemoveEdge(const T &src, const T &dst) {
for (unsigned long i = 0; i < vertices_.size(); i++)
if (vertices_[i]->data_ == src)
return vertices_[i]->RemoveAdjacentVertex(dst);
throw std::runtime_error("The edge is not exist");
}
template <class T>
void AdjacencyListGraph<T>::BreadthFirst(std::ostream &out) const {
std::vector<T> visited;
for (Vertex *v : vertices_) {
if (!(std::find(visited.begin(), visited.end(), v->data_) !=
visited.end())) {
visited.push_back(v->data_);
out << "Vertex(" << v->data_ << ") ";
}
for (Vertex *av : v->adjacent_vertices_) {
if (!(std::find(visited.begin(), visited.end(), av->data_) !=
visited.end())) {
visited.push_back(av->data_);
out << "Vertex(" << av->data_ << ") ";
}
}
}
}
template <class T>
void AdjacencyListGraph<T>::DepthFirstRecursive(std::ostream &out, Vertex *v,
std::vector<T> &visited) const {
if (!(std::find(visited.begin(), visited.end(), v->data_) != visited.end())) {
visited.push_back(v->data_);
out << "Vertex(" << v->data_ << ") ";
}
for (Vertex *av : v->adjacent_vertices_)
if (!(std::find(visited.begin(), visited.end(), av->data_) !=
visited.end()))
DepthFirstRecursive(out, av, visited);
}
template <class T>
void AdjacencyListGraph<T>::DepthFirst(std::ostream &out) const {
if (IsEmpty()) return;
std::vector<T> visited;
for (unsigned long i = 0; i < vertices_.size(); i++)
DepthFirstRecursive(out, vertices_[i], visited);
}
} // namespace graph
} // namespace data_structure
#endif // ALGORITHM_DATA_STRUCTURE_ADJACENCY_LIST_GRAPH_H_
| 28.387879
| 80
| 0.631512
|
c3c02619030717c1073883a1bad90e53b2eaa72e
| 5,086
|
cs
|
C#
|
src/MvcDemo/Areas/Security/Controllers/UsersController.cs
|
macasoivan-wmsu/mvcdemo1
|
258983971d910613588dabbb49f00efbd3d44ff7
|
[
"MIT"
] | null | null | null |
src/MvcDemo/Areas/Security/Controllers/UsersController.cs
|
macasoivan-wmsu/mvcdemo1
|
258983971d910613588dabbb49f00efbd3d44ff7
|
[
"MIT"
] | null | null | null |
src/MvcDemo/Areas/Security/Controllers/UsersController.cs
|
macasoivan-wmsu/mvcdemo1
|
258983971d910613588dabbb49f00efbd3d44ff7
|
[
"MIT"
] | null | null | null |
using MvcDemo.Areas.Security.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcDemo.dal;
namespace MvcDemo.Areas.Security.Controllers
{
public class UsersController : Controller
{
private IList<UserViewModel> Users
{
get
{
if (Session["data"] == null)
{
Session["data"] = new List<UserViewModel>() {
new UserViewModel {
Id = Guid.NewGuid(),
FirstName = "John",
LastName = "Doe",
Age = 29,
Gender = "Male"
},
new UserViewModel {
Id = Guid.NewGuid(),
FirstName = "Jane",
LastName = "Doe",
Age = 33,
Gender = "Female"
}
};
}
return Session["data"] as List<UserViewModel>;
}
}
public ActionResult Index()
{
using (var db = new DatabaseContext())
{
var users = from user in db.Users.ToList()
select new UserViewModel
{
Id=user.Id,
FirstName = user.FirstName,
LastName = user.LastName,
Age = user.Age,
Gender = user.Gender
};
return View(Users);
}
}
// GET: Security/Users/Details/5
public ActionResult Details(Guid id, UserViewModel viewModel)
{
var u = Users.FirstOrDefault(user => user.Id == id);
return View(u);
}
// GET: Security/Users/Create
public ActionResult Create()
{
ViewBag.Genders = new List<SelectListItem> {
new SelectListItem
{
Value = "Male",
Text = "Male"
},
new SelectListItem
{
Value = "Female",
Text = "Female"
}
};
return View();
}
// POST: Security/Users/Create
[HttpPost]
public ActionResult Create(UserViewModel viewModel)
{
try
{
Users.Add(new UserViewModel
{
Id = Guid.NewGuid(),
FirstName = viewModel.FirstName,
LastName = viewModel.LastName,
Age = viewModel.Age,
Gender = viewModel.Gender
});
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Security/Users/Edit/5
public ActionResult Edit(Guid id)
{
var u = Users.FirstOrDefault(user => user.Id == id);
ViewBag.Genders = new List<SelectListItem> {
new SelectListItem
{
Value = "Male",
Text = "Male"
},
new SelectListItem
{
Value = "Female",
Text = "Female"
}
};
return View(u);
}
// POST: Security/Users/Edit/5
[HttpPost]
public ActionResult Edit(Guid id, UserViewModel viewModel)
{
try
{
var u = Users.FirstOrDefault(user => user.Id == id);
u.FirstName = viewModel.FirstName;
u.LastName = viewModel.LastName;
u.Age = viewModel.Age;
u.Gender = viewModel.Gender;
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Security/Users/Delete/5
public ActionResult Delete(Guid id)
{
var u = Users.FirstOrDefault(user => user.Id == id);
return View(u);
}
// POST: Security/Users/Delete/5
[HttpPost]
public ActionResult Delete(Guid id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
var u = Users.FirstOrDefault(user => user.Id == id);
Users.Remove(u);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
| 29.398844
| 71
| 0.382226
|
e6c2490d4a731bbdbcd4baf3f68eeffa21536887
| 2,433
|
h
|
C
|
AvatarUI.framework/AVTAvatarActionsModel.h
|
reels-research/iOS-Private-Frameworks
|
9a4f4534939310a51fdbf5a439dd22487efb0f01
|
[
"MIT"
] | 4
|
2021-10-06T12:15:26.000Z
|
2022-02-21T02:26:00.000Z
|
AvatarUI.framework/AVTAvatarActionsModel.h
|
reels-research/iOS-Private-Frameworks
|
9a4f4534939310a51fdbf5a439dd22487efb0f01
|
[
"MIT"
] | null | null | null |
AvatarUI.framework/AVTAvatarActionsModel.h
|
reels-research/iOS-Private-Frameworks
|
9a4f4534939310a51fdbf5a439dd22487efb0f01
|
[
"MIT"
] | 1
|
2021-10-08T07:40:53.000Z
|
2021-10-08T07:40:53.000Z
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/AvatarUI.framework/AvatarUI
*/
@interface AVTAvatarActionsModel : NSObject <AVTAvatarEditorViewControllerDelegate> {
AVTAvatarRecord * _avatarRecord;
AVTViewSessionProvider * _avtViewSessionProvider;
bool _buttonsDisabled;
NSArray * _currentInlineActionButtons;
AVTAvatarRecordDataSource * _dataSource;
<AVTAvatarActionsModelDelegate> * _delegate;
AVTUIEnvironment * _environment;
bool _isCreatingAvatar;
}
@property (nonatomic, retain) AVTAvatarRecord *avatarRecord;
@property (nonatomic, readonly) AVTViewSessionProvider *avtViewSessionProvider;
@property (nonatomic) bool buttonsDisabled;
@property (nonatomic, retain) NSArray *currentInlineActionButtons;
@property (nonatomic, readonly) AVTAvatarRecordDataSource *dataSource;
@property (readonly, copy) NSString *debugDescription;
@property (nonatomic) <AVTAvatarActionsModelDelegate> *delegate;
@property (readonly, copy) NSString *description;
@property (nonatomic, readonly) AVTUIEnvironment *environment;
@property (readonly) unsigned long long hash;
@property (nonatomic, readonly) NSArray *inlineActionButtons;
@property (nonatomic) bool isCreatingAvatar;
@property (readonly) Class superclass;
+ (bool)actionIsDestructive:(long long)arg1;
+ (id)buttonForActionType:(long long)arg1 withActionBlock:(id /* block */)arg2;
+ (id)localizedTitleForActionType:(long long)arg1;
- (void).cxx_destruct;
- (void)avatarEditorViewController:(id)arg1 didFinishWithAvatarRecord:(id)arg2;
- (void)avatarEditorViewControllerDidCancel:(id)arg1;
- (id)avatarRecord;
- (id)avtViewSessionProvider;
- (bool)buttonsDisabled;
- (bool)canPerformActionType:(long long)arg1;
- (id)createBarButtonItem;
- (id)currentInlineActionButtons;
- (id)dataSource;
- (id)delegate;
- (void)didTapCreateNew:(id)arg1;
- (void)didTapDelete;
- (void)didTapDuplicate;
- (void)didTapEdit;
- (id)environment;
- (id)generateInlineActionButtons;
- (id)initWithAvatarRecord:(id)arg1 dataSource:(id)arg2 avtViewSessionProvider:(id)arg3 environment:(id)arg4;
- (id)inlineActionButtons;
- (bool)isCreatingAvatar;
- (void)presentEditor:(id)arg1 forCreating:(bool)arg2;
- (void)setAvatarRecord:(id)arg1;
- (void)setButtonsDisabled:(bool)arg1;
- (void)setCurrentInlineActionButtons:(id)arg1;
- (void)setDelegate:(id)arg1;
- (void)setIsCreatingAvatar:(bool)arg1;
- (void)updateForChangedContentCategorySize;
@end
| 38.619048
| 109
| 0.792437
|
52805992033f332b77d20ef74e72e3390b7d1411
| 71
|
rb
|
Ruby
|
lib/inspec/plugin/v1.rb
|
multani/inspec
|
29feee9b0003f68736d2c9e4f1121115820749f1
|
[
"Apache-2.0"
] | 1,348
|
2018-05-28T01:38:16.000Z
|
2022-03-30T06:21:06.000Z
|
lib/inspec/plugin/v1.rb
|
multani/inspec
|
29feee9b0003f68736d2c9e4f1121115820749f1
|
[
"Apache-2.0"
] | 2,967
|
2018-05-27T23:00:51.000Z
|
2022-03-31T23:32:20.000Z
|
lib/inspec/plugin/v1.rb
|
multani/inspec
|
29feee9b0003f68736d2c9e4f1121115820749f1
|
[
"Apache-2.0"
] | 458
|
2018-05-31T13:41:20.000Z
|
2022-03-23T17:28:23.000Z
|
require "inspec/plugin/v1/plugins"
require "inspec/plugin/v1/registry"
| 23.666667
| 35
| 0.802817
|
795d9e148c0d0ca6f0745c5fc4737e4b73ce18dd
| 3,173
|
php
|
PHP
|
frontend/messages/th/lan.php
|
tongfreedom/building
|
f473d108f9e41414b7bbd505b9d6101cd7b5275f
|
[
"BSD-3-Clause"
] | null | null | null |
frontend/messages/th/lan.php
|
tongfreedom/building
|
f473d108f9e41414b7bbd505b9d6101cd7b5275f
|
[
"BSD-3-Clause"
] | null | null | null |
frontend/messages/th/lan.php
|
tongfreedom/building
|
f473d108f9e41414b7bbd505b9d6101cd7b5275f
|
[
"BSD-3-Clause"
] | null | null | null |
<?php
return [
'TGDE' => 'สถาบันสหกิจศึกษาและพัฒนาสื่ออิเล็กทรอนิกส์ไทย-เยอรมัน',
'Dual Education' => 'สหกิจศึกษา',
'Search' => 'ค้นหาที่นี่',
'Home' => 'หน้าหลัก',
'About Us' => 'เกี่ยวกับเรา',
'About' => 'เกี่ยวกับเรา',
'Develop' => 'พัฒนาสื่อ',
'Portfolio' => 'ผลงาน',
'Contact Us' => 'ติดต่อเรา',
'Contact' => 'ติดต่อเรา',
'Office' => 'สำนักงาน',
'News' => 'ข่าว',
'Promote News' => 'ข่าวประชาสัมพันธ์',
'Dual Education News' => 'ข่าวสารสหกิจศึกษา',
'read more' => 'อ่านต่อ',
'Portfolio' => 'ผลงาน',
'TGDE' => 'สถาบันสหกิจศึกษาและพัฒนาสื่ออิเล็กทรอนิกส์ไทย-เยอรมัน',
'Dual Education' => 'สหกิจศึกษา',
'Vision' => 'ปรัชญา ปณิธาน วิสัยทัศน์ อัตลักษณ์',
'Knowledge' => 'องค์ความรู้',
'Article' => 'บทความ',
'VDO' => 'คลังวีดีโอ',
'Video' => 'คลังวีดีโอ',
'Gallery' => 'คลังรูปภาพ',
'FAQ' => 'คำถามที่พบบ่อย',
'Document' => 'เอกสาร',
'Services' => 'บริการของหน่วยงาน',
'Show All' => 'แสดงทั้งหมด',
'Views' => 'ผู้เข้าชม',
'Please Type Search' => 'พิมพ์คำที่ต้องการค้นหาและกด',
'Pantagit' => 'พันธกิจ',
'Team' => 'บุคลากร',
'Organization Chart' => 'โครงสร้างองค์กร',
'Address' => 'ที่อยู่',
'Phone' => 'โทร',
'Email' => 'อีเมล',
'Work Time' => 'เวลาทำการ',
'Subscribe' => 'รับข่าวสาร',
'Newsletter' => 'จดหมายข่าว',
'Enter your Email' => 'กรุณากรอกอีเมล',
'Popular News' => 'ข่าวยอดนิยม',
'Popular Articles' => 'บทความยอดนิยม',
'Popular Portfolios' => 'ผลงานยอดนิยม',
'Vdo' => 'คลังวีดีโอ',
'Faq' => 'คำถามที่พบบ่อย',
'Contact' => 'ติดต่อเรา',
'Address & Map' => 'ที่อยู่ & แผนที่',
'Get In Touch' => 'Get In Touch',
'Name' => 'ชื่อ',
'Subject' => 'หัวข้อ',
'Message' => 'รายละเอียด',
'Send Message' => 'ส่งข้อความ',
'Team' => 'บุคลากร',
'Document Type' => 'ประเภทเอกสาร',
'Document All' => 'เอกสารทั้งหมด',
'We have <strong>successfully</strong> received your Message and will get Back to you as soon as possible.' => 'เราได้รับข้อความของคุณและจะทำการตอบกลับมาให้คุณโดยเร็วที่สุดเท่าที่เป็นไปได้',
'Error!' => 'ผิดพลาด !',
'Develop News' => 'ข่าวสารพัฒนาสื่อ',
'Download Document' => 'เอกสารดาวน์โหลด',
'Dual Education Database' => 'ระบบฐานข้อมูลสหกิจศึกษา',
'Develop' => 'พัฒนาสื่อ',
'External Link' => 'ลิ้งค์ที่เกี่ยวข้อง',
'copyright' => '© TGDE - สถาบันสหกิจศึกษาและพัฒนาสื่ออิเล็กรอกนิกส์ ไทย-เยอรมัน , All Rights Reserved. ',
'View Gallery All' => 'ดูคลังรูปภาพทั้งหมด',
'View Video All' => 'ดูคลังวีดีโอทั้งหมด',
'Company Joined' => 'สถานประกอบการที่เข้าร่วมโครงการ',
'Post by' => 'ผู้เขียน',
'User Views' => 'จำนวนผู้เข้าชม',
'Create Date' => 'วันที่สร้าง',
'Update Date' => 'แก้ไขล่าสุด',
'Post by' => 'ผู้เขียน',
'Type' => 'ประเภท',
'Email Message' => 'ส่งข้อความถึงเรา',
'Enter Your Name' => 'โปรดระบุชื่อ-นามสกุล ของท่าน',
'Enter Your Email' => 'โปรดระบุอีเมล ของท่าน',
'Enter Subject....' => 'โปรดระบุหัวข้อ....',
'Enter Message....' => 'โปรดระบุรายละเอียด....',
'Send message' => 'ส่งข้อความ',
'Knowledge Management' => 'การจัดการความรู้',
'Annouce & Tender' => 'ประกาศ/ประกวดราคา',
'View Annouce & Tender All' => 'ดูข่าวประกาศ/ประกวดราคาทั้งหมด',
'view detail' => 'รายละเอียด',
];
| 37.329412
| 192
| 0.568232
|
3855e7f0b52820112bd51499b5b08aeb0e7df552
| 448
|
php
|
PHP
|
app/Http/Controllers/BlogController.php
|
nour-hejazi/blog
|
0d862b0c1bb9e796f936f2dc1d1e5a088fd4a14e
|
[
"MIT"
] | 1
|
2018-10-01T07:57:06.000Z
|
2018-10-01T07:57:06.000Z
|
app/Http/Controllers/BlogController.php
|
nour-hejazi/blog
|
0d862b0c1bb9e796f936f2dc1d1e5a088fd4a14e
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/BlogController.php
|
nour-hejazi/blog
|
0d862b0c1bb9e796f936f2dc1d1e5a088fd4a14e
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Comment;
use App\Post;
class BlogController extends Controller{
public function getIndex(){
$posts = Post::paginate(2);
return view('blog.index')->withPosts($posts);
}
public function getSingle($id){
$post = Post::where('id', '=', $id)->first();
$comments = Comment::all();
return view('blog.single', compact(['post', '$comments']));
}
}
| 13.575758
| 61
| 0.647321
|
72c5e4e3d439ed887d2c27cf8229fbdfe84e65b2
| 2,773
|
cs
|
C#
|
ExamPreparation2017January/SoftuniKaraoki1/Program.cs
|
stoyantodorovbg/Programming-Fundamentals
|
34e9478c292c40874f7394f3b0992b7bd9678c10
|
[
"MIT"
] | null | null | null |
ExamPreparation2017January/SoftuniKaraoki1/Program.cs
|
stoyantodorovbg/Programming-Fundamentals
|
34e9478c292c40874f7394f3b0992b7bd9678c10
|
[
"MIT"
] | null | null | null |
ExamPreparation2017January/SoftuniKaraoki1/Program.cs
|
stoyantodorovbg/Programming-Fundamentals
|
34e9478c292c40874f7394f3b0992b7bd9678c10
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftuniKaraoki1
{
class Program
{
static void Main(string[] args)
{
var participants = Console.ReadLine()
.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
var songs = Console.ReadLine()
.Split(',')
.Select(s => s.Trim(' '))
.ToArray();
var result = new Dictionary<string, List<string>>();
var containsPerformance = false;
while (true)
{
var performance = Console.ReadLine()
.Split(',')
.Select(s => s.Trim(' '))
.ToArray();
if (performance[0] == "dawn")
{
break;
}
if (performance[0] != "dawn")
{
containsPerformance = true;
}
var participant = performance[0];
var song = performance[1];
var award = performance[2];
var awards = new List<string>();
awards.Add(award);
if (participants.Contains(participant) && songs.Contains(song))
{
if (!result.ContainsKey(participant))
{
result[participant] = awards;
}
else
{
var contains = false;
for (int i = 0; i < result[participant].Count; i++)
{
if (result[participant][i] == award)
{
contains = true;
}
}
if (!contains)
{
result[participant].AddRange(awards);
}
}
}
}
if (containsPerformance)
{
foreach (var item in result.OrderByDescending(i => i.Value.Count).ThenBy(i => i.Key))
{
Console.WriteLine($"{item.Key}: {item.Value.Count} awards");
foreach (var award in item.Value.OrderBy(n => n))
{
Console.WriteLine($"--{award}");
}
}
}
else
{
Console.WriteLine("No awards");
}
}
}
}
| 27.73
| 101
| 0.367111
|
40289c58c0a21ae5f7e8999f4540098feec0f0b1
| 810
|
rb
|
Ruby
|
lib/et_fake_ccd/command/login_user_command.rb
|
hmcts/et-fake-ccd
|
d040ae727744973c2ba52829e757594a3b65b6e1
|
[
"MIT"
] | null | null | null |
lib/et_fake_ccd/command/login_user_command.rb
|
hmcts/et-fake-ccd
|
d040ae727744973c2ba52829e757594a3b65b6e1
|
[
"MIT"
] | 3
|
2020-10-14T08:43:00.000Z
|
2021-11-15T08:30:39.000Z
|
lib/et_fake_ccd/command/login_user_command.rb
|
hmcts/et-fake-ccd
|
d040ae727744973c2ba52829e757594a3b65b6e1
|
[
"MIT"
] | 1
|
2021-04-10T22:54:17.000Z
|
2021-04-10T22:54:17.000Z
|
require 'active_model'
module EtFakeCcd
module Command
class LoginUserCommand
include ActiveModel::Model
include ActiveModel::Attributes
def initialize(config: ::EtFakeCcd::Config.instance, **args)
self.config = config
super(**args)
end
attribute :username
attribute :password
def self.from_json(json)
new username: json['username'], password: json['password']
end
validate :validate_username_and_password
private
attr_accessor :config
def validate_username_and_password
return if config.valid_credentials.any? do |cred|
username == cred[:username] && password == cred[:password]
end
errors.add(:username, "Invalid username or password")
end
end
end
end
| 22.5
| 68
| 0.650617
|
96f7f4d25ba8b9cde47fb76b5196aa4c573d2fe0
| 2,204
|
cs
|
C#
|
Finished sample/BethanysPieShopHRM.Server/Services/EmployeeDataService.cs
|
274188A/BlazorAuthenticationAndAuthorization
|
c190333d95449ecc4aecf36c07eb84f3974fc0b9
|
[
"MIT"
] | null | null | null |
Finished sample/BethanysPieShopHRM.Server/Services/EmployeeDataService.cs
|
274188A/BlazorAuthenticationAndAuthorization
|
c190333d95449ecc4aecf36c07eb84f3974fc0b9
|
[
"MIT"
] | null | null | null |
Finished sample/BethanysPieShopHRM.Server/Services/EmployeeDataService.cs
|
274188A/BlazorAuthenticationAndAuthorization
|
c190333d95449ecc4aecf36c07eb84f3974fc0b9
|
[
"MIT"
] | null | null | null |
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using BethanysPieShopHRM.Shared;
using Microsoft.AspNetCore.Http;
namespace BethanysPieShopHRM.Server.Services
{
public class EmployeeDataService : IEmployeeDataService
{
private readonly HttpClient _httpClient;
public EmployeeDataService(HttpClient httpClient, IHttpContextAccessor httpContextAccessor)
{
_httpClient = httpClient ?? throw new System.ArgumentNullException(nameof(httpClient));
}
public async Task<IEnumerable<Employee>> GetAllEmployees()
{
return await JsonSerializer.DeserializeAsync<IEnumerable<Employee>>
(await _httpClient.GetStreamAsync($"api/employee"), new JsonSerializerOptions()
{ PropertyNameCaseInsensitive = true });
}
public async Task<Employee> GetEmployeeDetails(int employeeId)
{
return await JsonSerializer.DeserializeAsync<Employee>
(await _httpClient.GetStreamAsync($"api/employee/{employeeId}"),
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
public async Task<Employee> AddEmployee(Employee employee)
{
var employeeJson =
new StringContent(JsonSerializer.Serialize(employee), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("api/employee", employeeJson);
if (response.IsSuccessStatusCode)
{
return await JsonSerializer.DeserializeAsync<Employee>(await response.Content.ReadAsStreamAsync());
}
return null;
}
public async Task UpdateEmployee(Employee employee)
{
var employeeJson =
new StringContent(JsonSerializer.Serialize(employee), Encoding.UTF8, "application/json");
await _httpClient.PutAsync("api/employee", employeeJson);
}
public async Task DeleteEmployee(int employeeId)
{
await _httpClient.DeleteAsync($"api/employee/{employeeId}");
}
}
}
| 34.984127
| 115
| 0.65971
|
b63bb9ef74ddfe41bef7285fff5d1edd1e109d7b
| 1,873
|
rb
|
Ruby
|
lib/kymera/platform_utils.rb
|
jakesa/kymera
|
54aa1452f7fe083bdd18e545cf5b2c926885f445
|
[
"MIT"
] | 2
|
2015-10-14T17:08:31.000Z
|
2017-09-25T09:27:32.000Z
|
lib/kymera/platform_utils.rb
|
jakesa/kymera
|
54aa1452f7fe083bdd18e545cf5b2c926885f445
|
[
"MIT"
] | null | null | null |
lib/kymera/platform_utils.rb
|
jakesa/kymera
|
54aa1452f7fe083bdd18e545cf5b2c926885f445
|
[
"MIT"
] | null | null | null |
require 'socket'
module Kymera
def self.processor_count
@processor_count ||= case RbConfig::CONFIG['host_os']
when /darwin9/
`hwprefs cpu_count`.to_i
when /darwin/
(hwprefs_available? ? `hwprefs thread_count` : `sysctl -n hw.ncpu`).to_i
when /linux|cygwin/
`grep -c ^processor /proc/cpuinfo`.to_i
when /(net|open|free)bsd/
`sysctl -n hw.ncpu`.to_i
when /mswin|mingw/
require 'win32ole'
wmi = WIN32OLE.connect("winmgmts://")
cpu = wmi.ExecQuery("select NumberOfLogicalProcessors from Win32_Processor")
cpu.to_enum.first.NumberOfLogicalProcessors
when /solaris2/
`psrinfo -p`.to_i # this is physical cpus afaik
else
$stderr.puts "Unknown architecture ( #{RbConfig::CONFIG["host_os"]} ) assuming one processor."
1
end
end
def self.hwprefs_available?
avail = true
begin
`hwprefs`
rescue
avail = false
end
avail
end
def self.is_linux?
case RbConfig::CONFIG['host_os']
when /linux|darwin/
true
else
false
end
end
def self.is_windows?
case RbConfig::CONFIG['host_os']
when /mswin|mingw/
true
else
false
end
end
def self.ip_address
ips = Socket.ip_address_list
ip = ''
ips.each do |i|
ip = i.ip_address if i.ipv4? && i.ip_address.start_with?("10")
end
ip
end
def self.ruby_version
RbConfig::CONFIG["RUBY_VERSION_NAME"]
end
def self.os
"#{RbConfig::CONFIG["host_vendor"]} #{RbConfig::CONFIG["host_os"]} #{RbConfig::CONFIG["host_cpu"]}"
end
def self.host_name
Socket.gethostname
end
def self.wait_for(&block)
found = false
i = 0
until i == 60 || found
found = yield
sleep 1
i +=1
end
found
end
end
| 20.811111
| 103
| 0.597437
|
258ccf4e9bd6bbb4b1dbd3106c4e94e89c64fd8b
| 3,728
|
cs
|
C#
|
MediaBrowser.Theater.Interfaces/SerializableDictionary.cs
|
thogil/MediaBrowser.Theater
|
2deb62df4a9d1093f3fb44017711be6b10a63906
|
[
"MIT"
] | null | null | null |
MediaBrowser.Theater.Interfaces/SerializableDictionary.cs
|
thogil/MediaBrowser.Theater
|
2deb62df4a9d1093f3fb44017711be6b10a63906
|
[
"MIT"
] | null | null | null |
MediaBrowser.Theater.Interfaces/SerializableDictionary.cs
|
thogil/MediaBrowser.Theater
|
2deb62df4a9d1093f3fb44017711be6b10a63906
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Schema;
namespace MediaBrowser.Theater.Interfaces
{
/// <summary>
/// A Serializable Dictionary
/// </summary>
/// <typeparam name="TKey">
/// The Key Type
/// </typeparam>
/// <typeparam name="TValue">
/// The Value Type
/// </typeparam>
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members
/// <summary>
/// Get the Schema
/// </summary>
/// <returns>
/// Nothing. We don't use this.
/// </returns>
public XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Deserialize some XML into a dictionary
/// </summary>
/// <param name="reader">
/// The reader.
/// </param>
public void ReadXml(XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value;
if (reader.Name.Contains("ArrayOfString"))
{
XmlSerializer scSerializer = new XmlSerializer(typeof(StringCollection));
value = (TValue)scSerializer.Deserialize(reader);
}
else
{
value = (TValue)valueSerializer.Deserialize(reader);
}
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
/// <summary>
/// Write the Dictionary out to XML
/// </summary>
/// <param name="writer">
/// The writer.
/// </param>
public void WriteXml(XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
if (value.GetType() == typeof(StringCollection))
{
XmlSerializer scSerializer = new XmlSerializer(typeof(StringCollection));
scSerializer.Serialize(writer, value);
writer.WriteEndElement();
}
else
{
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
#endregion
}
}
| 29.824
| 98
| 0.524678
|
7b44588031d0f6b7435b214ee0ebf77dc2eb2567
| 3,272
|
swift
|
Swift
|
xjf-ios-mvvm/Modules/Carousel/View/CarouselViewController.swift
|
HaiTeng-Wang/Swift-VIPER-Rx
|
33f07bcbf511bda653324718c554e2da3aab44d5
|
[
"MIT"
] | 25
|
2017-12-11T09:29:07.000Z
|
2021-09-30T13:04:50.000Z
|
xjf-ios-mvvm/Modules/Carousel/View/CarouselViewController.swift
|
HaiTeng-Wang/Swift-VIPER-Rx
|
33f07bcbf511bda653324718c554e2da3aab44d5
|
[
"MIT"
] | null | null | null |
xjf-ios-mvvm/Modules/Carousel/View/CarouselViewController.swift
|
HaiTeng-Wang/Swift-VIPER-Rx
|
33f07bcbf511bda653324718c554e2da3aab44d5
|
[
"MIT"
] | 2
|
2018-01-25T09:42:55.000Z
|
2018-03-26T04:42:17.000Z
|
//
// CarouselCarouselViewController.swift
// xjf-ios-mvvm
//
// Created by xijinfa on 18/01/2017.
// Copyright © 2017 xijinfa. All rights reserved.
//
import UIKit
import Kingfisher
import RxSwift
import AppData
class CarouselViewController: UIViewController, CarouselViewInput, iCarouselDataSource, iCarouselDelegate {
var output: CarouselViewOutput!
var bannerData: [BannerData]?
var path: String?
let disposebag = DisposeBag()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(path: String) {
self.init(nibName: nil, bundle: nil)
self.path = path
}
private lazy var carsouselView: iCarousel = {
return iCarousel()
}()
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
view = carsouselView
carsouselView.isPagingEnabled = true
carsouselView.bounces = false
carsouselView.delegate = self
carsouselView.dataSource = self
}
// MARK: CarouselViewInput
func setupInitialState() {
}
func setBanner(banner: Banner) {
print("onNext I found errCode \(String(describing: banner.errCode))!")
print("onNext I found \(String(describing: banner.result?.data?[0].title))!")
self.bannerData = banner.result?.data
self.carsouselView.reloadData()
}
func loadBannerData() {
output.loadBannerData(path: path ?? "")
}
func numberOfItems(in carousel: iCarousel) -> Int {
return bannerData?.count ?? 0
}
func imageTapped() {
let position = carsouselView.currentItemIndex
Logger.logInfo(message: "imageTapped \(String(describing: bannerData?[position].link))!")
var params = Dictionary<String, String>()
params.updateValue("51215", forKey:"category_id")
if let bannerItem = bannerData?[position] {
let link = bannerItem.link
MainRouter.jumpByType(naviVC: self.topNavigationController, link: link)
}
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
let screenWidth = UIScreen.main.bounds.width
let tempView = UIView(frame: CGRect(x:0, y:0, width:screenWidth, height:160))
let frame = CGRect(x:0, y:0, width:screenWidth, height:160)
let imageView = UIImageView()
imageView.frame = frame
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
let tap = UITapGestureRecognizer(target: self, action: #selector(CarouselViewController.imageTapped))
imageView.addGestureRecognizer(tap)
imageView.isUserInteractionEnabled = true
if let banners = bannerData {
if let cover = banners[index].cover {
if let url = cover[0].url {
print("image url: \(url)")
imageView.kf.setImage(with: URL(string: url))
}
}
}
tempView.addSubview(imageView)
return tempView
}
}
| 29.214286
| 109
| 0.63967
|
293604f004ed932dbe3e43aceb7b8a3ceeeb4cb8
| 5,656
|
dart
|
Dart
|
bin/src/file_creator_helper.dart
|
jorre127/icapps_generatorV2
|
22348806f8231773a22487dd820e1a431ca305f3
|
[
"MIT"
] | null | null | null |
bin/src/file_creator_helper.dart
|
jorre127/icapps_generatorV2
|
22348806f8231773a22487dd820e1a431ca305f3
|
[
"MIT"
] | null | null | null |
bin/src/file_creator_helper.dart
|
jorre127/icapps_generatorV2
|
22348806f8231773a22487dd820e1a431ca305f3
|
[
"MIT"
] | null | null | null |
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart';
import 'case_util.dart';
class FileCreatorHelper {
FileCreatorHelper._();
static void createViewModelFile(String screenName, {required bool generateInjectable}) {
final sb = StringBuffer()..writeln("import 'package:icapps_architecture/icapps_architecture.dart';");
if (generateInjectable) {
sb
..writeln("import 'package:injectable/injectable.dart';")
..writeln()
..writeln('@injectable');
} else {
sb.writeln();
}
sb
..writeln('class ${CaseUtil.getCamelcase(screenName)}ViewModel with ChangeNotifierEx{')
..writeln(' late final ${CaseUtil.getCamelcase(screenName)}Navigator _navigator;')
..writeln()
..writeln(' Future<void> init(${CaseUtil.getCamelcase(screenName)}Navigator navigator) async {')
..writeln(' _navigator = navigator;')
..writeln(' }')
..writeln('}')
..writeln()
..writeln('abstract class ${CaseUtil.getCamelcase(screenName)}Navigator {}');
// Write to file
File(join('lib', 'viewmodel', screenName, '${screenName}_viewmodel.dart')).writeAsStringSync(sb.toString());
}
static void createScreenFile(String projectName, String screenName) {
final sb = StringBuffer()
..writeln("import 'package:$projectName/viewmodel/$screenName/${screenName}_viewmodel.dart';")
..writeln("import 'package:$projectName/widget/provider/provider_widget.dart';")
..writeln("import 'package:get_it/get_it.dart';")
..writeln("import 'package:flutter/material.dart';")
..writeln()
..writeln('class ${CaseUtil.getCamelcase(screenName)}Screen extends StatefulWidget {')
..writeln(" static const String routeName = '$screenName';")
..writeln()
..writeln(' const ${CaseUtil.getCamelcase(screenName)}Screen({Key? key}) : super(key: key);')
..writeln()
..writeln(' @override')
..writeln(' _${CaseUtil.getCamelcase(screenName)}ScreenState createState() => _${CaseUtil.getCamelcase(screenName)}ScreenState();')
..writeln('}')
..writeln()
..writeln(
'class _${CaseUtil.getCamelcase(screenName)}ScreenState extends State<${CaseUtil.getCamelcase(screenName)}Screen> implements ${CaseUtil.getCamelcase(screenName)}Navigator {')
..writeln(' @override')
..writeln(' Widget build(BuildContext context) {')
..writeln(' return ProviderWidget<${CaseUtil.getCamelcase(screenName)}ViewModel>(')
..writeln(' create: () => GetIt.I.get()..init(this),')
..writeln(' childBuilderWithViewModel: (context, viewModel, theme, localization) => const Scaffold(')
..writeln(' body: Center(),')
..writeln(' ),')
..writeln(' );')
..writeln(' }')
..writeln('}');
// Write to file
File(join('lib', 'screen', screenName, '${screenName}_screen.dart')).writeAsStringSync(sb.toString());
}
static Future<void> updateMainNavigator(String projectName, String screenName) async {
final mainNavigatorFile = File(join('lib', 'navigator', 'main_navigator.dart'));
if (!mainNavigatorFile.existsSync()) {
print('`lib/navigator/main_navigator.dart` does not exists. Can not add navigation logic.');
return;
}
final sb = StringBuffer()
..writeln("import 'package:$projectName/screen/$screenName/${screenName}_screen.dart';")
..writeln("import 'package:$projectName/widget/general/flavor_banner.dart';");
var writeOnGenerateRoute = false;
var overrideMissing = false;
await mainNavigatorFile.openRead().transform(const Utf8Decoder()).transform(const LineSplitter()).forEach((l) {
if (l == ' Route? onGenerateRoute(RouteSettings settings) {') {
writeOnGenerateRoute = true;
}
if (l == ' default:' && writeOnGenerateRoute) {
sb
..writeln(' case ${CaseUtil.getCamelcase(screenName)}Screen.routeName:')
..writeln(' return MaterialPageRoute(builder: (context) => const FlavorBanner(child: ${CaseUtil.getCamelcase(screenName)}Screen()), settings: settings);');
}
if (l == ' void closeDialog<T>({T? result}) => Navigator.of(context, rootNavigator: true).pop(result);') {
overrideMissing = true;
sb
..writeln(' void goTo${CaseUtil.getCamelcase(screenName)}() => navigationKey.currentState?.pushNamed(${CaseUtil.getCamelcase(screenName)}Screen.routeName);')
..writeln();
}
if (l != "import 'package:$projectName/widgets/general/flavor_banner.dart';") {
if (overrideMissing) {
overrideMissing = false;
sb
..writeln(' @override')
..writeln(l);
} else {
sb.writeln(l);
}
}
}).whenComplete(() {});
mainNavigatorFile.writeAsStringSync(sb.toString());
}
static Future<void> updateMainNavigation(String projectName, String screenName) async {
final mainNavigationFile = File(join('lib', 'navigator', 'main_navigation.dart'));
if (!mainNavigationFile.existsSync()) {
print('`lib/navigator/main_navigation.dart` does not exists. Can not add navigation logic.');
return;
}
final sb = StringBuffer();
await mainNavigationFile.openRead().transform(const Utf8Decoder()).transform(const LineSplitter()).forEach((l) {
sb.writeln(l);
if (l == ' void goBack<T>({T? result});') {
sb
..writeln()
..writeln(' void goTo${CaseUtil.getCamelcase(screenName)}();');
}
}).whenComplete(() {});
mainNavigationFile.writeAsStringSync(sb.toString());
}
}
| 43.844961
| 184
| 0.641266
|
e741c8e537f282001f232b6a3193237860a36bb9
| 6,110
|
php
|
PHP
|
app/views/jj/index.blade.php
|
shalaaoao/mushroom
|
c49891c8bf61bcd264949e230d14a2f3c1ac3cde
|
[
"MIT"
] | null | null | null |
app/views/jj/index.blade.php
|
shalaaoao/mushroom
|
c49891c8bf61bcd264949e230d14a2f3c1ac3cde
|
[
"MIT"
] | null | null | null |
app/views/jj/index.blade.php
|
shalaaoao/mushroom
|
c49891c8bf61bcd264949e230d14a2f3c1ac3cde
|
[
"MIT"
] | null | null | null |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<!-- saved from url=(0054)http://www.html5tricks.com/demo/jiaoben1892/index.html -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><HTML
xmlns="http://www.w3.org/1999/xhtml"><HEAD><META content="IE=10.000"
http-equiv="X-UA-Compatible">
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>HAPPY BIRTHDAY TO JINGJING</TITLE>
<STYLE type="text/css">
@font-face {
font-family: digit;
src: url('digital-7_mono.ttf') format("truetype");
}
</STYLE>
<LINK href="/assets/css/default.css" rel="stylesheet" type="text/css">
<SCRIPT src="/assets/js/jquery.js" type="text/javascript"></SCRIPT>
<SCRIPT src="/assets/js/garden.js" type="text/javascript"></SCRIPT>
<SCRIPT src="/assets/js/functions.js" type="text/javascript"></SCRIPT>
<META name="GENERATOR" content="MSHTML 10.00.9200.17357"></HEAD>
<BODY>
<DIV style="text-align: center; clear: both;">
<!--<SCRIPT src="1/gg_bd_ad_720x90.js" type="text/javascript"></SCRIPT>-->
<SCRIPT src="/assets/js/follow.js" type="text/javascript"></SCRIPT>
<DIV id="mainDiv">
<DIV id="content">
<DIV id="code">
<SPAN class="comments">/**</SPAN><BR><SPAN class="space"><SPAN class="comments">*1994—12-10,</SPAN><BR>
<SPAN class="space"><SPAN class="comments">*2016-12-10.</SPAN><BR><SPAN class="space"><SPAN class="comments">*/</SPAN><BR>
Birthday people name = <SPAN class="keyword">Miss</SPAN> JingJing Wen<BR><SPAN class="comments">//The girl's birthday 22st anniversary of the day. </SPAN><BR>
Forgive my word is poor.<BR><SPAN class="comments">//In addition to happy birthday to you.I don't know what to say.</SPAN><BR>
Say these similar to wish you good health happy every day;<BR><SPAN class="comments">//In a short period of time,</SPAN><BR>
I can't think of what to say,although I racked my brains.<BR><SPAN class="comments">//Maybe the programming using me abundant energy(Smile~),</SPAN><BR>
Maybe we have said so much more ordinarily.<BR><SPAN class="comments">// Program ape shortcomings is this</SPAN><BR>
(wo de ying yu hen cha a ,fan yi hao nan a...) <BR><SPAN class="comments">// I'm curious about when you receive the sunflowers, when you receive the chocolate, when you enjoying my music, and then when you receive this web.</SPAN><BR><SPAN class="comments">// Happy or Surprise or touched or the other?</SPAN><BR><SPAN class="keyword"></SPAN><span>"Nice to meet you" is the expression last ten years. </span><br/><SPAN class="keyword">"What's up" is the correct expression nowadays</SPAN>;<BR><SPAN class="keyword">I </SPAN> admire my this way of greeting...<br/><SPAN class="keyword">"A Chinese Ghost Story" is a good game, but I really don't have the time to play it, and I am too old to interested in it... </SPAN>;<BR><SPAN class="placeholder"><SPAN class="comments">//In addition,if you are willing to eat eat eat,I will take you to anyway anytime.</SPAN><BR><SPAN class="comments">Why?</SPAN><BR><SPAN class="placeholder"><SPAN class="comments">//Because,I also like to do it. :)</SPAN><BR><SPAN class="placeholder">I may at any time for BB with you, and I wish the same to you. <BR>
Miracles happen every day,<BR>
Sincerely wishing you happy every day;<BR>
</SPAN>
<div style="text-align:right;">—Dear Aoao</div>
</SPAN>
</SPAN>
</SPAN>
</SPAN>
</SPAN>
</DIV>
<DIV id="loveHeart">
<CANVAS id="garden"></CANVAS>
<DIV id="words">
<DIV id="messages">这是静静悄悄走过的岁月~
<DIV id="elapseClock"></DIV></DIV>
<DIV id="loveu"><div style="margin-right:35px;margin-bottom:15px;">愿你一生努力,一生被爱。</div>
<div style="margin-bottom:15px;">想要的都拥有,得不到的都释怀。</div>
<DIV class="signature">- 陈家傲</DIV>
</DIV>
</DIV>
</DIV>
</DIV>
</DIV>
<SCRIPT type="text/javascript">
var offsetX = $("#loveHeart").width() / 2;
var offsetY = $("#loveHeart").height() / 2 - 55;
var together = new Date();
together.setFullYear(1994, 12, 10);
together.setHours(0);
together.setMinutes(0);
together.setSeconds(0);
together.setMilliseconds(0);
if (!document.createElement('canvas').getContext) {
var msg = document.createElement("div");
msg.id = "errorMsg";
msg.innerHTML = "Your browser doesn't support HTML5!<br/>Recommend use Chrome 14+/IE 9+/Firefox 7+/Safari 4+";
document.body.appendChild(msg);
$("#code").css("display", "none")
$("#copyright").css("position", "absolute");
$("#copyright").css("bottom", "10px");
document.execCommand("stop");
} else {
setTimeout(function () {
startHeartAnimation();
}, 5000);
timeElapse(together);
setInterval(function () {
timeElapse(together);
}, 500);
adjustCodePosition();
$("#code").typewriter();
}
</SCRIPT>
<!--<div style="margin-top:300px;">-->
<!--<embed autostart="true" loop="-1" controls="ControlPanel" width="300" height="70" src="c";>-->
<!--</div>-->
<audio src="/assets/music/Legends.mp3" autoplay></audio>
</BODY></HTML>
| 60.49505
| 1,118
| 0.562029
|
72719ab2753b87a4db6f700769f42acb15537855
| 1,886
|
dart
|
Dart
|
lib/widgets/chartbarui.dart
|
7uhinn/ExpenseApp
|
547ceeebe0e62c0fc1e3494efa1d5987e559b1fe
|
[
"MIT"
] | null | null | null |
lib/widgets/chartbarui.dart
|
7uhinn/ExpenseApp
|
547ceeebe0e62c0fc1e3494efa1d5987e559b1fe
|
[
"MIT"
] | null | null | null |
lib/widgets/chartbarui.dart
|
7uhinn/ExpenseApp
|
547ceeebe0e62c0fc1e3494efa1d5987e559b1fe
|
[
"MIT"
] | null | null | null |
import 'package:flutter/material.dart';
import 'package:flutter_animation_progress_bar/flutter_animation_progress_bar.dart';
class Bar extends StatefulWidget {
final String weekday;
final String amount;
final double percent;
Bar(this.weekday, this.amount, this.percent);
@override
_BarState createState() => _BarState();
}
class _BarState extends State<Bar> {
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (ctx, constraints) {
return Column(
children: [
Container(
height: constraints.maxHeight*0.15,
child: FittedBox(
child: Text(
widget.weekday,
style: TextStyle(
color: Color.fromRGBO(100, 100, 100, 100),
),
),
),
),
SizedBox(
height: constraints.maxHeight*0.05,
),
Container(
height: constraints.maxHeight*0.60,
child: FAProgressBar(
currentValue: (widget.percent * 100).toInt(),
direction: Axis.vertical,
progressColor: Theme.of(context).primaryColor,
size: 10,
verticalDirection: VerticalDirection.up,
backgroundColor: Theme.of(context).accentColor,
),
),
SizedBox(
height: constraints.maxHeight*0.05,
),
Container(
height: constraints.maxHeight*0.15,
child: FittedBox(
child: Text(
widget.amount,
style: TextStyle(
color: Color.fromRGBO(100, 100, 100, 100),
),
),
),
),
],
);
},
);
}
}
| 28.149254
| 84
| 0.493107
|
e0207ce97f38c78469d318119c3a3db7155b1802
| 5,320
|
h
|
C
|
XADMaster.framework/Versions/A/Headers/CSInputBuffer.h
|
kanjitalk755/cooViewer
|
855ecb59022452e587ad754205ee2df92f20933b
|
[
"MIT"
] | 100
|
2019-12-31T18:53:24.000Z
|
2022-03-19T16:37:21.000Z
|
XADMaster.framework/Versions/A/Headers/CSInputBuffer.h
|
kanjitalk755/cooViewer
|
855ecb59022452e587ad754205ee2df92f20933b
|
[
"MIT"
] | 22
|
2020-01-03T08:03:59.000Z
|
2021-09-05T07:13:58.000Z
|
XADMaster.framework/Versions/A/Headers/CSInputBuffer.h
|
kanjitalk755/cooViewer
|
855ecb59022452e587ad754205ee2df92f20933b
|
[
"MIT"
] | 12
|
2020-01-02T12:29:36.000Z
|
2022-02-27T14:51:18.000Z
|
#import <Foundation/Foundation.h>
#import "CSHandle.h"
typedef struct CSInputBuffer
{
CSHandle *parent;
off_t startoffs;
BOOL eof;
uint8_t *buffer;
unsigned int bufsize,bufbytes,currbyte;
uint32_t bits;
unsigned int numbits;
} CSInputBuffer;
// Allocation and management
CSInputBuffer *CSInputBufferAlloc(CSHandle *parent,int size);
CSInputBuffer *CSInputBufferAllocWithBuffer(const uint8_t *buffer,int length,off_t startoffs);
CSInputBuffer *CSInputBufferAllocEmpty();
void CSInputBufferFree(CSInputBuffer *self);
void CSInputSetMemoryBuffer(CSInputBuffer *self,uint8_t *buffer,int length,off_t startoffs);
static inline CSHandle *CSInputHandle(CSInputBuffer *self)
{
return self->parent;
}
// Buffer and file positioning
void CSInputRestart(CSInputBuffer *self);
void CSInputFlush(CSInputBuffer *self);
void CSInputSynchronizeFileOffset(CSInputBuffer *self);
void CSInputSeekToFileOffset(CSInputBuffer *self,off_t offset);
void CSInputSeekToBufferOffset(CSInputBuffer *self,off_t offset);
void CSInputSetStartOffset(CSInputBuffer *self,off_t offset);
off_t CSInputBufferOffset(CSInputBuffer *self);
off_t CSInputFileOffset(CSInputBuffer *self);
off_t CSInputBufferBitOffset(CSInputBuffer *self);
void _CSInputFillBuffer(CSInputBuffer *self);
// Byte reading
#define CSInputBufferLookAhead 4
static inline void _CSInputBufferRaiseEOF(CSInputBuffer *self)
{
[self->parent _raiseEOF];
}
static inline int _CSInputBytesLeftInBuffer(CSInputBuffer *self)
{
return self->bufbytes-self->currbyte;
}
static inline void _CSInputCheckAndFillBuffer(CSInputBuffer *self)
{
if(!self->eof&&_CSInputBytesLeftInBuffer(self)<=CSInputBufferLookAhead) _CSInputFillBuffer(self);
}
static inline void CSInputSkipBytes(CSInputBuffer *self,int num)
{
self->currbyte+=num;
}
static inline int _CSInputPeekByteWithoutEOF(CSInputBuffer *self,int offs)
{
return self->buffer[self->currbyte+offs];
}
static inline int CSInputPeekByte(CSInputBuffer *self,int offs)
{
_CSInputCheckAndFillBuffer(self);
if(offs>=_CSInputBytesLeftInBuffer(self)) _CSInputBufferRaiseEOF(self);
return _CSInputPeekByteWithoutEOF(self,offs);
}
static inline int CSInputNextByte(CSInputBuffer *self)
{
int byte=CSInputPeekByte(self,0);
CSInputSkipBytes(self,1);
return byte;
}
static inline BOOL CSInputAtEOF(CSInputBuffer *self)
{
_CSInputCheckAndFillBuffer(self);
return _CSInputBytesLeftInBuffer(self)<=0;
}
// Bitstream reading
void _CSInputFillBits(CSInputBuffer *self);
void _CSInputFillBitsLE(CSInputBuffer *self);
unsigned int CSInputNextBit(CSInputBuffer *self);
unsigned int CSInputNextBitLE(CSInputBuffer *self);
unsigned int CSInputNextBitString(CSInputBuffer *self,int numbits);
unsigned int CSInputNextBitStringLE(CSInputBuffer *self,int numbits);
unsigned int CSInputNextLongBitString(CSInputBuffer *self,int numbits);
unsigned int CSInputNextLongBitStringLE(CSInputBuffer *self,int numbits);
void CSInputSkipBits(CSInputBuffer *self,int numbits);
void CSInputSkipBitsLE(CSInputBuffer *self,int numbits);
BOOL CSInputOnByteBoundary(CSInputBuffer *self);
void CSInputSkipToByteBoundary(CSInputBuffer *self);
void CSInputSkipTo16BitBoundary(CSInputBuffer *self);
static inline unsigned int CSInputBitsLeftInBuffer(CSInputBuffer *self)
{
_CSInputCheckAndFillBuffer(self);
return _CSInputBytesLeftInBuffer(self)*8+(self->numbits&7);
}
static inline void _CSInputCheckAndFillBits(CSInputBuffer *self,int numbits)
{
if(numbits>self->numbits) _CSInputFillBits(self);
}
static inline void _CSInputCheckAndFillBitsLE(CSInputBuffer *self,int numbits)
{
if(numbits>self->numbits) _CSInputFillBitsLE(self);
}
static inline unsigned int CSInputPeekBitString(CSInputBuffer *self,int numbits)
{
if(numbits==0) return 0;
_CSInputCheckAndFillBits(self,numbits);
return self->bits>>(32-numbits);
}
static inline unsigned int CSInputPeekBitStringLE(CSInputBuffer *self,int numbits)
{
if(numbits==0) return 0;
_CSInputCheckAndFillBitsLE(self,numbits);
return self->bits&((1<<numbits)-1);
}
static inline void CSInputSkipPeekedBits(CSInputBuffer *self,int numbits)
{
int numbytes=(numbits-(self->numbits&7)+7)>>3;
CSInputSkipBytes(self,numbytes);
if(_CSInputBytesLeftInBuffer(self)<0) _CSInputBufferRaiseEOF(self);
self->bits<<=numbits;
self->numbits-=numbits;
}
static inline void CSInputSkipPeekedBitsLE(CSInputBuffer *self,int numbits)
{
int numbytes=(numbits-(self->numbits&7)+7)>>3;
CSInputSkipBytes(self,numbytes);
if(_CSInputBytesLeftInBuffer(self)<0) _CSInputBufferRaiseEOF(self);
self->bits>>=numbits;
self->numbits-=numbits;
}
// Multibyte reading
#define CSInputNextValueImpl(type,name,conv) \
static inline type name(CSInputBuffer *self) \
{ \
_CSInputCheckAndFillBuffer(self); \
type val=conv(self->buffer+self->currbyte); \
CSInputSkipBytes(self,sizeof(type)); \
return val; \
}
CSInputNextValueImpl(int16_t,CSInputNextInt16LE,CSInt16LE)
CSInputNextValueImpl(int32_t,CSInputNextInt32LE,CSInt32LE)
CSInputNextValueImpl(uint16_t,CSInputNextUInt16LE,CSUInt16LE)
CSInputNextValueImpl(uint32_t,CSInputNextUInt32LE,CSUInt32LE)
CSInputNextValueImpl(int16_t,CSInputNextInt16BE,CSInt16BE)
CSInputNextValueImpl(int32_t,CSInputNextInt32BE,CSInt32BE)
CSInputNextValueImpl(uint16_t,CSInputNextUInt16BE,CSUInt16BE)
CSInputNextValueImpl(uint32_t,CSInputNextUInt32BE,CSUInt32BE)
| 26.467662
| 98
| 0.812218
|
a4355d2ad231af66fa97b2b759e9b60d8876829c
| 12,983
|
php
|
PHP
|
src/www/csrf/csrf-magic.php
|
sxnxl/opnsense-core
|
5d93e8d77de468c89a0ac8db6ba274c9c4a8c74c
|
[
"BSD-2-Clause"
] | 1
|
2019-06-30T16:11:42.000Z
|
2019-06-30T16:11:42.000Z
|
src/www/csrf/csrf-magic.php
|
mmorev/opnsense-core
|
956ea297f8e10e147b408a10abd448682f5075cf
|
[
"BSD-2-Clause"
] | null | null | null |
src/www/csrf/csrf-magic.php
|
mmorev/opnsense-core
|
956ea297f8e10e147b408a10abd448682f5075cf
|
[
"BSD-2-Clause"
] | null | null | null |
<?php
/**
* @file
*
* csrf-magic is a PHP library that makes adding CSRF-protection to your
* web applications a snap. No need to modify every form or create a database
* of valid nonces; just include this file at the top of every
* web-accessible page (or even better, your common include file included
* in every page), and forget about it! (There are, of course, configuration
* options for advanced users).
*
* This library is PHP4 and PHP5 compatible.
*/
// CONFIGURATION:
/**
* This is the amount of seconds you wish to allow before any token becomes
* invalid; the default is two hours, which should be more than enough for
* most websites.
*/
$GLOBALS['csrf']['expires'] = 7200;
/**
* Callback function to execute when there's the CSRF check fails and
* $fatal == true (see csrf_check). This will usually output an error message
* about the failure.
*/
$GLOBALS['csrf']['callback'] = 'csrf_callback';
/**
* Whether or not to include our JavaScript library which also rewrites
* AJAX requests on this domain. Set this to the web path. This setting only works
* with supported JavaScript libraries in Internet Explorer; see README.txt for
* a list of supported libraries.
*/
$GLOBALS['csrf']['rewrite-js'] = false;
/**
* A secret key used when hashing items. Please generate a random string and
* place it here. If you change this value, all previously generated tokens
* will become invalid.
*/
$GLOBALS['csrf']['secret'] = '';
// nota bene: library code should use csrf_get_secret() and not access
// this global directly
/**
* Set this to false to disable csrf-magic's output handler, and therefore,
* its rewriting capabilities. If you're serving non HTML content, you should
* definitely set this false.
*/
$GLOBALS['csrf']['rewrite'] = true;
/**
* Whether or not to use IP addresses when binding a user to a token. This is
* less reliable and less secure than sessions, but is useful when you need
* to give facilities to anonymous users and do not wish to maintain a database
* of valid keys.
*/
$GLOBALS['csrf']['allow-ip'] = true;
/**
* If this information is available, use the cookie by this name to determine
* whether or not to allow the request. This is a shortcut implementation
* very similar to 'key', but we randomly set the cookie ourselves.
*/
$GLOBALS['csrf']['cookie'] = '__csrf_cookie';
/**
* If this information is available, set this to a unique identifier (it
* can be an integer or a unique username) for the current "user" of this
* application. The token will then be globally valid for all of that user's
* operations, but no one else. This requires that 'secret' be set.
*/
$GLOBALS['csrf']['user'] = false;
/**
* This is an arbitrary secret value associated with the user's session. This
* will most probably be the contents of a cookie, as an attacker cannot easily
* determine this information. Warning: If the attacker knows this value, they
* can easily spoof a token. This is a generic implementation; sessions should
* work in most cases.
*
* Why would you want to use this? Lets suppose you have a squid cache for your
* website, and the presence of a session cookie bypasses it. Let's also say
* you allow anonymous users to interact with the website; submitting forms
* and AJAX. Previously, you didn't have any CSRF protection for anonymous users
* and so they never got sessions; you don't want to start using sessions either,
* otherwise you'll bypass the Squid cache. Setup a different cookie for CSRF
* tokens, and have Squid ignore that cookie for get requests, for anonymous
* users. (If you haven't guessed, this scheme was(?) used for MediaWiki).
*/
$GLOBALS['csrf']['key'] = false;
/**
* The name of the magic CSRF token that will be placed in all forms, i.e.
* the contents of <input type="hidden" name="$name" value="CSRF-TOKEN" />
*/
$GLOBALS['csrf']['input-name'] = '__csrf_magic';
/**
* Set this to false if your site must work inside of frame/iframe elements,
* but do so at your own risk: this configuration protects you against CSS
* overlay attacks that defeat tokens.
*/
$GLOBALS['csrf']['frame-breaker'] = true;
/**
* Whether or not csrf-magic should produce XHTML style tags.
*/
$GLOBALS['csrf']['xhtml'] = true;
// FUNCTIONS:
// Don't edit this!
$GLOBALS['csrf']['version'] = '1.0.4';
/**
* Rewrites <form> on the fly to add CSRF tokens to them. This can also
* inject our JavaScript library.
*/
function csrf_ob_handler($buffer, $flags)
{
// Even though the user told us to rewrite, we should do a quick heuristic
// to check if the page is *actually* HTML. We don't begin rewriting until
// we hit the first <html tag.
static $is_html = false;
if (!$is_html) {
// not HTML until proven otherwise
if (stripos($buffer, '<html') !== false) {
$is_html = true;
} else {
return $buffer;
}
}
$tokens = csrf_get_tokens();
$name = $GLOBALS['csrf']['input-name'];
$endslash = $GLOBALS['csrf']['xhtml'] ? ' /' : '';
$input = "<input type='hidden' name='$name' value=\"$tokens\"$endslash>";
$buffer = preg_replace('#(<form[^>]*method\s*=\s*["\']post["\'][^>]*>)#i', '$1' . $input, $buffer);
if ($GLOBALS['csrf']['frame-breaker']) {
$buffer = str_ireplace('</head>', '<script type="text/javascript">if (top != self) {top.location.href = self.location.href;}</script></head>', $buffer);
}
if ($js = $GLOBALS['csrf']['rewrite-js']) {
$buffer = str_ireplace(
'</head>',
'<script type="text/javascript">'.
'var csrfMagicToken = "'.$tokens.'";'.
'var csrfMagicName = "'.$name.'";</script>'.
'<script src="'.$js.'" type="text/javascript"></script></head>',
$buffer
);
$script = '<script type="text/javascript">CsrfMagic.end();</script>';
$buffer = str_ireplace('</body>', $script . '</body>', $buffer, $count);
if (!$count) {
$buffer .= $script;
}
}
return $buffer;
}
/**
* Checks if this is a post request, and if it is, checks if the nonce is valid.
* @param bool $fatal Whether or not to fatally error out if there is a problem.
* @return True if check passes or is not necessary, false if failure.
*/
function csrf_check($fatal = true)
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
return true;
}
$name = $GLOBALS['csrf']['input-name'];
$ok = false;
$tokens = '';
do {
if (!isset($_POST[$name])) {
break;
}
// we don't regenerate a token and check it because some token creation
// schemes are volatile.
$tokens = $_POST[$name];
if (!csrf_check_tokens($tokens)) {
break;
}
$ok = true;
} while (false);
if ($fatal && !$ok) {
$callback = $GLOBALS['csrf']['callback'];
if (trim($tokens, 'A..Za..z0..9:;,') !== '') {
$tokens = 'hidden';
}
$callback($tokens);
exit;
}
return $ok;
}
/**
* Retrieves a valid token(s) for a particular context. Tokens are separated
* by semicolons.
*/
function csrf_get_tokens()
{
$has_cookies = !empty($_COOKIE);
// $ip implements a composite key, which is sent if the user hasn't sent
// any cookies. It may or may not be used, depending on whether or not
// the cookies "stick"
$secret = csrf_get_secret();
if (!$has_cookies && $secret) {
// :TODO: Harden this against proxy-spoofing attacks
$ip = ';ip:' . csrf_hash($_SERVER['IP_ADDRESS']);
} else {
$ip = '';
}
// These are "strong" algorithms that don't require per se a secret
if (session_id()) {
return 'sid:' . csrf_hash(session_id()) . $ip;
}
if ($GLOBALS['csrf']['cookie']) {
$val = csrf_generate_secret();
setcookie($GLOBALS['csrf']['cookie'], $val);
return 'cookie:' . csrf_hash($val) . $ip;
}
if ($GLOBALS['csrf']['key']) {
return 'key:' . csrf_hash($GLOBALS['csrf']['key']) . $ip;
}
// These further algorithms require a server-side secret
if (!$secret) {
return 'invalid';
}
if ($GLOBALS['csrf']['user'] !== false) {
return 'user:' . csrf_hash($GLOBALS['csrf']['user']);
}
if ($GLOBALS['csrf']['allow-ip']) {
return ltrim($ip, ';');
}
return 'invalid';
}
/**
* @param $tokens is safe for HTML consumption
*/
function csrf_callback($tokens)
{
// (yes, $tokens is safe to echo without escaping)
header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
echo "<html><head><title>CSRF check failed</title></head>
<body>
<p>CSRF check failed. Your form session may have expired, or you may not have
cookies enabled.</p>
<p>Debug: $tokens</p></body></html>
";
}
/**
* Checks if a composite token is valid. Outward facing code should use this
* instead of csrf_check_token()
*/
function csrf_check_tokens($tokens)
{
if (is_string($tokens)) {
$tokens = explode(';', $tokens);
}
foreach ($tokens as $token) {
if (csrf_check_token($token)) {
return true;
}
}
return false;
}
/**
* Checks if a token is valid.
*/
function csrf_check_token($token)
{
if (strpos($token, ':') === false) {
return false;
}
list($type, $value) = explode(':', $token, 2);
if (strpos($value, ',') === false) {
return false;
}
list($x, $time) = explode(',', $token, 2);
if ($GLOBALS['csrf']['expires']) {
if (time() > $time + $GLOBALS['csrf']['expires']) {
return false;
}
}
switch ($type) {
case 'sid':
return $value === csrf_hash(session_id(), $time);
case 'cookie':
$n = $GLOBALS['csrf']['cookie'];
if (!$n) {
return false;
}
if (!isset($_COOKIE[$n])) {
return false;
}
return $value === csrf_hash($_COOKIE[$n], $time);
case 'key':
if (!$GLOBALS['csrf']['key']) {
return false;
}
return $value === csrf_hash($GLOBALS['csrf']['key'], $time);
// We could disable these 'weaker' checks if 'key' was set, but
// that doesn't make me feel good then about the cookie-based
// implementation.
case 'user':
if (!csrf_get_secret()) {
return false;
}
if ($GLOBALS['csrf']['user'] === false) {
return false;
}
return $value === csrf_hash($GLOBALS['csrf']['user'], $time);
case 'ip':
if (!csrf_get_secret()) {
return false;
}
// do not allow IP-based checks if the username is set, or if
// the browser sent cookies
if ($GLOBALS['csrf']['user'] !== false) {
return false;
}
if (!empty($_COOKIE)) {
return false;
}
if (!$GLOBALS['csrf']['allow-ip']) {
return false;
}
return $value === csrf_hash($_SERVER['IP_ADDRESS'], $time);
}
return false;
}
/**
* Sets a configuration value.
*/
function csrf_conf($key, $val)
{
if (!isset($GLOBALS['csrf'][$key])) {
trigger_error('No such configuration ' . $key, E_USER_WARNING);
return;
}
$GLOBALS['csrf'][$key] = $val;
}
/**
* Retrieves the secret, and generates one if necessary.
*/
function csrf_get_secret()
{
if ($GLOBALS['csrf']['secret']) {
return $GLOBALS['csrf']['secret'];
}
$dir = dirname(__FILE__);
$file = $dir . '/csrf-secret.php';
$secret = '';
if (file_exists($file)) {
include $file;
return $secret;
}
if (is_writable($dir)) {
$secret = csrf_generate_secret();
touch($file);
chmod($file, 0600);
$fh = fopen($file, 'w');
fwrite($fh, '<?php $secret = "'.$secret.'";' . PHP_EOL);
fclose($fh);
return $secret;
}
return '';
}
/**
* Generates a random string as the hash of time, microtime, and mt_rand.
*/
function csrf_generate_secret($len = 32)
{
$r = '';
for ($i = 0; $i < 32; $i++) {
$r .= chr(mt_rand(0, 255));
}
$r .= time() . microtime();
return sha1($r);
}
/**
* Generates a hash/expiry double. If time isn't set it will be calculated
* from the current time.
*/
function csrf_hash($value, $time = null)
{
if (!$time) {
$time = time();
}
return sha1(csrf_get_secret() . $value . $time) . ',' . $time;
}
// Load user configuration
if (function_exists('csrf_startup')) {
csrf_startup();
}
// Initialize our handler
if ($GLOBALS['csrf']['rewrite']) {
// limit output chunks to max 5MB
ob_start('csrf_ob_handler', 5242880);
}
// Perform check
csrf_check();
| 31.059809
| 160
| 0.589694
|
a10ae8962fd490f96e94439c115d65f4c33f0bcf
| 2,237
|
ts
|
TypeScript
|
packages/web/src/shared/utils/arrays.ts
|
codingwithchris/playground.web
|
d2d86c4cbb9ff00b00c41d7c145cb7cb6084f008
|
[
"MIT"
] | null | null | null |
packages/web/src/shared/utils/arrays.ts
|
codingwithchris/playground.web
|
d2d86c4cbb9ff00b00c41d7c145cb7cb6084f008
|
[
"MIT"
] | 110
|
2020-06-12T23:43:12.000Z
|
2022-03-27T17:41:05.000Z
|
packages/web/src/shared/utils/arrays.ts
|
codingwithchris/playground.web
|
d2d86c4cbb9ff00b00c41d7c145cb7cb6084f008
|
[
"MIT"
] | null | null | null |
/**
* Remove any falsy value from an array.
* Falsy values include: undefined, null, 0, false, NaN and "" (empty string)
*
* @param {array} array The array we want to scrub and remove falsy values from
*/
export const scrubArray = <T>(array: (T | undefined)[]): T[] =>
array.filter((item): item is T => !!item);
/**
* Checks to see if the previous item in an array exists
*
* @param array Any array
* @param currentIndex The current index from which we will check for the previous item
* @returns boolean
*/
export const hasValidPreviousArrayItem = <T>(
array: T[],
currentIndex: number
): boolean => !!array[currentIndex - 1];
/**
* Checks to see if the next item in an array exists
*
* @param array Any array
* @param currentIndex The current index from which we will check for the next item
* @returns boolean
*/
export const hasValidNextArrayItem = <T>(
array: T[],
currentIndex: number
): boolean => !!array[currentIndex + 1];
/**
* Get the previous item in an array
*
* @param array Any array
* @param currentIndex The starting point from which to get the previous array item
* @returns the next array item OR undefined if it doesn't exist
*/
export const getPreviousArrayItem = <T>(
array: T[],
currentIndex: number
): T | undefined =>
hasValidPreviousArrayItem(array, currentIndex)
? array[currentIndex - 1]
: undefined;
/**
* Get the next item in an array
*
* @param array Any array
* @param currentIndex The starting point from which to get the next array item
* @returns the next array item OR undefined if it doesn't exist
*/
export const getNextArrayItem = <T>(
array: T[],
currentIndex: number
): T | undefined =>
hasValidNextArrayItem(array, currentIndex)
? array[currentIndex + 1]
: undefined;
/**
* Remove a specified item from an array
* * NOTE: Doesn't mutate the existing array but rather, creates a new one
*
* @param array Any array
* @param itemIndex The index of the array item to remove
* @returns A new array with the specified index removed
*/
export const removeArrayItem = <T>(array: T[], itemIndex: number): T[] => {
return [...array.slice(0, itemIndex), ...array.slice(itemIndex)];
};
| 29.826667
| 87
| 0.679481
|
bb66c972d7f7cb9c41e9b46e308ce2ac56d1d7c1
| 4,343
|
cs
|
C#
|
MonoGame.Framework/Content/ContentReaders/Texture2DReader.cs
|
Gert-Jan/XnaUnitySpriteBatch
|
7651715e3b71cd5934767f9a32fcffd3261c80e0
|
[
"MS-PL"
] | 3
|
2015-02-28T13:39:28.000Z
|
2015-06-16T08:31:08.000Z
|
MonoGame.Framework/Content/ContentReaders/Texture2DReader.cs
|
Gert-Jan/XnaUnitySpriteBatch
|
7651715e3b71cd5934767f9a32fcffd3261c80e0
|
[
"MS-PL"
] | null | null | null |
MonoGame.Framework/Content/ContentReaders/Texture2DReader.cs
|
Gert-Jan/XnaUnitySpriteBatch
|
7651715e3b71cd5934767f9a32fcffd3261c80e0
|
[
"MS-PL"
] | 1
|
2021-12-02T17:03:23.000Z
|
2021-12-02T17:03:23.000Z
|
using System;
using Microsoft.Xna.Framework.Graphics;
using XnaWrapper;
namespace Microsoft.Xna.Framework.Content
{
internal class Texture2DReader : ContentTypeReader<Texture2D>
{
internal Texture2DReader()
{
// Do nothing
}
#if ANDROID
static string[] supportedExtensions = new string[] { ".jpg", ".bmp", ".jpeg", ".png", ".gif" };
#else
static string[] supportedExtensions = new string[] { ".jpg", ".bmp", ".jpeg", ".png", ".gif", ".pict", ".tga" };
#endif
internal static string Normalize(string fileName)
{
return Normalize(fileName, supportedExtensions);
}
protected internal override Texture2D Read(ContentReader reader, Texture2D existingInstance)
{
Texture2D texture = null;
SurfaceFormat surfaceFormat;
if (reader.version < 5)
{
SurfaceFormatLegacy legacyFormat = (SurfaceFormatLegacy)reader.ReadInt32();
switch (legacyFormat)
{
case SurfaceFormatLegacy.Dxt1:
surfaceFormat = SurfaceFormat.Dxt1;
break;
case SurfaceFormatLegacy.Dxt3:
surfaceFormat = SurfaceFormat.Dxt3;
break;
case SurfaceFormatLegacy.Dxt5:
surfaceFormat = SurfaceFormat.Dxt5;
break;
case SurfaceFormatLegacy.Color:
surfaceFormat = SurfaceFormat.Color;
break;
default:
throw new NotSupportedException("Unsupported legacy surface format.");
}
}
else
{
surfaceFormat = (SurfaceFormat)reader.ReadInt32();
}
int width = (reader.ReadInt32());
int height = (reader.ReadInt32());
int levelCount = (reader.ReadInt32());
int levelCountOutput = levelCount;
SurfaceFormat convertedFormat = surfaceFormat;
switch (surfaceFormat)
{
case SurfaceFormat.Dxt1:
case SurfaceFormat.Dxt1a:
convertedFormat = SurfaceFormat.Color;
break;
case SurfaceFormat.Dxt3:
case SurfaceFormat.Dxt5:
convertedFormat = SurfaceFormat.Color;
break;
case SurfaceFormat.NormalizedByte4:
convertedFormat = SurfaceFormat.Color;
break;
}
UnityEngine.Texture2D unityTexture = new UnityEngine.Texture2D(width, height, XnaToUnity.TextureFormat(convertedFormat), levelCountOutput > 1);
for (int level = 0; level < levelCount; level++)
{
int levelDataSizeInBytes = (reader.ReadInt32());
byte[] levelData = reader.ReadBytes(levelDataSizeInBytes);
int levelWidth = width >> level;
int levelHeight = height >> level;
if (level >= levelCountOutput)
{
continue;
}
//Convert the image data if required
switch (surfaceFormat)
{
case SurfaceFormat.Dxt1:
case SurfaceFormat.Dxt1a:
levelData = DxtUtil.DecompressDxt1(levelData, levelWidth, levelHeight);
break;
case SurfaceFormat.Dxt3:
levelData = DxtUtil.DecompressDxt3(levelData, levelWidth, levelHeight);
break;
case SurfaceFormat.Dxt5:
levelData = DxtUtil.DecompressDxt5(levelData, levelWidth, levelHeight);
break;
}
// un-premultiply alpha (instead do it in the shader)
for (int i = 0; i < levelData.Length; i += 4)
{
float r = levelData[i + 0] / 255.0f;
float g = levelData[i + 1] / 255.0f;
float b = levelData[i + 2] / 255.0f;
float a = levelData[i + 3] / 255.0f;
levelData[i + 0] = (byte)(r / a * 255.0f);
levelData[i + 1] = (byte)(g / a * 255.0f);
levelData[i + 2] = (byte)(b / a * 255.0f);
//levelData[i + 0] = 0;
//levelData[i + 1] = 255;
//levelData[i + 2] = 0;
//levelData[i + 3] = 255;
}
// swap rows because unity textures are laid out bottom-top instead of top-bottom
int rowSize = width * 4;
byte[] temp = new byte[rowSize];
for (int i = 0; i < levelData.Length / 2; i += rowSize)
{
for (int j = 0; j < rowSize; j++)
temp[j] = levelData[i + j];
int p = levelData.Length - (i + rowSize);
for (int j = 0; j < rowSize; j++)
levelData[i + j] = levelData[p + j];
for (int j = 0; j < rowSize; j++)
levelData[p + j] = temp[j];
}
UnityEngine.Color[] unityColors = new UnityEngine.Color[levelData.Length * 4];
unityTexture.SetPixels(XnaToUnity.Color(levelData, ref unityColors), level);
unityTexture.Apply();
texture = new Texture2D(unityTexture);
}
return texture;
}
}
}
| 29.344595
| 146
| 0.635736
|
6f5a8492493d533ad7c63b3c718cd6b587d6df72
| 1,177
|
php
|
PHP
|
resources/views/pages/page1.blade.php
|
jackys97/jackysproductions
|
3b883c0b622df8cf8e88455bfa3b57faaf3a95e4
|
[
"MIT"
] | null | null | null |
resources/views/pages/page1.blade.php
|
jackys97/jackysproductions
|
3b883c0b622df8cf8e88455bfa3b57faaf3a95e4
|
[
"MIT"
] | null | null | null |
resources/views/pages/page1.blade.php
|
jackys97/jackysproductions
|
3b883c0b622df8cf8e88455bfa3b57faaf3a95e4
|
[
"MIT"
] | null | null | null |
@extends('app')
@section('content')
<!-- Warming Up -->
<link href='http://fonts.googleapis.com/css?family=Buenard:700' rel='stylesheet' type='text/css'>
<body>
<!--Video Section-->
<section class="jumbotron content-section video-section" style="height: 480px">
<div class="pattern-overlay">
<a id="bgndVideo" class="player" data-property="{videoURL:'https://www.youtube.com/watch?v=vr0qNXmkUJ8',containment:'.video-section', quality:'large', autoPlay:true, mute:true, opacity:0.7}">bg</a>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1>Full Width Video</h1>
<h4>Enjoy Adding Full Screen Videos to your Page Sections</h4>
</div>
</div>
</div>
</div>
</section>
<script src="http://pupunzi.com/mb.components/mb.YTPlayer/demo/inc/jquery.mb.YTPlayer.js"></script>
</body>
@endsection
@section('js')
<script src="http://pupunzi.com/mb.components/mb.YTPlayer/demo/inc/jquery.mb.YTPlayer.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".player").mb_YTPlayer();
});
</script>
@endsection
| 31.810811
| 202
| 0.623619
|
f4588cdbdb21d03d1c2a43c5d224f89813c17445
| 643
|
cs
|
C#
|
src/Modules/Users/Inflow.Modules.Users.Core/DAL/Configurations/UserConfiguration.cs
|
devmentors/Inflow
|
95fe438e5962c31145bf65c39be792135efc49d3
|
[
"MIT"
] | 68
|
2021-09-06T09:39:49.000Z
|
2022-03-27T02:25:51.000Z
|
src/Modules/Users/Inflow.Modules.Users.Core/DAL/Configurations/UserConfiguration.cs
|
devmentors/Inflow
|
95fe438e5962c31145bf65c39be792135efc49d3
|
[
"MIT"
] | null | null | null |
src/Modules/Users/Inflow.Modules.Users.Core/DAL/Configurations/UserConfiguration.cs
|
devmentors/Inflow
|
95fe438e5962c31145bf65c39be792135efc49d3
|
[
"MIT"
] | 9
|
2021-12-15T08:46:38.000Z
|
2022-03-08T20:11:52.000Z
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Inflow.Modules.Users.Core.Entities;
using Inflow.Shared.Abstractions.Kernel.ValueObjects;
namespace Inflow.Modules.Users.Core.DAL.Configurations;
internal class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasIndex(x => x.Email).IsUnique();
builder.Property(x => x.Email).IsRequired().HasMaxLength(100)
.HasConversion(x => x.Value, x => new Email(x));
builder.Property(x => x.Password).IsRequired().HasMaxLength(500);
}
}
| 37.823529
| 73
| 0.73717
|
8c62ff1f1eb6f042f94917158365221f1e049adc
| 226
|
rb
|
Ruby
|
app/controllers/feedback_controller.rb
|
aliraeisdanaei/interactive-transcript
|
cb074690c1eceadbbd7f573c7fab294b35352523
|
[
"MIT"
] | null | null | null |
app/controllers/feedback_controller.rb
|
aliraeisdanaei/interactive-transcript
|
cb074690c1eceadbbd7f573c7fab294b35352523
|
[
"MIT"
] | null | null | null |
app/controllers/feedback_controller.rb
|
aliraeisdanaei/interactive-transcript
|
cb074690c1eceadbbd7f573c7fab294b35352523
|
[
"MIT"
] | null | null | null |
class FeedbackController < ApplicationController
def feedback
respond_to do |format|
format.json do
Feedback.create!(outcome: params[:outcome])
render json: { ok: true }
end
end
end
end
| 20.545455
| 51
| 0.650442
|
dcb04a60e53f830273efcb0665c6eac496058c8a
| 35,621
|
lua
|
Lua
|
loo.lua
|
MKlegoman357/Loo
|
b30e9a7368bf5c2a84d07534a3d3dfc1e5865d17
|
[
"MIT"
] | null | null | null |
loo.lua
|
MKlegoman357/Loo
|
b30e9a7368bf5c2a84d07534a3d3dfc1e5865d17
|
[
"MIT"
] | null | null | null |
loo.lua
|
MKlegoman357/Loo
|
b30e9a7368bf5c2a84d07534a3d3dfc1e5865d17
|
[
"MIT"
] | null | null | null |
local _type, _tonumber = type, tonumber
local reservedClassKeywords = {
["__prop__"] = true;
["base"] = true;
["this"] = true;
}
local primitiveTypes = {
["nil"] = true;
["number"] = true;
["string"] = true;
["table"] = true;
["function"] = true;
["thread"] = true;
}
local null = setmetatable({}, {__type = "null", __tostring = function () return "null" end})
local function type (val, ...)
if _type(val) == "table" and _type(getmetatable(val)) == "table" and getmetatable(val).__type ~= nil then
return tostring(getmetatable(val).__type)
else
return _type(val, ...)
end
end
local function tonumber (num, base, ...)
if _type(num) == "table" and _type(getmetatable(num)) == "table" and _type(getmetatable(num).__tonumber) == "function" then
return getmetatable(num).__tonumber(num, base, ...)
else
return _tonumber(num, base, ...)
end
end
local function expect (value, expectType, default, name, level)
level = level == nil and 2 or level == 0 and 0 or level + 1
local foundType = type(value)
if default ~= nil and value == nil then
return default
elseif foundType ~= expectType then
if name then
error(expectType .. " expected at field '" .. name .. "', got " .. foundType, level)
else
error(expectType .. " expected, got " .. foundType, level)
end
end
return value
end
local function isidentifier (str)
expect(str, "string")
return str:match("^[_a-zA-Z][_a-zA-Z0-9]*$")
end
local function isprimitive (val)
return primitiveTypes[type(val)] == true
end
local function isin (val, tab)
for k, v in pairs(tab) do
if v == val then
return true
end
end
return false
end
local function split (str, char)
expect(str, "string", nil, "string")
expect(char, "string", nil, "delimiter")
local result = {}
for match in str:gmatch("[^" .. char .. "]+") do
result[#result + 1] = match
end
return result
end
local function cast (obj, typ, level)
level = level == nil and 2 or level == 0 and 0 or level + 1
if isprimitive(obj) then
error("Cannot cast primitive type " .. type(obj), level)
elseif obj.__prop__ and type(obj.__prop__.selfChain) == "table" then
for i, self in ipairs(obj.__prop__.selfChain) do
if self.__prop__.classFullName == typ then
return self
end
end
end
error("Cannot cast type " .. type(obj) .. " to type " .. typ, level)
end
local function is (obj, typ)
if type(obj) == typ then
return true
elseif not isprimitive(obj) and type(obj.__prop__) == "table" and type(obj.__prop__.selfChain) == "table" then
for i, self in ipairs(obj.__prop__.selfChain) do
if self.__prop__.classFullName == typ then
return true
end
end
end
return false
end
local packages = {}
local function isPackageNameValid (name)
return type(name) == "string" and name:gsub("[^_a-zA-Z0-9%.]+", ""):gsub("%.+", "."):gsub("^%.", ""):gsub("%.$", ""):gsub("%.(%d)", "") == name
end
local function resolvePackage (name)
local identifiers = split(name, ".")
local pkg = packages
for i, identifier in ipairs(identifiers) do
if not pkg[identifier] then
pkg[identifier] = {}
elseif type(pkg[identifier]) ~= "table" then
return nil, pkg[identifier]
end
pkg = pkg[identifier]
end
return pkg
end
local _interfaces = {}
local interface = {}
function interface.resolvePackage (env)
return isPackageNameValid(env.__package) and env.__package or ""
end
function interface.getFullName (env, interfaceName)
if isPackageNameValid(env.__package) and _interfaces[env.__package .. "." .. interfaceName] then
return env.__package .. "." .. interfaceName
end
if type(env.__imports) == "table" then
for package in pairs(env.__imports) do
if isPackageNameValid(package) and _interfaces[package .. "." .. interfaceName] then
return package .. "." .. interfaceName
end
end
end
if _interfaces[interfaceName] then
return interfaceName
end
end
setmetatable(interface, {
__call = function (_, env, name, prop, level)
level = level == nil and 2 or level == 0 and 0 or level
expect(name, "string", nil, "interface name", level)
expect(prop, "table", true, "interface fields", level)
local package = interface.resolvePackage(env)
local this = {
name = name;
package = package;
fullName = (#package > 0 and package .. "." or "") .. name;
globals = {};
}
local proxy
proxy = setmetatable({}, {
__call = function (_, prop, level)
level = level or 2
expect(prop, "table", nil, "interface fields", level)
for field, fieldType in pairs(prop) do
expect(field, "string", nil, tostring(field), level)
expect(fieldType, "string", nil, tostring(fieldType), level)
if not isidentifier(field) then
error("Field '" .. field .. "' is not a valid identifier.", level)
end
this.globals[field] = fieldType
end
_interfaces[this.fullName] = this
end;
})
if prop then
return proxy(prop, 1 + level)
end
return proxy
end;
})
local _classes = {}
local classes = {}
local class = {}
function class.resolvePackage (env)
return isPackageNameValid(env.__package) and env.__package or ""
end
function class.getFullName (env, className)
if isPackageNameValid(env.__package) and classes[env.__package .. "." .. className] then
return env.__package .. "." .. className
end
if type(env.__imports) == "table" then
for package in pairs(env.__imports) do
if isPackageNameValid(package) and classes[package .. "." .. className] then
return package .. "." .. className
end
end
end
if classes[className] then
return className
end
end
setmetatable(class, {
__call = function (_, env, name, prop, level)
level = level == nil and 2 or level == 0 and 0 or level
expect(name, "string", nil, "class name", level)
expect(prop, "table", true, "class members", level)
local package = class.resolvePackage(env)
local this = {
name = name;
package = package;
fullName = (#package > 0 and package .. "." or "") .. name;
constructor = function () end;
locals = {};
globals = {};
static = {};
meta = {};
interfaces = nil;
inherits = nil;
}
local function checkIdentifier (identifier, level)
local id = isidentifier(identifier)
if not id then
error("Identifier '" .. identifier .. "' is not a valid identifier.", 1 + level)
end
return id
end
local function getInherit (class)
return {
name = class.name;
package = class.package;
fullName = class.fullName;
constructor = class.constructor;
locals = class.locals;
globals = class.globals;
static = class.static;
meta = class.meta;
inherits = class.inherits and getInherit(class.inherits) or nil;
interfaces = (function ()
if not class.interfaces then
return nil
end
local interfaces = {}
for i, interface in ipairs(class.interfaces) do
interfaces[#interfaces + 1] = {
name = interface.name;
package = interface.package;
fullName = interface.fullName;
requiredGlobals = interface.requiredGlobals;
globals = {};
}
for name, global in pairs(interface.globals) do
interfaces[#interfaces].globals[name] = {
value = global.value;
of = global.of;
locked = global.locked;
}
end
end
return interfaces
end)();
}
end
this.inherits = _classes["loo.Object"] and getInherit(_classes["loo.Object"]) or nil
local proxy, thisProxy
proxy = setmetatable({
inherits = function (_, classInherits)
expect(classInherits, "string", nil, "class members")
local classInherit = _classes[class.getFullName(env, classInherits)]
if classInherit then
this.inherits = getInherit(classInherit)
else
error("Cannot inherit a non-existant class " .. classInherits, 2)
end
return proxy
end;
implements = function (_, ...)
interfacesImplements = {...}
for i, implement in ipairs(interfacesImplements) do
local interfaceImplement = _interfaces[interface.getFullName(env, implement)]
if interfaceImplement then
this.interfaces = this.interfaces or {}
this.interfaces[#this.interfaces + 1] = {
name = interfaceImplement.name;
package = interfaceImplement.package;
fullName = interfaceImplement.fullName;
requiredGlobals = interfaceImplement.globals;
globals = {};
}
else
error("Cannot implement a non-existant interface " .. tostring(implement), 2)
end
end
return proxy
end;
}, {
__call = function (_, properties, level)
level = level or 2
expect(properties, "table", nil, level)
for variable, value in pairs(properties) do
expect(variable, "string", nil, tostring(variable) .. " (class: " .. this.fullName .. ")", level)
local identifier
local isLocal = variable:match("^local_")
local isStatic = variable:match("^static_")
local isMeta = variable:match("^meta_")
local isOverride = variable:match("^override_")
local isOf, interfaceName = variable:match("^(of)_([_a-zA-Z][a-zA-Z0-9]*)_")
local isVirtual = variable:match("^virtual_")
if isLocal then
identifier = checkIdentifier(variable:sub(7), level)
this.locals[identifier] = {
value = value;
locked = type(value) == "function" or nil;
}
elseif isStatic then
identifier = checkIdentifier(variable:sub(8), level)
if type(value) == "function" then
local val = value
value = function (...)
return val(thisProxy, ...)
end
end
this.static[identifier] = {
value = value;
isStatic = true;
locked = type(value) == "function" or nil;
}
elseif isMeta then
identifier = checkIdentifier(variable:sub(6), level)
this.meta["__" .. identifier] = value
elseif isOverride then
identifier = checkIdentifier(variable:sub(10), level)
local function findOverride (class, var)
if not class.inherits then
return false
elseif class.inherits.globals[var] and class.inherits.globals[var].isVirtual then
return true, class.inherits
else
return findOverride(class.inherits, var)
end
end
local canOverride, inherited = findOverride(this, identifier)
if canOverride then
this.globals[identifier] = {
value = value;
override = inherited.fullName;
locked = type(value) == "function" or nil;
}
else
error("Cannot override a non-existant virtual member " .. identifier .. " in class " .. this.fullName, level)
end
elseif isOf then
identifier = checkIdentifier(variable:sub(5 + #interfaceName), level)
interfaceName = interface.getFullName(env, interfaceName) or interfaceName
local function findInterface (class, interface)
if not class.interfaces then
return false
end
for i, inter in ipairs(class.interfaces) do
if inter.fullName == interface then
return true, inter
end
end
if class.inherits then
return findInterface(class.inherits, interface)
end
return false
end
local foundInterface, interface = findInterface(this, interfaceName)
if foundInterface then
if not interface.requiredGlobals[identifier] then
error("Cannot implement field " .. identifier .. " for interface " .. interfaceName .. " because the field does not exist.", level)
end
interface.globals[identifier] = {
value = value;
of = this.fullName;
locked = type(value) == "function" or nil;
}
else
error("Cannot implement field " .. identifier .. " for non-existant interface " .. interfaceName, level)
end
else
identifier = isVirtual and checkIdentifier(variable:sub(9), level) or checkIdentifier(variable, level)
if identifier == this.name then
expect(value, "function", "class constructor", 2 + level)
this.constructor = value
else
this.globals[identifier] = {
value = value;
isVirtual = not not isVirtual;
locked = type(value) == "function" or nil;
}
end
end
end
if this.interfaces then
for i, interface in ipairs(this.interfaces) do
for name, valueType in pairs(interface.requiredGlobals) do
if (not this.globals[name] or type(this.globals[name].value) ~= valueType) and (not interface.globals[name] or type(interface.globals[name].value) ~= valueType) then
error("Field " .. name .. " (" .. valueType .. ") of interface " .. interface.fullName .. " was not implemented in class " .. this.fullName, level)
end
end
end
end
_classes[this.fullName] = this
thisProxy = setmetatable({}, {
__type = "class";
__index = function (_, k)
if k == "__prop__" then
return {
className = this.name;
classPackage = this.package;
classFullName = this.fullName;
}
end
return this.static[k].value
end;
__newindex = function (_, k, v)
if reservedClassKeywords[k] then
error("Attempt to override reserved field " .. tostring(k) .. " of class " .. this.fullName .. ".", 2)
elseif not this.static[k] then
error("Attempt to set a non-existant static field " .. tostring(k) .. " of class " .. this.fullName .. ".", 2)
elseif this.static[k].locked then
error("Attempt to override static method " .. tostring(k) .. " of class " .. this.fullName .. ".", 2)
end
this.static[k].value = v
end;
__call = function (_, ...)
local selfChain, typeChain = {}
local function buildSelf (classInstance, index, showLocals, canOverride)
canOverride = expect(canOverride, "boolean", true)
local self, metatable, mt = {}, {}, {}
if classInstance.isInterface then
self[#self + 1] = classInstance.globals
for i = 1, #typeChain do
local instanceType = typeChain[i]
if instanceType.isClass then
local interfaceFields = {}
for name, global in pairs(instanceType.globals) do
if classInstance.class.requiredGlobals[name] then
interfaceFields[name] = global
end
end
self[#self + 1] = interfaceFields
end
end
elseif classInstance.isClass then
local isOverridable = {}
if showLocals then
self[#self + 1] = classInstance.locals
end
if canOverride then
for i = index, #typeChain do
local instanceType = typeChain[i]
if instanceType.isClass then
isOverridable[instanceType.fullName] = true
end
end
for i = index - 1, 1, -1 do
local instanceType = typeChain[i]
if instanceType.isClass then
local overriddenFields = {}
for name, global in pairs(instanceType.globals) do
if global.override and isOverridable[global.override] then
overriddenFields[name] = global
end
end
self[#self + 1] = overriddenFields
end
end
end
for i = index, #typeChain do
local instanceType = typeChain[i]
if instanceType.isClass then
self[#self + 1] = instanceType.globals
if showLocals then
self[#self + 1] = instanceType.static
end
end
end
for i = #typeChain, index, -1 do
local instanceType = typeChain[i]
if instanceType.isClass then
for name, metamethod in pairs(instanceType.meta) do
metatable[name] = {
value = metamethod;
selfInstance = instanceType;
}
end
end
end
end
if classInstance.isClass then
for k, v in pairs(metatable) do
if isin(k:sub(3), {"add", "sub", "mul", "div", "mod", "pow", "concat"}) then
mt[k] = function (a, b, ...)
if is(a, classInstance.fullName) then
return v.value(v.selfInstance.localSelf or v.selfInstance.self, b, ...)
end
return v.value(a, v.selfInstance.localSelf or v.selfInstance.self, ...)
end
elseif type(v.value) == "function" then
mt[k] = function (_, ...)
return v.value(v.selfInstance.localSelf or v.selfInstance.self, ...)
end
else
mt[k] = v.value
end
end
end
if not mt.__tostring then
mt.__tostring = function ()
return classInstance.fullName .. ": " .. tostring(classInstance)
end
end
local msgClass = (classInstance.isClass and "class" or "interface") .. " " .. classInstance.fullName
mt.__type = classInstance.fullName
mt.__index = function (_, k)
if k == "__prop__" then
return {
className = classInstance.name;
classPackage = classInstance.package;
classFullName = classInstance.fullName;
selfChain = classInstance.selfChain;
}
elseif k == "base" then
return showLocals and classInstance.class.inherits and (function ()
local indx
for i = index + 1, #typeChain do
if typeChain[i].fullName == classInstance.class.inherits.fullName then
indx = i
break;
end
end
if indx then
return setmetatable({}, {
__index = buildSelf(typeChain[indx], indx, false, false);
__call = indx and not typeChain.constructed and function (_, ...) classInstance.class.inherits.constructor(buildSelf(typeChain[indx], indx, true), ...) end
or
function () error("Attempt to call a constructor of an already constructed class.", 2) end
})
end
end)() or nil
elseif k == "this" then
return showLocals and classInstance.self or nil
end
for i, container in ipairs(self) do
if container[k] then
return container[k].value
end
end
if metatable.__index then
local var = metatable.__index
if type(var.value) == "function" then
return var.value(var.selfInstance.localSelf or var.selfInstance.self, k)
elseif type(var) == "table" then
return var.value[k]
end
end
error("Field " .. tostring(k) .. " in " .. msgClass .. " does not exist.", 2)
end
mt.__newindex = function (_, k, v)
if reservedClassKeywords[k] then
error("Attempt to override reserved field " .. tostring(k) .. " of " .. msgClass .. ".", 2)
end
for i, container in ipairs(self) do
if container[k] then
if container[k].isStatic then
error("Attempt to set static field " .. k .. " of " .. msgClass .. " through an instance.", 2)
elseif container[k].locked then
error("Attempt to override locked field " .. k .. " of " .. msgClass .. ".", 2)
end
container[k].value = v
return
end
end
if metatable.__newindex and type(metatable.__newindex.value) == "function" then
return metatable.__newindex.value(metatable.__newindex.selfInstance.localSelf or metatable.__newindex.selfInstance.self, k, v)
end
error("Attempt to set a non-existant field " .. tostring(k) .. " in " .. msgClass .. ".", 2)
end
return setmetatable({}, mt)
end
local function getTypeChain (typeChain, class, isInterface)
typeChain = typeChain or {}
if not isInterface then
local classInstance = {
isClass = true;
class = class;
selfChain = selfChain;
name = class.name;
package = class.package;
fullName = class.fullName;
locals = {};
globals = {};
static = class.static;
meta = class.meta;
self = nil;
localSelf = nil;
}
for name, var in pairs(class.locals) do
classInstance.locals[name] = {
value = var.value;
locked = var.locked;
}
end
for name, var in pairs(class.globals) do
local value = var.value
if type(value) == "function" then
value = function (self, ...)
return var.value(classInstance.localSelf, ...)
end
end
classInstance.globals[name] = {
value = value;
isVirtual = var.isVirtual;
override = var.override;
locked = var.locked;
}
end
typeChain[#typeChain + 1] = classInstance
if class.interfaces then
for i = 1, #class.interfaces do
getTypeChain(typeChain, class.interfaces[i], true)
end
end
if class.inherits then
getTypeChain(typeChain, class.inherits)
end
else
local interfaceInstance = {
isInterface = true;
class = class;
selfChain = selfChain;
name = class.name;
package = class.package;
fullName = class.fullName;
globals = {};
self = nil;
};
for name, var in pairs(class.globals) do
interfaceInstance.globals[name] = {
value = var.value;
of = var.of;
locked = var.locked;
}
end
typeChain[#typeChain + 1] = interfaceInstance
end
return typeChain
end
typeChain = getTypeChain({}, this)
for i, typeInstance in ipairs(typeChain) do
typeInstance.self = buildSelf(typeInstance, i)
if typeInstance.isClass then
typeInstance.localSelf = buildSelf(typeInstance, i, true)
end
selfChain[#selfChain + 1] = typeInstance.self
end
for i, typeInstance in ipairs(typeChain) do
if typeInstance.isInterface then
for name, var in pairs(typeInstance.globals) do
if type(var.value) == "function" then
local value, self = var.value
for i, typeInstance in ipairs(typeChain) do
if typeInstance.fullName == var.of then
self = typeInstance.localSelf
break;
end
end
var.value = function (_, ...)
return value(self, ...)
end
end
end
end
end
this.constructor(typeChain[1].localSelf, ...)
typeChain.constructed = true
return typeChain[1].self
end;
})
classes[this.fullName] = thisProxy
resolvePackage(this.package)[this.name] = thisProxy
return thisProxy
end;
})
if prop then
return proxy(prop, 1 + level)
end
return proxy
end
})
local function resolveType (env, typ)
local _typ = class.getFullName(env, typ)
return classes[_typ] and _typ or interface.getFullName(env, typ) or typ
end
local function switch (val, statements)
local function c (s)
if s[val] then
return true, s[val](val)
elseif s.default then
return false, s.default(val)
end
return false
end
if statements then
return c(statements)
end
return c
end
local function try (tryFunc, catchFunc)
local ok, err = pcall(tryFunc)
local function c (_, catchFunc)
if not ok then
catchFunc(err)
end
end
if catchFunc then
return c(_, catchFunc)
end
return {catch = c}
end
local function hook (env, root)
local _env = expect(env, "table", {}, "environment")
root = expect(root, "string", "/", "root")
env = setmetatable({}, { __index = function (_, k)
if isPackageNameValid(env.__package) then
local pkg = resolvePackage(env.__package)
if pkg and pkg[k] then
return pkg[k]
end
end
for import in pairs(env.__imports) do
if isPackageNameValid(import) then
local pkg, class = resolvePackage(import)
if pkg and pkg[k] then
return pkg[k]
elseif class and class.__prop__.className == k then
return class
end
end
end
if packages[k] then
return packages[k]
end
return _env[k]
end; })
env.null = null
env.type = type
env.tonumber = tonumber
env.isidentifier = isidentifier
env.isprimitive = isprimitive
env.isin = isin
env.split = split
env.isPackageNameValid = isPackageNameValid
env.classes = classes
env.hook = hook
env.switch = switch
env.try = try
env.resolveType = function (env, typ)
return resolveType(env, typ)
end
env.expect = function (value, expectType, default, name, level)
expectType = resolveType(env, expectType)
level = level == nil and 2 or level == 0 and 0 or level
return expect(value, expectType, default, name, level)
end
env.cast = function (obj, typ, level)
typ = resolveType(env, typ)
level = level == nil and 1 or level == 0 and 0 or level + 1
return cast(obj, typ, level)
end
env.is = function (obj, typ)
typ = resolveType(env, typ)
return is(obj, typ)
end
env.interface = setmetatable({}, {
__index = {
resolvePackage = function ()
return interface.resolvePackage(env)
end;
getFullName = function (name)
return interface.getFullName(env, name)
end;
};
__call = function (_, name, prop, level)
level = level == nil and 3 or level == 0 and 0 or level + 1
return interface(env, name, prop, level)
end;
})
env.class = setmetatable({}, {
__index = {
resolvePackage = function ()
return class.resolvePackage(env)
end;
getFullName = function (name)
return class.getFullName(env, name)
end;
};
__call = function (_, name, prop, level)
level = level == nil and 3 or level == 0 and 0 or level + 1
return class(env, name, prop, level)
end;
})
env.__package = ""
function env.package (package, importPackage)
expect(package, "string", nil, "package")
importPackage = expect(importPackage, "boolean", true, "import package")
if not isPackageNameValid(package) then
error("Invalid package name '" .. package .. "'.", 2)
end
packages[package] = resolvePackage(package)
env.__package = package
if importPackage and not packages[package][1] then
packages[package][1] = true
env.import(package)
packages[package][1] = false
end
end
env.__imports = {}
function env.import (name)
expect(name, "string", nil, "import name")
if env.__imports[name] then
return
end
if packages[name] and packages[name][2] then -- already imported
env.__imports[name] = true
return
end
local pkg = split(name, ".")
if #pkg >= 2 then
local className = pkg[#pkg]
local package = name:sub(1, -#className - 2)
if packages[package] and packages[package][className] then
env.__imports[name] = true
return
end
end
local function loadFile (path)
local env = hook(_env, root)
local func, err = loadfile(path, nil, env)
if func then
if setfenv then
setfenv(func, env)
end
local ok, err = pcall(func)
if not ok then
error("An error occured while loading '" .. path .. "':\n" .. err, 3)
end
if packages[name] then
packages[name][2] = true -- imported
end
else
error("An error occured while loading '" .. path .. "':\n" .. err, 3)
end
end
local path = fs.combine(root, fs.combine("", (name:gsub("%.", "/"))))
if fs.isDir(path) then
for i, file in ipairs(fs.list(path)) do
if file:sub(-4) == ".lua" and not fs.isDir(fs.combine(path, file)) then
loadFile(fs.combine(path, file))
env.__imports[name] = true
end
end
elseif fs.exists(path .. ".lua") then
loadFile(path .. ".lua")
env.__imports[name] = true
end
end
return env
end
local loo = hook(getfenv and getfenv() or _ENV)
loo.package ("loo", false)
loo.class "Object" {
virtual_toString = function (self)
return "Object: " .. self.__prop__.selfChain[1].__prop__.classFullName
end;
meta_tostring = function (self)
return self:toString()
end;
}
loo.class "Enumerable" {
virtual_next = function (self, control)
error("Method 'next' was not overridden.", 2)
end;
meta_call = function (self, state, control)
return self:next(state, control)
end;
}
loo.class "Array" : inherits "Enumerable" {
local_itemType = null;
local_items = null;
Array = function (self, itemType, items)
self.itemType = expect(itemType, "string", nil, "item type")
self.items = expect(items, "table", {}, "items")
for k, v in pairs(self.items) do
if type(k) ~= "number" or k <= 0 or k > #self.items or type(v) ~= self.itemType then
error("array of " .. self.itemType .. "s expected.", 3)
end
end
end;
insert = function (self, i, v)
if v == nil then
i, v = #self.items + 1, i
end
expect(i, "number", nil, "index")
expect(v, self.itemType, nil, "value")
if i <= 0 or i > #self.items + 1 then
error("Array index out of range.", 2)
end
table.insert(self.items, i, v)
end;
remove = function (self, i)
expect(i, "number", nil, "index")
if i <= 0 or i > #self.items then
error("Array index out of range.", 2)
end
return table.remove(self.items, i)
end;
each = function (self, func)
expect(func, "function", nil, "each function")
for i = 1, #self.items do
func(i, self.items[i])
end
end;
len = function (self)
return #self.items
end;
toTable = function (self)
local tab = {}
self:each(function (i, item)
tab[i] = item
end)
return tab
end;
override_next = function (self, state, i)
i = i and i + 1 or state or 1
if i <= 0 or i > #self.items then
return nil
end
return i, self.items[i]
end;
override_toString = function (self)
local str = "{"
self:each(function (i, item)
str = str .. tostring(item) .. ", "
end)
return str:sub(1, -3) .. "}"
end;
meta_index = function (self, i)
expect(i, "number", nil, "index", 2)
if i <= 0 or i > #self.items then
error("Array index out of range.", 2)
end
return self.items[i]
end;
meta_newindex = function (self, i, v)
expect(i, "number", nil, "index", 2)
expect(v, self.itemType, nil, "value", 2)
if i <= 0 or i > #self.items + 1 then
error("Array index out of range.", 2)
end
self.items[i] = v
end;
}
loo.class "String" {
static_split = function (self, str, del)
loo.expect(str, "string", nil, "string")
del = loo.expect(del, "string", ",", "delimiter")
return split(str, del)
end;
static_trimLeft = function (self, str, char)
loo.expect(str, "string", nil, "string")
char = loo.expect(char, "string", "%s", "trim character")
return str:gsub("^" .. char .. "+", "")
end;
static_trimRight = function (self, str, char)
loo.expect(str, "string", nil, "string")
char = loo.expect(char, "string", "%s", "trim character")
return str:gsub(char .. "+$", "")
end;
static_trim = function (self, str, char)
loo.expect(str, "string", nil, "string")
char = loo.expect(char, "string", "%s", "trim character")
return self.trimRight(self.trimLeft(str, char), char)
end;
}
return loo
| 28.749798
| 182
| 0.537211
|
cd21bb5ef9c8ee8009f46abc4d3d8612cf202f5e
| 1,399
|
cs
|
C#
|
csharp/Q021_MergeTwoSortedLists.cs
|
txchen/localleet
|
c2d79c6169bb42a1e58d119998b39f5b1c85dd85
|
[
"MIT"
] | null | null | null |
csharp/Q021_MergeTwoSortedLists.cs
|
txchen/localleet
|
c2d79c6169bb42a1e58d119998b39f5b1c85dd85
|
[
"MIT"
] | null | null | null |
csharp/Q021_MergeTwoSortedLists.cs
|
txchen/localleet
|
c2d79c6169bb42a1e58d119998b39f5b1c85dd85
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
// Merge two sorted linked lists and return it as a new list.
// The new list should be made by splicing together the nodes of the first two lists.
// https://leetcode.com/problems/merge-two-sorted-lists/
namespace LocalLeet
{
public class Q021
{
public ListNode<int> MergeTwoLists(ListNode<int> l1, ListNode<int> l2)
{
ListNode<int> preAnswer = new ListNode<int>(0);
var temp = preAnswer;
while (l1 != null && l2 != null)
{
if (l1.Val < l2.Val)
{
temp.Next = new ListNode<int>(l1.Val);
l1 = l1.Next;
}
else
{
temp.Next = new ListNode<int>(l2.Val);
l2 = l2.Next;
}
temp = temp.Next;
}
if (l1 != null)
{
temp.Next = l1;
}
if (l2 != null)
{
temp.Next = l2;
}
return preAnswer.Next;
}
[Fact]
public void Q021_MergeTwoSortedLists()
{
TestHelper.Run(input =>
MergeTwoLists(input[0].ToListNode<int>(), input[1].ToListNode<int>()).SerializeListNode());
}
}
}
| 27.431373
| 107
| 0.467477
|
5ae11e9641c487de83245d1238d1c3c8e0fce20a
| 1,251
|
cs
|
C#
|
FutbolApp/Modelo/USUARIO.cs
|
danykt/SoccerAPP
|
0627bbb6ced05e505d91c56435dbbdc37857f6b3
|
[
"MIT"
] | null | null | null |
FutbolApp/Modelo/USUARIO.cs
|
danykt/SoccerAPP
|
0627bbb6ced05e505d91c56435dbbdc37857f6b3
|
[
"MIT"
] | null | null | null |
FutbolApp/Modelo/USUARIO.cs
|
danykt/SoccerAPP
|
0627bbb6ced05e505d91c56435dbbdc37857f6b3
|
[
"MIT"
] | null | null | null |
using System;
namespace FutbolApp.Modelo
{
public class USUARIO
{
[Newtonsoft.Json.JsonProperty("Id")]
public string Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName { get; set; }
public bool deleted { get; set; }
public DateTime DateUtc { get; set; }
[Newtonsoft.Json.JsonIgnore]
public string DateLabel { get { return DateUtc.ToLocalTime().ToString("d");}}
[Newtonsoft.Json.JsonIgnore]
public string TimeLabel { get { return DateUtc.ToLocalTime().ToString("t"); }}
[Newtonsoft.Json.JsonIgnore]
public string NameLabel { get { return deleted ? "deleted" : FullName; } }
[Microsoft.WindowsAzure.MobileServices.Version]
public string AzureVersion { get; set; }
public USUARIO(){}
public USUARIO(string Username, string Password)
{
this.Username = Username;
this.Password = Password;
}
public bool CheckInformation()
{
if (this.Username != null && this.Password != null)
return true;
else
return false;
}
}
}
| 27.195652
| 86
| 0.573941
|
7979dcbf910fb98ba6cf6f333e2bc6bb8bf48c82
| 2,271
|
php
|
PHP
|
backend/views/trainer/index.php
|
geksor/amg-backend-Yii2
|
a456637434a857194f8dc8838a36b140c67ab98c
|
[
"BSD-3-Clause"
] | null | null | null |
backend/views/trainer/index.php
|
geksor/amg-backend-Yii2
|
a456637434a857194f8dc8838a36b140c67ab98c
|
[
"BSD-3-Clause"
] | null | null | null |
backend/views/trainer/index.php
|
geksor/amg-backend-Yii2
|
a456637434a857194f8dc8838a36b140c67ab98c
|
[
"BSD-3-Clause"
] | null | null | null |
<?php
use yii\helpers\Html;
use yiister\adminlte\widgets\grid\GridView;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $searchModel common\models\UserSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Тренеры';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php Pjax::begin(); ?>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<div class="box box-primary">
<div class="box-body">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
// 'id',
'username',
// 'surname',
'first_name',
// 'last_name',
//'auth_key',
//'password_hash',
//'password_reset_token',
// 'email:email',
//'status',
//'role',
//'created_at',
//'updated_at',
[
'label' => 'Дата тренинга',
'value' => function ($data){
/* @var $data \common\models\User */
if ($data->training_id){
return date('d.m.y', $data->training->date);
}
return null;
}
],
'group',
//'training_id',
//'dealer_center_id',
// 'amgStatic',
// 'mixStatic',
// 'mbux',
// 'xClassDrive',
// 'amgDrive',
// 'intelligent',
// 'mixDrive',
// 'xClassLine',
// 'quiz',
// 'moderatorPoints',
// 'totalPoint',
//'command_id',
[
'class' => 'yii\grid\ActionColumn',
'template' => '{view} {update}',
],
],
"condensed" => true,
"hover" => true,
]); ?>
</div>
</div>
<?php Pjax::end(); ?>
</div>
| 29.881579
| 73
| 0.380449
|
2580c378bdbd5123b20a8c7619b2a463e4e26c67
| 2,516
|
js
|
JavaScript
|
src/lib/models/AddressState.js
|
decentraland/auction
|
4ba807d2c8b36d3509169f04b5ee5942c6578b72
|
[
"Apache-2.0"
] | 35
|
2017-11-30T00:33:06.000Z
|
2021-11-20T09:05:42.000Z
|
src/lib/models/AddressState.js
|
BEAR-finance/auction
|
461447e469b099f37bc1f582d3486437e68f0bb6
|
[
"Apache-2.0"
] | 63
|
2017-11-28T09:25:10.000Z
|
2018-01-04T22:15:58.000Z
|
src/lib/models/AddressState.js
|
BEAR-finance/auction
|
461447e469b099f37bc1f582d3486437e68f0bb6
|
[
"Apache-2.0"
] | 9
|
2017-12-11T09:47:13.000Z
|
2021-11-20T09:05:19.000Z
|
import { Model } from 'decentraland-commons'
import BidGroup from './BidGroup'
class AddressState extends Model {
static tableName = 'address_states'
static columnNames = [
'address',
'balance',
'latestBidGroupId',
'email',
'returnAmount',
'withdrawnAmount'
]
static async findByAddress(address) {
return this.findOne({ address })
}
static async findAll(address) {
return this.find()
}
static async findByEmail(email) {
return this.findOne({ email })
}
static async findAllAddresses() {
return this.find().then(rows => rows.map(r => r.address))
}
static async findByAddressWithLastBidGroup(address) {
const rows = await this.db.query(
`SELECT "address_states".*, row_to_json(bid_groups.*) as "bidGroup" FROM address_states
LEFT JOIN bid_groups ON address_states."latestBidGroupId" = bid_groups."id"
WHERE address_states."address" = $1
LIMIT 1`,
[address]
)
if (rows.length > 0) {
const { bidGroup, ...addressState } = rows[0]
if (bidGroup) {
// We need to deserialize the stringified version of each BYTEA row generated by `row_to_json`
addressState.bidGroup = BidGroup.deserialize(bidGroup, 'bytea')
}
addressState.email = !!addressState.email
return addressState
}
}
static async findByAddressWithBidGroups(address) {
const rows = await this.db.query(
`SELECT "address_states".*, row_to_json(bid_groups.*) as "bidGroup" FROM address_states
LEFT JOIN bid_groups ON bid_groups."address" = $1
WHERE address_states."address" = $1`,
[address]
)
if (rows.length > 0) {
const addressState = rows[0]
addressState.bidGroups = BidGroup.deserializeJoinedRows(rows)
delete addressState.bidGroup
addressState.email = !!addressState.email
return addressState
}
}
static addBalance(address, balance) {
return this.db.query(
`UPDATE ${AddressState.tableName} SET balance = (balance::float + $1)::int::text WHERE address = $2`,
[balance, address]
)
}
static summary() {
return this.db
.query(
`SELECT COUNT(*), MAX(balance::int), SUM(balance::int) FROM ${AddressState.tableName}`
)
.then(r => r[0])
}
static countWithEmail() {
return this.db
.query(
`SELECT COUNT(*) FROM ${AddressState.tableName} WHERE email IS NOT NULL`
)
.then(r => r[0].count)
}
}
export default AddressState
| 25.938144
| 107
| 0.642687
|
f6005e2eaa3c6d0eeb1b64e27da3234b58af2f2f
| 8,489
|
cpp
|
C++
|
src/engine.cpp
|
mbeckem/extpp
|
06aa153ebf617c779e66d612cfc11e01869c602a
|
[
"MIT"
] | 1
|
2018-05-22T15:47:14.000Z
|
2018-05-22T15:47:14.000Z
|
src/engine.cpp
|
mbeckem/prequel
|
06aa153ebf617c779e66d612cfc11e01869c602a
|
[
"MIT"
] | null | null | null |
src/engine.cpp
|
mbeckem/prequel
|
06aa153ebf617c779e66d612cfc11e01869c602a
|
[
"MIT"
] | null | null | null |
#include <prequel/engine.hpp>
#include <prequel/deferred.hpp>
#include <boost/intrusive/list.hpp>
#include <boost/intrusive/list_hook.hpp>
#include <boost/intrusive/set.hpp>
#include <boost/intrusive/set_hook.hpp>
namespace prequel {
namespace detail {
// This is the real implementation of block handles,
// it contains the additional boost intrusive anchors.
//
// The index of a block handle instance MUST NOT change because
// it is used for indexing by the block handle manager.
//
// TODO: Maybe switch to intrusive hash table instead?
class block_handle_internal final : public block_handle_base {
friend engine;
friend block_handle_manager;
// Block handles are linked together using the block index field.
boost::intrusive::set_member_hook<> index_hook;
// Linked together in a free list.
boost::intrusive::list_member_hook<> freelist_hook;
void reset() {
m_refcount = 0;
m_engine = nullptr;
m_index = block_index();
m_data = nullptr;
m_cookie = 0;
}
};
class block_handle_manager {
public:
block_handle_manager() = default;
~block_handle_manager() {
m_freelist.clear_and_dispose([](block_handle_internal* handle) { delete handle; });
}
block_handle_manager(const block_handle_manager&) = delete;
block_handle_manager& operator=(const block_handle_manager&) = delete;
auto begin() { return m_handles.begin(); }
auto end() { return m_handles.end(); }
void insert(block_handle_internal& handle) noexcept {
auto result = m_handles.insert(handle);
PREQUEL_ASSERT(result.second, "Insertion must have succeeded.");
unused(result);
}
void remove(block_handle_internal& handle) noexcept {
PREQUEL_ASSERT(contains(handle), "Block handle is not linked.");
m_handles.erase(m_handles.iterator_to(handle));
}
bool contains(block_handle_internal& handle) const noexcept {
return handle.index_hook.is_linked();
}
block_handle_internal* find(block_index index) noexcept {
auto iterator = m_handles.find(index);
if (iterator == m_handles.end())
return nullptr;
return &*iterator;
}
size_t size() const noexcept { return m_handles.size(); }
block_handle_internal* allocate() {
if (!m_freelist.empty()) {
block_handle_internal* handle = &m_freelist.front();
m_freelist.pop_front();
return handle;
}
return new block_handle_internal();
}
void free(block_handle_internal* handle) {
static constexpr u32 max = 1024;
if (!handle)
return;
if (m_freelist.size() >= max) {
delete handle;
return;
}
handle->reset();
m_freelist.push_front(*handle);
}
private:
struct block_handle_index {
using type = block_index;
block_index operator()(const block_handle_base& handle_base) const noexcept {
return handle_base.index();
}
};
using set_t = boost::intrusive::set<
block_handle_internal,
boost::intrusive::member_hook<block_handle_internal, boost::intrusive::set_member_hook<>,
&block_handle_internal::index_hook>,
boost::intrusive::key_of_value<block_handle_index>>;
using freelist_t = boost::intrusive::list<
block_handle_internal,
boost::intrusive::member_hook<block_handle_internal, boost::intrusive::list_member_hook<>,
&block_handle_internal::freelist_hook>>;
private:
set_t m_handles;
freelist_t m_freelist;
};
} // namespace detail
engine::engine(u32 block_size)
: m_block_size(block_size)
, m_handle_manager(new detail::block_handle_manager()) {
if (!is_pow2(block_size)) {
PREQUEL_THROW(bad_argument(fmt::format("Block size is not a power of two: {}.", block_size)));
}
m_block_size_log = log2(block_size);
m_offset_mask = m_block_size - 1;
}
engine::~engine() {
if (handle_manager().size() > 0) {
PREQUEL_ABORT("There are still block handles in use while the engine is being destroyed.");
}
}
u64 engine::size() const {
return do_size();
}
void engine::grow(u64 n) {
if (n > 0) {
do_grow(n);
}
}
void engine::flush() {
do_flush();
}
block_handle engine::read(block_index index) {
if (!index.valid()) {
PREQUEL_THROW(bad_argument("Invalid block index."));
}
return internal_populate_handle(index, initialize_block_t{});
}
block_handle engine::overwrite_zero(block_index index) {
if (!index.valid()) {
PREQUEL_THROW(bad_argument("Invalid block index."));
}
return internal_populate_handle(index, initialize_zero_t{});
}
block_handle engine::overwrite(block_index index, const byte* data, size_t size) {
if (!index.valid()) {
PREQUEL_THROW(bad_argument("Invalid block index."));
}
if (size > m_block_size) {
PREQUEL_THROW(bad_argument(fmt::format(
"Buffer is too large for a single block ({} bytes given, block size is {} bytes).",
size, m_block_size)));
}
return internal_populate_handle(index, initialize_data_t{data, size});
}
template<typename Initializer>
block_handle engine::internal_populate_handle(block_index index, Initializer&& init) {
static constexpr bool overwrite =
!std::is_same_v<remove_cvref_t<Initializer>, initialize_block_t>;
PREQUEL_ASSERT(index.valid(), "Invalid index.");
auto& manager = handle_manager();
// We might have a handle to this block already.
if (auto handle = manager.find(index)) {
PREQUEL_ASSERT(handle->m_refcount > 0,
"The handle must be referenced "
"if it can be found through the manager.");
if constexpr (overwrite) {
init.apply(handle->m_data, m_block_size);
do_dirty(index, handle->m_cookie);
}
return block_handle(handle);
}
// Prepare a handle for the new block.
auto handle = manager.allocate();
deferred cleanup_handle = [&] { manager.free(handle); };
// Read the block from disk. Don't initialize the contents
// if we're about to overwrite them anyway.
pin_result pinned = do_pin(index, !overwrite);
deferred cleanup_pin = [&] { do_unpin(index, pinned.cookie); };
// Initialize the block contents.
if constexpr (overwrite) {
init.apply(pinned.data, m_block_size);
do_dirty(index, pinned.cookie);
}
handle->m_engine = this;
handle->m_index = index;
handle->m_data = pinned.data;
handle->m_cookie = pinned.cookie;
manager.insert(*handle);
cleanup_pin.disable();
cleanup_handle.disable();
return block_handle(handle);
(void) init; // unused warning :/
}
void engine::internal_flush_handle(detail::block_handle_base* base) {
PREQUEL_ASSERT(base, "Invalid handle instance.");
PREQUEL_ASSERT(base->get_engine() == this, "Handle does not belong to this engine.");
detail::block_handle_internal* handle = static_cast<detail::block_handle_internal*>(base);
PREQUEL_ASSERT(handle_manager().contains(*handle), "Handle is not managed by this instance.");
do_flush(handle->index(), handle->m_cookie);
}
void engine::internal_dirty_handle(detail::block_handle_base* base) {
PREQUEL_ASSERT(base, "Invalid handle instance.");
PREQUEL_ASSERT(base->get_engine() == this, "Handle does not belong to this engine.");
detail::block_handle_internal* handle = static_cast<detail::block_handle_internal*>(base);
PREQUEL_ASSERT(handle_manager().contains(*handle), "Handle is not managed by this instance.");
do_dirty(handle->index(), handle->m_cookie);
}
void engine::internal_release_handle(detail::block_handle_base* base) noexcept {
PREQUEL_ASSERT(base, "Invalid handle instance.");
PREQUEL_ASSERT(base->get_engine() == this, "Handle does not belong to this engine.");
detail::block_handle_internal* handle = static_cast<detail::block_handle_internal*>(base);
do_unpin(handle->index(), handle->m_cookie);
auto& manager = handle_manager();
manager.remove(*handle);
manager.free(handle);
}
detail::block_handle_manager& engine::handle_manager() const {
PREQUEL_ASSERT(m_handle_manager, "Invalid block handle manager instance.");
return *m_handle_manager;
}
} // namespace prequel
| 31.324723
| 102
| 0.668512
|
8b5f0f857866bc68c1b93cdc777f0b5b4de255f6
| 643
|
lua
|
Lua
|
assets/preload/data/body/modchart.lua
|
Tre-One/CAROL-HD-Open-Source
|
199e34565cefa2ac4a491d380945308b53e81663
|
[
"Apache-2.0"
] | null | null | null |
assets/preload/data/body/modchart.lua
|
Tre-One/CAROL-HD-Open-Source
|
199e34565cefa2ac4a491d380945308b53e81663
|
[
"Apache-2.0"
] | null | null | null |
assets/preload/data/body/modchart.lua
|
Tre-One/CAROL-HD-Open-Source
|
199e34565cefa2ac4a491d380945308b53e81663
|
[
"Apache-2.0"
] | 1
|
2022-01-28T18:45:38.000Z
|
2022-01-28T18:45:38.000Z
|
-- this gets called starts when the level loads.
function start(song) -- arguments, the song name
end
-- this gets called every frame
function update(elapsed) -- arguments, how long it took to complete a frame
end
-- this gets called every beat
function beatHit(beat) -- arguments, the current beat of the song
end
-- this gets called every step
function stepHit(step) -- arguments, the current step of the song (4 steps are in a beat)
if step == 189 then
playAnim('dad', 'hey')
end
if step == 701 then
playAnim('dad', 'hey')
end
if step == 897 then
playAnim('dad', 'hey')
end
end
| 20.741935
| 89
| 0.657854
|
e2435a4f2cef78c3c6b19974d341b9c8f6718a35
| 50,905
|
js
|
JavaScript
|
assets/js/sistemapic_1.js
|
DenerCampos/sistemapic
|
63604aa0fd00d9a896057b7b6df47376869cbf8c
|
[
"MIT"
] | null | null | null |
assets/js/sistemapic_1.js
|
DenerCampos/sistemapic
|
63604aa0fd00d9a896057b7b6df47376869cbf8c
|
[
"MIT"
] | null | null | null |
assets/js/sistemapic_1.js
|
DenerCampos/sistemapic
|
63604aa0fd00d9a896057b7b6df47376869cbf8c
|
[
"MIT"
] | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function() {
//função para mostrar o calendario do jquery no navegador firefox.
$(function(){
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
$('input[type=date]').datepicker({
dateFormat : 'yy-mm-dd'
}
);
}
});
//popover bootstrap
$('[data-toggle="popover"]').popover({
trigger: 'hover',
html: 'true',
placement: 'left',
container: 'map'
});
//tooltip bootstrap
$('[data-toggle="tooltip"]').tooltip();
//Login
$('.trigger').popover({
html: true,
title: function(){
return $(this).parent().find('.head').html();
},
content: function(){
return $(this).parent().find('.content').html();
},
placement: 'bottom',
container: 'body'
});
//Autocomplete Caixas
$('.buscaMaquina').autocomplete({
source: function(request, response){
$.ajax({
type:"get",
dataType: "json",
url: baseUrl+"caixa/buscarMaquina",
data: {
termo: request.term
},
success: function(data){
response(data);
}
});
}
});
//Verificar estado maquina onload
//$('span[onload]').trigger('onload');
//Criação de usuario - ao selecionar nivel tecnico, habilita area de atendimento
$("#selCriNivel").change(function(){
//console.log($("#selCriNivel").val());
if ($("#selCriNivel").val() !== "Técnico"){
$("#selCriArea").prop({disabled: true});
} else {
$("#selCriArea").prop({disabled: false})
}
});
$("#selEdtNivel").change(function(){
//console.log($("#selCriNivel").val());
if ($("#selEdtNivel").val() !== "Técnico"){
$("#selEdtArea").prop({disabled: true});
} else {
$("#selEdtArea").prop({disabled: false})
}
});
//Fotos usuario perfil
$('#iptEdtFoto').on("change", function(){
fotoPerfil(this);
});
//Anexar help desk
// Criar chamado
$('#cria-anexo0').change(function(){
console.log("input teve mudanças");
$elemento = $(this).parent().prev();
//$elemento.find('.lightview').removeClass("hidden");
anexarImagem(this, $elemento);
});
$('#cria-anexo1').change(function(){
console.log("input teve mudanças");
$elemento = $(this).parent().prev();
//$elemento.find('.lightview').removeClass("hidden");
anexarImagem(this, $elemento);
});
$('#cria-anexo2').change(function(){
console.log("input teve mudanças");
$elemento = $(this).parent().prev();
//$elemento.find('.lightview').removeClass("hidden");
anexarImagem(this, $elemento);
});
// editar chamado
$('#edita-anexo0').change(function(){
console.log("input teve mudanças");
$elemento = $(this).parent().prev();
//$elemento.find('.lightview').removeClass("hidden");
anexarImagem(this, $elemento);
});
$('#edita-anexo1').change(function(){
console.log("input teve mudanças");
$elemento = $(this).parent().prev();
//$elemento.find('.lightview').removeClass("hidden");
anexarImagem(this, $elemento);
});
$('#edita-anexo2').change(function(){
console.log("input teve mudanças");
$elemento = $(this).parent().prev();
//$elemento.find('.lightview').removeClass("hidden");
anexarImagem(this, $elemento);
});
// fechar chamado
$('#fecha-anexo0').change(function(){
console.log("input teve mudanças");
$elemento = $(this).parent().prev();
//$elemento.find('.lightview').removeClass("hidden");
anexarImagem(this, $elemento);
});
$('#fecha-anexo1').change(function(){
console.log("input teve mudanças");
$elemento = $(this).parent().prev();
//$elemento.find('.lightview').removeClass("hidden");
anexarImagem(this, $elemento);
});
$('#fecha-anexo2').change(function(){
console.log("input teve mudanças");
$elemento = $(this).parent().prev();
//$elemento.find('.lightview').removeClass("hidden");
anexarImagem(this, $elemento);
});
//Formularios
$(".formulario").submit(function(){
formulario = this;
botao = $(formulario).find(".carregando");
carregando(botao);
});
//Home animação
animacaoHome();
});
//Anexar imagem
function anexarImagem(input, elemento){
//verifica se existe realmente a imagem
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(elemento).find('.lightview').attr("href", e.target.result);
$(elemento).find('img').attr('src', e.target.result);
$(elemento).find('.lightview').removeClass("hidden");
};
reader.readAsDataURL(input.files[0]);
}
else {
}
}
//Animação home
function animacaoHome(){
$(".titulo-home").delay(100).slideDown(300);
//$(".img-home").delay(450);
$(".img-home").animate({
left: 0,
opacity: 1
});
$(".img-home").animate({
width: 250
});
$(".rodape-home").delay(1000).slideDown(1000);
}
//Esconder tela login
function esconderLogin(){
$('.trigger').popover('hide');
}
//Animação de carregando (botões)
function carregando(button){
$html = '<i class="fa fa-spinner fa-pulse fa-fw"></i>';
$valor = $(button).html();
$(button).html($valor+" "+$html);
$(button).attr("disabled", "disabled");
}
//CRUD MAQUINAS
//Verificar estado
function verificarEstado(ancor){
$(ancor).children().removeClass('fa-info-circle');
$(ancor).children().removeClass('fa-check-circle-o');
$(ancor).children().removeClass('fa-ban');
$(ancor).children().addClass('fa-refresh fa-spin');
$.ajax({
type:"post",
url:baseUrl+"caixa/verificarEstado",
data:{
"idmaquina": $(ancor).attr("data-id")
},
success:function(msg){
if(msg == true){
$(ancor).children().removeClass('fa-refresh fa-spin');
$(ancor).children().addClass('fa-check-circle-o');
}else {
$(ancor).children().removeClass('fa-refresh fa-spin');
$(ancor).children().addClass('fa-ban');
}
},
error: function(erro){
//alert (valueOf(erro));
console.log(erro);
}
});
//console.log($(span).attr("data-id"));
}
//Edição de caixa
function editarCaixa(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"caixa/editarCaixa",
//Dados
data:{
"idmaquina":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idmaquina);
$("#iptEdtNome").val(msg.nome);
$("#iptEdtIp").val(msg.ip);
$("#selEdtLocal").val(msg.local);
}
else{
alert(msg.erro);
}
}
});
}
//Remover caixa
function removerCaixa(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"caixa/removerCaixa",
//Dados
data:{
"idmaquina":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idmaquina);
$("#iptRmvNome").val(msg.nome);
$("#iptRmvIp").val(msg.ip);
$("#selRmvLocal").val(msg.local);
}
else{
alert(msg.erro);
}
}
});
}
//CRUD USUARIO
//Edição de usuario
function editarUsuario(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/usuario_admin/editarUsuario",
//Dados
data:{
"idusuario":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idusuario);
$("#iptEdtNome").val(msg.nome);
$("#iptEdtEmail").val(msg.login);
$("#selEdtNivel").val(msg.nivel);
$("#selEdtEstado").val(msg.estado);
$("#selEdtArea").val(msg.area);
//verifica area se tecnico para habilitar
if (msg.nivel === "Técnico"){
$("#selEdtArea").prop({disabled: false});
} else {
$("#selEdtArea").prop({disabled: true});
}
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Remover usuario
function removerUsuario(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/usuario_admin/removerUsuario",
//Dados
data:{
"idusuario":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idusuario);
$("#iptRmvNome").val(msg.nome);
$("#iptRmvEmail").val(msg.login);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Ativar usuario
function ativarUsuario(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/usuario_admin/ativarUsuario",
//Dados
data:{
"idusuario":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptAtvId").val(msg.idusuario);
$("#iptAtvNome").val(msg.nome);
$("#iptAtvEmail").val(msg.login);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//CRUD AREAS
//Edição de area
function editarArea(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/area_admin/editarArea",
//Dados
data:{
"idarea":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idarea);
$("#iptEdtNome").val(msg.nome);
$("#iptEdtEmail").val(msg.email);
$("#selEdtEstado").val(msg.estado);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Remover area
function removerArea(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/area_admin/removerArea",
//Dados
data:{
"idarea":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idarea);
$("#iptRmvNome").val(msg.nome);
$("#iptRmvEmail").val(msg.email);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//ativar area
function ativarArea(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/area_admin/ativarArea",
//Dados
data:{
"idarea":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptAtvId").val(msg.idarea);
$("#iptAtvNome").val(msg.nome);
$("#iptAtvEmail").val(msg.email);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//CRUD SETORES
//Edição de setor
function editarSetor(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/setor_admin/editarSetor",
//Dados
data:{
"idsetor":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idsetor);
$("#iptEdtNome").val(msg.nome);
$("#selEdtEstado").val(msg.estado);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Remover setor
function removerSetor(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/setor_admin/removerSetor",
//Dados
data:{
"idsetor":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idsetor);
$("#iptRmvNome").val(msg.nome);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//ativar setor
function ativarSetor(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/setor_admin/ativarSetor",
//Dados
data:{
"idsetor":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptAtvId").val(msg.idsetor);
$("#iptAtvNome").val(msg.nome);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//CRUD UNIDADES
//Edição de unidade
function editarUnidade(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/unidade_admin/editarUnidade",
//Dados
data:{
"idunidade":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idunidade);
$("#iptEdtNome").val(msg.nome);
$("#selEdtEstado").val(msg.estado);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Remover unidade
function removerUnidade(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/unidade_admin/removerUnidade",
//Dados
data:{
"idunidade":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idunidade);
$("#iptRmvNome").val(msg.nome);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//ativar setor
function ativarUnidade(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/unidade_admin/ativarUnidade",
//Dados
data:{
"idunidade":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptAtvId").val(msg.idunidade);
$("#iptAtvNome").val(msg.nome);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//CRUD PROBLEMAS
//Edição de problema
function editarProblema(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/problema_admin/editarProblema",
//Dados
data:{
"idproblema":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idproblema);
$("#iptEdtNome").val(msg.nome);
$("#iptEdtDesc").val(msg.descricao);
$("#selEdtEstado").val(msg.estado);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Remover problema
function removerProblema(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/problema_admin/removerProblema",
//Dados
data:{
"idproblema":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idproblema);
$("#iptRmvNome").val(msg.nome);
$("#iptRmvDesc").val(msg.descricao);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//ativar setor
function ativarProblema(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/problema_admin/ativarProblema",
//Dados
data:{
"idproblema":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptAtvId").val(msg.idproblema);
$("#iptAtvNome").val(msg.nome);
$("#iptAtvDesc").val(msg.descricao);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//CRUD ESTADO OCORRENCIAS
//Edição de problema
function editarEstado(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/ocorrencia_estado_admin/editarEstado",
//Dados
data:{
"idestado":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idestado);
$("#iptEdtNome").val(msg.nome);
$("#iptEdtDesc").val(msg.descricao);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//CRUD EMAIL CONF
//Edição de email conf
function editarEmailConf(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/email_conf_admin/editarEmailConf",
//Dados
data:{
"idemailconf":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idemailconf);
$("#iptEdtUserName").val(msg.username);
$("#selEdtProtocol").val(msg.protocol);
$("#iptEdtHost").val(msg.host);
$("#iptEdtUser").val(msg.user);
$("#iptEdtPass").val(msg.pass);
$("#iptEdtPort").val(msg.port);
$("#selEdtCryp").val(msg.cryp);
$("#selEdtEstado").val(msg.estado);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Remover email conf
function removerEmailConf(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/email_conf_admin/removerEmailConf",
//Dados
data:{
"idemailconf":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idemailconf);
$("#iptRmvUsername").val(msg.username);
$("#iptRmvHost").val(msg.host);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Ativar email conf
function ativarEmailConf(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/email_conf_admin/ativarEmailConf",
//Dados
data:{
"idemailconf":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptAtvId").val(msg.idemailconf);
$("#iptAtvUsername").val(msg.username);
$("#iptAtvHost").val(msg.host);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//CRUD LOCAIS MAQUINAS
//Edição
function editarLocal(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/local_maquina_admin/editarLocal",
//Dados
data:{
"idlocal":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idlocal);
$("#iptEdtNome").val(msg.nome);
$("#iptEdtShape").val(msg.shape);
$("#iptEdtCoords").val(msg.coords);
if (msg.caixa === "0"){
$("#chkEdtCaixa").attr("checked", "0");
}
$("#selEdtEstado").val(msg.estado);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Remover
function removerLocal(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/local_maquina_admin/removerLocal",
//Dados
data:{
"idlocal":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idlocal);
$("#iptRmvNome").val(msg.nome);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//ativar local
function ativarLocal(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/local_maquina_admin/ativarLocal",
//Dados
data:{
"idlocal":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptAtvId").val(msg.idlocal);
$("#iptAtvNome").val(msg.nome);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//CRUD TIPOS MAQUINAS
//Edição
function editarTipo(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/tipo_maquina_admin/editarTipo",
//Dados
data:{
"idtipo":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idtipo);
$("#iptEdtNome").val(msg.nome);
$("#selEdtEstado").val(msg.estado);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Remover
function removerTipo(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/tipo_maquina_admin/removerTipo",
//Dados
data:{
"idtipo":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idtipo);
$("#iptRmvNome").val(msg.nome);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//ativar local
function ativarTipo(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/tipo_maquina_admin/ativarTipo",
//Dados
data:{
"idtipo":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptAtvId").val(msg.idtipo);
$("#iptAtvNome").val(msg.nome);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//CRUD MAQUINAS ADMIN
//Edição
function editarMaquina(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/maquina_admin/editarMaquina",
//Dados
data:{
"idmaquina":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idmaquina);
$("#iptEdtNome").val(msg.nome);
$("#iptEdtIp").val(msg.ip);
$("#iptEdtUser").val(msg.login);
$("#iptEdtDesc").val(msg.descricao);
$("#selEdtLocal").val(msg.local);
$("#selEdtTipo").val(msg.tipo);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Remover
function removerMaquina(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"admin/maquina_admin/removerMaquina",
//Dados
data:{
"idmaquina":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idmaquina);
$("#iptRmvNome").val(msg.nome);
$("#iptRmvIp").val(msg.ip);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//atualizar maquinas via arquivo via ajax
function carregarArquivoMaquina(ancor){
$(ancor).children().removeClass("hidden");
$(ancor).children().addClass("fa-spin");
$(ancor).addClass("disabled");
$.ajax({
type:"post",
url:baseUrl+"LoadFile/loadFileIPAjax",
dataType:"json",
success:function(msg){
if(!msg.erro){
alert(msg.msg);
$(ancor).children().removeClass("fa-spin");
$(ancor).children().addClass("hidden");
$(ancor).removeClass("disabled");
}
else {
alert(msg.erro);
$(ancor).children().removeClass("fa-spin");
$(ancor).children().addClass("hidden");
$(ancor).removeClass("disabled");
}
}
});
}
//CRUD MAQUINAS IP
//Edição
function editarMaquinaIp(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"maquina/editarMaquina",
//Dados
data:{
"idmaquina":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idmaquina);
$("#iptEdtNome").val(msg.nome);
$("#iptEdtIp").val(msg.ip);
$("#iptEdtUser").val(msg.login);
$("#iptEdtDesc").val(msg.descricao);
$("#selEdtLocal").val(msg.local);
$("#selEdtTipo").val(msg.tipo);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//Remover
function removerMaquinaIp(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"maquina/removerMaquina",
//Dados
data:{
"idmaquina":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idmaquina);
$("#iptRmvNome").val(msg.nome);
$("#iptRmvIp").val(msg.ip);
}
else{
$("#alert").val(msg.erro).show;
}
}
});
}
//FUNÇÔES DO HELP-DESK (CHAMADOS)
//Atender Chamado
function atenderChamado(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"ocorrencia/atenderChamado",
//Dados
data:{
"idocorrencia":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptAtdId").val(msg.idocorrencia);
$("#iptAtdNumero").val(msg.idocorrencia);
$("#iptAtdUsuario").val(msg.nome);
$("#iptAtdProblema").val(msg.problema);
}
else{
}
}
});
}
//Imprimir Chamado
function imprimirChamado(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"ocorrencia/imprimirChamado",
//Dados
data:{
"idocorrencia":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptImpId").val(msg.idocorrencia);
$("#iptImpNumero").val(msg.idocorrencia);
$("#iptImpUsuario").val(msg.nome);
$("#iptImpProblema").val(msg.problema);
}
else{
}
}
});
}
//Visualizar Chamado
function visualizarChamado(ancor){
$(".carregando-modal").show();
$(".corpo-modal").hide();
$(".comentario").hide();
$(".vizualiza-anexo").remove();
//remove html dos anexos.
$(".corpo-anexo").remove();
$("#imagem-anexo-visualiza").remove();
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"ocorrencia/visualizarChamado",
//Dados
data:{
"idocorrencia":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptVslId").val(msg.idocorrencia);
$("#selVslUnidade").val(msg.unidade);
$("#selVslSetor").val(msg.setor);
$("#selVslProblema").val(msg.problema);
$("#selVslArea").val(msg.area);
$("#iptVslUsuario").val(msg.nome);
$("#iptVslVnc").val(msg.vnc);
$("#iptVslRamal").val(msg.ramal);
$("#iptVslDesc").val(msg.descricao);
$("#iptVslComentario").text("");
if (msg.comentarios){
$("#visualiza-comentario-badge").html(msg.comentarios.length);
for(var i = 0, len = msg.comentarios.length; i < len; ++i){
$html = '<p class="texto-comentario">'+msg.comentarios[i]+'</p>';
$("#iptVslComentario").append($html);
}
$(".comentario").show();
} else {
$("#visualiza-comentario-badge").html("");
}
if (msg.arquivos){
$("#visualiza-anexo-badge").html(msg.arquivos.length);
$cabecalho = '<div class="col-md-12 corpo-anexo">'+
'<label for="" class="control-label">Anexos:</label></div>'+
'<div class="col-md-12" id="imagem-anexo-visualiza"></div>';
$("#visualiza-anexo").append($cabecalho);
for (var i = 0, len = msg.arquivos.length; i < len; ++i){
$html = '<div class="vizualiza-anexo"><a href="'+msg.arquivos[i]+'" class="lightview"><img class="img-vizualiza-anexo img-thumbnail img-responsive" src="'+msg.arquivos[i]+'"></a></div>';
$("#imagem-anexo-visualiza").append($html);
//$(".anexo-grupo").removeClass("hidden");
}
} else {
$("#visualiza-anexo-badge").html("");
//$(".anexo-grupo").addClass("hidden");
}
}
else{
}
}
});
$(".carregando-modal").delay(700).hide("slow");
$(".corpo-modal").delay(1000).show("slow");
}
//Remover Chamado
function removerChamado(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"ocorrencia/removerChamado",
//Dados
data:{
"idocorrencia":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idocorrencia);
$("#iptRmvNumero").val(msg.idocorrencia);
$("#iptRmvUsuario").val(msg.nome);
$("#iptRmvProblema").val(msg.problema);
}
else{
}
}
});
}
//Encaminhar Chamado
function encaminharChamado(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"ocorrencia/encaminharChamado",
//Dados
data:{
"idocorrencia":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEncId").val(msg.idocorrencia);
$("#iptEncNumero").val(msg.idocorrencia);
$("#iptEncUsuario").val(msg.nome);
$("#iptEncProblema").val(msg.problema);
$("#selEncTecnico").val(msg.tecnico);
}
else{
}
}
});
}
//Editar Chamado
function editarChamado(ancor){
$(".carregando-modal").show();
$(".corpo-modal").hide();
$(".comentario").hide();
$(".editar-anexo").remove();
//remove html dos anexos.
$(".corpo-anexo").remove();
$("#imagem-anexo-edita").remove();
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"ocorrencia/editarChamado",
//Dados
data:{
"idocorrencia":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idocorrencia);
$("#selEdtUnidade").val(msg.unidade);
$("#selEdtSetor").val(msg.setor);
$("#selEdtProblema").val(msg.problema);
$("#selEdtArea").val(msg.area);
$("#iptEdtUsuario").val(msg.nome);
$("#iptEdtVnc").val(msg.vnc);
$("#iptEdtRamal").val(msg.ramal);
$("#iptEdtDesc").val(msg.descricao);
$("#iptEdtComentario").text("");
if (msg.comentarios){
$("#edita-comentario-badge").html(msg.comentarios.length);
for(var i = 0, len = msg.comentarios.length; i < len; ++i){
$html = '<p class="texto-comentario">'+msg.comentarios[i]+'</p>';
$("#iptEdtComentario").append($html);
}
$(".comentario").show();
} else {
$("#edita-comentario-badge").html("");
}
if (msg.arquivos){
$("#edita-anexo-badge").html(msg.arquivos.length);
$cabecalho = '<div class="col-md-12 corpo-anexo">'+
'<label for="" class="control-label">Anexos:</label></div>'+
'<div class="col-md-12" id="imagem-anexo-edita"></div>';
$("#edita-anexo-antigo").append($cabecalho);
for (var i = 0, len = msg.arquivos.length; i < len; ++i){
$html = '<div class="vizualiza-anexo"><a href="'+msg.arquivos[i]+'" class="lightview"><img class="img-vizualiza-anexo img-thumbnail img-responsive" src="'+msg.arquivos[i]+'"></a></div>';
$("#imagem-anexo-edita").append($html);
//$(".anexo-grupo").removeClass("hidden");
}
} else {
$("#edita-anexo-badge").html("");
//$(".anexo-grupo").addClass("hidden");
}
}
else{
}
}
});
$(".carregando-modal").delay(700).hide("slow");
$(".corpo-modal").delay(1000).show("slow");
}
//Fechar Chamado
function fecharChamado(ancor){
$(".carregando-modal").show();
$(".corpo-modal").hide();
$(".comentario").hide();
//remove html dos anexos.
$(".corpo-anexo").remove();
$("#imagem-anexo-fecha").remove();
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"ocorrencia/fecharChamado",
//Dados
data:{
"idocorrencia":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptFchId").val(msg.idocorrencia);
$("#selFchUnidade").val(msg.unidade);
$("#selFchSetor").val(msg.setor);
$("#selFchProblema").val(msg.problema);
$("#selFchArea").val(msg.area);
$("#iptFchUsuario").val(msg.nome);
$("#iptFchVnc").val(msg.vnc);
$("#iptFchRamal").val(msg.ramal);
$("#iptFchDesc").val(msg.descricao);
$("#iptFchComentario").text("");
if (msg.comentarios){
$("#fecha-comentario-badge").html(msg.comentarios.length);
for(var i = 0, len = msg.comentarios.length; i < len; ++i){
$html = '<p class="texto-comentario">'+msg.comentarios[i]+'</p>';
$("#iptFchComentario").append($html);
}
$(".comentario").show();
} else {
$("#fecha-comentario-badge").html("");
}
if (msg.arquivos){
$("#fecha-anexo-badge").html(msg.arquivos.length);
$cabecalho = '<div class="col-md-12 corpo-anexo">'+
'<label for="" class="control-label">Anexos:</label></div>'+
'<div class="col-md-12" id="imagem-anexo-fecha"></div>';
$("#fecha-anexo-antigo").append($cabecalho);
for (var i = 0, len = msg.arquivos.length; i < len; ++i){
$html = '<div class="vizualiza-anexo"><a href="'+msg.arquivos[i]+'" class="lightview"><img class="img-vizualiza-anexo img-thumbnail img-responsive" src="'+msg.arquivos[i]+'"></a></div>';
$("#imagem-anexo-fecha").append($html);
//$(".anexo-grupo").removeClass("hidden");
}
} else {
$("#fecha-anexo-badge").html("");
//$(".anexo-grupo").addClass("hidden");
}
}
else{
}
}
});
$(".carregando-modal").delay(700).hide("slow");
$(".corpo-modal").delay(1000).show("slow");
}
//FUNÇÔES DA MANUTENÇÂO (IMPRESSORAS)
//Enviar para manutenção
function enviarManutencao(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"manutencao/enviarParaManutencao",
//Dados
data:{
"idmanutencao":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEnvId").val(msg.idmanutencao);
$("#iptEnvEquipamento").val(msg.equipamento);
$("#iptEnvDataEnvio").val(msg.data);
$("#iptEnvFornecedor").val(msg.fornecedor);
}
else{
}
}
});
}
//Enviar para manutenção
function editarManutencao(ancor){
//ocultar alerta e ativar botão
$(".alerta-editar-manutencao").hide();
$(".carregando").removeAttr("disabled", "true");
$(".formulario").fadeIn();
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"manutencao/editarManutencao",
//Dados
data:{
"idmanutencao":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEdtId").val(msg.idmanutencao);
$("#iptEdtEquipamento").val(msg.equipamento);
$("#iptEdtDefeito").val(msg.defeito);
$("#iptEdtFornecedor").val(msg.fornecedor);
$("#iptEdtDataDefeito").val(msg.data);
$("#iptEdtDescricao").val(msg.descricao);
$("#iptEdtPatrimonio").val(msg.patrimonio);
$("#selEdtUnidade").val(msg.unidade);
$("#selEdtSetor").val(msg.setor);
}
else{
$(".alerta-editar-manutencao").html("<strong>Não existe o equipamento pesquisado, Tentar novamente!</strong>");
$(".alerta-editar-manutencao").fadeIn("slow");
$(".carregando").attr("disabled", "true");
$(".formulario").hide();
}
}
});
}
//Visualizar manutenção
function visualizarManutencao(ancor){
//Esconde a div motivo (mostra somente na visualização sem conserto)
$(".div-vsl-motivo").hide();
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"manutencao/editarManutencao",
//Dados
data:{
"idmanutencao":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptVslId").val(msg.idmanutencao);
$("#iptVslEquipamento").val(msg.equipamento);
$("#iptVslDefeito").val(msg.defeito);
$("#iptVslDataDefeito").val(msg.data);
$("#iptVslDescricao").val(msg.descricao);
$("#iptVslFornecedor").val(msg.fornecedor);
$("#iptVslPatrimonio").val(msg.patrimonio);
$("#selVslUnidade").val(msg.unidade);
$("#selVslSetor").val(msg.setor);
//mostra motivo se for na manutenção sem conserto
if(msg.motivo){
$("#iptVslmotivo").val(msg.motivo);
$(".div-vsl-motivo").show();
}
}
else{
}
}
});
}
//Enviar para manutenção
function removerManutencao(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"manutencao/enviarParaManutencao",
//Dados
data:{
"idmanutencao":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRmvId").val(msg.idmanutencao);
$("#iptRmvEquipamento").val(msg.equipamento);
$("#iptRmvDataDefeito").val(msg.data);
}
else{
}
}
});
}
//Retornar da manutenção
function retornoManutencao(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"manutencao/retornarParaManutencao",
//Dados
data:{
"idmanutencao":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptRtnId").val(msg.idmanutencao);
$("#iptRtnEquipamento").val(msg.equipamento);
$("#iptRtnDataDefeito").val(msg.data);
$("#iptRtnDataEnvio").val(msg.dataenvio);
}
else{
}
}
});
}
//Não obteve conserto.
function semconsertoManutencao(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"manutencao/semConsManutencao",
//Dados
data:{
"idmanutencao":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptScmId").val(msg.idmanutencao);
$("#iptScmEquipamento").val(msg.equipamento);
$("#iptScmDataDefeito").val(msg.data);
}
else{
}
}
});
}
//Apresentou defeito na garantia
function defeitoManutencao(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"manutencao/apresentouDefeitoManutencao",
//Dados
data:{
"idmanutencao":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptDftId").val(msg.idmanutencao);
$("#iptDftEquipamento").val(msg.equipamento);
$("#iptDftDefeito").val(msg.defeito);
$("#iptDftDescricao").val("Defeito anterior: "+msg.defeito+"\n"+msg.descricao);
$("#iptDftPatrimonio").val(msg.patrimonio);
$("#selDftUnidade").val(msg.unidade);
$("#selDftSetor").val(msg.setor);
}
else{
}
}
});
}
//Fotos Perfil
function fotoPerfil(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(".foto-usuario").attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
else {
var img = input.value;
$(".foto-usuario").attr('src', baseUrl+'document/user/0.png');
}
}
//FUNÇÔES DE RELATÓRIO DE PLANTÃO
//Enviar e-mail
function EnviarEmailPlantao(ancor){
$.ajax({
//tipo de requisição
type:"post",
//URL a ser invocada
url:baseUrl+"plantao/enviarEmailPlantao",
//Dados
data:{
"idplantao":$(ancor).attr("data-id")
},
//tipo de formato de dados
dataType:"json",
//se tudo ocorrer bem
success:function(msg){
if(!msg.erro){
$("#iptEmlId").val(msg.idrelatorio);
$("#iptEmlNumero").val(msg.idrelatorio);
$("#iptEmlData").val(msg.data);
$("#iptEmlUsuario").val(msg.usuario);
$("#iptEmlPara").val(msg.para);
$("#iptEmlCopia").val(msg.copia);
$("#iptEmlAssunto").val(msg.assunto);
$("#iptEmlCorpo").val(msg.corpo);
}
else{
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
}
});
}
| 29.238943
| 210
| 0.469738
|
52acee7d6fa745af32083c34a7be1843882b603f
| 1,106
|
lua
|
Lua
|
app/extensions/common/sync-helpers.lua
|
ami-megarac/MORF-SyncAgent
|
6aa5b9731f517a34896c88965be544c2d1823d1d
|
[
"Apache-2.0"
] | null | null | null |
app/extensions/common/sync-helpers.lua
|
ami-megarac/MORF-SyncAgent
|
6aa5b9731f517a34896c88965be544c2d1823d1d
|
[
"Apache-2.0"
] | null | null | null |
app/extensions/common/sync-helpers.lua
|
ami-megarac/MORF-SyncAgent
|
6aa5b9731f517a34896c88965be544c2d1823d1d
|
[
"Apache-2.0"
] | 1
|
2019-09-29T02:29:36.000Z
|
2019-09-29T02:29:36.000Z
|
--[[
Copyright 2018 American Megatrends Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
package.path = package.path .. ";./libs/?;./libs/?.lua;../redfish/libs/?.lua;"
local redis = require('redis')
local CONFIG = require('config')
local params = {
scheme = 'unix',
path = CONFIG.redis_sock,
-- host = CONFIG.redis_host,
-- port = CONFIG.redis_port,
timeout = 0
}
local db = redis.connect(params)
local sync_helpers = {}
sync_helpers.session_expire = function(groupname)
db:set("Redfish:SessionService:Sessions:LastModified", os.time())
end
return sync_helpers
| 29.891892
| 78
| 0.714286
|
df29fe6aa678cad5b2cc2d372945144957d1d329
| 9,460
|
cs
|
C#
|
src/Nethereum.BlockchainStore.Search.Azure/AzureSearchService.cs
|
khosro/Nethereum.BlockchainStorage
|
24f28071572997e6fdf8446f3000c1b6df2015e6
|
[
"MIT"
] | 35
|
2016-11-11T17:53:59.000Z
|
2021-09-06T14:10:51.000Z
|
src/Nethereum.BlockchainStore.Search.Azure/AzureSearchService.cs
|
khosro/Nethereum.BlockchainStorage
|
24f28071572997e6fdf8446f3000c1b6df2015e6
|
[
"MIT"
] | 5
|
2017-07-05T23:24:35.000Z
|
2020-01-28T16:22:14.000Z
|
src/Nethereum.BlockchainStore.Search.Azure/AzureSearchService.cs
|
khosro/Nethereum.BlockchainStorage
|
24f28071572997e6fdf8446f3000c1b6df2015e6
|
[
"MIT"
] | 29
|
2017-01-14T07:44:19.000Z
|
2021-07-27T14:54:58.000Z
|
using Microsoft.Azure.Search;
using Nethereum.ABI.FunctionEncoding.Attributes;
using Nethereum.Contracts;
using Nethereum.RPC.Eth.DTOs;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Index = Microsoft.Azure.Search.Models.Index;
namespace Nethereum.BlockchainStore.Search.Azure
{
public class AzureSearchService : IAzureSearchService, IDisposable
{
private readonly SearchServiceClient _client;
private readonly ConcurrentDictionary<string, Index> _indexes;
private readonly Dictionary<string, ISearchIndexClient> _clients;
private readonly List<IDisposable> _indexers;
private readonly bool createdSearchServiceClient;
public AzureSearchService(SearchServiceClient searchServiceClient)
{
_client = searchServiceClient;
_indexes = new ConcurrentDictionary<string, Index>();
_clients = new Dictionary<string, ISearchIndexClient>();
_indexers = new List<IDisposable>();
}
public AzureSearchService(string serviceName, string searchApiKey):
this(new SearchServiceClient(serviceName, new SearchCredentials(searchApiKey)))
{
createdSearchServiceClient = true;
}
public async Task<long> CountDocumentsAsync(string indexName)
{
var client = GetOrCreateIndexClient(indexName);
return await client.Documents.CountAsync().ConfigureAwait(false);
}
public ISearchIndexClient GetOrCreateIndexClient(string indexName)
{
if (_clients.ContainsKey(indexName))
{
return _clients[indexName];
}
var client = _client.Indexes.GetClient(indexName);
_clients.Add(indexName, client);
return client;
}
public Task<bool> IndexExistsAsync(string indexName)
=> _client.Indexes.ExistsAsync(indexName);
public async Task<Index> CreateIndexAsync(Index index)
{
index = await _client.Indexes.CreateAsync(index).ConfigureAwait(false);
_indexes.TryAdd(index.Name, index);
return index;
}
public Task<Index> CreateIndexAsync(IndexDefinition indexDefinition, bool convertFieldNamesToLowerCase = false)
=> CreateIndexAsync(indexDefinition.ToAzureIndex(convertFieldNamesToLowerCase));
public Task<Index> CreateIndexForLogAsync(string indexName)
=> CreateIndexAsync(FilterLogIndexUtil.Create(indexName));
public Task<Index> CreateIndexForEventLogAsync<TEventDTO>(string indexName = null)
where TEventDTO : class
=> CreateIndexAsync(new EventIndexDefinition<TEventDTO>(indexName), convertFieldNamesToLowerCase: true);
public Task<Index> CreateIndexForFunctionMessageAsync<TFunctionMessage>(string indexName = null)
where TFunctionMessage : FunctionMessage
=> CreateIndexAsync(new FunctionIndexDefinition<TFunctionMessage>(indexName), convertFieldNamesToLowerCase: true);
public async Task<Index> GetIndexAsync(string indexName)
{
if (_indexes.TryGetValue(indexName, out var index))
{
return index;
}
index = await _client.Indexes.GetAsync(indexName).ConfigureAwait(false);
if (index != null)
{
_indexes.TryAdd(indexName, index);
}
return index;
}
public async Task DeleteIndexAsync(string indexName)
{
if (await _client.Indexes.ExistsAsync(indexName).ConfigureAwait(false))
{
await _client.Indexes.DeleteAsync(indexName).ConfigureAwait(false);
}
_indexes.TryRemove(indexName, out _);
}
public IIndexer<TSource> CreateIndexer<TSource, TSearchDocument>(
string indexName, Func<TSource, TSearchDocument> mapper, int documentsPerBatch = 1)
where TSource : class
where TSearchDocument : class, IHasId
{
var indexClient = GetOrCreateIndexClient(indexName);
var azureIndexer = new AzureIndexer<TSource, TSearchDocument>(indexClient, mapper, documentsPerBatch);
_indexers.Add(azureIndexer);
return azureIndexer;
}
public IIndexer<FilterLog> CreateIndexerForLog(string indexName, int documentsPerBatch = 1)
{
var indexClient = GetOrCreateIndexClient(indexName);
var azureIndexer = new AzureFilterLogIndexer(indexClient, documentsPerBatch);
_indexers.Add(azureIndexer);
return azureIndexer;
}
public IIndexer<FilterLog> CreateIndexerForLog<TSearchDocument>(
string indexName, Func<FilterLog, TSearchDocument> mapper, int documentsPerBatch = 1)
where TSearchDocument : class, IHasId
{
var indexClient = GetOrCreateIndexClient(indexName);
var azureIndexer = new AzureFilterLogIndexer<TSearchDocument>(indexClient, mapper, documentsPerBatch);
_indexers.Add(azureIndexer);
return azureIndexer;
}
public IIndexer<EventLog<TEventDTO>> CreateIndexerForEventLog<TEventDTO>(
string indexName, int documentsPerBatch = 1)
where TEventDTO : class, IEventDTO, new()
{
var indexClient = GetOrCreateIndexClient(indexName);
var indexDefinition = new EventIndexDefinition<TEventDTO>(indexName);
var azureIndexer = new AzureEventIndexer<TEventDTO>(indexClient, indexDefinition, documentsPerBatch);
_indexers.Add(azureIndexer);
return azureIndexer;
}
public IIndexer<EventLog<TEventDTO>> CreateIndexerForEventLog<TEventDTO, TSearchDocument>(
string indexName, Func<EventLog<TEventDTO>, TSearchDocument> mapper, int documentsPerBatch = 1)
where TEventDTO : class, IEventDTO, new()
where TSearchDocument : class, IHasId
{
var indexClient = GetOrCreateIndexClient(indexName);
var azureIndexer = new AzureEventIndexer<TEventDTO, TSearchDocument>(indexClient, mapper, documentsPerBatch);
_indexers.Add(azureIndexer);
return azureIndexer;
}
public IIndexer<TransactionReceiptVO> CreateIndexerForTransactionReceiptVO(
string indexName, TransactionReceiptVOIndexDefinition indexDefinition, int documentsPerBatch = 1)
{
var indexClient = GetOrCreateIndexClient(indexName);
var azureIndexer = new AzureTransactionReceiptVOIndexer(indexClient, indexDefinition, documentsPerBatch);
_indexers.Add(azureIndexer);
return azureIndexer;
}
public IIndexer<TransactionReceiptVO> CreateIndexerForTransactionReceiptVO<TSearchDocument>(
string indexName, Func<TransactionReceiptVO, TSearchDocument> mapper, int documentsPerBatch = 1)
where TSearchDocument : class, IHasId
{
var indexClient = GetOrCreateIndexClient(indexName);
var azureIndexer = new AzureTransactionReceiptVOIndexer<TSearchDocument>(indexClient, mapper, documentsPerBatch);
_indexers.Add(azureIndexer);
return azureIndexer;
}
public IIndexer<TransactionForFunctionVO<TFunctionMessage>> CreateIndexerForFunctionMessage<TFunctionMessage>(
string indexName, int documentsPerBatch = 1)
where TFunctionMessage : FunctionMessage, new()
{
var indexClient = GetOrCreateIndexClient(indexName);
var indexDefinition = new FunctionIndexDefinition<TFunctionMessage>(indexName);
var azureIndexer = new AzureFunctionIndexer<TFunctionMessage>(indexClient, indexDefinition, documentsPerBatch);
_indexers.Add(azureIndexer);
return azureIndexer;
}
public IIndexer<TransactionForFunctionVO<TFunctionMessage>> CreateIndexerForFunctionMessage<TFunctionMessage, TSearchDocument>(
string indexName, Func<TransactionForFunctionVO<TFunctionMessage>, TSearchDocument> mapper, int documentsPerBatch = 1)
where TFunctionMessage : FunctionMessage, new()
where TSearchDocument : class, IHasId
{
var indexClient = GetOrCreateIndexClient(indexName);
var azureIndexer = new AzureFunctionIndexer<TFunctionMessage, TSearchDocument>(indexClient, mapper, documentsPerBatch);
_indexers.Add(azureIndexer);
return azureIndexer;
}
bool _disposed = false;
public void Dispose()
{
if(_disposed) return;
foreach (var indexer in _indexers)
{
indexer.Dispose();
}
foreach (var client in _clients.Values)
{
client.Dispose();
}
if (createdSearchServiceClient)
{
_client?.Dispose();
}
_disposed = true;
}
public IAzureIndexSearcher CreateIndexSearcher(Index index)
{
var client = GetOrCreateIndexClient(index.Name);
return new AzureIndexSearcher(index, client);
}
}
}
| 41.491228
| 135
| 0.656554
|
a356c86016134d5d7deff296a53bf90147a5473e
| 762
|
java
|
Java
|
src/main/java/st/redline/stout/NoOpRouter.java
|
nuclearsandwich/redline-smalltalk
|
6944f5bf5081710a4faf4293f6e7bdddd9521205
|
[
"MIT"
] | 1
|
2015-11-05T17:47:15.000Z
|
2015-11-05T17:47:15.000Z
|
src/main/java/st/redline/stout/NoOpRouter.java
|
will/redline-smalltalk-heroku
|
b9f9e8c8940c70f5e02e6ad7ea23179964f07f60
|
[
"MIT"
] | null | null | null |
src/main/java/st/redline/stout/NoOpRouter.java
|
will/redline-smalltalk-heroku
|
b9f9e8c8940c70f5e02e6ad7ea23179964f07f60
|
[
"MIT"
] | null | null | null |
/* Redline Smalltalk, Copyright (c) James C. Ladd. All rights reserved. See LICENSE in the root of this distribution */
package st.redline.stout;
import st.redline.core.PrimObject;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
class NoOpRouter implements Router {
static final Router INSTANCE = new NoOpRouter();
private NoOpRouter() {}
public void dispatchToBlock(PrimObject servletResponse, PrimObject requestPath) throws IOException { System.out.println("NOOP"); }
public void dispatchToBlock(HttpServletResponse servletResponse, String requestPath) throws IOException { System.out.println("NOOP"); }
public boolean canHandleRequest(String requestPath, String acceptType) {
return true;
}
}
| 34.636364
| 139
| 0.765092
|
a46cd2a066f3557f0e2f5f81b0aff1c8871d9d0f
| 25,527
|
php
|
PHP
|
bitrix/modules/calendar/lib/controller/calendarajax.php
|
shuchitamathur28/bitrix24
|
fafc179382f028989a4ee4a5f97422e49b1526b4
|
[
"Unlicense"
] | 1
|
2020-10-05T04:28:40.000Z
|
2020-10-05T04:28:40.000Z
|
bitrix/modules/calendar/lib/controller/calendarajax.php
|
shuchitamathur28/bitrix24
|
fafc179382f028989a4ee4a5f97422e49b1526b4
|
[
"Unlicense"
] | null | null | null |
bitrix/modules/calendar/lib/controller/calendarajax.php
|
shuchitamathur28/bitrix24
|
fafc179382f028989a4ee4a5f97422e49b1526b4
|
[
"Unlicense"
] | null | null | null |
<?
namespace Bitrix\Calendar\Controller;
use Bitrix\Main\Text\Encoding;
use Bitrix\Main\Error;
use \Bitrix\Main\Engine\Response;
use Bitrix\Main\Loader;
use Bitrix\Main\Localization\Loc;
use \Bitrix\Calendar\UserSettings;
Loc::loadMessages(__FILE__);
/**
* Class CalendarAjax
*/
class CalendarAjax extends \Bitrix\Main\Engine\Controller
{
public function configureActions()
{
return [
'getTimezoneList' => [
'-prefilters' => [
\Bitrix\Main\Engine\ActionFilter\Authentication::class
]
]
];
}
public function getTimezoneListAction()
{
$timezones = \CCalendar::getTimezoneList();
$defaultTimezone = \CCalendar::getGoodTimezoneForOffset(\CCalendar::getCurrentOffsetUTC(\CCalendar::getCurUserId()));
if (isset($timezones[$defaultTimezone]))
{
$timezones[$defaultTimezone]['default'] = true;
}
return $timezones;
}
public function editCalendarSectionAction()
{
$request = $this->getRequest();
$response = [];
$id = $request->getPost('id');
$isNew = (!isset($id) || !$id);
$type = $request->getPost('type');
$ownerId = intval($request->getPost('ownerId'));
$name = trim($request->getPost('name'));
$color = $request->getPost('color');
$customization = $request->getPost('customization') === 'Y';
$userId = \CCalendar::GetUserId();
$isPersonal = $type == 'user' && $ownerId == $userId;
$fields = [
'ID' => $id,
'NAME' => $name,
'COLOR' => $color,
'CAL_TYPE' => $type,
'OWNER_ID' => $ownerId,
'ACCESS' => $request->getPost('access')
];
if ($customization && !$isNew)
{
UserSettings::setSectionCustomization($userId, [$id => ['name' => $name, 'color' => $color]]);
}
else
{
if($isNew) // For new sections
{
if($type === 'group')
{
// It's for groups
if(!\CCalendarType::CanDo('calendar_type_edit_section', 'group'))
{
$this->addError(new Error('[se01]'.Loc::getMessage('EC_ACCESS_DENIED'), 'access_denied'));
}
}
else if($type === 'user')
{
if (!$isPersonal)
{
$this->addError(new Error('[se02]'.Loc::getMessage('EC_ACCESS_DENIED'), 'access_denied'));
}
}
else // other types
{
if (!\CCalendarType::CanDo('calendar_type_edit_section', $type))
{
$this->addError(new Error('[se03]'.Loc::getMessage('EC_ACCESS_DENIED'), 'access_denied'));
}
}
$fields['IS_EXCHANGE'] = $request->getPost('is_exchange') == 'Y';
}
else
{
$section = \CCalendarSect::GetById($id);
if (!$section && !$isPersonal && !\CCalendarSect::CanDo('calendar_edit_section', $id, $userId))
{
$this->addError(new Error('[se04]'.Loc::getMessage('EC_ACCESS_DENIED'), 'access_denied'));
}
$fields['CAL_TYPE'] = $section['CAL_TYPE'];
$fields['OWNER_ID'] = $section['OWNER_ID'];
}
$id = intval(\CCalendar::SaveSection(['arFields' => $fields]));
if ($id > 0)
{
\CCalendarSect::SetClearOperationCache(true);
$response['section'] = \CCalendarSect::GetById($id, true, true);
if (!$response['section'])
{
$this->addError(new Error('[se05]'.Loc::getMessage('EC_CALENDAR_SAVE_ERROR'), 'saving_error'));
}
$response['accessNames'] = \CCalendar::GetAccessNames();
}
else
{
$this->addError(new Error('[se06]'.Loc::getMessage('EC_CALENDAR_SAVE_ERROR'), 'saving_error'));
}
}
return $response;
}
public function hideExternalCalendarSectionAction()
{
$request = $this->getRequest();
$response = [];
$id = $request->getPost('id');
if (!\CCalendar::IsPersonal() && !\CCalendarSect::CanDo('calendar_edit_section', $id, \CCalendar::GetUserId()))
{
$this->addError(new Error('[sd02]'.Loc::getMessage('EC_ACCESS_DENIED'), 'access_denied'));
}
$section = \CCalendarSect::GetById($id);
// For exchange we change only calendar name
if ($section && $section['CAL_DAV_CON'])
{
\CCalendarSect::Edit([
'arFields' => [
"ID" => $id,
"ACTIVE" => "N"
]]);
// Check if it's last section from connection - remove it
$sections = \CCalendarSect::GetList(
['arFilter' => [
'CAL_DAV_CON' => $section['CAL_DAV_CON'],
'ACTIVE' => 'Y'
]]);
if(!$sections || count($sections) == 0)
{
\CCalendar::RemoveConnection(['id' => intval($section['CAL_DAV_CON']), 'del_calendars' => 'Y']);
}
}
return $response;
}
public function getTrackingSectionsAction()
{
$request = $this->getRequest();
$codes = $request->get('codes');
$mode = $request->get('type');
$users = [];
if ($mode == 'users')
{
$userIds = [];
$users = \CCalendar::GetDestinationUsers($codes, true);
foreach($users as $user)
{
$userIds[] = $user['ID'];
}
$sections = \CCalendarSect::getSuperposedList(['USERS' => $userIds]);
}
elseif($mode == 'groups')
{
$groupIds = [];
foreach($codes as $code)
{
if (substr($code, 0, 2) === 'SG')
{
$groupIds[] = intval(substr($code, 2));
}
}
$sections = \CCalendarSect::getSuperposedList(['GROUPS' => $groupIds]);
if (Loader::includeModule('socialnetwork'))
{
foreach($groupIds as $groupId)
{
$groupId = intval($groupId);
$createDefaultGroupSection = \CSocNetFeatures::isActiveFeature(SONET_ENTITY_GROUP, $groupId, "calendar");
if ($createDefaultGroupSection)
{
foreach($sections as $section)
{
if (intval($section['OWNER_ID']) === $groupId)
{
$createDefaultGroupSection = false;
break;
}
}
}
if ($createDefaultGroupSection)
{
$sections[] = \CCalendarSect::createDefault([
'type' => 'group',
'ownerId' => $groupId
]);
}
}
}
}
else
{
$types = [];
$typesRes = \CCalendarType::GetList();
foreach($typesRes as $type)
{
if ($type['XML_ID'] != 'user' && $type['XML_ID'] !== 'group' && $type['XML_ID'] !== 'location')
{
$types[] = $type['XML_ID'];
}
}
$sections = \CCalendarSect::getSuperposedList(['TYPES' => $types]);
}
return [
'users' => $users,
'sections' => $sections
];
}
public function setTrackingSectionsAction()
{
$request = $this->getRequest();
$codes = $request->get('codes');
$type = $request->get('type');
$sections = $request->get('sections');
$userId = \CCalendar::getCurUserId();
if ($type === 'users')
{
UserSettings::setTrackingUsers($userId, \CCalendar::getDestinationUsers($codes));
}
elseif($type === 'groups')
{
$groupIds = [];
foreach($codes as $code)
{
if (substr($code, 0, 2) === 'SG')
{
$groupIds[] = intval(substr($code, 2));
}
}
UserSettings::setTrackingGroups($userId, $groupIds);
}
\CCalendar::setDisplayedSuperposed($userId, $sections);
return [];
}
public function getEditEventSliderAction()
{
$request = $this->getRequest();
$additionalResponseParams = [];
$uniqueId = 'calendar_edit_slider_'.rand();
$formType = preg_replace('/[^\d|\w\_]/', '', $request->get('form_type'));
$entryId = intval($request->get('event_id'));
$userId = \CCalendar::GetCurUserId();
if ($entryId > 0)
{
$entry = \CCalendarEvent::GetList([
'arFilter' => ["ID" => $entryId],
'parseRecursion' => false,
'fetchAttendees' => true,
'checkPermissions' => true,
'setDefaultLimit' => false
]);
$entry = $entry && is_array($entry[0]) ? $entry[0] : false;
}
else
{
$entry = [];
}
if (!$entryId || !empty($entry) && \CCalendarSceleton::CheckBitrix24Limits(array('id' => $uniqueId)))
{
if ($entry['ID'] && $entry['IS_MEETING'])
{
$selectedUserCodes = $entry['ATTENDEES_CODES'];
}
else
{
$selectedUserCodes = ['U'.\CCalendar::GetCurUserId()];
}
$additionalResponseParams['uniqueId'] = $uniqueId;
$additionalResponseParams['editorId'] = $uniqueId.'_entry_slider_editor';
$additionalResponseParams['entry'] = $entry;
$additionalResponseParams['timezoneList'] = \CCalendar::GetTimezoneList();
$additionalResponseParams['socnetDestination'] = \CCalendar::GetSocNetDestination(false, $selectedUserCodes);
$additionalResponseParams['formSettings'] = \Bitrix\Calendar\UserSettings::getFormSettings($formType);
$additionalResponseParams['sections'] = \CCalendar::getSectionListAvailableForUser($userId);
$additionalResponseParams['trackingUsersList'] = \Bitrix\Calendar\UserSettings::getTrackingUsers($userId);
$additionalResponseParams['iblockMeetingRoomList'] = \CCalendar::GetMeetingRoomList();
$additionalResponseParams['locationFeatureEnabled'] = !\CCalendar::IsBitrix24() ||
\Bitrix\Bitrix24\Feature::isFeatureEnabled("calendar_location");
if ($additionalResponseParams['locationFeatureEnabled'])
{
$additionalResponseParams['locationList'] = \CCalendarLocation::GetList();
}
return new \Bitrix\Main\Engine\Response\Component(
'bitrix:calendar.edit.slider',
'',
[
'id' => $uniqueId,
'event' => $entry,
'formType' => $formType,
'type' => \CCalendar::GetType(),
'bIntranet' => \CCalendar::IsIntranetEnabled(),
'bSocNet' => \CCalendar::IsSocNet(),
'AVATAR_SIZE' => 21
],
$additionalResponseParams
);
}
else
{
$this->addError(new Error('[se05]No entry found'));
}
return [];
}
public function getViewEventSliderAction()
{
$request = $this->getRequest();
$additionalResponseParams = [];
$uniqueId = 'calendar_view_slider_'.rand();
$entryId = intval($request->get('event_id'));
$userId = \CCalendar::GetCurUserId();
$fromTs = \CCalendar::Timestamp($request->get('date_from')) - $request->get('date_from_offset');
$entry = \CCalendarEvent::GetList(
array(
'arFilter' => array(
"ID" => $entryId,
"DELETED" => "N",
"FROM_LIMIT" => \CCalendar::Date($fromTs),
"TO_LIMIT" => \CCalendar::Date($fromTs)
),
'parseRecursion' => true,
'maxInstanceCount' => 1,
'preciseLimits' => true,
'fetchAttendees' => true,
'checkPermissions' => true,
'setDefaultLimit' => false
)
);
if (!$entry || !is_array($entry[0]))
{
$entry = \CCalendarEvent::GetList(
array(
'arFilter' => array(
"ID" => $entryId,
"DELETED" => "N"
),
'parseRecursion' => true,
'maxInstanceCount' => 1,
'fetchAttendees' => true,
'checkPermissions' => true,
'setDefaultLimit' => false
)
);
}
// Here we can get events with wrong RRULE ('parseRecursion' => false)
if (!$entry || !is_array($entry[0]))
{
$entry = \CCalendarEvent::GetList(
array(
'arFilter' => array(
"ID" => $entryId,
"DELETED" => "N"
),
'parseRecursion' => false,
'fetchAttendees' => true,
'checkPermissions' => true,
'setDefaultLimit' => false
)
);
}
if ($entry && is_array($entry[0]))
{
$entry = $entry[0];
if ($entry['IS_MEETING'] && $entry['PARENT_ID'] != $entry['ID'])
{
$parentEvent = \CCalendarEvent::GetById(intval($entry['PARENT_ID']));
if($parentEvent['DELETED'] == 'Y')
{
\CCalendarEvent::CleanEventsWithDeadParents();
$entry = false;
}
}
}
if ($entry)
{
$additionalResponseParams['uniqueId'] = $uniqueId;
$additionalResponseParams['entry'] = $entry;
$additionalResponseParams['userIndex'] = \CCalendarEvent::getUserIndex();
$sections = \CCalendarSect::GetList(
[
'arFilter' => [
'ID' => $entry['SECTION_ID'],
'ACTIVE' => 'Y',
],
'checkPermissions' => true,
'getPermissions' => false
]);
$additionalResponseParams['section'] = isset($sections[0]) ? $sections[0] : null;
return new \Bitrix\Main\Engine\Response\Component(
'bitrix:calendar.view.slider',
'',
[
'id' => $uniqueId,
'event' => $entry,
'type' => \CCalendar::GetType(),
'sectionName' => $_REQUEST['section_name'],
'bIntranet' => \CCalendar::IsIntranetEnabled(),
'bSocNet' => \CCalendar::IsSocNet(),
'AVATAR_SIZE' => 21
],
$additionalResponseParams
);
}
else
{
$this->addError(new Error('[se05]No entry found'));
}
return [];
}
public function getCrmUserfieldAction()
{
$request = $this->getRequest();
$UF = \CCalendarEvent::GetEventUserFields(['PARENT_ID' => intval($request->get('event_id'))]);
if (isset($UF['UF_CRM_CAL_EVENT']))
{
$crmUF = $UF['UF_CRM_CAL_EVENT'];
$additionalResponseParams = [];
return new \Bitrix\Main\Engine\Response\Component(
'bitrix:system.field.edit',
$crmUF["USER_TYPE"]["USER_TYPE_ID"],
[
"bVarsFromForm" => false,
"arUserField" => $crmUF,
"form_name" => 'event_edit_form'
],
$additionalResponseParams
);
}
return [];
}
public function updatePlannerAction()
{
$request = $this->getRequest();
$curEventId = intval($request['cur_event_id']);
$userId = \CCalendar::GetCurUserId();
$codes = false;
if (isset($request['codes']) && is_array($request['codes']))
{
$codes = [];
foreach($request['codes'] as $code)
{
if($code && !in_array($code, $codes))
{
$codes[] = $code;
}
}
if($request['add_cur_user_to_list'] === 'Y' || count($codes) <= 0)
{
$codes[] = 'U'.$userId;
}
}
return \CCalendarPlanner::PrepareData([
'entry_id' => $curEventId,
'user_id' => $userId,
'codes' => $codes,
'entries' => $request['entries'],
'date_from' => \CCalendar::Date(\CCalendar::Timestamp($request['date_from']), false),
'date_to' => \CCalendar::Date(\CCalendar::Timestamp($request['date_to']), false),
'timezone' => $request['timezone'],
'location' => trim($request['location']),
'roomEventId' => intval($request['roomEventId'])
]);
}
public function getPlannerAction()
{
$request = $this->getRequest();
//global $APPLICATION;
//$APPLICATION->ShowAjaxHead();
\CCalendarPlanner::Init(array('id' => $request['planner_id']));
return [];
}
public function saveLocationListAction()
{
$request = $this->getRequest();
$locationList = $request['locationList'];
foreach($locationList as $location)
{
if ($location['id'] && ($location['deleted'] == 'Y' || $location['name'] === ''))
{
\CCalendarLocation::delete($location['id']);
}
elseif ((!$location['id'] || $location['changed'] == 'Y') && $location['name'] !== '')
{
\CCalendarLocation::update(array(
'id' => $location['id'],
'name' => $location['name']
));
}
}
\CCalendarLocation::clearCache();
return ['locationList' => \CCalendarLocation::getList()];
}
public function deleteCalendarEntryAction($entryId, $recursionMode)
{
$response = [];
$response['result'] = \CCalendar::deleteEvent($entryId, true, array('recursionMode' => $recursionMode));
if ($response['result'] !== true)
{
$this->addError(new Error('[ed01]'.Loc::getMessage('EC_EVENT_DEL_ERROR'), 'delete_entry_error'));
}
return $response;
}
public function changeRecurciveEntryUntilAction($entryId, $untilDate)
{
$response = ['result' => false];
$event = \CCalendarEvent::GetById(intval($entryId));
$untilTimestamp = \CCalendar::Timestamp($untilDate);
$recId = false;
if ($event)
{
if (\CCalendarEvent::CheckRecurcion($event))
{
$event['RRULE'] = \CCalendarEvent::ParseRRULE($event['RRULE']);
$event['RRULE']['UNTIL'] = \CCalendar::Date($untilTimestamp, false);
if (isset($event['RRULE']['COUNT']))
{
unset($event['RRULE']['COUNT']);
}
$id = \CCalendar::SaveEvent(array(
'arFields' => array(
"ID" => $event["ID"],
"RRULE" => $event['RRULE']
),
'silentErrorMode' => false,
'recursionEditMode' => 'skip',
'editParentEvents' => true,
));
$recId = $event["ID"];
$response['id'] = $id;
}
if($event["RECURRENCE_ID"] > 0)
{
$recParentEvent = \CCalendarEvent::GetById($event["RECURRENCE_ID"]);
if ($recParentEvent && \CCalendarEvent::CheckRecurcion($recParentEvent))
{
$recParentEvent['RRULE'] = \CCalendarEvent::ParseRRULE($recParentEvent['RRULE']);
if ($recParentEvent['RRULE']['UNTIL']
&& \CCalendar::Timestamp($recParentEvent['RRULE']['UNTIL']) > $untilTimestamp)
{
$recParentEvent['RRULE']['UNTIL'] = \CCalendar::Date($untilTimestamp, false);
if (isset($recParentEvent['RRULE']['COUNT']))
{
unset($recParentEvent['RRULE']['COUNT']);
}
$id = \CCalendar::SaveEvent(array(
'arFields' => array(
"ID" => $recParentEvent["ID"],
"RRULE" => $recParentEvent['RRULE']
),
'silentErrorMode' => false,
'recursionEditMode' => 'skip',
'editParentEvents' => true,
));
$response['id'] = $id;
}
}
$recId = $event["RECURRENCE_ID"];
}
if ($recId)
{
$recRelatedEvents = \CCalendarEvent::GetEventsByRecId($recId, false);
foreach($recRelatedEvents as $ev)
{
if(\CCalendar::Timestamp($ev['DATE_FROM']) > $untilTimestamp)
{
\CCalendar::DeleteEvent(intval($ev['ID']), true, array('recursionMode' => 'this'));
}
}
}
$response['result'] = true;
}
if ($response['result'] !== true)
{
$this->addError(new Error('[ed01]'.Loc::getMessage('EC_EVENT_DEL_ERROR'), 'change_recurcive_entry_until'));
}
return $response;
}
public function excludeRecursionDateAction($entryId, $excludeDate)
{
$response = [];
\CCalendarEvent::ExcludeInstance(intval($entryId), $excludeDate);
return $response;
}
public function editEntryAction()
{
$response = [];
$request = $this->getRequest();
$id = intval($request['id']);
$sectionId = intval($request['section']);
$userId = \CCalendar::getCurUserId();
if (!$id && !\CCalendarSect::CanDo('calendar_add', $sectionId, $userId)
||
$id && !\CCalendarSect::CanDo('calendar_edit', $sectionId, $userId))
{
$this->addError(new Error('[ee01]'.Loc::getMessage('EC_ACCESS_DENIED'), 'edit_entry_access_denied'));
}
else
{
// Default name for events
$name = trim($request['name']);
if(empty($name))
{
$name = Loc::getMessage('EC_DEFAULT_EVENT_NAME');
}
$remind = [];
if(isset($request['reminder']) && is_array($request['reminder']))
{
foreach($request['reminder'] as $remindValue)
{
$remind[] = ['type' => 'min', 'count' => intval($remindValue)];
}
}
$rrule = $request['EVENT_RRULE'];
if($request['rrule_endson'] === 'never')
{
unset($rrule['COUNT']);
unset($rrule['UNTIL']);
}
elseif($request['rrule_endson'] === 'count')
{
if(intval($rrule['COUNT']) <= 0)
$rrule['COUNT'] = 10;
unset($rrule['UNTIL']);
}
elseif($request['rrule_endson'] === 'until')
{
unset($rrule['COUNT']);
}
// Date & Time
$dateFrom = $request['date_from'];
$dateTo = $request['date_to'];
$skipTime = isset($request['skip_time']) && $request['skip_time'] == 'Y';
if(!$skipTime)
{
$dateFrom .= ' '.$request['time_from_real'];
$dateTo .= ' '.$request['time_to_real'];
}
$dateFrom = trim($dateFrom);
$dateTo = trim($dateTo);
// Timezone
$tzFrom = $request['tz_from'];
$tzTo = $request['tz_to'];
if(!$tzFrom && isset($request['default_tz']))
{
$tzFrom = $request['default_tz'];
}
if(!$tzTo && isset($request['default_tz']))
{
$tzTo = $request['default_tz'];
}
if(isset($request['default_tz']) && $request['default_tz'] != '')
{
\CCalendar::SaveUserTimezoneName(CCalendar::GetUserId(), $request['default_tz']);
}
$entryFields = [
"ID" => $id,
"DATE_FROM" => $dateFrom,
"DATE_TO" => $dateTo,
'TZ_FROM' => $tzFrom,
'TZ_TO' => $tzTo,
'NAME' => $name,
'DESCRIPTION' => trim($request['desc']),
'SECTIONS' => [$sectionId],
'COLOR' => $request['color'],
'ACCESSIBILITY' => $request['accessibility'],
'IMPORTANCE' => isset($request['importance']) ? $request['importance'] : 'normal',
'PRIVATE_EVENT' => $request['private_event'] === 'Y',
'RRULE' => $rrule,
'LOCATION' => [
"OLD" => $request['location_old'],
"NEW" => $request['location_new']
],
"REMIND" => $remind,
"IS_MEETING" => !!$request['is_meeting'],
"SKIP_TIME" => $skipTime
];
$accessCodes = [];
if(isset($request['EVENT_DESTINATION']) && is_array($request['EVENT_DESTINATION']))
{
foreach($request["EVENT_DESTINATION"] as $v => $k)
{
if(strlen($v) > 0 && is_array($k) && !empty($k))
{
foreach($k as $vv)
{
if(strlen($vv) > 0)
{
$accessCodes[] = $vv;
}
}
}
}
if((!count($accessCodes) || !$id) && (\CCalendar::GetType() != 'user' || \CCalendar::IsPersonal()))
{
$accessCodes[] = 'U'.\CCalendar::GetUserId();
}
$accessCodes = array_unique($accessCodes);
}
$entryFields['IS_MEETING'] = !empty($accessCodes) && $accessCodes != ['U'.\CCalendar::GetUserId()];
if($entryFields['IS_MEETING'])
{
$entryFields['ATTENDEES_CODES'] = $accessCodes;
$entryFields['ATTENDEES'] = \CCalendar::GetDestinationUsers($accessCodes);
}
// if($request['exclude_users'] && count($arFields['ATTENDEES']) > 0)
// {
// $excludeUsers = explode(",", $request['exclude_users']);
// $arFields['ATTENDEES_CODES'] = array();
// if(count($excludeUsers) > 0)
// {
// $arFields['ATTENDEES'] = array_diff($arFields['ATTENDEES'], $excludeUsers);
// foreach($arFields['ATTENDEES'] as $userId)
// {
// $arFields['ATTENDEES_CODES'][] = 'U'.intval($userId);
// }
// }
// }
if(\CCalendar::GetType() == 'user' && \CCalendar::GetOwnerId() != \CCalendar::GetUserId())
{
$entryFields['MEETING_HOST'] = \CCalendar::GetOwnerId();
}
else
{
$entryFields['MEETING_HOST'] = \CCalendar::GetUserId();
}
$entryFields['MEETING'] = array(
'HOST_NAME' => \CCalendar::GetUserName($entryFields['MEETING_HOST']),
'NOTIFY' => $request['meeting_notify'] === 'Y',
'REINVITE' => $request['meeting_reinvite'] === 'Y',
'ALLOW_INVITE' => $request['allow_invite'] === 'Y',
'MEETING_CREATOR' => \CCalendar::GetUserId()
);
// Userfields for event
$arUFFields = array();
foreach($request as $field => $value)
{
if(substr($field, 0, 3) == "UF_")
{
$arUFFields[$field] = $value;
}
}
$newId = \CCalendar::SaveEvent([
'arFields' => $entryFields,
'UF' => $arUFFields,
'silentErrorMode' => false,
'recursionEditMode' => $request['rec_edit_mode'],
'currentEventDateFrom' => \CCalendar::Date(\CCalendar::Timestamp($request['current_date_from']), false)
]);
$errors = \CCalendar::GetErrors();
$arEvents = [];
$eventIds = array($newId);
return;
if($newId && !count($errors))
{
$arFilter = array(
"ID" => $newId,
"FROM_LIMIT" => \CCalendar::Date(\CCalendar::Timestamp($entryFields["DATE_FROM"]) - CCalendar::DAY_LENGTH *
10, false),
"TO_LIMIT" => \CCalendar::Date(\CCalendar::Timestamp($entryFields["DATE_TO"]) + CCalendar::DAY_LENGTH * 90,
false));
$arEvents = CCalendarEvent::GetList(array('arFilter' => $arFilter, 'parseRecursion' => true, 'fetchAttendees' => true, 'userId' => CCalendar::GetUserId()));
if($entryFields['IS_MEETING'])
{
\Bitrix\Main\FinderDestTable::merge(array("CONTEXT" => "CALENDAR", "CODE" => \Bitrix\Main\FinderDestTable::convertRights($accessCodes, array('U'.CCalendar::GetUserId()))));
}
if(in_array($_REQUEST['rec_edit_mode'], array('this', 'next')))
{
unset($arFilter['ID']);
$arFilter['RECURRENCE_ID'] = ($arEvents && $arEvents[0] && $arEvents[0]['RECURRENCE_ID']) ? $arEvents[0]['RECURRENCE_ID'] : $newId;
$resRelatedEvents = CCalendarEvent::GetList(array('arFilter' => $arFilter, 'parseRecursion' => true, 'fetchAttendees' => true, 'userId' => CCalendar::GetUserId()));
foreach($resRelatedEvents as $ev)
{
$eventIds[] = $ev['ID'];
}
$arEvents = array_merge($arEvents, $resRelatedEvents);
}
elseif($id && $arEvents && $arEvents[0] && CCalendarEvent::CheckRecurcion($arEvents[0]))
{
$recId = $arEvents[0]['RECURRENCE_ID'] ? $arEvents[0]['RECURRENCE_ID'] : $arEvents[0]['ID'];
if($arEvents[0]['RECURRENCE_ID'] && $arEvents[0]['RECURRENCE_ID'] !== $arEvents[0]['ID'])
{
unset($arFilter['RECURRENCE_ID']);
$arFilter['ID'] = $arEvents[0]['RECURRENCE_ID'];
$resRelatedEvents = CCalendarEvent::GetList(array('arFilter' => $arFilter, 'parseRecursion' => true, 'fetchAttendees' => true, 'userId' => CCalendar::GetUserId()));
$eventIds[] = $arEvents[0]['RECURRENCE_ID'];
$arEvents = array_merge($arEvents, $resRelatedEvents);
}
$name = trim($request['name']);
if($recId)
{
unset($arFilter['ID']);
$arFilter['RECURRENCE_ID'] = $recId;
$resRelatedEvents = CCalendarEvent::GetList(array('arFilter' => $arFilter, 'parseRecursion' => true, 'fetchAttendees' => true, 'userId' => CCalendar::GetUserId()));
foreach($resRelatedEvents as $ev)
{
$eventIds[] = $ev['ID'];
}
$arEvents = array_merge($arEvents, $resRelatedEvents);
}
}
}
}
return $response;
}
public function deleteCalendarSectionAction()
{
$request = $this->getRequest();
$response = [];
$id = $request->getPost('id');
if (!\CCalendar::IsPersonal() && !\CCalendarSect::CanDo('calendar_edit_section', $id, \CCalendar::GetUserId()))
{
$this->addError(new Error('[sd01]'.Loc::getMessage('EC_ACCESS_DENIED'), 'access_denied'));
}
else
{
\CCalendar::DeleteSection($id);
}
return $response;
}
}
| 27.360129
| 177
| 0.599405
|
93bb57b5b164b9cd785ce73fc8d9ccb5d212b99a
| 518
|
cs
|
C#
|
Model/Models/Waifus/ShopWaifu.cs
|
ta1H3n/Namiko
|
e12c1b26899cbd56a6c65e708cb25076d20de171
|
[
"MIT"
] | 7
|
2018-12-04T07:16:41.000Z
|
2021-03-11T00:32:17.000Z
|
Model/Models/Waifus/ShopWaifu.cs
|
ta1H3n/Namiko
|
e12c1b26899cbd56a6c65e708cb25076d20de171
|
[
"MIT"
] | 60
|
2020-10-12T07:10:53.000Z
|
2022-01-02T16:22:13.000Z
|
Model/Models/Waifus/ShopWaifu.cs
|
ta1H3n/Namiko
|
e12c1b26899cbd56a6c65e708cb25076d20de171
|
[
"MIT"
] | 4
|
2019-11-18T16:55:36.000Z
|
2021-06-01T10:10:37.000Z
|
using System;
using System.ComponentModel.DataAnnotations;
namespace Model
{
public class ShopWaifu
{
[Key]
public int Id { get; set; }
public int Discount { get; set; }
public int Limited { get; set; }
public ulong BoughtBy { get; set; }
[Required]
public WaifuShop WaifuShop { get; set; }
public int WaifuShopId { get; set; }
[Required]
public Waifu Waifu { get; set; }
public string WaifuName { get; set; }
}
}
| 22.521739
| 48
| 0.571429
|
e34f9f49f6710f51b1ad6ffc661fd95c04374c2b
| 298
|
rb
|
Ruby
|
lib/cocoapods-pdk8/hook/podfile.rb
|
TyrantDante/cocoapods-pdk8
|
716c5a5c340f4a68f3a43d0c7df121b2a209c39a
|
[
"MIT"
] | 5
|
2021-07-20T12:54:11.000Z
|
2022-01-15T07:17:16.000Z
|
lib/cocoapods-pdk8/hook/podfile.rb
|
TyrantDante/cocoapods-pdk8
|
716c5a5c340f4a68f3a43d0c7df121b2a209c39a
|
[
"MIT"
] | 1
|
2021-07-21T03:26:00.000Z
|
2021-07-22T02:53:03.000Z
|
lib/cocoapods-pdk8/hook/podfile.rb
|
TyrantDante/cocoapods-pdk8
|
716c5a5c340f4a68f3a43d0c7df121b2a209c39a
|
[
"MIT"
] | null | null | null |
module Pod
class Podfile
module DSL
include SourceConfig::Mixin
def force_source url
SourceConfig.instance.add_force_source url
source url
end
def speed_up_enable enable
SourceConfig.instance.speed_up_enable enable
end
end
end
end
| 18.625
| 52
| 0.671141
|
cdc5f1ed4ce0872640a6da76f008dd497fa67dc9
| 3,443
|
cs
|
C#
|
SapphireDb/Connection/Websocket/WebsocketMiddleware.cs
|
greenapp-debug/SapphireDb
|
817ca3843c14971293acaf2c08add0790a1efe4c
|
[
"MIT"
] | 1
|
2020-07-27T01:15:16.000Z
|
2020-07-27T01:15:16.000Z
|
SapphireDb/Connection/Websocket/WebsocketMiddleware.cs
|
greenapp-debug/SapphireDb
|
817ca3843c14971293acaf2c08add0790a1efe4c
|
[
"MIT"
] | null | null | null |
SapphireDb/Connection/Websocket/WebsocketMiddleware.cs
|
greenapp-debug/SapphireDb
|
817ca3843c14971293acaf2c08add0790a1efe4c
|
[
"MIT"
] | null | null | null |
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using SapphireDb.Models;
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using SapphireDb.Command;
using SapphireDb.Command.Connection;
using SapphireDb.Helper;
using SapphireDb.Internal;
namespace SapphireDb.Connection.Websocket
{
class WebsocketMiddleware
{
private readonly ConnectionManager connectionManager;
private readonly SapphireDatabaseOptions options;
// ReSharper disable once UnusedParameter.Local
public WebsocketMiddleware(RequestDelegate next, ConnectionManager connectionManager, SapphireDatabaseOptions options)
{
this.connectionManager = connectionManager;
this.options = options;
}
public async Task Invoke(HttpContext context, CommandExecutor commandExecutor, IServiceProvider serviceProvider, ILogger<WebsocketConnection> logger)
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
if (!AuthHelper.CheckApiAuth(context.Request.Query["key"], context.Request.Query["secret"], options))
{
await webSocket.Send(new WrongApiResponse());
await webSocket.CloseAsync(WebSocketCloseStatus.PolicyViolation, "Wrong API key or secret", CancellationToken.None);
return;
}
WebsocketConnection connection = new WebsocketConnection(webSocket, context);
connectionManager.AddConnection(connection);
await connection.Send(new ConnectionResponse() {
ConnectionId = connection.Id
});
while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.Connecting)
{
try
{
string message = await connection.Websocket.Receive();
if (!string.IsNullOrEmpty(message))
{
_ = Task.Run(async () =>
{
CommandBase command = JsonHelper.DeserializeCommand(message);
if (command != null)
{
ResponseBase response = await commandExecutor.ExecuteCommand(command,
serviceProvider.CreateScope().ServiceProvider, connection.Information, logger,
connection);
if (response != null)
{
await connection.Send(response);
}
}
});
}
}
catch (OperationCanceledException)
{
break;
}
catch(Exception ex)
{
logger.LogError(ex.Message);
}
}
connectionManager.RemoveConnection(connection);
}
}
}
}
| 38.685393
| 157
| 0.525123
|
2c8f73e1ee56e62d6e929536ff805bcc91edea64
| 846
|
py
|
Python
|
ninja_schema/orm/getters.py
|
eadwinCode/django-schema
|
94280270aa4f9c8ed08808c938283a4e217d17f0
|
[
"MIT"
] | 9
|
2021-10-31T22:03:00.000Z
|
2022-03-27T19:40:40.000Z
|
ninja_schema/orm/getters.py
|
eadwinCode/django-schema
|
94280270aa4f9c8ed08808c938283a4e217d17f0
|
[
"MIT"
] | null | null | null |
ninja_schema/orm/getters.py
|
eadwinCode/django-schema
|
94280270aa4f9c8ed08808c938283a4e217d17f0
|
[
"MIT"
] | null | null | null |
from typing import Any
import pydantic
from django.db.models import Manager, QuerySet
from django.db.models.fields.files import FieldFile
from pydantic.utils import GetterDict
pydantic_version = list(map(int, pydantic.VERSION.split(".")))[:2]
assert pydantic_version >= [1, 6], "Pydantic 1.6+ required"
__all__ = [
"DjangoGetter",
]
class DjangoGetter(GetterDict):
def get(self, key: Any, default: Any = None) -> Any:
result = super().get(key, default)
if isinstance(result, Manager):
return list(result.all())
elif isinstance(result, getattr(QuerySet, "__origin__", QuerySet)):
return list(result)
elif isinstance(result, FieldFile):
if not result:
return None
return result.url
return result
| 26.4375
| 76
| 0.62766
|
7f3a5e29a9fc1480718ff40cc46899eaff45868c
| 2,574
|
php
|
PHP
|
purprocess/paypre/src/Form/PaypreFilterForm.php
|
hostspace/modules
|
a77ad880b0930c6b4a7c460c79b454ad86a1f4dc
|
[
"MIT"
] | null | null | null |
purprocess/paypre/src/Form/PaypreFilterForm.php
|
hostspace/modules
|
a77ad880b0930c6b4a7c460c79b454ad86a1f4dc
|
[
"MIT"
] | null | null | null |
purprocess/paypre/src/Form/PaypreFilterForm.php
|
hostspace/modules
|
a77ad880b0930c6b4a7c460c79b454ad86a1f4dc
|
[
"MIT"
] | null | null | null |
<?php
namespace Drupal\paypre\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
*
*/
class PaypreFilterForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'paypre_filter_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['filters'] = [
'#type' => 'details',
'#title' => '查询条件',
'#open' => !empty($_SESSION['paypre_filter']),
];
// @todo 待进一步优化搜索框
$form['filters']['user'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'user',
'#selection_handler' => 'username',
'#maxlength' => 1024,
'#title' => '申请人',
];
$form['filters']['begin'] = [
'#type' => 'textfield',
'#title' => '起始日期',
'#default_value' => empty($_SESSION['paypre_filter']['begin']) ? '' : $_SESSION['paypre_filter']['begin'],
];
$form['filters']['end'] = [
'#type' => 'textfield',
'#title' => '截止日期',
'#default_value' => empty($_SESSION['paypre_filter']['end']) ? '' : $_SESSION['paypre_filter']['end'],
];
// Requirement status.
// -999是为了排序,放到选项中的第一行。无意义。.
$options_all = [-999 => '请选择状态'];
$options_status = getPaypreStatus();
$options_status = $options_all + $options_status;
$filter = isset($_SESSION['paypro_filter']) ? $_SESSION['paypro_filter'] : [];
$filter_status = isset($filter['status']) ? $filter['status'] : 0;
$form['filters']['status'] = [
'#type' => 'select',
'#title' => '工单状态',
'#options' => $options_status,
'#default_value' => $filter_status,
];
$form['filters']['submit'] = [
'#type' => 'submit',
'#value' => '查询',
];
$form['filters']['reset'] = [
'#type' => 'submit',
'#value' => '清空',
'#submit' => ['::resetForm'],
];
$form['#attached'] = [
'library' => ['requirement/drupal.requirement.default'],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$_SESSION['paypre_filter']['user'] = $form_state->getValue('user');
$_SESSION['paypre_filter']['begin'] = $form_state->getValue('begin');
$_SESSION['paypre_filter']['end'] = $form_state->getValue('end');
$_SESSION['paypre_filter']['status'] = $form_state->getValue('status');
}
/**
* {@inheritdoc}
*/
public function resetForm(array &$form, FormStateInterface $form_state) {
$_SESSION['paypre_filter'] = [];
}
}
| 27.382979
| 112
| 0.558275
|
20e9213b8a1c875afd9f832ff134126f27af2f19
| 469
|
py
|
Python
|
openverse_catalog/dags/providers/metropolitan_museum_workflow.py
|
yavik-kapadia/openverse-catalog
|
853766f2176a96450f456a9fd6675e134c0866e1
|
[
"MIT"
] | 25
|
2021-05-06T20:53:45.000Z
|
2022-03-30T23:18:50.000Z
|
openverse_catalog/dags/providers/metropolitan_museum_workflow.py
|
yavik-kapadia/openverse-catalog
|
853766f2176a96450f456a9fd6675e134c0866e1
|
[
"MIT"
] | 272
|
2021-05-17T05:53:00.000Z
|
2022-03-31T23:57:20.000Z
|
openverse_catalog/dags/providers/metropolitan_museum_workflow.py
|
yavik-kapadia/openverse-catalog
|
853766f2176a96450f456a9fd6675e134c0866e1
|
[
"MIT"
] | 13
|
2021-06-12T07:09:06.000Z
|
2022-03-29T17:39:13.000Z
|
# airflow DAG (necessary for Airflow to find this file)
from datetime import datetime
from common.dag_factory import create_provider_api_workflow
from providers.provider_api_scripts import metropolitan_museum_of_art
DAG_ID = "metropolitan_museum_workflow"
globals()[DAG_ID] = create_provider_api_workflow(
DAG_ID,
metropolitan_museum_of_art.main,
start_date=datetime(1970, 1, 1),
max_active_tasks=1,
schedule_string="@daily",
dated=True,
)
| 24.684211
| 69
| 0.788913
|
da5585e91521ad80155247d978634523970f9eb4
| 977
|
php
|
PHP
|
app/Http/Controllers/OrderController.php
|
tuanminh99/caycanhBE
|
f1310294efe8aaae868a7d56a5d792dd1ff54eb1
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/OrderController.php
|
tuanminh99/caycanhBE
|
f1310294efe8aaae868a7d56a5d792dd1ff54eb1
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/OrderController.php
|
tuanminh99/caycanhBE
|
f1310294efe8aaae868a7d56a5d792dd1ff54eb1
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class OrderController extends Controller
{
public function index() {
$all_orders = DB::table('orders')
->join('customers','orders.customer_id','=','customers.customer_id')
->select('orders.*','customers.customer_name')
->orderby('orders.order_id','desc')->get();
return view('admin.donhang.manage_order',compact('all_orders'));
}
public function view($id) {
$order_by_id = DB::table('orders')
->join('customers','orders.customer_id','=','customers.customer_id')
->join('shippings','orders.shipping_id','=','shippings.shipping_id')
->join('order_details','orders.order_id','=','order_details.order_id')
->select('orders.*','customers.*','shippings.*','order_details.*')->get();
return view('admin.donhang.view',compact('order_by_id'));
}
}
| 36.185185
| 86
| 0.625384
|
c6442dd459b8ef1ad0eeea7694a9faf9276b8b13
| 2,385
|
rb
|
Ruby
|
app/jobs/blockchain_retrieve_job.rb
|
saschneider/VMVLedger
|
d17d623fbd4ca489b0b06ff6f4ee5c581dc2c31b
|
[
"MIT"
] | null | null | null |
app/jobs/blockchain_retrieve_job.rb
|
saschneider/VMVLedger
|
d17d623fbd4ca489b0b06ff6f4ee5c581dc2c31b
|
[
"MIT"
] | 9
|
2020-02-26T14:26:12.000Z
|
2022-03-31T00:35:43.000Z
|
app/jobs/blockchain_retrieve_job.rb
|
saschneider/VMVLedger
|
d17d623fbd4ca489b0b06ff6f4ee5c581dc2c31b
|
[
"MIT"
] | null | null | null |
#
# Blockchain retrieve job class.
#
# @author Matthew Casey
#
# (c) University of Surrey 2019
#
class BlockchainRetrieveJob < ApplicationJob
# Use a separate queue for blockchain retrieve jobs.
BLOCKCHAIN_RETRIEVE_QUEUE = :blockchain_retrieve
queue_as BLOCKCHAIN_RETRIEVE_QUEUE
# Constants.
JOB_INTERVAL = 5.minutes
#
# Perform the job.
#
def perform_if_enabled(upload_id = nil)
upload = nil
# If this is for a specific upload, find it.
upload = Upload.find_by(id: upload_id) unless upload_id.blank?
# If this is for any upload, find the next upload that needs to be retrieved. This is for any upload that can be retrieved and for which the last retrieval
# has expired.
upload = Upload.to_retrieve(Service.get_service.retrieve_interval_duration).first if upload.nil?
# Exit if nothing to do.
return if upload.nil?
# Check that the upload is valid for retrieval.
raise JobError, I18n.t('blockchain_retrieve_job.not_public', upload: upload.id) unless upload.public? && upload.file_type.public?
raise JobError, I18n.t('blockchain_retrieve_job.not_uploaded', upload: upload.id) unless upload.success? && upload.address.present?
# Retrieve the file.
Delayed::Worker.logger.info("retrieving uploaded file from blockchain: upload #{upload.id} #{upload.file.filename}")
success = upload.update_content!
raise JobError, I18n.t('blockchain_retrieve_job.failed_download', upload: upload.id) unless success
rescue => e
# Re-raise the error.
if e.instance_of?(JobError)
raise e
else
raise JobError, I18n.t('blockchain_retrieve_job.failed_perform', upload: upload.nil? ? upload_id : upload.id, message: e.message)
end
ensure
# Re-queue the job with no arguments, assuming nothing else has re-queued it already.
begin
BlockchainRetrieveJob.set(wait: JOB_INTERVAL).perform_later unless BlockchainRetrieveJob.is_queued?
rescue NotImplementedError => _e
Delayed::Worker.logger.error "**** no job queue available for future job #{self.class}"
end
end
#
# Is the job queued?
#
# @returns True if the job is already queued.
#
def self.is_queued?
# Ignore failed or running jobs (potentially this job).
Delayed::Job.where(failed_at: nil, locked_at: nil).where('queue like ?', "%#{BLOCKCHAIN_RETRIEVE_QUEUE}").count.positive?
end
end
| 35.073529
| 159
| 0.725786
|
33c29ec9e2915c953c7f818009f5b28d47cb3f89
| 6,910
|
h
|
C
|
dev/Gems/OSVR/Code/Source/OSVRDevice.h
|
jeikabu/lumberyard
|
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
|
[
"AML"
] | 8
|
2019-10-07T16:33:47.000Z
|
2020-12-07T03:59:58.000Z
|
dev/Gems/OSVR/Code/Source/OSVRDevice.h
|
jeikabu/lumberyard
|
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
|
[
"AML"
] | null | null | null |
dev/Gems/OSVR/Code/Source/OSVRDevice.h
|
jeikabu/lumberyard
|
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
|
[
"AML"
] | 5
|
2017-12-05T16:36:00.000Z
|
2021-04-27T06:33:54.000Z
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <OSVR/OSVRBus.h>
#include <AzCore/Component/Component.h>
#include "HMDBus.h"
//OSVR Client Kit
#include <osvr/ClientKit/ClientKit.h>
#include <osvr/ClientKit/Display.h>
//OSVR Render Kit
#include <osvr/RenderKit/RenderManagerC.h>
#include <osvr/RenderKit/RenderManagerD3D11C.h>
namespace OSVR
{
struct OSVRFrameInfo
{
//One RenderInfo struct for each eye
OSVR_RenderInfoD3D11 renderInfo[STEREO_EYE_COUNT];
};
class OSVRDevice
: public AZ::Component
, public AZ::VR::HMDDeviceRequestBus::Handler
, public AZ::VR::HMDInitRequestBus::Handler
, private OSVR::OSVRRequestBus::Handler
{
public:
AZ_COMPONENT(OSVRDevice, "{0A6F6BF4-6E41-40F8-B20B-0B2932339448}");
static void Reflect(AZ::ReflectContext* context);
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided);
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible);
OSVRDevice() = default;
~OSVRDevice() override = default;
/// AZ::Component //////////////////////////////////////////////////////////
void Activate() override;
void Deactivate() override;
////////////////////////////////////////////////////////////////////////////
/// HMDInitBus overrides /////////////////////////////////////////////////////
bool AttemptInit() override;
void Shutdown() override;
AZ::VR::HMDInitBus::HMDInitPriority GetInitPriority() const override;
//////////////////////////////////////////////////////////////////////////////
/// HMDDeviceBus overrides ///////////////////////////////////////////////////
void GetPerEyeCameraInfo(const EStereoEye eye, const float nearPlane, const float farPlane, AZ::VR::PerEyeCameraInfo& cameraInfo) override;
bool CreateRenderTargets(void* renderDevice, const TextureDesc& desc, size_t eyeCount, AZ::VR::HMDRenderTarget* renderTargets[]) override;
void DestroyRenderTarget(AZ::VR::HMDRenderTarget& renderTarget) override;
void UpdateInternalState() override;
AZ::VR::TrackingState* GetTrackingState() override;
void SubmitFrame(const EyeTarget& left, const EyeTarget& right) override;
void RecenterPose() override;
void SetTrackingLevel(const AZ::VR::HMDTrackingLevel level) override;
void OutputHMDInfo() override;
AZ::VR::HMDDeviceInfo* GetDeviceInfo() override;
bool IsInitialized() override;
void UpdateTrackingStates() override;
////////////////////////////////////////////////////////////////////////////
private:
///
/// Retrieve a blob of JSON data about the OSVR interface at the given path.
/// This will malloc a new string at the pointer that you provide and you will have to free it yourself.
///
/// @param paramPath The virtual path that you want to get more detail on.
/// @param params A reference to the string that you want to contain the parameters.
/// @return If true, the parameters were properly allocated to the provided char**
///
bool GetOSVRParameters(const char* paramPath, char*& params);
///
/// Retrieve information about the current frame. This is the best
/// way to get frame info. Do not access m_renderInfoCollection directly as
/// this function properly double buffers render info access.
///
/// @return A reference to the appropriate frame info
///
OSVRFrameInfo& GetOSVRFrameInfo();
AZ::Quaternion OSVRQuatToLYQuat(const OSVR_Quaternion& osvrQuat);
AZ::Vector3 OSVRVec3ToLYVec3(const OSVR_Vec3& osvrVec3);
///OSVR Client Info
/* It may seem strange that we have both C++ styled objects from the osvr namespace
* and C style structures here. This is because the C++ API is more concise and handles
* a lot of the nuances of OSVR much better than we can directly with the C API. For
* example, checking if m_displayConfig == nullptr wasn't enough to avoid a crash
* in the AzTestRunner's integration tests but the m_cppDisp object handles validation
* checks like that for us with no issue.
*
* Why not just use the C++ API rather than the C API? The OSVR SDK makes extensive use of the
* C++ std which doesn't mesh well with AZStd (mainly when it comes to usage of std::string).
* It also uses a ton of std exceptions in place of more traditional value checking.
* Exceptions are disabled when we compile Lumberyard so we don't want to
* use the OSVR C++ api where we don't have to. We will retrieve the C API structs from the C++ objects
* in AttemptInit().
*/
osvr::clientkit::ClientContext* m_cppCtx = nullptr;
osvr::clientkit::DisplayConfig* m_cppDisp = nullptr;
OSVR_ClientContext m_clientContext = nullptr; ///< Main interface for querying anything about the client or establishing an OSVR_Interface
OSVR_DisplayConfig m_displayConfig = nullptr; ///< Non-renderer interface to the display. Info from the RenderManager is more useful
///OSVR Render Manager Info
OSVR_RenderManager m_renderManager = nullptr; ///< Main interface to the render manager
OSVR_RenderManagerD3D11 m_renderManagerD3D11 = nullptr; ///< D3D11 interface to the render manager
OSVR_RenderParams m_renderParams; ///< Only necessary as a way to tell the presentation engine about our near and far planes
OSVR_RenderInfoCount m_renderInfoCount; ///< Useful for knowing how many targets we have render info about
OSVR_RenderInfoCollection m_renderInfoCollection; ///< An internal collection of OSVR_RenderInfoD3D11 structs that the RenderManager helps with. Access with GetOSVRFrameInfo;
OSVRFrameInfo m_frameInfo[2]; ///< Collection for double buffered frame info
AZ::VR::TrackingState m_trackingState; ///< Most recent tracking state of the HMD (not including any connected controllers).
AZ::VR::HMDDeviceInfo m_deviceInfo;
};
}// namespace OSVR
| 50.808824
| 200
| 0.643705
|
05f5840c418734188bd6fcf6f00cb7cbc206282a
| 606
|
py
|
Python
|
neo_finrl/env_fx_trading/util/action_enum.py
|
cove9988/NeoFinRL
|
ccb451216cb2e94da60240b7210a83023ed1f9ed
|
[
"MIT"
] | null | null | null |
neo_finrl/env_fx_trading/util/action_enum.py
|
cove9988/NeoFinRL
|
ccb451216cb2e94da60240b7210a83023ed1f9ed
|
[
"MIT"
] | null | null | null |
neo_finrl/env_fx_trading/util/action_enum.py
|
cove9988/NeoFinRL
|
ccb451216cb2e94da60240b7210a83023ed1f9ed
|
[
"MIT"
] | null | null | null |
class ActionEnum(enumerate):
"""
Enum for action space
"""
BUY = 1
SELL = -1
HOLD = 0
EXIT = 3
def form_action(action):
"""
Form action from action space
"""
r = 0.0
if action <= -0.5:
r =-(action + 0.5) * 2
return ActionEnum.SELL, r, "SELL"
elif action >= +0.5:
r = (action - 0.5) * 2
return ActionEnum.BUY, r, "BUY"
else:
return ActionEnum.HOLD, r, "NIL"
def normalize(x,min, max):
"""
Scale [min, max] to [0, 1]
Normalize x to [min, max]
"""
return (x - min) / (max - min)
| 20.2
| 42
| 0.486799
|
8ba6417925b37221af24f6d0a55e3d775339e94d
| 1,045
|
rb
|
Ruby
|
spec/models/revision_spec.rb
|
FirstToDisclose/firsttodisclose.net
|
7fdbeb5065cc1091a25874c179ef5639cb2f19ad
|
[
"MIT"
] | 4
|
2015-03-18T03:58:52.000Z
|
2021-08-28T21:58:40.000Z
|
spec/models/revision_spec.rb
|
FirstToDisclose/firsttodisclose.net
|
7fdbeb5065cc1091a25874c179ef5639cb2f19ad
|
[
"MIT"
] | 104
|
2015-03-15T17:01:35.000Z
|
2016-10-29T07:06:17.000Z
|
spec/models/revision_spec.rb
|
FirstToDisclose/firsttodisclose.net
|
7fdbeb5065cc1091a25874c179ef5639cb2f19ad
|
[
"MIT"
] | 5
|
2015-03-27T14:09:07.000Z
|
2017-02-24T17:05:52.000Z
|
require 'rails_helper'
RSpec.describe Revision, type: :model do
describe "attributes" do
it { should respond_to :innovation_id }
it { should respond_to :user_id }
it { should respond_to :title }
it { should respond_to :abstract }
it { should respond_to :body }
it { should respond_to :consented }
end
describe "associations" do
it { should belong_to :innovation }
it { should belong_to :user }
end
describe "validations" do
it { should validate_presence_of :title }
it { should validate_length_of(:title).is_at_least(10) }
it { should validate_length_of(:title).is_at_most(200) }
it { should validate_presence_of :body }
it { should validate_length_of(:body).is_at_least(140) }
it { should validate_length_of(:body).is_at_most(10_000) }
it { should validate_presence_of :abstract }
it { should validate_length_of(:abstract).is_at_least(140) }
it { should validate_length_of(:abstract).is_at_most(1000) }
it { should validate_presence_of :consented }
end
end
| 33.709677
| 64
| 0.708134
|
c9e40f8e6fe81e0c87cd2738c11ff725d9207b1b
| 968
|
ts
|
TypeScript
|
src/components/HeaderStackNavigation/styles.ts
|
solrachix/newspaper-app
|
d35212b65072f42536e7354429dd86e30bd8bfa3
|
[
"MIT"
] | 5
|
2020-07-21T21:33:42.000Z
|
2021-02-06T13:30:33.000Z
|
src/components/HeaderStackNavigation/styles.ts
|
solrachix/newspaper-app
|
d35212b65072f42536e7354429dd86e30bd8bfa3
|
[
"MIT"
] | 1
|
2022-02-19T04:54:41.000Z
|
2022-02-19T04:54:41.000Z
|
src/components/HeaderStackNavigation/styles.ts
|
solrachix/south-america-star
|
d35212b65072f42536e7354429dd86e30bd8bfa3
|
[
"MIT"
] | 1
|
2020-07-25T12:17:58.000Z
|
2020-07-25T12:17:58.000Z
|
import styled, { css } from 'styled-components/native'
import Text from '../Text'
interface props {
transparent: boolean
}
export const Container = styled.View<props>`
position: ${props => props.transparent ? 'absolute' : 'relative'};
z-index: 10;
width: 100%;
min-height: 50px;
padding: 0;
padding-left: 8%;
padding-right: 8%;
margin-top: 4%;
top: 4%;
left: 0px;
right: 0px;
flex-direction: row;
/* flex-flow: row wrap; */
justify-content: space-between;
align-items: center;
align-content: center;
background-color: ${props => props.transparent ? 'transparent' : '#15121E'};
elevation: ${props => props.transparent ? 0 : 5};
`
interface ViewProp {
align?: string
}
export const View = styled.View<ViewProp>`${({ align }) => css`
flex-grow: 3;
flex-shrink: 3;
justify-content: ${align || 'center'};
align-items: ${align || 'center'};
z-index: 15;
`}`
export const Title = styled(Text)`
width: auto;
`
| 19.36
| 78
| 0.636364
|
cae992744b92f581dc8be0640accfc2d866eae9f
| 538
|
rb
|
Ruby
|
nv_print.rb
|
fenrir-naru/mbn_utils
|
65f86ca0c794a48204db23141e7e98396e680e06
|
[
"BSD-3-Clause"
] | null | null | null |
nv_print.rb
|
fenrir-naru/mbn_utils
|
65f86ca0c794a48204db23141e7e98396e680e06
|
[
"BSD-3-Clause"
] | null | null | null |
nv_print.rb
|
fenrir-naru/mbn_utils
|
65f86ca0c794a48204db23141e7e98396e680e06
|
[
"BSD-3-Clause"
] | null | null | null |
#!/usr/bin/ruby
nv_table = proc{
res = {}
open(File::join(File::dirname(__FILE__), 'nv_complete.txt')).each{|line|
next if line =~ /^\s*(?:$|#)/ # accept empty line
next unless line.chomp =~ /(\d+)\^(\"[^\"]+\")\^(\"[^\"]+\")/
res[$1.to_i] = [$2, $3]
}
res
}.call
open(ARGV.shift).each{|line|
next if line =~ /^\s*(?:$|#)/ # accept empty line
type, attri, location, *other = line.chomp.split(',')
next if type.to_i != 1
idx = location.to_i
puts ([idx] + (nv_table[idx] || ([nil] * 2)) + other).join(',')
}
| 26.9
| 74
| 0.52974
|
254c268a309b2039c6a72b089ff99dd390be2f9f
| 4,769
|
cs
|
C#
|
src/Areas/Admin/Controllers/StyleEditorController.cs
|
Bungalow64/NOP-Plugin-StyleEditor
|
bf243afc45f44bcac4e5dbc69692789ef7cbed84
|
[
"Apache-2.0"
] | null | null | null |
src/Areas/Admin/Controllers/StyleEditorController.cs
|
Bungalow64/NOP-Plugin-StyleEditor
|
bf243afc45f44bcac4e5dbc69692789ef7cbed84
|
[
"Apache-2.0"
] | 1
|
2022-02-06T14:49:34.000Z
|
2022-02-17T10:20:56.000Z
|
src/Areas/Admin/Controllers/StyleEditorController.cs
|
Bungalow64/NOP-Plugin-StyleEditor
|
bf243afc45f44bcac4e5dbc69692789ef7cbed84
|
[
"Apache-2.0"
] | 4
|
2021-07-18T13:09:20.000Z
|
2022-03-13T16:09:08.000Z
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Nop.Plugin.Admin.StyleEditor.Areas.Admin.Models;
using Nop.Plugin.Admin.StyleEditor.Helpers;
using Nop.Plugin.Admin.StyleEditor.Settings;
using Nop.Services.Configuration;
using Nop.Services.Localization;
using Nop.Services.Messages;
using Nop.Services.Security;
using Nop.Web.Areas.Admin.Controllers;
namespace Nop.Plugin.Admin.StyleEditor.Areas.Admin.Controllers
{
/// <summary>
/// Controller for handling actions to configure and view the StyleEditor widget
/// </summary>
public class StyleEditorController : BaseAdminController
{
#region Fields
private readonly IPermissionService _permissionService;
private readonly INotificationService _notificationService;
private readonly ILocalizationService _localizationService;
private readonly ISettingService _settingService;
private readonly StyleEditorSettings _settings;
private readonly ICurrentDateTimeHelper _currentDateTimeHelper;
#endregion
#region Ctor
/// <summary>
/// Creates an instance of the <see cref="StyleEditorController"/>
/// </summary>
/// <param name="permissionService"></param>
/// <param name="notificationService"></param>
/// <param name="localizationService"></param>
/// <param name="settingService"></param>
/// <param name="settings"></param>
/// <param name="currentDateTimeHelper"></param>
public StyleEditorController(
IPermissionService permissionService,
INotificationService notificationService,
ILocalizationService localizationService,
ISettingService settingService,
StyleEditorSettings settings,
ICurrentDateTimeHelper currentDateTimeHelper)
{
_permissionService = permissionService;
_notificationService = notificationService;
_localizationService = localizationService;
_settingService = settingService;
_settings = settings;
_currentDateTimeHelper = currentDateTimeHelper;
}
#endregion
#region Methods
/// <summary>
/// Redirects to the page showing the configuration options for the plugin
/// </summary>
/// <returns>Returns the configuration page</returns>
public virtual async Task<IActionResult> Configure()
{
return await EditStyles();
}
/// <summary>
/// Gets the page showing the configuration options for the plugin
/// </summary>
/// <returns>Returns the configuration page</returns>
public virtual async Task<IActionResult> EditStyles()
{
if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManagePlugins))
{
return AccessDeniedView();
}
var model = new ConfigurationModel
{
DisableCustomStyles = _settings.DisableCustomStyles,
CustomStyles = _settings.CustomStyles,
RenderType = _settings.RenderType,
UseAsync = _settings.UseAsync
};
return View("~/Plugins/Admin.StyleEditor/Areas/Admin/Views/StyleEditor.cshtml", model);
}
/// <summary>
/// Updates the configuration settings for the plugin
/// </summary>
/// <param name="model">The updated settings</param>
/// <returns>Returns the configuration page</returns>
[HttpPost]
[AutoValidateAntiforgeryToken]
public virtual async Task<IActionResult> EditStyles(ConfigurationModel model)
{
if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManagePlugins))
{
return AccessDeniedView();
}
if (!ModelState.IsValid)
{
_notificationService.ErrorNotification(await _localizationService.GetResourceAsync("Plugins.Admin.StyleEditor.Configuration.CouldNotBeSaved"));
return await Configure();
}
_settings.DisableCustomStyles = model.DisableCustomStyles;
_settings.CustomStyles = model.CustomStyles;
_settings.RenderType = model.RenderType;
_settings.UseAsync = model.UseAsync;
_settings.UpdateVersion(_currentDateTimeHelper);
await _settingService.SaveSettingAsync(_settings);
_notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Plugins.Admin.StyleEditor.StylesUpdated"));
return await EditStyles();
}
#endregion
}
}
| 37.257813
| 159
| 0.65129
|
b1980ffdbe447aae3b94788a4be3de6c198446dd
| 715
|
py
|
Python
|
utils/data_preprocessing.py
|
vlasenckov/raif
|
6158c094eed9b974320a00debed532beed82b0e6
|
[
"MIT"
] | null | null | null |
utils/data_preprocessing.py
|
vlasenckov/raif
|
6158c094eed9b974320a00debed532beed82b0e6
|
[
"MIT"
] | null | null | null |
utils/data_preprocessing.py
|
vlasenckov/raif
|
6158c094eed9b974320a00debed532beed82b0e6
|
[
"MIT"
] | null | null | null |
def fixing_skewness(df):
"""
This function takes in a dataframe and return fixed skewed dataframe
"""
## Import necessary modules
from scipy.stats import skew
from scipy.special import boxcox1p
from scipy.stats import boxcox_normmax
## Getting all the data that are not of "object" type.
numeric_feats = df.dtypes[df.dtypes != "object"].index
# Check the skew of all numerical features
skewed_feats = df[numeric_feats].apply(lambda x: skew(x)).sort_values(ascending=False)
high_skew = skewed_feats[abs(skewed_feats) > 0.5]
skewed_features = high_skew.index
for feat in skewed_features:
df[feat] = boxcox1p(df[feat], boxcox_normmax(df[feat] + 1))
| 35.75
| 90
| 0.702098
|
ff3af5113991d0ad24dd02549627acebd7bf0f71
| 476
|
py
|
Python
|
bot/generics.py
|
terisikk/multi-proto-bot
|
0fa269c015d631f161806eadf23a93cf5fff4ff6
|
[
"MIT"
] | null | null | null |
bot/generics.py
|
terisikk/multi-proto-bot
|
0fa269c015d631f161806eadf23a93cf5fff4ff6
|
[
"MIT"
] | null | null | null |
bot/generics.py
|
terisikk/multi-proto-bot
|
0fa269c015d631f161806eadf23a93cf5fff4ff6
|
[
"MIT"
] | null | null | null |
import time
class GenericEvent(object):
def __init__(self, client, original):
self.name = self.__class__.__name__.lower()
self.timestamp = time.time()
self.client = client
self.original_event = original
class PublicMessage(GenericEvent):
def __init__(self, client, original, text, user, channel=None):
super().__init__(self, client, original)
self.text = text
self.user = user
self.channel = channel
| 26.444444
| 67
| 0.651261
|
df0cec697df4ad39d9bf12a9b12e19ed1c66d6b3
| 161
|
cs
|
C#
|
src/qolab-server/Qolab.API/Models/Enums.cs
|
igelover/qolab
|
8695a5acb48ac7c76e2089266ad368e12adc06c3
|
[
"MIT"
] | 1
|
2021-12-05T17:36:13.000Z
|
2021-12-05T17:36:13.000Z
|
src/qolab-server/Qolab.API/Models/Enums.cs
|
igelover/qolab
|
8695a5acb48ac7c76e2089266ad368e12adc06c3
|
[
"MIT"
] | null | null | null |
src/qolab-server/Qolab.API/Models/Enums.cs
|
igelover/qolab
|
8695a5acb48ac7c76e2089266ad368e12adc06c3
|
[
"MIT"
] | 1
|
2022-01-06T08:58:37.000Z
|
2022-01-06T08:58:37.000Z
|
namespace Qolab.API.Models
{
public class Enums
{
public enum Vote
{
UpVote = 0,
DownVote = 1
}
}
}
| 13.416667
| 27
| 0.428571
|
4bcbd4a88db694975244a07d5919e804c002e803
| 7,772
|
c
|
C
|
musicplayer/plugins/viceplugin/vice/log.c
|
Osmose/moseamp
|
8357daf2c93bc903c8041cc82bf3567e8d085a60
|
[
"MIT"
] | 6
|
2017-04-19T19:06:03.000Z
|
2022-01-11T14:44:14.000Z
|
plugins/viceplugin/vice/log.c
|
sasq64/musicplayer
|
372852c2f4e3231a09db2628fc4b7e7c2bfeec67
|
[
"MIT"
] | 4
|
2018-04-04T20:27:32.000Z
|
2020-04-25T10:46:21.000Z
|
musicplayer/plugins/viceplugin/vice/log.c
|
Osmose/moseamp
|
8357daf2c93bc903c8041cc82bf3567e8d085a60
|
[
"MIT"
] | 2
|
2018-06-08T15:20:48.000Z
|
2020-08-19T14:24:21.000Z
|
/*
* log.c - Logging facility.
*
* Written by
* Ettore Perazzoli <ettore@comm2000.it>
*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*
*/
#include "vice.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "archdep.h"
#include "cmdline.h"
#include "lib.h"
#include "log.h"
#include "resources.h"
#include "translate.h"
#include "util.h"
static FILE *log_file = NULL;
static char **logs = NULL;
static log_t num_logs = 0;
static int log_enabled = 0; /* cv: this flag allows to temporarly disable all logging */
static int verbose = 0;
static int locked = 0;
/* ------------------------------------------------------------------------- */
static char *log_file_name = NULL;
static void log_file_open(void)
{
if (log_file_name == NULL || *log_file_name == 0) {
log_file = archdep_open_default_log_file();
return;
} else {
#ifndef __OS2__
if (strcmp(log_file_name, "-") == 0)
log_file = stdout;
else
#endif
log_file = fopen(log_file_name, MODE_WRITE_TEXT);
}
/* flush all data direct to the output stream. */
if (log_file)
setbuf(log_file, NULL);
}
static int set_log_file_name(const char *val, void *param)
{
if (locked) {
return 0;
}
if (util_string_set(&log_file_name, val) < 0) {
return 0;
}
if (log_file) {
fclose(log_file);
log_file_open();
}
return 0;
}
static int log_verbose_opt(const char *param, void *extra_param)
{
verbose = vice_ptr_to_int(extra_param);
return 0;
}
int log_set_verbose(int n)
{
if (n) {
return log_verbose_opt(NULL, (void*)1);
}
return log_verbose_opt(NULL, (void*)0);
}
int log_verbose_init(int argc, char **argv)
{
if (argc > 1) {
if (!strcmp("-verbose", argv[1])) {
log_set_verbose(1);
}
}
return 0;
}
#ifndef __X1541__
static const resource_string_t resources_string[] = {
{ "LogFileName", "", RES_EVENT_NO, NULL,
&log_file_name, set_log_file_name, NULL },
{ NULL }
};
static int log_logfile_opt(const char *param, void *extra_param)
{
locked = 0;
set_log_file_name(param, NULL);
locked = 1;
return 0;
}
int log_resources_init(void)
{
return resources_register_string(resources_string);
}
void log_resources_shutdown(void)
{
lib_free(log_file_name);
}
static const cmdline_option_t cmdline_options[] = {
{ "-logfile", CALL_FUNCTION, 1,
log_logfile_opt, NULL, NULL, NULL,
USE_PARAM_ID, USE_DESCRIPTION_ID,
IDCLS_P_NAME, IDCLS_SPECIFY_LOG_FILE_NAME,
NULL, NULL },
{ "-verbose", CALL_FUNCTION, 0,
log_verbose_opt, (void*)1, NULL, NULL,
USE_PARAM_STRING, USE_DESCRIPTION_ID,
IDCLS_UNUSED, IDCLS_ENABLE_VERBOSE_LOG_OUTPUT,
NULL, NULL },
{ NULL }
};
int log_cmdline_options_init(void)
{
return cmdline_register_options(cmdline_options);
}
#endif
/* ------------------------------------------------------------------------- */
int log_init_with_fd(FILE *f)
{
if (f == NULL)
return -1;
log_file = f;
return 0;
}
int log_init(void)
{
#if 0
/*
* The current calling order in main.c (log_init() after processing
* resources) makes this break if anything in the resource set_*
* functions does a log_open(). On platforms that have no regular
* stdout (e.g win32) no logging will be seen. On win32 startup will
* also be preceeded by a modal error requester. / tlr
*/
if (logs != NULL)
return -1;
#endif
log_file_open();
return log_file == NULL ? -1 : 0;
}
log_t log_open(const char *id)
{
log_t new_log = 0;
log_t i;
for (i = 0; i < num_logs; i++) {
if (logs[i] == NULL) {
new_log = i;
break;
}
}
if (i == num_logs) {
new_log = num_logs++;
logs = lib_realloc(logs, sizeof(*logs) * num_logs);
}
logs[new_log] = lib_stralloc(id);
return new_log;
}
int log_close(log_t log)
{
if (logs[(unsigned int)log] == NULL)
return -1;
lib_free(logs[(unsigned int)log]);
logs[(unsigned int)log] = NULL;
return 0;
}
void log_close_all(void)
{
log_t i;
for (i = 0; i < num_logs; i++)
log_close(i);
lib_free(logs);
}
static int log_archdep(const char *logtxt, const char *fmt, va_list ap)
{
/*
* ------ Split into single lines ------
*/
int rc = 0;
char *txt = lib_mvsprintf(fmt, ap);
char *beg = txt;
char *end = txt + strlen(txt) + 1;
while (beg < end) {
char *eol = strchr(beg, '\n');
if (eol)
*eol='\0';
if (archdep_default_logger(*beg ? logtxt : "", beg) < 0) {
rc = -1;
break;
}
if (!eol)
break;
beg = eol + 1;
}
lib_free(txt);
return rc;
}
static int log_helper(log_t log, unsigned int level, const char *format,
va_list ap)
{
static const char *level_strings[3] = {
"",
"Warning - ",
"Error - "
};
const signed int logi = (signed int)log;
int rc = 0;
char *logtxt = NULL;
if (!log_enabled) {
return 0;
}
if ((logi != LOG_DEFAULT) && (logi != LOG_ERR) && (logs == NULL || logs[logi] == NULL)) {
return -1;
}
if ((logi != LOG_DEFAULT) && (logi != LOG_ERR) && (*logs[logi] != '\0')) {
logtxt = lib_msprintf("%s: %s", logs[logi], level_strings[level]);
} else {
logtxt = lib_msprintf("%s", level_strings[level]);
}
if (log_file == NULL) {
rc = log_archdep(logtxt, format, ap);
} else {
#ifdef WIN32
log_archdep(logtxt, format, ap);
#endif /* #ifdef WIN32 */
if (fputs(logtxt, log_file) == EOF
|| vfprintf(log_file, format, ap) < 0
|| fputc ('\n', log_file) == EOF)
rc = -1;
}
lib_free(logtxt);
return rc;
}
int log_message(log_t log, const char *format, ...)
{
va_list ap;
int rc;
va_start(ap, format);
rc = log_helper(log, 0, format, ap);
va_end(ap);
return rc;
}
int log_warning(log_t log, const char *format, ...)
{
va_list ap;
int rc;
va_start(ap, format);
rc = log_helper(log, 1, format, ap);
va_end(ap);
return rc;
}
int log_error(log_t log, const char *format, ...)
{
va_list ap;
int rc;
va_start(ap, format);
rc = log_helper(log, 2, format, ap);
va_end(ap);
return rc;
}
int log_debug(const char *format, ...)
{
va_list ap;
int rc;
va_start(ap, format);
rc = log_helper(LOG_DEFAULT, 0, format, ap);
va_end(ap);
return rc;
}
int log_verbose(const char *format, ...)
{
va_list ap;
int rc = 0;
va_start(ap, format);
if (verbose) {
rc = log_helper(LOG_DEFAULT, 0, format, ap);
}
va_end(ap);
return rc;
}
void log_enable(int on)
{
log_enabled = on;
}
| 20.560847
| 93
| 0.582604
|
dd66bfa059050ab78de0818c80218a9f8e62591a
| 277
|
java
|
Java
|
QueryBuilder-JPA1-local/src/main/java/net/sf/esfinge/querybuilder/jpa1/EntityManagerProvider.java
|
nascimentolwtn/querybuilder
|
5f6453f73948b60bdf9d398a3228ca1835295bbf
|
[
"MIT"
] | null | null | null |
QueryBuilder-JPA1-local/src/main/java/net/sf/esfinge/querybuilder/jpa1/EntityManagerProvider.java
|
nascimentolwtn/querybuilder
|
5f6453f73948b60bdf9d398a3228ca1835295bbf
|
[
"MIT"
] | null | null | null |
QueryBuilder-JPA1-local/src/main/java/net/sf/esfinge/querybuilder/jpa1/EntityManagerProvider.java
|
nascimentolwtn/querybuilder
|
5f6453f73948b60bdf9d398a3228ca1835295bbf
|
[
"MIT"
] | null | null | null |
package net.sf.esfinge.querybuilder.jpa1;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
public interface EntityManagerProvider {
public EntityManager getEntityManager();
public EntityManagerFactory getEntityManagerFactory();
}
| 21.307692
| 55
| 0.837545
|
43f65b82803c77a2a18f10a45ab97ae960285bbc
| 2,338
|
ts
|
TypeScript
|
tests/unit/useLevel.spec.ts
|
N00ts/vue3-treeview
|
ac9593e8ce01f9b2c288414595f7aaffbf4e30de
|
[
"MIT"
] | 10
|
2021-06-07T21:49:10.000Z
|
2022-03-31T07:32:28.000Z
|
tests/unit/useLevel.spec.ts
|
N00ts/vue3-treeview
|
ac9593e8ce01f9b2c288414595f7aaffbf4e30de
|
[
"MIT"
] | 8
|
2021-09-29T13:41:09.000Z
|
2022-03-31T05:43:48.000Z
|
tests/unit/useLevel.spec.ts
|
N00ts/vue3-treeview
|
ac9593e8ce01f9b2c288414595f7aaffbf4e30de
|
[
"MIT"
] | 6
|
2021-11-12T18:49:38.000Z
|
2022-03-20T07:02:02.000Z
|
import { defaultConfig } from '../../src/misc/default';
import { reactive, ref } from 'vue';
import useLevel from '../../src/setup/useLevel';
import { createState, states } from '../../src/setup/store';
describe("test useLevel", () => {
let props = null;
let useTest = null;
const nodes = {
id1: {
text: "test",
children: ["id11"]
},
id11: {
text: "test"
}
};
const config = {
roots: ["id1"]
};
const storeProps = reactive({
nodes,
config
});
let state = null
let v = require("vue");
v.inject = jest.fn(() => state);
beforeEach(() => {
const id = createState(storeProps);
state = states.get(id);
props = {
depth: ref(0),
parentId: ref(null)
};
useTest = useLevel(props);
});
it("Expect to have id", () => {
expect(useTest.id.value).toBeDefined();
});
it("Expect to have a level", () => {
expect(useTest.level.value).toBeInstanceOf(Array);
expect(useTest.level.value[0]).toMatchObject(nodes["id1"]);
});
it("Expect to have no padding", () => {
expect(useTest.padding.value).toBe(0);
});
it("Expect to have default style", () => {
expect(useTest.style.value).toMatchObject({
"list-style": "none",
"padding-left": "0px"
});
});
it("Expect to create level with parent", () => {
props.parentId.value = "id1";
expect(useTest.level.value[0]).toMatchObject({
id: "id11",
parent: "id1",
text: "test"
});
});
it("Expect level to be empty", () => {
props.depth.value = 1;
expect(useTest.level.value).toMatchObject([]);
});
it("Expect to have default padding", () => {
props.depth.value = 1;
expect(useTest.padding.value).toBe(defaultConfig.padding);
});
it("Expect to have config padding", () => {
props.depth.value = 1;
state.config.value.padding = 15;
expect(useTest.padding.value).toBe(15);
});
it("Expect padding to be 0", () => {
props.depth.value = 1;
state.config.value.padding = -100;
expect(useTest.padding.value).toBe(0);
});
});
| 24.354167
| 67
| 0.509837
|
386e5253475d4e7b73f483c75754d8584d8dc3ca
| 4,075
|
php
|
PHP
|
extend/ky/Upload/Driver/Local.php
|
yihuds/KyPHP
|
9fa216064a02521b7a7c309cd61fadbad8b54c59
|
[
"Apache-2.0"
] | 20
|
2020-07-07T15:18:11.000Z
|
2021-05-05T13:23:23.000Z
|
extend/ky/Upload/Driver/Local.php
|
yihuds/KyPHP
|
9fa216064a02521b7a7c309cd61fadbad8b54c59
|
[
"Apache-2.0"
] | null | null | null |
extend/ky/Upload/Driver/Local.php
|
yihuds/KyPHP
|
9fa216064a02521b7a7c309cd61fadbad8b54c59
|
[
"Apache-2.0"
] | 7
|
2020-08-02T04:45:51.000Z
|
2021-05-05T13:23:26.000Z
|
<?php
/**
* SCRIPT_NAME: Local.php
* Created by PhpStorm.
* Time: 2016/4/25 22:25
* FUNCTION: 文件上传工具
* @Author: Doogie <461960962>
*/
namespace ky\Upload\Driver;
class Local{
/**
* 上传文件根目录
* @var string
*/
private $rootPath;
/**
* 本地上传错误信息
* @var string
*/
private $error = ''; //上传错误信息
/**
* 构造函数,用于设置上传根路径
* @param null $config
*/
public function __construct($config = null){
}
/**
* 检测上传根目录
* @param string $rootpath 根目录
* @return boolean true-检测通过,false-检测失败
* @Author: Doogie <461960962>
*/
public function checkRootPath($rootpath){
if(!(is_dir($rootpath) && is_writable($rootpath))){
$this->error = '上传根目录不存在或没有可写权限!请尝试手动创建:'.$rootpath;
return false;
}
$this->rootPath = $rootpath;
return true;
}
/**
* 检测上传目录
* @param string $savepath 上传目录
* @return boolean 检测结果,true-通过,false-失败
*/
public function checkSavePath($savepath){
/* 检测并创建目录 */
if (!$this->mkdir($savepath)) {
return false;
} else {
/* 检测目录是否可写 */
if (!is_writable($this->rootPath . $savepath)) {
$this->error = '上传目录 ' . $savepath . ' 不可写!';
return false;
} else {
return true;
}
}
}
/**
* 保存指定文件
* @param array $file 保存的文件信息
* @param boolean $replace 同名文件是否覆盖
* @return boolean 保存状态,true-成功,false-失败
* @Author: Doogie <461960962>
*/
public function save(&$file, $replace=true) {
$filename = $this->rootPath . $file['savepath'] . $file['savename'];
/* 不覆盖同名文件 */
if (!$replace && is_file($filename)) {
$this->error = '存在同名文件' . $file['savename'];
return false;
}
/* 移动文件 */
if (!move_uploaded_file($file['tmp_name'], $filename)) {
$this->error = '文件上传保存错误!';
return false;
}
$file['url'] = substr($filename, 1);
$file['path'] = $filename;
return true;
}
/**
* 创建目录
* @param string $savepath 要创建的穆里
* @return boolean 创建状态,true-成功,false-失败
* @Author: Doogie <461960962>
*/
public function mkdir($savepath){
$dir = $this->rootPath . $savepath;
if(is_dir($dir)){
return true;
}
if(mkdir($dir, 0777, true)){
return true;
} else {
$this->error = "目录 {$savepath} 创建失败!";
return false;
}
}
/**
* 获取最后一次上传错误信息
* @return string 错误信息
* @Author: Doogie <461960962>
*/
public function getError(){
return $this->error;
}
/**
* 遍历获取目录下的指定类型的文件
* @param $path
* @param $allowFiles
* @param string $prefix 前缀
* @param array $files
* @return array|null
* @Author: Doogie <461960962@qq.com>
*/
function listFile($path, $allowFiles, $prefix='0-',&$files = [])
{
if (!is_dir($path)) return null;
if(substr($path, strlen($path) - 1) != '/') $path .= '/';
$handle = opendir($path);
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
$path2 = $path . $file;
if (is_dir($path2)) {
$this->listFile($path2, $allowFiles, $prefix, $files);
} else {
if (preg_match("/^".$prefix.".*\.(".$allowFiles.")$/i", $file)) {
$files[] = array(
'url'=> substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
'mtime'=> filemtime($path2)
);
}
}
}
}
return $files;
}
}
| 26.121795
| 87
| 0.446626
|
b7abb6c084120928b4a69973d6c300eb896ff568
| 128
|
hpp
|
C++
|
command.hpp
|
RustedBot/Pong
|
8e75d64b306cc4c3db433061dd2e3418b7102354
|
[
"MIT"
] | null | null | null |
command.hpp
|
RustedBot/Pong
|
8e75d64b306cc4c3db433061dd2e3418b7102354
|
[
"MIT"
] | null | null | null |
command.hpp
|
RustedBot/Pong
|
8e75d64b306cc4c3db433061dd2e3418b7102354
|
[
"MIT"
] | null | null | null |
#ifndef COMMAND_H
#define COMMAND_H
class Command
{
public:
virtual void execute() = 0;
private:
};
#endif // COMMAND_H
| 9.142857
| 31
| 0.6875
|
c4bce915f809e6a7583322ea1475f8dd37c80c23
| 6,525
|
cpp
|
C++
|
src/Text/FontCache.cpp
|
tido64/rainbow
|
b54b84860979eca86e7d32ab61f92d9745fecfaa
|
[
"MIT"
] | 43
|
2019-03-13T16:35:09.000Z
|
2021-11-14T20:35:05.000Z
|
src/Text/FontCache.cpp
|
tido64/rainbow
|
b54b84860979eca86e7d32ab61f92d9745fecfaa
|
[
"MIT"
] | 574
|
2019-02-27T22:21:55.000Z
|
2021-09-06T18:46:59.000Z
|
src/Text/FontCache.cpp
|
tn0502/rainbow
|
b54b84860979eca86e7d32ab61f92d9745fecfaa
|
[
"MIT"
] | 7
|
2015-12-22T20:12:55.000Z
|
2018-02-24T10:05:55.000Z
|
// Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
#include "Text/FontCache.h"
#include "Common/Logging.h"
#include "Common/TypeCast.h"
#include "FileSystem/File.h"
#include "Graphics/Image.h"
#include "Text/SystemFonts.h"
using rainbow::Color;
using rainbow::FontCache;
using rainbow::SpriteVertex;
using rainbow::Vec2i;
using rainbow::graphics::TextureProvider;
namespace
{
/// <summary>Horizontal/vertical resolution in dpi.</summary>
constexpr uint32_t kDPI = 96;
constexpr int kGlyphMargin = 1;
/// <summary>26.6 fixed-point pixel coordinates.</summary>
constexpr int kPixelFormat = 64;
constexpr size_t kTextureSizeBytes =
FontCache::kTextureSize * FontCache::kTextureSize * 4;
void blit(const uint8_t* src,
const stbrp_rect& src_rect,
Color* dst,
const Vec2i& dst_sz)
{
for (uint32_t row = 0; row < src_rect.h; ++row) {
auto out = dst + ((src_rect.y + row) * dst_sz.x + src_rect.x);
const auto begin = src + src_rect.w * row;
std::transform(begin, begin + src_rect.w, out, [](uint8_t alpha) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
return Color{0xff, alpha};
});
}
}
} // namespace
FontCache::FontCache()
{
const auto texture_size = ceil_pow2(kTextureSize);
stbrp_init_target(&bin_context_,
texture_size,
texture_size,
bin_nodes_.data(),
narrow_cast<int>(bin_nodes_.size()));
// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays)
bitmap_ = std::make_unique<uint8_t[]>(kTextureSizeBytes);
std::fill_n(bitmap_.get(), kTextureSizeBytes, 0);
FT_Init_FreeType(&library_);
R_ASSERT(library_, "Failed to initialise FreeType");
make_global();
}
FontCache::~FontCache()
{
if (library_ == nullptr)
return;
for (auto&& i : font_cache_)
FT_Done_Face(i.second.face);
FT_Done_FreeType(library_);
}
auto FontCache::get(std::string_view font_name) -> FT_Face
{
auto search = font_cache_.find(font_name);
if (search == font_cache_.end()) {
auto data = font_name.empty()
? text::monospace_font()
: File::read(font_name.data(), FileType::Asset);
FT_Face face;
[[maybe_unused]] FT_Error error =
FT_New_Memory_Face(library_,
data.as<FT_Byte*>(),
narrow_cast<FT_Long>(data.size()),
0,
&face);
R_ASSERT(error == FT_Err_Ok, "Failed to load font face");
R_ASSERT(FT_IS_SCALABLE(face), "Unscalable fonts are not supported");
error = FT_Select_Charmap(face, FT_ENCODING_UNICODE);
R_ASSERT(error == FT_Err_Ok, "Failed to select character map");
font_cache_.emplace(font_name, FontFace{face, std::move(data)});
return face;
}
return search->second.face;
}
auto FontCache::get_glyph(FT_Face face, int32_t font_size, uint32_t glyph_index)
-> std::array<SpriteVertex, 4>
{
const Index cache_index{face, font_size, glyph_index};
auto search = glyph_cache_.find(cache_index);
if (search == glyph_cache_.end()) {
FT_Set_Char_Size(face, 0, font_size * kPixelFormat, 0, kDPI);
FT_Load_Glyph(face, glyph_index, FT_LOAD_RENDER);
FT_GlyphSlot slot = face->glyph;
const FT_Bitmap& bitmap = slot->bitmap;
R_ASSERT(bitmap.num_grays == 256, "");
R_ASSERT(bitmap.pixel_mode == FT_PIXEL_MODE_GRAY, "");
stbrp_rect rect{
0,
static_cast<stbrp_coord>(bitmap.width + kGlyphMargin * 2),
static_cast<stbrp_coord>(bitmap.rows + kGlyphMargin * 2),
0,
0,
0};
stbrp_pack_rects(&bin_context_, &rect, 1);
R_ASSERT(rect.was_packed != 0,
"Failed to pack a glyph, please increase your texture size");
// Adjust coordinates to compensate for margins.
rect.w -= kGlyphMargin * 2;
rect.h -= kGlyphMargin * 2;
rect.x += kGlyphMargin;
rect.y += kGlyphMargin;
blit(bitmap.buffer,
rect,
reinterpret_cast<Color*>(bitmap_.get()),
{kTextureSize, kTextureSize});
state_ = State::NeedsUpdate;
std::array<SpriteVertex, 4> vx;
vx[0].position.x = slot->bitmap_left;
vx[0].position.y = narrow_cast<float>(slot->bitmap_top -
narrow_cast<FT_Int>(bitmap.rows));
vx[1].position.x = narrow_cast<float>(slot->bitmap_left + bitmap.width);
vx[1].position.y = vx[0].position.y;
vx[2].position.x = vx[1].position.x;
vx[2].position.y = narrow_cast<float>(slot->bitmap_top);
vx[3].position.x = vx[0].position.x;
vx[3].position.y = vx[2].position.y;
vx[0].texcoord.x = rect.x / narrow_cast<float>(kTextureSize);
vx[0].texcoord.y = (rect.y + rect.h) / narrow_cast<float>(kTextureSize);
vx[1].texcoord.x = (rect.x + rect.w) / narrow_cast<float>(kTextureSize);
vx[1].texcoord.y = vx[0].texcoord.y;
vx[2].texcoord.x = vx[1].texcoord.x;
vx[2].texcoord.y = rect.y / narrow_cast<float>(kTextureSize);
vx[3].texcoord.x = vx[0].texcoord.x;
vx[3].texcoord.y = vx[2].texcoord.y;
glyph_cache_[cache_index] = {vx};
return vx;
}
return search->second.vertices;
}
void FontCache::update(TextureProvider& texture_provider)
{
if (state_ != State::Ready) {
const auto image = Image{
Image::Format::RGBA,
narrow_cast<uint32_t>(kTextureSize),
narrow_cast<uint32_t>(kTextureSize),
32U,
4U,
kTextureSizeBytes,
bitmap_.get(),
};
if (!texture_)
texture_ = texture_provider.get("rainbow://font-cache", image);
else
texture_provider.update(texture_, image);
state_ = State::Ready;
}
}
#define STB_RECT_PACK_IMPLEMENTATION
// clang-format off
#include "ThirdParty/DisableWarnings.h"
#include <imgui/imstb_rectpack.h> // NOLINT(llvm-include-order)
#include "ThirdParty/ReenableWarnings.h"
// clang-format on
| 32.788945
| 80
| 0.6
|
6d813efc6c1ce36a65a17f40f800125f3e0d1185
| 701
|
ts
|
TypeScript
|
types/rdfjs__namespace/rdfjs__namespace-tests.ts
|
fes300/DefinitelyTyped
|
0ff89f656c5e796284e155524b64c53bb0ee4998
|
[
"MIT"
] | 84
|
2020-09-09T18:29:25.000Z
|
2021-06-28T17:06:00.000Z
|
types/rdfjs__namespace/rdfjs__namespace-tests.ts
|
fes300/DefinitelyTyped
|
0ff89f656c5e796284e155524b64c53bb0ee4998
|
[
"MIT"
] | 121
|
2021-04-15T00:06:33.000Z
|
2022-01-12T19:55:06.000Z
|
types/rdfjs__namespace/rdfjs__namespace-tests.ts
|
fes300/DefinitelyTyped
|
0ff89f656c5e796284e155524b64c53bb0ee4998
|
[
"MIT"
] | 3
|
2020-06-05T08:25:28.000Z
|
2021-01-11T02:47:23.000Z
|
import namespace = require('@rdfjs/namespace');
import { NamespaceBuilder } from '@rdfjs/namespace';
import { DataFactory, NamedNode } from 'rdf-js';
const factory: DataFactory = {} as any;
const builder1: NamespaceBuilder = namespace('http://schema.org/');
const builder2: NamespaceBuilder = namespace('http://schema.org/', {});
const builder3: NamespaceBuilder = namespace('http://schema.org/', { factory });
const node1: NamedNode = builder1.Thing;
const node2: NamedNode = builder1.url;
const node3: NamedNode = builder1('Thing');
const node4: NamedNode = builder1('url');
const node5: NamedNode = builder1`'Thing'`;
const node6: NamedNode = builder1`url`;
const node7: NamedNode = builder1();
| 38.944444
| 80
| 0.730385
|
38cb0e86a388bdd22b1c55562254c387a255e90a
| 54
|
php
|
PHP
|
modules/Reports/views/PaxHeader/MoveReports.php
|
Bvdldf/ABP
|
245d36043db59568fc373951dc477ba4c8454c77
|
[
"PHP-3.0",
"Apache-2.0",
"ECL-2.0"
] | null | null | null |
modules/Reports/views/PaxHeader/MoveReports.php
|
Bvdldf/ABP
|
245d36043db59568fc373951dc477ba4c8454c77
|
[
"PHP-3.0",
"Apache-2.0",
"ECL-2.0"
] | null | null | null |
modules/Reports/views/PaxHeader/MoveReports.php
|
Bvdldf/ABP
|
245d36043db59568fc373951dc477ba4c8454c77
|
[
"PHP-3.0",
"Apache-2.0",
"ECL-2.0"
] | null | null | null |
30 mtime=1556800909.698388446
24 SCHILY.fflags=extent
| 18
| 29
| 0.851852
|
574635e7a3e51cfc03bf7d9d3412005dfeb810a4
| 15,217
|
dart
|
Dart
|
lib/src/calendarheader.dart
|
robert-stevens/flutter_calendar
|
896a3b0f2adae35da45d7061e6dff601950e04a5
|
[
"BSD-2-Clause"
] | null | null | null |
lib/src/calendarheader.dart
|
robert-stevens/flutter_calendar
|
896a3b0f2adae35da45d7061e6dff601950e04a5
|
[
"BSD-2-Clause"
] | null | null | null |
lib/src/calendarheader.dart
|
robert-stevens/flutter_calendar
|
896a3b0f2adae35da45d7061e6dff601950e04a5
|
[
"BSD-2-Clause"
] | null | null | null |
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:timezone/timezone.dart';
import 'dart:async';
import 'calendarevent.dart';
import 'calendar.dart';
const Duration _kExpand = const Duration(milliseconds: 200);
///
/// This function will be called to generate a day in the header. By
/// default it does this. Which is overlaid by the event indicators.
/// button = new Center(
/// child: new FlatButton(
/// color: day.isAtSameMomentAs(nowTime)
/// ? theme.accentColor
/// : day.isAtSameMomentAs(displayDate)
/// ? Colors.grey.shade200
/// : Colors.white,
/// shape: new CircleBorder(),
/// child: new Text(day.day.toString()),
/// onPressed: () => sharedState.source.scrollToDay(day),
/// padding: EdgeInsets.zero,
/// ),
/// );
///
typedef HeaderDayIndicator = Widget Function(
ThemeData theme, DateTime day, DateTime nowTime);
///
/// Generates the small boxes on the calendar to indicate that there are events
/// on this specific day. It creates a stack and then puts in the main day
/// button inside the stack with the event indicators overlaid on top of it.
/// The calendar events are the events on this day. It can be an empty array.
///
typedef EventIndicator = Widget Function(
Widget button, List<CalendarEvent> events);
///
/// Displays the header for the calendar. This handles the title with the
/// month/year and a drop down item as well as opening to show the whole month.
///
class CalendarHeader extends StatefulWidget {
final Location _location;
final CalendarWidgetState state;
final ImageProvider bannerHeader;
final Color color;
final TextStyle headerStyle;
final EventIndicator eventIndicator;
final HeaderDayIndicator dayIndicator;
///
/// Creates the calendar header. [calendarKey] is the key to find the shared
/// state from. [location] to use for the calendar.
///
/// See [EventIndicator] and [HeaderDayIndicator] for details on how the
/// day and event indicators can be customized.
///
CalendarHeader(
this.state,
this.bannerHeader,
Location location,
this.color,
this.headerStyle,
this.dayIndicator,
this.eventIndicator,
) : _location = location ?? local;
@override
State createState() {
return new CalendarHeaderState();
}
}
///
/// The calendar state associated with the header.
///
class CalendarHeaderState extends State<CalendarHeader>
with SingleTickerProviderStateMixin {
double get maxExtent => 55.0;
StreamSubscription<int> _subscription;
StreamSubscription<bool> _headerExpandedSubscription;
StreamSubscription<int> _indexChangeSubscription;
//SharedCalendarState sharedState;
AnimationController _controller;
CurvedAnimation _easeInAnimation;
Animation<double> _iconTurns;
bool myExpandedState = false;
int _monthIndex;
int monthIndexFromTime(DateTime time) {
return (time.year - 1970) * 12 + (time.month - 1);
}
DateTime monthToShow(int index) {
return new DateTime(index ~/ 12 + 1970, index % 12 + 1, 1);
}
@override
void initState() {
super.initState();
_monthIndex = monthIndexFromTime(new DateTime.now());
_controller = new AnimationController(duration: _kExpand, vsync: this);
//sharedState = SharedCalendarState.get(widget.calendarKey);
_easeInAnimation =
new CurvedAnimation(parent: _controller, curve: Curves.easeIn);
_iconTurns =
new Tween<double>(begin: 0.0, end: 0.5).animate(_easeInAnimation);
_indexChangeSubscription =
widget.state.indexChangeStream.listen((int newTop) {
setState(() {
int ms = (widget.state.currentTopDisplayIndex + 1) *
Duration.millisecondsPerDay;
DateTime currentTopTemp = new DateTime.fromMillisecondsSinceEpoch(ms);
_monthIndex = monthIndexFromTime(currentTopTemp);
});
});
_headerExpandedSubscription =
widget.state.headerExpandedChangeStream.listen((bool change) {
if (myExpandedState != change) {
setState(() {
myExpandedState = change;
_doAnimation();
});
}
});
}
void _doAnimation() {
if (myExpandedState) {
_controller.forward();
} else {
_controller.reverse().then<void>((Null value) {
setState(() {
// Rebuild without widget.children.
});
});
}
}
@override
void dispose() {
super.dispose();
_subscription?.cancel();
_subscription = null;
_controller?.dispose();
_controller = null;
_headerExpandedSubscription?.cancel();
_headerExpandedSubscription = null;
_indexChangeSubscription?.cancel();
_indexChangeSubscription = null;
}
void _handleOpen() {
setState(() {
// Jump the page controller to the right spot.
myExpandedState = !widget.state.headerExpanded;
widget.state.headerExpanded = myExpandedState;
_doAnimation();
PageStorage.of(context)?.writeState(context, widget.state..headerExpanded);
});
}
Widget _buildChildren(BuildContext context, Widget child) {
return new Container(
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_buildCurrentHeader(context),
new ClipRect(
child: new Align(
heightFactor: _easeInAnimation.value,
child: new Container(
constraints:
new BoxConstraints(minHeight: 230.0, maxHeight: 230.0),
child: new Dismissible(
key: new ValueKey<int>(_monthIndex),
resizeDuration: null,
onDismissed: (DismissDirection direction) {
setState(() {
_monthIndex +=
direction == DismissDirection.endToStart ? 1 : -1;
// Update the current scroll pos too.
widget.state.scrollToDay(monthToShow(_monthIndex));
});
},
child: new _CalendarMonthDisplay(
widget.state,
widget._location,
monthToShow(_monthIndex),
widget.dayIndicator,
widget.eventIndicator,
),
),
),
),
),
],
),
);
}
@override
Widget build(BuildContext context) {
return new Material(
elevation: 4.0,
color: widget.color ?? Colors.white,
child: new AnimatedBuilder(
animation: _controller,
builder: _buildChildren,
child: _buildCurrentHeader(context),
),
);
}
Widget _buildCurrentHeader(BuildContext context) {
int ms =
(widget.state.currentTopDisplayIndex + 1) * Duration.millisecondsPerDay;
DateTime currentTopTemp = new DateTime.fromMillisecondsSinceEpoch(ms);
DateTime currentTop = new DateTime(
currentTopTemp.year, currentTopTemp.month, currentTopTemp.day);
return new Container(
padding: new EdgeInsets.only(top: 8.0, left: 5.0, bottom: 8.0),
decoration: new BoxDecoration(
color: widget.color ?? Colors.white,
image: new DecorationImage(
image: widget.bannerHeader,
fit: BoxFit.fitHeight,
alignment: new Alignment(1.0, 1.0),
),
),
child: new GestureDetector(
onTap: _handleOpen,
child: new Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
new Text(
myExpandedState
? MaterialLocalizations.of(context)
.formatMonthYear(monthToShow(_monthIndex))
: MaterialLocalizations.of(context)
.formatMonthYear(currentTop),
style: widget.headerStyle ??
Theme.of(context).textTheme.title.copyWith(fontSize: 25.0),
),
new RotationTransition(
turns: _iconTurns,
child: const Icon(
Icons.expand_more,
size: 25.0,
),
),
],
),
),
);
}
}
///
/// Shows a small dot for the event to show the calendar day has a specific
/// event at it.
///
class _CalendarEventIndicator extends CustomPainter {
final double _radius;
final CalendarEvent _event;
_CalendarEventIndicator(this._radius, this._event);
@override
void paint(Canvas canvas, Size size) {
if (_radius == null) {
return;
}
canvas.drawCircle(new Offset(_radius, _radius), _radius,
new Paint()..color = Colors.black);
}
@override
bool shouldRepaint(_CalendarEventIndicator other) =>
other._radius != _radius || other._event != _event;
}
///
/// The animated container to show for the month with all the days and the
/// day headers.
///
class _CalendarMonthDisplay extends StatelessWidget {
final CalendarWidgetState sharedState;
final Location location;
final DateTime displayDate;
final HeaderDayIndicator dayIndicator;
final EventIndicator eventIndicator;
static const Duration week = const Duration(days: 7);
_CalendarMonthDisplay(this.sharedState, this.location, this.displayDate,
this.dayIndicator, this.eventIndicator);
Widget _eventIndicator(Widget button, int eventIndex) {
if (sharedState.events.containsKey(eventIndex)) {
if (eventIndicator != null) {
return eventIndicator(button, sharedState.events[eventIndex]);
}
List<Widget> eventIndicators = <Widget>[];
for (CalendarEvent event in sharedState.events[eventIndex]) {
eventIndicators.add(
new SizedBox(
height: 4.0,
width: 4.0,
child: new CustomPaint(
painter: new _CalendarEventIndicator(2.0, event),
),
),
);
eventIndicators.add(
new SizedBox(
width: 2.0,
),
);
}
return new SizedBox(
width: 40.0,
height: 40.0,
child: new Stack(
children: <Widget>[
button,
new Container(
alignment: new Alignment(1.0, 1.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.max,
children: eventIndicators,
),
),
],
),
);
} else {
if (eventIndicator != null) {
return eventIndicator(button, <CalendarEvent>[]);
}
return new SizedBox(
width: 40.0,
height: 40.0,
child: button,
);
}
}
Widget _buildButton(ThemeData theme, DateTime day, DateTime nowTime) {
Widget button;
// Only show days in the current month.
if (day.month != displayDate.month) {
button = new SizedBox(width: 1.0);
} else {
if (dayIndicator != null) {
button = dayIndicator(theme, day, nowTime);
} else {
button = new Center(
child: new FlatButton(
color: day.isAtSameMomentAs(nowTime)
? theme.accentColor
: day.isAtSameMomentAs(displayDate)
? Colors.grey.shade200
: Colors.white,
shape: new CircleBorder(),
child: new Text(day.day.toString()),
onPressed: () => sharedState.scrollToDay(day),
padding: EdgeInsets.zero,
),
);
}
}
int eventIndex = CalendarEvent.indexFromMilliseconds(day, location);
return _eventIndicator(button, eventIndex);
}
@override
Widget build(BuildContext context) {
DateTime nowTmp = new DateTime.now();
DateTime nowTime = new DateTime(nowTmp.year, nowTmp.month, nowTmp.day);
DateTime topFirst = displayDate;
topFirst = topFirst.subtract(new Duration(days: topFirst.weekday));
DateTime topSecond = topFirst.add(week);
if (topSecond.day == 1) {
// Opps, out by a week.
topFirst = topSecond;
topSecond = topFirst.add(week);
}
DateTime topThird = topSecond.add(week);
DateTime topFourth = topThird.add(week);
DateTime topFifth = topFourth.add(week);
List<Widget> dayHeaders = <Widget>[];
List<Widget> firstDays = <Widget>[];
List<Widget> secondDays = <Widget>[];
List<Widget> thirdDays = <Widget>[];
List<Widget> fourthDays = <Widget>[];
List<Widget> fifthDays = <Widget>[];
ThemeData theme = Theme.of(context);
for (int i = 0; i < 7; i++) {
dayHeaders.add(
new SizedBox(
width: 40.0,
height: 20.0,
child: new Center(
child: new Text(
MaterialLocalizations.of(context)
.narrowWeekdays[topFirst.weekday % 7],
),
),
),
);
// First row.
firstDays.add(_buildButton(theme, topFirst, nowTime));
// Second row.
secondDays.add(_buildButton(theme, topSecond, nowTime));
// Third row.
thirdDays.add(_buildButton(theme, topThird, nowTime));
// Fourth row.
fourthDays.add(_buildButton(theme, topFourth, nowTime));
// Fifth row.
fifthDays.add(_buildButton(theme, topFifth, nowTime));
topFirst = topFirst.add(oneDay);
topSecond = topSecond.add(oneDay);
topThird = topThird.add(oneDay);
topFourth = topFourth.add(oneDay);
topFifth = topFifth.add(oneDay);
}
return new Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: dayHeaders,
),
new Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: firstDays,
),
new Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: secondDays,
),
new Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: thirdDays,
),
new Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: fourthDays,
),
new Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: fifthDays,
),
new SizedBox(height: 10.0),
],
);
}
}
| 31.118609
| 81
| 0.610436
|
c438243713e19a67983a5bfba993c012f021ee2b
| 8,292
|
ps1
|
PowerShell
|
Public/Converts/ConvertFrom-DistinguishedName.ps1
|
MikeYEG/PSSharedGoods
|
b049a7f85e7e9fa97eb552165556b8e3a28307dc
|
[
"MIT"
] | null | null | null |
Public/Converts/ConvertFrom-DistinguishedName.ps1
|
MikeYEG/PSSharedGoods
|
b049a7f85e7e9fa97eb552165556b8e3a28307dc
|
[
"MIT"
] | null | null | null |
Public/Converts/ConvertFrom-DistinguishedName.ps1
|
MikeYEG/PSSharedGoods
|
b049a7f85e7e9fa97eb552165556b8e3a28307dc
|
[
"MIT"
] | null | null | null |
function ConvertFrom-DistinguishedName {
<#
.SYNOPSIS
Converts a Distinguished Name to CN, OU, Multiple OUs or DC
.DESCRIPTION
Converts a Distinguished Name to CN, OU, Multiple OUs or DC
.PARAMETER DistinguishedName
Distinguished Name to convert
.PARAMETER ToOrganizationalUnit
Converts DistinguishedName to Organizational Unit
.PARAMETER ToDC
Converts DistinguishedName to DC
.PARAMETER ToDomainCN
Converts DistinguishedName to Domain CN
.EXAMPLE
$DistinguishedName = 'CN=Przemyslaw Klys,OU=Users,OU=Production,DC=ad,DC=evotec,DC=xyz'
ConvertFrom-DistinguishedName -DistinguishedName $DistinguishedName -ToOrganizationalUnit
Output:
OU=Users,OU=Production,DC=ad,DC=evotec,DC=xyz
.EXAMPLE
$DistinguishedName = 'CN=Przemyslaw Klys,OU=Users,OU=Production,DC=ad,DC=evotec,DC=xyz'
ConvertFrom-DistinguishedName -DistinguishedName $DistinguishedName
Output:
Przemyslaw Klys
.EXAMPLE
ConvertFrom-DistinguishedName -DistinguishedName 'OU=Users,OU=Production,DC=ad,DC=evotec,DC=xyz' -ToMultipleOrganizationalUnit -IncludeParent
Output:
OU=Users,OU=Production,DC=ad,DC=evotec,DC=xyz
OU=Production,DC=ad,DC=evotec,DC=xyz
.EXAMPLE
ConvertFrom-DistinguishedName -DistinguishedName 'OU=Users,OU=Production,DC=ad,DC=evotec,DC=xyz' -ToMultipleOrganizationalUnit
Output:
OU=Production,DC=ad,DC=evotec,DC=xyz
.EXAMPLE
$Con = @(
'CN=Windows Authorization Access Group,CN=Builtin,DC=ad,DC=evotec,DC=xyz'
'CN=Mmm,DC=elo,CN=nee,DC=RootDNSServers,CN=MicrosoftDNS,CN=System,DC=ad,DC=evotec,DC=xyz'
'CN=e6d5fd00-385d-4e65-b02d-9da3493ed850,CN=Operations,CN=DomainUpdates,CN=System,DC=ad,DC=evotec,DC=xyz'
'OU=Domain Controllers,DC=ad,DC=evotec,DC=pl'
'OU=Microsoft Exchange Security Groups,DC=ad,DC=evotec,DC=xyz'
)
ConvertFrom-DistinguishedName -DistinguishedName $Con -ToLastName
Output:
Windows Authorization Access Group
Mmm
e6d5fd00-385d-4e65-b02d-9da3493ed850
Domain Controllers
Microsoft Exchange Security Groups
.NOTES
General notes
#>
[CmdletBinding(DefaultParameterSetName = 'Default')]
param(
[Parameter(ParameterSetName = 'ToOrganizationalUnit')]
[Parameter(ParameterSetName = 'ToMultipleOrganizationalUnit')]
[Parameter(ParameterSetName = 'ToDC')]
[Parameter(ParameterSetName = 'ToDomainCN')]
[Parameter(ParameterSetName = 'Default')]
[Parameter(ParameterSetName = 'ToLastName')]
[alias('Identity', 'DN')][Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, Position = 0)][string[]] $DistinguishedName,
[Parameter(ParameterSetName = 'ToOrganizationalUnit')][switch] $ToOrganizationalUnit,
[Parameter(ParameterSetName = 'ToMultipleOrganizationalUnit')][alias('ToMultipleOU')][switch] $ToMultipleOrganizationalUnit,
[Parameter(ParameterSetName = 'ToMultipleOrganizationalUnit')][switch] $IncludeParent,
[Parameter(ParameterSetName = 'ToDC')][switch] $ToDC,
[Parameter(ParameterSetName = 'ToDomainCN')][switch] $ToDomainCN,
[Parameter(ParameterSetName = 'ToLastName')][switch] $ToLastName
)
Process {
foreach ($Distinguished in $DistinguishedName) {
if ($ToDomainCN) {
$DN = $Distinguished -replace '.*?((DC=[^=]+,)+DC=[^=]+)$', '$1'
$CN = $DN -replace ',DC=', '.' -replace "DC="
if ($CN) {
$CN
}
} elseif ($ToOrganizationalUnit) {
$Value = [Regex]::Match($Distinguished, '(?=OU=)(.*\n?)(?<=.)').Value
if ($Value) {
$Value
}
} elseif ($ToMultipleOrganizationalUnit) {
if ($IncludeParent) {
$Distinguished
}
while ($true) {
#$dn = $dn -replace '^.+?,(?=CN|OU|DC)'
$Distinguished = $Distinguished -replace '^.+?,(?=..=)'
if ($Distinguished -match '^DC=') {
break
}
$Distinguished
}
} elseif ($ToDC) {
#return [Regex]::Match($DistinguishedName, '(?=DC=)(.*\n?)(?<=.)').Value
# return [Regex]::Match($DistinguishedName, '.*?(DC=.*)').Value
$Value = $Distinguished -replace '.*?((DC=[^=]+,)+DC=[^=]+)$', '$1'
if ($Value) {
$Value
}
#return [Regex]::Match($DistinguishedName, 'CN=.*?(DC=.*)').Groups[1].Value
} elseif ($ToLastName) {
# Would be best if it worked, but there is too many edge cases so hand splits seems to be the best solution
# Feel free to change it back to regex if you know how ;)
<# https://stackoverflow.com/questions/51761894/regex-extract-ou-from-distinguished-name
$Regex = "^(?:(?<cn>CN=(?<name>.*?)),)?(?<parent>(?:(?<path>(?:CN|OU).*?),)?(?<domain>(?:DC=.*)+))$"
$Found = $Distinguished -match $Regex
if ($Found) {
$Matches.name
}
#>
$NewDN = $Distinguished -split ",DC="
if ($NewDN[0].Contains(",OU=")) {
[Array] $ChangedDN = $NewDN[0] -split ",OU="
} elseif ($NewDN[0].Contains(",CN=")) {
[Array] $ChangedDN = $NewDN[0] -split ",CN="
} else {
[Array] $ChangedDN = $NewDN[0]
}
if ($ChangedDN[0].StartsWith('CN=')) {
$ChangedDN[0] -replace 'CN=', ''
} else {
$ChangedDN[0] -replace 'OU=', ''
}
} else {
$Regex = '^CN=(?<cn>.+?)(?<!\\),(?<ou>(?:(?:OU|CN).+?(?<!\\),)+(?<dc>DC.+?))$'
#$Output = foreach ($_ in $Distinguished) {
$Found = $Distinguished -match $Regex
if ($Found) {
$Matches.cn
}
#}
#$Output.cn
}
}
}
}
#ConvertFrom-DistinguishedName -DistinguishedName 'OU=Users,OU=Production,DC=ad,DC=evotec,DC=xyz' -ToMultipleOrganizationalUnit -IncludeParent
#ConvertFrom-DistinguishedName -DistinguishedName 'CN=test,OU=Users,OU=Production,DC=ad,DC=evotec,DC=xyz'
<#
$DistinguishedName = @(
'CN=Przemyslaw Klys,OU=Users,OU=Production,DC=ad,DC=evotec,DC=xyz'
'CN=ITR03_AD Admins,OU=Security,OU=Groups,OU=Production,DC=ad,DC=evotec,DC=xyz'
'CN=SADM Testing 2,OU=Special,OU=Accounts,OU=Production,DC=ad,DC=evotec,DC=xyz'
)
ConvertFrom-DistinguishedName -ToOrganizationalUnit -DistinguishedName $DistinguishedName
#>
<#
$Oops = 'cn={55FB3860-74C9-4262-AD77-30197EAB9999},cn=policies,cn=system,DC=ad,DC=evotec,DC=xyz'
ConvertFrom-DistinguishedName -DistinguishedName $Oops -ToDomainCN | Format-Table -AutoSize
$Con = @(
'CN=Windows Authorization Access Group,CN=Builtin,DC=ad,DC=evotec,DC=xyz'
'CN=Mmm,DC=elo,CN=nee,DC=RootDNSServers,CN=MicrosoftDNS,CN=System,DC=ad,DC=evotec,DC=xyz'
'CN=e6d5fd00-385d-4e65-b02d-9da3493ed850,CN=Operations,CN=DomainUpdates,CN=System,DC=ad,DC=evotec,DC=xyz'
'OU=Domain Controllers,DC=ad,DC=evotec,DC=pl'
'OU=Microsoft Exchange Security Groups,DC=ad,DC=evotec,DC=xyz'
)
foreach ($_ in $Con) {
ConvertFrom-DistinguishedName -DistinguishedName $_ -ToDC | Format-Table -AutoSize
}
foreach ($_ in $Con) {
ConvertFrom-DistinguishedName -DistinguishedName $_ -ToOrganizationalUnit | Format-Table -AutoSize
}
return
$Search = '*DC=RootDNSServers*'
$Server = 'ad.evotec.xyz'
$DomainStructure = Get-ADObject -Filter * -Properties canonicalName -SearchScope OneLevel -Server $Server | Sort-Object canonicalName #| Select-Object objectClass, canonicalName, DistinguishedName
$Output = foreach ($Structure in $DomainStructure) {
Get-ADObject -SearchBase $Structure.DistinguishedName -Filter * -Properties canonicalName -Server $Server -SearchScope Subtree | Sort-Object canonicalName
}
$Output | Where-Object { $_.DistinguishedName -like $Search } | ft -a
#>
| 41.253731
| 196
| 0.606971
|
e854cb24b0d719d6d08633c7b8779b0b826bc207
| 85,141
|
cs
|
C#
|
test/EndToEndTests/Framework/TestProviders/Dictionary/DictionaryDataContext.cs
|
Sreejithpin/odata.net
|
b54d376a382440df9074e78ca2e76b080965a2eb
|
[
"CC-BY-3.0"
] | 629
|
2015-01-02T08:40:43.000Z
|
2022-03-28T15:28:06.000Z
|
test/EndToEndTests/Framework/TestProviders/Dictionary/DictionaryDataContext.cs
|
Sreejithpin/odata.net
|
b54d376a382440df9074e78ca2e76b080965a2eb
|
[
"CC-BY-3.0"
] | 2,078
|
2015-01-06T05:44:13.000Z
|
2022-03-31T08:37:22.000Z
|
test/EndToEndTests/Framework/TestProviders/Dictionary/DictionaryDataContext.cs
|
Sreejithpin/odata.net
|
b54d376a382440df9074e78ca2e76b080965a2eb
|
[
"CC-BY-3.0"
] | 412
|
2015-01-06T06:57:15.000Z
|
2022-03-11T13:40:39.000Z
|
//---------------------------------------------------------------------
// <copyright file="DictionaryDataContext.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.Test.OData.Framework.TestProviders.Dictionary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Xml;
using Microsoft.OData.Service.Providers;
using Microsoft.Test.OData.Framework.TestProviders.Common;
using Microsoft.Test.OData.Framework.TestProviders.Contracts;
/// <summary>
/// An implementation of the query, metadata, and update providers that uses typed/untyped and open/closed resources based on dictionaries
/// </summary>
public abstract class DictionaryDataContext
{
private static readonly Dictionary<Type, Dictionary<string, IList<ResourceInstance>>> resourceSetsByContextTypeStorage = new Dictionary<Type, Dictionary<string, IList<ResourceInstance>>>();
private readonly IList<object> deletedObjects = new List<object>();
private readonly IList<Action> pendingChanges = new List<Action>();
private readonly HashSet<string> resourceTypeCache = new HashSet<string>();
private readonly HashSet<string> resourceSetCache = new HashSet<string>();
private readonly HashSet<string> serviceOperationCache = new HashSet<string>();
private readonly HashSet<string> resourceAssociationSetCache = new HashSet<string>();
private readonly DictionaryMetadataHelper metadataHelper;
private readonly object dataServiceInstance;
private bool containerNameAlreadyAccessed = false;
private bool containerNamespaceAlreadyAccessed = false;
/// <summary>
/// Initializes a new instance of the DictionaryDataContext class
/// </summary>
/// <remarks>
/// Using this constructor is incompatible with service operations
/// </remarks>
protected DictionaryDataContext() : this(null)
{
}
/// <summary>
/// Initializes a new instance of the DictionaryDataContext class
/// </summary>
/// <param name="dataService">the Data Service</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Must be initialized at construction time")]
protected DictionaryDataContext(object dataService)
{
this.metadataHelper = this.CreateMetadataHelper();
this.dataServiceInstance = dataService;
if (!resourceSetsByContextTypeStorage.ContainsKey(this.GetType()))
{
resourceSetsByContextTypeStorage.Add(this.GetType(), new Dictionary<string, IList<ResourceInstance>>());
this.InitializeResourceSetsStorage();
}
this.EnsureDataIsInitialized();
}
/// <summary>
/// Gets the container name
/// </summary>
public virtual string ContainerName
{
get
{
if (ProviderImplementationSettings.Current.EnforceMetadataCaching)
{
ExceptionUtilities.ThrowDataServiceExceptionIfFalse(!this.containerNameAlreadyAccessed, 500, "IDSMP.ContainerName should be cached after the first access");
this.containerNameAlreadyAccessed = true;
}
return this.GetType().Name;
}
}
/// <summary>
/// Gets the container namespace
/// </summary>
public virtual string ContainerNamespace
{
get
{
if (ProviderImplementationSettings.Current.EnforceMetadataCaching)
{
ExceptionUtilities.ThrowDataServiceExceptionIfFalse(!this.containerNamespaceAlreadyAccessed, 500, "IDSMP.ContainerNamespace should be cached after the first access");
this.containerNamespaceAlreadyAccessed = true;
}
return this.GetType().Namespace;
}
}
/// <summary>
/// Gets the metadata providers's types
/// </summary>
public virtual IEnumerable<ResourceType> Types
{
get
{
// Because this is not a 'try-resolve' style API, do not throw on repeats
return this.metadataHelper.ResourceTypes.Select(t => this.EnforceMetadataCache(t, false, true));
}
}
/// <summary>
/// Gets the metadata providers's sets
/// </summary>
public virtual IEnumerable<ResourceSet> ResourceSets
{
get
{
// Because this is not a 'try-resolve' style API, do not throw on repeats
return this.metadataHelper.ResourceSets.Select(s => this.EnforceMetadataCache(s, false, true, true));
}
}
/// <summary>
/// Gets the metadata providers's service operations
/// </summary>
public virtual IEnumerable<ServiceOperation> ServiceOperations
{
get
{
// Because this is not a 'try-resolve' style API, do not throw on repeats
return this.metadataHelper.ServiceOperations.Select(s => this.EnforceMetadataCache(s, false));
}
}
/// <summary>
/// Gets or sets the current data source
/// </summary>
public virtual object CurrentDataSource { get; set; }
/// <summary>
/// Gets a value indicating whether or not null-propagation is required
/// </summary>
public virtual bool IsNullPropagationRequired
{
get { return true; }
}
/// <summary>
/// Gets the Dictionary that contains the resourceSets
/// </summary>
protected internal Dictionary<string, IList<ResourceInstance>> ResourceSetsStorage
{
get
{
Dictionary<string, IList<ResourceInstance>> resourceSetsLookup = null;
Type currentContextType = this.GetType();
bool found = resourceSetsByContextTypeStorage.TryGetValue(currentContextType, out resourceSetsLookup);
ExceptionUtilities.Assert(found, "Cannot find resource sets by the context type '{0}'", currentContextType);
return resourceSetsLookup;
}
}
/// <summary>
/// Gets the set of method replacement strategies to use when evaluating queries
/// </summary>
protected abstract IEnumerable<IMethodReplacementStrategy> MethodReplacementStrategies { get; }
/// <summary>
/// Gets the resource association set with the given values
/// </summary>
/// <param name="resourceSet">The resource set</param>
/// <param name="resourceType">The resource type</param>
/// <param name="resourceProperty">The resource property</param>
/// <returns>The resource association set</returns>
public virtual ResourceAssociationSet GetResourceAssociationSet(ResourceSet resourceSet, ResourceType resourceType, ResourceProperty resourceProperty)
{
ExceptionUtilities.CheckArgumentNotNull(resourceSet, "resourceSet");
ExceptionUtilities.CheckArgumentNotNull(resourceType, "resourceType");
ExceptionUtilities.CheckArgumentNotNull(resourceProperty, "resourceProperty");
ExceptionUtilities.Assert(
(resourceProperty.Kind & (ResourcePropertyKind.ResourceReference | ResourcePropertyKind.ResourceSetReference)) != 0,
"GetResourceAssociationSet called with non-navigation property '{0}' of kind '{1}'.",
resourceProperty.Name,
resourceProperty.Kind);
ExceptionUtilities.Assert(resourceType.GetLocalPropertiesLazily().Contains(resourceProperty), "ResourceProperty '{0}' must be on the ResourceType '{1}' when finding the ResourceAssociationSet", resourceProperty.Name, resourceType.Name);
ExceptionUtilities.Assert(this.metadataHelper.GetResourceTypesOfResourceSet(resourceSet).Contains(resourceType), "ResourceSet '{0}' does not contain ResourceType '{1}'", resourceSet.Name, resourceType.Name);
foreach (var associationSet in this.metadataHelper.ResourceAssociationSets)
{
if (associationSet.End1.ResourceSet == resourceSet && associationSet.End1.ResourceType == resourceType && associationSet.End1.ResourceProperty == resourceProperty)
{
return this.EnforceMetadataCache(associationSet, resourceSet, resourceType, resourceProperty, true);
}
if (associationSet.End2.ResourceSet == resourceSet && associationSet.End2.ResourceType == resourceType && associationSet.End2.ResourceProperty == resourceProperty)
{
return this.EnforceMetadataCache(associationSet, resourceSet, resourceType, resourceProperty, true);
}
}
return null;
}
/// <summary>
/// Trys to find the resource set with the given name
/// </summary>
/// <param name="name">The name of the set</param>
/// <param name="resourceSet">The set, if found</param>
/// <returns>Whether or not the set was found</returns>
public virtual bool TryResolveResourceSet(string name, out ResourceSet resourceSet)
{
ExceptionUtilities.CheckArgumentNotNull(name, "name");
resourceSet = this.GetResourceSet(name);
if (resourceSet != null)
{
// ideally, we would throw on re-resolution, but for each query interceptor this API will
// be invoked regardless of cache status and the actual resource type needs to match
resourceSet = this.EnforceMetadataCache(resourceSet, false, false, true);
return true;
}
return false;
}
/// <summary>
/// Trys to find the service operation with the given name
/// </summary>
/// <param name="name">The name of the set</param>
/// <param name="serviceOperation">The service operation, if found</param>
/// <returns>Whether or not the service operation was found</returns>
public virtual bool TryResolveServiceOperation(string name, out ServiceOperation serviceOperation)
{
ExceptionUtilities.CheckArgumentNotNull(name, "name");
serviceOperation = this.metadataHelper.ServiceOperations.SingleOrDefault(o => o.Name == name);
if (serviceOperation != null)
{
// Because this is a 'try-resolve' style API, throw on repeats
serviceOperation = this.EnforceMetadataCache(serviceOperation, true);
return true;
}
return false;
}
/// <summary>
/// Trys to find the resource type with the given name
/// </summary>
/// <param name="name">The name of the type</param>
/// <param name="resourceType">The type, if found</param>
/// <returns>Whether or not the type was found</returns>
public virtual bool TryResolveResourceType(string name, out ResourceType resourceType)
{
ExceptionUtilities.CheckArgumentNotNull(name, "name");
resourceType = this.metadataHelper.ResourceTypes.SingleOrDefault(t => t.FullName == name);
if (resourceType != null)
{
// Because this is a 'try-resolve' style API, throw on repeats
resourceType = this.EnforceMetadataCache(resourceType, true, true);
return true;
}
return false;
}
/// <summary>
/// Returns whether or not the type has derived types
/// </summary>
/// <param name="resourceType">The type to check for derived types</param>
/// <returns>True if the type has derived types, false otherwise</returns>
public virtual bool HasDerivedTypes(ResourceType resourceType)
{
ExceptionUtilities.CheckArgumentNotNull(resourceType, "resourceType");
ExceptionUtilities.Assert(resourceType.ResourceTypeKind == ResourceTypeKind.EntityType || resourceType.ResourceTypeKind == ResourceTypeKind.ComplexType, "HasDerivedTypes called on non-entity, non-complex type '{0}'", resourceType.FullName);
return this.metadataHelper.ResourceTypes.Any(t => t.BaseType == resourceType);
}
/// <summary>
/// Returns the types derived from the given type
/// </summary>
/// <param name="resourceType">The given type</param>
/// <returns>The type's derived types</returns>
public virtual IEnumerable<ResourceType> GetDerivedTypes(ResourceType resourceType)
{
ExceptionUtilities.CheckArgumentNotNull(resourceType, "resourceType");
ExceptionUtilities.Assert(resourceType.ResourceTypeKind == ResourceTypeKind.EntityType, "GetDerivedTypes called on non-entity type '{0}'", resourceType.FullName);
// Because this is not a 'try-resolve' style API, do not throw on repeats
return this.GetDerivedTypesInternal(resourceType).Select(t => this.EnforceMetadataCache(t, false, true));
}
/// <summary>
/// Gets the value of the given property for the given resource
/// </summary>
/// <param name="targetResource">The given resource</param>
/// <param name="resourceProperty">The property to get the value for</param>
/// <returns>The property value</returns>
public virtual object GetPropertyValue(object targetResource, ResourceProperty resourceProperty)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(resourceProperty, "resourceProperty");
ExceptionUtilities.Assert(!resourceProperty.CanReflectOnInstanceTypeProperty, "Should not have been called for property '{0}' which can be reflected on", resourceProperty.Name);
ExceptionUtilities.Assert(!resourceProperty.Kind.HasFlag(ResourcePropertyKind.Stream), "GetPropertyValue called on stream property '{0}'", resourceProperty.Name);
var resourceInstance = targetResource as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(resourceInstance, "Given target was not a resource instance. Type was '{0}'.", targetResource.GetType());
object propertyValue;
if (!resourceInstance.TryGetValue(resourceProperty.Name, out propertyValue))
{
propertyValue = null;
}
return propertyValue;
}
/// <summary>
/// Gets the open property values for the given resource
/// </summary>
/// <param name="target">The instance to get values from</param>
/// <returns>The open property values</returns>
public virtual IEnumerable<KeyValuePair<string, object>> GetOpenPropertyValues(object target)
{
ExceptionUtilities.CheckArgumentNotNull(target, "target");
var instance = target as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(instance, "Given target was not a resource instance. Type was '{0}'.", target.GetType());
ExceptionUtilities.Assert(instance.IsEntityType, "GetOpenPropertyValues called on instance of complex type '{0}'", instance.ResourceTypeName);
var resourceType = this.metadataHelper.ResourceTypes.Single(t => t.FullName == instance.ResourceTypeName);
ExceptionUtilities.Assert(resourceType.IsOpenType, "GetOpenPropertyValues called on non-open type '{0}'", resourceType.FullName);
return instance.Where(pair => !resourceType.GetAllPropertiesLazily().Any(p => p.Name == pair.Key));
}
/// <summary>
/// Gets an open property value with the given name
/// </summary>
/// <param name="target">The instance to get the value from</param>
/// <param name="propertyName">The open property name</param>
/// <returns>The value of the property</returns>
public virtual object GetOpenPropertyValue(object target, string propertyName)
{
ExceptionUtilities.CheckArgumentNotNull(target, "target");
ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName");
var instance = target as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(target, "Given target was not a resource instance. Type was '{0}'.", target.GetType());
ExceptionUtilities.Assert(instance.IsEntityType, "GetOpenPropertyValue called on instance of complex type '{0}'", instance.ResourceTypeName);
var resourceType = this.metadataHelper.ResourceTypes.Single(t => t.FullName == instance.ResourceTypeName);
ExceptionUtilities.Assert(resourceType.IsOpenType, "GetOpenPropertyValue called on non-open type '{0}'", resourceType.FullName);
ExceptionUtilities.Assert(
!resourceType.GetAllPropertiesLazily().Any(p => p.Name == propertyName),
"GetOpenPropertyValue called on declared property '{0}' on type '{1}'",
propertyName,
resourceType.FullName);
object value;
if (instance.TryGetValue(propertyName, out value))
{
return value;
}
return null;
}
/// <summary>
/// Gets the root queryable for the given set
/// </summary>
/// <param name="container">The resource set</param>
/// <returns>The root queryable</returns>
public virtual IQueryable GetQueryRootForResourceSet(ResourceSet container)
{
ExceptionUtilities.CheckArgumentNotNull(container, "container");
var queryable = this.ResourceSetsStorage[container.Name].AsQueryable();
if (this.MethodReplacementStrategies.Any())
{
var provider = new MethodReplacingQueryProvider(queryable.Provider, new MethodReplacingExpressionVisitor(this.MethodReplacementStrategies));
queryable = provider.CreateQuery<ResourceInstance>(queryable.Expression);
}
if (container.ResourceType.InstanceType == typeof(ResourceInstance))
{
return queryable;
}
else
{
MethodInfo castMethod = typeof(Queryable).GetMethod("Cast", BindingFlags.Static | BindingFlags.Public);
castMethod = castMethod.MakeGenericMethod(container.ResourceType.InstanceType);
object newQueryable = castMethod.Invoke(null, new object[] { queryable });
return newQueryable as IQueryable;
}
}
/// <summary>
/// Gets the resource type for the given instance
/// </summary>
/// <param name="resource">The instance to get the type for</param>
/// <returns>The type of the resource</returns>
public virtual ResourceType GetResourceType(object resource)
{
// Because this is not a 'try-resolve' style API, do not throw on repeats
return this.EnforceMetadataCache(this.GetResourceTypeInternal(resource), false, true);
}
/// <summary>
/// Invokes the service operation with the given parameters
/// </summary>
/// <param name="serviceOperation">The service operation to invoke</param>
/// <param name="parameters">The parameters to the service operation</param>
/// <returns>The result of invoking the service operation</returns>
public virtual object InvokeServiceOperation(ServiceOperation serviceOperation, object[] parameters)
{
ExceptionUtilities.CheckArgumentNotNull(serviceOperation, "serviceOperation");
ExceptionUtilities.CheckArgumentNotNull(parameters, "parameters");
ExceptionUtilities.CheckObjectNotNull(this.dataServiceInstance, "The data service instance has not been specified");
Type serviceType = this.dataServiceInstance.GetType();
MethodInfo serviceOperationMethod = serviceType.GetMethod(serviceOperation.Name);
ExceptionUtilities.CheckObjectNotNull(serviceOperationMethod, "Method for service operation {0} not found", serviceOperation.Name);
return serviceOperationMethod.Invoke(this.dataServiceInstance, BindingFlags.FlattenHierarchy | BindingFlags.Instance, null, parameters, System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>
/// Adds the given reference to the given collection property
/// </summary>
/// <param name="targetResource">The instance whose property to add to</param>
/// <param name="propertyName">The property to add</param>
/// <param name="resourceToBeAdded">The resource to add</param>
public virtual void AddReferenceToCollection(object targetResource, string propertyName, object resourceToBeAdded)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName");
ExceptionUtilities.CheckArgumentNotNull(resourceToBeAdded, "resourceToBeAdded");
targetResource = UpdatableToken.AssertIsTokenAndResolve(targetResource, "targetResource");
resourceToBeAdded = UpdatableToken.AssertIsTokenAndResolve(resourceToBeAdded, "resourceToBeAdded");
var targetInstance = targetResource as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(targetInstance, "Target resource was not a resource instance. Type was '{0}'", targetResource.GetType());
var addInstance = resourceToBeAdded as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(addInstance, "Resource to be added was not a resource instance. Type was '{0}'", targetResource.GetType());
this.pendingChanges.Add(() => this.AddReferenceToCollection_Internal(targetInstance, propertyName, addInstance, true));
}
/// <summary>
/// Creates a resource in the given set with the given type
/// </summary>
/// <param name="containerName">The given set name</param>
/// <param name="fullTypeName">The given type name</param>
/// <returns>The resource created</returns>
public virtual object CreateResource(string containerName, string fullTypeName)
{
ExceptionUtilities.CheckArgumentNotNull(fullTypeName, "fullTypeName");
ResourceType type = this.metadataHelper.ResourceTypes.SingleOrDefault(t => t.FullName == fullTypeName);
ExceptionUtilities.CheckObjectNotNull(type, "Could not find type with name '{0}'", fullTypeName);
ExceptionUtilities.ThrowDataServiceExceptionIfFalse(!type.IsAbstract, 400, "Cannot create resource because type '{0}' is abstract.", type.FullName);
ResourceInstance instance;
if (type.ResourceTypeKind == ResourceTypeKind.ComplexType)
{
ExceptionUtilities.Assert(containerName == null, "Container name must be null for complex types. Value was '{0}'", containerName);
if (type.InstanceType == typeof(ResourceInstance))
{
instance = new ResourceInstance(type);
}
else
{
ConstructorInfo constructor = type.InstanceType.GetConstructor(new[] { typeof(ResourceType) });
ExceptionUtilities.CheckObjectNotNull(constructor, "Could not find constructor for complex type '{0}'", type.InstanceType);
instance = (ResourceInstance)constructor.Invoke(new object[] { type });
}
}
else
{
ExceptionUtilities.CheckArgumentNotNull(containerName, "containerName");
ResourceSet set = this.GetResourceSet(containerName);
ExceptionUtilities.CheckObjectNotNull(set, "Could not find resource set with name '{0}'", containerName);
ExceptionUtilities.Assert(set.ResourceType == type || this.GetDerivedTypesInternal(set.ResourceType).Contains(type), "An entity of type '{0}' cannot be added to set '{1}'", fullTypeName, containerName);
if (type.InstanceType == typeof(ResourceInstance))
{
instance = new ResourceInstance(type, set);
}
else
{
ConstructorInfo constructor = type.InstanceType.GetConstructor(new[] { typeof(ResourceType), typeof(ResourceSet) });
ExceptionUtilities.CheckObjectNotNull(constructor, "Could not find constructor for entity type '{0}'", type.InstanceType);
instance = (ResourceInstance)constructor.Invoke(new object[] { type, set });
}
// TODO: better message
ExceptionUtilities.ThrowDataServiceExceptionIfFalse(!this.ResourceSetsStorage[set.Name].Any(e => this.AreKeysEqual(e, instance)), 500, "Duplicate key");
this.pendingChanges.Add(() => this.ResourceSetsStorage[set.Name].Add(instance));
}
var token = new UpdatableToken(instance);
// foreach property marked as being server generated
foreach (ResourceProperty property in type.GetAllPropertiesLazily())
{
string propertyName = property.Name;
object generatedValue;
if (this.TryGetStoreGeneratedValue(containerName, fullTypeName, propertyName, out generatedValue))
{
token.PendingPropertyUpdates[propertyName] = generatedValue;
this.pendingChanges.Add(() => instance[propertyName] = generatedValue);
}
}
this.InitializeCollectionProperties(type, instance, token, p => p.Kind == ResourcePropertyKind.ResourceSetReference || p.Kind == ResourcePropertyKind.Collection);
return token;
}
/// <summary>
/// Deletes the given resource
/// </summary>
/// <param name="targetResource">The resource to delete</param>
public virtual void DeleteResource(object targetResource)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
targetResource = UpdatableToken.AssertIsTokenAndResolve(targetResource, "targetResource");
var instance = targetResource as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(instance, "Target resource was not a resource instance. Type was '{0}'", targetResource.GetType());
ExceptionUtilities.Assert(instance.IsEntityType, "Target resource was not an entity instance. Resource type was '{0}'", instance.ResourceTypeName);
this.deletedObjects.Add(targetResource);
this.DeleteAllReferences(instance);
this.pendingChanges.Add(() => this.ResourceSetsStorage[instance.ResourceSetName].Remove(instance));
}
/// <summary>
/// Gets the singleton result of the given query
/// </summary>
/// <param name="query">The given query</param>
/// <param name="fullTypeName">The full type name</param>
/// <returns>The resource from the query</returns>
public virtual object GetResource(IQueryable query, string fullTypeName)
{
ExceptionUtilities.CheckArgumentNotNull(query, "query");
object resource = GetResourceInternal(query);
if (resource != null)
{
return new UpdatableToken(resource);
}
return null;
}
/// <summary>
/// Gets the value of the given property
/// </summary>
/// <param name="targetResource">The resource to get the property value from</param>
/// <param name="propertyName">The property name</param>
/// <returns>The value of the property</returns>
public virtual object GetValue(object targetResource, string propertyName)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName");
// resolve the token, and return a pending value if there is one
// NOTE: this code is specifically to handle cases of mapped complex-type values, because the product does not cache the
// value returned by CreateResource so we need to take into account any pending updates, or we risk returning stale data
var token = UpdatableToken.AssertIsToken(targetResource, "targetResource");
if (token.PendingPropertyUpdates.ContainsKey(propertyName))
{
return token.PendingPropertyUpdates[propertyName];
}
targetResource = token.Resource;
var instance = targetResource as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(instance, "Target resource was not a resource instance. Type was '{0}'", targetResource.GetType());
var resourceType = this.metadataHelper.ResourceTypes.Single(t => t.FullName == instance.ResourceTypeName);
var property = resourceType.GetAllPropertiesLazily().SingleOrDefault(p => p.Name == propertyName);
if (property != null)
{
ExceptionUtilities.Assert(!property.Kind.HasFlag(ResourcePropertyKind.Stream), "GetValue called on stream property '{0}'", property.Name);
}
object value = null;
// Check for strongly typed properties
var type = targetResource.GetType();
PropertyInfo propertyInfo = type.GetProperty(propertyName);
if (propertyInfo != null)
{
value = propertyInfo.GetValue(targetResource, null);
}
else
{
object propertyValue;
if (instance.TryGetValue(propertyName, out propertyValue))
{
value = propertyValue;
}
}
var valueInstance = value as ResourceInstance;
if (valueInstance != null)
{
ExceptionUtilities.Assert(!valueInstance.IsEntityType, "GetValue should never be called for reference properties. Type was '{0}', property was '{1}'", resourceType.FullName, propertyName);
value = new UpdatableToken(valueInstance);
}
return value;
}
/// <summary>
/// Removes the given resource from the given collection property
/// </summary>
/// <param name="targetResource">The resource whose collection property to modify</param>
/// <param name="propertyName">The name of the property</param>
/// <param name="resourceToBeRemoved">The resource to remove</param>
public virtual void RemoveReferenceFromCollection(object targetResource, string propertyName, object resourceToBeRemoved)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName");
ExceptionUtilities.CheckArgumentNotNull(resourceToBeRemoved, "resourceToBeRemoved");
targetResource = UpdatableToken.AssertIsTokenAndResolve(targetResource, "targetResource");
resourceToBeRemoved = UpdatableToken.AssertIsTokenAndResolve(resourceToBeRemoved, "resourceToBeRemoved");
var targetInstance = targetResource as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(targetInstance, "Target resource was not a resource instance. Type was '{0}'", targetResource.GetType());
var removeInstance = resourceToBeRemoved as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(removeInstance, "Resource to be removed was not a resource instance. Type was '{0}'", targetResource.GetType());
this.pendingChanges.Add(() => this.RemoveReferenceFromCollection_Internal(targetInstance, propertyName, removeInstance, true));
}
/// <summary>
/// Resets the given resource
/// </summary>
/// <param name="resource">The resource to reset</param>
/// <returns>The reset resource</returns>
public virtual object ResetResource(object resource)
{
ExceptionUtilities.CheckArgumentNotNull(resource, "resource");
var token = UpdatableToken.AssertIsToken(resource, "resource");
resource = token.Resource;
// create a new token
token = new UpdatableToken(resource);
var instance = resource as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(instance, "Resource was not a resource instance. Type was '{0}'", resource.GetType());
var resourceType = this.metadataHelper.ResourceTypes.Single(t => t.FullName == instance.ResourceTypeName);
foreach (ResourceProperty p in resourceType.GetAllPropertiesLazily())
{
var property = p;
if ((property.Kind & (ResourcePropertyKind.Key | ResourcePropertyKind.ResourceReference | ResourcePropertyKind.ResourceSetReference)) == 0)
{
// TODO: initialize to defaults?
this.pendingChanges.Add(() => instance.Remove(property.Name));
}
}
// remove all dynamic properties
// the ToList is so we can modify the collection inside the loop
foreach (string key in instance.Keys.Except(resourceType.GetAllPropertiesLazily().Select(p => p.Name)).ToList())
{
var propertyName = key;
this.pendingChanges.Add(() => instance.Remove(propertyName));
}
this.InitializeCollectionProperties(resourceType, instance, token, p => p.Kind == ResourcePropertyKind.Collection);
return token;
}
/// <summary>
/// Resolves the given resource
/// </summary>
/// <param name="resource">The resource to resolve</param>
/// <returns>The resolved resource</returns>
public virtual object ResolveResource(object resource)
{
ExceptionUtilities.CheckArgumentNotNull(resource, "resource");
return UpdatableToken.AssertIsTokenAndResolve(resource, "resource");
}
/// <summary>
/// Saves all pending changes
/// </summary>
public virtual void SaveChanges()
{
foreach (var pendingChange in this.pendingChanges)
{
pendingChange();
}
this.pendingChanges.Clear();
foreach (var deleted in this.deletedObjects)
{
foreach (var entity in this.ResourceSetsStorage.SelectMany(p => p.Value))
{
ExceptionUtilities.Assert(!object.ReferenceEquals(deleted, entity), "Found deleted entity!");
var resourceType = this.metadataHelper.ResourceTypes.Single(t => t.FullName == entity.ResourceTypeName);
foreach (var property in resourceType.GetAllPropertiesLazily())
{
object value;
if (!entity.TryGetValue(property.Name, out value))
{
continue;
}
ExceptionUtilities.Assert(!object.ReferenceEquals(deleted, value), "Found deleted entity!");
var enumerable = value as IEnumerable;
if (enumerable != null)
{
foreach (var valueElement in enumerable.Cast<object>())
{
ExceptionUtilities.Assert(!object.ReferenceEquals(deleted, valueElement), "Found deleted entity!");
}
}
}
}
}
this.deletedObjects.Clear();
}
/// <summary>
/// Sets the given reference property
/// </summary>
/// <param name="targetResource">The resource whose property to set</param>
/// <param name="propertyName">The name of the reference property</param>
/// <param name="propertyValue">The reference to set the property to</param>
public virtual void SetReference(object targetResource, string propertyName, object propertyValue)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName");
targetResource = UpdatableToken.AssertIsTokenAndResolve(targetResource, "targetResource");
if (propertyValue != null)
{
propertyValue = UpdatableToken.AssertIsTokenAndResolve(propertyValue, "propertyValue");
}
var targetInstance = targetResource as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(targetInstance, "Target resource was not a resource instance. Type was '{0}'", targetResource.GetType());
ResourceInstance valueInstance = null;
if (propertyValue != null)
{
valueInstance = propertyValue as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(valueInstance, "Value was not a resource instance. Type was '{0}'", propertyValue.GetType());
}
this.pendingChanges.Add(() => this.SetReference_Internal(targetInstance, propertyName, valueInstance, true));
}
/// <summary>
/// Sets the value of the given property UpdatableToken
/// </summary>
/// <param name="targetResource">The resource whose property to set</param>
/// <param name="propertyName">The name of the property</param>
/// <param name="propertyValue">The value to set the property to</param>
public virtual void SetValue(object targetResource, string propertyName, object propertyValue)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName");
// Resolve targetResource
var token = UpdatableToken.AssertIsToken(targetResource, "targetResource");
targetResource = token.Resource;
var instance = targetResource as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(instance, "Resource was not a resource instance. Type was '{0}'", targetResource.GetType());
if (propertyValue != null)
{
// TODO: Remove if these bugs gets fixed because this is a side affect of those.
// [Open Types] Server rejects updates to collection properties declared on complex types when accessed via an un-declared complex property
// [Open Types] Property and $value update codepath allows modifying undeclared properties on complex types to an arbitrary depth
propertyValue = this.ConvertPropertyValueType(propertyName, propertyValue, this.GetResourceTypeInternal(targetResource));
}
object generatedValue;
if (this.TryGetStoreGeneratedValue(instance.ResourceSetName, instance.ResourceTypeName, propertyName, out generatedValue))
{
propertyValue = generatedValue;
}
token.PendingPropertyUpdates[propertyName] = propertyValue;
this.SetValue(instance, propertyName, propertyValue);
}
/// <summary>
/// Sets the value of the given property ResourceInstance
/// </summary>
/// <param name="targetResource">The resource whose property to set</param>
/// <param name="propertyName">The name of the property</param>
/// <param name="propertyValue">The value to set the property to</param>
public virtual void SetValueResourceInstance(object targetResource, string propertyName, object propertyValue)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName");
var instance = targetResource as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(targetResource, "Resource was not a resource instance. Type was '{0}'", targetResource.GetType());
object generatedValue;
if (this.TryGetStoreGeneratedValue(instance.ResourceSetName, instance.ResourceTypeName, propertyName, out generatedValue))
{
propertyValue = generatedValue;
}
this.SetValue(instance, propertyName, propertyValue);
}
/// <summary>
/// Clears all pending changes
/// </summary>
public virtual void ClearChanges()
{
this.pendingChanges.Clear();
}
/// <summary>
/// Sets the original concurrency values of the given object so that optimistic concurrency can be enforced. Will throw immediately if they do not match.
/// </summary>
/// <param name="resourceCookie">The resource to set original values for</param>
/// <param name="checkForEquality">Whether the check should be for equality</param>
/// <param name="concurrencyValues">The concurrency values</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ETag", Justification = "Spelling is correct")]
public virtual void SetConcurrencyValues(object resourceCookie, bool? checkForEquality, IEnumerable<KeyValuePair<string, object>> concurrencyValues)
{
ExceptionUtilities.CheckArgumentNotNull(resourceCookie, "resourceCookie");
ExceptionUtilities.ThrowDataServiceExceptionIfFalse(checkForEquality.HasValue, 417, "Missing concurrency token for update operation");
ExceptionUtilities.Assert(checkForEquality.Value, "Should not be called with check for equality parameter equal to false");
ExceptionUtilities.CheckArgumentNotNull(concurrencyValues, "concurrencyValues");
// If-Match: *
if (!concurrencyValues.Any())
{
return;
}
var instance = UpdatableToken.AssertIsTokenAndResolve(resourceCookie, "resourceCookie") as ResourceInstance;
ExceptionUtilities.CheckObjectNotNull(instance, "Resource was not a resource instance");
var resourceType = this.metadataHelper.ResourceTypes.Single(t => t.FullName == instance.ResourceTypeName);
var etagPropertyNames = resourceType.GetAllPropertiesLazily().Where(p => p.Kind.HasFlag(ResourcePropertyKind.ETag)).Select(p => p.Name);
ExceptionUtilities.ThrowDataServiceExceptionIfFalse(
etagPropertyNames.SequenceEqual(concurrencyValues.Select(p => p.Key)),
412,
"Unexpected or missing ETag properties");
foreach (var etagProperty in concurrencyValues)
{
object propertyValue = this.GetValue(resourceCookie, etagProperty.Key);
ExceptionUtilities.ThrowDataServiceExceptionIfFalse(
ResourceInstance.ArePropertyValuesEqual(propertyValue, etagProperty.Value),
412,
"The etag value in the request header does not match with the current etag value of the object.");
}
}
/// <summary>
/// Get resources
/// </summary>
/// <param name="queryable">Queryable to get data from</param>
/// <returns>Object to return</returns>
public virtual object GetResources(IQueryable queryable)
{
if (DataServiceOverrides.UpdateProvider2.GetResourcesFunc != null)
{
return DataServiceOverrides.UpdateProvider2.GetResourcesFunc(queryable);
}
return queryable;
}
/// <summary>
/// Adds an invokable to list of operations occuring in savechanges
/// </summary>
/// <param name="invokable">Action to invoke at save changes</param>
public virtual void ScheduleInvokable(IDataServiceInvokable invokable)
{
if (DataServiceOverrides.UpdateProvider2.ImmediateCreateInvokableFunc != null)
{
DataServiceOverrides.UpdateProvider2.ImmediateCreateInvokableFunc(invokable);
}
else if (DataServiceOverrides.UpdateProvider2.AddPendingActionsCreateInvokableFunc != null)
{
this.pendingChanges.Add(
() =>
{
DataServiceOverrides.UpdateProvider2.AddPendingActionsCreateInvokableFunc(invokable);
});
}
else
{
this.pendingChanges.Add(
() =>
{
invokable.Invoke();
});
}
}
/// <summary>
/// Gets the instance type of a particular collection property
/// </summary>
/// <param name="fullTypeName">The full type name</param>
/// <param name="propertyName">The property name</param>
/// <returns>The instance type or null if the type is unknown</returns>
protected virtual Type GetCollectionPropertyType(string fullTypeName, string propertyName)
{
return null;
}
/// <summary>
/// Sets the value of a collection property
/// </summary>
/// <param name="targetResource">The resource to set the value on</param>
/// <param name="propertyName">The property to set</param>
/// <param name="propertyValue">The collection value</param>
protected virtual void SetCollectionPropertyValue(ResourceInstance targetResource, string propertyName, IEnumerable propertyValue)
{
Type collectionType = this.GetCollectionPropertyType(targetResource.ResourceTypeName, propertyName);
if (collectionType == null)
{
targetResource[propertyName] = propertyValue;
return;
}
// need to go through the enumerable and resolve any tokens
propertyValue = propertyValue.Cast<object>().Select(o => UpdatableToken.ResolveIfToken(o));
object collection;
var enumerableConstructor = collectionType.GetConstructor(new Type[] { typeof(IEnumerable) });
if (enumerableConstructor != null)
{
collection = enumerableConstructor.Invoke(new object[] { propertyValue });
}
else if (collectionType.IsGenericType && collectionType.GetGenericArguments().Count() == 1)
{
var typeArgument = collectionType.GetGenericArguments().Single();
var typedEnumerableConstructor = collectionType.GetConstructor(new Type[] { typeof(IEnumerable<>).MakeGenericType(typeArgument) });
if (typedEnumerableConstructor != null)
{
var typedEnumerable = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(typeArgument).Invoke(null, new object[] { propertyValue });
collection = typedEnumerableConstructor.Invoke(new object[] { typedEnumerable });
}
else
{
var typedAddMethod = collectionType.GetMethod("Add", new Type[] { typeArgument });
ExceptionUtilities.CheckObjectNotNull(typedAddMethod, "Could not find constructor or add method for type: " + collectionType.FullName);
collection = Activator.CreateInstance(collectionType);
foreach (var element in propertyValue)
{
typedAddMethod.Invoke(collection, new object[] { element });
}
}
}
else
{
var addMethod = collectionType.GetMethod("Add");
ExceptionUtilities.CheckObjectNotNull(addMethod, "Could not find constructor or add method for type: " + collectionType.FullName);
collection = Activator.CreateInstance(collectionType);
foreach (var element in propertyValue)
{
addMethod.Invoke(collection, new object[] { element });
}
}
targetResource[propertyName] = collection;
}
/// <summary>
/// Gets the specified resource set. This is for tests to use instead of the public API to avoid caching issues.
/// </summary>
/// <param name="name">The name of the resource set</param>
/// <returns>The given resource set.</returns>
protected ResourceSet GetResourceSet(string name)
{
ExceptionUtilities.CheckArgumentNotNull(name, "name");
return this.metadataHelper.ResourceSets.SingleOrDefault(s => s.Name == name);
}
/// <summary>
/// Creates a metadata helper for this context
/// </summary>
/// <returns>The metadata helper</returns>
protected abstract DictionaryMetadataHelper CreateMetadataHelper();
/// <summary>
/// Initializes data the first time it is called, then does nothing on subsequent calls
/// </summary>
protected abstract void EnsureDataIsInitialized();
/// <summary>
/// Attempts to get a store-generated value for the given property of an entity
/// </summary>
/// <param name="entitySetName">The entity set name</param>
/// <param name="fullTypeName">The full type name of the entity</param>
/// <param name="propertyName">The property name</param>
/// <param name="propertyValue">The generated property value</param>
/// <returns>Whether or not a value could (or should) be generated for the given property</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Type cannot be inferred statically")]
protected virtual bool TryGetStoreGeneratedValue(string entitySetName, string fullTypeName, string propertyName, out object propertyValue)
{
propertyValue = null;
return false;
}
/// <summary>
/// Converts the the property value to the expected property type if it is a declared primitive property.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="propertyValue">The property value.</param>
/// <param name="targetResourceType">Type of the target resource/entity.</param>
/// <returns>The converted property value</returns>
protected virtual object ConvertPropertyValueType(string propertyName, object propertyValue, ResourceType targetResourceType)
{
var resourceProperty = targetResourceType.GetAllPropertiesLazily().SingleOrDefault(p => p.Name == propertyName);
if (resourceProperty == null || !resourceProperty.Kind.HasFlag(ResourcePropertyKind.Primitive))
{
return propertyValue;
}
else
{
if (!resourceProperty.ResourceType.InstanceType.IsAssignableFrom(propertyValue.GetType()))
{
var propertyValueString = propertyValue as string;
if (propertyValueString != null)
{
propertyValue = this.ConvertStringToType(propertyValueString, resourceProperty.ResourceType.InstanceType);
}
else
{
propertyValue = Convert.ChangeType(propertyValue, resourceProperty.ResourceType.InstanceType, CultureInfo.InvariantCulture);
}
}
}
return propertyValue;
}
/// <summary>
/// Initializes the resource set storage with an empty container for each set.
/// </summary>
protected void InitializeResourceSetsStorage()
{
ExceptionUtilities.CheckObjectNotNull(this.ResourceSetsStorage, "Resource sets storage has not been created");
ExceptionUtilities.CheckObjectNotNull(this.metadataHelper, "Metadata helper has not been initialised");
foreach (var set in this.metadataHelper.ResourceSets)
{
if (!this.ResourceSetsStorage.ContainsKey(set.Name))
{
this.ResourceSetsStorage[set.Name] = new List<ResourceInstance>();
}
}
}
private static object GetResourceInternal(IQueryable query)
{
object resource = null;
foreach (object r in query)
{
ExceptionUtilities.Assert(resource == null, "Query returned more than one element. Query was '{0}'", query.Expression);
resource = r;
}
return resource;
}
/// <summary>
/// Returns whether two instances have equivalent keys
/// </summary>
/// <param name="instance1">The first instance to compare</param>
/// <param name="instance2">The second instance to compare</param>
/// <returns>True if the keys are equal, otherwise false</returns>
private bool AreKeysEqual(ResourceInstance instance1, ResourceInstance instance2)
{
ExceptionUtilities.CheckArgumentNotNull(instance1, "instance1");
ExceptionUtilities.CheckArgumentNotNull(instance2, "instance2");
ExceptionUtilities.Assert(instance1.IsEntityType, "Key equality check only supported on entities");
ExceptionUtilities.Assert(instance2.IsEntityType, "Key equality check only supported on entities");
if (instance1.ResourceSetName != instance2.ResourceSetName)
{
return false;
}
var type1 = this.metadataHelper.ResourceTypes.Single(t => t.FullName == instance1.ResourceTypeName);
var type2 = this.metadataHelper.ResourceTypes.Single(t => t.FullName == instance2.ResourceTypeName);
if (!type1.KeyProperties.SequenceEqual(type2.KeyProperties))
{
return false;
}
foreach (var keyProperty in type1.KeyProperties)
{
var value1 = instance1.Where(pair => pair.Key == keyProperty.Name).Select(pair => pair.Value).SingleOrDefault();
var value2 = instance2.Where(pair => pair.Key == keyProperty.Name).Select(pair => pair.Value).SingleOrDefault();
if (!ResourceInstance.ArePropertyValuesEqual(value1, value2))
{
return false;
}
}
return true;
}
private void SetReference_Internal(ResourceInstance targetResource, string propertyName, ResourceInstance propertyValue, bool setBackReference)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName");
var resourceType = this.metadataHelper.ResourceTypes.Single(t => t.FullName == targetResource.ResourceTypeName);
var property = resourceType.GetAllPropertiesLazily().SingleOrDefault(p => p.Name == propertyName);
ExceptionUtilities.CheckObjectNotNull(property, "Could not find resource property '{0}' on resource type '{1}'", propertyName, resourceType.FullName);
ExceptionUtilities.Assert(property.Kind == ResourcePropertyKind.ResourceReference, "SetReference called on property '{0}' with kind '{1}'", propertyName, property.Kind);
object oldValue;
if (!targetResource.TryGetValue(propertyName, out oldValue))
{
oldValue = null;
}
targetResource[propertyName] = propertyValue;
if (setBackReference)
{
if (propertyValue == null)
{
propertyValue = (ResourceInstance)oldValue;
}
if (propertyValue != null)
{
this.SetReverseNavigation(targetResource, propertyValue, propertyName, (propertyValue == null));
}
}
}
private void AddReferenceToCollection_Internal(ResourceInstance targetResource, string propertyName, ResourceInstance resourceToBeAdded, bool addBackReference)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName");
ExceptionUtilities.CheckArgumentNotNull(resourceToBeAdded, "resourceToBeAdded");
var resourceType = this.metadataHelper.ResourceTypes.Single(t => t.FullName == targetResource.ResourceTypeName);
var property = resourceType.GetAllPropertiesLazily().SingleOrDefault(p => p.Name == propertyName);
ExceptionUtilities.CheckObjectNotNull(property, "Could not find resource property '{0}' on resource type '{1}'", propertyName, resourceType.FullName);
ExceptionUtilities.Assert(property.Kind == ResourcePropertyKind.ResourceSetReference, "AddReferenceToCollection called on property '{0}' with kind '{1}'", propertyName, property.Kind);
object propertyValue;
if (!targetResource.TryGetValue(propertyName, out propertyValue))
{
Type collectionType = this.GetCollectionPropertyType(targetResource.ResourceTypeName, propertyName);
ExceptionUtilities.CheckObjectNotNull(collectionType, "Could not get collection type for '{0}.{1}'", targetResource.ResourceTypeName, propertyName);
targetResource[propertyName] = propertyValue = Activator.CreateInstance(collectionType);
}
// Check to see if item already exists
var collection = (IEnumerable)propertyValue;
foreach (var existingEntity in collection)
{
if (this.AreKeysEqual(resourceToBeAdded, (ResourceInstance)existingEntity))
{
// TODO: throw?
return;
}
}
var addMethod = collection.GetType().GetMethod("Add");
ExceptionUtilities.CheckObjectNotNull(addMethod, "Could not find 'Add' method on collection of type: " + collection.GetType());
addMethod.Invoke(collection, new object[] { resourceToBeAdded });
if (addBackReference)
{
this.SetReverseNavigation(targetResource, resourceToBeAdded, propertyName, false);
}
}
private void RemoveReferenceFromCollection_Internal(ResourceInstance targetResource, string propertyName, ResourceInstance resourceToBeRemoved, bool removeBackReference)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName");
ExceptionUtilities.CheckArgumentNotNull(resourceToBeRemoved, "resourceToBeRemoved");
var resourceType = this.metadataHelper.ResourceTypes.Single(t => t.FullName == targetResource.ResourceTypeName);
var property = resourceType.GetAllPropertiesLazily().SingleOrDefault(p => p.Name == propertyName);
ExceptionUtilities.CheckObjectNotNull(property, "Could not find resource property '{0}' on resource type '{1}'", propertyName, resourceType.FullName);
ExceptionUtilities.Assert(property.Kind == ResourcePropertyKind.ResourceSetReference, "RemoveReferenceFromCollection called on property '{0}' with kind '{1}'", propertyName, property.Kind);
var collection = (IEnumerable)targetResource[propertyName];
var removeMethod = collection.GetType().GetMethod("Remove");
ExceptionUtilities.CheckObjectNotNull(removeMethod, "Could not find 'Remove' method on collection of type: " + collection.GetType());
removeMethod.Invoke(collection, new object[] { resourceToBeRemoved });
if (removeBackReference)
{
this.SetReverseNavigation(targetResource, resourceToBeRemoved, propertyName, true);
}
}
/// <summary>
/// For the given association from source to target, perform the appropriate reversed action
/// </summary>
/// <param name="source">the source of the association to reverse</param>
/// <param name="target">the target of the association to reverse</param>
/// <param name="forwardPropertyName">the name of the property from source to target</param>
/// <param name="remove">whether or not to remove the reversed association</param>
private void SetReverseNavigation(ResourceInstance source, ResourceInstance target, string forwardPropertyName, bool remove)
{
ResourceType targetType;
ResourceType sourceType = this.GetResourceTypeInternal(source);
if (target == null)
{
targetType = sourceType.GetAllPropertiesLazily().Single(p => p.Name == forwardPropertyName).ResourceType;
}
else
{
targetType = this.GetResourceTypeInternal(target);
}
ResourceProperty forwardProperty = sourceType.GetAllPropertiesLazily().SingleOrDefault(p => p.Name == forwardPropertyName);
if (forwardProperty != null && forwardProperty.CustomState != null)
{
// because sourceType could match targetType, we need to make sure we filter out the target property
ResourceProperty reverseProperty = targetType.GetAllPropertiesLazily()
.SingleOrDefault(
p =>
p != forwardProperty && p.CustomState != null &&
(string)p.CustomState == (string)forwardProperty.CustomState);
if (reverseProperty != null)
{
bool reference = (reverseProperty.Kind & ResourcePropertyKind.ResourceReference) != 0;
if (remove)
{
if (reference)
{
this.SetReference_Internal(target, reverseProperty.Name, null, false);
}
else
{
this.RemoveReferenceFromCollection_Internal(target, reverseProperty.Name, source, false);
}
}
else
{
if (reference)
{
this.SetReference_Internal(target, reverseProperty.Name, source, false);
}
else
{
this.AddReferenceToCollection_Internal(target, reverseProperty.Name, source, false);
}
}
}
}
}
/// <summary>
/// The IUpdatable was leaving around left over references after it a resource was being deleted. This will ensure the reference is removed from collections
/// and reference properties
/// </summary>
/// <param name="targetResource">TargetResource To remove</param>
private void DeleteAllReferences(ResourceInstance targetResource)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ResourceSet targetResourceSet = this.GetResourceSet(targetResource.ResourceSetName);
ExceptionUtilities.CheckObjectNotNull(targetResourceSet, "Resource set could not be found");
List<ResourceSet> resourceSetsToCheck = this.metadataHelper.ResourceAssociationSets.Where(ras => ras.End1.ResourceSet == targetResourceSet).Select(ras2 => ras2.End2.ResourceSet).ToList();
resourceSetsToCheck.AddRange(this.metadataHelper.ResourceAssociationSets.Where(ras => ras.End2.ResourceSet == targetResourceSet).Select(ras2 => ras2.End1.ResourceSet).ToList());
resourceSetsToCheck = resourceSetsToCheck.Distinct().ToList();
foreach (var resourceSet in resourceSetsToCheck)
{
IList<ResourceInstance> entitySetList = this.ResourceSetsStorage[resourceSet.Name];
foreach (var currentEntityInstance in entitySetList)
{
ResourceType currentEntityInstanceType = this.GetResourceTypeInternal(currentEntityInstance);
foreach (var referenceProperty in currentEntityInstanceType.GetAllPropertiesLazily().Where(p => p.Kind == ResourcePropertyKind.ResourceReference))
{
if (this.metadataHelper.IsKindOf(currentEntityInstanceType, currentEntityInstanceType))
{
this.SetEntityReferenceToNullOnTargetResourceMatch(targetResource, referenceProperty, currentEntityInstance);
}
}
foreach (var collectionProperty in currentEntityInstanceType.GetAllPropertiesLazily().Where(p => p.Kind == ResourcePropertyKind.ResourceSetReference))
{
this.RemoveResourceFromCollectionOnTargetResourceMatch(targetResource, collectionProperty, currentEntityInstance);
}
}
}
}
/// <summary>
/// Method is done as a cleanup, when a resource is deleted, this method will remove the deleted object from an entityInstance collection property
/// </summary>
/// <param name="targetResource">Resource to look for in the currentEntityInstance</param>
/// <param name="property">The collection property to remove from</param>
/// <param name="currentEntityInstance">currentEntityInstance that may contain the targetResource</param>
private void RemoveResourceFromCollectionOnTargetResourceMatch(ResourceInstance targetResource, ResourceProperty property, ResourceInstance currentEntityInstance)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(property, "property");
ExceptionUtilities.CheckArgumentNotNull(currentEntityInstance, "currentEntityInstance");
ExceptionUtilities.Assert(property.Kind == ResourcePropertyKind.ResourceSetReference, "Should only be called with reference properties");
string propertyName = property.Name;
object propertyValue;
if (!currentEntityInstance.TryGetValue(propertyName, out propertyValue))
{
return;
}
IEnumerable childCollectionObject = propertyValue as IEnumerable;
ExceptionUtilities.CheckObjectNotNull(childCollectionObject, "Value of '{0}.{1}' was null or not a collection", currentEntityInstance.ResourceTypeName, propertyName);
var removeMethod = childCollectionObject.GetType().GetMethod("Remove");
ExceptionUtilities.CheckObjectNotNull(removeMethod, "Could not find remove method for collection property '{0}.{1}'", currentEntityInstance.ResourceTypeName, propertyName);
if (childCollectionObject.Cast<object>().Any(o => o == targetResource))
{
this.pendingChanges.Add(() => removeMethod.Invoke(childCollectionObject, new object[] { targetResource }));
}
}
/// <summary>
/// Method is done as a cleanup, when a resource is deleted, this method will remove the deleted object from an entityInstance reference property
/// </summary>
/// <param name="targetResource">Resource to look for in the currentEntityInstance</param>
/// <param name="property">Reference property to look in on the currentEntityInstance</param>
/// <param name="currentEntityInstance">currentEntityInstance that may contain the targetResource</param>
private void SetEntityReferenceToNullOnTargetResourceMatch(ResourceInstance targetResource, ResourceProperty property, ResourceInstance currentEntityInstance)
{
ExceptionUtilities.CheckArgumentNotNull(targetResource, "targetResource");
ExceptionUtilities.CheckArgumentNotNull(property, "property");
ExceptionUtilities.CheckArgumentNotNull(currentEntityInstance, "currentEntityInstance");
ExceptionUtilities.Assert(property.Kind == ResourcePropertyKind.ResourceReference, "Should only be called with reference properties");
string propertyName = property.Name;
object propertyValue;
if (currentEntityInstance.TryGetValue(propertyName, out propertyValue) && propertyValue == targetResource)
{
this.pendingChanges.Add(() => currentEntityInstance[propertyName] = null);
}
}
private void SetValue(ResourceInstance instance, string propertyName, object propertyValue)
{
var resourceType = this.metadataHelper.ResourceTypes.Single(t => t.FullName == instance.ResourceTypeName);
ResourceProperty property = resourceType.GetAllPropertiesLazily().SingleOrDefault(p => p.Name == propertyName);
bool isMultiValue = false;
if (property != null)
{
ExceptionUtilities.Assert(!property.Kind.HasFlag(ResourcePropertyKind.Stream), "SetValue called on stream property '{0}'", propertyName);
isMultiValue = property.Kind.HasFlag(ResourcePropertyKind.Collection);
}
if (isMultiValue)
{
var enumerable = propertyValue as IEnumerable;
ExceptionUtilities.CheckObjectNotNull(enumerable, "Collection property value was not an enumerable");
this.pendingChanges.Add(() => this.SetCollectionPropertyValue(instance, propertyName, enumerable));
}
else
{
this.pendingChanges.Add(() => instance[propertyName] = UpdatableToken.ResolveIfToken(propertyValue));
}
}
private void InitializeCollectionProperties(ResourceType type, ResourceInstance instance, UpdatableToken token, Func<ResourceProperty, bool> filter)
{
foreach (ResourceProperty property in type.GetAllPropertiesLazily().Where(filter))
{
string propertyName = property.Name;
Type collectionType = this.GetCollectionPropertyType(type.FullName, propertyName);
if (collectionType != null)
{
var newCollection = Activator.CreateInstance(collectionType);
token.PendingPropertyUpdates[propertyName] = newCollection;
this.pendingChanges.Add(() => instance[propertyName] = newCollection);
}
}
}
/// <summary>
/// Gets the resource type for the given instance
/// </summary>
/// <param name="resource">The instance to get the type for</param>
/// <returns>The type of the resource</returns>
private ResourceType GetResourceTypeInternal(object resource)
{
ExceptionUtilities.Assert(!(resource is UpdatableToken), "Should not be called with a token");
var instance = resource as ResourceInstance;
if (instance == null)
{
return null;
}
return this.metadataHelper.ResourceTypes.Single(t => t.FullName == instance.ResourceTypeName);
}
/// <summary>
/// Returns the types derived from the given type
/// </summary>
/// <param name="resourceType">The given type</param>
/// <returns>The type's derived types</returns>
private IEnumerable<ResourceType> GetDerivedTypesInternal(ResourceType resourceType)
{
var children = this.metadataHelper.ResourceTypes.Where(t => t.BaseType == resourceType);
return children.Union(children.SelectMany(t => this.GetDerivedTypesInternal(t)));
}
/// <summary>
/// Ensures that the product caches resource types based on their names.
/// </summary>
/// <param name="type">The resource type which may or may not be cached.</param>
/// <param name="throwIfAlreadyCached">Whether or not to throw if the resource type is already cached.</param>
/// <param name="addToCache">Whether or not to add the type to the cache. Certain code paths do not cache all the resource type they could.</param>
/// <returns>The same resource type if not cached, or a copy if it was.</returns>
private ResourceType EnforceMetadataCache(ResourceType type, bool throwIfAlreadyCached, bool addToCache)
{
if (type == null)
{
return null;
}
if (!ProviderImplementationSettings.Current.EnforceMetadataCaching)
{
return type;
}
if (type.ResourceTypeKind != ResourceTypeKind.ComplexType && type.ResourceTypeKind != ResourceTypeKind.EntityType)
{
return type;
}
bool cached;
if (addToCache)
{
cached = !this.resourceTypeCache.Add(type.FullName);
}
else
{
cached = this.resourceTypeCache.Contains(type.FullName);
}
if (!cached)
{
return type;
}
ExceptionUtilities.Assert(!throwIfAlreadyCached, "Resource type '{0}' was resolved more than once", type.Name);
var copy = new ResourceType(typeof(object), type.ResourceTypeKind, null, type.Namespace, type.Name, !type.IsAbstract);
copy.SetReadOnly();
return copy;
}
/// <summary>
/// Ensures that the product caches resource sets based on their names.
/// </summary>
/// <param name="resourceSet">The resource set which may or may not be cached.</param>
/// <param name="throwIfAlreadyCached">Whether or not to throw if the resource set is already cached.</param>
/// <param name="createDummyTypeIfCached">Whether or not to return a dummy type when copying the set for already-cached sets. In some places the product does not correctly resolve the copy to the original.</param>
/// <param name="addToCache">Whether or not to add the set to the cache. Certain code paths do not cache all the resource sets they could.</param>
/// <returns>The same resource set if not cached, or a copy if it was.</returns>
private ResourceSet EnforceMetadataCache(ResourceSet resourceSet, bool throwIfAlreadyCached, bool createDummyTypeIfCached, bool addToCache)
{
if (!ProviderImplementationSettings.Current.EnforceMetadataCaching)
{
return resourceSet;
}
// the ResourceType of a ResourceSet should be cached
ResourceType type;
if (createDummyTypeIfCached)
{
type = this.EnforceMetadataCache(resourceSet.ResourceType, false, true);
}
else
{
type = resourceSet.ResourceType;
}
bool cached;
if (addToCache)
{
cached = !this.resourceSetCache.Add(resourceSet.Name);
}
else
{
cached = this.resourceSetCache.Contains(resourceSet.Name);
}
if (!cached)
{
return resourceSet;
}
ExceptionUtilities.Assert(!throwIfAlreadyCached, "Resource set '{0}' was resolved more than once", resourceSet.Name);
var copy = new ResourceSet(resourceSet.Name, type);
copy.SetReadOnly();
return copy;
}
/// <summary>
/// Ensures that the product caches service operations based on their names.
/// </summary>
/// <param name="operation">The operation which may or may-not be cached.</param>
/// <param name="throwIfAlreadyCached">Whether or not to throw if the operation is already cached.</param>
/// <returns>The same operation if not cached, or a copy if it was.</returns>
private ServiceOperation EnforceMetadataCache(ServiceOperation operation, bool throwIfAlreadyCached)
{
if (!ProviderImplementationSettings.Current.EnforceMetadataCaching)
{
return operation;
}
ResourceType resultType = null;
ResourceSet resultSet = null;
if (operation.ResourceSet != null)
{
// The ResourceSet of a service operation should be cached, but it isnt
resultSet = this.EnforceMetadataCache(operation.ResourceSet, false, true, false);
resultType = resultSet.ResourceType;
}
else
{
// The ResultType of a service operation should be cached, but it isn't
resultType = this.EnforceMetadataCache(operation.ResultType, false, false);
}
if (this.serviceOperationCache.Add(operation.Name))
{
return operation;
}
ExceptionUtilities.Assert(!throwIfAlreadyCached, "Service operation '{0}' was resolved more than once", operation.Name);
var copy = new ServiceOperation(operation.Name, operation.ResultKind, resultType, resultSet, operation.Method, Enumerable.Empty<ServiceOperationParameter>());
copy.SetReadOnly();
return copy;
}
/// <summary>
/// Ensures that the product caches association sets based on the set/type/property name.
/// </summary>
/// <param name="associationSet">The association set which may or may-not be cached.</param>
/// <param name="resourceSet">The resource set used to find the association set.</param>
/// <param name="resourceType">Type of the resource used to find the association set.</param>
/// <param name="resourceProperty">The resource property used to find the association set.</param>
/// <param name="throwIfAlreadyCached">Whether or not to throw if the association set is already cached.</param>
/// <returns>The same association set if not cached, or a copy if it was.</returns>
private ResourceAssociationSet EnforceMetadataCache(ResourceAssociationSet associationSet, ResourceSet resourceSet, ResourceType resourceType, ResourceProperty resourceProperty, bool throwIfAlreadyCached)
{
if (!ProviderImplementationSettings.Current.EnforceMetadataCaching)
{
return associationSet;
}
var cacheKey = resourceSet.Name + "_" + resourceType.Name + "_" + (resourceProperty == null ? null : resourceProperty.Name);
var end1 = associationSet.End1;
var resourceSet1 = this.EnforceMetadataCache(end1.ResourceSet, false, true, true);
var resourceType1 = this.EnforceMetadataCache(end1.ResourceType, false, true);
var end2 = associationSet.End2;
var resourceSet2 = this.EnforceMetadataCache(end2.ResourceSet, false, true, true);
var resourceType2 = this.EnforceMetadataCache(end2.ResourceType, false, true);
if (this.resourceAssociationSetCache.Add(cacheKey))
{
return associationSet;
}
ExceptionUtilities.Assert(!throwIfAlreadyCached, "Association set with cache key '{0}' was resolved more than once", cacheKey);
return new ResourceAssociationSet(
associationSet.Name,
new ResourceAssociationSetEnd(resourceSet1, resourceType1, null),
new ResourceAssociationSetEnd(resourceSet2, resourceType2, null));
}
private object ConvertStringToType(string propertyValue, Type type)
{
// Unwrap if Nullable<T>
var innertype = Nullable.GetUnderlyingType(type);
if (innertype != null)
{
type = innertype;
}
if (type == typeof(DateTimeOffset))
{
return XmlConvert.ToDateTimeOffset(propertyValue);
}
else if (type == typeof(TimeSpan))
{
return XmlConvert.ToTimeSpan(propertyValue);
}
else if (type == typeof(Guid))
{
return Guid.Parse(propertyValue);
}
else if (type == typeof(byte[]))
{
return Convert.FromBase64String(propertyValue);
}
else if (type == typeof(long))
{
return long.Parse(propertyValue, CultureInfo.InvariantCulture);
}
else if (type == typeof(decimal))
{
return decimal.Parse(propertyValue, CultureInfo.InvariantCulture);
}
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Property value '{0}' could not be converted to type '{1}'", propertyValue, type.FullName));
}
}
}
| 50.800119
| 253
| 0.612596
|
6cb696d84cb6056496bff8ca617c4452d5d7558b
| 1,304
|
lua
|
Lua
|
spec/internal/socket_spec.lua
|
LuaDist-testing/reql
|
15dd2c71a4749385fd0a1732b68fe4431d8398a5
|
[
"Apache-2.0"
] | 2
|
2019-07-19T06:09:53.000Z
|
2021-09-10T23:01:12.000Z
|
spec/internal/socket_spec.lua
|
LuaDist-testing/reql
|
15dd2c71a4749385fd0a1732b68fe4431d8398a5
|
[
"Apache-2.0"
] | 1
|
2018-07-13T19:18:01.000Z
|
2018-07-13T19:18:01.000Z
|
spec/internal/socket_spec.lua
|
LuaDist-testing/reql
|
15dd2c71a4749385fd0a1732b68fe4431d8398a5
|
[
"Apache-2.0"
] | 2
|
2021-09-10T23:01:24.000Z
|
2021-12-29T00:16:40.000Z
|
local ltn12 = require('ltn12')
local function reql_error_formatter(err)
if type(err) ~= 'table' then return end
if err.ReQLError then
return err.message()
end
end
describe('socket', function()
local r, socket
setup(function()
assert:add_formatter(reql_error_formatter)
r = require('rethinkdb')
socket = require('rethinkdb.internal.socket')
end)
teardown(function()
socket = nil
r = nil
assert:remove_formatter(reql_error_formatter)
end)
it('closes repeatedly', function()
local client = assert.is_table(socket(r, 'localhost', 28015, nil, 1))
client.close()
client.close()
end)
it('connects', function()
local client = assert.is_table(socket(r, 'localhost', 28015, nil, 1))
finally(client.close)
assert.is_truthy(ltn12.pump.all(ltn12.source.string'\0\0\0\0\0\0\0\0\0\0\0\0', client.sink))
local sink, buffer = ltn12.sink.table()
local expected = table.concat{
'ERROR: Received an unsupported protocol version. This port is for ',
'RethinkDB queries. Does your client driver version not match the ',
'server?\n\0',
}
assert.is_truthy(ltn12.pump.all(client.source(string.len(expected)), sink))
local message = table.concat(buffer)
assert.are_equal(expected, message)
end)
end)
| 25.076923
| 96
| 0.680982
|
2c6cc68367f41d0284cd7f981f6da2ea7a251162
| 942
|
cpp
|
C++
|
Matrix/Median in a row-wise Sortedd Matrix.cpp
|
vermagaurav8/GeeksforGeeks
|
f54d3297337981b5fc5054272cfa6788011c2c5a
|
[
"Apache-2.0"
] | 9
|
2020-10-01T09:29:10.000Z
|
2022-02-12T04:58:41.000Z
|
Matrix/Median in a row-wise Sortedd Matrix.cpp
|
vermagaurav8/GeeksforGeeks
|
f54d3297337981b5fc5054272cfa6788011c2c5a
|
[
"Apache-2.0"
] | 6
|
2020-10-03T16:08:58.000Z
|
2020-10-14T12:06:25.000Z
|
Matrix/Median in a row-wise Sortedd Matrix.cpp
|
vermagaurav8/GeeksforGeeks
|
f54d3297337981b5fc5054272cfa6788011c2c5a
|
[
"Apache-2.0"
] | 17
|
2020-10-01T09:17:27.000Z
|
2021-06-18T09:36:31.000Z
|
class Solution{
public:
int median(vector<vector<int>> &matrix, int r, int c){
// code here
int min = INT_MAX, max = INT_MIN;
// Maximum and minimum element from the array
for(int i = 0;i<r;++i) {
if(matrix[i][0] < min) {
min = matrix[i][0];
}
if(matrix[i][c-1] > max) {
max = matrix[i][c-1];
}
}
int desired = (r*c +1)/2;
while(min<max) {
int mid = min + (max - min) /2;
int place = 0;
for(int i = 0 ;i<r;i++) {
place += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
}
if(place<desired) {
min = mid +1;
}
else{
max = mid;
}
}
return min;
}
};
| 25.459459
| 98
| 0.359873
|
43b03c949a237141d2cf056e90edbd89fd872800
| 1,010
|
ps1
|
PowerShell
|
Octopus.Client/PowerShell/Channels/CreateChannel.ps1
|
gdesai1234/OctopusDeploy-Api
|
c0b70fa5d5fb39b7ba5d0b75d90e0dbfc25e57b2
|
[
"Apache-2.0"
] | 199
|
2015-01-16T12:53:36.000Z
|
2022-03-22T08:18:16.000Z
|
Octopus.Client/PowerShell/Channels/CreateChannel.ps1
|
gdesai1234/OctopusDeploy-Api
|
c0b70fa5d5fb39b7ba5d0b75d90e0dbfc25e57b2
|
[
"Apache-2.0"
] | 66
|
2015-01-27T06:40:25.000Z
|
2021-12-17T13:57:42.000Z
|
Octopus.Client/PowerShell/Channels/CreateChannel.ps1
|
gdesai1234/OctopusDeploy-Api
|
c0b70fa5d5fb39b7ba5d0b75d90e0dbfc25e57b2
|
[
"Apache-2.0"
] | 139
|
2015-09-16T17:49:09.000Z
|
2022-03-10T18:16:07.000Z
|
# You can get this dll from your Octopus Server/Tentacle installation directory or from
# https://www.nuget.org/packages/Octopus.Client/
# Load Octopus Client assembly
Add-Type -Path 'path\to\Octopus.Client.dll'
$octopusURL = "https://YourUrl"
$octopusAPIKey = "API-YourAPIKey"
$spaceName = "Default"
$projectName = "MyProject"
$channelName = "NewChannel"
$endpoint = New-Object Octopus.Client.OctopusServerEndpoint($octopusURL, $octopusAPIKey)
$repository = New-Object Octopus.Client.OctopusRepository($endpoint)
$client = New-Object Octopus.Client.OctopusClient($endpoint)
# Get space
$space = $repository.Spaces.FindByName($spaceName)
$repositoryForSpace = $client.ForSpace($space)
# Get project
$project = $repositoryForSpace.Projects.FindByName($projectName)
# Createw new channel object
$channel = New-Object Octopus.Client.Model.ChannelResource
$channel.Name = $channelName
$channel.ProjectId = $project.Id
$channel.SpaceId = $space.Id
# Add channel
$repositoryForSpace.Channels.Create($channel)
| 32.580645
| 88
| 0.782178
|
be122609d7a8691e68f5c9916dc9c72b521c30bd
| 671
|
ts
|
TypeScript
|
packages/asset-gallery/tests/data.ts
|
arvinxx/components
|
81ec52074d191df7d36c1db335dd5f8055da8051
|
[
"MIT"
] | 8
|
2021-03-19T13:27:18.000Z
|
2021-12-21T07:34:20.000Z
|
packages/asset-gallery/tests/data.ts
|
arvinxx/components
|
81ec52074d191df7d36c1db335dd5f8055da8051
|
[
"MIT"
] | 865
|
2021-02-19T08:12:46.000Z
|
2022-03-28T16:33:30.000Z
|
packages/asset-gallery/tests/data.ts
|
arvinxx/components
|
81ec52074d191df7d36c1db335dd5f8055da8051
|
[
"MIT"
] | null | null | null |
import type { AssetList } from '@arvinxu/asset-gallery';
export const images: AssetList = [
{
title: '渐变色 Logo',
description: '渐变色',
url: 'https://gw.alipayobjects.com/zos/antfincdn/LFmaI3%26OJh/logo.svg',
},
{
title: '白色 Logo',
description: '暗色背景下使用',
dark: true,
padding: 12,
darkBackground: 'black',
url: 'https://gw.alipayobjects.com/zos/antfincdn/5qY87lPw9U/white-logo.svg',
},
];
export const pngYML = `
- 标题: 渐变色 Logo
描述: 渐变色
链接: https://gw.alipayobjects.com/zos/antfincdn/OuMB9liYZV/tupian%2525201.png
- 标题: 黑色 Logo
描述: 亮色背景下使用
链接: https://gw.alipayobjects.com/zos/antfincdn/5vmPNr6Qqz/tupian%2525202.png
`;
| 23.964286
| 80
| 0.669151
|
ef46a7aca5dde6c1e036f59cab964333acbd6783
| 883
|
h
|
C
|
tensorflow/core/platform/regexp.h
|
vsilyaev/tensorflow
|
f41959ccb2d9d4c722fe8fc3351401d53bcf4900
|
[
"Apache-2.0"
] | 4
|
2021-06-11T09:43:32.000Z
|
2021-11-17T11:15:52.000Z
|
tensorflow/core/platform/regexp.h
|
usepavlov/tensorflow
|
21fac39c471dede0e4ae62dd60e2b0b85db48415
|
[
"Apache-2.0"
] | null | null | null |
tensorflow/core/platform/regexp.h
|
usepavlov/tensorflow
|
21fac39c471dede0e4ae62dd60e2b0b85db48415
|
[
"Apache-2.0"
] | 2
|
2015-11-13T21:11:49.000Z
|
2015-11-29T04:13:49.000Z
|
#ifndef TENSORFLOW_PLATFORM_REGEXP_H_
#define TENSORFLOW_PLATFORM_REGEXP_H_
#include "tensorflow/core/platform/port.h"
#if defined(PLATFORM_GOOGLE) || defined(PLATFORM_GOOGLE_ANDROID)
#include "third_party/re2/re2.h"
namespace tensorflow {
typedef ::StringPiece RegexpStringPiece;
} // namespace tensorflow
#else
#include "external/re2/re2/re2.h"
namespace tensorflow {
typedef re2::StringPiece RegexpStringPiece;
} // namespace tensorflow
#endif
namespace tensorflow {
// Conversion to/from the appropriate StringPiece type for using in RE2
inline RegexpStringPiece ToRegexpStringPiece(tensorflow::StringPiece sp) {
return RegexpStringPiece(sp.data(), sp.size());
}
inline tensorflow::StringPiece FromRegexpStringPiece(RegexpStringPiece sp) {
return tensorflow::StringPiece(sp.data(), sp.size());
}
} // namespace tensorflow
#endif // TENSORFLOW_PLATFORM_REGEXP_H_
| 25.970588
| 76
| 0.795017
|
c9f2ac7d3293c47c531b5713322ff1b4c8e35bae
| 447
|
ts
|
TypeScript
|
src/collectionUtils/MemberVariableByNamePredicate.ts
|
MeasureAuthoringTool/model-info-parser
|
e768780ff0d95f085f6b0b4cac6dbe4175758de1
|
[
"CC0-1.0"
] | 1
|
2020-07-30T21:16:56.000Z
|
2020-07-30T21:16:56.000Z
|
src/collectionUtils/MemberVariableByNamePredicate.ts
|
MeasureAuthoringTool/model-info-parser
|
e768780ff0d95f085f6b0b4cac6dbe4175758de1
|
[
"CC0-1.0"
] | 220
|
2020-05-28T02:13:07.000Z
|
2022-03-30T17:56:29.000Z
|
src/collectionUtils/MemberVariableByNamePredicate.ts
|
MeasureAuthoringTool/model-info-parser
|
e768780ff0d95f085f6b0b4cac6dbe4175758de1
|
[
"CC0-1.0"
] | 1
|
2020-05-27T21:39:41.000Z
|
2020-05-27T21:39:41.000Z
|
import Predicate from "./core/Predicate";
import MemberVariable from "../model/dataTypes/MemberVariable";
/**
* This predicate compares a MemberVariable's name with a specified value
*/
export default class MemberVariableByNamePredicate extends Predicate<
MemberVariable
> {
constructor(public variableName: string) {
super();
}
evaluate(input: MemberVariable): boolean {
return input.variableName === this.variableName;
}
}
| 24.833333
| 73
| 0.747204
|
3f982bd978d1d0d36b8fd8fbe9da88236bfa2870
| 110
|
php
|
PHP
|
hphp/hack/test/lint/unsafe_cast_lower_bound2.php
|
donsbot/hhvm
|
ac98a590f75c569e1249b6c1145c7512c7bd240e
|
[
"PHP-3.01",
"Zend-2.0"
] | 1
|
2022-03-11T02:25:37.000Z
|
2022-03-11T02:25:37.000Z
|
hphp/hack/test/lint/unsafe_cast_lower_bound2.php
|
donsbot/hhvm
|
ac98a590f75c569e1249b6c1145c7512c7bd240e
|
[
"PHP-3.01",
"Zend-2.0"
] | 3
|
2022-02-17T04:00:03.000Z
|
2022-03-24T03:45:33.000Z
|
hphp/hack/test/lint/unsafe_cast_lower_bound2.php
|
donsbot/hhvm
|
ac98a590f75c569e1249b6c1145c7512c7bd240e
|
[
"PHP-3.01",
"Zend-2.0"
] | 1
|
2022-02-19T09:29:50.000Z
|
2022-02-19T09:29:50.000Z
|
<?hh
function unsafe_cast_lower_bound2(string $m): void {
\HH\FIXME\UNSAFE_CAST<mixed, int>($m); // Lint
}
| 18.333333
| 52
| 0.690909
|
14aaa6b96c132354bc5fe7ccc5cc9e8c445e9f5d
| 3,616
|
tsx
|
TypeScript
|
src/icons/Capsule.tsx
|
cabralRodrigo/react-native-swm-icon-pack
|
1870054648345251a84054eccda083f708e202be
|
[
"MIT"
] | null | null | null |
src/icons/Capsule.tsx
|
cabralRodrigo/react-native-swm-icon-pack
|
1870054648345251a84054eccda083f708e202be
|
[
"MIT"
] | null | null | null |
src/icons/Capsule.tsx
|
cabralRodrigo/react-native-swm-icon-pack
|
1870054648345251a84054eccda083f708e202be
|
[
"MIT"
] | null | null | null |
import React, { VFC } from 'react';
import { Color, G, Path } from 'react-native-svg';
import { createIcon } from '../helpers';
type BrokenProps = { color: Color, strokeWidth: number, };
type CurvedProps = { color: Color, strokeWidth: number, };
type DuotoneProps = { color: Color, strokeWidth: number, };
type OutlineProps = { color: Color, strokeWidth: number, };
type CapsuleProps =
{ variant: 'broken' } & BrokenProps |
{ variant: 'curved' } & CurvedProps |
{ variant: 'duotone' } & DuotoneProps |
{ variant: 'outline' } & OutlineProps;
const Broken: VFC<BrokenProps> = (props) => (
<G>
<Path d="M8.42892 8.57104L12.8579 13" stroke={props.color} strokeWidth={props.strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<Path d="M11.9645 5.03551C13.9171 3.08289 17.0829 3.08289 19.0356 5.03551C20.9882 6.98813 20.9882 10.154 19.0356 12.1066L15.5 15.6421L11.9645 19.1776C10.0119 21.1303 6.84604 21.1303 4.89342 19.1776C2.9408 17.225 2.9408 14.0592 4.89342 12.1066L8.42896 8.57104L9.5 7.5" stroke={props.color} strokeWidth={props.strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
</G>
);
const Curved: VFC<CurvedProps> = (props) => (
<G>
<Path d="M8.42896 8.57104L15.5 15.6421" stroke={props.color} strokeWidth={props.strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<Path d="M8.42896 8.57104L4.89342 12.1066C2.9408 14.0592 2.9408 17.225 4.89342 19.1776C6.84604 21.1303 10.0119 21.1303 11.9645 19.1776L15.5 15.6421L19.0356 12.1066C20.9882 10.154 20.9882 6.98813 19.0356 5.03551C17.0829 3.08289 13.9171 3.08289 11.9645 5.03551L8.42896 8.57104Z" stroke={props.color} strokeWidth={props.strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
</G>
);
const Duotone: VFC<DuotoneProps> = (props) => (
<G>
<Path opacity="0.15" d="M8.42896 8.57104L4.89342 12.1066C2.9408 14.0592 2.9408 17.225 4.89342 19.1776C6.84604 21.1303 10.0119 21.1303 11.9645 19.1776L15.5 15.6421L8.42896 8.57104Z" fill={props.color} />
<Path d="M8.42896 8.57104L15.5 15.6421" stroke={props.color} strokeWidth={props.strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<Path d="M8.42896 8.57104L4.89342 12.1066C2.9408 14.0592 2.9408 17.225 4.89342 19.1776C6.84604 21.1303 10.0119 21.1303 11.9645 19.1776L15.5 15.6421L19.0356 12.1066C20.9882 10.154 20.9882 6.98813 19.0356 5.03551C17.0829 3.08289 13.9171 3.08289 11.9645 5.03551L8.42896 8.57104Z" stroke={props.color} strokeWidth={props.strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
</G>
);
const Outline: VFC<OutlineProps> = (props) => (
<G>
<Path d="M8.42896 8.57104L15.5 15.6421" stroke={props.color} strokeWidth={props.strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
<Path d="M8.42896 8.57104L4.89342 12.1066C2.9408 14.0592 2.9408 17.225 4.89342 19.1776C6.84604 21.1303 10.0119 21.1303 11.9645 19.1776L15.5 15.6421L19.0356 12.1066C20.9882 10.154 20.9882 6.98813 19.0356 5.03551C17.0829 3.08289 13.9171 3.08289 11.9645 5.03551L8.42896 8.57104Z" stroke={props.color} strokeWidth={props.strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
</G>
);
const Capsule: VFC<CapsuleProps> = (props) => {
switch (props.variant) {
case 'broken':
return <Broken {...props} />;
case 'curved':
return <Curved {...props} />;
case 'duotone':
return <Duotone {...props} />;
case 'outline':
return <Outline {...props} />;
}
};
export default createIcon(Capsule);
| 62.344828
| 386
| 0.673119
|
c6991a801df0308c7227211edcd7e628100ef924
| 284
|
py
|
Python
|
ngram_bangla.py
|
mahirsust/RAKE-BengaliKeywordExtraction
|
82ffd2b12a868823d7002660fcda84c5e904c974
|
[
"MIT"
] | 3
|
2018-03-28T05:37:06.000Z
|
2021-04-06T17:54:20.000Z
|
ngram_bangla.py
|
mahirsust/RAKE-BengaliKeywordExtraction
|
82ffd2b12a868823d7002660fcda84c5e904c974
|
[
"MIT"
] | 1
|
2018-04-16T17:13:40.000Z
|
2018-04-16T17:13:40.000Z
|
ngram_bangla.py
|
mahirsust/RAKE-BengaliKeywordExtraction
|
82ffd2b12a868823d7002660fcda84c5e904c974
|
[
"MIT"
] | 2
|
2018-04-06T20:32:36.000Z
|
2020-07-11T14:54:54.000Z
|
from nltk import ngrams
sample_file = open('H:/xampp/htdocs/RAKE-BengaliKeywordExtraction/oneline_bangla.txt', 'r',encoding='utf8')
text = sample_file.read()
n = 3
sixgrams = ngrams(text.split(), n)
for grams in sixgrams:
print(grams, file=open("output2.txt", "a", encoding='utf8'))
| 40.571429
| 107
| 0.735915
|
cdbdfd51f83a70cd5704d7732ee89745267ce81a
| 3,981
|
cs
|
C#
|
src/BungieNetPlatform.Test/BungieNetPlatform.Model/DestinyDestinyActivityTests.cs
|
xlxCLUxlx/BungieNetPlatform
|
9b64489388ee852fe28c54b6c4f3ae095d517f61
|
[
"MIT"
] | 3
|
2019-02-14T16:51:48.000Z
|
2020-08-29T21:55:07.000Z
|
src/BungieNetPlatform.Test/BungieNetPlatform.Model/DestinyDestinyActivityTests.cs
|
xlxCLUxlx/BungieNetPlatform
|
9b64489388ee852fe28c54b6c4f3ae095d517f61
|
[
"MIT"
] | 2
|
2018-05-04T17:47:03.000Z
|
2018-09-17T19:39:37.000Z
|
src/BungieNetPlatform.Test/BungieNetPlatform.Model/DestinyDestinyActivityTests.cs
|
xlxCLUxlx/BungieNetPlatform
|
9b64489388ee852fe28c54b6c4f3ae095d517f61
|
[
"MIT"
] | 3
|
2018-05-04T17:10:18.000Z
|
2020-08-29T22:47:32.000Z
|
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.0.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using BungieNetPlatform.BungieNetPlatform.Api;
using BungieNetPlatform.BungieNetPlatform.Model;
using BungieNetPlatform.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace BungieNetPlatform.Test
{
/// <summary>
/// Class for testing DestinyDestinyActivity
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class DestinyDestinyActivityTests
{
// TODO uncomment below to declare an instance variable for DestinyDestinyActivity
//private DestinyDestinyActivity instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of DestinyDestinyActivity
//instance = new DestinyDestinyActivity();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of DestinyDestinyActivity
/// </summary>
[Test]
public void DestinyDestinyActivityInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" DestinyDestinyActivity
//Assert.IsInstanceOfType<DestinyDestinyActivity> (instance, "variable 'instance' is a DestinyDestinyActivity");
}
/// <summary>
/// Test the property 'ActivityHash'
/// </summary>
[Test]
public void ActivityHashTest()
{
// TODO unit test for the property 'ActivityHash'
}
/// <summary>
/// Test the property 'IsNew'
/// </summary>
[Test]
public void IsNewTest()
{
// TODO unit test for the property 'IsNew'
}
/// <summary>
/// Test the property 'CanLead'
/// </summary>
[Test]
public void CanLeadTest()
{
// TODO unit test for the property 'CanLead'
}
/// <summary>
/// Test the property 'CanJoin'
/// </summary>
[Test]
public void CanJoinTest()
{
// TODO unit test for the property 'CanJoin'
}
/// <summary>
/// Test the property 'IsCompleted'
/// </summary>
[Test]
public void IsCompletedTest()
{
// TODO unit test for the property 'IsCompleted'
}
/// <summary>
/// Test the property 'IsVisible'
/// </summary>
[Test]
public void IsVisibleTest()
{
// TODO unit test for the property 'IsVisible'
}
/// <summary>
/// Test the property 'DisplayLevel'
/// </summary>
[Test]
public void DisplayLevelTest()
{
// TODO unit test for the property 'DisplayLevel'
}
/// <summary>
/// Test the property 'RecommendedLight'
/// </summary>
[Test]
public void RecommendedLightTest()
{
// TODO unit test for the property 'RecommendedLight'
}
/// <summary>
/// Test the property 'DifficultyTier'
/// </summary>
[Test]
public void DifficultyTierTest()
{
// TODO unit test for the property 'DifficultyTier'
}
}
}
| 27.455172
| 194
| 0.564933
|
f44abebe1d43b1bf4c4375d489cd186daf2b3c56
| 39
|
ts
|
TypeScript
|
packages/server/src/interceptors/index.ts
|
vscode1111/mapbul-pub
|
1b7073d03788b2143fe94d87ee0fdd21d0f1689e
|
[
"MIT"
] | null | null | null |
packages/server/src/interceptors/index.ts
|
vscode1111/mapbul-pub
|
1b7073d03788b2143fe94d87ee0fdd21d0f1689e
|
[
"MIT"
] | 1
|
2019-11-03T07:56:43.000Z
|
2019-11-03T07:56:43.000Z
|
packages/server/src/interceptors/index.ts
|
vscode1111/mapbul-pub
|
1b7073d03788b2143fe94d87ee0fdd21d0f1689e
|
[
"MIT"
] | null | null | null |
export * from './NotFoundInterceptor';
| 19.5
| 38
| 0.74359
|
f4e40a4ff679f032e1c012c8c1e5bb82045372b2
| 345
|
rs
|
Rust
|
benchmark/benches/sync_naive_lru.rs
|
ikanago/cache_experiment
|
7ff685c8acac396800a62452b949227da3df4eb5
|
[
"MIT"
] | null | null | null |
benchmark/benches/sync_naive_lru.rs
|
ikanago/cache_experiment
|
7ff685c8acac396800a62452b949227da3df4eb5
|
[
"MIT"
] | 2
|
2021-12-12T04:39:48.000Z
|
2021-12-13T07:42:19.000Z
|
benchmark/benches/sync_naive_lru.rs
|
ikanago/cache_experiment
|
7ff685c8acac396800a62452b949227da3df4eb5
|
[
"MIT"
] | null | null | null |
use common::Cache;
use criterion::{criterion_group, Criterion};
use sync_naive_lru::SyncNaiveLru;
fn insert() {
let mut lru = SyncNaiveLru::new(4);
lru.insert(1, 2);
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("insert", |b| b.iter(|| insert()));
}
criterion_group!(sync_naive_lru_benches, criterion_benchmark);
| 23
| 62
| 0.713043
|
b300af201b5b6ca40f07dc6e4d46529eeb960016
| 35,585
|
py
|
Python
|
pyaz/vmss/__init__.py
|
py-az-cli/py-az-cli
|
9a7dc44e360c096a5a2f15595353e9dad88a9792
|
[
"MIT"
] | null | null | null |
pyaz/vmss/__init__.py
|
py-az-cli/py-az-cli
|
9a7dc44e360c096a5a2f15595353e9dad88a9792
|
[
"MIT"
] | null | null | null |
pyaz/vmss/__init__.py
|
py-az-cli/py-az-cli
|
9a7dc44e360c096a5a2f15595353e9dad88a9792
|
[
"MIT"
] | 1
|
2022-02-03T09:12:01.000Z
|
2022-02-03T09:12:01.000Z
|
'''
Manage groupings of virtual machines in an Azure Virtual Machine Scale Set (VMSS).
'''
from .. pyaz_utils import _call_az
from . import application, diagnostics, disk, encryption, extension, identity, nic, rolling_upgrade, run_command
def create(name, resource_group, accelerated_networking=None, admin_password=None, admin_username=None, app_gateway=None, app_gateway_capacity=None, app_gateway_sku=None, app_gateway_subnet_address_prefix=None, asgs=None, assign_identity=None, authentication_type=None, automatic_repairs_grace_period=None, backend_pool_name=None, backend_port=None, capacity_reservation_group=None, computer_name_prefix=None, custom_data=None, data_disk_caching=None, data_disk_encryption_sets=None, data_disk_iops=None, data_disk_mbps=None, data_disk_sizes_gb=None, disable_overprovision=None, dns_servers=None, edge_zone=None, enable_agent=None, enable_auto_update=None, enable_cross_zone_upgrade=None, enable_spot_restore=None, encryption_at_host=None, ephemeral_os_disk=None, ephemeral_os_disk_placement=None, eviction_policy=None, generate_ssh_keys=None, health_probe=None, host_group=None, image=None, instance_count=None, lb_nat_pool_name=None, lb_sku=None, license_type=None, load_balancer=None, location=None, max_batch_instance_percent=None, max_price=None, max_unhealthy_instance_percent=None, max_unhealthy_upgraded_instance_percent=None, network_api_version=None, no_wait=None, nsg=None, orchestration_mode=None, os_disk_caching=None, os_disk_encryption_set=None, os_disk_name=None, os_disk_size_gb=None, os_type=None, patch_mode=None, pause_time_between_batches=None, plan_name=None, plan_product=None, plan_promotion_code=None, plan_publisher=None, platform_fault_domain_count=None, ppg=None, prioritize_unhealthy_instances=None, priority=None, public_ip_address=None, public_ip_address_allocation=None, public_ip_address_dns_name=None, public_ip_per_vm=None, role=None, scale_in_policy=None, scope=None, secrets=None, single_placement_group=None, specialized=None, spot_restore_timeout=None, ssh_dest_key_path=None, ssh_key_values=None, storage_container_name=None, storage_sku=None, subnet=None, subnet_address_prefix=None, tags=None, terminate_notification_time=None, ultra_ssd_enabled=None, upgrade_policy_mode=None, use_unmanaged_disk=None, user_data=None, validate=None, vm_domain_name=None, vm_sku=None, vnet_address_prefix=None, vnet_name=None, zones=None):
'''
Create an Azure Virtual Machine Scale Set.
Required Parameters:
- name -- Name of the virtual machine scale set.
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- accelerated_networking -- enable accelerated networking. Unless specified, CLI will enable it based on machine image and size
- admin_password -- Password for the VM if authentication type is 'Password'.
- admin_username -- Username for the VM. Default value is current username of OS. If the default value is system reserved, then default value will be set to azureuser. Please refer to https://docs.microsoft.com/rest/api/compute/virtualmachines/createorupdate#osprofile to get a full list of reserved values.
- app_gateway -- Name to use when creating a new application gateway (default) or referencing an existing one. Can also reference an existing application gateway by ID or specify "" for none.
- app_gateway_capacity -- The number of instances to use when creating a new application gateway.
- app_gateway_sku -- SKU when creating a new application gateway.
- app_gateway_subnet_address_prefix -- The subnet IP address prefix to use when creating a new application gateway in CIDR format.
- asgs -- Space-separated list of existing application security groups to associate with the VM.
- assign_identity -- accept system or user assigned identities separated by spaces. Use '[system]' to refer system assigned identity, or a resource id to refer user assigned identity. Check out help for more examples
- authentication_type -- Type of authentication to use with the VM. Defaults to password for Windows and SSH public key for Linux. "all" enables both ssh and password authentication.
- automatic_repairs_grace_period -- The amount of time (in minutes, between 30 and 90) for which automatic repairs are suspended due to a state change on VM.
- backend_pool_name -- Name to use for the backend pool when creating a new load balancer or application gateway.
- backend_port -- When creating a new load balancer, backend port to open with NAT rules (Defaults to 22 on Linux and 3389 on Windows). When creating an application gateway, the backend port to use for the backend HTTP settings.
- capacity_reservation_group -- The ID or name of the capacity reservation group that is used to allocate. Pass in "None" to disassociate the capacity reservation group. Please note that if you want to delete a VM/VMSS that has been associated with capacity reservation group, you need to disassociate the capacity reservation group first.
- computer_name_prefix -- Computer name prefix for all of the virtual machines in the scale set. Computer name prefixes must be 1 to 15 characters long
- custom_data -- Custom init script file or text (cloud-init, cloud-config, etc..)
- data_disk_caching -- storage caching type for data disk(s), including 'None', 'ReadOnly', 'ReadWrite', etc. Use a singular value to apply on all disks, or use `<lun>=<vaule1> <lun>=<value2>` to configure individual disk
- data_disk_encryption_sets -- Names or IDs (space delimited) of disk encryption sets for data disks.
- data_disk_iops -- Specify the Read-Write IOPS (space delimited) for the managed disk. Should be used only when StorageAccountType is UltraSSD_LRS. If not specified, a default value would be assigned based on diskSizeGB.
- data_disk_mbps -- Specify the bandwidth in MB per second (space delimited) for the managed disk. Should be used only when StorageAccountType is UltraSSD_LRS. If not specified, a default value would be assigned based on diskSizeGB.
- data_disk_sizes_gb -- space-separated empty managed data disk sizes in GB to create
- disable_overprovision -- Overprovision option (see https://azure.microsoft.com/documentation/articles/virtual-machine-scale-sets-overview/ for details).
- dns_servers -- space-separated IP addresses of DNS servers, e.g. 10.0.0.5 10.0.0.6
- edge_zone -- The name of edge zone.
- enable_agent -- Indicate whether virtual machine agent should be provisioned on the virtual machine. When this property is not specified, default behavior is to set it to true. This will ensure that VM Agent is installed on the VM so that extensions can be added to the VM later
- enable_auto_update -- Indicate whether Automatic Updates is enabled for the Windows virtual machine
- enable_cross_zone_upgrade -- Set this Boolean property will allow VMSS to ignore AZ boundaries when constructing upgrade batches, and only consider Update Domain and maxBatchInstancePercent to determine the batch size
- enable_spot_restore -- Enable the Spot-Try-Restore feature where evicted VMSS SPOT instances will be tried to be restored opportunistically based on capacity availability and pricing constraints
- encryption_at_host -- Enable Host Encryption for the VM or VMSS. This will enable the encryption for all the disks including Resource/Temp disk at host itself.
- ephemeral_os_disk -- Allows you to create an OS disk directly on the host node, providing local disk performance and faster VM/VMSS reimage time.
- ephemeral_os_disk_placement -- Only applicable when used with `--ephemeral-os-disk`. Allows you to choose the Ephemeral OS disk provisioning location.
- eviction_policy -- The eviction policy for virtual machines in a Spot priority scale set. Default eviction policy is Deallocate for a Spot priority scale set
- generate_ssh_keys -- Generate SSH public and private key files if missing. The keys will be stored in the ~/.ssh directory
- health_probe -- Probe name from the existing load balancer, mainly used for rolling upgrade or automatic repairs
- host_group -- Name or ID of dedicated host group that the virtual machine scale set resides in
- image -- None
- instance_count -- Number of VMs in the scale set.
- lb_nat_pool_name -- Name to use for the NAT pool when creating a new load balancer.
- lb_sku -- Sku of the Load Balancer to create. Default to 'Standard' when single placement group is turned off; otherwise, default to 'Basic'. The public IP is supported to be created on edge zone only when it is 'Standard'
- license_type -- Specifies that the Windows image or disk was licensed on-premises. To enable Azure Hybrid Benefit for Windows Server, use 'Windows_Server'. To enable Multitenant Hosting Rights for Windows 10, use 'Windows_Client'. For more information see the Azure Windows VM online docs.
- load_balancer -- Name to use when creating a new load balancer (default) or referencing an existing one. Can also reference an existing load balancer by ID or specify "" for none.
- location -- Location in which to create VM and related resources. If default location is not configured, will default to the resource group's location
- max_batch_instance_percent -- The maximum percent of total virtual machine instances that will be upgraded simultaneously by the rolling upgrade in one batch. Default: 20%
- max_price -- The maximum price (in US Dollars) you are willing to pay for a Spot VM/VMSS. -1 indicates that the Spot VM/VMSS should not be evicted for price reasons
- max_unhealthy_instance_percent -- The maximum percentage of the total virtual machine instances in the scale set that can be simultaneously unhealthy. Default: 20%
- max_unhealthy_upgraded_instance_percent -- The maximum percentage of upgraded virtual machine instances that can be found to be in an unhealthy state. Default: 20%
- network_api_version -- Specify the Microsoft.Network API version used when creating networking resources in the Network Interface Configurations for Virtual Machine Scale Set with orchestration mode 'Flexible'. Default value is 2020-11-01.
- no_wait -- Do not wait for the long-running operation to finish.
- nsg -- Name or ID of an existing Network Security Group.
- orchestration_mode -- Choose how virtual machines are managed by the scale set. In Uniform mode, you define a virtual machine model and Azure will generate identical instances based on that model. In Flexible mode, you manually create and add a virtual machine of any configuration to the scale set or generate identical instances based on virtual machine model defined for the scale set.
- os_disk_caching -- Storage caching type for the VM OS disk. Default: ReadWrite
- os_disk_encryption_set -- Name or ID of disk encryption set for OS disk.
- os_disk_name -- The name of the new VM OS disk.
- os_disk_size_gb -- OS disk size in GB to create.
- os_type -- Type of OS installed on a custom VHD. Do not use when specifying an URN or URN alias.
- patch_mode -- Mode of in-guest patching to IaaS virtual machine. Allowed values for Windows VM: AutomaticByOS, AutomaticByPlatform, Manual. Allowed values for Linux VM: AutomaticByPlatform, ImageDefault. Manual - You control the application of patches to a virtual machine. You do this by applying patches manually inside the VM. In this mode, automatic updates are disabled; the paramater --enable-auto-update must be false. AutomaticByOS - The virtual machine will automatically be updated by the OS. The parameter --enable-auto-update must be true. AutomaticByPlatform - the virtual machine will automatically updated by the OS. ImageDefault - The virtual machine's default patching configuration is used. The parameter --enable-agent and --enable-auto-update must be true
- pause_time_between_batches -- The wait time between completing the update for all virtual machines in one batch and starting the next batch. Default: 0 seconds
- plan_name -- plan name
- plan_product -- plan product
- plan_promotion_code -- plan promotion code
- plan_publisher -- plan publisher
- platform_fault_domain_count -- Fault Domain count for each placement group in the availability zone
- ppg -- The name or ID of the proximity placement group the VMSS should be associated with.
- prioritize_unhealthy_instances -- Set this Boolean property will lead to all unhealthy instances in a scale set getting upgraded before any healthy instances
- priority -- Priority. Use 'Spot' to run short-lived workloads in a cost-effective way. 'Low' enum will be deprecated in the future. Please use 'Spot' to deploy Azure spot VM and/or VMSS. Default to Regular.
- public_ip_address -- Name of the public IP address when creating one (default) or referencing an existing one. Can also reference an existing public IP by ID or specify "" for None ('""' in Azure CLI using PowerShell or --% operator).
- public_ip_address_allocation -- None
- public_ip_address_dns_name -- Globally unique DNS name for a newly created public IP.
- public_ip_per_vm -- Each VM instance will have a public ip. For security, you can use '--nsg' to apply appropriate rules
- role -- Role name or id the system assigned identity will have
- scale_in_policy -- Specify the scale-in policy (space delimited) that decides which virtual machines are chosen for removal when a Virtual Machine Scale Set is scaled-in.
- scope -- Scope that the system assigned identity can access
- secrets -- One or many Key Vault secrets as JSON strings or files via `@{path}` containing `[{ "sourceVault": { "id": "value" }, "vaultCertificates": [{ "certificateUrl": "value", "certificateStore": "cert store name (only on windows)"}] }]`
- single_placement_group -- Limit the scale set to a single placement group. See https://docs.microsoft.com/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-placement-groups for details.
- specialized -- Indicate whether the source image is specialized.
- spot_restore_timeout -- Timeout value expressed as an ISO 8601 time duration after which the platform will not try to restore the VMSS SPOT instances
- ssh_dest_key_path -- Destination file path on the VM for the SSH key. If the file already exists, the specified key(s) are appended to the file. Destination path for SSH public keys is currently limited to its default value "/home/username/.ssh/authorized_keys" due to a known issue in Linux provisioning agent.
- ssh_key_values -- None
- storage_container_name -- Only applicable when used with `--use-unmanaged-disk`. Name of the storage container for the VM OS disk. Default: vhds
- storage_sku -- The SKU of the storage account with which to persist VM. Use a singular sku that would be applied across all disks, or specify individual disks. Usage: [--storage-sku SKU | --storage-sku ID=SKU ID=SKU ID=SKU...], where each ID is "os" or a 0-indexed lun. Allowed values: Standard_LRS, Premium_LRS, StandardSSD_LRS, UltraSSD_LRS, Premium_ZRS, StandardSSD_ZRS.
- subnet -- The name of the subnet when creating a new VNet or referencing an existing one. Can also reference an existing subnet by ID. If both vnet-name and subnet are omitted, an appropriate VNet and subnet will be selected automatically, or a new one will be created.
- subnet_address_prefix -- The subnet IP address prefix to use when creating a new VNet in CIDR format.
- tags -- space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.
- terminate_notification_time -- Length of time (in minutes, between 5 and 15) a notification to be sent to the VM on the instance metadata server till the VM gets deleted
- ultra_ssd_enabled -- Enables or disables the capability to have 1 or more managed data disks with UltraSSD_LRS storage account
- upgrade_policy_mode -- None
- use_unmanaged_disk -- Do not use managed disk to persist VM
- user_data -- UserData for the virtual machines in the scale set. It can be passed in as file or string.
- validate -- Generate and validate the ARM template without creating any resources.
- vm_domain_name -- domain name of VM instances, once configured, the FQDN is `vm<vm-index>.<vm-domain-name>.<..rest..>`
- vm_sku -- Size of VMs in the scale set. Default to "Standard_DS1_v2". See https://azure.microsoft.com/pricing/details/virtual-machines/ for size info.
- vnet_address_prefix -- The IP address prefix to use when creating a new VNet in CIDR format.
- vnet_name -- Name of the virtual network when creating a new one or referencing an existing one.
- zones -- Space-separated list of availability zones into which to provision the resource.
'''
return _call_az("az vmss create", locals())
def deallocate(name, resource_group, instance_ids=None, no_wait=None):
'''
Deallocate VMs within a VMSS.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- instance_ids -- Space-separated list of IDs (ex: 1 2 3 ...) or * for all instances. If not provided, the action will be applied on the scaleset itself
- no_wait -- Do not wait for the long-running operation to finish.
'''
return _call_az("az vmss deallocate", locals())
def delete(name, resource_group, force_deletion=None, no_wait=None):
'''
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- force_deletion -- Optional parameter to force delete a VM scale set. (Feature in Preview).
- no_wait -- Do not wait for the long-running operation to finish.
'''
return _call_az("az vmss delete", locals())
def delete_instances(instance_ids, name, resource_group, no_wait=None):
'''
Delete VMs within a VMSS.
Required Parameters:
- instance_ids -- Space-separated list of IDs (ex: 1 2 3 ...) or * for all instances.
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- no_wait -- Do not wait for the long-running operation to finish.
'''
return _call_az("az vmss delete-instances", locals())
def get_instance_view(name, resource_group, instance_id=None):
'''
View an instance of a VMSS.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- instance_id -- None
'''
return _call_az("az vmss get-instance-view", locals())
def list(resource_group=None):
'''
List VMSS.
Optional Parameters:
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
'''
return _call_az("az vmss list", locals())
def list_instances(name, resource_group, expand=None, filter=None, select=None):
'''
Get a list of all virtual machines in a VM scale sets.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- expand -- The expand expression to apply to the operation. Allowed values are 'instanceView'.
- filter -- The filter to apply to the operation. Allowed values are 'startswith(instanceView/statuses/code, 'PowerState') eq true', 'properties/latestModelApplied eq true', 'properties/latestModelApplied eq false'.
- select -- The list parameters. Allowed values are 'instanceView', 'instanceView/statuses'.
'''
return _call_az("az vmss list-instances", locals())
def list_instance_connection_info(name, resource_group):
'''
Get the IP address and port number used to connect to individual VM instances within a set.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
'''
return _call_az("az vmss list-instance-connection-info", locals())
def list_instance_public_ips(name, resource_group):
'''
List public IP addresses of VM instances within a set.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
'''
return _call_az("az vmss list-instance-public-ips", locals())
def list_skus(name, resource_group):
'''
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
'''
return _call_az("az vmss list-skus", locals())
def reimage(name, resource_group, instance_id=None, no_wait=None):
'''
Reimage VMs within a VMSS.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- instance_id -- None
- no_wait -- Do not wait for the long-running operation to finish.
'''
return _call_az("az vmss reimage", locals())
def perform_maintenance(name, resource_group, vm_instance_i_ds=None):
'''
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- vm_instance_i_ds -- A list of virtual machine instance IDs from the VM scale set.
'''
return _call_az("az vmss perform-maintenance", locals())
def restart(name, resource_group, instance_ids=None, no_wait=None):
'''
Restart VMs within a VMSS.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- instance_ids -- Space-separated list of IDs (ex: 1 2 3 ...) or * for all instances. If not provided, the action will be applied on the scaleset itself
- no_wait -- Do not wait for the long-running operation to finish.
'''
return _call_az("az vmss restart", locals())
def scale(name, new_capacity, resource_group, no_wait=None):
'''
Change the number of VMs within a VMSS.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- new_capacity -- None
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- no_wait -- Do not wait for the long-running operation to finish.
'''
return _call_az("az vmss scale", locals())
def show(name, resource_group, include_user_data=None, instance_id=None):
'''
Get details on VMs within a VMSS.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- include_user_data -- Include the user data properties in the query result.
- instance_id -- None
'''
return _call_az("az vmss show", locals())
def simulate_eviction(instance_id, name, resource_group):
'''
Simulate the eviction of a Spot virtual machine in a VM scale set.
Required Parameters:
- instance_id -- The instance ID of the virtual machine.
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
'''
return _call_az("az vmss simulate-eviction", locals())
def start(name, resource_group, instance_ids=None, no_wait=None):
'''
Start VMs within a VMSS.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- instance_ids -- Space-separated list of IDs (ex: 1 2 3 ...) or * for all instances. If not provided, the action will be applied on the scaleset itself
- no_wait -- Do not wait for the long-running operation to finish.
'''
return _call_az("az vmss start", locals())
def stop(name, resource_group, instance_ids=None, no_wait=None, skip_shutdown=None):
'''
Power off (stop) VMs within a VMSS.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- instance_ids -- Space-separated list of IDs (ex: 1 2 3 ...) or * for all instances. If not provided, the action will be applied on the scaleset itself
- no_wait -- Do not wait for the long-running operation to finish.
- skip_shutdown -- Skip shutdown and power-off immediately.
'''
return _call_az("az vmss stop", locals())
def update(name, resource_group, add=None, automatic_repairs_grace_period=None, capacity_reservation_group=None, enable_automatic_repairs=None, enable_cross_zone_upgrade=None, enable_spot_restore=None, enable_terminate_notification=None, ephemeral_os_disk_placement=None, force_string=None, instance_id=None, license_type=None, max_batch_instance_percent=None, max_price=None, max_unhealthy_instance_percent=None, max_unhealthy_upgraded_instance_percent=None, no_wait=None, pause_time_between_batches=None, ppg=None, prioritize_unhealthy_instances=None, priority=None, protect_from_scale_in=None, protect_from_scale_set_actions=None, remove=None, scale_in_policy=None, set=None, spot_restore_timeout=None, terminate_notification_time=None, ultra_ssd_enabled=None, user_data=None, vm_sku=None):
'''
Update a VMSS. Run 'az vmss update-instances' command to roll out the changes to VMs if you have not configured upgrade policy.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- add -- Add an object to a list of objects by specifying a path and key value pairs. Example: --add property.listProperty <key=value, string or JSON string>
- automatic_repairs_grace_period -- The amount of time (in minutes, between 30 and 90) for which automatic repairs are suspended due to a state change on VM.
- capacity_reservation_group -- The ID or name of the capacity reservation group that is used to allocate. Pass in "None" to disassociate the capacity reservation group. Please note that if you want to delete a VM/VMSS that has been associated with capacity reservation group, you need to disassociate the capacity reservation group first.
- enable_automatic_repairs -- Enable automatic repairs
- enable_cross_zone_upgrade -- Set this Boolean property will allow VMSS to ignore AZ boundaries when constructing upgrade batches, and only consider Update Domain and maxBatchInstancePercent to determine the batch size
- enable_spot_restore -- Enable the Spot-Try-Restore feature where evicted VMSS SPOT instances will be tried to be restored opportunistically based on capacity availability and pricing constraints
- enable_terminate_notification -- Enable terminate notification
- ephemeral_os_disk_placement -- Only applicable when used with `--vm-sku`. Allows you to choose the Ephemeral OS disk provisioning location.
- force_string -- When using 'set' or 'add', preserve string literals instead of attempting to convert to JSON.
- instance_id -- Update the VM instance with this ID. If missing, Update the VMSS.
- license_type -- Specifies that the Windows image or disk was licensed on-premises. To enable Azure Hybrid Benefit for Windows Server, use 'Windows_Server'. To enable Multitenant Hosting Rights for Windows 10, use 'Windows_Client'. For more information see the Azure Windows VM online docs.
- max_batch_instance_percent -- The maximum percent of total virtual machine instances that will be upgraded simultaneously by the rolling upgrade in one batch. Default: 20%
- max_price -- The maximum price (in US Dollars) you are willing to pay for a Spot VM/VMSS. -1 indicates that the Spot VM/VMSS should not be evicted for price reasons
- max_unhealthy_instance_percent -- The maximum percentage of the total virtual machine instances in the scale set that can be simultaneously unhealthy. Default: 20%
- max_unhealthy_upgraded_instance_percent -- The maximum percentage of upgraded virtual machine instances that can be found to be in an unhealthy state. Default: 20%
- no_wait -- Do not wait for the long-running operation to finish.
- pause_time_between_batches -- The wait time between completing the update for all virtual machines in one batch and starting the next batch. Default: 0 seconds
- ppg -- The name or ID of the proximity placement group the VMSS should be associated with.
- prioritize_unhealthy_instances -- Set this Boolean property will lead to all unhealthy instances in a scale set getting upgraded before any healthy instances
- priority -- Priority. Use 'Spot' to run short-lived workloads in a cost-effective way. 'Low' enum will be deprecated in the future. Please use 'Spot' to deploy Azure spot VM and/or VMSS. Default to Regular.
- protect_from_scale_in -- Protect the VM instance from scale-in operations.
- protect_from_scale_set_actions -- Protect the VM instance from scale set actions (including scale-in).
- remove -- Remove a property or an element from a list. Example: --remove property.list <indexToRemove> OR --remove propertyToRemove
- scale_in_policy -- Specify the scale-in policy (space delimited) that decides which virtual machines are chosen for removal when a Virtual Machine Scale Set is scaled-in.
- set -- Update an object by specifying a property path and value to set. Example: --set property1.property2=<value>
- spot_restore_timeout -- Timeout value expressed as an ISO 8601 time duration after which the platform will not try to restore the VMSS SPOT instances
- terminate_notification_time -- Length of time (in minutes, between 5 and 15) a notification to be sent to the VM on the instance metadata server till the VM gets deleted
- ultra_ssd_enabled -- Enables or disables the capability to have 1 or more managed data disks with UltraSSD_LRS storage account
- user_data -- UserData for the virtual machines in the scale set. It can be passed in as file or string. If empty string is passed in, the existing value will be deleted.
- vm_sku -- The new size of the virtual machine instances in the scale set. Default to "Standard_DS1_v2". See https://azure.microsoft.com/pricing/details/virtual-machines/ for size info.
'''
return _call_az("az vmss update", locals())
def update_instances(instance_ids, name, resource_group, no_wait=None):
'''
Upgrade VMs within a VMSS.
Required Parameters:
- instance_ids -- Space-separated list of IDs (ex: 1 2 3 ...) or * for all instances.
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- no_wait -- Do not wait for the long-running operation to finish.
'''
return _call_az("az vmss update-instances", locals())
def wait(name, resource_group, created=None, custom=None, deleted=None, exists=None, instance_id=None, interval=None, timeout=None, updated=None):
'''
Place the CLI in a waiting state until a condition of a scale set is met.
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
Optional Parameters:
- created -- wait until created with 'provisioningState' at 'Succeeded'
- custom -- Wait until the condition satisfies a custom JMESPath query. E.g. provisioningState!='InProgress', instanceView.statuses[?code=='PowerState/running']
- deleted -- wait until deleted
- exists -- wait until the resource exists
- instance_id -- Wait on the VM instance with this ID. If missing, Wait on the VMSS.
- interval -- polling interval in seconds
- timeout -- maximum wait in seconds
- updated -- wait until updated with provisioningState at 'Succeeded'
'''
return _call_az("az vmss wait", locals())
def get_os_upgrade_history(name, resource_group):
'''
Required Parameters:
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
'''
return _call_az("az vmss get-os-upgrade-history", locals())
def set_orchestration_service_state(action, name, resource_group, service_name, no_wait=None):
'''
Change ServiceState property for a given service within a VMSS.
Required Parameters:
- action -- The action to be performed.
- name -- Scale set name. You can configure the default using `az configure --defaults vmss=<name>`
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
- service_name -- The name of the orchestration service.
Optional Parameters:
- no_wait -- Do not wait for the long-running operation to finish.
'''
return _call_az("az vmss set-orchestration-service-state", locals())
| 78.208791
| 2,164
| 0.753295
|
e3f63814dda5e3efa3f4d5a867ac595a749f7a54
| 906
|
swift
|
Swift
|
LePigeonRebelle/ExpenseType+CoreDataProperties.swift
|
yassinedoghri/LePigeonRebelle-iOS
|
8372a23fe3080c07ac58b52deab4f3fa7da6e2de
|
[
"MIT"
] | null | null | null |
LePigeonRebelle/ExpenseType+CoreDataProperties.swift
|
yassinedoghri/LePigeonRebelle-iOS
|
8372a23fe3080c07ac58b52deab4f3fa7da6e2de
|
[
"MIT"
] | null | null | null |
LePigeonRebelle/ExpenseType+CoreDataProperties.swift
|
yassinedoghri/LePigeonRebelle-iOS
|
8372a23fe3080c07ac58b52deab4f3fa7da6e2de
|
[
"MIT"
] | null | null | null |
//
// ExpenseType+CoreDataProperties.swift
// LePigeonRebelle
//
// Created by iMac on 06/01/2018.
// Copyright © 2018 Le Pigeon Rebelle. All rights reserved.
//
import Foundation
import CoreData
extension ExpenseType {
@nonobjc public class func fetchRequest() -> NSFetchRequest<ExpenseType> {
return NSFetchRequest<ExpenseType>(entityName: "ExpenseType");
}
@NSManaged public var wording: String?
@NSManaged public var expenses: NSSet?
}
// MARK: Generated accessors for expenses
extension ExpenseType {
@objc(addExpensesObject:)
@NSManaged public func addToExpenses(_ value: Expense)
@objc(removeExpensesObject:)
@NSManaged public func removeFromExpenses(_ value: Expense)
@objc(addExpenses:)
@NSManaged public func addToExpenses(_ values: NSSet)
@objc(removeExpenses:)
@NSManaged public func removeFromExpenses(_ values: NSSet)
}
| 22.65
| 78
| 0.727373
|
11b2c47ec5d9f2377b5afa119e16dff5148954c8
| 2,918
|
kt
|
Kotlin
|
android-myenergy/app/src/main/java/net/myenv/myenergy/ui/statistics/StatisticsFragment.kt
|
mmaciejow/myenergy
|
3cd7f43c1aca8d28c28414bf2ba0de8da1fd9e45
|
[
"MIT"
] | 1
|
2021-04-21T11:40:19.000Z
|
2021-04-21T11:40:19.000Z
|
android-myenergy/app/src/main/java/net/myenv/myenergy/ui/statistics/StatisticsFragment.kt
|
mmaciejow/myenergy
|
3cd7f43c1aca8d28c28414bf2ba0de8da1fd9e45
|
[
"MIT"
] | null | null | null |
android-myenergy/app/src/main/java/net/myenv/myenergy/ui/statistics/StatisticsFragment.kt
|
mmaciejow/myenergy
|
3cd7f43c1aca8d28c28414bf2ba0de8da1fd9e45
|
[
"MIT"
] | null | null | null |
package net.myenv.myenergy.ui.statistics
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.TEXT_ALIGNMENT_TEXT_END
import android.view.ViewGroup
import android.widget.TableRow
import android.widget.TextView
import androidx.fragment.app.Fragment
import net.myenv.myenergy.MainViewModel
import net.myenv.myenergy.R
import net.myenv.myenergy.databinding.FragmentStatisticsBinding
import net.myenv.myenergy.databinding.TableRowBinding
import net.myenv.myenergy.model.EnergyStats
import net.myenv.myenergy.model.Result
import net.myenv.myenergy.utils.extension.getDatefromTimestamp
import net.myenv.myenergy.utils.extension.show
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class StatisticsFragment : Fragment() {
private val mainViewModel by sharedViewModel<MainViewModel>()
private var _binding: FragmentStatisticsBinding? = null
private val binding get() = _binding!!
private val progressBar by lazy { binding.progress.root }
private val error by lazy { binding.notFoundData }
private val statsTable by lazy { binding.statsTable }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentStatisticsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mainViewModel.getStats()
initListener()
}
private fun initListener() {
mainViewModel.statsEnergy.observe(viewLifecycleOwner, {
when (it) {
is Result.Loading -> {
progressBar.show(true)
}
is Result.Success -> {
error.show(false)
progressBar.show(false)
statsTable.show(true)
val stats = it.data as EnergyStats
showData(stats)
}
is Result.Failure -> {
error.show(false)
progressBar.show(true)
}
}
})
}
private fun showData(stats: EnergyStats) {
addRow(R.string.total_production, "${stats.pv_production} KW")
addRow(R.string.max_power, stats.max_power.toString())
addRow(R.string.max_power_date, getDatefromTimestamp(stats.max_power_date,"yyyy-MM-dd"))
}
private fun addRow(name: Int, value: String){
val tableRow = TableRowBinding.inflate(this.layoutInflater)
tableRow.value.textAlignment = TEXT_ALIGNMENT_TEXT_END
tableRow.name.text = getString(name)
tableRow.value.text = value
statsTable.addView(tableRow.root)
}
}
| 31.376344
| 96
| 0.674435
|
41b3ff32a3ffb2f4bc68ba96ba0025b2cbdae1c4
| 4,232
|
rs
|
Rust
|
sgx-types/src/secs.rs
|
squidboylan/enarx
|
5793d979d17689c6b837df897c13e3045d298e8a
|
[
"Apache-2.0"
] | null | null | null |
sgx-types/src/secs.rs
|
squidboylan/enarx
|
5793d979d17689c6b837df897c13e3045d298e8a
|
[
"Apache-2.0"
] | null | null | null |
sgx-types/src/secs.rs
|
squidboylan/enarx
|
5793d979d17689c6b837df897c13e3045d298e8a
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2020 Red Hat, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! SECS (Section 38.7)
//! The SGX Enclave Control Structure (SECS) is a special enclave page that is not
//! visible in the address space. In fact, this structure defines the address
//! range and other global attributes for the enclave and it is the first EPC
//! page created for any enclave. It is moved from a temporary buffer to an EPC
//! by the means of ENCLS(ECREATE) leaf.
use super::{attr, isv, misc::MiscSelect, sig::Contents};
use core::num::NonZeroU64;
/// Section 38.7
#[derive(Copy, Clone, Debug)]
#[repr(C, align(4096))]
pub struct Secs {
/// Size of address space (power of 2).
pub size: u64,
/// Base address of address space.
pub base: u64,
/// Size of an SSA frame.
pub ssa_size: u32,
/// Enumerates info the processor can save into the MISC region of SSA when an AEX occurs.
pub misc: MiscSelect,
reserved0: [u8; 24],
/// Enclave attributes as described in Table 38-3.
pub attr: attr::Attributes,
/// SHA256 hash of enclave contents.
pub mrenclave: [u8; 32],
reserved1: [u8; 32],
/// SHA256 hash of pubkey used to sign SIGSTRUCT.
pub mrsigner: [u8; 32],
reserved2: [u64; 12],
/// User-defined value used in key derivation.
pub isv_prod_id: isv::ProdId,
/// User-defined value used in key derivation.
pub isv_svn: isv::Svn,
}
testaso! {
struct Secs: 4096, 4096 => {
size: 0,
base: 8,
ssa_size: 16,
misc: 20,
reserved0: 24,
attr: 48,
mrenclave: 64,
reserved1: 96,
mrsigner: 128,
reserved2: 160,
isv_prod_id: 256,
isv_svn: 258
}
}
impl Secs {
/// # Usage
/// Returns the maximum enclave size for 64bit in bytes.
/// CPUID.(EAX=12H, ECX=0H) enumerates Intel SGX capability;
/// For more on CPUID enumeration leaves, see 37.7.2 and Table 37-4.
///
/// # Safety
/// This function is unsafe because it does not check if the `CPUID` instruction
/// is available before issuing it.
pub unsafe fn max_size() -> Option<NonZeroU64> {
const LEAF_MAX_PARAM: u32 = 0x0;
const LEAF_SGX_SUPPORT: u32 = 0x07;
const SUBLEAF_SGX_SUPPORT: u32 = 0x0;
const LEAF_MAX_ENCL_SIZE: u32 = 0x12;
const SUBLEAF_MAX_ENCL_SIZE: u32 = 0x0;
// Test for max leaf size
let res = core::arch::x86_64::__get_cpuid_max(LEAF_MAX_PARAM);
let max_leaf = res.0;
if max_leaf < LEAF_SGX_SUPPORT || max_leaf < LEAF_MAX_ENCL_SIZE {
return None;
}
// Test for SGX support
let res = core::arch::x86_64::__cpuid_count(LEAF_SGX_SUPPORT, SUBLEAF_SGX_SUPPORT);
if res.ebx & (1 << 2) == 0 {
return None;
}
// Test for max enclave size
let res = core::arch::x86_64::__cpuid_count(LEAF_MAX_ENCL_SIZE, SUBLEAF_MAX_ENCL_SIZE);
let max_size: u64 = 1 << (res.edx >> 8 as u8) as u64;
Some(NonZeroU64::new(max_size).unwrap())
}
/// Creates a new SECS struct based on a base address, size, SSA size, and Contents.
pub fn new(base: u64, size: u64, ssa: u32, mrsigner: [u8; 32], contents: &Contents) -> Self {
Self {
size,
base,
ssa_size: ssa,
misc: contents.misc.data & contents.misc.mask,
reserved0: [0; 24],
attr: contents.attr.data & contents.attr.mask,
mrenclave: contents.mrenclave,
reserved1: [0; 32],
mrsigner,
reserved2: [0; 12],
isv_prod_id: contents.isv_prod_id,
isv_svn: contents.isv_svn,
}
}
}
| 34.688525
| 97
| 0.622637
|