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
df5ddc19c88fc1aac8c90b3728de012dd8b0e721
139
jbuilder
Ruby
evaluationserver/app/views/steps/index.json.jbuilder
Lukasz-kal/Getaviz
32bfcd44eee3c6e71b11fe2e60927cafd296ad7f
[ "Apache-2.0" ]
45
2018-08-11T17:35:06.000Z
2022-03-24T17:54:26.000Z
evaluationserver/app/views/steps/index.json.jbuilder
Lukasz-kal/Getaviz
32bfcd44eee3c6e71b11fe2e60927cafd296ad7f
[ "Apache-2.0" ]
96
2018-07-09T14:17:11.000Z
2022-03-30T22:30:06.000Z
evaluationserver/app/views/steps/index.json.jbuilder
Lukasz-kal/Getaviz
32bfcd44eee3c6e71b11fe2e60927cafd296ad7f
[ "Apache-2.0" ]
57
2018-07-06T12:16:17.000Z
2022-03-30T07:05:05.000Z
json.array!(@scenes) do |scene| json.extract! scene, :id, :title, :description, :filename json.url scene_url(scene, format: :json) end
27.8
59
0.705036
419598390c7766fd4f4b8727d8041dac876a7820
3,000
h
C
source/blender/imbuf/intern/IMB_metadata.h
wycivil08/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
30
2015-01-29T14:06:05.000Z
2022-01-10T07:47:29.000Z
source/blender/imbuf/intern/IMB_metadata.h
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
1
2017-02-20T20:57:48.000Z
2018-12-19T23:44:38.000Z
source/blender/imbuf/intern/IMB_metadata.h
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
15
2015-04-23T02:38:36.000Z
2021-03-01T20:09:39.000Z
/* * $Id: IMB_metadata.h 35239 2011-02-27 20:23:21Z jesterking $ * * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2005 Blender Foundation * All rights reserved. * * The Original Code is: all of this file. * * Contributor(s): Austin Benesh. Ton Roosendaal. * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/imbuf/intern/IMB_metadata.h * \ingroup imbuf */ #ifndef _IMB_IMGINFO_H #define _IMB_IMGINFO_H struct ImBuf; typedef struct ImMetaData { struct ImMetaData *next, *prev; char* key; char* value; int len; } ImMetaData; /** The metadata is a list of key/value pairs (both char*) that can me saved in the header of several image formats. Apart from some common keys like 'Software' and 'Description' (png standard) we'll use keys within the Blender namespace, so should be called 'Blender::StampInfo' or 'Blender::FrameNum' etc... */ /* free blender ImMetaData struct */ void IMB_metadata_free(struct ImBuf* img); /** read the field from the image info into the field * @param img - the ImBuf that contains the image data * @param key - the key of the field * @param value - the data in the field, first one found with key is returned, memory has to be allocated by user. * @param len - length of value buffer allocated by user. * @return - 1 (true) if ImageInfo present and value for the key found, 0 (false) otherwise */ int IMB_metadata_get_field(struct ImBuf* img, const char* key, char* value, int len); /** set user data in the ImMetaData struct, which has to be allocated with IMB_metadata_create * before calling this function. * @param img - the ImBuf that contains the image data * @param key - the key of the field * @param value - the data to be written to the field. zero terminated string * @return - 1 (true) if ImageInfo present, 0 (false) otherwise */ int IMB_metadata_add_field(struct ImBuf* img, const char* key, const char* field); /** delete the key/field par in the ImMetaData struct. * @param img - the ImBuf that contains the image data * @param key - the key of the field * @return - 1 (true) if delete the key/field, 0 (false) otherwise */ int IMB_metadata_del_field(struct ImBuf *img, const char *key); #endif /* _IMB_IMGINFO_H */
34.883721
95
0.715667
f05d0a3641c60e67514c1823da24f5eae7e8f916
1,282
js
JavaScript
app/scripts/admin/UI/UIDirective.js
HanSeungHo/pinkpink
24eed78a9b61ee163d99dc68137f4f40170b0a89
[ "MIT" ]
null
null
null
app/scripts/admin/UI/UIDirective.js
HanSeungHo/pinkpink
24eed78a9b61ee163d99dc68137f4f40170b0a89
[ "MIT" ]
1
2015-07-24T13:36:10.000Z
2015-07-24T13:36:10.000Z
app/scripts/admin/UI/UIDirective.js
HanSeungHo/pinkpink
24eed78a9b61ee163d99dc68137f4f40170b0a89
[ "MIT" ]
null
null
null
(function() { 'use strict'; angular.module('app.ui.directives', []).directive('uiTime', [ function() { return { restrict: 'A', link: function(scope, ele) { var checkTime, startTime; startTime = function() { var h, m, s, t, time, today; today = new Date(); h = today.getHours(); m = today.getMinutes(); s = today.getSeconds(); m = checkTime(m); s = checkTime(s); time = h + ":" + m + ":" + s; ele.html(time); return t = setTimeout(startTime, 500); }; checkTime = function(i) { if (i < 10) { i = "0" + i; } return i; }; return startTime(); } }; } ]).directive('uiWeather', [ function() { return { restrict: 'A', link: function(scope, ele, attrs) { var color, icon, skycons; color = attrs.color; icon = Skycons[attrs.icon]; skycons = new Skycons({ "color": color, "resizeClear": true }); skycons.add(ele[0], icon); return skycons.play(); } }; } ]); }).call(this);
25.137255
63
0.418877
75ba48948064a9e980787093c2871bb1cadb0143
2,412
sql
SQL
scripts/functions/ppa_fn_verifica_homologacao.sql
evandojunior/urbem3.0
ba8d54109e51e82b689d1881e582fb0bce4375e0
[ "MIT" ]
null
null
null
scripts/functions/ppa_fn_verifica_homologacao.sql
evandojunior/urbem3.0
ba8d54109e51e82b689d1881e582fb0bce4375e0
[ "MIT" ]
null
null
null
scripts/functions/ppa_fn_verifica_homologacao.sql
evandojunior/urbem3.0
ba8d54109e51e82b689d1881e582fb0bce4375e0
[ "MIT" ]
1
2020-01-29T20:35:57.000Z
2020-01-29T20:35:57.000Z
CREATE OR REPLACE FUNCTION ppa.fn_verifica_homologacao(incodppa integer) RETURNS boolean LANGUAGE plpgsql AS $function$ DECLARE reRegistro RECORD; boRetorno BOOLEAN = false; stSql VARCHAR := ''; tpTimestampPublicacao TIMESTAMP; tpTimestampMacroObjetivo TIMESTAMP; tpTimestampProgramaSetorial TIMESTAMP; tpTimestampPrograma TIMESTAMP; tpTimestampAcao TIMESTAMP; BEGIN SELECT MAX(timestamp) INTO tpTimestampPublicacao FROM ppa.ppa_publicacao WHERE cod_ppa = inCodPPA; IF (tpTimestampPublicacao IS NOT NULL) THEN SELECT MAX(macro_objetivo.timestamp) INTO tpTimestampMacroObjetivo FROM ppa.macro_objetivo WHERE macro_objetivo.cod_ppa = inCodPPA; SELECT MAX(programa_setorial.timestamp) INTO tpTimestampProgramaSetorial FROM ppa.macro_objetivo JOIN ppa.programa_setorial ON programa_setorial.cod_macro = macro_objetivo.cod_macro WHERE macro_objetivo.cod_ppa = inCodPPA; SELECT MAX(programa.ultimo_timestamp_programa_dados) INTO tpTimestampPrograma FROM ppa.macro_objetivo JOIN ppa.programa_setorial ON programa_setorial.cod_macro = macro_objetivo.cod_macro JOIN ppa.programa ON programa.cod_setorial = programa_setorial.cod_setorial WHERE macro_objetivo.cod_ppa = inCodPPA; SELECT MAX(acao.ultimo_timestamp_acao_dados) INTO tpTimestampAcao FROM ppa.macro_objetivo JOIN ppa.programa_setorial ON programa_setorial.cod_macro = macro_objetivo.cod_macro JOIN ppa.programa ON programa.cod_setorial = programa_setorial.cod_setorial JOIN ppa.acao ON acao.cod_programa = programa.cod_programa WHERE macro_objetivo.cod_ppa = inCodPPA; IF (tpTimestampPublicacao > tpTimestampMacroObjetivo AND tpTimestampPublicacao > tpTimestampProgramaSetorial AND tpTimestampPublicacao > tpTimestampPrograma AND tpTimestampPublicacao > tpTimestampAcao) THEN -- o PPA está homologado boRetorno = true; ELSE -- o PPA não está homologado boRetorno = false; END IF; END IF; RETURN boRetorno; END; $function$
33.5
72
0.666252
dc3969da86a39d6a77b945e4af8f9269eacb2393
986
asm
Assembly
programs/oeis/099/A099923.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/099/A099923.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/099/A099923.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A099923: Fourth powers of Lucas numbers A000032. ; 16,1,81,256,2401,14641,104976,707281,4879681,33362176,228886641,1568239201,10750371856,73680216481,505022001201,3461445366016,23725169980801,162614549665681,1114577187760656,7639424429247601,52361397313124641,358890347609579776,2459871059916916881,16860207009072934081,115561578167838351376,792070839735797240641,5428934301108492458001,37210469265076397875456,255044350562142298814881,1748099984649718927484401,11981655542038776486464016,82123488809483258365443601,562882766124706520115713281,3858055874062513376424653056,26443508352315371644872474801,181246502592138583553655716641,1242282009792671742452782786576,8514727565956519030533655008481,58360810951903078191307243370481,400010949097364722731625894072576,2741715832729650780941023037576641,18791999880010188649399679456158801,128802283327341675248213351871511056,882823983411381523732479783409295281 seq $0,156279 ; 4 times the Lucas number A000032(n). pow $0,4 div $0,256
140.857143
860
0.91785
7c0e77a3afe4949938c422022099e4ad0c142637
1,140
kt
Kotlin
restdoc-web/src/main/kotlin/restdoc/web/model/HttpApiTestLog.kt
Overman-mxf/rest-doc
3cdf9de7593c78c819b3dadc9b583e736041d55f
[ "Apache-2.0" ]
2
2020-08-05T11:13:30.000Z
2020-08-08T02:23:12.000Z
restdoc-web/src/main/kotlin/restdoc/web/model/HttpApiTestLog.kt
Overman-mxf/rest-doc
3cdf9de7593c78c819b3dadc9b583e736041d55f
[ "Apache-2.0" ]
5
2020-08-20T08:22:32.000Z
2020-09-10T04:45:04.000Z
restdoc-web/src/main/kotlin/restdoc/web/model/HttpApiTestLog.kt
Overman-mxf/rest-doc
3cdf9de7593c78c819b3dadc9b583e736041d55f
[ "Apache-2.0" ]
1
2020-08-05T11:13:32.000Z
2020-08-05T11:13:32.000Z
package restdoc.web.model import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.index.HashIndexed import org.springframework.data.mongodb.core.mapping.Document import org.springframework.http.HttpMethod import java.util.* /** * WebApiTestLog * * * WebApiTestLog => {HeaderFieldDescriptor, BodyFieldDescriptor} */ @Document(collection = HTTP_API_TEST_LOG_COLLECTION) class HttpApiTestLog { @Id var id: String? = null var success: Boolean = true var remote: String? = null @HashIndexed var documentId: String? = null var url: String? = null var method: HttpMethod? = HttpMethod.GET var uriParameters: Map<String, Any>? = null var queryParameters: Map<String, Any>? = null var requestHeaderParameters: Map<String, String>? = null var requestBodyParameters: Map<String, Any>? = null var responseStatus: Int = 200 var responseHeader: Map<String, List<String>>? = null var responseBody: Any? = null var testDurationTimeMill: Long? = null var testMode: TestMode = TestMode.RPC var createTime: Long? = Date().time }
21.923077
64
0.714912
821155d2fd2983f276b7d3fa594f1562ba5d68ba
4,470
kt
Kotlin
ZimLX/src/org/zimmob/zimlx/adaptive/IconShapeManager.kt
damoasda/ZimLX
0a52e0fcb7a068135d938da4d93d5b0ac91d95fa
[ "Apache-2.0" ]
null
null
null
ZimLX/src/org/zimmob/zimlx/adaptive/IconShapeManager.kt
damoasda/ZimLX
0a52e0fcb7a068135d938da4d93d5b0ac91d95fa
[ "Apache-2.0" ]
null
null
null
ZimLX/src/org/zimmob/zimlx/adaptive/IconShapeManager.kt
damoasda/ZimLX
0a52e0fcb7a068135d938da4d93d5b0ac91d95fa
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 paphonb@xda * * This file is part of Lawnchair Launcher. * * Lawnchair Launcher is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Lawnchair Launcher is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Lawnchair Launcher. If not, see <https://www.gnu.org/licenses/>. */ package org.zimmob.zimlx.adaptive import android.annotation.SuppressLint import android.content.Context import android.graphics.Path import android.graphics.Rect import android.graphics.Region import android.graphics.RegionIterator import android.graphics.drawable.AdaptiveIconDrawable import android.os.Handler import android.text.TextUtils import androidx.core.graphics.PathParser import com.android.launcher3.LauncherAppState import com.android.launcher3.LauncherModel import com.android.launcher3.Utilities import com.android.launcher3.graphics.IconShapeOverride import org.zimmob.zimlx.folder.FolderShape import org.zimmob.zimlx.iconpack.AdaptiveIconCompat import org.zimmob.zimlx.runOnMainThread import org.zimmob.zimlx.util.ZimFlags.THEME_ICON_SHAPE import org.zimmob.zimlx.util.ZimSingletonHolder import org.zimmob.zimlx.zimPrefs class IconShapeManager(private val context: Context) { private val systemIconShape = getSystemShape() var iconShape by context.zimPrefs.StringBasedPref( THEME_ICON_SHAPE, systemIconShape, ::onShapeChanged, { IconShape.fromString(it) ?: systemIconShape }, IconShape::toString) { /* no dispose */ } init { migratePref() } @SuppressLint("RestrictedApi") private fun migratePref() { // Migrate from old path-based override val override = IconShapeOverride.getAppliedValue(context) if (!TextUtils.isEmpty(override)) { try { iconShape = findNearestShape(PathParser.createPathFromPathData(override)) Utilities.getPrefs(context).edit().remove(THEME_ICON_SHAPE).apply() } catch (e: RuntimeException) { // Just ignore the error } } } private fun getSystemShape(): IconShape { if (!Utilities.ATLEAST_OREO) return IconShape.Circle val iconMask = AdaptiveIconDrawable(null, null).iconMask val systemShape = findNearestShape(iconMask) return object : IconShape(systemShape) { override fun getMaskPath(): Path { return Path(iconMask) } override fun toString() = "" } } private fun findNearestShape(comparePath: Path): IconShape { val clip = Region(0, 0, 100, 100) val systemRegion = Region().apply { setPath(comparePath, clip) } val pathRegion = Region() val path = Path() val rect = Rect() return listOf( IconShape.Circle, IconShape.Square, IconShape.RoundedSquare, IconShape.Squircle, IconShape.Teardrop, IconShape.Cylinder).minBy { path.reset() it.addShape(path, 0f, 0f, 50f) pathRegion.setPath(path, clip) pathRegion.op(systemRegion, Region.Op.XOR) var difference = 0 val iter = RegionIterator(pathRegion) while (iter.next(rect)) { difference += rect.width() * rect.height() } difference }!! } private fun onShapeChanged() { Handler(LauncherModel.getWorkerLooper()).post { LauncherAppState.getInstance(context).reloadIconCache() runOnMainThread { AdaptiveIconCompat.resetMask() FolderShape.init(context) context.zimPrefs.recreate() } } } companion object : ZimSingletonHolder<IconShapeManager>(::IconShapeManager) { @JvmStatic fun getInstanceNoCreate() = dangerousGetInstance() } }
33.609023
89
0.650112
d9b796d063e2631ece96f46d89ea525cadd4be31
34,054
rs
Rust
src/librustc/traits/structural_impls.rs
byteset/rust
97fba3ccfc2f1299048342c59c5e9b62cc11ef66
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2021-08-13T16:21:02.000Z
2021-08-13T16:21:02.000Z
src/librustc/traits/structural_impls.rs
byteset/rust
97fba3ccfc2f1299048342c59c5e9b62cc11ef66
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
src/librustc/traits/structural_impls.rs
byteset/rust
97fba3ccfc2f1299048342c59c5e9b62cc11ef66
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
use chalk_engine; use smallvec::SmallVec; use crate::traits; use crate::traits::project::Normalized; use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor}; use crate::ty::{self, Lift, Ty, TyCtxt}; use syntax::symbol::Symbol; use std::fmt; use std::rc::Rc; use std::collections::{BTreeSet, BTreeMap}; // Structural impls for the structs in `traits`. impl<'tcx, T: fmt::Debug> fmt::Debug for Normalized<'tcx, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Normalized({:?}, {:?})", self.value, self.obligations) } } impl<'tcx, O: fmt::Debug> fmt::Debug for traits::Obligation<'tcx, O> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if ty::tls::with(|tcx| tcx.sess.verbose()) { write!( f, "Obligation(predicate={:?}, cause={:?}, param_env={:?}, depth={})", self.predicate, self.cause, self.param_env, self.recursion_depth ) } else { write!( f, "Obligation(predicate={:?}, depth={})", self.predicate, self.recursion_depth ) } } } impl<'tcx, N: fmt::Debug> fmt::Debug for traits::Vtable<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { super::VtableImpl(ref v) => write!(f, "{:?}", v), super::VtableAutoImpl(ref t) => write!(f, "{:?}", t), super::VtableClosure(ref d) => write!(f, "{:?}", d), super::VtableGenerator(ref d) => write!(f, "{:?}", d), super::VtableFnPointer(ref d) => write!(f, "VtableFnPointer({:?})", d), super::VtableObject(ref d) => write!(f, "{:?}", d), super::VtableParam(ref n) => write!(f, "VtableParam({:?})", n), super::VtableBuiltin(ref d) => write!(f, "{:?}", d), super::VtableTraitAlias(ref d) => write!(f, "{:?}", d), } } } impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableImplData<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "VtableImplData(impl_def_id={:?}, substs={:?}, nested={:?})", self.impl_def_id, self.substs, self.nested ) } } impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableGeneratorData<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "VtableGeneratorData(generator_def_id={:?}, substs={:?}, nested={:?})", self.generator_def_id, self.substs, self.nested ) } } impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableClosureData<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "VtableClosureData(closure_def_id={:?}, substs={:?}, nested={:?})", self.closure_def_id, self.substs, self.nested ) } } impl<N: fmt::Debug> fmt::Debug for traits::VtableBuiltinData<N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "VtableBuiltinData(nested={:?})", self.nested) } } impl<N: fmt::Debug> fmt::Debug for traits::VtableAutoImplData<N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "VtableAutoImplData(trait_def_id={:?}, nested={:?})", self.trait_def_id, self.nested ) } } impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableObjectData<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "VtableObjectData(upcast={:?}, vtable_base={}, nested={:?})", self.upcast_trait_ref, self.vtable_base, self.nested ) } } impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableFnPointerData<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "VtableFnPointerData(fn_ty={:?}, nested={:?})", self.fn_ty, self.nested ) } } impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableTraitAliasData<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "VtableTraitAlias(alias_def_id={:?}, substs={:?}, nested={:?})", self.alias_def_id, self.substs, self.nested ) } } impl<'tcx> fmt::Debug for traits::FulfillmentError<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "FulfillmentError({:?},{:?})", self.obligation, self.code) } } impl<'tcx> fmt::Debug for traits::FulfillmentErrorCode<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { super::CodeSelectionError(ref e) => write!(f, "{:?}", e), super::CodeProjectionError(ref e) => write!(f, "{:?}", e), super::CodeSubtypeError(ref a, ref b) => { write!(f, "CodeSubtypeError({:?}, {:?})", a, b) } super::CodeAmbiguity => write!(f, "Ambiguity"), } } } impl<'tcx> fmt::Debug for traits::MismatchedProjectionTypes<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MismatchedProjectionTypes({:?})", self.err) } } impl<'tcx> fmt::Display for traits::WhereClause<'tcx> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use crate::traits::WhereClause::*; // Bypass `ty::print` because it does not print out anonymous regions. // FIXME(eddyb) implement a custom `PrettyPrinter`, or move this to `ty::print`. fn write_region_name<'tcx>( r: ty::Region<'tcx>, fmt: &mut fmt::Formatter<'_> ) -> fmt::Result { match r { ty::ReLateBound(index, br) => match br { ty::BoundRegion::BrNamed(_, name) => write!(fmt, "{}", name), ty::BoundRegion::BrAnon(var) => { if *index == ty::INNERMOST { write!(fmt, "'^{}", var) } else { write!(fmt, "'^{}_{}", index.index(), var) } } _ => write!(fmt, "'_"), } _ => write!(fmt, "{}", r), } } match self { Implemented(trait_ref) => write!(fmt, "Implemented({})", trait_ref), ProjectionEq(projection) => write!(fmt, "ProjectionEq({})", projection), RegionOutlives(predicate) => { write!(fmt, "RegionOutlives({}: ", predicate.0)?; write_region_name(predicate.1, fmt)?; write!(fmt, ")") } TypeOutlives(predicate) => { write!(fmt, "TypeOutlives({}: ", predicate.0)?; write_region_name(predicate.1, fmt)?; write!(fmt, ")") } } } } impl<'tcx> fmt::Display for traits::WellFormed<'tcx> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use crate::traits::WellFormed::*; match self { Trait(trait_ref) => write!(fmt, "WellFormed({})", trait_ref), Ty(ty) => write!(fmt, "WellFormed({})", ty), } } } impl<'tcx> fmt::Display for traits::FromEnv<'tcx> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use crate::traits::FromEnv::*; match self { Trait(trait_ref) => write!(fmt, "FromEnv({})", trait_ref), Ty(ty) => write!(fmt, "FromEnv({})", ty), } } } impl<'tcx> fmt::Display for traits::DomainGoal<'tcx> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use crate::traits::DomainGoal::*; match self { Holds(wc) => write!(fmt, "{}", wc), WellFormed(wf) => write!(fmt, "{}", wf), FromEnv(from_env) => write!(fmt, "{}", from_env), Normalize(projection) => write!( fmt, "Normalize({} -> {})", projection.projection_ty, projection.ty ), } } } impl fmt::Display for traits::QuantifierKind { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use crate::traits::QuantifierKind::*; match self { Universal => write!(fmt, "forall"), Existential => write!(fmt, "exists"), } } } /// Collect names for regions / types bound by a quantified goal / clause. /// This collector does not try to do anything clever like in `ty::print`, it's just used /// for debug output in tests anyway. struct BoundNamesCollector { // Just sort by name because `BoundRegion::BrNamed` does not have a `BoundVar` index anyway. regions: BTreeSet<Symbol>, // Sort by `BoundVar` index, so usually this should be equivalent to the order given // by the list of type parameters. types: BTreeMap<u32, Symbol>, binder_index: ty::DebruijnIndex, } impl BoundNamesCollector { fn new() -> Self { BoundNamesCollector { regions: BTreeSet::new(), types: BTreeMap::new(), binder_index: ty::INNERMOST, } } fn is_empty(&self) -> bool { self.regions.is_empty() && self.types.is_empty() } fn write_names(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut start = true; for r in &self.regions { if !start { write!(fmt, ", ")?; } start = false; write!(fmt, "{}", r)?; } for (_, t) in &self.types { if !start { write!(fmt, ", ")?; } start = false; write!(fmt, "{}", t)?; } Ok(()) } } impl<'tcx> TypeVisitor<'tcx> for BoundNamesCollector { fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool { self.binder_index.shift_in(1); let result = t.super_visit_with(self); self.binder_index.shift_out(1); result } fn visit_ty(&mut self, t: Ty<'tcx>) -> bool { match t.kind { ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => { self.types.insert( bound_ty.var.as_u32(), match bound_ty.kind { ty::BoundTyKind::Param(name) => name, ty::BoundTyKind::Anon => Symbol::intern(&format!("^{}", bound_ty.var.as_u32()), ), } ); } _ => (), }; t.super_visit_with(self) } fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool { match r { ty::ReLateBound(index, br) if *index == self.binder_index => { match br { ty::BoundRegion::BrNamed(_, name) => { self.regions.insert(*name); } ty::BoundRegion::BrAnon(var) => { self.regions.insert(Symbol::intern(&format!("'^{}", var))); } _ => (), } } _ => (), }; r.super_visit_with(self) } } impl<'tcx> fmt::Display for traits::Goal<'tcx> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use crate::traits::GoalKind::*; match self { Implies(hypotheses, goal) => { write!(fmt, "if (")?; for (index, hyp) in hypotheses.iter().enumerate() { if index > 0 { write!(fmt, ", ")?; } write!(fmt, "{}", hyp)?; } write!(fmt, ") {{ {} }}", goal) } And(goal1, goal2) => write!(fmt, "({} && {})", goal1, goal2), Not(goal) => write!(fmt, "not {{ {} }}", goal), DomainGoal(goal) => write!(fmt, "{}", goal), Quantified(qkind, goal) => { let mut collector = BoundNamesCollector::new(); goal.skip_binder().visit_with(&mut collector); if !collector.is_empty() { write!(fmt, "{}<", qkind)?; collector.write_names(fmt)?; write!(fmt, "> {{ ")?; } write!(fmt, "{}", goal.skip_binder())?; if !collector.is_empty() { write!(fmt, " }}")?; } Ok(()) } Subtype(a, b) => write!(fmt, "{} <: {}", a, b), CannotProve => write!(fmt, "CannotProve"), } } } impl<'tcx> fmt::Display for traits::ProgramClause<'tcx> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let traits::ProgramClause { goal, hypotheses, .. } = self; write!(fmt, "{}", goal)?; if !hypotheses.is_empty() { write!(fmt, " :- ")?; for (index, condition) in hypotheses.iter().enumerate() { if index > 0 { write!(fmt, ", ")?; } write!(fmt, "{}", condition)?; } } write!(fmt, ".") } } impl<'tcx> fmt::Display for traits::Clause<'tcx> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use crate::traits::Clause::*; match self { Implies(clause) => write!(fmt, "{}", clause), ForAll(clause) => { let mut collector = BoundNamesCollector::new(); clause.skip_binder().visit_with(&mut collector); if !collector.is_empty() { write!(fmt, "forall<")?; collector.write_names(fmt)?; write!(fmt, "> {{ ")?; } write!(fmt, "{}", clause.skip_binder())?; if !collector.is_empty() { write!(fmt, " }}")?; } Ok(()) } } } } /////////////////////////////////////////////////////////////////////////// // Lift implementations impl<'a, 'tcx> Lift<'tcx> for traits::SelectionError<'a> { type Lifted = traits::SelectionError<'tcx>; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { match *self { super::Unimplemented => Some(super::Unimplemented), super::OutputTypeParameterMismatch(a, b, ref err) => { tcx.lift(&(a, b)).and_then(|(a, b)| tcx.lift(err) .map(|err| super::OutputTypeParameterMismatch(a, b, err)) ) } super::TraitNotObjectSafe(def_id) => Some(super::TraitNotObjectSafe(def_id)), super::ConstEvalFailure(err) => Some(super::ConstEvalFailure(err)), super::Overflow => Some(super::Overflow), } } } impl<'a, 'tcx> Lift<'tcx> for traits::ObligationCauseCode<'a> { type Lifted = traits::ObligationCauseCode<'tcx>; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { match *self { super::ReturnNoExpression => Some(super::ReturnNoExpression), super::MiscObligation => Some(super::MiscObligation), super::SliceOrArrayElem => Some(super::SliceOrArrayElem), super::TupleElem => Some(super::TupleElem), super::ProjectionWf(proj) => tcx.lift(&proj).map(super::ProjectionWf), super::ItemObligation(def_id) => Some(super::ItemObligation(def_id)), super::BindingObligation(def_id, span) => Some(super::BindingObligation(def_id, span)), super::ReferenceOutlivesReferent(ty) => { tcx.lift(&ty).map(super::ReferenceOutlivesReferent) } super::ObjectTypeBound(ty, r) => tcx.lift(&ty).and_then(|ty| tcx.lift(&r) .and_then(|r| Some(super::ObjectTypeBound(ty, r))) ), super::ObjectCastObligation(ty) => tcx.lift(&ty).map(super::ObjectCastObligation), super::Coercion { source, target } => Some(super::Coercion { source: tcx.lift(&source)?, target: tcx.lift(&target)?, }), super::AssignmentLhsSized => Some(super::AssignmentLhsSized), super::TupleInitializerSized => Some(super::TupleInitializerSized), super::StructInitializerSized => Some(super::StructInitializerSized), super::VariableType(id) => Some(super::VariableType(id)), super::ReturnValue(id) => Some(super::ReturnValue(id)), super::ReturnType => Some(super::ReturnType), super::SizedArgumentType => Some(super::SizedArgumentType), super::SizedReturnType => Some(super::SizedReturnType), super::SizedYieldType => Some(super::SizedYieldType), super::RepeatVec => Some(super::RepeatVec), super::FieldSized { adt_kind, last } => Some(super::FieldSized { adt_kind, last }), super::ConstSized => Some(super::ConstSized), super::ConstPatternStructural => Some(super::ConstPatternStructural), super::SharedStatic => Some(super::SharedStatic), super::BuiltinDerivedObligation(ref cause) => { tcx.lift(cause).map(super::BuiltinDerivedObligation) } super::ImplDerivedObligation(ref cause) => { tcx.lift(cause).map(super::ImplDerivedObligation) } super::CompareImplMethodObligation { item_name, impl_item_def_id, trait_item_def_id, } => Some(super::CompareImplMethodObligation { item_name, impl_item_def_id, trait_item_def_id, }), super::ExprAssignable => Some(super::ExprAssignable), super::MatchExpressionArm(box super::MatchExpressionArmCause { arm_span, source, ref prior_arms, last_ty, discrim_hir_id, }) => { tcx.lift(&last_ty).map(|last_ty| { super::MatchExpressionArm(box super::MatchExpressionArmCause { arm_span, source, prior_arms: prior_arms.clone(), last_ty, discrim_hir_id, }) }) } super::MatchExpressionArmPattern { span, ty } => { tcx.lift(&ty).map(|ty| super::MatchExpressionArmPattern { span, ty }) } super::IfExpression(box super::IfExpressionCause { then, outer, semicolon }) => { Some(super::IfExpression(box super::IfExpressionCause { then, outer, semicolon, })) } super::IfExpressionWithNoElse => Some(super::IfExpressionWithNoElse), super::MainFunctionType => Some(super::MainFunctionType), super::StartFunctionType => Some(super::StartFunctionType), super::IntrinsicType => Some(super::IntrinsicType), super::MethodReceiver => Some(super::MethodReceiver), super::BlockTailExpression(id) => Some(super::BlockTailExpression(id)), super::TrivialBound => Some(super::TrivialBound), super::AssocTypeBound(impl_sp, sp) => Some(super::AssocTypeBound(impl_sp, sp)), } } } impl<'a, 'tcx> Lift<'tcx> for traits::DerivedObligationCause<'a> { type Lifted = traits::DerivedObligationCause<'tcx>; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { tcx.lift(&self.parent_trait_ref).and_then(|trait_ref| tcx.lift(&*self.parent_code) .map(|code| traits::DerivedObligationCause { parent_trait_ref: trait_ref, parent_code: Rc::new(code), }) ) } } impl<'a, 'tcx> Lift<'tcx> for traits::ObligationCause<'a> { type Lifted = traits::ObligationCause<'tcx>; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { tcx.lift(&self.code).map(|code| traits::ObligationCause { span: self.span, body_id: self.body_id, code, }) } } // For codegen only. impl<'a, 'tcx> Lift<'tcx> for traits::Vtable<'a, ()> { type Lifted = traits::Vtable<'tcx, ()>; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { match self.clone() { traits::VtableImpl(traits::VtableImplData { impl_def_id, substs, nested, }) => tcx.lift(&substs).map(|substs| traits::VtableImpl(traits::VtableImplData { impl_def_id, substs, nested, }) ), traits::VtableAutoImpl(t) => Some(traits::VtableAutoImpl(t)), traits::VtableGenerator(traits::VtableGeneratorData { generator_def_id, substs, nested, }) => tcx.lift(&substs).map(|substs| traits::VtableGenerator(traits::VtableGeneratorData { generator_def_id: generator_def_id, substs: substs, nested: nested, }) ), traits::VtableClosure(traits::VtableClosureData { closure_def_id, substs, nested, }) => tcx.lift(&substs).map(|substs| traits::VtableClosure(traits::VtableClosureData { closure_def_id, substs, nested, }) ), traits::VtableFnPointer(traits::VtableFnPointerData { fn_ty, nested }) => { tcx.lift(&fn_ty).map(|fn_ty| traits::VtableFnPointer(traits::VtableFnPointerData { fn_ty, nested }) ) } traits::VtableParam(n) => Some(traits::VtableParam(n)), traits::VtableBuiltin(n) => Some(traits::VtableBuiltin(n)), traits::VtableObject(traits::VtableObjectData { upcast_trait_ref, vtable_base, nested, }) => tcx.lift(&upcast_trait_ref).map(|trait_ref| traits::VtableObject(traits::VtableObjectData { upcast_trait_ref: trait_ref, vtable_base, nested, }) ), traits::VtableTraitAlias(traits::VtableTraitAliasData { alias_def_id, substs, nested, }) => tcx.lift(&substs).map(|substs| traits::VtableTraitAlias(traits::VtableTraitAliasData { alias_def_id, substs, nested, }) ), } } } EnumLiftImpl! { impl<'a, 'tcx> Lift<'tcx> for traits::WhereClause<'a> { type Lifted = traits::WhereClause<'tcx>; (traits::WhereClause::Implemented)(trait_ref), (traits::WhereClause::ProjectionEq)(projection), (traits::WhereClause::TypeOutlives)(ty_outlives), (traits::WhereClause::RegionOutlives)(region_outlives), } } EnumLiftImpl! { impl<'a, 'tcx> Lift<'tcx> for traits::WellFormed<'a> { type Lifted = traits::WellFormed<'tcx>; (traits::WellFormed::Trait)(trait_ref), (traits::WellFormed::Ty)(ty), } } EnumLiftImpl! { impl<'a, 'tcx> Lift<'tcx> for traits::FromEnv<'a> { type Lifted = traits::FromEnv<'tcx>; (traits::FromEnv::Trait)(trait_ref), (traits::FromEnv::Ty)(ty), } } EnumLiftImpl! { impl<'a, 'tcx> Lift<'tcx> for traits::DomainGoal<'a> { type Lifted = traits::DomainGoal<'tcx>; (traits::DomainGoal::Holds)(wc), (traits::DomainGoal::WellFormed)(wf), (traits::DomainGoal::FromEnv)(from_env), (traits::DomainGoal::Normalize)(projection), } } EnumLiftImpl! { impl<'a, 'tcx> Lift<'tcx> for traits::GoalKind<'a> { type Lifted = traits::GoalKind<'tcx>; (traits::GoalKind::Implies)(hypotheses, goal), (traits::GoalKind::And)(goal1, goal2), (traits::GoalKind::Not)(goal), (traits::GoalKind::DomainGoal)(domain_goal), (traits::GoalKind::Quantified)(kind, goal), (traits::GoalKind::Subtype)(a, b), (traits::GoalKind::CannotProve), } } impl<'a, 'tcx> Lift<'tcx> for traits::Environment<'a> { type Lifted = traits::Environment<'tcx>; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { tcx.lift(&self.clauses).map(|clauses| { traits::Environment { clauses, } }) } } impl<'a, 'tcx, G: Lift<'tcx>> Lift<'tcx> for traits::InEnvironment<'a, G> { type Lifted = traits::InEnvironment<'tcx, G::Lifted>; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { tcx.lift(&self.environment).and_then(|environment| { tcx.lift(&self.goal).map(|goal| { traits::InEnvironment { environment, goal, } }) }) } } impl<'tcx, C> Lift<'tcx> for chalk_engine::ExClause<C> where C: chalk_engine::context::Context + Clone, C: traits::ChalkContextLift<'tcx>, { type Lifted = C::LiftedExClause; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { <C as traits::ChalkContextLift>::lift_ex_clause_to_tcx(self, tcx) } } impl<'tcx, C> Lift<'tcx> for chalk_engine::DelayedLiteral<C> where C: chalk_engine::context::Context + Clone, C: traits::ChalkContextLift<'tcx>, { type Lifted = C::LiftedDelayedLiteral; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { <C as traits::ChalkContextLift>::lift_delayed_literal_to_tcx(self, tcx) } } impl<'tcx, C> Lift<'tcx> for chalk_engine::Literal<C> where C: chalk_engine::context::Context + Clone, C: traits::ChalkContextLift<'tcx>, { type Lifted = C::LiftedLiteral; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { <C as traits::ChalkContextLift>::lift_literal_to_tcx(self, tcx) } } /////////////////////////////////////////////////////////////////////////// // TypeFoldable implementations. impl<'tcx, O: TypeFoldable<'tcx>> TypeFoldable<'tcx> for traits::Obligation<'tcx, O> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { traits::Obligation { cause: self.cause.clone(), recursion_depth: self.recursion_depth, predicate: self.predicate.fold_with(folder), param_env: self.param_env.fold_with(folder), } } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { self.predicate.visit_with(visitor) } } BraceStructTypeFoldableImpl! { impl<'tcx, N> TypeFoldable<'tcx> for traits::VtableImplData<'tcx, N> { impl_def_id, substs, nested } where N: TypeFoldable<'tcx> } BraceStructTypeFoldableImpl! { impl<'tcx, N> TypeFoldable<'tcx> for traits::VtableGeneratorData<'tcx, N> { generator_def_id, substs, nested } where N: TypeFoldable<'tcx> } BraceStructTypeFoldableImpl! { impl<'tcx, N> TypeFoldable<'tcx> for traits::VtableClosureData<'tcx, N> { closure_def_id, substs, nested } where N: TypeFoldable<'tcx> } BraceStructTypeFoldableImpl! { impl<'tcx, N> TypeFoldable<'tcx> for traits::VtableAutoImplData<N> { trait_def_id, nested } where N: TypeFoldable<'tcx> } BraceStructTypeFoldableImpl! { impl<'tcx, N> TypeFoldable<'tcx> for traits::VtableBuiltinData<N> { nested } where N: TypeFoldable<'tcx> } BraceStructTypeFoldableImpl! { impl<'tcx, N> TypeFoldable<'tcx> for traits::VtableObjectData<'tcx, N> { upcast_trait_ref, vtable_base, nested } where N: TypeFoldable<'tcx> } BraceStructTypeFoldableImpl! { impl<'tcx, N> TypeFoldable<'tcx> for traits::VtableFnPointerData<'tcx, N> { fn_ty, nested } where N: TypeFoldable<'tcx> } BraceStructTypeFoldableImpl! { impl<'tcx, N> TypeFoldable<'tcx> for traits::VtableTraitAliasData<'tcx, N> { alias_def_id, substs, nested } where N: TypeFoldable<'tcx> } EnumTypeFoldableImpl! { impl<'tcx, N> TypeFoldable<'tcx> for traits::Vtable<'tcx, N> { (traits::VtableImpl)(a), (traits::VtableAutoImpl)(a), (traits::VtableGenerator)(a), (traits::VtableClosure)(a), (traits::VtableFnPointer)(a), (traits::VtableParam)(a), (traits::VtableBuiltin)(a), (traits::VtableObject)(a), (traits::VtableTraitAlias)(a), } where N: TypeFoldable<'tcx> } BraceStructTypeFoldableImpl! { impl<'tcx, T> TypeFoldable<'tcx> for Normalized<'tcx, T> { value, obligations } where T: TypeFoldable<'tcx> } EnumTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for traits::WhereClause<'tcx> { (traits::WhereClause::Implemented)(trait_ref), (traits::WhereClause::ProjectionEq)(projection), (traits::WhereClause::TypeOutlives)(ty_outlives), (traits::WhereClause::RegionOutlives)(region_outlives), } } EnumTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for traits::WellFormed<'tcx> { (traits::WellFormed::Trait)(trait_ref), (traits::WellFormed::Ty)(ty), } } EnumTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for traits::FromEnv<'tcx> { (traits::FromEnv::Trait)(trait_ref), (traits::FromEnv::Ty)(ty), } } EnumTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for traits::DomainGoal<'tcx> { (traits::DomainGoal::Holds)(wc), (traits::DomainGoal::WellFormed)(wf), (traits::DomainGoal::FromEnv)(from_env), (traits::DomainGoal::Normalize)(projection), } } CloneTypeFoldableAndLiftImpls! { traits::QuantifierKind, } EnumTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for traits::GoalKind<'tcx> { (traits::GoalKind::Implies)(hypotheses, goal), (traits::GoalKind::And)(goal1, goal2), (traits::GoalKind::Not)(goal), (traits::GoalKind::DomainGoal)(domain_goal), (traits::GoalKind::Quantified)(qkind, goal), (traits::GoalKind::Subtype)(a, b), (traits::GoalKind::CannotProve), } } impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<traits::Goal<'tcx>> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { let v = self.iter() .map(|t| t.fold_with(folder)) .collect::<SmallVec<[_; 8]>>(); folder.tcx().intern_goals(&v) } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { self.iter().any(|t| t.visit_with(visitor)) } } impl<'tcx> TypeFoldable<'tcx> for traits::Goal<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { let v = (**self).fold_with(folder); folder.tcx().mk_goal(v) } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { (**self).visit_with(visitor) } } BraceStructTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for traits::ProgramClause<'tcx> { goal, hypotheses, category, } } CloneTypeFoldableAndLiftImpls! { traits::ProgramClauseCategory, } EnumTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for traits::Clause<'tcx> { (traits::Clause::Implies)(clause), (traits::Clause::ForAll)(clause), } } BraceStructTypeFoldableImpl! { impl<'tcx> TypeFoldable<'tcx> for traits::Environment<'tcx> { clauses } } BraceStructTypeFoldableImpl! { impl<'tcx, G> TypeFoldable<'tcx> for traits::InEnvironment<'tcx, G> { environment, goal } where G: TypeFoldable<'tcx> } impl<'tcx> TypeFoldable<'tcx> for traits::Clauses<'tcx> { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { let v = self.iter() .map(|t| t.fold_with(folder)) .collect::<SmallVec<[_; 8]>>(); folder.tcx().intern_clauses(&v) } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { self.iter().any(|t| t.visit_with(visitor)) } } impl<'tcx, C> TypeFoldable<'tcx> for chalk_engine::ExClause<C> where C: traits::ExClauseFold<'tcx>, C::Substitution: Clone, C::RegionConstraint: Clone, { fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self { <C as traits::ExClauseFold>::fold_ex_clause_with( self, folder, ) } fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool { <C as traits::ExClauseFold>::visit_ex_clause_with( self, visitor, ) } } EnumTypeFoldableImpl! { impl<'tcx, C> TypeFoldable<'tcx> for chalk_engine::DelayedLiteral<C> { (chalk_engine::DelayedLiteral::CannotProve)(a), (chalk_engine::DelayedLiteral::Negative)(a), (chalk_engine::DelayedLiteral::Positive)(a, b), } where C: chalk_engine::context::Context<CanonicalConstrainedSubst: TypeFoldable<'tcx>> + Clone, } EnumTypeFoldableImpl! { impl<'tcx, C> TypeFoldable<'tcx> for chalk_engine::Literal<C> { (chalk_engine::Literal::Negative)(a), (chalk_engine::Literal::Positive)(a), } where C: chalk_engine::context::Context<GoalInEnvironment: Clone + TypeFoldable<'tcx>> + Clone, } CloneTypeFoldableAndLiftImpls! { chalk_engine::TableIndex, }
33.817279
99
0.533858
5826d6bc6312dabc066b2477296473fedf4b7d75
796
h
C
MinimalSinkRenderer/Common/MFCriticSection.h
mofo7777/Stackoverflow
20aeebb815f6b9c1492abd54127dfe6b9be65b77
[ "Unlicense" ]
18
2018-10-03T21:49:19.000Z
2021-12-22T13:10:33.000Z
Common/MFCriticSection.h
mofo7777/MediaFoundationTransform
c247648dd4298b264419d72b1d12fd2af9aa1e49
[ "Unlicense" ]
1
2020-06-23T21:28:54.000Z
2020-06-24T18:33:28.000Z
MinimalSinkRenderer/Common/MFCriticSection.h
mofo7777/Stackoverflow
20aeebb815f6b9c1492abd54127dfe6b9be65b77
[ "Unlicense" ]
10
2020-01-01T12:09:41.000Z
2021-12-23T09:21:10.000Z
//---------------------------------------------------------------------------------------------- // MFCriticSection.h //---------------------------------------------------------------------------------------------- #ifndef MFCRITICSECTION_H #define MFCRITICSECTION_H class CriticSection{ private: CRITICAL_SECTION m_Section; public: CriticSection(){ InitializeCriticalSection(&m_Section); } ~CriticSection(){ DeleteCriticalSection(&m_Section); } void Lock(){ EnterCriticalSection(&m_Section); } void Unlock(){ LeaveCriticalSection(&m_Section); } }; class AutoLock{ private: CriticSection* m_pSection; public: AutoLock(CriticSection& critic){ m_pSection = &critic; m_pSection->Lock(); } ~AutoLock(){ m_pSection->Unlock(); } }; #endif
22.742857
97
0.526382
50e82d6dc007ad89757899ad96fb9adafaaa685e
16,063
go
Go
xslice/xslice_test.go
HappyFacade/gokit
0448a17eb37a301e70ceeac039be84503750f791
[ "Apache-2.0" ]
null
null
null
xslice/xslice_test.go
HappyFacade/gokit
0448a17eb37a301e70ceeac039be84503750f791
[ "Apache-2.0" ]
null
null
null
xslice/xslice_test.go
HappyFacade/gokit
0448a17eb37a301e70ceeac039be84503750f791
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2012-2020 Li Kexian * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * A toolkit for Golang development * https://www.likexian.com/ */ package xslice import ( "strings" "testing" "github.com/likexian/gokit/assert" ) type a struct { x, y int } type b struct { x, y int } func TestVersion(t *testing.T) { assert.Contains(t, Version(), ".") assert.Contains(t, Author(), "likexian") assert.Contains(t, License(), "Apache License") } func TestIsSlice(t *testing.T) { assert.False(t, IsSlice(0)) assert.False(t, IsSlice("0")) assert.True(t, IsSlice([]int{0, 1, 2})) assert.True(t, IsSlice([]string{"0", "1", "2"})) } func TestUnique(t *testing.T) { // Not a slice tests := []struct { in interface{} out interface{} }{ {1, 1}, {1.0, 1.0}, {true, true}, } for _, v := range tests { assert.Panic(t, func() { Unique(v.in) }) } // Is a slice tests = []struct { in interface{} out interface{} }{ {[]int{0, 0, 1, 1, 1, 2, 2, 3}, []int{0, 1, 2, 3}}, {[]int8{0, 0, 1, 1, 1, 2, 2, 3}, []int8{0, 1, 2, 3}}, {[]int16{0, 0, 1, 1, 1, 2, 2, 3}, []int16{0, 1, 2, 3}}, {[]int32{0, 0, 1, 1, 1, 2, 2, 3}, []int32{0, 1, 2, 3}}, {[]int64{0, 0, 1, 1, 1, 2, 2, 3}, []int64{0, 1, 2, 3}}, {[]uint{0, 0, 1, 1, 1, 2, 2, 3}, []uint{0, 1, 2, 3}}, {[]uint8{0, 0, 1, 1, 1, 2, 2, 3}, []uint8{0, 1, 2, 3}}, {[]uint16{0, 0, 1, 1, 1, 2, 2, 3}, []uint16{0, 1, 2, 3}}, {[]uint32{0, 0, 1, 1, 1, 2, 2, 3}, []uint32{0, 1, 2, 3}}, {[]uint64{0, 0, 1, 1, 1, 2, 2, 3}, []uint64{0, 1, 2, 3}}, {[]float32{0, 0, 1, 1, 1, 2, 2, 3}, []float32{0, 1, 2, 3}}, {[]float64{0, 0, 1, 1, 1, 2, 2, 3}, []float64{0, 1, 2, 3}}, {[]string{"a", "a", "b", "b", "b", "c"}, []string{"a", "b", "c"}}, {[]bool{true, true, true, false}, []bool{true, false}}, {[]interface{}{0, 1, 1, "1", 2}, []interface{}{0, 1, "1", 2}}, {[]interface{}{[]int{0, 1}, []int{0, 1}, []int{1, 2}}, []interface{}{[]int{0, 1}, []int{1, 2}}}, {[]interface{}{a{0, 1}, a{1, 2}, a{0, 1}, b{0, 1}}, []interface{}{a{0, 1}, a{1, 2}, b{0, 1}}}, } for _, v := range tests { assert.Equal(t, Unique(v.in), v.out) } } func TestIsUnique(t *testing.T) { // Not a slice tests := []struct { in interface{} }{ {1}, {1.0}, {true}, } for _, v := range tests { assert.Panic(t, func() { IsUnique(v.in) }) } // Is a slice tests = []struct { in interface{} }{ {[]int{0, 0, 1, 1, 1, 2, 2, 3}}, {[]int8{0, 0, 1, 1, 1, 2, 2, 3}}, {[]int16{0, 0, 1, 1, 1, 2, 2, 3}}, {[]int32{0, 0, 1, 1, 1, 2, 2, 3}}, {[]int64{0, 0, 1, 1, 1, 2, 2, 3}}, {[]uint{0, 0, 1, 1, 1, 2, 2, 3}}, {[]uint8{0, 0, 1, 1, 1, 2, 2, 3}}, {[]uint16{0, 0, 1, 1, 1, 2, 2, 3}}, {[]uint32{0, 0, 1, 1, 1, 2, 2, 3}}, {[]uint64{0, 0, 1, 1, 1, 2, 2, 3}}, {[]float32{0, 0, 1, 1, 1, 2, 2, 3}}, {[]float64{0, 0, 1, 1, 1, 2, 2, 3}}, {[]string{"a", "a", "b", "b", "b", "c"}}, {[]bool{true, true, true, false}}, {[]interface{}{0, 1, 1, "1", 2}}, {[]interface{}{[]int{0, 1}, []int{0, 1}, []int{1, 2}}}, {[]interface{}{a{0, 1}, a{1, 2}, a{0, 1}, b{0, 1}}}, } for _, v := range tests { assert.False(t, IsUnique(v.in)) } // Is a slice tests = []struct { in interface{} }{ {[]int{1}}, {[]int{0, 1, 2, 3}}, {[]int8{0, 1, 2, 3}}, {[]int16{0, 1, 2, 3}}, {[]int32{0, 1, 2, 3}}, {[]int64{0, 1, 2, 3}}, {[]uint{0, 1, 2, 3}}, {[]uint8{0, 1, 2, 3}}, {[]uint16{0, 1, 2, 3}}, {[]uint32{0, 1, 2, 3}}, {[]uint64{0, 1, 2, 3}}, {[]float32{0, 1, 2, 3}}, {[]float64{0, 1, 2, 3}}, {[]string{"a", "b", "c"}}, {[]bool{true, false}}, {[]interface{}{0, 1, "1", 2}}, {[]interface{}{[]int{0, 1}, []int{1, 2}}}, {[]interface{}{a{0, 1}, a{1, 2}, b{0, 1}}}, } for _, v := range tests { assert.True(t, IsUnique(v.in)) } } func TestIntersect(t *testing.T) { // Not a slice tests := []struct { x interface{} y interface{} out interface{} }{ {1, 1, nil}, {1.0, 1.0, nil}, {true, true, nil}, {[]int{1}, 1, nil}, {[]float64{1.0}, 1, nil}, {[]bool{true}, true, nil}, } for _, v := range tests { assert.Panic(t, func() { Intersect(v.x, v.y) }) } // Is a slice tests = []struct { x interface{} y interface{} out interface{} }{ {[]int{0, 1, 2}, []int{1, 2, 3}, []int{1, 2}}, {[]int8{0, 1, 2}, []int8{1, 2, 3}, []int8{1, 2}}, {[]int16{0, 1, 2}, []int16{1, 2, 3}, []int16{1, 2}}, {[]int32{0, 1, 2}, []int32{1, 2, 3}, []int32{1, 2}}, {[]int64{0, 1, 2}, []int64{1, 2, 3}, []int64{1, 2}}, {[]float32{0, 1, 2}, []float32{1, 2, 3}, []float32{1, 2}}, {[]float64{0, 1, 2}, []float64{1, 2, 3}, []float64{1, 2}}, {[]string{"0", "1", "2"}, []string{"1", "2", "3"}, []string{"1", "2"}}, {[]bool{true, false}, []bool{true}, []bool{true}}, {[]interface{}{0, 1, "1", 2}, []interface{}{1, "1", 2, 3}, []interface{}{1, "1", 2}}, {[]interface{}{[]int{0, 1}, []int{1, 2}}, []interface{}{[]int{1, 2}, []int{2, 3}}, []interface{}{[]int{1, 2}}}, {[]interface{}{a{0, 1}, a{1, 2}, b{0, 1}}, []interface{}{a{1, 2}, b{2, 3}}, []interface{}{a{1, 2}}}, } for _, v := range tests { assert.Equal(t, Intersect(v.x, v.y), v.out) } } func TestDifferent(t *testing.T) { // Not a slice tests := []struct { x interface{} y interface{} out interface{} }{ {1, 1, nil}, {1.0, 1.0, nil}, {true, true, nil}, {[]int{1}, 1, nil}, {[]float64{1.0}, 1, nil}, {[]bool{true}, true, nil}, } for _, v := range tests { assert.Panic(t, func() { Different(v.x, v.y) }) } // Is a slice tests = []struct { x interface{} y interface{} out interface{} }{ {[]int{0, 1, 2}, []int{1, 2, 3}, []int{0}}, {[]int8{0, 1, 2}, []int8{1, 2, 3}, []int8{0}}, {[]int16{0, 1, 2}, []int16{1, 2, 3}, []int16{0}}, {[]int32{0, 1, 2}, []int32{1, 2, 3}, []int32{0}}, {[]int64{0, 1, 2}, []int64{1, 2, 3}, []int64{0}}, {[]float32{0, 1, 2}, []float32{1, 2, 3}, []float32{0}}, {[]float64{0, 1, 2}, []float64{1, 2, 3}, []float64{0}}, {[]string{"0", "1", "2"}, []string{"1", "2", "3"}, []string{"0"}}, {[]bool{true, false}, []bool{true}, []bool{false}}, {[]interface{}{0, 1, "1", 2}, []interface{}{1, "1", 2, 3}, []interface{}{0}}, {[]interface{}{[]int{0, 1}, []int{1, 2}}, []interface{}{[]int{1, 2}, []int{2, 3}}, []interface{}{[]int{0, 1}}}, {[]interface{}{a{0, 1}, a{1, 2}, b{0, 1}}, []interface{}{a{1, 2}, b{2, 3}}, []interface{}{a{0, 1}, b{0, 1}}}, } for _, v := range tests { assert.Equal(t, Different(v.x, v.y), v.out) } } func TestMerge(t *testing.T) { // Not a slice tests := []struct { x interface{} y interface{} out interface{} }{ {1, 1, 1}, {1.0, 1.0, 1.0}, {true, true, true}, {[]int{1}, 1, []int{1}}, {[]float64{1.0}, 1, []float64{1.0}}, {[]bool{true}, true, []bool{true}}, } for _, v := range tests { assert.Panic(t, func() { Merge(v.x, v.y) }) } // Is a slice tests = []struct { x interface{} y interface{} out interface{} }{ {[]int{0, 1, 2}, []int{1, 2, 3}, []int{0, 1, 2, 3}}, {[]int8{0, 1, 2}, []int8{1, 2, 3}, []int8{0, 1, 2, 3}}, {[]int16{0, 1, 2}, []int16{1, 2, 3}, []int16{0, 1, 2, 3}}, {[]int32{0, 1, 2}, []int32{1, 2, 3}, []int32{0, 1, 2, 3}}, {[]int64{0, 1, 2}, []int64{1, 2, 3}, []int64{0, 1, 2, 3}}, {[]float32{0, 1, 2}, []float32{1, 2, 3}, []float32{0, 1, 2, 3}}, {[]float64{0, 1, 2}, []float64{1, 2, 3}, []float64{0, 1, 2, 3}}, {[]string{"0", "1", "2"}, []string{"1", "2", "3"}, []string{"0", "1", "2", "3"}}, {[]bool{true, false}, []bool{true}, []bool{true, false}}, {[]interface{}{0, 1, "1", 2}, []interface{}{1, "1", 2, 3}, []interface{}{0, 1, "1", 2, 3}}, {[]interface{}{[]int{0, 1}, []int{1, 2}}, []interface{}{[]int{1, 2}, []int{2, 3}}, []interface{}{[]int{0, 1}, []int{1, 2}, []int{2, 3}}}, {[]interface{}{a{0, 1}, a{1, 2}, b{0, 1}}, []interface{}{a{1, 2}, b{2, 3}}, []interface{}{a{0, 1}, a{1, 2}, b{0, 1}, b{2, 3}}}, } for _, v := range tests { assert.Equal(t, Merge(v.x, v.y), v.out) } } func TestReverse(t *testing.T) { // Not a slice tests := []struct { in interface{} out interface{} }{ {1, 1}, {1.0, 1.0}, {true, true}, } for _, v := range tests { assert.Panic(t, func() { Reverse(v.in) }) } // Is a slice tests = []struct { in interface{} out interface{} }{ {[]int{0, 1, 2, 3, 4}, []int{4, 3, 2, 1, 0}}, {[]int8{0, 1, 2, 3, 4}, []int8{4, 3, 2, 1, 0}}, {[]int16{0, 1, 2, 3, 4}, []int16{4, 3, 2, 1, 0}}, {[]int32{0, 1, 2, 3, 4}, []int32{4, 3, 2, 1, 0}}, {[]int64{0, 1, 2, 3, 4}, []int64{4, 3, 2, 1, 0}}, {[]float32{0, 1, 2, 3, 4}, []float32{4, 3, 2, 1, 0}}, {[]float64{0, 1, 2, 3, 4}, []float64{4, 3, 2, 1, 0}}, {[]string{"a", "b", "c", "d", "e"}, []string{"e", "d", "c", "b", "a"}}, {[]bool{true, false, true, false}, []bool{false, true, false, true}}, {[]interface{}{0, 1, 2, "3", 3}, []interface{}{3, "3", 2, 1, 0}}, {[]interface{}{[]int{0, 1}, []int{1, 2}}, []interface{}{[]int{1, 2}, []int{0, 1}}}, {[]interface{}{a{0, 1}, a{1, 2}, b{0, 1}}, []interface{}{b{0, 1}, a{1, 2}, a{0, 1}}}, } for _, v := range tests { Reverse(v.in) assert.Equal(t, v.in, v.out) } } func TestShuffle(t *testing.T) { // Not a slice tests := []struct { in interface{} out interface{} }{ {1, 1}, {1.0, 1.0}, {true, true}, } for _, v := range tests { assert.Panic(t, func() { Shuffle(v.in) }) } // Is a slice tests = []struct { in interface{} out interface{} }{ {[]int{0, 1, 2, 3, 4}, []int{0, 1, 2, 3, 4}}, {[]int8{0, 1, 2, 3, 4}, []int8{0, 1, 2, 3, 4}}, {[]int16{0, 1, 2, 3, 4}, []int16{0, 1, 2, 3, 4}}, {[]int32{0, 1, 2, 3, 4}, []int32{0, 1, 2, 3, 4}}, {[]int64{0, 1, 2, 3, 4}, []int64{0, 1, 2, 3, 4}}, {[]float32{0, 1, 2, 3, 4}, []float32{0, 1, 2, 3, 4}}, {[]float64{0, 1, 2, 3, 4}, []float64{0, 1, 2, 3, 4}}, {[]string{"a", "b", "c", "d", "e"}, []string{"a", "b", "c", "d", "e"}}, {[]bool{true, false, false, true, true}, []bool{true, false, false, true, true}}, {[]interface{}{0, 1, 2, "3", 3}, []interface{}{0, 1, 2, "3", 3}}, {[]interface{}{[]int{0, 1}, []int{1, 2}, []int{1, 2}}, []interface{}{[]int{0, 1}, []int{1, 2}, []int{1, 2}}}, {[]interface{}{a{0, 1}, a{1, 2}, b{0, 1}}, []interface{}{a{0, 1}, a{1, 2}, b{0, 1}}}, } for _, v := range tests { Shuffle(v.in) assert.NotEqual(t, v.in, v.out) } } func TestFill(t *testing.T) { tests := []struct { v interface{} n int out interface{} }{ {1, -1, nil}, {1, 0, nil}, } for _, v := range tests { assert.Panic(t, func() { Fill(v.v, v.n) }) } tests = []struct { v interface{} n int out interface{} }{ {1, 1, []int{1}}, {1, 3, []int{1, 1, 1}}, {int(1), 3, []int{1, 1, 1}}, {int8(1), 3, []int8{1, 1, 1}}, {int16(1), 3, []int16{1, 1, 1}}, {int32(1), 3, []int32{1, 1, 1}}, {int64(1), 3, []int64{1, 1, 1}}, {float32(1), 3, []float32{1, 1, 1}}, {float64(1), 3, []float64{1, 1, 1}}, {"a", 3, []string{"a", "a", "a"}}, {true, 3, []bool{true, true, true}}, {[]int{1, 2}, 3, [][]int{{1, 2}, {1, 2}, {1, 2}}}, {a{1, 2}, 3, []a{{1, 2}, {1, 2}, {1, 2}}}, {[]interface{}{0, "1"}, 3, [][]interface{}{{0, "1"}, {0, "1"}, {0, "1"}}}, {[]interface{}{[]int{0, 1}}, 3, [][]interface{}{{[]int{0, 1}}, {[]int{0, 1}}, {[]int{0, 1}}}}, {[]interface{}{a{0, 1}}, 3, [][]interface{}{{a{x: 0, y: 1}}, {a{x: 0, y: 1}}, {a{x: 0, y: 1}}}}, } for _, v := range tests { assert.Equal(t, Fill(v.v, v.n), v.out) } } func TestChunk(t *testing.T) { tests := []struct { v interface{} n int out interface{} }{ {1, 1, 1}, {[]int{1}, 0, nil}, } for _, v := range tests { assert.Panic(t, func() { Chunk(v.v, v.n) }) } tests = []struct { v interface{} n int out interface{} }{ {[]int{0, 1, 2}, 1, [][]int{{0}, {1}, {2}}}, {[]int{0, 1, 2, 3, 4}, 2, [][]int{{0, 1}, {2, 3}, {4}}}, {[]int{0, 1, 2, 3, 4, 5}, 2, [][]int{{0, 1}, {2, 3}, {4, 5}}}, {[]string{"a", "b", "c", "d", "e"}, 3, [][]string{{"a", "b", "c"}, {"d", "e"}}}, {[]interface{}{a{0, 1}, b{2, 3}, a{4, 5}}, 2, [][]interface{}{{a{0, 1}, b{2, 3}}, {a{4, 5}}}}, } for _, v := range tests { assert.Equal(t, Chunk(v.v, v.n), v.out) } } func TestConcat(t *testing.T) { tests := []struct { in interface{} out interface{} }{ {1, 1}, } for _, v := range tests { assert.Panic(t, func() { Concat(v.in) }) } tests = []struct { in interface{} out interface{} }{ {[]int{}, []int{}}, {[]int{0, 1, 2, 3, 4}, []int{0, 1, 2, 3, 4}}, {[][]int{{0, 1}, {2, 3}, {4}}, []int{0, 1, 2, 3, 4}}, {[][]string{{"a", "b"}, {"c"}, {"d", "e"}}, []string{"a", "b", "c", "d", "e"}}, {[][]interface{}{{a{0, 1}, b{0, 1}}, {a{1, 2}}}, []interface{}{a{0, 1}, b{0, 1}, a{1, 2}}}, } for _, v := range tests { assert.Equal(t, Concat(v.in), v.out) } } func TestFilter(t *testing.T) { // Panic tests tests := []struct { v interface{} f interface{} out interface{} }{ {1, nil, 1}, {[]int{1}, nil, nil}, {[]int{1}, 1, nil}, {[]int{1}, func() {}, nil}, {[]int{1}, func(v int) {}, nil}, {[]int{1}, func(v int) int { return v }, nil}, } for _, v := range tests { assert.Panic(t, func() { Filter(v.v, v.f) }) } // General tests tests = []struct { v interface{} f interface{} out interface{} }{ {[]interface{}{0, 1, nil, 2}, func(v interface{}) bool { return v != nil }, []interface{}{0, 1, 2}}, {[]int{-2, -1, 0, 1, 2}, func(v int) bool { return v >= 0 }, []int{0, 1, 2}}, {[]string{"a_0", "b_1", "a_1"}, func(v string) bool { return strings.HasPrefix(v, "a_") }, []string{"a_0", "a_1"}}, {[]bool{true, false, false}, func(v bool) bool { return !v }, []bool{false, false}}, } for _, v := range tests { assert.Equal(t, Filter(v.v, v.f), v.out) } } func TestMap(t *testing.T) { // Panic tests tests := []struct { v interface{} f interface{} out interface{} }{ {1, nil, 1}, {[]int{1}, nil, nil}, {[]int{1}, 1, nil}, {[]int{1}, func() {}, nil}, {[]int{1}, func(v int) {}, nil}, } for _, v := range tests { assert.Panic(t, func() { Map(v.v, v.f) }) } // General tests tests = []struct { v interface{} f interface{} out interface{} }{ {[]int{1, 2, 3, 4, 5}, func(v int) int { return v * v * v }, []int{1, 8, 27, 64, 125}}, {[]int{-2, -1, 0, 1, 2}, func(v int) bool { return v > 0 }, []bool{false, false, false, true, true}}, {[]string{"a", "b", "c"}, func(v string) string { return "x_" + v }, []string{"x_a", "x_b", "x_c"}}, {[]bool{true, false, false}, func(v bool) bool { return !v }, []bool{false, true, true}}, {[]interface{}{1, nil}, func(v interface{}) interface{} { return assert.If(v == nil, -1, v) }, []interface{}{1, -1}}, } for _, v := range tests { assert.Equal(t, Map(v.v, v.f), v.out) } } func TestReduce(t *testing.T) { // Panic tests tests := []struct { v interface{} f interface{} out interface{} }{ {1, nil, 1}, {[]int{}, nil, nil}, {[]int{0, 1}, nil, nil}, {[]int{0, 1}, 1, nil}, {[]int{0, 1}, func() {}, nil}, {[]int{0, 1}, func(x int) {}, nil}, {[]int{0, 1}, func(x, y int) {}, nil}, {[]int{0, 1}, func(x bool, y int) int { return y }, nil}, {[]int{0, 1}, func(x int, y bool) int { return x }, nil}, {[]int{0, 1}, func(x int, y int) bool { return true }, nil}, } for _, v := range tests { assert.Panic(t, func() { Reduce(v.v, v.f) }) } // General tests tests = []struct { v interface{} f interface{} out interface{} }{ {[]int{1}, func(x, y int) int { return x + y }, 1}, {[]int{1, 2}, func(x, y int) int { return x + y }, 3}, {[]int{1, 2, 3, 4}, func(x, y int) int { return x * y }, 24}, } for _, v := range tests { assert.Equal(t, Reduce(v.v, v.f).(int), v.out) } }
27.364566
139
0.474195
996011f7cbf0e1322f5366967f6790e855637bb3
4,863
h
C
System/Library/Frameworks/ExposureNotification.framework/ENExposureConfiguration.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/Frameworks/ExposureNotification.framework/ENExposureConfiguration.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/Frameworks/ExposureNotification.framework/ENExposureConfiguration.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:23:34 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/Frameworks/ExposureNotification.framework/ExposureNotification * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <libobjc.A.dylib/CUXPCCodable.h> @class NSDictionary, NSArray; @interface ENExposureConfiguration : NSObject <CUXPCCodable> { unsigned char _attenuationLevelValuesMap[8]; unsigned char _daysSinceLastExposureLevelValuesMap[8]; unsigned char _durationLevelValuesMap[8]; unsigned char _transmissionRiskLevelValuesMap[8]; unsigned char _minimumRiskScore; NSDictionary* _metadata; double _minimumRiskScoreFullRange; NSArray* _attenuationDurationThresholds; NSArray* _attenuationLevelValues; double _attenuationWeight; NSArray* _daysSinceLastExposureLevelValues; double _daysSinceLastExposureWeight; NSArray* _durationLevelValues; double _durationWeight; NSArray* _transmissionRiskLevelValues; double _transmissionRiskWeight; } @property (nonatomic,copy) NSDictionary * metadata; //@synthesize metadata=_metadata - In the implementation block @property (assign,nonatomic) unsigned char minimumRiskScore; //@synthesize minimumRiskScore=_minimumRiskScore - In the implementation block @property (assign,nonatomic) double minimumRiskScoreFullRange; //@synthesize minimumRiskScoreFullRange=_minimumRiskScoreFullRange - In the implementation block @property (nonatomic,copy,readonly) NSArray * attenuationDurationThresholds; //@synthesize attenuationDurationThresholds=_attenuationDurationThresholds - In the implementation block @property (nonatomic,copy) NSArray * attenuationLevelValues; //@synthesize attenuationLevelValues=_attenuationLevelValues - In the implementation block @property (assign,nonatomic) double attenuationWeight; //@synthesize attenuationWeight=_attenuationWeight - In the implementation block @property (nonatomic,copy) NSArray * daysSinceLastExposureLevelValues; //@synthesize daysSinceLastExposureLevelValues=_daysSinceLastExposureLevelValues - In the implementation block @property (assign,nonatomic) double daysSinceLastExposureWeight; //@synthesize daysSinceLastExposureWeight=_daysSinceLastExposureWeight - In the implementation block @property (nonatomic,copy) NSArray * durationLevelValues; //@synthesize durationLevelValues=_durationLevelValues - In the implementation block @property (assign,nonatomic) double durationWeight; //@synthesize durationWeight=_durationWeight - In the implementation block @property (nonatomic,copy) NSArray * transmissionRiskLevelValues; //@synthesize transmissionRiskLevelValues=_transmissionRiskLevelValues - In the implementation block @property (assign,nonatomic) double transmissionRiskWeight; //@synthesize transmissionRiskWeight=_transmissionRiskWeight - In the implementation block -(id)init; -(id)description; -(id)dictionaryRepresentation; -(void)setMetadata:(NSDictionary *)arg1 ; -(NSDictionary *)metadata; -(id)initWithDictionary:(id)arg1 error:(id*)arg2 ; -(id)initWithXPCObject:(id)arg1 error:(id*)arg2 ; -(void)encodeWithXPCObject:(id)arg1 ; -(double)attenuationLevelValueWithAttenuation:(unsigned char)arg1 ; -(double)daysSinceLastExposureLevelValueWithDays:(long long)arg1 ; -(double)durationLevelValueWithDuration:(double)arg1 ; -(double)transmissionLevelValueWithTransmissionRiskLevel:(unsigned char)arg1 ; -(double)attenuationWeight; -(double)daysSinceLastExposureWeight; -(double)durationWeight; -(double)transmissionRiskWeight; -(unsigned char)minimumRiskScore; -(void)setMinimumRiskScore:(unsigned char)arg1 ; -(double)minimumRiskScoreFullRange; -(void)setMinimumRiskScoreFullRange:(double)arg1 ; -(NSArray *)attenuationDurationThresholds; -(NSArray *)attenuationLevelValues; -(void)setAttenuationLevelValues:(NSArray *)arg1 ; -(void)setAttenuationWeight:(double)arg1 ; -(NSArray *)daysSinceLastExposureLevelValues; -(void)setDaysSinceLastExposureLevelValues:(NSArray *)arg1 ; -(void)setDaysSinceLastExposureWeight:(double)arg1 ; -(NSArray *)durationLevelValues; -(void)setDurationLevelValues:(NSArray *)arg1 ; -(void)setDurationWeight:(double)arg1 ; -(NSArray *)transmissionRiskLevelValues; -(void)setTransmissionRiskLevelValues:(NSArray *)arg1 ; -(void)setTransmissionRiskWeight:(double)arg1 ; @end
60.037037
200
0.749332
0764590f7d911ba9df9f4374e406422b4e2367f2
2,253
rs
Rust
rs/game.rs
canufeel/kitty-wars-yew-front
5cea75a73d9b65c24838b606a3b434e7490fdf88
[ "Apache-2.0", "MIT" ]
2
2020-02-21T22:39:53.000Z
2020-04-14T22:12:53.000Z
rs/game.rs
canufeel/kitty-wars-yew-front
5cea75a73d9b65c24838b606a3b434e7490fdf88
[ "Apache-2.0", "MIT" ]
6
2021-05-11T01:33:26.000Z
2022-02-26T22:52:17.000Z
rs/game.rs
canufeel/kitty-wars-yew-front
5cea75a73d9b65c24838b606a3b434e7490fdf88
[ "Apache-2.0", "MIT" ]
null
null
null
use std::collections::HashMap; use yew::{Html, html, Callback}; use stdweb::web::event::ClickEvent; pub enum ItemType { Weapon, Armor } pub struct Item { item_type: ItemType, item_power: String } impl Item { pub fn new( item_type: ItemType, item_power: String ) -> Self { Item { item_power, item_type } } } pub struct Player { weapon_id: String, armor_id: String, kitty_id: String, is_battling: bool } impl Player { pub fn new( weapon_id: String, armor_id: String, kitty_id: String, ) -> Self { Player { weapon_id, armor_id, kitty_id, is_battling: false } } pub fn set_battling(&mut self, is_battling: bool) { self.is_battling = is_battling; } } pub struct PlayerState { pub account: String, players: HashMap<String, Player>, items: HashMap<String, Item> } impl PlayerState { pub fn new( account: String, players: HashMap<String, Player>, items: HashMap<String, Item> ) -> Self { PlayerState { account, players, items } } pub fn has_player_for_account(&self) -> bool { self.players.contains_key(&self.account) } fn get_items_for_current_player(&self) -> Option<(&Item, &Item)> { match self.players.get(&self.account) { Some(items) => match (self.items.get(&items.weapon_id), self.items.get(&items.armor_id)) { (Some(weapon), Some(armor)) => Some((weapon, armor)), _ => None, }, _ => None } } pub fn get_player_details(&self, on_join: Callback<ClickEvent>) -> Html { let load_finished_data = match self.get_items_for_current_player() { None => html! { <div class="join"> <button onclick=on_join>{ "Join" }</button> </div> }, Some((weapon, armor)) => html!{ <div class="player-details"> <div class="weapon"> { format!("Weapon: {}", weapon.item_power) } </div> <div class="armor"> { format!("Armor: {}", armor.item_power) } </div> </div> } }; html! { <div class="finished"> <p>{ format!("Hello, {}", self.account) }</p> { load_finished_data } </div> } } }
20.297297
96
0.573014
9be046494b193a8252bb8698afb4c5be38bde476
5,799
js
JavaScript
JS-Applications/11- Async/02. FISHER-GAME/app.js
DenislavVelichkov/JS-Core-January-2020
8503a2de75ac3e67aad043b818a7cd95d607c8c2
[ "MIT" ]
null
null
null
JS-Applications/11- Async/02. FISHER-GAME/app.js
DenislavVelichkov/JS-Core-January-2020
8503a2de75ac3e67aad043b818a7cd95d607c8c2
[ "MIT" ]
null
null
null
JS-Applications/11- Async/02. FISHER-GAME/app.js
DenislavVelichkov/JS-Core-January-2020
8503a2de75ac3e67aad043b818a7cd95d607c8c2
[ "MIT" ]
null
null
null
import { fetchData } from './fetch.js'; const html = { loadButton: () => document.getElementsByClassName("load")[0], catchesCollection: () => document.getElementById("catches"), hr: () => document.createElement("hr"), addButton: () => document.getElementsByClassName("add")[0], anglerField: () => document.querySelector("fieldset > .angler"), weightField: () => document.querySelector("fieldset > .weight"), speciesField: () => document.querySelector("fieldset > .species"), locationField: () => document.querySelector("fieldset > .location"), baitField: () => document.querySelector("fieldset > .bait"), captureTimeField: () => document.querySelector("fieldset > .captureTime"), } function attachEvents() { html.loadButton().addEventListener("click", loadData); html.addButton().addEventListener("click", addData); } function loadData() { // html.catchesCollection().innerHTML = ""; fetchData().loadData() .then(data => { Object.entries(data) .forEach(([id, item]) => { const catchesDiv = document.createElement("div"); catchesDiv.classList.add("catch"); catchesDiv.setAttribute("data-id", id); const anglerLabel = createDomLabel("label", "Angler"); const anglerInput = createDomInput("input", "text", ["angler"], item.angler); const weightLabel = createDomLabel("label", "Weight"); const weightInput = createDomInput("input", "number", ["weight"], item.weight); const speciesLabel = createDomLabel("label", "Species"); const speciesInput = createDomInput("input", "text", ["species"], item.species); const locationLabel = createDomLabel("label", "Location"); const locationInput = createDomInput("input", "text", ["location"], item.location); const baitLabel = createDomLabel("label", "Bait"); const baitInput = createDomInput("input", "text", ["bait"], item.bait); const captureTimeLabel = createDomLabel("label", "Capture Time"); const captureTimeInput = createDomInput("input", "number", ["captureTime"], item.captureTime); const updateButton = createDomButton("button", ["update"], "Update"); updateButton.addEventListener("click", updateCatch); const deleteButton = createDomButton("button", ["delete"], "Delete"); deleteButton.addEventListener("click", deleteCatch); catchesDiv.append(anglerLabel, anglerInput, html.hr(), weightLabel, weightInput, html.hr()); catchesDiv.append(speciesLabel, speciesInput, html.hr(), locationLabel, locationInput, html.hr()); catchesDiv.append(baitLabel, baitInput, html.hr(), captureTimeLabel, captureTimeInput, html.hr()); catchesDiv.append(updateButton, deleteButton); html.catchesCollection().appendChild(catchesDiv); }) }) .catch(() => console.log("Error")); } function createDomLabel(element, text) { const label = document.createElement(element); label.textContent = text; return label; } function createDomInput(element, type, classes, itemValue) { const input = document.createElement(element); input.type = type; input.classList.add([...classes]); input.value = itemValue; return input; } function createDomButton(element, classes, text) { const button = document.createElement(element); button.classList.add([...classes]); button.textContent = text; return button; } function deleteCatch() { const id = this.parentNode.getAttribute("data-id"); this.parentNode.parentNode.removeChild(this.parentNode); const headers = { method: "DELETE" }; fetchData().deleteCatchesElement(id, headers) .then(() => { loadData(); }) .catch(() => console.log("Error")); } function updateCatch() { const id = this.parentNode.getAttribute("data-id"); const headers = { method: "PUT", headers: { "Content-type": "application/json" }, body: JSON.stringify({ "angler": this.parentNode.querySelector(".angler").value, "weight": this.parentNode.querySelector(".weight").value, "species": this.parentNode.querySelector(".species").value, "location": this.parentNode.querySelector(".location").value, "bait": this.parentNode.querySelector(".bait").value, "captureTime": this.parentNode.querySelector(".captureTime").value }) }; fetchData().updateCatch(id, headers) .then(() => { loadData(); }) .catch(() => console.log("Error")); } function addData() { const angler = html.anglerField().value; const weight = html.weightField().value; const species = html.speciesField().value; const location = html.locationField().value; const bait = html.baitField().value; const captureTime = html.captureTimeField().value; const headers = { method: "POST", headers: { "Content-type": "application/json" }, body: JSON.stringify({ "angler": angler, "weight": weight, "species": species, "location": location, "bait": bait, "captureTime": captureTime }) }; fetchData().addCatch(headers) .then(() => { loadData(); }) .catch(() => console.log("Error")); } attachEvents();
35.576687
118
0.58786
129c892c21fef82c4b8282cdda2319d2328f28fe
2,227
c
C
src/drivers/xf86-video-guac/composite.c
tkiapril/guacamole-server
d1e287b9fde60457dec71739c6f063129f912c87
[ "Apache-2.0" ]
null
null
null
src/drivers/xf86-video-guac/composite.c
tkiapril/guacamole-server
d1e287b9fde60457dec71739c6f063129f912c87
[ "Apache-2.0" ]
null
null
null
src/drivers/xf86-video-guac/composite.c
tkiapril/guacamole-server
d1e287b9fde60457dec71739c6f063129f912c87
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "config.h" #include "display.h" #include "drawable.h" #include "log.h" #include "pixmap.h" #include "screen.h" #include <xorg-server.h> #include <xf86.h> #include <fb.h> void guac_drv_composite(CARD8 op, PicturePtr src, PicturePtr mask, PicturePtr dst, INT16 src_x, INT16 src_y, INT16 mask_x, INT16 mask_y, INT16 dst_x, INT16 dst_y, CARD16 width, CARD16 height) { /* Get drawable */ guac_drv_drawable* guac_drawable = guac_drv_get_drawable(dst->pDrawable); /* Draw to windows only */ if (guac_drawable == NULL) return; guac_drv_log(GUAC_LOG_DEBUG, "guac_drv_composite layer=%i (%i, %i) %ix%i", guac_drawable->layer->layer->index, dst_x, dst_y, width, height); /* Get guac_drv_screen */ ScreenPtr screen = dst->pDrawable->pScreen; guac_drv_screen* guac_screen = (guac_drv_screen*) dixGetPrivate(&(screen->devPrivates), GUAC_SCREEN_PRIVATE); /* Invoke underlying composite implementation */ guac_screen->wrapped_composite(op, src, mask, dst, src_x, src_y, mask_x, mask_y, dst_x, dst_y, width, height); /* Copy region from framebuffer */ guac_drv_drawable_copy_fb(dst->pDrawable, dst_x, dst_y, width, height, guac_drawable, dst_x, dst_y); /* Signal change */ guac_drv_display_touch(guac_screen->display); }
32.75
78
0.685676
574565af69c9286e799b2f20b7f5544695d7b857
215
h
C
ALXcommercialCollege/ALXClasses/ALXDatabase/ALXDatabase.h
zhuzhiwen0527/ALXcommercialCollege
d689795edf2a643a0335e8b225c56a8a8fc2e5a0
[ "MIT" ]
null
null
null
ALXcommercialCollege/ALXClasses/ALXDatabase/ALXDatabase.h
zhuzhiwen0527/ALXcommercialCollege
d689795edf2a643a0335e8b225c56a8a8fc2e5a0
[ "MIT" ]
null
null
null
ALXcommercialCollege/ALXClasses/ALXDatabase/ALXDatabase.h
zhuzhiwen0527/ALXcommercialCollege
d689795edf2a643a0335e8b225c56a8a8fc2e5a0
[ "MIT" ]
null
null
null
// // ALXDatabase.h // ALXcommercialCollege // // Created by macbook pro on 16/7/20. // Copyright © 2016年 zzw. All rights reserved. // #import <Foundation/Foundation.h> @interface ALXDatabase : NSObject @end
15.357143
47
0.697674
501f01a185fa9476528737a802fbf324922d423b
1,975
asm
Assembly
programs/oeis/184/A184035.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/184/A184035.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/184/A184035.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A184035: 1/16 the number of (n+1) X 6 0..3 arrays with all 2 X 2 subblocks having the same four values. ; 169,181,202,244,322,478,778,1378,2554,4906,9562,18874,37402,74458,148378,296218,591514,1182106,2362522,4723354,9443482,18883738,37761178,75516058,151019674,302026906,604029082,1208033434,2416017562,4831985818,9663873178,19327647898,38655099034,77310001306,154619609242,309238825114,618476863642,1236952940698,2473904308378,4947807043738,9895610941594,19791218737306,39582431183002,79164856074394,158329699565722,316659386548378,633318747930778,1266637470695578,2533274891059354,5066549731786906,10133099362910362,20266198625157274,40532397048987802,81064793896648858,162129587390644378,324259174378635418,648518347951964314,1297036695098622106,2594073388586631322,5188146775562649754,10376293547904073882,20752587092586922138,41505174178731393178,83010348351020335258,166020696689155768474,332041393365426634906,664082786705083465882,1328165573384397127834,2656331146717254647962,5312662293382969688218,10625324586662860161178,21250649173222641107098,42501298346239123783834,85002596692272089137306,170005193384131861414042,340010386767851405967514,680020773534878178214042,1360041547068931722707098,2720083094136214177972378,5440166188270779088502938,10880332376538259642122394,21760664753073220749361306,43521329506139844428955802,87042659012273091788144794,174085318024532989436756122,348170636049052784733978778,696341272098079181188890778,1392682544196131974098714778,2785365088392211171639296154,5570730176784369566720458906,11141460353568633580324651162,22282920707137161607533035674,44565841414274112108833538202,89131682828548013111434543258,178263365657095604010404020378,356526731314190785808342974618,713053462628380727191755817114,1426106925256760609958581502106,2852213850513519531067302740122,5704427701027037373284745216154 mov $1,4 mov $2,$0 lpb $0 mul $1,2 add $1,$2 sub $1,$0 sub $0,1 trn $2,2 lpe sub $1,4 mul $1,3 add $1,169 mov $0,$1
116.176471
1,741
0.900759
6403f04334afcb60707f8631b39ad76e21945551
273
rs
Rust
lalr/src/error.rs
Dophin2009/isc
7f8481f3e6599b0db57472624733464c7286d672
[ "MIT" ]
1
2021-01-16T19:31:42.000Z
2021-01-16T19:31:42.000Z
lalr/src/error.rs
Dophin2009/isc
7f8481f3e6599b0db57472624733464c7286d672
[ "MIT" ]
null
null
null
lalr/src/error.rs
Dophin2009/isc
7f8481f3e6599b0db57472624733464c7286d672
[ "MIT" ]
null
null
null
#[derive(Debug, Clone, thiserror::Error)] pub enum Error { #[error("starting nonterminal has no productions")] NoStartRule, #[error("nonterminal in right-hand side does not exist")] InvalidNonterminal, } pub type Result<T> = std::result::Result<T, Error>;
27.3
61
0.692308
b88f52c8e129571d8d88b52881df7b53519662ac
413
html
HTML
src/_includes/header.html
thexdesk/dds.mil
f2116e74d326c48b753d091bed613b5be87296e7
[ "MIT" ]
null
null
null
src/_includes/header.html
thexdesk/dds.mil
f2116e74d326c48b753d091bed613b5be87296e7
[ "MIT" ]
null
null
null
src/_includes/header.html
thexdesk/dds.mil
f2116e74d326c48b753d091bed613b5be87296e7
[ "MIT" ]
1
2020-01-08T16:06:47.000Z
2020-01-08T16:06:47.000Z
<header id="fixed-header" class="dds-site-header"> <div class="usa-disclaimer-small"> <div class="usa-disclaimer-member"> </div> </div> <div class="dds-navbar"> <div class="dds-logo"> <a href="/"> <img alt="The logo of the Defense Digital Service" src="/assets/img/layout/logo-desktop-full.png" /> <em>Defense Digital Service</em> </a> </div> </div> </header>
25.8125
108
0.595642
3e4204831b7a1aec4a754ea3548bdbc1b227a478
6,209
h
C
include/linux/platform_data/video-msm_fb.h
CaelestisZ/IrisCore
6f0397e43335434ee58e418c9d1528833c57aea2
[ "MIT" ]
1
2020-06-28T00:49:21.000Z
2020-06-28T00:49:21.000Z
include/linux/platform_data/video-msm_fb.h
CaelestisZ/AetherAura
1b30acb7e6921042722bc4aff160dc63a975abc2
[ "MIT" ]
1
2020-05-28T13:06:06.000Z
2020-05-28T13:13:15.000Z
kernel/lge/msm8226/arch/arm/mach-msm/include/mach/msm_fb.h
Uswer/LineageOS-14.1_jag3gds
6fe76987fad4fca7b3c08743b067d5e79892e77f
[ "Apache-2.0" ]
4
2020-05-26T12:40:11.000Z
2021-07-15T06:46:33.000Z
/* arch/arm/mach-msm/include/mach/msm_fb.h * * Internal shared definitions for various MSM framebuffer parts. * * Copyright (C) 2007 Google Incorporated * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef _MSM_FB_H_ #define _MSM_FB_H_ #include <linux/device.h> struct mddi_info; /* output interface format */ #define MSM_MDP_OUT_IF_FMT_RGB565 0 #define MSM_MDP_OUT_IF_FMT_RGB666 1 struct msm_fb_data { int xres; /* x resolution in pixels */ int yres; /* y resolution in pixels */ int width; /* disply width in mm */ int height; /* display height in mm */ unsigned output_format; }; struct msmfb_callback { void (*func)(struct msmfb_callback *); }; enum { MSM_MDDI_PMDH_INTERFACE = 0, MSM_MDDI_EMDH_INTERFACE, MSM_EBI2_INTERFACE, MSM_LCDC_INTERFACE, MSM_MDP_NUM_INTERFACES = MSM_LCDC_INTERFACE + 1, }; #define MSMFB_CAP_PARTIAL_UPDATES (1 << 0) struct msm_panel_data { /* turns off the fb memory */ int (*suspend)(struct msm_panel_data *); /* turns on the fb memory */ int (*resume)(struct msm_panel_data *); /* turns off the panel */ int (*blank)(struct msm_panel_data *); /* turns on the panel */ int (*unblank)(struct msm_panel_data *); void (*wait_vsync)(struct msm_panel_data *); void (*request_vsync)(struct msm_panel_data *, struct msmfb_callback *); void (*clear_vsync)(struct msm_panel_data *); /* from the enum above */ unsigned interface_type; /* data to be passed to the fb driver */ struct msm_fb_data *fb_data; /* capabilities supported by the panel */ uint32_t caps; }; struct msm_mddi_client_data { void (*suspend)(struct msm_mddi_client_data *); void (*resume)(struct msm_mddi_client_data *); void (*activate_link)(struct msm_mddi_client_data *); void (*remote_write)(struct msm_mddi_client_data *, uint32_t val, uint32_t reg); uint32_t (*remote_read)(struct msm_mddi_client_data *, uint32_t reg); void (*auto_hibernate)(struct msm_mddi_client_data *, int); /* custom data that needs to be passed from the board file to a * particular client */ void *private_client_data; struct resource *fb_resource; /* from the list above */ unsigned interface_type; }; struct msm_mddi_platform_data { unsigned int clk_rate; void (*power_client)(struct msm_mddi_client_data *, int on); /* fixup the mfr name, product id */ void (*fixup)(uint16_t *mfr_name, uint16_t *product_id); int vsync_irq; struct resource *fb_resource; /*optional*/ /* number of clients in the list that follows */ int num_clients; /* array of client information of clients */ struct { unsigned product_id; /* mfr id in top 16 bits, product id * in lower 16 bits */ char *name; /* the device name will be the platform * device name registered for the client, * it should match the name of the associated * driver */ unsigned id; /* id for mddi client device node, will also * be used as device id of panel devices, if * the client device will have multiple panels * space must be left here for them */ void *client_data; /* required private client data */ unsigned int clk_rate; /* optional: if the client requires a * different mddi clk rate */ } client_platform_data[]; }; struct msm_lcdc_timing { unsigned int clk_rate; /* dclk freq */ unsigned int hsync_pulse_width; /* in dclks */ unsigned int hsync_back_porch; /* in dclks */ unsigned int hsync_front_porch; /* in dclks */ unsigned int hsync_skew; /* in dclks */ unsigned int vsync_pulse_width; /* in lines */ unsigned int vsync_back_porch; /* in lines */ unsigned int vsync_front_porch; /* in lines */ /* control signal polarity */ unsigned int vsync_act_low:1; unsigned int hsync_act_low:1; unsigned int den_act_low:1; }; struct msm_lcdc_panel_ops { int (*init)(struct msm_lcdc_panel_ops *); int (*uninit)(struct msm_lcdc_panel_ops *); int (*blank)(struct msm_lcdc_panel_ops *); int (*unblank)(struct msm_lcdc_panel_ops *); }; struct msm_lcdc_platform_data { struct msm_lcdc_panel_ops *panel_ops; struct msm_lcdc_timing *timing; int fb_id; struct msm_fb_data *fb_data; struct resource *fb_resource; }; struct mdp_blit_req; struct fb_info; struct mdp_device { struct device dev; void (*dma)(struct mdp_device *mdp, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h, uint32_t x, uint32_t y, struct msmfb_callback *callback, int interface); void (*dma_wait)(struct mdp_device *mdp, int interface); int (*blit)(struct mdp_device *mdp, struct fb_info *fb, struct mdp_blit_req *req); void (*set_grp_disp)(struct mdp_device *mdp, uint32_t disp_id); int (*check_output_format)(struct mdp_device *mdp, int bpp); int (*set_output_format)(struct mdp_device *mdp, int bpp); }; struct class_interface; int register_mdp_client(struct class_interface *class_intf); /**** private client data structs go below this line ***/ struct msm_mddi_bridge_platform_data { /* from board file */ int (*init)(struct msm_mddi_bridge_platform_data *, struct msm_mddi_client_data *); int (*uninit)(struct msm_mddi_bridge_platform_data *, struct msm_mddi_client_data *); /* passed to panel for use by the fb driver */ int (*blank)(struct msm_mddi_bridge_platform_data *, struct msm_mddi_client_data *); int (*unblank)(struct msm_mddi_bridge_platform_data *, struct msm_mddi_client_data *); struct msm_fb_data fb_data; /* board file will identify what capabilities the panel supports */ uint32_t panel_caps; }; struct mdp_v4l2_req; int msm_fb_v4l2_enable(struct mdp_overlay *req, bool enable, void **par); int msm_fb_v4l2_update(void *par, bool bUserPtr, unsigned long srcp0_addr, unsigned long srcp0_size, unsigned long srcp1_addr, unsigned long srcp1_size, unsigned long srcp2_addr, unsigned long srcp2_size); #endif
31.201005
73
0.732646
5f957c09953cabb17e2d9b8709f27b134cd84e2d
2,421
css
CSS
public/css/style.css
adamstaveley/cruddy-todo
c5ec719a7e285394a7d634982346c929a97ffa77
[ "MIT" ]
null
null
null
public/css/style.css
adamstaveley/cruddy-todo
c5ec719a7e285394a7d634982346c929a97ffa77
[ "MIT" ]
null
null
null
public/css/style.css
adamstaveley/cruddy-todo
c5ec719a7e285394a7d634982346c929a97ffa77
[ "MIT" ]
null
null
null
body { background-color: #26262d; } .todo-container { margin: 0 auto; padding: 20px; height: 100vh; width: 800px; background-color: #26262d; } @media (max-width: 800px) { .todo-container { width: 100vw; } } @media (max-width: 500px) { .todo-container { padding: 10px; } } .todo-container .entries { font-size: 18px; font-family: 'Roboto Mono', monospace; font-weight: 500; color: #50cda1; } .todo-container .entries ul.entry { background: #3b3b42; border-radius: 5px; padding: 0; } .todo-container .entries li { list-style-type: none; } .todo-container .entries li.text { margin: 0; padding: 5px 10px; cursor: pointer; animation-name: fadeIn; animation-duration: 0.5s; } .todo-container .entries li.buttons { padding: 5px 5px; text-align: center; background: #50cda1; color: #26262d; cursor: pointer; border-radius: 0 0 5px 5px; animation-name: changeColour; animation-duration: 1.5s; } .todo-container .entries li.buttons span { padding: 0px 3px; } .todo-container .entries li.buttons span .glyphicon:hover { color: #e4e4e4; } .todo-container .add { display: flex; flex-direction: row; flex-wrap: wrap; margin-bottom: 20px; } @media (max-width: 500px) { .todo-container .add { margin-bottom: 10px; } } .todo-container .add .add-button { padding: 10px; color: #50cda1; cursor: pointer; } .todo-container .add .add-button:hover { color: #e4e4e4; } .todo-container form.entry-form { width: 100%; } .todo-container form.entry-form input.entry-form-input { padding: 5px 10px; background: #26262d; color: #50cda1; border: none; font-size: 18px; font-family: 'Roboto Mono', monospace; font-weight: 500; width: 100%; background-color: #3b3b42; border-radius: 5px; animation-name: fadeIn, moveUp; animation-duration: 0.5s; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes changeColour { from { background-color: #3b3b42; } to { background-color: #50cda1; } } @keyframes moveUp { from { margin-top: 10px; } to { margin-top: 0; } } /*# sourceMappingURL=style.css.map */
26.032258
69
0.58323
f5cf221f14fa0f8bbd64144ae597ca0c3efb7b5d
78
sql
SQL
binding/owlapi/src/test/resources/iri-decomposition/iri-decomposition.sql
JervenBolleman/ontop
a38627e0f484730587eee45d27848e7911138d54
[ "Apache-2.0" ]
null
null
null
binding/owlapi/src/test/resources/iri-decomposition/iri-decomposition.sql
JervenBolleman/ontop
a38627e0f484730587eee45d27848e7911138d54
[ "Apache-2.0" ]
1
2022-02-11T19:37:51.000Z
2022-02-11T19:37:51.000Z
binding/owlapi/src/test/resources/iri-decomposition/iri-decomposition.sql
JervenBolleman/ontop
a38627e0f484730587eee45d27848e7911138d54
[ "Apache-2.0" ]
1
2022-01-27T10:09:43.000Z
2022-01-27T10:09:43.000Z
create table person ( nr integer ); create table review ( nr integer );
11.142857
21
0.666667
f06ae02416b8f8f9bb909dbd1c4d484476e5b8f7
4,498
py
Python
examples/pykey60/code-1.py
lesley-byte/pykey
ce21b5b6c0da938bf24891e5acb196d6779c433a
[ "MIT" ]
null
null
null
examples/pykey60/code-1.py
lesley-byte/pykey
ce21b5b6c0da938bf24891e5acb196d6779c433a
[ "MIT" ]
null
null
null
examples/pykey60/code-1.py
lesley-byte/pykey
ce21b5b6c0da938bf24891e5acb196d6779c433a
[ "MIT" ]
null
null
null
#pylint: disable = line-too-long import os import time import board import neopixel import keypad import usb_hid import pwmio import rainbowio from adafruit_hid.keyboard import Keyboard from pykey.keycode import KB_Keycode as KC from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS # Hardware definition: GPIO where RGB LED is connected. pixel_pin = board.NEOPIXEL num_pixels = 61 pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=1, auto_write=False) cyclecount = 0 def rainbow_cycle(wait): for i in range(num_pixels): rc_index = (i * 256 // num_pixels) + wait pixels[i] = rainbowio.colorwheel(rc_index & 255) pixels.show() buzzer = pwmio.PWMOut(board.SPEAKER, variable_frequency=True) OFF = 0 ON = 2**15 # Hardware definition: Switch Matrix Setup. keys = keypad.KeyMatrix( row_pins=(board.ROW1, board.ROW2, board.ROW3, board.ROW4, board.ROW5), column_pins=(board.COL1, board.COL2, board.COL3, board.COL4, board.COL5, board.COL6, board.COL7, board.COL8, board.COL9, board.COL10, board.COL11, board.COL12, board.COL13, board.COL14), columns_to_anodes=True, ) # CONFIGURABLES ------------------------ MACRO_FOLDER = '/layers' # CLASSES AND FUNCTIONS ---------------- class Layer: """ Class representing a layer, for which we have a set of macro sequences or keycodes""" def __init__(self, layerdata): self.name = layerdata['name'] self.macros = layerdata['macros'] # Neopixel update function def update_pixels(color): for i in range(num_pixels): pixels[i] = color pixels.show() # INITIALIZATION ----------------------- # Load all the macro key setups from .py files in MACRO_FOLDER layers = [] files = os.listdir(MACRO_FOLDER) files.sort() for filename in files: print(filename) if filename.endswith('.py'): try: module = __import__(MACRO_FOLDER + '/' + filename[:-3]) layers.append(Layer(module.layer)) except (SyntaxError, ImportError, AttributeError, KeyError, NameError, IndexError, TypeError) as err: print(err) pass if not layers: print('NO MACRO FILES FOUND') while True: pass layer_count = len(layers) # print(layer_count) def get_active_layer(layer_keys_pressed, layer_count): tmp = 0 if len(layer_keys_pressed)>0: for layer_id in layer_keys_pressed: if layer_id > tmp: # use highest layer number tmp = layer_id if tmp >= layer_count: tmp = layer_count-1 return tmp # setup variables keyboard = Keyboard(usb_hid.devices) keyboard_layout = KeyboardLayoutUS(keyboard) active_keys = [] not_sleeping = True layer_index = 0 buzzer.duty_cycle = ON buzzer.frequency = 440 # time.sleep(0.05) buzzer.frequency = 880 # time.sleep(0.05) buzzer.frequency = 440 # time.sleep(0.05) buzzer.duty_cycle = OFF while not_sleeping: key_event = keys.events.get() if key_event: key_number = key_event.key_number cyclecount = cyclecount +1 rainbow_cycle(cyclecount) # keep track of keys being pressed for layer determination if key_event.pressed: active_keys.append(key_number) else: active_keys.remove(key_number) # reset the layers and identify which layer key is pressed. layer_keys_pressed = [] for active_key in active_keys: group = layers[0].macros[active_key][2] for item in group: if isinstance(item, int): if (item >= KC.LAYER_0) and (item <= KC.LAYER_F) : layer_keys_pressed.append(item - KC.LAYER_0) layer_index = get_active_layer(layer_keys_pressed, layer_count) # print(layer_index) # print(layers[layer_index].macros[key_number][1]) group = layers[layer_index].macros[key_number][2] color = layers[layer_index].macros[key_number][0] if key_event.pressed: update_pixels(color) for item in group: if isinstance(item, int): keyboard.press(item) else: keyboard_layout.write(item) else: for item in group: if isinstance(item, int): if item >= 0: keyboard.release(item) #update_pixels(0x000000) time.sleep(0.002)
28.289308
106
0.631392
b8495de8799d806a34a07d96c003a49ec34f2278
903
rs
Rust
src/rust/engine/client/src/pantsd_tests.rs
yoav-orca/pants
995448e9add343975844c7a43d5d64618fc4e4d9
[ "Apache-2.0" ]
1,806
2015-01-05T07:31:00.000Z
2022-03-31T11:35:41.000Z
src/rust/engine/client/src/pantsd_tests.rs
yoav-orca/pants
995448e9add343975844c7a43d5d64618fc4e4d9
[ "Apache-2.0" ]
9,565
2015-01-02T19:01:59.000Z
2022-03-31T23:25:16.000Z
src/rust/engine/client/src/pantsd_tests.rs
ryanking/pants
e45b00d2eb467b599966bca262405a5d74d27bdd
[ "Apache-2.0" ]
443
2015-01-06T20:17:57.000Z
2022-03-31T05:28:17.000Z
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::net::TcpStream; use crate::pantsd; use crate::pantsd_testing::launch_pantsd; fn assert_connect(port: u16) { assert!( port >= 1024, "Pantsd should never be running on a privileged port." ); let stream = TcpStream::connect(("0.0.0.0", port)).unwrap(); assert_eq!(port, stream.peer_addr().unwrap().port()); } #[test] fn test_address_integration() { let (_, pants_subprocessdir) = launch_pantsd(); let pantsd_metadata = pantsd::Metadata::mount(&pants_subprocessdir).unwrap(); let port = pantsd_metadata.port().unwrap(); assert_connect(port); } #[test] fn test_probe() { let (build_root, pants_subprocessdir) = launch_pantsd(); let port = pantsd::probe(&build_root, pants_subprocessdir.path()).unwrap(); assert_connect(port); }
25.8
79
0.708749
39e22a08ea893b123c61730e49177bac7c91e8cb
318
asm
Assembly
sort.asm
creativcoder/asm8085
94eee431aec7e49df6ea8df01cc4c5a370e86df7
[ "MIT" ]
null
null
null
sort.asm
creativcoder/asm8085
94eee431aec7e49df6ea8df01cc4c5a370e86df7
[ "MIT" ]
null
null
null
sort.asm
creativcoder/asm8085
94eee431aec7e49df6ea8df01cc4c5a370e86df7
[ "MIT" ]
null
null
null
;Rahul Sharma ;In place sorting of an array of numbers in memory jmp start ;data ;code start: lxi h,0000h ;stores array length mov b,m dcr b oloop: mov c,b lxi h,0001h ; top most data of array iloop: mov a,m inx h cmp m jz skip jc skip mov e,m mov m,a dcx h mov m,e inx h skip: dcr c jnz iloop dcr b jnz oloop hlt
10.6
50
0.716981
d5b1085155917a0fe0918af1f225067eeaa85a1c
4,087
swift
Swift
MetovaTestKitTests/AsynchronousTestingTests/AsyncTestingTests.swift
bobbyrehm/MetovaTestKit
a0286ae32c179df74da52f6d0dd3429e3f49bf8b
[ "MIT" ]
26
2016-05-08T01:39:14.000Z
2021-08-29T06:45:08.000Z
MetovaTestKitTests/AsynchronousTestingTests/AsyncTestingTests.swift
bobbyrehm/MetovaTestKit
a0286ae32c179df74da52f6d0dd3429e3f49bf8b
[ "MIT" ]
31
2016-05-08T02:47:26.000Z
2018-11-29T22:30:48.000Z
MetovaTestKitTests/AsynchronousTestingTests/AsyncTestingTests.swift
bobbyrehm/MetovaTestKit
a0286ae32c179df74da52f6d0dd3429e3f49bf8b
[ "MIT" ]
3
2016-08-09T14:14:39.000Z
2019-10-15T13:46:08.000Z
// // AsyncTestingTests.swift // MetovaTestKit // // Created by Logan Gauthier on 5/5/17. // Copyright © 2017 Metova. All rights reserved. // // MIT License // // 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. // import XCTest @testable import MetovaTestKit class AsyncTestingTests: MTKBaseTestCase { // MARK: WaitDurationTester class WaitDurationTester { private var startTime: CFTimeInterval? private var endTime: CFTimeInterval? func beginRecordingDuration() { startTime = CACurrentMediaTime() } func endRecordingDuration(file: StaticString = #file, line: UInt = #line) { guard startTime != nil else { XCTFail("Attempting to end duration recording prior to initiating it. You must call `beginRecordingDuration` before calling `endRecordingDuration`.", file: file, line: line) return } endTime = CACurrentMediaTime() } func assertActualDurationMatches(expectedDuration: TimeInterval, file: StaticString = #file, line: UInt = #line) { guard let endTime = endTime, let startTime = startTime else { XCTFail("Failed to capture the start or end time for calculating the wait duration.", file: file, line: line) return } let actualDuration = endTime - startTime XCTAssertEqual(actualDuration, expectedDuration, accuracy: 1.0, file: file, line: line) XCTAssertTrue(actualDuration >= expectedDuration, "Because the test action is dispatched after the expected duration, the actual recorded duration (\(actualDuration) seconds) should never be less than the expected duration (\(expectedDuration) seconds).") } } // MARK: Tests func testSuccessfulAsyncTest() { let waitDurationTester = WaitDurationTester() waitDurationTester.beginRecordingDuration() let testAction = { waitDurationTester.endRecordingDuration() } MTKWaitThenContinueTest(after: 3) testAction() waitDurationTester.assertActualDurationMatches(expectedDuration: 3) } func testAsyncTestFailsWhenAssertionFailsInTheTestActionClosure() { let expectedFailure = BasicTestFailureExpectation(description: "Description", filePath: "File", lineNumber: 1) expectTestFailure(expectedFailure) { let waitDurationTester = WaitDurationTester() waitDurationTester.beginRecordingDuration() MTKWaitThenContinueTest(after: 3) waitDurationTester.endRecordingDuration() self.recordFailure(withDescription: "Description", inFile: "File", atLine: 1, expected: true) waitDurationTester.assertActualDurationMatches(expectedDuration: 3) } } }
38.556604
267
0.658429
0f537d1b0b72d63004db9e3a39f471d215394335
2,831
sql
SQL
model/SELECT_t___FROM_spoilers_spoilers_t.sql
patm1987/spoilerroulette
70bb8214dcc7fc2a6e077373d4198d4bef27e3c6
[ "MIT" ]
null
null
null
model/SELECT_t___FROM_spoilers_spoilers_t.sql
patm1987/spoilerroulette
70bb8214dcc7fc2a6e077373d4198d4bef27e3c6
[ "MIT" ]
null
null
null
model/SELECT_t___FROM_spoilers_spoilers_t.sql
patm1987/spoilerroulette
70bb8214dcc7fc2a6e077373d4198d4bef27e3c6
[ "MIT" ]
null
null
null
INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Jar Jar''s Past', 'Jar Jar was one of the original Knights of Ren, establishing not just a pair but a high council of Siths.', 0); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('It''s a Trap', 'Admiral Ackbar dies after escaping the First Order''s armada. He did not realize that he was, in fact, falling into a trap!', 0); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Ren''s Parents', 'Kylo Ren is the offspring of Han and Leiah, led to the darkside despite the best efforts of Luke.', 1); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Rey''s Parents', 'Rey is the grandchild of Supreme Leader Snoke, her family hid her on Jakku trying to flee Snoke''s bounty hunters.', 0); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Finn''s Parents', 'Finn is Boba Fett''s son, he was sold to the First Order after his father''s disappearance.', 0); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Han Solong', 'So long Han! He dies trying to convert his son from the dark side.', 1); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Chewey''s Doom', 'Chewbacca dies trying to land the Millenium Falcon during a daring attack on Star Base Killer. After heroically landing the falcon, a harpoon is thrust through the cockpit into the copilot''s seat.', 0); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('C-3P0''s Arm', 'C-3P0 had his arm modified to serve as Leiah''s guardian. Its displayed capabilities include improved strength, speed, and some sort of concussive projectile.', 0); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('BB-D2', 'Although R2 appears to be disabled midway through the movie, he has actually been transferred into BB-8''s body to aid in the recovery of Luke''s location.', 0); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Poe''s Untimely Death', 'Despite appearing to die in a Tie Fighter crash, Poe actually survives to save the day two more times. AKA: the soap opera death!', 1); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Stay for the Credits', 'If you stay after the credits, a mysterious figure is seen rescuing Han Solo from his apparent death.', 0); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Sleepy Finn', 'An egg after the credits seems to show Snoke activating Finn as a sleeper agent.', 0); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Han''s Divorce', 'For reasons left to the imagination, Han and Leia are divorced prior to the events of this movie.', 1); INSERT INTO spoilers.spoilers (title, body, factual) VALUES ('Leia''s Death', 'Leia is killed trying to protect Rey in a scene appearing to poorly mimic Obi Wan''s death in A New Hope...', 0);
202.214286
283
0.750971
dda0c9f1e2978ccf35dc275eb5383741c0e138e8
476
go
Go
io.go
nutterthanos/splash
cbcacdbd589500c3f5b87c87bcb8e1b44fdffc56
[ "MIT" ]
7
2020-08-27T21:40:21.000Z
2021-11-21T06:58:30.000Z
io.go
nutterthanos/splash
cbcacdbd589500c3f5b87c87bcb8e1b44fdffc56
[ "MIT" ]
7
2020-09-03T09:32:08.000Z
2022-03-13T06:10:53.000Z
io.go
nutterthanos/splash
cbcacdbd589500c3f5b87c87bcb8e1b44fdffc56
[ "MIT" ]
5
2020-11-10T02:56:20.000Z
2021-05-05T00:22:18.000Z
package main import ( "bytes" "io" ) type ReadSeekCloser interface { io.Reader io.Seeker io.Closer } type ByteCloser struct { r *bytes.Reader } func (bc ByteCloser) Read(p []byte) (int, error) { return bc.r.Read(p) } func (bc ByteCloser) Seek(offset int64, whence int) (int64, error) { return bc.r.Seek(offset, whence) } func (bc ByteCloser) Close() error { return nil } func NewByteCloser(data []byte) ByteCloser { return ByteCloser{bytes.NewReader(data)} }
14.424242
68
0.69958
1fa927409a1886a387721b1f7a7514a801a5a539
939
html
HTML
src/app/components/registration-form/registration-form.component.html
AlexArendsen/nulist-app-angular
94bd28cba6075abb0296fc96c7e0299fdefb6aa2
[ "MIT" ]
null
null
null
src/app/components/registration-form/registration-form.component.html
AlexArendsen/nulist-app-angular
94bd28cba6075abb0296fc96c7e0299fdefb6aa2
[ "MIT" ]
null
null
null
src/app/components/registration-form/registration-form.component.html
AlexArendsen/nulist-app-angular
94bd28cba6075abb0296fc96c7e0299fdefb6aa2
[ "MIT" ]
null
null
null
<form action="javascript:void(0)"> <div class="form-group"> <label for="username-field">Username</label> <input type="text" id="username-field" name="username" class="form-control" [(ngModel)]="username" placeholder="Username" /> </div> <div class="form-group"> <label for="password-field">Password</label> <input type="password" id="password-field" name="password" class="form-control" [(ngModel)]="password" placeholder="Password" /> </div> <div class="form-group"> <label for="password-confirm-field">Confirm Password</label> <input type="password" id="password-confirm-field" name="password-confirm" class="form-control" [(ngModel)]="passwordConfirm" placeholder="Confirm Password" /> </div> <button class="btn btn-primary" type="submit" (click)="submit()"> Register </button> </form>
23.475
64
0.607029
f015bf5e2e71b04cd941a3ba7f14c687b44c2b00
263
py
Python
apps/transactions/__init__.py
lsdlab/djshop_toturial
6d450225cc05e6a1ecd161de2b522e1af0b68cc0
[ "MIT" ]
null
null
null
apps/transactions/__init__.py
lsdlab/djshop_toturial
6d450225cc05e6a1ecd161de2b522e1af0b68cc0
[ "MIT" ]
6
2020-06-07T15:18:58.000Z
2021-09-22T19:07:33.000Z
apps/transactions/__init__.py
lsdlab/djshop_toturial
6d450225cc05e6a1ecd161de2b522e1af0b68cc0
[ "MIT" ]
null
null
null
from django.apps import AppConfig class TransactionsConfig(AppConfig): name = 'apps.transactions' verbose_name = "Transactions" def ready(self): import apps.transactions.signals default_app_config = 'apps.transactions.TransactionsConfig'
20.230769
59
0.752852
be7a64f77320fd681c829169bf63f1da8ca71b48
5,042
rs
Rust
src/helpers.rs
fewensa/microkv
89d983721e588dfad1460dcdf1c48c97c1ef7a14
[ "MIT" ]
null
null
null
src/helpers.rs
fewensa/microkv
89d983721e588dfad1460dcdf1c48c97c1ef7a14
[ "MIT" ]
null
null
null
src/helpers.rs
fewensa/microkv
89d983721e588dfad1460dcdf1c48c97c1ef7a14
[ "MIT" ]
null
null
null
use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use secstr::{SecStr, SecVec}; use serde::de::DeserializeOwned; use serde::Serialize; use sodiumoxide::crypto::secretbox::Nonce; use sodiumoxide::crypto::secretbox::{self, Key}; use crate::errors::{ErrorType, KVError, Result}; /// Defines the directory path where a key-value store /// (or multiple) can be interacted with. pub(crate) const DEFAULT_WORKSPACE_PATH: &str = ".microkv/"; /// Helper that retrieves the home directory by resolving $HOME #[inline] pub fn get_home_dir() -> PathBuf { dirs::home_dir().unwrap() } /// Helper that forms an absolute path from a given database name and the default workspace path. #[inline] pub fn get_db_path<S: AsRef<str>>(name: S) -> PathBuf { let mut path = get_home_dir(); path.push(DEFAULT_WORKSPACE_PATH); get_db_path_with_base_path(name, path) } /// with base path #[inline] pub fn get_db_path_with_base_path<S: AsRef<str>>(name: S, mut base_path: PathBuf) -> PathBuf { base_path.push(name.as_ref()); base_path.set_extension("kv"); base_path } /// read file and deserialize use bincode #[inline] pub fn read_file_and_deserialize_bincode<V>(path: &PathBuf) -> Result<V> where V: DeserializeOwned + 'static, { // read kv raw serialized structure to kv_raw let mut kv_raw: Vec<u8> = Vec::new(); File::open(path)?.read_to_end(&mut kv_raw)?; bincode::deserialize(&kv_raw).map_err(|_e| KVError { error: ErrorType::FileError, msg: Some(format!( "Failed read file {:?} an deserialize use bincode", path )), }) } /// gen nonce pub fn gen_nonce() -> Nonce { secretbox::gen_nonce() } /// encode value pub fn encode_value<V>(value: &V, pwd: &Option<SecStr>, nonce: &Nonce) -> Result<SecVec<u8>> where V: Serialize, { // serialize the object for committing to db let ser_val: Vec<u8> = bincode::serialize(&value).unwrap(); // encrypt and secure value if password is available let value: SecVec<u8> = match pwd { // encrypt using AEAD and secure memory Some(pwd) => { let key: Key = Key::from_slice(pwd.unsecure()).unwrap(); SecVec::new(secretbox::seal(&ser_val, nonce, &key)) } // otherwise initialize secure serialized object to insert to BTreeMap None => SecVec::new(ser_val), }; Ok(value) } /// decode value pub fn decode_value<V>(value: &SecVec<u8>, pwd: &Option<SecStr>, nonce: &Nonce) -> Result<V> where V: DeserializeOwned + 'static, { // get value to deserialize. If password is set, retrieve the value, and decrypt it // using AEAD. Otherwise just get the value and return let deser_val = match pwd { Some(pwd) => { // initialize key from pwd slice let key = match Key::from_slice(pwd.unsecure()) { Some(k) => k, None => { return Err(KVError { error: ErrorType::CryptoError, msg: Some("cannot derive key from password hash".to_string()), }); } }; // borrow secured value by reference, and decrypt before deserializing match secretbox::open(value.unsecure(), nonce, &key) { Ok(r) => r, Err(_) => { return Err(KVError { error: ErrorType::CryptoError, msg: Some("cannot validate value being decrypted".to_string()), }); } } } // if no password, return value as-is None => value.unsecure().to_vec(), }; // finally deserialize into deserializable object to return as let value = bincode::deserialize(&deser_val).map_err(|e| KVError { error: ErrorType::KVError, msg: Some(format!( "cannot deserialize into specified object type: {:?}", e )), })?; Ok(value) } /// Writes the IndexMap to persistent storage after encrypting with secure crypto construction. pub(crate) fn persist_serialize<S>(path: &PathBuf, object: &S) -> Result<()> where S: Serialize, { // initialize workspace directory if not exists match path.parent() { Some(path) => { if !path.is_dir() { std::fs::create_dir_all(path)?; } } None => { return Err(KVError { error: ErrorType::FileError, msg: Some("The store file parent path isn't sound".to_string()), }); } } // check if path to db exists, if not create it let path = Path::new(path); let mut file: File = OpenOptions::new().write(true).create(true).open(path)?; // acquire a file lock that unlocks at the end of scope // let _file_lock = Arc::new(Mutex::new(0)); let ser = bincode::serialize(object).unwrap(); file.write_all(&ser)?; Ok(()) }
31.5125
97
0.592622
70bf08d17ee5ecd10f37d4b4449a922a11003387
2,522
swift
Swift
Pods/AWCorePlatformHelpers/AWCorePlatformHelpers/UIColor+Format.swift
bhargavat/AW-iOS-Pods
8ee6ebd2d273e6166031970f2884d8087c535832
[ "Apache-2.0" ]
null
null
null
Pods/AWCorePlatformHelpers/AWCorePlatformHelpers/UIColor+Format.swift
bhargavat/AW-iOS-Pods
8ee6ebd2d273e6166031970f2884d8087c535832
[ "Apache-2.0" ]
null
null
null
Pods/AWCorePlatformHelpers/AWCorePlatformHelpers/UIColor+Format.swift
bhargavat/AW-iOS-Pods
8ee6ebd2d273e6166031970f2884d8087c535832
[ "Apache-2.0" ]
null
null
null
// // UIColor+Format.swift // AWCorePlatformHelpers // // Copyright © 2016 VMware, Inc. All rights reserved. This product is protected // by copyright and intellectual property laws in the United States and other // countries as well as by international treaties. VMware products are covered // by one or more patents listed at http://www.vmware.com/go/patents. // import Foundation private let AWColorComponentRedKey:String = "Red" private let AWColorComponentGreenKey:String = "Green" private let AWColorComponentBlueKey:String = "Blue" private let AWColorComponentAlphaKey:String = "Alpha" extension UIColor { public convenience init(number:Int) { let rgba: Int = number let redValue: Int = ((rgba & 0xff0000) >> 16) let greenValue: Int = ((rgba & 0x00ff00) >> 8) let blueValue:Int = (rgba & 0x0000ff) let red = CGFloat(redValue)/255.0 let green = CGFloat(greenValue)/255.0 let blue = CGFloat(blueValue)/255.0 self.init(red: red, green:green, blue: blue, alpha:1.0) } @objc (AW_colorComponents) public func colorComponents() -> Dictionary<String,NSNumber> { var colorInfo: Dictionary<String,NSNumber> = Dictionary() if let components = self.cgColor.components { colorInfo[AWColorComponentRedKey] = NSNumber(value: Float((components[0])*255) as Float) colorInfo[AWColorComponentGreenKey] = NSNumber(value: Float((components[1])*255) as Float) colorInfo[AWColorComponentBlueKey] = NSNumber(value: Float((components[2])*255) as Float) colorInfo[AWColorComponentAlphaKey] = NSNumber(value: Float((components[3])) as Float) } return colorInfo; } func transformARGBToHex() -> UInt? { var fRed: CGFloat = 0 var fGreen: CGFloat = 0 var fBlue: CGFloat = 0 var fAlpha: CGFloat = 0 if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) { let iRed = UInt(fRed * 255.0) let iGreen = UInt(fGreen * 255.0) let iBlue = UInt(fBlue * 255.0) let iAlpha = UInt(fAlpha * 255.0) // (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue). let rgb = ((iAlpha & 0xFF) << 24) | ((iRed & 0xFF) << 16) | ((iGreen & 0xFF) << 8) | (iBlue & 0xFF) return rgb } else { // Could not extract RGBA components: return nil } } }
38.212121
111
0.615781
d4dc2fd877b67683141c81f7787ff0a613b6239e
128
rs
Rust
src/test/ui/impl-trait/issues/issue-70971.rs
mbc-git/rust
2c7bc5e33c25e29058cbafefe680da8d5e9220e9
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
66,762
2015-01-01T08:32:03.000Z
2022-03-31T23:26:40.000Z
src/test/ui/impl-trait/issues/issue-70971.rs
Seanpm2001-Mozilla/rust
2885c474823637ae69c5967327327a337aebedb2
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
76,993
2015-01-01T00:06:33.000Z
2022-03-31T23:59:15.000Z
src/test/ui/impl-trait/issues/issue-70971.rs
Seanpm2001-Mozilla/rust
2885c474823637ae69c5967327327a337aebedb2
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
11,787
2015-01-01T00:01:19.000Z
2022-03-31T19:03:42.000Z
fn main() { let x : (impl Copy,) = (true,); //~^ `impl Trait` not allowed outside of function and method return types }
25.6
77
0.609375
9c61fdf2a3066087d39b9732047a8c5f2d578a08
880
js
JavaScript
src/components/PostsPage/PostsPage.js
JulianMayorga/FullStackBlog
0989555e070168af7f4ff6094a2e1a1a45474172
[ "MIT" ]
null
null
null
src/components/PostsPage/PostsPage.js
JulianMayorga/FullStackBlog
0989555e070168af7f4ff6094a2e1a1a45474172
[ "MIT" ]
null
null
null
src/components/PostsPage/PostsPage.js
JulianMayorga/FullStackBlog
0989555e070168af7f4ff6094a2e1a1a45474172
[ "MIT" ]
null
null
null
import React from 'react'; import { RouteTransition, presets } from 'react-router-transition'; import PostItem from '../PostItem'; import NewPostButton from '../NewPostButton'; import { post as postPropType } from '../propTypes'; export default class PostsPage extends React.Component { static propTypes = { location: React.PropTypes.shape({ pathname: React.PropTypes.string }), posts: React.PropTypes.arrayOf(postPropType), fetchPosts: React.PropTypes.func } static defaultProps = { posts: [] } componentWillMount() { this.props.fetchPosts(); } render() { return ( <section> <NewPostButton /> <RouteTransition {...presets.pop} pathname={this.props.location.pathname}> {this.props.posts.map(post => <PostItem key={post._id} post={post} />)} </RouteTransition> </section> ); } }
26.666667
82
0.653409
7ea168bbafb02ad70f1848084a4f33004bcf9a87
3,248
kt
Kotlin
http4k-format/kotlinx-serialization/src/main/kotlin/org/http4k/format/ConfigurableKotlinxSerialization.kt
NersesAM/http4k
20385465c05b1497b92672e396264988594a295e
[ "Apache-2.0" ]
null
null
null
http4k-format/kotlinx-serialization/src/main/kotlin/org/http4k/format/ConfigurableKotlinxSerialization.kt
NersesAM/http4k
20385465c05b1497b92672e396264988594a295e
[ "Apache-2.0" ]
null
null
null
http4k-format/kotlinx-serialization/src/main/kotlin/org/http4k/format/ConfigurableKotlinxSerialization.kt
NersesAM/http4k
20385465c05b1497b92672e396264988594a295e
[ "Apache-2.0" ]
null
null
null
package org.http4k.format import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonBuilder import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.boolean import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.doubleOrNull import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.long import java.math.BigDecimal import java.math.BigInteger import kotlinx.serialization.json.Json as KotlinxJson open class ConfigurableKotlinxSerialization( json: JsonBuilder.() -> Unit, ) : Json<JsonElement> { private val json = KotlinxJson { json() } private val prettyJson = KotlinxJson { json() prettyPrint = true } override fun typeOf(value: JsonElement) = when (value) { is JsonNull -> JsonType.Null is JsonPrimitive -> when { value.isString -> JsonType.String value.booleanOrNull != null -> JsonType.Boolean value.doubleOrNull != null -> JsonType.Number else -> throw RuntimeException() } is JsonArray -> JsonType.Array is JsonObject -> JsonType.Object else -> throw IllegalArgumentException("Don't know how to translate $value") } override fun JsonElement.asPrettyJsonString() = prettyJson.encodeToString(JsonElement.serializer(), this) override fun JsonElement.asCompactJsonString() = json.encodeToString(JsonElement.serializer(), this) override fun String.asJsonObject() = json.decodeFromString(JsonObject.serializer(), this) override fun String?.asJsonValue() = JsonPrimitive(this) override fun Int?.asJsonValue() = JsonPrimitive(this) override fun Double?.asJsonValue() = JsonPrimitive(this) override fun Long?.asJsonValue() = JsonPrimitive(this) override fun BigDecimal?.asJsonValue() = JsonPrimitive("$this") override fun BigInteger?.asJsonValue() = JsonPrimitive(this) override fun Boolean?.asJsonValue() = JsonPrimitive(this) override fun <T : Iterable<JsonElement>> T.asJsonArray() = JsonArray(this.toList()) override fun <LIST : Iterable<Pair<String, JsonElement>>> LIST.asJsonObject() = JsonObject(this.toMap()) override fun fields(node: JsonElement) = if (node !is JsonObject) emptyList() else node.toList() override fun elements(value: JsonElement) = when (value) { is JsonObject -> value.values is JsonArray -> value.jsonArray else -> emptyList() } override fun text(value: JsonElement) = value.jsonPrimitive.content override fun bool(value: JsonElement) = value.jsonPrimitive.boolean override fun integer(value: JsonElement) = value.jsonPrimitive.long override fun decimal(value: JsonElement): BigDecimal = BigDecimal(value.jsonPrimitive.content) override fun textValueOf(node: JsonElement, name: String) = when (node) { is JsonObject -> node[name]?.let { it.jsonPrimitive.content } else -> throw IllegalArgumentException("node is not an object") } }
36.909091
109
0.723214
0bae145441b5ce60726127f98ed4e7c41acfe8d3
490
js
JavaScript
014.route.js
qingbing/learn-nodejs
9e1ee492a8586307d271f59042953841624cca4f
[ "MIT" ]
null
null
null
014.route.js
qingbing/learn-nodejs
9e1ee492a8586307d271f59042953841624cca4f
[ "MIT" ]
null
null
null
014.route.js
qingbing/learn-nodejs
9e1ee492a8586307d271f59042953841624cca4f
[ "MIT" ]
null
null
null
var http = require('http'); var router = require('./014.route.router'); var handlers = require('./014.handler'); var handlers = { '/favicon.ico': handlers.favicon, '/': handlers.home, '/home': handlers.home, '/text': handlers.text, '/api': handlers.api }; // 响应返回html var server = http.createServer(function (request, response) { router.route(request, response, handlers); }); server.listen('3007', '127.0.0.1'); console.log('Server started on localhost 3007');
23.333333
61
0.653061
116f211ce763675b40dd9f96a472e0324c6e8ed7
2,591
rs
Rust
marked/src/logger.rs
joshstoik1/marked
1010a62cfd57e8ecd0ce505f57a3a4e744b1cba1
[ "Apache-2.0", "MIT" ]
6
2020-03-15T19:53:41.000Z
2022-03-24T08:41:26.000Z
marked/src/logger.rs
joshstoik1/marked
1010a62cfd57e8ecd0ce505f57a3a4e744b1cba1
[ "Apache-2.0", "MIT" ]
1
2020-03-17T04:26:57.000Z
2020-03-26T14:48:28.000Z
marked/src/logger.rs
joshstoik1/marked
1010a62cfd57e8ecd0ce505f57a3a4e744b1cba1
[ "Apache-2.0", "MIT" ]
1
2022-03-31T17:47:00.000Z
2022-03-31T17:47:00.000Z
//! A very simple Log output implementation for testing and any CLIs. use std::error::Error as StdError; use std::io::Write; #[cfg(test)] use std::sync::Once; /// Conveniently compact type alias for dyn Trait `std::error::Error`. type Flaw = Box<dyn StdError + Send + Sync + 'static>; struct Monolog { other: log::Level } impl log::Log for Monolog { fn enabled(&self, meta: &log::Metadata<'_>) -> bool { meta.level() <= self.other || meta.target().starts_with("marked") } fn log(&self, record: &log::Record<'_>) { if self.enabled(record.metadata()) { writeln!( std::io::stderr(), "{:5} {} {}: {}", record.level(), record.target(), std::thread::current().name().unwrap_or("-"), record.args() ).ok(); } } fn flush(&self) { std::io::stderr().flush().ok(); } } /// Setup logger for a test run, if not already setup, based on TEST_LOG /// environment variable. /// /// `TEST_LOG=0` : The default, no logging enabled. /// /// `TEST_LOG=1` : Info log level. /// /// `TEST_LOG=2` : Debug log level, Info for deps. /// /// `TEST_LOG=3` : Debug log level (for all). /// /// `TEST_LOG=4` : Trace log level, Debug for deps. /// /// `TEST_LOG=5`+ : Trace log level (for all). #[cfg(test)] pub(crate) fn ensure_logger() { static TEST_LOG_INIT: Once = Once::new(); TEST_LOG_INIT.call_once(|| { let level = if let Ok(l) = std::env::var("TEST_LOG") { l.parse().expect("TEST_LOG parse integer") } else { 0 }; if level > 0 { setup_logger(level).expect("setup logger"); } }); } /// Setup logger based on specified level. /// /// Will fail if already setup. pub fn setup_logger(level: u32) -> Result<(), Flaw> { if level > 0 { if level == 1 { log::set_max_level(log::LevelFilter::Info) } else if level < 4 { log::set_max_level(log::LevelFilter::Debug) } else { log::set_max_level(log::LevelFilter::Trace) } let other = match level { 1..=2 => log::Level::Info, 3..=4 => log::Level::Debug, _ => log::Level::Trace, // unfiltered }; log::set_boxed_logger(Box::new(Monolog { other }))?; } Ok(()) } #[cfg(test)] mod tests { use super::ensure_logger; use log::{debug, trace}; #[test] fn log_setup() { ensure_logger(); debug!("log message"); trace!("log message 2"); } }
25.15534
73
0.533385
9a24383b74ddd944f517010aa30ef2277854a40e
407
css
CSS
css/style.css
bamsi/MicroverseHajiRoberto
e0d589595f8f9e31bcbd36cba47ad90f3c8f45c9
[ "MIT" ]
null
null
null
css/style.css
bamsi/MicroverseHajiRoberto
e0d589595f8f9e31bcbd36cba47ad90f3c8f45c9
[ "MIT" ]
null
null
null
css/style.css
bamsi/MicroverseHajiRoberto
e0d589595f8f9e31bcbd36cba47ad90f3c8f45c9
[ "MIT" ]
null
null
null
#image { display: block; max-width: 100%; height: auto; margin: 0 auto; } #main { margin-left: 4rem; margin-right: 4rem; } #title { text-align: center; font-weight: bold; font-size: 20px; } #img-caption { text-align: center; font-size: 12px; } #tribute-info { font-size: 14px; } .footer-link { font-size: 12px; } #quote { font-style: italic; }
11.970588
23
0.565111
58150c1d8eeb469541fe11f31383cb8e76a34584
1,942
h
C
uwpapp/mupdfuwplib/mupdfwinrt_app/PrintPage.h
softkannan/komicreader
c61e922a7fd590718fc250ce411edccdc7fb4547
[ "MIT" ]
1
2020-09-18T06:02:53.000Z
2020-09-18T06:02:53.000Z
uwpapp/mupdfuwplib/mupdfwinrt_app/PrintPage.h
softkannan/komicreader
c61e922a7fd590718fc250ce411edccdc7fb4547
[ "MIT" ]
null
null
null
uwpapp/mupdfuwplib/mupdfwinrt_app/PrintPage.h
softkannan/komicreader
c61e922a7fd590718fc250ce411edccdc7fb4547
[ "MIT" ]
null
null
null
#pragma once #include <wrl\implements.h> #include <d2d1.h> #include <windows.graphics.printing.h> #include <printpreview.h> #include <documentsource.h> #include "MainPage.xaml.h" using namespace Microsoft::WRL; using namespace mupdf_cpp; /* This is the interface to the print thread calls */ class PrintPages : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::WinRtClassicComMix>, ABI::Windows::Graphics::Printing::IPrintDocumentSource, IPrintDocumentPageSource, IPrintPreviewPageCollection> { private: InspectableClass(L"Windows.Graphics.Printing.IPrintDocumentSource", BaseTrust); public: HRESULT RuntimeClassInitialize(IUnknown* pageRenderer) { HRESULT hr = (pageRenderer != nullptr) ? S_OK : E_INVALIDARG; if (SUCCEEDED(hr)) { m_paginate_called = false; m_totalpages = 1; m_height = 0.f; m_width = 0.f; m_renderer = reinterpret_cast<MainPage^>(pageRenderer); } return hr; } IFACEMETHODIMP GetPreviewPageCollection(IPrintDocumentPackageTarget* doc_target, IPrintPreviewPageCollection** doc_collection); IFACEMETHODIMP MakeDocument(IInspectable* doc_options, IPrintDocumentPackageTarget* doc_target); IFACEMETHODIMP Paginate(uint32 current_jobpage, IInspectable* doc_options); IFACEMETHODIMP MakePage(uint32 desired_jobpage, float width, float height); void ResetPreview(); private: float TransformedPageSize(float desired_width, float desired_height, Windows::Foundation::Size* preview_size); uint32 m_totalpages; bool m_paginate_called; float m_height; float m_width; D2D1_RECT_F m_imageable_rect; MainPage^ m_renderer; Microsoft::WRL::ComPtr<IPrintPreviewDxgiPackageTarget> m_dxgi_previewtarget; void DrawPreviewSurface(float width, float height, float scale_in, D2D1_RECT_F contentBox, uint32 page_num, IPrintPreviewDxgiPackageTarget* previewTarget); };
32.366667
125
0.762616
7d750637ac849d60ac00034848664c63f5bebc27
37,288
html
HTML
tools/pmd-bin-5.1.1/docs/xref/net/sourceforge/pmd/lang/java/rule/unnecessary/UselessOverridingMethodRule.html
ewiger/MetricsCarpet
b0b22f44f4b6e61e78362390983a3e1bb179ee13
[ "MIT" ]
1
2019-01-13T13:04:45.000Z
2019-01-13T13:04:45.000Z
tools/pmd-bin-5.1.1/docs/xref/net/sourceforge/pmd/lang/java/rule/unnecessary/UselessOverridingMethodRule.html
MetricsCarpet/MetricsCarpet
b0b22f44f4b6e61e78362390983a3e1bb179ee13
[ "MIT" ]
null
null
null
tools/pmd-bin-5.1.1/docs/xref/net/sourceforge/pmd/lang/java/rule/unnecessary/UselessOverridingMethodRule.html
MetricsCarpet/MetricsCarpet
b0b22f44f4b6e61e78362390983a3e1bb179ee13
[ "MIT" ]
null
null
null
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>UselessOverridingMethodRule xref</title> <link type="text/css" rel="stylesheet" href="../../../../../../../stylesheet.css" /> </head> <body> <div id="overview"><a href="../../../../../../../../apidocs/net/sourceforge/pmd/lang/java/rule/unnecessary/UselessOverridingMethodRule.html">View Javadoc</a></div><pre> <a class="jxr_linenumber" name="1" href="#1">1</a> <em class="jxr_javadoccomment">/**</em> <a class="jxr_linenumber" name="2" href="#2">2</a> <em class="jxr_javadoccomment"> * BSD-style license; for more info see <a href="http://pmd.sourceforge.net/license.html" target="alexandria_uri">http://pmd.sourceforge.net/license.html</a></em> <a class="jxr_linenumber" name="3" href="#3">3</a> <em class="jxr_javadoccomment"> */</em> <a class="jxr_linenumber" name="4" href="#4">4</a> <strong class="jxr_keyword">package</strong> net.sourceforge.pmd.lang.java.rule.unnecessary; <a class="jxr_linenumber" name="5" href="#5">5</a> <a class="jxr_linenumber" name="6" href="#6">6</a> <strong class="jxr_keyword">import</strong> java.util.ArrayList; <a class="jxr_linenumber" name="7" href="#7">7</a> <strong class="jxr_keyword">import</strong> java.util.List; <a class="jxr_linenumber" name="8" href="#8">8</a> <a class="jxr_linenumber" name="9" href="#9">9</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.ast.Node; <a class="jxr_linenumber" name="10" href="#10">10</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTAnnotation; <a class="jxr_linenumber" name="11" href="#11">11</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTArgumentList; <a class="jxr_linenumber" name="12" href="#12">12</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTArguments; <a class="jxr_linenumber" name="13" href="#13">13</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTBlock; <a class="jxr_linenumber" name="14" href="#14">14</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceBodyDeclaration; <a class="jxr_linenumber" name="15" href="#15">15</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; <a class="jxr_linenumber" name="16" href="#16">16</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; <a class="jxr_linenumber" name="17" href="#17">17</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; <a class="jxr_linenumber" name="18" href="#18">18</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTFormalParameters; <a class="jxr_linenumber" name="19" href="#19">19</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTImplementsList; <a class="jxr_linenumber" name="20" href="#20">20</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTMarkerAnnotation; <a class="jxr_linenumber" name="21" href="#21">21</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; <a class="jxr_linenumber" name="22" href="#22">22</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator; <a class="jxr_linenumber" name="23" href="#23">23</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTName; <a class="jxr_linenumber" name="24" href="#24">24</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTNameList; <a class="jxr_linenumber" name="25" href="#25">25</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression; <a class="jxr_linenumber" name="26" href="#26">26</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix; <a class="jxr_linenumber" name="27" href="#27">27</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix; <a class="jxr_linenumber" name="28" href="#28">28</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTResultType; <a class="jxr_linenumber" name="29" href="#29">29</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTStatement; <a class="jxr_linenumber" name="30" href="#30">30</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; <a class="jxr_linenumber" name="31" href="#31">31</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; <a class="jxr_linenumber" name="32" href="#32">32</a> <strong class="jxr_keyword">import</strong> net.sourceforge.pmd.lang.rule.properties.BooleanProperty; <a class="jxr_linenumber" name="33" href="#33">33</a> <a class="jxr_linenumber" name="34" href="#34">34</a> <em class="jxr_javadoccomment">/**</em> <a class="jxr_linenumber" name="35" href="#35">35</a> <em class="jxr_javadoccomment"> * @author Romain Pelisse, bugfix for [ 1522517 ] False +: UselessOverridingMethod</em> <a class="jxr_linenumber" name="36" href="#36">36</a> <em class="jxr_javadoccomment"> */</em> <a class="jxr_linenumber" name="37" href="#37">37</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../../../../net/sourceforge/pmd/lang/java/rule/unnecessary/UselessOverridingMethodRule.html">UselessOverridingMethodRule</a> <strong class="jxr_keyword">extends</strong> <a href="../../../../../../../net/sourceforge/pmd/lang/java/rule/AbstractJavaRule.html">AbstractJavaRule</a> { <a class="jxr_linenumber" name="38" href="#38">38</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">final</strong> List&lt;String&gt; exceptions; <a class="jxr_linenumber" name="39" href="#39">39</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">boolean</strong> ignoreAnnotations; <a class="jxr_linenumber" name="40" href="#40">40</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> String CLONE = <span class="jxr_string">"clone"</span>; <a class="jxr_linenumber" name="41" href="#41">41</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> String OBJECT = <span class="jxr_string">"Object"</span>; <a class="jxr_linenumber" name="42" href="#42">42</a> <a class="jxr_linenumber" name="43" href="#43">43</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> <a href="../../../../../../../net/sourceforge/pmd/lang/rule/properties/BooleanProperty.html">BooleanProperty</a> IGNORE_ANNOTATIONS_DESCRIPTOR = <strong class="jxr_keyword">new</strong> <a href="../../../../../../../net/sourceforge/pmd/lang/rule/properties/BooleanProperty.html">BooleanProperty</a>( <a class="jxr_linenumber" name="44" href="#44">44</a> <span class="jxr_string">"ignoreAnnotations"</span>, <span class="jxr_string">"Ignore annotations"</span>, false, 1.0f); <a class="jxr_linenumber" name="45" href="#45">45</a> <a class="jxr_linenumber" name="46" href="#46">46</a> <strong class="jxr_keyword">public</strong> <a href="../../../../../../../net/sourceforge/pmd/lang/java/rule/unnecessary/UselessOverridingMethodRule.html">UselessOverridingMethodRule</a>() { <a class="jxr_linenumber" name="47" href="#47">47</a> definePropertyDescriptor(IGNORE_ANNOTATIONS_DESCRIPTOR); <a class="jxr_linenumber" name="48" href="#48">48</a> <a class="jxr_linenumber" name="49" href="#49">49</a> exceptions = <strong class="jxr_keyword">new</strong> ArrayList&lt;String&gt;(1); <a class="jxr_linenumber" name="50" href="#50">50</a> exceptions.add(<span class="jxr_string">"CloneNotSupportedException"</span>); <a class="jxr_linenumber" name="51" href="#51">51</a> } <a class="jxr_linenumber" name="52" href="#52">52</a> <a class="jxr_linenumber" name="53" href="#53">53</a> @Override <a class="jxr_linenumber" name="54" href="#54">54</a> <strong class="jxr_keyword">public</strong> Object visit(<a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTCompilationUnit.html">ASTCompilationUnit</a> node, Object data) { <a class="jxr_linenumber" name="55" href="#55">55</a> init(); <a class="jxr_linenumber" name="56" href="#56">56</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="57" href="#57">57</a> } <a class="jxr_linenumber" name="58" href="#58">58</a> <a class="jxr_linenumber" name="59" href="#59">59</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">void</strong> init() { <a class="jxr_linenumber" name="60" href="#60">60</a> ignoreAnnotations = getProperty(IGNORE_ANNOTATIONS_DESCRIPTOR); <a class="jxr_linenumber" name="61" href="#61">61</a> } <a class="jxr_linenumber" name="62" href="#62">62</a> <a class="jxr_linenumber" name="63" href="#63">63</a> @Override <a class="jxr_linenumber" name="64" href="#64">64</a> <strong class="jxr_keyword">public</strong> Object visit(<a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTImplementsList.html">ASTImplementsList</a> clz, Object data) { <a class="jxr_linenumber" name="65" href="#65">65</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(clz, data); <a class="jxr_linenumber" name="66" href="#66">66</a> } <a class="jxr_linenumber" name="67" href="#67">67</a> <a class="jxr_linenumber" name="68" href="#68">68</a> @Override <a class="jxr_linenumber" name="69" href="#69">69</a> <strong class="jxr_keyword">public</strong> Object visit(<a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTClassOrInterfaceDeclaration.html">ASTClassOrInterfaceDeclaration</a> clz, Object data) { <a class="jxr_linenumber" name="70" href="#70">70</a> <strong class="jxr_keyword">if</strong> (clz.isInterface()) { <a class="jxr_linenumber" name="71" href="#71">71</a> <strong class="jxr_keyword">return</strong> data; <a class="jxr_linenumber" name="72" href="#72">72</a> } <a class="jxr_linenumber" name="73" href="#73">73</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(clz, data); <a class="jxr_linenumber" name="74" href="#74">74</a> } <a class="jxr_linenumber" name="75" href="#75">75</a> <a class="jxr_linenumber" name="76" href="#76">76</a> <em class="jxr_comment">//TODO: this method should be externalize into an utility class, shouldn't it ?</em> <a class="jxr_linenumber" name="77" href="#77">77</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">boolean</strong> isMethodType(<a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTMethodDeclaration.html">ASTMethodDeclaration</a> node, String methodType) { <a class="jxr_linenumber" name="78" href="#78">78</a> <strong class="jxr_keyword">boolean</strong> result = false; <a class="jxr_linenumber" name="79" href="#79">79</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTResultType.html">ASTResultType</a> type = node.getResultType(); <a class="jxr_linenumber" name="80" href="#80">80</a> <strong class="jxr_keyword">if</strong> (type != <strong class="jxr_keyword">null</strong>) { <a class="jxr_linenumber" name="81" href="#81">81</a> result = type.hasDescendantMatchingXPath(<span class="jxr_string">"./Type/ReferenceType/ClassOrInterfaceType[@Image = '"</span> <a class="jxr_linenumber" name="82" href="#82">82</a> + methodType + <span class="jxr_string">"']"</span>); <a class="jxr_linenumber" name="83" href="#83">83</a> } <a class="jxr_linenumber" name="84" href="#84">84</a> <strong class="jxr_keyword">return</strong> result; <a class="jxr_linenumber" name="85" href="#85">85</a> } <a class="jxr_linenumber" name="86" href="#86">86</a> <a class="jxr_linenumber" name="87" href="#87">87</a> <em class="jxr_comment">//TODO: this method should be externalize into an utility class, shouldn't it ?</em> <a class="jxr_linenumber" name="88" href="#88">88</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">boolean</strong> isMethodThrowingType(<a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTMethodDeclaration.html">ASTMethodDeclaration</a> node, List&lt;String&gt; exceptedExceptions) { <a class="jxr_linenumber" name="89" href="#89">89</a> <strong class="jxr_keyword">boolean</strong> result = false; <a class="jxr_linenumber" name="90" href="#90">90</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTNameList.html">ASTNameList</a> thrownsExceptions = node.getFirstChildOfType(ASTNameList.<strong class="jxr_keyword">class</strong>); <a class="jxr_linenumber" name="91" href="#91">91</a> <strong class="jxr_keyword">if</strong> (thrownsExceptions != <strong class="jxr_keyword">null</strong>) { <a class="jxr_linenumber" name="92" href="#92">92</a> List&lt;ASTName&gt; names = thrownsExceptions.findChildrenOfType(ASTName.<strong class="jxr_keyword">class</strong>); <a class="jxr_linenumber" name="93" href="#93">93</a> <strong class="jxr_keyword">for</strong> (ASTName name : names) { <a class="jxr_linenumber" name="94" href="#94">94</a> <strong class="jxr_keyword">for</strong> (String exceptedException : exceptedExceptions) { <a class="jxr_linenumber" name="95" href="#95">95</a> <strong class="jxr_keyword">if</strong> (exceptedException.equals(name.getImage())) { <a class="jxr_linenumber" name="96" href="#96">96</a> result = <strong class="jxr_keyword">true</strong>; <a class="jxr_linenumber" name="97" href="#97">97</a> } <a class="jxr_linenumber" name="98" href="#98">98</a> } <a class="jxr_linenumber" name="99" href="#99">99</a> } <a class="jxr_linenumber" name="100" href="#100">100</a> } <a class="jxr_linenumber" name="101" href="#101">101</a> <strong class="jxr_keyword">return</strong> result; <a class="jxr_linenumber" name="102" href="#102">102</a> } <a class="jxr_linenumber" name="103" href="#103">103</a> <a class="jxr_linenumber" name="104" href="#104">104</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">boolean</strong> hasArguments(<a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTMethodDeclaration.html">ASTMethodDeclaration</a> node) { <a class="jxr_linenumber" name="105" href="#105">105</a> <strong class="jxr_keyword">return</strong> node.hasDescendantMatchingXPath(<span class="jxr_string">"./MethodDeclarator/FormalParameters/*"</span>); <a class="jxr_linenumber" name="106" href="#106">106</a> } <a class="jxr_linenumber" name="107" href="#107">107</a> <a class="jxr_linenumber" name="108" href="#108">108</a> @Override <a class="jxr_linenumber" name="109" href="#109">109</a> <strong class="jxr_keyword">public</strong> Object visit(<a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTMethodDeclaration.html">ASTMethodDeclaration</a> node, Object data) { <a class="jxr_linenumber" name="110" href="#110">110</a> <em class="jxr_comment">// Can skip abstract methods and methods whose only purpose is to</em> <a class="jxr_linenumber" name="111" href="#111">111</a> <em class="jxr_comment">// guarantee that the inherited method is not changed by finalizing</em> <a class="jxr_linenumber" name="112" href="#112">112</a> <em class="jxr_comment">// them.</em> <a class="jxr_linenumber" name="113" href="#113">113</a> <strong class="jxr_keyword">if</strong> (node.isAbstract() || node.isFinal() || node.isNative() || node.isSynchronized()) { <a class="jxr_linenumber" name="114" href="#114">114</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="115" href="#115">115</a> } <a class="jxr_linenumber" name="116" href="#116">116</a> <em class="jxr_comment">// We can also skip the 'clone' method as they are generally</em> <a class="jxr_linenumber" name="117" href="#117">117</a> <em class="jxr_comment">// 'useless' but as it is considered a 'good practice' to</em> <a class="jxr_linenumber" name="118" href="#118">118</a> <em class="jxr_comment">// implement them anyway ( see bug 1522517)</em> <a class="jxr_linenumber" name="119" href="#119">119</a> <strong class="jxr_keyword">if</strong> (CLONE.equals(node.getMethodName()) &amp;&amp; node.isPublic() &amp;&amp; !<strong class="jxr_keyword">this</strong>.hasArguments(node) <a class="jxr_linenumber" name="120" href="#120">120</a> &amp;&amp; <strong class="jxr_keyword">this</strong>.isMethodType(node, OBJECT) &amp;&amp; <strong class="jxr_keyword">this</strong>.isMethodThrowingType(node, exceptions)) { <a class="jxr_linenumber" name="121" href="#121">121</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="122" href="#122">122</a> } <a class="jxr_linenumber" name="123" href="#123">123</a> <a class="jxr_linenumber" name="124" href="#124">124</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTBlock.html">ASTBlock</a> block = node.getBlock(); <a class="jxr_linenumber" name="125" href="#125">125</a> <strong class="jxr_keyword">if</strong> (block == <strong class="jxr_keyword">null</strong>) { <a class="jxr_linenumber" name="126" href="#126">126</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="127" href="#127">127</a> } <a class="jxr_linenumber" name="128" href="#128">128</a> <em class="jxr_comment">//Only process functions with one BlockStatement</em> <a class="jxr_linenumber" name="129" href="#129">129</a> <strong class="jxr_keyword">if</strong> (block.jjtGetNumChildren() != 1 || block.findDescendantsOfType(ASTStatement.<strong class="jxr_keyword">class</strong>).size() != 1) { <a class="jxr_linenumber" name="130" href="#130">130</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="131" href="#131">131</a> } <a class="jxr_linenumber" name="132" href="#132">132</a> <a class="jxr_linenumber" name="133" href="#133">133</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTStatement.html">ASTStatement</a> statement = (ASTStatement) block.jjtGetChild(0).jjtGetChild(0); <a class="jxr_linenumber" name="134" href="#134">134</a> <strong class="jxr_keyword">if</strong> (statement.jjtGetChild(0).jjtGetNumChildren() == 0) { <a class="jxr_linenumber" name="135" href="#135">135</a> <strong class="jxr_keyword">return</strong> data; <em class="jxr_comment">// skips empty return statements</em> <a class="jxr_linenumber" name="136" href="#136">136</a> } <a class="jxr_linenumber" name="137" href="#137">137</a> <a href="../../../../../../../net/sourceforge/pmd/lang/ast/Node.html">Node</a> statementGrandChild = statement.jjtGetChild(0).jjtGetChild(0); <a class="jxr_linenumber" name="138" href="#138">138</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTPrimaryExpression.html">ASTPrimaryExpression</a> primaryExpression; <a class="jxr_linenumber" name="139" href="#139">139</a> <a class="jxr_linenumber" name="140" href="#140">140</a> <strong class="jxr_keyword">if</strong> (statementGrandChild instanceof ASTPrimaryExpression) { <a class="jxr_linenumber" name="141" href="#141">141</a> primaryExpression = (ASTPrimaryExpression) statementGrandChild; <a class="jxr_linenumber" name="142" href="#142">142</a> } <strong class="jxr_keyword">else</strong> { <a class="jxr_linenumber" name="143" href="#143">143</a> List&lt;ASTPrimaryExpression&gt; primaryExpressions = findFirstDegreeChildrenOfType(statementGrandChild, <a class="jxr_linenumber" name="144" href="#144">144</a> ASTPrimaryExpression.<strong class="jxr_keyword">class</strong>); <a class="jxr_linenumber" name="145" href="#145">145</a> <strong class="jxr_keyword">if</strong> (primaryExpressions.size() != 1) { <a class="jxr_linenumber" name="146" href="#146">146</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="147" href="#147">147</a> } <a class="jxr_linenumber" name="148" href="#148">148</a> primaryExpression = primaryExpressions.get(0); <a class="jxr_linenumber" name="149" href="#149">149</a> } <a class="jxr_linenumber" name="150" href="#150">150</a> <a class="jxr_linenumber" name="151" href="#151">151</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTPrimaryPrefix.html">ASTPrimaryPrefix</a> primaryPrefix = findFirstDegreeChildrenOfType(primaryExpression, ASTPrimaryPrefix.<strong class="jxr_keyword">class</strong>) <a class="jxr_linenumber" name="152" href="#152">152</a> .get(0); <a class="jxr_linenumber" name="153" href="#153">153</a> <strong class="jxr_keyword">if</strong> (!primaryPrefix.usesSuperModifier()) { <a class="jxr_linenumber" name="154" href="#154">154</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="155" href="#155">155</a> } <a class="jxr_linenumber" name="156" href="#156">156</a> <a class="jxr_linenumber" name="157" href="#157">157</a> List&lt;ASTPrimarySuffix&gt; primarySuffixList = findFirstDegreeChildrenOfType(primaryExpression, <a class="jxr_linenumber" name="158" href="#158">158</a> ASTPrimarySuffix.<strong class="jxr_keyword">class</strong>); <a class="jxr_linenumber" name="159" href="#159">159</a> <strong class="jxr_keyword">if</strong> (primarySuffixList.size() != 2) { <a class="jxr_linenumber" name="160" href="#160">160</a> <em class="jxr_comment">// extra method call on result of super method</em> <a class="jxr_linenumber" name="161" href="#161">161</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="162" href="#162">162</a> } <a class="jxr_linenumber" name="163" href="#163">163</a> <a class="jxr_linenumber" name="164" href="#164">164</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTMethodDeclarator.html">ASTMethodDeclarator</a> methodDeclarator = findFirstDegreeChildrenOfType(node, ASTMethodDeclarator.<strong class="jxr_keyword">class</strong>).get(0); <a class="jxr_linenumber" name="165" href="#165">165</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTPrimarySuffix.html">ASTPrimarySuffix</a> primarySuffix = primarySuffixList.get(0); <a class="jxr_linenumber" name="166" href="#166">166</a> <strong class="jxr_keyword">if</strong> (!primarySuffix.hasImageEqualTo(methodDeclarator.getImage())) { <a class="jxr_linenumber" name="167" href="#167">167</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="168" href="#168">168</a> } <a class="jxr_linenumber" name="169" href="#169">169</a> <em class="jxr_comment">//Process arguments</em> <a class="jxr_linenumber" name="170" href="#170">170</a> primarySuffix = primarySuffixList.get(1); <a class="jxr_linenumber" name="171" href="#171">171</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTArguments.html">ASTArguments</a> arguments = (ASTArguments) primarySuffix.jjtGetChild(0); <a class="jxr_linenumber" name="172" href="#172">172</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTFormalParameters.html">ASTFormalParameters</a> formalParameters = (ASTFormalParameters) methodDeclarator.jjtGetChild(0); <a class="jxr_linenumber" name="173" href="#173">173</a> <strong class="jxr_keyword">if</strong> (formalParameters.jjtGetNumChildren() != arguments.jjtGetNumChildren()) { <a class="jxr_linenumber" name="174" href="#174">174</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="175" href="#175">175</a> } <a class="jxr_linenumber" name="176" href="#176">176</a> <a class="jxr_linenumber" name="177" href="#177">177</a> <strong class="jxr_keyword">if</strong> (!ignoreAnnotations) { <a class="jxr_linenumber" name="178" href="#178">178</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTClassOrInterfaceBodyDeclaration.html">ASTClassOrInterfaceBodyDeclaration</a> parent = (ASTClassOrInterfaceBodyDeclaration) node.jjtGetParent(); <a class="jxr_linenumber" name="179" href="#179">179</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = 0; i &lt; parent.jjtGetNumChildren(); i++) { <a class="jxr_linenumber" name="180" href="#180">180</a> <a href="../../../../../../../net/sourceforge/pmd/lang/ast/Node.html">Node</a> n = parent.jjtGetChild(i); <a class="jxr_linenumber" name="181" href="#181">181</a> <strong class="jxr_keyword">if</strong> (n instanceof ASTAnnotation) { <a class="jxr_linenumber" name="182" href="#182">182</a> <strong class="jxr_keyword">if</strong> (n.jjtGetChild(0) instanceof ASTMarkerAnnotation) { <a class="jxr_linenumber" name="183" href="#183">183</a> <em class="jxr_comment">// @Override is ignored</em> <a class="jxr_linenumber" name="184" href="#184">184</a> <strong class="jxr_keyword">if</strong> (<span class="jxr_string">"Override"</span>.equals(((ASTName) n.jjtGetChild(0).jjtGetChild(0)).getImage())) { <a class="jxr_linenumber" name="185" href="#185">185</a> <strong class="jxr_keyword">continue</strong>; <a class="jxr_linenumber" name="186" href="#186">186</a> } <a class="jxr_linenumber" name="187" href="#187">187</a> } <a class="jxr_linenumber" name="188" href="#188">188</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="189" href="#189">189</a> } <a class="jxr_linenumber" name="190" href="#190">190</a> } <a class="jxr_linenumber" name="191" href="#191">191</a> } <a class="jxr_linenumber" name="192" href="#192">192</a> <a class="jxr_linenumber" name="193" href="#193">193</a> <strong class="jxr_keyword">if</strong> (arguments.jjtGetNumChildren() == 0) { <a class="jxr_linenumber" name="194" href="#194">194</a> addViolation(data, node, getMessage()); <a class="jxr_linenumber" name="195" href="#195">195</a> } <strong class="jxr_keyword">else</strong> { <a class="jxr_linenumber" name="196" href="#196">196</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTArgumentList.html">ASTArgumentList</a> argumentList = (ASTArgumentList) arguments.jjtGetChild(0); <a class="jxr_linenumber" name="197" href="#197">197</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = 0; i &lt; argumentList.jjtGetNumChildren(); i++) { <a class="jxr_linenumber" name="198" href="#198">198</a> <a href="../../../../../../../net/sourceforge/pmd/lang/ast/Node.html">Node</a> expressionChild = argumentList.jjtGetChild(i).jjtGetChild(0); <a class="jxr_linenumber" name="199" href="#199">199</a> <strong class="jxr_keyword">if</strong> (!(expressionChild instanceof ASTPrimaryExpression) || expressionChild.jjtGetNumChildren() != 1) { <a class="jxr_linenumber" name="200" href="#200">200</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <em class="jxr_comment">//The arguments are not simply passed through</em> <a class="jxr_linenumber" name="201" href="#201">201</a> } <a class="jxr_linenumber" name="202" href="#202">202</a> <a class="jxr_linenumber" name="203" href="#203">203</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTPrimaryExpression.html">ASTPrimaryExpression</a> argumentPrimaryExpression = (ASTPrimaryExpression) expressionChild; <a class="jxr_linenumber" name="204" href="#204">204</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTPrimaryPrefix.html">ASTPrimaryPrefix</a> argumentPrimaryPrefix = (ASTPrimaryPrefix) argumentPrimaryExpression.jjtGetChild(0); <a class="jxr_linenumber" name="205" href="#205">205</a> <strong class="jxr_keyword">if</strong> (argumentPrimaryPrefix.jjtGetNumChildren() == 0) { <a class="jxr_linenumber" name="206" href="#206">206</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <em class="jxr_comment">//The arguments are not simply passed through (using "this" for instance)</em> <a class="jxr_linenumber" name="207" href="#207">207</a> } <a class="jxr_linenumber" name="208" href="#208">208</a> <a href="../../../../../../../net/sourceforge/pmd/lang/ast/Node.html">Node</a> argumentPrimaryPrefixChild = argumentPrimaryPrefix.jjtGetChild(0); <a class="jxr_linenumber" name="209" href="#209">209</a> <strong class="jxr_keyword">if</strong> (!(argumentPrimaryPrefixChild instanceof ASTName)) { <a class="jxr_linenumber" name="210" href="#210">210</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <em class="jxr_comment">//The arguments are not simply passed through</em> <a class="jxr_linenumber" name="211" href="#211">211</a> } <a class="jxr_linenumber" name="212" href="#212">212</a> <a class="jxr_linenumber" name="213" href="#213">213</a> <strong class="jxr_keyword">if</strong> (formalParameters.jjtGetNumChildren() &lt; i + 1) { <a class="jxr_linenumber" name="214" href="#214">214</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <em class="jxr_comment">// different number of args</em> <a class="jxr_linenumber" name="215" href="#215">215</a> } <a class="jxr_linenumber" name="216" href="#216">216</a> <a class="jxr_linenumber" name="217" href="#217">217</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTName.html">ASTName</a> argumentName = (ASTName) argumentPrimaryPrefixChild; <a class="jxr_linenumber" name="218" href="#218">218</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTFormalParameter.html">ASTFormalParameter</a> formalParameter = (ASTFormalParameter) formalParameters.jjtGetChild(i); <a class="jxr_linenumber" name="219" href="#219">219</a> <a href="../../../../../../../net/sourceforge/pmd/lang/java/ast/ASTVariableDeclaratorId.html">ASTVariableDeclaratorId</a> variableId = findFirstDegreeChildrenOfType(formalParameter, <a class="jxr_linenumber" name="220" href="#220">220</a> ASTVariableDeclaratorId.<strong class="jxr_keyword">class</strong>).get(0); <a class="jxr_linenumber" name="221" href="#221">221</a> <strong class="jxr_keyword">if</strong> (!argumentName.hasImageEqualTo(variableId.getImage())) { <a class="jxr_linenumber" name="222" href="#222">222</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <em class="jxr_comment">//The arguments are not simply passed through</em> <a class="jxr_linenumber" name="223" href="#223">223</a> } <a class="jxr_linenumber" name="224" href="#224">224</a> <a class="jxr_linenumber" name="225" href="#225">225</a> } <a class="jxr_linenumber" name="226" href="#226">226</a> addViolation(data, node, getMessage()); <em class="jxr_comment">//All arguments are passed through directly</em> <a class="jxr_linenumber" name="227" href="#227">227</a> } <a class="jxr_linenumber" name="228" href="#228">228</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">super</strong>.visit(node, data); <a class="jxr_linenumber" name="229" href="#229">229</a> } <a class="jxr_linenumber" name="230" href="#230">230</a> <a class="jxr_linenumber" name="231" href="#231">231</a> <strong class="jxr_keyword">public</strong> &lt;T&gt; List&lt;T&gt; findFirstDegreeChildrenOfType(<a href="../../../../../../../net/sourceforge/pmd/lang/ast/Node.html">Node</a> n, Class&lt;T&gt; targetType) { <a class="jxr_linenumber" name="232" href="#232">232</a> List&lt;T&gt; l = <strong class="jxr_keyword">new</strong> ArrayList&lt;T&gt;(); <a class="jxr_linenumber" name="233" href="#233">233</a> lclFindChildrenOfType(n, targetType, l); <a class="jxr_linenumber" name="234" href="#234">234</a> <strong class="jxr_keyword">return</strong> l; <a class="jxr_linenumber" name="235" href="#235">235</a> } <a class="jxr_linenumber" name="236" href="#236">236</a> <a class="jxr_linenumber" name="237" href="#237">237</a> <strong class="jxr_keyword">private</strong> &lt;T&gt; <strong class="jxr_keyword">void</strong> lclFindChildrenOfType(<a href="../../../../../../../net/sourceforge/pmd/lang/ast/Node.html">Node</a> node, Class&lt;T&gt; targetType, List&lt;T&gt; results) { <a class="jxr_linenumber" name="238" href="#238">238</a> <strong class="jxr_keyword">if</strong> (node.getClass().equals(targetType)) { <a class="jxr_linenumber" name="239" href="#239">239</a> results.add((T) node); <a class="jxr_linenumber" name="240" href="#240">240</a> } <a class="jxr_linenumber" name="241" href="#241">241</a> <a class="jxr_linenumber" name="242" href="#242">242</a> <strong class="jxr_keyword">if</strong> (node instanceof ASTClassOrInterfaceDeclaration &amp;&amp; ((ASTClassOrInterfaceDeclaration) node).isNested()) { <a class="jxr_linenumber" name="243" href="#243">243</a> <strong class="jxr_keyword">return</strong>; <a class="jxr_linenumber" name="244" href="#244">244</a> } <a class="jxr_linenumber" name="245" href="#245">245</a> <a class="jxr_linenumber" name="246" href="#246">246</a> <strong class="jxr_keyword">if</strong> (node instanceof ASTClassOrInterfaceBodyDeclaration <a class="jxr_linenumber" name="247" href="#247">247</a> &amp;&amp; ((ASTClassOrInterfaceBodyDeclaration) node).isAnonymousInnerClass()) { <a class="jxr_linenumber" name="248" href="#248">248</a> <strong class="jxr_keyword">return</strong>; <a class="jxr_linenumber" name="249" href="#249">249</a> } <a class="jxr_linenumber" name="250" href="#250">250</a> <a class="jxr_linenumber" name="251" href="#251">251</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = 0; i &lt; node.jjtGetNumChildren(); i++) { <a class="jxr_linenumber" name="252" href="#252">252</a> <a href="../../../../../../../net/sourceforge/pmd/lang/ast/Node.html">Node</a> child = node.jjtGetChild(i); <a class="jxr_linenumber" name="253" href="#253">253</a> <strong class="jxr_keyword">if</strong> (child.getClass().equals(targetType)) { <a class="jxr_linenumber" name="254" href="#254">254</a> results.add((T) child); <a class="jxr_linenumber" name="255" href="#255">255</a> } <a class="jxr_linenumber" name="256" href="#256">256</a> } <a class="jxr_linenumber" name="257" href="#257">257</a> } <a class="jxr_linenumber" name="258" href="#258">258</a> } </pre> <hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body> </html>
136.586081
490
0.666568
7b10d2ef4834d3dfb82caaae629961993b2d2920
366
rb
Ruby
lib/roxanne/consumers.rb
servebox/roxanne
6bf046d776d107261324bac9b514219ac0eac711
[ "MIT" ]
1
2015-06-15T13:50:55.000Z
2015-06-15T13:50:55.000Z
lib/roxanne/consumers.rb
servebox/roxanne
6bf046d776d107261324bac9b514219ac0eac711
[ "MIT" ]
null
null
null
lib/roxanne/consumers.rb
servebox/roxanne
6bf046d776d107261324bac9b514219ac0eac711
[ "MIT" ]
null
null
null
module Roxanne module Consumers module Priority def prioritize(current_status, former_status) [:red, :orange].each do |status| return status if status == former_status end current_status end end end end require 'roxanne/jenkins/consumer' require 'roxanne/test/consumer' require 'roxanne/travis/consumer'
18.3
51
0.677596
b56b66d1a2c59f68a775b3fc1ff2be71e31a597b
1,320
sql
SQL
sl-play/conf/evolutions/default/1.sql
serious-lunch/serious-lunch-services
0eff3544ae19de7450a9b01b64f8888bc7dd7a40
[ "MIT" ]
null
null
null
sl-play/conf/evolutions/default/1.sql
serious-lunch/serious-lunch-services
0eff3544ae19de7450a9b01b64f8888bc7dd7a40
[ "MIT" ]
null
null
null
sl-play/conf/evolutions/default/1.sql
serious-lunch/serious-lunch-services
0eff3544ae19de7450a9b01b64f8888bc7dd7a40
[ "MIT" ]
null
null
null
-- insert development data -- !Ups INSERT INTO `accounts` (`account_id`, `account_name`, `email_address`, `password_digest`, `created_at`, `updated_at`) VALUES (1, 'foo', 'foo@example.com', '$2a$10$W/ddZ.N7db0O8xdljE70F.hhWcxainSDTGbDCV/bJuxv.ku.Mz6nq', '2019-05-26 03:40:57', '2019-05-26 03:40:57'), (2, 'bar', 'bar@example.com', '$2a$10$gQKve8lQqggP6yxqCOV8MuTy22VO01egg6lyOGFTpXTsOz2Q1dfYq', '2019-05-26 03:40:57', '2019-05-26 03:40:57'); INSERT INTO `account_activations` (`account_id`, `activation_digest`, `activated`, `created_at`, `updated_at`) VALUES (1, '', TRUE, '2019-05-26 03:40:57', '2019-05-26 03:40:57'), (2, '', TRUE, '2019-05-26 03:40:57', '2019-05-26 03:40:57'); INSERT INTO `account_relationships` (`follower_account_id`, `followed_account_id`, `created_at`, `updated_at`) VALUES (1, 2, '2019-05-26 03:40:57', '2019-05-26 03:40:57'); INSERT INTO `lunches` (`lunch_id`, `account_id`, `lunch_date`, `comment`, `created_at`, `updated_at`) VALUES (1, 1, '2018-03-09', 'excellent', '2019-05-26 03:40:57', '2019-05-26 03:40:57'), (2, 2, '2018-03-09', 'bad', '2019-05-26 03:40:57', '2019-05-26 03:40:57'), (3, 1, '2018-03-08', 'good', '2019-05-26 03:40:57', '2019-05-26 03:40:57'); -- !Downs DROP TABLE lunches; DROP TABLE account_relationships; DROP TABLE account_activations; DROP TABLE accounts;
47.142857
140
0.683333
a580a9753bf9f23df4503d17bec1b3594d93f52d
1,099
kt
Kotlin
app/src/main/java/br/com/suellencolangelo/todolist/view/categoryList/CategoryListFragment.kt
SuellenAc/TodoList
a15f53eceeee197bb7cc3da245b927604e6ccce5
[ "Apache-2.0" ]
1
2021-06-08T07:08:37.000Z
2021-06-08T07:08:37.000Z
app/src/main/java/br/com/suellencolangelo/todolist/view/categoryList/CategoryListFragment.kt
SuellenAc/TodoList
a15f53eceeee197bb7cc3da245b927604e6ccce5
[ "Apache-2.0" ]
null
null
null
app/src/main/java/br/com/suellencolangelo/todolist/view/categoryList/CategoryListFragment.kt
SuellenAc/TodoList
a15f53eceeee197bb7cc3da245b927604e6ccce5
[ "Apache-2.0" ]
null
null
null
package br.com.suellencolangelo.todolist.view.categoryList import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import br.com.suellencolangelo.todolist.databinding.CategoryListFragmentBinding import br.com.suellencolangelo.todolist.navigation.general.CategoryListNavigator import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class CategoryListFragment : Fragment() { private lateinit var binding: CategoryListFragmentBinding @Inject lateinit var categoryListNavigator: CategoryListNavigator override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return CategoryListFragmentBinding.inflate(inflater).also { this.binding = it it.text.setOnClickListener { categoryListNavigator.navigateToCategoryDetail( this, "dummyId" ) } }.root } }
30.527778
80
0.722475
cb6bf0ac03e5283424df3784c1603e75f04951d1
4,722
go
Go
netapp/net-ipspace_test.go
britcey/go-netapp
3c5b98f52cf4d21d5209cd3b78a3f151f02f0c8e
[ "MIT" ]
16
2017-10-04T01:39:57.000Z
2021-11-14T20:04:28.000Z
netapp/net-ipspace_test.go
britcey/go-netapp
3c5b98f52cf4d21d5209cd3b78a3f151f02f0c8e
[ "MIT" ]
38
2017-10-30T19:48:18.000Z
2021-10-04T23:40:25.000Z
netapp/net-ipspace_test.go
britcey/go-netapp
3c5b98f52cf4d21d5209cd3b78a3f151f02f0c8e
[ "MIT" ]
26
2017-11-01T00:22:45.000Z
2022-02-05T14:43:59.000Z
package netapp_test import ( "reflect" "testing" "github.com/pepabo/go-netapp/netapp" ) func TestNet_IPSpaceCreateSuccess(t *testing.T) { c, teardown := createTestClientWithFixtures(t) defer teardown() call, _, err := c.Net.CreateIPSpace("test-ip-space", true) checkResponseSuccess(&call.Results.SingleResultBase, err, t) info := call.Results.NetIPSpaceCreateInfo var nilSlice *[]string tests := []struct { name string got interface{} want interface{} }{ {"Broadcast Domains", info.BroadcastDomains, nilSlice}, {"ID", info.ID, 39}, {"IP Space", info.IPSpace, "test-ip-space"}, {"Ports", info.Ports, nilSlice}, {"UUID", info.UUID, "af9fa457-c02d-11e8-bf6a-00a0983afb38"}, {"VServers", info.VServers, &[]string{"test-ip-space"}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if !reflect.DeepEqual(tt.got, tt.want) { t.Errorf("Net.CreateIPSpace() got = %+v, want %+v", tt.got, tt.want) } }) } } func TestNet_IPSpaceCreateFailure(t *testing.T) { c, teardown := createTestClientWithFixtures(t) defer teardown() call, _, err := c.Net.CreateIPSpace("test-ip-space", false) results := &call.Results.SingleResultBase checkResponseFailure(results, err, t) testFailureResult(13001, `Invalid IPspace name. The name "test-ip-space" is already in use by a cluster node, Vserver, or is the name of the local cluster.`, results, t) } func TestNet_IPSpaceGetSuccess(t *testing.T) { c, teardown := createTestClientWithFixtures(t) defer teardown() call, _, err := c.Net.GetIPSpace("test-net-ipspace") checkResponseSuccess(&call.Results.SingleResultBase, err, t) var createInfo *netapp.NetIPSpaceInfo info := call.Results.NetIPSpaceInfo tests := []struct { name string got interface{} want interface{} }{ {"Broadcast Domains", info.BroadcastDomains, &[]string{"test-net-ipspace"}}, {"Ports", info.Ports, &[]string{"lab-cluster01-02:a0a-3555", "lab-cluster01-01:a0a-3555"}}, {"VServers", info.VServers, &[]string{"Test-Vserver", "test-vserver"}}, {"Create Info is empty", call.Results.NetIPSpaceCreateInfo, createInfo}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if !reflect.DeepEqual(tt.got, tt.want) { t.Errorf("Net.GetIPSpace() got = %+v, want %+v", tt.got, tt.want) } }) } } func TestNet_IPSpaceListSuccess(t *testing.T) { c, teardown := createTestClientWithFixtures(t) defer teardown() query := &netapp.NetIPSpaceInfo{ IPSpace: "c666", } call, _, err := c.Net.ListIPSpaces(query) checkResponseSuccess(&call.Results.ResultBase, err, t) info := call.Results.Info[0] tests := []struct { name string got interface{} want interface{} }{ {"UUID", info.UUID, "c61db834-9a57-11e8-bf6a-00a0983afb38"}, {"ID", info.ID, 25}, {"Broadcast Domains", info.BroadcastDomains, &[]string{"test-net-ipspace"}}, {"Ports", info.Ports, &[]string{"lab-cluster01-02:a0a-3666", "lab-cluster01-01:a0a-3666"}}, {"VServers", info.VServers, &[]string{"C666", "c666"}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if !reflect.DeepEqual(tt.got, tt.want) { t.Errorf("Net.ListIPSpaces() got = %+v, want %+v", tt.got, tt.want) } }) } } func TestNet_IPSpaceGetFailure(t *testing.T) { c, teardown := createTestClientWithFixtures(t) defer teardown() call, _, err := c.Net.GetIPSpace("test-ip-space") results := &call.Results.SingleResultBase checkResponseFailure(results, err, t) testFailureResult(15661, `entry doesn"t exist`, results, t) } func TestNet_IPSpaceRenameSuccess(t *testing.T) { c, teardown := createTestClientWithFixtures(t) defer teardown() call, _, err := c.Net.RenameIPSpace("test-net-ipspace", "test-net-ipspace-new") checkResponseSuccess(&call.Results.SingleResultBase, err, t) } func TestNet_IPSpaceRenameFailure(t *testing.T) { c, teardown := createTestClientWithFixtures(t) defer teardown() call, _, err := c.Net.RenameIPSpace("test-net-ipspace", "test-net-ipspace-new") checkResponseFailure(&call.Results.SingleResultBase, err, t) testFailureResult(13001, "IPspace test-net-ipspace does not exist.", &call.Results.SingleResultBase, t) } func TestNet_IPSpaceDeleteSuccess(t *testing.T) { c, teardown := createTestClientWithFixtures(t) defer teardown() call, _, err := c.Net.DeleteIPSpace("test-net-ipspace-new") checkResponseSuccess(&call.Results.SingleResultBase, err, t) } func TestNet_IPSpaceDeleteFailure(t *testing.T) { c, teardown := createTestClientWithFixtures(t) defer teardown() call, _, err := c.Net.DeleteIPSpace("test-net-ipspace-new") checkResponseFailure(&call.Results.SingleResultBase, err, t) testFailureResult(15661, `entry doesn"t exist`, &call.Results.SingleResultBase, t) }
28.969325
170
0.703092
9bd1054fd2c63bfeb222b33077a8fb57d25c5357
10,593
js
JavaScript
src/gchart.js
metaphacts/YASGUI.YASR
962a611205ae6d3e6e3a9651fe639df832092445
[ "MIT" ]
null
null
null
src/gchart.js
metaphacts/YASGUI.YASR
962a611205ae6d3e6e3a9651fe639df832092445
[ "MIT" ]
null
null
null
src/gchart.js
metaphacts/YASGUI.YASR
962a611205ae6d3e6e3a9651fe639df832092445
[ "MIT" ]
1
2020-04-07T15:01:14.000Z
2020-04-07T15:01:14.000Z
"use strict"; /** * todo: chart height as option * */ var $ = require("jquery"), utils = require("./utils.js"), yUtils = require("yasgui-utils"); var root = module.exports = function(yasr) { var options = $.extend(true, {}, root.defaults); var id = yasr.container.closest("[id]").attr("id"); var chartWrapper = null; var editor = null; var initEditor = function(callback) { var google = require("google"); editor = new google.visualization.ChartEditor(); google.visualization.events.addListener(editor, "ok", function() { var tmp; chartWrapper = editor.getChartWrapper(); tmp = chartWrapper.getDataTable(); chartWrapper.setDataTable(null); //ugly: need to parse json string to json obj again, as google chart does not provide access to object directly options.chartConfig = JSON.parse(chartWrapper.toJSON()); //remove container ID though, for portability if (options.chartConfig.containerId) delete options.chartConfig["containerId"]; yasr.store(); chartWrapper.setDataTable(tmp); var wrapperId = id + "_gchartWrapper"; var $wrapper = $("#" + wrapperId); chartWrapper.setOption("width", $wrapper.width()); chartWrapper.setOption("height", $wrapper.height()); chartWrapper.draw(); yasr.updateHeader(); }); if (callback) callback(); }; return { name: "Google Chart", hideFromSelection: false, priority: 7, options: options, getPersistentSettings: function() { return { chartConfig: options.chartConfig, motionChartState: options.motionChartState }; }, setPersistentSettings: function(persSettings) { if (persSettings["chartConfig"]) options.chartConfig = persSettings["chartConfig"]; if (persSettings["motionChartState"]) options.motionChartState = persSettings["motionChartState"]; }, canHandleResults: function(yasr) { var results, variables; return (results = yasr.results) != null && (variables = results.getVariables()) && variables.length > 0; }, getDownloadInfo: function() { if (!yasr.results) return null; var svgEl = yasr.resultsContainer.find("svg"); if (svgEl.length > 0) { return { getContent: function() { if (svgEl[0].outerHTML) { return svgEl[0].outerHTML; } else { //outerHTML not supported. use workaround return $("<div>").append(svgEl.clone()).html(); } }, filename: "queryResults.svg", contentType: "image/svg+xml", buttonTitle: "Download SVG Image" }; } //ok, not a svg. is it a table? var $table = yasr.resultsContainer.find(".google-visualization-table-table"); if ($table.length > 0) { return { getContent: function() { return $table.tableToCsv(); }, filename: "queryResults.csv", contentType: "text/csv", buttonTitle: "Download as CSV" }; } }, getEmbedHtml: function() { if (!yasr.results) return null; var svgEl = yasr.resultsContainer .find("svg") .clone() //create clone, as we'd like to remove height/width attributes .removeAttr("height") .removeAttr("width") .css("height", "") .css("width", ""); if (svgEl.length == 0) return null; var htmlString = svgEl[0].outerHTML; if (!htmlString) { //outerHTML not supported. use workaround htmlString = $("<div>").append(svgEl.clone()).html(); } //wrap in div, so users can more easily tune width/height //don't use jquery, so we can easily influence indentation return '<div style="width: 800px; height: 600px;">\n' + htmlString + "\n</div>"; }, draw: function(_customOpts) { var customOpts = $.extend(true, {}, options, _customOpts); var doDraw = function() { //clear previous results (if any) yasr.resultsContainer.empty(); var wrapperId = id + "_gchartWrapper"; yasr.resultsContainer .append( $("<button>", { class: "openGchartBtn yasr_btn" }) .text("Chart Config") .click(function() { editor.openDialog(chartWrapper); }) ) .append( $("<div>", { id: wrapperId, class: "gchartWrapper" }) ); var dataTable = new google.visualization.DataTable(); //clone, because we'll be manipulating the literals types var jsonResults = $.extend(true, {}, yasr.results.getAsJson()); jsonResults.head.vars.forEach(function(variable) { var type = "string"; try { type = utils.getGoogleTypeForBindings(jsonResults.results.bindings, variable); } catch (e) { if (e instanceof require("./exceptions.js").GoogleTypeException) { yasr.warn(e.toHtml()); } else { throw e; } } dataTable.addColumn(type, variable); }); var usedPrefixes = null; if (yasr.options.getUsedPrefixes) { usedPrefixes = typeof yasr.options.getUsedPrefixes == "function" ? yasr.options.getUsedPrefixes(yasr) : yasr.options.getUsedPrefixes; } jsonResults.results.bindings.forEach(function(binding) { var row = []; jsonResults.head.vars.forEach(function(variable, columnId) { row.push(utils.castGoogleType(binding[variable], usedPrefixes, dataTable.getColumnType(columnId))); }); dataTable.addRow(row); }); if (customOpts.chartConfig && customOpts.chartConfig.chartType) { customOpts.chartConfig.containerId = wrapperId; chartWrapper = new google.visualization.ChartWrapper(customOpts.chartConfig); if (chartWrapper.getChartType() === "MotionChart" && customOpts.motionChartState) { chartWrapper.setOption("state", customOpts.motionChartState); google.visualization.events.addListener(chartWrapper, "ready", function() { var motionChart; motionChart = chartWrapper.getChart(); google.visualization.events.addListener(motionChart, "statechange", function() { customOpts.motionChartState = motionChart.getState(); yasr.store(); }); }); } chartWrapper.setDataTable(dataTable); } else { chartWrapper = new google.visualization.ChartWrapper({ chartType: "Table", dataTable: dataTable, containerId: wrapperId }); } var $wrapper = $("#" + wrapperId); chartWrapper.setOption("width", $wrapper.width()); chartWrapper.setOption("height", $wrapper.height()); chartWrapper.draw(); google.visualization.events.addListener(chartWrapper, "ready", yasr.updateHeader); }; if (!require("google") || !require("google").visualization || !editor) { require("./gChartLoader.js") .on("done", function() { initEditor(); doDraw(); }) .on("error", function() { //TODO: disable or something? }) .googleLoad(); } else { //everything (editor as well) is already initialized doDraw(); } } }; }; root.defaults = { height: "100%", width: "100%", persistencyId: "gchart", chartConfig: null, motionChartState: null }; function deepEq$(x, y, type) { var toString = ({}).toString, hasOwnProperty = ({}).hasOwnProperty, has = function(obj, key) { return hasOwnProperty.call(obj, key); }; var first = true; return eq(x, y, []); function eq(a, b, stack) { var className, length, size, result, alength, blength, r, key, ref, sizeB; if (a == null || b == null) { return a === b; } if (a.__placeholder__ || b.__placeholder__) { return true; } if (a === b) { return a !== 0 || 1 / a == 1 / b; } className = toString.call(a); if (toString.call(b) != className) { return false; } switch (className) { case "[object String]": return a == String(b); case "[object Number]": return a != +a ? b != +b : a == 0 ? 1 / a == 1 / b : a == +b; case "[object Date]": case "[object Boolean]": return +a == +b; case "[object RegExp]": return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != "object" || typeof b != "object") { return false; } length = stack.length; while (length--) { if (stack[length] == a) { return true; } } stack.push(a); size = 0; result = true; if (className == "[object Array]") { alength = a.length; blength = b.length; if (first) { switch (type) { case "===": result = alength === blength; break; case "<==": result = alength <= blength; break; case "<<=": result = alength < blength; break; } size = alength; first = false; } else { result = alength === blength; size = alength; } if (result) { while (size--) { if (!(result = size in a == size in b && eq(a[size], b[size], stack))) { break; } } } } else { if ("constructor" in a != "constructor" in b || a.constructor != b.constructor) { return false; } for (key in a) { if (has(a, key)) { size++; if (!(result = has(b, key) && eq(a[key], b[key], stack))) { break; } } } if (result) { sizeB = 0; for (key in b) { if (has(b, key)) { ++sizeB; } } if (first) { if (type === "<<=") { result = size < sizeB; } else if (type === "<==") { result = size <= sizeB; } else { result = size === sizeB; } } else { first = false; result = size === sizeB; } } } stack.pop(); return result; } }
32.003021
117
0.537619
5f1bf3cc12deb3a116fd1ca9f728a940bd2e6d1d
1,432
tsx
TypeScript
src/components/AuthForm/SignInForm/SignInForm.tsx
VadimKh/stay-on-the-way
93f562a05474b10bf48966897c4cf4764c9fcc28
[ "MIT" ]
null
null
null
src/components/AuthForm/SignInForm/SignInForm.tsx
VadimKh/stay-on-the-way
93f562a05474b10bf48966897c4cf4764c9fcc28
[ "MIT" ]
null
null
null
src/components/AuthForm/SignInForm/SignInForm.tsx
VadimKh/stay-on-the-way
93f562a05474b10bf48966897c4cf4764c9fcc28
[ "MIT" ]
null
null
null
import * as React from 'react'; import SignForm from '../SignForm'; import InputGroup from '../../InputGroup'; import CheckboxGroup from '../../CheckboxGroup'; export default function SignInForm(props: ISignInFormProps) { return ( <SignForm title="Sign In" mainColor="info" mainButtonContent={'Sign In'} mainButtonAction={props.mainAction} secondColor="primary" secondButtonContent={ <> <i className="fas fa-user-plus" /> Sign Up </> } secondButtonAction={props.secondAction} googleClickAction={props.googleClickAction} facebookClickAction={props.facebookClickAction} twiterClickAction={props.twiterClickAction} > <InputGroup type="email" iconClass="far fa-envelope" placeholder="Email..." onChange={props.emailChanged} /> <InputGroup type="password" iconClass="fas fa-lock" placeholder="Password..." onChange={props.passwordChanged} /> <CheckboxGroup title="Save me" onChange={props.saveMeChanged} /> </SignForm> ); } export interface ISignInFormProps { mainAction?: VoidFunction; secondAction?: VoidFunction; saveMeChanged?: VoidFunction; googleClickAction?: VoidFunction; twiterClickAction?: VoidFunction; facebookClickAction?: VoidFunction; emailChanged?: VoidFunction; passwordChanged?: VoidFunction; }
26.036364
70
0.662709
689624a92755295257a2cd6ed5803e3a347ac558
998
lua
Lua
src/app/controllers/MessageController.lua
a406761488/111
646f6dd3495c548c51ae72d54b4f5b949c3b5c90
[ "Zlib" ]
null
null
null
src/app/controllers/MessageController.lua
a406761488/111
646f6dd3495c548c51ae72d54b4f5b949c3b5c90
[ "Zlib" ]
null
null
null
src/app/controllers/MessageController.lua
a406761488/111
646f6dd3495c548c51ae72d54b4f5b949c3b5c90
[ "Zlib" ]
null
null
null
local class = require('middleclass') local Controller = require('mvc.Controller') local HasSignals = require('HasSignals') local MessageController = class("MessageController", Controller):include(HasSignals) function MessageController:initialize() Controller.initialize(self) HasSignals.initialize(self) end function MessageController:viewDidLoad() local app = require("app.App"):instance() local user = app.session.user self.view:layout() self.listener = { user:on('getNotify',function(msg) self.view:getNotify(msg) end), } user:getNotify() end function MessageController:clickBack() self.emitter:emit('back') end function MessageController:finalize()-- luacheck: ignore for i = 1,#self.listener do self.listener[i]:dispose() end end function MessageController:clicktab(sender) local data = sender:getComponent("ComExtensionData"):getCustomProperty() self.view:freshtab(data) end return MessageController
24.341463
85
0.725451
0698e2c5537ade652b75252bd4bbe52b4c2ac826
2,114
kt
Kotlin
app/src/main/java/com/moneytree/app/common/NSViewModel.kt
Dishantraiyani/moneytree
093356b039ebef395523a496a45b93a11cc74009
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/moneytree/app/common/NSViewModel.kt
Dishantraiyani/moneytree
093356b039ebef395523a496a45b93a11cc74009
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/moneytree/app/common/NSViewModel.kt
Dishantraiyani/moneytree
093356b039ebef395523a496a45b93a11cc74009
[ "Apache-2.0" ]
null
null
null
package com.moneytree.app.common import android.app.Application import android.content.Intent import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import com.moneytree.app.ui.login.NSLoginActivity /** * The base class for all view models which holds methods and members common to all view models */ open class NSViewModel(mApplication: Application) : AndroidViewModel(mApplication) { var isProgressShowing = MutableLiveData<Boolean>() var isBottomProgressShowing = MutableLiveData<Boolean>() val validationErrorId by lazy { NSSingleLiveEvent<Int>() } val failureErrorMessage: NSSingleLiveEvent<String?> = NSSingleLiveEvent() val apiErrors: NSSingleLiveEvent<List<Any>> = NSSingleLiveEvent() val noNetworkAlert: NSSingleLiveEvent<Boolean> = NSSingleLiveEvent() var isRefreshComplete = MutableLiveData<Boolean>() /** * To handle the API failure error and communicate back to UI * * @param errorMessage The error message to show */ protected fun handleFailure(errorMessage: String?) { isProgressShowing.value = false isBottomProgressShowing.value = false failureErrorMessage.value = errorMessage } /** * To handle api error message * * @param apiErrorList The errorList contains string resource id and string */ protected fun handleError(apiErrorList: List<Any>) { isProgressShowing.value = false isBottomProgressShowing.value = false if (apiErrorList.contains("Session TimeOut!!\n")) { NSApplication.getInstance().getPrefs().clearPrefData() NSApplication.getInstance().startActivity(Intent(NSApplication.getInstance(), NSLoginActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)) } else { apiErrors.value = apiErrorList } } /** * To handle no network */ protected open fun handleNoNetwork() { isProgressShowing.value = false isBottomProgressShowing.value = false noNetworkAlert.value = true } }
37.087719
194
0.715705
366767ef2a5be8d85526e6309416e9b4da4db81f
102
rs
Rust
extern_function_example/src/main.rs
getong/rust_example
19084811a912119f01a84f0091c716fcc3edf643
[ "Apache-2.0" ]
null
null
null
extern_function_example/src/main.rs
getong/rust_example
19084811a912119f01a84f0091c716fcc3edf643
[ "Apache-2.0" ]
null
null
null
extern_function_example/src/main.rs
getong/rust_example
19084811a912119f01a84f0091c716fcc3edf643
[ "Apache-2.0" ]
null
null
null
extern "C" { fn console_log(a: i32); } fn main() { unsafe { console_log(42); } }
10.2
27
0.480392
aeb26fd55f5f3fced4c156c1dc9c896f70f03365
2,459
rs
Rust
leetcode/src/tree/leetcode617.rs
SmiteWindows/leetcode
010d7e714c5a960dbb23a07f4aba85bba3450aad
[ "MIT" ]
1
2021-05-13T16:15:20.000Z
2021-05-13T16:15:20.000Z
leetcode/src/tree/leetcode617.rs
SmiteWindows/leetcode
010d7e714c5a960dbb23a07f4aba85bba3450aad
[ "MIT" ]
null
null
null
leetcode/src/tree/leetcode617.rs
SmiteWindows/leetcode
010d7e714c5a960dbb23a07f4aba85bba3450aad
[ "MIT" ]
null
null
null
// https://leetcode-cn.com/problems/merge-two-binary-trees/ // Runtime: 4 ms // Memory Usage: 2.1 MB use std::{cell::RefCell, rc::Rc}; pub fn merge_trees( t1: Option<Rc<RefCell<TreeNode>>>, t2: Option<Rc<RefCell<TreeNode>>>, ) -> Option<Rc<RefCell<TreeNode>>> { if t1.is_none() { return t2; } if t2.is_none() { return t1; } t1.as_deref()?.borrow_mut().val += t2.as_deref()?.borrow().val; let t1_left = t1.as_deref()?.borrow().left.clone(); let t2_left = t2.as_deref()?.borrow().left.clone(); let t1_right = t1.as_deref()?.borrow().right.clone(); let t2_right = t2.as_deref()?.borrow().right.clone(); t1.as_deref()?.borrow_mut().left = merge_trees(t1_left, t2_left); t1.as_deref()?.borrow_mut().right = merge_trees(t1_right, t2_right); t1 } // Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<Self>>>, pub right: Option<Rc<RefCell<Self>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { Self { val, left: None, right: None, } } } // tree #[test] fn test1_617() { let t1 = Some(Rc::new(RefCell::new(TreeNode { val: 1, left: Some(Rc::new(RefCell::new(TreeNode { val: 3, left: Some(Rc::new(RefCell::new(TreeNode::new(5)))), right: None, }))), right: Some(Rc::new(RefCell::new(TreeNode::new(2)))), }))); let t2 = Some(Rc::new(RefCell::new(TreeNode { val: 2, left: Some(Rc::new(RefCell::new(TreeNode { val: 1, left: None, right: Some(Rc::new(RefCell::new(TreeNode::new(4)))), }))), right: Some(Rc::new(RefCell::new(TreeNode { val: 3, left: None, right: Some(Rc::new(RefCell::new(TreeNode::new(7)))), }))), }))); let res = Some(Rc::new(RefCell::new(TreeNode { val: 3, left: Some(Rc::new(RefCell::new(TreeNode { val: 4, left: Some(Rc::new(RefCell::new(TreeNode::new(5)))), right: Some(Rc::new(RefCell::new(TreeNode::new(4)))), }))), right: Some(Rc::new(RefCell::new(TreeNode { val: 5, left: None, right: Some(Rc::new(RefCell::new(TreeNode::new(7)))), }))), }))); assert_eq!(res, merge_trees(t1, t2)); }
29.626506
72
0.533144
7bf593952c2a4c9d327f5ceacccc8ca2f09a2dbc
596
swift
Swift
MyCredit/View/EmptyListView.swift
Serasmi/swiftui-mycredit
9e7a6a2fe5a6e52ae602cc1ff7cfe00c15bf437a
[ "MIT" ]
null
null
null
MyCredit/View/EmptyListView.swift
Serasmi/swiftui-mycredit
9e7a6a2fe5a6e52ae602cc1ff7cfe00c15bf437a
[ "MIT" ]
null
null
null
MyCredit/View/EmptyListView.swift
Serasmi/swiftui-mycredit
9e7a6a2fe5a6e52ae602cc1ff7cfe00c15bf437a
[ "MIT" ]
null
null
null
// // EmptyListView.swift // MyCredit // // Created by Сергей Смирнов on 16.03.2021. // import SwiftUI struct EmptyListView: View { var body: some View { VStack(spacing: 10) { Spacer() Image(systemName: "icloud.slash") .foregroundColor(Color(.systemGray)) .font(.system(size: 32)) Text("No credits") .foregroundColor(Color(.systemGray)) Spacer() } } } struct EmptyListView_Previews: PreviewProvider { static var previews: some View { EmptyListView() } }
20.551724
52
0.557047
50f47c80d5ca0aa6be328d464202808d380855ac
8,327
go
Go
lib/lure/command/updateDependencies_test.go
coveooss/lure
e02ce066e0894f3454ee0a2c936ee7109842030f
[ "MIT" ]
3
2019-07-25T13:36:49.000Z
2019-10-28T14:24:43.000Z
lib/lure/command/updateDependencies_test.go
coveo/Lure
9ce00e0de7fb81a4e32607b9fc061f1af4f274de
[ "MIT" ]
18
2017-09-22T13:24:21.000Z
2019-06-18T13:56:22.000Z
lib/lure/command/updateDependencies_test.go
coveo/Lure
9ce00e0de7fb81a4e32607b9fc061f1af4f274de
[ "MIT" ]
7
2017-09-14T14:28:59.000Z
2019-02-06T20:02:48.000Z
package command_test import ( "regexp" "testing" "github.com/coveooss/lure/lib/lure/versionManager" "github.com/coveooss/lure/lib/lure/command" "github.com/coveooss/lure/lib/lure/project" managementsystem "github.com/coveooss/lure/lib/lure/repositorymanagementsystem" ) type dummySourceControl struct { } func (d *dummySourceControl) Update(string) (string, error) { return "watev", nil } func (d *dummySourceControl) CommitsBetween(string, string) ([]string, error) { return []string{"watev"}, nil } func (d *dummySourceControl) Branch(string) (string, error) { return "watev", nil } func (d *dummySourceControl) SoftBranch(string) (string, error) { return "watev", nil } func (d *dummySourceControl) Push() (string, error) { return "watev", nil } func (d *dummySourceControl) WorkingPath() string { return "watev" } func (d *dummySourceControl) ActiveBranches() ([]string, error) { return []string{"watev"}, nil } func (d *dummySourceControl) CloseBranch(string) error { return nil } func (d *dummySourceControl) LocalPath() string { return "watev" } func (d *dummySourceControl) SanitizeBranchName(branchName string) string { reg, _ := regexp.Compile("[^a-zA-Z0-9_-]+") safe := reg.ReplaceAllString(branchName, "_") return safe } func (d *dummySourceControl) Commit(string) (string, error) { return "watev", nil } type dummyRepository struct { ExistingPrs []managementsystem.PullRequest OpenPullRequestCalled bool } func (d *dummyRepository) CreatePullRequest(sourceBranch string, destBranch string, owner string, repo string, title string, description string, useDefaultReviewers bool) error { d.OpenPullRequestCalled = true return nil } func (d *dummyRepository) GetPullRequests(string, string, bool) ([]managementsystem.PullRequest, error) { return d.ExistingPrs, nil } func (d *dummyRepository) DeclinePullRequest(string, string, int) error { return nil } func (d *dummyRepository) GetURL() string { return "" } type dummyVersionControl struct { ModuleToReturn []versionManager.ModuleVersion GetOutdatedError error GetOutdatedWasCalled bool } func (d *dummyVersionControl) GetOutdated(path string) ([]versionManager.ModuleVersion, error) { d.GetOutdatedWasCalled = true return d.ModuleToReturn, d.GetOutdatedError } func (d *dummyVersionControl) UpdateDependency(path string, moduleVersion versionManager.ModuleVersion) (bool, error) { return true, nil } type dummyBranch struct { BranchName string } func (d *dummyBranch) GetName() string { return d.BranchName } func TestCheckForUpdatesJobCommandShouldNotOpenPRWhenPRAlreadyExists(t *testing.T) { skipPackageManageConfiguration := make(map[string]bool) skipPackageManageConfiguration["mvn"] = false mvn := &dummyVersionControl{} moduleToReturn := []versionManager.ModuleVersion{ versionManager.ModuleVersion{ ModuleUpdater: mvn, Module: "yolo", Current: "1.2.1", Latest: "1.2.3", Wanted: "1.2.3", Name: "swag", }, } mvn.ModuleToReturn = moduleToReturn existingPrs := []managementsystem.PullRequest{ managementsystem.PullRequest{ ID: 32, Title: "Update maven dependency yolo.swag to version 1.2.3", Source: &dummyBranch{BranchName: "lure-swag-1_2_3-71334c00-b060-4830-86c0-c7077545712d"}, Dest: &dummyBranch{BranchName: "irrelevant"}, State: "OPEN", }, } repository := &dummyRepository{ExistingPrs: existingPrs} useDefaultReviewers := false command.CheckForUpdatesJobCommand(project.Project{SkipPackageManager: skipPackageManageConfiguration, UseDefaultReviewers: &useDefaultReviewers}, &dummySourceControl{}, repository, make(map[string]string), mvn, &dummyVersionControl{}) if repository.OpenPullRequestCalled { t.Log("Should not open a pull request") t.Fail() } } func TestCheckForUpdatesJobCommandShouldNotOpenPRWhenDecliendPRExists(t *testing.T) { skipPackageManageConfiguration := make(map[string]bool) skipPackageManageConfiguration["mvn"] = false mvn := &dummyVersionControl{} moduleToReturn := []versionManager.ModuleVersion{ versionManager.ModuleVersion{ ModuleUpdater: mvn, Module: "yolo", Current: "1.2.1", Latest: "1.2.3", Wanted: "1.2.3", Name: "swag", }, } mvn.ModuleToReturn = moduleToReturn existingPrs := []managementsystem.PullRequest{ managementsystem.PullRequest{ ID: 32, Title: "Update maven dependency yolo.swag to version 1.2.3", Source: &dummyBranch{BranchName: "lure-swag-1_2_3-71334c00-b060-4830-86c0-c7077545712d"}, Dest: &dummyBranch{BranchName: "irrelevant"}, State: "DECLINED", }, } repository := &dummyRepository{ExistingPrs: existingPrs} useDefaultReviewers := false command.CheckForUpdatesJobCommand(project.Project{SkipPackageManager: skipPackageManageConfiguration, UseDefaultReviewers: &useDefaultReviewers}, &dummySourceControl{}, repository, make(map[string]string), mvn, &dummyVersionControl{}) if repository.OpenPullRequestCalled { t.Log("Should not open a pull request") t.Fail() } } func TestCheckForUpdatesJobCommandWithDecliendPRWithSamePrefix(t *testing.T) { skipPackageManageConfiguration := make(map[string]bool) skipPackageManageConfiguration["mvn"] = false mvn := &dummyVersionControl{} moduleToReturn := []versionManager.ModuleVersion{ versionManager.ModuleVersion{ ModuleUpdater: mvn, Module: "yolo", Current: "1.2.1", Latest: "1.2.3", Wanted: "1.2.3", Name: "swag", }, } mvn.ModuleToReturn = moduleToReturn existingPrs := []managementsystem.PullRequest{ managementsystem.PullRequest{ ID: 32, Title: "Update maven dependency yolo.swag to version 1.2.3", Source: &dummyBranch{BranchName: "lure-swag-1_2_2-71334c00-b060-4830-86c0-c7077545712d"}, Dest: &dummyBranch{BranchName: "irrelevant"}, State: "DECLINED", }, } repository := &dummyRepository{ExistingPrs: existingPrs} useDefaultReviewers := false command.CheckForUpdatesJobCommand(project.Project{SkipPackageManager: skipPackageManageConfiguration, UseDefaultReviewers: &useDefaultReviewers}, &dummySourceControl{}, repository, make(map[string]string), mvn, &dummyVersionControl{}) if !repository.OpenPullRequestCalled { t.Log("Should have opened a pull request with the latest version") t.Fail() } } func TestCheckForUpdatesJobCommandShouldOpenAPRWhenNoPRWasOpenedForThis(t *testing.T) { skipPackageManageConfiguration := make(map[string]bool) skipPackageManageConfiguration["mvn"] = false mvn := &dummyVersionControl{} moduleToReturn := []versionManager.ModuleVersion{ versionManager.ModuleVersion{ ModuleUpdater: mvn, Module: "AnOtherModule", Current: "1.2.1", Latest: "1.2.3", Wanted: "1.2.3", Name: "NoChill", }, } mvn.ModuleToReturn = moduleToReturn existingPrs := []managementsystem.PullRequest{ managementsystem.PullRequest{ ID: 32, Title: "Update maven dependency yolo.swag to version 1.2.3", Source: &dummyBranch{BranchName: "lure-swag-1_2_2-71334c00-b060-4830-86c0-c7077545712d"}, Dest: &dummyBranch{BranchName: "irrelevant"}, State: "DECLINED", }, } repository := &dummyRepository{ExistingPrs: existingPrs} useDefaultReviewers := false command.CheckForUpdatesJobCommand(project.Project{SkipPackageManager: skipPackageManageConfiguration, UseDefaultReviewers: &useDefaultReviewers}, &dummySourceControl{}, repository, make(map[string]string), mvn, &dummyVersionControl{}) if !repository.OpenPullRequestCalled { t.Log("Should have opened a pull request with the latest version") t.Fail() } } func TestNpmFailureShouldNotPreventMvnUpdate(t *testing.T) { skipPackageManageConfiguration := make(map[string]bool) skipPackageManageConfiguration["mvn"] = false skipPackageManageConfiguration["npm"] = false npm := &dummyVersionControl{} mvn := &dummyVersionControl{} repository := &dummyRepository{} useDefaultReviewers := false command.CheckForUpdatesJobCommand(project.Project{SkipPackageManager: skipPackageManageConfiguration, UseDefaultReviewers: &useDefaultReviewers}, &dummySourceControl{}, repository, make(map[string]string), mvn, npm) if !mvn.GetOutdatedWasCalled { t.Log("Should have called GetOutdated for Mvn") t.Fail() } }
30.726937
235
0.738681
5454faaa41b4408bd157b4f88f60bb746879f2e1
4,383
kt
Kotlin
exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/commands/check/CheckParsers.kt
40baht/Exam
1ba5fb794fb57aafcbb95f30add529f3d53f0fbe
[ "MIT" ]
null
null
null
exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/commands/check/CheckParsers.kt
40baht/Exam
1ba5fb794fb57aafcbb95f30add529f3d53f0fbe
[ "MIT" ]
null
null
null
exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/commands/check/CheckParsers.kt
40baht/Exam
1ba5fb794fb57aafcbb95f30add529f3d53f0fbe
[ "MIT" ]
null
null
null
package io.github.adven27.concordion.extensions.exam.db.commands.check import io.github.adven27.concordion.extensions.exam.core.commands.SuitableCommandParser import io.github.adven27.concordion.extensions.exam.core.commands.awaitConfig import io.github.adven27.concordion.extensions.exam.core.html.DbRowParser import io.github.adven27.concordion.extensions.exam.core.html.Html import io.github.adven27.concordion.extensions.exam.core.html.attr import io.github.adven27.concordion.extensions.exam.core.html.html import io.github.adven27.concordion.extensions.exam.db.DbTester.Companion.DEFAULT_DATASOURCE import io.github.adven27.concordion.extensions.exam.db.MarkedHasNoDefaultValue import io.github.adven27.concordion.extensions.exam.db.TableData import io.github.adven27.concordion.extensions.exam.db.builder.DataSetBuilder import io.github.adven27.concordion.extensions.exam.db.builder.ExamTable import io.github.adven27.concordion.extensions.exam.db.commands.ColParser import io.github.adven27.concordion.extensions.exam.db.commands.check.CheckCommand.Expected import org.concordion.api.CommandCall import org.concordion.api.Element import org.concordion.api.Evaluator import org.dbunit.dataset.Column import org.dbunit.dataset.DefaultTable import org.dbunit.dataset.ITable import org.dbunit.dataset.datatype.DataType abstract class CheckParser : SuitableCommandParser<Expected> { abstract fun table(command: CommandCall, evaluator: Evaluator): ITable abstract fun caption(command: CommandCall): String? override fun parse(command: CommandCall, evaluator: Evaluator) = Expected( ds = command.attr("ds", DEFAULT_DATASOURCE), caption = caption(command), table = table(command, evaluator), orderBy = command.html().takeAwayAttr("orderBy", evaluator)?.split(",")?.map { it.trim() } ?: listOf(), where = command.html().takeAwayAttr("where", evaluator) ?: "", await = command.awaitConfig() ) } class MdCheckParser : CheckParser() { override fun isSuitFor(element: Element): Boolean = element.localName != "div" override fun caption(command: CommandCall) = command.element.text.ifBlank { null } private fun root(command: CommandCall) = command.element.parentElement.parentElement override fun table(command: CommandCall, evaluator: Evaluator): ITable { val builder = DataSetBuilder() val tableName = command.expression return root(command) .let { cols(it) to values(it) } .let { (cols, rows) -> rows.forEach { row -> builder.newRowTo(tableName).withFields(cols.zip(row).toMap()).add() } builder.build().let { ExamTable( if (it.tableNames.isEmpty()) DefaultTable(tableName, toColumns(cols)) else it.getTable(tableName), evaluator ) } } } private fun toColumns(cols: List<String>) = cols.map { Column(it, DataType.UNKNOWN) }.toTypedArray() private fun cols(it: Element) = it.getFirstChildElement("thead").getFirstChildElement("tr").childElements.map { it.text.trim() } private fun values(it: Element) = it.getFirstChildElement("tbody").childElements.map { tr -> tr.childElements.map { it.text.trim() } } } open class HtmlCheckParser : CheckParser() { private val remarks = HashMap<String, Int>() private val colParser = ColParser() override fun isSuitFor(element: Element): Boolean = element.localName == "div" override fun caption(command: CommandCall) = command.html().attr("caption") override fun table(command: CommandCall, evaluator: Evaluator): ITable = command.html().let { TableData.filled( it.takeAwayAttr("table", evaluator)!!, DbRowParser(it, "row", null, null).parse(), parseCols(it), evaluator ) } protected fun parseCols(el: Html): Map<String, Any?> { val attr = el.takeAwayAttr("cols") return if (attr == null) emptyMap() else { val remarkAndVal = colParser.parse(attr) remarks += remarkAndVal.map { it.key to it.value.first }.filter { it.second > 0 } remarkAndVal.mapValues { if (it.value.second == null) MarkedHasNoDefaultValue() else it.value.second } } } }
46.136842
114
0.693817
cb04128cc7426c2a2c226dc047fb24a3ee65a92c
274
go
Go
spacelift/internal/structs/worker_pool.go
alexjurkiewicz/terraform-provider-spacelift
14d57c5a6be7d7b009e181af8ada24e04b255d6c
[ "MIT" ]
null
null
null
spacelift/internal/structs/worker_pool.go
alexjurkiewicz/terraform-provider-spacelift
14d57c5a6be7d7b009e181af8ada24e04b255d6c
[ "MIT" ]
null
null
null
spacelift/internal/structs/worker_pool.go
alexjurkiewicz/terraform-provider-spacelift
14d57c5a6be7d7b009e181af8ada24e04b255d6c
[ "MIT" ]
null
null
null
package structs // WorkerPool represents the WorkerPool data relevant to the provider. type WorkerPool struct { ID string `graphql:"id"` Config string `graphql:"config"` Name string `graphql:"name"` Description *string `graphql:"description"` }
27.4
70
0.693431
5624c87f85e1b3a04db1127a0d92c999b2c5ccda
443
kt
Kotlin
mvvm-hilt/src/main/java/com/example/mvvm_hilt/di/FragmentModule.kt
silladus/basiclib
72ed8f05e9b8cb5b196806ab336e21a6031afa39
[ "Apache-2.0" ]
null
null
null
mvvm-hilt/src/main/java/com/example/mvvm_hilt/di/FragmentModule.kt
silladus/basiclib
72ed8f05e9b8cb5b196806ab336e21a6031afa39
[ "Apache-2.0" ]
null
null
null
mvvm-hilt/src/main/java/com/example/mvvm_hilt/di/FragmentModule.kt
silladus/basiclib
72ed8f05e9b8cb5b196806ab336e21a6031afa39
[ "Apache-2.0" ]
null
null
null
package com.example.mvvm_hilt.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.FragmentComponent /** * Created by silladus on 2020/6/21. * GitHub: https://github.com/silladus * Description: */ @Module @InstallIn(FragmentComponent::class) class FragmentModule { @FragmentScope @Provides fun provideString(): String { return hashCode().toString() } }
21.095238
55
0.738149
3bbc8b0d05c5396c494215048597ce75d93b7457
1,037
h
C
src/pow.h
MyProductsKft/VitalCoin
492306908ee457362f2ba777cbd235d417f6d3b5
[ "MIT" ]
null
null
null
src/pow.h
MyProductsKft/VitalCoin
492306908ee457362f2ba777cbd235d417f6d3b5
[ "MIT" ]
null
null
null
src/pow.h
MyProductsKft/VitalCoin
492306908ee457362f2ba777cbd235d417f6d3b5
[ "MIT" ]
null
null
null
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef VITALCOIN_POW_H #define VITALCOIN_POW_H #include "consensus/params.h" #include <stdint.h> class CBlockHeader; class CBlockIndex; class uint256; unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params &); unsigned int CalculateNextWorkRequired(const CBlockIndex *pindexLast, int64_t nFirstBlockTime, const Consensus::Params &); /** Check whether a block hash satisfies the proof-of-work requirement specified * by nBits */ bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &, uint256 *best = nullptr); #endif // VITALCOIN_POW_H
34.566667
80
0.663452
e9c5a0ffd5e1f48a5bb0cf58f22717fe1cbb5e5f
340
rb
Ruby
app/controllers/doorkeeper_controller.rb
ErickMtz/gifts_api
f4cfbefb8ba4925e82d1c09a4ea40a4c9af7f7b5
[ "Apache-2.0" ]
null
null
null
app/controllers/doorkeeper_controller.rb
ErickMtz/gifts_api
f4cfbefb8ba4925e82d1c09a4ea40a4c9af7f7b5
[ "Apache-2.0" ]
null
null
null
app/controllers/doorkeeper_controller.rb
ErickMtz/gifts_api
f4cfbefb8ba4925e82d1c09a4ea40a4c9af7f7b5
[ "Apache-2.0" ]
null
null
null
class DoorkeeperController < ActionController::API def user user = User.find_by(email: user_params[:email]) user&.authenticate(user_params[:password]) || head(:unauthorized) end private def user_params {}.tap do |h| h[:email] = params.require(:email) h[:password] = params.require(:password) end end end
24.285714
69
0.679412
0c7a6a41c0a3a1f235803d1783bd66e37bc01cb9
217
py
Python
geoscilabs/gpr/Wiggle.py
jcapriot/geosci-labs
044a73432b9cb1187924f7761942ab329259d875
[ "MIT" ]
2
2019-01-15T03:02:28.000Z
2019-03-20T03:41:12.000Z
geoscilabs/gpr/Wiggle.py
jcapriot/geosci-labs
044a73432b9cb1187924f7761942ab329259d875
[ "MIT" ]
1
2018-12-30T20:09:25.000Z
2018-12-30T20:09:25.000Z
geoscilabs/gpr/Wiggle.py
jcapriot/geosci-labs
044a73432b9cb1187924f7761942ab329259d875
[ "MIT" ]
null
null
null
import numpy as np def PrimaryWave(x, velocity, tinterp): return tinterp + 1.0 / velocity * x def ReflectedWave(x, velocity, tinterp): time = np.sqrt(x ** 2 / velocity ** 2 + tinterp ** 2) return time
19.727273
57
0.645161
ced28f1b41981e46147c54e5f9738ec736b1332c
6,983
kt
Kotlin
src/main/kotlin/org/lanternpowered/kt/inject/KotlinBinderImpl.kt
Cybermaxke/KotlinAdapter
2218e169111c3153d8aab482959ce8445bdde7b7
[ "MIT" ]
1
2019-05-11T00:39:36.000Z
2019-05-11T00:39:36.000Z
src/main/kotlin/org/lanternpowered/kt/inject/KotlinBinderImpl.kt
Cybermaxke/KotlinAdapter
2218e169111c3153d8aab482959ce8445bdde7b7
[ "MIT" ]
null
null
null
src/main/kotlin/org/lanternpowered/kt/inject/KotlinBinderImpl.kt
Cybermaxke/KotlinAdapter
2218e169111c3153d8aab482959ce8445bdde7b7
[ "MIT" ]
null
null
null
/* * This file is part of KotlinAdapter, licensed under the MIT License (MIT). * * Copyright (c) LanternPowered <https://www.lanternpowered.org/> * Copyright (c) contributors * * 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. */ @file:Suppress("UNCHECKED_CAST") package org.lanternpowered.kt.inject import com.google.common.reflect.TypeToken import com.google.inject.Binder import com.google.inject.Key import com.google.inject.MembersInjector import com.google.inject.PrivateBinder import com.google.inject.Provider import com.google.inject.TypeLiteral import com.google.inject.binder.AnnotatedBindingBuilder import com.google.inject.binder.AnnotatedConstantBindingBuilder import com.google.inject.binder.AnnotatedElementBuilder import com.google.inject.binder.ConstantBindingBuilder import com.google.inject.binder.LinkedBindingBuilder import com.google.inject.binder.ScopedBindingBuilder import org.lanternpowered.kt.typeLiteral import kotlin.reflect.KClass internal class PrivateKotlinBinderImpl(private val binder: PrivateBinder) : PrivateKotlinBinder(), PrivateBinder by binder { override fun <T> bind(key: Key<T>) = KLinkedBindingBuilderImpl(this.binder.bind(key)) override fun <T> bind(typeLiteral: TypeLiteral<T>) = KAnnotatedBindingBuilderImpl(this.binder.bind(typeLiteral)) override fun <T> bind(type: Class<T>) = KAnnotatedBindingBuilderImpl(this.binder.bind(type)) override fun <T> bind(typeToken: TypeToken<T>): KAnnotatedBindingBuilder<T> = bind(typeToken.typeLiteral) override fun bindConstant() = KAnnotatedConstantBindingBuilderImpl(this.binder.bindConstant()) override fun <T : Any> getProvider(kClass: KClass<T>): Provider<T> = getProvider(Key.get(kClass.java)) override fun <T> getProvider(typeLiteral: TypeLiteral<T>): Provider<T> = getProvider(Key.get(typeLiteral)) override fun <T> getProvider(typeToken: TypeToken<T>): Provider<T> = getProvider(Key.get(typeToken.typeLiteral)) override fun <T : Any> getMembersInjector(kClass: KClass<T>): MembersInjector<T> = getMembersInjector(kClass.java) override fun <T> getMembersInjector(typeToken: TypeToken<T>): MembersInjector<T> = getMembersInjector(typeToken.typeLiteral) override fun expose(type: KClass<*>): AnnotatedElementBuilder = expose(type.java) override fun expose(type: TypeToken<*>): AnnotatedElementBuilder = expose(type.typeLiteral) } internal class KotlinBinderImpl(internal val binder: Binder) : KotlinBinder(), Binder by binder { override fun <T> bind(key: Key<T>) = KLinkedBindingBuilderImpl(this.binder.bind(key)) override fun <T> bind(typeLiteral: TypeLiteral<T>) = KAnnotatedBindingBuilderImpl(this.binder.bind(typeLiteral)) override fun <T> bind(type: Class<T>) = KAnnotatedBindingBuilderImpl(this.binder.bind(type)) override fun <T> bind(typeToken: TypeToken<T>) = bind(typeToken.typeLiteral) override fun bindConstant() = KAnnotatedConstantBindingBuilderImpl(this.binder.bindConstant()) override fun <T : Any> getProvider(kClass: KClass<T>): Provider<T> = getProvider(Key.get(kClass.java)) override fun <T> getProvider(typeLiteral: TypeLiteral<T>): Provider<T> = getProvider(Key.get(typeLiteral)) override fun <T> getProvider(typeToken: TypeToken<T>): Provider<T> = getProvider(Key.get(typeToken.typeLiteral)) override fun <T : Any> getMembersInjector(kClass: KClass<T>): MembersInjector<T> = getMembersInjector(kClass.java) override fun <T> getMembersInjector(typeToken: TypeToken<T>): MembersInjector<T> = getMembersInjector(typeToken.typeLiteral) } internal class KLinkedBindingBuilderImpl<T>( private val builder: LinkedBindingBuilder<T> ) : KLinkedBindingBuilder<T>(), LinkedBindingBuilder<T> by builder { override fun <T : Any> to(implementation: KClass<out T>): ScopedBindingBuilder { return (this as LinkedBindingBuilder<Any?>).to(implementation.java as Class<out Any?>) } override fun <R : T> toProvider(provider: () -> R): ScopedBindingBuilder = toProvider(Provider(provider)) } internal class KAnnotatedBindingBuilderImpl<T>( private val builder: AnnotatedBindingBuilder<T> ) : KAnnotatedBindingBuilder<T>(), AnnotatedBindingBuilder<T> by builder { override fun annotatedWith(annotationType: Class<out Annotation>) = this.builder.annotatedWith(annotationType).run { this as? KLinkedBindingBuilder<T> ?: KLinkedBindingBuilderImpl(this) } override fun annotatedWith(annotation: Annotation) = this.builder.annotatedWith(annotation).run { this as? KLinkedBindingBuilder<T> ?: KLinkedBindingBuilderImpl(this) } override fun <T : Any> to(implementation: KClass<out T>): ScopedBindingBuilder { return (this as LinkedBindingBuilder<Any?>).to(implementation.java as Class<out Any?>) } override fun annotatedWith(annotationType: KClass<out Annotation>) = annotatedWith(annotationType.java) override fun <R : T> toProvider(provider: () -> R): ScopedBindingBuilder = toProvider(Provider(provider)) } internal class KAnnotatedConstantBindingBuilderImpl( private val builder: AnnotatedConstantBindingBuilder ) : KAnnotatedConstantBindingBuilder(), AnnotatedConstantBindingBuilder by builder { override fun annotatedWith(annotationType: Class<out Annotation>) = this.builder.annotatedWith(annotationType).run { this as? KConstantBindingBuilder ?: KConstantBindingBuilderImpl(this) } override fun annotatedWith(annotation: Annotation) = this.builder.annotatedWith(annotation).run { this as? KConstantBindingBuilder ?: KConstantBindingBuilderImpl(this) } override fun annotatedWith(annotationType: KClass<out Annotation>): KConstantBindingBuilder = annotatedWith(annotationType.java) } internal class KConstantBindingBuilderImpl( private val builder: ConstantBindingBuilder ) : KConstantBindingBuilder(), ConstantBindingBuilder by builder { override fun to(value: KClass<*>) { to(value.java) } }
52.503759
132
0.768438
72417af1c809ea92f981f5d53f5a5ceb13ed43be
19,960
rs
Rust
src/types_edition.rs
PoignardAzur/venial
b490dd70226cb2b46d63849154bd06a35ee566d3
[ "MIT" ]
62
2022-03-10T10:45:40.000Z
2022-03-28T18:44:22.000Z
src/types_edition.rs
PoignardAzur/venial
b490dd70226cb2b46d63849154bd06a35ee566d3
[ "MIT" ]
4
2022-03-11T09:24:04.000Z
2022-03-30T15:08:21.000Z
src/types_edition.rs
PoignardAzur/venial
b490dd70226cb2b46d63849154bd06a35ee566d3
[ "MIT" ]
2
2022-03-11T14:16:19.000Z
2022-03-18T11:16:34.000Z
pub use crate::types::{ Attribute, AttributeValue, Declaration, Enum, EnumVariant, EnumVariantValue, Function, GenericBound, GenericParam, GenericParamList, GroupSpan, InlineGenericArgs, NamedField, Struct, StructFields, TupleField, TyExpr, Union, VisMarker, WhereClause, WhereClauseItem, }; use proc_macro2::{Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; impl Declaration { /// Returns the [`Vec<Attribute>`] of the declaration. pub fn attributes(&self) -> &Vec<Attribute> { match self { Declaration::Struct(struct_decl) => &struct_decl.attributes, Declaration::Enum(enum_decl) => &enum_decl.attributes, Declaration::Union(union_decl) => &union_decl.attributes, Declaration::Function(function_decl) => &function_decl.attributes, } } /// Returns the [`Vec<Attribute>`] of the declaration. pub fn attributes_mut(&mut self) -> &mut Vec<Attribute> { match self { Declaration::Struct(struct_decl) => &mut struct_decl.attributes, Declaration::Enum(enum_decl) => &mut enum_decl.attributes, Declaration::Union(union_decl) => &mut union_decl.attributes, Declaration::Function(function_decl) => &mut function_decl.attributes, } } /// Returns the [`GenericParamList`], if any, of the declaration. /// /// For instance, this will return Some for `struct MyStruct<A, B, C> { ... }` /// and None for `enum MyEnum { ... }`. pub fn generic_params(&self) -> Option<&GenericParamList> { match self { Declaration::Struct(struct_decl) => struct_decl.generic_params.as_ref(), Declaration::Enum(enum_decl) => enum_decl.generic_params.as_ref(), Declaration::Union(union_decl) => union_decl.generic_params.as_ref(), Declaration::Function(function_decl) => function_decl.generic_params.as_ref(), } } /// Returns the [`GenericParamList`], if any, of the declaration. pub fn generic_params_mut(&mut self) -> Option<&mut GenericParamList> { match self { Declaration::Struct(struct_decl) => struct_decl.generic_params.as_mut(), Declaration::Enum(enum_decl) => enum_decl.generic_params.as_mut(), Declaration::Union(union_decl) => union_decl.generic_params.as_mut(), Declaration::Function(function_decl) => function_decl.generic_params.as_mut(), } } /// Returns the [`Ident`] of the declaration. /// /// ``` /// # use venial::parse_declaration; /// # use quote::quote; /// let struct_type = parse_declaration(quote!( /// struct Hello(A, B); /// )).unwrap(); /// assert_eq!(struct_type.name().to_string(), "Hello"); /// ``` pub fn name(&self) -> Ident { match self { Declaration::Struct(struct_decl) => struct_decl.name.clone(), Declaration::Enum(enum_decl) => enum_decl.name.clone(), Declaration::Union(union_decl) => union_decl.name.clone(), Declaration::Function(function_decl) => function_decl.name.clone(), } } /// Returns the [`Struct`] variant of the enum if possible. pub fn as_struct(&self) -> Option<&Struct> { match self { Declaration::Struct(struct_decl) => Some(struct_decl), _ => None, } } /// Returns the [`Enum`] variant of the enum if possible. pub fn as_enum(&self) -> Option<&Enum> { match self { Declaration::Enum(enum_decl) => Some(enum_decl), _ => None, } } /// Returns the [`Union`] variant of the enum if possible. pub fn as_union(&self) -> Option<&Union> { match self { Declaration::Union(union_decl) => Some(union_decl), _ => None, } } /// Returns the [`Function`] variant of the enum if possible. pub fn as_function(&self) -> Option<&Function> { match self { Declaration::Function(function_decl) => Some(function_decl), _ => None, } } } impl Struct { /// Returns a collection of strings that can be used to exhaustively /// access the struct's fields. /// /// If the struct is a tuple struct, integer strings will be returned. /// /// ``` /// # use venial::parse_declaration; /// # use quote::quote; /// let struct_type = parse_declaration(quote!( /// struct Hello { /// a: Foo, /// b: Bar, /// } /// )).unwrap(); /// let struct_type = struct_type.as_struct().unwrap(); /// let field_names: Vec<_> = struct_type.field_names().into_iter().collect(); /// assert_eq!(field_names, ["a", "b"]); /// ``` /// /// ``` /// # use venial::parse_declaration; /// # use quote::quote; /// let tuple_type = parse_declaration(quote!( /// struct Hello(Foo, Bar); /// )).unwrap(); /// let tuple_type = tuple_type.as_struct().unwrap(); /// let field_names: Vec<_> = tuple_type.field_names().into_iter().collect(); /// assert_eq!(field_names, ["0", "1"]); /// ``` pub fn field_names(&self) -> impl IntoIterator<Item = String> { match &self.fields { StructFields::Unit => Vec::new(), StructFields::Tuple(tuple_fields) => { let range = 0..tuple_fields.fields.len(); range.map(|i| i.to_string()).collect() } StructFields::Named(named_fields) => named_fields .fields .items() .map(|field| field.name.to_string()) .collect(), } } /// Returns a collection of tokens that can be used to exhaustively /// access the struct's fields. /// /// If the struct is a tuple struct, span-less integer literals will be returned. pub fn field_tokens(&self) -> impl IntoIterator<Item = TokenTree> { match &self.fields { StructFields::Unit => Vec::new(), StructFields::Tuple(tuple_fields) => { let range = 0..tuple_fields.fields.len(); range.map(|i| Literal::usize_unsuffixed(i).into()).collect() } StructFields::Named(named_fields) => named_fields .fields .items() .map(|field| field.name.clone().into()) .collect(), } } /// Returns a collection of references to the struct's field types. pub fn field_types(&self) -> impl IntoIterator<Item = &TyExpr> { match &self.fields { StructFields::Unit => Vec::new(), StructFields::Tuple(tuple_fields) => { tuple_fields.fields.items().map(|field| &field.ty).collect() } StructFields::Named(named_fields) => { named_fields.fields.items().map(|field| &field.ty).collect() } } } } impl Enum { /// Returns true if every single variant is empty. /// /// ``` /// # use venial::parse_declaration; /// # use quote::quote; /// let enum_type = parse_declaration(quote!( /// enum MyEnum { A, B, C, D } /// )).unwrap(); /// let enum_type = enum_type.as_enum().unwrap(); /// assert!(enum_type.is_c_enum()); /// ``` pub fn is_c_enum(&self) -> bool { for variant in self.variants.items() { if !variant.is_empty_variant() { return false; } } true } } macro_rules! implement_common_methods { ($Kind:ident) => { impl $Kind { /// Builder method, add a [`GenericParam`] to `self.generic_params`. /// /// Creates a default [`GenericParamList`] if `self.generic_params` is None. pub fn with_param(mut self, param: GenericParam) -> Self { let params = self.generic_params.take().unwrap_or_default(); let params = params.with_param(param); self.generic_params = Some(params); self } /// Builder method, add a [`WhereClauseItem`] to `self.where_clause`. /// /// Creates a default [`WhereClause`] if `self.where_clause` is None. pub fn with_where_item(mut self, item: WhereClauseItem) -> Self { if let Some(where_clause) = self.where_clause { self.where_clause = Some(where_clause.with_item(item)); } else { self.where_clause = Some(WhereClause::from_item(item)); } self } /// Returns a collection of references to declared lifetime params, if any. pub fn get_lifetime_params(&self) -> impl Iterator<Item = &GenericParam> { let params: &[_] = if let Some(params) = self.generic_params.as_ref() { &params.params } else { &[] }; params .iter() .map(|(param, _punct)| param) .filter(|param| GenericParam::is_lifetime(param)) } /// Returns a collection of references to declared type params, if any. pub fn get_type_params(&self) -> impl Iterator<Item = &GenericParam> { let params: &[_] = if let Some(params) = self.generic_params.as_ref() { &params.params } else { &[] }; params .iter() .map(|(param, _punct)| param) .filter(|param| GenericParam::is_ty(param)) } /// Returns a collection of references to declared const generic params, if any. pub fn get_const_params(&self) -> impl Iterator<Item = &GenericParam> { let params: &[_] = if let Some(params) = self.generic_params.as_ref() { &params.params } else { &[] }; params .iter() .map(|(param, _punct)| param) .filter(|param| GenericParam::is_const(param)) } /// See [`InlineGenericArgs`] for details. pub fn get_inline_generic_args(&self) -> Option<InlineGenericArgs<'_>> { Some(self.generic_params.as_ref()?.as_inline_args()) } /// Returns a where clause that can be quoted to form /// a `impl TRAIT for TYPE where ... { ... }` trait implementation. /// /// This takes the bounds of the current declaration and adds one bound /// to `derived_trait` for every generic argument. For instance: /// /// ```no_run /// struct MyStruct<T, U> where T: Clone { /// t: T, /// u: U /// } /// /// // my_struct_decl.create_derive_where_clause(quote!(SomeTrait)) /// /// # trait SomeTrait {} /// impl<T, U> SomeTrait for MyStruct<T, U> /// // GENERATED WHERE CLAUSE /// where T: SomeTrait, U: SomeTrait, T: Clone /// { /// // ... /// } /// ``` pub fn create_derive_where_clause(&self, derived_trait: TokenStream) -> WhereClause { let mut where_clause = self.where_clause.clone().unwrap_or_default(); for param in self.get_type_params() { let item = WhereClauseItem { left_side: vec![param.name.clone().into()], bound: GenericBound { tk_colon: Punct::new(':', Spacing::Alone), tokens: derived_trait.clone().into_iter().collect(), }, }; where_clause = where_clause.with_item(item); } where_clause } } }; } implement_common_methods! { Struct } implement_common_methods! { Enum } implement_common_methods! { Union } impl Attribute { /// Returns Some if the attribute has a single path segment, eg `#[hello(...)]`. /// Returns None if the attribute has multiple segments, eg `#[hello::world(...)]`. pub fn get_single_path_segment(&self) -> Option<&Ident> { let mut segments: Vec<_> = self .path .iter() .filter_map(|segment| match segment { TokenTree::Ident(ident) => Some(ident), _ => None, }) .collect(); if segments.len() == 1 { segments.pop() } else { None } } /// Returns `foo + bar` for `#[hello = foo + bar]` and `#[hello(foo + bar)]`. /// Returns an empty slice for `#[hello]`. pub fn get_value_tokens(&self) -> &[TokenTree] { self.value.get_value_tokens() } } impl AttributeValue { /// Returns `foo + bar` for `#[hello = foo + bar]` and `#[hello(foo + bar)]`. /// Returns an empty slice for `#[hello]`. pub fn get_value_tokens(&self) -> &[TokenTree] { match self { AttributeValue::Group(_, tokens) => tokens, AttributeValue::Equals(_, tokens) => tokens, AttributeValue::Empty => &[], } } } impl EnumVariant { /// Returns true if the variant doesn't store a type. pub fn is_empty_variant(&self) -> bool { matches!(self.contents, StructFields::Unit) } /// Returns Some if the variant is a wrapper around a single type. /// Returns None otherwise. pub fn get_single_type(&self) -> Option<&TupleField> { match &self.contents { StructFields::Tuple(fields) if fields.fields.len() == 1 => Some(&fields.fields[0].0), StructFields::Tuple(_fields) => None, StructFields::Unit => None, StructFields::Named(_) => None, } } } impl GenericParamList { /// Builder method, add a [`GenericParam`]. /// /// Add lifetime params to the beginning of the list. pub fn with_param(mut self, param: GenericParam) -> Self { if param.is_lifetime() { self.params.insert(0, param, None); } else { self.params.push(param, None); } self } /// See [`InlineGenericArgs`] for details. pub fn as_inline_args(&self) -> InlineGenericArgs<'_> { InlineGenericArgs(self) } } impl GenericParam { /// Create new lifetime param from name. /// /// ``` /// # use venial::GenericParam; /// GenericParam::lifetime("a") /// # ; /// ``` pub fn lifetime(name: &str) -> Self { let lifetime_ident = Ident::new(name, Span::call_site()); GenericParam { tk_prefix: Some(Punct::new('\'', Spacing::Joint).into()), name: lifetime_ident, bound: None, } } /// Create new lifetime param from name and bound. /// /// ``` /// # use venial::GenericParam; /// # use quote::quote; /// GenericParam::bounded_lifetime("a", quote!(b + c).into_iter().collect()) /// # ; /// ``` pub fn bounded_lifetime(name: &str, bound: Vec<TokenTree>) -> Self { let lifetime_ident = Ident::new(name, Span::call_site()); GenericParam { tk_prefix: Some(Punct::new('\'', Spacing::Alone).into()), name: lifetime_ident, bound: Some(GenericBound { tk_colon: Punct::new(':', Spacing::Alone), tokens: bound, }), } } /// Create new type param from name. /// /// ``` /// # use venial::GenericParam; /// GenericParam::ty("T") /// # ; /// ``` pub fn ty(name: &str) -> Self { let ty_ident = Ident::new(name, Span::call_site()); GenericParam { tk_prefix: None, name: ty_ident, bound: None, } } /// Create new type param from name and bound. /// /// ``` /// # use venial::GenericParam; /// # use quote::quote; /// GenericParam::bounded_ty("T", quote!(Debug + Eq).into_iter().collect()) /// # ; /// ``` pub fn bounded_ty(name: &str, bound: Vec<TokenTree>) -> Self { let ty_ident = Ident::new(name, Span::call_site()); GenericParam { tk_prefix: None, name: ty_ident, bound: Some(GenericBound { tk_colon: Punct::new(':', Spacing::Alone), tokens: bound, }), } } /// Create new const param from name and type. /// /// ``` /// # use venial::GenericParam; /// # use quote::quote; /// GenericParam::const_param("N", quote!(i32).into_iter().collect()) /// # ; /// ``` pub fn const_param(name: &str, ty: Vec<TokenTree>) -> Self { let lifetime_ident = Ident::new(name, Span::call_site()); GenericParam { tk_prefix: Some(Ident::new("const", Span::call_site()).into()), name: lifetime_ident, bound: Some(GenericBound { tk_colon: Punct::new(':', Spacing::Alone), tokens: ty, }), } } /// Returns true if the generic param is a lifetime param. pub fn is_lifetime(&self) -> bool { match &self.tk_prefix { Some(TokenTree::Punct(punct)) if punct.as_char() == '\'' => true, _ => false, } } /// Returns true if the generic param is a type param. pub fn is_ty(&self) -> bool { #[allow(clippy::redundant_pattern_matching)] match &self.tk_prefix { Some(_) => false, None => true, } } /// Returns true if the generic param is a const param. pub fn is_const(&self) -> bool { match &self.tk_prefix { Some(TokenTree::Ident(ident)) if ident == "const" => true, _ => false, } } } impl WhereClause { /// Create where-clause with a single item. pub fn from_item(item: WhereClauseItem) -> Self { Self::default().with_item(item) } /// Builder method, add an item to the where-clause. pub fn with_item(mut self, item: WhereClauseItem) -> Self { self.items.push(item, None); self } } impl WhereClauseItem { /// Helper method to create a WhereClauseItem from a quote. /// /// # Panics /// /// Panics if given a token stream that isn't a valid where-clause item. pub fn parse(tokens: TokenStream) -> Self { let mut tokens = tokens.into_iter().peekable(); let left_side = crate::parse_utils::consume_stuff_until( &mut tokens, |token| match token { TokenTree::Punct(punct) if punct.as_char() == ':' => true, _ => false, }, false, ); let colon = match tokens.next() { Some(TokenTree::Punct(punct)) if punct.as_char() == ':' => punct, Some(token) => panic!( "cannot parse where-clause item: expected ':', found token {:?}", token ), None => { panic!("cannot parse where-clause item: expected colon, found end of stream") } }; let bound_tokens = tokens.collect(); WhereClauseItem { left_side, bound: GenericBound { tk_colon: colon, tokens: bound_tokens, }, } } } impl GroupSpan { /// Create from proc_macro2 Group. pub fn new(group: &Group) -> Self { Self { span: group.span(), delimiter: group.delimiter(), } } }
34.413793
99
0.528557
a3dc72f305515de72d1428ce475c4d5c9d326943
760
asm
Assembly
oeis/185/A185369.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/185/A185369.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/185/A185369.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A185369: Number of simple labeled graphs on n nodes of degree 1 or 2 without cycles. ; Submitted by Christian Krause ; 1,0,1,3,15,90,645,5355,50505,532980,6219045,79469775,1103335695,16533226710,265888247625,4566885297975,83422361847825,1614626682669000,33003508539026025,710350201433547675,16057073233633006575,380286190206828155250,9416074226166167885325,243272158343337774125475,6546343026432950997881625,183177929177077440823717500,5321767571151923885166298125,160301324409813009880336254375,4999782954461199729321781659375,161276853137587886420542119048750,5374145090926593942321071346260625 mov $4,1 lpb $0 sub $0,1 add $1,$4 mul $1,$0 mov $3,$2 mul $4,$0 add $3,$4 add $4,$1 div $4,2 sub $4,$2 add $2,$4 mov $4,$3 lpe mov $0,$4
38
479
0.805263
9c4772124d69013f40db629785d5755ba6a3e80c
422
asm
Assembly
libsrc/_DEVELOPMENT/string/c/sccz80/strrstr_callee.asm
UnivEngineer/z88dk
9047beba62595b1d88991bc934da75c0e2030d07
[ "ClArtistic" ]
1
2022-03-08T11:55:58.000Z
2022-03-08T11:55:58.000Z
libsrc/_DEVELOPMENT/string/c/sccz80/strrstr_callee.asm
UnivEngineer/z88dk
9047beba62595b1d88991bc934da75c0e2030d07
[ "ClArtistic" ]
2
2022-03-20T22:17:35.000Z
2022-03-24T16:10:00.000Z
libsrc/_DEVELOPMENT/string/c/sccz80/strrstr_callee.asm
jorgegv/z88dk
127130cf11f9ff268ba53e308138b12d2b9be90a
[ "ClArtistic" ]
null
null
null
; char *strrstr(const char *s, const char *w) SECTION code_clib SECTION code_string PUBLIC strrstr_callee EXTERN asm_strrstr strrstr_callee: IF __CPU_GBZ80__ pop bc pop de pop hl push bc call asm_strrstr ld d,h ld e,l ret ELSE pop hl pop de ex (sp),hl jp asm_strrstr ENDIF ; SDCC bridge for Classic IF __CLASSIC PUBLIC _strrstr_callee defc _strrstr_callee = strrstr_callee ENDIF
12.411765
45
0.725118
95c7c1ab14303df9086bb12d8b791903f3675a0d
338
sql
SQL
openGaussBase/testcase/SQL/DATATYPE/decimal/bigserial/Opengauss_Function_Datatype_Bigserial_Case0011.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/SQL/DATATYPE/decimal/bigserial/Opengauss_Function_Datatype_Bigserial_Case0011.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/SQL/DATATYPE/decimal/bigserial/Opengauss_Function_Datatype_Bigserial_Case0011.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
-- @testpoint: 插入指数形式值 drop table if exists bigserial_11; create table bigserial_11 (name bigserial); insert into bigserial_11 values (exp(33)); insert into bigserial_11 values (exp(-15)); insert into bigserial_11 values (exp(12.34)); insert into bigserial_11 values (exp(-99.99999)); select * from bigserial_11; drop table bigserial_11;
33.8
49
0.778107
3b3a4999ecd6ac88ea2540589cd7ca93157f0fd1
1,696
c
C
src/helpf.c
just6chill/hdir
94fabcb109cb6c29888c93b48eb1b0d5219736e3
[ "Apache-2.0" ]
9
2021-01-01T16:18:27.000Z
2022-03-20T09:59:00.000Z
src/helpf.c
just6chill/hdir
94fabcb109cb6c29888c93b48eb1b0d5219736e3
[ "Apache-2.0" ]
2
2021-01-01T16:20:24.000Z
2021-01-09T14:44:45.000Z
src/helpf.c
just6chill/hdir
94fabcb109cb6c29888c93b48eb1b0d5219736e3
[ "Apache-2.0" ]
3
2021-01-02T16:44:49.000Z
2021-03-10T07:23:11.000Z
#include "helpf.h" #include "color.h" #include <stdio.h> #include <windows.h> #define WHITESPACE printf("\n"); int helpf(char *args[]) { /* start help output */ green("syntax"); printf(": '"); green("hdir "); printf("<"); green("suffix"); printf("> <"); green("parameter1"); printf("> <"); green("parameter2"); printf(">' \n"); printf("'"); green("r"); printf("' - rename a file or a folder \n Example: 'hdir r example.txt newname.txt' \n "); WHITESPACE printf("'"); green("c"); printf("' - copy a file \n Example: 'hdir c example.txt newfile.txt' \n "); WHITESPACE printf("'"); green("d"); printf("' - delete a file \n Example: 'hdir d example.txt' \n "); WHITESPACE printf("'"); green("f"); printf("' - create a folder \n Example: 'hdir f folder1 folder2 foldern' \n "); WHITESPACE printf("'"); green("n"); printf("' - create a file with given extension \n Example: 'hdir n example.txt example1.txt examplen.txt' \n "); WHITESPACE printf("'"); green("k"); printf("' - delete a folder \n Example: 'hdir k examplefolder' \n "); WHITESPACE printf("'"); green("l"); printf("' - show all files and subfolders of the named folder/directory \n Example: 'hdir l examplefolder' \n "); WHITESPACE printf("'"); green("s"); printf("' - show stats of a file (size, perms, last change, user-id, drive) \n Example: 'hdir s example.txt' \n"); WHITESPACE printf("'"); green("h"); printf("' - type 'hdir h' for help \n"); printf("several parameters only allowed with create a folder or file as explained in the examples \n"); WHITESPACE printf("hdir made by "); green("just6chill"); printf("(github)"); return 0; }
44.631579
168
0.614976
fe28b50106f7ee4fe230e1fe94ef9f9e210bc2d0
1,009
c
C
jisuanke.com/C2991/A/a.c
jyi2ya/artifacts
c227d170592d1fec94a09b20e2f1f75a46dfdf1f
[ "MIT" ]
null
null
null
jisuanke.com/C2991/A/a.c
jyi2ya/artifacts
c227d170592d1fec94a09b20e2f1f75a46dfdf1f
[ "MIT" ]
null
null
null
jisuanke.com/C2991/A/a.c
jyi2ya/artifacts
c227d170592d1fec94a09b20e2f1f75a46dfdf1f
[ "MIT" ]
null
null
null
#include <stdio.h> long long gans; long long cnt; int stk1[5000009], stk2[5000009]; int tp1, tp2; void init(void) { cnt = 1; gans = 0; tp1 = tp2 = 0; } void PUSH(int x) { stk1[tp1++] = x; if (tp2 == 0 || x >= stk2[tp2 - 1]) stk2[tp2++] = x; gans ^= cnt * stk2[tp2 - 1]; ++cnt; } void POP(void) { if (tp1 > 0) { --tp1; if (tp1 > 0) { if (stk2[tp2 - 1] == stk1[tp1]) --tp2; gans ^= cnt * stk2[tp2 - 1]; } else { tp2 = 0; } } ++cnt; } int n, p, q, m; unsigned int SA, SB, SC; unsigned int rng61(void) { SA ^= SA << 16; SA ^= SA >> 5; SA ^= SA << 1; unsigned int t = SA; SA = SB; SB = SC; SC ^= t ^ SA; return SC; } void gen(void) { scanf("%d%d%d%d%u%u%u", &n, &p, &q, &m, &SA, &SB, &SC); for(int i = 1; i <= n; i++) { if(rng61() % (p + q) < (unsigned int)p) PUSH(rng61() % m + 1); else POP(); } } int main(void) { int T; int i; scanf("%d", &T); for (i = 1; i <= T; ++i) { init(); gen(); printf("Case #%d: %lld\n", i, gans); } return 0; }
13.103896
56
0.472745
cb2eedb0a54cd8132004b51e8c3cb30967e81607
706
h
C
ios/LycamPlus.framework/Versions/A/Headers/LCPQiniuStream.h
lycam/LycamPlusSDK-iOS
222d0c19a57b7ba697698567b2a1db21e0d8fa71
[ "MIT" ]
null
null
null
ios/LycamPlus.framework/Versions/A/Headers/LCPQiniuStream.h
lycam/LycamPlusSDK-iOS
222d0c19a57b7ba697698567b2a1db21e0d8fa71
[ "MIT" ]
null
null
null
ios/LycamPlus.framework/Versions/A/Headers/LCPQiniuStream.h
lycam/LycamPlusSDK-iOS
222d0c19a57b7ba697698567b2a1db21e0d8fa71
[ "MIT" ]
null
null
null
// // LCPQiniuStream.h // Pods // // Created by no on 15/11/9. // // #import "LCPStream.h" extern const struct LCPQiniuStreamAttributes { __unsafe_unretained NSString *bucketName; __unsafe_unretained NSURL *uploadURLBackup; __unsafe_unretained NSString *uploadIP; __unsafe_unretained NSString *uploadIPBackup; __unsafe_unretained NSString *uploadPort; } LCPQiniuStreamAttributes; @interface LCPQiniuStream : LCPStream @property (nonatomic, strong) NSString *bucketName; @property (nonatomic, strong) NSURL *uploadURLBackup; @property (nonatomic, strong) NSString *uploadIP; @property (nonatomic, strong) NSString *uploadIPBackup; @property (nonatomic) NSInteger uploadPort; @end
26.148148
55
0.773371
35788a6109ecfccd5f8f6be8aa7ff6e49d9c41df
369
lua
Lua
graphics/hello-world/game/main.lua
TurtleP/lovepotion-examples
c95b9d7ce6c4f0b2df3a08cd8dc3c0e172b3e4f9
[ "MIT" ]
2
2019-07-10T01:52:13.000Z
2021-08-07T20:29:47.000Z
graphics/hello-world/game/main.lua
TurtleP/lovepotion-examples
c95b9d7ce6c4f0b2df3a08cd8dc3c0e172b3e4f9
[ "MIT" ]
null
null
null
graphics/hello-world/game/main.lua
TurtleP/lovepotion-examples
c95b9d7ce6c4f0b2df3a08cd8dc3c0e172b3e4f9
[ "MIT" ]
6
2019-05-04T17:13:45.000Z
2022-03-24T18:46:32.000Z
function love.load() local down, OS = "plus", {love.system.getOS()} if OS[2] == "3DS" then down = "start" end exitKey = down end function love.update(dt) end function love.draw() love.graphics.print("Hello World!", 10, 10) end function love.gamepadpressed(joy, button) if button == exitKey then love.event.quit() end end
16.772727
50
0.623306
df855aeaaa0bc2369a8b24c6e2ccad59772b8130
229
ts
TypeScript
src/core/decorators/authUser.decorator.ts
yangheng15/sutdy-nest
d32be021ee4d1f1a21b9a89c1cace52129b47aa6
[ "MIT" ]
null
null
null
src/core/decorators/authUser.decorator.ts
yangheng15/sutdy-nest
d32be021ee4d1f1a21b9a89c1cace52129b47aa6
[ "MIT" ]
null
null
null
src/core/decorators/authUser.decorator.ts
yangheng15/sutdy-nest
d32be021ee4d1f1a21b9a89c1cace52129b47aa6
[ "MIT" ]
null
null
null
import { createParamDecorator } from "@nestjs/common"; export const AuthUser = createParamDecorator((data, ctx) => { const request = ctx.switchToHttp().getRequest(); const user = request.user; return user; })
20.818182
61
0.676856
612e7af6131a8fd8741e7eca83b8861562ae0a7a
5,108
css
CSS
UI/css/style.css
solomonfrank/PropertyPro-Lite
89df7e6aa725417c61065eeefdb4483beab71dcd
[ "MIT" ]
null
null
null
UI/css/style.css
solomonfrank/PropertyPro-Lite
89df7e6aa725417c61065eeefdb4483beab71dcd
[ "MIT" ]
4
2019-08-04T17:22:10.000Z
2021-05-07T22:56:29.000Z
UI/css/style.css
solomonfrank/PropertyPro-Lite
89df7e6aa725417c61065eeefdb4483beab71dcd
[ "MIT" ]
null
null
null
body { margin: 0; padding: 0; line-height: 1.5; background-color: white; overflow-x: hidden; } a { text-decoration: none; } .container { margin: auto; overflow: hidden; width: 80%; background-color: rgba(0, 0, 0, 0.4); width: 100vw; min-height: 300px; } ul { list-style-type: none; } header { background-color: #e8491d; width: 100vw; min-height: 70px; } .left-navbar { float: left; margin-left: 10px } .right-navbar { float: right; margin: 0; padding: 0; margin-right: 20px; } .left-navbar h3 { color: white; margin-left: 10px; } ul.navbar-link { list-style-type: none; padding: 0; display: none; } .navbar-link li { display: inline; padding: 0 10px 0 10px; } .navbar-link a { color: white; font-size: 19px; } .navbar-link a:hover { color: #e8491d; background-color: white; padding: 5px; } .icon{ margin-right:10px; } span.icon-bar { background-color: white; width: 46px; height: 5px; margin-bottom: 5px; position: relative; display: block; cursor: pointer; } .nav-container{ background-color:rgba(0, 0, 0, 0.7); color:white; display:none; padding:0; } .nav-list{ margin:0; } .navbar-list { padding-left:0; padding-top:0; padding-bottom:0; margin:0; } .navbar-list li{ padding:9px 0;; border:1px solid #e8491d; border-left:0; border-right:0; } .navbar-list a{ color:white; font-size:20px; margin-left:30px; font-weight: 400; line-height: 1.5; } .open{ display:block; } .navbar-list a:hover{ color: #e8491d; } section { background: url('../images/img1.jpg') no-repeat 0 -400px; min-height: 300px; } .search-wrapper { text-align: center; } .search-wrapper h3 { color: white; font-weight: 500; text-transform: uppercase; line-height: 1.8; } .purp-type { border: 1px solid rgba(143, 140, 140, 0.5); font-size: 19px; line-height: 1.5px; color: white; margin-left: 30px; padding: 3px 40px; } .search-title { margin-top: 50px; } .prop-type { margin-top: 50px; } .prop-search { margin-top: 20px; margin-left: 60px; } input[type="text"], #btn, select { height: 35px; border-radius: 3px; border: 0; padding-left: 10px; font-size: 15px; } .form-group { margin-top: 10px; } .form-group input[type="text"] { width: 80%; } .form-group select { width: 80%; } #btn { color: white; background-color: rgb(5, 116, 234); width: 80%; } .feature-wrap { width: 80%; margin: auto; overflow: hidden; } .feat-caption { text-align: center; } .prop-container { padding: 0; } .prop-img-wrapper { width: 100%; } .feat-caption h3 { text-transform: uppercase; color: #e8491d; } .prop-box { padding: 0; text-align: center; margin: 15px 10px; font-size: 18px; border: 1px solid rgba(0, 0, 0, 0.1); color: rgba(0, 0, 0, 0.8); text-transform: capitalize; } .prop-box img { width: 100%; height: 200px; } .link-wrap { padding: 20px 0; } .prop-box a { color: #e8491d; padding: 10px; border: 2px solid #e8491d; font-size: 19px; } .prop-box a:hover { background-color: #e8491d; color: white; } footer { text-align: center; background-color: rgb(92, 102, 112); margin-top: 10px; padding: 10px; font-size: 17px; line-height: 1.5; color: white; } .page-link{ padding:0; } .page-view{ float:right; padding:10px 0; } .page-view a:last-child{ margin-right:40px; } .page-view a{ background-color:rgb(5, 116, 234); color:white; padding: 5px 15px; border-radius:5px; margin:0; } @media screen and (min-width:768px) { .prop-search { margin-top: 20px; margin-left: auto; width: 80%; } .form-group { margin-top: 10px; float: left; margin: 10px 5px; } .form-group input[type="text"] { width: 100%; } .form-group select { width: 100%; } #btn { color: white; background-color: rgb(5, 116, 234); width: 100%; } .prop-box { float: left; width: 29%; } } @media screen and (min-width:990px) { ul.navbar-link { list-style-type: none; padding: 0; display: block; } .icon { display: none; } .nav-container{ display:none; } .prop-search { margin-top: 20px; margin-left: auto; width: 80%; } .form-group { margin-top: 10px; display: inline-block; } .form-group input[type="text"] { width: 100%; } .form-group select { width: 100%; } #btn { color: white; background-color: rgb(5, 116, 234); width: 100%; } .prop-box { float: left; width: 30%; } }
11.851508
61
0.542678
9f6ff887086cd2d1c8cdbfe0a8e02213ce8efc10
1,055
sql
SQL
DB/dml/workflow.sql
sandipnahak/QuickFabric
1010fb40235254c7a5e8d225e7d34d1abd6ec543
[ "Apache-2.0" ]
22
2020-03-10T20:55:26.000Z
2022-02-03T04:03:09.000Z
DB/dml/workflow.sql
sandipnahak/QuickFabric
1010fb40235254c7a5e8d225e7d34d1abd6ec543
[ "Apache-2.0" ]
13
2020-03-30T09:28:14.000Z
2021-10-06T05:53:40.000Z
DB/dml/workflow.sql
sandipnahak/QuickFabric
1010fb40235254c7a5e8d225e7d34d1abd6ec543
[ "Apache-2.0" ]
15
2020-03-30T09:12:22.000Z
2022-02-24T08:05:47.000Z
INSERT INTO `workflow` (`id`, `workflow_name`, `workflow_step`, `lookup_table`)VALUES (1,'CreateCluster','create_new_cluster','emr_cluster_metadata'), (2,'CreateCluster','cluster_bootstraps','cluster_step_request'), (3,'CreateCluster','cluster_custom_steps','cluster_step_request'), (4,'CreateCluster','health_check','emr_functional_testsuites_status'), (5,'RotateAMI-NonHA','terminate_current_cluster','emr_cluster_metadata'), (6,'RotateAMI-NonHA','create_new_cluster','emr_cluster_metadata'), (7,'RotateAMI-NonHA','cluster_bootstraps','cluster_step_request'), (8,'RotateAMI-NonHA','cluster_custom_steps','cluster_step_request'), (9,'RotateAMI-NonHA','health_check','emr_functional_testsuites_status'), (10,'RotateAMI-HA','create_new_cluster','emr_cluster_metadata'), (11,'RotateAMI-HA','cluster_bootstraps','cluster_step_request'), (12,'RotateAMI-HA','cluster_custom_steps','cluster_step_request'), (13,'RotateAMI-HA','health_check','emr_functional_testsuites_status'), (14,'RotateAMi-HA','mark_current_cluster_for_termination','emr_cluster_metadata');
70.333333
86
0.797156
181bf2b291175a111661f1eb96203d0d5419d6a9
2,284
rb
Ruby
spec/Enumerable_spec.rb
gcpmendez/prct11
51e323d811332daa3468bcccfdca26018bc618ec
[ "MIT" ]
null
null
null
spec/Enumerable_spec.rb
gcpmendez/prct11
51e323d811332daa3468bcccfdca26018bc618ec
[ "MIT" ]
null
null
null
spec/Enumerable_spec.rb
gcpmendez/prct11
51e323d811332daa3468bcccfdca26018bc618ec
[ "MIT" ]
null
null
null
# http://ruby-doc.org/core-2.2.3/Enumerable.html describe Enumerable do before :each do @ref1=["Programming Ruby 1.9 &2.0: The Pragmatic Programmers Guide","Pragmatic Bookshelf", 4,"07/07/2013",["978-1937785499","1937785491"], ["Dave Thomas","Andy Hunt","Chad Fowler"],"The Facets of Ruby"] @ref2=["Pro Git 2009th Edition","Apress", 2009,"27/08/2009",["978-1430218333","1430218339"], ["Scott Chacon"],"Pro"] @ref3=["The Ruby Programming Language","O’Reilly Media",1,"04/02/2008",["978-0596516178","0596516177"],["David Flanagan","Yukihiro Matsumoto"]] @ref4=["The RSpec Book: Behaviour Driven Development with RSpec, Cucumber, and Friends","Pragmatic Bookshelf", 1,"25/12/2010",["978-1934356371","1934356379"], ["David Chelimsky","Dave Astels","Bryan Helmkamp","Dan North","Zach Dennis","Aslak Hellesoy"],"The Facets of Ruby"] @ref5=["Git Pocket Guide","O’Reilly Media", 1,"02/08/2013",["978-1449325862","1449325866"], ["Richard E. Silverman"]] @ref6=["Los Fundamentos de Ruby","Internet","www.lpp.org","02/08/2013", ["Yo mismo"]] @list = LinkedList.new @list2 = LinkedList.new @list.insert_set([@ref1,@ref2,@ref3,@ref4,@ref5]) @list2.insert_set([@ref5,@ref6]) end it "Los elementos de la LinkedList pueden mostrarse enumerados por un each" do cadena = "" @list.each do |node| cadena= cadena + "#{node.to_s}," end expect(cadena).to be == "#{@ref1.to_s},#{@ref2.to_s},#{@ref3.to_s},#{@ref4.to_s},#{@ref5.to_s}," end it "Testeando el método count en una linkedlist" do expect(@list.count).to eq(5) end it "Testeando el max: El título mayor es 'The Ruby Programming Language'" do expect(@list.max[0]).to eq("The Ruby Programming Language") end it "Testeando el min: El título menosr es 'Git Pocket Guide'" do expect(@list.min[0]).to eq("Git Pocket Guide") end it "Testeando el all?: Todos los títulos tienen una longit mayor o igual a 3 caracteres" do expect(@list.all? { |word| word[0].length >= 3 }).to eq(true) end it "Testeando el drop: corta la LinkedList" do expect(@list.drop(2)[0][0]).to eq("The Ruby Programming Language") end end
53.116279
282
0.632224
9bebf9470ea2b216c78748bb6b3b873de58f46d5
612
js
JavaScript
ros/third_party/fast-rtps_x86_64/share/doc/fastrtps/api_reference/classeprosima_1_1fastrtps_1_1rtps_1_1_property_policy_helper.js
numberen/apollo-platform
8f359c8d00dd4a98f56ec2276c5663cb6c100e47
[ "Apache-2.0" ]
742
2017-07-05T02:49:36.000Z
2022-03-30T12:55:43.000Z
ros/third_party/fast-rtps_x86_64/share/doc/fastrtps/api_reference/classeprosima_1_1fastrtps_1_1rtps_1_1_property_policy_helper.js
numberen/apollo-platform
8f359c8d00dd4a98f56ec2276c5663cb6c100e47
[ "Apache-2.0" ]
73
2017-07-06T12:50:51.000Z
2022-03-07T08:07:07.000Z
ros/third_party/fast-rtps_x86_64/share/doc/fastrtps/api_reference/classeprosima_1_1fastrtps_1_1rtps_1_1_property_policy_helper.js
numberen/apollo-platform
8f359c8d00dd4a98f56ec2276c5663cb6c100e47
[ "Apache-2.0" ]
425
2017-07-04T22:03:29.000Z
2022-03-29T06:59:06.000Z
var classeprosima_1_1fastrtps_1_1rtps_1_1_property_policy_helper = [ [ "find_property", "classeprosima_1_1fastrtps_1_1rtps_1_1_property_policy_helper.html#a46cbf0e79fabdbef38d5887656dee204", null ], [ "find_property", "classeprosima_1_1fastrtps_1_1rtps_1_1_property_policy_helper.html#a033ab2801f69243e4d5c0149344a7bce", null ], [ "get_properties_with_prefix", "classeprosima_1_1fastrtps_1_1rtps_1_1_property_policy_helper.html#a3f79b1e01a7d64d30ee9b5f2b1bef3ab", null ], [ "length", "classeprosima_1_1fastrtps_1_1rtps_1_1_property_policy_helper.html#a36dcab7246ac2c9f5f3d9624dfa95137", null ] ];
87.428571
146
0.857843
fde31796e5cabcb4f949b9161903051e2d6855a3
681
lua
Lua
init.lua
aw/roomba-nodemcu
be12ea590241c7759a61e5b6000e738cae64f5c9
[ "MIT" ]
10
2017-07-31T08:31:46.000Z
2021-02-23T18:29:58.000Z
init.lua
aw/roomba-nodemcu
be12ea590241c7759a61e5b6000e738cae64f5c9
[ "MIT" ]
null
null
null
init.lua
aw/roomba-nodemcu
be12ea590241c7759a61e5b6000e738cae64f5c9
[ "MIT" ]
1
2017-10-22T14:10:36.000Z
2017-10-22T14:10:36.000Z
-- Roomba control library for NodeMCU / ESP8266 -- -- The MIT License (MIT) -- Copyright (c) 2017 Alexander Williams, Unscramble <license@unscramble.jp> -- Init uart.alt(0) -- timer to ensure we can kill the code if something is busted tmr.alarm(0, 5000, tmr.ALARM_SINGLE, function() dofile("roomba.lc") function drive_clockwise_example() roomba_write(OPCODES.start) -- start roomba_write(OPCODES.control) -- control roomba_write(OPCODES.drive, drive_bytes(200, DRIVE.clockwise)) -- spin end tmr.delay(3000000) gpio.write(0, gpio.LOW) -- orange led on drive_clockwise_example() tmr.delay(3000000) gpio.write(0, gpio.HIGH) -- orange led off end)
23.482759
76
0.718062
84af55739b9b5f5fb767ddb1beed085374194066
2,641
h
C
MMOCoreORB/src/templates/LootGroupTemplate.h
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/templates/LootGroupTemplate.h
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/templates/LootGroupTemplate.h
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* * LootGroupTemplate.h * * Created on: Jan 30, 2012 * Author: xyborn */ #ifndef LOOTGROUPTEMPLATE_H_ #define LOOTGROUPTEMPLATE_H_ #include "system/lang.h" #include "engine/lua/LuaObject.h" class LootGroupTemplate : public Object { String templateName; VectorMap<String, int> entryMap; public: LootGroupTemplate(const String& name) { templateName = name; entryMap.setNoDuplicateInsertPlan(); entryMap.setNullValue(0); } LootGroupTemplate(const LootGroupTemplate& lgt) : Object() { templateName = lgt.templateName; entryMap.setNoDuplicateInsertPlan(); entryMap.setNullValue(0); entryMap = lgt.entryMap; } LootGroupTemplate& operator=(const LootGroupTemplate& lgt) { if (this == &lgt) return *this; templateName = lgt.templateName; entryMap = lgt.entryMap; return *this; } String getLootGroupEntryForRoll(int roll) const { int totalChance = 0; for (int i = 0; i < entryMap.size(); ++i) { VectorMapEntry<String, int>* entry = &entryMap.elementAt(i); int weight = entry->getValue(); totalChance += weight; if (totalChance >= roll && weight > 0) return entry->getKey(); } //Should never get here unless the scripts didn't add up to 10000000. return ""; } int getLootGroupIntEntryForRoll(int roll) const { int totalChance = 0; for (int i = 0; i < entryMap.size(); ++i) { VectorMapEntry<String, int>* entry = &entryMap.elementAt(i); int weight = entry->getValue(); totalChance += weight; if (totalChance >= roll && weight > 0 ) return i; } //Should never get here unless the scripts didn't add up to 10000000. return -1; } int size() const { return entryMap.size(); } String getLootGroupEntryAt(int i) const { if( i < 0 ) return ""; if( i >= entryMap.size() ) return ""; VectorMapEntry<String, int>* entry = &entryMap.elementAt(i); return entry->getKey(); } void readObject(LuaObject* lua) { LuaObject lootItems = lua->getObjectField("lootItems"); if (!lootItems.isValidTable()) return; lua_State* L = lua->getLuaState(); for (int i = 1; i <= lootItems.getTableSize(); ++i) { lua_rawgeti(L, -1, i); LuaObject lootItem(L); String itemTemplate = lootItem.getStringField("itemTemplate"); String groupTemplate = lootItem.getStringField("groupTemplate"); int chance = lootItem.getIntField("weight"); if (itemTemplate.isEmpty()) entryMap.put(groupTemplate, chance); else entryMap.put(itemTemplate, chance); lootItem.pop(); } lootItems.pop(); } const String& getTemplateName() const { return templateName; } }; #endif /* LOOTGROUPTEMPLATE_H_ */
20.632813
71
0.676638
fed130c87cee81d42b644536e6687e694402b1e7
3,435
html
HTML
com/radityalabs/Python/origin/movie/17353.html
radityagumay/BenchmarkSentimentAnalysis_2
e509a4e749271da701ce9da1d9f16cdd78dcdf40
[ "Apache-2.0" ]
3
2017-06-08T01:17:55.000Z
2019-06-02T10:52:36.000Z
com/radityalabs/Python/origin/movie/17353.html
radityagumay/BenchmarkSentimentAnalysis_2
e509a4e749271da701ce9da1d9f16cdd78dcdf40
[ "Apache-2.0" ]
null
null
null
com/radityalabs/Python/origin/movie/17353.html
radityagumay/BenchmarkSentimentAnalysis_2
e509a4e749271da701ce9da1d9f16cdd78dcdf40
[ "Apache-2.0" ]
null
null
null
<HTML><HEAD> <TITLE>Review for Naked Souls (1995)</TITLE> <LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css"> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0113926">Naked Souls (1995)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Justin+Felix">Justin Felix</A></H3><HR WIDTH="40%" SIZE="4"> <P>NAKED SOULS (1995) A film review by Justin Felix. Copyright 1999 Justin Felix. Any comments about this review? Contact me at <A HREF="mailto:justinfelix@yahoo.com">justinfelix@yahoo.com</A> All of my film reviews are archived at <A HREF="http://us.imdb.com/M/reviews_by?Justin+Felix">http://us.imdb.com/M/reviews_by?Justin+Felix</A> </P> <PRE>Rating: * (out of five) </PRE> <P>Written by Frank Dietz. Directed by Lyndon Chubbuck. Starring Pamela Anderson, David Warner, and Dean Stockwell. Rated R (contains nudity, sexuality, profanity, and violence) 85 mins. </P> <P>Synopsis: Big-breasted and dim-witted sculptress Britt gets really mad at her grad student boyfriend because he spends too much time on his thought-transference experiments instead of her art showings. Elderly, evil scientist Everett Longstreet switches minds with Britt's boy, in the meantime, and goes completely mental. </P> <P>Comments: NAKED SOULS opens with a naked woman, and the movie makes no illusion that it's a sci-fi vehicle designed to show Pamela Anderson's, um, talents. If you are really interested in seeing Anderson's talents, however, I suggest you skip over this dud and watch the infamous Pam and Tommy Lee honeymoon sex tape, now available on home video. At least with that "movie," you don't have to go through the painful experience of watching Pamela try to pronounce multiple syllable words like "eclectic." </P> <P>A premise does exist in the movie. Basically, while Anderson wears skimpy clothes which barely contain her talents, she practices her art -- brilliantly slapping plaster of Paris on naked women. Her boyfriend, meanwhile, spends 20 hours a day in a morgue trying to view the memories of dead prison inmates because this will "make a difference to humanity." Whatever. The movie fails to explain how these two hooked up. Be grateful. After we meet the evil Everett Longstreet, lots of technobabble and mystical mumbo-jumbo get tossed about, Pammy has sex replete with cheesy make-out music, and minds get transferred. Never fear, though, Pammy uses her sharp mental abilities (ahem) to save her boyfriend in the end. Unfortunately, no one saves the movie. Avoid this would-be sci-fi thriller, unless you're in for a good laugh or two. </P> <HR><P CLASS=flush><SMALL>The review above was posted to the <A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR> The Internet Movie Database accepts no responsibility for the contents of the review and has no editorial control. Unless stated otherwise, the copyright belongs to the author.<BR> Please direct comments/criticisms of the review to relevant newsgroups.<BR> Broken URLs inthe reviews are the responsibility of the author.<BR> The formatting of the review is likely to differ from the original due to ASCII to HTML conversion. </SMALL></P> <P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P> </P></BODY></HTML>
60.263158
197
0.761572
46da271dad3cf99f742429b80382d2210d6c748d
527
css
CSS
src/components/layout/index.module.css
wilfriedbarth/wb-blog
2419cd43d3b12817a02bd4335a8084e5db6302e4
[ "MIT" ]
null
null
null
src/components/layout/index.module.css
wilfriedbarth/wb-blog
2419cd43d3b12817a02bd4335a8084e5db6302e4
[ "MIT" ]
16
2020-11-06T03:50:18.000Z
2021-08-25T04:47:04.000Z
src/components/layout/index.module.css
wilfriedbarth/wb-blog
2419cd43d3b12817a02bd4335a8084e5db6302e4
[ "MIT" ]
null
null
null
.container { display: flex; flex-direction: column; margin: 0 auto; min-height: 100vh; padding: 15px; } /* Mobile */ @media screen and (min-width: 576px) { .container { width: 576px; } } /* Tablet */ @media screen and (min-width: 768px) { .container { width: 768px; } } /* Laptop */ @media screen and (min-width: 992px) { .container { width: 992px; } } /* Desktop */ @media screen and (min-width: 1200px) { .container { width: 992px; } } .content { flex: 1; margin: 25px 0; }
12.853659
39
0.58444
9bacf5b5103d09ac638465c5c51d187de5b97b00
3,403
js
JavaScript
server/client/src/components/Landing/Register.js
pectom/Kid-Tracker-For-Parents
d4da70547b2077087aa4594858b753810cd731ef
[ "BSD-2-Clause" ]
null
null
null
server/client/src/components/Landing/Register.js
pectom/Kid-Tracker-For-Parents
d4da70547b2077087aa4594858b753810cd731ef
[ "BSD-2-Clause" ]
null
null
null
server/client/src/components/Landing/Register.js
pectom/Kid-Tracker-For-Parents
d4da70547b2077087aa4594858b753810cd731ef
[ "BSD-2-Clause" ]
null
null
null
import React from 'react'; import RegisterField from './RegisterField'; import { connect } from 'react-redux'; import { reduxForm, Field } from 'redux-form'; import validEmail from './validEmail'; import * as actions from '../../actions'; class Register extends React.Component { async myRegisterUser(values) { await this.props.registerUser(values); } renderMessage() { if(this.props.submitSucceeded){ return ( <div className="ui success message visible"> <div className="header"> Zostałeś zarejestrowany </div> </div> ); } } render() { return ( <div> <div className="ui segment"> <form className="ui form" onSubmit={this.props.handleSubmit(values => console.log('Rejestrujemy'))} > <div className="field"> <div className="two fields"> <Field id="register-name" component={RegisterField} type="text" label="Imię" name="firstName" /> <Field id="register-surname" component={RegisterField} type="text" label="Nazwisko" name="lastName" /> </div> </div> <Field id="register-email" component={RegisterField} type="text" label="Email" name="email" /> <div className="field"> <div className="two fields"> <Field id="register-password" component={RegisterField} type="password" label="Hasło" name="password" /> <Field id="register-password2" component={RegisterField} type="password" label="Powtórz hasło" name="passwordTwo" /> </div> </div> {this.renderMessage()} <button id="register-button" className="ui button primary" type="submit" onClick={() => this.myRegisterUser(this.props.formValues)} > Zarejestruj </button> </form> </div> </div> ); } } function validate(values) { const errors = {}; if (!values.firstname) { errors.firstname = "Wpisz imię"; } if (!values.lastname) { errors.lastname = "Wpisz nazwisko"; } if (!values.email) { errors.email = "Wpisz email"; } if (!validEmail(values.email)) { errors.email = "Email niepoprawny"; } if (!values.password) { errors.password = "Wpisz hasło"; } if (!values.passwordTwo) { errors.passwordTwo = "Potwierdź hasło"; } if(values.password !== values.passwordTwo) { errors.passwordTwo = "Hasła nie są identyczne"; } return errors; } function mapStateToProps({ form }) { return { formValues: form.registerForm.values, }; } export default reduxForm({ validate, form: 'registerForm' })(connect(mapStateToProps, actions)(Register));
35.082474
149
0.481928
f5c0fb7dfb9aef0583644045a861670f6d8d5b38
203
sql
SQL
src/main/java/com/xresch/cfw/features/api/resources/sql_getPermissionMapForTokenID.sql
xresch/CoreFramework
b41c98e79d20991f313c64f43b6a21b53acc8cf8
[ "MIT", "BSD-2-Clause", "CC0-1.0", "Apache-2.0" ]
1
2020-11-20T10:10:33.000Z
2020-11-20T10:10:33.000Z
src/main/java/com/xresch/cfw/features/api/resources/sql_getPermissionMapForTokenID.sql
xresch/CoreFramework
b41c98e79d20991f313c64f43b6a21b53acc8cf8
[ "MIT", "BSD-2-Clause", "CC0-1.0", "Apache-2.0" ]
7
2020-08-26T08:14:40.000Z
2022-02-24T18:03:45.000Z
src/main/java/com/xresch/cfw/features/api/resources/sql_getPermissionMapForTokenID.sql
xresch/CoreFramework
b41c98e79d20991f313c64f43b6a21b53acc8cf8
[ "MIT", "BSD-2-Clause", "CC0-1.0", "Apache-2.0" ]
null
null
null
SELECT P.PK_ID, P.ACTION_NAME, P.API_NAME, GP.FK_ID_TOKEN AS TOKEN_ID FROM CFW_APITOKEN_PERMISSION P LEFT JOIN CFW_APITOKEN_PERMISSION_MAP AS GP ON GP.FK_ID_PERMISSION = P.PK_ID AND GP.FK_ID_TOKEN = ?;
33.833333
69
0.812808
c3b51d2df8ab8d471770c5df8c13fe69b3109d0f
4,872
rs
Rust
src/lib.rs
DigitalZebra/palette-extract-rs
1f79b8125ef61d0171ccddedd55716200c2c1763
[ "MIT" ]
null
null
null
src/lib.rs
DigitalZebra/palette-extract-rs
1f79b8125ef61d0171ccddedd55716200c2c1763
[ "MIT" ]
null
null
null
src/lib.rs
DigitalZebra/palette-extract-rs
1f79b8125ef61d0171ccddedd55716200c2c1763
[ "MIT" ]
null
null
null
#![warn(missing_docs)] //! A lib crate for extracting a color palette from an image represented as a `u8` slice. //! //! Supports `RGB` and `RGBA`. //! //! # Examples //! See `examples` directory in code repo for a full set of functioning examples! //! //! ## Basic //! ``` //! use palette_extract::get_palette_rgb; //! let pixels: [u8; 12] = [255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0]; //! //! let palette = get_palette_rgb(&pixels); //! ``` //! //! ## With options //! //! ``` //! use palette_extract::{get_palette_with_options, Quality, MaxColors, PixelEncoding, PixelFilter}; //! //! let pixels: [u8; 12] = [255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0]; //! //! let color_palette = get_palette_with_options(&pixels, //! PixelEncoding::Rgb, //! Quality::new(1), //! MaxColors::new(4), //! PixelFilter::White); //! //! ``` mod mmcq_impl; use mmcq_impl::extract_colors; pub use mmcq_impl::{Color, PixelEncoding}; /// Represents the quality level used to extract the color palette. Defaults to 5. pub struct Quality(u8); impl Quality { /// Creates a new Quality struct. /// /// # Examples /// /// ``` /// use palette_extract::Quality; /// /// Quality::new(1); /// ``` pub fn new(quality: u8) -> Quality { Quality(quality) } } impl Default for Quality { fn default() -> Self { Quality(5) } } /// Represents the max number of colors to extract from the image. Defaults to 10. pub struct MaxColors(u8); impl MaxColors { /// Creates a new ['MaxColors'](self::MaxColors) struct. /// /// # Examples /// /// ``` /// use palette_extract::MaxColors; /// /// MaxColors::new(5); /// ``` pub fn new(max_colors: u8) -> MaxColors { MaxColors(max_colors) } } impl Default for MaxColors { fn default() -> Self { MaxColors(10) } } /// Represents a filter that can be applied to algorithm to filter out particular pixels. #[derive(Eq, PartialEq)] pub enum PixelFilter { /// Represents no filter. I.E. all colors/pixels will be considered. None, /// Represents a white pixel filter. All white pixels will be discarded for the purpose of extracting the palette from the image. White, } impl Default for PixelFilter { fn default() -> Self { PixelFilter::White } } /// Extracts a color palette from a slice of RGB color bytes represented with `u8`. Allows setting of various options. /// /// # Arguments /// - `pixels` - `u8` slice of pixels to extract the palette from. /// - `encoding` - How the pixels are represented in `pixels` slice. RGB or RGBA are most common, depending on source image. /// - `quality` - The number of pixels to consider when extracting the palette. A higher number will run quicker, but may be less accurate. /// - `max_colors` - The max number of colors to extract from the image. /// - `pixel_filter` - A filter applied to the pixels to exclude from considering. This can be useful if, for example, the subject of the image has a single color background (e.g. white) that shouldn't be considered in the palette. /// /// # Examples /// ``` /// use palette_extract::{get_palette_with_options, Quality, MaxColors, PixelEncoding, PixelFilter}; /// /// let pixels: [u8; 12] = [255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0]; /// /// let color_palette = get_palette_with_options(&pixels, /// PixelEncoding::Rgb, /// Quality::new(1), /// MaxColors::new(4), /// PixelFilter::White); /// /// ``` /// /// # Panics /// Panics if we are unable to perform an iteration of the algorithm. /// pub fn get_palette_with_options( pixels: &[u8], encoding: PixelEncoding, quality: Quality, max_colors: MaxColors, pixel_filter: PixelFilter, ) -> Vec<Color> { let result = extract_colors( pixels, encoding, quality.0, max_colors.0, pixel_filter == PixelFilter::White, ); result } /// Extracts a color palette from a slice of RGB color bytes represented with `u8`. Uses ['Quality'](Quality) of 5, ['MaxColors'](MaxColors) of 10, and ['PixelFilter::None'](PixelFilter::None). /// /// Uses default options. See ['get_palette_with_options'](get_palette_with_options) to extract a color palette with /// /// # Arguments /// - `pixels` - `u8` slice of pixels to extract the palette from. /// /// # Examples /// /// ``` /// use palette_extract::get_palette_rgb; /// let pixels: [u8; 12] = [255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0]; /// /// let palette = get_palette_rgb(&pixels); /// ``` /// # Panics /// Panics if we are unable to perform an iteration of the algorithm. /// pub fn get_palette_rgb(pixels: &[u8]) -> Vec<Color> { get_palette_with_options( pixels, PixelEncoding::Rgb, Quality::default(), MaxColors::default(), PixelFilter::None, ) }
28.325581
231
0.627258
31f7df3c45cb953b62bfa81480e47907ab025b38
953
asm
Assembly
programs/oeis/017/A017115.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/017/A017115.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/017/A017115.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A017115: a(n) = (8*n + 4)^3. ; 64,1728,8000,21952,46656,85184,140608,216000,314432,438976,592704,778688,1000000,1259712,1560896,1906624,2299968,2744000,3241792,3796416,4410944,5088448,5832000,6644672,7529536,8489664,9528128,10648000,11852352,13144256,14526784,16003008,17576000,19248832,21024576,22906304,24897088,27000000,29218112,31554496,34012224,36594368,39304000,42144192,45118016,48228544,51478848,54872000,58411072,62099136,65939264,69934528,74088000,78402752,82881856,87528384,92345408,97336000,102503232,107850176,113379904,119095488,125000000,131096512,137388096,143877824,150568768,157464000,164566592,171879616,179406144,187149248,195112000,203297472,211708736,220348864,229220928,238328000,247673152,257259456,267089984,277167808,287496000,298077632,308915776,320013504,331373888,343000000,354894912,367061696,379503424,392223168,405224000,418508992,432081216,445943744,460099648,474552000,489303872,504358336 mul $0,8 add $0,4 pow $0,3
136.142857
893
0.860441
f00d8a2ff37a2b007fa4edfda74f6d8657793532
3,684
py
Python
piton/lib/inquirer/questions.py
piton-package-manager/PPM
19015b76184befe1e2daa63189a13b039787868d
[ "MIT" ]
19
2016-04-08T04:00:07.000Z
2021-11-12T19:36:56.000Z
piton/lib/inquirer/questions.py
LookLikeAPro/PPM
19015b76184befe1e2daa63189a13b039787868d
[ "MIT" ]
9
2017-01-03T13:39:47.000Z
2022-01-15T20:38:20.000Z
piton/lib/inquirer/questions.py
LookLikeAPro/PPM
19015b76184befe1e2daa63189a13b039787868d
[ "MIT" ]
6
2017-04-01T03:38:45.000Z
2021-05-06T11:25:31.000Z
# -*- coding: utf-8 -*- """ Module that implements the questions types """ import json from . import errors def question_factory(kind, *args, **kwargs): for clazz in (Text, Password, Confirm, List, Checkbox): if clazz.kind == kind: return clazz(*args, **kwargs) raise errors.UnknownQuestionTypeError() def load_from_dict(question_dict): """ Load one question from a dict. It requires the keys 'name' and 'kind'. :return: The Question object with associated data. :return type: Question """ return question_factory(**question_dict) def load_from_list(question_list): """ Load a list of questions from a list of dicts. It requires the keys 'name' and 'kind' for each dict. :return: A list of Question objects with associated data. :return type: List """ return [load_from_dict(q) for q in question_list] def load_from_json(question_json): """ Load Questions from a JSON string. :return: A list of Question objects with associated data if the JSON contains a list or a Question if the JSON contains a dict. :return type: List or Dict """ data = json.loads(question_json) if isinstance(data, list): return load_from_list(data) if isinstance(data, dict): return load_from_dict(data) raise TypeError( 'Json contained a %s variable when a dict or list was expected', type(data)) class TaggedValue(object): def __init__(self, label, value): self.label = label self.value = value def __str__(self): return self.label def __repr__(self): return self.value def __cmp__(self, other): if isinstance(other, TaggedValue): return self.value != other.value return self.value != other class Question(object): kind = 'base question' def __init__(self, name, message='', choices=None, default=None, ignore=False, validate=True): self.name = name self._message = message self._choices = choices or [] self._default = default self._ignore = ignore self._validate = validate self.answers = {} @property def ignore(self): return bool(self._solve(self._ignore)) @property def message(self): return self._solve(self._message) @property def default(self): return self._solve(self._default) @property def choices_generator(self): for choice in self._solve(self._choices): yield ( TaggedValue(*choice) if isinstance(choice, tuple) and len(choice) == 2 else choice ) @property def choices(self): return list(self.choices_generator) def validate(self, current): try: if self._solve(self._validate, current): return except Exception: pass raise errors.ValidationError(current) def _solve(self, prop, *args, **kwargs): if callable(prop): return prop(self.answers, *args, **kwargs) if isinstance(prop, str): return prop.format(**self.answers) return prop class Text(Question): kind = 'text' class Password(Question): kind = 'password' class Confirm(Question): kind = 'confirm' def __init__(self, name, default=False, **kwargs): super(Confirm, self).__init__(name, default=default, **kwargs) class List(Question): kind = 'list' class Checkbox(Question): kind = 'checkbox'
24.236842
72
0.604777
650b61eb839964413b4047a7102a2ba07a9d68e0
1,518
py
Python
jake/test/test_audit.py
lvcarlosja/jake
0ecbcdd89352d27f50e35d1d73b624b86456e568
[ "Apache-2.0" ]
null
null
null
jake/test/test_audit.py
lvcarlosja/jake
0ecbcdd89352d27f50e35d1d73b624b86456e568
[ "Apache-2.0" ]
4
2021-07-29T18:51:06.000Z
2021-12-13T20:50:20.000Z
jake/test/test_audit.py
lvcarlosja/jake
0ecbcdd89352d27f50e35d1d73b624b86456e568
[ "Apache-2.0" ]
null
null
null
# # Copyright 2019-Present Sonatype Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ test_audit.py , for all your testing of audit py needs """ import unittest import json from pathlib import Path from ..audit.audit import Audit from ..types.results_decoder import ResultsDecoder class TestAudit(unittest.TestCase): """ TestAudit is responsible for testing the Audit class """ def setUp(self): self.func = Audit() def test_call_audit_results_prints_output(self): """ test_call_audit_results_prints_output ensures that when called with a valid result, audit_results returns the number of vulnerabilities found """ filename = Path(__file__).parent / "ossindexresponse.txt" with open(filename, "r") as stdin: response = json.loads( stdin.read(), cls=ResultsDecoder) self.assertEqual(self.func.audit_results(response), self.expected_results()) @staticmethod def expected_results(): """ Weeee, I'm helping! """ return 3
33
81
0.725296
4a40f17d330460d3c3b290eb627c7d22b14fa222
911
js
JavaScript
src/reducer/chatroomModel.js
chumakovvchuma/bridge-game
38edee8ed005ba792627c0a142ed9e7ab4acb63b
[ "MIT" ]
1
2018-11-05T17:19:15.000Z
2018-11-05T17:19:15.000Z
src/reducer/chatroomModel.js
chumakovvchuma/bridge-game
38edee8ed005ba792627c0a142ed9e7ab4acb63b
[ "MIT" ]
6
2020-07-12T02:29:57.000Z
2020-07-12T02:29:58.000Z
src/reducer/chatroomModel.js
chumakovvchuma/bridge-game
38edee8ed005ba792627c0a142ed9e7ab4acb63b
[ "MIT" ]
8
2018-11-05T01:08:33.000Z
2021-12-17T21:56:08.000Z
import Database from "../firebase"; import {dispatch} from "../reducer"; /* * A chatroom class to handle the communcation with database * @param linkId, string, a unique path name for a table, is generate from a timeStamp * @param id, string, a unique key of a table, is generate by firebase when push a new node */ export default class ChatroomModel { constructor(linkId, id) { this.linkId = linkId; this.id = id; this.get(); } // get data get() { Database.getChatRoomById(this.id).then(chatroom => { this.update(chatroom, this.id); this.listenChanged(); }); } // update data update(chatroom, id) { dispatch("UPDATE_CHAT_ROOM", { chatroom: chatroom, id: id }); } // register data change event listenChanged() { Database.getNodeByPath(`chatroom/${this.id}/`, snapshot => this.update(snapshot.val(), this.id) ); } }
23.973684
91
0.637761
b2e290a686a1065fd69b5d2e7d362f288caf266f
117
py
Python
Module01/OOP/FirstClassDef.py
fenglihanxiao/Python
872baf3a3a5ee42740161152605ca2b1ddf4cd30
[ "MIT" ]
null
null
null
Module01/OOP/FirstClassDef.py
fenglihanxiao/Python
872baf3a3a5ee42740161152605ca2b1ddf4cd30
[ "MIT" ]
null
null
null
Module01/OOP/FirstClassDef.py
fenglihanxiao/Python
872baf3a3a5ee42740161152605ca2b1ddf4cd30
[ "MIT" ]
null
null
null
""" First class definition""" class Cat: pass class RaceCar: pass cat1 = Cat() cat2 = Cat() cat3 = Cat()
9
29
0.589744
040a0f01eaa0fa8fca299c51d7662d802c5bcf55
1,092
js
JavaScript
src/js/section-feedback.js
dof-dss/nicsdru-nidirect-theme
f64d449955533235e73b2d85f756eed761fad6e0
[ "MIT" ]
1
2020-11-12T09:19:44.000Z
2020-11-12T09:19:44.000Z
src/js/section-feedback.js
dof-dss/nicsdru-nidirect-theme
f64d449955533235e73b2d85f756eed761fad6e0
[ "MIT" ]
41
2019-08-28T14:36:28.000Z
2022-01-17T11:54:25.000Z
src/js/section-feedback.js
dof-dss/nicsdru-nidirect-theme
f64d449955533235e73b2d85f756eed761fad6e0
[ "MIT" ]
2
2019-07-26T08:20:23.000Z
2021-08-06T14:07:16.000Z
/** * @file * Provides a script to handle the page feedback form section at the bottom of all pages. * */ /* eslint-disable */ (function ($, Drupal) { Drupal.behaviors.nicsdruSectionFeedback = { attach: function attach (context) { $('#section-feedback', context).once('nicsdruSectionFeedback').each(function() { var $feedback_heading = $('#section-feedback__heading'); var $feedback_form = $('#section-feedback__form'); var $btn = $('<button></button>'); $btn .attr('id', 'section-feedback__toggle') .addClass('section-feedback__toggle') .attr('aria-controls', 'section-feedback__form') .attr('aria-expanded', 'false') .click(function() { var $target = $feedback_form; var expanded = $(this).attr('aria-expanded') === 'true' || false; $(this).attr('aria-expanded', !expanded); $target.toggleClass('expanded', !$target.hasClass('expanded')); }); $feedback_heading.wrapInner($btn); }); } }; })(jQuery, Drupal);
29.513514
89
0.580586
56194e653a6410be882e918c4d0572fa56d2db57
446
asm
Assembly
libsrc/stdio/nascom/fputc_cons.asm
andydansby/z88dk-mk2
51c15f1387293809c496f5eaf7b196f8a0e9b66b
[ "ClArtistic" ]
1
2020-09-15T08:35:49.000Z
2020-09-15T08:35:49.000Z
libsrc/stdio/nascom/fputc_cons.asm
dex4er/deb-z88dk
9ee4f23444fa6f6043462332a1bff7ae20a8504b
[ "ClArtistic" ]
null
null
null
libsrc/stdio/nascom/fputc_cons.asm
dex4er/deb-z88dk
9ee4f23444fa6f6043462332a1bff7ae20a8504b
[ "ClArtistic" ]
null
null
null
; ; ROM Console routine for the NASCOM1/2 ; By Stefano Bodrato - 19/6/2003 ; ; $Id: fputc_cons.asm,v 1.1 2003/06/27 14:04:13 stefano Exp $ ; XLIB fputc_cons LIB montest .fputc_cons ld hl,2 add hl,sp ld a,(hl) push af call montest jr nz,nassys ; T monitor pop af cp 12 jr nz,notcls ld a,1eh .notcls cp 13 jr nz,notcr ld a,1fh .notcr jp c4ah .nassys ; NASSYS monitor pop af cp 12 jr nz,nocls ld a,0ch .nocls defb f7h ret
11.15
61
0.674888
520a0bfa2e2c02676722ad963ab2b23388fc08e3
370
kt
Kotlin
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/coordination/v1/spec.kt
trietsch/k8s-kotlin-dsl
3fff8b25f9aff8aa6076f06e5a2e99b13e3655e0
[ "MIT" ]
302
2017-03-19T21:27:57.000Z
2022-03-31T09:51:05.000Z
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/coordination/v1/spec.kt
trietsch/k8s-kotlin-dsl
3fff8b25f9aff8aa6076f06e5a2e99b13e3655e0
[ "MIT" ]
24
2017-08-28T17:47:00.000Z
2022-01-07T20:20:46.000Z
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/coordination/v1/spec.kt
trietsch/k8s-kotlin-dsl
3fff8b25f9aff8aa6076f06e5a2e99b13e3655e0
[ "MIT" ]
23
2017-03-20T00:44:49.000Z
2022-01-04T10:46:46.000Z
// GENERATED package com.fkorotkov.kubernetes.coordination.v1 import io.fabric8.kubernetes.api.model.coordination.v1.Lease as v1_Lease import io.fabric8.kubernetes.api.model.coordination.v1.LeaseSpec as v1_LeaseSpec fun v1_Lease.`spec`(block: v1_LeaseSpec.() -> Unit = {}) { if(this.`spec` == null) { this.`spec` = v1_LeaseSpec() } this.`spec`.block() }
23.125
80
0.721622
df0cf7fe3c5f6929b5ba6f9b340dcbd97a42a66d
174
kt
Kotlin
src/main/kotlin/io/github/jokoroukwu/zephyrng/http/testcycleupdate/UpdateTestCycleTestResult.kt
jokoroukwu/zephyrng
f06485240153d5c6b6da9ae60208f771698cfa40
[ "Apache-2.0" ]
2
2021-08-02T07:10:35.000Z
2021-08-14T07:37:44.000Z
src/main/kotlin/io/github/jokoroukwu/zephyrng/http/testcycleupdate/UpdateTestCycleTestResult.kt
jokoroukwu/zephyrng
f06485240153d5c6b6da9ae60208f771698cfa40
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/io/github/jokoroukwu/zephyrng/http/testcycleupdate/UpdateTestCycleTestResult.kt
jokoroukwu/zephyrng
f06485240153d5c6b6da9ae60208f771698cfa40
[ "Apache-2.0" ]
null
null
null
package io.github.jokoroukwu.zephyrng.http.testcycleupdate import kotlinx.serialization.Serializable @Serializable class UpdateTestCycleTestResult(val testCaseId: Long) { }
24.857143
58
0.856322
547b92ccf00ad69100276753c26a67c062f86746
2,634
swift
Swift
SwiftBluetooth/Classes/Operations/Write/WriteOperation.swift
CatchZeng/SwiftBluetooth
6b5ae0032ceb8306d6712d89acddd9aee79b672e
[ "MIT" ]
3
2018-02-27T08:59:02.000Z
2018-07-18T07:21:55.000Z
SwiftBluetooth/Classes/Operations/Write/WriteOperation.swift
CatchZeng/SwiftBluetooth
6b5ae0032ceb8306d6712d89acddd9aee79b672e
[ "MIT" ]
null
null
null
SwiftBluetooth/Classes/Operations/Write/WriteOperation.swift
CatchZeng/SwiftBluetooth
6b5ae0032ceb8306d6712d89acddd9aee79b672e
[ "MIT" ]
null
null
null
// // WriteOperation.swift // SwiftBluetooth // // Created by CatchZeng on 2017/9/5. // Copyright © 2017年 CatchZeng. All rights reserved. // import UIKit import CoreBluetooth open class WriteOperation: BLEOperation { // Maximum 20 bytes in a single ble package private static let notifyMTU = 20 private var peripheral: BLEPeripheral private var data: Data private var characteristic: CBCharacteristic private var type: CBCharacteristicWriteType private var callback: ((Result<(Data)>) -> Void)? public init(peripheral: BLEPeripheral, data: Data, characteristic: CBCharacteristic, type: CBCharacteristicWriteType, callback: ((Result<(Data)>) -> Void)?) { self.peripheral = peripheral self.data = data self.characteristic = characteristic self.type = type self.callback = callback } // MARK: BLEOperation public override func start() { if peripheral.peripheral.state != .connected { printLog("bluetooth is disconnected.") return } super.start() writeValue() if type == .withoutResponse { success() } } @discardableResult public override func process(event: Event) -> Any? { if type == .withoutResponse { return nil } if case .didWriteCharacteristic(let characteristic) = event { if characteristic.uuid == self.characteristic.uuid { success() } } return nil } public override func cancel() { super.cancel() callback?(.cancelled) callback = nil } public override func fail(_ error: Error?) { super.fail(error) callback?(.failure(error: error)) callback = nil } public override func success() { super.success() callback?(.success(data)) callback = nil } // MARK: Private Methods private func writeValue() { var sendIndex = 0 while true { var amountToSend = data.count - sendIndex if amountToSend > WriteOperation.notifyMTU { amountToSend = WriteOperation.notifyMTU } if amountToSend <= 0 { return } let dataChunk = data.subdata(in: sendIndex..<sendIndex+amountToSend) printLog("didSend: \(dataChunk.hexString)") peripheral.peripheral.writeValue(dataChunk, for: characteristic, type: type) sendIndex += amountToSend } } }
26.34
162
0.582384
546c3542cc1ed68e40274094ec32ef1430900dfe
2,195
go
Go
series/interface.go
BearerPipelineTest/lindb
c81e59d8e7a8e3cef22157cdec524ee4aa5892fa
[ "Apache-2.0" ]
714
2019-06-13T02:32:32.000Z
2019-08-02T03:12:30.000Z
series/interface.go
BearerPipelineTest/lindb
c81e59d8e7a8e3cef22157cdec524ee4aa5892fa
[ "Apache-2.0" ]
64
2019-06-14T03:37:26.000Z
2019-08-01T01:45:02.000Z
series/interface.go
BearerPipelineTest/lindb
c81e59d8e7a8e3cef22157cdec524ee4aa5892fa
[ "Apache-2.0" ]
74
2019-06-13T05:46:58.000Z
2019-08-01T05:32:13.000Z
// Licensed to LinDB under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. LinDB licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package series import ( "github.com/lindb/roaring" "github.com/lindb/lindb/series/tag" ) //go:generate mockgen -source ./interface.go -destination=./interface_mock.go -package=series // MetricMetaSuggester represents to suggest ability for metricNames and tagKeys. // default max limit of suggestions is set in constants type MetricMetaSuggester interface { // SuggestMetrics returns suggestions from a given prefix of metricName SuggestMetrics(namespace, metricPrefix string, limit int) ([]string, error) } // TagValueSuggester represents to suggest ability for tagValues. // default max limit of suggestions is set in constants type TagValueSuggester interface { // SuggestTagValues returns suggestions from given tag key id and prefix of tagValue SuggestTagValues(tagKeyID tag.KeyID, tagValuePrefix string, limit int) []string } // Filter represents the query ability for filtering seriesIDs by expr from an index of tags. type Filter interface { // GetSeriesIDsByTagValueIDs gets series ids by tag value ids for spec tag key of metric GetSeriesIDsByTagValueIDs(tagKeyID tag.KeyID, tagValueIDs *roaring.Bitmap) (*roaring.Bitmap, error) // GetSeriesIDsForTag gets series ids for spec tag key of metric GetSeriesIDsForTag(tagKeyID tag.KeyID) (*roaring.Bitmap, error) // GetSeriesIDsForMetric gets series ids for spec metric name GetSeriesIDsForMetric(namespace, metricName string) (*roaring.Bitmap, error) }
43.039216
100
0.784055
71576fdf6e4a482279521e3c89a2ec534472d331
4,294
lua
Lua
scene4.lua
M0Rf30/trosh
61862b65111c12b71cb95ab335a2a7a398372192
[ "WTFPL" ]
1
2016-12-08T20:51:22.000Z
2016-12-08T20:51:22.000Z
scene4.lua
M0Rf30/trosh
61862b65111c12b71cb95ab335a2a7a398372192
[ "WTFPL" ]
null
null
null
scene4.lua
M0Rf30/trosh
61862b65111c12b71cb95ab335a2a7a398372192
[ "WTFPL" ]
null
null
null
function scene4_load() backgroundwhite = 0 staralpha = 1 asteroids = {} bullets = {} love.audio.play(bgmusic) starttimer = 0 alerttimer = 0 flyingquad = 3 pspeedx = 0 pspeedy = 0 playerx = nil flyanimationtimer = 0 end function scene4_update(dt) if secondtimer then secondtimer = secondtimer + dt end for i, v in pairs(stars) do v:update(dt) end --EXPLOSION local delete = {} for i, v in pairs(explosions) do if v:update(dt) == true then table.insert(delete, i) end end table.sort(delete, function(a,b) return a>b end) for i, v in pairs(delete) do table.remove(explosions, v) --remove end if rockets[1] then rockets[1]:update(dt) end if (starttimer > 0 and starttimer < 3) or alerttimer > 0.1 then alerttimer = math.fmod(alerttimer + dt*7, math.pi*2) end if jumped then if rockets[1] then rockets[1].x = rockets[1].x - dt*3 end if rockets[1] and secondtimer > 2 and secondtimer - dt <= 2 then for i = 1, 20 do if explosions then table.insert(explosions, explosion:new(rockets[1].x-16+math.random(16)-8, rockets[1].y-20+math.random(16)-8)) end end starmover = math.pi rockets[1] = nil end playerx = playerx + pspeedx*dt playery = playery + pspeedy*dt if pspeedx > 0 then pspeedx = pspeedx - dt*5 end if playery >= 20 then playery = 20 pspeedy = 0 end if playerx >= 50 then pspeedx = 0 playerx = 50 end if secondtimer > 2 then local i = math.max(0, (1-(secondtimer-2)/2)) staralpha = math.max(0, (1-(secondtimer-2)/2))*i love.graphics.setBackgroundColor(153*(1-i), 217*(1-i), 234*(1-i)) if shakeamount < 5 then shakeamount = math.min(5, shakeamount+dt*3) elseif shakeamount > 5 then shakeamount = math.max(5, shakeamount-dt*3) end end if secondtimer > 4 then changegamestate("scene5") end end if starttimer >= 4.3 and starttimer - dt < 4.3 then playerx = rockets[1].x+4 playery = rockets[1].y end if jumped then flyanimationtimer = flyanimationtimer + dt while flyanimationtimer > 0.1 do flyanimationtimer = flyanimationtimer - 0.1 if flyingquad == 3 then flyingquad = 4 else flyingquad = 3 end end end end function scene4_draw() local r, g, b = love.graphics.getColor() love.graphics.setColor(math.random(255), math.random(255), math.random(255), 255*(1-scoreanim)) for i = 1, backgroundstripes, 2 do local alpha = math.rad((i/backgroundstripes + math.fmod(sunrot/100, 1)) * 360) local point1 = {lastexplosion[1]*scale+200*scale*math.cos(alpha), lastexplosion[2]*scale+200*scale*math.sin(alpha)} local alpha = math.rad(((i+1)/backgroundstripes + math.fmod(sunrot/100, 1)) * 360) local point2 = {lastexplosion[1]*scale+200*scale*math.cos(alpha), lastexplosion[2]*scale+200*scale*math.sin(alpha)} love.graphics.polygon("fill", lastexplosion[1]*scale, lastexplosion[2]*scale, point1[1], point1[2], point2[1], point2[2]) end love.graphics.setColor(r, g, b, 255) for i,v in pairs(stars) do v:draw() end if playerx then local off = 0 if rockets[1] then off = rockets[1].startingoffset end love.graphics.draw(playerimg, playerquad[flyingquad], (playerx+off)*scale, playery*scale, 0, scale, scale, 13, 6) end if rockets[1] then rockets[1]:draw() end for i, v in pairs(explosions) do v:draw() end if (starttimer > 0 and starttimer < 3) or alerttimer > 0.1 then local i = math.abs(math.sin(alerttimer)) love.graphics.setColor(255, 0, 0, i*100) love.graphics.rectangle("fill", 0, 0, 100*scale, 80*scale) love.graphics.setColor(255, 0, 0, i*255) draw(alertimg, 50+math.random(5)-3, 40+math.random(5)-3, (math.random()*2-1)*0.1, i*0.5+0.6, i*0.5+0.6, 54, 15) draw(randomshitimg, 50+math.random(20)-10, 40+math.random(20)-10, 0, 1, 1, 50, 42) end if starttimer > 4 and not jumped then love.graphics.setColor(255, 0, 0, math.random(255)) properprint("jump!!", 0, 40, scale*3) end end function scene4_action() if starttimer > 4.3 and not jumped then jumped = true secondtimer = 0 pspeedx = 20 pspeedy = 2 end end
24.537143
124
0.639031
c45386f65a0f21a7005f3de535eb084e23f6d9ad
1,897
h
C
Filters/FlowPaths/vtkLagrangianThreadedData.h
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
2
2021-07-07T22:53:19.000Z
2021-07-31T19:29:35.000Z
Filters/FlowPaths/vtkLagrangianThreadedData.h
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
2
2020-11-18T16:50:34.000Z
2022-01-21T13:31:47.000Z
Filters/FlowPaths/vtkLagrangianThreadedData.h
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
5
2020-10-02T10:14:35.000Z
2022-03-10T07:50:22.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkLagrangianParticleTracker.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @struct vtkLagrangianThreadedData * @brief struct to hold a user data * * Struct to hold threaded data used by the Lagrangian Particle Tracker. * Can be inherited and initialized in custom models. */ #ifndef vtkLagrangianThreadedData_h #define vtkLagrangianThreadedData_h #include "vtkBilinearQuadIntersection.h" #include "vtkFiltersFlowPathsModule.h" // For export macro #include "vtkGenericCell.h" #include "vtkIdList.h" #include "vtkPolyData.h" class vtkDataObject; class vtkInitialValueProblemSolver; struct VTKFILTERSFLOWPATHS_EXPORT vtkLagrangianThreadedData { vtkNew<vtkGenericCell> GenericCell; vtkNew<vtkIdList> IdList; vtkNew<vtkPolyData> ParticlePathsOutput; // FindInLocators cache data int LastDataSetIndex = -1; vtkIdType LastCellId = -1; double LastCellPosition[3]; std::vector<double> LastWeights; vtkBilinearQuadIntersection* BilinearQuadIntersection; vtkDataObject* InteractionOutput; vtkInitialValueProblemSolver* Integrator; vtkLagrangianThreadedData() { this->BilinearQuadIntersection = new vtkBilinearQuadIntersection; this->IdList->Allocate(10); } ~vtkLagrangianThreadedData() { delete this->BilinearQuadIntersection; } }; #endif // vtkLagrangianThreadedData_h // VTK-HeaderTest-Exclude: vtkLagrangianThreadedData.h
31.098361
75
0.723247
de7c31ba58e8fcc1e57222b65fd5a52e2ec71801
5,598
rs
Rust
rust/src/stake_credential.rs
tesseract-one/Cardano.swift
788698fee64669e78e33df7ed87cdff4d3ffb9f0
[ "Apache-2.0" ]
7
2021-02-23T18:01:59.000Z
2022-02-05T23:29:09.000Z
rust/src/stake_credential.rs
tesseract-one/Cardano.swift
788698fee64669e78e33df7ed87cdff4d3ffb9f0
[ "Apache-2.0" ]
3
2021-09-14T03:07:16.000Z
2022-03-02T12:02:30.000Z
rust/src/stake_credential.rs
tesseract-one/Cardano.swift
788698fee64669e78e33df7ed87cdff4d3ffb9f0
[ "Apache-2.0" ]
1
2021-08-15T11:32:59.000Z
2021-08-15T11:32:59.000Z
use super::data::CData; use super::error::CError; use super::panic::*; use super::ptr::Ptr; use crate::array::CArray; use crate::ptr::Free; use cardano_serialization_lib::address::{StakeCredKind, StakeCredential as RStakeCredential}; use cardano_serialization_lib::crypto::{ Ed25519KeyHash as REd25519KeyHash, ScriptHash as RScriptHash, }; use cardano_serialization_lib::Ed25519KeyHashes as REd25519KeyHashes; use std::convert::{TryFrom, TryInto}; #[repr(C)] #[derive(Copy, Clone, Hash, PartialEq, Eq)] pub struct Ed25519KeyHash { bytes: [u8; 28], len: u8, } impl Free for Ed25519KeyHash { unsafe fn free(&mut self) {} } impl TryFrom<REd25519KeyHash> for Ed25519KeyHash { type Error = CError; fn try_from(hash: REd25519KeyHash) -> Result<Self> { let bytes = hash.to_bytes(); let len = bytes.len() as u8; let bytes: [u8; 28] = bytes.try_into().map_err(|_| CError::DataLengthMismatch)?; Ok(Self { bytes, len }) } } impl From<Ed25519KeyHash> for REd25519KeyHash { fn from(hash: Ed25519KeyHash) -> Self { hash.bytes.into() } } pub type Ed25519KeyHashes = CArray<Ed25519KeyHash>; impl TryFrom<Ed25519KeyHashes> for REd25519KeyHashes { type Error = CError; fn try_from(ed25519_key_hashes: Ed25519KeyHashes) -> Result<Self> { let vec = unsafe { ed25519_key_hashes.unowned()? }; let mut ed25519_key_hashes = REd25519KeyHashes::new(); for ed25519_key_hash in vec.to_vec() { ed25519_key_hashes.add(&ed25519_key_hash.into()); } Ok(ed25519_key_hashes) } } impl TryFrom<REd25519KeyHashes> for Ed25519KeyHashes { type Error = CError; fn try_from(ed25519_key_hashes: REd25519KeyHashes) -> Result<Self> { (0..ed25519_key_hashes.len()) .map(|index| ed25519_key_hashes.get(index)) .map(|ed25519_key_hash| ed25519_key_hash.try_into()) .collect::<Result<Vec<Ed25519KeyHash>>>() .map(|ed25519_key_hashes| ed25519_key_hashes.into()) } } #[no_mangle] pub unsafe extern "C" fn cardano_ed25519_key_hashes_free( ed25519_key_hashes: &mut Ed25519KeyHashes, ) { ed25519_key_hashes.free(); } #[repr(C)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ScriptHash { bytes: [u8; 28], len: u8, } impl TryFrom<RScriptHash> for ScriptHash { type Error = CError; fn try_from(hash: RScriptHash) -> Result<Self> { let bytes = hash.to_bytes(); let len = bytes.len() as u8; let bytes: [u8; 28] = bytes.try_into().map_err(|_| CError::DataLengthMismatch)?; Ok(Self { bytes, len }) } } impl From<ScriptHash> for RScriptHash { fn from(hash: ScriptHash) -> Self { hash.bytes.into() } } #[repr(C)] #[derive(Copy, Clone, Hash, PartialEq, Eq)] pub enum StakeCredential { Key(Ed25519KeyHash), Script(ScriptHash), } impl Free for StakeCredential { unsafe fn free(&mut self) {} } impl TryFrom<RStakeCredential> for StakeCredential { type Error = CError; fn try_from(cred: RStakeCredential) -> Result<Self> { match cred.kind() { StakeCredKind::Key => cred .to_keyhash() .ok_or_else(|| "Empty Key Hash but kind is 0".into()) .and_then(|hash| hash.try_into()) .map(|key| Self::Key(key)), StakeCredKind::Script => cred .to_scripthash() .ok_or_else(|| "Empty Script Hash but kind is 1".into()) .and_then(|hash| hash.try_into()) .map(|key| Self::Script(key)), } } } impl From<StakeCredential> for RStakeCredential { fn from(cred: StakeCredential) -> Self { match cred { StakeCredential::Key(hash) => RStakeCredential::from_keyhash(&hash.into()), StakeCredential::Script(hash) => RStakeCredential::from_scripthash(&hash.into()), } } } #[no_mangle] pub unsafe extern "C" fn cardano_ed25519_key_hash_from_bytes( data: CData, result: &mut Ed25519KeyHash, error: &mut CError, ) -> bool { handle_exception_result(|| { data .unowned() .and_then(|bytes| REd25519KeyHash::from_bytes(bytes.into()).into_result()) .and_then(|hash| hash.try_into()) }) .response(result, error) } #[no_mangle] pub unsafe extern "C" fn cardano_ed25519_key_hash_to_bytes( hash: Ed25519KeyHash, result: &mut CData, error: &mut CError, ) -> bool { handle_exception(|| { let rhash: REd25519KeyHash = hash.into(); rhash.to_bytes().into() }) .response(result, error) } #[no_mangle] pub unsafe extern "C" fn cardano_script_hash_from_bytes( data: CData, result: &mut ScriptHash, error: &mut CError, ) -> bool { handle_exception_result(|| { data .unowned() .and_then(|bytes| RScriptHash::from_bytes(bytes.into()).into_result()) .and_then(|hash| hash.try_into()) }) .response(result, error) } #[no_mangle] pub unsafe extern "C" fn cardano_script_hash_to_bytes( hash: ScriptHash, result: &mut CData, error: &mut CError, ) -> bool { handle_exception(|| { let rhash: RScriptHash = hash.into(); rhash.to_bytes().into() }) .response(result, error) } #[no_mangle] pub unsafe extern "C" fn cardano_stake_credential_from_bytes( data: CData, result: &mut StakeCredential, error: &mut CError, ) -> bool { handle_exception_result(|| { data .unowned() .and_then(|bytes| RStakeCredential::from_bytes(bytes.into()).into_result()) .and_then(|cred| cred.try_into()) }) .response(result, error) } #[no_mangle] pub unsafe extern "C" fn cardano_stake_credential_to_bytes( cred: StakeCredential, result: &mut CData, error: &mut CError, ) -> bool { handle_exception(|| { let rcred: RStakeCredential = cred.into(); rcred.to_bytes().into() }) .response(result, error) }
26.657143
93
0.680957
71e50f0560634c2d7efa6fa1b347f5a1107714fd
7,749
ts
TypeScript
src/components/utils/helpers.ts
tinybat02/ES-trajectory-v4
3e317bd671442b2bb2ff8cc44d65746f530ea1aa
[ "Apache-2.0" ]
null
null
null
src/components/utils/helpers.ts
tinybat02/ES-trajectory-v4
3e317bd671442b2bb2ff8cc44d65746f530ea1aa
[ "Apache-2.0" ]
null
null
null
src/components/utils/helpers.ts
tinybat02/ES-trajectory-v4
3e317bd671442b2bb2ff8cc44d65746f530ea1aa
[ "Apache-2.0" ]
null
null
null
import Feature from 'ol/Feature'; import Point from 'ol/geom/Point'; import { Coordinate } from 'ol/coordinate'; import LineString from 'ol/geom/LineString'; import Circle from 'ol/geom/Circle'; import { Circle as CircleStyle, Stroke, Style, Fill, Icon, Text } from 'ol/style'; import GeometryType from 'ol/geom/GeometryType'; import { Draw } from 'ol/interaction'; import { Vector as VectorLayer } from 'ol/layer'; import { Vector as VectorSource } from 'ol/source'; import { FeatureLike } from 'ol/Feature'; import { getLength } from 'ol/sphere'; import Arrow from '../../img/arrow.png'; import Arrow1 from '../../img/arrow1.png'; interface SingleData { latitude: number; longitude: number; [key: string]: any; } export const formatLength = function(line: LineString) { const length = getLength(line); let output; if (length > 100) { output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km'; } else { output = Math.round(length * 100) / 100 + ' ' + 'm'; } return output; }; export const processDataES = (data: SingleData[]) => { data.reverse(); const perDeviceRoute: { [key: string]: [number, number][] } = {}; const perDeviceVendor: { [key: string]: string } = {}; const perDeviceTime: { [key: string]: number[] } = {}; const perDeviceUncertainty: { [key: string]: number[] } = {}; const perDeviceFloor: { [key: string]: number[] } = {}; data.map(datum => { (perDeviceRoute[datum.hash_id] = perDeviceRoute[datum.hash_id] || []).push([datum.longitude, datum.latitude]); (perDeviceTime[datum.hash_id] = perDeviceTime[datum.hash_id] || []).push(datum.timestamp); (perDeviceUncertainty[datum.hash_id] = perDeviceUncertainty[datum.hash_id] || []).push(datum.uncertainty); (perDeviceFloor[datum.hash_id] = perDeviceFloor[datum.hash_id] || []).push(datum.floor); if (!perDeviceVendor[datum.hash_id]) perDeviceVendor[datum.hash_id] = datum.vendor; }); const perDeviceRoute_nonSinglePoint: { [key: string]: [number, number][] } = {}; const perDeviceTime_nonSinglePoint: { [key: string]: number[] } = {}; const perDeviceTime_array: { hash_id: string; duration: number }[] = []; let singlePointCount = 0; Object.keys(perDeviceRoute).map(hash_id => { if (perDeviceRoute[hash_id].length > 1) { perDeviceRoute_nonSinglePoint[hash_id] = perDeviceRoute[hash_id]; } else { singlePointCount++; } }); Object.keys(perDeviceTime).map(hash_id => { if (perDeviceTime[hash_id].length > 1) { perDeviceTime_nonSinglePoint[hash_id] = perDeviceTime[hash_id]; perDeviceTime_array.push({ hash_id, duration: perDeviceTime[hash_id].slice(-1)[0] - perDeviceTime[hash_id][0] }); } }); perDeviceTime_array.sort((a, b) => { if (a.duration > b.duration) return -1; if (a.duration < b.duration) return 1; return 0; }); return { perDeviceRoute: perDeviceRoute_nonSinglePoint, perDeviceTime: perDeviceTime_nonSinglePoint, perDeviceVendor, perDeviceUncertainty, singlePointCount, perDeviceFloor, selectList: perDeviceTime_array.map(elm => elm.hash_id), }; }; export const createLine = (routeData: Coordinate[], iterRoute: number, floorData: number[], other_floor: number) => { let color = 'rgba(73,168,222)'; let pic = Arrow; if (floorData[iterRoute] == other_floor) color = 'rgba(255,176,0)'; if (floorData[iterRoute + 1] == other_floor) pic = Arrow1; const dx = routeData[iterRoute + 1][0] - routeData[iterRoute][0]; const dy = routeData[iterRoute + 1][1] - routeData[iterRoute][1]; const rotation = Math.atan2(dy, dx); const lineFeature = new Feature(new LineString([routeData[iterRoute], routeData[iterRoute + 1]])); lineFeature.setStyle([ new Style({ stroke: new Stroke({ color: color, width: 2, }), }), new Style({ geometry: new Point(routeData[iterRoute + 1]), image: new Icon({ src: pic, anchor: [0.75, 0.5], rotateWithView: true, rotation: -rotation, }), }), ]); return lineFeature; }; export const createLineWithLabel = ( routeData: Coordinate[], timeData: number[], iterRoute: number, floorData: number[], other_floor: number ) => { let color = 'rgba(73,168,222)'; let pic = Arrow; if (floorData[iterRoute] == other_floor) color = 'rgba(255,176,0)'; if (floorData[iterRoute + 1] == other_floor) pic = Arrow1; const dx = routeData[iterRoute + 1][0] - routeData[iterRoute][0]; const dy = routeData[iterRoute + 1][1] - routeData[iterRoute][1]; const rotation = Math.atan2(dy, dx); const lineFeature = new Feature(new LineString([routeData[iterRoute], routeData[iterRoute + 1]])); lineFeature.setStyle([ new Style({ stroke: new Stroke({ color: color, width: 2, }), text: new Text({ stroke: new Stroke({ color: '#fff', width: 2, }), font: '18px Calibri,sans-serif', text: `${timeData[iterRoute + 1] - timeData[iterRoute]}s`, }), }), new Style({ geometry: new Point(routeData[iterRoute + 1]), image: new Icon({ src: pic, anchor: [0.75, 0.5], rotateWithView: true, rotation: -rotation, }), }), ]); return lineFeature; }; export const createPoint = ( routeData: Coordinate[], routeRadiusData: number[], iterRoute: number, floorData: number[], other_floor: number ) => { let color = 'rgba(73,168,222,0.6)'; if (floorData[iterRoute] == other_floor) color = 'rgba(255,176,0,0.6)'; // const pointFeature = new Feature(new Point(routeData[iterRoute])); // pointFeature.setStyle( // new Style({ // image: new Circle({ // radius: routeRadiusData[iterRoute] || 2, // // radius: 5, // fill: new Fill({ color: color }), // }), // }) // ); const pointFeature = new Feature(new Circle(routeData[iterRoute], routeRadiusData[iterRoute] || 2)); pointFeature.setStyle( new Style({ fill: new Fill({ color: color }), }) ); return pointFeature; }; export const createMeasureLayer = (source: VectorSource) => { return new VectorLayer({ source: source, style: function(feature: FeatureLike) { const geometry = feature.getGeometry() as LineString; const line_styles = [ new Style({ fill: new Fill({ color: 'rgba(255, 255, 255, 0.2)', }), stroke: new Stroke({ color: 'rgba(0, 0, 0, 0.5)', width: 2, }), }), ]; geometry.forEachSegment(function(start, end) { const linestring = new LineString([start, end]); const len = formatLength(linestring); line_styles.push( new Style({ geometry: linestring, text: new Text({ fill: new Fill({ color: '#000' }), stroke: new Stroke({ color: '#fff', width: 2, }), font: '12px/1 sans-serif', text: len, }), }) ); }); return line_styles; }, zIndex: 2, }); }; export const createDraw = (source: VectorSource) => { return new Draw({ source: source, type: GeometryType.LINE_STRING, style: new Style({ fill: new Fill({ color: 'rgba(255, 255, 255, 0.2)', }), stroke: new Stroke({ color: 'rgba(0, 0, 0, 0.5)', lineDash: [10, 10], width: 2, }), image: new CircleStyle({ radius: 5, stroke: new Stroke({ color: 'rgba(0, 0, 0, 0.7)', }), fill: new Fill({ color: 'rgba(255, 255, 255, 0.2)', }), }), }), }); };
29.803846
119
0.597884
729130e495f16e6f89883e7675f41c663a06b3e5
5,988
lua
Lua
source/lua/CPPUtilities.lua
Steelcap/NS2_CombatPlusPlus
fa51c126e7bdfba960e4e5c0f3faace42f1a3b39
[ "MIT" ]
null
null
null
source/lua/CPPUtilities.lua
Steelcap/NS2_CombatPlusPlus
fa51c126e7bdfba960e4e5c0f3faace42f1a3b39
[ "MIT" ]
null
null
null
source/lua/CPPUtilities.lua
Steelcap/NS2_CombatPlusPlus
fa51c126e7bdfba960e4e5c0f3faace42f1a3b39
[ "MIT" ]
null
null
null
function CombatPlusPlus_XPRequiredForNextRank(currentXP, rank) local xpRequired = 0 if rank < kMaxCombatRank then xpRequired = kXPTable[ rank + 1 ]["XP"] end return xpRequired end function CombatPlusPlus_GetXPThresholdByRank(rank) rank = Clamp(rank, 1, kMaxCombatRank) return kXPTable[rank]["XP"] end function CombatPlusPlus_GetMarineTitleByRank(rank) rank = Clamp(rank, 1, kMaxCombatRank) return kXPTable[rank]["MarineName"] end function CombatPlusPlus_GetAlienTitleByRank(rank) rank = Clamp(rank, 1, kMaxCombatRank) return kXPTable[rank]["AlienName"] end function CombatPlusPlus_GetBaseKillXP(victimRank) victimRank = Clamp(victimRank, 1, kMaxCombatRank) return kXPTable[victimRank]["BaseXpOnKill"] end function CombatPlusPlus_GetRankByXP(xp) local rank = 1 if xp >= kXPTable[kMaxCombatRank]["XP"] then rank = kMaxCombatRank else for i = 1, kMaxCombatRank-1 do if xp < kXPTable[ i + 1 ]["XP"] then rank = kXPTable[i]["Rank"] break end end end return rank end function CombatPlusPlus_GetCostByTechId(techId) local techIdCostTable = {} techIdCostTable[kTechId.Pistol] = 1 techIdCostTable[kTechId.Rifle] = 1 techIdCostTable[kTechId.Shotgun] = 1 techIdCostTable[kTechId.Flamethrower] = 1 techIdCostTable[kTechId.GrenadeLauncher] = 2 techIdCostTable[kTechId.HeavyMachineGun] = 2 techIdCostTable[kTechId.Welder] = 1 techIdCostTable[kTechId.LayMines] = 1 techIdCostTable[kTechId.ClusterGrenade] = 1 techIdCostTable[kTechId.GasGrenade] = 1 techIdCostTable[kTechId.PulseGrenade] = 1 techIdCostTable[kTechId.Jetpack] = 2 techIdCostTable[kTechId.DualMinigunExosuit] = 2 techIdCostTable[kTechId.Armor1] = 1 techIdCostTable[kTechId.Armor2] = 1 techIdCostTable[kTechId.Armor3] = 1 techIdCostTable[kTechId.Weapons1] = 1 techIdCostTable[kTechId.Weapons2] = 1 techIdCostTable[kTechId.Weapons3] = 1 techIdCostTable[kTechId.MedPack] = 1 techIdCostTable[kTechId.AmmoPack] = 1 techIdCostTable[kTechId.CatPack] = 1 techIdCostTable[kTechId.Scan] = 1 techIdCostTable[kTechId.Armory] = 1 techIdCostTable[kTechId.PhaseGate] = 1 techIdCostTable[kTechId.Observatory] = 2 techIdCostTable[kTechId.Sentry] = 1 techIdCostTable[kTechId.RoboticsFactory] = 2 local cost = techIdCostTable[techId] if not cost then cost = 0 end return cost end function CombatPlusPlus_GetRequiredRankByTechId(techId) local techIdRankTable = {} techIdRankTable[kTechId.Pistol] = 1 techIdRankTable[kTechId.Rifle] = 1 techIdRankTable[kTechId.Shotgun] = 3 techIdRankTable[kTechId.Flamethrower] = 6 techIdRankTable[kTechId.GrenadeLauncher] = 7 techIdRankTable[kTechId.HeavyMachineGun] = 8 techIdRankTable[kTechId.Welder] = 1 techIdRankTable[kTechId.LayMines] = 5 techIdRankTable[kTechId.ClusterGrenade] = 6 techIdRankTable[kTechId.GasGrenade] = 6 techIdRankTable[kTechId.PulseGrenade] = 6 techIdRankTable[kTechId.Jetpack] = 9 techIdRankTable[kTechId.DualMinigunExosuit] = 10 techIdRankTable[kTechId.Armor1] = 1 techIdRankTable[kTechId.Armor2] = 2 techIdRankTable[kTechId.Armor3] = 3 techIdRankTable[kTechId.Weapons1] = 1 techIdRankTable[kTechId.Weapons2] = 2 techIdRankTable[kTechId.Weapons3] = 3 techIdRankTable[kTechId.MedPack] = 2 techIdRankTable[kTechId.AmmoPack] = 2 techIdRankTable[kTechId.CatPack] = 7 techIdRankTable[kTechId.Scan] = 5 techIdRankTable[kTechId.Armory] = 3 techIdRankTable[kTechId.PhaseGate] = 4 techIdRankTable[kTechId.Observatory] = 5 techIdRankTable[kTechId.Sentry] = 6 techIdRankTable[kTechId.RoboticsFactory] = 8 local rank = techIdRankTable[techId] if not rank then rank = 1 end return rank end function GetDistanceBetweenTechPoints() local marineTechPointOrigin = GetGameMaster():GetMarineTechPoint():GetOrigin() local alienTechPointOrigin = GetGameMaster():GetAlienTechPoint():GetOrigin() return math.abs((marineTechPointOrigin - alienTechPointOrigin):GetLength()) end function ScaleXPByDistance(player, baseXp) local enemyTechPointOrigin = nil local scaledXp = baseXp if player:GetTeamNumber() == kTeam1Index then enemyTechPointOrigin = GetGameMaster():GetAlienTechPoint():GetOrigin() elseif player:GetTeamNumber() == kTeam2Index then enemyTechPointOrigin = GetGameMaster():GetMarineTechPoint():GetOrigin() end if enemyTechPointOrigin ~= nil then local distance = math.abs((enemyTechPointOrigin - player:GetOrigin()):GetLength()) local percentage = 1 - distance / GetDistanceBetweenTechPoints() local modifier = LerpNumber(1, kDistanceXPModifierMaxUpperBound, percentage) scaledXp = math.ceil(baseXp * modifier) end return scaledXp end function CreateTechEntity( techPoint, techId, rightOffset, forwardOffset, teamType ) local origin = techPoint:GetOrigin() + Vector(0, 2, 0) local right = techPoint:GetCoords().xAxis local forward = techPoint:GetCoords().zAxis local position = origin + right * rightOffset + forward * forwardOffset local trace = Shared.TraceRay(position, position - Vector(0, 10, 0), CollisionRep.Move, PhysicsMask.All) if trace.fraction < 1 then position = trace.endPoint end local newEnt = CreateEntityForTeam(techId, position, teamType, nil) if HasMixin( newEnt, "Construct" ) then SetRandomOrientation( newEnt ) newEnt:SetConstructionComplete() end if HasMixin( newEnt, "Live" ) then newEnt:SetIsAlive(true) end return newEnt end
28.927536
109
0.69322
60593950862831b5a623005dc95ee630176613c4
1,220
html
HTML
blog.html
Chel-Ash/channel-ai
a29a8ea993d8c267f74c1fd1ab47d5919fb94a26
[ "MIT" ]
1
2020-06-24T03:14:00.000Z
2020-06-24T03:14:00.000Z
blog.html
Chel-Ash/channel-ai
a29a8ea993d8c267f74c1fd1ab47d5919fb94a26
[ "MIT" ]
null
null
null
blog.html
Chel-Ash/channel-ai
a29a8ea993d8c267f74c1fd1ab47d5919fb94a26
[ "MIT" ]
null
null
null
--- layout: default title: Blog - Understanding CV & VR | Become an Expert Developer in Computer Vision or Virtual reality - ChannelAI description: My ChannelAi Blog. All Ai news as we can cover --- <h1 style="font-family: sans-serif; text-align: center; font-weight: 700; background-color: black; padding: 40px; color: white; border-top: 3px solid white;">ChannelAI Blog</h1> <div class="container-fluid games-page"> <br> <h5 style="font-family: Montserrat, sans-serif; font-weight: 600;">LATEST ON BLOG</h5> {% for post in site.posts %} {% unless post.path contains 'games' or post.path contains 'projects' %} <hr> <div class="row"> <div class="col-lg-8 col-sm-8"> <h4><a href="{{ post.url }}" class="game-title">{{ post.title }}</a></h4> <p>{{ post.description | strip_html | strip_newlines | truncate: 208 }}</p> <p style="clear: both">{{ post.date | date: "%b %-d, %Y" }}</p> </div> <div class="col-lg-4 col-sm-4"> <a href="{{ post.url }}"> <img defer class="responsive p-2 bd-highlight borderaround" src="{{ post.img-src }}.webp" alt="{{ post.img-alt }}" width="330" height="200"></a> </div> </div> {% endunless %} {% endfor %} </div> <p style="clear: both;"></p>
42.068966
177
0.636066
0eb526c066dc5612042290579e2ed0b33fbf6830
4,257
sql
SQL
database/migrations/20200818103136_create_admin_role_menu_table.sql
Vfuryx/fagin
2a0a5c4f2611a018a574a0e96db0d94498999a92
[ "MIT" ]
5
2019-07-23T01:24:47.000Z
2021-06-20T15:49:09.000Z
database/migrations/20200818103136_create_admin_role_menu_table.sql
Vfuryx/fagin
2a0a5c4f2611a018a574a0e96db0d94498999a92
[ "MIT" ]
9
2021-09-21T09:46:10.000Z
2022-02-19T04:07:53.000Z
database/migrations/20200818103136_create_admin_role_menu_table.sql
Vfuryx/fagin
2a0a5c4f2611a018a574a0e96db0d94498999a92
[ "MIT" ]
null
null
null
-- +migrate Up DROP TABLE IF EXISTS `admin_role_menus`; -- Create the table in the specified schema CREATE TABLE `admin_role_menus` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `role_id` int unsigned NOT NULL DEFAULT '0' COMMENT '角色id', `menu_id` int unsigned NOT NULL DEFAULT '0' COMMENT '菜单id', PRIMARY KEY (`id`), UNIQUE KEY `idx_role_id_menu_id` (`role_id`, `menu_id`) USING BTREE, KEY `idx_menu_id` (`menu_id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT ='后台角色关联菜单表'; INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (1, 1, 1); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (2, 1, 2); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (3, 1, 3); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (4, 1, 4); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (5, 1, 7); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (6, 1, 8); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (7, 1, 9); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (8, 1, 10); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (9, 1, 13); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (10, 1, 14); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (11, 1, 15); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (12, 1, 16); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (13, 1, 17); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (14, 1, 18); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (15, 1, 19); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (16, 1, 20); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (17, 1, 21); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (18, 1, 22); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (19, 1, 23); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (20, 1, 24); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (21, 1, 25); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (22, 1, 26); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (23, 1, 27); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (24, 1, 28); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (25, 1, 29); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (26, 1, 30); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (27, 1, 31); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (28, 1, 32); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (29, 1, 33); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (30, 1, 34); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (31, 1, 35); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (32, 1, 36); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (33, 1, 37); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (34, 1, 38); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (35, 1, 39); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (36, 1, 40); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (37, 1, 41); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (38, 1, 42); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (39, 1, 43); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (40, 1, 44); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (41, 1, 45); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (42, 1, 46); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (43, 1, 47); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (44, 1, 48); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (45, 1, 49); INSERT INTO `admin_role_menus` (`id`, `role_id`, `menu_id`) VALUES (46, 1, 50); -- +migrate Down DROP TABLE `admin_role_menus`;
38.7
72
0.667606
3e99ec7b21316d727897e9fa989f01320f344c47
6,511
c
C
src/sp65/vic2sprite.c
mikeakohn/cc65
ca31e3af1effb268d36235495a11c2580b938682
[ "Zlib" ]
6
2018-11-28T15:42:20.000Z
2022-01-05T18:59:11.000Z
src/sp65/vic2sprite.c
mikeakohn/cc65
ca31e3af1effb268d36235495a11c2580b938682
[ "Zlib" ]
1
2018-01-06T18:19:29.000Z
2018-01-06T18:19:29.000Z
src/sp65/vic2sprite.c
mikeakohn/cc65
ca31e3af1effb268d36235495a11c2580b938682
[ "Zlib" ]
1
2022-01-05T18:59:16.000Z
2022-01-05T18:59:16.000Z
/*****************************************************************************/ /* */ /* vic2sprite.c */ /* */ /* VICII sprite format backend for the sp65 sprite and bitmap utility */ /* */ /* */ /* */ /* (C) 2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "attrib.h" #include "print.h" /* sp65 */ #include "attr.h" #include "error.h" #include "vic2sprite.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Sprite mode */ enum Mode { smAuto, smHighRes, smMultiColor }; /* Size of a sprite */ #define WIDTH_HR 24U #define WIDTH_MC 12U #define HEIGHT 21U /*****************************************************************************/ /* Code */ /*****************************************************************************/ static enum Mode GetMode (const Collection* A) /* Return the sprite mode from the attribute collection A */ { /* Check for a mode attribute */ const char* Mode = GetAttrVal (A, "mode"); if (Mode) { if (strcmp (Mode, "highres") == 0) { return smHighRes; } else if (strcmp (Mode, "multicolor") == 0) { return smMultiColor; } else { Error ("Invalid value for attribute `mode'"); } } return smAuto; } StrBuf* GenVic2Sprite (const Bitmap* B, const Collection* A) /* Generate binary output in VICII sprite format for the bitmap B. The output ** is stored in a string buffer (which is actually a dynamic char array) and ** returned. */ { enum Mode M; StrBuf* D; unsigned X, Y; /* Output the image properties */ Print (stdout, 1, "Image is %ux%u with %u colors%s\n", GetBitmapWidth (B), GetBitmapHeight (B), GetBitmapColors (B), BitmapIsIndexed (B)? " (indexed)" : ""); /* Get the sprite mode */ M = GetMode (A); /* Check the height of the bitmap */ if (GetBitmapHeight (B) != HEIGHT) { Error ("Invalid bitmap height (%u) for conversion to vic2 sprite", GetBitmapHeight (B)); } /* If the mode wasn't given, determine it from the image properties */ if (M == smAuto) { switch (GetBitmapWidth (B)) { case WIDTH_HR: M = smHighRes; break; case WIDTH_MC: M = smMultiColor; break; default: Error ("Cannot determine mode from image properties"); } } /* Now check if mode and the image properties match */ if (M == smMultiColor) { if (GetBitmapWidth (B) != WIDTH_MC || GetBitmapColors (B) > 4) { Error ("Invalid image properties for multicolor sprite"); } } else { if (GetBitmapWidth (B) != WIDTH_HR || GetBitmapColors (B) > 2) { Error ("Invalid image properties for highres sprite"); } } /* Create the output buffer and resize it to the required size. */ D = NewStrBuf (); SB_Realloc (D, 63); /* Convert the image */ for (Y = 0; Y < HEIGHT; ++Y) { unsigned char V = 0; if (M == smHighRes) { for (X = 0; X < WIDTH_HR; ++X) { /* Fetch next bit into byte buffer */ V = (V << 1) | (GetPixel (B, X, Y).Index & 0x01); /* Store full bytes into the output buffer */ if ((X & 0x07) == 0x07) { SB_AppendChar (D, V); V = 0; } } } else { for (X = 0; X < WIDTH_MC; ++X) { /* Fetch next bit into byte buffer */ V = (V << 2) | (GetPixel (B, X, Y).Index & 0x03); /* Store full bytes into the output buffer */ if ((X & 0x03) == 0x03) { SB_AppendChar (D, V); V = 0; } } } } /* Return the converted bitmap */ return D; }
36.172222
79
0.392413
ad64ec0ac1d91cc2b6581713c3c2f7b1fd4086c5
6,114
swift
Swift
BarFinder/App/App.swift
nikolamilovanovic/barfinder
56cce7e96dbc450f844d8ef9b81d067db859994b
[ "Apache-2.0" ]
null
null
null
BarFinder/App/App.swift
nikolamilovanovic/barfinder
56cce7e96dbc450f844d8ef9b81d067db859994b
[ "Apache-2.0" ]
null
null
null
BarFinder/App/App.swift
nikolamilovanovic/barfinder
56cce7e96dbc450f844d8ef9b81d067db859994b
[ "Apache-2.0" ]
null
null
null
// // App.swift // BarFinder // // Created by Nikola Milovanovic on 5/13/18. // Copyright © 2018 Nikola Milovanovic. All rights reserved. // import Foundation import RxSwift /// Model of the application. It is singleton that contains all services and methods needed by Model and View Model layer. It should not be called from View layer. It should not use any UIKit objects. All methods should be called from main thread, as this object is not thread safe typealias OpeninigAppURLHandler = (UIApplication, URL, [UIApplicationOpenURLOptionsKey : Any]) -> Bool typealias OpeninigURLHandler = (URL) -> Void final class App { static let current = App() private var openingAppURLHandler: OpeninigAppURLHandler? private var openingURLHandler: OpeninigURLHandler? private var appLaunchingBlock: (() -> Void)? private var viewLaunchingBlock: (() -> Void)? private let errorsSubject: PublishSubject<ErrorData> // private objects private var coreDataControllerHolder: ObjectLazyHolder<CoreDataControllerProtocol>! private var distanceSynchronizerHolder: ObjectLazyHolder<DistanceSynchronizerProtocol>! // public objects private var barsDataControllerHolder: ObjectLazyHolder<BarsDataControllerProtocol>! private var serviceHolder: ObjectLazyHolder<ServiceProtocol>! private var locationServiceHolder: ObjectLazyHolder<LocationServiceProtocol>! private var settingsHolder: ObjectLazyHolder<SettingsProtocol>! private var reachabilityServiceHolder: ObjectLazyHolder<ReachabilityServiceProtocol>! private init() { self.errorsSubject = PublishSubject() self.coreDataControllerHolder = ObjectLazyHolder(creator: CoreDataController(name: "BarFinder")) self.distanceSynchronizerHolder = ObjectLazyHolder(creator: DistanceSynchronizer()) self.barsDataControllerHolder = ObjectLazyHolder(creator: { [unowned self] in return BarsDataController(coreDataController: self.coreDataController) }) self.serviceHolder = ObjectLazyHolder(creator: { [unowned self] in return FoursquareService(coreDataController: self.coreDataController) }) self.locationServiceHolder = ObjectLazyHolder(creator: LocationService()) self.settingsHolder = ObjectLazyHolder(creator: Settings()) self.reachabilityServiceHolder = ObjectLazyHolder(creator: ReachabilityService()) self.appLaunchingBlock = { // on app launch start services that need to be started in that moment self.reachabilityService.start() self.service.start() } self.viewLaunchingBlock = { // connect error observables let errorObservables: [Observable<ErrorData>] = [App.current.service.errors, App.current.locationService.errors] _ = Observable.merge(errorObservables).bind(to: self.errorsSubject) // on view open start services that need to be started in that moment self.locationService.start() self.distanceSynchronizer.start() } } /// All errors combined from services var errors: Observable<ErrorData> { return errorsSubject } /// This should be called when application is launched. It will make side affect only on first call func applicationIsLaunched() { if let launchingBlock = appLaunchingBlock { launchingBlock() appLaunchingBlock = nil } } /// This should be called when view is launched. It will make side affect only on first call func viewIsLaunched() { if let launchingBlock = viewLaunchingBlock { launchingBlock() viewLaunchingBlock = nil } } // Registering open url handler. It should be called from AppDelegate via AppDelegateViewModel as it opening url uses UIApplication, that is part of UIKit and should not be part of model func registerOpenURLHandler(handler: @escaping OpeninigURLHandler) { self.openingURLHandler = handler } // Opening url func open(url: URL) { if let openingHandler = self.openingURLHandler { openingHandler(url) } } // Registering applicatin opening url handler that called in AppDelegate. This was used for enabling Twitter API. Twitter service called this method func registerOpenAppURLHandler(handler: @escaping OpeninigAppURLHandler) { self.openingAppURLHandler = handler } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if let openingHandler = self.openingAppURLHandler { return openingHandler(app, url, options) } return false } // private objects private var coreDataController: CoreDataControllerProtocol { return coreDataControllerHolder.getValue() } private var distanceSynchronizer: DistanceSynchronizerProtocol { return distanceSynchronizerHolder.getValue() } // public objects var barsDataController: BarsDataControllerProtocol { return barsDataControllerHolder.getValue() } func push(barsDataController: BarsDataControllerProtocol) { barsDataControllerHolder.push(barsDataController) } func popBarsDataController() { barsDataControllerHolder.pop() } var service: ServiceProtocol { return serviceHolder.getValue() } func push(service: ServiceProtocol) { serviceHolder.push(service) } func popService() { serviceHolder.pop() } var locationService: LocationServiceProtocol { return locationServiceHolder.getValue() } func push(locationService: LocationServiceProtocol) { locationServiceHolder.push(locationService) } func popLocationService() { locationServiceHolder.pop() } var settings: SettingsProtocol { return settingsHolder.getValue() } func push(settings: SettingsProtocol) { settingsHolder.push(settings) } func popSettings() { settingsHolder.pop() } var reachabilityService: ReachabilityServiceProtocol { return reachabilityServiceHolder.getValue() } func push(reachability: ReachabilityServiceProtocol) { reachabilityServiceHolder.push(reachability) } func popReachability() { reachabilityServiceHolder.pop() } }
32.695187
281
0.74403
3fb27b3160b9d585b1c60d2ca075f4a3e3b16eeb
544
c
C
find/ifind1.c
pranomostro/algo
680563dd939f1d5a5624ced90a7bac799895fe25
[ "MIT" ]
null
null
null
find/ifind1.c
pranomostro/algo
680563dd939f1d5a5624ced90a7bac799895fe25
[ "MIT" ]
null
null
null
find/ifind1.c
pranomostro/algo
680563dd939f1d5a5624ced90a7bac799895fe25
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <stdint.h> #include "findtest.h" size_t ifind1(uint32_t key, uint32_t* data, size_t len) { if(len==0||data[0]>=key) return 0; else if(data[len-1]<=key) return len; size_t low=0, high=len-1, mid=midcalc(key, data, len-1, 0); while(low<=high&&data[mid]!=key) { if(data[low]>key) { mid=low-1; break; } else if(data[high]<key) { mid=high+1; break; } mid=midcalc(key, data, high, low); if(data[mid]<key) low=mid+1; else high=mid-1; } return data[mid]<key?mid+1:mid; }
15.111111
60
0.604779
86bc5a30da3b110354fa5c248b4ca5120c06cc49
7,078
rs
Rust
base_layer/core/src/covenants/token.rs
zhangcheng/tari
f5a034e19caa5a67ec667c8e971462b19a78c6d8
[ "BSD-3-Clause" ]
null
null
null
base_layer/core/src/covenants/token.rs
zhangcheng/tari
f5a034e19caa5a67ec667c8e971462b19a78c6d8
[ "BSD-3-Clause" ]
null
null
null
base_layer/core/src/covenants/token.rs
zhangcheng/tari
f5a034e19caa5a67ec667c8e971462b19a78c6d8
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use std::{collections::VecDeque, io, iter::FromIterator}; use tari_common_types::types::{Commitment, PublicKey}; use tari_crypto::script::TariScript; use crate::covenants::{ arguments::{CovenantArg, Hash}, decoder::{CovenantDecodeError, CovenentReadExt}, fields::OutputField, filters::{ AbsoluteHeightFilter, AndFilter, CovenantFilter, FieldEqFilter, FieldsHashedEqFilter, FieldsPreservedFilter, IdentityFilter, NotFilter, OrFilter, OutputHashEqFilter, XorFilter, }, Covenant, }; #[derive(Debug, Clone, PartialEq, Eq)] pub enum CovenantToken { Filter(CovenantFilter), Arg(CovenantArg), } impl CovenantToken { pub fn read_from<R: io::Read>(reader: &mut R) -> Result<Option<Self>, CovenantDecodeError> { let code = match reader.read_next_byte_code()? { Some(c) => c, // Nothing further to read None => return Ok(None), }; match code { code if CovenantFilter::is_valid_code(code) => { let filter = CovenantFilter::try_from_byte_code(code)?; Ok(Some(CovenantToken::Filter(filter))) }, code if CovenantArg::is_valid_code(code) => { let arg = CovenantArg::read_from(reader, code)?; Ok(Some(CovenantToken::Arg(arg))) }, code => Err(CovenantDecodeError::UnknownByteCode { code }), } } pub fn write_to<W: io::Write>(&self, writer: &mut W) -> Result<usize, io::Error> { match self { CovenantToken::Filter(filter) => filter.write_to(writer), CovenantToken::Arg(arg) => arg.write_to(writer), } } pub fn as_filter(&self) -> Option<&CovenantFilter> { match self { CovenantToken::Filter(filter) => Some(filter), CovenantToken::Arg(_) => None, } } pub fn as_arg(&self) -> Option<&CovenantArg> { match self { CovenantToken::Filter(_) => None, CovenantToken::Arg(arg) => Some(arg), } } //---------------------------------- Macro helper functions --------------------------------------------// #[allow(dead_code)] pub fn identity() -> Self { CovenantToken::Filter(CovenantFilter::Identity(IdentityFilter)) } #[allow(dead_code)] pub fn and() -> Self { CovenantToken::Filter(CovenantFilter::And(AndFilter)) } #[allow(dead_code)] pub fn or() -> Self { CovenantToken::Filter(CovenantFilter::Or(OrFilter)) } #[allow(dead_code)] pub fn xor() -> Self { CovenantToken::Filter(CovenantFilter::Xor(XorFilter)) } #[allow(dead_code)] pub fn not() -> Self { CovenantToken::Filter(CovenantFilter::Not(NotFilter)) } #[allow(dead_code)] pub fn output_hash_eq() -> Self { CovenantToken::Filter(CovenantFilter::OutputHashEq(OutputHashEqFilter)) } #[allow(dead_code)] pub fn fields_preserved() -> Self { CovenantToken::Filter(CovenantFilter::FieldsPreserved(FieldsPreservedFilter)) } #[allow(dead_code)] pub fn field_eq() -> Self { CovenantToken::Filter(CovenantFilter::FieldEq(FieldEqFilter)) } #[allow(dead_code)] pub fn fields_hashed_eq() -> Self { CovenantToken::Filter(CovenantFilter::FieldsHashedEq(FieldsHashedEqFilter)) } #[allow(dead_code)] pub fn absolute_height() -> Self { CovenantToken::Filter(CovenantFilter::AbsoluteHeight(AbsoluteHeightFilter)) } #[allow(dead_code)] pub fn hash(hash: Hash) -> Self { CovenantToken::Arg(CovenantArg::Hash(hash)) } #[allow(dead_code)] pub fn public_key(public_key: PublicKey) -> Self { CovenantToken::Arg(CovenantArg::PublicKey(public_key)) } #[allow(dead_code)] pub fn commitment(commitment: Commitment) -> Self { CovenantToken::Arg(CovenantArg::Commitment(commitment)) } #[allow(dead_code)] pub fn script(script: TariScript) -> Self { CovenantToken::Arg(CovenantArg::TariScript(script)) } #[allow(dead_code)] pub fn covenant(covenant: Covenant) -> Self { CovenantToken::Arg(CovenantArg::Covenant(covenant)) } #[allow(dead_code)] pub fn uint(val: u64) -> Self { CovenantToken::Arg(CovenantArg::Uint(val)) } #[allow(dead_code)] pub fn field(field: OutputField) -> Self { CovenantToken::Arg(CovenantArg::OutputField(field)) } #[allow(dead_code)] pub fn fields(fields: Vec<OutputField>) -> Self { CovenantToken::Arg(CovenantArg::OutputFields(fields.into())) } #[allow(dead_code)] pub fn bytes(bytes: Vec<u8>) -> Self { CovenantToken::Arg(CovenantArg::Bytes(bytes)) } } #[derive(Debug, Clone, Default)] pub struct CovenantTokenCollection { tokens: VecDeque<CovenantToken>, } impl CovenantTokenCollection { pub fn is_empty(&self) -> bool { self.tokens.is_empty() } pub fn next(&mut self) -> Option<CovenantToken> { self.tokens.pop_front() } } impl FromIterator<CovenantToken> for CovenantTokenCollection { fn from_iter<T: IntoIterator<Item = CovenantToken>>(iter: T) -> Self { Self { tokens: iter.into_iter().collect(), } } } impl From<Vec<CovenantToken>> for CovenantTokenCollection { fn from(tokens: Vec<CovenantToken>) -> Self { Self { tokens: tokens.into() } } }
32.027149
119
0.639587