hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
c99f0a23e9da75cb7d86a3ea0a9c7b74fb001bc7
6,592
tsx
TypeScript
components/pageContent/homeContent/index.tsx
muclaud/profile-page
cc3e7358110c1f9f5661f544058afc02502959c3
[ "0BSD" ]
1
2021-12-17T13:23:21.000Z
2021-12-17T13:23:21.000Z
components/pageContent/homeContent/index.tsx
muclaud/profile-page
cc3e7358110c1f9f5661f544058afc02502959c3
[ "0BSD" ]
null
null
null
components/pageContent/homeContent/index.tsx
muclaud/profile-page
cc3e7358110c1f9f5661f544058afc02502959c3
[ "0BSD" ]
null
null
null
import React from "react" import TextAnimation from "components/animation/textAnimation" import CardWithIcon from "components/pageContent/homeContent/cardWithIcon" const HomeContent = (): JSX.Element => { return ( <> <div className="relative pt-16 flex content-center items-center justify-center min-h-screen-75"> <div className="container relative mx-auto"> <div className="items-center flex flex-wrap"> <div className="w-full lg:w-6/12 px-4 ml-auto mr-auto text-center"> <h1 className="font-semibold text-5xl"> <TextAnimation />{" "} </h1> </div> </div> </div> </div> <section className="relative lg:pt-0 pb-20 bg-green-300 dark:bg-green-600 -mt-24"> <div className="bottom-auto -top-16 left-0 right-0 w-full absolute pointer-events-none overflow-hidden h-16" style={{ transform: "translateZ(0)" }} > <svg className="absolute bottom-0 overflow-hidden" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" version="1.1" viewBox="0 0 2560 100" x="0" y="0" > <polygon className="text-green-300 dark:text-green-600 fill-current" points="2560 0 2560 100 0 100" ></polygon> </svg> </div> <div className="container mx-auto px-4"> <div className="flex flex-wrap"> <div className="lg:pt-12 pt-6 w-full md:w-4/12 px-4 text-center dark:text-green-900"> <CardWithIcon bgColor="bg-white" bgIconColor="bg-red-400" iconName="fa-award" cardTitle="Placeholder" textColor="text-green-500" text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrs standard dummy text." /> </div> <div className="w-full md:w-4/12 px-4 text-center dark:text-green-900"> <CardWithIcon bgColor="bg-white" bgIconColor="bg-blue-400" iconName="fa-retweet" cardTitle="Placeholder" textColor="text-green-500" text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text." /> </div> <div className="pt-6 w-full md:w-4/12 px-4 text-center dark:text-green-900"> <CardWithIcon bgColor="bg-white" bgIconColor="bg-green-400" iconName="fa-fingerprint" cardTitle="Placeholder" textColor="text-green-500" text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text." /> </div> </div> </div> </section> <section className="pb-20 relative block bg-green-300 dark:bg-green-600"> <div className="container mx-auto px-4 "> <div className="flex flex-wrap text-center justify-center"> <div className="w-full lg:w-6/12 px-4"> <h2 className="text-4xl font-semibold text-white"> Some text... </h2> <p className="text-lg leading-relaxed mt-4 mb-4 text-green-800"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&apos;s standard dummy text. </p> </div> </div> <div className="flex flex-wrap mt-12 justify-center"> <div className="w-full lg:w-3/12 px-4 text-center"> <div className="text-green-800 p-3 w-12 h-12 shadow-lg rounded-full bg-white inline-flex items-center justify-center"> <i className="fas fa-medal text-xl"></i> </div> <h6 className="text-xl mt-5 font-semibold text-white">First</h6> <p className="mt-2 mb-4 text-green-800"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&apos;s standard dummy text. </p> </div> <div className="w-full lg:w-3/12 px-4 text-center"> <div className="text-green-800 p-3 w-12 h-12 shadow-lg rounded-full bg-white inline-flex items-center justify-center"> <i className="fas fa-poll text-xl"></i> </div> <h5 className="text-xl mt-5 font-semibold text-white">Second</h5> <p className="mt-2 mb-4 text-green-800"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&apos;s standard dummy text. </p> </div> <div className="w-full lg:w-3/12 px-4 text-center"> <div className="text-green-800 p-3 w-12 h-12 shadow-lg rounded-full bg-white inline-flex items-center justify-center"> <i className="fas fa-lightbulb text-xl"></i> </div> <h5 className="text-xl mt-5 font-semibold text-white">Third</h5> <p className="mt-2 mb-4 text-green-800"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&apos;s standard dummy text. </p> </div> </div> </div> </section> <section className="relative block py-24 lg:pt-0 bg-green-300 dark:bg-green-600"> <div className="top-auto bottom-0 left-0 right-0 w-full absolute pointer-events-none overflow-hidden h-16" style={{ transform: "translateZ(0)" }} > <svg className="absolute bottom-0 overflow-hidden" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" version="1.1" viewBox="0 0 2560 100" x="0" y="0" > <polygon className="dark:text-green-900 text-green-200 fill-current" points="2560 0 2560 100 0 100" ></polygon> </svg> </div> </section> </> ) } export default HomeContent
42.529032
154
0.544448
b9334c7b51634c7aa64d5671dc1159eab72bd3a5
3,220
css
CSS
public/css/newStyle.css
nschenone/CSE_170_Final_Projet
53c63454c26086b562336a503c8542c3e62f33c8
[ "MIT" ]
null
null
null
public/css/newStyle.css
nschenone/CSE_170_Final_Projet
53c63454c26086b562336a503c8542c3e62f33c8
[ "MIT" ]
null
null
null
public/css/newStyle.css
nschenone/CSE_170_Final_Projet
53c63454c26086b562336a503c8542c3e62f33c8
[ "MIT" ]
null
null
null
:root { --primary-color: #393F4D; --secondary-color: #D4D4DC; } * { box-sizing: border-box; margin: 0; padding: 0; } html, body { height: 100%; font-family: 'Roboto', sans-serif; } .container { display: flex; flex-direction: column; padding: 0; height: 100%; width: 100%; } .content-container { display: flex; flex-direction: column; padding: 0; height: 100%; width: 100%; } .app-header { background-color: var(--primary-color); /* box-shadow: 2px 2px 5px #888; */ display: flex; flex-direction: column; height: 140px; margin-bottom: 15px; flex-grow: 0; flex-shrink: 0; } .app-header h3 { color: var(--secondary-color); margin: auto; } .app-header h5 { color: var(--secondary-color); margin: auto; margin-top: 10px; } .content { overflow: auto; margin-left: 10px; margin-right: 10px; flex: 1; } .container a,a:hover { /* color: #212529; */ /* text-decoration: none; */ color: black; } .content .card-block { display: flex; justify-content: space-between; background-color: var(--secondary-color); } .centered { display: flex; /* flex-direction: column; */ /* justify-content: center; */ /* padding: 50px; */ } .centered-outer { /* display: flex; */ flex-direction: row; /* margin: auto; */ /* justify-content: space-around; */ /* padding: 50px; */ } .centered-inner { margin: auto; /* padding-top: 50px; */ } .centered-inner img { /* margin: auto; */ /* width: 500px; */ /* color: green; */ /* padding-top: 50px; */ } .centered-inner-buttons { display: flex; justify-content: space-around; } .centered-inner-buttons i { margin-top: 35px; padding: 25px; font-size: 30px; color: var(--secondary-color); } .profile-pic { width: 100px; margin-left: 50px; /* padding-left: 100px; */ /* justify-content: center; */ /* margin: auto; */ } .class-name { font-size: 20px; } .class-description { font-size: 16px; } .class-professor { font-size: 14px; } .class-quarter { font-size: 14px; } .app-footer { flex-grow: 0; flex-shrink: 0; margin-top: 15px; height: 60px; background:var(--primary-color); padding: 9px; } .app-footer ul { display: flex; align-items: center; justify-content: space-evenly; /* justify-content: space-around; */ list-style: none; } .app-footer ul li { display: flex; flex-direction: column; align-items: center; color: var(--secondary-color); } .app-footer ul li .active { display: flex; flex-direction: column; align-items: center; color: var(--secondary-color); filter: sepia(100%); } .app-footer ul li i { font-size: 22px; margin-bottom: 2px; } .app-footer ul li p { font-size: 14px; margin-bottom: -7; } .profile-button { height: 60px; } .class-search { margin-bottom: 20px; } .file-upload input { display: none; } .upload-design-2 { border: solid; border-color: var(--primary-color); background-color: #e8f7fb; padding: 7px; /* width: 200px; */ /* margin: auto; */ }
16.262626
45
0.581988
b6eb89066b50954533530948e76f07fbb807c1ea
62
dart
Dart
lib/theme/config.dart
ERNICommunity/erni-eats-fe
05410780a9d5bed2c544a5935523d4690f69472c
[ "MIT" ]
null
null
null
lib/theme/config.dart
ERNICommunity/erni-eats-fe
05410780a9d5bed2c544a5935523d4690f69472c
[ "MIT" ]
26
2021-12-07T20:47:10.000Z
2022-02-01T08:18:57.000Z
lib/theme/config.dart
ERNICommunity/erni-eats-fe
05410780a9d5bed2c544a5935523d4690f69472c
[ "MIT" ]
null
null
null
import 'app-theme.dart'; AppTheme currentTheme = AppTheme();
15.5
35
0.741935
b608c72ba31ea7dbb8ba7f9de1316e504a930232
638
gemspec
Ruby
radix.gemspec
Odebe/radix
ddb8c5d1bb970fa7c02d0746f64d7ffd91236e0d
[ "MIT" ]
null
null
null
radix.gemspec
Odebe/radix
ddb8c5d1bb970fa7c02d0746f64d7ffd91236e0d
[ "MIT" ]
null
null
null
radix.gemspec
Odebe/radix
ddb8c5d1bb970fa7c02d0746f64d7ffd91236e0d
[ "MIT" ]
null
null
null
# encoding: utf-8 require File.expand_path('../lib/radix/version', __FILE__) Gem::Specification.new do |s| s.name = 'radix' s.version = Radix::VERSION s.authors = ['Luis Lavena', 'Odebe'] s.license = 'MIT' s.email = 'idunno' s.homepage = 'https://github.com/Odebe/radix' s.summary = 'Radix_tree implementation for Crystal language but ported to Ruby' s.description = 'Radix_tree implementation for Crystal language but ported to Ruby' s.files = Dir['{lib/**/*,[A-Z]*}'] s.platform = Gem::Platform::RUBY s.require_path = 'lib' s.rubyforge_project = '[none]' end
33.578947
86
0.628527
2d047fd5880279a10d9968e401c04e9ab80e3b33
342
css
CSS
src/app/ranked-option/ranked-option.component.css
blestander/electorate
d0219025417c4bbd01c11dce281ccc25479e1db3
[ "Apache-2.0" ]
null
null
null
src/app/ranked-option/ranked-option.component.css
blestander/electorate
d0219025417c4bbd01c11dce281ccc25479e1db3
[ "Apache-2.0" ]
1
2022-03-02T08:17:32.000Z
2022-03-02T08:17:32.000Z
src/app/ranked-option/ranked-option.component.css
blestander/electorate
d0219025417c4bbd01c11dce281ccc25479e1db3
[ "Apache-2.0" ]
null
null
null
div { margin-top: 2.5px; margin-bottom: 2.5px; padding: 2.5px; border-radius: 2.5px; text-align: center; vertical-align: middle; background-color: #7289DA; cursor: all-scroll; } div:hover { background-color: orangered } div.selected { cursor: pointer; } input { float: left; cursor: pointer; }
16.285714
31
0.619883
962b1fe7bbccedaab47e47b029a57b7686f65988
1,492
rb
Ruby
lib/imgflip/log.rb
callumanderson/imgflip-cucumber
d0676042c09ee0c9743c7bb6fe298e88ab47cccc
[ "MIT" ]
null
null
null
lib/imgflip/log.rb
callumanderson/imgflip-cucumber
d0676042c09ee0c9743c7bb6fe298e88ab47cccc
[ "MIT" ]
null
null
null
lib/imgflip/log.rb
callumanderson/imgflip-cucumber
d0676042c09ee0c9743c7bb6fe298e88ab47cccc
[ "MIT" ]
null
null
null
require 'colorize' require 'logger' module Imgflip class Log < Logger def format_message(severity, timestamp, progname, msg) if severity == 'DEBUG' "#{Time.now.strftime('%Y-%m-%d %X')} [#{severity}][#{self.calling_method}][#{self.line_calling_method}] ::#{msg}\n" elsif severity == 'WARN' "#{Time.now.strftime('%Y-%m-%d %X')} [#{severity}][#{self.calling_method}][#{self.line_calling_method}] ::#{msg}\n".magenta.bold elsif severity == 'INFO' "#{Time.now.strftime('%Y-%m-%d %X')} [#{severity}][#{self.calling_method}][#{self.line_calling_method}] :: #{msg}\n".green.bold elsif severity == 'ERROR' "#{Time.now.strftime('%Y-%m-%d %X')} [#{severity}][#{self.calling_method}][#{self.line_calling_method}] ::#{msg}\n".red.bold elsif severity == 'FATAL' "#{Time.now.strftime('%Y-%m-%d %X')} [#{severity}][#{self.calling_method}][#{self.line_calling_method}] ::#{msg}\n".black.blue.to_eol.bold else "#{Time.now.strftime('%Y-%m-%d %X')} [#{severity}][#{self.calling_method}][#{self.line_calling_method}] ::#{msg}\n".blue end end def deprecated(progname = nil, &block) add(DEPRECATED, nil, progname, &block) end #get name of the file where method is called def calling_method caller[3] =~ /.*\/(.*?)\:\d+/ and $1 end #get line number of the file where method is called def line_calling_method caller[3] =~ /.*\/.*?\:(\d+)/ and $1 end end end
37.3
146
0.595845
c51f92c8693d9c60667ab0718d3447ba5f75999e
95
css
CSS
public/projets_realises/css/style.css
OANDRE5/Simplon-Web
c7086ccb440e1e3f3cdc0478a92fef294a122bba
[ "MIT" ]
null
null
null
public/projets_realises/css/style.css
OANDRE5/Simplon-Web
c7086ccb440e1e3f3cdc0478a92fef294a122bba
[ "MIT" ]
1
2021-02-02T19:20:19.000Z
2021-02-02T19:20:19.000Z
public/projets_realises/css/style.css
OANDRE5/Simplon-Web
c7086ccb440e1e3f3cdc0478a92fef294a122bba
[ "MIT" ]
null
null
null
.marges { margin-left: 30%; margin-right: 30%; } .bordure { border-radius: 15px; }
9.5
24
0.568421
4570bf32f8a781a6b0414d933b138680e67aec35
861
py
Python
python/vision-ai/opencv/cv-image-base/image-gradient.py
media-tm/scrum-code
170efdc57bc65bd3114faf4091b5e3faceb46c74
[ "MIT" ]
null
null
null
python/vision-ai/opencv/cv-image-base/image-gradient.py
media-tm/scrum-code
170efdc57bc65bd3114faf4091b5e3faceb46c74
[ "MIT" ]
null
null
null
python/vision-ai/opencv/cv-image-base/image-gradient.py
media-tm/scrum-code
170efdc57bc65bd3114faf4091b5e3faceb46c74
[ "MIT" ]
null
null
null
#!/usr/bin/env python ''' 图像梯度原理: OpenCV提供了三种不同的梯度滤波器(高通滤波器):Sobel,Scharr和Laplacian。 Sobel和Scharr是求一阶或二阶导数。 Scharr是对Sobel(使用小的卷积核求解梯度角度时)的优化,Laplacian是求二阶导数。 https://www.kancloud.cn/aollo/aolloopencv ''' import cv2 import numpy from matplotlib import pyplot as plt img = cv2.imread('color-earth.png',0) laplacian = cv2.Laplacian(img,cv2.CV_64F) sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5) sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5) plt.subplot(2,2,1),plt.imshow(img,cmap='gray') plt.title('original'),plt.xticks([]),plt.yticks([]) plt.subplot(2,2,2),plt.imshow(laplacian,cmap='gray') plt.title('laplacian'),plt.xticks([]),plt.yticks([]) plt.subplot(2,2,3),plt.imshow(sobelx,cmap='gray') plt.title('Sobel X'),plt.xticks([]),plt.yticks([]) plt.subplot(2,2,4),plt.imshow(sobely,cmap='gray') plt.title('Sobel Y'),plt.xticks([]),plt.yticks([]) plt.show()
29.689655
52
0.729384
54bc15727861a9e686d27ad16915ff5488a0fd28
1,092
css
CSS
client/src/components/settings/user-profile/profile/profile.css
AlfiyaRF/cloud-pipeline
532c02a7e88928f42b28be87545aab93db404df5
[ "Apache-2.0" ]
null
null
null
client/src/components/settings/user-profile/profile/profile.css
AlfiyaRF/cloud-pipeline
532c02a7e88928f42b28be87545aab93db404df5
[ "Apache-2.0" ]
null
null
null
client/src/components/settings/user-profile/profile/profile.css
AlfiyaRF/cloud-pipeline
532c02a7e88928f42b28be87545aab93db404df5
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2017-2021 EPAM Systems, Inc. (https://www.epam.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. */ .container { flex: 1; overflow: auto; } .container .attributes { margin: 0 5px; } .header { font-size: large; font-weight: bold; margin: 0 8px; } .info { width: 150px; vertical-align: top; } .info-value { vertical-align: top; } .divider { margin: 10px 0; } .roles { display: flex; flex-wrap: wrap; align-items: center; } .role { margin: 0 5px 5px 0; border: 1px solid #ddd; padding: 2px 5px; border-radius: 5px; }
19.157895
76
0.677656
dfa6a25274eb7be6f381119da2f7e6a9d5bae850
5,563
cs
C#
src/go2cs/Converter/Converter_IfStmt.cs
rgwood/go2cs
9d9b931c53153bc1598268951de779ad9216e631
[ "MIT" ]
249
2018-06-02T10:42:32.000Z
2022-03-23T20:54:45.000Z
src/go2cs/Converter/Converter_IfStmt.cs
rgwood/go2cs
9d9b931c53153bc1598268951de779ad9216e631
[ "MIT" ]
14
2019-01-22T18:55:14.000Z
2022-03-13T21:26:45.000Z
src/go2cs/Converter/Converter_IfStmt.cs
rgwood/go2cs
9d9b931c53153bc1598268951de779ad9216e631
[ "MIT" ]
35
2018-08-01T18:04:30.000Z
2022-02-23T03:25:25.000Z
//****************************************************************************************************** // Converter_Statement.cs - Gbtc // // Copyright © 2018, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 05/04/2018 - J. Ritchie Carroll // Generated original version of source code. // //****************************************************************************************************** using go2cs.Metadata; using System; namespace go2cs { public partial class Converter { public const string IfElseMarker = ">>MARKER:IFELSE_LEVEL_{0}<<"; public const string IfElseBreakMarker = ">>MARKER:IFELSEBREAK_LEVEL_{0}<<"; public const string IfExpressionMarker = ">>MARKER:IFEXPR_LEVEL_{0}<<"; public const string IfStatementMarker = ">>MARKER:IFSTATEMENT_LEVEL_{0}<<"; private int m_ifExpressionLevel; public override void EnterIfStmt(GoParser.IfStmtContext context) { // ifStmt // : 'if '(simpleStmt ';') ? expression block ( 'else' ( ifStmt | block ) ) ? m_ifExpressionLevel++; if (context.simpleStmt() is not null && context.simpleStmt().emptyStmt() is null) { // Any declared variable will be scoped to if statement, so create a sub-block for it if (context.simpleStmt().shortVarDecl() is not null) { m_targetFile.AppendLine($"{Spacing()}{{"); IndentLevel++; // Handle storing of current values of any redeclared variables m_targetFile.Append(OpenRedeclaredVariableBlock(context.simpleStmt().shortVarDecl().identifierList(), m_ifExpressionLevel)); } m_targetFile.Append(string.Format(IfStatementMarker, m_ifExpressionLevel)); } m_targetFile.AppendLine($"{string.Format(IfElseBreakMarker, m_ifExpressionLevel)}{Spacing()}{string.Format(IfElseMarker, m_ifExpressionLevel)}if ({string.Format(IfExpressionMarker, m_ifExpressionLevel)})"); if (context.block().Length == 2) { PushOuterBlockSuffix(null); // For current block PushOuterBlockSuffix($"{Environment.NewLine}{Spacing()}else{(LineTerminatorAhead(context.block(0)) ? "" : Environment.NewLine)}"); } else { PushOuterBlockSuffix(null); // For current block } } public override void ExitIfStmt(GoParser.IfStmtContext context) { // ifStmt // : 'if '(simpleStmt ';') ? expression block ( 'else' ( ifStmt | block ) ) ? if (Expressions.TryGetValue(context.expression(), out ExpressionInfo expression)) { bool isElseIf = context.Parent is GoParser.IfStmtContext; // Replace if markers m_targetFile.Replace(string.Format(IfExpressionMarker, m_ifExpressionLevel), expression.Text); m_targetFile.Replace(string.Format(IfElseBreakMarker, m_ifExpressionLevel), isElseIf ? Environment.NewLine : ""); m_targetFile.Replace(string.Format(IfElseMarker, m_ifExpressionLevel), isElseIf ? "else " : ""); } else { AddWarning(context, $"Failed to find expression for if statement: {context.GetText()}"); } if (context.simpleStmt() is not null && context.simpleStmt().emptyStmt() is null) { if (m_simpleStatements.TryGetValue(context.simpleStmt(), out string statement)) m_targetFile.Replace(string.Format(IfStatementMarker, m_ifExpressionLevel), statement + Environment.NewLine); else AddWarning(context, $"Failed to find simple statement for if statement: {context.simpleStmt().GetText()}"); // Close any locally scoped declared variable sub-block if (context.simpleStmt().shortVarDecl() is not null) { // Handle restoration of previous values of any redeclared variables m_targetFile.Append(CloseRedeclaredVariableBlock(context.simpleStmt().shortVarDecl().identifierList(), m_ifExpressionLevel)); IndentLevel--; m_targetFile.AppendLine(); m_targetFile.Append($"{Spacing()}}}{CheckForCommentsRight(context)}"); } } if (!EndsWithLineFeed(m_targetFile.ToString())) m_targetFile.AppendLine(); m_ifExpressionLevel--; } } }
47.144068
218
0.584217
a016db255cb8fe6eda177f3a5e9e225ab4b65ac7
354
ts
TypeScript
src/themes/lightTheme.ts
vishnugopal/typed-themes-template
66992cf8d4914437407e2471dc474b4ba4b918e1
[ "MIT" ]
7
2020-08-14T20:03:53.000Z
2022-02-11T11:28:28.000Z
src/themes/lightTheme.ts
vishnugopal/typed-themes-template
66992cf8d4914437407e2471dc474b4ba4b918e1
[ "MIT" ]
null
null
null
src/themes/lightTheme.ts
vishnugopal/typed-themes-template
66992cf8d4914437407e2471dc474b4ba4b918e1
[ "MIT" ]
3
2020-08-14T20:04:22.000Z
2020-09-26T23:28:48.000Z
import Theme from './Theme'; const lightTheme: Theme = { name: 'Light', neutralColor: 'gray', actionColor: 'blue', secondaryActionColor: 'purple', dangerColor: 'red', warningColor: 'yellow', successColor: 'green', defaultIntensity: 200, hoverIntensity: 300, selectedIntensity: 600, }; export default lightTheme;
20.823529
35
0.661017
c30d40ad35eafc406dfcaa2e22e86ebc596f0e7d
806
swift
Swift
Douyu/Douyu/Classes/Tools/NetWorkTools.swift
a178960320/MyDouyu
d76a92fdf6f0446e2f1de1234e544d2676e2eb9b
[ "MIT" ]
null
null
null
Douyu/Douyu/Classes/Tools/NetWorkTools.swift
a178960320/MyDouyu
d76a92fdf6f0446e2f1de1234e544d2676e2eb9b
[ "MIT" ]
null
null
null
Douyu/Douyu/Classes/Tools/NetWorkTools.swift
a178960320/MyDouyu
d76a92fdf6f0446e2f1de1234e544d2676e2eb9b
[ "MIT" ]
null
null
null
// // NetWorkTools.swift // Douyu // // Created by 住梦iOS on 2017/2/28. // Copyright © 2017年 qiongjiwuxian. All rights reserved. // import UIKit import Alamofire enum MethodType{ case GET case Post } class NetWorkTools{ class func requestData(type:MethodType,URLString:String,parameters:Parameters? = nil,finishedCallBack:@escaping (_ result:AnyObject) -> ()) { //1.获取请求类型 Alamofire.request(URLString, method:type == .GET ? .get:.post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in guard let result = response.result.value else{ print(response.result.error) return } finishedCallBack(result as AnyObject) } } }
24.424242
169
0.62531
1298a72b720b7bdafd5a1d0a3389694bc8c68e8d
1,006
sql
SQL
third_party/ldbc/queries/sf10/q20.sql
graindb/graindb-demonstration
be901b3e66fc991ea3ecfbcfabdcd07af82dd2d7
[ "MIT" ]
1
2021-08-30T16:08:17.000Z
2021-08-30T16:08:17.000Z
third_party/ldbc/queries/sf10/q20.sql
graindb/graindb-demonstration
be901b3e66fc991ea3ecfbcfabdcd07af82dd2d7
[ "MIT" ]
1
2021-12-12T03:36:02.000Z
2021-12-12T03:36:02.000Z
third_party/ldbc/queries/sf10/q20.sql
graindb/graindb-demonstration
be901b3e66fc991ea3ecfbcfabdcd07af82dd2d7
[ "MIT" ]
null
null
null
/* interactive-complex-13 */ WITH RECURSIVE search_graph AS ( SELECT 26388279067527::bigint AS link, 0 AS depth --, ARRAY[26388279067527::bigint]::bigint[] AS path UNION ALL (WITH sg as (select link, depth from search_graph) -- Note: sg is only the diff produced in the previous iteration SELECT distinct k_person2id, x.depth + 1 --, array_append(path, k_person2id) FROM knows, sg x WHERE 1 = 1 and x.link = k_person1id --and k_person2id <> ALL (path) -- stop if we have reached person2 in the previous iteration and not exists(select * from sg y where y.link = 13194139540791::bigint) -- skip reaching persons reached in the previous iteration and not exists(select * from sg y where y.link = k_person2id) ) ) select max(depth) from ( select depth from search_graph where link = 13194139540791::bigint union select -1) tmp;
35.928571
118
0.620278
4ce2dbaa4310fb00a988715555c7dadd782f286e
406
py
Python
semesterpage/migrations/0015_remove_options_homepage_slug.py
JakobGM/WikiLinks
5743b1d4c3fefa66fcaa4d283436d2a3f0490604
[ "MIT" ]
6
2017-08-12T09:55:06.000Z
2019-09-03T08:05:21.000Z
semesterpage/migrations/0015_remove_options_homepage_slug.py
JakobGM/WikiLinks
5743b1d4c3fefa66fcaa4d283436d2a3f0490604
[ "MIT" ]
57
2017-08-11T23:05:07.000Z
2022-03-11T23:32:12.000Z
semesterpage/migrations/0015_remove_options_homepage_slug.py
JakobGM/WikiLinks
5743b1d4c3fefa66fcaa4d283436d2a3f0490604
[ "MIT" ]
1
2017-09-27T15:31:15.000Z
2017-09-27T15:31:15.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-02 11:00 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('semesterpage', '0014_auto_20170802_1253'), ] operations = [ migrations.RemoveField( model_name='options', name='homepage_slug', ), ]
20.3
52
0.625616
3f6e201ec58279a7b323bbe6e09c98df37b9db7e
23,531
sql
SQL
conf/evolutions/default/1.sql
VuongTuanKhanh/DevC_2019_Sendo
47a129e8d7099c8390799585f4373519d96c99c0
[ "CC0-1.0" ]
null
null
null
conf/evolutions/default/1.sql
VuongTuanKhanh/DevC_2019_Sendo
47a129e8d7099c8390799585f4373519d96c99c0
[ "CC0-1.0" ]
null
null
null
conf/evolutions/default/1.sql
VuongTuanKhanh/DevC_2019_Sendo
47a129e8d7099c8390799585f4373519d96c99c0
[ "CC0-1.0" ]
null
null
null
# --- Created by Ebean DDL # To stop Ebean DDL generation, remove this comment and start using Evolutions # --- !Ups create table agency ( id integer auto_increment not null, agency_name varchar(255), distribution_channel_id integer not null, enable tinyint(1) default 0, constraint pk_agency primary key (id) ); create table booker ( id integer auto_increment not null, user_id bigint, agency_id integer not null, distribution_channel_id integer not null, enable tinyint(1) default 0, constraint pk_booker primary key (id) ); create table distribution_channel ( id integer auto_increment not null, distribution_name varchar(255), enable tinyint(1) default 0, constraint pk_distribution_channel primary key (id) ); create table element ( id integer auto_increment not null, name varchar(255), atomic_number integer not null, symbol varchar(255), metal_group varchar(255), constraint pk_element primary key (id) ); create table element_sub ( id integer auto_increment not null, name varchar(255), atomic_number integer not null, symbol varchar(255), metal_group varchar(255), constraint pk_element_sub primary key (id) ); create table email_history ( id bigint auto_increment not null, order_id bigint, event_id bigint, order_status integer not null, email_status integer not null, email_time datetime(6), constraint pk_email_history primary key (id) ); create table event ( id bigint auto_increment not null, name_vi varchar(255), name_en varchar(255), event_type varchar(255), link varchar(255), address_vi varchar(255), address_en varchar(255), location varchar(255), venue_vi varchar(255), venue_en varchar(255), banner_vi varchar(255), banner_en varchar(255), poster_vi varchar(255), poster_en varchar(255), sit_map varchar(255), date_show bigint, enable tinyint(1) default 0, description_vi varchar(5000), description_en varchar(5000), email_contact varchar(255), phone_contact varchar(255), list_organizer varchar(1000), list_condition varchar(500), time_remind_event integer not null, time_remind_payment integer not null, time_cancel_payment integer not null, time_remind_payment_payoo_store integer not null, time_cancel_payment_payoo_store integer not null, time_remind_payment_office integer not null, time_cancel_payment_office integer not null, is_dual_language integer not null, is_send_email integer not null, is_send_email_remind integer not null, is_allow_checkin integer not null, is_send_email_remind_event integer not null, constraint pk_event primary key (id) ); create table event_condition ( id integer auto_increment not null, event_id bigint, id_condition integer not null, enable tinyint(1) default 0, constraint pk_event_condition primary key (id) ); create table event_gift ( id integer auto_increment not null, event_id bigint, name varchar(255), image varchar(255), description varchar(255), number integer not null, used integer not null, enable tinyint(1) default 0, constraint pk_event_gift primary key (id) ); create table event_group_voucher ( id bigint auto_increment not null, event_id bigint, type integer not null, name varchar(255), note varchar(255), number integer not null, number_min_ticket integer not null, discount_value integer not null, min_revenue_order integer not null, max_discount integer not null, code_group varchar(255), gen_code_type integer not null, revenue_discount_type integer not null, list_gift varchar(255), enable tinyint(1) default 0, constraint pk_event_group_voucher primary key (id) ); create table event_offer_discount ( id integer auto_increment not null, event_id bigint, offer_discount integer not null, agency_id integer not null, distribution_channel_id integer not null, enable tinyint(1) default 0, constraint pk_event_offer_discount primary key (id) ); create table event_order ( id bigint auto_increment not null, event_id bigint, gender integer not null, name varchar(255), phone varchar(255), email varchar(255), company_name varchar(255), company_address varchar(255), company_tax_code varchar(255), city varchar(255), district varchar(255), ward varchar(255), address varchar(255), buyer_user_id bigint, note varchar(255), pay_type integer not null, apply_voucher varchar(255), revenue_before integer not null, revenue_discount integer not null, revenue_after integer not null, ticket_info varchar(5000), time_create bigint, invoice_vat tinyint(1) default 0, status integer not null, time_payment_success bigint, time_send_email varchar(255), language_code integer not null, constraint pk_event_order primary key (id) ); create table event_order_gift ( id integer auto_increment not null, event_id bigint, id_order bigint, id_gift integer not null, number integer not null, time_create bigint, status integer not null, constraint pk_event_order_gift primary key (id) ); create table event_organizer ( id integer auto_increment not null, event_id bigint, name varchar(255), image varchar(255), enable tinyint(1) default 0, description varchar(5000), constraint pk_event_organizer primary key (id) ); create table event_payment_method ( id integer auto_increment not null, event_id bigint, id_payment_method integer not null, enable tinyint(1) default 0, constraint pk_event_payment_method primary key (id) ); create table event_payment_office_address ( id integer auto_increment not null, event_id bigint, address varchar(255), enable tinyint(1) default 0, constraint pk_event_payment_office_address primary key (id) ); create table event_refund_condition ( id integer auto_increment not null, event_id bigint, is_refund tinyint(1) default 0, refund_after_day integer not null, refund_condition varchar(255), enable tinyint(1) default 0, constraint pk_event_refund_condition primary key (id) ); create table event_require_info ( id integer auto_increment not null, event_id bigint, index_sort integer not null, question_vi varchar(255), question_en varchar(255), answer_type varchar(255), required tinyint(1) default 0, enable tinyint(1) default 0, constraint pk_event_require_info primary key (id) ); create table event_require_info_answer ( id integer auto_increment not null, event_id bigint, order_id bigint, event_require_info_id integer not null, answer varchar(255), constraint pk_event_require_info_answer primary key (id) ); create table event_require_info_detail ( id integer auto_increment not null, event_require_info_id integer not null, index_sort integer not null, value varchar(255), text_vi varchar(255), text_en varchar(255), enable tinyint(1) default 0, constraint pk_event_require_info_detail primary key (id) ); create table event_schedule ( id bigint auto_increment not null, event_id bigint, date varchar(255), time varchar(255), start bigint, end bigint, time_show bigint, title varchar(255), note varchar(255), enable tinyint(1) default 0, constraint pk_event_schedule primary key (id) ); create table event_schedule_ticket_type ( id integer auto_increment not null, id_schedule integer not null, id_ticket_type bigint, create_time bigint, action_user integer not null, note varchar(255), enable tinyint(1) default 0, number_ticket_sold integer not null, constraint pk_event_schedule_ticket_type primary key (id) ); create table event_ticket_type ( id bigint auto_increment not null, event_id bigint, name_vi varchar(255), name_en varchar(255), total integer not null, price bigint, min_buy integer not null, max_buy integer not null, start bigint, end bigint, start_date varchar(255), end_date varchar(255), start_time varchar(255), end_time varchar(255), type_ticket varchar(255), description_vi varchar(10000), description_en varchar(10000), note varchar(255), stop_ticketing tinyint(1) default 0, only_payment_office tinyint(1) default 0, schedule_text varchar(255), enable tinyint(1) default 0, total_ticket_sold integer not null, constraint pk_event_ticket_type primary key (id) ); create table event_type ( id integer auto_increment not null, name varchar(255), note varchar(255), constraint pk_event_type primary key (id) ); create table event_voucher ( id bigint auto_increment not null, event_id bigint, order_id bigint, group_voucher_id bigint, code varchar(255), used tinyint(1) default 0, enable tinyint(1) default 0, constraint pk_event_voucher primary key (id) ); create table event_voucher_condition ( id integer auto_increment not null, group_voucher_id bigint, ticket_type_id bigint, schedule_id bigint, number integer not null, start bigint, end bigint, enable tinyint(1) default 0, constraint pk_event_voucher_condition primary key (id) ); create table event_voucher_get_ticket ( id integer auto_increment not null, group_voucher_id bigint, ticket_type_id bigint, schedule_id bigint, number integer not null, enable tinyint(1) default 0, constraint pk_event_voucher_get_ticket primary key (id) ); create table event_voucher_gift ( id integer auto_increment not null, id_voucher bigint, id_gift integer not null, number integer not null, enable tinyint(1) default 0, constraint pk_event_voucher_gift primary key (id) ); create table event_voucher_ticket ( id integer auto_increment not null, id_voucher bigint, id_ticket_type integer not null, id_schedule integer not null, number integer not null, type_discount varchar(255), discount integer not null, enable tinyint(1) default 0, constraint pk_event_voucher_ticket primary key (id) ); create table list_condition ( id integer auto_increment not null, image varchar(255), description varchar(255), enable tinyint(1) default 0, constraint pk_list_condition primary key (id) ); create table payment_method ( id integer auto_increment not null, name varchar(255), enable tinyint(1) default 0, constraint pk_payment_method primary key (id) ); create table permission ( id integer auto_increment not null, event_id bigint, user_id bigint, permission_group_id integer not null, enable tinyint(1) default 0, constraint pk_permission primary key (id) ); create table permission_action_list ( id integer auto_increment not null, action_name varchar(255), enable tinyint(1) default 0, constraint pk_permission_action_list primary key (id) ); create table permission_list ( id integer auto_increment not null, permission_name varchar(255), time_create varchar(255), enable tinyint(1) default 0, note varchar(255), constraint uq_permission_list_permission_name unique (permission_name), constraint pk_permission_list primary key (id) ); create table permission_user_action ( id integer auto_increment not null, permission_id integer not null, action_id integer not null, enable tinyint(1) default 0, constraint pk_permission_user_action primary key (id) ); create table product ( product_id integer auto_increment not null, name varchar(255), image varchar(255), href varchar(255), price integer not null, belong_cate_level1_id integer not null, belong_cate_level2_id integer not null, belong_cate_level3_id integer not null, enable integer not null, constraint pk_product primary key (product_id) ); create table product_sale ( product_id integer auto_increment not null, name varchar(255), image varchar(255), href varchar(255), price integer not null, belong_cate_level1_id integer not null, belong_cate_level2_id integer not null, belong_cate_level3_id integer not null, enable integer not null, constraint pk_product_sale primary key (product_id) ); create table product_trending ( product_id integer auto_increment not null, name varchar(255), image varchar(255), href varchar(255), price integer not null, belong_cate_level1_id integer not null, belong_cate_level2_id integer not null, belong_cate_level3_id integer not null, enable integer not null, constraint pk_product_trending primary key (product_id) ); create table relationship ( id integer auto_increment not null, full_name varchar(255), user_name varchar(255), email varchar(255), phone_number varchar(255), password varchar(255), gender varchar(255), birthday varchar(255), permission_user varchar(255), time_create bigint, action_user varchar(255), note varchar(255), constraint pk_relationship primary key (id) ); create table slide_banner ( id integer auto_increment not null, event_id bigint, time_create bigint, type integer not null, date_from bigint, date_to bigint, enable tinyint(1) default 0, constraint pk_slide_banner primary key (id) ); create table status ( id integer auto_increment not null, value integer not null, content varchar(255), type varchar(255), note varchar(255), constraint pk_status primary key (id) ); create table ticket ( id bigint auto_increment not null, event_id bigint, id_order bigint, id_ticket_type bigint, id_schedule bigint, id_schedule_ticket_type integer not null, revenue_before integer not null, revenue_discount integer not null, revenue_after integer not null, time_create bigint, status integer not null, checkin_status integer not null, checkin_info varchar(255), note varchar(255), seat varchar(255), constraint pk_ticket primary key (id) ); create table token ( id integer auto_increment not null, phone varchar(255), token varchar(255), device varchar(255), time_create bigint, enable tinyint(1) default 0, constraint pk_token primary key (id) ); create table user ( user_id bigint auto_increment not null, name varchar(255), constraint pk_user primary key (user_id) ); create table user_product_log ( user_id varchar(255) not null, product_id integer not null, belong_cate_level1_id integer not null, belong_cate_level1_name varchar(255), belong_cate_level2_id integer not null, belong_cate_level2_name varchar(255), belong_cate_level3_id integer not null, belong_cate_level3_name varchar(255), time_create bigint, constraint pk_user_product_log primary key (user_id) ); create table user_search_keyword ( user_id varchar(255) not null, keyword varchar(255), time_create bigint, constraint pk_user_search_keyword primary key (user_id) ); # --- !Downs drop table if exists agency; drop table if exists booker; drop table if exists distribution_channel; drop table if exists element; drop table if exists element_sub; drop table if exists email_history; drop table if exists event; drop table if exists event_condition; drop table if exists event_gift; drop table if exists event_group_voucher; drop table if exists event_offer_discount; drop table if exists event_order; drop table if exists event_order_gift; drop table if exists event_organizer; drop table if exists event_payment_method; drop table if exists event_payment_office_address; drop table if exists event_refund_condition; drop table if exists event_require_info; drop table if exists event_require_info_answer; drop table if exists event_require_info_detail; drop table if exists event_schedule; drop table if exists event_schedule_ticket_type; drop table if exists event_ticket_type; drop table if exists event_type; drop table if exists event_voucher; drop table if exists event_voucher_condition; drop table if exists event_voucher_get_ticket; drop table if exists event_voucher_gift; drop table if exists event_voucher_ticket; drop table if exists list_condition; drop table if exists payment_method; drop table if exists permission; drop table if exists permission_action_list; drop table if exists permission_list; drop table if exists permission_user_action; drop table if exists product; drop table if exists product_sale; drop table if exists product_trending; drop table if exists relationship; drop table if exists slide_banner; drop table if exists status; drop table if exists ticket; drop table if exists token; drop table if exists user; drop table if exists user_product_log; drop table if exists user_search_keyword;
36.53882
78
0.539076
540b1e857fb8ff077a8cd029f21073a922111807
62
css
CSS
wro4j-core/src/test/resources/ro/isdc/wro/model/resource/processor/jawrcss/expected/css3.css
changcheng/wro4j
778e00e1be798f2cca9579450a88d55edd12a70a
[ "Apache-2.0" ]
517
2015-03-25T17:19:51.000Z
2022-03-02T15:44:08.000Z
wro4j-core/src/test/resources/ro/isdc/wro/model/resource/processor/jawrcss/expected/css3.css
changcheng/wro4j
778e00e1be798f2cca9579450a88d55edd12a70a
[ "Apache-2.0" ]
209
2015-03-25T21:07:40.000Z
2021-12-18T19:03:28.000Z
wro4j-core/src/test/resources/ro/isdc/wro/model/resource/processor/jawrcss/expected/css3.css
changcheng/wro4j
778e00e1be798f2cca9579450a88d55edd12a70a
[ "Apache-2.0" ]
146
2015-03-30T11:16:54.000Z
2022-03-22T02:18:21.000Z
ul.addobj a[href$='.pdf']{background-image:url(/img/pdf.png);}
62
62
0.693548
dd59f31e9e3b0afbf2d67dceb53fc62abe1812aa
11,840
java
Java
jodd-db/src/main/java/jodd/db/oom/DbOomManager.java
zhiyongwang/jodd
5af5518c1910ee64df4034540bf8f30a1771f15c
[ "BSD-2-Clause" ]
null
null
null
jodd-db/src/main/java/jodd/db/oom/DbOomManager.java
zhiyongwang/jodd
5af5518c1910ee64df4034540bf8f30a1771f15c
[ "BSD-2-Clause" ]
null
null
null
jodd-db/src/main/java/jodd/db/oom/DbOomManager.java
zhiyongwang/jodd
5af5518c1910ee64df4034540bf8f30a1771f15c
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.db.oom; import jodd.db.oom.naming.ColumnNamingStrategy; import jodd.db.oom.naming.TableNamingStrategy; import jodd.util.StringUtil; import jodd.log.Logger; import jodd.log.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * DbOom manager. Contains various global settings, DB-OOM (database - object-oriented) * mapping definitions, naming conventions etc. * <p> * Important: configure settings before entity registration! * <p> * Mapping definitions are used <b>only</b> by a result set mapper (such as {@link jodd.db.oom.mapper.ResultSetMapper} * to lookup for an entity from table name. Table names are read from result-set meta data, for example. * Moreover, it is not needed to use mappings at all: in that case just provide entity types during result set to * objects conversion. * * @see jodd.db.DbManager */ public class DbOomManager { private static final Logger log = LoggerFactory.getLogger(DbOomManager.class); // ---------------------------------------------------------------- singleton private static DbOomManager dbOomManager = new DbOomManager(); /** * Returns DbOom manager instance. */ public static DbOomManager getInstance() { return dbOomManager; } /** * Sets new DbOom manager. */ public static void setInstance(DbOomManager oomManager) { dbOomManager = oomManager; } /** * Resets DbOom Manager to defaults. * It's done by simply creating a new instance * of DbOom manager. */ public static void resetAll() { dbOomManager = new DbOomManager(); } // ---------------------------------------------------------------- naming protected String schemaName; protected TableNamingStrategy tableNames = new TableNamingStrategy(); protected ColumnNamingStrategy columnNames = new ColumnNamingStrategy(); /** * Returns current table name strategy. */ public TableNamingStrategy getTableNames() { return tableNames; } /** * Sets new table name strategy. */ public void setTableNames(TableNamingStrategy tableNames) { this.tableNames = tableNames; } /** * Returns current column name strategy. */ public ColumnNamingStrategy getColumnNames() { return columnNames; } /** * Sets new column name strategy, */ public void setColumnNames(ColumnNamingStrategy columnNames) { this.columnNames = columnNames; } // ---------------------------------------------------------------- registration protected String[] primitiveEntitiesPrefixes = new String[] { "java.lang.", "jodd.mutable.", int.class.getName(), long.class.getName(), float.class.getName(), double.class.getName(), short.class.getName(), boolean.class.getName(), byte.class.getName()}; public String[] getPrimitiveEntitiesPrefixes() { return primitiveEntitiesPrefixes; } /** * Specifies array of class name prefixes that will be mapped directly to column. */ public void setPrimitiveEntitiesPrefixes(String... primitiveEntitiesPrefixes) { this.primitiveEntitiesPrefixes = primitiveEntitiesPrefixes; } protected Map<Class, DbEntityDescriptor> descriptorsMap = new HashMap<>(); protected Map<String, DbEntityDescriptor> entityNamesMap = new HashMap<>(); protected Map<String, DbEntityDescriptor> tableNamesMap = new NamedValuesHashMap<>(); /** * Lookups {@link DbEntityDescriptor} for some type and registers the type if is new. * <p> * Returns <code>null</code> for core classes from <code>java</code> run-time packages! * Some types are <b>not</b> entities, i.e. domain objects. Instead, primitive entities * are simply mapped to one column. */ public <E> DbEntityDescriptor<E> lookupType(Class<E> type) { String typeName = type.getName(); if (StringUtil.startsWithOne(typeName, primitiveEntitiesPrefixes) != -1) { return null; } DbEntityDescriptor<E> ded = descriptorsMap.get(type); if (ded == null) { ded = registerType(type); } return ded; } /** * Returns <code>true</code> if type is registered withing manager. */ public boolean isRegistered(Class type) { return descriptorsMap.containsKey(type); } /** * Lookups for {@link jodd.db.oom.DbEntityDescriptor} that was registered with this manager. * Returns <code>null</code> if name not found. */ public DbEntityDescriptor lookupName(String typeName) { return entityNamesMap.get(typeName); } /** * Lookups for {@link jodd.db.oom.DbEntityDescriptor} that was registered with this manager. * Returns <code>null</code> if table name not found. Lookup is case-insensitive. */ public DbEntityDescriptor lookupTableName(String tableName) { return tableNamesMap.get(tableName); } /** * Registers just type and entity names. Enough for most usages. */ public <E> DbEntityDescriptor<E> registerType(Class<E> type) { DbEntityDescriptor<E> ded = createDbEntityDescriptor(type); DbEntityDescriptor<E> existing = descriptorsMap.put(type, ded); if (log.isDebugEnabled()) { log.debug("Register " + type.getName() + " as " + ded.getTableName()); } if (existing != null) { if (ded.getType() == type) { return ded; } throw new DbOomException("Type already registered: " + existing.getType()); } existing = entityNamesMap.put(ded.getEntityName(), ded); if (existing != null) { throw new DbOomException("Name '" + ded.getEntityName() + "' already mapped to an entity: " + existing.getType()); } return ded; } /** * Registers entity. {@link #registerType(Class) Registers types} and table names. */ public <E> DbEntityDescriptor<E> registerEntity(Class<E> type) { DbEntityDescriptor<E> ded = registerType(type); DbEntityDescriptor existing = tableNamesMap.put(ded.getTableName(), ded); if (existing != null) { if (ded.getType() == type) { return ded; } throw new DbOomException("Entity registration failed! Table '" + ded.getTableName() + "' already mapped to an entity: " + existing.getType()); } return ded; } /** * Registers entity. Existing entity will be removed if exist, so no exception will be thrown. */ public <E> DbEntityDescriptor<E> registerEntity(Class<E> type, boolean force) { if (force) { removeEntity(type); } return registerEntity(type); } /** * Removes entity and returns removed descriptor. */ public <E> DbEntityDescriptor<E> removeEntity(Class<E> type) { DbEntityDescriptor<E> ded = descriptorsMap.remove(type); if (ded == null) { ded = createDbEntityDescriptor(type); } entityNamesMap.remove(ded.getEntityName()); tableNamesMap.remove(ded.getTableName()); return ded; } /** * Creates {@link DbEntityDescriptor}. */ protected <E> DbEntityDescriptor<E> createDbEntityDescriptor(Class<E> type) { return new DbEntityDescriptor<>(type, schemaName, tableNames, columnNames); } // ---------------------------------------------------------------- stats /** * Returns total number of registered entity names. */ public int getTotalNames() { return entityNamesMap.size(); } /** * Returns total number of registered table names. */ public int getTotalTableNames() { return tableNamesMap.size(); } /** * Returns total number of registered types. */ public int getTotalTypes() { return descriptorsMap.size(); } /** * Resets the manager and clears descriptors maps. * The configuration is not changed, just table-related * data is cleared. To reset all, call {@link #resetAll()}. */ public void reset() { descriptorsMap.clear(); entityNamesMap.clear(); tableNamesMap.clear(); } // ---------------------------------------------------------------- table separators protected String columnAliasSeparator = "$"; /** * Returns value for separator for column aliases that divides table reference and column name. */ public String getColumnAliasSeparator() { return columnAliasSeparator; } /** * Specifies separator for column aliases that divides table reference and column name. * Separator should contains of characters that are not used in table names, such as: * '$' or '__'. */ public void setColumnAliasSeparator(String separator) { this.columnAliasSeparator = separator; } // ---------------------------------------------------------------- hint resolver protected JoinHintResolver hintResolver = new JoinHintResolver(); public JoinHintResolver getHintResolver() { return hintResolver; } /** * Specifies hint resolver. */ public void setHintResolver(JoinHintResolver hintResolver) { this.hintResolver = hintResolver; } // ---------------------------------------------------------------- default column alias type protected ColumnAliasType defaultColumnAliasType; public ColumnAliasType getDefaultColumnAliasType() { return defaultColumnAliasType; } /** * Specifies default column alias type. */ public void setDefaultColumnAliasType(ColumnAliasType defaultColumnAliasType) { this.defaultColumnAliasType = defaultColumnAliasType; } // ---------------------------------------------------------------- result set mapper protected boolean cacheEntitiesInResultSet; public boolean isCacheEntitiesInResultSet() { return cacheEntitiesInResultSet; } /** * Defines if entities have to be cached in result set. * When cached, more memory is consumed during the existence of * {@link jodd.db.oom.mapper.ResultSetMapper}. */ public void setCacheEntitiesInResultSet(boolean cacheEntitiesInResultSet) { this.cacheEntitiesInResultSet = cacheEntitiesInResultSet; } // ---------------------------------------------------------------- db list protected boolean entityAwareMode; /** * Returns <code>true</code> if entity-aware mode is enabled. */ public boolean isEntityAwareMode() { return entityAwareMode; } /** * Defines entity-aware mode, when resulting collections does not have duplicates. * It make sense to enable it only if {@link #setCacheEntitiesInResultSet(boolean) cache} is set. * Therefore, enabling smart mode will also enable caching. */ public void setEntityAwareMode(boolean entityAwareMode) { if (entityAwareMode) { this.cacheEntitiesInResultSet = true; } this.entityAwareMode = entityAwareMode; } // ---------------------------------------------------------------- create entity /** * Creates new entity instances. */ public <E> E createEntityInstance(Class<E> type) { try { return type.newInstance(); } catch (Exception ex) { throw new DbOomException(ex); } } }
29.526185
145
0.686402
4d1c800a0f24eedc8f750e03fac8d80b47a06bf3
2,227
cs
C#
Facturama/Models/Retentions/Complements/ServiciosPlataformasTecnologicas.cs
rafa-dx/facturama-dotnet-sdk
2bbbe66157522f627e736937223471f3e8f3d2aa
[ "Apache-2.0" ]
2
2019-03-26T19:47:42.000Z
2021-08-14T14:16:37.000Z
Facturama/Models/Retentions/Complements/ServiciosPlataformasTecnologicas.cs
rafa-dx/facturama-dotnet-sdk
2bbbe66157522f627e736937223471f3e8f3d2aa
[ "Apache-2.0" ]
1
2021-08-13T00:03:44.000Z
2021-08-20T18:41:02.000Z
Facturama/Models/Retentions/Complements/ServiciosPlataformasTecnologicas.cs
rafa-dx/facturama-dotnet-sdk
2bbbe66157522f627e736937223471f3e8f3d2aa
[ "Apache-2.0" ]
8
2018-03-28T18:21:40.000Z
2022-03-29T16:39:32.000Z
using System; using System.Collections.Generic; using System.Text; namespace Facturama.Models.Retentions.Complementos.ServiciosPlataformasTecnologicas { public class ServiciosPlataformasTecnologicas { /// <summary> /// Nodo requerido para detallar la información de los servicios prestados por /// personas físicas que utilicen plataformas tecnológicas. /// </summary> public List<DetallesDelServicio> Servicios { get; set; } /// <summary> /// Atributo requerido para especificar el periodo de retención. /// </summary> public string Periodicidad { get; set; } /// <summary> /// Atributo requerido para expresar el número de servicios realizados en el periodo. /// </summary> public int NumServ { get; set; } /// <summary> /// Atributo requerido para expresar monto total de los servicios realizados en el periodo, sin incluir el monto del IVA. /// </summary> public decimal MontToServSIva { get; set; } /// <summary> /// Atributo requerido para expresar monto total del IVA trasladado por los servicios realizados en el periodo. /// </summary> public decimal TotalIvaTrasladado { get; set; } /// <summary> /// Atributo requerido para expresar monto total del IVA retenido por los servicios realizados en el periodo. /// </summary> public decimal TotalIvaRetenido { get; set; } /// <summary> /// Atributo requerido para expresar monto total del ISR retenido por los servicios realizados en el periodo. /// </summary> public decimal TotalIsrRetenido { get; set; } /// <summary> /// Atributo requerido para expresar la diferencia del IVA entregado al prestador del servicio en el periodo. /// </summary> public decimal DifIvaEntregadoPrestServ { get; set; } /// <summary> /// Atributo requerido para expresar el monto total cobrado al /// prestador del servicio por el uso de la plataforma en el periodo. /// </summary> public decimal MonTotalporUsoPlataforma { get; set; } /// <summary> /// Atributo condicional para expresar la suma de los atributos /// “ImpContrib“ del nodo hijo “ContribucionGubernamental” del /// periodo que corresponda. /// </summary> public decimal? MonTotalContribucionGubernamental { get; set; } } }
34.796875
123
0.719802
0d8eef72719464cb8e3367d00f9a4609ff74de98
3,770
dart
Dart
lib/model/forward_email_options.dart
ductranit/mailslurp-client-dart
2ea7c02c74b9898f4fff1fc9de9fbc289b0c2044
[ "MIT" ]
1
2021-06-22T05:43:18.000Z
2021-06-22T05:43:18.000Z
lib/model/forward_email_options.dart
ductranit/mailslurp-client-dart
2ea7c02c74b9898f4fff1fc9de9fbc289b0c2044
[ "MIT" ]
1
2022-03-31T16:43:50.000Z
2022-03-31T16:43:50.000Z
lib/model/forward_email_options.dart
ductranit/mailslurp-client-dart
2ea7c02c74b9898f4fff1fc9de9fbc289b0c2044
[ "MIT" ]
2
2021-11-15T10:19:17.000Z
2021-12-13T02:11:50.000Z
// // AUTO-GENERATED FILE, DO NOT MODIFY! // // @dart=2.0 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: lines_longer_than_80_chars part of openapi.api; class ForwardEmailOptions { /// Returns a new [ForwardEmailOptions] instance. ForwardEmailOptions({ this.bcc = const [], this.cc = const [], this.from, this.subject, this.to = const [], this.useInboxName, }); /// Optional bcc recipients List<String> bcc; /// Optional cc recipients List<String> cc; /// Optional from override String from; /// Subject for forwarded email String subject; /// To recipients for forwarded email List<String> to; /// Optionally use inbox name as display name for sender email address bool useInboxName; @override bool operator ==(Object other) => identical(this, other) || other is ForwardEmailOptions && other.bcc == bcc && other.cc == cc && other.from == from && other.subject == subject && other.to == to && other.useInboxName == useInboxName; @override int get hashCode => (bcc == null ? 0 : bcc.hashCode) + (cc == null ? 0 : cc.hashCode) + (from == null ? 0 : from.hashCode) + (subject == null ? 0 : subject.hashCode) + (to == null ? 0 : to.hashCode) + (useInboxName == null ? 0 : useInboxName.hashCode); @override String toString() => 'ForwardEmailOptions[bcc=$bcc, cc=$cc, from=$from, subject=$subject, to=$to, useInboxName=$useInboxName]'; Map<String, dynamic> toJson() { final json = <String, dynamic>{}; if (bcc != null) { json[r'bcc'] = bcc; } if (cc != null) { json[r'cc'] = cc; } if (from != null) { json[r'from'] = from; } if (subject != null) { json[r'subject'] = subject; } if (to != null) { json[r'to'] = to; } if (useInboxName != null) { json[r'useInboxName'] = useInboxName; } return json; } /// Returns a new [ForwardEmailOptions] instance and imports its values from /// [json] if it's non-null, null if [json] is null. static ForwardEmailOptions fromJson(Map<String, dynamic> json) => json == null ? null : ForwardEmailOptions( bcc: json[r'bcc'] == null ? null : (json[r'bcc'] as List).cast<String>(), cc: json[r'cc'] == null ? null : (json[r'cc'] as List).cast<String>(), from: json[r'from'], subject: json[r'subject'], to: json[r'to'] == null ? null : (json[r'to'] as List).cast<String>(), useInboxName: json[r'useInboxName'], ); static List<ForwardEmailOptions> listFromJson(List<dynamic> json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : <ForwardEmailOptions>[] : json.map((v) => ForwardEmailOptions.fromJson(v)).toList(growable: true == growable); static Map<String, ForwardEmailOptions> mapFromJson(Map<String, dynamic> json) { final map = <String, ForwardEmailOptions>{}; if (json != null && json.isNotEmpty) { json.forEach((String key, dynamic v) => map[key] = ForwardEmailOptions.fromJson(v)); } return map; } // maps a json object with a list of ForwardEmailOptions-objects as value to a dart map static Map<String, List<ForwardEmailOptions>> mapListFromJson(Map<String, dynamic> json, {bool emptyIsNull, bool growable,}) { final map = <String, List<ForwardEmailOptions>>{}; if (json != null && json.isNotEmpty) { json.forEach((String key, dynamic v) { map[key] = ForwardEmailOptions.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); }); } return map; } }
29.224806
129
0.61565
b04c4fa82b964be326bed724fb232deff833597a
4,207
py
Python
CST1101_WK07CL12_Functions_Examples_15-Mar-2021.py
ProfessorPatrickOnline/AlgorithmicProblemSolving
8ddc2480a5922dde37140e64d48058930a546901
[ "MIT" ]
2
2021-03-15T16:33:01.000Z
2021-03-24T19:31:30.000Z
CST1101_WK07CL12_Functions_Examples_15-Mar-2021.py
ProfessorPatrickOnline/AlgorithmicProblemSolving
8ddc2480a5922dde37140e64d48058930a546901
[ "MIT" ]
null
null
null
CST1101_WK07CL12_Functions_Examples_15-Mar-2021.py
ProfessorPatrickOnline/AlgorithmicProblemSolving
8ddc2480a5922dde37140e64d48058930a546901
[ "MIT" ]
9
2021-03-15T12:38:26.000Z
2021-03-15T16:45:26.000Z
# Topic - Functions: Examples and Exercises # CST1101-OLXX Spr-2021 WK07CL12 Review # by Professor Patrick PaSlattery@CityTech.CUNY.edu ### VOID FUNCTION print("Example of a void function for its side effects") # a simple function which prints whatever argument it receives def print_void(argument): """This void function prints the value passed in as an argument""" print ("Your value is:", argument) print_this = input("What content should we use as an argument to print_void()? > ") print_void(print_this) # the following statements are scaffolding to pause and wait for Enter print() wait = input("Hit Enter to continue > ") print() ### LOCAL VARIABLES print("Example of local and global variable") # a simple function which changes the value of a local variable def change_value(argument): """This function changes the local value passed in to 17""" print ("Inside (local) argument is:", argument) argument = 17 print ("Inside (local) argument is changed to:", argument) number = 42 print ("Outside (global) number is:", number) change_value(number) print ("Outside (global) number is still:", number) # the following statements are scaffolding to pause and wait for Enter print() wait = input("Hit Enter to continue > ") print() ### GLOBAL VARIABLES INSIDE A FUNCTION print("Example of using the global statement to access a global variable") # a simple function which uses global to change a variable outside of scope def change_number(): """This function changes the value passed in to 19 (global)""" global number number = 19 number = 55 print ("Outside (global) number is:", number) change_number() print ("Outside (global) number is now:", number) # the following statements are scaffolding to pause and wait for Enter print() wait = input("Hit Enter to continue > ") print() ### RETURN VALUES print("Example of returning a value(s)") # a simple function which returns the square of an argument def square(root): """This function calculates the square of the argument value""" result = root * root return result # a rationalizing the function which returns the square of an argument def square(root): """This function calculates the square of the argument value""" # result = num * num return root * root # calling the square() function from within a for loop for i in range(1,11): print(square(i)) # the following statements are scaffolding to pause and wait for Enter print() wait = input("Hit Enter to continue > ") print() ### DEFAULT ARGUMENTS #1 print("Example of setting a default value for an argument") # Using a default value for the argument in our earlier square() function def square(root = 1): """This function calculates the square of a the argument value""" return root * root # calling the square() function and allowing the default value for the argument print(square()) # the following statements are scaffolding to pause and wait for Enter print() wait = input("Hit Enter to continue > ") print() ### DEFAULT ARGUMENTS #2 print("Examples of using/not-using a default value for an argument") # Using a default value to count number of times to prompt the user def prompt_user(prompt, num_tries = 2): """This function prompts the user for 'yes' or 'no' a number of times""" answer = input(prompt) while (answer != "yes" and answer != "no" and num_tries > 1): num_tries = num_tries - 1 print ("Try again") answer = input(prompt) # Calling prompt_user() with or without the default value prompt_user("Enter yes or no: ") prompt_user("Enter yes or no: ", 4) # the following statements are scaffolding to pause and wait for Enter print() wait = input("Hit Enter to continue > ") print() ### KEYWORD ARGUMENTS print("Example of using keywords to assign values to arguments") # Calling prompt_user() with keyword arguments prompt_user(prompt="Hello ") prompt_user(num_tries=1, prompt="Hi ") # the following statements are scaffolding to pause and wait for Enter print() wait = input("Hit Enter to continue > ") print()
32.361538
84
0.701925
07ae384693730b527165e22ce7894ba6f139a538
1,593
rb
Ruby
lib/model_to_graphql/objects/belongs_to_union_type.rb
cannalogue/model_to_graphql
c4bb327c618bf97f98b09a3089362f9a4f5085c3
[ "MIT" ]
2
2019-02-13T16:46:52.000Z
2019-12-15T22:20:08.000Z
lib/model_to_graphql/objects/belongs_to_union_type.rb
cannalogue/model_to_graphql
c4bb327c618bf97f98b09a3089362f9a4f5085c3
[ "MIT" ]
1
2019-11-06T05:09:22.000Z
2019-11-06T05:09:22.000Z
lib/model_to_graphql/objects/belongs_to_union_type.rb
cannalogue/model_to_graphql
c4bb327c618bf97f98b09a3089362f9a4f5085c3
[ "MIT" ]
1
2019-09-13T15:19:37.000Z
2019-09-13T15:19:37.000Z
# frozen_string_literal: true module ModelToGraphql module Objects module BelongsToUnionType def self.[](relation) "#{self.name}::#{relation.name.capitalize}".constantize end def self.const_missing(name) return self.const_get(name) if self.self_const_defined?(name) relation_name = name.to_s.downcase.to_sym graphql_types = Mongoid.models.select do |m| m.relations.any? { |_, field| field.options[:as] == relation_name } end.map do |m| ModelToGraphql::Objects::Type[m] end type_name = "Possible#{relation_name.to_s.capitalize}Type" union_type = Class.new(GraphQL::Schema::Union) do graphql_name(type_name) possible_types(*graphql_types) def self.resolve_type(obj, _ctx) ModelToGraphql::Objects::Type[obj.class] rescue => _ fail "Couldn't find the return type of object #{obj} when its class it's #{obj.class}" end end self.const_set(name, union_type) end def self.self_const_defined?(name) if self.const_defined?(name) c = self.const_get(name) c.name.start_with?(self.name) else false end end def self.remove_all_constants self.constants.each do |c| self.send(:remove_const, c) end end end end end
32.510204
112
0.539234
e79c75fca9bac3f48b2c85fbef68f7112b16d791
14,833
dart
Dart
test/coap_message_api_test.dart
Sorunome/coap
22f6714c01a84f0c80d17415172921cc8be0bf66
[ "MIT" ]
10
2018-07-20T08:34:25.000Z
2021-12-24T17:43:28.000Z
test/coap_message_api_test.dart
Sorunome/coap
22f6714c01a84f0c80d17415172921cc8be0bf66
[ "MIT" ]
52
2018-03-20T14:39:18.000Z
2022-03-29T23:36:48.000Z
test/coap_message_api_test.dart
Sorunome/coap
22f6714c01a84f0c80d17415172921cc8be0bf66
[ "MIT" ]
8
2019-11-17T08:37:29.000Z
2022-03-25T04:37:38.000Z
/* * Package : Coap * Author : S. Hamblett <steve.hamblett@linux.com> * Date : 20/09/2019 * Copyright : S.Hamblett */ import 'package:coap/coap.dart'; import 'package:coap/config/coap_config_logging.dart'; import 'package:test/test.dart'; // Note that nnot all API methods are tested here, some are tested in other unit test suites, // some in dynamic testing. void main() { // ignore: unused_local_variable final DefaultCoapConfig conf = CoapConfigLogging(); test('Construction', () { final message = CoapMessage(); expect(message.type, CoapMessageType.unknown); expect(message.code, CoapCode.notSet); expect(message.id! >= 1, isTrue); expect(message.id! <= CoapMessage.initialIdLimit, isTrue); expect(message.resolveHost == 'localhost', isTrue); expect(message.optionMap.isEmpty, isTrue); expect(message.bindAddress, isNull); expect(message.token, isNull); expect(message.tokenString, isNull); expect(message.destination, isNull); expect(message.source, isNull); expect(message.isAcknowledged, isFalse); expect(message.acknowledgedHook, isNull); expect(message.isRejected, isFalse); expect(message.isTimedOut, isFalse); expect(message.timedOutHook, isNull); expect(message.retransmittingHook, isNull); expect(message.isCancelled, isFalse); expect(message.duplicate, isFalse); expect(message.timestamp, isNull); expect(message.maxRetransmit, 0); expect(message.ackTimeout, 0); expect(message.payload, isNull); expect(message.payloadSize, 0); expect(message.payloadString, isNull); }); test('Options', () { final message = CoapMessage(); final opt1 = CoapOption(optionTypeUriHost); final opt2 = CoapOption(optionTypeReserved); final options = <CoapOption>[opt1, opt2]; message.addOptions(options); expect(message.optionMap.length, 2); expect(message.getOptions(optionTypeUriHost)!.length, 1); expect(message.getOptions(optionTypeReserved)!.length, 1); message.setOption(opt1); message.setOption(opt2); expect(message.optionMap.length, 2); expect(message.getOptions(optionTypeUriHost)!.length, 1); expect(message.getOptions(optionTypeReserved)!.length, 1); message.setOptions(options); expect(message.optionMap.length, 2); expect(message.getOptions(optionTypeUriHost)!.length, 1); expect(message.getOptions(optionTypeReserved)!.length, 1); expect( message.getFirstOption(optionTypeReserved)!.type, optionTypeReserved); expect(message.getFirstOption(optionTypeUriHost)!.type, optionTypeUriHost); expect(message.getFirstOption(optionTypeUriPort), isNull); expect(message.hasOption(optionTypeUriHost), isTrue); expect(message.hasOption(optionTypeUriPort), isFalse); message.removeOptions(optionTypeUriHost); expect(message.optionMap.length, 1); expect(message.getOptions(optionTypeUriHost), isNull); expect(message.getOptions(optionTypeReserved)!.length, 1); message.removeOptions(optionTypeReserved); expect(message.optionMap.length, 0); expect(message.getOptions(optionTypeUriHost), isNull); expect(message.getOptions(optionTypeReserved), isNull); message.addOptions(options); expect(message.optionMap.length, 2); final opt3 = CoapOption(optionTypeUriHost); message.addOption(opt3); expect(message.optionMap.length, 2); expect(message.getOptions(optionTypeUriHost)!.length, 2); final ret = message.removeOption(opt1); expect(ret, isTrue); expect(message.getOptions(optionTypeUriHost)!.length, 1); expect(message.getOptions(optionTypeUriHost)!.toList()[0] == opt3, isTrue); message.clearOptions(); expect(message.optionMap.length, 0); }); test('Message codes', () { final message = CoapMessage(); expect(message.isRequest, isFalse); expect(message.isResponse, isFalse); expect(message.isEmpty, isFalse); expect(message.isValid, isFalse); expect(message.codeString, 'Not Set'); }); test('Acknowledged', () { var acked = false; void ackHook() { acked = true; } final message = CoapMessage(); message.isAcknowledged = true; expect(message.isAcknowledged, isTrue); expect(acked, isFalse); final eventBus = CoapEventBus(); expect(eventBus.lastEvent is CoapAcknowledgedEvent, isTrue); eventBus.lastEvent = null; message.acknowledgedHook = ackHook; message.isAcknowledged = false; expect(message.isAcknowledged, isFalse); expect(acked, isTrue); expect(eventBus.lastEvent, isNull); }); test('Rejected', () { final message = CoapMessage(); message.isRejected = true; expect(message.isRejected, isTrue); final eventBus = CoapEventBus(); expect(eventBus.lastEvent is CoapRejectedEvent, isTrue); }); test('Timed out', () { var timedOut = false; void toHook() { timedOut = true; } final message = CoapMessage(); message.isTimedOut = true; expect(message.isTimedOut, isTrue); expect(timedOut, isFalse); final eventBus = CoapEventBus(); expect(eventBus.lastEvent is CoapTimedOutEvent, isTrue); eventBus.lastEvent = null; message.timedOutHook = toHook; message.isTimedOut = false; expect(message.isTimedOut, isFalse); expect(timedOut, isTrue); expect(eventBus.lastEvent, isNull); }); test('Retransmitting', () { final message = CoapMessage(); var retrans = false; void retransHook() { retrans = true; } message.fireRetransmitting(); expect(retrans, isFalse); message.retransmittingHook = retransHook; message.fireRetransmitting(); expect(retrans, isTrue); }); test('Cancelled', () { final message = CoapMessage(); message.isCancelled = true; expect(message.isCancelled, isTrue); final eventBus = CoapEventBus(); expect(eventBus.lastEvent is CoapCancelledEvent, isTrue); message.isCancelled = false; message.cancel(); expect(message.isCancelled, isTrue); }); test('Payload', () { final message = CoapMessage(); message.setPayload('This is the payload'); expect(message.payload, isNotNull); expect(message.payloadString, 'This is the payload'); expect(message.payloadSize, 19); }); test('If match', () { final message = CoapMessage(); expect(message.ifMatches.length, 0); message.addIfMatch('ETag-1').addIfMatch('ETag-2'); expect(message.ifMatches.length, 2); expect(message.ifMatches.toList()[0].stringValue, 'ETag-1'); expect(message.ifMatches.toList()[1].stringValue, 'ETag-2'); message.removeIfMatchOpaque(message.ifMatches.toList()[0].valueBytes); expect(message.ifMatches.length, 1); expect(message.ifMatches.toList()[0].stringValue, 'ETag-2'); message.clearIfMatches(); expect(message.ifMatches.length, 0); final opt1 = CoapOption(optionTypeUriHost); expect(() => message.removeIfMatch(opt1), throwsArgumentError); final opt2 = CoapOption(optionTypeIfMatch); opt2.stringValue = 'ETag-3'; message.addOption(opt2); expect(message.ifMatches.length, 1); message.removeIfMatch(opt2); expect(message.ifMatches.length, 0); }); test('ETags', () { final message = CoapMessage(); expect(message.etags.length, 0); final none = CoapOption(optionTypeIfMatch); final etag1 = CoapOption(optionTypeETag); etag1.stringValue = 'Etag-1'; final etag2 = CoapOption(optionTypeETag); etag2.stringValue = 'Etag-2'; expect(() => message.addEtag(none), throwsArgumentError); message.addEtag(etag1); expect(message.etags.length, 1); message.addETagOpaque(etag2.valueBytes); expect(message.etags.length, 2); message.removeETagOpaque(etag2.valueBytes); expect(message.etags.length, 1); expect(message.etags.toList()[0] == etag1, isTrue); message.clearETags(); expect(message.etags.length, 0); message.addEtag(etag1); expect(message.etags.length, 1); expect(() => message.removeEtag(none), throwsArgumentError); final ret = message.removeEtag(etag1); expect(ret, isTrue); expect(message.etags.length, 0); }); test('If None match', () { final message = CoapMessage(); expect(message.ifNoneMatches.length, 0); final none = CoapOption(optionTypeIfMatch); final inm1 = CoapOption(optionTypeIfNoneMatch); inm1.stringValue = 'Inm1'; final inm2 = CoapOption(optionTypeIfNoneMatch); inm2.stringValue = 'Inm2'; message.addIfNoneMatch(inm1).addIfNoneMatch(inm2); expect(message.ifNoneMatches.length, 2); expect(() => message.addIfNoneMatch(none), throwsArgumentError); final inm3 = CoapOption(optionTypeIfNoneMatch); inm3.stringValue = 'Inm3'; message.addIfNoneMatchOpaque(inm3.valueBytes); expect(message.ifNoneMatches.length, 3); message.removeIfNoneMatchOpaque(inm2.valueBytes); expect(message.ifNoneMatches.length, 2); expect(() => message.removeIfNoneMatch(none), throwsArgumentError); message.clearIfNoneMatches(); expect(message.ifNoneMatches.length, 0); }); test('Uri path', () { final message = CoapMessage(); expect(message.uriPaths.length, 0); message.uriPath = 'a/uri/path/'; expect(message.uriPaths.length, 3); expect(message.uriPathsString, 'a/uri/path'); message.addUriPath('longer'); expect(message.uriPaths.length, 4); expect(message.uriPathsString, 'a/uri/path/longer'); expect(() => message.addUriPath(null), throwsArgumentError); const tolong = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn' 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn'; expect(() => message.addUriPath(tolong), throwsArgumentError); message.removeUriPath('path'); expect(message.uriPaths.length, 3); expect(message.uriPathsString, 'a/uri/longer'); message.clearUriPath(); expect(message.uriPaths.length, 0); expect(message.uriPathsString.isEmpty, isTrue); }); test('Uri query', () { final message = CoapMessage(); expect(message.uriQueries.length, 0); message.uriQuery = 'a&uri=1&query=2'; expect(message.uriQueries.length, 3); expect(message.uriQueriesString, '?a&uri=1&query=2'); message.addUriQuery('longer=3'); expect(message.uriQueries.length, 4); expect(message.uriQueriesString, '?a&uri=1&query=2&longer=3'); expect(() => message.addUriQuery(null), throwsArgumentError); const tolong = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn' 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn'; expect(() => message.addUriQuery(tolong), throwsArgumentError); message.removeUriQuery('query=2'); expect(message.uriQueries.length, 3); expect(message.uriQueriesString, '?a&uri=1&longer=3'); message.clearUriQuery(); expect(message.uriQueries.length, 0); }); test('Location path', () { final message = CoapMessage(); expect(message.locationPaths.length, 0); message.locationPath = 'a/location/path/'; expect(message.locationPaths.length, 3); expect(message.locationPathsString, 'a/location/path'); expect(() => message.locationPath = '..', throwsArgumentError); expect(() => message.locationPath = '.', throwsArgumentError); message.addLocationPath('longer'); expect(message.locationPaths.length, 4); expect(message.locationPathsString, 'a/location/path/longer'); expect(() => message.addLocationPath(null), throwsArgumentError); const tolong = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn' 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn'; expect(() => message.addLocationPath(tolong), throwsArgumentError); message.removelocationPath('path'); expect(message.locationPaths.length, 3); expect(message.locationPathsString, 'a/location/longer'); message.clearLocationPath(); expect(message.locationPaths.length, 0); expect(message.locationPathsString.isEmpty, isTrue); }); test('Location query', () { final message = CoapMessage(); expect(message.locationQueries.length, 0); message.locationQuery = 'a&uri=1&query=2'; expect(message.locationQueries.length, 3); expect(message.locationQueriesString, '?a&uri=1&query=2'); message.addLocationQuery('longer=3'); expect(message.locationQueries.length, 4); expect(message.locationQueriesString, '?a&uri=1&query=2&longer=3'); expect(() => message.addLocationQuery(null), throwsArgumentError); const tolong = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn' 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn'; expect(() => message.addLocationQuery(tolong), throwsArgumentError); message.removeLocationQuery('query=2'); expect(message.locationQueries.length, 3); expect(message.locationQueriesString, '?a&uri=1&longer=3'); message.clearLocationQuery(); expect(message.locationQueries.length, 0); }); }
42.994203
210
0.739702
b4f2521454922bba2736fc5bceeae982fdf71732
409
sql
SQL
openGaussBase/testcase/KEYWORDS/found/Opengauss_Function_Keyword_Found_Case0019.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/found/Opengauss_Function_Keyword_Found_Case0019.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/found/Opengauss_Function_Keyword_Found_Case0019.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
-- @testpoint:opengauss关键字found(非保留),作为外部数据源名 --关键字不带引号-成功 drop data source if exists found; create data source found; drop data source found; --关键字带双引号-成功 drop data source if exists "found"; create data source "found"; drop data source "found"; --关键字带单引号-合理报错 drop data source if exists 'found'; create data source 'found'; --关键字带反引号-合理报错 drop data source if exists `found`; create data source `found`;
20.45
46
0.750611
ae761dd4e187ac5e0503c709d656eb3d6d49c171
375
cs
C#
Assets/Game/Scripts/CreationHelper.cs
khanhdrag9/FallGuyClone
6d0c2aa805eca66580a4cc9eef3d343f4ad93463
[ "MIT" ]
null
null
null
Assets/Game/Scripts/CreationHelper.cs
khanhdrag9/FallGuyClone
6d0c2aa805eca66580a4cc9eef3d343f4ad93463
[ "MIT" ]
null
null
null
Assets/Game/Scripts/CreationHelper.cs
khanhdrag9/FallGuyClone
6d0c2aa805eca66580a4cc9eef3d343f4ad93463
[ "MIT" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class CreationHelper { public static void SetLayer(Transform source, int layer, bool excluseParent) { if(!excluseParent) source.gameObject.layer = layer; foreach (Transform trans in source) trans.gameObject.layer = layer; } }
23.4375
80
0.685333
e221440688c47b0def7b5153c35b1c8584777076
2,743
py
Python
lessons/payments/clients/paypal.py
anuroop18/django-lessons-proj
756582c31287582c211004d5b4e86fd570fed1f9
[ "Apache-2.0" ]
null
null
null
lessons/payments/clients/paypal.py
anuroop18/django-lessons-proj
756582c31287582c211004d5b4e86fd570fed1f9
[ "Apache-2.0" ]
null
null
null
lessons/payments/clients/paypal.py
anuroop18/django-lessons-proj
756582c31287582c211004d5b4e86fd570fed1f9
[ "Apache-2.0" ]
2
2021-08-24T23:42:46.000Z
2022-01-14T14:03:45.000Z
import os import paypalrestsdk import yaml from django.conf import settings from lessons.payments import plans BASE_DIR = os.path.join( "..", # proj "..", # land os.path.dirname(__file__) # commands ) ORDER_A_CONF_PATH = os.path.join("paypal", "order-annual.yml") ORDER_M_CONF_PATH = os.path.join("paypal", "order-monthly.yml") class BaseClient: """ A thin wrapper over Paypal SDK. For unit tests will be replaced with own test client. """ def __init__(self, mode): self._mode = mode self._api = None @property def api_key(self): return self._api_key def create_subscription(self, lesson_plan): pass def get_subscription(self, billing_agreement_id): pass def get_url(self, url): pass def create_onetime_order(self, lesson_plan): pass class RealClient(BaseClient): def __init__(self, mode): self._mode = mode self._api = paypalrestsdk.Api({ "mode": mode, # noqa "client_id": settings.PAYPAL_CLIENT_ID, "client_secret": settings.PAYPAL_CLIENT_SECRET }) def create_subscription(self, lesson_plan): data = { 'plan_id': lesson_plan.paypal_plan_id, } return self._api.post( "v1/billing/subscriptions", data ) def get_subscription(self, billing_agreement_id): return self._api.get( f"v1/billing/subscriptions/{billing_agreement_id}" ) def get_url(self, url): return self._api.get( url ) def get_order(self, lesson_plan): data = None if isinstance(lesson_plan.plan, plans.LessonsAnnualPlan): order_path = ORDER_A_CONF_PATH elif isinstance(lesson_plan.plan, plans.LessonsMonthPlan): order_path = ORDER_M_CONF_PATH else: raise ValueError("Unexpected lesson plan instance") with open(order_path, "r") as f: data = yaml.safe_load(f) return data def create_onetime_order(self, lesson_plan): order_dict = self.get_order(lesson_plan) return self._api.post( "v2/checkout/orders", order_dict ) class FakeClient(BaseClient): def __init__(self, mode): pass def create_subscription(self, lesson_plan): return { 'id': 'fake_id' } def _mode(): if settings.DEBUG: return "sandbox" return "live" def get_paypal_client(): if hasattr(settings, 'TEST') and settings.TEST is True: return FakeClient(mode='blah') return RealClient( mode=_mode() ) paypal_client = get_paypal_client()
22.120968
66
0.610645
2fd7ccb0edcef982c78529cb3f2b6240607ff221
4,018
py
Python
test/TestHttpdConf.py
bigio/mod_md
5e34c14e2b7ad195f662290c26481cbc3a249fe0
[ "Apache-2.0" ]
null
null
null
test/TestHttpdConf.py
bigio/mod_md
5e34c14e2b7ad195f662290c26481cbc3a249fe0
[ "Apache-2.0" ]
null
null
null
test/TestHttpdConf.py
bigio/mod_md
5e34c14e2b7ad195f662290c26481cbc3a249fe0
[ "Apache-2.0" ]
null
null
null
################################################################################################### # httpd test configuration generator # # (c) 2019 greenbytes GmbH ################################################################################################### import os from shutil import copyfile from TestEnv import TestEnv class HttpdConf(object): # Utility class for creating Apache httpd test configurations def __init__(self, name="test.conf", local_ca=True, text=None, std_vhosts=True, proxy=False): self.path = os.path.join(TestEnv.GEN_DIR, name) if os.path.isfile(self.path): os.remove(self.path) if not text: text = """ LogLevel md:trace2 LogLevel ssl:debug """ if local_ca: text = """ MDCertificateAuthority %s MDCertificateAgreement accepted MDCACertificateFile %s/test-ca.pem %s """ % (TestEnv.ACME_URL, TestEnv.WEBROOT, text) if std_vhosts: text = """ Listen %s Listen %s MDPortMap 80:%s 443:%s include "conf/std_vhosts.conf" %s """ % (TestEnv.HTTP_PORT, TestEnv.HTTPS_PORT, TestEnv.HTTP_PORT, TestEnv.HTTPS_PORT, text) if proxy: text = """ include "conf/proxy.conf" %s """ % text open(self.path, "a").write(text) def clear(self): if os.path.isfile(self.path): os.remove(self.path) def _add_line(self, line): open(self.path, "a").write(line + "\n") def add_line(self, line): self._add_line(line) def add_drive_mode(self, mode): self._add_line(" MDRenewMode %s\n" % mode) def add_renew_window(self, window): self._add_line(" MDRenewWindow %s\n" % window) def add_private_key(self, key_type, key_params): self._add_line(" MDPrivateKeys %s %s\n" % (key_type, " ".join(map(lambda p: str(p), key_params)))) def add_admin(self, email): self._add_line(" ServerAdmin mailto:%s\n\n" % email) def add_md(self, domains): self._add_line(" MDomain %s\n\n" % " ".join(domains)) def start_md(self, domains): self._add_line(" <MDomain %s>\n" % " ".join(domains)) def start_md2(self, domains): self._add_line(" <MDomainSet %s>\n" % " ".join(domains)) def end_md(self): self._add_line(" </MDomain>\n") def end_md2(self): self._add_line(" </MDomainSet>\n") def add_must_staple(self, mode): self._add_line(" MDMustStaple %s\n" % mode) def add_ca_challenges(self, type_list): self._add_line(" MDCAChallenges %s\n" % " ".join(type_list)) def add_http_proxy(self, url): self._add_line(" MDHttpProxy %s\n" % url) def add_require_ssl(self, mode): self._add_line(" MDRequireHttps %s\n" % mode) def add_notify_cmd(self, cmd): self._add_line(" MDNotifyCmd %s\n" % cmd) def add_message_cmd(self, cmd): self._add_line(" MDMessageCmd %s\n" % cmd) def add_dns01_cmd(self, cmd): self._add_line(" MDChallengeDns01 %s\n" % cmd) def add_vhost(self, domains, port=None, doc_root="htdocs"): self.start_vhost(domains, port=port, doc_root=doc_root) self.end_vhost() def start_vhost(self, domains, port=None, doc_root="htdocs"): if not isinstance(domains, list): domains = [domains] if not port: port = TestEnv.HTTPS_PORT f = open(self.path, "a") f.write("<VirtualHost *:%s>\n" % port) f.write(" ServerName %s\n" % domains[0]) for alias in domains[1:]: f.write(" ServerAlias %s\n" % alias) f.write(" DocumentRoot %s\n\n" % doc_root) if TestEnv.HTTPS_PORT == port: f.write(" SSLEngine on\n") def end_vhost(self): self._add_line("</VirtualHost>\n\n") def install(self): copyfile(self.path, TestEnv.APACHE_TEST_CONF)
29.328467
107
0.559731
8e67e0b8e40bb05f74bec025f806a196b0c1fdac
30,116
js
JavaScript
src/languages/igorpro.js
GerHobbelt/highlight.js
61cf73430b1db8ca42226851bcd3290f5a8cf967
[ "BSD-3-Clause" ]
null
null
null
src/languages/igorpro.js
GerHobbelt/highlight.js
61cf73430b1db8ca42226851bcd3290f5a8cf967
[ "BSD-3-Clause" ]
null
null
null
src/languages/igorpro.js
GerHobbelt/highlight.js
61cf73430b1db8ca42226851bcd3290f5a8cf967
[ "BSD-3-Clause" ]
null
null
null
/* * Language: Igor Pro * Author: Adam Light <adam@wavemetrics.com>, * Thomas Braun <thomas.braun@byte-physics.de> * Contributors: * Category: scientific * Description: Programming language used by Igor Pro (www.igorpro.net) */ export default function(hljs) { var WAVE_DECLARATION = { className: 'keyword', relevance: 10, begin: '^\\s*Wave\\b' }; var PRE_PROCESSOR = { className: 'meta', begin: '^#[a-z]+' }; var IGOR_KEYWORDS = { /* Igor Keywords */ keyword: 'window while waveclear variable|10 uint64 try threadsafe switch svar ' + 'submenu structure struct strswitch string strconstant static return prompt prompt ' + 'proc picture override nvar multithread menu macro int64 int if ' + 'function funcref for endtry endswitch endstructure endmacro endif endfor end ' + 'elseif else double doprompt do dfref default continue constant complex ' + 'catch case break abortonvalue abortonrte', /* Igor Operations */ built_in: 'AddListItem AiryA AiryAD AiryB AiryBD AnnotationInfo AnnotationList AxisInfo' + 'AxisList AxisList AxisValFromPixel AxonTelegraphAGetDataNum' + 'AxonTelegraphAGetDataString AxonTelegraphAGetDataString' + 'AxonTelegraphAGetDataStruct AxonTelegraphAGetDataStruct AxonTelegraphGetDataNum' + 'AxonTelegraphGetDataString AxonTelegraphGetDataString' + 'AxonTelegraphGetDataStruct AxonTelegraphGetDataStruct AxonTelegraphGetTimeoutMs' + 'AxonTelegraphSetTimeoutMs AxonTelegraphSetTimeoutMs Besseli Besselj Besselk' + 'Bessely Bessely BinarySearch BinarySearchInterp CTabList CaptureHistory' + 'CaptureHistoryStart CaptureHistoryStart CheckName ChildWindowList CleanupName' + 'ContourInfo ContourInfo ContourNameList ContourNameToWaveRef ContourZ' + 'ControlNameList ControlNameList ConvertTextEncoding CountObjects' + 'CountObjectsDFR CountObjectsDFR CreationDate CsrInfo CsrWave CsrWaveRef' + 'CsrXWave CsrXWave CsrXWaveRef DataFolderDir DataFolderExists' + 'DataFolderRefStatus DataFolderRefStatus DataFolderRefsEqual DateToJulian Dawson' + 'DimDelta DimDelta DimOffset DimSize ExpConvExp ExpConvExpFit' + 'ExpConvExpFit1Shape ExpConvExpFit1Shape ExpConvExpFit1ShapeBL ExpConvExpFitBL' + 'ExpGauss ExpGauss ExpGaussFit ExpGaussFit1Shape ExpGaussFit1ShapeBL' + 'ExpGaussFitBL ExpGaussFitBL FetchURL FindDimLabel FindListItem FontList' + 'FontSizeHeight FontSizeHeight FontSizeStringWidth FresnelCos FresnelSin' + 'FuncRefInfo FuncRefInfo FunctionInfo FunctionList FunctionPath' + 'GISGetAllFileFormats GISGetAllFileFormats GISIgorGISVersion GISSRefsAreEqual' + 'Gauss Gauss Gauss1D Gauss2D GaussFit GaussFit1Width GaussFit1WidthBL GaussFitBL' + 'GetBrowserLine GetBrowserLine GetBrowserSelection GetDataFolder' + 'GetDataFolderDFR GetDataFolderDFR GetDefaultFont GetDefaultFontSize' + 'GetDefaultFontStyle GetDefaultFontStyle GetDimLabel GetEnvironmentVariable' + 'GetErrMessage GetErrMessage GetFormula GetIndependentModuleName' + 'GetIndexedObjName GetIndexedObjName GetIndexedObjNameDFR GetKeyState' + 'GetRTErrMessage GetRTErrMessage GetRTError GetRTLocInfo GetRTLocation' + 'GetRTStackInfo GetRTStackInfo GetScrapText GetUserData GetWavesDataFolder' + 'GetWavesDataFolderDFR GetWavesDataFolderDFR GizmoInfo GizmoScale GrepList' + 'GrepString GrepString GuideInfo GuideNameList HDF5AttributeInfo HDF5DatasetInfo' + 'HDF5LibraryInfo HDF5LibraryInfo HDF5TypeInfo Hash HyperG0F1 HyperG1F1 HyperG2F1' + 'HyperGNoise HyperGNoise HyperGPFQ IgorInfo IgorVersion ImageInfo ImageNameList' + 'ImageNameToWaveRef ImageNameToWaveRef IndependentModuleList IndexToScale' + 'IndexedDir IndexedDir IndexedFile Inf Integrate1D Interp2D Interp3D ItemsInList' + 'JacobiCn JacobiCn JacobiSn JulianToDate Laguerre LaguerreA LaguerreGauss' + 'LambertW LambertW LayoutInfo LegendreA ListMatch ListToTextWave' + 'ListToWaveRefWave ListToWaveRefWave LorentzianFit LorentzianFit1Width' + 'LorentzianFit1WidthBL LorentzianFit1WidthBL LorentzianFitBL LowerStr' + 'MCC_AutoBridgeBal MCC_AutoBridgeBal MCC_AutoFastComp MCC_AutoPipetteOffset' + 'MCC_AutoSlowComp MCC_AutoSlowComp MCC_AutoWholeCellComp MCC_GetBridgeBalEnable' + 'MCC_GetBridgeBalResist MCC_GetBridgeBalResist MCC_GetFastCompCap' + 'MCC_GetFastCompTau MCC_GetFastCompTau MCC_GetHolding MCC_GetHoldingEnable' + 'MCC_GetMode MCC_GetMode MCC_GetNeutralizationCap MCC_GetNeutralizationEnable' + 'MCC_GetOscKillerEnable MCC_GetOscKillerEnable MCC_GetPipetteOffset' + 'MCC_GetPrimarySignalGain MCC_GetPrimarySignalGain MCC_GetPrimarySignalHPF' + 'MCC_GetPrimarySignalLPF MCC_GetPrimarySignalLPF MCC_GetRsCompBandwidth' + 'MCC_GetRsCompCorrection MCC_GetRsCompCorrection MCC_GetRsCompEnable' + 'MCC_GetRsCompPrediction MCC_GetRsCompPrediction MCC_GetSecondarySignalGain' + 'MCC_GetSecondarySignalLPF MCC_GetSecondarySignalLPF MCC_GetSlowCompCap' + 'MCC_GetSlowCompTau MCC_GetSlowCompTau MCC_GetSlowCompTauX20Enable' + 'MCC_GetSlowCurrentInjEnable MCC_GetSlowCurrentInjEnable' + 'MCC_GetSlowCurrentInjLevel MCC_GetSlowCurrentInjLevel' + 'MCC_GetSlowCurrentInjSetlTime MCC_GetSlowCurrentInjSetlTime' + 'MCC_GetWholeCellCompCap MCC_GetWholeCellCompCap MCC_GetWholeCellCompEnable' + 'MCC_GetWholeCellCompResist MCC_GetWholeCellCompResist MCC_SelectMultiClamp700B' + 'MCC_SetBridgeBalEnable MCC_SetBridgeBalEnable MCC_SetBridgeBalResist' + 'MCC_SetFastCompCap MCC_SetFastCompCap MCC_SetFastCompTau MCC_SetHolding' + 'MCC_SetHoldingEnable MCC_SetHoldingEnable MCC_SetMode MCC_SetNeutralizationCap' + 'MCC_SetNeutralizationEnable MCC_SetNeutralizationEnable MCC_SetOscKillerEnable' + 'MCC_SetPipetteOffset MCC_SetPipetteOffset MCC_SetPrimarySignalGain' + 'MCC_SetPrimarySignalHPF MCC_SetPrimarySignalHPF MCC_SetPrimarySignalLPF' + 'MCC_SetRsCompBandwidth MCC_SetRsCompBandwidth MCC_SetRsCompCorrection' + 'MCC_SetRsCompEnable MCC_SetRsCompEnable MCC_SetRsCompPrediction' + 'MCC_SetSecondarySignalGain MCC_SetSecondarySignalGain MCC_SetSecondarySignalLPF' + 'MCC_SetSlowCompCap MCC_SetSlowCompCap MCC_SetSlowCompTau' + 'MCC_SetSlowCompTauX20Enable MCC_SetSlowCompTauX20Enable' + 'MCC_SetSlowCurrentInjEnable MCC_SetSlowCurrentInjEnable' + 'MCC_SetSlowCurrentInjLevel MCC_SetSlowCurrentInjLevel' + 'MCC_SetSlowCurrentInjSetlTime MCC_SetSlowCurrentInjSetlTime MCC_SetTimeoutMs' + 'MCC_SetWholeCellCompCap MCC_SetWholeCellCompCap MCC_SetWholeCellCompEnable' + 'MCC_SetWholeCellCompResist MCC_SetWholeCellCompResist MPFXEMGPeak' + 'MPFXExpConvExpPeak MPFXExpConvExpPeak MPFXGaussPeak MPFXLorenzianPeak' + 'MPFXVoigtPeak MPFXVoigtPeak MacroList MandelbrotPoint MarcumQ MatrixCondition' + 'MatrixDet MatrixDet MatrixDot MatrixRank MatrixTrace ModDate NVAR_Exists NaN' + 'NameOfWave NameOfWave NewFreeDataFolder NewFreeWave NormalizeUnicode' + 'NumVarOrDefault NumVarOrDefault NumberByKey OperationList PICTInfo PICTList' + 'PadString PadString PanelResolution ParamIsDefault ParseFilePath PathList Pi' + 'PixelFromAxisVal PixelFromAxisVal PolygonArea PossiblyQuoteName ProcedureText' + 'RemoveByKey RemoveByKey RemoveEnding RemoveFromList RemoveListItem' + 'ReplaceNumberByKey ReplaceNumberByKey ReplaceString ReplaceStringByKey' + 'SQL2DBinaryWaveToTextWave SQL2DBinaryWaveToTextWave SQLAllocHandle SQLAllocStmt' + 'SQLBinaryWavesToTextWave SQLBinaryWavesToTextWave SQLBindCol SQLBindParameter' + 'SQLBrowseConnect SQLBrowseConnect SQLBulkOperations SQLCancel SQLCloseCursor' + 'SQLColAttributeNum SQLColAttributeNum SQLColAttributeStr SQLColumnPrivileges' + 'SQLColumns SQLColumns SQLConnect SQLDataSources SQLDescribeCol SQLDescribeParam' + 'SQLDisconnect SQLDisconnect SQLDriverConnect SQLDrivers SQLEndTran SQLError' + 'SQLExecDirect SQLExecDirect SQLExecute SQLFetch SQLFetchScroll SQLForeignKeys' + 'SQLFreeConnect SQLFreeConnect SQLFreeEnv SQLFreeHandle SQLFreeStmt' + 'SQLGetConnectAttrNum SQLGetConnectAttrNum SQLGetConnectAttrStr SQLGetCursorName' + 'SQLGetDataNum SQLGetDataNum SQLGetDataStr SQLGetDescFieldNum SQLGetDescFieldStr' + 'SQLGetDescRec SQLGetDescRec SQLGetDiagFieldNum SQLGetDiagFieldStr SQLGetDiagRec' + 'SQLGetEnvAttrNum SQLGetEnvAttrNum SQLGetEnvAttrStr SQLGetFunctions' + 'SQLGetInfoNum SQLGetInfoNum SQLGetInfoStr SQLGetStmtAttrNum SQLGetStmtAttrStr' + 'SQLGetTypeInfo SQLGetTypeInfo SQLMoreResults SQLNativeSql SQLNumParams' + 'SQLNumResultCols SQLNumResultCols SQLNumResultRowsIfKnown SQLNumRowsFetched' + 'SQLParamData SQLParamData SQLPrepare SQLPrimaryKeys SQLProcedureColumns' + 'SQLProcedures SQLProcedures SQLPutData SQLReinitialize SQLRowCount' + 'SQLSetConnectAttrNum SQLSetConnectAttrNum SQLSetConnectAttrStr SQLSetCursorName' + 'SQLSetDescFieldNum SQLSetDescFieldNum SQLSetDescFieldStr SQLSetDescRec' + 'SQLSetEnvAttrNum SQLSetEnvAttrNum SQLSetEnvAttrStr SQLSetPos SQLSetStmtAttrNum' + 'SQLSetStmtAttrStr SQLSetStmtAttrStr SQLSpecialColumns SQLStatistics' + 'SQLTablePrivileges SQLTablePrivileges SQLTables SQLTextWaveTo2DBinaryWave' + 'SQLTextWaveToBinaryWaves SQLTextWaveToBinaryWaves SQLUpdateBoundValues' + 'SQLXOPCheckState SQLXOPCheckState SVAR_Exists ScreenResolution Secs2Date' + 'Secs2Time Secs2Time SelectNumber SelectString SetEnvironmentVariable SortList' + 'SpecialCharacterInfo SpecialCharacterInfo SpecialCharacterList SpecialDirPath' + 'SphericalBessJ SphericalBessJ SphericalBessJD SphericalBessY SphericalBessYD' + 'SphericalHarmonics SphericalHarmonics StartMSTimer StatsBetaCDF StatsBetaPDF' + 'StatsBinomialCDF StatsBinomialCDF StatsBinomialPDF StatsCMSSDCDF StatsCauchyCDF' + 'StatsCauchyPDF StatsCauchyPDF StatsChiCDF StatsChiPDF StatsCorrelation' + 'StatsDExpCDF StatsDExpCDF StatsDExpPDF StatsEValueCDF StatsEValuePDF' + 'StatsErlangCDF StatsErlangCDF StatsErlangPDF StatsErrorPDF StatsExpCDF' + 'StatsExpPDF StatsExpPDF StatsFCDF StatsFPDF StatsFriedmanCDF StatsGEVCDF' + 'StatsGEVPDF StatsGEVPDF StatsGammaCDF StatsGammaPDF StatsGeometricCDF' + 'StatsGeometricPDF StatsGeometricPDF StatsHyperGCDF StatsHyperGPDF' + 'StatsInvBetaCDF StatsInvBetaCDF StatsInvBinomialCDF StatsInvCMSSDCDF' + 'StatsInvCauchyCDF StatsInvCauchyCDF StatsInvChiCDF StatsInvDExpCDF' + 'StatsInvEValueCDF StatsInvEValueCDF StatsInvExpCDF StatsInvFCDF' + 'StatsInvFriedmanCDF StatsInvFriedmanCDF StatsInvGammaCDF StatsInvGeometricCDF' + 'StatsInvKuiperCDF StatsInvKuiperCDF StatsInvLogNormalCDF StatsInvLogisticCDF' + 'StatsInvMaxwellCDF StatsInvMaxwellCDF StatsInvMooreCDF StatsInvNBinomialCDF' + 'StatsInvNCChiCDF StatsInvNCChiCDF StatsInvNCFCDF StatsInvNormalCDF' + 'StatsInvParetoCDF StatsInvParetoCDF StatsInvPoissonCDF StatsInvPowerCDF' + 'StatsInvQCDF StatsInvQCDF StatsInvQpCDF StatsInvRayleighCDF' + 'StatsInvRectangularCDF StatsInvRectangularCDF StatsInvSpearmanCDF' + 'StatsInvStudentCDF StatsInvStudentCDF StatsInvTopDownCDF StatsInvTriangularCDF' + 'StatsInvUsquaredCDF StatsInvUsquaredCDF StatsInvVonMisesCDF StatsInvWeibullCDF' + 'StatsKuiperCDF StatsKuiperCDF StatsLogNormalCDF StatsLogNormalPDF' + 'StatsLogisticCDF StatsLogisticCDF StatsLogisticPDF StatsMaxwellCDF' + 'StatsMaxwellPDF StatsMaxwellPDF StatsMedian StatsMooreCDF StatsNBinomialCDF' + 'StatsNBinomialPDF StatsNBinomialPDF StatsNCChiCDF StatsNCChiPDF StatsNCFCDF' + 'StatsNCFPDF StatsNCFPDF StatsNCTCDF StatsNCTPDF StatsNormalCDF StatsNormalPDF' + 'StatsParetoCDF StatsParetoCDF StatsParetoPDF StatsPermute StatsPoissonCDF' + 'StatsPoissonPDF StatsPoissonPDF StatsPowerCDF StatsPowerNoise StatsPowerPDF' + 'StatsQCDF StatsQCDF StatsQpCDF StatsRayleighCDF StatsRayleighPDF' + 'StatsRectangularCDF StatsRectangularCDF StatsRectangularPDF StatsRunsCDF' + 'StatsSpearmanRhoCDF StatsSpearmanRhoCDF StatsStudentCDF StatsStudentPDF' + 'StatsTopDownCDF StatsTopDownCDF StatsTriangularCDF StatsTriangularPDF' + 'StatsTrimmedMean StatsTrimmedMean StatsUSquaredCDF StatsVonMisesCDF' + 'StatsVonMisesNoise StatsVonMisesNoise StatsVonMisesPDF StatsWaldCDF' + 'StatsWaldPDF StatsWaldPDF StatsWeibullCDF StatsWeibullPDF StopMSTimer' + 'StrVarOrDefault StrVarOrDefault StringByKey StringFromList StringList StudentA' + 'StudentT StudentT TDMAddChannel TDMAddGroup TDMAppendDataValues' + 'TDMAppendDataValuesTime TDMAppendDataValuesTime TDMChannelPropertyExists' + 'TDMCloseChannel TDMCloseChannel TDMCloseFile TDMCloseGroup' + 'TDMCreateChannelProperty TDMCreateChannelProperty TDMCreateFile' + 'TDMCreateFileProperty TDMCreateFileProperty TDMCreateGroupProperty' + 'TDMFilePropertyExists TDMFilePropertyExists TDMGetChannelPropertyNames' + 'TDMGetChannelPropertyNum TDMGetChannelPropertyNum TDMGetChannelPropertyStr' + 'TDMGetChannelPropertyTime TDMGetChannelPropertyTime TDMGetChannelPropertyType' + 'TDMGetChannelStringPropertyLen TDMGetChannelStringPropertyLen TDMGetChannels' + 'TDMGetDataType TDMGetDataType TDMGetDataValues TDMGetDataValuesTime' + 'TDMGetFilePropertyNames TDMGetFilePropertyNames TDMGetFilePropertyNum' + 'TDMGetFilePropertyStr TDMGetFilePropertyStr TDMGetFilePropertyTime' + 'TDMGetFilePropertyType TDMGetFilePropertyType TDMGetFileStringPropertyLen' + 'TDMGetGroupPropertyNames TDMGetGroupPropertyNames TDMGetGroupPropertyNum' + 'TDMGetGroupPropertyStr TDMGetGroupPropertyStr TDMGetGroupPropertyTime' + 'TDMGetGroupPropertyType TDMGetGroupPropertyType TDMGetGroupStringPropertyLen' + 'TDMGetGroups TDMGetGroups TDMGetLibraryErrorDescription' + 'TDMGetNumChannelProperties TDMGetNumChannelProperties TDMGetNumChannels' + 'TDMGetNumDataValues TDMGetNumDataValues TDMGetNumFileProperties' + 'TDMGetNumGroupProperties TDMGetNumGroupProperties TDMGetNumGroups' + 'TDMGroupPropertyExists TDMGroupPropertyExists TDMOpenFile TDMOpenFileEx' + 'TDMRemoveChannel TDMRemoveChannel TDMRemoveGroup TDMReplaceDataValues' + 'TDMReplaceDataValuesTime TDMReplaceDataValuesTime TDMSaveFile' + 'TDMSetChannelPropertyNum TDMSetChannelPropertyNum TDMSetChannelPropertyStr' + 'TDMSetChannelPropertyTime TDMSetChannelPropertyTime TDMSetDataValues' + 'TDMSetDataValuesTime TDMSetDataValuesTime TDMSetFilePropertyNum' + 'TDMSetFilePropertyStr TDMSetFilePropertyStr TDMSetFilePropertyTime' + 'TDMSetGroupPropertyNum TDMSetGroupPropertyNum TDMSetGroupPropertyStr' + 'TDMSetGroupPropertyTime TDMSetGroupPropertyTime TableInfo TagVal TagWaveRef' + 'TextEncodingCode TextEncodingCode TextEncodingName TextFile ThreadGroupCreate' + 'ThreadGroupGetDF ThreadGroupGetDF ThreadGroupGetDFR ThreadGroupRelease' + 'ThreadGroupWait ThreadGroupWait ThreadProcessorCount ThreadReturnValue' + 'TraceFromPixel TraceFromPixel TraceInfo TraceNameList TraceNameToWaveRef' + 'TrimString TrimString URLDecode URLEncode UnPadString UniqueName' + 'UnsetEnvironmentVariable UnsetEnvironmentVariable UpperStr VariableList' + 'Variance Variance Voigt VoigtFit VoigtFit1Shape VoigtFit1Shape1Width' + 'VoigtFit1Shape1WidthBL VoigtFit1Shape1WidthBL VoigtFit1ShapeBL VoigtFitBL' + 'VoigtFunc VoigtFunc WMFindWholeWord WaveCRC WaveDims WaveExists WaveInfo' + 'WaveList WaveList WaveMax WaveMin WaveName WaveRefIndexed WaveRefIndexedDFR' + 'WaveRefWaveToList WaveRefWaveToList WaveRefsEqual WaveTextEncoding WaveType' + 'WaveUnits WaveUnits WhichListItem WinList WinName WinRecreation WinType' + 'XWaveName XWaveName XWaveRefFromTrace ZernikeR abs acos acosh alog area areaXY' + 'asin asin asinh atan atan2 atanh beta betai binomial binomialNoise binomialln' + 'cabs cabs ceil cequal char2num chebyshev chebyshevU cmplx cmpstr conj cos' + 'cosIntegral cosIntegral cosh cot coth cpowi csc csch date date2secs datetime' + 'defined defined deltax digamma dilogarithm ei enoise equalWaves erf erfc erfcw' + 'exists exists exp expInt expIntegralE1 expNoise fDAQmx_AI_GetReader' + 'fDAQmx_AO_UpdateOutputs fDAQmx_AO_UpdateOutputs fDAQmx_CTR_Finished' + 'fDAQmx_CTR_IsFinished fDAQmx_CTR_IsFinished fDAQmx_CTR_IsPulseFinished' + 'fDAQmx_CTR_ReadCounter fDAQmx_CTR_ReadCounter fDAQmx_CTR_ReadWithOptions' + 'fDAQmx_CTR_SetPulseFrequency fDAQmx_CTR_SetPulseFrequency fDAQmx_CTR_Start' + 'fDAQmx_ConnectTerminals fDAQmx_ConnectTerminals fDAQmx_DIO_Finished' + 'fDAQmx_DIO_PortWidth fDAQmx_DIO_PortWidth fDAQmx_DIO_Read fDAQmx_DIO_Write' + 'fDAQmx_DeviceNames fDAQmx_DeviceNames fDAQmx_DisconnectTerminals' + 'fDAQmx_ErrorString fDAQmx_ErrorString fDAQmx_ExternalCalDate' + 'fDAQmx_NumAnalogInputs fDAQmx_NumAnalogInputs fDAQmx_NumAnalogOutputs' + 'fDAQmx_NumCounters fDAQmx_NumCounters fDAQmx_NumDIOPorts fDAQmx_ReadChan' + 'fDAQmx_ReadNamedChan fDAQmx_ReadNamedChan fDAQmx_ResetDevice' + 'fDAQmx_ScanGetAvailable fDAQmx_ScanGetAvailable fDAQmx_ScanGetNextIndex' + 'fDAQmx_ScanStart fDAQmx_ScanStart fDAQmx_ScanStop fDAQmx_ScanWait' + 'fDAQmx_ScanWaitWithTimeout fDAQmx_ScanWaitWithTimeout fDAQmx_SelfCalDate' + 'fDAQmx_SelfCalibration fDAQmx_SelfCalibration fDAQmx_WF_IsFinished' + 'fDAQmx_WF_WaitUntilFinished fDAQmx_WF_WaitUntilFinished fDAQmx_WaveformStart' + 'fDAQmx_WaveformStop fDAQmx_WaveformStop fDAQmx_WriteChan factorial fakedata' + 'faverage faverage faverageXY floor gamma gammaEuler gammaInc gammaNoise gammln' + 'gammp gammp gammq gcd gnoise hcsr hermite hermiteGauss imag interp inverseERF' + 'inverseERFC inverseERFC leftx limit ln log logNormalNoise lorentzianNoise' + 'magsqr magsqr max mean median min mod norm note num2char num2istr num2str' + 'numpnts numpnts numtype p2rect pcsr pnt2x poissonNoise poly poly2D qcsr r2polar' + 'real real rightx round sawtooth scaleToIndex sec sech sign sin sinIntegral sinc' + 'sinh sinh sqrt str2num stringCRC stringmatch strlen strsearch sum tan tanh' + 'ticks ticks time trunc vcsr viAssertIntrSignal viAssertTrigger' + 'viAssertUtilSignal viAssertUtilSignal viClear viClose viDisableEvent' + 'viDiscardEvents viDiscardEvents viEnableEvent viFindNext viFindRsrc' + 'viGetAttribute viGetAttribute viGetAttributeString viGpibCommand' + 'viGpibControlATN viGpibControlATN viGpibControlREN viGpibPassControl' + 'viGpibSendIFC viGpibSendIFC viIn16 viIn32 viIn8 viLock viMapAddress' + 'viMapTrigger viMapTrigger viMemAlloc viMemFree viMoveIn16 viMoveIn32 viMoveIn8' + 'viMoveOut16 viMoveOut16 viMoveOut32 viMoveOut8 viOpen viOpenDefaultRM viOut16' + 'viOut32 viOut32 viOut8 viPeek16 viPeek32 viPeek8 viPoke16 viPoke32 viPoke8' + 'viRead viRead viReadSTB viSetAttribute viSetAttributeString viStatusDesc' + 'viTerminate viTerminate viUnlock viUnmapAddress viUnmapTrigger viUsbControlIn' + 'viUsbControlOut viUsbControlOut viVxiCommandQuery viWaitOnEvent viWrite wnoise' + 'x2pnt x2pnt xcsr zcsr zeta', /* Igor Built-in Functions */ class: 'APMath Abort AddFIFOData AddFIFOVectData AddMovieAudio AddMovieFrame AdoptFiles' + 'Append Append AppendImage AppendLayoutObject AppendMatrixContour AppendText' + 'AppendToGizmo AppendToGizmo AppendToGraph AppendToLayout AppendToTable' + 'AppendXYZContour AppendXYZContour AutoPositionWindow AxonTelegraphFindServers' + 'BackgroundInfo BackgroundInfo Beep BoundingBall BoxSmooth BrowseURL BuildMenu' + 'Button Button CWT Chart CheckBox CheckDisplayed ChooseColor Close CloseHelp' + 'CloseMovie CloseMovie CloseProc ColorScale ColorTab2Wave Concatenate ControlBar' + 'ControlInfo ControlInfo ControlUpdate ConvertGlobalStringTextEncoding' + 'ConvexHull ConvexHull Convolve CopyFile CopyFolder CopyScales Correlate' + 'CreateAliasShortcut CreateAliasShortcut CreateBrowser Cross CtrlBackground' + 'CtrlFIFO CtrlFIFO CtrlNamedBackground Cursor CurveFit CustomControl' + 'DAQmx_AI_SetupReader DAQmx_AI_SetupReader DAQmx_AO_SetOutputs' + 'DAQmx_CTR_CountEdges DAQmx_CTR_CountEdges DAQmx_CTR_OutputPulse' + 'DAQmx_CTR_Period DAQmx_CTR_Period DAQmx_CTR_PulseWidth DAQmx_DIO_Config' + 'DAQmx_DIO_WriteNewData DAQmx_DIO_WriteNewData DAQmx_Scan DAQmx_WaveformGen DPSS' + 'DSPDetrend DSPDetrend DSPPeriodogram DWT Debugger DebuggerOptions DefaultFont' + 'DefaultGuiControls DefaultGuiControls DefaultGuiFont DefaultTextEncoding' + 'DefineGuide DefineGuide DelayUpdate DeleteAnnotations DeleteFile DeleteFolder' + 'DeletePoints DeletePoints Differentiate Display DisplayHelpTopic' + 'DisplayProcedure DisplayProcedure DoAlert DoIgorMenu DoUpdate DoWindow' + 'DoXOPIdle DoXOPIdle DrawAction DrawArc DrawBezier DrawLine DrawOval DrawPICT' + 'DrawPoly DrawPoly DrawRRect DrawRect DrawText DrawUserShape Duplicate' + 'DuplicateDataFolder DuplicateDataFolder EdgeStats Edit ErrorBars' + 'EstimatePeakSizes EstimatePeakSizes Execute ExecuteScriptText' + 'ExperimentModified ExperimentModified ExportGizmo Extract FBinRead FBinWrite' + 'FFT FFT FGetPos FIFO2Wave FIFOStatus FPClustering FReadLine FSetPos FStatus' + 'FTPCreateDirectory FTPCreateDirectory FTPDelete FTPDownload FTPUpload' + 'FastGaussTransform FastGaussTransform FastOp FilterFIR FilterIIR FindAPeak' + 'FindContour FindContour FindDuplicates FindLevel FindLevels FindPeak' + 'FindPointsInPoly FindPointsInPoly FindRoots FindSequence FindValue FuncFit' + 'FuncFitMD FuncFitMD GBLoadWave GISCreateVectorLayer GISGetRasterInfo' + 'GISGetRegisteredFileInfo GISGetRegisteredFileInfo GISGetVectorLayerInfo' + 'GISLoadRasterData GISLoadRasterData GISLoadVectorData GISRasterizeVectorData' + 'GISRegisterFile GISRegisterFile GISTransformCoords GISUnRegisterFile' + 'GISWriteFieldData GISWriteFieldData GISWriteGeometryData GISWriteRaster GPIB2' + 'GPIBRead2 GPIBRead2 GPIBReadBinary2 GPIBReadBinaryWave2 GPIBReadWave2' + 'GPIBWrite2 GPIBWrite2 GPIBWriteBinary2 GPIBWriteBinaryWave2 GPIBWriteWave2' + 'GetAxis GetAxis GetCamera GetFileFolderInfo GetGizmo GetLastUserMenuInfo' + 'GetMarquee GetMarquee GetMouse GetSelection GetWindow GraphNormal GraphWaveDraw' + 'GraphWaveEdit GraphWaveEdit Grep GroupBox HDF5CloseFile HDF5CloseGroup' + 'HDF5ConvertColors HDF5ConvertColors HDF5CreateFile HDF5CreateGroup' + 'HDF5CreateLink HDF5CreateLink HDF5Dump HDF5DumpErrors HDF5DumpState' + 'HDF5ListAttributes HDF5ListAttributes HDF5ListGroup HDF5LoadData HDF5LoadGroup' + 'HDF5LoadImage HDF5LoadImage HDF5OpenFile HDF5OpenGroup HDF5SaveData' + 'HDF5SaveGroup HDF5SaveGroup HDF5SaveImage HDF5TestOperation HDF5UnlinkObject' + 'HDFInfo HDFInfo HDFReadImage HDFReadSDS HDFReadVset Hanning HideIgorMenus' + 'HideInfo HideInfo HideProcedures HideTools HilbertTransform Histogram ICA IFFT' + 'ImageAnalyzeParticles ImageAnalyzeParticles ImageBlend ImageBoundaryToMask' + 'ImageEdgeDetection ImageEdgeDetection ImageFileInfo ImageFilter ImageFocus' + 'ImageFromXYZ ImageFromXYZ ImageGLCM ImageGenerateROIMask ImageHistModification' + 'ImageHistogram ImageHistogram ImageInterpolate ImageLineProfile ImageLoad' + 'ImageMorphology ImageMorphology ImageRegistration ImageRemoveBackground' + 'ImageRestore ImageRestore ImageRotate ImageSave ImageSeedFill ImageSkeleton3d' + 'ImageSnake ImageSnake ImageStats ImageThreshold ImageTransform ImageUnwrapPhase' + 'ImageWindow ImageWindow IndexSort InsertPoints Integrate Integrate2D' + 'IntegrateODE IntegrateODE Interp3DPath Interpolate2 Interpolate3D JCAMPLoadWave' + 'JointHistogram JointHistogram KMeans KillBackground KillControl KillDataFolder' + 'KillFIFO KillFIFO KillFreeAxis KillPICTs KillPath KillStrings KillVariables' + 'KillWaves KillWaves KillWindow Label Layout LayoutPageAction LayoutSlideShow' + 'Legend Legend LinearFeedbackShiftRegister ListBox LoadData LoadPICT' + 'LoadPackagePreferences LoadPackagePreferences LoadWave Loess LombPeriodogram' + 'MCC_FindServers MCC_FindServers MLLoadWave Make MakeIndex MarkPerfTestTime' + 'MatrixConvolve MatrixConvolve MatrixCorr MatrixEigenV MatrixFilter MatrixGLM' + 'MatrixGaussJ MatrixGaussJ MatrixInverse MatrixLLS MatrixLUBkSub MatrixLUD' + 'MatrixLUDTD MatrixLUDTD MatrixLinearSolve MatrixLinearSolveTD MatrixMultiply' + 'MatrixOP MatrixOP MatrixSVBkSub MatrixSVD MatrixSchur MatrixSolve' + 'MatrixTranspose MatrixTranspose MeasureStyledText Modify ModifyBrowser' + 'ModifyCamera ModifyCamera ModifyContour ModifyControl ModifyControlList' + 'ModifyFreeAxis ModifyFreeAxis ModifyGizmo ModifyGraph ModifyImage ModifyLayout' + 'ModifyPanel ModifyPanel ModifyTable ModifyWaterfall MoveDataFolder MoveFile' + 'MoveFolder MoveFolder MoveString MoveSubwindow MoveVariable MoveWave MoveWindow' + 'MultiTaperPSD MultiTaperPSD MultiThreadingControl NI4882 NeuralNetworkRun' + 'NeuralNetworkTrain NeuralNetworkTrain NewCamera NewDataFolder NewFIFO' + 'NewFIFOChan NewFIFOChan NewFreeAxis NewGizmo NewImage NewLayout NewMovie' + 'NewNotebook NewNotebook NewPanel NewPath NewWaterfall Note Notebook' + 'NotebookAction NotebookAction Open OpenHelp OpenNotebook Optimize PCA' + 'ParseOperationTemplate ParseOperationTemplate PathInfo PauseForUser PauseUpdate' + 'PlayMovie PlayMovie PlayMovieAction PlaySound PopupContextualMenu PopupMenu' + 'Preferences Preferences PrimeFactors Print PrintGraphs PrintLayout' + 'PrintNotebook PrintNotebook PrintSettings PrintTable Project PulseStats' + 'PutScrapText PutScrapText Quit RatioFromNumber Redimension Remove RemoveContour' + 'RemoveFromGizmo RemoveFromGizmo RemoveFromGraph RemoveFromLayout' + 'RemoveFromTable RemoveFromTable RemoveImage RemoveLayoutObjects RemovePath' + 'Rename Rename RenameDataFolder RenamePICT RenamePath RenameWindow ReorderImages' + 'ReorderTraces ReorderTraces ReplaceText ReplaceWave Resample ResumeUpdate' + 'Reverse Reverse Rotate SQLHighLevelOp Save SaveData SaveExperiment' + 'SaveGraphCopy SaveGraphCopy SaveNotebook SavePICT SavePackagePreferences' + 'SaveTableCopy SaveTableCopy SetActiveSubwindow SetAxis SetBackground' + 'SetDashPattern SetDashPattern SetDataFolder SetDimLabel SetDrawEnv SetDrawLayer' + 'SetFileFolderInfo SetFileFolderInfo SetFormula SetIgorHook SetIgorMenuMode' + 'SetIgorOption SetIgorOption SetMarquee SetProcessSleep SetRandomSeed SetScale' + 'SetVariable SetVariable SetWaveLock SetWaveTextEncoding SetWindow ShowIgorMenus' + 'ShowInfo ShowInfo ShowTools Silent Sleep Slider Smooth SmoothCustom Sort' + 'SortColumns SortColumns SoundInRecord SoundInSet SoundInStartChart' + 'SoundInStatus SoundInStatus SoundInStopChart SoundLoadWave SoundSaveWave' + 'SphericalInterpolate SphericalInterpolate SphericalTriangulate SplitString' + 'SplitWave SplitWave Stack StackWindows StatsANOVA1Test StatsANOVA2NRTest' + 'StatsANOVA2RMTest StatsANOVA2RMTest StatsANOVA2Test StatsAngularDistanceTest' + 'StatsChiTest StatsChiTest StatsCircularCorrelationTest StatsCircularMeans' + 'StatsCircularMoments StatsCircularMoments StatsCircularTwoSampleTest' + 'StatsCochranTest StatsCochranTest StatsContingencyTable StatsDIPTest' + 'StatsDunnettTest StatsDunnettTest StatsFTest StatsFriedmanTest' + 'StatsHodgesAjneTest StatsHodgesAjneTest StatsJBTest StatsKDE StatsKSTest' + 'StatsKWTest StatsKWTest StatsKendallTauTest StatsLinearCorrelationTest' + 'StatsLinearRegression StatsLinearRegression StatsMultiCorrelationTest' + 'StatsNPMCTest StatsNPMCTest StatsNPNominalSRTest StatsQuantiles' + 'StatsRankCorrelationTest StatsRankCorrelationTest StatsResample StatsSRTest' + 'StatsSample StatsSample StatsScheffeTest StatsShapiroWilkTest StatsSignTest' + 'StatsTTest StatsTTest StatsTukeyTest StatsVariancesTest StatsWRCorrelationTest' + 'StatsWatsonUSquaredTest StatsWatsonUSquaredTest StatsWatsonWilliamsTest' + 'StatsWheelerWatsonTest StatsWheelerWatsonTest StatsWilcoxonRankTest String' + 'StructGet StructGet StructPut SumDimension SumSeries TDMLoadData TDMSaveData' + 'TabControl TabControl Tag TextBox ThreadGroupPutDF ThreadStart Tile TileWindows' + 'TitleBox TitleBox ToCommandLine ToolsGrid Triangulate3d URLRequest Unwrap VDT2' + 'VDTClosePort2 VDTClosePort2 VDTGetPortList2 VDTGetStatus2 VDTOpenPort2' + 'VDTOperationsPort2 VDTOperationsPort2 VDTRead2 VDTReadBinary2' + 'VDTReadBinaryWave2 VDTReadBinaryWave2 VDTReadHex2 VDTReadHexWave2 VDTReadWave2' + 'VDTTerminalPort2 VDTTerminalPort2 VDTWrite2 VDTWriteBinary2 VDTWriteBinaryWave2' + 'VDTWriteHex2 VDTWriteHex2 VDTWriteHexWave2 VDTWriteWave2 VISAControl VISARead' + 'VISAReadBinary VISAReadBinary VISAReadBinaryWave VISAReadWave VISAWrite' + 'VISAWriteBinary VISAWriteBinary VISAWriteBinaryWave VISAWriteWave ValDisplay' + 'Variable Variable WaveMeanStdv WaveStats WaveTransform WignerTransform' + 'WindowFunction WindowFunction XLLoadWave cd dir fprintf printf pwd sprintf' + 'sscanf sscanf wfprintf' }; return { case_insensitive: true, // language is case-insensitive keywords: IGOR_KEYWORDS, illegal: '^@|^{', contains: [ PRE_PROCESSOR, WAVE_DECLARATION, hljs.C_LINE_COMMENT_MODE, hljs.QUOTE_STRING_MODE, ] }; }
75.29
94
0.81133
7994f801073c80d5700db5581cfb30d15c6d5e86
7,501
php
PHP
src/Core/Content/Product/SalesChannel/Price/ProductPriceDefinitionBuilder.php
szepeviktor/platform
7f528ac45cda4cd374b71afa8615e5d793d45ba9
[ "MIT" ]
null
null
null
src/Core/Content/Product/SalesChannel/Price/ProductPriceDefinitionBuilder.php
szepeviktor/platform
7f528ac45cda4cd374b71afa8615e5d793d45ba9
[ "MIT" ]
19
2020-09-06T09:54:53.000Z
2022-02-26T15:01:11.000Z
src/Core/Content/Product/SalesChannel/Price/ProductPriceDefinitionBuilder.php
franbow/shopware
14114003c16bcb44ef9ddb8bbd113d85630287da
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace Shopware\Core\Content\Product\SalesChannel\Price; use Shopware\Core\Checkout\Cart\Price\Struct\CartPrice; use Shopware\Core\Checkout\Cart\Price\Struct\PriceDefinitionCollection; use Shopware\Core\Checkout\Cart\Price\Struct\QuantityPriceDefinition; use Shopware\Core\Content\Product\Aggregate\ProductPrice\ProductPriceCollection; use Shopware\Core\Content\Product\ProductEntity; use Shopware\Core\Defaults; use Shopware\Core\Framework\Pricing\Price; use Shopware\Core\Framework\Pricing\PriceRuleEntity; use Shopware\Core\System\SalesChannel\SalesChannelContext; class ProductPriceDefinitionBuilder implements ProductPriceDefinitionBuilderInterface { public function build( ProductEntity $product, SalesChannelContext $salesChannelContext, int $quantity = 1 ): ProductPriceDefinitions { $listingPrice = $this->buildListingPriceDefinition($product, $salesChannelContext); return new ProductPriceDefinitions( $this->buildPriceDefinition($product, $salesChannelContext), $this->buildPriceDefinitions($product, $salesChannelContext), $listingPrice['from'], $listingPrice['to'], $this->buildPriceDefinitionForQuantity($product, $salesChannelContext, $quantity) ); } private function buildPriceDefinitions( ProductEntity $product, SalesChannelContext $salesChannelContext ): PriceDefinitionCollection { $taxRules = $product->getTaxRuleCollection(); $prices = $this->getFirstMatchingPriceRule($product->getPrices(), $salesChannelContext); if (!$prices) { return new PriceDefinitionCollection(); } $prices->sortByQuantity(); $definitions = []; foreach ($prices as $price) { $quantity = $price->getQuantityEnd() ?? $price->getQuantityStart(); $definitions[] = new QuantityPriceDefinition( $this->getCurrencyPrice($price, $salesChannelContext), $taxRules, $salesChannelContext->getContext()->getCurrencyPrecision(), $quantity, true ); } return new PriceDefinitionCollection($definitions); } private function buildPriceDefinition( ProductEntity $product, SalesChannelContext $salesChannelContext ): QuantityPriceDefinition { $price = $this->getPriceForTaxState( $product->getCurrencyPrice($salesChannelContext->getCurrency()->getId()), $salesChannelContext ); return new QuantityPriceDefinition( $price * $salesChannelContext->getContext()->getCurrencyFactor(), $product->getTaxRuleCollection(), $salesChannelContext->getContext()->getCurrencyPrecision(), 1, true ); } private function buildListingPriceDefinition(ProductEntity $product, SalesChannelContext $salesChannelContext): array { $taxRules = $product->getTaxRuleCollection(); $currencyPrecision = $salesChannelContext->getContext()->getCurrencyPrecision(); $currencyId = $salesChannelContext->getCurrency()->getId(); $factor = $salesChannelContext->getContext()->getCurrencyFactor(); if ($product->getListingPrices()) { $listingPrice = $product->getListingPrices()->getContextPrice($salesChannelContext->getContext()); if ($listingPrice) { // indexed listing prices are indexed for each currency $from = $this->getPriceForTaxState($listingPrice->getFrom(), $salesChannelContext); $to = $this->getPriceForTaxState($listingPrice->getTo(), $salesChannelContext); return [ 'from' => new QuantityPriceDefinition($from, $taxRules, $currencyPrecision, 1, true), 'to' => new QuantityPriceDefinition($to, $taxRules, $currencyPrecision, 1, true), ]; } } $prices = $this->getFirstMatchingPriceRule($product->getPrices(), $salesChannelContext); if (!$prices || $prices->count() <= 0) { $price = $this->getPriceForTaxState($product->getCurrencyPrice($currencyId), $salesChannelContext); $definition = new QuantityPriceDefinition($price * $factor, $taxRules, $currencyPrecision, 1, true); return ['from' => $definition, 'to' => $definition]; } $highest = $this->getCurrencyPrice($prices->first(), $salesChannelContext); $lowest = $highest; foreach ($prices as $price) { $value = $this->getCurrencyPrice($price, $salesChannelContext); $highest = $value > $highest ? $value : $highest; $lowest = $value < $lowest ? $value : $lowest; } return [ 'from' => new QuantityPriceDefinition($lowest, $taxRules, $currencyPrecision, 1, true), 'to' => new QuantityPriceDefinition($highest, $taxRules, $currencyPrecision, 1, true), ]; } private function buildPriceDefinitionForQuantity( ProductEntity $product, SalesChannelContext $salesChannelContext, int $quantity ): QuantityPriceDefinition { $taxRules = $product->getTaxRuleCollection(); /** @var ProductPriceCollection|null $prices */ $prices = $this->getFirstMatchingPriceRule($product->getPrices(), $salesChannelContext); if (!$prices) { $price = $this->getPriceForTaxState( $product->getCurrencyPrice($salesChannelContext->getCurrency()->getId()), $salesChannelContext ); return new QuantityPriceDefinition( $price * $salesChannelContext->getContext()->getCurrencyFactor(), $taxRules, $salesChannelContext->getContext()->getCurrencyPrecision(), $quantity, true ); } $prices = $prices->getQuantityPrices($quantity); return new QuantityPriceDefinition( $this->getCurrencyPrice($prices->first(), $salesChannelContext), $taxRules, $salesChannelContext->getContext()->getCurrencyPrecision(), $quantity, true ); } private function getFirstMatchingPriceRule( ProductPriceCollection $rules, SalesChannelContext $context ): ?ProductPriceCollection { foreach ($context->getRuleIds() as $ruleId) { $filtered = $rules->filterByRuleId($ruleId); if ($filtered->count() > 0) { /* @var ProductPriceCollection $filtered */ return $filtered; } } return null; } private function getCurrencyPrice(PriceRuleEntity $rule, SalesChannelContext $context): float { $price = $rule->getPrice()->getCurrencyPrice($context->getCurrency()->getId()); $value = $this->getPriceForTaxState($price, $context); if ($price->getCurrencyId() === Defaults::CURRENCY) { $value *= $context->getContext()->getCurrencyFactor(); } return $value; } private function getPriceForTaxState(Price $price, SalesChannelContext $context): float { if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) { return $price->getGross(); } return $price->getNet(); } }
36.0625
121
0.625917
96ad185334f005ac928b339338c395d66566a68c
2,002
sql
SQL
finddb_schema/base_schema/create_measurements_table.sql
sjsafranek/find5
c8d5bbbcfb4b33f420a83f07025bad9727474ce3
[ "MIT" ]
1
2019-08-17T00:48:06.000Z
2019-08-17T00:48:06.000Z
finddb_schema/base_schema/create_measurements_table.sql
sjsafranek/find5
c8d5bbbcfb4b33f420a83f07025bad9727474ce3
[ "MIT" ]
null
null
null
finddb_schema/base_schema/create_measurements_table.sql
sjsafranek/find5
c8d5bbbcfb4b33f420a83f07025bad9727474ce3
[ "MIT" ]
null
null
null
DROP TABLE IF EXISTS measurements CASCADE; -- @table measurements -- @description stores measurements collected by sensors at a given location CREATE TABLE IF NOT EXISTS measurements ( id SERIAL PRIMARY KEY, location_id VARCHAR(36) NOT NULL REFERENCES locations(id) ON DELETE CASCADE, sensor_id VARCHAR(36) NOT NULL CHECK(sensor_id != ''), key VARCHAR(50) NOT NULL CHECK(key != ''), value DOUBLE PRECISION NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (sensor_id) REFERENCES sensors(id) ON DELETE CASCADE, -- TODO: should be down in a database patch UNIQUE(sensor_id, value, key, created_at) ); COMMENT ON TABLE measurements IS 'measurements collected by device sensors at a given location'; COMMENT ON COLUMN measurements.sensor_id IS 'sensor that created the measurement'; COMMENT ON COLUMN measurements.location_id IS 'location where the measurement was made'; -- @method measurements__location_history__insert -- @description stores location_history record for sensor's device CREATE OR REPLACE FUNCTION measurements__location_history__insert() RETURNS TRIGGER AS $$ BEGIN IF NEW.location_id IS NOT NULL THEN INSERT INTO location_history (device_id, location_id, probability) (SELECT devices.id, NEW.location_id, 100.0 FROM sensors INNER JOIN devices ON devices.id = sensors.device_id WHERE sensors.id = NEW.sensor_id ) ON CONFLICT DO NOTHING; END IF; RETURN NEW; END; $$ language 'plpgsql'; -- @trigger measurements__location_history__insert DROP TRIGGER IF EXISTS measurements__location_history__insert ON measurements; CREATE TRIGGER measurements__location_history__insert AFTER INSERT ON measurements FOR EACH ROW EXECUTE PROCEDURE measurements__location_history__insert();
39.254902
96
0.696803
b77e355a449d985fa8a1ac1c11900ec489b00fa8
3,114
cpp
C++
UVa 12833 - Daily Potato/sample/12833 - Daily Potato.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 12833 - Daily Potato/sample/12833 - Daily Potato.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 12833 - Daily Potato/sample/12833 - Daily Potato.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> #include <string.h> #include <algorithm> #include <vector> using namespace std; #define MAXL 262144 char S[MAXL], C[MAXL], T[MAXL]; int dp[MAXL], n, m; int A[MAXL][26], SUM[MAXL][26]; void exbuild(char S[]) { // manacher's algorithm n = strlen(S), m = 2 * n + 1; int mx = 0, idx = 0; int ans = 0; T[0] = '$', T[m] = '#', T[m + 1] = '\0'; for (int i = 0; i < n; i++) T[i * 2 + 1] = '#', T[i * 2 + 2] = S[i]; // memset(SUM[0], 0, sizeof(SUM[0])); for (int i = 1; i < m; i++) { memcpy(SUM[i], SUM[i-1], sizeof(SUM[0])); if ('a' <= T[i] && T[i] <= 'z') SUM[i][T[i] - 'a']++; } // for (int i = 1; i < m; i++) { if (mx > i) { memcpy(A[i], A[2 * idx - i], sizeof(A[2 * idx - i])); dp[i] = min(dp[2 * idx - i], mx - i); if (dp[2 * idx - i] >= mx - i) { int r = idx - (mx - idx), l = 2 * idx - i - dp[2 * idx - i]; for (int j = 0; j < 26; j++) { A[i][j] -= (SUM[r][j] - SUM[l][j]) * 2; } } } else { for (int j = 0; j < 26; j++) A[i][j] = SUM[i][j] - SUM[i-1][j]; dp[i] = 1; } for(; T[i-dp[i]] == T[i+dp[i]]; dp[i]++) if ('a' <= T[i+dp[i]] && T[i+dp[i]] <= 'z') A[i][T[i-dp[i]] - 'a'] += 2; if(dp[i] + i > mx) mx = dp[i] + i, idx = i; } // for (int i = 1, j = 0; i < m; i ++, j++) // printf("[%02d] %c %d\n", i, T[i], dp[i]); } vector<int> pos[128]; vector<int> M[2][26]; void prepare() { for (int i = 0; i < 26; i++) M[0][i].clear(), M[1][i].clear(); // for (int i = 0; i < 128; i++) // pos[i].clear(); // for (int i = 1; i < m; i++) { // pos[T[i]].push_back(i); // } for (int i = 1; i < m; i++) { // printf("%c ", T[i]); for (int j = 0; j < 26; j++) { M[A[i][j]&1][j].push_back(A[i][j]); // printf("%d ", A[i][j]); } // puts(""); } for (int i = 0; i < 26; i++) { sort(M[0][i].begin(), M[0][i].end()); sort(M[1][i].begin(), M[1][i].end()); } } void query(int x, char c) { if (x == 0) {puts("0"); return;} // int sum = 0, front = 0, rear = 0; // int ret = 0, mid; // for (int i = x - 1, j = 0; i < pos[c].size(); i++, j++) { // front = pos[c][j], rear = pos[c][i]; // mid = (front + rear)/2; // if (mid + dp[mid] - 1 >= rear) // ret++; // } // printf("%d\n", ret); int p = (int) (lower_bound(M[x&1][c - 'a'].begin(), M[x&1][c - 'a'].end(), x) - M[x&1][c - 'a'].begin()); printf("%d\n", int(M[x&1][c - 'a'].size() - p)); } int main() { freopen("in.txt", "r+t", stdin); freopen("out2.txt", "w+t", stdout); int testcase, N, Q, cases = 0; int x; scanf("%d", &testcase); while(testcase--) { scanf("%d %s", &N, S); scanf("%d %s", &Q, C); exbuild(S); prepare(); printf("Case %d:\n", ++cases); for (int i = 0; i < Q; i++) { scanf("%d", &x); query(x, C[i]); } } return 0; } /* 1 8 abccbaab 6 abcabc 2 2 2 1 1 3 1000 6 abaaba 7 aaaaaab 5 4 3 2 1 0 2 123 10 ccecabebcb 10 ebddcdacad 5 6 2 5 5 5 5 1 9 9 10 abbbbeaaba 10 cbabcabcec 2 0 1 8 5 6 2 4 8 1 10 baddaeaecb 10 bbdebdbedd 1 5 5 6 2 9 9 1 5 0 */
22.729927
106
0.423892
4412e2b15f3a96f14e75d4d6fa700dcaeab1d097
1,902
py
Python
experiments/node_classification/gat/gat_train.py
yimengmin/wiki-cs-dataset
4078c80e698c58e5cfb3ef19f2716f1032dced4d
[ "MIT" ]
30
2020-07-05T12:04:24.000Z
2021-12-08T13:08:33.000Z
experiments/node_classification/gat/gat_train.py
yimengmin/wiki-cs-dataset
4078c80e698c58e5cfb3ef19f2716f1032dced4d
[ "MIT" ]
4
2021-02-26T13:59:42.000Z
2022-01-09T23:22:09.000Z
experiments/node_classification/gat/gat_train.py
yimengmin/wiki-cs-dataset
4078c80e698c58e5cfb3ef19f2716f1032dced4d
[ "MIT" ]
5
2020-07-07T09:21:57.000Z
2021-07-14T13:32:42.000Z
import argparse import torch.nn.functional as F from .. import load_graph_data from ..train import train_and_eval from ..train import register_general_args from .gat import GAT def gat_model_fn(args, data): heads = ([args.n_heads] * args.n_layers) + [args.n_out_heads] return GAT(data.graph, args.n_hidden_layers, data.n_feats, args.n_hidden_units, data.n_classes, heads, F.elu, args.in_drop, args.attn_drop, args.negative_slope, args.residual) def register_gat_args(parser): parser.add_argument("--n-hidden-units", type=int, default=16, help="number of hidden gcn units") parser.add_argument("--n-hidden-layers", type=int, default=1, help="number of hidden gat layers") parser.add_argument("--n-heads", type=int, default=8, help="number of hidden attention heads") parser.add_argument("--n-out-heads", type=int, default=1, help="number of output attention heads") parser.add_argument("--in-drop", type=float, default=.6, help="input feature dropout") parser.add_argument("--attn-drop", type=float, default=.6, help="attention dropout") parser.add_argument("--residual", action="store_true", default=False, help="use residual connection") parser.add_argument('--negative-slope', type=float, default=0.2, help="the negative slope of leaky relu") if __name__ == '__main__': parser = argparse.ArgumentParser(description='GAT') register_general_args(parser) register_gat_args(parser) args = parser.parse_args() print('Parsed args:', args) train_and_eval(gat_model_fn, load_graph_data.load(args), args)
36.576923
73
0.608833
1a89f5a3e10370c1d8a6cbf9255a650cab0b4335
2,172
py
Python
clock/clock.py
Shikkic/exercism.io.python
b7cd69dbe74886971c3a26dfb8b3c09013d87be2
[ "MIT" ]
null
null
null
clock/clock.py
Shikkic/exercism.io.python
b7cd69dbe74886971c3a26dfb8b3c09013d87be2
[ "MIT" ]
null
null
null
clock/clock.py
Shikkic/exercism.io.python
b7cd69dbe74886971c3a26dfb8b3c09013d87be2
[ "MIT" ]
null
null
null
class Clock(): # Set initial Clock state def __init__(self, hours, minutes): timeDic = self.calculateMinutes(minutes) self.minutes = timeDic['minutes'] self.hours = self.calculateHour(hours + timeDic['hours']) self.time = self.generateTimeString() # Add minutes to the clock (Can be positive or subtracting) def add(self, numMinutes=0): timeDic = self.calculateMinutes(self.minutes + numMinutes) self.setMinutes(timeDic['minutes']) hours = self.calculateHour(self.hours + timeDic['hours']) self.setHours(hours) self.time = self.generateTimeString() return self.time # Calculate Clock Hour in '24' from num of hours (Positive or Negative) def calculateHour(self, numHours=0): if numHours >= 0 and numHours < 24: return numHours hours = abs(numHours % 24) return hours # Caluclate Clock Minutes from num of minutes (Positive or Negative) # returns a dict of hours and minutes def calculateMinutes(self, numMinutes=0): if numMinutes >= 0 and numMinutes < 60: return { 'hours': 0, 'minutes': numMinutes } hours = (numMinutes / 60) minutes = (numMinutes % 60) if minutes == 60: minutes = 0 hours = hours + 1 return { 'hours': hours, 'minutes': minutes } # Generates time string from hours and minutes def generateTimeString(self): hourDigit = str(self.hours) if len(hourDigit) < 2: hourDigit = '%d%s' % (0, hourDigit) minuteDigit = str(self.minutes) if len(minuteDigit) < 2: minuteDigit = '%d%s' % (0, minuteDigit) return '%s:%s' % (hourDigit, minuteDigit) # ToString overide for instance def __str__(self): return self.time # Equality overide for instance def __eq__(self, other): return self.time == other.time # Setter for hours def setHours(self, hours): self.hours = hours # Setter for minutes def setMinutes(self, minutes): self.minutes = minutes
28.96
75
0.598066
e058adfe3cd669f493c6bcb1ca7aee6597a5b30a
1,139
h
C
net/irda/irsir/crystal.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/irda/irsir/crystal.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/irda/irsir/crystal.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/***************************************************************************** * * Copyright (c) 1998-1999 Microsoft Corporation * * @doc * @module Crystal.h | IrSIR NDIS Miniport Driver * @comm * *----------------------------------------------------------------------------- * * Author: Stan Adermann (stana) * * Date: 3/4/1998 (created) * * Contents: Crystal (AMP) dongle specific prototypes. * *****************************************************************************/ #ifndef Crystal_H #define Crystal_H #include "dongle.h" NDIS_STATUS Crystal_QueryCaps( PDONGLE_CAPABILITIES pDongleCaps ); NDIS_STATUS Crystal_Init( PDEVICE_OBJECT pSerialDevObj ); void Crystal_Deinit( PDEVICE_OBJECT pSerialDevObj ); NDIS_STATUS Crystal_SetSpeed( PDEVICE_OBJECT pSerialDevObj, UINT bitsPerSec, UINT currentSpeed ); #endif //Crystal_H
24.234043
79
0.403863
2c7129e6c67e09d9ed9cee18d0b3283fc670c17a
2,341
cpp
C++
app/src/tags.cpp
anovotarsk/utag
3c2b59af2a7056e724a01b31e50c788c08f67c67
[ "MIT" ]
null
null
null
app/src/tags.cpp
anovotarsk/utag
3c2b59af2a7056e724a01b31e50c788c08f67c67
[ "MIT" ]
null
null
null
app/src/tags.cpp
anovotarsk/utag
3c2b59af2a7056e724a01b31e50c788c08f67c67
[ "MIT" ]
null
null
null
#include <tags.h> /* 0 - Artist 1 - Title 2 - Album 3 - Genre */ MP3File::MP3File(std::string file) : m_path(file) { int len; std::string *s = strsplit(file, '/', &len); m_name = s[len - 1]; delete [] s; } MP3File::~MP3File() { } std::string MP3File::getName() { return m_name; } std::string MP3File::getPath() { return m_path; } int MP3File::fileErrors(int mode) { int error = (access(m_path.c_str(), mode) == -1) ? errno : 0; errno = 0; return error; } std::array <std::string, 4> MP3File::readTags() { std::array <std::string, 4> tags; TagLib::MPEG::File file(m_path.c_str(), false); tags[0] = file.tag()->artist().toCString(); tags[1] = file.tag()->title().toCString(); tags[2] = file.tag()->album().toCString(); tags[3] = file.tag()->genre().toCString(); errno = 0; return tags; } int MP3File::writeTags(std::array <std::string, 4> tags) { int error = (access(m_path.c_str(), 2) == -1) ? errno : 0; if (error == 0) { TagLib::MPEG::File file(m_path.c_str(), false); if (!file.isWritable(m_path.c_str())) return 13; file.tag()->setArtist(tags[0]); file.tag()->setTitle(tags[1]); file.tag()->setAlbum(tags[2]); file.tag()->setGenre(tags[3]); file.save(); error = errno; } errno = 0; return error; } bool compareArtist(std::string i, std::string j) { MP3File* mp3_i = new MP3File(i); MP3File* mp3_j = new MP3File(j); bool rez = mp3_i->readTags()[0] < mp3_j->readTags()[0]; delete mp3_i; delete mp3_j; return rez; } bool compareTitle(std::string i, std::string j) { MP3File* mp3_i = new MP3File(i); MP3File* mp3_j = new MP3File(j); bool rez = mp3_i->readTags()[1] < mp3_j->readTags()[1]; delete mp3_i; delete mp3_j; return rez; } bool compareAlbum(std::string i, std::string j) { MP3File* mp3_i = new MP3File(i); MP3File* mp3_j = new MP3File(j); bool rez = mp3_i->readTags()[2] < mp3_j->readTags()[2]; delete mp3_i; delete mp3_j; return rez; } bool compareGenre(std::string i, std::string j) { MP3File* mp3_i = new MP3File(i); MP3File* mp3_j = new MP3File(j); bool rez = mp3_i->readTags()[3] < mp3_j->readTags()[3]; delete mp3_i; delete mp3_j; return rez; }
21.675926
65
0.579667
33af57c5ef2f2154751a3fab83e09526281d9b18
1,564
h
C
editor/VandaEngine1/PublishProject.h
ehsankamrani/vandaengine
854430e41db6df1f4fcad9c19718fd8dfcc2c3cb
[ "MIT" ]
12
2021-06-22T11:28:12.000Z
2022-03-21T00:56:33.000Z
editor/VandaEngine1/PublishProject.h
ehsankamrani/vandaengine
854430e41db6df1f4fcad9c19718fd8dfcc2c3cb
[ "MIT" ]
null
null
null
editor/VandaEngine1/PublishProject.h
ehsankamrani/vandaengine
854430e41db6df1f4fcad9c19718fd8dfcc2c3cb
[ "MIT" ]
1
2018-10-05T08:17:29.000Z
2018-10-05T08:17:29.000Z
//Copyright (C) 2022 Ehsan Kamrani //This file is licensed and distributed under MIT license #pragma once #include "afxcmn.h" #include "afxwin.h" // CPublishProject dialog class CPublishProject : public CDialog { DECLARE_DYNAMIC(CPublishProject) public: CPublishProject(CWnd* pParent = NULL); // standard constructor virtual ~CPublishProject(); // Dialog Data enum { IDD = IDD_DIALOG_PUBLISH_PROJECT }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedBtnDestination(); afx_msg void OnBnClickedBtnIcon(); CRichEditCtrl m_editBoxDestination; CRichEditCtrl m_editBoxIcon; CString m_strIcon; CString m_strDestination; CString m_strName; CString m_strSplash; CBool m_saveCurrentScene; private: CBool m_publishDebug; protected: virtual void OnOK(); public: CButton m_checkBoxSave; virtual BOOL OnInitDialog(); CEdit m_editBoxName; afx_msg void OnEnChangeEditName(); afx_msg void OnBnClickedBtnSplashImage(); CRichEditCtrl m_editBoxSplash; CListCtrl m_listBoxAvailableScenes; CListCtrl m_listBoxScenesToBePublished; afx_msg void OnBnClickedAdd(); afx_msg void OnBnClickedRemove(); CInt availableSceneIndex; CInt sceneToBePublishedIndex; CVoid InserItemToAvailableScenesList( char * objectName ); CBool m_setFirstScene; CVoid InserItemToScenesToBePublishedList( char * objectName ); afx_msg void OnBnClickedOk(); afx_msg void OnBnClickedMarkAsFirstScene(); CButton m_checkBoxDebug; CBool GetPublishDebug() { return m_publishDebug; } };
25.225806
71
0.801151
662352b96b7ab0310edc50c9e45b24b0a7a4ed5b
1,094
py
Python
test codes/cython_test/cython_test_try_2/testing.py
DionEngels/MBxPython
1f1bc7f3be86082a6f3f4dc0eaf162db00061b34
[ "MIT" ]
null
null
null
test codes/cython_test/cython_test_try_2/testing.py
DionEngels/MBxPython
1f1bc7f3be86082a6f3f4dc0eaf162db00061b34
[ "MIT" ]
null
null
null
test codes/cython_test/cython_test_try_2/testing.py
DionEngels/MBxPython
1f1bc7f3be86082a6f3f4dc0eaf162db00061b34
[ "MIT" ]
null
null
null
import example_cy import numpy as np import mbx_fortran import optimized_cy import time size = 9 height = 1 center_x = 4 center_y = 4 width_x = 2 width_y = 2 data = np.zeros((size, size), dtype=np.uint16) num_loop = 10000 loops = list(range(0, num_loop)) start = time.time() for loop in loops: res_c = example_cy.gaussian(height, center_x, center_y, width_x, width_y, size, data) res_c2 = np.reshape(res_c, (size, size)) print('Time taken base c: ' + str(round(time.time() - start, 3)) + ' s. Loops: ' + str(len(loops))) start = time.time() for loop in loops: res_f = mbx_fortran.gaussian(height, center_x, center_y, width_x, width_y, size, data) res_f2 = np.reshape(res_f, (size, size)) print('Time taken base c: ' + str(round(time.time() - start, 3)) + ' s. Loops: ' + str(len(loops))) start = time.time() for loop in loops: res_c_opt = optimized_cy.gaussian(height, center_x, center_y, width_x, width_y, size, data) res_c_opt2 = np.reshape(res_c_opt, (size, size)) print('Time taken base c: ' + str(round(time.time() - start, 3)) + ' s. Loops: ' + str(len(loops)))
24.863636
99
0.680987
f8e0d2b6b1b20d8a2ad970435294443f57d849b0
77
sql
SQL
src/test/resources/sql/create_schema/956732ed.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
66
2018-06-15T11:34:03.000Z
2022-03-16T09:24:49.000Z
src/test/resources/sql/create_schema/956732ed.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
13
2019-03-19T11:56:28.000Z
2020-08-05T04:20:50.000Z
src/test/resources/sql/create_schema/956732ed.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
28
2019-01-05T19:59:02.000Z
2022-03-24T11:55:50.000Z
-- file:rowsecurity.sql ln:1789 expect:true CREATE SCHEMA regress_rls_schema
25.666667
43
0.831169
fb34c0ebf440bd5900c35a920d2ac64f5ab192b8
883
swift
Swift
JASOONTests/Sources/JSON.swift
JulianAlonso/JASOON
8262a878513591637479637635174794fbd1b3e3
[ "MIT" ]
3
2017-06-22T18:24:27.000Z
2017-06-23T15:45:46.000Z
JASOONTests/Sources/JSON.swift
JulianAlonso/JASOON
8262a878513591637479637635174794fbd1b3e3
[ "MIT" ]
null
null
null
JASOONTests/Sources/JSON.swift
JulianAlonso/JASOON
8262a878513591637479637635174794fbd1b3e3
[ "MIT" ]
1
2017-06-22T21:20:39.000Z
2017-06-22T21:20:39.000Z
// // ParsingTests.swift // JASON // // Created by Julian Parkfy on 21/3/17. // Copyright © 2017 Julian. All rights reserved. // @testable import JASOON import XCTest final class JSONTest: XCTestCase { func testSolvingTypeIsSettedWhenCallingJSONInitializableConstructor() { let data = "Object".data do { let json = try JSON(data) let parsed = try json.create(Test.self) print(parsed.parsingType) XCTAssertTrue(parsed.parsingType.contains("Test"), "parsingType must contain Test object name") } catch { XCTFail("Not expected error: \(error)") } } } fileprivate struct Test { let parsingType: String } extension Test: ExpressibleByJSON { init(_ json: JSON) throws { self.parsingType = json.context?.solvingTypeName ?? "Unknown" } }
22.075
107
0.622877
d7847ec54b383fed61becfedc8ae47faef206b67
4,037
dart
Dart
lib/portfolio_store.dart
adewaleafolabi/portfolio
d2dc401608f147c509e1a798e6a466442c5103b0
[ "Unlicense" ]
null
null
null
lib/portfolio_store.dart
adewaleafolabi/portfolio
d2dc401608f147c509e1a798e6a466442c5103b0
[ "Unlicense" ]
null
null
null
lib/portfolio_store.dart
adewaleafolabi/portfolio
d2dc401608f147c509e1a798e6a466442c5103b0
[ "Unlicense" ]
1
2019-02-27T00:14:01.000Z
2019-02-27T00:14:01.000Z
import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:mobx/mobx.dart'; import 'package:portfolio/service/portfolio_data.dart'; import 'package:portfolio/service/portfolio_service.dart'; import 'package:random_color/random_color.dart'; part 'portfolio_store.g.dart'; class PortfolioStore = _PortfolioStore with _$PortfolioStore; enum PortfolioType { LOGIN, INITIATE_RESET, COMPLETE_RESET } abstract class _PortfolioStore with Store { final PortfolioService portfolioService; @observable Portfolio portfolio; @observable bool loading = false; @observable bool sortAscending = true; @observable List<PortfolioData> selected = []; @observable Map<String, double> prices = {}; _PortfolioStore(this.portfolioService); @action Future<void> load() async { this.loading = true; portfolio = await portfolioService.load(); if (portfolio == null) { this.loading = false; return; } var dp = await portfolioService.fetchPrices(portfolio.data, 'CAD'); print(portfolioService.calculate(portfolio, dp).data); setPortfolio(portfolioService.calculate(portfolio, dp)); this.loading = false; } @action void setPrices(Map<String, double> value) => prices = value; @action void setPortfolio(Portfolio value) => portfolio = value; @action void addToSelected(PortfolioData value) { var temp = selected; temp.add(value); this.selected = temp; } @action void setSortAscending(bool value) => sortAscending = value; @action void setLoading(bool value) => loading = value; @action Future refreshPortfolio() async { loading = true; this.prices = await portfolioService.fetchPrices(portfolio.data, 'CAD'); setPortfolio(portfolioService.calculate(portfolio, prices)); loading = false; } @action Future<Null> futureRefreshPortfolio() async { this.refreshPortfolio(); } @action void toggleSelect(PortfolioData value) { if (this.selected.contains(value)) { this.selected.remove(value); this.selected = this.selected; //force state change return; } this.selected.add(value); this.selected = this.selected; //force state change } @action void deleteUsingSelected() { this.loading = false; this.portfolio.data.removeWhere((item) => selected.contains(item)); this.selected = []; portfolioService.save(this.portfolio); this.portfolio = this.portfolio; this.loading = true; } @action void deleteDataItem(PortfolioData value) { this.loading = true; this.portfolio.data.remove(value); portfolioService.save(this.portfolio); this.portfolio = this.portfolio; this.loading = false; } @action void createPortfolio(Portfolio portfolio){ print('create portfoliko called'); this.loading = true; this.portfolioService.save(portfolio); this.portfolio = portfolio; this.refreshPortfolio(); this.loading = false; print('create portfoliko ended'); } @action void saveDataItem(PortfolioData value) { if(value.code == null){ throw UnsupportedError("data code is null"); } this.loading = true; if (this.portfolio.data.contains(value)) { this.portfolio.data.remove(value); } this.portfolio.data.add(value); portfolioService.save(this.portfolio); this.portfolio = this.portfolio; this.loading = false; } @computed List<Color> get colors => RandomColor().randomColors(count: portfolio.data.length); bool isSelected(PortfolioData data) => this.selected.contains(data); @action void sort(int col, bool ascending) { setSortAscending(ascending); switch (col) { case 1: this.portfolio.data.sort((a, b) => ascending ? a.amount.compareTo(b.amount) : b.amount.compareTo(a.amount)); break; case 2: this.portfolio.data.sort((a, b) => ascending ? a.value.compareTo(b.value) : b.value.compareTo(a.value)); break; } } }
26.045161
76
0.681447
f173bb64946a53642caa87c14b75b23a0c3972b1
487
rb
Ruby
lib/uiza/api_operation/list.rb
uizaio/api-wrapper-ruby
b0dee726769674f9076dbcba7a2f43f49375516f
[ "MIT" ]
null
null
null
lib/uiza/api_operation/list.rb
uizaio/api-wrapper-ruby
b0dee726769674f9076dbcba7a2f43f49375516f
[ "MIT" ]
null
null
null
lib/uiza/api_operation/list.rb
uizaio/api-wrapper-ruby
b0dee726769674f9076dbcba7a2f43f49375516f
[ "MIT" ]
10
2019-02-11T04:37:56.000Z
2019-10-25T08:38:36.000Z
module Uiza module APIOperation module List def list params = {} url = "https://#{Uiza.workspace_api_domain}/api/public/#{Uiza.api_version}/#{self::OBJECT_API_PATH}" method = :get headers = {"Authorization" => Uiza.authorization} params["id"] = "" if self == Uiza::User uiza_client = UizaClient.new url, method, headers, params, self::OBJECT_API_DESCRIPTION_LINK[:list] uiza_client.execute_request end end end end
30.4375
108
0.64271
1a2f56cf093b461b930e93a13c1778c2f4a7b13d
1,915
py
Python
image_visualizer.py
bokachsub/CarNDPY
e828427e96dbd1053478f33945eedc57007aed56
[ "MIT" ]
null
null
null
image_visualizer.py
bokachsub/CarNDPY
e828427e96dbd1053478f33945eedc57007aed56
[ "MIT" ]
null
null
null
image_visualizer.py
bokachsub/CarNDPY
e828427e96dbd1053478f33945eedc57007aed56
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt import math, cv2, glob import numpy as np class ImageVisualizer: # region vars # endregion def __init__(self, shape): self.shape = shape # to get a name of parameter variable to print a name in subplot def param_to_str(self, obj, namespace): return [name for name in namespace if namespace[name] is obj] # tool to draw multiple images on plot def plot_images(self, images, descriptions = None, invert_colors=False): w = self.shape[0] h = self.shape[1] fig = plt.figure(figsize=(8, 8)) total_images = len(images) rows = math.ceil(total_images/3) columns = math.ceil(total_images/rows) for i in range(1, total_images + 1): fig.add_subplot(rows, columns, i) if invert_colors and len(images[i-1].shape) > 2: plt.imshow(cv2.cvtColor(images[i-1], cv2.COLOR_BGR2RGB)) # need to invert colors else: plt.imshow(images[i-1]) # do not need to invert colors when showing binary images #plt.gca().set_title(self.param_to_str(images[i-1], globals())) if not descriptions is None: plt.gca().set_title(descriptions[i-1]) mng = plt.get_current_fig_manager() # to maximize window mng.window.state('zoomed') plt.show() def get_image_info(self, image, alias ): print(f'Image {alias} shape is: {image.shape}') # tests solid green area on blank image def draw_solid_area_on_blank_image(self, array_of_points): blank_image = np.zeros(self.shape, dtype=np.uint8) cv2.fillPoly(blank_image, pts = [array_of_points],color = (255,255,0)) return blank_image def overlay_image_with_solid_area(self, main_image, image2): return cv2.addWeighted(main_image, 0.8, image2, 0.2, 0)
39.081633
97
0.627676
b0735c56d325e97b0fcfbc78aa1c07a7c7c45ee9
637
py
Python
openstates/openstates-master/scripts/tn_109fix/tnfix.py
Jgorsick/Advocacy_Angular
8906af3ba729b2303880f319d52bce0d6595764c
[ "CC-BY-4.0" ]
null
null
null
openstates/openstates-master/scripts/tn_109fix/tnfix.py
Jgorsick/Advocacy_Angular
8906af3ba729b2303880f319d52bce0d6595764c
[ "CC-BY-4.0" ]
null
null
null
openstates/openstates-master/scripts/tn_109fix/tnfix.py
Jgorsick/Advocacy_Angular
8906af3ba729b2303880f319d52bce0d6595764c
[ "CC-BY-4.0" ]
null
null
null
import sys import plop import pymongo def main(state): db = pymongo.MongoClient().fiftystates index = plop.Index() spec = dict(state=state) print('adding bills') for bill in db.bills.find(spec): index.add_object(bill) print('adding legislators') for obj in db.legislators.find(spec): index.add_object(obj) print('adding committees') for obj in db.committees.find(spec): index.add_object(obj) print('adding votes') for obj in db.votes.find(spec): index.add_object(obj) import pdb; pdb.set_trace() if __name__ == "__main__": main(*sys.argv[1:])
19.30303
42
0.643642
259b0e7dc3f841136ee3f6cdaa37d44eb50a9da3
1,112
dart
Dart
lib/screens/explore/widgets/create_your_own_activity_button.dart
StefanSuess/Bsc-Project-Aiya
f7f1af8faa7b45260b5a8f3cc4c81bc6446e8d82
[ "MIT" ]
null
null
null
lib/screens/explore/widgets/create_your_own_activity_button.dart
StefanSuess/Bsc-Project-Aiya
f7f1af8faa7b45260b5a8f3cc4c81bc6446e8d82
[ "MIT" ]
null
null
null
lib/screens/explore/widgets/create_your_own_activity_button.dart
StefanSuess/Bsc-Project-Aiya
f7f1af8faa7b45260b5a8f3cc4c81bc6446e8d82
[ "MIT" ]
1
2021-06-07T17:13:00.000Z
2021-06-07T17:13:00.000Z
import 'package:Aiya/constants.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:getwidget/components/button/gf_button.dart'; import 'package:getwidget/size/gf_size.dart'; import 'package:getwidget/types/gf_button_type.dart'; class CreateYourOwnActivityButton extends StatefulWidget { @override _CreateYourOwnActivityButtonState createState() => _CreateYourOwnActivityButtonState(); } class _CreateYourOwnActivityButtonState extends State<CreateYourOwnActivityButton> { @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ SizedBox( child: GFButton( size: GFSize.LARGE, text: 'Create Your Own Activity', icon: Icon( FontAwesomeIcons.plus, color: Theme.of(context).accentColor, ), onPressed: () { Navigator.of(context).pushNamed(constants.createRoute); }, type: GFButtonType.outline2x, )), ], ); } }
29.263158
67
0.676259
0d75bc34193484867af80738c9d8ae6345c74b7c
3,368
cs
C#
ICSharpCode.SharpDevelop.Dom/Src/DiffUtility.cs
jbuedel/AgentRalphPlugin
0a81a948ffc425f3e38713766a6f1577ac9e6376
[ "BSD-3-Clause" ]
6
2015-03-05T06:00:59.000Z
2015-05-11T07:26:28.000Z
ICSharpCode.SharpDevelop.Dom/Src/DiffUtility.cs
jbuedel/AgentRalphPlugin
0a81a948ffc425f3e38713766a6f1577ac9e6376
[ "BSD-3-Clause" ]
4
2015-01-22T20:38:16.000Z
2017-02-22T13:34:26.000Z
ICSharpCode.SharpDevelop.Dom/Src/DiffUtility.cs
jbuedel/AgentRalphPlugin
0a81a948ffc425f3e38713766a6f1577ac9e6376
[ "BSD-3-Clause" ]
5
2015-04-03T14:12:57.000Z
2021-05-20T06:06:08.000Z
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/> // <version>$Revision: 1661 $</version> // </file> using System; using System.Collections; using System.Collections.Generic; namespace ICSharpCode.SharpDevelop.Dom { public static class DiffUtility { public static int GetAddedItems(IList original, IList changed, IList result) { return GetAddedItems(original, changed, result, Comparer.Default); } public static int GetAddedItems(IList original, IList changed, IList result, IComparer comparer) { int count = 0; if(changed != null && result != null) { if(original == null) { foreach(object item in changed) { result.Add(item); } count = changed.Count; } else { foreach(object item in changed) { if(!Contains(original, item, comparer)) { result.Add(item); count++; } } } } return count; } public static int GetRemovedItems(IList original, IList changed, IList result) { return GetRemovedItems(original, changed, result, Comparer.Default); } public static int GetRemovedItems(IList original, IList changed, IList result, IComparer comparer) { return GetAddedItems(changed, original, result, comparer); } static bool Contains(IList list, object value, IComparer comparer) { foreach(object item in list) { if(0 == comparer.Compare(item, value)) { return true; } } return false; } static public int Compare(IList a, IList b) { return Compare(a, b, Comparer.Default); } static public int Compare<T>(IList<T> a, IList<T> b) { return Compare(a, b, Comparer.Default); } static public int Compare<T>(IList<T> a, IList<T> b, IComparer comparer) { if (a == null || b == null) { return 1; } if (a.Count != b.Count) { return Math.Sign(a.Count - b.Count); } int limit = (a.Count < b.Count) ? a.Count : b.Count; for(int i=0; i < limit; i++) { if (a[i] is IComparable && b[i] is IComparable) { int cmp = comparer.Compare(a[i], b[i]); if (cmp != 0) { return cmp; } } } return a.Count - b.Count; } static public int Compare(IList a, IList b, IComparer comparer) { if (a == null || b == null) { return 1; } if (a.Count != b.Count) { return Math.Sign(a.Count - b.Count); } int limit = (a.Count < b.Count) ? a.Count : b.Count; for(int i=0; i < limit; i++) { if (a[i] is IComparable && b[i] is IComparable) { int cmp = comparer.Compare(a[i], b[i]); if (cmp != 0) { return cmp; } } } return a.Count - b.Count; } static public int Compare(SortedList a, SortedList b) { return Compare(a, b, Comparer.Default); } static public int Compare(SortedList a, SortedList b, IComparer comparer) { if (a == null || b == null) { return 1; } int cmp; int limit = (a.Count < b.Count) ? a.Count : b.Count; for(int i=0; i < limit; i++) { if(0 != (cmp = comparer.Compare(a.GetByIndex(i), b.GetByIndex(i)))) { return cmp; } } return a.Count - b.Count; } } }
25.134328
101
0.5769
3952109feb06649c8830b9151ef3e96a63918193
1,043
py
Python
cm_lex/Generate.py
UKPLab/acl2021-metaphor-generation-conceptual
2db0c927ad2e89792030dbdcf0eddd78e18d8e85
[ "Apache-2.0" ]
6
2021-05-25T13:15:13.000Z
2022-01-05T06:15:26.000Z
cm_lex/Generate.py
UKPLab/acl2021-metaphor-generation-conceptual
2db0c927ad2e89792030dbdcf0eddd78e18d8e85
[ "Apache-2.0" ]
3
2021-07-25T23:17:29.000Z
2021-09-26T14:00:23.000Z
cm_lex/Generate.py
UKPLab/acl2021-metaphor-generation-conceptual
2db0c927ad2e89792030dbdcf0eddd78e18d8e85
[ "Apache-2.0" ]
1
2021-09-07T12:03:18.000Z
2021-09-07T12:03:18.000Z
import sys, getopt from LexicalReplacement import LexicalReplacement from ModelTesting import Test config = {"mappings":"../mappings/w2v_50.json", "embeddings":"../models/w2v_50"} def text_to_tests(texts): for line in texts: yield Test.from_tsv(line) def generate(model, texts): tests = text_to_tests(texts) for t in tests: print(model.generate_test(t)) def main(argv=None): if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], "hm:e:", ["help", "mappings", "embeddings"]) except Exception as e: print ("Error in args : " + str(argv[1:])) print (e) return 2 for o in opts: if o[0] == "-m": config["mappings"] = o[1] if o[0] == "-e": config["embeddings"] = o[1] model = LexicalReplacement(config["mappings"], config["embeddings"]) texts = [t.split("\t") for t in open(args[0]).readlines()] generate(model, texts) if __name__ == "__main__": main()
21.285714
89
0.580058
200864ff829de5b9fcb14d779a385acc6889742b
1,946
py
Python
bricks/mortar/rpcapi.py
CloudBrewery/bricks-service
e905c324b062bfd8a8b3917c788849ea0d497e54
[ "Apache-1.1" ]
null
null
null
bricks/mortar/rpcapi.py
CloudBrewery/bricks-service
e905c324b062bfd8a8b3917c788849ea0d497e54
[ "Apache-1.1" ]
null
null
null
bricks/mortar/rpcapi.py
CloudBrewery/bricks-service
e905c324b062bfd8a8b3917c788849ea0d497e54
[ "Apache-1.1" ]
null
null
null
""" Client side of the conductor RPC API. """ from oslo.config import cfg from bricks.objects import base as objects_base import bricks.openstack.common.rpc.proxy cfg.CONF.set_default('allowed_rpc_exception_modules', ['bricks.common.exception', 'exceptions', ]) class MortarAPI(bricks.openstack.common.rpc.proxy.RpcProxy): """The Mortar messaging API API version history: 1.0 - Initial version. """ RPC_API_VERSION = '1.0' def __init__(self, topic=None): topic = topic if topic else 'bricks.mortar_manager' super(MortarAPI, self).__init__( topic=topic, serializer=objects_base.BricksObjectSerializer(), default_version=self.RPC_API_VERSION) def do_ping(self, context, topic=None): self.fanout_cast( context, self.make_msg('process_notification', notification={'event_type': 'ping'}), topic=topic or self.topic) def do_execute(self, context, execution_task, topic=None): self.fanout_cast( context, self.make_msg('do_execute', execution_task=execution_task), topic=topic or self.topic) def do_check_instances(self, context, instance_list, topic=None): self.fanout_cast( context, self.make_msg('do_check_instances', instance_list=instance_list), topic=topic or self.topic) def do_check_last_task(self, context, instance_id, topic=None): self.cast( context, self.make_msg('do_check_last_task', instance_id=instance_id), topic=topic or self.topic) def do_tail_brick_log(self, context, brick_log, topic=None): return self.call( context, self.make_msg('do_tail_brick_log', brick_log=brick_log), topic=topic or self.topic)
29.938462
77
0.621788
52590f89663923f9e4ca3a93fc3979d1e65d89d8
14,665
swift
Swift
Tests/ImagePipelineCacheTests.swift
b9software/Nuke
32d188fbac904ad273495dbfcd501fea569a4a2b
[ "MIT" ]
6,940
2015-03-17T11:53:13.000Z
2022-03-31T19:00:42.000Z
Tests/ImagePipelineCacheTests.swift
b9software/Nuke
32d188fbac904ad273495dbfcd501fea569a4a2b
[ "MIT" ]
416
2015-06-25T10:00:27.000Z
2022-03-30T12:48:46.000Z
Tests/ImagePipelineCacheTests.swift
b9software/Nuke
32d188fbac904ad273495dbfcd501fea569a4a2b
[ "MIT" ]
531
2015-06-25T04:49:35.000Z
2022-03-31T03:59:16.000Z
// The MIT License (MIT) // // Copyright (c) 2015-2021 Alexander Grebenyuk (github.com/kean). import XCTest @testable import Nuke class ImagePipelineCacheTests: XCTestCase { var memoryCache: MockImageCache! var diskCache: MockDataCache! var dataLoader: MockDataLoader! var pipeline: ImagePipeline! var cache: ImagePipeline.Cache { pipeline.cache } override func setUp() { super.setUp() dataLoader = MockDataLoader() diskCache = MockDataCache() memoryCache = MockImageCache() pipeline = ImagePipeline { $0.dataLoader = dataLoader $0.imageCache = memoryCache $0.dataCache = diskCache } } // MARK: Subscripts func testSubscript() { // GIVEN cache[Test.request] = Test.container // THEN XCTAssertNotNil(cache[Test.request]) } func testDisableMemoryCacheRead() { // GIVEN cache[Test.request] = Test.container let request = ImageRequest(url: Test.url, options: [.disableMemoryCacheReads]) // THEN XCTAssertNil(cache[request]) } func testDisableMemoryCacheWrite() { // GIVEN let request = ImageRequest(url: Test.url, options: [.disableMemoryCacheWrites]) cache[request] = Test.container // THEN XCTAssertNil(cache[Test.request]) } func testSubscriptRemove() { // GIVEN cache[Test.request] = Test.container // WHEN cache[Test.request] = nil // THEN XCTAssertNil(cache[Test.request]) } func testSubscriptStoringPreviewWhenDisabled() { // GIVEN pipeline = pipeline.reconfigured { $0.isStoringPreviewsInMemoryCache = false } // WHEN cache[Test.request] = ImageContainer(image: Test.image, isPreview: true) // THEN XCTAssertNil(cache[Test.request]) } func testSubscriptStoringPreviewWhenEnabled() throws { // GIVEN pipeline = pipeline.reconfigured { $0.isStoringPreviewsInMemoryCache = true } // WHEN cache[Test.request] = ImageContainer(image: Test.image, isPreview: true) // THEN let response = try XCTUnwrap(cache[Test.request]) XCTAssertTrue(response.isPreview) } func testSubscriptWhenNoImageCache() { // GIVEN pipeline = pipeline.reconfigured { $0.imageCache = nil } cache[Test.request] = Test.container // THEN XCTAssertNil(cache[Test.request]) } func testSubscriptWithRealImageCache() { // GIVEN pipeline = pipeline.reconfigured { $0.imageCache = ImageCache() } cache[Test.request] = Test.container // THEN XCTAssertNotNil(cache[Test.request]) } // MARK: Cached Image func testGetCachedImageDefaultFromMemoryCache() { // GIVEN let request = Test.request memoryCache[cache.makeImageCacheKey(for: request)] = Test.container // WHEN let image = cache.cachedImage(for: request) // THEN XCTAssertNotNil(image) } func testGetCachedImageDefaultFromDiskCache() { // GIVEN let request = Test.request diskCache.storeData(Test.data, for: cache.makeDataCacheKey(for: request)) // WHEN let image = cache.cachedImage(for: request) // THEN XCTAssertNotNil(image) } func testGetCachedImageDefaultFromDiskCacheWhenOptionEnabled() { // GIVEN let request = Test.request diskCache.storeData(Test.data, for: cache.makeDataCacheKey(for: request)) // WHEN let image = cache.cachedImage(for: request, caches: [.disk]) // THEN returns nil because queries only memory cache by default XCTAssertNotNil(image) } func testGetCachedImageDefaultNotStored() { // GIVEN let request = Test.request // WHEN let image = cache.cachedImage(for: request) // THEN XCTAssertNil(image) } func testGetCachedImageDefaultFromMemoryCacheWhenCachePolicyPreventsLookup() { // GIVEN var request = Test.request memoryCache[cache.makeImageCacheKey(for: request)] = Test.container // WHEN request.options = [.reloadIgnoringCachedData] let image = cache.cachedImage(for: request) // THEN XCTAssertNil(image) } func testGetCachedImageDefaultFromDiskCacheWhenCachePolicyPreventsLookup() { // GIVEN var request = Test.request diskCache.storeData(Test.data, for: cache.makeDataCacheKey(for: request)) // WHEN request.options = [.reloadIgnoringCachedData] let image = cache.cachedImage(for: request, caches: [.disk]) // THEN XCTAssertNil(image) } func testGetCachedImageOnlyFromMemoryStoredInMemory() { // GIVEN let request = Test.request memoryCache[cache.makeImageCacheKey(for: request)] = Test.container // WHEN let image = cache.cachedImage(for: request, caches: [.memory]) // THEN XCTAssertNotNil(image) } func testGetCachedImageOnlyFromMemoryStoredOnDisk() { // GIVEN let request = Test.request diskCache.storeData(Test.data, for: cache.makeDataCacheKey(for: request)) // WHEN let image = cache.cachedImage(for: request, caches: [.memory]) // THEN XCTAssertNil(image) } func testDisableDiskCacheReads() { // GIVEN cache.storeCachedData(Test.data, for: Test.request) let request = ImageRequest(url: Test.url, options: [.disableDiskCacheReads]) // THEN XCTAssertNil(cache.cachedData(for: request)) } func testDisableDiskCacheWrites() { // GIVEN let request = ImageRequest(url: Test.url, options: [.disableDiskCacheWrites]) cache.storeCachedData(Test.data, for: request) // THEN XCTAssertNil(cache.cachedData(for: Test.request)) } func testGetCachedImageWhenNoDecoder() { // GIVEN pipeline = pipeline.reconfigured { $0.makeImageDecoder = { _ in nil } } cache.storeCachedData(Test.data, for: Test.url) // THEM XCTAssertNil(cache.cachedImage(for: Test.url, caches: [.disk])) } // MARK: Store Cached Image func testStoreCachedImageMemoryCache() { // WHEN let request = Test.request cache.storeCachedImage(Test.container, for: request) // THEN XCTAssertNotNil(cache.cachedImage(for: request)) XCTAssertNotNil(memoryCache[cache.makeImageCacheKey(for: request)]) XCTAssertNotNil(cache.cachedImage(for: request, caches: [.disk])) XCTAssertNotNil(diskCache.cachedData(for: cache.makeDataCacheKey(for: request))) } func testStoreCachedImageInDiskCache() { // WHEN let request = Test.request cache.storeCachedImage(Test.container, for: request, caches: [.disk]) // THEN XCTAssertNotNil(cache.cachedImage(for: request)) XCTAssertNil(memoryCache[cache.makeImageCacheKey(for: request)]) XCTAssertNotNil(cache.cachedImage(for: request, caches: [.disk])) XCTAssertNotNil(diskCache.cachedData(for: cache.makeDataCacheKey(for: request))) } func testStoreCachedImageInBothLayers() { // WHEN let request = Test.request cache.storeCachedImage(Test.container, for: request, caches: [.memory, .disk]) // THEN XCTAssertNotNil(cache.cachedImage(for: request)) XCTAssertNotNil(memoryCache[cache.makeImageCacheKey(for: request)]) XCTAssertNotNil(cache.cachedImage(for: request, caches: [.disk])) XCTAssertNotNil(diskCache.cachedData(for: cache.makeDataCacheKey(for: request))) } // MARK: Cached Data func testStoreCachedData() { // WHEN let request = Test.request cache.storeCachedData(Test.data, for: request) // THEN XCTAssertNotNil(cache.cachedImage(for: request)) XCTAssertNil(memoryCache[cache.makeImageCacheKey(for: request)]) XCTAssertNotNil(cache.cachedImage(for: request, caches: [.disk])) XCTAssertNotNil(diskCache.cachedData(for: cache.makeDataCacheKey(for: request))) } func testStoreCacheImageWhenMemoryCacheWriteDisabled() { // WHEN var request = Test.request request.options.insert(.disableMemoryCacheWrites) cache.storeCachedImage(Test.container, for: request, caches: [.memory]) // THEN XCTAssertNil(cache.cachedImage(for: request)) XCTAssertNil(memoryCache[cache.makeImageCacheKey(for: request)]) XCTAssertNil(cache.cachedImage(for: request, caches: [.disk])) XCTAssertNil(diskCache.cachedData(for: cache.makeDataCacheKey(for: request))) } func testStoreCacheDataWhenNoDataCache() { // GIVEN pipeline = pipeline.reconfigured { $0.dataCache = nil } // WHEN cache.storeCachedData(Test.data, for: Test.request) // THEN just make sure it doesn't do anything weird XCTAssertNil(cache.cachedData(for: Test.request)) } func testGetCachedDataWhenNoDataCache() { // GIVEN pipeline = pipeline.reconfigured { $0.dataCache = nil } // THEN just make sure it doesn't do anything weird XCTAssertNil(cache.cachedData(for: Test.request)) cache.removeCachedData(for: Test.request) } // MARK: Contains func testContainsWhenStoredInMemoryCache() { // GIVEN cache.storeCachedImage(Test.container, for: Test.request, caches: [.memory]) // WHEN/THEN XCTAssertTrue(cache.containsCachedImage(for: Test.request)) XCTAssertTrue(cache.containsCachedImage(for: Test.request, caches: [.all])) XCTAssertTrue(cache.containsCachedImage(for: Test.request, caches: [.memory])) XCTAssertFalse(cache.containsCachedImage(for: Test.request, caches: [.disk])) } func testContainsWhenStoredInDiskCache() { // GIVEN cache.storeCachedImage(Test.container, for: Test.request, caches: [.disk]) // WHEN/THEN XCTAssertTrue(cache.containsCachedImage(for: Test.request)) XCTAssertTrue(cache.containsCachedImage(for: Test.request, caches: [.all])) XCTAssertFalse(cache.containsCachedImage(for: Test.request, caches: [.memory])) XCTAssertTrue(cache.containsCachedImage(for: Test.request, caches: [.disk])) } func testsContainsStoredInBoth() { // GIVEN cache.storeCachedImage(Test.container, for: Test.request, caches: [.all]) // WHEN/THEN XCTAssertTrue(cache.containsCachedImage(for: Test.request)) XCTAssertTrue(cache.containsCachedImage(for: Test.request, caches: [.all])) XCTAssertTrue(cache.containsCachedImage(for: Test.request, caches: [.memory])) XCTAssertTrue(cache.containsCachedImage(for: Test.request, caches: [.disk])) } func testContainsData() { // GIVEN cache.storeCachedImage(Test.container, for: Test.request, caches: [.disk]) // WHEN/THEN XCTAssertTrue(cache.containsData(for: Test.request)) } func testContainsDataWithNoDataCache() { // GIVEN pipeline = pipeline.reconfigured { $0.dataCache = nil } // WHEN/THEN XCTAssertFalse(cache.containsData(for: Test.request)) } // MARK: Remove func testRemoveFromMemoryCache() { // GIVEN let request = Test.request cache.storeCachedImage(Test.container, for: request) // WHEN cache.removeCachedImage(for: request) // THEN XCTAssertNil(cache.cachedImage(for: request)) XCTAssertNil(memoryCache[cache.makeImageCacheKey(for: request)]) XCTAssertNil(memoryCache[cache.makeImageCacheKey(for: Test.url)]) } func testRemoveFromDiskCache() { // GIVEN let request = Test.request cache.storeCachedImage(Test.container, for: request, caches: [.disk]) // WHEN cache.removeCachedImage(for: request, caches: [.disk]) // THEN XCTAssertNil(cache.cachedImage(for: request, caches: [.disk])) XCTAssertNil(diskCache.cachedData(for: cache.makeDataCacheKey(for: request))) XCTAssertNil(diskCache.cachedData(for: cache.makeDataCacheKey(for: Test.url))) } func testRemoveFromAllCaches() { // GIVEN let request = Test.request cache.storeCachedImage(Test.container, for: request, caches: [.memory, .disk]) // WHEN cache.removeCachedImage(for: request, caches: [.memory, .disk]) // THEN XCTAssertNil(cache.cachedImage(for: request)) XCTAssertNil(memoryCache[cache.makeImageCacheKey(for: request)]) XCTAssertNil(cache.cachedImage(for: request, caches: [.disk])) XCTAssertNil(diskCache.cachedData(for: cache.makeDataCacheKey(for: request))) } // MARK: Remove All func testRemoveAll() { // GIVEM let request = Test.request cache.storeCachedImage(Test.container, for: request, caches: [.memory, .disk]) // WHEN cache.removeAll() // THEN XCTAssertNil(cache.cachedImage(for: request)) XCTAssertNil(memoryCache[cache.makeImageCacheKey(for: request)]) XCTAssertNil(cache.cachedImage(for: request, caches: [.disk])) XCTAssertNil(diskCache.cachedData(for: cache.makeDataCacheKey(for: request))) } func testRemoveAllWithAllStatic() { // GIVEM let request = Test.request cache.storeCachedImage(Test.container, for: request, caches: [.all]) // WHEN cache.removeAll() // THEN XCTAssertNil(cache.cachedImage(for: request)) XCTAssertNil(memoryCache[cache.makeImageCacheKey(for: request)]) XCTAssertNil(cache.cachedImage(for: request, caches: [.disk])) XCTAssertNil(diskCache.cachedData(for: cache.makeDataCacheKey(for: request))) } // MARK: ImageRequestConvertible func testMakeSureAllAPIsAreAvailable() { cache["https://example.com/image.jpeg"] = nil cache[URL(string: "https://example.com/image.jpeg")!] = nil cache[URLRequest(url: URL(string: "https://example.com/image.jpeg")!)] = nil cache[ImageRequest(url: URL(string: "https://example.com/image.jpeg")!)] = nil } }
30.488565
88
0.6373
4cffef23ff14bd4681cca1472a6ec291126b10af
9,518
py
Python
notebooks/0.1_SVM_Multiclass_Approach.py
AlessandroVol23/kdd-cup-2019
7f140d1d6213dc0d05d07a2c8bff9fe949b72ed8
[ "MIT" ]
10
2019-07-24T19:14:59.000Z
2022-01-04T06:35:27.000Z
notebooks/0.1_SVM_Multiclass_Approach.py
AlessandroVol23/kdd-cup-2019
7f140d1d6213dc0d05d07a2c8bff9fe949b72ed8
[ "MIT" ]
2
2020-07-02T15:53:45.000Z
2020-07-29T04:40:33.000Z
notebooks/0.1_SVM_Multiclass_Approach.py
AlessandroVol23/kdd-cup-2019
7f140d1d6213dc0d05d07a2c8bff9fe949b72ed8
[ "MIT" ]
8
2019-07-21T20:05:09.000Z
2021-12-28T03:03:40.000Z
# -*- coding: utf-8 -*- """ Created on Fri May 10 15:07:36 2019 @author: kuche_000 Multiclass Baselinemodels - KDD Cup """ # Packages import pandas as pd import numpy as np import sklearn.svm import sklearn.metrics as metrics import sklearn.tree import sklearn.ensemble import time import os import pickle from sklearn import svm from sklearn.model_selection import KFold from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier # Load the preprocessed data data = pd.read_pickle("data/processed/data_set_phase") # --- (1) --- """ Clean the DF: - each session should only offer one possibility for each transportation - if there are twice possibilities for the same transportation mode [e.g. twice possible connections with transportation mode "1"] only keep the first one! - checked couple of these secenarios, the ones offerd later, always worse in time or/and money... [reasonable sorted already] """ data_clean = data.drop_duplicates(["sid", "transport_mode"]) # --- (2) --- """ Create DF to train Multiclass with: - Each row one Session-ID - to each Session ID the transport specific cost/ time/ distance in a row [cost_1, ..., cost_11 -> cost for each transportation mode in an own col] - Non offered transport modes "NaN" [can be replaced later on] """ # Function to extract Information fromk data_clean [created above^] def create_multiclass_df(indeces, DF_name): """ Function to extraxt the transport specific distances/ costs/ times. Add them all to "df_" and save it as pickle Args: - indeces (list) : list of integers with all session IDs we want to extract [need to be in data_clean] - DF_name (str) : Addtion to the Name the DF shall be safed in [e.g. "2" --> "SVM_DF_2"] Return: - DF (pandas) : Dataframe with a column for each transpotationmode specific Distance/Time/Cost [Distance_1, ..., Distance_11, Time_1, ...,Time_11, Cost_1, ..., Cost_11] """ df_ = pd.DataFrame(columns = ["Distance_1", "Distance_2", "Distance_3", "Distance_4", "Distance_5", "Distance_6", "Distance_7", "Distance_8", "Distance_9", "Distance_10", "Distance_11", "Time_1", "Time_2", "Time_3", "Time_4", "Time_5", "Time_6", "Time_7", "Time_8", "Time_9", "Time_10", "Time_11", "Cost_1", "Cost_2", "Cost_3", "Cost_4", "Cost_5", "Cost_6", "Cost_7", "Cost_8", "Cost_9", "Cost_10", "Cost_11"]) # Loop over all SID and return an longitudinal DF [each transportsession one column] counter = 0 for index in indeces: # print the process: counter += 1 if counter % 100 == 0: print(str(counter) + " / " + str(len(indeces))) # get all rows with the same Index (same session): current_sess = data_clean.loc[data_clean["sid"] == index] # Get all offered transportation modes: possible_trans_modes = current_sess["transport_mode"].values # Create Dict to add it to the DF values_to_add = {} # Add all possible transportmodes specific times/ costs/ distances to df_ for i in possible_trans_modes: values_to_add["Distance_" + str(i)] = current_sess.loc[current_sess["transport_mode"] == i]["distance_plan"].values[0] values_to_add["Cost_" + str(i)] = current_sess.loc[current_sess["transport_mode"] == i]["price"].values[0] values_to_add["Time_" + str(i)] = current_sess.loc[current_sess["transport_mode"] == i]["eta"].values[0] df_ = df_.append(values_to_add, ignore_index=True) # Add the SessionIDs & save the Preprocessed DF: df_["SID"] = indeces df_.to_pickle("data/processed/SVM_Approach/SubDFs/SVM_DF_" + DF_name) # ---- Start extracting all the information for all Data-Points! -------------- # Extract all unqiue session ids [for 10k about 617seconds] unique_session_ids = data_clean["sid"].unique() # Loop over all SessionIDs, save the results from time to time! j = 0 for i in range(25000, len(unique_session_ids), 25000): # Print the current Range we're working on: print("from: "+ str(j) + " to " + str(i)) # Do the Trasnforming create_multiclass_df(unique_session_ids[j:i], str(i / 25000)) # update Indices j = i # Last Part: create_multiclass_df(unique_session_ids[450000:len(unique_session_ids)], "_19.0") # Create one big DF from all sub_DFs! ----------------------------------------- df_all = pd.read_pickle("data/processed/SVM_Approach/SubDFs/SVM_DF_1.0") for i in range(2, 20, 1): # Create Filename, based on the current number! file_number = str(i) file_name = "SVM_DF_" + file_number + ".0" # Read in the current Results: df_current = pd.read_pickle("data/processed/SVM_Approach/SubDFs/" + file_name) # Bind it to the big DF! df_all = pd.concat([df_all, df_current]) # Add the Response: df_all["Response"] = data_clean.drop_duplicates("sid")["click_mode"].values # Save the Files: df_all.to_pickle("data/processed/SVM_Approach/MulticlassTrainSet") data_clean.to_pickle("data/processed/SVM_Approach/data_clean") # Quality Check: df_all.loc[df_all["SID"] == 2101050]["Response"] data_clean.loc[data_clean["sid"] == 2101050]["click_mode"] #------------------------------------------------------------------------------ # Read data in: df_all = pd.read_pickle("data/processed/SVM_Approach/MulticlassTrainSet") data_clean = pd.read_pickle("data/processed/SVM_Approach/data_clean") # --- Add more features to df_ --- # (1) Add the Request time per SID and label it as night or day! req_times_ = data_clean.drop_duplicates("sid")["req_time"] # convert the time to day/night [can be done faster actually...] day_request = [] for i, tt in enumerate(req_times_): time_ = tt.split(" ")[1] if int(time_.split(":")[0]) in [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]: day_request.append(True) else: day_request.append(False) # Add to DF df_all["day_request"] = day_request # subset NA's df_all = df_all.fillna(0) # Extract Features --- feature_names = ['Distance_1','Distance_2','Distance_3','Distance_4','Distance_5', 'Distance_6', 'Distance_7', 'Distance_8', 'Distance_9', 'Distance_10', 'Distance_11','Time_1', 'Time_2', 'Time_3', 'Time_4', 'Time_5', 'Time_6','Time_7','Time_8','Time_9','Time_10','Time_11','Cost_1', 'Cost_2', 'Cost_3','Cost_4','Cost_5','Cost_6','Cost_7','Cost_8', 'Cost_9','Cost_10', 'Cost_11','day_request'] features = df_all[feature_names] response = np.array(df_all["Response"]) # Split Data with 5-fold CV --------------------------------------------------- kf = KFold(n_splits = 5, random_state = 10) kf.get_n_splits(features) # Run 5-fold CV on different predicters, save the results for each # [1] First Tree tree_1 = sklearn.tree.DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=0) test_1_res = [] for train_index, test_index in kf.split(features): tree_1.fit(features.iloc[train_index], response[train_index]) test_1_res.append(sklearn.metrics.f1_score(response[test_index], tree_1.predict(features.iloc[test_index]), average="weighted")) # [2] Second Tree tree_2 = sklearn.tree.DecisionTreeClassifier(criterion='entropy', max_depth=5, random_state=0) tree_2_res = [] for train_index, test_index in kf.split(features): tree_2.fit(features.iloc[train_index], response[train_index]) tree_2_res.append(sklearn.metrics.f1_score(response[test_index], tree_2.predict(features.iloc[test_index]), average="weighted")) # [3] RF_1 forest = sklearn.ensemble.RandomForestClassifier(criterion='entropy', n_estimators=10, random_state=1, n_jobs=2) # Parallelisierung auf 2 Kerne forest_1_res = [] for train_index, test_index in kf.split(features): forest.fit(features.iloc[train_index], response[train_index]) forest_1_res.append(sklearn.metrics.f1_score(response[test_index], forest.predict(features.iloc[test_index]), average="weighted")) # [4] RF_2 forest2 = sklearn.ensemble.RandomForestClassifier(criterion='entropy', n_estimators=15, random_state=1, n_jobs=2) # Parallelisierung auf 2 Kerne forest_2_res = [] for train_index, test_index in kf.split(features): forest2.fit(features.iloc[train_index], response[train_index]) forest_2_res.append(sklearn.metrics.f1_score(response[test_index], forest2.predict(features.iloc[test_index]), average="weighted")) #[5] NN # for NN scale the features scaler = StandardScaler() scaler.fit(features) features_scaled = scaler.transform(features) # Define NN 1 mlp = MLPClassifier(hidden_layer_sizes=(40, 40, 30)) MLP_res = [] for train_index, test_index in kf.split(features): mlp.fit(features_scaled[train_index], response[train_index]) MLP_res.append(sklearn.metrics.f1_score(response[test_index], mlp.predict(features_scaled[test_index]), average="weighted")) # Define NN 2 mlp2 = MLPClassifier(hidden_layer_sizes=(50, 40, 30, 20)) MLP_res2 = [] for train_index, test_index in kf.split(features): mlp2.fit(features_scaled[train_index], response[train_index]) MLP_res2.append(sklearn.metrics.f1_score(response[test_index], mlp2.predict(features_scaled[test_index]), average="weighted"))
34.610909
121
0.673041
c6c64629b86fa3174844343e399fb0565ca845d5
3,672
py
Python
openpifpaf/export_onnx.py
taylormordan/openpifpaf
c516dded6554de51d1126fabb748cdd782993cb1
[ "CC-BY-2.0" ]
null
null
null
openpifpaf/export_onnx.py
taylormordan/openpifpaf
c516dded6554de51d1126fabb748cdd782993cb1
[ "CC-BY-2.0" ]
null
null
null
openpifpaf/export_onnx.py
taylormordan/openpifpaf
c516dded6554de51d1126fabb748cdd782993cb1
[ "CC-BY-2.0" ]
null
null
null
"""Export a checkpoint as an ONNX model. Applies onnx utilities to improve the exported model and also tries to simplify the model with onnx-simplifier. https://github.com/onnx/onnx/blob/master/docs/PythonAPIOverview.md https://github.com/daquexian/onnx-simplifier """ import argparse import logging import shutil import torch import openpifpaf try: import onnx except ImportError: onnx = None try: import onnxsim except ImportError: onnxsim = None LOG = logging.getLogger(__name__) def image_size_warning(basenet_stride, input_w, input_h): if input_w % basenet_stride != 1: LOG.warning( 'input width (%d) should be a multiple of basenet ' 'stride (%d) + 1: closest are %d and %d', input_w, basenet_stride, (input_w - 1) // basenet_stride * basenet_stride + 1, ((input_w - 1) // basenet_stride + 1) * basenet_stride + 1, ) if input_h % basenet_stride != 1: LOG.warning( 'input height (%d) should be a multiple of basenet ' 'stride (%d) + 1: closest are %d and %d', input_h, basenet_stride, (input_h - 1) // basenet_stride * basenet_stride + 1, ((input_h - 1) // basenet_stride + 1) * basenet_stride + 1, ) def apply(model, outfile, verbose=True, input_w=129, input_h=97): image_size_warning(model.base_net.stride, input_w, input_h) # configure openpifpaf.network.heads.CompositeField3.inplace_ops = False dummy_input = torch.randn(1, 3, input_h, input_w) torch.onnx.export( model, dummy_input, outfile, verbose=verbose, input_names=['input_batch'], output_names=['cif', 'caf'], # keep_initializers_as_inputs=True, opset_version=11, do_constant_folding=True, dynamic_axes={ "input": {0: 'dynamic'}, "cif": {0: 'dynamic'}, "caf": {0: 'dynamic'}} ) def check(modelfile): model = onnx.load(modelfile) onnx.checker.check_model(model) def simplify(infile, outfile=None): if outfile is None: assert infile.endswith('.onnx') outfile = infile infile = infile.replace('.onnx', '.unsimplified.onnx') shutil.copyfile(outfile, infile) simplified_model, check_ok = onnxsim.simplify(infile, check_n=3, perform_optimization=False) assert check_ok onnx.save(simplified_model, outfile) class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass def main(): parser = argparse.ArgumentParser( prog='python3 -m openpifpaf.export_onnx', description=__doc__, formatter_class=CustomFormatter, ) parser.add_argument('--version', action='version', version='OpenPifPaf {version}'.format(version=openpifpaf.__version__)) openpifpaf.network.Factory.cli(parser) parser.add_argument('--outfile', default='openpifpaf-resnet50.onnx') parser.add_argument('--simplify', dest='simplify', default=False, action='store_true') parser.add_argument('--check', dest='check', default=False, action='store_true') parser.add_argument('--input-width', type=int, default=129) parser.add_argument('--input-height', type=int, default=97) args = parser.parse_args() openpifpaf.network.Factory.configure(args) model, _ = openpifpaf.network.Factory().factory() apply(model, args.outfile, input_w=args.input_width, input_h=args.input_height) if args.simplify: simplify(args.outfile) if args.check: check(args.outfile) if __name__ == '__main__': main()
29.376
96
0.657952
8e95f97c2e6af8808f7fdfe752ccbbd8fec6e995
375
js
JavaScript
node_modules/@iconify/icons-ic/outline-place.js
kagwicharles/Seniorproject-ui
265956867c8a00063067f03e8772b93f2986c626
[ "MIT" ]
null
null
null
node_modules/@iconify/icons-ic/outline-place.js
kagwicharles/Seniorproject-ui
265956867c8a00063067f03e8772b93f2986c626
[ "MIT" ]
null
null
null
node_modules/@iconify/icons-ic/outline-place.js
kagwicharles/Seniorproject-ui
265956867c8a00063067f03e8772b93f2986c626
[ "MIT" ]
1
2021-09-28T19:15:17.000Z
2021-09-28T19:15:17.000Z
var data = { "body": "<path d=\"M12 12c-1.1 0-2-.9-2-2s.9-2 2-2s2 .9 2 2s-.9 2-2 2zm6-1.8C18 6.57 15.35 4 12 4s-6 2.57-6 6.2c0 2.34 1.95 5.44 6 9.14c4.05-3.7 6-6.8 6-9.14zM12 2c4.2 0 8 3.22 8 8.2c0 3.32-2.67 7.25-8 11.8c-5.33-4.55-8-8.48-8-11.8C4 5.22 7.8 2 12 2z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; exports.__esModule = true; exports.default = data;
46.875
279
0.605333
b357ea7a98b7c2167eb8c26afbfc23ff4e5af43b
1,074
py
Python
user/models.py
farhad0085/django-money-management
d4622192d6b9df3f785abd5f4ef1bfcbf465d045
[ "MIT" ]
null
null
null
user/models.py
farhad0085/django-money-management
d4622192d6b9df3f785abd5f4ef1bfcbf465d045
[ "MIT" ]
null
null
null
user/models.py
farhad0085/django-money-management
d4622192d6b9df3f785abd5f4ef1bfcbf465d045
[ "MIT" ]
null
null
null
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from common.currencies import CURRENCIES class UserProfile(models.Model): """User profile for extending default django User model""" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile") full_name = models.CharField(max_length=60, blank=True, null=True) phone_number = models.CharField(null=True, max_length=15) profile_picture = models.ImageField(upload_to="%Y/%B/%d/images/dp") currency = models.CharField(max_length=20, choices=CURRENCIES, default='USD', blank=True) def __str__(self): return self.user.username # signals @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): """create profile for user.""" if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.user_profile.save()
35.8
93
0.755121
6d6b3fa571c4663b26573794b41061cd77889473
322
h
C
Sample application/iPhone/MobiPrint/StoresDownloadHandler.h
nanzhiwen666/thesis-code
fa7b8ef9c83e8437efdf5b4dd829049b49fed095
[ "CC-BY-3.0" ]
null
null
null
Sample application/iPhone/MobiPrint/StoresDownloadHandler.h
nanzhiwen666/thesis-code
fa7b8ef9c83e8437efdf5b4dd829049b49fed095
[ "CC-BY-3.0" ]
null
null
null
Sample application/iPhone/MobiPrint/StoresDownloadHandler.h
nanzhiwen666/thesis-code
fa7b8ef9c83e8437efdf5b4dd829049b49fed095
[ "CC-BY-3.0" ]
null
null
null
#import <Foundation/Foundation.h> @protocol StoresDownloadDelegate - (void)storesRetrieved:(NSArray*)stores error:(NSString*)error; @end @interface StoresDownloadHandler : NSObject - (id)initWithLocation:(NSString*)location resultDelegate:(id<StoresDownloadDelegate>)resultDelegate; - (void)cancel; - (void)go; @end
20.125
101
0.785714
48dd157ba5607124e4089a18642579dfac4b10d1
974
kt
Kotlin
picasso-sample/src/main/java/com/example/picasso/provider/PicassoContentProvider.kt
cbennett-mijem/picasso
b1722721b83cf5d3a59d5bea727abf42a6405e29
[ "Apache-2.0" ]
16,197
2015-01-01T02:56:36.000Z
2022-03-31T09:35:18.000Z
picasso-sample/src/main/java/com/example/picasso/provider/PicassoContentProvider.kt
seanpm2001-libraries/picasso
d79a385e9808a5d88856033865fabfb8330226a0
[ "Apache-2.0" ]
1,373
2015-01-01T07:52:26.000Z
2022-03-30T20:34:01.000Z
picasso-sample/src/main/java/com/example/picasso/provider/PicassoContentProvider.kt
seanpm2001-libraries/picasso
d79a385e9808a5d88856033865fabfb8330226a0
[ "Apache-2.0" ]
4,264
2015-01-01T07:27:49.000Z
2022-03-31T14:29:55.000Z
package com.example.picasso.provider import android.annotation.SuppressLint import android.content.ContentProvider import android.content.ContentValues import android.content.Context import android.net.Uri class PicassoContentProvider : ContentProvider() { override fun onCreate(): Boolean { autoContext = context return true } override fun query( uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String? ) = null override fun getType(uri: Uri) = null override fun insert( uri: Uri, values: ContentValues? ) = null override fun delete( uri: Uri, selection: String?, selectionArgs: Array<String>? ) = 0 override fun update( uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>? ) = 0 companion object { @SuppressLint("StaticFieldLeak") @JvmField var autoContext: Context? = null } }
19.48
50
0.689938
63b3a8907e94e389b810366320acf90e5789fecb
15,123
sql
SQL
jasa_android.sql
farhanfarhan9/cms-jasa-android
9d2fa63bfb50eca42258271bb320732bddfc9f84
[ "MIT" ]
null
null
null
jasa_android.sql
farhanfarhan9/cms-jasa-android
9d2fa63bfb50eca42258271bb320732bddfc9f84
[ "MIT" ]
null
null
null
jasa_android.sql
farhanfarhan9/cms-jasa-android
9d2fa63bfb50eca42258271bb320732bddfc9f84
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Sep 22, 2020 at 09:26 AM -- Server version: 10.3.16-MariaDB -- PHP Version: 7.3.7 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `jasa_android` -- -- -------------------------------------------------------- -- -- Table structure for table `blogs` -- CREATE TABLE `blogs` ( `id` bigint(20) UNSIGNED NOT NULL, `category_id` int(10) UNSIGNED NOT NULL, `judul_blog` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `slug` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `deskripsi` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `konten` text COLLATE utf8mb4_unicode_ci NOT NULL, `foto` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `blogs` -- INSERT INTO `blogs` (`id`, `category_id`, `judul_blog`, `slug`, `deskripsi`, `konten`, `foto`, `created_at`, `updated_at`) VALUES (6, 3, 'Rahasia meningkatkan penjualan melalui website diedit', 'rahasia-meningkatkan-penjualan-melalui-website-diedit', 'meningkatkan jual beli melalui website', '<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Esse alias, quas corrupti iste porro necessitatibus exercitationem aspernatur incidunt odit molestiae sapiente ea, eius libero voluptatum sed. Sit illo omnis magnam odit, aut nobis voluptate labore reprehenderit consectetur tenetur, perspiciatis ipsa perferendis culpa quam animi sed dolore vel adipisci! Voluptates modi, ut nostrum magnam provident, culpa, illum beatae rem velit nam architecto aspernatur distinctio, eaque necessitatibus. Omnis libero tempora perferendis magnam minima dolorum aperiam porro impedit iusto? Est tempore quos libero quis iste eius facere cum debitis nam excepturi facilis laboriosam doloremque iusto in, deleniti veniam, consequatur nihil sapiente dicta optio, blanditiis. Quis optio porro blanditiis ipsum quo assumenda quaerat maxime ea perferendis ut a libero eligendi sed illo reiciendis, accusantium, qui! Distinctio, esse ducimus ab similique velit? Doloribus, eum, nostrum. Numquam voluptates magni quidem est, nemo corrupti, sequi aspernatur odit porro sunt laborum optio nisi quasi deleniti quo molestiae. Earum quam amet, explicabo ea soluta ullam inventore architecto quae ut beatae numquam, id dignissimos possimus, aspernatur rem pariatur fugit laborum, aliquam? Facere quis error dolores sint unde, aliquid nesciunt, iste explicabo saepe, distinctio ducimus debitis, vel nam! Sint nulla, adipisci qui incidunt fugit, impedit aut voluptatum assumenda odit, ut a.</p>', 'blog/BpwsrRypgdtENbDueIkmI1zli9mmlNEBve5hEKoM.jpeg', '2020-09-21 20:56:21', '2020-09-21 21:48:30'), (7, 4, 'Google meluncurkan android 10 hari ini dengan codename \'Pie\'', 'google-meluncurkan-android-10-hari-ini-dengan-codename-pie', 'google meluncurkan android 10 hari ini', '<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Esse alias, quas corrupti iste porro necessitatibus exercitationem aspernatur incidunt odit molestiae sapiente ea, eius libero voluptatum sed. Sit illo omnis magnam odit, aut nobis voluptate labore reprehenderit consectetur tenetur, perspiciatis ipsa perferendis culpa quam animi sed dolore vel adipisci! Voluptates modi, ut nostrum magnam provident, culpa, illum beatae rem velit nam architecto aspernatur distinctio, eaque necessitatibus. Omnis libero tempora perferendis magnam minima dolorum aperiam porro impedit iusto? Est tempore quos libero quis iste eius facere cum debitis nam excepturi facilis laboriosam doloremque iusto in, deleniti veniam, consequatur nihil sapiente dicta optio, blanditiis. Quis optio porro blanditiis ipsum quo assumenda quaerat maxime ea perferendis ut a libero eligendi sed illo reiciendis, accusantium, qui! Distinctio, esse ducimus ab similique velit? Doloribus, eum, nostrum. Numquam voluptates magni quidem est, nemo corrupti, sequi aspernatur odit porro sunt laborum optio nisi quasi deleniti quo molestiae. Earum quam amet, explicabo ea soluta ullam inventore architecto quae ut beatae numquam, id dignissimos possimus, aspernatur rem pariatur fugit laborum, aliquam? Facere quis error dolores sint unde, aliquid nesciunt, iste explicabo saepe, distinctio ducimus debitis, vel nam! Sint nulla, adipisci qui incidunt fugit, impedit aut voluptatum assumenda odit, ut a.</p>', 'blog/AlMlJtbQpQeuvjuAivfi1VSPHvdNFQPbO5VNzbF6.jpeg', '2020-09-21 20:58:07', '2020-09-21 20:58:07'); -- -------------------------------------------------------- -- -- Table structure for table `categories` -- CREATE TABLE `categories` ( `id` bigint(20) UNSIGNED NOT NULL, `nama_kategori` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `categories` -- INSERT INTO `categories` (`id`, `nama_kategori`, `created_at`, `updated_at`) VALUES (3, 'Windows', '2020-09-13 22:05:13', '2020-09-13 22:05:13'), (4, 'Android', '2020-09-20 21:28:10', '2020-09-20 21:28:31'); -- -------------------------------------------------------- -- -- Table structure for table `contacts` -- CREATE TABLE `contacts` ( `id` bigint(20) UNSIGNED NOT NULL, `nama_kontak` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `alamat` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `pesan` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `contacts` -- INSERT INTO `contacts` (`id`, `nama_kontak`, `alamat`, `email`, `pesan`, `created_at`, `updated_at`) VALUES (1, 'Farhan edit', 'jl puwosari', 'farhan@gmail.com', 'asdasdaw', '2020-09-16 19:24:03', '2020-09-16 19:44:13'), (2, 'Farhan', 'jl puwosari', 'prayogoyogi21@gmail.com', 'asd', '2020-09-20 20:08:11', '2020-09-20 20:08:11'), (3, 'sandra', 'sutomo', 'sandra@mail.com', 'sawaa', '2020-09-20 20:10:12', '2020-09-20 20:10:12'); -- -------------------------------------------------------- -- -- Table structure for table `failed_jobs` -- CREATE TABLE `failed_jobs` ( `id` bigint(20) UNSIGNED NOT NULL, `connection` text COLLATE utf8mb4_unicode_ci NOT NULL, `queue` text COLLATE utf8mb4_unicode_ci NOT NULL, `payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `failed_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `galleries` -- CREATE TABLE `galleries` ( `id` bigint(20) UNSIGNED NOT NULL, `nama_gallery` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `deskripsi` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `foto` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1, '2014_10_12_000000_create_users_table', 1), (2, '2014_10_12_100000_create_password_resets_table', 1), (3, '2019_08_19_000000_create_failed_jobs_table', 1), (4, '2020_09_07_064751_create_galleries_table', 1), (5, '2020_09_07_065000_create_blogs_table', 1), (6, '2020_09_07_065038_create_sliders_table', 1), (7, '2020_09_07_065051_create_contacts_table', 1), (8, '2020_09_07_065118_create_categories_table', 1), (9, '2020_09_09_092618_create_testimonies_table', 1), (10, '2020_09_17_044104_create_products_table', 2), (11, '2020_09_22_034244_add_slug_to_blogs_table', 3); -- -------------------------------------------------------- -- -- Table structure for table `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` bigint(20) UNSIGNED NOT NULL, `nama_produk` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `deskripsi` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `foto` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `products` -- INSERT INTO `products` (`id`, `nama_produk`, `deskripsi`, `foto`, `created_at`, `updated_at`) VALUES (1, 'Aplikasi portal mahasiswa edit', 'aplikasi bla bla bla bla edit', 'product/fBe46iCfPFLKBT2afVFdR6fNsMxHaZCAn718Pgxl.png', '2020-09-16 21:56:41', '2020-09-16 22:01:57'); -- -------------------------------------------------------- -- -- Table structure for table `sliders` -- CREATE TABLE `sliders` ( `id` bigint(20) UNSIGNED NOT NULL, `nama_slider` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `foto` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `sliders` -- INSERT INTO `sliders` (`id`, `nama_slider`, `foto`, `created_at`, `updated_at`) VALUES (2, 'slider1', 'slider/7cm5Cj7MkaXyjKQFO4g6ohxc3t2ONYwudYNXXB5o.jpeg', '2020-09-20 20:57:30', '2020-09-20 20:57:30'), (3, 'slider2', 'slider/dFHlLxkYldXflt57ah0QFR3yTQbwTklWzfJg9VDP.jpeg', '2020-09-20 20:58:10', '2020-09-20 20:58:10'), (4, 'slider3', 'slider/phkhUSUYJswAL9P0S7VZHe5wT2WjDZHyZwPRHejv.jpeg', '2020-09-20 20:58:21', '2020-09-20 20:58:21'); -- -------------------------------------------------------- -- -- Table structure for table `testimonies` -- CREATE TABLE `testimonies` ( `id` bigint(20) UNSIGNED NOT NULL, `nama_testimoni` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `jabatan` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `testimoni` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `foto` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES (1, 'Farhan', 'farhan@gmail.com', NULL, '$2y$10$F5pR4ij.bYyWflD0U8T2EeJ.AnKww8aE.a0aTayJJdFfc73MzU0yS', NULL, '2020-09-14 19:46:49', '2020-09-14 19:46:49'); -- -- Indexes for dumped tables -- -- -- Indexes for table `blogs` -- ALTER TABLE `blogs` ADD PRIMARY KEY (`id`); -- -- Indexes for table `categories` -- ALTER TABLE `categories` ADD PRIMARY KEY (`id`); -- -- Indexes for table `contacts` -- ALTER TABLE `contacts` ADD PRIMARY KEY (`id`); -- -- Indexes for table `failed_jobs` -- ALTER TABLE `failed_jobs` ADD PRIMARY KEY (`id`); -- -- Indexes for table `galleries` -- ALTER TABLE `galleries` ADD PRIMARY KEY (`id`); -- -- Indexes for table `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indexes for table `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`); -- -- Indexes for table `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`id`); -- -- Indexes for table `sliders` -- ALTER TABLE `sliders` ADD PRIMARY KEY (`id`); -- -- Indexes for table `testimonies` -- ALTER TABLE `testimonies` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `blogs` -- ALTER TABLE `blogs` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `categories` -- ALTER TABLE `categories` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `contacts` -- ALTER TABLE `contacts` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `failed_jobs` -- ALTER TABLE `failed_jobs` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `galleries` -- ALTER TABLE `galleries` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT for table `products` -- ALTER TABLE `products` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `sliders` -- ALTER TABLE `sliders` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `testimonies` -- ALTER TABLE `testimonies` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
38.579082
1,753
0.721616
5a14e61ba9c4061da24189008b5a98613f7382e0
1,817
sh
Shell
shared-utils/verify_preflight-spokes.sh
kquinn1204/ztp-pipeline-relocatable
f3316bd0691b1bbc825c05c3180fb0328af7ea14
[ "Apache-2.0" ]
null
null
null
shared-utils/verify_preflight-spokes.sh
kquinn1204/ztp-pipeline-relocatable
f3316bd0691b1bbc825c05c3180fb0328af7ea14
[ "Apache-2.0" ]
null
null
null
shared-utils/verify_preflight-spokes.sh
kquinn1204/ztp-pipeline-relocatable
f3316bd0691b1bbc825c05c3180fb0328af7ea14
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env bash set -o pipefail set -o errexit set -o nounset set -m # variables # ######### # uncomment it, change it or get it from gh-env vars (default behaviour: get from gh-env) # export KUBECONFIG=/root/admin.kubeconfig # Load common vars source ${WORKDIR}/shared-utils/common.sh echo ">>>> Verify the DNS requirements" echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" for spoke in ${ALLSPOKES}; do grab_api_ingress ${spoke} echo ">>>> SPOKE_API_IP: ${SPOKE_API_IP}" echo ">>>> SPOKE_API_INGRESS: ${SPOKE_INGRESS_IP}" echo ">>>> HUB_BASEDOMAIN: ${HUB_BASEDOMAIN}" if [[ ${SPOKE_API_IP} == "" || ${SPOKE_INGRESS_IP} == "" || ${HUB_BASEDOMAIN} == "" ]]; then echo "Error: DNS Entry are not available for spoke ${spoke}" exit 7 fi done echo ">>>> Verify the Mandatory root_disk requirements" echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" index=0 for spoke in ${ALLSPOKES}; do for master in $(echo $(seq 0 $(($(yq eval ".spokes[${index}].[]|keys" ${SPOKES_FILE} | grep master | wc -l) - 1)))); do root_disk=$(yq e ".spokes[${index}].[].master${master}.root_disk" $SPOKES_FILE) if [[ ${root_disk} == "" ]] || [[ ${root_disk} == "null" ]]; then echo "Error: root_disk is not defined for master ${master} at spoke ${spoke}" exit 7 fi done for worker in $(echo $(seq 0 $(($(yq eval ".spokes[${index}].[]|keys" ${SPOKES_FILE} | grep worker | wc -l) - 1)))); do root_disk=$(yq e ".spokes.[${index}].[].worker${worker}.root_disk" $SPOKES_FILE) if [[ ${root_disk} == "" ]] || [[ ${root_disk} == "null" ]]; then echo "Error: root_disk is not defined for worker ${worker} at spoke ${spoke}" exit 7 fi done index=$((index + 1)) done echo ">>>> EOF" echo ">>>>>>>>" exit 0
33.648148
123
0.563566
72b82fde1d66053c11362a13224fa97c42a3236b
155
cs
C#
BoidsECSTest/DefaultEcs/Components/Acceleration.cs
Ubiguchi/BoidsECSTest
07c5ffb342f87f986e8ce46efc889b2f074582c8
[ "MIT" ]
null
null
null
BoidsECSTest/DefaultEcs/Components/Acceleration.cs
Ubiguchi/BoidsECSTest
07c5ffb342f87f986e8ce46efc889b2f074582c8
[ "MIT" ]
4
2020-05-28T10:21:31.000Z
2020-05-28T14:05:45.000Z
BoidsECSTest/DefaultEcs/Components/Acceleration.cs
Ubiguchi/BoidsECSTest
07c5ffb342f87f986e8ce46efc889b2f074582c8
[ "MIT" ]
null
null
null
using Microsoft.Xna.Framework; namespace BoidsECSTest.DefaultEcs.Components { public struct Acceleration { public Vector2 Value; } }
15.5
44
0.703226
dfa677035e30f1867fd78b99a0a8efb3538aeefe
411
cs
C#
carros_xamarin_clean/carros_xamarin_clean/AppSettings.cs
FagnerFun/carros_xamarin_clean
6000a9f894b66a946108a9550df30570aa136430
[ "MIT" ]
null
null
null
carros_xamarin_clean/carros_xamarin_clean/AppSettings.cs
FagnerFun/carros_xamarin_clean
6000a9f894b66a946108a9550df30570aa136430
[ "MIT" ]
null
null
null
carros_xamarin_clean/carros_xamarin_clean/AppSettings.cs
FagnerFun/carros_xamarin_clean
6000a9f894b66a946108a9550df30570aa136430
[ "MIT" ]
null
null
null
namespace carros_xamarin_clean { public class AppSettings { public const string AppCenterAndroidKey = "4ecc8208-e33f-496f-a80e-593094c7d35f"; public const string AppCenterIosKey = "368be960-56fc-42bf-913b-9f67df8ae414"; public const string ApiUrl = "https://carros-springboot.herokuapp.com"; public static string OffLineDataBaseName { get => "carsample.db"; } } }
31.615385
89
0.705596
af9846524a9e6c18615a0558cd330d32b5cd51d2
2,649
py
Python
app/core/tests/test_models.py
therealak12/recipe-app-api
1c0b2bf537e485871b7f9d3dccb57a145f7d3b06
[ "Unlicense" ]
null
null
null
app/core/tests/test_models.py
therealak12/recipe-app-api
1c0b2bf537e485871b7f9d3dccb57a145f7d3b06
[ "Unlicense" ]
null
null
null
app/core/tests/test_models.py
therealak12/recipe-app-api
1c0b2bf537e485871b7f9d3dccb57a145f7d3b06
[ "Unlicense" ]
null
null
null
from unittest.mock import patch from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='testemail@example.com', password='testpass'): """Create and return a sample user""" return get_user_model().objects.create_user(email, password) class ModelTests(TestCase): def test_create_user_with_email(self): """Test if a user is created with an email""" email = 'somemail@example.com' password = 'somepass' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_created_user_email_normalized(self): email = 'testmail@ExAmPle.CoM' user = get_user_model().objects.create_user(email, 'testpass') self.assertEqual(email.lower(), user.email) def test_created_user_no_mail_invalid(self): """Test that a new user cannot be created without email""" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'testpass') def test_create_superuser(self): superuser = get_user_model().objects.create_superuser( email='somemail@example.com', password='somepass' ) self.assertTrue(superuser.is_superuser) self.assertTrue(superuser.is_staff) def test_tag_str(self): """Test the tag __str__ method""" tag = models.Tag.objects.create( user=sample_user(), name='TagName' ) self.assertEqual(str(tag), tag.name) def test_ingredient_str(self): """Test the tag __str__ method""" ingredient = models.Ingredient.objects.create( user=sample_user(), name='Ingredient Name' ) self.assertEqual(str(ingredient), ingredient.name) def test_recipe_str(self): """Test the recipe __str__ method""" recipe = models.Recipe.objects.create( user=sample_user(), title='Steak and mushroom sauce', time_minutes=5, price=5.00 ) self.assertEqual(str(recipe), recipe.title) @patch('uuid.uuid4') def test_recipe_file_name_uuid(self, mock_uuid): """Test that imgage is saved in the correct location""" uuid = 'test-uuid' mock_uuid.return_value = uuid file_path = models.recipe_image_file_path(None, 'my_image.jpg') expected_path = f'uploads/recipe/{uuid}.jpg' self.assertEqual(file_path, expected_path)
30.802326
71
0.643639
572569676eeb26fa5efbda9dcbf18c723d25c57c
3,022
js
JavaScript
src/pluginManager.js
nicolasdao/userin
22cd297ca18df9d35dcdf7b87b16113e5b5c8a62
[ "BSD-3-Clause" ]
5
2019-12-12T02:04:42.000Z
2020-07-15T00:15:29.000Z
src/pluginManager.js
nicolasdao/userin
22cd297ca18df9d35dcdf7b87b16113e5b5c8a62
[ "BSD-3-Clause" ]
6
2020-03-18T12:07:38.000Z
2020-10-07T07:47:39.000Z
src/pluginManager.js
nicolasdao/userin
22cd297ca18df9d35dcdf7b87b16113e5b5c8a62
[ "BSD-3-Clause" ]
1
2019-12-24T01:43:06.000Z
2019-12-24T01:43:06.000Z
const passport = require('passport') const { consentPageRequest, consentPageResponse, openIdConsentPageRequest, openIdConsentPageResponse} = require('./fipauthorize') const passportManager = require('./passportManager') const openIdServerManager = require('./openIdServerManager') const { Postman } = require('./postman') const printErrors = (errors, message) => { if (errors) { errors.forEach(e => console.log(e.stack)) throw new Error(message) } } /** * Registers a new Plugin to the UserIn middleware. * * @param {Object} eventHandlerStore * @param {Function} createHttpHandler (endpointRef: String, method: String, handler: Handler): Void * This function mutates an 'endpoints' object by adding the details * of the new handler to it. This helps with building the discovery endpoint. * @param {UserIn} userIn * @return {Void} */ module.exports = (eventHandlerStore, createHttpHandler, userIn) => { return async (Plugin, options={}) => { if (!Plugin) throw new Error('Missing required \'Plugin\'') const isStrategy = Plugin.prototype instanceof passport.Strategy const isOpenIdServer = Plugin.name && Plugin.discovery const isPostman = Plugin instanceof Postman if (isStrategy || isOpenIdServer) { const installPlugin = isStrategy ? passportManager.install : openIdServerManager.install const [errors, result] = await installPlugin(Plugin, eventHandlerStore, options) printErrors(errors, 'Failed to install Passport Strategy.') const { name, scopes, authorization_endpoint, token_endpoint, client_id, client_secret } = result // authorization_endpoint const endpoint = `${name}/authorize` const endpointRedirect = `${name}/authorizecallback` const endpointRef = `authorization_${name}_endpoint` const endpointRedirectRef = `authorization_${name}_redirect_endpoint` const verifyClientId = false const getConsentPageRequestHandler = isStrategy ? consentPageRequest() : openIdConsentPageRequest({ authorization_endpoint, client_id }) const getConsentPageResponseHandler = isStrategy ? consentPageResponse() : openIdConsentPageResponse({ token_endpoint, client_id, client_secret }) const requestHandler = getConsentPageRequestHandler(endpoint, name, endpointRedirectRef, scopes, verifyClientId) const responseHandler = getConsentPageResponseHandler(endpointRedirect, name, verifyClientId) createHttpHandler(endpointRef, 'get', requestHandler) createHttpHandler(endpointRedirectRef, 'get', responseHandler) } else if (isPostman) { createHttpHandler('postman_endpoint', 'get', { endpoint:'postman/collection.json', handler: () => Plugin.getCollection(userIn) }, { formatJSON:true }) } else throw new Error('Invalid \'Plugin\'. \'Plugin\' must either be a Passport.Strategy class, an OpenID server config object, or a Postman instance.') } }
41.972222
149
0.713435
1a69f72b714d6cd02b7943fc217e43e81f7d8b6d
94
py
Python
order/user_order/apps.py
Virusuki/AWS_MSA_service_order
5b95fe1c86d06434f46ff2cb6be7add9874120a3
[ "Apache-2.0" ]
null
null
null
order/user_order/apps.py
Virusuki/AWS_MSA_service_order
5b95fe1c86d06434f46ff2cb6be7add9874120a3
[ "Apache-2.0" ]
null
null
null
order/user_order/apps.py
Virusuki/AWS_MSA_service_order
5b95fe1c86d06434f46ff2cb6be7add9874120a3
[ "Apache-2.0" ]
null
null
null
from django.apps import AppConfig class UserOrderConfig(AppConfig): name = 'user_order'
15.666667
33
0.765957
c6d60ab9d4ca744676616b6d969f8f91f8dc7254
3,209
css
CSS
css/post.css
Duxinghua/duxinghua.github.io
a8c2c5dd8ec14b76e6ba8057b3a76b8f017a1753
[ "Apache-2.0" ]
7
2017-08-11T16:52:21.000Z
2018-08-24T14:07:31.000Z
css/post.css
Duxinghua/duxinghua.github.io
a8c2c5dd8ec14b76e6ba8057b3a76b8f017a1753
[ "Apache-2.0" ]
6
2017-11-06T05:35:34.000Z
2022-01-06T10:01:47.000Z
css/post.css
Duxinghua/duxinghua.github.io
a8c2c5dd8ec14b76e6ba8057b3a76b8f017a1753
[ "Apache-2.0" ]
4
2017-11-06T05:39:00.000Z
2019-10-16T20:40:42.000Z
.content-bch{width:500px;margin:0 auto;text-align: center;} .content-bch-p{padding-top: 10px;text-align: left;font-weight:340;} .content-bch-t{padding-top: 10px;text-align: center;} .box_1{ padding: 0px 20px; border-width: 0px; height: auto; background: inherit; background-color: inherit; background-color: rgba(255, 255, 255, 1); box-sizing: border-box; border-width: 1px; border-style: solid; border-color: rgba(121, 121, 121, 1); border-radius: 8px; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; text-align: center; margin:0 auto 10px auto; } .div_h5{ margin-top:15px; margin-left:-20px; border-width: 0px; text-align: left; width: 300px; height: 33px; background: inherit; background-color: inherit; background-color: rgba(255, 255, 255, 1); box-sizing: border-box; border-width: 1px; border-style: solid; border-color: rgba(121, 121, 121, 1); border-radius: 0px; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } .div_h5 span{ padding-left: 20px; line-height: 33px; font-weight: 700; font-size: 13px; color: #333333; } .t1{ margin-top:30px; } .safe_info_p{ padding-bottom: 5px; } .safe_info_p strong{font-weight: 400} .content-bch-p strong,.list-span-mar strong{font-weight: 400} .div_safe{ width:45px;height:45px;border-radius: 50%;border:1px solid #333;line-height: 45px;text-align: center;float:left; } .safe_info{ text-align: left; margin-left: 54px; } .safe_info p{margin:0;font-weight: 340} .safe_info p span{ font-size: 12px; color: #666666; } .list-p{line-height: 45px} .list-span-header{ background:url(/img/first.png) no-repeat;background-size:100% 100% ;height:45px;width:45px;display:inline-block;float:left;margin:0 50px; } .three{background:url(/img/three.png) no-repeat;background-size:100% 100% ;} .second{background:url(/img/second.png) no-repeat;background-size:100% 100% ;} .four{background:url(/img/four.png) no-repeat;background-size:100% 100% ;} .list-span-in{ float:left; line-height:45px; width:90px; text-align: left; } .list-span-mar{ /*margin-left:20px;*/ } .list-span-r{ float:right } .content-bch-info{ font-size:11px; text-align:center; } .h5-bch-span{ float:left;padding-top:50px;margin-left:-43px; } body{ line-height: 1.6 } .end{ margin-bottom: 30px; } .bch-download{ padding-top: 0px } .list-span-mar strong{ padding: 0 5px; } .content-p p{ padding-top:10px; } .content-bch-p strong{ font-weight: 700 } @media(min-width:320px) and (max-width:767px){ .list-span-mar strong{ padding: 0 2px; } .content-bch{width:100%;} .div_h5{ width:100% } .box_1{ height:auto; } .list-span-header{ margin:0; } .list-span-mar{ margin:0; } .content-p{ width:100% !important; } .content-bch-info{ font-size:11px;text-align:left; } .bch_ads{ width:48px; height:48px; } .h5-bch-span{ float:left;padding-top:25px;margin-left:-23px;font-size: 14px !important } .content-bch-h{ text-align: left } .bch-post tr>td,.bch-post-en tr>td{ padding: 4px; font-size: 10px; } .bch-post tr>th,.bch-post-en tr>th{ padding: 4px; font-weight: 300; font-size: 12px; } .div-post-content{ width:100% !important; overflow: scroll; } .div-post-content-en{ overflow: scroll; } .bch-post-en{ width:650px !important; } }
18.442529
137
0.707697
1a9112ce873a1df83ab24254abdca769bd461a08
2,681
cs
C#
src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/OutputFieldDefinitionBase.cs
Drakkonite/hotchocolate
8aa8aa81677fe1a1fe2c2ce3a6cd64898a4ca954
[ "MIT" ]
3,399
2018-06-27T06:45:08.000Z
2022-03-31T21:16:35.000Z
src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/OutputFieldDefinitionBase.cs
Drakkonite/hotchocolate
8aa8aa81677fe1a1fe2c2ce3a6cd64898a4ca954
[ "MIT" ]
3,835
2018-06-05T18:24:45.000Z
2022-03-31T14:22:12.000Z
src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/OutputFieldDefinitionBase.cs
Drakkonite/hotchocolate
8aa8aa81677fe1a1fe2c2ce3a6cd64898a4ca954
[ "MIT" ]
587
2018-06-05T19:58:55.000Z
2022-03-28T02:53:02.000Z
using System; using System.Collections.Generic; using System.Linq; using HotChocolate.Language; #nullable enable namespace HotChocolate.Types.Descriptors.Definitions { public class OutputFieldDefinitionBase : FieldDefinitionBase<FieldDefinitionNode> , ICanBeDeprecated { private List<ArgumentDefinition>? _arguments; public string? DeprecationReason { get; set; } public bool IsDeprecated => !string.IsNullOrEmpty(DeprecationReason); public IList<ArgumentDefinition> Arguments => _arguments ??= new List<ArgumentDefinition>(); /// <summary> /// Specifies if this field has any arguments. /// </summary> public bool HasArguments => _arguments is { Count: > 0 }; public IReadOnlyList<ArgumentDefinition> GetArguments() { if (_arguments is null) { return Array.Empty<ArgumentDefinition>(); } return _arguments; } protected void CopyTo(OutputFieldDefinitionBase target) { base.CopyTo(target); if (_arguments is { Count: > 0 }) { target._arguments = new List<ArgumentDefinition>(); foreach (ArgumentDefinition argument in _arguments) { var newArgument = new ArgumentDefinition(); argument.CopyTo(newArgument); target._arguments.Add(newArgument); } } target.DeprecationReason = DeprecationReason; } protected void MergeInto(OutputFieldDefinitionBase target) { base.MergeInto(target); if (_arguments is { Count: > 0 }) { target._arguments ??= new List<ArgumentDefinition>(); foreach (ArgumentDefinition argument in _arguments) { ArgumentDefinition? targetArgument = target._arguments.FirstOrDefault(t => t.Name.Equals(argument.Name)); if (targetArgument is null) { targetArgument = new ArgumentDefinition(); argument.CopyTo(targetArgument); target._arguments.Add(targetArgument); } else { argument.MergeInto(targetArgument); } } } if (DeprecationReason is not null) { target.DeprecationReason = DeprecationReason; } } } }
29.461538
92
0.533383
ed158ba3c294470f2f57d5d7f8e3bcf60340176d
563
kt
Kotlin
core/src/main/kotlin/worlds/gregs/hestia/core/entity/npc/logic/systems/chunk/NpcChunkSubscriptionSystem.kt
Rune-Status/hestia
71e70a27d7352d93eb109e6ba0c1617652a30b51
[ "BSD-3-Clause" ]
17
2018-11-13T19:16:27.000Z
2022-01-02T06:27:19.000Z
core/src/main/kotlin/worlds/gregs/hestia/core/entity/npc/logic/systems/chunk/NpcChunkSubscriptionSystem.kt
Rune-Status/hestia
71e70a27d7352d93eb109e6ba0c1617652a30b51
[ "BSD-3-Clause" ]
110
2019-12-04T17:41:34.000Z
2020-03-15T19:03:16.000Z
core/src/main/kotlin/worlds/gregs/hestia/core/entity/npc/logic/systems/chunk/NpcChunkSubscriptionSystem.kt
Rune-Status/hestia
71e70a27d7352d93eb109e6ba0c1617652a30b51
[ "BSD-3-Clause" ]
6
2018-11-13T19:16:17.000Z
2022-03-02T05:48:29.000Z
package worlds.gregs.hestia.core.entity.npc.logic.systems.chunk import net.mostlyoriginal.api.event.common.EventSystem import worlds.gregs.hestia.core.entity.npc.api.Npc import worlds.gregs.hestia.core.entity.npc.model.events.NpcChunkChanged import worlds.gregs.hestia.core.world.movement.api.systems.ChunkSubscription class NpcChunkSubscriptionSystem : ChunkSubscription(Npc::class) { private lateinit var es: EventSystem override fun changedChunk(entityId: Int, from: Int?, to: Int?) { es.dispatch(NpcChunkChanged(entityId, from, to)) } }
40.214286
76
0.790409
f45fc47803ca44004daf1beed967b5fc1cec2c00
749
ts
TypeScript
src/app/forms/flat/flat.module.ts
Shaman739/TemplateAngular
bab7a5904768c24bc225e6f1646e32c88457516c
[ "MIT" ]
null
null
null
src/app/forms/flat/flat.module.ts
Shaman739/TemplateAngular
bab7a5904768c24bc225e6f1646e32c88457516c
[ "MIT" ]
null
null
null
src/app/forms/flat/flat.module.ts
Shaman739/TemplateAngular
bab7a5904768c24bc225e6f1646e32c88457516c
[ "MIT" ]
null
null
null
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { GridModule } from '../../core/component/grid/grid.module'; import { HttpClientModule } from '@angular/common/http'; import { FlatEditComponent } from './edit-component/flat-edit.component'; import { MatButtonModule } from '@angular/material/button'; import { MatDialogModule } from '@angular/material/dialog'; @NgModule({ imports: [ BrowserModule, FormsModule,HttpClientModule,GridModule,MatButtonModule,MatDialogModule], declarations: [ FlatEditComponent], entryComponents: [ FlatEditComponent], exports: [ FlatEditComponent] }) export class FlatModule { }
46.8125
108
0.730307
c6c28edc9315f9e4f8c0296bc7ff152c9793bb81
622
css
CSS
html04/case4/br_styles.css
jallen19/html04
4d0569f7ffbee0cf012e03c1341066f2fb1449b0
[ "Unlicense" ]
null
null
null
html04/case4/br_styles.css
jallen19/html04
4d0569f7ffbee0cf012e03c1341066f2fb1449b0
[ "Unlicense" ]
null
null
null
html04/case4/br_styles.css
jallen19/html04
4d0569f7ffbee0cf012e03c1341066f2fb1449b0
[ "Unlicense" ]
null
null
null
@charset "utf-8"; /* New Perspectives on HTML5 and CSS3, 7th Edition Tutorial 4 Case Problem 4 Browyer Realty Layout Styles Author: Date: Filename: br_styles.css */ html { background: url(br_paper.png); } body { height: 100%; width:1200px; margin-left:auto; margin-right: auto; border-left: 2px solid black; border-right: 2px solid black; background-image: url(br_photo10.jpg); color: white; } body > header > nav > ul > li a { display: block; float: left; position: relative; width: 20%; } aside { border: 3px double black; }
14.809524
50
0.614148
f1ae4fd70757f9935d136b921f2015d382d0b4a0
95
rb
Ruby
config/routes.rb
work-design/ruby_sdk
44841e64023f269abb1ad2096ecc0776cf3548ee
[ "MIT" ]
null
null
null
config/routes.rb
work-design/ruby_sdk
44841e64023f269abb1ad2096ecc0776cf3548ee
[ "MIT" ]
null
null
null
config/routes.rb
work-design/ruby_sdk
44841e64023f269abb1ad2096ecc0776cf3548ee
[ "MIT" ]
null
null
null
Rails.application.routes.draw do namespace :wd, defaults: { business: 'wd' } do end end
11.875
48
0.684211
e819c3cfdc1e226c1a4d299257659f9d04f4fe6c
370
ps1
PowerShell
Allfiles/Labs/auth.ps1
G-Eazy/AZ-204-DevelopingSolutionsforMicrosoftAzure
d97825bb36ea9d1aafbefcdab9fe52d2637d266b
[ "MIT" ]
null
null
null
Allfiles/Labs/auth.ps1
G-Eazy/AZ-204-DevelopingSolutionsforMicrosoftAzure
d97825bb36ea9d1aafbefcdab9fe52d2637d266b
[ "MIT" ]
null
null
null
Allfiles/Labs/auth.ps1
G-Eazy/AZ-204-DevelopingSolutionsforMicrosoftAzure
d97825bb36ea9d1aafbefcdab9fe52d2637d266b
[ "MIT" ]
null
null
null
clientID 3826d202-ef1e-405c-906f-e893f2e5bf1c tennantID 4cfe372a-37a4-44f8-91b2-5faf34253c62 4cfe372a-37a4-44f8-91b2-5faf34253c62 aad_lab_user-20317034@LODSPRODMCA.onmicrosoft.com aad_lab_user2@gregersorg.onmicrosoft.com dotnet new mvc --auth SingleOrg --client-id <application_ID> --tenant-id <tenant_ID> --domain <domain_Name> dotnet dev-certs https --trust
41.111111
108
0.810811
546f5b62b4bd918b8d699d991929b77033e854f2
718
css
CSS
samples/AdaptiveCards.Blazor.Samples/wwwroot/theme.css
iAmBipinPaul/Blazor.AdaptiveCards
3ba8769b8104f9362bdc4036abf13cfedd2a716f
[ "MIT" ]
45
2019-10-10T07:52:56.000Z
2022-01-12T16:21:43.000Z
samples/AdaptiveCards.Blazor.Samples/wwwroot/theme.css
iAmBipinPaul/Blazor.AdaptiveCards
3ba8769b8104f9362bdc4036abf13cfedd2a716f
[ "MIT" ]
16
2019-10-06T16:00:15.000Z
2021-10-19T01:07:28.000Z
samples/AdaptiveCards.Blazor.Samples/wwwroot/theme.css
iAmBipinPaul/Blazor.AdaptiveCards
3ba8769b8104f9362bdc4036abf13cfedd2a716f
[ "MIT" ]
15
2019-10-22T17:07:05.000Z
2022-01-25T15:10:41.000Z
.bd-navbar { background-color: #5D2F91; } .bd-navbar .navbar-nav .nav-link { color: white; } .slbImage { padding: 2em 0; } .bd-toc-link { padding: .25rem 1.0rem; } .bd-sidebar .nav > li > a { padding: .25rem 1.0rem; } @media (max-width: 991.98px) { .bd-navbar { padding-right: 1.0rem; padding-left: 1.0rem; } } @media (min-width: 992px) { .bd-content > ol, .bd-content > p, .bd-content > ul { max-width: 100%; } } pre[class*="language-"] > code { border-left-color: #5D2F91 !important; } .ac-adaptivecard { border: solid 1px #e5d8f3; } .ac-textinput.ac-input { width: 100%; } .ac-adaptivecard.ac-showCard{ border: 0px; }
14.958333
57
0.564067
1aa3236bf14f1a976e1df6829a06ab91bfbb45ff
10,663
py
Python
tests/sat/Models/c765.180.UNSAT.dimacs.test.py
bernardocuteri/wasp
05c8f961776dbdbf7afbf905ee00fc262eba51ad
[ "Apache-2.0" ]
19
2015-12-03T08:53:45.000Z
2022-03-31T02:09:43.000Z
tests/sat/Models/c765.180.UNSAT.dimacs.test.py
bernardocuteri/wasp
05c8f961776dbdbf7afbf905ee00fc262eba51ad
[ "Apache-2.0" ]
80
2017-11-25T07:57:32.000Z
2018-06-10T19:03:30.000Z
tests/sat/Models/c765.180.UNSAT.dimacs.test.py
bernardocuteri/wasp
05c8f961776dbdbf7afbf905ee00fc262eba51ad
[ "Apache-2.0" ]
6
2015-01-15T07:51:48.000Z
2020-06-18T14:47:48.000Z
input = """ c num blocks = 1 c num vars = 180 c minblockids[0] = 1 c maxblockids[0] = 180 p cnf 180 765 43 -70 -94 0 80 70 -20 0 34 -89 37 0 -99 -140 153 0 -30 131 14 0 136 20 17 0 -125 -172 -114 0 19 -13 -126 0 127 -138 -142 0 -127 -84 79 0 -63 -13 50 0 -15 -118 17 0 6 65 -116 0 -30 -167 157 0 -156 -143 -12 0 38 -60 154 0 -121 18 -76 0 142 -152 130 0 177 41 -62 0 -51 180 -105 0 -61 -76 26 0 -177 -180 -110 0 32 42 -144 0 155 119 73 0 95 -39 104 0 111 -56 -167 0 126 82 -111 0 -64 159 -36 0 -28 -79 40 0 157 -130 88 0 172 16 -88 0 100 21 -110 0 93 40 -22 0 -172 -179 28 0 178 36 -104 0 -45 1 -100 0 -55 -1 32 0 178 32 -16 0 -26 22 63 0 -13 -42 73 0 -131 107 -16 0 -61 -98 -91 0 154 -42 -67 0 -161 -87 9 0 -151 27 -77 0 129 121 -122 0 108 -97 -15 0 -6 12 86 0 -108 -171 -57 0 -30 -145 175 0 1 -78 3 0 141 54 -62 0 -69 -119 58 0 -177 142 -59 0 -144 -164 163 0 21 -116 -119 0 106 -69 -129 0 174 34 -2 0 -33 -119 -152 0 88 -45 -142 0 -56 -164 -22 0 -15 82 -132 0 -162 -45 179 0 67 46 -78 0 -11 -170 86 0 -145 111 -21 0 -23 20 -27 0 39 60 53 0 160 -116 -47 0 -160 45 102 0 -113 143 45 0 112 115 -140 0 29 174 -126 0 132 157 -25 0 123 69 -167 0 99 -36 -63 0 -164 29 -43 0 -152 149 -23 0 149 35 173 0 -81 75 -84 0 -161 -142 84 0 -124 -113 -172 0 7 -143 -18 0 90 55 -118 0 179 -103 23 0 -119 -35 161 0 -160 -153 -133 0 114 99 -4 0 -116 -85 122 0 141 72 -71 0 -163 52 -20 0 -112 144 161 0 -173 111 -120 0 -145 -33 -86 0 -31 144 -94 0 -74 94 158 0 -4 107 -119 0 15 -43 -76 0 117 179 -51 0 159 -104 158 0 -160 -117 21 0 -23 97 59 0 -97 143 91 0 8 61 69 0 41 164 160 0 60 -175 -160 0 -27 169 -67 0 -178 33 -69 0 -119 -107 83 0 53 93 -160 0 -45 -155 -153 0 9 167 15 0 -38 127 168 0 -28 -69 -108 0 135 21 -117 0 146 48 41 0 139 -2 104 0 44 -31 176 0 104 -23 -109 0 106 49 123 0 -14 -2 -63 0 -170 -5 -177 0 88 -180 -161 0 175 23 168 0 98 -135 -45 0 79 -161 136 0 -140 123 -129 0 -104 -79 178 0 -158 46 24 0 76 -165 -65 0 -31 82 -29 0 -16 -124 58 0 -11 83 -21 0 43 -33 -121 0 4 133 23 0 -9 -157 72 0 -27 -86 13 0 35 140 54 0 167 64 21 0 -118 -122 97 0 -23 149 126 0 65 128 96 0 -167 -175 -177 0 -53 -116 -92 0 52 139 37 0 -50 -1 -85 0 105 -132 53 0 -119 -8 20 0 -112 100 53 0 -74 45 -39 0 -59 -44 -23 0 -31 146 1 0 23 114 -20 0 39 -25 166 0 54 110 47 0 -43 -9 154 0 116 -123 -109 0 -26 138 -12 0 -169 128 37 0 -147 -119 -105 0 17 -49 -21 0 174 27 18 0 101 -121 -166 0 -99 161 -90 0 9 90 -142 0 158 161 169 0 -38 -9 171 0 -165 87 -48 0 -18 -15 148 0 -48 -130 -57 0 -32 -2 50 0 -171 65 -30 0 12 -30 29 0 -106 -136 -67 0 -98 -61 174 0 29 46 -132 0 177 -116 42 0 -140 176 10 0 -147 105 165 0 57 68 -95 0 56 44 -173 0 -68 9 119 0 -89 69 -172 0 -17 146 15 0 6 149 27 0 -141 -32 -136 0 -111 -67 84 0 -147 -133 -108 0 137 -126 -123 0 175 105 -101 0 -60 177 -98 0 52 -19 -31 0 -61 -123 -91 0 -155 101 62 0 44 119 -109 0 8 138 32 0 166 131 -56 0 -46 -54 -116 0 66 132 100 0 -158 -83 180 0 117 160 69 0 -159 -132 48 0 -21 -59 -123 0 -107 -42 27 0 -9 -50 35 0 -56 96 142 0 143 110 -147 0 75 17 -68 0 22 17 -144 0 -56 152 41 0 -141 163 -108 0 -66 -49 -155 0 -134 8 157 0 -18 49 31 0 -4 -106 146 0 -153 38 -39 0 -99 -61 119 0 -105 156 98 0 -42 -173 178 0 25 -102 -51 0 -180 -85 -6 0 -18 52 129 0 -93 130 -25 0 -149 77 106 0 -157 -180 43 0 -136 -129 -87 0 -121 151 -83 0 79 153 -15 0 -85 13 -116 0 -63 150 74 0 -8 95 -1 0 171 -152 -167 0 -165 176 -17 0 -35 -74 -122 0 160 155 -87 0 32 -73 -106 0 145 -180 -47 0 -39 178 -120 0 -120 35 174 0 112 167 58 0 -42 53 135 0 50 141 54 0 32 -101 154 0 -128 85 -143 0 -90 -53 -144 0 -50 -143 46 0 65 -175 9 0 -4 -3 16 0 -158 103 88 0 -110 142 -27 0 -146 -138 -133 0 151 -71 -129 0 116 24 119 0 -25 -116 138 0 -170 -77 -5 0 111 -154 87 0 47 39 89 0 148 163 -106 0 -156 -38 -168 0 -25 4 165 0 -1 -13 15 0 164 -15 -92 0 -65 -163 19 0 -10 -137 -131 0 46 86 149 0 -30 61 168 0 -75 93 43 0 -89 114 -25 0 -159 163 -9 0 53 73 -148 0 -124 32 -27 0 94 104 -164 0 134 -143 -11 0 -107 -85 61 0 21 55 82 0 5 170 54 0 83 117 34 0 -1 -31 -78 0 54 162 43 0 -171 48 4 0 -157 -45 -135 0 55 -131 127 0 13 76 -173 0 -109 -120 -25 0 19 82 -31 0 27 30 68 0 6 9 72 0 -63 -86 -62 0 97 160 -53 0 129 5 102 0 -178 -116 -19 0 -95 -157 -59 0 171 17 157 0 -178 -61 -98 0 42 -43 81 0 110 -139 -134 0 -158 -146 116 0 18 22 79 0 -161 130 -59 0 68 -133 -9 0 163 30 -177 0 -30 -34 114 0 89 -170 83 0 64 -55 -82 0 -3 121 -145 0 41 -74 87 0 -135 -19 11 0 32 81 31 0 130 -138 31 0 123 -63 39 0 -94 -38 149 0 -168 -125 -35 0 139 -95 -87 0 131 -56 -85 0 168 152 78 0 170 -145 39 0 121 -131 124 0 -124 83 177 0 50 -42 -37 0 -39 -37 158 0 156 107 115 0 171 35 -121 0 74 14 -51 0 -72 -21 -97 0 -44 102 85 0 -174 -46 2 0 -168 -6 -42 0 -75 42 47 0 -16 -112 -146 0 102 -82 79 0 -111 -33 -167 0 -167 -101 130 0 -74 -71 -17 0 110 -117 -88 0 171 92 -80 0 -39 126 -91 0 66 -165 83 0 87 -28 9 0 -128 -84 -15 0 -146 128 -90 0 31 -78 39 0 160 132 79 0 86 -111 -171 0 -138 -175 -128 0 101 46 85 0 -78 1 63 0 40 96 -53 0 68 -123 109 0 -74 79 132 0 -90 20 50 0 -180 97 -53 0 -60 112 143 0 157 -175 -40 0 79 -82 -160 0 -159 142 -9 0 129 -179 131 0 -107 72 34 0 -71 -163 16 0 -131 -64 10 0 -48 150 -30 0 52 -118 155 0 -72 42 -87 0 -135 118 16 0 178 3 -70 0 -28 -3 116 0 95 -60 160 0 73 -162 -39 0 129 -130 163 0 140 53 -130 0 -25 -108 -134 0 169 -4 -60 0 107 -113 55 0 171 -91 179 0 -111 -59 94 0 14 -56 -40 0 -125 -44 172 0 -34 42 -101 0 79 70 -139 0 -53 -106 55 0 17 158 128 0 102 -60 146 0 -134 -56 -176 0 71 153 89 0 -48 -97 -168 0 -15 23 160 0 107 119 93 0 -148 -142 12 0 26 -142 -16 0 10 179 -160 0 63 -179 112 0 -105 -17 -141 0 172 164 55 0 -107 -26 67 0 142 12 -125 0 -18 -148 -92 0 -87 -116 -84 0 -134 12 35 0 -150 142 82 0 -95 -171 -154 0 -72 18 81 0 24 -166 68 0 -146 45 -122 0 -89 -57 -77 0 57 68 -98 0 6 -169 73 0 94 138 -41 0 -41 46 -36 0 104 -161 -149 0 121 13 -92 0 -150 115 2 0 -93 18 136 0 -80 115 81 0 128 -15 39 0 -71 109 -111 0 -94 -147 53 0 -165 116 -54 0 179 -8 -148 0 48 -114 65 0 160 -127 -68 0 40 -88 -59 0 43 -63 15 0 -15 -6 -23 0 -112 140 49 0 78 -102 -93 0 120 -20 -42 0 51 15 -114 0 159 20 -75 0 -85 -3 10 0 -104 54 72 0 132 142 21 0 -151 122 153 0 -20 -81 -59 0 113 -132 -29 0 -113 -58 74 0 -130 88 144 0 91 -84 -2 0 5 -74 -145 0 -106 171 140 0 90 -134 115 0 145 50 -13 0 12 54 24 0 -129 101 -18 0 -60 -126 5 0 -179 -107 100 0 -103 -35 -7 0 34 66 7 0 -128 -23 -11 0 70 -92 23 0 19 166 140 0 -154 87 173 0 77 -103 -70 0 -26 177 86 0 152 72 -141 0 95 -64 -169 0 -147 57 -162 0 21 69 124 0 -157 -5 -68 0 128 11 -66 0 -154 61 92 0 18 -11 -175 0 -119 51 163 0 58 157 176 0 -124 63 -10 0 71 -160 -127 0 26 87 136 0 94 -148 134 0 49 -82 43 0 -164 -87 -167 0 162 -83 -167 0 -66 126 55 0 -88 -92 167 0 64 106 158 0 113 124 -118 0 -84 -91 146 0 160 114 131 0 -57 43 -7 0 160 -38 -65 0 -7 83 129 0 -131 82 -48 0 -79 122 -121 0 -157 54 -176 0 40 44 -56 0 -116 -98 36 0 26 142 -69 0 -20 90 -69 0 -117 -50 -111 0 -17 173 108 0 -96 31 -98 0 -164 30 -151 0 120 139 -50 0 -144 147 56 0 4 91 -39 0 -126 155 105 0 -174 106 -7 0 -169 86 136 0 121 -20 -55 0 -97 -93 104 0 -164 -104 102 0 -8 101 -39 0 -124 -31 -107 0 88 93 -63 0 -28 -84 -108 0 -91 135 155 0 -76 112 35 0 -50 99 56 0 -114 -77 56 0 -76 -99 13 0 -20 16 117 0 -11 1 179 0 -11 -68 133 0 81 155 -17 0 106 110 158 0 123 -137 -78 0 94 -11 -123 0 -137 -174 136 0 -138 154 36 0 19 -72 -78 0 165 14 -2 0 116 -26 119 0 107 79 -10 0 120 82 -158 0 24 55 -139 0 22 -25 102 0 -32 -94 -36 0 -64 150 5 0 -178 60 33 0 166 62 110 0 -77 -138 -11 0 12 -146 101 0 -73 -1 -123 0 15 -154 -150 0 109 -59 115 0 33 139 42 0 174 -177 -13 0 -124 146 125 0 136 1 -173 0 -172 -147 -51 0 142 45 163 0 -150 -177 137 0 52 170 -71 0 -54 -178 -83 0 -129 -51 127 0 -110 -141 -19 0 -155 129 87 0 -153 -116 84 0 101 139 54 0 119 -134 92 0 67 -49 110 0 -2 59 -53 0 75 105 100 0 51 -85 112 0 -41 -22 -120 0 -78 92 48 0 138 102 -108 0 -98 -26 90 0 -132 111 -113 0 -30 -160 170 0 -163 78 58 0 129 24 169 0 112 166 107 0 92 -12 104 0 169 -49 107 0 44 -86 -55 0 -83 -88 4 0 -103 -158 -71 0 37 18 -130 0 -62 -175 51 0 157 -137 -97 0 -72 -141 -96 0 -163 -40 -146 0 32 133 -10 0 -180 28 -102 0 -138 88 -157 0 -139 -179 -80 0 -80 -21 -169 0 15 -168 -10 0 -63 -41 -96 0 29 -95 -118 0 -83 -87 146 0 -119 -62 -135 0 60 -175 -128 0 81 145 73 0 93 -167 112 0 28 -79 -158 0 163 171 -162 0 -74 100 138 0 153 69 -176 0 -153 -174 -65 0 141 -29 165 0 126 158 112 0 -165 92 161 0 -82 125 15 0 15 -170 -71 0 68 89 -118 0 -172 56 45 0 -120 -52 177 0 -129 -127 168 0 -36 49 -147 0 135 -47 -10 0 16 -103 -28 0 52 -64 -87 0 -105 -71 140 0 -9 97 -136 0 95 -85 -93 0 -161 82 -107 0 -118 11 83 0 16 132 -21 0 166 103 -102 0 44 68 -19 0 149 -150 -170 0 8 -93 -6 0 -142 -29 66 0 -47 -85 -112 0 19 123 -2 0 -119 149 -152 0 -144 99 -150 0 -19 152 51 0 118 13 147 0 -73 -25 -15 0 173 -13 -11 0 -126 -98 -35 0 -160 91 60 0 27 -52 45 0 122 -33 -13 0 53 -22 87 0 -78 -44 -89 0 -11 -117 33 0 107 121 -143 0 -166 -66 147 0 140 124 29 0 115 -52 -112 0 -18 94 149 0 -141 142 -144 0 8 -152 56 0 107 40 -110 0 106 110 -144 0 -47 -167 -162 0 15 14 -91 0 27 93 -157 0 146 105 -138 0 154 38 127 0 170 39 -156 0 17 -19 84 0 -170 23 -46 0 36 -91 -81 0 -114 161 -113 0 167 -136 -16 0 -54 -134 -33 0 30 47 -127 0 -10 12 -14 0 -91 141 28 0 -32 -44 -38 0 -144 90 142 0 1 -118 -169 0 -178 -44 -79 0 -115 -70 -109 0 111 -102 93 0 21 -90 83 0 82 -50 154 0 158 -114 -82 0 -96 -174 137 0 -18 -161 -19 0 -24 -2 -136 0 -34 175 167 0 -155 13 -124 0 130 98 -76 0 -61 109 -143 0 -24 149 33 0 148 132 -44 0 -79 17 169 0 -127 158 150 0 162 139 -37 0 -100 66 -65 0 67 -50 78 0 107 -124 59 0 -72 114 -24 0 -172 -52 -118 0 -82 115 42 0 -90 -48 51 0 -80 -45 124 0 -106 -180 46 0 58 -172 129 0 87 105 -52 0 -99 -178 -176 0 -52 -4 113 0 -113 101 -76 0 -51 68 67 0 -10 -68 77 0 128 138 -126 0 10 147 20 0 -47 50 -126 0 -61 -73 -112 0 -77 -46 -138 0 37 -102 -12 0 62 -2 31 0 -165 32 -4 0 -169 -134 149 0 137 -32 33 0 127 49 67 0 -169 -84 -47 0 -43 6 117 0 20 104 54 0 122 141 103 0 -72 -142 -149 0 2 -62 -10 0 -136 -103 -9 0 -173 -44 -24 0 -8 57 169 0 9 -146 -47 0 76 -28 146 0 -149 -115 89 0 94 -157 81 0 176 -106 162 0 12 -2 -123 0 -82 -25 60 0 -123 74 -180 0 -62 -38 -36 0 -87 -99 44 0 -131 -82 122 0 -115 -85 -52 0 163 44 -117 0 63 42 -136 0 4 16 -71 0 -64 42 -142 0 -104 -15 106 0 4 139 -89 0 -70 -42 144 0 86 17 -91 0 7 -29 -21 0 -16 -127 -104 0 154 144 -157 0 -16 -121 -51 0 -124 164 142 0 -145 -39 -165 0 136 91 44 0 100 -33 -3 0 110 167 -47 0 2 -128 -105 0 -76 -142 73 0 55 95 -121 0 62 -12 20 0 20 -34 -14 0 -175 -99 19 0 166 74 175 0 61 -123 100 0 127 92 21 0 1 -38 -3 0 135 107 -38 0 174 12 19 0 176 97 136 0 152 -3 102 0 163 -108 -6 0 15 -47 -56 0 92 164 -105 0 -144 11 46 0 26 113 49 0 141 152 -7 0 -39 16 37 0 -129 -101 -50 0 -42 89 111 0 27 72 -84 0 167 -4 11 0 -154 -178 176 0 138 -149 -73 0 -89 9 -127 0 """ output = "UNSAT"
13.75871
22
0.596361
78404ffa33464f27a8bcaacd2ab9783411eff0bc
5,469
dart
Dart
lib/src/environment_specific/console_log_formatter_mixin.dart
PlugFox/l
ab19b9721f8c6b9410fc91278390bf476220deae
[ "WTFPL" ]
23
2020-04-28T20:05:14.000Z
2022-01-04T15:37:19.000Z
lib/src/environment_specific/console_log_formatter_mixin.dart
PlugFox/l
ab19b9721f8c6b9410fc91278390bf476220deae
[ "WTFPL" ]
13
2020-05-06T09:48:20.000Z
2022-03-30T11:31:44.000Z
lib/src/environment_specific/console_log_formatter_mixin.dart
PlugFox/l
ab19b9721f8c6b9410fc91278390bf476220deae
[ "WTFPL" ]
3
2021-03-26T11:27:46.000Z
2021-11-14T15:05:00.000Z
import 'package:meta/meta.dart'; import '../inner_zoned_mixin.dart'; import '../log_level.dart'; import 'message_formatting_pipeline.dart'; extension on StringBuffer { void writeEsc(String value) { this ..write(_esc) ..write(value); } String completeMessage(Object message) => (this ..write(']') ..write(' ') ..write(message)) .toString(); } /// {@nodoc} @internal mixin ConsoleLogFormatterMixin on MessageFormattingPipeline { @override String format({required Object message, required LogLevel logLevel}) { final prefix = logLevel.prefix; final printColors = getCurrentLogOptions()?.printColors ?? true; final formattedMessage = printColors ? logLevel.when<String>( shout: () => _shout(message, prefix), v: () => _v(message, prefix), error: () => _error(message, prefix), vv: () => _vv(message, prefix), warning: () => _warning(message, prefix), vvv: () => _vvv(message, prefix), info: () => _info(message, prefix), vvvv: () => _vvvv(message, prefix), debug: () => _debug(message, prefix), vvvvv: () => _vvvvv(message, prefix), vvvvvv: () => _vvvvvv(message, prefix), ) : _formatPlain(message, prefix); return super.format(message: formattedMessage, logLevel: logLevel); } static String _formatPlain(Object message, String prefix) => (StringBuffer('[')..write(prefix)).completeMessage(message); static String _formatStyled( Object message, String prefix, { String? font, String? foreground, String? background, }) { final buffer = StringBuffer('['); for (final value in [font, foreground, background]) { if (value != null) buffer.writeEsc(value); } buffer ..write(prefix) ..writeEsc(_reset); return buffer.completeMessage(message); } String _shout(Object message, String prefix) => _formatStyled( message, prefix, font: _ConsoleFont.underline.value, foreground: _ConsoleColor.black.foregroundValue, background: _ConsoleColor.white.backgroundValue, ); String _v(Object message, String prefix) => _formatStyled( message, prefix, font: _ConsoleFont.bold.value, foreground: _ConsoleColor.magenta.foregroundValue, ); String _error(Object message, String prefix) => _formatStyled( message, prefix, font: _ConsoleFont.bold.value, foreground: _ConsoleColor.red.foregroundValue, ); String _vv(Object message, String prefix) => _formatPlain(message, prefix); String _warning(Object message, String prefix) => _formatStyled( message, prefix, foreground: _ConsoleColor.yellow.foregroundValue, ); String _vvv(Object message, String prefix) => _formatPlain(message, prefix); String _info(Object message, String prefix) => _formatStyled( message, prefix, foreground: _ConsoleColor.green.foregroundValue, ); String _vvvv(Object message, String prefix) => _formatPlain(message, prefix); String _debug(Object message, String prefix) => _formatStyled( message, prefix, foreground: _ConsoleColor.cyan.foregroundValue, ); String _vvvvv(Object message, String prefix) => _formatPlain(message, prefix); String _vvvvvv(Object message, String prefix) => _formatPlain(message, prefix); } /// Ansi escape const String _esc = '\x1B['; /// Ansi reset const String _reset = '0m'; /// Available console colors enum _ConsoleColor { black, red, green, yellow, blue, magenta, cyan, white, byDefault, } extension _ConsoleColorX on _ConsoleColor { /// Ansi foreground colors for terminal String get foregroundValue { switch (this) { case _ConsoleColor.black: return '30m'; case _ConsoleColor.red: return '31m'; case _ConsoleColor.green: return '32m'; case _ConsoleColor.yellow: return '33m'; case _ConsoleColor.blue: return '34m'; case _ConsoleColor.magenta: return '35m'; case _ConsoleColor.cyan: return '36m'; case _ConsoleColor.white: return '37m'; case _ConsoleColor.byDefault: default: return ''; } } /// Ansi background colors for terminal String get backgroundValue { switch (this) { case _ConsoleColor.black: return '40m'; case _ConsoleColor.red: return '41m'; case _ConsoleColor.green: return '42m'; case _ConsoleColor.yellow: return '43m'; case _ConsoleColor.blue: return '44m'; case _ConsoleColor.magenta: return '45m'; case _ConsoleColor.cyan: return '46m'; case _ConsoleColor.white: return '47m'; case _ConsoleColor.byDefault: default: return ''; } } } /// Available console fonts enum _ConsoleFont { bold, underline, reversed, byDefault, } extension _ConsoleFontX on _ConsoleFont { /// Ansi decorations for terminal String get value { switch (this) { case _ConsoleFont.bold: return '1m'; case _ConsoleFont.underline: return '4m'; case _ConsoleFont.reversed: return '7m'; case _ConsoleFont.byDefault: default: return ''; } } }
25.437209
80
0.6226
b723fefae922b73dde92aba04057afde83e6c55d
215
cs
C#
src/SqlStreamStore/Streams/ReadNextStreamPage.cs
rvdkooy/SqlStreamStore
30e275fd3b44c55df41b9898ba58a070ff0be7ff
[ "MIT" ]
1
2017-02-23T15:58:18.000Z
2017-02-23T15:58:18.000Z
src/SqlStreamStore/Streams/ReadNextStreamPage.cs
rvdkooy/SqlStreamStore
30e275fd3b44c55df41b9898ba58a070ff0be7ff
[ "MIT" ]
null
null
null
src/SqlStreamStore/Streams/ReadNextStreamPage.cs
rvdkooy/SqlStreamStore
30e275fd3b44c55df41b9898ba58a070ff0be7ff
[ "MIT" ]
1
2020-04-24T16:47:15.000Z
2020-04-24T16:47:15.000Z
namespace SqlStreamStore.Streams { using System.Threading; using System.Threading.Tasks; public delegate Task<ReadStreamPage> ReadNextStreamPage(int nextVersion, CancellationToken cancellationToken); }
30.714286
114
0.804651
127938e8bf69ac6eaab0ed3aa3304497d41f7680
3,664
cs
C#
AutoForms/Controls/ControlGroup.cs
patrickabadi/AutoForms
52b9c08f54f23fbf1f0a9fc1b30ba788408247de
[ "MIT" ]
23
2020-09-18T23:56:31.000Z
2022-03-30T17:43:23.000Z
AutoForms/Controls/ControlGroup.cs
dev-thinks/AutoForms
52b9c08f54f23fbf1f0a9fc1b30ba788408247de
[ "MIT" ]
null
null
null
AutoForms/Controls/ControlGroup.cs
dev-thinks/AutoForms
52b9c08f54f23fbf1f0a9fc1b30ba788408247de
[ "MIT" ]
3
2021-04-13T10:58:40.000Z
2021-12-18T17:53:08.000Z
using AutoForms.Common; using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using Xamarin.Forms; namespace AutoForms.Controls { public class ControlGroup : ControlBase { protected Grid _grid; protected Grid _controlGrid; protected const double _spacing = 30; public ControlGroup(ControlConfig config):base(config) { } protected override View CreateControl(string bindingName, Type fieldType) => null; protected override View InitializeControl() { _grid = new Grid { VerticalOptions = LayoutOptions.StartAndExpand, RowDefinitions = { new RowDefinition {Height = GridLength.Auto}, new RowDefinition {Height = GridLength.Auto}, }, ColumnDefinitions = { new ColumnDefinition {Width = _spacing}, new ColumnDefinition {Width = GridLength.Auto}, new ColumnDefinition {Width = GridLength.Star}, } }; var b = new BoxView { Color = _config.SeparatorColor, WidthRequest = 8, }; Grid.SetRow(b, 0); Grid.SetColumn(b, 1); _grid.Children.Add(b); if(string.IsNullOrEmpty(Label) == false) { var style = _itemStyle; if(style == null) { style = LabelStyle; } var v = CreateLabel(Label, style, AutoFormsOrientation.Vertical, 0, 0) as Label; if(v != null) { Grid.SetColumnSpan(v, 3); _grid.Children.Add(v); } } _controlGrid = new Grid { VerticalOptions = LayoutOptions.StartAndExpand, RowDefinitions = { new RowDefinition {Height = GridLength.Auto}, } }; Grid.SetRow(_controlGrid, 0); Grid.SetColumn(_controlGrid, 2); _grid.Children.Add(_controlGrid); return _grid; } public override void SetGroupedProperty(PropertyInfo property) { var attributes = property.GetAttributes<AutoFormsAttribute>(); var attribute = GetFilteredAttribute(_config.Filter, attributes); if (attribute == null) { Debug.WriteLine($"ControlGroup.SetGroupedProperty - unable to create filtered control of name: {property.Name}"); return; } var config = new ControlConfig( _config.LayoutHorizontalPercentage, attribute, _config.LabelStyle, _config.EditorStyle, _config.SeparatorColor, property, _config.Filter); var v = CreateControl(config); if(v == null) { Debug.WriteLine($"ControlGroup.SetGroupedProperty - unable to create control of name: {property.Name}"); return; } Groups.Add(v); v.Initialize(); _controlGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); Grid.SetRow(v, _controlGrid.RowDefinitions.Count - 1); _controlGrid.Children.Add(v); } } }
30.789916
129
0.505731
1501790cdcf5c449c61865e0235f1daf46326582
7,092
dart
Dart
packages/sensors/lib/sensors.dart
dannyalbuquerque/plugins
9c3538b0ab6bb80ebf894d1d3c7a749232be5b0f
[ "BSD-3-Clause" ]
1
2021-01-18T14:52:09.000Z
2021-01-18T14:52:09.000Z
packages/sensors/lib/sensors.dart
dannyalbuquerque/plugins
9c3538b0ab6bb80ebf894d1d3c7a749232be5b0f
[ "BSD-3-Clause" ]
null
null
null
packages/sensors/lib/sensors.dart
dannyalbuquerque/plugins
9c3538b0ab6bb80ebf894d1d3c7a749232be5b0f
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 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. import 'dart:async'; import 'package:flutter/services.dart'; const EventChannel _accelerometerEventChannel = EventChannel('plugins.flutter.io/sensors/accelerometer'); const EventChannel _userAccelerometerEventChannel = EventChannel('plugins.flutter.io/sensors/user_accel'); const EventChannel _gyroscopeEventChannel = EventChannel('plugins.flutter.io/sensors/gyroscope'); /// Discrete reading from an accelerometer. Accelerometers measure the velocity /// of the device. Note that these readings include the effects of gravity. Put /// simply, you can use accelerometer readings to tell if the device is moving in /// a particular direction. class AccelerometerEvent { /// Contructs an instance with the given [x], [y], [z] and [timestamp] values. AccelerometerEvent(this.x, this.y, this.z, this.timestamp); /// Acceleration force along the x axis (including gravity) measured in m/s^2. /// /// When the device is held upright facing the user, positive values mean the /// device is moving to the right and negative mean it is moving to the left. final double x; /// Acceleration force along the y axis (including gravity) measured in m/s^2. /// /// When the device is held upright facing the user, positive values mean the /// device is moving towards the sky and negative mean it is moving towards /// the ground. final double y; /// Acceleration force along the z axis (including gravity) measured in m/s^2. /// /// This uses a right-handed coordinate system. So when the device is held /// upright and facing the user, positive values mean the device is moving /// towards the user and negative mean it is moving away from them. final double z; /// The time in milliseconds at which the event happened. /// The timestamp is the amount of time in milliseconds since the device booted. final double timestamp; @override String toString() => '[AccelerometerEvent (x: $x, y: $y, z: $z) @ $timestamp]'; } /// Discrete reading from a gyroscope. Gyroscopes measure the rate or rotation of /// the device in 3D space. class GyroscopeEvent { /// Contructs an instance with the given [x], [y], [z] and [timestamp] values. GyroscopeEvent(this.x, this.y, this.z, this.timestamp); /// Rate of rotation around the x axis measured in rad/s. /// /// When the device is held upright, this can also be thought of as describing /// "pitch". The top of the device will tilt towards or away from the /// user as this value changes. final double x; /// Rate of rotation around the y axis measured in rad/s. /// /// When the device is held upright, this can also be thought of as describing /// "yaw". The lengthwise edge of the device will rotate towards or away from /// the user as this value changes. final double y; /// Rate of rotation around the z axis measured in rad/s. /// /// When the device is held upright, this can also be thought of as describing /// "roll". When this changes the face of the device should remain facing /// forward, but the orientation will change from portrait to landscape and so /// on. final double z; /// The time in milliseconds at which the event happened. /// The timestamp is the amount of time in milliseconds since the device booted. final double timestamp; @override String toString() => '[GyroscopeEvent (x: $x, y: $y, z: $z) @ $timestamp]'; } /// Like [AccelerometerEvent], this is a discrete reading from an accelerometer /// and measures the velocity of the device. However, unlike /// [AccelerometerEvent], this event does not include the effects of gravity. class UserAccelerometerEvent { /// Contructs an instance with the given [x], [y], [z] and [timestamp] values. UserAccelerometerEvent(this.x, this.y, this.z, this.timestamp); /// Acceleration force along the x axis (excluding gravity) measured in m/s^2. /// /// When the device is held upright facing the user, positive values mean the /// device is moving to the right and negative mean it is moving to the left. final double x; /// Acceleration force along the y axis (excluding gravity) measured in m/s^2. /// /// When the device is held upright facing the user, positive values mean the /// device is moving towards the sky and negative mean it is moving towards /// the ground. final double y; /// Acceleration force along the z axis (excluding gravity) measured in m/s^2. /// /// This uses a right-handed coordinate system. So when the device is held /// upright and facing the user, positive values mean the device is moving /// towards the user and negative mean it is moving away from them. final double z; /// The time in milliseconds at which the event happened. /// The timestamp is the amount of time in milliseconds since the device booted. final double timestamp; @override String toString() => '[UserAccelerometerEvent (x: $x, y: $y, z: $z) @ $timestamp]'; } AccelerometerEvent _listToAccelerometerEvent(List<double> list) { return AccelerometerEvent(list[0], list[1], list[2], list[3]); } UserAccelerometerEvent _listToUserAccelerometerEvent(List<double> list) { return UserAccelerometerEvent(list[0], list[1], list[2], list[3]); } GyroscopeEvent _listToGyroscopeEvent(List<double> list) { return GyroscopeEvent(list[0], list[1], list[2], list[3]); } Stream<AccelerometerEvent> _accelerometerEvents; Stream<GyroscopeEvent> _gyroscopeEvents; Stream<UserAccelerometerEvent> _userAccelerometerEvents; final int _sampleRateDefault = 15; int _sampleRate; /// Set the specified sample rate if it is greater than zero. void setSensorsSampleRate(int sampleRate) { _sampleRate = (sampleRate > 0) ? sampleRate : _sampleRate; } /// A broadcast stream of events from the device accelerometer. Stream<AccelerometerEvent> get accelerometerEvents { if (_accelerometerEvents == null) { _accelerometerEvents = _accelerometerEventChannel .receiveBroadcastStream(_sampleRate ?? _sampleRateDefault) .map( (dynamic event) => _listToAccelerometerEvent(event.cast<double>())); } return _accelerometerEvents; } /// A broadcast stream of events from the device gyroscope. Stream<GyroscopeEvent> get gyroscopeEvents { if (_gyroscopeEvents == null) { _gyroscopeEvents = _gyroscopeEventChannel .receiveBroadcastStream(_sampleRate ?? _sampleRateDefault) .map((dynamic event) => _listToGyroscopeEvent(event.cast<double>())); } return _gyroscopeEvents; } /// Events from the device accelerometer with gravity removed. Stream<UserAccelerometerEvent> get userAccelerometerEvents { if (_userAccelerometerEvents == null) { _userAccelerometerEvents = _userAccelerometerEventChannel .receiveBroadcastStream(_sampleRate ?? _sampleRateDefault) .map((dynamic event) => _listToUserAccelerometerEvent(event.cast<double>())); } return _userAccelerometerEvents; }
39.620112
85
0.729554
a366b889dd0bf916a7f0c37f363cc9228eb6991f
643
ts
TypeScript
src/components/inspector/panel/TransformPanel.ts
gastrodia/ReEditor
212d1d4bc65de983b5769cc314833fa2e96e9355
[ "MIT" ]
1
2017-07-06T06:26:21.000Z
2017-07-06T06:26:21.000Z
src/components/inspector/panel/TransformPanel.ts
gastrodia/wasp-ui-editor
4abf747363dddc910303e059fbf5fad9a53f6c2f
[ "MIT" ]
null
null
null
src/components/inspector/panel/TransformPanel.ts
gastrodia/wasp-ui-editor
4abf747363dddc910303e059fbf5fad9a53f6c2f
[ "MIT" ]
null
null
null
import $ = require('jquery'); import {Component, View, coreDirectives, formDirectives} from 'angular2/angular2'; import angular2 = require('angular2/angular2'); import ng2Helper = require('../../ng2-library/ng2Helper'); import Panel = require('./Panel'); import AnchorModeField = require('../field/AnchorModeField'); const tpl = require('./transform-panel.html'); @Component({ selector: 'transform-panel', properties: ['objdata'] }) @View({ template: tpl, styles: [], directives: [AnchorModeField, Panel, coreDirectives, formDirectives] }) class TransformPanel { objdata; constructor() { } } export = TransformPanel;
23.814815
82
0.702955
f4d7c189b06030e086ebcb7122c9fd866309ba42
893
ts
TypeScript
src/lib/exportTypes/array.ts
paulgrotzke/parsing-lib
b0ba21226f2d37e6323b5d6b994da4305a35cae8
[ "MIT" ]
null
null
null
src/lib/exportTypes/array.ts
paulgrotzke/parsing-lib
b0ba21226f2d37e6323b5d6b994da4305a35cae8
[ "MIT" ]
null
null
null
src/lib/exportTypes/array.ts
paulgrotzke/parsing-lib
b0ba21226f2d37e6323b5d6b994da4305a35cae8
[ "MIT" ]
null
null
null
import { string, number, boolean, bigInt, symbol, fn } from './primitives' export const array = ( type: 'string' | 'number' | 'boolean' | 'bigInt' | 'symbol' | 'fn' | 'empty' | 'any' = 'any' ) => { const dic = { string: (val: string[]) => val.map((i) => string().parse(i)), number: (val: number[]) => val.map((i) => number().parse(i)), boolean: (val: boolean[]) => val.map((i) => boolean().parse(i)), bigInt: (val: bigint[]) => val.map((i) => bigInt().parse(i)), symbol: (val: symbol[]) => val.map((i) => symbol().parse(i)), fn: (val: ((val?: any) => any)[]) => val.map((i) => fn().parse(i)), empty: (val: void[]) => val.length === 0, any: (val: any[]) => true, } const greater0 = (val: any[]) => (val.length > 0 ? dic[type](val) : false) return { arrayParse: (val: any[]) => (Array.isArray(val) ? greater0(val) : false), type: type, } }
37.208333
94
0.522956
3f41deff03b69f1d4b4ecb79b752b63d59f81eb0
4,274
php
PHP
application/views/signup_view.php
richmartins/mtlaga
6be6250d3c8f75da78677775d24727e7e9bdff0c
[ "MIT" ]
2
2020-05-08T19:20:39.000Z
2020-05-14T11:17:15.000Z
application/views/signup_view.php
richmartins/mtlaga
6be6250d3c8f75da78677775d24727e7e9bdff0c
[ "MIT" ]
null
null
null
application/views/signup_view.php
richmartins/mtlaga
6be6250d3c8f75da78677775d24727e7e9bdff0c
[ "MIT" ]
null
null
null
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <style> .div_captcha_content{ display: flex; flex-direction: column; width: 100%; } .captcha_style_img { display: flex; align-items: center; align-content: space-around; justify-content: space-between; margin: .4em 0; } .captcha_style_form{ flex-direction: row; /* flex-wrap: wrap; */ } i.refresh-captcha:hover{ cursor: pointer; } </style> <div class="auth_flex_container"> <div class="auth_signup_<?=$this->session->flashdata('class');?>"> <?php if (null !== $this->session->flashdata('error')): ?> <p><?= $this->session->flashdata('error') ?></p> <?php endif;?> <?php if (null !== $this->session->flashdata('info')): ?> <p><?= $this->session->flashdata('info') ?></p> <?php endif;?> </div> </div> <div class="form_style_bck" > <p>S'inscrire</p> <form method="post" action="<?= site_url('auth/signup_process') ?>" > <div class="form_style_front" > <div class="form_style_title"> <p>Adresse mail</p> <input type="email" name="mail" class="form_input" required> </div> <div class="form_style_title"> <p>Mot de passe</p> <input id="password_input" type="password" name="password" class="form_input" required> <div class="form_style_signup_password_strengh"> <meter id="password-meter" low="4" high="4" min="0" max="10" value="0"></meter> <label class='stat_pass'> </label> </div> </div> <div class="form_style_title"> <p>Confirmer le mot de passe</p> <input type="password" name="password_confirm" class="form_input" required> </div> <!--Div principal contenant les flex-box--> <div class="form_style_title div_captcha_content"> <span>Êtes-vous humain ?</span> <div class="captcha_style_img"> <!--Ajout de l'image Captcha--> <img id="captcha" src="data:image/png;base64,<?= captcha(); ?>" alt="captcha"> <i class="fas fa-sync-alt refresh-captcha rotate captcha-image "></i> </div> <div class="captcha_style_form"> <input class="form_input" type="text" id="captcha" name="captcha" required> </div> </div> <div class="form_style_submit form_style_title"> <input id="form_signup_submit" type="submit" value="S'inscrire" class="form_input"> </div> <div class="form_style_link" id="signup_submit"> <p><a href="<?= base_url(); ?>auth/login">Retour à la page de connexion ?</a></p> </div> </div> </form> </div> <script> $(document).ready(function() { $('.refresh-captcha').click(function() { location.reload(); }) var strong = new RegExp("^(?=.*[A-Za-z])(?=.*[0-9])(?=.*[$@$!%*#?&])[A-Za-z0-9$@$!%*#?&]{8,}"); var medium = new RegExp('^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]{8,}'); var ok = new RegExp("^.{8}"); var low = new RegExp("^.{2}"); $('#password_input').keyup(function() { var value = $(this).val(); switch (true) { case strong.test(value): $('#password-meter').show(); $('#password-meter').val('10'); $('.stat_pass').empty(); $('.stat_pass').append('Mot de passe fort'); break; case medium.test(value): $('#password-meter').show(); $('#password-meter').val('7'); $('.stat_pass').empty(); $('.stat_pass').append('Mot de passe moyen'); break; case ok.test(value): $('#password-meter').show(); $('#password-meter').val('4'); $('.stat_pass').empty(); $('.stat_pass').append('Mot de passe bon'); break; case low.test(value): $('#password-meter').show(); $('#password-meter').val('1.5'); $('.stat_pass').empty(); $('.stat_pass').append('Mot de passe très faible'); break; case value = '': $('#password-meter').hide(); $('#password-meter').val('0'); $('.stat_pass').empty(); break; default: $('#password-meter').hide(); $('#password-meter').val('0'); $('.stat_pass').empty(); } }) }); </script>
33.131783
99
0.542583
20f19f8db7ce73c00d929e588c839e08dc4f4e9e
1,920
py
Python
lib/aquilon/worker/commands/del_netgroup_whitelist.py
ned21/aquilon
6562ea0f224cda33b72a6f7664f48d65f96bd41a
[ "Apache-2.0" ]
7
2015-07-31T05:57:30.000Z
2021-09-07T15:18:56.000Z
lib/aquilon/worker/commands/del_netgroup_whitelist.py
ned21/aquilon
6562ea0f224cda33b72a6f7664f48d65f96bd41a
[ "Apache-2.0" ]
115
2015-03-03T13:11:46.000Z
2021-09-20T12:42:24.000Z
lib/aquilon/worker/commands/del_netgroup_whitelist.py
ned21/aquilon
6562ea0f224cda33b72a6f7664f48d65f96bd41a
[ "Apache-2.0" ]
13
2015-03-03T11:17:59.000Z
2021-09-09T09:16:41.000Z
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2014,2015,2016,2017 Contributor # # 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. """Contains the logic for `aq del netgroup whitelist`.""" from aquilon.exceptions_ import ArgumentError from aquilon.aqdb.model import NetGroupWhiteList, Personality from aquilon.worker.broker import BrokerCommand from aquilon.worker.dbwrappers.change_management import ChangeManagement class CommandDelNetgroupWhitelist(BrokerCommand): required_parameters = ["netgroup"] def render(self, session, netgroup, user, justification, reason, logger, **arguments): dbng = NetGroupWhiteList.get_unique(session, name=netgroup, compel=True) # Validate ChangeManagement cm = ChangeManagement(session, user, justification, reason, logger, self.command, **arguments) cm.consider(dbng) cm.validate() q = session.query(Personality) q = q.filter(Personality.root_netgroups.contains(dbng)) pers = q.all() if pers: raise ArgumentError("Netgroup {0} used by following and cannot be deleted: ". format(netgroup) + ", ".join(sorted("{0}".format(p) for p in pers))) session.delete(dbng) session.flush()
38.4
102
0.677083
445e2c5ecb9cc7cb721237a11314539fc60fcfa0
684
lua
Lua
src/mod/elona/api/aspect/ItemBookAspect.lua
Ruin0x11/OpenNefia
548f1a1442eca704bb1c16b1a1591d982a34919f
[ "MIT" ]
109
2020-04-07T16:56:38.000Z
2022-02-17T04:05:40.000Z
src/mod/elona/api/aspect/ItemBookAspect.lua
Ruin0x11/OpenNefia
548f1a1442eca704bb1c16b1a1591d982a34919f
[ "MIT" ]
243
2020-04-07T08:25:15.000Z
2021-10-30T07:22:10.000Z
src/mod/elona/api/aspect/ItemBookAspect.lua
Ruin0x11/OpenNefia
548f1a1442eca704bb1c16b1a1591d982a34919f
[ "MIT" ]
15
2020-04-25T12:28:55.000Z
2022-02-23T03:20:43.000Z
local IItemBook = require("mod.elona.api.aspect.IItemBook") local Rand = require("api.Rand") local ItemBookAspect = class.class("ItemBookAspect", { IItemBook }) function ItemBookAspect:init(item, params) -- >>>>>>>> shade2/item.hsp:618 if iId(ci)=idBook :if iBookId(ci)=0:iBookId(ci)=i .. if params.book_id then self.book_id = params.book_id else local cands = data["elona.book"]:iter() :filter(function(book) return not book.no_generate end) :extract("_id") :to_list() self.book_id = Rand.choice(cands) end -- <<<<<<<< shade2/item.hsp:618 if iId(ci)=idBook :if iBookId(ci)=0:iBookId(ci)=i .. end return ItemBookAspect
32.571429
88
0.654971
6d866033f9cef6a25abfac495751ceeb36b4d4ca
1,347
c
C
code_guide/progs/20190728.review/draw_all_bst.c
YangXiaoHei/Interview_Question_Solutions
7c7c99be248f68c38856d655ecb4c36358bef8b1
[ "Apache-2.0" ]
null
null
null
code_guide/progs/20190728.review/draw_all_bst.c
YangXiaoHei/Interview_Question_Solutions
7c7c99be248f68c38856d655ecb4c36358bef8b1
[ "Apache-2.0" ]
null
null
null
code_guide/progs/20190728.review/draw_all_bst.c
YangXiaoHei/Interview_Question_Solutions
7c7c99be248f68c38856d655ecb4c36358bef8b1
[ "Apache-2.0" ]
null
null
null
#include "ds.h" #define ENQUEUE(q, x) queue_enqueue(q, (long)(x)) #define DEQUEUE(q) ((treenode *)queue_dequeue(q)) queue *gen_all_bst(int start, int end) { // 这个 queue 用来装 start -> end 产生的所有形态 // 的二叉树的根节点 queue *q = queue_create(); if (start > end) { ENQUEUE(q, NULL); return q; } // 对于 start -> end 之间所有的值 // 分别让他们各自充当头节点 for (int i = start; i <= end; i++) { // 创建头节点 treenode *root = treenode_create(i); // 当 i 成为头节点时,左右子树各有多少种形态? // left, right 是装有左右子树不同形态根节点的队列 queue *left = gen_all_bst(start, i - 1); queue *right = gen_all_bst(i + 1, end); // 对于每种左右子树 for (deque_node *ln = left->header; ln; ln = ln->next) { for (deque_node *rn = right->header; rn; rn = rn->next) { treenode *l = (treenode *)ln->val; treenode *r = (treenode *)rn->val; root->left = l; root->right = r; treenode *newtree = tree_clone(root); ENQUEUE(q, newtree); } } tree_release(&root); queue_release(&left); queue_release(&right); } return q; } int main(int argc, char *argv[]) { int n = 4; queue *q = gen_all_bst(1, n); while (!queue_empty(q)) tree_draw(DEQUEUE(q)); }
26.411765
69
0.512249
09287b8b33c8eb599819ab960d8f3d72154a436d
966
swift
Swift
TdlibKit/Models/ResendMessages.swift
modestman/tdlib-swift
0ef12cfe0d0a28db22e53e74d02c4f8e56b012cd
[ "MIT" ]
21
2019-09-29T20:05:41.000Z
2022-02-08T20:23:48.000Z
TdlibKit/Models/ResendMessages.swift
modestman/tdlib-swift
0ef12cfe0d0a28db22e53e74d02c4f8e56b012cd
[ "MIT" ]
3
2020-06-19T07:32:00.000Z
2021-09-16T16:33:22.000Z
TdlibKit/Models/ResendMessages.swift
modestman/tdlib-swift
0ef12cfe0d0a28db22e53e74d02c4f8e56b012cd
[ "MIT" ]
5
2020-01-11T05:58:04.000Z
2021-08-03T15:41:31.000Z
// // ResendMessages.swift // tl2swift // // Created by Code Generator // import Foundation /// Resends messages which failed to send. Can be called only for messages for which messageSendingStateFailed.can_retry is true and after specified in messageSendingStateFailed.retry_after time passed. If a message is re-sent, the corresponding failed to send message is deleted. Returns the sent messages in the same order as the message identifiers passed in message_ids. If a message can't be re-sent, null will be returned instead of the message public struct ResendMessages: Codable { /// Identifier of the chat to send messages public let chatId: Int64? /// Identifiers of the messages to resend. Message identifiers must be in a strictly increasing order public let messageIds: [Int64]? public init( chatId: Int64?, messageIds: [Int64]? ) { self.chatId = chatId self.messageIds = messageIds } }
32.2
450
0.727743
15fba55f24f325312ca868f121a2ad230ad4aaa2
271
rs
Rust
library/src/lib.rs
georgbramm/hope.rs
6f8f96265a6886ae31a5285d0894fd228a265d11
[ "MIT" ]
null
null
null
library/src/lib.rs
georgbramm/hope.rs
6f8f96265a6886ae31a5285d0894fd228a265d11
[ "MIT" ]
null
null
null
library/src/lib.rs
georgbramm/hope.rs
6f8f96265a6886ae31a5285d0894fd228a265d11
[ "MIT" ]
null
null
null
//! The backend library //#![deny(missing_docs)] pub mod bplus; pub mod scheme; pub mod elgamal; pub mod paillier; pub mod websocket; pub use crate::scheme::*; pub use crate::elgamal::*; pub use crate::paillier::*; pub use crate::bplus::*; pub use crate::websocket::*;
18.066667
28
0.693727
d1ec29b4079aaa3ebbb46f3989bed4d462a06ddf
1,201
rs
Rust
src/verbose.rs
lmburns/parallel
dc127577a505c7f728fc2947bb6be4ebef215f7e
[ "MIT" ]
1
2022-03-01T18:34:06.000Z
2022-03-01T18:34:06.000Z
src/verbose.rs
lmburns/parallel
dc127577a505c7f728fc2947bb6be4ebef215f7e
[ "MIT" ]
null
null
null
src/verbose.rs
lmburns/parallel
dc127577a505c7f728fc2947bb6be4ebef215f7e
[ "MIT" ]
null
null
null
use itoa; use std::io::{Stdout, Write}; pub fn total_inputs(stdout: &Stdout, threads: usize, inputs: usize) { let mut stdout = stdout.lock(); let _ = stdout.write(b"parallel: processing "); let _ = itoa::write(&mut stdout, inputs); let _ = stdout.write(b" inputs on "); let _ = itoa::write(&mut stdout, threads); let _ = stdout.write(b" threads\n"); } pub fn processing_task(stdout: &Stdout, job: usize, total: usize, input: &str) { let mut stdout = stdout.lock(); let _ = stdout.write(b"parallel: processing task #"); let _ = itoa::write(&mut stdout, job); let _ = stdout.write(b" of "); let _ = itoa::write(&mut stdout, total); let _ = stdout.write(b": '"); let _ = stdout.write(input.as_bytes()); let _ = stdout.write(b"'\n"); } pub fn task_complete(stdout: &Stdout, job: usize, total: usize, input: &str) { let mut stdout = stdout.lock(); let _ = stdout.write(b"parallel: completed task #"); let _ = itoa::write(&mut stdout, job); let _ = stdout.write(b" of "); let _ = itoa::write(&mut stdout, total); let _ = stdout.write(b": '"); let _ = stdout.write(input.as_bytes()); let _ = stdout.write(b"'\n"); }
35.323529
80
0.611157
f7839a8bb8ca22c867f79528ccb8f2dedf3ab2be
276
rb
Ruby
lib/mimic/subject_methods.rb
joshuaflanagan/mimic
cf4f67fa504880d4033370e5fbc5896ab291d686
[ "MIT" ]
null
null
null
lib/mimic/subject_methods.rb
joshuaflanagan/mimic
cf4f67fa504880d4033370e5fbc5896ab291d686
[ "MIT" ]
null
null
null
lib/mimic/subject_methods.rb
joshuaflanagan/mimic
cf4f67fa504880d4033370e5fbc5896ab291d686
[ "MIT" ]
null
null
null
module Mimic def self.subject_methods(cls) instance_method_names = cls.instance_methods.sort instance_method_names -= Mimic.preserved_methods instance_methods = instance_method_names.map do |method_name| cls.instance_method(method_name) end end end
25.090909
65
0.775362
652e39c39c00f85b2da90a92f1680221dd2035b4
6,080
css
CSS
figma-site/css/privacy-policy-page.css
amnamir00070/amnamir00070.github.io
0fc1c3505b2fe4be728299b7fc4ac762835be99d
[ "MIT" ]
1
2021-02-01T03:55:37.000Z
2021-02-01T03:55:37.000Z
figma-site/css/privacy-policy-page.css
amnamir00070/amnamir00070.github.io
0fc1c3505b2fe4be728299b7fc4ac762835be99d
[ "MIT" ]
null
null
null
figma-site/css/privacy-policy-page.css
amnamir00070/amnamir00070.github.io
0fc1c3505b2fe4be728299b7fc4ac762835be99d
[ "MIT" ]
1
2021-09-14T04:22:15.000Z
2021-09-14T04:22:15.000Z
@font-face { font-family: Roboto; src: url("fonts/Roboto-Light.ttf"); } .background { background: #F9FAFF; font-family: Roboto; padding: 0; margin: 0; } .mob-body { margin-top: 2rem; } .main-content { width: 100%; margin-right: auto; margin-left: auto; padding: 20px; } .grid-container { display: flex; flex-direction: row; } .main-col { width: 730px; margin-right: 38px; } .sidebar { width: 300px; height: 250px; box-shadow: rgb(100 100 111 / 20%) 2px 2px 29px 11px; border-radius: 25px; background-color: #fafafa; } .sidebar ul{ margin: 0%; padding: 0%; margin-top: 20px; margin-left: 25px; } .sidebar ul p{ margin: 0%; padding: 0%; font-size: 12px; font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif; font-weight: 500; color: #818181; margin-bottom: 2px; } .sidebar ul li{ list-style: none; font-size: 16px; padding: 2px; padding-left: 0%; color: #000000; } .sidebar ul li a{ color: #000000; } .sidebar ul li:hover a{ color: #3aabf0!important; text-decoration: none; } /* Sidebar mobile */ .add-part-mob { height: 250px; box-shadow: rgb(100 100 111 / 20%) 2px 2px 29px 11px; border-radius: 25px; background-color: #fafafa; margin: 1rem; } .add-part-mob ul{ margin: 0%; padding: 0%; margin-left: 25px; padding-top: 18px; padding-bottom: 18px; } .add-part-mob ul p{ margin: 0%; padding: 0%; font-size: 12px; font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif; font-weight: 500; color: #818181; margin-bottom: 2px; } .add-part-mob ul li{ list-style: none; font-size: 16px; padding: 2px; padding-left: 0%; color: #000000; } .add-part-mob ul li a{ color: #000000; } .add-part-mob ul li:hover a{ color: #3aabf0!important; text-decoration: none; } /* Sidebar mobile */ .main-content { margin-top: 73px; } @media only screen and (min-width: 992px) { .main-content { margin-right: auto; margin-left: auto; padding: 0px 10px; justify-content: center; } .main-col { width: 100%; } .main-col { width: 664px; } .sidebar { width: 300px; height: 250px; } } @media only screen and (min-width: 1280px) { .main-content { width: 1068px; margin-right: auto; margin-left: auto; padding: 0%; } .main-col { width: 730px; margin-right: 38px; } .page-title { font-size: 36px; line-height: 42.19px; color: #000000; font-weight: 400; font-family: Roboto; font-style: normal; margin-bottom: 31px; } .privacy-policy-text-container { width: 730px; } .privacy-policy-text-container .policy-content { font-size: 16px; line-height: 18.75px; color: #000000; font-weight: 400; font-family: Roboto; font-style: normal; } .sidebar { width: 300px; height: 250px; } footer { width: 600px; margin-left: auto; margin-right: auto; } } footer { justify-content: center; text-align: center; align-items: center; height: 14px; margin-bottom: 30px; margin-top: 37px; } footer span { color: #000000; height: 100%; font-style: normal; font-weight: normal; font-size: 12px; line-height: 14.06px; /* identical to box height */ text-align: center; font-family: Roboto; } footer .privacy-pages { cursor: pointer; color: #000000; } footer .privacy-pages:hover { color: #3aabf0!important; text-decoration: none; } .modes{ padding: 0%; margin: 0%; margin-left: 12px; } .modes button{ padding: 0; margin: 0%; height: 30px; width: 30px; font-size: 18px; border-radius: 25px; } .modes .btn-light{ /*color: #f4db87;*/ font-size: 20px; color: #f9d71c; background-color: #fff; box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2); border: none; } .modes .btn-light:hover{ color: #000; background-color: #fff; border: none; } .modes .btn-dark{ font-size: 15px; color: #FFD700; background-color: #3c3d46; box-shadow: 2px 2px 2px #888888; border: none; } .modes .btn-dark:hover{ color: #fff; border: none; } /* mobile modes */ .mob-modes{ padding: 0%; margin: 0%; } .mob-modes button{ padding: 0; margin: 0%; height: 30px; width: 30px; font-size: 18px; border-radius: 25px; } .mob-modes .btn-light{ color: #f9d71c; font-size: 20px; box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2); border: none; } .mob-modes .btn-light:hover{ color: #000; background-color: #fff; border: none; } .mob-modes .btn-dark{ font-size: 15px; color: #FFD700; box-shadow: 2px 2px 2px #888888; border: none; } .mob-modes .btn-dark:hover{ color: #fff; border: none; } /* back to top button */ #button { display: inline-block; background: linear-gradient(to right, #52A0FD 0%, #00e2fa 80%, #00e2fa 100%); width: 30px; height: 30px; text-align: center; border-radius: 25px; position: fixed; bottom: 80px; right: 30px; transition: background-color .3s, opacity .5s, visibility .5s; opacity: 0; visibility: hidden; z-index: 1000; } @media (min-width:992px) { #button{ bottom: 30px; } } #button::after { content: "\f106"; font-family: FontAwesome; font-weight: 300; font-style: normal; font-size: 20px; padding: 8px; color: #fff; } #button:hover { cursor: pointer; background-color: #333; } #button:active { background-color: #555; } #button.show { opacity: 1; visibility: visible; }
19.179811
137
0.580921
924024ec7209383c9bc6552c26ac96b45d7dac5b
2,250
swift
Swift
Packages/ClientRuntime/Sources/Middleware/Steps/DeserializeStep.swift
awslabs/smithy-swift
0faded826d80bd98f8c362daa6cab3d29a8f6340
[ "Apache-2.0" ]
7
2021-08-30T18:35:59.000Z
2022-02-17T07:41:06.000Z
Packages/ClientRuntime/Sources/Middleware/Steps/DeserializeStep.swift
awslabs/smithy-swift
0faded826d80bd98f8c362daa6cab3d29a8f6340
[ "Apache-2.0" ]
4
2021-09-17T22:26:30.000Z
2022-03-16T01:09:52.000Z
Packages/ClientRuntime/Sources/Middleware/Steps/DeserializeStep.swift
awslabs/smithy-swift
0faded826d80bd98f8c362daa6cab3d29a8f6340
[ "Apache-2.0" ]
3
2021-12-08T10:04:17.000Z
2022-03-15T20:47:41.000Z
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0. /// Reacts to the handler's response returned by the recipient of the request /// message. Deserializes the response into a structured type or error above /// stacks can react to. /// /// Should only forward Request to underlying handler. /// /// Takes Request, and returns result or error. /// /// Receives raw response, or error from underlying handler. public typealias DeserializeStep<O: HttpResponseBinding, E: HttpResponseBinding> = MiddlewareStep<HttpContext, SdkHttpRequest, OperationOutput<O>, SdkError<E>> public let DeserializeStepId = "Deserialize" public struct DeserializeStepHandler<OperationStackOutput: HttpResponseBinding, OperationStackError: HttpResponseBinding, H: Handler>: Handler where H.Context == HttpContext, H.Input == SdkHttpRequest, H.Output == OperationOutput<OperationStackOutput>, H.MiddlewareError == SdkError<OperationStackError> { public typealias Input = SdkHttpRequest public typealias Output = OperationOutput<OperationStackOutput> public typealias MiddlewareError = SdkError<OperationStackError> let handler: H public init(handler: H) { self.handler = handler } public func handle(context: HttpContext, input: Input) -> Result<Output, MiddlewareError> { return handler.handle(context: context, input: input) } } public struct OperationOutput<Output: HttpResponseBinding> { public var httpResponse: HttpResponse public var output: Output? public init(httpResponse: HttpResponse, output: Output? = nil) { self.httpResponse = httpResponse self.output = output } }
41.666667
116
0.568
c4ebcceb99ea1493cdca6d9dfd62fecda016417a
6,732
cpp
C++
CQGLFlocking/src/CQGLFlocking.cpp
colinw7/CQDemos
a66452e0f963613ae351fea4d078552c19aa002b
[ "MIT" ]
2
2019-12-22T09:49:25.000Z
2021-12-23T02:22:34.000Z
CQGLFlocking/src/CQGLFlocking.cpp
colinw7/CQDemos
a66452e0f963613ae351fea4d078552c19aa002b
[ "MIT" ]
null
null
null
CQGLFlocking/src/CQGLFlocking.cpp
colinw7/CQDemos
a66452e0f963613ae351fea4d078552c19aa002b
[ "MIT" ]
1
2019-04-01T13:35:49.000Z
2019-04-01T13:35:49.000Z
#include <CQGLFlocking.h> #include <CFlocking.h> #include <CQMenu.h> #include <CQGLControl.h> #include <CGLTexture.h> #include <QApplication> #include <QTimer> #include <QVBoxLayout> #include "images/bird1.xpm" #include "images/bird2.xpm" #include "images/bird3.xpm" #include "images/bird4.xpm" int main(int argc, char **argv) { QApplication app(argc, argv); CQGLFlocking *flocking = new CQGLFlocking; flocking->init(); flocking->resize(400, 400); flocking->show(); return app.exec(); } //------ CQGLFlocking:: CQGLFlocking() : CQMainWindow("CQGLFlocking") { flocking_ = new CFlocking; } QWidget * CQGLFlocking:: createCentralWidget() { QWidget *frame = new QWidget; QVBoxLayout *layout = new QVBoxLayout(frame); canvas_ = new CQGLFlockingCanvas(this); control_ = new CQGLControl(canvas_); toolbar_ = control_->createToolBar(); connect(control_, SIGNAL(stateChanged()), this, SLOT(controlSlot())); layout->addWidget(toolbar_); layout->addWidget(canvas_); timer_ = new QTimer; connect(timer_, SIGNAL(timeout()), this, SLOT(updateFlocking())); timer_->start(10); return frame; } void CQGLFlocking:: createWorkspace() { } void CQGLFlocking:: createMenus() { fileMenu_ = new CQMenu(this, "&File"); CQMenuItem *quitItem = new CQMenuItem(fileMenu_, "&Quit"); quitItem->setShortcut("Ctrl+Q"); quitItem->setStatusTip("Quit the application"); connect(quitItem->getAction(), SIGNAL(triggered()), this, SLOT(close())); //---- helpMenu_ = new CQMenu(this, "&Help"); //---- CQMenuItem *aboutItem = new CQMenuItem(helpMenu_, "&About"); aboutItem->setStatusTip("Show the application's About box"); //connect(aboutItem->getAction(), SIGNAL(triggered()), this, SLOT(aboutSlot())); } void CQGLFlocking:: createToolBars() { } void CQGLFlocking:: createStatusBar() { } void CQGLFlocking:: createDockWindows() { } void CQGLFlocking:: controlSlot() { canvas_->update(); } void CQGLFlocking:: updateFlocking() { flocking_->update(0.01); canvas_->update(); } //------ #define IMAGE_DATA(I) I, sizeof(I)/sizeof(char *) CQGLFlockingCanvas:: CQGLFlockingCanvas(CQGLFlocking *flocking) : QGLWidget(flocking), flocking_(flocking) { textures_[0] = NULL; textures_[1] = NULL; textures_[2] = NULL; textures_[3] = NULL; setFocusPolicy(Qt::StrongFocus); } void CQGLFlockingCanvas:: paintGL() { static GLfloat light_position[] = { 50.0, 50.0, 50.0, 0.0 }; static GLfloat colors[][4] = { { 1.0, 0.0, 0.0, 1.0 }, { 0.0, 1.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0, 1.0 }, { 1.0, 1.0, 0.0, 1.0 } }; static bool texture = false; if (textures_[0] == NULL) { textures_[0] = new CGLTexture; textures_[1] = new CGLTexture; textures_[2] = new CGLTexture; textures_[3] = new CGLTexture; textures_[0]->setImage(CImageMgrInst->createImage(CImageXPMSrc(IMAGE_DATA(bird1_data)))); textures_[1]->setImage(CImageMgrInst->createImage(CImageXPMSrc(IMAGE_DATA(bird2_data)))); textures_[2]->setImage(CImageMgrInst->createImage(CImageXPMSrc(IMAGE_DATA(bird3_data)))); textures_[3]->setImage(CImageMgrInst->createImage(CImageXPMSrc(IMAGE_DATA(bird4_data)))); } glLightfv(GL_LIGHT0, GL_POSITION, light_position); glEnable(GL_LIGHT0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CQGLControl *control = flocking_->getControl(); control->getDepthTest () ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); control->getCullFace () ? glEnable(GL_CULL_FACE) : glDisable(GL_CULL_FACE); control->getLighting () ? glEnable(GL_LIGHTING) : glDisable(GL_LIGHTING); control->getOutline () ? glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) : glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); control->getFrontFace () ? glFrontFace(GL_CW) : glFrontFace(GL_CCW); control->getSmoothShade() ? glShadeModel(GL_SMOOTH) : glShadeModel(GL_FLAT); CFlocking *flocking = flocking_->getFlocking(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if (texture) { glEnable(GL_TEXTURE_2D); //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } const CFlocking::BoidList &boids = flocking->getBoids(); CFlocking::BoidList::const_iterator pb1, pb2; for (pb1 = boids.begin(), pb2 = boids.end(); pb1 != pb2; ++pb1) { const CBoid *boid = *pb1; const CVector3D &pos = boid->getPos(); int id = boid->getFlock()->getId() % 4; if (texture) textures_[id]->bind(); CVector3D vel = boid->getVelocity().normalized(); CVector3D vel1(vel.getY(), -vel.getX(), vel.getZ()); CVector3D pos1 = pos + vel; CVector3D pos2 = pos + vel/2 + vel1/2; CVector3D pos3 = pos + vel/2 - vel1/2; //CVector3D pvel = vel.perp(); //CVector3D pos2 = pos + pvel/2; //CVector3D pos3 = pos - pvel/2; //const CRGBA &rgba = boid->getFlock()->getColor(); if (texture) { glBegin(GL_TRIANGLE_STRIP); glTexCoord2d(0,0); glVertex3f(pos .getX(), pos .getY(), pos .getZ()); // Bottom Left glTexCoord2d(0,1); glVertex3f(pos2.getX(), pos2.getY(), pos2.getZ()); // Top Left glTexCoord2d(1,0); glVertex3f(pos3.getX(), pos3.getY(), pos3.getZ()); // Bottom Right glTexCoord2d(1,1); glVertex3f(pos1.getX(), pos1.getY(), pos1.getZ()); // Top Right //glVertex3d(pos1.getX(), pos1.getY(), pos1.getZ()); //glVertex3d(pos2.getX(), pos2.getY(), pos2.getZ()); //glVertex3d(pos3.getX(), pos3.getY(), pos3.getZ()); glEnd(); } else { glBegin(GL_TRIANGLE_STRIP); glColor3fv(colors[id]); glTexCoord2d(0,0); glVertex3f(pos .getX(), pos .getY(), pos .getZ()); // Bottom Left glTexCoord2d(0,1); glVertex3f(pos2.getX(), pos2.getY(), pos2.getZ()); // Top Left glTexCoord2d(1,0); glVertex3f(pos3.getX(), pos3.getY(), pos3.getZ()); // Bottom Right glTexCoord2d(1,1); glVertex3f(pos1.getX(), pos1.getY(), pos1.getZ()); // Top Right glEnd(); } } } void CQGLFlockingCanvas:: resizeGL(int width, int height) { CQGLControl *control = flocking_->getControl(); control->handleResize(width, height); } void CQGLFlockingCanvas:: mousePressEvent(QMouseEvent *e) { CQGLControl *control = flocking_->getControl(); control->handleMousePress(e); update(); } void CQGLFlockingCanvas:: mouseReleaseEvent(QMouseEvent *e) { CQGLControl *control = flocking_->getControl(); control->handleMouseRelease(e); update(); } void CQGLFlockingCanvas:: mouseMoveEvent(QMouseEvent *e) { CQGLControl *control = flocking_->getControl(); control->handleMouseMotion(e); update(); } void CQGLFlockingCanvas:: keyPressEvent(QKeyEvent *) { }
21.646302
93
0.670826
402403b08aa7cd1a284dea80ded09a7a32840c1f
1,499
rb
Ruby
lib/realm/messaging/formatting/pretty_terminal_message_formatter.rb
ashmoran/realm
976eeba62941b70e4939bfcd3efe88809418ff7a
[ "MIT" ]
1
2015-08-18T11:22:40.000Z
2015-08-18T11:22:40.000Z
lib/realm/messaging/formatting/pretty_terminal_message_formatter.rb
ashmoran/realm
976eeba62941b70e4939bfcd3efe88809418ff7a
[ "MIT" ]
null
null
null
lib/realm/messaging/formatting/pretty_terminal_message_formatter.rb
ashmoran/realm
976eeba62941b70e4939bfcd3efe88809418ff7a
[ "MIT" ]
null
null
null
require 'term/ansicolor' module Realm module Messaging module Formatting class PrettyTerminalMessageFormatter include Term::ANSIColor # Because of the way AwesomePrint manages thread concurrency, # we have to have something we can initialize for each format run class PrettyAwesomeFormatter include Term::ANSIColor def initialize(inspector) @inspector = inspector end def attributes_string(attributes) attributes.map { |property, attribute| magenta(property.to_s) << ": " << @inspector.awesome(attribute) }.join(", ") end end def format(attrs) attributes_string = new_attributes_formatter.attributes_string( attrs.fetch(:attributes) ) "<" << cyan(attrs.fetch(:category).to_s) << " " << "type=" << magenta(attrs.fetch(:type).to_s) << " " << "version=" << attrs.fetch(:version).to_s << " " << "timestamp=" << attrs.fetch(:timestamp).inspect << " " << "attributes={" << attributes_string << "}" << ">" end private def new_attributes_formatter PrettyAwesomeFormatter.new(new_inspector) end def new_inspector AwesomePrint::Inspector.new( multiline: false, sort_keys: true ) end end end end end
27.254545
77
0.547698
2a17220855cd1bb0a68d97fcb7fc471e59a9ed40
22,435
rs
Rust
src/cxshaders_shared.rs
makepad/glui
6245631deb59f35dcde69927909ff8d8fd6e4006
[ "MIT" ]
12
2019-02-12T22:48:21.000Z
2020-09-16T21:55:25.000Z
src/cxshaders_shared.rs
makepad/glui
6245631deb59f35dcde69927909ff8d8fd6e4006
[ "MIT" ]
null
null
null
src/cxshaders_shared.rs
makepad/glui
6245631deb59f35dcde69927909ff8d8fd6e4006
[ "MIT" ]
null
null
null
// Shared shader-compiler code for generating GLSL and Metal shading language use crate::shader::*; //use crate::cxshaders::*; #[derive(Clone)] pub struct Sl{ pub sl:String, pub ty:String } #[derive(Clone)] pub struct SlErr{ pub msg:String } pub struct SlDecl{ pub name:String, pub ty:String } #[derive(Clone)] pub enum SlTarget{ Pixel, Vertex } pub struct SlCx<'a>{ pub depth:usize, pub target:SlTarget, pub defargs_fn:String, pub defargs_call:String, pub call_prefix:String, pub shader:&'a Shader, pub scope:Vec<SlDecl>, pub fn_deps:Vec<String>, pub fn_done:Vec<Sl>, pub auto_vary:Vec<ShVar> } pub enum MapCallResult{ Rename(String), Rewrite(String, String), None } impl<'a> SlCx<'a>{ pub fn scan_scope(&self, name:&str)->Option<&str>{ if let Some(decl) = self.scope.iter().find(|i| i.name == name){ return Some(&decl.ty); } None } pub fn get_type(&self, name:&str)->Result<&ShType, SlErr>{ if let Some(ty) = self.shader.find_type(name){ return Ok(ty); } Err(SlErr{msg:format!("Cannot find type {}", name)}) } } impl ShExpr{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ match self{ ShExpr::ShId(x)=>x.sl(cx), ShExpr::ShLit(x)=>x.sl(cx), ShExpr::ShAssign(x)=>x.sl(cx), ShExpr::ShCall(x)=>x.sl(cx), ShExpr::ShBinary(x)=>x.sl(cx), ShExpr::ShUnary(x)=>x.sl(cx), ShExpr::ShAssignOp(x)=>x.sl(cx), ShExpr::ShIf(x)=>x.sl(cx), ShExpr::ShWhile(x)=>x.sl(cx), ShExpr::ShForLoop(x)=>x.sl(cx), ShExpr::ShBlock(x)=>x.sl(cx), ShExpr::ShField(x)=>x.sl(cx), ShExpr::ShIndex(x)=>x.sl(cx), ShExpr::ShParen(x)=>x.sl(cx), ShExpr::ShReturn(x)=>x.sl(cx), ShExpr::ShBreak(x)=>x.sl(cx), ShExpr::ShContinue(x)=>x.sl(cx), } } } impl ShId{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ // ok so. we have to find our id on if let Some(ty) = cx.scan_scope(&self.name){ Ok(Sl{sl:self.name.to_string(), ty:ty.to_string()}) } else if let Some(cnst) = cx.shader.find_const(&self.name){ Ok(Sl{sl:self.name.to_string(), ty:cnst.ty.to_string()}) } else if let Some(var) = cx.shader.find_var(&self.name){ Ok(Sl{sl:cx.map_var(var), ty:var.ty.to_string()}) } else{ // id not found.. lets give an error Err(SlErr{ msg:format!("Id {} not resolved, is it declared?", self.name) }) } } } impl ShLit{ pub fn sl(&self, _cx:&mut SlCx)->Result<Sl,SlErr>{ // we do a literal match self{ ShLit::Int(val)=>{ Ok(Sl{sl:format!("{}", val), ty:"int".to_string()}) } ShLit::Str(val)=>{ Ok(Sl{sl:format!("\"{}\"", val), ty:"string".to_string()}) } ShLit::Float(val)=>{ if val.ceil() == *val{ Ok(Sl{sl:format!("{}.0", val), ty:"float".to_string()}) } else{ Ok(Sl{sl:format!("{}", val), ty:"float".to_string()}) } } ShLit::Bool(val)=>{ Ok(Sl{sl:format!("{}", val), ty:"bool".to_string()}) } } } } impl ShField{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let base = self.base.sl(cx)?; // we now have to figure out the type of member let shty = cx.get_type(&base.ty)?; // lets get our member if let Some(field) = shty.fields.iter().find(|i| i.name == self.member){ Ok(Sl{ sl:format!("{}.{}", base.sl, self.member), ty:field.ty.to_string() }) } else{ let mut mode = 0; let slots = shty.slots; if shty.name != "float" && shty.name != "vec2" && shty.name != "vec3" && shty.name != "vec4"{ return Err(SlErr{ msg:format!("member {} not found {}", self.member, base.ty) }) } if self.member.len() >4 { return Err(SlErr{ msg:format!("member {} not found or a valid swizzle of {}", self.member, base.ty) }) } for chr in self.member.chars(){ if chr == 'x' || chr == 'y' || chr == 'z' || chr == 'w'{ if chr == 'y' && slots<2{ mode = 3;} else if chr == 'z' && slots<3{ mode = 3;} else if chr == 'w' && slots<4{ mode = 3;}; if mode == 0{ mode = 1;} else if mode != 1{ return Err(SlErr{ msg:format!("member {} not a valid swizzle of {}", self.member, base.ty) }) } } else if chr == 'r' || chr == 'g' || chr == 'b' || chr == 'a'{ if chr == 'r' && slots<2{ mode = 3;} else if chr == 'g' && slots<3{ mode = 3;} else if chr == 'b' && slots<4{ mode = 3;}; if mode == 0{ mode = 2;} else if mode != 2{ return Err(SlErr{ msg:format!("member {} not a valid swizzle of {}", self.member, base.ty) }) } } } match self.member.len(){ 1=>return Ok(Sl{ sl:format!("{}.{}", base.sl, self.member), ty:"float".to_string() }), 2=>return Ok(Sl{ sl:format!("{}.{}", base.sl, self.member), ty:"vec2".to_string() }), 3=>return Ok(Sl{ sl:format!("{}.{}", base.sl, self.member), ty:"vec3".to_string() }), 4=>return Ok(Sl{ sl:format!("{}.{}", base.sl, self.member), ty:"vec4".to_string() }), _=>Err(SlErr{ msg:format!("member {} not cannot be found on type {}", self.member, base.ty) }) } } } } impl ShIndex{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let base = self.base.sl(cx)?; let index = self.index.sl(cx)?; // limit base type to vec2/3/4 if base.ty != "vec2" && base.ty != "vec3" && base.ty != "vec4"{ Err(SlErr{ msg:format!("index on unsupported type {}", base.ty) }) } else { Ok(Sl{ sl:format!("{}[{}]", base.sl, index.sl), ty:"float".to_string() }) } } } impl ShAssign{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let left = self.left.sl(cx)?; let right = self.right.sl(cx)?; if left.ty != right.ty{ Err(SlErr{ msg:format!("Left type {} not the same as right {} in assign {}={}", left.ty, right.ty, left.sl, right.sl) }) } else{ Ok(Sl{ sl:format!("{} = {}", left.sl, right.sl), ty:left.ty }) } } } impl ShAssignOp{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let left = self.left.sl(cx)?; let right = self.right.sl(cx)?; if left.ty != right.ty{ Err(SlErr{ msg:format!("Left type {} not the same as right {} in assign op {}{}{}", left.ty, self.op.to_string(), right.ty, left.sl, right.sl) }) } else{ Ok(Sl{ sl:format!("{}{}{}", left.sl, self.op.to_string(), right.sl), ty:left.ty }) } } } impl ShBinary{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let left = self.left.sl(cx)?; let right = self.right.sl(cx)?; if left.ty != right.ty{ if left.ty == "float" && (right.ty == "vec2" || right.ty == "vec3" || right.ty == "vec4"){ Ok(Sl{ sl:format!("{}{}{}", left.sl, self.op.to_string(), right.sl), ty:right.ty }) } else if right.ty == "float" && (left.ty == "vec2" || left.ty == "vec3" || left.ty == "vec4"){ Ok(Sl{ sl:format!("{}{}{}", left.sl, self.op.to_string(), right.sl), ty:left.ty }) } else{ Err(SlErr{ msg:format!("Left type {} not the same as right {} in binary op {}{}{}", left.ty, right.ty, left.sl, self.op.to_string(), right.sl) }) } } else{ Ok(Sl{ sl:format!("{}{}{}", left.sl, self.op.to_string(), right.sl), ty:left.ty }) } } } impl ShUnary{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let expr = self.expr.sl(cx)?; Ok(Sl{ sl:format!("{}{}", self.op.to_string(), expr.sl), ty:expr.ty }) } } impl ShParen{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let expr = self.expr.sl(cx)?; Ok(Sl{ sl:format!("({})", expr.sl), ty:expr.ty }) } } impl ShBlock{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let mut sl = String::new(); sl.push_str("{\n"); cx.depth += 1; for stmt in &self.stmts{ for _i in 0..cx.depth{ sl.push_str(" "); } match &**stmt{ ShStmt::ShLet(stmt) => { let out = stmt.sl(cx)?; sl.push_str(&out.sl); }, ShStmt::ShExpr(stmt) => { let out = stmt.sl(cx)?; sl.push_str(&out.sl); } ShStmt::ShSemi(stmt) => { let out = stmt.sl(cx)?; sl.push_str(&out.sl); } } sl.push_str(";\n"); } cx.depth -= 1; sl.push_str("}"); Ok(Sl{ sl:sl, ty:"void".to_string() }) } } impl ShCall{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ // we have a call, look up the call type on cx let mut out = String::new(); if let Some(shfn) = cx.shader.find_fn(&self.call){ let mut defargs_call = "".to_string(); if let Some(_block) = &shfn.block{ // not internal, so its a dep if cx.fn_deps.iter().find(|i| **i == self.call).is_none(){ cx.fn_deps.push(self.call.clone()); } defargs_call = cx.defargs_call.to_string(); out.push_str(&cx.call_prefix); }; // lets check our args and compose return type let mut gen_t = "".to_string(); let mut args_gl = Vec::new(); // loop over args and typecheck / fill in generics for arg in &self.args{ let arg_gl = arg.sl(cx)?; args_gl.push(arg_gl); }; let map_call= cx.map_call(&self.call, &args_gl); let ret_ty; if let MapCallResult::Rewrite(rewrite, rty) = map_call{ out.push_str(&rewrite); ret_ty = rty; } else{ if let MapCallResult::Rename(name) = map_call{ out.push_str(&name); } else{ out.push_str(&self.call); } out.push_str("("); // loop over args and typecheck / fill in generics for (i, arg_gl) in args_gl.iter().enumerate(){ //let arg_gl = args_gl[i];//.sl(cx)?; let in_ty = arg_gl.ty.clone(); if i != 0{ out.push_str(", "); } out.push_str(&arg_gl.sl); // lets check the type against our shfn if i >= shfn.args.len(){ return Err(SlErr{ msg:format!("Too many function arguments for call {} got:{} can use:{}", self.call, i+1, shfn.args.len()) }) } // lets check our arg type let fnarg = &shfn.args[i]; // lets see if ty is "T" or "O" or "F" or "B" if fnarg.ty == "T"{ // we already have a gen_t but its not the same if gen_t != "" && gen_t != in_ty{ return Err(SlErr{ msg:format!("Function type T incorrectly redefined for call {} type was {} given {} for arg {}", self.call, gen_t, in_ty, i) }) } gen_t = in_ty; } else if fnarg.ty == "F"{ // we have to be a float type if in_ty != "float" && in_ty != "vec2" && in_ty != "vec3" && in_ty != "vec4"{ return Err(SlErr{ msg:format!("Function type F is not a float-ty type for call {} for arg {} type {}", self.call, i, in_ty) }) } } else if fnarg.ty == "B"{ // have to be a boolvec if in_ty != "bool" && in_ty != "bvec2" && in_ty != "bvec3" && in_ty != "bvec4"{ return Err(SlErr{ msg:format!("Function arg is not a bool-ty type for call {} for arg {} type {}", self.call, i, in_ty) }) } gen_t = in_ty; } else if fnarg.ty != in_ty{ return Err(SlErr{ msg:format!("Arg wrong type for call {} for arg {} expected type {} got type {}", self.call, i, fnarg.ty, in_ty) }) } } // we have less args provided than the fn signature // check if they were optional if self.args.len() < shfn.args.len(){ for i in self.args.len()..shfn.args.len(){ let fnarg = &shfn.args[i]; if fnarg.ty != "O"{ return Err(SlErr{ msg:format!("Not enough args for call {} not enough args provided at {}, possible {}", self.call, i, shfn.args.len()) }) } } }; ret_ty = if shfn.ret == "T" || shfn.ret == "B"{ gen_t } else{ shfn.ret.clone() }; if defargs_call.len() != 0{ if self.args.len() != 0{ out.push_str(", "); } out.push_str(&defargs_call); } out.push_str(")"); } // check our arg types // if our return type is T, // use one of the args marked T as its type // make sure all args are the same type T Ok(Sl{ sl:out, ty:ret_ty }) } else{ // its a constructor call if let Some(glty) = cx.shader.find_type(&self.call){ out.push_str(&cx.map_type(&self.call)); out.push_str("("); // TODO check args for (i, arg) in self.args.iter().enumerate(){ let arg_gl = arg.sl(cx)?; if i != 0{ out.push_str(", "); } out.push_str(&arg_gl.sl); } out.push_str(")"); Ok(Sl{ sl:out, ty:glty.name.clone() }) } else{ Err(SlErr{ msg:format!("Cannot find function {}", self.call) }) } } } } impl ShIf{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let mut out = "".to_string(); out.push_str("if("); let cond = self.cond.sl(cx)?; out.push_str(&cond.sl); out.push_str(")"); let then = self.then_branch.sl(cx)?; out.push_str(&then.sl); if let Some(else_branch) = &self.else_branch{ let else_gl = else_branch.sl(cx)?; out.push_str("else "); out.push_str(&else_gl.sl); } Ok(Sl{ sl:out, ty:"void".to_string() }) } } impl ShWhile{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let mut out = "".to_string(); out.push_str("while("); let cond = self.cond.sl(cx)?; out.push_str(&cond.sl); out.push_str(")"); let body = self.body.sl(cx)?; out.push_str(&body.sl); Ok(Sl{ sl:out, ty:"void".to_string() }) } } impl ShForLoop{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let mut out = "".to_string(); out.push_str("for(int "); out.push_str(&self.iter); out.push_str("="); let from = self.from.sl(cx)?; out.push_str(&from.sl); out.push_str(";"); out.push_str(&self.iter); out.push_str(" < "); let to = self.to.sl(cx)?; out.push_str(&to.sl); out.push_str(";"); out.push_str(&self.iter); out.push_str("++)"); let body = self.body.sl(cx)?; out.push_str(&body.sl); Ok(Sl{ sl:out, ty:"void".to_string() }) } } impl ShReturn{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let mut out = "".to_string(); if let Some(expr) = &self.expr{ let expr_gl = expr.sl(cx)?; out.push_str("return "); out.push_str(&expr_gl.sl); } else{ out.push_str("return;"); } Ok(Sl{ sl:out, ty:"void".to_string() }) } } impl ShBreak{ pub fn sl(&self, _cx:&mut SlCx)->Result<Sl,SlErr>{ Ok(Sl{ sl:"break".to_string(), ty:"void".to_string() }) } } impl ShContinue{ pub fn sl(&self, _cx:&mut SlCx)->Result<Sl,SlErr>{ Ok(Sl{ sl:"continue".to_string(), ty:"void".to_string() }) } } impl ShLet{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let mut out = "".to_string(); let init = self.init.sl(cx)?; let ty = init.ty.clone(); if self.ty != "" && self.ty != init.ty{ return Err(SlErr{ msg:format!("Let definition {} type {} is different from initializer {}", self.name, self.ty, init.ty) }) } out.push_str(&cx.map_type(&ty)); out.push_str(" "); out.push_str(&self.name); out.push_str(" = "); // lets define our identifier on scope cx.scope.push(SlDecl{ name:self.name.clone(), ty:init.ty.clone() }); out.push_str(&init.sl); Ok(Sl{ sl:out, ty:"void".to_string() }) } } impl ShFn{ pub fn sl(&self, cx:&mut SlCx)->Result<Sl,SlErr>{ let mut out = "".to_string(); out.push_str(&cx.map_type(&self.ret)); out.push_str(" "); out.push_str(&cx.call_prefix); out.push_str(&self.name); out.push_str("("); for (i, arg) in self.args.iter().enumerate(){ if i != 0{ out.push_str(", "); } out.push_str(&cx.map_type(&arg.ty)); out.push_str(" "); out.push_str(&arg.name); cx.scope.push(SlDecl{ name:arg.name.clone(), ty:arg.ty.clone() }); }; if cx.defargs_fn.len() != 0{ if self.args.len() != 0{ out.push_str(", "); } out.push_str(&cx.defargs_fn); } out.push_str(")"); if let Some(block) = &self.block{ let block = block.sl(cx)?; out.push_str(&block.sl); }; Ok(Sl{ sl:out, ty:self.name.clone() }) } } pub fn assemble_fn_and_deps(sh:&Shader, cx:&mut SlCx)->Result<String, SlErr>{ let mut fn_local = Vec::new(); loop{ // find what deps we haven't done yet let fn_not_done = cx.fn_deps.iter().find(|cxfn|{ if let Some(_done) = cx.fn_done.iter().find(|i| i.ty == **cxfn){ false } else{ true } }); // do that dep. if let Some(fn_not_done) = fn_not_done{ let fn_to_do = sh.find_fn(fn_not_done); if let Some(fn_to_do) = fn_to_do{ cx.scope.clear(); let result = fn_to_do.sl(cx)?; cx.fn_done.push(result.clone()); fn_local.push(result); } else{ return Err(SlErr{msg:format!("Cannot find entry function {}", fn_not_done)}) } } else{ break; } } // ok lets reverse concatinate it let mut out = String::new(); for fnd in fn_local.iter().rev(){ out.push_str(&fnd.sl); out.push_str("\n"); } Ok(out) }
31.073407
157
0.41667
0668c6129b2b5082713ba0743d218cf6eae01974
957
dart
Dart
lib/functions/pickImageAndCrop.dart
WeWriteCodeWRC/coder_status
84d4e243e9abac07f140c53d22e32e508fbf045c
[ "MIT" ]
8
2021-08-25T16:13:01.000Z
2022-03-29T04:28:16.000Z
lib/functions/pickImageAndCrop.dart
WeWriteCodeWRC/coder_status
84d4e243e9abac07f140c53d22e32e508fbf045c
[ "MIT" ]
3
2022-03-16T09:38:19.000Z
2022-03-21T06:58:06.000Z
lib/functions/pickImageAndCrop.dart
WeWriteCodeWRC/coder_status
84d4e243e9abac07f140c53d22e32e508fbf045c
[ "MIT" ]
2
2021-11-19T15:42:37.000Z
2021-12-07T04:47:37.000Z
import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/painting.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:image_cropper/image_cropper.dart'; import 'package:image_picker/image_picker.dart'; final picker = ImagePicker(); Image avatarimage = Image(image: AssetImage('images/avatar1.jpg')); Future<File> cropSquareImage(File imageFile) async { return await ImageCropper.cropImage( sourcePath: imageFile.path, aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1), aspectRatioPresets: [CropAspectRatioPreset.square]); } Future<File> pickimage() async { final pickedfile = await picker.getImage(source: ImageSource.gallery); if (pickedfile == null) return null; final croppedfile = await cropSquareImage(File(pickedfile.path)); if (croppedfile != null) return croppedfile; else return null; }
30.870968
72
0.756531
e8d734a5a6f9c55c839888bbccf1404e13655658
1,134
swift
Swift
iOS/PluginClasses/Errors/ErrorViewConfiguration.swift
applicaster/zapp-player-plugin-brightcove
e5198221ad65fb4c9d0aceb307f340ef4bb39c42
[ "Apache-2.0" ]
null
null
null
iOS/PluginClasses/Errors/ErrorViewConfiguration.swift
applicaster/zapp-player-plugin-brightcove
e5198221ad65fb4c9d0aceb307f340ef4bb39c42
[ "Apache-2.0" ]
3
2018-10-17T11:48:34.000Z
2019-05-31T06:56:14.000Z
iOS/PluginClasses/Errors/ErrorViewConfiguration.swift
applicaster/zapp-player-plugin-brightcove
e5198221ad65fb4c9d0aceb307f340ef4bb39c42
[ "Apache-2.0" ]
null
null
null
// // ErrorViewConfiguration.swift // BrightcovePlayerPlugin // // Created by Roman Karpievich on 1/29/19. // import Foundation private enum CustomConfiguration: String { case videoPlayErrorMessage = "General_Error_Message" case videoPlayErrorButtonText = "General_Error_Button" case connectivityErrorMessage = "Connectivity_Error_Message" case connectivityErrorButtonText = "Connectivity_Error_Button" } class ErrorViewConfiguration { let videoPlayErrorMessage: String let videoPlayErrorButtonText: String let connectivityErrorMessage: String let connectivityErrorButtonText: String init(fromDictionary dict: NSDictionary) { videoPlayErrorMessage = dict[CustomConfiguration.videoPlayErrorMessage.rawValue] as? String ?? "" videoPlayErrorButtonText = dict[CustomConfiguration.videoPlayErrorButtonText.rawValue] as? String ?? "" connectivityErrorMessage = dict[CustomConfiguration.connectivityErrorMessage.rawValue] as? String ?? "" connectivityErrorButtonText = dict[CustomConfiguration.connectivityErrorButtonText.rawValue] as? String ?? "" } }
36.580645
117
0.773369
c68de9add5718f79dd1dd53174aec36a9976cd31
2,650
py
Python
docker/deps/torchlayers/torchlayers/regularization.py
DenDen047/SpatialNetworks
62a076d12af474b19b406e605d970662d9699cdf
[ "MIT" ]
3
2019-12-15T23:29:11.000Z
2020-05-08T03:26:20.000Z
docker/deps/torchlayers/torchlayers/regularization.py
DenDen047/SpatialNetworks
62a076d12af474b19b406e605d970662d9699cdf
[ "MIT" ]
null
null
null
docker/deps/torchlayers/torchlayers/regularization.py
DenDen047/SpatialNetworks
62a076d12af474b19b406e605d970662d9699cdf
[ "MIT" ]
3
2019-12-30T15:49:57.000Z
2020-04-30T08:06:18.000Z
import torch from ._dev_utils import modules class StochasticDepth(torch.nn.Module): """Randomly skip module during training with specified `p`, leaving inference untouched. Originally proposed by Gao Huang et. al in `Deep Networks with Stochastic Depth <www.arxiv.org/abs/1512.03385>`__. Originally devised as regularization, though `other research <https://web.stanford.edu/class/cs331b/2016/projects/kaplan_smith_jiang.pdf>`__ suggests: - "[...] StochasticDepth Nets are less tuned for low-level feature extraction but more tuned for higher level feature differentiation." - "[...] Stochasticity does not help with the ”dead neurons” problem; in fact the problem is actually more pronounced in the early layers. Nonetheless, the Stochastic Depth Network has relatively fewer dead neurons in later layers." It might be useful to employ this technique onto layers closer to the bottleneck. Parameters ---------- module: torch.nn.Module Any module whose output might be skipped (output shape of it has to be equal to the shape of inputs). p: float Probability to skip the module. """ def __init__(self, module: torch.nn.Module, p: float = 0.5): super().__init__() if not 0 < p < 1: raise ValueError( "Stochastic Depth p has to be between 0 and 1, " f"but got {p}" ) self.module: torch.nn.Module = module self.p: float = p self._sampler = torch.nn.Parameter(torch.Tensor(1), requires_grad=False) def forward(self, inputs): if self._sampler.uniform_() < self.p and self.training: return inputs return self.module(inputs) class Dropout(modules.InferDimension): """Randomly zero out some of the tensor elements. Based on input shape it either creates `2D` or `3D` version of dropout for inputs of shape `4D`, `5D` respectively (including batch as first dimension). For every other dimension, standard `torch.nn.Dropout` will be used. Otherwise works like standard PyTorch's `Dropout <https://pytorch.org/docs/stable/nn.html#dropout-layers>`__ Parameters ---------- p: float, optional Probability of an element to be zeroed. Default: ``0.5`` inplace: bool, optional If ``True``, will do this operation in-place. Default: ``False`` """ def __init__(self, p=0.5, inplace=False): super().__init__(p=p, inplace=inplace) # Dropout can have any input shape according to documentation def _module_not_found(self, inputs): return torch.nn.Dropout
36.805556
155
0.673585
05f5a3774dfdff522dee36b45d1f8e16494992e8
396
py
Python
server/dq/migrations/0002_alter_downloadjob_priority.py
tomaso/download-queue
ac2f02427d129d525a8ca32299d085461ac9c20b
[ "Apache-2.0" ]
null
null
null
server/dq/migrations/0002_alter_downloadjob_priority.py
tomaso/download-queue
ac2f02427d129d525a8ca32299d085461ac9c20b
[ "Apache-2.0" ]
5
2021-06-23T13:46:07.000Z
2021-07-26T14:50:51.000Z
server/dq/migrations/0002_alter_downloadjob_priority.py
tomaso/download-queue
ac2f02427d129d525a8ca32299d085461ac9c20b
[ "Apache-2.0" ]
null
null
null
# Generated by Django 3.2 on 2021-04-22 06:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("dq", "0001_initial"), ] operations = [ migrations.AlterField( model_name="downloadjob", name="priority", field=models.DecimalField(decimal_places=0, max_digits=10), ), ]
20.842105
71
0.603535
20e7ea4db004acfe47ec7c785de5574643a81c00
6,493
py
Python
linear.py
PVirie/neatly_active_classifier
d83fe42c5ada770f5927ac8adaa453bd5eac6a6a
[ "MIT" ]
null
null
null
linear.py
PVirie/neatly_active_classifier
d83fe42c5ada770f5927ac8adaa453bd5eac6a6a
[ "MIT" ]
null
null
null
linear.py
PVirie/neatly_active_classifier
d83fe42c5ada770f5927ac8adaa453bd5eac6a6a
[ "MIT" ]
null
null
null
import torch import os class Conceptor: def __init__(self, device, max_bases=-1, file_path=None): print("init") self.device = device self.max_bases = max_bases self.weights = [] self.importances = [] self.file_path = file_path self.max_input_channel = 0 self.count_bases = 0 self.orders = [] def save(self): if self.file_path: torch.save({"weights": self.weights, "importances": self.importances, "orders": self.orders}, self.file_path) def load(self): if self.file_path: temp = torch.load(self.file_path) self.weights = temp["weights"] self.importances = temp["importances"] self.orders = temp["orders"] def learn(self, input, expand_depth=1, expand_threshold=1e-4, expand_steps=1000, start_base_order=None, verbose=False): print("learn") self.max_input_channel = max(self.max_input_channel, input.shape[1]) criterion = torch.nn.MSELoss(reduction='mean') with torch.no_grad(): if start_base_order is not None: current_order = start_base_order else: current_order = self.count_bases mark = self.count_bases prev_loss = 0 for k in range(expand_steps): if self.max_bases > 0 and expand_depth + self.count_bases > self.max_bases: print("Stop expansion at", self.count_bases, "bases, before exceeding the maximum bases.") break if len(self.weights) is not 0: input_ = self.project(input) else: input_ = torch.zeros(1, input.shape[1], device=self.device) residue = input - input_ rloss = criterion(input_, input) if rloss.item() < expand_threshold: print("Stop expansion after", self.count_bases - mark, "bases, small reconstruction loss.", rloss.item()) break if abs(rloss.item() - prev_loss) < expand_threshold: print("Stop expansion after", self.count_bases - mark, "bases, small delta error.", rloss.item(), prev_loss) break # expand A = torch.empty(input.shape[1], expand_depth, device=self.device, requires_grad=False) M = torch.empty(expand_depth, device=self.device, requires_grad=False) AA = torch.matmul(torch.transpose(residue, 0, 1), residue) U, S, V = torch.svd(AA) A_ = V[:, 0:expand_depth] A.copy_(A_) check = S[expand_depth - 1].item() if abs(check) < expand_threshold: print("Failed solution, continue...", check) continue S_ = torch.sqrt(S[:expand_depth]) M.copy_(S_) # merge self.weights.append(A) self.importances.append(M) self.count_bases += expand_depth for i in range(expand_depth): self.orders.append(current_order) current_order += 1 prev_loss = rloss.item() return self.count_bases - mark def __internal__scale(self, input, importances): res = torch.div(input, torch.reshape(torch.cat(importances, dim=0), [1, -1])) return res def __internal__descale(self, input, importances): res = torch.mul(input, torch.reshape(torch.cat(importances, dim=0), [1, -1])) return res def __internal__forward(self, input, weights): res = torch.cat([ torch.matmul(input[:, 0:f.shape[0]], f) for f in weights ], dim=1) return res def __internal__get_canvas(self, hidden, weights, depth_out=0): depth_out = max(depth_out, self.max_input_channel) for f in weights: depth_out = max(depth_out, f.shape[0]) canvas = torch.zeros([hidden.shape[0], depth_out], device=self.device) return canvas def __internal__backward(self, hidden, weights, depth_out=0): canvas = self.__internal__get_canvas(hidden, weights, depth_out) from_depth = 0 for f in weights: to_depth = from_depth + f.shape[1] addition = torch.matmul(hidden[:, from_depth:to_depth], torch.transpose(f, 0, 1)) occupied_depth = f.shape[0] canvas[:, 0:occupied_depth] = canvas[:, 0:occupied_depth] + addition from_depth = to_depth return canvas # ----------- public functions --------------- def __lshift__(self, input): with torch.no_grad(): res = self.__internal__forward(input, self.weights) # output = self.__internal__scale(res, self.importances) return res def __rshift__(self, hidden): with torch.no_grad(): # norm = self.__internal__descale(hidden, self.importances) canvas = self.__internal__backward(hidden, self.weights) return canvas def project(self, input): hidden = self.__internal__forward(input, self.weights) input_ = self.__internal__backward(hidden, self.weights, input.shape[1]) return input_ def get_orders(self): return self.orders def get_count(self): return self.count_bases if __name__ == '__main__': print("assert conceptor preserves the containment property") dtype = torch.float device = torch.device("cuda:0") dir_path = os.path.dirname(os.path.realpath(__file__)) layer1 = Conceptor(device, file_path=os.path.join(dir_path, "weights", "linear_layer1.wt")) layer2 = Conceptor(device) criterion = torch.nn.MSELoss(reduction='mean') # if the model is correctly implemented, the total number of steps should not exceed min(x1.shape[0], x1.shape[1]) x1 = torch.rand(20, 30, device=device) x2 = torch.rand(20, 30, device=device) layer1.learn(x1, 1) x1_1 = layer1 << x1 layer2.learn(x1_1, 1) x1_2 = layer2 << x1_1 x_ = layer1 >> (layer2 >> x1_2) loss = criterion(x_, x1) print(loss.item()) layer1.learn(x2, 1) x2_1 = layer1 << x2 layer2.learn(x2_1, 1) hidden = (layer2 << (layer1 << x1)) x_ = layer1 >> (layer2 >> hidden) loss = criterion(x_, x1) print(loss.item())
32.959391
128
0.581549
f557bc935fd905c66c07e607fd551d2344b9176e
724
asm
Assembly
TP2/fun:fact.asm
kuoa/assembly-misc
5992cedee5c486768fc9daeb653ffbbb17810f06
[ "MIT" ]
null
null
null
TP2/fun:fact.asm
kuoa/assembly-misc
5992cedee5c486768fc9daeb653ffbbb17810f06
[ "MIT" ]
null
null
null
TP2/fun:fact.asm
kuoa/assembly-misc
5992cedee5c486768fc9daeb653ffbbb17810f06
[ "MIT" ]
null
null
null
.data n: .word 5 .text main: addiu $29, $29, -8 sw $31, 4($29) la $4, n # @n lw $4, 0($4) # val n jal fact or $4, $2, $0 ori $2, $0, 1 syscall # print fact(n) ori $2, $0, 10 syscall # exit lw $31, 4($29) addiu $29, $29, 8 jr $31 ############################################## fact: addiu $29, $29, -12 sw $31, 8($29) sw $10, 4($29) # $4 contains n bgtz $4, general # n > 0 then jump ori $2, $0, 1 # n <= 0 then return 1 jr $31 general: or $10, $4, $0 # save n value addi $4, $4, -1 # n = n -1 jal fact # fact(n-1) # $2 contains fact(n-1) mult $2, $10 # n * fact (n-1) mflo $2 # $2 = n * fact(n-1) lw $31, 8($29) lw $10, 4($29) addiu $29, $29, 12 jr $31
12.482759
47
0.447514
1460a2abfae5ecb26ee47bd8767fa7d2464add88
5,617
ts
TypeScript
src/app/App.ts
oimchat/oim-e
2d764557a434f47d0dce6c947bfc2e3d5cbc799e
[ "Apache-2.0" ]
3
2021-05-28T08:12:57.000Z
2021-11-21T08:33:09.000Z
src/app/App.ts
oimchat/oim-web
b6efbcffc4576a4bfe8aa47a429b7fc462f1d181
[ "Apache-2.0" ]
null
null
null
src/app/App.ts
oimchat/oim-web
b6efbcffc4576a4bfe8aa47a429b7fc462f1d181
[ "Apache-2.0" ]
4
2021-02-09T08:09:05.000Z
2022-02-23T10:09:02.000Z
import AppContext from '@/app/base/context/AppContext'; import ConnectHandler from '@/app/base/net/ConnectHandler'; import auth from '@/app/common/auth/Auth'; import SystemNetController from '@/app/com/main/module/business/system/controller/SystemNetController'; import LoginController from '@/app/com/main/module/business/index/controller/LoginController'; import PromptHandler from '@/app/com/client/define/prompt/PromptHandler'; import LaunchInitializerBox from '@/app/base/initialize/LaunchInitializerBox'; import LaunchInitializer from '@/app/base/initialize/LaunchInitializer'; import DefaultPromptHandlerImpl from '@/app/impl/default/client/prompt/DefaultPromptHandlerImpl'; import EnterInitializerBox from '@/app/base/initialize/EnterInitializerBox'; import InformationInitializer from '@/app/com/main/initialize/impl/InformationInitializer'; import ViewInitializer from '@/app/com/main/initialize/impl/ViewInitializer'; import ListInitializer from '@/app/com/main/initialize/impl/ListInitializer'; import PersonalInitializer from '@/app/com/main/initialize/impl/PersonalInitializer'; import ActionInitializer from '@/app/initialize/ActionInitializer'; import HttpInitializer from '@/app/initialize/HttpInitializer'; import NetModule from '@/app/com/common/module/NetModule'; import Prompter from '@/app/com/client/component/Prompter'; import ServerInitializer from '@/app/initialize/ServerInitializer'; import ComponentInitializer from '@/app/initialize/ComponentInitializer'; import ListenerInitializer from '@/app/initialize/ListenerInitializer'; import DefaultViewBuilder from '@/app/impl/default/DefaultViewBuilder'; import LaunchOrder from '@/app/LaunchOrder'; import AppLoader from '@/app/AppLoader'; class App { public appContext: AppContext = new AppContext(); public promptHandler: PromptHandler = new DefaultPromptHandlerImpl(); public actionLoader: AppLoader = new AppLoader(); public disconnection = false; constructor() { this.initializeApp(); LaunchOrder.start(this, 'constructor'); } public logout(): void { LaunchOrder.start(this, 'logout'); this.clearAuth(); this.closeNet(); this.buildAppContext(); this.initializeApp(); this.initializeLaunch(); } public initializeApp(): void { this.buildDefaultView(); // this.actionLoader.load(); } public initializeLaunch(): void { LaunchOrder.start(this, 'initialize'); this.initializeNetServer(); this.buildModule(); this.buildLaunch(); const launchInitializerBox = this.appContext.getMaterial(LaunchInitializerBox); launchInitializerBox.initialize(); const own = this; const connectHandler: ConnectHandler = { onIdle(): void { // TODO if (auth.isLogin()) { const snc: SystemNetController = own.appContext.getMaterial(SystemNetController); snc.heartbeat(); } }, onBreak(): void { // TODO const lc: LoginController = own.appContext.getMaterial(LoginController); lc.reconnect(); }, onConnectStatusChange(isConnected: boolean): void { // TODO if (auth.isLogin()) { own.disconnection = !isConnected; } else { own.disconnection = false; } if (!isConnected && auth.isLogin()) { own.prompt('网络已断开!'); } }, onError(): void { // TODO }, onClose(): void { // TODO }, onOpen(): void { // TODO const lc: LoginController = own.appContext.getMaterial(LoginController); lc.reAuth(); }, } as ConnectHandler; const netModule: NetModule = this.appContext.getMaterial(NetModule); netModule.netServer.setConnectHandler(connectHandler); } public prompt(message: string, title?: string, type?: string) { const prompter: Prompter = this.appContext.getMaterial(Prompter); prompter.prompt(message, title, type); } private clearAuth() { auth.clear(); } private closeNet() { const netModule: NetModule = this.appContext.getMaterial(NetModule); netModule.netServer.setSocketHost(''); netModule.netServer.closeNetSocket(); } private buildAppContext() { this.appContext = new AppContext(); } private buildDefaultView(): void { const builder = new DefaultViewBuilder(this.appContext); } private buildModule(): void { this.appContext.getMaterial(EnterInitializerBox); this.appContext.getMaterial(InformationInitializer); this.appContext.getMaterial(ListInitializer); this.appContext.getMaterial(PersonalInitializer); this.appContext.getMaterial(ViewInitializer); } private buildLaunch(): void { this.appContext.getMaterial(ActionInitializer); this.appContext.getMaterial(ComponentInitializer); this.appContext.getMaterial(HttpInitializer); this.appContext.getMaterial(ListenerInitializer); this.appContext.getMaterial(ServerInitializer); } private initializeNetServer(): void { const netModule: NetModule = this.appContext.getMaterial(NetModule); netModule.initializeNetServer(); } } export default new App();
37.952703
103
0.655688
4bdc221e0327722f39916db44bd5352c9dc306ac
3,074
h
C
aws-cpp-sdk-fms/include/aws/fms/model/PutAppsListResult.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-fms/include/aws/fms/model/PutAppsListResult.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-fms/include/aws/fms/model/PutAppsListResult.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/fms/FMS_EXPORTS.h> #include <aws/fms/model/AppsListData.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace FMS { namespace Model { class AWS_FMS_API PutAppsListResult { public: PutAppsListResult(); PutAppsListResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); PutAppsListResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The details of the Firewall Manager applications list.</p> */ inline const AppsListData& GetAppsList() const{ return m_appsList; } /** * <p>The details of the Firewall Manager applications list.</p> */ inline void SetAppsList(const AppsListData& value) { m_appsList = value; } /** * <p>The details of the Firewall Manager applications list.</p> */ inline void SetAppsList(AppsListData&& value) { m_appsList = std::move(value); } /** * <p>The details of the Firewall Manager applications list.</p> */ inline PutAppsListResult& WithAppsList(const AppsListData& value) { SetAppsList(value); return *this;} /** * <p>The details of the Firewall Manager applications list.</p> */ inline PutAppsListResult& WithAppsList(AppsListData&& value) { SetAppsList(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the applications list.</p> */ inline const Aws::String& GetAppsListArn() const{ return m_appsListArn; } /** * <p>The Amazon Resource Name (ARN) of the applications list.</p> */ inline void SetAppsListArn(const Aws::String& value) { m_appsListArn = value; } /** * <p>The Amazon Resource Name (ARN) of the applications list.</p> */ inline void SetAppsListArn(Aws::String&& value) { m_appsListArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the applications list.</p> */ inline void SetAppsListArn(const char* value) { m_appsListArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the applications list.</p> */ inline PutAppsListResult& WithAppsListArn(const Aws::String& value) { SetAppsListArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the applications list.</p> */ inline PutAppsListResult& WithAppsListArn(Aws::String&& value) { SetAppsListArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the applications list.</p> */ inline PutAppsListResult& WithAppsListArn(const char* value) { SetAppsListArn(value); return *this;} private: AppsListData m_appsList; Aws::String m_appsListArn; }; } // namespace Model } // namespace FMS } // namespace Aws
28.728972
117
0.67339
d63441ce302555a2da9a23202b339a8218f922c1
517
cs
C#
src/DND.Web.DynamicForms/Mvc/LookupTables/Notifications/LookupTablesNotifications.cs
davidikin45/DigitalNomadDaveAspNetCore
99be5389605223aaa7be87d778eb1a66c0c08340
[ "MIT" ]
null
null
null
src/DND.Web.DynamicForms/Mvc/LookupTables/Notifications/LookupTablesNotifications.cs
davidikin45/DigitalNomadDaveAspNetCore
99be5389605223aaa7be87d778eb1a66c0c08340
[ "MIT" ]
null
null
null
src/DND.Web.DynamicForms/Mvc/LookupTables/Notifications/LookupTablesNotifications.cs
davidikin45/DigitalNomadDaveAspNetCore
99be5389605223aaa7be87d778eb1a66c0c08340
[ "MIT" ]
null
null
null
using DND.Common.ApplicationServices.SignalR; using DND.Common.SignalRHubs; using DND.Domain.DynamicForms.LookupTables.Dtos; using Microsoft.AspNetCore.SignalR; namespace DND.Web.DynamicForms.Mvc.LookupTables.Notifications { public class LookupTablesNotifications : ISignalRHubMap { public void MapHub(HubRouteBuilder routes, string signalRUrlPrefix) { routes.MapHub<ApiNotificationHub<LookupTableDto>>(signalRUrlPrefix + "/forms/lookup-tables/notifications"); } } }
32.3125
119
0.758221
db76bb5201a18610ea6989e9a77356ea5e67809a
1,353
php
PHP
resources/views/admin/products/index.blade.php
alansslva/laravel-codedelivery
da451e8a6819de894e1f2802cebf6fa0b7bfafd4
[ "MIT" ]
null
null
null
resources/views/admin/products/index.blade.php
alansslva/laravel-codedelivery
da451e8a6819de894e1f2802cebf6fa0b7bfafd4
[ "MIT" ]
null
null
null
resources/views/admin/products/index.blade.php
alansslva/laravel-codedelivery
da451e8a6819de894e1f2802cebf6fa0b7bfafd4
[ "MIT" ]
null
null
null
@extends('app') @section('content') <div class="container"> <h3>Produtos</h3> <a href="{{ route('admin.products.create') }}"> <button class="btn">Criar Produto</button> </a> <table class="table"> <thead> <tr> <th>ID</th> <th>Produto</th> <th>Categoria</th> <th>Preço</th> <th>Ação</th> </tr> </thead> <tbody> @foreach($products as $product) <tr> <td>{{ $product->id }}</td> <td>{{ $product->name }}</td> <td>{{ $product->category->name }}</td> <td>{{ $product->price }}</td> <td> <a href="{{ route('admin.products.edit', ['id' => $product->id]) }}"> <button class="btn">Editar</button> </a> <a href="{{ route('admin.products.destroy', ['id' => $product->id]) }}"> <button class="btn">Apagar</button> </a> </td> </tr> @endforeach </tbody> </table> {!! $products->render() !!} </div> @endsection
26.529412
96
0.351072
cdb6e38acde832139ad3345864a292b1aa8c333b
9,974
cs
C#
src/WPF/ArcGISRuntime.WPF.Viewer/Samples/Layers/CreateAndSaveKmlFile/CreateAndSaveKmlFile.xaml.cs
lboyd93/arcgis-runtime-samples-dotnet
e07e37a89b15f60fc9599646f1fdba4a2cbb476d
[ "Apache-2.0" ]
2
2020-04-25T18:41:47.000Z
2021-03-22T19:08:25.000Z
src/WPF/ArcGISRuntime.WPF.Viewer/Samples/Layers/CreateAndSaveKmlFile/CreateAndSaveKmlFile.xaml.cs
munakbey/arcgis-runtime-samples-dotnet
53b8e9b604341a84a83add346a1d1c0f5b5374f8
[ "Apache-2.0" ]
null
null
null
src/WPF/ArcGISRuntime.WPF.Viewer/Samples/Layers/CreateAndSaveKmlFile/CreateAndSaveKmlFile.xaml.cs
munakbey/arcgis-runtime-samples-dotnet
53b8e9b604341a84a83add346a1d1c0f5b5374f8
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Esri. // // 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. using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Ogc; using Esri.ArcGISRuntime.UI; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows; using System.Windows.Controls; using Geometry = Esri.ArcGISRuntime.Geometry.Geometry; namespace ArcGISRuntime.WPF.Samples.CreateAndSaveKmlFile { [ArcGISRuntime.Samples.Shared.Attributes.Sample( "Create and save KML file", "Layers", "Construct a KML document and save it as a KMZ file.", "", "Featured")] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData()] public partial class CreateAndSaveKmlFile { private KmlDocument _kmlDocument; private KmlDataset _kmlDataset; private KmlLayer _kmlLayer; private KmlPlacemark _currentPlacemark; public CreateAndSaveKmlFile() { InitializeComponent(); Initialize(); } private void Initialize() { // Create the map. MyMapView.Map = new Map(Basemap.CreateImagery()); // Set the colors for the color picker. System.Reflection.PropertyInfo[] propertylist = typeof(Color).GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); List<Color> colorList = propertylist.Select(x => (Color)x.GetValue(x)).ToList(); colorList.RemoveAt(0); ColorPicker.ItemsSource = colorList; ColorPicker.SelectedIndex = 0; // Set the images for the point icon picker. List<string> iconLinks = new List<string>() { "https://static.arcgis.com/images/Symbols/Shapes/BlueCircleLargeB.png", "https://static.arcgis.com/images/Symbols/Shapes/BlueDiamondLargeB.png", "https://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png", "https://static.arcgis.com/images/Symbols/Shapes/BluePin2LargeB.png", "https://static.arcgis.com/images/Symbols/Shapes/BlueSquareLargeB.png", "https://static.arcgis.com/images/Symbols/Shapes/BlueStarLargeB.png" }; List<Uri> iconList = iconLinks.Select(x => new Uri(x)).ToList(); IconPicker.ItemsSource = iconList; IconPicker.SelectedIndex = 0; // Set up a new kml document and kml layer. ResetKml(); } private void ResetKml() { // Clear any existing layers from the map. MyMapView.Map.OperationalLayers.Clear(); // Reset the most recently placed placemark. _currentPlacemark = null; // Create a new KML document. _kmlDocument = new KmlDocument() { Name = "KML Sample Document" }; // Create a KML dataset using the KML document. _kmlDataset = new KmlDataset(_kmlDocument); // Create the KML layer using the KML dataset. _kmlLayer = new KmlLayer(_kmlDataset); // Add the KML layer to the map. MyMapView.Map.OperationalLayers.Add(_kmlLayer); } private async void Edit_Click(object sender, RoutedEventArgs e) { try { // Hide the base UI and enable the complete button. ShapesPanel.Visibility = Visibility.Hidden; CompleteButton.Visibility = Visibility.Visible; SaveResetGrid.IsEnabled = false; // Create variables for the sketch creation mode and color. SketchCreationMode creationMode; // Set the creation mode and UI based on which button called this method. switch (((Button)sender).Name) { case nameof(PointButton): creationMode = SketchCreationMode.Point; InstructionsText.Text = "Tap to add a point."; StyleText.Text = "Select an icon for the placemark."; break; case nameof(PolylineButton): creationMode = SketchCreationMode.Polyline; InstructionsText.Text = "Tap to add a vertex."; StyleText.Text = "Select a color for the placemark."; break; case nameof(PolygonButton): creationMode = SketchCreationMode.Polygon; InstructionsText.Text = "Tap to add a vertex."; StyleText.Text = "Select a color for the placemark."; break; default: return; } // Get the user-drawn geometry. Geometry geometry = await MyMapView.SketchEditor.StartAsync(creationMode, true); // Project the geometry to WGS84 (WGS84 is required by the KML standard). Geometry projectedGeometry = GeometryEngine.Project(geometry, SpatialReferences.Wgs84); // Create a KmlGeometry using the new geometry. KmlGeometry kmlGeometry = new KmlGeometry(projectedGeometry, KmlAltitudeMode.ClampToGround); // Create a new placemark. _currentPlacemark = new KmlPlacemark(kmlGeometry); // Add the placemark to the KmlDocument. _kmlDocument.ChildNodes.Add(_currentPlacemark); // Enable the style editing UI. StyleBorder.Visibility = Visibility.Visible; MainUI.IsEnabled = false; // Choose whether to enable the icon picker or color picker. IconPicker.Visibility = creationMode == SketchCreationMode.Point ? Visibility.Visible : Visibility.Collapsed; ColorPicker.Visibility = creationMode != SketchCreationMode.Point ? Visibility.Visible : Visibility.Collapsed; } catch (ArgumentException) { MessageBox.Show("Unsupported Geometry", "Error"); } finally { // Reset the UI. ShapesPanel.Visibility = Visibility.Visible; CompleteButton.Visibility = Visibility.Collapsed; InstructionsText.Text = "Select the type of feature you would like to add."; // Enable the save and reset buttons. SaveResetGrid.IsEnabled = true; } } private void Apply_Style_Click(object sender, RoutedEventArgs e) { // Create a new style for the placemark. _currentPlacemark.Style = new KmlStyle(); // Set the style for that Placemark. switch (_currentPlacemark.GraphicType) { // Create a KmlIconStyle using the selected icon. case KmlGraphicType.Point: _currentPlacemark.Style.IconStyle = new KmlIconStyle(new KmlIcon((Uri)IconPicker.SelectedItem), 1.0); break; // Create a KmlLineStyle using the selected color value. case KmlGraphicType.Polyline: _currentPlacemark.Style.LineStyle = new KmlLineStyle((Color)ColorPicker.SelectedItem, 8); break; // Create a KmlPolygonStyle using the selected color value. case KmlGraphicType.Polygon: _currentPlacemark.Style.PolygonStyle = new KmlPolygonStyle((Color)ColorPicker.SelectedItem); _currentPlacemark.Style.PolygonStyle.IsFilled = true; _currentPlacemark.Style.PolygonStyle.IsOutlined = false; break; } // Reset the UI. StyleBorder.Visibility = Visibility.Collapsed; MainUI.IsEnabled = true; } private void No_Style_Click(object sender, RoutedEventArgs e) { // Reset the UI. StyleBorder.Visibility = Visibility.Collapsed; MainUI.IsEnabled = true; } private void Complete_Click(object sender, RoutedEventArgs e) { try { // Finish the sketch. MyMapView.SketchEditor.CompleteCommand.Execute(null); } catch (ArgumentException) { } } private async void Save_Click(object sender, RoutedEventArgs e) { // Open a save dialog for the user. SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "kmz files (*.kmz)|*.kmz"; saveFileDialog.FilterIndex = 1; if (saveFileDialog.ShowDialog() == true) { try { // Write the KML document to the chosen path. await _kmlDocument.SaveAsAsync(saveFileDialog.FileName); MessageBox.Show("Item saved."); } catch { MessageBox.Show("File not saved."); } } } private void Reset_Click(object sender, RoutedEventArgs e) { ResetKml(); } } }
39.737052
167
0.580509
4575f1c3527e225921e38f6821449f2eb60bd89b
58
py
Python
dxm/lib/DxJobs/DxJobCounter.py
experiortec/dxm-toolkit
b2ab6189e163c62fa8d7251cd533d2a36430d44a
[ "Apache-2.0" ]
5
2018-08-23T15:47:05.000Z
2022-01-19T23:38:18.000Z
dxm/lib/DxJobs/DxJobCounter.py
experiortec/dxm-toolkit
b2ab6189e163c62fa8d7251cd533d2a36430d44a
[ "Apache-2.0" ]
59
2018-10-15T10:37:00.000Z
2022-03-22T20:49:25.000Z
dxm/lib/DxJobs/DxJobCounter.py
experiortec/dxm-toolkit
b2ab6189e163c62fa8d7251cd533d2a36430d44a
[ "Apache-2.0" ]
12
2019-03-08T19:59:13.000Z
2021-12-16T03:28:04.000Z
rows_total = 0 rows_masked = 0 ret = 0 profileret = 0
11.6
16
0.655172