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
e9431c6fad841550f40fefe3e434f928ae6e5756
8,136
go
Go
src/pkg/crypto/tls/handshake_server.go
SDpower/golang
8fd1bf1941d6fec1b1b5015578b23deadf1714c4
[ "BSD-3-Clause" ]
3
2016-08-12T18:47:59.000Z
2021-12-18T03:11:35.000Z
src/pkg/crypto/tls/handshake_server.go
SDpower/golang
8fd1bf1941d6fec1b1b5015578b23deadf1714c4
[ "BSD-3-Clause" ]
null
null
null
src/pkg/crypto/tls/handshake_server.go
SDpower/golang
8fd1bf1941d6fec1b1b5015578b23deadf1714c4
[ "BSD-3-Clause" ]
4
2016-03-17T06:53:07.000Z
2021-12-18T03:11:35.000Z
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package tls import ( "crypto" "crypto/rsa" "crypto/subtle" "crypto/x509" "io" "os" ) func (c *Conn) serverHandshake() os.Error { config := c.config msg, err := c.readHandshake() if err != nil { return err } clientHello, ok := msg.(*clientHelloMsg) if !ok { return c.sendAlert(alertUnexpectedMessage) } vers, ok := mutualVersion(clientHello.vers) if !ok { return c.sendAlert(alertProtocolVersion) } c.vers = vers c.haveVers = true finishedHash := newFinishedHash() finishedHash.Write(clientHello.marshal()) hello := new(serverHelloMsg) supportedCurve := false Curves: for _, curve := range clientHello.supportedCurves { switch curve { case curveP256, curveP384, curveP521: supportedCurve = true break Curves } } supportedPointFormat := false for _, pointFormat := range clientHello.supportedPoints { if pointFormat == pointFormatUncompressed { supportedPointFormat = true break } } ellipticOk := supportedCurve && supportedPointFormat var suite *cipherSuite var suiteId uint16 FindCipherSuite: for _, id := range clientHello.cipherSuites { for _, supported := range config.cipherSuites() { if id == supported { suite = cipherSuites[id] // Don't select a ciphersuite which we can't // support for this client. if suite.elliptic && !ellipticOk { continue } suiteId = id break FindCipherSuite } } } foundCompression := false // We only support null compression, so check that the client offered it. for _, compression := range clientHello.compressionMethods { if compression == compressionNone { foundCompression = true break } } if suite == nil || !foundCompression { return c.sendAlert(alertHandshakeFailure) } hello.vers = vers hello.cipherSuite = suiteId t := uint32(config.time()) hello.random = make([]byte, 32) hello.random[0] = byte(t >> 24) hello.random[1] = byte(t >> 16) hello.random[2] = byte(t >> 8) hello.random[3] = byte(t) _, err = io.ReadFull(config.rand(), hello.random[4:]) if err != nil { return c.sendAlert(alertInternalError) } hello.compressionMethod = compressionNone if clientHello.nextProtoNeg { hello.nextProtoNeg = true hello.nextProtos = config.NextProtos } if clientHello.ocspStapling && len(config.Certificates[0].OCSPStaple) > 0 { hello.ocspStapling = true } finishedHash.Write(hello.marshal()) c.writeRecord(recordTypeHandshake, hello.marshal()) if len(config.Certificates) == 0 { return c.sendAlert(alertInternalError) } certMsg := new(certificateMsg) certMsg.certificates = config.Certificates[0].Certificate finishedHash.Write(certMsg.marshal()) c.writeRecord(recordTypeHandshake, certMsg.marshal()) if hello.ocspStapling { certStatus := new(certificateStatusMsg) certStatus.statusType = statusTypeOCSP certStatus.response = config.Certificates[0].OCSPStaple finishedHash.Write(certStatus.marshal()) c.writeRecord(recordTypeHandshake, certStatus.marshal()) } keyAgreement := suite.ka() skx, err := keyAgreement.generateServerKeyExchange(config, clientHello, hello) if err != nil { c.sendAlert(alertHandshakeFailure) return err } if skx != nil { finishedHash.Write(skx.marshal()) c.writeRecord(recordTypeHandshake, skx.marshal()) } if config.AuthenticateClient { // Request a client certificate certReq := new(certificateRequestMsg) certReq.certificateTypes = []byte{certTypeRSASign} // An empty list of certificateAuthorities signals to // the client that it may send any certificate in response // to our request. finishedHash.Write(certReq.marshal()) c.writeRecord(recordTypeHandshake, certReq.marshal()) } helloDone := new(serverHelloDoneMsg) finishedHash.Write(helloDone.marshal()) c.writeRecord(recordTypeHandshake, helloDone.marshal()) var pub *rsa.PublicKey if config.AuthenticateClient { // Get client certificate msg, err = c.readHandshake() if err != nil { return err } certMsg, ok = msg.(*certificateMsg) if !ok { return c.sendAlert(alertUnexpectedMessage) } finishedHash.Write(certMsg.marshal()) certs := make([]*x509.Certificate, len(certMsg.certificates)) for i, asn1Data := range certMsg.certificates { cert, err := x509.ParseCertificate(asn1Data) if err != nil { c.sendAlert(alertBadCertificate) return os.ErrorString("could not parse client's certificate: " + err.String()) } certs[i] = cert } // TODO(agl): do better validation of certs: max path length, name restrictions etc. for i := 1; i < len(certs); i++ { if err := certs[i-1].CheckSignatureFrom(certs[i]); err != nil { c.sendAlert(alertBadCertificate) return os.ErrorString("could not validate certificate signature: " + err.String()) } } if len(certs) > 0 { key, ok := certs[0].PublicKey.(*rsa.PublicKey) if !ok { return c.sendAlert(alertUnsupportedCertificate) } pub = key c.peerCertificates = certs } } // Get client key exchange msg, err = c.readHandshake() if err != nil { return err } ckx, ok := msg.(*clientKeyExchangeMsg) if !ok { return c.sendAlert(alertUnexpectedMessage) } finishedHash.Write(ckx.marshal()) // If we received a client cert in response to our certificate request message, // the client will send us a certificateVerifyMsg immediately after the // clientKeyExchangeMsg. This message is a MD5SHA1 digest of all preceding // handshake-layer messages that is signed using the private key corresponding // to the client's certificate. This allows us to verify that the client is in // possession of the private key of the certificate. if len(c.peerCertificates) > 0 { msg, err = c.readHandshake() if err != nil { return err } certVerify, ok := msg.(*certificateVerifyMsg) if !ok { return c.sendAlert(alertUnexpectedMessage) } digest := make([]byte, 36) copy(digest[0:16], finishedHash.serverMD5.Sum()) copy(digest[16:36], finishedHash.serverSHA1.Sum()) err = rsa.VerifyPKCS1v15(pub, crypto.MD5SHA1, digest, certVerify.signature) if err != nil { c.sendAlert(alertBadCertificate) return os.ErrorString("could not validate signature of connection nonces: " + err.String()) } finishedHash.Write(certVerify.marshal()) } preMasterSecret, err := keyAgreement.processClientKeyExchange(config, ckx) if err != nil { c.sendAlert(alertHandshakeFailure) return err } masterSecret, clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := keysFromPreMasterSecret10(preMasterSecret, clientHello.random, hello.random, suite.macLen, suite.keyLen, suite.ivLen) clientCipher := suite.cipher(clientKey, clientIV, true /* for reading */ ) clientHash := suite.mac(clientMAC) c.in.prepareCipherSpec(clientCipher, clientHash) c.readRecord(recordTypeChangeCipherSpec) if err := c.error(); err != nil { return err } if hello.nextProtoNeg { msg, err = c.readHandshake() if err != nil { return err } nextProto, ok := msg.(*nextProtoMsg) if !ok { return c.sendAlert(alertUnexpectedMessage) } finishedHash.Write(nextProto.marshal()) c.clientProtocol = nextProto.proto } msg, err = c.readHandshake() if err != nil { return err } clientFinished, ok := msg.(*finishedMsg) if !ok { return c.sendAlert(alertUnexpectedMessage) } verify := finishedHash.clientSum(masterSecret) if len(verify) != len(clientFinished.verifyData) || subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { return c.sendAlert(alertHandshakeFailure) } finishedHash.Write(clientFinished.marshal()) serverCipher := suite.cipher(serverKey, serverIV, false /* not for reading */ ) serverHash := suite.mac(serverMAC) c.out.prepareCipherSpec(serverCipher, serverHash) c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) finished := new(finishedMsg) finished.verifyData = finishedHash.serverSum(masterSecret) c.writeRecord(recordTypeHandshake, finished.marshal()) c.handshakeComplete = true c.cipherSuite = suiteId return nil }
27.210702
119
0.720379
e1f2f6a3ab5d05a48d595234500c103d4faa09b4
556
swift
Swift
TodoList/UserInterface/Cells+Headers/Tableview/Cells/Task/Assignee/AssigneeCell.swift
musamaj/MVVMDemo
7d47a63f964e00c7366f75af93b8c3fe5a8b9a3e
[ "MIT" ]
null
null
null
TodoList/UserInterface/Cells+Headers/Tableview/Cells/Task/Assignee/AssigneeCell.swift
musamaj/MVVMDemo
7d47a63f964e00c7366f75af93b8c3fe5a8b9a3e
[ "MIT" ]
null
null
null
TodoList/UserInterface/Cells+Headers/Tableview/Cells/Task/Assignee/AssigneeCell.swift
musamaj/MVVMDemo
7d47a63f964e00c7366f75af93b8c3fe5a8b9a3e
[ "MIT" ]
null
null
null
// // AssigneeCell.swift // TodoList // // Created by Usama Jamil on 02/08/2019. // Copyright © 2019 Usama Jamil. All rights reserved. // import UIKit class AssigneeCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func populateData(viewModel: TaskDetailVM) { } }
19.172414
65
0.640288
977d850e536e89b8c4bb152d18cecce2ed07d6e2
5,845
dart
Dart
lib/src/ios/MAAnimatedAnnotation.g.dart
sen-Cai/amap_map_fluttify
2dd7d8ea42886db5803fab14d8010d8e7b5a0177
[ "Apache-2.0" ]
null
null
null
lib/src/ios/MAAnimatedAnnotation.g.dart
sen-Cai/amap_map_fluttify
2dd7d8ea42886db5803fab14d8010d8e7b5a0177
[ "Apache-2.0" ]
null
null
null
lib/src/ios/MAAnimatedAnnotation.g.dart
sen-Cai/amap_map_fluttify
2dd7d8ea42886db5803fab14d8010d8e7b5a0177
[ "Apache-2.0" ]
null
null
null
////////////////////////////////////////////////////////// // GENERATED BY FLUTTIFY. DO NOT EDIT IT. ////////////////////////////////////////////////////////// import 'dart:typed_data'; import 'package:amap_map_fluttify/src/ios/ios.export.g.dart'; import 'package:amap_map_fluttify/src/android/android.export.g.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; // ignore_for_file: non_constant_identifier_names, camel_case_types, missing_return, unused_import class MAAnimatedAnnotation extends MAPointAnnotation with MAAnimatableAnnotation { // generate getters Future<double> get_movingDirection() async { final result = await MethodChannel('me.yohom/amap_map_fluttify').invokeMethod("MAAnimatedAnnotation::get_movingDirection", {'refId': refId}); return result; } // generate setters Future<void> set_movingDirection(double movingDirection) async { await MethodChannel('me.yohom/amap_map_fluttify').invokeMethod('MAAnimatedAnnotation::set_movingDirection', {'refId': refId, "movingDirection": movingDirection}); } // generate methods Future<MAAnnotationMoveAnimation> addMoveAnimationWithKeyCoordinatesCountwithDurationwithNamecompleteCallback(List<CLLocationCoordinate2D> coordinates, int count, double duration, String name, void completeCallback(bool isFinished)) async { // print log if (fluttifyLogEnabled) { print('fluttify-dart: MAAnimatedAnnotation@$refId::addMoveAnimationWithKeyCoordinates([\'count\':$count, \'duration\':$duration, \'name\':$name])'); } // invoke native method final result = await MethodChannel('me.yohom/amap_map_fluttify').invokeMethod('MAAnimatedAnnotation::addMoveAnimationWithKeyCoordinatesCountwithDurationwithNamecompleteCallback', {"coordinates": coordinates.map((it) => it.refId).toList(), "count": count, "duration": duration, "name": name, "refId": refId}); // handle native call MethodChannel('MAAnimatedAnnotation::addMoveAnimationWithKeyCoordinatesCountwithDurationwithNamecompleteCallback::Callback') .setMethodCallHandler((methodCall) async { final args = methodCall.arguments as Map; // final refId = args['callerRefId'] as int; // if (refId != this.refId) return; switch (methodCall.method) { case 'Callback::void|BOOL isFinished::void|BOOL isFinished': // print log if (!kReleaseMode) { } // handle the native call completeCallback(args['isFinished']); break; default: break; } }); // convert native result to dart side object if (result == null) { return null; } else { kNativeObjectPool.add(MAAnnotationMoveAnimation()..refId = result..tag = 'amap_map_fluttify'); return MAAnnotationMoveAnimation()..refId = result..tag = 'amap_map_fluttify'; } } Future<MAAnnotationMoveAnimation> addMoveAnimationWithKeyCoordinatesCountwithDurationwithNamecompleteCallbackstepCallback(List<CLLocationCoordinate2D> coordinates, int count, double duration, String name, void completeCallback(bool isFinished), void stepCallback(MAAnnotationMoveAnimation currentAni)) async { // print log if (fluttifyLogEnabled) { print('fluttify-dart: MAAnimatedAnnotation@$refId::addMoveAnimationWithKeyCoordinates([\'count\':$count, \'duration\':$duration, \'name\':$name])'); } // invoke native method final result = await MethodChannel('me.yohom/amap_map_fluttify').invokeMethod('MAAnimatedAnnotation::addMoveAnimationWithKeyCoordinatesCountwithDurationwithNamecompleteCallbackstepCallback', {"coordinates": coordinates.map((it) => it.refId).toList(), "count": count, "duration": duration, "name": name, "refId": refId}); // handle native call MethodChannel('MAAnimatedAnnotation::addMoveAnimationWithKeyCoordinatesCountwithDurationwithNamecompleteCallbackstepCallback::Callback') .setMethodCallHandler((methodCall) async { final args = methodCall.arguments as Map; // final refId = args['callerRefId'] as int; // if (refId != this.refId) return; switch (methodCall.method) { case 'Callback::void|BOOL isFinished::void|BOOL isFinished': // print log if (!kReleaseMode) { } // handle the native call completeCallback(args['isFinished']); break; case 'Callback::void|MAAnnotationMoveAnimation currentAni::void|MAAnnotationMoveAnimation currentAni': // print log if (!kReleaseMode) { } // handle the native call stepCallback(MAAnnotationMoveAnimation()..refId = (args['currentAni'])..tag = 'amap_map_fluttify'); break; default: break; } }); // convert native result to dart side object if (result == null) { return null; } else { kNativeObjectPool.add(MAAnnotationMoveAnimation()..refId = result..tag = 'amap_map_fluttify'); return MAAnnotationMoveAnimation()..refId = result..tag = 'amap_map_fluttify'; } } Future<void> setNeedsStart() async { // print log if (fluttifyLogEnabled) { print('fluttify-dart: MAAnimatedAnnotation@$refId::setNeedsStart([])'); } // invoke native method final result = await MethodChannel('me.yohom/amap_map_fluttify').invokeMethod('MAAnimatedAnnotation::setNeedsStart', {"refId": refId}); // handle native call // convert native result to dart side object if (result == null) { return null; } else { return result; } } }
40.590278
324
0.659025
0893c79098c3a92e408525d17ab9ce3fb608675b
256
go
Go
goFile/goImports/needImport.go
mathbalduino/go-codegen
b9ca2e9a860ed27000ae4bbc8ed073b0fc21f9a4
[ "MIT" ]
null
null
null
goFile/goImports/needImport.go
mathbalduino/go-codegen
b9ca2e9a860ed27000ae4bbc8ed073b0fc21f9a4
[ "MIT" ]
6
2021-11-19T11:31:08.000Z
2021-11-30T19:03:08.000Z
goFile/goImports/needImport.go
mathbalduino/go-codegen
b9ca2e9a860ed27000ae4bbc8ed073b0fc21f9a4
[ "MIT" ]
null
null
null
package goImports // NeedImport will return true if the given package path needs // to be imported, when called inside the import list host package func (i *GoImports) NeedImport(otherPackagePath string) bool { return i.packagePath != otherPackagePath }
32
66
0.789063
0522fcf5ab5d4128b63f6fbcf846595d987059b6
1,319
rb
Ruby
ruby/SymmetryBySize.rb
wmatthew/hendecagon
91002e82e5b104d7b5e37d00b7502f63596a6131
[ "BSD-3-Clause" ]
1
2016-04-26T06:44:40.000Z
2016-04-26T06:44:40.000Z
ruby/SymmetryBySize.rb
wmatthew/hendecagon
91002e82e5b104d7b5e37d00b7502f63596a6131
[ "BSD-3-Clause" ]
null
null
null
ruby/SymmetryBySize.rb
wmatthew/hendecagon
91002e82e5b104d7b5e37d00b7502f63596a6131
[ "BSD-3-Clause" ]
null
null
null
=begin If you flip X coins and arrange them in a circle, what are the odds the pattern will be symmetrical? Size Sym Total Percent Symmetrical 1 1 1 100.0% <-- always symmetrical 2 2 2 100.0% 3 4 4 100.0% 4 8 8 100.0% 5 16 16 100.0% 6 26 32 81.25% 7 50 64 78.125% 8 80 128 62.5% 9 130 256 50.78125% <-- almost evenly split 10 212 512 41.40625% 11 342 1024 33.3984375% 12 518 2048 25.29296875% 13 820 4096 20.01953125% 14 1276 8192 15.576171875% 15 1864 16384 11.376953125% 16 2960 32768 9.033203125% 17 4336 65536 6.6162109375% 18 6704 131072 5.11474609375% 19 9710 262144 3.70407104492188% 20 15068 524288 2.87399291992188% <-- rarely symmetrical For example: 6 26 32 81.25% - If you flip 6 coins, - It will be symmetrical 26 / 32 times. - That's 81.25%. =end require 'HendecagonUtils.rb' include HendecagonUtils def evaluateSize(size) max = 2 ** (size-1) sym = 0 for i in (0..max-1) cand = dec2bin_length(i, size) if (isCircleSym(cand)) sym = sym + 1 end end puts "#{size}\t#{sym}\t#{max}\t#{100.0*sym/max}%" end puts "If you flip X coins and arrange them in a circle, what are the odds the pattern will be symmetrical?"; puts "Size\tSym\tTotal\tPercent Symmetrical" for size in 1..20 evaluateSize(size) end
21.983333
65
0.664898
90dc18286b085cc12f3c63609fcb5d16a18a4bfd
2,283
py
Python
dotnet.py
Gutem/scans-exploits
657f0058fd29daaa3ff084e00f61c1d0c5590007
[ "MIT" ]
3
2021-01-17T11:02:59.000Z
2021-08-30T19:55:46.000Z
dotnet.py
Gutem/scans-exploits
657f0058fd29daaa3ff084e00f61c1d0c5590007
[ "MIT" ]
null
null
null
dotnet.py
Gutem/scans-exploits
657f0058fd29daaa3ff084e00f61c1d0c5590007
[ "MIT" ]
2
2021-01-30T05:56:09.000Z
2021-08-30T19:55:49.000Z
#!/usr/bin/python3 """ ################################################################################ This script checks for CVE-2017-9248 https://nvd.nist.gov/vuln/detail/CVE-2017-9248 Telerik Web UI's Cryptographic Weakness ################################################################################ """ import sys import requests indicator="Telerik.Web.UI%2c+Version%3d" vulnerable_versions=["2007.1423","2008.31314","2010.31317","2013.1.403", "2015.2.729","2007.1521","2009.1311","2011.1315","2013.1.417","2015.2.826", "2007.1626","2009.1402","2011.1413","2013.2.611","2015.3.930","2007.2918", "2009.1527","2011.1519","2013.2.717","2015.3.1111","2007.2101","2009.2701", "2011.2712","2013.3.1015","2016.1.113","2007.21107","2009.2826","2011.2915", "2013.3.1114","2016.1.225","2007.31218","2009.31103","2011.31115","2013.3.1324", "2016.2.504","2007.31314","2009.31208","2011.3.1305","2014.1.225","2016.2.607", "2007.31425","2009.31314","2012.1.215","2014.1.403","2016.3.914","2008.1415", "2010.1309","2012.1.411","2014.2.618","2016.3.1018","2008.1515","2010.1415", "2012.2.607","2014.2.724","2016.3.1027","2008.1619","2010.1519","2012.2.724", "2014.3.1024","2017.1.118","2008.2723","2010.2713","2012.2.912","2015.1.204", "2017.1.228","2008.2826","2010.2826","2012.3.1016","2015.1.225","2017.2.503", "2008.21001","2010.2929","2012.3.1205","2015.1.401","2017.2.621","2008.31105", "2010.31109","2012.3.1308","2015.2.604","2017.2.711","2008.31125","2010.31215", "2013.1.220","2015.2.623","2017.3.913"] body_message="<div style='text-align:center;'>Loading the dialog...</div>" dialog_handler='Telerik.Web.UI.DialogHandler.aspx' url = str(sys.argv[1]) initial = requests.get(url) initial_result = initial.text handler = requests.get(url+dialog_handler) handler_result=handler.text if indicator in initial_result: for x in vulnerable_versions: if indicator+x in initial_result: print("Version", x, "found") if body_message in handler_result: print("[+]POSSIBLE VULNERABLE") else: print(dialog_handler, "not found") ################################################################################ ### TODO: Implement the gadget to exploit ### ################################################################################
44.764706
80
0.579501
1bf16fcff53a37d3e2ef97166e83d9870072512c
2,897
py
Python
jetten.py
AndrewQuijano/Treespace_REU_2017
e1aff2224ad5152d82f529675444146a70623bca
[ "MIT" ]
2
2021-06-07T12:22:46.000Z
2021-09-14T00:19:03.000Z
jetten.py
AndrewQuijano/Treespace_REU_2017
e1aff2224ad5152d82f529675444146a70623bca
[ "MIT" ]
null
null
null
jetten.py
AndrewQuijano/Treespace_REU_2017
e1aff2224ad5152d82f529675444146a70623bca
[ "MIT" ]
null
null
null
import networkx as nx from misc import maximum_matching_all from networkx import get_node_attributes from drawing import draw_bipartite import platform plt = platform.system() def is_tree_based(graph, name=None, draw=False): unmatched_omnian = jetten_graph(graph, name, draw) if len(unmatched_omnian) == 0: return True else: # print("unmatched omnian nodes: " + str(unmatched_omnian)) return False def get_omnians(graph): omnians = [] for node in graph.nodes(): if is_omnian(graph, node): omnians.append(node) return omnians def is_reticulation(graph, node): if graph.in_degree(node) >= 2 and graph.out_degree(node) == 1: return True else: return False def is_omnian(graph, node): for child in graph.successors(node): if not is_reticulation(graph, child): return False if graph.out_degree(node) != 0: return True else: return False def jetten_bipartite(graph): jetten = nx.Graph() omnians = [] reticulation = [] # Fill the nodes up for node in graph.nodes(): # set Reticulations if is_reticulation(graph, node): reticulation.append(node) jetten.add_node('R-' + node, biparite=1) # set Omnians if is_omnian(graph, node): omnians.append(node) jetten.add_node(node, biparite=0) data = get_node_attributes(jetten, 'biparite') for s, t in graph.edges(): try: # s is an omnian vertex if data[s] == 0: jetten.add_edge(s, 'R-' + t) except KeyError: # If you have a Leaf or Tree Vertex, it might not be Omnian or Reticulation... # print("Key Error: " + s + " OR " + t) continue # print("Omnians: " + str(omnians)) # print("Reticulation: " + str(reticulation)) return jetten # Use this for non-binary graph def jetten_graph(graph, name=None, draw=False): matched_omnians = set() try: jetten = jetten_bipartite(graph) max_match = maximum_matching_all(jetten) if draw: if name is None: draw_bipartite(jetten, max_match, graph_name="-jetten-bipartite") else: draw_bipartite(jetten, max_match, graph_name=name + "-jetten-bipartite") omnians = set(n for n, d in jetten.nodes(data=True) if d['biparite'] == 0) data = get_node_attributes(jetten, 'biparite') for s, t in max_match.items(): if data[s] == 1: matched_omnians.add(t) if data[t] == 1: matched_omnians.add(s) # print("matched omnians: " + str(matched_omnians)) set_minus = omnians - matched_omnians except nx.exception.NetworkXPointlessConcept: return list() return list(set_minus)
28.126214
90
0.602002
26b89eede24b954e54cb6797fb2e21d56aed8eb1
1,988
java
Java
packages/dashbuilder/dashbuilder-client/dashbuilder-widgets/src/main/java/org/dashbuilder/client/widgets/dataset/editor/DataSetDefColumnsFilterEditorView.java
zdrapela/kie-tools
2ecbb7bf39024d8618f40fc3a7d8e0328a3e24a8
[ "Apache-2.0" ]
4
2022-01-30T16:49:34.000Z
2022-03-28T13:24:32.000Z
packages/dashbuilder/dashbuilder-client/dashbuilder-widgets/src/main/java/org/dashbuilder/client/widgets/dataset/editor/DataSetDefColumnsFilterEditorView.java
zdrapela/kie-tools
2ecbb7bf39024d8618f40fc3a7d8e0328a3e24a8
[ "Apache-2.0" ]
86
2022-01-26T19:08:09.000Z
2022-03-31T07:40:37.000Z
packages/dashbuilder/dashbuilder-client/dashbuilder-widgets/src/main/java/org/dashbuilder/client/widgets/dataset/editor/DataSetDefColumnsFilterEditorView.java
zdrapela/kie-tools
2ecbb7bf39024d8618f40fc3a7d8e0328a3e24a8
[ "Apache-2.0" ]
6
2022-02-06T15:22:38.000Z
2022-03-31T05:59:50.000Z
package org.dashbuilder.client.widgets.dataset.editor; import javax.enterprise.context.Dependent; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import org.gwtbootstrap3.client.ui.TabContent; import org.gwtbootstrap3.client.ui.TabListItem; import org.gwtbootstrap3.client.ui.TabPane; /** * <p>Data Set columns and filter editor view.</p> * * @since 0.4.0 */ @Dependent public class DataSetDefColumnsFilterEditorView extends Composite implements DataSetDefColumnsFilterEditor.View { interface Binder extends UiBinder<Widget, DataSetDefColumnsFilterEditorView> { Binder BINDER = GWT.create(Binder.class); } DataSetDefColumnsFilterEditor presenter; @UiField TabListItem columnsTabItem; @UiField TabListItem filterTabItem; @UiField TabContent tabContent; @UiField TabPane columnsTabPane; @UiField TabPane filterTabPane; @UiField(provided = true) IsWidget columnsEditorView; @UiField(provided = true) DataSetDefFilterEditor.View dataSetFilterEditorView; @Override public void init(final DataSetDefColumnsFilterEditor presenter) { this.presenter = presenter; } @Override public void initWidgets(IsWidget columnsEditorView, DataSetDefFilterEditor.View dataSetFilterEditorView) { this.columnsEditorView = columnsEditorView; this.dataSetFilterEditorView = dataSetFilterEditorView; initWidget(Binder.BINDER.createAndBindUi(this)); columnsTabItem.setDataTargetWidget(columnsTabPane); filterTabItem.setDataTargetWidget(filterTabPane); } public void setMaxHeight(final String maxHeight) { tabContent.getElement().getStyle().setProperty("maxHeight", maxHeight); } }
28.4
112
0.747485
ff465224cb743260302b454e3e1e2f4d69e47829
817
kt
Kotlin
src/main/kotlin/no/nav/klage/util/StringToLanguageEnumConverter.kt
navikt/klage-dittnav-api
c8b3dff51796ff170aef6d6d48d9d33f98a328a2
[ "MIT" ]
null
null
null
src/main/kotlin/no/nav/klage/util/StringToLanguageEnumConverter.kt
navikt/klage-dittnav-api
c8b3dff51796ff170aef6d6d48d9d33f98a328a2
[ "MIT" ]
6
2020-05-12T13:26:56.000Z
2021-01-26T06:21:17.000Z
src/main/kotlin/no/nav/klage/util/StringToLanguageEnumConverter.kt
navikt/klage-dittnav-api
c8b3dff51796ff170aef6d6d48d9d33f98a328a2
[ "MIT" ]
null
null
null
package no.nav.klage.util import no.nav.klage.domain.LanguageEnum import no.nav.klage.domain.titles.TitleEnum import org.springframework.core.convert.converter.Converter import java.util.* class StringToLanguageEnumConverter : Converter<String?, LanguageEnum?> { override fun convert(source: String): LanguageEnum { if (source != null) { return LanguageEnum.valueOf(source.uppercase(Locale.getDefault())) } else { throw RuntimeException("error") } } } class StringToTitleEnumConverter : Converter<String?, TitleEnum?> { override fun convert(source: String): TitleEnum { if (source != null) { return TitleEnum.valueOf(source.uppercase(Locale.getDefault())) } else { throw RuntimeException("error") } } }
31.423077
78
0.671971
d288e95596916410c49f1fcf96e6166d8a4c6c08
985
lua
Lua
MMOCoreORB/bin/scripts/mobile/rori/ravenous_torton.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/bin/scripts/mobile/rori/ravenous_torton.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/bin/scripts/mobile/rori/ravenous_torton.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
ravenous_torton = Creature:new { objectName = "@mob/creature_names:ravenous_torton", socialGroup = "torton", faction = "", level = 34, chanceHit = 0.4, damageMin = 325, damageMax = 360, baseXp = 3370, baseHAM = 8600, baseHAMmax = 10500, armor = 0, resists = {20,20,20,-1,-1,145,145,180,-1}, meatType = "meat_carnivore", meatAmount = 1000, hideType = "hide_wooly", hideAmount = 1000, boneType = "bone_mammal", boneAmount = 1000, milk = 0, tamingChance = 0.25, ferocity = 9, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + HERD, optionsBitmask = AIENABLED, diet = CARNIVORE, templates = {"object/mobile/torton_hue.iff"}, hues = { 0, 1, 2, 3, 4, 5, 6, 7 }, controlDeviceTemplate = "object/intangible/pet/torton_hue.iff", scale = 1.1, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { {"knockdownattack",""}, {"dizzyattack",""} } } CreatureTemplates:addCreatureTemplate(ravenous_torton, "ravenous_torton")
23.452381
73
0.677157
595c956238f94fe83f1c9962ac4b1f4e459fdda3
15,684
c
C
framework/driver/gfx/src/drv_gfx_sh1101a_ssd1303.c
jerry-james/mla_gfx
9783cd987034c7bdd9c185188ef2bfdf98f9e0cb
[ "Apache-2.0" ]
null
null
null
framework/driver/gfx/src/drv_gfx_sh1101a_ssd1303.c
jerry-james/mla_gfx
9783cd987034c7bdd9c185188ef2bfdf98f9e0cb
[ "Apache-2.0" ]
1
2019-02-28T23:17:08.000Z
2019-02-28T23:17:08.000Z
framework/driver/gfx/src/drv_gfx_sh1101a_ssd1303.c
jerry-james/mla_gfx
9783cd987034c7bdd9c185188ef2bfdf98f9e0cb
[ "Apache-2.0" ]
4
2018-12-08T12:18:17.000Z
2019-05-08T16:38:14.000Z
/******************************************************************************* Display Driver for Microchip Graphics Library - Display Driver Layer Company: Microchip Technology Inc. File Name: drv_gfx_sh1101a_ssd1303.c Summary: Display Driver for use with the Microchip Graphics Library. Description: This module implements the display driver for the following controllers: * Sino Wealth Microelectronic SH1101A OLED controller driver * Solomon Systech SSD1303 LCD controller driver This module implements the basic Display Driver Layer API required by the Microchip Graphics Library to enable, initialize and render pixels to the display controller. *******************************************************************************/ // DOM-IGNORE-BEGIN /******************************************************************************* Copyright 2018 Microchip Technology Inc. (www.microchip.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. To request to license the code under the MLA license (www.microchip.com/mla_license), please contact mla_licensing@microchip.com *******************************************************************************/ // DOM-IGNORE-END // ***************************************************************************** // ***************************************************************************** // Section: Included Files // ***************************************************************************** // ***************************************************************************** #include "system.h" #include <stdint.h> #if defined(USE_GFX_DISPLAY_CONTROLLER_SH1101A) || defined (USE_GFX_DISPLAY_CONTROLLER_SSD1303) #include <libpic30.h> #include "driver/gfx/drv_gfx_display.h" #include "driver/gfx/drv_gfx_sh1101a_ssd1303.h" #include "gfx/gfx_primitive.h" #if defined (USE_GFX_PMP) #include "driver/gfx/drv_gfx_pmp.h" #elif defined (USE_GFX_EPMP) #include "driver/gfx/drv_gfx_epmp.h" #endif // ***************************************************************************** // ***************************************************************************** // Section: Local Functions // ***************************************************************************** // ***************************************************************************** // ***************************************************************************** /* Function: void DRV_GFX_AddressSet( uint8_t page, uint8_t lowerAddr, uint8_t higherAddr) Summary: This function sets the address of the pixel to be read or modified. Description: This function sets the address of the pixel to be read or modified. The address can be set once for contiguous pixels to be modified. Auto increment of the internal address pointer in the controller will be performed after every read or write. */ // ***************************************************************************** inline void __attribute__((always_inline)) DRV_GFX_AddressSet( uint8_t page, uint8_t lowerAddr, uint8_t higherAddr) { DisplaySetCommand(); DRV_GFX_PMPWrite(page); DRV_GFX_PMPWrite(lowerAddr); DRV_GFX_PMPWrite(higherAddr); DisplaySetData(); } // ***************************************************************************** /* Function: void DRV_GFX_Initialize(void) Summary: Initialize the graphics display driver. Description: This function initializes the graphics display driver. This function will be called by the application. */ // ***************************************************************************** void DRV_GFX_Initialize(void) { // Initialize the device DRV_GFX_PMPInitialize(); DisplayEnable(); DisplaySetCommand(); #if defined(USE_GFX_DISPLAY_CONTROLLER_SH1101A) // Setup Display DRV_GFX_PMPWrite(0xAE); // turn off the display (AF=ON, AE=OFF) DRV_GFX_PMPWrite(0xDB); // set VCOMH DRV_GFX_PMPWrite(0x23); DRV_GFX_PMPWrite(0xD9); // set VP DRV_GFX_PMPWrite(0x22); // Re-map DRV_GFX_PMPWrite(0xA1); // [A0]:column address 0 is map to SEG0 // [A1]:column address 131 is map to SEG0 // COM Output Scan Direction DRV_GFX_PMPWrite(0xC8); // C0 is COM0 to COMn, C8 is COMn to COM0 // COM Pins Hardware Configuration DRV_GFX_PMPWrite(0xDA); // set pins hardware configuration DRV_GFX_PMPWrite(0x12); // Multiplex Ratio DRV_GFX_PMPWrite(0xA8); // set multiplex ratio DRV_GFX_PMPWrite(0x3F); // set to 64 mux // Display Clock Divide DRV_GFX_PMPWrite(0xD5); // set display clock divide DRV_GFX_PMPWrite(0xA0); // set to 100Hz // Contrast Control Register DRV_GFX_PMPWrite(0x81); // Set contrast control DRV_GFX_PMPWrite(0x60); // display 0 ~ 127; 2C // Display Offset DRV_GFX_PMPWrite(0xD3); // set display offset DRV_GFX_PMPWrite(0x00); // no offset //Normal or Inverse Display DRV_GFX_PMPWrite(0xA6); // Normal display DRV_GFX_PMPWrite(0xAD); // Set DC-DC DRV_GFX_PMPWrite(0x8B); // 8B=ON, 8A=OFF // Display ON/OFF DRV_GFX_PMPWrite(0xAF); // AF=ON, AE=OFF __delay_ms(150); // Entire Display ON/OFF DRV_GFX_PMPWrite(0xA4); // A4=ON // Display Start Line DRV_GFX_PMPWrite(0x40); // Set display start line // Lower Column Address DRV_GFX_PMPWrite(0x00 + DRV_GFX_OFFSET); // Set lower column address // Higher Column Address DRV_GFX_PMPWrite(0x10); // Set higher column address __delay_ms(1); #elif defined (USE_GFX_DISPLAY_CONTROLLER_SSD1303) // Setup Display DRV_GFX_PMPWrite(0xAE); // turn off the display (AF=ON, AE=OFF) DRV_GFX_PMPWrite(0xDB); // set VCOMH DRV_GFX_PMPWrite(0x23); DRV_GFX_PMPWrite(0xD9); // set VP DRV_GFX_PMPWrite(0x22); DRV_GFX_PMPWrite(0xAD); // Set DC-DC DRV_GFX_PMPWrite(0x8B); // 8B=ON, 8A=OFF __delay_ms(1); // Display ON/OFF DRV_GFX_PMPWrite(0xAF); // AF=ON, AE=OFF // Init OLED display using SSD1303 driver // Display Clock Divide DRV_GFX_PMPWrite(0xD5); // set display clock divide DRV_GFX_PMPWrite(0xA0); // set to 100Hz // Display Offset DRV_GFX_PMPWrite(0xD3); // set display offset DRV_GFX_PMPWrite(0x00); // no offset // Multiplex Ratio DRV_GFX_PMPWrite(0xA8); // set multiplex ratio DRV_GFX_PMPWrite(0x3F); // set to 64 mux // Display Start Line DRV_GFX_PMPWrite(0x40); // Set display start line // Re-map DRV_GFX_PMPWrite(0xA0); // [A0]:column address 0 is map to SEG0 // [A1]:column address 131 is map to SEG0 // COM Output Scan Direction DRV_GFX_PMPWrite(0xC8); // C0 is COM0 to COMn, C8 is COMn to COM0 // COM Pins Hardware Configuration DRV_GFX_PMPWrite(0xDA); // set pins hardware configuration DRV_GFX_PMPWrite(0x12); // Contrast Control Register DRV_GFX_PMPWrite(0x81); // Set contrast control DRV_GFX_PMPWrite(0x60); // display 0 ~ 127; 2C // Entire Display ON/OFF DRV_GFX_PMPWrite(0xA4); // A4=ON //Normal or Inverse Display DRV_GFX_PMPWrite(0xA6); // Normal display #ifdef DISABLE_DC_DC_CONVERTER DRV_GFX_PMPWrite(0x8A); #else DRV_GFX_PMPWrite(0x8B); // 8B=ON, 8A=OFF #endif // Lower Column Address DRV_GFX_PMPWrite(0x00 + OFFSET); // Set lower column address // Higher Column Address DRV_GFX_PMPWrite(0x10); // Set higher column address __delay_ms(1); #else #error The controller is not supported. #endif DisplayDisable(); DisplaySetData(); } // ***************************************************************************** /* Function: GFX_STATUS GFX_PixelPut( uint16_t x, uint16_t y) Summary: Draw the pixel on the given position. Description: This routine draws the pixel on the given position. The color used is the color set by the last call to GFX_ColorSet(). If position is not on the frame buffer, then the behavior is undefined. If color is not set, before this function is called, the output is undefined. */ // ***************************************************************************** GFX_STATUS GFX_PixelPut(uint16_t x, uint16_t y) { uint8_t page, add, lAddr, hAddr; uint8_t mask, display; // Assign a page address if(y < 8) page = 0xB0; else if(y < 16) page = 0xB1; else if(y < 24) page = 0xB2; else if(y < 32) page = 0xB3; else if(y < 40) page = 0xB4; else if(y < 48) page = 0xB5; else if(y < 56) page = 0xB6; else page = 0xB7; add = x + DRV_GFX_OFFSET; lAddr = 0x0F & add; // Low address hAddr = 0x10 | (add >> 4); // High address // Calculate mask from rows basically do a y%8 and remainder is bit position add = y >> 3; // Divide by 8 add <<= 3; // Multiply by 8 add = y - add; // Calculate bit position mask = 1 << add; // Left shift 1 by bit position DisplayEnable(); DRV_GFX_AddressSet(page, lAddr, hAddr); // Set the address (sets the page, // lower and higher column address pointers) display = DRV_GFX_PMPSingleRead(); // Read to initiate Read transaction on PMP and dummy read // (requirement for data synchronization in the controller) display = DRV_GFX_PMPSingleRead(); // Read again as a requirement for data synchronization in the display controller display = DRV_GFX_PMPSingleRead(); // Read actual data from from display buffer if(GFX_ColorGet() > 0) // If non-zero for pixel on display |= mask; // or in mask else // If 0 for pixel off display &= ~mask; // and with inverted mask DRV_GFX_AddressSet(page, lAddr, hAddr); // Set the address (sets the page, // lower and higher column address pointers) DRV_GFX_PMPWrite(display); // restore the uint8_t with manipulated bit DisplayDisable(); return (GFX_STATUS_SUCCESS); } // ***************************************************************************** /* Function: GFX_COLOR GFX_PixelGet( uint16_t x, uint16_t y) Summary: Gets color of the pixel on the given position. Description: This routine gets the pixel on the given position. If position is not on the frame buffer, then the behavior is undefined. */ // ***************************************************************************** GFX_COLOR GFX_PixelGet(uint16_t x, uint16_t y) { uint8_t page, add, lAddr, hAddr; uint8_t mask, temp, display; // Assign a page address if(y < 8) page = 0xB0; else if(y < 16) page = 0xB1; else if(y < 24) page = 0xB2; else if(y < 32) page = 0xB3; else if(y < 40) page = 0xB4; else if(y < 48) page = 0xB5; else if(y < 56) page = 0xB6; else page = 0xB7; add = x + DRV_GFX_OFFSET; lAddr = 0x0F & add; // Low address hAddr = 0x10 | (add >> 4); // High address // Calculate mask from rows basically do a y%8 and remainder is bit position temp = y >> 3; // Divide by 8 temp <<= 3; // Multiply by 8 temp = y - temp; // Calculate bit position mask = 1 << temp; // Left shift 1 by bit position DisplayEnable(); DRV_GFX_AddressSet(page, lAddr, hAddr); // Set the address (sets the page, // lower and higher column address pointers) display = DRV_GFX_PMPSingleRead(); // Read to initiate Read transaction on PMP // Dummy Read (requirement for data // synchronization in the controller) display = DRV_GFX_PMP16BitRead(); // Read data from display buffer DisplayDisable(); return (display & mask); // mask all other bits and return // the result } // ***************************************************************************** /* Function: GFX_STATUS GFX_ScreenClear(void) Summary: Clears the screen to the currently set color (GFX_ColorSet()). Description: This function clears the screen with the current color and sets the line cursor position to (0, 0). If color is not set, before this function is called, the output is undefined. If the function returns GFX_STATUS_FAILURE, clearing is not yet finished. Application must call the function again to continue the clearing. */ // ***************************************************************************** GFX_STATUS GFX_ScreenClear(void) { uint8_t i, j; GFX_COLOR color; if (GFX_ColorGet() == 0) color = 0x00; else color = 0xFF; DisplayEnable(); for(i = 0xB0; i < 0xB8; i++) { // Go through all 8 pages DRV_GFX_AddressSet(i, 0x00, 0x10); for(j = 0; j < 132; j++) { // Write to all 132 bytes DRV_GFX_PMPWrite(color); } } DisplayDisable(); GFX_LinePositionSet(0, 0); return (GFX_STATUS_SUCCESS); } // ***************************************************************************** /* Function: GFX_STATUS GFX_RenderStatusGet() Summary: This function returns the driver's status on rendering. Description: The controller has no hardware accelerated rendering routines. Therefore, this function will always return GFX_STATUS_READY_BIT. This means that the driver's rendering status is always ready. Valid values returned are GFX_STATUS_BUSY_BIT or GFX_STATUS_READY_BIT. */ // ***************************************************************************** GFX_STATUS_BIT GFX_RenderStatusGet(void) { return GFX_STATUS_READY_BIT; } #endif // #if defined(USE_GFX_DISPLAY_CONTROLLER_SH1101A) || defined (USE_GFX_DISPLAY_CONTROLLER_SSD1303)
33.512821
129
0.531242
75eea81491aa1c5b43eeef5737b9826aeaa1b923
3,794
php
PHP
config/initializeDB.php
Akalanka47000/Online-Pharmacy-Portal
dc23f0eb4a35b82b3cb7a54d39a34269f77bb177
[ "MIT" ]
null
null
null
config/initializeDB.php
Akalanka47000/Online-Pharmacy-Portal
dc23f0eb4a35b82b3cb7a54d39a34269f77bb177
[ "MIT" ]
null
null
null
config/initializeDB.php
Akalanka47000/Online-Pharmacy-Portal
dc23f0eb4a35b82b3cb7a54d39a34269f77bb177
[ "MIT" ]
null
null
null
<?php function initializeDB(){ $servername = "localhost"; $username = "root"; $password = ""; $conn = new mysqli($servername, $username, $password); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "CREATE DATABASE IF NOT EXISTS pharmacyDB;"; if ($conn->query($sql) === TRUE) { $dbname = "pharmacyDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $results = []; $table1 = "CREATE TABLE IF NOT EXISTS Users ( email VARCHAR(30), username VARCHAR(20), password VARCHAR(32), userRole VARCHAR(10), address VARCHAR(40), constraint user_pk primary key (email) )"; $table2 = "CREATE TABLE IF NOT EXISTS Products ( productID VARCHAR(20), productName VARCHAR(30), productDescription VARCHAR(200), productImage VARCHAR(65535), productPrice DECIMAL (10, 2), productCategory VARCHAR (50), productBrand VARCHAR (30), availableStocks INTEGER, itemsSold INTEGER, constraint product_pk primary key (productID) )"; $table3 = "CREATE TABLE IF NOT EXISTS Orders( orderID VARCHAR(20), email VARCHAR(30), productID VARCHAR(20), placedDate DATETIME, orderStatus VARCHAR(15), constraint orders_PK PRIMARY KEY (orderID), constraint orders_fk1 FOREIGN KEY (email) REFERENCES Users(email), constraint orders_fk2 FOREIGN KEY (productID) REFERENCES Products(productID) )"; $table4 = "CREATE TABLE IF NOT EXISTS Chatrooms( chatroomID VARCHAR(20), participant1Email VARCHAR(30), participant2Email VARCHAR(30), chatroomStatus VARCHAR(15), constraint chatroom_pk primary key (chatroomID), constraint chatroom_pk_fk1 FOREIGN KEY(participant1Email) REFERENCES Users(email), constraint chatroom_pk_fk2 FOREIGN KEY(participant2Email) REFERENCES Users(email) )"; $table5 = "CREATE TABLE IF NOT EXISTS Messages( messageID VARCHAR(20), messageBody VARCHAR(200), createdAt DATETIME, senderEmail VARCHAR(30), chatroomID VARCHAR(20), constraint msg_pk primary key(messageID), constraint msg_fk1 foreign key (senderEmail) references Users(email), constraint msg_fk2 foreign key (chatroomID) references Chatrooms(chatroomID) )"; $encryptedPassword=md5("123456"); $query1 = "INSERT INTO Users (email, username, password, userRole, address) VALUES ('admin@gmail.com', 'admin', '$encryptedPassword' , 'Admin', 'NULL')"; $queries = [$table1, $table2, $table3, $table4, $table5, $query1]; foreach($queries as $k => $sql){ $query = @$conn->query($sql); if(!$query){ $results[] = "Table $k : Creation failed ($conn->error)"; }else{ $results[] = "Table $k : Creation done"; } } } else { echo "Error creating database: " . $conn->error; } } ?>
39.113402
98
0.515814
5b0f2eee3450349558ace1c599260bcd817363aa
1,942
h
C
Example/Pods/Headers/Private/libffi_iOS/ffi_cfi.h
wangwanjie/libffi-iOS
157a26d1fa7d4202b1518fb3af3eded4a5ac8255
[ "MIT" ]
1
2020-09-18T09:29:27.000Z
2020-09-18T09:29:27.000Z
Example/Pods/Headers/Public/libffi_iOS/ffi_cfi.h
wangwanjie/libffi_iOS
157a26d1fa7d4202b1518fb3af3eded4a5ac8255
[ "MIT" ]
null
null
null
Example/Pods/Headers/Public/libffi_iOS/ffi_cfi.h
wangwanjie/libffi_iOS
157a26d1fa7d4202b1518fb3af3eded4a5ac8255
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------- ffi_cfi.h - Copyright (c) 2014 Red Hat, Inc. Conditionally assemble cfi directives. Only necessary for building libffi. ----------------------------------------------------------------------- */ #ifndef FFI_CFI_H #define FFI_CFI_H #ifdef HAVE_AS_CFI_PSEUDO_OP # define cfi_startproc .cfi_startproc # define cfi_endproc .cfi_endproc # define cfi_def_cfa(reg, off) .cfi_def_cfa reg, off # define cfi_def_cfa_register(reg) .cfi_def_cfa_register reg # define cfi_def_cfa_offset(off) .cfi_def_cfa_offset off # define cfi_adjust_cfa_offset(off) .cfi_adjust_cfa_offset off # define cfi_offset(reg, off) .cfi_offset reg, off # define cfi_rel_offset(reg, off) .cfi_rel_offset reg, off # define cfi_register(r1, r2) .cfi_register r1, r2 # define cfi_return_column(reg) .cfi_return_column reg # define cfi_restore(reg) .cfi_restore reg # define cfi_same_value(reg) .cfi_same_value reg # define cfi_undefined(reg) .cfi_undefined reg # define cfi_remember_state .cfi_remember_state # define cfi_restore_state .cfi_restore_state # define cfi_window_save .cfi_window_save # define cfi_personality(enc, exp) .cfi_personality enc, exp # define cfi_lsda(enc, exp) .cfi_lsda enc, exp # define cfi_escape(...) .cfi_escape __VA_ARGS__ #else # define cfi_startproc # define cfi_endproc # define cfi_def_cfa(reg, off) # define cfi_def_cfa_register(reg) # define cfi_def_cfa_offset(off) # define cfi_adjust_cfa_offset(off) # define cfi_offset(reg, off) # define cfi_rel_offset(reg, off) # define cfi_register(r1, r2) # define cfi_return_column(reg) # define cfi_restore(reg) # define cfi_same_value(reg) # define cfi_undefined(reg) # define cfi_remember_state # define cfi_restore_state # define cfi_window_save # define cfi_personality(enc, exp) # define cfi_lsda(enc, exp) # define cfi_escape(...) #endif /* HAVE_AS_CFI_PSEUDO_OP */ #endif /* FFI_CFI_H */
34.678571
77
0.722451
998be636209919553863e761ec7fe86ccd76c094
3,027
swift
Swift
Swift-Playgrounds/Blogs/NSHipster/2014-08-18-SwiftLiteralConvertibles.playground/section-1.swift
cyrsis/SwiftSandBox
82bf7b4aaed4e3c4a7f82a9b92fa163753d5526c
[ "MIT" ]
204
2015-01-19T21:34:11.000Z
2022-03-27T17:14:35.000Z
Swift-Playgrounds/Blogs/NSHipster/2014-08-18-SwiftLiteralConvertibles.playground/section-1.swift
jeroendesloovere/examples-swift
da427aadfd84011d73801ab8f25b85d49e9d442c
[ "MIT" ]
2
2015-11-10T02:18:20.000Z
2017-08-08T22:51:41.000Z
Swift-Playgrounds/Blogs/NSHipster/2014-08-18-SwiftLiteralConvertibles.playground/section-1.swift
jeroendesloovere/examples-swift
da427aadfd84011d73801ab8f25b85d49e9d442c
[ "MIT" ]
61
2015-01-28T09:58:57.000Z
2022-02-10T08:23:11.000Z
// Swift Literal Convertibles from NSHipster http://nshipster.com/swift-literal-convertible/ import Foundation /* enum Optional<T> : Reflectable, NilLiteralConvertible { case None case Some(T) init() init(_ some: T) var hasValue: Bool { get } func map<U>(f: (T) -> U) -> U? func getMirror() -> MirrorType static func convertFromNilLiteral() -> T? } */ // Doesn't seem to work struct Regex { let pattern: String let options: NSRegularExpressionOptions! private var matcher: NSRegularExpression { return NSRegularExpression(pattern: self.pattern, options: self.options, error: nil) } init(pattern: String, options: NSRegularExpressionOptions = nil) { self.pattern = pattern self.options = options } func match(string: String, options: NSMatchingOptions = nil) -> Bool { return self.matcher.numberOfMatchesInString(string, options: options, range: NSMakeRange(0, string.utf16Count)) != 0 } } extension Regex: StringLiteralConvertible { typealias ExtendedGraphemeClusterLiteralType = StringLiteralType static func convertFromExtendedGraphemeClusterLiteral(value: ExtendedGraphemeClusterLiteralType) -> Regex { return self(pattern: value) } static func convertFromStringLiteral(value: StringLiteralType) -> Regex { return self(pattern: value) } } let string: String = "foo bar baz" let regex: Regex = "foo" regex.match(string) "foo".match(string) // ArrayLiteralConvertible and Sets struct Set<T: Hashable> { typealias Index = T private var dictionary: [T: Bool] init() { self.dictionary = [T: Bool]() } var count: Int { return self.dictionary.count } var isEmpty: Bool { return self.dictionary.isEmpty } func contains(element: T) -> Bool { return self.dictionary[element] ?? false } mutating func put(element: T) { self.dictionary[element] = true } mutating func remove(element: T) -> Bool { if self.contains(element) { self.dictionary.removeValueForKey(element) return true } else { return false } } } var basicSet: Set<Int> = Set() basicSet.put(1) basicSet.put(2) basicSet.put(3) basicSet.contains(1) basicSet.count extension Set: ArrayLiteralConvertible { static func convertFromArrayLiteral(elements: T...) -> Set<T> { var set = Set<T>() for element in elements { set.put(element) } return set } } let set: Set = [1, 2, 3] set.contains(1) set.count // StringLitralConvertible and URLs extension NSURL: StringLiteralConvertible { public class func convertFromExtendedGraphemeClusterLiteral(value: String) -> Self { return self(string: value) } public class func convertFromStringLiteral(value: String) -> Self { return self(string: value) } } "http://nshipster.com/".host
23.284615
124
0.644863
9d1225c8c9de5d8f59b201a0fe143d00512aafc0
10,853
html
HTML
public/resume/cv/old/resume_teaching.html
tjmonsi/begrafic
7155f964b2b357cb9cf8c0bae2edd1b820e28152
[ "MIT" ]
2
2017-09-05T06:33:31.000Z
2017-09-05T06:33:35.000Z
public/resume/cv/old/resume_teaching.html
tjmonsi/begrafic
7155f964b2b357cb9cf8c0bae2edd1b820e28152
[ "MIT" ]
1
2017-09-06T02:28:03.000Z
2017-09-06T04:15:06.000Z
public/resume/cv/old/resume_teaching.html
tjmonsi/begrafic
7155f964b2b357cb9cf8c0bae2edd1b820e28152
[ "MIT" ]
null
null
null
<html><head><title>a i s p u r o -- d e s i g n e r</title></head> <body bgcolor="ffffff" text="000000" link="#333366" vlink="#666666" alink="#669999"> <center> <table border=0 cellpadding=9 width=600 align="center"> <tr> <td colspan=4 align=left><img src="../../images/aispuro.gif" width=374 height=62></td> </tr> <tr> <td width=57></td> <td width=182></td> <td width=57></td> <td width=271 align=right> <a href="mailto:be@begrafic.com"><font face="Verdana, Arial, Helvetica, sans-serif" size="2">be@begrafic.com</font></a><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><br> 323.262.4450</font> </td> <tr> <td colspan=3 align=left valign="top"><img src="../../images/gdsoft.gif" width=282 height=29 alt="graphic design software"></td> <td width="271"></td> </tr> <tr> <td width="57"></td> <td rowspan=2 width="182" valign="top"> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> QuarkXpress <br> Photoshop <br> Image Ready <br> Illustrator <br> Dreamweaver <br> Cold Fusion<br> Flash <br> Dimensions <br> KPT Bryce <br> GifBuilder <br> PageMill <br> NetObjects Fusion <br> graphic converters <br> </font> </td> <td colspan=2 align=right valign=top> <img src="../../images/addskills.gif" width=284 height=27 alt="additional computer skills"></td> <tr> <td width="57"></td> <td width="57"></td> <td left width="271" valign="top"><font face="Verdana, Arial, Helvetica, sans-serif" size="2">Filemaker Pro<br> Word <br> Excel <br> UNIX <br> vi <br> Extensive HTML <br> Java Familiarity <br> </font> </td> </tr> <tr> <td width="57"></td> <td colspan=2 align=left valign=bottom><img src="../../images/otherskills.gif" width=207 height="28" alt="other skills"> <td width="271"></td> </tr> <tr> <td width="57"></td> <td colspan=2 align=left valign="top"> <font size="2" face="Verdana, Arial, Helvetica, sans-serif">Fluent in Spanish, Italian<br> Black and White Photography</font></td> <td width="271"></td> </tr> <tr> <td colspan=3 align=left valign="bottom" height="55"><img src="../../images/teachingexp.gif" width="284" height="31"></td> <td width="271" height="55"></td> </tr> <tr> <td align=left valign="top">&nbsp;</td> <td colspan=3 align=left valign="top"> <p><font face="Verdana, Arial, Helvetica, sans-serif" size="2">Wrote curriculum and conducted computer training classes for GPS staff and students in image/text scanning, html, software and hardware applications, UNIX, ftp, and Telnet </font></p> <p><font face="Verdana, Arial, Helvetica, sans-serif" size="2">Wrote instructional guides and materials on software and desktop publishing for staff in all departments at Caltech </font></p> <p><font face="Verdana, Arial, Helvetica, sans-serif" size="2">Conducted cross-training sessions on design, html, and desktop publishing with staff at SFUSD Language Academy </font></p> <p><font face="Verdana, Arial, Helvetica, sans-serif" size="2">Trained staff at Shopsports.com and Event411.com on Photoshop, Dreamweaver, Illustrator, and other software applications </font></p> <p><font face="Verdana, Arial, Helvetica, sans-serif" size="2">Provided teachers at SFUSD with instruction on using computers and teleconferencing equipment</font></p> </td> </tr> <tr> <td colspan=3 align=left valign="top"><img src="../../images/gdexper.gif" width=282 height="26" alt="graphic design experience"></td> <td width="271"></td> </tr> <tr> <td width="57"></td> <td colspan=3 valign="top"> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Redesigned/Restructured <a href="../../../ss/shopsports.html">web sites</a> for online sporting goods/web design company, Translated shopsports.com site into Spanish, and trained staff on Photoshop, Illustrator, Dreamweaver, and web design/html.</font></p> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Created page layout designs for a business to business software company offering online <a href="../../../e411/images/comps2/event.html">event planning tools</a> </font></p> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Did production work for redesign of Disney on-line store</font></p> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Designed <a href="../../../cels/logo.oyf.html"> logos</a>, <a href="../../../cels/poster.html">posters</a>, <a href="../../../cels/posts.html">postcards</a>, and various <a href="../../../cels/ad.html">advertisements</a> for Chinese Laundry Shoes</font></p> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Created web sites for <a href="http://www.begrafic.com/entergate/" target="_blank">Entergate Communications</a>, <a href="http://www.begrafic.com/gilbertwest/" target="_blank">Gilbert USA</a>, <a href="http://www.jacketfactory.com" target="_blank">Basicline Manufacturing</a></font></p> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Provided concept and production of page layouts and logo designs for Division of Geological and Planetary Sciences, and Seismological Laboratory at Caltech </font> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Developed site structure and page layout designs to launch first-ever web site for California Institute of Technology</font> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Served as editor and designer of the first ever GPS <a href="../../alumnews.html">Alumni Newsletter</a> </font> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Instructed staff, faculty, and students in computer training class (image/text scanning, html, software and hardware applications, UNIX, ftp, and Telnet)</font> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> Designed recruitment materials such as brochure, ads, lectureship/seminar flyers, invitations, and building signage for GPS</font> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> Managed installation, filing system, hardware configuration and troubleshooting of new computer systems </font> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Designed <a href="../../../rand.html">math assessment</a> comps for RAND</font> </td> </tr> <tr> <td colspan=3 align=left valign=top><img src="../../images/history.gif" width=210 height=28 alt="additional computer skills"> </td> <td width="271"></td> </tr> <tr> <td width="57"></td> <td colspan=3 valign="top"> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">AUGUST 2000 - PRESENT<br> Design Consultant - Begrafic.com, San Luis Obispo</font></p> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">APRIL 2000 - JULY 2000<br> Sr. Web Designer - ShopSports.com, San Luis Obispo</font></p> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">OCTOBER 1999 - APRIL 2000<br> Web Designer - Event411.com, Marina Del Rey</font></p> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">NOVEMBER 1998 - OCTOBER 1999<br> Freelance Webmaster, Designer, Los Angeles </font> </p> <p> <font size="2" face="Verdana, Arial, Helvetica, sans-serif">AUGUST 1998 - NOVEMBER 1998<br> Webmaster, Designer - SFUSD Language Academy, San Francisco </font> <p> <font size="2" face="Verdana, Arial, Helvetica, sans-serif">MAY 1998 - AUGUST 1998<br> Scheduling Coordinator - Netscape Communications, Mountain View </font> <p> <font size="2" face="Verdana, Arial, Helvetica, sans-serif">DECEMBER 1993 - MARCH 1998<br> Webmaster, Designer - Division of Geological and Planetary Sciences<br> California Institute of Technology, Pasadena </font> <p> <font size="2" face="Verdana, Arial, Helvetica, sans-serif">APRIL 1992 - JUNE 1993<br> Program Representative<br> American Language Center, UCLA Extension, Los Angeles </font> <p> </td> </tr> <tr> <td colspan=3 align=center valign=top><img src="../../images/education.gif" width=211 height=26 alt="education"> </td> <td width="271"></td> <tr> <td width="57"></td> <td colspan=3 valign="top"> <ol> <font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>Bachelor of Arts, Journalism/Public Relations, Spanish Minor<br> California State University, Long Beach - December 1991</b> </font> </ol> <blockquote> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>Art Center College of Design, Pasadena - 1995 to 1997</b></font></p> </blockquote> <ol> <blockquote> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> QuarkXPress<br> Web Design Seminar<br> Computer Imaging<br> Photography<br> Design with Computers<br> Package Design<br> Web Site Development </font></p> </blockquote> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>Conferences:</b> </font></p> <blockquote> <p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> Thunder Lizard Productions Photoshop, Monterey (1998)<br> Thunder Lizard Productions Web Design, Seattle (1997)<br> NetObjects Fusion, San Diego (1997) <br> </font> </p> </blockquote> <p>&nbsp;</p> </ol> </td> </tr> </table> <p><IMG SRC="http://www.begrafic.com/cgi-bin/makelog.pl?teachresume,http://www.begrafic.com/resume/resume_teaching.html"> </p> </center> </body> </html>
10,853
10,853
0.5932
af41b8292d960cd01b4e5240250d4af4dd103aae
996
rb
Ruby
spec/lib/fantasy-event_spec.rb
donSchoe/fantasy-irc
d2b6daa4be9a48d548b09738d43c9fbaff98129a
[ "MIT" ]
1
2015-11-10T13:03:12.000Z
2015-11-10T13:03:12.000Z
spec/lib/fantasy-event_spec.rb
donSchoe/fantasy-irc
d2b6daa4be9a48d548b09738d43c9fbaff98129a
[ "MIT" ]
4
2016-02-07T02:23:54.000Z
2021-04-03T13:49:52.000Z
spec/lib/fantasy-event_spec.rb
donSchoe/fantasy-irc
d2b6daa4be9a48d548b09738d43c9fbaff98129a
[ "MIT" ]
1
2016-02-07T02:13:56.000Z
2016-02-07T02:13:56.000Z
require 'spec_helper' describe Fantasy::Event do describe Fantasy::Event::Event do describe "#new" do it "takes a name as arument and returns a Fantasy::Event::Event object" do e = Fantasy::Event::Event.new("rspec_event") e.should be_an_instance_of Fantasy::Event::Event end end end describe Fantasy::Event::Factory do before :each do @fac = Fantasy::Event::Factory.new end describe "#new" do it "takes no arguments and returns a Fantasy::Event::Factory object" do @fac.should be_an_instance_of Fantasy::Event::Factory end end describe "create" do it "takes a name as arument, creates a new event with this name in lowercase and returns it" do event = @fac.create("rspec_event") event.should be_an_instance_of Fantasy::Event::Event end end end end
31.125
107
0.582329
e7e82052be7f7b60018df8e2041434f37eb840c1
13,410
swift
Swift
Storefront/CollectionsViewController.swift
CareUSolutions/mobile-buy-sdk-ios-sample
681abc0389a5c97a540e898b4b69e927fb33cdc6
[ "MIT" ]
null
null
null
Storefront/CollectionsViewController.swift
CareUSolutions/mobile-buy-sdk-ios-sample
681abc0389a5c97a540e898b4b69e927fb33cdc6
[ "MIT" ]
null
null
null
Storefront/CollectionsViewController.swift
CareUSolutions/mobile-buy-sdk-ios-sample
681abc0389a5c97a540e898b4b69e927fb33cdc6
[ "MIT" ]
null
null
null
// // CollectionsViewController.swift // Storefront // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // 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 UIKit import SwiftUI import Buy final class CollectionsViewController: UIViewController { @IBOutlet weak var tableView: StorefrontTableView! fileprivate var collections: PageableArray<CollectionViewModel>! // ---------------------------------- // MARK: - View Loading - // override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: "logo") navigationItem.titleView = UIImageView(image: image) self.configureTableView() self.fetchCollections() } private func configureTableView() { self.tableView.paginationDelegate = self if self.traitCollection.forceTouchCapability == .available { self.registerForPreviewing(with: self, sourceView: self.tableView) } // introduction // about us xib config let nib = UINib.init(nibName: "TestCell", bundle: nil) self.tableView.register(nib, forCellReuseIdentifier: "cell") // video xib config let nibVideo = UINib.init(nibName: "VideoCell", bundle: nil) self.tableView.register(nibVideo, forCellReuseIdentifier: "videoCell") // team xib config let nibTeam = UINib.init(nibName: "TeamCell", bundle: nil) self.tableView.register(nibTeam, forCellReuseIdentifier: "teamCell") // contact xib config let nibContact = UINib.init(nibName: "ContactCell", bundle: nil) self.tableView.register(nibContact, forCellReuseIdentifier: "contactCell") // item cell let nibItem = UINib.init(nibName: "ItemCell", bundle: nil) self.tableView.register(nibItem, forCellReuseIdentifier: "itemCell") } // ---------------------------------- // MARK: - Fetching - // fileprivate func fetchCollections(after cursor: String? = nil) { Client.shared.fetchCollections(after: cursor) { collections in if let collections = collections { self.collections = collections self.tableView.reloadData() } } } // ---------------------------------- // MARK: - View Controllers - // func productsViewControllerWith(_ collection: CollectionViewModel) -> ProductsViewController { let controller: ProductsViewController = self.storyboard!.instantiateViewController() controller.collection = collection return controller } func productDetailsViewControllerWith(_ product: ProductViewModel) -> ProductDetailsViewController { let controller: ProductDetailsViewController = self.storyboard!.instantiateViewController() controller.product = product return controller } } // ---------------------------------- // MARK: - Actions - // extension CollectionsViewController { @IBAction private func accountAction(_ sender: UIBarButtonItem) { let coordinator: CustomerCoordinator = self.storyboard!.instantiateViewController() self.present(coordinator, animated: true, completion: nil) } @IBAction private func cartAction(_ sender: Any) { let cartController: CartNavigationController = self.storyboard!.instantiateViewController() self.navigationController!.present(cartController, animated: true, completion: nil) } } // ---------------------------------- // MARK: - UIViewControllerPreviewingDelegate - // extension CollectionsViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { // // let tableView = previewingContext.sourceView as! UITableView // if let indexPath = tableView.indexPathForRow(at: location) { // // let cell = tableView.cellForRow(at: indexPath) as! CollectionCell // let touch = cell.convert(location, from: tableView) // // if let productResult = cell.productFor(touch) { // previewingContext.sourceRect = tableView.convert(productResult.sourceRect, from: cell) // return self.productDetailsViewControllerWith(productResult.model) // // } else if let collectionResult = cell.collectionFor(touch) { // previewingContext.sourceRect = tableView.convert(collectionResult.sourceRect, from: cell) // return self.productsViewControllerWith(collectionResult.model) // } // } return nil } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { // self.navigationController!.show(viewControllerToCommit, sender: self) } } // ---------------------------------- // MARK: - StorefrontTableViewDelegate - // extension CollectionsViewController: StorefrontTableViewDelegate { func tableViewShouldBeginPaging(_ table: StorefrontTableView) -> Bool { return self.collections?.hasNextPage ?? false } func tableViewWillBeginPaging(_ table: StorefrontTableView) { if let collections = self.collections, let lastCollection = collections.items.last { Client.shared.fetchCollections(after: lastCollection.cursor) { collections in if let collections = collections { self.collections.appendPage(from: collections) self.tableView.reloadData() self.tableView.completePaging() } } } } func tableViewDidCompletePaging(_ table: StorefrontTableView) { } } // ---------------------------------- // MARK: - CollectionCellDelegate - // extension CollectionsViewController: CollectionCellDelegate { func cell(_ collectionCell: CollectionCell, didRequestProductsIn collection: CollectionViewModel, after product: ProductViewModel) { Client.shared.fetchProducts(in: collection, limit: 20, after: product.cursor) { products in if let products = products, collectionCell.viewModel === collection { collectionCell.appendProductsPage(from: products) } } } func cell(_ collectionCell: CollectionCell, didSelectProduct product: ProductViewModel) { let detailsController: ProductDetailsViewController = self.storyboard!.instantiateViewController() detailsController.product = product self.navigationController!.show(detailsController, sender: self) } } // ---------------------------------- // MARK: - UICollectionViewDataSource - // extension CollectionsViewController: UITableViewDataSource { // ---------------------------------- // MARK: - Data - // func numberOfSections(in tableView: UITableView) -> Int { return self.collections?.items.count ?? 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 + self.collections.items[0].products.items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let collection = self.collections.items[0] let numberOfItems = collection.products.items.count let n = numberOfItems switch indexPath.row { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: CollectionCell.className, for: indexPath) as! CollectionCell let collection = self.collections.items[indexPath.section] cell.delegate = self cell.configureFrom(collection) return cell case 1 + n: let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TestCell cell.setTitle(title: "ABOUT US") cell.setContent(content: "Our company grew originally from the need and desire to serve our neighbors and Communities. The founders of CareU responded to the need for personal protection from their neighborhood organizations and first responders within their Community during the onset of the pandemic we still face. Understanding the larger needs of personal protection CareU was created.") let newImage = UIImage(named: "about-pic") cell.setImage(image: newImage!) return cell case 2 + n: let cell = tableView.dequeueReusableCell(withIdentifier: "videoCell", for: indexPath) as! VideoCell return cell case 3 + n: let cell = tableView.dequeueReusableCell(withIdentifier: "teamCell", for: indexPath) as! TeamCell let image1 = UIImage(named: "team1") let image2 = UIImage(named: "team2") let image3 = UIImage(named: "team3") let image4 = UIImage(named: "team4") cell.setImages(inputImage1: image1!, inputImage2: image2!, inputImage3: image3!, inputImage4: image4!) let name1 = "Mr. Louis Lam" let name2 = "Mrs. Ying Chen" let name3 = "Mr. Gerald Green" let name4 = "Lisa Wang" cell.setNames(inputName1: name1, inputName2: name2, inputName3: name3, inputName4: name4) cell.setTitle(title: "TEAM") return cell case 4 + n: let cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath) as! ContactCell return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath) as! ItemCell let product = collection.products.items[indexPath.row - 1] let title = product.title let summary = product.summary.interpretAsHTML(font: "Apple SD Gothic Neo", size: 13.0) let imageUrl = product.images.items.first?.url cell.configProduct(title, summary!, imageUrl!) cell.setMaskLogo(indexPath.row) let detailsController: ProductDetailsViewController = self.storyboard!.instantiateViewController() detailsController.product = product cell.setDetailController(detailsController) cell.setNavi(navController: self.navigationController!) return cell } } // ---------------------------------- // MARK: - Titles - // func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.collections.items[section].title } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return self.collections.items[section].description } // ---------------------------------- // MARK: - Height - // func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let width = tableView.bounds.width let height = width * 0.75 // 3:4 ratio return height + 150.0 // 150 is the height of the product collection } } // ---------------------------------- // MARK: - UICollectionViewDelegate - // extension CollectionsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let collection = self.collections.items[indexPath.section] let productsController = self.productsViewControllerWith(collection) if (indexPath.row == 0) { self.navigationController!.show(productsController, sender: self) } else if (indexPath.row <= collection.products.items.count) { let collection = self.collections.items[0] let product = collection.products.items[indexPath.row - 1] let detailsController: ProductDetailsViewController = self.storyboard!.instantiateViewController() detailsController.product = product self.navigationController!.show(detailsController, sender: self) } } }
41.775701
403
0.639896
414deb82abcb88c4dc8f0ab718093622e3175e0e
484
kt
Kotlin
src/ii_collections/n16FlatMap.kt
gokhanaliccii/kotlin-koans
afc7a4e95af680859b0c512397b7a9d718d5fcb7
[ "MIT" ]
null
null
null
src/ii_collections/n16FlatMap.kt
gokhanaliccii/kotlin-koans
afc7a4e95af680859b0c512397b7a9d718d5fcb7
[ "MIT" ]
null
null
null
src/ii_collections/n16FlatMap.kt
gokhanaliccii/kotlin-koans
afc7a4e95af680859b0c512397b7a9d718d5fcb7
[ "MIT" ]
null
null
null
package ii_collections import java.util.* fun example() { val result = listOf("abc", "12").flatMap { it.toList() } result == listOf('a', 'b', 'c', '1', '2') } val Customer.orderedProducts: Set<Product> get() { val flatMap = this.orders.flatMap { it.products } return flatMap.toSet() } val Shop.allOrderedProducts: Set<Product> get() { return this.customers.flatMap { it.orders } .flatMap { it.products }.toSet() }
21.043478
60
0.588843
4db014f1f9a51a83c1a3454ad0c39df3ab0ebc7a
6,613
kt
Kotlin
app/src/main/java/com/albertkhang/vietnamdateconverter/MainActivity.kt
albertkhang/VietnamDateConverter
c67f7f4f0ff050c0b31e8dd9cff682f0aae29a8e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/albertkhang/vietnamdateconverter/MainActivity.kt
albertkhang/VietnamDateConverter
c67f7f4f0ff050c0b31e8dd9cff682f0aae29a8e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/albertkhang/vietnamdateconverter/MainActivity.kt
albertkhang/VietnamDateConverter
c67f7f4f0ff050c0b31e8dd9cff682f0aae29a8e
[ "Apache-2.0" ]
null
null
null
package com.albertkhang.vietnamdateconverter import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import com.albertkhang.vietnamdateconverter.utils.LunarDate import com.albertkhang.vietnamdateconverter.utils.SolarDate import java.util.* class MainActivity : AppCompatActivity() { private lateinit var btnConvert: Button private lateinit var vietnamDateConverter: VietnamDateConverter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) addControl() addEvent() } private fun addControl() { btnConvert = findViewById(R.id.btnConvert) vietnamDateConverter = VietnamDateConverter.getInstance() } private fun addEvent() { btnConvert.setOnClickListener { // testGetLunarDate() // testGetSolarDate() // testGetCanChiDate() // testGetWeekdays() // testGetCanChiHour() // testGetSolarTerm() // testZodiacHour() } btnConvert.callOnClick() } private fun testZodiacHour() { val GET_ZODIACHOUR_LOG = "testZodiacHourLog" val solarDate = SolarDate() Log.d(GET_ZODIACHOUR_LOG, solarDate.toString()) val lunarDate = vietnamDateConverter.getLunarDate(solarDate) Log.d(GET_ZODIACHOUR_LOG, lunarDate.toString()) val zh1 = vietnamDateConverter.getZodiacHour() Log.d(GET_ZODIACHOUR_LOG, "zh1: ") zh1.forEach { Log.d(GET_ZODIACHOUR_LOG, it.toString()) } val zh2 = vietnamDateConverter.getZodiacHour(solarDate) Log.d(GET_ZODIACHOUR_LOG, "zh2: ") zh2.forEach { Log.d(GET_ZODIACHOUR_LOG, it.toString()) } val zh3 = vietnamDateConverter.getZodiacHour(lunarDate) Log.d(GET_ZODIACHOUR_LOG, "zh3: ") zh3.forEach { Log.d(GET_ZODIACHOUR_LOG, it.toString()) } val zh4 = vietnamDateConverter.getZodiacHour(23, 3, 2020) Log.d(GET_ZODIACHOUR_LOG, "zh4: ") zh4.forEach { Log.d(GET_ZODIACHOUR_LOG, it.toString()) } } private fun testGetSolarTerm() { val GET_SOLARTERM_LOG = "testGetSolarTermLog" val solarDate = SolarDate() Log.d(GET_SOLARTERM_LOG, solarDate.toString()) val lunarDate = vietnamDateConverter.getLunarDate(solarDate) Log.d(GET_SOLARTERM_LOG, lunarDate.toString()) val st1 = vietnamDateConverter.getSolarTerm() Log.d(GET_SOLARTERM_LOG, "st1: $st1") val st2 = vietnamDateConverter.getSolarTerm(solarDate) Log.d(GET_SOLARTERM_LOG, "st2: $st2") val st3 = vietnamDateConverter.getSolarTerm(lunarDate) Log.d(GET_SOLARTERM_LOG, "st3: $st3") val st4 = vietnamDateConverter.getSolarTerm(23, 3, 2020) Log.d(GET_SOLARTERM_LOG, "st4: $st4") } private fun testGetCanChiHour() { val GET_CANCHIHOUR_LOG = "testGetCanChiHourLog" val solarDate = SolarDate() Log.d(GET_CANCHIHOUR_LOG, solarDate.toString()) val lunarDate = vietnamDateConverter.getLunarDate(solarDate) Log.d(GET_CANCHIHOUR_LOG, lunarDate.toString()) val hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) //TODO: using HOUR_OF_DAY not HOUR Log.d(GET_CANCHIHOUR_LOG, hour.toString()) val minute = Calendar.getInstance().get(Calendar.MINUTE) Log.d(GET_CANCHIHOUR_LOG, minute.toString()) val cch1 = vietnamDateConverter.getCanChiHour() Log.d(GET_CANCHIHOUR_LOG, "cch1: $cch1") val cch2 = vietnamDateConverter.getCanChiHour(hour, minute) Log.d(GET_CANCHIHOUR_LOG, "cch2: $cch2") val cch3 = vietnamDateConverter.getCanChiHour(hour, minute, solarDate) Log.d(GET_CANCHIHOUR_LOG, "cch3: $cch3") val cch4 = vietnamDateConverter.getCanChiHour(hour, minute, lunarDate) Log.d(GET_CANCHIHOUR_LOG, "cch4: $cch4") val cch5 = vietnamDateConverter.getCanChiHour(hour, minute, 23, 3, 2020) Log.d(GET_CANCHIHOUR_LOG, "cch5: $cch5") } private fun testGetWeekdays() { val GET_WEEKDAYS_LOG = "testGetWeekdaysLog" val solarDate = SolarDate() Log.d(GET_WEEKDAYS_LOG, solarDate.toString()) val lunarDate = vietnamDateConverter.getLunarDate(solarDate) Log.d(GET_WEEKDAYS_LOG, lunarDate.toString()) val wd1 = vietnamDateConverter.getWeekdays() Log.d(GET_WEEKDAYS_LOG, "wd1: $wd1") val wd2 = vietnamDateConverter.getWeekdays(solarDate) Log.d(GET_WEEKDAYS_LOG, "wd2: $wd2") val wd3 = vietnamDateConverter.getWeekdays(lunarDate) Log.d(GET_WEEKDAYS_LOG, "wd3: $wd3") val wd4 = vietnamDateConverter.getWeekdays(23, 3, 2020) Log.d(GET_WEEKDAYS_LOG, "wd4: $wd4") } private fun testGetCanChiDate() { val GET_CANCHI_LOG = "testGetCanChiDateLog" val solarDate = SolarDate() Log.d(GET_CANCHI_LOG, solarDate.toString()) val lunarDate = vietnamDateConverter.getLunarDate(solarDate) Log.d(GET_CANCHI_LOG, lunarDate.toString()) val cd1 = vietnamDateConverter.getCanChiDate() Log.d(GET_CANCHI_LOG, "cd1: $cd1") val cd2 = vietnamDateConverter.getCanChiDate(lunarDate) Log.d(GET_CANCHI_LOG, "cd2: $cd2") val cd3 = vietnamDateConverter.getCanChiDate(solarDate) Log.d(GET_CANCHI_LOG, "cd3: $cd3") val cd4 = vietnamDateConverter.getCanChiDate(solarDate.day, solarDate.month, solarDate.year) Log.d(GET_CANCHI_LOG, "cd4: $cd4") } private fun testGetSolarDate() { val GET_SOLAR_LOG = "testGetSolarDateLog" val lunarDate = LunarDate(30, 2, 2020) Log.d(GET_SOLAR_LOG, lunarDate.toString()) val sd1 = vietnamDateConverter.getSolarDate(lunarDate) Log.d(GET_SOLAR_LOG, "sd1: $sd1") val sd2 = vietnamDateConverter.getSolarDate(30, 2, 2020) Log.d(GET_SOLAR_LOG, "sd2: $sd2") } private fun testGetLunarDate() { val GET_LUNAR_LOG = "testGetLunarDateLog" val solarDate = SolarDate() Log.d(GET_LUNAR_LOG, solarDate.toString()) val ld1 = vietnamDateConverter.getLunarDate() Log.d(GET_LUNAR_LOG, "ld1: $ld1") val ld2 = vietnamDateConverter.getLunarDate(solarDate) Log.d(GET_LUNAR_LOG, "ld2: $ld2") val ld3 = vietnamDateConverter.getLunarDate(23, 3, 2020) Log.d(GET_LUNAR_LOG, "ld3: $ld3") } }
32.737624
100
0.661727
35679c969bbbbc1c4fdd6024ff51c18c5d4024b1
88
sql
SQL
INDEX/PREF_AGENT_NAME.sql
MCZbase/DDL
2537cdbcc6037c263c605562994ff82505f33dc7
[ "Apache-2.0" ]
2
2020-06-24T21:23:27.000Z
2020-07-27T21:31:40.000Z
INDEX/PREF_AGENT_NAME.sql
MCZbase/DDL
2537cdbcc6037c263c605562994ff82505f33dc7
[ "Apache-2.0" ]
null
null
null
INDEX/PREF_AGENT_NAME.sql
MCZbase/DDL
2537cdbcc6037c263c605562994ff82505f33dc7
[ "Apache-2.0" ]
null
null
null
CREATE INDEX "PREF_AGENT_NAME" ON "AGENT" ("AGENT_ID", "PREFERRED_AGENT_NAME_ID")
29.333333
84
0.727273
281e9f8be04c9d6266d7edaaccde8a82669f3d01
1,752
rb
Ruby
Library/Homebrew/formula_versions.rb
ylht/brew
75a38b7187788b61461a0b76b7033bf96a33c1c1
[ "BSD-2-Clause" ]
34,807
2016-03-08T05:08:28.000Z
2022-03-31T18:48:38.000Z
Library/Homebrew/formula_versions.rb
jakechristman/brew
633202dac6be86b1cbae88e5640acfcb7d2ea743
[ "BSD-2-Clause" ]
9,228
2016-03-06T17:09:02.000Z
2022-03-31T17:04:42.000Z
Library/Homebrew/formula_versions.rb
jakechristman/brew
633202dac6be86b1cbae88e5640acfcb7d2ea743
[ "BSD-2-Clause" ]
10,309
2016-03-06T05:54:41.000Z
2022-03-31T20:32:32.000Z
# typed: true # frozen_string_literal: true require "formula" # Helper class for traversing a formula's previous versions. # # @api private class FormulaVersions include Context IGNORED_EXCEPTIONS = [ ArgumentError, NameError, SyntaxError, TypeError, FormulaSpecificationError, FormulaValidationError, ErrorDuringExecution, LoadError, MethodDeprecatedError ].freeze MAX_VERSIONS_DEPTH = 2 attr_reader :name, :path, :repository, :entry_name def initialize(formula) @name = formula.name @path = formula.path @repository = formula.tap.path @entry_name = @path.relative_path_from(repository).to_s @current_formula = formula @formula_at_revision = {} end def rev_list(branch) repository.cd do rev_list_cmd = ["git", "rev-list", "--abbrev-commit", "--remove-empty"] rev_list_cmd << "--first-parent" if repository != CoreTap.instance.path Utils.popen_read(*rev_list_cmd, branch, "--", entry_name) do |io| yield io.readline.chomp until io.eof? end end end def file_contents_at_revision(rev) repository.cd { Utils.popen_read("git", "cat-file", "blob", "#{rev}:#{entry_name}") } end def formula_at_revision(rev) Homebrew.raise_deprecation_exceptions = true yield @formula_at_revision[rev] ||= begin contents = file_contents_at_revision(rev) nostdout { Formulary.from_contents(name, path, contents, ignore_errors: true) } end rescue *IGNORED_EXCEPTIONS => e # We rescue these so that we can skip bad versions and # continue walking the history odebug "#{e} in #{name} at revision #{rev}", e.backtrace rescue FormulaUnavailableError nil ensure Homebrew.raise_deprecation_exceptions = false end end
28.258065
89
0.708904
f7ca55da9f10fbae355388288b570aa893065360
19,711
a51
Assembly
avengers/toolkit/compilers/asem-51/examples/boot51.a51
Arkh42/hardhack
33057b88cf6a782f201e2bfc84f1ad1359d9ddc7
[ "ECL-2.0" ]
1
2021-09-20T14:19:38.000Z
2021-09-20T14:19:38.000Z
avengers/toolkit/compilers/asem-51/examples/boot51.a51
Arkh42/hardhack
33057b88cf6a782f201e2bfc84f1ad1359d9ddc7
[ "ECL-2.0" ]
null
null
null
avengers/toolkit/compilers/asem-51/examples/boot51.a51
Arkh42/hardhack
33057b88cf6a782f201e2bfc84f1ad1359d9ddc7
[ "ECL-2.0" ]
null
null
null
; ************************* ; * B O O T - 5 1 * ; ************************* ; ; A Bootstrap Program for the MCS-51 Microcontroller Family ; ; Version 1.1 by W.W. Heinz 15. 12. 2002 ; ;----------------------------------------------------------------------- ; File boot51.inc contains the customization data for the target system: $INCLUDE(boot51.inc) ; (must be generated with the CUSTOMIZ program) ;ASCII characters: BEL EQU 7 ;beep BS EQU 8 ;backspace CR EQU 13 ;carriage return LF EQU 10 ;line feed DEL EQU 07FH ;delete CPROMPT EQU '>' ;command line prompt UPROMPT EQU ':' ;upload prompt DSEG AT 8 ;only register bank 0 is in use STACK: DS 28H ;stack starts right behind bank 0 CMDLIN: DS 47H ;command line buffer CMDMAX: DS 1 ;(last byte) CSEG AT STARTADDR ;on boards, where the EPROM doesn't start at address 0000H, ;first of all a long jump into the EPROM area may be required ;to remap memory: LJMP START ;on boards where the EPROM starts at address 0000H, the ;interrupt addresses should better be redirected to the ;area in extended RAM, where user programs start: REPT 20 LJMP $-STARTADDR+USERPROGS DS 5 ENDM ;Normally, 20 interrupt addresses should be enough. ;(The SIEMENS C517A has 17.) ;But you may insert some more, if required. ;(The Infineon C508 uses 20, but wastes 9 more!) ;this sign-on message is output after reset: SIGNON: DB CR,LF,CR,LF DB 'BOOT-51 V1.1' DB ' ' DB 'Copyright (c) 2002 by W.W. Heinz' DB CR,LF,0 START: ;start of bootstrap program CALL INITBG ;initialize baudrate generator MOV SCON,#072H ;UART mode 1, 8 bit, ignore garbage CALL DELAY ;let the UART have some clocks ... MOV DPTR,#SIGNON ;display sign-on message CALL STRING CALL INTERP ;call command line interpreter MOV SP,#7 ;better set to reset value PUSH DPL ;save start address of user program PUSH DPH ;on stack WARTEN: CALL CONOST ;wait until the UART is ready JZ WARTEN ;for the next character to send, CALL DELAY ;and the last bits have left the UART CALL STOPBG ;stop baudrate generator MOV DPTR,#0 ;set modified SFR to reset values: CLR A ;(if possible) MOV SCON,A MOV B,A MOV PSW,A RET ;up'n away (and SP --> 7) INTERP: ;command line interpreter CALL RDCOMM ;read command MOV R0,#CMDLIN ;command line start address INTER1: MOV A,@R0 ;end of command line reached ? JZ INTERP ;then read a new command CALL UPCASE ;convert character to upper case INC R0 ;point to next character CJNE A,#' ',INTER2 ;is it a blank ? JMP INTER1 ;then ignore it INTER2: MOV R7,A ;save character CALL NEWLIN ;new line MOV A,R7 ;command character CJNE A,#'U',INTER3 ;UPLOAD ? CALL NIXMER ;check for end of line JNZ INTER4 ;if no: input error CALL LDHEXF ;read Intel-HEX file JMP INTERP ;read a new command INTER3: CJNE A,#'G',INTER4 ;GOTO ? CALL EIN16 ;then read start address JZ INTER5 ;continue if o.k. INTER4: MOV R7,#ILLEGAL_COMMAND ;output error message otherwise CALL ERROUT ;ausgeben JMP INTERP ;and wait for a new command INTER5: MOV DPL,R5 ;load GOTO address into DPTR MOV DPH,R4 ;and return RET NIXMER: ;checks, whether there are only trailing blanks in ;the command line buffer starting from position R0. ;When this is the case, zero is returned in A, the next ;non-blank character otherwise with its position in R0. MOV A,@R0 ;load next character JZ NIXME1 ;if 0, end of line CJNE A,#' ',NIXME1 INC R0 ;if blank, next character JMP NIXMER NIXME1: RET RDCOMM: ;reads a command from the UART and stores it in the ;command line buffer at address CMDLIN in the internal ;RAM. The command line is terminated with a 0. CALL NEWLIN ;new line MOV A,#CPROMPT ;output prompt CALL CONOUT MOV R0,#CMDLIN ;address of command line buffer RDCOM1: MOV @R0,#0 ;always terminate buffer with a 0 CALL CONIN ;read character CJNE A,#CR,RDCOM2 ;if a CR has been input, RET ;the command is complete RDCOM2: CJNE A,#BS,RDCOM5 ;backspace ? RDCOM3: CJNE R0,#CMDLIN,RDCOM4 ;buffer empty ? JMP RDCOM1 ;then continue reading characters RDCOM4: MOV DPTR,#BACKSP ;otherwise delete last character CALL STRING DEC R0 JMP RDCOM1 RDCOM5: CJNE A,#DEL,RDCOM6 ;delete ? JMP RDCOM3 ;then delete last character, too RDCOM6: MOV R2,A ;save character CLR C ;is it a control character ? SUBB A,#' ' JC RDCOM1 ;then better ignore it MOV A,R2 SUBB A,#DEL ;is character >= 7F ? JNC RDCOM1 ;then ignore it too CJNE R0,#CMDMAX,RDCOM7 ;is buffer full ? MOV A,#BEL ;then beep CALL CONOUT JMP RDCOM1 ;and wait for further characters RDCOM7: MOV A,R2 ;echo character CALL CONOUT MOV A,R2 ;and append character to buffer MOV @R0,A INC R0 ;now its one more character JMP RDCOM1 ;wait for input characters BACKSP: DB BS,' ',BS,0 ;string to delete a character LDHEXF: ;reads an Intel-Hex file from the UART and loads it ;to its start address in the external RAM. ;When something has gone wrong, LDHEXF continues ;reading characters until it has received nothing ;for about 5 seconds (depending on clock frequency), ;and sends a corresponding error message. MOV A,#UPROMPT ;output upload prompt CALL CONOUT CALL UPLOAD ;load Intel-Hex file into external RAM MOV R7,A ;save error code JZ LDHEXM ;if no error, continue LDHEX1: MOV R0,#HIGH(TIMEBASE) ;otherwise wait for some seconds, MOV R1,#LOW(TIMEBASE) ;until no more characters are received MOV R2,#0 LDHEX2: CALL CONIST ;character received ? JZ LDHEX3 ;if not, continue CALL CONIN ;otherwise read character, JMP LDHEX1 ;and start from the beginning LDHEX3: NOP DJNZ R2,LDHEX2 DJNZ R1,LDHEX2 DJNZ R0,LDHEX2 LDHEXM: MOV A,R7 ;error code JZ LDHEX4 ;if no error, continue CALL ERRONL ;error message otherwise (code in R7) LDHEX4: RET ERRONL: ;outputs a new line and error message number R7. MOV DPTR,#ERRSTN SJMP ERROU1 ERROUT: ;outputs an error message with its number in R7. MOV DPTR,#ERRSTL ERROU1: CALL STRING MOV DPTR,#ERRTAB ;address of table of error messages MOV A,R7 ;error code RL A ;calculate address of error message MOVC A,@A+DPTR XCH A,R7 RL A INC A MOVC A,@A+DPTR MOV DPL,A MOV DPH,R7 CALL STRING ;output message MOV DPTR,#ERRSTR CALL STRING RET ;error codes: ILLEGAL_COMMAND EQU 0 ILLEGAL_HEXDIGIT EQU 1 CHECKSUM_ERROR EQU 2 UNEXPECTED_CHAR EQU 3 ILLEGAL_RECORDID EQU 4 ERRTAB: ;Table of error messages DW ILLCOM DW ILLHEX DW CKSERR DW UNXCHR DW ILLRID ;error messages: ILLCOM: DB 'illegal command',0 ILLHEX: DB 'illegal hex digit',0 CKSERR: DB 'checksum error',0 UNXCHR: DB 'unexpected character',0 ILLRID: DB 'illegal record ID',0 ERRSTN: DB CR,LF ERRSTL: DB '@@@@@ ',0 ERRSTR: DB ' @@@@@',0 UPLOAD: ;reads an Intel-Hex file from the UART and loads ;it to its start address in the external RAM. ;UPLOAD returns the following error codes in A: ; ; A = 0 hex file loaded correctly ; A = ILLEGAL_HEXDIGIT illegal hex digit ; A = CHECKSUM_ERROR checksum error ; A = UNEXPECTED_CHAR unexpected character ; A = ILLEGAL_RECORDID illegal record ID ; ;UPLOAD only changes registers A,B,DPTR,R0,R1,R2, and R7. CALL CONIN ;read characters CJNE A,#':',UPLOAD ;until a ":" is received UPLOA0: MOV R1,#0 ;initialize checksum CALL NEXTB ;convert next two characters to a byte JC UPLOA4 ;if they are no hex digits, error MOV R0,A ;save number of data bytes CALL NEXTB ;record address, HI byte JC UPLOA4 ;if no hex digits: error MOV DPH,A ;save HI byte CALL NEXTB ;record address, LO byte JC UPLOA4 ;if no hex digits: error MOV DPL,A ;save LO byte CALL NEXTB ;record ID JC UPLOA4 ;if no hex digits: error MOV R2,A ;save record ID MOV A,R0 ;number of data bytes JZ UPLOA2 ;if 0, probably EOF record UPLOA1: CALL NEXTB ;next data byte JC UPLOA4 ;if no hex digits: error MOVX @DPTR,A ;load it into external RAM INC DPTR ;next byte DJNZ R0,UPLOA1 ;until all data bytes are loaded UPLOA2: CALL NEXTB ;checksum JC UPLOA4 ;if no hex digits: error MOV A,R1 ;checksum = 0 ? JNZ UPLOA5 ;if no, checksum error MOV A,R2 ;record ID JNZ UPLOA3 ;if <> 0, probably EOF record CALL CONIN ;read character CJNE A,#CR,UPLOAU ;if no CR, may be UNIX style ASCII file CALL CONIN ;read next character CJNE A,#LF,UPLOA9 ;if no LF, may be ASCII upload with LF stripped UPLOA8: CALL CONIN ;read next character UPLOA9: CJNE A,#':',UPLOA6 ;if no ":", unexpected character JMP UPLOA0 ;read next HEX record UPLOAU: CJNE A,#LF,UPLOA6 ;if no LF, unexpected character JMP UPLOA8 UPLOA3: CJNE A,#1,UPLOA7 ;if <> 1, illegal record ID CALL CONIN ;read only final CR (RDCOMM ignores LF) CLR A ;hex file loaded, o.k. RET UPLOA4: MOV A,#ILLEGAL_HEXDIGIT ;illegal hex digit RET UPLOA5: MOV A,#CHECKSUM_ERROR ;checksum error RET UPLOA6: MOV A,#UNEXPECTED_CHAR ;unexpected character RET UPLOA7: MOV A,#ILLEGAL_RECORDID ;illegal record ID RET NEXTB: ;reads one byte in ASCII-hex representation from ;the UART and returns the binary value in A. ;The checksum in R1 is updated accordingly. ;(In case of error the carry flag is set.) ;NEXTB changes only registers A, B, R1 and R7. CALL CONIN ;read first hex digit CALL NIBBLE ;convert it to 4-bit binary JC NEXTBR ;stop, if error SWAP A ;otherwise move it to high order nibble MOV R7,A ;and save it CALL CONIN ;read second hex digit CALL NIBBLE ;convert it to 4-bit binary JC NEXTBR ;stop, if error ORL A,R7 ;join both nibbles XCH A,R1 ;add the whole byte ADD A,R1 ;to the checksum XCH A,R1 CLR C ;no error NEXTBR: RET ;finished, carry set if error EIN16: ;starting from the current line position R0, a 16-bit ;hex number is read from the command line buffer, and ;converted to a binary number which is returned in R4/R5. ;If no error was detected A=0 on return, A<>0 otherwise. MOV R6,#4 ;up to 4 digits CALL HEX16 ;convert to binary JNZ EIN16F ;error, if garbage CALL NIXMER ;check for end of line EIN16F: RET ;if garbage, error: A<>0 HEX16: ;starting from the current line position R0, a 16-bit ;hex number with up to R6 digits is read from the line ;buffer and converted to a binary number which is ;returned in R4/R5. ;If no error was detected A=0 on return, A<>0 otherwise. MOV A,@R0 ;read character JZ HEX16F ;error, if 0 CJNE A,#' ',HEX161 INC R0 ;skip leading blanks JMP HEX16 HEX161: MOV R4,#0 ;R4/R5 = 0 MOV R5,#0 CALL NIBBLE ;convert hex digit JC HEX16F ;error, when failed CALL SHIFT4 ;shift 4 bits into R4/R5 from the right side INC R0 ;next character DEC R6 HEX162: MOV A,@R0 ;read character CALL NIBBLE ;convert to hex digit JC HEX16R ;when failed, finished CALL SHIFT4 ;shift 4 bits into R4/R5 from the right side INC R0 ;next character DJNZ R6,HEX162 ;convert up to 4 hex digits HEX16R: CLR A ;o.k., number in R4/R5 RET HEX16F: MOV A,#0FFH ;conversion error RET NIBBLE: ;converts the hex digit in A into a 4-bit binary number ;which is returned in A. When the character is no hex ;digit, the carry flag is set on return. ;NIBBLE only changes registers A and B. CALL UPCASE ;convert character to upper case MOV B,A ;and save it CLR C ;is character < 0 ? SUBB A,#'0' JC NIBBLR ;then error MOV A,#'F' ;is character > F ? SUBB A,B JC NIBBLR ;then error, too MOV A,B ;is character <= 9 ? SUBB A,#('9'+1) JC NIBBL1 ;then decimal digit MOV A,B ;is character >= A ? SUBB A,#'A' JC NIBBLR ;if not, error NIBBL1: ADD A,#10 ;calculate binary number CLR C ;digit converted correctly NIBBLR: RET SHIFT4: ;shifts a 4-bit binary number in A into register ;pair R4/R5 (HI/LO) from the right side. SWAP A ;transfer nibble 4 bits to the left MOV R7,#6 ;Please do not ask for explaining THIS! SHIFT0: RLC A ; ==== XCH A,R5 RLC A XCH A,R4 DJNZ R7,SHIFT0 RET UPCASE: ;If the character in A is a lower case letter, it ;is converted to upper case and returned in A again. ;Otherwise it will be left unchanged. ;UPCASE only changes registers A and B. MOV B,A CLR C SUBB A,#'a' ;is character < a ? JC UPCRET ;then leave it unchanged MOV A,B SUBB A,#('z'+1) ;is character > z ? JNC UPCRET ;then leave it unchanged, too ADDC A,#'Z' ;otherwise convert it to upper case MOV B,A UPCRET: MOV A,B RET NEWLIN: ;outputs a new line. MOV A,#CR CALL CONOUT MOV A,#LF CALL CONOUT RET STRING: ;String output: start address in DPTR, terminated with 0. ;STRING only changes registers DPTR and A. CLR A MOVC A,@A+DPTR JZ STRRET CALL CONOUT CALL WMSEC ;Slow down output speed to about 9600 Baud! INC DPTR JMP STRING STRRET: RET CONOUT: ;output character in A. JNB TI,CONOUT ;wait for UART output buffer to become clear CLR TI MOV SBUF,A ;output character RET CONIN: ;read character and return it in A. JNB RI,CONIN MOV A,SBUF CLR RI ANL A,#07FH ;mask parity (if any) RET CONOST: ;output status: A=FF if ready, A=0 if not ready CLR A JNB TI,OSTRET ;wait for UART output buffer to become clear DEC A OSTRET: RET CONIST: ;input status: A=FF if character received, A=0 if not CLR A JNB RI,ISTRET ;no character received DEC A ISTRET: RET WMSEC: ;about 1 ms delay PUSH AR6 PUSH AR7 MOV R6,#HIGH(TIMEBASE) MOV R7,#LOW(TIMEBASE) WMSEC1: DJNZ R7,WMSEC1 DJNZ R6,WMSEC1 POP AR7 POP AR6 RET DELAY: ;wait for CHARTIME ms! ;CHARTIME is calculated to last for one byte sent by the UART. ;DELAY changes registers R6 and R7. MOV R6,#HIGH(CHARTIME) MOV R7,#LOW(CHARTIME) DELAY1: CALL WMSEC ;1 ms DJNZ R7,DELAY1 DJNZ R6,DELAY1 RET IFDEF INTEL8051 ;baudrate generator timer 1 INITBG: ;start baudrate generator timer 1 MOV TCON,#0 MOV TMOD,#020H MOV TH1,#RELOAD ANL PCON,#07FH ORL PCON,#SMOD SETB TR1 RET STOPBG: ;stop baudrate generator timer 1 CLR A MOV TCON,A MOV TMOD,A MOV TH1,A MOV TL1,A ANL PCON,#07FH RET ENDIF IFDEF INTEL8052 ;baudrate generator timer 2 T2CON DATA 0C8H RCAP2L DATA 0CAH RCAP2H DATA 0CBH TR2 BIT 0CAH INITBG: ;start baudrate generator timer 2 MOV T2CON,#030H MOV RCAP2H,#HIGH(RELOAD) MOV RCAP2L,#LOW(RELOAD) SETB TR2 RET STOPBG: ;stop baudrate generator timer 2 CLR A MOV T2CON,A MOV RCAP2H,A MOV RCAP2L,A RET ENDIF IFDEF SAB80535 ;internal 80535 baudrate generator BD BIT 0DFH INITBG: ;start internal 80535 baudrate generator ANL PCON,#07FH ORL PCON,#SMOD SETB BD RET STOPBG: ;stop internal 80535 baudrate generator CLR BD ANL PCON,#07FH RET ENDIF IFDEF SAB80C515A ;internal 80C535A baudrate generator SRELH DATA 0BAH SRELL DATA 0AAH BD BIT 0DFH INITBG: ;start internal 80C515A baudrate generator ANL PCON,#07FH ORL PCON,#SMOD MOV SRELH,#HIGH(RELOAD) MOV SRELL,#LOW(RELOAD) SETB BD RET STOPBG: ;stop internal 80C515A baudrate generator CLR BD MOV SRELH,#3 MOV SRELL,#0D9H ANL PCON,#07FH RET ENDIF IFDEF DS80C320 ;Dallas 80C320 timer 1 with clock/12 or clock/4 prescaler CKCON DATA 08EH INITBG: ;start 80C320 baudrate generator timer 1 MOV CKCON,#PRESCALE MOV TCON,#0 MOV TMOD,#020H MOV TH1,#RELOAD ANL PCON,#07FH ORL PCON,#SMOD SETB TR1 RET STOPBG: ;stop 80C320 baudrate generator timer 1 CLR A MOV TCON,A MOV TMOD,A MOV TH1,A MOV TL1,A ANL PCON,#07FH MOV CKCON,#1 RET ENDIF END
33.636519
74
0.549084
04ce7daebe682795b898e23bcb70f030dddbb313
287
sql
SQL
Employee table.sql
alex-d-bondarev/sql-practice
6b9c51c3102a48d093b14dff3078280d1aeaa77e
[ "MIT" ]
null
null
null
Employee table.sql
alex-d-bondarev/sql-practice
6b9c51c3102a48d093b14dff3078280d1aeaa77e
[ "MIT" ]
null
null
null
Employee table.sql
alex-d-bondarev/sql-practice
6b9c51c3102a48d093b14dff3078280d1aeaa77e
[ "MIT" ]
null
null
null
INSERT INTO `tutorial`.`employee` (`sJob`, `nSalary`, `company_id`, `user_id`) VALUES #('job1', 1000, 1, 8), #('job2', 2000, 1, 9), ('manager1', 3000, 1, 14), ('manager2', 5000, 3, 15), ('manager3', 1000, 3, 16); Delete from `tutorial`.`employee`; select * from `tutorial`.`employee`;
22.076923
44
0.616725
d250eb81fe7c00331cb5fdd8fa49c055143e2ecc
164
php
PHP
app/models/InventoryCategory.php
abdulawal/vault-designer-delivery
65861264370793747ac5577bb65eff0fb2a7c66d
[ "MIT" ]
null
null
null
app/models/InventoryCategory.php
abdulawal/vault-designer-delivery
65861264370793747ac5577bb65eff0fb2a7c66d
[ "MIT" ]
null
null
null
app/models/InventoryCategory.php
abdulawal/vault-designer-delivery
65861264370793747ac5577bb65eff0fb2a7c66d
[ "MIT" ]
null
null
null
<?php class InventoryCategory extends Eloquent { protected $guarded = array(); protected $table = 'inventory_category'; protected $primaryKey = 'id'; }
23.428571
44
0.695122
82eac4ea0f964295598ecb1f96bd5091e71847ac
656
kt
Kotlin
bloom/src/main/java/com/fjoglar/composechallenge/bloom/MainActivity.kt
fjoglar/jetpack-compose-challenge
435b20825ee38a11c7e5770269f2b2f049c73df8
[ "MIT" ]
null
null
null
bloom/src/main/java/com/fjoglar/composechallenge/bloom/MainActivity.kt
fjoglar/jetpack-compose-challenge
435b20825ee38a11c7e5770269f2b2f049c73df8
[ "MIT" ]
null
null
null
bloom/src/main/java/com/fjoglar/composechallenge/bloom/MainActivity.kt
fjoglar/jetpack-compose-challenge
435b20825ee38a11c7e5770269f2b2f049c73df8
[ "MIT" ]
null
null
null
package com.fjoglar.composechallenge.bloom import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.core.view.WindowCompat import com.fjoglar.composechallenge.bloom.navigation.BloomNavigation import com.fjoglar.composechallenge.bloom.ui.components.BloomTemplate class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) setContent { BloomTemplate { BloomNavigation() } } } }
29.818182
69
0.745427
518ea56b2fc2f577504b0e1940ddde8a48dad41e
47,744
asm
Assembly
rm.asm
philiphossu/CS450-xv6
d79ae29de77b5c21b303975b7d3d7ed1169f2707
[ "MIT-0" ]
null
null
null
rm.asm
philiphossu/CS450-xv6
d79ae29de77b5c21b303975b7d3d7ed1169f2707
[ "MIT-0" ]
null
null
null
rm.asm
philiphossu/CS450-xv6
d79ae29de77b5c21b303975b7d3d7ed1169f2707
[ "MIT-0" ]
2
2019-10-19T06:41:17.000Z
2021-11-27T23:18:33.000Z
_rm: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 57 push %edi 4: 56 push %esi int i; if(argc < 2){ 5: be 01 00 00 00 mov $0x1,%esi #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { a: 53 push %ebx b: 83 e4 f0 and $0xfffffff0,%esp e: 83 ec 10 sub $0x10,%esp 11: 8b 7d 08 mov 0x8(%ebp),%edi 14: 8b 45 0c mov 0xc(%ebp),%eax int i; if(argc < 2){ 17: 83 ff 01 cmp $0x1,%edi 1a: 8d 58 04 lea 0x4(%eax),%ebx 1d: 7e 3a jle 59 <main+0x59> 1f: 90 nop printf(2, "Usage: rm files...\n"); exit(); } for(i = 1; i < argc; i++){ if(unlink(argv[i]) < 0){ 20: 8b 03 mov (%ebx),%eax 22: 89 04 24 mov %eax,(%esp) 25: e8 c8 02 00 00 call 2f2 <unlink> 2a: 85 c0 test %eax,%eax 2c: 78 0f js 3d <main+0x3d> if(argc < 2){ printf(2, "Usage: rm files...\n"); exit(); } for(i = 1; i < argc; i++){ 2e: 83 c6 01 add $0x1,%esi 31: 83 c3 04 add $0x4,%ebx 34: 39 fe cmp %edi,%esi 36: 75 e8 jne 20 <main+0x20> printf(2, "rm: %s failed to delete\n", argv[i]); break; } } exit(); 38: e8 65 02 00 00 call 2a2 <exit> exit(); } for(i = 1; i < argc; i++){ if(unlink(argv[i]) < 0){ printf(2, "rm: %s failed to delete\n", argv[i]); 3d: 8b 03 mov (%ebx),%eax 3f: c7 44 24 04 9a 07 00 movl $0x79a,0x4(%esp) 46: 00 47: c7 04 24 02 00 00 00 movl $0x2,(%esp) 4e: 89 44 24 08 mov %eax,0x8(%esp) 52: e8 c9 03 00 00 call 420 <printf> break; 57: eb df jmp 38 <main+0x38> main(int argc, char *argv[]) { int i; if(argc < 2){ printf(2, "Usage: rm files...\n"); 59: c7 44 24 04 86 07 00 movl $0x786,0x4(%esp) 60: 00 61: c7 04 24 02 00 00 00 movl $0x2,(%esp) 68: e8 b3 03 00 00 call 420 <printf> exit(); 6d: e8 30 02 00 00 call 2a2 <exit> 72: 66 90 xchg %ax,%ax 74: 66 90 xchg %ax,%ax 76: 66 90 xchg %ax,%ax 78: 66 90 xchg %ax,%ax 7a: 66 90 xchg %ax,%ax 7c: 66 90 xchg %ax,%ax 7e: 66 90 xchg %ax,%ax 00000080 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 80: 55 push %ebp 81: 89 e5 mov %esp,%ebp 83: 8b 45 08 mov 0x8(%ebp),%eax 86: 8b 4d 0c mov 0xc(%ebp),%ecx 89: 53 push %ebx char *os; os = s; while((*s++ = *t++) != 0) 8a: 89 c2 mov %eax,%edx 8c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 90: 83 c1 01 add $0x1,%ecx 93: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 97: 83 c2 01 add $0x1,%edx 9a: 84 db test %bl,%bl 9c: 88 5a ff mov %bl,-0x1(%edx) 9f: 75 ef jne 90 <strcpy+0x10> ; return os; } a1: 5b pop %ebx a2: 5d pop %ebp a3: c3 ret a4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi aa: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000000b0 <strcmp>: int strcmp(const char *p, const char *q) { b0: 55 push %ebp b1: 89 e5 mov %esp,%ebp b3: 8b 55 08 mov 0x8(%ebp),%edx b6: 53 push %ebx b7: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) ba: 0f b6 02 movzbl (%edx),%eax bd: 84 c0 test %al,%al bf: 74 2d je ee <strcmp+0x3e> c1: 0f b6 19 movzbl (%ecx),%ebx c4: 38 d8 cmp %bl,%al c6: 74 0e je d6 <strcmp+0x26> c8: eb 2b jmp f5 <strcmp+0x45> ca: 8d b6 00 00 00 00 lea 0x0(%esi),%esi d0: 38 c8 cmp %cl,%al d2: 75 15 jne e9 <strcmp+0x39> p++, q++; d4: 89 d9 mov %ebx,%ecx d6: 83 c2 01 add $0x1,%edx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) d9: 0f b6 02 movzbl (%edx),%eax p++, q++; dc: 8d 59 01 lea 0x1(%ecx),%ebx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) df: 0f b6 49 01 movzbl 0x1(%ecx),%ecx e3: 84 c0 test %al,%al e5: 75 e9 jne d0 <strcmp+0x20> e7: 31 c0 xor %eax,%eax p++, q++; return (uchar)*p - (uchar)*q; e9: 29 c8 sub %ecx,%eax } eb: 5b pop %ebx ec: 5d pop %ebp ed: c3 ret ee: 0f b6 09 movzbl (%ecx),%ecx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) f1: 31 c0 xor %eax,%eax f3: eb f4 jmp e9 <strcmp+0x39> f5: 0f b6 cb movzbl %bl,%ecx f8: eb ef jmp e9 <strcmp+0x39> fa: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 00000100 <strlen>: return (uchar)*p - (uchar)*q; } uint strlen(char *s) { 100: 55 push %ebp 101: 89 e5 mov %esp,%ebp 103: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 106: 80 39 00 cmpb $0x0,(%ecx) 109: 74 12 je 11d <strlen+0x1d> 10b: 31 d2 xor %edx,%edx 10d: 8d 76 00 lea 0x0(%esi),%esi 110: 83 c2 01 add $0x1,%edx 113: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 117: 89 d0 mov %edx,%eax 119: 75 f5 jne 110 <strlen+0x10> ; return n; } 11b: 5d pop %ebp 11c: c3 ret uint strlen(char *s) { int n; for(n = 0; s[n]; n++) 11d: 31 c0 xor %eax,%eax ; return n; } 11f: 5d pop %ebp 120: c3 ret 121: eb 0d jmp 130 <memset> 123: 90 nop 124: 90 nop 125: 90 nop 126: 90 nop 127: 90 nop 128: 90 nop 129: 90 nop 12a: 90 nop 12b: 90 nop 12c: 90 nop 12d: 90 nop 12e: 90 nop 12f: 90 nop 00000130 <memset>: void* memset(void *dst, int c, uint n) { 130: 55 push %ebp 131: 89 e5 mov %esp,%ebp 133: 8b 55 08 mov 0x8(%ebp),%edx 136: 57 push %edi } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 137: 8b 4d 10 mov 0x10(%ebp),%ecx 13a: 8b 45 0c mov 0xc(%ebp),%eax 13d: 89 d7 mov %edx,%edi 13f: fc cld 140: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 142: 89 d0 mov %edx,%eax 144: 5f pop %edi 145: 5d pop %ebp 146: c3 ret 147: 89 f6 mov %esi,%esi 149: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000150 <strchr>: char* strchr(const char *s, char c) { 150: 55 push %ebp 151: 89 e5 mov %esp,%ebp 153: 8b 45 08 mov 0x8(%ebp),%eax 156: 53 push %ebx 157: 8b 55 0c mov 0xc(%ebp),%edx for(; *s; s++) 15a: 0f b6 18 movzbl (%eax),%ebx 15d: 84 db test %bl,%bl 15f: 74 1d je 17e <strchr+0x2e> if(*s == c) 161: 38 d3 cmp %dl,%bl 163: 89 d1 mov %edx,%ecx 165: 75 0d jne 174 <strchr+0x24> 167: eb 17 jmp 180 <strchr+0x30> 169: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 170: 38 ca cmp %cl,%dl 172: 74 0c je 180 <strchr+0x30> } char* strchr(const char *s, char c) { for(; *s; s++) 174: 83 c0 01 add $0x1,%eax 177: 0f b6 10 movzbl (%eax),%edx 17a: 84 d2 test %dl,%dl 17c: 75 f2 jne 170 <strchr+0x20> if(*s == c) return (char*)s; return 0; 17e: 31 c0 xor %eax,%eax } 180: 5b pop %ebx 181: 5d pop %ebp 182: c3 ret 183: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000190 <gets>: char* gets(char *buf, int max) { 190: 55 push %ebp 191: 89 e5 mov %esp,%ebp 193: 57 push %edi 194: 56 push %esi int i, cc; char c; for(i=0; i+1 < max; ){ 195: 31 f6 xor %esi,%esi return 0; } char* gets(char *buf, int max) { 197: 53 push %ebx 198: 83 ec 2c sub $0x2c,%esp int i, cc; char c; for(i=0; i+1 < max; ){ cc = read(0, &c, 1); 19b: 8d 7d e7 lea -0x19(%ebp),%edi gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 19e: eb 31 jmp 1d1 <gets+0x41> cc = read(0, &c, 1); 1a0: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 1a7: 00 1a8: 89 7c 24 04 mov %edi,0x4(%esp) 1ac: c7 04 24 00 00 00 00 movl $0x0,(%esp) 1b3: e8 02 01 00 00 call 2ba <read> if(cc < 1) 1b8: 85 c0 test %eax,%eax 1ba: 7e 1d jle 1d9 <gets+0x49> break; buf[i++] = c; 1bc: 0f b6 45 e7 movzbl -0x19(%ebp),%eax gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1c0: 89 de mov %ebx,%esi cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; 1c2: 8b 55 08 mov 0x8(%ebp),%edx if(c == '\n' || c == '\r') 1c5: 3c 0d cmp $0xd,%al for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; 1c7: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1) if(c == '\n' || c == '\r') 1cb: 74 0c je 1d9 <gets+0x49> 1cd: 3c 0a cmp $0xa,%al 1cf: 74 08 je 1d9 <gets+0x49> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1d1: 8d 5e 01 lea 0x1(%esi),%ebx 1d4: 3b 5d 0c cmp 0xc(%ebp),%ebx 1d7: 7c c7 jl 1a0 <gets+0x10> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1d9: 8b 45 08 mov 0x8(%ebp),%eax 1dc: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 1e0: 83 c4 2c add $0x2c,%esp 1e3: 5b pop %ebx 1e4: 5e pop %esi 1e5: 5f pop %edi 1e6: 5d pop %ebp 1e7: c3 ret 1e8: 90 nop 1e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000001f0 <stat>: int stat(char *n, struct stat *st) { 1f0: 55 push %ebp 1f1: 89 e5 mov %esp,%ebp 1f3: 56 push %esi 1f4: 53 push %ebx 1f5: 83 ec 10 sub $0x10,%esp int fd; int r; fd = open(n, O_RDONLY); 1f8: 8b 45 08 mov 0x8(%ebp),%eax 1fb: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 202: 00 203: 89 04 24 mov %eax,(%esp) 206: e8 d7 00 00 00 call 2e2 <open> if(fd < 0) 20b: 85 c0 test %eax,%eax stat(char *n, struct stat *st) { int fd; int r; fd = open(n, O_RDONLY); 20d: 89 c3 mov %eax,%ebx if(fd < 0) 20f: 78 27 js 238 <stat+0x48> return -1; r = fstat(fd, st); 211: 8b 45 0c mov 0xc(%ebp),%eax 214: 89 1c 24 mov %ebx,(%esp) 217: 89 44 24 04 mov %eax,0x4(%esp) 21b: e8 da 00 00 00 call 2fa <fstat> close(fd); 220: 89 1c 24 mov %ebx,(%esp) int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; r = fstat(fd, st); 223: 89 c6 mov %eax,%esi close(fd); 225: e8 a0 00 00 00 call 2ca <close> return r; 22a: 89 f0 mov %esi,%eax } 22c: 83 c4 10 add $0x10,%esp 22f: 5b pop %ebx 230: 5e pop %esi 231: 5d pop %ebp 232: c3 ret 233: 90 nop 234: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi int fd; int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; 238: b8 ff ff ff ff mov $0xffffffff,%eax 23d: eb ed jmp 22c <stat+0x3c> 23f: 90 nop 00000240 <atoi>: return r; } int atoi(const char *s) { 240: 55 push %ebp 241: 89 e5 mov %esp,%ebp 243: 8b 4d 08 mov 0x8(%ebp),%ecx 246: 53 push %ebx int n; n = 0; while('0' <= *s && *s <= '9') 247: 0f be 11 movsbl (%ecx),%edx 24a: 8d 42 d0 lea -0x30(%edx),%eax 24d: 3c 09 cmp $0x9,%al int atoi(const char *s) { int n; n = 0; 24f: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 254: 77 17 ja 26d <atoi+0x2d> 256: 66 90 xchg %ax,%ax n = n*10 + *s++ - '0'; 258: 83 c1 01 add $0x1,%ecx 25b: 8d 04 80 lea (%eax,%eax,4),%eax 25e: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 262: 0f be 11 movsbl (%ecx),%edx 265: 8d 5a d0 lea -0x30(%edx),%ebx 268: 80 fb 09 cmp $0x9,%bl 26b: 76 eb jbe 258 <atoi+0x18> n = n*10 + *s++ - '0'; return n; } 26d: 5b pop %ebx 26e: 5d pop %ebp 26f: c3 ret 00000270 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 270: 55 push %ebp char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 271: 31 d2 xor %edx,%edx return n; } void* memmove(void *vdst, void *vsrc, int n) { 273: 89 e5 mov %esp,%ebp 275: 56 push %esi 276: 8b 45 08 mov 0x8(%ebp),%eax 279: 53 push %ebx 27a: 8b 5d 10 mov 0x10(%ebp),%ebx 27d: 8b 75 0c mov 0xc(%ebp),%esi char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 280: 85 db test %ebx,%ebx 282: 7e 12 jle 296 <memmove+0x26> 284: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 288: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 28c: 88 0c 10 mov %cl,(%eax,%edx,1) 28f: 83 c2 01 add $0x1,%edx { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 292: 39 da cmp %ebx,%edx 294: 75 f2 jne 288 <memmove+0x18> *dst++ = *src++; return vdst; } 296: 5b pop %ebx 297: 5e pop %esi 298: 5d pop %ebp 299: c3 ret 0000029a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 29a: b8 01 00 00 00 mov $0x1,%eax 29f: cd 40 int $0x40 2a1: c3 ret 000002a2 <exit>: SYSCALL(exit) 2a2: b8 02 00 00 00 mov $0x2,%eax 2a7: cd 40 int $0x40 2a9: c3 ret 000002aa <wait>: SYSCALL(wait) 2aa: b8 03 00 00 00 mov $0x3,%eax 2af: cd 40 int $0x40 2b1: c3 ret 000002b2 <pipe>: SYSCALL(pipe) 2b2: b8 04 00 00 00 mov $0x4,%eax 2b7: cd 40 int $0x40 2b9: c3 ret 000002ba <read>: SYSCALL(read) 2ba: b8 05 00 00 00 mov $0x5,%eax 2bf: cd 40 int $0x40 2c1: c3 ret 000002c2 <write>: SYSCALL(write) 2c2: b8 10 00 00 00 mov $0x10,%eax 2c7: cd 40 int $0x40 2c9: c3 ret 000002ca <close>: SYSCALL(close) 2ca: b8 15 00 00 00 mov $0x15,%eax 2cf: cd 40 int $0x40 2d1: c3 ret 000002d2 <kill>: SYSCALL(kill) 2d2: b8 06 00 00 00 mov $0x6,%eax 2d7: cd 40 int $0x40 2d9: c3 ret 000002da <exec>: SYSCALL(exec) 2da: b8 07 00 00 00 mov $0x7,%eax 2df: cd 40 int $0x40 2e1: c3 ret 000002e2 <open>: SYSCALL(open) 2e2: b8 0f 00 00 00 mov $0xf,%eax 2e7: cd 40 int $0x40 2e9: c3 ret 000002ea <mknod>: SYSCALL(mknod) 2ea: b8 11 00 00 00 mov $0x11,%eax 2ef: cd 40 int $0x40 2f1: c3 ret 000002f2 <unlink>: SYSCALL(unlink) 2f2: b8 12 00 00 00 mov $0x12,%eax 2f7: cd 40 int $0x40 2f9: c3 ret 000002fa <fstat>: SYSCALL(fstat) 2fa: b8 08 00 00 00 mov $0x8,%eax 2ff: cd 40 int $0x40 301: c3 ret 00000302 <link>: SYSCALL(link) 302: b8 13 00 00 00 mov $0x13,%eax 307: cd 40 int $0x40 309: c3 ret 0000030a <mkdir>: SYSCALL(mkdir) 30a: b8 14 00 00 00 mov $0x14,%eax 30f: cd 40 int $0x40 311: c3 ret 00000312 <chdir>: SYSCALL(chdir) 312: b8 09 00 00 00 mov $0x9,%eax 317: cd 40 int $0x40 319: c3 ret 0000031a <dup>: SYSCALL(dup) 31a: b8 0a 00 00 00 mov $0xa,%eax 31f: cd 40 int $0x40 321: c3 ret 00000322 <getpid>: SYSCALL(getpid) 322: b8 0b 00 00 00 mov $0xb,%eax 327: cd 40 int $0x40 329: c3 ret 0000032a <sbrk>: SYSCALL(sbrk) 32a: b8 0c 00 00 00 mov $0xc,%eax 32f: cd 40 int $0x40 331: c3 ret 00000332 <sleep>: SYSCALL(sleep) 332: b8 0d 00 00 00 mov $0xd,%eax 337: cd 40 int $0x40 339: c3 ret 0000033a <uptime>: SYSCALL(uptime) 33a: b8 0e 00 00 00 mov $0xe,%eax 33f: cd 40 int $0x40 341: c3 ret 00000342 <myMemory>: SYSCALL(myMemory) 342: b8 16 00 00 00 mov $0x16,%eax 347: cd 40 int $0x40 349: c3 ret 0000034a <inodeTBWalker>: SYSCALL(inodeTBWalker) 34a: b8 17 00 00 00 mov $0x17,%eax 34f: cd 40 int $0x40 351: c3 ret 00000352 <deleteIData>: SYSCALL(deleteIData) 352: b8 18 00 00 00 mov $0x18,%eax 357: cd 40 int $0x40 359: c3 ret 0000035a <directoryWalker>: SYSCALL(directoryWalker) 35a: b8 19 00 00 00 mov $0x19,%eax 35f: cd 40 int $0x40 361: c3 ret 00000362 <compareWalkers>: SYSCALL(compareWalkers) 362: b8 1a 00 00 00 mov $0x1a,%eax 367: cd 40 int $0x40 369: c3 ret 0000036a <recoverFS>: SYSCALL(recoverFS) 36a: b8 1b 00 00 00 mov $0x1b,%eax 36f: cd 40 int $0x40 371: c3 ret 372: 66 90 xchg %ax,%ax 374: 66 90 xchg %ax,%ax 376: 66 90 xchg %ax,%ax 378: 66 90 xchg %ax,%ax 37a: 66 90 xchg %ax,%ax 37c: 66 90 xchg %ax,%ax 37e: 66 90 xchg %ax,%ax 00000380 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 380: 55 push %ebp 381: 89 e5 mov %esp,%ebp 383: 57 push %edi 384: 56 push %esi 385: 89 c6 mov %eax,%esi 387: 53 push %ebx 388: 83 ec 4c sub $0x4c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 38b: 8b 5d 08 mov 0x8(%ebp),%ebx 38e: 85 db test %ebx,%ebx 390: 74 09 je 39b <printint+0x1b> 392: 89 d0 mov %edx,%eax 394: c1 e8 1f shr $0x1f,%eax 397: 84 c0 test %al,%al 399: 75 75 jne 410 <printint+0x90> neg = 1; x = -xx; } else { x = xx; 39b: 89 d0 mov %edx,%eax static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 39d: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 3a4: 89 75 c0 mov %esi,-0x40(%ebp) x = -xx; } else { x = xx; } i = 0; 3a7: 31 ff xor %edi,%edi 3a9: 89 ce mov %ecx,%esi 3ab: 8d 5d d7 lea -0x29(%ebp),%ebx 3ae: eb 02 jmp 3b2 <printint+0x32> do{ buf[i++] = digits[x % base]; 3b0: 89 cf mov %ecx,%edi 3b2: 31 d2 xor %edx,%edx 3b4: f7 f6 div %esi 3b6: 8d 4f 01 lea 0x1(%edi),%ecx 3b9: 0f b6 92 ba 07 00 00 movzbl 0x7ba(%edx),%edx }while((x /= base) != 0); 3c0: 85 c0 test %eax,%eax x = xx; } i = 0; do{ buf[i++] = digits[x % base]; 3c2: 88 14 0b mov %dl,(%ebx,%ecx,1) }while((x /= base) != 0); 3c5: 75 e9 jne 3b0 <printint+0x30> if(neg) 3c7: 8b 55 c4 mov -0x3c(%ebp),%edx x = xx; } i = 0; do{ buf[i++] = digits[x % base]; 3ca: 89 c8 mov %ecx,%eax 3cc: 8b 75 c0 mov -0x40(%ebp),%esi }while((x /= base) != 0); if(neg) 3cf: 85 d2 test %edx,%edx 3d1: 74 08 je 3db <printint+0x5b> buf[i++] = '-'; 3d3: 8d 4f 02 lea 0x2(%edi),%ecx 3d6: c6 44 05 d8 2d movb $0x2d,-0x28(%ebp,%eax,1) while(--i >= 0) 3db: 8d 79 ff lea -0x1(%ecx),%edi 3de: 66 90 xchg %ax,%ax 3e0: 0f b6 44 3d d8 movzbl -0x28(%ebp,%edi,1),%eax 3e5: 83 ef 01 sub $0x1,%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 3e8: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 3ef: 00 3f0: 89 5c 24 04 mov %ebx,0x4(%esp) 3f4: 89 34 24 mov %esi,(%esp) 3f7: 88 45 d7 mov %al,-0x29(%ebp) 3fa: e8 c3 fe ff ff call 2c2 <write> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 3ff: 83 ff ff cmp $0xffffffff,%edi 402: 75 dc jne 3e0 <printint+0x60> putc(fd, buf[i]); } 404: 83 c4 4c add $0x4c,%esp 407: 5b pop %ebx 408: 5e pop %esi 409: 5f pop %edi 40a: 5d pop %ebp 40b: c3 ret 40c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi uint x; neg = 0; if(sgn && xx < 0){ neg = 1; x = -xx; 410: 89 d0 mov %edx,%eax 412: f7 d8 neg %eax int i, neg; uint x; neg = 0; if(sgn && xx < 0){ neg = 1; 414: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) 41b: eb 87 jmp 3a4 <printint+0x24> 41d: 8d 76 00 lea 0x0(%esi),%esi 00000420 <printf>: } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 420: 55 push %ebp 421: 89 e5 mov %esp,%ebp 423: 57 push %edi char *s; int c, i, state; uint *ap; state = 0; 424: 31 ff xor %edi,%edi } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 426: 56 push %esi 427: 53 push %ebx 428: 83 ec 3c sub $0x3c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 42b: 8b 5d 0c mov 0xc(%ebp),%ebx char *s; int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; 42e: 8d 45 10 lea 0x10(%ebp),%eax } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 431: 8b 75 08 mov 0x8(%ebp),%esi char *s; int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; 434: 89 45 d4 mov %eax,-0x2c(%ebp) for(i = 0; fmt[i]; i++){ 437: 0f b6 13 movzbl (%ebx),%edx 43a: 83 c3 01 add $0x1,%ebx 43d: 84 d2 test %dl,%dl 43f: 75 39 jne 47a <printf+0x5a> 441: e9 c2 00 00 00 jmp 508 <printf+0xe8> 446: 66 90 xchg %ax,%ax c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 448: 83 fa 25 cmp $0x25,%edx 44b: 0f 84 bf 00 00 00 je 510 <printf+0xf0> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 451: 8d 45 e2 lea -0x1e(%ebp),%eax 454: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 45b: 00 45c: 89 44 24 04 mov %eax,0x4(%esp) 460: 89 34 24 mov %esi,(%esp) c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ state = '%'; } else { putc(fd, c); 463: 88 55 e2 mov %dl,-0x1e(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 466: e8 57 fe ff ff call 2c2 <write> 46b: 83 c3 01 add $0x1,%ebx int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 46e: 0f b6 53 ff movzbl -0x1(%ebx),%edx 472: 84 d2 test %dl,%dl 474: 0f 84 8e 00 00 00 je 508 <printf+0xe8> c = fmt[i] & 0xff; if(state == 0){ 47a: 85 ff test %edi,%edi uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; 47c: 0f be c2 movsbl %dl,%eax if(state == 0){ 47f: 74 c7 je 448 <printf+0x28> if(c == '%'){ state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 481: 83 ff 25 cmp $0x25,%edi 484: 75 e5 jne 46b <printf+0x4b> if(c == 'd'){ 486: 83 fa 64 cmp $0x64,%edx 489: 0f 84 31 01 00 00 je 5c0 <printf+0x1a0> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 48f: 25 f7 00 00 00 and $0xf7,%eax 494: 83 f8 70 cmp $0x70,%eax 497: 0f 84 83 00 00 00 je 520 <printf+0x100> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 49d: 83 fa 73 cmp $0x73,%edx 4a0: 0f 84 a2 00 00 00 je 548 <printf+0x128> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 4a6: 83 fa 63 cmp $0x63,%edx 4a9: 0f 84 35 01 00 00 je 5e4 <printf+0x1c4> putc(fd, *ap); ap++; } else if(c == '%'){ 4af: 83 fa 25 cmp $0x25,%edx 4b2: 0f 84 e0 00 00 00 je 598 <printf+0x178> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4b8: 8d 45 e6 lea -0x1a(%ebp),%eax 4bb: 83 c3 01 add $0x1,%ebx 4be: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 4c5: 00 } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 4c6: 31 ff xor %edi,%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4c8: 89 44 24 04 mov %eax,0x4(%esp) 4cc: 89 34 24 mov %esi,(%esp) 4cf: 89 55 d0 mov %edx,-0x30(%ebp) 4d2: c6 45 e6 25 movb $0x25,-0x1a(%ebp) 4d6: e8 e7 fd ff ff call 2c2 <write> } else if(c == '%'){ putc(fd, c); } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); 4db: 8b 55 d0 mov -0x30(%ebp),%edx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4de: 8d 45 e7 lea -0x19(%ebp),%eax 4e1: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 4e8: 00 4e9: 89 44 24 04 mov %eax,0x4(%esp) 4ed: 89 34 24 mov %esi,(%esp) } else if(c == '%'){ putc(fd, c); } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); 4f0: 88 55 e7 mov %dl,-0x19(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4f3: e8 ca fd ff ff call 2c2 <write> int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4f8: 0f b6 53 ff movzbl -0x1(%ebx),%edx 4fc: 84 d2 test %dl,%dl 4fe: 0f 85 76 ff ff ff jne 47a <printf+0x5a> 504: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi putc(fd, c); } state = 0; } } } 508: 83 c4 3c add $0x3c,%esp 50b: 5b pop %ebx 50c: 5e pop %esi 50d: 5f pop %edi 50e: 5d pop %ebp 50f: c3 ret ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ state = '%'; 510: bf 25 00 00 00 mov $0x25,%edi 515: e9 51 ff ff ff jmp 46b <printf+0x4b> 51a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); 520: 8b 45 d4 mov -0x2c(%ebp),%eax 523: b9 10 00 00 00 mov $0x10,%ecx } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 528: 31 ff xor %edi,%edi } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); 52a: c7 04 24 00 00 00 00 movl $0x0,(%esp) 531: 8b 10 mov (%eax),%edx 533: 89 f0 mov %esi,%eax 535: e8 46 fe ff ff call 380 <printint> ap++; 53a: 83 45 d4 04 addl $0x4,-0x2c(%ebp) 53e: e9 28 ff ff ff jmp 46b <printf+0x4b> 543: 90 nop 544: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi } else if(c == 's'){ s = (char*)*ap; 548: 8b 45 d4 mov -0x2c(%ebp),%eax ap++; 54b: 83 45 d4 04 addl $0x4,-0x2c(%ebp) ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ s = (char*)*ap; 54f: 8b 38 mov (%eax),%edi ap++; if(s == 0) s = "(null)"; 551: b8 b3 07 00 00 mov $0x7b3,%eax 556: 85 ff test %edi,%edi 558: 0f 44 f8 cmove %eax,%edi while(*s != 0){ 55b: 0f b6 07 movzbl (%edi),%eax 55e: 84 c0 test %al,%al 560: 74 2a je 58c <printf+0x16c> 562: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 568: 88 45 e3 mov %al,-0x1d(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 56b: 8d 45 e3 lea -0x1d(%ebp),%eax ap++; if(s == 0) s = "(null)"; while(*s != 0){ putc(fd, *s); s++; 56e: 83 c7 01 add $0x1,%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 571: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 578: 00 579: 89 44 24 04 mov %eax,0x4(%esp) 57d: 89 34 24 mov %esi,(%esp) 580: e8 3d fd ff ff call 2c2 <write> } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 585: 0f b6 07 movzbl (%edi),%eax 588: 84 c0 test %al,%al 58a: 75 dc jne 568 <printf+0x148> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 58c: 31 ff xor %edi,%edi 58e: e9 d8 fe ff ff jmp 46b <printf+0x4b> 593: 90 nop 594: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 598: 8d 45 e5 lea -0x1b(%ebp),%eax } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 59b: 31 ff xor %edi,%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 59d: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 5a4: 00 5a5: 89 44 24 04 mov %eax,0x4(%esp) 5a9: 89 34 24 mov %esi,(%esp) 5ac: c6 45 e5 25 movb $0x25,-0x1b(%ebp) 5b0: e8 0d fd ff ff call 2c2 <write> 5b5: e9 b1 fe ff ff jmp 46b <printf+0x4b> 5ba: 8d b6 00 00 00 00 lea 0x0(%esi),%esi } else { putc(fd, c); } } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); 5c0: 8b 45 d4 mov -0x2c(%ebp),%eax 5c3: b9 0a 00 00 00 mov $0xa,%ecx } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 5c8: 66 31 ff xor %di,%di } else { putc(fd, c); } } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); 5cb: c7 04 24 01 00 00 00 movl $0x1,(%esp) 5d2: 8b 10 mov (%eax),%edx 5d4: 89 f0 mov %esi,%eax 5d6: e8 a5 fd ff ff call 380 <printint> ap++; 5db: 83 45 d4 04 addl $0x4,-0x2c(%ebp) 5df: e9 87 fe ff ff jmp 46b <printf+0x4b> while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ putc(fd, *ap); 5e4: 8b 45 d4 mov -0x2c(%ebp),%eax } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 5e7: 31 ff xor %edi,%edi while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ putc(fd, *ap); 5e9: 8b 00 mov (%eax),%eax #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 5eb: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 5f2: 00 5f3: 89 34 24 mov %esi,(%esp) while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ putc(fd, *ap); 5f6: 88 45 e4 mov %al,-0x1c(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 5f9: 8d 45 e4 lea -0x1c(%ebp),%eax 5fc: 89 44 24 04 mov %eax,0x4(%esp) 600: e8 bd fc ff ff call 2c2 <write> putc(fd, *s); s++; } } else if(c == 'c'){ putc(fd, *ap); ap++; 605: 83 45 d4 04 addl $0x4,-0x2c(%ebp) 609: e9 5d fe ff ff jmp 46b <printf+0x4b> 60e: 66 90 xchg %ax,%ax 00000610 <free>: static Header base; static Header *freep; void free(void *ap) { 610: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 611: a1 38 0a 00 00 mov 0xa38,%eax static Header base; static Header *freep; void free(void *ap) { 616: 89 e5 mov %esp,%ebp 618: 57 push %edi 619: 56 push %esi 61a: 53 push %ebx 61b: 8b 5d 08 mov 0x8(%ebp),%ebx Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 61e: 8b 08 mov (%eax),%ecx void free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; 620: 8d 53 f8 lea -0x8(%ebx),%edx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 623: 39 d0 cmp %edx,%eax 625: 72 11 jb 638 <free+0x28> 627: 90 nop if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 628: 39 c8 cmp %ecx,%eax 62a: 72 04 jb 630 <free+0x20> 62c: 39 ca cmp %ecx,%edx 62e: 72 10 jb 640 <free+0x30> 630: 89 c8 mov %ecx,%eax free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 632: 39 d0 cmp %edx,%eax if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 634: 8b 08 mov (%eax),%ecx free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 636: 73 f0 jae 628 <free+0x18> 638: 39 ca cmp %ecx,%edx 63a: 72 04 jb 640 <free+0x30> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 63c: 39 c8 cmp %ecx,%eax 63e: 72 f0 jb 630 <free+0x20> break; if(bp + bp->s.size == p->s.ptr){ 640: 8b 73 fc mov -0x4(%ebx),%esi 643: 8d 3c f2 lea (%edx,%esi,8),%edi 646: 39 cf cmp %ecx,%edi 648: 74 1e je 668 <free+0x58> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 64a: 89 4b f8 mov %ecx,-0x8(%ebx) if(p + p->s.size == bp){ 64d: 8b 48 04 mov 0x4(%eax),%ecx 650: 8d 34 c8 lea (%eax,%ecx,8),%esi 653: 39 f2 cmp %esi,%edx 655: 74 28 je 67f <free+0x6f> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 657: 89 10 mov %edx,(%eax) freep = p; 659: a3 38 0a 00 00 mov %eax,0xa38 } 65e: 5b pop %ebx 65f: 5e pop %esi 660: 5f pop %edi 661: 5d pop %ebp 662: c3 ret 663: 90 nop 664: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ bp->s.size += p->s.ptr->s.size; 668: 03 71 04 add 0x4(%ecx),%esi 66b: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 66e: 8b 08 mov (%eax),%ecx 670: 8b 09 mov (%ecx),%ecx 672: 89 4b f8 mov %ecx,-0x8(%ebx) } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ 675: 8b 48 04 mov 0x4(%eax),%ecx 678: 8d 34 c8 lea (%eax,%ecx,8),%esi 67b: 39 f2 cmp %esi,%edx 67d: 75 d8 jne 657 <free+0x47> p->s.size += bp->s.size; 67f: 03 4b fc add -0x4(%ebx),%ecx p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; freep = p; 682: a3 38 0a 00 00 mov %eax,0xa38 bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ p->s.size += bp->s.size; 687: 89 48 04 mov %ecx,0x4(%eax) p->s.ptr = bp->s.ptr; 68a: 8b 53 f8 mov -0x8(%ebx),%edx 68d: 89 10 mov %edx,(%eax) } else p->s.ptr = bp; freep = p; } 68f: 5b pop %ebx 690: 5e pop %esi 691: 5f pop %edi 692: 5d pop %ebp 693: c3 ret 694: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 69a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000006a0 <malloc>: return freep; } void* malloc(uint nbytes) { 6a0: 55 push %ebp 6a1: 89 e5 mov %esp,%ebp 6a3: 57 push %edi 6a4: 56 push %esi 6a5: 53 push %ebx 6a6: 83 ec 1c sub $0x1c,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6a9: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 6ac: 8b 1d 38 0a 00 00 mov 0xa38,%ebx malloc(uint nbytes) { Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6b2: 8d 48 07 lea 0x7(%eax),%ecx 6b5: c1 e9 03 shr $0x3,%ecx if((prevp = freep) == 0){ 6b8: 85 db test %ebx,%ebx malloc(uint nbytes) { Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6ba: 8d 71 01 lea 0x1(%ecx),%esi if((prevp = freep) == 0){ 6bd: 0f 84 9b 00 00 00 je 75e <malloc+0xbe> 6c3: 8b 13 mov (%ebx),%edx 6c5: 8b 7a 04 mov 0x4(%edx),%edi base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 6c8: 39 fe cmp %edi,%esi 6ca: 76 64 jbe 730 <malloc+0x90> 6cc: 8d 04 f5 00 00 00 00 lea 0x0(,%esi,8),%eax morecore(uint nu) { char *p; Header *hp; if(nu < 4096) 6d3: bb 00 80 00 00 mov $0x8000,%ebx 6d8: 89 45 e4 mov %eax,-0x1c(%ebp) 6db: eb 0e jmp 6eb <malloc+0x4b> 6dd: 8d 76 00 lea 0x0(%esi),%esi nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 6e0: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 6e2: 8b 78 04 mov 0x4(%eax),%edi 6e5: 39 fe cmp %edi,%esi 6e7: 76 4f jbe 738 <malloc+0x98> 6e9: 89 c2 mov %eax,%edx p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 6eb: 3b 15 38 0a 00 00 cmp 0xa38,%edx 6f1: 75 ed jne 6e0 <malloc+0x40> morecore(uint nu) { char *p; Header *hp; if(nu < 4096) 6f3: 8b 45 e4 mov -0x1c(%ebp),%eax 6f6: 81 fe 00 10 00 00 cmp $0x1000,%esi 6fc: bf 00 10 00 00 mov $0x1000,%edi 701: 0f 43 fe cmovae %esi,%edi 704: 0f 42 c3 cmovb %ebx,%eax nu = 4096; p = sbrk(nu * sizeof(Header)); 707: 89 04 24 mov %eax,(%esp) 70a: e8 1b fc ff ff call 32a <sbrk> if(p == (char*)-1) 70f: 83 f8 ff cmp $0xffffffff,%eax 712: 74 18 je 72c <malloc+0x8c> return 0; hp = (Header*)p; hp->s.size = nu; 714: 89 78 04 mov %edi,0x4(%eax) free((void*)(hp + 1)); 717: 83 c0 08 add $0x8,%eax 71a: 89 04 24 mov %eax,(%esp) 71d: e8 ee fe ff ff call 610 <free> return freep; 722: 8b 15 38 0a 00 00 mov 0xa38,%edx } freep = prevp; return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) 728: 85 d2 test %edx,%edx 72a: 75 b4 jne 6e0 <malloc+0x40> return 0; 72c: 31 c0 xor %eax,%eax 72e: eb 20 jmp 750 <malloc+0xb0> if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 730: 89 d0 mov %edx,%eax 732: 89 da mov %ebx,%edx 734: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi if(p->s.size == nunits) 738: 39 fe cmp %edi,%esi 73a: 74 1c je 758 <malloc+0xb8> prevp->s.ptr = p->s.ptr; else { p->s.size -= nunits; 73c: 29 f7 sub %esi,%edi 73e: 89 78 04 mov %edi,0x4(%eax) p += p->s.size; 741: 8d 04 f8 lea (%eax,%edi,8),%eax p->s.size = nunits; 744: 89 70 04 mov %esi,0x4(%eax) } freep = prevp; 747: 89 15 38 0a 00 00 mov %edx,0xa38 return (void*)(p + 1); 74d: 83 c0 08 add $0x8,%eax } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } } 750: 83 c4 1c add $0x1c,%esp 753: 5b pop %ebx 754: 5e pop %esi 755: 5f pop %edi 756: 5d pop %ebp 757: c3 ret base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ if(p->s.size == nunits) prevp->s.ptr = p->s.ptr; 758: 8b 08 mov (%eax),%ecx 75a: 89 0a mov %ecx,(%edx) 75c: eb e9 jmp 747 <malloc+0xa7> Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; 75e: c7 05 38 0a 00 00 3c movl $0xa3c,0xa38 765: 0a 00 00 base.s.size = 0; 768: ba 3c 0a 00 00 mov $0xa3c,%edx Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; 76d: c7 05 3c 0a 00 00 3c movl $0xa3c,0xa3c 774: 0a 00 00 base.s.size = 0; 777: c7 05 40 0a 00 00 00 movl $0x0,0xa40 77e: 00 00 00 781: e9 46 ff ff ff jmp 6cc <malloc+0x2c>
28.317912
60
0.422252
fee9cc508df74d59667ca43492d19aacf760299c
365
html
HTML
Martin.html
anachlas/w209FinalProject
dde3ccb3986c28f9d7de4fafbb689059bd1bab0e
[ "Apache-2.0" ]
null
null
null
Martin.html
anachlas/w209FinalProject
dde3ccb3986c28f9d7de4fafbb689059bd1bab0e
[ "Apache-2.0" ]
null
null
null
Martin.html
anachlas/w209FinalProject
dde3ccb3986c28f9d7de4fafbb689059bd1bab0e
[ "Apache-2.0" ]
null
null
null
<html> <h1>Martin</h1><br> <a href='http://www.irishcentral.com/news/irishvoice/Fianna-Fail-still-playing-games.html'>Fianna Fail still playing games</a><br> <a href='http://www.4-traders.com/CITIGROUP-INC-4818/news/Citigroup-Economist-Saunders-Joins-Bank-s-Rate-Setters-22180082/'>Citigroup : Economist Saunders Joins Bank's Rate-Setters | 4-Traders</a><br> <html>
73
200
0.761644
f70c997044dba1f12366cdd9cd24d3637e610c6d
21,111
c
C
drivers/CMSIS/DSP/examples/ARM/arm_signal_converge_example/arm_signal_converge_data.c
kutei/stm32_base_project
d8ffbe7d30e1126fdb7864755c9a259b96ded0c2
[ "MIT" ]
null
null
null
drivers/CMSIS/DSP/examples/ARM/arm_signal_converge_example/arm_signal_converge_data.c
kutei/stm32_base_project
d8ffbe7d30e1126fdb7864755c9a259b96ded0c2
[ "MIT" ]
2
2020-05-06T19:10:21.000Z
2020-06-02T16:33:10.000Z
drivers/CMSIS/DSP/examples/ARM/arm_signal_converge_example/arm_signal_converge_data.c
kutei/motor-driver
5abeba6acc98d3d1fd96a4097c9e4b87eebedeee
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------- * Copyright (C) 2010-2012 ARM Limited. All rights reserved. * * $Date: 17. January 2013 * $Revision: V1.4.0 * * Project: CMSIS DSP Library * Title: arm_signal_converge_data.c * * Description: Test input data for Floating point LMS Norm FIR filter * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #include "arm_math.h" /* ---------------------------------------------------------------------- ** Test input data for Floating point LMS Norm FIR filter ** Generated by the MATLAB randn() function ** ------------------------------------------------------------------- */ float32_t testInput_f32[1536] = { -0.432565, -1.665584, 0.125332, 0.287676, -1.146471, 1.190915, 1.189164, -0.037633, 0.327292, 0.174639, -0.186709, 0.725791, -0.588317, 2.183186, -0.136396, 0.113931, 1.066768, 0.059281, -0.095648, -0.832349, 0.294411, -1.336182, 0.714325, 1.623562, -0.691776, 0.857997, 1.254001, -1.593730, -1.440964, 0.571148, -0.399886, 0.689997, 0.815622, 0.711908, 1.290250, 0.668601, 1.190838, -1.202457, -0.019790, -0.156717, -1.604086, 0.257304, -1.056473, 1.415141, -0.805090, 0.528743, 0.219321, -0.921902, -2.170674, -0.059188, -1.010634, 0.614463, 0.507741, 1.692430, 0.591283, -0.643595, 0.380337, -1.009116, -0.019511, -0.048221, 0.000043, -0.317859, 1.095004, -1.873990, 0.428183, 0.895638, 0.730957, 0.577857, 0.040314, 0.677089, 0.568900, -0.255645, -0.377469, -0.295887, -1.475135, -0.234004, 0.118445, 0.314809, 1.443508, -0.350975, 0.623234, 0.799049, 0.940890, -0.992092, 0.212035, 0.237882, -1.007763, -0.742045, 1.082295, -0.131500, 0.389880, 0.087987, -0.635465, -0.559573, 0.443653, -0.949904, 0.781182, 0.568961, -0.821714, -0.265607, -1.187777, -2.202321, 0.986337, -0.518635, 0.327368, 0.234057, 0.021466, -1.003944, -0.947146, -0.374429, -1.185886, -1.055903, 1.472480, 0.055744, -1.217317, -0.041227, -1.128344, -1.349278, -0.261102, 0.953465, 0.128644, 0.656468, -1.167819, -0.460605, -0.262440, -1.213152, -1.319437, 0.931218, 0.011245, -0.645146, 0.805729, 0.231626, -0.989760, 1.339586, 0.289502, 1.478917, 1.138028, -0.684139, -1.291936, -0.072926, -0.330599, -0.843628, 0.497770, 1.488490, -0.546476, -0.846758, -0.246337, 0.663024, -0.854197, -1.201315, -0.119869, -0.065294, 0.485296, -0.595491, -0.149668, -0.434752, -0.079330, 1.535152, -0.606483, -1.347363, 0.469383, -0.903567, 0.035880, -0.627531, 0.535398, 0.552884, -0.203690, -2.054325, 0.132561, 1.592941, 1.018412, -1.580402, -0.078662, -0.681657, -1.024553, -1.234353, 0.288807, -0.429303, 0.055801, -0.367874, -0.464973, 0.370961, 0.728283, 2.112160, -1.357298, -1.022610, 1.037834, -0.389800, -1.381266, 0.315543, 1.553243, 0.707894, 1.957385, 0.504542, 1.864529, -0.339812, -1.139779, -0.211123, 1.190245, -1.116209, 0.635274, -0.601412, 0.551185, -1.099840, 0.085991, -2.004563, -0.493088, 0.462048, -0.321005, 1.236556, -0.631280, -2.325211, -1.231637, 1.055648, -0.113224, 0.379224, 0.944200, -2.120427, -0.644679, -0.704302, -1.018137, -0.182082, 1.521013, -0.038439, 1.227448, -0.696205, 0.007524, -0.782893, 0.586939, -0.251207, 0.480136, 0.668155, -0.078321, 0.889173, 2.309287, 0.524639, -0.011787, 0.913141, 0.055941, -1.107070, 0.485498, -0.005005, -0.276218, 1.276452, 1.863401, -0.522559, 0.103424, -0.807649, 0.680439, -2.364590, 0.990115, 0.218899, 0.261662, 1.213444, -0.274667, -0.133134, -1.270500, -1.663606, -0.703554, 0.280880, -0.541209, -1.333531, 1.072686, -0.712085, -0.011286, -0.000817, -0.249436, 0.396575, -0.264013, -1.664011, -1.028975, 0.243095, -1.256590, -0.347183, -0.941372, -1.174560, -1.021142, -0.401667, 0.173666, -0.116118, 1.064119, -0.245386, -1.517539, 0.009734, 0.071373, 0.316536, 0.499826, 1.278084, -0.547816, 0.260808, -0.013177, -0.580264, 2.136308, -0.257617, -1.409528, 1.770101, 0.325546, -1.119040, 0.620350, 1.269782, -0.896043, 0.135175, -0.139040, -1.163395, 1.183720, -0.015430, 0.536219, -0.716429, -0.655559, 0.314363, 0.106814, 1.848216, -0.275106, 2.212554, 1.508526, -1.945079, -1.680543, -0.573534, -0.185817, 0.008934, 0.836950, -0.722271, -0.721490, -0.201181, -0.020464, 0.278890, 1.058295, 0.621673, -1.750615, 0.697348, 0.811486, 0.636345, 1.310080, 0.327098, -0.672993, -0.149327, -2.449018, 0.473286, 0.116946, -0.591104, -0.654708, -1.080662, -0.047731, 0.379345, -0.330361, -0.499898, -0.035979, -0.174760, -0.957265, 1.292548, 0.440910, 1.280941, -0.497730, -1.118717, 0.807650, 0.041200, -0.756209, -0.089129, -2.008850, 1.083918, -0.981191, -0.688489, 1.339479, -0.909243, -0.412858, -0.506163, 1.619748, 0.080901, -1.081056, -1.124518, 1.735676, 1.937459, 1.635068, -1.255940, -0.213538, -0.198932, 0.307499, -0.572325, -0.977648, -0.446809, 1.082092, 2.372648, 0.229288, -0.266623, 0.701672, -0.487590, 1.862480, 1.106851, -1.227566, -0.669885, 1.340929, 0.388083, 0.393059, -1.707334, 0.227859, 0.685633, -0.636790, -1.002606, -0.185621, -1.054033, -0.071539, 0.279198, 1.373275, 0.179841, -0.542017, 1.634191, 0.825215, 0.230761, 0.671634, -0.508078, 0.856352, 0.268503, 0.624975, -1.047338, 1.535670, 0.434426, -1.917136, 0.469940, 1.274351, 0.638542, 1.380782, 1.319843, -0.909429, -2.305605, 1.788730, 0.390798, 0.020324, -0.405977, -1.534895, 0.221373, -1.374479, -0.839286, -0.208643, 0.755913, 0.375734, -1.345413, 1.481876, 0.032736, 1.870453, -1.208991, -0.782632, -0.767299, -0.107200, -0.977057, -0.963988, -2.379172, -0.838188, 0.257346, -0.183834, -0.167615, -0.116989, 0.168488, -0.501206, -0.705076, 0.508165, -0.420922, 0.229133, -0.959497, -0.146043, 0.744538, -0.890496, 0.139062, -0.236144, -0.075459, -0.358572, -2.077635, -0.143546, 1.393341, 0.651804, -0.377134, -0.661443, 0.248958, -0.383516, -0.528480, 0.055388, 1.253769, -2.520004, 0.584856, -1.008064, 0.944285, -2.423957, -0.223831, 0.058070, -0.424614, -0.202918, -1.513077, -1.126352, -0.815002, 0.366614, -0.586107, 1.537409, 0.140072, -1.862767, -0.454193, -0.652074, 0.103318, -0.220632, -0.279043, -0.733662, -0.064534, -1.444004, 0.612340, -1.323503, -0.661577, -0.146115, 0.248085, -0.076633, 1.738170, 1.621972, 0.626436, 0.091814, -0.807607, -0.461337, -1.405969, -0.374530, -0.470911, 1.751296, 0.753225, 0.064989, -0.292764, 0.082823, 0.766191, 2.236850, 0.326887, 0.863304, 0.679387, 0.554758, 1.001630, 1.259365, 0.044151, -0.314138, 0.226708, 0.996692, 1.215912, -0.542702, 0.912228, -0.172141, -0.335955, 0.541487, 0.932111, -0.570253, -1.498605, -0.050346, 0.553025, 0.083498, 1.577524, -0.330774, 0.795155, -0.784800, -1.263121, 0.666655, -1.392632, -1.300562, -0.605022, -1.488565, 0.558543, -0.277354, -1.293685, -0.888435, -0.986520, -0.071618, -2.414591, -0.694349, -1.391389, 0.329648, 0.598544, 0.147175, -0.101439, -2.634981, 0.028053, -0.876310, -0.265477, -0.327578, -1.158247, 0.580053, 0.239756, -0.350885, 0.892098, 1.578299, -1.108174, -0.025931, -1.110628, 0.750834, 0.500167, -0.517261, -0.559209, -0.753371, 0.925813, -0.248520, -0.149835, -1.258415, 0.312620, 2.690277, 0.289696, -1.422803, 0.246786, -1.435773, 0.148573, -1.693073, 0.719188, 1.141773, 1.551936, 1.383630, -0.758092, 0.442663, 0.911098, -1.074086, 0.201762, 0.762863, -1.288187, -0.952962, 0.778175, -0.006331, 0.524487, 1.364272, 0.482039, -0.787066, 0.751999, -0.166888, -0.816228, 2.094065, 0.080153, -0.937295, 0.635739, 1.682028, 0.593634, 0.790153, 0.105254, -0.158579, 0.870907, -0.194759, 0.075474, -0.526635, -0.685484, -0.268388, -1.188346, 0.248579, 0.102452, -0.041007, -2.247582, -0.510776, 0.249243, 0.369197, 0.179197, -0.037283, -1.603310, 0.339372, -0.131135, 0.485190, 0.598751, -0.086031, 0.325292, -0.335143, -0.322449, -0.382374, -0.953371, 0.233576, 1.235245, -0.578532, -0.501537, 0.722864, 0.039498, 1.541279, -1.701053, -1.033741, -0.763708, 2.176426, 0.431612, -0.443765, 0.029996, -0.315671, 0.977846, 0.018295, 0.817963, 0.702341, -0.231271, -0.113690, 0.127941, -0.799410, -0.238612, -0.089463, -1.023264, 0.937538, -1.131719, -0.710702, -1.169501, 1.065437, -0.680394, -1.725773, 0.813200, 1.441867, 0.672272, 0.138665, -0.859534, -0.752251, 1.229615, 1.150754, -0.608025, 0.806158, 0.217133, -0.373461, -0.832030, 0.286866, -1.818892, -1.573051, 2.015666, -0.071982, 2.628909, -0.243317, 0.173276, 0.923207, -0.178553, -0.521705, 1.431962, -0.870117, 0.807542, -0.510635, 0.743514, 0.847898, -0.829901, 0.532994, 1.032848, -1.052024, 0.362114, -0.036787, -1.227636, -0.275099, -0.160435, -1.083575, -1.954213, -0.909487, -0.005579, -1.723490, 1.263077, -0.600433, -2.063925, 0.110911, 1.487614, 0.053002, 0.161981, -0.026878, 0.173576, 0.882168, 0.182294, 0.755295, 0.508035, 0.131880, 0.280104, -0.982848, -0.944087, -0.013058, 0.354345, -0.894709, 0.812111, 0.109537, 2.731644, 0.411079, -1.306862, 0.383806, 0.499504, -0.510786, 0.234922, -0.597825, 0.020771, 0.419443, 1.191104, 0.771214, -2.644222, 0.285430, 0.826093, -0.008122, 0.858438, 0.774788, 1.305945, 1.231503, 0.958564, -1.654548, -0.990396, 0.685236, -0.974870, -0.606726, 0.686794, 0.020049, 1.063801, -1.341050, 0.479510, -1.633974, -1.442665, 0.293781, -0.140364, -1.130341, -0.292538, -0.582536, -0.896348, 0.248601, -1.489663, 0.313509, -2.025084, 0.528990, 0.343471, 0.758193, -0.691940, 0.680179, -1.072541, 0.899772, -2.123092, 0.284712, -0.733323, -0.773376, 0.151842, -0.336843, 0.970761, -0.107236, 1.013492, -0.475347, 0.068948, 0.398592, 1.116326, 0.620451, -0.287674, -1.371773, -0.685868, 0.331685, -0.997722, 0.291418, 1.107078, 0.244959, 0.164976, 0.406231, 1.215981, 1.448424, -1.025137, 0.205418, 0.588882, -0.264024, 2.495318, 0.855948, -0.850954, 0.811879, 0.700242, 0.759938, -1.712909, 1.537021, -1.609847, 1.109526, -1.109704, 0.385469, 0.965231, 0.818297, 0.037049, -0.926012, -0.111919, -0.803030, -1.665006, -0.901401, 0.588350, 0.554159, -0.415173, 0.061795, 0.457432, 0.199014, 0.257558, 2.080730, -2.277237, 0.339022, 0.289894, 0.662261, -0.580860, 0.887752, 0.171871, 0.848821, 0.963769, 1.321918, -0.064345, 1.317053, 0.228017, -1.429637, -0.149701, -0.504968, -1.729141, -0.417472, -0.614969, 0.720777, 0.339364, 0.882845, 0.284245, -0.145541, -0.089646, 0.289161, 1.164831, 0.805729, -1.355643, 0.120893, -0.222178, 0.571732, -0.300140, 1.134277, -0.179356, -1.467067, 1.395346, 0.440836, 0.565384, -0.693623, 0.833869, -2.237378, 1.097644, -0.001617, -1.614573, -1.228727, 0.207405, 0.220942, -1.006073, -0.453067, 1.399453, -0.461964, 0.032716, 0.798783, 0.896816, 0.137892, -1.619146, -1.646606, 0.428707, -0.737231, 0.564926, -1.384167, 0.460268, 0.629384, 0.379847, -1.013330, -0.347243, 0.441912, -1.590240, -0.701417, -1.077601, 1.002220, 1.729481, 0.709032, -0.747897, 0.228862, -0.223497, -0.853275, 0.345627, 0.109764, -1.133039, -0.683124, -0.277856, 0.654790, -1.248394, -0.597539, -0.481813, 0.983372, 1.762121, 1.427402, 0.911763, 0.326823, 0.069619, -1.499763, -0.418223, -0.021037, 0.228425, -1.008196, -0.664622, 0.558177, -1.188542, -0.775481, 0.271042, 1.534976, -1.052283, 0.625559, -0.797626, -0.313522, -0.602210, 1.259060, 0.858484, -2.105292, -0.360937, 0.553557, -1.556384, -0.206666, -0.425568, 0.493778, -0.870908, 0.079828, -0.521619, -1.413861, -0.384293, -0.457922, -0.291471, -0.301224, -1.588594, 1.094287, 1.324167, -0.126480, -0.737164, 0.213719, -0.400529, 0.064938, -1.757996, 1.686748, 0.327400, 0.715967, 1.598648, -2.064741, -0.743632, 0.176185, 0.527839, -0.553153, 0.298280, -1.226607, -0.189676, -0.301713, 0.956956, -0.533366, -0.901082, -0.892552, 0.278717, -0.745807, 1.603464, 0.574270, 0.320655, -0.151383, 0.315762, 1.343703, -2.237832, 1.292906, -0.378459, 0.002521, 0.884641, 0.582450, -1.614244, -1.503666, 0.573586, -0.910537, -1.631277, -0.359138, -0.397616, -1.161307, -1.109838, 0.290672, -1.910239, 1.314768, 0.665319, -0.275115, -0.023022, -0.907976, -1.043657, 0.373516, 0.901532, 1.278539, -0.128456, 0.612821, 1.956518, 2.266326, -0.373959, 2.238039, -0.159580, -0.703281, 0.563477, -0.050296, 1.163593, 0.658808, -1.550089, -3.029118, 0.540578, -1.008998, 0.908047, 1.582303, -0.979088, 1.007902, 0.158491, -0.586927, 1.574082, -0.516649, 1.227800, 1.583876, -2.088950, 2.949545, 1.356125, 1.050068, -0.767170, -0.257653, -1.371845, -1.267656, -0.894948, 0.589089, 1.842629, 1.347967, -0.491253, -2.177568, 0.237000, -0.735411, -1.779419, 0.448030, 0.581214, 0.856607, -0.266263, -0.417470, -0.205806, -0.174323, 0.217577, 1.684295, 0.119528, 0.650667, 2.080061, -0.339225, 0.730113, 0.293969, -0.849109, -2.533858, -2.378941, -0.346276, -0.610937, -0.408192, -1.415611, 0.227122, 0.207974, -0.719718, 0.757762, -1.643135, -1.056813, -0.251662, -1.298441, 1.233255, 1.494625, 0.235938, -1.404359, 0.658791, -2.556613, -0.534945, 3.202525, 0.439198, -1.149901, 0.886765, -0.283386, 1.035336, -0.364878, 1.341987, 1.008872, 0.213874, -0.299264, 0.255849, -0.190826, -0.079060, 0.699851, -0.796540, -0.801284, -0.007599, -0.726810, -1.490902, 0.870335, -0.265675, -1.566695, -0.394636, -0.143855, -2.334247, -1.357539, -1.815689, 1.108422, -0.142115, 1.112757, 0.559264, 0.478370, -0.679385, 0.284967, -1.332935, -0.723980, -0.663600, 0.198443, -1.794868, -1.387673, 0.197768, 1.469328, 0.366493, -0.442775, -0.048563, 0.077709, 1.957910, -0.072848, 0.938810, -0.079608, -0.800959, 0.309424, 1.051826, -1.664211, -1.090792, -0.191731, 0.463401, -0.924147, -0.649657, 0.622893, -1.335107, 1.047689, 0.863327, -0.642411, 0.660010, 1.294116, 0.314579, 0.859573, 0.128670, 0.016568, -0.072801, -0.994310, -0.747358, -0.030814, 0.988355, -0.599017, 1.476644, -0.813801, 0.645040, -1.309919, -0.867425, -0.474233, 0.222417, 1.871323, 0.110001, -0.411341, 0.511242, -1.199117, -0.096361, 0.445817, -0.295825, -0.167996, 0.179543, 0.421118, 1.677678, 1.996949, 0.696964, -1.366382, 0.363045, -0.567044, -1.044154, 0.697139, 0.484026, -0.193751, -0.378095, -0.886374, -1.840197, -1.628195, -1.173789, -0.415411, 0.175088, 0.229433, -1.240889, 0.700004, 0.426877, 1.454803, -0.510186, -0.006657, -0.525496, 0.717698, 1.088374, 0.500552, 2.771790, -0.160309, 0.429489, -1.966817, -0.546019, -1.888395, -0.107952, -1.316144, -0.672632, -0.902365, -0.154798, 0.947242, 1.550375, 0.429040, -0.560795, 0.179304, -0.771509, -0.943390, -1.407569, -1.906131, -0.065293, 0.672149, 0.206147, -0.008124, 0.020042, -0.558447, 1.886079, -0.219975, -1.414395, -0.302811, -0.569574, -0.121495, -0.390171, -0.844287, -1.737757, -0.449520, -1.547933, -0.095776, 0.907714, 2.369602, 0.519768, 0.410525, 1.052585, 0.428784, 1.295088, -0.186053, 0.130733, -0.657627, -0.759267, -0.595170, 0.812400, 0.069541, -1.833687, 1.827363, 0.654075, -1.544769, -0.375109, 0.207688, -0.765615, -0.106355, 0.338769, 1.033461, -1.404822, -1.030570, -0.643372, 0.170787, 1.344839, 1.936273, 0.741336, 0.811980, -0.142808, -0.099858, -0.800131, 0.493249, 1.237574, 1.295951, -0.278196, 0.217127, 0.630728, -0.548549, 0.229632, 0.355311, 0.521284, -0.615971, 1.345803, 0.974922, -2.377934, -1.092319, -0.325710, -2.012228, 1.567660, 0.233337, 0.646420, -1.129412, 0.197038, 1.696870, 0.726034, 0.792526, 0.603357, -0.058405, -1.108666, 2.144229, -1.352821, 0.457021, 0.391175, 2.073013, -0.323318, 1.468132, -0.502399, 0.209593, 0.754800, -0.948189, 0.613157, 1.760503, 0.088762, 2.595570, -0.675470, 2.786804, -0.016827, 0.271651, -0.914102, -1.951371, -0.317418, 0.588333, 0.828996, -1.674851, -1.922293, -0.436662, 0.044974, 2.416609, -0.309892, 0.187583, 0.947699, -0.525703, -1.115605, -1.592320, 1.174844, 0.485144, 1.645480, -0.454233, 1.008768, 2.049403, 0.602020, 0.017860, -1.610426, 1.238752, 0.683587, -0.780716, 0.530979, 2.134498, 0.354361, 0.231700, 1.287980, -0.013488, -1.333345, -0.556343, 0.755597, -0.911854, 1.371684, 0.245580, 0.118845, 0.384690, -0.070152, -0.578309, 0.469308, 1.299687, 1.634798, -0.702809, 0.807253, -1.027451, 1.294496, 0.014930, 0.218705, 1.713188, -2.078805, 0.112917, -1.086491, -1.558311, 0.637406, -0.404576, -0.403325, 0.084076, -0.435349, -0.562623, 0.878062, -0.814650, -0.258363, 0.493299, -0.802694, -0.008329, 0.627571, 0.154382, 2.580735, -1.306246, 1.023526, 0.777795, -0.833884, -0.586663, 0.065664, -0.012342, -0.076987, -1.558587, 1.702607, -0.468984, 0.094619, 0.287071, 0.919354, 0.510136, 0.245440, -1.400519, 0.969571, 1.593698, -1.437917, -1.534230, -0.074710, 0.081459, -0.843240, -0.564640, -0.028207, -1.243702, 0.733039, 0.059580, 0.149144, 1.595857, -0.777250, 1.550277, 1.055002, -0.166654, 0.314484, 1.419571, 0.327348, 0.475653, 0.398754, -0.072770, 1.314784, 0.978279, 1.722114, -0.412302, 0.565133, 0.739851, 0.220138, 1.312807, 0.629152, -1.107987, -0.447001, -0.725993, 0.354045, -0.506772, -2.103747, -0.664684, 1.450110, -0.329805, 2.701872, -1.634939, -0.536325, 0.547223, 1.492603, -0.455243, -0.496416, 1.235260, 0.040926, 0.748467, 1.230764, 0.304903, 1.077771, 0.765151, -1.319580, -0.509191, 0.555116, -1.957625, -0.760453, -2.443886, -0.659366, -0.114779, 0.300079, -0.583996, -3.073745, 1.551042, -0.407369, 1.428095, -1.353242, 0.903970, 0.541671, -0.465020}; /* ---------------------------------------------------------------------- ** Coefficients for 32-tap filter for Floating point LMS FIR filter * FIR high pass filter with cutoff freq 9.6kHz (transition 9.6KHz to 11.52KHz) ** ------------------------------------------------------------------- */ float32_t lmsNormCoeff_f32[32] = {-0.004240, 0.002301, 0.008860, -0.000000, -0.019782, -0.010543, 0.032881, 0.034736, -0.037374, -0.069586, 0.022397, 0.102169, 0.014185, -0.115908, -0.061648, 0.101018, 0.101018, -0.061648, -0.115908, 0.014185, 0.102169, 0.022397, -0.069586, -0.037374, 0.034736, 0.032881, -0.010543, -0.019782, -0.000000, 0.008860, 0.002301, -0.004240 }; /* ---------------------------------------------------------------------- ** Coefficients for 32-tap filter for Floating point FIR filter * FIR low pass filter with cutoff freq 24Hz (transition 24Hz to 240Hz) ** ------------------------------------------------------------------- */ const float32_t FIRCoeff_f32[32] = {0.004502, 0.005074, 0.006707, 0.009356, 0.012933, 0.017303, 0.022298, 0.027717, 0.033338, 0.038930, 0.044258, 0.049098, 0.053243, 0.056519, 0.058784, 0.059941, 0.059941, 0.058784, 0.056519, 0.053243, 0.049098, 0.044258, 0.038930, 0.033338, 0.027717, 0.022298, 0.017303, 0.012933, 0.009356, 0.006707, 0.005074, 0.004502 };
111.698413
146
0.614561
b8f0a398cdbdadc163a60add784843d98af87cc2
998
dart
Dart
test/actions_test.dart
grahamsmith/analyticsx
7fe9cbd5fc27df729e1ea357f79e0e59b127f839
[ "MIT" ]
3
2021-08-24T08:23:25.000Z
2021-08-24T13:39:19.000Z
test/actions_test.dart
grahamsmith/analyticsx
7fe9cbd5fc27df729e1ea357f79e0e59b127f839
[ "MIT" ]
1
2021-09-04T11:24:54.000Z
2021-09-04T11:24:54.000Z
test/actions_test.dart
grahamsmith/analyticsx
7fe9cbd5fc27df729e1ea357f79e0e59b127f839
[ "MIT" ]
1
2021-08-17T11:58:05.000Z
2021-08-17T11:58:05.000Z
import 'package:analyticsx/analytics_x.dart'; import 'package:test/test.dart'; import 'util/vendors_and_actions.dart'; void main() { late AnalyticsX ax; setUp(() { ax = AnalyticsX(); }); tearDown(() { ax.reset(); }); group('TrackEvent', () { test('TrackEvent is recorded', () async { const testEventName = 'test_event'; const testParams = {'p1': 'one', 'p2': 'two'}; final recordingVendor = RecordingVendor(); await ax.init([recordingVendor]); await ax.invokeAction(TrackEvent(testEventName, testParams)); expect(recordingVendor.trackEventRecordings, {testEventName: testParams}); }); test('TrackEvent is recorded without params', () async { const testEventName = 'test_event'; final recordingVendor = RecordingVendor(); await ax.init([recordingVendor]); await ax.invokeAction(TrackEvent(testEventName)); expect(recordingVendor.trackEventRecordings, {testEventName: null}); }); }); }
24.95
80
0.658317
d24f4b07adfc887099578d50c6648e67053617c0
784
php
PHP
application/models/Forgot_password_model.php
jamesl1500/sitelyftstudios
2294b1b6d735a9e284bad4e7031a6987c96e9b2f
[ "MIT" ]
null
null
null
application/models/Forgot_password_model.php
jamesl1500/sitelyftstudios
2294b1b6d735a9e284bad4e7031a6987c96e9b2f
[ "MIT" ]
null
null
null
application/models/Forgot_password_model.php
jamesl1500/sitelyftstudios
2294b1b6d735a9e284bad4e7031a6987c96e9b2f
[ "MIT" ]
null
null
null
<?php class Forgot_password_model extends CI_Model { function __construct() { parent::__construct(); $this->load->library('ForgotPasswordSystem'); } public function makeRequest($string) { $password = new ForgotPasswordSystem(); $password->makePasswordRequest($string); } public function checkRequestId($request_id, $unique_id) { $password = new ForgotPasswordSystem(); $check = $password->checkId($request_id, $unique_id); return $check; } public function changePassProcess($request_id, $unique_id, $password, $confirm_password) { $change = new ForgotPasswordSystem(); $change->changePass($request_id, $unique_id, $password, $confirm_password); } }
27.034483
92
0.637755
32c960a7730c18f7ac25a96fb49bb164214508cf
1,260
kt
Kotlin
src/main/kotlin/me/steven/indrev/items/energy/MachineBlockItem.kt
MCrafterzz/Industrial-Revolution
ba42d48c601e754ff3a263e98837bf8f4f531d2a
[ "Apache-2.0" ]
152
2020-06-28T16:38:46.000Z
2022-03-12T12:30:23.000Z
src/main/kotlin/me/steven/indrev/items/energy/MachineBlockItem.kt
MCrafterzz/Industrial-Revolution
ba42d48c601e754ff3a263e98837bf8f4f531d2a
[ "Apache-2.0" ]
355
2020-06-29T11:06:16.000Z
2022-03-31T22:43:30.000Z
src/main/kotlin/me/steven/indrev/items/energy/MachineBlockItem.kt
MCrafterzz/Industrial-Revolution
ba42d48c601e754ff3a263e98837bf8f4f531d2a
[ "Apache-2.0" ]
70
2020-06-28T16:10:46.000Z
2022-03-13T15:52:39.000Z
package me.steven.indrev.items.energy import me.steven.indrev.api.machines.Tier import me.steven.indrev.blocks.machine.MachineBlock import me.steven.indrev.gui.tooltip.energy.EnergyTooltipDataProvider import me.steven.indrev.utils.buildMachineTooltip import net.minecraft.block.Block import net.minecraft.client.item.TooltipContext import net.minecraft.item.BlockItem import net.minecraft.item.ItemStack import net.minecraft.text.Text import net.minecraft.world.World import team.reborn.energy.api.EnergyStorage import team.reborn.energy.impl.SimpleItemEnergyStorageImpl class MachineBlockItem(private val machineBlock: Block, settings: Settings) : BlockItem(machineBlock, settings), EnergyTooltipDataProvider { init { val capacity = ((machineBlock as? MachineBlock)?.config?.maxEnergyStored ?: 0).toLong() EnergyStorage.ITEM.registerForItems({ _, ctx -> SimpleItemEnergyStorageImpl.createSimpleStorage(ctx, capacity, Tier.MK4.io, 0) }, this) } override fun appendTooltip( stack: ItemStack?, world: World?, tooltip: MutableList<Text>?, options: TooltipContext? ) { val config = (machineBlock as? MachineBlock)?.config buildMachineTooltip(config ?: return, tooltip) } }
38.181818
143
0.761111
4045b6386447c61868dabc592d76d2b351f1fe27
865
py
Python
scarlet/scheduling/migrations/0001_initial.py
ff0000/scarlet
6c37befd810916a2d7ffff2cdb2dab57bcb6d12e
[ "MIT" ]
9
2015-10-13T04:35:56.000Z
2017-03-16T19:00:44.000Z
scarlet/scheduling/migrations/0001_initial.py
ff0000/scarlet
6c37befd810916a2d7ffff2cdb2dab57bcb6d12e
[ "MIT" ]
32
2015-02-10T21:09:18.000Z
2017-07-18T20:26:51.000Z
scarlet/scheduling/migrations/0001_initial.py
ff0000/scarlet
6c37befd810916a2d7ffff2cdb2dab57bcb6d12e
[ "MIT" ]
3
2017-07-13T13:32:21.000Z
2019-04-08T20:18:58.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import scarlet.scheduling.fields class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ] operations = [ migrations.CreateModel( name='Schedule', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('object_args', scarlet.scheduling.fields.JSONField()), ('when', models.DateTimeField()), ('action', models.CharField(max_length=255, null=True)), ('json_args', scarlet.scheduling.fields.JSONField()), ('content_type', models.ForeignKey(to='contenttypes.ContentType')), ], ), ]
32.037037
114
0.603468
c7fa0df0b44ae364fd49aeacf76d44fe3d152dda
25,914
java
Java
src/main/java/org/ednovo/gooru/client/mvp/shelf/collection/tab/collaborators/CollectionCollaboratorsTabView.java
mitraj/Gooru-Web
230d05e12bd3f5960b05bbe9687ecb5823f9c874
[ "MIT" ]
null
null
null
src/main/java/org/ednovo/gooru/client/mvp/shelf/collection/tab/collaborators/CollectionCollaboratorsTabView.java
mitraj/Gooru-Web
230d05e12bd3f5960b05bbe9687ecb5823f9c874
[ "MIT" ]
null
null
null
src/main/java/org/ednovo/gooru/client/mvp/shelf/collection/tab/collaborators/CollectionCollaboratorsTabView.java
mitraj/Gooru-Web
230d05e12bd3f5960b05bbe9687ecb5823f9c874
[ "MIT" ]
null
null
null
/******************************************************************************* * Copyright 2013 Ednovo d/b/a Gooru. All rights reserved. * * http://www.goorulearning.org/ * * 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. ******************************************************************************/ package org.ednovo.gooru.client.mvp.shelf.collection.tab.collaborators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.ednovo.gooru.client.SimpleAsyncCallback; import org.ednovo.gooru.client.gin.AppClientFactory; import org.ednovo.gooru.client.gin.BaseViewWithHandlers; import org.ednovo.gooru.client.mvp.search.event.RemoveCollaboratorObjectEvent; import org.ednovo.gooru.client.mvp.search.event.SetCollabCountEvent; import org.ednovo.gooru.client.mvp.search.event.SetHeaderZIndexEvent; import org.ednovo.gooru.client.mvp.search.event.SetPanelVisibilityEvent; import org.ednovo.gooru.client.mvp.search.event.SetPanelVisibilityHandler; import org.ednovo.gooru.client.mvp.shelf.collection.tab.collaborators.vc.CollaboratorViewVc; import org.ednovo.gooru.client.mvp.shelf.collection.tab.collaborators.vc.DeletePopupViewVc; import org.ednovo.gooru.client.mvp.shelf.collection.tab.collaborators.vc.SuccessPopupViewVc; import org.ednovo.gooru.client.uc.suggestbox.widget.AutoSuggestForm; import org.ednovo.gooru.client.util.MixpanelUtil; import org.ednovo.gooru.shared.model.content.CollaboratorsDo; import org.ednovo.gooru.shared.model.content.CollectionDo; import org.ednovo.gooru.shared.util.MessageProperties; import org.ednovo.gooru.shared.util.StringUtil; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Document; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.DomEvent; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.MultiWordSuggestOracle; import com.google.gwt.user.client.ui.SuggestOracle; import com.google.gwt.user.client.ui.SuggestOracle.Suggestion; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * * @fileName : CollectionCollaboratorsTabView.java * * @description : * * * @version : 1.0 * * @date: Jan 23, 2014 * * @Author Gooru Team * * @Reviewer: */ public class CollectionCollaboratorsTabView extends BaseViewWithHandlers<CollectionCollaboratorsTabUiHandlers> implements IsCollectionCollaboratorsTab,MessageProperties, SelectionHandler<SuggestOracle.Suggestion> { @UiField(provided = true) CollectionCollaboratorsCBundle res; private static CollectionAssignViewTabUiBinder uiBinder = GWT.create(CollectionAssignViewTabUiBinder.class); String EMAIL_REGEX = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$"; CollectionDo collectionDo = null; @UiField HTMLPanel panelViewMode, panelEditMode,panelCreator,panelCollaboratorsList,panelLoading, panelPendingSmallLoadingIcon;//, panelCurrentSmallLoadingIcon; @UiField VerticalPanel panelPendingCollabListContainer, panelActiveCollabListContainer; @UiField HTMLPanel panelPendingContainer, panelActiveContainer, panelSuggestBox, panelActions; @UiField Label lblCollectionCreator, lblCurrentCollaborators, lblYouAreTheCollectionCreator, lblAddCollaborator, lblCollaboratorsDesc, lblInviteCollaborators, lblErrorMessage; @UiField Label lblPendingInvitations, lblCurrentCollabTitle, lblPleaseWait, lblText/*, lblToolTip*/; @UiField Button btnInvite, btnRemoveSelectedInvities; AutoSuggestForm autoSuggetTextBox =null; MultiWordSuggestOracle oracle = new MultiWordSuggestOracle(); // private PopupPanel toolTipPopupPanel=new PopupPanel(); private static int collabLimitCount = 20; int currentCollabCount=0; int overAllCollabCount = 0; // @UiField TextBox txtCollaboratorsName; // SuggestBox suggestBox =null; interface CollectionAssignViewTabUiBinder extends UiBinder<Widget, CollectionCollaboratorsTabView> { } /** * Class constructor */ public CollectionCollaboratorsTabView() { res = CollectionCollaboratorsCBundle.INSTANCE; CollectionCollaboratorsCBundle.INSTANCE.css().ensureInjected(); setWidget(uiBinder.createAndBindUi(this)); SetPanelVisibilityHandler panelHander = new SetPanelVisibilityHandler() { @Override public void setPendingActiveVisibility() { setPanelsVisibility(); } }; AppClientFactory.getEventBus().addHandler(SetPanelVisibilityEvent.TYPE, panelHander); clearContainers(); } /** * */ @Override public void onLoad() { } @Override public void onUnload() { // setLabelsAndIds(); } @Override public void reset() { super.reset(); } /** * * @function setLabelsAndIds * * @created_date : Jan 23, 2014 * * @description * * * * @return : void * * @throws : <Mentioned if any exceptions> * * * * */ public void setLabelsAndIds(){ lblCollectionCreator.setText(GL0936); lblCurrentCollaborators.setText( GL0939); lblYouAreTheCollectionCreator.setText(GL0940); lblAddCollaborator.setText(GL0941); lblCollaboratorsDesc.setText(GL0942); lblInviteCollaborators.setText(GL0943); lblPendingInvitations.setText(GL1114); lblCurrentCollabTitle.setText(GL1113); btnInvite.setText(GL0944); btnInvite.getElement().setId("btnInvite"); btnInvite.setEnabled(false); panelActions.getElement().addClassName(res.css().buttonTooltip()); btnInvite.setVisible(true); lblText.setText(GL1184); // btnInvite.addMouseOverHandler(new OnBtnInviteMouseOver()); // btnInvite.addMouseOutHandler(new OnBtnInviteMouseOut()); btnRemoveSelectedInvities.setText(GL0237); btnRemoveSelectedInvities.setVisible(false); btnRemoveSelectedInvities.getElement().setId("btnRemoveSelectedInvities"); /* lblToolTip.setText(GL1165_1); lblToolTip.setVisible(false); */ lblErrorMessage.setVisible(false); setInviteButtonEnable(overAllCollabCount); lblPleaseWait.setText(GL1137); panelCollaboratorsList.clear(); // View mode panelPendingCollabListContainer.clear(); //edit mode panelActiveCollabListContainer.clear(); //edit mode lblPleaseWait.setVisible(false); createAutoSuggestBox(); } /** * @function setInviteButtonEnable * * @created_date : Mar 4, 2014 * * @description * * * * @return : void * * @throws : <Mentioned if any exceptions> * * * * */ @Override public void setInviteButtonEnable(int currentCount) { currentCollabCount = currentCount; if (currentCollabCount >=collabLimitCount){ btnInvite.getElement().addClassName("disabled"); btnInvite.setEnabled(false); panelActions.getElement().addClassName(res.css().buttonTooltip()); }else{ panelActions.getElement().removeClassName(res.css().buttonTooltip()); btnInvite.getElement().removeClassName("disabled"); btnInvite.setEnabled(true); } } /** * @function createAutoSuggestBox * * @created_date : Jan 30, 2014 * * @description * * * * @return : void * * @throws : <Mentioned if any exceptions> * * * * */ private void createAutoSuggestBox() { panelSuggestBox.setStyleName("auto_suggest"); autoSuggetTextBox = new AutoSuggestForm(oracle) { @Override public void onSubmit(DomEvent<EventHandler> event) { // Nothing to do.... } @Override public void dataObjectModel(String text) { if (text.trim().length() > 0){ AppClientFactory.getInjector().getCollaboratorsService().getSuggestionByName(text.trim(), new SimpleAsyncCallback<List<String>>() { @Override public void onSuccess(List<String> lstOfSuggestedCollaborators) { autoSuggetTextBox.clearAutoSuggestData(); for (String lstCollab : lstOfSuggestedCollaborators){ oracle.add(lstCollab); } autoSuggetTextBox.setAutoSuggest(oracle); } }); } } @Override public void keyPressOnTextBox(KeyPressEvent event) { lblErrorMessage.setVisible(false); } @Override public void errorMsgVisibility(boolean visibility, String emailId) { if (visibility){ showErrorMessage(StringUtil.generateMessage(GL1019, emailId)); }else{ lblErrorMessage.setVisible(false); } } }; autoSuggetTextBox.clearAutoSuggestData(); panelSuggestBox.clear(); panelSuggestBox.add(autoSuggetTextBox); autoSuggetTextBox.getTxtInput().getTxtInputBox().setFocus(true); } @UiHandler("btnRemoveSelectedInvities") public void onClickRemoveCollab(ClickEvent event){ List<String> emailIdsToRemove = null; if (panelActiveCollabListContainer.getWidgetCount()>0){ //get the selected item emailIdsToRemove = getCollaboratorOject(panelActiveCollabListContainer); } if (emailIdsToRemove == null && panelPendingCollabListContainer.getWidgetCount()>0){ //get the selected item emailIdsToRemove = getCollaboratorOject(panelPendingCollabListContainer); } if (emailIdsToRemove != null){ final String toRemove = emailIdsToRemove.get(0); final String emailId = emailIdsToRemove.get(1); final String collectionId = collectionDo.getGooruOid(); DeletePopupViewVc delete = new DeletePopupViewVc() { @Override public void onClickPositiveButton(ClickEvent event) { AppClientFactory.getInjector().getCollaboratorsService().removeCollaboratorsFromListByEmailIds(collectionId, "[\"" + toRemove +"\"]", new SimpleAsyncCallback<Void>() { @Override public void onSuccess(Void result) { hide(); Window.enableScrolling(true); AppClientFactory.fireEvent(new SetHeaderZIndexEvent(0, true)); AppClientFactory.fireEvent(new RemoveCollaboratorObjectEvent(toRemove)); AppClientFactory.fireEvent(new SetCollabCountEvent("decrementBy", 1)); // collectionDo.getMeta().setCollaboratorCount(collectionDo.getMeta().getCollaboratorCount() -1); if(panelActiveCollabListContainer.getWidgetCount() <= 0){ panelActiveContainer.setVisible(false); } if (panelPendingCollabListContainer.getWidgetCount() <= 0){ panelPendingContainer.setVisible(false); } } }); } @Override public void onClickNegitiveButton(ClickEvent event) { Window.enableScrolling(true); AppClientFactory.fireEvent(new SetHeaderZIndexEvent(0, true)); hide(); } }; delete.setPopupTitle(GL1118); delete.setDescText(StringUtil.generateMessage(GL1119, emailIdsToRemove.get(1) != null ? emailIdsToRemove.get(1) : emailIdsToRemove.get(0))); delete.setPositiveButtonText(GL_GRR_YES); delete.setNegitiveButtonText(GL0142); delete.center(); delete.show(); }else{ //give message... } autoSuggetTextBox.getTxtInput().getTxtInputBox().setFocus(true); } private List<String> getCollaboratorOject(VerticalPanel vpanelCollab) { int count = 0; List<String> selectedEmailIds=null; Iterator<Widget> widgets = vpanelCollab.iterator(); while (widgets.hasNext()) { Widget widget = widgets.next(); if (widget instanceof CollaboratorViewVc) { selectedEmailIds = ((CollaboratorViewVc) widget).getSelectedObjectId(); if (selectedEmailIds !=null && selectedEmailIds.size() > 0){ break; } } count++; } return selectedEmailIds; } @UiHandler("btnInvite") public void OnClick(ClickEvent event){ //Check for null - Check for Empty lblPleaseWait.setVisible(true); btnInvite.setVisible(false); String collabEmailIds = autoSuggetTextBox.getSelectedItemsAsString(); String emailIds[] = collabEmailIds.trim().split("\\s*,\\s*"); List<String> lstEmailID = new ArrayList<String>(); for (int i=0; i<emailIds.length; i++){ lstEmailID.add("\""+emailIds[i].toLowerCase().trim()+"\""); } if (collabEmailIds != null && collabEmailIds.equalsIgnoreCase("")){ // showErrorMessage(MessageProperties.GL1015); lblPleaseWait.setVisible(false); btnInvite.setVisible(true); return; } currentCollabCount = emailIds.length + overAllCollabCount; if (currentCollabCount > collabLimitCount){ lblPleaseWait.setVisible(false); btnInvite.setVisible(true); showErrorMessage(StringUtil.generateMessage(GL1016, ""+collabLimitCount)); return; } //Check for Valid Email ID format boolean from; for (int i=0; i<emailIds.length; i++){ String emailID = emailIds[i].toLowerCase().trim(); from = emailID.matches(EMAIL_REGEX); if (!from){ lblPleaseWait.setVisible(false); btnInvite.setVisible(true); showErrorMessage(StringUtil.generateMessage(GL1019, emailID)); return; } } if (AppClientFactory.getLoggedInUser().getEmailId()!=null){ boolean isValid=true; for (int i=0; i<emailIds.length; i++){ String emailId = emailIds[i].toLowerCase().trim(); if (emailId.equalsIgnoreCase(AppClientFactory.getLoggedInUser().getEmailId())){ lblPleaseWait.setVisible(false); btnInvite.setVisible(true); showErrorMessage(GL1018); isValid = false; break; } } if (!isValid){ return; } } btnInvite.getElement().addClassName("disabled"); btnInvite.setEnabled(false); // panelActions.getElement().addClassName(res.css().buttonTooltip()); - this is not required //Call API to add the collaborators to the list. getUiHandlers().addCollaborators(collectionDo.getGooruOid(), lstEmailID); // this will callback the displayCollaborators method. } public void showErrorMessage(String errorMessage){ lblErrorMessage.setText(errorMessage); lblErrorMessage.setVisible(true); } /** * @param FolderDo * */ @Override public void displayView(CollectionDo collectionDo) { this.collectionDo = collectionDo; setLabelsAndIds(); overAllCollabCount = 0; setInviteButtonEnable(overAllCollabCount); setLoadingVisibility(true); setActiveCollabPanelVisibility(false); setPendingCollabPanelVisibility(false); panelEditMode.setVisible(false); panelViewMode.setVisible(false); lblCollectionCreator.setVisible(false); // If Collaborator display only view of all collaborators. if (collectionDo.getMeta() !=null && collectionDo.getMeta().isIsCollaborator()){ panelViewMode.setVisible(true); lblCollectionCreator.setVisible(true); panelCreator.clear(); CollaboratorViewVc collabView = new CollaboratorViewVc(AppClientFactory.getCurrentPlaceToken(), null, collectionDo, false, true, false) { @Override public void setCollabCount(int count, String type) { updateCollabCount(count, type); } }; panelCreator.add(collabView); //Call Get collaborators API. This method will callback displayViewCollaboratorsByList. getUiHandlers().getCollaboratosListByCollectionId(collectionDo.getGooruOid(), "view"); }else if (collectionDo.getMeta() !=null && !collectionDo.getMeta().isIsCollaborator()){ // else if owner then display edit mode and list of all collaborators. panelEditMode.setVisible(true); //Call Get collaborators API. This method will callback displayActiveCollaboratorsByList & displayPendingCollaboratorsByList. getUiHandlers().getCollaboratosListByCollectionId(collectionDo.getGooruOid(), "edit"); autoSuggetTextBox.getTxtInput().getTxtInputBox().setFocus(true); // panelEditMode.add(suggestBox); } } private void updateCollabCount(int count, String type) { // collectionDo.getMeta().setCollaboratorCount(count); if (type.equalsIgnoreCase("decrementBy")){ if (overAllCollabCount > count){ overAllCollabCount -= count; } }else{ // This is not called because we are adding the collaborators in same class. // overAllCollabCount += count; } setInviteButtonEnable(overAllCollabCount); } /* * @description * this method is responsible to display the list of collaborators in view mode. */ @Override public void displayViewCollaboratorsByList(List<CollaboratorsDo> listCollaboratosDo){ // TODO create method to set the collobrators list from API. panelCollaboratorsList.clear(); panelLoading.setVisible(false); CollaboratorsDo collbDoYou = new CollaboratorsDo(); collbDoYou.setEmailId(AppClientFactory.getLoggedInUser().getEmailId()); collbDoYou.setGooruOid(collectionDo.getGooruOid()); collbDoYou.setGooruUid(AppClientFactory.getLoggedInUser().getGooruUId()); collbDoYou.setProfileImageUrl(AppClientFactory.getLoggedInUser().getProfileImageUrl() !=null ? AppClientFactory.getLoggedInUser().getProfileImageUrl() : ""); collbDoYou.setStatus("active"); collbDoYou.setUsername(AppClientFactory.getLoggedInUser().getUsername()); for(CollaboratorsDo collbDo : listCollaboratosDo){ boolean isYou = collbDo.getGooruUid().equalsIgnoreCase(AppClientFactory.getLoggedInUser().getGooruUId()) ? true : false; collbDoYou.setEmailId(collbDo.getEmailId()); if (isYou){ CollaboratorViewVc collabView = new CollaboratorViewVc(AppClientFactory.getCurrentPlaceToken(), collbDoYou, collectionDo, true, false, false) { @Override public void setCollabCount(int count, String type) { updateCollabCount(count, type); } }; panelCollaboratorsList.add(collabView); break; }else{ } } for(CollaboratorsDo collbDo : listCollaboratosDo){ boolean isYou = collbDo.getGooruUid().equalsIgnoreCase(AppClientFactory.getLoggedInUser().getGooruUId()) ? true : false; if (isYou){ }else{ CollaboratorViewVc collabView1 = new CollaboratorViewVc(AppClientFactory.getCurrentPlaceToken(), collbDo, collectionDo, isYou, false, false) { @Override public void setCollabCount(int count, String type) { updateCollabCount(count, type); } }; panelCollaboratorsList.add(collabView1); } } } /* * @description * this method is responsible to display the list of active collaborators in edit mode. */ @Override public void displayActiveCollaboratorsByList( List<CollaboratorsDo> lstCollaborators) { int count=0; panelActiveCollabListContainer.clear(); if (lstCollaborators.size() > 0){ setActiveCollabPanelVisibility(true); for(CollaboratorsDo collbDo : lstCollaborators){ CollaboratorViewVc collabView1 = new CollaboratorViewVc(AppClientFactory.getCurrentPlaceToken(), collbDo, collectionDo, false, false, false) { @Override public void setCollabCount(int count, String type) { updateCollabCount(count, type); } }; panelActiveCollabListContainer.insert(collabView1, count); count++; } overAllCollabCount +=count; } } /* * @description * this method is responsible to display the list of pending collaborators in edit mode. */ @Override public void displayPendingCollaboratorsByList( List<CollaboratorsDo> lstCollaborators) { int count =0; panelPendingCollabListContainer.clear(); if (lstCollaborators.size() > 0){ setPendingCollabPanelVisibility(true); for(CollaboratorsDo collbDo : lstCollaborators){ CollaboratorViewVc collabView1 = new CollaboratorViewVc(AppClientFactory.getCurrentPlaceToken(), collbDo, collectionDo, false, false, false) { @Override public void setCollabCount(int count, String type) { updateCollabCount(count, type); } }; panelPendingCollabListContainer.insert(collabView1, count); count++; } overAllCollabCount +=count; } } /* * @description * this method is responsible to display the list of collaborators after successfully added. */ @Override public void displayCollaborators(List<CollaboratorsDo> collabList) { lblPleaseWait.setVisible(false); btnInvite.setVisible(true); btnInvite.getElement().removeClassName("disabled"); btnInvite.setEnabled(true); final List<CollaboratorsDo> collabList1 = collabList; SuccessPopupViewVc success = new SuccessPopupViewVc() { @Override public void onClickPositiveButton(ClickEvent event) { int addedCount = 0; int pendingCount = 0; hide(); for(CollaboratorsDo collbDo : collabList1){ if (collbDo.getStatus().equalsIgnoreCase("active")){ Document ele = Document.get(); if (ele.getElementById(collbDo.getGooruUid()) == null){ setActiveCollabPanelVisibility(true); CollaboratorViewVc collabView1 = new CollaboratorViewVc(AppClientFactory.getCurrentPlaceToken(), collbDo, collectionDo, false, false, true) { @Override public void setCollabCount(int count, String type) { updateCollabCount(count, type); } }; panelActiveCollabListContainer.insert(collabView1, 0); addedCount++; } }else{ Document ele = Document.get(); if (ele.getElementById(collbDo.getEmailId()) == null){ setPendingCollabPanelVisibility(true); CollaboratorViewVc collabView1 = new CollaboratorViewVc(AppClientFactory.getCurrentPlaceToken(), collbDo, collectionDo, false, false, true) { @Override public void setCollabCount(int count, String type) { updateCollabCount(count, type); } }; panelPendingCollabListContainer.insert(collabView1, 0); pendingCount++; MixpanelUtil.mixpanelEvent("Collaborator_invite_pending"); } } oracle.add(collbDo.getEmailId()); MixpanelUtil.mixpanelEvent("Collaborator_invite_success"); //called for every user. } AppClientFactory.fireEvent(new SetCollabCountEvent("incrementBy", addedCount)); // collectionDo.getMeta().setCollaboratorCount(collectionDo.getMeta().getCollaboratorCount() + addedCount);//this is not required since this is handled by service. overAllCollabCount +=addedCount; overAllCollabCount +=pendingCount; currentCollabCount = overAllCollabCount; setInviteButtonEnable(currentCollabCount); autoSuggetTextBox.clearAutoSuggestData(); createAutoSuggestBox(); Window.enableScrolling(true); AppClientFactory.fireEvent(new SetHeaderZIndexEvent(0, true)); autoSuggetTextBox.getTxtInput().getTxtInputBox().setFocus(true); } }; success.setPopupTitle(GL1120); if (collabList.size()>1){ success.setDescText(GL1121); }else{ success.setDescText(GL1360); } success.setPositiveButtonText(GL0190); success.center(); success.show(); } public void setPendingCollabPanelVisibility(boolean visibility){ panelPendingContainer.setVisible(visibility); } public void setActiveCollabPanelVisibility(boolean visibility){ panelActiveContainer.setVisible(visibility); } @Override public void setRemoveCollabButtonVisibility(boolean visibility){ btnRemoveSelectedInvities.setVisible(false); } public void setLoadingVisibility(boolean visibility){ panelPendingSmallLoadingIcon.setVisible(visibility); } /* (non-Javadoc) * @see com.google.gwt.event.logical.shared.SelectionHandler#onSelection(com.google.gwt.event.logical.shared.SelectionEvent) */ @Override public void onSelection(SelectionEvent<Suggestion> event) { //TODO ... Set the selection. } public void setPanelsVisibility(){ if(panelActiveCollabListContainer.getWidgetCount() <= 0){ panelActiveContainer.setVisible(false); } if (panelPendingCollabListContainer.getWidgetCount() <= 0){ panelPendingContainer.setVisible(false); } btnInvite.setEnabled(true); btnInvite.removeStyleName("disabled"); panelActions.getElement().removeClassName(res.css().buttonTooltip()); } public void clearContainers(){ panelActiveCollabListContainer.clear(); panelPendingCollabListContainer.clear(); panelCollaboratorsList.clear(); //View mode. } // public class OnBtnInviteMouseOver implements MouseOverHandler{ // // @Override // public void onMouseOver(MouseOverEvent event) { // toolTipPopupPanel.clear(); // toolTipPopupPanel.setWidget(new GlobalToolTip(MessageProperties.GL1184,true)); // toolTipPopupPanel.setStyleName(""); // toolTipPopupPanel.setPopupPosition(btnInvite.getElement().getAbsoluteLeft()-35, btnInvite.getElement().getAbsoluteTop()+4); // toolTipPopupPanel.getElement().getStyle().setZIndex(999999); // toolTipPopupPanel.getElement().getStyle().setMarginLeft(40, Unit.PX); // toolTipPopupPanel.show(); // } // // } // public class OnBtnInviteMouseOut implements MouseOutHandler{ // // @Override // public void onMouseOut(MouseOutEvent event) { // toolTipPopupPanel.hide(); // } // } }
33.138107
215
0.734043
5d841f0b53f8f099f93e792b8b2f70f4ad338158
336
go
Go
api/example/main.go
albertoleal/gofeature
59e7d7e853e4288bc6e01b91adbd22efd5796f27
[ "BSD-2-Clause" ]
69
2015-11-04T14:56:44.000Z
2022-01-13T06:12:17.000Z
api/example/main.go
albertoleal/gofeature
59e7d7e853e4288bc6e01b91adbd22efd5796f27
[ "BSD-2-Clause" ]
15
2015-11-01T16:58:42.000Z
2020-11-14T15:12:43.000Z
api/example/main.go
albertoleal/gofeature
59e7d7e853e4288bc6e01b91adbd22efd5796f27
[ "BSD-2-Clause" ]
5
2015-11-17T01:42:06.000Z
2016-08-13T12:32:27.000Z
// Copyright 2015 Features authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "github.com/albertoleal/features/api" "github.com/albertoleal/features/engine/memory" ) func main() { api := api.NewApi(memory.New()) api.Run() }
21
56
0.729167
2746092d16d12f0d43587b9e32b54c68668d1865
1,983
kt
Kotlin
skiko/src/commonMain/kotlin/org/jetbrains/skia/paragraph/Shadow.kt
smallshen/Skiko_Open_Modifier
04860cfe6d481b2d8ad2f8cd05d0efe931997f34
[ "Apache-2.0" ]
null
null
null
skiko/src/commonMain/kotlin/org/jetbrains/skia/paragraph/Shadow.kt
smallshen/Skiko_Open_Modifier
04860cfe6d481b2d8ad2f8cd05d0efe931997f34
[ "Apache-2.0" ]
null
null
null
skiko/src/commonMain/kotlin/org/jetbrains/skia/paragraph/Shadow.kt
smallshen/Skiko_Open_Modifier
04860cfe6d481b2d8ad2f8cd05d0efe931997f34
[ "Apache-2.0" ]
null
null
null
package org.jetbrains.skia.paragraph import org.jetbrains.skia.Point class Shadow(val color: Int, val offsetX: Float, val offsetY: Float, val blurSigma: Double) { constructor(color: Int, offset: Point, blurSigma: Double) : this(color, offset.x, offset.y, blurSigma) {} val offset: Point get() = Point(offsetX, offsetY) override fun equals(o: Any?): Boolean { if (o === this) return true if (o !is Shadow) return false val other = o if (!other.canEqual(this as Any)) return false if (color != other.color) return false if (offsetX.compareTo(other.offsetX) != 0) return false if (offsetY.compareTo(other.offsetY) != 0) return false return blurSigma.compareTo(other.blurSigma) == 0 } protected fun canEqual(other: Any?): Boolean { return other is Shadow } override fun hashCode(): Int { val PRIME = 59 var result = 1 result = result * PRIME + color result = result * PRIME + offsetX.toBits() result = result * PRIME + offsetY.toBits() val `$_blurSigma` = blurSigma.toBits() result = result * PRIME + (`$_blurSigma` ushr 32 xor `$_blurSigma`).toInt() return result } override fun toString(): String { return "Shadow(_color=$color, _offsetX=$offsetX, _offsetY=$offsetY, _blurSigma=$blurSigma)" } fun withColor(_color: Int): Shadow { return if (color == _color) this else Shadow(_color, offsetX, offsetY, blurSigma) } fun withOffsetX(_offsetX: Float): Shadow { return if (offsetX == _offsetX) this else Shadow(color, _offsetX, offsetY, blurSigma) } fun withOffsetY(_offsetY: Float): Shadow { return if (offsetY == _offsetY) this else Shadow(color, offsetX, _offsetY, blurSigma) } fun withBlurSigma(_blurSigma: Double): Shadow { return if (blurSigma == _blurSigma) this else Shadow(color, offsetX, offsetY, _blurSigma) } }
34.789474
109
0.637922
626ad0dba4ca562a84a6550f10eb2aa309676b55
17,571
lua
Lua
source/liquid.lua
Ranguna/liq-d
2f58c20bee1fb7af0351a15c5df3534d4db3fac0
[ "MIT" ]
9
2015-01-18T14:16:47.000Z
2018-06-03T14:15:36.000Z
source/liquid.lua
Ranguna/liq-d
2f58c20bee1fb7af0351a15c5df3534d4db3fac0
[ "MIT" ]
null
null
null
source/liquid.lua
Ranguna/liq-d
2f58c20bee1fb7af0351a15c5df3534d4db3fac0
[ "MIT" ]
1
2016-07-22T17:46:23.000Z
2016-07-22T17:46:23.000Z
local liquid = {} local dist = function(x1,y1,x2,y2) if x2 and y2 then --two points return math.sqrt((x1-x2)^2 + (y1-y2)^2) else --vector return math.sqrt(x1^2 + y1^2) end end liquid._vars = {} liquid._vars.touch = love.system.getOS() == 'Android' and {} liquid._vars.threads = {} ----- liquid._vars.maxParticles = 1000 liquid._vars.radius = 0.6 liquid._vars.viscosity = 0.0004 --.0004 water, .004 blobish, .04 elastic liquid._vars.roughWaters = false liquid._vars.gravity = {0,0} ----- liquid._vars.scale = 32 liquid._vars.idealRadius = 50 liquid._vars.idealRadiusSQ = liquid._vars.idealRadius*liquid._vars.idealRadius liquid._vars.multiplier = liquid._vars.idealRadius/liquid._vars.radius liquid._vars.delta = {} --vec2[] liquid._vars.scaledPositions = {} liquid._vars.scaledVelocity = {} liquid._vars.numActiveParticles = 0 liquid._vars.liquid = {} liquid._vars.activeParticles = {} liquid._vars.maxNeighbors = 75 ----- liquid._vars.debug = {} liquid._vars.grid = {} --liquid._vars.grid.count = 0 liquid._vars.grid.cellSize = 0.5 liquid._vars.grid.transformCoord = function(v) return math.floor(v/liquid._vars.grid.cellSize) end liquid._vars.grid.getValue = function(k1,k2,i) --x,y or {x,y} if type(k1) == 'table' then k2 = k1[2] k1 = k1[1] end if liquid._vars.grid[k1] then if liquid._vars.grid[k1][k2] then return liquid._vars.grid[k1][k2] end end return false end liquid._vars.grid.add = function(k1,k2,v) --x,y,v or {x,y},v if type(k1) == 'table' then v=k2 k2 = k1[2] k1 = k1[1] end --print('going to create '.. k1,k2,v) if not liquid._vars.grid[k1] then --render specific --for i = 1,k1 do -- if not liquid._vars.grid[i] then -- liquid._vars.grid[i] = {} -- liquid._vars.grid[i].count = 0 -- end --end liquid._vars.grid[k1] = {} liquid._vars.grid[k1].count = 0 end if not liquid._vars.grid[k1][k2] then --render specific --for i = 1,k2 do -- if not liquid._vars.grid[k1][i] then -- liquid._vars.grid[k1][i] = {} -- liquid._vars.grid[k1][i].count = 0 -- end -- liquid._vars.grid[k1].count = liquid._vars.grid[k1].count +1 --end liquid._vars.grid[k1][k2] = {} liquid._vars.grid[k1][k2].count = 0 liquid._vars.grid[k1].count = liquid._vars.grid[k1].count +1 end local exists for a,b in ipairs(liquid._vars.grid[k1][k2]) do --eliminates double positioning if b == v then exists = true end end if not exists then liquid._vars.grid[k1][k2].count = liquid._vars.grid[k1][k2].count +1 liquid._vars.grid[k1][k2][#liquid._vars.grid[k1][k2]+1] = v --print('created '.. k1,k2,v,#liquid._vars.grid[k1][k2]+1) end end liquid._vars.grid.remove = function(k1,k2,v) --x,y,i,v or {x,y,i},v if type(k1) == 'table' then v=k2 k2 = k1[2] i = k1[3] k1 = k1[1] end --print('going to remove ',k1,k2,v) if liquid._vars.grid[k1] then if k2 then if liquid._vars.grid[k1][k2] then if v then --print('looking for '..v) local exists for a,b in ipairs(liquid._vars.grid[k1][k2]) do if b == v then exists = a break end end --print(exists and 'found',exists or 'not found') if exists then liquid._vars.grid[k1][k2].count = liquid._vars.grid[k1][k2].count -1 --liquid._vars.grid[k1][k2][exists] = nil table.remove(liquid._vars.grid[k1][k2],exists) --print('removed '..k1,k2,v,exists) end else liquid._vars.grid[k1].count = liquid._vars.grid[k1].count -1 liquid._vars.grid[k1][k2] = nil --print('removed '..k1,k2) end end else --liquid._vars.grid.count = liquid._vars.grid.count -1 liquid._vars.grid[k1] = nil --print('removed '..k1) end end end function liquid.newParticle(position,velocity,alive) local particle = {} particle.position = position particle.oldPosition = position particle.velocity = velocity particle.pressure = 0 particle.alive = alive particle.distances = {} particle.neighbors = {} particle.neighborCount = 0 particle.grid = {liquid._vars.grid.transformCoord(position[1]),liquid._vars.grid.transformCoord(position[2])} return particle end function liquid.findNeighbors(pindex) liquid._vars.liquid[pindex].neighbors = {} local particle = liquid._vars.liquid[pindex] particle.neighborCount = 0 for x = -1,1 do for y = -1,1 do local nx,ny = particle.grid[1] + x,particle.grid[2] + y if liquid._vars.grid.getValue(nx,ny) then for i,v in ipairs(liquid._vars.grid.getValue(nx,ny)) do if v ~= pindex then particle.neighbors[#particle.neighbors+1] = v end particle.neighborCount = particle.neighborCount +1 if particle.neighborCount == 75 then return end end end end end liquid._vars.liquid[pindex] = particle end function liquid.init() for i=1,liquid._vars.maxParticles do liquid._vars.liquid[i] = liquid.newParticle({0,0},{0,0},false) liquid._vars.liquid[i].index = i liquid._vars.delta[i] = {0,0} --vec2 liquid._vars.scaledPositions[i] = {} --vec2 liquid._vars.scaledVelocity[i] = {} --vec2 end end function liquid.settings(...) --mp,r,v,mn,pu,grv,rw or {mp=mp,r=r,v=v,mn=mn,pu=pu,grv=grv,rw} or {mp,r,v,mn,pu,grv,rw} args = {...} if #args == 1 then args = args[1] end liquid._vars.maxParticles = args.maxParticles or args[1] or liquid._vars.maxParticles --liquid._vars.radius = args.radius and (args.radius*love.graphics.getHeight())/600 or args[2] and (args[2]*love.graphics.getHeight())/600 or (liquid._vars.radius*love.graphics.getHeight())/600 liquid._vars.radius = args.radius or args[2] or liquid._vars.radius liquid._vars.viscosity = args.viscosity and args.viscosity or args[3] and args[3] or liquid._vars.viscosity --liquid._vars.viscosity = args.viscosity and (args.viscosity*love.graphics.getHeight())/600 or args[3] and (args[3]*love.graphics.getHeight())/600 or (liquid._vars.viscosity*love.graphics.getHeight())/600 liquid._vars.maxNeighbors = args.maxNeighbors or args[4] or liquid._vars.maxNeighbors liquid._vars.postUpdate = args.postUpdate or args[5] or nil liquid._vars.gravity = args.gravity or args[6] or liquid._vars.gravity liquid._vars.roughWaters = args.roughWaters or args[7] or liquid._vars.roughWaters --liquid._vars.scale = (32*love.graphics.getHeight())/600 liquid._vars.scale = ((liquid._vars.radius*32)/(0.6)) liquid._vars.idealRadius = ((liquid._vars.radius*50)/(0.6)) liquid._vars.idealRadiusSQ = liquid._vars.idealRadius*liquid._vars.idealRadius liquid._vars.multiplier = liquid._vars.idealRadius/liquid._vars.radius liquid._vars.grid.cellSize = ((liquid._vars.radius*0.5)/(0.6)) liquid._vars.multiplier = liquid._vars.idealRadius/liquid._vars.radius liquid._vars.numActiveParticles = 0 liquid._vars.liquid = {} liquid._vars.activeParticles = {} liquid.init() end function liquid.applyLiquidConstraints(dt) local velGrav = {not liquid._vars.roughWaters and liquid._vars.gravity[1] or 0,not liquid._vars.roughWaters and liquid._vars.gravity[2] or 0} --optimizations local deltaGrav = {liquid._vars.roughWaters and liquid._vars.gravity[1] or 0,liquid._vars.roughWaters and liquid._vars.gravity[2] or 0} --optimizations liquid._vars.debug = {} liquid._vars.debug[1] = {name = 'First loop',os.clock()} for i = 1,liquid._vars.numActiveParticles do local index = liquid._vars.activeParticles[i] local particle = liquid._vars.liquid[index] liquid._vars.scaledPositions[i] = {particle.position[1]*liquid._vars.multiplier,particle.position[2]*liquid._vars.multiplier} liquid._vars.scaledVelocity[i] = {particle.velocity[1]*liquid._vars.multiplier,particle.velocity[2]*liquid._vars.multiplier} liquid._vars.delta[index] = {0,0} --updates neighbors liquid._vars.debug[2] = {name = 'Neighbor search',os.clock()} liquid.findNeighbors(index) liquid._vars.debug[2][2] = os.clock() end for i = 1,liquid._vars.numActiveParticles do local index = liquid._vars.activeParticles[i] local particle = liquid._vars.liquid[index] --Calculate Pressure local p = 0 local pnear = 0 liquid._vars.debug[3] = {name = 'Pressure calculation',os.clock()} for i,v in ipairs(particle.neighbors) do local relativePosition = {liquid._vars.scaledPositions[v][1] - liquid._vars.scaledPositions[index][1],liquid._vars.scaledPositions[v][2] - liquid._vars.scaledPositions[index][2]} local distanceSQ = dist(relativePosition[1],relativePosition[2])^2 --within idealRadius check if distanceSQ < liquid._vars.idealRadiusSQ then particle.distances[i] = math.sqrt(distanceSQ) local oneminusq = 1 - (particle.distances[i]/liquid._vars.idealRadius) p = (p + oneminusq * oneminusq) liquid._vars.liquid[index].pressure = p pnear = (pnear + oneminusq*oneminusq*oneminusq) else particle.distances[i] = 1/0 -- float.MaxValue ? end end liquid._vars.debug[3][2] = os.clock() --Apply force local pressure = (p-5)/2 -- normal pressure term local presnear = pnear /2 -- near particles term local change = {0,0} liquid._vars.debug[4] = {name = 'Apply force',os.clock()} for i,v in ipairs(particle.neighbors) do local relativePosition = {liquid._vars.scaledPositions[v][1] - liquid._vars.scaledPositions[index][1],liquid._vars.scaledPositions[v][2] - liquid._vars.scaledPositions[index][2]} if particle.distances[i] < liquid._vars.idealRadius then local q = particle.distances[i] / liquid._vars.idealRadius local oneminusq = 1 - q local factor = oneminusq * (pressure+presnear*oneminusq)/(2*particle.distances[i]) local d = {relativePosition[1]*factor,relativePosition[2]*factor} local relativeVelocity = {liquid._vars.scaledVelocity[v][1] - liquid._vars.scaledVelocity[index][1],liquid._vars.scaledVelocity[v][2] - liquid._vars.scaledVelocity[index][2]} factor = liquid._vars.viscosity * oneminusq*dt d = {d[1] - (relativeVelocity[1]*factor),d[2] - (relativeVelocity[2]*factor)} liquid._vars.delta[v] = {liquid._vars.delta[v][1] + d[1]+deltaGrav[1],liquid._vars.delta[v][2] + d[2]+deltaGrav[2]} change = {change[1]-d[1],change[2]-d[2]} end end liquid._vars.debug[4][2] = os.clock() liquid._vars.delta[index] = {liquid._vars.delta[index][1] + change[1],liquid._vars.delta[index][2] + change[2]} liquid._vars.liquid[index].velocity = {liquid._vars.liquid[index].velocity[1]+velGrav[1],liquid._vars.liquid[index].velocity[2]+velGrav[2]} end liquid._vars.debug[1][2] = os.clock() liquid._vars.debug[5] = {name = 'Position update',os.clock()} for i = 1,liquid._vars.numActiveParticles do local index = liquid._vars.activeParticles[i] particle = liquid._vars.liquid[index] particle.oldPosition = particle.position particle.position = {particle.position[1] + (liquid._vars.delta[index][1]/liquid._vars.multiplier),particle.position[2] + (liquid._vars.delta[index][2]/liquid._vars.multiplier)} particle.velocity = {particle.velocity[1] + (liquid._vars.delta[index][1]/(liquid._vars.multiplier*dt)),particle.velocity[2] + (liquid._vars.delta[index][2]/(liquid._vars.multiplier*dt))} particle.position = {particle.position[1] + (liquid._vars.liquid[index].velocity[1]/liquid._vars.multiplier),particle.position[2] + (liquid._vars.liquid[index].velocity[2]/liquid._vars.multiplier)} if liquid._vars.postUpdate then liquid._vars.postUpdate(i) end local x,y = liquid._vars.grid.transformCoord(particle.position[1]),liquid._vars.grid.transformCoord(particle.position[2]) if x ~= particle.grid[1] or y ~= particle.grid[2] then --print('count on '..particle.grid[2],liquid._vars.grid[particle.grid[1]][particle.grid[2]].count) --print('sending '..particle.grid[1],particle.grid[2],index) liquid._vars.grid.remove(particle.grid[1],particle.grid[2],index) if liquid._vars.grid[particle.grid[1] ][particle.grid[2] ].count == 0 then liquid._vars.grid.remove(particle.grid[1],particle.grid[2]) if liquid._vars.grid[particle.grid[1] ].count == 0 then liquid._vars.grid.remove(particle.grid[1]) end end --print('sending to add '..x,y,index) liquid._vars.grid.add(x,y,index) particle.grid = {x,y} end end liquid._vars.debug[5][2] = os.clock() end function liquid.createParticle(x,y,n) local inactiveParticlei = {} for i,v in ipairs(liquid._vars.liquid) do if not v.alive then table.insert(inactiveParticlei,i) end if #inactiveParticlei == n then break end end for i,v in ipairs(inactiveParticlei) do jitter = {love.math.random()*2 -1, love.math.random() -0.5} liquid._vars.liquid[v] = liquid.newParticle({x+jitter[1],y+jitter[2]},{0,0},true) liquid._vars.scaledPositions[v] = {(x+jitter[1])*liquid._vars.multiplier,(y+jitter[2])*liquid._vars.multiplier} liquid._vars.scaledVelocity[v] = {0,0} liquid._vars.grid.add(liquid._vars.liquid[v].grid[1],liquid._vars.liquid[v].grid[2],v) local exists for a,b in ipairs(liquid._vars.activeParticles) do if b == v then exists = true end end if not exists then table.insert(liquid._vars.activeParticles,v) liquid._vars.numActiveParticles = liquid._vars.numActiveParticles +1 end end end function liquid.postUpdate(func) liquid._vars.postUpdate = func end function liquid.getParticlePosition(i) if liquid._vars.liquid[i] then return liquid._vars.liquid[i].position[1] * liquid._vars.scale,liquid._vars.liquid[i].position[2] * liquid._vars.scale end end function liquid.getOldParticlePosition(i) if liquid._vars.liquid[i] then return liquid._vars.liquid[i].oldPosition[1] * liquid._vars.scale,liquid._vars.liquid[i].oldPosition[2] * liquid._vars.scale end end function liquid.getParticleVelocity(i) if liquid._vars.liquid[i] then return liquid._vars.liquid[i].velocity[1],liquid._vars.liquid[i].velocity[2] end end function liquid.getGravity(...) --x,y, {x,y} return liquid._vars.gravity[1],liquid._vars.gravity[2] end function liquid.moveParticle(i,x,y,updtGrid) if liquid._vars.liquid[i] then if liquid._vars.liquid[i].alive then x,y = x and x/liquid._vars.scale or liquid._vars.liquid[i].position[1], y and y/liquid._vars.scale or liquid._vars.liquid[i].position[2] liquid._vars.liquid[i].position = {x,y} if updtGrid then local x,y = liquid._vars.grid.transformCoord(liquid._vars.liquid[i].position[1]),liquid._vars.grid.transformCoord(liquid._vars.liquid[i].position[2]) if x ~= liquid._vars.liquid[i].grid[1] or y ~= liquid._vars.liquid[i].grid[2] then --print('count on '..liquid._vars.liquid[i].grid[2],liquid._vars.grid[liquid._vars.liquid[i].grid[1]][liquid._vars.liquid[i].grid[2]].count) --print('sending '..liquid._vars.liquid[i].grid[1],liquid._vars.liquid[i].grid[2],index) liquid._vars.grid.remove(liquid._vars.liquid[i].grid[1],liquid._vars.liquid[i].grid[2],i) if liquid._vars.grid[liquid._vars.liquid[i].grid[1]][liquid._vars.liquid[i].grid[2]].count == 0 then liquid._vars.grid.remove(liquid._vars.liquid[i].grid[1],liquid._vars.liquid[i].grid[2]) if liquid._vars.grid[liquid._vars.liquid[i].grid[1]].count == 0 then liquid._vars.grid.remove(liquid._vars.liquid[i].grid[1]) end end --print('sending to add '..x,y,index) liquid._vars.grid.add(x,y,index) liquid._vars.liquid[i].grid = {x,y} end end end end end function liquid.changeVelocity(i,x,y) if liquid._vars.liquid[i] then if liquid._vars.liquid[i].alive then x,y = x or liquid._vars.liquid[i].velocity[1], y or liquid._vars.liquid[i].velocity[2] liquid._vars.liquid[i].velocity = {x,y} end end end function liquid.setGravity(...) --x,y, {x,y} gVec = {...} if #gVec == 1 then gVec = gVec[1] end liquid._vars.gravity = {gVec[1],gVec[2]} end function liquid.draw() local width = love.graphics.getLineWidth() love.graphics.setLineWidth(love.graphics.getHeight()/600) for i,v in ipairs(liquid._vars.activeParticles) do local particle = liquid._vars.liquid[v] local x,y = particle.position[1] * liquid._vars.scale,particle.position[2] * liquid._vars.scale --love.graphics.point(x, y) love.graphics.setColor(255*(particle.pressure/5), 255*((particle.pressure/5)/1.1), 255, 255) love.graphics.line(x, y, x+particle.velocity[1], y+particle.velocity[2]) end love.graphics.setLineWidth(width) love.graphics.setColor(255, 255, 255, 255) end if love.system.getOS() == 'Android' or love.system.getOS() == 'iOS' then function liquid.update(dt) local x,y = love.mouse.getPosition() x,y = (x+math.random(1,10)*math.random(-1,1))/liquid._vars.scale,(y+math.random(1,10)*math.random(-1,1))/liquid._vars.scale for i,v in ipairs( liquid._vars.touch) do liquid.createParticle(v[1]/liquid._vars.scale,v[2]/liquid._vars.scale,math.ceil((120*v[3])*dt)) end liquid.applyLiquidConstraints(dt) end function liquid.touchpressed(id,x,y,p) thing = {x*love.graphics.getWidth(),y*love.graphics.getHeight(),p,true} liquid._vars.touch[#liquid._vars.touch+1] = {x*love.graphics.getWidth(),y*love.graphics.getHeight(),p,true,id} end function liquid.touchreleased(id,x,y,p) for i,v in ipairs(liquid._vars.touch) do if v[5] == id then table.remove(liquid._vars.touch,i) return end end collectgarbage() end function liquid.touchmoved(id,x,y,p) for i,v in ipairs(liquid._vars.touch) do if v[5] == id then liquid._vars.touch[i] = {x*love.graphics.getWidth(),y*love.graphics.getHeight(),p,true,id} end end end else function liquid.update(dt) local x,y = love.mouse.getPosition() x,y = x/liquid._vars.scale,y/liquid._vars.scale if love.mouse.isDown('l') then liquid.createParticle(x,y,4) end liquid.applyLiquidConstraints(1/60) end end return liquid
36.006148
206
0.704627
8a5a27b5ea84bba8cbca3d2e725aee3ea3c05ca3
12,142
rs
Rust
src/sys/device_settings/src/main.rs
liexusong/fuchsia
81897680af92a1848a063e3c20ff3a4892ccff07
[ "BSD-2-Clause" ]
3
2021-09-02T07:21:06.000Z
2022-03-12T03:20:10.000Z
src/sys/device_settings/src/main.rs
liexusong/fuchsia
81897680af92a1848a063e3c20ff3a4892ccff07
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/sys/device_settings/src/main.rs
liexusong/fuchsia
81897680af92a1848a063e3c20ff3a4892ccff07
[ "BSD-2-Clause" ]
2
2022-02-25T12:22:49.000Z
2022-03-12T03:20:10.000Z
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use anyhow::{Context as _, Error}; use fuchsia_async as fasync; use fuchsia_component::server::ServiceFs; use fuchsia_syslog as syslog; use fuchsia_syslog::{fx_log_err, fx_log_info}; use futures::{future, io, StreamExt, TryFutureExt, TryStreamExt}; use parking_lot::Mutex; use std::collections::HashMap; use std::fs::{self, File}; use std::io::prelude::*; use std::sync::Arc; // Include the generated FIDL bindings for the `DeviceSetting` service. use fidl_fuchsia_devicesettings::{ DeviceSettingsManagerRequest, DeviceSettingsManagerRequestStream, DeviceSettingsWatcherProxy, Status, ValueType, }; type Watchers = Arc<Mutex<HashMap<String, Vec<DeviceSettingsWatcherProxy>>>>; struct DeviceSettingsManagerServer { setting_file_map: HashMap<String, String>, watchers: Watchers, } impl DeviceSettingsManagerServer { fn initialize_keys(&mut self, data_dir: &str, keys: &[&str]) { self.setting_file_map = keys .iter() .map(|k| (k.to_string(), format!("{}/{}", data_dir, k.to_lowercase()))) .collect(); } fn run_watchers(&mut self, key: &str, t: ValueType) { let mut map = self.watchers.lock(); if let Some(m) = map.get_mut(key) { m.retain(|w| { if let Err(e) = w.on_change_settings(t) { if e.is_closed() { return false; } fx_log_err!("Error call watcher: {:?}", e); } return true; }); } } fn set_key(&mut self, key: &str, buf: &[u8], t: ValueType) -> io::Result<bool> { match self.setting_file_map.get(key) { Some(file) => write_to_file(file, buf)?, None => return Ok(false), }; self.run_watchers(&key, t); Ok(true) } } static DATA_DIR: &'static str = "/data/device-settings"; fn write_to_file(file: &str, buf: &[u8]) -> io::Result<()> { let mut f = File::create(file)?; f.write_all(buf) } fn read_file(file: &str) -> io::Result<String> { let mut f = File::open(file)?; let mut contents = String::new(); if let Err(e) = f.read_to_string(&mut contents) { return Err(e); } Ok(contents) } fn spawn_device_settings_server( state: DeviceSettingsManagerServer, stream: DeviceSettingsManagerRequestStream, ) { let state = Arc::new(Mutex::new(state)); fasync::Task::spawn( stream .try_for_each(move |req| { let state = state.clone(); let mut state = state.lock(); future::ready(match req { DeviceSettingsManagerRequest::GetInteger { key, responder } => { let file = if let Some(f) = state.setting_file_map.get(&key) { f } else { return future::ready(responder.send(0, Status::ErrInvalidSetting)); }; match read_file(file) { Err(e) => { if e.kind() == io::ErrorKind::NotFound { responder.send(0, Status::ErrNotSet) } else { fx_log_err!("reading integer: {:?}", e); responder.send(0, Status::ErrRead) } } Ok(str) => match str.parse::<i64>() { Err(_e) => responder.send(0, Status::ErrIncorrectType), Ok(i) => responder.send(i, Status::Ok), }, } } DeviceSettingsManagerRequest::GetString { key, responder } => { let file = if let Some(f) = state.setting_file_map.get(&key) { f } else { return future::ready(responder.send("", Status::ErrInvalidSetting)); }; match read_file(file) { Err(e) => { if e.kind() == io::ErrorKind::NotFound { responder.send("", Status::ErrNotSet) } else { fx_log_err!("reading string: {:?}", e); responder.send("", Status::ErrRead) } } Ok(s) => responder.send(&*s, Status::Ok), } } DeviceSettingsManagerRequest::SetInteger { key, val, responder } => { match state.set_key(&key, val.to_string().as_bytes(), ValueType::Number) { Ok(r) => responder.send(r), Err(e) => { fx_log_err!("setting integer: {:?}", e); responder.send(false) } } } DeviceSettingsManagerRequest::SetString { key, val, responder } => { fx_log_info!("setting string key: {:?}, val: {:?}", key, val); match state.set_key(&key, val.as_bytes(), ValueType::Text) { Ok(r) => responder.send(r), Err(e) => { fx_log_err!("setting string: {:?}", e); responder.send(false) } } } DeviceSettingsManagerRequest::Watch { key, watcher, responder } => { if !state.setting_file_map.contains_key(&key) { return future::ready(responder.send(Status::ErrInvalidSetting)); } match watcher.into_proxy() { Err(e) => { fx_log_err!("getting watcher proxy: {:?}", e); responder.send(Status::ErrUnknown) } Ok(w) => { let mut map = state.watchers.lock(); let mv = map.entry(key).or_insert(Vec::new()); mv.push(w); responder.send(Status::Ok) } } } }) }) .map_ok(|_| ()) .unwrap_or_else(|e| eprintln!("error running device settings server: {:?}", e)), ) .detach() } fn main() { if let Err(e) = main_ds() { fx_log_err!("{:?}", e); } } fn main_ds() -> Result<(), Error> { syslog::init_with_tags(&["device_settings"])?; let mut core = fasync::SendExecutor::new().context("unable to create executor")?; let watchers = Arc::new(Mutex::new(HashMap::new())); // Attempt to create data directory fs::create_dir_all(DATA_DIR).context("creating directory")?; let mut fs = ServiceFs::new(); fs.dir("svc").add_fidl_service(move |stream| { let mut d = DeviceSettingsManagerServer { setting_file_map: HashMap::new(), watchers: watchers.clone(), }; d.initialize_keys( DATA_DIR, &["TestSetting", "Display.Brightness", "Audio", "FactoryReset"], ); spawn_device_settings_server(d, stream) }); fs.take_and_serve_directory_handle()?; Ok(core.run(fs.collect(), /* threads */ 2)) } #[cfg(test)] mod tests { use super::*; use fidl_fuchsia_devicesettings::{DeviceSettingsManagerMarker, DeviceSettingsManagerProxy}; use futures::prelude::*; use tempfile::TempDir; fn async_test<F, Fut>(keys: &[&str], f: F) where F: FnOnce(DeviceSettingsManagerProxy) -> Fut, Fut: Future<Output = Result<(), fidl::Error>>, { let (mut exec, device_settings, _t) = setup(keys).expect("Setup should not have failed"); let test_fut = f(device_settings); exec.run_singlethreaded(test_fut).expect("executor run failed"); } fn setup( keys: &[&str], ) -> Result<(fasync::LocalExecutor, DeviceSettingsManagerProxy, TempDir), ()> { let exec = fasync::LocalExecutor::new().unwrap(); let mut device_settings = DeviceSettingsManagerServer { setting_file_map: HashMap::new(), watchers: Arc::new(Mutex::new(HashMap::new())), }; let tmp_dir = TempDir::new().unwrap(); device_settings.initialize_keys(tmp_dir.path().to_str().unwrap(), keys); let (proxy, stream) = fidl::endpoints::create_proxy_and_stream::<DeviceSettingsManagerMarker>().unwrap(); spawn_device_settings_server(device_settings, stream); // return tmp_dir to keep it in scope return Ok((exec, proxy, tmp_dir)); } #[test] fn test_int() { async_test(&["TestKey"], |device_settings| async move { let response = device_settings.set_integer("TestKey", 18).await?; assert!(response, "set_integer failed"); let response = device_settings.get_integer("TestKey").await?; assert_eq!(response, (18, Status::Ok)); Ok(()) }); } #[test] fn test_string() { async_test(&["TestKey"], |device_settings| async move { let response = device_settings.set_string("TestKey", "mystring").await?; assert!(response, "set_string failed"); let response = device_settings.get_string("TestKey").await?; assert_eq!(response, ("mystring".to_string(), Status::Ok)); Ok(()) }); } #[test] fn test_invalid_key() { async_test(&[], |device_settings| async move { let response = device_settings.get_string("TestKey").await?; assert_eq!(response, ("".to_string(), Status::ErrInvalidSetting)); let response = device_settings.get_integer("TestKey").await?; assert_eq!(response, (0, Status::ErrInvalidSetting)); Ok(()) }); } #[test] fn test_incorrect_type() { async_test(&["TestKey"], |device_settings| async move { let response = device_settings.set_string("TestKey", "mystring").await?; assert!(response, "set_string failed"); let response = device_settings.get_integer("TestKey").await?; assert_eq!(response, (0, Status::ErrIncorrectType)); Ok(()) }); } #[test] fn test_not_set_err() { async_test(&["TestKey"], |device_settings| async move { let response = device_settings.get_integer("TestKey").await?; assert_eq!(response, (0, Status::ErrNotSet)); let response = device_settings.get_string("TestKey").await?; assert_eq!(response, ("".to_string(), Status::ErrNotSet)); Ok(()) }); } #[test] fn test_multiple_keys() { async_test(&["TestKey1", "TestKey2"], |device_settings| async move { let response = device_settings.set_integer("TestKey1", 18).await?; assert!(response, "set_integer failed"); let response = device_settings.set_string("TestKey2", "mystring").await?; assert!(response, "set_string failed"); let response = device_settings.get_integer("TestKey1").await?; assert_eq!(response, (18, Status::Ok)); let response = device_settings.get_string("TestKey2").await?; assert_eq!(response, ("mystring".to_string(), Status::Ok)); Ok(()) }); } }
38.302839
98
0.504942
7fe2a04bcb9926c7cfbff683e31c8d7a2fe5b183
4,869
go
Go
dec_calibrate_test.go
db47h/decimal
83ef17a6ceecac491abc5b1ee4c7d62b3bd1913d
[ "BSD-2-Clause", "BSD-3-Clause" ]
26
2020-05-28T02:00:20.000Z
2022-01-24T07:16:12.000Z
dec_calibrate_test.go
db47h/decimal
83ef17a6ceecac491abc5b1ee4c7d62b3bd1913d
[ "BSD-2-Clause", "BSD-3-Clause" ]
1
2020-05-28T14:06:39.000Z
2020-05-28T14:41:30.000Z
dec_calibrate_test.go
db47h/decimal
83ef17a6ceecac491abc5b1ee4c7d62b3bd1913d
[ "BSD-2-Clause", "BSD-3-Clause" ]
3
2021-12-04T13:26:38.000Z
2022-03-20T11:19:43.000Z
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Calibration used to determine thresholds for using // different algorithms. Ideally, this would be converted // to go generate to create thresholds.go // This file prints execution times for the Mul benchmark // given different Karatsuba thresholds. The result may be // used to manually fine-tune the threshold constant. The // results are somewhat fragile; use repeated runs to get // a clear picture. // Calculates lower and upper thresholds for when basicSqr // is faster than standard multiplication. // Usage: go test -run=TestDecCalibrate -v -calibrate -cpu 1 // Forcing a single logical CPU seems to yield more stable // benchmarks. package decimal import ( "flag" "fmt" "testing" "time" ) var calibrate = flag.Bool("calibrate", false, "run calibration test") const ( sqrModeMul = "mul(x, x)" sqrModeBasic = "basicSqr(x)" sqrModeKaratsuba = "karatsubaSqr(x)" ) func TestDecCalibrate(t *testing.T) { if !*calibrate { return } computeKaratsubaThresholds() // compute basicSqrThreshold where overhead becomes negligible minSqr := computeSqrThreshold(5, 20, 1, 3, sqrModeMul, sqrModeBasic) // compute karatsubaSqrThreshold where karatsuba is faster maxSqr := computeSqrThreshold(30, 300, 10, 3, sqrModeBasic, sqrModeKaratsuba) if minSqr != 0 { fmt.Printf("found basicSqrThreshold = %d\n", minSqr) } else { fmt.Println("no basicSqrThreshold found") } if maxSqr != 0 { fmt.Printf("found karatsubaSqrThreshold = %d\n", maxSqr) } else { fmt.Println("no karatsubaSqrThreshold found") } } func karatsubaLoad(b *testing.B) { BenchmarkDecMul1e4(b) } // measureKaratsuba returns the time to run a Karatsuba-relevant benchmark // given Karatsuba threshold th. func measureKaratsuba(th int) time.Duration { th, decKaratsubaThreshold = decKaratsubaThreshold, th res := testing.Benchmark(karatsubaLoad) decKaratsubaThreshold = th return time.Duration(res.NsPerOp()) } func computeKaratsubaThresholds() { fmt.Printf("Multiplication times for varying Karatsuba thresholds\n") fmt.Printf("(run repeatedly for good results)\n") // determine Tk, the work load execution time using basic multiplication Tb := measureKaratsuba(1e9) // th == 1e9 => Karatsuba multiplication disabled fmt.Printf("Tb = %10s\n", Tb) // thresholds th := 4 th1 := -1 th2 := -1 var deltaOld time.Duration for count := -1; count != 0 && th < 128; count-- { // determine Tk, the work load execution time using Karatsuba multiplication Tk := measureKaratsuba(th) // improvement over Tb delta := (Tb - Tk) * 100 / Tb fmt.Printf("th = %3d Tk = %10s %4d%%", th, Tk, delta) // determine break-even point if Tk < Tb && th1 < 0 { th1 = th fmt.Print(" break-even point") } // determine diminishing return if 0 < delta && delta < deltaOld && th2 < 0 { th2 = th fmt.Print(" diminishing return") } deltaOld = delta fmt.Println() // trigger counter if th1 >= 0 && th2 >= 0 && count < 0 { count = 10 // this many extra measurements after we got both thresholds } th++ } } func measureSqr(words, nruns int, mode string) time.Duration { // more runs for better statistics initBasicSqr, initKaratsubaSqr := decBasicSqrThreshold, decKaratsubaSqrThreshold switch mode { case sqrModeMul: decBasicSqrThreshold = words + 1 case sqrModeBasic: decBasicSqrThreshold, decKaratsubaSqrThreshold = words-1, words+1 case sqrModeKaratsuba: decKaratsubaSqrThreshold = words - 1 } var testval int64 for i := 0; i < nruns; i++ { res := testing.Benchmark(func(b *testing.B) { benchmarkDecSqr(b, words) }) testval += res.NsPerOp() } testval /= int64(nruns) decBasicSqrThreshold, decKaratsubaSqrThreshold = initBasicSqr, initKaratsubaSqr return time.Duration(testval) } func computeSqrThreshold(from, to, step, nruns int, lower, upper string) int { fmt.Printf("Calibrating threshold between %s and %s\n", lower, upper) fmt.Printf("Looking for a timing difference for x between %d - %d words by %d step\n", from, to, step) var initPos bool var threshold int for i := from; i <= to; i += step { baseline := measureSqr(i, nruns, lower) testval := measureSqr(i, nruns, upper) pos := baseline > testval delta := baseline - testval percent := delta * 100 / baseline fmt.Printf("words = %3d deltaT = %10s (%4d%%) is %s better: %v", i, delta, percent, upper, pos) if i == from { initPos = pos } if threshold == 0 && pos != initPos { threshold = i fmt.Printf(" threshold found") } fmt.Println() } if threshold != 0 { fmt.Printf("Found threshold = %d between %d - %d\n", threshold, from, to) } else { fmt.Printf("Found NO threshold between %d - %d\n", from, to) } return threshold }
27.664773
103
0.699733
5c3c55a432ef583f8ce1b3e78f2931672959f5c2
865
h
C
tools/brcm/hndtools-mipsel-uclibc-0.9.19/include/linux/netfilter_ipv4/ipt_mport.h
enfoTek/tomato.linksys.e2000.nvram-mod
2ce3a5217def49d6df7348522e2bfda702b56029
[ "FSFAP" ]
278
2015-11-03T03:01:20.000Z
2022-01-20T18:21:05.000Z
tools/brcm/hndtools-mipsel-uclibc-0.9.19/include/linux/netfilter_ipv4/ipt_mport.h
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
374
2015-11-03T12:37:22.000Z
2021-12-17T14:18:08.000Z
tools/brcm/hndtools-mipsel-uclibc-0.9.19/include/linux/netfilter_ipv4/ipt_mport.h
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
96
2015-11-22T07:47:26.000Z
2022-01-20T19:52:19.000Z
#ifndef _IPT_MPORT_H #define _IPT_MPORT_H #include <linux/netfilter_ipv4/ip_tables.h> #define IPT_MPORT_SOURCE (1<<0) #define IPT_MPORT_DESTINATION (1<<1) #define IPT_MPORT_EITHER (IPT_MPORT_SOURCE|IPT_MPORT_DESTINATION) #define IPT_MULTI_PORTS 15 /* Must fit inside union ipt_matchinfo: 32 bytes */ /* every entry in ports[] except for the last one has one bit in pflags * associated with it. If this bit is set, the port is the first port of * a portrange, with the next entry being the last. * End of list is marked with pflags bit set and port=65535. * If 14 ports are used (last one does not have a pflag), the last port * is repeated to fill the last entry in ports[] */ struct ipt_mport { u_int8_t flags:2; /* Type of comparison */ u_int16_t pflags:14; /* Port flags */ u_int16_t ports[IPT_MULTI_PORTS]; /* Ports */ }; #endif /*_IPT_MPORT_H*/
34.6
72
0.742197
3a06161849c1542a0824d0f5898b88923b62d454
4,869
asm
Assembly
coverage/IN_CTS/0470-COVERAGE-brw-nir-opt-peephole-ffma-231/work/variant/1_spirv_asm/shader.frag.asm
asuonpaa/ShaderTests
6a3672040dcfa0d164d313224446496d1775a15e
[ "Apache-2.0" ]
null
null
null
coverage/IN_CTS/0470-COVERAGE-brw-nir-opt-peephole-ffma-231/work/variant/1_spirv_asm/shader.frag.asm
asuonpaa/ShaderTests
6a3672040dcfa0d164d313224446496d1775a15e
[ "Apache-2.0" ]
47
2021-03-11T07:42:51.000Z
2022-03-14T06:30:14.000Z
coverage/IN_CTS/0470-COVERAGE-brw-nir-opt-peephole-ffma-231/work/variant/1_spirv_asm/shader.frag.asm
asuonpaa/ShaderTests
6a3672040dcfa0d164d313224446496d1775a15e
[ "Apache-2.0" ]
4
2021-03-09T13:37:19.000Z
2022-02-25T07:32:11.000Z
; SPIR-V ; Version: 1.0 ; Generator: Khronos Glslang Reference Front End; 10 ; Bound: 88 ; Schema: 0 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" %69 OpExecutionMode %4 OriginUpperLeft OpSource ESSL 320 OpName %4 "main" OpName %8 "f" OpName %12 "buf0" OpMemberName %12 0 "_GLF_uniform_float_values" OpName %14 "" OpName %21 "i" OpName %24 "buf1" OpMemberName %24 0 "_GLF_uniform_int_values" OpName %26 "" OpName %69 "_GLF_color" OpDecorate %11 ArrayStride 16 OpMemberDecorate %12 0 Offset 0 OpDecorate %12 Block OpDecorate %14 DescriptorSet 0 OpDecorate %14 Binding 0 OpDecorate %23 ArrayStride 16 OpMemberDecorate %24 0 Offset 0 OpDecorate %24 Block OpDecorate %26 DescriptorSet 0 OpDecorate %26 Binding 1 OpDecorate %69 Location 0 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeFloat 32 %7 = OpTypePointer Function %6 %9 = OpTypeInt 32 0 %10 = OpConstant %9 4 %11 = OpTypeArray %6 %10 %12 = OpTypeStruct %11 %13 = OpTypePointer Uniform %12 %14 = OpVariable %13 Uniform %15 = OpTypeInt 32 1 %16 = OpConstant %15 0 %17 = OpTypePointer Uniform %6 %20 = OpTypePointer Function %15 %22 = OpConstant %9 3 %23 = OpTypeArray %15 %22 %24 = OpTypeStruct %23 %25 = OpTypePointer Uniform %24 %26 = OpVariable %25 Uniform %27 = OpConstant %15 1 %28 = OpTypePointer Uniform %15 %39 = OpTypeBool %41 = OpConstant %15 3 %60 = OpConstant %15 2 %67 = OpTypeVector %6 4 %68 = OpTypePointer Output %67 %69 = OpVariable %68 Output %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %21 = OpVariable %20 Function %18 = OpAccessChain %17 %14 %16 %16 %19 = OpLoad %6 %18 OpStore %8 %19 %29 = OpAccessChain %28 %26 %16 %27 %30 = OpLoad %15 %29 OpStore %21 %30 OpBranch %31 %31 = OpLabel OpLoopMerge %33 %34 None OpBranch %35 %35 = OpLabel %36 = OpLoad %15 %21 %37 = OpAccessChain %28 %26 %16 %16 %38 = OpLoad %15 %37 %40 = OpSLessThan %39 %36 %38 OpBranchConditional %40 %32 %33 %32 = OpLabel %42 = OpAccessChain %17 %14 %16 %41 %43 = OpLoad %6 %42 %44 = OpFNegate %6 %43 %45 = OpLoad %6 %8 %46 = OpFMul %6 %44 %45 %47 = OpExtInst %6 %1 FAbs %46 %48 = OpAccessChain %17 %14 %16 %16 %49 = OpLoad %6 %48 %50 = OpFAdd %6 %47 %49 OpStore %8 %50 OpBranch %34 %34 = OpLabel %51 = OpLoad %15 %21 %52 = OpIAdd %15 %51 %27 OpStore %21 %52 OpBranch %31 %33 = OpLabel %53 = OpLoad %6 %8 %54 = OpAccessChain %17 %14 %16 %27 %55 = OpLoad %6 %54 %56 = OpFOrdGreaterThan %39 %53 %55 OpSelectionMerge %58 None OpBranchConditional %56 %57 %58 %57 = OpLabel %59 = OpLoad %6 %8 %61 = OpAccessChain %17 %14 %16 %60 %62 = OpLoad %6 %61 %63 = OpFOrdLessThan %39 %59 %62 OpBranch %58 %58 = OpLabel %64 = OpPhi %39 %56 %33 %63 %57 OpSelectionMerge %66 None OpBranchConditional %64 %65 %83 %65 = OpLabel %70 = OpAccessChain %28 %26 %16 %60 %71 = OpLoad %15 %70 %72 = OpConvertSToF %6 %71 %73 = OpAccessChain %28 %26 %16 %27 %74 = OpLoad %15 %73 %75 = OpConvertSToF %6 %74 %76 = OpAccessChain %28 %26 %16 %27 %77 = OpLoad %15 %76 %78 = OpConvertSToF %6 %77 %79 = OpAccessChain %28 %26 %16 %60 %80 = OpLoad %15 %79 %81 = OpConvertSToF %6 %80 %82 = OpCompositeConstruct %67 %72 %75 %78 %81 OpStore %69 %82 OpBranch %66 %83 = OpLabel %84 = OpAccessChain %28 %26 %16 %27 %85 = OpLoad %15 %84 %86 = OpConvertSToF %6 %85 %87 = OpCompositeConstruct %67 %86 %86 %86 %86 OpStore %69 %87 OpBranch %66 %66 = OpLabel OpReturn OpFunctionEnd
34.778571
61
0.479154
8fc7de74b82bcc02dcb2e2f5fd2f76a87bc75a74
12,827
swift
Swift
WePeiYang/PartyService/Controller/QuizTakingViewController.swift
twtstudio/WePeiYang-iOS-old
cf93f2ac090553d2d3ac5d9f5d2e7377723c4aef
[ "MIT" ]
19
2016-08-11T04:08:10.000Z
2020-10-16T23:47:28.000Z
WePeiYang/PartyService/Controller/QuizTakingViewController.swift
twtstudio/WePeiYang-iOS-old
cf93f2ac090553d2d3ac5d9f5d2e7377723c4aef
[ "MIT" ]
1
2017-01-14T16:09:10.000Z
2017-01-14T16:09:10.000Z
WePeiYang/PartyService/Controller/QuizTakingViewController.swift
twtstudio/WePeiYang-iOS-old
cf93f2ac090553d2d3ac5d9f5d2e7377723c4aef
[ "MIT" ]
2
2016-08-13T03:03:02.000Z
2017-06-08T06:56:30.000Z
// // QuizTakingViewController.swift // WePeiYang // // Created by Allen X on 8/24/16. // Copyright © 2016 Qin Yubo. All rights reserved. // class QuizTakingViewController: UIViewController { typealias Quiz = Courses.Study20.Quiz var courseID: String? = nil var currentQuizIndex = 0 //static var originalAnswer: [Int] = [] //static var userAnswer: [Int] = [] let bottomTabBar = UIView(color: .whiteColor()) var bgView: UIView! var quizView: QuizView! /* let lastQuiz: UIButton = { let foo = UIButton(title: "上一题") foo.titleLabel?.textColor = .whiteColor() foo.layer.cornerRadius = 8 foo.backgroundColor = .redColor() foo.addTarget(QuizTakingViewController(), action: #selector(QuizTakingViewController.swipeToLastQuiz), forControlEvents: .TouchUpInside) return foo }() let nextQuiz: UIButton = { let foo = UIButton(title: "下一题") foo.titleLabel?.textColor = .whiteColor() foo.layer.cornerRadius = 8 foo.backgroundColor = .redColor() foo.addTarget(QuizTakingViewController(), action: #selector(QuizTakingViewController.swipeToNextQuiz), forControlEvents: .TouchUpInside) return foo }() let allQuizes: UIButton = { let foo = UIButton(title: "所有题目") foo.titleLabel?.textColor = .whiteColor() foo.layer.cornerRadius = 8 foo.backgroundColor = .redColor() foo.addTarget(QuizTakingViewController(), action: #selector(QuizTakingViewController.showAllQuizesList), forControlEvents: .TouchUpInside) return foo }()*/ let lastQuiz = UIButton(title: "上一题") let nextQuiz = UIButton(title: "下一题") let allQuizes = UIButton(title: "所有题目") var quizList: [Quiz?] = [] override func viewWillAppear(animated: Bool) { self.view.frame.size.width = (UIApplication.sharedApplication().keyWindow?.frame.size.width)! //NavigationBar 的文字 self.navigationController!.navigationBar.tintColor = UIColor.whiteColor() //NavigationBar 的背景,使用了View self.navigationController!.jz_navigationBarBackgroundAlpha = 0; bgView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.navigationController!.navigationBar.frame.size.height+UIApplication.sharedApplication().statusBarFrame.size.height)) bgView.backgroundColor = partyRed self.view.addSubview(bgView) //改变 statusBar 颜色 UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: true) let quizSubmitBtn = UIBarButtonItem(title: "交卷", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(QuizTakingViewController.submitAnswer)) self.navigationItem.setRightBarButtonItem(quizSubmitBtn, animated: true) } override func viewDidLoad() { super.viewDidLoad() lastQuiz.titleLabel?.textColor = .whiteColor() lastQuiz.layer.cornerRadius = 8 lastQuiz.backgroundColor = .redColor() lastQuiz.addTarget(QuizTakingViewController(), action: #selector(QuizTakingViewController.swipeToLastQuiz), forControlEvents: .TouchUpInside) nextQuiz.titleLabel?.textColor = .whiteColor() nextQuiz.layer.cornerRadius = 8 nextQuiz.backgroundColor = .redColor() nextQuiz.addTarget(QuizTakingViewController(), action: #selector(QuizTakingViewController.swipeToNextQuiz), forControlEvents: .TouchUpInside) allQuizes.titleLabel?.textColor = .whiteColor() allQuizes.layer.cornerRadius = 8 allQuizes.backgroundColor = .redColor() allQuizes.addTarget(QuizTakingViewController(), action: #selector(QuizTakingViewController.showAllQuizesList), forControlEvents: .TouchUpInside) quizView = QuizView(quiz: Courses.Study20.courseQuizes[currentQuizIndex]!, at: currentQuizIndex) computeLayout() let shadowPath = UIBezierPath(rect: bottomTabBar.bounds) bottomTabBar.layer.masksToBounds = false bottomTabBar.layer.shadowColor = UIColor.blackColor().CGColor bottomTabBar.layer.shadowOffset = CGSizeMake(0.0, 0.5) bottomTabBar.layer.shadowOpacity = 0.5 bottomTabBar.layer.shadowPath = shadowPath.CGPath } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } //SnapKit layout Computation extension QuizTakingViewController { func computeLayout() { self.bottomTabBar.addSubview(lastQuiz) lastQuiz.snp_makeConstraints { make in make.left.equalTo(self.bottomTabBar).offset(10) make.centerY.equalTo(self.bottomTabBar) make.width.equalTo(88) } self.bottomTabBar.addSubview(nextQuiz) nextQuiz.snp_makeConstraints { make in make.right.equalTo(self.bottomTabBar).offset(-10) make.centerY.equalTo(self.bottomTabBar) make.width.equalTo(88) } self.bottomTabBar.addSubview(allQuizes) allQuizes.snp_makeConstraints { make in make.center.equalTo(self.bottomTabBar) make.width.equalTo(88) } self.view.addSubview(bottomTabBar) bottomTabBar.snp_makeConstraints { make in make.left.equalTo(self.view) make.right.equalTo(self.view) make.bottom.equalTo(self.view) make.height.equalTo(60) } self.view.addSubview(quizView) quizView.snp_makeConstraints { make in make.top.equalTo(self.view).offset(self.navigationController!.navigationBar.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height + 18) make.left.equalTo(self.view) make.right.equalTo(self.view) make.bottom.equalTo(self.bottomTabBar.snp_top) } } } extension QuizTakingViewController { convenience init(courseID: String) { self.init() self.courseID = courseID } } //Logic Func extension QuizTakingViewController { func submitAnswer() { //处理当前 quiz for fooView in self.view.subviews { if fooView.isKindOfClass(QuizView) { Courses.Study20.courseQuizes[fooView.tag]?.userAnswer = (fooView as! QuizView).calculateUserAnswerWeight() (fooView as! QuizView).saveChoiceStatus() } } let userAnswer = Courses.Study20.courseQuizes.flatMap { (quiz: Quiz?) -> Int? in guard let foo = quiz?.userAnswer else { MsgDisplay.showErrorMsg("你还没有完成答题,不能交卷") return nil } return foo } let originalAnswer = Courses.Study20.courseQuizes.flatMap { (quiz: Quiz?) -> Int? in guard let foo = Int((quiz?.answer)!) else { MsgDisplay.showErrorMsg("OOPS") return nil } return foo } //log.any(originalAnswer)/ //log.any(userAnswer)/ guard originalAnswer.count == userAnswer.count else { return } Courses.Study20.submitAnswer(of: self.courseID!, originalAnswer: originalAnswer, userAnswer: userAnswer) { let finishBtn = UIBarButtonItem(title: "完成", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(QuizTakingViewController.finishQuizTaking)) self.navigationItem.setRightBarButtonItem(finishBtn, animated: true) let finishView = FinalView(status: Courses.Study20.finalStatusAfterSubmitting!, msg: Courses.Study20.finalMsgAfterSubmitting!) for fooView in self.view.subviews { if fooView.isKindOfClass(QuizView) || fooView.isEqual(self.bottomTabBar) { fooView.removeFromSuperview() } } self.view.addSubview(finishView) finishView.snp_makeConstraints { make in make.top.equalTo(self.view).offset(self.navigationController!.navigationBar.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height + 18) make.left.equalTo(self.view) make.right.equalTo(self.view) make.bottom.equalTo(self.view) } } } func swipeToNextQuiz() { self.currentQuizIndex += 1 guard currentQuizIndex != Courses.Study20.courseQuizes.count else { MsgDisplay.showErrorMsg("你已经在最后一道题啦") self.currentQuizIndex -= 1 return } for fooView in self.view.subviews { if fooView.isKindOfClass(QuizView) { Courses.Study20.courseQuizes[fooView.tag]?.userAnswer = (fooView as! QuizView).calculateUserAnswerWeight() (fooView as! QuizView).saveChoiceStatus() fooView.removeFromSuperview() } } quizView = QuizView(quiz: Courses.Study20.courseQuizes[currentQuizIndex]!, at: currentQuizIndex) self.view.addSubview(quizView) quizView.snp_makeConstraints { make in make.top.equalTo(self.view).offset(self.navigationController!.navigationBar.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height + 18) make.left.equalTo(self.view) make.right.equalTo(self.view) make.bottom.equalTo(self.bottomTabBar.snp_top) } } func swipeToLastQuiz() { self.currentQuizIndex -= 1 guard currentQuizIndex >= 0 else { MsgDisplay.showErrorMsg("你已经在第一题啦") self.currentQuizIndex += 1 return } quizView = QuizView(quiz: Courses.Study20.courseQuizes[currentQuizIndex]!, at: currentQuizIndex) for fooView in self.view.subviews { if fooView.isKindOfClass(QuizView) { Courses.Study20.courseQuizes[fooView.tag]?.userAnswer = (fooView as! QuizView).calculateUserAnswerWeight() (fooView as! QuizView).saveChoiceStatus() //log.any(Courses.Study20.courseQuizes[fooView.tag])/ fooView.removeFromSuperview() } } self.view.addSubview(quizView) quizView.snp_makeConstraints { make in make.top.equalTo(self.view).offset(self.navigationController!.navigationBar.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height + 18) make.left.equalTo(self.view) make.right.equalTo(self.view) make.bottom.equalTo(self.bottomTabBar.snp_top) } } func showAllQuizesList() { //Handle current quiz for fooView in self.view.subviews { if fooView.isKindOfClass(QuizView) { Courses.Study20.courseQuizes[fooView.tag]?.userAnswer = (fooView as! QuizView).calculateUserAnswerWeight() (fooView as! QuizView).saveChoiceStatus() //log.any(Courses.Study20.courseQuizes[fooView.tag])/ } } let allVC = AllQuizViewController(quizList: Courses.Study20.courseQuizes) self.presentViewController(allVC, animated: true, completion: nil) } func showQuizAtIndex(at index: Int) { for fooView in self.view.subviews { if fooView.isKindOfClass(QuizView) { Courses.Study20.courseQuizes[fooView.tag]?.userAnswer = (fooView as! QuizView).calculateUserAnswerWeight() (fooView as! QuizView).saveChoiceStatus() //log.any(Courses.Study20.courseQuizes[fooView.tag])/ fooView.removeFromSuperview() } } self.currentQuizIndex = index quizView = QuizView(quiz: Courses.Study20.courseQuizes[currentQuizIndex]!, at: currentQuizIndex) self.view.addSubview(quizView) quizView.snp_makeConstraints { make in make.top.equalTo(self.view).offset(self.navigationController!.navigationBar.frame.size.height + UIApplication.sharedApplication().statusBarFrame.size.height + 18) make.left.equalTo(self.view) make.right.equalTo(self.view) make.bottom.equalTo(self.bottomTabBar.snp_top) } } func finishQuizTaking() { //self.dismissViewControllerAnimated(true, completion: nil) self.navigationController?.popViewControllerAnimated(true) } }
38.635542
214
0.629609
90c650cd1a5d5efc781549309236edb6cd9b31e7
3,325
dart
Dart
lib/main.dart
vikas-0/Distoptim
1b0ea9d275f4798bdde54357f46c52e58a2807a1
[ "MIT" ]
null
null
null
lib/main.dart
vikas-0/Distoptim
1b0ea9d275f4798bdde54357f46c52e58a2807a1
[ "MIT" ]
null
null
null
lib/main.dart
vikas-0/Distoptim
1b0ea9d275f4798bdde54357f46c52e58a2807a1
[ "MIT" ]
null
null
null
import 'package:dist_guesser_application/screen/about.dart'; import 'package:dist_guesser_application/screen/game.dart'; import 'package:dist_guesser_application/screen/leaderboard.dart'; import 'package:dist_guesser_application/screen/welcome.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:flutter/material.dart'; // Import the generated file import 'firebase_options.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Distance Guesser', theme: ThemeData( brightness: Brightness.dark, primarySwatch: Colors.indigo, canvasColor: Colors.indigo.shade900, textTheme: GoogleFonts.shareTechMonoTextTheme( const TextTheme( headline1: TextStyle( fontSize: 72.0, fontWeight: FontWeight.bold, color: Colors.white, ), headline2: TextStyle( fontSize: 36.0, fontWeight: FontWeight.bold, color: Colors.white, ), headline3: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, color: Colors.white, ), headline4: TextStyle( fontSize: 14.0, fontWeight: FontWeight.bold, color: Colors.white, ), headline5: TextStyle( fontSize: 12.0, fontWeight: FontWeight.bold, color: Colors.white, ), headline6: TextStyle( fontSize: 10.0, fontWeight: FontWeight.bold, color: Colors.white, ), bodyText1: TextStyle( fontSize: 14.0, fontWeight: FontWeight.bold, color: Colors.white, ), bodyText2: TextStyle( fontSize: 12.0, fontWeight: FontWeight.bold, color: Colors.white, ), button: TextStyle( fontSize: 14.0, fontWeight: FontWeight.bold, color: Colors.white, ), caption: TextStyle( fontSize: 12.0, fontWeight: FontWeight.bold, color: Colors.white, ), overline: TextStyle( fontSize: 10.0, fontWeight: FontWeight.bold, color: Colors.white, ), ), )), routes: <String, WidgetBuilder>{ '/': (BuildContext context) => const WelcomScreen(), '/game': (BuildContext context) => const GameScreen(), '/leaderboard': (BuildContext context) => const LeaderBoardScreen(), '/about': (BuildContext context) => const AboutScreen() }, initialRoute: '/', ); } }
33.25
76
0.538947
0bc80f63508ab7bf37d2b65ca6150615bcbcc537
625
js
JavaScript
resources/adminapp/js/store/store.js
Vong3432/webdev_test
0ae804ce80ea8df9a0b5ffe0f133753f465ab1fb
[ "MIT" ]
null
null
null
resources/adminapp/js/store/store.js
Vong3432/webdev_test
0ae804ce80ea8df9a0b5ffe0f133753f465ab1fb
[ "MIT" ]
4
2021-02-02T18:10:05.000Z
2022-02-27T10:09:18.000Z
resources/adminapp/js/store/store.js
petrcz26/laravel-php
9aa8d6754b909139ac0a9c01640efc651b518aa4
[ "MIT" ]
null
null
null
import Vue from 'vue' import Vuex from 'vuex' import Alert from './modules/alert' import PermissionsIndex from './cruds/Permissions' import PermissionsSingle from './cruds/Permissions/single' import RolesIndex from './cruds/Roles' import RolesSingle from './cruds/Roles/single' import UsersIndex from './cruds/Users' import UsersSingle from './cruds/Users/single' Vue.use(Vuex) const debug = process.env.NODE_ENV !== 'production' export default new Vuex.Store({ modules: { Alert, PermissionsIndex, PermissionsSingle, RolesIndex, RolesSingle, UsersIndex, UsersSingle }, strict: debug })
21.551724
58
0.7312
67213270dceb26b6f57fc532ab33daee0066bb87
2,100
asm
Assembly
libs/CPC_V1_SimplePalette.asm
CurlyPaul/cpc-z80-twisting-tower
7cdab1cb9871cd6248ae41e8e201f280d9bc1031
[ "MIT" ]
2
2021-07-06T14:03:11.000Z
2021-07-06T22:16:43.000Z
libs/CPC_V1_SimplePalette.asm
CurlyPaul/cpc-z80-twisting-tower
7cdab1cb9871cd6248ae41e8e201f280d9bc1031
[ "MIT" ]
null
null
null
libs/CPC_V1_SimplePalette.asm
CurlyPaul/cpc-z80-twisting-tower
7cdab1cb9871cd6248ae41e8e201f280d9bc1031
[ "MIT" ]
null
null
null
;;******************************************************************************************** ;; Originally based an example at http://www.cpcwiki.eu/index.php/Programming An_example_loader ;;******************************************************************************************** ColourPalette: ; hardware colours defb &44 ;; #0 Darkest Blue defb &55 ;; #1 Blue defb &57 ;; #2 Blue defb &5B ;; #3 Brightest Blue defb &4B ;; #4 White defb &5B ;; #5 defb &53 ;; #6 defb &5E ;; #7 defb &58 ;; #8 Darkest Purple defb &5D ;; #9 Purple defb &5F ;; #10 Purple defb &5B ;; #11 Brightest Purple (actually blue looks best here) defb &4B ;; #12 Another white defb &4C ;; #13 defb &54 ;; #14 Black defb &46 ;; #15 Background defb &46 ;; Border Palette_Init: ;; CPC has some quirks here as well, seems to be caused by the ability to flash each colour ;; ;; http://www.cpcwiki.eu/forum/programming/screen-scrolling-and-ink-commands/ ;; https://www.cpcwiki.eu/forum/programming/bios-call-scr_set_ink-and-interrupts/ ld hl,ColourPalette call SetupColours ret Palette_AllBackground: ld b,17 ;; 16 colours + 1 border xor a ;; start with pen 0 ld e,&46 DoColours_AllBlack: push bc ;; need to stash b as we are using it for our loop and need it ;; below to write to the port ld bc,&7F00 out (c),a ;; PENR:&7F{pp} - where pp is the palette/pen number out (c),e ;; INKR:&7F{hc} - where hc is the hardware colour number pop bc inc a ;; increment pen number djnz DoColours_AllBlack ret SetupColours: ;; Inputs: HL Address the palette values are stored ld b,17 ;; 16 colours + 1 border xor a ;; start with pen 0 DoColours: push bc ;; need to stash b as we are using it for our loop and need it ;; below to write to the port ld e,(hl) ;; read the value of the colour we want into e inc hl ;; move along ready for next time ld bc,&7F00 out (c),a ;; PENR:&7F{pp} - where pp is the palette/pen number out (c),e ;; INKR:&7F{hc} - where hc is the hardware colour number pop bc inc a ;; increment pen number djnz DoColours ret
31.343284
95
0.612381
83d924271ecdc5c5d8442e70bf9d2baf9b133a53
1,422
rs
Rust
crypto-primitives/src/commitment/injective_map/mod.rs
AleoHQ/zexe
d190054f587791da790d372be62867809e251f12
[ "Apache-2.0", "MIT" ]
3
2020-03-29T19:59:17.000Z
2020-09-10T02:53:31.000Z
crypto-primitives/src/commitment/injective_map/mod.rs
AleoHQ/zexe
d190054f587791da790d372be62867809e251f12
[ "Apache-2.0", "MIT" ]
null
null
null
crypto-primitives/src/commitment/injective_map/mod.rs
AleoHQ/zexe
d190054f587791da790d372be62867809e251f12
[ "Apache-2.0", "MIT" ]
1
2021-11-17T07:29:00.000Z
2021-11-17T07:29:00.000Z
use crate::Error; use core::marker::PhantomData; use rand::Rng; use super::{ pedersen::{PedersenCommitment, PedersenParameters, PedersenRandomness, PedersenWindow}, CommitmentScheme, }; pub use crate::crh::injective_map::InjectiveMap; use algebra_core::groups::Group; #[cfg(feature = "r1cs")] pub mod constraints; pub struct PedersenCommCompressor<G: Group, I: InjectiveMap<G>, W: PedersenWindow> { _group: PhantomData<G>, _compressor: PhantomData<I>, _comm: PedersenCommitment<G, W>, } impl<G: Group, I: InjectiveMap<G>, W: PedersenWindow> CommitmentScheme for PedersenCommCompressor<G, I, W> { type Output = I::Output; type Parameters = PedersenParameters<G>; type Randomness = PedersenRandomness<G>; fn setup<R: Rng>(rng: &mut R) -> Result<Self::Parameters, Error> { let time = start_timer!(|| format!("PedersenCompressor::Setup")); let params = PedersenCommitment::<G, W>::setup(rng); end_timer!(time); params } fn commit( parameters: &Self::Parameters, input: &[u8], randomness: &Self::Randomness, ) -> Result<Self::Output, Error> { let eval_time = start_timer!(|| "PedersenCompressor::Eval"); let result = I::injective_map(&PedersenCommitment::<G, W>::commit( parameters, input, randomness, )?)?; end_timer!(eval_time); Ok(result) } }
29.625
91
0.644163
e9cc0f00615f859f2b812a0f14a79897624a8ca8
2,885
rb
Ruby
Formula/gst-plugins-rs.rb
gerardbosch/homebrew-core
c6001df23bacf2ee9c42896733d8ceb921043649
[ "BSD-2-Clause" ]
null
null
null
Formula/gst-plugins-rs.rb
gerardbosch/homebrew-core
c6001df23bacf2ee9c42896733d8ceb921043649
[ "BSD-2-Clause" ]
null
null
null
Formula/gst-plugins-rs.rb
gerardbosch/homebrew-core
c6001df23bacf2ee9c42896733d8ceb921043649
[ "BSD-2-Clause" ]
null
null
null
class GstPluginsRs < Formula desc "GStreamer plugins written in Rust" homepage "https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs" url "https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs/-/archive/0.8.4/gst-plugins-rs-0.8.4.tar.bz2" sha256 "c3499bb73d44f93f0d5238a09e121bef96750e8869651e09daaee5777c2e215c" license "MIT" revision 1 bottle do sha256 cellar: :any, arm64_monterey: "63dae8a153e2bdbd5df4aefcd3b9f0284193ff6c445622fa6856e576b81e124b" sha256 cellar: :any, arm64_big_sur: "a4c0725297a1aa516636d8dec7c575a88c77845cff2fd79c580675dfe93b1bca" sha256 cellar: :any, monterey: "4b5f251c5bf0f1f48eb842560401ba33d0abec017a6011c75457e5a732484204" sha256 cellar: :any, big_sur: "15033557efa198a8dcd8fc1e3ececa06be5a39324a6138ff309678df2122bc03" sha256 cellar: :any, catalina: "d62686f1996af06e4302a5f9dd7f4d12c5d834aa7724ed1ffddddf357cd1af93" sha256 cellar: :any_skip_relocation, x86_64_linux: "36987244d8cddf346769d29128e7172250d3faf909e75c35add9f09312d1d778" end depends_on "cargo-c" => :build depends_on "meson" => :build depends_on "ninja" => :build depends_on "rust" => :build depends_on "dav1d" depends_on "gst-plugins-base" depends_on "gstreamer" depends_on "gtk4" depends_on "pango" # for closedcaption # commit ref, https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs/-/commit/ea98a0b5964cd196abbb48c621969a8ef33eb157 # remove in next release patch :DATA def install mkdir "build" do # csound is disabled as the dependency detection seems to fail # the sodium crate fails while building native code as well args = std_meson_args + %w[ -Dclosedcaption=enabled -Ddav1d=enabled -Dsodium=disabled -Dcsound=disabled -Dgtk4=enabled ] system "meson", *args, ".." system "ninja", "-v" system "ninja", "install", "-v" end end test do gst = Formula["gstreamer"].opt_bin/"gst-inspect-1.0" output = shell_output("#{gst} --plugin rsfile") assert_match version.to_s, output end end __END__ diff --git a/video/dav1d/Cargo.toml b/video/dav1d/Cargo.toml index 9ae00ef..2c2e005 100644 --- a/video/dav1d/Cargo.toml +++ b/video/dav1d/Cargo.toml @@ -10,7 +10,7 @@ description = "Dav1d Plugin" [dependencies] atomic_refcell = "0.1" -dav1d = "0.7" +dav1d = "0.8" gst = { package = "gstreamer", git = "https://gitlab.freedesktop.org/gstreamer/gstreamer-rs", branch = "0.18", version = "0.18" } gst-base = { package = "gstreamer-base", git = "https://gitlab.freedesktop.org/gstreamer/gstreamer-rs", branch = "0.18", version = "0.18" } gst-video = { package = "gstreamer-video", git = "https://gitlab.freedesktop.org/gstreamer/gstreamer-rs", branch = "0.18", version = "0.18", features = ["v1_12"] }
41.214286
164
0.697747
40082050b9c3faca6067b136031f88848ae20ba2
5,651
py
Python
ooobuild/csslo/beans/__init__.py
Amourspirit/ooo_uno_tmpl
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
[ "Apache-2.0" ]
null
null
null
ooobuild/csslo/beans/__init__.py
Amourspirit/ooo_uno_tmpl
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
[ "Apache-2.0" ]
null
null
null
ooobuild/csslo/beans/__init__.py
Amourspirit/ooo_uno_tmpl
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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. # from ...lo.beans.ambiguous import Ambiguous as Ambiguous from ...lo.beans.defaulted import Defaulted as Defaulted from ...lo.beans.get_direct_property_tolerant_result import GetDirectPropertyTolerantResult as GetDirectPropertyTolerantResult from ...lo.beans.get_property_tolerant_result import GetPropertyTolerantResult as GetPropertyTolerantResult from ...lo.beans.illegal_type_exception import IllegalTypeException as IllegalTypeException from ...lo.beans.introspection import Introspection as Introspection from ...lo.beans.introspection_exception import IntrospectionException as IntrospectionException from ...lo.beans.method_concept import MethodConcept as MethodConcept from ...lo.beans.named_value import NamedValue as NamedValue from ...lo.beans.not_removeable_exception import NotRemoveableException as NotRemoveableException from ...lo.beans.optional import Optional as Optional from ...lo.beans.pair import Pair as Pair from ...lo.beans.property import Property as Property from ...lo.beans.property_attribute import PropertyAttribute as PropertyAttribute from ...lo.beans.property_bag import PropertyBag as PropertyBag from ...lo.beans.property_change_event import PropertyChangeEvent as PropertyChangeEvent from ...lo.beans.property_concept import PropertyConcept as PropertyConcept from ...lo.beans.property_exist_exception import PropertyExistException as PropertyExistException from ...lo.beans.property_set import PropertySet as PropertySet from ...lo.beans.property_set_info_change import PropertySetInfoChange as PropertySetInfoChange from ...lo.beans.property_set_info_change_event import PropertySetInfoChangeEvent as PropertySetInfoChangeEvent from ...lo.beans.property_state import PropertyState as PropertyState from ...lo.beans.property_state_change_event import PropertyStateChangeEvent as PropertyStateChangeEvent from ...lo.beans.property_value import PropertyValue as PropertyValue from ...lo.beans.property_values import PropertyValues as PropertyValues from ...lo.beans.property_veto_exception import PropertyVetoException as PropertyVetoException from ...lo.beans.set_property_tolerant_failed import SetPropertyTolerantFailed as SetPropertyTolerantFailed from ...lo.beans.string_pair import StringPair as StringPair from ...lo.beans.tolerant_property_set_result_type import TolerantPropertySetResultType as TolerantPropertySetResultType from ...lo.beans.unknown_property_exception import UnknownPropertyException as UnknownPropertyException from ...lo.beans.x_exact_name import XExactName as XExactName from ...lo.beans.x_fast_property_set import XFastPropertySet as XFastPropertySet from ...lo.beans.x_hierarchical_property_set import XHierarchicalPropertySet as XHierarchicalPropertySet from ...lo.beans.x_hierarchical_property_set_info import XHierarchicalPropertySetInfo as XHierarchicalPropertySetInfo from ...lo.beans.x_introspection import XIntrospection as XIntrospection from ...lo.beans.x_introspection_access import XIntrospectionAccess as XIntrospectionAccess from ...lo.beans.x_material_holder import XMaterialHolder as XMaterialHolder from ...lo.beans.x_multi_hierarchical_property_set import XMultiHierarchicalPropertySet as XMultiHierarchicalPropertySet from ...lo.beans.x_multi_property_set import XMultiPropertySet as XMultiPropertySet from ...lo.beans.x_multi_property_states import XMultiPropertyStates as XMultiPropertyStates from ...lo.beans.x_properties_change_listener import XPropertiesChangeListener as XPropertiesChangeListener from ...lo.beans.x_properties_change_notifier import XPropertiesChangeNotifier as XPropertiesChangeNotifier from ...lo.beans.x_property import XProperty as XProperty from ...lo.beans.x_property_access import XPropertyAccess as XPropertyAccess from ...lo.beans.x_property_bag import XPropertyBag as XPropertyBag from ...lo.beans.x_property_change_listener import XPropertyChangeListener as XPropertyChangeListener from ...lo.beans.x_property_container import XPropertyContainer as XPropertyContainer from ...lo.beans.x_property_set import XPropertySet as XPropertySet from ...lo.beans.x_property_set_info import XPropertySetInfo as XPropertySetInfo from ...lo.beans.x_property_set_info_change_listener import XPropertySetInfoChangeListener as XPropertySetInfoChangeListener from ...lo.beans.x_property_set_info_change_notifier import XPropertySetInfoChangeNotifier as XPropertySetInfoChangeNotifier from ...lo.beans.x_property_set_option import XPropertySetOption as XPropertySetOption from ...lo.beans.x_property_state import XPropertyState as XPropertyState from ...lo.beans.x_property_state_change_listener import XPropertyStateChangeListener as XPropertyStateChangeListener from ...lo.beans.x_property_with_state import XPropertyWithState as XPropertyWithState from ...lo.beans.x_tolerant_multi_property_set import XTolerantMultiPropertySet as XTolerantMultiPropertySet from ...lo.beans.x_vetoable_change_listener import XVetoableChangeListener as XVetoableChangeListener from ...lo.beans.the_introspection import theIntrospection as theIntrospection
75.346667
126
0.860379
c473594572b3f66fe685a26a1ed340f0247a0266
15,700
c
C
devices-framework/riot-app/riot/cpu/nrf5x_common/radio/nrfmin/nrfmin.c
bench-os/bench-os
38ade08e097ca215f7465047dfa70503af11d612
[ "MIT" ]
1
2020-02-21T09:16:17.000Z
2020-02-21T09:16:17.000Z
extension-framework/riot-app/riot/cpu/nrf5x_common/radio/nrfmin/nrfmin.c
bench-os/bench-os
38ade08e097ca215f7465047dfa70503af11d612
[ "MIT" ]
null
null
null
extension-framework/riot-app/riot/cpu/nrf5x_common/radio/nrfmin/nrfmin.c
bench-os/bench-os
38ade08e097ca215f7465047dfa70503af11d612
[ "MIT" ]
1
2020-02-21T09:21:45.000Z
2020-02-21T09:21:45.000Z
/* * Copyright (C) 2015-2017 Freie Universität Berlin * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup drivers_nrf5x_nrfmin * @{ * * @file * @brief Implementation of the nrfmin radio driver for nRF51 radios * * @author Hauke Petersen <hauke.petersen@fu-berlin.de> * * @} */ #include <string.h> #include <errno.h> #include "cpu.h" #include "mutex.h" #include "assert.h" #include "periph_conf.h" #include "periph/cpuid.h" #include "nrfmin.h" #include "net/netdev.h" #ifdef MODULE_GNRC_SIXLOWPAN #include "net/gnrc/nettype.h" #endif #define ENABLE_DEBUG (0) #include "debug.h" /** * @brief Driver specific device configuration * @{ */ #define CONF_MODE RADIO_MODE_MODE_Nrf_1Mbit #define CONF_LEN (8U) #define CONF_S0 (0U) #define CONF_S1 (0U) #define CONF_STATLEN (0U) #define CONF_BASE_ADDR_LEN (4U) #define CONF_ENDIAN RADIO_PCNF1_ENDIAN_Big #define CONF_WHITENING RADIO_PCNF1_WHITEEN_Disabled #define CONF_CRC_LEN (2U) #define CONF_CRC_POLY (0x11021) #define CONF_CRC_INIT (0xf0f0f0) /** @} */ /** * @brief Driver specific address configuration * @{ */ #define CONF_ADDR_PREFIX0 (0xe7e7e7e7) #define CONF_ADDR_BASE (0xe7e70000) #define CONF_ADDR_BCAST (CONF_ADDR_BASE | NRFMIN_ADDR_BCAST) /** @} */ /** * @brief We define a pseudo NID for compliance to 6LoWPAN */ #define CONF_PSEUDO_NID (0xaffe) /** * @brief Driver specific (interrupt) events (not all of them used currently) * @{ */ #define ISR_EVENT_RX_START (0x0001) #define ISR_EVENT_RX_DONE (0x0002) #define ISR_EVENT_TX_START (0x0004) #define ISR_EVENT_TX_DONE (0x0008) #define ISR_EVENT_WRONG_CHKSUM (0x0010) /** @} */ /** * @brief Possible internal device states */ typedef enum { STATE_OFF, /**< device is powered off */ STATE_IDLE, /**< device is in idle mode */ STATE_RX, /**< device is in receive mode */ STATE_TX, /**< device is transmitting data */ } state_t; /** * @brief Since there can only be 1 nrfmin device, we allocate it right here */ netdev_t nrfmin_dev; /** * @brief For faster lookup we remember our own 16-bit address */ static uint16_t my_addr; /** * @brief We need to keep track of the radio state in SW (-> PAN ID 20) * * See nRF51822 PAN ID 20: RADIO State Register is not functional. */ static volatile state_t state = STATE_OFF; /** * @brief We also remember the 'long-term' state, so we can resume after TX */ static volatile state_t target_state = STATE_OFF; /** * @brief When sending out data, the data needs to be in one continuous memory * region. So we need to buffer outgoing data on the driver level. */ static nrfmin_pkt_t tx_buf; /** * @brief As the device is memory mapped, we need some space to save incoming * data to. * * @todo Improve the RX buffering to at least use double buffering */ static nrfmin_pkt_t rx_buf; /** * @brief While we listen for incoming data, we lock the RX buffer */ static volatile uint8_t rx_lock = 0; /** * @brief Set radio into idle (DISABLED) state */ static void go_idle(void) { /* set device into basic disabled state */ NRF_RADIO->EVENTS_DISABLED = 0; NRF_RADIO->TASKS_DISABLE = 1; while (NRF_RADIO->EVENTS_DISABLED == 0) {} /* also release any existing lock on the RX buffer */ rx_lock = 0; state = STATE_IDLE; } /** * @brief Set radio into the target state as defined by `target_state` * * Trick here is, that the driver can go back to it's previous state after a * send operation, so it can differentiate if the driver was in DISABLED or in * RX mode before the send process had started. */ static void goto_target_state(void) { go_idle(); if ((target_state == STATE_RX) && (rx_buf.pkt.hdr.len == 0)) { /* set receive buffer and our own address */ rx_lock = 1; NRF_RADIO->PACKETPTR = (uint32_t)(&rx_buf); NRF_RADIO->BASE0 = (CONF_ADDR_BASE | my_addr); /* goto RX mode */ NRF_RADIO->TASKS_RXEN = 1; state = STATE_RX; } if (target_state == STATE_OFF) { NRF_RADIO->POWER = 0; state = STATE_OFF; } } void nrfmin_setup(void) { nrfmin_dev.driver = &nrfmin_netdev; nrfmin_dev.event_callback = NULL; nrfmin_dev.context = NULL; #ifdef MODULE_NETSTATS_L2 memset(&nrfmin_dev.stats, 0, sizeof(netstats_t));; #endif } uint16_t nrfmin_get_addr(void) { return my_addr; } void nrfmin_get_pseudo_long_addr(uint16_t *addr) { for (int i = 0; i < 4; i++) { addr[i] = my_addr; } } void nrfmin_get_iid(uint16_t *iid) { iid[0] = 0; iid[1] = 0xff00; iid[2] = 0x00fe; iid[3] = my_addr; } uint16_t nrfmin_get_channel(void) { return (uint16_t)(NRF_RADIO->FREQUENCY >> 2); } netopt_state_t nrfmin_get_state(void) { switch (state) { case STATE_OFF: return NETOPT_STATE_OFF; case STATE_IDLE: return NETOPT_STATE_SLEEP; case STATE_RX: return NETOPT_STATE_IDLE; case STATE_TX: return NETOPT_STATE_TX; default: return NETOPT_STATE_RESET; /* should never show */ } } int16_t nrfmin_get_txpower(void) { int8_t p = (int8_t)NRF_RADIO->TXPOWER; if (p < 0) { return (int16_t)(0xff00 | p); } return (int16_t)p; } void nrfmin_set_addr(uint16_t addr) { my_addr = addr; goto_target_state(); } int nrfmin_set_channel(uint16_t chan) { if (chan > NRFMIN_CHAN_MAX) { return -EOVERFLOW; } NRF_RADIO->FREQUENCY = (chan << 2); goto_target_state(); return sizeof(uint16_t); } void nrfmin_set_txpower(int16_t power) { if (power > 2) { NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Pos4dBm; } else if (power > -2) { NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_0dBm; } else if (power > -6) { NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Neg4dBm; } else if (power > -10) { NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Neg8dBm; } else if (power > -14) { NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Neg12dBm; } else if (power > -18) { NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Neg16dBm; } else if (power > -25) { NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Neg20dBm; } else { NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Neg30dBm; } } int nrfmin_set_state(netopt_state_t val) { /* make sure radio is turned on and no transmission is in progress */ NRF_RADIO->POWER = 1; switch (val) { case NETOPT_STATE_OFF: target_state = STATE_OFF; break; case NETOPT_STATE_SLEEP: target_state = STATE_IDLE; break; case NETOPT_STATE_IDLE: target_state = STATE_RX; break; default: return -ENOTSUP; } goto_target_state(); return sizeof(netopt_state_t); } /** * @brief Radio interrupt routine */ void isr_radio(void) { if (NRF_RADIO->EVENTS_END == 1) { NRF_RADIO->EVENTS_END = 0; /* did we just send or receive something? */ if (state == STATE_RX) { /* drop packet on invalid CRC */ if ((NRF_RADIO->CRCSTATUS != 1) || !(nrfmin_dev.event_callback)) { rx_buf.pkt.hdr.len = 0; NRF_RADIO->TASKS_START = 1; return; } rx_lock = 0; nrfmin_dev.event_callback(&nrfmin_dev, NETDEV_EVENT_ISR); } else if (state == STATE_TX) { goto_target_state(); } } cortexm_isr_end(); } static int nrfmin_send(netdev_t *dev, const iolist_t *iolist) { (void)dev; assert((iolist) && (state != STATE_OFF)); /* wait for any ongoing transmission to finish and go into idle state */ while (state == STATE_TX) {} go_idle(); /* copy packet data into the transmit buffer */ int pos = 0; for (const iolist_t *iol = iolist; iol; iol = iol->iol_next) { if ((pos + iol->iol_len) > NRFMIN_PKT_MAX) { DEBUG("[nrfmin] send: unable to do so, packet is too large!\n"); return -EOVERFLOW; } memcpy(&tx_buf.raw[pos], iol->iol_base, iol->iol_len); pos += iol->iol_len; } /* set output buffer and destination address */ nrfmin_hdr_t *hdr = (nrfmin_hdr_t *)iolist->iol_base; NRF_RADIO->PACKETPTR = (uint32_t)(&tx_buf); NRF_RADIO->BASE0 = (CONF_ADDR_BASE | hdr->dst_addr); /* trigger the actual transmission */ DEBUG("[nrfmin] send: putting %i byte into the ether\n", (int)hdr->len); state = STATE_TX; NRF_RADIO->TASKS_TXEN = 1; return (int)pos; } static int nrfmin_recv(netdev_t *dev, void *buf, size_t len, void *info) { (void)dev; (void)info; assert(state != STATE_OFF); unsigned pktlen = rx_buf.pkt.hdr.len; /* check if packet data is readable */ if (rx_lock || (pktlen == 0)) { DEBUG("[nrfmin] recv: no packet data available\n"); return 0; } if (buf == NULL) { if (len > 0) { /* drop packet */ DEBUG("[nrfmin] recv: dropping packet of length %i\n", pktlen); rx_buf.pkt.hdr.len = 0; goto_target_state(); } } else { DEBUG("[nrfmin] recv: reading packet of length %i\n", pktlen); pktlen = (len < pktlen) ? len : pktlen; memcpy(buf, rx_buf.raw, pktlen); rx_buf.pkt.hdr.len = 0; goto_target_state(); } return pktlen; } static int nrfmin_init(netdev_t *dev) { (void)dev; uint8_t cpuid[CPUID_LEN]; /* check given device descriptor */ assert(dev); /* initialize our own address from the CPU ID */ my_addr = 0; cpuid_get(cpuid); for (unsigned i = 0; i < CPUID_LEN; i++) { my_addr ^= cpuid[i] << (8 * (i & 0x01)); } /* power on the NRFs radio */ NRF_RADIO->POWER = 1; /* load driver specific configuration */ NRF_RADIO->MODE = CONF_MODE; /* configure variable parameters to default values */ NRF_RADIO->TXPOWER = NRFMIN_TXPOWER_DEFAULT; NRF_RADIO->FREQUENCY = NRFMIN_CHAN_DEFAULT; /* pre-configure radio addresses */ NRF_RADIO->PREFIX0 = CONF_ADDR_PREFIX0; NRF_RADIO->BASE0 = (CONF_ADDR_BASE | my_addr); NRF_RADIO->BASE1 = CONF_ADDR_BCAST; /* always send from logical address 0 */ NRF_RADIO->TXADDRESS = 0x00UL; /* and listen to logical addresses 0 and 1 */ NRF_RADIO->RXADDRESSES = 0x03UL; /* configure data fields and packet length whitening and endianess */ NRF_RADIO->PCNF0 = ((CONF_S1 << RADIO_PCNF0_S1LEN_Pos) | (CONF_S0 << RADIO_PCNF0_S0LEN_Pos) | (CONF_LEN << RADIO_PCNF0_LFLEN_Pos)); NRF_RADIO->PCNF1 = ((CONF_WHITENING << RADIO_PCNF1_WHITEEN_Pos) | (CONF_ENDIAN << RADIO_PCNF1_ENDIAN_Pos) | (CONF_BASE_ADDR_LEN << RADIO_PCNF1_BALEN_Pos) | (CONF_STATLEN << RADIO_PCNF1_STATLEN_Pos) | (NRFMIN_PKT_MAX << RADIO_PCNF1_MAXLEN_Pos)); /* configure the CRC unit, we skip the address field as this seems to lead * to wrong checksum calculation on nRF52 devices in some cases */ NRF_RADIO->CRCCNF = CONF_CRC_LEN | RADIO_CRCCNF_SKIPADDR_Msk; NRF_RADIO->CRCPOLY = CONF_CRC_POLY; NRF_RADIO->CRCINIT = CONF_CRC_INIT; /* set shortcuts for more efficient transfer */ NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk; /* enable interrupts */ NVIC_EnableIRQ(RADIO_IRQn); /* enable END interrupt */ NRF_RADIO->EVENTS_END = 0; NRF_RADIO->INTENSET = RADIO_INTENSET_END_Msk; /* put device in receive mode */ target_state = STATE_RX; goto_target_state(); DEBUG("[nrfmin] initialization successful\n"); return 0; } static void nrfmin_isr(netdev_t *dev) { if (nrfmin_dev.event_callback) { nrfmin_dev.event_callback(dev, NETDEV_EVENT_RX_COMPLETE); } } static int nrfmin_get(netdev_t *dev, netopt_t opt, void *val, size_t max_len) { (void)dev; (void)max_len; switch (opt) { case NETOPT_CHANNEL: assert(max_len >= sizeof(uint16_t)); *((uint16_t *)val) = nrfmin_get_channel(); return sizeof(uint16_t); case NETOPT_ADDRESS: assert(max_len >= sizeof(uint16_t)); *((uint16_t *)val) = nrfmin_get_addr(); return sizeof(uint16_t); case NETOPT_STATE: assert(max_len >= sizeof(netopt_state_t)); *((netopt_state_t *)val) = nrfmin_get_state(); return sizeof(netopt_state_t); case NETOPT_TX_POWER: assert(max_len >= sizeof(int16_t)); *((int16_t *)val) = nrfmin_get_txpower(); return sizeof(int16_t); case NETOPT_MAX_PACKET_SIZE: assert(max_len >= sizeof(uint16_t)); *((uint16_t *)val) = NRFMIN_PAYLOAD_MAX; return sizeof(uint16_t); case NETOPT_ADDRESS_LONG: assert(max_len >= sizeof(uint64_t)); nrfmin_get_pseudo_long_addr((uint16_t *)val); return sizeof(uint64_t); case NETOPT_ADDR_LEN: assert(max_len >= sizeof(uint16_t)); *((uint16_t *)val) = 2; return sizeof(uint16_t); case NETOPT_NID: assert(max_len >= sizeof(uint16_t)); *((uint16_t*)val) = CONF_PSEUDO_NID; return sizeof(uint16_t); #ifdef MODULE_GNRC_SIXLOWPAN case NETOPT_PROTO: assert(max_len >= sizeof(uint16_t)); *((uint16_t *)val) = GNRC_NETTYPE_SIXLOWPAN; return sizeof(uint16_t); #endif case NETOPT_DEVICE_TYPE: assert(max_len >= sizeof(uint16_t)); *((uint16_t *)val) = NETDEV_TYPE_NRFMIN; return sizeof(uint16_t); case NETOPT_IPV6_IID: assert(max_len >= sizeof(uint64_t)); nrfmin_get_iid((uint16_t *)val); return sizeof(uint64_t); default: return -ENOTSUP; } } static int nrfmin_set(netdev_t *dev, netopt_t opt, const void *val, size_t len) { (void)dev; (void)len; switch (opt) { case NETOPT_CHANNEL: assert(len == sizeof(uint16_t)); return nrfmin_set_channel(*((const uint16_t *)val)); case NETOPT_ADDRESS: assert(len == sizeof(uint16_t)); nrfmin_set_addr(*((const uint16_t *)val)); return sizeof(uint16_t); case NETOPT_ADDR_LEN: case NETOPT_SRC_LEN: assert(len == sizeof(uint16_t)); if (*((const uint16_t *)val) != 2) { return -EAFNOSUPPORT; } return sizeof(uint16_t); case NETOPT_STATE: assert(len == sizeof(netopt_state_t)); return nrfmin_set_state(*((const netopt_state_t *)val)); case NETOPT_TX_POWER: assert(len == sizeof(int16_t)); nrfmin_set_txpower(*((const int16_t *)val)); return sizeof(int16_t); default: return -ENOTSUP; } } /** * @brief Export of the netdev interface */ const netdev_driver_t nrfmin_netdev = { .send = nrfmin_send, .recv = nrfmin_recv, .init = nrfmin_init, .isr = nrfmin_isr, .get = nrfmin_get, .set = nrfmin_set };
27.836879
80
0.609936
d2ac4d7eae9a3ea569d5e5eab3a05a9c89ccc975
4,765
php
PHP
tests/ResponseTest.php
IngeniozIT/psr-http-message
aefc35110274b631d9c1cabec83872ea6fbf5b76
[ "MIT" ]
null
null
null
tests/ResponseTest.php
IngeniozIT/psr-http-message
aefc35110274b631d9c1cabec83872ea6fbf5b76
[ "MIT" ]
1
2019-09-07T17:14:21.000Z
2019-09-07T17:14:21.000Z
tests/ResponseTest.php
IngeniozIT/psr-http-message
aefc35110274b631d9c1cabec83872ea6fbf5b76
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace IngeniozIT\Http\Message\Tests; use IngeniozIT\Http\Message\Tests\MessageTest; use Psr\Http\Message\ResponseInterface; /** * @coversDefaultClass \IngeniozIT\Http\Message\Response */ class ResponseTest extends MessageTest { // ========================================== // // Implementation specific // // ========================================== // /** @var string $className Class name of the tested class */ protected string $className = \IngeniozIT\Http\Message\Response::class; /** * @var int Implementation's default HTTP status code. */ protected $defaultStatusCode = 200; /** * @var string Implementation's default HTTP reason phrase. */ protected $defaultReasonPhrase = 'OK'; /** * Get an instance of the tested Response object. * @return ResponseInterface */ protected function getResponse(): ResponseInterface { return $this->getMessage(); } // ========================================== // // Defaults // // ========================================== // /** * Check default status code and reason phrase. */ public function testGetDefaults() { $response = $this->getResponse(); $this->assertSame($this->defaultStatusCode, $response->getStatusCode()); $this->assertSame($this->defaultReasonPhrase, $response->getReasonPhrase()); } // ========================================== // // Status // // ========================================== // /** * Return an instance with the specified status code */ public function testWithStatus() { $response = $this->getResponse(); $response2 = $response->withStatus(404); $this->assertSame(404, $response2->getStatusCode()); } /** * Return an instance with the specified status code * The status code is a 3-digit integer result code of the server's attempt * to understand and satisfy the request. */ public function testWithBadStatus() { $response = $this->getResponse(); $this->expectException(\InvalidArgumentException::class); $response2 = $response->withStatus(4040); } /** * Return an instance with the specified status code and, optionally, reason phrase. */ public function testWithStatusAndReasonPhrase() { $response = $this->getResponse(); $response2 = $response->withStatus(404, 'A reason phrase'); $this->assertSame(404, $response2->getStatusCode()); $this->assertSame('A reason phrase', $response2->getReasonPhrase()); } /** * Return an instance with the specified status code and, optionally, reason phrase. * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * updated status and reason phrase. */ public function testWithStatusIsImmutable() { $response = $this->getResponse()->withStatus(200); $response2 = $response->withStatus(200); $response3 = $response->withStatus(404); $this->assertSame(200, $response->getStatusCode()); $this->assertSame(200, $response2->getStatusCode()); $this->assertSame(404, $response3->getStatusCode()); $this->assertNotSame($response3, $response, 'Response status code is not immutable.'); $this->assertSame($response, $response2, 'Response status code is badly immutable.'); } /** * Return an instance with the specified status code and, optionally, reason phrase. * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * updated status and reason phrase. */ public function testWithStatusAndReasonPhraseIsImmutable() { $response = $this->getResponse()->withStatus(200, 'Reason phrase'); $response2 = $response->withStatus(200, 'Reason phrase'); $response3 = $response->withStatus(200, 'Another reason phrase'); $response4 = $response->withStatus(404, 'Reason phrase'); $response5 = $response->withStatus(404, 'Another reason phrase'); $this->assertNotSame($response, $response3, 'Response status code is not immutable.'); $this->assertNotSame($response, $response4, 'Response status code is not immutable.'); $this->assertNotSame($response, $response5, 'Response status code is not immutable.'); $this->assertSame($response, $response2, 'Response status code is badly immutable.'); } }
34.528986
94
0.59937
e9c4a9b3119218eb8b428f815de1fd48df366702
2,020
go
Go
service/excel/excel.go
wimgithub/filfox_data
fae3af4ac720889137b4599bba10e88cdc22f0ba
[ "MIT" ]
2
2021-01-05T06:35:04.000Z
2021-07-08T08:19:02.000Z
service/excel/excel.go
wimgithub/filfox_data
fae3af4ac720889137b4599bba10e88cdc22f0ba
[ "MIT" ]
null
null
null
service/excel/excel.go
wimgithub/filfox_data
fae3af4ac720889137b4599bba10e88cdc22f0ba
[ "MIT" ]
1
2021-05-24T16:14:37.000Z
2021-05-24T16:14:37.000Z
package excel import ( model "filfox_data/models" "filfox_data/models/mysql" "fmt" "github.com/gin-gonic/gin" "github.com/tealeg/xlsx" "sort" "time" ) func (a Datas) Len() int { return len(a) } func (a Datas) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a Datas) Less(i, j int) bool { return a[i].Time < a[j].Time } type Datas []*model.Data var Rows = []string{"时间", "消息ID", "发送方", "接收方", "净收入", "类型"} func GetExcel(c *gin.Context, begin, end, height int64, msg, to, t string) (string, error) { file := xlsx.NewFile() sheet, err := file.AddSheet("Sheet1") if err != nil { return "", err } first := sheet.AddRow() first.SetHeightCM(1) //设置每行的高度 for _, r := range Rows { cell := first.AddCell() cell.Value = r } data, _ := mysql.SharedStore().GetFilFoxData(begin, end, height, msg, to, t) sort.Sort(Datas(data)) for _, v := range data { row := sheet.AddRow() row.SetHeightCM(1) //设置每行的高度 cell := row.AddCell() //cell 1 cell.Value = time.Unix(v.Time, 0).Format("2006-01-02 15:04:05") //时间 cell = row.AddCell() //cell 2 cell.Value = v.Message //消息ID cell = row.AddCell() //cell 3 cell.Value = v.FilFrom //发送方 cell = row.AddCell() //cell 4 cell.Value = v.FilTo //接收方 cell = row.AddCell() //cell 5 cell.Value = v.Value // 净收入 cell = row.AddCell() //cell 6 cell.Value = v.Type // 类型 } n := fmt.Sprint(time.Now(), ".xlsx") name := fmt.Sprint("./excel/", n) err = file.Save(name) if err != nil { return "", err } return n, nil }
33.666667
92
0.451485
8a4712e12723d26b5f4c5ac422325cc090852ec3
710
kt
Kotlin
src/commonTest/kotlin/com/soywiz/kpspemu/format/PbpTest.kt
soywiz/kpspemu
5ad15d161bef8baa40961ee508643306d933a50a
[ "MIT" ]
63
2017-10-29T23:49:58.000Z
2022-03-27T10:47:11.000Z
src/commonTest/kotlin/com/soywiz/kpspemu/format/PbpTest.kt
soywiz/kpspemu
5ad15d161bef8baa40961ee508643306d933a50a
[ "MIT" ]
16
2017-11-21T19:09:41.000Z
2017-12-07T16:13:02.000Z
src/commonTest/kotlin/com/soywiz/kpspemu/format/PbpTest.kt
soywiz/kpspemu
5ad15d161bef8baa40961ee508643306d933a50a
[ "MIT" ]
6
2018-03-10T01:28:20.000Z
2021-11-18T20:04:30.000Z
package com.soywiz.kpspemu.format import com.soywiz.korio.file.std.* import com.soywiz.korio.stream.* import com.soywiz.kpspemu.* import com.soywiz.kpspemu.format.elf.* import kotlin.test.* class PbpTest : BaseTest() { @Test fun name() = pspSuspendTest { val pbp = Pbp.load(resourcesVfs["lines.pbp"].open()) assertEquals(listOf(408L, 0L, 0L, 0L, 0L, 0L, 30280L, 0L), pbp.streams.map { it.size() }) assertEquals(408, pbp[Pbp.PARAM_SFO]!!.readAll().size) assertEquals(408, pbp[Pbp.PARAM_SFO]!!.readAll().size, "read twice") assertEquals(30280, pbp[Pbp.PSP_DATA]!!.readAll().size) val elf = Elf.fromStream(pbp[Pbp.PSP_DATA]!!.readAll().openSync()) } }
37.368421
97
0.666197
39c12c35921ad75a0f2459108d88ef875c82f4a2
2,215
js
JavaScript
lib/templates/default_player.js
jsa-research/embedza
ae14d877833e5f0b0c9d01b95431883ce171ea23
[ "MIT" ]
54
2015-09-28T20:01:38.000Z
2021-12-16T14:11:43.000Z
lib/templates/default_player.js
jsa-research/embedza
ae14d877833e5f0b0c9d01b95431883ce171ea23
[ "MIT" ]
6
2015-08-20T14:42:10.000Z
2017-06-08T01:43:44.000Z
lib/templates/default_player.js
jsa-research/embedza
ae14d877833e5f0b0c9d01b95431883ce171ea23
[ "MIT" ]
6
2018-07-07T10:51:30.000Z
2021-04-30T21:35:17.000Z
'use strict'; module.exports = `<% var player = _.find(self.snippets, snippet => { return snippet.tags.indexOf('player') !== -1 && snippet.tags.indexOf('html5') !== -1; }); var desiredThumbnailWidth = 480; var thumbnail = _.chain(self.snippets) // Get thumbnails .filter(snippet => snippet.tags.indexOf('thumbnail') !== -1) // Sort by width (closest to "desiredThumbnailWidth") .sortBy(snippet => Math.abs((snippet.media.width || 0) - desiredThumbnailWidth)) // Get first .first() .value(); var href = player.href; // Modify or set autoplay param. http://stackoverflow.com/questions/7517332 if (player.media.autoplay) { var param = player.media.autoplay.split('='); var parts = self.utils.url.parse(href, true); parts.query[param[0]] = param[1]; delete parts.search; href = self.utils.url.format(parts); } var placeholder = '<iframe class="ez-player-frame" src="' + _.escape(href) + '" allowfullscreen></iframe>'; var duration; if (player.media.duration && player.media.duration > 0) { var s = player.media.duration % 60; duration = [ Math.floor(player.media.duration / 3600), // hours Math.floor(player.media.duration / 60) % 60, // minutes s < 10 ? '0' + s : s // seconds with leading '0' ]; // Remove hours if video shorter than hour if (duration[0] === 0) { duration.shift(); } } %> <div class="ez-player ez-domain-<%= self.domain.replace(/[.]/g, '_') %> ez-block" data-placeholder="<%- placeholder %>"> <div class="ez-player-container" style="padding-bottom: <%= _.round(100 / player.media.width * player.media.height, 4) %>%;"> <a class="ez-player-placeholder" target="_blank" href="<%- self.src %>" rel="nofollow"> <div class="ez-player-picture" style="background-image: url('<%- thumbnail.href %>');"></div> <% if (self.meta.title) { %> <div class="ez-player-header"> <div class="ez-player-title"> <%- self.meta.title %> </div> </div> <% } %> <div class="ez-player-button"></div> <div class="ez-player-logo"></div> <% if (duration) { %> <div class="ez-player-duration"><%= duration.join(':') %></div> <% } %> </a> </div> </div>`;
31.642857
128
0.609029
f9d57aa5a20834b102eda661ef7aface04360667
200
sql
SQL
core/src/main/resources/schema/app/20160628142654_CLOUD-59100_remove_service_componenttype.sql
anmolnar/cloudbreak
81e18cca143c30389ecf4958b1a4dcae211bddf4
[ "Apache-2.0" ]
174
2017-07-14T03:20:42.000Z
2022-03-25T05:03:18.000Z
core/src/main/resources/schema/app/20160628142654_CLOUD-59100_remove_service_componenttype.sql
anmolnar/cloudbreak
81e18cca143c30389ecf4958b1a4dcae211bddf4
[ "Apache-2.0" ]
2,242
2017-07-12T05:52:01.000Z
2022-03-31T15:50:08.000Z
core/src/main/resources/schema/app/20160628142654_CLOUD-59100_remove_service_componenttype.sql
anmolnar/cloudbreak
81e18cca143c30389ecf4958b1a4dcae211bddf4
[ "Apache-2.0" ]
172
2017-07-12T08:53:48.000Z
2022-03-24T12:16:33.000Z
-- // CLOUD-61094_remove_service_componenttype -- Migration SQL that makes the change goes here. DELETE FROM component WHERE componenttype='SERVICE'; -- //@UNDO -- SQL to undo the change goes here.
25
52
0.755
05c0afd45cd7671e84fa6f67815b314e8517fa5a
188
rb
Ruby
test/mailers/previews/vehicle_report_card_mailer_preview.rb
JohnRenzone/AutoTracker
35ee6de18a3b0ef6817d316627161f4ed853614a
[ "MIT" ]
1
2019-01-08T18:59:23.000Z
2019-01-08T18:59:23.000Z
test/mailers/previews/vehicle_report_card_mailer_preview.rb
JohnRenzone/AutoTracker
35ee6de18a3b0ef6817d316627161f4ed853614a
[ "MIT" ]
null
null
null
test/mailers/previews/vehicle_report_card_mailer_preview.rb
JohnRenzone/AutoTracker
35ee6de18a3b0ef6817d316627161f4ed853614a
[ "MIT" ]
null
null
null
class VehicleReportCardMailerPreview < ActionMailer::Preview def email_report_card VehicleReportCardMailer.email_report_card(VehicleReportCard.first,nil, Dealership.first) end end
31.333333
92
0.851064
fe46da7d06d23aad9b38e8dc9d9a6ef2652cef98
217
h
C
Samples/Objc-Sample01/iOS-Sample01/ViewController.h
IngeoSDK/ingeo-ios-sdk
d4e2c10da7dd20877e018c41222cd6cd5d42740a
[ "Apache-2.0" ]
116
2015-02-13T17:29:21.000Z
2021-12-24T10:19:28.000Z
Samples/Objc-Sample01/iOS-Sample01/ViewController.h
IngeoSDK/ingeo-ios-sdk
d4e2c10da7dd20877e018c41222cd6cd5d42740a
[ "Apache-2.0" ]
4
2016-09-29T07:07:57.000Z
2019-06-23T10:28:45.000Z
Samples/Objc-Sample01/iOS-Sample01/ViewController.h
IngeoSDK/ingeo-ios-sdk
d4e2c10da7dd20877e018c41222cd6cd5d42740a
[ "Apache-2.0" ]
12
2015-02-16T16:09:21.000Z
2019-06-15T19:30:18.000Z
// // ViewController.h // iOS-Sample01 // // Created by Amit Palomo on 12/29/14. // Copyright (c) 2014 Ingeo. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
13.5625
50
0.682028
ffa37904f4582edb22ad8a2c84a5d31327ae5749
136
sql
SQL
src/main/resources/liquibase/harness/change/expectedSql/mariadb/alterSequenceCycleProperty.sql
kevin-at-datical/liquibase-test-harness
b3625d7429d092ab70508f9f92442e9e449918a7
[ "Apache-2.0" ]
null
null
null
src/main/resources/liquibase/harness/change/expectedSql/mariadb/alterSequenceCycleProperty.sql
kevin-at-datical/liquibase-test-harness
b3625d7429d092ab70508f9f92442e9e449918a7
[ "Apache-2.0" ]
null
null
null
src/main/resources/liquibase/harness/change/expectedSql/mariadb/alterSequenceCycleProperty.sql
kevin-at-datical/liquibase-test-harness
b3625d7429d092ab70508f9f92442e9e449918a7
[ "Apache-2.0" ]
null
null
null
CREATE SEQUENCE lbcat.test_sequence INCREMENT BY 1 MINVALUE 1 MAXVALUE 100 START WITH 1 CYCLE ALTER SEQUENCE lbcat.test_sequence NOCYCLE
68
93
0.860294
56de9fecb0432cc63e82f0189d27a993a3c92655
435
go
Go
pkg/forwarder/audit_log.go
jjfallete/cb-event-forwarder
b6db42f5253f3376ff0fda42d408ca9d13b12c60
[ "MIT" ]
73
2015-09-29T20:05:40.000Z
2022-02-28T04:02:21.000Z
pkg/forwarder/audit_log.go
jjfallete/cb-event-forwarder
b6db42f5253f3376ff0fda42d408ca9d13b12c60
[ "MIT" ]
144
2015-07-20T16:43:37.000Z
2022-03-14T17:13:12.000Z
pkg/forwarder/audit_log.go
jjfallete/cb-event-forwarder
b6db42f5253f3376ff0fda42d408ca9d13b12c60
[ "MIT" ]
50
2015-09-28T21:17:35.000Z
2022-03-14T16:18:01.000Z
package forwarder import ( "encoding/json" ) type AuditLogEvent struct { Message string `json:"message"` Type string `json:"type"` CbServer string `json:"cb_server"` } func (auditLogEvent AuditLogEvent) asJson() ([]byte, error) { return json.Marshal(auditLogEvent) } func NewAuditLogEvent(message, logType, serverName string) AuditLogEvent { return AuditLogEvent{Message: message, Type: logType, CbServer: serverName} }
21.75
76
0.749425
1fce3a9b691ff70af026eec74770fdc90e57fffe
929
swift
Swift
SberbankHomeworks/Lection 11/Lection 11/Lection 11/ViewController.swift
KirstonMoon/SberbankHomeworks
59eb5dab256e39d2cc16f1513ad353df4ec13720
[ "MIT" ]
null
null
null
SberbankHomeworks/Lection 11/Lection 11/Lection 11/ViewController.swift
KirstonMoon/SberbankHomeworks
59eb5dab256e39d2cc16f1513ad353df4ec13720
[ "MIT" ]
null
null
null
SberbankHomeworks/Lection 11/Lection 11/Lection 11/ViewController.swift
KirstonMoon/SberbankHomeworks
59eb5dab256e39d2cc16f1513ad353df4ec13720
[ "MIT" ]
null
null
null
// // ViewController.swift // Lection 11 // // Created by Kirill Magerya on 19.05.2021. // import UIKit final class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(buttonTapped)) } @objc private func buttonTapped() { let customActivity = CustomActivity() let customActivityVC = UIActivityViewController(activityItems: [""], applicationActivities: [customActivity]) customActivityVC.excludedActivityTypes = [.postToFlickr, .postToVimeo, .saveToCameraRoll] present(customActivityVC, animated: true) } }
29.967742
117
0.594187
9938b49b12c78a62440a8b51ded84f1374e7d5c5
1,720
h
C
text/class_hierarchy_serialization.h
melardev/CppBoostSerializationSnippets
e87d30719311a318f2505bdfc5bead843ed4f3b0
[ "MIT" ]
null
null
null
text/class_hierarchy_serialization.h
melardev/CppBoostSerializationSnippets
e87d30719311a318f2505bdfc5bead843ed4f3b0
[ "MIT" ]
null
null
null
text/class_hierarchy_serialization.h
melardev/CppBoostSerializationSnippets
e87d30719311a318f2505bdfc5bead843ed4f3b0
[ "MIT" ]
null
null
null
#pragma once #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <iostream> #include <sstream> namespace ClassHierarchySerialization { const int PACKET_TYPE_MOVEMENT = 1; const int PACKET_TYPE_SHOT = 2; const int PACKET_TYPE_EXIT_GAME = 3; std::stringstream ss; class Packet { public: Packet() = default; Packet(const int packet_type) : packet_type_{packet_type} { } int packet_type() const { return packet_type_; } private: friend class boost::serialization::access; template <typename Archive> void serialize(Archive& ar, const unsigned int version) { ar & packet_type_; } int packet_type_; }; class PacketPlayerMovement : public Packet { public: PacketPlayerMovement() = default; PacketPlayerMovement(double xPos, double yPos) : Packet{PACKET_TYPE_MOVEMENT}, y_pos_{yPos}, x_pos_{xPos} { } double x_pos() const { return x_pos_; } double y_pos() const { return y_pos_; } private: friend class boost::serialization::access; template <typename Archive> void serialize(Archive& ar, const unsigned int version) { ar & boost::serialization::base_object<Packet>(*this); ar & x_pos_; ar & y_pos_; } double y_pos_; double x_pos_; }; void save() { boost::archive::text_oarchive oa{ss}; const PacketPlayerMovement packet{10.0, 20.0}; oa << packet; } void load() { boost::archive::text_iarchive ia{ss}; PacketPlayerMovement packet; ia >> packet; std::cout << "Packet type" << packet.packet_type() << std::endl; std::cout << "X pos " << packet.x_pos() << std::endl; std::cout << "Y Pos " << packet.y_pos() << std::endl; } int main() { save(); load(); return 0; } }
19.325843
80
0.684302
dd4d94cc37f5e3ddbbc301d2e84c21e6c02a492d
1,089
dart
Dart
lib/presentation/common/selectable/cupertino_selectable.dart
abe2602/comic_organizer
87e236398b2a7129867135c5692967fd77fafc0f
[ "MIT" ]
null
null
null
lib/presentation/common/selectable/cupertino_selectable.dart
abe2602/comic_organizer
87e236398b2a7129867135c5692967fd77fafc0f
[ "MIT" ]
null
null
null
lib/presentation/common/selectable/cupertino_selectable.dart
abe2602/comic_organizer
87e236398b2a7129867135c5692967fd77fafc0f
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; /// Makes the child widget selectable and gives it the visual feedback of /// the selection. class CupertinoSelectable extends StatefulWidget { const CupertinoSelectable({@required this.child, Key key, this.onTap}) : assert(child != null), super(key: key); final GestureTapCallback onTap; final Widget child; @override _CupertinoSelectableState createState() => _CupertinoSelectableState(); } class _CupertinoSelectableState extends State<CupertinoSelectable> { bool _isSelected = false; @override Widget build(BuildContext context) => GestureDetector( behavior: HitTestBehavior.opaque, onTap: widget.onTap, onTapDown: (_) => setState(() { _isSelected = true; }), onTapUp: (_) => setState(() { _isSelected = false; }), onTapCancel: () => setState(() { _isSelected = false; }), child: Container( color: _isSelected ? Theme.of(context).splashColor : Colors.transparent, child: widget.child, ), ); }
26.560976
73
0.679522
b95fbfcbb614fc92154b92abcbc43aecaf7800d1
1,237
asm
Assembly
src/menu_items.asm
onslaught-demogroup/ons_paddo_music_disk
6a945f918fd1220b325385d14327b5e1ee86295d
[ "MIT" ]
null
null
null
src/menu_items.asm
onslaught-demogroup/ons_paddo_music_disk
6a945f918fd1220b325385d14327b5e1ee86295d
[ "MIT" ]
null
null
null
src/menu_items.asm
onslaught-demogroup/ons_paddo_music_disk
6a945f918fd1220b325385d14327b5e1ee86295d
[ "MIT" ]
null
null
null
.var menu_x = 2 .var menu_y = 3 .var menu_h = 20 .var menu_w = 11 .var item_w = 50 menu_screen_lo: .pc=* "menu_screen_lo" .for(var i=0;i<menu_h;i++){ .byte <($0400 + (menu_y * $28) + menu_x + (i * $28)) } menu_screen_hi: .pc=* "menu_screen_hi" .for(var i=0;i<menu_h;i++){ .byte >($0400 + (menu_y * $28) + menu_x + (i * $28)) } menu_title_length: .pc=* "menu_title_length" .for(var i=0;i<sid_name.size();i++){ .var title = sid_name.get(i) .var index = title.size() - 1 .while((title.charAt(index) == ' ') && (index > 0)){ .eval index-- } .if(index < menu_w + 3){ .eval index = menu_w + 3 } .byte index - menu_w + 2 } .align $100 .pc=* "menu_indexes_lo" menu_indexes_lo: .for(var i=0;i<sid_name.size();i++){ .byte <(menu_items + (i * 64)) } .align $80 .pc=* "menu_indexes_hi" menu_indexes_hi: .for(var i=0;i<sid_name.size();i++){ .byte >(menu_items + (i * 64)) } .align $100 .pc=* "menu_items" menu_items: .for(var i=0;i<sid_name.size();i++){ .align $40 .byte sid_disk.get(i) .for(var j=0;j<63;j++){ .if(j < sid_name.get(i).size()){ .byte sid_name.get(i).toLowerCase().charAt(j) } else { .byte $20 } } }
19.951613
57
0.549717
44cce064cccff3040b53ee9c32ad961566e75bd4
30
cql
SQL
blog/src/main/resources/config/cql/drop-keyspace.cql
mraible/devoxxus-jhipster-microservices-demo
286f5644ab5b717049db3d66f4a2b152a7397d78
[ "Apache-2.0" ]
10
2017-03-23T03:29:09.000Z
2019-04-14T04:31:08.000Z
blog/src/main/resources/config/cql/drop-keyspace.cql
mraible/devoxxus-jhipster-microservices-demo
286f5644ab5b717049db3d66f4a2b152a7397d78
[ "Apache-2.0" ]
null
null
null
blog/src/main/resources/config/cql/drop-keyspace.cql
mraible/devoxxus-jhipster-microservices-demo
286f5644ab5b717049db3d66f4a2b152a7397d78
[ "Apache-2.0" ]
4
2017-06-12T16:30:08.000Z
2017-10-04T20:27:36.000Z
DROP KEYSPACE IF EXISTS blog;
15
29
0.8
ddadc3c94f9f3088e18b4b5e8857bc1dad7c9fdf
3,195
php
PHP
console/run.php
oyym123/oyym
0c058677a5e1cfcda8f0ab997d1e7e6d9002226c
[ "BSD-3-Clause" ]
1
2020-06-02T16:37:25.000Z
2020-06-02T16:37:25.000Z
console/run.php
oyym123/oyym
0c058677a5e1cfcda8f0ab997d1e7e6d9002226c
[ "BSD-3-Clause" ]
null
null
null
console/run.php
oyym123/oyym
0c058677a5e1cfcda8f0ab997d1e7e6d9002226c
[ "BSD-3-Clause" ]
null
null
null
<?php /** * PHP crontab * 使用方法:在config.ini中配置要执行的计划任务 * 在php-cli执行run.php * @author Devil **/ while(true){ $config = parse_ini_file('./config/crontab.php',true); foreach($config as $cronName=>$info){ if(array_key_exists('log_dir',$info) && !empty($info['log_dir'])){ $outputCommon = ' 1>>'.$info['log_dir'].' 2>&1 &'; }else{ $outputCommon = ''; } $runStatus = timeMark($info['run_time']); if($runStatus){ $memory = convert(memory_get_usage(true)); //echo '['.date('Y-m-d H:i:s').'] Task:['.$cronName."]->Is Runing Mem:".$memory."\r\n"; pclose( popen('cd '.$info['cd_dir'].'&'.$info['common'].$outputCommon,'r')); //pclose($handle); }else{ //echo '['.date('Y-m-d H:i:s').']'."Waiting for a task\r\n"; } } sleep(1); } /** *解析时间计划任务规则 */ //$match = '*/3 18 * * *'; //$res = timeMark($match); function timeMark($match){ $s = date('s');//秒 $i = date('i');//分 $h = date('H');//时 $d = date('d');//日 $m = date('m');//月 $w = date('w');//周 $run_time = explode(' ',$match); $data[] = T($run_time[0],$s,'s'); $data[] = T($run_time[1],$i,'i'); $data[] = T($run_time[2],$h,'h'); $data[] = T($run_time[3],$d,'d'); $data[] = T($run_time[4],$m,'m'); $data[] = T($run_time[5],$w,'w'); return !in_array(false,$data)?true:false; } //解析单个时间规则细节 function T($rule,$time,$timeType){ if(is_numeric($rule)){ return $rule == $time ?true:false; }elseif(strstr($rule,',')){ $iArr = explode(',',$rule); return in_array($time,$iArr)?true:false; }elseif(strstr($rule,'/') && !strstr($rule,'-')){ list($left,$right) = explode('/',$rule); return in_array($left,array('*',0)) && analysis_t($time,$right)?true:false; }elseif(strstr($rule,'/') && strstr($rule,'-')){ list($left,$right) = explode('/',$rule); if(strstr($left,'-')){ return analysis($left,$right,$time,$timeType); } }elseif(strstr($rule,'-')){ list($left,$right) = explode('-',$rule); return $time >= $left && $time <=$right?true:false; }elseif($rule =='*' || $rule==0){ return true; }else{ return false; } } //解析12-2 23-22 任何时间的通用 //$rank范围 $num阀值 $time当前时间 $timeType时间类型 function analysis($rank,$num,$time,$timeType){ $type = array( 'i'=>59,'h'=>23,'d'=>31,'m'=>12,'w'=>6, ); list($left,$right) = explode('-',$rank); if($left<$right){ for($i=$left;$i<=$right;$i=$i+$num){ $temp[] = $i; } } if($left > $right){ for($i=$left;$i<=$type[$timeType]+$right;$i=$i+$num){ $temp[] = $i>$type[$timeType]?$i-$type[$timeType]:$i; } } return in_array($time,$temp)?true:false; } //根据当前时间计算是否定时循环执行 //$time当前时间 $num周期值 function analysis_t($time,$num){ return $time%$num == 0?true:false; } //$path 日志路径 $body 日志信息 function writeLog($path,$body){ if(!empty($path) && !empty($body)){ $temp = pathinfo($path); if(!file_exists($temp['dirname'])){ mkdir($temp['dirname'],0755,true); } file_put_contents($path,'['.date('Y-m-d H:i:s')."]\r\n".$body."\r\n\n",FILE_APPEND); } } //字节换算 function convert($size) { $unit=array('b','kb','mb','gb','tb','pb'); return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; }
27.076271
91
0.546166
28144a9e146f5d9d4e6707a9dab9cf11b376d98c
203
go
Go
src/tools/dnsenum/programName_test.go
Asymmetric-Effort/asymmetric-toolkit
64dab0a64b274ade31f14e1d8c0be0a58b33726c
[ "MIT" ]
1
2021-01-28T19:44:02.000Z
2021-01-28T19:44:02.000Z
src/tools/dnsenum/programName_test.go
Asymmetric-Effort/asymmetric-toolkit
64dab0a64b274ade31f14e1d8c0be0a58b33726c
[ "MIT" ]
null
null
null
src/tools/dnsenum/programName_test.go
Asymmetric-Effort/asymmetric-toolkit
64dab0a64b274ade31f14e1d8c0be0a58b33726c
[ "MIT" ]
1
2021-01-30T02:42:09.000Z
2021-01-30T02:42:09.000Z
package main import ( "asymmetric-effort/asymmetric-toolkit/src/common/errors" "testing" ) func TestProgramName(t *testing.T){ errors.Assert(ProgramName=="dnsName","dnsName program name mismatch") }
20.3
70
0.768473
7ba4a118e97d0b5cf1bcb6e89bf10da6753c347f
160
css
CSS
styles.css
microhod/ball-simulator
62a35962d307459ef6b69f3ffab3dbfeb76793aa
[ "MIT" ]
null
null
null
styles.css
microhod/ball-simulator
62a35962d307459ef6b69f3ffab3dbfeb76793aa
[ "MIT" ]
1
2022-02-13T22:01:15.000Z
2022-02-13T22:01:15.000Z
styles.css
microhod/ball-simulator
62a35962d307459ef6b69f3ffab3dbfeb76793aa
[ "MIT" ]
null
null
null
h1 { text-align: center; } body { background: gray; color: white; } canvas { background: white; padding: 0; margin: 0 auto; display: block; }
10
21
0.60625
5f10558e08319c71626f8a220362b61ae7c77b43
481
sql
SQL
typz-all/typz-web/src/main/resources/dbmigrate/mysql/shop/V0_0_4__t_sh_goods_price.sql
prayjourney/typz-backend
4d8fbecc31eeb15f39e7cb800a1672df78eb078c
[ "Apache-2.0" ]
39
2016-05-04T09:11:39.000Z
2021-06-12T11:37:08.000Z
typz-all/typz-web/src/main/resources/dbmigrate/mysql/shop/V0_0_4__t_sh_goods_price.sql
prayjourney/typz-backend
4d8fbecc31eeb15f39e7cb800a1672df78eb078c
[ "Apache-2.0" ]
1
2016-05-04T01:17:31.000Z
2016-05-04T01:17:31.000Z
typz-all/typz-web/src/main/resources/dbmigrate/mysql/shop/V0_0_4__t_sh_goods_price.sql
izhbg/typz
4d8fbecc31eeb15f39e7cb800a1672df78eb078c
[ "Apache-2.0" ]
32
2016-05-04T09:35:54.000Z
2020-03-08T06:40:23.000Z
CREATE TABLE `t_sh_goods_price` ( `id` varchar(50) NOT NULL, `goods_id` varchar(50) DEFAULT NULL, `version` int(11) DEFAULT NULL, `price_type` int(11) DEFAULT NULL, `price` double DEFAULT NULL, `del_status` int(11) DEFAULT NULL, `create_time` datetime DEFAULT NULL, `create_user` varchar(50) DEFAULT NULL, `update_time` datetime DEFAULT NULL, `update_user` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
28.294118
42
0.694387
c3bf259354f78d93c30e5a289627a76c0494e9db
1,571
go
Go
engine/engine_manager.go
qingmingliang/baudengine
6f1a1790033c54414af56ac220cb3a0de016c9ca
[ "Apache-2.0" ]
null
null
null
engine/engine_manager.go
qingmingliang/baudengine
6f1a1790033c54414af56ac220cb3a0de016c9ca
[ "Apache-2.0" ]
null
null
null
engine/engine_manager.go
qingmingliang/baudengine
6f1a1790033c54414af56ac220cb3a0de016c9ca
[ "Apache-2.0" ]
null
null
null
package engine import ( "errors" "fmt" ) var ( engines map[string]EngineBuilder ErrorNameInvalid = errors.New("Registration name is invalid") ) func init() { engines = make(map[string]EngineBuilder, 8) } // EngineBuilder is used to build the engine. type EngineBuilder func(cfg EngineConfig) (Engine, error) // EngineConfig holds all configuration parameters used in setting up a new Engine instance. type EngineConfig struct { // Path is the data directory. Path string // ReadOnly will open the engine in read only mode if set to true. ReadOnly bool // ExtraOptions contains extension options using a json format ("{key1:value1,key2:value2}"). ExtraOptions string // Schema Schema string } // Register is used to register the engine implementers in the initialization phase. func Register(name string, builder EngineBuilder) { if name == "" || builder == nil { panic("Registration name and builder cannot be empty") } if _, ok := engines[name]; ok { panic(fmt.Sprintf("Duplicate registration engine name for %s", name)) } engines[name] = builder } // Build create an engine based on the specified name. func Build(name string, cfg EngineConfig) (e Engine, err error) { if name == "" { return nil, ErrorNameInvalid } if builder := engines[name]; builder != nil { e, err = builder(cfg) } else { err = fmt.Errorf("Registered engine[%s] does not exist", name) } return } // Exist return whether the engine exists. func Exist(name string) bool { if builder := engines[name]; builder != nil { return true } return false }
23.102941
94
0.714831
502eafc92ada65166056ff9b6f4fce16b3df7677
371
go
Go
pkg/harbor_test.go
spotmaxtech/mcrepo
2e46da49652932d815b0c36e9168cfd7b8a587c4
[ "MIT" ]
1
2022-02-18T01:28:34.000Z
2022-02-18T01:28:34.000Z
pkg/harbor_test.go
spotmaxtech/mcrepo
2e46da49652932d815b0c36e9168cfd7b8a587c4
[ "MIT" ]
null
null
null
pkg/harbor_test.go
spotmaxtech/mcrepo
2e46da49652932d815b0c36e9168cfd7b8a587c4
[ "MIT" ]
null
null
null
package pkg import ( "testing" ) func TestHarborRegistry_ListRepo(t *testing.T) { InitConfig() InitHarborRegistryMap(GMcrepoConfig.Harbor) HarborRegistryMap["second"].ListRepo() } func TestHarborRegistry_ListRepoTag(t *testing.T) { InitConfig() InitHarborRegistryMap(GMcrepoConfig.Harbor) HarborRegistryMap["second"].ListRepoTag("official-website/cms_server") }
21.823529
71
0.797844
550f70defe3ad5f0e9f3fbae7f0943faa33de2b5
3,004
swift
Swift
Sources/TensorFlow/Epochs/Slices.swift
vguerra/swift-apis
215c1380874c55d2f12ae81ce78968f9e25ed723
[ "Apache-2.0" ]
848
2019-02-12T00:27:29.000Z
2022-01-26T04:41:50.000Z
Sources/TensorFlow/Epochs/Slices.swift
BradLarson/swift-apis
02f31d531cbbfbd72de2b2f288f24f8645ee5bcb
[ "Apache-2.0" ]
698
2019-02-12T12:35:54.000Z
2022-01-25T00:48:53.000Z
Sources/TensorFlow/Epochs/Slices.swift
ProfFan/swift-apis
f51ee4618d652a2419e998bf9418ad80bda67454
[ "Apache-2.0" ]
181
2019-02-12T00:33:34.000Z
2021-12-05T19:15:55.000Z
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// A collection of the longest non-overlapping contiguous slices of some `Base` /// collection, starting with its first element, and having some fixed maximum /// length. /// /// The elements of this collection, except for the last, all have a `count` of /// `batchSize`, unless `Base.count % batchSize !=0`, in which case /// the last batch's `count` is `base.count % batchSize.` public struct Slices<Base: Collection> { /// The collection from which slices will be drawn. private let base: Base /// The maximum length of the slices. private let batchSize: Int /// Creates an instance that divides `base` into batches /// of size `n`. /// /// If `base.count % n != 0` the `count` of the last batch /// will be `base.count % n` public init(_ base: Base, batchSize n: Int) { self.base = base batchSize = n } } extension Slices: Collection { /// A position in `Slices`. public struct Index: Comparable { /// The range of base indices covered by the element at this position. var focus: Range<Base.Index> /// Returns true iff `l` precedes `r` in the collection. public static func < (l: Index, r: Index) -> Bool { l.focus.lowerBound < r.focus.lowerBound } } /// Returns the element at `i`. public subscript(i: Index) -> Base.SubSequence { base[i.focus] } /// Returns the base index that marks the end of the element of `self` that /// begins at `i` in the `base`, or `base.endIndex` if `i == base.endIndex`. private func sliceBoundary(after i: Base.Index) -> Base.Index { base.index(i, offsetBy: batchSize, limitedBy: base.endIndex) ?? base.endIndex } /// Returns the index after `i`. public func index(after i: Index) -> Index { Index(focus: i.focus.upperBound..<sliceBoundary(after: i.focus.upperBound)) } /// Returns the first position in `self`. public var startIndex: Index { Index(focus: base.startIndex..<sliceBoundary(after: base.startIndex)) } /// Returns the position one past the last element of `self`. public var endIndex: Index { Index(focus: base.endIndex..<base.endIndex) } } extension Collection { /// Returns the longest non-overlapping slices of `self`, starting with its /// first element, having a maximum length of `batchSize`. public func inBatches(of batchSize: Int) -> Slices<Self> { Slices(self, batchSize: batchSize) } }
35.341176
80
0.688748
3c04d02a1594adb67758ef9b7bbabd6719e68ba3
1,663
dart
Dart
flutter/lib/module_auth/ui/states/login_states/login_state_error.dart
aliomom/tourist
a187fd724c0a607d3f28981abfe2a4154197dac0
[ "MIT" ]
null
null
null
flutter/lib/module_auth/ui/states/login_states/login_state_error.dart
aliomom/tourist
a187fd724c0a607d3f28981abfe2a4154197dac0
[ "MIT" ]
1
2020-07-19T13:04:49.000Z
2020-07-19T13:04:49.000Z
flutter/lib/module_auth/ui/states/login_states/login_state_error.dart
aliomom/tourist
a187fd724c0a607d3f28981abfe2a4154197dac0
[ "MIT" ]
2
2021-03-14T19:09:03.000Z
2021-04-29T18:55:47.000Z
import 'package:tourists/module_auth/enums/user_type.dart'; import 'package:tourists/module_auth/ui/screen/login_screen/login_screen.dart'; import 'package:tourists/module_auth/ui/states/login_states/login_state.dart'; import 'package:tourists/module_auth/ui/widget/phone_email_link_login/phone_email_link_login.dart'; import 'package:flutter/material.dart'; class LoginStateError extends LoginState { String errorMsg; UserRole userType = UserRole.ROLE_TOURIST; final loginTypeController = PageController(initialPage: UserRole.ROLE_TOURIST.index); bool loading = false; String email; String password; UserRole role; LoginStateError( LoginScreenState screen, this.errorMsg, this.email, this.password, this.role) : super(screen); @override Widget getUI(BuildContext context) { return SafeArea( child: Column( children: [ Expanded( child: Center( child: PhoneEmailLinkLoginFormWidget( onEmailLinkRequest: (email, role) { screen.sendLoginLink(email, role); }, onCodeRequested: (phoneNumber, role) { screen.loginViaPhone(phoneNumber, role); }, onGmailLoginRequested: (role) { screen.loginViaGoogle(role); }, onSnackBarRequested: (msg) { screen.showSnackBar(msg); }, ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text(errorMsg, maxLines: 3,), ) ], ), ); } }
30.796296
99
0.603127
393ef164b5a04b6ac1b5c03f92fb406145d7a89b
589
html
HTML
src/app/components/svg/svg-video/svg-video.component.html
AshleyJSheridan/a11y-checklist
afe36d79c04b47d68b2cad2de5cd1fd7f8f449f0
[ "MIT" ]
1
2021-05-05T07:07:05.000Z
2021-05-05T07:07:05.000Z
src/app/components/svg/svg-video/svg-video.component.html
AshleyJSheridan/a11y-checklist
afe36d79c04b47d68b2cad2de5cd1fd7f8f449f0
[ "MIT" ]
10
2020-12-07T23:53:58.000Z
2022-02-27T06:53:13.000Z
src/app/components/svg/svg-video/svg-video.component.html
AshleyJSheridan/a11y-checklist
afe36d79c04b47d68b2cad2de5cd1fd7f8f449f0
[ "MIT" ]
2
2021-02-01T13:50:24.000Z
2021-05-05T07:07:11.000Z
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300" viewBox="0 0 300 300" version="1.1" fill="none" stroke="#000000" stroke-linejoin="round" role="img" aria-hidden="true"> <g transform="scale(.9), translate(15,0)"> <rect width="284.62003" height="169.65601" x="10.525463" y="121.13264" ry="0.1311852"/> <rect width="287.07401" height="38.578964" x="-13.888877" y="82.214249" ry="0.029830884" transform="rotate(-11.525174)"/> <path d="M 11.881188,158.88119 H 294.05939"/> <path d="m 171.09719,219.96619 -45.23085,30.9942 v -62.00494 l 45.23085,31.01074"/> </g> </svg>
73.625
184
0.665535
b9683f4055e4ce2131547f9f56e936b497bf2d8c
2,312
h
C
src/comet/core/engine.h
m4jr0/gameengine
8b63893ac65c5853852c1418550d2772c22cd10f
[ "MIT" ]
2
2018-09-15T21:18:26.000Z
2018-10-03T14:28:26.000Z
src/comet/core/engine.h
m4jr0/gameengine
8b63893ac65c5853852c1418550d2772c22cd10f
[ "MIT" ]
null
null
null
src/comet/core/engine.h
m4jr0/gameengine
8b63893ac65c5853852c1418550d2772c22cd10f
[ "MIT" ]
null
null
null
// Copyright 2021 m4jr0. All Rights Reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. #ifndef COMET_COMET_CORE_ENGINE_H_ #define COMET_COMET_CORE_ENGINE_H_ #include "comet/event/event_manager.h" #include "comet/game_object/camera/camera.h" #include "comet/game_object/game_object_manager.h" #include "comet/input/input_manager.h" #include "comet/physics/physics_manager.h" #include "comet/rendering/rendering_manager.h" #include "comet/resource/resource_manager.h" #include "comet/time/time_manager.h" #include "comet_precompile.h" namespace comet { namespace core { class Engine { public: static constexpr double kMsPerUpdate_ = 16.66; // 60 Hz refresh. Engine(const Engine&) = delete; Engine(Engine&&) = delete; Engine& operator=(const Engine&) = delete; Engine& operator=(Engine&&) = delete; virtual ~Engine() = default; virtual void Initialize(); virtual void Run(); virtual void Stop(); virtual void Destroy(); virtual void Quit(); static Engine& GetEngine(); resource::ResourceManager& GetResourceManager(); rendering::RenderingManager& GetRenderingManager(); input::InputManager& GetInputManager(); time::TimeManager& GetTimeManager(); game_object::GameObjectManager& GetGameObjectManager(); event::EventManager& GetEventManager(); game_object::Camera& GetMainCamera(); const bool is_running() const noexcept; protected: inline static Engine* engine_; Engine(); virtual void Exit(); void OnEvent(const event::Event&); std::unique_ptr<resource::ResourceManager> resource_manager_ = nullptr; std::unique_ptr<input::InputManager> input_manager_ = nullptr; std::unique_ptr<physics::PhysicsManager> physics_manager_ = nullptr; std::unique_ptr<rendering::RenderingManager> rendering_manager_ = nullptr; std::unique_ptr<game_object::GameObjectManager> game_object_manager_ = nullptr; std::unique_ptr<time::TimeManager> time_manager_ = nullptr; std::unique_ptr<event::EventManager> event_manager_ = nullptr; std::shared_ptr<game_object::Camera> main_camera_ = nullptr; private: bool is_running_ = false; bool is_exit_requested_ = false; }; std::unique_ptr<Engine> CreateEngine(); } // namespace core } // namespace comet #endif // COMET_COMET_CORE_ENGINE_H_
30.826667
76
0.757785
92ea1daa3f1ef029ceae99ea45737d0196b3a8be
22,357
c
C
patricialib/Patricia.c
trijezdci/C-Collections
0d5671846f59f3bba69793004648cc1c3bf78800
[ "BSD-3-Clause" ]
1
2021-08-06T02:47:18.000Z
2021-08-06T02:47:18.000Z
patricialib/Patricia.c
trijezdci/C-Collections
0d5671846f59f3bba69793004648cc1c3bf78800
[ "BSD-3-Clause" ]
null
null
null
patricialib/Patricia.c
trijezdci/C-Collections
0d5671846f59f3bba69793004648cc1c3bf78800
[ "BSD-3-Clause" ]
2
2021-08-06T02:47:37.000Z
2021-12-16T12:25:48.000Z
/* Patricia Trie Library * * @file Patricia.h * Patricia implementation * * Universal Patricia Trie * * Author: Benjamin Kowarsch * * Copyright (C) 2009 Benjamin Kowarsch. All rights reserved. * * License: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met * * 1) NO FEES may be charged for the provision of the software. The software * may NOT be published on websites that contain advertising, unless * specific prior written permission has been obtained. * * 2) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 3) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and other materials provided with the distribution. * * 4) Neither the author's name nor the names of any contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * 5) Where this list of conditions or the following disclaimer, in part or * as a whole is overruled or nullified by applicable law, no permission * is granted to use the software. * * 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. * */ // --------------------------------------------------------------------------- // Reference documents // --------------------------------------------------------------------------- // // Patricia, Practical Algorithm To Retrieve Information Coded In Alphanumeric // by Donald R.Morrison, published in JACM, Vol.15, Issue 4, 1968, by ACM // Abstract: http://portal.acm.org/citation.cfm?doid=321479.321481 // // Use of a binary tree structure for processing files // by G. Gwehenberger, published in Elektronische Rechenanlagen, No. 10, 1968 // Full text: http://cr.yp.to/bib/1968/gwehenberger.html (in German only) #include "Patricia.h" #include "../common/alloc.h" // --------------------------------------------------------------------------- // Determine suitable unsigned integer type for bit index // --------------------------------------------------------------------------- #if (PTRIE_MAXIMUM_KEY_LENGTH * 8 <= ((1 << 8) - 1)) #define PTRIE_BIT_INDEX_BASE_TYPE uint8_t #elif (PTRIE_MAXIMUM_KEY_LENGTH * 8 <= ((1 << 16) - 1)) #define PTRIE_BIT_INDEX_BASE_TYPE uint16_t #elif (PTRIE_MAXIMUM_KEY_LENGTH * 8 <= ((1 << 32) - 1)) #define PTRIE_BIT_INDEX_BASE_TYPE uint32_t #elif (PTRIE_MAXIMUM_KEY_LENGTH * 8 <= ((1 << 64UL) - 1)) #define PTRIE_BIT_INDEX_BASE_TYPE uint64_t #else /* out of range for 64 bit unsigned */ #error PTRIE_MAXIMUM_KEY_LENGTH too large #endif // --------------------------------------------------------------------------- // Bit index type // --------------------------------------------------------------------------- typedef PTRIE_BIT_INDEX_BASE_TYPE ptrie_index_t; // --------------------------------------------------------------------------- // Patricia trie node pointer type for self referencing declaration of node // --------------------------------------------------------------------------- struct _ptrie_node_s; /* FORWARD */ typedef struct _ptrie_node_s *ptrie_node_p; // --------------------------------------------------------------------------- // Patricia trie node type // --------------------------------------------------------------------------- struct _ptrie_node_s { ptrie_index_t index; ptrie_key_t key; ptrie_data_t value; ptrie_node_p left; ptrie_node_p right; }; typedef struct _ptrie_node_s ptrie_node_s; // --------------------------------------------------------------------------- // Patricia trie type // --------------------------------------------------------------------------- typedef struct /* ptrie_s */ { ptrie_counter_t entry_count; ptrie_node_s *root_node; } ptrie_s; // --------------------------------------------------------------------------- // Patricia trie node sentinel representing the bottom of a trie // --------------------------------------------------------------------------- static ptrie_node_s _bottom = { 0, NULL, NULL, &_bottom, &_bottom }; static ptrie_node_s *bottom = &_bottom; // =========================================================================== // P R I V A T E F U N C T I O N P R O T O T Y P E S // =========================================================================== static fmacro ptrie_node_p _search(ptrie_node_p start_node, ptrie_key_t key, bool *exact_match); static ptrie_node_p _insert(ptrie_node_p node, ptrie_key_t key, ptrie_data_t value, ptrie_status_t *status); static void _remove(ptrie_node_p node, ptrie_key_t key, ptrie_status_t *status); // =========================================================================== // P U B L I C F U N C T I O N I M P L E M E N T A T I O N S // =========================================================================== // --------------------------------------------------------------------------- // function: ptrie_new_trie( status ) // --------------------------------------------------------------------------- // // Creates and returns a new trie object. Returns NULL if the trie object // could not be created. // // The status of the operation is passed back in <status>, unless NULL was // passed in for <status>. ptrie_t ptrie_new_trie(ptrie_status_t *status) { ptrie_s *new_trie; // allocate new trie new_trie = ALLOCATE(sizeof(ptrie_s)); // bail out if allocation failed if (new_trie == NULL) { ASSIGN_BY_REF(status, PTRIE_STATUS_ALLOCATION_FAILED); return NULL; } // end if // initialise new trie new_trie->entry_count = 0; new_trie->root_node = bottom; // pass new trie and status to caller ASSIGN_BY_REF(status, PTRIE_STATUS_SUCCESS); return (ptrie_t) new_trie; } // end ptrie_new_trie // --------------------------------------------------------------------------- // function: ptrie_store_entry( trie, key, value, status ) // --------------------------------------------------------------------------- // // Stores <value> for <key> in <trie>. The new entry is added by reference, // NO data is copied. The function fails if NULL is passed in for <trie> or // <value> or if zero is passed in for <key>. // // The status of the operation is passed back in <status>, unless NULL was // passed in for <status>. void ptrie_store_entry(ptrie_t trie, ptrie_key_t key, ptrie_data_t value, ptrie_status_t *status) { #define this_trie ((ptrie_s *)trie) ptrie_node_s *insertion_point; ptrie_node_s *new_node; ptrie_status_t r_status; bool exact_match; // bail out if trie is NULL if (trie == NULL) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_TRIE); return; } // end if // bail out if key is NULL or empty if ((key == NULL) || (key[0] == 0)) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_KEY); return NULL; } // end if insertion_point = _search(this_trie->root_node, key, &exact_match); // bail out if entry already exists if (exact_match == true) { ASSIGN_BY_REF(status, PTRIE_STATUS_KEY_NOT_UNIQUE); return; } // end if this_trie->root_node = _insert(insertion_point, key, value, &r_status); if (r_status == PTRIE_STATUS_SUCCESS) this_trie->entry_count++; // pass status to caller ASSIGN_BY_REF(status, r_status); return; #undef this_trie } // end ptrie_store_entry // --------------------------------------------------------------------------- // function: ptrie_replace_entry( trie, key, value, status ) // --------------------------------------------------------------------------- // // Searches the entry in <trie> whose key matches <key> and replaces its value // with <value>. The function fails if NULL is passed in for <trie> or <key>, // or if a pointer to a zero length string is passed in for <key>, or if no // entry is found in <trie> with a key that matches <key>. // // The status of the operation is passed back in <status>, unless NULL was // passed in for <status>. void ptrie_replace_entry(ptrie_t trie, ptrie_key_t key, ptrie_data_t value, ptrie_status_t *status) { #define this_trie ((ptrie_s *)trie) ptrie_node_s *this_node; bool exact_match; // bail out if trie is NULL if (trie == NULL) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_TRIE); return; } // end if // bail out if key is NULL or empty if ((key == NULL) || (key[0] == 0)) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_KEY); return NULL; } // end if this_node = _search(this_trie->root_node, key, &exact_match); if (exact_match == true) { ASSIGN_BY_REF(status, PTRIE_STATUS_SUCCESS); this_node->value = value; } else /* not exact match */ { ASSIGN_BY_REF(status, PTRIE_STATUS_ENTRY_NOT_FOUND); } // end if return; #undef this_trie } // end ptrie_replace_entry // --------------------------------------------------------------------------- // function: ptrie_value_for_key( trie, index, status ) // --------------------------------------------------------------------------- // // Returns the value stored for <key> in <trie>. If no value for <key> exists // in <trie>, or if NULL is passed in for <trie>, then NULL is returned. // // The status of the operation is passed back in <status>, unless NULL was // passed in for <status>. ptrie_data_t ptrie_value_for_key(ptrie_t trie, ptrie_key_t key, ptrie_status_t *status) { #define this_trie ((ptrie_s *)trie) ptrie_node_s *this_node; bool exact_match; // bail out if trie is NULL if (trie == NULL) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_TRIE); return NULL; } // end if // bail out if key is NULL or empty if ((key == NULL) || (key[0] == 0)) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_KEY); return NULL; } // end if this_node = _search(this_trie->root_node, key, &exact_match); if (exact_match == true) { ASSIGN_BY_REF(status, PTRIE_STATUS_SUCCESS); return this_node->key; } else /* not exact match */ { ASSIGN_BY_REF(status, PTRIE_STATUS_ENTRY_NOT_FOUND); return NULL; } // end if #undef this_trie } // end ptrie_value_for_key // --------------------------------------------------------------------------- // function: ptrie_foreach_entry_do( trie, prefix, action, status ) // --------------------------------------------------------------------------- // // Traverses <trie> visiting all entries whose keys have a common prefix with // <prefix> and invokes the action callback function passed in for <action> // for each entry visited. If an empty string is passed in for <prefix>, // then each entry in <trie> will be visited. The function returns the number // of entries visited. The function fails and returns zero if NULL is passed // in for <trie> or <prefix> or <action>. // // Each time <action> is called, the following parameters are passed to it: // // o first parameter : the key of the visited node // o second parameter: the value of the visited node // // The status of the operation is passed back in <status>, unless NULL was // passed in for <status>. ptrie_counter_t ptrie_foreach_entry_do(ptrie_t trie, ptrie_key_t prefix, ptrie_action_f action, ptrie_status_t *status) { #define this_trie ((ptrie_s *)trie) // bail out if trie is NULL if (trie == NULL) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_TRIE); return 0; } // end if // bail out if key is NULL if (key == NULL) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_KEY); return 0; } // end if // bail out if action is NULL if (action == NULL) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_ACTION); return 0; } // end if // TO DO #undef this_trie } // end ptrie_foreach_entry_do // --------------------------------------------------------------------------- // function: ptrie_number_of_entries( trie ) // --------------------------------------------------------------------------- // // Returns the number of entries stored in <trie>, returns zero if NULL is // passed in for <trie>. inline ptrie_counter_t ptrie_number_of_entries(ptrie_t trie) { #define this_trie ((ptrie_s *)trie) if (trie == NULL) return 0; return this_trie->entry_count; #undef this_trie } // end ptrie_number_of_entries // --------------------------------------------------------------------------- // function: ptrie_number_of_entries_with_prefix( trie, prefix ) // --------------------------------------------------------------------------- // // Returns the number of entries stored in <trie> whose keys have a common // prefix with <prefix>. If an empty string is passed in for <prefix>, then // the total number of entries stored in <trie> is returned. The function // fails and returns zero if NULL is passed in for <trie> or <key>. ptrie_counter_t ptrie_number_of_entries_with_prefix(ptrie_t trie, ptrie_key_t prefix) { #define this_trie ((ptrie_s *)trie) if (trie == NULL) return 0; // TO DO return 0; #undef this_trie } // end ptrie_number_of_entries_with_prefix // --------------------------------------------------------------------------- // function: ptrie_remove_entry( trie ) // --------------------------------------------------------------------------- // // Removes the entry stored for <key> from <trie>. The function fails if NULL // is passed in for <trie> or if no entry for <key> is stored in <trie>. // // The status of the operation is passed back in <status>, unless NULL was // passed in for <status>. void ptrie_remove_entry(ptrie_t trie, ptrie_key_t key, ptrie_status_t *status) { #define this_trie ((ptrie_s *)trie) ptrie_status_t r_status; // bail out if trie is NULL if (trie == NULL) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_TRIE); return NULL; } // end if // bail out if key is NULL or empty if ((key == NULL) || (key[0] == 0)) { ASSIGN_BY_REF(status, PTRIE_STATUS_INVALID_KEY); return NULL; } // end if _remove(this_trie->root_node, key, &r_status); if (r_status == PTRIE_STATUS_SUCCESS) this_trie->entry_count--; // pass status to caller ASSIGN_BY_REF(status, r_status); return; #undef this_trie } // end ptrie_remove_entry // --------------------------------------------------------------------------- // function: ptrie_dispose_trie( trie ) // --------------------------------------------------------------------------- // // Disposes of trie object <trie>. Returns NULL. ptrie_t *ptrie_dispose_trie(ptrie_t trie) { #define this_trie ((ptrie_s *)trie) if (trie != NULL) { // deallocate all nodes _remove_all(this_trie->root_node); // deallocate the trie DEALLOCATE(this_trie); } // end if return NULL; #undef this_trie } // end ptrie_dispose_trie // =========================================================================== // P R I V A T E F U N C T I O N I M P L E M E N T A T I O N S // =========================================================================== // --------------------------------------------------------------------------- // private macro: BIT_AT_INDEX( key, index ) // --------------------------------------------------------------------------- // // Tests bit at <index> in <key> and evaluates to its value. An index value // of N denotes the position of bit (7 - N % 8) in byte (N / 8) of key. // // pre-conditions: // // o index must not be less than 0 // o index must not be larger than 8 * length of key - 1 // o key must be a pointer to a C string or a byte array // // post-conditions: // // o macro evaluates to 0 if bit at index in key is 0 // o macro evaluates to 1 if but at index in key is 1 // // error-conditions: // // o undefined behaviour if pre-conditions are not met #define BIT_AT_INDEX(_key, _index) \ (((_key[_index / 8] & (7 - (index % 8))) == 0) ? 0 : 1) // --------------------------------------------------------------------------- // private function: _search( start_node, search_key ) // --------------------------------------------------------------------------- // // Searches for the node whose key matches <search_key>. The search starts at // node <start_node>. If an exact match is found, then the node whose key // matches is returned and true is passed back in <exact_match>. If an exact // match is not found, then the node whose key is the closest match in <trie> // is returned and false is passed back in <exact_match>. NULL must NOT be // passed in for <start_node> or <search_key< or <exact_match>. static fmacro ptrie_node_p _search(ptrie_node_p start_node, ptrie_key_t search_key, bool *exact_match) { ptrie_node_p this_node; ptrie_index_t index; this_node = start_node; // The bit index of a parent node is always larger // than the bit index of either of its child nodes. // to find an uplink, we move down the trie until the index of // a node is less than or equal to the index of its predecessor. repeat /* until uplink found */ { // remember bit index index = this_node->index; // test bit at index in search key if /* bit at index is 0 */ (BIT_AT_INDEX(search_key, index) == 0) { // move down the trie to the left this_node = this_node->left; } else /* bit at index is 1 */ { // move down the trie to the right this_node = this_node->right; } // end if } until (index >= this_node->index); // indicate exact match or best match *exact_match = (index == this_node->index); return this_node; } // end _search // --------------------------------------------------------------------------- // private function: _insert( node, key, value, status ) // --------------------------------------------------------------------------- // // Searches the trie starting at <node> for the insertion point for a new node // with key <key>. If no exact match exists, then a new node is allocated, // initialised with <key> and <value>, then inserted at the insertion point. // If <node> is pointing to the bottom sentinel node, then <node> itself be- // comes the insertion point. NULL must NOT be passed in for <node>, <key>, // or <status>. The status of the operation is passed back in <status>. static ptrie_node_p _insert(ptrie_node_p node, ptrie_key_t key, ptrie_data_t value, ptrie_status_t *status) { ptrie_node_s *new_node; if (node == bottom) { // allocate new node new_node = ALLOCATE(sizeof(ptrie_node_s)); // bail out if allocation failed if (new_node == NULL) { *status = PTRIE_STATUS_ALLOCATION_FAILED; return NULL; } // end if // initialise new node new_node->index = 0; new_node->key = key; new_node->value = value; new_node->left = bottom; new_node->right = new_node; // pass new node and status to caller *status = PTRIE_STATUS_SUCCESS; return new_node; } // end if // TO DO // return root node return node; } // end _insert // --------------------------------------------------------------------------- // private function: _remove( node ) // --------------------------------------------------------------------------- static void _remove(ptrie_node_p node, ptrie_key_t key, ptrie_status_t *status) { // TO DO return; } // end _remove // --------------------------------------------------------------------------- // private function: _remove_all( node ) // --------------------------------------------------------------------------- // // Recursively deallocates all nodes in the trie whose root node is <node>. static void _remove_all(ptrie_node_p node) { if (node == NULL) return; aat_remove_all(node->left); aat_remove_all(node->right); DEALLOCATE(node->key); DEALLOCATE(node); return; } // end _remove_all // END OF FILE
34.028919
78
0.528425
90ed2a5b899de00b1000351d64609b10108834bb
7,137
py
Python
db_utils.py
timwoj/tlmbot
4a4a4f4db18dc6e1e49cf549644d980211e5fe8a
[ "MIT" ]
null
null
null
db_utils.py
timwoj/tlmbot
4a4a4f4db18dc6e1e49cf549644d980211e5fe8a
[ "MIT" ]
9
2021-12-17T03:02:10.000Z
2022-03-16T04:52:46.000Z
db_utils.py
timwoj/tlmbot
4a4a4f4db18dc6e1e49cf549644d980211e5fe8a
[ "MIT" ]
null
null
null
import os import sqlite3 import sys import unittest from furl import furl from urllib.parse import urlparse,parse_qs from datetime import datetime def connect(path, read_only): full_path = path if read_only: full_path = f'file:{path}?mode=ro' conn = None try: conn = sqlite3.connect(full_path) except: if 'unittest' not in sys.modules.keys(): print(f'Failed to load database file \'{path}\': {sys.exc_info()[1]}') return None # Ensure we get Row objects back for queries. This makes handling # the results a little easier later. conn.row_factory = sqlite3.Row # Create a cursor and add the table if it doesn't exist already. cur = conn.cursor() cur.execute('create table if not exists urls(' 'url text primary key not null, ' 'count integer default 1, ' 'latest datetime not null default current_timestamp, ' 'orig_paster text not null, ' 'orig_date datetime not null default current_timestamp)') cur.execute('create table if not exists karma(' 'string text primary key not null, ' 'count integer default 1, ' 'orig_paster text not null, ' 'orig_date datetime not null default current_timestamp)') conn.commit() return conn # Parses a URL and strips unwanted params from def filter_query(url): f = furl(url) keys_to_remove = set() # for Amazon URLs, there's a few things that are always true. First, # all params are useless and can be removed. Also, the ending part of # the path starting with 'ref=' can be removed, if it exists. if f.host.find('amazon') != -1: f.args.clear() if f.path.segments[-1].startswith('ref='): f.path.segments.pop() elif f.host.find('twitter') != -1: # For Twitter, the same thing holds about params f.args.clear() else: for k in f.args: if f.host.find('amazon') != -1: keys_to_remove.add(k) elif k.startswith('utm_'): keys_to_remove.add(k) for k in keys_to_remove: f.args.pop(k) return f.url def store_url(db, url, paster): # trim all of the tracking stuff off it new_url = filter_query(url) # check if the new URI is in the database yet cur = db.cursor() cur.execute('select * from urls where url = ?', [new_url]) results = cur.fetchone() ret = None if results: ret = { 'count': results['count'], 'paster': results['orig_paster'], 'when': results['orig_date'] } now = datetime.now().replace(microsecond = 0) cur.execute('update urls set count = ?, latest = ? where url = ?', [results['count']+1, now, new_url]) else: # insert new URL with new count and original date cur.execute('insert into urls (url, orig_paster) values(?, ?)', [new_url, paster]) db.commit() return ret def _query_urls(db, command, stack): cur = db.cursor() if stack: cur.execute(command, stack) else: cur.execute(command) results = cur.fetchall() ret = [] for r in results: ret.append({'url': r['url'], 'count': r['count'], 'when': r['latest']}) return ret def get_urls(db, day_range=None, start_date=None, end_date=None): command = 'select * from urls ' stack = [] if day_range == 'all': # Nothing happens here. We just have the if statement to avoid # fallthrough into one of the other cases None elif day_range: command += f'where date(latest) between date("now", "{day_range}", "localtime") and date("now","localtime")' elif start_date: command += f'where datetime(latest) between datetime(?,"unixepoch") and datetime(?,"unixepoch")' stack.append(start_date) stack.append(end_date) else: command += 'where date(latest) = date("now","localtime")' command += ' order by latest desc' return _query_urls(db, command, stack) def search_urls(db, text): cur = db.cursor() command = 'select * from urls where url like ? order by latest desc' stack = [f'%{text}%'] return _query_urls(db, command, stack) def set_karma(db, text, paster, increase): cur = db.cursor() cur.execute('select * from karma where string = ?', [text]) results = cur.fetchone() if results: count = int(results['count']) if increase: count += 1 else: count -= 1 cur.execute('update karma set count = ? where string = ?', [count, text]) else: cur.execute('insert into karma (string, orig_paster) values(?, ?)', [text, paster]) db.commit() def get_karma(db, text): cur = db.cursor() cur.execute('select * from karma where string = ?', [text]) results = cur.fetchone() count = 0 if results: count = int(results['count']) return count class _TestCases(unittest.TestCase): def test_connect_failure(self): db = connect('/tmp/dbutil-test/sqlite.db') self.assertEqual(db, None) def test_connect_success(self): import tempfile path = os.path.join(tempfile.gettempdir(), 'testing-dbutils-sqlite.db') db = connect(str(path)) self.assertNotEqual(db, None) db.close() os.unlink(str(path)) def test_filter_query(self): a = filter_query('https://test.com') self.assertEqual(a, 'https://test.com') a = filter_query('https://test.com?test=abcd&utm_thing=goaway') self.assertEqual(a, 'https://test.com?test=abcd') a = filter_query('https://www.amazon.com/Minions-Super-Size-Blaster-Sounds-Realistic/dp/B082G4ZZWH/ref=dp_fod_1?pd_rd_i=B082G4ZZWH&psc=1') self.assertEqual(a, 'https://www.amazon.com/Minions-Super-Size-Blaster-Sounds-Realistic/dp/B082G4ZZWH') # TODO: decide how best to test the rest of these def test_store_url(self): import tempfile path = os.path.join(tempfile.gettempdir(), 'testing-dbutils-sqlite.db') db = connect(str(path)) db.close() os.unlink(str(path)) return def test_get_urls(self): import tempfile path = os.path.join(tempfile.gettempdir(), 'testing-dbutils-sqlite.db') db = connect(str(path)) db.close() os.unlink(str(path)) return def test_set_karma(self): import tempfile path = os.path.join(tempfile.gettempdir(), 'testing-dbutils-sqlite.db') db = connect(str(path)) db.close() os.unlink(str(path)) return def test_get_karma(self): import tempfile path = os.path.join(tempfile.gettempdir(), 'testing-dbutils-sqlite.db') db = connect(str(path)) db.close() os.unlink(str(path)) return if __name__ == "__main__": unittest.main()
29.491736
146
0.593667
fcb72d7db73df5923c991fc1da23a93973eeb2b4
589
dart
Dart
lib/src/api/model/connect/settings_payouts_schedule.dart
DeadBryam/stripe-dart
3b15e1f07329e75bb795cb6930c957096bd0543d
[ "MIT" ]
8
2020-08-20T06:49:39.000Z
2021-04-27T17:20:51.000Z
lib/src/api/model/connect/settings_payouts_schedule.dart
DeadBryam/stripe-dart
3b15e1f07329e75bb795cb6930c957096bd0543d
[ "MIT" ]
6
2020-05-25T15:44:41.000Z
2021-02-22T18:35:17.000Z
lib/src/api/model/connect/settings_payouts_schedule.dart
DeadBryam/stripe-dart
3b15e1f07329e75bb795cb6930c957096bd0543d
[ "MIT" ]
6
2020-07-15T22:41:42.000Z
2021-12-13T17:39:32.000Z
import 'package:json_annotation/json_annotation.dart'; part 'settings_payouts_schedule.g.dart'; @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) class SettingsPayoutsSchedule { int? delayDays; String? interval; int? monthlyAnchor; String? weeklyAnchor; SettingsPayoutsSchedule( {this.delayDays, this.interval, this.monthlyAnchor, this.weeklyAnchor}); factory SettingsPayoutsSchedule.fromJson(Map<String, dynamic> json) => _$SettingsPayoutsScheduleFromJson(json); Map<String, dynamic> toJson() => _$SettingsPayoutsScheduleToJson(this); }
32.722222
78
0.782683
2a8ea255e03078fb2f3c8e73ed2cd777e02330e2
2,335
java
Java
src/model/Book.java
Arique69/perpustakaan-pbo
63db2fcd2b770f0ab9a388c239bd9b6407c2f666
[ "MIT" ]
null
null
null
src/model/Book.java
Arique69/perpustakaan-pbo
63db2fcd2b770f0ab9a388c239bd9b6407c2f666
[ "MIT" ]
null
null
null
src/model/Book.java
Arique69/perpustakaan-pbo
63db2fcd2b770f0ab9a388c239bd9b6407c2f666
[ "MIT" ]
1
2020-08-29T09:47:10.000Z
2020-08-29T09:47:10.000Z
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; /** * * @author ganjarggt */ public class Book { private String title, author, publisher, bookCode, category, status; public Book(){ } public Book(String bookCode, String status){ this.bookCode = bookCode; this.status = status; } public Book(String bookCode, String title, String author, String publisher, String category){ this.title = title; this.author = author; this.publisher = publisher; this.bookCode = bookCode; this.category = category; } public Book(String bookCode, String title, String author, String publisher, String category, String status){ this.title = title; this.author = author; this.publisher = publisher; this.bookCode = bookCode; this.category = category; this.status = status; } public Book(String bookCode){ this.bookCode = bookCode; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public void setPublisher(String publisher){ this.publisher = publisher; } public String getPublisher(){ return publisher; } public void setBookCode(String bookCode){ this.bookCode = bookCode; } public String getBookCode(){ return this.bookCode; } public void setBookCategory(String category){ this.category = category; } public String getBookCategory(){ return this.category; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
23.35
113
0.577302
2a3852c588d3a5d6388f0be20e8774e19ae14616
415
java
Java
TimoCloud-API/src/main/java/cloud/timo/TimoCloud/api/events/proxyGroup/ProxyGroupProxyChooseStrategyChangeEvent.java
TheMagBum/TimoCloud
fdae67efe288be6bbcab260932f273910268f8f2
[ "BSD-3-Clause" ]
123
2018-02-24T17:41:31.000Z
2022-03-13T18:54:43.000Z
TimoCloud-API/src/main/java/cloud/timo/TimoCloud/api/events/proxyGroup/ProxyGroupProxyChooseStrategyChangeEvent.java
TheMagBum/TimoCloud
fdae67efe288be6bbcab260932f273910268f8f2
[ "BSD-3-Clause" ]
86
2018-02-24T16:55:29.000Z
2022-01-24T20:10:41.000Z
TimoCloud-API/src/main/java/cloud/timo/TimoCloud/api/events/proxyGroup/ProxyGroupProxyChooseStrategyChangeEvent.java
TheMagBum/TimoCloud
fdae67efe288be6bbcab260932f273910268f8f2
[ "BSD-3-Clause" ]
73
2018-02-24T17:05:06.000Z
2022-02-25T19:37:49.000Z
package cloud.timo.TimoCloud.api.events.proxyGroup; import cloud.timo.TimoCloud.api.events.Event; import cloud.timo.TimoCloud.api.objects.ProxyChooseStrategy; import cloud.timo.TimoCloud.api.objects.ProxyGroupObject; public interface ProxyGroupProxyChooseStrategyChangeEvent extends Event { ProxyGroupObject getProxyGroup(); ProxyChooseStrategy getOldValue(); ProxyChooseStrategy getNewValue(); }
25.9375
73
0.821687
f02c314c5aaf915e5619ee218d99196ba7494309
184
js
JavaScript
modal/node_modules/axe-core/lib/checks/label/implicit.js
maze-runnar/modal-component
bb4a146b0473d3524552e379d5bbdbfcca49e6be
[ "MIT" ]
6
2020-09-04T23:52:01.000Z
2021-05-02T10:10:37.000Z
modal/node_modules/axe-core/lib/checks/label/implicit.js
maze-runnar/modal-component
bb4a146b0473d3524552e379d5bbdbfcca49e6be
[ "MIT" ]
32
2020-11-14T03:41:58.000Z
2022-02-27T10:44:09.000Z
modal/node_modules/axe-core/lib/checks/label/implicit.js
maze-runnar/modal-component
bb4a146b0473d3524552e379d5bbdbfcca49e6be
[ "MIT" ]
5
2020-10-12T11:46:25.000Z
2022-02-21T07:09:41.000Z
const { dom, text } = axe.commons; var label = dom.findUpVirtual(virtualNode, 'label'); if (label) { return !!text.accessibleText(label, { inControlContext: true }); } return false;
23
65
0.701087
9390581ae6ee0c07e3edf882139e0ebcc168a3ba
29,707
rs
Rust
system-node/core/pvf-checker/src/tests.rs
elexeum/elexeum-node
19e350dff9b4c790fe6746773007d3250a5a9b2e
[ "Apache-2.0" ]
1
2022-03-23T06:29:04.000Z
2022-03-23T06:29:04.000Z
system-node/core/pvf-checker/src/tests.rs
elexeum/elexeum-node
19e350dff9b4c790fe6746773007d3250a5a9b2e
[ "Apache-2.0" ]
null
null
null
system-node/core/pvf-checker/src/tests.rs
elexeum/elexeum-node
19e350dff9b4c790fe6746773007d3250a5a9b2e
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Parity Technologies (UK) Ltd. // This file is part of Polkadot. // Polkadot 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. // Polkadot 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 Polkadot. If not, see <http://www.gnu.org/licenses/>. use ::test_helpers::{dummy_digest, dummy_hash}; use futures::{channel::oneshot, future::BoxFuture, prelude::*}; use elexeum_node_subsystem::{ jaeger, messages::{ AllMessages, CandidateValidationMessage, PreCheckOutcome, PvfCheckerMessage, RuntimeApiMessage, RuntimeApiRequest, }, ActivatedLeaf, ActiveLeavesUpdate, FromOverseer, LeafStatus, OverseerSignal, RuntimeApiError, }; use elexeum_node_subsystem_test_helpers::{make_subsystem_context, TestSubsystemContextHandle}; use elexeum_primitives::{ v1::{ BlockNumber, Hash, Header, SessionIndex, ValidationCode, ValidationCodeHash, ValidatorId, }, v2::PvfCheckStatement, }; use sp_application_crypto::AppKey; use sp_core::testing::TaskExecutor; use sp_keyring::Sr25519Keyring; use sp_keystore::SyncCryptoStore; use sp_runtime::traits::AppVerify; use std::{collections::HashMap, sync::Arc, time::Duration}; type VirtualOverseer = TestSubsystemContextHandle<PvfCheckerMessage>; fn dummy_validation_code_hash(descriminator: u8) -> ValidationCodeHash { ValidationCode(vec![descriminator]).hash() } struct StartsNewSession { session_index: SessionIndex, validators: Vec<Sr25519Keyring>, } #[derive(Debug, Clone)] struct FakeLeaf { block_hash: Hash, block_number: BlockNumber, pvfs: Vec<ValidationCodeHash>, } impl FakeLeaf { fn new(parent_hash: Hash, block_number: BlockNumber, pvfs: Vec<ValidationCodeHash>) -> Self { let block_header = Header { parent_hash, number: block_number, digest: dummy_digest(), state_root: dummy_hash(), extrinsics_root: dummy_hash(), }; let block_hash = block_header.hash(); Self { block_hash, block_number, pvfs } } fn descendant(&self, pvfs: Vec<ValidationCodeHash>) -> FakeLeaf { FakeLeaf::new(self.block_hash, self.block_number + 1, pvfs) } } struct LeafState { /// The session index at which this leaf was activated. session_index: SessionIndex, /// The list of PVFs that are pending in this leaf. pvfs: Vec<ValidationCodeHash>, } /// The state we model about a session. struct SessionState { validators: Vec<ValidatorId>, } struct TestState { leaves: HashMap<Hash, LeafState>, sessions: HashMap<SessionIndex, SessionState>, last_session_index: SessionIndex, } const OUR_VALIDATOR: Sr25519Keyring = Sr25519Keyring::Alice; fn validator_pubkeys(val_ids: &[Sr25519Keyring]) -> Vec<ValidatorId> { val_ids.iter().map(|v| v.public().into()).collect() } impl TestState { fn new() -> Self { // Initialize the default session 1. No validators are present there. let last_session_index = 1; let mut sessions = HashMap::new(); sessions.insert(last_session_index, SessionState { validators: vec![] }); let mut leaves = HashMap::new(); leaves.insert(dummy_hash(), LeafState { session_index: last_session_index, pvfs: vec![] }); Self { leaves, sessions, last_session_index } } /// A convenience function to receive a message from the overseer and returning `None` if nothing /// was received within a reasonable (for local tests anyway) timeout. async fn recv_timeout(&mut self, handle: &mut VirtualOverseer) -> Option<AllMessages> { futures::select! { msg = handle.recv().fuse() => { Some(msg) } _ = futures_timer::Delay::new(Duration::from_millis(500)).fuse() => { None } } } async fn send_conclude(&mut self, handle: &mut VirtualOverseer) { // To ensure that no messages are left in the queue there is no better way to just wait. match self.recv_timeout(handle).await { Some(msg) => { panic!("we supposed to conclude, but received a message: {:#?}", msg); }, None => { // No messages are received. We are good. }, } handle.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } /// Convenience function to invoke [`active_leaves_update`] with the new leaf that starts a new /// session and there are no deactivated leaves. /// /// Returns the block hash of the newly activated leaf. async fn activate_leaf_with_session( &mut self, handle: &mut VirtualOverseer, leaf: FakeLeaf, starts_new_session: StartsNewSession, ) { self.active_leaves_update(handle, Some(leaf), Some(starts_new_session), &[]) .await } /// Convenience function to invoke [`active_leaves_update`] with a new leaf. The leaf does not /// start a new session and there are no deactivated leaves. async fn activate_leaf(&mut self, handle: &mut VirtualOverseer, leaf: FakeLeaf) { self.active_leaves_update(handle, Some(leaf), None, &[]).await } async fn deactive_leaves( &mut self, handle: &mut VirtualOverseer, deactivated: impl IntoIterator<Item = &Hash>, ) { self.active_leaves_update(handle, None, None, deactivated).await } /// Sends an `ActiveLeavesUpdate` message to the overseer and also updates the test state to /// record leaves and session changes. /// /// NOTE: This function may stall if there is an unhandled message for the overseer. async fn active_leaves_update( &mut self, handle: &mut VirtualOverseer, fake_leaf: Option<FakeLeaf>, starts_new_session: Option<StartsNewSession>, deactivated: impl IntoIterator<Item = &Hash>, ) { if let Some(new_session) = starts_new_session { assert!(fake_leaf.is_some(), "Session can be started only with an activated leaf"); self.last_session_index = new_session.session_index; let prev = self.sessions.insert( new_session.session_index, SessionState { validators: validator_pubkeys(&new_session.validators) }, ); assert!(prev.is_none(), "Session {} already exists", new_session.session_index); } let activated = if let Some(activated_leaf) = fake_leaf { self.leaves.insert( activated_leaf.block_hash.clone(), LeafState { session_index: self.last_session_index, pvfs: activated_leaf.pvfs.clone(), }, ); Some(ActivatedLeaf { hash: activated_leaf.block_hash, span: Arc::new(jaeger::Span::Disabled), number: activated_leaf.block_number, status: LeafStatus::Fresh, }) } else { None }; handle .send(FromOverseer::Signal(OverseerSignal::ActiveLeaves(ActiveLeavesUpdate { activated, deactivated: deactivated.into_iter().cloned().collect(), }))) .await; } /// Expects that the subsystem has sent a `Validators` Runtime API request. Answers with the /// mocked validators for the requested leaf. async fn expect_validators(&mut self, handle: &mut VirtualOverseer) { match self.recv_timeout(handle).await.expect("timeout waiting for a message") { AllMessages::RuntimeApi(RuntimeApiMessage::Request( relay_parent, RuntimeApiRequest::Validators(tx), )) => match self.leaves.get(&relay_parent) { Some(leaf) => { let session_index = leaf.session_index; let session = self.sessions.get(&session_index).unwrap(); tx.send(Ok(session.validators.clone())).unwrap(); }, None => { panic!("a request to an unknown relay parent has been made"); }, }, msg => panic!("Unexpected message was received: {:#?}", msg), } } /// Expects that the subsystem has sent a `SessionIndexForChild` Runtime API request. Answers /// with the mocked session index for the requested leaf. async fn expect_session_for_child(&mut self, handle: &mut VirtualOverseer) { match self.recv_timeout(handle).await.expect("timeout waiting for a message") { AllMessages::RuntimeApi(RuntimeApiMessage::Request( relay_parent, RuntimeApiRequest::SessionIndexForChild(tx), )) => match self.leaves.get(&relay_parent) { Some(leaf) => { tx.send(Ok(leaf.session_index)).unwrap(); }, None => { panic!("a request to an unknown relay parent has been made"); }, }, msg => panic!("Unexpected message was received: {:#?}", msg), } } /// Expects that the subsystem has sent a `PvfsRequirePrecheck` Runtime API request. Answers /// with the mocked PVF set for the requested leaf. async fn expect_pvfs_require_precheck( &mut self, handle: &mut VirtualOverseer, ) -> ExpectPvfsRequirePrecheck<'_> { match self.recv_timeout(handle).await.expect("timeout waiting for a message") { AllMessages::RuntimeApi(RuntimeApiMessage::Request( relay_parent, RuntimeApiRequest::PvfsRequirePrecheck(tx), )) => ExpectPvfsRequirePrecheck { test_state: self, relay_parent, tx }, msg => panic!("Unexpected message was received: {:#?}", msg), } } /// Expects that the subsystem has sent a pre-checking request to candidate-validation. Returns /// a mocked handle for the request. async fn expect_candidate_precheck( &mut self, handle: &mut VirtualOverseer, ) -> ExpectCandidatePrecheck { match self.recv_timeout(handle).await.expect("timeout waiting for a message") { AllMessages::CandidateValidation(CandidateValidationMessage::PreCheck( relay_parent, validation_code_hash, tx, )) => ExpectCandidatePrecheck { relay_parent, validation_code_hash, tx }, msg => panic!("Unexpected message was received: {:#?}", msg), } } /// Expects that the subsystem has sent a `SubmitPvfCheckStatement` runtime API request. Returns /// a mocked handle for the request. async fn expect_submit_vote(&mut self, handle: &mut VirtualOverseer) -> ExpectSubmitVote { match self.recv_timeout(handle).await.expect("timeout waiting for a message") { AllMessages::RuntimeApi(RuntimeApiMessage::Request( relay_parent, RuntimeApiRequest::SubmitPvfCheckStatement(stmt, signature, tx), )) => { let signing_payload = stmt.signing_payload(); assert!(signature.verify(&signing_payload[..], &OUR_VALIDATOR.public().into())); ExpectSubmitVote { relay_parent, stmt, tx } }, msg => panic!("Unexpected message was received: {:#?}", msg), } } } #[must_use] struct ExpectPvfsRequirePrecheck<'a> { test_state: &'a mut TestState, relay_parent: Hash, tx: oneshot::Sender<Result<Vec<ValidationCodeHash>, RuntimeApiError>>, } impl<'a> ExpectPvfsRequirePrecheck<'a> { fn reply_mock(self) { match self.test_state.leaves.get(&self.relay_parent) { Some(leaf) => { self.tx.send(Ok(leaf.pvfs.clone())).unwrap(); }, None => { panic!( "a request to an unknown relay parent has been made: {:#?}", self.relay_parent ); }, } } fn reply_not_supported(self) { self.tx .send(Err(RuntimeApiError::NotSupported { runtime_api_name: "pvfs_require_precheck" })) .unwrap(); } } #[must_use] struct ExpectCandidatePrecheck { relay_parent: Hash, validation_code_hash: ValidationCodeHash, tx: oneshot::Sender<PreCheckOutcome>, } impl ExpectCandidatePrecheck { fn reply(self, outcome: PreCheckOutcome) { self.tx.send(outcome).unwrap(); } } #[must_use] struct ExpectSubmitVote { relay_parent: Hash, stmt: PvfCheckStatement, tx: oneshot::Sender<Result<(), RuntimeApiError>>, } impl ExpectSubmitVote { fn reply_ok(self) { self.tx.send(Ok(())).unwrap(); } } fn test_harness(test: impl FnOnce(TestState, VirtualOverseer) -> BoxFuture<'static, ()>) { let pool = TaskExecutor::new(); let (ctx, handle) = make_subsystem_context::<PvfCheckerMessage, _>(pool.clone()); let keystore = Arc::new(sc_keystore::LocalKeystore::in_memory()); // Add OUR_VALIDATOR (which is Alice) to the keystore. SyncCryptoStore::sr25519_generate_new( &*keystore, ValidatorId::ID, Some(&OUR_VALIDATOR.to_seed()), ) .expect("Generating keys for our node failed"); let subsystem_task = crate::run(ctx, keystore, crate::Metrics::default()).map(|x| x.unwrap()); let test_state = TestState::new(); let test_task = test(test_state, handle); futures::executor::block_on(future::join(subsystem_task, test_task)); } #[test] fn concludes_correctly() { test_harness(|mut test_state, mut handle| { async move { test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn reacts_to_new_pvfs_in_heads() { test_harness(|mut test_state, mut handle| { async move { let block = FakeLeaf::new(dummy_hash(), 1, vec![dummy_validation_code_hash(1)]); test_state .activate_leaf_with_session( &mut handle, block.clone(), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; let pre_check = test_state.expect_candidate_precheck(&mut handle).await; assert_eq!(pre_check.relay_parent, block.block_hash); pre_check.reply(PreCheckOutcome::Valid); let vote = test_state.expect_submit_vote(&mut handle).await; assert_eq!(vote.relay_parent, block.block_hash); assert_eq!(vote.stmt.accept, true); assert_eq!(vote.stmt.session_index, 2); assert_eq!(vote.stmt.validator_index, 0.into()); assert_eq!(vote.stmt.subject, dummy_validation_code_hash(1)); vote.reply_ok(); test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn no_new_session_no_validators_request() { test_harness(|mut test_state, mut handle| { async move { test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 1, vec![]), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; test_state .activate_leaf(&mut handle, FakeLeaf::new(dummy_hash(), 2, vec![])) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn activation_of_descendant_leaves_pvfs_in_view() { test_harness(|mut test_state, mut handle| { async move { let block_1 = FakeLeaf::new(dummy_hash(), 1, vec![dummy_validation_code_hash(1)]); let block_2 = block_1.descendant(vec![dummy_validation_code_hash(1)]); test_state .activate_leaf_with_session( &mut handle, block_1.clone(), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; test_state .expect_candidate_precheck(&mut handle) .await .reply(PreCheckOutcome::Valid); test_state.expect_submit_vote(&mut handle).await.reply_ok(); // Now we deactivate the first block and activate it's descendant. test_state .active_leaves_update( &mut handle, Some(block_2), None, // no new session started &[block_1.block_hash], ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn reactivating_pvf_leads_to_second_check() { test_harness(|mut test_state, mut handle| { async move { let pvf = dummy_validation_code_hash(1); let block_1 = FakeLeaf::new(dummy_hash(), 1, vec![pvf.clone()]); let block_2 = block_1.descendant(vec![]); let block_3 = block_2.descendant(vec![pvf.clone()]); test_state .activate_leaf_with_session( &mut handle, block_1.clone(), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; test_state .expect_candidate_precheck(&mut handle) .await .reply(PreCheckOutcome::Valid); test_state.expect_submit_vote(&mut handle).await.reply_ok(); // Now activate a descdedant leaf, where the PVF is not present. test_state .active_leaves_update( &mut handle, Some(block_2.clone()), None, &[block_1.block_hash], ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; // Now the third block is activated, where the PVF is present. test_state.activate_leaf(&mut handle, block_3).await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state .expect_candidate_precheck(&mut handle) .await .reply(PreCheckOutcome::Valid); // We do not vote here, because the PVF was already voted on within this session. test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn dont_double_vote_for_pvfs_in_view() { test_harness(|mut test_state, mut handle| { async move { let pvf = dummy_validation_code_hash(1); let block_1_1 = FakeLeaf::new([1; 32].into(), 1, vec![pvf.clone()]); let block_2_1 = FakeLeaf::new([2; 32].into(), 1, vec![pvf.clone()]); let block_1_2 = block_1_1.descendant(vec![pvf.clone()]); test_state .activate_leaf_with_session( &mut handle, block_1_1.clone(), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; // Pre-checking will take quite some time. let pre_check = test_state.expect_candidate_precheck(&mut handle).await; // Activate a sibiling leaf, has the same PVF. test_state.activate_leaf(&mut handle, block_2_1).await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; // Now activate a descendant leaf with the same PVF. test_state .active_leaves_update( &mut handle, Some(block_1_2.clone()), None, &[block_1_1.block_hash], ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; // Now finish the pre-checking request. pre_check.reply(PreCheckOutcome::Valid); test_state.expect_submit_vote(&mut handle).await.reply_ok(); test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn judgements_come_out_of_order() { test_harness(|mut test_state, mut handle| { async move { let pvf_1 = dummy_validation_code_hash(1); let pvf_2 = dummy_validation_code_hash(2); let block_1 = FakeLeaf::new([1; 32].into(), 1, vec![pvf_1.clone()]); let block_2 = FakeLeaf::new([2; 32].into(), 1, vec![pvf_2.clone()]); test_state .activate_leaf_with_session( &mut handle, block_1.clone(), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; let pre_check_1 = test_state.expect_candidate_precheck(&mut handle).await; // Activate a sibiling leaf, has the second PVF. test_state.activate_leaf(&mut handle, block_2).await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; let pre_check_2 = test_state.expect_candidate_precheck(&mut handle).await; // Resolve the PVF pre-checks out of order. pre_check_2.reply(PreCheckOutcome::Valid); pre_check_1.reply(PreCheckOutcome::Invalid); // Catch the vote for the second PVF. let vote_2 = test_state.expect_submit_vote(&mut handle).await; assert_eq!(vote_2.stmt.accept, true); assert_eq!(vote_2.stmt.subject, pvf_2.clone()); vote_2.reply_ok(); // Catch the vote for the first PVF. let vote_1 = test_state.expect_submit_vote(&mut handle).await; assert_eq!(vote_1.stmt.accept, false); assert_eq!(vote_1.stmt.subject, pvf_1.clone()); vote_1.reply_ok(); test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn dont_vote_until_a_validator() { test_harness(|mut test_state, mut handle| { async move { test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 1, vec![dummy_validation_code_hash(1)]), StartsNewSession { session_index: 2, validators: vec![Sr25519Keyring::Bob] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; test_state .expect_candidate_precheck(&mut handle) .await .reply(PreCheckOutcome::Invalid); // Now a leaf brings a new session. In this session our validator comes into the active // set. That means it will cast a vote for each judgement it has. test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 2, vec![dummy_validation_code_hash(1)]), StartsNewSession { session_index: 3, validators: vec![Sr25519Keyring::Bob, OUR_VALIDATOR], }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; let vote = test_state.expect_submit_vote(&mut handle).await; assert_eq!(vote.stmt.accept, false); assert_eq!(vote.stmt.session_index, 3); assert_eq!(vote.stmt.validator_index, 1.into()); assert_eq!(vote.stmt.subject, dummy_validation_code_hash(1)); vote.reply_ok(); test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn resign_on_session_change() { test_harness(|mut test_state, mut handle| { async move { let pvf_1 = dummy_validation_code_hash(1); let pvf_2 = dummy_validation_code_hash(2); test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 1, vec![pvf_1, pvf_2]), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; let pre_check_1 = test_state.expect_candidate_precheck(&mut handle).await; assert_eq!(pre_check_1.validation_code_hash, pvf_1); pre_check_1.reply(PreCheckOutcome::Valid); let pre_check_2 = test_state.expect_candidate_precheck(&mut handle).await; assert_eq!(pre_check_2.validation_code_hash, pvf_2); pre_check_2.reply(PreCheckOutcome::Invalid); test_state.expect_submit_vote(&mut handle).await.reply_ok(); test_state.expect_submit_vote(&mut handle).await.reply_ok(); // So far so good. Now we change the session. test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 2, vec![pvf_1, pvf_2]), StartsNewSession { session_index: 3, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; // The votes should be re-signed and re-submitted. let mut statements = Vec::new(); let vote_1 = test_state.expect_submit_vote(&mut handle).await; statements.push(vote_1.stmt.clone()); vote_1.reply_ok(); let vote_2 = test_state.expect_submit_vote(&mut handle).await; statements.push(vote_2.stmt.clone()); vote_2.reply_ok(); // Find and check the votes. // Unfortunately, the order of revoting is not deterministic so we have to resort to // a bit of trickery. assert_eq!(statements.iter().find(|s| s.subject == pvf_1).unwrap().accept, true); assert_eq!(statements.iter().find(|s| s.subject == pvf_2).unwrap().accept, false); test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn dont_resign_if_not_us() { test_harness(|mut test_state, mut handle| { async move { let pvf_1 = dummy_validation_code_hash(1); let pvf_2 = dummy_validation_code_hash(2); test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 1, vec![pvf_1, pvf_2]), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; let pre_check_1 = test_state.expect_candidate_precheck(&mut handle).await; assert_eq!(pre_check_1.validation_code_hash, pvf_1); pre_check_1.reply(PreCheckOutcome::Valid); let pre_check_2 = test_state.expect_candidate_precheck(&mut handle).await; assert_eq!(pre_check_2.validation_code_hash, pvf_2); pre_check_2.reply(PreCheckOutcome::Invalid); test_state.expect_submit_vote(&mut handle).await.reply_ok(); test_state.expect_submit_vote(&mut handle).await.reply_ok(); // So far so good. Now we change the session. test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 2, vec![pvf_1, pvf_2]), StartsNewSession { session_index: 3, // not us validators: vec![Sr25519Keyring::Bob], }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; // We do not expect any votes to be re-signed. test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn api_not_supported() { test_harness(|mut test_state, mut handle| { async move { test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 1, vec![dummy_validation_code_hash(1)]), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_not_supported(); test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn not_supported_api_becomes_supported() { test_harness(|mut test_state, mut handle| { async move { test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 1, vec![dummy_validation_code_hash(1)]), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_not_supported(); test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 1, vec![dummy_validation_code_hash(1)]), StartsNewSession { session_index: 3, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; test_state .expect_candidate_precheck(&mut handle) .await .reply(PreCheckOutcome::Valid); test_state.expect_submit_vote(&mut handle).await.reply_ok(); test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn unexpected_pvf_check_judgement() { test_harness(|mut test_state, mut handle| { async move { let block_1 = FakeLeaf::new(dummy_hash(), 1, vec![dummy_validation_code_hash(1)]); test_state .activate_leaf_with_session( &mut handle, block_1.clone(), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; // Catch the pre-check request, but don't reply just yet. let pre_check = test_state.expect_candidate_precheck(&mut handle).await; // Now deactive the leaf and reply to the precheck request. test_state.deactive_leaves(&mut handle, &[block_1.block_hash]).await; pre_check.reply(PreCheckOutcome::Invalid); // the subsystem must remain silent. test_state.send_conclude(&mut handle).await; } .boxed() }); } #[test] fn abstain_for_nondeterministic_pvfcheck_failure() { test_harness(|mut test_state, mut handle| { async move { test_state .activate_leaf_with_session( &mut handle, FakeLeaf::new(dummy_hash(), 1, vec![dummy_validation_code_hash(1)]), StartsNewSession { session_index: 2, validators: vec![OUR_VALIDATOR] }, ) .await; test_state.expect_pvfs_require_precheck(&mut handle).await.reply_mock(); test_state.expect_session_for_child(&mut handle).await; test_state.expect_validators(&mut handle).await; test_state .expect_candidate_precheck(&mut handle) .await .reply(PreCheckOutcome::Failed); test_state.send_conclude(&mut handle).await; } .boxed() }); }
31.704376
98
0.719292
5cbad5a4ef516c07ff418d29fce91b6b62fcbfc7
504
lua
Lua
src/app/objects/gameplay/level/environment/logic/checkpoint.lua
Greentwip/WhateverTheFuck
8fb922bd1acf598f8ff273a78a160f4e19c635ad
[ "MIT" ]
1
2015-09-24T12:48:29.000Z
2015-09-24T12:48:29.000Z
src/app/objects/gameplay/level/environment/logic/checkpoint.lua
Greentwip/WhateverTheFuck
8fb922bd1acf598f8ff273a78a160f4e19c635ad
[ "MIT" ]
null
null
null
src/app/objects/gameplay/level/environment/logic/checkpoint.lua
Greentwip/WhateverTheFuck
8fb922bd1acf598f8ff273a78a160f4e19c635ad
[ "MIT" ]
null
null
null
-- Copyright 2014-2015 Greentwip. All Rights Reserved. local block = import("app.objects.gameplay.level.environment.core.block") local checkpoint = class("checkpoint", block) function checkpoint:ctor(position, size) self:setup(position, size) self:getPhysicsBody():getShapes()[1]:setTag(cc.tags.check_point) end function checkpoint:prepare(raw_element) if raw_element.type == "first" then self.type_ = cc.tags.logic.check_point.first_ end return self end return checkpoint
22.909091
73
0.748016
8348ba7b1a32d0208cae2080b70788a45ad3c343
183
sql
SQL
HousingManager.DB/HousingManager.DB.SqlServer/Batch/BatchType.sql
revaturelabs/housing-manager
a27258dff42f9053735b57cd985db47415b59520
[ "MIT" ]
null
null
null
HousingManager.DB/HousingManager.DB.SqlServer/Batch/BatchType.sql
revaturelabs/housing-manager
a27258dff42f9053735b57cd985db47415b59520
[ "MIT" ]
null
null
null
HousingManager.DB/HousingManager.DB.SqlServer/Batch/BatchType.sql
revaturelabs/housing-manager
a27258dff42f9053735b57cd985db47415b59520
[ "MIT" ]
null
null
null
create table Batch.BatchType( BatchTypeId int primary key clustered IDENTITY(1,1) not null, Type nvarchar(50) not null, [Guid] UNIQUEIDENTIFIER DEFAULT NEWID() not null );
36.6
66
0.737705
fbba0a97507a77c32bd2a7cb3468eec5d657c9c2
2,236
h
C
media/capture/video/chromeos/mock_camera_module.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/capture/video/chromeos/mock_camera_module.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/capture/video/chromeos/mock_camera_module.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_CAPTURE_VIDEO_CHROMEOS_MOCK_CAMERA_MODULE_H_ #define MEDIA_CAPTURE_VIDEO_CHROMEOS_MOCK_CAMERA_MODULE_H_ #include <stddef.h> #include <stdint.h> #include "base/threading/thread.h" #include "media/capture/video/chromeos/mojo/arc_camera3.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "testing/gmock/include/gmock/gmock.h" namespace media { namespace unittest_internal { class MockCameraModule : public arc::mojom::CameraModule { public: MockCameraModule(); ~MockCameraModule(); void OpenDevice(int32_t camera_id, arc::mojom::Camera3DeviceOpsRequest device_ops_request, OpenDeviceCallback callback) override; MOCK_METHOD3(DoOpenDevice, void(int32_t camera_id, arc::mojom::Camera3DeviceOpsRequest& device_ops_request, OpenDeviceCallback& callback)); void GetNumberOfCameras(GetNumberOfCamerasCallback callback) override; MOCK_METHOD1(DoGetNumberOfCameras, void(GetNumberOfCamerasCallback& callback)); void GetCameraInfo(int32_t camera_id, GetCameraInfoCallback callback) override; MOCK_METHOD2(DoGetCameraInfo, void(int32_t camera_id, GetCameraInfoCallback& callback)); void SetCallbacks(arc::mojom::CameraModuleCallbacksPtr callbacks, SetCallbacksCallback callback) override; MOCK_METHOD2(DoSetCallbacks, void(arc::mojom::CameraModuleCallbacksPtr& callbacks, SetCallbacksCallback& callback)); arc::mojom::CameraModulePtrInfo GetInterfacePtrInfo(); private: void CloseBindingOnThread(); void BindOnThread(base::WaitableEvent* done, arc::mojom::CameraModulePtrInfo* ptr_info); base::Thread mock_module_thread_; mojo::Binding<arc::mojom::CameraModule> binding_; arc::mojom::CameraModuleCallbacksPtr callbacks_; DISALLOW_COPY_AND_ASSIGN(MockCameraModule); }; } // namespace unittest_internal } // namespace media #endif // MEDIA_CAPTURE_VIDEO_CHROMEOS_MOCK_CAMERA_MODULE_H_
33.373134
76
0.7339
292924b8a9afed3122d104fc8674aeec7034734c
16,127
py
Python
sphinxcontrib/needs/services/github.py
twodrops/sphinxcontrib-needs
c2081bd499fe7d36840d29ca3fb05c80e7bf2284
[ "MIT" ]
null
null
null
sphinxcontrib/needs/services/github.py
twodrops/sphinxcontrib-needs
c2081bd499fe7d36840d29ca3fb05c80e7bf2284
[ "MIT" ]
null
null
null
sphinxcontrib/needs/services/github.py
twodrops/sphinxcontrib-needs
c2081bd499fe7d36840d29ca3fb05c80e7bf2284
[ "MIT" ]
null
null
null
import os import requests import textwrap import time from urllib.parse import urlparse from sphinxcontrib.needs.api import add_need_type from sphinxcontrib.needs.api.exceptions import NeedsApiConfigException from sphinxcontrib.needs.services.base import BaseService # Additional needed options, which are not defined by default EXTRA_DATA_OPTIONS = ['user', 'created_at', 'updated_at', 'closed_at', 'service'] EXTRA_LINK_OPTIONS = ['url'] EXTRA_IMAGE_OPTIONS = ['avatar'] # Additional options, which are used to configure the service and shall not be part of the later needs CONFIG_OPTIONS = ['type', 'query', 'specific', 'max_amount', 'max_content_lines', 'id_prefix'] # All Github related data options GITHUB_DATA = ['status', 'tags'] + EXTRA_DATA_OPTIONS + EXTRA_LINK_OPTIONS + EXTRA_IMAGE_OPTIONS # Needed for layout. Example: "user","avatar",... GITHUB_DATA_STR = '"' + '","'.join(EXTRA_DATA_OPTIONS + EXTRA_LINK_OPTIONS + EXTRA_IMAGE_OPTIONS) + '"' CONFIG_DATA_STR = '"' + '","'.join(CONFIG_OPTIONS) + '"' GITHUB_LAYOUT = { 'grid': 'complex', 'layout': { 'head_left': [ '<<meta_id()>>', '<<collapse_button("meta,footer", collapsed="icon:arrow-down-circle", ' 'visible="icon:arrow-right-circle", initial=True)>>' ], 'head': ['**<<meta("title")>>** (' + ", ".join(['<<link("{value}", text="{value}", is_dynamic=True)>>'.format(value=x) for x in EXTRA_LINK_OPTIONS]) + ')'], 'head_right': [ '<<image("field:avatar", width="40px", align="middle")>>', '<<meta("user")>>' ], 'meta_left': ['<<meta("{value}", prefix="{value}: ")>>'.format(value=x) for x in EXTRA_DATA_OPTIONS] + [ '<<link("{value}", text="Link", prefix="{value}: ", is_dynamic=True)>>'.format(value=x) for x in EXTRA_LINK_OPTIONS], 'meta_right': [ '<<meta("type_name", prefix="type: ")>>', '<<meta_all(no_links=True, exclude=["layout","style",{}, {}])>>'.format(GITHUB_DATA_STR, CONFIG_DATA_STR), '<<meta_links_all()>>' ], 'footer_left': [ 'layout: <<meta("layout")>>', ], 'footer': [ 'service: <<meta("service")>>', ], 'footer_right': [ 'style: <<meta("style")>>' ] } } class GithubService(BaseService): options = CONFIG_OPTIONS + EXTRA_DATA_OPTIONS + EXTRA_LINK_OPTIONS + EXTRA_IMAGE_OPTIONS def __init__(self, app, name, config, **kwargs): self.app = app self.name = name self.config = config self.url = self.config.get('url', 'https://api.github.com/') if self.url[len(self.url)-1] != "/": self.url = self.url + "/" self.max_amount = self.config.get('max_amount', 5) self.max_content_lines = self.config.get('max_content_lines', -1) self.id_prefix = self.config.get('id_prefix', 'GITHUB_') self.layout = self.config.get('layout', 'github') self.download_avatars = self.config.get('download_avatars', True) self.download_folder = self.config.get('download_folder', 'github_images') self.username = self.config.get('username', None) self.token = self.config.get('token', None) if 'github' not in self.app.config.needs_layouts.keys(): self.app.config.needs_layouts['github'] = GITHUB_LAYOUT self.gh_type_config = { 'issue': { 'url': 'search/issues', 'query': 'is:issue', 'need_type': 'issue' }, 'pr': { 'url': 'search/issues', 'query': 'is:pr', 'need_type': 'pr' }, 'commit': { 'url': 'search/commits', 'query': '', 'need_type': 'commit' }, } try: add_need_type(self.app, 'issue', 'Issue', 'IS_', '#cccccc', 'card') except NeedsApiConfigException: pass # Issue already exists, so we are fine try: add_need_type(self.app, 'pr', 'PullRequest', 'PR_', '#aaaaaa', 'card') except NeedsApiConfigException: pass # PR already exists, so we are fine try: add_need_type(self.app, 'commit', 'Commit', 'C_', '#888888', 'card') except NeedsApiConfigException: pass # Commit already exists, so we are fine if 'gh_type' in kwargs: self.gh_type = kwargs['gh_type'] if self.gh_type not in self.gh_type_config.keys(): raise KeyError('github type "{}" not supported. Use: {}'.format( self.gh_type, ", ".join(self.gh_type_config.keys()))) # Set need_type to use by default self.need_type = self.config.get('need_type', self.gh_type_config[self.gh_type]['need_type']) super(GithubService, self).__init__() def _send(self, query, options, specific=False): headers = {} if self.gh_type == 'commit': headers['Accept'] = "application/vnd.github.cloak-preview+json" if not specific: url = self.url + self.gh_type_config[self.gh_type]['url'] query = '{} {}'.format(query, self.gh_type_config[self.gh_type]["query"]) params = { 'q': query, 'per_page': options.get('max_amount', self.max_amount) } else: try: specific_elements = query.split('/') owner = specific_elements[0] repo = specific_elements[1] number = specific_elements[2] if self.gh_type == 'issue': single_type = 'issues' elif self.gh_type == 'pr': single_type = 'pulls' else: single_type = 'commits' url = self.url + 'repos/{owner}/{repo}/{single_type}/{number}'.format( owner=owner, repo=repo, single_type=single_type, number=number) except IndexError: raise NeedGithubServiceException('Single option ot valid, must follow "owner/repo/number"') params = {} self.log.info('Service {} requesting data for query: {}'.format(self.name, query)) if self.username: auth = (self.username, self.token) else: auth = None resp = requests.get(url, params=params, auth=auth, headers=headers) if resp.status_code > 299: extra_info = "" # Lets try to get information about the rate limit, as this is mostly the main problem. if 'rate limit' in resp.json()['message']: resp_limit = requests.get(self.url + 'rate_limit', auth=auth) extra_info = resp_limit.json() self.log.info('GitHub: API rate limit exceeded. We need to wait 60 secs...') self.log.info(extra_info) time.sleep(61) resp = requests.get(url, params=params, auth=auth, headers=headers) if resp.status_code > 299: if 'rate limit' in resp.json()['message']: raise NeedGithubServiceException("GitHub: API rate limit exceeded (twice). Stop here.") else: raise NeedGithubServiceException('Github service error during request.\n' 'Status code: {}\n' 'Error: {}\n' '{}'.format(resp.status_code, resp.text, extra_info)) else: raise NeedGithubServiceException('Github service error during request.\n' 'Status code: {}\n' 'Error: {}\n' '{}'.format(resp.status_code, resp.text, extra_info)) if specific: return {'items': [resp.json()]} return resp.json() def request(self, options=None): if options is None: options = {} self.log.debug('Requesting data for service {}'.format(self.name)) if 'query' not in options and 'specific' not in options: raise NeedGithubServiceException('"query" or "specific" missing as option for github service.') elif 'query' in options and 'specific' in options: raise NeedGithubServiceException('Only "query" or "specific" allowed for github service. Not both!') elif 'query' in options: query = options['query'] specific = False else: query = options['specific'] specific = True response = self._send(query, options, specific=specific) if 'items' not in response.keys(): if 'errors' in response.keys(): raise NeedGithubServiceException('GitHub service query error: {}\n' 'Used query: {}'.format(response["errors"][0]["message"], query)) else: raise NeedGithubServiceException('Github service: Unknown error.') if self.gh_type == 'issue' or self.gh_type == 'pr': data = self.prepare_issue_data(response['items'], options) elif self.gh_type == 'commit': data = self.prepare_commit_data(response['items'], options) else: raise NeedGithubServiceException('Github service failed. Wrong gh_type...') return data def prepare_issue_data(self, items, options): data = [] for item in items: # wraps content lines, if they are too long. Respects already existing newlines. content_lines = ['\n '.join(textwrap.wrap(line, 60, break_long_words=True, replace_whitespace=False)) for line in item["body"].splitlines() if line.strip() != ''] content = '\n\n '.join(content_lines) # Reduce content length, if requested by config if self.max_content_lines > 0: max_lines = int(options.get('max_content_lines', self.max_content_lines)) content_lines = content.splitlines() if len(content_lines) > max_lines: content_lines = content_lines[0:max_lines] content_lines.append('\n [...]\n') # Mark, if content got cut content = '\n'.join(content_lines) # Be sure the content gets not interpreted as rst or html code, so we put # everything in a safe code-block content = '.. code-block:: text\n\n ' + content prefix = options.get('id_prefix', self.id_prefix) need_id = prefix + str(item["number"]) given_tags = options.get('tags', False) github_tags = ",".join([x['name'] for x in item["labels"]]) if given_tags: tags = str(given_tags) + ', ' + str(github_tags) else: tags = github_tags avatar_file_path = self._get_avatar(item["user"]['avatar_url']) element_data = { 'service': self.name, 'type': options.get('type', self.need_type), 'layout': options.get('layout', self.layout), 'id': need_id, 'title': item["title"], 'content': content, 'status': item["state"], 'tags': tags, 'user': item["user"]['login'], 'url': item['html_url'], 'avatar': avatar_file_path, 'created_at': item['created_at'], 'updated_at': item['updated_at'], 'closed_at': item['closed_at'] } self._add_given_options(options, element_data) data.append(element_data) return data def prepare_commit_data(self, items, options): data = [] for item in items: avatar_file_path = self._get_avatar(item["author"]['avatar_url']) element_data = { 'service': self.name, 'type': options.get('type', self.need_type), 'layout': options.get('layout', self.layout), 'id': self.id_prefix + item['sha'][:6], 'title': item['commit']['message'].split('\n')[0][:60], # 1. line, max length 60 chars 'content': item['commit']['message'], 'user': item['author']['login'], 'url': item['html_url'], 'avatar': avatar_file_path, 'created_at': item['commit']['author']['date'] } self._add_given_options(options, element_data) data.append(element_data) return data def _get_avatar(self, avatar_url): """ Download and store avatar image :param avatar_url: :return: """ url_parsed = urlparse(avatar_url) filename = os.path.basename(url_parsed.path) + '.png' path = os.path.join(self.app.srcdir, self.download_folder) avatar_file_path = os.path.join(path, filename) # Placeholder avatar, if things go wrong or avatar download is deactivated default_avatar_file_path = os.path.join(os.path.dirname(__file__), '../images/avatar.png') if self.download_avatars: # Download only, if file not downloaded yet if not os.path.exists(avatar_file_path): try: os.mkdir(path) except FileExistsError: pass if self.username and self.token: auth = (self.username, self.token) else: auth = () response = requests.get(avatar_url, auth=auth, allow_redirects=False) if response.status_code == 200: with open(avatar_file_path, 'wb') as f: f.write(response.content) elif response.status_code == 302: self.log.warning('GitHub service {} could not download avatar image ' 'from {}.\n' ' Status code: {}\n' ' Reason: Looks like the authentication provider tries to redirect you.' ' This is not supported and is a common problem, ' 'if you use GitHub Enterprise.'.format(self.name, avatar_url, response.status_code)) avatar_file_path = default_avatar_file_path else: self.log.warning('GitHub service {} could not download avatar image ' 'from {}.\n' ' Status code: {}'.format(self.name, avatar_url, response.status_code )) avatar_file_path = default_avatar_file_path else: avatar_file_path = default_avatar_file_path return avatar_file_path def _add_given_options(self, options, element_data): """ Add data from options, which was defined by user but is not set by this service :param options: :param element_data: :return: """ for key, value in options.items(): # Check if given option is not already handled and is not part of the service internal options if key not in element_data.keys() and key not in GITHUB_DATA: element_data[key] = value class NeedGithubServiceException(BaseException): pass
42.664021
118
0.529919
6fc57f3abc4da021c1e64c9cb80dced320db8cdf
965
swift
Swift
Examples/Memory/Sources/AlertRoute.swift
Woods99/Boomerang
ec05ba3e4f04ee161995a8c4cb89647195b2ed44
[ "MIT" ]
34
2017-01-04T06:21:06.000Z
2021-06-15T18:53:57.000Z
Examples/Memory/Sources/AlertRoute.swift
Woods99/Boomerang
ec05ba3e4f04ee161995a8c4cb89647195b2ed44
[ "MIT" ]
32
2017-02-15T08:29:59.000Z
2021-12-29T16:57:19.000Z
Examples/Memory/Sources/AlertRoute.swift
Woods99/Boomerang
ec05ba3e4f04ee161995a8c4cb89647195b2ed44
[ "MIT" ]
10
2017-08-13T11:05:17.000Z
2021-12-06T08:36:22.000Z
// // AlertRoute.swift // GameOfFifteen_iOS // // Created by Stefano Mondino on 05/12/21. // import Foundation import Boomerang import UIKit struct AlertRoute: UIKitRoute { struct Action { let title: String let callback: () -> Void } let createViewController: () -> UIViewController? init(title: String, message: String, actions: [Action]) { createViewController = { let controller = UIAlertController(title: title, message: message, preferredStyle: .alert) actions .map { value in .init(title: value.title, style: .default) { _ in value.callback() } } .forEach { controller.addAction($0) } return controller } } func execute<T>(from scene: T?) where T: UIViewController { if let controller = createViewController() { scene?.present(controller, animated: true, completion: nil) } } }
26.081081
102
0.598964
128559effd0f75bfafba3275841ddbb37678b29a
285
h
C
src/ClosestHit.h
szellmann/fakeOwl
f938504b9dbb218aa0aad0b47513cebd79e47e13
[ "MIT" ]
4
2021-05-01T20:53:27.000Z
2021-05-05T00:35:55.000Z
src/ClosestHit.h
szellmann/fakeOwl
f938504b9dbb218aa0aad0b47513cebd79e47e13
[ "MIT" ]
null
null
null
src/ClosestHit.h
szellmann/fakeOwl
f938504b9dbb218aa0aad0b47513cebd79e47e13
[ "MIT" ]
null
null
null
#pragma once #include "Program.h" namespace fake { struct ClosestHit : Program { std::string entryPointPrefix(); int rayType = 0; // Symbol to prepare an intersection program call void* fakePrepareClosestHitSym = nullptr; }; } // fake
15
57
0.617544
26b43fcc8f59efc697072cc7df950db40c6e238a
239
java
Java
com/sun/jna/platform/win32/COM/IStream.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
2
2021-07-16T10:43:25.000Z
2021-12-15T13:54:10.000Z
com/sun/jna/platform/win32/COM/IStream.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
1
2021-10-12T22:24:55.000Z
2021-10-12T22:24:55.000Z
com/sun/jna/platform/win32/COM/IStream.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
null
null
null
package com.sun.jna.platform.win32.COM; public interface IStream {} /* Location: /mnt/r/ConTenDoViewer.jar!/com/sun/jna/platform/win32/COM/IStream.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
26.555556
97
0.665272
97c2531d4482588084cd09107999a1ecd41902e1
2,073
kt
Kotlin
yat-lib/src/main/java/yat/android/sdk/models/AdminNewLootBoxTypeConfig.kt
alexandrVakhtinTari/yat-lib-android
122a3ef6897279e58965891e1820c1fdc31c5224
[ "BSD-3-Clause" ]
null
null
null
yat-lib/src/main/java/yat/android/sdk/models/AdminNewLootBoxTypeConfig.kt
alexandrVakhtinTari/yat-lib-android
122a3ef6897279e58965891e1820c1fdc31c5224
[ "BSD-3-Clause" ]
2
2021-06-11T06:49:26.000Z
2021-06-14T12:23:05.000Z
yat-lib/src/main/java/yat/android/sdk/models/AdminNewLootBoxTypeConfig.kt
alexandrVakhtinTari/yat-lib-android
122a3ef6897279e58965891e1820c1fdc31c5224
[ "BSD-3-Clause" ]
null
null
null
/** * Emoji ID API server * Emoji ID is a directory service that associates almost any type of structured data with a short, memorable identifier the emoji id. * * The version of the OpenAPI document: 0.2.262 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package yat.android.sdk.models import com.squareup.moshi.Json import java.io.Serializable /** * The configuration parameters for the loot box type * @param guarantees A set of guaranteed drops in this loot box type * @param maxBaseScore The upper bound (inclusive) rhythm score for standard yats in the loot box * @param maxLength Maximum yat length * @param minBaseScore The lower bound (inclusive) rhythm score for standard yats in the loot box * @param minLength Minimum yat length * @param size The number of yats in the loot box * @param weights A set of probability weightings for chance-based drops */ data class AdminNewLootBoxTypeConfig ( /* A set of guaranteed drops in this loot box type */ @Json(name = "guarantees") val guarantees: kotlin.collections.List<AdminNewLootBoxTypeConfigGuarantees>, /* The upper bound (inclusive) rhythm score for standard yats in the loot box */ @Json(name = "max_base_score") val maxBaseScore: kotlin.Long, /* Maximum yat length */ @Json(name = "max_length") val maxLength: kotlin.Long, /* The lower bound (inclusive) rhythm score for standard yats in the loot box */ @Json(name = "min_base_score") val minBaseScore: kotlin.Long, /* Minimum yat length */ @Json(name = "min_length") val minLength: kotlin.Long, /* The number of yats in the loot box */ @Json(name = "size") val size: kotlin.Long, /* A set of probability weightings for chance-based drops */ @Json(name = "weights") val weights: kotlin.collections.List<AdminNewLootBoxTypeConfigWeights> ) : Serializable { companion object { private const val serialVersionUID: Long = 123 } }
36.368421
133
0.718765
70e23c2c108f2b40a8bc15e1670f6ccf61527580
907
go
Go
dyndns/external.go
tommedge/name-dyndns
27d65b9113260c7fad286568cefe81e753806efc
[ "MIT" ]
null
null
null
dyndns/external.go
tommedge/name-dyndns
27d65b9113260c7fad286568cefe81e753806efc
[ "MIT" ]
null
null
null
dyndns/external.go
tommedge/name-dyndns
27d65b9113260c7fad286568cefe81e753806efc
[ "MIT" ]
null
null
null
package dyndns import ( "errors" "io/ioutil" "net/http" "strings" ) // Urls contains a set of mirrors in which a // raw IP string can be retreived. It is exported // for the intent of modification. var ( Urls = []string{"http://myexternalip.com/raw"} ) func tryMirror(url string) (string, error) { resp, err := http.Get(url) if err != nil { return "", err } defer resp.Body.Close() contents, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return strings.TrimSpace(string(contents)), nil } // GetExternalIP retrieves the external facing IP Address. // If multiple mirrors are provided in Urls, // it will try each one (in order), should // preceding mirrors fail. func GetExternalIP() (string, error) { for _, url := range Urls { resp, err := tryMirror(url) if err == nil { return resp, err } } return "", errors.New("Could not retreive external IP") }
19.717391
58
0.669239
5639f081c8b1c45b1abaa20f889914fa758100d9
3,919
go
Go
pkg/app/flow.go
gabstv/go-app
025112d6e21fdfbcf31106c54de1660b38342ec7
[ "MIT" ]
6
2021-04-02T18:26:58.000Z
2021-04-10T17:00:39.000Z
pkg/app/flow.go
gabstv/go-app
025112d6e21fdfbcf31106c54de1660b38342ec7
[ "MIT" ]
null
null
null
pkg/app/flow.go
gabstv/go-app
025112d6e21fdfbcf31106c54de1660b38342ec7
[ "MIT" ]
null
null
null
package app import ( "strconv" "time" "github.com/google/uuid" "github.com/maxence-charriere/go-app/v8/pkg/errors" ) const ( flowItemBaseWidth = 300 flowResizeSizeDelay = time.Millisecond * 100 ) // UIFlow is the interface that describes a container that displays its items as // a flow. // // EXPERIMENTAL WIDGET. type UIFlow interface { UI // Class adds a CSS class to the flow root HTML element class property. Class(v string) UIFlow // Content sets the content with the given UI elements. Content(elems ...UI) UIFlow // ID sets the flow root HTML element id property. ID(v string) UIFlow // ItemsBaseWidth sets the items base width in px. Items size is adjusted to // fit the space in the container. Default is 300px. ItemsBaseWidth(px int) UIFlow // StrechtOnSingleRow makes the items to occupy all the available space when // the flow spreads on a single row. StrechtOnSingleRow() UIFlow } // Flow creates a container that displays its items as a flow. // // EXPERIMENTAL WIDGET. func Flow() UIFlow { return &flow{ IitemsBaseWitdh: flowItemBaseWidth, id: "goapp-flow-" + uuid.New().String(), } } type flow struct { Compo IitemsBaseWitdh int Iclass string Iid string Icontent []UI IstrechOnSingleRow bool id string contentLen int width int itemWidth int adjustSizeTimer *time.Timer } func (f *flow) Class(v string) UIFlow { if v == "" { return f } if f.Iclass != "" { f.Iclass += " " } f.Iclass += v return f } func (f *flow) Content(elems ...UI) UIFlow { f.Icontent = FilterUIElems(elems...) return f } func (f *flow) ID(v string) UIFlow { f.Iid = v return f } func (f *flow) ItemsBaseWidth(px int) UIFlow { if px > 0 { f.IitemsBaseWitdh = px } return f } func (f *flow) StrechtOnSingleRow() UIFlow { f.IstrechOnSingleRow = true return f } func (f *flow) OnMount(ctx Context) { if f.requiresLayoutUpdate() { f.refreshLayout(ctx) } } func (f *flow) OnNav(ctx Context) { if f.requiresLayoutUpdate() { f.refreshLayout(ctx) } } func (f *flow) OnResize(ctx Context) { f.refreshLayout(ctx) } func (f *flow) OnDismount() { f.cancelAdjustItemSizes() } func (f *flow) Render() UI { if f.requiresLayoutUpdate() { f.Defer(f.refreshLayout) } return Div(). ID(f.id). Class("goapp-flow"). Class(f.Iclass). Body( Range(f.Icontent).Slice(func(i int) UI { itemWidth := strconv.Itoa(f.itemWidth) + "px" return Div(). Class("goapp-flow-item"). Style("max-width", itemWidth). Style("width", itemWidth). Body(f.Icontent[i]) }), ) } func (f *flow) requiresLayoutUpdate() bool { return (f.Iid != "" && f.Iid != f.id) || len(f.Icontent) != f.contentLen } func (f *flow) refreshLayout(ctx Context) { if f.Iid != "" && f.Iid != f.id { f.id = f.Iid f.Update() return } f.contentLen = len(f.Icontent) if IsServer { return } f.cancelAdjustItemSizes() if f.adjustSizeTimer != nil { f.adjustSizeTimer.Reset(flowResizeSizeDelay) return } f.adjustSizeTimer = time.AfterFunc(flowResizeSizeDelay, func() { f.Defer(f.adjustItemSizes) }) } func (f *flow) adjustItemSizes(ctx Context) { if f.IitemsBaseWitdh == 0 || len(f.Icontent) == 0 { return } elem := Window().GetElementByID(f.id) if !elem.Truthy() { Log(errors.New("flow root element found").Tag("id", f.id)) return } width := elem.Get("clientWidth").Int() if width == 0 { return } defer f.ResizeContent() defer f.Update() itemWidth := f.IitemsBaseWitdh itemsPerRow := width / itemWidth if itemsPerRow <= 1 { f.itemWidth = width return } itemWidth = width / itemsPerRow if l := len(f.Icontent); l <= itemsPerRow && f.IstrechOnSingleRow { itemWidth = width / l } f.itemWidth = itemWidth } func (f *flow) cancelAdjustItemSizes() { if f.adjustSizeTimer != nil { f.adjustSizeTimer.Stop() } }
18.661905
80
0.65578
5f3e61532bd695b34c9aa62a189bb254bdb67c40
576
ts
TypeScript
app/components/travelingExpenses/components/details/components/kreirajNalogeZaPrenosModal/kreirajNalogeZaPrenosModal.actions.ts
BogMil/racunovodja
1ba95eafb2a04056ea279f7a93fb1b034564060a
[ "MIT" ]
1
2020-09-19T19:21:58.000Z
2020-09-19T19:21:58.000Z
app/components/travelingExpenses/components/details/components/kreirajNalogeZaPrenosModal/kreirajNalogeZaPrenosModal.actions.ts
BogMil/racunovodja
1ba95eafb2a04056ea279f7a93fb1b034564060a
[ "MIT" ]
3
2021-01-28T21:01:59.000Z
2022-02-08T17:50:37.000Z
app/components/travelingExpenses/components/details/components/kreirajNalogeZaPrenosModal/kreirajNalogeZaPrenosModal.actions.ts
BogMil/racunovodja
1ba95eafb2a04056ea279f7a93fb1b034564060a
[ "MIT" ]
null
null
null
import { Action } from '../../../../../../reducers/types'; export const OPEN = 'OPEN'; export const CLOSE = 'CLOSE'; export const HANDLE_CHANGE = 'HANDLE_CHANGE'; export const NAMESPACE = 'KREIRAJ_NALOGE_ZA_PRENOS_MODAL'; export function open(): Action { return { namespace: NAMESPACE, type: OPEN }; } export function close(): Action { return { namespace: NAMESPACE, type: CLOSE }; } export function handleChange(name: string, value: any): Action { return { namespace: NAMESPACE, type: HANDLE_CHANGE, payload: { name, value } }; }
19.2
64
0.654514
5d59bc2298688126d5a3eccd96c03d54d6c8f549
6,191
go
Go
internal/library/category_component_test.go
akbarpambudi/go-point-of-sales
337bbefca57a62e9be6697579e6cd4204262f8e0
[ "Apache-2.0" ]
1
2021-04-06T08:50:30.000Z
2021-04-06T08:50:30.000Z
internal/library/category_component_test.go
akbarpambudi/go-point-of-sales
337bbefca57a62e9be6697579e6cd4204262f8e0
[ "Apache-2.0" ]
null
null
null
internal/library/category_component_test.go
akbarpambudi/go-point-of-sales
337bbefca57a62e9be6697579e6cd4204262f8e0
[ "Apache-2.0" ]
null
null
null
//+build component_test package library_test import ( "context" "fmt" "net/http" "testing" "github.com/akbarpambudi/go-point-of-sales/internal/common/errors" "github.com/akbarpambudi/go-point-of-sales/internal/common/testinghelper" "github.com/akbarpambudi/go-point-of-sales/internal/library" "github.com/akbarpambudi/go-point-of-sales/internal/library/adapter/adapterent/ent" "github.com/akbarpambudi/go-point-of-sales/internal/library/adapter/adapterent/ent/enttest" "github.com/akbarpambudi/go-point-of-sales/internal/library/domain/category" "github.com/google/uuid" _ "github.com/lib/pq" "github.com/orlangure/gnomock" "github.com/orlangure/gnomock/preset/postgres" "github.com/steinfletcher/apitest" jsonpath "github.com/steinfletcher/apitest-jsonpath" "github.com/stretchr/testify/suite" ) type CategoryComponentTestSuite struct { suite.Suite stopService func() ent *ent.Client service http.Handler container *gnomock.Container } func (s *CategoryComponentTestSuite) SetupSuite() { p := postgres.Preset( postgres.WithUser("username", "password"), postgres.WithDatabase("category"), ) container, err := gnomock.Start(p) if err != nil { s.FailNow(err.Error()) return } connStr := fmt.Sprintf( "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", container.Host, container.DefaultPort(), "username", "password", "category", ) s.ent = enttest.Open(s.T(), "postgres", connStr) service, stopService, err := library.NewWebService(context.TODO(), library.SetDataSourceClient(s.ent)) if err != nil { s.T().Fatal(err) } s.service = service s.stopService = stopService s.container = container s.setupDataSample() } func (s *CategoryComponentTestSuite) TearDownSuite() { _ = s.ent.Close() err := gnomock.Stop(s.container) if err != nil { s.T().Error(err) } s.stopService() } func (s CategoryComponentTestSuite) TestCreateCategoryShouldBeSuccess() { apitest.New("Test Create Category"). Handler(s.service). Post("/api/category"). JSON(testinghelper.JSONDictionary{ "id": "f1e1a9fa-690f-4756-907a-1d85bc044391", "name": "Beverage", }).Expect(s.T()). Status(http.StatusCreated). End() } func (s CategoryComponentTestSuite) TestCreateCategoryShouldResponseWithBadRequest() { type expectedResponse struct { responseBodyMatcher func(*http.Response, *http.Request) error } testTable := []struct { requestBody JSONDictionary want expectedResponse }{ { requestBody: JSONDictionary{ "name": "Dessert", }, want: expectedResponse{ responseBodyMatcher: jsonpath. Chain(). Equal("$.message", "invalid input data"). Equal("$.messageKey", category.CreationErrKey). Equal("$.errorType", errors.ErrorTypeIllegalInputError). Contains("$.children[*]", JSONDictionary{ "message": category.ErrCategoryIDCantBeEmpty.(*errors.POSError).Message(), "messageKey": category.ErrCategoryIDCantBeEmpty.(*errors.POSError).Key(), "errorType": category.ErrCategoryIDCantBeEmpty.(*errors.POSError).ErrType(), }). End(), }, }, { requestBody: JSONDictionary{ "id": "f1e1a9fa-690f-4756-907a-1d85bc044391", }, want: expectedResponse{ responseBodyMatcher: jsonpath. Chain(). Equal("$.message", "invalid input data"). Equal("$.messageKey", category.CreationErrKey). Equal("$.errorType", errors.ErrorTypeIllegalInputError). Contains("$.children[*]", JSONDictionary{ "message": category.ErrCategoryNameCantBeEmpty.(*errors.POSError).Message(), "messageKey": category.ErrCategoryNameCantBeEmpty.(*errors.POSError).Key(), "errorType": category.ErrCategoryNameCantBeEmpty.(*errors.POSError).ErrType(), }). End(), }, }, { requestBody: JSONDictionary{}, want: expectedResponse{ responseBodyMatcher: jsonpath. Chain(). Equal("$.message", "invalid input data"). Equal("$.messageKey", category.CreationErrKey). Equal("$.errorType", errors.ErrorTypeIllegalInputError). Contains("$.children[*]", JSONDictionary{ "message": category.ErrCategoryNameCantBeEmpty.(*errors.POSError).Message(), "messageKey": category.ErrCategoryNameCantBeEmpty.(*errors.POSError).Key(), "errorType": category.ErrCategoryNameCantBeEmpty.(*errors.POSError).ErrType(), }). Contains("$.children[*]", JSONDictionary{ "message": category.ErrCategoryIDCantBeEmpty.(*errors.POSError).Message(), "messageKey": category.ErrCategoryIDCantBeEmpty.(*errors.POSError).Key(), "errorType": category.ErrCategoryIDCantBeEmpty.(*errors.POSError).ErrType(), }). End(), }, }, } for i, r := range testTable { testCaseName := fmt.Sprintf("TestCase#%d", i) s.Run(testCaseName, func() { apitest.New("Test Create Category"). Handler(s.service). Post("/api/category"). JSON(r.requestBody).Expect(s.T()). Status(http.StatusBadRequest). Assert(r.want.responseBodyMatcher). End() }) } } func (s CategoryComponentTestSuite) TestGetCategoryByIDShouldBeSuccess() { apitest.New("Test Get Category by ID"). Handler(s.service). Get("/api/category/e88d1f9b-d7b7-437a-9c6a-2a80291c2427"). Expect(s.T()). Status(http.StatusOK). Assert(jsonpath.Equal("$.id", "e88d1f9b-d7b7-437a-9c6a-2a80291c2427")). Assert(jsonpath.Equal("$.name", "Main Course")). End() } func (s CategoryComponentTestSuite) TestGetCategoryByIDShouldReturnStatusNotFound() { apitest.New("Test Get Category by ID"). Handler(s.service). Get("/api/category/bd3fcd27-40b7-493d-98b1-22d031c97960"). Expect(s.T()). Status(http.StatusNotFound). End() } func (s *CategoryComponentTestSuite) setupDataSample() { ctx := context.TODO() dataSamples := []struct { id string name string }{ { id: "e88d1f9b-d7b7-437a-9c6a-2a80291c2427", name: "Main Course", }, { id: "3965e166-4be0-46cb-ae6c-db4f467f5815", name: "Appetizer", }, } for _, r := range dataSamples { s.ent.Category.Create().SetID(uuid.MustParse(r.id)).SetName(r.name).SaveX(ctx) } } func TestRunCategoryComponentTestSuite(t *testing.T) { suite.Run(t, new(CategoryComponentTestSuite)) }
30.053398
103
0.698433
5fd843f85598c99f2199c1fa3793067fbde187e8
2,114
c
C
src/main.c
dseguin/steg-image
ac3babda00eefd58d3c895eb2c455f5c99f8f31f
[ "MIT" ]
null
null
null
src/main.c
dseguin/steg-image
ac3babda00eefd58d3c895eb2c455f5c99f8f31f
[ "MIT" ]
null
null
null
src/main.c
dseguin/steg-image
ac3babda00eefd58d3c895eb2c455f5c99f8f31f
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include "libsteg/steganography.h" #define SET_ENCODE 0x01 #define SET_DECODE 0x02 /*steg operation to perform*/ unsigned char op; const char *e_file = NULL; const char *i_file = NULL; const char *o_file = NULL; unsigned num_bits = 0; void print_usage(const char *prog_name) { fprintf(stderr, "\nUSAGE: %s [-d|-e DATA_TO_EMBED] [-o OUT_FILE] [-b NUM_BITS] -i IMAGE_FILE\n\n", prog_name); fprintf(stderr, " -i Use IMAGE_FILE for steganography\n"); fprintf(stderr, " -d Decode the data embedded in IMAGE_FILE\n"); fprintf(stderr, " and send the result to stdout\n"); fprintf(stderr, " -e Embed the file DATA_TO_EMBED into IMAGE_FILE\n"); fprintf(stderr, " and send the result to stdout\n"); fprintf(stderr, " -b Use NUM_BITS as number of bits per color channel\n"); fprintf(stderr, " for embedded data (MIN: 1, MAX: 8, defaults to 2)\n"); fprintf(stderr, " -o Write output to OUT_FILE (defaults to stdout)\n\n"); } int process_args(int n, char **s) { int i; for(i = 1; i < n; i++) { if(s[i][0] != '-') continue; switch(s[i][1]) { case 'e': if(!(e_file = (i == n-1) ? NULL : s[i+1])) return 1; op = SET_ENCODE; break; case 'd': op = SET_DECODE; break; case 'i': if(!(i_file = (i == n-1) ? NULL : s[i+1])) return 1; break; case 'o': if(!(o_file = (i == n-1) ? NULL : s[i+1])) return 1; break; case 'b': { char *c = NULL; if(i == n-1) return 1; num_bits = (unsigned)strtoul(s[i+1], &c, 10); if(num_bits < 1 || num_bits > 8 || (c && *c != '\0')) return 1; } break; case 'h': return 1; default: break; } } return (!op) ? 1 : 0; } int main(int argc, char **argv) { int ret = 1; if(argc < 4 || process_args(argc, argv)) { print_usage(argv[0]); return ret; } steg_init(); if(num_bits) set_num_bits(num_bits); if(load_image(i_file)) return ret; if(op == SET_ENCODE) ret = steg_encode_to_file(e_file, o_file); else if(op == SET_DECODE) ret = steg_decode_to_file(o_file); else print_usage(argv[0]); steg_quit(); return ret; }
23.488889
111
0.610691
a56718dd8f16ae81787004b5dead266f597efd04
18,728
sql
SQL
db/forum_db.sql
uutbudiarto/forum
a38f89416bd03c5fce816706a64a9dcf69860c37
[ "MIT" ]
null
null
null
db/forum_db.sql
uutbudiarto/forum
a38f89416bd03c5fce816706a64a9dcf69860c37
[ "MIT" ]
null
null
null
db/forum_db.sql
uutbudiarto/forum
a38f89416bd03c5fce816706a64a9dcf69860c37
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jul 12, 2020 at 09:25 AM -- Server version: 10.4.11-MariaDB -- PHP Version: 7.2.30 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `forum_db` -- -- -------------------------------------------------------- -- -- Table structure for table `announcement` -- CREATE TABLE `announcement` ( `id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, `urgency` varchar(128) NOT NULL, `ann_title` text NOT NULL, `ann_text` text NOT NULL, `time_created` varchar(128) NOT NULL, `time_exp` varchar(20) NOT NULL, `created_at` varchar(128) NOT NULL, `updated_at` varchar(128) NOT NULL, `deleted_at` varchar(128) DEFAULT NULL, `is_active` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `announcement` -- INSERT INTO `announcement` (`id`, `user_id`, `role_id`, `urgency`, `ann_title`, `ann_text`, `time_created`, `time_exp`, `created_at`, `updated_at`, `deleted_at`, `is_active`) VALUES (17, 26, 2, 'info', 'Penting1', 'Low', '1593755645', '1593759245', '2020-07-03', '2020-07-03', NULL, 0), (18, 26, 2, 'info', 'Penting', 'jadi low udah diubah', '1593755660', '1593759260', '2020-07-03', '2020-07-03', NULL, 0), (19, 26, 2, 'danger', 'Ini Pengumuman Baru', 'Penting bgt', '1593756879', '1593760479', '2020-07-03', '2020-07-03', NULL, 0), (20, 25, 1, 'danger', 'Penting', 'Pengumuman Dari Admin 1', '1593757999', '1594276399', '2020-07-03', '2020-07-03', NULL, 0), (21, 25, 1, 'warning', 'Pengumuman 2', 'Dari Admin 1', '1593758298', '1594276698', '2020-07-03', '2020-07-03', NULL, 0), (22, 26, 2, 'danger', 'Pengumuman 1', 'Pengumuman 1 dari admin\r\nPengumuman 1 dari admin\r\nPengumuman 1 dari admin', '1593758449', '1594276849', '2020-07-03', '2020-07-12', NULL, 1), (23, 29, 3, 'warning', 'Pengumuman Role3', 'Pengumuman Dari Role 3', '1594535921', '1595054321', '2020-07-12', '2020-07-12', NULL, 1), (24, 29, 3, 'danger', 'ROLE 3 BUAT PENGUMUMAM', 'Lorem ipsum', '1594535988', '1595054388', '2020-07-12', '2020-07-12', NULL, 1), (25, 26, 2, 'warning', 'PENGUMUMAN ROLE 2', '1. Role 2 BUAT pengumuman\r\n2. Role 2 BUAT pengumuman', '1594536066', '1595054466', '2020-07-12', '2020-07-12', NULL, 1); -- -------------------------------------------------------- -- -- Table structure for table `chat` -- CREATE TABLE `chat` ( `id` int(11) NOT NULL, `chat_root_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `chat_text` text NOT NULL, `time_created` varchar(100) NOT NULL, `created_at` varchar(100) NOT NULL, `updated_at` varchar(100) NOT NULL, `deleted_at` varchar(100) NOT NULL, `is_readed` int(11) NOT NULL, `is_active` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `chat` -- INSERT INTO `chat` (`id`, `chat_root_id`, `user_id`, `chat_text`, `time_created`, `created_at`, `updated_at`, `deleted_at`, `is_readed`, `is_active`) VALUES (184, 24, 25, 'OK', '1593951128', '2020-07-05', '2020-07-05', '', 0, 1), (186, 24, 27, 'OK', '1593963388', '2020-07-05', '2020-07-05', '', 0, 1), (187, 24, 27, 'OK', '1593963399', '2020-07-05', '2020-07-05', '', 0, 1), (188, 24, 27, 'OK', '1593963432', '2020-07-05', '2020-07-05', '', 0, 1), (189, 29, 25, 'Hallo MIn', '1594089857', '2020-07-07', '2020-07-07', '', 0, 1), (190, 29, 26, 'Haloo', '1594089924', '2020-07-07', '2020-07-07', '', 0, 1), (191, 29, 25, 'Apa Kabar', '1594089936', '2020-07-07', '2020-07-07', '', 0, 1), (192, 29, 26, 'Baik', '1594089941', '2020-07-07', '2020-07-07', '', 0, 1), (193, 29, 25, 'OK', '1594090097', '2020-07-07', '2020-07-07', '', 0, 1), (194, 29, 26, '1', '1594090103', '2020-07-07', '2020-07-07', '', 0, 1), (195, 29, 25, '1', '1594090107', '2020-07-07', '2020-07-07', '', 0, 1), (196, 28, 27, '1', '1594202487', '2020-07-08', '2020-07-08', '', 0, 1), (197, 28, 26, '2', '1594202543', '2020-07-08', '2020-07-08', '', 0, 1), (198, 28, 26, '21212', '1594202553', '2020-07-08', '2020-07-08', '', 0, 1), (199, 28, 27, 'ewewew', '1594202559', '2020-07-08', '2020-07-08', '', 0, 1), (200, 28, 26, 'qwqwqw', '1594202565', '2020-07-08', '2020-07-08', '', 0, 1), (201, 28, 27, 'qwqwqw', '1594202569', '2020-07-08', '2020-07-08', '', 0, 1), (202, 21, 27, 'OK', '1594202829', '2020-07-08', '2020-07-08', '', 0, 1), (203, 28, 27, 'OK', '1594203725', '2020-07-08', '2020-07-08', '', 0, 1), (204, 28, 26, 'OKOK', '1594203734', '2020-07-08', '2020-07-08', '', 0, 1); -- -------------------------------------------------------- -- -- Table structure for table `chat_root` -- CREATE TABLE `chat_root` ( `id` int(11) NOT NULL, `from_user` int(11) NOT NULL, `to_user` int(11) NOT NULL, `time_created` varchar(128) NOT NULL, `created_at` varchar(128) NOT NULL, `updated_at` varchar(128) NOT NULL, `deleted_at` varchar(128) DEFAULT NULL, `is_active` int(11) NOT NULL, `count_chat_adm` int(11) DEFAULT NULL, `count_chat_emp` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `chat_root` -- INSERT INTO `chat_root` (`id`, `from_user`, `to_user`, `time_created`, `created_at`, `updated_at`, `deleted_at`, `is_active`, `count_chat_adm`, `count_chat_emp`) VALUES (24, 25, 27, '1593852709', '2020-07-04', '2020-07-04', NULL, 1, 0, 0), (25, 25, 24, '1593854121', '2020-07-04', '2020-07-04', NULL, 1, 0, 0), (27, 25, 28, '1593859177', '2020-07-04', '2020-07-04', NULL, 1, 0, 0), (28, 26, 27, '1593876223', '2020-07-04', '2020-07-04', NULL, 1, 0, 0), (29, 25, 26, '1594089845', '2020-07-07', '2020-07-07', NULL, 1, 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `comment_reports` -- CREATE TABLE `comment_reports` ( `id` int(11) NOT NULL, `comment_text` text NOT NULL, `report_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, `like_indicator` int(11) NOT NULL, `time_created` varchar(100) NOT NULL, `created_at` varchar(100) NOT NULL, `updated_at` varchar(100) NOT NULL, `deleted_at` varchar(100) DEFAULT NULL, `is_active` int(11) NOT NULL, `is_owner_readed` int(11) NOT NULL, `is_manager_readed` int(11) NOT NULL, `is_manager2_readed` int(11) NOT NULL, `is_user_readed` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `comment_reports` -- INSERT INTO `comment_reports` (`id`, `comment_text`, `report_id`, `user_id`, `role_id`, `like_indicator`, `time_created`, `created_at`, `updated_at`, `deleted_at`, `is_active`, `is_owner_readed`, `is_manager_readed`, `is_manager2_readed`, `is_user_readed`) VALUES (257, 'Coba komen dari diri sendiri', 57, 27, 4, 5, '1594464629', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (258, 'Komen dari admin1', 57, 26, 2, 5, '1594464706', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (259, 'Komen dari admin2', 57, 29, 3, 5, '1594464804', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (260, 'Komen dari role 1', 57, 25, 1, 5, '1594464852', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (261, 'Hitung koment, ini role user biasa', 57, 27, 4, 5, '1594465298', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (262, 'Ini role 3', 57, 29, 3, 5, '1594465361', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (263, 'INI role 1', 57, 25, 1, 5, '1594465399', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (264, 'Role 3 Komemn', 57, 29, 3, 5, '1594465474', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (265, '12', 57, 26, 2, 5, '1594465634', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (266, 'role2', 57, 26, 2, 5, '1594465746', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (267, 'Role 22', 57, 26, 2, 5, '1594465812', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (268, 'josss', 57, 25, 1, 5, '1594465834', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (269, 'WAW', 57, 29, 3, 5, '1594465848', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (270, 'OK', 57, 27, 4, 5, '1594474552', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (271, 'saya role1', 57, 25, 1, 5, '1594474620', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (272, 'saya role 2', 57, 26, 2, 5, '1594474655', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (273, 'saya role 3', 57, 29, 3, 5, '1594474667', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (274, 'JOS', 57, 25, 1, 5, '1594474689', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (275, 'Yang punya laporan komen', 57, 27, 4, 5, '1594475730', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (276, 'Boleh\n', 57, 26, 2, 5, '1594475744', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (277, 'Bebas', 57, 29, 3, 5, '1594475754', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (278, '1', 58, 26, 2, 5, '1594476551', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (279, '2', 58, 29, 3, 5, '1594476558', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (280, 'SIAP', 58, 28, 4, 5, '1594476582', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (281, 'Komen Di laporan 5 dari role2', 62, 26, 2, 5, '1594484322', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0), (282, 'Komen di laporan sendiri', 58, 28, 4, 5, '1594487693', '2020-07-12', '2020-07-12', NULL, 1, 0, 0, 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `menus` -- CREATE TABLE `menus` ( `id` int(11) NOT NULL, `menu_title` varchar(128) NOT NULL, `menu_name` varchar(128) NOT NULL, `menu_url` varchar(128) NOT NULL, `menu_icon` varchar(128) NOT NULL, `role_id` int(11) NOT NULL, `is_active` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `menus` -- INSERT INTO `menus` (`id`, `menu_title`, `menu_name`, `menu_url`, `menu_icon`, `role_id`, `is_active`) VALUES (1, 'Home', 'home', 'home', 'home.png', 4, 1), (2, 'Report', 'report', 'report', 'report.png', 1, 0), (3, 'Employee', 'employee', 'employee', 'employee.png', 4, 1), (4, 'Profile', 'profile', 'profile', 'profile.png', 4, 1), (5, 'Report', 'laporan', 'report', 'report.png', 1, 1), (7, 'Chat', 'chat', 'chat/history/', 'chat.png', 1, 1), (8, 'Pengumuman', 'announcement', 'announcement', 'announcement.png', 1, 1); -- -------------------------------------------------------- -- -- Table structure for table `position` -- CREATE TABLE `position` ( `id` int(11) NOT NULL, `position_name` varchar(128) NOT NULL, `indicator` int(11) NOT NULL, `is_active` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `position` -- INSERT INTO `position` (`id`, `position_name`, `indicator`, `is_active`) VALUES (1, 'Owner', 5, 1), (2, 'Manager', 4, 1), (3, 'Asisten Manager', 3, 1), (4, 'Model', 2, 1), (5, 'Admin', 3, 1), (6, 'Manager Keuangan', 4, 1), (7, 'HR Manager', 4, 1), (8, 'Gudang', 2, 1), (9, 'IT / Programmer', 3, 1); -- -------------------------------------------------------- -- -- Table structure for table `readed_status` -- CREATE TABLE `readed_status` ( `id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `report_id` int(11) NOT NULL, `is_read` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `reports` -- CREATE TABLE `reports` ( `id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `report_text` text NOT NULL, `report_image` varchar(128) NOT NULL, `report_file` varchar(128) NOT NULL, `time_created` varchar(100) NOT NULL, `created_at` varchar(100) NOT NULL, `updated_at` varchar(100) NOT NULL, `deleted_at` varchar(100) DEFAULT NULL, `is_active` int(11) NOT NULL, `is_owner_readed` int(11) NOT NULL, `is_manager_readed` int(11) NOT NULL, `is_manager2_readed` int(11) NOT NULL, `is_user_readed` int(11) NOT NULL, `count_comment` int(11) NOT NULL, `count_comment_manager` int(11) NOT NULL, `count_comment_manager2` int(11) NOT NULL, `count_comment_owner` int(11) NOT NULL, `count_comment_user` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `reports` -- INSERT INTO `reports` (`id`, `user_id`, `report_text`, `report_image`, `report_file`, `time_created`, `created_at`, `updated_at`, `deleted_at`, `is_active`, `is_owner_readed`, `is_manager_readed`, `is_manager2_readed`, `is_user_readed`, `count_comment`, `count_comment_manager`, `count_comment_manager2`, `count_comment_owner`, `count_comment_user`) VALUES (57, 27, 'Test laporan dari mahfud, rolenya user', 'default.png', 'default.txt', '1594461542', '2020-07-11', '2020-07-11', NULL, 1, 1, 1, 1, 1, 13, 1, 1, 0, 1), (58, 28, 'user biasa ke 2 laporan ni', 'default.png', 'default.txt', '1594475832', '2020-07-11', '2020-07-11', NULL, 1, 0, 1, 1, 1, 4, 0, 0, 0, 1), (59, 27, 'Laporan 2 Laporan 2\r\nLaporan 2\r\nLaporan 2', 'default.png', 'default.txt', '1594481901', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0), (60, 27, 'Laporan 3\r\nLaporan 3\r\nLaporan 3\r\nLaporan 3', 'default.png', 'default.txt', '1594481920', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0), (61, 27, 'Laporan 4\r\nLaporan 4\r\nLaporan 4\r\nLaporan 4\r\nLaporan 4', 'default.png', 'default.txt', '1594481935', '2020-07-11', '2020-07-11', NULL, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1), (62, 27, 'Laporan 5\r\nLaporan 5\r\nLaporan 5\r\nLaporan 5', 'default.png', 'default.txt', '1594481950', '2020-07-11', '2020-07-11', NULL, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (63, 26, 'Role 2 Membuat Laporan', 'default.png', 'default.txt', '1594487849', '2020-07-12', '2020-07-12', NULL, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0), (64, 27, 'Pengumuman Dari Role 3', 'default.png', 'default.txt', '1594535850', '2020-07-12', '2020-07-12', NULL, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `role` -- CREATE TABLE `role` ( `id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `role` varchar(128) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `email` varchar(128) NOT NULL, `phone` varchar(20) NOT NULL, `password` varchar(128) NOT NULL, `fullname` varchar(128) NOT NULL, `image` varchar(128) NOT NULL, `position_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, `date_created` varchar(100) NOT NULL, `created_at` varchar(100) NOT NULL, `updated_at` varchar(100) NOT NULL, `deleted_at` varchar(100) DEFAULT NULL, `is_active` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `email`, `phone`, `password`, `fullname`, `image`, `position_id`, `role_id`, `date_created`, `created_at`, `updated_at`, `deleted_at`, `is_active`) VALUES (24, 'forum_adm@gmail.com', '0892220089090', '$2y$10$Pdwf2QQCgtYDGo41sGrG/eM7XGGB4chVrYhpBYK1VBW24Qojkq8ty', 'Admin Tester', 'logo.jpg', 9, 1, '2020/06/26', '1593140451', '1593140451', NULL, 1), (25, 'role1@gmail.com', '089600000001', '$2y$10$0yuY93Wzaf9T1WcGfrdpMeZ1hvJ3qwjQ6P2vVwjVxSmqk.TZp7uq2', 'Jokowi', 'default.png', 1, 1, '1593141217', '2020-06-26', '2020-06-26', NULL, 1), (26, 'role2@gmail.com', '089600000002', '$2y$10$6aK/6RWGFwAg4A3C1Q8WqOfRbnr4/YHOQuMuEYPGtWm9xtxqnCar.', 'Makruf Amin', 'default.png', 2, 2, '1593141258', '2020-06-26', '2020-06-26', NULL, 1), (27, 'role3-1@gmail.com', '089600000003', '$2y$10$geKrlBfV6z7uwEPA2xTAae4l9Lw4dD.voAExQg0Gh3oAhzX76V/ou', 'Mahfud', 'aycrl4be_400x400.jpg', 3, 4, '1593141295', '2020-06-26', '2020-06-26', NULL, 1), (28, 'role3-2@gmail.com', '089600000004', '$2y$10$mGTIzoUnc.Xdz0fFgZ6V4O/op/eYVrg4ZGMiSZ4/FNyNUzFaDVH6S', 'Nadim', 'default.png', 5, 4, '1593141342', '2020-06-26', '2020-06-26', NULL, 1), (29, 'admin3@gmail.com', '0897777777', '$2y$10$ArwzDMpeRwMibZz2n6jCWePAYpr.cNpmqUnmUr35uZRFAofkcqoE.', 'admin3', 'default.png', 2, 3, '1594392316', '2020-07-10', '2020-07-10', NULL, 1); -- -- Indexes for dumped tables -- -- -- Indexes for table `announcement` -- ALTER TABLE `announcement` ADD PRIMARY KEY (`id`); -- -- Indexes for table `chat` -- ALTER TABLE `chat` ADD PRIMARY KEY (`id`); -- -- Indexes for table `chat_root` -- ALTER TABLE `chat_root` ADD PRIMARY KEY (`id`); -- -- Indexes for table `comment_reports` -- ALTER TABLE `comment_reports` ADD PRIMARY KEY (`id`); -- -- Indexes for table `menus` -- ALTER TABLE `menus` ADD PRIMARY KEY (`id`); -- -- Indexes for table `position` -- ALTER TABLE `position` ADD PRIMARY KEY (`id`); -- -- Indexes for table `readed_status` -- ALTER TABLE `readed_status` ADD PRIMARY KEY (`id`); -- -- Indexes for table `reports` -- ALTER TABLE `reports` ADD PRIMARY KEY (`id`); -- -- Indexes for table `role` -- ALTER TABLE `role` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `announcement` -- ALTER TABLE `announcement` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26; -- -- AUTO_INCREMENT for table `chat` -- ALTER TABLE `chat` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=205; -- -- AUTO_INCREMENT for table `chat_root` -- ALTER TABLE `chat_root` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30; -- -- AUTO_INCREMENT for table `comment_reports` -- ALTER TABLE `comment_reports` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=283; -- -- AUTO_INCREMENT for table `menus` -- ALTER TABLE `menus` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT for table `position` -- ALTER TABLE `position` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `readed_status` -- ALTER TABLE `readed_status` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `reports` -- ALTER TABLE `reports` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=65; -- -- AUTO_INCREMENT for table `role` -- ALTER TABLE `role` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
38.935551
356
0.619714
95c2926a0d50d2fe0e51d338f36f73a400dab7e0
408
sql
SQL
create.sql
jondam1985/human-inventory-management-system
51fd953c394a2f8a49d72bad68055acdae2f1bb0
[ "MIT" ]
null
null
null
create.sql
jondam1985/human-inventory-management-system
51fd953c394a2f8a49d72bad68055acdae2f1bb0
[ "MIT" ]
1
2021-05-10T21:07:10.000Z
2021-05-10T21:07:10.000Z
create.sql
jondam1985/human-inventory-management-system
51fd953c394a2f8a49d72bad68055acdae2f1bb0
[ "MIT" ]
null
null
null
CREATE database hr_management; USE hr_management; CREATE table employee ( id int not null, first_name varchar(30) not null, last_name varchar(30) not null, role_id int, manager_id int, primary key(id)); CREATE TABLE role ( id int not null, title varchar(30), salary decimal default 0.0, department_id int, primary key(id) ); CREATE TABLE department ( id int not null, name varchar(30), primary key(id) );
16.32
32
0.757353
d2d136e7fa073c19fcbbd1130b97973eae444f80
2,680
php
PHP
app/Http/Controllers/ChambreController.php
haidaraKarara/codification
e8a7ef7beffaab3cd5eec525a61068a3cdfd0aa8
[ "MIT" ]
null
null
null
app/Http/Controllers/ChambreController.php
haidaraKarara/codification
e8a7ef7beffaab3cd5eec525a61068a3cdfd0aa8
[ "MIT" ]
null
null
null
app/Http/Controllers/ChambreController.php
haidaraKarara/codification
e8a7ef7beffaab3cd5eec525a61068a3cdfd0aa8
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Client; use GuzzleHttp\Exception\TransferException; class ChambreController extends Controller { private $user; private $response; private $body; private $message; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); $this->user = new Client(); } public function choisirBatiment() { $batiments = $this->recupBatiments(); return view('partials/chambreChoixBatiment',['batiments' => $batiments]); } public function choisirEtage(Request $req) { $req = $req->input('batiment'); $etages = $this->recupEtages($req); return view('partials/chambreChoixEtage',['etages' => $etages]); } public function choisirCouloir(Request $req) { $req = $req->input('etage'); $couloir = $this->recupCouloir($req); return view('partials/chambreChoixCouloir',['couloirs' => $couloir]); } public function recupBatiments() { $this->response = $this->user->get('https://codificationesp.herokuapp.com/api/Batiments'); $this->body = $this->response->getBody(); $this->body = json_decode($this->body); return $this->body; } public function recupEtages($id) { $this->response = $this->user->get('https://codificationesp.herokuapp.com/api/Batiments/'.$id.'/etages'); $this->body = $this->response->getBody(); $this->body = json_decode($this->body); return $this->body; } public function recupCouloir($id) { $this->response = $this->user->get('https://codificationesp.herokuapp.com/api/Etages/'.$id.'/coulois'); $this->body = $this->response->getBody(); $this->body = json_decode($this->body); return $this->body; } public function createChambre(Request $req) { $idCouloir = $req->input('couloir'); $numChambre = $req->input('chambre'); $maxOcc = $req->input('maxOccupant'); $this->user->post('https://codificationesp.herokuapp.com/api/Chambres', ['body' => [ 'numchambre' => $numChambre, 'nbremaxoccupants' => $maxOcc, 'couloirId' => $idCouloir ]]); $message = 'La chambre '.'<<'.$numChambre.'>> a été créé avec succès !'; $fin = 'Fin création de la chambre'.$numChambre; return view('partials/ajoutChambre',['message' => $message, 'fin' => $fin]); } }
31.529412
113
0.595896
b96737f1c0f4e23b84d108b42cb97bb80cc5c2cf
2,188
lua
Lua
Slipe/Core/Lua/Compiled/Client/Source/SlipeClient/Gui/GuiBrowser.lua
DezZolation/trains
0ed198bf6f314860b13e045f06714c644de55686
[ "Apache-2.0" ]
1
2020-08-29T20:34:10.000Z
2020-08-29T20:34:10.000Z
Slipe/Core/Lua/Compiled/Client/Source/SlipeClient/Gui/GuiBrowser.lua
DezZolation/trains
0ed198bf6f314860b13e045f06714c644de55686
[ "Apache-2.0" ]
null
null
null
Slipe/Core/Lua/Compiled/Client/Source/SlipeClient/Gui/GuiBrowser.lua
DezZolation/trains
0ed198bf6f314860b13e045f06714c644de55686
[ "Apache-2.0" ]
null
null
null
-- Generated by CSharp.lua Compiler local System = System local SlipeClientBrowsers local SlipeClientGui local SlipeMtaDefinitions System.import(function (out) SlipeClientBrowsers = Slipe.Client.Browsers SlipeClientGui = Slipe.Client.Gui SlipeMtaDefinitions = Slipe.MtaDefinitions end) System.namespace("Slipe.Client.Gui", function (namespace) -- <summary> -- GUI variant of a browser element -- </summary> namespace.class("GuiBrowser", function (namespace) local getBrowser, __ctor1__, __ctor2__ __ctor1__ = function (this, element) SlipeClientGui.GuiElement.__ctor__(this, element) end -- <summary> -- Create a new GUI browser -- </summary> __ctor2__ = function (this, position, width, height, isLocal, isTransparent, relative, parent) local default = parent if default ~= nil then default = default:getMTAElement() end __ctor1__(this, SlipeMtaDefinitions.MtaClient.GuiCreateBrowser(position.X, position.Y, width, height, isLocal, isTransparent, relative, default)) this.browser = SlipeClientBrowsers.Browser(SlipeMtaDefinitions.MtaClient.GuiGetBrowser(this.element)) end getBrowser = function (this) return this.browser end return { __inherits__ = function (out) return { out.Slipe.Client.Gui.GuiElement } end, getBrowser = getBrowser, __ctor__ = { __ctor1__, __ctor2__ }, __metadata__ = function (out) return { fields = { { "browser", 0x1, out.Slipe.Client.Browsers.Browser } }, properties = { { "Browser", 0x206, out.Slipe.Client.Browsers.Browser, getBrowser } }, methods = { { ".ctor", 0x106, __ctor1__, out.Slipe.MtaDefinitions.MtaElement }, { ".ctor", 0x706, __ctor2__, System.Numerics.Vector2, System.Single, System.Single, System.Boolean, System.Boolean, System.Boolean, out.Slipe.Client.Gui.GuiElement } }, class = { 0x6, System.new(out.Slipe.Shared.Elements.DefaultElementClassAttribute, 2, 13 --[[ElementType.GuiBrowser]]) } } end } end) end)
34.730159
177
0.656307
e79a1e21558bedbf4d334999ed98f00e8c0104dd
7,700
sql
SQL
cps_atlas.sql
QuietLearn/contentPay
540731fbefd9f19461da369f03c8a3c657dc8426
[ "Apache-2.0" ]
1
2019-07-10T09:14:06.000Z
2019-07-10T09:14:06.000Z
cps_atlas.sql
QuietLearn/contentPay
540731fbefd9f19461da369f03c8a3c657dc8426
[ "Apache-2.0" ]
null
null
null
cps_atlas.sql
QuietLearn/contentPay
540731fbefd9f19461da369f03c8a3c657dc8426
[ "Apache-2.0" ]
null
null
null
/* Navicat MySQL Data Transfer Source Server : mysql Source Server Version : 50554 Source Host : 127.0.0.1:3306 Source Database : guns Target Server Type : MYSQL Target Server Version : 50554 File Encoding : 65001 Date: 2018-10-15 08:43:16 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for cps_atlas -- ---------------------------- DROP TABLE IF EXISTS `cps_atlas`; CREATE TABLE `cps_atlas` ( `id` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT, `account_id` int(10) DEFAULT NULL, `picId` int(11) DEFAULT NULL COMMENT '图片编号', `title` varchar(200) DEFAULT NULL COMMENT '图片名称', `description` text COMMENT '描述', `pay_points` int(10) DEFAULT NULL COMMENT '支付积分', `tags_ids` varchar(255) DEFAULT NULL COMMENT '标签类型', `cover_pic` varchar(255) DEFAULT NULL COMMENT '封面', `type_id` int(2) DEFAULT NULL COMMENT '图集类型', `number` int(11) DEFAULT NULL COMMENT '图集编号', `is_del` int(2) DEFAULT NULL, `picaddress` varchar(255) DEFAULT NULL COMMENT '图片地址', `gmtcreated` datetime DEFAULT NULL, `gmtmodified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6514 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of cps_atlas -- ---------------------------- -- ---------------------------- -- Table structure for cps_chapter -- ---------------------------- DROP TABLE IF EXISTS `cps_chapter`; CREATE TABLE `cps_chapter` ( `id` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT, `novelId` int(11) DEFAULT NULL COMMENT '小说编号', `number` int(11) DEFAULT NULL COMMENT '章节编号', `title` varchar(200) DEFAULT NULL COMMENT '章节名称', `content` mediumtext COMMENT '章节内容', `is_del` int(2) DEFAULT NULL '逻辑删除', `gmt_created` datetime DEFAULT NULL '创建时间', `gmt_modified` datetime DEFAULT NULL '修改时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of cps_chapter -- ---------------------------- -- ---------------------------- -- Table structure for cps_novel -- ---------------------------- DROP TABLE IF EXISTS `cps_novel`; CREATE TABLE `cps_novel` ( `id` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT, `account_id` int(10) DEFAULT NULL, `title` varchar(200) DEFAULT NULL COMMENT ' 小说标题', `pic_address` varchar(200) DEFAULT NULL COMMENT '小说封面', `type` int(2) DEFAULT NULL COMMENT '小说类别', `author` varchar(45) DEFAULT NULL COMMENT '作者名', `refresh_time` varchar(45) DEFAULT NULL COMMENT '更新时间', `status` varchar(10) DEFAULT NULL COMMENT '小说状态', `pay_points` int(10) DEFAULT NULL '支付积分', `description` text '描述', `is_del` int(2) DEFAULT NULL '逻辑删除', `gmt_created` datetime DEFAULT NULL '创建时间', `gmt_modified` datetime DEFAULT NULL '修改时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of cps_novel -- ---------------------------- -- ---------------------------- -- Table structure for cps_picture -- ---------------------------- DROP TABLE IF EXISTS `cps_picture`; CREATE TABLE `cps_picture` ( `id` int(10) NOT NULL AUTO_INCREMENT 'id', `account_id` int(10) DEFAULT NULL '用户', `title` varchar(200) DEFAULT NULL '标题', `is_del` int(2) DEFAULT NULL '逻辑删除', `description` text '描述', `gmt_created` datetime DEFAULT NULL '创建时间', `gmt_modified` datetime DEFAULT NULL '修改时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4639 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of cps_picture -- ---------------------------- -- ---------------------------- -- Table structure for key_words -- ---------------------------- DROP TABLE IF EXISTS `key_words`; CREATE TABLE `key_words` ( `id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT 'id', `name` varchar(200) DEFAULT NULL COMMENT '模特名字', `is_del` int(2) DEFAULT NULL '逻辑删除', `gmt_created` datetime DEFAULT NULL '创建时间', `gmt_modified` datetime DEFAULT NULL '修改时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of key_words -- ---------------------------- -- ---------------------------- -- Table structure for pay_channel -- ---------------------------- DROP TABLE IF EXISTS `pay_channel`; CREATE TABLE `pay_channel` ( `id` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT 'id', `name` varchar(45) DEFAULT NULL '名字', `pay_code` varchar(45) DEFAULT NULL '支付码', `pay_type` int(2) DEFAULT NULL COMMENT '支付渠道类型', `is_choose` int(2) DEFAULT NULL '选中', `sort` int(11) DEFAULT NULL COMMENT '支付先后顺序', `is_del` int(2) DEFAULT NULL '逻辑删除', `gmt_created` datetime DEFAULT NULL '创建时间', `gmt_modified` datetime DEFAULT NULL '修改时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of pay_channel -- ---------------------------- INSERT INTO `pay_channel` VALUES ('0000000001', '第三方', '0', 'DSF', '2', '1', '1', '2018-06-14 18:16:50', '2018-06-15 15:18:55'); INSERT INTO `pay_channel` VALUES ('0000000002', '支付宝', '0', 'ZFB', '3', '0', '2', '2018-06-15 14:49:24', '2018-06-15 14:49:26'); INSERT INTO `pay_channel` VALUES ('0000000003', '微信', '0', 'WX', '4', '0', '3', '2018-06-15 15:19:47', '2018-06-15 15:19:47'); -- ---------------------------- -- Table structure for pay_points -- ---------------------------- DROP TABLE IF EXISTS `pay_points`; CREATE TABLE `pay_points` ( `id` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT 'id', `accoutid` int(11) DEFAULT NULL COMMENT '用户id', `type` int(10) DEFAULT NULL COMMENT '积分购买类型', `is_del` int(2) DEFAULT NULL '逻辑删除', `gmt_created` datetime DEFAULT NULL '创建时间', `gmt_modified` datetime DEFAULT NULL '修改时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of pay_points -- ---------------------------- -- ---------------------------- -- Table structure for service_orders -- ---------------------------- DROP TABLE IF EXISTS `service_orders`; CREATE TABLE `service_orders` ( `id` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT, `accountId` int(11) DEFAULT NULL COMMENT '用户账号id', `channelId` varchar(30) DEFAULT NULL , `pay_orderId` varchar(100) DEFAULT NULL COMMENT '支付订单号', `pay_type` int(2) DEFAULT NULL COMMENT '0 积分支付 1 pc支付宝 2 手机支付宝 3 是手机微信 4模豆支付 5 苹果内购', `pay_status` int(2) DEFAULT NULL COMMENT '支付状态 1未支付 2支付成功 3支付失败', `pay_money` varchar(100) DEFAULT NULL COMMENT '支付金额', `buy_goodsId` int(11) DEFAULT NULL COMMENT '商品id\n', `quantity` int(11) DEFAULT NULL, `price` float DEFAULT NULL '价格', `description` text '描述', `days` int(11) DEFAULT NULL COMMENT '服务天数', `buy_type` int(2) DEFAULT NULL COMMENT '购买商品类型 1 会员 2 自定义商品 3积分商品 4 模豆提取码商品', `order_type` int(2) DEFAULT NULL COMMENT ' 1 代表 直接开通趣向资源包 2 代表商城购买商品 ', `goods_name` varchar(45) DEFAULT NULL COMMENT '商品名称 ', `goods_alias` varchar(45) DEFAULT NULL '商品图片', `points` int(11) DEFAULT NULL COMMENT '消费的积分', `extract` text COMMENT '提取网文本', `appId` varchar(45) DEFAULT NULL, `gmt_created` datetime DEFAULT NULL '创建时间', `gmt_modified` datetime DEFAULT NULL '修改时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of service_orders -- ---------------------------- INSERT INTO `service_orders` VALUES ('0000000001', '222', '22', '22', '22', '2', '462', '62462', '62642', '626', '6264', '6246', '1', '2', '546', '642', '64', '62462626', '6', '2018-06-22 17:53:00', '2018-06-22 17:53:03');
38.308458
223
0.592468
963a5f8cad9da5ddfe49047ba3c198428fd8489e
927
php
PHP
app/Models/SupplierOrder.php
Sander0542-School/Avans-VINPRJ1
62bcf4fd10ca77ed1177ace4018dc78d7adb866e
[ "MIT" ]
null
null
null
app/Models/SupplierOrder.php
Sander0542-School/Avans-VINPRJ1
62bcf4fd10ca77ed1177ace4018dc78d7adb866e
[ "MIT" ]
null
null
null
app/Models/SupplierOrder.php
Sander0542-School/Avans-VINPRJ1
62bcf4fd10ca77ed1177ace4018dc78d7adb866e
[ "MIT" ]
null
null
null
<?php /** * Created by Reliese Model. */ namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; /** * Class SupplierOrder * * @property int $id * @property int $supplier_id * @property int $product_id * @property int $amount * @property float $price * @property Carbon $date * * @property Product $product * @property Supplier $supplier * * @package App\Models */ class SupplierOrder extends Model { protected $table = 'supplier_orders'; public $timestamps = false; protected $casts = [ 'supplier_id' => 'int', 'product_id' => 'int', 'quantity' => 'int', 'price' => 'float' ]; protected $dates = [ 'date' ]; protected $fillable = [ 'supplier_id', 'product_id', 'quantity', 'price', 'date' ]; public function product() { return $this->belongsTo(Product::class); } public function supplier() { return $this->belongsTo(Supplier::class); } }
15.196721
43
0.648328
305560bc5bfc87dd9b4f797ca97d86837ab6e093
85
lua
Lua
NativeLibraries/iOS/HERE_iOS_SDK_Premium_v3.15.2_92/framework/NMAKit.framework/NMABundle.bundle/diskcache/voices/en-US_generic_platform/skin.lua
KarinBerg/Xamarin.HEREMaps
87927ba567892528d1251ee83ffaab34fe201899
[ "MIT" ]
15
2020-07-06T00:42:33.000Z
2022-02-23T21:55:05.000Z
NativeLibraries/iOS/HERE_iOS_SDK_Premium_v3.15.2_92/framework/NMAKit.framework/NMABundle.bundle/diskcache/voices/en-US_generic_platform/skin.lua
KarinBerg/Xamarin.HEREMaps
87927ba567892528d1251ee83ffaab34fe201899
[ "MIT" ]
1
2021-09-22T05:48:37.000Z
2021-09-29T20:35:43.000Z
NativeLibraries/iOS/HERE_iOS_SDK_Premium_v3.15.2_92/framework/NMAKit.framework/NMABundle.bundle/diskcache/voices/en-US_generic_platform/skin.lua
KarinBerg/Xamarin.HEREMaps
87927ba567892528d1251ee83ffaab34fe201899
[ "MIT" ]
3
2020-08-09T06:06:40.000Z
2021-11-14T12:23:32.000Z
require("manifest") require("ruleset") require("prompts") require("platform_format")
17
26
0.764706
2a11eb66d95689ae109d59e6d0fa352cfaca69f8
267
java
Java
src/main/java/pl/sda/weatherman/model/WeatherRequestModel.java
jackverone/weatherman
e921f66f20e2304dda10d768d1b686fe9ccf71df
[ "MIT" ]
null
null
null
src/main/java/pl/sda/weatherman/model/WeatherRequestModel.java
jackverone/weatherman
e921f66f20e2304dda10d768d1b686fe9ccf71df
[ "MIT" ]
null
null
null
src/main/java/pl/sda/weatherman/model/WeatherRequestModel.java
jackverone/weatherman
e921f66f20e2304dda10d768d1b686fe9ccf71df
[ "MIT" ]
null
null
null
package pl.sda.weatherman.model; public class WeatherRequestModel { private String city; private String countryCode; public WeatherRequestModel(String city, String countryCode) { this.city = city; this.countryCode = countryCode; } }
22.25
65
0.70412