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
64075624df733eb1202dba9a9f571b9cd81d7495
719
py
Python
jogo/objetos/objeto.py
luizklitzke1/SpaceInvaders-PyArcade
82f3e594b05e4362dcb7092dff0ab50699b8cb3b
[ "MIT" ]
6
2020-01-10T00:35:53.000Z
2020-05-11T23:40:17.000Z
jogo/objetos/objeto.py
luizklitzke1/SpaceInvader-PyArcade
82f3e594b05e4362dcb7092dff0ab50699b8cb3b
[ "MIT" ]
null
null
null
jogo/objetos/objeto.py
luizklitzke1/SpaceInvader-PyArcade
82f3e594b05e4362dcb7092dff0ab50699b8cb3b
[ "MIT" ]
null
null
null
import arcade class Objeto(arcade.Sprite): def __init__(self, imagem, dimensao_imagem, center_x=0, center_y=0): super().__init__(imagem, dimensao_imagem) self.center_x = center_x self.center_y = center_y def set_center_x(self, novo_x): self.center_x = novo_x def get_center_x(self): return self.center_x def set_center_y(self, novo_y): self.center_y = novo_y def get_center_y(self): return self.center_y #Remove o objeto da tela caso passe dos limites: def remover_se_sair(self, width, height, bottom, top, left, right): if bottom < 50 or top > height - 70 or right < 0 or left > width: self.kill()
27.653846
73
0.642559
7f37e10a6ff77fe2a78a75fbaaf502ab42090817
363
cs
C#
Amalgam.Core/Contracts/Handlers/IGiftHandler.cs
titosilva/Amalgam
823ccf43ec606b3b285e5caf512569ae50942860
[ "MIT" ]
null
null
null
Amalgam.Core/Contracts/Handlers/IGiftHandler.cs
titosilva/Amalgam
823ccf43ec606b3b285e5caf512569ae50942860
[ "MIT" ]
null
null
null
Amalgam.Core/Contracts/Handlers/IGiftHandler.cs
titosilva/Amalgam
823ccf43ec606b3b285e5caf512569ae50942860
[ "MIT" ]
null
null
null
using System; using System.Threading.Tasks; using Amalgam.Core.Contracts.Commands; using Amalgam.Core.Entities; namespace Amalgam.Core.Contracts.Handlers { public interface IGiftHandler { Gift CreateGift(CreateGiftCommand command); Task<Gift> UpdateGiftAsync(Guid id, UpdateGiftCommand command); Task DeleteGiftAsync(Guid id); } }
27.923077
71
0.752066
e90a975b3397c8809aba5a6ecd8548527ec23aea
703
lua
Lua
Project/05 - Content/Interface/SelectMapMenu.lua
CollectifBlueprint/GoalRush
509af56659b2d2190ce01a4a786f9fa138c49dda
[ "MIT" ]
5
2019-01-21T20:06:06.000Z
2022-02-18T22:27:21.000Z
Project/05 - Content/Interface/SelectMapMenu.lua
CollectifBlueprint/GoalRush
509af56659b2d2190ce01a4a786f9fa138c49dda
[ "MIT" ]
null
null
null
Project/05 - Content/Interface/SelectMapMenu.lua
CollectifBlueprint/GoalRush
509af56659b2d2190ce01a4a786f9fa138c49dda
[ "MIT" ]
2
2019-05-26T19:30:52.000Z
2021-08-30T09:06:49.000Z
Menu = { Name = "SelectMap", Script = { _class = "AltSelectMapScript" }, Items = { { Name = "Team", Text = "Team", Enabled = 0, }, { Name = "Arena", Text = "Arena", Enabled = 1, }, { Name = "Play", Text = "Play", Enabled = 0, }, }, Sounds = "@Interface/MenuSounds.lua::MenuSoundsDefault" } Params = { DescriptionPanelSize = 600, SelectionPanelSize = 300, SeparatorLineOffset = 530, SeparatorMargin = 60, DescriptionPreviewSize = { X = 640, Y = 360 }, DescriptionPreviewHeight = 120, DescriptionPreviewMargin = 50, SelectionPreviewSize = { X = 288, Y = 162 }, SelectionPreviewMargin = 25, }
17.146341
56
0.561878
b1146185b8bd8139e8919eb5834e35b75179948f
1,950
py
Python
recipes/Python/578485_First_Class_Enums_in_Python/recipe-578485.py
tdiprima/code
61a74f5f93da087d27c70b2efe779ac6bd2a3b4f
[ "MIT" ]
2,023
2017-07-29T09:34:46.000Z
2022-03-24T08:00:45.000Z
recipes/Python/578485_First_Class_Enums_in_Python/recipe-578485.py
unhacker/code
73b09edc1b9850c557a79296655f140ce5e853db
[ "MIT" ]
32
2017-09-02T17:20:08.000Z
2022-02-11T17:49:37.000Z
recipes/Python/578485_First_Class_Enums_in_Python/recipe-578485.py
unhacker/code
73b09edc1b9850c557a79296655f140ce5e853db
[ "MIT" ]
780
2017-07-28T19:23:28.000Z
2022-03-25T20:39:41.000Z
#!/usr/bin/env python def enum(*names): """A true immutable symbolic enumeration with qualified value access.""" class EnumValue(object): __slots__ = ("type", "value",) def __init__(self, type, value): self.type = type self.value = value def __hash__(self): return hash(self.value) def __cmp__(self, other): return cmp(self.value, other.value) def __invert__(self): return self.type.values[(len(self.type) - 1) - self.value] def __nonzero__(self): return bool(self.value) def __repr__(self): return str(self.type.names[self.value]) class EnumClass(object): __slots__ = ("names", "mapping", "values",) def __init__(self, *names): self.names = names self.values = dict( (i, EnumValue(self, i)) for i in range(len(names)) ) self.mapping = dict( (names[i], value) for i, value in self.values.items() ) def __getattr__(self, attr): try: return self.mapping[attr] except KeyError: raise AttributeError(attr) def __iter__(self): return iter(self.values.values()) def __len__(self): return len(self.values) def __getitem__(self, i): return self.values[i] def __repr__(self): return "<Enum {0:s}>".format(str(self.names)) def __str__(self): return "enum {0:s}".format(str(self.values)) return EnumClass(*names) Days = enum("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") print Days print Days.Mon print Days.Fri print Days.Mon < Days.Fri print list(Days) for day in Days: print "Day: {0:s}".format(repr(day)) Confirmation = enum("No", "Yes") answer = Confirmation.No print "Your answer is not", ~answer
24.683544
76
0.550769
7ab1957fc72bb0b3b76c648ef7ed2c7f2156141a
1,379
cs
C#
PropertySettings/SimpleTinyMCESettings.cs
episerver/cms-ui-extension-samples
58a8f3cd526a5eb5fa278226dcaf416438dde783
[ "Apache-2.0" ]
3
2015-04-09T08:18:07.000Z
2017-02-01T20:28:15.000Z
PropertySettings/SimpleTinyMCESettings.cs
episerver/cms-ui-extension-samples
58a8f3cd526a5eb5fa278226dcaf416438dde783
[ "Apache-2.0" ]
null
null
null
PropertySettings/SimpleTinyMCESettings.cs
episerver/cms-ui-extension-samples
58a8f3cd526a5eb5fa278226dcaf416438dde783
[ "Apache-2.0" ]
2
2016-05-16T06:25:30.000Z
2019-05-31T16:23:37.000Z
using EPiServer.Core.PropertySettings; using EPiServer.Editor.TinyMCE; using EPiServer.Security; using EPiServer.ServiceLocation; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace UIExtensionSamples.PropertySettings { [ServiceConfiguration(ServiceType = typeof(EPiServer.Core.PropertySettings.PropertySettings))] public class SimpleTinyMCESettings : PropertySettings<TinyMCESettings> { public SimpleTinyMCESettings() { //This class can be configured to be used for specific properties. IsDefault = false; DisplayName = "Test of settings from code"; } public override TinyMCESettings GetPropertySettings() { var settings = new TinyMCESettings(); var mainToolbar = new ToolbarRow(new List<string>() { "bold" }); if (PrincipalInfo.CurrentPrincipal.IsInRole("administrators")) { //Chance to personalize. mainToolbar.Buttons.Add("italic"); } settings.ToolbarRows.Add(mainToolbar); settings.Height = 20; settings.Width = 200; return settings; } public override System.Guid ID { get { return new System.Guid("a6fe936f-190d-45e2-b83c-ccc0501a7311"); } } } }
29.340426
98
0.634518
f739888f1087fc0e9656d5851dd4ad3a757ce17c
245
rb
Ruby
features/step_definitions/pusher_steps.rb
theodi/metrics-api
b01c1353780ad91bfb98f2e25a12bf5c4db3a09a
[ "MIT" ]
17
2016-06-03T14:13:16.000Z
2021-06-15T19:59:03.000Z
features/step_definitions/pusher_steps.rb
enterstudio/bothan
4641e34e5b4df70781984457af90b8a4e01fde23
[ "MIT" ]
187
2016-04-14T14:37:20.000Z
2021-05-17T21:42:38.000Z
features/step_definitions/pusher_steps.rb
enterstudio/bothan
4641e34e5b4df70781984457af90b8a4e01fde23
[ "MIT" ]
10
2016-08-18T21:00:41.000Z
2020-06-06T09:51:25.000Z
Given(/^I set up a Pusher spy$/) do allow(Pusher).to receive(:trigger) end Then(/^the Pusher endpoint should have recieved "(.*?)" with "(.*?)"$/) do |metric, message| expect(Pusher).to have_received(:trigger).with(metric, message, {}) end
30.625
92
0.673469
12fe7d8a37bf10e23360905b7e61b059c7995e53
253
cs
C#
Monofoxe.Spriter/Monofoxe.Spriter/Models/SpriterMainlineKey.cs
Martenfur/Monofoxe.Spriter
755c4943e5339c6fca8f04db5fd9afca7d58dbf8
[ "MIT" ]
1
2021-08-04T13:31:22.000Z
2021-08-04T13:31:22.000Z
Monofoxe.Spriter/Monofoxe.Spriter/Models/SpriterMainlineKey.cs
Martenfur/Monofoxe.Spriter
755c4943e5339c6fca8f04db5fd9afca7d58dbf8
[ "MIT" ]
null
null
null
Monofoxe.Spriter/Monofoxe.Spriter/Models/SpriterMainlineKey.cs
Martenfur/Monofoxe.Spriter
755c4943e5339c6fca8f04db5fd9afca7d58dbf8
[ "MIT" ]
null
null
null
using System.Xml.Serialization; namespace Monofoxe.Spriter.Models { public class SpriterMainlineKey : SpriterKey { [XmlElement("bone_ref")] public SpriterRef[] BoneRefs; [XmlElement("object_ref")] public SpriterObjectRef[] ObjectRefs; } }
18.071429
45
0.750988
6d3976bb6a07ced92066262e29a9e91872a25458
699
ts
TypeScript
packages/webapp/src/_app/utils/meetings.ts
abitmore/Eden
90bf6c5c7297b1dc79745b0ea001e1c48e7ba170
[ "MIT" ]
35
2021-04-02T02:17:39.000Z
2021-11-23T17:46:50.000Z
packages/webapp/src/_app/utils/meetings.ts
abitmore/Eden
90bf6c5c7297b1dc79745b0ea001e1c48e7ba170
[ "MIT" ]
323
2021-04-07T15:07:39.000Z
2022-01-25T01:11:38.000Z
packages/webapp/src/_app/utils/meetings.ts
abitmore/Eden
90bf6c5c7297b1dc79745b0ea001e1c48e7ba170
[ "MIT" ]
8
2021-05-10T01:19:47.000Z
2022-01-24T23:05:00.000Z
const acceptedMeetingRegexes = [ // Zoom Meeting Link with Password // eg: https://us05web.zoom.us/j/12340622987?pwd=Z3EvYWpaNk5mWURXMlZWbUU4Lzd56789 /^https?:\/\/[\S.]*\zoom\.us\/j\/[\S]+\?pwd=[\S]+$/, ]; export const validateMeetingLink = (meetingLink: string) => { if (!meetingLink) { throw new Error("Meeting link is empty"); } for (const regex of acceptedMeetingRegexes) { if (regex.test(meetingLink)) { return; } } throw new Error( "Invalid meeting link. Please enter a generated Zoom meeting link with the password appended to the end. E.g., https://us06web.zoom.us/j/71043116043?pwd=RZFqdZ1TUFBzSVRE." ); };
31.772727
179
0.635193
96e26175a96601349c43c57372e9a32fcce44875
220
swift
Swift
Sources/SafePreviewDevice/PreviewDeviceExtension.swift
posix88/SafePreviewDevice
a4982d971ea51e2fad27b5e3fc9e3edf21a4254e
[ "MIT" ]
13
2020-04-30T08:31:14.000Z
2022-01-19T03:01:24.000Z
Sources/SafePreviewDevice/PreviewDeviceExtension.swift
posix88/SafePreviewDevice
a4982d971ea51e2fad27b5e3fc9e3edf21a4254e
[ "MIT" ]
null
null
null
Sources/SafePreviewDevice/PreviewDeviceExtension.swift
posix88/SafePreviewDevice
a4982d971ea51e2fad27b5e3fc9e3edf21a4254e
[ "MIT" ]
1
2022-01-17T19:21:31.000Z
2022-01-17T19:21:31.000Z
#if canImport(SwiftUI) import SwiftUI @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) public extension PreviewDevice { init(device: Devices) { self.init(rawValue: device.rawValue) } } #endif
18.333333
58
0.677273
ee3f7a4d7df67017a32ef1bbe59bfd85237da9b4
13,665
go
Go
v23/security/caveat_test.go
noahtseng/core
f6156e31be2e9f62a8442ec242f6be7ebe1c6db4
[ "BSD-3-Clause" ]
null
null
null
v23/security/caveat_test.go
noahtseng/core
f6156e31be2e9f62a8442ec242f6be7ebe1c6db4
[ "BSD-3-Clause" ]
null
null
null
v23/security/caveat_test.go
noahtseng/core
f6156e31be2e9f62a8442ec242f6be7ebe1c6db4
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Vanadium Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package security_test import ( "fmt" "reflect" "testing" "time" "v.io/v23/context" "v.io/v23/internal/sectest" "v.io/v23/security" "v.io/v23/uniqueid" "v.io/v23/vdl" "v.io/v23/verror" ) func TestStandardCaveatFactoriesECDSA(t *testing.T) { testStandardCaveatFactories(t, sectest.NewECDSAPrincipalP256(t)) } func TestStandardCaveatFactoriesED25519(t *testing.T) { testStandardCaveatFactories(t, sectest.NewED25519Principal(t)) } func testStandardCaveatFactories(t *testing.T, self security.Principal) { var ( balice, _ = security.UnionOfBlessings( sectest.BlessSelf(t, self, "alice:phone"), sectest.BlessSelf(t, self, "alice:tablet")) bother = sectest.BlessSelf(t, self, "other") b, _ = security.UnionOfBlessings(balice, bother) now = time.Now() call = security.NewCall(&security.CallParams{ Timestamp: now, Method: "Foo", LocalPrincipal: self, LocalBlessings: b, }) C = func(c security.Caveat, err error) security.Caveat { if err != nil { t.Fatal(err) } return c } tests = []struct { cav security.Caveat ok bool }{ // ExpiryCaveat {C(security.NewExpiryCaveat(now.Add(time.Second))), true}, {C(security.NewExpiryCaveat(now.Add(-1 * time.Second))), false}, // MethodCaveat {C(security.NewMethodCaveat("Foo")), true}, {C(security.NewMethodCaveat("Bar")), false}, {C(security.NewMethodCaveat("Foo", "Bar")), true}, {C(security.NewMethodCaveat("Bar", "Baz")), false}, // PeerBlesingsCaveat {C(security.NewCaveat(security.PeerBlessingsCaveat, []security.BlessingPattern{"alice:phone"})), true}, {C(security.NewCaveat(security.PeerBlessingsCaveat, []security.BlessingPattern{"alice:tablet", "other"})), true}, {C(security.NewCaveat(security.PeerBlessingsCaveat, []security.BlessingPattern{"alice:laptop", "other", "alice:$"})), false}, {C(security.NewCaveat(security.PeerBlessingsCaveat, []security.BlessingPattern{"alice:laptop", "other", "alice"})), true}, } ) if err := security.AddToRoots(self, balice); err != nil { t.Fatal(err) } ctx, cancel := context.RootContext() defer cancel() for idx, test := range tests { err := test.cav.Validate(ctx, call) if test.ok && err != nil { t.Errorf("#%d: %v.Validate(...) failed validation: %v", idx, test.cav, err) } else if !test.ok && verror.ErrorID(err) != security.ErrCaveatValidation.ID { t.Errorf("#%d: %v.Validate(...) returned error='%v' (errorid=%v), want errorid=%v", idx, test.cav, err, verror.ErrorID(err), security.ErrCaveatValidation.ID) } } } func TestPublicKeyThirdPartyCaveatECDSA(t *testing.T) { testPublicKeyThirdPartyCaveat(t, sectest.NewECDSAPrincipalP256(t), sectest.NewECDSAPrincipalP256(t), ) } func TestPublicKeyThirdPartyCaveatED25519(t *testing.T) { testPublicKeyThirdPartyCaveat(t, sectest.NewED25519Principal(t), sectest.NewED25519Principal(t), ) } func TestPublicKeyThirdPartyCaveat(t *testing.T) { testPublicKeyThirdPartyCaveat(t, sectest.NewECDSAPrincipalP256(t), sectest.NewED25519Principal(t), ) testPublicKeyThirdPartyCaveat(t, sectest.NewED25519Principal(t), sectest.NewECDSAPrincipalP256(t), ) } func testPublicKeyThirdPartyCaveat(t *testing.T, discharger, randomserver security.Principal) { var ( now = time.Now() valid = sectest.NewExpiryCaveat(t, now.Add(time.Second)) expired = sectest.NewExpiryCaveat(t, now.Add(-1*time.Second)) ctxCancelAndCall = func(method string, discharges ...security.Discharge) (*context.T, context.CancelFunc, security.Call) { params := &security.CallParams{ Timestamp: now, Method: method, RemoteDischarges: make(map[string]security.Discharge), } for _, d := range discharges { params.RemoteDischarges[d.ID()] = d } root, cancel := context.RootContext() return root, cancel, security.NewCall(params) } ) tpc, err := security.NewPublicKeyCaveat(discharger.PublicKey(), "location", security.ThirdPartyRequirements{}, valid) if err != nil { t.Fatal(err) } // Caveat should fail validation without a discharge ctx0, cancel0, call0 := ctxCancelAndCall("Method1") defer cancel0() if err := matchesError(tpc.Validate(ctx0, call0), "missing discharge"); err != nil { t.Fatal(err) } // Should validate when the discharge is present (and caveats on the discharge are met). d, err := discharger.MintDischarge(tpc, sectest.NewMethodCaveat(t, "Method1")) if err != nil { t.Fatal(err) } ctx1, cancel1, call1 := ctxCancelAndCall("Method1", d) defer cancel1() if err := tpc.Validate(ctx1, call1); err != nil { t.Fatal(err) } // Should fail validation when caveats on the discharge are not met. ctx2, cancel2, call2 := ctxCancelAndCall("Method2", d) defer cancel2() if err := matchesError(tpc.Validate(ctx2, call2), "discharge failed to validate"); err != nil { t.Fatal(err) } // Discharge can be converted to and from wire format: var d2 security.Discharge if err := sectest.RoundTrip(d, &d2); err != nil || !reflect.DeepEqual(d, d2) { t.Errorf("Got (%#v, %v), want (%#v, nil)", d2, err, d) } // A discharge minted by another principal should not be respected. if d, err = randomserver.MintDischarge(tpc, security.UnconstrainedUse()); err == nil { ctx3, cancel3, call3 := ctxCancelAndCall("Method1", d) defer cancel3() if err := matchesError(tpc.Validate(ctx3, call3), "signature verification on discharge"); err != nil { t.Fatal(err) } } // And ThirdPartyCaveat should not be dischargeable if caveats encoded within it fail validation. tpc, err = security.NewPublicKeyCaveat(discharger.PublicKey(), "location", security.ThirdPartyRequirements{}, expired) if err != nil { t.Fatal(err) } ctx, cancel := context.RootContext() defer cancel() call := security.NewCall(&security.CallParams{Timestamp: now}) if merr := matchesError(tpc.ThirdPartyDetails().Dischargeable(ctx, call), "could not validate embedded restriction"); merr != nil { t.Fatal(merr) } } func TestCaveat(t *testing.T) { uid, err := uniqueid.Random() if err != nil { t.Fatal(err) } anyCd := security.CaveatDescriptor{ Id: uid, ParamType: vdl.AnyType, } if _, err := security.NewCaveat(anyCd, 9); verror.ErrorID(err) != security.ErrCaveatParamAny.ID { t.Errorf("Got '%v' (errorid=%v), want errorid=%v", err, verror.ErrorID(err), security.ErrCaveatParamAny.ID) } cd := security.CaveatDescriptor{ Id: uid, ParamType: vdl.TypeOf(string("")), } if _, err := security.NewCaveat(cd, nil); verror.ErrorID(err) != security.ErrCaveatParamTypeMismatch.ID { t.Errorf("Got '%v' (errorid=%v), want errorid=%v", err, verror.ErrorID(err), security.ErrCaveatParamTypeMismatch.ID) } // A param of type *vdl.Value with underlying type string should succeed. if _, err := security.NewCaveat(cd, vdl.StringValue(nil, "")); err != nil { t.Errorf("vdl value should have succeeded: %v", err) } call := security.NewCall(&security.CallParams{ Method: "Foo", }) ctx, cancel := context.RootContext() defer cancel() c1, err := security.NewCaveat(cd, "Foo") if err != nil { t.Fatal(err) } c2, err := security.NewCaveat(cd, "Bar") if err != nil { t.Fatal(err) } // Validation will fail when the validation function isn't registered. if err := c1.Validate(ctx, call); verror.ErrorID(err) != security.ErrCaveatNotRegistered.ID { t.Errorf("Got '%v' (errorid=%v), want errorid=%v", err, verror.ErrorID(err), security.ErrCaveatNotRegistered.ID) } // Once registered, then it should be invoked security.RegisterCaveatValidator(cd, func(ctx *context.T, call security.Call, param string) error { if call.Method() == param { return nil } return fmt.Errorf("na na na") }) if err := c1.Validate(ctx, call); err != nil { t.Error(err) } if err := c2.Validate(ctx, call); verror.ErrorID(err) != security.ErrCaveatValidation.ID { t.Errorf("Got '%v' (errorid=%v), want errorid=%v", err, verror.ErrorID(err), security.ErrCaveatValidation.ID) } // If a malformed caveat was received, then validation should fail c3 := security.Caveat{Id: cd.Id, ParamVom: nil} if err := c3.Validate(ctx, call); verror.ErrorID(err) != security.ErrCaveatParamCoding.ID { t.Errorf("Got '%v' (errorid=%v), want errorid=%v", err, verror.ErrorID(err), security.ErrCaveatParamCoding.ID) } } func TestRegisterCaveat(t *testing.T) { uid, err := uniqueid.Random() if err != nil { t.Fatal(err) } var ( cd = security.CaveatDescriptor{ Id: uid, ParamType: vdl.TypeOf(string("")), } npanics int expectPanic = func(details string) { npanics++ if err := recover(); err == nil { t.Errorf("%s: expected a panic", details) } } ) func() { defer expectPanic("not a function") security.RegisterCaveatValidator(cd, "not a function") }() func() { defer expectPanic("wrong #outputs") security.RegisterCaveatValidator(cd, func(*context.T, security.Call, string) (error, error) { return nil, nil }) }() func() { defer expectPanic("bad output type") security.RegisterCaveatValidator(cd, func(*context.T, security.Call, string) int { return 0 }) }() func() { defer expectPanic("wrong #inputs") security.RegisterCaveatValidator(cd, func(*context.T, string) error { return nil }) }() func() { defer expectPanic("bad input arg 0") security.RegisterCaveatValidator(cd, func(int, security.Call, string) error { return nil }) }() func() { defer expectPanic("bad input arg 1") security.RegisterCaveatValidator(cd, func(*context.T, int, string) error { return nil }) }() func() { defer expectPanic("bad input arg 2") security.RegisterCaveatValidator(cd, func(*context.T, security.Call, int) error { return nil }) }() func() { // Successful registration: No panic: security.RegisterCaveatValidator(cd, func(*context.T, security.Call, string) error { return nil }) }() func() { defer expectPanic("Duplication registration") security.RegisterCaveatValidator(cd, func(*context.T, security.Call, string) error { return nil }) }() if got, want := npanics, 8; got != want { t.Errorf("Got %d panics, want %d", got, want) } } func TestThirdPartyDetailsECDSA(t *testing.T) { testThirdPartyDetails(t, sectest.NewECDSAPrincipalP256(t)) } func TestThirdPartyDetailsED25519(t *testing.T) { testThirdPartyDetails(t, sectest.NewED25519Principal(t)) } func testThirdPartyDetails(t *testing.T, p security.Principal) { niltests := []security.Caveat{ sectest.NewExpiryCaveat(t, time.Now()), sectest.NewMethodCaveat(t, "Foo", "Bar"), } for _, c := range niltests { if tp := c.ThirdPartyDetails(); tp != nil { t.Errorf("Caveat [%v] recognized as a third-party caveat: %v", c, tp) } } req := security.ThirdPartyRequirements{ReportMethod: true} c, err := security.NewPublicKeyCaveat(p.PublicKey(), "location", req, sectest.NewExpiryCaveat(t, time.Now())) if err != nil { t.Fatal(err) } if got := c.ThirdPartyDetails(); got.Location() != "location" { t.Errorf("Got location %q, want %q", got.Location(), "location") } else if !reflect.DeepEqual(got.Requirements(), req) { t.Errorf("Got requirements %+v, want %+v", got.Requirements(), req) } } func TestPublicKeyDischargeExpiryECDSA(t *testing.T) { testPublicKeyDischargeExpiry(t, sectest.NewECDSAPrincipalP256(t)) } func TestPublicKeyDischargeExpiryED25519(t *testing.T) { testPublicKeyDischargeExpiry(t, sectest.NewED25519Principal(t)) } func testPublicKeyDischargeExpiry(t *testing.T, discharger security.Principal) { var ( now = time.Now() oneh = sectest.NewExpiryCaveat(t, now.Add(time.Hour)) twoh = sectest.NewExpiryCaveat(t, now.Add(2*time.Hour)) threeh = sectest.NewExpiryCaveat(t, now.Add(3*time.Hour)) ) tpc, err := security.NewPublicKeyCaveat(discharger.PublicKey(), "location", security.ThirdPartyRequirements{}, oneh) if err != nil { t.Fatal(err) } // Mint three discharges; one with no ExpiryCaveat... noExpiry, err := discharger.MintDischarge(tpc, sectest.NewMethodCaveat(t, "Method1")) if err != nil { t.Fatal(err) } // another with an ExpiryCaveat one hour from now... oneCav, err := discharger.MintDischarge(tpc, oneh) if err != nil { t.Fatal(err) } // and finally, one with an ExpiryCaveat of one, two, and three hours from now. // Use a random order to help test that Expiry always returns the earliest time. threeCav, err := discharger.MintDischarge(tpc, threeh, oneh, twoh) if err != nil { t.Fatal(err) } if exp := noExpiry.Expiry(); !exp.IsZero() { t.Errorf("got %v, want %v", exp, time.Time{}) } if got, want := oneCav.Expiry().UTC(), now.Add(time.Hour).UTC(); got != want { t.Errorf("got %v, want %v", got, want) } if got, want := threeCav.Expiry().UTC(), now.Add(time.Hour).UTC(); got != want { t.Errorf("got %v, want %v", got, want) } } // Benchmark creation of a new caveat using one of the simplest caveats // (expiry) func BenchmarkNewCaveat(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := security.NewExpiryCaveat(time.Time{}); err != nil { b.Fatal(err) } } } // Benchmark caveat valdation using one of the simplest caveats (expiry). func BenchmarkValidateCaveat(b *testing.B) { cav, err := security.NewExpiryCaveat(time.Now().Add(time.Hour)) if err != nil { b.Fatal(err) } call := security.NewCall(&security.CallParams{}) ctx, cancel := context.RootContext() defer cancel() b.ResetTimer() for i := 0; i < b.N; i++ { if err := cav.Validate(ctx, call); err != nil { b.Fatalf("iteration: %v: %v", i, err) } } }
33.007246
160
0.689499
79e9a02d68c1753c06e9503d1fe3f3db843837a5
70,461
php
PHP
resources/views/nurse/show_dependent.blade.php
kenkode/afyapepe
da57ad8671e81be8d894e7f388b5af9c0c2d2fa4
[ "MIT" ]
null
null
null
resources/views/nurse/show_dependent.blade.php
kenkode/afyapepe
da57ad8671e81be8d894e7f388b5af9c0c2d2fa4
[ "MIT" ]
null
null
null
resources/views/nurse/show_dependent.blade.php
kenkode/afyapepe
da57ad8671e81be8d894e7f388b5af9c0c2d2fa4
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Afyapepe- Show Dependent </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="_token" content="{!! csrf_token() !!}" /> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" /> <link rel="stylesheet" href="{{ asset('css/plugins/toastr/toastr.min.css') }}" /> <link rel="stylesheet" href="{{ asset('js/plugins/gritter/jquery.gritter.css') }}" /> <link rel="stylesheet" href="{{ asset('css/vendor.css') }}" /> <link rel="stylesheet" href="{{ asset('css/app.css') }}" /> <link rel="stylesheet" href="{{asset('select/select2.min.css') }}" /> <link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}" /> <link rel="stylesheet" href="{{ asset('font-awesome/css/font-awesome.css') }}" /> <link rel="stylesheet" href="{{ asset('css/plugins/dataTables/datatables.min.css') }}" /> <link rel="stylesheet" href="{{ asset('css/animate.css') }}" /> <link rel="stylesheet" href="{{ asset('css/style.css') }}" /> <link rel="stylesheet" href="{!!asset('css/plugins/fullcalendar/fullcalendar.css')!!}" /> <link rel="stylesheet" media="print" href="{!!asset('css/plugins/fullcalendar/fullcalendar.print.css')!!}" /> <link rel="stylesheet" href="{!! asset('css/plugins/iCheck/custom.css') !!}" /> <link rel="stylesheet" href="{!! asset('css/plugins/steps/jquery.steps.css') !!}" /> <script type="text/javascript" src="{{ asset('js/modernizr.js') }}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="{{asset('js/ajaxscript.js')}}"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <link href="{{ asset('css/plugins/bootstrap-tagsinput/bootstrap-tagsinput.css') }}" rel="stylesheet"> <link href="{{ asset('/plugins/datapicker/datepicker3.css') }}" rel="stylesheet"> <link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet"> <link href="{{ asset('font-awesome/css/font-awesome.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/iCheck/custom.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/chosen/bootstrap-chosen.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/bootstrap-tagsinput/bootstrap-tagsinput.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/colorpicker/bootstrap-colorpicker.min.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/cropper/cropper.min.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/switchery/switchery.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/jasny/jasny-bootstrap.min.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/nouslider/jquery.nouislider.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/datapicker/datepicker3.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/ionRangeSlider/ion.rangeSlider.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/ionRangeSlider/ion.rangeSlider.skinFlat.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/awesome-bootstrap-checkbox/awesome-bootstrap-checkbox.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/clockpicker/clockpicker.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/daterangepicker/daterangepicker-bs3.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/select2/select2.min.css" rel="stylesheet') }}"> <link href="{{ asset('css/plugins/touchspin/jquery.bootstrap-touchspin.min.css') }}" rel="stylesheet"> <link href="{{ asset('css/plugins/dualListbox/bootstrap-duallistbox.min.css') }}" rel="stylesheet"> <link href="{{ asset('css/animate.css') }}" rel="stylesheet"> <link href="{{ asset('css/style.css') }}" rel="stylesheet"> </head> <body> <div id="wrapper"> @include('includes.nurse_inc.leftmenu') <div id="page-wrapper" class="gray-bg dashbard-1"> @include('includes.nurse_inc.headbar') <?php $mothers=DB::table('triage_infants')->where('dependant_id',$id)->first(); $details=DB::table('infant_details')->where('dependant_id',$id)->first();?> <div class="row"> <div class="col-lg-6 "> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Dependant Information</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> <a class="close-link"> <i class="fa fa-times"></i> </a> </div> </div> <div class="ibox-content"> <?php $dependant=DB::table('dependant')->where('id',$id)->first(); ?> <div class="form-group"> <label for="exampleInputEmail1">Name</label> <input type="name" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Next Kin Name" name="kin_name" value="{{$dependant->firstName}} {{$dependant->secondName}}" readonly="" > </div> <div class="form-group"> <label for="exampleInputPassword1">Blood Group</label> <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Blood Group" name="phone" value="{{$dependant->blood_type or ''}}" readonly > </div> <div class="form-group"> <label for="exampleInputPassword1">Gender</label> <?php $dgender=$dependant->gender;?> <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Next of Kin Phone" name="phone" value="@if($dgender==1){{"Male"}}@else{{"Female"}}@endif" readonly > </div> </div> </div> </div> <div class="col-lg-6 "> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Parent Information</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> <a class="close-link"> <i class="fa fa-times"></i> </a> </div> </div> <div class="ibox-content"> <?php $father=DB::table('dependant_parent')->where('dependant_id',$id)->where('relationship','=','Father')->first();?> @if(is_null($father)) <a data-toggle="modal" class="btn btn-primary" href="#modal-formf">Add Father</a> <div id="modal-formf" class="modal fade" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <form class="form-horizontal" role="form" method="POST" action="/addfather" novalidate> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <input type="hidden" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" value="{{$id}}" name="id" required> <div class="form-group"> <label for="exampleInputEmail1">Father Name</label> <input type="name" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Father Name" name="father_name" > </div> <div class="form-group"> <label for="exampleInputPassword1">Father Phone</label> <input type="number" class="form-control" id="exampleInputPassword1" placeholder="Father Phone" name="father_phone" > </div> <input type="submit" name="submit" value="Add" > </form> </div> </div> </div> </div> @else <div class="form-group"> <label for="exampleInputPassword1">Father Name</label> <input type="text" class="form-control" id="exampleInputPassword1" name="phone" value="{{$father->name or ''}}" readonly > </div> <div class="form-group"> <label for="exampleInputPassword1">Father Phone</label> <input type="text" class="form-control" id="exampleInputPassword1" name="phone" value="{{$father->phone or ''}}" readonly > </div> @endif <?php $mother=DB::table('dependant_parent')->where('dependant_id',$id)->where('relationship','=','Mother')->first(); ?> @if(is_null($mother)) <a data-toggle="modal" class="btn btn-primary" href="#modal-formp">Add Mother</a> <div id="modal-formp" class="modal fade" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <form class="form-horizontal" role="form" method="POST" action="/addmother" novalidate> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <input type="hidden" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" value="{{$id}}" name="id" required> <div class="form-group"> <label for="exampleInputPassword1">Mother Name</label> <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Mother Name" name="mother_name"> </div> <div class="form-group"> <label for="exampleInputPassword1">Mother Phone</label> <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Mother Phone" name="mother_phone" > </div> <div class="form-group"> <label for="exampleInputPassword1">Birth Number</label> <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Birth Number" name="Birth_number" > </div> <div class="form-group"> <label for="exampleInputEmail1">Younger sibling(born to mother)?</label> No <input type="checkbox" value="No" name="birth" /> Yes <input type="checkbox" value="Yes" name="birth" /> <div class="Yes" style="display: none"> <div class="form-group" id="data_1"> <label>Date of Birth</label> <div class="input-group date"> <span class="input-group-addon"><i class="fa fa-calendar"></i></span> <input type="text" class="form-control" name="dob" value=""> </div> </div> </div> <input type="submit" name="submit" value="Add"> </form> </div> </div> </div> </div> </div> @else <?php $db=DB::table('afya_users')->where('users_id',$mother->afya_user_id)->first();?> <div class="form-group"> <label for="exampleInputPassword1">Mother Name</label> <input type="text" class="form-control" id="exampleInputPassword1" name="phone" value="{{$mother->name or ''}}" readonly > </div> <div class="form-group"> <label for="exampleInputPassword1">Mother Phone</label> <input type="text" class="form-control" id="exampleInputPassword1" name="phone" value="{{$mother->phone or ''}}" readonly > </div> @endif </div> </div> </div> <div class="row"> <div class="col-lg-12"> <div class="ibox"> <div class="ibox-title"> <h5>Dependant information</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-wrench"></i> </a> <ul class="dropdown-menu dropdown-user"> <li><a href="#">Config option 1</a> </li> <li><a href="#">Config option 2</a> </li> </ul> <a class="close-link"> <i class="fa fa-times"></i> </a> </div> </div> <div class="ibox-content"> <form id="form" action="{{ url('babytriage') }}" method="post" class="wizard-big"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <input type="hidden" name="id" value="{{$dependant->id}}"> <h1>Baby Details</h1> <fieldset> <div class="row"> @if(!empty($details)) <div class="col-sm-6"> <div class="form-group"> <label for="exampleInputPassword1">Date</label> <input type="text" class="form-control" value="{{$details->admission_date}}" readonly=""> </div> <div class="form-group"> <label for="exampleInputPassword1">IP No</label> <input type="text" class="form-control" name="ipno" value="{{$details->ipno}}" readonly=""> </div> <div class="form-group"> <label for="exampleInputPassword1">Gestation</label> <input type="text" class="form-control" name="ipno" value="{{$details->gestation}} Gestation" readonly=""> </div> <div class="form-group"> <label for="exampleInputPassword1">Temperature</label> <input type="number" class="form-control" name="temperature" value="{{$details->temperature}}" readonly=""> </div> <div class="form-group"> <label for="exampleInputEmail1">APGar</label> <input type="text" class="form-control" name="apgar" value="{{$details->apgar}}" readonly=""> </div> <div class="form-group"> <label for="exampleInputPassword1">Birth Weight(kgs)</label> <input type="number" class="form-control" name="birthweight" value="{{$details->birthweight}}" readonly=""> </div> </div> @else <div class="col-sm-6"> <div class="form-group"> <label for="exampleInputPassword1">IP No</label> <input type="text" class="form-control" name="ipno"> </div> <div class="form-group"> <label for="exampleInputPassword1">Gestation</label> <select name="gestation" class="form-control"> <option value="24">24 weeks</option> <option value="25">25 weeks</option> <option value="26">26 weeks</option> <option value="27">27 weeks</option> <option value="28">28 weeks</option> <option value="29">29 weeks</option> <option value="30">30 weeks</option> <option value="31">31 weeks</option> <option value="32">32 weeks</option> <option value="33">33 weeks</option> <option value="34">34 weeks</option> <option value="35">35 weeks</option> <option value="36">36 weeks</option> <option value="37">37 weeks</option> <option value="38">38 weeks</option> <option value="39">39 weeks</option> <option value="40">40 weeks</option> <option value="41">41 weeks</option> <option value="42">42 weeks</option> <option value="43">43 weeks</option> <option value="44">44 weeks</option> <option value="45">45 weeks</option> <option value="46">46 weeks</option> </select> </div> <div class="form-group"> <label for="exampleInputPassword1">Temperature</label> <input type="number" class="form-control" name="temperature"> </div> <div class="form-group"> <label for="exampleInputEmail1">APGar</label> 1m <input type="checkbox" value="1m" name="apgar"/> 5m <input type="checkbox" value="5m" name="apgar"/> 10m <input type="checkbox" value="10m" name="apgar"/> </div> <div class="form-group"> <label for="exampleInputPassword1">Birth Weight</label> <input type="number" class="form-control" name="birthweight"> </div> <div class="form-group"> <label for="exampleInputPassword1">Weight Now</label> <input type="number" class="form-control" name="weightnow"> </div> </div> @endif @if(!empty($details)) <div class="col-sm-6"> <div class="form-group"> <label class="exampleInputPassword1" for="name">BBA</label> <input type="text" class="form-control" name="weightnow" value="{{$details->bba}}" readonly=""> </div> <div class="form-group"> <label>Born Where</label> <input type="text" class="form-control" name="weightnow" value="{{$details->bba_where}}" readonly=""> </div> <!--<div class="form-group"> <label for="exampleInputEmail1">BBA</label> No <input type="checkbox" value="No" id="type" name="bba" /> Yes <input type="checkbox" value="Yes" id="type" name="bba" /> <div id="embedcode"> <label>Born Where</label> Home <input type="checkbox" value="Home" name="bba_where"/> Clinic <input type="checkbox" value="Clinic" name="bba_where" /> Other Hospitals <input type="checkbox" value="Other" name="bba_where" /> </div> </div>--> <div class="form-group"> <label for="exampleInputEmail1">Delivery</label> <input type="text" class="form-control" name="weightnow" value="{{$details->delivery}}" readonly=""> </div> <div class="form-group"> <label>Resuscitation</label> <input type="text" class="form-control" name="weightnow" value="{{$details->resuscitation}}" readonly=""> </div> <div class="form-group"> <label>ROM</label> <input type="text" class="form-control" name="weightnow" value="{{$details->rom}}" readonly=""> </div> <div class="form-group"> <label>Given Vitamen: K</label> <input type="text" class="form-control" name="weightnow" value="{{$details->vitamen}}" readonly=""> </div> <div class="form-group"> <label>Given Eye Prophylaxis</label> <input type="text" class="form-control" name="weightnow" value="{{$details->prophylaxis}}" readonly=""> </div> <br> <div class="form-group"> <label>Babies Presenting Problems</label> <textarea name="babyproblem" class="form-control" readonly="">{{$details->babyproblem}}</textarea> </div> <!--<div class="form-group"> <label for="exampleInputPassword1">Revelant Drugs( Pre Admission)</label> <select multiple="multiple" class="select2" name="brevelantdrugs[]" > <?php $chiefs = DB::table('druglists')->get();?> @foreach($chiefs as $chief) <option value="{{$chief->drugname}}">{{$chief->drugname}}</option> @endforeach </select> </div>--> <div class="form-group"> <label >Revelant Drugs:</label> <textarea name="babyproblem" class="form-control" readonly="">{{$details->revelantdrugs}}</textarea> </div> </div> @else <div class="col-sm-6"> <div class="form-group"> <label class="exampleInputPassword1" for="name">BBA</label><br> No<input type="checkbox" value="No" name="bba"/>Yes<input type="checkbox" value="Yes" name="bba"/> <div id="embedcode"> <label>Born Where</label> Home <input type="checkbox" value="Home" name="bba_where"/> Clinic <input type="checkbox" value="Clinic" name="bba_where" /> Other Hospitals <input type="checkbox" value="Other" name="bba_where" /> </div> </div> <!--<div class="form-group"> <label for="exampleInputEmail1">BBA</label> No <input type="checkbox" value="No" id="type" name="bba" /> Yes <input type="checkbox" value="Yes" id="type" name="bba" /> <div id="embedcode"> <label>Born Where</label> Home <input type="checkbox" value="Home" name="bba_where"/> Clinic <input type="checkbox" value="Clinic" name="bba_where" /> Other Hospitals <input type="checkbox" value="Other" name="bba_where" /> </div> </div>--> <div class="form-group"> <label for="exampleInputEmail1">Delivery</label> SDV <input type="checkbox" value="SDV" name="delivery"/> Vacuum <input type="checkbox" value="vaccum" name="delivery"/> Breech <input type="checkbox" value="breech" name="delivery"/> Cs <input type="checkbox" value="cs" name="delivery"/> </div> <div class="form-group"> <label>Resuscitation</label> None <input type="checkbox" value="None" name="resuscitation"/> Oxygen <input type="checkbox" value="Oxygen" name="resuscitation"/> Bag/Mask <input type="checkbox" value="Bag/Mask" name="resuscitation"/> </div> <div class="form-group"> <label>ROM</label> 12 h<input type="checkbox" value="-<12h" name="rom"/> 12-18>18<input type="checkbox" value="12-18>18h" name="rom"/> </div> <div class="form-group"> <label>Given Vitamen: K</label> Yes <input type="checkbox" name="vitamen" value="Yes"> No <input type="checkbox" name="vitamen" value="No"> </div> <div class="form-group"> <label>Given Eye Prophylaxis</label> Yes <input type="checkbox" name="prophylaxis" value="Yes"> No <input type="checkbox" name="prophylaxis" value="No"> </div> <br> <div class="form-group"> <label>Babies Presenting Problems</label> <textarea name="babyproblem" class="form-control"></textarea> </div> <!--<div class="form-group"> <label for="exampleInputPassword1">Revelant Drugs( Pre Admission)</label> <select multiple="multiple" class="select2" name="brevelantdrugs[]" > <?php $chiefs = DB::table('druglists')->get();?> @foreach($chiefs as $chief) <option value="{{$chief->drugname}}">{{$chief->drugname}}</option> @endforeach </select> </div>--> <div class="form-group"> <label >Revelant Drugs:</label> <select multiple="multiple" id="presc1" name="brevelantdrugs[]" class="form-control presc1" style="width:50%" required></select> </div> </div> @endif </div> </fieldset> <h1>Mother Details</h1> <fieldset> <div class="row"> @if(!empty($details)) <div class="col-lg-6"> <?php $mother=DB::table('mother_details')->join('afya_users','afya_users.id','=','mother_details.afya_user_id')->where('mother_details.dependant_id',$id)->select('mother_details.*','afya_users.dob as dob')->first(); ?> <div class="form-group"> <label>Date of Birth</label><br> <input type="text" name="gravidity" id="gravidity" autocomplete="off" placeholder="mother gravidity" class="form-control" readonly="" value="{{$mother->dob}}" /> </div> <div class="form-group"> <label>Gravidity</label><br> <input type="number" name="gravidity" id="gravidity" value="{{$mother->gravity}}" autocomplete="off" placeholder="mother gravidity" class="form-control" readonly="" /> </div> <div class="form-group"> <label>Parity</label><br> <input type="number" name="parity" readonly="" value="{{$mother->parity}}" class="form-control" placeholder="mother parity" /> </div> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover dataTables-example" > <thead> <tr> <th>No</th> <th>Disease Name</th> <th>Disease Type</th> <th>Treatment</th> </tr> </thead> <?php $i =1; $diseases=DB::table('patient_diagnosis')->join('diagnoses','diagnoses.id','=','patient_diagnosis.disease_id')->select('diagnoses.name as name','patient_diagnosis.*')->where('patient_diagnosis.afya_user_id',$mother->afya_user_id)->get(); ?> <tbody> @foreach($diseases as $ds) <tr> <td>{{$i}}</td> <td>{{$ds->name}}</td> <td><?php $state=$ds->state;?> @if(!empty($state)){{$ds->state}}@else{{$ds->name}}@endif</td> <td><?php $tr=$ds->treatment;?> @if(!empty($tr)){{$ds->treatment}}@else{{"Yes"}}@endif</td> </tr> <?php $i++; ?> @endforeach </tbody> </table> </div> </div> @else <div class="col-lg-6"> <input type="hidden" class="form-control" name="dob" value="{{$db->dob or ''}}"> <div class="form-group"> <label>Gravidity</label><br> <input type="number" name="gravidity" id="gravidity" maxlength="6" autocomplete="off" placeholder="mother gravidity" class="form-control" /> </div> <div class="form-group"> <label>Parity</label><br> <input type="number" name="parity" class="form-control" placeholder="mother parity" /> </div> <div class="form-group"> <label for="exampleInputEmail1">Hiv status</label> Negative <input type="checkbox" value="Negative" name="hiv" /> Positive <input type="checkbox" value="Positive" name="hiv" /> <div id="hiv"> <label>ARV's</label> No <input type="checkbox" value="No" name="arvs"/> Yes <input type="checkbox" value="Yes" name="arvs" /> </div> </div> <div class="form-group"> <label>VDRL</label> Negative <input type="checkbox" value="Negative" name="vdrl" /> Positive <input type="checkbox" value="Positive" name="vdrl" /> </div> <div class="form-group"> <label>Fever</label> No <input type="checkbox" value="No" name="fever" /> Yes <input type="checkbox" value="Yes" name="fever" /> </div> <div class="form-group"> <label>Antibiotics</label> Yes <input type="checkbox" name="antibiotics" value="Yes" /> No <input type="checkbox" name="antibiotics" value="No" /> </div> <div class="form-group"> <label>Hypertention</label> Yes <input type="checkbox" name="hypertention" value="Yes" /> No <input type="checkbox" name="hypertention" value="No" /> </div> <div class="form-group"> <label>Diabetes</label> Yes <input type="checkbox" name="diabetes" value="Yes" /> No <input type="checkbox" name="diabetes" value="No" /> </div> <div class="form-group"> <label>TB Positive</label> Yes <input type="checkbox" name="tb" value="Yes" /> No <input type="checkbox" name="tb" value="No" /> <div id="tb"> <label>TB Type </label> Latent TB <input type="checkbox" value="Latent TB" name="tb_type"/> TB Disease <input type="checkbox" value="TB Disease" name="tb_type" /> <br> <label>TB Treatment</label> Yes <input type="checkbox" name="tb_treatment" value="Yes" /> No <input type="checkbox" name="tb_treatment" value="No" /> </div> </div> </div> @endif @if(!empty($details)) <div class="col-lg-6"> <div class="form-group"> <label>Labour</label><br> 1 stage <input type="text" name="labour1" class="form-control" placeholder="Enter Hours" readonly="" value="{{$mother->labour1}}" /> 2 stage <input type="text" name="labour2" class="form-control" placeholder="Enter Minutes" readonly="" value="{{$mother->labour2}}" /> </div> <div class="form-group"> <label>APH</label> <input type="text" name="labour2" class="form-control" value="{{$mother->aph}}" placeholder="Enter Minutes" readonly="" /> </div> <div class="form-group"> <label>Mother Presenting Problems?</label> <textarea name="motherproblem" class="form-control" readonly="">{{$mother->motherproblem}}</textarea> </div> <div class="form-group"> <label >Revelant Drugs:</label> <textarea name="motherproblem" class="form-control" readonly="">{{$mother->revelantdrugs}}</textarea> </div> </div> @else <div class="col-lg-6"> <div class="form-group"> <label>Labour</label><br> 1 stage <input type="text" name="labour1" class="form-control" placeholder="Enter Hours"/> 2 stage <input type="text" name="labour2" class="form-control" placeholder="Enter Minutes"/> </div> <div class="form-group"> <label>Hypertention</label> Yes <input type="checkbox" name="hypertention" value="Yes" /> No <input type="checkbox" name="hypertention" value="No" /> </div> <div class="form-group"> <label>APH</label> Yes <input type="checkbox" name="aph" value="Yes" /> No <input type="checkbox" name="aph" value="No" /> </div> <div class="form-group"> <label>Mother Presenting Problems?</label> <textarea name="motherproblem" class="form-control"></textarea> </div> <div class="form-group"> <label >Revelant Drugs:</label> <select multiple="multiple" id="presc1" name="mrevelantdrugs[]" class="form-control presc1" style="width:50%" required></select> </div> </div> @endif </div> </fieldset> <h1>Allergies</h1> <fieldset> <div class="row"> <div class="col-sm-6"> <div class="form-group"> Drug Allergy <input type="checkbox" value="drug" name="drug" /> <div id="drug"> <label>Drug Name</label><br> <select multiple="multiple" class="form-control" name="drugs[]"> <?php $druglists = DB::table('allergies_type')->where('allergies_id',1)->get();?> @foreach($druglists as $druglist) <option value="{{$druglist->id}}">{{$druglist->name}}</option> @endforeach </select> </div> Food Allergy <input type="checkbox" value="food" name="food" /> <div id="food"> <label>Allergy Name</label><br> <select multiple="multiple" class="form-control" name="foods[]" > <?php $foods = DB::table('allergies_type')->where('allergies_id',2)->get();?> @foreach($foods as $food) <option value="{{$food->id}}">{{$food->name}}</option> @endforeach </select> </div> Latex Allergy <input type="checkbox" value="latex" name="latex" /> <div id="latex"> <label>Allergy Name</label><br> <select multiple="multiple" class="form-control" name="latexs[]" > <?php $foods = DB::table('allergies_type')->where('allergies_id',3)->get();?> @foreach($foods as $food) <option value="{{$food->id}}">{{$food->name}}</option> @endforeach </select> </div> Mold Allergy <input type="checkbox" value="mold" name="molds" /> <div id="mold"> <label>Allergy Name</label><br> <select multiple="multiple" class="form-control" name="molds[]" > <?php $foods = DB::table('allergies_type')->where('allergies_id',4)->get();?> @foreach($foods as $food) <option value="{{$food->id}}">{{$food->name}}</option> @endforeach </select> </div> Pet Allergy <input type="checkbox" value="pet" name="pets" /> <div id="pet"> <label>Allergy Name</label><br> <select multiple="multiple" class="form-control" name="pets[]" > <?php $foods = DB::table('allergies_type')->where('allergies_id',5)->get();?> @foreach($foods as $food) <option value="{{$food->id}}">{{$food->name}}</option> @endforeach </select> </div> Pollen Allergy <input type="checkbox" value="pollen" name="pollens" /> <div id="pollen"> <label>Allergy Name</label><br> <select multiple="multiple" class="form-control" name="pollens[]" > <?php $foods = DB::table('allergies_type')->where('allergies_id',6)->get();?> @foreach($foods as $food) <option value="{{$food->id}}">{{$food->name}}</option> @endforeach </select> </div> Insect Allergy <input type="checkbox" value="insect" name="insects" /> <div id="insect"> <label>Allergy Name</label><br> <select multiple="multiple" class="form-control" name="insects[]" > <?php $foods = DB::table('allergies_type')->where('allergies_id',7)->get();?> @foreach($foods as $food) <option value="{{$food->id}}">{{$food->name}}</option> @endforeach </select> </div> </div> </div> <br> <div class="col-sm-6"> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover dataTables-example" > <thead> <tr> <th>No</th> <th>Allery Type</th> <th>Allery Name</th> <th>Date</th> </tr> </thead> <?php $i =1; $allergies=DB::table('afya_users_allergy') ->Join('allergies_type','allergies_type.id','=','afya_users_allergy.allergies_type_id') ->Join('allergies','allergies.id','=','allergies_type.allergies_id') ->select('allergies_type.name','allergies.name as Allergy','afya_users_allergy.created_at as dates') ->Where('afya_users_allergy.dependant_id','=',$id) ->get(); ?> <tbody> @foreach($allergies as $allergy) <tr> <td>{{$i}}</td> <td>{{$allergy->Allergy}}</td> <td>{{$allergy->name}}</td> <td>{{$allergy->dates}}</td> </tr> <?php $i++; ?> @endforeach </tbody> </table> </div> </div> </div> </fieldset> <h1>Disablility and Abnormalities</h1> <fieldset> <div class="row"> <div class="col-sm-6"> <?php $disabilities=DB::table('patient_disabilities')->where('id',$id)->get(); ?> <div class="form-group"> <label>Can suck/breastfeed</label> Yes <input type="checkbox" name="breastfeed" value="Yes" /> No <input type="checkbox" name="breastfeed" value="No" /> </div> <div class="form-group"> <label>Stiff neck</label> Yes <input type="checkbox" name="neck" value="Yes" /> No <input type="checkbox" name="neck" value="No" /> </div> <div class="form-group"> <label>Bulging fontanelle</label> Yes <input type="checkbox" name="fontanelle" value="Yes" /> No <input type="checkbox" name="fontanelle" value="No" /> </div> <div class="form-group"> <label>Irritable</label> Yes <input type="checkbox" name="irritable" value="Yes" /> No <input type="checkbox" name="irritable" value="No" /> </div> <div class="form-group"> <label>Reduced movement/tone</label> Yes <input type="checkbox" name="tone" value="Yes" /> No <input type="checkbox" name="tone" value="No" /> </div> <br> @if(!empty($disabilities)) <h1>Disabilities</h1> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover dataTables-example" > <thead> <tr> <th>No</th> <th>Disability</th> <th>Date</th> </tr> </thead> <?php $i =1; ?> <tbody> @foreach($disabilities as $dis) <tr> <td>{{$i}}</td> <td>{{$dis->name}}</td> <td>{{$dis->created_at}}</td> </tr> <?php $i++; ?> @endforeach </tbody> </table> </div> @endif </div> <div class="col-lg-6"> Skull <input type="checkbox" value="skull" name="skull" /> <div id="skull"> <label>Describe</label> <textarea name="skull_descr" class="form-control"></textarea> </div> Limbs <input type="checkbox" value="limbs" name="limbs" /> <div id="limbs"> <label>Describe</label> <textarea name="limbs_descr" class="form-control"></textarea> </div> Spine <input type="checkbox" value="spine" name="spine" /> <div id="spine"> <label>Describe</label> <textarea name="spine_descr" class="form-control"></textarea> </div> Palate <input type="checkbox" value="palate" name="palate" /> <div id="palate"> <label>Describe</label> <textarea name="palate_descr" class="form-control"></textarea> </div> Face <input type="checkbox" value="face" name="face" /> <div id="face"> <label>Describe</label> <textarea name="face_descr" class="form-control"></textarea> </div> Anus <input type="checkbox" value="anus" name="anus" /> <div id="anus"> <label>Describe</label> <textarea name="anus_descr" class="form-control"></textarea> </div> Dysmorphic <input type="checkbox" value="dysmorphic" name="dysmorphic" /> <div id="dysmorphic"> <label>Describe</label> <textarea name="dysmorphic_descr" class="form-control"></textarea> </div> <?php $abnormalities=DB::table('patient_abnormalities')->where('dependant_id',$id)->get();?> @if(!empty($abnormalities)) <h1>Abnormalities</h1> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover dataTables-example" > <thead> <tr> <th>No</th> <th>Abnormalities</th> <th>Description</th> <th>Date</th> </tr> </thead> <?php $i =1; ?> <tbody> @foreach($abnormalities as $ab) <tr> <td>{{$i}}</td> <td>{{$ab->name}}</td> <td>{{$ab->notes}}</td> <td>{{$ab->created_at}}</td> </tr> <?php $i++; ?> @endforeach </tbody> </table> </div> @endif </div> </div> </fieldset> <h1>Growth</h1> <fieldset> <div class="row"> <div class="col-sm-12"> <?php $nutritions=DB::table('dependant_nutrition_test')->where('dependant_id',$id)->get();?> @if(!empty($nutritions)) <h1>Growth</h1> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover dataTables-example" > <thead> <tr> <th>No</th> <th>Score</th> <th>MUAC</th> <th>Date</th> </tr> </thead> <?php $i =1; ?> <tbody> @foreach($nutritions as $nut) <tr> <td>{{$i}}</td> <td>{{$nut->score}}</td> <td><?php $score=$nut->score;?> @if($score<=110)<span class="btn-danger">{{"Severe Acute Malnutrition"}} </span> @elseif($score > 110 && $score <=125)<span class="btn-warning">{{"Moderate Acute Malnutrition"}}</span>@elseif($score > 125 && $score<=135)<span class="btn-info">{{"Growth Promotion and Monitoring"}}</span>@else<span class="btn-success">{{"Well Nourished"}}</span>@endif</td> <td>{{$nut->created_at}}</td> </tr> <?php $i++; ?> @endforeach </tbody> </table> </div> @endif <br> <div class="form-group"> <label for="exampleInputEmail1">MUAC Reading</label> <input type="number" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder=" in mm" name="muac" required> </div> </div> </div> </fieldset> <h1>Immunination Chart</h1> <fieldset> <div class="row"> <div class="col-sm-12"> <table class="table table-small-font table-bordered table-striped"> <thead> <tr> <th>Disease</th> <th>Antigen</th> <th>Duration</th> <th>Date Guideline</th> <th>Status</th> <th>Vaccination Date</th> <th></th> </tr> </thead> <?php $vaccines=DB::table('vaccine')->join('dependant_vaccination','dependant_vaccination.vaccine_id','=','vaccine.id')->distinct()->select('vaccine.*','dependant_vaccination.*','dependant_vaccination.id as id') ->where('vaccine.age','=>',$length) ->where('dependant_vaccination.dependent_id','=',$id)->get(); ?> <?php $i=1; ?> @foreach($vaccines as $vaccine) <tbody> <tr> <td>{{$vaccine->disease}}</td> <td>{{$vaccine->antigen}}</a></td> <td><?php $age=$vaccine->age; if($age==0){echo("Birth");} else if($age==42){echo("6 Weeks");} else if($age==70){echo("10 Weeks");} else if($age==98){echo("14 Weeks");} else if($age==183){echo("6 months");} else if($age==274){echo("9 months");} else if($age==335){echo("11 months");} else if($age==456){echo("15 months");} else if($age==730){echo("2 Years");}?></td> <td>{{date('d -m- Y', strtotime($vaccine->date_guideline))}}</td> <td>{{$vaccine->status or ''}}</td> <td>{{$vaccine->status_date or ''}}</td> <td><?php if(is_null($vaccine->status)){ echo "<select name='vaccines[]'> <option></option> <option value='<?php echo $vaccine->id;?>'>Done</option>"; } ?></td> <td style="display:none;"><input type="number" name="vaccines[]" value="{{$vaccine->id}}"></td> </tr> </tbody> <?php $i++ ?> @endforeach </table> </div> </div> </fieldset> <h1>Baby Vitals</h1> <fieldset> <h4> <label><u>Vitals</u></label></h4> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label>Difficulty Breathing</label> No <input type="checkbox" value="No" name="difficulty_breathing" /> Yes <input type="checkbox" value="Yes" name="difficulty_breathing" /> </div> <div class="form-group"> <label for="exampleInputEmail1">Diarrhoea</label> No<input type="checkbox" value="No_diarrhoea" name="diarrhoea" /> Yes <input type="checkbox" value="Yes_diarrhoea" name="diarrhoea" /> <div id="diarrhoea"> <label>Number of days</label> <input type="number" value="No" name="diarrhoea_days"/> <br> <label>Diarrhoea-Bloody</label> No <input type="checkbox" value="No" name="diarrhoea_bloody" /> Yes <input type="checkbox" value="Yes" name="diarrhoea_bloody" /> </div> </div> <div class="form-group"> <label>Vomiting ?</label> No <input type="checkbox" value="No_vomiting" name="vomiting" /> Yes <input type="checkbox" value="Yes_vomiting" name="vomiting" /> <div id="vomiting"> <label>number per 24 hours</label> <input type="number" name="vomiting_hours"/><br> <label>Vomits Everything?</label> No <input type="checkbox" value="No" name="vomits_eveything" /> Yes <input type="checkbox" value="Yes" name="vomits_eveything" /> </div> </div> <div class="form-group"> <label>Difficult Feeding?</label> No <input type="checkbox" value="No" name="feeding_difficult" /> Yes <input type="checkbox" value="Yes" name="feeding_difficult" /> </div> <div class="form-group"> <label>Convulsion</label> No <input type="checkbox" value="No_convulsion" name="convulsion" /> Yes <input type="checkbox" value="Yes_convulsion" name="convulsion" /> <div class="Yes_convulsion" style="display: none"> <label>number per 24 hours</label><br> <input type="number" name="convulsion_hours"/> </div> </div> <div class="form-group"> <label>Partial/Focal Fits?</label> No <input type="checkbox" value="No" name="fits" /> Yes <input type="checkbox" value="Yes" name="fits" /> </div> <div class="form-group"> <label>Apnoea?</label> No <input type="checkbox" value="No" name="apnoea" /> Yes <input type="checkbox" value="Yes" name="apnoea" /> </div> <h4> <label><U>Circulation</U></label></h4> <div class="form-group"> <label>Femoral Pulse</label> Normal <input type="checkbox" value="Normal" name="femoral_pulse"/> Weak <input type="checkbox" value="Weak" name="femoral_pulse"/> </div> <div class="form-group"> <label>Cap Refill</label> Possible <input type="checkbox" name="refill" value="possible" /> Not Possible <input type="checkbox" name="refill" value="notpossible"> <div id="refill"> <label>In Seconds</label> <input type="number" name="Seconds"> </div> </div> <div class="form-group"> <label>Murmur</label> Yes <input type="checkbox" name="Murmur" value="Murmur_Yes" /> No <input type="checkbox" name="Murmur" value="Murmur_No"> <div id="Murmur"> <label>Yes?</label> <input type="text" name="murmur_yes"> </div> </div> <div> <label>Pallor/Anaemia</label> 0 <input type="checkbox" name="pallor" value="0" /> + <input type="checkbox" name="pallor" value="+" /> +++ <input type="checkbox" name="pallor" value="+++" /> </div> <div class="form-group"> <label>Skin cold</label> Hand <input type="checkbox" name="skincold" value="Hand" /> Elbow <input type="checkbox" name="skincold" value="Elbow" /> Shoulder <input type="checkbox" name="skincold" value="Shoulder" /> </div> </div> <div class="col-lg-6"> <h4> <label><u>General Examination</u></label></h4> <div class="form-group"> <label for="exampleInputPassword1">Skin</label> Bruising <input type="checkbox" value="Bruising" name="skin"/> Rash <input type="checkbox" value="Rash" name="skin"/> Pustules <input type="checkbox" value="Pustules" name="skin"/> </div> <div class="form-group"> <label>Jaundice</label> None <input type="checkbox" value="None" name="jaundice"/> + <input type="checkbox" value="+" name="jaundice"/> +++ <input type="checkbox" value="+++" name="jaundice"/> </div> <div class="form-group"> <label>Gest/Size</label> Normal <input type="checkbox" value="Normal" name="gest_size"/> Perm <input type="checkbox" value="Perm" name="gest_size"/> SGA/wasted <input type="checkbox" value="SGA/wasted" name="gest_size"/> </div> <h4> <label><u>Umbilicus</u></label></h4> <div class="form-group"> <label>Umbilicus</label> Clean <input type="checkbox" value="Clean" name="umbilicus"/> Local Pus <input type="checkbox" value="LocalPus" name="umbilicus"/> Pus + red skin <input type="checkbox" value="Pus red skin " name="umbilicus"/> </div> <h4> <label><u>Airways & Breathing</u></label></h4> <div class="form-group"> <label for="exampleInputPassword1">Stridor</label> No <input type="checkbox" value="No" name="stridor"/> Yes <input type="checkbox" value="Yes" name="stridor"/> </div> <div class="form-group"> <label>Oxygen Saturation (enter(represent this in %)</label> <input type="text" name="oxygen_saturation" class="form-control"> </div> <div class="form-group"> <label>Central Cyanosis</label> No <input type="checkbox" value="No" name="cyanosis"/> Yes <input type="checkbox" value="Yes" name="cyanosis"/> </div> <div class="form-group"> <label>InDrawing</label> None <input type="checkbox" name="indrawing" value="None"> Severe <input type="checkbox" name="indrawing" value="Severe"> Sternum <input type="checkbox" name="indrawing" value="Sternum"> </div> <div class="form-group"> <label for="exampleInputPassword1">Grunting</label> No <input type="checkbox" value="No" name="grunting"/> Yes <input type="checkbox" value="Yes" name="grunting"/> </div> <div class="form-group"> <label for="exampleInputPassword1">Air Entry Bilateral</label> No <input type="checkbox" value="No" name="air_entry"/> Yes <input type="checkbox" value="Yes" name="air_entry"/> </div> <div class="form-group"> <label>Crackles</label> No <input type="checkbox" value="No" name="crackles"/> Yes <input type="checkbox" value="Yes" name="crackles"/> </div> <div class="form-group"> <label>Cry</label> Normal <input type="checkbox" value="No" name="cry"/> Hoarse <input type="checkbox" value="Yes" name="cry"/> Weak <input type="checkbox" value="Yes" name="cry"/> </div> </div> </div> </fieldset> <h1>Other Vitals</h1> <fieldset> <div class="col-lg-8 col-lg-offset-2"> <h4> <label><u>Other Vitals</u></label></h4> <div class="form-group"> <label for="exampleInputEmail1">Weight</label> <input type="name" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Weight" name="weight" required> </div> <div class="form-group"> <label for="exampleInputEmail1">Height</label> <input type="name" class="form-control" placeholder="Height in Metres" name="current_height" required> </div> <div class="form-group"> <label for="exampleInputEmail1">Head Head Measurement</label> <input type="name" class="form-control" placeholder="" name="cir"> </div> <div class="form-group"> <label for="exampleInputPassword1">Systolic BP</label> <input type="name" class="form-control" id="exampleInputPassword1" placeholder="Systolic BP" name="systolic" required> </div> <div class="form-group"> <label for="exampleInputEmail1">Diastolic BP</label> <input type="name" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Diastolic BP" name="diastolic" required> </div> <label for="exampleInputPassword1">Pregnant?</label> <div> <input type="radio" value="No" name="pregnant"> No <input type="radio" value="Yes" name="pregnant"> Yes</div> <div class="form-group" id="data_1"> <label for="exampleInputPassword1">LMP</label> <div class="input-group date"> <span class="input-group-addon"><i class="fa fa-calendar"></i></span> <input type="text" class="form-control" name="lmp" value=""> </div> </div> <div class="form-group"> <label >Chief Complaint/Reason for visit:</label> <select multiple="multiple" id="chief" name="chiefcompliants[]" class="form-control chief" style="width:50%" required></select> </div> <!--<div class="form-group"> <label for="exampleInputPassword1">Observation</label> <select multiple="multiple" class="form-control" name="observations[]" id="observation" > @foreach($observations as $observation) <option value="{{$observation->name}}">{{$observation->name}}</option> @endforeach </select> </div>--> <div class="form-group"> <label >Observation:</label> <select multiple="multiple" id="observation" name="observations[]" class="form-control observation" style="width:50%" required></select> </div> <div class="form-group"> <label >Symptom:</label> <select multiple="multiple" id="symptom" name="symptoms[]" class="form-control symptom" style="width:50%" required></select> </div> <div class="form-group"> <label for="exampleInputPassword1">Nurse Notes</label> <textarea class="form-control" placeholer="" name="nurse" required> </textarea> </div> <div class="form-group"> <label for="exampleInputEmail1">Consulting Physician</label> <select class="form-control" name="doctor" > <?php $facilitycode=DB::table('facility_nurse')->where('user_id', Auth::id())->first(); $doctors = DB::table('users')-> join('facility_doctor','facility_doctor.user_id','=','users.id') ->select('facility_doctor.*','users.name as name')->Where('facility_doctor.facilitycode',$facilitycode->facilitycode)->where('users.role','=','Doctor')->get();?> @foreach($doctors as $doctor) <option value="{{$doctor->doctor_id}}">{{$doctor->name}}</option> @endforeach </select> </div> </div> </fieldset> </form> </div> </div> </div> </div> <div class="footer"> <div class="pull-right"> Afyapepe <strong>Health</strong> Platform. </div> <div> <strong>Copyright</strong> afyapepe.co.ke &copy; 2016-2017 </div> </div> </div> </div> <!-- Mainly scripts --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="{{asset('js/ajaxscript.js')}}"></script> <script src="{{ asset('js/app.js') }}" type="text/javascript"></script> <!-- Mainly scripts --> <script src="{{ asset('js/jquery-3.1.1.min.js') }}" type="text/javascript"></script> <script src="{{ asset('js/bootstrap.min.js') }}" type="text/javascript"></script> <script src="{{ asset('js/plugins/metisMenu/jquery.metisMenu.js') }}" type="text/javascript"></script> <script src="{{ asset('js/plugins/steps/jquery.steps.min.js') }}"></script> <script src="{{ asset('js/plugins/validate/jquery.validate.min.js') }}"></script> <script src="{{ asset('js/plugins/datapicker/bootstrap-datepicker.js') }}" type="text/javascript"></script> <script src="{{ asset('js/plugins/datapicker/bootstrap-datepicker.js') }}" type="text/javascript"></script> <script src="{{asset('js/ajaxscript.js')}}"></script> <!-- Custom and plugin javascript --> <!-- Custom and plugin javascript --> <script src="{{ asset('js/plugins/pace/pace.min.js') }}" type="text/javascript"></script> <script src="{{ asset('select/select2.min.js') }}" type="text/javascript"></script> <!-- <script src="{{ asset('js/inspinia.js') }}" type="text/javascript"></script>--> <!-- Page-Level Scripts --> <script type="text/javascript"> $(document).ready(function(){ $('.multi-field-wrapper').each(function() { var $wrapper = $('.multi-fields', this); $(".add-field", $(this)).click(function(e) { $('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus(); }); $('.multi-field .remove-field', $wrapper).click(function() { if ($('.multi-field', $wrapper).length > 1) $(this).parent('.multi-field').remove(); }); }); }); </script> <script> $(document).ready(function(){ $("#wizard").steps(); $("#form").steps({ bodyTag: "fieldset", onStepChanging: function (event, currentIndex, newIndex) { // Always allow going backward even if the current step contains invalid fields! if (currentIndex > newIndex) { return true; } // Forbid suppressing "Warning" step if the user is to young if (newIndex === 3 && Number($("#age").val()) < 18) { return true; } var form = $(this); // Clean up if user went backward before if (currentIndex < newIndex) { // To remove error styles $(".body:eq(" + newIndex + ") label.error", form).remove(); $(".body:eq(" + newIndex + ") .error", form).removeClass("error"); } // Disable validation on fields that are disabled or hidden. form.validate().settings.ignore = ":disabled,:hidden"; // Start validation; Prevent going forward if false return form.valid(); }, onFinishing: function (event, currentIndex) { var form = $(this); // Disable validation on fields that are disabled. // At this point it's recommended to do an overall check (mean ignoring only disabled fields) form.validate().settings.ignore = ":disabled"; // Start validation; Prevent form submission if false return form.valid(); }, onFinished: function (event, currentIndex) { var form = $(this); // Submit form input form.submit(); } }); $.ajaxSetup({ headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') } }); $(".presc1").select2({ placeholder: "Select revelant drugs...", minimumInputLength: 2, ajax: { url: '/tag/drugs', dataType: 'json', data: function (params) { return { q: $.trim(params.term) }; }, processResults: function (data) { return { results: data }; }, cache: true } }); $(".observation").select2({ placeholder: "Select observations...", minimumInputLength: 2, ajax: { url: '/tag/observation', dataType: 'json', data: function (params) { return { q: $.trim(params.term) }; }, processResults: function (data) { return { results: data }; }, cache: true } }); $(".symptom").select2({ placeholder: "Select symptom...", minimumInputLength: 2, ajax: { url: '/tag/symptom', dataType: 'json', data: function (params) { return { q: $.trim(params.term) }; }, processResults: function (data) { return { results: data }; }, cache: true } }); $(".chief").select2({ placeholder: "Select chief compliant...", minimumInputLength: 2, ajax: { url: '/tag/chief', dataType: 'json', data: function (params) { return { q: $.trim(params.term) }; }, processResults: function (data) { return { results: data }; }, cache: true } }); }); </script> <script type="text/javascript"> $(document).ready(function(){ $("#embedcode").hide(); $("#hiv").hide(); $("#tb").hide(); $("#drug").hide(); $("#food").hide(); $("#latex").hide(); $("#mold").hide(); $("#pet").hide(); $("#pollen").hide(); $("#insect").hide(); $("#skull").hide(); $("#limbs").hide(); $("#spine").hide(); $("#palate").hide(); $("#face").hide(); $("#anus").hide(); $("#dysmorphic").hide(); $("#diarrhoea").hide(); $("#vomiting").hide(); $("#refill").hide(); $("#Murmur").hide(); $("input[name='bba']").change(function () { if($(this).val() == "Yes") $("#embedcode").show(); else $("#embedcode").hide(); }); $("input[name='hiv']").change(function () { if($(this).val() == "Positive") $("#hiv").show(); else $("#hiv").hide(); }); $("input[name='tb']").change(function () { if($(this).val() == "Yes") $("#tb").show(); else $("#tb").hide(); }); $("input[name='drug']").change(function () { $("#drug").toggle(this.checked); }); $("input[name='food']").change(function () { $("#food").toggle(this.checked); }); $("input[name='latex']").change(function () { $("#latex").toggle(this.checked); }); $("input[name='molds']").change(function () { $("#mold").toggle(this.checked); }); $("input[name='pets']").change(function () { $("#pet").toggle(this.checked); }); $("input[name='pollens']").change(function () { $("#pollen").toggle(this.checked); }); $("input[name='insects']").change(function () { $("#insect").toggle(this.checked); }); $("input[name='skull']").change(function () { $("#skull").toggle(this.checked); }); $("input[name='limbs']").change(function () { $("#limbs").toggle(this.checked); }); $("input[name='spine']").change(function () { $("#spine").toggle(this.checked); }); $("input[name='palate']").change(function () { $("#palate").toggle(this.checked); }); $("input[name='face']").change(function () { $("#face").toggle(this.checked); }); $("input[name='anus']").change(function () { $("#anus").toggle(this.checked); }); $("input[name='dysmorphic']").change(function () { $("#dysmorphic").toggle(this.checked); }); $("input[name='diarrhoea']").change(function () { if($(this).val() == "Yes_diarrhoea") $("#diarrhoea").show(); else $("#diarrhoea").hide(); }); $("input[name='vomiting']").change(function () { if($(this).val() == "Yes_vomiting") $("#vomiting").show(); else $("#vomiting").hide(); }); $("input[name='refill']").change(function () { if($(this).val() == "possible") $("#refill").show(); else $("#refill").hide(); }); $("input[name='Murmur']").change(function () { if($(this).val() == "Murmur_Yes") $("#Murmur").show(); else $("#Murmur").hide(); }); $('input[type="checkbox"]').on('change', function() { $('input[name="' + this.name + '"]').not(this).prop('checked', false); }); $('#data_1 .input-group.date').datepicker({ todayBtn: "linked", keyboardNavigation: false, forceParse: false, calendarWeeks: true, autoclose: true, format: 'yyyy-mm-dd', }); $(document).ready(function(){ $("button").click(function(){ $("#testR").toggle(); }); }); }); </script> </script> </body> </html>
38.169556
394
0.498361
c6fc0309875d16f38a6c60c663a5c876654dd0b5
661
rb
Ruby
server/app/graphql/mutations/api_key_mutations/create_api_key.rb
harehare/rackany
8a921ce97634620563a8de8948787f1e891f5cef
[ "MIT" ]
null
null
null
server/app/graphql/mutations/api_key_mutations/create_api_key.rb
harehare/rackany
8a921ce97634620563a8de8948787f1e891f5cef
[ "MIT" ]
7
2021-09-05T13:54:57.000Z
2021-09-15T14:23:09.000Z
server/app/graphql/mutations/api_key_mutations/create_api_key.rb
harehare/rackany
8a921ce97634620563a8de8948787f1e891f5cef
[ "MIT" ]
null
null
null
module Mutations module ApiKeyMutations class CreateApiKey < Mutations::AuthMutation include Authorization argument :project_id, ID, required: true argument :name, String, required: true argument :role, Types::Enum::Role, required: true type Types::ApiKeyType def resolve(project_id:, name:, role:) authenticate_owner!(context, project_id) api_key = ApiKey.new({ project_id: project_id, name: name, role: role }) raise GraphqlErrors::InputError, 'invalid parameter' unless api_key.save api_key end end end end
28.73913
80
0.615734
dae7d99a7d2f547a5d6eb138887a47780a338a42
5,874
ts
TypeScript
packages/connector/src/ts/api/api.ts
blinkk/editor
d8a7d5e20698d67d2747719bbb2e6e1f1ea5e3a7
[ "MIT" ]
null
null
null
packages/connector/src/ts/api/api.ts
blinkk/editor
d8a7d5e20698d67d2747719bbb2e6e1f1ea5e3a7
[ "MIT" ]
null
null
null
packages/connector/src/ts/api/api.ts
blinkk/editor
d8a7d5e20698d67d2747719bbb2e6e1f1ea5e3a7
[ "MIT" ]
1
2022-02-10T20:36:26.000Z
2022-02-10T20:36:26.000Z
import { ApiError, DeviceData, EditorFileData, EmptyData, FileData, ProjectData, PublishResult, WorkspaceData, } from '@blinkk/editor.dev-ui/dist/editor/api'; import {ErrorReporting} from '@google-cloud/error-reporting'; import {ProjectTypeStorageComponent} from '../storage/storage'; import express from 'express'; const MODE = process.env.MODE || 'dev'; const errorReporting = new ErrorReporting({ reportMode: MODE === 'prod' ? 'always' : 'never', }); export interface ApiBaseComponent { apiRouter: express.Router; } export interface ApiComponent extends ApiBaseComponent { copyFile( expressRequest: express.Request, expressResponse: express.Response, request: CopyFileRequest ): Promise<FileData>; createFile( expressRequest: express.Request, expressResponse: express.Response, request: CreateFileRequest ): Promise<FileData>; createWorkspace( expressRequest: express.Request, expressResponse: express.Response, request: CreateWorkspaceRequest ): Promise<WorkspaceData>; deleteFile( expressRequest: express.Request, expressResponse: express.Response, request: DeleteFileRequest ): Promise<EmptyData>; getDevices( expressRequest: express.Request, expressResponse: express.Response, request: GetDevicesRequest ): Promise<Array<DeviceData>>; getFile( expressRequest: express.Request, expressResponse: express.Response, request: GetFileRequest ): Promise<EditorFileData>; getFiles( expressRequest: express.Request, expressResponse: express.Response, request: GetFilesRequest ): Promise<Array<FileData>>; getProject( expressRequest: express.Request, expressResponse: express.Response, request: GetProjectRequest ): Promise<ProjectData>; getWorkspace( expressRequest: express.Request, expressResponse: express.Response, request: GetWorkspaceRequest ): Promise<WorkspaceData>; getWorkspaces( expressRequest: express.Request, expressResponse: express.Response, request: GetWorkspacesRequest ): Promise<Array<WorkspaceData>>; publish( expressRequest: express.Request, expressResponse: express.Response, request: PublishRequest ): Promise<PublishResult>; saveFile( expressRequest: express.Request, expressResponse: express.Response, request: SaveFileRequest ): Promise<EditorFileData>; uploadFile( expressRequest: express.Request, expressResponse: express.Response, request: UploadFileRequest ): Promise<FileData>; } /** * Method for retrieving the storage component. * * Different services require different ways to manage the storage component. * To keep things consistent, allow the service to determine the best way * to retrieve the service component. */ export type GetStorage = ( expressRequest: express.Request, expressResponse: express.Response ) => Promise<ProjectTypeStorageComponent>; export interface CopyFileRequest { originalPath: string; path: string; } export interface CreateFileRequest { path: string; content?: string; } export interface CreateWorkspaceRequest { base: WorkspaceData; workspace: string; } export interface DeleteFileRequest { file: FileData; } // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface GetDevicesRequest {} export interface GetFileRequest { file: FileData; } // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface GetFilesRequest {} // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface GetProjectRequest {} // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface GetWorkspaceRequest {} export interface GetWorkspacesRequest { org?: string; repo?: string; } // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface PingRequest {} export interface PublishRequest { workspace: WorkspaceData; data?: Record<string, any>; } export interface SaveFileRequest { file: EditorFileData; isRawEdit: boolean; } export interface UploadFileRequest { file: File; options?: Record<string, any>; } export class GenericApiError extends Error { apiError: ApiError; constructor(message: string, apiError: ApiError) { super(message); this.name = 'ApiError'; this.apiError = apiError; this.stack = (<any>new Error()).stack; } } /** * Shortcut for adding an api route to the router with error handling * to keep the api result in a consistent format. * * @param router Router for api. * @param route Route path for the endpoint. * @param apiMethod Method to handle the request. */ export function addApiRoute( router: express.Router, route: string, apiMethod: ( req: express.Request, res: express.Response, request: any ) => Promise<any> ): void { router.post(route, (req, res) => { apiMethod(req, res, req.body) .then(response => res.json(response)) .catch(err => apiErrorHandler(err, req, res)); }); } export function apiErrorHandler( err: any, // eslint-disable-next-line @typescript-eslint/no-unused-vars req: express.Request, res: express.Response, // eslint-disable-next-line @typescript-eslint/no-unused-vars next?: express.NextFunction ) { // Cloud error reporting errorReporting.report(err); console.error(err); res.status(500); if (err.apiError) { // Handle as an GenericApiError response. res.json((err as GenericApiError).apiError); } else if (err.message && err.description) { // Handle as an ApiError response. res.json(err as ApiError); } else if (err.name === 'ApiError') { // Handle as an ApiError response. res.json((err as GenericApiError).apiError); } else { // Handle as a generic error. res.json({ message: err.message || err, } as ApiError); } }
24.475
77
0.72523
bb563646bd6f0e3549290a2356e7b271807f5b7c
1,867
cs
C#
code/NAP_2017-12-16/Library/Collab/Base/Assets/Scripts/PlayerController.cs
AdrianSchneble/nap
790abb7963d471093e46133e1ce95c38cef58d77
[ "MIT" ]
2
2017-10-25T07:11:10.000Z
2017-11-05T15:05:00.000Z
code/NAP_2017-12-16/Library/Collab/Base/Assets/Scripts/PlayerController.cs
AdrianSchneble/nap
790abb7963d471093e46133e1ce95c38cef58d77
[ "MIT" ]
12
2017-10-04T10:23:10.000Z
2017-11-29T10:42:21.000Z
code/NAP_2017-12-16/Library/Collab/Base/Assets/Scripts/PlayerController.cs
AdrianSchneble/nap
790abb7963d471093e46133e1ce95c38cef58d77
[ "MIT" ]
2
2017-11-15T07:41:13.000Z
2018-06-11T06:55:52.000Z
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float speed = 0.1f; public int roomSize = 20; public GameObject groundTile; public GameObject wallTile; public GameObject doorTile; // Use this for initialization void Start () { for (int multipleRooms = 0; multipleRooms < 2; multipleRooms++) { int offset = multipleRooms * (roomSize - 1); //TODO: this is prototyping shit. Don't leave it like this! for (int column = 0; column < roomSize; column++) { int lastTileIndex = roomSize - 1; for (int row = 0; row < roomSize; row++) { int doorTileNum = (roomSize % 2 == 0) ? -1 : (roomSize - 1) / 2; bool isDoor = row == doorTileNum || column == doorTileNum; //TODO bool isWall = column == 0 || column == lastTileIndex || row == 0 || row == lastTileIndex; if (isWall && isDoor) { Instantiate(doorTile, new Vector3(column - 5 + offset, row - 5, 1), new Quaternion()); } else if (isWall) { Instantiate(wallTile, new Vector3(column - 5 + offset, row - 5, 1), new Quaternion()); } else // is ground { Instantiate(groundTile, new Vector3(column - 5 + offset, row - 5, 1), new Quaternion()); } } } } } // Update is called once per frame void Update () { float x = Input.GetAxis("Horizontal") * speed; float y = Input.GetAxis("Vertical") * speed; transform.Translate(new Vector3(x, y)); } }
34.574074
119
0.504553
0b5888dd9b27a8e021f960afa63814a58b88b7c2
2,565
swift
Swift
GBMChallengeiOS/Sources/GBMChallengeiOS/IPCFeed/View/Cells/LatestValueCell.swift
Aldoukfm/GBM_Challenge
e49815d69989a2ce0b5cb2ddc82728118d9faafa
[ "MIT" ]
null
null
null
GBMChallengeiOS/Sources/GBMChallengeiOS/IPCFeed/View/Cells/LatestValueCell.swift
Aldoukfm/GBM_Challenge
e49815d69989a2ce0b5cb2ddc82728118d9faafa
[ "MIT" ]
null
null
null
GBMChallengeiOS/Sources/GBMChallengeiOS/IPCFeed/View/Cells/LatestValueCell.swift
Aldoukfm/GBM_Challenge
e49815d69989a2ce0b5cb2ddc82728118d9faafa
[ "MIT" ]
null
null
null
import UIKit import Combine import CombineHelpers public class LatestValueCell: UICollectionViewCell, ReuseIdentifiableView { private(set) public var priceLbl: UILabel! = { let lbl = UILabel() lbl.font = Fonts.headline lbl.textColor = Colors.primaryText lbl.translatesAutoresizingMaskIntoConstraints = false return lbl }() private(set) public var changeImg: UIImageView! = { let img = UIImageView() img.contentMode = UIView.ContentMode.scaleAspectFit img.translatesAutoresizingMaskIntoConstraints = false return img }() private(set) public var changeLbl: UILabel! = { let lbl = UILabel() lbl.font = Fonts.normalText lbl.setContentHuggingPriority(.defaultHigh, for: .vertical) lbl.translatesAutoresizingMaskIntoConstraints = false return lbl }() private(set) public var dateLbl: UILabel! = { let lbl = UILabel() lbl.font = Fonts.normalText lbl.textColor = Colors.primaryText lbl.translatesAutoresizingMaskIntoConstraints = false return lbl }() override init(frame: CGRect) { super.init(frame: frame) setupLayout() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError() } private func setupLayout() { let changeContainer = UIStackView(arrangedSubviews: [changeImg, changeLbl]) changeContainer.translatesAutoresizingMaskIntoConstraints = false changeContainer.axis = .horizontal changeContainer.alignment = .center changeContainer.spacing = 2 changeImg.constraintHeightTo(changeLbl, constant: -5) let verticalStack = UIStackView(arrangedSubviews: [priceLbl, changeContainer, dateLbl]) verticalStack.axis = .vertical verticalStack.alignment = .center verticalStack.spacing = 4 verticalStack.setCustomSpacing(3, after: priceLbl) verticalStack.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(verticalStack) verticalStack.constraintTo(contentView, attributes: [.left, .right, .centerY]) } func bind(viewModel: LatestValueViewModel) { priceLbl.text = viewModel.price changeLbl.text = viewModel.change changeLbl.textColor = viewModel.changeColor changeImg.image = viewModel.changeIcon dateLbl.text = viewModel.date } }
31.280488
95
0.650292
6b918dcfb7b67da69ced9db68ddbb1eb925f057a
574
js
JavaScript
src/main.js
lucklcy/hello_vue
fbc4e7f6fe24fb43fba2547c32dfbdd8f039f8ff
[ "MIT" ]
null
null
null
src/main.js
lucklcy/hello_vue
fbc4e7f6fe24fb43fba2547c32dfbdd8f039f8ff
[ "MIT" ]
null
null
null
src/main.js
lucklcy/hello_vue
fbc4e7f6fe24fb43fba2547c32dfbdd8f039f8ff
[ "MIT" ]
null
null
null
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import ElementUI from "element-ui"; import "element-ui/lib/theme-chalk/index.css"; // 浏览器默认样式重置 import "normalize.css/normalize.css"; import "@/assets/less/common.less"; // 调用接口封装 import api from "@/service"; Vue.config.productionTip = false; // mock 数据 if (process.env.VUE_APP_MOCK === "yes") require("@/service/mock"); Vue.use(ElementUI, { size: "mini", zIndex: 3000 }); // 将调用接口的函数扩展到每个组件中 Vue.prototype.$http = api; new Vue({ router, render: (h) => h(App), }).$mount("#app");
20.5
66
0.6777
522ccaf29192b9804c7218344ccc2f6aa09d8c68
4,284
go
Go
int_formatter.go
glossina/go-format
5114c47d6db14d23e5ab1d9089c82c6e5e29a50a
[ "MIT" ]
16
2018-01-16T08:23:51.000Z
2022-01-26T09:53:15.000Z
int_formatter.go
glossina/go-format
5114c47d6db14d23e5ab1d9089c82c6e5e29a50a
[ "MIT" ]
1
2019-01-21T19:55:24.000Z
2019-01-21T19:55:24.000Z
int_formatter.go
glossina/go-format
5114c47d6db14d23e5ab1d9089c82c6e5e29a50a
[ "MIT" ]
2
2019-09-09T08:21:24.000Z
2021-08-10T20:51:24.000Z
package format import ( "fmt" "strings" ) // intFormatter formats int type intFormatter struct { value int } // Clarify ... func (f intFormatter) Clarify(a string) (Formatter, error) { if len(strings.TrimSpace(a)) != 0 { return f, fmt.Errorf("No clarification available for int8 formatter") } return f, nil } // Format ... func (f intFormatter) Format(a string) (string, error) { return fmt.Sprintf("%"+a+"d", f.value), nil } // uintFormatter formats uint type uintFormatter struct { value uint } // Clarify ... func (f uintFormatter) Clarify(a string) (Formatter, error) { if len(strings.TrimSpace(a)) != 0 { return f, fmt.Errorf("No clarification available for uint8 formatter") } return f, nil } // Format ... func (f uintFormatter) Format(a string) (string, error) { return fmt.Sprintf("%"+a+"d", f.value), nil } // i8Formatter ... type i8Formatter struct { value int8 } // Clarify formatter implementation func (f i8Formatter) Clarify(a string) (Formatter, error) { if len(strings.TrimSpace(a)) != 0 { return f, fmt.Errorf("No clarification available for int8 formatter") } return f, nil } // Format formatter implementation func (f i8Formatter) Format(a string) (string, error) { return fmt.Sprintf("%"+a+"d", f.value), nil } // i16Formatter ... type i16Formatter struct { value int16 } // Clarify formatter implementation func (f i16Formatter) Clarify(a string) (Formatter, error) { if len(strings.TrimSpace(a)) != 0 { return f, fmt.Errorf("No clarification available for int16 formatter") } return f, nil } // Format formatter implementation func (f i16Formatter) Format(a string) (string, error) { return fmt.Sprintf("%"+a+"d", f.value), nil } // i32Formatter ... type i32Formatter struct { value int32 } // Clarify formatter implementation func (f i32Formatter) Clarify(a string) (Formatter, error) { if len(strings.TrimSpace(a)) != 0 { return f, fmt.Errorf("No clarification available for int32 formatter") } return f, nil } // Format formatter implementation func (f i32Formatter) Format(a string) (string, error) { return fmt.Sprintf("%"+a+"d", f.value), nil } // i64Formatter ... type i64Formatter struct { value int64 } // Clarify formatter implementation func (f i64Formatter) Clarify(a string) (Formatter, error) { if len(strings.TrimSpace(a)) != 0 { return f, fmt.Errorf("No clarification available for int64 formatter") } return f, nil } // Format formatter implementation func (f i64Formatter) Format(a string) (string, error) { return fmt.Sprintf("%"+a+"d", f.value), nil } // u8Formatter ... type u8Formatter struct { value uint8 } // Clarify formatter implementation func (f u8Formatter) Clarify(a string) (Formatter, error) { if len(strings.TrimSpace(a)) != 0 { return f, fmt.Errorf("No clarification available for uint8 formatter") } return f, nil } // Format formatter implementation func (f u8Formatter) Format(a string) (string, error) { return fmt.Sprintf("%"+a+"d", f.value), nil } // u16Formatter ... type u16Formatter struct { value uint16 } // Clarify formatter implementation func (f u16Formatter) Clarify(a string) (Formatter, error) { if len(strings.TrimSpace(a)) != 0 { return f, fmt.Errorf("No clarification available for uint16 formatter") } return f, nil } // Format formatter implementation func (f u16Formatter) Format(a string) (string, error) { return fmt.Sprintf("%"+a+"d", f.value), nil } // u32Formatter ... type u32Formatter struct { value uint32 } // Clarify formatter implementation func (f u32Formatter) Clarify(a string) (Formatter, error) { if len(strings.TrimSpace(a)) != 0 { return f, fmt.Errorf("No clarification available for uint32 formatter") } return f, nil } // Format formatter implementation func (f u32Formatter) Format(a string) (string, error) { return fmt.Sprintf("%"+a+"d", f.value), nil } // u64Formatter ... type u64Formatter struct { value uint64 } // Clarify formatter implementation func (f u64Formatter) Clarify(a string) (Formatter, error) { if len(strings.TrimSpace(a)) != 0 { return f, fmt.Errorf("No clarification available for uint64 formatter") } return f, nil } // Format formatter implementation func (f u64Formatter) Format(a string) (string, error) { return fmt.Sprintf("%"+a+"d", f.value), nil }
22.909091
73
0.703548
d177770206d1f41948b5243808d73d23a1ff9ae6
1,468
dart
Dart
lib/sensing/audio_user_task.dart
cph-cachet/pulmonary_monitor_app
b56081cd13076ed3249c55abdfb3e5229cf7c6c3
[ "MIT" ]
3
2020-12-29T21:05:57.000Z
2022-01-25T06:19:19.000Z
lib/sensing/audio_user_task.dart
cph-cachet/pulmonary_monitor_app
b56081cd13076ed3249c55abdfb3e5229cf7c6c3
[ "MIT" ]
1
2021-09-08T21:53:12.000Z
2021-09-08T21:53:12.000Z
lib/sensing/audio_user_task.dart
cph-cachet/pulmonary_monitor_app
b56081cd13076ed3249c55abdfb3e5229cf7c6c3
[ "MIT" ]
1
2021-08-07T03:41:06.000Z
2021-08-07T03:41:06.000Z
part of pulmonary_monitor_app; /// A user task handling audio recordings. /// When started, creates a [AudioMeasurePage] and shows it to the user. class AudioUserTask extends UserTask { static const String AUDIO_TYPE = 'audio'; StreamController<int> _countDownController = StreamController.broadcast(); Stream<int> get countDownEvents => _countDownController.stream; /// Duration of audio recording in seconds. int recordingDuration = 10; AudioUserTask(AppTaskExecutor executor) : super(executor); @override void onStart(BuildContext context) { super.onStart(context); Navigator.push( context, MaterialPageRoute( builder: (context) => AudioMeasurePage(audioUserTask: this)), ); } /// Callback when recording is to start. void onRecord() { executor.resume(); Timer.periodic(new Duration(seconds: 1), (timer) { _countDownController.add(--recordingDuration); if (recordingDuration == 0) { timer.cancel(); _countDownController.close(); executor.pause(); state = UserTaskState.done; } }); } } class PulmonaryUserTaskFactory implements UserTaskFactory { List<String> types = [ AudioUserTask.AUDIO_TYPE, ]; UserTask create(AppTaskExecutor executor) { switch (executor.appTask.type) { case AudioUserTask.AUDIO_TYPE: return AudioUserTask(executor); default: return SensingUserTask(executor); } } }
25.310345
76
0.686649
7f79fabc88a2e3c776c3135a1cb1da87abea0b82
511
php
PHP
src/ForumBundle/Repository/AnswerRepository.php
BlackOut-Team/ScrumifyApi
08c4e03a4bd51dfdf28472ab4e91974c39a020eb
[ "MIT" ]
1
2020-05-11T20:02:50.000Z
2020-05-11T20:02:50.000Z
src/ForumBundle/Repository/AnswerRepository.php
BlackOut-Team/ScrumifyApi
08c4e03a4bd51dfdf28472ab4e91974c39a020eb
[ "MIT" ]
null
null
null
src/ForumBundle/Repository/AnswerRepository.php
BlackOut-Team/ScrumifyApi
08c4e03a4bd51dfdf28472ab4e91974c39a020eb
[ "MIT" ]
null
null
null
<?php namespace ForumBundle\Repository; /** * AnswerRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class AnswerRepository extends \Doctrine\ORM\EntityRepository { public function countForUser($user){ return $this->createQueryBuilder('q') ->SELECT('COUNT(q.id)') ->where('q.User = :user') ->setParameter('user' , $user) ->getQuery() ->getSingleScalarResult(); } }
23.227273
68
0.616438
b0e64cb24385e65387ee2e5a8c3e52d4bc8cf92b
457
swift
Swift
Example/SuitUpExample/View/Button+Stylable.swift
wupdigital/SuitUp
c49984612e7c8e7f535f00b80f59d3e627dfdf35
[ "Apache-2.0" ]
3
2020-09-04T16:44:13.000Z
2020-09-04T16:44:39.000Z
Example/SuitUpExample/View/Button+Stylable.swift
wupdigital/SuitUp
c49984612e7c8e7f535f00b80f59d3e627dfdf35
[ "Apache-2.0" ]
3
2020-09-02T08:00:23.000Z
2020-09-02T13:42:30.000Z
Example/SuitUpExample/View/Button+Stylable.swift
wupdigital/SuitUp
c49984612e7c8e7f535f00b80f59d3e627dfdf35
[ "Apache-2.0" ]
null
null
null
// // Button+Stylable.swift // SuitUpExample // // Created by Dávid Széles-Szép on 2020. 09. 01.. // Copyright © 2020. W.UP. All rights reserved. // import UIKit @objc extension UIButton { var normalTitleColor: UIColor? { get { titleColor(for: .normal) } set { setTitleColor(newValue, for: .normal) } } var titleFont: UIFont? { get { titleLabel?.font } set { titleLabel?.font = newValue } } }
19.041667
53
0.595186
b13b0c5c1b01745f79be3797f678242f65c55946
1,532
py
Python
colors.py
xnaas/custom-bot-commands
c9acf602fa69ea62750af12a204a15982da2ff98
[ "Unlicense" ]
null
null
null
colors.py
xnaas/custom-bot-commands
c9acf602fa69ea62750af12a204a15982da2ff98
[ "Unlicense" ]
null
null
null
colors.py
xnaas/custom-bot-commands
c9acf602fa69ea62750af12a204a15982da2ff98
[ "Unlicense" ]
null
null
null
""" Authors: dgw (2020-2021), xnaas (2020-2022) Fork: https://github.com/xnaas/sopel-color-text Source: https://github.com/sopel-irc/sopel-rainbow License: Eiffel Forum License, version 2 """ import itertools import unicodedata from sopel import plugin from sopel.formatting import color, plain COLOR_SCHEMES = { 'rainbow': [4, 7, 8, 3, 12, 2, 6], 'usa': [4, 0, 2], 'commie': [4, 8], 'spooky': [8, 7, 0], } SCHEME_ERRORS = { 'rainbow': "I can't make a rainbow out of nothing!", 'usa': "I can't distribute FREEDOM out of nothing!", 'commie': "I need text to commie-ize!", 'spooky': "I need text to spookify!", } @plugin.commands('rainbow', 'usa', 'commie', 'spooky') def rainbow_cmd(bot, trigger): """Make text colored. Options are 'rainbow', 'usa', 'commie', and 'spooky'.""" text = plain(trigger.group(2) or '') scheme = trigger.group(1).lower() if not text: return bot.reply(SCHEME_ERRORS[scheme]) try: colors = COLOR_SCHEMES[scheme] except KeyError: # not possible to reach this at time of writing, but who knows? # mistakes happen when updating stuff that needs to be changed in # parallel return bot.reply( f"I don't know what color sequence to use for '{scheme}'!") color_cycle = itertools.cycle(colors) bot.say( ''.join( char if unicodedata.category(char) == 'Zs' else color(char, next(color_cycle)) for char in text ), max_messages=4 )
28.37037
82
0.619452
7f5d7168e071ee61d4a5b7c6122bc5e329d83da0
4,484
php
PHP
application/views/category_level2/view.php
MerDoLive/AdminPanel
bd74f9307e7320c80b0d28004c5c27343737dd9a
[ "MIT" ]
null
null
null
application/views/category_level2/view.php
MerDoLive/AdminPanel
bd74f9307e7320c80b0d28004c5c27343737dd9a
[ "MIT" ]
46
2018-06-23T14:30:57.000Z
2018-10-22T10:02:13.000Z
application/views/category_level2/view.php
MerEComm/AdminPanel
bd74f9307e7320c80b0d28004c5c27343737dd9a
[ "MIT" ]
null
null
null
<?php $this->load->view('common/header'); ?> <?php $this->load->view('common/left_panel'); ?> <section id="content"> <div class="container"> <div class="card"> <div class="card-header"> <div class="col-md-4" style="padding: 0"><h3><i class="zmdi zmdi-city-alt"></i>&nbsp;<?= $subheading ?></h3></div> <div style="clear:both"></div> </div> <div class="table-responsive"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="col-md-6"> <div class="form-group"> <div class="fg-line"> <label class="control-label" for="inputSuccess1">Category Type</label> <input class="form-control" id="inputSuccess1" value="<?= $categoryTypeName; ?>" type="text" disabled=""> </div> </div> </div> </div> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="col-md-6"> <div class="form-group"> <div class="fg-line"> <label class="control-label" for="inputSuccess1">Category Level 1</label> <input class="form-control" id="inputSuccess1" value="<?= $categoryLevel1; ?>" type="text" disabled=""> </div> </div> </div> </div> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="col-md-6"> <div class="form-group"> <div class="fg-line"> <label class="control-label" for="inputSuccess1">Category Level 2</label> <input class="form-control" id="inputSuccess1" value="<?= $categoryLevel2; ?>" type="text" disabled=""> </div> </div> </div> </div> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="col-md-6"> <div class="form-group"> <div class="fg-line"> <label class="control-label" for="inputSuccess1">Category Description</label> <?= html_entity_decode($desc) ?> </div> </div> </div> </div> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="col-md-6"> <div class="form-group"> <div class="fg-line"> <label class="control-label" for="inputSuccess1">Category Level</label> <input class="form-control" id="inputSuccess1" value="<?= $level; ?>" type="text" disabled=""> </div> </div> </div> </div> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="col-md-6"> <div class="form-group"> <div class="fg-line"> <label class="control-label" for="inputSuccess1">Category Position</label> <input class="form-control" id="inputSuccess1" value="<?= $position; ?>" type="text" disabled=""> </div> </div> </div> </div> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="col-md-6"> <div class="form-group"> <button type="button" class="btn btn-sm btn-danger" onclick="window.location='<?= site_url('Categories_level2/index/'.$cond2) ?>'" >Back</button> </div> </div> </div> </form> </div> </div> </div> </section> </section>
53.380952
181
0.370874
dda33575bd661425b5475e27e9e66270adbf92cd
2,112
java
Java
src/main/java/de/dakror/arise/net/packet/Packet20Takeover.java
Dakror/Arise
4afc8f985e5f89bb519b39f3024e70a9e73a12e4
[ "Apache-2.0" ]
null
null
null
src/main/java/de/dakror/arise/net/packet/Packet20Takeover.java
Dakror/Arise
4afc8f985e5f89bb519b39f3024e70a9e73a12e4
[ "Apache-2.0" ]
null
null
null
src/main/java/de/dakror/arise/net/packet/Packet20Takeover.java
Dakror/Arise
4afc8f985e5f89bb519b39f3024e70a9e73a12e4
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2015 Maximilian Stark | Dakror <mail@dakror.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.dakror.arise.net.packet; /** * @author Dakror */ public class Packet20Takeover extends Packet { int cityTakenOverId, stage, timeleft, newUserId; String newUsername; public Packet20Takeover(int cityTakenOverId, int stage, int timeleft, int newUserId, String newUsername) { super(20); this.cityTakenOverId = cityTakenOverId; this.stage = stage; this.timeleft = timeleft; this.newUserId = newUserId; this.newUsername = newUsername; } public Packet20Takeover(byte[] data) { super(20); String[] parts = readData(data).split(":"); cityTakenOverId = Integer.parseInt(parts[0]); stage = Integer.parseInt(parts[1]); timeleft = Integer.parseInt(parts[2]); newUserId = Integer.parseInt(parts[3]); newUsername = parts[4]; } @Override protected byte[] getPacketData() { return (cityTakenOverId + ":" + stage + ":" + timeleft + ":" + newUserId + ":" + newUsername).getBytes(); } public int getCityTakenOverId() { return cityTakenOverId; } public int getStage() { return stage; } public boolean isCityTakenOver() { return stage == -1; } public int getTimeleft() { return timeleft; } public int getNewUserId() { return newUserId; } public String getNewUsername() { return newUsername; } }
27.428571
108
0.633996
b0459ab31de0abe03994e4d8b3589f512d689f69
525
py
Python
menu.py
magnoborgo/RotoPaintToSplineWarp2
dd4139c36f10c63ac84d8c4f44ef32f0d9faab0d
[ "BSD-3-Clause" ]
3
2016-07-07T05:50:03.000Z
2022-01-25T18:14:09.000Z
menu.py
magnoborgo/RotoPaintToSplineWarp2
dd4139c36f10c63ac84d8c4f44ef32f0d9faab0d
[ "BSD-3-Clause" ]
null
null
null
menu.py
magnoborgo/RotoPaintToSplineWarp2
dd4139c36f10c63ac84d8c4f44ef32f0d9faab0d
[ "BSD-3-Clause" ]
null
null
null
import nuke nuke.tprint('Loading RotopaintToSplineWarp_v2.py') try: from RotopaintToSplineWarp_v2 import * except: pass #=============================================================================== # BVFX ToolBar Menu definitions #=============================================================================== toolbar = nuke.menu("Nodes") bvfxt = toolbar.addMenu("BoundaryVFX Tools", "BoundaryVFX.png") bvfxt.addCommand('Rotopaint to SplineWarp Nukev7', 'Roto_to_WarpSpline_v2()', 'F8', icon='bvfx_SplineW.png')
37.5
108
0.531429
ed522351cbf33a493ab4dc2e060636a12e863a6b
2,240
h
C
v1/phttp_status_code.h
kokabe2/linc
1fc1b5acf91c9dbc960075ae8bf96bc502c5e206
[ "MIT" ]
null
null
null
v1/phttp_status_code.h
kokabe2/linc
1fc1b5acf91c9dbc960075ae8bf96bc502c5e206
[ "MIT" ]
null
null
null
v1/phttp_status_code.h
kokabe2/linc
1fc1b5acf91c9dbc960075ae8bf96bc502c5e206
[ "MIT" ]
null
null
null
// Copyright(c) 2020 Ken Okabe // This software is released under the MIT License, see LICENSEk #ifndef V1_PHTTP_STATUS_CODE_H_ #define V1_PHTTP_STATUS_CODE_H_ typedef enum { kStatusContinue = 100, kStatusSwitchingProtocols = 101, kStatusProcessing = 102, kStatusEarlyHints = 103, kStatusOK = 200, kStatusCreated = 201, kStatusAccepted = 202, kStatusNonAuthoritativeInfo = 203, kStatusNoContent = 204, kStatusResetContent = 205, kStatusPartialContent = 206, kStatusMultiStatus = 207, kStatusAlreadyReported = 208, kStatusIMUsed = 226, kStatusMultipleChoices = 300, kStatusMovedPermanently = 301, kStatusFound = 302, kStatusSeeOther = 303, kStatusNotModified = 304, kStatusUseProxy = 305, kStatusTemporaryRedirect = 307, kStatusPermanentRedirect = 308, kStatusBadRequest = 400, kStatusUnauthorized = 401, kStatusPaymentRequired = 402, kStatusForbidden = 403, kStatusNotFound = 404, kStatusMethodNotAllowed = 405, kStatusNotAcceptable = 406, kStatusProxyAuthRequired = 407, kStatusRequestTimeout = 408, kStatusConflict = 409, kStatusGone = 410, kStatusLengthRequired = 411, kStatusPreconditionFailed = 412, kStatusRequestEntityTooLarge = 413, kStatusRequestURITooLong = 414, kStatusUnsupportedMediaType = 415, kStatusRequestedRangeNotSatisfiable = 416, kStatusExpectationFailed = 417, kStatusTeapot = 418, kStatusMisdirectedRequest = 421, kStatusUnprocessableEntity = 422, kStatusLocked = 423, kStatusFailedDependency = 424, kStatusTooEarly = 425, kStatusUpgradeRequired = 426, kStatusPreconditionRequired = 428, kStatusTooManyRequests = 429, kStatusRequestHeaderFieldsTooLarge = 431, kStatusUnavailableForLegalReasons = 451, kStatusInternalServerError = 500, kStatusNotImplemented = 501, kStatusBadGateway = 502, kStatusServiceUnavailable = 503, kStatusGatewayTimeout = 504, kStatusHTTPVersionNotSupported = 505, kStatusVariantAlsoNegotiates = 506, kStatusInsufficientStorage = 507, kStatusLoopDetected = 508, kStatusNotExtended = 510, kStatusNetworkAuthenticationRequired = 511, } PhttpStatusCodes; #endif // V1_PHTTP_STATUS_CODE_H_
29.473684
65
0.75
9e0b3d56ef7339e2fedf6fa9961245ec36843f6d
296
cs
C#
stable/dotnetcore/src/Kubeless.Core/Interfaces/IInvoker.cs
Psidium/runtimes
29fa4622d61fea4395e20e5c48b57ef734730971
[ "Apache-2.0" ]
null
null
null
stable/dotnetcore/src/Kubeless.Core/Interfaces/IInvoker.cs
Psidium/runtimes
29fa4622d61fea4395e20e5c48b57ef734730971
[ "Apache-2.0" ]
null
null
null
stable/dotnetcore/src/Kubeless.Core/Interfaces/IInvoker.cs
Psidium/runtimes
29fa4622d61fea4395e20e5c48b57ef734730971
[ "Apache-2.0" ]
null
null
null
using Kubeless.Functions; using System.Threading; namespace Kubeless.Core.Interfaces { public interface IInvoker { IFunction Function { get; } object Execute(CancellationTokenSource cancellationSource, Event kubelessEvent, Context kubelessContext); } }
22.769231
114
0.709459
c86aa22dc28aa7b8406166d606c16ac8fd4a382d
1,299
kt
Kotlin
app/src/main/java/org/task/manager/data/network/api/AudiovisualApi.kt
Steampunk1453/todo-task-manager-android
612c7a0a3c3a86d0a7f185e88273d6cccd991a03
[ "Apache-2.0" ]
6
2020-08-12T16:30:21.000Z
2021-07-10T08:51:28.000Z
app/src/main/java/org/task/manager/data/network/api/AudiovisualApi.kt
Steampunk1453/todo-task-manager-android
612c7a0a3c3a86d0a7f185e88273d6cccd991a03
[ "Apache-2.0" ]
1
2021-07-09T08:40:31.000Z
2021-08-29T09:42:49.000Z
app/src/main/java/org/task/manager/data/network/api/AudiovisualApi.kt
Steampunk1453/todo-task-manager-android
612c7a0a3c3a86d0a7f185e88273d6cccd991a03
[ "Apache-2.0" ]
null
null
null
package org.task.manager.data.network.api import org.task.manager.data.network.model.request.AudiovisualRequest import org.task.manager.data.network.model.response.AudiovisualResponse import org.task.manager.data.network.model.response.PlatformResponse import org.task.manager.data.network.model.response.TitleResponse import org.task.manager.shared.Constants import retrofit2.Response import retrofit2.http.* interface AudiovisualApi { @POST(Constants.AUDIOVISUAL_URL) suspend fun createAudiovisual(@Body request: AudiovisualRequest): Response<AudiovisualResponse> @PUT(Constants.AUDIOVISUAL_URL) suspend fun updateAudiovisual(@Body request: AudiovisualRequest): Response<AudiovisualResponse> @GET(Constants.AUDIOVISUAL_URL) suspend fun getAllAudiovisuals(): Response<List<AudiovisualResponse>> @DELETE(Constants.AUDIOVISUAL_URL + Constants.ID) suspend fun deleteAudiovisual(@Path("id") id: Long): Response<Void> @GET(Constants.TITLE_URL) suspend fun getAllTitles(): Response<List<TitleResponse>> @GET(Constants.TITLE_URL + Constants.FILTER) suspend fun getAllTitlesByFilter(@Path("filter") filter: String): Response<List<TitleResponse>> @GET(Constants.PLATFORM_URL) suspend fun getAllPlatforms(): Response<List<PlatformResponse>> }
38.205882
99
0.795227
cdecec1d22e9e183ca4de98cb02c01fc38cd42a7
31,569
cs
C#
Valigator.Core/Extensions/NullableRequiredNullableCollectionStateValidatorExtensions.cs
rolan18/Valigator
1e1d7c14319fe35184b63a35724f0d7f53bb861b
[ "MIT" ]
4
2020-02-07T16:14:03.000Z
2021-08-22T08:45:03.000Z
Valigator.Core/Extensions/NullableRequiredNullableCollectionStateValidatorExtensions.cs
rolan18/Valigator
1e1d7c14319fe35184b63a35724f0d7f53bb861b
[ "MIT" ]
23
2019-06-13T17:20:38.000Z
2021-09-01T04:00:16.000Z
Valigator.Core/Extensions/NullableRequiredNullableCollectionStateValidatorExtensions.cs
rolan18/Valigator
1e1d7c14319fe35184b63a35724f0d7f53bb861b
[ "MIT" ]
5
2019-05-31T18:30:08.000Z
2022-01-05T11:49:53.000Z
// NOTE: GENERATED FILE // using Functional; using System; using System.Collections.Generic; using Valigator.Core; using Valigator.Core.DataContainers.Factories; using Valigator.Core.DataSources; using Valigator.Core.StateValidators; using Valigator.Core.ValueValidators; namespace Valigator { public static class NullableRequiredNullableCollectionStateValidatorExtensions { public static DataSourceInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TValue, TValue>, Option<Option<TValue>[]>, Option<TValue>[], TValueValidator> Not<TValue, TValueValidator>(this NullableRequiredNullableCollectionStateValidator<TValue> source, Func<NullableRequiredNullableCollectionStateValidator<TValue>, DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TValue, TValue>, Option<Option<TValue>[]>, Option<TValue>[], TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertOne(); public static DataSourceInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSource<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[]> source, Func<DataSource<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[]>, DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertOne(); public static DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TValue, TValue>, Option<Option<TValue>[]>, Option<TValue>[], CustomValidator<Option<TValue>[]>> Assert<TValue>(this NullableRequiredNullableCollectionStateValidator<TValue> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSource<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[]> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TValue, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>> Unique<TValue>(this NullableRequiredNullableCollectionStateValidator<TValue> source) => source.Add(new UniqueValidator<Option<TValue>>()); public static DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>> Unique<TSource, TValue>(this DataSource<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[]> source) => source.Add(new UniqueValidator<Option<TValue>>()); public static DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TValue, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>> ItemCount<TValue>(this NullableRequiredNullableCollectionStateValidator<TValue> source, int? minimumItems = null, int? maximumItems = null) => source.Add(new ItemCountValidator<Option<TValue>>(minimumItems, maximumItems)); public static DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>> ItemCount<TSource, TValue>(this DataSource<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[]> source, int? minimumItems = null, int? maximumItems = null) => source.Add(new ItemCountValidator<Option<TValue>>(minimumItems, maximumItems)); public static DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>> ItemCount<TSource, TValue>(this DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>> source, int? minimumItems = null, int? maximumItems = null) => source.Add(new ItemCountValidator<Option<TValue>>(minimumItems, maximumItems)); public static DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>> ItemCount<TSource, TValue>(this DataSourceInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>> source, int? minimumItems = null, int? maximumItems = null) => source.Add(new ItemCountValidator<Option<TValue>>(minimumItems, maximumItems)); public static DataSourceStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>> source, Func<DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>>, DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertTwo(); public static DataSourceInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>> source, Func<DataSourceInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>>, DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertTwo(); public static DataSourceStandardStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceInvertedStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceStandardInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceInvertedInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceStandardStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>> source, Func<DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>>, DataSourceStandardStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertThree(); public static DataSourceInvertedStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>> source, Func<DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>>, DataSourceInvertedStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertThree(); public static DataSourceStandardInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>> source, Func<DataSourceStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>>, DataSourceStandardInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertThree(); public static DataSourceInvertedInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>> source, Func<DataSourceInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>>, DataSourceInvertedInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], UniqueValidator<Option<TValue>>, ItemCountValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertThree(); public static DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>> Unique<TSource, TValue>(this DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>> source) => source.Add(new UniqueValidator<Option<TValue>>()); public static DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>> Unique<TSource, TValue>(this DataSourceInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>> source) => source.Add(new UniqueValidator<Option<TValue>>()); public static DataSourceStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>> source, Func<DataSourceStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>>, DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertTwo(); public static DataSourceInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>> source, Func<DataSourceInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>>, DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertTwo(); public static DataSourceStandardStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceInvertedStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceStandardInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceInvertedInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, CustomValidator<Option<TValue>[]>> Assert<TSource, TValue>(this DataSourceInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>> source, string description, Func<Option<TValue>[], bool> validator) => source.Add(new CustomValidator<Option<TValue>[]>(description, validator)); public static DataSourceStandardStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>> source, Func<DataSourceStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>>, DataSourceStandardStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertThree(); public static DataSourceInvertedStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>> source, Func<DataSourceInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>>, DataSourceInvertedStandardStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertThree(); public static DataSourceStandardInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>> source, Func<DataSourceStandardInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>>, DataSourceStandardInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertThree(); public static DataSourceInvertedInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, TValueValidator> Not<TSource, TValue, TValueValidator>(this DataSourceInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>> source, Func<DataSourceInvertedInverted<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>>, DataSourceInvertedInvertedStandard<NullableCollectionNullableDataContainerFactory<NullableRequiredNullableCollectionStateValidator<TValue>, TSource, TValue>, Option<Option<TValue>[]>, Option<TValue>[], ItemCountValidator<Option<TValue>>, UniqueValidator<Option<TValue>>, TValueValidator>> validatorFactory) where TValueValidator : struct, IValueValidator<Option<TValue>[]> => validatorFactory.Invoke(source).InvertThree(); } }
230.430657
1,193
0.837626
e734afd011263d6c3eb16b129563862a2d8fa679
3,293
lua
Lua
scite/old/wscite_zzz/lexers/notused/sml.lua
mobarski/sandbox
64ac79143750d5dcbd4d0f3abdab6efeb9bdf50c
[ "MIT" ]
1
2019-02-11T00:52:36.000Z
2019-02-11T00:52:36.000Z
scite/old/wscite_zzz/lexers/notused/sml.lua
mobarski/sandbox
64ac79143750d5dcbd4d0f3abdab6efeb9bdf50c
[ "MIT" ]
null
null
null
scite/old/wscite_zzz/lexers/notused/sml.lua
mobarski/sandbox
64ac79143750d5dcbd4d0f3abdab6efeb9bdf50c
[ "MIT" ]
null
null
null
-- Copyright 2017 Murray Calavera. See LICENSE. -- Standard ML LPeg lexer. local l = require('lexer') local token = l.token function mlword(words) return l.word_match(words, "'") end local ws = token(l.WHITESPACE, l.space^1) -- single line comments are valid in successor ml local cl = '(*)' * l.nonnewline^0 local comment = token(l.COMMENT, cl + l.nested_pair('(*', '*)')) local string = token(l.STRING, lpeg.P('#')^-1 * l.delimited_range('"', true)) local function num(digit) return digit * (digit^0 * lpeg.P('_'))^0 * digit^1 + digit end local int = num(l.digit) local frac = lpeg.P('.') * int local minus = lpeg.P('~')^-1 local exp = lpeg.S('eE') * minus * int local real = int * frac^-1 * exp + int * frac * exp^-1 local hex = num(l.xdigit) local bin = num(lpeg.S('01')) local number = token(l.NUMBER, lpeg.P('0w') * int + (lpeg.P('0wx') + lpeg.P('0xw')) * hex + (lpeg.P('0wb') + lpeg.P('0bw')) * bin + minus * lpeg.P('0x') * hex + minus * lpeg.P('0b') * bin + minus * real + minus * int ) local keyword = token(l.KEYWORD, mlword{ 'abstype', 'and', 'andalso', 'as', 'case', 'do', 'datatype', 'else', 'end', 'exception', 'fn', 'fun', 'handle', 'if', 'in', 'infix', 'infixr', 'let', 'local', 'nonfix', 'of', 'op', 'orelse', 'raise', 'rec', 'then', 'type', 'val', 'with', 'withtype', 'while', 'eqtype', 'functor', 'include', 'sharing', 'sig', 'signature', 'struct', 'structure' }) -- includes valid symbols for identifiers local operator = token(l.OPERATOR, lpeg.S('!*/+-^:@=<>()[]{},;._|#%&$?~`\\')) local type = token(l.TYPE, mlword{ 'int', 'real', 'word', 'bool', 'char', 'string', 'unit', 'array', 'exn', 'list', 'option', 'order', 'ref', 'substring', 'vector' }) -- `real`, `vector` and `substring` are a problem local func = token(l.FUNCTION, mlword{ 'app', 'before', 'ceil', 'chr', 'concat', 'exnMessage', 'exnName', 'explode', 'floor', 'foldl', 'foldr', 'getOpt', 'hd', 'ignore', 'implode', 'isSome', 'length', 'map', 'not', 'null', 'ord', 'print', 'real', 'rev', 'round', 'size', 'str', 'substring', 'tl', 'trunc', 'valOf', 'vector', 'o', 'abs', 'mod', 'div' }) -- non-symbolic identifiers only local id = (l.alnum + "'" + '_')^0 local aid = l.alpha * id local longid = (aid * lpeg.P('.'))^0 * aid local identifier = token(l.IDENTIFIER, l.lower * id) local typevar = token(l.VARIABLE, "'" * id) local c = mlword{'true', 'false', 'nil'} local const = token(l.CONSTANT, l.upper * id + c) local structure = token(l.CLASS, aid * lpeg.P('.')) local open = token(l.KEYWORD, mlword{'open', 'structure', 'functor'}) * ws * token(l.CLASS, longid) local struct_dec = token(l.KEYWORD, lpeg.P('structure')) * ws * token(l.CLASS, aid) * ws * token(l.OPERATOR, lpeg.P('=')) * ws local struct_new = struct_dec * token(l.KEYWORD, lpeg.P('struct')) local struct_alias = struct_dec * token(l.CLASS, longid) local M = {_NAME = 'sml'} M._rules = { {'whitespace', ws}, {'comment', comment}, {'number', number}, {'struct_new', struct_new}, {'struct_alias', struct_alias}, {'structure', structure}, {'open', open}, {'type', type}, {'keyword', keyword}, {'function', func}, {'string', string}, {'operator', operator}, {'typevar', typevar}, {'constant', const}, {'identifier', identifier}, } return M
29.401786
77
0.595809
3f71c2634d91ba94fb3a60cde50f4f4c26bc0cf3
265
php
PHP
app/Http/Controllers/TshirtsController.php
Fsilva13/MagicShirts_Store
c6663c248f3df341c019075cafd563a8694e108a
[ "MIT" ]
null
null
null
app/Http/Controllers/TshirtsController.php
Fsilva13/MagicShirts_Store
c6663c248f3df341c019075cafd563a8694e108a
[ "MIT" ]
null
null
null
app/Http/Controllers/TshirtsController.php
Fsilva13/MagicShirts_Store
c6663c248f3df341c019075cafd563a8694e108a
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use App\Tshirt; use Illuminate\Http\Request; class TshirtsController extends Controller { public function index() { $tshirt = Tshirt::paginate(9); return view('Tshirt.list', compact('tshirt')); } }
16.5625
53
0.671698
cf032ba2c3e604fac24ef21be36abda720e3b8bf
847
php
PHP
database/migrations/2021_04_25_165339_create_ambulance_mission_rescuers_table.php
barhous/redcross
8b4fbc2daf183c9e3996f4c7bc4b405ffb789893
[ "MIT" ]
null
null
null
database/migrations/2021_04_25_165339_create_ambulance_mission_rescuers_table.php
barhous/redcross
8b4fbc2daf183c9e3996f4c7bc4b405ffb789893
[ "MIT" ]
null
null
null
database/migrations/2021_04_25_165339_create_ambulance_mission_rescuers_table.php
barhous/redcross
8b4fbc2daf183c9e3996f4c7bc4b405ffb789893
[ "MIT" ]
null
null
null
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAmbulanceMissionRescuersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('ambulance_mission_rescuers', function (Blueprint $table) { $table->id(); $table->foreignId('ambulance_id')->constrained('ambulance'); $table->foreignId('mission_id')->constrained('mission'); $table->foreignId('rescuer_id')->constrained('rescuers'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('ambulance_mission_rescuers'); } }
24.2
82
0.608028
385a2365527531734b5ee7842d3105ff6fbf2555
3,881
php
PHP
resources/views/sub-views/createdByUserText.blade.php
prakash-zentreasury/terraformcicdtest
78055504808e5afd4c3c64472edbf9a4617aeee0
[ "MIT" ]
null
null
null
resources/views/sub-views/createdByUserText.blade.php
prakash-zentreasury/terraformcicdtest
78055504808e5afd4c3c64472edbf9a4617aeee0
[ "MIT" ]
9
2021-04-30T20:26:09.000Z
2022-03-08T23:34:25.000Z
resources/views/sub-views/createdByUserText.blade.php
prakash-zentreasury/terraformcicdtest
78055504808e5afd4c3c64472edbf9a4617aeee0
[ "MIT" ]
2
2021-01-15T05:04:38.000Z
2021-01-19T06:26:25.000Z
@if(isset($copy)) @if(isset($notShowId)) <h2 class="section-heading d-flex justify-content-center justify-content-md-start"> @lang('master.Copy') {!!$type!!}</h2> @else <h2 class="section-heading d-flex justify-content-center justify-content-md-start"> @lang('master.Copy') {!!$type!!} @if(isset($deal->short_name)) ({!! $deal->short_name !!}) @else {!!$deal->id!!} @endif</h2> @endif @elseif(isset($deal)) @if(isset($notShowId)) <h2 class="section-heading d-flex justify-content-center justify-content-md-start"> {!!$type!!}</h2> @else <h2 class="section-heading d-flex justify-content-center justify-content-md-start">{!!$type!!} @if(isset($deal->short_name)) ({!! $deal->short_name !!}) @elseif(isset($deal->name)) ({!! $deal->name !!}) @else {!!$deal->id!!} @endif</h2> @endif <small class="d-flex justify-content-md-start justify-content-center"> @lang('master.Created by') {!! $deal->createdByUser->name ?? ''!!} @lang('master.on') <?php switch(Auth ::user() -> locale){ case "fi": setlocale(LC_TIME, 'fi_FI.utf8'); echo Carbon\Carbon ::parse($deal -> created_at) -> formatLocalized('%d %Bta %Y'); break; case "sv": setlocale(LC_TIME, 'sv_SV.utf8'); echo Carbon\Carbon ::parse($deal -> created_at) -> formatLocalized('%d %B %Y'); break; case "de": setlocale(LC_TIME, 'de_DE.utf8'); echo Carbon\Carbon ::parse($deal -> created_at) -> formatLocalized('%d %B %Y'); break; case "fr": setlocale(LC_TIME, 'fr_FR.utf8'); echo Carbon\Carbon ::parse($deal -> created_at) -> formatLocalized('%d %B %Y'); break; default: setlocale(LC_TIME, 'en'); echo Carbon\Carbon ::parse($deal -> created_at) -> formatLocalized('%d %B %Y'); }?> @if(isset($deal->updated_user_id) && $deal->updated_user_id!=0)@lang('master.and last updated by') {!! $deal->updatedByUser->name ?? ''!!} @lang('master.on') <?php switch(Auth ::user() -> locale){ case "fi": setlocale(LC_TIME, 'fi_FI.utf8'); echo Carbon\Carbon ::parse($deal -> updated_at) -> formatLocalized('%d %Bta %Y'); break; case "sv": setlocale(LC_TIME, 'sv_SV.utf8'); echo Carbon\Carbon ::parse($deal -> updated_at) -> formatLocalized('%d %B %Y'); break; case "de": setlocale(LC_TIME, 'de_DE.utf8'); echo Carbon\Carbon ::parse($deal -> updated_at) -> formatLocalized('%d %B %Y'); break; case "fr": setlocale(LC_TIME, 'fr_FR.utf8'); echo Carbon\Carbon ::parse($deal -> updated_at) -> formatLocalized('%d %B %Y'); break; default: setlocale(LC_TIME, 'en'); echo Carbon\Carbon ::parse($deal -> updated_at) -> formatLocalized('%d %B %Y'); } ?> @endif </small> <small class="d-none"> <span class="required">*</span> @lang('master.indicates required fields') </small> @else <h2 class="section-heading d-flex justify-content-center justify-content-md-start">@lang('master.New') {!!$type!!} </h2> <small class="d-none"> <span class="required">*</span> @lang('master.indicates required fields') </small> @endif
45.658824
249
0.491368
ec23556305e7fe9c75261286cdc4ec7983cf1334
565
swift
Swift
Package.swift
Bauer312/election-calc
cbc5065064b760287da9f4f3d62cd065c1d2f1e1
[ "MIT" ]
null
null
null
Package.swift
Bauer312/election-calc
cbc5065064b760287da9f4f3d62cd065c1d2f1e1
[ "MIT" ]
null
null
null
Package.swift
Bauer312/election-calc
cbc5065064b760287da9f4f3d62cd065c1d2f1e1
[ "MIT" ]
null
null
null
import PackageDescription let package = Package( name: "election-calc", targets: [ Target( name: "CalcIndex", dependencies: [ .Target(name: "Boundary"), .Target(name: "Core") ] ), Target( name: "Core", dependencies: [ .Target(name: "Boundary") ] ), Target( name: "Boundary" ) ], dependencies: [ .Package(url: "https://github.com/PerfectlySoft/Perfect-PostgreSQL.git", versions: Version(0,0,0)..<Version(10,0,0)) ] )
20.925926
122
0.507965
7bd9bc4275b8320cf4b5800f645a7b13598b1bf8
3,316
lua
Lua
suitvoice/lua/autorun/suitvoice.lua
AgentAgrimar/Suit-Voice
b451a38b1304df41ccb3fc1f41785521fd7a2351
[ "MIT" ]
null
null
null
suitvoice/lua/autorun/suitvoice.lua
AgentAgrimar/Suit-Voice
b451a38b1304df41ccb3fc1f41785521fd7a2351
[ "MIT" ]
null
null
null
suitvoice/lua/autorun/suitvoice.lua
AgentAgrimar/Suit-Voice
b451a38b1304df41ccb3fc1f41785521fd7a2351
[ "MIT" ]
null
null
null
--[[ Hazardous EnVironment Suit Voice Module ]] -- Original Code: Valve -- Lua Port: Agent Agrimar -- We register voice packs by passing in a string, which then temporarily -- saves it to the disk as the function that precaches sentences works with files only. suitVoicePacks = {}; function RegisterSuitVoicePack( name, value, sentences ) table.Add( suitVoicePacks, { { name = name, value = value, rawsentencedata = sentences } } ) end -- Check to see if there's any addon packs. local files, directories = file.Find( "suitvoice/packs/*.lua", "LUA" ); for _, luaPackFile in pairs( files ) do include( "suitvoice/packs/" .. luaPackFile ); if SERVER then AddCSLuaFile( "suitvoice/packs/" .. luaPackFile ); end print( "Included H.E.V. Suit Voice Pack: " .. string.StripExtension( luaPackFile ) ); end if SERVER then -- Parse over the table and create sentence files necessary for use by the suit voice. for _, v in pairs( suitVoicePacks ) do if ( v.rawsentencedata == nil ) then break; end if ( !file.Exists( "suitvoice/packs", "DATA" ) ) then file.CreateDir( "suitvoice/packs" ); file.CreateDir( "suitvoice/packs/loose" ); end file.Write( "suitvoice/packs/" .. v.value .. ".txt", v.rawsentencedata ); end local files, directories = file.Find( "suitvoice/packs/loose/*.txt", "DATA" ); for _, sentencePackFile in pairs( files ) do PrecacheSentenceFile( "data/suitvoice/packs/loose/" .. sentencePackFile ); end -- Parse any sentence file found here for use by the suit voice. local files, directories = file.Find( "suitvoice/packs/*.txt", "DATA" ); for _, sentencePackFile in pairs( files ) do -- If we find the same file here, then we're using the loose one instead. if ( !file.Exists( "suitvoice/packs/loose/" .. sentencePackFile, "DATA" ) ) then if ( file.Exists( "suitvoice/packs/" .. string.StripExtension( sentencePackFile ) .. ".lua", "LUA" ) ) then PrecacheSentenceFile( "data/suitvoice/packs/" .. sentencePackFile ); end end file.Delete( "suitvoice/packs/" .. sentencePackFile ); end end -- Now load the important parts. if SERVER then include( "suitvoice/sv_suitvoice_core.lua" ); AddCSLuaFile( "suitvoice/cl_suitvoice_core.lua" ); AddCSLuaFile( "suitvoice/cl_suitvoice_localization.lua" ); AddCSLuaFile( "suitvoice/cl_suitvoice_options.lua" ); elseif CLIENT then include( "suitvoice/cl_suitvoice_core.lua" ); include( "suitvoice/cl_suitvoice_localization.lua" ); include( "suitvoice/cl_suitvoice_options.lua" ); end -- Checks to see if an invalid pack was set, just incase it's been deleted. local function CheckVoicePackConVar( value ) if SERVER then if ( value == "" ) then return; end end for _, v in pairs( suitVoicePacks ) do if ( value == v.value ) then return; end end suitvoice_pack:SetString( suitvoice_pack:GetDefault() ); end CheckVoicePackConVar( suitvoice_pack:GetString() ); cvars.AddChangeCallback( suitvoice_pack:GetName(), function( _, _, new ) CheckVoicePackConVar( new ); end )
36.43956
120
0.647165
00d6bee6ba8f435dbe5b64d7c8af4f3f88234514
10,141
go
Go
vendor/github.com/kataras/go-events/events.go
adambemiller/elastic-search-api
069063e61d5755e2d30714a3e86d2231b310375c
[ "MIT" ]
1
2020-01-15T04:31:16.000Z
2020-01-15T04:31:16.000Z
vendor/github.com/kataras/go-events/events.go
adambemiller/elastic-search-api
069063e61d5755e2d30714a3e86d2231b310375c
[ "MIT" ]
null
null
null
vendor/github.com/kataras/go-events/events.go
adambemiller/elastic-search-api
069063e61d5755e2d30714a3e86d2231b310375c
[ "MIT" ]
null
null
null
// Package events provides simple EventEmmiter support for Go Programming Language package events import ( "log" "sync" ) const ( // Version current version number Version = "0.0.2" // DefaultMaxListeners is the number of max listeners per event // default EventEmitters will print a warning if more than x listeners are // added to it. This is a useful default which helps finding memory leaks. // Defaults to 0, which means unlimited DefaultMaxListeners = 0 // EnableWarning prints a warning when trying to add an event which it's len is equal to the maxListeners // Defaults to false, which means it does not prints a warning EnableWarning = false ) type ( // EventName is just a type of string, it's the event name EventName string // Listener is the type of a Listener, it's a func which receives any,optional, arguments from the caller/emmiter Listener func(...interface{}) // Events the type for registered listeners, it's just a map[string][]func(...interface{}) Events map[EventName][]Listener // EventEmmiter is the message/or/event manager EventEmmiter interface { // AddListener is an alias for .On(eventName, listener). AddListener(EventName, ...Listener) // Emit fires a particular event, // Synchronously calls each of the listeners registered for the event named // eventName, in the order they were registered, // passing the supplied arguments to each. Emit(EventName, ...interface{}) // EventNames returns an array listing the events for which the emitter has registered listeners. // The values in the array will be strings. EventNames() []EventName // GetMaxListeners returns the max listeners for this emmiter // see SetMaxListeners GetMaxListeners() int // ListenerCount returns the length of all registered listeners to a particular event ListenerCount(EventName) int // Listeners returns a copy of the array of listeners for the event named eventName. Listeners(EventName) []Listener // On registers a particular listener for an event, func receiver parameter(s) is/are optional On(EventName, ...Listener) // Once adds a one time listener function for the event named eventName. // The next time eventName is triggered, this listener is removed and then invoked. Once(EventName, ...Listener) // RemoveAllListeners removes all listeners, or those of the specified eventName. // Note that it will remove the event itself. // Returns an indicator if event and listeners were found before the remove. RemoveAllListeners(EventName) bool // Clear removes all events and all listeners, restores Events to an empty value Clear() // SetMaxListeners obviously this function allows the MaxListeners // to be decrease or increase. Set to zero for unlimited SetMaxListeners(int) // Len returns the length of all registered events Len() int } emmiter struct { maxListeners int evtListeners Events mu sync.Mutex } ) // CopyTo copies the event listeners to an EventEmmiter func (e Events) CopyTo(emmiter EventEmmiter) { if e != nil && len(e) > 0 { // register the events to/with their listeners for evt, listeners := range e { if len(listeners) > 0 { emmiter.AddListener(evt, listeners...) } } } } // New returns a new, empty, EventEmmiter func New() EventEmmiter { return &emmiter{maxListeners: DefaultMaxListeners, evtListeners: Events{}} } var ( _ EventEmmiter = &emmiter{} defaultEmmiter = New() ) // AddListener is an alias for .On(eventName, listener). func AddListener(evt EventName, listener ...Listener) { defaultEmmiter.AddListener(evt, listener...) } func (e *emmiter) AddListener(evt EventName, listener ...Listener) { if len(listener) == 0 { return } e.mu.Lock() defer e.mu.Unlock() if e.evtListeners == nil { e.evtListeners = Events{} } listeners := e.evtListeners[evt] if e.maxListeners > 0 && len(listeners) == e.maxListeners { if EnableWarning { log.Printf(`(events) warning: possible EventEmitter memory ' leak detected. %d listeners added. ' Use emitter.SetMaxListeners(n int) to increase limit.`, len(listeners)) } return } if listeners == nil { listeners = make([]Listener, e.maxListeners) } e.evtListeners[evt] = append(listeners, listener...) } // Emit fires a particular event, // Synchronously calls each of the listeners registered for the event named // eventName, in the order they were registered, // passing the supplied arguments to each. func Emit(evt EventName, data ...interface{}) { defaultEmmiter.Emit(evt, data...) } func (e *emmiter) Emit(evt EventName, data ...interface{}) { if e.evtListeners == nil { return // has no listeners to emit/speak yet } if listeners := e.evtListeners[evt]; listeners != nil && len(listeners) > 0 { // len() should be just fine, but for any case on future... for i := range listeners { l := listeners[i] if l != nil { l(data...) } } } } // EventNames returns an array listing the events for which the emitter has registered listeners. // The values in the array will be strings. func EventNames() []EventName { return defaultEmmiter.EventNames() } func (e *emmiter) EventNames() []EventName { if e.evtListeners == nil || e.Len() == 0 { return nil } names := make([]EventName, e.Len(), e.Len()) i := 0 for k := range e.evtListeners { names[i] = k i++ } return names } // GetMaxListeners returns the max listeners for this emmiter // see SetMaxListeners func GetMaxListeners() int { return defaultEmmiter.GetMaxListeners() } func (e *emmiter) GetMaxListeners() int { return e.maxListeners } // ListenerCount returns the length of all registered listeners to a particular event func ListenerCount(evt EventName) int { return defaultEmmiter.ListenerCount(evt) } func (e *emmiter) ListenerCount(evt EventName) int { if e.evtListeners == nil { return 0 } len := 0 if evtListeners := e.evtListeners[evt]; evtListeners != nil { // len() should be just fine, but for any case on future... for _, l := range evtListeners { if l == nil { continue } len++ } } return len } // Listeners returns a copy of the array of listeners for the event named eventName. func Listeners(evt EventName) []Listener { return defaultEmmiter.Listeners(evt) } func (e *emmiter) Listeners(evt EventName) []Listener { if e.evtListeners == nil { return nil } var listeners []Listener if evtListeners := e.evtListeners[evt]; evtListeners != nil { // do not pass any inactive/removed listeners(nil) for _, l := range evtListeners { if l == nil { continue } listeners = append(listeners, l) } if len(listeners) > 0 { return listeners } } return nil } // On registers a particular listener for an event, func receiver parameter(s) is/are optional func On(evt EventName, listener ...Listener) { defaultEmmiter.On(evt, listener...) } func (e *emmiter) On(evt EventName, listener ...Listener) { e.AddListener(evt, listener...) } // Once adds a one time listener function for the event named eventName. // The next time eventName is triggered, this listener is removed and then invoked. func Once(evt EventName, listener ...Listener) { defaultEmmiter.Once(evt, listener...) } func (e *emmiter) Once(evt EventName, listener ...Listener) { if len(listener) == 0 { return } var modifiedListeners []Listener if e.evtListeners == nil { e.evtListeners = Events{} } for i, l := range listener { idx := len(e.evtListeners) + i // get the next index (where this event should be added) and adds the i for the 'capacity' func(listener Listener, index int) { fired := false // remove the specific listener from the listeners before fire the real listener modifiedListeners = append(modifiedListeners, func(data ...interface{}) { if e.evtListeners == nil { return } if !fired { // make sure that we don't get a panic(index out of array or nil map here if e.evtListeners[evt] != nil && (len(e.evtListeners[evt]) > index || index == 0) { e.mu.Lock() //e.evtListeners[evt] = append(e.evtListeners[evt][:index], e.evtListeners[evt][index+1:]...) // we do not must touch the order because of the pre-defined indexes, we need just to make this listener nil in order to be not executed, // and make the len of listeners increase when listener is not nil, not just the len of listeners. // so set this listener to nil e.evtListeners[evt][index] = nil e.mu.Unlock() } fired = true listener(data...) } }) }(l, idx) } e.AddListener(evt, modifiedListeners...) } // RemoveAllListeners removes all listeners, or those of the specified eventName. // Note that it will remove the event itself. // Returns an indicator if event and listeners were found before the remove. func RemoveAllListeners(evt EventName) bool { return defaultEmmiter.RemoveAllListeners(evt) } func (e *emmiter) RemoveAllListeners(evt EventName) bool { if e.evtListeners == nil { return false // has nothing to remove } e.mu.Lock() defer e.mu.Unlock() if listeners := e.evtListeners[evt]; listeners != nil { l := e.ListenerCount(evt) // in order to not get the len of any inactive/removed listeners delete(e.evtListeners, evt) if l > 0 { return true } } return false } // Clear removes all events and all listeners, restores Events to an empty value func Clear() { defaultEmmiter.Clear() } func (e *emmiter) Clear() { e.evtListeners = Events{} } // SetMaxListeners obviously this function allows the MaxListeners // to be decrease or increase. Set to zero for unlimited func SetMaxListeners(n int) { defaultEmmiter.SetMaxListeners(n) } func (e *emmiter) SetMaxListeners(n int) { if n < 0 { if EnableWarning { log.Printf("(events) warning: MaxListeners must be positive number, tried to set: %d", n) return } } e.maxListeners = n } // Len returns the length of all registered events func Len() int { return defaultEmmiter.Len() } func (e *emmiter) Len() int { if e.evtListeners == nil { return 0 } return len(e.evtListeners) }
28.566197
143
0.701607
b0e9718525a91d5887dc890f0b6646470d2766b2
1,007
py
Python
testOpera/operas/cache_test/cache_t3.py
canotf/aestate
e95580a8042103d0762b3edff8774b51908dcc72
[ "Apache-2.0" ]
null
null
null
testOpera/operas/cache_test/cache_t3.py
canotf/aestate
e95580a8042103d0762b3edff8774b51908dcc72
[ "Apache-2.0" ]
null
null
null
testOpera/operas/cache_test/cache_t3.py
canotf/aestate
e95580a8042103d0762b3edff8774b51908dcc72
[ "Apache-2.0" ]
null
null
null
# -*- utf-8 -*- import time from aestate.util.Log import logging from aestate.work.Cache import SqlCacheManage, CacheStatus from testOpera.table.demoModels import ReadXmlClass rxc = ReadXmlClass() log = logging.gen(rxc) scm = SqlCacheManage() def find(): s_time = time.time() start_time = time.time() for i in range(100): log.warn(rxc.findInDemo(id=i)) if i == 5: SqlCacheManage.status = CacheStatus.OPEN log.warn('execute:', time.time() - start_time) start_time = time.time() log.warn('using:', time.time() - s_time) log.info('get_size:', scm.get_size()) log.info('get_capacity_max:', scm.get_capacity_max()) log.info('get_max:', scm.get_max()) rxc.insertTest(name='a', password="b") log.warn('using:', time.time() - s_time) log.info('get_size:', scm.get_size()) log.info('get_capacity_max:', scm.get_capacity_max()) log.info('get_max:', scm.get_max()) find() find() log.info('size:', scm.get_size()) find()
27.216216
58
0.647468
45bae5c534848edffbebe506c88aee5b73c615e3
4,628
py
Python
prep/coco_pre_prep.py
gurkirt/FPN.pytorch1.0
ba9338a0ed511bd7b8659b57562bfad3788684a6
[ "MIT" ]
67
2019-03-06T01:27:37.000Z
2021-12-16T05:24:07.000Z
prep/coco_pre_prep.py
gurkirt/RetinaNet
ecd9d26152ab636586e4363b30c41413b84f76c7
[ "MIT" ]
9
2019-04-09T18:29:15.000Z
2021-12-16T12:13:00.000Z
prep/coco_pre_prep.py
gurkirt/FPN.pytorch
ba9338a0ed511bd7b8659b57562bfad3788684a6
[ "MIT" ]
22
2019-04-10T14:46:01.000Z
2022-01-10T03:18:12.000Z
""" Author: Gurkirt Singh Purpose: resave the annotations in desired format Licensed under The MIT License [see LICENSE for details] """ import json, os, pdb, cv2 import argparse parser = argparse.ArgumentParser(description='prepare VOC dataset') # anchor_type to be used in the experiment parser.add_argument('--base_dir', default='/home/gurkirt/datasets/voc/', help='Location to root directory for the dataset') # /mnt/mars-fast/datasets/ visuals = False def get_wh(images): img_list = {} for img in images: image_id = img['id'] box = [img['width'], img['height']] if str(image_id) in img_list.keys(): raise ('image_id should not repeat') else: img_list[str(image_id)] = box print('Number of images ', len(img_list)) return img_list def convert(size, box): '''Normlise box coordinate between 0 and 1''' dw = 1./size[0] dh = 1./size[1] xmin = box[0]*dw xmax = box[2]*dw ymin = box[1]*dh ymax = box[3]*dh return (xmin,ymin,xmax,ymax) def get_coco_classes(anno_file): with open(anno_file, 'r') as f: obj = json.load(f) cls_dict = obj['categories'] idsto = {} cls_list = [] id_list = [] super_list = [] scount = 0 count = 0 for c in cls_dict: cls_list.append(c['name']) id_list.append(str(c['id'])) supername = c['supercategory'] if supername not in super_list: super_list.append(supername) scount += 1 sl = super_list.index(supername) idsto[str(c['id'])] = [count, sl] # sl = slcount count += 1 return cls_list, super_list, id_list, idsto def get_image_annots(base_dir, filename, subset_str = 'train2017', annots=dict()): with open(filename, 'r') as f: obj = json.load(f) # pdb.set_trace() whs = get_wh(obj['images']) annos = obj['annotations'] for anno in annos: image_id = anno['image_id'] str_id = subset_str+'/{:012d}'.format(image_id) wh = whs[str(image_id)] if str_id not in annots['annotations'].keys(): annots['annotations'][str_id] = dict() annots['annotations'][str_id]['annos'] = [] annots['annotations'][str_id]['wh'] = wh annots['annotations'][str_id]['set'] = subset_str bb = anno['bbox'] bb[2] = bb[2] + bb[0] bb[3] = bb[3] + bb[1] cid = anno['category_id'] labels = annots['idstolabels'][str(cid)] if visuals: imagename = base_dir+subset_str+'/{:012d}.jpg'.format(image_id) print(imagename) image = cv2.imread(imagename) assert wh[0] == image.shape[1] and wh[1] == image.shape[0] print(bb, image.shape, wh, annots['classes'][labels[0]] ) image = cv2.rectangle(image,(int(bb[0]),int(bb[1])),(int(bb[2]),int(bb[3])),(0,255,0), thickness=3) cv2.imshow('image99', image) k = cv2.waitKey(0) bb = convert(wh, bb) condition = True for b in bb: if b<0 and b>1: condition = False if condition and bb[0]<bb[2] and bb[1]<bb[3]: an_b = {} an_b['cls'] = annots['classes'][labels[0]] an_b['label'] = labels[0] an_b['suprlbl'] = labels[1] an_b['bbox'] = bb annots['annotations'][str_id]['annos'].append(an_b) else: print('we are skipping ', bb, image_id, len(annots['annotations'][str_id])) # annos.append(anno) return annots if __name__ == '__main__': args = parser.parse_args() train_filename = args.base_dir + 'annotations/instances_train2017.json' val_filename = args.base_dir + 'annotations/instances_val2017.json' cls_list, super_list, id_list, idstolabels = get_coco_classes(val_filename) db = dict() db['classes'] = cls_list db['superclasses'] = super_list db['ids'] = id_list db['idstolabels'] = idstolabels db['annotations'] = dict() db = get_image_annots(args.base_dir, val_filename, 'val2017', db) db = get_image_annots(args.base_dir, train_filename, 'train2017', db) ic = 0 ac = 0 for img_id in db['annotations'].keys(): num_a = len(db['annotations'][img_id]['annos']) assert num_a>0, num_a ic += 1 ac += num_a print('Avergage number of annotation per image are ', float(ac)/ic) with open(args.base_dir + 'annots.json', 'w') as f: json.dump(db,f)
29.477707
124
0.571953
25d8d54c4f7f5bd1bc64e9719b7008d2d15847b7
2,120
cs
C#
Our.Umbraco.Query.Language.Tests/When_Building_Lucene_Query.cs
lars-erik/our-umbraco-query-language
aa6ce4d0e60ba91a9f53be67ba9b045484a6e910
[ "MIT" ]
null
null
null
Our.Umbraco.Query.Language.Tests/When_Building_Lucene_Query.cs
lars-erik/our-umbraco-query-language
aa6ce4d0e60ba91a9f53be67ba9b045484a6e910
[ "MIT" ]
null
null
null
Our.Umbraco.Query.Language.Tests/When_Building_Lucene_Query.cs
lars-erik/our-umbraco-query-language
aa6ce4d0e60ba91a9f53be67ba9b045484a6e910
[ "MIT" ]
null
null
null
using System; using System.Globalization; using Irony.Parsing; using Lucene.Net.Index; using Lucene.Net.Search; using NUnit.Framework; namespace Our.Umbraco.Query.Language.Tests { [TestFixture] public class When_Building_Lucene_Query : ParsingTest { [Test] public void Adds_Criteria_For_NodeType() { var queryString = "news"; var tree = ParseTree(queryString); var visitor = new LuceneQueryParser(); var query = visitor.Execute((IVisitable)tree.Root.AstNode); Assert.That(query.ToString(), Is.EqualTo("+__nodeType:news")); } [Test] public void Adds_Order_And_Limit() { var queryString = "latest 1 news"; var tree = ParseTree(queryString); var visitor = new LuceneQueryParser(); visitor.Execute((IVisitable)tree.Root.AstNode); Assert.That(visitor.Limit, Is.EqualTo(1)); Assert.That(visitor.Sort.GetSort()[0].GetField(), Is.EqualTo("__created")); } } public class LuceneQueryParser : IQueryVisitor { private BooleanQuery query; public Sort Sort { get; private set; } public int Limit { get; private set; } public LuceneQueryParser() { } public Lucene.Net.Search.Query Execute(IVisitable node) { query = new Lucene.Net.Search.BooleanQuery(); node.Visit(this); return query; } public void Visit(ContentNode node) { query.Add(new TermQuery(new Term("__nodeType", node.ContentType)), BooleanClause.Occur.MUST); } public void Visit(OrderModifierNode node) { Sort = new Sort(new SortField("__created", CultureInfo.InvariantCulture, true)); } public void Visit(LimitModifierNode limitModifier) { Limit = limitModifier.Limit; } // TODO: Baseclass this void IQueryVisitor.Visit(IVisitable node) { node.Visit(this); } } }
27.179487
105
0.585377
031da442d0500c712d64656de4df09852905a755
716
hh
C++
UserWorkDir/P02_Geometry/source/include/PrimaryGenerator.hh
hmdyt/Geant4Tutorial
cf6dea24a983a80b1994f3ca82fab5e7bb27f03c
[ "MIT" ]
2
2020-07-08T12:54:10.000Z
2021-07-21T02:37:02.000Z
P09_Analysis/source-CS/include/PrimaryGenerator.hh
koichi-murakami/g4tutorial2020
0162a94dc1407a39dd0651ac530d10913037c6f0
[ "BSD-2-Clause" ]
null
null
null
P09_Analysis/source-CS/include/PrimaryGenerator.hh
koichi-murakami/g4tutorial2020
0162a94dc1407a39dd0651ac530d10913037c6f0
[ "BSD-2-Clause" ]
1
2019-12-27T06:48:15.000Z
2019-12-27T06:48:15.000Z
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // PrimaryGenerator.hh //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #ifndef PrimaryGenerator_h #define PrimaryGenerator_h 1 #include "G4VUserPrimaryGeneratorAction.hh" class G4Event; class G4ParticleGun; //------------------------------------------------------------------------------ class PrimaryGenerator : public G4VUserPrimaryGeneratorAction //------------------------------------------------------------------------------ { public: PrimaryGenerator(); ~PrimaryGenerator(); public: void GeneratePrimaries( G4Event* ); private: G4ParticleGun* fpParticleGun; }; #endif
27.538462
80
0.420391
96fc344c798a199c3d353e15e3f708800913d9b1
981
cs
C#
src/Sanderling.ABot/Bot/Strategies/WaitForCommandState.cs
Fulborg/A-Bot
6688dca1bf6c23129c6bd291ed01420d354116d0
[ "Apache-2.0" ]
null
null
null
src/Sanderling.ABot/Bot/Strategies/WaitForCommandState.cs
Fulborg/A-Bot
6688dca1bf6c23129c6bd291ed01420d354116d0
[ "Apache-2.0" ]
null
null
null
src/Sanderling.ABot/Bot/Strategies/WaitForCommandState.cs
Fulborg/A-Bot
6688dca1bf6c23129c6bd291ed01420d354116d0
[ "Apache-2.0" ]
null
null
null
using System.Linq; using SlackAPI; namespace Sanderling.ABot.Bot.Strategies { internal class WaitForCommandState : IStragegyState { private SlackClient slack; public WaitForCommandState(string messageToSend) { slack = new SlackClient("https://hooks.slack.com/services/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"); slack.GetChannelList(_ => { }); var channelId = slack.Channels.FirstOrDefault().id; slack.PostMessage(pr => { }, channelId, "testMessageV2", "EveBot1", blocks: new[] { new ActionsBlock() { block_id = "t1", elements = new[] { new ButtonElement() {action_id = "hooray", text = new Text(){text = "Hooray"}}, } } }); } public IBotTask GetStateActions(Bot bot) { //TODO Check command server if anything required return null; } public IBotTask GetStateExitActions(Bot bot) => null; public IStragegyState NextState { get; private set; } public bool MoveToNext => NextState != null; } }
25.153846
108
0.685015
186241ff367330cb493a55bacdc583ec07667bfa
2,889
ts
TypeScript
src/provider/aws/ec2/vpc/cmds/flowlogsEnabled.test.ts
lstatro/cloud-search
fc57a420ffd98f03f25f8d8c0b5f3e74d0e00f51
[ "MIT" ]
2
2021-06-03T21:30:52.000Z
2021-07-28T02:29:00.000Z
src/provider/aws/ec2/vpc/cmds/flowlogsEnabled.test.ts
lstatro/cloud-search
fc57a420ffd98f03f25f8d8c0b5f3e74d0e00f51
[ "MIT" ]
6
2020-10-13T03:17:39.000Z
2021-08-14T20:17:40.000Z
src/provider/aws/ec2/vpc/cmds/flowlogsEnabled.test.ts
lstatro/cloud-search
fc57a420ffd98f03f25f8d8c0b5f3e74d0e00f51
[ "MIT" ]
null
null
null
import { useFakeTimers, SinonFakeTimers } from 'sinon' import { mock, restore } from 'aws-sdk-mock' import { handler } from './flowlogsEnabled' import { expect } from 'chai' describe('vpc flowlogs enabled', () => { const now = new Date(0) let clock: SinonFakeTimers beforeEach(() => { clock = useFakeTimers(now) mock('EC2', 'describeRegions', { Regions: [{ RegionName: 'us-east-1' }] }) }) afterEach(() => { clock.restore() restore() }) it('should return OK when passed in a ResourceId that has FlowLogs enabled ', async () => { mock('EC2', 'describeFlowLogs', { FlowLogs: [{ ResourceId: 'test' }], }) const audits = await handler({ region: 'test', profile: 'test', resourceId: 'test', }) expect(audits).to.eql([ { physicalId: 'test', profile: 'test', provider: 'aws', region: 'test', rule: 'FlowlogsEnabled', service: 'ec2', state: 'OK', time: '1970-01-01T00:00:00.000Z', }, ]) }) it('should return FAIL when passed a ResourceId with no FlowLogs', async () => { mock('EC2', 'describeFlowLogs', { FlowLogs: [], }) const audits = await handler({ region: 'test', profile: 'test', resourceId: 'test', }) expect(audits).to.eql([ { physicalId: 'test', profile: 'test', provider: 'aws', region: 'test', rule: 'FlowlogsEnabled', service: 'ec2', state: 'FAIL', time: '1970-01-01T00:00:00.000Z', }, ]) }) it('should return OK after listing VPCs, then checking if flowlogs are enabled', async () => { mock('EC2', 'describeVpcs', { Vpcs: [{ VpcId: 'test' }], }) mock('EC2', 'describeFlowLogs', { FlowLogs: [ { ResourceId: 'test', }, ], }) const audits = await handler({ region: 'test', profile: 'test', }) expect(audits).to.eql([ { physicalId: 'test', profile: 'test', provider: 'aws', region: 'test', rule: 'FlowlogsEnabled', service: 'ec2', state: 'OK', time: '1970-01-01T00:00:00.000Z', }, ]) }) it('should return FAIL after listing VPCs, then checking if flowlogs are enabled', async () => { mock('EC2', 'describeVpcs', { Vpcs: [ { VpcId: 'test', }, ], }) mock('EC2', 'describeFlowLogs', { FlowLogs: [], }) const audits = await handler({ region: 'test', profile: 'test', }) expect(audits).to.eql([ { physicalId: 'test', profile: 'test', provider: 'aws', region: 'test', rule: 'FlowlogsEnabled', service: 'ec2', state: 'FAIL', time: '1970-01-01T00:00:00.000Z', }, ]) }) })
23.876033
98
0.509519
5e24d233d8064f01eb2b4e4599e6059008d8dc72
2,475
swift
Swift
Sources/CustomizingProtocols/CustomCell.swift
TintPoint/Overlay
1a9ae1016492f38a89fdaead041247667e9ffbf7
[ "MIT" ]
54
2016-08-12T15:44:29.000Z
2020-12-26T06:04:04.000Z
Sources/CustomizingProtocols/CustomCell.swift
TintPoint/Overlay
1a9ae1016492f38a89fdaead041247667e9ffbf7
[ "MIT" ]
9
2016-08-13T14:47:42.000Z
2018-07-18T06:03:17.000Z
Sources/CustomizingProtocols/CustomCell.swift
TintPoint/Overlay
1a9ae1016492f38a89fdaead041247667e9ffbf7
[ "MIT" ]
8
2016-08-25T13:16:47.000Z
2020-12-26T06:04:06.000Z
// // CustomCell.swift // Overlay // // Created by Justin Jia on 6/24/17. // Copyright © 2017 TintPoint. MIT license. // import UIKit /// A protocol that describes a cell that will be customized. public protocol CustomCell { /// The `UINib` that describes the cell, or `nil` if no nib is set. static var contentNib: UINib? { get } /// The `String` that represents the cell identifier. static var suggestedIdentifier: String { get } /// Returns a `CustomCell` loaded from the nib. /// - Returns: a `CustomCell` loaded from the nib, or `nil` if no nib is set. static func loadCellFromNib(owner: Any?) -> Self? } /// A protocol that describes a header footer view that will be customized. public protocol CustomHeaderFooterView { /// The `UINib` that describes the header footer view, or `nil` if no nib is set. static var contentNib: UINib? { get } /// The `String` that represents the header footer view identifier. static var suggestedIdentifier: String { get } /// Returns a `CustomHeaderFooterView` loaded from the nib. /// - Returns: a `CustomHeaderFooterView` loaded from the nib, or `nil` if no nib is set. static func loadHeaderFooterViewFromNib(owner: Any?) -> Self? } /// A protocol that describes a reusable view that will be customized. public protocol CustomReusableView { /// The `UINib` that describes the reusable view, or `nil` if no nib is set. static var contentNib: UINib? { get } /// The `String` that represents the reusable view kind. static var suggestedKind: String { get } /// The `String` that represents the reusable view identifier. static var suggestedIdentifier: String { get } /// Returns a `CustomReusableView` loaded from the nib. /// - Returns: a `CustomReusableView` loaded from the nib, or `nil` if no nib is set. static func loadReusableViewFromNib(owner: Any?) -> Self? } public extension CustomCell { static func loadCellFromNib(owner: Any? = nil) -> Self? { return contentNib?.instantiate(withOwner: owner).first as? Self } } public extension CustomHeaderFooterView { static func loadHeaderFooterViewFromNib(owner: Any? = nil) -> Self? { return contentNib?.instantiate(withOwner: owner).first as? Self } } public extension CustomReusableView { static func loadReusableViewFromNib(owner: Any? = nil) -> Self? { return contentNib?.instantiate(withOwner: owner).first as? Self } }
35.357143
93
0.694949
33a80e7a802c807041e316bd49f2303be4ae7fa2
706
h
C
Plugins/UnrealImGui/Source/ImGui/Private/Widgets/SImGuiLayout.h
bernhardrieder/Quarto-with-MCTS-AI
5932ffb04a999c2a2ad311e68aaa46c5c2a00164
[ "Unlicense" ]
1
2020-06-25T10:02:19.000Z
2020-06-25T10:02:19.000Z
Plugins/UnrealImGui/Source/ImGui/Private/Widgets/SImGuiLayout.h
bernhardrieder/Quarto-with-MCTS-AI
5932ffb04a999c2a2ad311e68aaa46c5c2a00164
[ "Unlicense" ]
null
null
null
Plugins/UnrealImGui/Source/ImGui/Private/Widgets/SImGuiLayout.h
bernhardrieder/Quarto-with-MCTS-AI
5932ffb04a999c2a2ad311e68aaa46c5c2a00164
[ "Unlicense" ]
null
null
null
// Distributed under the MIT License (MIT) (see accompanying LICENSE file) #pragma once #include <Widgets/SCompoundWidget.h> class FImGuiModuleManager; class UGameViewportClient; // Layout preset for ImGui Widget. class SImGuiLayout : public SCompoundWidget { typedef SCompoundWidget Super; public: SLATE_BEGIN_ARGS(SImGuiLayout) {} SLATE_ARGUMENT(FImGuiModuleManager*, ModuleManager) SLATE_ARGUMENT(UGameViewportClient*, GameViewport) SLATE_ARGUMENT(int32, ContextIndex) SLATE_END_ARGS() void Construct(const FArguments& InArgs); const TWeakObjectPtr<UGameViewportClient>& GetGameViewport() const { return GameViewport; } private: TWeakObjectPtr<UGameViewportClient> GameViewport; };
21.393939
92
0.805949
06dc96779b55679a50f09db099de34fa259fef93
29
py
Python
lingua_franca/config.py
NeonDaniel/lingua-franca
eee95702016b4013b0d81dc74da98cd2d2f53358
[ "Apache-2.0" ]
null
null
null
lingua_franca/config.py
NeonDaniel/lingua-franca
eee95702016b4013b0d81dc74da98cd2d2f53358
[ "Apache-2.0" ]
null
null
null
lingua_franca/config.py
NeonDaniel/lingua-franca
eee95702016b4013b0d81dc74da98cd2d2f53358
[ "Apache-2.0" ]
null
null
null
load_langs_on_demand = False
14.5
28
0.862069
b8aca881e3e3104a8277d099a280edf60869aa4d
4,412
c
C
romio/mpi-io/fortran/read_ordf.c
RWTH-OS/MP-MPICH
f2ae296477bb9d812fda587221b3419c09f85b4a
[ "mpich2" ]
null
null
null
romio/mpi-io/fortran/read_ordf.c
RWTH-OS/MP-MPICH
f2ae296477bb9d812fda587221b3419c09f85b4a
[ "mpich2" ]
null
null
null
romio/mpi-io/fortran/read_ordf.c
RWTH-OS/MP-MPICH
f2ae296477bb9d812fda587221b3419c09f85b4a
[ "mpich2" ]
1
2021-01-23T11:01:01.000Z
2021-01-23T11:01:01.000Z
/* * $Id: read_ordf.c 3744 2005-07-18 10:55:08Z georg $ * * Copyright (C) 1997 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "mpio.h" #include "adio.h" #if defined(MPIO_BUILD_PROFILING) || defined(HAVE_WEAK_SYMBOLS) #ifdef FORTRANCAPS #define mpi_file_read_ordered_ PMPI_FILE_READ_ORDERED #elif defined(FORTRANDOUBLEUNDERSCORE) #define mpi_file_read_ordered_ pmpi_file_read_ordered__ #elif !defined(FORTRANUNDERSCORE) #if defined(HPUX) || defined(SPPUX) #pragma _HP_SECONDARY_DEF pmpi_file_read_ordered pmpi_file_read_ordered_ #endif #define mpi_file_read_ordered_ pmpi_file_read_ordered #else #if defined(HPUX) || defined(SPPUX) #pragma _HP_SECONDARY_DEF pmpi_file_read_ordered_ pmpi_file_read_ordered #endif #define mpi_file_read_ordered_ pmpi_file_read_ordered_ #endif #if defined(HAVE_WEAK_SYMBOLS) #if defined(HAVE_PRAGMA_WEAK) #if defined(FORTRANCAPS) #pragma weak MPI_FILE_READ_ORDERED = PMPI_FILE_READ_ORDERED #elif defined(FORTRANDOUBLEUNDERSCORE) #pragma weak mpi_file_read_ordered__ = pmpi_file_read_ordered__ #elif !defined(FORTRANUNDERSCORE) #pragma weak mpi_file_read_ordered = pmpi_file_read_ordered #else #pragma weak mpi_file_read_ordered_ = pmpi_file_read_ordered_ #endif #elif defined(HAVE_ATTRIBUTE_WEAK) #if defined(FORTRANCAPS) void FORTRAN_API MPI_FILE_READ_ORDERED (MPI_Fint *fh,void *buf,int *count, MPI_Fint *datatype,MPI_Status *status, int *ierr ) __attribute__ ((weak, alias ("PMPI_FILE_READ_ORDERED"))); #elif defined(FORTRANDOUBLEUNDERSCORE) void FORTRAN_API mpi_file_read_ordered__ (MPI_Fint *fh,void *buf,int *count, MPI_Fint *datatype,MPI_Status *status, int *ierr ) __attribute__ ((weak, alias ("pmpi_file_read_ordered__"))); #elif !defined(FORTRANUNDERSCORE) void FORTRAN_API mpi_file_read_ordered (MPI_Fint *fh,void *buf,int *count, MPI_Fint *datatype,MPI_Status *status, int *ierr ) __attribute__ ((weak, alias ("pmpi_file_read_ordered"))); #else void FORTRAN_API mpi_file_read_ordered_ (MPI_Fint *fh,void *buf,int *count, MPI_Fint *datatype,MPI_Status *status, int *ierr ) __attribute__ ((weak, alias ("pmpi_file_read_ordered_"))); #endif #elif defined(HAVE_PRAGMA_HP_SEC_DEF) #if defined(FORTRANCAPS) #pragma _HP_SECONDARY_DEF PMPI_FILE_READ_ORDERED MPI_FILE_READ_ORDERED #elif defined(FORTRANDOUBLEUNDERSCORE) #pragma _HP_SECONDARY_DEF pmpi_file_read_ordered__ mpi_file_read_ordered__ #elif !defined(FORTRANUNDERSCORE) #pragma _HP_SECONDARY_DEF pmpi_file_read_ordered mpi_file_read_ordered #else #pragma _HP_SECONDARY_DEF pmpi_file_read_ordered_ mpi_file_read_ordered_ #endif #elif defined(HAVE_PRAGMA_CRI_DUP) #if defined(FORTRANCAPS) #pragma _CRI duplicate MPI_FILE_READ_ORDERED as PMPI_FILE_READ_ORDERED #elif defined(FORTRANDOUBLEUNDERSCORE) #pragma _CRI duplicate mpi_file_read_ordered__ as pmpi_file_read_ordered__ #elif !defined(FORTRANUNDERSCORE) #pragma _CRI duplicate mpi_file_read_ordered as pmpi_file_read_ordered #else #pragma _CRI duplicate mpi_file_read_ordered_ as pmpi_file_read_ordered_ #endif /* end of weak pragmas */ #endif /* Include mapping from MPI->PMPI */ #include "mpioprof.h" #endif #else #ifdef FORTRANCAPS #define mpi_file_read_ordered_ MPI_FILE_READ_ORDERED #elif defined(FORTRANDOUBLEUNDERSCORE) #define mpi_file_read_ordered_ mpi_file_read_ordered__ #elif !defined(FORTRANUNDERSCORE) #if defined(HPUX) || defined(SPPUX) #pragma _HP_SECONDARY_DEF mpi_file_read_ordered mpi_file_read_ordered_ #endif #define mpi_file_read_ordered_ mpi_file_read_ordered #else #if defined(HPUX) || defined(SPPUX) #pragma _HP_SECONDARY_DEF mpi_file_read_ordered_ mpi_file_read_ordered #endif #endif #endif #if defined(MPIHP) || defined(MPILAM) void mpi_file_read_ordered_(MPI_Fint *fh,void *buf,int *count, MPI_Fint *datatype,MPI_Status *status, int *ierr ) { MPI_File fh_c; MPI_Datatype datatype_c; fh_c = MPI_File_f2c(*fh); datatype_c = MPI_Type_f2c(*datatype); *ierr = MPI_File_read_ordered(fh_c,buf,*count,datatype_c,status); } #else void FORTRAN_API mpi_file_read_ordered_(MPI_Fint *fh,void *buf,int *count, MPI_Datatype *datatype,MPI_Status *status, int *ierr ){ MPI_File fh_c; fh_c = MPI_File_f2c(*fh); *ierr = MPI_File_read_ordered(fh_c,buf,*count,*datatype,status); } #endif
34.740157
77
0.784225
7f5dc367cd9d19b4066431e84122e0d6e7cba488
250
php
PHP
app/Http/Controllers/StationController.php
nynkevd/IPMEDT4
e5300290aaf4e2a74571dc79ce7f1e9a2f6c25fa
[ "MIT" ]
null
null
null
app/Http/Controllers/StationController.php
nynkevd/IPMEDT4
e5300290aaf4e2a74571dc79ce7f1e9a2f6c25fa
[ "MIT" ]
8
2020-07-17T01:55:49.000Z
2022-02-26T10:54:00.000Z
app/Http/Controllers/StationController.php
nynkevd/IPMEDT4
e5300290aaf4e2a74571dc79ce7f1e9a2f6c25fa
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Station; class StationController extends Controller { // public function getSTations(){ $stations = Station::pluck('station'); return $stations; } }
14.705882
43
0.688
9d346dcd244816362c950ade5e3886b111efab38
2,563
dart
Dart
lib/app/global/widget/meet_link_selector.dart
DSC-KIIT/class-links
920cd86af042b577893e934187df023e9c7c0454
[ "MIT" ]
1
2022-03-07T05:21:24.000Z
2022-03-07T05:21:24.000Z
lib/app/global/widget/meet_link_selector.dart
DSC-KIIT/class-links
920cd86af042b577893e934187df023e9c7c0454
[ "MIT" ]
1
2022-02-19T16:29:41.000Z
2022-02-19T16:29:41.000Z
lib/app/global/widget/meet_link_selector.dart
DSC-KIIT/class-links
920cd86af042b577893e934187df023e9c7c0454
[ "MIT" ]
1
2022-01-07T05:54:43.000Z
2022-01-07T05:54:43.000Z
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; enum MeetLinkType { googleClassroom, zoomLink } class MeetLinkController { final TextEditingController textController = TextEditingController(); String get text => textController.text; set text(String s) => textController.text = s; } class MeetLinkSelector extends StatelessWidget { final MeetLinkController controller; final MeetLinkType meetType; const MeetLinkSelector({ Key? key, required this.controller, required this.meetType, }) : super(key: key); String? validation(String? value) { if (meetType == MeetLinkType.googleClassroom) { if (value == null || value.isEmpty) { return null; } else if (!urlValidator(value)) { return 'Please enter a valid Google Classroom link'; } else { return null; } } else if (meetType == MeetLinkType.zoomLink) { if (value == null || value.isEmpty) { return null; } else if (!urlValidator(value)) { return 'Please enter a valid Zoom link'; } else { return null; } } return null; } bool urlValidator(String url) { if (meetType == MeetLinkType.googleClassroom) { if (url.startsWith('https://classroom.google.com/')) return true; if (url.startsWith('https://meet.google.com/')) return true; } else if (meetType == MeetLinkType.zoomLink) { if (url.contains('zoom.us') && url.startsWith('https://')) return true; } return false; } @override Widget build(BuildContext context) => Stack( children: [ TextFormField( controller: controller.textController, maxLines: 1, decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.circular(8.0), borderSide: const BorderSide( width: 0, style: BorderStyle.none, ), ), suffixIcon: IconButton( onPressed: _pastText, icon: const Icon(Icons.paste), ), filled: true, hintText: "Paste ${meetType == MeetLinkType.googleClassroom ? "google meet" : "zoom"} Link", ), validator: validation, ), ], ); void _pastText() async { final k = await Clipboard.getData("text/plain"); if (k != null && k.text != null) { controller.textController.text = k.text!; } } }
28.797753
100
0.584471
0ab13ef32781af1d150ce467116704372b8d8513
415
cs
C#
Coderful.Layouts/Logic/View/MyWebViewPage.cs
manhng83/niaher-coderful
d6e894110ad3a8ab71cb9953bce9627792353bc3
[ "MIT", "Unlicense" ]
null
null
null
Coderful.Layouts/Logic/View/MyWebViewPage.cs
manhng83/niaher-coderful
d6e894110ad3a8ab71cb9953bce9627792353bc3
[ "MIT", "Unlicense" ]
null
null
null
Coderful.Layouts/Logic/View/MyWebViewPage.cs
manhng83/niaher-coderful
d6e894110ad3a8ab71cb9953bce9627792353bc3
[ "MIT", "Unlicense" ]
null
null
null
namespace Coderful.Layouts.Logic.View { using Coderful.Web.Mvc; public abstract class MyWebViewPage<TModel> : CoderfulWebViewPage<TModel, StrongViewBag> { protected MyWebViewPage() : base(new StrideViewBagFactory()) { } private class StrideViewBagFactory : IViewBagFactory<StrongViewBag> { public StrongViewBag Create(dynamic viewBag) { return new StrongViewBag(viewBag); } } } }
19.761905
89
0.73494
a3702a21120608069a622452ad678b932ef4008c
242
java
Java
spring/spring-cloud/task-service/src/test/java/io/ashimjk/spring/cloud/task/service/TaskServiceApplicationTests.java
ashimjk/ajk-research
a4061a6451229e0a49dac8818e51370c9bda53e4
[ "MIT" ]
2
2022-02-27T14:20:46.000Z
2022-03-29T16:41:55.000Z
spring/spring-cloud/task-service/src/test/java/io/ashimjk/spring/cloud/task/service/TaskServiceApplicationTests.java
ashim-jung-khadka/ajk-research
a4061a6451229e0a49dac8818e51370c9bda53e4
[ "MIT" ]
22
2021-09-02T17:42:24.000Z
2022-03-02T09:59:08.000Z
spring/spring-cloud/task-service/src/test/java/io/ashimjk/spring/cloud/task/service/TaskServiceApplicationTests.java
ashim-jung-khadka/ajk-research
a4061a6451229e0a49dac8818e51370c9bda53e4
[ "MIT" ]
null
null
null
package io.ashimjk.spring.cloud.task.service; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class TaskServiceApplicationTests { @Test void contextLoads() { } }
17.285714
60
0.764463
160b784bb873bb95e1c9fd0e3c9161f65477f8f7
2,239
swift
Swift
LocationManager/LocationManager/ViewController.swift
agamarra88/iOSLocationManager
9d475417fa268659b45d11d2119b85032d9bb5e9
[ "MIT" ]
null
null
null
LocationManager/LocationManager/ViewController.swift
agamarra88/iOSLocationManager
9d475417fa268659b45d11d2119b85032d9bb5e9
[ "MIT" ]
null
null
null
LocationManager/LocationManager/ViewController.swift
agamarra88/iOSLocationManager
9d475417fa268659b45d11d2119b85032d9bb5e9
[ "MIT" ]
null
null
null
// // ViewController.swift // LocationManager // // Created by Arturo Gamarra on 12/9/19. // Copyright © 2019 Abstract. All rights reserved. // import UIKit import CoreLocation class ViewController: UIViewController { let identifier = "Cell" @IBOutlet weak var tableView:UITableView! var locations:[LocationDate] = [] override func viewDidLoad() { super.viewDidLoad() ABSLocationManager.shared.delegate = self ABSLocationManager.shared.alwaysRequestLocation = true ABSLocationManager.shared.startUpdatingLocation() } @IBAction func clearButtonTapped(_ sender: Any) { locations.removeAll() tableView.reloadData() } } extension ViewController: ABSLocationManagerDelegate { func locationManager(_ sender: ABSLocationManager, unavailableWithStatus status: CLAuthorizationStatus) { // If general location settings are disabled then open general location settings let urlString = ABSLocationManager.shared.isLocationServicesEnabled ? UIApplication.openSettingsURLString : "App-Prefs:root=Privacy&path=LOCATION" if let url = URL(string: urlString) { UIApplication.shared.open(url) } } func locationManager(_ sender: ABSLocationManager, didFailWithError error: Error) { } func locationManager(_ sender: ABSLocationManager, updatedLocation location: CLLocation) { let locationDate = LocationDate(location: location, date: Date()) locations.insert(locationDate, at: 0) tableView.reloadData() } } extension ViewController:UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return locations.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) let item = locations[indexPath.item] cell.textLabel?.text = "Lat: \(item.location.coordinate.latitude) Long:\(item.location.coordinate.longitude)" cell.detailTextLabel?.text = item.date.description return cell } }
32.449275
155
0.699866
c1866c8d1177518de90b58b9eae8f2d5628d8dfd
11,048
lua
Lua
lgi/override/GLib-Variant.lua
gregier/lgi
9bfc4331217f3edbf8f3e34ab2ef9e39ba0c02d7
[ "MIT" ]
1
2016-11-01T05:35:37.000Z
2016-11-01T05:35:37.000Z
lgi/override/GLib-Variant.lua
gregier/lgi
9bfc4331217f3edbf8f3e34ab2ef9e39ba0c02d7
[ "MIT" ]
null
null
null
lgi/override/GLib-Variant.lua
gregier/lgi
9bfc4331217f3edbf8f3e34ab2ef9e39ba0c02d7
[ "MIT" ]
null
null
null
------------------------------------------------------------------------------ -- -- LGI GLib Variant support implementation. -- -- Copyright (c) 2011 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local select, type, pairs, tostring, setmetatable, error, assert = select, type, pairs, tostring, setmetatable, error, assert local lgi = require 'lgi' local core = require 'lgi.core' local bytes = require 'bytes' local gi = core.gi local GLib = lgi.GLib local Variant = GLib.Variant local variant_info = gi.GLib.Variant -- Add custom methods for variant handling. Variant._refsink = variant_info.methods.ref_sink Variant._free = variant_info.methods.unref -- Add 'type' property to variant, an alias to get_type(). Variant._attribute = { type = { get = Variant.get_type_string } } local VariantBuilder = GLib.VariantBuilder local VariantType = GLib.VariantType -- VariantBuilder and VariantType are boxed only in glib-2.29 and -- newer, add custom _free recipe for older glibs. if not VariantBuilder._gtype then VariantBuilder._free = gi.GLib.VariantBuilder.methods.unref end if not VariantType._gtype then VariantBuilder._free = gi.GLib.VariantType.methods.free end -- Add constants containing basic variant types. for k, v in pairs { BOOLEAN = 'b', BYTE = 'y', INT16 = 'n', UINT16 = 'q', INT32 = 'i', UINT32 = 'u', INT64 = 'x', UINT64 = 't', DOUBLE = 'd', STRING = 's', OBJECT_PATH = 'o', SIGNATURE = 'g', VARIANT = 'v', ANY = '*', BASIC = '?', MAYBE = 'm*', ARRAY = 'a*', TUPLE = 'r', UNIT = '()', DICT_ENTRY = '{?*}', DICTIONARY = 'a{?*}', STRING_ARRAY = 'as', BYTESTRING = 'ay', BYTESTRING_ARRAY = 'aay', } do VariantType[k] = VariantType.new(v) end -- g_variant_get_type() is hidden by g-i (because scanner thinks that -- this is GType getter), so provide manual override. function Variant:get_type() return VariantType.new(Variant.get_type_string(self)) end -- Implementation of Variant.new() from type and value. local variant_new local variant_basic_typemap = { b = 'boolean', y = 'byte', n = 'int16', q = 'uint16', i = 'int32', u = 'uint32', x = 'int64', t = 'uint64', d = 'double', s = 'string', o = 'object_path', g = 'signature', } -- Checks validity of variant type format beginning at pos, return -- position in format string after end of valid part. Returns nil -- when format is not valid. local function read_format(format, pos, basic) local t = format:sub(pos, pos) pos = pos + 1 if variant_basic_typemap[t] then return pos elseif basic then return nil elseif t =='v' then return pos elseif t == 'a' or t == 'm' then return read_format(format, pos) elseif t == '{' then pos = read_format(format, pos, true) if pos then pos = read_format(format, pos) end if not pos or format:sub(pos, pos) ~= '}' then return nil end return pos + 1 elseif t == '(' then while format:sub(pos, pos) ~= ')' do pos = read_format(format, pos) if not pos then return nil end end return pos + 1 end end local function variant_new_basic(format, val) local func = variant_basic_typemap[format] if not func then return end local v = Variant['new_' .. func](val) if not v then error(("Variant.new(`%s') - invalid source value"):format(format)) end return v end function variant_new(format, pos, val) local t = format:sub(pos, pos) pos = pos + 1 local variant = variant_new_basic(t, val) if variant then return variant, pos elseif t == 'v' then return Variant.new_variant(val), pos elseif t == 'm' then local epos if val then variant, epos = variant_new(format, pos, val) else epos = read_format(format, pos) if not epos then return nil end end return Variant.new_maybe(VariantType.new(format:sub(pos, epos - 1)), variant), epos elseif t == 'a' then if format:sub(pos, pos) == 'y' then -- Bytestring is just simple Lua string. return Variant.new_bytestring(val), pos + 1 end local epos = read_format(format, pos) if not epos then return nil end local et = VariantType.new(format:sub(pos, epos - 1)) local builder = VariantBuilder.new(VariantType.new_array(et)) if et:is_subtype_of(VariantType.DICT_ENTRY) then -- Map dictionary to Lua table directly. for k, v in pairs(val) do builder:add_value(Variant.new_dict_entry( variant_new(format, pos + 1, k), variant_new(format, pos + 2, v))) end else -- We have an issue with 'array with holes'. An attempt is -- made here to work around it with 'n' field, if present. for i = 1, val.n or #val do builder:add_value(variant_new(format, pos, val[i])) end end return builder:_end(), epos elseif t == '(' or t == '{' then -- Extract and check whole tuple or entry format. local epos = read_format(format, pos -1) if not epos then return nil end -- Prepare builder with specified format. local builder = VariantBuilder.new( VariantType.new(format:sub(pos - 1, epos - 1))) -- Loop through provided value array and build variant using -- prepared builder. local i = 1 while not format:sub(pos, pos):match('^[%)}]') do local v, epos = variant_new(format, pos, val[i]) if not v then return nil end builder:add_value(v) pos = epos i = i + 1 end return builder:_end(), pos + 1 end end -- Variant.new() is just a facade over variant_new backend. function Variant.new(vt, val) if type(vt) == 'userdata' then -- Wrap existing pointer to variant. return core.record.new(Variant, vt, val) end if type(vt) ~= 'string' then vt = vt:dup_string() end local v, epos = variant_new(vt, 1, val) if not v or epos ~= #vt + 1 then error(("Variant.new(`%s') - invalid type"):format(vt)) end return v end function Variant:_new(...) return Variant.new(...) end -- Implement VariantBuilder:add() using the same facade. function VariantBuilder:add(type, val) VariantBuilder.add_value(Variant.new(type, val)) end -- Converts variant to nearest possible Lua value, but leaves arrays -- intact (use indexing and/or iterators for handling arrays). local simple_unpack_map = { b = 'boolean', y = 'byte', n = 'int16', q = 'uint16', i = 'int32', u = 'uint32', x = 'int64', t = 'uint64', d = 'double', s = 'string', o = 'string', g = 'string', v = 'variant' } local function variant_get(v) local type = v:get_type_string() local func = simple_unpack_map[type] if func then return Variant['get_' .. func](v) elseif type:match('^m') then return v:n_children() == 1 and variant_get(v:get_child_value(0)) or nil elseif type:match('^[{(r]') then -- Unpack dictionary entry or tuple into array. local array = { n = v:n_children() } for i = 1, array.n do array[i] = variant_get(v:get_child_value(i - 1)) end return array elseif Variant.is_of_type(v, VariantType.BYTESTRING) then return tostring(Variant.get_bytestring(v)) elseif Variant.is_of_type(v, VariantType.DICTIONARY) then -- Return proxy table which dynamically looks up items in the -- target variant. local meta = {} if Variant.is_of_type(v, VariantType.new('a{s*}')) then -- Use g_variant_lookup_value. function meta:__index(key) local found = Variant.lookup_value(v, key) return found and variant_get(found) end else -- Custom search, walk key-by-key. Cache key positions in -- the meta table. function meta:__index(key) for i = 0, Variant.n_children(v) - 1 do local entry = Variant.get_child_value(v, i) local vkey = variant_get(Variant.get_child_value(entry, 0)) if vkey == key then local found = Variant.get_child_value(entry, 1) return found and variant_get(found) end end end end return setmetatable({}, meta) end -- No simple unpacking is possible, return just self. Complex -- compound types are meant to be accessed by indexing or -- iteration, implemented below. return v end -- Map simple unpacking to reading 'value' property. Variant._attribute.value = { get = variant_get } -- Define meaning of # and number-indexing to children access. Note -- that GVariant g_asserts when these methods are invoked on variants -- of inappropriate type, so we have to check manually before. function Variant:_len() return self:is_container() and self:n_children() or 0 end local variant_element = Variant._element function Variant:_element(variant, name) -- If number is requested, consider it a special operation, -- indexing a variant. if type(name) == 'number' then return name, '_index' end return variant_element(self, variant, name) end function Variant:_access_index(variant, index, ...) assert(select('#', ...) == 0, 'GLib.Variant is not writable') if (Variant.is_container(variant) and Variant.n_children(variant) >= index) then return Variant.get_child_value(variant, index - 1).value end end -- Implementation of iterators over compound variant (simulating -- standard Lua pairs() and ipairs() methods). local function variant_inext(parent, index) index = index + 1 if index <= #parent then return index, parent[index] end end function Variant:ipairs() return variant_inext, self, 0 end function Variant:pairs() if self:is_of_type(VariantType.DICTIONARY) then -- For dictionaries, provide closure iterator which goes through -- all key-value pairs of the parent. local index = 0 return function() index = index + 1 if index <= #self then local child = self[index] return child[1], child[2] end end end -- For non-dictionaries, pairs() is the same as ipairs(). return self:ipairs() end -- Serialization support. Override Variant:get_data() with safer -- method which fills size to the resulting ref. Variant._attribute.data = {} function Variant._attribute.data:get() local buffer = bytes.new(Variant.get_size(self)) Variant.store(self, buffer) return buffer end -- Map get_data to read-only 'data' property. -- Override for new_from_data. Takes care mainly about tricky -- DestroyNotify handling. local variant_new_from_data = Variant.new_from_data function Variant.new_from_data(vt, data, trusted) if type(vt) == 'string' then vt = VariantType.new(vt) end if trusted == nil then trusted = true end return variant_new_from_data( vt, data, trusted, -- DestroyNotify implemented as closure which holds 'data' value -- as an upvalue. The 'notify' argument is scope-async, which -- means that closure together with its upvalue will be -- destroyed after called. Up to that time 'data' is safely -- held in upvalue for this closure. function() data = nil end) end
33.682927
78
0.662835
99039dc049211bc3b6719532aba82c761c9d2d43
955
lua
Lua
init.lua
NiLSPACE/Login
882d767e8bf24afd40a72ab7b2de1e3ee77cd4cd
[ "Apache-2.0" ]
20
2015-02-14T11:57:23.000Z
2021-09-19T15:54:57.000Z
init.lua
NiLSPACE/Login
882d767e8bf24afd40a72ab7b2de1e3ee77cd4cd
[ "Apache-2.0" ]
4
2015-02-13T21:51:48.000Z
2020-08-23T16:58:23.000Z
init.lua
NiLSPACE/Login
882d767e8bf24afd40a72ab7b2de1e3ee77cd4cd
[ "Apache-2.0" ]
5
2015-02-13T19:50:40.000Z
2020-09-11T11:15:27.000Z
function Initialize(a_Plugin) a_Plugin:SetName("Login") a_Plugin:SetVersion(g_PluginInfo.Version) -- Load the InfoReg shared library: dofile(cPluginManager:GetPluginsPath() .. "/InfoReg.lua") -- Bind all the commands: RegisterPluginInfoCommands(); -- Load and initialize the config. InitConfig() -- Load the password storage according to the config file InitStorage() -- Load the hooks InitHooks() cRoot:Get():ForEachPlayer( function(a_Player) -- Log all the users that are currently online in GetPlayerState(a_Player, true) end ) LOG("Login is initialized") return true end function OnDisable() cRoot:Get():ForEachPlayer( function(a_Player) local PlayerState = GetPlayerState(a_Player) if (not PlayerState:IsLoggedIn()) then PlayerState:TeleportBack() a_Player:GetClientHandle():Kick("The server reloaded while you were not logged in") end end ) g_PassStorage:Disable() end
16.754386
87
0.72356
255c11b568e756b6b37da97e77bef4e63a6da10c
10,694
cs
C#
BachelorDiploma/SilverClient/FourierTransform.cs
KvanTTT/Education
e9dc00bfc25ccf0e25c4e7ec187bccb680f126f9
[ "MIT" ]
1
2018-04-06T19:47:37.000Z
2018-04-06T19:47:37.000Z
BachelorDiploma/SilverClient/FourierTransform.cs
KvanTTT/Education
e9dc00bfc25ccf0e25c4e7ec187bccb680f126f9
[ "MIT" ]
null
null
null
BachelorDiploma/SilverClient/FourierTransform.cs
KvanTTT/Education
e9dc00bfc25ccf0e25c4e7ec187bccb680f126f9
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008 Ernest Laurentin (http://www.ernzo.com/) // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // File: FFT.cs // Version: 1.0 /////////////////////////////////////////////////////////////////////////////// // Based on 1998 original version by: Don Cross <dcross@intersrv.com> /////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; namespace Saluse.MediaKit.Sample { public class FourierTransform { public const int FREQUENCYSLOTCOUNT = 19; private static int[] _meterFrequencies = new int[FREQUENCYSLOTCOUNT] { 30, 55, 80, 120, 155, 195, 250, 375, 500, 750, 1000, 1500, 2000, 3000, 4000, 6000, 8000, 12000, 16000 }; private static int _frequencySlotCount = FREQUENCYSLOTCOUNT; /// <summary> /// Changes the Frequency Bands to analyze. /// Affects the other static methods /// </summary> /// <param name="meterFrequencies"></param> public static void SetMeterFrequencies(int[] meterFrequencies) { _meterFrequencies = meterFrequencies; _frequencySlotCount = meterFrequencies.Length; } public static double[] FFTDb(ref double[] x) { //uint pow2Samples = FFT.NextPowerOfTwo((uint)x.Length); double[] xre = new double[x.Length]; double[] xim = new double[x.Length]; Compute((uint)x.Length, x, null, xre, xim, false); double[] decibel = new double[xre.Length / 2]; for (int i = 0; i < decibel.Length; i++) decibel[i] = 10.0 * Math.Log10((float)(Math.Sqrt((xre[i] * xre[i]) + (xim[i] * xim[i])))); return decibel; } public const Double DDC_PI = 3.14159265358979323846; /// <summary> /// Verifies a number is a power of two /// </summary> /// <param name="x">Number to check</param> /// <returns>true if number is a power two (i.e.:1,2,4,8,16,...)</returns> public static Boolean IsPowerOfTwo(UInt32 x) { return ((x != 0) && (x & (x - 1)) == 0); } /// <summary> /// Get Next power of number. /// </summary> /// <param name="x">Number to check</param> /// <returns>A power of two number</returns> public static UInt32 NextPowerOfTwo(UInt32 x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); return x + 1; } /// <summary> /// Get Number of bits needed for a power of two /// </summary> /// <param name="PowerOfTwo">Power of two number</param> /// <returns>Number of bits</returns> public static UInt32 NumberOfBitsNeeded(UInt32 PowerOfTwo) { if (PowerOfTwo > 0) { for (UInt32 i = 0, mask = 1; ; i++, mask <<= 1) { if ((PowerOfTwo & mask) != 0) return i; } } return 0; // error } /// <summary> /// Reverse bits /// </summary> /// <param name="index">Bits</param> /// <param name="NumBits">Number of bits to reverse</param> /// <returns>Reverse Bits</returns> public static UInt32 ReverseBits(UInt32 index, UInt32 NumBits) { UInt32 i, rev; for (i = rev = 0; i < NumBits; i++) { rev = (rev << 1) | (index & 1); index >>= 1; } return rev; } /// <summary> /// Return index to frequency based on number of samples /// </summary> /// <param name="Index">sample index</param> /// <param name="NumSamples">number of samples</param> /// <returns>Frequency index range</returns> public static Double IndexToFrequency(UInt32 Index, UInt32 NumSamples) { if (Index >= NumSamples) return 0.0; else if (Index <= NumSamples / 2) return (double)Index / (double)NumSamples; return -(double)(NumSamples - Index) / (double)NumSamples; } /// <summary> /// Compute FFT /// </summary> /// <param name="NumSamples">NumSamples Number of samples (must be power two)</param> /// <param name="pRealIn">Real samples</param> /// <param name="pImagIn">Imaginary (optional, may be null)</param> /// <param name="pRealOut">Real coefficient output</param> /// <param name="pImagOut">Imaginary coefficient output</param> /// <param name="bInverseTransform">bInverseTransform when true, compute Inverse FFT</param> public static void Compute(UInt32 NumSamples, Double[] pRealIn, Double[] pImagIn, Double[] pRealOut, Double[] pImagOut, Boolean bInverseTransform) { UInt32 NumBits; /* Number of bits needed to store indices */ UInt32 i, j, k, n; UInt32 BlockSize, BlockEnd; double angle_numerator = 2.0 * DDC_PI; double tr, ti; /* temp real, temp imaginary */ if (pRealIn == null || pRealOut == null || pImagOut == null) { // error throw new ArgumentNullException("Null argument"); } if (!IsPowerOfTwo(NumSamples)) { // error throw new ArgumentException("Number of samples must be power of 2"); } if (pRealIn.Length < NumSamples || (pImagIn != null && pImagIn.Length < NumSamples) || pRealOut.Length < NumSamples || pImagOut.Length < NumSamples) { // error throw new ArgumentException("Invalid Array argument detected"); } if (bInverseTransform) angle_numerator = -angle_numerator; NumBits = NumberOfBitsNeeded(NumSamples); /* ** Do simultaneous data copy and bit-reversal ordering into outputs... */ for (i = 0; i < NumSamples; i++) { j = ReverseBits(i, NumBits); pRealOut[j] = pRealIn[i]; pImagOut[j] = (double)((pImagIn == null) ? 0.0 : pImagIn[i]); } /* ** Do the FFT itself... */ BlockEnd = 1; for (BlockSize = 2; BlockSize <= NumSamples; BlockSize <<= 1) { double delta_angle = angle_numerator / (double)BlockSize; double sm2 = Math.Sin(-2 * delta_angle); double sm1 = Math.Sin(-delta_angle); double cm2 = Math.Cos(-2 * delta_angle); double cm1 = Math.Cos(-delta_angle); double w = 2 * cm1; double ar0, ar1, ar2; double ai0, ai1, ai2; for (i = 0; i < NumSamples; i += BlockSize) { ar2 = cm2; ar1 = cm1; ai2 = sm2; ai1 = sm1; for (j = i, n = 0; n < BlockEnd; j++, n++) { ar0 = w * ar1 - ar2; ar2 = ar1; ar1 = ar0; ai0 = w * ai1 - ai2; ai2 = ai1; ai1 = ai0; k = j + BlockEnd; tr = ar0 * pRealOut[k] - ai0 * pImagOut[k]; ti = ar0 * pImagOut[k] + ai0 * pRealOut[k]; pRealOut[k] = (pRealOut[j] - tr); pImagOut[k] = (pImagOut[j] - ti); pRealOut[j] += (tr); pImagOut[j] += (ti); } } BlockEnd = BlockSize; } /* ** Need to normalize if inverse transform... */ if (bInverseTransform) { double denom = (double)(NumSamples); for (i = 0; i < NumSamples; i++) { pRealOut[i] /= denom; pImagOut[i] /= denom; } } } /// <summary> /// Calculate normal (power spectrum) /// </summary> /// <param name="NumSamples">Number of sample</param> /// <param name="pReal">Real coefficient buffer</param> /// <param name="pImag">Imaginary coefficient buffer</param> /// <param name="pAmpl">Working buffer to hold amplitude Xps(m) = | X(m)^2 | = Xreal(m)^2 + Ximag(m)^2</param> public static void Norm(UInt32 NumSamples, Double[] pReal, Double[] pImag, Double[] pAmpl) { if (pReal == null || pImag == null || pAmpl == null) { // error throw new ArgumentNullException("pReal,pImag,pAmpl"); } if (pReal.Length < NumSamples || pImag.Length < NumSamples || pAmpl.Length < NumSamples) { // error throw new ArgumentException("Invalid Array argument detected"); } // Calculate amplitude values in the buffer provided for (UInt32 i = 0; i < NumSamples; i++) { pAmpl[i] = pReal[i] * pReal[i] + pImag[i] * pImag[i]; } } /// <summary> /// Find Peak frequency in Hz /// </summary> /// <param name="NumSamples">Number of samples</param> /// <param name="pAmpl">Current amplitude</param> /// <param name="samplingRate">Sampling rate in samples/second (Hz)</param> /// <param name="index">Frequency index</param> /// <returns>Peak frequency in Hz</returns> public static Double PeakFrequency(UInt32 NumSamples, Double[] pAmpl, Double samplingRate, ref UInt32 index) { UInt32 N = NumSamples >> 1; // number of positive frequencies. (numSamples/2) if (pAmpl == null) { // error throw new ArgumentNullException("pAmpl"); } if (pAmpl.Length < NumSamples) { // error throw new ArgumentException("Invalid Array argument detected"); } double maxAmpl = -1.0; double peakFreq = -1.0; index = 0; for (UInt32 i = 0; i < N; i++) { if (pAmpl[i] > maxAmpl) { maxAmpl = (double)pAmpl[i]; index = i; peakFreq = (double)(i); } } return samplingRate * peakFreq / (double)(NumSamples); } public static byte[] GetPeaks(double[] leftChannel, double[] rightChannel, int sampleFrequency) { byte[] peaks = new byte[_frequencySlotCount]; byte[] channelPeaks = GetPeaksForChannel(leftChannel, sampleFrequency); ComparePeaks(peaks, channelPeaks); return peaks; } private static void ComparePeaks(byte[] overallPeaks, byte[] channelPeaks) { for (int i = 0; i < _frequencySlotCount; i++) { overallPeaks[i] = Math.Max(overallPeaks[i], channelPeaks[i]); } } private static byte[] GetPeaksForChannel(double[] normalizedArray, int sampleFrequency) { byte[] peaks = new byte[_frequencySlotCount]; // update meter int centerFreq = (sampleFrequency / 2); byte peak; for (int i = 0; i < _frequencySlotCount; ++i) { if (_meterFrequencies[i] > centerFreq) { peak = 0; } else { int index = (int)(_meterFrequencies[i] * normalizedArray.Length / sampleFrequency); peak = (byte)Math.Max(0, (17.0 * Math.Log10(normalizedArray[index]))); } peaks[i] = peak; } return peaks; } } }
28.747312
177
0.609594
b89c6bde070f0fc058b31ff480ed341680ceedd6
483
h
C
LLModularizationDemo/LLModularizationDemo/DataBase/DataBase+LabelModuleLabelNode.h
lilianmao/LLModularization
6d99bd03550d3d10dca8aeee5152a046e93c6795
[ "MIT" ]
9
2017-12-07T12:08:46.000Z
2019-08-08T16:03:48.000Z
LLModularizationDemo/LLModularizationDemo/DataBase/DataBase+LabelModuleLabelNode.h
lilianmao/LLModularization
6d99bd03550d3d10dca8aeee5152a046e93c6795
[ "MIT" ]
null
null
null
LLModularizationDemo/LLModularizationDemo/DataBase/DataBase+LabelModuleLabelNode.h
lilianmao/LLModularization
6d99bd03550d3d10dca8aeee5152a046e93c6795
[ "MIT" ]
2
2018-01-10T11:59:43.000Z
2019-05-04T08:33:44.000Z
// // DataBase+LabelModuleLabelNode.h // LLModularizationDemo // // Created by 李林 on 1/10/18. // Copyright © 2018 lee. All rights reserved. // #import "DataBase.h" #import "LabelModuleLabelNode.h" @interface DataBase (LabelModuleLabelNode) - (NSArray<LabelModuleLabelNode *> *)LabelModuleLabelNode_getAllElementsWithSQL:(NSString *)sql; - (BOOL)LabelModuleLabelNode_setElementwithSQL:(NSString *)sql labelStr:(NSString *)labelStr; @end
24.15
96
0.701863
b5ae73d5770fb5f0101bb9ef0758860566b19373
607
rb
Ruby
lib/bing-ads-api/data/location_target.rb
liskape/bing-ads-api
28e5d52a8f1efb7b7b1269f1b829f3c6f3748304
[ "MIT" ]
null
null
null
lib/bing-ads-api/data/location_target.rb
liskape/bing-ads-api
28e5d52a8f1efb7b7b1269f1b829f3c6f3748304
[ "MIT" ]
5
2020-02-25T10:46:28.000Z
2022-02-26T03:51:47.000Z
lib/bing-ads-api/data/location_target.rb
liskape/bing-ads-api
28e5d52a8f1efb7b7b1269f1b829f3c6f3748304
[ "MIT" ]
null
null
null
# -*- encoding : utf-8 -*- module BingAdsApi ## # Public : Defines the base object of an location target. # # Reference: https://msdn.microsoft.com/library/4349d964-0553-4d68-a53e-5011ff51a8f9 # # Author:: seodma@gmailc.com # class LocationTarget < BingAdsApi::DataObject attr_accessor :id, :city_target, :radius_target, :postal_code_target def to_hash(keys = :camelcase) hash = super(keys) return hash end private # Internal: Retrieve the ordered array of keys corresponding to this data # object. # # Author: alex.cavalli@offers.com end end
17.342857
85
0.678748
472f53217038ac3bacc5b28ffc87357a032c00e9
81
sql
SQL
src/test/resources/sql/select/713f2d1b.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
66
2018-06-15T11:34:03.000Z
2022-03-16T09:24:49.000Z
src/test/resources/sql/select/713f2d1b.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
13
2019-03-19T11:56:28.000Z
2020-08-05T04:20:50.000Z
src/test/resources/sql/select/713f2d1b.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
28
2019-01-05T19:59:02.000Z
2022-03-24T11:55:50.000Z
-- file:date.sql ln:249 expect:true SELECT EXTRACT(MILLENNIUM FROM CURRENT_DATE)
27
44
0.802469
4473df88284fe39be09ae66fe0899d684a0a28fc
352
py
Python
algorithms/sherlock-and-squares.py
gajubadge11/HackerRank-1
7b136ccaa1ed47ae737467ace6b494c720ccb942
[ "MIT" ]
340
2018-06-17T19:45:56.000Z
2022-03-22T02:26:15.000Z
algorithms/sherlock-and-squares.py
gajubadge11/HackerRank-1
7b136ccaa1ed47ae737467ace6b494c720ccb942
[ "MIT" ]
3
2021-02-02T17:17:29.000Z
2021-05-18T10:06:04.000Z
algorithms/sherlock-and-squares.py
gajubadge11/HackerRank-1
7b136ccaa1ed47ae737467ace6b494c720ccb942
[ "MIT" ]
229
2019-04-20T08:28:49.000Z
2022-03-31T04:23:52.000Z
#!/bin/python3 import sys from math import ceil, floor def squares(a, b): res = 0 res = floor(b**0.5)+1 - ceil(a**0.5) return res if __name__ == "__main__": q = int(input().strip()) for a0 in range(q): a, b = input().strip().split(' ') a, b = [int(a), int(b)] result = squares(a, b) print(result)
19.555556
41
0.522727
a3a7ae0e38f933bf01bf1a8a990b3a35e8265e92
5,945
java
Java
ios-moe/src/de/tomgrill/gdxfirebase/iosmoe/fcm/IOSMOEFirebaseFCM.java
TomGrill/gdx-firebase
71b69f5fee13fcba0a205ca22240ad8eebac2c92
[ "Apache-2.0" ]
34
2016-07-19T10:59:04.000Z
2022-01-13T08:35:27.000Z
ios-moe/src/de/tomgrill/gdxfirebase/iosmoe/fcm/IOSMOEFirebaseFCM.java
TomGrill/gdx-firebase
71b69f5fee13fcba0a205ca22240ad8eebac2c92
[ "Apache-2.0" ]
3
2017-03-14T11:57:41.000Z
2022-03-25T07:03:24.000Z
ios-moe/src/de/tomgrill/gdxfirebase/iosmoe/fcm/IOSMOEFirebaseFCM.java
TomGrill/gdx-firebase
71b69f5fee13fcba0a205ca22240ad8eebac2c92
[ "Apache-2.0" ]
9
2016-08-31T16:34:44.000Z
2021-06-11T10:53:33.000Z
package de.tomgrill.gdxfirebase.iosmoe.fcm; import apple.foundation.NSError; import apple.foundation.NSProcessInfo; import apple.uikit.UIApplication; import apple.uikit.UIUserNotificationSettings; import apple.uikit.enums.UIUserNotificationType; import apple.usernotifications.UNNotification; import apple.usernotifications.UNNotificationResponse; import apple.usernotifications.UNUserNotificationCenter; import apple.usernotifications.enums.UNAuthorizationOptions; import apple.usernotifications.protocol.UNUserNotificationCenterDelegate; import com.badlogic.gdx.utils.Array; import com.google.firebasecore.FIRApp; import com.google.firebasemessaging.FIRMessaging; import com.google.firebasemessaging.FIRMessagingRemoteMessage; import com.google.firebasemessaging.protocol.FIRMessagingDelegate; import de.tomgrill.gdxfirebase.core.fcm.FirebaseFCM; import de.tomgrill.gdxfirebase.core.fcm.RemoteMessage; import de.tomgrill.gdxfirebase.core.fcm.RemoteMessageListener; import de.tomgrill.gdxfirebase.core.fcm.TokenRefreshListener; import de.tomgrill.gdxfirebase.iosmoe.ConfigureOverwatch; public class IOSMOEFirebaseFCM implements FirebaseFCM, UNUserNotificationCenterDelegate, FIRMessagingDelegate { private Array<TokenRefreshListener> tokenRefreshListeners = new Array<>(); private Array<RemoteMessageListener> remoteMessageListeners = new Array<>(); private String currentToken; public IOSMOEFirebaseFCM() { if (!ConfigureOverwatch.isConfigured) { FIRApp.configure(); ConfigureOverwatch.isConfigured = true; } FIRMessaging.messaging().setDelegate(this); if (NSProcessInfo.processInfo().operatingSystemVersion().majorVersion() < 10) { // below 10 long userNotificationTypeBits = UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge; UIUserNotificationSettings uiUserNotificationSettings = UIUserNotificationSettings.settingsForTypesCategories(userNotificationTypeBits, null); UIApplication.sharedApplication().registerUserNotificationSettings(uiUserNotificationSettings); } else { // with ios 10+ UNUserNotificationCenter.currentNotificationCenter().setDelegate(this); long optionBits = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Badge; UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptionsCompletionHandler(optionBits, new UNUserNotificationCenter.Block_requestAuthorizationWithOptionsCompletionHandler() { @Override public void call_requestAuthorizationWithOptionsCompletionHandler(boolean allowed, NSError arg1) { // System.out.println("AJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA COMPLETE AUTH WITH: " + allowed); // System.out.println("AJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA COMPLETE AUTH ERROR: " + arg1); } }); } UIApplication.sharedApplication().registerForRemoteNotifications(); currentToken = FIRMessaging.messaging().FCMToken(); } @Override public void addTokenRefreshListener(TokenRefreshListener tokenRefreshListener) { if (currentToken != null) { tokenRefreshListener.onTokenRefresh(currentToken); } tokenRefreshListeners.add(tokenRefreshListener); } @Override public void removeTokenRefreshListener(TokenRefreshListener tokenRefreshListener) { tokenRefreshListeners.removeValue(tokenRefreshListener, true); } @Override public void addRemoteMessageListener(RemoteMessageListener remoteMessageListener) { remoteMessageListeners.add(remoteMessageListener); } @Override public void removeRemoteMessageListener(RemoteMessageListener remoteMessageListener) { remoteMessageListeners.removeValue(remoteMessageListener, true); } @Override public void subscribeToTopic(String topic) { FIRMessaging.messaging().subscribeToTopic(topic); } @Override public void unsubscribeFromTopic(String topic) { FIRMessaging.messaging().unsubscribeFromTopic(topic); } @Override public void frontUpClean() { remoteMessageListeners.clear(); tokenRefreshListeners.clear(); } @Override public void userNotificationCenterDidReceiveNotificationResponseWithCompletionHandler(UNUserNotificationCenter center, UNNotificationResponse response, Block_userNotificationCenterDidReceiveNotificationResponseWithCompletionHandler completionHandler) { // System.out.println("AAHAHAAAAAA RECEIVE MSG"); } @Override public void userNotificationCenterWillPresentNotificationWithCompletionHandler(UNUserNotificationCenter center, UNNotification notification, Block_userNotificationCenterWillPresentNotificationWithCompletionHandler completionHandler) { // System.out.println("AAHAHAAAAAA WILL PRESEN"); } @Override public void messagingDidReceiveMessage(FIRMessaging messaging, FIRMessagingRemoteMessage FIRremoteMessage) { // System.out.println("DIDI RECEIVE MESSAGEEE" + FIRremoteMessage); RemoteMessage remoteMessage = new RemoteMessage(); for (Object key : FIRremoteMessage.appData().allKeys()) { Object object = FIRremoteMessage.appData().get(key); remoteMessage.getData().put(key.toString(), object); } for (int i = 0; i < remoteMessageListeners.size; i++) { remoteMessageListeners.get(i).onRemoteMessage(remoteMessage); } } @Override public void messagingDidReceiveRegistrationToken(FIRMessaging messaging, String fcmToken) { currentToken = fcmToken; for (int i = 0; i < tokenRefreshListeners.size; i++) { tokenRefreshListeners.get(i).onTokenRefresh(currentToken); } } }
43.07971
256
0.75492
4c6c692918a37ce8bac1b59a34aa3a2e06cf34a9
19,712
swift
Swift
Sources/CloudKitCodable/Encoder.swift
colemancda/CloudKitCodable
598e04c5c6f1162d51fdc45d11c85574d39ee85c
[ "MIT" ]
6
2019-09-10T19:56:11.000Z
2020-05-16T12:22:45.000Z
Sources/CloudKitCodable/Encoder.swift
colemancda/CloudKitCodable
598e04c5c6f1162d51fdc45d11c85574d39ee85c
[ "MIT" ]
null
null
null
Sources/CloudKitCodable/Encoder.swift
colemancda/CloudKitCodable
598e04c5c6f1162d51fdc45d11c85574d39ee85c
[ "MIT" ]
null
null
null
// // Encoder.swift // // // Created by Alsey Coleman Miller on 9/10/19. // import Foundation import CloudKit /// CloudKit Record Recorder public final class CloudKitEncoder { // MARK: - Properties /// CloudKit encoding context. public let context: CloudKitContext /// Any contextual information set by the user for encoding. public var userInfo = [CodingUserInfoKey : Any]() /// Logger handler public var log: ((String) -> ())? public var options = Options() // MARK: - Initialization public init(context: CloudKitContext) { self.context = context } // MARK: - Methods public func encode <T: CloudKitEncodable> (_ value: T) throws -> CKModifyRecordsOperation { log?("Will encode \(String(reflecting: T.self))") //let options = Encoder.Options() let operation = CKModifyRecordsOperation() let encoder = CKRecordEncoder( value, operation: operation, userInfo: userInfo, log: log, context: context, options: options ) try value.encode(to: encoder) return operation } } public extension CloudKitEncoder { /// CloudKit Encoder Options typealias Options = CloudKitCodingOptions } // MARK: - Supporting Types internal final class CKRecordEncoder: Swift.Encoder { // MARK: - Properties /// CloudKit encoding context. public let context: CloudKitContext /// The path of coding keys taken to get to this point in encoding. fileprivate(set) var codingPath: [CodingKey] /// Any contextual information set by the user for encoding. let userInfo: [CodingUserInfoKey : Any] /// Logger let log: ((String) -> ())? let options: CloudKitEncoder.Options /// Encodable value let value: CloudKitEncodable /// CloudKit modify records operation. let operation: CKModifyRecordsOperation /// Container stack private(set) var stack = Stack() // MARK: - Initialization init(_ value: CloudKitEncodable, operation: CKModifyRecordsOperation, codingPath: [CodingKey] = [], userInfo: [CodingUserInfoKey : Any], log: ((String) -> ())?, context: CloudKitContext, options: CloudKitEncoder.Options) { self.value = value self.operation = operation self.codingPath = codingPath self.userInfo = userInfo self.log = log self.context = context self.options = options } // MARK: - Encoder func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey { log?("Requested container keyed by \(type.sanitizedName) for path \"\(codingPath.path)\"") /// cannot encode guard stack.containers.isEmpty else { let error = EncodingError.invalidValue(CloudKitEncodable.self, EncodingError.Context(codingPath: codingPath, debugDescription: "Nested value should conform to \(CloudKitEncodable.self)")) let keyedContainer = CKRecordInvalidKeyedEncodingContainer<Key>(codingPath: codingPath, error: error) return KeyedEncodingContainer(keyedContainer) } do { // find or create record let recordID = value.cloudIdentifier.cloudRecordID let record = try context.fetch(record: recordID) ?? CKRecord( recordType: Swift.type(of: value.cloudIdentifier).cloudRecordType, recordID: recordID ) // set parent record if #available(macOS 10.12, iOS 10, tvOS 10, watchOS 3, *) { record.setParent(value.parentRecord?.cloudRecordID) } // add to CloudKit operation operation.save(record) // push container self.stack.push(.record(record)) let keyedContainer = CKRecordKeyedEncodingContainer<Key>(referencing: self, wrapping: record) return KeyedEncodingContainer(keyedContainer) } catch { let keyedContainer = CKRecordInvalidKeyedEncodingContainer<Key>(codingPath: codingPath, error: error) return KeyedEncodingContainer(keyedContainer) } } func unkeyedContainer() -> UnkeyedEncodingContainer { log?("Requested unkeyed container for path \"\(codingPath.path)\"") let stackContainer = ListContainer() self.stack.push(.list(stackContainer)) return CKRecordUnkeyedEncodingContainer(referencing: self, wrapping: stackContainer) } func singleValueContainer() -> SingleValueEncodingContainer { log?("Requested single value container for path \"\(codingPath.path)\"") let stackContainer = ValueContainer() self.stack.push(.value(stackContainer)) return CKRecordSingleValueEncodingContainer(referencing: self, wrapping: stackContainer) } } // MARK: - Boxing Values internal extension CKRecordEncoder { func boxEncodable <T: Encodable> (_ value: T) throws -> CKRecordValueProtocol? { if let url = value as? URL { // attempt to convert to CKAsset return options.assets(url) ?? url.absoluteString } else if let uuid = value as? UUID { return uuid.uuidString } else if let locationValue = value as? CloudKitLocation { // encode CLLocation return locationValue.location } else if let identifier = value as? CloudKitIdentifier { // store nested reference return boxIdentifier(identifier) } else if let encodable = value as? CloudKitEncodable { // store nested record let encoder = CKRecordEncoder( encodable, operation: operation, codingPath: codingPath, userInfo: userInfo, log: log, context: context, options: options ) try encodable.encode(to: encoder) guard case let .record(record) = encoder.stack.root else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: "\(String(reflecting: Swift.type(of: encodable))) should encode to record")) } return boxRecord(record) } else if let recordValue = value as? CKRecordValueProtocol { // return CloudKit native attribute value return recordValue } else { // encode using Encodable, should push new container. try value.encode(to: self) let container = stack.pop() switch container { case let .record(record): return boxRecord(record) case let .value(valueContainer): return valueContainer.value case let .list(listContainer): return listContainer.value } } } private func boxRecord(_ record: CKRecord) -> CKRecord.Reference { let reference = CKRecord.Reference(record: record, action: .none) return reference } private func boxIdentifier(_ identifier: CloudKitIdentifier) -> CKRecord.Reference { let reference = CKRecord.Reference(recordID: identifier.cloudRecordID, action: .none) return reference } } // MARK: - Stack internal extension CKRecordEncoder { struct Stack { private(set) var containers = [Container]() fileprivate init() { } var top: Container { guard let container = containers.last else { fatalError("Empty container stack.") } return container } var root: Container { guard let container = containers.first else { fatalError("Empty container stack.") } return container } mutating func push(_ container: Container) { containers.append(container) } @discardableResult mutating func pop() -> Container { guard let container = containers.popLast() else { fatalError("Empty container stack.") } return container } } } internal extension CKRecordEncoder { enum Container { case record(CKRecord) case value(ValueContainer) case list(ListContainer) } final class ValueContainer { var value: CKRecordValueProtocol? } final class ListContainer { // should be homegenous array var value = NSMutableArray() } } // MARK: - KeyedEncodingContainerProtocol internal struct CKRecordInvalidKeyedEncodingContainer <K : CodingKey> : KeyedEncodingContainerProtocol { let codingPath: [CodingKey] let error: Swift.Error typealias Key = K func encodeNil(forKey key: K) throws { throw error } func encode(_ value: Bool, forKey key: K) throws { throw error } func encode(_ value: Int, forKey key: K) throws { throw error } func encode(_ value: Int8, forKey key: K) throws { throw error } func encode(_ value: Int16, forKey key: K) throws { throw error } func encode(_ value: Int32, forKey key: K) throws { throw error } func encode(_ value: Int64, forKey key: K) throws { throw error } func encode(_ value: UInt, forKey key: K) throws { throw error } func encode(_ value: UInt8, forKey key: K) throws { throw error } func encode(_ value: UInt16, forKey key: K) throws { throw error } func encode(_ value: UInt32, forKey key: K) throws { throw error } func encode(_ value: UInt64, forKey key: K) throws { throw error } func encode(_ value: Float, forKey key: K) throws { throw error } func encode(_ value: Double, forKey key: K) throws { throw error } func encode(_ value: String, forKey key: K) throws { throw error } func encode <T: Encodable> (_ value: T, forKey key: K) throws { throw error } func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey { fatalError() } func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer { fatalError() } func superEncoder() -> Encoder { fatalError() } func superEncoder(forKey key: K) -> Encoder { fatalError() } } internal final class CKRecordKeyedEncodingContainer <K : CodingKey> : KeyedEncodingContainerProtocol { typealias Key = K // MARK: - Properties /// A reference to the encoder we're writing to. let encoder: CKRecordEncoder /// The path of coding keys taken to get to this point in encoding. let codingPath: [CodingKey] /// A reference to the container we're writing to. let container: CKRecord // MARK: - Initialization init(referencing encoder: CKRecordEncoder, wrapping container: CKRecord) { self.encoder = encoder self.codingPath = encoder.codingPath self.container = container } // MARK: - Methods func encodeNil(forKey key: K) throws { setValue(nil, forKey: key) } func encode(_ value: Bool, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: Int, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: Int8, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: Int16, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: Int32, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: Int64, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: UInt, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: UInt8, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: UInt16, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: UInt32, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: UInt64, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: Float, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: Double, forKey key: K) throws { setValue(value, forKey: key) } func encode(_ value: String, forKey key: K) throws { setValue(value, forKey: key) } func encode <T: Encodable> (_ value: T, forKey key: K) throws { // don't encode identifier guard encoder.options.identifierKey(key) == false else { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } let recordID = encoder.value.cloudIdentifier.cloudRecordID encoder.log?("Will encode record ID \"\(recordID.recordName)\" for key \"\(key.stringValue)\" at path \"\(encoder.codingPath.path)\"") // do nothing return } try setValue(try encoder.boxEncodable(value), forKey: key) } func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey { fatalError() } func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer { fatalError() } func superEncoder() -> Encoder { fatalError() } func superEncoder(forKey key: K) -> Encoder { fatalError() } // MARK: - Private Methods private func setValue(_ value: @autoclosure () throws -> (CKRecordValueProtocol?), forKey key: K) rethrows { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } encoder.log?("Will encode value for key \"\(key.stringValue)\" at path \"\(encoder.codingPath.path)\"") let recordValue = try value() if #available(macOS 10.11, iOS 9.0, watchOS 3.0, *) { self.container[key.stringValue] = recordValue } else { guard let objcValue = (recordValue as Any?) as? __CKRecordObjCValue? else { fatalError("Cannot convert \(String(reflecting: type(of: recordValue))) to ObjC value") } self.container.setObject(objcValue, forKey: key.stringValue) } } } // MARK: - SingleValueEncodingContainer internal final class CKRecordSingleValueEncodingContainer: SingleValueEncodingContainer { // MARK: - Properties /// A reference to the encoder we're writing to. let encoder: CKRecordEncoder /// The path of coding keys taken to get to this point in encoding. let codingPath: [CodingKey] /// A reference to the container we're writing to. let container: CKRecordEncoder.ValueContainer /// Whether the data has been written private(set) var didWrite = false // MARK: - Initialization init(referencing encoder: CKRecordEncoder, wrapping container: CKRecordEncoder.ValueContainer) { self.encoder = encoder self.codingPath = encoder.codingPath self.container = container } // MARK: - Methods func encodeNil() throws { write(nil) } func encode(_ value: Bool) throws { write(value) } func encode(_ value: String) throws { write(value) } func encode(_ value: Double) throws { write(value) } func encode(_ value: Float) throws { write(value) } func encode(_ value: Int) throws { write(value) } func encode(_ value: Int8) throws { write(value) } func encode(_ value: Int16) throws { write(value) } func encode(_ value: Int32) throws { write(value) } func encode(_ value: Int64) throws { write(value) } func encode(_ value: UInt) throws { write(value) } func encode(_ value: UInt8) throws { write(value) } func encode(_ value: UInt16) throws { write(value) } func encode(_ value: UInt32) throws { write(value) } func encode(_ value: UInt64) throws { write(value) } func encode <T: Encodable> (_ value: T) throws { write(try encoder.boxEncodable(value)) } // MARK: - Private Methods private func write(_ value: CKRecordValueProtocol?) { precondition(didWrite == false, "Data already written") self.container.value = value self.didWrite = true } } // MARK: - UnkeyedEncodingContainer internal final class CKRecordUnkeyedEncodingContainer: UnkeyedEncodingContainer { // MARK: - Properties /// A reference to the encoder we're writing to. let encoder: CKRecordEncoder /// The path of coding keys taken to get to this point in encoding. let codingPath: [CodingKey] /// A reference to the container we're writing to. let container: CKRecordEncoder.ListContainer // MARK: - Initialization init(referencing encoder: CKRecordEncoder, wrapping container: CKRecordEncoder.ListContainer) { self.encoder = encoder self.codingPath = encoder.codingPath self.container = container } // MARK: - Methods /// The number of elements encoded into the container. var count: Int { return container.value.count } func encodeNil() throws { append(nil) } func encode(_ value: Bool) throws { append(value) } func encode(_ value: String) throws { append(value) } func encode(_ value: Double) throws { append(value) } func encode(_ value: Float) throws { append(value) } func encode(_ value: Int) throws { append(value) } func encode(_ value: Int8) throws { append(value) } func encode(_ value: Int16) throws { append(value) } func encode(_ value: Int32) throws { append(value) } func encode(_ value: Int64) throws { append(value) } func encode(_ value: UInt) throws { append(value) } func encode(_ value: UInt8) throws { append(value) } func encode(_ value: UInt16) throws { append(value) } func encode(_ value: UInt32) throws { append(value) } func encode(_ value: UInt64) throws { append(value) } func encode <T: Encodable> (_ value: T) throws { append(try encoder.boxEncodable(value)) } func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey { fatalError() } func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { fatalError() } func superEncoder() -> Encoder { fatalError() } // MARK: - Private Methods private func append(_ value: CKRecordValueProtocol?) { if let value = value { self.container.value.add(value) } } } // MARK: - Extensions internal extension CKModifyRecordsOperation { func save(_ record: CKRecord) { var recordsToSave = self.recordsToSave ?? [] recordsToSave.removeAll(where: { $0 === record }) recordsToSave.append(record) self.recordsToSave = recordsToSave } }
31.793548
199
0.613129
e1f85d7b12f69e05b5002a48c513f48503288fc4
8,879
asm
Assembly
Transynther/x86/_processed/AVXALIGN/_st_4k_/i9-9900K_12_0xa0.log_21829_343.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/AVXALIGN/_st_4k_/i9-9900K_12_0xa0.log_21829_343.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/AVXALIGN/_st_4k_/i9-9900K_12_0xa0.log_21829_343.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r15 push %r8 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_WT_ht+0x1d7ce, %rbx nop nop nop nop cmp %r8, %r8 movb $0x61, (%rbx) nop nop nop nop xor $22291, %r15 lea addresses_A_ht+0xf98e, %rsi lea addresses_normal_ht+0x13ecd, %rdi nop nop nop nop and %rbx, %rbx mov $16, %rcx rep movsb sub $36401, %rcx lea addresses_D_ht+0x15404, %rcx xor %r11, %r11 mov $0x6162636465666768, %r8 movq %r8, (%rcx) nop xor %r8, %r8 lea addresses_A_ht+0x1344e, %r15 nop nop nop nop nop and %r8, %r8 mov (%r15), %edi nop nop nop nop nop sub $11022, %rsi lea addresses_WT_ht+0x9fce, %rcx clflush (%rcx) nop nop nop nop nop inc %rdi mov $0x6162636465666768, %r8 movq %r8, %xmm5 movups %xmm5, (%rcx) xor %r11, %r11 lea addresses_normal_ht+0x177ce, %rdi clflush (%rdi) and %rcx, %rcx movb $0x61, (%rdi) nop xor %r11, %r11 lea addresses_A_ht+0x192e, %rsi lea addresses_WC_ht+0x61ce, %rdi nop nop nop nop and $33176, %r8 mov $44, %rcx rep movsq add %r8, %r8 lea addresses_WC_ht+0xa8ae, %r15 nop nop nop add $55223, %r11 mov $0x6162636465666768, %rdi movq %rdi, %xmm5 movups %xmm5, (%r15) nop nop nop nop nop sub $6452, %rcx lea addresses_WT_ht+0xeece, %rdi nop nop sub %rsi, %rsi mov (%rdi), %r8d nop sub $11904, %rcx lea addresses_D_ht+0xb74e, %rcx nop nop sub $46711, %rdi mov $0x6162636465666768, %r11 movq %r11, (%rcx) nop nop nop sub %rdi, %rdi lea addresses_WT_ht+0xfce, %rcx nop nop and %r8, %r8 movb $0x61, (%rcx) cmp $59574, %rcx lea addresses_normal_ht+0x1ddee, %rsi lea addresses_WC_ht+0x29ce, %rdi sub $34631, %r9 mov $106, %rcx rep movsb nop nop cmp %r9, %r9 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r8 pop %r15 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r9 push %rax push %rcx push %rdx push %rsi // Store lea addresses_RW+0xd21b, %rdx nop nop sub $37960, %r14 movl $0x51525354, (%rdx) dec %r10 // Store lea addresses_WC+0x1d04e, %r14 nop nop add $14325, %rcx movb $0x51, (%r14) nop nop nop nop xor $16478, %rcx // Store lea addresses_PSE+0x1b1ce, %rdx nop dec %rsi mov $0x5152535455565758, %rax movq %rax, (%rdx) nop sub %rax, %rax // Store lea addresses_UC+0x1b9ce, %rsi add $28699, %rdx movw $0x5152, (%rsi) nop nop nop nop dec %r14 // Store mov $0x6c8be90000000e80, %r10 nop and $37847, %rcx movw $0x5152, (%r10) nop dec %r14 // Store mov $0x806, %r9 clflush (%r9) cmp %rdx, %rdx mov $0x5152535455565758, %rax movq %rax, (%r9) dec %rsi // Store lea addresses_A+0xb176, %rcx nop nop nop nop add $62687, %r9 mov $0x5152535455565758, %r14 movq %r14, %xmm3 movups %xmm3, (%rcx) nop and $22482, %rsi // Store lea addresses_PSE+0x19ece, %rsi nop nop nop nop nop inc %r9 mov $0x5152535455565758, %rdx movq %rdx, %xmm2 movups %xmm2, (%rsi) nop nop cmp %r9, %r9 // Faulty Load lea addresses_WC+0x19ce, %rax nop add $32225, %rsi mov (%rax), %r10d lea oracles, %rax and $0xff, %r10 shlq $12, %r10 mov (%rax,%r10,1), %r10 pop %rsi pop %rdx pop %rcx pop %rax pop %r9 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_RW', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 7, 'type': 'addresses_WC', 'AVXalign': False, 'size': 1}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_UC', 'AVXalign': False, 'size': 2}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_NC', 'AVXalign': False, 'size': 2}} {'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 3, 'type': 'addresses_P', 'AVXalign': False, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_A', 'AVXalign': False, 'size': 16}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 16}} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': True, 'size': 4}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}} {'src': {'same': False, 'congruent': 1, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_normal_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 8}} {'src': {'NT': False, 'same': True, 'congruent': 7, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 16}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1}} {'src': {'same': False, 'congruent': 5, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16}} {'src': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 7, 'type': 'addresses_D_ht', 'AVXalign': True, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}} {'src': {'same': False, 'congruent': 5, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_WC_ht'}} {'52': 21829} 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 */
32.054152
2,999
0.650411
a82cd3f89c8417fd7d4ee50153bc7a2d6c89b61c
14,632
lua
Lua
turbineControl_v2/src/program/reactorControl.lua
LennartKobosil/Reactor-and-Turbine-control-program
aba24807437fb284cef5930c1166c414bfb7f34c
[ "MIT" ]
17
2016-10-29T19:52:58.000Z
2021-02-01T16:43:59.000Z
turbineControl_v2/src/program/reactorControl.lua
LennartKobosil/Reactor-and-Turbine-control-program
aba24807437fb284cef5930c1166c414bfb7f34c
[ "MIT" ]
40
2016-08-28T10:06:52.000Z
2021-01-30T15:15:34.000Z
turbineControl_v2/src/program/reactorControl.lua
LennartKobosil/Reactor-and-Turbine-control-program
aba24807437fb284cef5930c1166c414bfb7f34c
[ "MIT" ]
25
2017-02-07T20:52:22.000Z
2022-01-25T13:23:35.000Z
-- Reactor- und Turbine control by Thor_s_Crafter -- -- Version 2.6 -- -- Reactor control -- --Loads the touchpoint and input APIs shell.run("cp /reactor-turbine-program/config/touchpoint.lua /touchpoint") os.loadAPI("touchpoint") shell.run("rm touchpoint") shell.run("cp /reactor-turbine-program/config/input.lua /input") os.loadAPI("input") shell.run("rm input") --Some variables local page = touchpoint.new(touchpointLocation) local rodLevel local enPer local fuel local fuelPer local rfGen local fuelCons local isOn local enPerR local rOn local rOff local internalBuffer --Create the buttons function createButtons() --In Deutsch if lang == "de" then page:add("Hauptmenue", function() run("/reactor-turbine-program/start/menu.lua") end, 2, 22, 17, 22) --In Englisch elseif lang == "en" then page:add("Main Menu", function() run("/reactor-turbine-program/start/menu.lua") end, 2, 22, 17, 22) end --Control Rods Buttons page:add("-1", function() setControlRods("-", 1) end, 45, 5, 48, 5) page:add("-10", function() setControlRods("-", 10) end, 39, 5, 43, 5) page:add("-100", function() setControlRods("-", 100) end, 32, 5, 37, 5) page:add("+1", function() setControlRods("+", 1) end, 45, 7, 48, 7) page:add("+10", function() setControlRods("+", 10) end, 39, 7, 43, 7) page:add("+100", function() setControlRods("+", 100) end, 32, 7, 37, 7) page:draw() end --Create additional manual buttons function createButtonsMan() createButtons() --Reactor Toggle Button if lang == "de" then rOn = { " Ein ", label = "reactorOn" } rOff = { " Aus ", label = "reactorOn" } elseif lang == "en" then rOn = { " On ", label = "reactorOn" } rOff = { " Off ", label = "reactorOn" } end page:add("reactorOn", toggleReactor, 11, 10, 15, 10) if r.getActive() then page:rename("reactorOn", rOn, true) page:toggleButton("reactorOn") else page:rename("reactorOn", rOff, true) end --Print buttons page:draw() end --Checks, if all peripherals were setup correctly function checkPeripherals() mon.setBackgroundColor(colors.black) mon.clear() mon.setCursorPos(1, 1) mon.setTextColor(colors.red) term.clear() term.setCursorPos(1, 1) term.setTextColor(colors.red) if r == "" then if lang == "de" then mon.write("Reaktor nicht gefunden! Bitte pruefen und den Computer neu starten (Strg+R gedrueckt halten)") error("Reaktor nicht gefunden! Bitte pruefen und den Computer neu starten (Strg+R gedrueckt halten)") elseif lang == "en" then mon.write("Reactor not found! Please check and reboot the computer (Press and hold Ctrl+R)") error("Reactor not found! Please check and reboot the computer (Press and hold Ctrl+R)") end end if v == "" then v = r internalBuffer = true else internalBuffer = false end end --Toggles the reactor on/off function toggleReactor() r.setActive(not r.getActive()) page:toggleButton("reactorOn") if r.getActive() then page:rename("reactorOn", rOn, true) else page:rename("reactorOn", rOff, true) end end --Adjusts the control rods function setControlRods(operation, value) local targetValue = r.getControlRodLevel(0) if operation == "-" then targetValue = targetValue - value if targetValue < 1 then targetValue = 0 end elseif operation == "+" then targetValue = targetValue + value if targetValue > 98 then targetValue = 99 end end r.setAllControlRodLevels(targetValue) end --Returns the current energy level (energy storage) function getEnergy() local en = v.getEnergyStored() local enMax if v == r then enMax = 10000000 else enMax = v.getMaxEnergyStored() end return math.floor(en / enMax * 100) end --Returns the current energy level (reactor) function getEnergyR() local en = r.getEnergyStored() local enMax = 10000000 return math.floor(en / enMax * 100) end --Reads all the reactors data function getReactorData() rodLevel = r.getControlRodLevel(0) enPer = getEnergy() enPerR = getEnergyR() fuel = r.getFuelAmount() local fuelMax = r.getFuelAmountMax() fuelPer = math.floor(fuel / fuelMax * 100) rfGen = r.getEnergyProducedLastTick() fuelCons = r.getFuelConsumedLastTick() isOn = r.getActive() end --Checks for button clicks function getClick() while true do --Refresh Data getReactorData() --refresh screen if overallMode == "auto" then displayDataAuto() elseif overallMode == "manual" then displayDataMan() end --timer local timer1 = os.startTimer(1) while true do --gets the event local event, p1 = page:handleEvents(os.pullEvent()) print(event .. ", " .. p1) --execute a buttons function if clicked if event == "button_click" then page:flash(p1) page.buttonList[p1].func() break elseif event == "timer" and p1 == timer1 then break end end end end --Displays the data on the screen (auto mode) function displayDataAuto() if enPer <= reactorOnAt then r.setActive(true) elseif enPer > reactorOffAt then r.setActive(false) end --Print all buttons page:draw() mon.setBackgroundColor(tonumber(backgroundColor)) mon.setTextColor(tonumber(textColor)) --Print the energy bar mon.setCursorPos(2, 2) if lang == "de" then mon.write("Energie: " .. enPer .. "% ") elseif lang == "en" then mon.write("Energy: " .. enPer .. "% ") end mon.setCursorPos(2, 3) local part1 = enPer / 5 mon.setCursorPos(2, 3) mon.setBackgroundColor(colors.lightGray) mon.write(" ") mon.setBackgroundColor(colors.green) mon.setCursorPos(2, 3) for i = 1, part1 do mon.write(" ") end mon.setTextColor(textColor) mon.setBackgroundColor(tonumber(backgroundColor)) --Print the reactor energy bar mon.setCursorPos(2, 5) if lang == "de" then mon.write("Energie (Reaktor): " .. enPerR .. "% ") elseif lang == "en" then mon.write("Energy (Reactor): " .. enPerR .. "% ") end mon.setCursorPos(2, 6) local part2 = enPerR / 5 mon.setCursorPos(2, 6) mon.setBackgroundColor(colors.lightGray) mon.write(" ") mon.setBackgroundColor(colors.green) mon.setCursorPos(2, 6) for i = 1, part2 do mon.write(" ") end mon.setTextColor(textColor) mon.setBackgroundColor(tonumber(backgroundColor)) --Print the RodLevel bar mon.setCursorPos(30, 2) mon.write("RodLevel: " .. rodLevel .. " ") mon.setCursorPos(30, 3) local part3 = rodLevel / 5 mon.setCursorPos(30, 3) mon.setBackgroundColor(colors.lightGray) mon.write(" ") mon.setBackgroundColor(colors.green) mon.setCursorPos(30, 3) for i = 1, part3 do mon.write(" ") end mon.setTextColor(textColor) mon.setBackgroundColor(tonumber(backgroundColor)) mon.setCursorPos(2, 8) if lang == "de" then mon.write("RF-Produktion: " .. input.formatNumber(math.floor(rfGen)) .. " RF/t ") elseif lang == "en" then mon.write("RF-Production: " .. input.formatNumberComma(math.floor(rfGen)) .. " RF/t ") end mon.setCursorPos(2, 10) if lang == "de" then mon.write("Reaktor: ") if r.getActive() then mon.setTextColor(colors.green) mon.write("an ") end if not r.getActive() then mon.setTextColor(colors.red) mon.write("aus") end elseif lang == "en" then mon.write("Reactor: ") if r.getActive() then mon.setTextColor(colors.green) mon.write("on ") end if not r.getActive() then mon.setTextColor(colors.red) mon.write("off") end end mon.setTextColor(tonumber(textColor)) --Display Fuel Consumption mon.setCursorPos(2, 12) local fuelCons2 = string.sub(fuelCons, 0, 4) if lang == "de" then mon.write("Reaktor-Verbrauch: " .. fuelCons2 .. "mb/t ") elseif lang == "en" then mon.write("Fuel Consumption: " .. fuelCons2 .. "mb/t ") end --Display Reactor Efficiency (RF/mb) mon.setCursorPos(2, 14) --Calculation and formatting of the efficiency local fuelEfficiency = rfGen / fuelCons if tonumber(fuelCons) == 0 then fuelEfficiency = 0 end local fuelEfficiency2 = math.floor(fuelEfficiency) if lang == "de" then mon.write("Effizienz: " .. input.formatNumber(fuelEfficiency2) .. " RF/mb ") elseif lang == "en" then mon.write("Efficiency: " .. input.formatNumberComma(fuelEfficiency2) .. " RF/mb ") end --Display the current Casing/Core Temperature local caT = tostring(r.getCasingTemperature()) local caseTemp = string.sub(caT, 0, 6) local coT = tostring(r.getFuelTemperature()) local coreTemp = string.sub(coT, 0, 6) mon.setCursorPos(2, 16) if lang == "de" then mon.write("Huellentemperatur: " .. caseTemp .. "C ") mon.setCursorPos(2, 17) mon.write("Kerntemperatur: " .. coreTemp .. "C ") elseif lang == "en" then mon.write("Casing Temperature: " .. caseTemp .. "C ") mon.setCursorPos(2, 17) mon.write("Core Temperature: " .. coreTemp .. "C ") end mon.setCursorPos(2, 25) mon.write("Version " .. version) end --Displays the data on the screen (manual mode) function displayDataMan() if r.getActive() then if not page.buttonList["reactorOn"].active then page:toggleButton("reactorOn") page:rename("reactorOn", rOn, true) end else if page.buttonList["reactorOn"].active then page:toggleButton("reactorOn") page:rename("reactorOn", rOff, true) end end page:draw() mon.setBackgroundColor(tonumber(backgroundColor)) mon.setTextColor(tonumber(textColor)) --Print the energy bar mon.setCursorPos(2, 2) if lang == "de" then mon.write("Energie: " .. enPer .. "% ") elseif lang == "en" then mon.write("Energy: " .. enPer .. "% ") end mon.setCursorPos(2, 3) local part1 = enPer / 5 mon.setCursorPos(2, 3) mon.setBackgroundColor(colors.lightGray) mon.write(" ") mon.setBackgroundColor(colors.green) mon.setCursorPos(2, 3) for i = 1, part1 do mon.write(" ") end mon.setTextColor(textColor) mon.setBackgroundColor(tonumber(backgroundColor)) --Print the reactor energy bar mon.setCursorPos(2, 5) if lang == "de" then mon.write("Energie (Reaktor): " .. enPerR .. "% ") elseif lang == "en" then mon.write("Energy (Reactor): " .. enPerR .. "% ") end mon.setCursorPos(2, 6) local part2 = enPerR / 5 mon.setCursorPos(2, 6) mon.setBackgroundColor(colors.lightGray) mon.write(" ") mon.setBackgroundColor(colors.green) mon.setCursorPos(2, 6) for i = 1, part2 do mon.write(" ") end mon.setTextColor(textColor) mon.setBackgroundColor(tonumber(backgroundColor)) --Print the RodLevel bar mon.setCursorPos(30, 2) mon.write("RodLevel: " .. rodLevel .. " ") mon.setCursorPos(30, 3) local part3 = rodLevel / 5 mon.setCursorPos(30, 3) mon.setBackgroundColor(colors.lightGray) mon.write(" ") mon.setBackgroundColor(colors.green) mon.setCursorPos(30, 3) for i = 1, part3 do mon.write(" ") end mon.setTextColor(textColor) mon.setBackgroundColor(tonumber(backgroundColor)) --Print the current RF Production of the reactor mon.setCursorPos(2, 8) if lang == "de" then mon.write("RF-Produktion: " .. input.formatNumber(math.floor(rfGen)) .. " RF/t ") elseif lang == "en" then mon.write("RF-Production: " .. input.formatNumberComma(math.floor(rfGen)) .. " RF/t ") end --Print the current status of the reactor mon.setCursorPos(2, 10) if lang == "de" then mon.write("Reaktor: ") elseif lang == "en" then mon.write("Reactor: ") end mon.setTextColor(tonumber(textColor)) --Display Fuel Consumption mon.setCursorPos(2, 12) local fuelCons2 = string.sub(tostring(fuelCons), 0, 4) if lang == "de" then mon.write("Reaktor-Verbrauch: " .. fuelCons2 .. "mb/t ") elseif lang == "en" then mon.write("Fuel Consumption: " .. fuelCons2 .. "mb/t ") end --Display Reactor Efficiency (RF/mb) mon.setCursorPos(2, 14) --Calculation and formatting of the efficiency local fuelEfficiency = rfGen / fuelCons if tonumber(fuelCons) == 0 then fuelEfficiency = 0 end local fuelEfficiency2 = math.floor(fuelEfficiency) if lang == "de" then mon.write("Effizienz: " .. input.formatNumber(fuelEfficiency2) .. " RF/mb ") elseif lang == "en" then mon.write("Efficiency: " .. input.formatNumberComma(fuelEfficiency2) .. " RF/mb ") end --Display the current Casing/Core temperature of the reactor local caT = tostring(r.getCasingTemperature()) local caseTemp = string.sub(caT, 0, 6) local coT = tostring(r.getFuelTemperature()) local coreTemp = string.sub(coT, 0, 6) mon.setCursorPos(2, 16) if lang == "de" then mon.write("Huellentemperatur: " .. caseTemp .. "C ") mon.setCursorPos(2, 17) mon.write("Kerntemperatur: " .. coreTemp .. "C ") elseif lang == "en" then mon.write("Casing Temperature: " .. caseTemp .. "C ") mon.setCursorPos(2, 17) mon.write("Core Temperature: " .. coreTemp .. "C ") end --Print the current version mon.setCursorPos(2, 25) mon.write("Version " .. version) end --Runs another program function run(program) shell.run(program) error("terminated.") end --Run checkPeripherals() if overallMode == "auto" then createButtons() elseif overallMode == "manual" then createButtonsMan() end mon.setBackgroundColor(tonumber(backgroundColor)) mon.setTextColor(tonumber(textColor)) mon.clear() getClick()
28.859961
117
0.611195
5d68da9b3e976b64485e5338e00a22222106cd49
1,901
cpp
C++
Demonstration/ranges.cpp
XuhuaHuang/Embeded-Cpp-Course
e1f67238fa3ae21963f144e4861802700845ebd9
[ "MIT" ]
null
null
null
Demonstration/ranges.cpp
XuhuaHuang/Embeded-Cpp-Course
e1f67238fa3ae21963f144e4861802700845ebd9
[ "MIT" ]
null
null
null
Demonstration/ranges.cpp
XuhuaHuang/Embeded-Cpp-Course
e1f67238fa3ae21963f144e4861802700845ebd9
[ "MIT" ]
null
null
null
/*****************************************************************//** * \file ranges.cpp * \brief Demonstration of ranges and views in C++ 20. * * $ g++ ranges.cpp -o exec -std=c++20 -Wall -Wextra -Wpedantic * $ ./exec * * \author Xuhua Huang * \date March 2022 *********************************************************************/ #include <iostream> #include <iomanip> #include <vector> #include <ranges> int main() { std::vector<std::int16_t> vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; constexpr auto is_even = [&](int elem) -> bool { return elem % 2 == 0; }; constexpr auto square = [&](int elem) -> int { return elem * elem; }; /* with std::views::filter */ auto even_nums = vec | std::views::filter(is_even); // view on stack with adaptor for (const int16_t& i : even_nums) { std::cout << i << " "; } std::cout << "\n" << "End execution with " << std::quoted("std::views::filter(is_even)") << "\n"; /* with std::ranges::filter_view */ for (const int16_t& i : std::ranges::filter_view(vec, is_even)) { std::cout << i << " "; } std::cout << "\n" << "End execution with " << std::quoted("std::ranges::filter_view(vec, is_even)") << "\n"; /* with std::views::transform */ auto even_nums_squared = even_nums | std::views::transform(square); // view on range-for loop for (const int16_t& i : even_nums_squared) { std::cout << i << " "; } std::cout << "\n" << "End execution with " << std::quoted("std::views::transform(square)") << "\n"; /* pipelining syntax */ auto output = vec | std::views::filter(is_even) | std::views::transform(square); // view on range-for loop for (const int16_t& i : output) { std::cout << i << " "; } std::cout << "\n" << "End execution with pipeline syntax" << "\n"; return 0; }
31.163934
97
0.509732
854ec3dc71eda90cbc2bfcf246ac4c972b0539bc
582
cs
C#
Chilicki.StarWars/Chilicki.StarWars.Data/Databases/UnitOfWorks/UnitOfWork.cs
mchilicki/star-wars-rest-api
f3bc6edc42ae2f741d3bec837c9cde88186c38ac
[ "MIT" ]
null
null
null
Chilicki.StarWars/Chilicki.StarWars.Data/Databases/UnitOfWorks/UnitOfWork.cs
mchilicki/star-wars-rest-api
f3bc6edc42ae2f741d3bec837c9cde88186c38ac
[ "MIT" ]
null
null
null
Chilicki.StarWars/Chilicki.StarWars.Data/Databases/UnitOfWorks/UnitOfWork.cs
mchilicki/star-wars-rest-api
f3bc6edc42ae2f741d3bec837c9cde88186c38ac
[ "MIT" ]
null
null
null
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Chilicki.StarWars.Data.Databases.UnitOfWorks { public class UnitOfWork : IUnitOfWork { private readonly DbContext context; public UnitOfWork(DbContext context) { this.context = context; } public async Task SaveAsync() { await context.SaveChangesAsync(); } public void Dispose() { context.Dispose(); } } }
20.068966
54
0.61512
be8b6f4950859f65a10f74de80c53029deae240f
107
ts
TypeScript
src/shared/models/domain/pt-task.model.ts
sebastiandenis/nativescripting-rpsnestapi
8b4323b96d1d3fb9ca2beef758d2f298c50c428f
[ "MIT" ]
null
null
null
src/shared/models/domain/pt-task.model.ts
sebastiandenis/nativescripting-rpsnestapi
8b4323b96d1d3fb9ca2beef758d2f298c50c428f
[ "MIT" ]
null
null
null
src/shared/models/domain/pt-task.model.ts
sebastiandenis/nativescripting-rpsnestapi
8b4323b96d1d3fb9ca2beef758d2f298c50c428f
[ "MIT" ]
null
null
null
import { PtObjectBase } from "./"; export interface PtTask extends PtObjectBase { completed: boolean; }
17.833333
46
0.728972
431a49aae83a4baaa64a4f0da15125df965919db
1,234
swift
Swift
KanjiRyokucha/UIViewExtensions.swift
gbuela/kanjiryokucha
d0acab917fc3257f70294dfa5472663293181ebb
[ "MIT" ]
4
2020-06-09T05:42:58.000Z
2021-01-21T15:19:07.000Z
KanjiRyokucha/UIViewExtensions.swift
gbuela/kanjiryokucha
d0acab917fc3257f70294dfa5472663293181ebb
[ "MIT" ]
59
2017-03-06T17:32:22.000Z
2020-06-01T02:30:17.000Z
KanjiRyokucha/UIViewExtensions.swift
gbuela/kanjiryokucha
d0acab917fc3257f70294dfa5472663293181ebb
[ "MIT" ]
null
null
null
// // UIViewExtensions.swift // KanjiRyokucha // // Created by German Buela on 12/9/16. // Copyright © 2016 German Buela. All rights reserved. // import UIKit protocol UIViewLoading {} extension UIView : UIViewLoading {} extension UIViewLoading where Self : UIView { static func loadFromNib() -> Self { let nibName = "\(self)".split{$0 == "."}.map(String.init).last! let nib = UINib(nibName: nibName, bundle: nil) let view = nib.instantiate(withOwner: self, options: nil).first as! Self view.translatesAutoresizingMaskIntoConstraints = false return view } } extension UIView { func layoutAttachAll(subview: UIView) { subview.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true subview.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true subview.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true subview.topAnchor.constraint(equalTo: self.topAnchor).isActive = true } func roundedCorners() { roundedCorners(withRadius: 8) } func roundedCorners(withRadius radius: Int) { layer.cornerRadius = CGFloat(radius) clipsToBounds = true } }
28.045455
85
0.675851
cd59260064baddc5806502ae7c0338a3bdb4452f
1,073
cs
C#
ExampleGame.Embedded/Form1.cs
TagsRocks/MonoGame-WinFormsControls
fa174f477937db7248f26ab7274c58575dbd5bd8
[ "MS-PL" ]
21
2015-03-19T04:36:57.000Z
2019-11-23T16:35:17.000Z
ExampleGame.Embedded/Form1.cs
TagsRocks/MonoGame-WinFormsControls
fa174f477937db7248f26ab7274c58575dbd5bd8
[ "MS-PL" ]
1
2015-09-28T06:22:20.000Z
2017-07-06T00:22:19.000Z
ExampleGame.Embedded/Form1.cs
TagsRocks/MonoGame-WinFormsControls
fa174f477937db7248f26ab7274c58575dbd5bd8
[ "MS-PL" ]
9
2015-06-02T15:36:57.000Z
2021-10-17T02:11:54.000Z
using System; using System.Windows.Forms; namespace ExampleGame { public partial class Form1 : Form { public Form1 () { InitializeComponent(); exampleGame1.BottomHitCountChanged += HandleBottomHitCountChanged; } protected override bool ProcessKeyPreview (ref Message m) { exampleGame1.ProcessKeyMessage(ref m); return base.ProcessKeyPreview(ref m); } protected override bool ProcessCmdKey (ref Message msg, Keys keyData) { exampleGame1.ProcessKeyMessage(ref msg); if (checkBox1.Checked) return true; return base.ProcessCmdKey(ref msg, keyData); } private void HandleBottomHitCountChanged (object sender, EventArgs e) { textBox1.Text = exampleGame1.BottomHitCount.ToString(); } private void numericUpDown1_ValueChanged (object sender, EventArgs e) { exampleGame1.SetBallCount((int)numericUpDown1.Value); } } }
26.170732
78
0.608574
5cab570caad92fb829e88f0dbc4604618f58bc30
1,388
dart
Dart
lib/src/middlewares/merger.dart
paulosilva159/fountain
b172688dd837145af9b79cc240cc12d1ad70ff12
[ "MIT" ]
47
2021-05-05T18:08:40.000Z
2021-09-06T13:36:54.000Z
lib/src/middlewares/merger.dart
paulosilva159/fountain
b172688dd837145af9b79cc240cc12d1ad70ff12
[ "MIT" ]
3
2021-05-05T18:42:24.000Z
2021-06-27T07:51:07.000Z
lib/src/middlewares/merger.dart
paulosilva159/fountain
b172688dd837145af9b79cc240cc12d1ad70ff12
[ "MIT" ]
4
2021-05-06T00:19:21.000Z
2021-11-30T05:42:15.000Z
import 'dart:async'; import 'package:fountain/src/event.dart'; import '../context.dart'; import 'middleware.dart'; /// Ignore duplicated concurent events. class EventMerger<TState> extends Middleware<TState> { EventMerger({ required this.eventTypes, }); final List<Type> eventTypes; final List<EventProcessing<TState>> processedEvents = <EventProcessing<TState>>[]; @override Stream<TState> call( Context<TState> context, Event event, NextMiddleware<TState> next, ) async* { if (eventTypes.contains(event.runtimeType)) { final existing = processedEvents.cast<EventProcessing<TState>?>().firstWhere( (x) => x!.event.runtimeType == event.runtimeType, orElse: () => null, ); if (existing != null) { await existing.updates.toList(); } else { final controller = StreamController<TState>(); final processing = EventProcessing(event, controller.stream); processedEvents.add(processing); await for (final state in next(context, event)) { yield state; controller.add(state); } processedEvents.remove(processing); controller.close(); } } } } class EventProcessing<TState> { const EventProcessing(this.event, this.updates); final Event event; final Stream<TState> updates; }
25.703704
70
0.636888
31a046accd2fc78ad635bf8ccb09ce998f1240db
541
go
Go
client/gossip_seed.go
tyrone-groves-3r/go-gesclient
15830d93281ad16923509c49ec775d901ecfb14e
[ "MIT" ]
39
2017-06-14T01:18:33.000Z
2022-01-26T05:18:17.000Z
client/gossip_seed.go
tyrone-groves-3r/go-gesclient
15830d93281ad16923509c49ec775d901ecfb14e
[ "MIT" ]
13
2017-07-21T04:46:11.000Z
2020-10-02T17:57:01.000Z
client/gossip_seed.go
tyrone-groves-3r/go-gesclient
15830d93281ad16923509c49ec775d901ecfb14e
[ "MIT" ]
19
2017-04-18T17:00:53.000Z
2021-05-14T15:32:43.000Z
package client import ( "fmt" "net" ) type GossipSeed struct { ipEndpoint *net.TCPAddr hostHeader string } func NewGossipSeed(ipEndpoint *net.TCPAddr, hostHeader string) *GossipSeed { return &GossipSeed{ ipEndpoint: ipEndpoint, hostHeader: hostHeader, } } func (gs *GossipSeed) IpEndpoint() *net.TCPAddr { return gs.ipEndpoint } func (gs *GossipSeed) HostHeader() string { return gs.hostHeader } func (gs *GossipSeed) String() string { return fmt.Sprintf("&{ipEndpoint:%+v hostHeader:%s}", gs.ipEndpoint, gs.hostHeader) }
17.451613
84
0.728281
403f4e9c33b279f8d31270e3bb37663e644350ce
3,097
rb
Ruby
app/models/precomputed_query_doc.rb
trevorsaunders/studentinsights
466e27cf4838f491cfc1f0137af8ab42afec1b85
[ "MIT" ]
134
2016-02-15T20:50:17.000Z
2022-01-04T01:59:14.000Z
app/models/precomputed_query_doc.rb
trevorsaunders/studentinsights
466e27cf4838f491cfc1f0137af8ab42afec1b85
[ "MIT" ]
2,201
2016-02-08T20:29:07.000Z
2022-02-27T18:31:58.000Z
app/models/precomputed_query_doc.rb
trevorsaunders/studentinsights
466e27cf4838f491cfc1f0137af8ab42afec1b85
[ "MIT" ]
72
2016-02-10T01:20:11.000Z
2021-09-14T05:12:05.000Z
class PrecomputedQueryDoc < ApplicationRecord # A key-value store for holding a precomputed JSON doc (eg, for a query that's hard to optimize # or wants to use arbitrary Ruby code). It's intended to be precomputed and durable, not a # read-through cache (since the computations are expensive). # Read back precomputed hashes for students. Return nil if the most recent document is more # stale than a specific window. def self.latest_precomputed_student_hashes_for(authorized_student_ids, options = {}) time_now = options.fetch(:time_now, Time.now) is_fresh_window = options.fetch(:is_fresh_window, 48.hours) key = PrecomputedQueryDoc.precomputed_student_hashes_key(authorized_student_ids) doc = PrecomputedQueryDoc .where(key: key) .where('created_at > ?', time_now - is_fresh_window) .order(created_at: :desc) .limit(1) .first return nil if doc.nil? JSON.parse(doc.json).deep_symbolize_keys![:student_hashes] end # The primary key means nothing, and reads and writes should be done based on the `key` column. # # There are a few variations on this over time. # # 1) precomputed_student_hashes / :force_deprecated_key # The original formats to this key concatenated all student_ids but is deprecated and # no longer used (although it's still here since data still exists thats keyed like that). # That can be accessed with `force_deprecated_key`. # # 2) short / :force_deprecated_day_based_key # This hashes all the student_ids, since plain concatenation led to really long strings that # were outside the length limit for the key column. # # 3) continuous_for_student_ids # originally we ran the import every day, and scheduled the precompute task to come after, # so it made sense for the key to be "give me the value for this day" but running more # frequent imports means this doesn't fit as well, and then complicates the fallback from # simply "last computed value". this no longer uses the "date" as a key, and we add this # precompute task to the end of the import job. def self.precomputed_student_hashes_key(authorized_student_ids, options = {}) if options[:force_deprecated_key] timestamp = options.fetch(:time_now, Time.now).beginning_of_day.to_i students_key = authorized_student_ids.sort.join(',') ['precomputed_student_hashes', timestamp, students_key].join('_') elsif options[:force_deprecated_day_based_key] timestamp = options.fetch(:time_now, Time.now).beginning_of_day.to_i students_digest = self.authorized_students_digest(authorized_student_ids) ['short', timestamp, authorized_student_ids.size, students_digest].join(':') else students_digest = self.authorized_students_digest(authorized_student_ids) ['continuous_for_student_ids', authorized_student_ids.size, students_digest].join(':') end end def self.authorized_students_digest(authorized_student_ids) authorized_students_key = authorized_student_ids.sort.join(',') Digest::SHA256.hexdigest(authorized_students_key) end end
49.15873
97
0.752341
be712ea952b8565854ffc9d7ee72cbc3c7652e94
20,423
ts
TypeScript
app/elements/screensaver-element/screensaver-element.ts
EricTousignant/screensaver
c6906a67ce6227b2688355fbd1a0c9b4bda13bbb
[ "BSD-3-Clause" ]
26
2019-02-20T04:23:08.000Z
2021-11-17T04:12:06.000Z
app/elements/screensaver-element/screensaver-element.ts
EricTousignant/screensaver
c6906a67ce6227b2688355fbd1a0c9b4bda13bbb
[ "BSD-3-Clause" ]
25
2019-02-16T15:06:50.000Z
2021-05-08T02:40:39.000Z
app/elements/screensaver-element/screensaver-element.ts
EricTousignant/screensaver
c6906a67ce6227b2688355fbd1a0c9b4bda13bbb
[ "BSD-3-Clause" ]
13
2019-05-27T03:54:53.000Z
2021-12-28T16:09:12.000Z
/** * Custom element for a screensaver * * @module els/screensaver */ /** */ /* * Copyright (c) 2015-2019, Michael A. Updike All rights reserved. * Licensed under the BSD-3-Clause * https://opensource.org/licenses/BSD-3-Clause * https://github.com/opus1269/screensaver/blob/master/LICENSE.md */ import {NeonAnimatedPagesElement} from '../../node_modules/@polymer/neon-animation/neon-animated-pages'; import {DomRepeat} from '../../node_modules/@polymer/polymer/lib/elements/dom-repeat'; import {TIME_FORMAT} from '../../node_modules/@opus1269/chrome-ext-utils/src/time'; import {SSPhoto} from '../../scripts/screensaver/ss_photo'; import {IPhoto} from '../../scripts/sources/photo_source'; import {ScreensaverSlideElement} from '../screensaver-slide/screensaver-slide'; import {customElement, property, query} from '../../node_modules/@polymer/decorators/lib/decorators.js'; import {html} from '../../node_modules/@polymer/polymer/polymer-element.js'; import '../../node_modules/@polymer/font-roboto/roboto.js'; import '../../node_modules/@polymer/iron-image/iron-image.js'; import '../../node_modules/@polymer/neon-animation/neon-animatable.js'; import '../../node_modules/@polymer/neon-animation/neon-animated-pages.js'; import '../../node_modules/@polymer/neon-animation/neon-animations.js'; import {BaseElement} from '../../node_modules/@opus1269/common-custom-elements/src/base-element/base-element.js'; import '../../elements/screensaver-slide/screensaver-slide.js'; import * as ChromeGA from '../../node_modules/@opus1269/chrome-ext-utils/src/analytics.js'; import * as ChromeLog from '../../node_modules/@opus1269/chrome-ext-utils/src/log.js'; import * as ChromeMsg from '../../node_modules/@opus1269/chrome-ext-utils/src/msg.js'; import * as ChromeStorage from '../../node_modules/@opus1269/chrome-ext-utils/src/storage.js'; import {ChromeTime} from '../../node_modules/@opus1269/chrome-ext-utils/src/time.js'; import * as ChromeUtils from '../../node_modules/@opus1269/chrome-ext-utils/src/utils.js'; import * as MyGA from '../../scripts/my_analytics.js'; import * as MyMsg from '../../scripts/my_msg.js'; import * as Permissions from '../../scripts/permissions.js'; import * as FaceDetect from '../../scripts/screensaver/face_detect.js'; import * as SSEvents from '../../scripts/screensaver/ss_events.js'; import * as SSHistory from '../../scripts/screensaver/ss_history.js'; import * as SSPhotos from '../../scripts/screensaver/ss_photos.js'; import * as SSRunner from '../../scripts/screensaver/ss_runner.js'; import * as PhotoSourceFactory from '../../scripts/sources/photo_source_factory.js'; import {GoogleSource} from '../../scripts/sources/photo_source_google.js'; // removeIf(always) import ChromePromise from 'chrome-promise/chrome-promise'; // endRemoveIf(always) const chromep = new ChromePromise(); /** Slide transition animation type */ export const enum TRANS_TYPE { SCALE_UP = 0, FADE, SLIDE_FROM_RIGHT, SLIDE_DOWN, SPIN_UP, SLIDE_UP, SLIDE_FROM_BOTTOM, SLIDE_RIGHT, RANDOM, } /** Slide appearance type */ export const enum VIEW_TYPE { LETTERBOX = 0, ZOOM, FRAME, FULL, RANDOM, } /** Object to handle Google Photos load errors */ const errHandler = { /** maximum number of times to call */ MAX_COUNT: 168, // about a weeks worth, if all goes well /** count of calls */ count: 0, /** true if an event is handling an error */ isUpdating: false, /** throttle calls to this fast in case something weird happens */ TIME_LIMIT: (5 * 60000), // five minutes in milli sec /** last time called */ lastTime: 0, }; /** Polymer element to display a screensaver */ @customElement('screensaver-element') export class ScreensaverElement extends BaseElement { /** Get slide appearance */ protected static getViewType() { let type = ChromeStorage.get('photoSizing', VIEW_TYPE.LETTERBOX); if (type === VIEW_TYPE.RANDOM) { // pick random sizing type = ChromeUtils.getRandomInt(0, VIEW_TYPE.RANDOM - 1); } return type; } /** Get between photo's animation */ protected static getAniType() { let type = ChromeStorage.get('photoTransition', TRANS_TYPE.FADE); if (type === TRANS_TYPE.RANDOM) { // pick random transition type = ChromeUtils.getRandomInt(0, TRANS_TYPE.RANDOM - 1); } return type; } /** Set the window zoom factor to 1.0 */ protected static async setZoom() { try { const zoomFactor = await chromep.tabs.getZoom(); if ((zoomFactor <= 0.99) || (zoomFactor >= 1.01)) { chrome.tabs.setZoom(1.0); } } catch (err) { ChromeGA.error(err.message, 'SS.setZoom'); } } /** * Setup face detection * * @throws An error if failed to initialize face-api.js */ protected static async setupFaceDetect() { const panAndZoom = ChromeStorage.get('panAndScan', false); if (panAndZoom) { await FaceDetect.initialize(); } } /** * Maximum number of slides to create * * @remarks * Actual number will be the smaller of this and the total number of photos */ protected readonly MAX_SLIDES = 10; /** Array of {@link SSPhoto} in the views */ @property({type: Array}) protected photos: SSPhoto[] = []; /** Type for between photo animation */ @property({type: Number}) protected readonly aniType = ScreensaverElement.getAniType(); /** Type for photo appearance */ @property({type: Number}) protected readonly viewType = ScreensaverElement.getViewType(); /** Flag to indicate if slideshow is paused */ @property({type: Boolean, observer: 'pausedChanged'}) protected paused = false; /** Flag to indicate if we have no valid photos */ @property({type: Boolean}) protected noPhotos = false; /** Label for current time */ @property({type: String}) protected timeLabel = ''; /** Slide repeat template */ @query('#repeatTemplate') protected repeatTemplate: DomRepeat; /** NeonAnimatedPages */ @query('#pages') protected pages: NeonAnimatedPagesElement; /** Delay before showing first slide in milli secs */ protected delayTime = 1500; /** * Called when the element is added to a document. * Can be called multiple times during the lifetime of an element. */ public connectedCallback() { super.connectedCallback(); // listen for events SSEvents.addListeners(); } /** * Called when the element is removed from a document. * Can be called multiple times during the lifetime of an element. */ public disconnectedCallback() { super.disconnectedCallback(); // stop listening for events SSEvents.removeListeners(); } /** * Called during Polymer-specific element initialization. * Called once, the first time the element is attached to the document. */ public async ready() { super.ready(); // set selected background image document.body.style.background = ChromeStorage.get('background', 'background:linear-gradient(to bottom, #3a3a3a, #b5bdc8)').substring(11); MyGA.initialize(); ChromeGA.page('/screensaver.html'); await ScreensaverElement.setZoom(); } /** Launch the slide show */ public async launch() { const METHOD = 'SS.launch'; try { // load all the photos const shuffle = ChromeStorage.get('shuffle', false); const hasPhotos = await SSPhotos.loadPhotos(shuffle); if (!hasPhotos) { this.setNoPhotos(); return; } // setup face detection try { await ScreensaverElement.setupFaceDetect(); } catch (err) { ChromeGA.error(err.message, METHOD); } // initialize the slide photos const photos: SSPhoto[] = []; const length = Math.min(SSPhotos.getCount(), this.MAX_SLIDES); for (let i = 0; i < length; i++) { const photo = SSPhotos.getNextUsable(); if (photo) { photos.push(photo); } } this.set('photos', photos); this.repeatTemplate.render(); if (photos.length === 0) { this.setNoPhotos(); return; } // send msg to update weather. don't wait can be slow ChromeMsg.send(MyMsg.TYPE.UPDATE_WEATHER).catch(() => {}); // set time label timer this.setupTime(); // kick off the slide show SSRunner.start(this.delayTime); } catch (err) { ChromeLog.error(err.message, METHOD); this.setNoPhotos(); } } /** Get max number of slides */ public getMaxSlideCount() { return this.MAX_SLIDES; } /** Get the photos currently in the slides */ public getPhotos() { return this.photos; } /** * Get the selected photo * * @returns The selected photo, undefined if non selected */ public getSelectedPhoto() { let ret; const idx = this.getSelectedSlideIndex(); if (idx !== -1) { ret = this.photos[idx]; } return ret; } /** * Replace the slide photo at the given index * * @param photo - new photo * @param idx - index to replace */ public replacePhoto(photo: SSPhoto, idx: number) { if (photo && (idx >= 0)) { this.splice('photos', idx, 1, photo); // force immediate update of url const slide = this.getSlide(idx); slide.setUrl(photo.getUrl()); slide.notifyPath('url'); } } /** * Try to find a slide photo that has finished loading * * @param idx - index into {@link photos} * @returns index into {@link photos}, -1 if none are loaded */ public findLoadedPhoto(idx: number) { if (!this.hasUsablePhoto()) { this.replaceAllPhotos(); } const curSlide = this.getSlide(idx); if (curSlide && curSlide.isPhotoLoaded()) { return idx; } // wrap-around loop: https://stackoverflow.com/a/28430482/4468645 for (let i = 0; i < this.photos.length; i++) { const index = (i + idx) % this.photos.length; const slide = this.getSlide(index); const photo = this.photos[index]; if (SSRunner.isCurrentPair(index)) { // don't use current animation pair continue; } if (slide.isPhotoLoaded()) { return index; } else if (slide.isPhotoError() && !photo.isBad()) { photo.markBad(); if (!SSPhotos.hasUsable()) { // all photos bad this.setNoPhotos(); return -1; } } } return -1; } /** * Is the given idx the selected slide * * @param idx - index into {@link photos} * @returns true if selected */ public isSelectedSlideIndex(idx: number) { let ret = false; if (this.pages && (idx === this.pages.selected)) { ret = true; } return ret; } /** * Get the index of the selected slide * * @returns The index of the current slide, -1 if none selected */ public getSelectedSlideIndex() { if (this.pages) { let selected: number; if (typeof this.pages.selected === 'string') { selected = parseInt(this.pages.selected, 10); } else { selected = this.pages.selected; } return selected; } return -1; } /** * Set the selected index of the pages * * @param idx - slide index */ public setSelectedSlideIndex(idx: number) { if (this.pages) { this.pages.selected = idx; } } /** Get the number of slides */ public getSlideCount() { return this.photos ? this.photos.length : 0; } /** Get the slide at the given index */ public getSlide(idx: number) { const selector = `#slide${idx}`; return (this.shadowRoot as ShadowRoot).querySelector(selector) as ScreensaverSlideElement; } /** Do we have usable photos */ public isNoPhotos() { return this.noPhotos; } /** Set the state when no photos are available */ public setNoPhotos() { this.set('noPhotos', true); } /** Set the paused state of the slideshow */ public setPaused(paused: boolean) { this.set('paused', paused); } /** Setup timer for time label */ protected setupTime() { const showTime = ChromeStorage.get('showTime', TIME_FORMAT.NONE); if (showTime !== TIME_FORMAT.NONE) { this.setTimeLabel(); // update current time once a minute setInterval(this.setTimeLabel.bind(this), 61 * 1000); } } /** Set the time label */ protected setTimeLabel() { let label = ''; const showTime = ChromeStorage.get('showTime', TIME_FORMAT.NONE); if ((showTime !== TIME_FORMAT.NONE)) { label = ChromeTime.getStringShort(showTime); this.set('timeLabel', label); } } /** * Simple Observer: Paused state changed * * @param newValue - new value * @param oldValue - old value */ protected pausedChanged(newValue: boolean, oldValue: boolean) { if (oldValue === undefined) { return; } if (newValue) { this.$.pauseImage.classList.add('fadeOut'); this.$.playImage.classList.remove('fadeOut'); } else { this.$.playImage.classList.add('fadeOut'); this.$.pauseImage.classList.remove('fadeOut'); } } /** Do we have a photo that is loaded */ protected hasUsablePhoto() { let ret = false; for (let i = 0; i < this.photos.length; i++) { const photo = this.photos[i]; if (SSRunner.isCurrentPair(i)) { // don't check current animation pair continue; } if (!photo.isBad()) { ret = true; break; } } return ret; } /** Replace the photo in all the slides but the current animation pair */ protected replaceAllPhotos() { for (let i = 0; i < this.photos.length; i++) { if (SSRunner.isCurrentPair(i)) { // don't replace current animation pair continue; } const photo = SSPhotos.getNextUsable(this.photos); if (photo) { this.replacePhoto(photo, i); } else { // all bad break; } } SSHistory.clear(); } /** * Update the url in all the slides * * @param photos - Photos whose url's have changed */ protected updateAllUrls(photos: IPhoto[]) { for (let i = 0; i < this.photos.length; i++) { const photo = this.photos[i]; const type = photo.getType(); if (type === PhotoSourceFactory.Type.GOOGLE_USER) { const slide = this.getSlide(i); const index = photos.findIndex((e) => { return e.ex.id === photo.getEx().id; }); if (index >= 0) { slide.setUrl(photos[index].url); } } } } // noinspection JSUnusedGlobalSymbols /** * An image failed to load * * @event */ protected async onImageError(ev: CustomEvent) { if (errHandler.isUpdating) { // another error event is already handling this return; } // url failed to load errHandler.isUpdating = true; const index = ev.detail.value; const thePhoto = this.photos[index]; const theType = thePhoto.getType(); if (theType === PhotoSourceFactory.Type.GOOGLE_USER) { try { // Google baseUrl may have expired, try to update some photos // no point if not online if (!navigator.onLine) { errHandler.isUpdating = false; return; } // throttle call rate to Google API per screensaver session // in case something weird happens if ((Date.now() - errHandler.lastTime) < errHandler.TIME_LIMIT) { errHandler.isUpdating = false; return; } // limit max number of calls to Google API per screensaver session // in case something weird happens errHandler.count++; if (errHandler.count >= errHandler.MAX_COUNT) { errHandler.isUpdating = false; return; } // update last call time errHandler.lastTime = Date.now(); const url = thePhoto.getUrl(); const hasCors = await Permissions.isGoogleSourceOrigin(url); if (hasCors) { // If we can make a cors request, fetch again and check status. // If it is not a 403 error, return; try { const response = await fetch(url, {method: 'get'}); const status = response.status; if (status !== 403) { // some other problem, don't know how to fix it errHandler.isUpdating = false; return; } } catch (err) { // some other problem, don't know how to fix it errHandler.isUpdating = false; return; } } // Calculate an hours worth of photos max const transValue = ChromeStorage.get('transitionTime', {base: 30, display: 30, unit: 0}); const transTime = transValue.base * 1000; let nPhotos = Math.round(ChromeTime.MSEC_IN_HOUR / transTime); // do at least 50, still one rpc. will help when displaying // a lot for short times nPhotos = Math.max(nPhotos, 50); if (errHandler.count === 1) { // limit to 50 on first call for quicker starts nPhotos = Math.min(nPhotos, 50); } else { // limit to 300 on subsequent calls nPhotos = Math.min(nPhotos, 300); } // get max of nPhotos Google Photo ids starting at this one const startIdx = SSPhotos.getIndex(thePhoto); const photos = SSPhotos.getNextGooglePhotos(nPhotos, startIdx); const ids = []; for (const photo of photos) { // unique ids only - required for batchGet call const ex = photo.getEx(); if (ex) { const id = ex.id; if (ids.indexOf(id) === -1) { ids.push(id); } } } // load the new photos from Google Photos const newPhotos = await GoogleSource.loadPhotos(ids); // update the Google Photos baseUrls for this screensaver session SSPhotos.updateGooglePhotoUrls(newPhotos); // update any views with the new google photos this.updateAllUrls(newPhotos); // persist new baseUrls to albumSelections const updated = await GoogleSource.updateBaseUrls(newPhotos); if (!updated) { // major problem, give up for this session ChromeGA.error('Failed to save new urls', 'SS.onImageError'); errHandler.count = errHandler.MAX_COUNT + 1; errHandler.isUpdating = true; return; } errHandler.isUpdating = false; } catch (err) { // major problem, give up for this session ChromeGA.error(err.message, 'SS.onImageError'); errHandler.count = errHandler.MAX_COUNT + 1; errHandler.isUpdating = true; return; } } } static get template() { // language=HTML format=false return html`<style include="shared-styles iron-flex iron-flex-alignment iron-positioning"> :host { display: block; } /* Added programmatically */ .fadeOut { animation: fadeOut 1s 2s; animation-fill-mode: both; } @keyframes fadeOut { from { opacity: 1.0; } to { opacity: 0.0; } } .vcr { position: fixed; width: 15vh; height: 15vh; left: 50%; top: 50%; transform: translate(-50%, -50%); opacity: 0.0; } .noPhotos { font-size: 5vh; font-weight: 600; position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); color: rgba(48, 63, 159, 1); opacity: .8; } </style> <div id="mainContainer" class="flex" hidden$="[[noPhotos]]"> <neon-animated-pages id="pages" class="fit" animate-initial-selection> <template is="dom-repeat" id="repeatTemplate" as="photo" items="[[photos]]"> <screensaver-slide class="fit" id="slide[[index]]" view-type="[[viewType]]" ani-type="[[aniType]]" photo="[[photo]]" index="[[index]]" time-label="[[timeLabel]]" on-image-error="onImageError"> </screensaver-slide> </template> </neon-animated-pages> </div> <div class="noPhotos" hidden$="[[!noPhotos]]">[[localize('no_photos')]]</div> <iron-image id="pauseImage" class="vcr" src="../images/pause.png" sizing="contain" preload hidden$="[[!paused]]"></iron-image> <iron-image id="playImage" class="vcr" src="../images/play.png" sizing="contain" preload hidden$="[[paused]]"></iron-image> `; } }
28.643759
118
0.618567
79e99d0b7373144016cd33f01a72c0d4b3c1afcf
4,303
hpp
C++
src/include/vector2d.hpp
andeluvian/micromachines
566e51a7555c0b3ab974e0fb87e3387a3427f655
[ "Apache-2.0" ]
null
null
null
src/include/vector2d.hpp
andeluvian/micromachines
566e51a7555c0b3ab974e0fb87e3387a3427f655
[ "Apache-2.0" ]
null
null
null
src/include/vector2d.hpp
andeluvian/micromachines
566e51a7555c0b3ab974e0fb87e3387a3427f655
[ "Apache-2.0" ]
null
null
null
#ifndef VECTOR2D_HH #define VECTOR2D_HH #define PI 3.141592654 #include <iostream> #include "structures.hpp" /** * Author: Miika Karsimus * * Utility class for representing 2-dimensional vector (x and y components). * Note that most part of the functions are overloaded operators. * It makes it easy to use the class. You can, for example, sum two vector by typing v1 + v2 * or calculate the dot product of two vectors by typing v1 * v2. * * The vector can be used for example representing velocity, acceleration, direction or * just a point in xy-space. */ class Vector2D { public: /// Pass x and y components as parameters Vector2D(const double& x1, const double& y1); double getLength() const; // Self-explanatory functions. inline const double& getX() const { return x; } inline const double& getY() const { return y; } inline void setX(double x1) { x = x1; } inline void setY(double y1) { y = y1; } /// Rotate the vector clockwise (direction in SFML coordinate frame). void rotate(double degs); /// Mirror the vector about x or y-axis. void mirror(const char& c); /// Mirror the vector about and arbitrary vector. /// E.g. [0, 1] mirrored about [1, 1] yields [1, 0]. void mirror(const Vector2D& vector); /// Returns a string representation of the vector. std::string str() const; /// Return an unit vector parallel to this vector. Vector2D getUnitVector() const; /// Get unit vector which angle is degs degrees relative to x-axis. /// e.g. calling with parameter 45 would result [0.707, 0.707]. static Vector2D getUnitVector(const double& degs); /// Get vector which is the normal of mirrorVector. Direction depends on v1. static Vector2D getMirrorNormal(Vector2D& v1, const Vector2D& mirrorVector); /// Convert degrees to radians. static double deg2rad(const double& degs); /// Convert radians to degrees. static double rad2deg(const double& rads); /// Return angle between vector and x-axis. static double axisAngle(const Vector2D& v); /// Move point to the direction of the vector and return a new Point. /// E.g. calling with {2, 1}, {5, 7} yields {7, 8}. static structures::Point movePoint(const structures::Point& point, const Vector2D& v); /// Return a new rotated vector. Doesn't affect this vector. /// Note the difference between this and the member-function rotate. static Vector2D rotated(const Vector2D& v, double degs); /// Tell if two vector are parallel. static bool isParallel(const Vector2D& v1, const Vector2D& v2); /// Return the angle between two vectors in degrees. static double angleBetween(const Vector2D& v1, const Vector2D& v2); /// Determinant between two vector. Needed by the angleBetween() function. static double determinant(const Vector2D& v1, const Vector2D& v2); private: double x; // x-component double y; // y-component // The following functions are declared as friends in order to // access the private members x and y. friend std::ostream& operator<<(std::ostream& os, const Vector2D& v); friend double operator*(const Vector2D& v1, const Vector2D& v2); friend Vector2D operator*(const Vector2D& v1, double coeff); friend Vector2D operator/(const Vector2D& v1, double coeff); friend Vector2D operator+(const Vector2D& v1, const Vector2D& v2); friend Vector2D operator-(const Vector2D& v1, const Vector2D& v2); friend Vector2D operator-(const Vector2D& v); friend class VehiclePhysics; }; // overloaded operators /// Print vector to stdout. std::ostream& operator<<(std::ostream& os, const Vector2D& v); // Dot product with another vector. Returns scalar (double). double operator*(const Vector2D& v1, const Vector2D& v2); /// Product with a floating point number. Vector2D operator*(const Vector2D& v1, double coeff); /// Divide vector with floating point number. Vector2D operator/(const Vector2D& v1, double coeff); /// Sum two vectors. Vector2D operator+(const Vector2D& v1, const Vector2D& v2); /// Substraction of two vectors. Vector2D operator-(const Vector2D& v1, const Vector2D& v2); /// Unary operator. Vector2D operator-(const Vector2D& v); #endif
29.272109
92
0.695329
ee966c9251762cfe7c65c53fe36939ce38c81a7e
2,920
rb
Ruby
lib/active_brainz/models/recording/recording.rb
floriandejonckheere/active_brainz
b84e53e203600e4145bf4bc6d35f6070cf4f398a
[ "MIT" ]
1
2021-02-24T09:53:45.000Z
2021-02-24T09:53:45.000Z
lib/active_brainz/models/recording/recording.rb
floriandejonckheere/active_brainz
b84e53e203600e4145bf4bc6d35f6070cf4f398a
[ "MIT" ]
null
null
null
lib/active_brainz/models/recording/recording.rb
floriandejonckheere/active_brainz
b84e53e203600e4145bf4bc6d35f6070cf4f398a
[ "MIT" ]
null
null
null
# frozen_string_literal: true module ActiveBrainz class Recording < Base self.table_name = "recording" include HasGID belongs_to :recording_artist_credit, class_name: "ArtistCredit", foreign_key: "artist_credit", optional: true # has_many :edit_recordings, # class_name: "EditRecording", # foreign_key: "recording" # has_many :editor_collection_recordings, # class_name: "EditorCollectionRecording", # foreign_key: "recording" # has_many :isrcs, # class_name: "Isrc", # foreign_key: "recording" # has_many :recording_aliases, # class_name: "RecordingAlias", # foreign_key: "recording" # has_many :recording_annotations, # class_name: "RecordingAnnotation", # foreign_key: "recording" # has_many :recording_attributes, # class_name: "RecordingAttribute", # foreign_key: "recording" # has_many :recording_first_release_dates, # class_name: "RecordingFirstReleaseDate", # foreign_key: "recording" # has_many :recording_gid_redirects, # class_name: "RecordingGIDRedirect", # foreign_key: "new_id" # has_many :recording_meta, # class_name: "RecordingMeta", # foreign_key: "id" # has_many :recording_rating_raws, # class_name: "RecordingRatingRaw", # foreign_key: "recording" # has_many :recording_tag_raws, # class_name: "RecordingTagRaw", # foreign_key: "recording" # has_many :recording_tags, # class_name: "RecordingTag", # foreign_key: "recording" has_many :tracks, class_name: "Track", foreign_key: "recording" attribute :name attribute :comment attribute :length, :integer attribute :video, :boolean attribute :edits_pending, :integer attribute :last_updated, :datetime end end # == Schema Information # # Table name: recording # # id :integer not null, primary key # artist_credit :integer not null # comment :string(255) default(""), not null # edits_pending :integer default(0), not null # gid :uuid not null # last_updated :datetime # length :integer # name :string not null # video :boolean default(FALSE), not null # # Indexes # # recording_idx_artist_credit (artist_credit) # recording_idx_gid (gid) UNIQUE # recording_idx_musicbrainz_collate (name) # recording_idx_name (name) # recording_idx_txt (mb_simple_tsvector((name)::text)) USING gin # # Foreign Keys # # recording_fk_artist_credit (artist_credit => artist_credit.id) #
28.627451
82
0.594521
da20d54d0319faef29232b8bddca7709c4028de5
1,022
php
PHP
database/migrations/PURCHASESMS/2020_05_19_163901_create_accounts_purchases.php
exelpack/exelpack-api
ddbb2631c7c0dd40053d823c8779695450cf0432
[ "MIT" ]
null
null
null
database/migrations/PURCHASESMS/2020_05_19_163901_create_accounts_purchases.php
exelpack/exelpack-api
ddbb2631c7c0dd40053d823c8779695450cf0432
[ "MIT" ]
null
null
null
database/migrations/PURCHASESMS/2020_05_19_163901_create_accounts_purchases.php
exelpack/exelpack-api
ddbb2631c7c0dd40053d823c8779695450cf0432
[ "MIT" ]
null
null
null
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAccountsPurchases extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('purchasesms_apdetails', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('ap_item_id')->unsigned(); $table->double('ap_withholding')->default(0)->nullable(); $table->string('ap_officialreceipt_no',100); $table->boolean('ap_is_check')->default(0); $table->string('ap_check_no',50)->nullable(); $table->string('ap_bankname',150)->nullable(); $table->date('ap_payment_date')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('purchasesms_apdetails'); } }
26.205128
77
0.59589
989a30fce01799e9f09b7c41fbf76d1c86b1c5f0
258
lua
Lua
example/server/init.server.lua
Nezuo/class
26c027926c856ea91d42ce2cacd430b6a802c446
[ "MIT" ]
2
2020-10-19T03:27:05.000Z
2020-12-13T15:17:07.000Z
example/server/init.server.lua
Nezuo/class
26c027926c856ea91d42ce2cacd430b6a802c446
[ "MIT" ]
null
null
null
example/server/init.server.lua
Nezuo/class
26c027926c856ea91d42ce2cacd430b6a802c446
[ "MIT" ]
null
null
null
local ServerScriptService = game:GetService("ServerScriptService") local Pet = require(ServerScriptService.Pet) local Dog = require(ServerScriptService.Dog) local pet = Pet.new("Chuck", 6) pet:sayHi() local dog = Dog.new("Annie", 7) dog:sayHi() dog:bark()
23.454545
66
0.751938
bba00ee841f31df42d368fb0716036e946ea819c
9,794
kt
Kotlin
tinyK-frontend-cheesy/src/main/kotlin/tinyK/frontend/cheesy/parser/Parser.kt
pocmo/tinyK
1e57fb51c659e6e4dc713087d09a76be935bf2c5
[ "Apache-2.0" ]
null
null
null
tinyK-frontend-cheesy/src/main/kotlin/tinyK/frontend/cheesy/parser/Parser.kt
pocmo/tinyK
1e57fb51c659e6e4dc713087d09a76be935bf2c5
[ "Apache-2.0" ]
15
2020-08-23T17:07:14.000Z
2020-09-03T20:24:36.000Z
tinyK-frontend-cheesy/src/main/kotlin/tinyK/frontend/cheesy/parser/Parser.kt
pocmo/tinyK
1e57fb51c659e6e4dc713087d09a76be935bf2c5
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Sebastian Kaspari * * 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 tinyK.frontend.cheesy.parser import tinyK.ast.BinaryOperation import tinyK.ast.ConjunctionNode import tinyK.ast.DisjunctionNode import tinyK.ast.EqualityNode import tinyK.ast.ExpressionNode import tinyK.ast.FunctionCallNode import tinyK.ast.IdentifierNode import tinyK.ast.LiteralNode import tinyK.ast.MemberAccessNode import tinyK.ast.PropertyDeclarationNode import tinyK.ast.ScriptNode import tinyK.ast.StatementNode import tinyK.ast.metadata.Type import tinyK.frontend.cheesy.scanner.Token import tinyK.frontend.cheesy.scanner.isAdditiveOperator import tinyK.frontend.cheesy.scanner.isCallSuffix import tinyK.frontend.cheesy.scanner.isDeclaration import tinyK.frontend.cheesy.scanner.isEqualityOperator import tinyK.frontend.cheesy.scanner.isLiteral import tinyK.frontend.cheesy.scanner.isMemberAccessOperator import tinyK.frontend.cheesy.scanner.isMultiplicativeOperator import tinyK.frontend.cheesy.scanner.isPostfixUnarySuffix import tinyK.frontend.cheesy.scanner.isPropertyDeclaration import tinyK.frontend.cheesy.util.TokenReader /** * An exception that happened during parsing. */ class ParserException(message: String) : Exception(message) /** * A hand-written recursive decent parser supporting a subset of the Kotlin programming language. * * Kotlin Grammar: * https://kotlinlang.org/docs/reference/grammar.html * * Kotlin Grammar in ANTLR4 notation: * https://github.com/Kotlin/kotlin-spec/blob/release/grammar/src/main/antlr/KotlinParser.g4 * * Clang AST docs: * https://clang.llvm.org/docs/IntroductionToTheClangAST.html * * Kotlin PSI: * https://github.com/JetBrains/kotlin/tree/master/compiler/psi/src/org/jetbrains/kotlin/psi */ class Parser { fun parse(reader: TokenReader): ScriptNode { val statements = mutableListOf<StatementNode>() while (reader.token().type != Token.Type.EOF) { // Grammar: shebangLine? fileAnnotation* packageHeader importList (statement semi)* EOF // Note: Currently we only parse statements here. statements.add(reader.statement()) } return ScriptNode(statements) } } private fun TokenReader.statement(): StatementNode { // Grammar: (label | annotation)* (declaration | assignment | loopStatement | expression) return when { token().isDeclaration() -> declaration() else -> expression() } } private fun TokenReader.declaration(): StatementNode { // Grammar: classDeclaration | objectDeclaration | functionDeclaration | propertyDeclaration | typeAlias // Note: Currently we only support propertyDeclaration at this level. return when { token().isPropertyDeclaration() -> propertyDeclaration() else -> throw ParserException("Unknown declaration: ${token()}") } } private fun TokenReader.propertyDeclaration(): StatementNode { // Grammar: // : modifiers? ('val' | 'var') typeParameters? // (receiverType '.')? // (multiVariableDeclaration | variableDeclaration) // typeConstraints? // (('=' expression) | propertyDelegate)? ';'? // ((getter? (semi? setter)?) | (setter? (semi? getter)?)) // Note: We only support a small subset of the property declaration grammar here currently. val immutable = when (tokenAndProceed().type) { Token.Type.VAR -> false Token.Type.VAL -> true else -> throw ParserException("Expected beginning of property declaration.") } val identifier = tokenAndProceed(Token.Type.IDENTIFIER).value.toString() val type = if (token().type == Token.Type.COLON) { proceed() val typeIdentifier = tokenAndProceed(Token.Type.IDENTIFIER) Type.fromString(typeIdentifier.value.toString()) } else { Type.Unknown } val expression = if (checkTokenAndProceed(Token.Type.EQUAL)) { expression() } else { null } return PropertyDeclarationNode(immutable, identifier, type, expression) } private fun TokenReader.expression(): ExpressionNode { return disjunction() } private fun TokenReader.disjunction(): ExpressionNode { // conjunction ('||' conjunction)* var conjunction = conjunction() while (token().type == Token.Type.DISJUNCTION) { proceed() conjunction = DisjunctionNode(conjunction, conjunction()) } return conjunction } private fun TokenReader.conjunction(): ExpressionNode { // equality ('&&' equality)* var equality = equality() while (token().type == Token.Type.CONJUNCTION) { proceed() equality = ConjunctionNode(equality, equality()) } return equality } private fun TokenReader.equality(): ExpressionNode { // comparison (equalityOperator comparison)* var expression = comparison() while (token().isEqualityOperator()) { val equalityOperator = tokenAndProceed().value.toString() expression = EqualityNode(expression, equalityOperator, comparison()) } return expression } private fun TokenReader.comparison(): ExpressionNode { // genericCallLikeComparison (comparisonOperator genericCallLikeComparison)* return genericCallLikeComparison() } private fun TokenReader.genericCallLikeComparison(): ExpressionNode { // infixOperation callSuffix* val operation = infixOperation() when { token().isCallSuffix() -> return FunctionCallNode(operation, callSuffix()) } return operation } private fun TokenReader.callSuffix(): List<ExpressionNode> { // typeArguments? valueArguments? annotatedLambda // | typeArguments? valueArguments // Note: We ignore `typeArguments` and `annotatedLambda` for now. return valueArguments() } private fun TokenReader.valueArguments(): List<ExpressionNode> { tokenAndProceed(Token.Type.LEFT_PARENTHESIS) val arguments = mutableListOf<ExpressionNode>() while (token().type != Token.Type.RIGHT_PARENTHESIS && token().type != Token.Type.EOF) { if (arguments.isNotEmpty()) { tokenAndProceed(Token.Type.COMMA) } arguments.add(expression()) } tokenAndProceed(Token.Type.RIGHT_PARENTHESIS) return arguments } private fun TokenReader.infixOperation(): ExpressionNode { // Grammar: elvisExpression ((inOperator elvisExpression) | (isOperator type))* // Note: We shortcut to additiveExpression here. return additiveExpression() } private fun TokenReader.additiveExpression(): ExpressionNode { // Grammar: multiplicativeExpression (additiveOperator multiplicativeExpression)* var expression = multiplicativeExpression() while (token().isAdditiveOperator()) { val operator = tokenAndProceed() expression = BinaryOperation(expression, operator.value.toString(), multiplicativeExpression()) } return expression } private fun TokenReader.multiplicativeExpression(): ExpressionNode { // Grammar: asExpression (multiplicativeOperator asExpression)* var expression = asExpression() while (token().isMultiplicativeOperator()) { val operator = tokenAndProceed() expression = BinaryOperation(expression, operator.value.toString(), asExpression()) } return expression } private fun TokenReader.asExpression(): ExpressionNode { // Note: We shortcut to postfixUnaryExpression here. return postfixUnaryExpression() } private fun TokenReader.postfixUnaryExpression(): ExpressionNode { // : primaryExpression // | primaryExpression postfixUnarySuffix+ var expression = primaryExpression() while (token().isPostfixUnarySuffix()) { when { token().isMemberAccessOperator() -> { proceed() expression = MemberAccessNode(expression, identifier()) } } } return expression } private fun TokenReader.primaryExpression(): ExpressionNode { // : parenthesizedExpression // | simpleIdentifier // | literalConstant // | stringLiteral // | callableReference // | functionLiteral // | objectLiteral // | collectionLiteral // | thisExpression // | superExpression // | ifExpression // | whenExpression // | tryExpression // | jumpExpression return when { token().isLiteral() -> literal() checkTokenAndProceed(Token.Type.LEFT_PARENTHESIS) -> expression().also { assertAndProceed(Token.Type.RIGHT_PARENTHESIS) } else -> identifier() } } private fun TokenReader.literal(): LiteralNode { val token = tokenAndProceed() return when (token.type) { Token.Type.DOUBLE_LITERAL -> LiteralNode.DoubleLiteralNode(token.value as Double) Token.Type.FLOAT_LITERAL -> LiteralNode.FloatLiteralNode(token.value as Float) Token.Type.INTEGER_LITERAL -> LiteralNode.IntegerLiteralNode(token.value as Int) Token.Type.BOOLEAN_LITERAL -> LiteralNode.BooleanLiteralNode(token.value as Boolean) else -> throw ParserException("Expected literal. Got: $token") } } private fun TokenReader.identifier(): IdentifierNode { val token = tokenAndProceed(Token.Type.IDENTIFIER) return IdentifierNode(token.value.toString()) }
31.593548
129
0.708087
0a2c0ca31fc6f18e2388abe3e084b330c61d7473
2,596
rs
Rust
crates/traits/fold_bisect/src/lib.rs
rsk0315/library-rs
34ea62b18348f790890b1743e0b7b785c25cf50b
[ "MIT" ]
6
2020-10-26T13:37:55.000Z
2021-12-29T13:48:59.000Z
crates/traits/fold_bisect/src/lib.rs
rsk0315/library-rs
34ea62b18348f790890b1743e0b7b785c25cf50b
[ "MIT" ]
11
2020-10-18T05:16:02.000Z
2022-02-23T11:03:50.000Z
crates/traits/fold_bisect/src/lib.rs
rsk0315/library-rs
34ea62b18348f790890b1743e0b7b785c25cf50b
[ "MIT" ]
null
null
null
//! 区間和の二分探索に関するトレイトたち。 //! //! 区間のモノイド積が述語を満たすような区間のうち、最大のものを返す。 use std::ops::Range; use binop::Magma; use fold::Fold; /// 左端を固定したときの境界を求める。 pub trait FoldBisect: Fold<Range<usize>> { /// 添字 `l` と述語 `pred` を引数に取り、次の条件を満たす `r` を返す。 /// ただし、区間長を `n` とする。 /// - `pred(&self.fold(l..r))` /// - `r == n || !pred(&self.fold(l..r + 1))` /// /// # Requirements /// 対象のモノイドの単位元を `e` とするとき、 `pred(e)` が成り立つ。 /// /// # Examples /// ``` /// use nekolib::ds::VecSegtree; /// use nekolib::traits::{Fold, FoldBisect}; /// use nekolib::utils::OpAdd; /// /// let vs: VecSegtree<OpAdd<i32>> = vec![2, 4, 1, 3, 5].into(); /// /// assert_eq!(vs.fold_bisect(1, |&x| x < 4), (1_usize, 0)); /// assert_eq!(vs.fold_bisect(1, |&x| x <= 4), (2_usize, 4)); /// assert_eq!(vs.fold_bisect(1, |&x| x < 13), (4_usize, 8)); /// assert_eq!(vs.fold_bisect(1, |&x| x <= 13), (5_usize, 13)); /// /// let l = 1; /// let pred = |&x: &i32| x <= 12; /// let (r, x) = vs.fold_bisect(l, pred); /// assert_eq!(vs.fold(l..r), x); /// assert!(pred(&x)); /// assert!(r == vs.len() || !pred(&vs.fold(l..r + 1))); /// ``` fn fold_bisect<F>( &self, l: usize, pred: F, ) -> (usize, <Self::Output as Magma>::Set) where F: Fn(&<Self::Output as Magma>::Set) -> bool; } /// 右端を固定したときの境界を求める。 pub trait FoldBisectRev: Fold<Range<usize>> { /// 添字 `r` と述語 `pred` を引数に取り、次の条件を満たす `l` を返す。 /// - `pred(&self.fold(l..r))` /// - `l == 0 || !pred(&self.fold(l - 1..r))` /// /// # Requirements /// 対象のモノイドの単位元を `e` とするとき、`pred(e)` が成り立つ。 /// /// # Examples /// ``` /// use nekolib::ds::VecSegtree; /// use nekolib::traits::{Fold, FoldBisectRev}; /// use nekolib::utils::OpAdd; /// /// let vs: VecSegtree<OpAdd<i32>> = vec![2, 4, 1, 3, 5].into(); /// /// assert_eq!(vs.fold(..), 15); /// assert_eq!(vs.fold_bisect_rev(5, |&x| x <= 0), (5_usize, 0)); /// assert_eq!(vs.fold_bisect_rev(5, |&x| x < 15), (1_usize, 13)); /// assert_eq!(vs.fold_bisect_rev(5, |&x| x <= 15), (0_usize, 15)); /// /// let r = 5; /// let pred = |&x: &i32| x <= 12; /// let (l, x) = vs.fold_bisect_rev(r, pred); /// assert_eq!(vs.fold(l..r), x); /// assert!(pred(&x)); /// assert!(l == 0 || !pred(&vs.fold(l - 1..r))); /// ``` fn fold_bisect_rev<F>( &self, r: usize, pred: F, ) -> (usize, <Self::Output as Magma>::Set) where F: Fn(&<Self::Output as Magma>::Set) -> bool; }
30.186047
71
0.489214
a15bb6cf9025d3cb79c9bb4bdb639f28cf7f328c
302
asm
Assembly
src/asm/boot-sect0.asm
geenvenstersos/tinu-tom-OS
b73e7a77baf9ae5601a5d2e413df4981141e97e0
[ "MIT" ]
null
null
null
src/asm/boot-sect0.asm
geenvenstersos/tinu-tom-OS
b73e7a77baf9ae5601a5d2e413df4981141e97e0
[ "MIT" ]
null
null
null
src/asm/boot-sect0.asm
geenvenstersos/tinu-tom-OS
b73e7a77baf9ae5601a5d2e413df4981141e97e0
[ "MIT" ]
null
null
null
mov ah, 0x0e mov al , 'H' int 0x10 mov al , 'E' int 0x10 mov al , 'L' int 0x10 mov al , 'L' int 0x10 mov al , 'O' int 0x10 mov al , ' ' int 0x10 mov al , 'W' int 0x10 mov al , 'O' int 0x10 mov al , 'R' int 0x10 mov al , 'L' int 0x10 mov al , 'D' int 0x10 jmp $ times 510-($-$$) db 0 dw 0xaa55
8.388889
21
0.572848
606159c6a13649f339c58ca515a20e28db242845
16,650
c
C
src/iqa/test/source/test_ssim.c
tssajo/archive2webp
09d47e59418a003f4cabd148d638944f38928b4f
[ "W3C", "MIT" ]
null
null
null
src/iqa/test/source/test_ssim.c
tssajo/archive2webp
09d47e59418a003f4cabd148d638944f38928b4f
[ "W3C", "MIT" ]
null
null
null
src/iqa/test/source/test_ssim.c
tssajo/archive2webp
09d47e59418a003f4cabd148d638944f38928b4f
[ "W3C", "MIT" ]
null
null
null
/* * Copyright (c) 2011, Tom Distler (http://tdistler.com) * All rights reserved. * * The BSD License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the tdistler.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "test_ssim.h" #include "iqa.h" #include "convolve.h" #include "bmp.h" #include "hptime.h" #include "math_utils.h" #include <stdio.h> #include <string.h> static const int img_width = 22; static const int img_height = 15; static const int img_stride = 23; static const unsigned char img_22x15[] = { 27, 25, 83, 56, 139, 147, 119, 153, 147, 132, 113, 147, 160, 163, 169, 151, 148, 120, 113, 149, 132, 145, 0, 0, 0, 25, 25, 73, 49, 148, 145, 126, 127, 113, 110, 116, 102, 99, 118, 161, 149, 149, 129, 114, 137, 0, 136, 154, 0, 0, 24, 29, 76, 63, 143, 137, 114, 117, 116, 117, 147, 142, 119, 98, 163, 139, 147, 137, 0, 114, 117, 141, 147, 0, 0, 23, 23, 66, 51, 144, 144, 102, 95, 104, 130, 147, 161, 129, 125, 85, 131, 0, 97, 111, 119, 107, 132, 144, 0, 0, 24, 26, 36, 104, 135, 147, 110, 136, 101, 163, 170, 172, 150, 124, 0, 122, 135, 118, 85, 116, 120, 136, 147, 0, 0, 24, 21, 30, 51, 148, 151, 120, 33, 66, 79, 164, 95, 0, 50, 132, 130, 76, 117, 142, 120, 130, 137, 143, 0, 0, 25, 24, 48, 50, 147, 150, 145, 43, 120, 147, 0, 170, 136, 169, 155, 105, 132, 43, 118, 120, 143, 141, 153, 0, 0, 23, 23, 44, 46, 144, 158, 135, 149, 0, 110, 94, 122, 114, 149, 136, 74, 57, 92, 104, 99, 149, 166, 166, 0, 0, 25, 27, 61, 46, 143, 163, 0, 137, 151, 132, 64, 163, 174, 145, 74, 205, 91, 101, 88, 94, 95, 97, 95, 0, 0, 21, 26, 150, 39, 0, 149, 75, 89, 108, 111, 98, 19, 21, 80, 229, 26, 94, 100, 102, 106, 94, 110, 101, 0, 0, 21, 24, 0, 161, 38, 99, 110, 95, 112, 126, 94, 89, 63, 108, 228, 119, 111, 102, 99, 97, 105, 83, 99, 0, 0, 0, 24, 21, 155, 81, 112, 93, 71, 104, 111, 95, 111, 235, 64, 228, 105, 110, 113, 108, 98, 105, 112, 112, 0, 0, 0, 23, 20, 61, 92, 91, 69, 74, 107, 97, 98, 99, 117, 66, 92, 104, 104, 106, 106, 101, 74, 0, 86, 83, 0, 0, 21, 88, 83, 92, 95, 86, 94, 93, 86, 111, 98, 106, 86, 118, 110, 108, 113, 107, 0, }; static float lpf_linear_2x2[] = { 0.25f, 0.25f, 0.25f, 0.25f, }; static const struct iqa_ssim_args ssim_args = { 0.39f, /* alpha */ 0.731f, /* beta */ 1.12f, /* gamma */ 187, /* L */ 0.025987f, /* K1 */ 0.0173f, /* K2 */ 1 /* factor */ }; /* Defines the answer format */ struct answer { float value; /**< Expected result */ int precision; /**< Digits of precision */ }; static const struct answer ans_key_22x15_gauss[] = { {1.00000f, 5}, /* Identical */ {0.99668f, 5}, /* Mean Shift +7 */ {0.68944f, 5}, /* 2x2 low-pass filter */ }; static const struct answer ans_key_22x15_linear[] = { {1.00000f, 5}, /* Identical */ {0.99737f, 5}, /* Mean Shift +7 */ {0.71679f, 5}, /* 2x2 low-pass filter */ }; static const struct answer ans_key_22x15_args[] = { {1.00000f, 5}, /* Identical */ {0.99870f, 5}, /* Mean Shift +7 */ {0.67986f, 5}, /* 2x2 low-pass filter */ }; static const struct answer ans_key_einstein_gauss[] = { {1.00000f, 5}, /* Identical */ {0.69408f, 5}, /* Blur */ {0.91327f, 5}, /* Contrast */ {0.28771f, 5}, /* Flip Vertical */ {0.83957f, 5}, /* Impulse */ {0.66246f, 5}, /* JPEG */ {0.98836f, 5}, /* Mean Shift */ }; static const struct answer ans_key_einstein_linear[] = { {1.00000f, 5}, /* Identical */ {0.72422f, 5}, /* Blur */ {0.91273f, 5}, /* Contrast */ {0.25001f, 5}, /* Flip Vertical */ {0.82213f, 5}, /* Impulse */ {0.68550f, 5}, /* JPEG */ {0.98845f, 5}, /* Mean Shift */ }; /* NOTE: Values verified. Different from Octave due to float precision. */ static const struct answer ans_key_einstein_args[] = { {1.00000f, 5}, /* Identical */ {0.56509f, 5}, /* Blur */ {0.94412f, 5}, /* Contrast */ {0.13106f, 5}, /* Flip Vertical */ {0.81263f, 5}, /* Impulse */ {0.50202f, 4}, /* JPEG (rounding error on 64-bit)*/ {0.99542f, 5}, /* Mean Shift */ }; static const struct answer ans_key_courtright[] = { {1.00000f, 5}, /* Identical */ {0.74989f, 2}, /* Noise (rounding error) */ }; #define BMP_ORIGINAL "einstein.bmp" #define BMP_BLUR "blur.bmp" #define BMP_CONTRAST "contrast.bmp" #define BMP_FLIPVERT "flipvertical.bmp" #define BMP_IMPULSE "impulse.bmp" #define BMP_JPG "jpg.bmp" #define BMP_MEANSHIFT "meanshift.bmp" #define BMP_CR_ORIGINAL "Courtright.bmp" #define BMP_CR_NOISE "Courtright_Noise.bmp" static int _test_ssim_22x15(int gaussian, const struct answer *answers, const struct iqa_ssim_args *args); static int _test_ssim_einstein_bmp(int gaussian, const struct answer *answers, const struct iqa_ssim_args *args); static int _test_ssim_courtright_bmp(int gaussian, const struct answer *answers, const struct iqa_ssim_args *args); /*---------------------------------------------------------------------------- * TEST ENTRY POINT *---------------------------------------------------------------------------*/ int test_ssim() { int failure = 0; printf("\nSSIM:\n"); failure += _test_ssim_22x15(1, ans_key_22x15_gauss, 0); failure += _test_ssim_22x15(0, ans_key_22x15_linear, 0); failure += _test_ssim_22x15(1, ans_key_22x15_args, &ssim_args); failure += _test_ssim_einstein_bmp(1, ans_key_einstein_gauss, 0); failure += _test_ssim_einstein_bmp(0, ans_key_einstein_linear, 0); failure += _test_ssim_einstein_bmp(1, ans_key_einstein_args, &ssim_args); failure += _test_ssim_courtright_bmp(1, ans_key_courtright, 0); return failure; } /*---------------------------------------------------------------------------- * _test_ssim_22x15 *---------------------------------------------------------------------------*/ int _test_ssim_22x15(int gaussian, const struct answer *answers, const struct iqa_ssim_args *args) { int x,y; int passed, failures=0; float result; unsigned long long start, end; unsigned char img_tmp[sizeof(img_22x15)]; float img_tmp_f[sizeof(img_22x15)]; struct _kernel lpf; printf("\t22x15 Image (%s%s):\n", gaussian?"Gaussian":"Linear",args?" - Custom Args":""); printf("\t Identical: "); memcpy(img_tmp, img_22x15, sizeof(img_22x15)); start = hpt_get_time(); result = iqa_ssim(img_22x15, img_tmp, img_width, img_height, img_stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[0].value, answers[0].precision) ? 0 : 1; printf("\t\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; printf("\t Mean-shifted +7: "); memcpy(img_tmp, img_22x15, sizeof(img_22x15)); for (y=0; y < img_height; ++y) { for (x=0; x < img_width; ++x) { img_tmp[y*img_stride+x] += 7; } } start = hpt_get_time(); result = iqa_ssim(img_22x15, img_tmp, img_width, img_height, img_stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[1].value, answers[1].precision) ? 0 : 1; printf("\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; printf("\t 2x2 linear low-pass: "); lpf.kernel = lpf_linear_2x2; lpf.w = lpf.h = 2; lpf.normalized = 1; lpf.bnd_opt = KBND_SYMMETRIC; for (y=0; y < img_height; ++y) { for (x=0; x < img_width; ++x) { img_tmp_f[y*img_width+x] = (float)img_22x15[y*img_stride+x]; } } if (_iqa_img_filter(img_tmp_f, img_width, img_height, &lpf, 0)) { printf("FAILED\n"); failures++; } else { for (y=0; y < img_height; ++y) { for (x=0; x < img_width; ++x) { img_tmp[y*img_stride+x] = (unsigned char)_round(img_tmp_f[y*img_width+x]); } } start = hpt_get_time(); result = iqa_ssim(img_22x15, img_tmp, img_width, img_height, img_stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[2].value, answers[2].precision) ? 0 : 1; printf("\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; } return failures; } /*---------------------------------------------------------------------------- * _test_ssim_einstein_bmp *---------------------------------------------------------------------------*/ int _test_ssim_einstein_bmp(int gaussian, const struct answer *answers, const struct iqa_ssim_args *args) { struct bmp orig, cmp; int passed, failures=0; float result; unsigned long long start, end; printf("\tEinstein (%s%s):\n", gaussian?"Gaussian":"Linear",args?" - Custom Args":""); if (load_bmp(BMP_ORIGINAL, &orig)) { printf("FAILED to load \'%s\'\n", BMP_ORIGINAL); return 1; } printf("\t Identical: "); start = hpt_get_time(); result = iqa_ssim(orig.img, orig.img, orig.w, orig.h, orig.stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[0].value, answers[0].precision) ? 0 : 1; printf("\t\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; printf("\t Blur: "); if (load_bmp(BMP_BLUR, &cmp)) { printf("FAILED to load \'%s\'\n", BMP_BLUR); failures++; } else { start = hpt_get_time(); result = iqa_ssim(orig.img, cmp.img, orig.w, orig.h, orig.stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[1].value, answers[1].precision) ? 0 : 1; printf("\t\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; free_bmp(&cmp); } printf("\t Contrast: "); if (load_bmp(BMP_CONTRAST, &cmp)) { printf("FAILED to load \'%s\'\n", BMP_CONTRAST); failures++; } else { start = hpt_get_time(); result = iqa_ssim(orig.img, cmp.img, orig.w, orig.h, orig.stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[2].value, answers[2].precision) ? 0 : 1; printf("\t\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; free_bmp(&cmp); } printf("\t Flip Vertical: "); if (load_bmp(BMP_FLIPVERT, &cmp)) { printf("FAILED to load \'%s\'\n", BMP_FLIPVERT); failures++; } else { start = hpt_get_time(); result = iqa_ssim(orig.img, cmp.img, orig.w, orig.h, orig.stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[3].value, answers[3].precision) ? 0 : 1; printf("\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; free_bmp(&cmp); } printf("\t Impulse: "); if (load_bmp(BMP_IMPULSE, &cmp)) { printf("FAILED to load \'%s\'\n", BMP_IMPULSE); failures++; } else { start = hpt_get_time(); result = iqa_ssim(orig.img, cmp.img, orig.w, orig.h, orig.stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[4].value, answers[4].precision) ? 0 : 1; printf("\t\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; free_bmp(&cmp); } printf("\t Jpeg: "); if (load_bmp(BMP_JPG, &cmp)) { printf("FAILED to load \'%s\'\n", BMP_JPG); failures++; } else { start = hpt_get_time(); result = iqa_ssim(orig.img, cmp.img, orig.w, orig.h, orig.stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[5].value, answers[5].precision) ? 0 : 1; printf("\t\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; free_bmp(&cmp); } printf("\t Meanshift: "); if (load_bmp(BMP_MEANSHIFT, &cmp)) { printf("FAILED to load \'%s\'\n", BMP_MEANSHIFT); failures++; } else { start = hpt_get_time(); result = iqa_ssim(orig.img, cmp.img, orig.w, orig.h, orig.stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[6].value, answers[6].precision) ? 0 : 1; printf("\t\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; free_bmp(&cmp); } free_bmp(&orig); return failures; } /*---------------------------------------------------------------------------- * _test_ssim_courtright_bmp *---------------------------------------------------------------------------*/ int _test_ssim_courtright_bmp(int gaussian, const struct answer *answers, const struct iqa_ssim_args *args) { struct bmp orig, cmp; int passed, failures=0; float result; unsigned long long start, end; printf("\tCourtright (%s%s):\n", gaussian?"Gaussian":"Linear",args?" - Custom Args":""); if (load_bmp(BMP_CR_ORIGINAL, &orig)) { printf("FAILED to load \'%s\'\n", BMP_CR_ORIGINAL); return 1; } printf("\t Identical: "); start = hpt_get_time(); result = iqa_ssim(orig.img, orig.img, orig.w, orig.h, orig.stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[0].value, answers[0].precision) ? 0 : 1; printf("\t\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; printf("\t Noise: "); if (load_bmp(BMP_CR_NOISE, &cmp)) { printf("FAILED to load \'%s\'\n", BMP_CR_NOISE); failures++; } else { start = hpt_get_time(); result = iqa_ssim(orig.img, cmp.img, orig.w, orig.h, orig.stride, gaussian, args); end = hpt_get_time(); passed = _cmp_float(result, answers[1].value, answers[1].precision) ? 0 : 1; printf("\t\t%.5f (%.3lf ms)\t%s\n", result, hpt_elapsed_time(start,end,hpt_get_frequency()) * 1000.0, passed?"PASS":"FAILED"); failures += passed?0:1; free_bmp(&cmp); } free_bmp(&orig); return failures; }
37.58465
115
0.572853
ffbb48584e60d6cc61869e5a032d3006921f8054
298
py
Python
_TEMPLATE/tests/unit_tests/test_version.py
realead/pyproj_maker
2846a02855a0b612fda4973544221dcbcb02e4ac
[ "MIT" ]
1
2020-01-12T07:15:52.000Z
2020-01-12T07:15:52.000Z
_TEMPLATE/tests/unit_tests/test_version.py
realead/pyproj_maker
2846a02855a0b612fda4973544221dcbcb02e4ac
[ "MIT" ]
null
null
null
_TEMPLATE/tests/unit_tests/test_version.py
realead/pyproj_maker
2846a02855a0b612fda4973544221dcbcb02e4ac
[ "MIT" ]
null
null
null
import unittest import {name} class VersionTester(unittest.TestCase): def test_major(self): self.assertEqual({name}.__version__[0], 0) def test_minor(self): self.assertEqual({name}.__version__[1], 1) def test_last(self): self.assertEqual({name}.__version__[2], 0)
18.625
48
0.684564
799adeb2f93f47f86a09869c28f51538cf4c74e3
185
php
PHP
tests/data/SimpleWithNoClassCest.php
BearerPipelineTest/Codeception
df7b3c38d4522c766cd76dd85e77c3ebb444cf7b
[ "MIT" ]
null
null
null
tests/data/SimpleWithNoClassCest.php
BearerPipelineTest/Codeception
df7b3c38d4522c766cd76dd85e77c3ebb444cf7b
[ "MIT" ]
null
null
null
tests/data/SimpleWithNoClassCest.php
BearerPipelineTest/Codeception
df7b3c38d4522c766cd76dd85e77c3ebb444cf7b
[ "MIT" ]
null
null
null
<?php class SimpleWithNoClassCest { public function phpFunctions(CodeGuy $I) { $I->execute(fn () => strtoupper('hello')); $I->seeResultEquals('HELLO'); } }
16.818182
50
0.589189
3f642c5da3b334a2da7b4fb6d7f2d6cab55e5221
2,665
php
PHP
app/Http/Controllers/CartController.php
Duy912555/WebBanHang
91601b66adca495b01803e35112bba7455a6b7fb
[ "MIT" ]
null
null
null
app/Http/Controllers/CartController.php
Duy912555/WebBanHang
91601b66adca495b01803e35112bba7455a6b7fb
[ "MIT" ]
null
null
null
app/Http/Controllers/CartController.php
Duy912555/WebBanHang
91601b66adca495b01803e35112bba7455a6b7fb
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Cart; use App\Models\Products; use App\Models\Customer; use App\Models\Orders; use App\Models\Order_detail; use DateTime; class CartController extends Controller { public function getAddCart($id){ $product = Products::find($id); if($product->promotion_price > 0){ Cart::instance('cart')->add(['id' => $id, 'name' => $product->name, 'qty' => 1, 'price' => $product->promotion_price, 'weight' => 550, 'options' => ['image' => $product->image, 'unit' => $product->unit]]); } else{ Cart::instance('cart')->add(['id' => $id, 'name' => $product->name, 'qty' => 1, 'price' => $product->unit_price, 'weight' => 550, 'options' => ['image' => $product->image, 'unit' => $product->unit]]); } return redirect('cart/show'); } public function getShowCart(){ $data['product'] = Cart::instance('cart')->content(); $data['total'] = Cart::instance('cart')->subtotal(); return view('page.cart', $data); } public function getDeleteCart($id){ Cart::instance('cart')->remove($id); return back(); } public function getUpdateCart(Request $request){ Cart::instance('cart')->update($request->rowId, $request->qty); } public function getCheckout(){ $total = Cart::instance('cart')->subtotal(); return view('page.checkout', compact('total')); } public function postCheckout(Request $request){ $cart = Cart::instance('cart')->content(); $customer = new Customer; $customer->name = $request->name; $customer->gender = $request->gender; $customer->email = $request->email; $customer->address = $request->address; $customer->phonenumber = $request->phone; $customer->note = $request->note; $customer->save(); $order = new Orders; $order->id_customer = $customer->id; $order->date_order = date('Y-m-d'); $order->total = Cart::instance('cart')->subtotal(); $order->payment = $request->payment_method; $order->note = $request->note; $order->save(); foreach($cart as $value){ $order_detail = new Order_detail; $order_detail->id_order = $order->id; $order_detail->id_product = $value->id; $order_detail->quantity = $value->qty; $order_detail->unit_price = $value->price; $order_detail->save(); } Cart::instance('cart')->destroy(); return redirect()->back()->with('thongbao','Đặt hàng thành công'); } }
33.3125
217
0.572983
e77397a6f703aab482d51578e804e0a787acdb1d
2,978
php
PHP
vt-member/library/Am/Grid/Action/Sort/CustomField.php
neeraj24a/8str
78c8c32740df796e1b360dc89a3f687690252fff
[ "BSD-3-Clause" ]
null
null
null
vt-member/library/Am/Grid/Action/Sort/CustomField.php
neeraj24a/8str
78c8c32740df796e1b360dc89a3f687690252fff
[ "BSD-3-Clause" ]
null
null
null
vt-member/library/Am/Grid/Action/Sort/CustomField.php
neeraj24a/8str
78c8c32740df796e1b360dc89a3f687690252fff
[ "BSD-3-Clause" ]
null
null
null
<?php class Am_Grid_Action_Sort_CustomField extends Am_Grid_Action_Sort_Abstract { protected $privilege = null, $table; public function setTable($table) { $this->table = $table->getName(true); } protected function getRecordParams($obj) { return array( 'id' => $obj->name, ); } protected function setSortBetween($item, $after, $before) { $after = $after ? $after['id'] : null; $before = $before ? $before['id'] : null; $id = $item['id']; $db = Am_Di::getInstance()->db; $item = $db->selectRow("SELECT * FROM ?_custom_field_sort WHERE custom_field_name=? AND custom_field_table=? ", $id, $this->table); if ($before) { $beforeItem = $db->selectRow("SELECT * FROM ?_custom_field_sort WHERE custom_field_name=? AND custom_field_table=? ", $before, $this->table); $sign = $beforeItem['sort_order'] > $item['sort_order'] ? '-': '+'; $newSortOrder = $beforeItem['sort_order'] > $item['sort_order'] ? $beforeItem['sort_order']-1: $beforeItem['sort_order']; $db->query("UPDATE ?_custom_field_sort SET sort_order=sort_order{$sign}1 WHERE sort_order BETWEEN ? AND ? AND custom_field_name<>? AND custom_field_table=?", min($newSortOrder, $item['sort_order']), max($newSortOrder, $item['sort_order']), $id, $this->table); $db->query("UPDATE ?_custom_field_sort SET sort_order=? WHERE custom_field_name=? AND custom_field_table=?", $newSortOrder, $id, $this->table); } elseif ($after) { $afterItem = $db->selectRow("SELECT * FROM ?_custom_field_sort WHERE custom_field_name=? AND custom_field_table=? ", $after, $this->table); $sign = $afterItem['sort_order'] > $item['sort_order'] ? '-': '+'; $newSortOrder = $afterItem['sort_order'] > $item['sort_order'] ? $afterItem['sort_order']: $afterItem['sort_order']+1; $db->query("UPDATE ?_custom_field_sort SET sort_order=sort_order{$sign}1 WHERE sort_order BETWEEN ? AND ? AND custom_field_name<>? AND custom_field_table=?", min($newSortOrder, $item['sort_order']), max($newSortOrder, $item['sort_order']), $id, $this->table); $db->query("UPDATE ?_custom_field_sort SET sort_order=? WHERE custom_field_name=? AND custom_field_table=?", $newSortOrder, $id, $this->table); } } }
33.840909
77
0.506716
2dff3388c4a0b537bc2b43c379ebfb4190366657
6,255
cpp
C++
Visual Mercutio/zWinUtil32/PSS_CreateFolderWizard.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zWinUtil32/PSS_CreateFolderWizard.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zWinUtil32/PSS_CreateFolderWizard.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_CreateFolderWizard ----------------------------------------------* **************************************************************************** * Description : Provides a create folder Wizard * * Developer : Processsoft * ****************************************************************************/ #include "stdafx.h" #include "PSS_CreateFolderWizard.h" // processsoft #include "zBaseLib\PSS_File.h" #include "PSS_CreateFolderWizardStartDialog.h" #include "PSS_CreateFolderWizardExistDialog.h" #include "PSS_OpenDirDialog.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif //--------------------------------------------------------------------------- // PSS_CreateFolderWizardDialog //--------------------------------------------------------------------------- PSS_CreateFolderWizard::PSS_CreateFolderWizard(BOOL useFolderNameAsFileName, const CString& fileDirectory, const CString& fileExtension, const CString& folderName, const CString& folderDescription) : m_FileDirectory(fileDirectory), m_FolderName(folderName), m_FolderDescription(folderDescription), m_FileExtension(fileExtension), m_UseFolderNameAsFileName(useFolderNameAsFileName) {} //--------------------------------------------------------------------------- PSS_CreateFolderWizard::~PSS_CreateFolderWizard() {} //--------------------------------------------------------------------------- BOOL PSS_CreateFolderWizard::Execute() { PSS_CreateFolderWizardStartDialog createFolderWizardStart(m_UseFolderNameAsFileName, m_FileDirectory, m_FolderName, m_FolderDescription, "", m_FileExtension); if (createFolderWizardStart.DoModal() == IDCANCEL) return FALSE; // if the file directory is empty, get it if (m_FileDirectory.IsEmpty()) { PSS_OpenDirDialog openDirDlg(IDS_CHOOSEDIRECTORYFORFOLDER); m_FileDirectory = openDirDlg.ProcessDirectory(); if (m_FileDirectory.IsEmpty()) return FALSE; } // check if the file name already exists m_FolderName = createFolderWizardStart.GetFolderName(); // create empty file name CString fileName; if (!m_UseFolderNameAsFileName) fileName = createFolderWizardStart.GetFileName(); PSS_CreateFolderWizardExistDialog::IEFolderExistInitialChoice initialChoice = PSS_CreateFolderWizardExistDialog::IE_FC_FolderName; while (CheckFolderExist(fileName)) if (m_UseFolderNameAsFileName) { PSS_CreateFolderWizardExistDialog createFolderWizardExist(m_FolderName, m_FileDirectory, m_CompleteFileName, initialChoice); if (createFolderWizardExist.DoModal() == IDCANCEL) return FALSE; if (createFolderWizardExist.IsFolderNameSelected()) { // assign the new folder name m_FolderName = createFolderWizardExist.GetFolderName(); // empty the file name fileName.Empty(); // keep choice for next use initialChoice = PSS_CreateFolderWizardExistDialog::IE_FC_FolderName; } else if (createFolderWizardExist.IsDirectorySelected()) { // assign the new directory m_FileDirectory = createFolderWizardExist.GetFileDirectory(); // empty the file name fileName.Empty(); // keep choice for next use initialChoice = PSS_CreateFolderWizardExistDialog::IE_FC_Directory; } else if (createFolderWizardExist.IsFileNameSelected()) { // assign the new file name fileName = createFolderWizardExist.GetFileName(); // keep choice for next use initialChoice = PSS_CreateFolderWizardExistDialog::IE_FC_FileName; } else if (createFolderWizardExist.IsReWriteSelected()) break; } else { PSS_CreateFolderWizardStartDialog correctCreateFolderWizardStart(m_UseFolderNameAsFileName, m_FileDirectory, m_FolderName, m_FolderDescription, fileName, m_FileExtension); if (correctCreateFolderWizardStart.DoModal() == IDCANCEL) return FALSE; // assign the new file name fileName = correctCreateFolderWizardStart.GetFileName(); } return TRUE; } //--------------------------------------------------------------------------- BOOL PSS_CreateFolderWizard::CheckFolderExist(const CString& fileName) { // build the complete file name if (fileName.IsEmpty()) m_CompleteFileName = m_FileDirectory + "\\" + m_FolderName + "." + m_FileExtension; else m_CompleteFileName = fileName; PSS_File file(m_CompleteFileName); return file.Exist(); } //---------------------------------------------------------------------------
40.882353
103
0.466347
a440c665b48d9b0bb066d20bf43749a5b2131c6b
375
php
PHP
resources/views/student/student_side_nav.blade.php
NdagiStanley/student-planet
c7963ceea11c8aa76a934578b7708669cabe2598
[ "MIT" ]
1
2019-02-18T08:41:56.000Z
2019-02-18T08:41:56.000Z
resources/views/student/student_side_nav.blade.php
NdagiStanley/student-planet
c7963ceea11c8aa76a934578b7708669cabe2598
[ "MIT" ]
2
2017-11-02T18:18:44.000Z
2018-05-10T17:40:01.000Z
resources/views/student/student_side_nav.blade.php
NdagiStanley/student-planet
c7963ceea11c8aa76a934578b7708669cabe2598
[ "MIT" ]
null
null
null
<ul class="list-group"> <li class="list-group-item{{ url()->current() == route('new_project') ? ' active': '' }}"> <a href="{{ route('new_project') }}">Add New Project</a> </li> <li class="list-group-item{{ url()->current() == route('profile_update') ? ' active': '' }}"> <a href="{{ route('profile_update') }}">Update Profile</a> </li> </ul>
41.666667
97
0.538667
457733343cca642cbffbb70a0e251eea64564f12
112
py
Python
tcsdk/api/performance/__init__.py
tsbxmw/tcsdk
fb4042cdece83f681a9057ff36ca09954988a31d
[ "MIT" ]
1
2019-12-04T09:30:06.000Z
2019-12-04T09:30:06.000Z
tcsdk/api/performance/__init__.py
tsbxmw/tcsdk
fb4042cdece83f681a9057ff36ca09954988a31d
[ "MIT" ]
null
null
null
tcsdk/api/performance/__init__.py
tsbxmw/tcsdk
fb4042cdece83f681a9057ff36ca09954988a31d
[ "MIT" ]
null
null
null
from .performance import PerformanceApi, Task, Label PerformanceApi = PerformanceApi Task = Task Label = Label
18.666667
52
0.803571
45a31a0fe5c885df739a26b05bf62bdb598b4203
3,710
py
Python
score_binary_classification.py
DanCunnington/CSV2FastLAS
56f74724d03d8b2c968590c7c0436d8ace8034e8
[ "Apache-2.0" ]
null
null
null
score_binary_classification.py
DanCunnington/CSV2FastLAS
56f74724d03d8b2c968590c7c0436d8ace8034e8
[ "Apache-2.0" ]
null
null
null
score_binary_classification.py
DanCunnington/CSV2FastLAS
56f74724d03d8b2c968590c7c0436d8ace8034e8
[ "Apache-2.0" ]
null
null
null
import argparse import re def main(args): learned_hyp_file_path = args.learned_hyp_file test_examples_path = args.test_examples predictor_pos_value = args.predictor_positive_value # Take in learned hypothesis, test las file and generate F1 score and accuracy # over the test examples. learned_hyp_file = open(learned_hyp_file_path, "r").read() test_examples_file = open(test_examples_path, "r").read().split("% Background Knowledge")[0].split("% Examples")[1] # Extract examples using RegEX r_str = '(#pos\(.*, {)(((\s*)+[^\)|\}]+\)\.)+)' matches = re.findall(r_str, test_examples_file) positive_examples = [] negative_examples = [] for m in matches: pos_or_neg_str = m[0].split(',') features_and_values = m[1] # Remove whitespace r_str = re.compile(r'\s+') features_and_values = re.sub(r_str, '', features_and_values).split('.') example = {} for fv in features_and_values: if fv != '': feature = fv.split('(')[0] value = fv.split('(')[1].split(')')[0] example[feature] = value if predictor_pos_value in pos_or_neg_str[1]: positive_examples.append(example) else: negative_examples.append(example) # Build rules rules_for_accept = [] r_str = '(attack :- )([^\.]+)' matches = re.findall(r_str, learned_hyp_file) for rule in matches: to_check = {} features_and_values = rule[1].split(', ') for fv in features_and_values: feature = fv.split('(')[0] value = fv.split('(')[1].split(')')[0] to_check[feature] = value rules_for_accept.append(to_check) # For each positive example, compute prediction based on rules for accept def calculate_results(examples): predictions = [] for ex in examples: rule_results = [] for r in rules_for_accept: rule_fail = False for idx,k in enumerate(r): target = r[k] if ex[k] != target: rule_fail = True rule_results.append(not rule_fail) # If any results are true, this means accept predictions.append(any(rule_results)) return predictions positive_predictions = calculate_results(positive_examples) negative_predictions = calculate_results(negative_examples) # Calculate F1 Score tp = sum(positive_predictions) fn = len(positive_predictions) - tp fp = sum(negative_predictions) tn = len(negative_predictions) - fp precision = tp / (tp + fp) recall = tp / (tp + fn) f1 = 2 * ((precision*recall) / (precision + recall)) # Calculate Accuracy accuracy = (tp + tn) / (tp + tn + fp + fn) print('Number of Positive Examples: ', len(positive_examples)) print('Number of Negative Examples: ', len(negative_examples)) print('Precision: ', precision) print('Recall: ', recall) print('F1 Score: ', f1) print('Accuracy: ', accuracy) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Score a learned hypothesis over test examples') parser.add_argument('learned_hyp_file', help='The learned hypothesis file to score against') parser.add_argument('test_examples', help='The .las file containing the test examples') parser.add_argument('--predictor_positive_value', help='The value of the predictor for a positive class in binary classification (default: accept).', default='accept') args = parser.parse_args() main(args)
35
119
0.612129
da2f1e03657e3207ce82fef190b9f4ba0c51ae07
1,727
cs
C#
src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducer.cs
damonsiusta/Brighter
5a0d4db5af4a53604f4d0395c2ad4ad9cb5bc46c
[ "MIT" ]
null
null
null
src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducer.cs
damonsiusta/Brighter
5a0d4db5af4a53604f4d0395c2ad4ad9cb5bc46c
[ "MIT" ]
null
null
null
src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducer.cs
damonsiusta/Brighter
5a0d4db5af4a53604f4d0395c2ad4ad9cb5bc46c
[ "MIT" ]
null
null
null
using System; using System.Threading.Tasks; using Paramore.Brighter.Logging; using Paramore.Brighter.MessagingGateway.MsSql.SqlQueues; namespace Paramore.Brighter.MessagingGateway.MsSql { public class MsSqlMessageProducer : IAmAMessageProducer, IAmAMessageProducerAsync { private static readonly Lazy<ILog> Logger = new Lazy<ILog>(LogProvider.For<MsSqlMessageProducer>); private readonly MsSqlMessageQueue<Message> _sqlQ; private Publication _publication; // -- placeholder for future use public MsSqlMessageProducer( MsSqlMessagingGatewayConfiguration msSqlMessagingGatewayConfiguration, Publication publication = null) { _sqlQ = new MsSqlMessageQueue<Message>(msSqlMessagingGatewayConfiguration); _publication = publication ?? new Publication() {MakeChannels = OnMissingChannel.Create}; } public void Send(Message message) { var topic = message.Header.Topic; Logger.Value.Debug($"MsSqlMessageProducer: send message with topic {topic} and id {message.Id.ToString()}"); _sqlQ.Send(message, topic); } public void SendWithDelay(Message message, int delayMilliseconds = 0) { //No delay support implemented Send(message); } public async Task SendAsync(Message message) { var topic = message.Header.Topic; Logger.Value.Debug( $"MsSqlMessageProducer: send async message with topic {topic} and id {message.Id.ToString()}"); await _sqlQ.SendAsync(message, topic); } public void Dispose() { } } }
32.584906
120
0.649102
b30cf156a05a2a9a6b71b16f8d419a38e3538c9a
1,194
py
Python
setup.py
PureCS/django-tagify
efb84bd9c9308c3f3d42721df16ceefbaf990e01
[ "MIT" ]
1
2018-08-17T19:09:22.000Z
2018-08-17T19:09:22.000Z
setup.py
dozmus/django-tagify
efb84bd9c9308c3f3d42721df16ceefbaf990e01
[ "MIT" ]
null
null
null
setup.py
dozmus/django-tagify
efb84bd9c9308c3f3d42721df16ceefbaf990e01
[ "MIT" ]
null
null
null
import os from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() setup( name='django-tagify', version='0.20', packages=['django_tagify'], description='django tag input field', long_description=README, author='PureCS', author_email='purecs@hotmail.com', url='https://github.com/purecs/django-tagify/', license='MIT', install_requires=[ 'Django>=2.0.0', ], include_package_data=True, package_data={ 'django_tagify': [ 'templates/*.html', 'static/js/*.js', 'static/css/*.css', ] }, classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 2.0', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
28.428571
59
0.577052
6614577bf08e9c5aa745097c1a41c442572ea4c5
285
py
Python
src/oscar/apps/dashboard/communications/config.py
sainjusajan/django-oscar
466e8edc807be689b0a28c9e525c8323cc48b8e1
[ "BSD-3-Clause" ]
null
null
null
src/oscar/apps/dashboard/communications/config.py
sainjusajan/django-oscar
466e8edc807be689b0a28c9e525c8323cc48b8e1
[ "BSD-3-Clause" ]
null
null
null
src/oscar/apps/dashboard/communications/config.py
sainjusajan/django-oscar
466e8edc807be689b0a28c9e525c8323cc48b8e1
[ "BSD-3-Clause" ]
null
null
null
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class CommunicationsDashboardConfig(AppConfig): label = 'communications_dashboard' name = 'oscar.apps.dashboard.communications' verbose_name = _('Communications dashboard')
31.666667
56
0.775439
81bc457f0fc126d6adba58d30c45ea68fdd5fa0c
1,606
php
PHP
tests/PHPExif/Adapter/ExiftoolProcOpenTest.php
IlliSystems/php-exif
4fd2b9e325982f476fdd8bd356cb51d7fa312021
[ "MIT" ]
4
2021-01-04T20:37:42.000Z
2022-03-15T07:21:22.000Z
tests/PHPExif/Adapter/ExiftoolProcOpenTest.php
IlliSystems/php-exif
4fd2b9e325982f476fdd8bd356cb51d7fa312021
[ "MIT" ]
25
2019-12-16T13:38:06.000Z
2022-03-15T12:46:20.000Z
tests/PHPExif/Adapter/ExiftoolProcOpenTest.php
IlliSystems/php-exif
4fd2b9e325982f476fdd8bd356cb51d7fa312021
[ "MIT" ]
8
2020-03-10T07:35:18.000Z
2022-01-21T18:10:37.000Z
<?php // disable the mock by default namespace { $mockProcOpen = false; } // same namespace as SUT namespace PHPExif\Adapter { // stub the function function proc_open($cmd, array $descriptorspec , &$pipes = array()) { global $mockProcOpen; if (isset($mockProcOpen) && !$mockProcOpen) { return \proc_open( $cmd, $descriptorspec, $pipes ); } return false; } /** * @covers \PHPExif\Adapter\Exiftool::<!public> */ class ExiftoolProcOpenTest extends \PHPUnit\Framework\TestCase { /** * @var \PHPExif\Adapter\Exiftool */ protected $adapter; public function setUp() : void { global $mockProcOpen; $mockProcOpen = true; $this->adapter = new \PHPExif\Adapter\Exiftool(); } public function tearDown() : void { global $mockProcOpen; $mockProcOpen = false; } /** * @group exiftool * @covers \PHPExif\Adapter\Exiftool::getCliOutput */ public function testGetCliOutput() { $this->expectException('RuntimeException'); $reflMethod = new \ReflectionMethod('\PHPExif\Adapter\Exiftool', 'getCliOutput'); $reflMethod->setAccessible(true); $result = $reflMethod->invoke( $this->adapter, sprintf( '%1$s', 'pwd' ) ); } } }
23.275362
93
0.493151
0daf916860d46d15bafaa7d8fe279c027bfeae19
766
rake
Ruby
lib/tasks/db.rake
skeleton1998/NaCl_prac
a2651d6461a92a8ab9b4db6f7c9735e27c92978a
[ "MIT" ]
null
null
null
lib/tasks/db.rake
skeleton1998/NaCl_prac
a2651d6461a92a8ab9b4db6f7c9735e27c92978a
[ "MIT" ]
null
null
null
lib/tasks/db.rake
skeleton1998/NaCl_prac
a2651d6461a92a8ab9b4db6f7c9735e27c92978a
[ "MIT" ]
2
2020-11-04T06:32:56.000Z
2020-11-06T11:01:49.000Z
require 'active_record' namespace :db do # db タスクの設定を追加する task :load_config do ActiveRecord::Tasks::DatabaseTasks.fixtures_path = File.join Rails.root, 'spec', 'fixtures' end desc "upgrade db schema" task :upgrade => :environment do schema_info = "#{ActiveRecord::Base.table_name_prefix}schema_info#{ActiveRecord::Base.table_name_suffix}" if ActiveRecord::Base.connection.table_exists?(schema_info) ActiveRecord::Base.connection.drop_table(schema_info) ActiveRecord::SchemaMigration.create_table if ActiveRecord::SchemaMigration.count(:version) == 0 puts 'upgrade db schema' ActiveRecord::SchemaMigration.create!(version: '00000000000001') Rake::Task['db:migrate'].invoke end end end end
33.304348
109
0.725849
5400e0adf21d71437dcef9fd5c1596b2c0078453
26,548
rb
Ruby
spec/extensions/validation_class_methods_spec.rb
zeroknol/sequel
49b12c49a6fe84b0e46622ff8b92fb9029b3fc2b
[ "MIT" ]
2
2015-11-06T02:42:54.000Z
2021-01-09T17:42:12.000Z
spec/extensions/validation_class_methods_spec.rb
rkh/sequel
9e9b768d86326109f01bf88ea234e26e7ab448ad
[ "MIT" ]
null
null
null
spec/extensions/validation_class_methods_spec.rb
rkh/sequel
9e9b768d86326109f01bf88ea234e26e7ab448ad
[ "MIT" ]
null
null
null
require File.join(File.dirname(File.expand_path(__FILE__)), "spec_helper") describe Sequel::Model do before do @c = Class.new(Sequel::Model) do def self.validates_coolness_of(attr) validates_each(attr) {|o, a, v| o.errors[a] << 'is not cool' if v != :cool} end end end specify "should respond to validates, validations, has_validations?" do @c.should respond_to(:validations) @c.should respond_to(:has_validations?) end specify "should acccept validation definitions using validates_each" do @c.validates_each(:xx, :yy) {|o, a, v| o.errors[a] << 'too low' if v < 50} o = @c.new o.should_receive(:xx).once.and_return(40) o.should_receive(:yy).once.and_return(60) o.valid?.should == false o.errors.full_messages.should == ['xx too low'] end specify "should return true/false for has_validations?" do @c.has_validations?.should == false @c.validates_each(:xx) {1} @c.has_validations?.should == true end specify "should validate multiple attributes at once" do o = @c.new def o.xx 1 end def o.yy 2 end vals = nil atts = nil @c.validates_each([:xx, :yy]){|obj,a,v| atts=a; vals=v} o.valid? vals.should == [1,2] atts.should == [:xx, :yy] end specify "should respect allow_missing option when using multiple attributes" do o = @c.new def o.xx self[:xx] end def o.yy self[:yy] end vals = nil atts = nil @c.validates_each([:xx, :yy], :allow_missing=>true){|obj,a,v| atts=a; vals=v} o.values[:xx] = 1 o.valid? vals.should == [1,nil] atts.should == [:xx, :yy] vals = nil atts = nil o.values.clear o.values[:yy] = 2 o.valid? vals.should == [nil, 2] atts.should == [:xx, :yy] vals = nil atts = nil o.values.clear o.valid?.should == true vals.should == nil atts.should == nil end specify "should overwrite existing validation with the same tag and attribute" do @c.validates_each(:xx, :xx, :tag=>:low) {|o, a, v| o.xxx; o.errors[a] << 'too low' if v < 50} @c.validates_each(:yy, :yy) {|o, a, v| o.yyy; o.errors[a] << 'too low' if v < 50} @c.validates_presence_of(:zz, :zz) @c.validates_length_of(:aa, :aa, :tag=>:blah) o = @c.new def o.zz @a ||= 0 @a += 1 end def o.aa @b ||= 0 @b += 1 end o.should_receive(:xx).once.and_return(40) o.should_receive(:yy).once.and_return(60) o.should_receive(:xxx).once o.should_receive(:yyy).twice o.valid?.should == false o.zz.should == 2 o.aa.should == 2 o.errors.full_messages.should == ['xx too low'] end specify "should provide a validates method that takes block with validation definitions" do @c.validates do coolness_of :blah end @c.validations[:blah].should_not be_empty o = @c.new o.should_receive(:blah).once.and_return(nil) o.valid?.should == false o.errors.full_messages.should == ['blah is not cool'] end end describe Sequel::Model do before do @c = Class.new(Sequel::Model) @c.class_eval do columns :score validates_each :score do |o, a, v| o.errors[a] << 'too low' if v < 87 end end @o = @c.new end specify "should supply a #valid? method that returns true if validations pass" do @o.score = 50 @o.should_not be_valid @o.score = 100 @o.should be_valid end specify "should provide an errors object" do @o.score = 100 @o.should be_valid @o.errors.should be_empty @o.score = 86 @o.should_not be_valid @o.errors[:score].should == ['too low'] @o.errors[:blah].should be_empty end end describe Sequel::Plugins::ValidationClassMethods::ClassMethods::Generator do before do $testit = nil @c = Class.new(Sequel::Model) do def self.validates_blah $testit = 1324 end end end specify "should instance_eval the block, sending everything to its receiver" do @c.validates do blah end $testit.should == 1324 end end describe Sequel::Model do before do @c = Class.new(Sequel::Model) do columns :value def self.filter(*args) o = Object.new def o.count; 2; end o end def skip; false; end def dont_skip; true; end end @m = @c.new end specify "should validate acceptance_of" do @c.validates_acceptance_of :value @m.should be_valid @m.value = '1' @m.should be_valid end specify "should validate acceptance_of with accept" do @c.validates_acceptance_of :value, :accept => 'true' @m.value = '1' @m.should_not be_valid @m.value = 'true' @m.should be_valid end specify "should validate acceptance_of with allow_nil => false" do @c.validates_acceptance_of :value, :allow_nil => false @m.should_not be_valid end specify "should validate acceptance_of with allow_missing => true" do @c.validates_acceptance_of :value, :allow_missing => true @m.should be_valid end specify "should validate acceptance_of with allow_missing => true and allow_nil => false" do @c.validates_acceptance_of :value, :allow_missing => true, :allow_nil => false @m.should be_valid @m.value = nil @m.should_not be_valid end specify "should validate acceptance_of with if => true" do @c.validates_acceptance_of :value, :if => :dont_skip @m.value = '0' @m.should_not be_valid end specify "should validate acceptance_of with if => false" do @c.validates_acceptance_of :value, :if => :skip @m.value = '0' @m.should be_valid end specify "should validate acceptance_of with if proc that evaluates to true" do @c.validates_acceptance_of :value, :if => proc{true} @m.value = '0' @m.should_not be_valid end specify "should validate acceptance_of with if proc that evaluates to false" do @c.validates_acceptance_of :value, :if => proc{false} @m.value = '0' @m.should be_valid end specify "should raise an error if :if option is not a Symbol, Proc, or nil" do @c.validates_acceptance_of :value, :if => 1 @m.value = '0' proc{@m.valid?}.should raise_error(Sequel::Error) end specify "should validate confirmation_of" do @c.send(:attr_accessor, :value_confirmation) @c.validates_confirmation_of :value @m.value = 'blah' @m.should_not be_valid @m.value_confirmation = 'blah' @m.should be_valid end specify "should validate confirmation_of with if => true" do @c.send(:attr_accessor, :value_confirmation) @c.validates_confirmation_of :value, :if => :dont_skip @m.value = 'blah' @m.should_not be_valid end specify "should validate confirmation_of with if => false" do @c.send(:attr_accessor, :value_confirmation) @c.validates_confirmation_of :value, :if => :skip @m.value = 'blah' @m.should be_valid end specify "should validate confirmation_of with allow_missing => true" do @c.send(:attr_accessor, :value_confirmation) @c.validates_acceptance_of :value, :allow_missing => true @m.should be_valid @m.value_confirmation = 'blah' @m.should be_valid @m.value = nil @m.should_not be_valid end specify "should validate format_of" do @c.validates_format_of :value, :with => /.+_.+/ @m.value = 'abc_' @m.should_not be_valid @m.value = 'abc_def' @m.should be_valid end specify "should raise for validate_format_of without regexp" do proc {@c.validates_format_of :value}.should raise_error(ArgumentError) proc {@c.validates_format_of :value, :with => :blah}.should raise_error(ArgumentError) end specify "should validate format_of with if => true" do @c.validates_format_of :value, :with => /_/, :if => :dont_skip @m.value = 'a' @m.should_not be_valid end specify "should validate format_of with if => false" do @c.validates_format_of :value, :with => /_/, :if => :skip @m.value = 'a' @m.should be_valid end specify "should validate format_of with allow_missing => true" do @c.validates_format_of :value, :allow_missing => true, :with=>/./ @m.should be_valid @m.value = nil @m.should_not be_valid end specify "should validate length_of with maximum" do @c.validates_length_of :value, :maximum => 5 @m.should_not be_valid @m.value = '12345' @m.should be_valid @m.value = '123456' @m.should_not be_valid end specify "should validate length_of with minimum" do @c.validates_length_of :value, :minimum => 5 @m.should_not be_valid @m.value = '12345' @m.should be_valid @m.value = '1234' @m.should_not be_valid end specify "should validate length_of with within" do @c.validates_length_of :value, :within => 2..5 @m.should_not be_valid @m.value = '12345' @m.should be_valid @m.value = '1' @m.should_not be_valid @m.value = '123456' @m.should_not be_valid end specify "should validate length_of with is" do @c.validates_length_of :value, :is => 3 @m.should_not be_valid @m.value = '123' @m.should be_valid @m.value = '12' @m.should_not be_valid @m.value = '1234' @m.should_not be_valid end specify "should validate length_of with allow_nil" do @c.validates_length_of :value, :is => 3, :allow_nil => true @m.should be_valid end specify "should validate length_of with if => true" do @c.validates_length_of :value, :is => 3, :if => :dont_skip @m.value = 'a' @m.should_not be_valid end specify "should validate length_of with if => false" do @c.validates_length_of :value, :is => 3, :if => :skip @m.value = 'a' @m.should be_valid end specify "should validate length_of with allow_missing => true" do @c.validates_length_of :value, :allow_missing => true, :minimum => 5 @m.should be_valid @m.value = nil @m.should_not be_valid end specify "should allow multiple calls to validates_length_of with different options without overwriting" do @c.validates_length_of :value, :maximum => 5 @c.validates_length_of :value, :minimum => 5 @m.should_not be_valid @m.value = '12345' @m.should be_valid @m.value = '123456' @m.should_not be_valid @m.value = '12345' @m.should be_valid @m.value = '1234' @m.should_not be_valid end specify "should validate numericality_of" do @c.validates_numericality_of :value @m.value = 'blah' @m.should_not be_valid @m.value = '123' @m.should be_valid @m.value = '123.1231' @m.should be_valid @m.value = '+1' @m.should be_valid @m.value = '-1' @m.should be_valid @m.value = '+1.123' @m.should be_valid @m.value = '-0.123' @m.should be_valid @m.value = '-0.123E10' @m.should be_valid @m.value = '32.123e10' @m.should be_valid @m.value = '+32.123E10' @m.should be_valid @m.should be_valid @m.value = '.0123' end specify "should validate numericality_of with only_integer" do @c.validates_numericality_of :value, :only_integer => true @m.value = 'blah' @m.should_not be_valid @m.value = '123' @m.should be_valid @m.value = '123.1231' @m.should_not be_valid end specify "should validate numericality_of with if => true" do @c.validates_numericality_of :value, :if => :dont_skip @m.value = 'a' @m.should_not be_valid end specify "should validate numericality_of with if => false" do @c.validates_numericality_of :value, :if => :skip @m.value = 'a' @m.should be_valid end specify "should validate numericality_of with allow_missing => true" do @c.validates_numericality_of :value, :allow_missing => true @m.should be_valid @m.value = nil @m.should_not be_valid end specify "should validate presence_of" do @c.validates_presence_of :value @m.should_not be_valid @m.value = '' @m.should_not be_valid @m.value = 1234 @m.should be_valid @m.value = nil @m.should_not be_valid @m.value = true @m.should be_valid @m.value = false @m.should be_valid end specify "should validate inclusion_of with an array" do @c.validates_inclusion_of :value, :in => [1,2] @m.should_not be_valid @m.value = 1 @m.should be_valid @m.value = 1.5 @m.should_not be_valid @m.value = 2 @m.should be_valid @m.value = 3 @m.should_not be_valid end specify "should validate inclusion_of with a range" do @c.validates_inclusion_of :value, :in => 1..4 @m.should_not be_valid @m.value = 1 @m.should be_valid @m.value = 1.5 @m.should be_valid @m.value = 0 @m.should_not be_valid @m.value = 5 @m.should_not be_valid end specify "should raise an error if inclusion_of doesn't receive a valid :in option" do lambda { @c.validates_inclusion_of :value }.should raise_error(ArgumentError) lambda { @c.validates_inclusion_of :value, :in => 1 }.should raise_error(ArgumentError) end specify "should raise an error if inclusion_of handles :allow_nil too" do @c.validates_inclusion_of :value, :in => 1..4, :allow_nil => true @m.value = nil @m.should be_valid @m.value = 0 @m.should_not be_valid end specify "should validate presence_of with if => true" do @c.validates_presence_of :value, :if => :dont_skip @m.should_not be_valid end specify "should validate presence_of with if => false" do @c.validates_presence_of :value, :if => :skip @m.should be_valid end specify "should validate presence_of with allow_missing => true" do @c.validates_presence_of :value, :allow_missing => true @m.should be_valid @m.value = nil @m.should_not be_valid end specify "should validate uniqueness_of with if => true" do @c.validates_uniqueness_of :value, :if => :dont_skip @m.value = 'a' @m.should_not be_valid end specify "should validate uniqueness_of with if => false" do @c.validates_uniqueness_of :value, :if => :skip @m.value = 'a' @m.should be_valid end specify "should validate uniqueness_of with allow_missing => true" do @c.validates_uniqueness_of :value, :allow_missing => true @m.should be_valid @m.value = nil @m.should_not be_valid end end context "Superclass validations" do before do @c1 = Class.new(Sequel::Model) @c1.class_eval do columns :value validates_length_of :value, :minimum => 5 end @c2 = Class.new(@c1) @c2.class_eval do columns :value validates_format_of :value, :with => /^[a-z]+$/ end end specify "should be checked when validating" do o = @c2.new o.value = 'ab' o.valid?.should == false o.errors.full_messages.should == [ 'value is too short' ] o.value = '12' o.valid?.should == false o.errors.full_messages.should == [ 'value is too short', 'value is invalid' ] o.value = 'abcde' o.valid?.should be_true end specify "should be skipped if skip_superclass_validations is called" do @c2.skip_superclass_validations o = @c2.new o.value = 'ab' o.valid?.should be_true o.value = '12' o.valid?.should == false o.errors.full_messages.should == [ 'value is invalid' ] o.value = 'abcde' o.valid?.should be_true end end context ".validates with block" do specify "should support calling .each" do @c = Class.new(Sequel::Model) @c.class_eval do columns :vvv validates do each :vvv do |o, a, v| o.errors[a] << "is less than zero" if v.to_i < 0 end end end o = @c.new o.vvv = 1 o.should be_valid o.vvv = -1 o.should_not be_valid end end describe Sequel::Model, "Validations" do before(:all) do class ::Person < Sequel::Model columns :id,:name,:first_name,:last_name,:middle_name,:initials,:age, :terms end class ::Smurf < Person end class ::Cow < Sequel::Model columns :id, :name, :got_milk end class ::User < Sequel::Model columns :id, :username, :password end class ::Address < Sequel::Model columns :id, :zip_code end end it "should validate the acceptance of a column" do class ::Cow < Sequel::Model validations.clear validates_acceptance_of :got_milk, :accept => 'blah', :allow_nil => false end @cow = Cow.new @cow.should_not be_valid @cow.errors.full_messages.should == ["got_milk is not accepted"] @cow.got_milk = "blah" @cow.should be_valid end it "should validate the confirmation of a column" do class ::User < Sequel::Model def password_confirmation "test" end validations.clear validates_confirmation_of :password end @user = User.new @user.should_not be_valid @user.errors.full_messages.should == ["password is not confirmed"] @user.password = "test" @user.should be_valid end it "should validate format of column" do class ::Person < Sequel::Model validates_format_of :first_name, :with => /^[a-zA-Z]+$/ end @person = Person.new :first_name => "Lancelot99" @person.valid?.should be_false @person = Person.new :first_name => "Anita" @person.valid?.should be_true end it "should validate length of column" do class ::Person < Sequel::Model validations.clear validates_length_of :first_name, :maximum => 30 validates_length_of :last_name, :minimum => 30 validates_length_of :middle_name, :within => 1..5 validates_length_of :initials, :is => 2 end @person = Person.new( :first_name => "Anamethatiswaytofreakinglongandwayoverthirtycharacters", :last_name => "Alastnameunderthirtychars", :initials => "LGC", :middle_name => "danger" ) @person.should_not be_valid @person.errors.full_messages.size.should == 4 @person.errors.full_messages.should include( 'first_name is too long', 'last_name is too short', 'middle_name is the wrong length', 'initials is the wrong length' ) @person.first_name = "Lancelot" @person.last_name = "1234567890123456789012345678901" @person.initials = "LC" @person.middle_name = "Will" @person.should be_valid end it "should validate that a column doesn't have a string value" do p = Class.new(Sequel::Model) p.class_eval do columns :age, :price, :confirmed self.raise_on_typecast_failure = false validates_not_string :age validates_not_string :confirmed validates_not_string :price, :message=>'is not valid' @db_schema = {:age=>{:type=>:integer}} end @person = p.new @person.should be_valid @person.confirmed = 't' @person.should_not be_valid @person.errors.full_messages.should == ['confirmed is a string'] @person.confirmed = true @person.should be_valid @person.age = 'a' @person.should_not be_valid @person.errors.full_messages.should == ['age is not a valid integer'] @person.db_schema[:age][:type] = :datetime @person.should_not be_valid @person.errors.full_messages.should == ['age is not a valid datetime'] @person.age = 20 @person.should be_valid @person.price = 'a' @person.should_not be_valid @person.errors.full_messages.should == ['price is not valid'] @person.price = 20 @person.should be_valid end it "should validate numericality of column" do class ::Person < Sequel::Model validations.clear validates_numericality_of :age end @person = Person.new :age => "Twenty" @person.should_not be_valid @person.errors.full_messages.should == ['age is not a number'] @person.age = 20 @person.should be_valid end it "should validate the presence of a column" do class ::Cow < Sequel::Model validations.clear validates_presence_of :name end @cow = Cow.new @cow.should_not be_valid @cow.errors.full_messages.should == ['name is not present'] @cow.name = "Betsy" @cow.should be_valid end it "should validate the uniqueness of a column" do class ::User < Sequel::Model validations.clear validates do uniqueness_of :username end end User.dataset.extend(Module.new { def fetch_rows(sql) @db << sql case sql when /COUNT.*username = '0records'/ yield({:v => 0}) when /COUNT.*username = '2records'/ yield({:v => 2}) when /COUNT.*username = '1record'/ yield({:v => 1}) when /username = '1record'/ yield({:id => 3, :username => "1record", :password => "test"}) end end }) @user = User.new(:username => "2records", :password => "anothertest") @user.should_not be_valid @user.errors.full_messages.should == ['username is already taken'] @user = User.new(:username => "1record", :password => "anothertest") @user.should_not be_valid @user.errors.full_messages.should == ['username is already taken'] @user = User.load(:id=>4, :username => "1record", :password => "anothertest") @user.should_not be_valid @user.errors.full_messages.should == ['username is already taken'] @user = User.load(:id=>3, :username => "1record", :password => "anothertest") @user.should be_valid @user.errors.full_messages.should == [] @user = User.new(:username => "0records", :password => "anothertest") @user.should be_valid @user.errors.full_messages.should == [] end it "should validate the uniqueness of multiple columns" do class ::User < Sequel::Model validations.clear validates do uniqueness_of [:username, :password] end end User.dataset.extend(Module.new { def fetch_rows(sql) @db << sql case sql when /COUNT.*username = '0records'/ yield({:v => 0}) when /COUNT.*username = '2records'/ yield({:v => 2}) when /COUNT.*username = '1record'/ yield({:v => 1}) when /username = '1record'/ if sql =~ /password = 'anothertest'/ yield({:id => 3, :username => "1record", :password => "anothertest"}) else yield({:id => 4, :username => "1record", :password => "test"}) end end end }) @user = User.new(:username => "2records", :password => "anothertest") @user.should_not be_valid @user.errors.full_messages.should == ['username and password is already taken'] @user = User.new(:username => "1record", :password => "anothertest") @user.should_not be_valid @user.errors.full_messages.should == ['username and password is already taken'] @user = User.load(:id=>4, :username => "1record", :password => "anothertest") @user.should_not be_valid @user.errors.full_messages.should == ['username and password is already taken'] @user = User.load(:id=>3, :username => "1record", :password => "test") @user.should_not be_valid @user.errors.full_messages.should == ['username and password is already taken'] @user = User.load(:id=>3, :username => "1record", :password => "anothertest") @user.should be_valid @user.errors.full_messages.should == [] @user = User.new(:username => "0records", :password => "anothertest") @user.should be_valid @user.errors.full_messages.should == [] end it "should have a validates block that contains multiple validations" do class ::Person < Sequel::Model validations.clear validates do format_of :first_name, :with => /^[a-zA-Z]+$/ length_of :first_name, :maximum => 30 end end Person.validations[:first_name].size.should == 2 @person = Person.new :first_name => "Lancelot99" @person.valid?.should be_false @person2 = Person.new :first_name => "Wayne" @person2.valid?.should be_true end it "should allow 'longhand' validations direcly within the model." do lambda { class ::Person < Sequel::Model validations.clear validates_length_of :first_name, :maximum => 30 end }.should_not raise_error Person.validations.length.should eql(1) end it "should define a has_validations? method which returns true if the model has validations, false otherwise" do class ::Person < Sequel::Model validations.clear validates do format_of :first_name, :with => /\w+/ length_of :first_name, :maximum => 30 end end class ::Smurf < Person validations.clear end Person.should have_validations Smurf.should_not have_validations end it "should validate correctly instances initialized with string keys" do class ::Can < Sequel::Model columns :id, :name validates_length_of :name, :minimum => 4 end Can.new('name' => 'ab').should_not be_valid Can.new('name' => 'abcd').should be_valid end end describe "Model#save" do before do @c = Class.new(Sequel::Model(:people)) @c.class_eval do columns :id, :x validates_each :x do |o, a, v| o.errors[a] << 'blah' unless v == 7 end end @m = @c.load(:id => 4, :x=>6) MODEL_DB.reset end specify "should save only if validations pass" do @m.raise_on_save_failure = false @m.should_not be_valid @m.save MODEL_DB.sqls.should be_empty @m.x = 7 @m.should be_valid @m.save.should_not be_false MODEL_DB.sqls.should == ['UPDATE people SET x = 7 WHERE (id = 4)'] end specify "should skip validations if the :validate=>false option is used" do @m.raise_on_save_failure = false @m.should_not be_valid @m.save(:validate=>false) MODEL_DB.sqls.should == ['UPDATE people SET x = 6 WHERE (id = 4)'] end specify "should raise error if validations fail and raise_on_save_faiure is true" do proc{@m.save}.should raise_error(Sequel::ValidationFailed) end specify "should return nil if validations fail and raise_on_save_faiure is false" do @m.raise_on_save_failure = false @m.save.should == nil end end
26.952284
114
0.635829
6b11d992906357f766ce42e644e0793e8b06126e
601
js
JavaScript
pwa_v_1/src/components/Routers.js
miguelnetoarte/pwa-react-generate
e0ef71be30140ad3c1cf04680736234b0c39c56e
[ "MIT" ]
3
2019-03-19T17:26:51.000Z
2019-12-05T19:09:13.000Z
pwa_v_1/src/components/Routers.js
miguenetoarte/pwa-react-generate
e0ef71be30140ad3c1cf04680736234b0c39c56e
[ "MIT" ]
5
2020-09-07T07:44:17.000Z
2022-02-18T10:27:25.000Z
pwa_v_1/src/components/Routers.js
miguelnetoarte/pwa-react-generate
e0ef71be30140ad3c1cf04680736234b0c39c56e
[ "MIT" ]
null
null
null
import React from 'react'; import * as routers from "../constants/routers"; import { BrowserRouter as Router, Route } from "react-router-dom"; import PrivateRoute from "./PrivateRoute"; import { HeaderContent, FooterContent } from "./layout"; import { Login, Logout } from "./pages"; const Routers = () => ( <Router key={Math.random()}> <HeaderContent/> <Route exact path={routers.ROOT} component={Login}/> <PrivateRoute path={routers.LOGOUT} component={Logout} /> <FooterContent/> </Router> ) export default Routers;
30.05
73
0.620632
a9de7ae2a315c08fdcbfa7681d323dfa168c74e1
810
php
PHP
app/Http/Requests/EmployeeStoreRequest.php
tuhindewan/caab
61ed4d9af6b66f177aacc55a7ff511cfbfa21f3b
[ "MIT" ]
null
null
null
app/Http/Requests/EmployeeStoreRequest.php
tuhindewan/caab
61ed4d9af6b66f177aacc55a7ff511cfbfa21f3b
[ "MIT" ]
null
null
null
app/Http/Requests/EmployeeStoreRequest.php
tuhindewan/caab
61ed4d9af6b66f177aacc55a7ff511cfbfa21f3b
[ "MIT" ]
null
null
null
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class EmployeeStoreRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required|string|max:191', 'designation' => 'required|string|max:191', 'department' => 'required|string|max:191', 'email' => 'required|string|email|max:191|unique:users', 'mobile' => 'required|numeric|min:11|unique:employees', 'roles' => 'required', ]; } }
22.5
68
0.562963
a367be4803155835c557101d076ea57b9b042bda
353
java
Java
src/main/java/com/ll/blog/dao/CategoryInfoMapper.java
lightnine/blog-backend
d12ca2328bd3ddc4bc2573b9d73d5e5b750d8078
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ll/blog/dao/CategoryInfoMapper.java
lightnine/blog-backend
d12ca2328bd3ddc4bc2573b9d73d5e5b750d8078
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ll/blog/dao/CategoryInfoMapper.java
lightnine/blog-backend
d12ca2328bd3ddc4bc2573b9d73d5e5b750d8078
[ "Apache-2.0" ]
null
null
null
package com.ll.blog.dao; import com.ll.blog.entity.CategoryInfo; import java.util.List; public interface CategoryInfoMapper { int deleteByPrimaryKey(Long id); int insert(CategoryInfo record); CategoryInfo selectByPrimaryKey(Long id); List<CategoryInfo> selectAll(); int updateByPrimaryKey(CategoryInfo record); }
22.0625
49
0.728045
056f92942e482e37259ec22e7b6f40454e655ed3
144
rb
Ruby
sinatra-contrib/lib/sinatra/decompile.rb
osamtimizer/sinatra
6ee7fc1a42e0e930eb603b9a4b67a4ff7406bfe0
[ "MIT" ]
6,825
2015-01-01T11:20:10.000Z
2022-03-31T08:30:02.000Z
sinatra-contrib/lib/sinatra/decompile.rb
zerocqool33/sinatra
a4dd24add24f2dd0e7299b9e68e12038138294d3
[ "MIT" ]
742
2015-01-02T17:17:20.000Z
2022-03-17T07:39:34.000Z
sinatra-contrib/lib/sinatra/decompile.rb
zerocqool33/sinatra
a4dd24add24f2dd0e7299b9e68e12038138294d3
[ "MIT" ]
1,593
2015-01-01T13:32:34.000Z
2022-03-30T13:32:47.000Z
warn "Sinatra::Decompile is deprecated without replacement." def warn(message) super "#{caller.first[/^[^:]:\d+:/]} warning: #{message}" end
24
60
0.680556
795ad9891d55ab5262db98d4de79a3429be7cde4
19,068
php
PHP
src/Boot.php
lamgor666/phpboot-core-php8
a42e34dd3f803ddde163af4ffba10eab58e829b6
[ "MIT" ]
1
2022-02-03T13:15:52.000Z
2022-02-03T13:15:52.000Z
src/Boot.php
lamgor666/phpboot-core-php8
a42e34dd3f803ddde163af4ffba10eab58e829b6
[ "MIT" ]
null
null
null
src/Boot.php
lamgor666/phpboot-core-php8
a42e34dd3f803ddde163af4ffba10eab58e829b6
[ "MIT" ]
null
null
null
<?php namespace phpboot; use Closure; use phpboot\common\AppConf; use phpboot\common\constant\ReqParamSecurityMode; use phpboot\common\swoole\Swoole; use phpboot\common\util\ArrayUtils; use phpboot\common\util\JsonUtils; use phpboot\common\util\StringUtils; use phpboot\exception\ExceptionHandler; use phpboot\exception\ExceptionHandlerImpl; use phpboot\exception\HttpError; use phpboot\exception\JwtAuthException; use phpboot\exception\ValidateException; use phpboot\http\middleware\Middleware; use phpboot\http\server\Request; use phpboot\http\server\Response; use phpboot\http\server\response\JsonResponse; use phpboot\logging\LogContext; use RuntimeException; use Symfony\Component\Routing\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; use Throwable; final class Boot { private static array $map1 = []; private function __construct() { } public static function initRouteRulesInSwooleMode(int $workerId): void { $filepath = RouteRulesBuilder::cacheFile(); if ($filepath === '' || !is_file($filepath)) { return; } try { $routeRules = include($filepath); } catch (Throwable) { $routeRules = null; } if (!is_array($routeRules)) { $routeRules = []; } self::$map1["route_rules_worker$workerId"] = $routeRules; foreach ($routeRules as $rule) { self::addControllerBean($workerId, $rule['handler']); } } public static function gzipOutputEnabled(?bool $flag = null): bool { $key = 'gzip_output_enabled'; if (is_bool($flag)) { self::$map1[$key] = $flag; return false; } return self::$map1[$key] === true; } public static function withExceptionHandler(ExceptionHandler $handler): void { self::checkNecessaryExceptionHandlers(); $key = 'exception_handlers'; if (!is_array(self::$map1[$key])) { self::$map1[$key] = [$handler]; return; } $idx = -1; /* @var ExceptionHandler $item */ foreach (self::$map1[$key] as $i => $item) { if ($item->getExceptionClassName() === $handler->getExceptionClassName()) { $idx = $i; break; } } if ($idx < 0) { self::$map1[$key][] = $handler; } else { self::$map1[$key][$idx] = $handler; } } public static function withMiddleware(Middleware $middleware): void { if (self::isMiddlewareExists(get_class($middleware))) { return; } $key = 'middlewares'; if (!is_array(self::$map1[$key])) { self::$map1[$key] = [$middleware]; } else { self::$map1[$key][] = $middleware; } } public static function handleRequest(Request $request, Response $response, string $routeRulesCacheFile = ''): void { if (strtoupper($request->getMethod()) === 'OPTIONS') { $response->withPayload(JsonResponse::withPayload(['code' => 200])); $response->send(); return; } if (!empty($routeRulesCacheFile)) { $request->withContextParam('routeRulesCacheFile', $routeRulesCacheFile); } self::checkNecessaryExceptionHandlers(); $response->withExceptionHandlers(self::getExceptionHandlers()); $ctx = RequestContext::fromUri($request->getRequestUrl()); $ctx->setMethod($request->getMethod()); $routes = new RouteCollection(); $workerId = Swoole::getWorkerId(); $routeRules = []; if ($workerId >= 0) { $rulesKey = "route_rules_worker$workerId"; $routeRules = self::$map1[$rulesKey]; } else { $cacheFile = empty($routeRulesCacheFile) ? RouteRulesBuilder::cacheFile() : $routeRulesCacheFile; if ($cacheFile !== '' && is_file($cacheFile)) { try { $routeRules = include($cacheFile); } catch (Throwable) { $routeRules = []; } } } if (!is_array($routeRules)) { $routeRules = []; } foreach ($routeRules as $rule) { $route = new Route($rule['requestMapping']); if ($rule['httpMethod'] === 'ALL') { $route->setMethods(['GET', 'POST']); } else { $route->setMethods([$rule['httpMethod']]); } $routes->add($rule['handler'], $route); } $matcher = new UrlMatcher($routes, $ctx); try { $result = $matcher->match($request->getRequestUrl()); $handlerFunc = $result['_route']; $request->withContextParam('pathVariables', ArrayUtils::removeKeys($result, '_route')); } catch (Throwable $ex) { if ($ex instanceof ResourceNotFoundException) { if (AppConf::getBoolean('logging.logNotFound')) { $logger = LogContext::getRuntimeLogger(); $map1 = [ 'baseUrl' => $ctx->getBaseUrl(), 'pathInfo' => $ctx->getPathInfo(), 'method' => $ctx->getMethod(), 'host' => $ctx->getHost(), 'scheme' => $ctx->getScheme(), 'httpPort' => $ctx->getHttpPort(), 'httpsPort' => $ctx->getHttpsPort(), 'queryString' => $ctx->getQueryString() ]; $msg = sprintf( 'http 404 not found, request url: %s, ctx: %s', $request->getRequestUrl(), JsonUtils::toJson($map1) ); $logger->info($msg); } $response->withPayload(HttpError::create(404)); } else if ($ex instanceof MethodNotAllowedException) { $response->withPayload(HttpError::create(405)); } else { $response->withPayload($ex); } $response->send(); return; } $request->withContextParam('handlerName', $handlerFunc); $matchedRule = null; foreach ($routeRules as $rule) { if ($rule['handler'] === $handlerFunc) { $matchedRule = $rule; break; } } if (empty($matchedRule)) { $response->withPayload(new RuntimeException("handler not found for request uri: {$request->getRequestUrl()}")); $response->send(); return; } if (isset($matchedRule['rateLimitSettings']) && !empty($matchedRule['rateLimitSettings'])) { $request->withContextParam('rateLimitSettings', $matchedRule['rateLimitSettings']); } if (isset($matchedRule['jwtAuthKey']) && !empty($matchedRule['jwtAuthKey'])) { $request->withContextParam('jwtAuthKey', $matchedRule['jwtAuthKey']); } if (isset($matchedRule['validateRules']) && !empty($matchedRule['validateRules'])) { $request->withContextParam('validateRules', $matchedRule['validateRules']); } if (isset($matchedRule['extraAnnos']) && !empty($matchedRule['extraAnnos'])) { $request->withContextParam('extraAnnos', $matchedRule['extraAnnos']); } $handler = function (Request $req, Response $resp) use ($matchedRule) { $middlewares = collect(Boot::getMiddlewares()) ->filter(fn(Middleware $mid) => $mid->getType() === Middleware::PRE_HANDLE_MIDDLEWARE) ->sortBy(fn(Middleware $mid) => $mid->getOrder(), SORT_NUMERIC); /* @var Middleware $mid */ foreach ($middlewares->toArray() as $mid) { $mid->handle($req, $resp); } $argList = []; $args = empty($matchedRule['handlerFuncArgs']) ? [] : $matchedRule['handlerFuncArgs']; foreach ($args as $i => $argInfo) { if (!is_array($argInfo)) { throw new RuntimeException("fail to inject arg$i for handler: {$matchedRule['handler']}"); } if ($argInfo['rawReq']) { $argList[] = $req; continue; } if ($argInfo['rawJwt']) { $argList[] = $req->getJwt(); continue; } if ($argInfo['clientIp']) { $argList[] = $req->getClientIp(); continue; } if (isset($argInfo['httpHeaderName'])) { $hname = str_replace('{argName}', $argInfo['name'], $argInfo['httpHeaderName']); $argList[] = $req->getHeader($hname); continue; } if ($argInfo['rawBody']) { $argList[] = $req->getRawBody(); continue; } if (isset($argInfo['uploadedFileKey'])) { $argList[] = $req->getUploadedFile($argInfo['uploadedFileKey']); continue; } if (isset($argInfo['pathVariableName'])) { $pname = str_replace('{argName}', $argInfo['name'], $argInfo['pathVariableName']); $dv = $argInfo['defaultValue'] ?? ''; $argList[] = match ($argInfo['type']) { 'int' => $req->pathVariableAsInt($pname, $dv), 'float' => $req->pathVariableAsFloat($pname, $dv), 'bool' => $req->pathVariableAsBoolean($pname, $dv), 'string' => $req->pathVariableAsString($pname, $dv), default => throw new RuntimeException("unsupported type for pathVariable: $pname") }; continue; } if (isset($argInfo['jwtClaimName'])) { $cname = str_replace('{argName}', $argInfo['name'], $argInfo['jwtClaimName']); $dv = $argInfo['defaultValue'] ?? ''; $argList[] = match ($argInfo['type']) { 'int' => $req->jwtIntCliam($cname, $dv), 'float' => $req->jwtFloatClaim($cname, $dv), 'bool' => $req->jwtBooleanClaim($cname, $dv), 'string' => $req->jwtStringClaim($cname, $dv), 'array' => $req->jwtArrayClaim($cname), default => throw new RuntimeException("unsupported type for jwt claim: $cname") }; continue; } if (isset($argInfo['reqParamName'])) { $rname = str_replace('{argName}', $argInfo['name'], $argInfo['reqParamName']); $dv = $argInfo['defaultValue'] ?? ''; switch ($argInfo['type']) { case 'int': $argList[] = $req->requestParamAsInt($rname, $dv); break; case 'float': $argList[] = $req->requestParamAsFloat($rname, $dv); break; case 'bool': $argList[] = $req->requestParamAsBoolean($rname, $dv); break; case 'string': if ($argInfo['decimal']) { $securityMode = ReqParamSecurityMode::STRIP_TAGS; $paramValue = $req->requestParamAsString($rname, $securityMode, $dv); $argList[] = bcadd($paramValue, 0, 2); } else { $securityMode = $argInfo['securityMode'] ?? ReqParamSecurityMode::STRIP_TAGS; $argList[] = $req->requestParamAsString($rname, $securityMode, $dv); } break; case 'array': $argList[] = $req->requestParamAsArray($rname); break; default: throw new RuntimeException("unsupported type for request param: $rname"); } continue; } if ($argInfo['mapBind']) { $argList[] = $req->getMap($argInfo['mapBindRules']); continue; } throw new RuntimeException("fail to inject arg$i [{$argInfo['name']}] for handler: {$matchedRule['handler']}"); } $className = StringUtils::substringBefore($matchedRule['handler'], '@'); $className = StringUtils::ensureLeft($className, "\\"); $methodName = StringUtils::substringAfter($matchedRule['handler'], '@'); if (Swoole::inCoroutineMode(true)) { $bean = Boot::getControllerBean($className); } else { $bean = new $className(); } $payload = call_user_func_array([$bean, $methodName], $argList); $middlewares = collect(Boot::getMiddlewares()) ->filter(fn(Middleware $mid) => $mid->getType() === Middleware::POST_HANDLE_MIDDLEWARE) ->sortBy(fn(Middleware $mid) => $mid->getOrder(), SORT_NUMERIC); /* @var Middleware $mid */ foreach ($middlewares->toArray() as $mid) { $mid->handle($req, $resp); } $resp->withPayload($payload); }; try { $handler($request, $response); } catch (Throwable $ex) { $response->withPayload($ex); } $response->send(); } public static function getControllerBean(string $handlerName, ?int $workerId = null) { if (!Swoole::inCoroutineMode(true)) { return null; } if (!is_int($workerId) || $workerId < 0) { $workerId = Swoole::getWorkerId(); } if ($workerId < 0) { return null; } $key = "controllers_worker$workerId"; $map1 = self::$map1[$key]; if (!is_array($map1)) { return null; } list($clazz) = explode('@', $handlerName); if (!is_string($clazz) || $clazz === '') { return null; } $clazz = StringUtils::ensureLeft($clazz, "\\"); $bean = $map1[$clazz]; return is_object($bean) ? $bean : null; } private static function checkNecessaryExceptionHandlers(): void { $key = 'exception_handlers'; $handlers = self::$map1[$key]; if (!is_array($handlers)) { $handlers = []; } $classes = [ JwtAuthException::class, ValidateException::class ]; foreach ($classes as $clazz) { $found = false; foreach ($handlers as $handler) { if (str_contains($handler->getExceptionClassName(), $clazz)) { $found = true; break; } } if (!$found) { $handlers[] = ExceptionHandlerImpl::create($clazz); } } self::$map1[$key] = $handlers; } private static function isMiddlewareExists(string $clazz): bool { $key = 'middlewares'; if (isset(self::$map1[$key])) { $middlewares = self::$map1[$key]; } else { self::$map1[$key] = []; return false; } $clazz = StringUtils::ensureLeft($clazz, "\\"); foreach ($middlewares as $mid) { if (StringUtils::ensureLeft(get_class($mid), "\\") === $clazz) { return true; } } return false; } /** * @return ExceptionHandler[] */ private static function getExceptionHandlers(): array { $key = 'exception_handlers'; $handlers = self::$map1[$key]; return is_array($handlers) ? $handlers : []; } /** * @return Middleware[] */ public static function getMiddlewares(): array { $middlewares = self::$map1['middlewares']; return is_array($middlewares) ? $middlewares : []; } private static function addRoute(int $workerId, Route $route): void { if ($workerId < 0) { return; } $mapKey = "route_items_worker$workerId"; if (is_array(self::$map1[$mapKey])) { self::$map1[$mapKey][] = $route; } else { self::$map1[$mapKey] = [$route]; } } private static function addRequestHandler(int $workerId, string $handlerName, Closure $fn): void { if ($workerId < 0) { return; } $mapKey = "request_handlers_worker$workerId"; if (is_array(self::$map1[$mapKey])) { self::$map1[$mapKey][$handlerName] = $fn; } else { self::$map1[$mapKey] = [$handlerName => $fn]; } } private static function addControllerBean(int $workerId, string $handlerName): void { if ($workerId < 0) { return; } $key = "controllers_worker$workerId"; list($clazz) = explode('@', $handlerName); if (!is_string($clazz) || $clazz === '') { return; } $clazz = StringUtils::ensureLeft($clazz, "\\"); $map1 = self::$map1[$key]; if (!is_array($map1)) { $map1 = []; } if (isset($map1[$clazz])) { return; } try { $bean = new $clazz(); } catch (Throwable) { return; } if (!is_object($bean)) { return; } $map1[$clazz] = $bean; self::$map1[$key] = $map1; } }
33.335664
128
0.472572
f8974ed4c02fd960d445bcb14159f4c106362435
297
go
Go
cmd/version.go
ryosan-470/slackctl
211d455bffecdb8bf4a1e68d3b9261e13b1c7d8a
[ "MIT" ]
1
2019-01-15T02:04:58.000Z
2019-01-15T02:04:58.000Z
cmd/version.go
ryosan-470/slackctl
211d455bffecdb8bf4a1e68d3b9261e13b1c7d8a
[ "MIT" ]
12
2018-11-19T14:51:42.000Z
2019-02-27T04:35:41.000Z
cmd/version.go
ryosan-470/slackctl
211d455bffecdb8bf4a1e68d3b9261e13b1c7d8a
[ "MIT" ]
null
null
null
package cmd import "github.com/spf13/cobra" var Version = "0.0.1" func NewShowVersion() *cobra.Command { cmd := &cobra.Command{ Use: "version", Short: "Show version", Run: func(cmd *cobra.Command, args []string) { cmd.Printf("slackctl version: %s\n", Version) }, } return cmd }
17.470588
48
0.649832
4dbaeb830ad6adb1409844945341f4feb2472e47
159
cs
C#
src/Plugin.Boilerplate.Android/Properties/AssemblyInfo.cs
juanroman/xamarin-boilerplate
6f95e30ec92cccff3590cf1f2271ad4f545900e6
[ "MIT" ]
3
2018-12-30T15:57:34.000Z
2021-01-05T00:10:38.000Z
src/Plugin.Boilerplate.Android/Properties/AssemblyInfo.cs
juanroman/xamarin-boilerplate
6f95e30ec92cccff3590cf1f2271ad4f545900e6
[ "MIT" ]
null
null
null
src/Plugin.Boilerplate.Android/Properties/AssemblyInfo.cs
juanroman/xamarin-boilerplate
6f95e30ec92cccff3590cf1f2271ad4f545900e6
[ "MIT" ]
1
2021-08-14T07:33:49.000Z
2021-08-14T07:33:49.000Z
using System.Reflection; [assembly: AssemblyTitle("Plugin.Boilerplate.Android")] [assembly: AssemblyDescription("Plugin.Boilerplate Android Class Library")]
31.8
75
0.811321
4bff039ea5d156c76454504b2e387be75404fcb0
246
h
C
kernel/include/precompile.h
zhiayang/nx
0d9da881f67ec351244abd72e1f3884816b48f5b
[ "Apache-2.0" ]
16
2019-03-14T19:45:02.000Z
2022-02-06T19:18:08.000Z
kernel/include/precompile.h
zhiayang/nx
0d9da881f67ec351244abd72e1f3884816b48f5b
[ "Apache-2.0" ]
1
2020-05-08T08:40:02.000Z
2020-05-08T13:27:59.000Z
kernel/include/precompile.h
zhiayang/nx
0d9da881f67ec351244abd72e1f3884816b48f5b
[ "Apache-2.0" ]
2
2021-01-16T20:42:05.000Z
2021-12-01T23:37:18.000Z
// precompile.h // Copyright (c) 2020, zhiayang // Licensed under the Apache License Version 2.0. #ifdef ZPR_FREESTANDING #undef ZPR_FREESTANDING #endif #define ZPR_FREESTANDING 1 #include <cstddef> #include <cstdint> #include <zst/zpr.h>
14.470588
49
0.743902