identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/encounter/dawn-cmake/blob/master/src/dawn/native/CacheKey.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
dawn-cmake
|
encounter
|
C++
|
Code
| 198
| 416
|
// Copyright 2022 The Dawn Authors
//
// 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.
#include "dawn/native/CacheKey.h"
#include <iomanip>
namespace dawn::native {
std::ostream& operator<<(std::ostream& os, const CacheKey& key) {
os << std::hex;
for (const int b : key) {
os << std::setfill('0') << std::setw(2) << b << " ";
}
os << std::dec;
return os;
}
template <>
void CacheKeySerializer<std::string>::Serialize(CacheKey* key, const std::string& t) {
key->Record(static_cast<size_t>(t.length()));
key->insert(key->end(), t.begin(), t.end());
}
template <>
void CacheKeySerializer<CacheKey>::Serialize(CacheKey* key, const CacheKey& t) {
// For nested cache keys, we do not record the length, and just copy the key so that it
// appears we just flatten the keys into a single key.
key->insert(key->end(), t.begin(), t.end());
}
} // namespace dawn::native
| 18,742
|
https://github.com/hangetzzu/Lime-Worm/blob/master/Project/Server_0.5/Server_0.5/Forms/About.Designer.vb
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Lime-Worm
|
hangetzzu
|
Visual Basic
|
Code
| 1,116
| 4,385
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class About
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Label1 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.Label4 = New System.Windows.Forms.Label()
Me.Label5 = New System.Windows.Forms.Label()
Me.Label6 = New System.Windows.Forms.Label()
Me.Label7 = New System.Windows.Forms.Label()
Me.Label8 = New System.Windows.Forms.Label()
Me.Label9 = New System.Windows.Forms.Label()
Me.Label10 = New System.Windows.Forms.Label()
Me.Label11 = New System.Windows.Forms.Label()
Me.Label12 = New System.Windows.Forms.Label()
Me.Label15 = New System.Windows.Forms.Label()
Me.Label16 = New System.Windows.Forms.Label()
Me.Label17 = New System.Windows.Forms.Label()
Me.Label18 = New System.Windows.Forms.Label()
Me.Label19 = New System.Windows.Forms.Label()
Me.Label20 = New System.Windows.Forms.Label()
Me.Label21 = New System.Windows.Forms.Label()
Me.Label22 = New System.Windows.Forms.Label()
Me.Label23 = New System.Windows.Forms.Label()
Me.Label24 = New System.Windows.Forms.Label()
Me.Label25 = New System.Windows.Forms.Label()
Me.Label26 = New System.Windows.Forms.Label()
Me.Label27 = New System.Windows.Forms.Label()
Me.SuspendLayout()
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.ForeColor = System.Drawing.Color.Lime
Me.Label1.Location = New System.Drawing.Point(12, 15)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(104, 20)
Me.Label1.TabIndex = 0
Me.Label1.Text = "Project Name"
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.ForeColor = System.Drawing.Color.Lime
Me.Label2.Location = New System.Drawing.Point(166, 15)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(97, 20)
Me.Label2.TabIndex = 1
Me.Label2.Text = ": Lime Worm"
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.ForeColor = System.Drawing.Color.Lime
Me.Label3.Location = New System.Drawing.Point(166, 35)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(96, 20)
Me.Label3.TabIndex = 3
Me.Label3.Text = ": NYAN CAT"
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.ForeColor = System.Drawing.Color.Lime
Me.Label4.Location = New System.Drawing.Point(12, 35)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(76, 20)
Me.Label4.TabIndex = 2
Me.Label4.Text = "Coded by"
'
'Label5
'
Me.Label5.AutoSize = True
Me.Label5.ForeColor = System.Drawing.Color.Lime
Me.Label5.Location = New System.Drawing.Point(166, 55)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(63, 20)
Me.Label5.TabIndex = 5
Me.Label5.Text = ": 0.5.8C"
'
'Label6
'
Me.Label6.AutoSize = True
Me.Label6.ForeColor = System.Drawing.Color.Lime
Me.Label6.Location = New System.Drawing.Point(12, 55)
Me.Label6.Name = "Label6"
Me.Label6.Size = New System.Drawing.Size(63, 20)
Me.Label6.TabIndex = 4
Me.Label6.Text = "Version"
'
'Label7
'
Me.Label7.AutoSize = True
Me.Label7.ForeColor = System.Drawing.Color.Lime
Me.Label7.Location = New System.Drawing.Point(166, 147)
Me.Label7.Name = "Label7"
Me.Label7.Size = New System.Drawing.Size(47, 20)
Me.Label7.TabIndex = 7
Me.Label7.Text = ": njq8"
'
'Label8
'
Me.Label8.AutoSize = True
Me.Label8.ForeColor = System.Drawing.Color.Lime
Me.Label8.Location = New System.Drawing.Point(12, 147)
Me.Label8.Name = "Label8"
Me.Label8.Size = New System.Drawing.Size(59, 20)
Me.Label8.TabIndex = 6
Me.Label8.Text = "Socket"
'
'Label9
'
Me.Label9.AutoSize = True
Me.Label9.ForeColor = System.Drawing.Color.Lime
Me.Label9.Location = New System.Drawing.Point(167, 167)
Me.Label9.Name = "Label9"
Me.Label9.Size = New System.Drawing.Size(104, 20)
Me.Label9.TabIndex = 9
Me.Label9.Text = ": NAPOLEON"
'
'Label10
'
Me.Label10.AutoSize = True
Me.Label10.ForeColor = System.Drawing.Color.Lime
Me.Label10.Location = New System.Drawing.Point(12, 167)
Me.Label10.Name = "Label10"
Me.Label10.Size = New System.Drawing.Size(61, 20)
Me.Label10.TabIndex = 8
Me.Label10.Text = "Spread"
'
'Label11
'
Me.Label11.AutoSize = True
Me.Label11.ForeColor = System.Drawing.Color.Lime
Me.Label11.Location = New System.Drawing.Point(166, 187)
Me.Label11.Name = "Label11"
Me.Label11.Size = New System.Drawing.Size(92, 20)
Me.Label11.TabIndex = 11
Me.Label11.Text = ": Rottweiler "
'
'Label12
'
Me.Label12.AutoSize = True
Me.Label12.ForeColor = System.Drawing.Color.Lime
Me.Label12.Location = New System.Drawing.Point(13, 189)
Me.Label12.Name = "Label12"
Me.Label12.Size = New System.Drawing.Size(86, 20)
Me.Label12.TabIndex = 10
Me.Label12.Text = "Passowrds"
'
'Label15
'
Me.Label15.AutoSize = True
Me.Label15.ForeColor = System.Drawing.Color.Lime
Me.Label15.Location = New System.Drawing.Point(12, 228)
Me.Label15.Name = "Label15"
Me.Label15.Size = New System.Drawing.Size(105, 20)
Me.Label15.TabIndex = 10
Me.Label15.Text = "GIO Function"
'
'Label16
'
Me.Label16.AutoSize = True
Me.Label16.ForeColor = System.Drawing.Color.Lime
Me.Label16.Location = New System.Drawing.Point(167, 228)
Me.Label16.Name = "Label16"
Me.Label16.Size = New System.Drawing.Size(90, 20)
Me.Label16.TabIndex = 11
Me.Label16.Text = ": Dr-Hazem"
'
'Label17
'
Me.Label17.AutoSize = True
Me.Label17.ForeColor = System.Drawing.Color.Lime
Me.Label17.Location = New System.Drawing.Point(167, 209)
Me.Label17.Name = "Label17"
Me.Label17.Size = New System.Drawing.Size(47, 20)
Me.Label17.TabIndex = 13
Me.Label17.Text = ": njq8"
'
'Label18
'
Me.Label18.AutoSize = True
Me.Label18.ForeColor = System.Drawing.Color.Lime
Me.Label18.Location = New System.Drawing.Point(13, 209)
Me.Label18.Name = "Label18"
Me.Label18.Size = New System.Drawing.Size(43, 20)
Me.Label18.TabIndex = 12
Me.Label18.Text = "RDP"
'
'Label19
'
Me.Label19.AutoSize = True
Me.Label19.ForeColor = System.Drawing.Color.Lime
Me.Label19.Location = New System.Drawing.Point(12, 248)
Me.Label19.Name = "Label19"
Me.Label19.Size = New System.Drawing.Size(112, 20)
Me.Label19.TabIndex = 10
Me.Label19.Text = "Ransomeware"
'
'Label20
'
Me.Label20.AutoSize = True
Me.Label20.ForeColor = System.Drawing.Color.Lime
Me.Label20.Location = New System.Drawing.Point(167, 248)
Me.Label20.Name = "Label20"
Me.Label20.Size = New System.Drawing.Size(84, 20)
Me.Label20.TabIndex = 11
Me.Label20.Text = ": Utku Sen"
'
'Label21
'
Me.Label21.AutoSize = True
Me.Label21.ForeColor = System.Drawing.Color.Lime
Me.Label21.Location = New System.Drawing.Point(13, 268)
Me.Label21.Name = "Label21"
Me.Label21.Size = New System.Drawing.Size(87, 20)
Me.Label21.TabIndex = 10
Me.Label21.Text = "Mono.Cecil"
'
'Label22
'
Me.Label22.AutoSize = True
Me.Label22.ForeColor = System.Drawing.Color.Lime
Me.Label22.Location = New System.Drawing.Point(166, 268)
Me.Label22.Name = "Label22"
Me.Label22.Size = New System.Drawing.Size(77, 20)
Me.Label22.TabIndex = 11
Me.Label22.Text = ": Jb Evain"
'
'Label23
'
Me.Label23.AutoSize = True
Me.Label23.ForeColor = System.Drawing.Color.Lime
Me.Label23.Location = New System.Drawing.Point(13, 288)
Me.Label23.Name = "Label23"
Me.Label23.Size = New System.Drawing.Size(58, 20)
Me.Label23.TabIndex = 10
Me.Label23.Text = "Theme"
'
'Label24
'
Me.Label24.AutoSize = True
Me.Label24.ForeColor = System.Drawing.Color.Lime
Me.Label24.Location = New System.Drawing.Point(166, 288)
Me.Label24.Name = "Label24"
Me.Label24.Size = New System.Drawing.Size(98, 20)
Me.Label24.TabIndex = 11
Me.Label24.Text = ": Carter (CH)"
'
'Label25
'
Me.Label25.AutoSize = True
Me.Label25.Font = New System.Drawing.Font("Sitka Subheading", 160.0!, System.Drawing.FontStyle.Bold)
Me.Label25.ForeColor = System.Drawing.Color.Lime
Me.Label25.Location = New System.Drawing.Point(380, -72)
Me.Label25.Name = "Label25"
Me.Label25.Size = New System.Drawing.Size(379, 462)
Me.Label25.TabIndex = 14
Me.Label25.Text = "L"
'
'Label26
'
Me.Label26.AutoSize = True
Me.Label26.ForeColor = System.Drawing.Color.Lime
Me.Label26.Location = New System.Drawing.Point(13, 75)
Me.Label26.Name = "Label26"
Me.Label26.Size = New System.Drawing.Size(67, 20)
Me.Label26.TabIndex = 4
Me.Label26.Text = "Website"
'
'Label27
'
Me.Label27.AutoSize = True
Me.Label27.ForeColor = System.Drawing.Color.Lime
Me.Label27.Location = New System.Drawing.Point(167, 75)
Me.Label27.Name = "Label27"
Me.Label27.Size = New System.Drawing.Size(191, 20)
Me.Label27.TabIndex = 5
Me.Label27.Text = ": github.com/NYAN-x-CAT"
'
'About
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(9.0!, 20.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.Color.Black
Me.ClientSize = New System.Drawing.Size(708, 382)
Me.Controls.Add(Me.Label25)
Me.Controls.Add(Me.Label17)
Me.Controls.Add(Me.Label18)
Me.Controls.Add(Me.Label24)
Me.Controls.Add(Me.Label22)
Me.Controls.Add(Me.Label20)
Me.Controls.Add(Me.Label16)
Me.Controls.Add(Me.Label23)
Me.Controls.Add(Me.Label21)
Me.Controls.Add(Me.Label19)
Me.Controls.Add(Me.Label15)
Me.Controls.Add(Me.Label11)
Me.Controls.Add(Me.Label12)
Me.Controls.Add(Me.Label9)
Me.Controls.Add(Me.Label10)
Me.Controls.Add(Me.Label7)
Me.Controls.Add(Me.Label8)
Me.Controls.Add(Me.Label27)
Me.Controls.Add(Me.Label5)
Me.Controls.Add(Me.Label26)
Me.Controls.Add(Me.Label6)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label4)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.Label1)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "About"
Me.ShowIcon = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Lime Worm | About"
Me.TopMost = True
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label1 As Label
Friend WithEvents Label2 As Label
Friend WithEvents Label3 As Label
Friend WithEvents Label4 As Label
Friend WithEvents Label5 As Label
Friend WithEvents Label6 As Label
Friend WithEvents Label7 As Label
Friend WithEvents Label8 As Label
Friend WithEvents Label9 As Label
Friend WithEvents Label10 As Label
Friend WithEvents Label11 As Label
Friend WithEvents Label12 As Label
Friend WithEvents Label15 As Label
Friend WithEvents Label16 As Label
Friend WithEvents Label17 As Label
Friend WithEvents Label18 As Label
Friend WithEvents Label19 As Label
Friend WithEvents Label20 As Label
Friend WithEvents Label21 As Label
Friend WithEvents Label22 As Label
Friend WithEvents Label23 As Label
Friend WithEvents Label24 As Label
Friend WithEvents Label25 As Label
Friend WithEvents Label26 As Label
Friend WithEvents Label27 As Label
End Class
| 46,375
|
https://github.com/proserium/proserium-web/blob/master/src/main/ts/net/proserium/web/app/app.component.scss
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
proserium-web
|
proserium
|
SCSS
|
Code
| 16
| 38
|
/*
* app.component.scss
*
* Copyright by proserium, all rights reserved.
* MIT License: https://mit-license.org
*/
| 37,180
|
https://github.com/imichaelnorris/ARgeofEmpires/blob/master/Assets/TangoSDK/Examples/ExperimentalMeshOcclusion/Shaders/OcclusionMask.shader
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
ARgeofEmpires
|
imichaelnorris
|
GLSL
|
Code
| 128
| 234
|
//-----------------------------------------------------------------------
// <copyright file="OcclusionMask.shader" company="Google">
//
// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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.
//
// </copyright>
//-----------------------------------------------------------------------
Shader "Custom/OcclusionMask"
{
SubShader
{
// Tags {"Queue" = "Geometry+10" }
ColorMask 0
ZWrite On
Pass { }
}
}
| 16,467
|
https://github.com/misterpilou/genshin/blob/master/src/utils/LinkOrExternal.jsx
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
genshin
|
misterpilou
|
JavaScript
|
Code
| 48
| 159
|
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
const isExternal = (link) => (/(http(s?)):\/\//i.test(link));
const LinkOrExternal = ({ to, children }) => (isExternal(to)
? <a href={to} target="_blank" rel="noreferrer">{children}</a>
: <Link to={to}>{children}</Link>);
LinkOrExternal.propTypes = {
children: PropTypes.string.isRequired,
to: PropTypes.string.isRequired,
};
export default LinkOrExternal;
| 12,812
|
https://github.com/sharwell/repose/blob/master/project-set/core/core-lib/src/main/java/com/rackspace/papi/service/datastore/impl/distributed/hash/ClusteredDatastore.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
repose
|
sharwell
|
Java
|
Code
| 51
| 199
|
package com.rackspace.papi.service.datastore.impl.distributed.hash;
import com.rackspace.papi.service.datastore.impl.distributed.common.RemoteBehavior;
import com.rackspace.papi.service.datastore.Datastore;
import com.rackspace.papi.service.datastore.StoredElement;
import java.util.concurrent.TimeUnit;
/**
*
* @author zinic
*/
public interface ClusteredDatastore extends Datastore {
StoredElement get(String key, RemoteBehavior behavior);
boolean remove(String key, RemoteBehavior behavior);
void put(String key, byte[] value, RemoteBehavior behavior);
void put(String key, byte[] value, int ttl, TimeUnit timeUnit, RemoteBehavior behavior);
}
| 45,596
|
https://github.com/KeenSoftwareHouse/Unreal.Net/blob/master/DotNetPlugin/Plugins/DotNet/Source/ThirdParty/DotnetInUE/Unreal.Generator/Metadata/TypeDefinitionBuilder.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Unreal.Net
|
KeenSoftwareHouse
|
C#
|
Code
| 280
| 867
|
// Copyright (c) 2021 Keen Software House
// Licensed under the MIT license.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Unreal.Generation;
using Unreal.Marshalling;
namespace Unreal.Metadata
{
public class TypeDefinitionBuilder<TBuilder> : MemberDefinitionBuilder<TBuilder>
where TBuilder : TypeDefinitionBuilder<TBuilder>
{
public string? NativeName;
public ITypeInfo? ParentType;
public INamedTypeSymbol? TypeSymbol;
public bool IsManagedUObject;
public string Namespace;
public string Header;
public TypeKind Kind;
public NativeTransferType TypicalArgumentType;
public ITypeMarshaller? DefaultMarshaller;
public string CosmeticName;
public string NativeModule;
public TypeDefinitionBuilder(Module module, string name, TypeDefinition? declaringType)
: base(module, name, declaringType)
{
NativeModule = module.Name;
Header = "";
Kind = TypeKind.Class;
TypicalArgumentType = NativeTransferType.ByValue;
Namespace = "";
CosmeticName = name;
}
public TBuilder WithNativeName(string nativeName)
{
NativeName = nativeName;
return Get();
}
public TBuilder WithParentType(ITypeInfo? parentType)
{
ParentType = parentType;
return Get();
}
public TBuilder WithTypeSymbol(INamedTypeSymbol? typeSymbol)
{
TypeSymbol = typeSymbol;
return Get();
}
public TBuilder WithIsManagedUObject(bool isManagedUObject)
{
IsManagedUObject = isManagedUObject;
return Get();
}
public TBuilder WithNamespace(string @namespace)
{
Namespace = @namespace;
return Get();
}
public TBuilder WithHeader(string header)
{
Header = header;
return Get();
}
public TBuilder WithKind(TypeKind kind)
{
Kind = kind;
return Get();
}
public TBuilder WithTypicalArgumentType(NativeTransferType typicalArgumentType)
{
TypicalArgumentType = typicalArgumentType;
return Get();
}
public TBuilder WithDefaultMarshaller(ITypeMarshaller? defaultMarshaller)
{
DefaultMarshaller = defaultMarshaller;
return Get();
}
public TBuilder WithCosmeticName(string cosmeticName)
{
CosmeticName = cosmeticName;
return Get();
}
public TBuilder WithNativeModule(string nativeModule)
{
NativeModule = nativeModule;
return Get();
}
}
public class TypeDefinitionBuilder : TypeDefinitionBuilder<TypeDefinitionBuilder>
{
public TypeDefinitionBuilder(Module module, string name, TypeDefinition? declaringType)
: base(module, name, declaringType)
{ }
public TypeDefinition Build()
{
// Use default name if native name is not set.
NativeName ??= Name;
return new(Name, Module, GetMetaAttributes(), Documentation, Comments, DeclaringType,
Visibility, Attributes, ManagedAttributes.ToImmutableArray(), NativeName, ParentType, TypeSymbol, IsManagedUObject, Namespace, Header, Kind,
TypicalArgumentType, DefaultMarshaller, CosmeticName, NativeModule);
}
}
}
| 31,971
|
https://github.com/avmgan/Alchemy4Tridion/blob/master/Client Proxies/CoreService/Tridion.ContentManager.CoreService.Client/ProcessInstanceData.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
Alchemy4Tridion
|
avmgan
|
C#
|
Code
| 72
| 306
|
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Runtime.Serialization;
namespace Alchemy4Tridion.Plugins.Clients.CoreService
{
[GeneratedCode("System.Runtime.Serialization", "4.0.0.0"), DebuggerStepThrough, DataContract(Name = "ProcessInstanceData", Namespace = "http://www.sdltridion.com/ContentManager/R6")]
public class ProcessInstanceData : ProcessData
{
private LinkToProcessDefinitionData ProcessDefinitionField;
private VariablesDictionary VariablesField;
[DataMember(EmitDefaultValue = false)]
public LinkToProcessDefinitionData ProcessDefinition
{
get
{
return this.ProcessDefinitionField;
}
set
{
this.ProcessDefinitionField = value;
}
}
[DataMember(EmitDefaultValue = false)]
public VariablesDictionary Variables
{
get
{
return this.VariablesField;
}
set
{
this.VariablesField = value;
}
}
}
}
| 23,689
|
https://github.com/CharLemAznable/char-elves/blob/master/src/test/java/com/github/charlemaznable/core/lang/MapListTest.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
char-elves
|
CharLemAznable
|
Java
|
Code
| 70
| 340
|
package com.github.charlemaznable.core.lang;
import lombok.val;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static com.github.charlemaznable.core.lang.Listt.listFromMap;
import static com.github.charlemaznable.core.lang.Mapp.mapFromList;
import static com.github.charlemaznable.core.lang.Mapp.of;
import static com.google.common.collect.Lists.newArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
public class MapListTest {
@Test
public void testMapList() {
List<Map<String, String>> list = newArrayList();
list.add(of("key", "key1", "value", "value1"));
list.add(of("key", "key2", "value", "value2"));
val map = mapFromList(list, "key", "value");
assertEquals("value1", map.get("key1"));
assertEquals("value2", map.get("key2"));
val list2 = listFromMap(map, "key", "value");
assertIterableEquals(list, list2);
}
}
| 25,286
|
https://github.com/fgprodigal/RayUI/blob/master/Interface/AddOns/RayUI/modules/misc/debugTools.lua
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
RayUI
|
fgprodigal
|
Lua
|
Code
| 303
| 1,461
|
----------------------------------------------------------
-- Load RayUI Environment
----------------------------------------------------------
RayUI:LoadEnv("Misc")
local M = _Misc
local S = R.Skins
--Enhanced debugtools from ElvUI
local D = M:NewModule("DebugTools", "AceEvent-3.0", "AceHook-3.0", "AceConsole-3.0")
function D:ModifyErrorFrame()
ScriptErrorsFrame.ScrollFrame.Text.cursorOffset = 0
ScriptErrorsFrame.ScrollFrame.Text.cursorHeight = 0
ScriptErrorsFrame.ScrollFrame.Text:SetScript("OnEditFocusGained", nil)
local function ScriptErrors_UnHighlightText()
ScriptErrorsFrame.ScrollFrame.Text:HighlightText(0, 0)
end
hooksecurefunc(ScriptErrorsFrame, "Update", ScriptErrors_UnHighlightText)
-- Unhighlight text when focus is hit
local function UnHighlightText(self)
self:HighlightText(0, 0)
end
ScriptErrorsFrame.ScrollFrame.Text:HookScript("OnEscapePressed", UnHighlightText)
ScriptErrorsFrame:Size(500, 300)
ScriptErrorsFrame.ScrollFrame:Size(ScriptErrorsFrame:GetWidth() - 45, ScriptErrorsFrame:GetHeight() - 71)
local BUTTON_WIDTH = 75
local BUTTON_HEIGHT = 24
local BUTTON_SPACING = 2
-- Add a first button
local firstButton = CreateFrame("Button", nil, ScriptErrorsFrame, "UIPanelButtonTemplate")
firstButton:Point("LEFT", ScriptErrorsFrame.reload, "RIGHT", BUTTON_SPACING, 0)
firstButton:SetText(L["第一页"])
firstButton:Height(BUTTON_HEIGHT)
firstButton:Width(BUTTON_WIDTH)
firstButton:SetScript("OnClick", function(self)
ScriptErrorsFrame.index = 1
ScriptErrorsFrame:Update()
end)
ScriptErrorsFrame.firstButton = firstButton
S:Reskin(firstButton)
-- Also add a Last button for errors
local lastButton = CreateFrame("Button", nil, ScriptErrorsFrame, "UIPanelButtonTemplate")
lastButton:Point("RIGHT", ScriptErrorsFrame.close, "LEFT", -BUTTON_SPACING, 0)
lastButton:Height(BUTTON_HEIGHT)
lastButton:Width(BUTTON_WIDTH)
lastButton:SetText(L["最后页"])
lastButton:SetScript("OnClick", function(self)
ScriptErrorsFrame.index = #(ScriptErrorsFrame.order)
ScriptErrorsFrame:Update()
end)
ScriptErrorsFrame.lastButton = lastButton
S:Reskin(lastButton)
end
function D:ScriptErrorsFrame_UpdateButtons()
local numErrors = #ScriptErrorsFrame.order
local index = ScriptErrorsFrame.index
if ( index == 0 ) then
ScriptErrorsFrame.lastButton:Disable()
ScriptErrorsFrame.firstButton:Disable()
else
if ( numErrors == 1 ) then
ScriptErrorsFrame.lastButton:Disable()
ScriptErrorsFrame.firstButton:Disable()
else
ScriptErrorsFrame.lastButton:Enable()
ScriptErrorsFrame.firstButton:Enable()
end
end
end
function D:ScriptErrorsFrame_OnError(_, _, keepHidden)
if keepHidden or D.MessagePrinted or not InCombatLockdown() or GetCVarBool("scriptErrors") ~= true then return end
D.MessagePrinted = true
end
function D:PLAYER_REGEN_ENABLED()
ScriptErrorsFrame:SetParent(UIParent)
D.MessagePrinted = nil
end
function D:PLAYER_REGEN_DISABLED()
ScriptErrorsFrame:SetParent(self.HideFrame)
end
function D:TaintError(event, addonName, addonFunc)
if GetCVarBool("scriptErrors") ~= true or addonName ~= "RayUI" then return end
R:ThrowError(L["%s: %s 尝试调用保护函数 '%s'."]:format(event, addonName or "<name>", addonFunc or "<func>"))
ScriptErrorsFrame:OnError(L["%s: %s 尝试调用保护函数 '%s'."]:format(event, addonName or "<name>", addonFunc or "<func>"), false, false)
end
function D:ShowScriptErrorsFrame()
ScriptErrorsFrame:Show()
ScriptErrorsFrame:SetParent(R.UIParent)
end
function D:StaticPopup_Show(name)
if(name == "ADDON_ACTION_FORBIDDEN") then
StaticPopup_Hide(name)
end
end
function D:Initialize()
if( not IsAddOnLoaded("Blizzard_DebugTools") ) then
LoadAddOn("Blizzard_DebugTools")
end
SetCVar("scriptErrors", 1)
self:ModifyErrorFrame()
self:SecureHook(ScriptErrorsFrame, "UpdateButtons", D.ScriptErrorsFrame_UpdateButtons)
self:SecureHook(ScriptErrorsFrame, "OnError", D.ScriptErrorsFrame_OnError)
self:SecureHook('StaticPopup_Show')
self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
if R:IsDeveloper() then
self:RegisterEvent("ADDON_ACTION_BLOCKED", "TaintError")
self:RegisterEvent("ADDON_ACTION_FORBIDDEN", "TaintError")
end
self:RegisterChatCommand("error", "ShowScriptErrorsFrame")
self.HideFrame = CreateFrame("Frame")
self.HideFrame:Hide()
end
M:RegisterMiscModule(D:GetName())
| 22,464
|
https://github.com/Jiyooung/ALGORITHM/blob/master/programmers/SQL/SELECT/JY_reverse_sorting.sql
|
Github Open Source
|
Open Source
|
MIT
| null |
ALGORITHM
|
Jiyooung
|
SQL
|
Code
| 21
| 60
|
/*
programmers : 역순 정렬하기
solved by JY
DATE : 2021.01.06
*/
SELECT NAME, DATETIME
FROM ANIMAL_INS
ORDER BY ANIMAL_ID DESC;
| 18,392
|
https://github.com/cphill11/social-network/blob/master/server.js
|
Github Open Source
|
Open Source
|
MIT
| null |
social-network
|
cphill11
|
JavaScript
|
Code
| 70
| 215
|
const express = require('express');
// set up mongoose to connect when the app is started
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 3001;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
// tell Mongoose which DB we want to connect to
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/social-network', {
useNewUrlParser: true,
useUnifiedTopology: true
});
app.use(require('./routes'));
// Log mongo queries being executed
mongoose.set('debug', true);
app.listen(PORT, () => console.log(`🌍 Connected on localhost:${PORT}`));
| 35,079
|
https://github.com/jberkow713/DS-Unit-3-Sprint-2-SQL-and-Databases/blob/master/module2-sql-for-analysis/RPGnew.py
|
Github Open Source
|
Open Source
|
MIT
| null |
DS-Unit-3-Sprint-2-SQL-and-Databases
|
jberkow713
|
Python
|
Code
| 157
| 509
|
import json
from dotenv import load_dotenv
import psycopg2
from psycopg2.extras import execute_values
import sqlite3
import os
load_dotenv()
DB_NAME = os.getenv("DB_NAME", default="OOPS")
DB_USER = os.getenv("DB_USER", default="OOPS")
DB_PW = os.getenv("DB_PW", default="OOPS")
DB_HOST = os.getenv("DB_HOST", default="OOPS")
# Create connection and cursor
conn = psycopg2.connect(
dbname=DB_NAME, user=DB_USER,
password=DB_PW, host=DB_HOST
)
cursor = conn.cursor()
# Create RPG data connection and cursor
sl_conn = sqlite3.connect('rpg_db.sqlite3')
sl_curs = sl_conn.cursor()
# Extract data
get_characters = 'SELECT * FROM charactercreator_character'
characters = sl_curs.execute(get_characters).fetchall()
# Transform data
create_character_table = """
CREATE TABLE charactercreator_character (
character_id SERIAL PRIMARY KEY,
name VARCHAR(30),
level INT,
exp INT,
hp INT,
strength INT,
intelligence INT,
dexterity INT,
wisdom INT
);
"""
pg_curs.execute(create_character_table)
pg_conn.commit()
# Insert data into table
for character in characters:
insert_character = """
INSERT INTO charactercreator_character
(name, level, exp, hp, strength, intelligence, dexterity, wisdom)
VALUES """ + str(characters[0][1:]) + ";"
pg_curs.execute(insert_character)
pg_conn.commit()
# Print table
pg_curs.execute('SELECT * FROM charactercreator_character LIMIT 5')
character_table = pg_curs.fetchall()
print(character_table)
| 2,816
|
https://github.com/vzateychuk/nodata/blob/master/src/server.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
nodata
|
vzateychuk
|
JavaScript
|
Code
| 470
| 1,434
|
import mongoose from 'mongoose';
import createExpress from './express';
import Resource from './ODataResource';
mongoose.Promise = global.Promise;
function checkAuth(auth, req) {
return !auth || auth(req);
}
class Server {
constructor(db, prefix, options) {
this._app = createExpress(options);
this._mongoose = mongoose;
this._settings = {
maxTop: 10000,
maxSkip: 10000,
orderby: undefined,
};
this.defaultConfiguration(db, prefix);
// TODO: Infact, resources is a mongooseModel instance, origin name is repositories.
// Should mix _resources object and resources object: _resources + resource = resources.
// Encapsulation to a object, separate mognoose, try to use *repository pattern*.
// 这里也许应该让 resources 支持 odata 查询的, 以方便直接在代码中使用 OData 查询方式来进行数据筛选, 达到隔离 mongo 的效果.
this._resources = [];
this.resources = {};
}
defaultConfiguration(db, prefix = '') {
this.set('app', this._app);
this.set('db', db);
this.set('prefix', prefix);
}
resource(name, model) {
if (model === undefined) {
return this._resources.name;
}
const resource = new Resource(name, model);
this._resources.push(resource);
return resource;
}
post(url, callback, auth) {
const app = this.get('app');
const prefix = this.get('prefix');
app.post(`${prefix}${url}`, (req, res, next) => {
if (checkAuth(auth, req)) {
callback(req, res, next);
} else {
res.status(401).end();
}
});
}
put(url, callback, auth) {
const app = this.get('app');
const prefix = this.get('prefix');
app.put(`${prefix}${url}`, (req, res, next) => {
if (checkAuth(auth, req)) {
callback(req, res, next);
} else {
res.status(401).end();
}
});
}
delete(url, callback, auth) {
const app = this.get('app');
const prefix = this.get('prefix');
app.delete(`${prefix}${url}`, (req, res, next) => {
if (checkAuth(auth, req)) {
callback(req, res, next);
} else {
res.status(401).end();
}
});
}
patch(url, callback, auth) {
const app = this.get('app');
const prefix = this.get('prefix');
app.patch(`${prefix}${url}`, (req, res, next) => {
if (checkAuth(auth, req)) {
callback(req, res, next);
} else {
res.status(401).end();
}
});
}
listen(...args) {
this._resources.map((resource) => {
const router = resource._router(this._db, this._settings);
this._app.use(this.get('prefix'), router);
this.resources[resource._name] = this._db.model(resource._name);
return true;
});
return this._app.listen(...args);
}
use(...args) {
if (args[0] instanceof Resource) {
this._resources.push(args[0]);
return;
}
this._app.use(...args);
}
get(key, callback, auth) {
if (callback === undefined) {
return this._settings[key];
}
// TODO: Need to refactor, same as L70-L80
const app = this.get('app');
const prefix = this.get('prefix');
return app.get(`${prefix}${key}`, (req, res, next) => {
if (checkAuth(auth, req)) {
callback(req, res, next);
} else {
res.status(401).end();
}
});
}
set(key, val) {
switch (key) {
case 'db': {
const options = { server: { reconnectTries: Number.MAX_VALUE } };
this._db = mongoose.createConnection(val, options, (err) => {
if (err) {
console.error('Failed to connect to database on startup.');
process.exit();
}
});
this._settings[key] = val;
break;
}
case 'prefix': {
let prefix = val;
if (prefix === '/') {
prefix = '';
}
if (prefix.length > 0 && prefix[0] !== '/') {
prefix = `/${prefix}`;
}
this._settings[key] = prefix;
break;
}
default: {
this._settings[key] = val;
break;
}
}
return this;
}
// provide a event listener to handle not able to connect DB.
on(name, event) {
if (['connected', 'disconnected'].indexOf(name) > -1) {
this._db.on(name, event);
}
}
engine(...args) {
this._app.engine(...args);
}
}
export default Server;
| 37,452
|
https://github.com/grzegorz-jamroz/entity-storage/blob/master/tests/Variant/UserStorage.php
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
entity-storage
|
grzegorz-jamroz
|
PHP
|
Code
| 20
| 82
|
<?php
declare(strict_types=1);
namespace Tests\Variant;
use Ifrost\EntityStorage\Storage\JsonEntityStorage;
class UserStorage extends JsonEntityStorage
{
public function __construct(string $directoryPath)
{
parent::__construct(User::class, $directoryPath);
}
}
| 16,008
|
https://github.com/ola-ct/gpstools/blob/master/Qeo/MainWindow.h
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
gpstools
|
ola-ct
|
C
|
Code
| 169
| 738
|
// $Id$
// Copyright (c) 2008 Oliver Lau <oliver@ersatzworld.net>
// Alle Rechte vorbehalten.
#ifndef __MAINWINDOW_H_
#define __MAINWINDOW_H_
#include <QMainWindow>
#include <QString>
#include <QVector>
#include <QColor>
#include <QPolygon>
#include <QTransform>
#include <QSettings>
#include <QStringList>
#include "gpslib/GPXFile.h"
#include "ui_MainWindow.h"
#include "TrackEditor.h"
#include "CalibrationWindow.h"
#include "TrackStatisticsWindow.h"
#include "BrowserWindow.h"
#include "GPXFileTableModel.h"
#include "TrackTableModel.h"
#include "LonLatTableModel.h"
#include "CalibrationIniFile.h"
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget* parent = 0);
~MainWindow();
protected:
void keyPressEvent(QKeyEvent*);
private:
static const int MaxRecentFiles = 10;
QAction* recentFileActs[MaxRecentFiles];
QAction* recentFileListSeparator;
int recentFileCount;
Ui::MainWindowClass ui;
QStringList lastLoaded;
QString lastTrackFilePath;
QStatusBar* status;
QSettings* settings;
QVector<TrackEditor*> editTrackTabList;
#ifdef _DEBUG
BrowserWindow browserWindow;
#endif
TrackStatisticsWindow statisticsWindow;
CalibrationWindow calibrationWindow;
private:
void readSettings(void);
void writeSettings(void);
void closeTab(int tabIndex);
void closeAllTabs(void);
void saveAllTabs(void);
void saveCurrentTab(void);
void updateRecentFileActions(void);
void openGPXFile(const QString& filename);
GPS::GPXFile* currentGPXFile(void);
void createTab(const QString& filename, GPS::GPXFile* file);
private slots:
void on_actionAboutQt_triggered();
void on_actionAboutQeo_triggered();
void on_actionSave_triggered();
void on_actionSaveAll_triggered();
void on_actionClose_triggered();
void on_actionCloseAll_triggered();
void on_actionOpen_triggered();
void on_actionExit_triggered();
void on_actionNew_triggered();
void on_actionCalibrateMaps_triggered();
void on_actionCompareTracks_triggered();
void on_actionBrowseTheWeb_triggered();
void openRecentFile(void);
void prepareExit(void);
void trackChanged(void);
void closeCurrentTab(void);
};
#endif // __MAINWINDOW_H_
| 12,493
|
https://github.com/QianglinSIMON/Reinforcement_Learning_An_Introduction/blob/master/chp5/racetrack.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Reinforcement_Learning_An_Introduction
|
QianglinSIMON
|
Python
|
Code
| 22
| 81
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 21 16:40:10 2021
@author: leyuan
reference:
https://github.com/brynhayder/reinforcement_learning_an_introduction/tree/master/code/exercises/ex_5_10
"""
'''
TO DO
'''
| 24,896
|
https://github.com/xknife-erian/nknife.jeelusrc/blob/master/NKnife.App.WebsiteBuilder/SimplusD/Client/Win/Common/ToolStripXmlDocument/ToolStripItemXmlElement.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
nknife.jeelusrc
|
xknife-erian
|
C#
|
Code
| 553
| 2,170
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
namespace Jeelu.SimplusD.Client.Win
{
internal class ToolStripItemXmlElement : XmlElement
{
/// <summary>
/// 构造函数
/// </summary>
internal ToolStripItemXmlElement(XmlDocument doc)
: base(string.Empty, "ToolStripItem", string.Empty, doc) { }
#region 控件的扩展属性
/// <summary>
/// 功能名, Control.Name
/// </summary>
internal string Fucation { get { return this.GetAttribute("fucation"); } }
/// <summary>
/// 控件的文本, Control.Text
/// </summary>
internal string TextString
{
get
{
string textString = this.GetAttribute("text");//(&F)
if (!string.IsNullOrEmpty(this.GetAttribute("hotkey")))
{
textString += "(&" + this.GetAttribute("hotkey").ToUpper() + ")";
}
if (this.IsPop)
{
textString += "...";
}
return textString;
}
}
/// <summary>
/// 是否是可执行的功能
/// </summary>
internal bool IsRun { get { return bool.Parse(this.GetAttribute("isRun")); } }
/// <summary>
/// 快捷键
/// </summary>
internal Keys ShortcutKey { get { return ParseShortcut(this.GetAttribute("shortcutKey")); } }
/// <summary>
/// 控件的位置,如:菜单、工具栏,两者都在
/// </summary>
internal ControlPlace Place
{
get
{
if (!this.HasAttribute("place"))
{
return ControlPlace.Nothing;
}
string place = this.GetAttribute("place");
switch (place)
{
case "ToolBar|Menu":
case "Menu|ToolBar":
return ControlPlace.MenuAndToolbar;
case "Menu":
return ControlPlace.Menu;
case "ToolBar":
return ControlPlace.ToolBar;
case "":
default:
return ControlPlace.Nothing;
}
}
}
/// <summary>
/// 是否是弹出式的功能
/// </summary>
internal bool IsPop
{
get
{
if (this.HasAttribute("isPop"))
{
if (!string.IsNullOrEmpty(this.GetAttribute("isPop")))
{
return bool.Parse(this.GetAttribute("isPop"));
}
}
return false;
}
}
/// <summary>
/// 获取在工具栏上的控件类型
/// </summary>
internal ToolStripItemType ToolBarControlType
{
get
{
string myValue = this.GetAttribute("toolBarControlType");
switch (myValue)
{
case "Button":
return ToolStripItemType.Button;
case "ComboBox":
return ToolStripItemType.ComboBox;
case "DropDownButton":
return ToolStripItemType.DropDownButton;
case "Label":
return ToolStripItemType.Label;
case "ProgressBar":
return ToolStripItemType.ProgressBar;
case "SplitButton":
return ToolStripItemType.SplitButton;
case "StatusLabel":
return ToolStripItemType.StatusLabel;
case "TextBox":
return ToolStripItemType.TextBox;
case "MenuItem":
return ToolStripItemType.MenuItem;
case "Separator":
return ToolStripItemType.Separator;
default:
throw new Exception("开发期错误:定义了错误的控件类型");
}
}
}
/// <summary>
/// 获取在菜单上的控件类型
/// </summary>
internal MenuItemType MenuControlType
{
set
{
if (value == MenuItemType.MenuItem)
{
if (this.Place == ControlPlace.Menu)
{
if (this.GetAttribute("menuControlType") != "Separator")
{
this.SetAttribute("menuControlType", "MenuItem");
}
}
}
else
{
throw new Exception("開發期錯誤:設置成無效的控件類型");
}
}
get
{
string myValue = this.GetAttribute("menuControlType");
switch (myValue)
{
case "ComboBox":
return MenuItemType.ComboBox;
case "MenuItem":
return MenuItemType.MenuItem;
case "TextBox":
return MenuItemType.TextBox;
case "Separator":
return MenuItemType.Separator;
default:
throw new Exception("开发期错误:定义了错误的控件类型");
}
}
}
/// <summary>
/// Icon的路径
/// </summary>
internal Image IconForElement
{
get
{
string icoValue = this.GetAttribute("hasIcon");
if (icoValue.ToUpper() != "FALSE")
{
//Bitmap bitmap = new Bitmap(icoValue);
return null;
}
return null;
}
}
/// <summary>
/// 控件的选中状态
/// </summary>
internal ControlCheckState MyCheckState
{
get
{
switch (this.GetAttribute("CheckState").ToUpper())
{
case "NULL":
return ControlCheckState.NoSetting;
case "TRUE":
return ControlCheckState.isChecked;
case "FALSE":
return ControlCheckState.isNotChecked;
default:
throw new Exception("开发期错误:菜单配置文件中有无法解析的控件状态类型(CheckState)");
}
}
}
/// <summary>
/// 控件的显示样式
/// </summary>
internal ToolStripItemDisplayStyle ToolBarDisplayStyle
{
get
{
switch (this.GetAttribute("inToolBarStyle").ToUpper())
{
case "IMAGE":
return ToolStripItemDisplayStyle.Image;
case "IMAGE|TEXT":
return ToolStripItemDisplayStyle.ImageAndText;
case "TEXT":
return ToolStripItemDisplayStyle.Text;
case "":
case "NOTHING":
default:
return ToolStripItemDisplayStyle.None;
}
}
}
/// <summary>
/// 控件的显示样式
/// </summary>
internal ToolStripItemDisplayStyle MenuDisplayStyle
{
get
{
switch (this.GetAttribute("inMenuStyle").ToUpper())
{
case "IMAGE":
return ToolStripItemDisplayStyle.Image;
case "IMAGE|TEXT":
return ToolStripItemDisplayStyle.ImageAndText;
case "TEXT":
return ToolStripItemDisplayStyle.Text;
case "":
case "NOTHING":
default:
return ToolStripItemDisplayStyle.None;
}
}
}
#endregion
/// <summary>
/// 将字符串解析为快捷键
/// </summary>
private Keys ParseShortcut(string strShortcut)
{
if (string.IsNullOrEmpty(strShortcut))
{
return Keys.None;
}
Keys myKeys = Keys.None;
string[] strs = strShortcut.Split('+');
foreach (string str in strs)
{
switch (str.ToUpper())
{
case "DEL":
case "DELETE":
myKeys |= Keys.Delete;
break;
case "CTRL":
myKeys |= Keys.Control;
break;
default:
try
{
myKeys |= (Keys)Enum.Parse(typeof(Keys), str);
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
break;
}
}
return myKeys;
}
}
}
| 42,765
|
https://github.com/famousczm/whisper/blob/master/public/javascripts/main.js
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
whisper
|
famousczm
|
JavaScript
|
Code
| 851
| 3,168
|
$(function() {
const FADE_TIME = 150 // ms
const TYPING_TIMER_LENGTH = 400 // ms
const COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
]
/** Initialize variables **/
let $window = $(window)
// Input for username
let $usernameInput = $('.usernameInput')
// Message area
let $messages = $('.messages')
// Input message input box
let $inputMessage = $('.inputMessage')
// Send message button
let $add = $('#add')[0]
$add.onclick = sendMessage
// The login page
let $loginPage = $('.login.page')
// The chatroom page
let $chatPage = $('.chat.page')
/** Prompt for setting a username **/
let username
let connected = false
let typing = false
let lastTypingTime
let $currentInput = $usernameInput.focus()
let socket = io()
function addParticipantsMessage (data) {
if (!data) return
let message = ''
message = `目前聊天室有${data.numUsers}个人`
log(message)
}
// 设置用户昵称
function setUsername () {
username = cleanInput($usernameInput.val().trim()).replace(/\s+/g, '')
// 关闭登录页,显示聊天页面
if (username) {
$loginPage.fadeOut()
$chatPage.show()
$loginPage.off('click')
$currentInput = $inputMessage.focus()
// 发送登录请求
socket.emit('add user', username)
}
}
// 发送一条消息
function sendMessage () {
let message = cleanInput($inputMessage.val())
if (!message || message.replace(/\s+/g, '') === '') {
$inputMessage.val('')
return
}
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('')
addChatMessage({
username: username,
message: message
})
// 发送发送信息请求
socket.emit('new message', message)
}
socket.emit('stop typing')
typing = false
}
/**
* 打印一个消息
* @param data
* @param options
*/
function log (message, options) {
if (!message) return
let $el = $('<li>').addClass('log').text(message)
addMessageElement($el, options)
}
/**
* 增加一条聊天消息
* @param data
* @param options
*/
function addChatMessage (data, options) {
if (!data) return
// Don't fade the message in if there is an 'X was typing'
let $typingMessages = getTypingMessages(data)
options = options || {}
if ($typingMessages.length !== 0) {
options.fade = false
$typingMessages.remove()
}
let $usernameDiv = $('<span class="username">')
.text(data.username)
.css('color', getUsernameColor(data.username))
let $messageBodyDiv = $('<span class="messageBody">')
.text(data.message)
let typingClass = data.typing ? 'typing' : ''
let $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv)
addMessageElement($messageDiv, options)
}
/**
* 增加一条正在输入的信息
* @param data
*/
function addChatTyping (data) {
if (!data) return
data.typing = true
data.message = '正在输入...'
addChatMessage(data)
}
/**
* 移除正在输入的消息
* @param data
*/
function removeChatTyping(data) {
if (!data) return
getTypingMessages(data).fadeOut(function () {
$(this).remove()
})
}
/**
* 增加一条消息在屏幕上
* @param el - 新增的消息元素
* @param options - 配置参数,可选
* options.fade - 元素是否要有隐现效果,默认 true
* options.prepend - 元素应该放置在所以消息之前,默认 false
*/
function addMessageElement (el, options) {
if (!el) return
var $el = $(el)
// Setup default options
if (!options) {
options = {}
}
if (typeof options.fade === 'undefined') {
options.fade = true
}
if (typeof options.prepend === 'undefined') {
options.prepend = false
}
// Apply options
if (options.fade) {
$el.hide().fadeIn(FADE_TIME)
}
if (options.prepend) {
$messages.prepend($el)
} else {
$messages.append($el)
}
$messages[0].scrollTop = $messages[0].scrollHeight
}
/**
* 过滤输入内容,防止输入注入标记
* @param input
*/
function cleanInput (input) {
if (!input) return
return $('<div/>').text(input).html()
}
/**
* 更新正在输入事件
*/
function updateTyping () {
if (connected) {
if (!typing) {
typing = true
socket.emit('typing')
}
lastTypingTime = (new Date()).getTime()
// 设置定时器来判断是否在连续输入中
setTimeout(function () {
let typingTimer = (new Date()).getTime()
let timeDiff = typingTimer - lastTypingTime
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing')
typing = false
}
}, TYPING_TIMER_LENGTH)
}
}
/**
* 获得 'X 正在输入' 的信息
* @param data
*/
function getTypingMessages (data) {
if (!data) return
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username
})
}
/**
* 根据用户名通过特定算法获得颜色
* @param username
* @return {String}
*/
function getUsernameColor (username) {
if (!username) return
// Compute hash code
let hash = 7
for (let i = 0, len = username.length; i < len; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash
}
// Calculate color
let index = Math.abs(hash % COLORS.length)
return COLORS[index]
}
// Keyboard.keydown
$window.keydown(function (event) {
// 当按下除了 ctrl meta alt 这几个键的任意键时自动对焦当前的输入框
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus()
}
// 按下 ENTER 键,如果用户名存在则发送信息,否则进行登录操作
if (event.which === 13) {
if (username) {
sendMessage()
} else {
setUsername()
}
}
})
// 监听输入框的输入操作
$inputMessage.on('input', function () {
updateTyping()
})
// Click events
// 点击登录页面自动对焦输入框
$loginPage.click(function () {
$currentInput.focus()
})
// 点击消息输入框对焦输入框
$inputMessage.click(function () {
$inputMessage.focus()
})
// Socket events
// 监听 login 回调,并显示登录信息
socket.on('login', function (data) {
if (!data) {
console.error('服务器错误')
return
}
connected = true
// Display the welcome message
let message = '欢迎来讲悄悄话,版本号 1.0.0'
log(message, {
prepend: true
})
addParticipantsMessage(data)
})
// 监听 new message 回调,更新聊天窗口内容
socket.on('new message', function (data) {
if (!data) {
console.error('服务器错误')
return
}
addChatMessage(data)
})
// 监听 user joined 回调,并显示加入信息
socket.on('user joined', function (data) {
if (!data) {
console.error('服务器错误')
return
}
log(data.username + ' 加入聊天')
addParticipantsMessage(data)
})
// 监听 user left 回调,并显示离开信息
socket.on('user left', function (data) {
if (!data) {
console.error('服务器错误')
return
}
log(data.username + ' 离开了')
addParticipantsMessage(data)
removeChatTyping(data)
})
// 监听 typing 回调,并显示输入信息
socket.on('typing', function (data) {
if (!data) {
console.error('服务器错误')
return
}
addChatTyping(data)
})
// 监听 stop typing 回调,关闭显示信息
socket.on('stop typing', function (data) {
if (!data) {
console.error('服务器错误')
return
}
removeChatTyping(data)
})
socket.on('disconnect', function () {
log('你已经断线了')
})
// socket.on('reconnect', function () {
// log('你已经重连回来')
// if (username) {
// socket.emit('add user', username)
// }
// })
//
// socket.on('reconnect_error', function () {
// log('重连失败')
// })
});
| 38,683
|
https://github.com/ritkal/core-ui/blob/master/src/services/toastNotification/views/ToastNotificationView.js
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
core-ui
|
ritkal
|
JavaScript
|
Code
| 107
| 325
|
/**
* Developer: Vladislav Smirnov
* Date: 23.01.2017
* Copyright: 2009-2017 Comindware®
* All Rights Reserved
*
* THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Comindware
* The copyright notice above does not evidence any
* actual or intended publication of such source code.
*/
import template from '../templates/toastNotification.html';
const notificationTypes = {
INFO: 'Info',
ERROR: 'Error',
SUCCESS: 'Success'
};
export default Marionette.ItemView.extend({
className() {
const sizeClass = this.model.get('title') ? 'dev-fr-alert-extended' : 'dev-fr-alert-compact';
switch (this.model.get('type')) {
case notificationTypes.SUCCESS:
return `${sizeClass} fr-alert dev-alert_success dev-fr-alert`;
case notificationTypes.ERROR:
return `${sizeClass} fr-alert fr-alert_error dev-fr-alert`;
case notificationTypes.INFO:
default:
return `${sizeClass} fr-alert dev-fr-alert`;
}
},
triggers: {
click: 'view:click'
},
template: Handlebars.compile(template)
});
| 23,066
|
https://github.com/Anton-Saurytski/gradle-plugin-cq-bundle/blob/master/src/main/groovy/com/twcable/gradle/sling/osgi/BundleServerConfiguration.groovy
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
gradle-plugin-cq-bundle
|
Anton-Saurytski
|
Groovy
|
Code
| 201
| 483
|
/*
* Copyright 2014-2017 Time Warner Cable, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twcable.gradle.sling.osgi
import com.twcable.gradle.sling.SlingServerConfiguration
import groovy.transform.TypeChecked
import javax.annotation.Nonnull
/**
* Enriches {@link SlingServerConfiguration} with additional information for dealing with bundles
*/
@TypeChecked
class BundleServerConfiguration {
static final String BUNDLE_CONTROL_BASE_PATH = '/system/console/bundles'
final SlingServerConfiguration serverConf
BundleServerConfiguration(SlingServerConfiguration serverConfiguration) {
this.serverConf = serverConfiguration
}
/**
* Returns the base URL to control a bundle.
*/
@Nonnull
URI getBundleControlBaseUri() {
URI base = serverConf.baseUri
return new URI(base.scheme, base.userInfo, base.host, base.port, BUNDLE_CONTROL_BASE_PATH, null, null)
}
/**
* Returns the URL to use to do actions on bundles.
*/
@Nonnull
URI getBundlesControlUri() {
URI base = serverConf.baseUri
return new URI(base.scheme, base.userInfo, base.host, base.port, "${BUNDLE_CONTROL_BASE_PATH}.json", null, null)
}
}
| 50,656
|
https://github.com/BluesYoung-web/blog-vitessg/blob/master/src/pages/[...all].vue
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
blog-vitessg
|
BluesYoung-web
|
Vue
|
Code
| 40
| 133
|
<!--
* @Author: zhangyang
* @Date: 2022-01-10 16:16:14
* @LastEditTime: 2022-01-25 10:29:22
* @Description: 404
-->
<script setup lang="ts">
const { t } = useI18n();
</script>
<template>
<div class="dark:text-gray-100">
{{ t('not-found') }}
</div>
</template>
<route lang="yaml">
meta:
layout: 404
</route>
| 40,065
|
https://github.com/maciek3000/GnuCash-Expenses-Vis/blob/master/tests/test_gnucash_db_parser.py
|
Github Open Source
|
Open Source
|
Unlicense
| 2,021
|
GnuCash-Expenses-Vis
|
maciek3000
|
Python
|
Code
| 683
| 2,949
|
import pandas as pd
import numpy as np
from datetime import date, datetime
def test_get_list_of_expense_transactions_example_book(gnucash_db_parser_example_book):
"""Testing returned list of expense transactions from Example GnuCash file"""
returned_list = gnucash_db_parser_example_book._GnuCashDBParser__get_list_of_transactions(
gnucash_db_parser_example_book.expense_name
)
assert len(returned_list) == 2480
def test_get_list_of_income_transactions_example_book(gnucash_db_parser_example_book):
"""Testing returned list of income transactions from Example GnuCash file"""
returned_list = gnucash_db_parser_example_book._GnuCashDBParser__get_list_of_transactions(
gnucash_db_parser_example_book.income_name
)
assert len(returned_list) == 24
def test_get_list_of_expense_transactions_simple_book(gnucash_db_parser_simple_book):
"""Testing returned list of expense transactions from simple piecash book (created manually)"""
curr = "PLN"
expected_transactions = [
("Apples #1", "2019-01-01", "nan", "Expenses:Main Type #1:Fruits:Apples", "5", curr),
("Eggs #1", "2019-01-02", "nan", "Expenses:Main Type #2:Dairy:Eggs", "10", curr),
("Other Apples", "2019-01-03", "nan", "Expenses:Main Type #1:Fruits:Apples", "4.5", curr),
("Shop #1", "2019-01-10", "Apples #1", "Expenses:Main Type #1:Fruits:Apples", "3", curr),
("Shop #1", "2019-01-10", "Eggs #1", "Expenses:Main Type #2:Dairy:Eggs", "7", curr),
("Shop #2", "2019-01-11", "Other Apples", "Expenses:Main Type #1:Fruits:Apples", "3", curr),
("Shop #2", "2019-01-11", "Apples #1", "Expenses:Main Type #1:Fruits:Apples", "5", curr)
]
returned_list = gnucash_db_parser_simple_book._GnuCashDBParser__get_list_of_transactions(
gnucash_db_parser_simple_book.expense_name
)
assert len(returned_list) == 7
for expected_tr, returned_tr in zip(expected_transactions, returned_list):
for exp_elem, ret_elem in zip(expected_tr, returned_tr):
assert exp_elem == ret_elem
def test_get_list_of_income_transactions_simple_book(gnucash_db_parser_simple_book):
"""Testing returned list of income transactions from simple piecash book (created manually)"""
curr = "PLN"
expected_income_list = [
("Salary", "2019-01-01", "nan", "Income:Income #1", "-1000", curr),
("Salary", "2019-01-01", "nan", "Income:Income #2", "-1500", curr)
]
actual_income_list = gnucash_db_parser_simple_book._GnuCashDBParser__get_list_of_transactions(
gnucash_db_parser_simple_book.income_name
)
assert len(actual_income_list) == 2
for expected_income, actual_income in zip(expected_income_list, actual_income_list):
for exp_elem, act_elem in zip(expected_income, actual_income):
assert act_elem == exp_elem
def test_create_expense_df_from_simple_book(gnucash_db_parser_simple_book):
"""Testing Expense DataFrame returned by GnucashDBParser from simple piecash book (created manually)"""
d = {
"Date": ["01-Jan-2019", "02-Jan-2019", "03-Jan-2019", "10-Jan-2019", "11-Jan-2019"],
"Price": 37.5,
"Currency": "PLN",
"Product": ["Apples #1", "Eggs #1", "Other Apples"],
"Shop": ["Shop #1", "Shop #2"],
"ALL_CATEGORIES": ["Expenses:Main Type #1:Fruits:Apples", "Expenses:Main Type #2:Dairy:Eggs"],
"Type": ["Main Type #1", "Main Type #2"],
"Category": ["Apples", "Eggs"],
"MonthYear": ["2019-01"]
}
df = gnucash_db_parser_simple_book.get_expenses_df()
assert len(df.columns) == 9
keys = list(d.keys())
keys.remove("Price")
keys.remove("Currency")
keys.remove("Date")
keys.remove("ALL_CATEGORIES")
for col in keys:
unique = list(df[col].unique())
for elem in unique:
if not pd.isna(elem):
assert elem in d[col]
# Price
assert df['Price'].sum() == d['Price']
# Currency
unique_curr = df['Currency'].unique()
assert unique_curr[0] == 'PLN' and len(unique_curr) == 1
# Dates
dates = df['Date'].unique()
for single_date in dates:
assert pd.to_datetime(str(single_date)).strftime("%d-%b-%Y") in d['Date']
# ALL_CATEGORIES
for elem in df['ALL_CATEGORIES']:
assert elem in d['ALL_CATEGORIES']
def test_create_income_df_from_simple_book(gnucash_db_parser_simple_book):
"""Testing Income DataFrame returned by GnucashDBParser from simple piecash book (created manually)"""
expected_df = pd.DataFrame(
data={
"Product": ["Salary", "Salary"],
"Shop": [np.nan, np.nan],
"Date": ([date(year=2019, month=1, day=1)]*2),
"Price": [-1000.0, -1500.0],
"MonthYear": ["2019-01", "2019-01"],
"ALL_CATEGORIES": ["Income:Income #1", "Income:Income #2"],
"Currency": ["PLN", "PLN"],
"Type": ["Income #1", "Income #2"],
"Category": ["Income #1", "Income #2"]
}
)
expected_df["Date"] = pd.to_datetime(expected_df["Date"], yearfirst=True)
expected_df["Shop"] = expected_df["Shop"].astype("object")
actual_df = gnucash_db_parser_simple_book.get_income_df()
assert set(actual_df.columns) == set(expected_df.columns)
expected_df = expected_df[actual_df.columns]
assert actual_df.equals(expected_df)
def test_create_expense_df_from_example_book(gnucash_db_parser_example_book):
"""Testing Expense DataFrame returned by GnucashDBParser from Example Gnucash file"""
all_categories = set(map(lambda x: "Expenses:Family:" + x, [
"Grocery:Bread",
"Grocery:Eggs",
"Grocery:Meat",
"Grocery:Chips",
"Grocery:Fruits and Vegetables",
"Car:Petrol",
"Flat:Rent",
"Flat:Water and Electricity",
"Bathroom:Toilet",
"Bathroom:Personal - John",
"Bathroom:Personal - Susan",
"Other"
])).union(["Expenses:John's Expenses:Clothes",
"Expenses:Susan's Expenses:Clothes", ])
shops = ["Grocery Shop #1", "Grocery Shop #2"]
date_range = pd.date_range("01-Jan-2019", "31-Dec-2019")
types = ["Family", "John's Expenses", "Susan's Expenses"]
products = [
"Clothes",
"White Bread",
"Rye Bread",
"Butter",
"Chicken",
"Cow",
"Eggs",
"Chips",
"Lollipops",
"Apple",
"Banana",
"Tomato",
"Pear",
"Petrol",
"Rent",
"Water and Electricity",
"Toilet Paper",
"Facial Tissues",
"Beard Balm",
"Shampoo",
"Face Cleanser",
"Other"
]
categories = [
"Clothes",
"Bread",
"Eggs",
"Fruits and Vegetables",
"Meat",
"Chips",
"Petrol",
"Rent",
"Water and Electricity",
"Toilet",
"Personal - John",
"Personal - Susan",
"Other"
]
test_dict = {
"Shop": shops,
"Date": date_range,
"Type": types,
"Category": categories,
"Product": products
}
df = gnucash_db_parser_example_book.get_expenses_df()
assert len(df) == 2480
# cols from test_dict
for col in test_dict.keys():
unique = df[col].unique()
for elem in unique:
if not pd.isna(elem):
assert elem in test_dict[col]
# ALL_CATEGORIES
for elem in df["ALL_CATEGORIES"]:
assert elem in all_categories
# Price
assert round(df["Price"].sum(), 2) == 55653.90
def test_create_income_df_from_example_book(gnucash_db_parser_example_book):
"""Testing Income DataFrame returned by GnucashDBParser from Example Gnucash file"""
expected_df = pd.DataFrame(
data={
"Product": (["Salary"]*24),
"Price": ([-3000.0]*24),
"Shop": ([np.nan]*24),
"ALL_CATEGORIES": (["Income:John's Income", "Income:Susan's Income"]*12),
"Currency": (["PLN"]*24),
"Type": (["John's Income", "Susan's Income"]*12),
"Category": (["John's Income", "Susan's Income"]*12),
}
)
expected_df["Shop"] = expected_df["Shop"].astype("object")
expected_df["Date"] = pd.Series(sorted([datetime(year=2019, day=25, month=x) for x in range(1, 13)]*2))
expected_df["MonthYear"] = expected_df["Date"].dt.strftime("%Y-%m")
actual_df = gnucash_db_parser_example_book.get_income_df()
for col in expected_df.columns:
assert actual_df[col].equals(expected_df[col])
| 33,185
|
https://github.com/dimitarminchev/ITCareer/blob/master/07. Software Development/2021/3. Debugging/Demo/Console.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ITCareer
|
dimitarminchev
|
C#
|
Code
| 93
| 316
|
namespace Demo
{
internal static class Console
{
/// <summary>
/// Метод за отпечатване
/// </summary>
/// <param name="message">Съобщение</param>
public static void WriteLine(object message)
{
// Отпечатваме съобщение
System.Console.WriteLine(message);
}
/// <summary>
/// Метод за негативно отпечатване
/// </summary>
/// <param name="message">Съобщение</param>
public static void WriteNegative(object message)
{
// Текущи стойности на цвета на конзолята
var bc = System.Console.BackgroundColor;
var fc = System.Console.ForegroundColor;
// Смяна на цвета на конзолата
System.Console.BackgroundColor = System.ConsoleColor.Green;
System.Console.ForegroundColor = System.ConsoleColor.Black;
// Отпечатваме съобщение
System.Console.WriteLine(message);
// Връщане на оригиналните настройки
System.Console.BackgroundColor = bc;
System.Console.ForegroundColor = fc;
}
}
}
| 22,443
|
https://github.com/king/results-cache-service/blob/master/build.gradle
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
results-cache-service
|
king
|
Gradle
|
Code
| 105
| 510
|
import org.codehaus.groovy.runtime.GStringImpl
// Copyright (C) king.com Ltd 2019
// https://github.com/king/results-cache-service
// License: Apache 2.0, https://raw.githubusercontent.com/king/results-cache-service/master/LICENSE-APACHE
plugins {
id 'java'
id 'org.springframework.boot' version '2.0.5.RELEASE'
}
ext {
gradleExtensions = "${rootProject.projectDir}/gradle" as GStringImpl
versions = [
gradle : '6.8',
junit : '4.12',
hamcrest : '1.3',
logback : '1.2.3',
ehcache : '3.5.2',
swagger : '2.8.0',
boot : '2.0.5.RELEASE',
spring : '5.1.0.RELEASE'
]
}
apply from: "${gradleExtensions}/repositories.gradle"
apply from: "${gradleExtensions}/spring-boot.gradle"
apply from: "${gradleExtensions}/ide.gradle"
apply from: "${gradleExtensions}/java.gradle"
wrapper {
gradleVersion = versions.gradle
}
configurations.all {
// Check for updates every build
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}
dependencies {
implementation "org.springframework.boot:spring-boot-dependencies:${versions.boot}"
implementation "org.ehcache:ehcache:${versions.ehcache}"
implementation "ch.qos.logback:logback-classic:${versions.logback}"
implementation "ch.qos.logback:logback-core:${versions.logback}"
implementation "io.springfox:springfox-swagger2:${versions.swagger}"
implementation "io.springfox:springfox-swagger-ui:${versions.swagger}"
}
| 40,208
|
https://github.com/cedrou/cpp-multiformats/blob/master/include/multiformats/uvarint.h
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
cpp-multiformats
|
cedrou
|
C
|
Code
| 311
| 917
|
#pragma once
#include "common.h"
namespace multiformats {
namespace uvarint {
namespace details {
template <typename T, typename ValueType> struct Iterator_value_type { typedef ValueType type; };
template <typename T> struct Iterator_value_type<T, void> { typedef typename T::container_type::value_type type; };
template <typename Iter> struct IteratorValueType { typedef typename Iterator_value_type<Iter, typename Iter::value_type>::type type; };
template <typename Iter> struct IteratorValueType<Iter*> { typedef Iter type; };
}
const size_t max_varint_size = 9;
const uint64_t max_value = 0x7FFF'FFFF'FFFF'FFFF;
template <typename T, typename OutputIt>
inline OutputIt encode(T value, OutputIt outIt)
{
using OutputType = typename details::IteratorValueType<OutputIt>::type;
static_assert(std::is_integral<T>::value || std::is_enum<T>::value, "Integral type is required.");
static_assert(sizeof(OutputType) == 1, "Output iterator value type must be 8 bits.");
using uT = typename std::make_unsigned<T>::type;
auto uvalue = static_cast<uT>(value);
if (uvalue > max_value) throw std::out_of_range("value to encode to uvarint type is too large");
auto out = buffer_t{};
auto outIter = std::back_inserter(out);
*outIter++ = gsl::narrow<OutputType>(uvalue & 0x7F);
uvalue >>= 7;
while (uvalue)
{
*outIter++ = gsl::narrow<OutputType>( (uvalue & 0x7F) | 0x80 );
uvalue >>= 7;
}
//return std::copy(std::rbegin(out), std::rend(out), first);
auto begin = std::rbegin(out);
auto end = std::rend(out);
for (auto it = begin; it != end; ++it)
{
*outIt++ = *it;
}
return outIt;
}
template <typename T>
inline buffer_t encode(T value)
{
auto out = buffer_t{};
encode(value, std::back_inserter(out));
return out;
}
template <typename T, typename InputIt>
inline InputIt decode(InputIt first, InputIt last, T* pOut)
{
auto out = uint64_t{ 0 };
auto stop = false;
while (!stop && first != last) {
if (first == last) throw std::exception("Invalid input data");
auto value = gsl::narrow<unsigned char>(*first++);
stop = !(value & 0x80);
out <<= 7;
out += value & 0x7F;
}
*pOut = gsl::narrow<T>(out);
return first;
}
template <typename T>
inline bufferview_t decode(bufferview_t src, T* pOut) {
auto it = decode(src.begin(), src.end(), pOut);
return src.last(src.end() - it);
}
inline uint64_t decode(bufferview_t in)
{
auto out = uint64_t{ 0 };
decode(std::begin(in), std::end(in), &out);
return out;
}
}
}
| 24,483
|
https://github.com/cunla/RPSP/blob/master/src/main/java/com/emc/rpsp/fal/commons/PhoenixClusterState.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
RPSP
|
cunla
|
Java
|
Code
| 352
| 985
|
package com.emc.rpsp.fal.commons;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement
@XmlType(name = "PhoenixClusterState")
public class PhoenixClusterState {
private ClusterUID cluster;
private String clusterName;
private long diskCapacity;
private Long availableDisk;
private PhoenixClusterStatus status;
public PhoenixClusterState() {
}
public PhoenixClusterState(ClusterUID cluster, String clusterName, long diskCapacity, Long availableDisk, PhoenixClusterStatus status) {
this.cluster = cluster;
this.clusterName = clusterName;
this.diskCapacity = diskCapacity;
this.availableDisk = availableDisk;
this.status = status;
}
public ClusterUID getCluster() {
return cluster;
}
public void setCluster(ClusterUID cluster) {
this.cluster = cluster;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public long getDiskCapacity() {
return diskCapacity;
}
public void setDiskCapacity(long diskCapacity) {
this.diskCapacity = diskCapacity;
}
public Long getAvailableDisk() {
return availableDisk;
}
public void setAvailableDisk(Long availableDisk) {
this.availableDisk = availableDisk;
}
public PhoenixClusterStatus getStatus() {
return status;
}
public void setStatus(PhoenixClusterStatus status) {
this.status = status;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((availableDisk == null) ? 0 : availableDisk.hashCode());
result = prime * result
+ ((clusterName == null) ? 0 : clusterName.hashCode());
result = prime * result + (int) (diskCapacity ^ (diskCapacity >>> 32));
result = prime * result + ((cluster == null) ? 0 : cluster.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PhoenixClusterState other = (PhoenixClusterState) obj;
if (availableDisk == null) {
if (other.availableDisk != null)
return false;
} else if (!availableDisk.equals(other.availableDisk))
return false;
if (clusterName == null) {
if (other.clusterName != null)
return false;
} else if (!clusterName.equals(other.clusterName))
return false;
if (diskCapacity != other.diskCapacity)
return false;
if (cluster == null) {
if (other.cluster != null)
return false;
} else if (!cluster.equals(other.cluster))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PhoenixClusterState [availableDisk=").append(
availableDisk).append(", clusterName=").append(clusterName)
.append(", diskCapacity=").append(diskCapacity).append(
", cluster=").append(cluster).append(", status=").append(
status).append("]");
return builder.toString();
}
}
| 46,391
|
https://github.com/ronaldoussoren/py2app/blob/master/src/py2app/recipes/pygame.py
|
Github Open Source
|
Open Source
|
MIT, Python-2.0
| 2,023
|
py2app
|
ronaldoussoren
|
Python
|
Code
| 63
| 199
|
import os
import typing
from modulegraph.modulegraph import ModuleGraph
from .. import build_app
from ._types import RecipeInfo
def check(cmd: "build_app.py2app", mf: ModuleGraph) -> typing.Optional[RecipeInfo]:
m = mf.findNode("pygame")
if m is None or m.filename is None:
return None
def addpath(f: str) -> str:
assert m is not None
assert m.filename is not None
return os.path.join(os.path.dirname(m.filename), f)
RESOURCES = ["freesansbold.ttf", "pygame_icon.icns"]
return {"loader_files": [("pygame", list(map(addpath, RESOURCES)))]}
| 27,985
|
https://github.com/JKJUN527/eshunter-version2/blob/master/resources/views/components/wheelmenu.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
eshunter-version2
|
JKJUN527
|
Blade
|
Code
| 89
| 452
|
<script src="{{asset('js/jquery.wheelmenu.js')}}" type="text/javascript"></script>
<div class="QQ_each">
<a class="wheel-button float_qq" href="#wheel" style="opacity: 1;"></a>
<ul class="wheel" id="wheel">
<li class="item">
<a href="#"></a>
</li>
<li class="item">
<a href="#"></a>
</li>
<li class="item">
<a href="#"></a>
</li>
<li class="item">
<a href="#"></a>
</li>
<li class="item">
<a class="bj" href="/position/advanceSearch" target="_blank">寻找<br>工作</a></li>
<li class="item">
<a class="wk" href="/position/publish" target="_blank">发布<br>职位</a></li>
<li class="item">
<a class="ts" href="/about" target="_blank">联系<br>我们</a></li>
<li class="item">
<a href="#"></a>
</li>
<li class="item">
<a href="#"></a>
</li>
<li class="item">
<a href="#"></a>
</li>
</ul>
</div>
{{--<a style="display:none;margin-left: 1340px;" class="back_to_top" title="" href="#"></a>--}}
<script type="text/javascript">
$(".wheel-button").wheelmenu({
// alert(1);
trigger: "hover",
animation: "fly",
angle: [0, 360]
});
</script>
| 37,068
|
https://github.com/SeregPie/PicMap/blob/master/src/core/CSS/font.js
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
PicMap
|
SeregPie
|
JavaScript
|
Code
| 18
| 44
|
// todo
export default function(family, size, style, variant, weight) {
return [style, variant, weight, `${size}px`, family].join(' ');
}
| 4,175
|
https://github.com/harangju/cascades/blob/master/analysis/dynamics/csc_durations.m
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
cascades
|
harangju
|
MATLAB
|
Code
| 19
| 49
|
function d = csc_durations(Y)
% returns cascade duration for cell array, Y, of cascades
d = cellfun(@(x) size(x,2)-1,Y);
end
| 15,674
|
https://github.com/Grupo-Intecsa/catalogo-virtual/blob/master/src/views/Cmenu/Cmenu.js
|
Github Open Source
|
Open Source
|
MIT
| null |
catalogo-virtual
|
Grupo-Intecsa
|
JavaScript
|
Code
| 75
| 267
|
import React, { Fragment } from 'react'
import { CLink } from '@coreui/react'
const Cmenu = ({ props }) => {
return(
<Fragment>
<div className="menuTop">
{Object.values(props).slice(0, Object.values(props).length - 1 ).map((item, index) => {
return(
<div key={`${index} ${item._id}`}>
<CLink
onClick={() => document.body.scrollTop = 0 }
to={`/product/${(props.cardname).toLowerCase()}/${item._id}`}
className="nolink d-flex justify-content-between menu--categorias--container">
<p>
{item.title}
<br />
{item.count}
</p>
</CLink>
</div>
)}
)}
</div>
</Fragment>
)
}
// window.scrollTo(0,0) ya no se quiere ir para arriba
export default Cmenu
| 41,812
|
https://github.com/whstruts/thinkingWMS/blob/master/src/components/Selector/ItemType/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
thinkingWMS
|
whstruts
|
JavaScript
|
Code
| 7
| 16
|
import ItemType from './ItemType.vue'
export default ItemType
| 9,772
|
https://github.com/Syzygianinfern0/espnet/blob/master/espnet2/samplers/unsorted_batch_sampler.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
espnet
|
Syzygianinfern0
|
Python
|
Code
| 231
| 661
|
import logging
from typing import Iterator
from typing import Tuple
from typeguard import check_argument_types
from espnet2.samplers.abs_sampler import AbsSampler
from espnet2.utils.fileio import read_2column_text
class UnsortedBatchSampler(AbsSampler):
"""BatchSampler with constant batch-size.
Any sorting is not done in this class,
so no length information is required,
This class is convenient for decoding mode,
or not seq2seq learning e.g. classification.
Args:
batch_size:
key_file:
"""
def __init__(self, batch_size: int, key_file: str, drop_last: bool = False):
assert check_argument_types()
assert batch_size > 0
self.batch_size = batch_size
self.key_file = key_file
self.drop_last = drop_last
# utt2shape:
# uttA <anything is o.k>
# uttB <anything is o.k>
utt2any = read_2column_text(key_file)
if len(utt2any) == 0:
logging.warning(f"{key_file} is empty")
# In this case the, the first column in only used
keys = list(utt2any)
if len(keys) == 0:
raise RuntimeError(f"0 lines found: {key_file}")
# Apply max(, 1) to avoid 0-batches
N = max(len(keys) // batch_size, 1)
if not self.drop_last:
# Split keys evenly as possible as. Note that If N != 1,
# the these batches always have size of batch_size at minimum.
self.batch_list = [
keys[i * len(keys) // N : (i + 1) * len(keys) // N] for i in range(N)
]
else:
self.batch_list = [
tuple(keys[i * batch_size : (i + 1) * batch_size]) for i in range(N)
]
def __repr__(self):
return (
f"{self.__class__.__name__}("
f"N-batch={len(self)}, "
f"batch_size={self.batch_size}, "
f"key_file={self.key_file}, "
)
def __len__(self):
return len(self.batch_list)
def __iter__(self) -> Iterator[Tuple[str, ...]]:
return iter(self.batch_list)
| 33,533
|
https://github.com/vacaly/Alink/blob/master/core/src/main/java/com/alibaba/alink/common/pyrunner/fn/PyFnFactory.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
Alink
|
vacaly
|
Java
|
Code
| 265
| 1,702
|
package com.alibaba.alink.common.pyrunner.fn;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;
import com.alibaba.alink.common.exceptions.AkUnclassifiedErrorException;
import com.alibaba.alink.common.exceptions.AkUnsupportedOperationException;
import com.alibaba.alink.common.pyrunner.fn.impl.PyBigDecimalScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyBooleanScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyByteScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyDateScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyDoubleScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyFloatScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyIntegerScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyLongScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyMTableScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyShortScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyStringScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyTensorScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyTimeScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyTimestampScalarFn;
import com.alibaba.alink.common.pyrunner.fn.impl.PyVectorScalarFn;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PyFnFactory {
private static final Map <String, Class <?>> SCALAR_FN_MAPPING = new HashMap <>();
static {
SCALAR_FN_MAPPING.put("BOOL", PyBooleanScalarFn.class);
SCALAR_FN_MAPPING.put("BOOLEAN", PyBooleanScalarFn.class);
SCALAR_FN_MAPPING.put("BYTE", PyByteScalarFn.class);
SCALAR_FN_MAPPING.put("TINYINT", PyByteScalarFn.class);
SCALAR_FN_MAPPING.put("SHORT", PyShortScalarFn.class);
SCALAR_FN_MAPPING.put("SMALLINT", PyShortScalarFn.class);
SCALAR_FN_MAPPING.put("INT", PyIntegerScalarFn.class);
SCALAR_FN_MAPPING.put("INTEGER", PyIntegerScalarFn.class);
SCALAR_FN_MAPPING.put("BIGINT", PyLongScalarFn.class);
SCALAR_FN_MAPPING.put("LONG", PyLongScalarFn.class);
SCALAR_FN_MAPPING.put("FLOAT", PyFloatScalarFn.class);
SCALAR_FN_MAPPING.put("DOUBLE", PyDoubleScalarFn.class);
SCALAR_FN_MAPPING.put("BIG_DEC", PyBigDecimalScalarFn.class);
SCALAR_FN_MAPPING.put("BIGDECIMAL", PyBigDecimalScalarFn.class);
SCALAR_FN_MAPPING.put("DECIMAL", PyBigDecimalScalarFn.class);
SCALAR_FN_MAPPING.put("STRING", PyStringScalarFn.class);
SCALAR_FN_MAPPING.put("VARCHAR", PyStringScalarFn.class);
SCALAR_FN_MAPPING.put("TIMESTAMP", PyTimestampScalarFn.class);
SCALAR_FN_MAPPING.put("DATETIME", PyTimestampScalarFn.class);
SCALAR_FN_MAPPING.put("DATE", PyDateScalarFn.class);
SCALAR_FN_MAPPING.put("TIME", PyTimeScalarFn.class);
SCALAR_FN_MAPPING.put("VECTOR", PyVectorScalarFn.class);
SCALAR_FN_MAPPING.put("TENSOR", PyTensorScalarFn.class);
SCALAR_FN_MAPPING.put("MTABLE", PyMTableScalarFn.class);
}
public static ScalarFunction makeScalarFn(String name, String resultType, String fnSpecJson) {
return PyFnFactory.makeScalarFn(name, resultType, fnSpecJson, Collections.emptyMap());
}
public static ScalarFunction makeScalarFn(String name, String resultType, String fnSpecJson,
Map <String, String> runConfig) {
if (!SCALAR_FN_MAPPING.containsKey(resultType.toUpperCase())) {
throw new AkUnsupportedOperationException(
String.format("Invalid result type %s for Python scalar function.", resultType));
}
Class <?> clz = SCALAR_FN_MAPPING.get(resultType.toUpperCase());
try {
Constructor <?> constructor = clz.getConstructor(String.class, String.class, Map.class);
return (ScalarFunction) constructor.newInstance(name, fnSpecJson, runConfig);
} catch (InvocationTargetException | NoSuchMethodException | InstantiationException |
IllegalAccessException e) {
throw new AkUnclassifiedErrorException(String.format("Unable to construct %s.", clz.getSimpleName()), e);
}
}
public static TableFunction <Row> makeTableFn(String name, String fnSpecJson, List <String> resultTypes) {
return PyFnFactory.makeTableFn(name, fnSpecJson, resultTypes.toArray(new String[0]));
}
public static TableFunction <Row> makeTableFn(String name, String fnSpecJson, String[] resultTypes) {
return PyFnFactory.makeTableFn(name, fnSpecJson, resultTypes, Collections.emptyMap());
}
public static TableFunction <Row> makeTableFn(String name, String fnSpecJson, String[] resultTypes,
Map <String, String> runConfig) {
return new PyTableFn(name, fnSpecJson, resultTypes, runConfig);
}
}
| 992
|
https://github.com/Djohnnie/CSharpWars/blob/master/src/frontend/CSharpWars/Assets/External/Adic/Scripts/Framework/Attributes/Inject.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
CSharpWars
|
Djohnnie
|
C#
|
Code
| 141
| 296
|
using System;
namespace Adic {
/// <summary>
/// Marks a setter injection point.
///
/// If an identifier is provided, the injector looks the binder for a key with the given name.
///
/// If no identifier is provided, the injector looks the binder for a key of the type of the field/property.
/// </summary>
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Property |
AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public class Inject : Attribute {
/// <summary>The identifier of the binding to inject.</summary>
public object identifier;
/// <summary>
/// Initializes a new instance of the <see cref="Inject"/> class.
/// </summary>
public Inject() {
this.identifier = null;
}
/// <summary>
/// Initializes a new instance of the <see cref="Inject"/> class.
/// </summary>
/// <param name="identifier">The identifier of the binding to inject.</param>
public Inject(object identifier) {
this.identifier = identifier;
}
}
}
| 10,506
|
https://github.com/dlang/dmd/blob/master/compiler/test/fail_compilation/fail20000.d
|
Github Open Source
|
Open Source
|
BSL-1.0
| 2,023
|
dmd
|
dlang
|
D
|
Code
| 321
| 849
|
/*
TEST_OUTPUT:
---
fail_compilation/fail20000.d(25): Error: cast from `fail20000.DClass` to `fail20000.CppClass` not allowed in safe code
fail_compilation/fail20000.d(26): Error: cast from `fail20000.DInterface` to `fail20000.CppClass` not allowed in safe code
fail_compilation/fail20000.d(27): Error: cast from `fail20000.CppClass2` to `fail20000.CppClass` not allowed in safe code
fail_compilation/fail20000.d(28): Error: cast from `fail20000.CppInterface2` to `fail20000.CppClass` not allowed in safe code
fail_compilation/fail20000.d(30): Error: cast from `fail20000.DClass` to `fail20000.CppInterface` not allowed in safe code
fail_compilation/fail20000.d(31): Error: cast from `fail20000.DInterface` to `fail20000.CppInterface` not allowed in safe code
fail_compilation/fail20000.d(32): Error: cast from `fail20000.CppClass2` to `fail20000.CppInterface` not allowed in safe code
fail_compilation/fail20000.d(33): Error: cast from `fail20000.CppInterface2` to `fail20000.CppInterface` not allowed in safe code
fail_compilation/fail20000.d(35): Error: cast from `fail20000.CppClass` to `fail20000.DClass` not allowed in safe code
fail_compilation/fail20000.d(36): Error: cast from `fail20000.CppInterface` to `fail20000.DClass` not allowed in safe code
fail_compilation/fail20000.d(38): Error: cast from `fail20000.CppClass` to `fail20000.DInterface` not allowed in safe code
fail_compilation/fail20000.d(39): Error: cast from `fail20000.CppInterface` to `fail20000.DInterface` not allowed in safe code
---
*/
extern(C++) class CppClass { int a; }
extern(C++) class CppClass2 { void* a; }
extern(C++) interface CppInterface { int b(); }
extern(C++) interface CppInterface2 { void* b(); }
class DClass { int c; }
interface DInterface { int d(); }
bool isCppClass(DClass a) @safe { return cast(CppClass) a !is null; }
bool isCppClass(DInterface a) @safe { return cast(CppClass) a !is null; }
bool isCppClass(CppClass2 a) @safe { return cast(CppClass) a !is null; }
bool isCppClass(CppInterface2 a) @safe { return cast(CppClass) a !is null; }
bool isCppInterface(DClass a) @safe { return cast(CppInterface) a !is null; }
bool isCppInterface(DInterface a) @safe { return cast(CppInterface) a !is null; }
bool isCppInterface(CppClass2 a) @safe { return cast(CppInterface) a !is null; }
bool isCppInterface(CppInterface2 a) @safe { return cast(CppInterface) a !is null; }
bool isDClass(CppClass a) @safe { return cast(DClass) a !is null; }
bool isDClass(CppInterface a) @safe { return cast(DClass) a !is null; }
bool isDInterface(CppClass a) @safe { return cast(DInterface) a !is null; }
bool isDInterface(CppInterface a) @safe { return cast(DInterface) a !is null; }
| 37,681
|
https://github.com/AsjadHasan/newton/blob/master/resources/views/admin/Mail/password_change_confirmation_mail.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
newton
|
AsjadHasan
|
PHP
|
Code
| 66
| 137
|
@component('mail::message')
# Done
You are receiving this email because we received a password change request for your account.
You are Changing your password ?
If ans is not than, From the forget password link, you can change your password.
@component('mail::button', ['url' => 'http://127.0.0.1:8000/password/reset'])
Forget Password Link
@endcomponent
If you did not request a password reset, no further action is required.
Regards,
<br>
{{ config('app.name') }}
@endcomponent
| 18,800
|
https://github.com/medav/spelunking/blob/master/topics/uarch-sec/cc-side-channel/attack-test/spy.c
|
Github Open Source
|
Open Source
|
MIT
| null |
spelunking
|
medav
|
C
|
Code
| 490
| 1,355
|
#include "common.h"
typedef enum {
reset = 0,
recv = 1,
boundary = 2
} SpyState;
#define AVG_SIZE 1000
unsigned long long avg(unsigned long long arr[AVG_SIZE]) {
unsigned long long sum = 0;
for (int i = 0; i < AVG_SIZE; i++) {
sum += arr[i];
}
return sum / AVG_SIZE;
}
static __inline__ unsigned long long rdtsc(void)
{
unsigned hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}
static void wait_cycles(unsigned long long num_cycles) {
volatile unsigned long long endtime = rdtsc() + num_cycles;
while (rdtsc() < endtime) {}
}
static inline void flush(const char *adrs) {
asm __volatile__ ("mfence\nclflush 0(%0)" : : "r" (adrs) :);
}
static inline unsigned long long time_access_no_flush(const char *adrs) {
volatile unsigned long time;
asm __volatile__ (
" mfence \n"
" lfence \n"
" rdtsc \n"
" lfence \n"
" movl %%eax, %%esi \n"
" movl (%1), %%eax \n"
" lfence \n"
" rdtsc \n"
" subl %%esi, %%eax \n"
: "=a" (time)
: "c" (adrs)
: "%esi", "%edx");
return time;
}
int main() {
//printf("Started Spy\n");
pin_thread(6);
char msg[1000];
int msg_idx = 0;
void * shlib = dlopen("./shlib.so", RTLD_LAZY);
void * mem = dlsym(shlib, "get_foo");
unsigned long long tarr[AVG_SIZE];
int cur_idx = 0;
SpyState state = reset;
uint8_t cur_byte = 0;
uint8_t cur_bit = 0;
unsigned long long t = 0;
int counter = 0;
int reset_counter = 0;
for (int s = 0; s < T_step; s++) {
tarr[cur_idx] = time_access_no_flush((void *)mem);
flush(mem);
cur_idx = (cur_idx + 1) % AVG_SIZE;
}
unsigned long long next_sample_time = rdtsc() + T_step;
unsigned long long wait_count = 0;
while (1) {
while (rdtsc() < next_sample_time) {wait_count += 1;}
next_sample_time += T_step;
tarr[cur_idx] = time_access_no_flush((void *)mem);
flush(mem);
cur_idx = (cur_idx + 1) % AVG_SIZE;
t = avg(tarr);
//continue;
if (state == reset && t > CYC_thresh) {
state = recv;
counter = 0;
cur_byte = 0;
cur_bit = 0;
}
else if (state == recv) {
counter += 1;
if (t < CYC_thresh) {
state = boundary;
reset_counter = 0;
// printf("%d\n", counter);
if (counter > T_thresh) {
cur_byte |= (1 << cur_bit);
}
cur_bit++;
if (cur_bit == 8) {
msg[msg_idx++] = cur_byte;
if (msg_idx >= 1000) msg_idx = 0;
cur_byte = 0;
cur_bit = 0;
}
}
}
else if (state == boundary) {
reset_counter += 1;
if (t > CYC_thresh) {
if (reset_counter < T_boundary - T_tol) {
state = reset;
}
state = recv;
counter = 0;
}
if (reset_counter > T_reset - 10) {
reset_counter = 0;
state = reset;
msg[msg_idx] = 0;
for (int i = 0; i < msg_idx; i++) {
if (!((msg[i] >= 'A' && msg[i] <= 'Z') || (msg[i] >= 'a' && msg[i] <= 'z'))) {
msg[i] = ' ';
}
}
printf("\nReset\n");
printf("msg = /%s/\n", msg);
printf("msg_idx = %d\n", msg_idx);
printf("wait_count = %lld\n", wait_count);
wait_count = 0;
msg_idx = 0;
fflush(stdout);
}
}
}
return 0;
}
| 2,080
|
https://github.com/TheLarkInn/isomorphic-git/blob/master/src/commands/push.js
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
isomorphic-git
|
TheLarkInn
|
JavaScript
|
Code
| 1,007
| 2,455
|
import pad from 'pad'
import pako from 'pako'
import path from 'path'
import createHash from 'sha.js'
import { PassThrough } from 'stream'
import { GitObjectManager, GitRefManager, GitRemoteManager } from '../managers'
import { FileSystem, GitCommit, GitPktLine, GitTree } from '../models'
import { log, pkg } from '../utils'
import { config } from './config'
const types = {
commit: 0b0010000,
tree: 0b0100000,
blob: 0b0110000,
tag: 0b1000000,
ofs_delta: 0b1100000,
ref_delta: 0b1110000
}
/**
* Push a branch
*
* @link https://isomorphic-git.github.io/docs/push.html
*/
export async function push ({
dir,
gitdir = path.join(dir, '.git'),
fs: _fs,
emitter,
ref,
remote = 'origin',
url,
authUsername,
authPassword
}) {
const fs = new FileSystem(_fs)
// TODO: Figure out how pushing tags works. (This only works for branches.)
if (url === undefined) {
url = await config({ fs, gitdir, path: `remote.${remote}.url` })
}
let fullRef = ref.startsWith('refs/') ? ref : `refs/heads/${ref}`
let oid = await GitRefManager.resolve({ fs, gitdir, ref })
let auth
if (authUsername !== undefined && authPassword !== undefined) {
auth = {
username: authUsername,
password: authPassword
}
}
let GitRemoteHTTP = GitRemoteManager.getRemoteHelperFor({ url })
let httpRemote = await GitRemoteHTTP.discover({
service: 'git-receive-pack',
url,
auth
})
let commits = await listCommits({
fs,
gitdir,
start: [oid],
finish: httpRemote.refs.values()
})
let objects = await listObjects({ fs, gitdir, oids: commits })
let packstream = new PassThrough()
let oldoid =
httpRemote.refs.get(fullRef) || '0000000000000000000000000000000000000000'
const capabilities = `report-status side-band-64k agent=git/${pkg.name}@${
pkg.version
}`
packstream.write(
GitPktLine.encode(`${oldoid} ${oid} ${fullRef}\0 ${capabilities}\n`)
)
packstream.write(GitPktLine.flush())
pack({
fs,
gitdir,
oids: [...objects],
outputStream: packstream
})
let { packfile, progress } = await GitRemoteHTTP.connect({
service: 'git-receive-pack',
url,
auth,
stream: packstream
})
if (emitter) {
progress.on('data', chunk => {
let msg = chunk.toString('utf8')
emitter.emit('message', msg)
})
}
let result = {}
// Parse the response!
let response = ''
let read = GitPktLine.streamReader(packfile)
let line = await read()
while (line !== true) {
if (line !== null) response += line.toString('utf8') + '\n'
line = await read()
}
let lines = response.toString('utf8').split('\n')
// We're expecting "unpack {unpack-result}"
line = lines.shift()
if (!line.startsWith('unpack ')) {
throw new Error(
`Unparsable response from server! Expected 'unpack ok' or 'unpack [error message]' but got '${line}'`
)
}
if (line === 'unpack ok') {
result.ok = ['unpack']
} else {
result.errors = [line.trim()]
}
for (let line of lines) {
let status = line.slice(0, 2)
let refAndMessage = line.slice(3)
if (status === 'ok') {
result.ok = result.ok || []
result.ok.push(refAndMessage)
} else if (status === 'ng') {
result.errors = result.errors || []
result.errors.push(refAndMessage)
}
}
log(result)
return result
}
export async function listCommits ({
dir,
gitdir = path.join(dir, '.git'),
fs: _fs,
start,
finish
}) {
const fs = new FileSystem(_fs)
let startingSet = new Set()
let finishingSet = new Set()
for (let ref of start) {
startingSet.add(await GitRefManager.resolve({ fs, gitdir, ref }))
}
for (let ref of finish) {
// We may not have these refs locally so we must try/catch
try {
let oid = await GitRefManager.resolve({ fs, gitdir, ref })
finishingSet.add(oid)
} catch (err) {}
}
let visited = new Set()
// Because git commits are named by their hash, there is no
// way to construct a cycle. Therefore we won't worry about
// setting a default recursion limit.
async function walk (oid) {
visited.add(oid)
let { type, object } = await GitObjectManager.read({ fs, gitdir, oid })
if (type !== 'commit') {
throw new Error(`Expected type commit but type is ${type}`)
}
let commit = GitCommit.from(object)
let parents = commit.headers().parent
for (oid of parents) {
if (!finishingSet.has(oid) && !visited.has(oid)) {
await walk(oid)
}
}
}
// Let's go walking!
for (let oid of startingSet) {
await walk(oid)
}
return visited
}
export async function listObjects ({
dir,
gitdir = path.join(dir, '.git'),
fs: _fs,
oids
}) {
const fs = new FileSystem(_fs)
let visited = new Set()
// We don't do the purest simplest recursion, because we can
// avoid reading Blob objects entirely since the Tree objects
// tell us which oids are Blobs and which are Trees.
async function walk (oid) {
visited.add(oid)
let { type, object } = await GitObjectManager.read({ fs, gitdir, oid })
if (type === 'commit') {
let commit = GitCommit.from(object)
let tree = commit.headers().tree
await walk(tree)
} else if (type === 'tree') {
let tree = GitTree.from(object)
for (let entry of tree) {
visited.add(entry.oid)
// only recurse for trees
if (entry.type === 'tree') {
await walk(entry.oid)
}
}
}
}
// Let's go walking!
for (let oid of oids) {
await walk(oid)
}
return visited
}
export async function pack ({
dir,
gitdir = path.join(dir, '.git'),
fs: _fs,
oids,
outputStream
}) {
const fs = new FileSystem(_fs)
let hash = createHash('sha1')
function write (chunk, enc) {
outputStream.write(chunk, enc)
hash.update(chunk, enc)
}
function writeObject ({ stype, object }) {
let lastFour, multibyte, length
// Object type is encoded in bits 654
let type = types[stype]
if (type === undefined) throw new Error('Unrecognized type: ' + stype)
// The length encoding get complicated.
length = object.length
// Whether the next byte is part of the variable-length encoded number
// is encoded in bit 7
multibyte = length > 0b1111 ? 0b10000000 : 0b0
// Last four bits of length is encoded in bits 3210
lastFour = length & 0b1111
// Discard those bits
length = length >>> 4
// The first byte is then (1-bit multibyte?), (3-bit type), (4-bit least sig 4-bits of length)
let byte = (multibyte | type | lastFour).toString(16)
write(byte, 'hex')
// Now we keep chopping away at length 7-bits at a time until its zero,
// writing out the bytes in what amounts to little-endian order.
while (multibyte) {
multibyte = length > 0b01111111 ? 0b10000000 : 0b0
byte = multibyte | (length & 0b01111111)
write(pad(2, byte.toString(16), '0'), 'hex')
length = length >>> 7
}
// Lastly, we can compress and write the object.
write(Buffer.from(pako.deflate(object)))
}
write('PACK')
write('00000002', 'hex')
// Write a 4 byte (32-bit) int
write(pad(8, oids.length.toString(16), '0'), 'hex')
for (let oid of oids) {
let { type, object } = await GitObjectManager.read({ fs, gitdir, oid })
writeObject({ write, object, stype: type })
}
// Write SHA1 checksum
let digest = hash.digest()
outputStream.end(digest)
return outputStream
}
| 17,365
|
https://github.com/Bonsaikitt3n/RubyRedditAPI/blob/master/lib/ruby_reddit_api/submission.rb
|
Github Open Source
|
Open Source
|
MIT, Ruby
| 2,012
|
RubyRedditAPI
|
Bonsaikitt3n
|
Ruby
|
Code
| 232
| 678
|
# @author James Cook
module Reddit
class Submission < Thing
include JsonListing
include Voteable
attr_reader :domain, :media_embed, :subreddit, :selftext_html, :selftext, :likes, :saved, :clicked, :media, :score, :over_18, :hidden, :thumbnail, :subreddit_id, :downs, :is_self, :permalink, :name, :created, :url, :title, :created_utc, :num_comments, :ups, :kind, :last_comment_id
def inspect
"<Reddit::Submission id='#{id}' author='#{@author}' title='#{title}'>"
end
# Add a comment to a submission
# @param [String] Comment text
# @return [true,false]
def add_comment(text)
resp = self.class.post("/api/comment", {:body => {:thing_id => id, :text => text, :uh => modhash, :r => subreddit }, :headers => base_headers, :debug_output => @debug })
resp.code == 200
end
# Save submission
# @return [true,false]
def save
toggle :save
end
# Unsave submission
# @return [true,false]
def unsave
toggle :unsave
end
# Hide submission
# @return [true,false]
def hide
toggle :hide
end
# Unhide submission
# @return [true,false]
def unhide
toggle :unhide
end
def moderator_distinguish
add_distinction "yes"
end
def admin_distinguish
add_distinction "admin"
end
def indistinguish
add_distinction "no"
end
# Fetch submission comments
# @todo Move to 'Thing' class
# @return [Array<Reddit::Comment>]
def comments
_comments = read( permalink + ".json", {:handler => "Comment", :query => {:limit => 250}} )
@last_comment_id = _comments.last.id if _comments && _comments.any?
_comments.shift # First 'comment' is actually the submission
return _comments
end
protected
def add_distinction(verb)
resp=self.class.post("/api/distinguish/#{verb}", {:body => {:id => id, :uh => modhash, :r => subreddit, :executed => "distinguishing..."}, :headers => base_headers, :debug_output => @debug })
resp.code == 200
end
end
end
| 49,321
|
https://github.com/bloomreach/bloomgateway/blob/master/cli/bg_s3cli/scripts/module_rule_factory.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
bloomgateway
|
bloomreach
|
Python
|
Code
| 195
| 423
|
#
# Copyright 2016 BloomReach, Inc.
# Copyright 2016 Ronak Kothari <ronak.kothari@gmail.com>.
#
# 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.
#
###knows how to build rules based on module, rule_data
###throws exception if data invalid or insufficient to build rule
from utils import module_rule_utils
from rate_limiter_rule import RateLimiterRule
from access_control_rule import AccessControlRule
from router_rule import RouterRule
class ModuleRuleFactory:
@staticmethod
def buildModule(module_name, rule_dict):
"""builds the corresponding module rule
return rule if build successfully
throws exception if error in building rule
TODO handle error conditions
"""
module_rule = None
if(module_name == module_rule_utils.ratelimiter_module):
module_rule = RateLimiterRule(rule_dict)
elif(module_name == module_rule_utils.access_module):
module_rule = AccessControlRule(rule_dict)
elif(module_name == module_rule_utils.router_module):
module_rule = RouterRule(rule_dict)
#TODO handle module == None case
return module_rule
| 298
|
https://github.com/sjug/cluster-node-tuning-operator/blob/master/assets/tuned/daemon/tests/unit/func_basic.sh
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
cluster-node-tuning-operator
|
sjug
|
Shell
|
Code
| 32
| 89
|
#!/bin/bash
systemctl restart tuned
tuned-adm recommend
PROFILES=`tuned-adm list | sed -n '/^\-/ s/^- // p'`
for p in $PROFILES
do
tuned-adm profile "$p"
sleep 5
tuned-adm active
done
tuned-adm profile `tuned-adm recommend`
| 12,163
|
https://github.com/rklyne/traikoa/blob/master/src/traikoa/eddn.cr
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
traikoa
|
rklyne
|
Crystal
|
Code
| 39
| 147
|
require "logger"
require "./eddn/data"
require "./eddn/parser"
require "./eddn/client"
module Traikoa
# EDDN ([GitHub](https://github.com/jamesremuscat/EDDN))
module EDDN
# EDDN version
VERSION = "0.6.2"
# EDDN TCP relay URL
RELAY_URL = "tcp://eddn.edcd.io:9500"
# Logger for gateway Events
LOGGER = Logger.new(STDOUT)
end
end
| 557
|
https://github.com/Xferno2/Hearts-Of-Iron-IV-Launcher/blob/master/Hoi4 Launcher/Parser/descriptorGenerator.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
Hearts-Of-Iron-IV-Launcher
|
Xferno2
|
C#
|
Code
| 360
| 1,124
|
using Hoi4_Launcher.Utility;
using SharpCompress.Readers;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Hoi4_Launcher.Parser
{
class descriptorGenerator
{
public string modsFolder;
public string[] mods;
public bool isPathValid = false;
public Exception exception;
public descriptorGenerator(string thisPath)
{
this.modsFolder = workshop(thisPath);
try
{
mods = Directory.GetDirectories(modsFolder);
this.isPathValid = true;
}
catch (Exception ex) {
string message = "I couldn't find the path to the mods directory." +
Environment.NewLine+
"Perhaps this is not a steam install?" +
Environment.NewLine +
"Either way descriptor.mod is disabled. If you think this is an issue, open one on github."+
Environment.NewLine +
"More info in Log tab!";
string title = "Something intresting happened";
MessageBox.Show(message, title);
Properties.Settings.Default.generateDescriptor = false;
Properties.Settings.Default.Save();
this.exception = ex;
}
}
public string workshop(string path) => path.Split(new string[] { "steamapps" }, StringSplitOptions.None)[0] + "steamapps\\workshop\\content\\394360";
public bool createDescriptorFile(string path, string savePath, string id)
{
DirectoryInfo dInfo = new DirectoryInfo(path);
FileInfo zipFile;
try
{
zipFile = dInfo.GetFilesByExtensions(new string[] { ".rar", ".zip", ".7z" }).First();
}
catch (Exception ex) {
zipFile = null;
}
// We are going to check if descriptor.mod exists
if (File.Exists(dInfo.FullName + "\\descriptor.mod"))
{
if (!File.Exists(savePath + "\\ugc_" + id + ".mod")){
var descriptorFile = editDescriptor(File.ReadAllText(dInfo.FullName + "\\descriptor.mod"), dInfo.FullName);
System.IO.File.WriteAllLines(savePath + "\\ugc_" + id + ".mod", descriptorFile);
}
return true;
}
else if (zipFile != null)
{
if (!File.Exists(savePath + "\\ugc_" + id + ".mod"))
{
try
{
using (Stream stream = File.OpenRead(zipFile.FullName))
using (var reader = ReaderFactory.Open(stream))
{
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory && reader.Entry.Key == "descriptor.mod")
{
reader.WriteEntryToFile(@"tempDescriptor.mod");
var descriptorFile = editDescriptor(File.ReadAllText(@"tempDescriptor.mod"), zipFile.FullName);
System.IO.File.WriteAllLines(savePath + "\\ugc_" + id + ".mod", descriptorFile);
break;
}
}
}
}
catch (Exception ex) { }
}
if (File.Exists(@"tempDescriptor.mod"))
{
File.Delete(@"tempDescriptor.mod");
}
return true;
}
else
{
return false;
}
}
// this rlly needs a rewrite
private string[] editDescriptor(string descriptor, string path)
{
bool doesItContainPath = false;
List<string> descriptorFile = new List<string>();
foreach (var line in descriptor.Split(new string[] { Environment.NewLine, "\n\t", "\n\r", "\n"}, StringSplitOptions.RemoveEmptyEntries))
{
var currentLine = line;
if (line.Split('=').First().ToLower() == "path")
{
currentLine = "path=" + "\""+ path +"\"";
doesItContainPath = true;
}
descriptorFile.Add(currentLine);
}
if (!doesItContainPath)
{
descriptorFile.Add("path=" + path);
}
return descriptorFile.ToArray();
}
}
}
| 11,962
|
https://github.com/eliasespinosa6/guardian/blob/master/Assembly-CSharp/NGUI/UIDraggablePanel.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
guardian
|
eliasespinosa6
|
C#
|
Code
| 1,632
| 5,780
|
using System;
using UnityEngine;
[ExecuteInEditMode]
[RequireComponent(typeof(UIPanel))]
[AddComponentMenu("NGUI/Interaction/Draggable Panel")]
public class UIDraggablePanel : IgnoreTimeScale
{
public delegate void OnDragFinished();
public enum DragEffect
{
None,
Momentum,
MomentumAndSpring
}
public enum ShowCondition
{
Always,
OnlyIfNeeded,
WhenDragging
}
public bool restrictWithinPanel = true;
public bool disableDragIfFits;
public DragEffect dragEffect = DragEffect.MomentumAndSpring;
public bool smoothDragStart = true;
public Vector3 scale = Vector3.one;
public float scrollWheelFactor;
public float momentumAmount = 35f;
public Vector2 relativePositionOnReset = Vector2.zero;
public bool repositionClipping;
public bool iOSDragEmulation = true;
public UIScrollBar horizontalScrollBar;
public UIScrollBar verticalScrollBar;
public ShowCondition showScrollBars = ShowCondition.OnlyIfNeeded;
public OnDragFinished onDragFinished;
private Transform mTrans;
private UIPanel mPanel;
private Plane mPlane;
private Vector3 mLastPos;
private bool mPressed;
private Vector3 mMomentum = Vector3.zero;
private float mScroll;
private Bounds mBounds;
private bool mCalculatedBounds;
private bool mShouldMove;
private bool mIgnoreCallbacks;
private int mDragID = -10;
private Vector2 mDragStartOffset = Vector2.zero;
private bool mDragStarted;
public UIPanel panel => mPanel;
public Bounds bounds
{
get
{
if (!mCalculatedBounds)
{
mCalculatedBounds = true;
mBounds = NGUIMath.CalculateRelativeWidgetBounds(mTrans, mTrans);
}
return mBounds;
}
}
public bool shouldMoveHorizontally
{
get
{
Vector3 size = bounds.size;
float num = size.x;
if (mPanel.clipping == UIDrawCall.Clipping.SoftClip)
{
float num2 = num;
Vector2 clipSoftness = mPanel.clipSoftness;
num = num2 + clipSoftness.x * 2f;
}
float num3 = num;
Vector4 clipRange = mPanel.clipRange;
return num3 > clipRange.z;
}
}
public bool shouldMoveVertically
{
get
{
Vector3 size = bounds.size;
float num = size.y;
if (mPanel.clipping == UIDrawCall.Clipping.SoftClip)
{
float num2 = num;
Vector2 clipSoftness = mPanel.clipSoftness;
num = num2 + clipSoftness.y * 2f;
}
float num3 = num;
Vector4 clipRange = mPanel.clipRange;
return num3 > clipRange.w;
}
}
private bool shouldMove
{
get
{
if (!disableDragIfFits)
{
return true;
}
if (mPanel == null)
{
mPanel = GetComponent<UIPanel>();
}
Vector4 clipRange = mPanel.clipRange;
Bounds bounds = this.bounds;
float num = (clipRange.z != 0f) ? (clipRange.z * 0.5f) : ((float)Screen.width);
float num2 = (clipRange.w != 0f) ? (clipRange.w * 0.5f) : ((float)Screen.height);
if (!Mathf.Approximately(scale.x, 0f))
{
Vector3 min = bounds.min;
if (min.x < clipRange.x - num)
{
return true;
}
Vector3 max = bounds.max;
if (max.x > clipRange.x + num)
{
return true;
}
}
if (!Mathf.Approximately(scale.y, 0f))
{
Vector3 min2 = bounds.min;
if (min2.y < clipRange.y - num2)
{
return true;
}
Vector3 max2 = bounds.max;
if (max2.y > clipRange.y + num2)
{
return true;
}
}
return false;
}
}
public Vector3 currentMomentum
{
get
{
return mMomentum;
}
set
{
mMomentum = value;
mShouldMove = true;
}
}
private void Awake()
{
mTrans = base.transform;
mPanel = GetComponent<UIPanel>();
UIPanel uIPanel = mPanel;
uIPanel.onChange = (UIPanel.OnChangeDelegate)Delegate.Combine(uIPanel.onChange, new UIPanel.OnChangeDelegate(OnPanelChange));
}
private void OnDestroy()
{
if (mPanel != null)
{
UIPanel uIPanel = mPanel;
uIPanel.onChange = (UIPanel.OnChangeDelegate)Delegate.Remove(uIPanel.onChange, new UIPanel.OnChangeDelegate(OnPanelChange));
}
}
private void OnPanelChange()
{
UpdateScrollbars(recalculateBounds: true);
}
private void Start()
{
UpdateScrollbars(recalculateBounds: true);
if (horizontalScrollBar != null)
{
UIScrollBar uIScrollBar = horizontalScrollBar;
uIScrollBar.onChange = (UIScrollBar.OnScrollBarChange)Delegate.Combine(uIScrollBar.onChange, new UIScrollBar.OnScrollBarChange(OnHorizontalBar));
horizontalScrollBar.alpha = ((showScrollBars != 0 && !shouldMoveHorizontally) ? 0f : 1f);
}
if (verticalScrollBar != null)
{
UIScrollBar uIScrollBar2 = verticalScrollBar;
uIScrollBar2.onChange = (UIScrollBar.OnScrollBarChange)Delegate.Combine(uIScrollBar2.onChange, new UIScrollBar.OnScrollBarChange(OnVerticalBar));
verticalScrollBar.alpha = ((showScrollBars != 0 && !shouldMoveVertically) ? 0f : 1f);
}
}
public bool RestrictWithinBounds(bool instant)
{
Vector3 vector = mPanel.CalculateConstrainOffset(bounds.min, bounds.max);
if (vector.magnitude > 0.001f)
{
if (!instant && dragEffect == DragEffect.MomentumAndSpring)
{
SpringPanel.Begin(mPanel.gameObject, mTrans.localPosition + vector, 13f);
}
else
{
MoveRelative(vector);
mMomentum = Vector3.zero;
mScroll = 0f;
}
return true;
}
return false;
}
public void DisableSpring()
{
SpringPanel component = GetComponent<SpringPanel>();
if (component != null)
{
component.enabled = false;
}
}
public void UpdateScrollbars(bool recalculateBounds)
{
if (mPanel == null)
{
return;
}
if (horizontalScrollBar != null || verticalScrollBar != null)
{
if (recalculateBounds)
{
mCalculatedBounds = false;
mShouldMove = shouldMove;
}
Bounds bounds = this.bounds;
Vector2 vector = bounds.min;
Vector2 vector2 = bounds.max;
if (mPanel.clipping == UIDrawCall.Clipping.SoftClip)
{
Vector2 clipSoftness = mPanel.clipSoftness;
vector -= clipSoftness;
vector2 += clipSoftness;
}
if (horizontalScrollBar != null && vector2.x > vector.x)
{
Vector4 clipRange = mPanel.clipRange;
float num = clipRange.z * 0.5f;
float num2 = clipRange.x - num;
Vector3 min = bounds.min;
float num3 = num2 - min.x;
Vector3 max = bounds.max;
float num4 = max.x - num - clipRange.x;
float num5 = vector2.x - vector.x;
num3 = Mathf.Clamp01(num3 / num5);
num4 = Mathf.Clamp01(num4 / num5);
float num6 = num3 + num4;
mIgnoreCallbacks = true;
horizontalScrollBar.barSize = 1f - num6;
horizontalScrollBar.scrollValue = ((!(num6 > 0.001f)) ? 0f : (num3 / num6));
mIgnoreCallbacks = false;
}
if (verticalScrollBar != null && vector2.y > vector.y)
{
Vector4 clipRange2 = mPanel.clipRange;
float num7 = clipRange2.w * 0.5f;
float num8 = clipRange2.y - num7 - vector.y;
float num9 = vector2.y - num7 - clipRange2.y;
float num10 = vector2.y - vector.y;
num8 = Mathf.Clamp01(num8 / num10);
num9 = Mathf.Clamp01(num9 / num10);
float num11 = num8 + num9;
mIgnoreCallbacks = true;
verticalScrollBar.barSize = 1f - num11;
verticalScrollBar.scrollValue = ((!(num11 > 0.001f)) ? 0f : (1f - num8 / num11));
mIgnoreCallbacks = false;
}
}
else if (recalculateBounds)
{
mCalculatedBounds = false;
}
}
public void SetDragAmount(float x, float y, bool updateScrollbars)
{
DisableSpring();
Bounds bounds = this.bounds;
Vector3 min = bounds.min;
float x2 = min.x;
Vector3 max = bounds.max;
if (x2 == max.x)
{
return;
}
Vector3 min2 = bounds.min;
float y2 = min2.y;
Vector3 max2 = bounds.max;
if (y2 == max2.y)
{
return;
}
Vector4 clipRange = mPanel.clipRange;
float num = clipRange.z * 0.5f;
float num2 = clipRange.w * 0.5f;
Vector3 min3 = bounds.min;
float num3 = min3.x + num;
Vector3 max3 = bounds.max;
float num4 = max3.x - num;
Vector3 min4 = bounds.min;
float num5 = min4.y + num2;
Vector3 max4 = bounds.max;
float num6 = max4.y - num2;
if (mPanel.clipping == UIDrawCall.Clipping.SoftClip)
{
float num7 = num3;
Vector2 clipSoftness = mPanel.clipSoftness;
num3 = num7 - clipSoftness.x;
float num8 = num4;
Vector2 clipSoftness2 = mPanel.clipSoftness;
num4 = num8 + clipSoftness2.x;
float num9 = num5;
Vector2 clipSoftness3 = mPanel.clipSoftness;
num5 = num9 - clipSoftness3.y;
float num10 = num6;
Vector2 clipSoftness4 = mPanel.clipSoftness;
num6 = num10 + clipSoftness4.y;
}
float num11 = Mathf.Lerp(num3, num4, x);
float num12 = Mathf.Lerp(num6, num5, y);
if (!updateScrollbars)
{
Vector3 localPosition = mTrans.localPosition;
if (scale.x != 0f)
{
localPosition.x += clipRange.x - num11;
}
if (scale.y != 0f)
{
localPosition.y += clipRange.y - num12;
}
mTrans.localPosition = localPosition;
}
clipRange.x = num11;
clipRange.y = num12;
mPanel.clipRange = clipRange;
if (updateScrollbars)
{
UpdateScrollbars(recalculateBounds: false);
}
}
public void ResetPosition()
{
mCalculatedBounds = false;
SetDragAmount(relativePositionOnReset.x, relativePositionOnReset.y, updateScrollbars: false);
SetDragAmount(relativePositionOnReset.x, relativePositionOnReset.y, updateScrollbars: true);
}
private void OnHorizontalBar(UIScrollBar sb)
{
if (!mIgnoreCallbacks)
{
float x = horizontalScrollBar == null ? 0f : horizontalScrollBar.scrollValue;
float y = verticalScrollBar == null ? 0f : verticalScrollBar.scrollValue;
SetDragAmount(x, y, updateScrollbars: false);
}
}
private void OnVerticalBar(UIScrollBar sb)
{
if (!mIgnoreCallbacks)
{
float x = horizontalScrollBar == null ? 0f : horizontalScrollBar.scrollValue;
float y = verticalScrollBar == null ? 0f : verticalScrollBar.scrollValue;
SetDragAmount(x, y, updateScrollbars: false);
}
}
public void MoveRelative(Vector3 relative)
{
mTrans.localPosition += relative;
Vector4 clipRange = mPanel.clipRange;
clipRange.x -= relative.x;
clipRange.y -= relative.y;
mPanel.clipRange = clipRange;
UpdateScrollbars(recalculateBounds: false);
}
public void MoveAbsolute(Vector3 absolute)
{
Vector3 a = mTrans.InverseTransformPoint(absolute);
Vector3 b = mTrans.InverseTransformPoint(Vector3.zero);
MoveRelative(a - b);
}
public void Press(bool pressed)
{
if (smoothDragStart && pressed)
{
mDragStarted = false;
mDragStartOffset = Vector2.zero;
}
if (!base.enabled || !NGUITools.GetActive(base.gameObject))
{
return;
}
if (!pressed && mDragID == UICamera.currentTouchID)
{
mDragID = -10;
}
mCalculatedBounds = false;
mShouldMove = shouldMove;
if (!mShouldMove)
{
return;
}
mPressed = pressed;
if (pressed)
{
mMomentum = Vector3.zero;
mScroll = 0f;
DisableSpring();
mLastPos = UICamera.lastHit.point;
mPlane = new Plane(mTrans.rotation * Vector3.back, mLastPos);
return;
}
if (restrictWithinPanel && mPanel.clipping != 0 && dragEffect == DragEffect.MomentumAndSpring)
{
RestrictWithinBounds(instant: false);
}
if (onDragFinished != null)
{
onDragFinished();
}
}
public void Drag()
{
if (!base.enabled || !NGUITools.GetActive(base.gameObject) || !mShouldMove)
{
return;
}
if (mDragID == -10)
{
mDragID = UICamera.currentTouchID;
}
UICamera.currentTouch.clickNotification = UICamera.ClickNotification.BasedOnDelta;
if (smoothDragStart && !mDragStarted)
{
mDragStarted = true;
mDragStartOffset = UICamera.currentTouch.totalDelta;
}
Ray ray = (!smoothDragStart) ? UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos) : UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos - mDragStartOffset);
float enter = 0f;
if (mPlane.Raycast(ray, out enter))
{
Vector3 point = ray.GetPoint(enter);
Vector3 vector = point - mLastPos;
mLastPos = point;
if (vector.x != 0f || vector.y != 0f)
{
vector = mTrans.InverseTransformDirection(vector);
vector.Scale(scale);
vector = mTrans.TransformDirection(vector);
}
mMomentum = Vector3.Lerp(mMomentum, mMomentum + vector * (0.01f * momentumAmount), 0.67f);
if (!iOSDragEmulation)
{
MoveAbsolute(vector);
}
else if (mPanel.CalculateConstrainOffset(bounds.min, bounds.max).magnitude > 0.001f)
{
MoveAbsolute(vector * 0.5f);
mMomentum *= 0.5f;
}
else
{
MoveAbsolute(vector);
}
if (restrictWithinPanel && mPanel.clipping != 0 && dragEffect != DragEffect.MomentumAndSpring)
{
RestrictWithinBounds(instant: true);
}
}
}
public void Scroll(float delta)
{
if (base.enabled && NGUITools.GetActive(base.gameObject) && scrollWheelFactor != 0f)
{
DisableSpring();
mShouldMove = shouldMove;
if (Mathf.Sign(mScroll) != Mathf.Sign(delta))
{
mScroll = 0f;
}
mScroll += delta * scrollWheelFactor;
}
}
private void LateUpdate()
{
if (repositionClipping)
{
repositionClipping = false;
mCalculatedBounds = false;
SetDragAmount(relativePositionOnReset.x, relativePositionOnReset.y, updateScrollbars: true);
}
if (!Application.isPlaying)
{
return;
}
float num = UpdateRealTimeDelta();
if (showScrollBars != 0)
{
bool flag = false;
bool flag2 = false;
if (showScrollBars != ShowCondition.WhenDragging || mDragID != -10 || mMomentum.magnitude > 0.01f)
{
flag = shouldMoveVertically;
flag2 = shouldMoveHorizontally;
}
if ((bool)verticalScrollBar)
{
float alpha = verticalScrollBar.alpha;
alpha += ((!flag) ? ((0f - num) * 3f) : (num * 6f));
alpha = Mathf.Clamp01(alpha);
if (verticalScrollBar.alpha != alpha)
{
verticalScrollBar.alpha = alpha;
}
}
if ((bool)horizontalScrollBar)
{
float alpha2 = horizontalScrollBar.alpha;
alpha2 += ((!flag2) ? ((0f - num) * 3f) : (num * 6f));
alpha2 = Mathf.Clamp01(alpha2);
if (horizontalScrollBar.alpha != alpha2)
{
horizontalScrollBar.alpha = alpha2;
}
}
}
if (mShouldMove && !mPressed)
{
mMomentum -= scale * (mScroll * 0.05f);
if (mMomentum.magnitude > 0.0001f)
{
mScroll = NGUIMath.SpringLerp(mScroll, 0f, 20f, num);
Vector3 absolute = NGUIMath.SpringDampen(ref mMomentum, 9f, num);
MoveAbsolute(absolute);
if (restrictWithinPanel && mPanel.clipping != 0)
{
RestrictWithinBounds(instant: false);
}
if (mMomentum.magnitude < 0.0001f && onDragFinished != null)
{
onDragFinished();
}
return;
}
mScroll = 0f;
mMomentum = Vector3.zero;
}
else
{
mScroll = 0f;
}
NGUIMath.SpringDampen(ref mMomentum, 9f, num);
}
}
| 43,467
|
https://github.com/ParkingAbility/parkingability/blob/master/src/Controllers/LocalesController.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
parkingability
|
ParkingAbility
|
C#
|
Code
| 65
| 242
|
using Microsoft.AspNetCore.Mvc;
using ParkingAbilityServer.BusinessLayer;
using ParkingAbilityServer.Models;
using System.Threading.Tasks;
namespace ParkingAbilityServer.Controllers
{
[Route("locales")]
public class LocalesController : Controller
{
private readonly IContentRepository repository;
private readonly IFlightProvider flightProvider;
public LocalesController(IContentRepository repository, IFlightProvider flightProvider)
{
this.repository = repository;
this.flightProvider = flightProvider;
}
[Route("{id}")]
[HttpGet]
public async Task<IActionResult> LocaleAsync(string id)
{
ViewData["Title"] = id;
LocaleViewModel viewModel = await repository.LoadAsync(id);
ViewData["Flight"] = await flightProvider.CalculateFlightAsync(id);
return View("Locales", viewModel);
}
}
}
| 26,790
|
https://github.com/lure9999/CardAndMonsterSanGuo/blob/master/client/cocos2d-x-2.2.6/projects/YLHDKaPaiSanGuo/Byte_Resources/Image/Fight/player/sunquan/sunquan0.plist
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
CardAndMonsterSanGuo
|
lure9999
|
XML Property List
|
Code
| 892
| 9,469
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>frames</key>
<dict>
<key>skill/sunquan_skill_3/sunquan_skill_3_1.png</key>
<dict>
<key>width</key>
<integer>100</integer>
<key>height</key>
<integer>60</integer>
<key>originalWidth</key>
<integer>100</integer>
<key>originalHeight</key>
<integer>60</integer>
<key>x</key>
<integer>0</integer>
<key>y</key>
<integer>0</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>skill/sunquan_skill_3/sunquan_skill_3_2.png</key>
<dict>
<key>width</key>
<integer>100</integer>
<key>height</key>
<integer>60</integer>
<key>originalWidth</key>
<integer>100</integer>
<key>originalHeight</key>
<integer>60</integer>
<key>x</key>
<integer>0</integer>
<key>y</key>
<integer>61</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>skill/sunquan_skill_3/sunquan_skill_3_3.png</key>
<dict>
<key>width</key>
<integer>100</integer>
<key>height</key>
<integer>60</integer>
<key>originalWidth</key>
<integer>100</integer>
<key>originalHeight</key>
<integer>60</integer>
<key>x</key>
<integer>101</integer>
<key>y</key>
<integer>0</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_7.png</key>
<dict>
<key>width</key>
<integer>100</integer>
<key>height</key>
<integer>8</integer>
<key>originalWidth</key>
<integer>100</integer>
<key>originalHeight</key>
<integer>8</integer>
<key>x</key>
<integer>101</integer>
<key>y</key>
<integer>61</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_3_1/sunquan_manualskill_3_5.png</key>
<dict>
<key>width</key>
<integer>100</integer>
<key>height</key>
<integer>84</integer>
<key>originalWidth</key>
<integer>100</integer>
<key>originalHeight</key>
<integer>84</integer>
<key>x</key>
<integer>0</integer>
<key>y</key>
<integer>122</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_3_1/sunquan_manualskill_3_4.png</key>
<dict>
<key>width</key>
<integer>150</integer>
<key>height</key>
<integer>29</integer>
<key>originalWidth</key>
<integer>150</integer>
<key>originalHeight</key>
<integer>29</integer>
<key>x</key>
<integer>101</integer>
<key>y</key>
<integer>70</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_3_1/sunquan_manualskill_3_3.png</key>
<dict>
<key>width</key>
<integer>150</integer>
<key>height</key>
<integer>31</integer>
<key>originalWidth</key>
<integer>150</integer>
<key>originalHeight</key>
<integer>31</integer>
<key>x</key>
<integer>101</integer>
<key>y</key>
<integer>100</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_3_1/sunquan_manualskill_3_2.png</key>
<dict>
<key>width</key>
<integer>150</integer>
<key>height</key>
<integer>59</integer>
<key>originalWidth</key>
<integer>150</integer>
<key>originalHeight</key>
<integer>59</integer>
<key>x</key>
<integer>101</integer>
<key>y</key>
<integer>132</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_3_1/sunquan_manualskill_3_1.png</key>
<dict>
<key>width</key>
<integer>150</integer>
<key>height</key>
<integer>59</integer>
<key>originalWidth</key>
<integer>150</integer>
<key>originalHeight</key>
<integer>59</integer>
<key>x</key>
<integer>101</integer>
<key>y</key>
<integer>192</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_2_1/sunquan_manualskill_2_1.png</key>
<dict>
<key>width</key>
<integer>150</integer>
<key>height</key>
<integer>126</integer>
<key>originalWidth</key>
<integer>150</integer>
<key>originalHeight</key>
<integer>126</integer>
<key>x</key>
<integer>252</integer>
<key>y</key>
<integer>0</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_2_1/sunquan_manualskill_2_2.png</key>
<dict>
<key>width</key>
<integer>150</integer>
<key>height</key>
<integer>126</integer>
<key>originalWidth</key>
<integer>150</integer>
<key>originalHeight</key>
<integer>126</integer>
<key>x</key>
<integer>252</integer>
<key>y</key>
<integer>127</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_2_1/sunquan_manualskill_2_3.png</key>
<dict>
<key>width</key>
<integer>150</integer>
<key>height</key>
<integer>126</integer>
<key>originalWidth</key>
<integer>150</integer>
<key>originalHeight</key>
<integer>126</integer>
<key>x</key>
<integer>0</integer>
<key>y</key>
<integer>252</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_1_1/sunquan_manualskill_1_4.png</key>
<dict>
<key>width</key>
<integer>80</integer>
<key>height</key>
<integer>69</integer>
<key>originalWidth</key>
<integer>80</integer>
<key>originalHeight</key>
<integer>69</integer>
<key>x</key>
<integer>0</integer>
<key>y</key>
<integer>379</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_1_1/sunquan_manualskill_1_3.png</key>
<dict>
<key>width</key>
<integer>100</integer>
<key>height</key>
<integer>117</integer>
<key>originalWidth</key>
<integer>100</integer>
<key>originalHeight</key>
<integer>117</integer>
<key>x</key>
<integer>151</integer>
<key>y</key>
<integer>252</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_1_1/sunquan_manualskill_1_2.png</key>
<dict>
<key>width</key>
<integer>200</integer>
<key>height</key>
<integer>99</integer>
<key>originalWidth</key>
<integer>200</integer>
<key>originalHeight</key>
<integer>99</integer>
<key>x</key>
<integer>81</integer>
<key>y</key>
<integer>379</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_1_1/sunquan_manualskill_1_1.png</key>
<dict>
<key>width</key>
<integer>150</integer>
<key>height</key>
<integer>29</integer>
<key>originalWidth</key>
<integer>150</integer>
<key>originalHeight</key>
<integer>29</integer>
<key>x</key>
<integer>252</integer>
<key>y</key>
<integer>254</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>skill/sunquan_skill_1/sunquan_skill_1_2.png</key>
<dict>
<key>width</key>
<integer>160</integer>
<key>height</key>
<integer>10</integer>
<key>originalWidth</key>
<integer>160</integer>
<key>originalHeight</key>
<integer>10</integer>
<key>x</key>
<integer>252</integer>
<key>y</key>
<integer>284</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>skill/sunquan_skill_1/sunquan_skill_1_1.png</key>
<dict>
<key>width</key>
<integer>160</integer>
<key>height</key>
<integer>10</integer>
<key>originalWidth</key>
<integer>160</integer>
<key>originalHeight</key>
<integer>10</integer>
<key>x</key>
<integer>252</integer>
<key>y</key>
<integer>295</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>skill/sunquan_skill_1/sunquan_skill_1_3.png</key>
<dict>
<key>width</key>
<integer>160</integer>
<key>height</key>
<integer>10</integer>
<key>originalWidth</key>
<integer>160</integer>
<key>originalHeight</key>
<integer>10</integer>
<key>x</key>
<integer>252</integer>
<key>y</key>
<integer>306</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>skill/sunquan_skill_2/sunquan_skill_2_1.png</key>
<dict>
<key>width</key>
<integer>80</integer>
<key>height</key>
<integer>87</integer>
<key>originalWidth</key>
<integer>80</integer>
<key>originalHeight</key>
<integer>87</integer>
<key>x</key>
<integer>403</integer>
<key>y</key>
<integer>0</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>skill/sunquan_skill_2/sunquan_skill_2_2.png</key>
<dict>
<key>width</key>
<integer>80</integer>
<key>height</key>
<integer>87</integer>
<key>originalWidth</key>
<integer>80</integer>
<key>originalHeight</key>
<integer>87</integer>
<key>x</key>
<integer>403</integer>
<key>y</key>
<integer>88</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>skill/sunquan_skill_2/sunquan_skill_2_3.png</key>
<dict>
<key>width</key>
<integer>80</integer>
<key>height</key>
<integer>87</integer>
<key>originalWidth</key>
<integer>80</integer>
<key>originalHeight</key>
<integer>87</integer>
<key>x</key>
<integer>403</integer>
<key>y</key>
<integer>176</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_2.png</key>
<dict>
<key>width</key>
<integer>51</integer>
<key>height</key>
<integer>50</integer>
<key>originalWidth</key>
<integer>51</integer>
<key>originalHeight</key>
<integer>50</integer>
<key>x</key>
<integer>0</integer>
<key>y</key>
<integer>449</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_4.png</key>
<dict>
<key>width</key>
<integer>106</integer>
<key>height</key>
<integer>117</integer>
<key>originalWidth</key>
<integer>106</integer>
<key>originalHeight</key>
<integer>117</integer>
<key>x</key>
<integer>282</integer>
<key>y</key>
<integer>317</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>manualskill/sunquan_manualskill_3.png</key>
<dict>
<key>width</key>
<integer>86</integer>
<key>height</key>
<integer>96</integer>
<key>originalWidth</key>
<integer>86</integer>
<key>originalHeight</key>
<integer>96</integer>
<key>x</key>
<integer>413</integer>
<key>y</key>
<integer>264</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>headdress03_sunquan.png</key>
<dict>
<key>width</key>
<integer>17</integer>
<key>height</key>
<integer>48</integer>
<key>originalWidth</key>
<integer>17</integer>
<key>originalHeight</key>
<integer>48</integer>
<key>x</key>
<integer>202</integer>
<key>y</key>
<integer>0</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>head_sunquan.png</key>
<dict>
<key>width</key>
<integer>73</integer>
<key>height</key>
<integer>66</integer>
<key>originalWidth</key>
<integer>73</integer>
<key>originalHeight</key>
<integer>66</integer>
<key>x</key>
<integer>282</integer>
<key>y</key>
<integer>435</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>headdress01_sunquan.png</key>
<dict>
<key>width</key>
<integer>57</integer>
<key>height</key>
<integer>45</integer>
<key>originalWidth</key>
<integer>57</integer>
<key>originalHeight</key>
<integer>45</integer>
<key>x</key>
<integer>389</integer>
<key>y</key>
<integer>361</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>face_sunquan.png</key>
<dict>
<key>width</key>
<integer>64</integer>
<key>height</key>
<integer>87</integer>
<key>originalWidth</key>
<integer>64</integer>
<key>originalHeight</key>
<integer>87</integer>
<key>x</key>
<integer>389</integer>
<key>y</key>
<integer>407</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>l_lingzi_sunquan.png</key>
<dict>
<key>width</key>
<integer>70</integer>
<key>height</key>
<integer>40</integer>
<key>originalWidth</key>
<integer>70</integer>
<key>originalHeight</key>
<integer>40</integer>
<key>x</key>
<integer>0</integer>
<key>y</key>
<integer>207</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>r_lingzi_sunquan.png</key>
<dict>
<key>width</key>
<integer>23</integer>
<key>height</key>
<integer>27</integer>
<key>originalWidth</key>
<integer>23</integer>
<key>originalHeight</key>
<integer>27</integer>
<key>x</key>
<integer>220</integer>
<key>y</key>
<integer>0</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>l_forearm_sunqan.png</key>
<dict>
<key>width</key>
<integer>27</integer>
<key>height</key>
<integer>27</integer>
<key>originalWidth</key>
<integer>27</integer>
<key>originalHeight</key>
<integer>27</integer>
<key>x</key>
<integer>220</integer>
<key>y</key>
<integer>28</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>l_shoulder_sunquan.png</key>
<dict>
<key>width</key>
<integer>56</integer>
<key>height</key>
<integer>41</integer>
<key>originalWidth</key>
<integer>56</integer>
<key>originalHeight</key>
<integer>41</integer>
<key>x</key>
<integer>447</integer>
<key>y</key>
<integer>361</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>l_arm_sunqan.png</key>
<dict>
<key>width</key>
<integer>39</integer>
<key>height</key>
<integer>51</integer>
<key>originalWidth</key>
<integer>39</integer>
<key>originalHeight</key>
<integer>51</integer>
<key>x</key>
<integer>454</integer>
<key>y</key>
<integer>403</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>l_hand_sunquan.png</key>
<dict>
<key>width</key>
<integer>22</integer>
<key>height</key>
<integer>22</integer>
<key>originalWidth</key>
<integer>22</integer>
<key>originalHeight</key>
<integer>22</integer>
<key>x</key>
<integer>71</integer>
<key>y</key>
<integer>207</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>r_shoulder_sunquan.png</key>
<dict>
<key>width</key>
<integer>31</integer>
<key>height</key>
<integer>29</integer>
<key>originalWidth</key>
<integer>31</integer>
<key>originalHeight</key>
<integer>29</integer>
<key>x</key>
<integer>52</integer>
<key>y</key>
<integer>479</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>r_piaodai_sunquan.png</key>
<dict>
<key>width</key>
<integer>16</integer>
<key>height</key>
<integer>23</integer>
<key>originalWidth</key>
<integer>16</integer>
<key>originalHeight</key>
<integer>23</integer>
<key>x</key>
<integer>484</integer>
<key>y</key>
<integer>0</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>l_piaodai_sunquan.png</key>
<dict>
<key>width</key>
<integer>35</integer>
<key>height</key>
<integer>27</integer>
<key>originalWidth</key>
<integer>35</integer>
<key>originalHeight</key>
<integer>27</integer>
<key>x</key>
<integer>84</integer>
<key>y</key>
<integer>479</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>l_skirt_sunquan.png</key>
<dict>
<key>width</key>
<integer>26</integer>
<key>height</key>
<integer>39</integer>
<key>originalWidth</key>
<integer>26</integer>
<key>originalHeight</key>
<integer>39</integer>
<key>x</key>
<integer>484</integer>
<key>y</key>
<integer>24</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>r_skirt_sunquan.png</key>
<dict>
<key>width</key>
<integer>19</integer>
<key>height</key>
<integer>38</integer>
<key>originalWidth</key>
<integer>19</integer>
<key>originalHeight</key>
<integer>38</integer>
<key>x</key>
<integer>484</integer>
<key>y</key>
<integer>64</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>guashi_sunquan.png</key>
<dict>
<key>width</key>
<integer>26</integer>
<key>height</key>
<integer>40</integer>
<key>originalWidth</key>
<integer>26</integer>
<key>originalHeight</key>
<integer>40</integer>
<key>x</key>
<integer>252</integer>
<key>y</key>
<integer>317</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>skirt_sunquan.png</key>
<dict>
<key>width</key>
<integer>45</integer>
<key>height</key>
<integer>53</integer>
<key>originalWidth</key>
<integer>45</integer>
<key>originalHeight</key>
<integer>53</integer>
<key>x</key>
<integer>454</integer>
<key>y</key>
<integer>455</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>r_forearm_sunqan.png</key>
<dict>
<key>width</key>
<integer>31</integer>
<key>height</key>
<integer>38</integer>
<key>originalWidth</key>
<integer>31</integer>
<key>originalHeight</key>
<integer>38</integer>
<key>x</key>
<integer>356</integer>
<key>y</key>
<integer>435</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>l_foot_sunquan.png</key>
<dict>
<key>width</key>
<integer>19</integer>
<key>height</key>
<integer>22</integer>
<key>originalWidth</key>
<integer>19</integer>
<key>originalHeight</key>
<integer>22</integer>
<key>x</key>
<integer>52</integer>
<key>y</key>
<integer>449</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
<key>r_foot_sunquan.png</key>
<dict>
<key>width</key>
<integer>19</integer>
<key>height</key>
<integer>25</integer>
<key>originalWidth</key>
<integer>19</integer>
<key>originalHeight</key>
<integer>25</integer>
<key>x</key>
<integer>484</integer>
<key>y</key>
<integer>103</integer>
<key>offsetX</key>
<real>0</real>
<key>offsetY</key>
<real>0</real>
</dict>
</dict>
<key>metadata</key>
<dict>
<key>format</key>
<integer>0</integer>
<key>textureFileName</key>
<string>sunquan0.png</string>
<key>realTextureFileName</key>
<string>sunquan0.png</string>
<key>size</key>
<string>{512,512}</string>
</dict>
<key>texture</key>
<dict>
<key>width</key>
<integer>512</integer>
<key>height</key>
<integer>512</integer>
</dict>
</dict>
</plist>
| 42,019
|
https://github.com/antonin-lfv/Matplotlib_and_plotly_tutorial/blob/master/plotly_ex.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Matplotlib_and_plotly_tutorial
|
antonin-lfv
|
Python
|
Code
| 2,346
| 10,923
|
""" Plotly examples """
#### importation --------------------------------------------------
from plotly.offline import plot # pour travailler en offline!
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from sklearn.datasets import load_digits
from umap import UMAP # pip install umap-learn
from sklearn.manifold import TSNE
import networkx as nx
#### Templates
templates_plotly = ['ggplot2', 'seaborn', 'simple_white', 'plotly',
'plotly_white', 'plotly_dark', 'presentation', 'xgridoff',
'ygridoff', 'gridon', 'none']
#### Plotly.Express -----------------------------------------------
# Scatter plot
"On personnalise les figures de plotly express suivant ce modèle : "
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", # nom de la colonne du dataframe
y="sepal_length", # nom de la colonne du dataframe
color="species", # nom de la colonne du dataframe
)
fig.update_layout(title="Scatter avec px et ajout d'une figure avec Go",
font_family="Rockwell")
fig.update_xaxes(title_text='largeur sepales')
fig.update_yaxes(title_text='longueur sepales')
fig.add_trace(
go.Scatter(
x=[2, 4],
y=[4, 8],
mode="lines",
marker=dict(color="gray"),
name="droite",
showlegend=True) # True par défaut
)
plot(fig)
"Si on veut superposer des courbes avec les données du même dataset on écrit : "
df = px.data.iris()
fig = px.line(df, y=["sepal_width", "sepal_length", "petal_width"],
#text="species_id" on ajoute ici l'id de l'espèce au dessus de chaque point
color_discrete_map={"sepal_width":"blue", "sepal_length":"black","petal_width":"green" }, # couleur de chaque ligne
)
plot(fig)
"On peut aussi séparer les figures en plusieurs, c'est le seul moyen de faire des subplots avec plotly express"
df = px.data.iris()
fig = px.line(df, y=["sepal_width", "sepal_length", "petal_width"],
#text="species_id" on ajoute ici l'id de l'espèce au dessus de chaque point
color_discrete_map={"sepal_width":"blue", "sepal_length":"black","petal_width":"green" }, # couleur de chaque ligne
facet_col="species" # ou facet_col pour séparer en colonne
)
plot(fig)
df = px.data.iris()
fig = px.line(df, y=["sepal_width", "sepal_length", "petal_width"],
#text="species_id" on ajoute ici l'id de l'espèce au dessus de chaque point
color_discrete_map={"sepal_width":"blue", "sepal_length":"black","petal_width":"green" }, # couleur de chaque ligne
facet_row="species" # ou facet_col pour séparer en colonne
)
plot(fig)
"création d'animations"
df = px.data.gapminder()
df_fr=df[df['country']=='France']
df_us=df[df['country']=='United States']
df = pd.concat([df_fr, df_us])
fig = px.scatter(df,
y="gdpPercap",
x="year",
color="country",
title="évolution pib france et USA",
range_x=[1952,2007],
range_y=[df['gdpPercap'].min(), df['gdpPercap'].max()],
animation_frame="year")
plot(fig)
"Personnalisation des axes avec un range slider visible"
df = px.data.carshare()
fig = px.line(df, y="car_hours",
#text="species_id" on ajoute ici l'id de l'espèce au dessus de chaque point
color_discrete_map={"car_hours":"black"}, # couleur de chaque ligne
)
fig.update_xaxes(rangeslider_visible=True)
plot(fig)
"Ajout de rectangle et de ligne"
df = px.data.stocks(indexed=True)
fig = px.line(df, facet_col="company",
facet_col_wrap=2 # nombre de figure par ligne
)
fig.add_hline( # ou vline pour verticale
y=1, line_dash="dot",
annotation_text="1er janvier 2018",
annotation_position="bottom right")
fig.add_vrect( # ou hrect pour horizontal
x0="2018-09-24", x1="2018-12-18",
col=2, # numéro de la colonne (les figures de droites)
annotation_text="24/09 au 18/12 2018",
annotation_position="top left",
fillcolor="red", opacity=0.2, line_width=0.1)
fig.add_hrect( # ou hrect pour horizontal
y0=1.1, y1=1.7,
col=1, # numéro de la colonne (les figures de droites)
annotation_text="1.1 à 1.7",
annotation_position="top right",
fillcolor="blue", opacity=0.15, line_width=0.4)
plot(fig)
"Avec indicateurs marginaux"
df = px.data.iris()
fig = px.scatter(df, x="sepal_length", # données
color="species", # couleur par expèce
marginal_x='box', # marge en boxplot
marginal_y='violin', # marge en violon
trendline="ols" # courbe de tendances
)
plot(fig)
"Curseur sur les axes"
df = px.data.gapminder().query("continent=='Oceania'")
fig = px.line(df, x="year", y="lifeExp", color="country",
title="curseurs")
fig.update_traces(mode="markers+lines") # courbe avec ligne et points apparent
fig.update_xaxes(showspikes=True)
fig.update_yaxes(showspikes=True)
plot(fig)
"plot 3D"
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
color='species', size='petal_length', size_max=18,symbol='species', opacity=1)
plot(fig)
# BarChart
"simple barchart, on colorie sur une colonne et on sépare par couleur"
df = px.data.tips()
fig=px.bar(df,
x="sex",
y="total_bill",
color="smoker",
barmode="group")
fig.update_traces( marker_line_color='rgb(8,48,107)',
marker_line_width=1.5, opacity=0.6)
plot(fig)
"histogramme avec marge en violon"
df = px.data.iris()
fig = px.histogram(df, x="sepal_length",
nbins=50, # on choisi le nombre de barres
marginal='violin' # rug, box
)
plot(fig)
"histogramme avec marge en boxplot"
df = px.data.iris()
fig = px.histogram(df, x="sepal_length",
nbins=50, # on choisi le nombre de barres
marginal='box'
)
plot(fig)
# PieChart
df = px.data.tips()
fig = px.pie(df, values='tip', # ce qu'on compte
names='day', # sur quoi on tri
color='day',
hole=.3, # donut chart
color_discrete_map={'Thur':'lightblue', # couleur spécifique par valeur
'Fri':'lightred',
'Sat':'gold',
'Sun':'green'})
plot(fig)
# Polar bar charts
df = px.data.wind()
fig = px.bar_polar(df, r="frequency", theta="direction", color="strength",
template="seaborn",
color_discrete_sequence= px.colors.sequential.Plasma_r)
plot(fig)
# ML
"regression linéaire"
from sklearn.linear_model import LinearRegression
df = px.data.tips()
X = df.total_bill.values.reshape(-1, 1)
model = LinearRegression()
model.fit(X, df.tip)
x_range = np.linspace(X.min(), X.max(), 100)
y_range = model.predict(x_range.reshape(-1, 1))
fig = px.scatter(df, x='total_bill', y='tip', opacity=0.65)
fig.add_traces(go.Scatter(x=x_range, y=y_range, name='Regression Fit'))
plot(fig)
"UMAP"
digits = load_digits()
umap_2d = UMAP(random_state=0)
umap_2d.fit(digits.data)
projections = umap_2d.transform(digits.data)
fig = px.scatter(
projections, x=0, y=1,
color=digits.target.astype(str), labels={'color': 'digit'}
)
plot(fig)
"tsne"
df = px.data.iris()
features = df.loc[:, :'petal_width']
tsne = TSNE(n_components=3, random_state=0)
projections = tsne.fit_transform(features, )
fig = px.scatter_3d(
projections, x=0, y=1, z=2,
color=df.species, labels={'color': 'species'}
)
fig.update_traces(marker_size=8)
plot(fig)
# Graphique de corrélations
df = px.data.iris()
fig = px.scatter_matrix(df, dimensions=["sepal_width", "sepal_length", "petal_width", "petal_length"], color="species")
plot(fig)
#### Plotly.graph_objects -----------------------------------------
# subplots
"pour un subplots on utilise un autre moyen pour initialiser la figure :"
fig = make_subplots(rows=2, cols=2,
#column_widths=[0.6, 0.4],
#row_heights=[0.3, 0.3, 0.3],
subplot_titles=["", "", ""],
specs=[[{'type': 'xy'}, {'type': 'domain'}], # 1er ligne
[{'type': 'xy', 'colspan': 2}, None]], # 2e ligne, dont la 1er colonne s'etend sur celle de droite
# si on s'etend sur une colonne on utilise rowspan
# il existe plusieurs type de specs : xy, domain, scene, polar, ternary, mapbox
#horizontal_spacing=0.2,
#vertical_spacing=0.5
)
"Ensuite on ajoute les figure normalement, en indiquant juste l'emplacement du graphique avec les paramètres row et col"
x=np.linspace(-4,4)
# 1er figure
fig.add_scatter(x=np.linspace(-4,4), y=np.tanh(x),
marker=dict(color='green'),
row=1, col=1, name="tangente hyperbolique"
)
# 2e figure
fig.add_pie(labels=['oui', 'non'],
values=[201902,192981], row=1, col=2)
# 3e figure
fig.add_traces( # je vais ajouter 2 courbes en même temps sur la dernière ligne
[
go.Scatter(x=x, y=np.square(x), mode='markers+lines', name='x²'),
go.Scatter(x=x,y=-np.square(x), name='-x²')
],
rows=2, cols=1
)
plot(fig)
# Scatter
# pour un grand dataset, on utilisera scattergl
"basique scatter"
x = np.linspace(-2, 2, 100)
y = 1/(1+np.exp(-x))
fig = go.Figure()
# 1ere solution, on ajoute toutes les figures avec le même appel (pour appliquer une seule fois certains parametres)
fig.add_traces([go.Scatter(x=x, y=y, mode='markers', name='sigmoid'),
go.Scatter(x=x, y=-y, mode='lines', name='negative sigmoid')] )
# 2e solution, on ajoute les figures indépendemment
fig.add_scatter(x=x, y=1+y, mode='markers', name='sigmoid+1')
fig.add_scatter(x=x, y=1-y, mode='lines', name='1-sigmoid')
fig.update_layout(title="sigmoid")
plot(fig)
"ajout d'annotations"
x = np.linspace(-5, 5, 100)
y = 1/(1+np.exp(-x))
fig = go.Figure()
fig.add_scatter(x=x,y=y,mode='lines',
name='sigmoid',
marker=dict(color='green'))
fig.add_annotation(x=0, y=0.5,
text='point en x=0',
showarrow=True,
arrowhead=1,
arrowsize=1,
arrowwidth=2,
arrowcolor='black',
bgcolor="orange",
borderwidth=1,
yshift=10)
plot(fig)
"ajout de plage de valeurs"
x = np.linspace(-5, 5, 100)
y = -1/(1+np.exp(-x))
fig=go.Figure()
fig.add_scatter(x=x, y=y)
fig.add_hline(y=-0.5, line_dash="dot", # vline pour verticale
annotation_text="0.5",
annotation_position="bottom right"
)
fig.add_hrect(y0=-0.85, y1=-0.15, # vrect pour verticale
annotation_text="-0.15 à -0.85",
annotation_position="top right",
fillcolor="blue", opacity=0.15, line_width=0.4)
plot(fig)
"Interpolation"
temps_exec = [0.40251994132995605, 0.014573812484741211, 0.23034405708312988, 0.4499189853668213, 0.8043158054351807, 0.21565508842468262, 0.10195517539978027, 0.35376596450805664, 0.5991549491882324, 0.08605694770812988, 1.1117901802062988, 0.9011919498443604, 0.3789708614349365, 0.8676671981811523, 1.3645083904266357, 0.8764557838439941, 0.13943982124328613, 0.05235695838928223, 0.1372683048248291, 0.29303503036499023]
l = [3.4549849033355713, 5.4536731243133545, 1.2118861675262451, 0.7063937187194824, 4.295026779174805, 11.98727297782898, 1.0320260524749756, 5.288934707641602, 9.74186897277832, 1.484644889831543, 6.555363893508911, 0.8726191520690918, 2.6839470863342285, 9.980525970458984, 0.665977954864502, 4.907128095626831, 2.7749810218811035, 5.096926927566528, 11.398299217224121, 3.3110921382904053]
fig=make_subplots(rows=2, cols=1,
subplot_titles=["Courbe bleue", "Courbe rouge"],
specs=[[{'type': 'xy'}], [{'type': 'xy'}]],
shared_xaxes=True,
)
## figures principales en haut ##
# Interpolation linéaire
fig.add_scatter(y=l, mode='lines', opacity=0.4, line=dict(color='royalblue', width=4), line_dash='dot', name='interpolation linéaire',row=1,col=1)
# Interpolation par spline
fig.add_scatter(y=l, mode='lines', line=dict(color='royalblue', width=4), line_shape='spline', name='interpolation par spline',
hovertemplate = "<br>%{y:.0f}</br>", row=1,col=1)
fig.update_xaxes(title="x", row=1, col=1)
fig.update_yaxes(title="y", row=1, col=1)
## Titre + axes labels ##
fig.update_layout(title="Interpolation")
## ligne moyenne ##
fig.add_shape(type="line", line_color="firebrick", line_width=2, opacity=1, line_dash="dot",
x0=0, x1=len(l)-1, y0=np.mean(l), y1=np.mean(l), row=1, col=1)
## fleche moyenne ##
fig.add_annotation(text="Moyenne : {}".format(int(np.mean(l)), grouping=True, monetary=True),
x=int(len(l)/5)*4, # arrows' head
y=np.mean(l)*1.2, # arrows' head
arrowhead=2, showarrow=True, row=1, col=1)
## layout custom ##
fig.update_xaxes(
showline=True,
showgrid=False,
showticklabels=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
ticks='outside',
tickfont=dict(
family='Arial',
size=12,
color='rgb(82, 82, 82)',
), row=1,col=1)
fig.update_yaxes(
showgrid=False,
zeroline=True,
showline=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
ticks='outside',
tickfont=dict(
family='Arial',
size=12,
color='rgb(82, 82, 82)',
), row=1, col=1)
## figures principales en bas ##
# Interpolation linéaire
fig.add_scatter(y=temps_exec, mode='lines', opacity=0.4, line=dict(color='firebrick', width=4), line_dash='dot', name="Interpolation linéaire",
row=2,col=1)
# Interpolation par spline
fig.add_scatter(y=temps_exec, mode='lines', line=dict(color='firebrick', width=4), line_shape='spline', name="Interpolation par spline",
hovertemplate = "<br>%{y:.3f}</br>", row=2,col=1)
## ligne moyenne ##
fig.add_shape(type="line", line_color="royalblue", line_width=2, opacity=1, line_dash="dot",
x0=0, x1=len(l)-1, y0=np.mean(temps_exec), y1=np.mean(temps_exec), row=2, col=1)
## fleche moyenne ##
fig.add_annotation(text="Moyenne : {} sec".format(round(np.mean(temps_exec),2), grouping=True, monetary=True),
x=int(len(temps_exec)/5)*4, # arrows' head
y=np.mean(temps_exec)*1.2, # arrows' head
arrowhead=2, showarrow=True, row=2, col=1)
fig.update_xaxes(title="x", row=2, col=1)
fig.update_yaxes(title="y", row=2, col=1)
## layout custom ##
fig.update_xaxes(
showline=True,
showgrid=False,
showticklabels=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
ticks='outside',
tickfont=dict(
family='Arial',
size=12,
color='rgb(82, 82, 82)',
), row=2, col=1)
fig.update_yaxes(
showgrid=False,
zeroline=True,
showline=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
ticks='outside',
tickfont=dict(
family='Arial',
size=12,
color='rgb(82, 82, 82)',
), row=2, col=1)
fig.update_layout(plot_bgcolor='white',
hoverlabel_align='right')
plot(fig)
# Financial chart
vert = '#599673'
rouge = '#e95142'
noir = '#000'
df = pd.read_csv('EURUSD_5y.csv')
fig = go.Figure()
fig.add_trace(go.Scatter(
y = df['Close'],
x = df['Date'],
line=dict(color=noir, width=1),
name="",
hovertemplate=
"Date: %{x}<br>" +
"Close: %{y}<br>"
))
fig.add_hline(y=df['Close'].iloc[0],
line_dash="dot",
annotation_text="25 mai 2016",
annotation_position="bottom right",
line_width=1.5, line=dict(color='black'))
# montée 1
fig.add_vrect(x0='2017-01-01',x1='2018-02-20',
fillcolor=vert, opacity=0.2, line_width=0.4,
annotation_text='01-01-2017 au 02-20-2018',
annotation_position="top left",
annotation=dict(font=dict(size=8))
)
fig.add_traces(go.Indicator(
mode = "number+delta",
value = 1.239864,
number={'prefix': "$", 'font_size' : 40},
delta = {"reference": 1.052698, "valueformat": ".6f", "position" : "bottom"},
title = {"text": "Eur/USD"},
domain = {'y': [0, 0.5], 'x': [0.15, 0.4]}))
# descente 1
fig.add_traces(go.Indicator(
mode = "number+delta",
value = 1.077702,
number={'prefix': "$", 'font_size' : 40},
delta = {"reference": 1.237317, "valueformat": ".6f", "position" : "bottom"},
title = {"text": "Eur/USD"},
domain = {'y': [0.5, 0.7], 'x': [0.55, 0.75]}))
fig.add_vrect(x0='2018-04-18',x1='2020-04-24',
fillcolor=rouge, opacity=0.2, line_width=0.4,
annotation_text='18-04-2018 au 24-04-2020',
annotation_position="top right",
annotation=dict(font=dict(size=8))
)
fig.update_layout(
template='simple_white',
yaxis_title="Euro/USD close",
title_text="Euro/USD Close"
)
plot(fig)
# Pie chart
labels = ['Apple','Samsung','Nokia','Wiko']
values = [4500, 3000, 1053, 500]
fig = go.Figure()
fig.add_pie(labels=labels, # les valeurs sur lesquelles on compte
values=values, # ce qui sert à faire les pourcentages
pull=[0, 0, 0, 0.2], # represente une fraction de pi, ici on décale le 4e label
textposition='inside',
)
fig.update_traces(hoverinfo='label+percent', # ce qu'on voit avec la souris
textinfo='value', # Ce qu'on lit dans le pie
textfont_size=20, # taille du texte du pie
marker=dict(colors=['gold', 'mediumturquoise', 'darkorange', 'lightgreen']) # couleur des secteurs
)
plot(fig)
# violin chart
df = px.data.iris()
fig=go.Figure()
fig.add_violin(y=df['sepal_length'],
points='all', # pour tous les afficher
box_visible=True,
meanline_visible=True,
fillcolor='lightblue',
opacity=0.7,
name="longueur sepale")
fig.update_layout(yaxis_zeroline=False)
plot(fig)
# histogramme, bar
df = px.data.iris()
fig=go.Figure()
fig.add_histogram(x=df['sepal_width'])
plot(fig)
fig.add_bar(y=df['sepal_width'])
plot(fig)
# graphiques 3D
"surface"
z_data = df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/volcano.csv")
fig = go.Figure(data=[go.Surface(z=z_data, colorscale='IceFire')]) # Z1 liste de liste
fig.update_layout(title='Mountain')
plot(fig)
"nuage de points"
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
color='species', size='petal_length', size_max=18,symbol='species', opacity=0.7)
plot(fig)
"réseau de neurones"
# liens
edge_x, edge_y = [1.5,3,None,1.5,3,None,1.5,3,None,1.5,3,None,1.5,3,None,1.5,3,None,3,4.5,None,3,4.5,None,3,4.5,None,3,4.5,None,3,4.5,None,3,4.5,None,3,4.5,None,],\
[1,0,None,1,2,None,1,4,None,3,0,None,3,2,None,3,4,None,0,1,None,0,1,None,0,3,None,2,1,None,2,3,None,4,1,None,4,3,None,]
# None pour couper la ligne
edge_trace = go.Scatter(
x=edge_x, y=edge_y,
line=dict(width=2, color='#000000'),
hoverinfo='none',
mode='lines')
# traçage des noeuds
node_x, node_y = [1.5,1.5,3,3,3,4.5,4.5],\
[1,3,0,2,4,1,3]
node_trace = go.Scatter(
x=node_x, y=node_y,
mode='markers',
hoverinfo='text',
marker=dict(
color='green',
size=20,
line_width=1.5))
# affichage
fig = go.Figure(data=[edge_trace, node_trace],
layout=go.Layout(
titlefont_size=16,
showlegend=False,
hovermode='closest',
margin=dict(b=20,l=5,r=5,t=40),
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis_range=[-6,10],
xaxis_range=[-5,11]
)
)
plot(fig)
"regression surfacique"
z1=[0,0,0,1,2,2,2,3,4,5,5,5,5,5,4,4,5,4,4,4,4,3,3,2,2]
z2=[0,1,1,2,2,3,3,3,4,5,6,6,6,5,5,5,6,5,5,5,4,4,3,3,3]
z3=[1,1,2,2,3,3,3,4,4,5,6,6,6,6,6,6,6,6,6,5,5,4,4,3,3]
z4=[1,2,2,3,3,3,4,4,5,6,6,6,7,7,7,6,6,6,6,5,5,5,4,4,3]
z5=[2,2,3,3,4,4,4,4,5,6,6,7,7,7,7,7,7,7,6,6,5,5,5,4,4]
z6=[2,2,3,4,4,4,5,5,6,6,7,7,7,7,7,7,7,7,6,6,6,6,5,5,4]
z7=[2,3,4,4,4,5,5,6,6,7,7,7,8,8,8,8,7,7,7,7,7,6,5,5,4]
z8=[3,3,4,4,5,5,6,6,7,7,7,8,8,9,8,8,8,7,7,7,7,6,6,5,5]
z9=[3,4,4,4,5,6,6,7,7,8,8,9,9,9,9,8,8,8,7,7,7,6,6,6,5]
z10=[3,4,4,5,5,6,6,7,7,8,8,9,10,10,9,8,8,7,7,7,7,6,6,6,5]
z11=[3,4,4,5,6,6,7,7,8,8,9,10,10,9,9,8,7,7,7,7,6,6,6,6,5]
z12=[3,4,4,5,6,6,7,7,8,8,9,9,9,9,8,7,7,7,7,6,6,6,5,5,4]
z13=[3,4,4,5,6,6,7,7,8,8,8,9,9,9,8,7,7,7,7,6,6,5,5,4,4]
z14=[3,4,4,5,5,6,6,7,7,8,8,8,8,8,8,7,7,7,7,6,6,5,5,4,3]
z15=[3,3,4,4,5,6,6,7,7,7,7,7,8,8,8,7,7,7,7,6,6,5,5,4,4]
z16=[3,3,4,4,5,6,6,6,6,7,7,7,7,7,7,7,7,7,6,6,6,5,5,5,4]
z17=[3,3,4,4,5,6,6,6,6,6,6,7,7,7,7,7,6,6,6,6,5,5,5,4,3]
z18=[2,3,4,4,5,5,5,6,6,6,6,6,7,7,6,6,6,6,5,5,5,5,4,4,3]
z19=[2,3,4,4,4,5,5,5,5,4,5,6,6,6,6,6,5,5,5,4,4,4,4,3,3]
z20=[2,3,4,4,4,4,4,4,3,3,5,6,6,6,6,5,5,4,4,4,4,4,3,3,2]
z21=[2,3,3,3,3,3,3,3,2,4,5,6,6,6,5,4,4,4,3,3,3,3,2,2,2]
z22=[2,2,3,3,3,3,3,2,2,4,4,5,5,5,5,4,4,3,3,2,2,2,2,1,1]
z23=[1,2,2,2,2,2,2,1,2,4,4,4,5,5,4,4,3,3,2,2,1,1,1,1,1]
z24=[1,1,1,1,1,1,1,1,2,4,4,4,4,4,4,3,3,2,1,1,1,1,0,0,0]
z25=[0,0,0,0,0,0,0,0,1,2,3,3,3,3,3,2,2,1,1,1,0,0,0,0,0]
Z1 = [z1,z2,z3,z4,z5,z6,z7,z8,z9,z10,z11,z12,z13,z14,z15,z16,z17,z18,z19,z20,z21,z22,z23,z24,z25]
lis=[]
for j in Z1:
for i in j:
lis.append(i)
df_z = pd.DataFrame(lis)
df_z.columns=['hauteurs']
xlis = [i for i in range (25)]*25
df_xlis=pd.DataFrame(xlis)
ylis = []
for i in range (25):
for j in range (25):
ylis.append(i)
df_ylis=pd.DataFrame(ylis)
df_2d=pd.concat([df_xlis,df_ylis],axis=1)
df_2d.columns=['x','y']
df_final = pd.concat([df_z,df_2d], axis=1)
from sklearn.svm import SVR
mesh_size = .02
margin = 0
df = df_final
X = df[['x', 'y']]
y = df['hauteurs']
# Modele
model = SVR(C=1.)
model.fit(X, y)
# mesh grid
x_min, x_max = X.x.min() - margin, X.x.max() + margin
y_min, y_max = X.y.min() - margin, X.y.max() + margin
xrange = np.arange(x_min, x_max, mesh_size)
yrange = np.arange(y_min, y_max, mesh_size)
xx, yy = np.meshgrid(xrange, yrange)
# On run le modele
pred = model.predict(np.c_[xx.ravel(), yy.ravel()])
pred = pred.reshape(xx.shape)
# plot
fig = px.scatter_3d(df, x='x', y='y', z='hauteurs')
fig.update_traces(marker=dict(size=5))
fig.add_traces(go.Surface(x=xrange, y=yrange, z=pred, name='pred_surface'))
plot(fig)
# Maps
"Ligne entre Miami et Chicago"
fig = go.Figure()
fig.add_scattermapbox(
# on relie Miami (lat = 25.7616798, long = -80.1917902) et Chicago (lat = 41.8119, long = -87.6873)
mode = "markers+lines",
lon = [-80.1917902, -87.6873],
lat = [25.7616798, 41.8119],
marker = {'size': 10,
'color': 'firebrick',
})
fig.update_layout(
margin ={'l':0,'t':0,'b':0,'r':0}, # marge left, top, bottom, right
mapbox = {
'center': {'lon': -80, 'lat': 40},
'style': "stamen-terrain",
'zoom': 3})
plot(fig)
"Aire colorée sur une carte, triangle des bermudes"
fig = go.Figure()
# les 3 points :
# Bermudes : lat = 32.320236, long = -64.7740215
# Miami : lat = 25.7616798, long = -80.1917902
# San Juan : lat = 18.2232855, long = -66.5927315
fig.add_scattermapbox(
fill = "toself",
lon = [-64.7740215, -80.1917902, -66.5927315], lat = [32.320236, 25.7616798, 18.2232855],
marker = { 'size': 2, 'color': "red" })
fig.update_layout(
margin ={'l':0,'t':0,'b':0,'r':0},
mapbox = {
'style': "stamen-terrain",
'center': {'lon': -80, 'lat': 25 },
'zoom': 3},
showlegend = False)
plot(fig)
"Scatter sur une map"
df = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(df, locations="iso_alpha", # on situe le pays avec son raccourci international
color="continent", # on colorie par continent
hover_name="country", # ce qu'on voit avec la souris
size="gdpPercap", # la taille des points dépend du pib du pays
projection="natural earth" # type de carte
)
plot(fig)
"Scatter avec groupe de points"
token = 'your token from https://studio.mapbox.com'
fig = go.Figure()
df = pd.read_table('quake.dat', names=['depth', 'lat','long','richter'], sep=',' ,encoding='utf-8', skiprows=8)
fig.add_scattermapbox(
mode="markers",
name="",
lon=list(df['long'].apply(lambda x: float(x))),
lat=list(df['lat'].apply(lambda x: float(x))),
marker=dict(size=5,
color=df['richter'],
showscale=True,
colorscale="jet"
),
hovertemplate=
"longitude: %{lon}<br>" +
"latitude: %{lat}<br>" +
"intensité: %{marker.color}",
)
fig.update_layout(
margin={'l': 0, 't': 0, 'b': 0, 'r': 0},
mapbox={
'accesstoken': token,
'style': 'light',
'center': {'lon': -80, 'lat': 25}, },
)
plot(fig)
#### Plotly.figure_factory -----------------------------------------
"Distplot"
x = [np.random.randn(150)]
label = ['Groupe 1']
color = ['#B36CD2']
fig = ff.create_distplot(x, label, colors=color,
bin_size=.2, show_rug=False)
fig.update_layout(title_text='Distplot')
plot(fig)
"Heatmap avec annotations"
z = [[1, 1, 3],
[3, 1, 3],
[3, 1, 1]]
x = ['Équipe A', 'Équipe B', 'Équipe C']
y = ['Match 3', 'Match 2', 'Match 1']
z_text = [['Perdu', 'Perdu', 'Gagné'],
['Gagné', 'Perdu', 'Gagné'],
['Gagné', 'Perdu', 'Perdu']]
fig = ff.create_annotated_heatmap(z, x=x, y=y, annotation_text=z_text, colorscale='gnbu')
plot(fig)
"Dendrogrames"
X = np.array([[1],[2], [5], [3]])
fig = ff.create_dendrogram(X)
fig.update_layout(width=1080, height=675)
plot(fig)
"champ vectoriel"
x,y = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2))
u = -np.cos(y)*x
v = np.sin(x)*y+1
fig = ff.create_quiver(x, y, u, v)
plot(fig)
"Lignes de flux"
x = np.linspace(-4, 4, 80)
y = np.linspace(-4, 4, 80)
Y, X = np.meshgrid(x, y)
u = -(1 + X )**2 + 2*Y
v = 1 - X + (Y+1)**2
fig = ff.create_streamline(x, y, u, v, arrow_scale=.2)
plot(fig)
"Création d'un tableau"
# avec latex à la main
data_matrix = [['Forme factorisée', 'Forme developpée'],
['$(a+b)^{2}$', '$a^{2}+2ab+b^{2}$'],
['$(a-b)^{2}$', '$a^{2}-2ab+b^{2}$'],
['$(a+b)(a-b)$', '$a^{2}-b^{2}$']]
fig = ff.create_table(data_matrix)
plot(fig, include_mathjax='cdn')
# à partir d'un dataframe pandas
df = px.data.iris()
fig=ff.create_table(df)
plot(fig)
| 44,567
|
https://github.com/JAD-SVK/mono-tools/blob/master/rules/Gendarme.Rules.BadPractice/ReturnNullRule.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
mono-tools
|
JAD-SVK
|
C#
|
Code
| 447
| 971
|
//
// Abstract Gendarme.Rules.BadPractice.ReturnsNullRule
//
// Authors:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2008, 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using Mono.Cecil;
using Mono.Cecil.Cil;
using Gendarme.Framework;
using Gendarme.Framework.Engines;
using Gendarme.Framework.Rocks;
namespace Gendarme.Rules.BadPractice {
// Notes:
// * We don't implement IMethodRule on purpose since a rule that inherit
// from us can be an ITypeRule (checking for a specific method in the type)
[EngineDependency (typeof (OpCodeEngine))]
abstract public class ReturnNullRule : Rule {
void CheckReturn (Instruction ins, MethodDefinition method)
{
// trace back what is being returned
Instruction previous = ins.TraceBack (method);
while (previous != null) {
// most of the time we'll find the null value on the first trace back call
if (previous.OpCode.Code == Code.Ldnull) {
Report (method, ins);
break;
}
// but CSC non-optimized code generation results in strange IL that needs a few
// more calls. e.g. "return null" == "nop | ldnull | stloc.0 | br.s | ldloc.0 | ret"
if ((previous.OpCode.FlowControl == FlowControl.Branch) || (previous.IsLoadLocal ()
|| previous.IsStoreLocal ())) {
previous = previous.TraceBack (method);
} else
break;
}
}
void CheckLdnull (Instruction ins, MethodDefinition method)
{
Instruction branch = (ins.Next.Operand as Instruction);
if (branch.Is (Code.Ret))
Report (method, ins);
}
public virtual RuleResult CheckMethod (MethodDefinition method)
{
// is there any Ldnull instructions in this method
if (!OpCodeEngine.GetBitmask (method).Get (Code.Ldnull))
return RuleResult.DoesNotApply;
foreach (Instruction ins in method.Body.Instructions) {
switch (ins.OpCode.Code) {
case Code.Ret:
// look if a null is returned
CheckReturn (ins, method);
break;
case Code.Ldnull:
// look for branching, e.g. immediate if
CheckLdnull (ins, method);
break;
}
}
return Runner.CurrentRuleResult;
}
protected abstract void Report (MethodDefinition method, Instruction ins);
}
}
| 13,094
|
https://github.com/jrStaff/pixiedust/blob/master/tests/chromeDriverTest.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
pixiedust
|
jrStaff
|
Python
|
Code
| 194
| 631
|
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import time
import sys
sys.path.append(os.path.abspath("."))
import runPixiedustNotebooks as runPixie
import subprocess
class JupyterSeleniumInstance():
def __init__(self):
self.url = ""
self.pid = 0
def startJupyterNotebookInBackground(self):
# the pid plus 1 is there because the shell, which is necessary,
# is the pid returned for the shell instance process,
# but the child process (jupyter) is immediately created
# and there is the shell process pid + 1
# lookup nohup and & symbol if you aren't familiar with those
self.pid = subprocess.Popen("nohup jupyter notebook --no-browser &", shell=True).pid + 1
#wait for jupyter notebook to initialize
print("Running jupyter server on pid:" + str(self.pid))
time.sleep(3)
def killJupyterNotebook(self):
os.system('kill ' + str(self.pid))
def getJupyterUrlFromNohup(self):
try:
nohup = open("nohup.out", "r").read()
return self.parseOutUrl(nohup)
except IOError:
print("Error: Problem opening nohup.out file.")
finally:
os.system("rm nohup.out")
def parseOutUrl(self, nohup):
nohup_split = nohup.splitlines()
for line in nohup_split:
line = line.strip()
if "http" in line:
begin_i= int(line.find("http"))
url = line[begin_i:]
print("Jupyter url:" + url)
self.url = url.strip()
#not tested fully, but it should load in the pixiedust kernal
#if it doesn't exist
runPixie.createKernelSpecIfNeeded()
try:
jsi = JupyterSeleniumInstance()
jsi.startJupyterNotebookInBackground()
jsi.getJupyterUrlFromNohup()
driver = webdriver.Chrome()
driver.get(jsi.url)
finally:
time.sleep(10)
jsi.killJupyterNotebook()
| 12,348
|
https://github.com/doubcrick/hasor/blob/master/hasor-spring/src/main/java/net/hasor/spring/beans/SpringTypeSupplier.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
hasor
|
doubcrick
|
Java
|
Code
| 177
| 436
|
/*
* Copyright 2002-2005 the original author or authors.
*
* 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 net.hasor.spring.beans;
import net.hasor.core.Provider;
import net.hasor.core.TypeSupplier;
import org.springframework.context.ApplicationContext;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Spring 的 TypeSupplier
* @version : 2020年02月27日
* @author 赵永春 (zyc@hasor.net)
*/
public class SpringTypeSupplier implements TypeSupplier {
private final Supplier<ApplicationContext> applicationContext;
public SpringTypeSupplier(ApplicationContext applicationContext) {
this(Provider.of(Objects.requireNonNull(applicationContext)));
}
public SpringTypeSupplier(Supplier<ApplicationContext> applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public <T> T get(Class<? extends T> targetType) {
return applicationContext.get().getBean(targetType);
}
@Override
public <T> boolean test(Class<? extends T> targetType) {
return applicationContext.get().getBeanNamesForType(targetType).length > 0;
}
}
| 50,511
|
https://github.com/dilini-muthumala/ballerina/blob/master/modules/ballerina-core/src/main/java/org/ballerinalang/util/debugger/dto/VariableDTO.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
ballerina
|
dilini-muthumala
|
Java
|
Code
| 230
| 523
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.ballerinalang.util.debugger.dto;
import org.ballerinalang.bre.nonblocking.debugger.VariableInfo;
/**
* DTO class representing variables in the stack upon a debug hit.
*
* @since 0.8.0
*/
public class VariableDTO {
private String scope, name;
private String type, value;
public VariableDTO() {
}
public VariableDTO(VariableInfo vinfo) {
this.scope = vinfo.getScope();
this.name = vinfo.getName();
this.type = vinfo.getType();
this.value = vinfo.getbValueSting();
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| 30,322
|
https://github.com/yasenm/a2-netcore/blob/master/A4CoreBlog/A4CoreBlog.Data.Infrastructure/Lists/BasePaginatedList.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
a2-netcore
|
yasenm
|
C#
|
Code
| 61
| 143
|
namespace A4CoreBlog.Data.Infrastructure
{
public class BasePaginatedList
{
public int PageIndex { get; set; }
public int TotalPages { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
}
}
| 16,342
|
https://github.com/kintoproj/kintohub/blob/master/dashboard/src/components/pages/CreateFirstEnv.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
kintohub
|
kintoproj
|
TSX
|
Code
| 417
| 1,375
|
import 'types/yup';
import FormikTextField from 'components/atoms/FormikTextField';
import SolidIconButtonSeparated from 'components/atoms/SolidIconButtonSeparated';
import { VerticalSpacer } from 'components/atoms/Spacer';
import { useServiceNavigate } from 'components/hooks/PathHook';
import { Formik, FormikProps } from 'formik';
import { EnvNameSchema } from 'libraries/helpers/yup';
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import styled, { ThemeProvider } from 'styled-components';
import * as Yup from 'yup';
import { MuiThemeProvider, Typography } from '@material-ui/core';
import { mainTheme } from 'theme';
import { createEnvironment, getEnvironments } from 'libraries/grpc/environment';
import { updateEnvList as updateEnvironments } from 'states/auth/actions';
import { doHidePanel } from 'states/sidePanel/actions';
import { PATH_MAINTENANCE } from 'libraries/constants';
import { push } from 'connected-react-router';
import FullPageLoading from '../molecules/FullPageLoading';
import { useGRPCWrapper } from '../templates/GRPCWrapper';
const StyledDiv = styled.div`
position: relative;
overflow: hidden;
height: 100%;
width: 100vw;
display: flex;
flex-direction: row;
.content {
padding: 20px;
overflow-y: auto;
height: 100%;
.MuiButton-root {
width: 100%;
}
display: flex;
align-items: center;
.content-wrapper {
display: flex;
flex-direction: column;
}
}
.main {
width: 100%;
height: 100%;
position: absolute;
display: flex;
}
`;
const validationSchema = Yup.object({
envName: EnvNameSchema,
clusterId: Yup.string().required(),
});
type SignUpValues = {
envName: string;
};
export default () => {
const grpcWrapper = useGRPCWrapper();
const dispatch = useDispatch();
const { navigateToServices } = useServiceNavigate();
const [initLoaded, setInitLoaded] = useState(true);
useEffect(() => {
const initLoad = async () => {
try {
const envs = await grpcWrapper(getEnvironments, {});
const envList = envs.getItemsList();
if (envList.length !== 0) {
navigateToServices({ targetEnvId: envList[0].getId() });
}
} catch (error) {
dispatch(push(PATH_MAINTENANCE, { error }));
}
setInitLoaded(true);
};
initLoad();
}, []);
return (
<Formik<SignUpValues>
initialValues={{
envName: '',
}}
validationSchema={validationSchema}
onSubmit={(values, actions) => {
actions.setSubmitting(false);
}}
>
{(props: FormikProps<SignUpValues>) => {
// force to validate the form at first load
useEffect(() => {
props.validateForm();
}, []);
const createEnv = async () => {
props.setSubmitting(true);
try {
const env = await grpcWrapper(createEnvironment, {
envName: props.values.envName,
});
// submit the env token
const envId = env.getId();
// Must update the environment first
dispatch(
updateEnvironments([
{
name: props.values.envName,
envId,
},
])
);
navigateToServices({ targetEnvId: envId });
props.setSubmitting(false);
dispatch(doHidePanel());
} catch (error) {
props.setSubmitting(false);
props.setFieldError('envName', error.message);
}
};
return (
<StyledDiv>
{!initLoaded && <FullPageLoading />}
<MuiThemeProvider theme={mainTheme}>
<ThemeProvider theme={mainTheme}>
<form onSubmit={props.handleSubmit}>
<div className="main">
<div className="content">
<div className="content-wrapper">
<Typography variant="h2">
Name Your First Environment
</Typography>
<Typography variant="body2">
Choose an intuitive name for your new environment.
</Typography>
<VerticalSpacer size={40} />
<FormikTextField
variant="outlined"
name="envName"
placeholder="e.g. Production"
/>
<VerticalSpacer size={16} />
<SolidIconButtonSeparated
data-cy="name-env-continue-button"
text="Create"
isLoading={props.isSubmitting}
disabled={!!props.errors.envName}
onClick={createEnv}
/>
</div>
</div>
</div>
</form>
</ThemeProvider>
</MuiThemeProvider>
</StyledDiv>
);
}}
</Formik>
);
};
| 24,008
|
https://github.com/coco-robotics/rllab-curriculum/blob/master/scripts/run_experiment_lite.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
rllab-curriculum
|
coco-robotics
|
Python
|
Code
| 413
| 1,754
|
import sys
sys.path.append(".")
from rllab.misc.ext import is_iterable, set_seed
from rllab.misc.instrument import concretize
from rllab import config
import rllab.misc.logger as logger
import argparse
import os.path as osp
import datetime
import dateutil.tz
import ast
import uuid
import pickle as pickle
import base64
import joblib
import logging
def run_experiment(argv):
default_log_dir = config.LOG_DIR
now = datetime.datetime.now(dateutil.tz.tzlocal())
# avoid name clashes when running distributed jobs
rand_id = str(uuid.uuid4())[:5]
timestamp = now.strftime('%Y_%m_%d_%H_%M_%S_%f_%Z')
default_exp_name = 'experiment_%s_%s' % (timestamp, rand_id)
parser = argparse.ArgumentParser()
parser.add_argument('--n_parallel', type=int, default=1,
help='Number of parallel workers to perform rollouts. 0 => don\'t start any workers')
parser.add_argument(
'--exp_name', type=str, default=default_exp_name, help='Name of the experiment.')
parser.add_argument('--log_dir', type=str, default=None,
help='Path to save the log and iteration snapshot.')
parser.add_argument('--snapshot_mode', type=str, default='all',
help='Mode to save the snapshot. Can be either "all" '
'(all iterations will be saved), "last" (only '
'the last iteration will be saved), or "none" '
'(do not save snapshots)')
parser.add_argument('--snapshot_gap', type=int, default=1,
help='Gap between snapshot iterations.')
parser.add_argument('--tabular_log_file', type=str, default='progress.csv',
help='Name of the tabular log file (in csv).')
parser.add_argument('--text_log_file', type=str, default='debug.log',
help='Name of the text log file (in pure text).')
parser.add_argument('--params_log_file', type=str, default='params.json',
help='Name of the parameter log file (in json).')
parser.add_argument('--variant_log_file', type=str, default='variant.json',
help='Name of the variant log file (in json).')
parser.add_argument('--resume_from', type=str, default=None,
help='Name of the pickle file to resume experiment from.')
parser.add_argument('--plot', type=ast.literal_eval, default=False,
help='Whether to plot the iteration results')
parser.add_argument('--log_tabular_only', type=ast.literal_eval, default=False,
help='Whether to only print the tabular log information (in a horizontal format)')
parser.add_argument('--seed', type=int,
help='Random seed for numpy')
parser.add_argument('--args_data', type=str,
help='Pickled data for stub objects')
parser.add_argument('--variant_data', type=str,
help='Pickled data for variant configuration')
parser.add_argument('--use_cloudpickle', type=ast.literal_eval, default=False)
args = parser.parse_args(argv[1:])
if args.seed is not None:
set_seed(args.seed)
if args.n_parallel > 0:
from rllab.sampler import parallel_sampler
parallel_sampler.initialize(n_parallel=args.n_parallel)
if args.seed is not None:
parallel_sampler.set_seed(args.seed)
if args.plot:
from rllab.plotter import plotter
plotter.init_worker()
if args.log_dir is None:
log_dir = osp.join(default_log_dir, args.exp_name)
else:
log_dir = args.log_dir
tabular_log_file = osp.join(log_dir, args.tabular_log_file)
text_log_file = osp.join(log_dir, args.text_log_file)
params_log_file = osp.join(log_dir, args.params_log_file)
if args.variant_data is not None:
variant_data = pickle.loads(base64.b64decode(args.variant_data))
variant_log_file = osp.join(log_dir, args.variant_log_file)
logger.log_variant(variant_log_file, variant_data)
else:
variant_data = None
if not args.use_cloudpickle:
logger.log_parameters_lite(params_log_file, args)
logger.add_text_output(text_log_file)
logger.add_tabular_output(tabular_log_file)
prev_snapshot_dir = logger.get_snapshot_dir()
prev_mode = logger.get_snapshot_mode()
logger.set_snapshot_dir(log_dir)
logger.set_tf_summary_dir(osp.join(log_dir, "tf_summary"))
logger.set_snapshot_mode(args.snapshot_mode)
logger.set_snapshot_gap(args.snapshot_gap)
logger.set_log_tabular_only(args.log_tabular_only)
logger.push_prefix("[%s] " % args.exp_name)
if args.resume_from is not None:
data = joblib.load(args.resume_from)
assert 'algo' in data
algo = data['algo']
maybe_iter = algo.train()
if is_iterable(maybe_iter):
for _ in maybe_iter:
pass
else:
# read from stdin
if args.use_cloudpickle:
import cloudpickle
method_call = cloudpickle.loads(base64.b64decode(args.args_data))
method_call(variant_data)
else:
data = pickle.loads(base64.b64decode(args.args_data))
maybe_iter = concretize(data)
if is_iterable(maybe_iter):
for _ in maybe_iter:
pass
logger.set_snapshot_mode(prev_mode)
logger.set_snapshot_dir(prev_snapshot_dir)
logger.remove_tabular_output(tabular_log_file)
logger.remove_text_output(text_log_file)
logger.pop_prefix()
if __name__ == "__main__":
run_experiment(sys.argv)
| 11,414
|
https://github.com/kadkins-pivotal/steeltoe/blob/master/src/Management/test/EndpointCore.Test/Metrics/Observer/AspNetCoreHostingObserverTest.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
steeltoe
|
kadkins-pivotal
|
C#
|
Code
| 519
| 1,867
|
// Copyright 2017 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using OpenCensus.Stats;
using OpenCensus.Stats.Aggregations;
using OpenCensus.Tags;
using Steeltoe.Management.Census.Stats;
using Steeltoe.Management.Census.Tags;
using Steeltoe.Management.Endpoint.Test;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using Xunit;
namespace Steeltoe.Management.Endpoint.Metrics.Observer.Test
{
public class AspNetCoreHostingObserverTest : BaseTest
{
[Fact]
public void Constructor_RegistersExpectedViews()
{
var options = new MetricsEndpointOptions();
var stats = new OpenCensusStats();
var tags = new OpenCensusTags();
var observer = new AspNetCoreHostingObserver(options, stats, tags, null);
Assert.NotNull(stats.ViewManager.GetView(ViewName.Create("http.server.request.time")));
Assert.NotNull(stats.ViewManager.GetView(ViewName.Create("http.server.request.count")));
}
[Fact]
public void ShouldIgnore_ReturnsExpected()
{
var options = new MetricsEndpointOptions();
var stats = new OpenCensusStats();
var tags = new OpenCensusTags();
var obs = new AspNetCoreHostingObserver(options, stats, tags, null);
Assert.True(obs.ShouldIgnoreRequest("/cloudfoundryapplication/info"));
Assert.True(obs.ShouldIgnoreRequest("/cloudfoundryapplication/health"));
Assert.True(obs.ShouldIgnoreRequest("/foo/bar/image.png"));
Assert.True(obs.ShouldIgnoreRequest("/foo/bar/image.gif"));
Assert.True(obs.ShouldIgnoreRequest("/favicon.ico"));
Assert.True(obs.ShouldIgnoreRequest("/foo.js"));
Assert.True(obs.ShouldIgnoreRequest("/foo.css"));
Assert.True(obs.ShouldIgnoreRequest("/javascript/foo.js"));
Assert.True(obs.ShouldIgnoreRequest("/css/foo.css"));
Assert.True(obs.ShouldIgnoreRequest("/foo.html"));
Assert.True(obs.ShouldIgnoreRequest("/html/foo.html"));
Assert.False(obs.ShouldIgnoreRequest("/api/test"));
Assert.False(obs.ShouldIgnoreRequest("/v2/apps"));
}
[Fact]
public void ProcessEvent_IgnoresNulls()
{
var options = new MetricsEndpointOptions();
var stats = new OpenCensusStats();
var tags = new OpenCensusTags();
var observer = new AspNetCoreHostingObserver(options, stats, tags, null);
observer.ProcessEvent("foobar", null);
observer.ProcessEvent(AspNetCoreHostingObserver.STOP_EVENT, null);
Activity act = new Activity("Test");
act.Start();
observer.ProcessEvent(AspNetCoreHostingObserver.STOP_EVENT, null);
act.Stop();
}
[Fact]
public void GetException_ReturnsExpected()
{
var options = new MetricsEndpointOptions();
var stats = new OpenCensusStats();
var tags = new OpenCensusTags();
var observer = new AspNetCoreHostingObserver(options, stats, tags, null);
var context = GetHttpRequestMessage();
string exception = observer.GetException(context);
Assert.Equal("None", exception);
context = GetHttpRequestMessage();
var exceptionHandlerFeature = new ExceptionHandlerFeature()
{
Error = new ArgumentNullException()
};
context.Features.Set<IExceptionHandlerFeature>(exceptionHandlerFeature);
exception = observer.GetException(context);
Assert.Equal("ArgumentNullException", exception);
}
[Fact]
public void GetTagContext_ReturnsExpected()
{
var options = new MetricsEndpointOptions();
var stats = new OpenCensusStats();
var tags = new OpenCensusTags();
var observer = new AspNetCoreHostingObserver(options, stats, tags, null);
var context = GetHttpRequestMessage();
var exceptionHandlerFeature = new ExceptionHandlerFeature()
{
Error = new ArgumentNullException()
};
context.Features.Set<IExceptionHandlerFeature>(exceptionHandlerFeature);
context.Response.StatusCode = 404;
var tagContext = observer.GetTagContext(context);
var tagValues = tagContext.ToList();
tagValues.Contains(Tag.Create(TagKey.Create("exception"), TagValue.Create("ArgumentNullException")));
tagValues.Contains(Tag.Create(TagKey.Create("uri"), TagValue.Create("/foobar")));
tagValues.Contains(Tag.Create(TagKey.Create("status"), TagValue.Create("404")));
tagValues.Contains(Tag.Create(TagKey.Create("method"), TagValue.Create("GET")));
}
[Fact]
public void HandleStopEvent_RecordsStats()
{
var options = new MetricsEndpointOptions();
var stats = new OpenCensusStats();
var tags = new OpenCensusTags();
var observer = new AspNetCoreHostingObserver(options, stats, tags, null);
var context = GetHttpRequestMessage();
var exceptionHandlerFeature = new ExceptionHandlerFeature()
{
Error = new ArgumentNullException()
};
context.Features.Set<IExceptionHandlerFeature>(exceptionHandlerFeature);
context.Response.StatusCode = 500;
Activity act = new Activity("Test");
act.Start();
Thread.Sleep(1000);
act.SetEndTime(DateTime.UtcNow);
observer.HandleStopEvent(act, context);
observer.HandleStopEvent(act, context);
var reqData = stats.ViewManager.GetView(ViewName.Create("http.server.request.time"));
var aggData1 = reqData.SumWithTags() as IDistributionData;
Assert.Equal(2, aggData1.Count);
Assert.True(aggData1.Mean > 1000.00);
Assert.True(aggData1.Max > 1000.00);
act.Stop();
}
private HttpContext GetHttpRequestMessage()
{
return GetHttpRequestMessage("GET", "/foobar");
}
private HttpContext GetHttpRequestMessage(string method, string path)
{
HttpContext context = new DefaultHttpContext
{
TraceIdentifier = Guid.NewGuid().ToString()
};
context.Request.Body = new MemoryStream();
context.Response.Body = new MemoryStream();
context.Request.Method = method;
context.Request.Path = new PathString(path);
context.Request.Scheme = "http";
context.Request.Host = new HostString("localhost", 5555);
return context;
}
private class ExceptionHandlerFeature : IExceptionHandlerFeature
{
public Exception Error { get; set; }
}
}
}
| 49,317
|
https://github.com/shenjie1993/assaic/blob/master/src/com/cineplex/service/MemberService.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
assaic
|
shenjie1993
|
Java
|
Code
| 312
| 728
|
package com.cineplex.service;
import java.util.List;
import com.cineplex.entity.Activity;
import com.cineplex.entity.BankCard;
import com.cineplex.entity.FeeRecord;
import com.cineplex.entity.Member;
/**
* interface of service for member operation
* @author Andy 1993sj19993@gmail.com
* @date 2015年3月4日 上午11:28:45
*
*/
public interface MemberService {
/**
* check if a member is valid
* @param accountName
* @param password
* @return boolean: result of login
* @throws
*/
public Member login(String accountName, String password);
/**
* register a new member
* @param member
* @return boolean: success or not
* @throws
*/
public boolean register(Member member);
/**
* recharge money into a bank account
* @param bankCardId
* @param money
* @return boolean:
* @throws
*/
public boolean recharge(long bankCardId, int money);
/**
* check bank account information for a member
* @param id
* @return BankCard:
* @throws
*/
public BankCard checkBankAccount(int id);
/**
* get activities which are still active
* @param id
* @return List<Activity>:
* @throws
*/
public List<Activity> getAvaibleActivities(int id);
/**
* add a record for a member attending a activity
* @param id
* @param activityId
* @param answer:
* @return void:
* @throws
*/
public void attendActivity(int id, int activityId, int answer);
/**
* buy a ticket by a member card
* @param id: member card id
* @param money:
* @return void:
* @throws
*/
public boolean buyTicketsByCard(int id, int money);
/**
* buy a ticket by integral in a member card
* @param id
* @param money
* @return boolean:
* @throws
*/
public boolean buyTicketByIntegral(int id, int money);
/**
* get an activity information by its id
* @param activityId
* @return Activity:
* @throws
*/
public Activity getActivityById(int activityId);
/**
* get consumption records of a member
* @param id
* @return List<FeeRecord>:
* @throws
*/
public List<FeeRecord> getConsumption(int id);
/**
* get rechrage records of a member
* @param id
* @return List<FeeRecord>:
* @throws
*/
public List<FeeRecord> getRecharge(int id);
}
| 44,275
|
https://github.com/ExpressGradient/ezrel/blob/master/.npmignore
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ezrel
|
ExpressGradient
|
Ignore List
|
Code
| 5
| 22
|
src
node_modules
.idea
prettier.config.js
tsconfig.json
| 3,072
|
https://github.com/lefb766/mono/blob/master/mcs/errors/cs0100-6.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
mono
|
lefb766
|
C#
|
Code
| 23
| 40
|
// CS0100: The parameter name `obj' is a duplicate
// Line: 4
class C
{
public extern C (object obj, object obj);
}
| 2,872
|
https://github.com/sk-2809/c-/blob/master/printing num using while loop.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
c-
|
sk-2809
|
C++
|
Code
| 14
| 46
|
#include<iostream>
using namespace std;
int main()
{
int i=1;
while(i<=5){
cout<<i<<endl;
i++;
}
}
| 45,331
|
https://github.com/mhraihan/product-manager/blob/master/src/store/state.js
|
Github Open Source
|
Open Source
|
MIT
| null |
product-manager
|
mhraihan
|
JavaScript
|
Code
| 10
| 36
|
export default {
products: JSON.parse(localStorage.getItem("vuex") || "[]"),
metafields: []
};
| 16,883
|
https://github.com/Cuber01/sand-game/blob/master/src/elements/smoke.hpp
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
sand-game
|
Cuber01
|
C++
|
Code
| 37
| 132
|
#ifndef smoke_hpp
#define smoke_hpp
#include <stdint.h>
class CSmoke : public CElement
{
public:
CSmoke();
virtual void update(uint16_t x, uint16_t y);
void move(uint16_t x, uint16_t y);
void handleLifetime(uint16_t x, uint16_t y);
void receiveHeat(float heatAmount);
int16_t lifetime;
};
#endif
| 47,855
|
https://github.com/DjConsti/webengineering/blob/master/UE3/we-lab3-group09/build.sbt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
webengineering
|
DjConsti
|
Scala
|
Code
| 38
| 145
|
name := """we-lab3-group09"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayJava)
scalaVersion := "2.11.1"
libraryDependencies ++= Seq(
javaJdbc,
javaCore,
javaJpa,
"org.hibernate" % "hibernate-entitymanager" % "4.3.1.Final",
"com.google.code.gson" % "gson" % "2.2"
)
fork in run := false
| 33,336
|
https://github.com/aws-samples/visitor-prioritization-switcher/blob/master/lib/waitingroom-stack.ts
|
Github Open Source
|
Open Source
|
MIT-0
| 2,022
|
visitor-prioritization-switcher
|
aws-samples
|
TypeScript
|
Code
| 59
| 154
|
import { Stack, StackProps, CfnOutput } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Monitor } from './monitor';
import { WebHosting } from './webhosting';
export class WaitingroomStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const webHosting = new WebHosting(this, 'WebHosting');
new Monitor(this, 'Monitor', {
distribution: webHosting.distribution,
cff: webHosting.cff,
})
}
}
| 18,262
|
https://github.com/Deep-Learning-4-VB-NET/deeplearning4vb/blob/master/deeplearning4vb/datavec/datavec-api/src/main/java/org/datavec/api/transform/transform/column/AddConstantColumnTransform.vb
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
deeplearning4vb
|
Deep-Learning-4-VB-NET
|
Visual Basic
|
Code
| 504
| 1,304
|
Imports System
Imports System.Collections.Generic
Imports Data = lombok.Data
Imports ColumnType = org.datavec.api.transform.ColumnType
Imports Transform = org.datavec.api.transform.Transform
Imports ColumnMetaData = org.datavec.api.transform.metadata.ColumnMetaData
Imports Schema = org.datavec.api.transform.schema.Schema
Imports Writable = org.datavec.api.writable.Writable
Imports JsonProperty = org.nd4j.shade.jackson.annotation.JsonProperty
'
' * ******************************************************************************
' * *
' * *
' * * This program and the accompanying materials are made available under the
' * * terms of the Apache License, Version 2.0 which is available at
' * * https://www.apache.org/licenses/LICENSE-2.0.
' * *
' * * See the NOTICE file distributed with this work for additional
' * * information regarding copyright ownership.
' * * 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.
' * *
' * * SPDX-License-Identifier: Apache-2.0
' * *****************************************************************************
'
Namespace org.datavec.api.transform.transform.column
'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
'ORIGINAL LINE: @Data public class AddConstantColumnTransform implements org.datavec.api.transform.Transform
<Serializable>
Public Class AddConstantColumnTransform
Implements Transform
Private ReadOnly newColumnName As String
Private ReadOnly newColumnType As ColumnType
Private ReadOnly fixedValue As Writable
'JAVA TO VB CONVERTER NOTE: The field inputSchema was renamed since Visual Basic does not allow fields to have the same name as other class members:
Private inputSchema_Conflict As Schema
'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
'ORIGINAL LINE: public AddConstantColumnTransform(@JsonProperty("newColumnName") String newColumnName, @JsonProperty("newColumnType") org.datavec.api.transform.ColumnType newColumnType, @JsonProperty("fixedValue") org.datavec.api.writable.Writable fixedValue)
Public Sub New(ByVal newColumnName As String, ByVal newColumnType As ColumnType, ByVal fixedValue As Writable)
Me.newColumnName = newColumnName
Me.newColumnType = newColumnType
Me.fixedValue = fixedValue
End Sub
Public Overrides Function transform(ByVal inputSchema As Schema) As Schema
Dim outMeta As IList(Of ColumnMetaData) = New List(Of ColumnMetaData)(inputSchema.getColumnMetaData())
Dim newColMeta As ColumnMetaData = newColumnType.newColumnMetaData(newColumnName)
outMeta.Add(newColMeta)
Return inputSchema.newSchema(outMeta)
End Function
Public Overridable Property InputSchema As Schema
Set(ByVal inputSchema As Schema)
Me.inputSchema_Conflict = inputSchema
End Set
Get
Return inputSchema_Conflict
End Get
End Property
Public Overridable Function outputColumnName() As String
Return newColumnName
End Function
Public Overridable Function outputColumnNames() As String()
Return New String() {outputColumnName()}
End Function
Public Overridable Function columnNames() As String()
Return New String(){}
End Function
Public Overridable Function columnName() As String
Return newColumnName
End Function
Public Overridable Function map(ByVal writables As IList(Of Writable)) As IList(Of Writable) Implements Transform.map
Dim [out] As IList(Of Writable) = New List(Of Writable)(writables.Count + 1)
CType([out], List(Of Writable)).AddRange(writables)
[out].Add(fixedValue)
Return [out]
End Function
Public Overridable Function mapSequence(ByVal sequence As IList(Of IList(Of Writable))) As IList(Of IList(Of Writable)) Implements Transform.mapSequence
Dim outSeq As IList(Of IList(Of Writable)) = New List(Of IList(Of Writable))(sequence.Count)
For Each l As IList(Of Writable) In sequence
outSeq.Add(map(l))
Next l
Return outSeq
End Function
Public Overridable Function map(ByVal input As Object) As Object Implements Transform.map
Throw New System.NotSupportedException()
End Function
Public Overridable Function mapSequence(ByVal sequence As Object) As Object Implements Transform.mapSequence
Throw New System.NotSupportedException()
End Function
End Class
End Namespace
| 362
|
https://github.com/NunoEdgarGFlowHub/torchio/blob/master/torchio/transforms/augmentation/spatial/random_elastic_deformation.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
torchio
|
NunoEdgarGFlowHub
|
Python
|
Code
| 308
| 1,326
|
from typing import Tuple, Optional
import torch
import numpy as np
import SimpleITK as sitk
from ....utils import is_image_dict, check_consistent_shape
from ....torchio import LABEL, DATA, AFFINE, TYPE
from .. import Interpolation
from .. import RandomTransform
class RandomElasticDeformation(RandomTransform):
"""B-spline dense elastic deformation.
Args:
num_control_points:
deformation_std:
proportion_to_augment:
image_interpolation:
seed:
"""
def __init__(
self,
num_control_points: int = 4,
deformation_std: float = 15,
proportion_to_augment: float = 1,
image_interpolation: Interpolation = Interpolation.LINEAR,
seed: Optional[int] = None,
):
super().__init__(seed=seed)
self._bspline_transformation = None
self.num_control_points = max(num_control_points, 2)
self.deformation_std = max(deformation_std, 1)
self.proportion_to_augment = self.parse_probability(
proportion_to_augment,
'proportion_to_augment',
)
self.interpolation = self.parse_interpolation(image_interpolation)
def apply_transform(self, sample: dict) -> dict:
check_consistent_shape(sample)
bspline_params = None
sample['random_elastic_deformation'] = {}
params_dict = sample['random_elastic_deformation']
for image_dict in sample.values():
if not is_image_dict(image_dict):
continue
if image_dict[TYPE] == LABEL:
interpolation = Interpolation.NEAREST
else:
interpolation = self.interpolation
if bspline_params is None:
image = self.nib_to_sitk(
image_dict[DATA][0],
image_dict[AFFINE],
)
do_augmentation, bspline_params = self.get_params(
image,
self.num_control_points,
self.deformation_std,
self.proportion_to_augment,
)
params_dict['bspline_params'] = bspline_params
params_dict['do_augmentation'] = int(do_augmentation)
if not do_augmentation:
return sample
image_dict[DATA] = self.apply_bspline_transform(
image_dict[DATA],
image_dict[AFFINE],
bspline_params,
interpolation,
)
return sample
@staticmethod
def get_params(
image: sitk.Image,
num_control_points: int,
deformation_std: float,
probability: float,
) -> Tuple:
mesh_shape = 3 * (num_control_points,)
bspline_transform = sitk.BSplineTransformInitializer(image, mesh_shape)
default_params = bspline_transform.GetParameters()
bspline_params = torch.rand(len(default_params)) # [0, 1)
bspline_params -= 0.5 # [-0.5, 0.5)
bspline_params *= deformation_std # [-std/2, std/2)
do_augmentation = torch.rand(1) < probability
return do_augmentation, bspline_params.numpy()
@staticmethod
def get_bspline_transform(
image: sitk.Image,
num_control_points: int,
bspline_params: np.ndarray,
) -> sitk.BSplineTransformInitializer:
mesh_shape = 3 * (num_control_points,)
bspline_transform = sitk.BSplineTransformInitializer(image, mesh_shape)
bspline_transform.SetParameters(bspline_params.tolist())
return bspline_transform
def apply_bspline_transform(
self,
tensor: torch.Tensor,
affine: np.ndarray,
bspline_params: np.ndarray,
interpolation: Interpolation,
) -> torch.Tensor:
assert tensor.ndim == 4
assert len(tensor) == 1
image = self.nib_to_sitk(tensor[0], affine)
floating = reference = image
bspline_transform = self.get_bspline_transform(
image,
self.num_control_points,
bspline_params,
)
resampler = sitk.ResampleImageFilter()
resampler.SetReferenceImage(reference)
resampler.SetTransform(bspline_transform)
resampler.SetInterpolator(interpolation.value)
resampler.SetDefaultPixelValue(tensor.min().item())
resampler.SetOutputPixelType(sitk.sitkFloat32)
resampled = resampler.Execute(floating)
np_array = sitk.GetArrayFromImage(resampled)
np_array = np_array.transpose() # ITK to NumPy
tensor[0] = torch.from_numpy(np_array)
return tensor
| 30,458
|
https://github.com/KlimovKirill/EPAM.XT_NET_WEB/blob/master/EPAM.Task7/UsersAndAwords.PL.Interface/IUsersAndAwardsPL.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
EPAM.XT_NET_WEB
|
KlimovKirill
|
C#
|
Code
| 19
| 66
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UsersAndAwords.PL.Interface
{
public interface IUsersAndAwardsPL
{
}
}
| 22,615
|
https://github.com/maltissimo/OASYS1-ELETTRA-Extension/blob/master/orangecontrib/elettra/util/elettra_util.py
|
Github Open Source
|
Open Source
|
MIT
| null |
OASYS1-ELETTRA-Extension
|
maltissimo
|
Python
|
Code
| 105
| 419
|
__author__ = 'maltissimo'
import sys, os, numpy, platform
import orangecanvas.resources as resources
from PyQt5 import QtGui, QtCore
try:
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import figure as matfig
import pylab
except ImportError:
print(sys.exc_info()[1])
pass
import xraylib
from oasys.widgets import gui
class EmittingStream(QtCore.QObject):
textWritten = QtCore.pyqtSignal(str)
def write(self, text):
self.textWritten.emit(str(text))
class XoppyPlot:
@classmethod
def plot_histo(cls, plot_window, x, y, title, xtitle, ytitle, color='blue', replace=True):
matplotlib.rcParams['axes.formatter.useoffset']='False'
plot_window.addCurve(x, y, title, symbol='', color=color, xlabel=xtitle, ylabel=ytitle, replace=replace) #'+', '^', ','
if not xtitle is None: plot_window.setGraphXLabel(xtitle)
if not ytitle is None: plot_window.setGraphYLabel(ytitle)
if not title is None: plot_window.setGraphTitle(title)
# plot_window.setDrawModeEnabled(True, 'rectangle')
plot_window.setInteractiveMode('zoom',color='orange')
plot_window.resetZoom()
plot_window.replot()
plot_window.setActiveCurve(title)
| 46,840
|
https://github.com/everpay/consoles/blob/master/api/services/teams/verifyInvitationToken.service.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
consoles
|
everpay
|
JavaScript
|
Code
| 38
| 112
|
import { ApolloError } from 'apollo-server-express';
import { getDetailTeamInvitation } from '~/repository/team_invitations.repository';
export async function verifyInvitationToken(token) {
const [teamInvitation] = await getDetailTeamInvitation(token);
if (!teamInvitation || teamInvitation.status === 'inactive') {
throw new ApolloError('Token not valid');
}
return teamInvitation;
}
| 44,406
|
https://github.com/meta-rti/Basic-Video-Call/blob/master/Group-Video/OpenVideoCall-iOS-Objective-C/OpenVideoCall/FileCenter.h
|
Github Open Source
|
Open Source
|
MIT
| null |
Basic-Video-Call
|
meta-rti
|
C
|
Code
| 40
| 126
|
//
// FileCenter.h
// OpenVideoCall
//
// Created by 3 on 2020/12/15.
// Portions Copyright (c) 2020 meta-rti. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface FileCenter : NSObject
+ (NSString *)logDirectory;
+ (NSString *)logFilePath;
+ (NSString *)audioFilePath;
@end
NS_ASSUME_NONNULL_END
| 787
|
https://github.com/gparap/android/blob/master/e-commerce/app/src/androidTest/java/gparap/apps/e_commerce/ui/auth/LoginActivityInstrumentedTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
android
|
gparap
|
Java
|
Code
| 344
| 1,751
|
/*
* Copyright 2023 gparap
*
* 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 gparap.apps.e_commerce.ui.auth;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.RootMatchers.withDecorView;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.CoreMatchers.not;
import android.view.View;
import androidx.test.core.app.ActivityScenario;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.espresso.Espresso;
import org.junit.Before;
import org.junit.Test;
import gparap.apps.e_commerce.R;
import gparap.apps.e_commerce.ui.auth.LoginActivity;
public class LoginActivityInstrumentedTest {
private View decorView;
@Before
public void setUp() {
ActivityScenario<LoginActivity> activityScenario = ActivityScenario.launch(LoginActivity.class);
//get the root view of this activity
activityScenario.onActivity(activity -> {
decorView = activity.getWindow().getDecorView();
});
}
@Test
public void isVisible_AppLogo() {
onView(withId(R.id.image_view_login)).check(matches(isDisplayed()));
}
@Test
public void isVisible_Email() {
onView(withId(R.id.edit_text_login_username)).check(matches(isDisplayed()));
}
@Test
public void isVisible_Password() {
onView(withId(R.id.edit_text_login_password)).check(matches(isDisplayed()));
}
@Test
public void isNotVisible_ProgressBar() {
onView(withId(R.id.progress_login)).check(matches(not(isDisplayed())));
}
@Test
public void isVisible_LoginButton() {
onView(withId(R.id.button_login)).check(matches(isDisplayed()));
}
@Test
public void isVisible_UserNotRegisterText() {
onView(withId(R.id.text_view_user_not_registered)).check(matches(isDisplayed()));
}
@Test
public void isVisible_RegisterButton() {
onView(withId(R.id.button_goto_register)).check(matches(isDisplayed()));
}
@Test
public void loginUser_isFailed() {
//using test credentials
String username = "test_user";
String password = "000"; //wrong password
//try to login user
onView(withId(R.id.edit_text_login_username)).perform(click());
onView(withId(R.id.edit_text_login_username)).perform(typeText(username));
Espresso.closeSoftKeyboard();
onView(withId(R.id.edit_text_login_password)).perform(click());
onView(withId(R.id.edit_text_login_password)).perform(typeText(password));
Espresso.closeSoftKeyboard();
onView(withId(R.id.button_login)).perform(click());
//asset login failed
onView(withText(R.string.text_login_failed))
.inRoot(withDecorView(not(decorView)))
.check(matches(isDisplayed()));
}
@Test
public void loginUser_isSuccessful() {
//using test credentials
String username = "test_user";
String password = "123456"; //correct password
String welcomeText = ApplicationProvider.getApplicationContext().getResources().getString(R.string.text_welcome_user_after_login) + username;
//try to login user
onView(withId(R.id.edit_text_login_username)).perform(click());
onView(withId(R.id.edit_text_login_username)).perform(typeText(username));
Espresso.closeSoftKeyboard();
onView(withId(R.id.edit_text_login_password)).perform(click());
onView(withId(R.id.edit_text_login_password)).perform(typeText(password));
Espresso.closeSoftKeyboard();
onView(withId(R.id.button_login)).perform(click());
//asset login succeeded
onView(withText(welcomeText))
.inRoot(withDecorView(not(decorView)))
.check(matches(isDisplayed()));
}
@Test
public void redirectToRegistration() {
onView(withId(R.id.button_goto_register)).perform(click());
onView(withId(R.id.layout_activity_register)).check(matches(isDisplayed()));
}
@Test
public void redirectToRegistration_passInputDataFromLogin() {
//test credentials
String username = "test_user";
String password = "123456";
//enter login input and redirect to registration
onView(withId(R.id.edit_text_login_username)).perform(click());
onView(withId(R.id.edit_text_login_username)).perform(typeText(username));
Espresso.closeSoftKeyboard();
onView(withId(R.id.edit_text_login_password)).perform(click());
onView(withId(R.id.edit_text_login_password)).perform(typeText(password));
Espresso.closeSoftKeyboard();
onView(withId(R.id.button_goto_register)).perform(click());
//assert data passed successfully
onView(withId(R.id.edit_text_register_username)).check(matches(withText(username)));
onView(withId(R.id.edit_text_register_password)).check(matches(withText(password)));
}
}
| 23,770
|
https://github.com/jlankitus/DaddysPlayground/blob/master/Assets/Shadertoy/Gears2.shader
|
Github Open Source
|
Open Source
|
Unlicense
| null |
DaddysPlayground
|
jlankitus
|
GLSL
|
Code
| 552
| 1,870
|
Shader "ShaderMan/Gears2"
{
Properties{
bg_color ("Background Color", Color) = (0,0,0,0)
}
SubShader
{
Tags { "RenderType" = "Transparent" "Queue" = "Transparent" }
Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
fixed4 bg_color;
float4 vec4(float x,float y,float z,float w){return float4(x,y,z,w);}
float4 vec4(float x){return float4(x,x,x,x);}
float4 vec4(float2 x,float2 y){return float4(float2(x.x,x.y),float2(y.x,y.y));}
float4 vec4(float3 x,float y){return float4(float3(x.x,x.y,x.z),y);}
float3 vec3(float x,float y,float z){return float3(x,y,z);}
float3 vec3(float x){return float3(x,x,x);}
float3 vec3(float2 x,float y){return float3(float2(x.x,x.y),y);}
float2 vec2(float x,float y){return float2(x,y);}
float2 vec2(float x){return float2(x,x);}
float vec(float x){return float(x);}
struct VertexInput {
float4 vertex : POSITION;
float2 uv:TEXCOORD0;
float4 tangent : TANGENT;
float3 normal : NORMAL;
//VertexInput
};
struct VertexOutput {
float4 pos : SV_POSITION;
float2 uv:TEXCOORD0;
//VertexOutput
};
VertexOutput vert (VertexInput v)
{
VertexOutput o;
o.pos = UnityObjectToClipPos (v.vertex);
o.uv = v.uv;
//VertexFactory
return o;
}
// Inspired by:
// http://cmdrkitten.tumblr.com/post/172173936860
#define Pi 3.14159265359
struct Gear
{
float t; // Time
float gearR; // Gear radius
float teethH; // Teeth height
float teethR; // Teeth "roundness"
float teethCount; // Teeth count
float diskR; // Inner or outer border radius
float3 color; // Color
};
float GearFunction(float2 uv, Gear g)
{
float r = length(uv);
float a = atan2( uv.x,uv.y);
// Gear polar function:
// A sine squashed by a logistic function gives a convincing
// gear shape!
float p = g.gearR-0.5*g.teethH +
g.teethH/(1.0+exp(g.teethR*sin(g.t + g.teethCount*a)));
float gear = r - p;
float disk = r - g.diskR;
return g.gearR > g.diskR ? max(-disk, gear) : max(disk, -gear);
}
float GearDe(float2 uv, Gear g)
{
// IQ's f/|Grad(f)| distance estimator:
float f = GearFunction(uv, g);
float2 eps = vec2(0.0001, 0);
float2 grad = vec2(
GearFunction(uv + eps.xy, g) - GearFunction(uv - eps.xy, g),
GearFunction(uv + eps.yx, g) - GearFunction(uv - eps.yx, g)) / (2.0*eps.x);
return (f)/length(grad);
}
float GearShadow(float2 uv, Gear g)
{
float r = length(uv+vec2(0.1));
float de = r - g.diskR + 0.0*(g.diskR - g.gearR);
float eps = 0.4*g.diskR;
return smoothstep(eps, 0., abs(de));
}
void DrawGear(inout float3 color, float2 uv, Gear g, float eps)
{
float d = smoothstep(eps, -eps, GearDe(uv, g));
float s = 1.0 - 0.7*GearShadow(uv, g);
color = lerp(s*color, g.color, d);
}
fixed4 frag(VertexOutput vertex_output) : SV_Target
{
float t = 0.5*_Time.y;
float2 uv = 2.0*(vertex_output.uv - 0.5*1)/1;
float eps = 2.0/1;
// Scene parameters;
float3 base = vec3(0.95, 0.7, 0.2);
base.xyz = bg_color.xyz;
float count = 8.0;
// Gear outer = Gear(0.0, 0.8, 0.08, 4.0, 32.0, 0.9, base);
// Gear inner = Gear(0.0, 0.4, 0.08, 4.0, 16.0, 0.3, base);
/*
struct Gear
{
float t; // Time
float gearR; // Gear radius
float teethH; // Teeth height
float teethR; // Teeth "roundness"
float teethCount; // Teeth count
float diskR; // Inner or outer border radius
float3 color; // Color
};
*/
Gear outer;
outer.t = 0.0;
outer.gearR = 0.8;
outer.teethH = 0.08;
outer.teethR = 4.0;
outer.teethCount = 32.0;
outer.diskR = 0.9;
outer.color = base;
Gear inner;
inner.t = 0.0;
inner.gearR = 0.4;
inner.teethH = 0.08;
inner.teethR = 4.0;
inner.teethCount = 16.0;
inner.diskR = 0.3;
inner.color = base;
// Draw inner gears back to front:
float3 color = vec3(0.0);
[unroll(100)]
for(float i=0.0; i<count; i++)
{
t += 2.0*Pi/count;
inner.t = 16.0*t;
inner.color = base*(0.35 + 0.6*i/(count-1.0));
DrawGear(color, uv+0.4*vec2(cos(t),sin(t)), inner, eps);
}
// Draw outer gear:
DrawGear(color, uv, outer, eps);
return vec4(color,1.0);
}
ENDCG
}
}
}
| 20,889
|
https://github.com/jptrsn/meet-cute/blob/master/angular/src/app/modules/popup/pages/light/light.component.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
meet-cute
|
jptrsn
|
TypeScript
|
Code
| 138
| 516
|
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';
import { WledService } from '../../services/wled.service';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({
selector: 'app-light',
templateUrl: './light.component.html',
styleUrls: ['./light.component.scss']
})
export class LightComponent implements OnInit, OnDestroy {
state: any = {};
address: string = '';
stateNames: string[];
stateCtrl: FormControl;
constructor(private wled: WledService,
private snackBar: MatSnackBar) {
this.stateCtrl = new FormControl('');
}
async ngOnInit() {
const {address, state} = await this.wled.getLightDetails();
this.address = address;
this.handleLightState_(state);
const savedStates = await this.wled.getSavedStates();
this.stateNames = Object.keys(savedStates);
}
ngOnDestroy(): void {
}
private toast_(message: string) {
this.snackBar.open(message, null, {duration: 1000});
}
private handleLightState_(state: any) {
this.state = state;
}
openAddress() {
chrome.tabs.create({url: `http://${this.address}`});
}
viewState() {
console.log('viewState', this.stateCtrl.value);
this.wled.viewState(this.stateCtrl.value).then(() => {
this.toast_('Opened in tab')
this.openAddress()
});
}
saveState() {
console.log('saveState', this.stateCtrl.value);
this.wled.saveState(this.stateCtrl.value).then(() => this.toast_('Done!'));
}
}
| 10,769
|
https://github.com/catapult-project/catapult/blob/master/telemetry/telemetry/wpr/archive_info_unittest.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
catapult
|
catapult-project
|
Python
|
Code
| 837
| 5,001
|
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
import json
import os
import shutil
import tempfile
import unittest
import six
import mock
from py_utils import cloud_storage # pylint: disable=import-error
from telemetry.page import page
from telemetry.wpr import archive_info
class MockPage(page.Page):
def __init__(self, url, name=None, platform_specific=False):
super(MockPage, self).__init__(url, None, name=name)
self._platform_specific = platform_specific
page1 = MockPage('http://www.page1.com/', 'Page1')
page2 = MockPage('http://www.page2.com/', 'Page2', platform_specific=True)
page3 = MockPage('http://www.page3.com/', 'Page3', platform_specific=True)
pageNew1 = MockPage('http://www.new1.com/', 'New1')
pageNew2 = MockPage('http://www.new2.com/', 'New2', platform_specific=True)
recording1 = 'data_abcdef0001.wprgo'
recording2 = 'data_abcdef0002.wprgo'
recording3 = 'data_abcdef0003.wprgo'
recording4 = 'data_abcdef0004.wprgo'
recording5 = 'data_abcdef0005.wprgo'
_DEFAULT_PLATFORM = archive_info._DEFAULT_PLATFORM
default_archives_info_contents_dict = {
"platform_specific": True,
"archives": {
"Page1": {
_DEFAULT_PLATFORM: recording1
},
"Page2": {
_DEFAULT_PLATFORM: recording2
},
"Page3": {
_DEFAULT_PLATFORM: recording1,
"win": recording2,
"mac": recording3,
"linux": recording4,
"android": recording5
}
}
}
default_archive_info_contents = json.dumps(default_archives_info_contents_dict)
default_wpr_files = [
'data_abcdef0001.wprgo', 'data_abcdef0002.wprgo', 'data_abcdef0003.wprgo',
'data_abcdef0004.wprgo', 'data_abcdef0005.wprgo']
_BASE_ARCHIVE = {
u'platform_specific': True,
u'description': (u'Describes the Web Page Replay archives for a'
u' story set. Don\'t edit by hand! Use record_wpr for'
u' updating.'),
u'archives': {},
}
class WprArchiveInfoTest(unittest.TestCase):
def setUp(self):
self.tmp_dir = tempfile.mkdtemp()
# Set file for the metadata.
self.story_set_archive_info_file = os.path.join(
self.tmp_dir, 'story_name.json')
self.maxDiff = None
def tearDown(self):
shutil.rmtree(self.tmp_dir)
def createArchiveInfo(
self, archive_data=default_archive_info_contents,
cloud_storage_bucket=cloud_storage.PUBLIC_BUCKET, wpr_files=None):
# Cannot set lists as a default parameter, so doing it this way.
if wpr_files is None:
wpr_files = default_wpr_files
with open(self.story_set_archive_info_file, 'w') as f:
f.write(archive_data)
assert isinstance(wpr_files, list)
for wpr_file in wpr_files:
assert isinstance(wpr_file, six.string_types)
with open(os.path.join(self.tmp_dir, wpr_file), 'w') as f:
f.write(archive_data)
return archive_info.WprArchiveInfo.FromFile(
self.story_set_archive_info_file, cloud_storage_bucket)
def testInitNotPlatformSpecific(self):
with open(self.story_set_archive_info_file, 'w') as f:
f.write('{}')
with self.assertRaises(AssertionError):
self.createArchiveInfo(archive_data='{}')
@mock.patch('telemetry.wpr.archive_info.cloud_storage.GetIfChanged')
def testDownloadArchivesIfNeededAllOrOneNeeded(self, get_mock):
test_archive_info = self.createArchiveInfo()
test_archive_info.DownloadArchivesIfNeeded()
expected_recordings = [
recording1, recording1, recording2, recording2, recording3, recording4,
recording5
]
expected_calls = [
mock.call(os.path.join(self.tmp_dir, r), cloud_storage.PUBLIC_BUCKET)
for r in expected_recordings
]
get_mock.assert_has_calls(expected_calls, any_order=True)
@mock.patch('telemetry.wpr.archive_info.cloud_storage.GetIfChanged')
def testDownloadArchivesIfNeededWithStoryNames(self, get_mock):
test_archive_info = self.createArchiveInfo()
story_names = ['Page1', 'Page2', 'Not_used']
test_archive_info.DownloadArchivesIfNeeded(story_names=story_names)
expected_calls = [
mock.call(os.path.join(self.tmp_dir, r), cloud_storage.PUBLIC_BUCKET)
for r in (recording1, recording2)
]
get_mock.assert_has_calls(expected_calls, any_order=True)
self.assertEqual(get_mock.call_count, 2)
@mock.patch('telemetry.wpr.archive_info.cloud_storage.GetIfChanged')
def testDownloadArchivesIfNeededNonDefault(self, get_mock):
data = {
'platform_specific': True,
'archives': {
'http://www.page3.com/': {
_DEFAULT_PLATFORM: 'data_abcdef0001.wprgo',
'win': 'data_abcdef0002.wprgo',
'linux': 'data_abcdef0004.wprgo',
'mac': 'data_abcdef0003.wprgo',
'android': 'data_abcdef0005.wprgo'},
'Page1': {_DEFAULT_PLATFORM: 'data_abcdef0003.wprgo'},
'Page2': {_DEFAULT_PLATFORM: 'data_abcdef0002.wprgo'}
}
}
test_archive_info = self.createArchiveInfo(
archive_data=json.dumps(data, separators=(',', ': ')))
test_archive_info.DownloadArchivesIfNeeded(target_platforms=['linux'])
expected_calls = [
mock.call(os.path.join(self.tmp_dir, r), cloud_storage.PUBLIC_BUCKET)
for r in (recording1, recording2, recording3, recording4)
]
get_mock.assert_has_calls(expected_calls, any_order=True)
@mock.patch('telemetry.wpr.archive_info.cloud_storage.GetIfChanged')
def testDownloadArchivesIfNeededNoBucket(self, get_mock):
test_archive_info = self.createArchiveInfo(cloud_storage_bucket=None)
test_archive_info.DownloadArchivesIfNeeded()
self.assertEqual(get_mock.call_count, 0)
def testWprFilePathForStoryDefault(self):
test_archive_info = self.createArchiveInfo()
self.assertEqual(
test_archive_info.WprFilePathForStory(page1),
os.path.join(self.tmp_dir, recording1))
self.assertEqual(
test_archive_info.WprFilePathForStory(page2),
os.path.join(self.tmp_dir, recording2))
self.assertEqual(
test_archive_info.WprFilePathForStory(page3),
os.path.join(self.tmp_dir, recording1))
def testWprFilePathForStoryMac(self):
test_archive_info = self.createArchiveInfo()
self.assertEqual(test_archive_info.WprFilePathForStory(page1, 'mac'),
os.path.join(self.tmp_dir, recording1))
self.assertEqual(test_archive_info.WprFilePathForStory(page2, 'mac'),
os.path.join(self.tmp_dir, recording2))
self.assertEqual(test_archive_info.WprFilePathForStory(page3, 'mac'),
os.path.join(self.tmp_dir, recording3))
def testWprFilePathForStoryWin(self):
test_archive_info = self.createArchiveInfo()
self.assertEqual(test_archive_info.WprFilePathForStory(page1, 'win'),
os.path.join(self.tmp_dir, recording1))
self.assertEqual(test_archive_info.WprFilePathForStory(page2, 'win'),
os.path.join(self.tmp_dir, recording2))
self.assertEqual(test_archive_info.WprFilePathForStory(page3, 'win'),
os.path.join(self.tmp_dir, recording2))
def testWprFilePathForStoryAndroid(self):
test_archive_info = self.createArchiveInfo()
self.assertEqual(test_archive_info.WprFilePathForStory(page1, 'android'),
os.path.join(self.tmp_dir, recording1))
self.assertEqual(test_archive_info.WprFilePathForStory(page2, 'android'),
os.path.join(self.tmp_dir, recording2))
self.assertEqual(test_archive_info.WprFilePathForStory(page3, 'android'),
os.path.join(self.tmp_dir, recording5))
def testWprFilePathForStoryLinux(self):
test_archive_info = self.createArchiveInfo()
self.assertEqual(test_archive_info.WprFilePathForStory(page1, 'linux'),
os.path.join(self.tmp_dir, recording1))
self.assertEqual(test_archive_info.WprFilePathForStory(page2, 'linux'),
os.path.join(self.tmp_dir, recording2))
self.assertEqual(test_archive_info.WprFilePathForStory(page3, 'linux'),
os.path.join(self.tmp_dir, recording4))
def testWprFilePathForStoryBadStory(self):
test_archive_info = self.createArchiveInfo()
self.assertIsNone(test_archive_info.WprFilePathForStory(pageNew1))
def testAddRecordedStoriesNoStories(self):
test_archive_info = self.createArchiveInfo()
old_data = test_archive_info._data.copy()
test_archive_info.AddNewTemporaryRecording()
test_archive_info.AddRecordedStories(None)
self.assertDictEqual(old_data, test_archive_info._data)
def assertWprFileDoesNotExist(self, file_name):
sha_file = file_name + '.sha1'
self.assertFalse(os.path.isfile(os.path.join(self.tmp_dir, sha_file)))
self.assertFalse(os.path.isfile(os.path.join(self.tmp_dir, file_name)))
def assertWprFileDoesExist(self, file_name):
sha_file = file_name + '.sha1'
self.assertTrue(os.path.isfile(os.path.join(self.tmp_dir, sha_file)))
self.assertTrue(os.path.isfile(os.path.join(self.tmp_dir, file_name)))
@mock.patch(
'telemetry.wpr.archive_info.cloud_storage.CalculateHash',
return_value='abcdef0006deadcode')
def testAddRecordedStoriesDefault(self, hash_mock):
test_archive_info = self.createArchiveInfo()
self.assertWprFileDoesNotExist('story_name_abcdef0006.wprgo')
new_temp_recording = os.path.join(self.tmp_dir, 'recording.wprgo')
with open(new_temp_recording, 'w') as f:
f.write('wpr data')
test_archive_info.AddNewTemporaryRecording(new_temp_recording)
test_archive_info.AddRecordedStories([page2, page3])
with open(self.story_set_archive_info_file, 'r') as f:
archive_file_contents = json.load(f)
expected_archive_contents = _BASE_ARCHIVE.copy()
expected_archive_contents['archives'] = {
page1.name: {
_DEFAULT_PLATFORM: recording1
},
page2.name: {
_DEFAULT_PLATFORM: 'story_name_abcdef0006.wprgo'
},
page3.name: {
_DEFAULT_PLATFORM: 'story_name_abcdef0006.wprgo',
'linux': recording4,
'mac': recording3,
'win': recording2,
'android': recording5
}
}
self.assertDictEqual(expected_archive_contents, archive_file_contents)
# Ensure the saved JSON does not contain trailing spaces.
with open(self.story_set_archive_info_file, 'rU') as f:
for line in f:
self.assertFalse(line.rstrip('\n').endswith(' '))
self.assertWprFileDoesExist('story_name_abcdef0006.wprgo')
self.assertEquals(hash_mock.call_count, 1)
hash_mock.assert_called_with(new_temp_recording)
@mock.patch(
'telemetry.wpr.archive_info.cloud_storage.CalculateHash',
return_value='abcdef0006deadcode')
def testAddRecordedStoriesNotDefault(self, hash_mock):
test_archive_info = self.createArchiveInfo()
self.assertWprFileDoesNotExist('story_name_abcdef0006.wprgo')
new_temp_recording = os.path.join(self.tmp_dir, 'recording.wprgo')
with open(new_temp_recording, 'w') as f:
f.write('wpr data')
test_archive_info.AddNewTemporaryRecording(new_temp_recording)
test_archive_info.AddRecordedStories([page2, page3],
target_platform='android')
with open(self.story_set_archive_info_file, 'r') as f:
archive_file_contents = json.load(f)
expected_archive_contents = _BASE_ARCHIVE.copy()
expected_archive_contents['archives'] = {
page1.name: {
_DEFAULT_PLATFORM: recording1
},
page2.name: {
_DEFAULT_PLATFORM: recording2,
'android': 'story_name_abcdef0006.wprgo'
},
page3.name: {
_DEFAULT_PLATFORM: recording1,
'linux': recording4,
'mac': recording3,
'win': recording2,
'android': 'story_name_abcdef0006.wprgo'
},
}
self.assertDictEqual(expected_archive_contents, archive_file_contents)
# Ensure the saved JSON does not contain trailing spaces.
with open(self.story_set_archive_info_file, 'rU') as f:
for line in f:
self.assertFalse(line.rstrip('\n').endswith(' '))
self.assertWprFileDoesExist('story_name_abcdef0006.wprgo')
self.assertEqual(hash_mock.call_count, 1)
hash_mock.assert_called_with(new_temp_recording)
def testAddRecordedStoriesNewPage(self):
test_archive_info = self.createArchiveInfo()
self.assertWprFileDoesNotExist('story_name_abcdef0006.wprgo')
self.assertWprFileDoesNotExist('story_name_abcdef0007.wprgo')
new_temp_recording = os.path.join(self.tmp_dir, 'recording.wprgo')
with mock.patch('telemetry.wpr.archive_info.cloud_storage.CalculateHash',
return_value='abcdef0006deadcode') as hash_mock:
with open(new_temp_recording, 'w') as f:
f.write('wpr data')
test_archive_info.AddNewTemporaryRecording(new_temp_recording)
self.assertEqual(hash_mock.call_count, 0)
test_archive_info.AddRecordedStories([pageNew1])
hash_mock.assert_any_call(new_temp_recording)
self.assertEqual(hash_mock.call_count, 1)
with mock.patch('telemetry.wpr.archive_info.cloud_storage.CalculateHash',
return_value='abcdef0007deadcode') as hash_mock:
with open(new_temp_recording, 'w') as f:
f.write('wpr data2')
test_archive_info.AddNewTemporaryRecording(new_temp_recording)
self.assertEqual(hash_mock.call_count, 0)
test_archive_info.AddRecordedStories([pageNew2],
target_platform='android')
hash_mock.assert_any_call(new_temp_recording)
self.assertEqual(hash_mock.call_count, 1)
with open(self.story_set_archive_info_file, 'r') as f:
archive_file_contents = json.load(f)
expected_archive_contents = _BASE_ARCHIVE.copy()
expected_archive_contents['archives'] = {
page1.name: {
_DEFAULT_PLATFORM: recording1
},
page2.name: {
_DEFAULT_PLATFORM: recording2,
},
page3.name: {
_DEFAULT_PLATFORM: recording1,
'linux': recording4,
'mac': recording3,
'win': recording2,
'android': recording5
},
pageNew1.name: {
_DEFAULT_PLATFORM: 'story_name_abcdef0006.wprgo'
},
pageNew2.name: {
_DEFAULT_PLATFORM: 'story_name_abcdef0007.wprgo',
'android': 'story_name_abcdef0007.wprgo'
}
}
self.assertDictEqual(expected_archive_contents, archive_file_contents)
# Ensure the saved JSON does not contain trailing spaces.
with open(self.story_set_archive_info_file, 'rU') as f:
for line in f:
self.assertFalse(line.rstrip('\n').endswith(' '))
self.assertWprFileDoesExist('story_name_abcdef0006.wprgo')
self.assertWprFileDoesExist('story_name_abcdef0007.wprgo')
| 7,102
|
https://github.com/ugcmedia/mooladev/blob/master/resources/views/public/homepage/partials/top-links.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
mooladev
|
ugcmedia
|
PHP
|
Code
| 88
| 582
|
<section class="footer pt-5">
<div class="container">
<div class="footer-top py-5">
<div class="row">
@php
$topFooter = AppClass::getTopFooter();
@endphp
@foreach($topFooter as $tfooter)
<div class="col-6 col-lg-2 col-md-3">
<div class="ft-link">
<span class="text-dark fw-700">{{$tfooter->title}}</span>
<ul class="list-unstyled">
@if($tfooter->list_type == 'stores')
@foreach(AppClass::getStoreByList($tfooter->stores) as $ftstores)
<li><a href="{{url('store/'.str_slug($ftstores->store_slug))}}" class="success-link font-13 fw-400">{{$ftstores->store_name}} offers</a></li>
@endforeach
@elseif($tfooter->list_type == 'categories')
@foreach(AppClass::getCatByList($tfooter->categories) as $ftcat)
<li><a href="{{url('category/'.str_slug($ftcat->cat_slug))}}" class="success-link font-13 fw-400">{{$ftcat->cat_name}} offers</a></li>
@endforeach
@elseif($tfooter->list_type == 'brand')
@foreach(AppClass::getBrandByList($tfooter->brands) as $ftbrand)
<li><a href="{{url('brand/'.str_slug($ftbrand->brand_slug))}}" class="success-link font-13 fw-400">{{$ftbrand->brand_name}} offers</a></li>
@endforeach
@elseif($tfooter->list_type == 'tag')
@foreach(AppClass::getTagsByList($tfooter->tags) as $ftags)
<li><a href="{{url('tag/'.str_slug($ftags->tag_slug))}}" class="success-link font-13 fw-400">{{$ftags->tag_name}} offers</a></li>
@endforeach
@endif
</ul>
</div>
</div>
@endforeach
</div>
</section>
| 48,228
|
https://github.com/keen/keen/blob/master/packages/typography/src/types.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
keen
|
keen
|
TypeScript
|
Code
| 37
| 81
|
export type FontWeight =
| 'normal'
| 'bold'
| 'bolder'
| 'lighter'
| 100
| 200
| 300
| 400
| 500
| 600
| 700
| 800
| 900;
export type LineHeight = number | string;
| 23,529
|
https://github.com/bronto/bronto-api-java-sdk/blob/master/client/src/main/java/com/bronto/api/model/DeliveryFilter.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
bronto-api-java-sdk
|
bronto
|
Java
|
Code
| 800
| 1,993
|
package com.bronto.api.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for deliveryFilter complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="deliveryFilter">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="type" type="{http://api.bronto.com/v4}filterType" minOccurs="0"/>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="start" type="{http://api.bronto.com/v4}dateValue" maxOccurs="unbounded" minOccurs="0"/>
* <element name="status" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="deliveryType" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "deliveryFilter", propOrder = {
"type",
"id",
"messageId",
"start",
"status",
"deliveryType"
})
public class DeliveryFilter {
@XmlSchemaType(name = "string")
protected FilterType type;
@XmlElement(nillable = true)
protected List<String> id;
@XmlElement(nillable = true)
protected List<String> messageId;
@XmlElement(nillable = true)
protected List<DateValue> start;
@XmlElement(nillable = true)
protected List<String> status;
@XmlElement(nillable = true)
protected List<String> deliveryType;
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link FilterType }
*
*/
public FilterType getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link FilterType }
*
*/
public void setType(FilterType value) {
this.type = value;
}
/**
* Gets the value of the id property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the id property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getId() {
if (id == null) {
id = new ArrayList<String>();
}
return this.id;
}
/**
* Gets the value of the messageId property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the messageId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMessageId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getMessageId() {
if (messageId == null) {
messageId = new ArrayList<String>();
}
return this.messageId;
}
/**
* Gets the value of the start property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the start property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getStart().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DateValue }
*
*
*/
public List<DateValue> getStart() {
if (start == null) {
start = new ArrayList<DateValue>();
}
return this.start;
}
/**
* Gets the value of the status property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the status property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getStatus().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getStatus() {
if (status == null) {
status = new ArrayList<String>();
}
return this.status;
}
/**
* Gets the value of the deliveryType property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the deliveryType property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDeliveryType().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getDeliveryType() {
if (deliveryType == null) {
deliveryType = new ArrayList<String>();
}
return this.deliveryType;
}
}
| 14,989
|
https://github.com/odinshen/ComputeLibrary_17.9_BareMetal/blob/master/documentation/classarm__compute_1_1graph_1_1_activation_layer.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ComputeLibrary_17.9_BareMetal
|
odinshen
|
JavaScript
|
Code
| 20
| 182
|
var classarm__compute_1_1graph_1_1_activation_layer =
[
[ "ActivationLayer", "classarm__compute_1_1graph_1_1_activation_layer.xhtml#afac1172e48fcb7c2e806f1629da9624a", null ],
[ "instantiate_node", "classarm__compute_1_1graph_1_1_activation_layer.xhtml#aaa115a53f16316ee0a38398e90415968", null ],
[ "print_info", "classarm__compute_1_1graph_1_1_activation_layer.xhtml#ab9acab91b0e030ef0c969aa9c2fe7529", null ]
];
| 32,193
|
https://github.com/Jodyheryanto/Pustaka_Obor/blob/master/database/migrations/2020_12_08_054321_create_tb_distributor.php
|
Github Open Source
|
Open Source
|
MIT
| null |
Pustaka_Obor
|
Jodyheryanto
|
PHP
|
Code
| 72
| 395
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTbDistributor extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tb_distributor', function (Blueprint $table) {
$table->increments('id_distributor');
$table->string('NPWP', 255)->nullable();
$table->string('nm_distributor', 255);
$table->string('email', 255);
$table->string('telepon', 255);
$table->char('tb_kota_id', 4);
$table->char('tb_kecamatan_id', 7);
$table->char('tb_kelurahan_id', 10);
$table->bigInteger('kode_pos');
$table->string('alamat', 255);
$table->foreign('tb_kota_id')->references('id')->on('tb_kota');
$table->foreign('tb_kecamatan_id')->references('id')->on('tb_kecamatan');
$table->foreign('tb_kelurahan_id')->references('id')->on('tb_kelurahan');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tb_distributor');
}
}
| 8,067
|
https://github.com/leanprover/lean4/blob/master/doc/examples/ICERM2022/notation.lean
|
Github Open Source
|
Open Source
|
Apache-2.0, LLVM-exception, NCSA, LGPL-3.0-only, LicenseRef-scancode-inner-net-2.0, BSD-3-Clause, LGPL-2.0-or-later, Spencer-94, LGPL-2.1-or-later, HPND, LicenseRef-scancode-pcre, ISC, LGPL-2.1-only, LicenseRef-scancode-other-permissive, SunPro, CMU-Mach
| 2,023
|
lean4
|
leanprover
|
Lean
|
Code
| 203
| 422
|
import Lean
def f (x y : Nat) := x * y + 1
infixl:65 " *' " => f
#check 2 *' 3
notation "unitTest " x => Prod.mk x ()
#check unitTest 42
notation "parenthesisTest " x => Nat.sub (x)
#check parenthesisTest 12
def Set (α : Type u) := α → Prop
def setOf {α : Type} (p : α → Prop) : Set α := p
notation "{ " x " | " p " }" => setOf (fun x => p)
#check { x | x ≤ 1 }
notation "cdotTest " "(" x ", " y ")" => Prod.map (· + 1) (1 + ·) (x, y)
#check cdotTest (13, 12)
notation "tupleFunctionTest " "(" x ", " y ")"=> Prod.map (Nat.add 1) (Nat.add 2) (x, y)
#check tupleFunctionTest (15, 12)
notation "diag " x => Prod.mk x x
#check diag 12
open Lean Meta PrettyPrinter Delaborator SubExpr in
@[delab app.Prod.mk] def delabDoubleRhsTest : Delab := do
let e ← getExpr
let #[_, _, x, y] := e.getAppArgs | failure
guard (← isDefEq x y)
let stx ← withAppArg delab
`(diag $stx)
#check diag 3
#check (3, 3)
#check (3, 4)
#check (2+1, 3)
#check (true, true)
| 27,824
|
https://github.com/jimmyzhong/webui-aria2/blob/master/js/services/rpc/sockcall.js
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
webui-aria2
|
jimmyzhong
|
JavaScript
|
Code
| 302
| 799
|
app.factory('$sockcall', ['$_', '$json', '$name', '$utils', function(_, JSON, name, utils) {
return {
// true when sockrpc is ready to be used,
// false when either initializing
// or no support for web sockets
initialized: false,
// ongoing connection handles containing connection id and callbacks
handles: [],
// websocket connection socket used for all connections
sock: null,
// connection configuration
conf: null,
// socket connection scheme, default to unencrypted connection
scheme: 'ws',
// called when a connection error occurs
onerror: function() {
_.each(this.handles, function(h) { h.error() });
this.handles = [];
},
// when connection opens
onopen: function() {
this.initialized = true;
},
// when message is recieved
onmessage: function(message) {
var data = JSON.parse(message.data);
// reverse loop because we are deleting elements
// while looping over the old items
for (var i = this.handles.length - 1; i >= 0; i--) {
if (this.handles[i].id === data.id) {
this.handles[i].success(data);
this.handles.splice(i, 1);
return;
}
}
},
// call to use the rpc
invoke: function(opts) {
var data = {
jsonrpc: 2.0,
id: name + '_' + utils.randStr(),
method: opts.func,
params: opts.params && opts.params.length ? opts.params : undefined
};
if (data.params && !data.params.length) data.params = undefined;
this.handles.push({
success: opts.success || angular.noop,
error: opts.error || angular.noop,
id: data.id
});
this.sock.send( JSON.stringify(data) );
},
// should be called initially to start using the sock rpc
init: function(conf) {
if (typeof WebSocket == "undefined") {
return;
}
this.conf = conf || this.conf;
this.initialized = false;
this.scheme = this.conf.encryption ? 'wss' : 'ws';
if (this.sock) {
this.onopen = this.sock.onmessage = this.sock.onerror = this.sock.onclose = null;
this.onerror();
}
try {
this.sock = new WebSocket(this.scheme + '://' + conf.host + ':' + conf.port + '/jsonrpc');
this.sock.onopen = this.onopen;
this.sock.onclose = this.sock.onerror = this.onerror;
this.sock.onmessage = this.onmessage;
}
catch (ex) {
// ignoring IE securty exception on local ip addresses
}
},
};
}]);
| 12,066
|
https://github.com/huyhoang1995/laravel-vue/blob/master/resources/assets/js/components/clinic/PatientDetailComponent.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
laravel-vue
|
huyhoang1995
|
Vue
|
Code
| 485
| 2,436
|
<template>
<div>
<div class="col-md-12">
<div class="panel panel-bordered panel-success ">
<div class="panel-heading">
<h3 class="panel-title">Thông tin người dùng</h3>
</div>
<div class="panel-body">
<div class="col-md-2">
<img v-bind:src="'./images/avatar.png'" alt="">
</div>
<div class="col-md-10">
<h3>
Nguyễn Văn A
</h3>
<table class="table table-hover" style="font-size: 18px;">
<thead>
<tr>
<td>Giới tính</td>
<td>Tuổi</td>
<td>Gói dịch vụ</td>
<td>Thời gian</td>
</tr>
</thead>
<tbody>
<tr style="font-weight: bold">
<td>Nam</td>
<td>54 Tuổi</td>
<td>Huyết áp cao</td>
<td>3 tháng</td>
</tr>
</tbody>
</table>
<div style="font-size: 20px;margin-left: -10px">
<i class="fa fa-home col-md-4" aria-hidden="true">Thanh Trình - Hà Nội</i>
<i class="fa fa-envelope-o col-md-4" aria-hidden="true">hoangnh@newtel.com</i>
<i class="fa fa-id-card-o col-md-4" aria-hidden="true">0382924061</i>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="panel panel-bordered panel-success">
<div class="panel-heading" style="position: relative;">
<h3 class="panel-title">Lịch sử</h3>
<button class="btn btn-info" style="position: absolute; right: 20px;top: 20%;">Chọn ngày</button>
</div>
<div class="panel-body">
<div class="table-responsive" style="font-size: 25px;overflow: auto:;height: 200px" >
<table class="table table-hover">
<tbody>
<tr>
<td @click="showModal()"><i class="fa fa-home" aria-hidden="true"></i> <button ></button> 21/10/2018 HomeWork1</td>
</tr>
<tr>
<td><i class="fa fa-home" aria-hidden="true"></i> 21/10/2018 HomeWork2</td>
</tr>
<tr>
<td><i class="fa fa-home" aria-hidden="true"></i> 21/10/2018 HomeWork3</td>
</tr>
<tr>
<td><i class="fa fa-home" aria-hidden="true"></i> 21/10/2018 HomeWork4</td>
</tr>
<tr>
<td><i class="fa fa-home" aria-hidden="true"></i> 21/10/2018 HomeWork5</td>
</tr>
<tr>
<td><i class="fa fa-home" aria-hidden="true"></i> 21/10/2018 HomeWork6</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-bordered panel-warning">
<div class="panel-heading" style="position: relative;">
<h3 class="panel-title">Huyết áp</h3>
<div style="position: absolute; right: 20px;top: 20%;">
<button class="btn btn-info" >Hôm nay</button>
<button class="btn btn-info" >Tuần</button>
<button class="btn btn-info" >Tháng</button>
<button class="btn btn-info" >Năm</button>
</div>
</div>
<div class="panel-body">
<router-link to="/patientChartDetail">
<a class="btn btn-info">
Detail
</a>
</router-link>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-bordered panel-warning">
<div class="panel-heading" style="position: relative;">
<h3 class="panel-title">Nhịp tim</h3>
<div style="position: absolute; right: 20px;top: 20%;">
<button class="btn btn-info" >Hôm nay</button>
<button class="btn btn-info" >Tuần</button>
<button class="btn btn-info" >Tháng</button>
<button class="btn btn-info" >Năm</button>
</div>
</div>
<div class="panel-body">
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-bordered panel-warning">
<div class="panel-heading" style="position: relative;">
<h3 class="panel-title">Số bước đi</h3>
<div style="position: absolute; right: 20px;top: 20%;">
<button class="btn btn-info" >Hôm nay</button>
<button class="btn btn-info" >Tuần</button>
<button class="btn btn-info" >Tháng</button>
<button class="btn btn-info" >Năm</button>
</div>
</div>
<div class="panel-body">
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-bordered panel-warning">
<div class="panel-heading" style="position: relative;">
<h3 class="panel-title">Đường huyết</h3>
<div style="position: absolute; right: 20px;top: 20%;">
<button class="btn btn-info" >Hôm nay</button>
<button class="btn btn-info" >Tuần</button>
<button class="btn btn-info" >Tháng</button>
<button class="btn btn-info" >Năm</button>
</div>
</div>
<div class="panel-body">
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-bordered panel-warning">
<div class="panel-heading" style="position: relative;">
<h3 class="panel-title">Đông máu</h3>
<div style="position: absolute; right: 20px;top: 20%;">
<button class="btn btn-info" >Hôm nay</button>
<button class="btn btn-info" >Tuần</button>
<button class="btn btn-info" >Tháng</button>
<button class="btn btn-info" >Năm</button>
</div>
</div>
<div class="panel-body">
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-bordered panel-warning">
<div class="panel-heading" style="position: relative;">
<h3 class="panel-title">Lượng nước tiểu</h3>
<div style="position: absolute; right: 20px;top: 20%;">
<button class="btn btn-info" >Hôm nay</button>
<button class="btn btn-info" >Tuần</button>
<button class="btn btn-info" >Tháng</button>
<button class="btn btn-info" >Năm</button>
</div>
</div>
<div class="panel-body">
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data: function() {
return{
historyModal:{
id: "historyModal"
}
}
},
methods:{
showModal: function() {
$("#" + this.historyModal.id).modal("show");
}
},
components: {
historyModal: require("@component/modal/clinic/PatientDetailHistoryComponent.vue")
}
}
</script>
| 28,975
|
https://github.com/fayyaztech/Helios/blob/master/helios/ext/libcms/scanners/cms_scanner.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
Helios
|
fayyaztech
|
Python
|
Code
| 299
| 1,161
|
import time
import requests
import os
import logging
import sys
class Scanner:
# set frequency for update call
update_frequency = 0
name = ""
aggressive = False
last_update = 0
cache_dir = os.path.join(os.path.dirname(__file__), 'cache')
logger = None
updates = {}
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}
cookies = {}
def get_version(self, url):
return None
def set_logger(self, log_level=logging.DEBUG):
self.logger = logging.getLogger("CMS-%s" % self.name)
self.logger.setLevel(log_level)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(log_level)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
if not self.logger.handlers:
self.logger.addHandler(ch)
def update(self):
pass
def run(self, url):
return {}
def get_update_cache(self):
if os.path.exists(self.cache_file('updates.txt')):
self.logger.debug("Reading update cache")
with open(self.cache_file('updates.txt'), 'r') as f:
for x in f.read().strip().split('\n'):
if len(x):
scanner, last_update = x.split(':')
self.updates[scanner] = int(last_update)
else:
self.logger.warning("There appears to be an error in the updates cache file")
self.updates[self.name] = 0
if self.name in self.updates:
self.last_update = self.updates[self.name]
else:
self.updates[self.name] = time.time()
else:
self.logger.debug("No updates cache file found, creating empty one")
self.updates[self.name] = time.time()
def set_update_cache(self):
self.logger.debug("Updating updates cache file")
with open(self.cache_file('updates.txt'), 'w') as f:
for x in self.updates:
f.write("%s:%d\n" % (x, self.updates[x]))
def cache_file(self, r):
return os.path.join(self.cache_dir, r)
def setup(self):
if not os.path.exists(self.cache_dir):
self.logger.info("Creating cache directory")
os.mkdir(self.cache_dir)
self.get_update_cache()
if self.last_update + self.update_frequency < time.time():
self.last_update = time.time()
self.updates[self.name] = time.time()
self.update()
self.set_update_cache()
else:
self.logger.debug("Database is up to date, skipping..")
def match_versions(self, version, fixed_in):
if version == fixed_in:
return False
parts_version = version.split('.')
parts_fixed_in = fixed_in.split('.')
if len(parts_version) <= len(parts_fixed_in):
for x in range(len(parts_version)):
if int(parts_version[x]) < int(parts_fixed_in[x]):
return True
if int(parts_version[x]) > int(parts_fixed_in[x]):
return False
return False
else:
for x in range(len(parts_fixed_in)):
if int(parts_version[x]) < int(parts_fixed_in[x]):
return True
if int(parts_version[x]) > int(parts_fixed_in[x]):
return False
return False
def get(self, url, data=None):
if not data:
result = requests.get(url, allow_redirects=False, headers=self.headers, cookies=self.cookies)
return result
else:
result = requests.post(url, data=data, allow_redirects=False, headers=self.headers, cookies=self.cookies)
return result
| 48,492
|
https://github.com/deepaksingh112018/laravel/blob/master/raj/routes/web.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
laravel
|
deepaksingh112018
|
PHP
|
Code
| 79
| 226
|
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/abc', function () {
// return view('welcome');
// });
// Route::get('/raj', function() {
// return view('rajform');
// });
Route::get('/raj', 'User@view');
Route::get('backend', 'User@index');
Route::get('delete', 'User@delete');
Route::get('edit', 'User@edit');
Route::get('update', 'User@update');
Route::get('/file', 'FileController@index');
Route::post('saveForm', 'FileController@create')->name('saveForm');
| 7,454
|
https://github.com/msnijder30/JKik/blob/master/src/main/java/com/github/msnijder30/jkik/message/FriendPickerMessage.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
JKik
|
msnijder30
|
Java
|
Code
| 44
| 161
|
package com.github.msnijder30.jkik.message;
import java.util.ArrayList;
import com.github.msnijder30.jkik.Chat;
import lombok.Getter;
public class FriendPickerMessage extends Message {
@Getter
private ArrayList<String> picked;
public FriendPickerMessage(Chat chat, long timestamp, String mention, boolean readReceiptRequested, String id, ArrayList<String> picked) {
super(chat, timestamp, mention, readReceiptRequested, MessageType.FRIEND_PICKER, id, null);
this.picked = picked;
}
}
| 48,573
|
https://github.com/3prm3/ATBYW/blob/master/src/main/java/net/azagwen/atbyw/blocks/stairs/DirtStairsBlock.java
|
Github Open Source
|
Open Source
|
MIT
| null |
ATBYW
|
3prm3
|
Java
|
Code
| 148
| 638
|
package net.azagwen.atbyw.blocks.stairs;
import net.azagwen.atbyw.blocks.AtbywBlocks;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.tag.FluidTags;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.WorldView;
import net.minecraft.world.chunk.light.ChunkLightProvider;
import java.util.Random;
public class DirtStairsBlock extends StairsBlockSubClass {
public DirtStairsBlock(Settings settings) {
super(AtbywBlocks.TICKING_DIRT, settings);
}
private static boolean canSurvive(BlockState state, WorldView worldView, BlockPos pos) {
BlockPos blockPos = pos.up();
BlockState blockState = worldView.getBlockState(blockPos);
return !blockState.isSideSolidFullSquare(worldView, blockPos, Direction.UP);
}
private static boolean canSpread(BlockState state, WorldView worldView, BlockPos pos) {
BlockPos blockPos = pos.up();
return canSurvive(state, worldView, pos) && !worldView.getFluidState(blockPos).isIn(FluidTags.WATER);
}
@Override
public void randomTick(BlockState state, ServerWorld world, BlockPos pos, Random random) {
if (world.getLightLevel(pos.up()) >= 9) {
for(int i = 0; i < 4; ++i) {
BlockPos blockPos = pos.add(random.nextInt(3) - 1, random.nextInt(3) - 1, random.nextInt(3) - 1);
BlockState newState = world.getBlockState(pos);
if (world.getBlockState(blockPos).isOf(Blocks.GRASS_BLOCK) && canSpread(state, world, pos)) {
world.setBlockState(pos, copyStates(AtbywBlocks.GRASS_BLOCK_STAIRS.getDefaultState(), newState));
}
else if (world.getBlockState(blockPos).isOf(Blocks.MYCELIUM) && canSpread(state, world, pos)) {
world.setBlockState(pos, copyStates(AtbywBlocks.MYCELIUM_STAIRS.getDefaultState(), newState));
}
}
}
}
}
| 20,836
|
https://github.com/cefoler/configuration/blob/master/core/src/main/java/com/cefoler/configuration/core/exception/unchecked/unchecked/impl/reflection/impl/member/impl/executable/UncheckedExecutableException.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
configuration
|
cefoler
|
Java
|
Code
| 38
| 196
|
package com.cefoler.configuration.core.exception.unchecked.unchecked.impl.reflection.impl.member.impl.executable;
import com.cefoler.configuration.core.exception.checked.reflection.impl.member.impl.executable.ExecutableException;
import com.cefoler.configuration.core.exception.unchecked.unchecked.impl.reflection.impl.member.UncheckedMemberException;
public class UncheckedExecutableException extends UncheckedMemberException {
private static final long serialVersionUID = 778187107196259634L;
public UncheckedExecutableException(final ExecutableException cause) {
super(cause);
}
public UncheckedExecutableException(final String error, final ExecutableException cause) {
super(error, cause);
}
}
| 31,539
|
https://github.com/deshmukhmayur/one-platform/blob/master/packages/developer-console-spa/src/components/lighthouse/CreateProjectForm.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
one-platform
|
deshmukhmayur
|
TypeScript
|
Code
| 295
| 898
|
import { Button, Flex, FlexItem, Form, FormGroup, TextInput } from '@patternfly/react-core';
import { Dispatch, SetStateAction, useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { createLightHouseProjects } from '../../services/lighthouse';
type CreateProjectFormValues = {
projectName: string;
repoUrl: string;
baseBranch: string;
};
type CreateProjectProps = {
setActiveTabKey: Dispatch<SetStateAction<number>>,
setSelectedProject: Dispatch<SetStateAction<Lighthouse.Project>>,
setShowConfirmation: Dispatch<SetStateAction<boolean>>;
};
const CreateProjectForm = ( props: CreateProjectProps ) => {
const [ isPrimaryLoading, setIsPrimaryLoading ] = useState<boolean>( false );
const { handleSubmit, control, formState: { errors } } = useForm<CreateProjectFormValues>( {
mode: 'onBlur'
} );
const createProject = ( data: CreateProjectFormValues ) => {
setIsPrimaryLoading( true );
let project = {
name: data.projectName,
baseBranch: data.baseBranch,
externalUrl: data.repoUrl
};
createLightHouseProjects( project ).then( res => {
setIsPrimaryLoading( false );
props.setSelectedProject( res );
props.setShowConfirmation( true );
} );
};
return (
<Form onSubmit={ handleSubmit( createProject ) } className="lighthouse-projectForm--marginTop" >
<FormGroup
isRequired
fieldId=""
helperTextInvalid="Project Name is mandatory"
helperTextInvalidIcon={ <ion-icon name="alert-circle-outline"></ion-icon> }
validated={ errors.projectName ? "error" : "default" }
label="Project Name"
>
<Controller
render={ ( { field } ) => (
<TextInput
{ ...field }
type="text"
id="project-name"
aria-describedby="projectName"
validated={ errors.projectName ? "error" : "default" }
/>
) }
name="projectName"
control={ control }
rules={ { required: true } }
/>
</FormGroup>
<FormGroup fieldId="" label="Repository URL">
<Controller
render={ ( { field } ) => (
<TextInput
{ ...field }
type="text"
id="project-name"
aria-describedby="projectName"
/>
) }
name="repoUrl"
control={ control }
/>
</FormGroup>
<FormGroup fieldId="" label="Base Branch">
<Controller
render={ ( { field } ) => (
<TextInput
{ ...field }
type="text"
id="project-name"
aria-describedby="projectName"
/>
) }
name="baseBranch"
control={ control }
/>
</FormGroup>
<FormGroup fieldId="">
<Flex>
<FlexItem align={ { default: 'alignRight' } }>
<Button
type="submit"
disabled={ isPrimaryLoading }
spinnerAriaValueText={ isPrimaryLoading ? 'Loading' : undefined }
isLoading={ isPrimaryLoading }
variant="primary"
>
Create Project
</Button>
</FlexItem>
</Flex>
</FormGroup>
</Form>
);
};
export default CreateProjectForm;
| 25,665
|
https://github.com/airicyu/rameter/blob/master/samples/sample9-custom-sampler/app.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
rameter
|
airicyu
|
JavaScript
|
Code
| 169
| 426
|
import { Rameter, HttpRequestSampler, CustomSampler, sleep, UserModelConfig } from "rameter";
const rameter = new Rameter();
/**
* up-lifting
*/
await rameter.runStandalone();
/**
* define user groups
*/
rameter.defineUserGroup("members");
/**
* define user test scenario
*/
rameter.defineUserScenario("run custom operation scenario", async ({ globalContext, nodeContext, userContext, userId }) => {
try {
// use CustomSampler to measure dummy operation
const { data: result } = await CustomSampler.run(async () => {
await sleep(500);
const randomResult = Math.round(Math.random() * 100);
return {
data: { foo: randomResult },
sampleRecord: {
label: "Mocking some operation",
},
};
});
// randomly log the result
if (result.foo > 95) {
console.log(new Date().toISOString(), result.foo);
}
} catch (e) {
console.error(e);
} finally {
await sleep(100); // think time
}
});
await rameter.readyTest(); // Get ready to test
/**
* Start the load test. Run until test finished.
*/
await rameter.runUntilFinished([
{
userModel: UserModelConfig.stepUserForTime({
maxUsers: 20,
steps: 10,
rampUpTime: 10,
holdTime: 20,
}),
userGroups: ["members"],
scenarios: ["run custom operation scenario"],
},
]);
/**
* shutdown
*/
await rameter.down();
process.exit();
| 35,476
|
https://github.com/squinix/Hostinec-Stolet-/blob/master/resources/views/home.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
Hostinec-Stolet-
|
squinix
|
PHP
|
Code
| 160
| 684
|
@extends('layouts.app')
@section('content')
<div class="container" style="min-height: 100vh;">
<div>
<h1 class="text-4xl font-thin uppercase text-center py-16 pb-2">
Denní menu
</h1>
</div>
<div class="grid grid-cols-2 gap-4 py-16 m-5">
<div class="m-5">
<h1 class="text-sm font-normal uppercase text-center pb-2">
Aktuální nahrané menu
</h1>
<p class="text-center text-base font-thin text-gray-600">
{{ __('messages.' . now()->format('l')) }} {{ now()->format('d.m.') }}
</p>
<img src="/storage/uploads/denni_menu.jpg?{{ now() }}" alt="Denní menu {{ now()->format('d.m.Y') }}" class="m-auto" width="100%">
</div>
<div class="m-5">
<h1 class="text-sm font-normal uppercase text-left pb-8">
Pomocí formuláře níže nahrajte nové denní menu
</h1>
<form action="{{ route('home.store') }}" method="POST" enctype="multipart/form-data" class="text-left p-6">
@csrf
<input type="file" name="denni_menu" id="denni_menu">
{{ $errors->first('image') }}
<div class="d-flex justify-content-end">
<button type="submit" class="bg-brown hover:shadow-xl text-white font-thin py-2 sm:py-4 px-4 sm:px-6 text-xs sm:text-base mt-8 mb-16 uppercase">
Nahrát nové menu
</button>
</div>
</form>
</div>
</div>
<div class="text-right">
<button class="bg-brown hover:shadow-xl text-white font-thin py-2 sm:py-4 px-4 sm:px-6 text-xs sm:text-base mt-8 mb-16 uppercase">
<a class="dropdown-item" href="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Odhlásit se
</a>
</button>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
@csrf
</form>
</div>
</div>
@endsection
| 12,548
|
https://github.com/khoind6725/woodshop/blob/master/resources/views/components/social-info.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
woodshop
|
khoind6725
|
PHP
|
Code
| 40
| 204
|
<div class="row m0 social-info">
<ul class="social-icon">
<li><a href="#"><i class="fa fa-facebook"></i></a></li>
<li><a href="#"><i class="fa fa-twitter"></i></a></li>
<li><a href="#"><i class="fa fa-google-plus"></i></a></li>
<li><a href="#"><i class="fa fa-linkedin"></i></a></li>
<li class="tel"><a href="tel:+1234567890"><i class="fa fa-phone"></i> + (123) 456 7890 </a></li>
<li class="email"><a href="#"><i class="fa fa-envelope-o"></i> info@woodworkshop</a></li>
</ul>
</div>
| 37,306
|
https://github.com/CragonGame/CasinosClient/blob/master/Assets/Arts/Particle/Textures/Textures/Materials/longzhu.mat.meta
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
CasinosClient
|
CragonGame
|
Unity3D Asset
|
Code
| 6
| 39
|
fileFormatVersion: 2
guid: 22be2a3d58c34a643ba49770dc505edb
NativeFormatImporter:
userData:
| 3,637
|
https://github.com/lotusronin/KronosEngine/blob/master/Shader.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
KronosEngine
|
lotusronin
|
C++
|
Code
| 216
| 818
|
#include "Shader.h"
#include <string.h>
#include <iostream>
#include <fstream>
#include <GL/glew.h>
#include <GL/gl.h>
Shader::Shader(const std::string& vert, const std::string& frag)
{
vs ="";
fs = "";
//Load vertex shader
vs = load(vert);
//Load fragment shader
fs = load(frag);
vert_src = vs.c_str();
frag_src = fs.c_str();
}
Shader::~Shader()
{}
void Shader::disable()
{
glUseProgram(0);
}
void Shader::enable()
{
glUseProgram(shaderProgram);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
}
void Shader::compile()
{
vShader = glCreateShader(GL_VERTEX_SHADER);
fShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vShader, 1, &vert_src, 0);
glShaderSource(fShader, 1, &frag_src, 0);
glCompileShader(vShader);
glCompileShader(fShader);
//Error Check//
GLint error = 0;
glGetShaderiv(vShader, GL_COMPILE_STATUS, &error);
if(error == GL_FALSE)
{
GLchar e[1024];
glGetShaderInfoLog(vShader, sizeof(e), NULL, e);
std::cout << "Error compiling vertex shader!!!!\n";
std::cout << e;
}
else
{
std::cout << "vertex shader compiled successfully!\n";
}
error = 0;
glGetShaderiv(fShader, GL_COMPILE_STATUS, &error);
if(error == GL_FALSE)
{
GLchar e[1024];
glGetShaderInfoLog(fShader, sizeof(e), NULL, e);
std::cout << "Error compiling fragment shader!!!!\n";
std::cout << e;
}
else
{
std::cout << "fragment shader compiled successfully!\n";
}
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vShader);
glAttachShader(shaderProgram, fShader);
glBindAttribLocation(shaderProgram, 0, "pos");
glBindAttribLocation(shaderProgram, 1, "texCoord");
glLinkProgram(shaderProgram);
}
std::string Shader::load(std::string filename)
{
filename = "./shaders/"+filename;
std::string s, temp;
std::ifstream vsf (filename);
if(vsf.is_open()){
while(getline(vsf, temp))
{
s = s + temp + '\n';
}
vsf.close();
std::cout << "Shader " << filename << " loaded...\n";
}
else{
std::cout << "error opening shader file: " << filename << "\n";
}
return s;
}
| 47,310
|
https://github.com/DevJohnC/DataKit/blob/master/DataKit.Modelling/TypeModels/PropertyField.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
DataKit
|
DevJohnC
|
C#
|
Code
| 198
| 648
|
using System;
using System.Reflection;
namespace DataKit.Modelling.TypeModels
{
public abstract class PropertyField : IModelField<TypeModel, PropertyField>
{
public DataType FieldType => GetDataType();
public abstract string FieldName { get; }
public abstract bool CanWrite { get; }
public abstract bool CanRead { get; }
public PropertyInfo Property { get; protected set; }
public virtual TypeModel FieldModel => TypeModel.GetModelOf(FieldType.Type);
IDataModel IModelField.FieldModel => FieldModel;
private void InitalizeFromPropertyInfo(PropertyInfo propertyInfo)
{
Property = propertyInfo;
InitalizeFromPropertyInfoOverride(propertyInfo);
}
protected abstract DataType GetDataType();
protected abstract void InitalizeFromPropertyInfoOverride(PropertyInfo propertyInfo);
/// <summary>
/// Create a PropertyInfoField from a PropertyInfo instance.
/// </summary>
/// <param name="propertyInfo"></param>
/// <returns></returns>
public static PropertyField CreateFromPropertyInfo(PropertyInfo propertyInfo)
{
var ret = Activator.CreateInstance(typeof(PropertyField<>).MakeGenericType(
propertyInfo.PropertyType
)) as PropertyField;
ret.InitalizeFromPropertyInfo(propertyInfo);
return ret;
}
public abstract IModelNode Accept(IModelVisitor visitor);
}
public class PropertyField<T> : PropertyField, IModelFieldOf<T>
{
private string _fieldName;
public override string FieldName => _fieldName;
private bool _canWrite;
public override bool CanWrite => _canWrite;
private bool _canRead;
public override bool CanRead => _canRead;
private DataType<T> _fieldType;
public new DataType<T> FieldType => _fieldType;
protected override void InitalizeFromPropertyInfoOverride(PropertyInfo propertyInfo)
{
_fieldName = propertyInfo.Name;
_canRead = propertyInfo.CanRead;
_canWrite = propertyInfo.CanWrite;
_fieldType = DataType.GetTypeOf<T>();
}
protected override DataType GetDataType() => _fieldType;
public override IModelNode Accept(IModelVisitor visitor)
{
return visitor.VisitField(this);
}
}
}
| 21,613
|
https://github.com/cyylog/Vue_status/blob/master/src/views/cfg/create.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
Vue_status
|
cyylog
|
Vue
|
Code
| 145
| 772
|
<template>
<div class="app-container">
<el-form ref="form" :model="config" label-width="120px">
<el-form-item label="分组">
<el-select allow-create v-model="config.group" filterable placeholder="输入分组">
<el-option
v-for="item in groups"
:key="item"
:label="item"
:value="item">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="数据ID">
<el-input style="width: 350px" v-model="config.dataId" />
</el-form-item>
<el-form-item label="版本">
<el-select v-model="config.version" placeholder="请选择版本">
<el-option v-for="v in 10" :label="'v'+v" :value="'v'+v" />
</el-select>
</el-form-item>
<el-form-item label="描述">
<el-input style="width: 350px" type="textarea" v-model="configValue.desc" />
</el-form-item>
<el-form-item label="配置内容">
<el-input rows="5" type="textarea" v-model="configValue.content" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">保存</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { getGroups,saveConfig } from '@/api/cfg'
export default {
data() {
return {
config:{
group:'',
dataId:'',
version:''
},
configValue:{
desc:'',
md5:'',
context:''
},
groups:[]
}
},
created(){
getGroups().then(rsp=>{
this.groups=rsp.data.result
})
},
methods: {
onSubmit() {
let obj=Object.assign({},this.config,this.configValue)
let formData=new FormData();
for(var prop in obj){
formData.append(prop,obj[prop])
}
saveConfig(formData).then(rsp=>{
if(rsp.data.message && rsp.data.message==="Ok"){
this.$router.push({name:'cfgList'})
}
}).catch(err=>{
this.$message({ type: 'error', message: '保存失败,数据不完整!'});
})
},
onCancel() {
}
}
}
</script>
<style scoped>
.line{
text-align: center;
}
</style>
| 10,388
|
https://github.com/nnaumenko/metafsimple/blob/master/test/integration_temp_pres_historical.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
metafsimple
|
nnaumenko
|
C++
|
Code
| 656
| 2,849
|
/*
* Copyright (C) 2020 Nick Naumenko (https://gitlab.com/nnaumenko,
* https:://github.com/nnaumenko)
* All rights reserved.
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "comparisons.hpp"
#include "gtest/gtest.h"
#include "metafsimple.hpp"
using namespace metafsimple;
////////////////////////////////////////////////////////////////////////////////
// Tests 24-hour and 6-hour min/max temperature groups and pressure tendency
// group specified in remarks
////////////////////////////////////////////////////////////////////////////////
TEST(IntegrationHistoricalPressure, pressureTendencyTrend) {
Simple result;
Historical historical;
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 50132=");
historical = Historical();
historical.pressureChange3h = Pressure {132, Pressure::Unit::TENTHS_HPA};
historical.pressureTendency =
Historical::PressureTendency::INCREASING_THEN_DECREASING;
historical.pressureTrend =
Historical::PressureTrend::HIGHER_OR_SAME;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 51132=");
historical = Historical();
historical.pressureChange3h = Pressure {132, Pressure::Unit::TENTHS_HPA};
historical.pressureTendency =
Historical::PressureTendency::INCREASING_MORE_SLOWLY;
historical.pressureTrend =
Historical::PressureTrend::HIGHER;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 52132=");
historical = Historical();
historical.pressureChange3h = Pressure {132, Pressure::Unit::TENTHS_HPA};
historical.pressureTendency =
Historical::PressureTendency::INCREASING;
historical.pressureTrend =
Historical::PressureTrend::HIGHER;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 53132=");
historical = Historical();
historical.pressureChange3h = Pressure {132, Pressure::Unit::TENTHS_HPA};
historical.pressureTendency =
Historical::PressureTendency::INCREASING_MORE_RAPIDLY;
historical.pressureTrend =
Historical::PressureTrend::HIGHER;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 54132=");
historical = Historical();
historical.pressureChange3h = Pressure {132, Pressure::Unit::TENTHS_HPA};
historical.pressureTendency =
Historical::PressureTendency::STEADY;
historical.pressureTrend =
Historical::PressureTrend::SAME;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 55132=");
historical = Historical();
historical.pressureChange3h = Pressure {132, Pressure::Unit::TENTHS_HPA};
historical.pressureTendency =
Historical::PressureTendency::DECREASING_THEN_INCREASING;
historical.pressureTrend =
Historical::PressureTrend::LOWER_OR_SAME;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 56132=");
historical = Historical();
historical.pressureChange3h = Pressure {132, Pressure::Unit::TENTHS_HPA};
historical.pressureTendency =
Historical::PressureTendency::DECREASING_MORE_SLOWLY;
historical.pressureTrend =
Historical::PressureTrend::LOWER;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 57132=");
historical = Historical();
historical.pressureChange3h = Pressure {132, Pressure::Unit::TENTHS_HPA};
historical.pressureTendency =
Historical::PressureTendency::DECREASING;
historical.pressureTrend =
Historical::PressureTrend::LOWER;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 58132=");
historical = Historical();
historical.pressureChange3h = Pressure {132, Pressure::Unit::TENTHS_HPA};
historical.pressureTendency =
Historical::PressureTendency::DECREASING_MORE_RAPIDLY;
historical.pressureTrend =
Historical::PressureTrend::LOWER;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 59132=");
historical = Historical();
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 5/132=");
historical = Historical();
historical.pressureChange3h = Pressure {132, Pressure::Unit::TENTHS_HPA};
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 53///=");
historical = Historical();
historical.pressureTendency =
Historical::PressureTendency::INCREASING_MORE_RAPIDLY;
historical.pressureTrend =
Historical::PressureTrend::HIGHER;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK 5////=");
historical = Historical();
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK PRESRR=");
historical = Historical();
historical.pressureTendency =
Historical::PressureTendency::RISING_RAPIDLY;
historical.pressureTrend =
Historical::PressureTrend::UNKNOWN;
EXPECT_EQ(result.historical, historical);
result = metafsimple::simplify("METAR ZZZZ 070800Z /////KT RMK PRESFR=");
historical = Historical();
historical.pressureTendency =
Historical::PressureTendency::FALLING_RAPIDLY;
historical.pressureTrend =
Historical::PressureTrend::UNKNOWN;
EXPECT_EQ(result.historical, historical);
}
TEST(IntegrationHistoricalTemperature, minMax24hour) {
static const auto rawReport =
"METAR ZZZZ 071135Z /////KT RMK 401001015=";
// fake report created for this test
const auto result = metafsimple::simplify(rawReport);
Report refReport;
refReport.type = Report::Type::METAR;
refReport.reportTime = Time{7, 11, 35};
refReport.error = Report::Error::NO_ERROR;
EXPECT_EQ(result.report, refReport);
Station refStation;
refStation.icaoCode = "ZZZZ";
EXPECT_EQ(result.station, refStation);
Historical refHistorical;
refHistorical.temperatureMax24h =
Temperature {100, Temperature::Unit::TENTH_C};
refHistorical.temperatureMin24h =
Temperature {-15, Temperature::Unit::TENTH_C};
EXPECT_EQ(result.historical, refHistorical);
EXPECT_EQ(result.aerodrome, Aerodrome());
EXPECT_EQ(result.current, Current());
EXPECT_EQ(result.forecast, Forecast());
}
TEST(IntegrationHistoricalTemperature, minMax6hour) {
static const auto rawReport =
"METAR ZZZZ 071135Z /////KT RMK 10142 20012=";
// fake report created for this test
const auto result = metafsimple::simplify(rawReport);
Report refReport;
refReport.type = Report::Type::METAR;
refReport.reportTime = Time{7, 11, 35};
refReport.error = Report::Error::NO_ERROR;
EXPECT_EQ(result.report, refReport);
Station refStation;
refStation.icaoCode = "ZZZZ";
EXPECT_EQ(result.station, refStation);
Historical refHistorical;
refHistorical.temperatureMin6h =
Temperature {12, Temperature::Unit::TENTH_C};
refHistorical.temperatureMax6h =
Temperature {142, Temperature::Unit::TENTH_C};
EXPECT_EQ(result.historical, refHistorical);
EXPECT_EQ(result.aerodrome, Aerodrome());
EXPECT_EQ(result.current, Current());
EXPECT_EQ(result.forecast, Forecast());
}
TEST(IntegrationHistoricalTemperature, min6hour) {
static const auto rawReport =
"METAR ZZZZ 071135Z /////KT RMK 20012=";
// fake report created for this test
const auto result = metafsimple::simplify(rawReport);
Report refReport;
refReport.type = Report::Type::METAR;
refReport.reportTime = Time{7, 11, 35};
refReport.error = Report::Error::NO_ERROR;
EXPECT_EQ(result.report, refReport);
Station refStation;
refStation.icaoCode = "ZZZZ";
EXPECT_EQ(result.station, refStation);
Historical refHistorical;
refHistorical.temperatureMin6h =
Temperature {12, Temperature::Unit::TENTH_C};
EXPECT_EQ(result.historical, refHistorical);
EXPECT_EQ(result.aerodrome, Aerodrome());
EXPECT_EQ(result.current, Current());
EXPECT_EQ(result.forecast, Forecast());
}
TEST(IntegrationHistoricalTemperature, max6hour) {
static const auto rawReport =
"METAR ZZZZ 071135Z /////KT RMK 10142=";
// fake report created for this test
const auto result = metafsimple::simplify(rawReport);
Report refReport;
refReport.type = Report::Type::METAR;
refReport.reportTime = Time{7, 11, 35};
refReport.error = Report::Error::NO_ERROR;
EXPECT_EQ(result.report, refReport);
Station refStation;
refStation.icaoCode = "ZZZZ";
EXPECT_EQ(result.station, refStation);
Historical refHistorical;
refHistorical.temperatureMax6h =
Temperature {142, Temperature::Unit::TENTH_C};
EXPECT_EQ(result.historical, refHistorical);
EXPECT_EQ(result.aerodrome, Aerodrome());
EXPECT_EQ(result.current, Current());
EXPECT_EQ(result.forecast, Forecast());
}
| 15,970
|
https://github.com/team-moebius/hashmain-data-pipeline/blob/master/api/src/test/groovy/com/moebius/api/grocery/TradeHistoryGrocery.groovy
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
hashmain-data-pipeline
|
team-moebius
|
Groovy
|
Code
| 91
| 348
|
package com.moebius.api.grocery
import com.moebius.api.entity.TradeHistory
import java.time.LocalDateTime
class TradeHistoryGrocery {
static def basicTradeHistory(Map map = defaultMap()) {
return new TradeHistory(
map.id as String,
map.exchange as String,
map.symbol as String,
map.tradeType as String,
map.change as String,
map.price as Double,
map.volume as Double,
map.prevClosingPrice as Double,
map.changePrice as Double,
map.createdAt as LocalDateTime
)
}
static def defaultMap() {
return [
"id" : "06a4d841-a18e-4a22-b033-dc78a9eada83",
"exchange" : "UPBIT",
"symbol" : "KRW-EOS",
"tradeType" : "BID",
"change" : "RISE",
"price" : 3135.0,
"volume" : 16.7106,
"prevClosingPrice": 3085.0,
"changePrice" : 50.0,
"transactionPrice": 52387.731,
"createdAt" : "2020-07-25T15:00:36.040"
]
}
}
| 19,996
|
https://github.com/some-mthfka/Viy/blob/master/neosfml.vim
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
Viy
|
some-mthfka
|
Vim Script
|
Code
| 61
| 288
|
"Used for Viy GUI
"Goes to neovim's autoload directory
function! neosfml#PicCopyAndInc(reps)
let c = 1
while c <= a:reps
execute "normal! yyp$bb\<C-a>"
let c += 1
endwhile
endfunction
function! neosfml#PicSize()
return split(getline('.'), '|')[-3] - 1
endfunction
function! neosfml#PicExpand()
call neosfml#PicCopyAndInc(neosfml#PicSize())
endfunction
function! neosfml#PicExpandAll()
"don't forget to restore register @a
execute "g/<|\\(\\w\\| \\)\\+\\.\\w\\+|\\d*|0|>/call neosfml#PicExpand()"
endfunction
function! neosfml#PicContractAll()
silent execute "g/<|\\(\\w\\| \\)\\+\\.\\w\\+|\\d\\{1,2}|\\d*|>/d_"
endfunction
| 48,170
|
https://github.com/Hendis/brew/blob/master/Library/Homebrew/test/rubocops/options_cop_spec.rb
|
Github Open Source
|
Open Source
|
CC-BY-4.0, BSD-2-Clause
| 2,017
|
brew
|
Hendis
|
Ruby
|
Code
| 294
| 1,082
|
require "rubocop"
require "rubocop/rspec/support"
require_relative "../../extend/string"
require_relative "../../rubocops/options_cop"
describe RuboCop::Cop::FormulaAudit::Options do
subject(:cop) { described_class.new }
context "When auditing options" do
it "32-bit" do
source = <<-EOS.undent
class Foo < Formula
url 'http://example.com/foo-1.0.tgz'
option "32-bit", "with 32-bit"
end
EOS
expected_offenses = [{ message: described_class::DEPRECATION_MSG,
severity: :convention,
line: 3,
column: 10,
source: source }]
inspect_source(cop, source)
expected_offenses.zip(cop.offenses).each do |expected, actual|
expect_offense(expected, actual)
end
end
end
end
describe RuboCop::Cop::FormulaAuditStrict::Options do
subject(:cop) { described_class.new }
context "When auditing options strictly" do
it "with universal" do
source = <<-EOS.undent
class Foo < Formula
url 'http://example.com/foo-1.0.tgz'
option :universal
end
EOS
expected_offenses = [{ message: described_class::DEPRECATION_MSG,
severity: :convention,
line: 3,
column: 2,
source: source }]
inspect_source(cop, source)
expected_offenses.zip(cop.offenses).each do |expected, actual|
expect_offense(expected, actual)
end
end
it "with deprecated options" do
source = <<-EOS.undent
class Foo < Formula
url 'http://example.com/foo-1.0.tgz'
option :cxx11
option "examples", "with-examples"
end
EOS
MSG_1 = "Options should begin with with/without."\
" Migrate '--examples' with `deprecated_option`.".freeze
expected_offenses = [{ message: MSG_1,
severity: :convention,
line: 4,
column: 2,
source: source }]
inspect_source(cop, source)
expected_offenses.zip(cop.offenses).each do |expected, actual|
expect_offense(expected, actual)
end
end
it "with misc deprecated options" do
source = <<-EOS.undent
class Foo < Formula
url 'http://example.com/foo-1.0.tgz'
option "without-check"
end
EOS
MSG_2 = "Use '--without-test' instead of '--without-check'."\
" Migrate '--without-check' with `deprecated_option`.".freeze
expected_offenses = [{ message: MSG_2,
severity: :convention,
line: 3,
column: 2,
source: source }]
inspect_source(cop, source)
expected_offenses.zip(cop.offenses).each do |expected, actual|
expect_offense(expected, actual)
end
end
end
end
describe RuboCop::Cop::NewFormulaAudit::Options do
subject(:cop) { described_class.new }
context "When auditing options for a new formula" do
it "with deprecated options" do
source = <<-EOS.undent
class Foo < Formula
url 'http://example.com/foo-1.0.tgz'
deprecated_option "examples" => "with-examples"
end
EOS
expected_offenses = [{ message: described_class::MSG,
severity: :convention,
line: 3,
column: 2,
source: source }]
inspect_source(cop, source)
expected_offenses.zip(cop.offenses).each do |expected, actual|
expect_offense(expected, actual)
end
end
end
end
| 5,758
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.