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
ffa9f94f428544d6339b987418edab75686890b3
515
py
Python
hitokoto.py
greenhandatsjtu/wechat-bot
51eda32c365cb4368366e1c60478ada295aadb1b
[ "Apache-2.0" ]
null
null
null
hitokoto.py
greenhandatsjtu/wechat-bot
51eda32c365cb4368366e1c60478ada295aadb1b
[ "Apache-2.0" ]
null
null
null
hitokoto.py
greenhandatsjtu/wechat-bot
51eda32c365cb4368366e1c60478ada295aadb1b
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python3 from urllib.parse import urlencode import requests url_base = 'https://v1.hitokoto.cn/?' params = { 'c': 'a', 'charset': 'utf-8', 'encode': 'json' } url = url_base + urlencode(params) def get_content(url): results = requests.get(url) text = results.json() hitokoto = text['hitokoto'] return hitokoto def main(): content = get_content(url) return content if __name__ == '__main__': res = get_content(url) print(res)
17.166667
38
0.598058
f40a3917630c19bad74991eed3913093c5b16650
12,249
cs
C#
CyDar.ServiceLocator.Tests/ServiceLocatorTest.cs
cyrusdargahi/CyDar
cbd1f0bccdd8d1cb94539aeaf0b32f3fceaa693e
[ "MIT" ]
null
null
null
CyDar.ServiceLocator.Tests/ServiceLocatorTest.cs
cyrusdargahi/CyDar
cbd1f0bccdd8d1cb94539aeaf0b32f3fceaa693e
[ "MIT" ]
null
null
null
CyDar.ServiceLocator.Tests/ServiceLocatorTest.cs
cyrusdargahi/CyDar
cbd1f0bccdd8d1cb94539aeaf0b32f3fceaa693e
[ "MIT" ]
null
null
null
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using CyDar.ServiceLocator.Enums; using CyDar.ServiceLocator.Exceptions; using CyDar.ServiceLocator.Interfaces; using CyDar.ServiceLocator.Tests.Concretes; using CyDar.ServiceLocator.Tests.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CyDar.ServiceLocator.Tests { [TestClass] public class ServiceLocatorTest { private readonly ServiceLocator serviceLocator = new ServiceLocator(); [TestInitialize] public void TestInit() { serviceLocator.Clear(); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_Resolved_Types_Registered_As_Singelton_Should_Be_Same() { serviceLocator.Register<IDummy>(_ => new Dummy(), Scope.Singelton); var expected = serviceLocator.Resolve<IDummy>(); var actual = serviceLocator.Resolve<IDummy>(); Assert.AreSame(expected, actual); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_Resolved_Types_In_Different_Threads_Registered_As_Singelton_Should_Be_Same() { serviceLocator.Register<IDummy>(_ => new Dummy(), Scope.Singelton); var expected = serviceLocator.Resolve<IDummy>(); var task = Task.Run(async () => { await Task.Yield(); return serviceLocator.Resolve<IDummy>(); }); task.Wait(); Assert.AreSame(expected, task.Result); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_Resolved_Types_In_Same_Thread_Registered_As_Thread_Should_Be_Same() { serviceLocator.Register<IDummy>(_ => new Dummy(), Scope.Thread); var expected = serviceLocator.Resolve<IDummy>(); var actual = serviceLocator.Resolve<IDummy>(); Assert.AreSame(expected, actual); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_Resolved_Types_In_Different_Threads_Registered_As_Thread_Should_Not_Be_Same() { serviceLocator.Register<IDummy>(_ => new Dummy(), Scope.Thread); var expected = serviceLocator.Resolve<IDummy>(); var task = Task.Run(async () => { await Task.Yield(); return serviceLocator.Resolve<IDummy>(); }); task.Wait(); Assert.AreNotSame(expected, task.Result); } [TestMethod] [TestCategory("ServiceLocator"), ExpectedException(typeof(InvalidOperationException))] public void ServiceLocator_Register_With_Scope_Thread_With_Condition_Should_Throw_Exception() { var conditionObject = new List<int> { 1 }; serviceLocator.Register<IDummy>(_ => new Dummy(1), Scope.Thread).When(r => conditionObject.First() == 1); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_Resolved_Types_Registered_With_Scope_Thread_With_Condition_Should_Return_Correct() { var conditionObject = new List<int> { 1 }; serviceLocator.Register<IDummy>(_ => new Dummy(1)).When(r => conditionObject.First() == 1); serviceLocator.Register<IDummy>(_ => new Dummy(2), Scope.Thread); var expected = serviceLocator.Resolve<IDummy>(); Assert.AreEqual(1, expected.GetValue()); conditionObject[0] = 2; var actual = serviceLocator.Resolve<IDummy>(); Assert.AreNotSame(expected, actual); Assert.AreEqual(2, actual.GetValue()); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_Resolved_Types_Registered_As_Transient_Should_Not_Be_Same() { serviceLocator.Register<IDummy>(_ => new Dummy(), Scope.Transient); var expected = serviceLocator.Resolve<IDummy>(); var actual = serviceLocator.Resolve<IDummy>(); Assert.AreNotSame(expected, actual); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_Resolved_Types_Registered_As_Custom_Should_Be_Same() { serviceLocator.SetStorage(CreateStorage()); serviceLocator.Register<IDummy>(_ => new Dummy(), Scope.Custom); var expected = serviceLocator.Resolve<IDummy>(); var actual = serviceLocator.Resolve<IDummy>(); Assert.AreSame(expected, actual); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_Resolved_Types_Registered_With_Condition_Should_Return_Right_Instance_When_Condition_Is_Met() { var testObject = new List<int> { 0 }; const int expected1 = 1001; const int expected2 = 1002; serviceLocator.Register<IDummy>(_ => new Dummy(expected1)).When(_ => testObject.First() == 0); serviceLocator.Register<IDummy>(_ => new Dummy(expected2)).When(_ => testObject.First() == 1); var dummy = serviceLocator.Resolve<IDummy>(); var actual1 = dummy.GetValue(); Assert.AreEqual(expected1, actual1); testObject.Clear(); testObject.Add(1); dummy = serviceLocator.Resolve<IDummy>(); var actual2 = dummy.GetValue(); Assert.AreEqual(expected2, actual2); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_Resolved_Types_Registered_With_Condition_In_Singelton_Scope_Should_Return_Right_Instance_When_Condition_Is_Met() { var testObject = new List<int> { 0 }; const int expected1 = 1001; const int expected2 = 1002; serviceLocator.Register<IDummy>(_ => new Dummy(expected1), Scope.Singelton).When(_ => testObject.First() == 0); serviceLocator.Register<IDummy>(_ => new Dummy(expected2), Scope.Singelton).When(_ => testObject.First() == 1); var dummy = serviceLocator.Resolve<IDummy>(); var actual1 = dummy.GetValue(); Assert.AreEqual(expected1, actual1); testObject.Clear(); testObject.Add(1); dummy = serviceLocator.Resolve<IDummy>(); var actual2 = dummy.GetValue(); Assert.AreEqual(expected2, actual2); } [TestMethod] [TestCategory("ServiceLocator"), ExpectedException(typeof(TypeCannotBeResolvedException))] public void ServiceLocator_Resolved_Types_Registered_With_Condition_Should_Throw_Exception_When_Condition_Is_Not_Met() { var testObject = new List<int> { 0 }; serviceLocator.Register<IDummy>(_ => new Dummy()).When(_ => testObject.First() == 1); serviceLocator.Register<IDummy>(_ => new Dummy()).When(_ => testObject.First() == 2); serviceLocator.Resolve<IDummy>(); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_RegisterToResolveAs_Types_Should_Be_Resolved() { serviceLocator.Register<IDummy>(_ => new Dummy()); serviceLocator.RegisterToResolveAs<IDummier, IDummy>(); Assert.IsNotNull(serviceLocator.Resolve<IDummier>()); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_RegisterToResolveAs_Types_In_Singelton_Scope_Should_Be_Same_When_Resolved() { serviceLocator.Register<IDummy>(_ => new Dummy(), Scope.Singelton); serviceLocator.RegisterToResolveAs<IDummier, IDummy>(); var dummy = serviceLocator.Resolve<IDummy>(); var dummier = serviceLocator.Resolve<IDummier>(); Assert.AreSame(dummy, dummier); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_RegisterToResolveAs_Types_In_Custom_Scope_Should_Be_Same_When_Resolved() { serviceLocator.SetStorage(CreateStorage()); serviceLocator.Register<IDummy>(_ => new Dummy(), Scope.Custom); serviceLocator.RegisterToResolveAs<IDummier, IDummy>(); var dummy = serviceLocator.Resolve<IDummy>(); var dummier = serviceLocator.Resolve<IDummier>(); Assert.AreSame(dummy, dummier); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_RegisterToResolveAs_Types_In_Transient_Scope_Should_Not_Be_Same_When_Resolved() { serviceLocator.Register<IDummy>(_ => new Dummy()); serviceLocator.RegisterToResolveAs<IDummier, IDummy>(); var dummy = serviceLocator.Resolve<IDummy>(); var dummier = serviceLocator.Resolve<IDummier>(); Assert.AreNotSame(dummy, dummier); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_RegisterToResolveAs_Types_And_Condition_Should_Be_Resolved_When_Condition_Is_Met() { var testObject = new List<int> { 0 }; serviceLocator.Register<IDummy>(_ => new Dummy()).When(_ => testObject.First() == 0); serviceLocator.RegisterToResolveAs<IDummier, IDummy>(); Assert.IsNotNull(serviceLocator.Resolve<IDummier>()); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_RegisterToResolveAs_Types_And_Condition_Should_Be_Resolved_To_Correct_Instance_When_Condition_Is_Met() { var testObject = new List<int> { 0 }; serviceLocator.Register<IDummy>(_ => new Dummy(1001)).When(_ => testObject.First() == 0); serviceLocator.Register<IDummy>(_ => new Dummy(1002)); serviceLocator.RegisterToResolveAs<IDummier, IDummy>(); Assert.AreEqual(1001, serviceLocator.Resolve<IDummier>().GetValue()); testObject[0] = 1; Assert.AreEqual(1002, serviceLocator.Resolve<IDummier>().GetValue()); } [TestMethod] [TestCategory("ServiceLocator"), ExpectedException(typeof(TypeCannotBeResolvedException))] public void ServiceLocator_RegisterToResolveAs_Types_And_Condition_Should_Throw_Exception_When_Condition_Is_Not_Met() { var testObject = new List<int> { 0 }; serviceLocator.Register<IDummy>(_ => new Dummy()).When(_ => testObject.First() == 1); serviceLocator.RegisterToResolveAs<IDummier, IDummy>(); serviceLocator.Resolve<IDummier>(); } [TestMethod] [TestCategory("ServiceLocator"), ExpectedException(typeof(TypeNotRegisteredException))] public void ServiceLocator_RegisterToResolveAs_Types_Should_Throw_Exception_When_Type_Is_Not_Registered() { serviceLocator.RegisterToResolveAs<IDummier, IDummy>(); serviceLocator.Resolve<IDummier>(); } [TestMethod] [TestCategory("ServiceLocator")] public void ServiceLocator_Should_Store_Registered_Types_Between_Instances() { var expected = new Dummy(1); serviceLocator.Register<IDummy>(_ => expected); var actual = new ServiceLocator().Resolve<IDummy>(); Assert.AreEqual(expected, actual); Assert.AreEqual(expected.GetValue(), actual.GetValue()); } private static IStorage CreateStorage() { var store = new Dictionary<Type, object>(); var moq = new Mock<IStorage>(); moq.Setup(f => f.StoreObject(It.IsAny<Type>(), It.IsAny<object>())).Callback((Type key, object value) => store.Add(key, value)); moq.Setup(f => f.GetObject(It.IsAny<Type>())).Returns((Type key) => store.ContainsKey(key) ? store[key] : null); moq.Setup(f => f.RemoveObject(It.IsAny<Type>())).Callback((Type key) => store.Remove(key)); return moq.Object; } } }
37.458716
147
0.634174
58d6c4a78cc4694316860d8b11f21067e3d7c76a
9,838
php
PHP
application/views/classifications/list.php
demesajerry/mglb-covid19-tracker
f889d05c85aee4d0bfb5a82e80df9ff2863814db
[ "MIT" ]
null
null
null
application/views/classifications/list.php
demesajerry/mglb-covid19-tracker
f889d05c85aee4d0bfb5a82e80df9ff2863814db
[ "MIT" ]
null
null
null
application/views/classifications/list.php
demesajerry/mglb-covid19-tracker
f889d05c85aee4d0bfb5a82e80df9ff2863814db
[ "MIT" ]
null
null
null
<div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Covid-19 Classifications <small></small> </h1> <ol class="breadcrumb"> <li><a href="#"> Admin</a></li> <li class="active">Classifications</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">Classifications</h3> <div class="box-tools"> <button class="btn btn-info" id="add_users" > <i class="fa fa-plus fa-1x"> </i> Add Classifications </button> </div> </div> <div class="box-body table-responsive"> <div class="modal fade" id="add_class_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header alert alert-info"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title" id="myModalLabel"> <p id="modal_title"></p> </h4> </div> <!-- Modal Body --> <div class="modal-body"> <form method="POST" id="form1" class="form-horizontal" role="form" action="<?php echo base_url()."users/add_users"; ?>"> <input type="hidden" name="c_status_id" id="c_status_id"> <table class="table table-bordered table-hover"> <tr> <td>Classification: </td> <td> <input type="text" name="c_classification" id="c_classification" class="form-control"></td> </tr> <tr> <tr> <td>Template Color: </td> <td> <select id="template" name="template" class="form-control"> <option value="bg-light">None</option> <option value="bg-success">Green</option> <option value="bg-warning">Yellow</option> <option value="bg-info">Blue</option> <option value="bg-danger">Red</option> </select> </tr> <tr> <td>Status: </td> <td> <select id="status" name="status" class="form-control"> <option value="1">Active</option> <option value="0">In-Active</option> </select> </td> </tr> </tr> </table> <!--SUBMIT BUTTON --> <div class="modal-footer" align="right"> <div class="form-group"> <div class="col-sm-12" align="right"> <button type="button" class="btn btn-default" data-dismiss="modal"> Close </button> <button type="submit" class="btn btn-success" id="submit_add">Save</button> </div> </div> </div> </form> </div><!--end Modal body--> </div><!--end Modal content--> </div><!--end Modal dialog--> </div><!--end modal receive--> <hr /> <table class="table table-striped table-bordered table-hover" id="viewresult"> <thead> <tr > <th width="10%">Classification ID</th> <th width="30%">Covid Classification</th> <th width="10%">action</th> </tr> </thead> <?php if($covidStatus_list != false){ foreach($covidStatus_list as $covidStatus){ ?> <tr> <td><?php echo $covidStatus->c_status_id; ?></td> <td><?php echo $covidStatus->c_classification; ?></td> <td> <a class="edit_modal" href="#" c_status_id="<?php echo $covidStatus->c_status_id; ?>" c_classification="<?php echo $covidStatus->c_classification; ?>" > <i class="fa fa-edit"></i> </a> | </td> </tr> <?php } } ?> </table> </div> </div> </div> </div> </section> </div> <script> $(document).ready(function() { $("#submit_add").click(function (e) { $('input[type=text]').val (function () { return this.value.toUpperCase(); }) $('input[type=text], textarea').val (function () { return this.value.toUpperCase(); }) $("#form1").submit(); }); $("#add_users").click(function() { $('#form1')[0].reset(); $("#modal_title").text('Add Classification'); //set selected value for select2 $('#station_id').val(""); //trigger change for select2 $('#station_id').select2().trigger('station_id'); //set selected value for select2 $('#access').val(""); //trigger change for select2 $('#access').select2().trigger('access'); document.getElementById('form1').action = '<?php echo base_url()."classifications/add_classifications"; ?>'; $('#add_class_modal').modal('show'); }); $(".edit_modal").click(function() { var dt = new Date(); $('#form1')[0].reset(); var c_status_id = this.getAttribute("c_status_id"); var c_classification = this.getAttribute("c_classification"); $("#c_status_id").val(c_status_id); $("#c_classification").val(c_classification); document.getElementById('form1').action = '<?php echo base_url()."classifications/edit_classifications"; ?>'; $('#add_class_modal').modal('show'); }); $('#viewresult').DataTable({ responsive: true, "aLengthMenu": [[5, 10, 20, -1], [5, 10, 20, "All"]], "iDisplayLength": 10, dom: 'Blfrtip', select: true, "buttons":[ { extend: 'print', text: 'Print all', title:"Clients List", messageTop:"", exportOptions:{ columns: [ 0, 1, 2, 3], modifier: { selected: null }, } }, { extend: 'print', text: 'Print Selected', title:"Clients List", messageTop:"", exportOptions:{ columns: [ 0, 1, 2, 3], modifier: { selected: true }, } }, { extend: 'pdf', text: 'Pdf', title:"Clients List", exportOptions:{ columns:[ 0, 1, 2, 3], modifier: { selected: null }, } }, { extend: 'excel', text: 'Excel', title:"Clients List", exportOptions:{ columns: [ 0, 1, 2, 3], modifier: { selected: null }, } }, ], }); $( "#datepicker" ).datepicker({ changeYear:true, changeMonth: true, yearRange: "1980:2015", dateFormat: 'yy-mm-dd' }); $( "#birthday" ).datepicker({ changeYear:true, changeMonth: true, yearRange: "1980:2015", dateFormat: 'yy-mm-dd' }); }); </script>
40.319672
154
0.359016
05c59a89c08a2945aa2c0224c8212dc47adb84cc
10,997
py
Python
synthdid/optimizer.py
MasaAsami/pysynthdid
01afe33ae22f513c65f9cfdec56a4b21ca547c28
[ "Apache-2.0" ]
null
null
null
synthdid/optimizer.py
MasaAsami/pysynthdid
01afe33ae22f513c65f9cfdec56a4b21ca547c28
[ "Apache-2.0" ]
null
null
null
synthdid/optimizer.py
MasaAsami/pysynthdid
01afe33ae22f513c65f9cfdec56a4b21ca547c28
[ "Apache-2.0" ]
2
2022-03-11T03:13:36.000Z
2022-03-20T22:55:13.000Z
from tqdm import tqdm import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from scipy.optimize import fmin_slsqp from toolz import partial from sklearn.model_selection import KFold, TimeSeriesSplit, RepeatedKFold from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV from bayes_opt import BayesianOptimization class Optimize(object): #### # Synthetic Difference in Differences (SDID) #### def est_zeta(self, Y_pre_c) -> float: """ # SDID Parameter to adjust the L2 penalty term """ return (self.n_treat * self.n_post_term) ** (1 / 4) * np.std( Y_pre_c.diff().dropna().values ) def est_omega(self, Y_pre_c, Y_pre_t, zeta): """ # SDID estimating omega """ Y_pre_t = Y_pre_t.copy() n_features = Y_pre_c.shape[1] nrow = Y_pre_c.shape[0] _w = np.repeat(1 / n_features, n_features) _w0 = 1 start_w = np.append(_w, _w0) if type(Y_pre_t) == pd.core.frame.DataFrame: Y_pre_t = Y_pre_t.mean(axis=1) # Required to have non negative values max_bnd = abs(Y_pre_t.mean()) * 2 w_bnds = tuple( (0, 1) if i < n_features else (max_bnd * -1, max_bnd) for i in range(n_features + 1) ) caled_w = fmin_slsqp( partial(self.l2_loss, X=Y_pre_c, y=Y_pre_t, zeta=zeta, nrow=nrow), start_w, f_eqcons=lambda x: np.sum(x[:n_features]) - 1, bounds=w_bnds, disp=False, ) return caled_w def est_lambda(self, Y_pre_c, Y_post_c): """ # SDID estimating lambda """ Y_pre_c_T = Y_pre_c.T Y_post_c_T = Y_post_c.T n_pre_term = Y_pre_c_T.shape[1] _lambda = np.repeat(1 / n_pre_term, n_pre_term) _lambda0 = 1 start_lambda = np.append(_lambda, _lambda0) if type(Y_post_c_T) == pd.core.frame.DataFrame: Y_post_c_T = Y_post_c_T.mean(axis=1) max_bnd = abs(Y_post_c_T.mean()) * 2 lambda_bnds = tuple( (0, 1) if i < n_pre_term else (max_bnd * -1, max_bnd) for i in range(n_pre_term + 1) ) caled_lambda = fmin_slsqp( partial(self.l2_loss, X=Y_pre_c_T, y=Y_post_c_T, zeta=0, nrow=0), start_lambda, f_eqcons=lambda x: np.sum(x[:n_pre_term]) - 1, bounds=lambda_bnds, disp=False, ) return caled_lambda[:n_pre_term] def l2_loss(self, W, X, y, zeta, nrow) -> float: """ Loss function with L2 penalty """ if type(y) == pd.core.frame.DataFrame: y = y.mean(axis=1) _X = X.copy() _X["intersept"] = 1 return np.sum((y - _X.dot(W)) ** 2) + nrow * zeta ** 2 * np.sum(W[:-1] ** 2) #### # Synthetic Control Method (SC) #### def rmse_loss(self, W, X, y, intersept=True) -> float: if type(y) == pd.core.frame.DataFrame: y = y.mean(axis=1) _X = X.copy() if intersept: _X["intersept"] = 1 return np.mean(np.sqrt((y - _X.dot(W)) ** 2)) def rmse_loss_with_V(self, W, V, X, y) -> float: if type(y) == pd.core.frame.DataFrame: y = y.mean(axis=1) _rss = (y - X.dot(W)) ** 2 _n = len(y) _importance = np.zeros((_n, _n)) np.fill_diagonal(_importance, V) return np.sum(_importance @ _rss) def _v_loss(self, V, X, y, return_loss=True): Y_pre_t = self.Y_pre_t.copy() n_features = self.Y_pre_c.shape[1] _w = np.repeat(1 / n_features, n_features) if type(Y_pre_t) == pd.core.frame.DataFrame: Y_pre_t = Y_pre_t.mean(axis=1) w_bnds = tuple((0, 1) for i in range(n_features)) _caled_w = fmin_slsqp( partial(self.rmse_loss_with_V, V=V, X=X, y=y), _w, f_eqcons=lambda x: np.sum(x) - 1, bounds=w_bnds, disp=False, ) if return_loss: return self.rmse_loss(_caled_w, self.Y_pre_c, Y_pre_t, intersept=False) else: return _caled_w def estimate_v(self, additional_X, additional_y): _len = len(additional_X) _v = np.repeat(1 / _len, _len) caled_v = fmin_slsqp( partial(self._v_loss, X=additional_X, y=additional_y), _v, f_eqcons=lambda x: np.sum(x) - 1, bounds=tuple((0, 1) for i in range(_len)), disp=False, ) return caled_v def est_omega_ADH( self, Y_pre_c, Y_pre_t, additional_X=pd.DataFrame(), additional_y=pd.DataFrame() ): """ # SC estimating omega for synthetic control method (not for synthetic diff.-in-diff.) """ Y_pre_t = Y_pre_t.copy() n_features = Y_pre_c.shape[1] nrow = Y_pre_c.shape[0] _w = np.repeat(1 / n_features, n_features) if type(Y_pre_t) == pd.core.frame.DataFrame: Y_pre_t = Y_pre_t.mean(axis=1) # Required to have non negative values w_bnds = tuple((0, 1) for i in range(n_features)) if len(additional_X) == 0: caled_w = fmin_slsqp( partial(self.rmse_loss, X=Y_pre_c, y=Y_pre_t, intersept=False), _w, f_eqcons=lambda x: np.sum(x) - 1, bounds=w_bnds, disp=False, ) return caled_w else: assert additional_X.shape[1] == Y_pre_c.shape[1] if type(additional_y) == pd.core.frame.DataFrame: additional_y = additional_y.mean(axis=1) # normalized temp_df = pd.concat([additional_X, additional_y], axis=1) ss = StandardScaler() ss_df = pd.DataFrame( ss.fit_transform(temp_df), columns=temp_df.columns, index=temp_df.index ) ss_X = ss_df.iloc[:, :-1] ss_y = ss_df.iloc[:, -1] add_X = pd.concat([Y_pre_c, ss_X]) add_y = pd.concat([Y_pre_t, ss_y]) self.caled_v = self.estimate_v(additional_X=add_X, additional_y=add_y) return self._v_loss(self.caled_v, X=add_X, y=add_y, return_loss=False) ##### # cv search for zeta #### def _zeta_given_cv_loss_inverse(self, zeta, cv=5, split_type="KFold"): return -1 * self._zeta_given_cv_loss(zeta, cv, split_type)[0] def _zeta_given_cv_loss(self, zeta, cv=5, split_type="KFold"): nrow = self.Y_pre_c.shape[0] if split_type == "KFold": kf = KFold(n_splits=cv, random_state=self.random_seed) elif split_type == "TimeSeriesSplit": kf = TimeSeriesSplit(n_splits=cv) elif split_type == "RepeatedKFold": _cv = max(2, int(cv / 2)) kf = RepeatedKFold( n_splits=_cv, n_repeats=_cv, random_state=self.random_seed ) loss_result = [] nf_result = [] for train_index, test_index in kf.split(self.Y_pre_c, self.Y_pre_t): train_w = self.est_omega( self.Y_pre_c.iloc[train_index], self.Y_pre_t.iloc[train_index], zeta ) nf_result.append(np.sum(np.round(np.abs(train_w), 3) > 0) - 1) loss_result.append( self.rmse_loss( train_w, self.Y_pre_c.iloc[test_index], self.Y_pre_t.iloc[test_index], ) ) return np.mean(loss_result), np.mean(nf_result) def grid_search_zeta( self, cv=5, n_candidate=20, candidate_zata=[], split_type="KFold" ): """ Search for zeta using grid search instead of theoretical values """ if len(candidate_zata) == 0: for _z in np.linspace(0.1, self.base_zeta * 2, n_candidate): candidate_zata.append(_z) candidate_zata.append(self.base_zeta) candidate_zata.append(0) candidate_zata = sorted(candidate_zata) result_loss_dict = {} result_nf_dict = {} print("cv: zeta") for _zeta in tqdm(candidate_zata): result_loss_dict[_zeta], result_nf_dict[_zeta] = self._zeta_given_cv_loss( _zeta, cv=cv, split_type=split_type ) loss_sorted = sorted(result_loss_dict.items(), key=lambda x: x[1]) return loss_sorted[0] def bayes_opt_zeta( self, cv=5, init_points=5, n_iter=5, zeta_max=None, zeta_min=None, split_type="KFold", ): """ Search for zeta using Bayesian Optimization instead of theoretical values """ if zeta_max == None: zeta_max = self.base_zeta * 1.02 zeta_max2 = self.base_zeta * 2 if zeta_min == None: zeta_min = self.base_zeta * 0.98 zeta_min2 = 0.01 pbounds = {"zeta": (zeta_min, zeta_max)} optimizer = BayesianOptimization( f=partial(self._zeta_given_cv_loss_inverse, cv=cv, split_type=split_type), pbounds=pbounds, random_state=self.random_seed, ) optimizer.maximize( init_points=2, n_iter=2, ) optimizer.set_bounds(new_bounds={"zeta": (zeta_min2, zeta_max2)}) optimizer.maximize( init_points=init_points, n_iter=n_iter, ) optimizer.max["params"]["zeta"] return (optimizer.max["params"]["zeta"], optimizer.max["target"] * -1) ##### # The following is for sparse estimation #### def est_omega_ElasticNet(self, Y_pre_c, Y_pre_t): Y_pre_t = Y_pre_t.copy() if type(Y_pre_t) == pd.core.frame.DataFrame: Y_pre_t = Y_pre_t.mean(axis=1) # Y_pre_t.columns = "treatment_group" regr = ElasticNetCV(cv=5, random_state=0) regr.fit(Y_pre_c, Y_pre_t) self.elastic_net_alpha = regr.alpha_ caled_w = regr.coef_ return np.append(caled_w, regr.intercept_) def est_omega_Lasso(self, Y_pre_c, Y_pre_t): Y_pre_t = Y_pre_t.copy() if type(Y_pre_t) == pd.core.frame.DataFrame: Y_pre_t = Y_pre_t.mean(axis=1) regr = LassoCV(cv=5, random_state=0) regr.fit(Y_pre_c, Y_pre_t) self.lasso_alpha = regr.alpha_ caled_w = regr.coef_ return np.append(caled_w, regr.intercept_) def est_omega_Ridge(self, Y_pre_c, Y_pre_t): Y_pre_t = Y_pre_t.copy() if type(Y_pre_t) == pd.core.frame.DataFrame: Y_pre_t = Y_pre_t.mean(axis=1) regr = RidgeCV(cv=5) regr.fit(Y_pre_c, Y_pre_t) self.ridge_alpha = regr.alpha_ caled_w = regr.coef_ return np.append(caled_w, regr.intercept_)
29.561828
88
0.559516
94c002b3beb89fff3540ab21ef77febea9df3151
529
swift
Swift
Sources/InkView/Internal/Views/BlockquoteView.swift
Finnvoor/Ink
8883bdf54f21a85cb620cf0d484c0e01c1e0a826
[ "MIT" ]
null
null
null
Sources/InkView/Internal/Views/BlockquoteView.swift
Finnvoor/Ink
8883bdf54f21a85cb620cf0d484c0e01c1e0a826
[ "MIT" ]
null
null
null
Sources/InkView/Internal/Views/BlockquoteView.swift
Finnvoor/Ink
8883bdf54f21a85cb620cf0d484c0e01c1e0a826
[ "MIT" ]
null
null
null
// // File.swift // // // Created by Finn Voorhees on 15/03/2020. // import SwiftUI internal struct BlockquoteView: View { let text: String @State private var textRect: CGRect = CGRect() var body: some View { HStack { Rectangle() .frame(width: 4, height: self.textRect.height) Text(self.text) .lineLimit(nil) .background(GeometryGetter(rect: self.$textRect)) }.foregroundColor(.secondary).padding(.horizontal) } }
22.041667
65
0.572779
52f3f6ca22336e1ea60cedad3591a556596e0e60
4,139
rb
Ruby
spec/store_size_xcarchive_check_action_spec.rb
philihp/fastlane-plugin-store_sizer
5419490b8ce479c22cc8abf91648ac774b9a70f3
[ "MIT" ]
20
2017-06-29T18:42:43.000Z
2021-07-22T14:00:05.000Z
spec/store_size_xcarchive_check_action_spec.rb
philihp/fastlane-plugin-store_sizer
5419490b8ce479c22cc8abf91648ac774b9a70f3
[ "MIT" ]
9
2017-06-23T18:12:22.000Z
2019-05-21T13:31:33.000Z
spec/store_size_xcarchive_check_action_spec.rb
philihp/fastlane-plugin-store_sizer
5419490b8ce479c22cc8abf91648ac774b9a70f3
[ "MIT" ]
4
2017-12-13T08:56:28.000Z
2020-12-04T20:14:02.000Z
describe Fastlane::Actions::StoreSizeXcarchiveCheckAction do let(:thinning_report) { Plist.parse_xml(File.join("./spec/fixtures/export", "app-thinning.plist")) } def make_segments_report(min_os_version, text_segments_size, text_max_slice_size) result = {} result["min_os_version"] = min_os_version result["text_segments_size"] = text_segments_size result["text_max_slice_size"] = text_max_slice_size result end context "check Apple constraints" do it 'breaks if ios <= 6 and size exceed' do report = make_segments_report([6, 0, 0], Fastlane::Actions::StoreSizeXcarchiveCheckAction::MAX_TEXT_6_LESS + 1, 0) expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: report, max_wifi_size: 0) }.to raise_error(FastlaneCore::Interface::FastlaneTestFailure) end it 'breaks if 7 <= ios <= 8 and size exceed' do report = make_segments_report([7, 0, 0], 0, Fastlane::Actions::StoreSizeXcarchiveCheckAction::MAX_SEGMENT_7_TO_8 + 1) expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: report, max_wifi_size: 0) }.to raise_error(FastlaneCore::Interface::FastlaneTestFailure) report = make_segments_report([8, 0, 0], 0, Fastlane::Actions::StoreSizeXcarchiveCheckAction::MAX_SEGMENT_7_TO_8 + 1) expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: report, max_wifi_size: 0) }.to raise_error(FastlaneCore::Interface::FastlaneTestFailure) end it 'breaks if ios >= 9 and size exceed' do report = make_segments_report([9, 0, 0], Fastlane::Actions::StoreSizeXcarchiveCheckAction::MAX_TEXT_9_PLUS + 1, 0) expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: report, max_wifi_size: 0) }.to raise_error(FastlaneCore::Interface::FastlaneTestFailure) end it 'pass if ios <= 6 and size fits' do report = make_segments_report([6, 0, 0], Fastlane::Actions::StoreSizeXcarchiveCheckAction::MAX_TEXT_6_LESS, 0) expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: report, max_wifi_size: 0) }.not_to raise_error end it 'pass if 7 <= ios <= 8 and size fits' do report = make_segments_report([7, 0, 0], 0, Fastlane::Actions::StoreSizeXcarchiveCheckAction::MAX_SEGMENT_7_TO_8) expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: report, max_wifi_size: 0) }.not_to raise_error report = make_segments_report([8, 0, 0], 0, Fastlane::Actions::StoreSizeXcarchiveCheckAction::MAX_SEGMENT_7_TO_8) expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: report, max_wifi_size: 0) }.not_to raise_error end it 'pass if ios >= 9 and size fits' do report = make_segments_report([9, 0, 0], Fastlane::Actions::StoreSizeXcarchiveCheckAction::MAX_TEXT_9_PLUS, 0) expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: report, max_wifi_size: 0) }.not_to raise_error end end context "check Wi-Fi sizes" do it 'breaks if download size exceeds, ignore universal' do max = thinning_report["variants"].reject { |n, v| v["variantIds"].nil? }.map { |n, v| v["sizeCompressedApp"] }.max expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: thinning_report, max_wifi_size: max - 1, ignore_universal: true) }.to raise_error(FastlaneCore::Interface::FastlaneTestFailure) end it 'breaks if download size exceeds, check universal' do max = thinning_report["variants"].map { |n, v| v["sizeCompressedApp"] }.max expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: thinning_report, max_wifi_size: max - 1, ignore_universal: false) }.to raise_error(FastlaneCore::Interface::FastlaneTestFailure) end it 'pass if download size fits, ignore universal' do expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: thinning_report, ignore_universal: true) }.not_to raise_error end it 'pass if download size fits, check universal' do expect { Fastlane::Actions::StoreSizeXcarchiveCheckAction.run(report: thinning_report, ignore_universal: false) }.not_to raise_error end end end
59.128571
204
0.744866
643ae99b478011011002ba14dfb2bc3f7d230569
322
py
Python
example/3_decision_logic.py
waskitaTREK/python_bim_engineer
964023a69a26bdc462b5aaff5d05b4087abffcba
[ "MIT" ]
1
2021-06-09T04:39:18.000Z
2021-06-09T04:39:18.000Z
example/3_decision_logic.py
waskitaTREK/python_bim_engineer
964023a69a26bdc462b5aaff5d05b4087abffcba
[ "MIT" ]
null
null
null
example/3_decision_logic.py
waskitaTREK/python_bim_engineer
964023a69a26bdc462b5aaff5d05b4087abffcba
[ "MIT" ]
null
null
null
number = 5 numbers = [1,2,3,4,5] # if statement if number == 5: print(number) if len(numbers) == 5: print(numbers[3]) if number in numbers: # if 3 in [1,2,3,4,5] print("3 is here") # elif and else statement if number == 3: print("is 3") elif number == 5: print("is 5") else: print("not 3 & 5")
15.333333
43
0.574534
45c4e52b6d11492b4ca4b3af39e648ac643280a0
382
py
Python
Northq/Exercise1/Excercise1.py
Amr116/challenges
49cd92af5bc9f01c73e4615b37facced60c7bc48
[ "MIT" ]
null
null
null
Northq/Exercise1/Excercise1.py
Amr116/challenges
49cd92af5bc9f01c73e4615b37facced60c7bc48
[ "MIT" ]
null
null
null
Northq/Exercise1/Excercise1.py
Amr116/challenges
49cd92af5bc9f01c73e4615b37facced60c7bc48
[ "MIT" ]
null
null
null
def RemovesNthDupicate(array, n): hashTable = {} i = 0 while i < len(array): if array[i] in hashTable: hashTable[array[i]] += 1 if hashTable[array[i]] == n: hashTable[array[i]] = 1 array.pop(i) else: hashTable[array[i]] = 1 i += 1 return array
23.875
55
0.426702
525372213a9a96ecf0e8966bb5ad299a73fa9bd4
64
jbuilder
Ruby
app/views/members/show.json.jbuilder
mthorn/photo-store
4665be598113a6187e79a343f42cac1394bf9301
[ "MIT" ]
null
null
null
app/views/members/show.json.jbuilder
mthorn/photo-store
4665be598113a6187e79a343f42cac1394bf9301
[ "MIT" ]
3
2020-06-24T17:48:41.000Z
2021-09-27T20:40:03.000Z
app/views/members/show.json.jbuilder
mthorn/photo-store
4665be598113a6187e79a343f42cac1394bf9301
[ "MIT" ]
null
null
null
json.partial! 'member', library_membership: @library_membership
32
63
0.828125
960014c04b1670199b19aae57a6ba2c124ed1817
43
dart
Dart
lib/screens/screens.dart
alex-melnyk/flutter_state_machine
ecd68cd8b34c4009dafa0d3bbee0a402e010b94b
[ "BSD-3-Clause" ]
null
null
null
lib/screens/screens.dart
alex-melnyk/flutter_state_machine
ecd68cd8b34c4009dafa0d3bbee0a402e010b94b
[ "BSD-3-Clause" ]
null
null
null
lib/screens/screens.dart
alex-melnyk/flutter_state_machine
ecd68cd8b34c4009dafa0d3bbee0a402e010b94b
[ "BSD-3-Clause" ]
null
null
null
export 'cart.dart'; export 'catalog.dart';
14.333333
22
0.72093
769dd4746a737152ff2a5a7443df7db5a03e3e48
4,043
lua
Lua
game/manager/managerEnum.lua
lualcs/xsServer
dc774f9f4364b5a24924c9ce5293d7cf5265c2d4
[ "MIT" ]
1
2021-02-08T12:27:24.000Z
2021-02-08T12:27:24.000Z
game/manager/managerEnum.lua
lualcs/xsServer
dc774f9f4364b5a24924c9ce5293d7cf5265c2d4
[ "MIT" ]
null
null
null
game/manager/managerEnum.lua
lualcs/xsServer
dc774f9f4364b5a24924c9ce5293d7cf5265c2d4
[ "MIT" ]
1
2022-01-23T05:14:55.000Z
2022-01-23T05:14:55.000Z
--[[ file:gameEnum.lua desc:游戏枚举 auth:Caorl Luo ]] local class = require("class") ---@class managerEnum @游戏枚举 local managerEnum = class() local this = managerEnum ---构造 function managerEnum:ctor() end ---重启 function managerEnum:dataReboot() end ---同意 ---@return senum function managerEnum.agree() return "agree" end ---拒绝 ---@return senum function managerEnum.refuse() return "refuse" end ---服务 ---@return senum function managerEnum.mapServices() return "mapServices" end ---联盟 ---@return senum function managerEnum.club() return "club" end ---代理 ---@return senum function managerEnum.admin() return "admin" end ---成员 ---@return senum function managerEnum.member() return "member" end ---单人 ---@return senum function managerEnum.assignSingle() return "assignSingle" end ---百人 ---@return senum function managerEnum.assignHundred() return "assignHundred" end ---竞技 ---@return senum function managerEnum.assignKilling() return "assignKilling" end ---错误消息 ---@return senum function managerEnum.error() return "error" end ---成功 ---@return senum function managerEnum.succeed() return "succeed" end ---心跳 ---@return senum function managerEnum.heartbeat() return "heartbeat" end ---登陆消息 ---@return senum function managerEnum.login() return "login" end ---大厅消息 ---@return senum function managerEnum.lobby() return "lobby" end ---桌子消息 ---@return senum function managerEnum.competition() return "table" end ---离线 ---@return senum function managerEnum.offline() return "offline" end ---在线 ---@return senum function managerEnum.online() return "online" end ---邀请 ---@return senum function managerEnum.invite() return "invite" end ---聊天 ---@return senum function managerEnum.chat() return "chat" end ---比赛 ---@return senum function managerEnum.competition() return "competition" end ---参与 ---@return senum function managerEnum.join() return "join" end ---游客 ---@return senum function managerEnum.tourists() return "tourists" end ---手机 ---@return senum function managerEnum.phone() return "phone" end ---微信 ---@return senum function managerEnum.wechat() return "wechat" end ---创建 ---@return senum function managerEnum.create() return "create" end ---删除 ---@return senum function managerEnum.delete() return "delete" end ---机器人 ---@return senum function managerEnum.robot() return "robot" end ---真人 ---@return senum function managerEnum.player() return "player" end ---root ---@return senum function managerEnum.root() return "root" end ---admin ---@return senum function managerEnum.admin() return "admin" end ---游客登录 ---@return senum function managerEnum.c2s_loginTourists() return "c2s_loginTourists" end ---账号登录 ---@return senum function managerEnum.c2s_loginAccount() return "c2s_loginAccount" end ---手机登录 ---@return senum function managerEnum.c2s_loginPhone() return "c2s_loginPhone" end ---微信登陆 ---@return senum function managerEnum.c2s_loginWeChat() return "c2s_loginWeChat" end ---登陆结果 ---@return senum function managerEnum.s2c_loginResult() return "s2c_loginResult" end ---联盟信息 ---@return senum function managerEnum.s2c_clubInfo() return "s2c_clubInfo" end ---代理信息 ---@return senum function managerEnum.s2c_adminInfo() return "s2c_adminInfo" end ---联盟成员 ---@return senum function managerEnum.s2c_memberInfo() return "s2c_memberInfo" end ---更改昵称 ---@return senum function managerEnum.c2s_changeNickname() return "c2s_changeNickname" end ---更新头像 ---@return senum function managerEnum.c2s_changeLogolink() return "c2s_changeLogolink" end ---联盟信息 ---@return senum function managerEnum.c2s_clubBase() return "c2s_clubBase" end ---联盟信息 ---@return senum function managerEnum.s2c_clubBase() return "s2c_clubBase" end ---联盟数据 ---@return senum function managerEnum.c2s_clubClubs() return "c2s_clubClubs" end ---联盟数据 ---@return senum function managerEnum.s2c_clubClubs() return "s2c_clubClubs" end return managerEnum
13.893471
41
0.705664
f454d654960b869a7710deb31da5eaa6c7b8dd24
4,164
tsx
TypeScript
src/Box/box.stories.tsx
ParishConnect/ui
8c56a2f27ae011551f3466f5e75d79bc85209b1c
[ "MIT" ]
null
null
null
src/Box/box.stories.tsx
ParishConnect/ui
8c56a2f27ae011551f3466f5e75d79bc85209b1c
[ "MIT" ]
null
null
null
src/Box/box.stories.tsx
ParishConnect/ui
8c56a2f27ae011551f3466f5e75d79bc85209b1c
[ "MIT" ]
null
null
null
import React from 'react' import { Text, Strong } from '../Text' import { Box } from './Box' import { Pane } from './Pane' import { Card } from './Card' import { Theme } from '../theme' import { motion } from 'framer-motion' export default { title: 'Box', component: Box, } const colors = ['blue', 'red', 'purple', 'gray', 'orange', 'yellow', 'teal', 'green'] export const box = () => { return ( <Box display="grid" gridTemplateColumns="repeat(auto-fit, 200px)" gridGap={3}> {colors.map(color => ( <Box key={color} size={25} backgroundColor={color} padding={3}> <Text color="white" level={600}> {color} </Text> </Box> ))} </Box> ) } export const animatedbox = () => ( <Box margin={20} size={20} padding={2} tint as={motion.div} animate={{ scale: [1, 2, 2, 1, 1], rotate: [0, 0, 270, 270, 0], borderRadius: ['20%', '20%', '50%', '50%', '20%'], }} transition={{ duration: 2, ease: 'easeInOut', times: [0, 0.2, 0.5, 0.8, 1], loop: Infinity, repeatDelay: 1, }} > This is a box rendered as a motion div </Box> ) export const Panes = () => ( <Box margin={3}> <Text display="block" my={2}> Pane composes the {`<Box/>`} component and adds a few helper props </Text> <Strong level={500} marginBottom={2}> Borders </Strong> <Box display="grid" gridTemplateColumns="repeat(auto-fit, 150px)" gridGap={3}> {['border', 'borderTop', 'borderBottom', 'borderRight', 'borderLeft'].map(b => ( <Pane padding={2} {...{ [b]: true }}> <Text>{b}</Text> </Pane> ))} </Box> <Strong level={500} marginY={2}> Borders (muted) </Strong> <Box display="grid" gridTemplateColumns="repeat(auto-fit, 150px)" gridGap={3}> {['border', 'borderTop', 'borderBottom', 'borderRight', 'borderLeft'].map(b => ( <Pane padding={2} {...{ [b]: 'muted' }}> <Text>{b}</Text> </Pane> ))} </Box> <Strong mt={2} level={500}> Tints </Strong> <Text display="block" marginBottom={2}> Borders are added thematically </Text> <Box display="grid" gridTemplateColumns="repeat(auto-fit, 150px)" gridGap={3}> {new Theme().themeColors.map(b => ( <Pane padding={2} tint={b} border> <Text>{b}</Text> </Pane> ))} </Box> <Strong mt={2} level={500}> Gradients </Strong> <Text display="block" marginBottom={2}> Text color is adapted based on luminance </Text> <Box display="grid" gridTemplateColumns="repeat(auto-fit, 150px)" gridGap={3}> {new Theme().themeColors.map(b => ( <Pane padding={2} gradient={b}> <Text>{b}</Text> </Pane> ))} </Box> <Strong level={500} marginY={2}> Elevations </Strong> <Box display="grid" gridTemplateColumns="repeat(auto-fit, 150px)" gridGap={3}> {[0, 1, 2, 3, 4].map(e => ( <Pane key={e} elevation={e} padding={2} height={10}> <Text>{e}</Text> </Pane> ))} </Box> <Strong level={500} marginY={2}> Hover Elevations </Strong> <Box display="grid" gridTemplateColumns="repeat(auto-fit, 150px)" gridGap={3}> {[0, 1, 2, 3, 4].map(e => ( <Pane key={e + 'hover'} hoverElevation={e} elevation={0} padding={2} height={10}> <Text>{e}</Text> </Pane> ))} </Box> <Strong level={500} marginY={2}> Active Elevation </Strong> <Box display="grid" gridTemplateColumns="repeat(auto-fit, 150px)" gridGap={3}> <Pane activeElevation={3} elevation={0} padding={2} height={10}> <Text>Click or Focus</Text> </Pane> </Box> </Box> ) export const Cards = () => ( <Box margin={3}> <Text my={2}> Card composes the {`<Pane/>`} component but with a default border according to its size </Text> <Card border tint height={25} width={35} p={3} hoverElevation={4} activeElevation={2} elevation={3} > A Card component </Card> </Box> )
26.864516
93
0.534342
38b74cfea2e9d95588f18ac693ee488ceb70cd2a
8,698
php
PHP
admin/service/edit.php
dikalasenjadatang/PANEL-SMM
a0f7db4e1b2b4a213e32e48ed632e474db33589a
[ "CC-BY-3.0" ]
2
2021-12-08T16:25:01.000Z
2021-12-22T05:40:47.000Z
admin/service/edit.php
haimaslian/PANEL-SMM
a0f7db4e1b2b4a213e32e48ed632e474db33589a
[ "CC-BY-3.0" ]
null
null
null
admin/service/edit.php
haimaslian/PANEL-SMM
a0f7db4e1b2b4a213e32e48ed632e474db33589a
[ "CC-BY-3.0" ]
1
2022-03-31T08:58:08.000Z
2022-03-31T08:58:08.000Z
<?php session_start(); require("../../mainconfig.php"); $msg_type = "nothing"; if (isset($_SESSION['user'])) { $sess_username = $_SESSION['user']['username']; $check_user = mysqli_query($db, "SELECT * FROM users WHERE username = '$sess_username'"); $data_user = mysqli_fetch_assoc($check_user); if (mysqli_num_rows($check_user) == 0) { header("Location: ".$cfg_baseurl."logout.php"); } else if ($data_user['status'] == "Suspended") { header("Location: ".$cfg_baseurl."logout.php"); } else if ($data_user['level'] != "Developers") { header("Location: ".$cfg_baseurl); } else { if (isset($_GET['sid'])) { $post_sid = $_GET['sid']; $checkdb_service = mysqli_query($db, "SELECT * FROM services WHERE sid = '$post_sid'"); $datadb_service = mysqli_fetch_assoc($checkdb_service); if (mysqli_num_rows($checkdb_service) == 0) { header("Location: ".$cfg_baseurl."admin/services.php"); } else { if (isset($_POST['edit'])) { $post_cat = $_POST['category']; $post_service = $_POST['service']; $post_note = $_POST['note']; $post_min = $_POST['min']; $post_max = $_POST['max']; $post_price = $_POST['price']; $post_pid = $_POST['pid']; $post_provider = $_POST['provider']; $post_status = $_POST['status']; if (empty($post_service) || empty($post_note) || empty($post_min) || empty($post_max) || empty($post_price) || empty($post_pid) || empty($post_provider)) { $msg_type = "error"; $msg_content = "<b>Gagal:</b> Mohon mengisi input."; } else if ($post_status != "Active" AND $post_status != "Not active") { $msg_type = "error"; $msg_content = "<b>Gagal:</b> Input tidak sesuai."; } else { $update_service = mysqli_query($db, "UPDATE services SET category = '$post_cat', service = '$post_service', note = '$post_note', min = '$post_min', max = '$post_max', price = '$post_price', status = '$post_status', pid = '$post_pid', provider = '$post_provider' WHERE sid = '$post_sid'"); if ($update_service == TRUE) { $msg_type = "success"; $msg_content = "<b>Berhasil:</b> Layanan berhasil diubah.<br /><b>Service ID:</b> $post_sid<br /><b>Service Name:</b> $post_service<br /><b>Category:</b> $post_cat<br /><b>Note:</b> $post_note<br /><b>Min:</b> ".number_format($post_min,0,',','.')."<br /><b>Max:</b> ".number_format($post_max,0,',','.')."<br /><b>Price/1000:</b> Rp ".number_format($post_price,0,',','.')."<br /><b>Provider ID:</b> $post_pid<br /><b>Provider Code:</b> $post_provider<br /><b>Status:</b> $post_status"; } else { $msg_type = "error"; $msg_content = "<b>Gagal:</b> Error system."; } } } $checkdb_service = mysqli_query($db, "SELECT * FROM services WHERE sid = '$post_sid'"); $datadb_service = mysqli_fetch_assoc($checkdb_service); include("../../lib/header.php"); ?> <div class="col-md-12"> <div class="card"> <div class="card-body"> <h3 class="card-title"><i class="fa fa-edit"></i> Ubah Layanan</h3> </div> <div class="card-body"> <?php if ($msg_type == "success") { ?> <div class="alert alert-success"> <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> <i class="fa fa-check-circle"></i> <?php echo $msg_content; ?> </div> <?php } else if ($msg_type == "error") { ?> <div class="alert alert-danger"> <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> <i class="fa fa-times-circle"></i> <?php echo $msg_content; ?> </div> <?php } ?> <form class="form-horizontal" role="form" method="POST"> <div class="form-group"> <label class="col-md-2 control-label">Service ID</label> <div class="col-md-10"> <input type="text" class="form-control" placeholder="Service ID" value="<?php echo $datadb_service['sid']; ?>" readonly> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">Service Name</label> <div class="col-md-10"> <input type="text" class="form-control" name="service" placeholder="Service Name" value="<?php echo $datadb_service['service']; ?>"> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">Category</label> <div class="col-md-10"> <select class="form-control" name="category"> <option value="<?php echo $datadb_service['category']; ?>"><?php echo $datadb_service['category']; ?> (Selected)</option> <?php $check_cat = mysqli_query($db, "SELECT * FROM service_cat ORDER BY name ASC"); while ($data_cat = mysqli_fetch_assoc($check_cat)) { ?> <option value="<?php echo $data_cat['code']; ?>"><?php echo $data_cat['name']; ?></option> <?php } ?> </select> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">Note</label> <div class="col-md-10"> <input type="text" class="form-control" name="note" placeholder="Note" value="<?php echo $datadb_service['note']; ?>"> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">Min Order</label> <div class="col-md-10"> <input type="number" class="form-control" name="min" placeholder="Min Order" value="<?php echo $datadb_service['min']; ?>"> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">Max Order</label> <div class="col-md-10"> <input type="number" class="form-control" name="max" placeholder="Max Order" value="<?php echo $datadb_service['max']; ?>"> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">Price/1000</label> <div class="col-md-10"> <input type="number" class="form-control" name="price" placeholder="Price/1000" value="<?php echo $datadb_service['price']; ?>"> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">Provider ID</label> <div class="col-md-10"> <input type="text" class="form-control" name="pid" placeholder="Provider ID" value="<?php echo $datadb_service['pid']; ?>"> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">Provider Code</label> <div class="col-md-10"> <select class="form-control" name="provider"> <option value="<?php echo $datadb_service['provider']; ?>"><?php echo $datadb_service['provider']; ?> (Selected)</option> <?php $check_prov = mysqli_query($db, "SELECT * FROM provider"); while ($data_prov = mysqli_fetch_assoc($check_prov)) { ?> <option value="<?php echo $data_prov['code']; ?>"><?php echo $data_prov['code']; ?></option> <?php } ?> </select> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">Status</label> <div class="col-md-10"> <select class="form-control" name="status"> <option value="<?php echo $datadb_service['status']; ?>"><?php echo $datadb_service['status']; ?> (Selected)</option> <option value="Active">Active</option> <option value="Not active">Not active</option> </select> </div> </div> <a href="<?php echo $cfg_baseurl; ?>admin/services.php" class="btn btn-info btn-bordered waves-effect w-md waves-light">Kembali ke daftar</a> <div class="pull-right"> <button type="reset" class="btn btn-danger btn-bordered waves-effect w-md waves-light">Ulangi</button> <button type="submit" class="btn btn-success btn-bordered waves-effect w-md waves-light" name="edit">Ubah</button> </div> </form> </div> </div> </div> </div> <!-- end row --> <?php include("../../lib/footer.php"); } } else { header("Location: ".$cfg_baseurl."admin/news.php"); } } } else { header("Location: ".$cfg_baseurl); } ?>
46.763441
491
0.542309
0765bda4c8b50f3a2ecfd180cd36a783dfd20786
107
rb
Ruby
test/rails/excludes/postgresql/PostgreSQLExplainTest.rb
deezzer/activerecord-jdbc-adapter
4e8d06a4466a28cad7b0a0b0dac409b2611129fe
[ "BSD-2-Clause" ]
null
null
null
test/rails/excludes/postgresql/PostgreSQLExplainTest.rb
deezzer/activerecord-jdbc-adapter
4e8d06a4466a28cad7b0a0b0dac409b2611129fe
[ "BSD-2-Clause" ]
null
null
null
test/rails/excludes/postgresql/PostgreSQLExplainTest.rb
deezzer/activerecord-jdbc-adapter
4e8d06a4466a28cad7b0a0b0dac409b2611129fe
[ "BSD-2-Clause" ]
2
2019-09-11T13:54:13.000Z
2022-02-20T17:10:46.000Z
exclude :test_explain_with_eager_loading, 'test checks for $1 instead of ? when using prepared statements'
53.5
106
0.82243
ffb8ace7e263c7bd7949763625b33c44161d06c9
17,072
py
Python
src/data/data_studio.py
decisionscients/Airbnb
f61bc76e4d2806bb827f625fd4acbf14e783b97e
[ "BSD-3-Clause" ]
null
null
null
src/data/data_studio.py
decisionscients/Airbnb
f61bc76e4d2806bb827f625fd4acbf14e783b97e
[ "BSD-3-Clause" ]
null
null
null
src/data/data_studio.py
decisionscients/Airbnb
f61bc76e4d2806bb827f625fd4acbf14e783b97e
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # ============================================================================ # # Project : Airbnb # # Version : 0.1.0 # # File : data_classes.py # # Python : 3.8.0 # # ---------------------------------------------------------------------------- # # Author : John James # # Company: DecisionScients # # Email : jjames@decisionscients.com # # ---------------------------------------------------------------------------- # # Created : Monday, 6th January 2020 11:38:57 am # # Last Modified: Monday, 6th January 2020 11:50:59 am # # Modified By : John James (jjames@decisionscients.com>) # # ---------------------------------------------------------------------------- # # License: BSD # # Copyright (c) 2020 DecisionScients # # ============================================================================ # """Data cleaning, transforming, and analysis for machine learning. This module includes a Data Object abstraction, support for data cleaning and preparation as well as analysis and inference capabilities commonly performed during end-to-end analysis and machine learning projects. This analysis and modeling framework centers upon three capabilities: 1. Data as Objects : Data organized and managed as objects and metadata 2. Data Curation : Cleaning, transforming, normalizing and curating 3. Data Influence : Data-driven learning and change. Accordingly, the core offering is the Data object model, a composite data class that integrates basic analysis and metadata. Data processing and development functionality extends the data objects as they move through the AI process. An analysis and inference module is about inference, insight, and storytelling. """ #%% from datetime import datetime import os from pathlib import Path import platform import psutil import site import time import uuid PROJECT_DIR = Path(__file__).resolve().parents[1] site.addsitedir(PROJECT_DIR) from abc import ABC, abstractmethod from collections import OrderedDict import pandas as pd pd.set_option('display.max_columns', None) from src.analysis.univariate import Describe from src.data.file_classes import File from src.utils.system import get_size from .constants import DTYPES # --------------------------------------------------------------------------- # # DataComponent # # --------------------------------------------------------------------------- # """Abstract class that defines the interface for all Data classes. Parameters ---------- name : str The name to assign to the DataComponent object df : DataFrame The DataFrame containing the data """ class DataComponent(ABC): def __init__(self, path): self._id = uuid.uuid4() self._name = os.path.basename(path) self._path = path self._df = pd.DataFrame() self._summary = pd.DataFrame() # meta data self._metadata = {} self._metadata['name'] = os.path.basename(path) self._metadata['path'] = path self._metadata['creator'] = os.getlogin() self._metadata['created'] = time.ctime(os.path.getctime(__file__)) self._metadata['modifier'] = os.getlogin() self._metadata['modified'] = time.ctime(os.path.getmtime(__file__)) def metadata(self): """Prints object metadata.""" print("\n#","="*30, "Author Information", "="*30,"#") print(f"Id: {self._id}") print(f"Creator: {self._creator}") print(f"Created: {self._created}") print(f"Modifier: {self._modifier}") print(f"Modified: {self._modified}") @property def name(self): return self._name @name.setter def name(self, value): self._name = value return self @abstractmethod def summarize(self): pass @abstractmethod def get_data(self, name): """Returns the Data object designated by the name.""" pass @abstractmethod def add(self, data): pass @abstractmethod def remove(self, name): pass # --------------------------------------------------------------------------- # # DataCollection # # --------------------------------------------------------------------------- # class DataCollection(DataComponent): """The Composite of the Data Object Model.""" def __init__(self, name): super(DataCollection, self).__init__(name) self._data_collection = OrderedDict() def merge_data(self): """Merges all DataSets and DataCollections into a single DataFrame.""" merged = pd.DataFrame() for _, data_object in self._data_collection.items(): df = data_object.get_data() merged = pd.concat([merged,df], axis=0) return merged def metadata(self): """Prints DataCollection metadata.""" super(DataCollection, self).metadata(verbose) print("="*30, "DataType Summary", "="*30) merged = self._merge_data() metadata = pd.DataFrame() metadata[self._name] = merged.dtypes.value_counts() print(metadata) return metadata def summarize(self): """Descriptive summaries for DataCollection and DataSet objects. Parameters ---------- verbose : Bool True if the summary should be printed. Returns ------- Dict : Cointaining quantitative and qualitative descriptive statistics. """ describe = Describe() df = self.merge_data() describe.fit(df) summary = describe.get_analysis() print("#","=*35 Quantitative Analysis 35*=","#") print(summary['quant']) print("#","=*35 Quantitative Analysis 35*=","#") print(summary['qual']) return summary def get_data(self, name=None): """Return all data or the named dataset or collection. Parameters ---------- name : str The name of the DataSet or DataCollection object. """ if name: return self._data_collection[name] else: return self._data_collection def add(self, data): """Adds a DataSet or DataCollection object to the collection. Parameters ---------- dataset : DataSet or DataCollection object. """ name = data.name self._data_collection[name] = data return self def remove(self, name): """Removes a DataSet or DataCollection object from the collection.""" del self._data_collection[name] return self def replace_string(self, pattern, replace, columns=None, regex=True): """Regex capable, string replace method for DataSet objects. Parameters ---------- pattern : str A (regex) pattern to find in the DataSet or designated columns. replace : str A string sequence to replace the pattern columns : array-like (Optional) List of columns to which the replacement should be applied. regex : Bool Indicates whether the pattern and replacement are valid regex. """ for _, data_object in self._data_collection.items(): if columns: data_object.replace_string(pattern, replace, columns, regex) else: data_object.replace_string(pattern, replace, regex) self._add(data_object) def cast_types(self, data_types): """Cast objects of the dataframe to designated types.""" for _, data_object in self._data_collection.items(): data_object.cast_types(data_types) self._add(data_object) def import_data(self, directory, columns=None): """Creates DataSet objects, imports the data and adds the DataSets. Parameters ---------- directory : str The directory containing the files to import. columns : list List of column names to return. """ filenames = os.listdir(directory) for filename in filenames: name = filename.split(".")[0] dataset = DataSet(name=name) path = os.path.join(directory, filename) dataset.import_data(filename=path, columns=columns) self.add(data=dataset) return self def export_data(self, directory, file_format='csv'): """Exports the data from contained DataSets to the directory in format. Parameters ---------- directory : str The directory to which the data will be exported. file_format : str The format in which the data will be saved. """ for name, dataset in self._data_collection.items(): filename = name + "." + file_format path = os.path.join(directory, filename) dataset.export_data(filename=path) return self # --------------------------------------------------------------------------- # # DataSet # # --------------------------------------------------------------------------- # class DataSet(DataComponent): """Base class for all DataSet subclasses. Parameters ---------- name : str The name of the dataset. df : DataFrame (Optional) The content in DataFrame format. """ def __init__(self, name): super(DataSet, self).__init__(name) def metadata(self): """Prints DataSet metadata.""" super(DataSet, self).metadata() print("#","="*30, "DataType Summary", "="*30,"#") metadata = pd.DataFrame() metadata[self._name] = self._df.dtypes.value_counts() print(metadata) print("#","="*30, "DataType Detail", "="*30,"#") metadata = pd.DataFrame() metadata[self._name] = self._df.dtypes.T print(metadata) return metadata def summarize(self, verbose=True): """Prints DataSet descriptive statistics.""" describe = Describe() describe.fit(self) summary = describe.get_analysis() if verbose: print("\n#=*35 Quantitative Analysis 35*=#") print(summary['quant']) print("#=*35 Qualitative Analysis 35*=#") print(summary['qual']) return summary def add(self, data): pass def remove(self, name): pass def replace_string(self, pattern, replace, columns=None, regex=True): """Regex capable, string replace method for DataSet objects. Parameters ---------- pattern : str A (regex) pattern to find in the DataSet or designated columns. replace : str A string sequence to replace the pattern columns : array-like (Optional) List of columns to which the replacement should be applied. regex : Bool Indicates whether the pattern and replacement are valid regex. """ if columns: self._df[columns] = self._df[columns].replace({pattern:replace}, regex=regex) else: self._df = self._df.replace({pattern:replace}, regex=regex) def import_data(self, filename, columns=None): """Reads the data from filename and appends it to the dataframe member.""" f = File() df = f.read(filename, columns=columns) self._df = pd.concat([self._df, df], axis=0, sort=False) return self def export_data(self, filename): """Writes the data to the location designated by the filename.""" f = File() f.write(filename, self._df) return self def get_data(self, attribute=None): """Method to return all data or one, or more attributes. Parameters ---------- attribute : str or list (Optional) The attribute or attributes to retrieve Returns ------- DataFrame or Series """ if attribute is not None: return self._df[attribute] return self._df from .constants import DTYPES # --------------------------------------------------------------------------- # # TYPE CASTER # # --------------------------------------------------------------------------- # class TypeCaster(): """Type casting, conversions, normalization, standardization, transformation.""" types = ["BOOL", "CATEGORY", "DATETIME", "FLOAT", "INT", "OBJECT"] def cast_bool(self, df, labels): """Casts the labeled data as type boolean.""" for label in labels: df[label].astype('bool') return df def cast_category(self, df, labels): """Casts the labeled data as type category.""" for label in labels: df[label].astype('category') return df def cast_datetime(self, df, labels): """Casts the labeled data as type datetime.""" for label in labels: pd.to_datetime(df[[labels]]) return df def cast_float(self, df, labels): """Casts the labeled data as type float.""" for label in labels: df[label]astype('float') return df def cast_int(self, df, labels): """Casts the labeled data as type integer.""" for label in labels: df[label]astype('int') return df def cast_object(self, df, labels): """Casts the labeled data as type integer.""" for label in labels: df[label]astype('object') return df # --------------------------------------------------------------------------- # # QUANT STUDIO # # --------------------------------------------------------------------------- # class QuantStudio(ABC): """Abstract base class and interface for the treatment of quantitative data.""" def __init__(self, name): self._id = uuid.uuid4() self._name = name self._creator = os.getlogin() self._created = time.ctime(os.path.getctime(__file__)) self._modifier = os.getlogin() self._modified = time.ctime(os.path.getmtime(__file__)) def fit(dataset, y=None): pass def transform(dataset, y=None): pass def reverse(dataset, y=None): pass # --------------------------------------------------------------------------- # # RINSE DATA # # --------------------------------------------------------------------------- # class RinseData(QuantStudio): """Basic hygeine for quantitativae data.""" def __init__(self, name): super(RinseData, self).__init__(name) vars = [price,weekly_price, monthly_price, security_deposit, cleaning_fee, extra_people] df = dataset.get_data() for var in vars: df[var] = df[var].str.replace(',', '') df[var] = df[var].str.replace('$', '') df[var] = df[var].str.replace('%', '') dataset.add(df) return dataset # --------------------------------------------------------------------------- # # DATA SERVER # # --------------------------------------------------------------------------- # def serve_data(): """Serves the data forward during the preliminary inspection.""" for year, directory in Constants.SFO.items(): for filename in os.listdir(directory): name = "_".join(filename.split("_")[1:4]) dataset = DataSet(name=name) dataset.import_data(os.path.join(directory, filename)) dataset = number_rince(dataset) dataset = text_rince(dataset) dataset = type_cast(dataset) dataset = format_data(dataset) dataset = select_data(dataset) dataset = check_data(dataset)
34.840816
89
0.508259
46c0592185cecc7b9fe3f64bca818b5cb488f910
402
py
Python
public_tool/random_cut.py
mapicccy/Stock-Market-Trend-Analysis-Using-HMM-LSTM
5be0f294208d727d5a3e28b0e99496d056102b4c
[ "MIT" ]
147
2018-08-27T09:05:07.000Z
2022-03-27T13:06:16.000Z
public_tool/random_cut.py
mapicccy/Stock-Market-Trend-Analysis-Using-HMM-LSTM
5be0f294208d727d5a3e28b0e99496d056102b4c
[ "MIT" ]
null
null
null
public_tool/random_cut.py
mapicccy/Stock-Market-Trend-Analysis-Using-HMM-LSTM
5be0f294208d727d5a3e28b0e99496d056102b4c
[ "MIT" ]
70
2018-09-10T03:12:54.000Z
2022-03-26T06:46:48.000Z
import random def random_cut(X, y, k_fold=5): # 随机切片,用于CV # output: # X_train, y_train, X_valid, y_valid temp = [i for i in range(X.shape[0])] random.shuffle(temp) temp_index = int(len(temp) / k_fold) X_train, y_train = X[temp_index:], y[temp_index:] X_valid, y_valid = X[:temp_index], y[:temp_index] return X_train, y_train, X_valid, y_valid
25.125
54
0.616915
5d2a22a3ee1d87aaad98253af00bf68a0238fa0e
2,820
cpp
C++
libs/network/src/p2pservice/identity_cache.cpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/network/src/p2pservice/identity_cache.cpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/network/src/p2pservice/identity_cache.cpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
2
2019-11-13T10:55:24.000Z
2019-11-13T11:37:09.000Z
//------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "network/p2pservice/identity_cache.hpp" #include <algorithm> #include <iterator> namespace fetch { namespace p2p { void IdentityCache::Update(ConnectionMap const &connections) { FETCH_LOCK(lock_); for (auto const &element : connections) { auto const &address = element.first; auto const &uri = element.second; UpdateInternal(address, uri); } } void IdentityCache::Update(Address const &address, Uri const &uri) { FETCH_LOCK(lock_); UpdateInternal(address, uri); } bool IdentityCache::Lookup(Address const &address, Uri &uri) const { bool success = false; FETCH_LOCK(lock_); auto it = cache_.find(address); if (it != cache_.end()) { uri = it->second.uri; success = true; } return success; } IdentityCache::AddressSet IdentityCache::FilterOutUnresolved(AddressSet const &addresses) { AddressSet resolvedAddresses; { FETCH_LOCK(lock_); std::copy_if(addresses.begin(), addresses.end(), std::inserter(resolvedAddresses, resolvedAddresses.begin()), [this](Address const &address) { bool resolved = false; auto it = cache_.find(address); if ((it != cache_.end()) && (it->second.uri.scheme() != Uri::Scheme::Muddle)) { resolved = true; } return resolved; }); } return resolvedAddresses; } void IdentityCache::UpdateInternal(Address const &address, Uri const &uri) { auto cache_it = cache_.find(address); if (cache_it != cache_.end()) { auto &cache_entry = cache_it->second; // if the cache entry exists them only update it if the if (uri.scheme() != Uri::Scheme::Muddle) { cache_entry.uri = uri; cache_entry.last_update = Clock::now(); cache_entry.resolve = false; // This entry is considered resolved } } else { cache_.emplace(address, uri); } } } // namespace p2p } // namespace fetch
25.87156
96
0.599645
a9e9f435f1ae71ea47a680612faceaa5686128ba
5,744
php
PHP
resources/views/header.blade.php
thanhhandsome/TeamWork-Laravel
6d7406f435be77ed0a3245dd27aed3bab6bf4ad7
[ "MIT" ]
null
null
null
resources/views/header.blade.php
thanhhandsome/TeamWork-Laravel
6d7406f435be77ed0a3245dd27aed3bab6bf4ad7
[ "MIT" ]
null
null
null
resources/views/header.blade.php
thanhhandsome/TeamWork-Laravel
6d7406f435be77ed0a3245dd27aed3bab6bf4ad7
[ "MIT" ]
null
null
null
<header id="header"><!--header--> <div class="header_top"><!--header_top--> <div class="container"> <div class="row col-sm-12"> <div class="col-sm-5"> <div class="contactinfo"> <ul class="nav nav-pills"> <li><a href="#"><i class="fa fa-phone"></i> =></a></li> <li><a href="https://github.com/buddylol123/webgiadung"><i class="fa fa-github"></i> Link GitHUB</a></li> </ul> </div> </div> <div class="col-sm-5"> <div class="social-icons pull-right"> <ul class="nav navbar-nav"> <li><a href="https://www.facebook.com/"><i class="fa fa-facebook"></i></a></li> <li><a href="https://twitter.com/"><i class="fa fa-twitter"></i></a></li> <li><a href="https://www.instagram.com/"><i class="fa fa-instagram"></i></a></li> <li><a href="https://accounts.google.com/"><i class="fa fa-google-plus"></i></a></li> </ul> </div> </div> </div> </div> </div><!--/header_top--> <div class="header-middle"><!--header-middle--> <div class="container"> <div class="row"> <div class="col-sm-12"> <form action="{{URL::to('/tim-kiem')}}" method="POST"> {{ csrf_field() }} <div class="search_box pull-right" > <input type="text" name="tukhoa" placeholder="Tìm kiếm sản phẩm" /> <input type="submit" name="search_items" style="margin-top: 0; color:#000" class="btn btn-primary btn-sm" value="Tìm"> </div> </form> <div class="shop-menu pull-right"> <ul class="nav navbar-nav"> <li><a href="{{URL::to('/trang-chu')}}" class="active">Trang chủ</a></li> <?php $customer = Session()->get('makh'); $email = Session()->get('name'); if($customer){ ?> <li><a href="{{URL::to('/check-history')}}"><i class="fa fa-crosshairs"></i>Đơn hàng</a></li> <li><a href="{{URL::to('/payment')}}"><i class="fa fa-crosshairs"></i> Thanh toán</a></li> <li><a href="{{URL::to('/show-cart')}}"><i class="fa fa-shopping-cart"></i> Giỏ hàng</a></li> <li><a href="{{ URL::to('/getinfo/'.Session()->get('makh')) }}"><i class="fa fa-user"></i><?php echo $email ?></a></li> <li><a href="{{URL::to('/dangxuat')}}"><i class="fa fa-sign-out"></i> Đăng xuất</a></li> <?php } else{ ?> <li><a href="{{URL::to('/dangnhap')}}"><i class="fa fa-lock"></i> Đăng nhập</a></li> <li><a href="{{URL::to('/dangky')}}"><i class="fa fa-lock"></i> Đăng ký</a></li> <li><a href="{{URL::to('/dangnhap')}}"><i class="fa fa-crosshairs"></i> Thanh toán</a></li> <li><a href="{{URL::to('/dangnhap')}}"><i class="fa fa-shopping-cart"></i> Giỏ hàng</a></li> <?php } ?> <li></li> </ul> </div> </div> </div> </div> </div><!--/header-middle--> <div class="header-bottom"><!--header-bottom--> </div><!--/header-bottom--> </header><!--/header--> <section> <div class="container"> <div class="row" style="margin-bottom: 20px"> <div class="col-sm-3"> <div class="left-sidebar"> <h2>Danh mục sản phẩm</h2> <div class="panel-group category-products" id="accordian"><!--category-productsr--> @foreach($cate_product as $key => $value) <div class="panel panel-default"> @if($value->category_parent=='0') <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordian" href="#{{$value->slug_loaisp}}"> <span class="badge pull-right"><i class="fa fa-plus"></i></span> {{$value->tenloai}} </a> </h4> </div> <div id="{{$value->slug_loaisp}}" class="panel-collapse collapse"> <div class="panel-body"> <ul> @foreach($cate_product as $key => $cate_sub) @if($cate_sub->category_parent==$value->maloai) <li><a href="{{URL::to('/danhmucsanpham/'.$cate_sub->slug_loaisp)}}"> {{$cate_sub->tenloai}} </a></li> @endif @endforeach </ul> </div> </div> @endif </div> @endforeach </div><!--/category-products--> <div class="brands_products"><!--brands_products--> <h2>Thương hiệu sản phẩm</h2> <div class="brands-name"> <ul class="nav nav-pills nav-stacked"> @foreach($brand_product as $key => $data) <li><a href="{{URL::to('/thuonghieusanpham/'.$data->mansx)}}">{{$data->tennsx}}</a></li> @endforeach </ul> </div> </div><!--/brands_products--> <div class="mass_products"> <h2 >Lọc theo kg</h2> <div class="mass-name"> <form> @csrf <ul class="nav nav-pills nav-stacked" name="sort" id="sort"> <!-- <option value="{{Request::url()}}?sort_by=none">lọc</option> --> <li><a style="color: black" href="{{Request::url()}}?sort_by=1-50">1kg-50kg</a></li> <li><a style="color: black" href="{{Request::url()}}?sort_by=100-500">100kg-500kg</a></li> </ul> </form> </div> </div> <div class="price-range"> <h2 for="amount" >Lọc giá theo</h2> <form> <div id="slider-range"></div> <style type="text/css"> .style-range p{ float: left; width: 37% } </style> <div class="style-range"> <p><input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;"></p> <input type="hidden" name="start_price" id="start_price"> <input type="hidden" name="end_price" id="end_price"> <br> <div class="clearfix"></div> <p><input type="submit" name="filter_price" value="Lọc giá" class="btn btn-sm btn-default"></p> </div> </form> </div> </div> </div> <div class="col-sm-9 padding-right"> @yield('content') </div> </div> </div> </section> <!-- {{URL::to('/danhmucsanpham/'.$value->maloai)}} -->
33.788235
125
0.54335
05b7a52ed67da4f0dbbcde07afc8cefe5f9a1cdd
9,306
py
Python
onetech/scriptsData/test/test.py
biddy1618/rasaOneTech
7276746f859093543be6a65872b5459c8812598e
[ "Apache-2.0" ]
null
null
null
onetech/scriptsData/test/test.py
biddy1618/rasaOneTech
7276746f859093543be6a65872b5459c8812598e
[ "Apache-2.0" ]
5
2020-01-28T22:55:13.000Z
2022-02-10T00:21:04.000Z
onetech/scriptsData/test/test.py
biddy1618/rasaOneTech
7276746f859093543be6a65872b5459c8812598e
[ "Apache-2.0" ]
null
null
null
import json import os import yaml import pickle import sys import argparse import requests import random import string PATH_DIALOGFLOW_DATA = './scriptsData/migration/modifiedDFData/intents' PATH_RESULTS_FILE = './scriptsData/test/results/results.txt' BOT_URL = 'http://chat.onedev.zone/bot/conversations/respond' BOT_URL_LOCAL = 'http://localhost:5005/conversations/respond' BOT_SERVER_USE = BOT_URL def testBot(local=False): global BOT_SERVER_USE BOT_SERVER_USE = BOT_URL_LOCAL if local else BOT_URL templates = {} intents = [] stories = {} for f in sorted(os.listdir(os.path.abspath(PATH_DIALOGFLOW_DATA))): if 'usersays' in f: name = f[:-17] if name not in templates: templates[name] = {} else: assert('responses' in templates[name]) with open(os.path.join((os.path.abspath(PATH_DIALOGFLOW_DATA)), f), 'r', encoding='utf-8') as f: data = json.loads(f.read()) expressions = [temp['data'][0]['text'] for temp in data] templates[name]['expressions'] = expressions continue with open(os.path.join((os.path.abspath(PATH_DIALOGFLOW_DATA)), f), 'r', encoding='utf-8') as f: data = json.loads(f.read()) name = data['name'] intents.append(name) assert(len(data['responses']) == 1) if len(data['contexts']) != 0: if name not in stories: stories[name] = {'input': [], 'output': []} if name not in stories: stories[name] = {'input': [], 'output': []} for inputContext in data['contexts']: if inputContext not in stories: stories[inputContext] = {'input': [], 'output': []} stories[name]['input'].append(inputContext) stories[inputContext]['output'].append(name) messages = [] buttons = [] for message in data['responses'][0]['messages']: if message['type'] == 0: if isinstance(message['speech'], list): for m in message['speech']: messages.append(m) else: messages.append(message['speech']) if message['type'] == 4: if 'quickReplyOptions' in message['payload']: for button in message['payload']['quickReplyOptions']: buttons.append(button['title']) elif 'chatControl' in message['payload']: for button in message['payload']['chatControl']['chatButtons']['buttons']: buttons.append(button['title']) if name not in templates: templates[name] = {} else: assert('expressions' in templates[name]) templates[name]['responses'] = messages templates[name]['buttons'] = buttons endIntensForStories = [] startIntentsForStories = [] for k, v in stories.items(): if len(v['output']) == 0: endIntensForStories.append(k) if len(v['input']) == 0: startIntentsForStories.append(k) storiesWhole = [] for s in endIntensForStories: story = [s] if len(stories[s]['input']) > 1: print(s) break temp = s while len(stories[temp]['input']) > 0: story.append(stories[temp]['input'][0]) temp = stories[temp]['input'][0] storiesWhole.append(story[::-1]) intentsStories = [] for v in storiesWhole: for i in v: intentsStories.append(i) storySingle = sorted(list(set(intents) - set(intentsStories))) with open(PATH_RESULTS_FILE, 'w') as f: print(f'Checking single-level stories ({len(storySingle)} stories):') f.write(f'Checking single-level stories ({len(storySingle)} stories):\n') successSingle = 0 for i, story in enumerate(storySingle): res = checkStory([story], templates) if res[0][0]: successSingle += 1 writeStoryResult(res, i, story, f) print(f'Checking multi-level stories ({len(storiesWhole)} stories):') f.write(f'Checking multi-level stories ({len(storiesWhole)} stories):\n') successMulti = 0 for i, story in enumerate(storiesWhole): res = checkStory(story, templates) if res[0][0]: successMulti += 1 writeStoryResult(res, i, story[-1], f) print(f'Out of {len(storySingle)} single-level stories {successSingle} were successfull ({100*successSingle/len(storySingle):.1f}% accuracy).') f.write(f'Out of {len(storySingle)} single-level stories {successSingle} were successfull ({100*successSingle/len(storySingle):.1f}% accuracy).\n') print(f'Out of {len(storiesWhole)} multi-level stories {successMulti} were successfull ({100*successMulti/len(storiesWhole):.1f}% accuracy).') f.write(f'Out of {len(storiesWhole)} multi-level stories {successMulti} were successfull ({100*successMulti/len(storiesWhole):.1f}% accuracy).\n') def id_generator(size=8, chars=string.ascii_letters + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def testCon(local=False): global BOT_SERVER_USE BOT_SERVER_USE = BOT_URL_LOCAL if local else BOT_URL sender_id = id_generator() expression = "Ты готова?" data = { 'query': expression, 'sender_id': sender_id } response = requests.post(BOT_SERVER_USE, data=json.dumps(data)).json()[0] print(response) def checkStory(story, templates): sender_id = id_generator() results = [] for s in story: expression = random.choice(templates[s]['expressions']) buttons = None if 'buttons' not in templates[s] else templates[s]['buttons'] if buttons is not None: query = {'expressions' :templates[s]['expressions'], 'expression': expression, \ 'responses': [r.strip().lower() for r in templates[s]['responses']], 'buttons': buttons} else: query = {'expressions' :templates[s]['expressions'], 'expression': expression, \ 'responses': [r.strip().lower() for r in templates[s]['responses']]} data = { 'query': expression, 'sender_id': sender_id } # try: response = requests.post(BOT_SERVER_USE, data=json.dumps(data)).json()[0] # except Exception as e: # response = {'text': 'fail'} result = { 'response': response['text'].strip().lower(), 'buttons': [r['title'] for r in response['buttons']] } if 'buttons' in response else {'response': response['text'].strip().lower()} results.append((expression, query['responses'], result['response'])) res = check(query, result) if res[0]: continue else: return (res, results) return (res, results) def check(query, result): if result['response'] not in query['responses']: return (False, 'response') if ('button' in query) != ('button' in result): return (False, 'buttons') if 'button' in query: for button in result['buttons']: if button not in query['buttons']: return (False, 'buttons') return (True, 'perfect') def writeStoryResult(res, i, story, file): if res[0][0]: print(f'{i+1} --> Successful story - {story}') file.write(f'{i+1} --> Successful story - {story}\n') else: print(f'{i+1} --> Failed story - {story}:') file.write(f'{i+1} --> Failed story - {story}:\n') for k in range(0, len(res[1])-1): temp = res[1][k] print(f'---{temp[0]}') file.write(f'---{temp[0]}\n') print(f'------{temp[2]}') file.write(f'------{temp[2]}\n') print(f'---{res[1][-1][0]}') file.write(f'---{res[1][-1][0]}\n') if res[0][1] == 'response': print('------Error - response mismatch') file.write('------Error - response mismatch\n') print(f'---------DF: {res[1][-1][1]}') file.write(f'---------DF: {res[1][-1][1]}\n') print(f'---------Rasa: {res[1][-1][2]}') file.write(f'---------Rasa: {res[1][-1][2]}\n') else: print('------Error - buttons mismatch') file.write('------Error - buttons mismatch\n') print(f'---------{res[1][-1][1]}') file.write(f'---------{res[1][-1][1]}\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Create Rasa Core train files from DialogFlow data') parser.add_argument('--test', action='store_true', help='test the server (check if it is up)') parser.add_argument('--local', action='store_true', help='start testing the local server (default remote)') args = parser.parse_args() if args.test: testCon(local=args.local) else: testBot(local=args.local)
36.069767
155
0.552762
cc7741fe1f9b88c4f9aaef770db245744aa28452
2,482
swift
Swift
Source/Layout/RandomAccessCollection+IntrinsicRun.swift
iosgoodproject/Tehreer-Cocoa
0980a6dddaa4cdf5415a0f1c826f973e730a74c3
[ "Apache-2.0" ]
32
2019-11-17T23:08:45.000Z
2022-01-25T08:52:59.000Z
Source/Layout/RandomAccessCollection+IntrinsicRun.swift
iosgoodproject/Tehreer-Cocoa
0980a6dddaa4cdf5415a0f1c826f973e730a74c3
[ "Apache-2.0" ]
8
2019-11-18T00:44:23.000Z
2021-10-12T17:32:46.000Z
Source/Layout/RandomAccessCollection+IntrinsicRun.swift
iosgoodproject/Tehreer-Cocoa
0980a6dddaa4cdf5415a0f1c826f973e730a74c3
[ "Apache-2.0" ]
10
2020-12-01T17:47:30.000Z
2022-03-10T15:58:51.000Z
// // Copyright (C) 2019-2020 Muhammad Tayyab Akram // // 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. // import CoreGraphics extension RandomAccessCollection where Element == IntrinsicRun, Index == Int { func binarySearchIndex(forCodeUnitAt index: Int) -> Int { var low = 0 var high = count - 1 while low <= high { let mid = (low + high) >> 1 let intrinsicRun = self[mid] let runRange = intrinsicRun.codeUnitRange if index >= runRange.upperBound { low = mid + 1 } else if index < runRange.lowerBound { high = mid - 1 } else { return mid } } return -1 } func binarySearchIndex(ofCharacterAt index: String.Index) -> Int { var low = 0 var high = count - 1 while low <= high { let mid = (low + high) >> 1 let intrinsicRun = self[mid] if index >= intrinsicRun.endIndex { low = mid + 1 } else if index < intrinsicRun.startIndex { high = mid - 1 } else { return mid } } return -1 } func measureCharacters(in codeUnitRange: Range<Int>) -> CGFloat { var extent: CGFloat = 0.0 if !codeUnitRange.isEmpty { var startIndex = codeUnitRange.lowerBound let endIndex = codeUnitRange.upperBound var runIndex = binarySearchIndex(forCodeUnitAt: startIndex) repeat { let intrinsicRun = self[runIndex] let segmentEnd = Swift.min(endIndex, intrinsicRun.codeUnitRange.upperBound) extent += intrinsicRun.measureCharacters(in: startIndex ..< segmentEnd) startIndex = segmentEnd runIndex += 1 } while startIndex < endIndex } return extent } }
29.2
91
0.571313
fa240238d0e3e24d89c3bb4725beee42accb3714
5,896
lua
Lua
udf/hyc_delete_rec_module.lua
CacheboxInc/aerospike-server.docker
f64140ced6ede81834f6a702e896debc7188d166
[ "Apache-2.0" ]
null
null
null
udf/hyc_delete_rec_module.lua
CacheboxInc/aerospike-server.docker
f64140ced6ede81834f6a702e896debc7188d166
[ "Apache-2.0" ]
5
2018-10-17T07:47:44.000Z
2020-04-17T10:13:42.000Z
udf/hyc_delete_rec_module.lua
CacheboxInc/aerospike-server.docker
f64140ced6ede81834f6a702e896debc7188d166
[ "Apache-2.0" ]
2
2018-04-25T07:41:31.000Z
2018-05-28T07:01:59.000Z
local function split(str, sep) local result = {} local regex = ("([^%s]+)"):format(sep) for each in str:gmatch(regex) do table.insert(result, each) end return result end function hyc_delete_rec(rec, input_ids) trace("HYC_UDF args:: (%s)--------------------", tostring(input_ids)); trace("HYC_UDF key:: (%s)--------------------", record.key(rec)); local rec_vmdkid = -1; rec_ckptid = -1; rec_offset = -1 local vals = split(record.key(rec), ":") local count = 0 for _,val in ipairs(vals) do if count == 0 then rec_vmdkid = tonumber(val) elseif count == 1 then rec_ckptid = tonumber(val) elseif count == 2 then rec_offset = tonumber(val) end count = count + 1 end trace("HYC_UDF Post split count : %d, vmdkid : %d, ckpt_id : %d, offset :%d", count, rec_vmdkid, rec_ckptid, rec_offset); if rec_vmdkid == -1 or rec_ckptid == -1 or rec_offset == -1 or count ~= 3 then trace("HYC_UDF Error, Invalid record format"); else local elem local result local input_vmdkid = -1; input_ckptid = -1 for elm in list.iterator(input_ids) do result = split(elm, ":") trace("HYC_UDF result:: (%s)--------------------", tostring(result)); count = 0 for _,val in ipairs(result) do if count == 0 then input_vmdkid = tonumber(val) elseif count == 1 then input_ckptid = tonumber(val) end count = count + 1 end trace("HYC_UDF input_vmdkid: %d rec_vmdkid: %d", tonumber(input_vmdkid), tonumber(rec_vmdkid)); trace("HYC_UDF input_ckptid: %d rec_ckptid: %d", tonumber(input_ckptid), tonumber(rec_ckptid)); if rec_vmdkid == input_vmdkid and (input_ckptid == 0 or rec_ckptid == input_ckptid) then trace("HYC_UDF found match ckpt ID :: %d, offset : %d", tonumber(rec_ckptid), rec_offset); aerospike:remove(rec) end end end end function hyc_delete_rec_bin_ext(rec, input_ids) trace("HYC_UDF args:: (%s)--------------------", tostring(input_ids)); trace("HYC_UDF key:: (%s)--------------------", record.key(rec)); names = record.bin_names(rec) for i, name in ipairs(names) do trace("HYC_UDF bin %d name = %s", i, tostring(name)) end local rec_vmdkid = -1; rec_ckptid = -1; rec_offset = -1 trace("HYC_UDF key_bin value is : %s", tostring(rec['Key'])); local vals = split(tostring(rec['Key']), ":") local count = 0 for _,val in ipairs(vals) do if count == 0 then rec_vmdkid = tonumber(val) elseif count == 1 then rec_ckptid = tonumber(val) elseif count == 2 then rec_offset = tonumber(val) end count = count + 1 end trace("HYC_UDF Post split count : %d, vmdkid : %d, ckpt_id : %d, offset :%d", count, rec_vmdkid, rec_ckptid, rec_offset); if rec_vmdkid == -1 or rec_ckptid == -1 or rec_offset == -1 or count ~= 3 then trace("HYC_UDF Error, Invalid record format"); else local elem local result local input_vmdkid = -1; input_ckptid = -1 for elm in list.iterator(input_ids) do result = split(elm, ":") trace("HYC_UDF result:: (%s)--------------------", tostring(result)); count = 0 for _,val in ipairs(result) do if count == 0 then input_vmdkid = tonumber(val) elseif count == 1 then input_ckptid = tonumber(val) end count = count + 1 end trace("HYC_UDF input_vmdkid: %d rec_vmdkid: %d", tonumber(input_vmdkid), tonumber(rec_vmdkid)); trace("HYC_UDF input_ckptid: %d rec_ckptid: %d", tonumber(input_ckptid), tonumber(rec_ckptid)); if rec_vmdkid == input_vmdkid and (input_ckptid == 0 or rec_ckptid == input_ckptid) then trace("HYC_UDF found match ckpt ID :: %d, offset : %d", tonumber(rec_ckptid), rec_offset); aerospike:remove(rec) end end end end function hyc_delete_rec_bin_ext_with_update_time(rec, input_ids) trace("HYC_UDF args:: (%s)--------------------", tostring(input_ids)); trace("HYC_UDF key:: (%s)--------------------", record.key(rec)); names = record.bin_names(rec) for i, name in ipairs(names) do trace("HYC_UDF bin %d name = %s", i, tostring(name)) end local rec_vmdkid = -1; rec_ckptid = -1; rec_offset = -1; rec_timestamp = -1 trace("HYC_UDF key_bin value is : %s", tostring(rec['Key'])); local vals = split(tostring(rec['Key']), ":") local count = 0 for _,val in ipairs(vals) do if count == 0 then rec_vmdkid = tonumber(val) elseif count == 1 then rec_ckptid = tonumber(val) elseif count == 2 then rec_offset = tonumber(val) end count = count + 1 end rec_timestamp = tonumber(rec['UpdateTime']) trace("HYC_UDF Post split count : %d, vmdkid : %d, ckpt_id : %d, offset :%d, timestamp: %d", count, rec_vmdkid, rec_ckptid, rec_offset, rec_timestamp); if rec_vmdkid == -1 or rec_ckptid == -1 or rec_offset == -1 or rec_timestamp == -1 or count ~= 3 then trace("HYC_UDF Error, Invalid record format"); else local elem local result local input_vmdkid = -1; input_ckptid = -1; input_timestamp = -1 for elm in list.iterator(input_ids) do result = split(elm, ":") trace("HYC_UDF result:: (%s)--------------------", tostring(result)); count = 0 for _,val in ipairs(result) do if count == 0 then input_vmdkid = tonumber(val) elseif count == 1 then input_ckptid = tonumber(val) elseif count == 2 then input_timestamp = tonumber(val) end count = count + 1 end trace("HYC_UDF input_vmdkid: %d rec_vmdkid: %d", tonumber(input_vmdkid), tonumber(rec_vmdkid)); trace("HYC_UDF input_ckptid: %d rec_ckptid: %d", tonumber(input_ckptid), tonumber(rec_ckptid)); trace("HYC_UDF input_ts: %d rec_ts: %d", tonumber(input_timestamp), tonumber(rec_timestamp)); if rec_vmdkid == input_vmdkid and (input_ckptid == 0 or rec_ckptid == input_ckptid) and (input_timestamp == 0 or rec_timestamp <= input_timestamp) then trace("HYC_UDF found match ckpt ID :: %d, offset : %d, rec_timestamp : %d", tonumber(rec_ckptid), rec_offset, rec_timestamp); aerospike:remove(rec) end end end end
33.123596
152
0.652476
f4ef3c142f3b3444b3c87c54f82fb82c84c17d7f
699
ts
TypeScript
src/utils/getStyleTemplate.ts
xqyi/vue3.0-template-admin
158faa9f4a53da4abb32f4bebb8aa9a1bd531ef3
[ "MIT" ]
544
2021-06-17T02:06:11.000Z
2022-03-31T07:50:36.000Z
src/utils/getStyleTemplate.ts
lizhengpeng/vue3.0-template-admin
aa13dbddd7d7d9e54462b2ba28420414b3b0b58c
[ "MIT" ]
48
2021-07-04T03:04:14.000Z
2022-03-29T02:53:52.000Z
src/utils/getStyleTemplate.ts
lizhengpeng/vue3.0-template-admin
aa13dbddd7d7d9e54462b2ba28420414b3b0b58c
[ "MIT" ]
185
2021-06-30T19:55:56.000Z
2022-03-31T07:50:43.000Z
declare type colorsType={ [key: string]: any; } export const getStyleTemplate = (data: string) => { const colorMap:colorsType = { '#3a8ee6': 'shade-1', '#409eff': 'primary', '#53a8ff': 'light-1', '#66b1ff': 'light-2', '#79bbff': 'light-3', '#8cc5ff': 'light-4', '#a0cfff': 'light-5', '#b3d8ff': 'light-6', '#c6e2ff': 'light-7', '#d9ecff': 'light-8', '#ecf5ff': 'light-9' } Object.keys(colorMap).forEach(key => { const value = colorMap[key] // eslint-disable-next-line no-param-reassign data = data.replace(new RegExp(key, 'ig'), value) }) return data } export default getStyleTemplate
24.964286
55
0.549356
0f5e08967ff416639bc6b0fb5daf4b9e5537db4a
660
css
CSS
src/core/client/ui/components/v2/Marker/Marker.css
GlynnPhillips/talk
c109188efe39b5fb030e832afaa0dfaa57d627f0
[ "Apache-2.0" ]
null
null
null
src/core/client/ui/components/v2/Marker/Marker.css
GlynnPhillips/talk
c109188efe39b5fb030e832afaa0dfaa57d627f0
[ "Apache-2.0" ]
null
null
null
src/core/client/ui/components/v2/Marker/Marker.css
GlynnPhillips/talk
c109188efe39b5fb030e832afaa0dfaa57d627f0
[ "Apache-2.0" ]
null
null
null
.root { font-family: var(--v2-font-family-primary); font-weight: var(--v2-font-weight-primary-semi-bold); font-size: 0.8125rem; letter-spacing: calc(-0.35em / 13); color: var(--v2-palette-marker-reported); border: 1px solid currentColor; border-radius: 20px; padding: 1px var(--mini-unit); white-space: nowrap; } .colorReported { color: var(--v2-palette-marker-reported); } .colorPending { color: var(--v2-palette-marker-pending); } .variantRegular { } .variantFilled { &.colorReported { background-color: var(--v2-palette-marker-reported); } &.colorPending { background-color: var(--v2-palette-marker-pending); } }
19.411765
56
0.674242
6bb3a3744808a00050b5ce826499c44ec27a3934
1,014
hpp
C++
original_periodic/src/timer.hpp
four-spins/dissertation
6a61b6d5b133c8839b7aa740784472c2beb5912e
[ "MIT" ]
null
null
null
original_periodic/src/timer.hpp
four-spins/dissertation
6a61b6d5b133c8839b7aa740784472c2beb5912e
[ "MIT" ]
null
null
null
original_periodic/src/timer.hpp
four-spins/dissertation
6a61b6d5b133c8839b7aa740784472c2beb5912e
[ "MIT" ]
null
null
null
/****************************************************************************** * * @file: timer.hpp * * @date: 09/22/2012 01:18:09 PM (CEST) * * @author: Marco Müller <muelma@gmail.com> * ******************************************************************************/ # ifndef TIMER_HPP # define TIMER_HPP # include <chrono> // use it like // // timer estim_time; // // do something // unsigned seconds = estim_time.elapsed().count(); // class timer { private: typedef std::chrono::high_resolution_clock clock; clock::time_point start; public: timer() : start(clock::now()){} clock::time_point restart() { start = clock::now(); return start;} std::chrono::milliseconds elapsed_ms() { return std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start);} std::chrono::seconds elapsed() { return std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start);} }; # endif // TIMER_HPP
28.971429
98
0.510848
458289e4f11ba10d6a0003b4ef41b1bf27bdd6d5
208
py
Python
hasilla/const.py
DAVZAN/hasilla
1b0dbd58613a28cf4b8aa675d86b4062d41a305d
[ "MIT" ]
null
null
null
hasilla/const.py
DAVZAN/hasilla
1b0dbd58613a28cf4b8aa675d86b4062d41a305d
[ "MIT" ]
null
null
null
hasilla/const.py
DAVZAN/hasilla
1b0dbd58613a28cf4b8aa675d86b4062d41a305d
[ "MIT" ]
null
null
null
"""Silla constants.""" from typing import Final COMMAND_BACKLOG: Final = "Backlog" CONF_MANUFACTURER: Final = "manufacturer" CONF_NAME: Final = "name" CONF_MODEL: Final = "md" CONF_SW_VERSION: Final = "sw"
20.8
41
0.735577
77d6c9e8058bff9b93e47797fe47d529298071a0
2,808
c
C
tools/font/build/single_font_files/u8g2_font_fur14_t_symbol.c
kaidegit/u8g2
54051b6162d240141f6919890d57baf2b6f1ea80
[ "BSD-2-Clause" ]
3,055
2016-05-01T16:33:17.000Z
2022-03-31T21:18:32.000Z
tools/font/build/single_font_files/u8g2_font_fur14_t_symbol.c
TBULE/u8g2
30e78ca9890ac51df8cff4c99756d231eea21efb
[ "BSD-2-Clause" ]
1,646
2016-04-27T16:41:12.000Z
2022-03-30T11:16:47.000Z
tools/font/build/single_font_files/u8g2_font_fur14_t_symbol.c
TBULE/u8g2
30e78ca9890ac51df8cff4c99756d231eea21efb
[ "BSD-2-Clause" ]
870
2016-06-13T19:38:56.000Z
2022-03-28T03:33:52.000Z
/* Fontname: -FreeType-FreeUniversal-Medium-R-Normal--19-190-72-72-P-92-ISO10646-1 Copyright: (FreeUniversal) Copyright (c) Stephen Wilson 2009 a modification of: Original Font (SIL Sophia) Copyright (c) SIL International, 1994-2008. Glyphs: 45/243 BBX Build Mode: 0 */ const uint8_t u8g2_font_fur14_t_symbol[1024] U8G2_FONT_SECTION("u8g2_font_fur14_t_symbol") = "-\0\4\3\5\5\4\5\6\31\24\0\374\16\374\16\375\0\0\0\0\1\347 \6\0 \64\1##\314" "%tKD,&.&LD\346\200(&LDL$\350\200(DLD,&.&LD\12\0" "$#I\246[)\60\254F\42BI\10I\220HP\225\31U\210P\10I\10I\210\204D\204LY" "`\20\0%,\320%\224\203,HD*HF&JFDJF$LD$\260$<\204PBD" ".DFJDF*FQ\220\210T\24\11\0&!\314%t\207NDJ(JFLD\214\220F" "DBFBFDBHB\325\210\230\214L\33\1'\7\301,>\301\0(\17#j;%BE\204" "\376I\210\204H\0)\22#j;!$DB$DB_D\250\10\11\1*\21\350\350e%QH" "\224\314A\214\24\215\210\4\0+\15\213\61\234KR\217\16\250$u\4,\13\243\244+C\202B\42\4" "\0-\7%$=\241\0.\7B(,\201\0/\26\6\246CI(*H(*HQT\220PT" "\220PT\24\0\60\26\311%\134\205Hd$HB*B\212_\205\4\211L\314\320\0\61\14\305)\134" "e\342`DF\377\1\62\23\310%\134\205FDB\210HL\225\252\241)\315\16\2\63\30\311%\134\245" "FdD\210JNLhpN\220\212JBF\246\4\0\64\30\312%\134kn\214JB*DHD" "F'B\42\7\7f\202J\0\65\30\311%\134\341 BN\13\22\22\11\251\10)\71\71*\42\21E" "\64\0\66\31\311%\134\245F\205\24\235\12\222\203\10!\11)V\22Q!\42\63%\0\67\22\310%\134" "\341 LY\230*\61Ub\252\304\204\0\70\26\311%\134\245F\205\24+\11\31\231\32\25R\134I\310" "\310\224\0\71\31\311%\134\245F\205T\204\24+\11\231\211\12\71\71\252\220 \21E\64\0\0\0\0\4" "\377\377\3\224\37\314!d-\66tr\60B\60D,F,F,H(J(L$N$N\342\240" "\0\3\251#\316!|\253NJHNdnBRBRBRBRDNFNHJ$(&\310" "\346\200\246\0\3\274\33\312%cAHDHDHDHDHDHDHDHdIC\15\1\3" "\300\34J!T\343\340\240&$J$J$J$*&*&$BfDH\2\0 \60\65\330%" "\324\203,XD*XF&ZFDZF$\134D$\36\242$\36.\204\210PBD\273\20\31\42" ")\21\31\42\251\30\31\42\241 \21\255\242\210H\0 \71\15\3i<%\202B\42DI\0 :\15" "\3i<!D\205\12\212\20\0 D\24\311%\134O.N.a\134\234\134\234\134:\271@\0!\42" "\27\253$n\201BD\42FD\42&B\42M\204D\232\10\211\0\42\2\36\11\346[\203R\60\62\60" "\241\10\205\32\11\251\10\251\10!\11!\11\241\30\221\60!\0\42\17)/\246\203\341A\304\234\220\234\220" "\234\220\234\220\234\220\234\220\234\220\234\220\234\220\234\220\234\220\234\220\234\220\234\314\234\210\215\1\42\21\31," "\246s\341\200b.d,fTtS\321\234\312E\10F\34<\20\42\22\11+p\235\341\200\0\42\32" "\31\312%\134Q\60\62\60\62D*F(M\224HXH\330\240\312 \0\42\36\25\255\354\234\203\206\42" "FBd*JF\42(\202\206\2\0\42+\23H&Kk(B(L\177\26\227#\211\240)\0\42" "H\16\253\60\235\301H\212\330H\250\2\0\42`\21+q\234\63\311\1Yd\262\3\222\310H\0\42d" "\17Kq\234q\210Y\354Z\322\330\3\2\42e\22Kq\234av\226\66nj\210.\36\354\200\0%" "\312\37\351%TGNL\42*$(MPHXD\330XH\220HP\22\241\220\60\71!\0\0";
70.2
163
0.654202
e246e504d0f5509065f779300d57520724184cca
156
py
Python
examples/pwn/ex_plt.py
devonnuri/nurlib
96e52499fa1fef1c5b35c10d07279f00df9e204f
[ "MIT" ]
null
null
null
examples/pwn/ex_plt.py
devonnuri/nurlib
96e52499fa1fef1c5b35c10d07279f00df9e204f
[ "MIT" ]
null
null
null
examples/pwn/ex_plt.py
devonnuri/nurlib
96e52499fa1fef1c5b35c10d07279f00df9e204f
[ "MIT" ]
null
null
null
#!/usr/bin/env python from ptrlib import * elf = ELF("/bin/ls") print(hex(elf.got("calloc"))) print(hex(elf.plt("calloc"))) print(hex(elf.plt("calloc")))
17.333333
29
0.653846
0aa1adb4e500e1e69781d4bae048a80d036bff79
1,370
cs
C#
WSIP_APP/UltraSonic/QueuePath.cs
miracleshih/SmartIoTPlatform
fb933a552624d1999ec3b39bc6cbbdd88458e54f
[ "MIT" ]
1
2019-11-13T11:49:41.000Z
2019-11-13T11:49:41.000Z
WSIP_APP/UltraSonic/QueuePath.cs
miracleshih/SmartIoTPlatform
fb933a552624d1999ec3b39bc6cbbdd88458e54f
[ "MIT" ]
null
null
null
WSIP_APP/UltraSonic/QueuePath.cs
miracleshih/SmartIoTPlatform
fb933a552624d1999ec3b39bc6cbbdd88458e54f
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UltraSonic { public class QueuePath : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private string _PathFrom = ""; public string PathFrom { get { return _PathFrom; } set { _PathFrom = value; OnPropertyChanged("PathFrom"); } } private List<string> _PathTo = new List<string>(); public List<string> PathTo { get { return _PathTo; } set { _PathTo = value; OnPropertyChanged("PathTo"); } } public override string ToString() { string str = PathFrom + " -->"; for (int i = 0; i < PathTo.Count; i++) str += "\n " + PathTo[i]; return str; } } }
22.833333
87
0.472263
e7770984cf115d3f50cbd49b227d3d8443ee7f21
9,107
php
PHP
database/doctrine_generator/Generate/domain/generated/BasePolicies.php
fernan2cas96/nomeke
71b780d1ab7733163b7276e31256a1c2be4d1912
[ "MIT" ]
null
null
null
database/doctrine_generator/Generate/domain/generated/BasePolicies.php
fernan2cas96/nomeke
71b780d1ab7733163b7276e31256a1c2be4d1912
[ "MIT" ]
2
2021-03-09T15:10:56.000Z
2021-05-10T08:30:34.000Z
database/doctrine_generator/Generate/domain/generated/BasePolicies.php
fernan2cas96/nomeke
71b780d1ab7733163b7276e31256a1c2be4d1912
[ "MIT" ]
null
null
null
<?php /** * BasePolicies * * This class has been auto-generated by the Doctrine ORM Framework * * @property integer $id * @property timestamp $created_at * @property timestamp $updated_at * @property string $policy * @property integer $section_id * @property boolean $role1 * @property boolean $role2 * @property boolean $role3 * @property boolean $role4 * @property boolean $role5 * @property boolean $role6 * @property boolean $role7 * @property boolean $role8 * @property boolean $role9 * @property boolean $role10 * @property boolean $role11 * @property boolean $role12 * @property boolean $role13 * @property boolean $role14 * @property boolean $role15 * @property boolean $role16 * @property boolean $role17 * @property boolean $role18 * @property boolean $role19 * @property boolean $role20 * @property boolean $role21 * @property boolean $role22 * * @package ##PACKAGE## * @subpackage ##SUBPACKAGE## * @author ##NAME## <##EMAIL##> * @version SVN: $Id: Builder.php 6820 2009-11-30 17:27:49Z jwage $ */ abstract class BasePolicies extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('policies'); $this->hasColumn('id', 'integer', 4, array( 'type' => 'integer', 'length' => 4, 'fixed' => false, 'unsigned' => false, 'primary' => true, 'sequence' => 'policies_id', )); $this->hasColumn('created_at', 'timestamp', null, array( 'type' => 'timestamp', 'fixed' => false, 'unsigned' => false, 'notnull' => false, 'primary' => false, )); $this->hasColumn('updated_at', 'timestamp', null, array( 'type' => 'timestamp', 'fixed' => false, 'unsigned' => false, 'notnull' => false, 'primary' => false, )); $this->hasColumn('policy', 'string', null, array( 'type' => 'string', 'fixed' => false, 'unsigned' => false, 'notnull' => false, 'primary' => false, )); $this->hasColumn('section_id', 'integer', 4, array( 'type' => 'integer', 'length' => 4, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'primary' => false, )); $this->hasColumn('role1', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role2', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role3', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role4', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role5', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role6', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role7', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role8', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role9', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role10', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role11', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role12', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role13', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role14', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role15', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role16', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role17', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role18', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role19', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role20', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role21', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); $this->hasColumn('role22', 'boolean', 1, array( 'type' => 'boolean', 'length' => 1, 'fixed' => false, 'unsigned' => false, 'notnull' => true, 'default' => false, 'primary' => false, )); } public function setUp() { parent::setUp(); } }
31.621528
70
0.409026
da18e140fd3a79db952f84c78524e20451c51ed3
7,848
php
PHP
changeInfoProcess.php
Jonathandik/Eshop
dab43ceabed05fdede9631969b71e6e4ce25c081
[ "MIT" ]
1
2019-03-31T17:19:49.000Z
2019-03-31T17:19:49.000Z
changeInfoProcess.php
jonathandik/Eshop
dab43ceabed05fdede9631969b71e6e4ce25c081
[ "MIT" ]
null
null
null
changeInfoProcess.php
jonathandik/Eshop
dab43ceabed05fdede9631969b71e6e4ce25c081
[ "MIT" ]
null
null
null
<?php /*error_reporting function is used to hide errors that do not affect the functionality of the program.*/ session_start(); $emailSesssion=$_SESSION['email']; error_reporting(E_ERROR); //hide errors. include ("includes/db_connection.php"); //connect to the database. //The following variables retrieve data from form in changeInfo.php. $firstName=$_POST['firstname']; $lastName=$_POST['lastname']; $age=$_POST['agerange']; $gender=$_POST['sex']; $phone=$_POST['phone']; $email=$_POST['email']; $speOffer=$_POST['specialoffers']; //The following variables have been initialised to validate the form and handle relative errors. $firstnameErr = $lastnameErr = $genderErr = $phoneErr= $emailErr = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { //Retrieves the form method from changeInfo.php. /*The following functions check if the user has entered the information correctly,else they display according messages.*/ if (empty($firstName)) { $firstnameErr = "*First name is required"; } else { //check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) { $firstnameErr = "Only letters and white space allowed!"; } } if (empty($lastName)) { $lastnameErr = "*Last name is required"; } else { //check if name only contains letters and whitespace. if (!preg_match("/^[a-zA-Z ]*$/",$lastName)) { $lastnameErr = "Only letters and white space allowed!"; } } if (empty($gender)) { $genderErr = "*Please choose your gender"; } if (empty($phone)) { $phoneErr = "*Phone number is required"; } else { //check if phone number is well-formed. if (!preg_match("/^[+0-9]{3}-[0-9]{3}-[0-9]{7}$/", $phone)) { $phoneErr="Invalid Phone Number!"; } } if (empty($email)) { $emailErr = "*Email"; } else { //check if e-mail address is well-formed. if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format!"; } } //Check whether there are errors. if ($firstnameErr !="" || $lastnameErr!="" || $genderErr!="" || $phoneErr!="" || $emailErr!="") { ?> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="css/changeInfo.css"> </head> <body> <form method="POST" action="welcomeChangeInfoProcess.php"> <table> <tr> <td>First&nbsp;Name:</td> <td> <input type="text" name="firstname" size="25" value="<?php echo $firstName;?>"> </td> <tr><td>&nbsp;</td><td><span class="error"><?php echo $firstnameErr;?></span> </td> </tr> <tr> <td>Last&nbsp;Name:</td> <td> <input type="text" name="lastname" size="25" value="<?php echo $lastName;?>"> </td> </td> <tr><td>&nbsp;</td><td><span class="error"><?php echo $lastnameErr;?></span> </td> </tr> <tr> <td>Age:</td> <td> <select name="agerange" size="1"> <option>Under 18</option> <option>18 - 24</option> <option>25 - 34</option> <option>35 - 44</option> <option>45 - 54</option> <option>55 - 64</option> <option>65 and older</option> </select> </td> </tr> <tr> <td>Sex:</td> <td> <input type="radio" name="sex" <?php if (isset($gender)&& $gender=="Male")echo "checked";?> value="Male">Male <input type="radio" name="sex" <?php if (isset($gender)&& $gender=="Female")echo "checked";?> value="Female">Female </td> </td> <tr><td>&nbsp;</td><td><span class="error"><?php echo $genderErr;?></span> </td> </tr> <tr> <td>Phone&nbsp;Number:</td> <td> <input type="text" name="phone" size="25" maxlength="15" placeholder="+XX-XXX-XXXXXXX" value="<?php echo $phone;?>"> </td> </td> <tr><td>&nbsp;</td><td><span class="error"><?php echo $phoneErr;?></span> </td> </tr> <tr> <td>E-mail:</td> <td> <input type="text" name="email" size="25" placeholder="name@example.com" value="<?php echo $email;?>"> </td> </td> <tr><td>&nbsp;</td><td><span class="error"><?php echo $emailErr;?></span> </td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> </tr> </table> <table style="width:100%"> <tr> <td style="font-size:14px;"><input type="checkbox" name="specialoffers" <?php if (isset($speOffer)&& $speOffer!="") { echo "checked"; } ?> value=" "> Check the box to receive special offers from us via email.</td> </tr> <tr> <td><input type="submit" value="Update Information"></td> </tr> </table> </form> <?php /*if the user has entered the correct data properly, display them in a new page and execute a query to update their data.*/ }else { ?> <div style="color:red"> <?php echo "<h3>Your new information is the following:</h3>"; /*stripslashes() function is useful to remove unnecessary characters like \, while mysqli_real_escape_string is used for security*/ $firstname=stripslashes($_POST['firstname']); $firstname=mysqli_real_escape_string($conn, $_POST['firstname']); echo "<h4>Full Name: $firstName $lastName</h4>"; $lastname=stripslashes($_POST['lastname']); $lastname=mysqli_real_escape_string($conn, $_POST['lastname']); echo "<h4>Age range: $age</h4>"; $agerange=$_POST['agerange']; echo "<h4>Sex: $gender</h4>"; $gender=$_POST['sex']; echo "<h4>Phone number:$phone</h4>"; $phone=stripslashes($_POST['phone']); $phone=mysqli_real_escape_string($conn, $_POST['phone']); echo "<h4>Email address: $email</h4>"; $email=stripslashes($_POST['email']); $email=mysqli_real_escape_string($conn, $_POST['email']); $speOffer=$_POST['specialoffers']; /*If the user has filled the ckecbox the following message is displayed and then update the fields in the database.*/ if ($speOffer!=NULL) { $speOffer="You would like to receive details of special offers."; } echo "<h5>$speOffer </h5>"; $sql="UPDATE users SET FIRSTNAME='$firstname', LASTNAME='$lastname', AGE='$agerange', GENDER='$gender', PHONE='$phone', EMAIL='$email', SPEOFFER='$speOffer' WHERE EMAIL='$emailSesssion'"; echo "<h5>Your information has been updated.Logging out.</h5>"; echo "<script>setTimeout(\"location.href = 'login.php';\",10000);</script>"; //Redirect page in 10 seconds. session_destroy(); if (!$conn->query($sql)){ //if an error occurs regarding the query, show it. echo "<h5>\"An error occured\"</h5>"; } } } $conn->close(); ?> </div> </body> </html>
37.371429
190
0.513889
7a7205f7913d85efd602242e9fe6c3004d852386
131
go
Go
internal/monitor/custom_metric.go
dhamith93/SyMon
c5db42d766da46375a7d08ab0ad777551d2bc1fa
[ "MIT" ]
1
2020-11-29T11:07:53.000Z
2020-11-29T11:07:53.000Z
internal/monitor/custom_metric.go
dhamith93/SyMon
c5db42d766da46375a7d08ab0ad777551d2bc1fa
[ "MIT" ]
null
null
null
internal/monitor/custom_metric.go
dhamith93/SyMon
c5db42d766da46375a7d08ab0ad777551d2bc1fa
[ "MIT" ]
1
2021-09-22T10:55:54.000Z
2021-09-22T10:55:54.000Z
package monitor type CustomMetric struct { Name string Unit string Value string ServerId string Time string }
13.1
26
0.694656
b6bb191510cddf9f18d32a012c05dd2fc2bd73b2
2,246
rb
Ruby
spec/integration/board/update!_spec.rb
MoskitoHero/ruby-trello
335f6aab7c9cf60f4ff6f70c894ba2aae87ec9fa
[ "MIT" ]
401
2015-01-03T04:11:32.000Z
2022-03-17T07:21:37.000Z
spec/integration/board/update!_spec.rb
MoskitoHero/ruby-trello
335f6aab7c9cf60f4ff6f70c894ba2aae87ec9fa
[ "MIT" ]
139
2015-01-03T04:18:21.000Z
2022-03-12T01:09:34.000Z
spec/integration/board/update!_spec.rb
MoskitoHero/ruby-trello
335f6aab7c9cf60f4ff6f70c894ba2aae87ec9fa
[ "MIT" ]
198
2015-01-02T15:06:27.000Z
2022-03-16T11:15:59.000Z
require 'spec_helper' RSpec.describe 'Trell::Board.update!' do include IntegrationHelpers before { setup_trello } it 'can update! a card with all fields' do VCR.use_cassette('can_success_update_bong_a_board') do board = Trello::Board.find('5e93ba403f1ab3603ba81a09') expect(board.name).to eq('IT 1') expect(board.description).to eq('') expect(board.organization_id).to eq('5e93ba154634282b6df23bcc') board.name = 'IT 1 - Changed' board.description = 'This is a test board called IT 1' board.closed = false board.organization_id = '5eb427016b5a464a74803f1c' board.visibility_level = 'org' board.enable_self_join = false board.enable_card_covers = false board.voting_permission_level = 'org' board.comment_permission_level = 'org' board.background_color = 'green' board.update! board = Trello::Board.find('5e93ba403f1ab3603ba81a09') expect(board.name).to eq('IT 1 - Changed') expect(board.description).to eq('This is a test board called IT 1') expect(board.closed).to eq(false) expect(board.organization_id).to eq('5eb427016b5a464a74803f1c') expect(board.visibility_level).to eq('org') expect(board.enable_self_join).to eq(false) expect(board.enable_card_covers).to eq(false) expect(board.voting_permission_level).to eq('org') expect(board.comment_permission_level).to eq('org') expect(board.background_color).to eq('green') end end it 'can update! a card with specific fields' do VCR.use_cassette('can_success_update_bong_a_board_with_specific_fields') do board = Trello::Board.find('5e93ba403f1ab3603ba81a09') expect(board.name).to eq('IT 1') expect(board.description).to eq('This is a test board called IT 1') expect(board.comment_permission_level).to eq('org') board.name = 'IT 1 - Changed' board.comment_permission_level = 'members' board.update! board = Trello::Board.find('5e93ba403f1ab3603ba81a09') expect(board.name).to eq('IT 1 - Changed') expect(board.description).to eq('This is a test board called IT 1') expect(board.comment_permission_level).to eq('members') end end end
35.650794
79
0.695013
e4c5648387634e94c3cd86e3aa9029b9b98b9757
3,891
h
C
releases/include/qcParser.h
pili-engineering/PLWinPlayer
54faea319697cf47d956ff9ae9f1f8af43191caa
[ "Apache-2.0" ]
40
2017-12-31T06:59:37.000Z
2021-11-16T12:49:36.000Z
releases/include/qcParser.h
pili-engineering/PLWinPlayer
54faea319697cf47d956ff9ae9f1f8af43191caa
[ "Apache-2.0" ]
5
2017-12-19T09:21:50.000Z
2020-03-20T06:46:15.000Z
releases/include/qcParser.h
pili-engineering/PLWinPlayer
54faea319697cf47d956ff9ae9f1f8af43191caa
[ "Apache-2.0" ]
21
2017-12-19T06:54:25.000Z
2021-01-08T07:11:55.000Z
/******************************************************************************* File: qcParser.h Contains: Parser interface define header file. Written by: Bangfei Jin Change History (most recent first): 2016-11-29 Bangfei Create file *******************************************************************************/ #ifndef __qcParser_h__ #define __qcParser_h__ #include "qcIO.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #define QC_PARSER_BASE 0X13000000 // Set the last playback bitrate // The parameter should be int *. #define QCPARSER_PID_LastBitrate QC_PARSER_BASE + 0X01 // Set to exit read immediately // The parameter should be int. 1 exit, 0 no. #define QCPARSER_PID_ExitRead QC_PARSER_BASE + 0X02 // Get the seek io pos // The parameter should be long long * #define QCPARSER_PID_SEEK_IO_POS QC_PARSER_BASE + 0X03 /** * the qc parser interface */ typedef struct { // Define the version of the Parser. It shuild be 1 int nVer; // Define the base instance void * pBaseInst; // The Parser handle, it will fill in function. void * hParser; // This is buffer manager pointer for internal use. It will set by caller. void * pBuffMng; // Open the parser. The flag should be 0 now. the other value shulde be use later. int (* Open) (void * hParser, QC_IO_Func * pIO, const char * pURL, int nFlag); // Close the parser to release the resource int (* Close) (void * hParser); // get the stream info int (* GetStreamCount) (void * hParser, QCMediaType nType); int (* GetStreamPlay) (void * hParser, QCMediaType nType); int (* SetStreamPlay) (void * hParser, QCMediaType nType, int nStream); // get the source duration. long long (* GetDuration) (void * hParser); // get the playing stream format. Caller can not change the format. int (* GetStreamFormat) (void * hParser, int nID, QC_STREAM_FORMAT ** ppStreamFmt); int (* GetAudioFormat) (void * hParser, int nID, QC_AUDIO_FORMAT ** ppAudioFmt); int (* GetVideoFormat) (void * hParser, int nID, QC_VIDEO_FORMAT ** ppVideoFmt); int (* GetSubttFormat) (void * hParser, int nID, QC_SUBTT_FORMAT ** ppSubttFmt); // get the source is end of stream or not. bool (* IsEOS) (void * hParser); // get the source is live or not. bool (* IsLive) (void * hParser); // enable the subtitle or not. int (* EnableSubtt) (void * hParser,bool bEnable); // control the Parser int (* Run) (void * hParser); int (* Pause) (void * hParser); int (* Stop) (void * hParser); // read the data, return read size int (* Read) (void * hParser, QC_DATA_BUFF * pBuff); // parse the data, return process size int (* Process) (void * hParser, unsigned char * pBuff, int nSize); // return > 0 cans seek, < 0 was failed. int (* CanSeek) (void * hIO); // return the current time. ms long long (* GetPos) (void * hParser); // return current pos after set pos. ms long long (* SetPos) (void * hParser, long long llPos); // for extend function later. int (* GetParam) (void * hParser, int nID, void * pParam); int (* SetParam) (void * hParser, int nID, void * pParam); } QC_Parser_Func; // create the Parser with Parser type. DLLEXPORT_C int qcCreateParser (QC_Parser_Func * pParser, QCParserFormat nFormat); // destory the Parser DLLEXPORT_C int qcDestroyParser (QC_Parser_Func * pParser); DLLEXPORT_C int ffCreateParser(QC_Parser_Func * pParser, QCParserFormat nFormat); typedef int (*FFCREATEPARSER) (QC_Parser_Func * pParser, QCParserFormat nFormat); DLLEXPORT_C int ffDestroyParser(QC_Parser_Func * pParser); typedef int (*FFDESTROYPARSER) (QC_Parser_Func * pParser); #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ #endif // __qcParser_h__
32.425
88
0.643022
5a08ffa74e9c086a8a1a8562432d9ae8256c2925
22,841
ps1
PowerShell
tests/Unit/MSFT_xClusterPreferredOwner.Tests.ps1
bjoka042/xFailOverCluster
48e63a42262c1f74c4ecb0c2ca21b14d04e82f88
[ "MIT" ]
36
2015-06-24T06:10:26.000Z
2019-11-04T07:51:39.000Z
tests/Unit/MSFT_xClusterPreferredOwner.Tests.ps1
bjoka042/xFailOverCluster
48e63a42262c1f74c4ecb0c2ca21b14d04e82f88
[ "MIT" ]
201
2015-04-23T16:25:05.000Z
2019-11-25T14:00:07.000Z
tests/Unit/MSFT_xClusterPreferredOwner.Tests.ps1
bjoka042/xFailOverCluster
48e63a42262c1f74c4ecb0c2ca21b14d04e82f88
[ "MIT" ]
63
2015-05-10T00:55:12.000Z
2019-10-28T18:53:42.000Z
$script:DSCModuleName = 'xFailOverCluster' $script:DSCResourceName = 'MSFT_xClusterPreferredOwner' function Invoke-TestSetup { param ( [Parameter(Mandatory = $true)] [string] $ModuleVersion ) try { Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' } $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` -DSCResourceName $script:dscResourceName ` -ResourceType 'Mof' ` -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath "Stubs\FailoverClusters$ModuleVersion.stubs.psm1") -Global -Force $global:moduleVersion = $ModuleVersion } function Invoke-TestCleanup { Restore-TestEnvironment -TestEnvironment $script:testEnvironment Remove-Variable -Name moduleVersion -Scope Global -ErrorAction SilentlyContinue } foreach ($moduleVersion in @('2012', '2016')) { Invoke-TestSetup -ModuleVersion $moduleVersion try { InModuleScope $script:DSCResourceName { $mockPreferredOwnerNode1 = 'Node1' $mockPreferredOwnerNode2 = 'Node2' $mockPreferredOwnerNode3 = 'Node3' $mockDesiredPreferredOwnerNodes = @($mockPreferredOwnerNode1, $mockPreferredOwnerNode2) $mockAllPreferredOwnerNodes = @($mockPreferredOwnerNode1, $mockPreferredOwnerNode2, $mockPreferredOwnerNode3) $mockWrongPreferredOwnerNode1 = 'Node4' $mockWrongPreferredOwnerNode2 = 'Node5' $mockWrongPreferredOwnerNodes = @($mockWrongPreferredOwnerNode1, $mockWrongPreferredOwnerNode2) $mockKnownClusterResourceName = 'Resource1' $mockUnknownClusterResourceName = 'UnknownResource' $mockDefaultTestParameters = @{ ClusterGroup = 'ClusterGroup1' ClusterName = 'ClusterName1' } $mockTestParameters_Present_DesiredPreferredOwners = $mockDefaultTestParameters.Clone() $mockTestParameters_Present_DesiredPreferredOwners += @{ Nodes = $mockDesiredPreferredOwnerNodes ClusterResources = $mockKnownClusterResourceName Ensure = 'Present' } $mockTestParameters_Present_AllPreferredOwners = $mockDefaultTestParameters.Clone() $mockTestParameters_Present_AllPreferredOwners += @{ Nodes = $mockAllPreferredOwnerNodes ClusterResources = $mockKnownClusterResourceName Ensure = 'Present' } $mockTestParameters_Present_WrongPreferredOwnerNodes = $mockDefaultTestParameters.Clone() $mockTestParameters_Present_WrongPreferredOwnerNodes += @{ Nodes = $mockWrongPreferredOwnerNodes ClusterResources = $mockKnownClusterResourceName Ensure = 'Present' } $mockTestParameters_Present_WrongClusterResources = $mockDefaultTestParameters.Clone() $mockTestParameters_Present_WrongClusterResources += @{ Nodes = $mockDesiredPreferredOwnerNodes ClusterResources = $mockUnknownClusterResourceName Ensure = 'Present' } $mockTestParameters_Absent_ButPreferredOwnersExist = $mockDefaultTestParameters.Clone() $mockTestParameters_Absent_ButPreferredOwnersExist += @{ Nodes = $mockDesiredPreferredOwnerNodes ClusterResources = $mockKnownClusterResourceName Ensure = 'Absent' } $mockTestParameters_Absent_AndPreferredOwnersDoesNotExist = $mockDefaultTestParameters.Clone() $mockTestParameters_Absent_AndPreferredOwnersDoesNotExist += @{ Nodes = $mockWrongPreferredOwnerNodes ClusterResources = $mockKnownClusterResourceName Ensure = 'Absent' } $mockGetClusterGroup = { @{ Name = 'ClusterGroup1' OwnerNode = 'Node1' State = 'Online' } } $mockGetClusterGroup_ParameterFilter = { $Cluster -eq 'ClusterName1' } $GetClusterOwnerNode = { @{ ClusterObject = 'ClusterName1' OwnerNodes = @( @{name = $mockPreferredOwnerNode1 } @{name = $mockPreferredOwnerNode2 } @{name = $mockPreferredOwnerNode3 } ) } } $mockGetClusterNode = { @{ Name = $mockDesiredPreferredOwnerNodes } } $mockGetClusterResource = { @{ Name = $mockKnownClusterResourceName State = 'Online' OwnerGroup = 'ClusterGroup1' ResourceType = 'type1' } } Describe "xClusterDisk_$moduleVersion\Get-TargetResource" { BeforeAll { Mock -CommandName 'Get-ClusterGroup' -ParameterFilter $mockGetClusterGroup_ParameterFilter -MockWith $mockGetClusterGroup Mock -CommandName 'Get-ClusterOwnerNode' -MockWith $GetClusterOwnerNode Mock -CommandName 'Get-ClusterNode' -MockWith $mockGetClusterNode Mock -CommandName 'Get-ClusterResource' -MockWith $mockGetClusterResource } Context 'When the system is not in the desired state' { Context 'When Ensure is set to ''Present'' but the preferred owner is not a possible owner of the cluster nodes and the cluster resources' { It 'Should return the correct type' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Present_WrongPreferredOwnerNodes $getTargetResourceResult | Should -BeOfType [System.Collections.Hashtable] } It 'Should return the same values as passed as parameters' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Present_WrongPreferredOwnerNodes $getTargetResourceResult.ClusterGroup | Should -Be $mockTestParameters_Present_WrongPreferredOwnerNodes.ClusterGroup $getTargetResourceResult.ClusterName | Should -Be $mockTestParameters_Present_WrongPreferredOwnerNodes.ClusterName $getTargetResourceResult.Ensure | Should -Be $mockTestParameters_Present_WrongPreferredOwnerNodes.Ensure } It 'Should return the wrong preferred owner nodes and the right cluster resources' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Present_WrongPreferredOwnerNodes $getTargetResourceResult.Nodes | Should -Not -Be $mockTestParameters_Present_WrongPreferredOwnerNodes.Nodes $getTargetResourceResult.ClusterResources | Should -Be $mockTestParameters_Present_WrongPreferredOwnerNodes.ClusterResources } } Context 'When Ensure is set to ''Present'' but the preferred owner is a possible owner of the cluster nodes but the cluster resources is missing' { It 'Should return the same values as passed as parameters' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Present_WrongClusterResources $getTargetResourceResult.ClusterGroup | Should -Be $mockTestParameters_Present_WrongClusterResources.ClusterGroup $getTargetResourceResult.ClusterName | Should -Be $mockTestParameters_Present_WrongClusterResources.ClusterName $getTargetResourceResult.Ensure | Should -Be $mockTestParameters_Present_WrongClusterResources.Ensure } It 'Should return the correct preferred owner nodes and the wrong cluster resources' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Present_WrongClusterResources $getTargetResourceResult.Nodes | Should -Be $mockAllPreferredOwnerNodes $getTargetResourceResult.ClusterResources | Should -Be $mockTestParameters_Present_WrongClusterResources.ClusterResources } } Context 'When Ensure is set to ''Absent'' and the preferred owner is still a possible owner of the cluster nodes and the cluster resources' { It 'Should return the same values as passed as parameters' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Absent_ButPreferredOwnersExist $getTargetResourceResult.ClusterGroup | Should -Be $mockTestParameters_Absent_ButPreferredOwnersExist.ClusterGroup $getTargetResourceResult.ClusterName | Should -Be $mockTestParameters_Absent_ButPreferredOwnersExist.ClusterName $getTargetResourceResult.Ensure | Should -Be $mockTestParameters_Absent_ButPreferredOwnersExist.Ensure } It 'Should return the correct preferred owner nodes and the wrong cluster resources' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Absent_ButPreferredOwnersExist $getTargetResourceResult.Nodes | Should -Be $mockAllPreferredOwnerNodes $getTargetResourceResult.ClusterResources | Should -Be $mockTestParameters_Absent_ButPreferredOwnersExist.ClusterResources } } } Context 'When the system is in the desired state' { Context 'When Ensure is set to ''Present'' and the preferred owner is a possible owner of the cluster nodes and the cluster resources' { It 'Should return the same values as passed as parameters' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Present_DesiredPreferredOwners $getTargetResourceResult.ClusterGroup | Should -Be $mockTestParameters_Present_DesiredPreferredOwners.ClusterGroup $getTargetResourceResult.ClusterName | Should -Be $mockTestParameters_Present_DesiredPreferredOwners.ClusterName $getTargetResourceResult.Ensure | Should -Be $mockTestParameters_Present_DesiredPreferredOwners.Ensure } It 'Should return the right preferred owner nodes and the right cluster resources' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Present_DesiredPreferredOwners $getTargetResourceResult.Nodes | Should -Be $mockAllPreferredOwnerNodes $getTargetResourceResult.ClusterResources | Should -Be $mockTestParameters_Present_DesiredPreferredOwners.ClusterResources } } Context 'When Ensure is set to ''Absent'' and the preferred owner is not a possible owner of the cluster nodes and the cluster resources' { It 'Should return the same values as passed as parameters' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Absent_AndPreferredOwnersDoesNotExist $getTargetResourceResult.ClusterGroup | Should -Be $mockTestParameters_Absent_AndPreferredOwnersDoesNotExist.ClusterGroup $getTargetResourceResult.ClusterName | Should -Be $mockTestParameters_Absent_AndPreferredOwnersDoesNotExist.ClusterName $getTargetResourceResult.Ensure | Should -Be $mockTestParameters_Absent_AndPreferredOwnersDoesNotExist.Ensure } It 'Should return the correct preferred owner nodes and the wrong cluster resources' { $getTargetResourceResult = Get-TargetResource @mockTestParameters_Absent_AndPreferredOwnersDoesNotExist $getTargetResourceResult.Nodes | Should -Not -Be $mockTestParameters_Absent_AndPreferredOwnersDoesNotExist.Nodes $getTargetResourceResult.ClusterResources | Should -Be $mockTestParameters_Absent_AndPreferredOwnersDoesNotExist.ClusterResources } } } } Describe "xClusterDisk_$moduleVersion\Test-TargetResource" { BeforeAll { Mock -CommandName 'Get-ClusterGroup' -ParameterFilter $mockGetClusterGroup_ParameterFilter -MockWith $mockGetClusterGroup Mock -CommandName 'Get-ClusterOwnerNode' -MockWith $GetClusterOwnerNode Mock -CommandName 'Get-ClusterNode' -MockWith $mockGetClusterNode Mock -CommandName 'Get-ClusterResource' -MockWith $mockGetClusterResource } Context 'When the system is not in the desired state' { Context 'When Ensure is set to ''Present'' but the preferred owner is not a possible owner of the cluster nodes and the cluster resources' { It 'Should return the result as $false ' { $testTargetResourceResult = Test-TargetResource @mockTestParameters_Present_WrongPreferredOwnerNodes $testTargetResourceResult | Should -Be $false } } # This test is skipped due to a logic error in the code that needs to be fixed (issue #94). Context 'When Ensure is set to ''Present'' but the preferred owner is a possible owner of the cluster nodes but the cluster resources is missing' { It 'Should return the result as $false ' -Skip { $testTargetResourceResult = Test-TargetResource @mockTestParameters_Present_WrongClusterResources $testTargetResourceResult | Should -Be $false } } Context 'When Ensure is set to ''Absent'' and the preferred owner is still a possible owner of the cluster nodes and the cluster resources' { It 'Should return the result as $false ' { $testTargetResourceResult = Test-TargetResource @mockTestParameters_Absent_ButPreferredOwnersExist $testTargetResourceResult | Should -Be $false } } Context 'When Ensure is set to ''Present'' and the preferred owners is a possible owners of the cluster nodes and the cluster resources, but there are one additional preferred owner on the nodes that should not be present' { It 'Should return the result as $false ' { $testTargetResourceResult = Test-TargetResource @mockTestParameters_Present_DesiredPreferredOwners $testTargetResourceResult | Should -Be $false } } } Context 'When the system is in the desired state' { Context 'When Ensure is set to ''Present'' and the preferred owner is a possible owner of the cluster nodes and the cluster resources' { It 'Should return the result as $true ' { $testTargetResourceResult = Test-TargetResource @mockTestParameters_Present_AllPreferredOwners $testTargetResourceResult | Should -Be $true } } Context 'When Ensure is set to ''Absent'' and the preferred owner is not a possible owner of the cluster nodes and the cluster resources' { It 'Should return the result as $true ' { $testTargetResourceResult = Test-TargetResource @mockTestParameters_Absent_AndPreferredOwnersDoesNotExist $testTargetResourceResult | Should -Be $true } } } } Describe "xClusterDisk_$moduleVersion\Set-TargetResource" { BeforeAll { Mock -CommandName 'Get-ClusterGroup' -ParameterFilter $mockGetClusterGroup_ParameterFilter -MockWith $mockGetClusterGroup Mock -CommandName 'Get-ClusterOwnerNode' -MockWith $GetClusterOwnerNode Mock -CommandName 'Get-ClusterNode' -MockWith $mockGetClusterNode Mock -CommandName 'Get-ClusterResource' -MockWith $mockGetClusterResource Mock -CommandName 'Set-ClusterOwnerNode' Mock -CommandName 'Move-ClusterGroup' } Context 'When the system is not in the desired state' { Context 'When Ensure is set to ''Present'' but the preferred owner is not a possible owner of the cluster nodes and the cluster resources' { It 'Should set the preferred owners' { { Set-TargetResource @mockTestParameters_Present_WrongPreferredOwnerNodes } | Should -Not -Throw # Called three times, one times for each node (2 nodes), and one time for each cluster resource (1 resource). Assert-MockCalled -CommandName 'Set-ClusterOwnerNode' -Exactly -Times 3 -Scope It # Moves the cluster group to the target node (issue #64 open). Assert-MockCalled -CommandName 'Move-ClusterGroup' -Exactly -Times 1 -Scope It } } Context 'When Ensure is set to ''Present'' but the preferred owner is a possible owner of the cluster nodes but the cluster resources is missing' { It 'Should set the preferred owners' { { Set-TargetResource @mockTestParameters_Present_WrongClusterResources } | Should -Not -Throw # Called two times, one times for each node (2 nodes), and not called for cluster resource because cluster resource is missing. Assert-MockCalled -CommandName 'Set-ClusterOwnerNode' -Exactly -Times 2 -Scope It # Moves the cluster group to the target node (issue #64 open). Assert-MockCalled -CommandName 'Move-ClusterGroup' -Exactly -Times 1 -Scope It } } Context 'When Ensure is set to ''Absent'' and the preferred owner is still a possible owner of the cluster nodes and the cluster resources' { It 'Should remove the preferred owners, leaving one preferred owner' { { Set-TargetResource @mockTestParameters_Absent_ButPreferredOwnersExist } | Should -Not -Throw # Called two times, one times for each node (2 nodes), and one time for each cluster resource (1 resource). Assert-MockCalled -CommandName 'Set-ClusterOwnerNode' -Exactly -Times 3 -Scope It # Moves the cluster group to the target node (issue #64 open). Assert-MockCalled -CommandName 'Move-ClusterGroup' -Exactly -Times 1 -Scope It } } } Context 'When the system is in the desired state' { # This tests wrongly calls Set-ClusterOwnerNode and Move-ClusterGroup. See issue #97. Context 'When Ensure is set to ''Present'' and the preferred owner is a possible owner of the cluster nodes and the cluster resources' { It 'Should do nothing' { { Set-TargetResource @mockTestParameters_Present_AllPreferredOwners } | Should -Not -Throw # Called two times, one times for each node (2 nodes), and one time for each cluster resource (1 resource). Assert-MockCalled -CommandName 'Set-ClusterOwnerNode' -Exactly -Times 3 -Scope It # Moves the cluster group to the target node (issue #64 open). Assert-MockCalled -CommandName 'Move-ClusterGroup' -Exactly -Times 1 -Scope It } } # This tests wrongly calls Set-ClusterOwnerNode and Move-ClusterGroup. See issue #97. Context 'When Ensure is set to ''Absent'' and the preferred owner is not a possible owner of the cluster nodes and the cluster resources' { It 'Should do nothing' { { Set-TargetResource @mockTestParameters_Absent_AndPreferredOwnersDoesNotExist } | Should -Not -Throw # Called two times, one times for each node (2 nodes), and one time for each cluster resource (1 resource). Assert-MockCalled -CommandName 'Set-ClusterOwnerNode' -Exactly -Times 3 -Scope It # Moves the cluster group to the target node (issue #64 open). Assert-MockCalled -CommandName 'Move-ClusterGroup' -Exactly -Times 1 -Scope It } } } } } } finally { Invoke-TestCleanup } }
60.909333
245
0.589817
8531a47ad580aa9f0c7732d1542e002c5ffdcebf
95
cs
C#
CollectionTracking.Core/Entities/IEntity.cs
nurcanfly3/nurcanfly3
4bf4fa31ecc2162f73471ab60942f94f3667e8fd
[ "MIT" ]
null
null
null
CollectionTracking.Core/Entities/IEntity.cs
nurcanfly3/nurcanfly3
4bf4fa31ecc2162f73471ab60942f94f3667e8fd
[ "MIT" ]
null
null
null
CollectionTracking.Core/Entities/IEntity.cs
nurcanfly3/nurcanfly3
4bf4fa31ecc2162f73471ab60942f94f3667e8fd
[ "MIT" ]
null
null
null
namespace CollectionTracking.Core.Entities { public interface IEntity { } }
13.571429
44
0.642105
d6ec8895c67f4f84da71979998b69afed31bfa51
4,147
swift
Swift
CoreDataDefaults/CoreDataDefaults/Sources/CoreDataDefaults.swift
ankitthakur/CoreDataPreference
ae1a4001d59b7a6b7211a48015febc9fd2e3f4ba
[ "MIT" ]
null
null
null
CoreDataDefaults/CoreDataDefaults/Sources/CoreDataDefaults.swift
ankitthakur/CoreDataPreference
ae1a4001d59b7a6b7211a48015febc9fd2e3f4ba
[ "MIT" ]
null
null
null
CoreDataDefaults/CoreDataDefaults/Sources/CoreDataDefaults.swift
ankitthakur/CoreDataPreference
ae1a4001d59b7a6b7211a48015febc9fd2e3f4ba
[ "MIT" ]
null
null
null
// // CoreDataDefaults.swift // CoreDataDefaults // // Created by Ankit Thakur on 1/11/19. // import Foundation public struct CoreDataDefaults { } public extension CoreDataDefaults { static func string(forKey key: String) throws -> String? { do { let data = try CoreDataDefaults.data(forKey: key) return String(data: data!, encoding: .utf8) } catch let error { print(error) } return nil } static func set(value: String, forKey key: String) throws { do { let data: Data = value.data(using: .utf8)! try CoreDataDefaults.setData(value: data, forKey: key) } catch let error { print(error) } } static func integer(forKey key: String) throws -> Int? { do { let data = try CoreDataDefaults.data(forKey: key) let intValue: Int = data!.withUnsafeBytes { (pointer: UnsafePointer<Int>) -> Int? in if MemoryLayout<Int>.size != data!.count { return nil } return pointer.pointee } ?? 0 return intValue } catch let error { print(error) } return nil } static func set(value: Int, forKey key: String) throws { do { let data = withUnsafeBytes(of: value) { Data($0) } try CoreDataDefaults.setData(value: data, forKey: key) } catch let error { print(error) } } static func float(forKey key: String) throws -> Float? { do { let data = try CoreDataDefaults.data(forKey: key) let floatValue: Float = data!.withUnsafeBytes { (pointer: UnsafePointer<Float>) -> Float? in if MemoryLayout<Float>.size != data!.count { return nil } return pointer.pointee } ?? 0 return floatValue } catch let error { print(error) } return nil } static func set(value: Float, forKey key: String) throws { do { let data = withUnsafeBytes(of: value) { Data($0) } try CoreDataDefaults.setData(value: data, forKey: key) } catch let error { print(error) } } static func double(forKey key: String) throws -> Double? { do { let data = try CoreDataDefaults.data(forKey: key) let doubleValue: Double = data!.withUnsafeBytes { (pointer: UnsafePointer<Double>) -> Double? in if MemoryLayout<Double>.size != data!.count { return nil } return pointer.pointee } ?? 0 return doubleValue } catch let error { print(error) } return nil } static func set(value: Double, forKey key: String) throws { do { let data = withUnsafeBytes(of: value) { Data($0) } try CoreDataDefaults.setData(value: data, forKey: key) } catch let error { print(error) } } static func boolean(forKey key: String) throws -> Bool? { do { let data = try CoreDataDefaults.data(forKey: key) let booleanValue: Int = data!.withUnsafeBytes { (pointer: UnsafePointer<Int>) -> Int? in if MemoryLayout<Int>.size != data!.count { return nil } return pointer.pointee } ?? 0 return booleanValue != 0 } catch let error { print(error) } return nil } static func set(value: Bool, forKey key: String) throws { do { let intValue = value ? 1 : 0 let data = withUnsafeBytes(of: intValue) { Data($0) } try CoreDataDefaults.setData(value: data, forKey: key) } catch let error { print(error) throw error } } static func remove(valueForKey key: String) throws { do { try CDDefault.remove(CDDefault.self, forKey: key) } catch let error { print(error) throw error } } }
30.050725
108
0.530986
fa26334d0dd0ebdc20aba0b1d40e6a776c173f77
3,306
cpp
C++
benchmark/pubsub.cpp
Watch-Later/shadesmar
be782a0ead538ea74463947a2ca17c94124ab514
[ "MIT" ]
298
2019-08-05T04:28:05.000Z
2022-03-28T09:02:18.000Z
benchmark/pubsub.cpp
xian0gang/shadesmar
041ce70133ad413f3e68645fa5d1ad5800d7354b
[ "MIT" ]
34
2019-11-26T15:52:04.000Z
2022-03-06T14:04:24.000Z
benchmark/pubsub.cpp
xian0gang/shadesmar
041ce70133ad413f3e68645fa5d1ad5800d7354b
[ "MIT" ]
38
2019-11-24T14:18:38.000Z
2022-03-31T01:58:53.000Z
/* MIT License Copyright (c) 2020 Dheeraj R Reddy 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. ==============================================================================*/ #include <cassert> #include <chrono> #include <iostream> #ifdef SINGLE_HEADER #include "shadesmar.h" #else #include "shadesmar/memory/copier.h" #include "shadesmar/memory/dragons.h" #include "shadesmar/pubsub/publisher.h" #include "shadesmar/pubsub/subscriber.h" #include "shadesmar/stats.h" #endif const char topic[] = "raw_benchmark_topic"; shm::stats::Welford per_second_lag; struct Message { uint64_t count; uint64_t timestamp; uint8_t *data; }; uint64_t current_count = 0; void callback(shm::memory::Memblock *memblock) { if (memblock->is_empty()) { return; } auto *msg = reinterpret_cast<Message *>(memblock->ptr); auto lag = shm::current_time() - msg->timestamp; // assert(current_count == msg->count - 1); assert(current_count < msg->count); current_count = msg->count; per_second_lag.add(lag); } void subscribe_loop(int seconds) { shm::pubsub::Subscriber sub(topic, callback); for (int sec = 0; sec < seconds; ++sec) { auto start = std::chrono::steady_clock::now(); for (auto now = start; now < start + std::chrono::seconds(1); now = std::chrono::steady_clock::now()) { sub.spin_once(); } std::cout << per_second_lag << std::endl; per_second_lag.clear(); } } void publish_loop(int seconds, int vector_size) { std::cout << "Number of bytes = " << vector_size << std::endl; std::cout << "Time unit = " << TIMESCALE_NAME << std::endl; auto *rawptr = malloc(vector_size); std::memset(rawptr, 255, vector_size); Message *msg = reinterpret_cast<Message *>(rawptr); msg->count = 0; shm::pubsub::Publisher pub(topic); auto start = std::chrono::steady_clock::now(); for (auto now = start; now < start + std::chrono::seconds(seconds); now = std::chrono::steady_clock::now()) { msg->count++; msg->timestamp = shm::current_time(); pub.publish(msg, vector_size); } free(msg); } int main() { const int SECONDS = 10; const int VECTOR_SIZE = 32 * 1024; std::thread subscribe_thread(subscribe_loop, SECONDS); std::thread publish_thread(publish_loop, SECONDS, VECTOR_SIZE); subscribe_thread.join(); publish_thread.join(); }
31.188679
80
0.699335
38b0a2ca63301fbb52b3b23b0141c9cb8654473d
407
php
PHP
src/Domain/Game/Exception/UnexpectedNumberOfPlayers.php
rogergros/ddd-example
0f920a45946da668003733bc665feb73229b2cd0
[ "MIT" ]
1
2022-01-25T16:21:06.000Z
2022-01-25T16:21:06.000Z
src/Domain/Game/Exception/UnexpectedNumberOfPlayers.php
rogergros/ddd-example
0f920a45946da668003733bc665feb73229b2cd0
[ "MIT" ]
null
null
null
src/Domain/Game/Exception/UnexpectedNumberOfPlayers.php
rogergros/ddd-example
0f920a45946da668003733bc665feb73229b2cd0
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace DDDExample\Domain\Game\Exception; use DDDExample\Shared\Exception\UnexpectedValueException; final class UnexpectedNumberOfPlayers extends UnexpectedValueException { public function __construct(int $received, int $maxLanes) { parent::__construct(sprintf("Each game must have between 1 and %d players, received %d", $maxLanes, $received)); } }
25.4375
120
0.761671
e2c3ab4e7e1a7fbc423f0a67578e871c76706c56
105
py
Python
update_supply_chain_information/supply_chains/apps.py
uktrade/update-supply-chain-information
5cdcc795257b8351cf11b57487b194012ee8886d
[ "MIT" ]
null
null
null
update_supply_chain_information/supply_chains/apps.py
uktrade/update-supply-chain-information
5cdcc795257b8351cf11b57487b194012ee8886d
[ "MIT" ]
204
2021-05-26T16:15:04.000Z
2022-02-14T05:10:44.000Z
update_supply_chain_information/supply_chains/apps.py
uktrade/defend-data-capture
5cdcc795257b8351cf11b57487b194012ee8886d
[ "MIT" ]
1
2021-06-26T10:28:30.000Z
2021-06-26T10:28:30.000Z
from django.apps import AppConfig class SupplyChainUpdateConfig(AppConfig): name = "supply_chains"
17.5
41
0.790476
2caa275e81cc1de445765f7534d25b471bea7b79
464
py
Python
setup.py
Tbarkin121/CubeBot
02a96f5d71a27c9a8b1b6a6433f46d2ee7d8cc09
[ "MIT" ]
null
null
null
setup.py
Tbarkin121/CubeBot
02a96f5d71a27c9a8b1b6a6433f46d2ee7d8cc09
[ "MIT" ]
null
null
null
setup.py
Tbarkin121/CubeBot
02a96f5d71a27c9a8b1b6a6433f46d2ee7d8cc09
[ "MIT" ]
null
null
null
from setuptools import setup setup( name="simple_driving", version='0.0.1', install_requires=['gym', 'pybullet', 'numpy', 'matplotlib', 'torch'] ) setup( name="box_pendulum", version='0.0.1', install_requires=['gym', 'pybullet', 'numpy', 'matplotlib', 'torch'] )
22.095238
35
0.394397
ed42dc919b14845ce034c9f381d5bf45bb6b5db1
3,957
hpp
C++
src/cppsim_experimental/type.hpp
kodack64/qulacs-osaka
4ccc3ff084f10942e22d8663a01ed67efd24d9f7
[ "MIT" ]
null
null
null
src/cppsim_experimental/type.hpp
kodack64/qulacs-osaka
4ccc3ff084f10942e22d8663a01ed67efd24d9f7
[ "MIT" ]
null
null
null
src/cppsim_experimental/type.hpp
kodack64/qulacs-osaka
4ccc3ff084f10942e22d8663a01ed67efd24d9f7
[ "MIT" ]
null
null
null
#pragma once #include <Eigen/Core> #include <Eigen/Sparse> #include <cereal/access.hpp> #include <cereal/archives/portable_binary.hpp> #include <cereal/cereal.hpp> #include <cereal/types/base_class.hpp> #include <cereal/types/complex.hpp> #include <cereal/types/memory.hpp> #include <cereal/types/polymorphic.hpp> #include <cereal/types/tuple.hpp> #include <cereal/types/vector.hpp> #include <complex> #include <csim/type.hpp> typedef std::complex<double> CPPCTYPE; typedef Eigen::VectorXcd ComplexVector; // In order to use matrix raw-data without reordering, we use RowMajor as // default. typedef Eigen::Matrix<CPPCTYPE, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> ComplexMatrix; typedef Eigen::SparseMatrix<CPPCTYPE> SparseComplexMatrix; // reference: // https://stackoverflow.com/questions/22884216/serializing-eigenmatrix-using-cereal-library namespace cereal { template <class Archive> void save(Archive& ar, const ComplexMatrix& m) { size_t rows = m.rows(); size_t cols = m.cols(); ar(rows); ar(cols); ar(binary_data( m.data(), static_cast<std::size_t>(rows * cols * sizeof(CPPCTYPE)))); } template <class Archive> void load(Archive& ar, ComplexMatrix& m) { size_t rows; size_t cols; ar(rows); ar(cols); m.resize(rows, cols); ar(binary_data( m.data(), static_cast<std::size_t>(rows * cols * sizeof(CPPCTYPE)))); } template <class Archive> void save(Archive& ar, const ComplexVector& m) { size_t rows = m.rows(); size_t cols = m.cols(); ar(rows); ar(cols); ar(binary_data( m.data(), static_cast<std::size_t>(rows * cols * sizeof(CPPCTYPE)))); } template <class Archive> void load(Archive& ar, ComplexVector& m) { size_t rows; size_t cols; ar(rows); ar(cols); m.resize(rows, cols); ar(binary_data( m.data(), static_cast<std::size_t>(rows * cols * sizeof(CPPCTYPE)))); } template <class Archive> void save(Archive& ar, const SparseComplexMatrix& m) { Eigen::Index rows = m.rows(); Eigen::Index cols = m.cols(); ar(rows); ar(cols); std::vector<std::tuple<Eigen::Index, Eigen::Index, CPPCTYPE>> TripletList; for (Eigen::Index k = 0; k < m.outerSize(); ++k) { for (Eigen::SparseMatrix<CPPCTYPE>::InnerIterator it(m, k); it; ++it) { TripletList.push_back( std::tuple<Eigen::Index, Eigen::Index, CPPCTYPE>( it.row(), it.col(), it.value())); } } ar(TripletList); } template <class Archive> void load(Archive& ar, SparseComplexMatrix& m) { Eigen::Index rows; Eigen::Index cols; ar(rows); ar(cols); m.resize(rows, cols); std::vector<std::tuple<Eigen::Index, Eigen::Index, CPPCTYPE>> TripletList; ar(TripletList); std::vector<Eigen::Triplet<CPPCTYPE>> Triplets; for (size_t i = 0; i < TripletList.size(); ++i) { Triplets.push_back( Eigen::Triplet<CPPCTYPE>((int)std::get<0>(TripletList[i]), (int)std::get<1>(TripletList[i]), std::get<2>(TripletList[i]))); } m.setFromTriplets(Triplets.begin(), Triplets.end()); } template <class Archive> void save(Archive& ar, const Eigen::Triplet<CPPCTYPE>& m) { ar(m.row()); ar(m.col()); ar(m.value()); } template <class Archive> void load(Archive& ar, Eigen::Triplet<CPPCTYPE>& m) { int row, col, value; ar(row, col, value); m = Eigen::Triplet<CPPCTYPE>(row, col, value); } } // namespace cereal #ifdef __GNUC__ #if __GNUC__ >= 8 using namespace std::complex_literals; #endif #endif #ifdef _MSC_VER inline static FILE* popen(const char* command, const char* mode) { return _popen(command, mode); } inline static void pclose(FILE* fp) { _pclose(fp); } #define strncasecmp _strnicmp #define strcasecmp _stricmp #endif #if defined(__MINGW32__) || defined(_MSC_VER) #define DllExport __declspec(dllexport) #else #define DllExport __attribute__((visibility("default"))) #endif
27.289655
92
0.661865
93e4cec60a2e7c499bccc7dbaa8899c165f2c358
584
cs
C#
tests/SixLabors.Core.Tests/Helpers/GeometryUtilitiesTests.cs
aTiKhan/Core
28fb18f1ac34d526ee7fdb56dcfcfe9e5d381a49
[ "Apache-2.0" ]
25
2017-06-25T14:29:47.000Z
2022-01-26T15:09:14.000Z
tests/SixLabors.Core.Tests/Helpers/GeometryUtilitiesTests.cs
SixLabors/Primitives
28fb18f1ac34d526ee7fdb56dcfcfe9e5d381a49
[ "Apache-2.0" ]
22
2017-06-25T13:08:58.000Z
2019-08-08T16:10:08.000Z
tests/SixLabors.Core.Tests/Helpers/GeometryUtilitiesTests.cs
SixLabors/Primitives
28fb18f1ac34d526ee7fdb56dcfcfe9e5d381a49
[ "Apache-2.0" ]
24
2017-08-23T04:55:00.000Z
2020-06-30T21:43:27.000Z
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using Xunit; namespace SixLabors.Tests.Helpers { public class GeometryUtilitiesTests { [Fact] public void Convert_Degree_To_Radian() => Assert.Equal((float)(Math.PI / 2D), GeometryUtilities.DegreeToRadian(90F), new FloatRoundingComparer(6)); [Fact] public void Convert_Radian_To_Degree() => Assert.Equal(60F, GeometryUtilities.RadianToDegree((float)(Math.PI / 3D)), new FloatRoundingComparer(5)); } }
29.2
120
0.681507
e2719f88e0f21a862bb2f0ea12f3cf44f52e57ba
188
js
JavaScript
src/pages/index.js
Jay9596/JAM_greeting
724e3ed8f6444ca6fac8d107f832c1c6ddf44622
[ "MIT" ]
null
null
null
src/pages/index.js
Jay9596/JAM_greeting
724e3ed8f6444ca6fac8d107f832c1c6ddf44622
[ "MIT" ]
null
null
null
src/pages/index.js
Jay9596/JAM_greeting
724e3ed8f6444ca6fac8d107f832c1c6ddf44622
[ "MIT" ]
null
null
null
import React from 'react' import Link from 'gatsby-link' const IndexPage = () => ( <div> <h1>Hello! </h1> <p>\( ̄O ̄)</p> <p>I'm Jay.</p> </div> ) export default IndexPage
14.461538
30
0.558511
2ca604241ad4a9089d3cdf3375eaef03d46f60d3
1,505
cpp
C++
cpp/test/longest_common_subsequence_test.cpp
CarnaViire/training
5a01a022167a88a9c90bc6db4e14347ad60ee9e4
[ "Unlicense" ]
3
2017-07-08T05:18:33.000Z
2021-06-11T13:49:37.000Z
cpp/test/longest_common_subsequence_test.cpp
kondratyev-nv/training
ed28507694bc2026867b67c26dc9c4a955b24fb4
[ "Unlicense" ]
44
2017-10-05T20:23:03.000Z
2022-02-10T19:50:21.000Z
cpp/test/longest_common_subsequence_test.cpp
CarnaViire/training
5a01a022167a88a9c90bc6db4e14347ad60ee9e4
[ "Unlicense" ]
4
2017-10-06T19:29:55.000Z
2022-01-04T23:25:18.000Z
#include "gmock/gmock.h" #include "gtest/gtest.h" #include "longest_common_subsequence.hpp" TEST(longest_common_subsequence, returns_zero_for_empty_vector) { ASSERT_THAT(longest_common_subsequence({1, 2, 3}, {}), testing::ElementsAre()); ASSERT_THAT(longest_common_subsequence({}, {1, 2, 3}), testing::ElementsAre()); } TEST(longest_common_subsequence, returns_zero_for_no_common_symbols) { ASSERT_THAT(longest_common_subsequence({1, 2, 3}, {4, 5, 6}), testing::ElementsAre()); } TEST(longest_common_subsequence, returns_one_for_single_common_symbol) { ASSERT_THAT(longest_common_subsequence({1, 2, 3}, {4, 5, 6, 2}), testing::ElementsAre(2)); } TEST(longest_common_subsequence, returns_for_multiple_common_symbols) { ASSERT_THAT(longest_common_subsequence({2, 7, 5}, {2, 5}), testing::ElementsAre(2, 5)); ASSERT_THAT(longest_common_subsequence({2, 7, 8, 3}, {5, 2, 8, 7}), testing::AnyOf(testing::ElementsAre(2, 7), testing::ElementsAre(2, 8))); ASSERT_THAT(longest_common_subsequence({1, 2, 2, 3, 1, 4}, {2, 5, 3, 5, 1, 6, 4}), testing::ElementsAre(2, 3, 1, 4)); } TEST(longest_common_subsequence, returns_for_three_sequences) { ASSERT_THAT(longest_common_subsequence({8, 3, 2, 1, 7}, {8, 2, 1, 3, 8, 10, 7}, {6, 8, 3, 1, 4, 7}), testing::AnyOf(testing::ElementsAre(8, 3, 7), testing::ElementsAre(8, 1, 7))); ASSERT_THAT(longest_common_subsequence({1, 2, 3}, {2, 1, 3}, {1, 3, 5}), testing::ElementsAre(1, 3)); }
47.03125
105
0.684385
a1012ef120b5eff1a1583cb274b8ce84be0079fd
1,288
ts
TypeScript
app/user-form.component.ts
dmytro-lebedev/ng2-quiz
592742b0a038671d01869fe391e5808a3ae1a9a0
[ "Apache-2.0" ]
null
null
null
app/user-form.component.ts
dmytro-lebedev/ng2-quiz
592742b0a038671d01869fe391e5808a3ae1a9a0
[ "Apache-2.0" ]
null
null
null
app/user-form.component.ts
dmytro-lebedev/ng2-quiz
592742b0a038671d01869fe391e5808a3ae1a9a0
[ "Apache-2.0" ]
null
null
null
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UserService } from './user.service'; import { User } from './user.model'; @Component({ moduleId: module.id, selector: 'user-form', templateUrl: 'user-form.component.html', styleUrls: ['user-form.component.css'] }) export class UserFormComponent implements OnInit { user: User; submitted = false; constructor( private router: Router, private userService: UserService) { } ngOnInit(): void { this.userService.removeSessionUser(); this.user = new User('', ''); } getSubmitText(): string { if (this.router.isActive('/register', true)) { return 'Register'; } else { return 'Login'; } } onSubmit(): void { this.submitted = true; if (this.router.isActive('/register', true)) { this.userService.register(this.user) .then(() => this.router.navigate(['/login'])) .catch(() => this.submitted = false); } else { this.userService.login(this.user) .then(() => this.router.navigate(['/quiz'])) .catch(() => this.submitted = false); } } }
26.285714
61
0.550466
0a7155e9f27b29a072144d733e412046b14ed520
539
cs
C#
Source/Core/Runtime/Configuration/IInteractionComponentConfiguration.cs
VaLiuM09/VPG-Core
8b87c3b5877eb7d8c38302bc88e6641421c886ca
[ "Apache-2.0" ]
2
2021-07-15T18:43:25.000Z
2021-08-12T09:03:35.000Z
Source/Core/Runtime/Configuration/IInteractionComponentConfiguration.cs
MindPort-GmbH/VR-Builder-Core
8b87c3b5877eb7d8c38302bc88e6641421c886ca
[ "Apache-2.0" ]
1
2021-08-22T15:50:32.000Z
2021-08-22T15:50:32.000Z
Source/Core/Runtime/Configuration/IInteractionComponentConfiguration.cs
VaLiuM09/VPG-Core
8b87c3b5877eb7d8c38302bc88e6641421c886ca
[ "Apache-2.0" ]
4
2021-11-13T10:05:04.000Z
2022-03-10T08:06:20.000Z
namespace VRBuilder.Core.Configuration { /// <summary> /// Should be implemented by every interaction component in order to qualify as such. /// </summary> public interface IInteractionComponentConfiguration { /// <summary> /// Display name of the interaction component. /// </summary> string DisplayName { get; } /// <summary> /// True if the interaction component is meant to work with XR. /// </summary> bool IsXRInteractionComponent { get; } } }
28.368421
89
0.61039
45b07a4470e8dc5546324d1f703f9a61ca2a74cd
3,977
py
Python
tests/test_paragraphs.py
atvaccaro/homer
c19b08bca6a783041b1e9f2ee8ab7d392ab4626b
[ "MIT" ]
660
2019-08-11T08:16:29.000Z
2022-03-08T08:03:01.000Z
tests/test_paragraphs.py
atvaccaro/homer
c19b08bca6a783041b1e9f2ee8ab7d392ab4626b
[ "MIT" ]
8
2019-08-15T20:40:54.000Z
2021-09-29T17:41:45.000Z
tests/test_paragraphs.py
atvaccaro/homer
c19b08bca6a783041b1e9f2ee8ab7d392ab4626b
[ "MIT" ]
41
2019-08-15T18:33:00.000Z
2022-03-24T19:28:39.000Z
import unittest from homer import analyzer class TestParagraphs(unittest.TestCase): def test_sentence_length(self): sentences = [ { 'para': """Big or small, Panda is adorable. Call me something. But let me share a very interesting story with you, which I am sure you have never heard of.""", 'longest_sentence': """But let me share a very interesting story with you, which I am sure you have never heard of.""" }, { 'para': 'I love winter. Summer is good too. Autumn is the best and my whole family likes it.', 'longest_sentence': 'Autumn is the best and my whole family likes it.' }, { 'para': 'Do you like great books? I love books. They really get me going since they help me enhance my knowledge.', 'longest_sentence': 'They really get me going since they help me enhance my knowledge.' } ] for data in sentences: paragraph_obj = analyzer.Paragraph(data['para']) self.assertEqual(data['longest_sentence'], str(paragraph_obj.longest_sentence)) def test_word_count(self): sentences = [ { 'para': '''Life is short, as everyone knows. When I was a kid I used to wonder about this. Is life actually short, or are we really complaining about its finiteness? Would we be just as likely to feel life was short if we lived 10 times as long?''', 'words': 47, 'sentences': 4 }, { 'para': '''Having kids showed me how to convert a continuous quantity, time, into discrete quantities. You only get 52 weekends with your 2 year old. If Christmas-as-magic lasts from say ages 3 to 10, you only get to watch your child experience it 8 times. And while it's impossible to say what is a lot or a little of a continuous quantity like time, 8 is not a lot of something. If you had a handful of 8 peanuts, or a shelf of 8 books to choose from, the quantity would definitely seem limited, no matter what your lifespan was.''', 'words': 98, 'sentences': 5 }, { 'para': '''Ok, so life actually is short. Does it make any difference to know that?''', 'words': 14, 'sentences': 2 }, { 'para': '''Call me Ishmael. Some years ago—never mind how long precisely— having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off—then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me.''', 'words': 201, 'sentences': 8 } ] for data in sentences: para = analyzer.Paragraph(data['para']) # for p in para.sentences: # print(p.words) self.assertEqual(data['words'], para.total_words) self.assertEqual(data['sentences'], len(para)) if __name__ == "__main__": unittest.main()
67.40678
1,139
0.638169
72d51d65ddc274fc72b09b888eebf6f9603ea146
467
rs
Rust
cli/ext/main.rs
patractlabs/wasm-utils
b4cda1c6f8afc0e9e4f02550598b77383fa95ea7
[ "Apache-2.0", "MIT" ]
1
2022-02-18T03:53:56.000Z
2022-02-18T03:53:56.000Z
cli/ext/main.rs
patractlabs/wasm-utils
b4cda1c6f8afc0e9e4f02550598b77383fa95ea7
[ "Apache-2.0", "MIT" ]
null
null
null
cli/ext/main.rs
patractlabs/wasm-utils
b4cda1c6f8afc0e9e4f02550598b77383fa95ea7
[ "Apache-2.0", "MIT" ]
1
2021-11-13T10:48:22.000Z
2021-11-13T10:48:22.000Z
fn main() { pwasm_utils::logger::init(); let args = std::env::args().collect::<Vec<_>>(); if args.len() != 3 { println!("Usage: {} input_file.wasm output_file.wasm", args[0]); return; } let module = pwasm_utils::externalize( parity_wasm::deserialize_file(&args[1]).expect("Module to deserialize ok"), vec!["_free", "_malloc", "_memcpy", "_memset", "_memmove"], ); parity_wasm::serialize_to_file(&args[2], module).expect("Module to serialize ok"); }
27.470588
83
0.659529
82e9718eecc334cce94783358b9794ea44d3d760
129
ps1
PowerShell
src/Public/Schemas/Get-OktaSchemas.ps1
natescherer/OktaAdmin
caeb1bbec3fa505d23a47cd266bb5cae8dad5940
[ "MIT" ]
null
null
null
src/Public/Schemas/Get-OktaSchemas.ps1
natescherer/OktaAdmin
caeb1bbec3fa505d23a47cd266bb5cae8dad5940
[ "MIT" ]
null
null
null
src/Public/Schemas/Get-OktaSchemas.ps1
natescherer/OktaAdmin
caeb1bbec3fa505d23a47cd266bb5cae8dad5940
[ "MIT" ]
null
null
null
function Get-OktaSchemas { [CmdletBinding()] param() Invoke-OktaApi -Uri "v1/meta/schemas/user/default" -Method GET }
25.8
66
0.689922
4b91b0f9fe178a22024479cf967d1b16dc4dbe2e
6,467
cpp
C++
OpenSimRoot/src/modules/WaterModule/WaterUptakeByRoots.cpp
nb-e/OpenRootSim
aaa1cd18e94ebf613c28737842401daba3b8d5ef
[ "BSD-3-Clause" ]
1
2021-08-03T00:52:58.000Z
2021-08-03T00:52:58.000Z
OpenSimRoot/src/modules/WaterModule/WaterUptakeByRoots.cpp
nb-e/OpenRootSim
aaa1cd18e94ebf613c28737842401daba3b8d5ef
[ "BSD-3-Clause" ]
null
null
null
OpenSimRoot/src/modules/WaterModule/WaterUptakeByRoots.cpp
nb-e/OpenRootSim
aaa1cd18e94ebf613c28737842401daba3b8d5ef
[ "BSD-3-Clause" ]
1
2021-08-03T00:52:59.000Z
2021-08-03T00:52:59.000Z
/* Copyright © 2016, The Pennsylvania State University All rights reserved. Copyright © 2016 Forschungszentrum Jülich GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted under the GNU General Public License v3 and provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer 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. You should have received the GNU GENERAL PUBLIC LICENSE v3 with this file in license.txt but can also be found at http://www.gnu.org/licenses/gpl-3.0.en.html NOTE: The GPL.v3 license requires that all derivative work is distributed under the same license. That means that if you use this source code in any other program, you can only distribute that program with the full source code included and licensed under a GPL license. */ #include "WaterUptakeByRoots.hpp" #include "../PlantType.hpp" WaterUptakeFromHopmans::WaterUptakeFromHopmans(SimulaDynamic* pSD):DerivativeBase(pSD) { //Check the units if(pSD->getUnit()=="cm3") { mode=1; }else if (pSD->getUnit()=="cm3/cm"){ mode=0; }else{ msg::error("WaterUptakeFromHopmans: expected unit cm3"); } //pointer to total transpiration of this plant SimulaBase *plant(pSD); PLANTTOP(plant) potentialTranspiration=plant->getChild("plantPosition")->getChild("shoot")->getChild("potentialTranspiration","cm3"); //pointer to segment length segmentLength=pSD->getSibling("rootSegmentLength","cm"); //check position of the root Coordinate pos; pSD->getAbsolute(pSD->getStartTime(),pos); if(pos.y>=0) mode=-1; //pointer to total root length totalRootLength=plant->existingChild("rootLengthBelowTheSurface",segmentLength->getUnit()); if(!totalRootLength){ totalRootLength=plant->getChild("rootLongitudinalGrowth",segmentLength->getUnit()); if(mode<0) msg::warning("WaterUptakeFromHopmans: rootsegment is above ground, but averaging potential transpiration over total root length. Consider adding rootLenthBelowTheSurface to your plant template."); } } void WaterUptakeFromHopmans::calculate(const Time &t,double &total){ if(mode==-1){ //root is above ground, set uptake to 0 total=0; return; } //get the total transpiration double tr; potentialTranspiration->getRate(t,tr); //get fraction double tl; totalRootLength->get(t,tl); if(tl!=0){ if(mode){ double sl; segmentLength->get(t,sl); total=tr*(sl/tl); }else{ total=tr/tl; } }else{ if (tr!=0)msg::warning("WaterUptakeFromHopmans: Transpiration but zero root length."); total=0; } } std::string WaterUptakeFromHopmans::getName()const{ return "waterUptakeFromHopmans"; } DerivativeBase * newInstantiationWaterUptakeFromHopmans(SimulaDynamic* const pSD){ return new WaterUptakeFromHopmans(pSD); } ScaledWaterUptake::ScaledWaterUptake(SimulaDynamic* pSD):DerivativeBase(pSD) { //Check the units if(pSD->getUnit()=="cm3") { length=nullptr; }else if (pSD->getUnit()=="cm3/cm"){ length=pSD->getSibling("rootSegmentLength","cm");; }else{ msg::error("ScaledWaterUptake: expected unit cm3"); } //pointer to total transpiration of this plant SimulaBase *plant(pSD); PLANTTOP(plant) actualTranspiration=plant->getChild("plantPosition")->getChild("shoot")->getChild("actualTranspiration","cm3");; total=plant->getChild("rootPotentialWaterUptake","cm3"); fraction=pSD->getSibling("rootSegmentPotentialWaterUptake","cm3"); } void ScaledWaterUptake::calculate(const Time &t,double &uptake){ //get the total transpiration actualTranspiration->getRate(t,uptake); //get fraction double tl; total->getRate(t,tl); if(tl!=0){ double sl; fraction->getRate(t,sl); uptake*=(sl/tl); if(length){ length->get(t,sl); if(sl>0){ uptake/=sl; }else{ uptake=0; } } }else{ uptake=0; } if(std::isnan(uptake)) msg::error("ScaledWaterUptake: value is nan"); } std::string ScaledWaterUptake::getName()const{ return "scaledWaterUptake"; } DerivativeBase * newInstantiationScaledWaterUptake(SimulaDynamic* const pSD){ return new ScaledWaterUptake(pSD); } GetValuesFromPlantWaterUptake::GetValuesFromPlantWaterUptake(SimulaDynamic* pSD):DerivativeBase(pSD){ SimulaBase * top=pSD->getParent(); if(!top->existingChild("plantPosition") ) { PLANTTOP(top); } wu=top->getChild("rootWaterUptakeCheck"); } std::string GetValuesFromPlantWaterUptake::getName()const{ return "getValuesFromPlantWaterUptake"; } void GetValuesFromPlantWaterUptake::calculate(const Time &t,double &var){ wu->get(t,var); } DerivativeBase * newInstantiationGetValuesFromPlantWaterUptake(SimulaDynamic* const pSD) { return new GetValuesFromPlantWaterUptake(pSD); } //Register the module class AutoRegisterWaterUptakeInstantiationFunctions { public: AutoRegisterWaterUptakeInstantiationFunctions() { BaseClassesMap::getDerivativeBaseClasses()["waterUptakeFromHopmans"] = newInstantiationWaterUptakeFromHopmans; BaseClassesMap::getDerivativeBaseClasses()["scaledWaterUptake"] = newInstantiationScaledWaterUptake; BaseClassesMap::getDerivativeBaseClasses()["getValuesFromPlantWaterUptake"] = newInstantiationGetValuesFromPlantWaterUptake; } }; // our one instance of the proxy static AutoRegisterWaterUptakeInstantiationFunctions l654645648435135753;
37.381503
755
0.772692
1a66b293fa34e0968068877c8dd7bc6153a6215c
453
py
Python
app/email.py
derrokip34/Pitch
1fa82422024aaaacfb912ae1aea6d43f1ef09d12
[ "MIT" ]
null
null
null
app/email.py
derrokip34/Pitch
1fa82422024aaaacfb912ae1aea6d43f1ef09d12
[ "MIT" ]
null
null
null
app/email.py
derrokip34/Pitch
1fa82422024aaaacfb912ae1aea6d43f1ef09d12
[ "MIT" ]
null
null
null
from flask_mail import Message from flask import render_template from . import mail from app.models import User subject_pref = 'PITCH IDEAS' sender_email = 'derrickip34@gmail.com' def mail_message(subject,template,to,**kwargs): email = Message(subject_pref+subject, sender=sender_email, recipients=[to]) email.body= render_template(template + ".txt",**kwargs) email.html = render_template(template + ".html",**kwargs) mail.send(email)
32.357143
79
0.754967
f6121cfdbab82fc640601de7f28d2d1300055ee8
8,281
cpp
C++
examples/prepared_statement.cpp
tstrutz/sqlite_orm
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
[ "BSD-3-Clause" ]
1,566
2016-12-20T15:31:04.000Z
2022-03-31T18:17:34.000Z
examples/prepared_statement.cpp
tstrutz/sqlite_orm
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
[ "BSD-3-Clause" ]
620
2017-01-06T13:53:35.000Z
2022-03-31T12:05:50.000Z
examples/prepared_statement.cpp
tstrutz/sqlite_orm
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
[ "BSD-3-Clause" ]
274
2017-01-07T05:34:24.000Z
2022-03-27T18:22:47.000Z
/** * There are two member functions in storage_t class which you need to use to operate with * prepared statements: storage_t::prepare and storage_t::execute. * Also if you need to rebind arguments just use get<N>(statement) = ... syntax * just like you do with std::tuple. * Once a statement is prepared it holds a connection to a database inside. This connection will be open * until at least one statement object exists. */ #include <sqlite_orm/sqlite_orm.h> #include <iostream> using namespace sqlite_orm; using std::cout; using std::endl; struct Doctor { int doctor_id = 0; std::string doctor_name; std::string degree; }; struct Speciality { int spl_id = 0; std::string spl_descrip; int doctor_id = 0; }; struct Visit { int doctor_id = 0; std::string patient_name; std::string vdate; }; int main() { auto storage = make_storage("prepared.sqlite", make_table("doctors", make_column("doctor_id", &Doctor::doctor_id, primary_key()), make_column("doctor_name", &Doctor::doctor_name), make_column("degree", &Doctor::degree)), make_table("speciality", make_column("spl_id", &Speciality::spl_id, primary_key()), make_column("spl_descrip", &Speciality::spl_descrip), make_column("doctor_id", &Speciality::doctor_id)), make_table("visits", make_column("doctor_id", &Visit::doctor_id), make_column("patient_name", &Visit::patient_name), make_column("vdate", &Visit::vdate))); storage.sync_schema(); storage.remove_all<Doctor>(); storage.remove_all<Speciality>(); storage.remove_all<Visit>(); { // first we create a statement object for replace query with a doctor object auto replaceStatement = storage.prepare(replace(Doctor{210, "Dr. John Linga", "MD"})); cout << "replaceStatement = " << replaceStatement.sql() << endl; // next we execute our statement storage.execute(replaceStatement); // now 'doctors' table has one row [210, 'Dr. John Linga', 'MD'] // Next we shall reuse the statement to replace another doctor // replaceStatement contains a doctor inside it which can be obtained // with get<0>(statement) function get<0>(replaceStatement) = {211, "Dr. Peter Hall", "MBBS"}; storage.execute(replaceStatement); // now 'doctors' table has two rows. // Next we shall reuse the statement again with member assignment auto &doctor = get<0>(replaceStatement); // doctor is Doctor & doctor.doctor_id = 212; doctor.doctor_name = "Dr. Ke Gee"; doctor.degree = "MD"; storage.execute(replaceStatement); // now 'doctors' table has three rows. } { // also prepared statement can store arguments by reference. To do this you can // pass a std::reference_wrapper instead of object value. Doctor doctorToReplace{213, "Dr. Pat Fay", "MD"}; auto replaceStatementByRef = storage.prepare(replace(std::ref(doctorToReplace))); cout << "replaceStatementByRef = " << replaceStatementByRef.sql() << endl; storage.execute(replaceStatementByRef); // now 'doctors' table has four rows. // next we shall change doctorToReplace object and then execute our statement. // Statement will be affected cause it stores a reference to the doctor doctorToReplace.doctor_id = 214; doctorToReplace.doctor_name = "Mosby"; doctorToReplace.degree = "MBBS"; storage.execute(replaceStatementByRef); // and now 'doctors' table has five rows } cout << "Doctors count = " << storage.count<Doctor>() << endl; for(auto &doctor: storage.iterate<Doctor>()) { cout << storage.dump(doctor) << endl; } { auto insertStatement = storage.prepare(insert(Speciality{1, "CARDIO", 211})); cout << "insertStatement = " << insertStatement.sql() << endl; storage.execute(insertStatement); get<0>(insertStatement) = {2, "NEURO", 213}; storage.execute(insertStatement); get<0>(insertStatement) = {3, "ARTHO", 212}; storage.execute(insertStatement); get<0>(insertStatement) = {4, "GYNO", 210}; storage.execute(insertStatement); } cout << "Specialities count = " << storage.count<Speciality>() << endl; for(auto &speciality: storage.iterate<Speciality>()) { cout << storage.dump(speciality) << endl; } { // let's insert (replace) 5 visits. We create two vectors with 2 visits each std::vector<Visit> visits; visits.push_back({210, "Julia Nayer", "2013-10-15"}); visits.push_back({214, "TJ Olson", "2013-10-14"}); // let's make a statement auto replaceRangeStatement = storage.prepare(replace_range(visits.begin(), visits.end())); cout << "replaceRangeStatement = " << replaceRangeStatement.sql() << endl; // replace two objects storage.execute(replaceRangeStatement); std::vector<Visit> visits2; visits2.push_back({215, "John Seo", "2013-10-15"}); visits2.push_back({212, "James Marlow", "2013-10-16"}); // reassign iterators to point to other visits. Beware that if end - begin // will have different distance then you'll get a runtime error cause statement is // already compiled with a fixed amount of arguments to bind get<0>(replaceRangeStatement) = visits2.begin(); get<1>(replaceRangeStatement) = visits2.end(); storage.execute(replaceRangeStatement); storage.replace(Visit{212, "Jason Mallin", "2013-10-12"}); } cout << "Visits count = " << storage.count<Visit>() << endl; for(auto &visit: storage.iterate<Visit>()) { cout << storage.dump(visit) << endl; } { // SELECT doctor_id // FROM visits // WHERE LENGTH(patient_name) > 8 auto selectStatement = storage.prepare(select(&Visit::doctor_id, where(length(&Visit::patient_name) > 8))); cout << "selectStatement = " << selectStatement.sql() << endl; { auto rows = storage.execute(selectStatement); cout << "rows count = " << rows.size() << endl; for(auto &id: rows) { cout << id << endl; } } // same statement, other bound values // SELECT doctor_id // FROM visits // WHERE LENGTH(patient_name) > 11 { get<0>(selectStatement) = 11; auto rows = storage.execute(selectStatement); cout << "rows count = " << rows.size() << endl; for(auto &id: rows) { cout << id << endl; } } } { // SELECT rowid, 'Doctor ' || doctor_name // FROM doctors // WHERE degree LIKE '%S' auto selectStatement = storage.prepare( select(columns(rowid(), "Doctor " || c(&Doctor::doctor_name)), where(like(&Doctor::degree, "%S")))); cout << "selectStatement = " << selectStatement.sql() << endl; { auto rows = storage.execute(selectStatement); cout << "rows count = " << rows.size() << endl; for(auto &row: rows) { cout << get<0>(row) << '\t' << get<1>(row) << endl; } } // SELECT rowid, 'Nice ' || doctor_name // FROM doctors // WHERE degree LIKE '%D' get<0>(selectStatement) = "Nice "; get<1>(selectStatement) = "%D"; { auto rows = storage.execute(selectStatement); cout << "rows count = " << rows.size() << endl; for(auto &row: rows) { cout << get<0>(row) << '\t' << get<1>(row) << endl; } } } return 0; }
39.433333
115
0.567685
da6af458f7a6db975200d01d74e56002df022eb1
3,342
php
PHP
resources/views/survey/layouts/results.blade.php
johnpyle6/survey
640d3f41ffff5249a2dd19c537d00d56d0963a10
[ "MIT" ]
null
null
null
resources/views/survey/layouts/results.blade.php
johnpyle6/survey
640d3f41ffff5249a2dd19c537d00d56d0963a10
[ "MIT" ]
null
null
null
resources/views/survey/layouts/results.blade.php
johnpyle6/survey
640d3f41ffff5249a2dd19c537d00d56d0963a10
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="eng"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>The Wealth Authority</title> <link rel="Shortcut icon" href="http://www.wealthauthority.com/wp-content/themes/the_wealth_authority/images/favicon.ico" /> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="/survey.js"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-24216112-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <link rel="stylesheet" href="/results.css"> </head> <body class="container-fluid" style="background-image: url(/images/{{ $survey->layout->bg_image_name }})"> <div id="main" class="center-block"> <header> <p class="header-top"> {{ date('l, F j') }} </p> @section('header') <p> <span class="header-text-top">{{ $survey->layout->header_text_top }}</span><br> <img class="center-block img-responsive header-img" src="/images/{{ $survey->layout->header_image_name }}" alt=""><br> </p> <div class="jumbotron"> <h1 class="header-text-bottom">{{ $survey->layout->header_text_bottom }}</h1> <p class="header-text-bottom"> <a class="btn btn-primary btn-lg" onclick="surveyScroll()"> View Live Stats<br> <span class="scroll"><em>Scroll Down</em></span> </a> </p> </div> </p> <p class="header-bottom"> </p> </header> <hr> <section id="survey"> @foreach ($survey->questions as $question) {{ $question->qorder}}. {{$question->text}} <ul> @foreach ($question->answers as $answer) <li>{{$answer->text}}: <strong>{{ $answer->percentage }}% ({{ $answer->votes }} votes)</strong></li> @endforeach </ul> @endforeach </section> @if (count($survey->ads) > 0) <section id="re" class="container-fluid"> @foreach($survey->ads as $ad) @include('survey.ads.' . $ad->template_name) @endforeach </section> @endif @if ($survey->layout->show_logo) <section id="newhead"> <img class="center-block img-responsive headerimg" src="/images/newhead.png" alt=""/> </section> @endif <footer id="content-footer"> @if ( $survey->layout->org == "WA") @include('survey.layouts.footer_wa') @elseif ($survey->layout->org == "LOP") @include('survey.layouts.footer_lop') @endif </footer> </div> </body> </html>
32.764706
134
0.552663
a4110dea932ba890bf18c66c34217db0822d6e7f
272
php
PHP
src/Api/HiPay/Model/Status/NotificationStatus.php
hipay/hipay-wallet-cashout-mirakl-library
a40ae6535f824a4a789a2fe795b84e3bd2e5755e
[ "Apache-2.0" ]
7
2017-04-27T15:33:49.000Z
2022-02-02T14:32:05.000Z
src/Api/HiPay/Model/Status/NotificationStatus.php
hipay/hipay-wallet-cashout-mirakl-library
a40ae6535f824a4a789a2fe795b84e3bd2e5755e
[ "Apache-2.0" ]
3
2016-09-01T13:39:43.000Z
2017-12-14T18:07:41.000Z
src/Api/HiPay/Model/Status/NotificationStatus.php
hipay/hipay-wallet-cashout-mirakl-library
a40ae6535f824a4a789a2fe795b84e3bd2e5755e
[ "Apache-2.0" ]
5
2016-03-07T08:51:47.000Z
2019-06-09T18:08:54.000Z
<?php namespace HiPay\Wallet\Mirakl\Api\HiPay\Model\Status; /** * Constants for the status of the notification * * @author Ivanis Kouamé <ivanis.kouame@smile.fr> * @copyright 2015 Smile */ class NotificationStatus { const OK = 'ok'; const NOK = 'nok'; }
17
53
0.676471
7c08cee77f26b7d8c4698edd2646d083c5652c23
2,040
py
Python
scripts/artifacts/deviceActivator.py
xperylabhub/iLEAPP
fd1b301bf2094387f51ccdbd10ed233ce9abd687
[ "MIT" ]
325
2019-12-24T08:04:05.000Z
2022-03-31T13:46:21.000Z
scripts/artifacts/deviceActivator.py
xperylabhub/iLEAPP
fd1b301bf2094387f51ccdbd10ed233ce9abd687
[ "MIT" ]
85
2020-02-13T11:31:28.000Z
2022-03-28T20:22:42.000Z
scripts/artifacts/deviceActivator.py
xperylabhub/iLEAPP
fd1b301bf2094387f51ccdbd10ed233ce9abd687
[ "MIT" ]
69
2019-12-31T15:49:28.000Z
2022-03-27T17:23:03.000Z
import re import base64 import os from itertools import compress import xml.etree.ElementTree as ET from scripts.artifact_report import ArtifactHtmlReport from scripts.ilapfuncs import logfunc, tsv, logdevinfo, is_platform_windows def get_deviceActivator(files_found, report_folder, seeker): data_list = [] alllines = '' file_found = str(files_found[0]) with open(file_found, 'r') as f_in: for line in f_in: line = line.strip() alllines = alllines + line found = re.findall('<key>ActivationInfoXML</key><data>(.*)</data><key>RKCertification</key><data>', alllines) base64_message= found[0] data = base64.b64decode(base64_message) outpath = os.path.join(report_folder, "results.xml") with open(outpath, 'wb') as f_out: f_out.write(data) xmlfile = outpath tree = ET.parse(xmlfile) root = tree.getroot() for elem in root: for elemx in elem: for elemz in elemx: data_list.append(str(elemz.text).strip()) it = iter(data_list) results = list(zip(it, it)) for x in results: if x[0] == 'EthernetMacAddress': logdevinfo(f"Ethernet Mac Address: {x[1]}") if x[0] == 'BluetoothAddress': logdevinfo(f"Bluetooth Address: {x[1]}") if x[0] == 'WifiAddress': logdevinfo(f"Wifi Address: {x[1]}") if x[0] == 'ModelNumber': logdevinfo(f"Model Number: {x[1]}") if len(results) > 0: report = ArtifactHtmlReport('iOS Device Activator Data') report.start_artifact_report(report_folder, 'iOS Device Activator Data') report.add_script() data_headers = ('Key','Values') report.write_artifact_data_table(data_headers, results, file_found) report.end_artifact_report() tsvname = 'iOS Device Activator Data' tsv(report_folder, data_headers, results, tsvname) else: logfunc('No iOS Device Activator Data')
31.875
113
0.622059
6735c412e2a7a4431eea957f9e67f24a0156dfdc
16,027
rs
Rust
dpar/src/models/tensorflow/collector.rs
sfb833-a3/dpar
4ec74f78238198b7ce9fc21b46e19f47b34ddf19
[ "Apache-2.0" ]
null
null
null
dpar/src/models/tensorflow/collector.rs
sfb833-a3/dpar
4ec74f78238198b7ce9fc21b46e19f47b34ddf19
[ "Apache-2.0" ]
4
2019-01-25T14:56:21.000Z
2019-03-13T08:04:51.000Z
dpar/src/models/tensorflow/collector.rs
sfb833-a3/dpar
4ec74f78238198b7ce9fc21b46e19f47b34ddf19
[ "Apache-2.0" ]
null
null
null
use enum_map::EnumMap; use tensorflow::Tensor; use failure::Error; use features::{InputVectorizer, Layer}; use models::tensorflow::{CopyBatches, InstanceSlices, LayerTensors, TensorWrap}; use system::ParserState; use system::TransitionSystem; use train::InstanceCollector; /// Collect gold-standard instances into Tensorflow tensors. /// /// This data type implements the `Collector` trait, collecting instances /// into Tensorflow tensors. The collected instances can be used to train /// or validate a ternsorflow model. /// /// After all instances are collected, the `into_data` method can be used /// to get the collected tensors. The last batch will be resized to the /// number of instances collected into the last batch. pub struct TensorCollector<'a, T> { transition_system: T, vectorizer: &'a InputVectorizer, batch_size: usize, lookup_inputs: Vec<LayerTensors<i32>>, labels: Vec<Tensor<i32>>, non_lookup_inputs: Vec<Tensor<f32>>, instance_idx: usize, } impl<'a, T> TensorCollector<'a, T> where T: TransitionSystem, { /// Construct a tensor collector. /// /// The tensor collector will use the given transition system, parser state /// vectorizer, and batch size. pub fn new(transition_system: T, vectorizer: &'a InputVectorizer, batch_size: usize) -> Self { TensorCollector { transition_system, vectorizer, batch_size, lookup_inputs: Vec::new(), labels: Vec::new(), non_lookup_inputs: Vec::new(), instance_idx: 0, } } /// Resize the last batch to the number of instances in that batch. fn resize_last_batch(&mut self) { if self.instance_idx == 0 { return; } let last_size = self.instance_idx; let old_lookup_inputs = self.lookup_inputs.pop().expect("No batches"); self.lookup_inputs .push(old_lookup_inputs.copy_batches(last_size as u64)); let old_labels = self.labels.pop().expect("No batches"); self.labels.push(old_labels.copy_batches(last_size as u64)); let old_non_lookup_inputs = self.non_lookup_inputs.pop().expect("No batches"); self.non_lookup_inputs .push(old_non_lookup_inputs.copy_batches(last_size as u64)); } /// Get the collected tensors. /// /// This method returns the collected label and vectorized parser state /// tensors. Each tensor is `batch_size` in its first dimension, except /// the last label/layer tensors, which is sized to the number of instances /// of the last batch. pub fn into_data(mut self) -> (Vec<Tensor<i32>>, Vec<LayerTensors<i32>>, Vec<Tensor<f32>>) { self.resize_last_batch(); (self.labels, self.lookup_inputs, self.non_lookup_inputs) } /// Get the transition system of the collector. pub fn transition_system(&self) -> &T { &self.transition_system } /// Construct net layer batch tensors. /// /// Each tensor has shape `[batch_size, layer_size]`. fn new_layer_tensors(&self, batch_size: usize) -> LayerTensors<i32> { let layer_sizes = self.vectorizer.layer_sizes(); let mut layers: EnumMap<Layer, TensorWrap<i32>> = EnumMap::new(); for (layer, tensor) in &mut layers { *tensor = TensorWrap(Tensor::new(&[batch_size as u64, layer_sizes[layer] as u64])); } layers } } impl<'a, T> InstanceCollector<T> for TensorCollector<'a, T> where T: TransitionSystem, { fn collect(&mut self, t: &T::Transition, state: &ParserState) -> Result<(), Error> { // Lazily add a new batch tensor. let n_deprel_embeds = self .vectorizer .layer_lookups() .layer_lookup(Layer::DepRel) .unwrap() .len(); if self.instance_idx == 0 { let layer_tensors = self.new_layer_tensors(self.batch_size); self.lookup_inputs.push(layer_tensors); self.labels.push(Tensor::new(&[self.batch_size as u64])); self.non_lookup_inputs.push(Tensor::new(&[ self.batch_size as u64, (n_deprel_embeds * T::ATTACHMENT_ADDRS.len()) as u64, ])); } let batch = self.labels.len() - 1; let label = self.transition_system.transitions().lookup(t.clone()); self.labels[batch][self.instance_idx] = label as i32; let n_non_lookup_inputs = n_deprel_embeds * T::ATTACHMENT_ADDRS.len(); self.vectorizer.realize_into( state, &mut self.lookup_inputs[batch].to_instance_slices(self.instance_idx), &mut self.non_lookup_inputs[batch][(self.instance_idx * n_non_lookup_inputs) ..(self.instance_idx * n_non_lookup_inputs + n_non_lookup_inputs)], &T::ATTACHMENT_ADDRS, ); self.instance_idx += 1; if self.instance_idx == self.batch_size { self.instance_idx = 0; } Ok(()) } } #[cfg(test)] mod tests { use std::collections::HashMap; use conllx::Token; use features::addr::{AddressedValue, Layer, Source}; use features::{ self, AddressedValues, InputVectorizer, LayerLookups, Lookup, MutableLookupTable, }; use system::{ParserState, Transition}; use systems::stack_projective::{StackProjectiveSystem, StackProjectiveTransition}; use train::InstanceCollector; use super::TensorCollector; #[test] fn collect_zero() { let vectorizer = test_vectorizer(); let collector = test_collector(&vectorizer); let (labels, lookup_inputs, non_lookup_inputs) = collector.into_data(); assert_eq!(labels.len(), 0); assert_eq!(lookup_inputs.len(), 0); assert_eq!(non_lookup_inputs.len(), 0); } #[test] fn collect_two() { let sent = vec![Token::new("een"), Token::new("test")]; let mut state = ParserState::new(&sent); let vectorizer = test_vectorizer(); let mut collector = test_collector(&vectorizer); collector .collect(&StackProjectiveTransition::Shift, &state) .unwrap(); StackProjectiveTransition::Shift.apply(&mut state); collector .collect(&StackProjectiveTransition::LeftArc("FOO".into()), &state) .unwrap(); let (labels, lookup_inputs, non_lookup_inputs) = collector.into_data(); // There should be one batch. assert_eq!(labels.len(), 1); assert_eq!(lookup_inputs.len(), 1); assert_eq!(non_lookup_inputs.len(), 1); // Check batch shapes. assert_eq!(labels[0].dims(), &[2]); assert_eq!(lookup_inputs[0][features::Layer::Token].dims(), &[2, 2]); assert_eq!(non_lookup_inputs[0].dims(), &[2, 2]); assert_eq!(lookup_inputs[0][features::Layer::DepRel].dims(), &[2, 0]); // Check batch contents. assert_eq!(&*labels[0], &[1, 2]); assert_eq!( lookup_inputs[0][features::Layer::Token].as_ref(), &[1, 2, 2, 3] ); assert_eq!(&*non_lookup_inputs[0], &[0.0, 0.0, 0.0, 0.0]); } #[test] fn collect_three() { let sent = vec![ Token::new("een"), Token::new("collector"), Token::new("test"), ]; let mut state = ParserState::new(&sent); let vectorizer = test_vectorizer(); let mut collector = test_collector(&vectorizer); collector .collect(&StackProjectiveTransition::Shift, &state) .unwrap(); StackProjectiveTransition::Shift.apply(&mut state); collector .collect(&StackProjectiveTransition::Shift, &state) .unwrap(); StackProjectiveTransition::Shift.apply(&mut state); collector .collect(&StackProjectiveTransition::LeftArc("FOO".into()), &state) .unwrap(); let (labels, lookup_inputs, non_lookup_inputs) = collector.into_data(); // There should be two batches. assert_eq!(labels.len(), 2); assert_eq!(lookup_inputs.len(), 2); assert_eq!(non_lookup_inputs.len(), 2); // Check batch shapes. assert_eq!(labels[0].dims(), &[2]); assert_eq!(lookup_inputs[0][features::Layer::Token].dims(), &[2, 2]); assert_eq!(non_lookup_inputs[0].dims(), &[2, 2]); assert_eq!(labels[1].dims(), &[1]); assert_eq!(lookup_inputs[1][features::Layer::Token].dims(), &[1, 2]); assert_eq!(non_lookup_inputs[1].dims(), &[1, 2]); // Check batch contents. assert_eq!(&*labels[0], &[1, 1]); assert_eq!( lookup_inputs[0][features::Layer::Token].as_ref(), &[1, 2, 2, 3] ); assert_eq!(&*non_lookup_inputs[0], &[0.0, 0.0, 0.0, 0.0]); assert_eq!(&*labels[1], &[2]); assert_eq!(lookup_inputs[1][features::Layer::Token].as_ref(), &[3, 4]); assert_eq!(&*non_lookup_inputs[1], &[0.0, 0.0]); } #[test] fn collect_one_pmi() { let sent = vec![ Token::new("een"), Token::new("collector"), Token::new("test"), ]; let mut state = ParserState::new(&sent); let pmi_vectorizer = test_pmi_vectorizer(); let mut collector = test_collector(&pmi_vectorizer); collector .collect(&StackProjectiveTransition::Shift, &state) .unwrap(); StackProjectiveTransition::Shift.apply(&mut state); collector .collect(&StackProjectiveTransition::Shift, &state) .unwrap(); StackProjectiveTransition::Shift.apply(&mut state); collector .collect(&StackProjectiveTransition::LeftArc("FOO".into()), &state) .unwrap(); StackProjectiveTransition::LeftArc("FOO".into()).apply(&mut state); collector .collect(&StackProjectiveTransition::Shift, &state) .unwrap(); let (_labels, _lookup_inputs, non_lookup_inputs) = collector.into_data(); // There should be two batches. assert_eq!(non_lookup_inputs.len(), 2); // Check batch shapes. assert_eq!(non_lookup_inputs[0].dims(), &[2, 2]); assert_eq!(non_lookup_inputs[1].dims(), &[2, 2]); // Check batch contents. assert_eq!(&*non_lookup_inputs[0], &[0.0, 0.0, 0.0, 0.0]); assert_eq!(&*non_lookup_inputs[1], &[0.0, 0.0, 1.0, 1.0]); } #[test] fn collect_two_pmis() { let sent = vec![ Token::new("een"), Token::new("collector"), Token::new("test"), ]; let mut state = ParserState::new(&sent); let pmi_vectorizer = test_pmi_vectorizer(); let mut collector = test_collector(&pmi_vectorizer); collector .collect(&StackProjectiveTransition::Shift, &state) .unwrap(); StackProjectiveTransition::Shift.apply(&mut state); collector .collect(&StackProjectiveTransition::Shift, &state) .unwrap(); StackProjectiveTransition::Shift.apply(&mut state); collector .collect(&StackProjectiveTransition::LeftArc("FOO".into()), &state) .unwrap(); StackProjectiveTransition::LeftArc("FOO".into()).apply(&mut state); collector .collect(&StackProjectiveTransition::Shift, &state) .unwrap(); StackProjectiveTransition::Shift.apply(&mut state); collector .collect(&StackProjectiveTransition::LeftArc("BAR".into()), &state) .unwrap(); StackProjectiveTransition::LeftArc("BAR".into()).apply(&mut state); collector .collect(&StackProjectiveTransition::Shift, &state) .unwrap(); let (_labels, _lookup_inputs, non_lookup_inputs) = collector.into_data(); // There should be two batches. assert_eq!(non_lookup_inputs.len(), 3); // Check batch shapes. assert_eq!(non_lookup_inputs[0].dims(), &[2, 2]); assert_eq!(non_lookup_inputs[1].dims(), &[2, 2]); assert_eq!(non_lookup_inputs[2].dims(), &[2, 4]); // Check batch contents. assert_eq!(&*non_lookup_inputs[0], &[0.0, 0.0, 0.0, 0.0]); assert_eq!(&*non_lookup_inputs[1], &[0.0, 0.0, 1.0, 1.0]); assert_eq!( &*non_lookup_inputs[2], &[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0] ); } fn test_vectorizer() -> InputVectorizer { let stack0 = AddressedValue { address: vec![Source::Stack(0)], layer: Layer::Token, }; let buffer0 = AddressedValue { address: vec![Source::Buffer(0)], layer: Layer::Token, }; let mut lookups = LayerLookups::new(); let token_table: Box<Lookup> = Box::new(MutableLookupTable::new()); lookups.insert(features::Layer::Token, token_table); let deprel_table: Box<Lookup> = Box::new(MutableLookupTable::new()); lookups.insert(features::Layer::DepRel, deprel_table); let association_strengths = HashMap::new(); let no_lowercase_tags = vec!["ROOT".to_string(), "NN".to_string(), "NE".to_string()]; InputVectorizer::new( lookups, AddressedValues(vec![stack0, buffer0]), association_strengths, no_lowercase_tags, ) } fn test_pmi_vectorizer() -> InputVectorizer { let stack0 = AddressedValue { address: vec![Source::Stack(0)], layer: Layer::Token, }; let stack1 = AddressedValue { address: vec![Source::Stack(1)], layer: Layer::Token, }; let stack0_ldep0 = AddressedValue { address: vec![Source::Stack(0), Source::LDep(0)], layer: Layer::DepRel, }; let stack1_rdep0 = AddressedValue { address: vec![Source::Stack(1), Source::RDep(0)], layer: Layer::DepRel, }; let mut lookups = LayerLookups::new(); let token_table: Box<Lookup> = Box::new(MutableLookupTable::new()); lookups.insert(features::Layer::Token, token_table); let deprel_table: Box<Lookup> = Box::new(MutableLookupTable::new()); lookups.insert(features::Layer::DepRel, deprel_table); let mut association_strengths = HashMap::new(); association_strengths.insert( ( "collector".to_string(), "ROOT".to_string(), "FOO".to_string(), ), 1.0, ); association_strengths.insert( ( "ROOT".to_string(), "collector".to_string(), "FOO".to_string(), ), 1.0, ); association_strengths.insert( ("ROOT".to_string(), "test".to_string(), "FOO".to_string()), 1.0, ); association_strengths.insert( ("test".to_string(), "ROOT".to_string(), "FOO".to_string()), 1.0, ); association_strengths.insert( ("ROOT".to_string(), "test".to_string(), "BAR".to_string()), 1.0, ); association_strengths.insert( ("test".to_string(), "ROOT".to_string(), "BAR".to_string()), 1.0, ); let no_lowercase_tags = vec!["ROOT".to_string(), "NN".to_string(), "NE".to_string()]; InputVectorizer::new( lookups, AddressedValues(vec![stack0, stack1, stack0_ldep0, stack1_rdep0]), association_strengths, no_lowercase_tags, ) } fn test_collector(vectorizer: &InputVectorizer) -> TensorCollector<StackProjectiveSystem> { TensorCollector::new(StackProjectiveSystem::new(), vectorizer, 2) } }
35.14693
98
0.581643
1452d64918a18f705113f0d951154a4be33d02a9
969
ts
TypeScript
cypress/e2e/subtitles.test.ts
Zweihander-Main/torystories.stream
99f91377a8c1b54081de8e3da465fc832ef521e9
[ "MIT" ]
null
null
null
cypress/e2e/subtitles.test.ts
Zweihander-Main/torystories.stream
99f91377a8c1b54081de8e3da465fc832ef521e9
[ "MIT" ]
null
null
null
cypress/e2e/subtitles.test.ts
Zweihander-Main/torystories.stream
99f91377a8c1b54081de8e3da465fc832ef521e9
[ "MIT" ]
null
null
null
describe('Subtitles ', () => { beforeEach(() => { cy.visitAndSpyStorage('/', 'getItem'); cy.findByTitle(/Episode Info and Subtitles/).click(); }); it('change as player is playing', () => { cy.findByLabelText('Seek and progress slider').as('slider'); cy.findByLabelText('Start playback').as('playbutton'); cy.get('@slider').invoke('val').should('eq', '0'); cy.get('@playbutton').click(); cy.get('@slider').invoke('val', 0.5).trigger('pointerup'); cy.get('@slider', { timeout: 10000 }) .invoke('val') .should((val) => { let valNum; if (typeof val === 'string') { valNum = parseFloat(val); expect(valNum).to.be.gte(0.5); } else { valNum = val; expect(valNum).to.be.gte(0.5); } }); cy.get( '[aria-label="Subtitle Scrolling Text"] > [aria-selected="true"]' ).as('initial-sub'); cy.get('@initial-sub', { timeout: 20000 }).should( 'have.attr', 'aria-selected', 'false' ); }); }); export {};
27.685714
68
0.581011
8e1d611127c69cad451f4a588aea1b23da80689e
64
rb
Ruby
lib/omniauth-boletosimples.rb
BoletoSimples/omniauth-boletosimples
4f5fffce5f43f5d6d6ec7fa7e1f7ac65746a419b
[ "MIT" ]
1
2016-11-21T15:00:44.000Z
2016-11-21T15:00:44.000Z
lib/omniauth-boletosimples.rb
BoletoSimples/omniauth-boletosimples
4f5fffce5f43f5d6d6ec7fa7e1f7ac65746a419b
[ "MIT" ]
2
2020-05-12T18:43:10.000Z
2020-05-12T18:43:10.000Z
lib/omniauth-boletosimples.rb
BoletoSimples/omniauth-boletosimples
4f5fffce5f43f5d6d6ec7fa7e1f7ac65746a419b
[ "MIT" ]
null
null
null
# frozen_string_literal: true require 'omniauth/boletosimples'
16
32
0.828125
ea7ba177d3c95ed5bb8649581a40aedb69ed9717
571
dart
Dart
app_bar/lib/home.dart
JhaNviSadhu/Flutter-1
2b339c9f10b08b3e082a4858695afe0e193c210e
[ "MIT" ]
null
null
null
app_bar/lib/home.dart
JhaNviSadhu/Flutter-1
2b339c9f10b08b3e082a4858695afe0e193c210e
[ "MIT" ]
2
2021-10-04T04:09:33.000Z
2021-10-04T11:45:28.000Z
app_bar/lib/home.dart
JhaNviSadhu/Flutter-1
2b339c9f10b08b3e082a4858695afe0e193c210e
[ "MIT" ]
2
2021-10-01T16:58:06.000Z
2021-10-02T06:33:17.000Z
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class Home extends StatefulWidget { const Home({ Key? key }) : super(key: key); @override _HomeState createState() => _HomeState(); } //Custom app bar class MyBar extends AppBar{ MyBar({Key? key, required Widget title,Color ?color}):super(key: key,title: title,actions: <Widget>[Icon(Icons.home)]); } class _HomeState extends State<Home> { @override Widget build(BuildContext context) { return Scaffold( appBar: MyBar(title: Text('Home'), ), ); } }
23.791667
121
0.681261
dd8d7647e22677ed032fb3c025c293ca28beaed9
17,500
java
Java
src/main/java/mekanism/common/content/network/BoxedChemicalNetwork.java
momo-i/Mekanism
24108d99ed37cebc90e08dd70169b8dc4d820379
[ "MIT" ]
null
null
null
src/main/java/mekanism/common/content/network/BoxedChemicalNetwork.java
momo-i/Mekanism
24108d99ed37cebc90e08dd70169b8dc4d820379
[ "MIT" ]
null
null
null
src/main/java/mekanism/common/content/network/BoxedChemicalNetwork.java
momo-i/Mekanism
24108d99ed37cebc90e08dd70169b8dc4d820379
[ "MIT" ]
1
2022-01-22T15:55:21.000Z
2022-01-22T15:55:21.000Z
package mekanism.common.content.network; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import mekanism.api.Action; import mekanism.api.MekanismAPI; import mekanism.api.chemical.Chemical; import mekanism.api.chemical.ChemicalStack; import mekanism.api.chemical.ChemicalType; import mekanism.api.chemical.IChemicalHandler; import mekanism.api.chemical.IChemicalTank; import mekanism.api.chemical.gas.GasStack; import mekanism.api.chemical.gas.IGasTank; import mekanism.api.chemical.gas.attribute.GasAttributes; import mekanism.api.chemical.infuse.IInfusionTank; import mekanism.api.chemical.merged.BoxedChemical; import mekanism.api.chemical.merged.BoxedChemicalStack; import mekanism.api.chemical.merged.MergedChemicalTank; import mekanism.api.chemical.merged.MergedChemicalTank.Current; import mekanism.api.chemical.pigment.IPigmentTank; import mekanism.api.chemical.slurry.ISlurryTank; import mekanism.api.text.TextComponentUtil; import mekanism.common.Mekanism; import mekanism.common.MekanismLang; import mekanism.common.capabilities.chemical.BoxedChemicalHandler; import mekanism.common.capabilities.chemical.dynamic.IGasTracker; import mekanism.common.capabilities.chemical.dynamic.IInfusionTracker; import mekanism.common.capabilities.chemical.dynamic.IPigmentTracker; import mekanism.common.capabilities.chemical.dynamic.ISlurryTracker; import mekanism.common.capabilities.chemical.variable.VariableCapacityChemicalTankBuilder; import mekanism.common.content.network.distribution.BoxedChemicalTransmitterSaveTarget; import mekanism.common.content.network.distribution.ChemicalHandlerTarget; import mekanism.common.content.network.transmitter.BoxedPressurizedTube; import mekanism.common.lib.transmitter.DynamicBufferedNetwork; import mekanism.common.util.ChemicalUtil; import mekanism.common.util.EmitUtils; import mekanism.common.util.MekanismUtils; import net.minecraft.util.Direction; import net.minecraft.util.text.ITextComponent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.LazyOptional; /** * A DynamicNetwork extension created specifically for the transfer of Chemicals. */ public class BoxedChemicalNetwork extends DynamicBufferedNetwork<BoxedChemicalHandler, BoxedChemicalNetwork, BoxedChemicalStack, BoxedPressurizedTube> implements IGasTracker, IInfusionTracker, IPigmentTracker, ISlurryTracker { public final MergedChemicalTank chemicalTank; private final List<IGasTank> gasTanks; private final List<IInfusionTank> infusionTanks; private final List<IPigmentTank> pigmentTanks; private final List<ISlurryTank> slurryTanks; @Nonnull public BoxedChemical lastChemical = BoxedChemical.EMPTY; private long prevTransferAmount; public BoxedChemicalNetwork(UUID networkID) { super(networkID); chemicalTank = MergedChemicalTank.create( VariableCapacityChemicalTankBuilder.GAS.createAllValid(this::getCapacity, this), VariableCapacityChemicalTankBuilder.INFUSION.createAllValid(this::getCapacity, this), VariableCapacityChemicalTankBuilder.PIGMENT.createAllValid(this::getCapacity, this), VariableCapacityChemicalTankBuilder.SLURRY.createAllValid(this::getCapacity, this) ); gasTanks = Collections.singletonList(chemicalTank.getGasTank()); infusionTanks = Collections.singletonList(chemicalTank.getInfusionTank()); pigmentTanks = Collections.singletonList(chemicalTank.getPigmentTank()); slurryTanks = Collections.singletonList(chemicalTank.getSlurryTank()); } public BoxedChemicalNetwork(Collection<BoxedChemicalNetwork> networks) { this(UUID.randomUUID()); adoptAllAndRegister(networks); } public boolean isTankEmpty() { return chemicalTank.getCurrent() == Current.EMPTY; } public IGasTank getGasTank() { return chemicalTank.getGasTank(); } public IInfusionTank getInfusionTank() { return chemicalTank.getInfusionTank(); } public IPigmentTank getPigmentTank() { return chemicalTank.getPigmentTank(); } public ISlurryTank getSlurryTank() { return chemicalTank.getSlurryTank(); } /** * @implNote Falls back to the gas tank if empty */ private IChemicalTank<?, ?> getCurrentTankWithFallback() { Current current = chemicalTank.getCurrent(); return current == Current.EMPTY ? getGasTank() : chemicalTank.getTankFromCurrent(current); } @Override protected void forceScaleUpdate() { if (!isTankEmpty() && getCapacity() > 0) { currentScale = (float) Math.min(1, getCurrentTankWithFallback().getStored() / (double) getCapacity()); } else { currentScale = 0; } } @Override public List<BoxedPressurizedTube> adoptTransmittersAndAcceptorsFrom(BoxedChemicalNetwork net) { float oldScale = currentScale; long oldCapacity = getCapacity(); List<BoxedPressurizedTube> transmittersToUpdate = super.adoptTransmittersAndAcceptorsFrom(net); //Merge the chemical scales long capacity = getCapacity(); currentScale = Math.min(1, capacity == 0 ? 0 : (currentScale * oldCapacity + net.currentScale * net.capacity) / capacity); if (isRemote()) { if (isTankEmpty()) { adoptBuffer(net); } } else { if (!net.isTankEmpty()) { if (isTankEmpty()) { adoptBuffer(net); } else { Current current = chemicalTank.getCurrent(); Current netCurrent = net.chemicalTank.getCurrent(); if (current == netCurrent) { //If the chemical types match (then compare the chemicals themselves) IChemicalTank<?, ?> tank = chemicalTank.getTankFromCurrent(current); IChemicalTank<?, ?> netTank = net.chemicalTank.getTankFromCurrent(current); if (tank.getType() == netTank.getType()) { long amount = netTank.getStored(); MekanismUtils.logMismatchedStackSize(tank.growStack(amount, Action.EXECUTE), amount); } netTank.setEmpty(); } else { Mekanism.logger.error("Incompatible chemical networks merged: {}, {}.", current, netCurrent); } } } if (oldScale != currentScale) { //We want to make sure we update to the scale change needsUpdate = true; } } return transmittersToUpdate; } private void adoptBuffer(BoxedChemicalNetwork net) { Current netCurrent = net.chemicalTank.getCurrent(); if (netCurrent == Current.GAS) { moveBuffer(getGasTank(), net.getGasTank()); } else if (netCurrent == Current.INFUSION) { moveBuffer(getInfusionTank(), net.getInfusionTank()); } else if (netCurrent == Current.PIGMENT) { moveBuffer(getPigmentTank(), net.getPigmentTank()); } else if (netCurrent == Current.SLURRY) { moveBuffer(getSlurryTank(), net.getSlurryTank()); } } private <CHEMICAL extends Chemical<CHEMICAL>, STACK extends ChemicalStack<CHEMICAL>, TANK extends IChemicalTank<CHEMICAL, STACK>> void moveBuffer(TANK tank, TANK other) { tank.setStack(ChemicalUtil.copy(other.getStack())); other.setEmpty(); } @Nonnull @Override public BoxedChemicalStack getBuffer() { Current current = chemicalTank.getCurrent(); if (current == Current.EMPTY) { return BoxedChemicalStack.EMPTY; } return BoxedChemicalStack.box(chemicalTank.getTankFromCurrent(current).getStack().copy()); } @Override public void absorbBuffer(BoxedPressurizedTube transmitter) { BoxedChemicalStack chemical = transmitter.releaseShare(); if (!chemical.isEmpty()) { Current current = chemicalTank.getCurrent(); ChemicalStack<?> chemicalStack = chemical.getChemicalStack(); if (current == Current.EMPTY) { setStack(chemicalStack.copy(), chemicalTank.getTankForType(chemical.getChemicalType())); } else if (ChemicalUtil.compareTypes(chemical.getChemicalType(), current)) { IChemicalTank<?, ?> tank = chemicalTank.getTankFromCurrent(current); if (chemicalStack.getType() == tank.getType()) { long amount = chemicalStack.getAmount(); MekanismUtils.logMismatchedStackSize(tank.growStack(amount, Action.EXECUTE), amount); } } } } @Override public void clampBuffer() { Current current = chemicalTank.getCurrent(); if (current != Current.EMPTY) { long capacity = getCapacity(); IChemicalTank<?, ?> tank = chemicalTank.getTankFromCurrent(current); if (tank.getStored() > capacity) { MekanismUtils.logMismatchedStackSize(tank.setStackSize(capacity, Action.EXECUTE), capacity); } } } @Override protected void updateSaveShares(@Nullable BoxedPressurizedTube triggerTransmitter) { super.updateSaveShares(triggerTransmitter); if (!isEmpty()) { updateSaveShares(triggerTransmitter, getCurrentTankWithFallback().getStack()); } } private <CHEMICAL extends Chemical<CHEMICAL>, STACK extends ChemicalStack<CHEMICAL>> void updateSaveShares(@Nullable BoxedPressurizedTube triggerTransmitter, STACK chemical) { STACK empty = ChemicalUtil.getEmptyStack(chemical); BoxedChemicalTransmitterSaveTarget<CHEMICAL, STACK> saveTarget = new BoxedChemicalTransmitterSaveTarget<>(empty, chemical, transmitters); long sent = EmitUtils.sendToAcceptors(saveTarget, chemical.getAmount(), chemical); if (triggerTransmitter != null && sent < chemical.getAmount()) { disperse(triggerTransmitter, ChemicalUtil.copyWithAmount(chemical, chemical.getAmount() - sent)); } saveTarget.saveShare(); } @Override protected void onLastTransmitterRemoved(@Nonnull BoxedPressurizedTube triggerTransmitter) { Current current = chemicalTank.getCurrent(); if (current != Current.EMPTY) { disperse(triggerTransmitter, chemicalTank.getTankFromCurrent(current).getStack()); } } protected <CHEMICAL extends Chemical<CHEMICAL>, STACK extends ChemicalStack<CHEMICAL>> void disperse(@Nonnull BoxedPressurizedTube triggerTransmitter, STACK chemical) { if (chemical instanceof GasStack && chemical.has(GasAttributes.Radiation.class)) { // Handle radiation leakage MekanismAPI.getRadiationManager().dumpRadiation(triggerTransmitter.getTileCoord(), (GasStack) chemical); } } private <CHEMICAL extends Chemical<CHEMICAL>, STACK extends ChemicalStack<CHEMICAL>> long tickEmit(@Nonnull STACK stack) { ChemicalType chemicalType = ChemicalType.getTypeFor(stack); Collection<Map<Direction, LazyOptional<BoxedChemicalHandler>>> acceptorValues = acceptorCache.getAcceptorValues(); ChemicalHandlerTarget<CHEMICAL, STACK, IChemicalHandler<CHEMICAL, STACK>> target = new ChemicalHandlerTarget<>(stack, acceptorValues.size() * 2); for (Map<Direction, LazyOptional<BoxedChemicalHandler>> acceptors : acceptorValues) { for (LazyOptional<BoxedChemicalHandler> lazyAcceptor : acceptors.values()) { lazyAcceptor.ifPresent(acceptor -> { IChemicalHandler<CHEMICAL, STACK> handler = acceptor.getHandlerFor(chemicalType); if (handler != null && ChemicalUtil.canInsert(handler, stack)) { target.addHandler(handler); } }); } } return EmitUtils.sendToAcceptors(target, stack.getAmount(), stack); } @Override public void onUpdate() { super.onUpdate(); if (needsUpdate) { MinecraftForge.EVENT_BUS.post(new ChemicalTransferEvent(this, lastChemical)); needsUpdate = false; } Current current = chemicalTank.getCurrent(); if (current == Current.EMPTY) { prevTransferAmount = 0; } else { IChemicalTank<?, ?> tank = chemicalTank.getTankFromCurrent(current); prevTransferAmount = tickEmit(tank.getStack()); MekanismUtils.logMismatchedStackSize(tank.shrinkStack(prevTransferAmount, Action.EXECUTE), prevTransferAmount); } } @Override protected float computeContentScale() { float scale = (float) (getCurrentTankWithFallback().getStored() / (double) getCapacity()); float ret = Math.max(currentScale, scale); if (prevTransferAmount > 0 && ret < 1) { ret = Math.min(1, ret + 0.02F); } else if (prevTransferAmount <= 0 && ret > 0) { ret = Math.max(scale, ret - 0.02F); } return ret; } public long getPrevTransferAmount() { return prevTransferAmount; } @Override public ITextComponent getNeededInfo() { return TextComponentUtil.build(getCurrentTankWithFallback().getNeeded()); } @Override public ITextComponent getStoredInfo() { if (isTankEmpty()) { return MekanismLang.NONE.translate(); } IChemicalTank<?, ?> tank = getCurrentTankWithFallback(); return MekanismLang.NETWORK_MB_STORED.translate(tank.getStack(), tank.getStored()); } @Override public ITextComponent getFlowInfo() { return MekanismLang.NETWORK_MB_PER_TICK.translate(prevTransferAmount); } @Override public boolean isCompatibleWith(BoxedChemicalNetwork other) { if (super.isCompatibleWith(other)) { Current current = chemicalTank.getCurrent(); if (current == Current.EMPTY) { return true; } Current otherCurrent = other.chemicalTank.getCurrent(); return otherCurrent == Current.EMPTY || current == otherCurrent && chemicalTank.getTankFromCurrent(current).getType() == other.chemicalTank.getTankFromCurrent(otherCurrent).getType(); } return false; } @Override public ITextComponent getTextComponent() { return MekanismLang.NETWORK_DESCRIPTION.translate(MekanismLang.CHEMICAL_NETWORK, transmittersSize(), getAcceptorCount()); } @Override public String toString() { return "[ChemicalNetwork] " + transmittersSize() + " transmitters, " + getAcceptorCount() + " acceptors."; } @Override public void onContentsChanged() { markDirty(); Current current = chemicalTank.getCurrent(); BoxedChemical type = current == Current.EMPTY ? BoxedChemical.EMPTY : BoxedChemical.box(chemicalTank.getTankFromCurrent(current).getType()); if (!lastChemical.equals(type)) { //If the chemical type does not match update it, and mark that we need an update if (!type.isEmpty()) { lastChemical = type; } needsUpdate = true; } } public void setLastChemical(@Nonnull BoxedChemical chemical) { if (chemical.isEmpty()) { Current current = chemicalTank.getCurrent(); if (current != Current.EMPTY) { chemicalTank.getTankFromCurrent(current).setEmpty(); } } else { lastChemical = chemical; setStackClearOthers(lastChemical.getChemical().getStack(1), chemicalTank.getTankForType(lastChemical.getChemicalType())); } } @Nonnull @Override public List<IGasTank> getGasTanks(@Nullable Direction side) { return gasTanks; } @Nonnull @Override public List<IInfusionTank> getInfusionTanks(@Nullable Direction side) { return infusionTanks; } @Nonnull @Override public List<IPigmentTank> getPigmentTanks(@Nullable Direction side) { return pigmentTanks; } @Nonnull @Override public List<ISlurryTank> getSlurryTanks(@Nullable Direction side) { return slurryTanks; } private <CHEMICAL extends Chemical<CHEMICAL>, STACK extends ChemicalStack<CHEMICAL>> void setStack(STACK stack, IChemicalTank<?, ?> tank) { ((IChemicalTank<CHEMICAL, STACK>) tank).setStack(stack); } private void setStackClearOthers(ChemicalStack<?> stack, IChemicalTank<?, ?> tank) { setStack(stack, tank); for (IChemicalTank<?, ?> tankToClear : chemicalTank.getAllTanks()) { if (tank != tankToClear) { tankToClear.setEmpty(); } } } public static class ChemicalTransferEvent extends TransferEvent<BoxedChemicalNetwork> { public final BoxedChemical transferType; public ChemicalTransferEvent(BoxedChemicalNetwork network, BoxedChemical type) { super(network); transferType = type; } } }
41.966427
174
0.6668
128e7f60ca20bbd7cfb7e179eee16b515c60362e
496
swift
Swift
Sources/Apollo/HTTPURLResponse+Helpers.swift
mishagray/apollo-ios
bd2c507b763bf7dd2423c236781a41b473e99ceb
[ "MIT" ]
4
2020-10-20T12:47:15.000Z
2021-08-24T15:58:10.000Z
Sources/Apollo/HTTPURLResponse+Helpers.swift
mishagray/apollo-ios
bd2c507b763bf7dd2423c236781a41b473e99ceb
[ "MIT" ]
2
2021-05-11T06:29:48.000Z
2022-01-22T11:00:55.000Z
Sources/Apollo/HTTPURLResponse+Helpers.swift
mishagray/apollo-ios
bd2c507b763bf7dd2423c236781a41b473e99ceb
[ "MIT" ]
3
2020-09-08T07:05:34.000Z
2021-08-10T18:27:50.000Z
import Foundation extension HTTPURLResponse { var isSuccessful: Bool { return (200..<300).contains(statusCode) } var statusCodeDescription: String { return HTTPURLResponse.localizedString(forStatusCode: statusCode) } var textEncoding: String.Encoding? { guard let encodingName = textEncodingName else { return nil } return String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString))) } }
27.555556
147
0.780242
4a100691b26626efa52a5a7f7d8982d1ad0055ac
427
kt
Kotlin
modules/common_feature_toggles/src/main/java/kekmech/ru/common_feature_toggles/di/CommonFeatureTogglesModule.kt
tonykolomeytsev/mpeiapp
28cd15c2cc23b91f88d5bae9f7e16907f9ec0365
[ "MIT" ]
14
2019-08-24T21:41:34.000Z
2022-01-17T08:54:23.000Z
modules/common_feature_toggles/src/main/java/kekmech/ru/common_feature_toggles/di/CommonFeatureTogglesModule.kt
tonykolomeytsev/mpeiapp
28cd15c2cc23b91f88d5bae9f7e16907f9ec0365
[ "MIT" ]
125
2019-09-29T21:51:42.000Z
2021-09-25T13:46:36.000Z
modules/common_feature_toggles/src/main/java/kekmech/ru/common_feature_toggles/di/CommonFeatureTogglesModule.kt
tonykolomeytsev/mpeiapp
28cd15c2cc23b91f88d5bae9f7e16907f9ec0365
[ "MIT" ]
8
2019-10-10T17:47:32.000Z
2021-09-16T19:34:40.000Z
package kekmech.ru.common_feature_toggles.di import kekmech.ru.common_di.ModuleProvider import kekmech.ru.common_feature_toggles.FeatureToggles import kekmech.ru.common_feature_toggles.FeatureTogglesImpl import org.koin.core.qualifier.named import org.koin.dsl.bind object CommonFeatureTogglesModule : ModuleProvider({ single { FeatureTogglesImpl(get(named("firebaseRemoteConfigWrapper"))) } bind FeatureToggles::class })
38.818182
103
0.850117
02aea3a9f2104d5b36ad58263d19937bd6aea589
3,234
cc
C++
vos/MotifApp/YesNoDialog.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
16
2020-10-21T05:56:26.000Z
2022-03-31T10:02:01.000Z
vos/MotifApp/YesNoDialog.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
null
null
null
vos/MotifApp/YesNoDialog.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
2
2021-03-09T01:51:08.000Z
2021-03-23T00:23:24.000Z
/////////////////////////////////////////////////////////////// // YesNoDialog.h: Motif Question dialog that also contains No // button. Note that this dialog is not cached, it is created // at every request and destroys itself when user presses any of // the buttons. //////////////////////////////////////////////////////////////// #include "YesNoDialog.h" #include "Cmd.h" #include "Application.h" #include <Xm/MessageB.h> #include <Xm/PushB.h> #include <stdio.h> String YesNoDialog::_defaults[] = { (char *)"*okLabelString: Yes", (char *)"*no.labelString: No", NULL, }; #define DEFAULTQUESTION "Do you want to save changes?" YesNoDialog::YesNoDialog (const char *name, void *clientData, const char *question, DialogCallback yes, DialogCallback no, DialogCallback cancel, DialogCallback help) : UIComponent (name) { _clientData = clientData; _yes = yes; _no = no; _cancel = cancel; _help = help; if (question && strlen(question)) _question = strdup(question); else _question = strdup(DEFAULTQUESTION); XmString msgStr = XmStringCreateLocalized (_question); Arg args[5]; int n = 0; XtSetArg (args[n], XmNautoUnmanage, False); n++; XtSetArg (args[n], XmNmessageString, msgStr); n++; setDefaultResources ( theApplication->baseWidget(), _defaults ); Widget dialog = XmCreateQuestionDialog (theApplication->baseWidget(), _name, args, n); XtVaSetValues (dialog, XmNdialogStyle, XmDIALOG_FULL_APPLICATION_MODAL, NULL); if (help == NULL) XtUnmanageChild (XmMessageBoxGetChild (dialog, XmDIALOG_HELP_BUTTON)); _w = XtParent (dialog); installDestroyHandler(); XtAddCallback (dialog, XmNokCallback, YesNoDialog::yesCallback, (XtPointer) this); XtAddCallback (dialog, XmNcancelCallback, YesNoDialog::cancelCallback, (XtPointer) this); XmStringFree (msgStr); Widget noButton = XtVaCreateManagedWidget ("no", xmPushButtonWidgetClass, dialog, NULL); XtAddCallback (noButton, XmNactivateCallback, YesNoDialog::noCallback, (XtPointer) this); XtManageChild(dialog); manage(); } YesNoDialog::~YesNoDialog() { XtPopdown (_w); } void YesNoDialog::manage() { UIComponent::manage(); XtPopup (_w, XtGrabNone); } void YesNoDialog::yesCallback (Widget, XtPointer clientData, XtPointer) { YesNoDialog *obj = (YesNoDialog *) clientData; // Call the base class execute() member function // to do all the usual processing of the command obj->yes(); delete obj; } void YesNoDialog::yes() { (*_yes)(_clientData); } void YesNoDialog::noCallback (Widget, XtPointer clientData, XtPointer) { YesNoDialog *obj = (YesNoDialog *) clientData; obj->no(); delete obj; } void YesNoDialog::no() { (*_no)(_clientData); } void YesNoDialog::cancelCallback (Widget, XtPointer clientData, XtPointer) { YesNoDialog *obj = (YesNoDialog *) clientData; delete obj; } void YesNoDialog::helpCallback (Widget, XtPointer clientData, XtPointer) { YesNoDialog *obj = (YesNoDialog *) clientData; obj->help(); } void YesNoDialog::help() { (*_help)(_clientData); }
22.774648
74
0.648423
e7154f693224dcb7d5856df566cb69fc686c5663
106
php
PHP
frontend/views/site/_category.php
dimabdc/SimpleCatalog
417c64a4565100ed4e0be87d2b2c63a21e77348c
[ "BSD-3-Clause" ]
null
null
null
frontend/views/site/_category.php
dimabdc/SimpleCatalog
417c64a4565100ed4e0be87d2b2c63a21e77348c
[ "BSD-3-Clause" ]
null
null
null
frontend/views/site/_category.php
dimabdc/SimpleCatalog
417c64a4565100ed4e0be87d2b2c63a21e77348c
[ "BSD-3-Clause" ]
null
null
null
<?php use yii\helpers\Html; use yii\helpers\HtmlPurifier; ?> <?= Html::a($model->title, [$model->id]) ?>
15.142857
43
0.632075
6d29c0f83cf871276959f314d65bf6441dc43614
1,094
ts
TypeScript
src/app/helpers/auth.guard.ts
alikazmi2000/aman-backoffice
1b452425b31dc1cb02d2443edab98c913638c0e4
[ "MIT" ]
null
null
null
src/app/helpers/auth.guard.ts
alikazmi2000/aman-backoffice
1b452425b31dc1cb02d2443edab98c913638c0e4
[ "MIT" ]
null
null
null
src/app/helpers/auth.guard.ts
alikazmi2000/aman-backoffice
1b452425b31dc1cb02d2443edab98c913638c0e4
[ "MIT" ]
null
null
null
// Angular import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router'; // RxJS import {Observable, of} from 'rxjs'; import {catchError, map} from 'rxjs/operators'; // NGRX import {Store} from '@ngrx/store'; // Auth reducers and selectors import {AppState} from '../store/app.states'; import {AuthService} from '../services/auth.service'; import {isSuccessResponse} from './helpers'; @Injectable() export class AuthGuard implements CanActivate { constructor(private store: Store<AppState>, private router: Router, private authservice: AuthService) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { return this.authservice.validateToken().pipe( map((data) => { if (isSuccessResponse(data)) { return true; } else { this.router.navigateByUrl('/login'); return false; } }), catchError(() => { this.router.navigateByUrl('/login'); return of(false); }), ); } }
30.388889
105
0.666362
9afe89b0bcd96642f21e80e15ece0207747e7790
1,294
py
Python
src/systemmanager.py
WinterLicht/Chaos-Projectile
3fffb788b241b7baa4247c1e630d83a7210ddc2e
[ "CC-BY-4.0" ]
59
2015-03-25T21:29:06.000Z
2022-01-17T22:48:05.000Z
src/systemmanager.py
WinterLicht/Chaos-Projectile
3fffb788b241b7baa4247c1e630d83a7210ddc2e
[ "CC-BY-4.0" ]
11
2015-07-07T07:10:42.000Z
2021-11-21T12:47:42.000Z
src/systemmanager.py
WinterLicht/Chaos-Projectile
3fffb788b241b7baa4247c1e630d83a7210ddc2e
[ "CC-BY-4.0" ]
19
2015-07-13T06:44:44.000Z
2022-02-05T03:09:27.000Z
""" .. module:: systemmanager :Platform: Unix, Windows :Synopsis: system manager contains all game systems. """ import rendersystem import collisionsystem import inputsystem import animationsystem import combatsystem import statesystem import soundsystem class SystemManager(object): """System manager is a container of all game systems. :Attributes: - *systems* (systems list): all systems are stored here """ def __init__(self, event_manager, gameWorld): """ :param event_manager: event manager :type event_manager: events.EventManager :param gameWorld: game world :type gameWorld: gameWorld.GameWorld """ self.systems = list() self.systems.append(collisionsystem.CollisionSystem(event_manager, gameWorld)) self.systems.append(animationsystem.AnimationSystem(event_manager, gameWorld)) self.systems.append(inputsystem.InputSystem(event_manager, gameWorld)) self.systems.append(statesystem.StateSystem(event_manager, gameWorld)) self.systems.append(rendersystem.RenderSystem(event_manager, gameWorld)) self.systems.append(combatsystem.CombatSystem(event_manager, gameWorld)) #self.systems.append(soundsystem.SoundSystem(event_manager, gameWorld))
34.972973
86
0.729521
80983bf5ad90ede47353ee8ab54272c709e752e0
613
sh
Shell
entrypoint.sh
AshbyHeadHunter/TechChallengeApp
154f04524f2493b1495ba88dee6fd60a762f8461
[ "MIT" ]
null
null
null
entrypoint.sh
AshbyHeadHunter/TechChallengeApp
154f04524f2493b1495ba88dee6fd60a762f8461
[ "MIT" ]
null
null
null
entrypoint.sh
AshbyHeadHunter/TechChallengeApp
154f04524f2493b1495ba88dee6fd60a762f8461
[ "MIT" ]
null
null
null
#!/bin/sh if [ ! -z "${DBHOST}" ]; then sed -i -e "s/^\"DbHost\".*/\"DbHost\" = \"${DBHOST}\"/" conf.toml fi if [ ! -z "${DBPORT}" ]; then sed -i -e "s/^\"DbPort\".*/\"DbPort\" = \"${DBPORT}\"/" conf.toml fi if [ ! -z "${DBNAME}" ]; then sed -i -e "s/^\"DbName\".*/\"DbName\" = \"${DBNAME}\"/" conf.toml fi if [ ! -z "${DBPASSWORD}" ]; then sed -i -e "s/^\"DbPassword\".*/\"DbPassword\" = \"${DBPASSWORD}\"/" conf.toml fi if [ ! -z "${DBUSER}" ]; then sed -i -e "s/^\"DbUser\".*/\"DbUser\" = \"${DBUSER}\"/" conf.toml fi cat config.toml nc ${DBHOST} 5432 -vz exec ./TechChallengeApp $@
22.703704
81
0.49429
7f8b753631a30383e12263b8e38ea56b3647d2d0
659
php
PHP
resources/views/nav.blade.php
evulpo/laravel-translation
8ab1b6e0645d262722bda8eb2cc7349f24294028
[ "MIT" ]
null
null
null
resources/views/nav.blade.php
evulpo/laravel-translation
8ab1b6e0645d262722bda8eb2cc7349f24294028
[ "MIT" ]
null
null
null
resources/views/nav.blade.php
evulpo/laravel-translation
8ab1b6e0645d262722bda8eb2cc7349f24294028
[ "MIT" ]
null
null
null
<nav class="header"> <h1 class="text-lg px-6">{{ config('app.name') }}</h1> <ul class="flex-grow justify-end pr-2"> <li> <a href="{{ route('languages.index') }}" class="{{ set_active('') }}{{ set_active('/create') }}"> @include('translation::icons.globe') {{__('Languages')}} </a> </li> <li> <a href="{{ route('languages.translations.index', config('app.locale')) }}" class="{{ set_active('*/translations') }}"> @include('translation::icons.translate') {{ __('Translation') }} </a> </li> </ul> </nav>
32.95
131
0.462822
e352a9b1eaa70d12e6854e50a38b211c6a436bf5
318
rb
Ruby
db/migrate/20160530020252_create_transactions.rb
fabrinal/resto-backend
243a25a1d05c367fa9db90f39bd7637b6b90f865
[ "MIT" ]
null
null
null
db/migrate/20160530020252_create_transactions.rb
fabrinal/resto-backend
243a25a1d05c367fa9db90f39bd7637b6b90f865
[ "MIT" ]
null
null
null
db/migrate/20160530020252_create_transactions.rb
fabrinal/resto-backend
243a25a1d05c367fa9db90f39bd7637b6b90f865
[ "MIT" ]
null
null
null
class CreateTransactions < ActiveRecord::Migration def change create_table :transactions do |t| t.references :order, index: true, foreign_key: true t.decimal :paid_amount t.decimal :discount t.string :validation_id t.string :status t.timestamps null: false end end end
22.714286
57
0.68239
459fbfe0a987188f21d91369d2cabc02520fbd75
3,919
go
Go
maybe_pb.go
powerman/conv
2d5686f496fccad0dd365a4c8c88d2cd9f76294f
[ "MIT" ]
null
null
null
maybe_pb.go
powerman/conv
2d5686f496fccad0dd365a4c8c88d2cd9f76294f
[ "MIT" ]
21
2021-03-29T08:53:43.000Z
2022-03-30T22:09:23.000Z
maybe_pb.go
powerman/conv
2d5686f496fccad0dd365a4c8c88d2cd9f76294f
[ "MIT" ]
null
null
null
package conv import ( "time" "github.com/shopspring/decimal" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" ) // MaybeBool converts from protobuf WKT. func MaybeBool(wkt *wrapperspb.BoolValue) *bool { if wkt == nil { return nil } return &wkt.Value } // MaybePbBool converts to protobuf WKT. func MaybePbBool(v *bool) *wrapperspb.BoolValue { if v == nil { return nil } return wrapperspb.Bool(*v) } // MaybeFloat32 converts from protobuf WKT. func MaybeFloat32(wkt *wrapperspb.FloatValue) *float32 { if wkt == nil { return nil } return &wkt.Value } // MaybePbFloat converts to protobuf WKT. func MaybePbFloat(v *float32) *wrapperspb.FloatValue { if v == nil { return nil } return wrapperspb.Float(*v) } // MaybeFloat64 converts from protobuf WKT. func MaybeFloat64(wkt *wrapperspb.DoubleValue) *float64 { if wkt == nil { return nil } return &wkt.Value } // MaybePbDouble converts to protobuf WKT. func MaybePbDouble(v *float64) *wrapperspb.DoubleValue { if v == nil { return nil } return wrapperspb.Double(*v) } // MaybeInt32 converts from protobuf WKT. func MaybeInt32(wkt *wrapperspb.Int32Value) *int32 { if wkt == nil { return nil } return &wkt.Value } // MaybePbInt32 converts to protobuf WKT. func MaybePbInt32(v *int32) *wrapperspb.Int32Value { if v == nil { return nil } return wrapperspb.Int32(*v) } // MaybeInt64 converts from protobuf WKT. func MaybeInt64(wkt *wrapperspb.Int64Value) *int64 { if wkt == nil { return nil } return &wkt.Value } // MaybePbInt64 converts to protobuf WKT. func MaybePbInt64(v *int64) *wrapperspb.Int64Value { if v == nil { return nil } return wrapperspb.Int64(*v) } // MaybeString converts from protobuf WKT. func MaybeString(wkt *wrapperspb.StringValue) *string { if wkt == nil { return nil } return &wkt.Value } // MaybePbString converts to protobuf WKT. func MaybePbString(v *string) *wrapperspb.StringValue { if v == nil { return nil } return wrapperspb.String(*v) } // MaybeUInt32 converts from protobuf WKT. func MaybeUInt32(wkt *wrapperspb.UInt32Value) *uint32 { if wkt == nil { return nil } return &wkt.Value } // MaybePbUInt32 converts to protobuf WKT. func MaybePbUInt32(v *uint32) *wrapperspb.UInt32Value { if v == nil { return nil } return wrapperspb.UInt32(*v) } // MaybeUInt64 converts from protobuf WKT. func MaybeUInt64(wkt *wrapperspb.UInt64Value) *uint64 { if wkt == nil { return nil } return &wkt.Value } // MaybePbUInt64 converts to protobuf WKT. func MaybePbUInt64(v *uint64) *wrapperspb.UInt64Value { if v == nil { return nil } return wrapperspb.UInt64(*v) } // MaybeDuration converts from protobuf WKT. func MaybeDuration(wkt *durationpb.Duration) *time.Duration { if wkt == nil { return nil } v := wkt.AsDuration() return &v } // MaybePbDuration converts to protobuf WKT. func MaybePbDuration(v *time.Duration) *durationpb.Duration { if v == nil { return nil } return durationpb.New(*v) } // MaybeTime converts from protobuf WKT, returns zero time for nil. func MaybeTime(wkt *timestamppb.Timestamp) time.Time { if wkt == nil { return time.Time{} } return wkt.AsTime() } // MaybePbTimestamp converts to protobuf WKT, returns nil for zero time. func MaybePbTimestamp(v time.Time) *timestamppb.Timestamp { if v.IsZero() { return nil } return timestamppb.New(v) } // MaybeDecimal converts from protobuf WKT. func MaybeDecimal(wkt *wrapperspb.StringValue) (*decimal.Decimal, error) { if wkt == nil { return nil, nil } d, err := decimal.NewFromString(wkt.Value) if err != nil { return nil, err } return &d, nil } // MaybePbStringFromDecimal converts to protobuf WKT. func MaybePbStringFromDecimal(d *decimal.Decimal) *wrapperspb.StringValue { if d == nil { return nil } return wrapperspb.String(d.String()) }
20.411458
75
0.71804
ff3227026d0c64407542b104191740d81c3cfd30
1,998
py
Python
stt_api/__init__.py
medabalimi/stt_en_us
9a0796552ff63afb39add53f5cd8ec2cd2d1b06d
[ "Apache-2.0" ]
null
null
null
stt_api/__init__.py
medabalimi/stt_en_us
9a0796552ff63afb39add53f5cd8ec2cd2d1b06d
[ "Apache-2.0" ]
null
null
null
stt_api/__init__.py
medabalimi/stt_en_us
9a0796552ff63afb39add53f5cd8ec2cd2d1b06d
[ "Apache-2.0" ]
null
null
null
""" # 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 # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED # WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, # MERCHANTABLITY OR NON-INFRINGEMENT. # See the Apache 2 License for the specific language governing permissions and # limitations under the License. """ from flask import Flask from flask_ipban import IpBan from stt_api.celerifier import make_celery import requests import os from flasgger import Swagger app = Flask(__name__) swagger = Swagger(app) app.config.from_object('config') app_path='/'.join(app.root_path.split('/')[:-1]) app.config['MOUNT_POINT'] = f"{app_path}/mount" app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True app.config['UPLOAD_FOLDER'] = f"{app.config['MOUNT_POINT']}/{app.config['RELATIVE_UPLOAD_FOLDER']}" app.config['REDACTED_FOLDER'] = f"{app.config['MOUNT_POINT']}/{app.config['RELATIVE_REDACTED_FOLDER']}" app.config['DB_FOLDER'] = f"{app.config['MOUNT_POINT']}/database" app.config['ASR_MODEL_FOLDER'] = f"{app_path}/models/asr" app.config['TMP_FOLDER'] = f"{app.config['MOUNT_POINT']}/tmp" app.config['TASK_LOG_FILE'] = f"{app.config['DB_FOLDER']}/task_list.txt" dir_list = ['UPLOAD_FOLDER', 'REDACTED_FOLDER', 'DB_FOLDER', 'ASR_MODEL_FOLDER', 'TMP_FOLDER'] app.config['JSON_AS_ASCII'] = False for d in dir_list: if not os.path.isdir(app.config[d]): os.makedirs(app.config[d], exist_ok=True) if not os.path.isdir(app.config['REDACTED_FOLDER']): os.makedirs(app.config['REDACTED_FOLDER'], exist_ok=True) app.config['IP_BAN_LIST_COUNT'] = 6 app.config['IP_BAN_LIST_SECONDS'] = 3600 ip_ban = IpBan(app) ip_ban.load_nuisances() celery_tasks = make_celery(app) import stt_api.routes
29.820896
103
0.746747
c678e10feedbccce944c147fb062aaa2aae8259d
5,328
py
Python
AppSettings.py
FrUh/userpass-manager
340a57786169333cff0687d1568729e7acf2275c
[ "MIT" ]
1
2016-03-18T09:59:22.000Z
2016-03-18T09:59:22.000Z
AppSettings.py
FrUh/userpass-manager
340a57786169333cff0687d1568729e7acf2275c
[ "MIT" ]
2
2015-10-11T22:12:58.000Z
2015-10-17T19:33:20.000Z
AppSettings.py
FrUh/userpass-manager
340a57786169333cff0687d1568729e7acf2275c
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- """ MIT License Copyright (c) 2013-2016 Frantisek Uhrecky 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 os import logging from PyQt4 import QtCore import sys # file ssytem encoding FILE_SYS_ENCODING = sys.getfilesystemencoding() def getAbsAppRoot(): """ Return absolute root dir. """ global FILE_SYS_ENCODING if (not FILE_SYS_ENCODING): FILE_SYS_ENCODING = "utf-8" root_dir = os.path.dirname((str(sys.argv[0]).decode(FILE_SYS_ENCODING)).encode("utf-8")) if (len(root_dir) > 0): # if is not empty add dir separator at the end root_dir = root_dir + os.sep return str(root_dir) # application relative path path APP_ABS_ROOT = getAbsAppRoot() # tmp directory TMP_PATH = APP_ABS_ROOT + "tmp" + os.sep # App version APP_VERSION = "v0.0.7-dev" # App version APP_DB_VERSION = 1 # language LANG = "en" # when inserted worng password, sleep for seconds WRONG_PASWD_SLEEP = 3 # clipboard 'live' in miliseconds CLIPBOARD_LIVE_MSEC = 60000 # default user name for passwords user USER_NAME = "user" # default data path DATA_PATH = APP_ABS_ROOT + "data" + os.path.sep # default settings file name SETTINGS_FILE_NAME = "settings.ini" # settings file apth SETTINGS_FILE_PATH = DATA_PATH + SETTINGS_FILE_NAME # default DB path DB_PATH = APP_ABS_ROOT + "db" + os.path.sep # default DB file name DB_FILE_NAME = "userpass.db" # default DB DEFAULT_DB = "db" + os.path.sep + DB_FILE_NAME # icons path ICONS_PATH = APP_ABS_ROOT + "icons" + os.sep # translations path TRANS_PATH = APP_ABS_ROOT + "translation" + os.sep # translation suffix TRANS_SUFFIX = ".txt" # backup path BACKUP_PATH = APP_ABS_ROOT + "backup" + os.sep # app icon path APP_ICON_PATH = ICONS_PATH + "userpass.ico" """ Settings keys. """ # database file path key SET_KEY_DB = "database/file_path" # language key SET_KEY_LANG = "general/language" def writeSettings(): """ """ pass def readDbFilePath(): """ Read DB file name and path from settings file. @return: DB file path """ # open settings settings = QtCore.QSettings(QtCore.QString.fromUtf8(SETTINGS_FILE_PATH), QtCore.QSettings.IniFormat) data = str(settings.value(SET_KEY_DB, DEFAULT_DB).toString().toUtf8()) logging.debug("reading setting file: '%s', key: '%s', data: '%s'", SETTINGS_FILE_PATH, SET_KEY_DB, data) # read DB file path return data def writeDbFilePath(db_path): """ Write DB file name and path to settings file. Write just relative path from App root dir. @param db_path: DB file path """ logging.debug("current working dir: '%s'", APP_ABS_ROOT) logging.debug("writing setting file: '%s', key: '%s', data: '%s'", SETTINGS_FILE_PATH, SET_KEY_DB, db_path) # open settings settings = QtCore.QSettings(QtCore.QString.fromUtf8(SETTINGS_FILE_PATH), QtCore.QSettings.IniFormat) settings.setValue(SET_KEY_DB, QtCore.QString.fromUtf8(db_path)) def readLanguage(): """ Read default language @return: language """ # open settings settings = QtCore.QSettings(QtCore.QString.fromUtf8(SETTINGS_FILE_PATH), QtCore.QSettings.IniFormat) data = str(settings.value(SET_KEY_LANG, LANG).toString().toUtf8()) logging.debug("reading setting file: '%s', key: '%s', data: '%s'", SETTINGS_FILE_PATH, SET_KEY_LANG, data) # read DB file path return data def writeLanguage(lang): """ Write language. @param lang: language mark """ logging.debug("writing setting file: '%s', key: '%s', data: '%s'", SETTINGS_FILE_PATH, SET_KEY_LANG, lang) # open settings settings = QtCore.QSettings(QtCore.QString.fromUtf8(SETTINGS_FILE_PATH), QtCore.QSettings.IniFormat) settings.setValue(SET_KEY_LANG, QtCore.QString.fromUtf8(lang)) def decodePath(path): """ Decode path from utf-8 to system encoding. @param path: path in utf-8 encoding @return: encoded path in system encoding """ out = str(path).decode("utf-8").encode(FILE_SYS_ENCODING) logging.info("in: '%s', out: '%s'", path, out) return out
28.340426
111
0.685435
b04c6141fedbb533cdbc6268cd510cb01618834d
6,537
py
Python
Minion/Collectors/ipmitoolParser.py
onderogluserdar/boardInstrumentFramework
00f4dc5f3e6993ce372ee12067da43720d1ae175
[ "Apache-2.0" ]
16
2018-02-19T11:07:33.000Z
2022-01-02T10:32:00.000Z
Minion/Collectors/ipmitoolParser.py
mosfa/Board-Instrumentation-Framework
5689bde340f0d28cceef6474f795267df724b5fe
[ "Apache-2.0" ]
11
2018-04-10T23:38:15.000Z
2021-02-17T17:38:05.000Z
Minion/Collectors/ipmitoolParser.py
mosfa/Board-Instrumentation-Framework
5689bde340f0d28cceef6474f795267df724b5fe
[ "Apache-2.0" ]
11
2017-12-31T06:22:47.000Z
2021-11-12T21:08:41.000Z
############################################################################## # Copyright (c) 2016 Intel Corporation # # 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. ############################################################################## # File Abstract: # Takes a file that is the output of ipmitool and gets a specific item, or # create a new file for the DynamicCollector to use with the other function: GenerateFile # ############################################################################## import os import subprocess import time import traceback #Makes path (if passed) os independent def convertPath(path): separator = os.path.sep if separator == '/': path = path.replace('\\',os.path.sep) elif separator == '\\': path = path.replace('/',os.path.sep) return path #gets a specific item from the file, such as rx_packets, or Advertised link #modes def GetItem(inpfile,item,instance): Filename = convertPath(inpfile) file = open(Filename,'rt') if None == file: return "File [" + Filename + "] does not exist" try: instance = int(instance) except: return "Invalid instance: " + instance + " for IPMItoolParser()" retStr = "not found" currInst = 0 for line in file: line = line.strip() # get rid of leading/trailing stuff parsedItems = line.split("|") if len(parsedItems) >= 2: device = parsedItems[0].strip() if device == item: # is case sensitive! if currInst == instance: retStr = parsedItems[1].strip() break currInst += 1 return retStr #Generates a new file for you, if you specify True or "True" for # showOnlyValid, then it will ignore anything with value of 0x00 # or "Not Readable. Otherwise it will put everything int the # specified file def GenerateFile(inpfile,outputfile,showOnlyValid): Filename = convertPath(inpfile) file = open(Filename,'rt') if None == file: return "File [" + Filename + "] does not exist" if str(showOnlyValid).upper() == "TRUE": showOnlyValid = True elif str(showOnlyValid).upper() == "FALSE": showOnlyValid = False else: return "showOnlyValid is invalid parameter: " + str(showOnlyValid) dataStr = "" items = {} # generate a hashmap of data points, because there are many that have same # name but diff values for line in file: line = line.strip() # get rid of leading/trailing stuff parsedItems = line.split("|") if len(parsedItems) >= 2: device = parsedItems[0].strip() value = parsedItems[1].strip() if showOnlyValid and value == 'Not Readable': # skip if not good continue if showOnlyValid and value == '0x00': #skip if not good continue if not device in items: # 1st time for this data name items[device] = [] # create a new array items[device].append(value) if len(items) > 1: for key in items: list = items[key] if 1 == len(list): dataStr += key + "=" + list[0] + os.linesep else: entryNumber = 0 for entry in list: dataStr += key + "." + str(entryNumber) + "=" + list[entryNumber] + os.linesep entryNumber+=1 file = open(outputfile,"wt") file.write(dataStr) file.close() return "HelenKeller" # don't want to send anything def __readIPMI_Data(prefix=""): ## this will throw an exception if ipmitool not installed - I catch it elsewhere now data = subprocess.check_output(['ipmitool','sdr']).splitlines() items = {} dataStr = "" for line in data: line = line.decode('utf-8') line = line.strip() # get rid of leading/trailing stuff parsedItems = line.split("|") if len(parsedItems) >= 2: device = prefix + parsedItems[0].strip().replace(' ','_') value = parsedItems[1].strip() if value == 'Not Readable': # skip if not good continue if value == '0x00': #skip if not good continue parts = value.split() if len(parts) > 1: # strip off any words like 'celcius' value = parts[0] items[device] = value if len(items) > 1: for key in items: list = items[key] if 1 == len(list): dataStr += key + "=" + list[0] + os.linesep else: entryNumber = 0 for entry in list: dataStr += key + "." + str(entryNumber) + "=" + list[entryNumber] + os.linesep entryNumber+=1 return items def GetInitialInfoForSetup(): return __readIPMI_Data() def CollectIPMI_Info(frameworkInterface): global Logger Logger = frameworkInterface.Logger Logger.info("Starting IPMI Collector") try: while not frameworkInterface.KillThreadSignalled(): dataMap = __readIPMI_Data('ipmi.') for entry in dataMap: if not frameworkInterface.DoesCollectorExist(entry): # Do we already have this ID? frameworkInterface.AddCollector(entry) # Nope, so go add it frameworkInterface.SetCollectorValue(entry,dataMap[entry]) time.sleep(float(frameworkInterface.Interval)/1000.0) except Exception as ex: Logger.error("Unrecoverable error in CollectIPMI_Info Collector plugin: " + str(ex)) for line in traceback.format_stack(): Logger.error(line.strip()) #print(GetItem("ipmitool_results.txt","VCORE PG",0)) #print(GetItem("ipmitool_results.txt","VCORE PG",1)) #GenerateFile("ipmitool_results.txt","ipmiout.txt","True")
33.695876
98
0.569374
a46902b4b81c61db8694861bb8e621e8190504e2
195
php
PHP
app/Http/Controllers/TesteController.php
denison3965/-apply_laravel
9e56696078a80b00351b12a48d556a5eaa98bf71
[ "MIT" ]
null
null
null
app/Http/Controllers/TesteController.php
denison3965/-apply_laravel
9e56696078a80b00351b12a48d556a5eaa98bf71
[ "MIT" ]
null
null
null
app/Http/Controllers/TesteController.php
denison3965/-apply_laravel
9e56696078a80b00351b12a48d556a5eaa98bf71
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class TesteController extends Controller { public static function receiveData() { return "Hello world"; } }
15
43
0.707692
38dbca15b91be381e0ede2e6fdffd0251c46475e
6,734
php
PHP
resources/views/home.blade.php
leitnernorman/charts-example-1
5a48c58d8db17972f1111c28b383108458f38c22
[ "MIT" ]
null
null
null
resources/views/home.blade.php
leitnernorman/charts-example-1
5a48c58d8db17972f1111c28b383108458f38c22
[ "MIT" ]
null
null
null
resources/views/home.blade.php
leitnernorman/charts-example-1
5a48c58d8db17972f1111c28b383108458f38c22
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <title>Laravel 8 Highcharts Demo</title> </head> <body> <!-- <div class="buttons"> <button id="uncertified" class="active"> Uncertified/Conventional </button> <button id="traceable"> Fully/partially traceable </button> <button id="certified"> Certified green </button> </div>--> <div id="container1" style="display:none;"></div> <figure class="highcharts-figure"> <div id="container"></div> <!-- <p class="highcharts-description"> A variation of a 3D pie chart with an inner radius added. These charts are often referred to as donut charts. </p> --> </figure> <figure class="highcharts-figure"> <div id="container3"></div> </figure> <figure class="highcharts-figure"> <div id="container4"></div> </figure> <div id="container2"></div> </body> <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/highcharts-3d.js"></script> <script src="https://code.highcharts.com/modules/accessibility.js"></script> <script type="text/javascript"> var userData = <?php echo json_encode($userData)?>; Highcharts.chart('container2', { chart: { type: 'column' }, title: { text: 'Largest palm oil handling companies' }, subtitle: { text: 'Source: data.js :)' }, xAxis: { categories: [ 'Wilmar', 'GAR', 'Sime Darby Plantation', 'IOI', 'KLK', 'Bunge', 'Unilever', 'Savola Group', 'P&G', 'Nestle', 'Kao', 'RB', 'Yum! Brands', 'Colgate', 'Mondelez', 'Nissin Foods', 'Rest of buyers' ], crosshair: true }, yAxis: { min: 0, title: { text: 'Pailm oil buy/produce (ton)' } }, tooltip: { headerFormat: '<span style="font-size:10px">{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y:.1f} ton</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true }, plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } }, series: [{ name: 'Uncertified/Conventional', data: [23246764, 7615904, 1201485, 1387979, 836294, 893688, 326180, 538766, 281104, 219647, 323900, 159728, 10241, 42745, 5781, 91106, 353625] }, { name: 'Fully/partially traceable', data: [1053236, 431575, 2037439, 536104, 249596, 166312, 698641, 33019, 182191, 130617, 87500, 12700, 52583, 67490, 4409, 22903, 827093] }, { name: 'Certified green', data: [0, 0, 0, 20326, 114667, 0, 13356, 0, 0, 75250, 10000, 0, 94952, 28255, 280127, 0, 363497] }] }); Highcharts.chart('container1', { title: { text: 'New User Growth, 2020' }, subtitle: { text: 'Source: positronx.io' }, xAxis: { categories: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] }, yAxis: { title: { text: 'Number of New Users' } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, plotOptions: { series: { allowPointSelect: true } }, series: [{ name: 'New Users', data: userData }], responsive: { rules: [{ condition: { maxWidth: 500 }, chartOptions: { legend: { layout: 'horizontal', align: 'center', verticalAlign: 'bottom' } } }] } }); Highcharts.chart('container', { chart: { type: 'pie', options3d: { enabled: true, alpha: 45 } }, title: { text: 'Uncertified/Conventional palm oil production/buy' }, subtitle: { text: 'Source: data.js :)' }, plotOptions: { pie: { innerSize: 100, depth: 45 } }, series: [{ name: 'Palm oil handling in ton', data: [ ['Wilmar', 23246764], ['GAR', 7615904], ['Sime Darby Plantation', 1201485], ['IOI', 1387979], ['KLK', 836294], ['Bunge', 893688], ['Unilever', 326180], ['Savola Group', 538766], ['P&G', 281104], ['Nestle', 219647], ['Kao', 323900], ['RB', 159728], ['Yum! Brands', 10241], ['Colgate', 42745], ['Mondelez', 5781], ['Nissin Foods', 91106], ['Rest of buyers', 353625] ] }] }); Highcharts.chart('container3', { chart: { type: 'pie', options3d: { enabled: true, alpha: 45 } }, title: { text: 'Fully/partially traceable palm oil production/buy' }, subtitle: { text: 'Source: data.js :)' }, plotOptions: { pie: { innerSize: 100, depth: 45 } }, series: [{ name: 'Palm oil handling in ton', data: [ ['Wilmar', 1053236], ['GAR', 431575], ['Sime Darby Plantation', 2037439], ['IOI', 536104], ['KLK', 249596], ['Bunge', 166312], ['Unilever', 698641], ['Savola Group', 33019], ['P&G', 182191], ['Nestle', 130617], ['Kao', 87500], ['RB', 12700], ['Yum! Brands', 52583], ['Colgate', 67490], ['Mondelez', 4409], ['Nissin Foods', 22903], ['Rest of buyers', 827093] ] }] }); Highcharts.chart('container4', { chart: { type: 'pie', options3d: { enabled: true, alpha: 45 } }, title: { text: 'Certified green palm oil production/buy' }, subtitle: { text: 'Source: data.js :)' }, plotOptions: { pie: { innerSize: 100, depth: 45 } }, series: [{ name: 'Palm oil handling in ton', data: [ ['Wilmar', 0], ['GAR', 0], ['Sime Darby Plantation', 0], ['IOI', 20326], ['KLK', 114667], ['Bunge', 0], ['Unilever', 13356], ['Savola Group', 0], ['P&G', 0], ['Nestle', 75250], ['Kao', 10000], ['RB', 0], ['Yum! Brands', 94952], ['Colgate', 28255], ['Mondelez', 280127], ['Nissin Foods', 0], ['Rest of buyers', 363497] ] }] }); </script> </html>
23.061644
150
0.49109
a346050e4feb4e03769b877f8d757d04d1fb611c
977
java
Java
app/src/main/java/com/devband/stabilawalletforandroid/ui/balancecheck/BalanceCheckingActivity.java
stabilaclick/stabilaclick-android
693b927634c6d43e3e76c06f05197f1034fe41fa
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/devband/stabilawalletforandroid/ui/balancecheck/BalanceCheckingActivity.java
stabilaclick/stabilaclick-android
693b927634c6d43e3e76c06f05197f1034fe41fa
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/devband/stabilawalletforandroid/ui/balancecheck/BalanceCheckingActivity.java
stabilaclick/stabilaclick-android
693b927634c6d43e3e76c06f05197f1034fe41fa
[ "Apache-2.0" ]
null
null
null
package com.devband.stabilawalletforandroid.ui.balancecheck; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.RecyclerView; import com.devband.stabilawalletforandroid.R; import com.devband.stabilawalletforandroid.common.CommonActivity; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; public class BalanceCheckingActivity extends CommonActivity implements BalanceCheckingView { @Inject BalanceCheckingPresenter balanceCheckingPresenter; @BindView(R.id.check_listview) public RecyclerView recyclerView; @BindView(R.id.fab_add) public FloatingActionButton addButton; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_balance_checking); ButterKnife.bind(this); } }
27.914286
92
0.801433
1a5848c0c63b5c43ab54431a537bffcd372d95db
1,210
py
Python
py/idasplode/analysis/struct.py
zachriggle/ida-splode
a4aee3be415b318a0e051a523ebd0a8d6d5e0026
[ "MIT" ]
87
2015-01-08T08:53:35.000Z
2022-03-18T11:52:39.000Z
py/idasplode/analysis/struct.py
nihilus/ida-splode
0128879b8a5dabbf78550acb7b830784861b3611
[ "MIT" ]
null
null
null
py/idasplode/analysis/struct.py
nihilus/ida-splode
0128879b8a5dabbf78550acb7b830784861b3611
[ "MIT" ]
26
2015-02-08T18:57:19.000Z
2020-12-16T03:47:01.000Z
#!/usr/bin/env python # -*- coding: latin-1 -*- """ Routines for reconstructing structures based on recorded manipulations """ from .. import query from meta import Meta def ReconStructHeap(EA): # # For the current instruction, find all heap references # Traces = query.GetTraces(EA) if not Traces: print "No heap traces for %x" % EA return # # Get at the metadata # Metadata = [Meta(Trace['Address']) for Trace in Traces] # # Ensure homogoneity of: # - Allocation type # - Allocation size # - Allocation offset # - Allocation trace # HeapMeta = tuple(M for M in Metadata if M.Heap) Sizes = set(M.Size for M in HeapMeta) Offsets = set(M.Offset for M in HeapMeta) Traces = set(M.Trace for M in HeapMeta) if len(HeapMeta) != len(Metadata) print "Non-Fatal: Not all interactions are heap metadata!" if len(Sizes) != 1: print "Fatal: Multiple sizes %r" % Sizes if len(Offsets) != 1: print "Fatal: Multiple offsets %r" % Offsets if len(Traces) != 1: print "Fatal: Multiple allocation stacks"
24.693878
71
0.585124
d326bc2a8ca2f15c2e2b6c0b319bea1f0ee0378c
1,167
lua
Lua
repo-tools/generate-dist/src/CodeNormalizer/Normalizer/CommentRemover.lua
wesen1/ac-gema-mode
c44a304b0c3d110ccb31f4085236f2d0a7e0844d
[ "MIT" ]
3
2020-07-04T19:35:14.000Z
2020-11-14T19:25:03.000Z
repo-tools/generate-dist/src/CodeNormalizer/Normalizer/CommentRemover.lua
wesen1/ac-gema-mode
c44a304b0c3d110ccb31f4085236f2d0a7e0844d
[ "MIT" ]
16
2018-06-30T23:06:00.000Z
2021-10-16T12:29:26.000Z
repo-tools/generate-dist/src/CodeNormalizer/Normalizer/CommentRemover.lua
wesen1/ac-gema-mode
c44a304b0c3d110ccb31f4085236f2d0a7e0844d
[ "MIT" ]
null
null
null
--- -- @author wesen -- @copyright 2020 wesen <wesen-ac@web.de> -- @release 0.1 -- @license MIT -- local BaseNormalizer = require "src.CodeNormalizer.Normalizer.Base" --- -- Normalizer that removes trailing comments from given sets of lines. -- -- @type CommentRemover -- local CommentRemover = BaseNormalizer:extend() -- Public Methods --- -- Removes trailing comments from a given set of lines. -- -- @tparam string[] _lines The lines to remove trailing comments from -- -- @treturn string[] The lines with removed trailing comments -- function CommentRemover:normalize(_lines) local normalizedLine local normalizedLines = {} for _, line in ipairs(_lines) do if (line:match("^docremark")) then -- TODO: Fix for now to prevent URLs (e.g. http://example.com) from being interpreted as comments -- In this codebase docremark is never used manually, so there will never be trailing comments after -- these commands table.insert(normalizedLines, line) else normalizedLine = line:gsub("//.*$", "") table.insert(normalizedLines, normalizedLine) end end return normalizedLines end return CommentRemover
22.882353
106
0.706941
a302e8b55184fd14e17b8203ee010783baec1267
5,716
c
C
src/worker_milter.c
jawed123/gross
6c82f3c73c8de0d3e8e244d4aa1ac3f412db6ce7
[ "0BSD" ]
5
2016-01-13T15:34:28.000Z
2021-02-08T13:39:57.000Z
src/worker_milter.c
jawed123/gross
6c82f3c73c8de0d3e8e244d4aa1ac3f412db6ce7
[ "0BSD" ]
null
null
null
src/worker_milter.c
jawed123/gross
6c82f3c73c8de0d3e8e244d4aa1ac3f412db6ce7
[ "0BSD" ]
2
2015-12-24T11:21:49.000Z
2016-02-29T14:09:26.000Z
/* $Id$ */ /* * Copyright (c) 2007, 2008 * Eino Tuominen <eino@utu.fi> * Antti Siira <antti@utu.fi> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "common.h" #include "proto_sjsms.h" #include "srvutils.h" #include "worker.h" #include "utils.h" #include <libmilter/mfapi.h> struct private_ctx_s { char *client_address; char *sender; char *helo_name; }; #define MILTER_PRIVATE ((struct private_ctx_s *) smfi_getpriv(milter_ctx)) /* internal functions */ sfsistat mlfi_connect(SMFICTX * milter_ctx, char *hostname, _SOCK_ADDR * hostaddr); sfsistat mlfi_helo(SMFICTX * milter_ctx, char *helohost); sfsistat mlfi_envfrom(SMFICTX * milter_ctx, char **argv); sfsistat mlfi_envrcpt(SMFICTX * milter_ctx, char **argv); sfsistat mlfi_close(SMFICTX * milter_ctx); static void *milter_server(void *arg); struct smfiDesc grossfilter = { "Gross", /* filter name */ SMFI_VERSION, /* version code -- do not change */ 0, /* flags */ mlfi_connect, /* connection info filter */ mlfi_helo, /* SMTP HELO command filter */ mlfi_envfrom, /* envelope sender filter */ mlfi_envrcpt, /* envelope recipient filter */ NULL, /* header filter */ NULL, /* end of header */ NULL, /* body block filter */ NULL, /* end of message */ NULL, /* message aborted */ mlfi_close /* connection cleanup */ }; sfsistat mlfi_connect(SMFICTX * milter_ctx, char *hostname, _SOCK_ADDR * hostaddr) { struct private_ctx_s *priv; struct sockaddr_in *client_saddr; char caddr[INET_ADDRSTRLEN + 1]; logstr(GLOG_INSANE, "milter: connect"); client_saddr = (struct sockaddr_in *)hostaddr; if (client_saddr->sin_family != AF_INET) { /* not supported */ logstr(GLOG_INFO, "milter: unsupported protocol %d", client_saddr->sin_family); return SMFIS_ACCEPT; } if (NULL == inet_ntop(AF_INET, &client_saddr->sin_addr, caddr, INET_ADDRSTRLEN)) { logstr(GLOG_ERROR, "inet_top failed: %s", strerror(errno)); return SMFIS_ACCEPT; } priv = Malloc(sizeof(*priv)); bzero(priv, sizeof(*priv)); priv->client_address = strdup(caddr); smfi_setpriv(milter_ctx, priv); return SMFIS_CONTINUE; } sfsistat mlfi_helo(SMFICTX * milter_ctx, char *helohost) { struct private_ctx_s *priv = MILTER_PRIVATE; logstr(GLOG_INSANE, "milter: helo"); priv->helo_name = strdup(helohost); return SMFIS_CONTINUE; } sfsistat mlfi_envfrom(SMFICTX * milter_ctx, char **argv) { struct private_ctx_s *priv = MILTER_PRIVATE; priv->sender = strdup(argv[0]); logstr(GLOG_INSANE, "milter: envfrom: %s", priv->sender); return SMFIS_CONTINUE; } sfsistat mlfi_envrcpt(SMFICTX * milter_ctx, char **argv) { struct private_ctx_s *priv = MILTER_PRIVATE; grey_tuple_t *tuple; final_status_t *status; int retvalue = SMFIS_CONTINUE; int ret; logstr(GLOG_INSANE, "milter: envrcpt"); tuple = request_new(); status = init_status("milter"); tuple->sender = strdup(priv->sender); tuple->recipient = strdup(argv[0]); tuple->client_address = strdup(priv->client_address); if (priv->helo_name) tuple->helo_name = strdup(priv->helo_name); ret = test_tuple(status, tuple, NULL); switch (status->status) { case STATUS_GREY: smfi_setreply(milter_ctx, "452", "4.4.3", status->reason ? status->reason : "Please try again later"); retvalue = SMFIS_TEMPFAIL; break; case STATUS_BLOCK: smfi_setreply(milter_ctx, "550", "5.7.1", status->reason ? status->reason : "Rejected by policy"); retvalue = SMFIS_REJECT; break; default: retvalue = SMFIS_CONTINUE; break; } finalize(status); request_unlink(tuple); return retvalue; } sfsistat mlfi_close(SMFICTX * milter_ctx) { struct private_ctx_s *priv = MILTER_PRIVATE; logstr(GLOG_INSANE, "milter: close"); if (priv) { if (priv->sender) Free(priv->sender); if (priv->client_address) Free(priv->client_address); if (priv->helo_name) Free(priv->helo_name); Free(priv); smfi_setpriv(milter_ctx, NULL); } return SMFIS_CONTINUE; } static void * milter_server(void *arg) { int ret; ret = smfi_setconn(ctx->config.milter.listen); if (MI_FAILURE == ret) daemon_shutdown(EXIT_FATAL, "smfi_setconn failed"); if (strncasecmp(ctx->config.milter.listen, "unix:", 5) == 0) unlink(ctx->config.milter.listen + 5); if (strncasecmp(ctx->config.milter.listen, "local:", 5) == 0) unlink(ctx->config.milter.listen + 6); ret = smfi_register(grossfilter); if (MI_FAILURE == ret) daemon_shutdown(EXIT_FATAL, "smfi_register failed"); logstr(GLOG_DEBUG, "milter thread calling smfi_main()"); smfi_main(); /* NOTREACHED */ pthread_exit(NULL); } static void * milter_watcher(void *arg) { int ret; ret = pthread_join(*ctx->process_parts.milter_server.thread, NULL); daemon_shutdown(EXIT_NOERROR, "milter exited"); pthread_exit(NULL); } void milter_server_init(void) { logstr(GLOG_INFO, "starting milter policy server"); /* the milter thread */ create_thread(&ctx->process_parts.milter_server, 0, &milter_server, NULL); /* watcher thread */ create_thread(NULL, DETACH, &milter_watcher, NULL); }
25.404444
83
0.715885
b6badb9d397b001d691a1d9d8bcc45448b156095
4,204
rb
Ruby
lib/puppet/pops/lookup/data_hash_function_provider.rb
openinfrastructure/puppet
f55eeb430c8b7c8435fdd19dfbc3b2a8ad4b0155
[ "Apache-2.0" ]
4,660
2015-01-01T02:14:05.000Z
2022-03-31T08:22:07.000Z
lib/puppet/pops/lookup/data_hash_function_provider.rb
openinfrastructure/puppet
f55eeb430c8b7c8435fdd19dfbc3b2a8ad4b0155
[ "Apache-2.0" ]
4,603
2015-01-01T04:00:18.000Z
2022-03-17T22:03:50.000Z
lib/puppet/pops/lookup/data_hash_function_provider.rb
openinfrastructure/puppet
f55eeb430c8b7c8435fdd19dfbc3b2a8ad4b0155
[ "Apache-2.0" ]
1,874
2015-01-01T02:14:16.000Z
2022-03-30T07:05:10.000Z
require_relative 'function_provider' require_relative 'interpolation' module Puppet::Pops module Lookup # @api private class DataHashFunctionProvider < FunctionProvider include SubLookup include Interpolation TAG = 'data_hash'.freeze def self.trusted_return_type @trusted_return_type ||= Types::PHashType.new(DataProvider.key_type, DataProvider.value_type) end # Performs a lookup with the assumption that a recursive check has been made. # # @param key [LookupKey] The key to lookup # @param lookup_invocation [Invocation] The current lookup invocation # @param merge [MergeStrategy,String,Hash{String => Object},nil] Merge strategy, merge strategy name, strategy and options hash, or nil (implies "first found") # @return [Object] the found object # @throw :no_such_key when the object is not found def unchecked_key_lookup(key, lookup_invocation, merge) root_key = key.root_key lookup_invocation.with(:data_provider, self) do MergeStrategy.strategy(merge).lookup(locations, lookup_invocation) do |location| invoke_with_location(lookup_invocation, location, root_key) end end end private def invoke_with_location(lookup_invocation, location, root_key) if location.nil? lookup_key(lookup_invocation, nil, root_key) else lookup_invocation.with(:location, location) do if location.exist? lookup_key(lookup_invocation, location, root_key) else lookup_invocation.report_location_not_found throw :no_such_key end end end end def lookup_key(lookup_invocation, location, root_key) lookup_invocation.report_found(root_key, data_value(lookup_invocation, location, root_key)) end def data_value(lookup_invocation, location, root_key) hash = data_hash(lookup_invocation, location) value = hash[root_key] if value.nil? && !hash.include?(root_key) lookup_invocation.report_not_found(root_key) throw :no_such_key end value = validate_data_value(value) do msg = "Value for key '#{root_key}', in hash returned from #{full_name}" location.nil? ? msg : "#{msg}, when using location '#{location}'," end interpolate(value, lookup_invocation, true) end def data_hash(lookup_invocation, location) ctx = function_context(lookup_invocation, location) ctx.data_hash ||= parent_data_provider.validate_data_hash(call_data_hash_function(ctx, lookup_invocation, location)) do msg = "Value returned from #{full_name}" location.nil? ? msg : "#{msg}, when using location '#{location}'," end end def call_data_hash_function(ctx, lookup_invocation, location) ctx.function.call(lookup_invocation.scope, options(location), Context.new(ctx, lookup_invocation)) end end # @api private class V3DataHashFunctionProvider < DataHashFunctionProvider TAG = 'v3_data_hash'.freeze def initialize(name, parent_data_provider, function_name, options, locations) @datadir = options.delete(HieraConfig::KEY_DATADIR) super end def unchecked_key_lookup(key, lookup_invocation, merge) extra_paths = lookup_invocation.hiera_v3_location_overrides if extra_paths.nil? || extra_paths.empty? super else # Extra paths provided. Must be resolved and placed in front of known paths paths = parent_data_provider.config(lookup_invocation).resolve_paths(@datadir, extra_paths, lookup_invocation, false, ".#{@name}") all_locations = paths + locations root_key = key.root_key lookup_invocation.with(:data_provider, self) do MergeStrategy.strategy(merge).lookup(all_locations, lookup_invocation) do |location| invoke_with_location(lookup_invocation, location, root_key) end end end end end # TODO: API 5.0, remove this class # @api private class V4DataHashFunctionProvider < DataHashFunctionProvider TAG = 'v4_data_hash'.freeze def name "Deprecated API function \"#{function_name}\"" end def full_name "deprecated API function '#{function_name}'" end def call_data_hash_function(ctx, lookup_invocation, location) ctx.function.call(lookup_invocation.scope) end end end end
33.102362
161
0.737393
ff88cabacd92dacbee9217bbd9c80f1a798a3ac3
1,265
py
Python
setup.py
shanedrabing/seedling
0dd62ba198a2db2007f8e6b8e44ca0ffd64e2adf
[ "MIT" ]
null
null
null
setup.py
shanedrabing/seedling
0dd62ba198a2db2007f8e6b8e44ca0ffd64e2adf
[ "MIT" ]
null
null
null
setup.py
shanedrabing/seedling
0dd62ba198a2db2007f8e6b8e44ca0ffd64e2adf
[ "MIT" ]
null
null
null
__author__ = "Shane Drabing" __license__ = "MIT" __email__ = "shane.drabing@gmail.com" # IMPORTS import sys import subprocess import setuptools from setuptools.command.install import install # CONSTANTS HERE = sys.path[0] WINDOWS = str(sys.platform) in ("win32", "cygwin") # CLASSES class Install(install): """Post-installation for installation mode.""" def run(self): install.run(self) if WINDOWS: subprocess.run(["call", ".\src\compile.bat"], cwd=HERE, shell=True) else: subprocess.run(["sh", "./src/compile.sh"], cwd=HERE) # SCRIPT setuptools.setup( name="seedling", version="0.0.1", author="Shane Drabing", author_email="shane.drabing@gmail.com", packages=setuptools.find_packages(), url="https://github.com/shanedrabing/seedling", description="Quick and easy molecular phylogenies.", long_description=open("README.md", "r").read(), long_description_content_type="text/markdown", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", ], data_files=[ ("", ["LICENSE"]) ], install_requires=[ "requests" ], cmdclass={ "install": Install, }, )
20.403226
79
0.626877
91a5e093dcfbcacc87589e07c80add32331c736c
1,313
kt
Kotlin
NoMoneyTrip/app/src/main/java/com/mtjin/nomoneytrip/data/tour_detail/Item.kt
wbh3110/NoMoneyTrip
e0108bacafa68405a299e98bad933556c533104c
[ "MIT" ]
30
2020-10-06T02:51:11.000Z
2022-03-19T02:39:09.000Z
NoMoneyTrip/app/src/main/java/com/mtjin/nomoneytrip/data/tour_detail/Item.kt
wbh3110/NoMoneyTrip
e0108bacafa68405a299e98bad933556c533104c
[ "MIT" ]
10
2020-11-29T08:43:42.000Z
2021-04-08T08:45:08.000Z
NoMoneyTrip/app/src/main/java/com/mtjin/nomoneytrip/data/tour_detail/Item.kt
mtjin/NoMoneyTrip
e0108bacafa68405a299e98bad933556c533104c
[ "MIT" ]
5
2020-09-04T03:37:15.000Z
2021-12-09T08:48:04.000Z
package com.mtjin.nomoneytrip.data.tour_detail import com.google.gson.annotations.SerializedName data class Item( @SerializedName("addr1") val addr1: String, @SerializedName("addr2") val addr2: String, @SerializedName("areacode") val areacode: String, @SerializedName("booktour") val booktour: String, @SerializedName("cat1") val cat1: String, @SerializedName("cat2") val cat2: String, @SerializedName("cat3") val cat3: String, @SerializedName("contentid") val contentid: String, @SerializedName("contenttypeid") val contenttypeid: String, @SerializedName("createdtime") val createdtime: String, @SerializedName("firstimage") val firstimage: String, @SerializedName("firstimage2") val firstimage2: String, @SerializedName("homepage") val homepage: String, @SerializedName("mapx") val mapx: String, @SerializedName("mapy") val mapy: String, @SerializedName("mlevel") val mlevel: String, @SerializedName("modifiedtime") val modifiedtime: String, @SerializedName("overview") val overview: String, @SerializedName("sigungucode") val sigungucode: String, @SerializedName("title") val title: String, @SerializedName("zipcode") val zipcode: String )
26.795918
49
0.681645
b8dcf6392878114e06cfa62172548db178c9a74f
5,521
dart
Dart
lib/ui/authentication/forgot_password.dart
toxsltech/Flutter-Dart
c150bfad85dc9d76fbd6b8aa192943e219f7d37b
[ "FSFAP" ]
null
null
null
lib/ui/authentication/forgot_password.dart
toxsltech/Flutter-Dart
c150bfad85dc9d76fbd6b8aa192943e219f7d37b
[ "FSFAP" ]
null
null
null
lib/ui/authentication/forgot_password.dart
toxsltech/Flutter-Dart
c150bfad85dc9d76fbd6b8aa192943e219f7d37b
[ "FSFAP" ]
null
null
null
/* * @copyright : ToXSL Technologies Pvt. Ltd. < www.toxsl.com > * @author : Shiv Charan Panjeta < shiv@toxsl.com > * All Rights Reserved. * Proprietary and confidential : All information contained herein is, and remains * the property of ToXSL Technologies Pvt. Ltd. and its partners. * Unauthorized copying of this file, via any medium is strictly prohibited. */ // Project imports: import 'package:alanis/export.dart'; class ForgotPassword extends StatefulWidget { @override _LoginScreenState createState() => _LoginScreenState(); } class _LoginScreenState extends State<ForgotPassword> { final _formKey = GlobalKey<FormState>(); TextEditingController _emailTextController; FocusNode _emailNode; CustomLoader _customLoader = CustomLoader(); ForgotPasswordResponseModel _forgotPasswordResponseModel = ForgotPasswordResponseModel(); @override void initState() { super.initState(); _emailNode = new FocusNode(); _emailTextController = new TextEditingController(); } @override void dispose() { _customLoader.hide(); super.dispose(); } @override Widget build(BuildContext context) { return Container( color: Colors.white, child: SafeArea( child: Scaffold( backgroundColor: Colors.white, body: _body(), ), ), ); } Widget _body() { return Stack( children: [ Container( height: 100.0, width: HelperUtility.fullWidthScreen(context: context), child: Image.asset(Assets.bg_3, fit: BoxFit.fill)), Center( child: SingleChildScrollView( physics: ClampingScrollPhysics(), child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ HelperWidget.sizeBox(height: Dimens.height_50), loginHeading(), HelperWidget.sizeBox(height: Dimens.height_10), Padding( padding: EdgeInsets.only(left: 20.0, right: 20.0), child: loginSubTitle1(), ), loginSubTitle2(), HelperWidget.sizeBox(height: Dimens.height_10), _form(), HelperWidget.sizeBox(height: Dimens.height_30), _onSubmitPress(), ], ), ), ), _backButton() ], ); } Widget loginHeading() => Text( Strings.forgotPasswords, style: HelperUtility.textStyleBold( fontWeight: FontWeight.w400, color: Colors.black, fontsize: Dimens.font_20), ); Widget loginSubTitle1() => Text( Strings.text1, textAlign: TextAlign.start, maxLines: 2, style: HelperUtility.textStyle( color: Colors.grey, fontsize: Dimens.font_15), ); Widget loginSubTitle2() => Text( Strings.text2, textAlign: TextAlign.start, maxLines: 2, style: HelperUtility.textStyle( color: Colors.grey, fontsize: Dimens.font_15), ); /*================================================================ Creation of From ========================================================*/ _form() => Form( key: _formKey, child: Column( children: <Widget>[ _emailEditText(), ], ), ); /*=================================================================== Email Edit Text ====================================================================*/ Widget _emailEditText() => Padding( padding: EdgeInsets.only(left: 20, right: 20.0), child: TextFieldWidget( focusNode: _emailNode, textController: _emailTextController, hint: Strings.email, inputAction: TextInputAction.done, validate: (String val) { return EmailFormValidator.validate(val); }, inputType: TextInputType.emailAddress, icon: Assets.email, ), ); _onSubmitPress() => Padding( padding: EdgeInsets.only(left: 20, right: 20.0), child: CustomButton( height: Dimens.height_45, isbold: true, buttonText: Strings.submit, fontsize: Dimens.font_18, textColor: Colors.white, buttonIcon: Assets.facebook, isIcon: false, onPressed: () { if (_formKey.currentState.validate()) forgotApiCall(); }, buttonColor: primaryColor, ), ); _backButton() => Padding( padding: EdgeInsets.all(Dimens.width_15), child: HelperWidget.getInkwell( onTap: () { Navigator.pop(context); }, widget: Icon(Icons.arrow_back), ), ); void forgotApiCall() async { _customLoader.show(context); var response = AuthRequestModel.forgotPasswordDataRequest( firstName: _emailTextController.text.trim(), ); await APIRepository.forgotApiCall(response, context).then((value) { _customLoader.hide(); _forgotPasswordResponseModel = value; HelperUtility.push(context: context, route: LoginScreen()); HelperWidget.toast(_forgotPasswordResponseModel.message); }).onError((error, stackTrace) { _customLoader.hide(); HelperWidget.toast(error); }); } }
30.169399
158
0.56584
5dad76ffbddaefea91423f5e315c49c177c7cac1
2,745
cpp
C++
图论/差分约束/acwing_1170.cpp
tempure/algorithm-advance
38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b
[ "MIT" ]
3
2020-11-16T08:58:30.000Z
2020-11-16T08:58:33.000Z
图论/差分约束/acwing_1170.cpp
tempure/algorithm-advance
38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b
[ "MIT" ]
null
null
null
图论/差分约束/acwing_1170.cpp
tempure/algorithm-advance
38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define rep(i,a,n) for(int i = a; i< n; i++) #define per(i,a,n) for(int i=n-1; i>=a; i--) #define pb push_back #define mp make_pair #define all(x) (x).begin(), (x).end() #define x first #define y second #define sz(x) ((int)(x).size()) typedef vector<int> vi; typedef long long ll; typedef pair<int, int> pii; mt19937 mrand(random_device{}()); const ll mod = 1000000007; int rnd(int x) { return mrand() % x;} ll mulmod(ll a, ll b) {ll res=0;a%=mod;assert(b>=0);for(;b;b>>=1){if(b&1)res=(res+a)%mod;a=2*a%mod;}return res;} ll powmod(ll a, ll b) {ll res=1;a%=mod;assert(b>=0);for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;} ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a;} //snippet-head //第一个就是判负环 全部加入队列跑一次SPFA即可 //所有奶牛的距离都是相对距离,所以需要虚拟原点,假设所有牛都在数轴的正半轴 所有点都在x0的左边 也就是说x0是最右边的 //对于第二个要求 直接把1号点固定在0 也就是 x1 = 0 因为都是相对距离 不影响距离 最后看一下xn是不是可以无限大 这也等价于1号点到其他点的最短距离 //但是虚拟原点 不需要实现 实际上 在判断负环的时候所有点都已经入队 可以起到同样的效果 //求一下xn的最长路 如果无穷大 就是无穷大 否则就是最大值 //约束条件:xi <= x[i+1] + 0, xb <= xa + l, xa <= xb - d const int INF = 0x3f3f3f3f; const int N = 1010, M = 21010; //边数判断就是满足条件的类 每类需要多少点 全部加起来 //因为加边 的时候 会满足所有条件 也就是说每个条件 都要单独加边 int q[N], h[N], e[M], ne[M], idx, w[M], cnt[N], dist[N]; bool st[N]; int n, m1, m2; void add(int a, int b, int c){ e[idx] = b; ne[idx] = h[a]; w[idx] = c; h[a] = idx ++; } bool spfa(int sz){ memset(dist, 0x3f, sizeof dist); memset(st, 0, sizeof st); memset(cnt, 0, sizeof cnt); int hh = 0, tt = 1; for(int i = 1; i <= sz; i++){ //加入队列 求负环 dist[i] = 0; q[tt++] = i; st[i] = true; } while(hh != tt){ int t = q[hh++]; if(hh == N) hh = 0; st[t] = false; for(int i = h[t]; i != -1; i = ne[i]){ int j = e[i]; if(dist[j] > dist[t] + w[i]){ dist[j] = dist[t] + w[i]; cnt[j] = cnt[t] + 1; if(cnt[j] >= n) return false; if(!st[j]){ q[tt++] = j; if(tt == N) tt = 0; st[j] = true; } } } } return true; } int main(){ memset(h, -1, sizeof h); scanf("%d%d%d", &n, &m1, &m2); for(int i = 1; i < n; i++) add(i + 1, i, 0); while(m1 --){ int a, b, c; scanf("%d%d%d", &a, &b, &c); if(b < a ) swap(a, b); add(a, b, c); } while(m2 --){ int a,b ,c; scanf("%d%d%d", &a, &b, &c); if(b < a) swap(a, b); add(b, a, -c); } if(!spfa(n)) puts("-1"); //前n个点的图有负环 else{ spfa(1); //将第一个点放进去求 if(dist[n] == INF) puts("-2"); else printf("%d\n", dist[n]); } return 0; }
26.394231
112
0.488889
cdad5c44252649449a477faf75e879c7225d04c7
207
cs
C#
NBi.Core/ResultSet/IRow.cs
TheAutomatingMrLynch/NBi
d775d7cc2520db38351f3dc2f248702fba618490
[ "Apache-2.0" ]
null
null
null
NBi.Core/ResultSet/IRow.cs
TheAutomatingMrLynch/NBi
d775d7cc2520db38351f3dc2f248702fba618490
[ "Apache-2.0" ]
null
null
null
NBi.Core/ResultSet/IRow.cs
TheAutomatingMrLynch/NBi
d775d7cc2520db38351f3dc2f248702fba618490
[ "Apache-2.0" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NBi.Core.ResultSet { public interface IRow { IList<ICell> Cells { get; } } }
15.923077
36
0.637681
0c65ac739342673228019c11da1210ed14afcbcb
23,563
lua
Lua
examples/lush_tutorial.lua
astridlyre/lush.nvim
20e2822c2c140a6e6ab1ea73fb13a365e648b5d9
[ "MIT" ]
null
null
null
examples/lush_tutorial.lua
astridlyre/lush.nvim
20e2822c2c140a6e6ab1ea73fb13a365e648b5d9
[ "MIT" ]
null
null
null
examples/lush_tutorial.lua
astridlyre/lush.nvim
20e2822c2c140a6e6ab1ea73fb13a365e648b5d9
[ "MIT" ]
null
null
null
-- -- ,gggg, -- d8" "8I ,dPYb, -- 88 ,dP IP'`Yb -- 8888888P" I8 8I -- 88 I8 8' -- 88 gg gg ,g, I8 dPgg, -- ,aa,_88 I8 8I ,8'8, I8dP" "8I -- dP" "88P I8, ,8I ,8' Yb I8P I8 -- Yb,_,d88b,,_ ,d8b, ,d8b,,8'_ 8) ,d8 I8, -- "Y8P" "Y888888P'"Y88P"`Y8P' "YY8P8P88P `Y8 -- -- This is the Lush tutorial. It demostrates the functionality of Lush and how -- to write a basic lush-spec. For more information, see the README and :h lush. -- -- A Lush theme starter template can be found in the examples folder. -- -- First, enable lush.ify on this file, run: -- -- `:Lushify` -- -- or -- -- `:lua require('lush').ify()` -- -- (try putting your cursor inside the ` and typing yi`:@"<CR>) -- (make sure to enable termguicolors with `set termguicolors`) -- -- Calls to hsl()/hsluv() are now highlighted with the correct background colour -- Highlight names groups will have the highlight style applied to them. -- Lets get started, first we have to require lush, and optionally bind -- hsl to a more usable name. HSL can also be imported into other modules. local lush = require('lush') local hsl = lush.hsl -- You may also use the HSLuv colorspace, see http://www.hsluv.org/ and h: lush-hsluv-colors. -- Replace calls to hsl() with hsluv() -- local hsluv = lush.hsluv -- HSL stands for Hue (0 - 360) -- Saturation (0 - 100) -- Lightness (0 - 100) -- -- By working with HSL, it's easy to define relationships between colours. -- -- For example, rotating a hue between 30 and 60 degrees will find harmonious -- colours, or 180 degrees will find it's complementary colour. Colour theory -- is beyond the scope of this document, but with the examples below it -- should start to make some sense. -- -- Lets define some colors (these should already be highlighted for you): local sea_foam = hsl(208, 80, 80) -- Try presing C-a and C-x local sea_crest = hsl(208, 90, 30) -- to increment or decrement local sea_deep = hsl(208, 90, 10) -- the integers used here. -- Note: Some CursorLine highlighting can obscure any other -- highlighing on the current line until you move your cursor. -- -- You can disable the cursor line temporarily with: -- -- `setlocal nocursorline` -- You can see we have 3 blues, all with the same hue and adjusted levels -- of saturation and brightness. They naturally sit well together. -- -- Try editing these values to see the colours update in real time. -- -- Remember hue: [0-360], saturation and lightness: [0-100]. -- (HSL will fix any invalid values internally.) -- -- Many online palette helpers provide hex values by default, so you can -- also import those into hsl. local sea_gull = hsl("#c6c6c6") -- as as string, preceeded with a # -- Lush.hsl provides a number of convenience functions for: -- -- Relative adjustment (rotate(), saturate(), desaturate(), lighten(), darken()) -- Absolute adjustment (prefix above with abs_) -- Combination (mix()) -- Overrides (hue(), saturation(), lightness()) -- Access (.h, .s, .l) -- Coercion (tostring(), "Concatination: " .. color) -- Helpers (readable()) -- -- Adjustment functions have shortcut aliases, ro, sa, de, li, da -- abs_sa, abs_de, abs_li, abs_da -- Lets find some harmonious colours from our original set. -- (Unfortunately, deep inspection of lushify modifiers is currently WIP.) -- rotate 120 deg arond the colour wheel local sea_foam_triadic = sea_foam.rotate(120) -- rotate 180 degrees, darken and saturate the colour. local sea_foam_complement = sea_foam.rotate(180).darken(10).saturate(10) -- Now that you know the basics of using hsl(), we can define our colour -- scheme. To do this, we will write what is called a lush-spec. -- We must pass a function to Lush, which returns a table containing -- our spec. This may seem a little confusing at first, it's a lua quirk, -- just follow the template. -- When called in this manner, Lush will process our lush-spec, and return -- a table, which we can use later to compile into vimscript and apply, or -- we can access in other lua modules to use our themes color data. -- -- If you want more control over the compilation process or to export for use -- without Lush, see the README or the bottom of this file. -- Call lush with our lush-spec. -- ignore the "theme" variable for now ---@diagnostic disable: undefined-global local theme = lush(function() return { -- It's recommended to disable wrapping with `setlocal nowrap`, each -- group in this tutorial is appended by it's description for ease of use, -- but the wrapping may be distracting. -- -- You may also receive (mostly ignorable) linter/lsp warnings, -- because our lua is a bit more dynamic than they expect. -- You may also wish to disable those while editing your theme -- they produce a lot of visual noise. -- lush-spec statements are in the form: -- -- <HighlightGroupName> { bg = <hsl>|<string>, -- fg = <hsl>|<string>, -- sp = <hsl>|<string>, -- gui = <string> }, -- -- Any vim highlight group name is valid, and any unrecognized key is -- omitted. -- -- Lets define our "Normal" highlight group, using our sea colours. -- Set a highlight group from hsl variables -- Uncomment "Normal" -- Normal { bg = sea_deep, fg = sea_foam }, -- normal text -- You should be on the water now, Lush.ify has automatically -- recognized our Highlight definition and applied it in real time. -- Note: This is applied *vim wide* so other buffers reflect your changes -- too. Try opening up a project in a split to see your new theme in -- a real setting. -- Lush is most useful when you use previously defined groups aid in -- picking colours for future groups. -- -- For example, lets set our cursorline (if enabled: `setlocal cursorline`) -- to be slightly lighter than our normal background. -- -- Set a highlight group from another highlight group -- CursorLine { bg = Normal.bg.lighten(5) }, -- Screen-line at the cursor, when 'cursorline' is set. Low-priority if foreground (ctermfg OR guifg) is not set. -- Or maybe lets style our visual selection to match Cusorlines background, -- and render text in Normal's foreground complement. -- Visual { bg = CursorLine.bg, fg = Normal.fg.rotate(180) }, -- We can also link a group to another group. These will inherit all -- of the linked group options (See h: hi-link). -- (`setlocal cursorcolumn`) -- (May have performance impact depending on terminal) -- CursorColumn { CursorLine }, -- Screen-column at the cursor, when 'cursorcolumn' is set. -- We can make white space characters slighly visible -- Whitespace { fg = Normal.bg.desaturate(25).lighten(25) }, -- We can inherit properties if we want to tweak a group slightly -- Note: This looks similar to a link, but the defined group will have its -- own properties, cloned from the parent. -- Lets make Comments look like Whitespace, but with italics -- Comment { Whitespace, gui="italic" }, -- Here's how we might set our line numbers to be relational to Normal, -- note we'er also using some shorter aliases here. -- (`setlocal number`) -- LineNr { bg = Normal.bg.da(10), fg = Normal.bg.li(5) }, -- Line number for ":number" and ":#" commands, and when 'number' or 'relativenumber' option is set. -- CursorLineNr { bg = CursorLine.bg, fg = Normal.fg.ro(180) }, -- Like LineNr when 'cursorline' or 'relativenumber' is set for the cursor line. -- You can also use highlight groups to define "base" colors, if you dont -- want to use regular lua variables. They will behave in the same way. -- Note that these groups *will* be defined as a vim-highlight-group, so -- try not to pick names that might end up being used by something. -- -- CamelCase is by tradition but you don't have to use it. -- search_base { bg = hsl(52, 52, 52), fg = hsl(52, 10, 10) }, -- Search { search_base }, -- IncSearch { bg = search_base.bg.rotate(-20), fg = search_base.fg.darken(90) }, -- We can also mix colours together -- Type { fg = Normal.fg.mix(LineNr.fg, 30) } -- And that's the basics of using Lush! -- -- If you want to know more about exporting themes for use without lush -- (for distribution) or integration with other plugins (such as -- lightline), see the bottom of this file `/export-external`, the README, -- or the examples folder. -- For experimentation, below is all the Neovim default highlight groups -- from docs as of 0.5.0-812. -- -- If you wish to create a theme, it's recommended you copy the template -- folder from the examples folder. -- -- Referenced/linked groups must come before being referenced/linked, -- (i.e. above we create Normal before trying to set CursorLine) -- so the order shown ((mostly) alphabetical) is likely -- not the order you will end up with. -- -- You can uncomment these and leave them empty to disable any -- styling for that group (meaning they mostly get styled as Normal) -- or leave them commented to apply vims default colouring or linking. -- NormalFloat { }, -- Normal text in floating windows. -- ColorColumn { }, -- used for the columns set with 'colorcolumn' -- Conceal { }, -- placeholder characters substituted for concealed text (see 'conceallevel') -- Cursor { }, -- character under the cursor -- lCursor { }, -- the character under the cursor when |language-mapping| is used (see 'guicursor') -- CursorIM { }, -- like Cursor, but used when in IME mode |CursorIM| -- Directory { }, -- directory names (and other special names in listings) -- DiffAdd { }, -- diff mode: Added line |diff.txt| -- DiffChange { }, -- diff mode: Changed line |diff.txt| -- DiffDelete { }, -- diff mode: Deleted line |diff.txt| -- DiffText { }, -- diff mode: Changed text within a changed line |diff.txt| -- EndOfBuffer { }, -- filler lines (~) after the end of the buffer. By default, this is highlighted like |hl-NonText|. -- TermCursor { }, -- cursor in a focused terminal -- TermCursorNC { }, -- cursor in an unfocused terminal -- ErrorMsg { }, -- error messages on the command line -- VertSplit { }, -- the column separating vertically split windows -- Folded { }, -- line used for closed folds -- FoldColumn { }, -- 'foldcolumn' -- SignColumn { }, -- column where |signs| are displayed -- Substitute { }, -- |:substitute| replacement text highlighting -- MatchParen { }, -- The character under the cursor or just before it, if it is a paired bracket, and its match. |pi_paren.txt| -- ModeMsg { }, -- 'showmode' message (e.g., "-- INSERT -- ") -- MsgArea { }, -- Area for messages and cmdline -- MsgSeparator { }, -- Separator for scrolled messages, `msgsep` flag of 'display' -- MoreMsg { }, -- |more-prompt| -- NonText { }, -- '@' at the end of the window, characters from 'showbreak' and other characters that do not really exist in the text (e.g., ">" displayed when a double-wide character doesn't fit at the end of the line). See also |hl-EndOfBuffer|. -- NormalNC { }, -- normal text in non-current windows -- Pmenu { }, -- Popup menu: normal item. -- PmenuSel { }, -- Popup menu: selected item. -- PmenuSbar { }, -- Popup menu: scrollbar. -- PmenuThumb { }, -- Popup menu: Thumb of the scrollbar. -- Question { }, -- |hit-enter| prompt and yes/no questions -- QuickFixLine { }, -- Current |quickfix| item in the quickfix window. Combined with |hl-CursorLine| when the cursor is there. -- SpecialKey { }, -- Unprintable characters: text displayed differently from what it really is. But not 'listchars' whitespace. |hl-Whitespace| -- SpellBad { }, -- Word that is not recognized by the spellchecker. |spell| Combined with the highlighting used otherwise. -- SpellCap { }, -- Word that should start with a capital. |spell| Combined with the highlighting used otherwise. -- SpellLocal { }, -- Word that is recognized by the spellchecker as one that is used in another region. |spell| Combined with the highlighting used otherwise. -- SpellRare { }, -- Word that is recognized by the spellchecker as one that is hardly ever used. |spell| Combined with the highlighting used otherwise. -- StatusLine { }, -- status line of current window -- StatusLineNC { }, -- status lines of not-current windows Note: if this is equal to "StatusLine" Vim will use "^^^" in the status line of the current window. -- TabLine { }, -- tab pages line, not active tab page label -- TabLineFill { }, -- tab pages line, where there are no labels -- TabLineSel { }, -- tab pages line, active tab page label -- Title { }, -- titles for output from ":set all", ":autocmd" etc. -- Visual { }, -- Visual mode selection -- VisualNOS { }, -- Visual mode selection when vim is "Not Owning the Selection". -- WarningMsg { }, -- warning messages -- Whitespace { }, -- "nbsp", "space", "tab" and "trail" in 'listchars' -- WildMenu { }, -- current match in 'wildmenu' completion -- These groups are not listed as default vim groups, -- but they are defacto standard group names for syntax highlighting. -- commented out groups should chain up to their "preferred" group by -- default, -- Uncomment and edit if you want more specific syntax highlighting. -- Constant { }, -- (preferred) any constant -- String { }, -- a string constant: "this is a string" -- Character { }, -- a character constant: 'c', '\n' -- Number { }, -- a number constant: 234, 0xff -- Boolean { }, -- a boolean constant: TRUE, false -- Float { }, -- a floating point constant: 2.3e10 -- Identifier { }, -- (preferred) any variable name -- Function { }, -- function name (also: methods for classes) -- Statement { }, -- (preferred) any statement -- Conditional { }, -- if, then, else, endif, switch, etc. -- Repeat { }, -- for, do, while, etc. -- Label { }, -- case, default, etc. -- Operator { }, -- "sizeof", "+", "*", etc. -- Keyword { }, -- any other keyword -- Exception { }, -- try, catch, throw -- PreProc { }, -- (preferred) generic Preprocessor -- Include { }, -- preprocessor #include -- Define { }, -- preprocessor #define -- Macro { }, -- same as Define -- PreCondit { }, -- preprocessor #if, #else, #endif, etc. -- Type { }, -- (preferred) int, long, char, etc. -- StorageClass { }, -- static, register, volatile, etc. -- Structure { }, -- struct, union, enum, etc. -- Typedef { }, -- A typedef -- Special { }, -- (preferred) any special symbol -- SpecialChar { }, -- special character in a constant -- Tag { }, -- you can use CTRL-] on this -- Delimiter { }, -- character that needs attention -- SpecialComment { }, -- special things inside a comment -- Debug { }, -- debugging statements -- Underlined { gui = "underline" }, -- (preferred) text that stands out, HTML links -- Bold { gui = "bold" }, -- Italic { gui = "italic" }, -- ("Ignore", below, may be invisible...) -- Ignore { }, -- (preferred) left blank, hidden |hl-Ignore| -- Error { }, -- (preferred) any erroneous construct -- Todo { }, -- (preferred) anything that needs extra attention; mostly the keywords TODO FIXME and XXX -- These groups are for the native LSP client. Some other LSP clients may use -- these groups, or use their own. Consult your LSP client's documentation. -- LspDiagnosticsError { }, -- used for "Error" diagnostic virtual text -- LspDiagnosticsErrorSign { }, -- used for "Error" diagnostic signs in sign column -- LspDiagnosticsErrorFloating { }, -- used for "Error" diagnostic messages in the diagnostics float -- LspDiagnosticsWarning { }, -- used for "Warning" diagnostic virtual text -- LspDiagnosticsWarningSign { }, -- used for "Warning" diagnostic signs in sign column -- LspDiagnosticsWarningFloating { }, -- used for "Warning" diagnostic messages in the diagnostics float -- LspDiagnosticsInformation { }, -- used for "Information" diagnostic virtual text -- LspDiagnosticsInformationSign { }, -- used for "Information" signs in sign column -- LspDiagnosticsInformationFloating { }, -- used for "Information" diagnostic messages in the diagnostics float -- LspDiagnosticsHint { }, -- used for "Hint" diagnostic virtual text -- LspDiagnosticsHintSign { }, -- used for "Hint" diagnostic signs in sign column -- LspDiagnosticsHintFloating { }, -- used for "Hint" diagnostic messages in the diagnostics float -- LspReferenceText { }, -- used for highlighting "text" references -- LspReferenceRead { }, -- used for highlighting "read" references -- LspReferenceWrite { }, -- used for highlighting "write" references -- These groups are for the neovim tree-sitter highlights. -- As of writing, tree-sitter support is a WIP, group names may change. -- By default, most of these groups link to an appropriate Vim group, -- TSError -> Error for example, so you do not have to define these unless -- you explicitly want to support Treesitter's improved syntax awareness. -- TSError { }, -- For syntax/parser errors. -- TSPunctDelimiter { }, -- For delimiters ie: `.` -- TSPunctBracket { }, -- For brackets and parens. -- TSPunctSpecial { }, -- For special punctutation that does not fall in the catagories before. -- TSConstant { }, -- For constants -- TSConstBuiltin { }, -- For constant that are built in the language: `nil` in Lua. -- TSConstMacro { }, -- For constants that are defined by macros: `NULL` in C. -- TSString { }, -- For strings. -- TSStringRegex { }, -- For regexes. -- TSStringEscape { }, -- For escape characters within a string. -- TSCharacter { }, -- For characters. -- TSNumber { }, -- For integers. -- TSBoolean { }, -- For booleans. -- TSFloat { }, -- For floats. -- TSFunction { }, -- For function (calls and definitions). -- TSFuncBuiltin { }, -- For builtin functions: `table.insert` in Lua. -- TSFuncMacro { }, -- For macro defined fuctions (calls and definitions): each `macro_rules` in Rust. -- TSParameter { }, -- For parameters of a function. -- TSParameterReference { }, -- For references to parameters of a function. -- TSMethod { }, -- For method calls and definitions. -- TSField { }, -- For fields. -- TSProperty { }, -- Same as `TSField`. -- TSConstructor { }, -- For constructor calls and definitions: ` { }` in Lua, and Java constructors. -- TSConditional { }, -- For keywords related to conditionnals. -- TSRepeat { }, -- For keywords related to loops. -- TSLabel { }, -- For labels: `label:` in C and `:label:` in Lua. -- TSOperator { }, -- For any operator: `+`, but also `->` and `*` in C. -- TSKeyword { }, -- For keywords that don't fall in previous categories. -- TSKeywordFunction { }, -- For keywords used to define a fuction. -- TSException { }, -- For exception related keywords. -- TSType { }, -- For types. -- TSTypeBuiltin { }, -- For builtin types (you guessed it, right ?). -- TSNamespace { }, -- For identifiers referring to modules and namespaces. -- TSInclude { }, -- For includes: `#include` in C, `use` or `extern crate` in Rust, or `require` in Lua. -- TSAnnotation { }, -- For C++/Dart attributes, annotations that can be attached to the code to denote some kind of meta information. -- TSText { }, -- For strings considered text in a markup language. -- TSStrong { }, -- For text to be represented with strong. -- TSEmphasis { }, -- For text to be represented with emphasis. -- TSUnderline { }, -- For text to be represented with an underline. -- TSTitle { }, -- Text that is part of a title. -- TSLiteral { }, -- Literal text. -- TSURI { }, -- Any URI like a link or email. -- TSVariable { }, -- Any variable name that does not have another highlight. -- TSVariableBuiltin { }, -- Variable names that are defined by the languages, like `this` or `self`. } end) -- export-external -- -- Integrating Lush with other tools: -- -- By default, lush() actually returns your theme in parsed form. You can -- interact with it in much the same way as you can inside a lush-spec. -- -- This looks something like: -- -- local theme = lush(function() -- return { -- Normal { fg = hsl(0, 100, 50) }, -- CursorLine { Normal }, -- } -- end) -- -- theme.Normal.fg() -- returns table {h = h, s = s, l = l} -- tostring(theme.Normal.fg) -- returns "#hexstring" -- tostring(theme.Normal.fg.lighten(10)) -- you can still modify colours, etc -- -- This means you can `require('my_lush_file')` in any lua code to access your -- themes's color information. -- -- Note: -- -- "Linked" groups do not expose their colours, you can find the key -- of their linked group via the 'link' key (may require chaining) -- -- theme.CursorLine.fg() -- This is bad! -- theme.CursorLine.link -- = "Normal" -- -- Also Note: -- -- Most plugins expose their own Highlight groups, which *should be the primary -- method for setting theme colours*, there are however some plugins that -- require adjustments to a global or configuration variable. -- -- To set a global variable, use neovims lua bridge, -- -- vim.g.my_plugin.color_for_widget = theme.Normal.fg.hex -- -- An example of where you may use this, might be to configure Lightline. See -- the examples folder for two styles of this. -- -- Exporting your theme beyond Lush: -- -- If you wish to use your theme in Vim, or without loading lush, you may export -- your theme via `lush.export_to_buffer(parsed_lush_spec)`. The readme has -- further details on how to do this. -- return our parsed theme for extension or use else where. return theme -- vi:nowrap:cursorline:number
52.362222
257
0.618512
90bb8acb88bcf900e05dd4ac525a9108dae36eec
911
dart
Dart
lib/services/user_service.dart
william-franco/app-github
3e14437aa28acd29efc6f1a430ebcde0bdbb90d4
[ "Unlicense", "MIT" ]
1
2021-01-12T12:04:04.000Z
2021-01-12T12:04:04.000Z
lib/services/user_service.dart
william-franco/app-github
3e14437aa28acd29efc6f1a430ebcde0bdbb90d4
[ "Unlicense", "MIT" ]
null
null
null
lib/services/user_service.dart
william-franco/app-github
3e14437aa28acd29efc6f1a430ebcde0bdbb90d4
[ "Unlicense", "MIT" ]
null
null
null
import 'dart:convert'; import 'package:app_github/models/user_model.dart'; import 'package:http/http.dart' as http; import 'package:url_launcher/url_launcher.dart'; class UserService { static final String apiUrl = "https://api.github.com/repositories"; static Future<dynamic> getAllUsers() async { final url = "https://api.github.com/repositories"; var response = await http.get(url); if (response.statusCode == 200) { Iterable decoded = jsonDecode(response.body); List<UserModel> result = decoded.map((data) => UserModel.fromJson(data)).toList(); return result; } return response; } static launchURL(String url, {bool forceSafariVC}) async { try { if (await canLaunch(url)) { if(forceSafariVC != null) await launch(url, forceSafariVC: forceSafariVC); else await launch(url); } } catch (e) { print(e); } } }
24.621622
88
0.659715
f4a00ada8290d4d6fc9326c3127e7be687a58f7e
138
ts
TypeScript
interface/IKoa.ts
LockingReal/awilix-koa-nodebff-template
d5e36e93ef4ecb2b8392ec7a16c8e3e6bc5a6f99
[ "MIT" ]
null
null
null
interface/IKoa.ts
LockingReal/awilix-koa-nodebff-template
d5e36e93ef4ecb2b8392ec7a16c8e3e6bc5a6f99
[ "MIT" ]
null
null
null
interface/IKoa.ts
LockingReal/awilix-koa-nodebff-template
d5e36e93ef4ecb2b8392ec7a16c8e3e6bc5a6f99
[ "MIT" ]
null
null
null
import * as Koa from 'koa'; import * as render from 'koa-swig'; export interface Context extends Koa.Context{ render:typeof render; }
23
45
0.724638
f23c7b1d773181e8e73b4488f8f44632fb18bb16
1,077
php
PHP
application/views/chat/chat.php
RodrigoNunesP/zatos
82f5888604b0cff33673f31f692b8a90885111a2
[ "MIT" ]
null
null
null
application/views/chat/chat.php
RodrigoNunesP/zatos
82f5888604b0cff33673f31f692b8a90885111a2
[ "MIT" ]
null
null
null
application/views/chat/chat.php
RodrigoNunesP/zatos
82f5888604b0cff33673f31f692b8a90885111a2
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html> <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="<?php echo base_url(); ?>public/css/chat.css" rel="stylesheet"> <link href="<?php echo base_url(); ?>public/js/chat.css" rel="stylesheet"> </head> <body> <div class="col-sm-3 col-sm-offset-4 frame"> <ul></ul> <div> <div class="msj-rta macro"> <div class="text text-r" style="background:whitesmoke !important"> <input class="mytext" placeholder="Type a message"/> </div> </div> <div style="padding:10px;"> <span class="glyphicon glyphicon-share-alt"></span> </div> </div> </div> </body> </html>
38.464286
117
0.511606
ddde8ab13016f2009438c88d2c8df999d92b1cbe
10,685
java
Java
src/main/java/com/tencentcloudapi/mgobe/v20201014/models/Room.java
sharplook/tencentcloud-sdk-java-test
dfe11d6717d2eac26331fab14857f2b85535e700
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tencentcloudapi/mgobe/v20201014/models/Room.java
sharplook/tencentcloud-sdk-java-test
dfe11d6717d2eac26331fab14857f2b85535e700
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tencentcloudapi/mgobe/v20201014/models/Room.java
sharplook/tencentcloud-sdk-java-test
dfe11d6717d2eac26331fab14857f2b85535e700
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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. */ package com.tencentcloudapi.mgobe.v20201014.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class Room extends AbstractModel{ /** * 表示房间名称。最长不超过32个字符。 */ @SerializedName("Name") @Expose private String Name; /** * 表示房间最大玩家数量。最大不超过100人。 */ @SerializedName("MaxPlayers") @Expose private Long MaxPlayers; /** * 表示房主OpenId。最长不超过16个字符。 */ @SerializedName("OwnerOpenId") @Expose private String OwnerOpenId; /** * 表示是否私有,私有指的是不允许其他玩家通过匹配加入房间。 */ @SerializedName("IsPrivate") @Expose private Boolean IsPrivate; /** * 表示玩家详情列表。 */ @SerializedName("Players") @Expose private Player [] Players; /** * 表示团队属性列表。 */ @SerializedName("Teams") @Expose private Team [] Teams; /** * 表示房间 ID。出参用,由后端返回。 */ @SerializedName("Id") @Expose private String Id; /** * 表示房间类型。最长不超过32个字符。 */ @SerializedName("Type") @Expose private String Type; /** * 表示创建方式:0.单人主动发起创建房间请求;1.多人在线匹配请求分配房间;2. 直接创建满员房间。调用云API的创房请求默认为3,目前通过云API调用只支持第3种方式。 */ @SerializedName("CreateType") @Expose private Long CreateType; /** * 表示自定义房间属性,不传为空字符串。最长不超过1024个字符。 */ @SerializedName("CustomProperties") @Expose private String CustomProperties; /** * 表示房间帧同步状态。0表示未开始帧同步,1表示已开始帧同步,用于出参。 */ @SerializedName("FrameSyncState") @Expose private Long FrameSyncState; /** * 表示帧率。由控制台设置,用于出参。 */ @SerializedName("FrameRate") @Expose private Long FrameRate; /** * 表示路由ID。用于出参。 */ @SerializedName("RouteId") @Expose private String RouteId; /** * 表示房间创建的时间戳(单位:秒)。 */ @SerializedName("CreateTime") @Expose private Long CreateTime; /** * 表示开始帧同步时的时间戳(单位:秒),未开始帧同步时返回为0。 */ @SerializedName("StartGameTime") @Expose private Long StartGameTime; /** * 表示是否禁止加入房间。出参使用,默认为False,通过SDK的ChangeRoom接口可以修改。 */ @SerializedName("IsForbidJoin") @Expose private Boolean IsForbidJoin; /** * 表示房主PlayerId。 */ @SerializedName("Owner") @Expose private String Owner; /** * Get 表示房间名称。最长不超过32个字符。 * @return Name 表示房间名称。最长不超过32个字符。 */ public String getName() { return this.Name; } /** * Set 表示房间名称。最长不超过32个字符。 * @param Name 表示房间名称。最长不超过32个字符。 */ public void setName(String Name) { this.Name = Name; } /** * Get 表示房间最大玩家数量。最大不超过100人。 * @return MaxPlayers 表示房间最大玩家数量。最大不超过100人。 */ public Long getMaxPlayers() { return this.MaxPlayers; } /** * Set 表示房间最大玩家数量。最大不超过100人。 * @param MaxPlayers 表示房间最大玩家数量。最大不超过100人。 */ public void setMaxPlayers(Long MaxPlayers) { this.MaxPlayers = MaxPlayers; } /** * Get 表示房主OpenId。最长不超过16个字符。 * @return OwnerOpenId 表示房主OpenId。最长不超过16个字符。 */ public String getOwnerOpenId() { return this.OwnerOpenId; } /** * Set 表示房主OpenId。最长不超过16个字符。 * @param OwnerOpenId 表示房主OpenId。最长不超过16个字符。 */ public void setOwnerOpenId(String OwnerOpenId) { this.OwnerOpenId = OwnerOpenId; } /** * Get 表示是否私有,私有指的是不允许其他玩家通过匹配加入房间。 * @return IsPrivate 表示是否私有,私有指的是不允许其他玩家通过匹配加入房间。 */ public Boolean getIsPrivate() { return this.IsPrivate; } /** * Set 表示是否私有,私有指的是不允许其他玩家通过匹配加入房间。 * @param IsPrivate 表示是否私有,私有指的是不允许其他玩家通过匹配加入房间。 */ public void setIsPrivate(Boolean IsPrivate) { this.IsPrivate = IsPrivate; } /** * Get 表示玩家详情列表。 * @return Players 表示玩家详情列表。 */ public Player [] getPlayers() { return this.Players; } /** * Set 表示玩家详情列表。 * @param Players 表示玩家详情列表。 */ public void setPlayers(Player [] Players) { this.Players = Players; } /** * Get 表示团队属性列表。 * @return Teams 表示团队属性列表。 */ public Team [] getTeams() { return this.Teams; } /** * Set 表示团队属性列表。 * @param Teams 表示团队属性列表。 */ public void setTeams(Team [] Teams) { this.Teams = Teams; } /** * Get 表示房间 ID。出参用,由后端返回。 * @return Id 表示房间 ID。出参用,由后端返回。 */ public String getId() { return this.Id; } /** * Set 表示房间 ID。出参用,由后端返回。 * @param Id 表示房间 ID。出参用,由后端返回。 */ public void setId(String Id) { this.Id = Id; } /** * Get 表示房间类型。最长不超过32个字符。 * @return Type 表示房间类型。最长不超过32个字符。 */ public String getType() { return this.Type; } /** * Set 表示房间类型。最长不超过32个字符。 * @param Type 表示房间类型。最长不超过32个字符。 */ public void setType(String Type) { this.Type = Type; } /** * Get 表示创建方式:0.单人主动发起创建房间请求;1.多人在线匹配请求分配房间;2. 直接创建满员房间。调用云API的创房请求默认为3,目前通过云API调用只支持第3种方式。 * @return CreateType 表示创建方式:0.单人主动发起创建房间请求;1.多人在线匹配请求分配房间;2. 直接创建满员房间。调用云API的创房请求默认为3,目前通过云API调用只支持第3种方式。 */ public Long getCreateType() { return this.CreateType; } /** * Set 表示创建方式:0.单人主动发起创建房间请求;1.多人在线匹配请求分配房间;2. 直接创建满员房间。调用云API的创房请求默认为3,目前通过云API调用只支持第3种方式。 * @param CreateType 表示创建方式:0.单人主动发起创建房间请求;1.多人在线匹配请求分配房间;2. 直接创建满员房间。调用云API的创房请求默认为3,目前通过云API调用只支持第3种方式。 */ public void setCreateType(Long CreateType) { this.CreateType = CreateType; } /** * Get 表示自定义房间属性,不传为空字符串。最长不超过1024个字符。 * @return CustomProperties 表示自定义房间属性,不传为空字符串。最长不超过1024个字符。 */ public String getCustomProperties() { return this.CustomProperties; } /** * Set 表示自定义房间属性,不传为空字符串。最长不超过1024个字符。 * @param CustomProperties 表示自定义房间属性,不传为空字符串。最长不超过1024个字符。 */ public void setCustomProperties(String CustomProperties) { this.CustomProperties = CustomProperties; } /** * Get 表示房间帧同步状态。0表示未开始帧同步,1表示已开始帧同步,用于出参。 * @return FrameSyncState 表示房间帧同步状态。0表示未开始帧同步,1表示已开始帧同步,用于出参。 */ public Long getFrameSyncState() { return this.FrameSyncState; } /** * Set 表示房间帧同步状态。0表示未开始帧同步,1表示已开始帧同步,用于出参。 * @param FrameSyncState 表示房间帧同步状态。0表示未开始帧同步,1表示已开始帧同步,用于出参。 */ public void setFrameSyncState(Long FrameSyncState) { this.FrameSyncState = FrameSyncState; } /** * Get 表示帧率。由控制台设置,用于出参。 * @return FrameRate 表示帧率。由控制台设置,用于出参。 */ public Long getFrameRate() { return this.FrameRate; } /** * Set 表示帧率。由控制台设置,用于出参。 * @param FrameRate 表示帧率。由控制台设置,用于出参。 */ public void setFrameRate(Long FrameRate) { this.FrameRate = FrameRate; } /** * Get 表示路由ID。用于出参。 * @return RouteId 表示路由ID。用于出参。 */ public String getRouteId() { return this.RouteId; } /** * Set 表示路由ID。用于出参。 * @param RouteId 表示路由ID。用于出参。 */ public void setRouteId(String RouteId) { this.RouteId = RouteId; } /** * Get 表示房间创建的时间戳(单位:秒)。 * @return CreateTime 表示房间创建的时间戳(单位:秒)。 */ public Long getCreateTime() { return this.CreateTime; } /** * Set 表示房间创建的时间戳(单位:秒)。 * @param CreateTime 表示房间创建的时间戳(单位:秒)。 */ public void setCreateTime(Long CreateTime) { this.CreateTime = CreateTime; } /** * Get 表示开始帧同步时的时间戳(单位:秒),未开始帧同步时返回为0。 * @return StartGameTime 表示开始帧同步时的时间戳(单位:秒),未开始帧同步时返回为0。 */ public Long getStartGameTime() { return this.StartGameTime; } /** * Set 表示开始帧同步时的时间戳(单位:秒),未开始帧同步时返回为0。 * @param StartGameTime 表示开始帧同步时的时间戳(单位:秒),未开始帧同步时返回为0。 */ public void setStartGameTime(Long StartGameTime) { this.StartGameTime = StartGameTime; } /** * Get 表示是否禁止加入房间。出参使用,默认为False,通过SDK的ChangeRoom接口可以修改。 * @return IsForbidJoin 表示是否禁止加入房间。出参使用,默认为False,通过SDK的ChangeRoom接口可以修改。 */ public Boolean getIsForbidJoin() { return this.IsForbidJoin; } /** * Set 表示是否禁止加入房间。出参使用,默认为False,通过SDK的ChangeRoom接口可以修改。 * @param IsForbidJoin 表示是否禁止加入房间。出参使用,默认为False,通过SDK的ChangeRoom接口可以修改。 */ public void setIsForbidJoin(Boolean IsForbidJoin) { this.IsForbidJoin = IsForbidJoin; } /** * Get 表示房主PlayerId。 * @return Owner 表示房主PlayerId。 */ public String getOwner() { return this.Owner; } /** * Set 表示房主PlayerId。 * @param Owner 表示房主PlayerId。 */ public void setOwner(String Owner) { this.Owner = Owner; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "Name", this.Name); this.setParamSimple(map, prefix + "MaxPlayers", this.MaxPlayers); this.setParamSimple(map, prefix + "OwnerOpenId", this.OwnerOpenId); this.setParamSimple(map, prefix + "IsPrivate", this.IsPrivate); this.setParamArrayObj(map, prefix + "Players.", this.Players); this.setParamArrayObj(map, prefix + "Teams.", this.Teams); this.setParamSimple(map, prefix + "Id", this.Id); this.setParamSimple(map, prefix + "Type", this.Type); this.setParamSimple(map, prefix + "CreateType", this.CreateType); this.setParamSimple(map, prefix + "CustomProperties", this.CustomProperties); this.setParamSimple(map, prefix + "FrameSyncState", this.FrameSyncState); this.setParamSimple(map, prefix + "FrameRate", this.FrameRate); this.setParamSimple(map, prefix + "RouteId", this.RouteId); this.setParamSimple(map, prefix + "CreateTime", this.CreateTime); this.setParamSimple(map, prefix + "StartGameTime", this.StartGameTime); this.setParamSimple(map, prefix + "IsForbidJoin", this.IsForbidJoin); this.setParamSimple(map, prefix + "Owner", this.Owner); } }
24.229025
110
0.62059
f23e9296c259e5b27e411208e0074389f8a9009c
510
php
PHP
storage/framework/views/4dedd4aed01eecfc516d9c2071fd1ee070b5d5a9.php
deanoamor/anoart-website
ff88eb4cfc1bf476ca024e20aeec62cefe4dd299
[ "MIT" ]
null
null
null
storage/framework/views/4dedd4aed01eecfc516d9c2071fd1ee070b5d5a9.php
deanoamor/anoart-website
ff88eb4cfc1bf476ca024e20aeec62cefe4dd299
[ "MIT" ]
null
null
null
storage/framework/views/4dedd4aed01eecfc516d9c2071fd1ee070b5d5a9.php
deanoamor/anoart-website
ff88eb4cfc1bf476ca024e20aeec62cefe4dd299
[ "MIT" ]
null
null
null
<meta name="keywords" content="design, asset, flat design, ano , art , anoart, svg , download"> <meta name="description" content="This website is a place to get design assets that can be used commercially and free. All files are in the svg format and are allowed to change the design or make design assets on this web as the basis for creating new designs."> <meta name="author" content="anoart"><?php /**PATH C:\xampp\htdocs\anoart\resources\views/template/meta.blade.php ENDPATH**/ ?>
127.5
167
0.719608
483e76ac1d1be555f92d99aa54b0c4e9a13949f8
199
ps1
PowerShell
sqrt/sqrt.ps1
hpissei/hacktoberfest
1851a8845a71df3ac919ca650c07ce778ec5da47
[ "MIT" ]
1
2020-02-08T07:11:32.000Z
2020-02-08T07:11:32.000Z
sqrt/sqrt.ps1
hpissei/hacktoberfest
1851a8845a71df3ac919ca650c07ce778ec5da47
[ "MIT" ]
2
2020-01-19T14:40:27.000Z
2020-01-19T14:42:51.000Z
sqrt/sqrt.ps1
hpissei/hacktoberfest
1851a8845a71df3ac919ca650c07ce778ec5da47
[ "MIT" ]
1
2019-10-17T17:22:26.000Z
2019-10-17T17:22:26.000Z
Write-Host "Please enter a number to calculate the square root of it:" $input = Read-Host $root = [System.Math]::Round([System.Math]::Sqrt($input), 4) Write-Host "Square root of " $input " is" $root
49.75
71
0.698492
e1d60685a71ae8102665d66369a5d17e439a59cb
1,586
cs
C#
Assets/Scripts/MapElements/MapElementSplitInfo.cs
TrutzX/9nations
c8a0df8460a60341c441b2d63defb8c60c408b1d
[ "MIT" ]
1
2021-11-02T14:27:53.000Z
2021-11-02T14:27:53.000Z
Assets/Scripts/MapElements/MapElementSplitInfo.cs
TrutzX/9Nations
c8a0df8460a60341c441b2d63defb8c60c408b1d
[ "MIT" ]
null
null
null
Assets/Scripts/MapElements/MapElementSplitInfo.cs
TrutzX/9Nations
c8a0df8460a60341c441b2d63defb8c60c408b1d
[ "MIT" ]
null
null
null
using System.Linq; using Buildings; using Game; using UI; using UI.Show; namespace MapElements { class MapElementSplitInfo : SplitElement { private readonly MapElementInfo _info; public MapElementSplitInfo(MapElementInfo info) : base(info.name,info.baseData.Sprite()) { this._info = info; } public override void ShowDetail(PanelBuilder panel) { panel.AddImageLabel(_info.name, _info.Sprite()); panel.AddHeaderLabel("Information"); //diff unit? if (!_info.Owner(S.ActPlayerID())) { panel.AddSubLabel("Owner",_info.Player().name, _info.Player().Coat().Icon); panel.AddSubLabel("HP",$"??/{_info.baseData.hp}","hp"); panel.AddSubLabel("AP",$"??/{_info.baseData.ap}","ap"); return; } panel.RichText(_info.data.info.LastInfo()); panel.AddSubLabel("HP",$"{_info.data.hp}/{_info.data.hpMax}","hp"); panel.AddSubLabel("AP",$"{_info.data.ap}/{_info.data.apMax}","ap"); Construction con = _info.GetComponent<Construction>(); if (con != null) { panel.AddResT("constructionOnGoing",_info.data.construction.ToDictionary(entry => entry.Key,entry => entry.Value)); panel.AddLabelT("constructionOnGoingDesc"); } panel.AddModi(_info.data.modi); } public override void Perform() { } } }
32.367347
131
0.544767
4e8accfbd8872c92f3b4f2d1e5a1bdfc9a8e88a7
1,662
swift
Swift
Sources/PitchSpeller/PitchSpeller/Wetherfield/FlowNode.swift
bwetherfield/PitchSpeller
f4fe72e5f3c5f613dd364da7edd6f10c09e2200a
[ "MIT" ]
3
2019-06-04T18:58:07.000Z
2020-09-04T00:49:19.000Z
Sources/PitchSpeller/PitchSpeller/Wetherfield/FlowNode.swift
bwetherfield/PitchSpeller
f4fe72e5f3c5f613dd364da7edd6f10c09e2200a
[ "MIT" ]
null
null
null
Sources/PitchSpeller/PitchSpeller/Wetherfield/FlowNode.swift
bwetherfield/PitchSpeller
f4fe72e5f3c5f613dd364da7edd6f10c09e2200a
[ "MIT" ]
null
null
null
// // FlowNode.swift // PitchSpeller // // Created by Benjamin Wetherfield on 6/4/19. // import DataStructures public enum FlowNode<Index>: Hashable where Index: Hashable { case `internal`(Index) case source case sink } func bind <S: Hashable, A: Hashable> (_ f: @escaping (S) -> A) -> (FlowNode<S>) -> FlowNode<A> { return { flowNodeS in switch flowNodeS { case .internal(let index): return .internal(f(index)) case .source: return .source case .sink: return .sink } } } extension FlowNode: Codable where Index: Codable { private enum CodingKeys: String, CodingKey { case external case `internal` } enum CodingError: Error { case decoding(String) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) if let node = try? values.decode(Index.self, forKey: .internal) { self = .internal(node) return } else if let node = try? values.decode(String.self, forKey: .external) { self = (node == "source") ? .source : .sink return } throw CodingError.decoding("Decoding Error: \(dump(values))") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .internal(let node): try container.encode(node, forKey: .internal) case .source: try container.encode("source", forKey: .external) case .sink: try container.encode("sink", forKey: .external) } } }
29.157895
96
0.598676
23ce74b1520796f7afa1945371e4762700009751
1,853
js
JavaScript
app/client/templates/contracts/abi/savingPoints.js
TOMOAKI12345/Intee
537da5119382e0cdb38ee5d9b69c67d0d93ea951
[ "MIT" ]
2
2017-05-15T21:16:07.000Z
2021-09-17T02:04:42.000Z
app/client/templates/contracts/abi/savingPoints.js
TOMOAKI12345/Intee
537da5119382e0cdb38ee5d9b69c67d0d93ea951
[ "MIT" ]
null
null
null
app/client/templates/contracts/abi/savingPoints.js
TOMOAKI12345/Intee
537da5119382e0cdb38ee5d9b69c67d0d93ea951
[ "MIT" ]
null
null
null
var savingPointsABI = [ { "constant": false, "inputs": [ { "name": "account", "type": "address" } ], "name": "getSPBalance", "outputs": [ { "name": "balance", "type": "uint256" } ], "type": "function" }, { "constant": false, "inputs": [], "name": "saveEther", "outputs": [ { "name": "sufficient", "type": "bool" } ], "type": "function" }, { "constant": false, "inputs": [], "name": "getFundSPBalance", "outputs": [ { "name": "balance", "type": "uint256" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "borrowAmount", "type": "uint256" } ], "name": "borrowEther", "outputs": [ { "name": "sufficient", "type": "bool" } ], "type": "function" }, { "constant": false, "inputs": [], "name": "getFundBalance", "outputs": [ { "name": "balance", "type": "uint256" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "account", "type": "address" } ], "name": "getEtherBalance", "outputs": [ { "name": "balance", "type": "uint256" } ], "type": "function" } ]
20.588889
39
0.296816
834443f48de75bfae880de73f50fe6e52b0358b6
672
ts
TypeScript
src/core/src/lib/extensions/field-expression/utils.spec.ts
Effera/ngx-formly
c3ad3841503dff1bc299e4115e6c058e2164d455
[ "MIT" ]
1
2020-03-26T14:08:21.000Z
2020-03-26T14:08:21.000Z
src/core/src/lib/extensions/field-expression/utils.spec.ts
HarshitChhipa/ngx-formly
3194a2ce9659d23e9f15b1e636a91879a531aa75
[ "MIT" ]
null
null
null
src/core/src/lib/extensions/field-expression/utils.spec.ts
HarshitChhipa/ngx-formly
3194a2ce9659d23e9f15b1e636a91879a531aa75
[ "MIT" ]
null
null
null
import { evalExpression, evalStringExpression } from './utils'; describe('evalStringExpression', () => { it('should the value correctly', () => { const warn = spyOn(console, 'warn'); evalStringExpression('this.field.templateOptions.label', []); expect(warn).toHaveBeenCalledWith(`NgxFormly: using 'this.field' in expressionProperties is deprecated since v5.1, use 'field' instead.`); }); }); describe('evalExpression', () => { it('should evaluate the value correctly', () => { let expression = () => { return this.model.val; }; this.model = { val: 2, }; expect(evalExpression(expression, this, [this.model])).toBe(2); }); });
32
142
0.644345
1a5ecb6c12e8db85c2c8ed41f472685bc122e3d8
222
py
Python
dask_sql/physical/rex/core/__init__.py
compose2-ankit/dask-sql
0818e3f4b5719116e17fec355aafda7d373bebe8
[ "MIT" ]
1
2021-11-06T08:19:29.000Z
2021-11-06T08:19:29.000Z
dask_sql/physical/rex/core/__init__.py
ciusji/dask-sql
3815a494e1e93558fca86a86d59578ba6696c9c5
[ "MIT" ]
1
2021-05-24T21:16:27.000Z
2021-05-25T19:12:57.000Z
dask_sql/physical/rex/core/__init__.py
ciusji/dask-sql
3815a494e1e93558fca86a86d59578ba6696c9c5
[ "MIT" ]
1
2021-01-24T05:52:50.000Z
2021-01-24T05:52:50.000Z
from .call import RexCallPlugin from .input_ref import RexInputRefPlugin from .literal import RexLiteralPlugin from .over import RexOverPlugin __all__ = [RexCallPlugin, RexInputRefPlugin, RexLiteralPlugin, RexOverPlugin]
31.714286
77
0.851351
7f18a00acc76195d1bbf5f296522449226cf027e
235
dart
Dart
bin/swupdate.dart
tvolkert/tesla.dart
1feb3dea25f8428f4d7678b1be836b55d96da825
[ "MIT" ]
null
null
null
bin/swupdate.dart
tvolkert/tesla.dart
1feb3dea25f8428f4d7678b1be836b55d96da825
[ "MIT" ]
null
null
null
bin/swupdate.dart
tvolkert/tesla.dart
1feb3dea25f8428f4d7678b1be836b55d96da825
[ "MIT" ]
null
null
null
import 'dart:async'; import 'package:tesla/tool.dart'; Future main() async { var client = getTeslaClient(); for (var vehicle in await client.listVehicles()) { await vehicle.scheduleSoftwareUpdate(); } client.close(); }
16.785714
52
0.689362
e708554f1da6db781b164f9422a59e87e1311bf0
1,033
php
PHP
tests/Beanie/Command/CommandLineCreator/PutCommandLineCreatorTest.php
zwilias/Beanie
8f0993a163c73ca0dfe1d0b3779fb188ff9cc304
[ "MIT" ]
null
null
null
tests/Beanie/Command/CommandLineCreator/PutCommandLineCreatorTest.php
zwilias/Beanie
8f0993a163c73ca0dfe1d0b3779fb188ff9cc304
[ "MIT" ]
null
null
null
tests/Beanie/Command/CommandLineCreator/PutCommandLineCreatorTest.php
zwilias/Beanie
8f0993a163c73ca0dfe1d0b3779fb188ff9cc304
[ "MIT" ]
null
null
null
<?php namespace Beanie\Command\CommandLineCreator; class PutCommandLineCreatorTest extends \PHPUnit_Framework_TestCase { const TEST_COMMAND = 'test'; /** * @param $params * @dataProvider putCommandParams */ public function testCreate_withData_setsDataAndLength( $params ) { $paramsCopy = array_slice($params, 0); $data = array_shift($paramsCopy); array_push($paramsCopy, strlen($data)); $expected = sprintf('%s %s', self::TEST_COMMAND, join(' ', $paramsCopy)); $commandLineCreator = new PutCommandLineCreator(self::TEST_COMMAND, $params); $commandLine = $commandLineCreator->getCommandLine(); $this->assertEquals($expected, $commandLine); $this->assertTrue($commandLineCreator->hasData()); $this->assertEquals($data, $commandLineCreator->getData()); } public function putCommandParams() { return [ [['this is some data']], [['more data', 1, 2, 3]] ]; } }
24.595238
85
0.619555
4442fda6b37b49f1bd1e561c729db66060986767
1,888
py
Python
src/botus_receptus/gino/model.py
gpontesss/botus_receptus
bf29f5f70a2e7ae3548a44287c636515f78e7e77
[ "BSD-3-Clause" ]
3
2019-04-15T01:45:46.000Z
2020-04-07T13:31:19.000Z
src/botus_receptus/gino/model.py
gpontesss/botus_receptus
bf29f5f70a2e7ae3548a44287c636515f78e7e77
[ "BSD-3-Clause" ]
244
2020-04-20T22:10:23.000Z
2022-03-31T23:03:48.000Z
src/botus_receptus/gino/model.py
gpontesss/botus_receptus
bf29f5f70a2e7ae3548a44287c636515f78e7e77
[ "BSD-3-Clause" ]
1
2021-11-08T08:52:32.000Z
2021-11-08T08:52:32.000Z
from __future__ import annotations from typing import Any, Final, TypeVar, cast from gino.declarative import ModelType from gino.engine import GinoEngine from sqlalchemy.dialects.postgresql import insert from ..compat import Mapping, Sequence from ..compat import dict as Dict from ..compat import list, type _M = TypeVar('_M', bound='ModelMixin') DEFAULT: Final = cast(int, object()) class ModelMixin: @classmethod async def create_or_update( cls: type[_M], /, *, set_: Sequence[str] | Mapping[str, str], bind: GinoEngine | None = None, timeout: int = DEFAULT, **values: Any, ) -> _M: assert isinstance(cls, ModelType) cls._check_abstract() column_name_map = cls._column_name_map index_elements: list[str] = [ column_name_map[k] for k in cls.__table__.primary_key.columns.keys() ] insert_values: Dict[str, Any] = { column_name_map[k]: v for k, v in values.items() } set_values: Mapping[str, str] if hasattr(set_, 'get'): set_values = cast(Mapping[str, str], set_) else: set_values = {v: v for v in cast(Sequence[str], set_)} opts: Dict[str, Any] = dict(return_model=False, model=cls) if timeout is not DEFAULT: opts['timeout'] = timeout stmt = insert(cls).values(**insert_values).returning(*cls) stmt = stmt.on_conflict_do_update( index_elements=index_elements, set_={k: getattr(stmt.excluded, v) for k, v in set_values.items()}, ).execution_options(**opts) if bind is None: assert cls.__metadata__.bind is not None bind = cls.__metadata__.bind row = await bind.first(stmt) return cls(**{column_name_map.invert_get(k, ''): v for k, v in row.items()})
29.046154
84
0.614936