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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
21ca244acd8058df7849f076cff96d9e6e67183f
| 6,442
|
js
|
JavaScript
|
docs/search/functions_11.js
|
FurongYe/IOHexperimenter
|
ebc54792cf5b2a3ce23b59c56a6264339ea64072
|
[
"BSD-3-Clause"
] | null | null | null |
docs/search/functions_11.js
|
FurongYe/IOHexperimenter
|
ebc54792cf5b2a3ce23b59c56a6264339ea64072
|
[
"BSD-3-Clause"
] | 1
|
2022-03-27T00:10:58.000Z
|
2022-03-27T00:10:58.000Z
|
docs/search/functions_11.js
|
FurongYe/IOHexperimenter
|
ebc54792cf5b2a3ce23b59c56a6264339ea64072
|
[
"BSD-3-Clause"
] | 1
|
2022-03-23T12:35:55.000Z
|
2022-03-23T12:35:55.000Z
|
var searchData=
[
['time_5franges_1001',['time_ranges',['../classioh_1_1trigger_1_1_during.html#aefa7a4d14e6880aac30a6385b0ba3c9b',1,'ioh::trigger::During']]],
['track_5fproblem_1002',['track_problem',['../structioh_1_1suite_1_1_suite_1_1_iterator.html#a2e9b0683c491572d43ba780a46a340be',1,'ioh::suite::Suite::Iterator']]],
['transform_5fobjectives_1003',['transform_objectives',['../classioh_1_1problem_1_1bbob_1_1_attractive_sector.html#a1c1c21f7f3edebf4767394a301083f21',1,'ioh::problem::bbob::AttractiveSector::transform_objectives()'],['../classioh_1_1problem_1_1_b_b_o_b.html#adda50860dc4abdeeade7c60596ce7f16',1,'ioh::problem::BBOB::transform_objectives()'],['../classioh_1_1problem_1_1bbob_1_1_bueche_rastrigin.html#a7f34a7bbce2fccff57ce7327f68bc444',1,'ioh::problem::bbob::BuecheRastrigin::transform_objectives()'],['../classioh_1_1problem_1_1bbob_1_1_katsuura.html#a960420656410133addb047e6f4262e44',1,'ioh::problem::bbob::Katsuura::transform_objectives()'],['../classioh_1_1problem_1_1bbob_1_1_schaffers.html#ac46f5cd0bcd45ece69d42450d61264d5',1,'ioh::problem::bbob::Schaffers::transform_objectives()'],['../classioh_1_1problem_1_1bbob_1_1_step_ellipsoid.html#a2209a0c4d8d8f0e7f0e8c55571c9beba',1,'ioh::problem::bbob::StepEllipsoid::transform_objectives()'],['../classioh_1_1problem_1_1bbob_1_1_weierstrass.html#a6e74172ea1d8e4fbe4d1f180d3dea2af',1,'ioh::problem::bbob::Weierstrass::transform_objectives()'],['../classioh_1_1problem_1_1_p_b_o.html#a7e86a8d6ddbf7232ca5c31eff308aa8d',1,'ioh::problem::PBO::transform_objectives()'],['../classioh_1_1problem_1_1_problem.html#a47cda64061790c2b2b0c2bb4c208b377',1,'ioh::problem::Problem::transform_objectives()'],['../classioh_1_1problem_1_1_wrapped_problem.html#ae836918dbda64c847ce4d9825df3a278',1,'ioh::problem::WrappedProblem::transform_objectives()'],['../classioh_1_1problem_1_1_w_model.html#a1a1aefac44c2cd9e3dd3a161be7ed65b',1,'ioh::problem::WModel::transform_objectives()']]],
['transform_5fvariables_1004',['transform_variables',['../classioh_1_1problem_1_1bbob_1_1_attractive_sector.html#afd79c0136bc8a7dce922314c178db1fe',1,'ioh::problem::bbob::AttractiveSector::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_bent_cigar.html#a2a310a0aaf91eabcfb83186f56522c45',1,'ioh::problem::bbob::BentCigar::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_bueche_rastrigin.html#a4fd938505364c606644afcf7b6fe7644',1,'ioh::problem::bbob::BuecheRastrigin::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_different_powers.html#a19801c18d6d8f61a522c425989b33dec',1,'ioh::problem::bbob::DifferentPowers::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_discus.html#acbee0ecc7a599c8d0503da9ba136faf0',1,'ioh::problem::bbob::Discus::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_ellipsoid_base.html#af190391a66f4e3e8c23ffde934221abe',1,'ioh::problem::bbob::EllipsoidBase::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_ellipsoid_rotated.html#af7f94fe4be2e46396fca2c9fcd2a5c73',1,'ioh::problem::bbob::EllipsoidRotated::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_griewank_rosen_brock.html#ad470c1443b832b804aa070afa26b7d70',1,'ioh::problem::bbob::GriewankRosenBrock::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_katsuura.html#a4e3317561c1221dfd00bf865ea72d769',1,'ioh::problem::bbob::Katsuura::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_rastrigin_base.html#a5f33701c9f3137cf95ae3061822c3457',1,'ioh::problem::bbob::RastriginBase::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_rastrigin_rotated.html#a837d4dbab420b019a3996b3d4632bb32',1,'ioh::problem::bbob::RastriginRotated::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_rosenbrock_base.html#a487b53bf7c893bafa53044956e22d54c',1,'ioh::problem::bbob::RosenbrockBase::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_rosenbrock_rotated.html#a2a5e2a087a2a76923c39cec1af4c901c',1,'ioh::problem::bbob::RosenbrockRotated::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_schaffers.html#a9ca9a28485bba6b972558b8cefa36607',1,'ioh::problem::bbob::Schaffers::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_schwefel.html#a2c29eac5da3ab4ef468c37c74d8683d9',1,'ioh::problem::bbob::Schwefel::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_sharp_ridge.html#ab1f208572073b95d19de4b9a5de0dcc3',1,'ioh::problem::bbob::SharpRidge::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_sphere.html#a416687ff69b2780f61229694cce2593a',1,'ioh::problem::bbob::Sphere::transform_variables()'],['../classioh_1_1problem_1_1bbob_1_1_weierstrass.html#a34677a16351a6aec9fcf2958bde865a8',1,'ioh::problem::bbob::Weierstrass::transform_variables()'],['../classioh_1_1problem_1_1_p_b_o.html#ab7509f9cbafc8b51aea2bfc816418a68',1,'ioh::problem::PBO::transform_variables()'],['../classioh_1_1problem_1_1_problem.html#a7673c3bf03e3743bae9fec30f35ae62a',1,'ioh::problem::Problem::transform_variables()'],['../classioh_1_1problem_1_1_wrapped_problem.html#a8aa1133f8affa08d288cf606df097e1b',1,'ioh::problem::WrappedProblem::transform_variables()'],['../classioh_1_1problem_1_1_w_model.html#a289deb8dd961f7900ab422860ec12e06',1,'ioh::problem::WModel::transform_variables()']]],
['transformationstate_1005',['TransformationState',['../structioh_1_1problem_1_1_b_b_o_b_1_1_transformation_state.html#a253e867722e7dbe45430f24b2542966b',1,'ioh::problem::BBOB::TransformationState']]],
['transformedy_1006',['TransformedY',['../structioh_1_1watch_1_1_transformed_y.html#ad2cc288edf849c0b382ee34210dbe5c9',1,'ioh::watch::TransformedY']]],
['transformedybest_1007',['TransformedYBest',['../structioh_1_1watch_1_1_transformed_y_best.html#a7f472d68d4d897552f3f7c1fe8106fe5',1,'ioh::watch::TransformedYBest']]],
['trigger_1008',['trigger',['../classioh_1_1_logger.html#a6512e30b152073802eae818758054897',1,'ioh::Logger']]],
['triggers_1009',['triggers',['../classioh_1_1trigger_1_1_set.html#ab1d0ea581c5855d69f64095807fedc33',1,'ioh::trigger::Set']]],
['type_1010',['type',['../classioh_1_1common_1_1_f_optimization_type.html#a9dc6c0c0a8d35a86db216903919e0fbe',1,'ioh::common::FOptimizationType::type()'],['../classioh_1_1trigger_1_1_on_improvement.html#a49930a6b4958d734ee34019bfb796f07',1,'ioh::trigger::OnImprovement::type()']]],
['type_5fname_1011',['type_name',['../namespaceioh_1_1common.html#a5975c051598fd88b74343ea4b56620e0',1,'ioh::common']]]
];
| 429.466667
| 3,312
| 0.827383
|
4ee600fac45e55d775f4ed0e974b4dafa265f1c4
| 2,216
|
cc
|
C++
|
src/logkafka/file_position_entry.cc
|
Qihoo360/logkafka
|
f329b5a9806e0b0f716884759edbe54e72e4dec0
|
[
"MIT"
] | 568
|
2015-06-23T07:41:50.000Z
|
2022-03-30T11:32:05.000Z
|
src/logkafka/file_position_entry.cc
|
Qihoo360/logkafka
|
f329b5a9806e0b0f716884759edbe54e72e4dec0
|
[
"MIT"
] | 26
|
2015-09-27T07:25:31.000Z
|
2021-07-25T13:30:09.000Z
|
src/logkafka/file_position_entry.cc
|
Qihoo360/logkafka
|
f329b5a9806e0b0f716884759edbe54e72e4dec0
|
[
"MIT"
] | 138
|
2015-06-23T07:41:50.000Z
|
2021-12-13T02:31:40.000Z
|
///////////////////////////////////////////////////////////////////////////
//
// logkafka - Collect logs and send lines to Apache Kafka v0.8+
//
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Qihoo 360 Technology Co., Ltd. All rights reserved.
//
// Licensed under the MIT 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://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////
#include "logkafka/file_position_entry.h"
namespace logkafka {
const size_t FilePositionEntry::POS_SIZE = 16;
const size_t FilePositionEntry::INO_OFFSET = 17;
const size_t FilePositionEntry::INO_SIZE = 8;
const int FilePositionEntry::LN_OFFSET = 25;
const int FilePositionEntry::SIZE = 26;
FilePositionEntry::FilePositionEntry(FILE *file, off_t seek)
{/*{{{*/
m_file = file;
m_seek = seek;
}/*}}}*/
bool FilePositionEntry::update(ino_t inode, off_t pos)
{/*{{{*/
fseek(m_file, m_seek, SEEK_SET);
fprintf(m_file, "%016llx\t%08x",
(unsigned long long)pos, (unsigned int)inode);
return true;
}/*}}}*/
bool FilePositionEntry::updatePos(off_t pos)
{/*{{{*/
fseek(m_file, m_seek, SEEK_SET);
fprintf(m_file, "%016llx", (unsigned long long)pos);
return true;
}/*}}}*/
off_t FilePositionEntry::readPos()
{/*{{{*/
fseek(m_file, m_seek, SEEK_SET);
char buf[POS_SIZE + 1] = {'\0'};
return (1 == fread(buf, POS_SIZE, 1, m_file)) ?
hexstr2num(buf, -1): -1;
}/*}}}*/
ino_t FilePositionEntry::readInode()
{/*{{{*/
fseek(m_file, m_seek + INO_OFFSET, SEEK_SET);
char buf[INO_SIZE + 1] = {'\0'};
return (1 == fread(buf, INO_SIZE, 1, m_file)) ?
hexstr2num(buf, INO_NONE): INO_NONE;
}/*}}}*/
} // namespace logkafka
| 30.777778
| 75
| 0.603791
|
0df01ab99a4e1a4b1cb9835c99202afd058c3edb
| 352
|
cs
|
C#
|
src/client/Microsoft.Identity.Client/Instance/Discovery/IUserMetadataProvider.cs
|
MiggieNRG/microsoft-authentication-library-for-dotnet
|
17102ff3bb457207d31c59dd5bae6f470fd909f8
|
[
"MIT"
] | 1,010
|
2016-04-13T15:30:28.000Z
|
2022-03-31T15:16:05.000Z
|
src/client/Microsoft.Identity.Client/Instance/Discovery/IUserMetadataProvider.cs
|
MiggieNRG/microsoft-authentication-library-for-dotnet
|
17102ff3bb457207d31c59dd5bae6f470fd909f8
|
[
"MIT"
] | 2,316
|
2016-04-02T01:14:31.000Z
|
2022-03-31T18:59:22.000Z
|
src/client/Microsoft.Identity.Client/Instance/Discovery/IUserMetadataProvider.cs
|
MiggieNRG/microsoft-authentication-library-for-dotnet
|
17102ff3bb457207d31c59dd5bae6f470fd909f8
|
[
"MIT"
] | 279
|
2016-04-28T23:08:01.000Z
|
2022-03-23T09:03:38.000Z
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.Identity.Client.Core;
namespace Microsoft.Identity.Client.Instance.Discovery
{
internal interface IUserMetadataProvider
{
InstanceDiscoveryMetadataEntry GetMetadataOrThrow(string environment, ICoreLogger logger);
}
}
| 27.076923
| 98
| 0.778409
|
2c737130a6b4a3b19d530105baa65e078c00faa1
| 7,675
|
cc
|
C++
|
components/viz/common/gl_nv12_converter.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
components/viz/common/gl_nv12_converter.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86
|
2015-10-21T13:02:42.000Z
|
2022-03-14T07:50:50.000Z
|
components/viz/common/gl_nv12_converter.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
// Copyright 2021 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.
#include "components/viz/common/gl_nv12_converter.h"
#include "base/memory/ptr_util.h"
#include "components/viz/common/gl_i420_converter.h"
#include "components/viz/common/gpu/context_provider.h"
namespace viz {
// static
std::unique_ptr<GLNV12Converter> GLNV12Converter::CreateConverterForTest(
ContextProvider* context_provider,
bool allow_mrt_path) {
return base::WrapUnique(
new GLNV12Converter(context_provider, allow_mrt_path));
}
GLNV12Converter::GLNV12Converter(ContextProvider* context_provider)
: GLNV12Converter(context_provider, true) {}
GLNV12Converter::GLNV12Converter(ContextProvider* context_provider,
bool allow_mrt_path)
: context_provider_(context_provider),
step1_(context_provider_),
step2_(context_provider_) {
DCHECK(context_provider_);
context_provider_->AddObserver(this);
if (!allow_mrt_path || step1_.GetMaxDrawBuffersSupported() < 2) {
step3_ = std::make_unique<GLScaler>(context_provider_);
}
}
GLNV12Converter::~GLNV12Converter() {
OnContextLost(); // Free context-related resources.
}
// static
gfx::Rect GLNV12Converter::ToAlignedRect(const gfx::Rect& rect) {
// Origin coordinates: FLOOR(...)
const int aligned_x =
((rect.x() < 0) ? ((rect.x() - 3) / 4) : (rect.x() / 4)) * 4;
const int aligned_y =
((rect.y() < 0) ? ((rect.y() - 1) / 2) : (rect.y() / 2)) * 2;
// Span coordinates: CEIL(...)
const int aligned_right =
((rect.right() < 0) ? (rect.right() / 4) : ((rect.right() + 3) / 4)) * 4;
const int aligned_bottom =
((rect.bottom() < 0) ? (rect.bottom() / 2) : ((rect.bottom() + 1) / 2)) *
2;
return gfx::Rect(aligned_x, aligned_y, aligned_right - aligned_x,
aligned_bottom - aligned_y);
}
// static
bool GLNV12Converter::ParametersAreEquivalent(const Parameters& a,
const Parameters& b) {
// Implemented in terms of GLI420Converter:
return GLI420Converter::ParametersAreEquivalent(a, b);
}
void GLNV12Converter::EnsureIntermediateTextureDefined(
const gfx::Size& required) {
if (intermediate_texture_size_ == required) {
return;
}
auto* const gl = context_provider_->ContextGL();
if (intermediate_texture_ == 0) {
gl->GenTextures(1, &intermediate_texture_);
}
gl->BindTexture(GL_TEXTURE_2D, intermediate_texture_);
gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, required.width(), required.height(),
0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
intermediate_texture_size_ = required;
}
bool GLNV12Converter::Configure(const Parameters& params) {
Parameters step1_params = params;
if (!step1_params.output_color_space.IsValid()) {
step1_params.output_color_space = gfx::ColorSpace::CreateREC709();
}
// Configure the "step 1" scaler.
if (is_using_mrt_path()) {
step1_params.export_format = Parameters::ExportFormat::NV61;
DCHECK_EQ(step1_params.swizzle[0], params.swizzle[0]);
step1_params.swizzle[1] = GL_RGBA; // Don't swizzle 2nd rendering target.
} else {
step1_params.export_format = Parameters::ExportFormat::INTERLEAVED_QUADS;
step1_params.swizzle[0] = GL_RGBA; // Will swizzle in steps 2-3.
}
if (!step1_.Configure(step1_params)) {
return false;
}
// Configure the "step 2" scaler (and step 3 for the non-MRT path) that
// further transform the output from the "step 1" scaler to produce the final
// outputs.
Parameters step2_params;
step2_params.scale_to = gfx::Vector2d(1, 1);
step2_params.source_color_space = step1_params.output_color_space;
step2_params.output_color_space = step1_params.output_color_space;
// Use FAST quality, a single bilinear pass, because there will either be no
// scaling or exactly 50% scaling.
step2_params.quality = Parameters::Quality::FAST;
step2_params.swizzle[0] = params.swizzle[0];
if (is_using_mrt_path()) {
// NV61 provides half-width and full-height U/V. NV12 UV planes are
// half-width and half-height. So, scale just the Y by 50%.
step2_params.scale_from = gfx::Vector2d(1, 2);
step2_params.export_format = Parameters::ExportFormat::INTERLEAVED_QUADS;
step2_params.swizzle[1] = step2_params.swizzle[0];
if (!step2_.Configure(step2_params)) {
return false;
}
} else {
// Extract a full-size Y plane from the interleaved YUVA from step 1.
step2_params.scale_from = gfx::Vector2d(1, 1);
step2_params.export_format = Parameters::ExportFormat::CHANNEL_0;
if (!step2_.Configure(step2_params)) {
return false;
}
// Extract a half-size UV plane from the interleaved YUVA from step 1.
// UV_CHANNELS provides half-width and full-height UV plane. NV12 UV planes
// are half-wifth and half-height. So, scale just the Y by 50%.
step2_params.scale_from = gfx::Vector2d(1, 2);
step2_params.export_format = Parameters::ExportFormat::UV_CHANNELS;
if (!step3_->Configure(step2_params)) {
return false;
}
}
params_ = params;
return true;
}
bool GLNV12Converter::Convert(GLuint src_texture,
const gfx::Size& src_texture_size,
const gfx::Vector2d& src_offset,
const gfx::Rect& aligned_output_rect,
const GLuint yuv_textures[2]) {
DCHECK_EQ(aligned_output_rect.x() % 4, 0);
DCHECK_EQ(aligned_output_rect.width() % 4, 0);
DCHECK_EQ(aligned_output_rect.y() % 2, 0);
DCHECK_EQ(aligned_output_rect.height() % 2, 0);
if (!context_provider_) {
return false;
}
if (is_using_mrt_path()) {
const gfx::Rect luma_output_rect(
aligned_output_rect.x() / 4, aligned_output_rect.y(),
aligned_output_rect.width() / 4, aligned_output_rect.height());
EnsureIntermediateTextureDefined(luma_output_rect.size());
const gfx::Rect chroma_output_rect(
gfx::Size(luma_output_rect.width(), luma_output_rect.height() / 2));
return (step1_.ScaleToMultipleOutputs(
src_texture, src_texture_size, src_offset, yuv_textures[0],
intermediate_texture_, luma_output_rect) &&
step2_.Scale(intermediate_texture_, intermediate_texture_size_,
gfx::Vector2d(), yuv_textures[1], chroma_output_rect));
}
// Non-MRT path:
EnsureIntermediateTextureDefined(aligned_output_rect.size());
const gfx::Rect luma_output_rect(0, 0, aligned_output_rect.width() / 4,
aligned_output_rect.height());
const gfx::Rect chroma_output_rect(0, 0, luma_output_rect.width(),
luma_output_rect.height() / 2);
return (step1_.Scale(src_texture, src_texture_size, src_offset,
intermediate_texture_, aligned_output_rect) &&
step2_.Scale(intermediate_texture_, intermediate_texture_size_,
gfx::Vector2d(), yuv_textures[0], luma_output_rect) &&
step3_->Scale(intermediate_texture_, intermediate_texture_size_,
gfx::Vector2d(), yuv_textures[1], chroma_output_rect));
}
void GLNV12Converter::OnContextLost() {
if (intermediate_texture_ != 0) {
if (auto* gl = context_provider_->ContextGL()) {
gl->DeleteTextures(1, &intermediate_texture_);
}
intermediate_texture_ = 0;
intermediate_texture_size_ = gfx::Size();
}
if (context_provider_) {
context_provider_->RemoveObserver(this);
context_provider_ = nullptr;
}
}
} // namespace viz
| 39.158163
| 80
| 0.679088
|
8bfbb4ea360a5ca65689e0cc517a19601b4816bf
| 101
|
rb
|
Ruby
|
Examples And Tutorials/Language Tutorials/Ruby Basics/Derek Banas One Video Ruby/other-loop.rb
|
RitamDey/My-Simple-Programs
|
147b455a6a40c371ec894ce979e8a61d242e03bd
|
[
"Unlicense"
] | 2
|
2016-10-14T16:58:05.000Z
|
2017-05-04T04:59:18.000Z
|
Examples And Tutorials/Language Tutorials/Ruby Basics/Derek Banas One Video Ruby/other-loop.rb
|
GreenJoey/My-Simple-Programs
|
147b455a6a40c371ec894ce979e8a61d242e03bd
|
[
"Unlicense"
] | null | null | null |
Examples And Tutorials/Language Tutorials/Ruby Basics/Derek Banas One Video Ruby/other-loop.rb
|
GreenJoey/My-Simple-Programs
|
147b455a6a40c371ec894ce979e8a61d242e03bd
|
[
"Unlicense"
] | null | null | null |
x = 1
loop do
x += 1
next unless x%2 == 0
break unless x<=10
$stdout.puts x
end
| 7.769231
| 24
| 0.50495
|
723c5f900892f7622284276afdfecdea977fa8ee
| 921
|
swift
|
Swift
|
SGUVIndex/Services/URLSessionWrapper.swift
|
Henryforce/SGUVIndex
|
0e53ba00464f33a2638cecb7983dccf63cff55ae
|
[
"MIT"
] | null | null | null |
SGUVIndex/Services/URLSessionWrapper.swift
|
Henryforce/SGUVIndex
|
0e53ba00464f33a2638cecb7983dccf63cff55ae
|
[
"MIT"
] | null | null | null |
SGUVIndex/Services/URLSessionWrapper.swift
|
Henryforce/SGUVIndex
|
0e53ba00464f33a2638cecb7983dccf63cff55ae
|
[
"MIT"
] | null | null | null |
//
// URLSessionWrapper.swift
// SGUVIndex
//
// Created by Henry Javier Serrano Echeverria on 2/1/21.
//
import Foundation
protocol URLSessionWrapper {
func dataTask(
with url: URL,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
) -> URLSessionDataTask
}
final class StandardURLSessionWrapper: URLSessionWrapper {
private let urlSession: URLSession
init(
urlSession: URLSession
) {
self.urlSession = urlSession
}
convenience init() {
let urlSession = URLSession(configuration: .default)
self.init(urlSession: urlSession)
}
func dataTask(
with url: URL,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
) -> URLSessionDataTask {
urlSession.dataTask(
with: url,
completionHandler: completionHandler
)
}
}
| 21.418605
| 74
| 0.616721
|
a404c3299e9d7922ae9f012dcae039ac002414b2
| 359
|
sh
|
Shell
|
spark_cluster/04_1_machine_only/ML1_workflow_on_NYT_5rounds_3x3_sim1_and_sim2_to_sim3/run.sh
|
poltextlab/nyt_hybrid_classification_workflow
|
3f676938b08f4373be3a83e975ee51dfa5ce6bf5
|
[
"MIT"
] | null | null | null |
spark_cluster/04_1_machine_only/ML1_workflow_on_NYT_5rounds_3x3_sim1_and_sim2_to_sim3/run.sh
|
poltextlab/nyt_hybrid_classification_workflow
|
3f676938b08f4373be3a83e975ee51dfa5ce6bf5
|
[
"MIT"
] | null | null | null |
spark_cluster/04_1_machine_only/ML1_workflow_on_NYT_5rounds_3x3_sim1_and_sim2_to_sim3/run.sh
|
poltextlab/nyt_hybrid_classification_workflow
|
3f676938b08f4373be3a83e975ee51dfa5ce6bf5
|
[
"MIT"
] | null | null | null |
#!/bin/bash
python ./ML1_wf_on_NYT_5rounds_3x3_sim1_and_sim2_to_sim3_round1.py &&
python ./ML1_wf_on_NYT_5rounds_3x3_sim1_and_sim2_to_sim3_round2.py &&
python ./ML1_wf_on_NYT_5rounds_3x3_sim1_and_sim2_to_sim3_round3.py &&
python ./ML1_wf_on_NYT_5rounds_3x3_sim1_and_sim2_to_sim3_round4.py &&
python ./ML1_wf_on_NYT_5rounds_3x3_sim1_and_sim2_to_sim3_round5.py
| 51.285714
| 69
| 0.883008
|
11a55786769f3387a761b252fe105fe4c02b7c9d
| 1,429
|
go
|
Go
|
dsync/test_sessions.go
|
qri-io/dag
|
e8a2affbb114087990f686b5b12de391d7dbcc4a
|
[
"MIT"
] | 20
|
2018-12-05T20:39:57.000Z
|
2022-02-11T00:46:12.000Z
|
dsync/test_sessions.go
|
qri-io/dag
|
e8a2affbb114087990f686b5b12de391d7dbcc4a
|
[
"MIT"
] | 18
|
2018-12-05T20:39:17.000Z
|
2020-07-07T03:46:49.000Z
|
dsync/test_sessions.go
|
qri-io/dag
|
e8a2affbb114087990f686b5b12de391d7dbcc4a
|
[
"MIT"
] | 2
|
2020-02-05T16:25:09.000Z
|
2020-12-22T14:00:14.000Z
|
package dsync
import (
"context"
"io"
"time"
cid "github.com/ipfs/go-cid"
ipld "github.com/ipfs/go-ipld-format"
coreiface "github.com/ipfs/interface-go-ipfs-core"
"github.com/ipfs/interface-go-ipfs-core/options"
"github.com/ipfs/interface-go-ipfs-core/path"
)
// NewTestDsync returns a Dsync pointer suitable for testing
func NewTestDsync() *Dsync {
return &Dsync{
lng: newTestNodeGetter(),
bapi: newTestBlockAPI(),
sessionPool: make(map[string]*session),
sessionCancels: make(map[string]context.CancelFunc),
sessionTTLDur: time.Hour * 5,
}
}
type testNodeGetter struct{}
func newTestNodeGetter() ipld.NodeGetter {
return &testNodeGetter{}
}
func (t *testNodeGetter) Get(context.Context, cid.Cid) (ipld.Node, error) {
return nil, nil
}
func (t *testNodeGetter) GetMany(context.Context, []cid.Cid) <-chan *ipld.NodeOption {
return nil
}
type testBlockAPI struct{}
func newTestBlockAPI() coreiface.BlockAPI {
return &testBlockAPI{}
}
func (t *testBlockAPI) Put(context.Context, io.Reader, ...options.BlockPutOption) (coreiface.BlockStat, error) {
return nil, nil
}
func (t *testBlockAPI) Get(context.Context, path.Path) (io.Reader, error) {
return nil, nil
}
func (t *testBlockAPI) Rm(context.Context, path.Path, ...options.BlockRmOption) error {
return nil
}
func (t *testBlockAPI) Stat(context.Context, path.Path) (coreiface.BlockStat, error) {
return nil, nil
}
| 23.42623
| 112
| 0.719384
|
c48bbdb2ce3091134a336575d0b5786ec4223478
| 496
|
lua
|
Lua
|
assets/preload/data/ringmaster/modchart.lua
|
CQTheKid/Erratic-master
|
ec910c55a9b140c77da07e1d08f2b760fed4289c
|
[
"MIT"
] | null | null | null |
assets/preload/data/ringmaster/modchart.lua
|
CQTheKid/Erratic-master
|
ec910c55a9b140c77da07e1d08f2b760fed4289c
|
[
"MIT"
] | null | null | null |
assets/preload/data/ringmaster/modchart.lua
|
CQTheKid/Erratic-master
|
ec910c55a9b140c77da07e1d08f2b760fed4289c
|
[
"MIT"
] | null | null | null |
function start(song)
end
function update(elapsed)
if curStep > 320 and curStep < 1712 then
local currentBeat = (songPos / 1000)*(bpm/60)
for i=0,7 do
setActorX(_G['defaultStrum'..i..'X'] + 7 * math.sin((currentBeat + i*0.25) * math.pi), i)
setActorY(_G['defaultStrum'..i..'Y'] + 14 * math.cos((currentBeat + i*0.25) * math.pi), i)
end
end
end
function beatHit(beat)
end
function stepHit(step)
end
function playerTwoTurn()
end
function playerOneTurn()
end
| 17.103448
| 93
| 0.65121
|
4924b76681197ba96ae620af754fa1401c7e2ebd
| 8,300
|
py
|
Python
|
src/modules/contribute.py
|
doraemu/mytelegram_bot_v13.8
|
5d89a73f564f0c31b8e061cae492f5144915baf2
|
[
"MIT"
] | null | null | null |
src/modules/contribute.py
|
doraemu/mytelegram_bot_v13.8
|
5d89a73f564f0c31b8e061cae492f5144915baf2
|
[
"MIT"
] | null | null | null |
src/modules/contribute.py
|
doraemu/mytelegram_bot_v13.8
|
5d89a73f564f0c31b8e061cae492f5144915baf2
|
[
"MIT"
] | null | null | null |
import telegram
import database as db
import lockmanage as lock
from telegram import InputMediaVideo, InputMediaPhoto
MAIN_CONFIG = db.read("config")
CONFIG = db.read("sub_config")
DB = db.read("sub_data")
MEDIAS = {} # 暂存组图片或视频数据
post_type = {"real":"保留", "anonymous":"匿名" }
def contribute_close(bot, query):
reply = query.message.reply_to_message
root = DB[str(CONFIG['Group_ID']) + ':' + str(reply.message_id)]
root['Closed'] = True
root['Editor_ID'] = query.from_user.name
msg = "审核未通过\n投稿人:{0}\n来源:{1}\n审核人:{2}".format(root['Sender_Name'], post_type[root['Type']], query.from_user.name)
query.edit_message_text(text=msg)
bot.send_message(chat_id=root['Sender_ID'], text="您的稿件未通过审核", reply_to_message_id=root['Original_MsgID'])
db.save("sub_data", DB, True)
if reply.media_group_id: MEDIAS.pop(reply.media_group_id)
def contribute_post(bot, query, ptype, cid):
reply = query.message.reply_to_message
if reply.media_group_id:
if not reply.media_group_id in MEDIAS.keys(): return
bot.send_media_group(chat_id=cid, media=MEDIAS[reply.media_group_id])
MEDIAS.pop(reply.media_group_id)
else:
if ptype == "real":
bot.forward_message(chat_id=cid, from_chat_id=CONFIG['Group_ID'], message_id=reply.message_id)
else:
if reply.audio:
bot.send_audio(chat_id=cid, audio=reply.audio, caption=reply.caption)
elif reply.document:
bot.send_document(chat_id=cid, document=reply.document, caption=reply.caption)
elif reply.voice:
bot.send_voice(chat_id=cid, voice=reply.voice, caption=reply.caption)
elif reply.video:
bot.send_video(chat_id=cid, video=reply.video, caption=reply.caption)
elif reply.photo:
bot.send_photo(chat_id=cid, photo=reply.photo[0], caption=reply.caption)
else:
reply.send_message(chat_id=cid, text=reply.text_markdown, parse_mode=telegram.ParseMode.MARKDOWN)
root = DB[str(CONFIG['Group_ID']) + ':' + str(reply.message_id)]
root['Posted'] = True
root['Channel_ID'] = cid
root['Editor_ID'] = query.from_user.name
msg = "已采纳\n投稿人:{0}\n来源:{1}\n审核人:{2}".format(root['Sender_Name'], post_type[root['Type']], query.from_user.name)
query.edit_message_text(text=msg)
bot.send_message(chat_id=root['Sender_ID'], text="您的稿件已过审,感谢您对我们的支持", reply_to_message_id=root['Original_MsgID'])
db.save("sub_data", DB, True)
def process_command(update, context):
if update.message.from_user.id != MAIN_CONFIG['Admin']: return
command = update.message.text[1:]
args = command.split(" ")
if args[0] == 'setsubgroup':
CONFIG['Group_ID'] = update.message.chat_id
db.save("sub_config", CONFIG)
update.message.reply_text(text="已设置本群为审稿群")
return
elif args[0] == 'setsubchannel' and len(args) == 3:
CONFIG['Publish_Channel'][args[1]] = args[2]
db.save("sub_config", CONFIG)
update.message.reply_text(text=args[2] + "已设置为发布频道")
return
def process_msg(update, context):
if not update.message.video and not update.message.photo: return # 只接收图片和视频投稿
if lock.user_check(update.message.from_user.id): return # 检查用户锁避免和批量转发冲突
if update.message.media_group_id: # 用于一组图片和视频转发
if update.message.media_group_id not in MEDIAS.keys(): MEDIAS[update.message.media_group_id] = []
if update.message.video: MEDIAS[update.message.media_group_id].append(InputMediaVideo(update.message.video, caption=update.message.caption))
if update.message.photo: MEDIAS[update.message.media_group_id].append(InputMediaPhoto(media=update.message.photo[len(update.message.photo) - 1], caption=update.message.caption))
if len(MEDIAS[update.message.media_group_id]) > 1: return
if update.message.from_user.id == update.message.chat_id:
if update.message.forward_from or update.message.forward_from_chat:
if update.message.forward_from_chat or update.message.forward_from.id:
markup = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton("是", callback_data='contribute:anonymous')],
[telegram.InlineKeyboardButton("取消投稿", callback_data='contribute:cancel')]])
update.message.reply_text(text="即将完成投稿...\n转发的消息将不保留消息来源,是否继续投稿?)", reply_markup=markup, reply_to_message_id=update.message.message_id)
else:
markup = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton("是" , callback_data='contribute:real'),
telegram.InlineKeyboardButton("否", callback_data='contribute:anonymous')],
[telegram.InlineKeyboardButton("取消投稿", callback_data='contribute:cancel')]])
update.message.reply_text(text="即将完成投稿...\n您是否想要保留消息来源(保留消息发送者用户名)", reply_markup=markup, reply_to_message_id=update.message.message_id)
def process_callback(update, context):
query = update.callback_query
cmds = query.data.split(":")
if cmds[0] != 'contribute': return
if cmds[1] == 'receive' and query.message.chat_id == CONFIG['Group_ID']:
contribute_post(context.bot, query, cmds[2], cmds[3])
return
elif cmds[1] == 'close' and query.message.chat_id == CONFIG['Group_ID']:
contribute_close(context.bot, query)
return
elif cmds[1] == 'cancel':
query.edit_message_text(text="已取消投稿")
return
elif cmds[1] == 'real' or cmds[1] == 'anonymous':
query.edit_message_text(text="感谢您的投稿,稍后会通知您结果")
if query.message.reply_to_message.media_group_id:
if not query.message.reply_to_message.media_group_id in MEDIAS.keys(): return
fwd_group_msg = context.bot.send_media_group(chat_id=CONFIG['Group_ID'], media=MEDIAS[query.message.reply_to_message.media_group_id])
if not fwd_group_msg: return
MEDIAS.pop(query.message.reply_to_message.media_group_id)
fwd_msg = fwd_group_msg[0]
for group_msg in fwd_group_msg:
if group_msg.media_group_id not in MEDIAS.keys(): MEDIAS[group_msg.media_group_id] = []
caption = None
if cmds[1] == 'real' and not MEDIAS[group_msg.media_group_id]:
caption = group_msg.caption + " Forwarded from " + query.message.reply_to_message.from_user.name if group_msg.caption else "Forwarded from " + query.message.reply_to_message.from_user.name
if group_msg.video: MEDIAS[group_msg.media_group_id].append(InputMediaVideo(group_msg.video, caption=caption))
if group_msg.photo: MEDIAS[group_msg.media_group_id].append(InputMediaPhoto(group_msg.photo[0], caption=caption))
else: fwd_msg = context.bot.forward_message(chat_id=CONFIG['Group_ID'], from_chat_id=query.message.chat_id, message_id=query.message.reply_to_message.message_id)
root = DB[str(CONFIG['Group_ID']) + ':' + str(fwd_msg.message_id)] = {}
root['Posted'] = False
root['Sender_Name'] = query.message.reply_to_message.from_user.name
root['Sender_ID'] = query.message.reply_to_message.from_user.id
root['Original_MsgID'] = query.message.reply_to_message.message_id
root['Media_Group_ID'] = query.message.reply_to_message.media_group_id
root['Channel_ID'] = ""
root['Type'] = cmds[1]
msg = "新投稿\n投稿人:{0}\n来源:{1}".format(query.message.reply_to_message.from_user.name, post_type[cmds[1]])
buttons = []
for key in CONFIG['Publish_Channel'].keys():
buttons.append(telegram.InlineKeyboardButton("采纳[" + CONFIG['Publish_Channel'][key] + "]", callback_data="contribute:receive:{0}:{1}".format(cmds[1], key)))
markup = telegram.InlineKeyboardMarkup([buttons, [telegram.InlineKeyboardButton("审核不通过", callback_data='contribute:close')]])
try:
context.bot.send_message(chat_id=CONFIG['Group_ID'], text=msg, reply_to_message_id=fwd_msg.message_id, reply_markup=markup)
finally:
db.save("sub_data", DB, True)
| 55.333333
| 208
| 0.667108
|
20d3b3676e48d8dfe575f20a0b570602de7351a6
| 3,559
|
cs
|
C#
|
BolaoNet.Application/Base/GenericApp.cs
|
Thoris/BolaoNet
|
f4bf12762912ed202ccc77df5abc1bde0ab7fcac
|
[
"MIT"
] | null | null | null |
BolaoNet.Application/Base/GenericApp.cs
|
Thoris/BolaoNet
|
f4bf12762912ed202ccc77df5abc1bde0ab7fcac
|
[
"MIT"
] | 105
|
2017-07-24T10:53:05.000Z
|
2021-12-20T10:17:18.000Z
|
BolaoNet.Application/Base/GenericApp.cs
|
Thoris/BolaoNet
|
f4bf12762912ed202ccc77df5abc1bde0ab7fcac
|
[
"MIT"
] | null | null | null |
using BolaoNet.Application.Interfaces.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BolaoNet.Application.Base
{
/// <summary>
/// Classe que trabalha com funcionalidades genéricas para gerenciamento das entidades de integração.
/// </summary>
public abstract class GenericApp<T> : IGenericApp<T> where T : class
{
#region Variables
protected Domain.Interfaces.Services.Base.IGenericService<T> _service;
#endregion
#region Constructors/Destructors
public GenericApp(Domain.Interfaces.Services.Base.IGenericService<T> service)
{
_service = service;
}
#endregion
#region IGenericApp members
/// <summary>
/// Método que carrega um registro a partir de dados básicos da entidade.
/// </summary>
/// <param name="entity">Entidade que será utilizada para carregar os dados.</param>
/// <returns>Item encontrado, ou null caso não encontre.</returns>
public T Load(T entity)
{
return _service.Load(entity);
}
/// <summary>
/// Método que insere um registro na base de dados.
/// </summary>
/// <param name="entity">Entidade com os dados a serem inseridos.</param>
/// <returns>Identificador do registro, ou quantidade de registro afetados.</returns>
public long Insert(T entity)
{
return _service.Insert(entity);
}
/// <summary>
/// Método que exclui um registro da base de dados.
/// </summary>
/// <param name="entity">Entidade a ser pesquisada para ser excluída.</param>
/// <returns>True se conseguiu excluir o registro.</returns>
public bool Delete(T id)
{
return _service.Delete(id);
}
/// <summary>
/// Método que atualiza um registro na base de dados.
/// </summary>
/// <param name="oldEntity">Registro atual que deve ser pesquisado na base de dados.</param>
/// <param name="entity">Dados do registro a ser atualizado na base de dados.</param>
/// <returns>True se conseguiu atualizar o registro.</returns>
public bool Update(T entity)
{
return _service.Update(entity);
}
/// <summary>
/// Método que retorna a lista de registros de entidades a partir de uma condição.
/// </summary>
/// <param name="where">Condição a ser usada na pesquisa.</param>
/// <returns>Lista de entidades encontradas.</returns>
public ICollection<T> GetList(Expression<Func<T, bool>> where)
{
return _service.GetList(where);
}
/// <summary>
/// Método que retorna lista de registros de uma entidade em específico.
/// </summary>
/// <returns>Lista de registros encontrados.</returns>
public ICollection<T> GetAll()
{
return _service.GetAll();
}
/// <summary>
/// Método que retorna a quantidade de registros da entidade.
/// </summary>
/// <returns>Quantidade de registros encontrados.</returns>
public long Count()
{
return _service.Count();
}
public long Count(Expression<Func<T, bool>> where)
{
return _service.Count(where);
}
#endregion
}
}
| 34.221154
| 105
| 0.597078
|
93d4244b70c6364c51002b00829c3c02dd436fb0
| 5,345
|
cs
|
C#
|
Assets/Scripts/Playmode/Tales Of Ascaria/Aspect/OnInput/MovePlayerOnInput.cs
|
LuckyLph/Tales-Of-Ascaria
|
bcbc37a6ebe9571f802713567d2ad02f44f42619
|
[
"MIT"
] | null | null | null |
Assets/Scripts/Playmode/Tales Of Ascaria/Aspect/OnInput/MovePlayerOnInput.cs
|
LuckyLph/Tales-Of-Ascaria
|
bcbc37a6ebe9571f802713567d2ad02f44f42619
|
[
"MIT"
] | null | null | null |
Assets/Scripts/Playmode/Tales Of Ascaria/Aspect/OnInput/MovePlayerOnInput.cs
|
LuckyLph/Tales-Of-Ascaria
|
bcbc37a6ebe9571f802713567d2ad02f44f42619
|
[
"MIT"
] | null | null | null |
using UnityEngine;
using Harmony;
using System.Collections;
namespace TalesOfAscaria
{
public class MovePlayerOnInput : GameScript
{
private PlayersList playersList;
private PlayerMovementEventPublisher playerMovementEventPublisher;
private PlayerMovementValidator playerMovementValidator;
private PlayerTranslateMover playerTranslateMover;
private TranslateAnimator translateAnimator;
private PlayerController playerController;
private PlayerInput playerInput;
private LivingEntity livingEntity;
private Coroutine teleportCoroutine;
private bool hasMoved;
private bool timerIsStarted;
private bool timerMustStart;
private bool timerMustStop;
private void InjectMovePlayerOnInput([ApplicationScope] PlayersList playersList,
[EntityScope] PlayerMovementEventPublisher playerMovementEventPublisher,
[EntityScope] PlayerMovementValidator playerMovementValidator,
[EntityScope] PlayerTranslateMover playerTranslateMover,
[EntityScope] TranslateAnimator translateAnimator,
[GameObjectScope] PlayerController playerController,
[GameObjectScope] PlayerInput playerInput,
[GameObjectScope] LivingEntity livingEntity)
{
this.playersList = playersList;
this.playerMovementEventPublisher = playerMovementEventPublisher;
this.playerMovementValidator = playerMovementValidator;
this.playerTranslateMover = playerTranslateMover;
this.translateAnimator = translateAnimator;
this.playerController = playerController;
this.playerInput = playerInput;
this.livingEntity = livingEntity;
}
private void Awake()
{
InjectDependencies("InjectMovePlayerOnInput");
}
private void OnEnable()
{
playerInput.OnMove += OnMove;
}
private void Update()
{
if (!timerIsStarted)
{
timerMustStart = playerMovementValidator.IsPlayerOutsideCamera(gameObject.transform.position, playerController.PlayerSize);
}
else if (!playerMovementValidator.IsPlayerOutsideCamera(gameObject.transform.position, playerController.PlayerSize))
{
timerMustStop = true;
}
if (timerMustStart && !timerIsStarted)
{
timerIsStarted = true;
timerMustStart = false;
timerMustStop = false;
teleportCoroutine = StartCoroutine(TeleportAfterDelay());
}
else if (timerMustStop && timerIsStarted)
{
StopCoroutine(teleportCoroutine);
timerMustStop = false;
timerIsStarted = false;
}
}
private void LateUpdate()
{
if (!hasMoved)
{
translateAnimator.SetAnimationState(R.S.AnimatorParameter.IsWalking, false);
}
hasMoved = false;
}
private void OnDisable()
{
playerInput.OnMove -= OnMove;
}
private void OnMove(Vector2 movementVector)
{
if (livingEntity.GetCrowdControl().StunCounter <= 0)
{
playerController.Direction = movementVector;
if (livingEntity.GetCrowdControl().SnareCounter <= 0)
{
hasMoved = true;
float speed = livingEntity.GetStats().Agility;
bool canMoveUp = playerMovementValidator.ValidateUpMovement(transform.position, movementVector,
playerController.PlayerSize.y, speed);
bool canMoveDown = playerMovementValidator.ValidateDownMovement(transform.position, movementVector,
playerController.PlayerSize.y, speed);
bool canMoveRight = playerMovementValidator.ValidateRightMovement(transform.position, movementVector,
playerController.PlayerSize.x, speed);
bool canMoveLeft = playerMovementValidator.ValidateLeftMovement(transform.position, movementVector,
playerController.PlayerSize.x, speed);
if (playerTranslateMover.Move(movementVector, speed, canMoveUp, canMoveDown, canMoveRight, canMoveLeft))
{
playerMovementEventPublisher.Publish(gameObject, movementVector);
}
translateAnimator.SetAnimationState(R.S.AnimatorParameter.IsWalking, true);
translateAnimator.Animate(movementVector);
}
else
{
translateAnimator.SetAnimationState(R.S.AnimatorParameter.IsWalking, false);
translateAnimator.Animate(movementVector);
}
}
}
private IEnumerator TeleportAfterDelay()
{
yield return new WaitForSeconds(2);
GameObject[] players = playersList.PlayersAlive.ToArray();
for (int i = 0; i < players.Length; i++)
{
if (!playerMovementValidator.IsPlayerOutsideCamera(players[i].transform.position,
playersList.SpriteRenderers[i].bounds.size))
{
transform.parent.position = players[i].transform.position;
break;
}
}
}
}
}
| 37.907801
| 131
| 0.634238
|
4545b03ada14dece977958db3accf844b1793965
| 478
|
py
|
Python
|
LeetCode/Python/remove_duplicates_from_sorted_array.py
|
tejeshreddy/competitive-programming
|
e98d3800c7f1dcca285286cac1ac056b11201e12
|
[
"MIT"
] | null | null | null |
LeetCode/Python/remove_duplicates_from_sorted_array.py
|
tejeshreddy/competitive-programming
|
e98d3800c7f1dcca285286cac1ac056b11201e12
|
[
"MIT"
] | null | null | null |
LeetCode/Python/remove_duplicates_from_sorted_array.py
|
tejeshreddy/competitive-programming
|
e98d3800c7f1dcca285286cac1ac056b11201e12
|
[
"MIT"
] | null | null | null |
"""
Title: 0026 - Remove Duplicates from Sorted Array
Tags: Array
Time: O(n)
Space: O(1)
Source: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Difficulty: Easy
"""
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
last = 0
for i in range(len(nums)):
if nums[i] != nums[last]:
last += 1
nums[last] = nums[i]
return last + 1
| 22.761905
| 74
| 0.564854
|
10b948eca24975de055b87683e04b0005b8e9980
| 475
|
sh
|
Shell
|
HCP_fMRI_files/gen_fMRI_main.sh
|
govindasurampudi/HCP_SC_TS_FC
|
ef9e5887afb1a8b8088de1838d83db0e1ca71fae
|
[
"MIT"
] | null | null | null |
HCP_fMRI_files/gen_fMRI_main.sh
|
govindasurampudi/HCP_SC_TS_FC
|
ef9e5887afb1a8b8088de1838d83db0e1ca71fae
|
[
"MIT"
] | null | null | null |
HCP_fMRI_files/gen_fMRI_main.sh
|
govindasurampudi/HCP_SC_TS_FC
|
ef9e5887afb1a8b8088de1838d83db0e1ca71fae
|
[
"MIT"
] | null | null | null |
# get subject id
subj_id="$1"
parc="$2"
fMRI="$3"
# collect files from aws server
bash ~/<working_dir>/script_data_fMRI.sh "$subjid"
# go to the folder
cd /scratch/`whoami`/"$subj_id"/
# generate ROIs' BOLD timeseries
bash ~/<working_dir>/gen_fMRI_command.sh "$fMRI" "$parc"
# copy files to HCP data folder in home directory
cp /scratch/`whoami`/"$subj_id"/TS_"$fMRI"/meants_"$fMRI".txt ~/<data_storage>/"$fMRI"/"$subjid"_"parc".ts
# come back!
cd ~/<working_dir>/
wait
| 22.619048
| 106
| 0.698947
|
b7aba78817d1568600cf99f740f797e1be2d84e6
| 1,017
|
dart
|
Dart
|
example/customize.dart
|
cxp108/flutter_memory_cache
|
ddc278cfa4bf447c492a167e7755317767d57824
|
[
"BSD-3-Clause"
] | 3
|
2020-03-03T01:49:09.000Z
|
2021-12-10T08:33:53.000Z
|
example/customize.dart
|
cxp108/flutter_memory_cache
|
ddc278cfa4bf447c492a167e7755317767d57824
|
[
"BSD-3-Clause"
] | null | null | null |
example/customize.dart
|
cxp108/flutter_memory_cache
|
ddc278cfa4bf447c492a167e7755317767d57824
|
[
"BSD-3-Clause"
] | null | null | null |
import 'dart:io';
import 'package:flutter_memory_cache/flutter_memory_cache.dart';
main() {
// when cache object number over capacity*0.8 more then 5 times(continuously) of evict check.
// 基于容量的检查策略,当缓存数量超过水位线(容量*evictLevel)连续5次,则启动清理
CapacitySensitivePolicy capacitySensitivePolicy = CapacitySensitivePolicy(
evictLevel: 0.8, tolerance: 5);
// when cache is overflow, Eviction will start immediately,cache will be droped.
// default ttl set to 5 seconds
// 当缓存数量大于容量(capacity)时,立刻启动清理,默认ttl设置为5秒
MemoryCache memoryCache = MemoryCache(
capacity: 3000, ttl: 5, policy: capacitySensitivePolicy);
var cache1 = {'name': 'cache1'};
var cache2 = {'name': 'cache2'};
// Default ttl is 5 seconds
memoryCache.put('cache1', cache1);
memoryCache.putWithTTL('cache2', cache2,30);
sleep(Duration(seconds: 6));
var ret = memoryCache.get('cache1');
print('cache1 is $ret');
assert(ret == null);
ret = memoryCache.get('cache2');
print('cache2 is $ret');
assert(ret != null);
}
| 32.806452
| 96
| 0.710914
|
c6ea453692c124238039b3386ea0bb2e05c716b8
| 20,791
|
lua
|
Lua
|
module_modmail.lua
|
Elanis/NotaBot
|
0405044aec4aa920baa644c717372d510a6a095f
|
[
"MIT"
] | 1
|
2021-12-01T14:47:42.000Z
|
2021-12-01T14:47:42.000Z
|
module_modmail.lua
|
Equinox4/NotaBot
|
60ff8d7b29742e074bdb05d38f999be84f22f17a
|
[
"MIT"
] | null | null | null |
module_modmail.lua
|
Equinox4/NotaBot
|
60ff8d7b29742e074bdb05d38f999be84f22f17a
|
[
"MIT"
] | null | null | null |
-- Copyright (C) 2020 Jérôme Leclercq
-- This file is part of the "Not a Bot" application
-- For conditions of distribution and use, see copyright notice in LICENSE
local bot = Bot
local client = Client
local discordia = Discordia
local enums = discordia.enums
discordia.extensions() -- load all helpful extensions
local json = require("json")
Module.Name = "modmail"
function Module:GetConfigTable()
return {
{
Name = "Category",
Description = "Where should modmail channels be created",
Type = bot.ConfigType.Category,
Default = ""
},
{
Name = "ArchiveCategory",
Description = "Category where modmail channels are moved to when closed",
Type = bot.ConfigType.Category,
Optional = true
},
{
Name = "LogChannel",
Description = "Where should modmail logs should be stored",
Type = bot.ConfigType.Channel,
Optional = true
},
{
Array = true,
Name = "TicketHandlingRoles",
Description = "Roles allowed to close tickets (and force open them for members)",
Type = bot.ConfigType.Role,
Default = {}
},
{
Array = true,
Name = "ForbiddenRoles",
Description = "Roles that aren't allowed to open a ticket",
Type = bot.ConfigType.Role,
Default = {}
},
{
Array = true,
Name = "AllowedRoles",
Description = "Roles allowed to open tickets for them (if empty, everyone)",
Type = bot.ConfigType.Role,
Default = {}
},
{
Name = "MaxConcurrentChannels",
Description = "How many concurrents (active) channels can be created",
Type = bot.ConfigType.Integer,
Default = 10
},
{
Name = "DeleteDuration",
Description = "How many time does a ticket channel take to be deleted after being closed",
Type = bot.ConfigType.Duration,
Default = 24 * 60 * 60
},
{
Name = "SaveTicketContent",
Description = "Should the bot save every message in a modmail ticket when closing them? (up to 2000 messages)",
Type = bot.ConfigType.Boolean,
Default = true
},
{
Name = "MemberCloseOwnTickets",
Description = "Should the bot allow members to close tickets them opened themselves?",
Type = bot.ConfigType.Boolean,
Default = true
}
}
end
function Module:OnLoaded()
self.Timer = Bot:CreateRepeatTimer(1, -1, function ()
local now = os.time()
self:ForEachGuild(function (guildId, config, data, persistentData)
local guild = client:getGuild(guildId)
if (guild) then
local config = self:GetConfig(guild)
local deleteDuration = config.DeleteDuration
local data = self:GetPersistentData(guild)
local archiveData = data.archivedChannels[1]
if (archiveData and now >= archiveData.closedAt + deleteDuration) then
table.remove(data.archivedChannels, 1)
local channel = guild:getChannel(archiveData.channelId)
if (channel) then
channel:delete()
end
end
end
end)
end)
self:RegisterCommand({
Name = "newticket",
Args = {
{Name = "member", Type = Bot.ConfigType.Member, Optional = true},
{Name = "message", Type = Bot.ConfigType.String, Optional = true},
},
Help = "Allows you to contact the server staff in private",
Silent = true,
Func = function (commandMessage, targetMember, reason)
local fromMember = commandMessage.member
local authorized, err = self:CheckOpenTicketPermission(fromMember, targetMember)
if not authorized then
return commandMessage:reply(err)
end
local success, err = self:OpenTicket(fromMember, targetMember or fromMember, reason, true)
if (not success) then
return commandMessage:reply(err)
end
end
})
self:RegisterCommand({
Name = "modticket",
Args = {
{Name = "member", Type = Bot.ConfigType.Member},
{Name = "message", Type = Bot.ConfigType.String, Optional = true},
},
PrivilegeCheck = function (member)
local guild = member.guild
local config = self:GetConfig(guild)
return util.MemberHasAnyRole(member, config.TicketHandlingRoles)
end,
Help = "Opens a moderation ticket for someone (same as newticket but doesn't allow the target user to talk)",
Silent = true,
Func = function (commandMessage, targetMember, reason)
local success, err = self:OpenTicket(commandMessage.member, targetMember, reason, false)
if (not success) then
return commandMessage:reply(err)
end
end
})
self:RegisterCommand({
Name = "closeticket",
Args = {
{Name = "reason", Type = Bot.ConfigType.String, Optional = true},
},
Help = "When used in a ticket channel, close it",
Silent = true,
Func = function (commandMessage, reason)
local ret = self:HandleTicketClose(commandMessage.member, commandMessage, reason, false)
if (ret == nil) then
commandMessage:reply(bot:Format(commandMessage.guild, "MODMAIL_NOTACTIVETICKET", commandMessage.member.user.mentionString))
elseif (ret == false) then
commandMessage:reply(bot:Format(commandMessage.guild, "MODMAIL_NOTAUTHORIZED", commandMessage.member.user.mentionString))
end
end
})
self:RegisterCommand({
Name = "createticketform",
Args = {
{Name = "channel", Type = Bot.ConfigType.Channel},
},
PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end,
Help = "Creates a button in the specified channel to open the ticket form",
Silent = true,
Func = function (commandMessage, channel)
channel:send({
components = {
{
type = enums.componentType.actionRow,
components = {
{
type = enums.componentType.button,
style = enums.buttonStyle.primary,
custom_id = "modmail_openticketform",
label = bot:Format(commandMessage.guild, "MODMAIL_OPENTICKET_BUTTON_LABEL")
}
}
}
}
})
end
})
return true
end
function Module:OnUnload()
self.Timer:Stop()
end
function Module:OnEnable(guild)
local config = self:GetConfig(guild)
local modmailCategory = guild:getChannel(config.Category)
if (not modmailCategory or modmailCategory.type ~= enums.channelType.category) then
return false, "Invalid modmail category (check your configuration)"
end
local data = self:GetPersistentData(guild)
data.activeChannels = data.activeChannels or {}
data.archivedChannels = data.archivedChannels or {}
return true
end
function Module:HandleEmojiAdd(userId, message, reactionName)
if (userId == client.user.id) then
-- Ignore bot own reaction
return
end
if (reactionName ~= "👋") then
return
end
local guild = message.guild
local member = guild:getMember(userId)
if (not member) then
return
end
self:HandleTicketClose(member, message, nil, true)
end
function Module:HandleTicketClose(member, message, reason, reactionClose)
local guild = message.guild
local config = self:GetConfig(guild)
local data = self:GetPersistentData(guild)
for userId, channelData in pairs(data.activeChannels) do
local channelTest = false
if (reactionClose) then
channelTest = (channelData.topMessageId == message.id)
else
channelTest = (channelData.channelId == message.channel.id)
end
if (channelTest) then
local archiveData = channelData
local authorized = false
if config.MemberCloseOwnTickets then
if channelData.openedByMember == member.id then
authorized = true
end
end
if not authorized and not util.MemberHasAnyRole(member, config.TicketHandlingRoles) then
return false
end
local ticketChannel = guild:getChannel(channelData.channelId)
if channelData.topMessageComponents then
local topMessage = ticketChannel:getMessage(channelData.topMessageId)
if topMessage then
-- Disable "close ticket" button
channelData.topMessageComponents[1].components[1].disabled = true
topMessage:setComponents(channelData.topMessageComponents)
end
end
local closeMessage = bot:Format(guild, "MODMAIL_TICKETCLOSE_MESSAGE", member.user.mentionString, util.DiscordRelativeTime(config.DeleteDuration))
if (reason and #reason > 0) then
local author = member.user
ticketChannel:send({
content = closeMessage,
embed = {
author = {
name = author.tag,
icon_url = author.avatarURL
},
description = reason,
timestamp = discordia.Date():toISO('T', 'Z')
}
})
else
ticketChannel:send(closeMessage)
end
ticketChannel:setName(ticketChannel.name .. "✅")
data.activeChannels[userId] = nil
if (config.ArchiveCategory and config.ArchiveCategory ~= ticketChannel.id) then
local archiveCategory = guild:getChannel(config.ArchiveCategory)
if (archiveCategory and archiveCategory.type == enums.channelType.category) then
ticketChannel:setCategory(config.ArchiveCategory)
end
end
local ticketMember = guild:getMember(userId)
if (ticketMember) then
local permissions = ticketChannel:getPermissionOverwriteFor(ticketMember)
if (not permissions or not permissions:setPermissions(enums.permission.viewChannel, enums.permission.sendMessages)) then
ticketChannel:sendf("Failed to deny send messages permission to %s.", ticketMember.mentionString)
end
end
if (config.LogChannel) then
local channel = guild:getChannel(config.LogChannel)
if (channel) then
local author
if (ticketMember) then
author = {
name = ticketMember.tag,
icon_url = ticketMember.avatarURL
}
end
local fields
if (reason and #reason > 0) then
fields = {
{
name = "Close message",
value = reason
}
}
end
local file
if config.SaveTicketContent then
local messages, err = Bot:FetchChannelMessages(ticketChannel, nil, 2000)
if not messages then
table.insert(fields, {
{
name = "⚠️ Failed to save ticket content",
value = string.format("error: %s", err)
}
})
end
local jsonSave = json.encode(bot:MessagesToTable(messages), { indent = 1})
file = {
"messages.json",
jsonSave
}
fields = fields or {}
table.insert(fields, {
name = "🗒️ ticket content has been saved",
value = "Check attachment file"
})
end
local success, err = channel:send({
embed = {
author = author,
color = 16711680,
description = member.mentionString .. " has closed ticket " .. ticketChannel.mentionString,
fields = fields,
footer = {
text = "UserID: " .. userId .. " | TicketID: " .. ticketChannel.id
},
timestamp = discordia.Date():toISO('T', 'Z')
},
file = file
})
if not success then
self:LogError(guild, "Failed to post closing ticket message (%s)", err)
end
end
end
-- Insert into archived channels once deletion is possible
table.insert(data.archivedChannels, {
channelId = ticketChannel.id,
closedAt = os.time()
})
return true
end
end
end
function Module:CheckOpenTicketPermission(fromMember, targetMember)
local guild = fromMember.guild
local config = self:GetConfig(guild)
if util.MemberHasAnyRole(fromMember, config.ForbiddenRoles) then
return false, bot:Format(guild, "MODMAIL_OPENTICKET_FORBIDDEN")
end
if targetMember and targetMember ~= fromMember then
local authorized = util.MemberHasAnyRole(fromMember, config.TicketHandlingRoles)
if not authorized then
return false, bot:Format(guild, "MODMAIL_OPENTICKET_NOTALLOWED_OTHERMEMBER")
end
else
local allowedRoles = config.AllowedRoles
if #allowedRoles > 0 then
local authorized = util.MemberHasAnyRole(fromMember, allowedRoles)
if not authorized then
return false, bot:Format(guild, "MODMAIL_OPENTICKET_NOTALLOWED")
end
end
end
return true
end
function Module:OpenTicket(fromMember, targetMember, reason, twoWays)
local guild = fromMember.guild
local config = self:GetConfig(guild)
local data = self:GetPersistentData(guild)
if (data.activeChannels[targetMember.user.id]) then
if (targetMember == fromMember) then
return false, string.format("you already have an active ticket on this server, %s.", targetMember.user.mentionString)
else
return false, string.format("%s already has an active ticket on this server.", targetMember.user.tag, targetMember.user.mentionString)
end
return
end
if (config.MaxConcurrentChannels > 0 and table.count(data.activeChannels) >= config.MaxConcurrentChannels) then
return false, string.format("sorry %s, but there are actually too many tickets open at the same time, please retry in a moment", fromMember.user.mentionString)
end
local modmailCategory = guild:getChannel(config.Category)
if (not modmailCategory or modmailCategory.type ~= enums.channelType.category) then
return false, "this server is not well configured, please tell the admins!"
end
local filteredUsername = targetMember.user.username:gsub("[^%w]", ""):sub(1, 8)
if (#filteredUsername == 0) then
filteredUsername = "empty"
end
local ticketChannel, err = modmailCategory:createTextChannel(string.format("%s-%s", filteredUsername, targetMember.user.discriminator))
if (not ticketChannel) then
print(err)
return false, "failed to create the channel, this is likely a bug."
end
local permissionOverwrite, err = ticketChannel:getPermissionOverwriteFor(targetMember)
if (not permissionOverwrite) then
print(err)
return false, "failed to create the channel, this is likely a bug."
end
local allowedPermissions = enums.permission.viewChannel
local deniedPermissions = 0
if (twoWays) then
allowedPermissions = bit.bor(allowedPermissions, enums.permission.sendMessages)
else
deniedPermissions = bit.bor(deniedPermissions, enums.permission.sendMessages)
end
if (not permissionOverwrite:setPermissions(allowedPermissions, deniedPermissions)) then
return false, "failed to create the channel, this is likely a bug."
end
if (config.LogChannel) then
local channel = guild:getChannel(config.LogChannel)
if (channel) then
local color, desc
if (fromMember == targetMember) then
color = 61695
desc = targetMember.mentionString .. " has opened a new ticket (" .. ticketChannel.mentionString .. ")"
elseif (twoWays) then
color = 65280
desc = fromMember.mentionString .. " has opened a new ticket for " .. targetMember.mentionString .. " (" .. ticketChannel.mentionString .. ")"
else
color = 16776960
desc = fromMember.mentionString .. " has opened a moderator ticket for " .. targetMember.mentionString .. " (" .. ticketChannel.mentionString .. ")"
end
local fields
if (reason and #reason > 0) then
fields = {
{
name = "Ticket message",
value = reason
}
}
end
local success, err = channel:send({
embed = {
author = {
name = targetMember.tag,
icon_url = targetMember.avatarURL
},
color = color,
description = desc,
fields = fields,
footer = {
text = "UserID: " .. targetMember.user.id .. " | TicketID: " .. ticketChannel.id
},
timestamp = discordia.Date():toISO('T', 'Z')
}
})
if not success then
self:LogError(guild, "Failed to post opening ticket message (%s)", err)
end
end
end
local activeChannelData = {
createdAt = os.time(),
channelId = ticketChannel.id,
targetMember = targetMember.id,
openedByMember = fromMember.id
}
data.activeChannels[targetMember.user.id] = activeChannelData
local message
if (targetMember == fromMember) then
message = bot:Format(guild, "MODMAIL_TICKETOPENING_MESSAGE", targetMember.user.mentionString, guild.name)
else
message = bot:Format(guild, "MODMAIL_TICKETOPENING_MESSAGE_MODERATION", targetMember.user.mentionString, guild.name)
end
local components = {
{
type = enums.componentType.actionRow,
components = {
{
type = enums.componentType.button,
style = enums.buttonStyle.primary,
custom_id = "modmail_closeticket",
label = bot:Format(guild, "MODMAIL_CLOSETICKET"),
emoji = {
name = "👋"
}
}
}
}
}
local messageData = {
content = message,
components = components
}
local message = ticketChannel:send(messageData)
message:pin()
activeChannelData.topMessageComponents = components
activeChannelData.topMessageId = message.id
if (reason and #reason > 0) then
local author = fromMember.user
local message, err = ticketChannel:send({
content = bot:Format(guild, "MODMAIL_TICKETMESSAGE"),
embed = {
author = {
name = author.tag,
icon_url = author.avatarURL
},
description = reason,
timestamp = discordia.Date():toISO()
}
})
if not message then
self:LogError(guild, "Failed to post reason message (%s)", err)
end
end
return ticketChannel
end
function Module:OnReactionAdd(reaction, userId)
local message = reaction.message
if (not bot:IsPublicChannel(message.channel)) then
return
end
self:HandleEmojiAdd(userId, message, reaction.emojiName)
end
function Module:OnReactionAddUncached(channel, messageId, reactionIdOrName, userId)
if (not bot:IsPublicChannel(channel)) then
return
end
local message = channel:getMessage(messageId)
if (not message) then
return
end
self:HandleEmojiAdd(userId, message, reactionIdOrName)
end
function Module:OnChannelDelete(channel)
if (not bot:IsPublicChannel(channel)) then
return
end
local guild = channel.guild
local data = self:GetPersistentData(guild)
for userId, channelData in pairs(data.activeChannels) do
if (channelData.channelId == channel.id) then
data.activeChannels[userId] = nil
break
end
end
end
function Module:OnMemberLeave(member)
local data = self:GetPersistentData(member.guild)
local channelData = data.activeChannels[member.user.id]
if channelData then
local ticketChannel = member.guild:getChannel(channelData.channelId)
if ticketChannel then
ticketChannel:send(bot:Format(member.guild, "MODMAIL_LEFTSERVER", member.mentionString))
end
end
end
function Module:OnInteractionCreate(interaction)
local guild = interaction.guild
if not guild then
return
end
local config = self:GetConfig(guild)
local interactionType = interaction.data.custom_id
if interactionType == "modmail_closeticket" then
-- "Waiting"
interaction:respond({
type = enums.interactionResponseType.deferredChannelMessageWithSource,
data = {
flags = enums.interactionResponseFlag.ephemeral
}
})
local ret = self:HandleTicketClose(interaction.member, interaction.message, nil, true)
if (ret == nil) then
interaction:editResponse({
content = bot:Format(guild, "MODMAIL_NOTACTIVETICKET", interaction.member.mentionString),
})
elseif (ret == false) then
interaction:editResponse({
content = bot:Format(guild, "MODMAIL_NOTAUTHORIZED", interaction.member.mentionString),
})
else
interaction:editResponse({
content = bot:Format(guild, "MODMAIL_TICKETCLOSED_CONFIRMATION", interaction.member.mentionString)
})
end
elseif interactionType == "modmail_openticketform" then
local authorized, err = self:CheckOpenTicketPermission(interaction.member)
if not authorized then
return interaction:respond({
type = enums.interactionResponseType.channelMessageWithSource,
data = {
content = "❌ " .. tostring(err),
flags = enums.interactionResponseFlag.ephemeral
}
})
end
interaction:respond({
type = enums.interactionResponseType.modal,
data = {
title = bot:Format(guild, "MODMAIL_FORM_TITLE"),
custom_id = "modmail_ticketform",
components = {
{
type = enums.componentType.actionRow,
components = {
{
type = enums.componentType.textInput,
style = enums.textInputStyle.paragraph,
custom_id = "form_desc",
label = bot:Format(guild, "MODMAIL_FORM_DESCRIPTION_LABEL")
}
}
}
}
}
})
elseif interactionType == "modmail_ticketform" then
local fromMember = interaction.member
local authorized, err = self:CheckOpenTicketPermission(fromMember)
if not authorized then
return interaction:respond({
type = enums.interactionResponseType.channelMessageWithSource,
data = {
content = "❌ " .. tostring(err),
flags = enums.interactionResponseFlag.ephemeral
}
})
end
local reason = interaction.data.components[1].components[1].value
-- "Waiting"
interaction:respond({
type = enums.interactionResponseType.deferredChannelMessageWithSource,
data = {
flags = enums.interactionResponseFlag.ephemeral
}
})
local ticketChannel, err = self:OpenTicket(fromMember, fromMember, reason, true)
if not ticketChannel then
return interaction:editResponse({
content = "❌ " .. tostring(err)
})
end
return interaction:editResponse({
content = bot:Format(guild, "MODMAIL_TICKEDOPENED", ticketChannel.mentionString)
})
end
end
| 28.210312
| 161
| 0.704343
|
d03b4fa828cf3f58853c1f36b32e379562622a20
| 755
|
cpp
|
C++
|
C_C++_Projects/BAPS Contest/charlie/drunkenbinary.cpp
|
sunjerry019/RandomCodes
|
4402604aaeee63bb1ce6fa962c496b438bb17e50
|
[
"MIT"
] | null | null | null |
C_C++_Projects/BAPS Contest/charlie/drunkenbinary.cpp
|
sunjerry019/RandomCodes
|
4402604aaeee63bb1ce6fa962c496b438bb17e50
|
[
"MIT"
] | null | null | null |
C_C++_Projects/BAPS Contest/charlie/drunkenbinary.cpp
|
sunjerry019/RandomCodes
|
4402604aaeee63bb1ce6fa962c496b438bb17e50
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
long long arr[1000000];
int r(int x){
long long ans;
if(x==0)
ans=1;
else if(x<1000000&&arr[x]!=-1)
return arr[x];
else if(x%2==1)
ans=r(x/2);
else ans=r(x/2)+r(x/2-1);
if(x<1000000)
arr[x]=ans;
return ans;
}
int main(){
int n,tc;
scanf("%d %d",&n,&tc);
int i,j;
for(int i=0;i<1000000;i++){
arr[i]=-1;
}
// printf("%d",r(4));
for(int i=0;i<1000000;i++){
r(i);
}
for (int ii=0;ii<tc;ii++){
scanf("%d %d",&i,&j);
if(i==j)
printf("%d\n",0);
else if(i==0)
printf("%d\n",(int)floor(sqrt(r(j))));
else if(r(j)-r(i)>0)
printf("%d\n",(int)floor(sqrt(r(j)-r(i))));
else
printf("%d\n",(int)-floor(sqrt(r(i)-r(j))));
}
}
| 18.414634
| 47
| 0.490066
|
483320ddfd54191734246510f3a93c71472cd47d
| 36
|
sql
|
SQL
|
hasura/migrations/1610193617417_drop_table_public_ChatReaction/up.sql
|
LasseWolter/clowdr
|
4777fc8386a7cd4f09b7a366ccd01662608c3e01
|
[
"BSD-3-Clause"
] | 49
|
2021-01-09T07:09:08.000Z
|
2022-03-27T05:16:46.000Z
|
hasura/migrations/1610193617417_drop_table_public_ChatReaction/up.sql
|
LasseWolter/clowdr
|
4777fc8386a7cd4f09b7a366ccd01662608c3e01
|
[
"BSD-3-Clause"
] | 333
|
2021-01-17T14:52:22.000Z
|
2022-03-10T02:38:53.000Z
|
hasura/migrations/1610193617417_drop_table_public_ChatReaction/up.sql
|
LasseWolter/clowdr
|
4777fc8386a7cd4f09b7a366ccd01662608c3e01
|
[
"BSD-3-Clause"
] | 15
|
2021-01-29T14:17:38.000Z
|
2022-02-14T22:13:48.000Z
|
DROP TABLE "public"."ChatReaction";
| 18
| 35
| 0.75
|
7afdd9402e660dac690b5746a53c686c9b827217
| 992
|
cs
|
C#
|
Framework/Dragon.Framework.Data.Dapper/DapperOptions.cs
|
T-Manson/Dragon
|
c9e72ff4e7f68244d9df63f470272f4f277915f5
|
[
"MIT"
] | 19
|
2018-05-21T10:48:11.000Z
|
2021-02-25T01:42:57.000Z
|
Framework/Dragon.Framework.Data.Dapper/DapperOptions.cs
|
T-Manson/Dragon
|
c9e72ff4e7f68244d9df63f470272f4f277915f5
|
[
"MIT"
] | 1
|
2019-03-06T15:00:30.000Z
|
2019-04-04T13:26:30.000Z
|
Framework/Dragon.Framework.Data.Dapper/DapperOptions.cs
|
T-Manson/Dragon
|
c9e72ff4e7f68244d9df63f470272f4f277915f5
|
[
"MIT"
] | 11
|
2018-06-26T02:11:13.000Z
|
2021-02-25T01:42:59.000Z
|
using Dapper;
using Dragon.Framework.Data.Dapper.Common.Enums;
namespace Dragon.Framework.Data.Dapper
{
/// <summary>
/// Dapper配置类
/// </summary>
public class DapperOptions
{
/// <summary>
/// 大小写规则
/// </summary>
public CapitalizationRule CapitalizationRule { get; set; } = CapitalizationRule.LowerCase;
/// <summary>
/// DB标识符映射策略
/// </summary>
private DbIdentifierMappingStrategy _dbIdentifierMappingStrategy = DbIdentifierMappingStrategy.Underline;
/// <summary>
/// 表名映射策略
/// </summary>
public virtual DbIdentifierMappingStrategy DbIdentifierMappingStrategy
{
get => _dbIdentifierMappingStrategy;
set
{
_dbIdentifierMappingStrategy = value;
DefaultTypeMap.MatchNamesWithUnderscores = _dbIdentifierMappingStrategy != DbIdentifierMappingStrategy.PascalCase;
}
}
}
}
| 28.342857
| 130
| 0.610887
|
0aec1223714769b1b0f688130f00131e7311c73a
| 617
|
cs
|
C#
|
src/Jeebs.Auth.Data.Clients.PostgreSql/Migrations/0001_AddAuthSchema.cs
|
bfren/jeebs
|
f096f4cc15094ac0b36ec02086ad98727f5a1a63
|
[
"MIT"
] | 1
|
2022-01-30T08:54:32.000Z
|
2022-01-30T08:54:32.000Z
|
src/Jeebs.Auth.Data.Clients.PostgreSql/Migrations/0001_AddAuthSchema.cs
|
bfren/jeebs
|
f096f4cc15094ac0b36ec02086ad98727f5a1a63
|
[
"MIT"
] | 134
|
2021-07-16T14:31:27.000Z
|
2022-03-31T15:03:25.000Z
|
src/Jeebs.Auth.Data.Clients.PostgreSql/Migrations/0001_AddAuthSchema.cs
|
bfren/jeebs
|
f096f4cc15094ac0b36ec02086ad98727f5a1a63
|
[
"MIT"
] | null | null | null |
// Jeebs Rapid Application Development
// Copyright (c) bfren - licensed under https://mit.bfren.dev/2013
using SimpleMigrations;
namespace Jeebs.Auth.Data.Clients.PostgreSql.Migrations;
/// <summary>
/// Migration: Add auth schema
/// </summary>
[Migration(1, "Add auth schema")]
public sealed class AddAuthSchema : Migration
{
/// <summary>
/// Migrate up
/// </summary>
protected override void Up()
{
Execute(@"
CREATE SCHEMA IF NOT EXISTS ""Auth""
;
");
}
/// <summary>
/// Migrate down
/// </summary>
protected override void Down()
{
Execute(@"DROP SCHEMA IF EXISTS ""Auth"";");
}
}
| 18.69697
| 66
| 0.659643
|
c96cb4e2c04f18b6d620cab12f7faacc8cd440ed
| 576
|
ts
|
TypeScript
|
examples/ts-dev-gauge-googlecharts/src/util.ts
|
Caballero1218/spotfire-mods
|
44174deab6ea04bb52d689bf2f6a55aaa5ac8a65
|
[
"BSD-3-Clause"
] | 34
|
2020-09-23T13:32:48.000Z
|
2022-03-21T20:18:27.000Z
|
examples/ts-dev-gauge-googlecharts/src/util.ts
|
Caballero1218/spotfire-mods
|
44174deab6ea04bb52d689bf2f6a55aaa5ac8a65
|
[
"BSD-3-Clause"
] | 47
|
2020-11-04T15:36:15.000Z
|
2022-03-26T08:22:01.000Z
|
examples/ts-dev-gauge-googlecharts/src/util.ts
|
admariner/spotfire-mods
|
d3f313c48d2aec166f49119075e19755a44cc620
|
[
"BSD-3-Clause"
] | 20
|
2020-10-13T23:46:19.000Z
|
2022-03-08T08:17:59.000Z
|
/*
* Copyright © 2020. TIBCO Software Inc.
* This file is subject to the license terms contained
* in the license file that is distributed with this file.
*/
/**
* Helper function to retrieve a DOM element if it exists.
* @param selector - A css selector string
*/
export function findElem(selector: string): HTMLElement {
return document.querySelector(selector) as HTMLElement;
}
/**
* Finds the max value in a data list
* @param data -
*/
export function maxInList(data: [string, number][]) {
return data.reduce((p, c) => Math.max(c[1] ?? p, p), 0);
}
| 26.181818
| 60
| 0.682292
|
0aedeb8f2004e1a28d80bfafff965b32eb8c7716
| 335
|
cs
|
C#
|
BlazorMovies/Shared/DTOs/MovieUpdateDTO.cs
|
Marcus-V-Freitas/BlazorMovies
|
9566a4ad4633fc712895477d014da993a20be91e
|
[
"MIT"
] | null | null | null |
BlazorMovies/Shared/DTOs/MovieUpdateDTO.cs
|
Marcus-V-Freitas/BlazorMovies
|
9566a4ad4633fc712895477d014da993a20be91e
|
[
"MIT"
] | null | null | null |
BlazorMovies/Shared/DTOs/MovieUpdateDTO.cs
|
Marcus-V-Freitas/BlazorMovies
|
9566a4ad4633fc712895477d014da993a20be91e
|
[
"MIT"
] | null | null | null |
using System.Collections.Generic;
namespace BlazorMovies.Shared.DTOs
{
public class MovieUpdateDTO
{
public MovieDTO Movie { get; set; }
public List<PersonDTO> Actors { get; set; }
public List<GenreDTO> SelectedGenres { get; set; }
public List<GenreDTO> NotSelectedGenres { get; set; }
}
}
| 27.916667
| 61
| 0.656716
|
e845945a578a8a8c051bffcb5d60dab5dd546c31
| 1,273
|
cs
|
C#
|
src/Web/Extensions/CacheHelpers.cs
|
dianareis/eShopOnWeb
|
fc35609a37bb687435af52d9431d962369d65e7d
|
[
"MIT"
] | null | null | null |
src/Web/Extensions/CacheHelpers.cs
|
dianareis/eShopOnWeb
|
fc35609a37bb687435af52d9431d962369d65e7d
|
[
"MIT"
] | null | null | null |
src/Web/Extensions/CacheHelpers.cs
|
dianareis/eShopOnWeb
|
fc35609a37bb687435af52d9431d962369d65e7d
|
[
"MIT"
] | null | null | null |
using System;
using System.Globalization;
namespace Microsoft.eShopWeb.Web.Extensions
{
public static class CacheHelpers
{
public static readonly TimeSpan DefaultCacheDuration = TimeSpan.FromSeconds(30);
private static readonly string _itemsKeyTemplate = "items-{0}-{1}-{2}-{3}-{4}-{5}";
public static string GenerateCatalogItemCacheKey(int pageIndex, int itemsPage, string searchText, int? brandId, int? typeId, string cultureName)
{
if(pageIndex < 0) {
throw new InvalidPageIndexException();
}
string _searchText = string.IsNullOrEmpty(searchText)?"":searchText.Replace(" ", ""); // TODO: Handle invalid special chars in cache keys?
return string.Format(_itemsKeyTemplate, pageIndex, itemsPage, _searchText, brandId, typeId, cultureName);
}
public static string GenerateBrandsCacheKey()
{
return "brands";
}
public static string GenerateTypesCacheKey()
{
return "types";
}
public static string GenerateCatalogItemIdKey(int id)
{
return $"catalog_item_{id}";
}
}
public class InvalidPageIndexException : Exception
{
}
}
| 31.04878
| 152
| 0.627651
|
871429c483b1da5bd4b9d4ce949c6254f5fdcc2c
| 1,099
|
rb
|
Ruby
|
spec/features/shelters/user_can_update_each_shelter_spec.rb
|
StephanieFriend/paired_adopt_dont_shop_2001
|
c842556eddcb11b134dfc8ddaa807fefe971149a
|
[
"Ruby",
"MIT"
] | null | null | null |
spec/features/shelters/user_can_update_each_shelter_spec.rb
|
StephanieFriend/paired_adopt_dont_shop_2001
|
c842556eddcb11b134dfc8ddaa807fefe971149a
|
[
"Ruby",
"MIT"
] | 10
|
2020-03-25T21:34:44.000Z
|
2022-03-31T00:58:46.000Z
|
spec/features/shelters/user_can_update_each_shelter_spec.rb
|
StephanieFriend/paired_adopt_dont_shop_2001
|
c842556eddcb11b134dfc8ddaa807fefe971149a
|
[
"Ruby",
"MIT"
] | 1
|
2021-11-10T21:49:15.000Z
|
2021-11-10T21:49:15.000Z
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'shelter update process', type: :feature do
it "can take a user to '/shelters/:id/edit'" do
visit "/shelters/#{@shelter1.id}"
click_link 'Edit Shelter'
expect(current_path).to eq("/shelters/#{@shelter1.id}/edit")
end
it "can see a form to edit shelter's data" do
visit "/shelters/#{@shelter1.id}/edit"
expect(page).to have_selector('form')
expect(page).to have_field('name', with: @shelter1.name)
expect(page).to have_field('address', with: @shelter1.address)
expect(page).to have_field('city', with: @shelter1.city)
expect(page).to have_field('state', with: @shelter1.state)
expect(page).to have_field('zip', with: @shelter1.zip)
end
it 'can complete update with PATCH and redirect' do
visit "/shelters/#{@shelter1.id}/edit"
fill_in 'name', with: 'Testing Update'
click_button 'Submit'
expect(current_path).to eq("/shelters/#{@shelter1.id}")
expect(page).to have_content('Testing Update')
expect(page).to_not have_content('Pet Palace')
end
end
| 29.702703
| 66
| 0.686988
|
14ae2c78f4608d5a98ffcaf87165c9668bd24899
| 1,932
|
ts
|
TypeScript
|
server/src/migration/1562745775039-hipp-request-has-data-capture-types.ts
|
ausseabed/survey-request-and-planning-tool
|
f4d280bf5f8e1fa35caa5ea62a3b5276712acffa
|
[
"Apache-2.0"
] | 2
|
2021-06-06T21:11:33.000Z
|
2021-08-21T19:29:41.000Z
|
server/src/migration/1562745775039-hipp-request-has-data-capture-types.ts
|
ausseabed/survey-request-and-planning-tool
|
f4d280bf5f8e1fa35caa5ea62a3b5276712acffa
|
[
"Apache-2.0"
] | 5
|
2020-08-14T04:38:36.000Z
|
2022-02-27T21:28:14.000Z
|
server/src/migration/1562745775039-hipp-request-has-data-capture-types.ts
|
ausseabed/survey-request-and-planning-tool
|
f4d280bf5f8e1fa35caa5ea62a3b5276712acffa
|
[
"Apache-2.0"
] | 2
|
2019-12-03T05:48:30.000Z
|
2020-02-29T16:21:55.000Z
|
import {MigrationInterface, QueryRunner} from "typeorm";
export class hippRequestHasDataCaptureTypes1562745775039 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`CREATE TABLE "hipp_request_data_capture_types_data_capture_type" ("hippRequestId" uuid NOT NULL, "dataCaptureTypeId" uuid NOT NULL, CONSTRAINT "PK_0a3bfc82748e43444fe52ecb8c0" PRIMARY KEY ("hippRequestId", "dataCaptureTypeId"))`);
await queryRunner.query(`CREATE INDEX "IDX_91c097eba45c9f85b67cdb41bf" ON "hipp_request_data_capture_types_data_capture_type" ("hippRequestId") `);
await queryRunner.query(`CREATE INDEX "IDX_0456a9ef019a27835c8fd24751" ON "hipp_request_data_capture_types_data_capture_type" ("dataCaptureTypeId") `);
await queryRunner.query(`ALTER TABLE "hipp_request_data_capture_types_data_capture_type" ADD CONSTRAINT "FK_91c097eba45c9f85b67cdb41bfe" FOREIGN KEY ("hippRequestId") REFERENCES "hipp_request"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "hipp_request_data_capture_types_data_capture_type" ADD CONSTRAINT "FK_0456a9ef019a27835c8fd24751b" FOREIGN KEY ("dataCaptureTypeId") REFERENCES "data_capture_type"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
}
public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`ALTER TABLE "hipp_request_data_capture_types_data_capture_type" DROP CONSTRAINT "FK_0456a9ef019a27835c8fd24751b"`);
await queryRunner.query(`ALTER TABLE "hipp_request_data_capture_types_data_capture_type" DROP CONSTRAINT "FK_91c097eba45c9f85b67cdb41bfe"`);
await queryRunner.query(`DROP INDEX "IDX_0456a9ef019a27835c8fd24751"`);
await queryRunner.query(`DROP INDEX "IDX_91c097eba45c9f85b67cdb41bf"`);
await queryRunner.query(`DROP TABLE "hipp_request_data_capture_types_data_capture_type"`);
}
}
| 87.818182
| 263
| 0.800725
|
c6fe4e8e78dacacad39ae6497348314757f4b5ea
| 3,726
|
rb
|
Ruby
|
app/models/sms/handler.rb
|
nmckahd/AHDBurundi
|
7ae34ef1331f5301d2e9d71e661d24e32f799519
|
[
"Apache-2.0"
] | null | null | null |
app/models/sms/handler.rb
|
nmckahd/AHDBurundi
|
7ae34ef1331f5301d2e9d71e661d24e32f799519
|
[
"Apache-2.0"
] | null | null | null |
app/models/sms/handler.rb
|
nmckahd/AHDBurundi
|
7ae34ef1331f5301d2e9d71e661d24e32f799519
|
[
"Apache-2.0"
] | null | null | null |
# Takes an incoming Sms::Message and returns a translated and formatted reply.
# Handles errors.
# Defers to Sms::Decoder for intricacies of decoding.
class Sms::Handler
# takes an incoming sms and returns an outgoing one
# may return nil if no response is appropriate
def handle(sms)
elmo_response = nil
reply_body = begin
# decode and get the (ELMO) response
elmo_response = Sms::Decoder.new(sms).decode
# attempt to save it
elmo_response.save!
# send congrats!
t_sms_msg("sms_form.decoding.congrats", :user => elmo_response.user, :form => elmo_response.form, :mission => sms.mission)
# if there is a decoding error, respond accordingly
rescue Sms::DecodingError
# If it's an automated sender, send no reply at all
if $!.type == "automated_sender"
nil
else
msg = t_sms_msg("sms_form.decoding.#{$!.type}", $!.params)
# if this is an answer format error, add an intro to the beginning and add a period
if $!.type =~ /^answer_not_/
t_sms_msg("sms_form.decoding.answer_error_intro", $!.params) + " " + msg + "."
else
msg
end
end
# if there is a validation error, respond accordingly
rescue ActiveRecord::RecordInvalid
# we only need to handle the first error
field, error_msgs = elmo_response.errors.messages.first
error_msg = error_msgs.first
# get the orignal error key by inverting the dictionary
# we use the system-wide locale since that's what the model would have used when generating the error
dict = I18n.t("activerecord.errors.models.response")
key = dict ? dict.invert[error_msg] : nil
case key
when :missing_answers
# if it's the missing_answers error, we need to include which answers are missing
# get the ranks
ranks = elmo_response.missing_answers.map(&:rank).sort.join(",")
# pluralize the translation key if appropriate
key = "sms_form.validation.missing_answer"
key += "s" if elmo_response.missing_answers.size > 1
# translate
t_sms_msg(key, :ranks => ranks, :user => elmo_response.user, :form => elmo_response.form, :mission => sms.mission)
when :invalid_answers
# if it's the invalid_answers error, we need to find the first answer that's invalid and report its error
invalid_answer = elmo_response.answers.detect{|a| a.errors && a.errors.messages.size > 0}
t_sms_msg("sms_form.validation.invalid_answer", :rank => invalid_answer.questioning.rank,
:error => invalid_answer.errors.messages.values.join(", "),
:user => elmo_response.user, :form => elmo_response.form, :mission => sms.mission)
else
# if we don't recognize the key, just use the regular message. it may not be pretty but it's better than nothing.
error_msg
end
end
if reply_body.nil?
return nil
else
return Sms::Message.new(:to => sms.from, :body => reply_body, :mission => sms.mission, :direction => 'outgoing')
end
end
private
# translates a message for the sms reply using the appropriate locale
def t_sms_msg(key, options = {})
# throw in the form_code if it's not there already and we have the form
options[:form_code] ||= options[:form].current_version.code if options[:form]
# get the reply language (if we have the user, use their pref_lang; if not, use default)
lang = options[:user] && options[:user].pref_lang ? options[:user].pref_lang.to_sym : I18n.default_locale
# do the translation, raising error on failure
I18n.t(key, options.merge(:locale => lang, :raise => true))
end
end
| 39.221053
| 128
| 0.665325
|
cde047066540e3fb2929908687aa2537d52f45db
| 3,085
|
cs
|
C#
|
src/aspnet/StackExchange.Redis.Extensions.AspNetCore/Extensions/IServiceCollectionExtensions.cs
|
adamralph/StackExchange.Redis.Extensions
|
059c24ee04242e5e3a2fe7057a59955801541278
|
[
"MIT"
] | null | null | null |
src/aspnet/StackExchange.Redis.Extensions.AspNetCore/Extensions/IServiceCollectionExtensions.cs
|
adamralph/StackExchange.Redis.Extensions
|
059c24ee04242e5e3a2fe7057a59955801541278
|
[
"MIT"
] | null | null | null |
src/aspnet/StackExchange.Redis.Extensions.AspNetCore/Extensions/IServiceCollectionExtensions.cs
|
adamralph/StackExchange.Redis.Extensions
|
059c24ee04242e5e3a2fe7057a59955801541278
|
[
"MIT"
] | null | null | null |
// Copyright (c) Ugo Lattanzi. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using StackExchange.Redis.Extensions.Core;
using StackExchange.Redis.Extensions.Core.Abstractions;
using StackExchange.Redis.Extensions.Core.Configuration;
using StackExchange.Redis.Extensions.Core.Implementations;
namespace Microsoft.Extensions.DependencyInjection;
/// <summary>
/// A set of extension methods that help you to confire StackExchangeRedisExtensions into your dependency injection
/// </summary>
public static class IServiceCollectionExtensions
{
/// <summary>
/// Add StackExchange.Redis with its serialization provider.
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="redisConfiguration">The redis configration.</param>
/// <typeparam name="T">The typof of serializer. <see cref="ISerializer" />.</typeparam>
public static IServiceCollection AddStackExchangeRedisExtensions<T>(
this IServiceCollection services,
RedisConfiguration redisConfiguration)
where T : class, ISerializer
{
return services.AddStackExchangeRedisExtensions<T>(sp => new[] { redisConfiguration });
}
/// <summary>
/// Add StackExchange.Redis with its serialization provider.
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="redisConfiguration">The redis configration.</param>
/// <typeparam name="T">The typof of serializer. <see cref="ISerializer" />.</typeparam>
public static IServiceCollection AddStackExchangeRedisExtensions<T>(
this IServiceCollection services,
IEnumerable<RedisConfiguration> redisConfiguration)
where T : class, ISerializer
{
return services.AddStackExchangeRedisExtensions<T>(sp => redisConfiguration);
}
/// <summary>
/// Add StackExchange.Redis with its serialization provider.
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="redisConfigurationFactory">The redis configration factory.</param>
/// <typeparam name="T">The typof of serializer. <see cref="ISerializer" />.</typeparam>
public static IServiceCollection AddStackExchangeRedisExtensions<T>(
this IServiceCollection services,
Func<IServiceProvider, IEnumerable<RedisConfiguration>> redisConfigurationFactory)
where T : class, ISerializer
{
services.AddSingleton<IRedisClientFactory, RedisClientFactory>();
services.AddSingleton<ISerializer, T>();
services.AddSingleton((provider) => provider
.GetRequiredService<IRedisClientFactory>()
.GetDefaultRedisClient());
services.AddSingleton((provider) => provider
.GetRequiredService<IRedisClientFactory>()
.GetDefaultRedisClient()
.GetDefaultDatabase());
services.AddSingleton(redisConfigurationFactory);
return services;
}
}
| 41.689189
| 147
| 0.713452
|
9e14a27ed7f58b1433740d5a7826238186e0bd78
| 2,758
|
lua
|
Lua
|
Full Examples/set_marker.lua
|
NTUSPMS/BinooAPI
|
f371f2f3a424ca8a1ac3e9736e4b89bb7012d68b
|
[
"MIT"
] | null | null | null |
Full Examples/set_marker.lua
|
NTUSPMS/BinooAPI
|
f371f2f3a424ca8a1ac3e9736e4b89bb7012d68b
|
[
"MIT"
] | 1
|
2018-02-14T03:49:17.000Z
|
2018-02-14T03:51:50.000Z
|
Full Examples/set_marker.lua
|
NTUSPMS/BinooAPI
|
f371f2f3a424ca8a1ac3e9736e4b89bb7012d68b
|
[
"MIT"
] | 1
|
2019-10-07T02:26:28.000Z
|
2019-10-07T02:26:28.000Z
|
--[[
ff table holds marker to be found in the scene
--]]
b = BinooAPI
b:DebugMode(true)
ff = {}
-- c = 0 -> wrong marker
-- c = 1 -> correct marker
-- anim = true/false -> animated marker/fixed marker
-- anims = 0/1 -> increase first/decrease first, helper variable to control animation
ff[1] = { phi=0, theta = 0, c = 0, anim = true, anims = 0}
ff[2] = { phi=0, theta = 20, c = 1, anim = true, anims = 0}
ff[3] = { phi=0, theta = -20, c = 1, anim = true, anims = 0}
--radius where the objects are placed
r = 13 -- radius where markers are placed
rs = 1.1 -- size of the marker
tf = 0 -- total number of markers to be found; is calculated below
pi = math.pi
for k,v in ipairs(ff) do
b:CreateGameObject(tostring(k))
b:AddBoxCollider(tostring(k), 0, 0, 0, rs, rs, rs)
b:MoveObject(tostring(k),
r*math.cos(v.phi*pi/180),
r*math.sin(v.theta*pi/180),
r*math.sin(v.phi*pi/180))
b:AddGazeTarget(tostring(k))
b:AddEvent(tostring(k),"CLICK","myclick")
if v.c == 1 then
tf = tf + 1
end
end
b:SendCommand("MESSAGE|find " .. tostring(tf) .. " objects.")
function myclick(sender)
local objname = "s" .. sender
if b:FindObject(objname) then
b:Destroy(objname)
else
sn = tonumber(sender)
v=ff[sn]
b:CreateTorus(objname, 0, 45, rs, rs/4, 32, 16)
b:SetPosition(objname,
r*math.cos(v.phi*pi/180),
r*math.sin(v.theta*pi/180),
r*math.sin(v.phi*pi/180))
b:SetRotation(objname, 0, 0, 90)
b:SetColor(objname, 242, 239, 29) -- yellow
end
end
return function()
while true do
local f = true
local f_f = 0
-- check for objects and animate
for k,v in ipairs(ff) do
if b:FindObject("s" .. tostring(k)) then
-- check if object should be animated
--if ff[k].anim then
if (ff[k].anims == 1) then
b:TweenScale("s" .. tostring(k), 1.1, 1)
ff[k].anims = 0
else
b:TweenScale("s" .. tostring(k), 0.9, 1)
ff[k].anims = 1
end
--end
if (v.c == 0) then
-- wrong object found
f = false
elseif (v.c == 1) then
f_f = f_f +1
end
elseif (v.c == 1) then
-- object not yet marked
f = false
end
end
if (f == true) and (f_f == tf) then
b:SendCommand("MESSAGE|all objects found")
end
coroutine.yield(1)
end
end
| 28.43299
| 85
| 0.495286
|
e72604b1e40ac744a9082c3d9df2aa0b1fd6a5af
| 1,165
|
php
|
PHP
|
models/WeatherHistorySearchByDate.php
|
wartur/jsonrpc-server-microservice-example
|
740d3c293876084a483c7808fb1972a8398c3287
|
[
"BSD-3-Clause"
] | null | null | null |
models/WeatherHistorySearchByDate.php
|
wartur/jsonrpc-server-microservice-example
|
740d3c293876084a483c7808fb1972a8398c3287
|
[
"BSD-3-Clause"
] | null | null | null |
models/WeatherHistorySearchByDate.php
|
wartur/jsonrpc-server-microservice-example
|
740d3c293876084a483c7808fb1972a8398c3287
|
[
"BSD-3-Clause"
] | null | null | null |
<?php
/*
* Рабочие модели
*/
namespace app\models;
use app\models\activeModels\WeatherHistory;
/**
* Поиск погоды по дате
*/
class WeatherHistorySearchByDate extends \yii\base\Model
{
/**
* @var string дата на которую ищем
*/
public $date;
/**
* @var array Результат
*/
public $result;
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['date'], 'date', 'format' => 'php:Y-m-d'],
[['date'], 'required'],
];
}
/**
* Поиск
* @return array
*/
public function execute()
{
if (!$this->validate()) {
return false;
}
// ну, я тут не стал усложнять, можно было через модели и модели сериализировать,
// но это все крсивости и с виду по задаче не особо нужны,
// да и жрало бы это лишних ресурсов в данном случае
$query = WeatherHistory::find();
// grid filtering conditions
$query->andFilterWhere([
'weather_history.date_at' => $this->date,
]);
$this->result = $query->asArray()->one();
return true;
}
}
| 18.790323
| 89
| 0.522747
|
0a66a59a22ae5dffca6500c9deebd79368463d47
| 593
|
cs
|
C#
|
Programming Fundamentals/C#/09.Regular Expressions/Lab/P01_MatchFullName/P01_MatchFullName.cs
|
radrex/SoftuniCourses
|
06df2d09b0256af5ac37ddbeede5512cefb9af94
|
[
"MIT"
] | 7
|
2020-11-02T09:33:58.000Z
|
2021-12-22T01:31:00.000Z
|
Programming Fundamentals/C#/09.Regular Expressions/Lab/P01_MatchFullName/P01_MatchFullName.cs
|
radrex/SoftuniCourses
|
06df2d09b0256af5ac37ddbeede5512cefb9af94
|
[
"MIT"
] | null | null | null |
Programming Fundamentals/C#/09.Regular Expressions/Lab/P01_MatchFullName/P01_MatchFullName.cs
|
radrex/SoftuniCourses
|
06df2d09b0256af5ac37ddbeede5512cefb9af94
|
[
"MIT"
] | 13
|
2020-04-04T21:23:29.000Z
|
2021-12-19T12:59:10.000Z
|
namespace P01_MatchFullName
{
using System;
using System.Text.RegularExpressions;
class P01_MatchFullName
{
static void Main(string[] args)
{
string pattern = @"\b[A-Z][a-z]+ [A-Z][a-z]+\b";
string names = Console.ReadLine();
MatchCollection matches = Regex.Matches(names, pattern);
string validNames = string.Empty;
foreach (Match name in matches)
{
validNames += name.Value + " ";
}
Console.WriteLine(validNames.TrimEnd());
}
}
}
| 23.72
| 68
| 0.531197
|
e27c7c66c556444257b6a483f619a65f094b749a
| 394
|
js
|
JavaScript
|
src/_pages/LangueAddPage.js
|
natacha-steiver/react_backoffice
|
2588f7cb77aee150ff283e9ab7022531772f5191
|
[
"MIT"
] | null | null | null |
src/_pages/LangueAddPage.js
|
natacha-steiver/react_backoffice
|
2588f7cb77aee150ff283e9ab7022531772f5191
|
[
"MIT"
] | null | null | null |
src/_pages/LangueAddPage.js
|
natacha-steiver/react_backoffice
|
2588f7cb77aee150ff283e9ab7022531772f5191
|
[
"MIT"
] | null | null | null |
import React,{ useState,useEffect } from 'react';
import LangueAddForm from '../_components/Form/LangueAddForm';
import { useDispatch,useSelector } from 'react-redux';
import { history } from '../_helpers/history';
//import classes from './RegisterPage.module.scss';
const LangueAddPage = (props) => {
return (
<LangueAddForm />
);
}
export default LangueAddPage;
| 17.909091
| 62
| 0.682741
|
e3ef52c45730fe65eca432cfd6ebda2512c9affa
| 84
|
sh
|
Shell
|
scripts/mlst_salmonella_st.sh
|
jcgneto/salmonella_usa_database
|
8f9cd5c9a9682248c5b085e4af85589eaed269c2
|
[
"MIT"
] | 1
|
2019-09-27T19:43:23.000Z
|
2019-09-27T19:43:23.000Z
|
scripts/mlst_salmonella_st.sh
|
jcgneto/salmonella_usa_database
|
8f9cd5c9a9682248c5b085e4af85589eaed269c2
|
[
"MIT"
] | null | null | null |
scripts/mlst_salmonella_st.sh
|
jcgneto/salmonella_usa_database
|
8f9cd5c9a9682248c5b085e4af85589eaed269c2
|
[
"MIT"
] | null | null | null |
#!/bin/bash
mlst --legacy --scheme senterica *.fa --csv > salmonellast_output.csv
| 16.8
| 69
| 0.702381
|
e272dc0ea1e6fc2bba92b8ee5210cf2e54731ca6
| 3,709
|
js
|
JavaScript
|
script.js
|
va6un/openUR-chromium
|
374caf029dfc425e68e8e6c8a37e3f772fb52b4f
|
[
"MIT"
] | null | null | null |
script.js
|
va6un/openUR-chromium
|
374caf029dfc425e68e8e6c8a37e3f772fb52b4f
|
[
"MIT"
] | null | null | null |
script.js
|
va6un/openUR-chromium
|
374caf029dfc425e68e8e6c8a37e3f772fb52b4f
|
[
"MIT"
] | null | null | null |
"use strict";
var items = []; // stores values from storage
var input_url = document.getElementById("url");
var form = document.querySelector("form");
var ol = document.querySelector("ol");
var clear = document.getElementById("clear");
var openURL = document.getElementById("openURL");
var addURL = document.getElementById("addURL");
var error = document.getElementById("error");
var count = document.getElementById("count");
var domain;
var li;
var getAllURL = document.getElementById("getAllURL");
var el;
var last_el;
function isValidURL(value) {
return value.match(
/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g
)
? true
: false;
}
function scrollItems() {
el = document.querySelectorAll(".item-url");
last_el = el[el.length - 1];
last_el.scrollIntoView();
}
function setItemsToList(url) {
domain = url
.replace("http://", "")
.replace("https://", "")
.replace("www.", "")
.split(/[/?#]/)[0];
li = document.createElement("li");
li.className = "item-url";
li.innerHTML =
"<span class='small small-danger'>" +
domain +
"</span><span class='small'>" +
url +
"</span>";
ol.appendChild(li);
count.innerHTML = items.length;
if (items.length && items.length > 4) {
scrollItems();
}
}
function getItemsFromStorage() {
if (localStorage.getItem("openUR") != null) {
items = JSON.parse(localStorage.getItem("openUR"));
items.forEach(function(item) {
setItemsToList(item);
});
} else items = [];
}
function checkForDuplicate(value) {
return items.indexOf(value) > -1 ? false : true;
}
function hideError() {
error.innerHTML = "";
error.style.visibility = "hidden";
}
function displayError(text) {
error.innerHTML = text;
error.style.visibility = "visible";
}
function storeValue(value) {
items.push(value);
localStorage.setItem("openUR", JSON.stringify(items));
setItemsToList(value);
}
// events
getAllURL.addEventListener("click", function() {
hideError();
chrome.windows.getAll({ populate: true }, function(windows) {
windows.forEach(function(window) {
window.tabs.forEach(function(tab) {
if (checkForDuplicate(tab.url)) {
storeValue(tab.url);
} else {
displayError("Web address already in favorite list!");
}
});
});
});
});
addURL.addEventListener("click", function() {
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function(tabs) {
if (checkForDuplicate(tabs[0].url)) {
storeValue(tabs[0].url);
} else {
displayError("Web address already in favorite list!");
}
});
});
// (function(item){
// window.open(item, '_blank');
// })(item);
openURL.addEventListener("click", function() {
if (typeof items !== undefined && items.length > 0) {
items.forEach(function(item) {
chrome.tabs.create({ url: item });
});
} else {
displayError("Favorite list is empty! Please add some.");
}
});
form.addEventListener("submit", function(e) {
e.preventDefault();
hideError();
if (typeof Storage === undefined)
displayMessage("Error: Unable to store data!");
else if (checkForDuplicate(input_url.value) == false)
displayError("Website already added to favorite list");
else if (isValidURL(input_url.value) == false)
displayError("Please enter a valid webaddress!");
else storeValue(input_url.value);
input_url.value = "";
});
clear.addEventListener("click", function(e) {
e.preventDefault();
hideError();
localStorage.clear();
while (ol.firstChild) {
ol.removeChild(ol.firstChild);
}
items = [];
count.innerHTML = "";
});
// invoking
hideError();
getItemsFromStorage();
| 26.876812
| 104
| 0.641682
|
c6e02c9b17de1b9871c3e85aecd74719f42f90d3
| 1,852
|
rs
|
Rust
|
src/lib.rs
|
denosaurs/deno_json_op
|
b30e3f9b1da7f8e7ad69d0dbb858b89f775cd17b
|
[
"MIT"
] | 4
|
2020-11-13T23:29:43.000Z
|
2021-01-03T05:41:31.000Z
|
src/lib.rs
|
denosaurs/deno_json_op
|
b30e3f9b1da7f8e7ad69d0dbb858b89f775cd17b
|
[
"MIT"
] | null | null | null |
src/lib.rs
|
denosaurs/deno_json_op
|
b30e3f9b1da7f8e7ad69d0dbb858b89f775cd17b
|
[
"MIT"
] | null | null | null |
extern crate proc_macro;
use proc_macro::TokenStream;
use syn::parse_macro_input;
use syn::ItemFn;
use quote::format_ident;
use quote::quote;
#[proc_macro_attribute]
pub fn json_op(_args: TokenStream, item: TokenStream) -> TokenStream {
let func = parse_macro_input!(item as ItemFn);
let ItemFn {
attrs,
vis,
sig,
block,
} = func;
let is_async = sig.asyncness.is_some();
let name = &sig.ident;
let impl_name = format_ident!("__impl_{}", name);
let mut impl_sig = sig.clone();
impl_sig.ident = impl_name.clone();
let impl_func = ItemFn {
attrs,
vis,
sig: impl_sig,
block,
};
let body = if is_async {
// TODO
// quote! {
// let fut = #impl_name(val, rest)
// .then(|res| async {
// let res = match res {
// Ok(val) => deno_core::serde_json::json!({ "ok": val }),
// Err(err) => deno_core::serde_json::json!({
// "err": err.to_string()
// }),
// };
// deno_core::serde_json::to_vec(&res).unwrap().into_boxed_slice()
// });
// deno_core::Op::Async(fut.boxed())
// }
panic!("async functions are not supported yet");
} else {
quote! {
let res = match #impl_name(val, rest) {
Ok(val) => deno_core::serde_json::json!({
"ok": val
}),
Err(err) => deno_core::serde_json::json!({
"err": err.to_string()
}),
};
deno_core::Op::Sync(deno_core::serde_json::to_vec(&res).unwrap().into_boxed_slice())
}
};
(quote! {
#impl_func
fn #name (_interface: &mut dyn deno_core::plugin_api::Interface, zero_copy: &mut [deno_core::ZeroCopyBuf]) -> Op {
let val = deno_core::serde_json::from_slice(&zero_copy[0]).unwrap();
let rest = &mut zero_copy[1..];
#body
}
}).into()
}
| 23.74359
| 118
| 0.561555
|
b30ab106063e0eb7cc4463bc974b66f0d6656fd2
| 2,465
|
rs
|
Rust
|
examples/template0.rs
|
wdevore/Ranger-Rust-SDL
|
f5aacfbedb273427d02385d359e538d46bf5b593
|
[
"MIT"
] | 1
|
2019-09-25T00:13:08.000Z
|
2019-09-25T00:13:08.000Z
|
examples/template0.rs
|
wdevore/Ranger-Rust-SDL
|
f5aacfbedb273427d02385d359e538d46bf5b593
|
[
"MIT"
] | null | null | null |
examples/template0.rs
|
wdevore/Ranger-Rust-SDL
|
f5aacfbedb273427d02385d359e538d46bf5b593
|
[
"MIT"
] | null | null | null |
// Run this example from the Ranger-Rust-SDL:
// $ cargo run --example template0
extern crate ranger;
use ranger::{nodes::node::Nodes, nodes::scenes::scene_boot::SceneBoot, world::World};
mod template_0;
use template_0::game_scene::GameScene;
use template_0::splash_scene::SplashScene;
const DISPLAY_RATIO: f32 = 16.0 / 9.0;
const WIDTH: u32 = 1024 + 512;
// Larget number causes the view to encompass more of the world
// which makes objects appear smaller.
const VIEW_SCALE: f64 = 1.5;
fn main() {
// Use the Ranger engine to configure, boot and launch game.
let window_width = WIDTH;
let window_height = (WIDTH as f32 / DISPLAY_RATIO) as u32;
let view_width = window_width as f64 * VIEW_SCALE;
let view_height = window_height as f64 * VIEW_SCALE;
println!("Display dimensions: [{} x {}]", window_width, window_height);
println!("View dimensions: [{} x {}]", view_width, view_height);
let mut world = match World::new(
window_width,
window_height,
view_width,
view_height,
true,
"Ranger Basic",
"game.config",
true,
) {
Ok(eng) => eng,
Err(err) => {
panic!("Could not create Engine: {}", err);
}
};
match world.configure() {
Ok(msg) => {
if msg != "Configured" {
panic!("Unknown Configured response: {}", msg);
}
}
Err(err) => {
panic!("Error during Configured sequence: {}", err);
}
}
match world.launch(build) {
Ok(msg) => {
println!("World: {}", msg);
}
Err(err) => {
panic!("Error during launch and/or exit sequence: {}", err);
}
}
}
fn build(world: &mut World) -> bool {
println!("Building...");
let game_scene = GameScene::new("GameScene", world);
Nodes::register_timing_targets(&game_scene, world.get_scheduler());
let splash_scene = SplashScene::with_replacement("SplashScene", game_scene, world);
{
let mut splash = splash_scene.borrow_mut();
if let Some(n) = splash.as_any_mut().downcast_mut::<SplashScene>() {
n.pause_for_seconds(0.25);
}
}
Nodes::register_timing_targets(&splash_scene, world.get_scheduler());
let boot_scene = SceneBoot::with_replacement("BootScene", splash_scene, world);
world.push_scene(boot_scene);
println!("Build complete.");
true
}
| 27.087912
| 87
| 0.599594
|
c620f2ef0c94e251847a1fad3ca77b85fcb87f7b
| 95
|
jbuilder
|
Ruby
|
teammember/app/views/members/show.json.jbuilder
|
sakwaa/lab7part3
|
2dadc38fd0c7c6f83415bb61eafee369ffa8e7b6
|
[
"MIT"
] | null | null | null |
teammember/app/views/members/show.json.jbuilder
|
sakwaa/lab7part3
|
2dadc38fd0c7c6f83415bb61eafee369ffa8e7b6
|
[
"MIT"
] | null | null | null |
teammember/app/views/members/show.json.jbuilder
|
sakwaa/lab7part3
|
2dadc38fd0c7c6f83415bb61eafee369ffa8e7b6
|
[
"MIT"
] | null | null | null |
json.extract! @member, :id, :id, :first_name, :last_name, :job_title, :created_at, :updated_at
| 47.5
| 94
| 0.726316
|
e2ff76bc19689784b9143d8907870e7c9759def0
| 2,278
|
py
|
Python
|
installer.py
|
stevenplatt/tcp_air
|
61960bd5df69cf2a561ee626387ac974e97252a0
|
[
"MIT"
] | null | null | null |
installer.py
|
stevenplatt/tcp_air
|
61960bd5df69cf2a561ee626387ac974e97252a0
|
[
"MIT"
] | null | null | null |
installer.py
|
stevenplatt/tcp_air
|
61960bd5df69cf2a561ee626387ac974e97252a0
|
[
"MIT"
] | null | null | null |
# import the os module
import os
from shutil import copyfile
# assign and create the base directories for TCP Air
rootpath = "/etc/config/tcp_air"
locpeers = "/etc/config/tcp_air/peers"
netpeers = "/etc/config/tcp_air/peers/network_peers"
cwd = os.getcwd()
def main():
os.makedirs(rootpath)
# create base folders
folders = ['scripts','additions','peers']
for folder in folders:
try:
os.mkdir(os.path.join(rootpath,folder))
except OSError:
print ("Creation of the directory %s failed" % folder)
else:
print ("Successfully created the directory %s" % folder)
# create an additional directory inside /etc/config/tcp_air/peers
try:
os.mkdir(netpeers)
except OSError:
print ("Creation of the directory network_peers failed")
else:
print ("Successfully created the directory network_peers")
# create an empty local peers file to be modified by the user
try:
peerfile = open(os.path.join(locpeers, 'local_peers.txt'), 'w')
except OSError:
print ("Creation of local_peers file failed")
else:
print ("Successfully created the file local_peers")
config()
# copy python program files from installer to device folders
def config():
try:
copyfile(os.path.join(cwd, 'network_sync.py'), '/etc/config/tcp_air/scripts/network_sync.py')
except IOError:
print ("Creation of network_sync file failed")
else:
print ("Successfully created the file network_sync")
pass
try:
copyfile(os.path.join(cwd, 'update_peering.py'), '/etc/config/tcp_air/scripts/update_peering.py')
except IOError:
print ("Creation of update_peering file failed")
else:
print ("Successfully created the file update_peering")
pass
try:
copyfile(os.path.join(cwd, 'update_firewall.py'), '/etc/config/tcp_air/scripts/update_firewall.py')
except IOError:
print ("Creation of update_firewall file failed")
else:
print ("Successfully created the file update_firewall")
pass
# if code is not run my issuing the python interpreter command - start the main() function anyway
if __name__ == '__main__':
main()
| 32.542857
| 107
| 0.660667
|
6fb8090b54a210548d2960eb5cd8209f7acee956
| 163
|
sql
|
SQL
|
script.sql
|
wandersonsousa/pagination-codeigniter4-datatables
|
f5010d5ce834c71fa39cee4665cf3e45ee63d19f
|
[
"MIT"
] | 1
|
2020-10-30T23:17:58.000Z
|
2020-10-30T23:17:58.000Z
|
script.sql
|
wandersonsousa/pagination-codeigniter4-datatables
|
f5010d5ce834c71fa39cee4665cf3e45ee63d19f
|
[
"MIT"
] | 22
|
2021-04-26T07:29:51.000Z
|
2022-03-30T13:04:31.000Z
|
script.sql
|
wandersonsousa/pagination-codeigniter4-datatables
|
f5010d5ce834c71fa39cee4665cf3e45ee63d19f
|
[
"MIT"
] | null | null | null |
CREATE DATABASE 'pagination_ci4';
USE pagination_ci4;
CREATE TABLE TB_Posts(
id INT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
body TEXT NOT NULL
);
| 14.818182
| 33
| 0.711656
|
f63c765a8159d4e82b57e11add5c5cda6d32629a
| 5,924
|
cpp
|
C++
|
src/S1L.cpp
|
vismate/Algoritmusok
|
501b9310bb01261aacda5b617a451b64b2a60ec7
|
[
"MIT"
] | null | null | null |
src/S1L.cpp
|
vismate/Algoritmusok
|
501b9310bb01261aacda5b617a451b64b2a60ec7
|
[
"MIT"
] | null | null | null |
src/S1L.cpp
|
vismate/Algoritmusok
|
501b9310bb01261aacda5b617a451b64b2a60ec7
|
[
"MIT"
] | null | null | null |
// Fejelem nélküli egyszeresen csatolt lista egyszerű, procedurális implementációja
// Az egyes függvények, bár megtehetnék, nem használják egymást. Külön-külön működőképesek.
#include <iostream>
// Egy nódus egy T típusú adattagot, illetve a következő nódusra mutató pointert tartalmazza.
template <typename T>
struct ListNode
{
T data;
ListNode<T> *next = nullptr;
};
// Operátor overload kiíratáshoz.
template <typename T>
std::ostream &operator<<(std::ostream &stream, const ListNode<T> *p)
{
stream << "[ ";
while (p != nullptr)
{
stream << p->data << " ";
p = p->next;
}
stream << "]";
return stream;
}
// Egy std::initializer_list-ből állítunk elő egy új listát.
template <typename T>
auto create(std::initializer_list<T> init_list) -> ListNode<T> *
{
if (init_list.size() == 0)
return nullptr;
// Lefoglaljuk és inicializáljuk az első nódust, majd a 2. elemtől kezdve hozzáfűzögetjük az elemeket.
ListNode<T> *p = new ListNode<T>{*init_list.begin()}, *q = p;
for (auto itr = init_list.begin() + 1; itr != init_list.end(); itr++)
{
q->next = new ListNode<T>{*itr};
q = q->next;
}
// Visszaadjuk az elmentett első nódusra mutató pointert.
return p;
}
template <typename T>
auto length(ListNode<T> *p) -> size_t
{
size_t n = 0;
while (p != nullptr)
{
n++;
p = p->next;
}
return n;
}
// Itt elkezdünk pointer-referenciákat alkalmazni,
// mivel a paraméterül kapott első nódusra mutató pointer
// a függvény során megváltozhat.
// Ez itt látszik a legtisztábban.
template <typename T>
auto push_front(ListNode<T> *&p, T item) -> void
{
p = new ListNode<T>{item, p};
}
template <typename T>
auto push_back(ListNode<T> *&p, T item) -> void
{
// Ha a listánk üres, mutasson 'p' az új elemre.
if (p == nullptr)
p = new ListNode<T>{item, nullptr};
else
{
// Eliterálunk az utolsó nódusig.
ListNode<T> *q = p; // Lemásoljuk 'p'-t, mert nem akarjuk megváltoztatni.
while (q->next != nullptr)
{
q = q->next;
}
// Az utolsó nódus 'next' mezője mutasson az úl elemre.
q->next = new ListNode<T>{item, nullptr};
}
}
template <typename T>
auto pop_front(ListNode<T> *&p) -> void
{
if (p != nullptr)
{
ListNode<T> *next = p->next;
delete p;
p = next;
}
}
template <typename T>
auto pop_back(ListNode<T> *&p) -> void
{
if (p == nullptr)
return;
// Iterálunk a lista utolsó nódusáig, de számon tartjuk az azt megelőző nódust is.
ListNode<T> *prev = nullptr, *q = p;
while (q->next != nullptr)
{
prev = q;
q = q->next;
}
// Töröljük az utolsó nódust, és ha volt azt megelőző elem, akkor annak a 'next' mezőjét,
// ellenkező esetben a 'p'-t állítjuk nullptr-re.
delete q;
(prev ? prev->next : p) = nullptr;
}
template <typename T>
auto reverse(ListNode<T> *&p) -> void
{
ListNode<T> *prev = nullptr, *next = nullptr;
while (p != nullptr)
{
next = p->next;
p->next = prev;
prev = p;
p = next;
}
p = prev;
}
template <typename T>
auto purge(ListNode<T> *p) -> void
{
while (p != nullptr)
{
ListNode<T> *tmp = p->next;
delete p;
p = tmp;
}
}
template <typename T>
auto find(ListNode<T> *p, const T &item) -> ListNode<T> *
{
while (p != nullptr)
{
if (p->data == item)
return p;
p = p->next;
}
return nullptr;
}
template <typename T>
auto at(ListNode<T> *p, size_t ind) -> ListNode<T> *
{
while (p != nullptr && ind > 0)
{
ind--;
p = p->next;
}
return p;
}
template <typename T>
auto append(ListNode<T> *&p1, ListNode<T> *p2) -> void
{
// Ha az első lista üres, legyen a lista első nódusa a második lista első nódusa.
if (p1 == nullptr)
p1 = p2;
// Megkeressük az első lista utolsó nódusát, majd annak a 'next' mezőjét p2-re állítjuk.
ListNode<T> *q = p1;
while (q->next != nullptr)
{
q = q->next;
}
q->next = p2;
}
template <typename T>
auto remove(ListNode<T> *&p, ListNode<T> *item) -> void
{
if (p == nullptr || item == nullptr)
return;
// Ha az első elemet kell törölnünk, a p-t a lista második elemére állítjuk.
if (p == item)
{
p = item->next;
delete item;
return;
}
// Megkeressük a törlendő elem előtti nódust, majd ha megtaláltuk kifűzzük az elemet és töröljük.
ListNode<T> *q = p;
while (q != nullptr && q->next != item)
{
q = q->next;
}
if (q)
{
q->next = item->next;
delete item;
}
}
template <typename T>
auto insert(ListNode<T> *p, ListNode<T> *q) -> void
{
if (p == nullptr || q == nullptr)
return;
q->next = p->next;
p->next = q;
}
#ifdef S1L
int main()
{
auto int_list = create({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
push_front(int_list, 6);
push_back(int_list, 11);
std::cout << "Lista: " << int_list << std::endl;
reverse(int_list);
std::cout << "Megfordítva: " << int_list << std::endl;
pop_back(int_list);
pop_front(int_list);
std::cout << "Se eleje, se vége: " << int_list << std::endl;
std::cout << "Hossz: " << length(int_list) << std::endl;
auto string_list = create({"list.", "a", "I\'m"});
append(string_list, create({"World!", "Hello"}));
reverse(string_list);
std::cout << string_list << std::endl;
remove(string_list, string_list);
std::cout << "Eleje nélkül: " << string_list << std::endl;
std::cout << "World utáni szó: " << find(string_list, (const char *)"World!")->next->data << std::endl;
std::cout << "Negyedik szó: " << at(string_list, 3)->data << std::endl;
purge(int_list);
purge(string_list);
}
#endif
| 22.354717
| 107
| 0.57208
|
cf017fcd6278e302a33dc396bb9ddcda24342be3
| 2,038
|
php
|
PHP
|
resources/views/excel/partials/logs.blade.php
|
jimbomilk/allowappMng
|
d77b850742ddf3a801f7fac3d40cb7963b3acb1b
|
[
"MIT"
] | null | null | null |
resources/views/excel/partials/logs.blade.php
|
jimbomilk/allowappMng
|
d77b850742ddf3a801f7fac3d40cb7963b3acb1b
|
[
"MIT"
] | 1
|
2021-02-02T21:42:23.000Z
|
2021-02-02T21:42:23.000Z
|
resources/views/excel/partials/logs.blade.php
|
jimbomilk/allowappMng
|
d77b850742ddf3a801f7fac3d40cb7963b3acb1b
|
[
"MIT"
] | null | null | null |
<div class="row">
<div class="col-sm-offset-3 col-sm-6" >
<div class="panel panel-default" >
<div class="panel-heading" style="background-color: rgb(246,216,88);color: #000000">
Log Importaciones
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<table class="table table-responsive table-striped">
@foreach($excels as $index=>$element)
@if ($index == 0)
<tr>
@foreach($element->getAttributes() as $key=>$value)
@if ($key!='location_id' && $key!='updated_at')
<th>{{trans("label.".$name.".".$key)}}</th>
@endif
@endforeach
</tr>
@endif
<tr data-id="{{$element->id}}">
@foreach($element->getAttributes() as $key=>$value)
@if ($key!='location_id' && $key!='updated_at')
<td>@if($key=='user_id'){{App\User::find($value)->name}}@else {{$value}} @endif</td>
@endif
@endforeach
</tr>
@endforeach
</table>
</div>
<div class="col-sm-12 ">
<a class="btn btn-info center-block" href="{{ url("locations/$name/create") }}" role="button">
{{trans('labels.new')}} {{trans('label.'.$name)}}
</a>
</div>
</div>
</div>
</div>
</div>
</div>
| 42.458333
| 124
| 0.327282
|
a9e8506fdd99fe8ad5e96cfdeb2ff8a2cda3a314
| 5,352
|
php
|
PHP
|
app/controllers/judicial.php
|
zak4u/ibrmsnew
|
141b225ffbe83c97388ca510a5687bbdafb6ca1b
|
[
"MIT"
] | null | null | null |
app/controllers/judicial.php
|
zak4u/ibrmsnew
|
141b225ffbe83c97388ca510a5687bbdafb6ca1b
|
[
"MIT"
] | null | null | null |
app/controllers/judicial.php
|
zak4u/ibrmsnew
|
141b225ffbe83c97388ca510a5687bbdafb6ca1b
|
[
"MIT"
] | null | null | null |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Judicial extends CI_Controller {
var $data;
function __construct() {
parent::__construct(); // needed when adding a constructor to a controller
//page_specific
$this->data = array(
'head_content' => 'layouts/page_specific/blank',
'foot_content' => 'layouts/page_specific/blank'
);
// $this->data can be accessed from anywhere in the controller.
$this->load->model('kp07_m', 'kp07_m');
}
public function index() {
$data = $this->data;
$data['main_content'] = 'judicial_list';
$data['pagename'] = 'Judicial Cases';
$data['pagesubname'] = 'List of Barangay Judicial Cases';
$data['lists'] = $this->kp07_m->list_kp07_status_m('On-going');
// foreach ($data['lists'] as $list) {
// $casenum = $list->kp07_casenumber;
// }
//
// $data['listsinvolved'] = $this->kp07_m->list_kp07_involved_case_m($casenum);
$this->load->view('layouts/main', $data);
}
//////////////// KP 07
public function kp07_view($casenum) {
$data = $this->data;
$data['main_content'] = 'judicial_view_case';
$data['pagename'] = 'Judicial Case';
$data['pagesubname'] = 'Resident Case Overview';
$data['kp07s'] = $this->kp07_m->get_kp07_m($casenum);
$data['listscaseinvolved'] = $this->kp07_m->list_kp07_involved_case_m($casenum);
$this->load->view('layouts/main', $data);
}
public function kp07_add() {
$data = $this->data;
$data['main_content'] = 'judicial_kp07_add';
$data['pagename'] = 'Judicial Case';
$data['pagesubname'] = 'KP 07 - Complaint Form';
$this->load->view('layouts/main', $data);
}
public function add_kp07() {
$result = $this->kp07_m->add_kp07_m();
if ($result == FALSE) {
$this->session->set_flashdata('msg', "Failed!");
} else {
$this->session->set_flashdata('msg', "Case successfully added!");
}
redirect('judicial');
}
public function kp07_edit($casenum) {
$data = $this->data;
$data['main_content'] = 'judicial_kp07_edit';
$data['pagename'] = 'Edit Case';
$data['pagesubname'] = 'KP 07 - Complaint Form';
$data['listscase'] = $this->kp07_m->get_kp07_m($casenum);
$data['listscaseC'] = $this->kp07_m->list_kp07_involved_case_restype_m($casenum,'Complainant');
$data['listscaseR'] = $this->kp07_m->list_kp07_involved_case_restype_m($casenum,'Respondent');
$this->load->view('layouts/main', $data);
}
public function edit_kp07($casenum) {
$result = $this->kp07_m->edit_kp07_m();
if($result == FALSE){
$this->session->set_flashdata('msg',"Failed!");
}else{
$this->session->set_flashdata('msg',"Purok updated!");
}
redirect('judicial/kp07_view/'.$casenum);
}
public function kp07_delete($casenum) {
$result = $this->kp07_m->delete_kp07_m($casenum);
if($result == FALSE){
$this->session->set_flashdata('msg',"Failed!");
}else{
$this->session->set_flashdata('msg',"Purok removed!");
}
redirect('judicial');
}
//////////////// KP 07 END
public function kp08add() {
$data = $this->data;
$data['main_content'] = 'judicial_kp08add';
$data['pagename'] = 'Add Form';
$data['pagesubname'] = 'KP Form No. 08 - Notice of Hearing';
$this->load->view('layouts/main', $data);
}
public function kp08edit() {
$data = $this->data;
$data['main_content'] = 'judicial_kp08edit';
$data['pagename'] = 'Edit Form';
$data['pagesubname'] = 'KP Form No. 08 - Notice of Hearing';
$this->load->view('layouts/main', $data);
}
public function kp08print() {
$data = $this->data;
$data['main_content'] = 'judicial_kp08print';
$data['pagename'] = 'Print Form';
$data['pagesubname'] = 'KP Form No. 08 - Notice of Hearing';
$this->load->view('layouts/main', $data);
}
public function kp09add() {
$data = $this->data;
$data['main_content'] = 'judicial_kp09add';
$data['pagename'] = 'Add Form';
$data['pagesubname'] = 'KP Form No. 09 - Summons';
$this->load->view('layouts/main', $data);
}
public function kp09edit() {
$data = $this->data;
$data['main_content'] = 'judicial_kp09edit';
$data['pagename'] = 'Edit Form';
$data['pagesubname'] = 'KP Form No. 09 - Summons';
$this->load->view('layouts/main', $data);
}
public function kp09print() {
$data = $this->data;
$data['main_content'] = 'judicial_kp09print';
$data['pagename'] = 'Print Form';
$data['pagesubname'] = 'KP Form No. 09 - Summons';
$this->load->view('layouts/main', $data);
}
public function judicial_reports() {
$data = $this->data;
$data['main_content'] = 'judicial_reports';
$data['pagename'] = 'Judicial Reports';
$data['pagesubname'] = '';
$this->load->view('layouts/main', $data);
}
}
| 29.245902
| 103
| 0.554559
|
ff874f114b26382458eb9559880f0ecf2444bc3a
| 272
|
asm
|
Assembly
|
TurtleTools/Examples/test_instruction_memory.asm
|
foxostro/TurtleTTL
|
7d2163b11b91ae04ad69d38c0354194b9c306ed0
|
[
"MIT"
] | 1
|
2021-08-18T22:30:11.000Z
|
2021-08-18T22:30:11.000Z
|
TurtleTools/Examples/old/test_instruction_memory.asm
|
foxostro/Turtle16
|
67e6d2afa02f2bc07711f8e8d756e5b891ea8df5
|
[
"MIT"
] | null | null | null |
TurtleTools/Examples/old/test_instruction_memory.asm
|
foxostro/Turtle16
|
67e6d2afa02f2bc07711f8e8d756e5b891ea8df5
|
[
"MIT"
] | null | null | null |
LI X, 0x00
LI Y, 0x00
LI D, 0
LI P, 0x28 # LI A
LI D, 1
LI P, 0xff
LI Y, 0x01
LI D, 0
LI P, 0x98 # LI U
LI D, 1
LI P, 0xff
LI Y, 0x02
LI D, 0
LI P, 0x58 # LI V
LI D, 1
LI P, 0xff
LI Y, 0x03
LI D, 0
LI P, 0x80 # HLT
LI D, 1
LI P, 0x0
LI X, 0x80
LI Y, 0x00
JMP
NOP
NOP
| 8.5
| 17
| 0.577206
|
438c7eeb15a51e743bb485372f591e66e69f1f59
| 809
|
ts
|
TypeScript
|
src/utils/statcord.ts
|
EndBug/game-tracker
|
98d795664fe77a575966640bec9c5e13357d7165
|
[
"MIT"
] | 12
|
2020-05-17T07:56:56.000Z
|
2021-12-09T16:17:21.000Z
|
src/utils/statcord.ts
|
EndBug/game-tracker
|
98d795664fe77a575966640bec9c5e13357d7165
|
[
"MIT"
] | 61
|
2019-04-28T20:28:21.000Z
|
2022-02-11T23:57:39.000Z
|
src/utils/statcord.ts
|
EndBug/game-tracker
|
98d795664fe77a575966640bec9c5e13357d7165
|
[
"MIT"
] | 5
|
2019-12-08T11:51:01.000Z
|
2020-11-16T07:17:43.000Z
|
import { Client as StatClient } from 'statcord.js'
import { Client as DiscordClient } from 'discord.js-light'
export let statcord: StatClient
export const init = (client: DiscordClient) => {
statcord = new StatClient({
client,
key: process.env.STATCORD_TOKEN
})
}
interface postOptions {
errorHandling?: 'throw' | 'log' | 'ignore'
ignoreUndefined?: boolean
}
export function postCommand(
command_name: string,
user_id: string,
options: postOptions = {}
) {
try {
if (statcord) statcord.postCommand(command_name, user_id)
else if (options.ignoreUndefined === false)
throw new Error('Statcord client is undefined')
} catch (e) {
if (!options.errorHandling || options.errorHandling == 'throw') throw e
if (options.errorHandling == 'log') console.error(e)
}
}
| 26.096774
| 75
| 0.692213
|
2302740a010f7353337b36ad4f9404db1925cf62
| 14,598
|
swift
|
Swift
|
Chirrrup/TweetsViewController.swift
|
SatyamJ/Chirrrup
|
0780f12d31d68585d8d42842e14c7b6108f959fd
|
[
"Apache-2.0"
] | null | null | null |
Chirrrup/TweetsViewController.swift
|
SatyamJ/Chirrrup
|
0780f12d31d68585d8d42842e14c7b6108f959fd
|
[
"Apache-2.0"
] | 3
|
2016-02-21T15:20:52.000Z
|
2016-03-01T14:40:58.000Z
|
Chirrrup/TweetsViewController.swift
|
SatyamJ/Twitter
|
0780f12d31d68585d8d42842e14c7b6108f959fd
|
[
"Apache-2.0"
] | null | null | null |
//
// TweetsViewController.swift
// Twitter
//
// Created by Satyam Jaiswal on 2/20/16.
// Copyright © 2016 Satyam Jaiswal. All rights reserved.
//
import UIKit
import AFNetworking
import MBProgressHUD
class TweetsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CellDelegate, UIScrollViewDelegate, ComposeTweetDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var menuBarButton: UIBarButtonItem!
@IBOutlet weak var logoView: UIView!
@IBOutlet weak var networkErrorImageView: UIImageView!
@IBOutlet weak var ntwkErrStackView: UIStackView!
var tweets: [Tweet]?
var moreDataRequested: Bool = false
var loadingMoreView:InfiniteScrollActivityView?
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
override func viewDidAppear(_ animated: Bool) {
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func setupUI(){
self.setupNavigationBar()
self.setupTableView()
self.requestNetworkData()
self.setupRefreshControl()
self.setupInfiniteScrollView()
self.networkErrorImageView.alpha = 0
self.setupGestureRecognizers()
}
fileprivate func setupGestureRecognizers(){
let networkGesture = UITapGestureRecognizer()
networkGesture.addTarget(self, action: #selector(onTapNetworkError))
self.ntwkErrStackView.addGestureRecognizer(networkGesture)
self.ntwkErrStackView.isUserInteractionEnabled = true
}
func onTapNetworkError(_ sender: AnyObject){
// print("onTapNetworkError called")
hideNetworkError()
self.requestNetworkData()
}
fileprivate func setupTableView(){
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
self.tableView.tableFooterView = UIView()
}
fileprivate func setupRefreshControl(){
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged)
tableView.insertSubview(refreshControl, at: 0)
}
fileprivate func setupNavigationBar(){
self.menuBarButton.target = self.revealViewController()
self.menuBarButton.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
// self.menuBarButton.image = User.currentUser.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.tweets == nil {
return 0
}else{
return self.tweets!.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TweetCell", for: indexPath) as! TweetCell
cell.tweet = self.tweets![indexPath.row]
cell.delegate = self
cell.accessoryType = .none
return cell
}
fileprivate func setupInfiniteScrollView(){
// Set up Infinite Scroll loading indicator
let frame = CGRect(x: 0, y: tableView.contentSize.height, width: tableView.bounds.size.width, height: InfiniteScrollActivityView.defaultHeight)
loadingMoreView = InfiniteScrollActivityView(frame: frame)
loadingMoreView!.isHidden = true
tableView.addSubview(loadingMoreView!)
var insets = tableView.contentInset;
insets.bottom += InfiniteScrollActivityView.defaultHeight;
tableView.contentInset = insets
}
func refreshControlAction(_ refreshControl: UIRefreshControl){
requestNetworkData()
refreshControl.endRefreshing()
}
fileprivate func requestNetworkData(){
MBProgressHUD.showAdded(to: self.view, animated: true)
TwitterClient.sharedInstance?.homeTimeline({ (tweets:[Tweet]) -> () in
if tweets.count > 0 {
self.tweets = tweets
self.tableView.reloadData()
MBProgressHUD.hide(for: self.view, animated: true)
self.hideNetworkError()
}
MBProgressHUD.hide(for: self.view, animated: true)
}) { (error: NSError) -> () in
print("Error: \(error.localizedDescription)")
MBProgressHUD.hide(for: self.view, animated: true)
if error.localizedDescription.contains("429"){
self.requestCountExceeded()
}else{
self.showNetworkError()
}
}
}
fileprivate func requestCountExceeded(){
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud?.show(animated: true, whileExecuting: {
hud?.labelText = "Request limit exceeded. Try again later."
})
hud?.hide(true, afterDelay: 1)
}
fileprivate func showNetworkError(){
UIView.animate(withDuration: 2, animations: {
self.networkErrorImageView.alpha = 1.0
})
}
fileprivate func hideNetworkError(){
UIView.animate(withDuration: 1, animations: {
self.networkErrorImageView.alpha = 0.0
})
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (!moreDataRequested){
let scrollViewContentHeight = self.tableView.contentSize.height
let scrollOffsetThreshold = scrollViewContentHeight - self.tableView.bounds.size.height
if scrollView.contentOffset.y > scrollOffsetThreshold && tableView.isDragging {
moreDataRequested = true
// Update position of loadingMoreView, and start loading indicator
let frame = CGRect(x: 0, y: tableView.contentSize.height, width: tableView.bounds.size.width, height: InfiniteScrollActivityView.defaultHeight)
if let progressView = self.loadingMoreView{
progressView.frame = frame
progressView.startAnimating()
}
loadMoreData()
}
}
}
fileprivate func loadMoreData(){
TwitterClient.sharedInstance?.homeTimelineOnScroll(self.getEarliestTweetId(), success: { (moreTweets: [Tweet]) in
if moreTweets.count > 0 {
self.tweets?.append(contentsOf: moreTweets)
self.tableView.reloadData()
}
self.loadingMoreView?.stopAnimating()
self.moreDataRequested = false
}) { (error: NSError) in
self.loadingMoreView?.stopAnimating()
print("Error in loading more feeds: \(error.localizedDescription)")
}
}
fileprivate func getEarliestTweetId() -> Int? {
var id:Int?
if let tweets = self.tweets{
if tweets.count > 0{
if let strId = tweets[tweets.count-1].tweetId{
id = Int(strId)
}
}
}
return id
}
func onTapCellProfileImage(_ sender: AnyObject?){
//print("onTapCellProfileImage")
performSegue(withIdentifier: "showUserProfileSegue", sender: sender)
}
func onTapCellLike(_ sender: AnyObject?) {
//print("onTapCellLike called")
if let recognizer = sender as? UITapGestureRecognizer{
let imageView = recognizer.view
if let cellView = imageView?.superview?.superview?.superview as? TweetCell {
if let indexPath = self.tableView.indexPath(for: cellView) {
if let tweet = self.tweets?[indexPath.row]{
//print("processing tweet id: \(tweet.tweetId)")
if tweet.liked == true{
//self.tweets![(indexPath?.row)!].liked = false
TwitterClient.sharedInstance?.unlike(String(tweet.tweetId!),
success: { () -> () in
self.tweets![indexPath.row].liked = false
self.tweets![indexPath.row].likes_count -= 1
self.tableView.reloadData()
}, failure: { (error: NSError) -> () in
print("Tweet Unlike error: \(error.localizedDescription)")
})
}else{
//self.tweets![(indexPath?.row)!].liked = true
TwitterClient.sharedInstance?.like(String(tweet.tweetId!),
success: { () -> () in
self.tweets![indexPath.row].liked = true
self.tweets![indexPath.row].likes_count += 1
self.tableView.reloadData()
}, failure: { (error: NSError) -> () in
print("Tweet Like error: \(error.localizedDescription)")
})
}
}
}
}
}
}
func onTapCellReply(_ sender: AnyObject?) {
performSegue(withIdentifier: "tweetSegue", sender: sender)
}
func onTapCellRetweet(_ sender: AnyObject?) {
//print("onTapCellRetweet called")
if let recognizer = sender as? UITapGestureRecognizer{
let imageView = recognizer.view
if let cellView = imageView?.superview?.superview?.superview as? TweetCell {
if let indexPath = self.tableView.indexPath(for: cellView) {
if let tweet = self.tweets?[indexPath.row]{
//print("processing tweet id: \(tweet.tweetId!)")
if tweet.retweeted == true{
TwitterClient.sharedInstance?.unretweet(String(tweet.tweetId!),
success: { () -> () in
self.tweets![indexPath.row].retweeted = false
self.tweets![indexPath.row].retweet_count -= 1
self.tableView.reloadData()
}, failure: { (error: NSError) -> () in
print("Un-retweet error: \(error.localizedDescription)")
})
}else{
TwitterClient.sharedInstance?.retweet(String(tweet.tweetId!),
success: { () -> () in
self.tweets![indexPath.row].retweeted = true
self.tweets![indexPath.row].retweet_count += 1
self.tableView.reloadData()
}, failure: { (error: NSError) -> () in
print("Retweet error: \(error.localizedDescription)")
})
}
}
}
}
}
}
@IBAction func onComposeTapped(_ sender: Any) {
performSegue(withIdentifier: "tweetSegue", sender: sender)
}
func onNewTweet(status: Tweet) {
self.tweets?.insert(status, at: 0)
self.tableView.reloadData()
}
func reload(_ sender: TweetCell) {
if let indexPath = self.tableView.indexPath(for: sender){
self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none)
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "TweetDetailsSegue"{
if let detailsViewController = segue.destination as? TweetDetailsViewController {
if let cell = sender as? TweetCell{
if let indexPath = tableView.indexPath(for: cell) {
detailsViewController.tweet = self.tweets![indexPath.row] as Tweet
detailsViewController.row = indexPath.row
let bgView = UIView()
bgView.backgroundColor = UIColor.gray
cell.selectedBackgroundView = bgView
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
} else if segue.identifier == "showUserProfileSegue" {
if let profileViewController = segue.destination as? MeViewController {
if let recog = sender as? UITapGestureRecognizer {
let view = recog.view
if let cell = view?.superview?.superview as? TweetCell {
if let indexPath = tableView.indexPath(for: cell) {
if let tweet = tweets?[indexPath.row] {
profileViewController.user = tweet.user
}
}
}
}
}
} else if segue.identifier == "tweetSegue" {
if let nc = segue.destination as? UINavigationController {
if let composeViewController = nc.topViewController as? ComposeTweetViewController {
composeViewController.delegate = self
if let recognizer = sender as? UIGestureRecognizer{
let view = recognizer.view
if let cell = view?.superview?.superview?.superview as? TweetCell{
if let indexPath = tableView.indexPath(for: cell) {
if let tweet = self.tweets?[indexPath.row]{
composeViewController.recepientTweetId = tweet.tweetId
composeViewController.recepientUser = tweet.user
}
}
}
}
}
}
}
}
}
| 40.890756
| 159
| 0.552678
|
d87e47c08dd2dab5e40b02202760c712953b0b3e
| 543
|
ps1
|
PowerShell
|
private/set-sspr.ps1
|
robkoo/SecureScore
|
78c0192fd379d3f0a907fff6d87fb4519b073e54
|
[
"MIT"
] | 6
|
2020-08-10T00:51:52.000Z
|
2021-10-15T02:08:41.000Z
|
private/set-sspr.ps1
|
robkoo/SecureScore
|
78c0192fd379d3f0a907fff6d87fb4519b073e54
|
[
"MIT"
] | 1
|
2021-08-14T07:21:09.000Z
|
2021-08-14T07:21:09.000Z
|
private/set-sspr.ps1
|
robkoo/SecureScore
|
78c0192fd379d3f0a907fff6d87fb4519b073e54
|
[
"MIT"
] | 3
|
2020-08-25T15:03:00.000Z
|
2021-08-12T19:06:55.000Z
|
function Set-SSPR {
if (!$script:confirmed) {
Write-Warning "This will enable self service password reset, at the next logon users that do not have a mobile phone and/or alternative e-mail set, will be request to fill one in. Do you want to continue?" -WarningAction Inquire
}
if ($script:ExternallyResolved) {
Set-ExternallyResolved -issue 'SelfServicePasswordReset'
}
else {
Set-MsolCompanySettings -TenantId $tenant.TenantId -SelfServePasswordResetEnabled:$true -erroraction Stop
}
}
| 41.769231
| 237
| 0.709024
|
33c4e23c4261c4cb399589855c721fe2f1d77a84
| 266
|
ps1
|
PowerShell
|
2019-06-psconfeu/Pester internals v2/demos/discovery/demo-filtering-whole-file.Tests.ps1
|
nohwnd/presentations
|
cae23d4936f1d85107fd371fe0d79e7c5197db23
|
[
"MIT"
] | 3
|
2020-05-21T00:19:32.000Z
|
2020-11-05T16:19:01.000Z
|
2019-06-psconfeu/Pester internals v2/demos/discovery/demo-filtering-whole-file.Tests.ps1
|
nohwnd/presentations
|
cae23d4936f1d85107fd371fe0d79e7c5197db23
|
[
"MIT"
] | null | null | null |
2019-06-psconfeu/Pester internals v2/demos/discovery/demo-filtering-whole-file.Tests.ps1
|
nohwnd/presentations
|
cae23d4936f1d85107fd371fe0d79e7c5197db23
|
[
"MIT"
] | 1
|
2020-09-21T20:49:31.000Z
|
2020-09-21T20:49:31.000Z
|
BeforeAll {
Write-Host "Waiting 3 second..."
Start-Sleep -Seconds 3
}
Describe "d2" {
BeforeAll {
Write-Host "Setup 2"
}
Describe "d22" {
It "t2" -Tag "ReleaseOnly" {
1 | Should -Be 1
}
}
}
| 16.625
| 37
| 0.462406
|
3bace919a91887437413e65354eb010f73700ccd
| 1,296
|
lua
|
Lua
|
ShwordJam/gameobject/player/states/wait.lua
|
pfirsich/ShwordJam
|
5be383aa98929083484ce3a5648e678a14931bad
|
[
"MIT"
] | null | null | null |
ShwordJam/gameobject/player/states/wait.lua
|
pfirsich/ShwordJam
|
5be383aa98929083484ce3a5648e678a14931bad
|
[
"MIT"
] | null | null | null |
ShwordJam/gameobject/player/states/wait.lua
|
pfirsich/ShwordJam
|
5be383aa98929083484ce3a5648e678a14931bad
|
[
"MIT"
] | null | null | null |
local const = require("constants")
local class = require("libs.class")
local states = require("gameobject.player.states.states")
local Shword = require("gameobject.shword")
local Wait = class("Wait", states.Base)
function Wait:initialize(player, ...)
states.Base.initialize(self, player)
end
function Wait:enter()
self.lastMove = nil
self.player.animator:play('idle')
self.canDash = false
end
function Wait:exit(newState)
end
function Wait:update()
local player = self.player
player:friction(const.player.friction)
if math.abs(player.moveDir[1]) <= 1e-5 then
self.canDash = true
self.lastMove = nil
else
if not self.lastMove then
self.lastMove = player.time
end
end
if self.canDash and math.abs(player.moveDir[1]) > const.player.dashThresh then
player:setState(states.Dash)
return
end
if self.lastMove and player.time - self.lastMove > const.player.dashInputDelay then
player:setState(states.Run)
return
end
if player.controller.jump.pressed then
player:setState(states.JumpSquat)
return
end
if not player:onGround() then
player:setState(states.Fall)
return
end
player:enterAimShword()
end
return Wait
| 21.6
| 87
| 0.667438
|
640e2ccc7af542d82f8d219b6173e91225df3b04
| 6,572
|
py
|
Python
|
notebooks/util.py
|
JoeriHermans/constraining-dark-matter-with-stellar-streams-and-ml
|
389e6ccf0b876b94477e2ed15442775e75b9c66b
|
[
"BSD-3-Clause"
] | 12
|
2020-11-30T12:36:54.000Z
|
2022-03-15T15:54:13.000Z
|
notebooks/util.py
|
JoeriHermans/constraining-dark-matter-with-stellar-streams-and-ml
|
389e6ccf0b876b94477e2ed15442775e75b9c66b
|
[
"BSD-3-Clause"
] | 6
|
2020-12-01T09:00:23.000Z
|
2022-03-12T00:51:51.000Z
|
notebooks/util.py
|
JoeriHermans/constraining-dark-matter-with-stellar-streams-and-ml
|
389e6ccf0b876b94477e2ed15442775e75b9c66b
|
[
"BSD-3-Clause"
] | 1
|
2021-03-31T15:26:29.000Z
|
2021-03-31T15:26:29.000Z
|
import glob
import hypothesis
import numpy as np
import os
import requests
import torch
from hypothesis.nn.amortized_ratio_estimation import RatioEstimatorEnsemble
from ratio_estimation import DoubleRatioEstimator
from ratio_estimation import MLPRatioEstimator
from ratio_estimation import RatioEstimator
from ratio_estimation import SingleRatioEstimator
from ratio_estimation import resnet_depth
from torch.distributions.uniform import Uniform
def load(model, marginalized=True):
model = model.lower()
if marginalized:
t = "marginalized"
else:
t = "not-marginalized"
mapping = {
"all": "models/4096/" + t + "/selu/*-batchnorm-0*/best-model.th",
"all-bn": "models/4096/" + t + "/selu/*-batchnorm-1*/best-model.th",
"mlp": "models/4096/" + t + "/selu/ratio-estimator-mlp-*-batchnorm-0*/best-model.th",
"mlp-bn": "models/4096/" + t + "/selu/ratio-estimator-mlp-*-batchnorm-1*/best-model.th",
"resnet-18": "models/4096/" + t + "/selu/ratio-estimator-resnet-18-*-batchnorm-0*/best-model.th",
"resnet-18-bn": "models/4096/" + t + "/selu/ratio-estimator-resnet-18-*-batchnorm-1*/best-model.th",
"resnet-50": "models/4096/" + t + "/selu/ratio-estimator-resnet-50-*-batchnorm-0*/best-model.th",
"resnet-50-bn": "models/4096/" + t + "/selu/ratio-estimator-resnet-50-*-batchnorm-1*/best-model.th"}
if model not in mapping.keys():
raise ValueError("Unknown model!")
return load_ratio_estimator(mapping[model])
@torch.no_grad()
def MarginalizedAgePrior():
lower = torch.tensor(1).float()
lower = lower.to(hypothesis.accelerator)
upper = torch.tensor(50.01).float()
upper = upper.to(hypothesis.accelerator)
return Uniform(lower, upper)
@torch.no_grad()
def Prior():
lower = torch.tensor([1, 3]).float()
lower = lower.to(hypothesis.accelerator)
upper = torch.tensor([50.01, 7]).float()
upper = upper.to(hypothesis.accelerator)
return Uniform(lower, upper)
def load_activation(activation):
activations = {
"elu": torch.nn.ELU,
"leakyrelu": torch.nn.LeakyReLU,
"prelu": torch.nn.PReLU,
"relu": torch.nn.ReLU,
"prelu": torch.nn.PReLU,
"selu": torch.nn.SELU,
"tanh": torch.nn.Tanh}
if activation not in activations.keys():
raise ValueError("Activation", activation, "is not available.")
return activations[activation]
def load_ratio_estimator(path, normalize_inputs=False):
if '*' in path:
estimator = load_ensemble_ratio_estimator(path, normalize_inputs)
else:
estimator = load_single_ratio_estimator(path, normalize_inputs)
# Move to the default Hypothesis accelerator
estimator.to(hypothesis.accelerator)
estimator.eval()
return estimator
def load_ensemble_ratio_estimator(query, normalize_inputs=False):
paths = glob.glob(query)
estimators = []
for path in paths:
estimators.append(load_single_ratio_estimator(path, normalize_inputs))
if(len(estimators) == 0):
raise ValueError("No ratio estimators found! Verify the specified path.")
return RatioEstimatorEnsemble(estimators)
def load_single_ratio_estimator(path, normalize_inputs=False):
# Check if the path exists.
if not os.path.exists(path):
raise ValueError("Path " + path + " does not exist.")
weights = torch.load(path)
dirname = os.path.dirname(path)
segments = path.split('/')
# Check what activation to use
activation = load_activation(path.split('/')[-3])
segments = dirname.split('-')
# Extract the dropout setting
index = segments.index("dropout")
dropout = float(segments[index + 1])
# Extract the batch normalization setting
index = segments.index("batchnorm")
batchnorm = bool(int(segments[index + 1]))
# Check if it's the marginalized model.
if "not-marginalized" in path:
inputs_dim = 2
else:
inputs_dim = 1
# Extract the ResNet depth configuration
try:
index = segments.index("resnet")
depth = int(segments[index + 1])
mlp = False
except:
mlp = True
# Load the MLP
if not mlp:
# Allocate the ratio estimator
ratio_estimator = RatioEstimator(
activation=activation,
batchnorm=batchnorm,
depth=depth,
dim_inputs=inputs_dim,
dropout=dropout,
normalize_inputs=normalize_inputs)
# Backward compatibility
if "_normalizer.weight" in weights.keys():
weights["bn_inputs.weight"] = weights["_normalizer.weight"]
del weights["_normalizer.weight"]
weights["bn_inputs.bias"] = weights["_normalizer.bias"]
del weights["_normalizer.bias"]
weights["bn_inputs.running_mean"] = weights["_normalizer.running_mean"]
del weights["_normalizer.running_mean"]
weights["bn_inputs.running_var"] = weights["_normalizer.running_var"]
del weights["_normalizer.running_var"]
weights["bn_inputs.num_batches_tracked"] = weights["_normalizer.num_batches_tracked"]
del weights["_normalizer.num_batches_tracked"]
else:
ratio_estimator = MLPRatioEstimator(
activation=activation,
batchnorm=batchnorm,
dim_inputs=inputs_dim,
dropout=dropout,
normalize_inputs=normalize_inputs)
ratio_estimator.load_state_dict(weights)
ratio_estimator = ratio_estimator.eval()
return ratio_estimator
def download(id, destination="."):
r"""Adapted from:
https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url
"""
URL = "https://docs.google.com/uc?export=download"
session = requests.Session()
response = session.get(URL, params = { 'id' : id }, stream = True)
token = get_confirm_token(response)
if token:
params = { 'id' : id, 'confirm' : token }
response = session.get(URL, params = params, stream = True)
save_response_content(response, destination)
def get_confirm_token(response):
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
def save_response_content(response, destination):
CHUNK_SIZE = 32768
with open(destination, "wb") as f:
for chunk in response.iter_content(CHUNK_SIZE):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
| 33.702564
| 108
| 0.661442
|
03151313d36dc16786262a19de70bb1e6cb170b9
| 2,950
|
lua
|
Lua
|
scripts/BACH-JP/c101107010.lua
|
MisterKay7/ygopro-pre-script
|
a2aac1ae52c584c5ed0b28ad28b89b85e8a88540
|
[
"Unlicense"
] | null | null | null |
scripts/BACH-JP/c101107010.lua
|
MisterKay7/ygopro-pre-script
|
a2aac1ae52c584c5ed0b28ad28b89b85e8a88540
|
[
"Unlicense"
] | null | null | null |
scripts/BACH-JP/c101107010.lua
|
MisterKay7/ygopro-pre-script
|
a2aac1ae52c584c5ed0b28ad28b89b85e8a88540
|
[
"Unlicense"
] | null | null | null |
--ダイノルフィア・ディプロス
--
--Script by Trishula9
function c101107010.initial_effect(c)
--to grave
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOGRAVE+CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCountLimit(1,101107010)
e1:SetTarget(c101107010.tgtg)
e1:SetOperation(c101107010.tgop)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_DESTROYED)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCountLimit(1,101107010+100)
e3:SetCondition(c101107010.spcon)
e3:SetCost(c101107010.spcost)
e3:SetTarget(c101107010.sptg)
e3:SetOperation(c101107010.spop)
c:RegisterEffect(e3)
end
function c101107010.tgfilter(c)
return c:IsSetCard(0x273) and c:IsAbleToGrave()
end
function c101107010.tgtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c101107010.tgfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_GRAVE)
if Duel.GetLP(tp)<=2000 then
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500)
end
end
function c101107010.tgop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c101107010.tgfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 and Duel.SendtoGrave(g,REASON_EFFECT)~=0 and Duel.GetLP(tp)<=2000 then
Duel.BreakEffect()
Duel.Damage(1-tp,500,REASON_EFFECT)
end
end
function c101107010.spcon(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,REASON_EFFECT+REASON_BATTLE)~=0
end
function c101107010.costfilter(c)
return c:IsType(TYPE_TRAP) and c:IsAbleToRemoveAsCost()
end
function c101107010.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c101107010.costfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c101107010.costfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c101107010.spfilter(c,e,tp)
return c:IsSetCard(0x273) and not c:IsCode(101107010) and c:IsLevelBelow(4) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c101107010.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c101107010.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE)
end
function c101107010.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c101107010.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| 38.311688
| 125
| 0.804746
|
79cfeb17b19647d0384ccbbb4d14c294dc390707
| 294
|
php
|
PHP
|
application/index/validate/StockOrderValidate.php
|
levislin2016/power
|
dd5dbeb96c8bf6c53b19bc58c058f568a1bba254
|
[
"Apache-2.0"
] | null | null | null |
application/index/validate/StockOrderValidate.php
|
levislin2016/power
|
dd5dbeb96c8bf6c53b19bc58c058f568a1bba254
|
[
"Apache-2.0"
] | 3
|
2019-06-13T02:21:21.000Z
|
2019-09-02T02:10:51.000Z
|
application/index/validate/StockOrderValidate.php
|
levislin2016/power
|
dd5dbeb96c8bf6c53b19bc58c058f568a1bba254
|
[
"Apache-2.0"
] | null | null | null |
<?php
namespace app\index\validate;
class StockOrderValidate extends BaseValidate
{
protected $rule = [
'stock_id' => 'isNotEmpty|isPositiveInteger',
'project_id' => 'isNotEmpty|isPositiveInteger',
'note' => 'ok',
'info' => 'isNotEmpty'
];
}
| 21
| 55
| 0.595238
|
23c432eded9ee5ccd6ee0bcb378bae6f34e9ce84
| 140
|
js
|
JavaScript
|
docs/_next/static/Wr68OhD8pY7PvbQVxQsm7/_buildManifest.js
|
PSniezak/resume
|
ad9cc1361b603b573b956bfd40f354e0d45b0e44
|
[
"MIT"
] | null | null | null |
docs/_next/static/Wr68OhD8pY7PvbQVxQsm7/_buildManifest.js
|
PSniezak/resume
|
ad9cc1361b603b573b956bfd40f354e0d45b0e44
|
[
"MIT"
] | null | null | null |
docs/_next/static/Wr68OhD8pY7PvbQVxQsm7/_buildManifest.js
|
PSniezak/resume
|
ad9cc1361b603b573b956bfd40f354e0d45b0e44
|
[
"MIT"
] | null | null | null |
self.__BUILD_MANIFEST = {"/[lang]":["static\u002Fcss\u002Fbbea1f84b38af3eeb955.css"]};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()
| 140
| 140
| 0.8
|
c3fb42714fefe3badf0b79a18324bd5419dbcc66
| 1,053
|
swift
|
Swift
|
Play-with-Swift-2-master/22-Memory-Management/03-2-Use-weak.playground/Contents.swift
|
ZhaoBingDong/PlayWithSwift
|
60b86404eb018482f76b4b5138e1b5bce6a30545
|
[
"Apache-2.0"
] | 1
|
2019-03-21T03:18:37.000Z
|
2019-03-21T03:18:37.000Z
|
Play-with-Swift-2-master/22-Memory-Management/03-2-Use-weak.playground/Contents.swift
|
ZhaoBingDong/PlayWithSwift
|
60b86404eb018482f76b4b5138e1b5bce6a30545
|
[
"Apache-2.0"
] | null | null | null |
Play-with-Swift-2-master/22-Memory-Management/03-2-Use-weak.playground/Contents.swift
|
ZhaoBingDong/PlayWithSwift
|
60b86404eb018482f76b4b5138e1b5bce6a30545
|
[
"Apache-2.0"
] | null | null | null |
//: Playground - noun: a place where people can play
import UIKit
class Person{
var name: String
var apartment: Apartment?
init(name: String){
self.name = name
print("Person", name, "is initialized")
}
deinit{
print("Person", name, "is being deinitialized!")
}
}
class Apartment{
let name: String
// weak must be optional
// weak must be var, not let!
// Then, weak can be change to nil
// can be !
weak var tenant: Person?
init(name: String){
self.name = name
print("Apartment", name, "is initialized!")
}
deinit{
print("Apartment", name, "is being deinitialized!")
}
}
var liuyubobobo: Person? = Person(name: "liuyubobobo")
var imoocApartment: Apartment? = Apartment(name: "imooc Apartment")
liuyubobobo!.apartment = imoocApartment
imoocApartment!.tenant = liuyubobobo
//imoocApartment = nil
//liuyubobobo = nil
liuyubobobo = nil
imoocApartment?.tenant //nil
imoocApartment = nil
// 两种顺序内存都能够正确释放
| 18.473684
| 67
| 0.625831
|
e26638fef8d9b03ae1dd53b117483eb14344104e
| 4,859
|
py
|
Python
|
pincer/objects/guild/member.py
|
DamnikB/Pincer
|
d2b1e22d49a528d59c3e912ddbd4735d9d5a3ef9
|
[
"MIT"
] | 1
|
2021-12-24T07:08:09.000Z
|
2021-12-24T07:08:09.000Z
|
pincer/objects/guild/member.py
|
DamnikB/Pincer
|
d2b1e22d49a528d59c3e912ddbd4735d9d5a3ef9
|
[
"MIT"
] | null | null | null |
pincer/objects/guild/member.py
|
DamnikB/Pincer
|
d2b1e22d49a528d59c3e912ddbd4735d9d5a3ef9
|
[
"MIT"
] | null | null | null |
# Copyright Pincer 2021-Present
# Full MIT License can be found in `LICENSE` at the project root.
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from ..user.user import User
from ...utils.api_object import APIObject
from ...utils.conversion import construct_client_dict
from ...utils.snowflake import Snowflake
from ...utils.timestamp import Timestamp
from ...utils.types import MISSING
if TYPE_CHECKING:
from typing import List, Optional
from ...client import Client
from ...utils.types import APINullable
@dataclass(repr=False)
class BaseMember(APIObject):
"""Represents the base of a guild member.
Attributes
----------
deaf: :class:`bool`
Whether the user is deafened in voice channels
joined_at: :class:`~pincer.utils.timestamp.Timestamp`
Then the user joined the guild
mute: :class:`bool`
Whether the user is muted in voice channels
roles: List[:class:`~pincer.utils.snowflake.Snowflake`]
Array of role object ids
hoisted_role: APINullable[:class:`~pincer.utils.snowflake.Snowflake`]
The user's top role in the guild.
"""
joined_at: APINullable[Timestamp] = MISSING
roles: APINullable[List[Snowflake]] = MISSING
deaf: bool = MISSING
mute: bool = MISSING
hoisted_role: APINullable[Snowflake] = MISSING
@dataclass(repr=False)
class PartialGuildMember(APIObject):
"""Represents a partial guild member.
This is a reference to a member from a guild which does not contain
all information.
This gets used in form example message mentions.
Attributes
----------
id: :class:`~pincer.utils.snowflake.Snowflake`
The user's id
username: :class:`str`
The user's username, not unique across the platform
discriminator: :class:`str`
The user's 4-digit discord-tag
avatar: :class:`str`
The user's avatar hash
public_flags: :class:`int`
The flags on a user's account
member: :class:`~pincer.objects.guild.member.BaseMember`
The user their (partial) guild information.
"""
id: Snowflake
username: str
discriminator: str
avatar: str
public_flags: int
member: Optional[BaseMember]
@dataclass(repr=False)
class GuildMember(BaseMember, User, APIObject):
"""Represents a member which resides in a guild/server.
Attributes
----------
nick: APINullable[Optional[:class:`str`]]
This users guild nickname
pending: APINullable[:class:`bool`]
Whether the user has not yet passed the guild's Membership
Screening requirements
is_pending: APINullable[:class:`bool`]
Deprecated version of pending.
permissions: APINullable[:class:`str`]
Total permissions of the member in the channel,
including overwrites, returned when in the interaction object
premium_since: APINullable[Optional[:class:`~pincer.utils.timestamp.Timestamp`]]
When the user started boosting the guild
user: APINullable[:class:`~pincer.objects.user.user.User`]
The user this guild member represents
avatar: APINullable[:class:`str`]
The user's avatar.
communication_disabled_until: APINullable[Optional[:class:`~pincer.utils.timestamp.Timestamp`]]
The timestamp at which the user is no longer timed out.
.. note::
This may be in the past if the user has been timed out recently.
""" # noqa: E501
nick: APINullable[Optional[str]] = MISSING
pending: APINullable[bool] = MISSING
is_pending: APINullable[bool] = MISSING
permissions: APINullable[str] = MISSING
premium_since: APINullable[Optional[Timestamp]] = MISSING
user: APINullable[User] = MISSING
avatar: APINullable[str] = MISSING
communication_disabled_until: APINullable[Optional[Timestamp]] = MISSING
def __post_init__(self):
super().__post_init__()
if self.user is not MISSING:
self.set_user_data(self.user)
def set_user_data(self, user: User):
"""
Used to set the user parameters of a GuildMember instance
user: APINullable[:class:`~pincer.objects.user.user.User`]
A user class to copy the fields from
"""
# Inspired from this thread
# https://stackoverflow.com/questions/57962873/easiest-way-to-copy-all-fields-from-one-dataclass-instance-to-another
for key, value in user.__dict__.items():
setattr(self, key, value)
self.user = MISSING
@classmethod
async def from_id(
cls,
client: Client,
guild_id: int,
user_id: int
) -> GuildMember:
data = await client.http.get(f"guilds/{guild_id}/members/{user_id}")
return cls.from_dict(construct_client_dict(client, data))
| 32.393333
| 124
| 0.679358
|
32136fe52ec780290b4f84219d8941a4af67682a
| 1,688
|
dart
|
Dart
|
lib/core/services/ledgerparty.dart
|
phamquocduy1110/Flutter-based-template-for-a-business-assistant-application
|
0b7a585aced9e7e0a179969f7c980c2152c2c14f
|
[
"MIT"
] | 8
|
2021-11-09T06:57:38.000Z
|
2022-03-07T17:44:28.000Z
|
lib/core/services/ledgerparty.dart
|
zephcod/GJAM-ASSIST
|
a902cd5376226e7713046b4c27b9af4894aade98
|
[
"MIT"
] | 1
|
2021-12-27T10:37:23.000Z
|
2021-12-27T10:37:23.000Z
|
lib/core/services/ledgerparty.dart
|
zephcod/GJAM-ASSIST
|
a902cd5376226e7713046b4c27b9af4894aade98
|
[
"MIT"
] | 9
|
2021-11-09T06:57:41.000Z
|
2022-03-30T18:34:56.000Z
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:tall/core/models/ledgerparty.dart';
class LedgerPartyService {
final String uid;
final String voucherId;
LedgerPartyService({this.uid, this.voucherId});
final CollectionReference companyCollection =
Firestore.instance.collection('company');
Stream<List<LedgerParty>> get voucherLedgerData {
return companyCollection
.document(this.uid)
.collection('ledger_entries')
.where('restat_voucher_master_id', isEqualTo: voucherId)
.snapshots()
.map(_voucherLedgerData);
}
List<LedgerParty> _voucherLedgerData(QuerySnapshot snapshot) {
return snapshot.documents.map((doc) {
return LedgerParty(
amount: doc.data['amount'].toDouble() ?? 0,
isDeemedPositive: doc.data['isdeemedpositive'].toString() ?? '',
isPartyLedger: doc.data['ispartyledger'].toString() ?? '',
ledgerGuid: doc.data['ledger_guid'].toString() ?? '',
ledgerMasterId: doc.data['ledgername'].toString() ?? '',
ledgerRefMasterId: doc.data['ledgerrefname'].toString() ?? '',
// primaryVoucherType:
// doc.data['primary_voucher_type_name'].toString() ?? '',
primaryGroup: doc.data['primarygroup'].toString() ?? '',
ledgerName: doc.data['restat_ledger_name'].toString() ?? '',
ledgerRefName: doc.data['restat_ledger_ref_name'].toString() ?? '',
partyName: doc.data['restat_party_ledger_name'].toString() ?? '',
date: doc.data['restat_voucher_date'].toDate() ?? null,
voucherMasterID: doc.data['restat_voucher_master_id'].toString() ?? '',
);
}).toList();
}
}
| 38.363636
| 79
| 0.65936
|
a9e3a446a0ef3c4932a9536038f9659092e9dbfb
| 748
|
asm
|
Assembly
|
programs/oeis/185/A185706.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | 1
|
2021-03-15T11:38:20.000Z
|
2021-03-15T11:38:20.000Z
|
programs/oeis/185/A185706.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | null | null | null |
programs/oeis/185/A185706.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | null | null | null |
; A185706: Characteristic function of positive numbers that are primes ending in 3.
; 0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
mov $1,$0
add $1,1
cal $0,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
mul $1,$0
mov $0,5
mov $2,$1
sub $2,3
gcd $0,$2
mov $1,$0
div $1,4
| 53.428571
| 501
| 0.558824
|
9848424dca7d7aad4346e0f8cf1a5ed561344d38
| 2,026
|
go
|
Go
|
internal/handlers/initrd.go
|
adriengentil/assisted-image-service
|
d67d761513d06f2d3ca95de35176e3c66c0ab00b
|
[
"Apache-2.0"
] | null | null | null |
internal/handlers/initrd.go
|
adriengentil/assisted-image-service
|
d67d761513d06f2d3ca95de35176e3c66c0ab00b
|
[
"Apache-2.0"
] | null | null | null |
internal/handlers/initrd.go
|
adriengentil/assisted-image-service
|
d67d761513d06f2d3ca95de35176e3c66c0ab00b
|
[
"Apache-2.0"
] | null | null | null |
package handlers
import (
"fmt"
"net/http"
"time"
"github.com/openshift/assisted-image-service/pkg/imagestore"
"github.com/openshift/assisted-image-service/pkg/isoeditor"
"github.com/openshift/assisted-image-service/pkg/overlay"
)
type initrdHandler struct {
ImageStore imagestore.ImageStore
client *AssistedServiceClient
}
var _ http.Handler = &initrdHandler{}
func (h *initrdHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
imageID, err := parseImageID(r.URL.Path)
if err != nil {
httpErrorf(w, http.StatusNotFound, "failed to parse image ID: %v\n", err)
return
}
version := r.URL.Query().Get("version")
if version == "" {
httpErrorf(w, http.StatusBadRequest, "'version' parameter required for initrd download")
return
}
arch := r.URL.Query().Get("arch")
if arch == "" {
arch = defaultArch
}
if !h.ImageStore.HaveVersion(version, arch) {
httpErrorf(w, http.StatusBadRequest, "version for %s %s, not found", version, arch)
return
}
isoPath := h.ImageStore.PathForParams(imagestore.ImageTypeFull, version, arch)
fsFile, err := isoeditor.GetFileFromISO(isoPath, "/images/pxeboot/initrd.img")
if err != nil {
httpErrorf(w, http.StatusInternalServerError, "failed to get base initrd: %v", err)
return
}
ignition, code, err := h.client.ignitionContent(r, imageID)
if err != nil {
httpErrorf(w, code, "Error retrieving ignition content: %v", err)
return
}
ignitionReader, err := ignition.Archive()
if err != nil {
httpErrorf(w, http.StatusInternalServerError, "Failed to create ignition archive: %v", err)
return
}
initrdReader, err := overlay.NewAppendReader(fsFile, ignitionReader)
if err != nil {
httpErrorf(w, http.StatusInternalServerError, "Failed to create append reader for initrd: %v", err)
return
}
defer initrdReader.Close()
fileName := fmt.Sprintf("%s-initrd.img", imageID)
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))
http.ServeContent(w, r, fileName, time.Now(), initrdReader)
}
| 27.753425
| 101
| 0.71767
|
fdaa69bb0bc5146243181eb19abc91cca48583a5
| 614
|
css
|
CSS
|
receiver/style.css
|
mixisLv/chromecast
|
fd107d58ce4dd628cdfd9a2ec22bf0293e9c6e67
|
[
"MIT"
] | null | null | null |
receiver/style.css
|
mixisLv/chromecast
|
fd107d58ce4dd628cdfd9a2ec22bf0293e9c6e67
|
[
"MIT"
] | null | null | null |
receiver/style.css
|
mixisLv/chromecast
|
fd107d58ce4dd628cdfd9a2ec22bf0293e9c6e67
|
[
"MIT"
] | null | null | null |
html, body {
width: 100%;
height: 100%;
overflow: hidden;
background: #404751;
color: #fff;
}
.logo {
display: inline-block;
width: 146px;
height: 120px;
background: url(chromecast-logo.svg);
background-size: 146px 120px;
margin-bottom: 40px;
}
.content {
text-align: center;
margin-top: 100px;
}
.iframe {
width: 100%;
height: 100%;
border: none;
position: absolute;
top: 0;
left: 0;
overflow: hidden;
}
.wrapper .iframe {
display: none;
}
.wrapper.casting .iframe {
display: block;
}
.wrapper.casting .details {
display: none;
}
.large {
font-size: 42px;
}
| 12.791667
| 39
| 0.63355
|
42ccf1c2d158ae847acaa94caf3feb0a7623c122
| 214
|
kt
|
Kotlin
|
hammer-adventure/src/main/kotlin/dev/vini2003/hammeradventure/common/util/extension/ServerCommandSourceExtension.kt
|
vini2003/Blade
|
2648af62a7682955c98f02d442ab86834b6a0ed0
|
[
"MIT"
] | 3
|
2020-08-12T10:33:15.000Z
|
2020-09-19T02:21:36.000Z
|
hammer-adventure/src/main/kotlin/dev/vini2003/hammeradventure/common/util/extension/ServerCommandSourceExtension.kt
|
vini2003/Blade
|
2648af62a7682955c98f02d442ab86834b6a0ed0
|
[
"MIT"
] | 3
|
2020-09-03T21:36:34.000Z
|
2020-09-16T15:07:34.000Z
|
hammer-adventure/src/main/kotlin/dev/vini2003/hammeradventure/common/util/extension/ServerCommandSourceExtension.kt
|
vini2003/Blade
|
2648af62a7682955c98f02d442ab86834b6a0ed0
|
[
"MIT"
] | null | null | null |
package dev.vini2003.hammeradventure.common.util.extension
import dev.vini2003.hammer.HA
import net.minecraft.server.command.ServerCommandSource
fun ServerCommandSource.audience() = HA.INSTANCE!!.audience(player)
| 35.666667
| 67
| 0.845794
|
0d3e8d1db05d210daba0404ddbacd82d3ed89af3
| 3,550
|
cs
|
C#
|
Anamnesis/Services/TerritoryService.cs
|
Packetdancer/Anamnesis
|
02feee3e1f329bcaf9ae816b6e42c96a6d5ee7b3
|
[
"MIT"
] | null | null | null |
Anamnesis/Services/TerritoryService.cs
|
Packetdancer/Anamnesis
|
02feee3e1f329bcaf9ae816b6e42c96a6d5ee7b3
|
[
"MIT"
] | null | null | null |
Anamnesis/Services/TerritoryService.cs
|
Packetdancer/Anamnesis
|
02feee3e1f329bcaf9ae816b6e42c96a6d5ee7b3
|
[
"MIT"
] | null | null | null |
// Concept Matrix 3.
// Licensed under the MIT license.
namespace Anamnesis
{
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Anamnesis.Core.Memory;
using Anamnesis.GameData;
using Anamnesis.Memory;
using Anamnesis.Services;
using PropertyChanged;
[AddINotifyPropertyChangedInterface]
[SuppressPropertyChangedWarnings]
public class TerritoryService : ServiceBase<TerritoryService>
{
private ushort currentWeatherId;
public int CurrentTerritoryId { get; private set; }
public string CurrentTerritoryName { get; private set; } = "Unknown";
public ITerritoryType? CurrentTerritory { get; private set; }
public ushort CurrentWeatherId
{
get
{
return this.currentWeatherId;
}
set
{
if (this.currentWeatherId == value)
return;
this.currentWeatherId = value;
this.CurrentWeather = null;
if (this.CurrentTerritory != null)
{
foreach (IWeather weather in this.CurrentTerritory.Weathers)
{
if (weather.WeatherId == value)
{
this.CurrentWeather = weather;
}
}
}
}
}
public IWeather? CurrentWeather { get; set; }
public static bool GetIsBarracks()
{
// Twin adder barracks = 534
// Immortal Flame barracks = 535
// Maelstrom barracks = 536
if (Instance.CurrentTerritoryId >= 534 && Instance.CurrentTerritoryId <= 536)
return true;
return false;
}
public override async Task Start()
{
await base.Start();
_ = Task.Run(this.Update);
this.PropertyChanged += this.OnThisPropertyChanged;
}
private async Task Update()
{
while (this.IsAlive)
{
await Task.Delay(10);
// Update territory
int newTerritoryId = MemoryService.Read<int>(AddressService.Territory);
if (newTerritoryId != this.CurrentTerritoryId)
{
this.CurrentTerritoryId = newTerritoryId;
if (GameDataService.Territories == null)
{
this.CurrentTerritoryName = $"Unkown ({this.CurrentTerritoryId})";
}
else
{
this.CurrentTerritory = GameDataService.Territories.Get(this.CurrentTerritoryId);
this.CurrentTerritoryName = this.CurrentTerritory?.Region + " - " + this.CurrentTerritory?.Place;
}
}
// Update weather
ushort weatherId;
if (GposeService.Instance.IsGpose)
{
weatherId = MemoryService.Read<ushort>(AddressService.GPoseWeather);
}
else
{
weatherId = MemoryService.Read<byte>(AddressService.Weather);
}
if (weatherId != this.CurrentWeatherId)
{
this.CurrentWeatherId = weatherId;
}
}
}
private void OnThisPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(TerritoryService.CurrentWeatherId))
{
ushort current;
if (GposeService.Instance.IsGpose)
{
current = MemoryService.Read<ushort>(AddressService.GPoseWeather);
if (current != this.CurrentWeatherId)
{
MemoryService.Write<ushort>(AddressService.GPoseWeather, this.CurrentWeatherId);
}
}
else
{
current = MemoryService.Read<byte>(AddressService.Weather);
if (current != this.CurrentWeatherId)
{
MemoryService.Write<byte>(AddressService.Weather, (byte)this.CurrentWeatherId);
}
}
}
else if (e.PropertyName == nameof(TerritoryService.CurrentWeather))
{
if (this.CurrentWeather == null)
return;
if (this.CurrentWeatherId == this.CurrentWeather.WeatherId)
return;
this.CurrentWeatherId = this.CurrentWeather.WeatherId;
}
}
}
}
| 23.355263
| 103
| 0.680563
|
45d8c330ea3479bc9b2ccc754b5d31165192b514
| 4,521
|
py
|
Python
|
tests/unit/test_odometry_helpers_unit.py
|
akhand9999/b2
|
1d3c8ac7fc31fac69c5e91bab01dd3f943dd6322
|
[
"MIT"
] | 2
|
2018-05-27T00:35:58.000Z
|
2020-03-27T08:18:46.000Z
|
b2_base/tests/unit/test_odometry_helpers_unit.py
|
sheaffej/b2-base
|
5e9ddc2db244d9c319e28aacfa10892dd0b7da01
|
[
"MIT"
] | 1
|
2020-05-27T13:27:48.000Z
|
2020-06-10T08:24:39.000Z
|
b2_base/tests/unit/test_odometry_helpers_unit.py
|
sheaffej/b2-base
|
5e9ddc2db244d9c319e28aacfa10892dd0b7da01
|
[
"MIT"
] | 2
|
2021-01-26T16:53:19.000Z
|
2021-02-06T18:16:31.000Z
|
import unittest
import math
from b2_logic.odometry_helpers import normalize_theta, calc_world_frame_pose, calc_steering_angle
PKG = 'b2'
NAME = 'b2_odom_helpers_unittest'
pi = math.pi
twopi = pi * 2
class TestOdometryHelpers(unittest.TestCase):
def setUp(self):
print()
def test_normalize_theta(self):
# (input_theta, exp_normal_theta)
tests = [
# Positive & Negatives
(pi, pi), # 180 = 180
(-pi, pi), # -180 = 180
(twopi, 0.0), # 360 = 0
(-twopi, 0.0), # -360 = 0
(0, 0), # 0 = 0
(pi/2 - pi, pi * 1.5), # -90 = 270
# More that 2 Pi cases
(twopi + pi, pi), # 3 pi = pi
(-twopi - pi, pi), # -3 pi = pi
(pi + pi * 1.5, pi/2) # 2.5 pi = 0.5 pi
]
for input_theta, exp_normal_theta in tests:
normal_theta = normalize_theta(input_theta)
print("Input theta: {}, actual: {}, expected: {}".format(
input_theta, normal_theta, exp_normal_theta))
self.assertAlmostEqual(normal_theta, exp_normal_theta, 3)
def test_calc_steering_angle(self):
# (current_heading, target_heading, exp_steering_angle)
tests = [
(pi/2, pi, pi/2), # 90 deg -> 180 deg = +90 deg
(pi/4, -pi/4, -pi/2), # 45 deg -> -45 deg = -90 deg
(1.1, 0.0, -1.1),
(twopi - 1.0, 0.0, 1.0),
(1.0, twopi - 1.0, -2.0),
]
for (current_heading, target_heading, exp_steering_angle) in tests:
steering_angle = calc_steering_angle(current_heading, target_heading)
print(
"Current heading: {}, Target heading: {} ==> "
"Steering angle actual: {}, expected: {}".format(
current_heading, target_heading, steering_angle, exp_steering_angle))
self.assertAlmostEqual(
steering_angle, exp_steering_angle, 3)
def test_calc_world_frame_pose(self):
"""Tests the odometry_helpers.calc_world_frame_pose() function.
Inputs: world x-y-theta velocities, and world starting coordinates, and duration
Outputs: new world x-y-theta pose
"""
tests = [
# (world_x_velocity, world_y_velocity, world_angular_velocity,
# begin_world_x, begin_world_y, begin_world_theta, time_delta_secs),
# ==> (new_world_x, new_world_y, new_world_theta)
# Drive straight forward at 0.5 m/s for 1 sec from origin
((0.5, 0.0, 0.0,
0.0, 0.0, 0.0, 1),
(0.5, 0.0, 0.0)),
# Rotate left at 1 r/s for 1 sec from origin
((0.0, 0.0, 1.0,
0.0, 0.0, 0.0, 1),
(0.0, 0.0, 1.0)),
# Rotate left at 3 r/s for 3 sec from origin
((0.0, 0.0, 3.0,
0.0, 0.0, 0.0, 3),
(0.0, 0.0, (3 * 3) % math.pi)),
# Rotate right at 1 r/s for 1 sec from origin
((0.0, 0.0, -1.0,
0.0, 0.0, 0.0, 1),
(0.0, 0.0, 5.28)),
# Drive x = 1.0 m/s, y = 1.0ms/s and rotation 1.0 r/s for 1 sec
# from the origin and 0.0 heading
((1.0, 1.0, 1.0,
0.0, 0.0, 0.0, 1),
(1.0, 1.0, 1.0)),
# Drive x = 1.0 m/s, y = 1.0ms/s and rotation 1.0 r/s for 1 sec
# from the location (-123, 345) heading = 4 radians
((1.0, 1.0, 1.0,
-123.0, 345.0, 4.0, 1),
(-122.0, 346.0, 5.0)),
]
for inputs, expects in tests:
(world_x_velocity, world_y_velocity, world_angular_velocity,
begin_world_x, begin_world_y, begin_world_theta, time_delta_secs) = inputs
exp_world_x, exp_world_y, exp_world_theta = expects
new_world_x, new_world_y, new_world_theta = calc_world_frame_pose(
world_x_velocity, world_y_velocity, world_angular_velocity,
begin_world_x, begin_world_y, begin_world_theta,
time_delta_secs
)
self.assertAlmostEqual(new_world_x, exp_world_x, places=2)
self.assertAlmostEqual(new_world_y, exp_world_y, places=2)
self.assertAlmostEqual(new_world_theta, exp_world_theta, places=2)
if __name__ == "__main__":
import rosunit
rosunit.unitrun(PKG, NAME, TestOdometryHelpers)
| 36.756098
| 97
| 0.52975
|
e71982781155c534d09d80d7164e3c99570668f1
| 360
|
php
|
PHP
|
app/Http/Controllers/Auth/RegularLoginController.php
|
folayarn/Sport
|
557ce51b53cf09d3f0e1f57a081aa5f4fd128559
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/Auth/RegularLoginController.php
|
folayarn/Sport
|
557ce51b53cf09d3f0e1f57a081aa5f4fd128559
|
[
"MIT"
] | 1
|
2020-06-15T11:43:34.000Z
|
2020-06-15T11:43:34.000Z
|
app/Http/Controllers/Auth/RegularLoginController.php
|
folayarn/Sport
|
557ce51b53cf09d3f0e1f57a081aa5f4fd128559
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class RegularLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:regular');
}
public function showLoginForm(){
return view('auth.regular');
}
public function login(){
}
}
| 13.333333
| 47
| 0.697222
|
e2e22c5be491570581b1f1a99a3a5dc847aecb55
| 1,807
|
py
|
Python
|
Pong.py
|
PythonMHGit/Ping-Pong
|
682d9846998ae081f6e7312cd82a5a81a3a6994d
|
[
"CC0-1.0"
] | null | null | null |
Pong.py
|
PythonMHGit/Ping-Pong
|
682d9846998ae081f6e7312cd82a5a81a3a6994d
|
[
"CC0-1.0"
] | null | null | null |
Pong.py
|
PythonMHGit/Ping-Pong
|
682d9846998ae081f6e7312cd82a5a81a3a6994d
|
[
"CC0-1.0"
] | null | null | null |
#Importing Needed Stuff
from pygame import *
#framerate
clock = time.Clock()
FPS = 60
#Variables
running = True
paddle_width = 20
paddle_height = 80
#Game Window Set Up
win_width = 700
win_height = 500
window = display.set_mode((win_width, win_height))
#Classes
class GameSprite(sprite.Sprite):
def __init__(self, player_image, player_x, player_y, size_x, size_y, player_speed):
super().__init__()
self.image = transform.scale(image.load(player_image), (size_x, size_y))
self.speed = player_speed
self.rect = self.image.get_rect()
self.rect.x = player_x
self.rect.y = player_y
def reset(self):
window.blit(self.image, (self.rect.x, self.rect.y))
class LeftPlayer(GameSprite):
def update(self):
keys = key.get_pressed()
if keys[K_w] and self.rect.y > 0:
self.rect.y -= self.speed
if keys[K_s] and self.rect.y < win_height - paddle_height:
self.rect.y += self.speed
class RightPlayer(GameSprite):
def update(self):
pass
keys = key.get_pressed()
if keys[K_UP] and self.rect.y > 0:
self.rect.y -= self.speed
if keys[K_DOWN] and self.rect.y < win_height - paddle_height:
self.rect.y += self.speed
#Creating All Sprites
l_player = LeftPlayer("Paddle.png", 10, 0, paddle_width, paddle_height, 5)
r_player = RightPlayer("Paddle.png", win_width - paddle_width - 10, 0, paddle_width, paddle_height, 5)
#Game Loop
while running:
for e in event.get():
if e.type == QUIT:
running = False
window.fill((37, 150, 190))
l_player.update()
l_player.reset()
r_player.update()
r_player.reset()
display.update()
clock.tick(FPS)
| 28.234375
| 103
| 0.621472
|
b926c51647807a789304d30dd713aac2ea0790b1
| 670
|
rs
|
Rust
|
src/train/mod.rs
|
iduartgomez/tf-rs
|
faa9c126cd1b0b2c125b5f72fa4696e3322193b7
|
[
"Apache-2.0",
"MIT"
] | 31
|
2017-10-26T19:40:15.000Z
|
2021-01-13T15:51:34.000Z
|
src/train/mod.rs
|
iduartgomez/tf-rs
|
faa9c126cd1b0b2c125b5f72fa4696e3322193b7
|
[
"Apache-2.0",
"MIT"
] | 4
|
2017-10-16T16:53:18.000Z
|
2017-10-27T21:19:28.000Z
|
src/train/mod.rs
|
iduartgomez/tf-rs
|
faa9c126cd1b0b2c125b5f72fa4696e3322193b7
|
[
"Apache-2.0",
"MIT"
] | 4
|
2017-09-17T06:32:13.000Z
|
2018-05-29T11:37:17.000Z
|
//! Support for training models.
use super::*;
use super::framework::*;
use errors::*;
mod moving_averages;
mod slot_creator;
pub mod nn;
pub mod optimizers;
pub use self::moving_averages::*;
pub use self::slot_creator::*;
fn validate_convnet_data_dormat(data_format: &str) -> Result<&'static str> {
match data_format {
"NHWC" => Ok("NHWC"),
"NCHW" => Ok("NCHW"),
_ => Err(Error::from(ErrorKind::Stub)),
}
}
fn _validate_convnet_3d_data_dormat(data_format: &str) -> Result<&'static str> {
match data_format {
"NDHWC" => Ok("NDHWC"),
"NCDHW" => Ok("NCDHW"),
_ => Err(Error::from(ErrorKind::Stub)),
}
}
| 22.333333
| 80
| 0.614925
|
18929a7ff0e9fe58e6863b2cbee2d1d9de84422a
| 226
|
ts
|
TypeScript
|
packages/back-end/test/app.test.ts
|
epugh/growthbook
|
385d300c7efdac51b87159e63a94515c656a5b36
|
[
"MIT"
] | null | null | null |
packages/back-end/test/app.test.ts
|
epugh/growthbook
|
385d300c7efdac51b87159e63a94515c656a5b36
|
[
"MIT"
] | null | null | null |
packages/back-end/test/app.test.ts
|
epugh/growthbook
|
385d300c7efdac51b87159e63a94515c656a5b36
|
[
"MIT"
] | null | null | null |
import request from "supertest";
import app from "../src/app";
describe("api", () => {
it("should return 401 when hitting non-existing endpoint", (done) => {
request(app).get("/random-url").expect(401, done);
});
});
| 25.111111
| 72
| 0.628319
|
c8d649b9e184fe9a1e3b2936fcf3965351fe5359
| 1,766
|
dart
|
Dart
|
test/object_tests/structs_test.dart
|
DanTup/winmd
|
34e43abafc341814eec79fd81050e8f0fb52e0cc
|
[
"BSD-3-Clause"
] | 12
|
2021-01-24T21:08:41.000Z
|
2022-02-10T15:01:30.000Z
|
test/object_tests/structs_test.dart
|
DanTup/winmd
|
34e43abafc341814eec79fd81050e8f0fb52e0cc
|
[
"BSD-3-Clause"
] | 15
|
2021-02-10T13:44:36.000Z
|
2021-12-23T11:59:42.000Z
|
test/object_tests/structs_test.dart
|
DanTup/winmd
|
34e43abafc341814eec79fd81050e8f0fb52e0cc
|
[
"BSD-3-Clause"
] | 5
|
2021-02-11T00:43:32.000Z
|
2021-12-22T15:05:16.000Z
|
@TestOn('windows')
import 'package:test/test.dart';
import 'package:winmd/winmd.dart';
/// Exhaustively test a class representation.
void main() {
// .class public sequential ansi sealed beforefieldinit Windows.Win32.UI.WindowsAndMessaging.ACCEL
// extends [netstandard]System.ValueType
// {
// // Fields
// .field public uint8 fVirt
// .field public uint16 key
// .field public uint16 cmd
//
// } // end of class Windows.Win32.UI.WindowsAndMessaging.ACCEL
test('Windows.Win32.UI.WindowsAndMessaging.ACCEL', () {
final scope = MetadataStore.getWin32Scope();
final accel =
scope.findTypeDef('Windows.Win32.UI.WindowsAndMessaging.ACCEL')!;
expect(accel.isClass, isTrue);
expect(accel.typeVisibility, equals(TypeVisibility.public));
expect(accel.typeLayout, equals(TypeLayout.sequential));
expect(accel.stringFormat, equals(StringFormat.ansi));
expect(accel.isSealed, isTrue);
expect(accel.isBeforeFieldInit, isTrue);
expect(accel.name, equals('Windows.Win32.UI.WindowsAndMessaging.ACCEL'));
expect(accel.parent?.name, equals('System.ValueType'));
expect(accel.fields.length, equals(3));
expect(accel.fields[0].name, equals('fVirt'));
expect(accel.fields[0].typeIdentifier.baseType, equals(BaseType.Uint8));
expect(accel.fields[0].fieldAccess, equals(FieldAccess.public));
expect(accel.fields[1].name, equals('key'));
expect(accel.fields[1].typeIdentifier.baseType, equals(BaseType.Uint16));
expect(accel.fields[1].fieldAccess, equals(FieldAccess.public));
expect(accel.fields[2].name, equals('cmd'));
expect(accel.fields[2].typeIdentifier.baseType, equals(BaseType.Uint16));
expect(accel.fields[2].fieldAccess, equals(FieldAccess.public));
});
}
| 38.391304
| 100
| 0.719139
|
01b132844a0411821da9addcbb80ef005e799c6d
| 1,881
|
rs
|
Rust
|
src/lib.rs
|
mauro-balades/is-url
|
d3abf89792a62e3624c3ab3782b1f660ed4f44cb
|
[
"MIT"
] | 1
|
2022-02-11T22:25:06.000Z
|
2022-02-11T22:25:06.000Z
|
src/lib.rs
|
mauro-balades/is-url
|
d3abf89792a62e3624c3ab3782b1f660ed4f44cb
|
[
"MIT"
] | null | null | null |
src/lib.rs
|
mauro-balades/is-url
|
d3abf89792a62e3624c3ab3782b1f660ed4f44cb
|
[
"MIT"
] | null | null | null |
/*
| MIT License
|
| Copyright (c) 2022 Mauro Baladés
|
| Permission is hereby granted, free of charge, to any person obtaining a copy
| of this software and associated documentation files (the "Software"), to deal
| in the Software without restriction, including without limitation the rights
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
| copies of the Software, and to permit persons to whom the Software is
| furnished to do so, subject to the following conditions:
|
| The above copyright notice and this permission notice shall be included in all
| copies or substantial portions of the Software.
|
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
| SOFTWARE.
*/
#[macro_use]
extern crate lazy_static;
use regex::Regex;
const URL_REGEX: &str =
r"https?://(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)";
lazy_static! {
static ref RE: Regex = {
Regex::new(URL_REGEX).unwrap()
};
}
pub fn is_url(url: &str) -> bool {
return RE.is_match(url);
}
#[cfg(test)]
mod tests {
use crate::is_url;
#[test]
fn normal_url() {
assert!(is_url("https://hello.com"));
}
#[test]
fn url_path() {
assert!(is_url("https://hello.com/example"));
}
#[test]
fn url_section() {
assert!(is_url("https://hello.com#example"));
}
#[test]
fn url_arguments() {
assert!(is_url("https://hello.com?q=hello"));
}
}
| 28.074627
| 97
| 0.669856
|
e3fd2da74957656b33be374286e4a3d6772696e2
| 2,187
|
css
|
CSS
|
www/style.css
|
Masafuro/Mathcalator2
|
84b245c8ec13239ff9df825ef3f6f677d880bec1
|
[
"BSD-3-Clause"
] | null | null | null |
www/style.css
|
Masafuro/Mathcalator2
|
84b245c8ec13239ff9df825ef3f6f677d880bec1
|
[
"BSD-3-Clause"
] | null | null | null |
www/style.css
|
Masafuro/Mathcalator2
|
84b245c8ec13239ff9df825ef3f6f677d880bec1
|
[
"BSD-3-Clause"
] | null | null | null |
html{
height: 100%;
}
body {
background-color: #ffffff;
height:100%;
}
a {
color: currentColor;
text-decoration: none;
}
@font-face {
font-family: "rank";
src: url("font/Rabelo_Regular.ttf");
}
@font-face {
font-family: "key";
src: url("font/18holes.ttf");
}
@font-face {
font-family: "title";
src: url("font/ki_kokumin.ttf");
}
@font-face {
font-family: "kokugo";
src: url("font/ki_kokugo.ttf");
}
.app-title{
font-size: 3rem;
}
.title{
font-family: title;
color: #333333;
font-size: 1.2rem;
}
.Rank {
font-family: rank;
font-size: 2rem;
color: #FF0000;
}
.number{
font-family: key;
margin-left: auto;
margin-right: auto;
font-size: 4.5rem;
text-align: center;
}
.tenkey{
font-family: key;
margin-left: auto;
margin-right: auto;
font-size: 3.5rem;
text-align: center;
color: #333333;
}
.device{
}
.answer{
font-family: title;
color: #333333;
font-size: 2.3rem;
}
.answerbutton{
font-family: key;
font-size: 3rem;
margin-left: auto;
margin-right: auto;
text-align: center;
}
.question{
font-family: kokugo;
font-size: 1.5rem;
text-align: left;
margin-left: auto;
margin-right: auto;
}
.white{
color: white;
}
.p-mode{
background-color: #4a4e4f
}
.t-mode{
background-color: #ed1239
}
.n-mode{
background-color: #545454
}
.console {
border: 1px solid #666;
color: #FFFFFF;
text-shadow: 0px 0px 20px rgba(255,255,0,1);
background-color: #444444;
font-family: "MS ゴシック","Andale Mono",Courier,Monospace;
font-size: 1.2em;
line-height: 100%;
margin-bottom: 0.4em;
margin-left: auto;
margin-right: auto;
padding: 0.4em 0.4em;
white-space: pre;
height: 25%;
}
.console:after{
content:" _";
opacity: 0;
animation: cursor 1s infinite;
}
.app-content{
height: 100%;
}
/* console */
@keyframes cursor {
0% { opacity: 0; }
40% { opacity: 0; }
50% { opacity: 1; }
90% { opacity: 1; }
100% { opacity: 0; }
}
| 14.201299
| 59
| 0.55647
|
dddbcfd319534ea45d3a2127601262f37bab7bfd
| 214
|
java
|
Java
|
eadp-02-hundirlaflota/src/main/java/com/arteco/eadp/java/eadp/hundirlaflota/game/ImpactType.java
|
arteco/eadp-java
|
d992d5d7c2369461c614578a61838c5f0a46f72d
|
[
"Apache-2.0"
] | null | null | null |
eadp-02-hundirlaflota/src/main/java/com/arteco/eadp/java/eadp/hundirlaflota/game/ImpactType.java
|
arteco/eadp-java
|
d992d5d7c2369461c614578a61838c5f0a46f72d
|
[
"Apache-2.0"
] | 2
|
2020-04-23T21:05:18.000Z
|
2021-01-21T01:04:06.000Z
|
eadp-02-hundirlaflota/src/main/java/com/arteco/eadp/java/eadp/hundirlaflota/game/ImpactType.java
|
arteco/eadp-java
|
d992d5d7c2369461c614578a61838c5f0a46f72d
|
[
"Apache-2.0"
] | null | null | null |
package com.arteco.eadp.java.eadp.hundirlaflota.game;
/**
* Created by rarnau on 24/10/2019.
* Arteco Consulting SL.
* info@arteco-consulting.com
*/
public enum ImpactType {
WATER, TOUCHED, SUNKEN, OUT;
}
| 19.454545
| 53
| 0.71028
|
e733eb613a4685915d6c461ca32ab3d25f4cc615
| 4,075
|
php
|
PHP
|
donjo-app/views/web/artikel/widget-form.php
|
deanvhin2/KELURAHAN
|
e9e415dd728d4e2af2eb1251db0ca0a517cc3e4d
|
[
"Apache-2.0"
] | null | null | null |
donjo-app/views/web/artikel/widget-form.php
|
deanvhin2/KELURAHAN
|
e9e415dd728d4e2af2eb1251db0ca0a517cc3e4d
|
[
"Apache-2.0"
] | null | null | null |
donjo-app/views/web/artikel/widget-form.php
|
deanvhin2/KELURAHAN
|
e9e415dd728d4e2af2eb1251db0ca0a517cc3e4d
|
[
"Apache-2.0"
] | 2
|
2021-07-22T16:18:19.000Z
|
2021-07-22T17:18:56.000Z
|
<div class="content-wrapper">
<section class="content-header">
<h1>Pengaturan Widget</h1>
<ol class="breadcrumb">
<li><a href="<?= site_url('hom_sid')?>"><i class="fa fa-home"></i> Home</a></li>
<li><a href="<?= site_url('web_widget')?>"> Daftar Widget</a></li>
<li class="active">Pengaturan Widget</li>
</ol>
</section>
<section class="content" id="maincontent">
<form id="validasi" action="<?= $form_action?>" method="POST" enctype="multipart/form-data" class="form-horizontal">
<div class="row">
<div class="col-md-12">
<div class="box box-info">
<div class="box-header with-border">
<a href="<?= site_url("web_widget")?>" class="btn btn-social btn-flat btn-info btn-sm btn-sm visible-xs-block visible-sm-inline-block visible-md-inline-block visible-lg-inline-block" title="Tambah Artikel">
<i class="fa fa-arrow-circle-left "></i>Kembali ke Daftar Widget
</a>
</div>
<div class="box-body">
<div class="form-group">
<label class="col-sm-4 control-label" for="judul">Judul Widget</label>
<div class="col-sm-6">
<input id="judul" name="judul" class="form-control input-sm required" type="text" placeholder="Judul Widget" value="<?= $widget['judul']?>"></input>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="jenis">Jenis Widget</label>
<div class="col-sm-6">
<select id="jenis_widget" name="jenis_widget" class="form-control input-sm">
<option value="">-- Pilih Jenis Widget --</option>
<option value="2" <?php selected($widget['jenis_widget'], 2);?>>Statis</option>
<option value="3" <?php selected($widget['jenis_widget'], 3);?>>Dinamis</option>
</select>
</div>
</div>
<?php if ($widget['jenis_widget'] AND $widget['jenis_widget'] != 1 AND $widget['jenis_widget'] !=2) $dinamis = true; ?>
<div id="dinamis" class="form-group" <?php !$dinamis and print('style="display:none;"') ?>>
<label class="col-sm-4 control-label" for="alamat_kantor">Kode Widget</label>
<div class="col-sm-6">
<textarea style="resize:none;height:150px;" id="isi-dinamis" name="isi-dinamis" class="form-control input-sm" placeholder="Kode Widget"><?=$widget['isi']?></textarea>
</div>
</div>
<?php if ($widget['jenis_widget'] AND $widget['jenis_widget'] ==2) $statis = true; ?>
<div id="statis" class="form-group" <?php !$statis and print('style="display:none;"') ?>>
<label class="col-sm-4 control-label" for="isi-statis">Nama File Widget (.php)</label>
<div class="col-sm-6">
<?php if($list_widget):?>
<select id="isi-statis" name="isi-statis" class="form-control input-sm">
<option value="">-- Pilih Widget --</option>
<?php foreach ($list_widget as $list):?>
<option value="<?=$list?>" <?php selected($list, $widget['isi']); ?>><?=$list?></option>
<?php endforeach;?>
</select>
<?php else:?>
<span class="help-block"><code>Widget tidak tersedia atau sudah ditambahkan semua (desa/widgets atau desa/themes/nama_tema/widgets)</code></span>
<?php endif;?>
</div>
</div>
</div>
<div class='box-footer'>
<div class='col-xs-12'>
<button type='reset' class='btn btn-social btn-flat btn-danger btn-sm' ><i class='fa fa-times'></i> Batal</button>
<button type='submit' class='btn btn-social btn-flat btn-info btn-sm pull-right confirm'><i class='fa fa-check'></i> Simpan</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</section>
</div>
<script>
var elem = document.getElementById("jenis_widget");
elem.onchange = function()
{
var dinamis = document.getElementById("dinamis");
var statis = document.getElementById("statis");
dinamis.style.display = (this.value == "3") ? "block":"none";
statis.style.display = (this.value == "2") ? "block":"none";
};
</script>
| 47.941176
| 214
| 0.595583
|
4580677a1611f683f8752a69690787068fe7eb87
| 1,784
|
py
|
Python
|
spotilyzer/subcommands/csv/requests.py
|
conrad-mukai/spotilyzer
|
7d535bfcb46907a41794ef9fa18ada3b7931fa0a
|
[
"MIT"
] | null | null | null |
spotilyzer/subcommands/csv/requests.py
|
conrad-mukai/spotilyzer
|
7d535bfcb46907a41794ef9fa18ada3b7931fa0a
|
[
"MIT"
] | null | null | null |
spotilyzer/subcommands/csv/requests.py
|
conrad-mukai/spotilyzer
|
7d535bfcb46907a41794ef9fa18ada3b7931fa0a
|
[
"MIT"
] | null | null | null |
"""
spotilyzer requests CSV
"""
# system imports
import csv
# project imports
from ..json.requests import REQUESTS_KEY, POD_NAME_KEY, REPLICAS_KEY, \
CORE_LIMIT_KEY, MEM_LIMIT_KEY
# constants
_types = (str, int, float, float)
def load_requests(frequests):
"""
Load requests CSV file. Formatting checks are performed
:param frequests: path to CSV file.
:return: requests object
"""
request_list = []
with open(frequests, mode='r', encoding='utf-8-sig') as fobj:
reader = csv.reader(fobj)
header = reader.__next__()
_validate_header(header, frequests)
rowlen = len(header)
line = 2
for row in reader:
_validate_row(rowlen, row, frequests, line)
request = _get_request(rowlen, header, row, frequests, line)
request_list.append(request)
line += 1
_validate_pod_names(request_list, frequests)
return {REQUESTS_KEY: request_list}
def _validate_header(header, frequests):
if header != [POD_NAME_KEY, REPLICAS_KEY, CORE_LIMIT_KEY, MEM_LIMIT_KEY]:
raise SyntaxError(f"invalid header in {frequests}")
def _validate_row(rowlen, row, frequests, line):
if len(row) != rowlen:
raise SyntaxError("incorrect number of entries in "
f"{frequests}, line {line}")
def _get_request(rowlen, header, row, frequests, line):
try:
return {header[i]: _types[i](row[i]) for i in range(rowlen)}
except ValueError as err:
raise SyntaxError(f"invalid type in {frequests}, line {line}") from err
def _validate_pod_names(request_list, frequests):
if len(request_list) != len(set(r[POD_NAME_KEY] for r in request_list)):
raise SyntaxError(f"pod names in {frequests} are not unique")
| 30.237288
| 79
| 0.664798
|
c9fceeb37a0661ca2debdb837d1d959afd59a7d1
| 1,367
|
ts
|
TypeScript
|
FactoryMap.ts
|
BryceCicada/DefaultMap
|
5f0d47d058aee089b406b3bbb5b30adf8a7e3015
|
[
"MIT"
] | 5
|
2018-01-11T21:15:34.000Z
|
2022-02-03T11:25:01.000Z
|
FactoryMap.ts
|
BryceCicada/DefaultMap
|
5f0d47d058aee089b406b3bbb5b30adf8a7e3015
|
[
"MIT"
] | 1
|
2021-05-10T21:01:18.000Z
|
2021-05-10T21:01:18.000Z
|
FactoryMap.ts
|
BryceCicada/DefaultMap
|
5f0d47d058aee089b406b3bbb5b30adf8a7e3015
|
[
"MIT"
] | null | null | null |
export class FactoryMap<K, V> extends Map<K, V> {
private factory?: (k: K) => V;
public constructor(iterableOrDefaultValueFactory?: Iterable<[K, V]> | ((k: K) => V), defaultValueFactory?: (k: K) => V) {
const isFunctionOrUndefined = (f?: Iterable<[K, V]> | ((k: K) => V)): f is (((k: K) => V) | undefined) => iterableOrDefaultValueFactory === undefined || typeof iterableOrDefaultValueFactory === 'function';
if (isFunctionOrUndefined(iterableOrDefaultValueFactory)) {
if (iterableOrDefaultValueFactory && defaultValueFactory) {
throw new Error('Unexpected constructor params');
}
super();
this.factory = iterableOrDefaultValueFactory;
} else {
super(iterableOrDefaultValueFactory);
this.factory = defaultValueFactory;
}
}
public get(key: K, defaultValueFactory?: (k: K) => V): V;
public get(key: K, defaultValueFactory?: (k: K) => V | undefined): V | undefined {
let r = super.get(key);
if (r === undefined) {
if (defaultValueFactory) {
r = defaultValueFactory(key);
} else if (this.factory) {
r = this.factory(key);
}
if (r !== undefined) {
super.set(key, r);
}
}
return r;
}
}
| 39.057143
| 213
| 0.547184
|
ef49a7e630b500b34325577f3ce45c5856ca5fac
| 688
|
h
|
C
|
src/mirheo/core/walls/velocity_field/none.h
|
LMNS3d/Mirheo
|
e710291502eb3d1b4001e3811f7b7d105af82c86
|
[
"MIT"
] | null | null | null |
src/mirheo/core/walls/velocity_field/none.h
|
LMNS3d/Mirheo
|
e710291502eb3d1b4001e3811f7b7d105af82c86
|
[
"MIT"
] | null | null | null |
src/mirheo/core/walls/velocity_field/none.h
|
LMNS3d/Mirheo
|
e710291502eb3d1b4001e3811f7b7d105af82c86
|
[
"MIT"
] | 1
|
2021-07-14T13:24:05.000Z
|
2021-07-14T13:24:05.000Z
|
#pragma once
#include <mirheo/core/datatypes.h>
#include <mirheo/core/utils/cpu_gpu_defines.h>
namespace mirheo
{
/// Zero velocity field
class VelocityFieldNone
{
public:
/// to fit the interface
void setup(__UNUSED real t, __UNUSED DomainInfo domain)
{}
/// get a handler that can be used on device
const VelocityFieldNone& handler() const
{
return *this;
}
/** Evaluate the velocity field at a given position
\param [in] r The position in local coordinates
\return The velocity value
*/
__D__ inline real3 operator()(__UNUSED real3 r) const
{
return {0._r, 0._r, 0._r};
}
};
} // namespace mirheo
| 19.657143
| 59
| 0.648256
|
da297e83169caaaf300c4bee57bd3d4ba646e958
| 953
|
php
|
PHP
|
app/Imports/AssociationImport.php
|
NabeelYousafPasha/module-task-subtask-importer
|
83feb2d10f61a428acf79ba4fa08a15052db6e44
|
[
"MIT"
] | null | null | null |
app/Imports/AssociationImport.php
|
NabeelYousafPasha/module-task-subtask-importer
|
83feb2d10f61a428acf79ba4fa08a15052db6e44
|
[
"MIT"
] | null | null | null |
app/Imports/AssociationImport.php
|
NabeelYousafPasha/module-task-subtask-importer
|
83feb2d10f61a428acf79ba4fa08a15052db6e44
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class AssociationImport implements WithMultipleSheets
{
/**
* @param Collection $collection
*/
public function collection(Collection $collection)
{
//
}
/**
* @return array
*/
public function sheets(): array
{
return [
'Governance' => new ModuleTaskSubtaskImport(),
'Management' => new ModuleTaskSubtaskImport(),
'Business Model' => new ModuleTaskSubtaskImport(),
'Operations' => new ModuleTaskSubtaskImport(),
'Products' => new ModuleTaskSubtaskImport(),
'Technology' => new ModuleTaskSubtaskImport(),
'Stakeholders Relations' => new ModuleTaskSubtaskImport(),
'Human Capital' => new ModuleTaskSubtaskImport(),
];
}
}
| 26.472222
| 70
| 0.628541
|
7aef6e6b773045ce15504d6f0df5cfab38b0a5bf
| 226
|
cs
|
C#
|
src/Sfx.Templates/TextChunk.cs
|
scorredoira/Sfx.Templates
|
97b3cf50c894b60c7f09daa994a808cd919e80dc
|
[
"MIT"
] | 7
|
2015-01-15T20:26:05.000Z
|
2018-05-16T05:48:54.000Z
|
src/Sfx.Templates/TextChunk.cs
|
scorredoira/Sfx.Templates
|
97b3cf50c894b60c7f09daa994a808cd919e80dc
|
[
"MIT"
] | 1
|
2017-11-11T07:36:22.000Z
|
2017-11-11T07:45:44.000Z
|
src/Sfx.Templates/TextChunk.cs
|
scorredoira/Sfx.Templates
|
97b3cf50c894b60c7f09daa994a808cd919e80dc
|
[
"MIT"
] | 2
|
2018-05-16T05:48:58.000Z
|
2021-08-24T15:15:36.000Z
|
namespace Sfx.Templates
{
// Una cadena de texto
sealed class TextChunk : IRenderizable
{
public string Value { get; set; }
public void Render(RenderContext context)
{
context.Writer.Write (this.Value);
}
}
}
| 15.066667
| 43
| 0.690265
|
ef51f2e60865d051a70a0637f4fd3ebdfcc1d476
| 786
|
js
|
JavaScript
|
src/micro-frontend/parent-vue/src/main.js
|
littleLane/jagdrevier
|
550a7f218411ab22980d669455760d5d3afb0619
|
[
"MIT"
] | null | null | null |
src/micro-frontend/parent-vue/src/main.js
|
littleLane/jagdrevier
|
550a7f218411ab22980d669455760d5d3afb0619
|
[
"MIT"
] | 15
|
2020-08-31T15:24:13.000Z
|
2022-02-27T11:20:53.000Z
|
src/micro-frontend/parent-vue/src/main.js
|
littleLane/jagdrevier
|
550a7f218411ab22980d669455760d5d3afb0619
|
[
"MIT"
] | null | null | null |
import Vue from 'vue'
import { registerApplication, start } from 'single-spa'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
async function loadScript(url) {
return new Promise((resolve, reject) => {
const script = document.createElement('script')
script.src = url
script.onload = resolve
script.onerror = reject
document.body.appendChild(script)
})
}
registerApplication(
'singleVue',
async () => {
console.log('加载 Vue 子应用')
await loadScript('http://localhost:4004/js/chunk-vendors.js')
await loadScript('http://localhost:4004/js/app.js')
return window.singleVue
},
location => location.pathname.startsWith('/vue')
)
start()
new Vue({
router,
render: h => h(App)
}).$mount('#app')
| 20.684211
| 65
| 0.675573
|
50245a24a2383fb17fcef04c4a682e0509fafaa4
| 375
|
sql
|
SQL
|
db/layout/20-emails.sql
|
Qadra/cometh
|
db31cea3ae12a3ccc8049f3f2fb6ab3a49238aeb
|
[
"MIT"
] | null | null | null |
db/layout/20-emails.sql
|
Qadra/cometh
|
db31cea3ae12a3ccc8049f3f2fb6ab3a49238aeb
|
[
"MIT"
] | null | null | null |
db/layout/20-emails.sql
|
Qadra/cometh
|
db31cea3ae12a3ccc8049f3f2fb6ab3a49238aeb
|
[
"MIT"
] | null | null | null |
CREATE TABLE `emails` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(80) NOT NULL,
`user` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
KEY `user` (`user`),
CONSTRAINT `emails_ibfk_1` FOREIGN KEY (`user`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
| 37.5
| 112
| 0.677333
|
a3328518191084ba4d6c77d328ab49e2d0950329
| 881
|
h
|
C
|
Twitter-Dumped/7.51.5/t1/T1LiveEventAuthorAttributionTheme-Protocol.h
|
ichitaso/TwitterListEnabler
|
d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df
|
[
"MIT"
] | 1
|
2019-10-15T09:26:49.000Z
|
2019-10-15T09:26:49.000Z
|
Twitter-Dumped/7.60.6/T1LiveEventAuthorAttributionTheme-Protocol.h
|
ichitaso/TwitterListEnabler
|
d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df
|
[
"MIT"
] | null | null | null |
Twitter-Dumped/7.60.6/T1LiveEventAuthorAttributionTheme-Protocol.h
|
ichitaso/TwitterListEnabler
|
d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df
|
[
"MIT"
] | 1
|
2019-11-17T06:06:49.000Z
|
2019-11-17T06:06:49.000Z
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <T1Twitter/NSObject-Protocol.h>
@class T1AvatarImageView, TFNLayoutMetrics, UIColor, UIFont, UIImageView, UILabel, UIView;
@protocol T1LiveEventAuthorAttributionTheme <NSObject>
@property(readonly, copy, nonatomic) UIColor *authorUserHandleColor;
@property(readonly, copy, nonatomic) UIFont *authorUserHandleFont;
@property(readonly, copy, nonatomic) UIColor *authorUserFullnameColor;
@property(readonly, copy, nonatomic) UIFont *authorUserFullnameFont;
- (UIView *)viewContainingAvatarImageView:(T1AvatarImageView *)arg1 fullNameLabel:(UILabel *)arg2 verifiedIcon:(UIImageView *)arg3 handleLabel:(UILabel *)arg4;
- (double)avatarHeightWithLayoutMetrics:(TFNLayoutMetrics *)arg1;
@end
| 44.05
| 159
| 0.784336
|
df2257780b396d1eac80d0192411e8dd5a385bcc
| 397
|
sql
|
SQL
|
Kwc/News/Category/Directory/Update/34542.sql
|
yacon/koala-framework
|
2dae1d6e8e003c73bceaf4cb529c534282f4559d
|
[
"BSD-2-Clause"
] | 40
|
2015-01-16T13:37:56.000Z
|
2019-09-06T08:12:55.000Z
|
Kwc/News/Category/Directory/Update/34542.sql
|
yacon/koala-framework
|
2dae1d6e8e003c73bceaf4cb529c534282f4559d
|
[
"BSD-2-Clause"
] | 340
|
2015-01-07T09:48:38.000Z
|
2022-03-25T12:16:52.000Z
|
Kwc/News/Category/Directory/Update/34542.sql
|
yacon/koala-framework
|
2dae1d6e8e003c73bceaf4cb529c534282f4559d
|
[
"BSD-2-Clause"
] | 31
|
2015-03-22T14:18:27.000Z
|
2021-07-21T11:24:33.000Z
|
ALTER TABLE `kwc_news_to_categories` DROP FOREIGN KEY `kwc_news_to_categories_ibfk_1` ,
ADD FOREIGN KEY ( `news_id` ) REFERENCES `kwc_news` (
`id`
) ON DELETE CASCADE ON UPDATE CASCADE ;
ALTER TABLE `kwc_news_to_categories` DROP FOREIGN KEY `kwc_news_to_categories_ibfk_2` ,
ADD FOREIGN KEY ( `category_id` ) REFERENCES `kwc_directories_categories` (
`id`
) ON DELETE CASCADE ON UPDATE CASCADE ;
| 39.7
| 87
| 0.785894
|
bec0b6652b8ca71a623bd53efc913e5fa7b0ebb5
| 354
|
tsx
|
TypeScript
|
components/icon/search/search.tsx
|
The-End-Hero/strength-ui
|
a53a7d68656e321cde16eac909e12d56feb38815
|
[
"MIT"
] | null | null | null |
components/icon/search/search.tsx
|
The-End-Hero/strength-ui
|
a53a7d68656e321cde16eac909e12d56feb38815
|
[
"MIT"
] | null | null | null |
components/icon/search/search.tsx
|
The-End-Hero/strength-ui
|
a53a7d68656e321cde16eac909e12d56feb38815
|
[
"MIT"
] | null | null | null |
import React from "react";
const SEARCH_ICON = require("../../../static/images/other/search.svg");
const SEARCH = "SEARCH";
function SearchIcon(props: any) {
const { style, className } = props;
return (
<img src={SEARCH_ICON} className={`${className ? className : ""}`} alt={SEARCH}
style={style}/>
);
}
export default SearchIcon;
| 22.125
| 83
| 0.644068
|
b9677d80bbf2ef7a32537d74e9b5a225316b841f
| 1,212
|
css
|
CSS
|
services/ogame_php/src2/css/admin/chatbrowser_body.css
|
0z-cloud/vx
|
dd0d0a4caed66cc740a8ed053a63a72f17f24091
|
[
"MIT"
] | 14
|
2020-11-18T21:23:05.000Z
|
2022-01-26T15:28:52.000Z
|
services/ogame_php/src2/css/admin/chatbrowser_body.css
|
0z-cloud/vx
|
dd0d0a4caed66cc740a8ed053a63a72f17f24091
|
[
"MIT"
] | 8
|
2021-04-22T13:53:24.000Z
|
2021-08-18T02:59:23.000Z
|
services/ogame_php/src2/css/admin/chatbrowser_body.css
|
0z-cloud/vx
|
dd0d0a4caed66cc740a8ed053a63a72f17f24091
|
[
"MIT"
] | 2
|
2021-04-24T21:53:41.000Z
|
2021-08-30T11:38:39.000Z
|
/* Pagination */
.mr_20 {
margin-right: 20px;
}
.fatB {
font-weight: 700;
}
.pagin {
border: 1px solid #415680;
padding: 4px 5px;
}
.pagination {
padding: 7px;
}
/* Buttons */
.delID {
line-height: 12px;
background: url('../../../images/delete.png') no-repeat 0px 2px;
padding-left: 12px;
cursor: pointer;
}
/* Page */
.hide {
display: none;
}
.button {
font-weight: 700;
padding: 2px 10px;
}
.checkBox {
width: 25px;
}
.msgUser {
padding: 3px 5px;
text-align: right;
width: 1px;
}
.msgText {
text-align: left;
font-weight: normal;
padding: 3px 5px;
}
.msgDate {
padding: 3px 5px;
text-align: right;
width: 200px;
}
#Messages > tr > th:nth-child(5) {
width: 50px;
}
#Messages > tr:nth-child(odd) > th {
background-color: #3D5076;
border-color: #496392;
}
.msgHighlight > th {
background-color: #4E6797 !important;
border-color: #607BAF !important;
}
/* User Colors */
.usrColor_0 {color: #BFBFBF;}
.usrColor_20 {color: lime;}
.usrColor_50 {color: lime;}
.usrColor_70 {color: skyblue;}
.usrColor_90 {color: orange;}
.usrColor_100 {color: orange;}
.usrColor_110 {color: red;}
.usrColor_120 {color: red;}
| 17.314286
| 68
| 0.614686
|
26907b534fd1f48ef32dfb0a0042b7b96fc1587e
| 8,802
|
rs
|
Rust
|
src/core/math/dot_ndarray.rs
|
cgubbin/conflux
|
9c96256ba6aba9bcff92ff37a88b07805bd7687d
|
[
"MIT"
] | 1
|
2021-12-25T03:17:37.000Z
|
2021-12-25T03:17:37.000Z
|
src/core/math/dot_ndarray.rs
|
cgubbin/conflux
|
9c96256ba6aba9bcff92ff37a88b07805bd7687d
|
[
"MIT"
] | null | null | null |
src/core/math/dot_ndarray.rs
|
cgubbin/conflux
|
9c96256ba6aba9bcff92ff37a88b07805bd7687d
|
[
"MIT"
] | null | null | null |
use crate::core::math::FPDot;
use ndarray::{Array1, Array2};
macro_rules! make_dot {
($t:ty) => {
impl FPDot<Array1<$t>, $t> for Array1<$t> {
#[inline]
fn dot(&self, other: &Array1<$t>) -> $t {
ndarray::Array1::dot(self, other)
}
}
impl FPDot<$t, Array1<$t>> for Array1<$t> {
#[inline]
fn dot(&self, other: &$t) -> Array1<$t> {
*other * self
}
}
impl<'a> FPDot<Array1<$t>, Array1<$t>> for $t {
#[inline]
fn dot(&self, other: &Array1<$t>) -> Array1<$t> {
other * *self
}
}
impl FPDot<Array2<$t>, Array1<$t>> for Array1<$t> {
#[inline]
fn dot(&self, other: &Array2<$t>) -> Array1<$t> {
self.dot(other)
}
}
impl FPDot<Array1<$t>, Array2<$t>> for Array1<$t> {
#[inline]
fn dot(&self, other: &Array1<$t>) -> Array2<$t> {
let mut out = Array2::zeros((self.len(), other.len()));
for i in 0..self.len() {
for j in 0..other.len() {
out[(i, j)] = self[i] * other[j];
}
}
out
}
}
impl FPDot<Array1<$t>, Array1<$t>> for Array2<$t> {
#[inline]
fn dot(&self, other: &Array1<$t>) -> Array1<$t> {
ndarray::Array2::dot(self, other)
}
}
impl FPDot<Array2<$t>, Array2<$t>> for Array2<$t> {
#[inline]
fn dot(&self, other: &Array2<$t>) -> Array2<$t> {
ndarray::Array2::dot(self, other)
}
}
impl FPDot<$t, Array2<$t>> for Array2<$t> {
#[inline]
fn dot(&self, other: &$t) -> Array2<$t> {
*other * self
}
}
impl<'a> FPDot<Array2<$t>, Array2<$t>> for $t {
#[inline]
fn dot(&self, other: &Array2<$t>) -> Array2<$t> {
other * *self
}
}
};
}
make_dot!(i8);
make_dot!(u8);
make_dot!(i16);
make_dot!(u16);
make_dot!(i32);
make_dot!(u32);
make_dot!(i64);
make_dot!(u64);
make_dot!(f32);
make_dot!(f64);
#[cfg(test)]
mod tests {
use super::*;
use ndarray::array;
use paste::item;
macro_rules! make_test {
($t:ty) => {
item! {
#[test]
fn [<test_vec_vec_ $t>]() {
let a = array![1 as $t, 2 as $t, 3 as $t];
let b = array![4 as $t, 5 as $t, 6 as $t];
let res: $t = <Array1<$t> as FPDot<Array1<$t>, $t>>::dot(&a, &b);
assert!((((res - 32 as $t) as f64).abs()) < std::f64::EPSILON);
}
}
item! {
#[test]
fn [<test_vec_scalar_ $t>]() {
let a = array![1 as $t, 2 as $t, 3 as $t];
let b = 2 as $t;
let product: Array1<$t> =
<Array1<$t> as FPDot<$t, Array1<$t>>>::dot(&a, &b);
let res = array![2 as $t, 4 as $t, 6 as $t];
for i in 0..3 {
assert!((((res[i] - product[i]) as f64).abs()) < std::f64::EPSILON);
}
}
}
item! {
#[test]
fn [<test_scalar_vec_ $t>]() {
let a = array![1 as $t, 2 as $t, 3 as $t];
let b = 2 as $t;
let product: Array1<$t> =
<$t as FPDot<Array1<$t>, Array1<$t>>>::dot(&b, &a);
let res = array![2 as $t, 4 as $t, 6 as $t];
for i in 0..3 {
assert!((((res[i] - product[i]) as f64).abs()) < std::f64::EPSILON);
}
}
}
item! {
#[test]
fn [<test_mat_vec_ $t>]() {
let a = array![1 as $t, 2 as $t, 3 as $t];
let b = array![4 as $t, 5 as $t, 6 as $t];
let res = array![
[4 as $t, 5 as $t, 6 as $t],
[8 as $t, 10 as $t, 12 as $t],
[12 as $t, 15 as $t, 18 as $t]
];
let product: Array2<$t> =
<Array1<$t> as FPDot<Array1<$t>, Array2<$t>>>::dot(&a, &b);
for i in 0..3 {
for j in 0..3 {
assert!((((res[(i, j)] - product[(i, j)]) as f64).abs()) < std::f64::EPSILON);
}
}
}
}
item! {
#[test]
fn [<test_mat_vec_2_ $t>]() {
let a = array![
[1 as $t, 2 as $t, 3 as $t],
[4 as $t, 5 as $t, 6 as $t],
[7 as $t, 8 as $t, 9 as $t]
];
let b = array![1 as $t, 2 as $t, 3 as $t];
let res = array![14 as $t, 32 as $t, 50 as $t];
let product: Array1<$t> =
<Array2<$t> as FPDot<Array1<$t>, Array1<$t>>>::dot(&a, &b);
for i in 0..3 {
assert!((((res[i] - product[i]) as f64).abs()) < std::f64::EPSILON);
}
}
}
item! {
#[test]
fn [<test_mat_mat_ $t>]() {
let a = array![
[1 as $t, 2 as $t, 3 as $t],
[4 as $t, 5 as $t, 6 as $t],
[3 as $t, 2 as $t, 1 as $t]
];
let b = array![
[3 as $t, 2 as $t, 1 as $t],
[6 as $t, 5 as $t, 4 as $t],
[2 as $t, 4 as $t, 3 as $t]
];
let res = array![
[21 as $t, 24 as $t, 18 as $t],
[54 as $t, 57 as $t, 42 as $t],
[23 as $t, 20 as $t, 14 as $t]
];
let product: Array2<$t> =
<Array2<$t> as FPDot<Array2<$t>, Array2<$t>>>::dot(&a, &b);
for i in 0..3 {
for j in 0..3 {
assert!((((res[(i, j)] - product[(i, j)]) as f64).abs()) < std::f64::EPSILON);
}
}
}
}
item! {
#[test]
fn [<test_mat_primitive_ $t>]() {
let a = array![
[1 as $t, 2 as $t, 3 as $t],
[4 as $t, 5 as $t, 6 as $t],
[3 as $t, 2 as $t, 1 as $t]
];
let res = array![
[2 as $t, 4 as $t, 6 as $t],
[8 as $t, 10 as $t, 12 as $t],
[6 as $t, 4 as $t, 2 as $t]
];
let product: Array2<$t> =
<Array2<$t> as FPDot<$t, Array2<$t>>>::dot(&a, &(2 as $t));
for i in 0..3 {
for j in 0..3 {
assert!((((res[(i, j)] - product[(i, j)]) as f64).abs()) < std::f64::EPSILON);
}
}
}
}
item! {
#[test]
fn [<test_primitive_mat_ $t>]() {
let a = array![
[1 as $t, 2 as $t, 3 as $t],
[4 as $t, 5 as $t, 6 as $t],
[3 as $t, 2 as $t, 1 as $t]
];
let res = array![
[2 as $t, 4 as $t, 6 as $t],
[8 as $t, 10 as $t, 12 as $t],
[6 as $t, 4 as $t, 2 as $t]
];
let product: Array2<$t> =
<$t as FPDot<Array2<$t>, Array2<$t>>>::dot(&(2 as $t), &a);
for i in 0..3 {
for j in 0..3 {
assert!((((res[(i, j)] - product[(i, j)]) as f64).abs()) < std::f64::EPSILON);
}
}
}
}
};
}
make_test!(i8);
make_test!(u8);
make_test!(i16);
make_test!(u16);
make_test!(i32);
make_test!(u32);
make_test!(i64);
make_test!(u64);
make_test!(f32);
make_test!(f64);
}
| 33.984556
| 106
| 0.315269
|
256e052b1dda9b234677621edc913b2ac038d580
| 602
|
js
|
JavaScript
|
nopNode.js
|
raytracer/CGPFun
|
9374337f56f65d83e4962f297be0302c671bf73d
|
[
"MIT"
] | 1
|
2015-02-24T16:28:23.000Z
|
2015-02-24T16:28:23.000Z
|
nopNode.js
|
raytracer/CGPFun
|
9374337f56f65d83e4962f297be0302c671bf73d
|
[
"MIT"
] | null | null | null |
nopNode.js
|
raytracer/CGPFun
|
9374337f56f65d83e4962f297be0302c671bf73d
|
[
"MIT"
] | null | null | null |
// nopNode.js
// A node that just passes the input through.
var NopNode = function(in1) {
this.in1 = in1;
};
NopNode.prototype.calculate = function(field) {
return field.nodes[this.in1].calculate(field);
};
NopNode.prototype.toString = function(field) {
return field.nodes[this.in1].toString(field);
};
NopNode.prototype.clone = function() {
return new NopNode(this.in1);
};
var randomNode = function(newPos) {
var newIn1 = Math.floor(Math.random() * (newPos + 1));
return new NopNode(newIn1);
};
module.exports.NopNode = NopNode;
module.exports.randomNode = randomNode;
| 21.5
| 58
| 0.694352
|
19754b5db2a2180112f350fd3c065a8ec417c528
| 181
|
dart
|
Dart
|
lib/localized_value.dart
|
zooper-lib/zooper_flutter_localization
|
91e04d93b2728aec33d6744b7b6e60314f02a4fe
|
[
"MIT"
] | null | null | null |
lib/localized_value.dart
|
zooper-lib/zooper_flutter_localization
|
91e04d93b2728aec33d6744b7b6e60314f02a4fe
|
[
"MIT"
] | null | null | null |
lib/localized_value.dart
|
zooper-lib/zooper_flutter_localization
|
91e04d93b2728aec33d6744b7b6e60314f02a4fe
|
[
"MIT"
] | null | null | null |
import 'dart:ui';
/// Model that stores the locale and it's value
class LocalizedValue {
Locale locale;
String localeValue;
LocalizedValue(this.locale, this.localeValue);
}
| 18.1
| 48
| 0.740331
|
c10f5cd579d7235f176bc6868ed0ea23b61384f4
| 1,790
|
ps1
|
PowerShell
|
psVaultUtils/Public/Policies/Show-VaultPolicy.ps1
|
wayfair-contribs/psVaultUtils
|
08d3a920e18d9ad60301c7d39f0ba62689a9e3ef
|
[
"BSD-2-Clause"
] | 1
|
2020-02-09T02:30:32.000Z
|
2020-02-09T02:30:32.000Z
|
psVaultUtils/Public/Policies/Show-VaultPolicy.ps1
|
wayfair-incubator/psVaultUtils
|
08d3a920e18d9ad60301c7d39f0ba62689a9e3ef
|
[
"BSD-2-Clause"
] | 4
|
2019-09-18T21:00:14.000Z
|
2019-10-11T18:00:38.000Z
|
psVaultUtils/Public/Policies/Show-VaultPolicy.ps1
|
wayfair-incubator/psVaultUtils
|
08d3a920e18d9ad60301c7d39f0ba62689a9e3ef
|
[
"BSD-2-Clause"
] | null | null | null |
function Show-VaultPolicy {
<#
.Synopsis
Lists all configured policies in Vault.
.DESCRIPTION
Show-VaultPolicy lists all configured policies in Vault.
.EXAMPLE
PS> Show-VaultPolicy
keys : {default, dsc-secret-consumer, jenkins-secret-consumer...}
policies : {default, dsc-secret-consumer, jenkins-secret-consumer...}
request_id : b871c03e-9760-6774-5c83-4e274dd2cfee
lease_id :
renewable : False
lease_duration : 0
data : @{keys=System.Object[]; policies=System.Object[]}
wrap_info :
warnings :
auth :
.EXAMPLE
PS> Show-VaultPolicy -JustPolicies | Select-Object -ExpandProperty policies
default
dsc-secret-consumer
jenkins-secret-consumer
log-rotation
operator
root
#>
[CmdletBinding()]
param(
[Parameter(
Position = 0
)]
[ValidateSet('Json','PSObject','Hashtable')]
[String] $OutputType = 'PSObject',
[Switch] $JustPolicies
)
begin {
Test-VaultSessionVariable -CheckFor 'Address','Token'
}
process {
$uri = $global:VAULT_ADDR
$irmParams = @{
Uri = "$uri/v1/sys/policy"
Header = @{ "X-Vault-Token" = $global:VAULT_TOKEN }
Method = 'Get'
}
try {
$result = Invoke-RestMethod @irmParams
}
catch {
throw
}
$formatParams = @{
InputObject = $result
DataType = 'policy_data'
JustData = $JustPolicies.IsPresent
OutputType = $OutputType
}
Format-VaultOutput @formatParams
}
end {
}
}
Set-Alias -Name 'List-VaultPolicy' -Value 'Show-VaultPolicy'
| 22.658228
| 79
| 0.559218
|
1a648592ab13a8eec979beb3ea5cf76790095ed8
| 10,770
|
py
|
Python
|
misc/test_compsp.py
|
wrensuess/prospector
|
08173f84ddfc2b031c78822344fc821778d35bae
|
[
"MIT"
] | 94
|
2016-10-12T19:29:58.000Z
|
2022-03-24T13:25:39.000Z
|
misc/test_compsp.py
|
wrensuess/prospector
|
08173f84ddfc2b031c78822344fc821778d35bae
|
[
"MIT"
] | 168
|
2016-04-15T20:01:34.000Z
|
2022-03-31T21:03:07.000Z
|
misc/test_compsp.py
|
wrensuess/prospector
|
08173f84ddfc2b031c78822344fc821778d35bae
|
[
"MIT"
] | 53
|
2016-07-14T07:19:11.000Z
|
2022-03-21T03:10:28.000Z
|
# Test the analytic full SFR integrals implemented in SSPBasis against the
# COMPSP implementations of same.
import sys, os, time
import numpy as np
import matplotlib.pyplot as pl
import fsps
from prospect.sources import CompositeSFH
sfhtype = {1:'tau', 4: 'delaytau', 5: 'simha'}
compute_vega_mags = False
zcontinuous = 1
sps = fsps.StellarPopulation(compute_vega_mags=compute_vega_mags,
zcontinuous=zcontinuous)
mysps = CompositeSFH(sfh_type='tau', interp_type='logarithmic', flux_interp='linear',
compute_vega_mags=compute_vega_mags, zcontinuous=zcontinuous)
mysps.configure()
sspages = np.insert(mysps.logage, 0, 0)
mysps.mint_log=-3
wlo = 1e3
whi = 1.2e4
def main():
tage = 1.4
# vary sf_trunc
sf_trunc = tage * np.linspace(0.90, 1.02, 9)
figlist = test_taumodel_sft(values=sf_trunc, tau=1.0,
sf_slope=10.0, tage=tage, sfh=4)
figlist[1].axes[0].set_xlim(5, 9)
figlist[0].savefig('figures/test_sft_spec.pdf')
figlist[1].savefig('figures/test_sft_wght.pdf')
# vary sf_trunc, simha SFH
sf_trunc = tage * np.linspace(0.90, 1.02, 9)
figlist = test_taumodel_sft(values=sf_trunc, tau=4.2,
sf_slope=10.0, tage=tage, sfh=5)
figlist[1].axes[0].set_xlim(5, 10.5)
figlist[0].savefig('figures/test_sft_simha_spec.pdf')
figlist[1].savefig('figures/test_sft_simha_wght.pdf')
#sys.exit()
# vary sf_slope
figlist = test_taumodel_sfslope()
figlist[1].axes[0].set_xlim(5, 10.5)
figlist[0].savefig('figures/test_sfslope_spec.pdf')
figlist[1].savefig('figures/test_sfslope_wght.pdf')
# vary tage
figlist = test_taumodel_tage(sfh=1)
figlist[0].savefig('figures/test_tage_spec.pdf')
figlist[1].savefig('figures/test_tage_wght.pdf')
# vary tau
figlist = test_taumodel_tau(sfh=1)
figlist[0].savefig('figures/test_tau_spec.pdf')
figlist[1].savefig('figures/test_tau_wght.pdf')
#pl.show()
def test_mint_convergence():
"""Test convergence of most recent bin.
"""
sfh_params = {'tage': 1e9, 'tau':14e9}
# set up an array of minimum values, and get the weights for each minimum value
mint = np.linspace(-4, 2, 100)
w = np.zeros([len(mint), len(mysps.logage)+1])
for i, m in enumerate(mint):
mysps.update(**sfh_params)
mysps.mint_log = m
mysps.configure()
w[i,:] = mysps.all_ssp_weights
# Plot summed weight for zeroth and 1st SSP
pl.figure()
zero = (w[:,0] + w[:,1])
pl.plot(mint, zero, '-o')
pl.yscale('log')
pl.show()
# Plot fractional weight error (relative to smallest tmin) as a function of tmin
pl.figure()
pl.plot(np.log10(mint), 1 - w[:,0]/w[0,0], '-o')
pl.plot(np.log10(mint), 1 - w[:,1]/w[0,1], '-o')
pl.show()
def test_taumodel_dust(values=np.linspace(0.0, 4.0, 9),
tage=3.0, tau=1.0, sfh=1):
pname = r'$\tau_V$'
sps.params['sfh'] = sfh
mysps.sfh_type = sfhtype[sfh]
mysps.configure()
sfig, saxes = pl.subplots(2, 1, figsize=(11, 8.5))
rax, dax = saxes
#wfig, wax = pl.subplots()
for dust2 in values:
sps.params['tau'] = tau
sps.params['tage'] = tage
sps.params['dust2'] = dust2
sfh_params = {'tage': tage*1e9, 'tau': tau*1e9, 'dust2': dust2}
w, spec = sps.get_spectrum(tage=tage, peraa=True)
mw, myspec, mstar = mysps.get_galaxy_spectrum(**sfh_params)
rax.plot(mw, myspec / spec, label=r'{}={:4.2f}'.format(pname, dust2))
dax.plot(mw, spec - myspec, label=r'{}={:4.2f}'.format(pname, dust2))
#wax.plot(sspages, mysps.all_ssp_weights, '-o', label=r'{}={:4.2f}'.format(pname, dust2))
rax.set_xlim(1e3, 1e7)
rax.set_ylabel('pro / FSPS')
dax.set_xlim(1e3, 1e7)
dax.set_ylabel('FSPS - pro')
[ax.set_xscale('log') for ax in [rax, dax]]
[ax.text(0.1, 0.8, r'$\tau_{{SF}}={}, tage={}$'.format(tau, tage), transform=ax.transAxes)
for ax in [rax, dax]]
[ax.legend(loc=0, prop={'size': 10}) for ax in [rax, dax]]
#wax.set_yscale('log')
#wax.set_xlabel('log t$_{lookback}$')
#wax.set_ylabel('weight')
[ax.set_title('SFH={} ({} model)'.format(sfh, sfhtype[sfh]))
for ax in [rax]]
return [sfig]
def test_taumodel_tau(values=10**np.linspace(-1, 1, 9),
tage=10.0, sfh=1):
"""Test (delayed-) tau models
"""
pname = r'$\tau$'
sps.params['sfh'] = sfh
mysps.sfh_type = sfhtype[sfh]
mysps.configure()
sfig, saxes = pl.subplots(2, 1, figsize=(11, 8.5))
rax, dax = saxes
wfig, wax = pl.subplots()
for tau in values:
sps.params['tau'] = tau
sps.params['tage'] = tage
sfh_params = {'tage': tage*1e9, 'tau': tau*1e9}
w, spec = sps.get_spectrum(tage=tage, peraa=True)
mw, myspec, mstar = mysps.get_galaxy_spectrum(**sfh_params)
rax.plot(mw, myspec / spec, label=r'{}={:4.2f}'.format(pname, tau))
dax.plot(mw, spec - myspec, label=r'{}={:4.2f}'.format(pname, tau))
wax.plot(sspages, mysps.all_ssp_weights, '-o', label=r'{}={:4.2f}'.format(pname, tau))
rax.set_xlim(wlo, whi)
rax.set_ylabel('pro / FSPS')
dax.set_xlim(wlo, whi)
dax.set_ylabel('FSPS - pro')
[ax.legend(loc=0, prop={'size': 10}) for ax in [rax, dax, wax]]
wax.set_yscale('log')
wax.set_xlabel('log t$_{lookback}$')
wax.set_ylabel('weight')
[ax.set_title('SFH={} ({} model)'.format(sfh, sfhtype[sfh]))
for ax in [rax, wax]]
return [sfig, wfig]
def test_taumodel_tage(values=10**np.linspace(np.log10(0.11), 1, 9),
tau=1.0, sf_slope=0.0, sfh=1):
"""Test (delayed-) tau models
"""
pname = 'tage'
sps.params['sfh'] = sfh
mysps.sfh_type = sfhtype[sfh]
mysps.configure()
sfig, saxes = pl.subplots(2, 1, figsize=(11, 8.5))
rax, dax = saxes
wfig, wax = pl.subplots()
for tage in values:
sps.params['tau'] = tau
sps.params['tage'] = tage
#sps.params['sf_slope'] = sf_slope
sfh_params = {'tage': tage*1e9, 'tau': tau*1e9}
w, spec = sps.get_spectrum(tage=tage, peraa=True)
mw, myspec, mstar = mysps.get_galaxy_spectrum(**sfh_params)
rax.plot(mw, myspec / spec, label=r'{}={:4.2f}'.format(pname, tage))
dax.plot(mw, spec - myspec, label=r'{}={:4.2f}'.format(pname, tage))
wax.plot(sspages, mysps.all_ssp_weights, '-o', label=r'{}={:4.2f}'.format(pname, tage))
rax.set_xlim(wlo, whi)
rax.set_ylabel('pro / FSPS')
dax.set_xlim(wlo, whi)
dax.set_ylabel('FSPS - pro')
[ax.legend(loc=0, prop={'size': 10}) for ax in [rax, dax, wax]]
wax.set_yscale('log')
wax.set_xlabel('log t$_{lookback}$')
wax.set_ylabel('weight')
[ax.set_title('SFH={} ({} model)'.format(sfh, sfhtype[sfh]))
for ax in [rax, wax]]
return [sfig, wfig]
def test_taumodel_sft(values=11 - 10**np.linspace(np.log10(0.11), 1, 9),
tau=1.0, sf_slope=0, tage=11.0, sfh=1):
"""Test (delayed-) tau models with a truncation
"""
pname = 'sf_trunc'
sps.params['sfh'] = sfh
mysps.sfh_type = sfhtype[sfh]
mysps.configure()
sfig, saxes = pl.subplots(2, 1, figsize=(11, 8.5))
rax, dax = saxes
wfig, wax = pl.subplots()
for sf_trunc in values:
sps.params['tau'] = tau
sps.params['tage'] = tage
sps.params['sf_trunc'] = sf_trunc
sps.params['sf_slope'] = sf_slope
sfh_params = {'tage': tage*1e9, 'tau': tau*1e9, 'sf_trunc': sf_trunc*1e9,
'sf_slope': sf_slope / 1e9}
w, spec = sps.get_spectrum(tage=tage, peraa=True)
mw, myspec, mstar = mysps.get_galaxy_spectrum(**sfh_params)
rax.plot(mw, myspec / spec, label=r'{}={:4.2f}'.format(pname, sf_trunc))
dax.plot(mw, spec - myspec, label=r'{}={:4.2f}'.format(pname, sf_trunc))
wax.plot(sspages, mysps.all_ssp_weights, '-o', label=r'{}={:4.2f}'.format(pname, sf_trunc))
#print(mysps.all_ssp_weights.sum())
if tage > sf_trunc:
wax.axvline(np.log10((tage - sf_trunc) * 1e9), linestyle=':', color='k')
rax.set_xlim(wlo, whi)
rax.set_ylabel('pro / FSPS')
dax.set_xlim(wlo, whi)
dax.set_ylabel('FSPS - pro')
[ax.text(0.1, 0.8, '$tau_{{SF}}={}, tage={}$\n sf_slope={:3.1f}'.format(tau, tage, sf_slope), transform=ax.transAxes)
for ax in [rax, dax, wax]]
[ax.legend(loc=0, prop={'size': 10}) for ax in [rax, dax, wax]]
wax.set_yscale('log')
wax.set_xlabel('log t$_{lookback}$')
wax.set_ylabel('weight')
logttrunc = np.log10((tage - values) * 1e9)
wax.set_xlim(logttrunc.min() - 0.5, logttrunc.max() + 0.5)
[ax.set_title('SFH={} ({} model)'.format(sfh, sfhtype[sfh]))
for ax in [rax, wax]]
return [sfig, wfig]
def test_taumodel_sfslope(values=np.linspace(-10, 10, 9),
tau=10.0, sf_trunc=10.0, tage=11.0, sfh=5):
"""Test (delayed-) tau models
"""
pname = 'sf_slope'
sps.params['sfh'] = sfh
mysps.sfh_type = sfhtype[sfh]
mysps.configure()
sfig, saxes = pl.subplots(2, 1, figsize=(11, 8.5))
rax, dax = saxes
wfig, wax = pl.subplots()
for sf_slope in values:
sps.params['tau'] = tau
sps.params['tage'] = tage
sps.params['sf_trunc'] = sf_trunc
sps.params['sf_slope'] = sf_slope
sfh_params = {'tage': tage*1e9, 'tau': tau*1e9, 'sf_trunc': sf_trunc*1e9,
'sf_slope': sf_slope / 1e9}
w, spec = sps.get_spectrum(tage=tage, peraa=True)
mw, myspec, mstar = mysps.get_galaxy_spectrum(**sfh_params)
rax.plot(mw, myspec / spec, label=r'{}={:4.2f}'.format(pname, sf_slope))
dax.plot(mw, spec - myspec, label=r'{}={:4.2f}'.format(pname, sf_slope))
wax.plot(sspages, mysps.all_ssp_weights, '-o', label=r'{}={:4.2f}'.format(pname, sf_slope))
wax.axvline(np.log10((tage - sf_trunc) * 1e9), linestyle=':', color='k')
#print(mysps.all_ssp_weights.sum())
rax.set_xlim(wlo, whi)
rax.set_ylabel('pro / FSPS')
dax.set_xlim(wlo, whi)
dax.set_ylabel('FSPS - pro')
[ax.legend(loc=0, prop={'size': 10}) for ax in [rax, dax, wax]]
[ax.text(0.1, 0.8, '$tau_{{SF}}={}, tage={}$\n sf_trunc={}'.format(tau, tage, sf_trunc), transform=ax.transAxes)
for ax in [rax, dax, wax]]
wax.set_yscale('log')
wax.set_xlabel('log t$_{lookback}$')
wax.set_ylabel('weight')
logttrunc = np.log10((tage - values) * 1e9)
wax.set_xlim(logttrunc.min() - 0.5, logttrunc.max() + 0.5)
[ax.set_title('SFH={} ({} model)'.format(sfh, sfhtype[sfh]))
for ax in [rax, wax]]
return [sfig, wfig]
if __name__ == "__main__":
main()
| 38.602151
| 121
| 0.598886
|
cd52f88925080994d31b3ded44eda4f34677a059
| 3,355
|
cs
|
C#
|
src/TBOptimizer/TBOptimizerTests/Climber/TestGeneralHillClimber.cs
|
jlat96/TBOptimizer
|
fedd258f9ee4fff8749d5d6e35a56042bb258d47
|
[
"MIT"
] | null | null | null |
src/TBOptimizer/TBOptimizerTests/Climber/TestGeneralHillClimber.cs
|
jlat96/TBOptimizer
|
fedd258f9ee4fff8749d5d6e35a56042bb258d47
|
[
"MIT"
] | null | null | null |
src/TBOptimizer/TBOptimizerTests/Climber/TestGeneralHillClimber.cs
|
jlat96/TBOptimizer
|
fedd258f9ee4fff8749d5d6e35a56042bb258d47
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using NUnit.Framework;
using OptimizerTests.TestModels.Evaluable;
using OptimizerTests.TestModels.State;
using TBOptimizer.Climber;
using TBOptimizer.Climber.Events;
using TrailBlazer.TBOptimizer.Climber;
using TrailBlazer.TBOptimizer.Climber.Algorithm;
using TrailBlazer.TBOptimizer.Comparison;
using TrailBlazer.TBOptimizer.Configuration;
using TrailBlazer.TBOptimizer.State;
namespace OptimizerTests.Climber
{
[TestFixture]
public class TestGeneralHillClimber
{
private MaximizingComparer<TestIntegerEvaluableState> comparer;
private ISuccessorGenerator<TestIntegerEvaluableState, int> generator;
private ClimberSuccessorSelector<TestIntegerEvaluableState, int> picker;
private LocalClimberAlgorithm<TestIntegerEvaluableState, int> algorithm;
private IHillClimber<TestIntegerEvaluableState, int> climber;
[SetUp]
public void Setup()
{
comparer = new MaximizingComparer<TestIntegerEvaluableState>();
generator = new TestLinearIntegerSuccessorGenerator();
climber = new ClimberConfiguration<TestIntegerEvaluableState, int>()
.ComparesUsing(new MaximizingComparer<TestIntegerEvaluableState>())
.GeneratesSuccessorsWith(generator)
.Build();
}
[Test, Timeout(5000)]
public void TestPerformOptimization()
{
TestIntegerEvaluableState initial = new TestIntegerEvaluableState(2);
TestIntegerEvaluableState result;
List<TestIntegerEvaluableState> states = new List<TestIntegerEvaluableState>();
List<TestIntegerEvaluableState> expectedStates = new List<TestIntegerEvaluableState>();
for (int i = 3; i <= 100; i++)
{
expectedStates.Add(new TestIntegerEvaluableState(i));
}
void eventCallback(object sender, ClimberStepEvent<TestIntegerEvaluableState, int> args)
{
states.Add(args.CurrentState);
};
climber.ClimberStepPerformedEvent += eventCallback;
result = climber.Optimize(initial);
Assert.AreEqual(100, result.Value);
Assert.AreEqual(expectedStates.Count, states.Count);
for (int i = 0; i < states.Count; i++)
{
Assert.IsTrue(states[i].CompareTo(expectedStates[i]) == 0);
}
}
[Test, Timeout(5000)]
public void TestPerformOptimizationReturnsLocalExtrema()
{
TestIntegerEvaluableState initial = new TestIntegerEvaluableState(2);
TestIntegerEvaluableState result;
generator = new TestIntegerLocalMaximaSuccessorGenerator();
picker = new ClimberSuccessorSelector<TestIntegerEvaluableState, int>(generator, comparer);
algorithm = new LocalClimberAlgorithm<TestIntegerEvaluableState, int>(picker);
climber = new ClimberConfiguration<TestIntegerEvaluableState, int>()
.ComparesUsing(comparer)
.GeneratesSuccessorsWith(generator)
.Build();
result = climber.Optimize(initial);
Assert.AreEqual(50, result.Value);
}
}
}
| 37.696629
| 103
| 0.670641
|
105c9afa79355a64ebf94b9bacab08ddf970f146
| 1,421
|
dart
|
Dart
|
lib/common/widgets/t_dropdown.dart
|
PetIsland/petisland
|
73597405f2fa50b09c32899cb3058c694ac1bd14
|
[
"Apache-2.0"
] | 5
|
2019-12-04T17:52:54.000Z
|
2019-12-23T19:58:48.000Z
|
lib/common/widgets/t_dropdown.dart
|
PetIsland/petisland
|
73597405f2fa50b09c32899cb3058c694ac1bd14
|
[
"Apache-2.0"
] | 111
|
2019-10-03T16:30:21.000Z
|
2020-01-08T03:04:43.000Z
|
lib/common/widgets/t_dropdown.dart
|
PetIsland/pet-island
|
73597405f2fa50b09c32899cb3058c694ac1bd14
|
[
"Apache-2.0"
] | 3
|
2019-12-07T17:38:05.000Z
|
2020-02-15T03:06:55.000Z
|
part of petisland.common.widgets;
class TDropDown extends StatefulWidget {
final int itemCount;
final IndexedWidgetBuilder builder;
final int initSelectedItem;
final ValueChanged<int> onSelectedChanged;
TDropDown.builder({
@required this.itemCount,
@required this.builder,
this.initSelectedItem = 0,
this.onSelectedChanged,
});
@override
_TDropDownState createState() => _TDropDownState();
}
class _TDropDownState extends State<TDropDown> {
final List<DropdownMenuItem<int>> items = <DropdownMenuItem<int>>[];
int currentSelected;
void initState() {
super.initState();
currentSelected = widget.initSelectedItem ?? 0;
items.addAll(
List<DropdownMenuItem<int>>.generate(
widget.itemCount,
(int i) => DropdownMenuItem<int>(
value: i,
child: Builder(builder: (context) => widget.builder(context, i)),
),
),
);
}
@override
Widget build(BuildContext context) {
return DropdownButton<int>(
elevation: 1,
iconEnabledColor: Theme.of(context).primaryColor,
iconSize: 32,
items: items,
value: currentSelected,
onChanged: _onSelectedChanged,
isExpanded: true,
);
}
void _onSelectedChanged(int value) {
setState(() {
currentSelected = value;
});
if (widget.onSelectedChanged != null)
widget.onSelectedChanged(currentSelected);
}
}
| 24.084746
| 75
| 0.667136
|
93751d183f60b967756c8ce1459c4d19df159b73
| 4,004
|
swift
|
Swift
|
Kit/LocalDB/LocalDB.swift
|
dreymonde/TheGreatGame
|
723db179dfbd1f6e9ebf485355d40868baec145e
|
[
"MIT"
] | 148
|
2017-07-17T07:24:38.000Z
|
2021-11-14T20:18:49.000Z
|
Kit/LocalDB/LocalDB.swift
|
dreymonde/TheGreatGame
|
723db179dfbd1f6e9ebf485355d40868baec145e
|
[
"MIT"
] | 1
|
2017-10-03T06:32:00.000Z
|
2017-10-04T02:10:09.000Z
|
Kit/LocalDB/LocalDB.swift
|
dreymonde/TheGreatGame
|
723db179dfbd1f6e9ebf485355d40868baec145e
|
[
"MIT"
] | 14
|
2017-07-17T07:36:02.000Z
|
2020-12-16T01:50:18.000Z
|
//
// LocalDB.swift
// TheGreatGame
//
// Created by Олег on 27.12.2017.
// Copyright © 2017 The Great Game. All rights reserved.
//
import Foundation
import Shallows
public final class LocalDB : DeepStoring {
public typealias PreferredDirectory = Library.Application_Support.db
public static func preferredDirectory(from base: BaseFolder.Type) -> Library.Application_Support.db {
return base.Library.Application_Support.db
}
public static var filenameEncoder: Filename.Encoder {
return .noEncoding
}
public let teams: LocalModel<[Team.Compact]>
public let stages: LocalModel<[Stage]>
public let groups: LocalModel<[Group.Compact]>
public let fullMatches: LocalModel<[Match.Full]>
public let fullTeam: (Team.ID) -> LocalModel<Team.Full>
public let fullMatch: (Match.ID) -> LocalModel<Match.Full>
public init(teams: LocalModel<[Team.Compact]>,
stages: LocalModel<[Stage]>,
groups: LocalModel<[Group.Compact]>,
fullMatches: LocalModel<[Match.Full]>,
fullTeam: @escaping (Team.ID) -> LocalModel<Team.Full>,
fullMatch: @escaping (Match.ID) -> LocalModel<Match.Full>) {
self.teams = teams
self.stages = stages
self.groups = groups
self.fullMatches = fullMatches
self.fullTeam = fullTeam
self.fullMatch = fullMatch
}
public convenience init(container: Container) {
let teams: LocalModel<[Team.Compact]> = LocalModel<[Team.Compact]>.inStorage(
LocalDB.substorage(in: container, subFolder: { $0.teams }), filename: "teams-compact"
)
let stages: LocalModel<[Stage]> = LocalModel<[Stage]>.inStorage(
LocalDB.substorage(in: container, subFolder: { $0.stages }), filename: "stages"
)
let groups: LocalModel<[Group.Compact]> = LocalModel<[Group.Compact]>.inStorage(
LocalDB.substorage(in: container, subFolder: { $0.groups }), filename: "all-groups"
)
let matches: LocalModel<[Match.Full]> = LocalModel<[Match.Full]>.inStorage(
LocalDB.substorage(in: container, subFolder: { $0.matches }), filename: "matches-full"
)
let fullTeam = LocalDB.makeFullTeam(makeStorage: { produce in LocalDB.substorage(in: container, subFolder: produce) })
let fullMatch = LocalDB.makeFullMatch(makeStorage: { produce in LocalDB.substorage(in: container, subFolder: produce) })
self.init(teams: teams,
stages: stages,
groups: groups,
fullMatches: matches,
fullTeam: fullTeam,
fullMatch: fullMatch)
}
}
extension LocalDB {
public static func inContainer(_ container: Container) -> LocalDB {
return LocalDB(container: container)
}
}
extension LocalDB {
static func makeLazy<IDType : Hashable, Value : Mappable>(storage: Disk,
makeFilename: @escaping (IDType) -> Filename) -> (IDType) -> LocalModel<Value> {
let lazyDict = LazyDictionary<IDType, LocalModel<Value>> { id in
return LocalModel<Value>.inStorage(storage, filename: makeFilename(id))
}
let tsLazyDict = ThreadSafe(lazyDict)
return { id in
return tsLazyDict.read()[id]
}
}
static func makeFullTeam(makeStorage: ((PreferredDirectory) -> (Directory)) -> Disk) -> (Team.ID) -> LocalModel<Team.Full> {
return makeLazy(storage: makeStorage({ $0.teams }),
makeFilename: { Filename.init(rawValue: "team-\($0)") })
}
static func makeFullMatch(makeStorage: ((PreferredDirectory) -> (Directory)) -> Disk) -> (Match.ID) -> LocalModel<Match.Full> {
return makeLazy(storage: makeStorage({ $0.matches }),
makeFilename: { Filename.init(rawValue: "match-\($0)") })
}
}
| 38.133333
| 142
| 0.614635
|
758fc8ae4503b76b316ba1ee176fa21e1695cde0
| 613
|
css
|
CSS
|
public/css/styles.css
|
jamesgilley/Greenhaus
|
41d18d8ce3102e4154848b203aaf0ebb34ae6d2a
|
[
"MIT"
] | 1
|
2021-03-17T03:20:13.000Z
|
2021-03-17T03:20:13.000Z
|
public/css/styles.css
|
maxx-808/Greenhaus
|
5b062def0cd06d723a79d274e39b1d0d777fd518
|
[
"MIT"
] | null | null | null |
public/css/styles.css
|
maxx-808/Greenhaus
|
5b062def0cd06d723a79d274e39b1d0d777fd518
|
[
"MIT"
] | 6
|
2021-01-16T19:48:06.000Z
|
2021-01-29T18:16:57.000Z
|
body {
background-image: url("../css/palm-leaf.png");
}
select {
display: block;
}
.brand-logo {
margin-top: 2px;
margin-left: 10px;
}
.bkg-img {
background-image: url("../css/sfconservatory-bkg.jpeg");
background-repeat: no-repeat;
height: 60%;
background-size: cover;
}
.form {
padding: 50px;
}
.header {
margin: 0 auto;
}
.homenav {
padding: 10px;
}
.plant-container {
margin: 5px;
padding: 5px;
}
.titlebox {
border: 5px solid #000000;
margin-top: 10px;
}
.title-text {
margin-right: 15px;
margin-left: 15px;
}
#title-icon {
margin: 0 auto;
max-height: 32px;
}
| 11.788462
| 58
| 0.624796
|
254cbb1fe181b0ba6bac3625cdff245feacdae62
| 1,004
|
cs
|
C#
|
BOL/tbl_Url.cs
|
nickgoodrow/Mvc3Tier_LinkHub
|
d0b06a12fb6b51e27894799d4973a23a43e5348f
|
[
"MIT"
] | null | null | null |
BOL/tbl_Url.cs
|
nickgoodrow/Mvc3Tier_LinkHub
|
d0b06a12fb6b51e27894799d4973a23a43e5348f
|
[
"MIT"
] | null | null | null |
BOL/tbl_Url.cs
|
nickgoodrow/Mvc3Tier_LinkHub
|
d0b06a12fb6b51e27894799d4973a23a43e5348f
|
[
"MIT"
] | null | null | null |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BOL
{
using System;
using System.Collections.Generic;
public partial class tbl_Url
{
public int i_UrlId { get; set; }
public string c_UrlTitle { get; set; }
public string c_Url { get; set; }
public string c_UrlDesc { get; set; }
public Nullable<int> i_CategoryId { get; set; }
public Nullable<int> i_UserId { get; set; }
public string c_IsApproved { get; set; }
public virtual tbl_Category tbl_Category { get; set; }
public virtual tbl_User tbl_User { get; set; }
}
}
| 34.62069
| 85
| 0.535857
|
e14723602caa8eb38d3b965b9d94b531081d6de1
| 357
|
rb
|
Ruby
|
init.rb
|
isotes/redmine-repository-readme-preview
|
ba4fe7ad0a0208dfd74eabd24f3a065d994dd71d
|
[
"MIT"
] | null | null | null |
init.rb
|
isotes/redmine-repository-readme-preview
|
ba4fe7ad0a0208dfd74eabd24f3a065d994dd71d
|
[
"MIT"
] | null | null | null |
init.rb
|
isotes/redmine-repository-readme-preview
|
ba4fe7ad0a0208dfd74eabd24f3a065d994dd71d
|
[
"MIT"
] | null | null | null |
require_dependency 'repository_readme_preview'
Redmine::Plugin.register :repository_readme_preview do
name 'Repository Readme Preview'
author 'Robert Sauter'
description 'Inline preview of Readme files in repository browser'
version '0.1.0'
url 'https://github.com/isotes/redmine-repository-readme-preview'
author_url 'https://github.com/isotes'
end
| 32.454545
| 67
| 0.806723
|
df3eb9e1b6e5f14e1120982044a29b9e23b916c3
| 282
|
sql
|
SQL
|
microservices/user/src/main/resources/db/migration/V01__init.sql
|
ekino/micronaut-demo
|
73ce01e2c60df56dc1e1f11c6f49bfcc7f1b55b6
|
[
"MIT"
] | 2
|
2018-11-02T20:10:27.000Z
|
2019-02-03T08:33:59.000Z
|
microservices/user/src/main/resources/db/migration/V01__init.sql
|
ekino/micronaut-demo
|
73ce01e2c60df56dc1e1f11c6f49bfcc7f1b55b6
|
[
"MIT"
] | 1
|
2018-11-26T08:44:34.000Z
|
2018-11-26T08:44:34.000Z
|
microservices/user/src/main/resources/db/migration/V01__init.sql
|
ekino/micronaut-demo
|
73ce01e2c60df56dc1e1f11c6f49bfcc7f1b55b6
|
[
"MIT"
] | 3
|
2018-11-26T08:31:01.000Z
|
2019-08-23T16:03:57.000Z
|
CREATE TABLE "user" (
id UUID NOT NULL,
emailAddress VARCHAR(100) NOT NULL,
firstName VARCHAR(100) NOT NULL,
lastName VARCHAR(100) NOT NULL,
age INTEGER NOT NULL,
CONSTRAINT pk_user PRIMARY KEY (id)
);
ALTER TABLE "user"
ADD CONSTRAINT uk_user UNIQUE (emailAddress);
| 23.5
| 47
| 0.730496
|
c5541b3ca1c867d569b3731b97ab1fe4c891c1b8
| 1,390
|
css
|
CSS
|
assets/libs/ckeditor-full/plugins/filemanager/scripts/jquery.splitter/jquery.splitter.css
|
IlucielI/journeystory
|
0ea16bdd39acdb759e9c20aa77b330004940be0d
|
[
"MIT"
] | 15
|
2018-06-13T20:32:02.000Z
|
2022-01-16T11:55:08.000Z
|
assets/libs/ckeditor-full/plugins/filemanager/scripts/jquery.splitter/jquery.splitter.css
|
IlucielI/journeystory
|
0ea16bdd39acdb759e9c20aa77b330004940be0d
|
[
"MIT"
] | 4
|
2020-03-12T13:59:36.000Z
|
2020-03-12T13:59:40.000Z
|
assets/libs/ckeditor-full/plugins/filemanager/scripts/jquery.splitter/jquery.splitter.css
|
IlucielI/journeystory
|
0ea16bdd39acdb759e9c20aa77b330004940be0d
|
[
"MIT"
] | 10
|
2018-06-14T06:45:52.000Z
|
2022-01-16T11:55:08.000Z
|
/*
Splitter container. Set this to the desired width and height
of the combined left and right panes. In this example, the
height is fixed and the width is the full width of the body,
less the margin on the splitter itself.
*/
#splitter {
background-color: white;
height: 400px;
border: 1px solid #ccc;
/* border: 4px solid #E2EAF3; */ /* No padding allowed */
}
/*
Left-side element of the splitter. Use pixel units for the
min-width and max-width; the splitter plugin parses them to
determine the splitter movement limits. Set the width to
the desired initial width of the element; the plugin changes
the width of this element dynamically.
*/
#filetree { /* padding: 4px; */
overflow: auto;
width: 200px; /* optional, initial splitbar position */
min-width: 200px; /* optional */ /* No margin or border allowed */
}
#filetree>ul {
padding: 4px;
}
/*
Right-side element of the splitter.
*/
#fileinfo {
padding: 4px;
min-width: 100px;
overflow: auto;
/* No margin or border allowed */
}
/*
Splitter bar style; the .active class is added when the
mouse is over the splitter or the splitter is focused
via the keyboard taborder or an accessKey.
*/
#splitter .vsplitbar {
width: 6px;
background: #ccc url(vgrabber.gif) no-repeat center;
}
/*
#splitter .vsplitbar.active,
#splitter .vsplitbar:hover {
background: #e88 url(vgrabber.gif) no-repeat center;
}
*/
| 24.821429
| 67
| 0.716547
|
b0982e32603c9e5e5b1ff6a4bdce6cf738971d70
| 682
|
py
|
Python
|
Python Projects/QtGraphics.py
|
jonnyhyman/Programming-Classes
|
f56a9cf90e3b8e4aafad99644f1ed7e87ba14995
|
[
"MIT"
] | 23
|
2018-12-15T01:10:51.000Z
|
2021-07-02T05:23:45.000Z
|
Python Projects/QtGraphics.py
|
jonnyhyman/Programming-Classes
|
f56a9cf90e3b8e4aafad99644f1ed7e87ba14995
|
[
"MIT"
] | null | null | null |
Python Projects/QtGraphics.py
|
jonnyhyman/Programming-Classes
|
f56a9cf90e3b8e4aafad99644f1ed7e87ba14995
|
[
"MIT"
] | 5
|
2020-02-15T12:47:42.000Z
|
2021-02-28T03:01:19.000Z
|
from PyQt5 import QtGui, QtCore, QtWidgets
import sys
Window = QtWidgets.QMainWindow
Brush = QtGui.QBrush
Pen = QtGui.QPen
Color = QtGui.QColor
Stage = QtWidgets.QGraphicsScene
ImageItem = QtWidgets.QGraphicsPixmapItem
Image = QtGui.QPixmap
class View(QtWidgets.QGraphicsView):
def __init__(self, stage):
super().__init__(stage)
self.stage = stage
i = Image('moon.jpg')
i = i.scaledToHeight(600)
self.stage.addItem(ImageItem(i))
if __name__=='__main__':
app = QtWidgets.QApplication(sys.argv)
stage = Stage(0, 0, 800, 600)
view = View(stage)
view.show()
app.exec_() # complete all execution code in the GUI
| 20.666667
| 57
| 0.681818
|
0afb2d55eb7df8cef18a92295f95aa909d100c72
| 2,214
|
cs
|
C#
|
Yuki Theme.Core/FontManager.cs
|
UI-Apps/Yuki-Theme
|
29c7d5998ca733b27995556138bcfa97727b782e
|
[
"MIT"
] | 15
|
2021-12-01T10:53:53.000Z
|
2022-03-30T14:25:57.000Z
|
Yuki Theme.Core/FontManager.cs
|
UI-Apps/Yuki-Theme
|
29c7d5998ca733b27995556138bcfa97727b782e
|
[
"MIT"
] | 11
|
2021-12-01T13:59:53.000Z
|
2022-02-20T15:48:18.000Z
|
Yuki Theme.Core/FontManager.cs
|
UI-Apps/Yuki-Theme
|
29c7d5998ca733b27995556138bcfa97727b782e
|
[
"MIT"
] | 4
|
2021-12-03T10:05:49.000Z
|
2022-03-30T14:25:46.000Z
|
using System;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Yuki_Theme.Core
{
public static class FontManager
{
[System.Runtime.InteropServices.DllImport ("gdi32.dll")]
private static extern IntPtr AddFontMemResourceEx (IntPtr pbFont, uint cbFont,
IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);
private static PrivateFontCollection _fonts = new PrivateFontCollection ();
private static bool _initialized = false;
private static void LoadFont (string resource)
{
// receive resource stream
Stream fontStream = Assembly.GetExecutingAssembly ().GetManifestResourceStream (resource);
// create an unsafe memory block for the font data
System.IntPtr data = Marshal.AllocCoTaskMem ((int) fontStream.Length);
// create a buffer to read in to
byte [] fontdata = new byte[fontStream.Length];
// read the font data from the resource
fontStream.Read (fontdata, 0, (int) fontStream.Length);
// copy the bytes to the unsafe memory block
Marshal.Copy (fontdata, 0, data, (int) fontStream.Length);
// pass the font to the font collection
_fonts.AddMemoryFont (data, (int) fontStream.Length);
// close the resource stream
fontStream.Close ();
// free up the unsafe memory
Marshal.FreeCoTaskMem (data);
}
private static void Initialize ()
{
LoadFont("Yuki_Theme.Core.Resources.Fonts.Montserrat-Regular.ttf");
LoadFont ("Yuki_Theme.Core.Resources.Fonts.SAOUITT-Regular.ttf");
_initialized = true;
}
public static FontFamily GetFont (int which)
{
if (!_initialized)
Initialize ();
return _fonts.Families [which];
}
public static void SetAllControlsFont(Control.ControlCollection ctrls, int which) {
foreach(Control c in ctrls) {
if(c.Controls != null) {
SetAllControlsFont(c.Controls, which);
}
SetControlFont (c, which);
}
}
public static void SetControlFont (Control c, int which)
{
c.Font = new Font (GetFont (which), c.Font.Size);
}
}
}
| 28.384615
| 122
| 0.688799
|
5805af494899a076e51aa4a1d9353d0c0bc3c7c7
| 608
|
css
|
CSS
|
client/src/components/record/record.css
|
krisk0su/Dynamo
|
16d8fd150807cc226529f546415d3b3e051caf0a
|
[
"MIT"
] | null | null | null |
client/src/components/record/record.css
|
krisk0su/Dynamo
|
16d8fd150807cc226529f546415d3b3e051caf0a
|
[
"MIT"
] | null | null | null |
client/src/components/record/record.css
|
krisk0su/Dynamo
|
16d8fd150807cc226529f546415d3b3e051caf0a
|
[
"MIT"
] | null | null | null |
.record {
width: 90%;
height: 3em;
display: flex;
align-items: center;
justify-content: space-around;
border: 0.1em solid black;
border-radius: 0.6em;
background: rgba(187, 224, 112, 0.5);
margin: 1em 0;
}
.record p {
color: red;
padding-top: 1em;
}
.record label {
display: flex;
align-items: center;
justify-content: center;
}
.record input[type="text"] {
width: 20em;
height: 1.7em;
padding: 0 0.5em;
background: white;
border: 1px solid black;
border-radius: 0.5em;
font-family: "Montserrat", sans-serif;
}
.record input[type="checkbox"] {
margin-left: 1em;
}
| 18.424242
| 40
| 0.651316
|
4073c8ffaae56fd3bb4a4e133f9e4fac01230518
| 200
|
rb
|
Ruby
|
app/mailers/ninja_mailer.rb
|
WingardiumJKEULEYA/BlernsWar
|
a510d1eeee6201483079a296ee57cf77949dc50e
|
[
"MIT"
] | null | null | null |
app/mailers/ninja_mailer.rb
|
WingardiumJKEULEYA/BlernsWar
|
a510d1eeee6201483079a296ee57cf77949dc50e
|
[
"MIT"
] | null | null | null |
app/mailers/ninja_mailer.rb
|
WingardiumJKEULEYA/BlernsWar
|
a510d1eeee6201483079a296ee57cf77949dc50e
|
[
"MIT"
] | null | null | null |
# Ninja Mailer
class NinjaMailer < ApplicationMailer
def update_ninja(ninja)
@ninja = ninja
@user = @ninja.user
mail(to: @user.email, subject: 'Your ninja has been updated !')
end
end
| 22.222222
| 67
| 0.69
|
4db655e8f002cd0ee6ea16bf114986bdfb588f42
| 2,095
|
cs
|
C#
|
DreamTeam/Areas/Api/Admin/SeasonController.cs
|
subshock/dreamteam
|
14588ef7229e3fd69172f08a6cde2b6bb1a83fea
|
[
"MIT"
] | null | null | null |
DreamTeam/Areas/Api/Admin/SeasonController.cs
|
subshock/dreamteam
|
14588ef7229e3fd69172f08a6cde2b6bb1a83fea
|
[
"MIT"
] | null | null | null |
DreamTeam/Areas/Api/Admin/SeasonController.cs
|
subshock/dreamteam
|
14588ef7229e3fd69172f08a6cde2b6bb1a83fea
|
[
"MIT"
] | null | null | null |
using DreamTeam.Areas.Api.Admin.ViewModels;
using DreamTeam.Data;
using DreamTeam.Models;
using DreamTeam.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DreamTeam.Areas.Api.Admin
{
[Route("api/admin/[controller]")]
public partial class SeasonController : BaseAdminController
{
private readonly ApplicationDbContext _db;
public SeasonController(ApplicationDbContext db)
{
_db = db;
}
[HttpGet]
public async Task<IActionResult> GetSeasons()
{
return Ok(await _db.GetSeasonsAsync());
}
[HttpGet("{id:guid}")]
public async Task<IActionResult> GetSeason(Guid id)
{
var obj = await _db.GetSeasonAsync(id);
if (obj == null)
return NotFound();
return Ok(obj);
}
[HttpPost]
public async Task<IActionResult> CreateSeason([FromBody] UpdateSeasonViewModel model)
{
if (!ModelState.IsValid)
return BadRequest(model);
var season = await _db.CreateSeasonAsync(model);
return Ok(new { season.Id });
}
[HttpPost("{id:guid}")]
public async Task<IActionResult> UpdateSeason(Guid id, [FromBody] UpdateSeasonViewModel model)
{
if (!ModelState.IsValid)
return BadRequest(model);
await _db.UpdateSeasonAsync(id, model);
return Ok();
}
[HttpDelete("{id:guid}")]
public async Task<IActionResult> DeleteSeason(Guid id)
{
await _db.DeleteSeasonAsync(id);
return Ok();
}
[HttpPost("{id:guid}/status")]
public async Task<IActionResult> ChangeSeasonStatus(Guid id, [FromBody] SeasonStateType state)
{
var result = await _db.UpdateSeasonStatusAsync(id, state);
return Ok(new { Result = result });
}
}
}
| 26.1875
| 102
| 0.594749
|
525ad197e5f8c65c4ce129104cbe29d0970f2899
| 2,731
|
dart
|
Dart
|
lib/image_transformer.dart
|
vscmaster/optimized_cached_image
|
5018f73bcd6108f3ccf3ee6b1d1256b54cc2b880
|
[
"MIT"
] | null | null | null |
lib/image_transformer.dart
|
vscmaster/optimized_cached_image
|
5018f73bcd6108f3ccf3ee6b1d1256b54cc2b880
|
[
"MIT"
] | null | null | null |
lib/image_transformer.dart
|
vscmaster/optimized_cached_image
|
5018f73bcd6108f3ccf3ee6b1d1256b54cc2b880
|
[
"MIT"
] | null | null | null |
import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path/path.dart' as p;
import 'image_cache_manager.dart';
class DefaultImageTransformer extends ImageTransformer {
final ImageCacheConfig config;
DefaultImageTransformer(this.config);
final tmpFileSuffix = '_tmp';
final _compressionFormats = {
'.jpg': CompressFormat.jpeg,
'.jpeg': CompressFormat.jpeg,
'.webp': CompressFormat.webp,
'.png': CompressFormat.png,
'.heic': CompressFormat.heic,
};
final _extensionFormats = {
CompressFormat.jpeg: '.jpg',
CompressFormat.webp: '.webp',
CompressFormat.png: '.png',
CompressFormat.heic: '.heic'
};
@override
Future<FileInfo> transform(FileInfo info, String uri) async {
final dimens = _getDimensionsFromUrl(uri);
await _scaleImageFile(info, dimens[0], dimens[1]);
return info;
}
List<int> _getDimensionsFromUrl(String url) {
Uri uri = Uri.parse(url);
String heightParam = uri.queryParameters[config.heightKey];
int height = heightParam != null ? int.tryParse(heightParam) : null;
String widthParam = uri.queryParameters[config.widthKey];
int width = widthParam != null ? int.tryParse(widthParam) : null;
return [width, height];
}
Future<FileInfo> _scaleImageFile(FileInfo info, int width, int height) async {
File file = info.file;
final screen = window.physicalSize;
var minWidth = width ?? screen.width.toInt();
var minHeight = height ?? screen.height.toInt();
if (minWidth == 0) {
minWidth = screen.width.toInt();
}
if (minHeight == 0) {
minHeight = screen.height.toInt();
}
if (file.existsSync()) {
String extension = p.extension(file.path) ?? '';
final format = _compressionFormats[extension] ?? CompressFormat.png;
final tmpFile = getTempFile(file, format);
final srcSize = file.lengthSync();
File resizedFile = await FlutterImageCompress.compressAndGetFile(file.path, tmpFile.path,
minWidth: minWidth, minHeight: minHeight, format: format);
if (resizedFile != null && resizedFile.existsSync()) {
if (resizedFile.lengthSync() < srcSize) {
resizedFile.renameSync(file.path);
} else {
resizedFile.deleteSync();
}
}
}
return info;
}
File getTempFile(File file, CompressFormat format) {
final directory = file.parent;
final destPath = directory.path +
"/" +
p.basenameWithoutExtension(file.path) +
tmpFileSuffix +
_extensionFormats[format];
return File(destPath);
}
}
| 31.390805
| 95
| 0.673746
|
ff846ba2c62e7e2834b9c4c6ce9421ed288620f9
| 4,585
|
py
|
Python
|
resources/dot_PyCharm/system/python_stubs/-762174762/PySide/QtGui/QFormLayout.py
|
basepipe/developer_onboarding
|
05b6a776f8974c89517868131b201f11c6c2a5ad
|
[
"MIT"
] | 1
|
2020-04-20T02:27:20.000Z
|
2020-04-20T02:27:20.000Z
|
resources/dot_PyCharm/system/python_stubs/cache/8cdc475d469a13122bc4bc6c3ac1c215d93d5f120f5cc1ef33a8f3088ee54d8e/PySide/QtGui/QFormLayout.py
|
basepipe/developer_onboarding
|
05b6a776f8974c89517868131b201f11c6c2a5ad
|
[
"MIT"
] | null | null | null |
resources/dot_PyCharm/system/python_stubs/cache/8cdc475d469a13122bc4bc6c3ac1c215d93d5f120f5cc1ef33a8f3088ee54d8e/PySide/QtGui/QFormLayout.py
|
basepipe/developer_onboarding
|
05b6a776f8974c89517868131b201f11c6c2a5ad
|
[
"MIT"
] | null | null | null |
# encoding: utf-8
# module PySide.QtGui
# from C:\Python27\lib\site-packages\PySide\QtGui.pyd
# by generator 1.147
# no doc
# imports
import PySide.QtCore as __PySide_QtCore
import Shiboken as __Shiboken
from QLayout import QLayout
class QFormLayout(QLayout):
# no doc
def addItem(self, *args, **kwargs): # real signature unknown
pass
def addRow(self, *args, **kwargs): # real signature unknown
pass
def count(self, *args, **kwargs): # real signature unknown
pass
def expandingDirections(self, *args, **kwargs): # real signature unknown
pass
def fieldGrowthPolicy(self, *args, **kwargs): # real signature unknown
pass
def formAlignment(self, *args, **kwargs): # real signature unknown
pass
def getItemPosition(self, *args, **kwargs): # real signature unknown
pass
def getLayoutPosition(self, *args, **kwargs): # real signature unknown
pass
def getWidgetPosition(self, *args, **kwargs): # real signature unknown
pass
def hasHeightForWidth(self, *args, **kwargs): # real signature unknown
pass
def heightForWidth(self, *args, **kwargs): # real signature unknown
pass
def horizontalSpacing(self, *args, **kwargs): # real signature unknown
pass
def insertRow(self, *args, **kwargs): # real signature unknown
pass
def invalidate(self, *args, **kwargs): # real signature unknown
pass
def itemAt(self, *args, **kwargs): # real signature unknown
pass
def labelAlignment(self, *args, **kwargs): # real signature unknown
pass
def labelForField(self, *args, **kwargs): # real signature unknown
pass
def minimumSize(self, *args, **kwargs): # real signature unknown
pass
def rowCount(self, *args, **kwargs): # real signature unknown
pass
def rowWrapPolicy(self, *args, **kwargs): # real signature unknown
pass
def setFieldGrowthPolicy(self, *args, **kwargs): # real signature unknown
pass
def setFormAlignment(self, *args, **kwargs): # real signature unknown
pass
def setGeometry(self, *args, **kwargs): # real signature unknown
pass
def setHorizontalSpacing(self, *args, **kwargs): # real signature unknown
pass
def setItem(self, *args, **kwargs): # real signature unknown
pass
def setLabelAlignment(self, *args, **kwargs): # real signature unknown
pass
def setLayout(self, *args, **kwargs): # real signature unknown
pass
def setRowWrapPolicy(self, *args, **kwargs): # real signature unknown
pass
def setSpacing(self, *args, **kwargs): # real signature unknown
pass
def setVerticalSpacing(self, *args, **kwargs): # real signature unknown
pass
def setWidget(self, *args, **kwargs): # real signature unknown
pass
def sizeHint(self, *args, **kwargs): # real signature unknown
pass
def spacing(self, *args, **kwargs): # real signature unknown
pass
def takeAt(self, *args, **kwargs): # real signature unknown
pass
def verticalSpacing(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
AllNonFixedFieldsGrow = PySide.QtGui.QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow
DontWrapRows = PySide.QtGui.QFormLayout.RowWrapPolicy.DontWrapRows
ExpandingFieldsGrow = PySide.QtGui.QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow
FieldGrowthPolicy = None # (!) real value is "<type 'PySide.QtGui.QFormLayout.FieldGrowthPolicy'>"
FieldRole = PySide.QtGui.QFormLayout.ItemRole.FieldRole
FieldsStayAtSizeHint = PySide.QtGui.QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint
ItemRole = None # (!) real value is "<type 'PySide.QtGui.QFormLayout.ItemRole'>"
LabelRole = PySide.QtGui.QFormLayout.ItemRole.LabelRole
RowWrapPolicy = None # (!) real value is "<type 'PySide.QtGui.QFormLayout.RowWrapPolicy'>"
SpanningRole = PySide.QtGui.QFormLayout.ItemRole.SpanningRole
staticMetaObject = None # (!) real value is '<PySide.QtCore.QMetaObject object at 0x0000000003F48208>'
WrapAllRows = PySide.QtGui.QFormLayout.RowWrapPolicy.WrapAllRows
WrapLongRows = PySide.QtGui.QFormLayout.RowWrapPolicy.WrapLongRows
| 31.840278
| 106
| 0.676118
|