text
stringlengths
201
300k
source_other
stringlengths
180
1.21k
<reponame>bopopescu/BEMOSSx import logging import sys from volttron.platform.agent import BaseAgent, PublishMixin, periodic from volttron.platform.agent import utils, matching from volttron.platform.messaging import headers as headers_mod, topics utils.setup_logging() _log = logging.getLogger(__name__) class TestRegistrationAgent(PublishMixin, BaseAgent): def __init__(self, config_path, **kwargs): super(TestRegistrationAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) def setup(self): self._agent_id = self.config['agentid'] super(TestRegistrationAgent, self).setup() self.run_tests() def run_tests(self): _log.debug("Attempting to register devices") self.post_register_test() _log.debug("Attempting to list registered devices") self.post_list_registered_test() _log.debug("Attempting to unregister devices") self.post_unregister_test() _log.debug("Attempting to list registered devices") self.post_list_registered_test() _log.debug("Attempting to see if individual devices are registered") self.post_is_registered_test() def post_register_test(self): headers = {'requesterID' : self._agent_id, "From" : "RegistrationAgentTester"} msg = {"agents_to_register" : {"agent_1" : "agent_1 info", "agent_2" : "agent_2_info"} } self.publish_json("registration/register", headers, msg) @matching.match_exact("registration/register/response") def on_test_register_response(self, topic, headers, message, match): try: print "Received registration response.\nMessage: {msg}".format(msg = message) except: print "FAILURE due to exception: %s" % sys.exc_info()[0] def post_unregister_test(self): headers = {'requesterID' : self._agent_id, "From" : "RegistrationAgentTester"} msg = {"agents_to_unregister" : ["agent_1", "agent_3"]} self.publish_json("registration/unregister", headers, msg) @matching.match_exact("registration/unregister/response") def on_test_unregister_response(self, topic, headers, message, match): try: print "Received unregistration response.\nMessage: {msg}".format(msg = message) except: print "FAILURE due to exception: %s" % sys.exc_info()[0] def post_list_registered_test(self): headers = {'requesterID' : self._agent_id, "From" : "RegistrationAgentTester"} msg = {} self.publish_json("registration/list", headers, msg) @matching.match_exact("registration/list/response") def on_test_list_registered_response(self, topic, headers, message, match): try: print "Received list_registered response.\nMessage: {msg}".format(msg = message) except: print "FAILURE due to exception: %s" % sys.exc_info()[0] def post_is_registered_test(self): headers = {'requesterID' : self._agent_id, "From" : "RegistrationAgentTester"} msg = {"agents" : ["agent_1"]} self.publish_json("registration/is_registered", headers, msg) msg = {"agents" : ["agent_2"]} self.publish_json("registration/is_registered", headers, msg) msg = {"agents" : ["agent_3"]} self.publish_json("registration/is_registered", headers, msg) msg = {"agents" : ["agent_1", "agent_2", "agent_3"]} self.publish_json("registration/is_registered", headers, msg) @matching.match_exact("registration/is_registered/response") def on_test_is_registered_response(self, topic, headers, message, match): try: print "Received is_registered response.\nMessage: {msg}".format(msg = message) except: print "FAILURE due to exception: %s" % sys.exc_info()[0] def main(argv=sys.argv): '''Main method called by the eggsecutable.''' utils.default_main(TestRegistrationAgent, description='Testing agent for Archiver Agent in VOLTTRON Lite', argv=argv) if __name__ == '__main__': # Entry point for script try: sys.exit(main()) except KeyboardInterrupt: pass
{'dir': 'python', 'id': '624343', 'max_stars_count': '0', 'max_stars_repo_name': 'bopopescu/BEMOSSx', 'max_stars_repo_path': 'Agents/TestRegistrationAgent/testregistrationAgent/agent.py', 'n_tokens_mistral': 1293, 'n_tokens_neox': 1248, 'n_words': 270}
using System; using Eklee.Azure.Functions.GraphQl.Repository.DocumentDb; using Eklee.Azure.Functions.GraphQl.Repository.Http; using Eklee.Azure.Functions.GraphQl.Repository.InMemory; namespace Eklee.Azure.Functions.GraphQl { public interface IModelConventionInputBuilder<TSource> where TSource : class { InMemoryConfiguration<TSource> ConfigureInMemory<TType>(); HttpConfiguration<TSource> ConfigureHttp<TType>(); DocumentDbConfiguration<TSource> ConfigureDocumentDb<TType>(); ModelConventionInputBuilder<TSource> Delete<TDeleteInput, TDeleteOutput>( Func<TDeleteInput, TSource> mapDelete, Func<TSource, TDeleteOutput> transform); ModelConventionInputBuilder<TSource> DeleteAll<TDeleteOutput>(Func<TDeleteOutput> getOutput); void Build(); } }
{'dir': 'c-sharp', 'id': '7138376', 'max_stars_count': '67', 'max_stars_repo_name': 'seekdavidlee/Eklee-Azure-Functions-GraphQl', 'max_stars_repo_path': 'Eklee.Azure.Functions.GraphQl/IModelConventionInputBuilder.cs', 'n_tokens_mistral': 243, 'n_tokens_neox': 228, 'n_words': 36}
import socket if "__main__" == __name__: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM); print("create socket succ!"); sock.bind(('127.0.0.1', 6010)); print("bind socket succ!"); sock.listen(5); print("listen succ!"); except: print("init socket err!"); while True: print("listen for client..."); conn, addr = sock.accept(); print("get client"); print(addr); conn.settimeout(5); szBuf = conn.recv(1024); print("recv:" + szBuf); if "0" == szBuf: conn.send('exit'); else: conn.send('welcome client!'); conn.close(); print("end of sevice");
{'dir': 'python', 'id': '9241120', 'max_stars_count': '0', 'max_stars_repo_name': 'mabotech/mabo.io', 'max_stars_repo_path': 'py/AK/test/ak_server2.py', 'n_tokens_mistral': 242, 'n_tokens_neox': 227, 'n_words': 51}
import ControlScheme from "src/components/player/ControlScheme"; const Player = "Player"; Crafty.c(Player, { init() { this.reset(); }, reset() { if (this.has(ControlScheme)) { this.removeComponent(ControlScheme); } } }); export default Player;
{'dir': 'javascript', 'id': '177390', 'max_stars_count': '19', 'max_stars_repo_name': 'speedlazer/game-play', 'max_stars_repo_path': 'src/components/player/Player.js', 'n_tokens_mistral': 91, 'n_tokens_neox': 88, 'n_words': 17}
<gh_stars>0 import unittest import numpy as np from graphz.dataset import GraphDataset class TestCreation(unittest.TestCase): def setUp(self): # This is NOT symmetric. self.sample_A = np.matrix([ [1.0, 0.1, 0.0, 0.3], [0.7, 0.0, 0.0, 0.4], [0.0, 0.0, 0.0, 0.9], [0.5, 0.6, 0.8, 0.0] ]) def test_from_simple_edge_list(self): edges = [(0, 0), (0, 1), (0, 2), (0, 3), (3, 4)] g = GraphDataset.from_edges(n_nodes=5, edges=edges, name='GraphX') self.assertEqual(g.name, 'GraphX') self.assertFalse(g.weighted) self.assertFalse(g.directed) self.assertEqual(g.n_nodes, 5) self.assertEqual(g.n_edges, 5) self.assertSetEqual(set(g.get_edge_iter()), set(map(lambda e : (e[0], e[1], 1), edges))) def test_from_adj_mat_dense_undirected_unweighted(self): node_attrs = ['a', 'b', 'c', 'd'] node_labels = [1, 2, 4, 5] edges_expected = [(0, 0, 1), (0, 1, 1), (0, 3, 1), (1, 3, 1), (2, 3, 1)] g = GraphDataset.from_adj_mat(self.sample_A, directed=False, weighted=False, name='Unweighted', node_attributes=node_attrs, node_labels=node_labels) self.assertEqual(g.name, 'Unweighted') self.assertSetEqual(set(g.get_edge_iter()), set(edges_expected)) self.assertListEqual(list(g.node_attributes), node_attrs) self.assertListEqual(list(g.node_labels), node_labels) def test_from_adj_mat_dense_undirected_weighted(self): edges_expected = [(0, 0, 1.0), (0, 1, 0.1), (0, 3, 0.3), (1, 3, 0.4), (2, 3, 0.9)] g = GraphDataset.from_adj_mat(self.sample_A, directed=False, weighted=True, name='Weighted') self.assertEqual(g.name, 'Weighted') self.assertSetEqual(set(g.get_edge_iter()), set(edges_expected)) def test_from_adj_mat_dense_directed_unweighted(self): edges_expected = [(0, 0, 1), (0, 1, 1), (0, 3, 1), (1, 3, 1), (2, 3, 1), (1, 0, 1), (3, 0, 1), (3, 1, 1), (3, 2, 1)] g = GraphDataset.from_adj_mat(self.sample_A, directed=True, weighted=False, name='Unweighted') self.assertEqual(g.name, 'Unweighted') self.assertSetEqual(set(g.get_edge_iter()), set(edges_expected)) def test_from_adj_mat_dense_directed_weighted(self): edges_expected = [(0, 0, 1.0), (0, 1, 0.1), (0, 3, 0.3), (1, 3, 0.4), (2, 3, 0.9), (1, 0, 0.7), (3, 0, 0.5), (3, 1, 0.6), (3, 2, 0.8)] g = GraphDataset.from_adj_mat(self.sample_A, directed=True, weighted=True, name='Weighted') self.assertEqual(g.name, 'Weighted') self.assertSetEqual(set(g.get_edge_iter()), set(edges_expected)) class TestViews(unittest.TestCase): def setUp(self): edges = [(0, 1), (0, 2), (1, 1), (1, 2), (1, 3)] self.g_undirected = GraphDataset.from_edges(n_nodes=5, edges=edges) self.g_directed = GraphDataset.from_edges(n_nodes=5, edges=edges, directed=True) def test_deg_list(self): self.assertListEqual(list(self.g_undirected.deg_list), [2, 4, 2, 1, 0]) # Out degree self.assertListEqual(list(self.g_directed.deg_list), [2, 3, 0, 0, 0]) def test_adj_list(self): self.assertSetEqual(set(self.g_undirected.adj_list[1].keys()), {0, 1, 2, 3}) self.assertSetEqual(set(self.g_undirected.adj_list[2].keys()), {0, 1}) self.assertSetEqual(set(self.g_directed.adj_list[0].keys()), {1, 2}) self.assertEqual(len(self.g_directed.adj_list[2]), 0) class TestAdjacencyMatrix(unittest.TestCase): def test_undirected(self): edges = [(0, 1, 0.1), (1, 2, 0.2), (2, 3, 0.3)] g = GraphDataset.from_edges(n_nodes=4, edges=edges, weighted=True) A = g.get_adj_matrix() A_expected = np.array([ [0.0, 0.1, 0.0, 0.0], [0.1, 0.0, 0.2, 0.0], [0.0, 0.2, 0.0, 0.3], [0.0, 0.0, 0.3, 0.0] ]) self.assertTrue(np.array_equal(A, A_expected)) def test_directed(self): edges = [(0, 1, 0.1), (1, 2, 0.2), (3, 3, 0.5)] g = GraphDataset.from_edges(n_nodes=4, edges=edges, weighted=True, directed=True) A = g.get_adj_matrix() A_expected = np.array([ [0.0, 0.1, 0.0, 0.0], [0.0, 0.0, 0.2, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.5] ]) self.assertTrue(np.array_equal(A, A_expected)) class TestLaplacianMatrix(unittest.TestCase): def setUp(self): edges = [(0, 1, 2.0), (0, 2, 1.5), (1, 2, 0.4), (1, 3, 0.2)] self.g_weighted = GraphDataset.from_edges(n_nodes=4, edges=edges, weighted=True) self.g_unweighted = GraphDataset.from_edges(n_nodes=4, edges=edges) def test_unweighted(self): L = self.g_unweighted.get_laplacian() L_sparse = self.g_unweighted.get_laplacian(sparse=True).todense() L_expected = np.array([ [ 2.0, -1.0, -1.0, 0.0], [-1.0, 3.0, -1.0, -1.0], [-1.0, -1.0, 2.0, 0.0], [ 0.0, -1.0, 0.0, 1.0] ]) self.assertTrue(np.array_equal(L, L_expected)) self.assertTrue(np.array_equal(L, L_sparse)) def test_unweighted_normalized(self): Ln = self.g_unweighted.get_laplacian(normalize=True) Ln_sparse = self.g_unweighted.get_laplacian(normalize=True, sparse=True).todense() Ln_expected = np.array([ [ 1. , -0.40824829, -0.5 , 0. ], [-0.40824829, 1. , -0.40824829, -0.57735027], [-0.5 , -0.40824829, 1. , 0. ], [ 0. , -0.57735027, 0. , 1. ] ]) self.assertTrue(np.allclose(Ln, Ln_expected)) self.assertTrue(np.allclose(Ln, Ln_sparse)) def test_weighted(self): L = self.g_weighted.get_laplacian() L_sparse = self.g_weighted.get_laplacian(sparse=True).todense() L_expected = np.array([ [ 3.5, -2.0, -1.5, 0.0], [-2.0, 2.6, -0.4, -0.2], [-1.5, -0.4, 1.9, 0.0], [ 0.0, -0.2, 0.0, 0.2] ]) self.assertTrue(np.array_equal(L, L_expected)) self.assertTrue(np.array_equal(L, L_sparse)) class TestSubgraph(unittest.TestCase): def setUp(self): # A loop graph edges = [(0, 1, 0.1, 'a'), (1, 2, 0.2, 'b'), (2, 3, 0.3, 'c'), (3, 4, 0.4, 'd'), (4, 5, 0.5, 'e'), (5, 0, 0.6, 'f')] node_labels = [11, 22, 33, 44, 55, 66] node_attributes = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6'] self.g_loop = GraphDataset.from_edges(n_nodes=6, edges=edges, weighted=True, directed=False, has_edge_data=True, node_labels=node_labels, node_attributes=node_attributes) def test_edge_removal(self): edges_to_remove = [(0, 1), (0, 2), (4, 3), (1, 0)] sg = self.g_loop.subgraph(edges_to_remove=edges_to_remove) expected_edges = [(1, 2, 0.2, 'b'), (2, 3, 0.3, 'c'), (4, 5, 0.5, 'e'), (0, 5, 0.6, 'f')] self.assertSetEqual(set(sg.get_edge_iter(data=True)), set(expected_edges)) self.assertListEqual(list(sg.deg_list), [1, 1, 2, 1, 1, 2]) def test_node_removal(self): nodes_to_remove = [1, 4, 2, 3] sg = self.g_loop.subgraph(nodes_to_remove=nodes_to_remove) expected_edges = [(0, 1, 0.6, 'f')] self.assertSetEqual(set(sg.get_edge_iter(data=True)), set(expected_edges)) expected_node_data = [(11, 'n1'), (66, 'n6')] self.assertSetEqual(set(zip(sg.node_labels, sg.node_attributes)), set(expected_node_data)) self.assertListEqual(list(sg.deg_list), [1, 1]) def test_node_keeping(self): nodes_to_keep = [2, 1] sg = self.g_loop.subgraph(nodes_to_keep=nodes_to_keep) expected_edges = [(0, 1, 0.2, 'b')] self.assertSetEqual(set(sg.get_edge_iter(data=True)), set(expected_edges)) expected_node_data = [(22, 'n2'), (33, 'n3')] self.assertSetEqual(set(zip(sg.node_labels, sg.node_attributes)), set(expected_node_data)) self.assertListEqual(list(sg.deg_list), [1, 1]) def test_node_plus_edge_removal(self): nodes_to_remove = [0, 2] edges_to_remove = [(1, 0), (2, 3), (4, 5), (5, 0), (3, 4), (0, 1)] sg = self.g_loop.subgraph(nodes_to_remove=nodes_to_remove, edges_to_remove=edges_to_remove) self.assertEqual(sg.n_edges, 0) expected_node_data = [(22, 'n2'), (44, 'n4'), (55, 'n5'), (66, 'n6')] self.assertSetEqual(set(zip(sg.node_labels, sg.node_attributes)), set(expected_node_data)) self.assertListEqual(list(sg.deg_list), [0, 0, 0, 0]) if __name__ == '__main__': unittest.main()
{'dir': 'python', 'id': '2534506', 'max_stars_count': '0', 'max_stars_repo_name': 'morriswmz/graphz', 'max_stars_repo_path': 'graphz/tests/test_graph_dataset.py', 'n_tokens_mistral': 3772, 'n_tokens_neox': 3438, 'n_words': 647}
<gh_stars>0 --- layout: post title: Do not leave any question date: 2007-09-10 11:00:49.000000000 +09:30 type: post published: true status: publish categories: - Thinking tags: [thinking] meta: posturl_add_url: 'yes' _edit_last: '1' views: '825' --- <h1></h1> <div>Remeber: do not leave any question which confuse you, or else you will be lost more when you met it again.</div>
{'dir': 'html', 'id': '434528', 'max_stars_count': '0', 'max_stars_repo_name': 'dbaeyes/dbaeyes.github.io', 'max_stars_repo_path': '_posts/2007-09-10-do-not-leave-any-question.html', 'n_tokens_mistral': 165, 'n_tokens_neox': 139, 'n_words': 52}
package lk.ijse.dep.pos.dao.custom.impl; import lk.ijse.dep.pos.dao.custom.QueryDAO; import lk.ijse.dep.pos.entity.CustomEntity; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.sql.Date; import java.util.ArrayList; import java.util.List; @Repository public class QueryDAOImpl implements QueryDAO { @PersistenceContext private EntityManager entityManager; @Override public CustomEntity getOrderInfo(int orderId) throws Exception { return null; } @Override public List<CustomEntity> getOrdersInfo(String query) throws Exception { List<Object[]> resultList = entityManager.createNativeQuery( "SELECT o.id, c.cusId , c.name, o.date, od.qty * od.unit_price FROM Customer c " + "JOIN `order` o ON c.cusId=o.customer_Id " + "JOIN orderdetail od on o.id = od.order_id " + "WHERE o.id LIKE ?1 OR " + "c.cusId LIKE ?1 OR " + "c.name LIKE ?1 OR " + "o.date LIKE ?1 GROUP BY o.id" ).setParameter(1, query).getResultList(); ArrayList<CustomEntity> list = new ArrayList<>(); for (Object[] clo : resultList) { list.add(new CustomEntity((int) clo[0], (String) clo[1], (String) clo[2], (Date) clo[3], (Double) clo[4])); } return list; } }
{'dir': 'java', 'id': '13338155', 'max_stars_count': '0', 'max_stars_repo_name': 'rivinduchamath/POS-Spring-JPA', 'max_stars_repo_path': 'src/lk/ijse/dep/pos/dao/custom/impl/QueryDAOImpl.java', 'n_tokens_mistral': 462, 'n_tokens_neox': 441, 'n_words': 110}
#ifndef CLM_H #define CLM_H #define MUS_VERSION 5 #define MUS_REVISION 14 #define MUS_DATE "19-Apr-13" /* isn't mus_env_interp backwards? */ #include "sndlib.h" #ifndef _MSC_VER #include <sys/param.h> #endif #if HAVE_COMPLEX_TRIG #include <complex.h> #endif #if(!defined(M_PI)) #define M_PI 3.14159265358979323846264338327 #define M_PI_2 (M_PI / 2.0) #endif #define MUS_DEFAULT_SAMPLING_RATE 44100.0 #define MUS_DEFAULT_FILE_BUFFER_SIZE 8192 #define MUS_DEFAULT_ARRAY_PRINT_LENGTH 8 typedef enum {MUS_NOT_SPECIAL, MUS_SIMPLE_FILTER, MUS_FULL_FILTER, MUS_OUTPUT, MUS_INPUT, MUS_DELAY_LINE} mus_clm_extended_t; typedef struct mus_any_class mus_any_class; typedef struct { struct mus_any_class *core; } mus_any; typedef enum {MUS_INTERP_NONE, MUS_INTERP_LINEAR, MUS_INTERP_SINUSOIDAL, MUS_INTERP_ALL_PASS, MUS_INTERP_LAGRANGE, MUS_INTERP_BEZIER, MUS_INTERP_HERMITE} mus_interp_t; typedef enum {MUS_RECTANGULAR_WINDOW, MUS_HANN_WINDOW, MUS_WELCH_WINDOW, MUS_PARZEN_WINDOW, MUS_BARTLETT_WINDOW, MUS_HAMMING_WINDOW, MUS_BLACKMAN2_WINDOW, MUS_BLACKMAN3_WINDOW, MUS_BLACKMAN4_WINDOW, MUS_EXPONENTIAL_WINDOW, MUS_RIEMANN_WINDOW, MUS_KAISER_WINDOW, MUS_CAUCHY_WINDOW, MUS_POISSON_WINDOW, MUS_GAUSSIAN_WINDOW, MUS_TUKEY_WINDOW, MUS_DOLPH_CHEBYSHEV_WINDOW, MUS_HANN_POISSON_WINDOW, MUS_CONNES_WINDOW, MUS_SAMARAKI_WINDOW, MUS_ULTRASPHERICAL_WINDOW, MUS_BARTLETT_HANN_WINDOW, MUS_BOHMAN_WINDOW, MUS_FLAT_TOP_WINDOW, MUS_BLACKMAN5_WINDOW, MUS_BLACKMAN6_WINDOW, MUS_BLACKMAN7_WINDOW, MUS_BLACKMAN8_WINDOW, MUS_BLACKMAN9_WINDOW, MUS_BLACKMAN10_WINDOW, MUS_RV2_WINDOW, MUS_RV3_WINDOW, MUS_RV4_WINDOW, MUS_MLT_SINE_WINDOW, MUS_PAPOULIS_WINDOW, MUS_DPSS_WINDOW, MUS_SINC_WINDOW, MUS_NUM_FFT_WINDOWS} mus_fft_window_t; typedef enum {MUS_SPECTRUM_IN_DB, MUS_SPECTRUM_NORMALIZED, MUS_SPECTRUM_RAW} mus_spectrum_t; typedef enum {MUS_CHEBYSHEV_EITHER_KIND, MUS_CHEBYSHEV_FIRST_KIND, MUS_CHEBYSHEV_SECOND_KIND} mus_polynomial_t; #define MUS_MAX_CLM_SINC_WIDTH 65536 #define MUS_MAX_CLM_SRC 65536.0 #ifdef __cplusplus extern "C" { #endif MUS_EXPORT void mus_initialize(void); MUS_EXPORT int mus_make_generator_type(void); MUS_EXPORT mus_any_class *mus_generator_class(mus_any *ptr); MUS_EXPORT mus_any_class *mus_make_generator(int type, char *name, int (*release)(mus_any *ptr), char *(*describe)(mus_any *ptr), bool (*equalp)(mus_any *gen1, mus_any *gen2)); MUS_EXPORT void mus_generator_set_release(mus_any_class *p, int (*release)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_describe(mus_any_class *p, char *(*describe)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_equalp(mus_any_class *p, bool (*equalp)(mus_any *gen1, mus_any *gen2)); MUS_EXPORT void mus_generator_set_data(mus_any_class *p, mus_float_t *(*data)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_data(mus_any_class *p, mus_float_t *(*set_data)(mus_any *ptr, mus_float_t *new_data)); MUS_EXPORT void mus_generator_set_length(mus_any_class *p, mus_long_t (*length)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_length(mus_any_class *p, mus_long_t (*set_length)(mus_any *ptr, mus_long_t new_length)); MUS_EXPORT void mus_generator_set_frequency(mus_any_class *p, mus_float_t (*frequency)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_frequency(mus_any_class *p, mus_float_t (*set_frequency)(mus_any *ptr, mus_float_t new_freq)); MUS_EXPORT void mus_generator_set_phase(mus_any_class *p, mus_float_t (*phase)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_phase(mus_any_class *p, mus_float_t (*set_phase)(mus_any *ptr, mus_float_t new_phase)); MUS_EXPORT void mus_generator_set_scaler(mus_any_class *p, mus_float_t (*scaler)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_scaler(mus_any_class *p, mus_float_t (*set_scaler)(mus_any *ptr, mus_float_t val)); MUS_EXPORT void mus_generator_set_increment(mus_any_class *p, mus_float_t (*increment)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_increment(mus_any_class *p, mus_float_t (*set_increment)(mus_any *ptr, mus_float_t val)); MUS_EXPORT void mus_generator_set_run(mus_any_class *p, mus_float_t (*run)(mus_any *gen, mus_float_t arg1, mus_float_t arg2)); MUS_EXPORT void mus_generator_set_closure(mus_any_class *p, void *(*closure)(mus_any *gen)); MUS_EXPORT void mus_generator_set_channels(mus_any_class *p, int (*channels)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_offset(mus_any_class *p, mus_float_t (*offset)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_offset(mus_any_class *p, mus_float_t (*set_offset)(mus_any *ptr, mus_float_t val)); MUS_EXPORT void mus_generator_set_width(mus_any_class *p, mus_float_t (*width)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_width(mus_any_class *p, mus_float_t (*set_width)(mus_any *ptr, mus_float_t val)); MUS_EXPORT void mus_generator_set_xcoeff(mus_any_class *p, mus_float_t (*xcoeff)(mus_any *ptr, int index)); MUS_EXPORT void mus_generator_set_set_xcoeff(mus_any_class *p, mus_float_t (*set_xcoeff)(mus_any *ptr, int index, mus_float_t val)); MUS_EXPORT void mus_generator_set_hop(mus_any_class *p, mus_long_t (*hop)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_hop(mus_any_class *p, mus_long_t (*set_hop)(mus_any *ptr, mus_long_t new_length)); MUS_EXPORT void mus_generator_set_ramp(mus_any_class *p, mus_long_t (*ramp)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_ramp(mus_any_class *p, mus_long_t (*set_ramp)(mus_any *ptr, mus_long_t new_length)); MUS_EXPORT void mus_generator_set_read_sample(mus_any_class *p, mus_float_t (*read_sample)(mus_any *ptr, mus_long_t samp, int chan)); MUS_EXPORT void mus_generator_set_write_sample(mus_any_class *p, mus_float_t (*write_sample)(mus_any *ptr, mus_long_t samp, int chan, mus_float_t data)); MUS_EXPORT void mus_generator_set_file_name(mus_any_class *p, char *(*file_name)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_end(mus_any_class *p, int (*end)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_location(mus_any_class *p, mus_long_t (*location)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_location(mus_any_class *p, mus_long_t (*set_location)(mus_any *ptr, mus_long_t loc)); MUS_EXPORT void mus_generator_set_channel(mus_any_class *p, int (*channel)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_ycoeff(mus_any_class *p, mus_float_t (*ycoeff)(mus_any *ptr, int index)); MUS_EXPORT void mus_generator_set_set_ycoeff(mus_any_class *p, mus_float_t (*set_ycoeff)(mus_any *ptr, int index, mus_float_t val)); MUS_EXPORT void mus_generator_set_xcoeffs(mus_any_class *p, mus_float_t *(*xcoeffs)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_ycoeffs(mus_any_class *p, mus_float_t *(*ycoeffs)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_reset(mus_any_class *p, void (*reset)(mus_any *ptr)); MUS_EXPORT void mus_generator_set_set_closure(mus_any_class *p, void *(*set_closure)(mus_any *gen, void *e)); MUS_EXPORT void mus_generator_set_extended_type(mus_any_class *p, mus_clm_extended_t extended_type); MUS_EXPORT void mus_generator_set_feeder(mus_any *g, mus_float_t (*feed)(void *arg, int direction)); MUS_EXPORT mus_float_t mus_radians_to_hz(mus_float_t radians); MUS_EXPORT mus_float_t mus_hz_to_radians(mus_float_t hz); MUS_EXPORT mus_float_t mus_degrees_to_radians(mus_float_t degrees); MUS_EXPORT mus_float_t mus_radians_to_degrees(mus_float_t radians); MUS_EXPORT mus_float_t mus_db_to_linear(mus_float_t x); MUS_EXPORT mus_float_t mus_linear_to_db(mus_float_t x); MUS_EXPORT mus_float_t mus_srate(void); MUS_EXPORT mus_float_t mus_set_srate(mus_float_t val); MUS_EXPORT mus_long_t mus_seconds_to_samples(mus_float_t secs); MUS_EXPORT mus_float_t mus_samples_to_seconds(mus_long_t samps); MUS_EXPORT int mus_array_print_length(void); MUS_EXPORT int mus_set_array_print_length(int val); MUS_EXPORT mus_float_t mus_float_equal_fudge_factor(void); MUS_EXPORT mus_float_t mus_set_float_equal_fudge_factor(mus_float_t val); MUS_EXPORT mus_float_t mus_ring_modulate(mus_float_t s1, mus_float_t s2); MUS_EXPORT mus_float_t mus_amplitude_modulate(mus_float_t s1, mus_float_t s2, mus_float_t s3); MUS_EXPORT mus_float_t mus_contrast_enhancement(mus_float_t sig, mus_float_t index); MUS_EXPORT mus_float_t mus_dot_product(mus_float_t *data1, mus_float_t *data2, mus_long_t size); #if HAVE_COMPLEX_TRIG MUS_EXPORT complex double mus_edot_product(complex double freq, complex double *data, mus_long_t size); #endif MUS_EXPORT void mus_clear_array(mus_float_t *arr, mus_long_t size); MUS_EXPORT bool mus_arrays_are_equal(mus_float_t *arr1, mus_float_t *arr2, mus_float_t fudge, mus_long_t len); MUS_EXPORT mus_float_t mus_polynomial(mus_float_t *coeffs, mus_float_t x, int ncoeffs); MUS_EXPORT void mus_multiply_arrays(mus_float_t *data, mus_float_t *window, mus_long_t len); MUS_EXPORT void mus_rectangular_to_polar(mus_float_t *rl, mus_float_t *im, mus_long_t size); MUS_EXPORT void mus_rectangular_to_magnitudes(mus_float_t *rl, mus_float_t *im, mus_long_t size); MUS_EXPORT void mus_polar_to_rectangular(mus_float_t *rl, mus_float_t *im, mus_long_t size); MUS_EXPORT mus_float_t mus_array_interp(mus_float_t *wave, mus_float_t phase, mus_long_t size); MUS_EXPORT double mus_bessi0(mus_float_t x); MUS_EXPORT mus_float_t mus_interpolate(mus_interp_t type, mus_float_t x, mus_float_t *table, mus_long_t table_size, mus_float_t y); MUS_EXPORT bool mus_interp_type_p(int val); MUS_EXPORT bool mus_fft_window_p(int val); MUS_EXPORT int mus_data_format_zero(int format); MUS_EXPORT bool mus_run_exists(mus_any *gen); /* -------- generic functions -------- */ MUS_EXPORT int mus_type(mus_any *ptr); MUS_EXPORT int mus_free(mus_any *ptr); MUS_EXPORT char *mus_describe(mus_any *gen); MUS_EXPORT bool mus_equalp(mus_any *g1, mus_any *g2); MUS_EXPORT mus_float_t mus_phase(mus_any *gen); MUS_EXPORT mus_float_t mus_set_phase(mus_any *gen, mus_float_t val); MUS_EXPORT mus_float_t mus_set_frequency(mus_any *gen, mus_float_t val); MUS_EXPORT mus_float_t mus_frequency(mus_any *gen); MUS_EXPORT mus_float_t mus_run(mus_any *gen, mus_float_t arg1, mus_float_t arg2); MUS_EXPORT mus_long_t mus_length(mus_any *gen); MUS_EXPORT mus_long_t mus_set_length(mus_any *gen, mus_long_t len); MUS_EXPORT mus_long_t mus_order(mus_any *gen); MUS_EXPORT mus_float_t *mus_data(mus_any *gen); MUS_EXPORT mus_float_t *mus_set_data(mus_any *gen, mus_float_t *data); MUS_EXPORT const char *mus_name(mus_any *ptr); MUS_EXPORT const char *mus_set_name(mus_any *ptr, const char *new_name); MUS_EXPORT mus_float_t mus_scaler(mus_any *gen); MUS_EXPORT mus_float_t mus_set_scaler(mus_any *gen, mus_float_t val); MUS_EXPORT mus_float_t mus_offset(mus_any *gen); MUS_EXPORT mus_float_t mus_set_offset(mus_any *gen, mus_float_t val); MUS_EXPORT mus_float_t mus_width(mus_any *gen); MUS_EXPORT mus_float_t mus_set_width(mus_any *gen, mus_float_t val); MUS_EXPORT char *mus_file_name(mus_any *ptr); MUS_EXPORT void mus_reset(mus_any *ptr); MUS_EXPORT mus_float_t *mus_xcoeffs(mus_any *ptr); MUS_EXPORT mus_float_t *mus_ycoeffs(mus_any *ptr); MUS_EXPORT mus_float_t mus_xcoeff(mus_any *ptr, int index); MUS_EXPORT mus_float_t mus_set_xcoeff(mus_any *ptr, int index, mus_float_t val); MUS_EXPORT mus_float_t mus_ycoeff(mus_any *ptr, int index); MUS_EXPORT mus_float_t mus_set_ycoeff(mus_any *ptr, int index, mus_float_t val); MUS_EXPORT mus_float_t mus_increment(mus_any *rd); MUS_EXPORT mus_float_t mus_set_increment(mus_any *rd, mus_float_t dir); MUS_EXPORT mus_long_t mus_location(mus_any *rd); MUS_EXPORT mus_long_t mus_set_location(mus_any *rd, mus_long_t loc); MUS_EXPORT int mus_channel(mus_any *rd); MUS_EXPORT int mus_channels(mus_any *ptr); MUS_EXPORT int mus_position(mus_any *ptr); /* only C, envs (snd-env.c), shares slot with mus_channels */ MUS_EXPORT int mus_interp_type(mus_any *ptr); MUS_EXPORT mus_long_t mus_ramp(mus_any *ptr); MUS_EXPORT mus_long_t mus_set_ramp(mus_any *ptr, mus_long_t val); MUS_EXPORT mus_long_t mus_hop(mus_any *ptr); MUS_EXPORT mus_long_t mus_set_hop(mus_any *ptr, mus_long_t val); MUS_EXPORT mus_float_t mus_feedforward(mus_any *gen); MUS_EXPORT mus_float_t mus_set_feedforward(mus_any *gen, mus_float_t val); MUS_EXPORT mus_float_t mus_feedback(mus_any *rd); MUS_EXPORT mus_float_t mus_set_feedback(mus_any *rd, mus_float_t dir); /* -------- generators -------- */ MUS_EXPORT mus_float_t mus_oscil(mus_any *o, mus_float_t fm, mus_float_t pm); MUS_EXPORT mus_float_t mus_oscil_unmodulated(mus_any *ptr); MUS_EXPORT mus_float_t mus_oscil_fm(mus_any *ptr, mus_float_t fm); MUS_EXPORT mus_float_t mus_oscil_pm(mus_any *ptr, mus_float_t pm); MUS_EXPORT bool mus_oscil_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_oscil(mus_float_t freq, mus_float_t phase); MUS_EXPORT bool mus_oscil_bank_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_oscil_bank(mus_any *ptr); MUS_EXPORT mus_any *mus_make_oscil_bank(int size, mus_float_t *freqs, mus_float_t *phases, mus_float_t *amps); MUS_EXPORT mus_any *mus_make_ncos(mus_float_t freq, int n); MUS_EXPORT mus_float_t mus_ncos(mus_any *ptr, mus_float_t fm); MUS_EXPORT bool mus_ncos_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_nsin(mus_float_t freq, int n); MUS_EXPORT mus_float_t mus_nsin(mus_any *ptr, mus_float_t fm); MUS_EXPORT bool mus_nsin_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_nrxysin(mus_float_t frequency, mus_float_t y_over_x, int n, mus_float_t r); MUS_EXPORT mus_float_t mus_nrxysin(mus_any *ptr, mus_float_t fm); MUS_EXPORT bool mus_nrxysin_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_nrxycos(mus_float_t frequency, mus_float_t y_over_x, int n, mus_float_t r); MUS_EXPORT mus_float_t mus_nrxycos(mus_any *ptr, mus_float_t fm); MUS_EXPORT bool mus_nrxycos_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_rxykcos(mus_float_t freq, mus_float_t phase, mus_float_t r, mus_float_t ratio); MUS_EXPORT mus_float_t mus_rxykcos(mus_any *ptr, mus_float_t fm); MUS_EXPORT bool mus_rxykcos_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_rxyksin(mus_float_t freq, mus_float_t phase, mus_float_t r, mus_float_t ratio); MUS_EXPORT mus_float_t mus_rxyksin(mus_any *ptr, mus_float_t fm); MUS_EXPORT bool mus_rxyksin_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_delay(mus_any *gen, mus_float_t input, mus_float_t pm); MUS_EXPORT mus_float_t mus_delay_unmodulated(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_float_t mus_tap(mus_any *gen, mus_float_t loc); MUS_EXPORT mus_float_t mus_tap_unmodulated(mus_any *gen); MUS_EXPORT mus_any *mus_make_delay(int size, mus_float_t *line, int line_size, mus_interp_t type); MUS_EXPORT bool mus_delay_p(mus_any *ptr); MUS_EXPORT bool mus_tap_p(mus_any *ptr); MUS_EXPORT bool mus_delay_line_p(mus_any *gen); /* added 2-Mar-03 for tap error checks */ MUS_EXPORT mus_float_t mus_delay_tick(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_float_t mus_delay_unmodulated_noz(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_float_t mus_comb(mus_any *gen, mus_float_t input, mus_float_t pm); MUS_EXPORT mus_float_t mus_comb_unmodulated(mus_any *gen, mus_float_t input); MUS_EXPORT mus_any *mus_make_comb(mus_float_t scaler, int size, mus_float_t *line, int line_size, mus_interp_t type); MUS_EXPORT bool mus_comb_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_comb_unmodulated_noz(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_float_t mus_comb_bank(mus_any *bank, mus_float_t inval); MUS_EXPORT mus_any *mus_make_comb_bank(int size, mus_any **combs); MUS_EXPORT bool mus_comb_bank_p(mus_any *g); MUS_EXPORT mus_float_t mus_notch(mus_any *gen, mus_float_t input, mus_float_t pm); MUS_EXPORT mus_float_t mus_notch_unmodulated(mus_any *gen, mus_float_t input); MUS_EXPORT mus_any *mus_make_notch(mus_float_t scaler, int size, mus_float_t *line, int line_size, mus_interp_t type); MUS_EXPORT bool mus_notch_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_notch_unmodulated_noz(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_float_t mus_all_pass(mus_any *gen, mus_float_t input, mus_float_t pm); MUS_EXPORT mus_float_t mus_all_pass_unmodulated(mus_any *gen, mus_float_t input); MUS_EXPORT mus_any *mus_make_all_pass(mus_float_t backward, mus_float_t forward, int size, mus_float_t *line, int line_size, mus_interp_t type); MUS_EXPORT bool mus_all_pass_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_all_pass_unmodulated_noz(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_float_t mus_all_pass_bank(mus_any *bank, mus_float_t inval); MUS_EXPORT mus_any *mus_make_all_pass_bank(int size, mus_any **combs); MUS_EXPORT bool mus_all_pass_bank_p(mus_any *g); MUS_EXPORT mus_any *mus_make_moving_average(int size, mus_float_t *line); MUS_EXPORT bool mus_moving_average_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_moving_average(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_any *mus_make_moving_max(int size, mus_float_t *line); MUS_EXPORT bool mus_moving_max_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_moving_max(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_float_t mus_table_lookup(mus_any *gen, mus_float_t fm); MUS_EXPORT mus_float_t mus_table_lookup_unmodulated(mus_any *gen); MUS_EXPORT mus_any *mus_make_table_lookup(mus_float_t freq, mus_float_t phase, mus_float_t *wave, mus_long_t wave_size, mus_interp_t type); MUS_EXPORT bool mus_table_lookup_p(mus_any *ptr); MUS_EXPORT mus_float_t *mus_partials_to_wave(mus_float_t *partial_data, int partials, mus_float_t *table, mus_long_t table_size, bool normalize); MUS_EXPORT mus_float_t *mus_phase_partials_to_wave(mus_float_t *partial_data, int partials, mus_float_t *table, mus_long_t table_size, bool normalize); MUS_EXPORT mus_float_t mus_sawtooth_wave(mus_any *gen, mus_float_t fm); MUS_EXPORT mus_any *mus_make_sawtooth_wave(mus_float_t freq, mus_float_t amp, mus_float_t phase); MUS_EXPORT bool mus_sawtooth_wave_p(mus_any *gen); MUS_EXPORT mus_float_t mus_square_wave(mus_any *gen, mus_float_t fm); MUS_EXPORT mus_any *mus_make_square_wave(mus_float_t freq, mus_float_t amp, mus_float_t phase); MUS_EXPORT bool mus_square_wave_p(mus_any *gen); MUS_EXPORT mus_float_t mus_triangle_wave(mus_any *gen, mus_float_t fm); MUS_EXPORT mus_any *mus_make_triangle_wave(mus_float_t freq, mus_float_t amp, mus_float_t phase); MUS_EXPORT bool mus_triangle_wave_p(mus_any *gen); MUS_EXPORT mus_float_t mus_triangle_wave_unmodulated(mus_any *ptr); MUS_EXPORT mus_float_t mus_pulse_train(mus_any *gen, mus_float_t fm); MUS_EXPORT mus_any *mus_make_pulse_train(mus_float_t freq, mus_float_t amp, mus_float_t phase); MUS_EXPORT bool mus_pulse_train_p(mus_any *gen); MUS_EXPORT mus_float_t mus_pulse_train_unmodulated(mus_any *ptr); MUS_EXPORT void mus_set_rand_seed(unsigned long seed); MUS_EXPORT unsigned long mus_rand_seed(void); MUS_EXPORT mus_float_t mus_random(mus_float_t amp); MUS_EXPORT mus_float_t mus_frandom(mus_float_t amp); MUS_EXPORT int mus_irandom(int amp); MUS_EXPORT mus_float_t mus_rand(mus_any *gen, mus_float_t fm); MUS_EXPORT mus_any *mus_make_rand(mus_float_t freq, mus_float_t base); MUS_EXPORT bool mus_rand_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_rand_with_distribution(mus_float_t freq, mus_float_t base, mus_float_t *distribution, int distribution_size); MUS_EXPORT mus_float_t mus_rand_interp(mus_any *gen, mus_float_t fm); MUS_EXPORT mus_any *mus_make_rand_interp(mus_float_t freq, mus_float_t base); MUS_EXPORT bool mus_rand_interp_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_rand_interp_with_distribution(mus_float_t freq, mus_float_t base, mus_float_t *distribution, int distribution_size); MUS_EXPORT mus_float_t mus_rand_interp_unmodulated(mus_any *ptr); MUS_EXPORT mus_float_t mus_rand_unmodulated(mus_any *ptr); MUS_EXPORT mus_float_t mus_asymmetric_fm(mus_any *gen, mus_float_t index, mus_float_t fm); MUS_EXPORT mus_float_t mus_asymmetric_fm_unmodulated(mus_any *gen, mus_float_t index); MUS_EXPORT mus_any *mus_make_asymmetric_fm(mus_float_t freq, mus_float_t phase, mus_float_t r, mus_float_t ratio); MUS_EXPORT bool mus_asymmetric_fm_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_one_zero(mus_any *gen, mus_float_t input); MUS_EXPORT mus_any *mus_make_one_zero(mus_float_t a0, mus_float_t a1); MUS_EXPORT bool mus_one_zero_p(mus_any *gen); MUS_EXPORT mus_float_t mus_one_pole(mus_any *gen, mus_float_t input); MUS_EXPORT mus_any *mus_make_one_pole(mus_float_t a0, mus_float_t b1); MUS_EXPORT bool mus_one_pole_p(mus_any *gen); MUS_EXPORT mus_float_t mus_two_zero(mus_any *gen, mus_float_t input); MUS_EXPORT mus_any *mus_make_two_zero(mus_float_t a0, mus_float_t a1, mus_float_t a2); MUS_EXPORT bool mus_two_zero_p(mus_any *gen); MUS_EXPORT mus_any *mus_make_two_zero_from_frequency_and_radius(mus_float_t frequency, mus_float_t radius); MUS_EXPORT mus_float_t mus_two_pole(mus_any *gen, mus_float_t input); MUS_EXPORT mus_any *mus_make_two_pole(mus_float_t a0, mus_float_t b1, mus_float_t b2); MUS_EXPORT bool mus_two_pole_p(mus_any *gen); MUS_EXPORT mus_any *mus_make_two_pole_from_frequency_and_radius(mus_float_t frequency, mus_float_t radius); MUS_EXPORT mus_float_t mus_one_pole_all_pass(mus_any *f, mus_float_t input); MUS_EXPORT mus_any *mus_make_one_pole_all_pass(int size, mus_float_t coeff); MUS_EXPORT bool mus_one_pole_all_pass_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_formant(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_any *mus_make_formant(mus_float_t frequency, mus_float_t radius); MUS_EXPORT bool mus_formant_p(mus_any *ptr); MUS_EXPORT void mus_set_formant_radius_and_frequency(mus_any *ptr, mus_float_t radius, mus_float_t frequency); MUS_EXPORT mus_float_t mus_formant_with_frequency(mus_any *ptr, mus_float_t input, mus_float_t freq_in_radians); MUS_EXPORT mus_float_t mus_formant_bank(mus_any *bank, mus_float_t inval); MUS_EXPORT mus_float_t mus_formant_bank_with_inputs(mus_any *bank, mus_float_t *inval); MUS_EXPORT mus_any *mus_make_formant_bank(int size, mus_any **formants, mus_float_t *amps); MUS_EXPORT bool mus_formant_bank_p(mus_any *g); MUS_EXPORT mus_float_t mus_firmant(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_any *mus_make_firmant(mus_float_t frequency, mus_float_t radius); MUS_EXPORT bool mus_firmant_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_firmant_with_frequency(mus_any *ptr, mus_float_t input, mus_float_t freq_in_radians); MUS_EXPORT mus_float_t mus_filter(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_any *mus_make_filter(int order, mus_float_t *xcoeffs, mus_float_t *ycoeffs, mus_float_t *state); MUS_EXPORT bool mus_filter_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_fir_filter(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_any *mus_make_fir_filter(int order, mus_float_t *xcoeffs, mus_float_t *state); MUS_EXPORT bool mus_fir_filter_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_iir_filter(mus_any *ptr, mus_float_t input); MUS_EXPORT mus_any *mus_make_iir_filter(int order, mus_float_t *ycoeffs, mus_float_t *state); MUS_EXPORT bool mus_iir_filter_p(mus_any *ptr); MUS_EXPORT mus_float_t *mus_make_fir_coeffs(int order, mus_float_t *env, mus_float_t *aa); MUS_EXPORT mus_float_t *mus_filter_set_xcoeffs(mus_any *ptr, mus_float_t *new_data); MUS_EXPORT mus_float_t *mus_filter_set_ycoeffs(mus_any *ptr, mus_float_t *new_data); MUS_EXPORT int mus_filter_set_order(mus_any *ptr, int order); MUS_EXPORT mus_float_t mus_filtered_comb(mus_any *ptr, mus_float_t input, mus_float_t pm); MUS_EXPORT mus_float_t mus_filtered_comb_unmodulated(mus_any *ptr, mus_float_t input); MUS_EXPORT bool mus_filtered_comb_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_filtered_comb(mus_float_t scaler, int size, mus_float_t *line, int line_size, mus_interp_t type, mus_any *filt); MUS_EXPORT mus_float_t mus_filtered_comb_bank(mus_any *bank, mus_float_t inval); MUS_EXPORT mus_any *mus_make_filtered_comb_bank(int size, mus_any **combs); MUS_EXPORT bool mus_filtered_comb_bank_p(mus_any *g); MUS_EXPORT mus_float_t mus_wave_train(mus_any *gen, mus_float_t fm); MUS_EXPORT mus_float_t mus_wave_train_unmodulated(mus_any *gen); MUS_EXPORT mus_any *mus_make_wave_train(mus_float_t freq, mus_float_t phase, mus_float_t *wave, mus_long_t wsize, mus_interp_t type); MUS_EXPORT bool mus_wave_train_p(mus_any *gen); MUS_EXPORT mus_float_t *mus_partials_to_polynomial(int npartials, mus_float_t *partials, mus_polynomial_t kind); MUS_EXPORT mus_float_t *mus_normalize_partials(int num_partials, mus_float_t *partials); MUS_EXPORT mus_any *mus_make_polyshape(mus_float_t frequency, mus_float_t phase, mus_float_t *coeffs, int size, int cheby_choice); MUS_EXPORT mus_float_t mus_polyshape(mus_any *ptr, mus_float_t index, mus_float_t fm); MUS_EXPORT mus_float_t mus_polyshape_unmodulated(mus_any *ptr, mus_float_t index); #define mus_polyshape_no_input(Obj) mus_polyshape(Obj, 1.0, 0.0) MUS_EXPORT bool mus_polyshape_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_polywave(mus_float_t frequency, mus_float_t *coeffs, int n, int cheby_choice); MUS_EXPORT bool mus_polywave_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_polywave_unmodulated(mus_any *ptr); MUS_EXPORT mus_float_t mus_polywave(mus_any *ptr, mus_float_t fm); MUS_EXPORT mus_float_t mus_chebyshev_t_sum(mus_float_t x, int n, mus_float_t *tn); MUS_EXPORT mus_float_t mus_chebyshev_u_sum(mus_float_t x, int n, mus_float_t *un); MUS_EXPORT mus_float_t mus_chebyshev_tu_sum(mus_float_t x, int n, mus_float_t *tn, mus_float_t *un); MUS_EXPORT mus_float_t mus_env(mus_any *ptr); MUS_EXPORT mus_any *mus_make_env(mus_float_t *brkpts, int npts, double scaler, double offset, double base, double duration, mus_long_t end, mus_float_t *odata); MUS_EXPORT bool mus_env_p(mus_any *ptr); MUS_EXPORT double mus_env_interp(double x, mus_any *env); MUS_EXPORT mus_long_t *mus_env_passes(mus_any *gen); /* for Snd */ MUS_EXPORT double *mus_env_rates(mus_any *gen); /* for Snd */ MUS_EXPORT double mus_env_offset(mus_any *gen); /* for Snd */ MUS_EXPORT double mus_env_scaler(mus_any *gen); /* for Snd */ MUS_EXPORT double mus_env_initial_power(mus_any *gen); /* for Snd */ MUS_EXPORT int mus_env_breakpoints(mus_any *gen); /* for Snd */ MUS_EXPORT mus_float_t mus_env_any(mus_any *e, mus_float_t (*connect_points)(mus_float_t val)); #define mus_make_env_with_length(Brkpts, Pts, Scaler, Offset, Base, Length) mus_make_env(Brkpts, Pts, Scaler, Offset, Base, 0.0, (Length) - 1, NULL) MUS_EXPORT mus_any *mus_make_pulsed_env(mus_any *e, mus_any *p); MUS_EXPORT bool mus_pulsed_env_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_pulsed_env(mus_any *pl, mus_float_t inval); MUS_EXPORT mus_float_t mus_pulsed_env_unmodulated(mus_any *pl); MUS_EXPORT bool mus_frame_p(mus_any *ptr); MUS_EXPORT bool mus_frame_or_mixer_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_empty_frame(int chans); MUS_EXPORT mus_any *mus_make_frame(int chans, ...); MUS_EXPORT mus_any *mus_frame_add(mus_any *f1, mus_any *f2, mus_any *res); MUS_EXPORT mus_any *mus_frame_multiply(mus_any *f1, mus_any *f2, mus_any *res); MUS_EXPORT mus_any *mus_frame_scale(mus_any *uf1, mus_float_t scl, mus_any *ures); MUS_EXPORT mus_any *mus_frame_offset(mus_any *uf1, mus_float_t offset, mus_any *ures); MUS_EXPORT mus_float_t mus_frame_ref(mus_any *f, int chan); MUS_EXPORT mus_float_t mus_frame_set(mus_any *f, int chan, mus_float_t val); MUS_EXPORT mus_any *mus_frame_copy(mus_any *uf); MUS_EXPORT mus_float_t mus_frame_fill(mus_any *uf, mus_float_t val); MUS_EXPORT bool mus_mixer_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_empty_mixer(int chans); MUS_EXPORT mus_any *mus_make_identity_mixer(int chans); MUS_EXPORT mus_any *mus_make_mixer(int chans, ...); MUS_EXPORT mus_float_t mus_mixer_ref(mus_any *f, int in, int out); MUS_EXPORT mus_float_t mus_mixer_set(mus_any *f, int in, int out, mus_float_t val); MUS_EXPORT mus_any *mus_frame_to_frame(mus_any *f, mus_any *in, mus_any *out); MUS_EXPORT mus_any *mus_sample_to_frame(mus_any *f, mus_float_t in, mus_any *out); MUS_EXPORT mus_float_t mus_frame_to_sample(mus_any *f, mus_any *in); MUS_EXPORT mus_any *mus_mixer_multiply(mus_any *f1, mus_any *f2, mus_any *res); MUS_EXPORT mus_any *mus_mixer_add(mus_any *f1, mus_any *f2, mus_any *res); MUS_EXPORT mus_any *mus_mixer_scale(mus_any *uf1, mus_float_t scaler, mus_any *ures); MUS_EXPORT mus_any *mus_mixer_offset(mus_any *uf1, mus_float_t offset, mus_any *ures); MUS_EXPORT mus_any *mus_make_scalar_mixer(int chans, mus_float_t scalar); MUS_EXPORT mus_any *mus_mixer_copy(mus_any *uf); MUS_EXPORT mus_float_t mus_mixer_fill(mus_any *uf, mus_float_t val); MUS_EXPORT bool mus_file_to_sample_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_file_to_sample(const char *filename); MUS_EXPORT mus_any *mus_make_file_to_sample_with_buffer_size(const char *filename, mus_long_t buffer_size); MUS_EXPORT mus_float_t mus_file_to_sample(mus_any *ptr, mus_long_t samp, int chan); MUS_EXPORT mus_float_t mus_in_any_from_file(mus_any *ptr, mus_long_t samp, int chan); MUS_EXPORT mus_float_t mus_readin(mus_any *rd); MUS_EXPORT mus_any *mus_make_readin_with_buffer_size(const char *filename, int chan, mus_long_t start, int direction, mus_long_t buffer_size); #define mus_make_readin(Filename, Chan, Start, Direction) mus_make_readin_with_buffer_size(Filename, Chan, Start, Direction, mus_file_buffer_size()) MUS_EXPORT bool mus_readin_p(mus_any *ptr); MUS_EXPORT bool mus_output_p(mus_any *ptr); MUS_EXPORT bool mus_input_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_in_any(mus_long_t frame, int chan, mus_any *IO); MUS_EXPORT bool mus_in_any_is_safe(mus_any *IO); MUS_EXPORT mus_any *mus_make_file_to_frame(const char *filename); MUS_EXPORT bool mus_file_to_frame_p(mus_any *ptr); MUS_EXPORT mus_any *mus_file_to_frame(mus_any *ptr, mus_long_t samp, mus_any *f); MUS_EXPORT mus_any *mus_make_file_to_frame_with_buffer_size(const char *filename, mus_long_t buffer_size); MUS_EXPORT bool mus_sample_to_file_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_sample_to_file_with_comment(const char *filename, int out_chans, int out_format, int out_type, const char *comment); #define mus_make_sample_to_file(Filename, Chans, OutFormat, OutType) mus_make_sample_to_file_with_comment(Filename, Chans, OutFormat, OutType, NULL) MUS_EXPORT mus_float_t mus_sample_to_file(mus_any *ptr, mus_long_t samp, int chan, mus_float_t val); MUS_EXPORT mus_any *mus_continue_sample_to_file(const char *filename); MUS_EXPORT int mus_close_file(mus_any *ptr); MUS_EXPORT mus_any *mus_sample_to_file_add(mus_any *out1, mus_any *out2); MUS_EXPORT mus_float_t mus_out_any(mus_long_t frame, mus_float_t val, int chan, mus_any *IO); MUS_EXPORT mus_float_t mus_safe_out_any_to_file(mus_long_t samp, mus_float_t val, int chan, mus_any *IO); MUS_EXPORT bool mus_out_any_is_safe(mus_any *IO); MUS_EXPORT mus_float_t mus_out_any_to_file(mus_any *ptr, mus_long_t samp, int chan, mus_float_t val); MUS_EXPORT mus_long_t mus_out_any_data_start(mus_any *IO); MUS_EXPORT mus_long_t mus_out_any_data_end(mus_any *IO); MUS_EXPORT int mus_out_any_channels(mus_any *IO); MUS_EXPORT mus_float_t **mus_out_any_buffers(mus_any *IO); MUS_EXPORT void mus_out_any_set_end(mus_any *IO, mus_long_t end); MUS_EXPORT bool mus_frame_to_file_p(mus_any *ptr); MUS_EXPORT mus_any *mus_frame_to_file(mus_any *ptr, mus_long_t samp, mus_any *data); MUS_EXPORT mus_any *mus_make_frame_to_file_with_comment(const char *filename, int chans, int out_format, int out_type, const char *comment); #define mus_make_frame_to_file(Filename, Chans, OutFormat, OutType) mus_make_frame_to_file_with_comment(Filename, Chans, OutFormat, OutType, NULL) MUS_EXPORT mus_any *mus_continue_frame_to_file(const char *filename); MUS_EXPORT void mus_locsig(mus_any *ptr, mus_long_t loc, mus_float_t val); MUS_EXPORT mus_any *mus_make_locsig(mus_float_t degree, mus_float_t distance, mus_float_t reverb, int chans, mus_any *output, int rev_chans, mus_any *revput, mus_interp_t type); MUS_EXPORT bool mus_locsig_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_locsig_ref(mus_any *ptr, int chan); MUS_EXPORT mus_float_t mus_locsig_set(mus_any *ptr, int chan, mus_float_t val); MUS_EXPORT mus_float_t mus_locsig_reverb_ref(mus_any *ptr, int chan); MUS_EXPORT mus_float_t mus_locsig_reverb_set(mus_any *ptr, int chan, mus_float_t val); MUS_EXPORT void mus_move_locsig(mus_any *ptr, mus_float_t degree, mus_float_t distance); MUS_EXPORT mus_any *mus_locsig_outf(mus_any *ptr); MUS_EXPORT mus_any *mus_locsig_revf(mus_any *ptr); MUS_EXPORT void *mus_locsig_closure(mus_any *ptr); MUS_EXPORT void mus_locsig_set_detour(mus_any *ptr, void (*detour)(mus_any *ptr, mus_long_t val)); MUS_EXPORT bool mus_locsig_output_is_safe(mus_any *ptr); MUS_EXPORT int mus_locsig_channels(mus_any *ptr); MUS_EXPORT int mus_locsig_reverb_channels(mus_any *ptr); MUS_EXPORT mus_any *mus_locsig_out_writer(mus_any *ptr); MUS_EXPORT mus_any *mus_locsig_rev_writer(mus_any *ptr); MUS_EXPORT bool mus_move_sound_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_move_sound(mus_any *ptr, mus_long_t loc, mus_float_t val); MUS_EXPORT mus_any *mus_make_move_sound(mus_long_t start, mus_long_t end, int out_channels, int rev_channels, mus_any *doppler_delay, mus_any *doppler_env, mus_any *rev_env, mus_any **out_delays, mus_any **out_envs, mus_any **rev_envs, int *out_map, mus_any *output, mus_any *revput, bool free_arrays, bool free_gens); MUS_EXPORT mus_any *mus_move_sound_outf(mus_any *ptr); MUS_EXPORT mus_any *mus_move_sound_revf(mus_any *ptr); MUS_EXPORT void *mus_move_sound_closure(mus_any *ptr); MUS_EXPORT void mus_move_sound_set_detour(mus_any *ptr, void (*detour)(mus_any *ptr, mus_long_t val)); MUS_EXPORT mus_any *mus_make_src(mus_float_t (*input)(void *arg, int direction), mus_float_t srate, int width, void *closure); MUS_EXPORT mus_any *mus_make_src_with_init(mus_float_t (*input)(void *arg, int direction), mus_float_t srate, int width, void *closure, void (*init)(void *p, mus_any *g)); MUS_EXPORT mus_float_t mus_src(mus_any *srptr, mus_float_t sr_change, mus_float_t (*input)(void *arg, int direction)); MUS_EXPORT bool mus_src_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_src_20(mus_any *srptr, mus_float_t (*input)(void *arg, int direction)); MUS_EXPORT mus_float_t mus_src_05(mus_any *srptr, mus_float_t (*input)(void *arg, int direction)); MUS_EXPORT bool mus_convolve_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_convolve(mus_any *ptr, mus_float_t (*input)(void *arg, int direction)); MUS_EXPORT mus_any *mus_make_convolve(mus_float_t (*input)(void *arg, int direction), mus_float_t *filter, mus_long_t fftsize, mus_long_t filtersize, void *closure); MUS_EXPORT mus_float_t *mus_spectrum(mus_float_t *rdat, mus_float_t *idat, mus_float_t *window, mus_long_t n, mus_spectrum_t type); MUS_EXPORT void mus_fft(mus_float_t *rl, mus_float_t *im, mus_long_t n, int is); MUS_EXPORT mus_float_t *mus_make_fft_window(mus_fft_window_t type, mus_long_t size, mus_float_t beta); MUS_EXPORT mus_float_t *mus_make_fft_window_with_window(mus_fft_window_t type, mus_long_t size, mus_float_t beta, mus_float_t mu, mus_float_t *window); MUS_EXPORT const char *mus_fft_window_name(mus_fft_window_t win); MUS_EXPORT const char **mus_fft_window_names(void); MUS_EXPORT mus_float_t *mus_autocorrelate(mus_float_t *data, mus_long_t n); MUS_EXPORT mus_float_t *mus_correlate(mus_float_t *data1, mus_float_t *data2, mus_long_t n); MUS_EXPORT mus_float_t *mus_convolution(mus_float_t *rl1, mus_float_t *rl2, mus_long_t n); MUS_EXPORT void mus_convolve_files(const char *file1, const char *file2, mus_float_t maxamp, const char *output_file); MUS_EXPORT mus_float_t *mus_cepstrum(mus_float_t *data, mus_long_t n); MUS_EXPORT bool mus_granulate_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_granulate(mus_any *ptr, mus_float_t (*input)(void *arg, int direction)); MUS_EXPORT mus_float_t mus_granulate_with_editor(mus_any *ptr, mus_float_t (*input)(void *arg, int direction), int (*edit)(void *closure)); MUS_EXPORT mus_any *mus_make_granulate(mus_float_t (*input)(void *arg, int direction), mus_float_t expansion, mus_float_t length, mus_float_t scaler, mus_float_t hop, mus_float_t ramp, mus_float_t jitter, int max_size, int (*edit)(void *closure), void *closure); MUS_EXPORT int mus_granulate_grain_max_length(mus_any *ptr); MUS_EXPORT void mus_granulate_set_edit_function(mus_any *ptr, int (*edit)(void *closure)); MUS_EXPORT mus_long_t mus_set_file_buffer_size(mus_long_t size); MUS_EXPORT mus_long_t mus_file_buffer_size(void); MUS_EXPORT void mus_mix(const char *outfile, const char *infile, mus_long_t out_start, mus_long_t out_samps, mus_long_t in_start, mus_any *mx, mus_any ***envs); MUS_EXPORT void mus_mix_with_reader_and_writer(mus_any *outf, mus_any *inf, mus_long_t out_start, mus_long_t out_frames, mus_long_t in_start, mus_any *umx, mus_any ***envs); MUS_EXPORT mus_float_t mus_apply(mus_any *gen, mus_float_t f1, mus_float_t f2); MUS_EXPORT bool mus_phase_vocoder_p(mus_any *ptr); MUS_EXPORT mus_any *mus_make_phase_vocoder(mus_float_t (*input)(void *arg, int direction), int fftsize, int overlap, int interp, mus_float_t pitch, bool (*analyze)(void *arg, mus_float_t (*input)(void *arg1, int direction)), int (*edit)(void *arg), /* return value is ignored (int return type is intended to be consistent with granulate) */ mus_float_t (*synthesize)(void *arg), void *closure); MUS_EXPORT mus_float_t mus_phase_vocoder(mus_any *ptr, mus_float_t (*input)(void *arg, int direction)); MUS_EXPORT mus_float_t mus_phase_vocoder_with_editors(mus_any *ptr, mus_float_t (*input)(void *arg, int direction), bool (*analyze)(void *arg, mus_float_t (*input)(void *arg1, int direction)), int (*edit)(void *arg), mus_float_t (*synthesize)(void *arg)); MUS_EXPORT mus_float_t *mus_phase_vocoder_amp_increments(mus_any *ptr); MUS_EXPORT mus_float_t *mus_phase_vocoder_amps(mus_any *ptr); MUS_EXPORT mus_float_t *mus_phase_vocoder_freqs(mus_any *ptr); MUS_EXPORT mus_float_t *mus_phase_vocoder_phases(mus_any *ptr); MUS_EXPORT mus_float_t *mus_phase_vocoder_phase_increments(mus_any *ptr); MUS_EXPORT mus_any *mus_make_ssb_am(mus_float_t freq, int order); MUS_EXPORT bool mus_ssb_am_p(mus_any *ptr); MUS_EXPORT mus_float_t mus_ssb_am_unmodulated(mus_any *ptr, mus_float_t insig); MUS_EXPORT mus_float_t mus_ssb_am(mus_any *ptr, mus_float_t insig, mus_float_t fm); MUS_EXPORT void mus_clear_sinc_tables(void); MUS_EXPORT void *mus_environ(mus_any *gen); MUS_EXPORT void *mus_set_environ(mus_any *gen, void *e); /* used only in run.lisp */ MUS_EXPORT mus_any *mus_make_frame_with_data(int chans, mus_float_t *data); MUS_EXPORT mus_any *mus_make_mixer_with_data(int chans, mus_float_t *data); #ifdef __cplusplus } #endif #endif /* Change log. * * 19-Apr: rxyk!cos and rxyk!sin from generators.scm. * 11-Apr: mus_tap_p as a better name for mus_delay_line_p. * 27-Mar: comb-bank, all-pass-bank, filtered-comb-bank, pulsed-env, oscil-bank. * 21-Mar: one-pole-all-pass generator. * 14-Mar: formant-bank generator. * removed mus_delay_tick_noz. * 4-Mar: moving_max generator. * removed the unstable filter check in make_two_pole. * 21-Jan-13: changed mus_formant_bank parameters. * -------- * 22-Dec: removed all the safety settings. * 15-Nov: removed mus_env_t, mus_env_type, and other recently deprecated stuff. * 15-Jul: more changes for clm2xen. * 4-July-12: moved various struct definitions to clm.c * added accessors for mus_any_class etc. * -------- * 1-Sep: mus_type. * 20-Aug: changed type of mus_locsig to void, added mus_locsig_function_reset. * removed function-as-output-location from locsig et al. * 14-Jul-11: removed pthread stuff. * -------- * 7-Mar-10: protect in-any and out-any from sample numbers less than 0. * -------- * 14-Oct: sine-summation, sum-of-sines, sum-of-cosines removed. * 28-Aug: changed some fft-related sizes from int to mus_long_t. * 17-Aug: mus_frame|mixer_copy|fill. * 27-Jul: mus_float_t for Float, and mus_long_t for off_t. * 15-Jun: mus_rectangular_to_magnitudes (polar, but ignore phases). * 11-Jun: mus_cepstrum. * 11-May: MUS_ENV_LINEAR and friends, also mus_env_linear|exponential. * mus_frame_to_frame_mono|stereo. * 12-Mar: sinc, papoulis and dpss (slepian windows). * 1-Jan-09: added MUS_EXPORT. * -------- * 11-Dec: deprecated the sine-summation, sum-of-cosines, and sum-of-sines generators. * 30-Oct: mus_sample_to_file_add. * mus_describe once again allocates a fresh output string. * finally removed sine-bank. * 9-Oct: various thread-related internal changes. * 14-Jul: mus_data_format_zero. * 12-Jul: mus_interp_type_p and mus_fft_window_p for C++'s benefit. * 1-July: mus-safety and various ints changed to mus_long_t. * 20-Jun: support for pthreads. * 16-Jun: changed init_mus_module to mus_initialize. * 30-May: changed polyshape to use cos and added cheby_choice arg to mus_make_polyshape. * 27-May: mus_waveshape retired -- generators.scm has a wrapper for it. * clm_free, clm_realloc etc for rt work. * mus_chebyshev_tu_sum. * 25-May: mus_polywave algorithm changed. * 17-May: mus_normalize_partials. * 12-Apr: added choice arg to mus_make_polywave. * 8-Apr: polywave uses sine-bank if highest harmonic out of Chebyshev range. * 1-Mar: mus_set_name. * 26-Feb: removed mus_cosines (use mus_length) * 24-Feb: removed mus_make_env_with_start, added mus_make_env_with_length * 20-Feb: clm 4: * polywave for polyshape and waveshape. * mus_formant_with_frequency. * firmant generator. * removed mus_formant_radius and mus_set_formant_radius. * removed "gain" arg from mus_make_formant. * reversed the order of the arguments to mus_make_formant. * fixed long-standing bug in gain calculation in mus_formant. * mus_env_any for arbitrary connecting functions. * 15-Feb: nrxysin and nrxycos for sine-summation. * 12-Feb: nsin for sum_of_sines, ncos for sum_of_cosines. * 4-Feb: clm_default_frequency (clm2xen) and *clm-default-frequency* (ws.scm). * 7-Jan-08: :dur replaced by :length in make-env. * -------- * 19-Oct: all *_0 *_1 *_2 names now use _fm|_pm|_unmodulated|_no_input. * 17-Oct: replace some method macros with functions (def-clm-struct local methods need true names). * 15-Oct: mus_oscil_1 -> _fm, _2->_pm. * mus_phase_vocoder_outctr accessors changed to use mus_location. * 11-Oct: changed default srate to 44100. * 5-Oct: mus_oscil_2. * 6-Sep: changed asymmetric-fm to use cos(sin) and added amplitude normalization. * 6-Aug: mus_autocorrelate, mus_correlate. * 3-Aug: blackman5..10 and Rife-Vincent (RV2..4 fft), mlt-sine windows. * 16-July: removed start arg from mus_make_env (see mus_make_env_with_start). * 5-July: changed some mus_float_ts to doubles in env funcs. * exp envs now use repeated multiplies rather than direct exp call. * 19-June: mus-increment on gens with a notion of frequency (phase increment); * to make room for this, asymmetric-fm ratio and sine-summation b moved to mus-offset. * 22-Feb: mus_big_fft and mus_spectrum_t. * 21-Feb: mus_fft_window_name. * 14-Feb-07: three more fft window choices. * -------- * 27-Nov: move-sound array access parallel to locsig. * 22-Nov: had to add non-backwards-compatible reverb chans arg to mus_make_locsig. * 21-Nov: mus_float_equal_fudge_factor, mus_arrays_are_equal. * 30-July: renamed average to moving_average. * 28-July: renamed make_ppolar and make_zpolar to make_two_pole|zero_from_radius_and_frequency. * added mus_scaler and mus_frequency methods for two_pole and two_zero. * 21-July: removed mus_wrapper field -- old way can't work since we need the original XEN object. * 3-July: mus_move_sound (dlocsig) generator. * changed return type of mus_locsig to float. * 28-June: mus_filtered_comb generator. * 8-May: mus_apply now takes 3 args: gen, two doubles (rather than bug-prone varargs). * 1-Mar-06: granulate now has a local random number seed (settable via the mus-location method). * -------- * 20-Dec: samaraki and ultraspherical windows. * this required a non-backwards-compatible additional argument in mus_make_fft_window_with_window. * 1-Nov: mus_filter_set_x|ycoeffs, mus_filter_set_order (needed by Snd). * 1-May: mus-scaler|feedback ok with delay and average. * 18-Apr: mus_set_environ. * 11-Apr: mus_mixer|frame_offset, mus_frame_scale (for higher level generic functions). * 23-Mar: frame_to_frame arg interpretation changed. * 21-Mar: mus_make_readin|file_to_sample|file_to_frame_with_buffer_size. * 16-Mar: polyshape generator (waveshaper as polynomial + oscil) * mus_chebyshev_first|second_kind. * mus_partials_to_waveshape no longer normalizes the partials. * 18-Feb: mus_interpolate. * 14-Feb: deprecated mus_restart_env and mus_clear_filter_state. * 7-Feb-05: mus_reset method, replaces mus_restart_env and mus_clear_filter_state. * -------- * 20-Dec: changed "jitter" handling if hop < .05 in granulate. * 15-Dec: mus_generator? for type checks (clm2xen). * 11-Sep: removed buffer generator. * 6-Sep: removed mus_oscil_bank, mus_bank. * 24-Aug: removed mus_inspect method -- overlaps mus_describe and is useless given gdb capabilities. * 27-July: mus_granulate_with_editor and mus_phase_vocoder_with_editors. * 21-July: edit-func as run-time arg to granulate (for CL/clm compatibility) * 19-July: clm 3: * deprecated mus_ina|b, mus-outa|b|c|d. * mus_make_frame_to_file_with_comment, mus_mixer_scale, mus_make_frame|mixer_with_data. * mus_make_scalar_mixer, mus_mixer_add, mus_continue_frame_to_file. * changed pv_* to phase_vocoder_* * 28-June: ssb_am + added fm arg (ssb_am_1 is the previous form). * 21-June: wrapper method. * 14-June: ssb_am generator. * deprecated mus-a*|b*, replaced by mus-x|ycoeff. * 9-June: mus_edot_product. * 7-June: removed mus-x*|y* generic functions. * 24-May: distribution arg to make-rand, make-rand-interp. * 11-May: type arg to mus_make_table_lookup|wave_train, MUS_INTERP_NONE, MUS_INTERP_HERMITE. * mus-interp-type. * 10-May: changed MUS_LINEAR and MUS_SINUSOIDAL to MUS_INTERP_LINEAR and MUS_INTERP_SINUSOIDAL. * mus-linear renamed mus-interp-linear, mus-sinusoidal renamed mus-interp-sinusoidal. * added type arg to mus_make_delay|all_pass|comb|notch. * added mus_delay_tick, all-pass delay line interpolation. * 3-May: envelope arg to make-rand and make-rand-interp to give any arbitrary random number distribution. * added mus_make_rand_with_distribution and mus_make_rand_interp_with_distribution. * rand/rand-interp mus-data returns distribution (weight) function, mus-length its length. * locsig mus-data returns output scalers, mus-xcoeffs returns reverb scalers * 26-Apr: mus_sum_of_sines changed to mus_sine_bank. * new mus_sum_of_sines parallels mus_sum_of_cosines. * deprecated mus_sin. * 14-Apr: changed "2" to "_to_" in several function names. * 12-Apr: mus_average, mus_average_p, mus_make_average. * 17-Mar: edit function added to mus_granulate. * replaced MUS_DATA_POSITION with MUS_DATA_WRAPPER. * 22-Jan: various "environ" variables renamed for Windows' benefit. * 5-Jan-04: env_interp bugfix. * -------- * 29-Sep: removed length arg from spectrum in clm2xen. * 24-Aug: changed mus_length|ramp|hop type to mus_long_t. * 21-Aug: export MUS_INPUT and friends (needed for specialized INA handlers). * 11-Aug: int -> bool. * 7-Aug: removed mus_type. * 20-July: more run methods. * 15-July: linear->dB check for 0.0 arg. * 27-June: mus_samples_to_seconds and mus_seconds_to_samples. * 9-June: mus_mix_with_reader_and_writer. * 27-May: bugfix: interpolating all-pass ("zall-pass") had an extra delay. * 25-Apr: mus_spectrum and mus_convolution now return mus_float_t*. * 9-Apr: removed MUS_HANNING_WINDOW (use MUS_HANN_WINDOW). * 3-Mar: mus_delay_line_p for tap error checking. * 27-Feb: mus_length for env -> original duration in samples. * 21-Feb: mus_set_cosines added, mus_cosines moved to hop slot. * mus_[set_]x1/x2/y1/y2. * 10-Feb: mus_file_name moved into the mus_input|output structs. * folded mus_input|output into mus_any. * moved mus_frame|mixer declarations into clm.c. * all mus_input|output|frame|mixer pointers->mus_any. * all method void pointers->mus_any. * 7-Feb: split strings out of clm2xen.c into clm-strings.h. * 3-Feb: mus_offset for envs, mus_width for square_wave et al. * new core class fields(10) for various methods. * 7-Jan-03: mus_src with very large sr_change segfault bugfix. * -------- * 17-Dec: mus_env_offset|initial_power for Snd exp env optimizations. * 13-Sep: mus_frandom and mus_irandom(for Snd optimizer). * 19-Aug: changed internal phase-vocoder array accessor names * 13-Aug: set!(*-ref) for frame, locsig, mixer, locsig-reverb. * 29-Jul: various *_1 cases for the optimizer. * 15-Jul: mus_continue_sample2file. * 10-Jul: mus_file_name. * 7-Jun: fftw support added. * 31-May: changed mus_any_class. * 3-May: many int->mus_long_t changes for large files. * 8-Apr: off-by-1 env bug(Lisp/C are now identical), env_interp of exp env beyond end bugfix. * 1-Apr: sine-summation n=0 bugfix. * 27-Mar: negative degree locsig bugfix. * 18-Mar: mus_move_locsig. * 15-Mar: n-chan locsig(and reverb scalers), 'type' arg to mus_make_locsig. * 6-Mar: mus_scaler in asymmetric-fm now refers to the "r" parameter, "a" in sine-summation. * 5-Mar: dumb typo in asymmetric-fm generator fixed. * 19-Feb: buffer reallocation redundant free bugfix. * 25-Jan-02: mus_increment of env returns base. * -------- * 10-Dec: add outctr calls, phase-vocoder bugfixes, thanks to <NAME>. * 21-Oct: fill in some set-data methods. * 1-Sep: mus_polar2rectangular. * 6-July: scm -> xen. * 26-May: mus_rand_seed. * 22-May: locsig reverb distance calc was upside down. * 18-May: mus_describe and mus_inspect returned string should not be freed any more. * 7-May: filled in some leftover equal_p methods. * 1-Apr: mus_make_file2sample_with_comment and mus_length for file->sample/sample->file. * mus_file_buffer_size. * 26-Mar: extended_type field added to mus_any_class for more robust type checking. * 16-Mar: mus_phase of env -> current_value. * 28-Feb: added mus_position(currently only for envs). * 8-Feb: clm2scm.h. * 24-Jan: mus-bank in clm2scm. * 5-Jan: clm2scm gens are applicable. * 4-Jan: mus_bank. * 2-Jan-01: mus_run method. * -------- * 28-Dec: mus_clear_filter_state and other minor tweaks for Snd. * 28-Nov: Dolph-Chebyshev window(under HAVE_GSL flag -- needs complex trig support). * 8-Nov: mus_clear_sinc_tables. * 12-Oct: mus_formant_bank takes one input(can't remember why I had an array here) * 27-Sep: mus_array_interp bugfix(imitates mus.lisp now). * 18-Sep: clm now assumes it's used as a part of sndlib. * 11-Sep: generalized set! to generic functions in clm2scm.c. * 31-Aug: changed formant field setters(thanks to <NAME>). * 10-Aug: removed built-in setf support(clm2scm.c). * 31-Jul: mus_granulate tries to protect against illegal length and ramp values. * 24-Jul: mus_make_fir_coeffs. * 20-Jul: sum_of_sines, atan2 to rectangular->polar, phase_vocoder gen. * 22-June: made mus_bessi0 local again. * 1-June: bugfixes for linuxppc 2000. * 19-May: mus_apply. * 8-May: added "const" and XEN_PROCEDURE_CAST(for c++), made mus_bessi0 global. * 24-Apr: changed formant radius to match lisp version(it's now 1-old_radius) * 20-Apr: mus_convolve_files * 7-Apr: src width bug fixed * 31-Mar: finally implemented set-location for envs. * 14-Feb: buffer-full?. * 1-Feb: removed mus_phasepartials2waveshape. * 3-Jan-00: format and type args added to make_sample2file, * mus_file_close. * removed make_file_input and make_file_output. * -------- * 29-Dec: various bugfixes especially in envelope handlers. * 19-Nov: mus_oscil_bank and mus_formant_bank. * 5-Nov: mus_sin exported. * 4-Oct:(scm) make-env arg order changed to reflect mus.lisp. * 29-Sep: implemented mus-increment and mus-frequency for granulate(as in mus.lisp). * clm's fft renamed mus-fft to avoid collision with snd's version. * added max_size arg to make_granulate(to reflect mus.lisp). * 25-Sep-99: added width arg to make_src -- forgot this somehow in first pass. * decided to make mus_inspect return char* like mus_describe. */
{'dir': 'c', 'id': '17726', 'max_stars_count': '1', 'max_stars_repo_name': 'SiddGururani/MUSI8903_Assignment_2', 'max_stars_repo_path': '3rdparty/sndlib/clm.h', 'n_tokens_mistral': 21856, 'n_tokens_neox': 20514, 'n_words': 4616}
const generatePins = async (modules) => { const { fs, request, csvDir, log, endpoint, stringify, order } = modules; var columns = {}; var pins = []; var lastPin = await request(endpoint); function random () { return Math.floor(1000000 + Math.random() * 9000000); }; function incrementString (string) { const toInt = +string + 1; return ('0000000' + toInt).slice(-7); }; function generate (lastPinArg, quantity) { let counter = lastPinArg.slice(-9).slice(0, 7); for (let i = 0; i < quantity; i++) { counter = incrementString(counter); let pin = `${random()}${counter}BH`; if (!pins[i]) { pins.push([pin]); } else { pins[i] = pins[i].concat([pin]); } }; lastPin = pins[pins.length - 1][0]; }; order.forEach((order, index) => { generate(lastPin, order.quantity); columns[`card${1 + index}`] = order.upc; }); stringify(pins, { columns, header: true }, (err, output) => { if (err) { console.log(err); } let dateStamp = (new Date()).toISOString().slice(0,10).replace(/-/g,""); fs.writeFileSync(`${csvDir}/${dateStamp}-pins.csv`, output); }); let orderTotal = order.reduce((prev, curr) => curr.quantity + prev.quantity); let message = `Successfully generated ${orderTotal} PINs.`; fs.appendFileSync(log, `${new Date().toString()} ${message}\n`); console.log(message); }; module.exports = { generatePins };
{'dir': 'javascript', 'id': '9697906', 'max_stars_count': '0', 'max_stars_repo_name': 'nhuesmann/blackhawk-pin-generator', 'max_stars_repo_path': 'bhn_generate_pins.js', 'n_tokens_mistral': 532, 'n_tokens_neox': 485, 'n_words': 107}
<gh_stars>0 // -------------------------------------------------------------------------------------------------------------------- // <copyright file="ProductDto.cs" company=""> // Copyright (c) 2013 <NAME>, for OrderDynamics coding test. All Rights Reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace WingtipToys.Core.Dtos { /// <summary> /// A data transfer object for Product. /// </summary> public class ProductDto { #region Public Properties /// <summary> /// Gets or sets the name of the category. /// </summary> /// <value> /// The name of the category. /// </value> public string CategoryName { get; set; } /// <summary> /// Gets or sets the search keywords. /// </summary> /// <value> /// The search keywords. /// </value> public string SearchKeywords { get; set; } #endregion } }
{'dir': 'c-sharp', 'id': '1001324', 'max_stars_count': '0', 'max_stars_repo_name': 'prototypev/coding-tests', 'max_stars_repo_path': 'WingtipToys/WingtipToys.Core/Dtos/ProductDto.cs', 'n_tokens_mistral': 240, 'n_tokens_neox': 236, 'n_words': 73}
const languageSelect = document.getElementById('languages') const sentenceInput = document.getElementById('text') const resultText = document.getElementById('stopwordsRemoved') function updateSentence() { const language = languageSelect.value const oldString = sentenceInput.value.split(' ') const newString = sw.removeStopwords(oldString, sw[language]).join(' ') console.group('Stopwords applied') console.log('oldString:', oldString.join(' ')) console.log('newString:', newString) console.groupEnd() // Populate with only meaningful words resultText.textContent = newString } // Listen to events and initiate a stopword removal sentenceInput.addEventListener('keyup', updateSentence) // Configure the language select const allLanguages = Object.entries(sw) .filter(([key, val]) => Array.isArray(val)) .map((val) => val[0]) languageSelect.addEventListener('change', function (event) { languageSelect.value = event.target.value sentenceInput.focus() updateSentence() }) languageSelect.innerHTML = allLanguages .map((lang) => `<option value=${lang}>${lang}</option>`) .join('') languageSelect.value = 'en'
{'dir': 'javascript', 'id': '10090297', 'max_stars_count': '176', 'max_stars_repo_name': 'joshmorenx/CitySends', 'max_stars_repo_path': 'blog/static/blog/stopword/demo/stopword-app.js', 'n_tokens_mistral': 324, 'n_tokens_neox': 321, 'n_words': 72}
<filename>src/Image Splitter.pyw<gh_stars>0 import sys from PyQt5 import QtWidgets, QtGui, QtCore from PyQt5.QtCore import * from PIL import Image from PIL.ImageQt import ImageQt font = QtGui.QFont("Arial", 12) def splitImage(filename, split_x, split_y, foldername, return_list = False): im = Image.open(filename) short_filename = filename.split('/')[-1] short_filename_no_ext = '.'.join(short_filename.split('.')[:-1]) file_ext = '.' + short_filename.split('.')[-1] images = list() for y in range(0, im.height, im.height // split_y): for x in range(0, im.width, im.width // split_x): cropped = im.crop((x, y, x + (im.width // split_x), y + (im.height // split_y))) images.append(cropped.copy()) if return_list: return images for i, im in enumerate(images): im.save(foldername + '/' + short_filename_no_ext + '_' + str(i) + file_ext) def calcScale(image_size, targetSize: tuple): w, h = image_size x_ratio = targetSize[0] / w y_ratio = targetSize[1] / h scale = x_ratio if y_ratio > x_ratio else y_ratio return scale class Window(QtWidgets.QWidget): def __init__(self): super().__init__() self.windowSize = (800, 600) self.imageMaxSize = (self.windowSize[0] * 0.6, self.windowSize[1] * 0.6) self.imageLoaded = False self.folderSelected = False self.setWindowTitle("Image Splitter") self.setGeometry(0, 0, self.windowSize[0], self.windowSize[1]) self.center() self.UI() self.show() self.timer = QtCore.QTimer(self) self.timer.setInterval(1) self.timer.timeout.connect(self.checkResized) self.timer.start() # Things would happen when window resized def checkResized(self): if self.width() * 0.6 != self.imageMaxSize[0] or self.height() * 0.6 != self.imageMaxSize[1]: self.windowSize = (self.width(), self.height()) self.imageMaxSize = (self.windowSize[0] * 0.6, self.windowSize[1] * 0.6) self.imagePreview.setMaximumSize(int(self.imageMaxSize[0]), int(self.imageMaxSize[1])) if self.imageLoaded: scale = calcScale(self.original_image.size, self.imageMaxSize) resized = (int(self.original_image.width * scale), int(self.original_image.height * scale)) self.pil_image = self.original_image.resize(resized, Image.ANTIALIAS) self.pil_image = self.pil_image.convert("RGBA") data = self.pil_image.tobytes('raw', 'RGBA') qim = QtGui.QImage(data, self.pil_image.size[0], self.pil_image.size[1], QtGui.QImage.Format_RGBA8888) self.imagePreview.setPixmap(QtGui.QPixmap.fromImage(qim)) self.drawStripes() # Open File Dialog def loadFile(self): self.filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', 'c:\\', "PNG files (*.png);;JPG files (*.jpg);;BMP files (*.bmp);;ICO files (*.ico)") if self.filename[0]: self.imageLoaded = True self.filename = self.filename[0] self.pil_image = Image.open(self.filename) self.original_image = self.pil_image.copy() scale = calcScale(self.pil_image.size, self.imageMaxSize) resized = (int(self.pil_image.width * scale), int(self.pil_image.height * scale)) self.pil_image = self.pil_image.resize(resized, Image.ANTIALIAS) self.pil_image = self.pil_image.convert("RGBA") data = self.pil_image.tobytes('raw', 'RGBA') qim = QtGui.QImage(data, self.pil_image.size[0], self.pil_image.size[1], QtGui.QImage.Format_RGBA8888) self.imagePreview.setPixmap(QtGui.QPixmap.fromImage(qim)) self.imagePreview.show() self.drawStripes() def drawStripes(self): if self.imageLoaded: im = self.pil_image.copy() pieceC = self.xSpinBox.value() pieceC = int(pieceC) per_pix = int(im.width / pieceC) for y in range(im.height): for x in range(per_pix, im.width, per_pix): pix = im.getpixel((x, y)) pix = (255 - pix[0], 255 - pix[1], 255 - pix[2], 255) im.putpixel((x, y), pix) pieceC = self.ySpinBox.value() pieceC = int(pieceC) per_pix = int(im.height / pieceC) for y in range(per_pix, im.height, per_pix): for x in range(im.width): if True: pix = im.getpixel((x, y)) pix = (255 - pix[0], 255 - pix[1], 255 - pix[2], 255) im.putpixel((x, y), pix) im = im.convert("RGBA") data = im.tobytes('raw', 'RGBA') qim = QtGui.QImage(data, im.size[0], im.size[1], QtGui.QImage.Format_RGBA8888) self.imagePreview.setPixmap(QtGui.QPixmap.fromImage(qim)) # Select Folder Dialog def selectFolder(self): file = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Folder")) if file: self.folderSelected = True self.foldername = file def split(self): if self.imageLoaded and self.folderSelected: splitImage(self.filename, int(self.xSpinBox.value()), int(self.ySpinBox.value()), self.foldername) QtWidgets.QMessageBox.information(self, 'Operation Successfull!', 'Your image splitted successfully and saved to ' + self.foldername) else: QtWidgets.QMessageBox.critical(self, "Error!", "You must load an image and select a folder before splitting!") def makeGif(self): if self.imageLoaded and self.folderSelected: images = splitImage(self.filename, int(self.xSpinBox.value()), int(self.ySpinBox.value()), self.foldername, return_list=True) filename_no_ext = '.'.join(self.filename.split('/')[-1].split('.')[:-1]) images[0].save(self.foldername + '/' + filename_no_ext + '.gif', save_all=True, append_images=images[1:], optimize=False, loop=0, duration=40) QtWidgets.QMessageBox.information(self, 'Operation Successfull!', 'Your gif file created successfully and saved to ' + self.foldername) else: QtWidgets.QMessageBox.critical(self, "Error!", "You must load an image and select a folder before making gif!") def UI(self): # Layouts self.mainHLayout = QtWidgets.QHBoxLayout() self.mainVLayout = QtWidgets.QVBoxLayout() self.leftVLayout = QtWidgets.QVBoxLayout() self.rightVLayout = QtWidgets.QVBoxLayout() self.leftHLayout = QtWidgets.QHBoxLayout() self.rightHLayout = QtWidgets.QHBoxLayout() self.bottomHLayout = QtWidgets.QHBoxLayout() self.bottomVLayout = QtWidgets.QVBoxLayout() self.xAxisLayout = QtWidgets.QHBoxLayout() self.yAxisLayout = QtWidgets.QHBoxLayout() # Buttons self.selectFileButton = QtWidgets.QPushButton("Select File...") self.selectFileButton.setFont(font) self.selectFileButton.setMinimumSize(50, 40) self.selectFileButton.clicked.connect(self.loadFile) self.selectFolderButton = QtWidgets.QPushButton("Select Folder...") self.selectFolderButton.setFont(font) self.selectFolderButton.setMinimumSize(50, 40) self.selectFolderButton.clicked.connect(self.selectFolder) self.splitButton = QtWidgets.QPushButton("Split!") self.splitButton.setFont(font) self.splitButton.setMinimumSize(50, 40) self.splitButton.clicked.connect(self.split) self.makeGifButton = QtWidgets.QPushButton("Make Gif!") self.makeGifButton.setFont(font) self.makeGifButton.setMinimumSize(50, 40) self.makeGifButton.clicked.connect(self.makeGif) # Labels self.inputFileLabel = QtWidgets.QLabel(" Input File") self.inputFileLabel.setFont(font) self.outputFolderLabel = QtWidgets.QLabel(" Output Folder") self.outputFolderLabel.setFont(font) self.splitLabel_x = QtWidgets.QLabel("Split") self.splitLabel_x.setFont(font) self.splitLabel_y = QtWidgets.QLabel("Split") self.splitLabel_y.setFont(font) self.xAxisLabel = QtWidgets.QLabel("parts on x axis") self.xAxisLabel.setFont(font) self.yAxisLabel = QtWidgets.QLabel("parts on y axis") self.yAxisLabel.setFont(font) self.imagePreview = QtWidgets.QLabel() self.imagePreview.setMaximumSize(int(self.imageMaxSize[0]), int(self.imageMaxSize[1])) # Spin boxes self.xSpinBox = QtWidgets.QSpinBox() self.xSpinBox.setRange(1, 16) self.xSpinBox.setMaximumSize(50, 20) self.xSpinBox.valueChanged.connect(self.drawStripes) self.ySpinBox = QtWidgets.QSpinBox() self.ySpinBox.setRange(1, 16) self.ySpinBox.setMaximumSize(50, 20) self.ySpinBox.valueChanged.connect(self.drawStripes) # Design self.xAxisLayout.addWidget(self.splitLabel_x) self.xAxisLayout.addWidget(self.xSpinBox) self.xAxisLayout.addWidget(self.xAxisLabel) self.xAxisLayout.addStretch() self.yAxisLayout.addWidget(self.splitLabel_y) self.yAxisLayout.addWidget(self.ySpinBox) self.yAxisLayout.addWidget(self.yAxisLabel) self.yAxisLayout.addStretch() self.leftVLayout.addStretch() self.leftVLayout.addWidget(self.inputFileLabel) self.leftVLayout.addWidget(self.selectFileButton) self.leftVLayout.addStretch() self.leftVLayout.addLayout(self.xAxisLayout) self.leftVLayout.addLayout(self.yAxisLayout) self.leftVLayout.addStretch() self.leftVLayout.addWidget(self.outputFolderLabel) self.leftVLayout.addWidget(self.selectFolderButton) self.leftVLayout.addStretch() self.leftHLayout.addStretch() self.leftHLayout.addLayout(self.leftVLayout) self.leftHLayout.addStretch() self.rightVLayout.addStretch() self.rightVLayout.addWidget(self.imagePreview) self.rightVLayout.addStretch() self.rightHLayout.addStretch() self.rightHLayout.addLayout(self.rightVLayout) self.rightHLayout.addStretch() self.bottomHLayout.addStretch() self.bottomHLayout.addWidget(self.splitButton) self.bottomHLayout.addWidget(self.makeGifButton) self.bottomHLayout.addStretch() self.bottomVLayout.addStretch() self.bottomVLayout.addLayout(self.bottomHLayout) self.bottomVLayout.addStretch() self.mainHLayout.addLayout(self.leftHLayout) self.mainHLayout.addLayout(self.rightHLayout) self.mainVLayout.addLayout(self.mainHLayout) self.mainVLayout.addLayout(self.bottomVLayout) self.setLayout(self.mainVLayout) def center(self): qr = self.frameGeometry() cp = QtWidgets.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def main(): app = QtWidgets.QApplication(sys.argv) window = Window() sys.exit(app.exec_()) if __name__ == '__main__': main()
{'dir': 'python', 'id': '5249356', 'max_stars_count': '0', 'max_stars_repo_name': 'YunusEmre0037/Image-Splitter', 'max_stars_repo_path': 'src/Image Splitter.pyw', 'n_tokens_mistral': 3785, 'n_tokens_neox': 3588, 'n_words': 574}
<filename>src/components/Tables/Tables.tsx<gh_stars>0 import React, { useState } from 'react' import { columns as column } from './data/columns' const Tables =(props:any)=>{ const seller_data = props.sellerData; const buyer_data =props.buyerData; let sellerAndBuyerData:any = {...seller_data,...buyer_data} const [rows,setRows] = useState([ { id:'Add id', description:'Add description', unit:'Unit', quantity:'Quantity', unit_price:'Unit price', line:'Line total' }, ]) const handleChange =(index:any)=>{ if(index===rows.length-1){ let newRow = { id:'Add id', description:'Add description', unit:'Unit', quantity:'Quantity', unit_price:'Unit price', line:'Line total' }; let newRows = [...rows]; newRows.push(newRow); setRows(newRows); } } const print =()=>{ console.log(sellerAndBuyerData) const ipcRenderer = require("electron").ipcRenderer; const sellerName = sellerAndBuyerData.seller_name; const sellerTinNo = sellerAndBuyerData.tin_no const sellerAddress = sellerAndBuyerData.address const sellerSpecificAddress = sellerAndBuyerData.specific_addres const sellerPhone = sellerAndBuyerData.phone const fsno = sellerAndBuyerData.fsno; const date = sellerAndBuyerData.date const reference = sellerAndBuyerData.reference const bill_to = sellerAndBuyerData.bill_to const buyerTin = sellerAndBuyerData.buyer_tin_no // const buyerAddres = sellerAndBuyerData.buyer_address const content = [ { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:`TIN: ${sellerTinNo}`, style: `text-align:center;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:sellerName, style: `text-align:center;`, css: {"font-size": "12px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:sellerAddress, style: `text-align:center;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:sellerSpecificAddress, style: `text-align:center;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:sellerPhone, style: `text-align:center;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:`FS NO.${fsno}`, style: `text-align:start;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:date, style: `text-align:start;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:'11:13', style: `text-align:end;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:'# Cash sales invoice ', style: `text-align:start;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:`# Reference ${reference}`, style: `text-align:start;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:"# Prepared by: Ni", style: `text-align:start;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:`# To: ${bill_to}`, style: `text-align:start;`, css: {"font-size": "8px"} }, { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:`Buyer's TIN: ${buyerTin}`, style: `text-align:start;`, css: {"font-size": "8px","margin-bottom":"20px"} } ] let totalPrice:number =0.0; let taxPayment:number=0.0 let totalPayment:number=0.0 for(let i=0;i<rows.length-1;i++){ let descriptionValue = (document.getElementById(`description_${i}`) as HTMLInputElement).value; let quantityValue = (document.getElementById(`quantity_${i}`) as HTMLInputElement).value; let unitPriceValue = (document.getElementById(`unit_price_${i}`) as HTMLInputElement).value; let lineValue = (document.getElementById(`line_${i}`) as HTMLInputElement).value; let rowSummery = ` ${quantityValue} x ${unitPriceValue}` totalPrice +=parseInt(lineValue); content.push( { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:rowSummery, style: 'margin-left:20px', css: {"font-size": "8px"} } ) content.push( { type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:`${descriptionValue} -------------------------------------------- ${lineValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`, style: `text-align:start;`, css: {"font-size": "8px"} } ) } taxPayment = Math.round((15/100)*totalPrice); totalPayment = Math.round(totalPrice+taxPayment) content.push({ type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:"- - - -", style: 'text-align:center;margin-top:25px;', css: {"font-size": "8px"} }) content.push({ type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:`TXBL1 ---------------------------------------------${totalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`, style: 'text-align:start;', css: {"font-size": "8px"} }) content.push({ type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:`TAX1 15% ---------------------------------${taxPayment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`, style: 'text-align:start;', css: {"font-size": "8px"} }) content.push({ type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:"- - - -", style: 'text-align:center;', css: {"font-size": "8px"} }) content.push({ type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:`Total -------------------------------${totalPayment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`, style: 'text-align:start;', css: {"font-size": "12px"} }) content.push({ type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:`# Cash -----------------------------------${totalPayment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`, style: 'text-align:start;', css: {"font-size": "8px"} }) content.push({ type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:"E R C A", style: 'text-align:center;', css: {"font-size": "8px"} }) content.push({ type: 'text', // 'text' | 'barCode' | 'qrCode' | 'image' | 'table value:"Powered by MarakiPOS 4.0", style: 'text-align:center;', css: {"font-size": "8px"} }) ipcRenderer.send("print", content); } const sumTotal =(index:number)=>{ let quantityValue = parseInt((document.getElementById(`quantity_${index}`) as HTMLInputElement).value); let unitPriceValue = parseInt((document.getElementById(`unit_price_${index}`) as HTMLInputElement).value); let lineTotalValue = quantityValue*unitPriceValue; (document.getElementById(`line_${index}`) as HTMLInputElement).value = lineTotalValue.toString(); } return <div> <table style={{borderCollapse:'collapse',width:'100%',border:'1px solid grey'}}> <tr style={{border:'1px solid grey'}}> { column.map(column=>( <th style={{border:'1px solid grey'}}>{column.label}</th> )) } </tr> <tbody> { rows.map((row,index)=>( ( <tr key={index} style={{border:'1px solid grey'}}> <td style={{border:'1px solid grey'}}> <input id={`id_${index}`} onFocus={()=>handleChange(index)} style={{width:'90%',padding:10}} placeholder={row.id}/> </td> <td style={{border:'1px solid grey'}}> <input id={`description_${index}`} style={{width:'90%',padding:10}} placeholder={row.description}/> </td> <td style={{border:'1px solid grey'}}> <input id={`unit_${index}`} style={{width:'90%',padding:10}} placeholder={row.unit}/> </td> <td style={{border:'1px solid grey'}}> <input id={`quantity_${index}`} style={{width:'90%',padding:10}} placeholder={row.quantity}/> </td> <td style={{border:'1px solid grey'}}> <input onChange={()=>sumTotal(index)} id={`unit_price_${index}`} style={{width:'90%',padding:10}} placeholder={row.unit_price}/> </td> <td style={{border:'1px solid grey'}}> <input id={`line_${index}`} style={{width:'90%',padding:10}} placeholder={row.line}/> </td> </tr> ) )) } </tbody> </table> <div style={{display:'flex',flexDirection:'row',justifyContent:'flex-end',padding:20}}> <button onClick={()=>print()} style={{backgroundColor:'green', color:'white',paddingTop:10,paddingBottom:10, paddingRight:50,paddingLeft:50}}> Print </button> </div> </div> } export default Tables
{'dir': 'typescript', 'id': '2608088', 'max_stars_count': '0', 'max_stars_repo_name': 'messyKassaye/electron-printer', 'max_stars_repo_path': 'src/components/Tables/Tables.tsx', 'n_tokens_mistral': 3425, 'n_tokens_neox': 3278, 'n_words': 593}
package com.jstappdev.e4client.ui; import android.annotation.SuppressLint; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import com.jstappdev.e4client.MainActivity; import com.jstappdev.e4client.R; import com.jstappdev.e4client.SharedViewModel; import com.jstappdev.e4client.data.E4SessionData; import com.jstappdev.e4client.util.Utils; import java.util.Locale; public class ConnectionFragment extends Fragment { private SharedViewModel sharedViewModel; private TextView accel_xLabel; private TextView accel_yLabel; private TextView accel_zLabel; private TextView bvpLabel; private TextView edaLabel; private TextView ibiLabel; private TextView hrLabel; private TextView temperatureLabel; private TextView batteryLabel; private TextView statusLabel; private TextView deviceNameLabel; private TextView wristStatusLabel; private View dataArea; private String microsiemens; private String celsius; @SuppressLint("SourceLockedOrientationActivity") public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class); final View root = inflater.inflate(R.layout.fragment_connection, container, false); final TextView textView = root.findViewById(R.id.status); sharedViewModel.getSessionStatus().observe(getViewLifecycleOwner(), new Observer<String>() { @Override public void onChanged(@Nullable String s) { textView.setText(s); } }); return root; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { statusLabel = view.findViewById(R.id.status); accel_xLabel = view.findViewById(R.id.accel_x); accel_yLabel = view.findViewById(R.id.accel_y); accel_zLabel = view.findViewById(R.id.accel_z); bvpLabel = view.findViewById(R.id.bvp); edaLabel = view.findViewById(R.id.eda); ibiLabel = view.findViewById(R.id.ibi); hrLabel = view.findViewById(R.id.hr); temperatureLabel = view.findViewById(R.id.temperature); batteryLabel = view.findViewById(R.id.battery); deviceNameLabel = view.findViewById(R.id.deviceName); wristStatusLabel = view.findViewById(R.id.wrist_status_label); dataArea = view.findViewById(R.id.dataArea); microsiemens = getString(R.string.microsiemens); celsius = getString(R.string.celsius); view.findViewById(R.id.disconnectButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((MainActivity) requireContext()).disconnect(); dataArea.setVisibility(View.GONE); ((MainActivity) requireContext()).openFragment(R.id.nav_home); } }); //noinspection ConstantConditions if (!sharedViewModel.getIsConnected().getValue()) { ((MainActivity) requireContext()).initEmpaticaDeviceManager(); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final LifecycleOwner owner = getViewLifecycleOwner(); sharedViewModel.getIsConnected().observe(owner, new Observer<Boolean>() { @Override public void onChanged(Boolean isConnected) { if (isConnected) { dataArea.setVisibility(View.VISIBLE); E4SessionData.clear(); E4SessionData.getInstance().setInitialTime(Utils.getCurrentTimestamp()); } else { dataArea.setVisibility(View.GONE); } } }); sharedViewModel.getDeviceName().observe(owner, new Observer<String>() { @Override public void onChanged(String deviceName) { deviceNameLabel.setText(deviceName); } }); sharedViewModel.getSessionStatus().observe(owner, new Observer<String>() { @Override public void onChanged(String status) { statusLabel.setText(status); } }); sharedViewModel.getOnWrist().observe(owner, new Observer<Boolean>() { @Override public void onChanged(Boolean onWrist) { wristStatusLabel.setText(onWrist ? "ON WRIST" : "NOT ON WRIST"); } }); sharedViewModel.getBattery().observe(owner, new Observer<Float>() { @Override public void onChanged(Float battery) { batteryLabel.setText(String.format(Locale.getDefault(), "%.0f %%", battery * 100)); } }); sharedViewModel.getCurrentAccX().observe(owner, new Observer<Integer>() { public void onChanged(Integer accX) { accel_xLabel.setText(accX.toString()); } }); sharedViewModel.getCurrentAccY().observe(owner, new Observer<Integer>() { public void onChanged(Integer accY) { accel_yLabel.setText(accY.toString()); } }); sharedViewModel.getCurrentAccZ().observe(owner, new Observer<Integer>() { public void onChanged(Integer accZ) { accel_zLabel.setText(accZ.toString()); } }); sharedViewModel.getCurrentGsr().observe(owner, new Observer<Float>() { @Override public void onChanged(Float gsr) { edaLabel.setText(String.format(Locale.getDefault(), "%.2f %s", gsr, microsiemens)); } }); sharedViewModel.getCurrentIbi().observe(owner, new Observer<Float>() { @Override public void onChanged(Float ibi) { ibiLabel.setText(String.format(Locale.getDefault(), "%.2f s", ibi)); } }); sharedViewModel.getCurrentHr().observe(owner, new Observer<Float>() { @Override public void onChanged(Float averageHr) { hrLabel.setText(String.format(Locale.getDefault(), "%.0f BPM", averageHr)); } }); sharedViewModel.getCurrentTemp().observe(owner, new Observer<Float>() { @Override public void onChanged(Float temp) { temperatureLabel.setText(String.format(Locale.getDefault(), "%.2f %s", temp, celsius)); } }); sharedViewModel.getCurrentBvp().observe(owner, new Observer<Float>() { int count = 0; @Override public void onChanged(Float bvp) { if (count++ % 10 == 0) bvpLabel.setText(String.format(Locale.getDefault(), "%.0f", bvp)); } }); } }
{'dir': 'java', 'id': '3234122', 'max_stars_count': '0', 'max_stars_repo_name': 'j05t/e4client', 'max_stars_repo_path': 'app/src/main/java/com/jstappdev/e4client/ui/ConnectionFragment.java', 'n_tokens_mistral': 2061, 'n_tokens_neox': 1919, 'n_words': 346}
<gh_stars>0 import React, { ChangeEvent, Component, createRef } from 'react'; import FormCheckboxGroup from '../../components/form/FormCheckboxGroup'; import { RadioChangeEventHandler } from '../../components/form/FormRadio'; import FormRadioGroup from '../../components/form/FormRadioGroup'; import PageHeading from '../../components/PageHeading'; import Tabs from '../../components/Tabs'; import TabsSection from '../../components/TabsSection'; import PrototypePage from '../components/PrototypePage'; import PrototypeAbsenceGeneralChart from './charts/PrototypeAbsenceGeneralChart'; import PrototypeAbsenceRateChart from './charts/PrototypeAbsenceRateChart'; import PrototypeFixedPeriodExclusionsChart from './charts/PrototypeFixedPeriodExclusionsChart'; import PrototypePermanentExclusionsChart from './charts/PrototypePermanentExclusionsChart'; import PublicationMenu, { MenuChangeEventHandler, MenuOption, } from './components/PublicationMenu'; import { allTableData as exclusionTableData } from './test-data/exclusionsDataV1'; import { allTableData as absenceTableData } from './test-data/pupilAbsenceDataV1'; type DataToggles = 'CHARTS_TABLES' | 'CHARTS' | 'TABLES' | null; const allTableData: any = { exclusions: exclusionTableData, pupilAbsence: absenceTableData, }; type PupilAbsenceGeneralFilters = 'enrolments' | 'schools'; type PupilAbsenceSessionsFilters = | 'authorisedRate' | 'overallRate' | 'unauthorisedRate'; type ExclusionsExclusionsFilters = | 'permanent' | 'permanentRate' | 'fixedPeriod' | 'fixedPeriodRate'; interface State { chartData: { [key: string]: number; }[]; dataToggle: DataToggles; menuOption?: MenuOption | null; filters: { exclusions: { exclusions: { [key in ExclusionsExclusionsFilters]: boolean }; }; pupilAbsence: { general: { [key in PupilAbsenceGeneralFilters]: boolean }; sessions: { [key in PupilAbsenceSessionsFilters]: boolean }; }; }; tableData: string[][]; } class PrototypeDataTableV2 extends Component<{}, State> { public state: State = { chartData: [], dataToggle: null, filters: { exclusions: { exclusions: { fixedPeriod: false, fixedPeriodRate: false, permanent: false, permanentRate: false, }, }, pupilAbsence: { general: { enrolments: false, schools: false, }, sessions: { authorisedRate: false, overallRate: false, unauthorisedRate: false, }, }, }, menuOption: null, tableData: [], }; private dataTableRef = createRef<HTMLDivElement>(); private handleMenuChange: MenuChangeEventHandler = menuOption => { this.setState( { menuOption, filters: { exclusions: { exclusions: { fixedPeriod: false, fixedPeriodRate: false, permanent: false, permanentRate: false, }, }, pupilAbsence: { general: { enrolments: false, schools: false, }, sessions: { authorisedRate: false, overallRate: false, unauthorisedRate: false, }, }, }, tableData: [], }, () => { if (this.dataTableRef.current) { this.dataTableRef.current.scrollIntoView({ behavior: 'smooth' }); } }, ); }; private createTableData(filters: {}) { return Object.entries(filters).flatMap(([publicationKey, publication]) => { return Object.entries(publication) .flatMap(([groupKey, group]) => { return Object.entries(group) .filter(([_, isChecked]) => isChecked) .map(([filterKey]) => { return allTableData[publicationKey][groupKey][filterKey]; }); }) .filter(row => row.length > 0); }); } private handleAllFilterCheckboxChange = ( publicationKey: 'pupilAbsence' | 'exclusions', filterGroupKey: 'exclusions' | 'general' | 'sessions', event: ChangeEvent<HTMLInputElement>, ) => { const filterGroup = this.state.filters[publicationKey] as any; const subFilterGroup = filterGroup[filterGroupKey]; const filters = { ...this.state.filters, [publicationKey]: { ...filterGroup, [filterGroupKey]: Object.keys(subFilterGroup).reduce((acc, key) => { return { ...acc, [key]: event.target.checked, }; }, {}), }, }; this.setState({ filters, tableData: this.createTableData(filters), }); }; private handleFilterCheckboxChange = ( publicationKey: 'pupilAbsence' | 'exclusions', filterGroupKey: 'exclusions' | 'general' | 'sessions', event: ChangeEvent<HTMLInputElement>, ) => { const filterGroup = this.state.filters[publicationKey] as any; const subFilterGroup = filterGroup[filterGroupKey]; const filters = { ...this.state.filters, [publicationKey]: { ...filterGroup, [filterGroupKey]: { ...subFilterGroup, [event.target.value]: event.target.checked, }, }, }; this.setState({ filters, tableData: this.createTableData(filters), }); }; private handleRadioChange: RadioChangeEventHandler<{ value: DataToggles; }> = event => { this.setState({ dataToggle: event.target.value }); }; private hasSessionsFilters() { return ( Object.values(this.state.filters.pupilAbsence.sessions).indexOf(true) > -1 ); } private hasGeneralFilters() { return ( Object.values(this.state.filters.pupilAbsence.general).indexOf(true) > -1 ); } private hasPermanentExclusionFilters() { return ( this.state.filters.exclusions.exclusions.permanent || this.state.filters.exclusions.exclusions.permanentRate ); } private hasFixedPeriodExclusionFilters() { return ( this.state.filters.exclusions.exclusions.fixedPeriod || this.state.filters.exclusions.exclusions.fixedPeriodRate ); } private hasAnyFilters() { return Object.values(this.state.filters).map(filterGroup => Object.values(filterGroup).some(filter => filter.size > 0), ); } private getFilterValues(filters: { [key: string]: boolean }) { return Object.entries(filters) .filter(([_, isChecked]) => isChecked) .map(([key]) => key); } public render() { const { filters } = this.state; return ( <PrototypePage breadcrumbs={[ { text: 'Education training and skills' }, { text: 'National level' }, { text: 'Explore statistics' }, ]} wide > <PageHeading caption="National level" heading="Explore statistics" /> <ul> <li> You can explore all the DfE statistics available at national level here. </li> <li> Once you've chosen your data you can view it by year, school type, area or pupil characteristics. </li> <li> You can also download it, visualise it or copy and paste it as you need. </li> </ul> <div className="govuk-grid-row"> <div className="govuk-grid-column-full"> <PublicationMenu onChange={this.handleMenuChange} /> </div> </div> {(this.state.menuOption === 'EXCLUSIONS' || this.state.menuOption === 'PUPIL_ABSENCE') && ( <div ref={this.dataTableRef}> {this.state.menuOption === 'PUPIL_ABSENCE' && ( <h2> 2. Explore statistics from 'Pupil absence' <span className="govuk-hint"> Select any statistics you are interested in from the checkboxes below </span> </h2> )} {this.state.menuOption === 'EXCLUSIONS' && ( <h2> 2. Explore statistics from 'Exclusions' <span className="govuk-hint"> Select any statistics you are interested in from the checkboxes below </span> </h2> )} <div className="govuk-grid-row"> <div className="govuk-grid-column-one-quarter"> {this.state.menuOption === 'PUPIL_ABSENCE' && ( <> <div className="govuk-form-group"> <FormCheckboxGroup value={this.getFilterValues( this.state.filters.pupilAbsence.general, )} name="pupilAbsenceGeneral" id="pupilAbsenceGeneral" legend="General" onAllChange={this.handleAllFilterCheckboxChange.bind( this, 'pupilAbsence', 'general', )} onChange={this.handleFilterCheckboxChange.bind( this, 'pupilAbsence', 'general', )} options={[ { id: 'general-enrolments', label: 'Enrolments', value: 'enrolments', }, { id: 'general-schools', label: 'Schools', value: 'schools', }, ]} /> </div> <div className="govuk-form-group"> <FormCheckboxGroup value={this.getFilterValues( this.state.filters.pupilAbsence.sessions, )} name="pupilAbsenceSessions" id="pupilAbsenceSessions" legend="Sessions absent" onAllChange={this.handleAllFilterCheckboxChange.bind( this, 'pupilAbsence', 'sessions', )} onChange={this.handleFilterCheckboxChange.bind( this, 'pupilAbsence', 'sessions', )} options={[ { id: 'sessions-authorised-rate', label: 'Authorised rate', value: 'authorisedRate', }, { id: 'sessions-overall-rate', label: 'Overall rate', value: 'overallRate', }, { id: 'sessions-unauthorised-rate', label: 'Unauthorised rate', value: 'unauthorisedRate', }, ]} /> </div> </> )} {this.state.menuOption === 'EXCLUSIONS' && ( <FormCheckboxGroup value={this.getFilterValues( this.state.filters.exclusions.exclusions, )} name="exclusions" id="exclusions" legend="Exclusions" onAllChange={this.handleAllFilterCheckboxChange.bind( this, 'exclusions', 'exclusions', )} onChange={this.handleFilterCheckboxChange.bind( this, 'exclusions', 'exclusions', )} options={[ { id: 'permanent-exclusions', label: 'Permanent exclusions', value: 'permanent', }, { id: 'permanent-exclusions-rate', label: 'Permanent exclusion rate', value: 'permanentRate', }, { id: 'fixed-period-exclusions', label: 'Fixed period exclusions', value: 'fixedPeriod', }, { id: 'fixed-period-exclusions-rate', label: 'Fixed period exclusion rate', value: 'fixedPeriodRate', }, ]} /> )} </div> {this.hasAnyFilters() && ( <div className="govuk-grid-column-three-quarters"> <FormRadioGroup value={this.state.dataToggle} inline id="dataToggle" name="dataToggle" legend="What do you want to see?" legendSize="m" onChange={this.handleRadioChange as any} options={[ { id: 'chartsAndTable', label: 'Charts and table', value: 'CHARTS_TABLES', }, { id: 'charts', label: 'Charts', value: 'CHARTS' }, { id: 'table', label: 'Table', value: 'TABLES' }, ]} /> {this.state.dataToggle && ( <> <p>View by:</p> <Tabs> <TabsSection id="years" title="Academic years"> <> {(this.state.dataToggle === 'CHARTS_TABLES' || this.state.dataToggle === 'CHARTS') && ( <div className="govuk-grid-row"> {this.state.menuOption === 'PUPIL_ABSENCE' && ( <> {this.hasGeneralFilters() && ( <div className="govuk-grid-column-one-half"> <p>General</p> <PrototypeAbsenceGeneralChart enrolments={ filters.pupilAbsence.general .enrolments } schools={ filters.pupilAbsence.general.schools } /> </div> )} {this.hasSessionsFilters() && ( <div className="govuk-grid-column-one-half"> <p>Sessions absent</p> <PrototypeAbsenceRateChart authorised={ filters.pupilAbsence.sessions .authorisedRate } unauthorised={ filters.pupilAbsence.sessions .unauthorisedRate } overall={ filters.pupilAbsence.sessions .overallRate } /> </div> )} </> )} {this.state.menuOption === 'EXCLUSIONS' && ( <> {this.hasPermanentExclusionFilters() && ( <div className="govuk-grid-column-one-half"> <p>Permanent exclusions</p> <PrototypePermanentExclusionsChart exclusions={ filters.exclusions.exclusions .permanent } exclusionsRate={ filters.exclusions.exclusions .permanentRate } /> </div> )} {this.hasFixedPeriodExclusionFilters() && ( <div className="govuk-grid-column-one-half"> <p>Fixed period exclusions</p> <PrototypeFixedPeriodExclusionsChart exclusions={ filters.exclusions.exclusions .fixedPeriod } exclusionsRate={ filters.exclusions.exclusions .fixedPeriodRate } /> </div> )} </> )} </div> )} {this.hasAnyFilters() && ( <> <hr /> {(this.state.dataToggle === 'CHARTS_TABLES' || this.state.dataToggle === 'TABLES') && ( <table className="govuk-table"> <caption> Comparing statistics between 2012 and 2017 </caption> <thead> <tr> <th /> <th scope="col">2012/13</th> <th scope="col">2013/14</th> <th scope="col">2014/15</th> <th scope="col">2015/16</th> <th scope="col">2016/17</th> </tr> </thead> <tbody> {this.state.tableData.map( ([firstCell, ...cells], rowIndex) => ( <tr key={rowIndex}> <td scope="row">{firstCell}</td> {cells.map((cell, cellIndex) => ( <td key={cellIndex}>{cell}</td> ))} </tr> ), )} </tbody> </table> )} <ul className="govuk-list"> <li> <a href="#download">Download data (.csv)</a> </li> <li> <a href="#api">Access developer API</a> </li> <li> <a href="#methodology">Methodology</a> </li> <li> <a href="#contact">Contact</a> </li> </ul> </> )} </> </TabsSection> <TabsSection id="school-type" title="School type"> {null} </TabsSection> <TabsSection id="geography" title="Geography"> {null} </TabsSection> <TabsSection id="demographics-characteristics" title="Demographics/characteristics" > {null} </TabsSection> </Tabs> </> )} </div> )} </div> </div> )} </PrototypePage> ); } } export default PrototypeDataTableV2;
{'dir': 'typescript', 'id': '1471650', 'max_stars_count': '0', 'max_stars_repo_name': 'markhiveit/explore-education-statistics', 'max_stars_repo_path': 'src/explore-education-statistics-frontend/src/prototypes/data-table/PrototypeDataTableV2.tsx', 'n_tokens_mistral': 5007, 'n_tokens_neox': 4698, 'n_words': 812}
/** * Provides a wrapper to interact with the security configuration */ var jenkins = require('../util/jenkins'); /** * Calls a stapler post method to save the first user settings */ exports.saveFirstUser = function($form, success, error) { jenkins.staplerPost( '/setupWizard/createAdminUser', $form, function(response) { var crumbRequestField = response.data.crumbRequestField; if (crumbRequestField) { require('window-handle').getWindow().crumb.init(crumbRequestField, response.data.crumb); } success(response); }, { error: error }); }; exports.saveConfigureInstance = function($form, success, error){ jenkins.staplerPost( '/setupWizard/configureInstance', $form, function(response) { var crumbRequestField = response.data.crumbRequestField; if (crumbRequestField) { require('window-handle').getWindow().crumb.init(crumbRequestField, response.data.crumb); } success(response); }, { error: error }); }; /** * Calls a stapler post method to save the first user settings */ exports.saveProxy = function($form, success, error) { jenkins.staplerPost( '/pluginManager/proxyConfigure', $form, success, { dataType: 'html', error: error }); };
{'dir': 'javascript', 'id': '2916345', 'max_stars_count': '637', 'max_stars_repo_name': '1st/jenkins', 'max_stars_repo_path': 'war/src/main/js/api/securityConfig.js', 'n_tokens_mistral': 438, 'n_tokens_neox': 385, 'n_words': 82}
<reponame>The-Graphe-A-Design-Studio/member-directory<filename>app/Http/Controllers/api/v1/user/UserController.php <?php namespace App\Http\Controllers\api\v1\user; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; use App\User; use Validator; class UserController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return User::all(); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request) { $user = Auth::user(); $rules = [ 'IM_no' => 'nullable|regex:/^[A-Za-z0-9 ]+$/', 'name' => 'nullable|regex:/^[A-Za-z ]+$/', 'dob' => 'nullable|date', 'phone' => 'nullable|unique:users|min:10|max:10|regex:/^[0-9]+$/', 'email' => 'nullable|unique:users|email', 'password' => 'nullable|regex:/^[A-Za-z0-9 ]+$/', 'gender' => 'nullable|in:Male,Female,Others', 'photo' => 'nullable|mimes:jpg,jpeg,png', 'club_name' => 'nullable|regex:/^[A-Za-z0-9 ]+$/', 'designation' => 'nullable|regex:/^[A-Za-z0-9 ]+$/', 'occupation' => 'nullable|regex:/^[A-Za-z0-9 ]+$/', 'blood_group' => 'nullable|in:A+,A-,B+,B-,O+,O-,AB+,AB-', 'sponsorer' => 'nullable|regex:/^[A-Za-z0-9 ]+$/', ]; $validator = Validator::make($request->all(), $rules); if($validator->fails()){ return response()->json($validator->errors(), 400); } if($request->hasFile('photo')) { //delete old visiting card if exists if($user->photo != null){ // $storage = "/home/thegrhmw/public_html/developers/flexy/storage/app/visiting_card/"; // $storage = "storage/app/profile_pic/"; // $path = $storage . $user->photo; $storage = Storage::disk('local')->getAdapter()->getPathPrefix(); $path = $storage . "profile_pic/" . $user->photo; unlink($path); // unlink($user->photo); } //add the new image $file = $request->file('photo'); //Get file name with the extension $fileNameWithExt = $file->getClientOriginalName(); //Get just Filename $filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME); //Get just Extension $extension = $file->getClientOriginalExtension(); // Filename to store $fileNameToStore = $filename.'_'.time().'.'.$extension; Storage::disk('local')->putFileAs('profile_pic', $request->file('photo'), $fileNameToStore); } $user->IM_no = ( empty($request->get('IM_no')) ) ? $user->IM_no : $request->get('IM_no'); $user->name = ( empty($request->get('name')) ) ? $user->name : $request->get('name'); $user->dob = ( empty($request->get('dob')) ) ? $user->dob : $request->get('dob'); $user->phone = ( empty($request->get('phone')) ) ? $user->phone : $request->get('phone'); $user->email = ( empty($request->get('email')) ) ? $user->email : $request->get('email'); $user->gender = ( empty($request->get('gender')) ) ? $user->gender : $request->get('gender'); $user->photo = ( empty($fileNameToStore) ) ? $user->photo : $fileNameToStore; $user->club_name = ( empty($request->get('club_name')) ) ? $user->club_name : $request->get('club_name'); $user->designation = ( empty($request->get('designation')) ) ? $user->designation : $request->get('designation'); $user->occupation = ( empty($request->get('occupation')) ) ? $user->occupation : $request->get('occupation'); $user->blood_group = ( empty($request->get('blood_group')) ) ? $user->blood_group : $request->get('blood_group'); $user->save(); return response()->json(['status' => 'success', 'messege' => 'Member details updated'], 200); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function search(Request $request) { $term = $request->input('term'); $members = User::where('name', 'LIKE', '%'.$term.'%') ->orWhere('club_name', 'LIKE', '%'.$term.'%') ->orWhere('designation', 'LIKE', '%'.$term.'%') ->orWhere('occupation', 'LIKE', '%'.$term.'%') ->orWhere('IM_no', 'LIKE', '%'.$term.'%')->get(); if(!empty($members)) { return response()->json(['status' => 'success', 'members' => $members], 200); } return response()->json(['status' => 'success', 'message' => 'No members found'], 200); } public function getleos(Request $request) { $leos = User::where('leo', 1)->get(); return response()->json(['status' => 'success', 'members' => $leos], 200); } }
{'dir': 'php', 'id': '11521909', 'max_stars_count': '0', 'max_stars_repo_name': 'The-Graphe-A-Design-Studio/member-directory', 'max_stars_repo_path': 'app/Http/Controllers/api/v1/user/UserController.php', 'n_tokens_mistral': 1927, 'n_tokens_neox': 1879, 'n_words': 318}
<reponame>adityaagassi/ympimisdev <!DOCTYPE html> <html> <head> <title>YMPI 情報システム</title> <!-- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> --> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, user-scalable=yes, initial-scale=1.0" name="viewport"> <style type="text/css"> body{ font-size: 10px; } #isi > thead > tr > td { text-align: center; } #isi > tbody > tr > td { text-align: left; padding-left: 5px; } * { font-family: arial; } .page-break { page-break-after: always; } @page { } .footer { position: fixed; left: 0px; bottom: 100px; right: 0px; height: 130px;text-align: center;} .footer .pagenum:before { content: counter(page); } </style> </head> <body> <header> <table style="width: 100%; font-family: arial; border-collapse: collapse; text-align: left;"> <thead> <tr> <td colspan="12" style="font-weight: bold;font-size: 13px">PT. YAMAHA MUSICAL PRODUCTS INDONESIA</td> </tr> <tr> <td colspan="12"><br></td> </tr> <tr> <td colspan="3">&nbsp;</td> <td colspan="6" style="text-align: center;font-weight: bold;font-size: 16px">PURCHASE REQUISITION FORM</td> <td colspan="2" style="text-align: right;font-size: 12px">No:</td> <td colspan="1" style="text-align: right;font-size: 14px;font-weight: bold">{{ $pr[0]->no_pr }}</td> </tr> <tr> <td colspan="12"><br></td> </tr> <tr> <td colspan="2" style="font-size: 12px;width: 22%">Department</td> <td colspan="10" style="font-size: 12px;">: {{ $pr[0]->department }}</td> </tr> <tr> <td colspan="2" style="font-size: 12px;width: 22%">Section</td> @if($pr[0]->section != null) <td colspan="10" style="font-size: 12px;">: {{ $pr[0]->section }}</td> @else <td colspan="10" style="font-size: 12px;">: {{ $pr[0]->department }}</td> @endif </tr> <tr> <td colspan="2" style="font-size: 12px;width: 22%">Date Of Submission</td> <td colspan="10" style="font-size: 12px;">: <?= date('d-M-Y', strtotime($pr[0]->submission_date)) ?></td> </tr> <tr> <td colspan="2" style="font-size: 12px;width: 22%">Budget</td> <td colspan="10" style="font-size: 12px;">: {{ $pr[0]->no_budget }}</td> </tr> <tr> <td colspan="12"><br></td> </tr> </thead> </table> </header> @if($pr[0]->receive_date != null) <img width="120" src="{{ public_path() . '/files/ttd_pr_po/received.jpg' }}" alt="" style="padding: 0;position: absolute;top: 55px;left: 840px"> <span style="position: absolute;width: 100px;font-size: 12px;font-weight: bold;font-family: arial-narrow;top:88px;left: 875px;color:#c34354"><?= date('d-M-y', strtotime($pr[0]->receive_date)) ?></span> @endif <main> <table style="width: 100%; font-family: arial; border-collapse: collapse; " id="isi"> <thead> <tr style="font-size: 12px"> <td colspan="1" style="padding:10px;height: 15px; width:1%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">No</td> <td colspan="1" style="width:3%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Item Code</td> <td colspan="3" style="width:8%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Description</td> <td colspan="1" style="width:4%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Request Date</td> <td colspan="1" style="width:2%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Qty</td> <td colspan="1" style="width:3%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Currency</td> <td colspan="1" style="width:3%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Unit Price</td> <td colspan="2" style="width:3%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Amount</td> <td colspan="1" style="width:4%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Last Order</td> </tr> </thead> <tbody> <?php $no = 1; $totalidr = 0; foreach($pr as $purchase_r) { if($purchase_r->item_currency == "IDR"){ $totalidr += $purchase_r->item_amount; } if ($no % 15 == 0) { ?> <tr> <td colspan="1" style="height: 26px; border: 1px solid black;text-align: center;padding: 0">{{ $no }}</td> <td colspan="1" style="border: 1px solid black;">{{ $purchase_r->item_code }}</td> <td colspan="3" style="border: 1px solid black;"> {{ $purchase_r->item_desc }} </td> <!-- <td clolspan="1" style="border: 1px solid black;">{{ $purchase_r->item_stock }}</td> --> <td colspan="1" style="border: 1px solid black;text-align: right;padding-right: 5px"><?= date('d-M-y', strtotime($purchase_r->item_request_date)) ?></td> <td colspan="1" style="border: 1px solid black;">{{ $purchase_r->item_qty }} {{ $purchase_r->item_uom }}</td> <td colspan="1" style="border: 1px solid black;">{{ $purchase_r->item_currency }}</td> @if($purchase_r->item_currency == "IDR") <td colspan="1" style="border: 1px solid black;text-align: right;padding-right: 5px"><?= number_format($purchase_r->item_price,0,"",".") ?></td> @else <td colspan="1" style="border: 1px solid black;text-align: right;padding-right: 5px"><?= $purchase_r->item_price ?></td> @endif @if($purchase_r->item_currency == "IDR") <td colspan="2" style="border: 1px solid black;text-align: right;padding-right: 5px"><?= number_format($purchase_r->item_amount,0,"",".") ?></td> @else <td colspan="2" style="border: 1px solid black;text-align: right;padding-right: 5px"><?= $purchase_r->item_amount ?></td> @endif <td colspan="1" style="border: 1px solid black;"> @if($purchase_r->last_order != null) <?= date('d-M-Y', strtotime($purchase_r->last_order)) ?> @else - @endif </td> </tr> </tbody> </table> <footer> <div class="footer"> <table style="width: 100%;font-family: arial;border-collapse: collapse;"> <tr> <th colspan="3" style="background-color: #4caf50; border: 1px solid black;font-size: 12px;text-align: center;font-weight: bold">Summary Total PR</th> <th colspan="1"></th> <th colspan="3" style="background-color: yellow; border: 1px solid black;font-size: 12px;text-align: center;font-weight: bold">Budget Detail</th> </tr> <tr> <th colspan="1" style="background-color: #4caf50; border: 1px solid black;font-size: 12px;text-align: center;">Currency</th> <th colspan="1" style="background-color: #4caf50; border: 1px solid black;font-size: 12px;text-align: center;">Amount (Original)</th> <th colspan="1" style="background-color: #4caf50; border: 1px solid black;font-size: 12px;text-align: center;">Amount (US$)</th> <th colspan="1"></th> <th colspan="1" style="background-color:yellow; font-size: 12px;text-align:center; padding:10px; height: 15px; font-weight: bold; border: 1px solid black;">Beg Balance</th> <th colspan="1" style="background-color:yellow; font-size: 12px;text-align:center; padding:10px; height: 15px; font-weight: bold; border: 1px solid black;">Amount</th> <th colspan="1" style="background-color:yellow; font-size: 12px;text-align:center; padding:10px; height: 15px; font-weight: bold; border: 1px solid black;">End Balance</th> </tr> <tr> <td colspan="1" rowspan="2" style="border: 1px solid black;font-size: 12px;text-align: center;">IDR</td> <td colspan="1" rowspan="2" style="border: 1px solid black;font-size: 12px;text-align: center;">Rp. <?= number_format($totalidr,0,"",".") ?></td> <td colspan="1" rowspan="2" style="border: 1px solid black;font-size: 12px;text-align: center;"> <?php $totalkonversiidr = $totalidr / $rate[0]->rate; ?> $ <?= number_format($totalkonversiidr,0,".","") ?> </td> <th colspan="1" rowspan="2"></th> <?php $totalamount = 0; foreach ($pr as $pr_budget) { $totalamount += $pr_budget->amount; } ?> <td colspan="1" rowspan="2" style="text-align:center; font-size:14px; font-weight: bold; padding:5px; height: 15px; border: 1px solid black;">$ <?= number_format($pr[0]->beg_bal,0,".","") ?></td> <td colspan="1" rowspan="2" style="text-align:center; font-size:14px; font-weight: bold; padding:5px; height: 15px; border: 1px solid black;">$ <?= number_format($totalamount,0,".","") ?></td> <td colspan="1" rowspan="2" style="text-align:center; font-weight: bold;font-size:14px; padding:5px; height: 15px; border: 1px solid black;">$ <?= number_format($pr[0]->beg_bal - $totalamount,0,".","") ?></td> </tr> <tr> </tr> <tr> <td colspan="7"> &nbsp;</td> </tr> </table> <table style="width: 100%; font-family: arial; border-collapse: collapse; text-align: center;" border="1"> <thead> <tr> <td colspan="1" style="width:15%;height: 26px; border: 1px solid black;text-align: center;padding: 0">Applied By</td> <td colspan="1" style="width:15%;">Acknowledge By</td> <td colspan="1" style="width:15%;">Approve By</td> <td colspan="6" rowspan="3" style="text-align: left;padding: 5px;vertical-align: top;font-size: 11px"> Note : @if($pr[0]->note == null) - @else <br><?= $pr[0]->note ?> @endif </td> </tr> </thead> <tbody> <tr> <td colspan="1" style="height: 40px"> @if($pr[0]->posisi != "staff") <?= $pr[0]->emp_name ?> @endif </td> <td colspan="1" style="height: 40px"> @if($pr[0]->approvalm == "Approved") <?= $pr[0]->manager_name ?> @endif </td> <td colspan="1" style="height: 40px"> @if($pr[0]->approvalgm == "Approved" && $pr[0]->gm == "PI1206001") <img width="70" src="{{ public_path() . '/files/ttd_pr_po/stempel_pak_hayakawa.jpg' }}" alt="" style="padding: 0"> <span style="position: absolute;left: 227px;width: 75px;font-size: 8px;color: #f84c32;top: 165px;font-family: arial-narrow"><?= date('d F Y', strtotime($pr[0]->dateapprovalgm)) ?></span> @elseif($pr[0]->approvalgm == "Approved" && $pr[0]->gm == "PI9709001") <img width="70" src="{{ public_path() . '/files/ttd_pr_po/stempel_pak_arief.jpg' }}" alt="" style="padding: 0"> <span style="position: absolute;left: 227px;width: 75px;font-size: 8px;color: #f84c32;top: 165px;font-family: arial-narrow"><?= date('d F Y', strtotime($pr[0]->dateapprovalgm)) ?></span> @elseif($pr[0]->approvalgm == "Approved" && $pr[0]->gm == "PI0109004") <img width="70" src="{{ public_path() . '/files/ttd_pr_po/stempel_pak_budhi.jpg' }}" alt="" style="padding: 0"> <span style="position: absolute;left: 227px;width: 75px;font-size: 8px;color: #f84c32;top: 165px;font-family: arial-narrow"><?= date('d F Y', strtotime($pr[0]->dateapprovalgm)) ?></span> @endif </td> </tr> <tr> <td colspan="1">User</td> <td colspan="1">Manager</td> <td colspan="1">Director</td> </tr> </tbody> </table> Page <span class="pagenum"></span> </div> </footer> <div class="page-break"></div> <header> <table style="width: 100%; font-family: arial; border-collapse: collapse; text-align: left;"> <thead> <tr> <td colspan="12" style="font-weight: bold;font-size: 13px">PT. YAMAHA MUSICAL PRODUCTS INDONESIA</td> </tr> <tr> <td colspan="12"><br></td> </tr> <tr> <td colspan="3">&nbsp;</td> <td colspan="6" style="text-align: center;font-weight: bold;font-size: 16px">PURCHASE REQUISITION FORM</td> <td colspan="2" style="text-align: right;font-size: 12px">No:</td> <td colspan="1" style="text-align: right;font-size: 14px;font-weight: bold">{{ $pr[0]->no_pr }}</td> </tr> <tr> <td colspan="12"><br></td> </tr> <tr> <td colspan="2" style="font-size: 12px;width: 22%">Department</td> <td colspan="10" style="font-size: 12px;">: {{ $pr[0]->department }}</td> </tr> <tr> <td colspan="2" style="font-size: 12px;width: 22%">Section</td> @if($pr[0]->section != null) <td colspan="10" style="font-size: 12px;">: {{ $pr[0]->section }}</td> @else <td colspan="10" style="font-size: 12px;">: {{ $pr[0]->department }}</td> @endif </tr> <tr> <td colspan="2" style="font-size: 12px;width: 22%">Date Of Submission</td> <td colspan="10" style="font-size: 12px;">: <?= date('d-M-Y', strtotime($pr[0]->submission_date)) ?></td> </tr> <tr> <td colspan="2" style="font-size: 12px;width: 22%">Budget</td> <td colspan="10" style="font-size: 12px;">: {{ $pr[0]->no_budget }}</td> </tr> <tr> <td colspan="12"><br></td> </tr> </thead> </table> </header> @if($pr[0]->receive_date != null) <img width="120" src="{{ public_path() . '/files/ttd_pr_po/received.jpg' }}" alt="" style="padding: 0;position: absolute;top: 55px;left: 840px"> <span style="position: absolute;width: 100px;font-size: 12px;font-weight: bold;font-family: arial-narrow;top:88px;left: 875px;color:#c34354"><?= date('d-M-y', strtotime($pr[0]->receive_date)) ?></span> @endif <table style="width: 100%; font-family: arial; border-collapse: collapse; " id="isi"> <thead> <tr style="font-size: 12px"> <td colspan="1" style="padding:10px;height: 15px; width:1%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">No</td> <td colspan="1" style="width:3%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Item Code</td> <td colspan="3" style="width:8%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Description</td> <!-- <td colspan="1" style="width:2%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Stock WIP</td> --> <td colspan="1" style="width:4%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Request Date</td> <td colspan="1" style="width:2%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Qty</td> <td colspan="1" style="width:3%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Currency</td> <td colspan="1" style="width:3%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Unit Price</td> <td colspan="2" style="width:3%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Amount</td> <td colspan="1" style="width:4%; background-color: #03a9f4; font-weight: bold; border: 1px solid black;">Last Order</td> </tr> </thead> <tbody> <?php } else { ?> <tr> <td colspan="1" style="height: 26px; border: 1px solid black;text-align: center;padding: 0">{{ $no }}</td> <td colspan="1" style="border: 1px solid black;">{{ $purchase_r->item_code }}</td> <td colspan="3" style="border: 1px solid black;"> {{ $purchase_r->item_desc }} </td> <!-- <td clolspan="1" style="border: 1px solid black;">{{ $purchase_r->item_stock }}</td> --> <td colspan="1" style="border: 1px solid black;text-align: right;padding-right: 5px"><?= date('d-M-y', strtotime($purchase_r->item_request_date)) ?></td> <td colspan="1" style="border: 1px solid black;">{{ $purchase_r->item_qty }} {{ $purchase_r->item_uom }}</td> <td colspan="1" style="border: 1px solid black;">{{ $purchase_r->item_currency }}</td> @if($purchase_r->item_currency == "IDR") <td colspan="1" style="border: 1px solid black;text-align: right;padding-right: 5px"><?= number_format($purchase_r->item_price,0,"",".") ?></td> @else <td colspan="1" style="border: 1px solid black;text-align: right;padding-right: 5px"><?= $purchase_r->item_price ?></td> @endif @if($purchase_r->item_currency == "IDR") <td colspan="2" style="border: 1px solid black;text-align: right;padding-right: 5px"><?= number_format($purchase_r->item_amount,0,"",".") ?></td> @else <td colspan="2" style="border: 1px solid black;text-align: right;padding-right: 5px"><?= $purchase_r->item_amount ?></td> @endif <td colspan="1" style="border: 1px solid black;"> @if($purchase_r->last_order != null) <?= date('d-M-Y', strtotime($purchase_r->last_order)) ?> @else - @endif </td> </tr> <?php } ?> <?php $no++; } ?> <tr> <td colspan="12">&nbsp;</td> </tr> </tbody> </table> </main> <footer> <div class="footer"> <table style="width: 100%;font-family: arial;border-collapse: collapse;"> <tr> <th colspan="3" style="background-color: #4caf50; border: 1px solid black;font-size: 12px;text-align: center;font-weight: bold">Summary Total PR</th> <th colspan="1"></th> <th colspan="3" style="background-color: yellow; border: 1px solid black;font-size: 12px;text-align: center;font-weight: bold">Budget Detail</th> </tr> <tr> <th colspan="1" style="background-color: #4caf50; border: 1px solid black;font-size: 12px;text-align: center;">Currency</th> <th colspan="1" style="background-color: #4caf50; border: 1px solid black;font-size: 12px;text-align: center;">Amount (Original)</th> <th colspan="1" style="background-color: #4caf50; border: 1px solid black;font-size: 12px;text-align: center;">Amount (US$)</th> <th colspan="1"></th> <th colspan="1" style="background-color:yellow; font-size: 12px;text-align:center; padding:10px; height: 15px; font-weight: bold; border: 1px solid black;">Beg Balance</th> <th colspan="1" style="background-color:yellow; font-size: 12px;text-align:center; padding:10px; height: 15px; font-weight: bold; border: 1px solid black;">Amount</th> <th colspan="1" style="background-color:yellow; font-size: 12px;text-align:center; padding:10px; height: 15px; font-weight: bold; border: 1px solid black;">End Balance</th> </tr> <tr> <td colspan="1" rowspan="2" style="border: 1px solid black;font-size: 12px;text-align: center;">IDR</td> <td colspan="1" rowspan="2" style="border: 1px solid black;font-size: 12px;text-align: center;">Rp. <?= number_format($totalidr,0,"",".") ?></td> <td colspan="1" rowspan="2" style="border: 1px solid black;font-size: 12px;text-align: center;"> <?php $totalkonversiidr = $totalidr / $rate[0]->rate; ?> $ <?= number_format($totalkonversiidr,0,".","") ?> </td> <th colspan="1" rowspan="2"></th> <?php $totalamount = 0; foreach ($pr as $pr_budget) { $totalamount += $pr_budget->amount; } ?> <td colspan="1" rowspan="2" style="text-align:center; font-size:14px; font-weight: bold; padding:5px; height: 15px; border: 1px solid black;">$ <?= number_format($pr[0]->beg_bal,0,".","") ?></td> <td colspan="1" rowspan="2" style="text-align:center; font-size:14px; font-weight: bold; padding:5px; height: 15px; border: 1px solid black;">$ <?= number_format($totalamount,0,".","") ?></td> <td colspan="1" rowspan="2" style="text-align:center; font-weight: bold;font-size:14px; padding:5px; height: 15px; border: 1px solid black;">$ <?= number_format($pr[0]->beg_bal - $totalamount,0,".","") ?></td> </tr> <tr> </tr> <tr> <td colspan="7"> &nbsp;</td> </tr> </table> <table style="width: 100%; font-family: arial; border-collapse: collapse; text-align: center;" border="1"> <thead> <tr> <td colspan="1" style="width:15%;height: 26px; border: 1px solid black;text-align: center;padding: 0">Applied By</td> <td colspan="1" style="width:15%;">Acknowledge By</td> <td colspan="1" style="width:15%;">Approve By</td> <td colspan="6" rowspan="3" style="text-align: left;padding: 5px;vertical-align: top;font-size: 11px"> Note : @if($pr[0]->note == null) - @else <br><?= $pr[0]->note ?> @endif </td> </tr> </thead> <tbody> <tr> <td colspan="1" style="height: 40px"> @if($pr[0]->posisi != "staff") <?= $pr[0]->emp_name ?> @endif </td> <td colspan="1" style="height: 40px"> @if($pr[0]->approvalm == "Approved") <?= $pr[0]->manager_name ?> @endif </td> <td colspan="1" style="height: 40px"> @if($pr[0]->approvalgm == "Approved" && $pr[0]->gm == "PI1206001") <img width="70" src="{{ public_path() . '/files/ttd_pr_po/stempel_pak_hayakawa.jpg' }}" alt="" style="padding: 0"> <span style="position: absolute;left: 227px;width: 75px;font-size: 8px;color: #f84c32;top: 165px;font-family: arial-narrow"><?= date('d F Y', strtotime($pr[0]->dateapprovalgm)) ?></span> @elseif($pr[0]->approvalgm == "Approved" && $pr[0]->gm == "PI9709001") <img width="70" src="{{ public_path() . '/files/ttd_pr_po/stempel_pak_arief.jpg' }}" alt="" style="padding: 0"> <span style="position: absolute;left: 227px;width: 75px;font-size: 8px;color: #f84c32;top: 165px;font-family: arial-narrow"><?= date('d F Y', strtotime($pr[0]->dateapprovalgm)) ?></span> @elseif($pr[0]->approvalgm == "Approved" && $pr[0]->gm == "PI0109004") <img width="70" src="{{ public_path() . '/files/ttd_pr_po/stempel_pak_budhi.jpg' }}" alt="" style="padding: 0"> <span style="position: absolute;left: 227px;width: 75px;font-size: 8px;color: #f84c32;top: 165px;font-family: arial-narrow"><?= date('d F Y', strtotime($pr[0]->dateapprovalgm)) ?></span> @endif </td> </tr> <tr> <td colspan="1">User</td> <td colspan="1">Manager</td> <td colspan="1">Director</td> </tr> </tbody> </table> Page <span class="pagenum"></span> </div> </footer> </body> </html>
{'dir': 'php', 'id': '6257201', 'max_stars_count': '1', 'max_stars_repo_name': 'adityaagassi/ympimisdev', 'max_stars_repo_path': 'resources/views/general_affairs/report/report_pr.blade.php', 'n_tokens_mistral': 11114, 'n_tokens_neox': 8133, 'n_words': 1692}
<?php namespace Cruxinator\ClassFinder\Tests; use Composer\Autoload\ClassLoader; use Cruxinator\ClassFinder\ClassFinder; use ReflectionClass; use ReflectionProperty; /** * Class ClassFinderConcrete. * @property bool classLoaderInit * @property null|array optimisedClassMap * @property array loadedNamespaces * @property string vendorDir * @package Tests\Cruxinator\ClassFinder * @method array getProjectClasses(string $namespace) * @method array getClassMap(string $namespace) * @method bool strStartsWith($needle, $haystack) * @method void checkState() * @method void initClassMap() * @method array getClasses(string $namespace = '',callable $conditional = null, bool $includeVendor = true) * @method array getProjectSearchDirs(string $namespace) * @method bool isClassInVendor(string $className) * @method ClassLoader getComposerAutoloader() * @method string getVendorDir() * @method array findCompatibleNamespace(string $namespace, array $psr4) */ class ClassFinderConcrete extends ClassFinder { public function __construct() { $this->loadedNamespaces = []; $this->optimisedClassMap = null; $this->vendorDir = ''; $this->classLoaderInit = false; } /** * @param $name * @throws \ReflectionException * @return \ReflectionMethod */ protected static function getMethod($name) { $class = new ReflectionClass(self::class); $method = $class->getMethod($name); $method->setAccessible(true); return $method; } /** * @param $name * @throws \ReflectionException * @return ReflectionProperty */ protected static function getProperty($name) { $reflectionProperty = new ReflectionProperty(parent::class, $name); $reflectionProperty->setAccessible(true); return $reflectionProperty; } /** * @param $name * @param $arguments * @throws \ReflectionException * @return mixed */ public function __call($name, $arguments) { $method = self::getMethod($name); return $method->invokeArgs(null, $arguments); } /** * @param $name * @param $value * @throws \ReflectionException */ public function __set($name, $value) { $property = self::getProperty($name); $property->setValue(null, $value); } /** * @param $name * @throws \ReflectionException */ public function __get($name) { $property = self::getProperty($name); return $property->getValue(); } }
{'dir': 'php', 'id': '12353032', 'max_stars_count': '0', 'max_stars_repo_name': 'cruxinator/ClassFinder', 'max_stars_repo_path': 'tests/ClassFinderConcrete.php', 'n_tokens_mistral': 726, 'n_tokens_neox': 728, 'n_words': 165}
import nock from 'nock'; import path from 'path'; import { fetchCsvBasedTimeline } from './fetch-timeline'; const TESTDATA_DIR = path.resolve(__dirname, '..', '..', 'testdata'); describe('fetchCsvBasedTimeSeries', () => { beforeEach(() => { nock( 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series', ) .get('/time_series_covid19_confirmed_global.csv') .replyWithFile(200, path.join(TESTDATA_DIR, 'confirmed.csv')) .get('/time_series_covid19_deaths_global.csv') .replyWithFile(200, path.join(TESTDATA_DIR, 'deceased.csv')) .get('/time_series_covid19_recovered_global.csv') .replyWithFile(200, path.join(TESTDATA_DIR, 'recovered.csv')); nock('https://raw.githubusercontent.com/lukes/ISO-3166-Countries-with-Regional-Codes/master/all') .get('/all.csv') .replyWithFile(200, path.join(TESTDATA_DIR, 'all.csv')); }); it('works', async () => { try { const result = await fetchCsvBasedTimeline(); expect(result).toMatchSnapshot(); } catch (err) { fail(err); } }); });
{'dir': 'typescript', 'id': '4893254', 'max_stars_count': '8', 'max_stars_repo_name': 'svandriel/covid19-graphql', 'max_stars_repo_path': 'src/fetching/fetch-timeline.spec.ts', 'n_tokens_mistral': 424, 'n_tokens_neox': 398, 'n_words': 48}
<div class="row"> <div class="col-xs-12"> <?php $location_widget_activated = osc_get_preference('show-locations', 'frclassifieds'); ?> <?php $contry_code = get_user_country_code(); if($contry_code !=''){ $code = $contry_code; }else{ $code = 0; } ?> <?php if($location_widget_activated=!'' && $location_widget_activated == 'activated'){?> <?php if(osc_count_list_regions($code) > 0 ) { ?> <div class="box location"> <ul> <?php while(osc_has_list_regions() ) { ?> <li><a class="btn btn-outlined btn-sm btn-transparent-theme <?php if(get_region_location() == osc_list_region_name() ){ echo 'active'; }?>" href="<?php echo osc_list_region_url(); ?>"><?php echo osc_list_region_name() ; ?> <em>(<?php echo osc_list_region_items() ; ?>)</em></a></li> <?php } ?> </ul> </div> <?php } ?> <?php } ?> </div> </div>
{'dir': 'php', 'id': '12189493', 'max_stars_count': '0', 'max_stars_repo_name': 'EloneSampaio/classificado-da-fronteira', 'max_stars_repo_path': 'oc-content/themes/frclassifieds/inc/locations.php', 'n_tokens_mistral': 369, 'n_tokens_neox': 328, 'n_words': 57}
<filename>trackme/lib/py2/past/__init__.py # coding=utf-8 """ past: compatibility with Python 2 from Python 3 =============================================== ``past`` is a package to aid with Python 2/3 compatibility. Whereas ``future`` contains backports of Python 3 constructs to Python 2, ``past`` provides implementations of some Python 2 constructs in Python 3 and tools to import and run Python 2 code in Python 3. It is intended to be used sparingly, as a way of running old Python 2 code from Python 3 until the code is ported properly. Potential uses for libraries: - as a step in porting a Python 2 codebase to Python 3 (e.g. with the ``futurize`` script) - to provide Python 3 support for previously Python 2-only libraries with the same APIs as on Python 2 -- particularly with regard to 8-bit strings (the ``past.builtins.str`` type). - to aid in providing minimal-effort Python 3 support for applications using libraries that do not yet wish to upgrade their code properly to Python 3, or wish to upgrade it gradually to Python 3 style. Here are some code examples that run identically on Python 3 and 2:: >>> from past.builtins import str as oldstr >>> philosopher = oldstr(u'\u5b54\u5b50'.encode('utf-8')) >>> # This now behaves like a Py2 byte-string on both Py2 and Py3. >>> # For example, indexing returns a Python 2-like string object, not >>> # an integer: >>> philosopher[0] '\xe5' >>> type(philosopher[0]) <past.builtins.oldstr> >>> # List-producing versions of range, reduce, map, filter >>> from past.builtins import range, reduce >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 15 >>> # Other functions removed in Python 3 are resurrected ... >>> from past.builtins import execfile >>> execfile('myfile.py') >>> from past.builtins import raw_input >>> name = raw_input('What is your name? ') What is your name? [cursor] >>> from past.builtins import reload >>> reload(mymodule) # equivalent to imp.reload(mymodule) in Python 3 >>> from past.builtins import xrange >>> for i in xrange(10): ... pass It also provides import hooks so you can import and use Python 2 modules like this:: $ python3 >>> from past.translation import autotranslate >>> authotranslate('mypy2module') >>> import mypy2module until the authors of the Python 2 modules have upgraded their code. Then, for example:: >>> mypy2module.func_taking_py2_string(oldstr(b'abcd')) Credits ------- :Author: <NAME> :Sponsor: Python Charmers Pty Ltd, Australia: http://pythoncharmers.com Licensing --------- Copyright 2013-2018 Python Charmers Pty Ltd, Australia. The software is distributed under an MIT licence. See LICENSE.txt. """ from future import __version__, __copyright__, __license__ __title__ = 'past' __author__ = '<NAME>'
{'dir': 'python', 'id': '4057288', 'max_stars_count': '1', 'max_stars_repo_name': 'duanshuaimin/trackme', 'max_stars_repo_path': 'trackme/lib/py2/past/__init__.py', 'n_tokens_mistral': 935, 'n_tokens_neox': 838, 'n_words': 369}
<filename>src/main/java/br/rickcm/transacaoapp/TransacaoAppApplication.java package br.rickcm.transacaoapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @EnableFeignClients @EnableJpaRepositories(enableDefaultTransactions = false) public class TransacaoAppApplication { public static void main(String[] args) { SpringApplication.run(TransacaoAppApplication.class, args); } }
{'dir': 'java', 'id': '5469851', 'max_stars_count': '0', 'max_stars_repo_name': 'rick-cm/desafio-transacao', 'max_stars_repo_path': 'src/main/java/br/rickcm/transacaoapp/TransacaoAppApplication.java', 'n_tokens_mistral': 183, 'n_tokens_neox': 180, 'n_words': 25}
<reponame>JetBrains/teamcity-vmware-plugin<gh_stars>10-100 /* * Copyright 2000-2021 JetBrains s.r.o. * * 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 jetbrains.buildServer.clouds.vmware.connector; import com.vmware.vim25.LocalizedMethodFault; import com.vmware.vim25.TaskInfo; import com.vmware.vim25.TaskInfoState; import com.vmware.vim25.mo.Task; import java.util.Date; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; import jetbrains.buildServer.clouds.base.connector.AsyncCloudTask; import jetbrains.buildServer.clouds.base.connector.CloudTaskResult; import jetbrains.buildServer.log.LogUtil; import jetbrains.buildServer.util.impl.Lazy; import org.jetbrains.annotations.NotNull; /** * @author Sergey.Pak * Date: 7/29/2014 * Time: 6:22 PM */ public class VmwareTaskWrapper implements AsyncCloudTask { private final Callable<Task> myVmwareTask; private final String myTaskName; private volatile long myStartTime; private final Lazy<CloudTaskResult> myResultLazy; private final AtomicBoolean myIsDone = new AtomicBoolean(false); public VmwareTaskWrapper(@NotNull final Callable<Task> vmwareTask, String taskName){ myVmwareTask = vmwareTask; myTaskName = taskName; myResultLazy = new Lazy<CloudTaskResult>() { @Override protected CloudTaskResult createValue() { try { myStartTime = System.currentTimeMillis(); return getResult(myVmwareTask.call()); } catch (Exception e) { return createErrorTaskResult(e); } finally { myIsDone.set(true); } } }; } @Override public CloudTaskResult executeOrGetResult() { return myResultLazy.getValue(); } @NotNull public String getName() { return myTaskName; } public long getStartTime() { return myStartTime; } @Override public boolean isDone() { return myIsDone.get(); } @NotNull private CloudTaskResult getResult(final Task task) { try { final String result = task.waitForTask(); final TaskInfo taskInfo = task.getTaskInfo(); if (taskInfo.getState() == TaskInfoState.error){ final LocalizedMethodFault error = taskInfo.getError(); return new CloudTaskResult(true, result, new Exception(error== null ? "Unknown error" : error.getLocalizedMessage())); } else { return new CloudTaskResult(result); } } catch (Exception e) { return new CloudTaskResult(true, e.toString(), e); } } private CloudTaskResult createErrorTaskResult(Exception e){ return new CloudTaskResult(true, e.toString(), e); } @Override public String toString() { return "VmwareTaskWrapper{" + "TaskName='" + myTaskName + '\'' + ",StartTime=" + LogUtil.describe(new Date(myStartTime)) + '}'; } }
{'dir': 'java', 'id': '3108380', 'max_stars_count': '17', 'max_stars_repo_name': 'JetBrains/teamcity-vmware-plugin', 'max_stars_repo_path': 'cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/VmwareTaskWrapper.java', 'n_tokens_mistral': 1023, 'n_tokens_neox': 978, 'n_words': 260}
<filename>chapter_004/src/test/java/ru/job4j/list/DynamicArrayTest.java<gh_stars>0 package ru.job4j.list; import org.hamcrest.core.Is; import org.junit.Before; import org.junit.Test; import java.util.ConcurrentModificationException; import java.util.Iterator; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /** * DynamicArrayTest. * @author <NAME> * @since 04.05.2018 * @version 1.0 */ public class DynamicArrayTest { /** Container. */ private DynamicArray<Integer> list; /** * Customize tests. */ @Before public void beforeTest() { list = new DynamicArray<>(); list.add(1); list.add(2); list.add(3); } /** * Test for get method. */ @Test public void whenAddThreeElementsThenUseGetOneResultTwo() { assertThat(list.get(1), is(2)); } /** * Iterator Testing. */ @Test public void whenIteratorThanIteratorOfThisContainer() { Iterator<Integer> iterator = list.iterator(); assertThat(iterator.hasNext(), Is.is(true)); assertThat(iterator.hasNext(), Is.is(true)); assertThat(iterator.next(), Is.is(1)); assertThat(iterator.hasNext(), Is.is(true)); assertThat(iterator.next(), Is.is(2)); assertThat(iterator.hasNext(), Is.is(true)); assertThat(iterator.next(), Is.is(3)); assertThat(iterator.hasNext(), Is.is(false)); } /** * Testing of automatic container increase. */ @Test public void whenAddElementsMoreThanSizeOfContainerThanContainerIncreases() { list.add(4); list.add(5); list.add(6); list.add(7); list.add(8); list.add(9); list.add(10); list.add(11); assertThat(list.get(10), is(11)); } /** * Test with an incorrectly assigned index. */ @Test(expected = IndexOutOfBoundsException.class) public void shoulThrowIndexOfBoundsException() { list.get(3); } /** * Test behavior when the collection was modified during the action of the iterator. */ @Test(expected = ConcurrentModificationException.class) public void shoulThrowConcurrentModificationException() { Iterator<Integer> iterator = list.iterator(); list.add(4); iterator.next(); } }
{'dir': 'java', 'id': '2443403', 'max_stars_count': '0', 'max_stars_repo_name': 'IvanBelyaev/ibelyaev', 'max_stars_repo_path': 'chapter_004/src/test/java/ru/job4j/list/DynamicArrayTest.java', 'n_tokens_mistral': 739, 'n_tokens_neox': 715, 'n_words': 134}
<reponame>kernelcase/autoposter-web package com.facebook_autoposter.robot.core.facebook; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Inject; import com.facebook_autoposter.robot.exception.BusinessException; import com.facebook_autoposter.robot.exception.Validation; import com.facebook_autoposter.robot.persistence.FacebookEntity; import com.facebook_autoposter.robot.persistence.FacebookQuery; @Stateless public class CreateFacebookEJB { @Inject private FacebookQuery facebookQuery; @TransactionAttribute( TransactionAttributeType.REQUIRES_NEW) public Integer createFacebook(FacebookDTO facebookDTO) { // Validate the input Validation.required().setParam("facebookDTO", facebookDTO).validate(); Validation.required() .setParam("idFacebook", facebookDTO.getIdFacebook()) .setParam("facebookUsername", facebookDTO.getFacebookUsername()) .setParam("facebookPassword", facebookDTO.getFacebookPassword()) .validate(); FacebookEntity duplicated = facebookQuery.getFacebookByUsername(facebookDTO.getFacebookUsername()); boolean isDuplicated = duplicated != null; if(isDuplicated) { throw new BusinessException("the facebook account is duplicated"); } FacebookEntity facebookEntity = new FacebookEntity(); facebookEntity.setIdFacebook(facebookDTO.getIdFacebook()); facebookEntity.setFacebookUsername(facebookDTO.getFacebookUsername()); facebookEntity.setFacebookPassword(facebookDTO.getFacebookPassword()); facebookEntity.setFacebookStatus(FacebookStatus.NEW); facebookQuery.save(facebookEntity); return facebookEntity.getIdFacebook(); } @TransactionAttribute( TransactionAttributeType.REQUIRES_NEW) public boolean verify(Integer idFacebook) { boolean verify = false; while(!verify) { FacebookEntity facebookEntity = facebookQuery.getFacebookById(idFacebook); verify = facebookEntity.getFacebookStatus().equals(FacebookStatus.VERIFIED); } return verify; } @TransactionAttribute( TransactionAttributeType.REQUIRES_NEW) public void deleteFacebook(Integer idFacebook) { FacebookEntity facebookEntity = facebookQuery.getFacebookById(idFacebook); facebookQuery.delete(facebookEntity); } }
{'dir': 'java', 'id': '18108284', 'max_stars_count': '0', 'max_stars_repo_name': 'kernelcase/autoposter-web', 'max_stars_repo_path': 'autopost/src/main/java/com/facebook_autoposter/robot/core/facebook/CreateFacebookEJB.java', 'n_tokens_mistral': 707, 'n_tokens_neox': 609, 'n_words': 99}
// // TempDataGenerator.h // MHelloNestedTemplate // // Created by Chen,Meisong on 2017/11/6. // Copyright © 2017年 hellochenms. All rights reserved. // #import <Foundation/Foundation.h> #import "News.h" @interface TempDataGenerator : NSObject + (NSArray<News *> *)newses; @end
{'dir': 'c', 'id': '2158658', 'max_stars_count': '0', 'max_stars_repo_name': 'hellochenms/MHelloNestedTemplate', 'max_stars_repo_path': 'MHelloNestedTemplate/Src/Data/TempDataGenerator.h', 'n_tokens_mistral': 110, 'n_tokens_neox': 100, 'n_words': 24}
<reponame>olukas/hazelcast-go-client // Copyright (c) 2008-2018, Hazelcast, Inc. 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 internal import ( "sync" "sync/atomic" "github.com/hazelcast/hazelcast-go-client/core" "github.com/hazelcast/hazelcast-go-client/internal/proto" ) const ( authenticated = iota credentialsFailed serializationVersionMismatch ) type connectionManager interface { //getActiveConnections returns a snapshot of active connections getActiveConnections() map[string]*Connection //getActiveConnection returns connection if available, nil otherwise getActiveConnection(address core.Address) *Connection //ConnectionCount returns number of active connections ConnectionCount() int32 //getOrConnect returns associated connection if available, creates new connection otherwise getOrConnect(address core.Address, asOwner bool) (*Connection, error) //getOrTriggerConnect returns associated connection if available, returns error and triggers new connection creation otherwise getOrTriggerConnect(address core.Address) (*Connection, error) getOwnerConnection() *Connection addListener(listener connectionListener) onConnectionClose(connection *Connection, cause error) NextConnectionID() int64 shutdown() } func (cm *connectionManagerImpl) addListener(listener connectionListener) { cm.listenerMutex.Lock() defer cm.listenerMutex.Unlock() if listener != nil { listeners := cm.connectionListeners.Load().([]connectionListener) size := len(listeners) + 1 copyListeners := make([]connectionListener, size) copy(copyListeners, listeners) copyListeners[size-1] = listener cm.connectionListeners.Store(copyListeners) } } func (cm *connectionManagerImpl) getActiveConnection(address core.Address) *Connection { return cm.getConnection(address, false) } func (cm *connectionManagerImpl) ConnectionCount() int32 { cm.connectionsMutex.RLock() defer cm.connectionsMutex.RUnlock() return int32(len(cm.connections)) } func (cm *connectionManagerImpl) getActiveConnections() map[string]*Connection { connections := make(map[string]*Connection) cm.connectionsMutex.RLock() defer cm.connectionsMutex.RUnlock() for k, v := range cm.connections { connections[k] = v } return connections } func (cm *connectionManagerImpl) onConnectionClose(connection *Connection, cause error) { //If Connection was authenticated fire event address, ok := connection.endpoint.Load().(core.Address) if ok { cm.connectionsMutex.Lock() delete(cm.connections, address.String()) cm.connectionsMutex.Unlock() listeners := cm.connectionListeners.Load().([]connectionListener) for _, listener := range listeners { if _, ok := listener.(connectionListener); ok { listener.(connectionListener).onConnectionClosed(connection, cause) } } } else { //Clean up unauthenticated Connection cm.client.InvocationService.cleanupConnection(connection, cause) } } func (cm *connectionManagerImpl) getOrTriggerConnect(address core.Address) (*Connection, error) { connection := cm.getConnection(address, false) if connection != nil { return connection, nil } go cm.getOrCreateConnectionInternal(address, false) return nil, core.NewHazelcastIOError("No available connection to address "+address.String(), nil) } func (cm *connectionManagerImpl) getOrConnect(address core.Address, asOwner bool) (*Connection, error) { connection := cm.getConnection(address, asOwner) if connection != nil { return connection, nil } return cm.getOrCreateConnectionInternal(address, asOwner) } func (cm *connectionManagerImpl) getOwnerConnection() *Connection { ownerConnectionAddress := cm.client.ClusterService.getOwnerConnectionAddress() if ownerConnectionAddress == nil { return nil } return cm.getActiveConnection(ownerConnectionAddress) } func (cm *connectionManagerImpl) shutdown() { activeCons := cm.getActiveConnections() for _, con := range activeCons { con.close(core.NewHazelcastClientNotActiveError("client is shutting down", nil)) } } //internal definitions and methods called inside connection manager process type connectionManagerImpl struct { client *HazelcastClient connectionsMutex sync.RWMutex connections map[string]*Connection nextConnectionID int64 listenerMutex sync.Mutex connectionListeners atomic.Value } func newConnectionManager(client *HazelcastClient) connectionManager { cm := connectionManagerImpl{ client: client, connections: make(map[string]*Connection), } cm.connectionListeners.Store(make([]connectionListener, 0)) return &cm } func (cm *connectionManagerImpl) getConnection(address core.Address, asOwner bool) *Connection { cm.connectionsMutex.RLock() conn, found := cm.connections[address.String()] cm.connectionsMutex.RUnlock() if !found { return nil } if !asOwner { return conn } if conn.isOwnerConnection { return conn } return nil } // following methods are called under same connectionsMutex writeLock // only entry point is getOrCreateConnectionInternal func (cm *connectionManagerImpl) getOrCreateConnectionInternal(address core.Address, asOwner bool) (*Connection, error) { cm.connectionsMutex.Lock() defer cm.connectionsMutex.Unlock() conn, found := cm.connections[address.String()] if !found { return cm.createConnection(address, asOwner) } if !asOwner { return conn, nil } if conn.isOwnerConnection { return conn, nil } err := cm.authenticate(conn, asOwner) if err == nil { return conn, nil } return nil, err } func (cm *connectionManagerImpl) NextConnectionID() int64 { cm.nextConnectionID = cm.nextConnectionID + 1 return cm.nextConnectionID } func (cm *connectionManagerImpl) encodeAuthenticationRequest(asOwner bool) *proto.ClientMessage { uuid := cm.client.ClusterService.uuid.Load().(string) ownerUUID := cm.client.ClusterService.ownerUUID.Load().(string) clientType := proto.ClientType name := cm.client.ClientConfig.GroupConfig().Name() password := cm.client.ClientConfig.GroupConfig().Password() clientVersion := "ALPHA" //TODO This should be replace with a build time version variable, BuildInfo etc. request := proto.ClientAuthenticationEncodeRequest( name, password, uuid, ownerUUID, asOwner, clientType, 1, clientVersion, ) return request } func (cm *connectionManagerImpl) authenticate(connection *Connection, asOwner bool) error { request := cm.encodeAuthenticationRequest(asOwner) invocationResult := cm.client.InvocationService.invokeOnConnection(request, connection) result, err := invocationResult.ResultWithTimeout(cm.client.HeartBeatService.heartBeatTimeout) if err != nil { return err } //status, address, uuid, ownerUUID, serializationVersion, serverHazelcastVersion , clientUnregisteredMembers status, address, uuid, ownerUUID, _, serverHazelcastVersion, _ := proto.ClientAuthenticationDecodeResponse(result)() switch status { case authenticated: connection.serverHazelcastVersion = serverHazelcastVersion connection.endpoint.Store(address) connection.isOwnerConnection = asOwner cm.connections[address.String()] = connection go cm.fireConnectionAddedEvent(connection) if asOwner { cm.client.ClusterService.ownerConnectionAddress.Store(address) cm.client.ClusterService.ownerUUID.Store(ownerUUID) cm.client.ClusterService.uuid.Store(uuid) } case credentialsFailed: return core.NewHazelcastAuthenticationError("invalid credentials!", nil) case serializationVersionMismatch: return core.NewHazelcastAuthenticationError("serialization version mismatches with the server!", nil) } return nil } func (cm *connectionManagerImpl) fireConnectionAddedEvent(connection *Connection) { listeners := cm.connectionListeners.Load().([]connectionListener) for _, listener := range listeners { if _, ok := listener.(connectionListener); ok { listener.(connectionListener).onConnectionOpened(connection) } } } func (cm *connectionManagerImpl) createConnection(address core.Address, asOwner bool) (*Connection, error) { if !asOwner && cm.client.ClusterService.getOwnerConnectionAddress() == nil { return nil, core.NewHazelcastIllegalStateError("ownerConnection is not active", nil) } invocationService := cm.client.InvocationService.(*invocationServiceImpl) connectionID := cm.NextConnectionID() con := newConnection(address, invocationService.handleResponse, connectionID, cm) if con == nil { return nil, core.NewHazelcastTargetDisconnectedError("target is disconnected", nil) } err := cm.authenticate(con, asOwner) if err != nil { return nil, err } return con, nil } type connectionListener interface { onConnectionClosed(connection *Connection, cause error) onConnectionOpened(connection *Connection) }
{'dir': 'go', 'id': '1533102', 'max_stars_count': '0', 'max_stars_repo_name': 'olukas/hazelcast-go-client', 'max_stars_repo_path': 'internal/connection_manager.go', 'n_tokens_mistral': 2707, 'n_tokens_neox': 2602, 'n_words': 673}
<filename>resources/views/admin/blogs/create.blade.php @extends('admin.layouts.master') @section("title", "Steller Winds") @section('content') <style type="text/css"> .red{ color:#FF0000; } .panel-body .form-control{ color: #666666; } </style> <script src="//cdn.ckeditor.com/4.5.10/standard/ckeditor.js"></script> <section id="main-content"> <section class="wrapper wrapper-area"> @include('admin.elements.notifications') <div class="row"> <div class="col-lg-12"> <section class="panel"> <header class="panel-heading"> <h3>Add New Blog <a class="btn btn-primary pull-right" href="{{ route('admin.blogs.index') }}">Back</a> </h3> </header> <div class="panel-body"> <?php $title = Session::has('title') ? Session::get('title') : ''; $description = Session::has('description') ? Session::get('description') : ''; $image = Session::has('image') ? Session::get('image') : ''; $status = Session::has('status') ? Session::get('status') : ''; ?> <form role="form" enctype="multipart/form-data" method="post" action="{{ route('admin.blogs.store') }}"> {{ csrf_field() }} <div class="form-group "> <label>Title</label> <input type="text" class="form-control" name="title" placeholder="Enter Title" value="{{ $title }}"> @if ($errors->any() && $errors->first('title') != "") <span class="help-block red"> {!! $errors->first('title') !!} </span> @endif </div> <div class="form-group"> <label>Description</label> <textarea class="form-control" name="description" id="text-area" rows="15" cols="50">{{ $description }} </textarea> @if ($errors->any() && $errors->first('description') != "") <span class="help-block red"> {!! $errors->first('description') !!} </span> @endif <script> CKEDITOR.replace('text-area'); </script> </div> <div class="form-group"> <label>Image</label> <input type="file" name="image" id=""> @if ($errors->any() && $errors->first('image') != "") <span class="help-block red"> {!! $errors->first('image') !!} </span> @endif </div> <div class="form-group"> <label>Status</label> <select name="status" class="form-control"> <option selected="selected" value="">Select Status</option> <option value="1">Active</option> <option value="0">Inactive</option> </select> @if ($errors->any() && $errors->first('status') != "") <span class="help-block red"> {!! $errors->first('status') !!} </span> @endif </div> <div class="form-group"> <label>Category</label> @foreach($blogCategories as $blogCategory) <div class="checkbox"> <label> <input type="checkbox" name="categories[]" value="{{ $blogCategory->id }}"> {{ $blogCategory->name }} </label> </div> @endforeach </div> <input type="submit" value="submit" class="btn btn-success"> <a href="{{ route('admin.blogs.index') }}"><button class="btn btn-danger" type="button">Cancel</button></a> </form> </div> </section> </div> </div> </section> </section> @endsection
{'dir': 'php', 'id': '9773217', 'max_stars_count': '1', 'max_stars_repo_name': 'zhenangroup/cartumo', 'max_stars_repo_path': 'resources/views/admin/blogs/create.blade.php', 'n_tokens_mistral': 1173, 'n_tokens_neox': 1092, 'n_words': 191}
using System; using System.Collections.Generic; using System.Text; using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Auth; namespace pelazem.azure.storage { public class Common { #region Storage Primitives public static StorageCredentials GetStorageCredentials(string storageAccountName, string storageAccountKey) { StorageCredentials storageCredentials = new StorageCredentials(storageAccountName, storageAccountKey); return storageCredentials; } public static CloudStorageAccount GetStorageAccount(StorageCredentials storageCredentials) { CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true); return storageAccount; } public static CloudStorageAccount GetStorageAccount(string connectionString) { CloudStorageAccount storageAccount; try { bool worked = CloudStorageAccount.TryParse(connectionString, out storageAccount); } catch { // TODO log exception storageAccount = null; } return storageAccount; } #endregion } }
{'dir': 'c-sharp', 'id': '2705927', 'max_stars_count': '0', 'max_stars_repo_name': 'plzm/pelazem.azure.storage', 'max_stars_repo_path': 'pelazem.azure.storage/Common.cs', 'n_tokens_mistral': 328, 'n_tokens_neox': 276, 'n_words': 66}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using TheBezitEstateApp.Web.Models; using TheBezitEstateApp.Web.Interfaces; using Microsoft.AspNetCore.Identity; using TheBezitEstateApp.Data.Entities; namespace TheBezitEstateApp.Web.Controllers { public class AccountController : Controller { private readonly IAccountService _accountService; private readonly SignInManager<ApplicationUser> _signInManager; public AccountController(IAccountService accountService, SignInManager<ApplicationUser> signInManager) { _accountService = accountService; _signInManager = signInManager; } [HttpPost] public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); return LocalRedirect("~/"); } [HttpGet] public IActionResult Login() { return View(); } [HttpPost] public async Task<IActionResult> Login(LoginModel model) { try { //if they pass in the right email and password and if their email/password is wrong it throws error using the false. var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false ); //this will sign the user in if(!result.Succeeded) { var errorMessage = "Login failed, please check your details again!"; ModelState.AddModelError("", errorMessage); return View(); } return LocalRedirect("~/"); // this will reutn the user to the homepage } catch (Exception ex) { ModelState.AddModelError("", ex.Message); return View(); } } [HttpGet] public IActionResult Register() { return View(); } [HttpPost] public async Task<IActionResult> Register(RegisterModel model) { if(!ModelState.IsValid) return View(); try { var user = await _accountService.CreateUserAsync(model); await _signInManager.SignInAsync(user, isPersistent: false); //this will sign them in after creating the user; return LocalRedirect("~/"); //after signng a user in, this will retutn the user to the homepage of our application } catch(Exception ex) { ModelState.AddModelError("", ex.Message); return View(); } } } }
{'dir': 'c-sharp', 'id': '1536834', 'max_stars_count': '0', 'max_stars_repo_name': 'Kennybello099/BezitEstateApp', 'max_stars_repo_path': 'src/TheBezitEstateApp.Web/Controllers/AccountController.cs', 'n_tokens_mistral': 691, 'n_tokens_neox': 673, 'n_words': 187}
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Job extends Model { protected $fillable = [ 'type_loker', 'company_name', 'company_tagline', 'description_company', 'company_address', 'company_website', 'company_email', 'company_phone', 'position_sought', 'type_work', 'description_job', 'recruit_process', 'logo_url', 'upload_poster', 'evidence_transfer' ]; public $timestamps = true; }
{'dir': 'php', 'id': '804954', 'max_stars_count': '0', 'max_stars_repo_name': 'mauritswalalayo/jobhun', 'max_stars_repo_path': 'Job.php', 'n_tokens_mistral': 172, 'n_tokens_neox': 171, 'n_words': 29}
// Test the various geometry/position transformations in calorimeter // regions input from the RCT to the GCT emulator. // This used to be done in a class called L1GctMap. #include "DataFormats/L1CaloTrigger/interface/L1CaloRegion.h" #include <iostream> using namespace std; int main() { bool testPass = true; cout << "\nTesting eta,phi to/from ID conversion" << endl << endl; for (unsigned ieta = 0; ieta < 22; ieta++) { // loop over eta cout << ieta << " "; for (unsigned iphi = 0; iphi < 18; iphi++) { // loop over phi L1CaloRegionDetId temp(ieta, iphi); if (temp.iphi() != iphi) { testPass = false; cout << "Error : phi->id->phi conversion failed for phi=" << iphi << " stored phi=" << temp.iphi() << endl; } if (temp.ieta() != ieta) { testPass = false; cout << "Error : eta->id->eta conversion failed for eta=" << ieta << " stored eta=" << temp.ieta() << endl; } } } cout << endl; cout << "\nTest of L1GctMap " << (testPass ? "passed!" : "failed!") << endl; return 0; }
{'dir': 'cpp', 'id': '447250', 'max_stars_count': '852', 'max_stars_repo_name': 'ckamtsikis/cmssw', 'max_stars_repo_path': 'L1Trigger/GlobalCaloTrigger/test/testGctMap.cpp', 'n_tokens_mistral': 388, 'n_tokens_neox': 366, 'n_words': 117}
package de.digitalcollections.iiif.hymir.config; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Optional; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix = "custom.iiif.headers") public class CustomResponseHeaders { private List<ResponseHeader> all = new ArrayList<>(); private HashMap<String, List<ResponseHeader>> image = new HashMap<>(); private HashMap<String, List<ResponseHeader>> presentation = new HashMap<>(); // custom.iiif.headers.all public void setAll(List<ResponseHeader> all) { this.all = all; } public List<ResponseHeader> getAll() { return this.all; } // custom.iiif.headers.image public HashMap<String, List<ResponseHeader>> getImage() { return image; } public void setImage(HashMap<String, List<ResponseHeader>> image) { this.image = image; } // custom.iiif.headers.presentation public void setPresentation(HashMap<String, List<ResponseHeader>> presentation) { this.presentation = presentation; } public HashMap<String, List<ResponseHeader>> getPresentation() { return presentation; } public List<ResponseHeader> forImageTile() { List<ResponseHeader> result = new ArrayList<>(); Optional.ofNullable(all).ifPresent(result::addAll); Optional.ofNullable(image.get("image")).ifPresent(result::addAll); return result; } public List<ResponseHeader> forImageInfo() { List<ResponseHeader> result = new ArrayList<>(); Optional.ofNullable(all).ifPresent(result::addAll); Optional.ofNullable(image.get("info")).ifPresent(result::addAll); return result; } public List<ResponseHeader> forPresentationManifest() { List<ResponseHeader> result = new ArrayList<>(); Optional.ofNullable(all).ifPresent(result::addAll); Optional.ofNullable(presentation.get("manifest")).ifPresent(result::addAll); return result; } public List<ResponseHeader> forPresentationCollection() { List<ResponseHeader> result = new ArrayList<>(); Optional.ofNullable(all).ifPresent(result::addAll); Optional.ofNullable(presentation.get("collection")).ifPresent(result::addAll); return result; } public List<ResponseHeader> forPresentationAnnotationList() { List<ResponseHeader> result = new ArrayList<>(); Optional.ofNullable(all).ifPresent(result::addAll); Optional.ofNullable(presentation.get("annotationList")).ifPresent(result::addAll); return result; } public static class ResponseHeader { private String name; private String value; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
{'dir': 'java', 'id': '12436177', 'max_stars_count': '25', 'max_stars_repo_name': 'cmahnke/iiif-server-hymir', 'max_stars_repo_path': 'src/main/java/de/digitalcollections/iiif/hymir/config/CustomResponseHeaders.java', 'n_tokens_mistral': 833, 'n_tokens_neox': 811, 'n_words': 164}
<reponame>axules/fuzzy-tools import { matchString } from './matchString'; import { matchList } from './matchList'; import { match } from './match'; import { filter } from './filter'; export { match, matchString, matchList, filter }; export default { match, matchString, matchList, filter };
{'dir': 'javascript', 'id': '18114926', 'max_stars_count': '3', 'max_stars_repo_name': 'axules/fuzzy-tools', 'max_stars_repo_path': 'src/index.js', 'n_tokens_mistral': 101, 'n_tokens_neox': 99, 'n_words': 28}
<reponame>userAhmedDean/ahmmmmedddddddddddddddddddddddddddddd const Discord = require('discord.js'); const fs = require('fs'); const client = new Discord.Client(); var prefix = "#" client.on('message', message => { if (!message.content.startsWith(prefix)) return; var args = message.content.split(' ').slice(1); var argresult = args.join(' '); if (message.author.id !== "5<PASSWORD>") return; if (message.content.startsWith(prefix + 'setwatch')) { client.user.setActivity(argresult, {type: 'WATCHING'}) console.log('test' + argresult); message.channel.sendMessage(`Watch Now: **${argresult}`) } if (message.content.startsWith(prefix + 'setlis')) { client.user.setActivity(argresult, {type: 'LISTENING'}) console.log('test' + argresult); message.channel.sendMessage(`LISTENING Now: **${argresult}`) } if (message.content.startsWith(prefix + 'setname')) { client.user.setUsername(argresult).then message.channel.sendMessage(`Username Changed To **${argresult}**`) return message.reply("You Can change the username 2 times per hour"); } if (message.content.startsWith(prefix + 'setavatar')) { client.user.setAvatar(argresult); message.channel.sendMessage(`Avatar Changed Successfully To **${argresult}**`); } if (message.content.startsWith(prefix + 'setT')) { client.user.setGame(argresult, "https://www.twitch.tv/peery13"); console.log('test' + argresult); message.channel.sendMessage(`Streaming: **${argresult}`) } if (message.content.startsWith(prefix + 'setgame')) { client.user.setGame(argresult); console.log('test' + argresult); message.channel.sendMessage(`Playing: **${argresult}`) } }); client.login('NTIyMjUzOTM0NjYwNjgxNzI5.D<KEY>');
{'dir': 'javascript', 'id': '5977685', 'max_stars_count': '0', 'max_stars_repo_name': 'userAhmedDean/ahmmmmedddddddddddddddddddddddddddddd', 'max_stars_repo_path': 'bot.js', 'n_tokens_mistral': 624, 'n_tokens_neox': 612, 'n_words': 96}
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Author: kerlomz <<EMAIL>> class LayoutGUI(object): def __init__(self, layout, window_width): self.layout = layout self.window_width = window_width def widget_from_right(self, src, target, width, height, tiny_space=False): target_edge = self.object_edge_info(target) src.place( x=self.window_width - width - self.layout['global']['space']['x'], y=target_edge['edge_y'] + self.layout['global']['tiny_space' if tiny_space else 'space']['y'], width=width, height=height ) def before_widget(self, src, target, width, height, tiny_space=False): target_edge = self.object_edge_info(target) src.place( x=target_edge['x'] - width - self.layout['global']['tiny_space' if tiny_space else 'space']['x'], y=target_edge['y'], width=width, height=height ) @staticmethod def object_edge_info(obj): info = obj.place_info() x = int(info['x']) y = int(info['y']) edge_x = int(info['x']) + int(info['width']) edge_y = int(info['y']) + int(info['height']) return {'x': x, 'y': y, 'edge_x': edge_x, 'edge_y': edge_y} def inside_widget(self, src, target, width, height): target_edge = self.object_edge_info(target) src.place( x=target_edge['x'] + self.layout['global']['space']['x'], y=target_edge['y'] + self.layout['global']['space']['y'], width=width, height=height ) def below_widget(self, src, target, width, height, tiny_space=False): target_edge = self.object_edge_info(target) src.place( x=target_edge['x'], y=target_edge['edge_y'] + self.layout['global']['tiny_space' if tiny_space else 'space']['y'], width=width, height=height ) def next_to_widget(self, src, target, width, height, tiny_space=False, offset_y=0): target_edge = self.object_edge_info(target) src.place( x=target_edge['edge_x'] + self.layout['global']['tiny_space' if tiny_space else 'space']['x'], y=target_edge['y'] + offset_y, width=width, height=height )
{'dir': 'python', 'id': '7168809', 'max_stars_count': '2548', 'max_stars_repo_name': 'liepeiming/captcha_trainer', 'max_stars_repo_path': 'gui/utils.py', 'n_tokens_mistral': 725, 'n_tokens_neox': 716, 'n_words': 136}
import React, { useMemo, useRef, useEffect, useCallback } from 'react' import { useFrame } from 'react-three-fiber' import { smoothstep, smootherstep } from 'three/src/math/MathUtils' import { gsap } from 'gsap' import * as THREE from 'three' import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js" import { GUI } from 'dat.gui' import fragmentShader from './shaders/progress/fragmentShader2.glsl' import vertexShader from './shaders/progress/vertexShader2.glsl' export default function Progress2({ mousePos, progressContainer, scrollRef, state, sliderProgress }) { // Refs const materialRef = useRef() const sphereRef = useRef() const startProgress = useRef() const pepperArray = useRef() const animationProgress = useRef() animationProgress.current = { t: 0 } const pepperRotation = useRef() pepperRotation.current = { rotX: 0, rotZ: 0 } const spherePosition = useRef() spherePosition.current = { x: 250, y: -50 } const offsetRef = useRef() offsetRef.current = { x: spherePosition.current.x, y: spherePosition.current.y } const pepperCount = useRef() const geometryRef = useRef() const lightA = useRef() const lightB = useRef() const progressContainerRect = useRef() const completed = useRef({ "BRIEFING": { size: 1, color: "#000" }, "DESIGN": { uDisplacementFrequency: 0.01, uDisplacementStrength: 10 }, "DEVELOPMENT": { uDistortionFrequency: 0.005, uDistortionStrength: 50 }, "FEEDBACK": { uFresnelOffset: -0.5, uFresnelMultiplier: 0.9 } }) // LIGHTS lightA.current = {} lightA.current.intensity = 0.5 lightA.current.color = {} lightA.current.color.value = '#fff' lightA.current.color.instance = new THREE.Color(lightA.current.color.value) lightA.current.spherical = new THREE.Spherical(1, 0.615, 2.049) lightB.current = {} lightB.current.intensity = 0.5 lightB.current.color = {} lightB.current.color.value = '#fff' lightB.current.color.instance = new THREE.Color(lightB.current.color.value) lightB.current.spherical = new THREE.Spherical(1, 2.561, - 1.844) // OBJLoader // const loader = new OBJLoader() // loader.load('/models/paprika2.obj', // (obj) => { // let positionPepper = obj.children[0].geometry.attributes.position // let finalPosition = positionPepper // pepperCount.current = finalPosition.count // pepperArray.current = finalPosition // }, (xhr) => { // // the request is in progress // console.log(xhr) // }, // (err) => { // // something went wrong // console.error("loading .obj went wrong, ", err) // } // ) // Sphere positions // let N = 30000 // let positions = useMemo(() => { // let positions = new Float32Array(N * 3) // let inc = Math.PI * (3 - Math.sqrt(5)) // let off = 4 / N // let rad = 180 // for (let i = 0; i < N; i++) { // let y = i * off - 1 + (off / 2) // let r = Math.sqrt(1 - y * y) // let phi = i * inc // positions[3 * i] = rad * Math.cos(phi) * r; // positions[3 * i + 1] = rad * y; // positions[3 * i + 2] = rad * Math.sin(phi) * r; // } // return positions // }) // let t = 0; // let f = 0.002; // let a = 3; // const graph = useCallback((x, z) => { // return Math.sin(f * (x ** 2 + z ** 2 + t)) * a; // }, [t, f, a]) // const count = 100 // const sep = 3 // let positions = useMemo(() => { // let positions = [] // for (let xi = 0; xi < count; xi++) { // for (let zi = 0; zi < count; zi++) { // let x = sep * (xi - count / 2); // let z = sep * (zi - count / 2); // let y = graph(x, z); // positions.push(x, y, z); // } // } // return new Float32Array(positions) // }); // useEffect // const gui = new GUI() useEffect(() => { // const folder = gui.addFolder("Displacement") // folder.add(materialRef.current.uniforms.uDistortionFrequency, 'value', 0, 0.05, 0.001) // folder.add(materialRef.current.uniforms.uDistortionStrength, 'value', 0, 200, 1) // folder.add(materialRef.current.uniforms.uDisplacementFrequency, 'value', 0, 0.05, 0.001) // folder.add(materialRef.current.uniforms.uDisplacementStrength, 'value', 0, 200, 1) // // folder.open() // const fresnelFolder = gui.addFolder("FresnelFolder") // fresnelFolder.add(materialRef.current.uniforms.uFresnelOffset, 'value', -3, 3, 0.1) // fresnelFolder.add(materialRef.current.uniforms.uFresnelMultiplier, 'value', 0, 4, 0.1) // fresnelFolder.add(materialRef.current.uniforms.uFresnelPower, 'value', 0, 3, 0.1) // fresnelFolder.open() progressContainerRect.current = progressContainer.current.getBoundingClientRect() startProgress.current = 0 materialRef.current.uniforms.uLightAPosition.value.setFromSpherical(lightA.current.spherical) materialRef.current.uniforms.uLightBPosition.value.setFromSpherical(lightB.current.spherical) geometryRef.current.computeTangents() }, []) // useFrame useFrame(({ clock }, delta) => { const tick = clock.getElapsedTime() let normalMouse = { x: (mousePos.x + window.innerWidth / 2) / window.innerWidth, y: (mousePos.y + window.innerHeight / 2) / window.innerHeight } // uniforms materialRef.current.uniforms.time.value = tick * 0.5 materialRef.current.uniforms.uMouse.value = new THREE.Vector2(mousePos.x, mousePos.y) materialRef.current.uniforms.uMouseNormal.value = new THREE.Vector2(mousePos.x + window.innerWidth / 2, mousePos.y + window.innerHeight / 2) // materialRef.current.uniforms.uAnimationProgress.value = animationProgress.current.t sphereRef.current.position.y = scrollRef.current + offsetRef.current.y sphereRef.current.position.x = offsetRef.current.x materialRef.current.uniforms.uLightBColor.value = new THREE.Color(lightB.current.color.value) materialRef.current.uniforms.uLightAColor.value = new THREE.Color(lightA.current.color.value) gsap.to(sphereRef.current.position, { y: scrollRef.current - progressContainerRect.current.top + window.innerHeight / 2 - progressContainerRect.current.height / 2.5, x: progressContainerRect.current.left - window.innerWidth / 2 + progressContainerRect.current.width / 2.5, duration: 0 }) // DIFFERENT STATES if (state.current == "BRIEFING") { // DEFAULTS gsap.to(materialRef.current.uniforms.uDisplacementFrequency, { value: completed.current["DESIGN"].uDisplacementFrequency }) gsap.to(materialRef.current.uniforms.uDisplacementStrength, { value: completed.current["DESIGN"].uDisplacementStrength }) gsap.to(materialRef.current.uniforms.uDistortionFrequency, { value: completed.current["DEVELOPMENT"].uDistortionFrequency }) gsap.to(materialRef.current.uniforms.uDistortionStrength, { value: completed.current["DEVELOPMENT"].uDistortionStrength }) gsap.to(materialRef.current.uniforms.uFresnelOffset, { value: completed.current["FEEDBACK"].uFresnelOffset }) gsap.to(materialRef.current.uniforms.uFresnelMultiplier, { value: completed.current["FEEDBACK"].uFresnelMultiplier }) // CHANGING gsap.to(materialRef.current.uniforms.uSize, { value: sliderProgress.x / 2 + 0.5 }) completed.current["BRIEFING"].size = sliderProgress.x / 2 + 0.5 materialRef.current.uniforms.uColor.value = new THREE.Color(`hsl(${sliderProgress.y * 360},70%,8%)`) completed.current["BRIEFING"].color = `hsl(${sliderProgress.y * 360},70%,8%)` } else if (state.current == "DESIGN") { // DEFAULTS gsap.to(materialRef.current.uniforms.uSize, { value: completed.current["BRIEFING"].size }) materialRef.current.uniforms.uColor.value = new THREE.Color(completed.current["BRIEFING"].color) gsap.to(materialRef.current.uniforms.uDistortionFrequency, { value: completed.current["DEVELOPMENT"].uDistortionFrequency }) gsap.to(materialRef.current.uniforms.uDistortionStrength, { value: completed.current["DEVELOPMENT"].uDistortionStrength }) gsap.to(materialRef.current.uniforms.uFresnelOffset, { value: completed.current["FEEDBACK"].uFresnelOffset }) gsap.to(materialRef.current.uniforms.uFresnelMultiplier, { value: completed.current["FEEDBACK"].uFresnelMultiplier }) // CHANGING gsap.to(materialRef.current.uniforms.uDisplacementFrequency, { value: sliderProgress.y * 0.01 + 0.01 }) completed.current["DESIGN"].uDisplacementFrequency = sliderProgress.y * 0.01 + 0.01 gsap.to(materialRef.current.uniforms.uDisplacementStrength, { value: sliderProgress.x * 50 + 10 }) completed.current["DESIGN"].uDisplacementStrength = sliderProgress.x * 50 + 10 } else if (state.current == "DEVELOPMENT") { // DEFAULTS gsap.to(materialRef.current.uniforms.uSize, { value: completed.current["BRIEFING"].size }) materialRef.current.uniforms.uColor.value = new THREE.Color(completed.current["BRIEFING"].color) gsap.to(materialRef.current.uniforms.uDisplacementFrequency, { value: completed.current["DESIGN"].uDisplacementFrequency }) gsap.to(materialRef.current.uniforms.uDisplacementStrength, { value: completed.current["DESIGN"].uDisplacementStrength }) gsap.to(materialRef.current.uniforms.uFresnelOffset, { value: completed.current["FEEDBACK"].uFresnelOffset }) gsap.to(materialRef.current.uniforms.uFresnelMultiplier, { value: completed.current["FEEDBACK"].uFresnelMultiplier }) // CHANGING gsap.to(materialRef.current.uniforms.uDistortionFrequency, { value: sliderProgress.y * 0.006 + 0.005 }) completed.current["DEVELOPMENT"].uDistortionFrequency = sliderProgress.y * 0.006 + 0.005 gsap.to(materialRef.current.uniforms.uDistortionStrength, { value: sliderProgress.x * 100 + 50 }) completed.current["DEVELOPMENT"].uDistortionStrength = sliderProgress.x * 100 + 50 } else if (state.current == "FEEDBACK") { // DEFAULTS gsap.to(materialRef.current.uniforms.uSize, { value: completed.current["BRIEFING"].size }) materialRef.current.uniforms.uColor.value = new THREE.Color(completed.current["BRIEFING"].color) gsap.to(materialRef.current.uniforms.uDisplacementFrequency, { value: completed.current["DESIGN"].uDisplacementFrequency }) gsap.to(materialRef.current.uniforms.uDisplacementStrength, { value: completed.current["DESIGN"].uDisplacementStrength }) gsap.to(materialRef.current.uniforms.uDistortionFrequency, { value: completed.current["DEVELOPMENT"].uDistortionFrequency }) gsap.to(materialRef.current.uniforms.uDistortionStrength, { value: completed.current["DEVELOPMENT"].uDistortionStrength }) // CHANGING gsap.to(materialRef.current.uniforms.uFresnelOffset, { value: sliderProgress.x - 0.5 }) completed.current["FEEDBACK"].uFresnelOffset = sliderProgress.x - 0.5 gsap.to(materialRef.current.uniforms.uFresnelMultiplier, { value: sliderProgress.y * 1 + 0.9 }) completed.current["FEEDBACK"].uFresnelMultiplier = sliderProgress.y * 1 + 0.9 } }) return ( <mesh ref={sphereRef} position={[280, -60, -10]}> <sphereGeometry ref={geometryRef} args={[446 / 3, 256, 256]} /> {/* <meshBasicMaterial /> */} {/* <bufferGeometry ref={bufferGeometryRef} attach='geometry' > <bufferAttribute attachObject={['attributes', 'position']} array={positions} count={positions.length / 3} itemSize={3} /> </bufferGeometry> */} <shaderMaterial ref={materialRef} uniforms={{ time: { value: 0 }, uMouse: { value: new THREE.Vector2(mousePos.x, mousePos.y) }, uMouseNormal: { value: new THREE.Vector2(mousePos.x, mousePos.y) }, uAnimationProgress: { value: 0 }, uLightAColor: { value: lightA.current.color.instance }, uLightAPosition: { value: new THREE.Vector3(1, 1, 0) }, uLightAIntensity: { value: lightA.current.intensity }, uSubdivision: { value: new THREE.Vector2(256, 256) }, uLightBColor: { value: lightB.current.color.instance }, uLightBPosition: { value: new THREE.Vector3(- 1, - 1, 0) }, uLightBIntensity: { value: lightB.current.intensity }, // uFresnelOffset: { value: 0.8 }, // uFresnelMultiplier: { value: 0.2 }, // uFresnelPower: { value: 0.593 }, uFresnelOffset: { value: -0.5 }, uFresnelMultiplier: { value: 0.9 }, uFresnelPower: { value: 1 }, uSize: { value: 0. }, uColor: { value: new THREE.Color("#000") }, uLightAOffset: { value: new THREE.Vector3(0, 0, 0) }, uLightBOffset: { value: new THREE.Vector3(0, 0, 0) }, uDistortionFrequency: { value: 0.005 }, uDistortionStrength: { value: 150 }, uDisplacementFrequency: { value: 0.01520 }, uDisplacementStrength: { value: 15 }, uOffset: { value: new THREE.Vector3() }, }} defines={{ USE_TANGENT: '' }} vertexShader={vertexShader} fragmentShader={fragmentShader} /> </mesh> ) }
{'dir': 'javascript', 'id': '2938709', 'max_stars_count': '0', 'max_stars_repo_name': 'thomasmeylaers/FPD', 'max_stars_repo_path': 'src/webgl/Progress2.js', 'n_tokens_mistral': 4655, 'n_tokens_neox': 4293, 'n_words': 747}
<filename>frontend/e2e/authenticated/christmas-trees/xmas-tree-application.e2e-spec.ts import { browser, element, by, Key } from 'protractor'; import { ChristmasTreeOrderConfirmation } from './christmas-tree-form-confirmation.po'; import { ChristmasTreeForm } from './christmas-tree-form.po'; describe('Apply for a Christmas tree permit', () => { let christmasTreeForm: ChristmasTreeForm; let confirmPage: ChristmasTreeOrderConfirmation; const forestId = 'mthood'; describe('fill out basic user info', () => { beforeEach(() => { christmasTreeForm = new ChristmasTreeForm(); }); it('should display the permit name in the header', () => { christmasTreeForm.navigateTo(forestId); expect<any>(element(by.css('app-root h1')).getText()).toEqual('Buy a Christmas tree permit'); }); it('should show the breadcrumb', () => { expect<any>(element(by.css('nav')).isPresent()).toBeTruthy(); }); it('should show all fields as invalid if submitted without input', () => { christmasTreeForm.submit().click(); browser.sleep(500); }); it('should require a first name', () => { christmasTreeForm.navigateTo(forestId); expect<any>(christmasTreeForm.firstName().isDisplayed()).toBeTruthy(); christmasTreeForm.submit().click(); browser.sleep(1000); expect<any>(christmasTreeForm.firstName().isDisplayed()).toBeTruthy(); expect<any>(christmasTreeForm.firstNameError().isDisplayed()).toBeTruthy(); }); it('should let the user enter a first name', () => { christmasTreeForm.firstName().sendKeys('Melvin'); christmasTreeForm.submit().click(); expect<any>(christmasTreeForm.firstNameError().isPresent()).toBeFalsy(); }); it('should require a last name', () => { expect<any>(christmasTreeForm.lastName().isDisplayed()).toBeTruthy(); christmasTreeForm.submit().click(); browser.sleep(1000); expect<any>(christmasTreeForm.lastName().isDisplayed()).toBeTruthy(); expect<any>(christmasTreeForm.lastNameError().isDisplayed()).toBeTruthy(); }); it('should let the user enter a last name', () => { christmasTreeForm.lastName().sendKeys('Apharce'); christmasTreeForm.submit().click(); expect<any>(christmasTreeForm.lastNameError().isPresent()).toBeFalsy(); }); it('should display an error for an invalid email address', () => { expect<any>(christmasTreeForm.email().isDisplayed()).toBeTruthy(); christmasTreeForm.email().sendKeys('aaaaaa'); expect<any>(christmasTreeForm.emailError().isDisplayed()).toBeTruthy(); christmasTreeForm.email().sendKeys('@aaa.com'); expect<any>(christmasTreeForm.emailError().isPresent()).toBeFalsy(); }); it('should display an error for an invalid email address confirmation', () => { expect<any>(christmasTreeForm.emailConfirmation().isDisplayed()).toBeTruthy(); christmasTreeForm.email().clear(); christmasTreeForm.email().sendKeys('<EMAIL>aa<EMAIL>'); christmasTreeForm.emailConfirmation().sendKeys('aaaaaa'); expect<any>(christmasTreeForm.emailConfirmationError().isDisplayed()).toBeTruthy(); expect<any>(christmasTreeForm.emailGroupError().isPresent()).toBeTruthy(); christmasTreeForm.emailConfirmation().sendKeys('@aaa.com'); expect<any>(christmasTreeForm.emailConfirmationError().isPresent()).toBeFalsy(); expect<any>(christmasTreeForm.emailGroupError().isPresent()).toBeFalsy(); }); it('should display an error for an invalid tree amount', () => { expect<any>(christmasTreeForm.treeAmount().isDisplayed()).toBeTruthy(); christmasTreeForm.treeAmount().clear(); christmasTreeForm.treeAmount().sendKeys('-'); expect<any>(christmasTreeForm.treeAmountError().isDisplayed()).toBeTruthy(); }); it('should display an error for an 0 tree amount', () => { expect<any>(christmasTreeForm.treeAmountError().isDisplayed()).toBeTruthy(); christmasTreeForm.treeAmount().clear(); christmasTreeForm.treeAmount().sendKeys('0'); expect<any>(christmasTreeForm.treeAmountError().isDisplayed()).toBeTruthy(); }); it('should display an error for a tree amount great than max', () => { christmasTreeForm.treeAmount().clear(); christmasTreeForm.treeAmount().sendKeys('9'); expect<any>(christmasTreeForm.treeAmountError().isDisplayed()).toBeTruthy(); }); it('should let the user enter a valid tree amount', () => { christmasTreeForm.treeAmount().clear(); christmasTreeForm.treeAmount().sendKeys('1'); expect<any>(christmasTreeForm.treeAmountError().isPresent()).toBeFalsy(); }); it('should calculate total cost', () => { christmasTreeForm.navigateTo(forestId); christmasTreeForm.fillOutForm(); browser.sleep(500); expect<any>(element(by.id('total-cost')).getText()).toEqual('$10'); }); }); describe('application rules', () => { beforeAll(() => { christmasTreeForm = new ChristmasTreeForm(); christmasTreeForm.navigateTo(forestId); browser.sleep(500); christmasTreeForm.fillOutForm(); browser.sleep(500); }); it('should have a Next button', () => { expect(christmasTreeForm.submit().isPresent()).toBeTruthy(); christmasTreeForm.submit().click(); }); it('should show the rules section after next is clicked', () => { expect<any>(christmasTreeForm.treeApplicationRulesContainer().getText()).toContain( 'Christmas trees may be taken from the Mt. Hood National Forest' ); }); it('should make the user accept the rules before they can submit', () => { christmasTreeForm.submitRules().click(); expect<any>(christmasTreeForm.rulesAcceptedError().isDisplayed()).toBeTruthy(); }); it('should redirect to mock pay.gov on application submit', () => { christmasTreeForm.navigateTo(forestId); christmasTreeForm.fillOutFormAndSubmit(); browser.sleep(1500); expect(browser.getCurrentUrl()).toContain('http://localhost:4200/mock-pay-gov'); }); it('should redirect to confirmation page from mock pay.gov on success', () => { element(by.id('credit-card-number')).sendKeys('1100000000000123'); christmasTreeForm.mockPayGovSubmit().click(); browser.sleep(1500); expect(browser.getCurrentUrl()).toContain( `http://localhost:4200/christmas-trees/forests/${forestId}/applications/permits` ); }); }); describe('confirmation page', () => { beforeAll(() => { confirmPage = new ChristmasTreeOrderConfirmation(); christmasTreeForm = new ChristmasTreeForm(); christmasTreeForm.navigateTo(forestId); browser.sleep(1000); expect(browser.getCurrentUrl()).toContain(`http://localhost:4200/christmas-trees/forests/${forestId}/applications`); christmasTreeForm.fillOutFormAndSubmit(); browser.sleep(1000); expect(browser.getCurrentUrl()).toContain('http://localhost:4200/mock-pay-gov'); element(by.id('credit-card-number')).sendKeys('1100000000000123'); christmasTreeForm.mockPayGovSubmit().click(); browser.sleep(1000); expect(browser.getCurrentUrl()).toContain( `http://localhost:4200/christmas-trees/forests/${forestId}/applications/permits` ); browser.sleep(1000); }); it('should show confirmation details', () => { expect<any>(confirmPage.confirmationDetails().isDisplayed()).toBeTruthy(); }); it('should show the breadcrumb', () => { expect<any>(element(by.css('nav')).isPresent()).toBeTruthy(); }); it('should show the order summary', () => { expect<any>(confirmPage.orderSummary().isDisplayed()).toBeTruthy(); }); it('should show additional information', () => { expect<any>(confirmPage.additionalInfo().isDisplayed()).toBeTruthy(); }); it('should show the print permit button', () => { expect<any>(confirmPage.printPermitButton().isDisplayed()).toBeTruthy(); }); it('should show error page if credit card error', () => { christmasTreeForm.navigateTo(forestId); christmasTreeForm.fillOutFormAndSubmit(); browser.sleep(900); element(by.id('credit-card-number')).sendKeys('0000000000000123'); christmasTreeForm.mockPayGovSubmit().click(); browser.sleep(1900); expect<any>(element(by.id('pay-gov-errors')).isDisplayed()).toBeTruthy(); christmasTreeForm.navigateTo(forestId); }); }); describe('pay gov token errors', () => { beforeEach(() => { confirmPage = new ChristmasTreeOrderConfirmation(); christmasTreeForm = new ChristmasTreeForm(); christmasTreeForm.navigateTo(forestId); }); it('should show 500 error if first name is unknown', () => { christmasTreeForm.fillOutFormAndSubmit('unknown', '2'); expect<any>(element(by.css('.usa-alert-heading')).getText()).toEqual( 'Sorry, we were unable to process your request. Please try again.' ); }); it('should show 500 error if first name is duplicate', () => { christmasTreeForm.fillOutFormAndSubmit('duplicate', '1'); browser.sleep(500); expect<any>(element(by.css('.usa-alert-heading')).getText()).toEqual( 'Sorry, we were unable to process your request. Please try again.' ); }); }); describe('repopulating fields after cancel', () => { beforeAll(() => { confirmPage = new ChristmasTreeOrderConfirmation(); christmasTreeForm = new ChristmasTreeForm(); christmasTreeForm.navigateTo(forestId); christmasTreeForm.fillOutFormAndSubmit(); browser.sleep(1500); }); let permitId = ''; it('should redirect to application on cancel and display a message telling the user what to do', () => { element(by.css('.usa-button-grey')).click(); browser.sleep(1500); expect(christmasTreeForm.cancelInfo().isDisplayed()).toBeTruthy(); browser.getCurrentUrl().then(url => { permitId = url.split('/')[8]; }); }); it('should have the first name prefilled', () => { expect(christmasTreeForm.firstName().getAttribute('value')).toBe('Sarah'); }); it('should have the last name prefilled', () => { expect(christmasTreeForm.lastName().getAttribute('value')).toBe('Bell'); }); it('should have the email address prefilled', () => { expect(christmasTreeForm.email().getAttribute('value')).toBe('<EMAIL>'); }); it('should have the quantity prefilled', () => { expect(christmasTreeForm.treeAmount().getAttribute('value')).toBe('2'); }); it('should have the cost calculated', () => { expect(christmasTreeForm.permitCost().getText()).not.toEqual('$0'); }); it('should be hide message telling the user what to do next if they resubmit with errors', () => { christmasTreeForm.submit().click(); expect(christmasTreeForm.cancelInfo().isPresent()).toBeFalsy(); }); }); });
{'dir': 'typescript', 'id': '6173893', 'max_stars_count': '27', 'max_stars_repo_name': '18F/fs-open-forest-platform', 'max_stars_repo_path': 'frontend/e2e/authenticated/christmas-trees/xmas-tree-application.e2e-spec.ts', 'n_tokens_mistral': 3312, 'n_tokens_neox': 3135, 'n_words': 499}
<gh_stars>10-100 package sap.ciep.sdi.webserviceadapter; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import com.sap.hana.dp.adapter.sdk.AdapterException; import com.sap.hana.dp.adapter.sdk.AdapterRowSet; public abstract class WebserviceResponseRecord { protected static Logger logger = LogManager.getLogger("WebserviceResponseRecord"); /** * Append this record to response to HANA. * @param rows * @throws AdapterException */ public abstract void appendTo(AdapterRowSet rows) throws AdapterException; }
{'dir': 'java', 'id': '13689939', 'max_stars_count': '25', 'max_stars_repo_name': 'RonaldKonijnenburg/hana-native-adapters', 'max_stars_repo_path': 'WebserviceAdapter/src/sap/ciep/sdi/webserviceadapter/WebserviceResponseRecord.java', 'n_tokens_mistral': 183, 'n_tokens_neox': 171, 'n_words': 38}
import { FunctionDeclaration } from '../components/general/FunctionDeclaration'; import { VariableStatement } from '../components/general/VariableStatement'; import { Decorator } from '../components/decorator/Decorator'; import { Constructor } from '../components/classDeclaration/members/constructor/Constructor'; import { PropertyDeclaration } from '../components/classDeclaration/members/property/PropertyDeclaration'; import { Method } from '../components/classDeclaration/members/method/Method'; import { ClassDeclaration } from '../components/classDeclaration/ClassDeclaration'; import { InterfaceDeclaration } from '../components/interfaceDeclaration/InterfaceDeclaration'; import { InterfaceMethod } from '../components/interfaceDeclaration/members/method/InterfaceMethod'; import { TSFile } from '../components/TSFile'; import { InterfaceProperty } from '../components/interfaceDeclaration/members/InterfaceProperty'; export function mergeImports(baseFile: TSFile, patchFile: TSFile) { let exists: boolean; if (baseFile.getImports().length === 0) { patchFile.getImports().forEach((patchImportClause) => { baseFile.addImport(patchImportClause); }); } else { patchFile.getImports().forEach((patchImportClause) => { exists = false; baseFile.getImports().forEach((importClause) => { if (importClause.getModule() === patchImportClause.getModule()) { importClause.merge(patchImportClause); exists = true; } }); if (!exists) { baseFile.addImport(patchImportClause); } }); } } export function mergeExports(baseFile: TSFile, patchFile: TSFile) { let exists: boolean; if (baseFile.getExports().length === 0) { patchFile.getExports().forEach((patchExportClause) => { baseFile.addExport(patchExportClause); }); } else { patchFile.getExports().forEach((patchExportClause) => { exists = false; baseFile.getExports().forEach((importClause) => { if (importClause.getModule() === patchExportClause.getModule()) { importClause.merge(patchExportClause); exists = true; } }); if (!exists) { baseFile.addExport(patchExportClause); } }); } } export function mergeExpressions( baseFile: TSFile, patchFile: TSFile, patchOverrides, ) { let exists: boolean; if (baseFile.getExpressions().length === 0) { patchFile.getExpressions().forEach((patchExpressionStatement) => { baseFile.addExpression(patchExpressionStatement); }); } else { patchFile.getExpressions().forEach((patchExpressionStatement) => { exists = false; baseFile.getExpressions().forEach((expressionStatement) => { if ( expressionStatement.getName() === patchExpressionStatement.getName() ) { expressionStatement.merge(patchExpressionStatement, patchOverrides); exists = true; } }); if (!exists) { baseFile.addExpression(patchExpressionStatement); } }); } } export function mergeClass( baseClass: ClassDeclaration, patchClass: ClassDeclaration, patchOverrides: boolean, ) { let exists: boolean; if (patchOverrides) { baseClass.setHeritages(patchClass.getHeritages()); } mergeHeritages( baseClass.getHeritages(), patchClass.getHeritages(), patchOverrides, ); mergeComments( baseClass.getComments(), patchClass.getComments(), patchOverrides, ); mergeDecorators( baseClass.getDecorators(), patchClass.getDecorators(), patchOverrides, ); mergeProperties( baseClass.getProperties(), patchClass.getProperties(), patchOverrides, ); mergeConstructor( baseClass.getConstructor(), patchClass.getConstructor(), patchOverrides, ); mergeMethods(baseClass.getMethods(), patchClass.getMethods(), patchOverrides); } export function mergeInterface( baseInterface: InterfaceDeclaration, patchInterface: InterfaceDeclaration, patchOverrides: boolean, ) { let exists: boolean; if (patchOverrides) { baseInterface.setModifiers(patchInterface.getModifiers()); } mergeHeritages( baseInterface.getHeritages(), patchInterface.getHeritages(), patchOverrides, ); mergeComments( baseInterface.getComments(), patchInterface.getComments(), patchOverrides, ); mergeInterfaceProperties( baseInterface.getProperties(), patchInterface.getProperties(), patchOverrides, ); mergeInterfaceMethods( baseInterface.getMethods(), patchInterface.getMethods(), patchOverrides, ); baseInterface.setIndex( mergeIndexSignature( baseInterface.getIndex(), patchInterface.getIndex(), patchOverrides, ), ); } export function mergeDecorators( baseDecorators: Decorator[], patchDecorators: Decorator[], patchOverrides: boolean, ) { let exists: boolean; patchDecorators.forEach((patchDecorator) => { exists = false; baseDecorators.forEach((decorator) => { if (patchDecorator.getIdentifier() === decorator.getIdentifier()) { exists = true; decorator.merge(patchDecorator, patchOverrides); } }); if (!exists) { baseDecorators.push(patchDecorator); } }); } export function mergeVariableProperties( baseVariableProperties: String[], patchVariableProperties: String[], patchOverrides: boolean ) { if (patchOverrides) { return patchVariableProperties; } patchVariableProperties.forEach(property => { if (baseVariableProperties.indexOf(property) == -1) { baseVariableProperties.push(property); } }); } export function mergeProperties( baseProperties: PropertyDeclaration[], patchProperties: PropertyDeclaration[], patchOverrides: boolean, ) { let exists: boolean; patchProperties.forEach((patchProperty) => { exists = false; baseProperties.forEach((property) => { if (patchProperty.getIdentifier() === property.getIdentifier()) { exists = true; property.merge(patchProperty, patchOverrides); } }); if (!exists) { baseProperties.push(patchProperty); } }); } export function mergeConstructor( baseConstructor: Constructor, patchConstructor: Constructor, patchOverrides: boolean, ) { mergeMethod(baseConstructor, patchConstructor, patchOverrides); } export function mergeMethods( baseMethods: Method[], patchMethods: Method[], patchOverrides, ) { let exists: boolean; patchMethods.forEach((patchMethod) => { exists = false; baseMethods.forEach((method) => { if (patchMethod.getIdentifier() === method.getIdentifier()) { exists = true; mergeMethod(method, patchMethod, patchOverrides); } }); if (!exists) { baseMethods.push(patchMethod); } }); } export function mergeIndexSignature( baseIndex: string, patchIndex: string, patchOverrides: boolean, ): string { if (patchOverrides) { baseIndex = patchIndex; } return baseIndex; } export function mergeHeritages( baseHeritages: String[], patchHeritages: String[], patchOverrides: boolean, ) { let exists: boolean; if (patchHeritages.length > 0) { // If there is no extension on base, let's add it directly if (baseHeritages.length <= 0) { baseHeritages[0] = patchHeritages[0]; } else { // Currently we only support to either merge extensions or implements let patchHeritage: String = patchHeritages[0]; let baseHeritage: String = baseHeritages[0]; // We get the string "extends" or "implements" let inheritanceValue: String = baseHeritage.match(/\s*([\w\-]+)/)[0]; // We only need the interfaces names: extends a,b,c (let's remove "extends") patchHeritage = patchHeritage.trim().replace(/\s*([\w\-]+)/, ''); baseHeritage = baseHeritage.trim().replace(/\s*([\w\-]+)/, ''); // split by comma to get the different interfaces let patchHeritageNames: String[] = patchHeritage.split(','); let baseHeritageNames: String[] = baseHeritage.split(','); patchHeritageNames.forEach((patchHeritageName) => { exists = false; baseHeritageNames.forEach((baseHeritageName) => { if (baseHeritageName === patchHeritageName) { exists = true; if (patchOverrides) { baseHeritageName = patchHeritageName; } } }); if (!exists) { baseHeritageNames.push(patchHeritageName); } }); baseHeritages[0] = inheritanceValue + ' ' + baseHeritageNames.join(','); } } } export function mergeComments( baseComments: string[], patchComments: string[], patchOverrides: boolean, ) { let exists: boolean; patchComments.forEach((patchComment, index) => { let isNotRemoved: boolean = true; baseComments.forEach((baseComment) => { if (patchOverrides) { if (isNotRemoved) { baseComments.splice(index, 1, patchComment); isNotRemoved = false; } } }); }); } export function mergeInterfaceProperties( baseProperties: InterfaceProperty[], patchProperties: InterfaceProperty[], patchOverrides: boolean, ) { let exists: boolean; patchProperties.forEach((patchProperty) => { exists = false; baseProperties.forEach((property) => { if (patchProperty.id === property.id) { exists = true; if (patchOverrides) { property.text = patchProperty.text; } } }); if (!exists) { baseProperties.push(patchProperty); } }); } export function mergeInterfaceMethods( baseMethods: InterfaceMethod[], patchMethods: InterfaceMethod[], patchOverrides, ) { let exists: boolean; patchMethods.forEach((patchMethod) => { exists = false; baseMethods.forEach((method) => { if (patchMethod.getIdentifier() === method.getIdentifier()) { exists = true; mergeInterfaceMethod(method, patchMethod, patchOverrides); } }); if (!exists) { baseMethods.push(patchMethod); } }); } export function mergeMethod( baseMethod: Method, patchMethod: Method, patchOverrides: boolean, ) { baseMethod.merge(patchMethod, patchOverrides); } export function mergeInterfaceMethod( baseMethod: InterfaceMethod, patchMethod: InterfaceMethod, patchOverrides: boolean, ) { baseMethod.merge(patchMethod, patchOverrides); } export function mergeVariables( baseFile: TSFile, patchFile: TSFile, patchOverrides: boolean, ) { let exists: boolean; patchFile.getVariables().forEach((patchVariable) => { exists = false; baseFile.getVariables().forEach((variable) => { if (patchVariable.getIdentifier() === variable.getIdentifier()) { exists = true; variable.merge(patchVariable, patchOverrides); } }); if (!exists) { baseFile.addVariable(patchVariable); } }); } export function mergeFunctions( baseFunctions: FunctionDeclaration[], patchFunctions: FunctionDeclaration[], patchOverrides, ) { let exists: boolean; patchFunctions.forEach((patchFunction) => { exists = false; baseFunctions.forEach((func) => { if (patchFunction.getIdentifier() === func.getIdentifier()) { exists = true; mergeFunction(func, patchFunction, patchOverrides); } }); if (!exists) { baseFunctions.push(patchFunction); } }); } export function mergeFunction( baseFunction: FunctionDeclaration, patchFunction: FunctionDeclaration, patchOverrides: boolean, ) { baseFunction.merge(patchFunction, patchOverrides); }
{'dir': 'typescript', 'id': '6154944', 'max_stars_count': '3', 'max_stars_repo_name': 'jan-vcapgemini/ts-merger', 'max_stars_repo_path': 'src/tools/MergerTools.ts', 'n_tokens_mistral': 3311, 'n_tokens_neox': 3322, 'n_words': 607}
<reponame>poschis80/android<filename>xpshome/net/components/Unity.java package xpshome.net.components; import android.app.Application; import android.content.Context; import android.support.annotation.NonNull; import android.util.Pair; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Objects; /** * Created by <NAME> on 25.09.2015. */ public class Unity { private static Unity instance = null; @SuppressWarnings("unused") public static Unity Instance() { if (instance == null) { instance = new Unity(); } return instance; } @SuppressWarnings("unused") public static Unity Create(Context context) { Unity i = Instance(); i.appContext = context; return i; } @SuppressWarnings("unused") public static class SingletonBase { public void init() {} public void destroy() {} } protected Context appContext; private final Object lockObject; private HashMap<Class<?>, Object> classes; protected Unity() { classes = new HashMap<>(); lockObject = new Object(); } private void instantiateNewObject(Class<?> cl) { try { Constructor ctor; Object o = null; Pair<Boolean, Constructor> res = findBestSuitableConstructor(cl); if (res.first) { o = res.second.newInstance(); } else if (!res.first && res.second != null) { o = res.second.newInstance(appContext); } if (o != null) { if (o instanceof SingletonBase) { ((SingletonBase) o).init(); } classes.put(cl, o); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } private Pair<Boolean, Constructor> findBestSuitableConstructor(Class<?> cl) { Constructor[] ctors = cl.getConstructors(); for (Constructor c : ctors) { Class<?>[] params = c.getParameterTypes(); if (params == null || params.length <= 0) { // return default ctor return new Pair<>(true, c); } else { if (params.length == 1 && params[0].getName().compareTo(Context.class.getName()) == 0) { // return ctor with one param of type Context return new Pair<>(false, c); } } } return new Pair<>(false, null); } @SuppressWarnings("unused") public Unity register(Class<?> object) { if (object == null) { return this; } synchronized (lockObject) { if (!classes.containsKey(object)) { classes.put(object, null); } } return this; } @SuppressWarnings("unused") public Unity register(Class<?> object, Object instance) { if (object == null || instance == null) { return this; } classes.put(object, instance); return this; } @SuppressWarnings("unused") public <T> Unity register(T object) { if (object == null) { return this; } if (!classes.containsKey(object.getClass())) { classes.put(object.getClass(), object); } return this; } @SuppressWarnings("unused") public Unity registerClasses(Class<?>... objects) { if (objects == null) { return this; } for (Class<?> c : objects) { register(c); } return this; } @SuppressWarnings("unused") public Unity unregisterAll() { synchronized (lockObject) { for (Object o : classes.values()) { if (o instanceof SingletonBase) { ((SingletonBase)o).destroy(); } } classes.clear(); } return this; } @SuppressWarnings("unused") public Unity unregister(Class<?> object) { if (object == null) { return this; } synchronized (lockObject) { Object o = classes.get(object); if (o != null) { if (o instanceof SingletonBase) { ((SingletonBase) o).destroy(); } } classes.remove(object); } return this; } @SuppressWarnings("unused unchecked") public final <T> T getInstance(@NonNull final String className) { try { return getInstance((Class<T>)Class.forName(className)); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } @SuppressWarnings("unused unchecked") public final <T> T getInstance(Class<T> object) { if (object == null) { return null; } synchronized (lockObject) { if (classes.containsKey(object)) { if (classes.get(object) == null) { instantiateNewObject(object); } return (T) classes.get(object); } } return null; } @SuppressWarnings("unused unchecked") public final <T> T getInstanceForceRegister(Class<T> object) { if (object == null) { return null; } synchronized (lockObject) { if (!classes.containsKey(object)) { register(object); instantiateNewObject(object); } else if (classes.get(object) == null) { instantiateNewObject(object); } return (T) classes.get(object); } } }
{'dir': 'java', 'id': '6057817', 'max_stars_count': '1', 'max_stars_repo_name': 'poschis80/android', 'max_stars_repo_path': 'xpshome/net/components/Unity.java', 'n_tokens_mistral': 1575, 'n_tokens_neox': 1554, 'n_words': 372}
export * from './AbsoluteBoardState' export * from './AbsoluteMove' export * from './BoardStateNode' export * from './BoardState' export * from './CubeState' export * from './Dices' export * from './GameConf' export * from './Move' export * from './Ply' export * from './Score'
{'dir': 'typescript', 'id': '6508495', 'max_stars_count': '0', 'max_stars_repo_name': 'tkshio/tsgammon-core', 'max_stars_repo_path': 'src/index.ts', 'n_tokens_mistral': 82, 'n_tokens_neox': 81, 'n_words': 30}
<filename>resources/views/Mailsignature/addedit.blade.php<gh_stars>0 @extends('layouts.app') @section('content') <script type="text/javascript"> var datetime = '<?php echo date('Ymdhis'); ?>'; var mainmenu = '<?php echo $request->mainmenu; ?>'; $(document).ready(function() { if($('#editflg').val()=="2"){ $('#reghead').show(); $('#regbtn').show(); $('#regcancel').show(); } else { $('#edithead').show(); $('#updatebtn').show(); $('#updatecancel').show(); } }); </script> {{ HTML::script('resources/assets/js/mailsignature.js') }} <div class="CMN_display_block" id="main_contents"> <!-- article to select the main&sub menu --> <article id="mail" class="DEC_flex_wrapper " data-category="mail mail_sub_3"> {{ Form::open(array('name'=>'frmaddedit', 'id'=>'frmaddedit', 'url' => 'Mailsignature/addeditprocess?mainmenu='.$request->mainmenu.'&time='.date('YmdHis'), 'files'=>true, 'method' => 'POST')) }} {{ Form::hidden('useridhdn',$request->useridhdn , array('id' => 'useridhdn')) }} {{ Form::hidden('editflg',$request->editflg, array('id' => 'editflg')) }} {{ Form::hidden('updateprocess',$request->updateprocess, array('id' => 'updateprocess')) }} {{ Form::hidden('id',$request->id, array('id' => 'id')) }} <!-- Start Heading --> @if(Session::get('userclassification') == "4") <div class="row hline"> @else <div class="row hline" style="width:123%"> @endif <div class="col-xs-12"> <img class="pull-left box35 mt10" src="{{ URL::asset('resources/assets/images/signature.png') }}"> <h2 class="pull-left pl5 mt10">{{ trans('messages.lbl_mailsignature') }}</h2> <h2 class="pull-left mt10">・</h2> <h2 class="pull-left mt10"><span id="reghead" class="green" style="display: none;"> {{ trans('messages.lbl_register') }}</span> <span id="edithead" style="display: none;" class="red"> {{ trans('messages.lbl_edit') }}</h2></span> </div> </div> <div id="errorSectiondisplay" align="center" class="box100per"></div> @if(Session::get('userclassification') == "4") <div class="ml10 mr10 box99per"> @else <div class="ml10 mr10" style="width:121%"> @endif <fieldset> @if(Session::get('userclassification') == "4") <div class="col-xs-12 mt10"> <div class="col-xs-3 text-right clr_blue mr5"> <label>{{ trans('messages.lbl_usernamesign') }}<span class="fr ml2 red"> * </span></label> </div> <div class="box25per fll pl10"> {{ Form::hidden('userid','',array('id'=>'userid')) }} {{ Form::text('txtuserid',(isset($getname)?$getname:""),array('id'=>'txtuserid', 'name' => 'txtuserid', 'class'=>'form-control', 'readonly','readonly','data-label' => trans('messages.lbl_usernamesign'))) }} </div> <div class="col-xs-3 mr25"> <button type="button" id="bnkpopup" class="btn btn-success box75 pt3 h30" style ="color:white;background-color: green;cursor: pointer;" onclick="return popupenable('{{ $request->mainmenu }}');">{{ trans('messages.lbl_Browse') }} </button> </div> </div> @endif <div class="col-xs-12 mt5 mb10"> <div class="col-xs-3 clr_blue text-right"> <label>{{ trans('messages.lbl_mailsignature') }}<span class="fr ml2 red"> * </span></label> </div> <div class="col-xs-9"> {{ Form::textarea('content',(isset($getdataforupdate[0]->content)?$getdataforupdate[0]->content:""), array('name' => 'content', 'id' => 'content', 'data-label' => trans('messages.lbl_mailsignature'), 'class' => 'box60per form-control','size' => '100x9')) }} </div> </div> </fieldset> <fieldset style="background-color: #DDF1FA;"> <div class="form-group"> <div align="center" class="mt5"> <button type="submit" class="btn edit btn-warning addeditprocess box100" id="updatebtn" style="display: none;"> <i class="fa fa-edit" aria-hidden="true"></i> {{ trans('messages.lbl_update') }} </button> <a onclick="javascript:gotoindex('1','{{$request->mainmenu}}','{{$request->updateprocess}}','{{$request->editflg}}');" class="btn btn-danger box120 white" id="updatecancel" style="display: none;"> <i class="fa fa-times" aria-hidden="true"></i> {{trans('messages.lbl_cancel')}} </a> <button type="submit" class="btn btn-success add box100 addeditprocess ml5" id="regbtn" style="display: none;"> <i class="fa fa-plus" aria-hidden="true"></i> {{ trans('messages.lbl_register') }} </button> @if(Session::get('userclassification') == "4") <a onclick="javascript:gotoindex('2','{{$request->mainmenu}}');" class="btn btn-danger box120 white" id="regcancel" style="display: none;"> <i class="fa fa-times" aria-hidden="true"></i> {{trans('messages.lbl_cancel')}} </a> @else <a onclick="javascript:gotoviewscrn('2','{{$request->mainmenu}}');" class="btn btn-danger box120 white" id="regcancel" style="display: none;"> <i class="fa fa-times" aria-hidden="true"></i> {{trans('messages.lbl_cancel')}} </a> @endif </div> </div> </fieldset> </div> {{ Form::close() }} {{ Form::open(array('name'=>'mailsignaddeditcancel', 'id'=>'mailsignaddeditcancel', 'url' => 'Mailsignature/addeditprocess?mainmenu='.$request->mainmenu.'&time='.date('YmdHis'),'files'=>true,'method' => 'POST')) }} {{ Form::hidden('editflg','', array('id' => 'editflg')) }} {{ Form::hidden('id',$request->id, array('id' => 'id')) }} {{ Form::hidden('signid',$request->signid, array('id' => 'signid')) }} {{ Form::close() }} <div id="mailsignaturepopup" class="modal fade"> <div id="login-overlay"> <div class="modal-content"> <!-- Popup will be loaded here --> </div> </div> </div> </article> </div> @endsection
{'dir': 'php', 'id': '12275905', 'max_stars_count': '0', 'max_stars_repo_name': 'RajeshMaster/Accounting', 'max_stars_repo_path': 'resources/views/Mailsignature/addedit.blade.php', 'n_tokens_mistral': 2592, 'n_tokens_neox': 2152, 'n_words': 338}
<?php namespace App\Models; use CodeIgniter\Model; class TransportPrixArticlesModel extends Model{ protected $table = 'g_interne_transport_articles_prix'; protected $DBGroup = 'default'; protected $primaryKey = 'id'; protected $allowedFields = ['zone_id','article_id','prix']; protected $useTimestamps = true; protected $validationRules = [ 'zone_id' => 'required|checkingForeignKeyExist[st_zone,id]', 'article_id' => 'required|checkingForeignKeyExist[g_articles,id]', 'prix' =>'required|greater_than[0]' ]; protected $validationMessages = [ 'zone_id'=>[ 'required' => 'La zône est obligatoire', 'checkingForeignKeyExist' => 'La zône choisie n\'existe pas' ], 'article_id'=>[ 'required' => 'L\'article est obligatoire', 'checkingForeignKeyExist' => 'L\'article choisi n\'existe pas' ], 'prix'=>[ 'required' => 'Le prix est obligatoire', 'greater_than' => 'Le prix doit être superieur à 0' ], ]; protected $returnType ='App\Entities\TransportPrixArticlesEntity'; public function checkingIfConfigExist($zone, $article){ if($this->Where('zone_id', $zone)->Where('article_id', $article)->find()){ return true; } return false; } // LES TRANSACTIONS public function beginTrans(){ $this->db->transBegin(); } public function RollbackTrans(){ $this->db->transRollback(); } public function commitTrans(){ $this->db->transCommit(); } }
{'dir': 'php', 'id': '1157478', 'max_stars_count': '0', 'max_stars_repo_name': 'ted1104/Gestion-Jml', 'max_stars_repo_path': 'app/Models/TransportPrixArticlesModel.php', 'n_tokens_mistral': 494, 'n_tokens_neox': 478, 'n_words': 98}
import { createAction, createReducer } from 'redux-act' import { add } from 'ramda' export const togglePause = createAction('worldState/togglePause') export const worldTick = createAction('worldState/worldTick') interface InitialState { paused: boolean timePassed: number } const initialState: InitialState = { paused: true, timePassed: 0, } const worldReducer = createReducer( { [togglePause.getType()]: (state, payload) => ({ ...state, paused: payload ? payload.mode : !state.paused, }), [worldTick.getType()]: (state, { time }) => ({ ...state, timePassed: add(state.timePassed, time), }), }, initialState, ) export default worldReducer
{'dir': 'typescript', 'id': '7164507', 'max_stars_count': '0', 'max_stars_repo_name': 'Azein/frontend_sim', 'max_stars_repo_path': 'src/domains/world/WorldState.ts', 'n_tokens_mistral': 226, 'n_tokens_neox': 224, 'n_words': 52}
<reponame>chanzuckerberg/dcp-prototype import typing from backend.corpora.common.corpora_orm import ( Base, DatasetArtifactFileType, UploadStatus, ValidationStatus, ) from tests.unit.backend.fixtures.mock_aws_test_case import CorporaTestCaseUsingMockAWS from tests.unit.backend.utils import BogusDatasetParams class TestDataset(CorporaTestCaseUsingMockAWS): def setUp(self): super().setUp() self.uuid = "test_dataset_id" self.bucket_name = self.CORPORA_TEST_CONFIG["bucket_name"] def create_dataset_with_artifacts(self, artifact_count=1, artifact_params=None): """ Create a dataset with a variable number of artifacts """ if not artifact_params: artifact_params = dict( filename="filename_x", filetype=DatasetArtifactFileType.H5AD, user_submitted=True, s3_uri="some_uri", ) dataset_params = BogusDatasetParams.get() dataset = self.generate_dataset( self.session, **dataset_params, artifacts=[artifact_params] * artifact_count, processing_status={ "upload_progress": 9 / 13, "upload_status": UploadStatus.UPLOADING, "validation_status": ValidationStatus.NA, }, ) return dataset def assertRowsDeleted(self, tests: typing.List[typing.Tuple[str, Base]]): """ Verify if rows have been deleted from the database. :param tests: a list of tuples with (primary_key, table) """ self.session.expire_all() for p_key, table in tests: actual = [i for i in self.session.query(table).filter(table.id == p_key)] self.assertFalse(actual, f"Row not deleted {table.__name__}:{p_key}") def assertRowsExist(self, tests): """ Verify if rows exist in the database. :param tests: a list of tuples with (primary_key, table) """ self.session.expire_all() for p_key, table in tests: actual = [i for i in self.session.query(table).filter(table.id == p_key)] self.assertTrue(actual, f"Row does not exist {table.__name__}:{p_key}")
{'dir': 'python', 'id': '9395450', 'max_stars_count': '2', 'max_stars_repo_name': 'chanzuckerberg/dcp-prototype', 'max_stars_repo_path': 'tests/unit/backend/corpora/common/entities/datasets/__init__.py', 'n_tokens_mistral': 660, 'n_tokens_neox': 639, 'n_words': 146}
$(function () { // constants var SHOW_CLASS = 'show', HIDE_CLASS = 'hide', ACTIVE_CLASS = 'login-item-link--active'; $('.login-list').on('click', '.login-item .login-item-link', function (e) { e.preventDefault(); var $tab = $(this), href = $tab.attr('href'); $('.login-item-link--active').removeClass(ACTIVE_CLASS); $tab.addClass(ACTIVE_CLASS); $('.show') .removeClass(SHOW_CLASS) .addClass(HIDE_CLASS) .hide(); $('.login-item').toggleClass('login-item--active'); $(href) .removeClass(HIDE_CLASS) .addClass(SHOW_CLASS) .hide() .fadeIn(550); }); });
{'dir': 'javascript', 'id': '1040496', 'max_stars_count': '0', 'max_stars_repo_name': 'etterwin/DiaVita-Club-s-cabinet', 'max_stars_repo_path': 'school/assets/js/tabsLogin.js', 'n_tokens_mistral': 232, 'n_tokens_neox': 226, 'n_words': 32}
/* * #%L * ********************************************************************** * ORGANIZATION : Pi4J * PROJECT : Pi4J :: Java Examples * FILENAME : MCP4725GpioExample.java * * This file is part of the Pi4J project. More information about * this project can be found here: http://www.pi4j.com/ * ********************************************************************** * %% * Copyright (C) 2012 - 2014 Pi4J * %% * 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. * #L% */ import com.pi4j.gpio.extension.mcp.MCP4725GpioProvider; import com.pi4j.gpio.extension.mcp.MCP4725Pin; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinAnalogOutput; import com.pi4j.io.i2c.I2CBus; /** * <p> * This example code demonstrates how to setup a custom GpioProvider * for analog output pin. * </p> * * <p> * This GPIO provider implements the MCP4725 12-Bit Digital-to-Analog Converter as native Pi4J GPIO pins. * More information about the board can be found here: * http://http://www.adafruit.com/product/935 * </p> * * <p> * The MCP4725 is connected via SPI connection to the Raspberry Pi and provides 1 GPIO analog output pin. * </p> * * @author <NAME> */ public class MCP4725GpioExample { public static void main(String args[]) throws Exception { System.out.println("<--Pi4J--> MCP4725 DAC Example ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // create gpio provider final MCP4725GpioProvider gpioProvider = new MCP4725GpioProvider(I2CBus.BUS_1, MCP4725GpioProvider.MCP4725_ADDRESS_1); // create output pin final GpioPinAnalogOutput vout = gpio.provisionAnalogOutputPin(gpioProvider, MCP4725Pin.OUTPUT); // generate sinus wave on output pin for (int i = 0; i < 360; i++) { double y = Math.sin(Math.toRadians(i)); y = y / 2 + 0.5; vout.setValue(y); if (i == 359) { i = 0; } } } }
{'dir': 'java', 'id': '8978491', 'max_stars_count': '0', 'max_stars_repo_name': 'bobpaulin/pi4j', 'max_stars_repo_path': 'pi4j-example/src/main/java/MCP4725GpioExample.java', 'n_tokens_mistral': 850, 'n_tokens_neox': 779, 'n_words': 252}
<gh_stars>1-10 const EventEmitter = require('events'); class MyEmitter extends EventEmitter { } const myEmitter = new MyEmitter(); myEmitter.on('WaterFall', () => { console.log('Please click the photo'); setTimeout(() => { console.log('Please click the picture fast'); }, 3000); }); // myEmitter.emit('event'); console.log("The script is running") myEmitter.emit('WaterFall'); console.log("The script is still running") myEmitter.emit('WaterFall');
{'dir': 'javascript', 'id': '862238', 'max_stars_count': '1', 'max_stars_repo_name': 'codewithsom/Website', 'max_stars_repo_path': 'nodejsevents.js', 'n_tokens_mistral': 146, 'n_tokens_neox': 150, 'n_words': 36}
<reponame>wrldwzrd89/older-java-games<filename>LaserTank Improved/src/com/puttysoftware/lasertank/Application.java /* LaserTank: An Arena-Solving Game Copyright (C) 2008-2013 <NAME> Any questions should be directed to the author via email at: <EMAIL> */ package com.puttysoftware.lasertank; import java.awt.Container; import java.awt.Dimension; import java.awt.event.KeyListener; import java.awt.event.WindowFocusListener; import java.awt.event.WindowListener; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.reflect.InvocationTargetException; import javax.swing.JFrame; import javax.swing.JProgressBar; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import com.puttysoftware.dialogs.CommonDialogs; import com.puttysoftware.integration.NativeIntegration; import com.puttysoftware.lasertank.arena.ArenaManager; import com.puttysoftware.lasertank.editor.ArenaEditor; import com.puttysoftware.lasertank.game.GameManager; import com.puttysoftware.lasertank.strings.CommonString; import com.puttysoftware.lasertank.strings.DialogString; import com.puttysoftware.lasertank.strings.MessageString; import com.puttysoftware.lasertank.strings.StringLoader; import com.puttysoftware.lasertank.strings.global.GlobalLoader; import com.puttysoftware.lasertank.strings.global.UntranslatedString; import com.puttysoftware.lasertank.utilities.ArenaObjectList; public final class Application { private static final int VERSION_MAJOR = 0; private static final int VERSION_MINOR = 0; private static final int VERSION_BUGFIX = 0; private static final int VERSION_BETA = 2; private static final int STATUS_GUI = 0; private static final int STATUS_GAME = 1; private static final int STATUS_EDITOR = 2; private static final int STATUS_NULL = 3; public static String getLogoVersionString() { if (Application.isBetaModeEnabled()) { return StringLoader.loadCommon(CommonString.LOGO_VERSION_PREFIX) + Application.VERSION_MAJOR + StringLoader.loadCommon(CommonString.NOTL_PERIOD) + Application.VERSION_MINOR + StringLoader.loadCommon(CommonString.NOTL_PERIOD) + Application.VERSION_BUGFIX + StringLoader.loadCommon(CommonString.BETA_SHORT) + Application.VERSION_BETA; } else { return StringLoader.loadCommon(CommonString.LOGO_VERSION_PREFIX) + Application.VERSION_MAJOR + StringLoader.loadCommon(CommonString.NOTL_PERIOD) + Application.VERSION_MINOR + StringLoader.loadCommon(CommonString.NOTL_PERIOD) + Application.VERSION_BUGFIX; } } private static String getVersionString() { if (Application.isBetaModeEnabled()) { return StringLoader.loadCommon(CommonString.EMPTY) + Application.VERSION_MAJOR + StringLoader.loadCommon(CommonString.NOTL_PERIOD) + Application.VERSION_MINOR + StringLoader.loadCommon(CommonString.NOTL_PERIOD) + Application.VERSION_BUGFIX + StringLoader.loadMessage(MessageString.BETA) + Application.VERSION_BETA; } else { return StringLoader.loadCommon(CommonString.EMPTY) + Application.VERSION_MAJOR + StringLoader.loadCommon(CommonString.NOTL_PERIOD) + Application.VERSION_MINOR + StringLoader.loadCommon(CommonString.NOTL_PERIOD) + Application.VERSION_BUGFIX; } } private static boolean isBetaModeEnabled() { return Application.VERSION_BETA > 0; } // Fields private final JFrame masterFrame; private AboutDialog about; private GameManager gameMgr; private ArenaManager arenaMgr; private MenuManager menuMgr; private ArenaEditor editor; private GUIManager guiMgr; private int mode, formerMode; private final ArenaObjectList objects; private final NativeIntegration ni; // Constructors public Application(final NativeIntegration newNI) { this.ni = newNI; this.masterFrame = new JFrame(); this.masterFrame.setResizable(false); this.objects = new ArenaObjectList(); this.mode = Application.STATUS_NULL; this.formerMode = Application.STATUS_NULL; } void init() { // Create Managers this.menuMgr = new MenuManager(); this.about = new AboutDialog(Application.getVersionString()); this.guiMgr = new GUIManager(); this.gameMgr = new GameManager(); this.editor = new ArenaEditor(); // Cache Logo this.guiMgr.updateLogo(); } void bootGUI() { // Set up default error handling final UncaughtExceptionHandler eh = (t, e) -> LaserTank .logNonFatalError(e); final Runnable doRun = () -> Thread.currentThread() .setUncaughtExceptionHandler(eh); try { SwingUtilities.invokeAndWait(doRun); } catch (InvocationTargetException | InterruptedException e) { LaserTank.logError(e); } // Boot GUI this.guiMgr.showGUI(); } // Methods public void activeLanguageChanged() { // Rebuild menus this.menuMgr.populateMenuBar(); this.ni.setDefaultMenuBar(this.menuMgr.getMenuBar(), this.masterFrame); // Fire hooks this.getGameManager().activeLanguageChanged(); this.getEditor().activeLanguageChanged(); } void exitCurrentMode() { if (this.mode == Application.STATUS_GUI) { this.guiMgr.tearDown(); } else if (this.mode == Application.STATUS_GAME) { this.gameMgr.tearDown(); } else if (this.mode == Application.STATUS_EDITOR) { this.editor.tearDown(); } } AboutDialog getAboutDialog() { return this.about; } public ArenaManager getArenaManager() { if (this.arenaMgr == null) { this.arenaMgr = new ArenaManager(); } return this.arenaMgr; } public ArenaEditor getEditor() { return this.editor; } public int getFormerMode() { return this.formerMode; } public GameManager getGameManager() { return this.gameMgr; } public GUIManager getGUIManager() { return this.guiMgr; } public String[] getLevelInfoList() { return this.arenaMgr.getArena().getLevelInfoList(); } public MenuManager getMenuManager() { return this.menuMgr; } public boolean isInGameMode() { return this.mode == Application.STATUS_GAME; } public boolean isInEditorMode() { return this.mode == Application.STATUS_EDITOR; } public boolean isInGUIMode() { return this.mode == Application.STATUS_GUI; } public ArenaObjectList getObjects() { return this.objects; } public void setInEditor(final Container masterContent) { this.formerMode = this.mode; this.mode = Application.STATUS_EDITOR; this.tearDownFormerMode(); this.editor.setUp(); this.menuMgr.activateEditorCommands(); this.masterFrame.setContentPane(masterContent); } public void setInGame(final Container masterContent) { this.formerMode = this.mode; this.mode = Application.STATUS_GAME; this.tearDownFormerMode(); this.gameMgr.setUp(); this.menuMgr.activateGameCommands(); this.masterFrame.setContentPane(masterContent); } void setInGUI(final Container masterContent) { this.formerMode = this.mode; this.mode = Application.STATUS_GUI; this.tearDownFormerMode(); this.guiMgr.setUp(); this.menuMgr.activateGUICommands(); this.masterFrame.setContentPane(masterContent); if (!this.masterFrame.isVisible()) { this.masterFrame.setVisible(true); this.masterFrame.pack(); } } public Container getMasterContent() { return this.masterFrame.getContentPane(); } public void setTitle(final String title) { this.masterFrame.setTitle(title); } public void updateDirtyWindow(final boolean appDirty) { this.masterFrame.getRootPane().putClientProperty( GlobalLoader .loadUntranslated(UntranslatedString.WINDOW_MODIFIED), Boolean.valueOf(appDirty)); } public void pack() { this.masterFrame.pack(); } public void addWindowListener(final WindowListener l) { this.masterFrame.addWindowListener(l); } public void addWindowFocusListener(final WindowFocusListener l) { this.masterFrame.addWindowFocusListener(l); } public void addKeyListener(final KeyListener l) { this.masterFrame.addKeyListener(l); } public void removeWindowListener(final WindowListener l) { this.masterFrame.removeWindowListener(l); } public void removeWindowFocusListener(final WindowFocusListener l) { this.masterFrame.removeWindowFocusListener(l); } public void removeKeyListener(final KeyListener l) { this.masterFrame.removeKeyListener(l); } public void showMessage(final String msg) { if (this.mode == Application.STATUS_EDITOR) { this.getEditor().setStatusMessage(msg); } else { CommonDialogs.showDialog(msg); } } private void tearDownFormerMode() { if (this.formerMode == Application.STATUS_GUI) { this.getGUIManager().tearDown(); } else if (this.formerMode == Application.STATUS_GAME) { this.getGameManager().tearDown(); } else if (this.formerMode == Application.STATUS_EDITOR) { this.getEditor().tearDown(); } } public void updateLevelInfoList() { JFrame loadFrame; JProgressBar loadBar; loadFrame = new JFrame( StringLoader.loadDialog(DialogString.UPDATING_LEVEL_INFO)); loadBar = new JProgressBar(); loadBar.setIndeterminate(true); loadBar.setPreferredSize(new Dimension(600, 20)); loadFrame.getContentPane().add(loadBar); loadFrame.setResizable(false); loadFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); loadFrame.pack(); loadFrame.setVisible(true); this.arenaMgr.getArena().generateLevelInfoList(); loadFrame.setVisible(false); } }
{'dir': 'java', 'id': '5012989', 'max_stars_count': '0', 'max_stars_repo_name': 'wrldwzrd89/older-java-games', 'max_stars_repo_path': 'LaserTank Improved/src/com/puttysoftware/lasertank/Application.java', 'n_tokens_mistral': 3026, 'n_tokens_neox': 2954, 'n_words': 531}
<reponame>cck-fullstack/graceshopper<filename>client/components/admin-page.js /* eslint-disable complexity */ import React, {Component} from 'react' import {connect} from 'react-redux' import { getItemsThunk, deleteItemThunk, updateItemCountThunk, addItemThunk } from '../store/items' import {getAllUsersThunk, deleteUserThunk} from '../store/user' import ItemForm from './itemForm' const defaultState = { name: '', price: 0.0, inventory: 0, description: '', category: '', warningMessage: 'Field is required!', showAddForm: false, showEditItems: false, showEditUsersForm: false } class AdminPage extends Component { constructor() { super() this.state = defaultState } componentDidMount() { this.props.fetchItems() this.props.fetchUsers() } handleChange = evt => { this.setState({ [evt.target.name]: evt.target.value }) } handleSubmit = evt => { evt.preventDefault() const newItem = { name: this.state.name, price: this.state.price, inventory: this.state.inventory, description: this.state.description, category: this.state.category } this.props.createItem(newItem) this.setState(defaultState) } changeAmount = (event, item) => { event.preventDefault() this.props.changeItemCount(item, event.path[0][0].valueAsNumber) } render() { const {showAddForm, showEditItems, showEditUsersForm} = this.state const { addOneItem, deleteItem, deleteUser, removeOneItem, items, users } = this.props return ( <span> <h3>Admin Panel</h3> <button type="button" onClick={() => this.setState({showAddForm: !showAddForm})} > Add Item Form </button> {showAddForm ? ( <ItemForm {...this.state} handleChange={this.handleChange} handleSubmit={this.handleSubmit} /> ) : ( <div /> )} <button type="button" onClick={() => this.setState({showEditItems: !showEditItems})} > Edit Item Quantity </button> {showEditItems ? ( <ul style={{display: 'flex', flexWrap: 'wrap'}}> {items.map(item => ( <div key={item.id}> <li> <li> {item.name} <button type="button" onClick={() => deleteItem(item.id)}> X </button> </li> <li>Price: ${item.price / 100}</li> <li> <button type="button" onClick={() => removeOneItem(item)}> - </button> Stock:{item.inventory} <button type="button" onClick={() => addOneItem(item)}> + </button> </li> <li> Change Amount:<form onSubmit={() => this.changeAmount(event, item)} > <li className="collection-item"> <input name="inventory" type="number" placeholder={item.inventory} style={{width: '3em'}} /> </li> </form> </li> </li> </div> ))} </ul> ) : ( <div /> )} <button type="button" onClick={() => this.setState({showEditUsersForm: !showEditUsersForm})} > Show Edit User Form{' '} </button> {showEditUsersForm ? ( <ul> {users.data.map(user => ( <div key={user.id}> <li> {user.firstName} {user.lastName} <button type="button" onClick={() => deleteUser(user.id)}> X </button> </li> {/* <li>Admin</li> <Select size='s'> <option value="">Choose your option</option> <option value="true">True</option> <option value="false">False</option> </Select> */} </div> ))} </ul> ) : ( <div /> )} </span> ) } } const mapStateToProps = state => { return { items: state.items, cart: state.cart, users: state.user.usersData } } const mapDispatchToProps = dispatch => ({ fetchItems: () => dispatch(getItemsThunk()), createItem: item => dispatch(addItemThunk(item)), addOneItem: item => dispatch(updateItemCountThunk(item, 1)), removeOneItem: item => dispatch(updateItemCountThunk(item, -1)), changeItemCount: (item, amt) => dispatch(updateItemCountThunk(item, amt)), deleteItem: id => dispatch(deleteItemThunk(id)), fetchUsers: () => dispatch(getAllUsersThunk()), deleteUser: id => dispatch(deleteUserThunk(id)) }) export default connect(mapStateToProps, mapDispatchToProps)(AdminPage)
{'dir': 'javascript', 'id': '17140972', 'max_stars_count': '0', 'max_stars_repo_name': 'cck-fullstack/graceshopper', 'max_stars_repo_path': 'client/components/admin-page.js', 'n_tokens_mistral': 1496, 'n_tokens_neox': 1460, 'n_words': 268}
#!/usr/bin/env python3 import os class Utilities : SERVER_IP = "10.10.10.1" SERVER_MAC = "11:55:AB:2E:FF:EF" ROUTER_IP = "192.168.1.1" ROUTER_MAC = "EE:12:1B:25:0F:00" ROUTER_UDP_PORT = 8091 ROUTER_TCP_PORT = 8092 LOCALHOST = "127.0.0.1" BUFFER_SIZE = 4096 N_TEST_CLIENT = 4 # Numero di client attivi che invieranno messaggi N_TEST_MESSAGE = 2 # Numero di messaggi che invia un singolo client al router N_TEST_WAIT_SERVER_CON = 3 # Numero di secondi da aspettare per l'invio del prossimo messaggio FILE_LOG_FOLDER = "Log" FILE_LOG_FILE = "Log.txt" FILE_LOG_PATH = os.path.join(os.getcwd(), FILE_LOG_FOLDER , FILE_LOG_FILE) EXIT_DAEMON = None DATE_TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f' @staticmethod def Hex(number): if(number < 10) : return str(number) if(number == 10): return "A" if(number == 11): return "B" if(number == 12): return "C" if(number == 13): return "D" if(number == 14): return "E" if(number == 15): return "F" @staticmethod def Reset(): f = None try: if not os.path.exists(Utilities.FILE_LOG_PATH): os.mkdir(Utilities.FILE_LOG_FOLDER, 0o666) f = open(Utilities.FILE_LOG_PATH, 'w') except: f.close() finally: f.close() @staticmethod def PrintAndWrite(log): print(log) f = None try: mode = 'a' if not os.path.exists(Utilities.FILE_LOG_PATH): os.mkdir(Utilities.FILE_LOG_FOLDER, 0o666) mode = 'w' f = open(Utilities.FILE_LOG_PATH, mode) f.write(log) except: f.close() finally: f.close() @staticmethod def Write(log): f = None try: mode = 'a' if not os.path.exists(Utilities.FILE_LOG_PATH): os.mkdir(Utilities.FILE_LOG_FOLDER, 0o666) mode = 'w' f = open(Utilities.FILE_LOG_PATH, mode) f.write(log) except: f.close() finally: f.close() @staticmethod def DateDifference(data1, data2) : delta = 0.0 if (data1 > data2): delta = (data1 - data2).total_seconds() else: delta = (data2 - data1).total_seconds() delta = round(delta * 1000.0, 3) return str(delta) + " MS"
{'dir': 'python', 'id': '1256547', 'max_stars_count': '0', 'max_stars_repo_name': 'FedericoCampanozzi/ProjectProgrammazioneDiReti20-Trace1', 'max_stars_repo_path': 'src/utilities.py', 'n_tokens_mistral': 966, 'n_tokens_neox': 882, 'n_words': 187}
<reponame>mjs7231/pkmeter<filename>setup.py #!/usr/bin/python3 from distutils.core import setup from pip.req import parse_requirements from setuptools import find_packages requirements = [str(line.req) for line in parse_requirements('requirements.pip')] setup( name='pkmeter', version='1.0', description='QT-based meters and gadgets for your desktop!', author='pkkid', author_email='', url='http://bitbucket.org/mjs7231/pkmeter', packages=find_packages(), scripts=['pkmeter'], install_requires=requirements, long_description=open('README.txt').read() )
{'dir': 'python', 'id': '7238524', 'max_stars_count': '16', 'max_stars_repo_name': 'mjs7231/pkmeter', 'max_stars_repo_path': 'setup.py', 'n_tokens_mistral': 207, 'n_tokens_neox': 197, 'n_words': 37}
<filename>edit/Interactive Features/Getting Started/CS/Form2.cs<gh_stars>0 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Syncfusion.Windows.Forms; using Syncfusion.WinForms.Controls; namespace ActionGroupingDemo { public partial class Form2 : SfForm { public Form2(Form1 form1) { // // Required for Windows Form Designer support // Mainform = form1; InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } private void button1_Click(object sender, System.EventArgs e) { this.Close(); } public int startLine { get { int result; if (int.TryParse(textBox1.Text, out result)) return result = Convert.ToInt32(textBox1.Text); else return 1; } } public int endLine { get { int result; if (int.TryParse(textBox3.Text, out result)) return result = Convert.ToInt32(textBox3.Text); else return 1; } } public int startColumn { get { int result; if (int.TryParse(textBox2.Text, out result)) return result = Convert.ToInt32(textBox2.Text); else return 2; } } public int endColumn { get { int result; if (int.TryParse(textBox4.Text, out result)) return result = Convert.ToInt32(textBox4.Text); else return 1; } } private void button2_Click(object sender, System.EventArgs e) { this.Close(); } private void Form2_Load(object sender, System.EventArgs e) { this.textBox1.Focus(); } } }
{'dir': 'c-sharp', 'id': '1138222', 'max_stars_count': '0', 'max_stars_repo_name': 'aTiKhan/winforms-demos', 'max_stars_repo_path': 'edit/Interactive Features/Getting Started/CS/Form2.cs', 'n_tokens_mistral': 592, 'n_tokens_neox': 553, 'n_words': 133}
package com.karateca.ddescriber; /** * Represents the jasmine syntax. */ public enum JasmineSyntax { Version1("ddescribe", "iit"), Version2("fdescribe", "fit"); private String includeDescribe; private String includeIt; JasmineSyntax(String includeDescribe, String includeIt) { this.includeDescribe = includeDescribe; this.includeIt = includeIt; } String getIncludedDescribe() { return includeDescribe; } String getIncludedit() { return includeIt; } }
{'dir': 'java', 'id': '3605162', 'max_stars_count': '7', 'max_stars_repo_name': 'andresdominguez/ddescriber', 'max_stars_repo_path': 'src/com/karateca/ddescriber/JasmineSyntax.java', 'n_tokens_mistral': 158, 'n_tokens_neox': 153, 'n_words': 35}
<reponame>rivaldivirgiawan/testsimrs @extends('layouts.master') @section('content') <div class="main"> <div class="main-content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <!-- TABLE HOVER --> <div class="panel"> <div class="panel-heading"> <h1 class="panel-title text-center">Transaksi</h1> </div> <div class="panel-body"> <table class="table table-hover"> <thead> <tr> <th>ID PENDAFTARAN</th> <th>POLIKLINIK</th> <th>ID PASIEN</th> <th>NAMA</th> <th>JENIS KELAMIN</th> <th>ALAMAT</th> <th>TELPON</th> <th>DIAGNOSA</th> <th>TGL DAFTAR</th> <th></th> </tr> </thead> <tbody> @foreach($transaksi as $transaksi) <tr> <td>{{$transaksi->id}}</td> <td>{{$transaksi->poliklinik->nama}}</td> <td>{{$transaksi->pasien->id}}</td> <td>{{$transaksi->pasien->nama}}</td> <td>{{$transaksi->pasien->jenis_kelamin}}</td> <td>{{$transaksi->pasien->alamat}}</td> <td>{{$transaksi->pasien->notelp}}</td> <td>{{$transaksi->kesimpulan}}</td> <td>{{$transaksi->created_at}}</td> <td> <a href="/pasien/{{$transaksi->pasien->id}}/detail" class="btn-primary btn-sm">Detail</a> </td> </tr> @endforeach </tbody> </table> </div> </div> <!-- END TABLE HOVER --> </div> </div> </div> </div> </div> @stop
{'dir': 'php', 'id': '6833463', 'max_stars_count': '0', 'max_stars_repo_name': 'rivaldivirgiawan/testsimrs', 'max_stars_repo_path': 'resources/views/transaksi/index.blade.php', 'n_tokens_mistral': 1105, 'n_tokens_neox': 620, 'n_words': 81}
<filename>src/CSBill/ClientBundle/Tests/ContactTypesExtensionTest.php<gh_stars>0 <?php /* * This file is part of CSBill package. * * (c) 2013-2015 <NAME> <<EMAIL>> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace CSBill\ClientBundle\Tests\Twig\Extension; use CSBill\ClientBundle\Twig\Extension\ContactTypesExtension; class ContactTypesExtensionTest extends \PHPUnit_Framework_TestCase { public function testGetFunctions() { $manager = \Mockery::mock('Doctrine\Common\Persistence\ObjectManager'); $registry = \Mockery::mock('Doctrine\Bundle\DoctrineBundle\Registry', array('getManager' => $manager)); $extension = new ContactTypesExtension($registry); $functions = $extension->getFunctions(); $this->assertTrue(is_array($functions)); $this->assertCount(1, $functions); $this->assertInstanceof('Twig_SimpleFunction', $functions[0]); } public function testGetContactTypes() { $array = array( 1, 3, 5, 7, 9, ); $manager = \Mockery::mock('Doctrine\Common\Persistence\ObjectManager'); $objectRepository = \Mockery::mock('Doctrine\Common\Persistence\ObjectRepository', array('findAll' => $array)); $registry = \Mockery::mock('Doctrine\Bundle\DoctrineBundle\Registry', array('getManager' => $manager)); $manager->shouldReceive('getRepository') ->once() ->with('CSBillClientBundle:ContactType') ->andReturn($objectRepository); $extension = new ContactTypesExtension($registry); $this->assertSame($array, $extension->getContactTypes()); // Run twice, to ensure the contact types is cached and no duplicate queries are executed // when getting the contact types more than once $this->assertSame($array, $extension->getContactTypes()); } public function testGetName() { $manager = \Mockery::mock('Doctrine\Common\Persistence\ObjectManager'); $registry = \Mockery::mock('Doctrine\Bundle\DoctrineBundle\Registry', array('getManager' => $manager)); $extension = new ContactTypesExtension($registry); $this->assertSame('client_contact_types_extension', $extension->getName()); } }
{'dir': 'php', 'id': '2341378', 'max_stars_count': '0', 'max_stars_repo_name': 'kprempeh/app.invoice', 'max_stars_repo_path': 'src/CSBill/ClientBundle/Tests/ContactTypesExtensionTest.php', 'n_tokens_mistral': 646, 'n_tokens_neox': 623, 'n_words': 128}
/* To run: jasmine-node updateTelevision....spec PUT new information for an existing amplifier *Fails because the fixed id doesn't exist */ var frisby = require('../node_modules/frisby'); var id = '553c3c90c0541225496a8481'; var URL = 'http://localhost:3000/televisions/' + id; frisby.create('PUT new values for a television with the specified id') .put(URL, { brand: 'dell' } ) .expectStatus(200) .expectHeader('Content-type', 'application/json; charset=utf-8') .expectJSON({ component: 'television', brand: 'dell', cost: 1300, performance: 5, reliability: 0.7, height: 30.8, width: 50.6, thickness: 1.2, weight: 48.7, inputs: [{ type: 'ac power', quantity: 1 }, { type: 'hdmi', quantity: 1 }, { type: 'video', quantity: 1 }], outputs: [] }) .toss();
{'dir': 'javascript', 'id': '18790650', 'max_stars_count': '0', 'max_stars_repo_name': 'pjlinn/homeTheaterNodeApp', 'max_stars_repo_path': 'fullHomeTheaterApp/server/spec/updateTelevision_spec.js', 'n_tokens_mistral': 379, 'n_tokens_neox': 306, 'n_words': 80}
//////////////////////////////////////////////////////////////////////////////// // // CopyRight (c) 2016 <NAME> // // Author : <NAME> // // Description : Thread safe hash table // //////////////////////////////////////////////////////////////////////////////// #pragma once #include "SFTypedefs.h" #include "SFAssert.h" #include "Container/SFIndexing.h" #include "Multithread/SFSystemSynchronization.h" #include "Container/SFArray.h" #include "Container/SFContainerTrait.h" namespace SF { ///////////////////////////////////////////////////////////////////////////////// // // Thread safe hash map // template< typename KeyType, typename ItemType, typename Trait = UniqueKeyTrait, typename ThreadTrait = ThreadSyncTraitReadWriteT<KeyType,ItemType>, typename HasherType = SF::hash<KeyType> > class HashTable2 { public: // internal aliasing typedef ItemType ValueType; typedef typename ThreadTrait::TicketLockType TicketLockType; typedef typename ThreadTrait::ItemContainer ItemContainer; // internal aliasing //typedef typename ItemContainer::iterator ItemIterator; /////////////////////////////////////////////////////////////////////////////////////////////// // Hash bucket class Bucket { public: // thread lock for bucket access mutable TicketLockType m_Lock; public: void ReadLock() { m_Lock.NonExLock(); } void ReadUnlock() { m_Lock.NonExUnlock(); } void WriteLock() { m_Lock.ExLock(); } void WriteUnlock() { m_Lock.ExUnlock(); } friend HashTable2; public: // Bucket item container ItemContainer *m_Items; IHeap* m_Heap; // Constructor Bucket() : m_Heap(nullptr) { m_Items = nullptr; } // Copy Constructor Bucket( const Bucket& src ) : m_Heap(src.m_Heap) { m_Items = nullptr; (void)(src); // No one use this bucket, while this operation //Assert( !src.m_Lock.IsLocked() ); Assert(false); } // Destructor ~Bucket() { if (m_Items != nullptr) IHeap::Delete(m_Items); } Bucket& operator = ( const Bucket& src ) { // No one use this bucket, while this operation Assert( !src.m_Lock.IsLocked() ); Assert( !m_Lock.IsLocked() ); //m_Items = src.m_Items; Assert(false); return *this; } Bucket& operator = ( Bucket&& src ) { // No one use this bucket, while this operation Assert( !src.m_Lock.IsLocked() ); Assert( !m_Lock.IsLocked() ); //m_Items = src.m_Items; Assert(false); return *this; } void SetObjectPool(IHeap& memoryManager) { m_Heap = &memoryManager; if (m_Items) memoryManager.Delete(m_Items); m_Items = new(memoryManager) ItemContainer(memoryManager); } // validate bucket id bool Validate( size_t iMyBucket, size_t szNumBucket ) { bool isSuccess = true; // Validate only debug mode //#ifdef _DEBUG // std::atomic_thread_fence(std::memory_order_acquire); // m_Items->ForeachOrder(0, (uint)m_Items->size(), [](const KeyType& key, const ValueType& value) -> bool // { // size_t hashVal = HasherType()(key); // size_t iBucket = hashVal%szNumBucket; // AssertRel( iBucket == iMyBucket ); // if( iBucket != iMyBucket ) // { // isSuccess &= false; // } // return true; // }); //#endif return isSuccess; } }; typedef std::vector<Bucket> BucketListType; typedef typename BucketListType::iterator BucketListIterator; //// Iterator //class iterator //{ //public: //private: // // Is Bucket internal iterator?, then only iterate inside bucket // bool m_bIsIterInBucket; // // Bucket list iterator. directing which bucket // BucketListIterator m_itBucket; // // in-bucket item iterator // ItemIterator m_itItem; // // Main container pointer // HashTable *m_pContainer; // enum { END_IDX = -1 }; // // constructor // iterator(HashTable *pContainer, const BucketListIterator& itBucket, const ItemIterator& itItem, bool bIsBucketIter = false) // : m_bIsIterInBucket(bIsBucketIter) // , m_itBucket(itBucket) // , m_itItem(itItem) // , m_pContainer(pContainer) // { // if (m_pContainer && m_itBucket != m_pContainer->bucket_end() && m_itItem != m_itBucket->m_Items.end()) // m_itBucket->ReadLock(); // } // friend class HashTable2; // void NextIter() // { // Assert(m_pContainer != nullptr); // Assert(m_itBucket != m_pContainer->bucket_end()); // ++m_itItem; // if (m_itItem == m_itBucket->m_Items.end()) // return; // if (m_bIsIterInBucket) // { // m_iIdx = m_itBucket->m_Items.end(); // m_itBucket = m_pContainer->bucket_end(); // return; // } // m_itBucket->ReadUnlock(); // m_itBucket++; // while (m_itBucket != m_pContainer->bucket_end()) // { // if (m_itBucket->m_Items.size() != 0) // { // m_itBucket->ReadLock(); // if (m_itBucket->m_Items.size() != 0) // { // m_itItem = m_itBucket->m_Items.begin(); // return; // } // // no item, move to next bucket // m_itBucket->ReadUnlock(); // } // m_itBucket++; // } // m_itItem = ItemIterator(); // } // // set iter // void Set(HashTable *pContainer, const BucketListIterator& itBucket, const ItemIterator& itItem, bool bIsLock = true, bool bIsBucketIter = false) // { // if (m_pContainer && m_itBucket != m_pContainer->bucket_end() && m_iIdx > END_IDX) // m_itBucket->ReadUnlock(); // m_bIsIterInBucket = bIsBucketIter; // m_pContainer = pContainer; // m_itBucket = itBucket; // m_itItem = itItem; // if (m_pContainer && m_itBucket != m_pContainer->bucket_end() && m_itItem != m_itBucket->m_Items.end()) // m_itBucket->ReadLock(); // } //public: // iterator() // : m_bIsIterInBucket(false) // , m_pContainer(nullptr) // { // } // iterator(const iterator& src) // : m_bIsIterInBucket(false) // , m_itBucket(src.m_itBucket) // , m_pContainer(src.m_pContainer) // , m_itItem(src.m_itItem) // { // if (m_pContainer && m_itBucket != m_pContainer->bucket_end()) // { // m_itBucket->ReadLock(); // } // } // ~iterator() // { // if (m_pContainer && m_itBucket != m_pContainer->bucket_end()) // m_itBucket->ReadUnlock(); // } // iterator& operator++() // { // NextIter(); // return *this; // } // const iterator& operator++() const // { // NextIter(); // return *this; // } // ItemType& operator* () // { // AssertRel(m_pContainer != nullptr); // m_pCache = m_itItem; // return m_itItem->Data; // } // const ItemType& operator* () const // { // AssertRel(m_pContainer != nullptr); // return m_itItem->Data; // } // ItemType& operator-> () // { // AssertRel(m_pContainer != nullptr); // return m_itItem->Data; // } // const ItemType& operator-> () const // { // AssertRel(m_pContainer != nullptr); // return m_itItem->Data; // } // KeyType GetKey() const // { // return m_itItem->Key; // } // bool operator !=(const iterator& op) const // { // return ((m_pContainer != op.m_pContainer) || (m_itBucket != op.m_itBucket) || (m_itItem != op.m_itItem)); // } // bool operator ==(const iterator& op) const // { // return ((m_pContainer == op.m_pContainer) && (m_itBucket == op.m_itBucket) && (m_itItem == op.m_itItem)); // } // // Check validity // bool IsValid() // { // return m_pContainer && m_itBucket != m_pContainer->bucket_end(); // } // // reset iterator and make invalid // void Reset() // { // *this = nullptr; // } // iterator& operator = (const iterator& op) // { // if (m_pContainer && m_itBucket != m_pContainer->bucket_end()) // { // m_itBucket->ReadUnlock(); // } // m_pContainer = op.m_pContainer; // m_itBucket = op.m_itBucket; // m_itItem = op.m_itItem; // //// if some write lock occurred after op gain read lock then this case make Dead lock // //// if you got this assert then use with another way // //Assert( m_pContainer == nullptr || m_itBucket == m_pContainer->bucket_end() ); // if (m_pContainer && m_itBucket != m_pContainer->bucket_end()) // { // m_itBucket->ReadLock(); // } // return *this; // } // iterator& operator = (const void* pPtr) // { // Assert(pPtr == 0); // if (m_pContainer && m_itBucket != m_pContainer->bucket_end()) // { // m_itBucket->ReadUnlock(); // m_itBucket = m_pContainer->bucket_end(); // } // m_pContainer = nullptr; // m_itItem = ItemIterator(); // // if some write lock occurred after op gain read lock then this case make Dead lock // // if you got this assert then use with another way // Assert(m_pContainer == nullptr || m_itBucket == m_pContainer->bucket_end()); // return *this; // } //}; private: IHeap& m_Heap; // bucket std::vector<Bucket> m_Buckets; // total count of item SyncCounter m_lItemCount; public: HashTable2( IHeap& memoryManager, INT iBucketCount = 16) : m_Heap(memoryManager) , m_lItemCount(0) { SetBucketCount(iBucketCount); } virtual ~HashTable2() { } CounterType size() { return m_lItemCount.load(std::memory_order_relaxed); } // resize bucket // NOTE: This method is NOT THREAD SAFE and NOT DATA SAFE void SetBucketCount( size_t iBucketCount ) { m_Buckets.resize( iBucketCount ); for (uint iBucket = 0; iBucket < m_Buckets.size(); iBucket++) { m_Buckets[iBucket].SetObjectPool(m_Heap); } } // Bucket Count size_t GetBucketCount() const { return m_Buckets.size(); } BucketListIterator bucket_begin() { return m_Buckets.begin(); } BucketListIterator bucket_end() { return m_Buckets.end(); } ////////////////////////////////////////////////////////////////////////// // // Insert/erase/clear // Result Insert( const KeyType key, const ItemType &data ) { size_t hashVal = HasherType()(key); size_t iBucket = hashVal%m_Buckets.size(); Bucket& bucket = m_Buckets[iBucket]; TicketScopeLockT<TicketLockType> scopeLock( TicketLock::LockMode::Exclusive, bucket.m_Lock ); if constexpr (Trait::UniqueKey) { ItemType dataFound; if constexpr (ThreadTrait::ThreadSafe) { if ((bucket.m_Items->FindInWriteTree(key, dataFound))) { return ResultCode::FAIL; } } else { if ((bucket.m_Items->Find(key, dataFound))) { return ResultCode::FAIL; } } } bucket.m_Items->Insert(key, data); if constexpr (ThreadTrait::ThreadSafe) { bucket.m_Items->CommitChanges(); } m_lItemCount.fetch_add(1,std::memory_order_relaxed); #ifdef _DEBUG Assert( bucket.Validate(iBucket, m_Buckets.size()) ); #endif return ResultCode::SUCCESS; } Result insert(const KeyType key, const ItemType &data) { return Insert(key, data); } Result Find( const KeyType& keyVal, ItemType &data ) const { size_t hashVal = HasherType()( keyVal ); size_t iBucket = hashVal%m_Buckets.size(); auto& bucket = m_Buckets[iBucket]; TicketScopeLockT<TicketLockType> scopeLock( TicketLock::LockMode::NonExclusive, bucket.m_Lock ); Result hr = bucket.m_Items->Find(keyVal, data); return hr; } Result find(const KeyType& keyVal, ItemType &data) const { return Find(keyVal, data); } // Erase a data from hash map Result Erase(const KeyType &key, ValueType& erasedValue) { if (m_Buckets.size() == 0) return ResultCode::SUCCESS_FALSE; size_t hashVal = HasherType()(key); size_t iBucket = hashVal%m_Buckets.size(); Bucket& bucket = m_Buckets[iBucket]; TicketScopeLockT<TicketLockType> scopeLock(TicketLock::LockMode::Exclusive, bucket.m_Lock); if ((bucket.m_Items->Remove(key, erasedValue))) { if constexpr (ThreadTrait::ThreadSafe) { bucket.m_Items->CommitChanges(); } m_lItemCount.fetch_sub(1, std::memory_order_relaxed); return ResultCode::SUCCESS; } Assert(bucket.Validate(iBucket, m_Buckets.size())); return ResultCode::FAIL; } Result erase(const KeyType &key) { ValueType erasedValue; return Erase(key, erasedValue); } Result erase(const KeyType &key, ValueType& erasedValue) { return Erase(key, erasedValue); } Result remove(const KeyType& key) { ValueType erasedValue; return Erase(key, erasedValue); } Result remove(const KeyType& key, ValueType& erasedValue) { return Erase(key, erasedValue); } Result Clear() { return Reset(); } Result Reset() { m_lItemCount = 0; auto itBucket = m_Buckets.begin(); for( ; itBucket != m_Buckets.end(); ++itBucket ) { itBucket->m_Items->ClearMap(); } return ResultCode::SUCCESS; } bool Validate() { #ifdef _DEBUG BucketListType::iterator itBucket = m_Buckets.begin(); for( INT iBucket = 0; itBucket != m_Buckets.end(); ++itBucket, ++iBucket ) { if( !itBucket->Validate( iBucket, m_Buckets.size() ) ) return false; } #endif return true; } // Func(const KeyType& key, const ItemType& item)->bool template<class Functor> // (const KeyType& key, const ItemType& item) void for_each(Functor func) { auto itBucket = m_Buckets.begin(); for (INT iBucket = 0; itBucket != m_Buckets.end(); ++itBucket, ++iBucket) { if (itBucket->m_Items == nullptr) continue; itBucket->m_Items->ForeachOrder(0, (uint)itBucket->m_Items->size(), func); } } }; } // namespace SF
{'dir': 'c', 'id': '2763618', 'max_stars_count': '1', 'max_stars_repo_name': 'blue3k/StormForge', 'max_stars_repo_path': 'Engine/Src/SFCore/Container/SFHashTable2.h', 'n_tokens_mistral': 6396, 'n_tokens_neox': 4982, 'n_words': 937}
<filename>src/fptr10.h<gh_stars>0 #include <nan.h> #include "libfptr10.h" #include "utils.h" class Fptr10 : public Nan::ObjectWrap { public: libfptr_handle fptr; double x; static NAN_MODULE_INIT(Init); static NAN_METHOD(New); static NAN_METHOD(IsOpened); static NAN_METHOD(Create); static NAN_METHOD(Destroy); static NAN_METHOD(GetSettings); static NAN_METHOD(SetSettings); static NAN_METHOD(Open); static NAN_METHOD(Close); static NAN_METHOD(ProcessJson); static NAN_METHOD(FnReport); static NAN_METHOD(FindLastDocument); static NAN_GETTER(HandleGetters); static NAN_SETTER(HandleSetters); static Nan::Persistent<v8::FunctionTemplate> constructor; };
{'dir': 'c', 'id': '6799377', 'max_stars_count': '0', 'max_stars_repo_name': 'pbardov/node-atol-wrapper', 'max_stars_repo_path': 'src/fptr10.h', 'n_tokens_mistral': 263, 'n_tokens_neox': 249, 'n_words': 47}
<filename>VirtualWork.WinForms/Providers/PasswordManagerGroupsProvider.cs using System.Linq; using System.Windows.Forms; using LanguageService; using VirtualWork.Interfaces.Enums; using VirtualWork.Persistence.Repositories; namespace VirtualWork.WinForms.Providers { public class PasswordManagerGroupsProvider { private readonly CredentialsRepository credentialsRepository; public PasswordManagerGroupsProvider(CredentialsRepository credentialsRepository) { this.credentialsRepository = credentialsRepository; } public void GetGroups(ComboBox comboBox) { comboBox.Items.Clear(); var groups = credentialsRepository.GetGroups(credentials => (credentials.ActorType == (int)ActorType.User && credentials.ActorId == Initializer.LoggedInUser.Id) || (credentials.ActorType == (int)ActorType.Group && Initializer.LoggedInUser.Groups.Any(group => group.Id == credentials.ActorId))); comboBox.Items.Add(Lng.Elem("All")); foreach (var group in groups) { comboBox.Items.Add(group); } } } }
{'dir': 'c-sharp', 'id': '10374901', 'max_stars_count': '0', 'max_stars_repo_name': 'Mortens4444/VirtualWork', 'max_stars_repo_path': 'VirtualWork.WinForms/Providers/PasswordManagerGroupsProvider.cs', 'n_tokens_mistral': 338, 'n_tokens_neox': 295, 'n_words': 49}
<reponame>openeuler-mirror/raspberrypi-build<gh_stars>0 #!/bin/bash systemctl enable sshd systemctl enable systemd-timesyncd systemctl enable hciuart systemctl enable haveged echo openEuler > /etc/hostname echo "openeuler" | passwd --stdin root if [ -f /usr/share/zoneinfo/Asia/Shanghai ]; then if [ -f /etc/localtime ]; then rm -f /etc/localtime fi ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime fi if [ -f /etc/rc.d/rc.local ]; then chmod +x /etc/rc.d/rc.local fi cd /etc/rc.d/init.d chmod +x extend-root.sh chkconfig --add extend-root.sh chkconfig extend-root.sh on cd - ln -s /lib/firmware /etc/firmware
{'dir': 'shell', 'id': '315684', 'max_stars_count': '0', 'max_stars_repo_name': 'openeuler-mirror/raspberrypi-build', 'max_stars_repo_path': 'config/chroot.sh', 'n_tokens_mistral': 257, 'n_tokens_neox': 249, 'n_words': 63}
<filename>nyla.solutions.xml/src/main/java/nyla/solutions/xml/XmlXslDecorator.java package nyla.solutions.xml; import nyla.solutions.core.data.Textable; import nyla.solutions.core.exception.RequiredException; import nyla.solutions.core.exception.SystemException; import nyla.solutions.core.patterns.decorator.TextDecorator; import nyla.solutions.core.util.Config; import nyla.solutions.core.util.Debugger; import nyla.solutions.core.util.Text; public class XmlXslDecorator implements TextDecorator<Textable> { /** * * * @return the XML */ public Textable getTarget() { return xml; }//-------------------------------------------- /** * Calls target.getText if target is a textable else * @param target */ public void setTarget(Textable target) { if(target == null) throw new RequiredException("target in XmlXslDecorator.setTarget"); this.xml = target; }//-------------------------------------------- /** * * @return the XML text */ public String getText() { try { String text = xml.getText(); if(Text.isNull(text)) { return emptyResults; } String results = null; if(this.xslUrl != null) { DOM4J xmlService = new DOM4J(this.xml.getText()); results = XML.transform(xmlService.getXml(), xslUrl); } else { if(this.xsl == null || this.xsl.length() == 0) throw new RequiredException("xsl"); if(this.stripHeader) { xsl = XML.stripHeader(this.xsl); } results = XSL.transform(XSL.toStreamSource(this.xsl), this.xml.getText()); } if(this.stripHeader) results = XML.stripHeader(results); return results; } catch (Exception e) { throw new SystemException(Debugger.stackTrace(e)+ "xml="+xml); } }//-------------------------------------------- /** * @return the xslUrl */ public String getXslUrl() { return xslUrl; }//-------------------------------------------- /** * @param xslUrl the xslUrl to set */ public void setXslUrl(String xslUrl) { this.xslUrl = xslUrl; }//-------------------------------------------- /** * @return the stripHeader */ public boolean isStripHeader() { return stripHeader; }//-------------------------------------------- /** * @param stripHeader the stripHeader to set */ public void setStripHeader(boolean stripHeader) { this.stripHeader = stripHeader; }//-------------------------------------------- /** * @return the emptyResults */ public String getEmptyResults() { return emptyResults; } /** * @param emptyResults the emptyResults to set */ public void setEmptyResults(String emptyResults) { this.emptyResults = emptyResults; } /** * @return the xsl */ public String getXsl() { return xsl; } /** * @param xsl the xsl to set */ public void setXsl(String xsl) { this.xsl = xsl; } private String emptyResults = ""; private String xslUrl = null; private String xsl = null; private Textable xml = null; private boolean stripHeader = Config.getPropertyBoolean(XmlXslDecorator.class.getName()+".stripHeader", true).booleanValue(); }
{'dir': 'java', 'id': '704284', 'max_stars_count': '0', 'max_stars_repo_name': 'nyla-solutions/nyla-xml', 'max_stars_repo_path': 'nyla.solutions.xml/src/main/java/nyla/solutions/xml/XmlXslDecorator.java', 'n_tokens_mistral': 1085, 'n_tokens_neox': 1036, 'n_words': 205}
/* * Copyright (C) 2013 <NAME> * * 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 fr.julienvermet.bugdroid.ui.phone; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.Spinner; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.Tab; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Window; import fr.julienvermet.bugdroid.R; import fr.julienvermet.bugdroid.model.Bug; import fr.julienvermet.bugdroid.ui.BugFragment; public class BugActivity extends SherlockFragmentActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener, BugFragment.BugLoadingListener { private static final String BUG_ID = "bugId"; private static final String BUG_TITLE = "bugTitle"; // Android private Tab mTabDetails, mTabComments, mTabAttachments, mTabCcs; public BugFragment mBugFragment; private ActionBar mActionBar; // Objects private int mBugId; private String mBugTitle; public static Intent getIntent(Context context, int bugId, String bugTitle) { Intent intent = new Intent(context, BugActivity.class); intent.putExtra(BUG_ID, bugId); intent.putExtra(BUG_TITLE, bugTitle); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.activity_singlepane_empty); Bundle bundle = getIntent().getExtras(); if (bundle != null) { mBugId = bundle.getInt(BUG_ID); mBugTitle = bundle.getString(BUG_TITLE); } else { mBugId = savedInstanceState.getInt(BUG_ID); mBugTitle = savedInstanceState.getString(BUG_TITLE); } mActionBar = getSupportActionBar(); mActionBar.setDisplayHomeAsUpEnabled(true); mActionBar.setTitle(String.valueOf(mBugId)); // We use tab navigation mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mTabDetails = mActionBar.newTab().setText("Details").setTabListener(this); mActionBar.addTab(mTabDetails); mTabComments = mActionBar.newTab().setText("Comments").setTabListener(this); mActionBar.addTab(mTabComments); mTabAttachments = mActionBar.newTab().setText("Attachments").setTabListener(this); mActionBar.addTab(mTabAttachments); mTabCcs = mActionBar.newTab().setText("Ccs").setTabListener(this); mActionBar.addTab(mTabCcs); mBugFragment = (BugFragment) getSupportFragmentManager().findFragmentByTag( BugFragment.class.getSimpleName()); if (mBugFragment == null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); mBugFragment = BugFragment.newInstance(mBugId, mBugTitle); ft.add(R.id.root_container, mBugFragment, BugFragment.class.getSimpleName()); ft.commit(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(BUG_ID, mBugId); outState.putString(BUG_TITLE, mBugTitle); } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { if (mBugFragment != null && mBugFragment.mViewPager != null) { mBugFragment.mViewPager.setCurrentItem(tab.getPosition()); } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageSelected(int position) { mActionBar.setSelectedNavigationItem(position); mActionBar.getTabAt(position).select(); ViewParent root = findViewById(android.R.id.content).getParent(); findAndUpdateSpinner(root, position); } /** * Searches the view hierarchy excluding the content view for a possible * Spinner in the ActionBar. * * @param root * The parent of the content view * @param position * The position that should be selected * @return if the spinner was found and adjusted */ private boolean findAndUpdateSpinner(Object root, int position) { if (root instanceof android.widget.Spinner) { // Found the Spinner Spinner spinner = (Spinner) root; spinner.setSelection(position); return true; } else if (root instanceof ViewGroup) { ViewGroup group = (ViewGroup) root; if (group.getId() != android.R.id.content) { // Found a container that isn't the container holding our screen // layout for (int i = 0; i < group.getChildCount(); i++) { if (findAndUpdateSpinner(group.getChildAt(i), position)) { // Found and done searching the View tree return true; } } } } // Nothing found return false; } @Override public void onBugLoading(int bugId) { setSupportProgressBarIndeterminateVisibility(true); } @Override public void onBugLoaded(Bug bug) { setSupportProgressBarIndeterminateVisibility(false); } }
{'dir': 'java', 'id': '8806040', 'max_stars_count': '1', 'max_stars_repo_name': 'JulienDev/BugDroid', 'max_stars_repo_path': 'app/src/main/java/fr/julienvermet/bugdroid/ui/phone/BugActivity.java', 'n_tokens_mistral': 1849, 'n_tokens_neox': 1755, 'n_words': 432}
package camelinaction; import java.util.List; /** * JMX MBean to find deprecated Camel components. * <p/> * This MBean is what hawtio uses to talk to the backend when it needs * to query the JVM for Camel applications that runs deprecated Camel components. */ public interface CamelComponentDeprecatedMBean { List<String> findDeprecatedComponents(); }
{'dir': 'java', 'id': '5798866', 'max_stars_count': '3', 'max_stars_repo_name': 'maniac787/Apache-Camel-book-camel-in-action-2', 'max_stars_repo_path': 'chapter19/hawtio-custom-plugin/src/main/java/camelinaction/CamelComponentDeprecatedMBean.java', 'n_tokens_mistral': 105, 'n_tokens_neox': 98, 'n_words': 43}
<!DOCTYPE html> <html lang="en"> <head> <?php include 'session_view.php';?> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>AdminLTE 3 | Dashboard</title> <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback"> <!-- Font Awesome --> <link rel="stylesheet" href=".././plugins/fontawesome-free/css/all.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <!-- Tempusdominus Bootstrap 4 --> <link rel="stylesheet" href=".././plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css"> <!-- iCheck --> <link rel="stylesheet" href=".././plugins/icheck-bootstrap/icheck-bootstrap.min.css"> <!-- JQVMap --> <link rel="stylesheet" href=".././plugins/jqvmap/jqvmap.min.css"> <!-- Theme style --> <link rel="stylesheet" href=".././dist/css/adminlte.min.css"> <!-- overlayScrollbars --> <link rel="stylesheet" href=".././plugins/overlayScrollbars/css/OverlayScrollbars.min.css"> <!-- Daterange picker --> <link rel="stylesheet" href=".././plugins/daterangepicker/daterangepicker.css"> <!-- summernote --> <link rel="stylesheet" href=".././plugins/summernote/summernote-bs4.min.css"> <link rel="stylesheet" href="<?php echo base_url() ?>jquery/jquery-3.6.0.min.js"> </head> <body class="hold-transition sidebar-mini layout-fixed"> <?php include "templateAdmin_view.php" ?>; <div class="container "> <div class="row justify-content-center"> <div class="col-6"> <h3 class="text-center">Add football match </h3> <form method="POST" enctype="multipart/form-data" action="InsertMatch_controller/insertMatch"> <fieldset class="form-group"> <label for="img">Image team home</label> <input name="img-home" type="file" class="form-control" id="img-home" > </fieldset> <fieldset class="form-group"> <label for="name">Name team home</label> <input name="name-home" type="text" class="form-control" id="name-home" placeholder="Ex : Anh"> </fieldset> <fieldset class="form-group"> <label for="time">Time this match</label> <input name="time" type="text" class="form-control" id="time" placeholder="02:00"> </fieldset> <fieldset class="form-group"> <select name="date" class="form-select" aria-label="Default select example"> <option selected>---Select date---</option> <option value="Hôm nay">Hôm nay</option> <option value="Ngày mai">Ngày mai</option> </select> </fieldset> <fieldset class="form-group"> <label for="img">Image team way</label> <input name="img-way" type="file" class="form-control" id="img-way" > </fieldset> <fieldset class="form-group"> <label for="name">Name team way</label> <input name="name-way" type="text" class="form-control" id="name-way" placeholder="Ex : Ukraine"> </fieldset> <fieldset class="form-group"> <label for="name">Name league</label> <input name="name-league" type="text" class="form-control" id="name-league" placeholder="Ex : Euro2021"> </fieldset> <div style="margin-top: 5px;"><button class="btn btn-outline-info" type="submit">Create match</button></div> </form> </div> </div> </div> <!-- jQuery --> <script src=".././plugins/jquery/jquery.min.js"></script> <!-- jQuery UI 1.11.4 --> <script src=".././plugins/jquery-ui/jquery-ui.min.js"></script> <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --> <script> $.widget.bridge('uibutton', $.ui.button) </script> <!-- Bootstrap 4 --> <script src=".././plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- ChartJS --> <script src=".././plugins/chart.js/Chart.min.js"></script> <!-- Sparkline --> <script src=".././plugins/sparklines/sparkline.js"></script> <!-- JQVMap --> <script src=".././plugins/jqvmap/jquery.vmap.min.js"></script> <script src=".././plugins/jqvmap/maps/jquery.vmap.usa.js"></script> <!-- jQuery Knob Chart --> <script src=".././plugins/jquery-knob/jquery.knob.min.js"></script> <!-- daterangepicker --> <script src=".././plugins/moment/moment.min.js"></script> <script src=".././plugins/daterangepicker/daterangepicker.js"></script> <!-- Tempusdominus Bootstrap 4 --> <script src=".././plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script> <!-- Summernote --> <script src=".././plugins/summernote/summernote-bs4.min.js"></script> <!-- overlayScrollbars --> <script src=".././plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script> <!-- AdminLTE App --> <script src=".././dist/js/adminlte.js"></script> <!-- AdminLTE for demo purposes --> <script src=".././dist/js/demo.js"></script> <!-- AdminLTE dashboard demo (This is only for demo purposes) --> <script src=".././dist/js/pages/dashboard.js"></script> <script> $('a').removeClass('active'); $('#manageMatch').addClass('active'); </script> </body> </html>
{'dir': 'php', 'id': '8017889', 'max_stars_count': '0', 'max_stars_repo_name': 'vinh37/football-web', 'max_stars_repo_path': 'application/views/insertMatch_view.php', 'n_tokens_mistral': 1787, 'n_tokens_neox': 1640, 'n_words': 290}
<reponame>aAmanHussain/attainu-ui-service import React from 'react'; import { InputComponent, SelectTagComponent } from '../'; import { SortConfig } from '../../config/sort.config'; import { FilterConfig } from '../../config/filter.config'; export const SearchComponent = ({ term, filter, sort, handleChange, handleSubmit, handleFilter, handleSort }: any) => { return ( <form className='wrapper' onSubmit={handleSubmit}> <InputComponent type='text' name='term' onClick={handleChange} value={term} onChange={handleChange} /> <SelectTagComponent value={filter} options={FilterConfig} onChange={handleFilter} /> <SelectTagComponent value={sort} options={SortConfig} onChange={handleSort} /> <InputComponent type='submit' value='Search' /> </form> ); }
{'dir': 'typescript', 'id': '902020', 'max_stars_count': '0', 'max_stars_repo_name': 'aAmanHussain/attainu-ui-service', 'max_stars_repo_path': 'src/components/search/search.component.tsx', 'n_tokens_mistral': 217, 'n_tokens_neox': 219, 'n_words': 50}
/** * @class Oskari.statistics.statsgrid.StatsGridBundle * * Definitpation for bundle. See source for details. */ Oskari.clazz.define("Oskari.statistics.statsgrid.StatsGridBundle", /** * @method create called automatically on construction * @static */ function () { }, { "create": function () { return Oskari.clazz.create("Oskari.statistics.statsgrid.StatsGridBundleInstance", 'statsgrid'); } }, { "protocol": ["Oskari.bundle.Bundle", "Oskari.mapframework.bundle.extension.ExtensionBundle"], "source": { "scripts": [{ "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/instance.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/FlyoutManager.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/Tile.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/MyIndicatorsTab.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/service/SeriesService.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/service/StatisticsService.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/service/ClassificationService.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/service/ColorService.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/service/StateService.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/service/ErrorService.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/service/Cache.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/service/CacheHelper.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/IndicatorSelection.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/IndicatorParameters.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/IndicatorParametersHandler.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/RegionsetSelector.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/SelectedIndicatorsMenu.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/IndicatorForm.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/IndicatorParametersList.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/IndicatorDataForm.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/IndicatorList.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/Diagram.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/SpanSelect.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/view/TableFlyout.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/view/DiagramFlyout.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/view/Filter.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/view/SearchFlyout.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/view/IndicatorFormFlyout.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/Datatable.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/plugin/TogglePlugin.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/SeriesControl.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/publisher/SeriesToggleTool.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/components/RegionsetViewer.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/event/IndicatorEvent.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/event/DatasourceEvent.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/event/FilterEvent.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/event/RegionsetChangedEvent.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/event/ActiveIndicatorChangedEvent.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/event/RegionSelectedEvent.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/event/ClassificationChangedEvent.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/event/ParameterChangedEvent.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/event/StateChangedEvent.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/publisher/AbstractStatsPluginTool.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/publisher/StatsTableTool.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/publisher/ClassificationTool.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/publisher/ClassificationToggleTool.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/publisher/OpacityTool.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/plugin/ClassificationPlugin.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/plugin/SeriesControlPlugin.js" }, { "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/publisher/DiagramTool.js" }, { "type": "text/css", "src": "../../../bundles/statistics/statsgrid2016/resources/scss/style.scss" }, { "type": "text/css", "src": "../../../bundles/statistics/statsgrid2016/resources/css/seriesplayback.css" }, { "src": "../../../libraries/chosen/1.5.1/chosen.jquery.js", "type": "text/javascript" }, { "src": "../../../libraries/chosen/1.5.1/chosen.css", "type": "text/css" }], "locales": [{ "lang": "en", "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/resources/locale/en.js" }, { "lang": "fi", "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/resources/locale/fi.js" }, { "lang": "fr", "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/resources/locale/fr.js" }, { "lang": "sv", "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/resources/locale/sv.js" }, { "lang": "ru", "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/resources/locale/ru.js" }, { "lang": "is", "type": "text/javascript", "src": "../../../bundles/statistics/statsgrid2016/resources/locale/is.js" }] }, "bundle": { "manifest": { "Bundle-Identifier": "statsgrid", "Bundle-Name": "statsgrid", "Bundle-Author": [{ "Name": "jjk", "Organisatpation": "nls.fi", "Temporal": { "Start": "2013", "End": "2013" }, "Copyleft": { "License": { "License-Name": "EUPL", "License-Online-Resource": "http://www.paikkatietoikkuna.fi/license" } } }], "Bundle-Verspation": "1.0.0", "Import-Namespace": ["Oskari"], "Import-Bundle": {} } }, /** * @static * @property dependencies */ "dependencies": ["jquery"] }); Oskari.bundle_manager.installBundleClass("statsgrid", "Oskari.statistics.statsgrid.StatsGridBundle");
{'dir': 'javascript', 'id': '15270685', 'max_stars_count': '17', 'max_stars_repo_name': 'tsallinen/oskari-frontend', 'max_stars_repo_path': 'packages/statistics/statsgrid/bundle.js', 'n_tokens_mistral': 3168, 'n_tokens_neox': 2898, 'n_words': 315}
class MarkDownElement: def __init__(self, text=''): self._text = text def __str__(self): return self.text def __add__(self, other): return self.text + str(other) def __radd__(self, other): return str(other) + self.text @property def text(self): return str(self._text) class H1(MarkDownElement): def __str__(self): return f'# {self.text}' class H2(MarkDownElement): def __str__(self): return f'## {self.text}' class H3(MarkDownElement): def __str__(self): return f'### {self.text}' class H4(MarkDownElement): def __str__(self): return f'#### {self.text}' class PlainText(MarkDownElement): def __str__(self): return self.text class BlankLine(MarkDownElement): def __str__(self): return '' class Table(MarkDownElement): def __init__(self, headers): self._headers = tuple(str(h) for h in headers) self._entries = [] def add_entry(self, entry): if len(entry) != len(self._headers): raise RuntimeError('Number of element per entry should match that of the header') self._entries.append(tuple([str(e) for e in entry])) def __str__(self): def columns(seq, char='|'): return f'{char}{char.join(seq)}{char}' widths = [len(h) for h in self._headers] for entry in self._entries: for i, z in enumerate(zip(widths, entry)): w, e = z widths[i] = max(w, len(e)) header = [] for i, h in enumerate(self._headers): header.append(self._headers[i].center(widths[i] + 2)) header = columns(header) divider = columns(['-' * (i + 2) for i in widths]) entries = [] for entry in self._entries: e = [f' {i[1].ljust(i[0])} ' for i in zip(widths, entry)] entries.append(columns(e)) result = [] result.append(header) result.append(divider) result+=entries result = '\n'.join(result) return result
{'dir': 'python', 'id': '3262521', 'max_stars_count': '4', 'max_stars_repo_name': 'joshuaskelly/wick', 'max_stars_repo_path': 'wick/generators/markdown/elements.py', 'n_tokens_mistral': 664, 'n_tokens_neox': 632, 'n_words': 171}
<!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="{{base_url('/assets/libs/jquery-3.3.1.min.js')}}"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> {{--datatables script--}} <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script> {{--end datatables script--}} <script src="{{base_url('/assets/js/main.js')}}"></script> <script src="{{base_url('/assets/js/table_config.js')}}"></script>
{'dir': 'php', 'id': '10458181', 'max_stars_count': '0', 'max_stars_repo_name': 'iguxa/test_sof_com_bank', 'max_stars_repo_path': 'application/views/templates/includes/footer_scripts.blade.php', 'n_tokens_mistral': 311, 'n_tokens_neox': 296, 'n_words': 36}
package main import ( "fmt" "github.com/MG-RAST/Shock/conf" e "github.com/MG-RAST/Shock/errors" "github.com/MG-RAST/Shock/store" "github.com/MG-RAST/Shock/store/filter" "github.com/MG-RAST/Shock/store/indexer" "github.com/MG-RAST/Shock/store/user" "github.com/jaredwilkening/goweb" "io" "labix.org/v2/mgo/bson" "net/http" "os" "strconv" "strings" ) type NodeController struct{} func handleAuthError(err error, cx *goweb.Context) { switch err.Error() { case e.MongoDocNotFound: cx.RespondWithErrorMessage("Invalid username or password", http.StatusBadRequest) return case e.InvalidAuth: cx.RespondWithErrorMessage("Invalid Authorization header", http.StatusBadRequest) return } log.Error("Error at Auth: " + err.Error()) cx.RespondWithError(http.StatusInternalServerError) return } // Options: /node func (cr *NodeController) Options(cx *goweb.Context) { LogRequest(cx.Request) cx.RespondWithOK() return } // POST: /node func (cr *NodeController) Create(cx *goweb.Context) { // Log Request and check for Auth LogRequest(cx.Request) u, err := AuthenticateRequest(cx.Request) if err != nil && err.Error() != e.NoAuth { handleAuthError(err, cx) return } // Fake public user if u == nil { if conf.ANON_WRITE { u = &user.User{Uuid: ""} } else { cx.RespondWithErrorMessage(e.NoAuth, http.StatusUnauthorized) return } } // Parse uploaded form params, files, err := ParseMultipartForm(cx.Request) if err != nil { // If not multipart/form-data it will create an empty node. // TODO: create another request parser for non-multipart request // to handle this cleaner. if err.Error() == "request Content-Type isn't multipart/form-data" { node, err := store.CreateNodeUpload(u, params, files) if err != nil { log.Error("Error at create empty: " + err.Error()) cx.RespondWithError(http.StatusInternalServerError) return } if node == nil { // Not sure how you could get an empty node with no error // Assume it's the user's fault cx.RespondWithError(http.StatusBadRequest) return } else { cx.RespondWithData(node) return } } else { // Some error other than request encoding. Theoretically // could be a lost db connection between user lookup and parsing. // Blame the user, Its probaby their fault anyway. log.Error("Error parsing form: " + err.Error()) cx.RespondWithError(http.StatusBadRequest) return } } // Create node node, err := store.CreateNodeUpload(u, params, files) if err != nil { log.Error("err " + err.Error()) cx.RespondWithErrorMessage(err.Error(), http.StatusBadRequest) return } cx.RespondWithData(node) return } // DELETE: /node/{id} func (cr *NodeController) Delete(id string, cx *goweb.Context) { LogRequest(cx.Request) cx.RespondWithError(http.StatusNotImplemented) } // DELETE: /node func (cr *NodeController) DeleteMany(cx *goweb.Context) { LogRequest(cx.Request) cx.RespondWithError(http.StatusNotImplemented) } // GET: /node/{id} // ToDo: clean up this function. About to get unmanageable func (cr *NodeController) Read(id string, cx *goweb.Context) { // Log Request and check for Auth LogRequest(cx.Request) u, err := AuthenticateRequest(cx.Request) if err != nil && err.Error() != e.NoAuth { handleAuthError(err, cx) return } // Fake public user if u == nil { if conf.ANON_READ { u = &user.User{Uuid: ""} } else { cx.RespondWithErrorMessage(e.NoAuth, http.StatusUnauthorized) return } } // Gather query params query := &Query{list: cx.Request.URL.Query()} var fFunc filter.FilterFunc = nil if query.Has("filter") { if filter.Has(query.Value("filter")) { fFunc = filter.Filter(query.Value("filter")) } } // Load node and handle user unauthorized node, err := store.LoadNode(id, u.Uuid) if err != nil { if err.Error() == e.UnAuth { cx.RespondWithError(http.StatusUnauthorized) return } else if err.Error() == e.MongoDocNotFound { cx.RespondWithNotFound() return } else { // In theory the db connection could be lost between // checking user and load but seems unlikely. log.Error("Err@node_Read:LoadNode: " + err.Error()) cx.RespondWithError(http.StatusInternalServerError) return } } // Switch though param flags // ?download=1 if query.Has("download") { if !node.HasFile() { cx.RespondWithErrorMessage("File not found", http.StatusBadRequest) return } //_, chunksize := // ?index=foo if query.Has("index") { //handling bam file if query.Value("index") == "bai" { s := &streamer{rs: []store.SectionReader{}, ws: cx.ResponseWriter, contentType: "application/octet-stream", filename: node.Id, size: node.File.Size, filter: fFunc} var region string if query.Has("region") { //retrieve alingments overlapped with specified region region = query.Value("region") } argv, err := ParseSamtoolsArgs(query) if err != nil { cx.RespondWithErrorMessage("Invaid args in query url", http.StatusBadRequest) return } err = s.stream_samtools(node.FilePath(), region, argv...) if err != nil { cx.RespondWithErrorMessage("error while involking samtools", http.StatusBadRequest) return } return } // if forgot ?part=N if !query.Has("part") { cx.RespondWithErrorMessage("Index parameter requires part parameter", http.StatusBadRequest) return } // open file r, err := node.FileReader() if err != nil { log.Error("Err@node_Read:Open: " + err.Error()) cx.RespondWithError(http.StatusInternalServerError) return } // load index idx, err := node.Index(query.Value("index")) if err != nil { cx.RespondWithErrorMessage("Invalid index", http.StatusBadRequest) return } if idx.Type() == "virtual" { csize := int64(1048576) if query.Has("chunksize") { csize, err = strconv.ParseInt(query.Value("chunksize"), 10, 64) if err != nil { cx.RespondWithErrorMessage("Invalid chunksize", http.StatusBadRequest) return } } idx.Set(map[string]interface{}{"ChunkSize": csize}) } var size int64 = 0 s := &streamer{rs: []store.SectionReader{}, ws: cx.ResponseWriter, contentType: "application/octet-stream", filename: node.Id, filter: fFunc} for _, p := range query.List("part") { pos, length, err := idx.Part(p) if err != nil { cx.RespondWithErrorMessage("Invalid index part", http.StatusBadRequest) return } size += length s.rs = append(s.rs, io.NewSectionReader(r, pos, length)) } s.size = size err = s.stream() if err != nil { // causes "multiple response.WriteHeader calls" error but better than no response cx.RespondWithErrorMessage(err.Error(), http.StatusBadRequest) log.Error("err: " + err.Error()) } } else { //!query.Has("index") nf, err := node.FileReader() if err != nil { // File not found or some sort of file read error. // Probably deserves more checking log.Error("err " + err.Error()) cx.RespondWithError(http.StatusBadRequest) return } s := &streamer{rs: []store.SectionReader{nf}, ws: cx.ResponseWriter, contentType: "application/octet-stream", filename: node.Id, size: node.File.Size, filter: fFunc} err = s.stream() if err != nil { // causes "multiple response.WriteHeader calls" error but better than no response cx.RespondWithErrorMessage(err.Error(), http.StatusBadRequest) log.Error("err " + err.Error()) } } return } else if query.Has("pipe") { cx.RespondWithError(http.StatusNotImplemented) } else if query.Has("list") { cx.RespondWithError(http.StatusNotImplemented) } else { // Base case respond with node in json cx.RespondWithData(node) } } // GET: /node // To do: // - Iterate node queries func (cr *NodeController) ReadMany(cx *goweb.Context) { // Log Request and check for Auth LogRequest(cx.Request) u, err := AuthenticateRequest(cx.Request) if err != nil && err.Error() != e.NoAuth { handleAuthError(err, cx) return } // Gather query params query := &Query{list: cx.Request.URL.Query()} // Setup query and nodes objects q := bson.M{} nodes := store.Nodes{} if u != nil { // Admin sees all if !u.Admin { q["$or"] = []bson.M{bson.M{"acl.read": []string{}}, bson.M{"acl.read": u.Uuid}} } } else { if conf.ANON_READ { // select on only nodes with no read rights set q["acl.read"] = []string{} } else { cx.RespondWithErrorMessage(e.NoAuth, http.StatusUnauthorized) return } } // Gather params to make db query. Do not include the // following list. skip := map[string]int{"limit": 1, "skip": 1, "query": 1, "querytypes": 1} if query.Has("query") { for key, val := range query.All() { _, s := skip[key] if !s { q[fmt.Sprintf("attributes.%s", key)] = val[0] } } } if query.Has("querytypes") { if query.Value("querytypes") != "" { querytypes := strings.Split(query.Value("querytypes"), ",") q["type"] = bson.M{"$all": querytypes} } } // Limit and skip. Set default if both are not specified if query.Has("limit") || query.Has("skip") { var lim, off int if query.Has("limit") { lim, _ = strconv.Atoi(query.Value("limit")) } else { lim = 100 } if query.Has("skip") { off, _ = strconv.Atoi(query.Value("skip")) } else { off = 0 } // Get nodes from db err := nodes.GetAllLimitOffset(q, lim, off) if err != nil { log.Error("err " + err.Error()) cx.RespondWithError(http.StatusBadRequest) return } } else { // Get nodes from db err := nodes.GetAll(q) if err != nil { log.Error("err " + err.Error()) cx.RespondWithError(http.StatusBadRequest) return } } cx.RespondWithData(nodes) return } // PUT: /node/{id} -> multipart-form func (cr *NodeController) Update(id string, cx *goweb.Context) { // Log Request and check for Auth LogRequest(cx.Request) u, err := AuthenticateRequest(cx.Request) if err != nil && err.Error() != e.NoAuth { handleAuthError(err, cx) return } // Gather query params query := &Query{list: cx.Request.URL.Query()} // Fake public user if u == nil { u = &user.User{Uuid: ""} } node, err := store.LoadNode(id, u.Uuid) if err != nil { if err.Error() == e.UnAuth { cx.RespondWithError(http.StatusUnauthorized) return } else if err.Error() == e.MongoDocNotFound { cx.RespondWithNotFound() return } else { // In theory the db connection could be lost between // checking user and load but seems unlikely. log.Error("Err@node_Update:LoadNode: " + err.Error()) cx.RespondWithError(http.StatusInternalServerError) return } } if query.Has("index") { if !node.HasFile() { cx.RespondWithErrorMessage("node file empty", http.StatusBadRequest) return } if query.Value("index") == "bai" { //bam index is created by the command-line tool samtools if ext := node.FileExt(); ext == ".bam" { if err := CreateBamIndex(node.FilePath()); err != nil { cx.RespondWithErrorMessage("Error while creating bam index", http.StatusBadRequest) return } return } else { cx.RespondWithErrorMessage("Index type bai requires .bam file", http.StatusBadRequest) return } } newIndexer := indexer.Indexer(query.Value("index")) f, _ := os.Open(node.FilePath()) defer f.Close() idxer := newIndexer(f) err := idxer.Create() if err != nil { log.Error("err " + err.Error()) } err = idxer.Dump(node.IndexPath() + "/record") if err != nil { cx.RespondWithErrorMessage(err.Error(), http.StatusBadRequest) return } else { cx.RespondWithOK() return } } else { params, files, err := ParseMultipartForm(cx.Request) if err != nil { log.Error("err " + err.Error()) cx.RespondWithError(http.StatusBadRequest) return } err = node.Update(params, files) if err != nil { errors := []string{e.FileImut, e.AttrImut, "parts cannot be less than 1"} for e := range errors { if err.Error() == errors[e] { cx.RespondWithErrorMessage(err.Error(), http.StatusBadRequest) return } } log.Error("err " + err.Error()) cx.RespondWithErrorMessage(err.Error(), http.StatusBadRequest) return } cx.RespondWithData(node) } return } // PUT: /node func (cr *NodeController) UpdateMany(cx *goweb.Context) { LogRequest(cx.Request) cx.RespondWithError(http.StatusNotImplemented) }
{'dir': 'go', 'id': '999310', 'max_stars_count': '1', 'max_stars_repo_name': 'prinsmike/Shock', 'max_stars_repo_path': 'shock-server/nodeController.go', 'n_tokens_mistral': 4906, 'n_tokens_neox': 4236, 'n_words': 1017}
<reponame>danmysak/polymapper const DEFAULT_MARKER_RADIUS = 20; // In Google Maps units (~meters), if divided by RADIUS_COEFFICIENT const MIN_MARKER_RADIUS = 1; const MAX_MARKER_RADIUS = 500; const RADIUS_COEFFICIENT = 2000; const DEFAULT_MARKER_COLOR = '#0000ff'; const DEFAULT_POLYGON_COLOR = '#ff0000'; const MARKER_STROKE_OPACITY = 1.0; const MARKER_FILL_OPACITY = 0.4; const POLYGON_STROKE_OPACITY = 1.0; const POLYGON_FILL_OPACITY = 0.4; const NEW_POLYGON_RATIO = 4.0; // The new square’s side will be this times less than Maps’ least dimension const MAP_OPTIONS = { zoom: 2, center: {lat: 0, lng: 0}, mapTypeId: 'terrain', streetViewControl: false, rotateControl: false };
{'dir': 'javascript', 'id': '9956177', 'max_stars_count': '0', 'max_stars_repo_name': 'danmysak/polymapper', 'max_stars_repo_path': 'src/config/params.js', 'n_tokens_mistral': 315, 'n_tokens_neox': 277, 'n_words': 71}
import * as React from "react"; const SvgDatabase = (props: React.SVGProps<SVGSVGElement>) => { const { size, fill, style } = props; return ( <svg {...props} className="database_svg__icon" viewBox="0 0 1087 1024" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" fontSize={size || 32} fill={fill || "currentColor"} style={style} > <path d="M127.936 154.867a411.314 154.867 0 10822.629 0 411.314 154.867 0 10-822.629 0z" /> <path d="M676.462 756.87l64.863-64.8c-59.554 10.17-127.744 16.696-199.964 16.696-224.911 0-412.401-62.689-412.401-104.652v209.111c0 75.994 184.675 137.276 412.401 137.276a1145.027 1145.027 0 00166.637-11.77l75.226-75.227L676.462 756.87zM543.344 634.499c227.79 0 412.402-62.817 412.402-140.474V279.988c0 42.987-187.554 107.082-412.402 107.082s-412.401-64.095-412.401-107.082v214.037c0 77.657 184.675 140.474 412.401 140.474z" /> <path d="M1086.88 754.759l-52.197-52.198-108.874 108.937L819.11 704.864l-52.133 52.006 106.698 106.698-107.786 107.85 52.07 52.198 107.914-107.914 108.874 108.938 52.134-52.07-108.938-108.874 108.938-108.937z" /> </svg> ); }; export default SvgDatabase;
{'dir': 'typescript', 'id': '9217914', 'max_stars_count': '0', 'max_stars_repo_name': 'pengjielee/xun-icons', 'max_stars_repo_path': 'src/icons/Database.tsx', 'n_tokens_mistral': 888, 'n_tokens_neox': 531, 'n_words': 90}
# # When publishing work that uses these basis sets, please use the following citation: # # <NAME>, Theor. Chem. Acc. (1998) 99:366; addendum Theor. Chem. Acc. (2002) 108:365; # revision Theor. Chem. Acc. (2006) 115:441. Basis sets available from the Dirac web site, # http://dirac.chem.sdu.dk. Pt = [[0, -1, [62342089.0,1]], [0, -1, [16589944.0,1]], [0, -1, [5681162.1,1]], [0, -1, [2164841.8,1]], [0, -1, [902504.9,1]], [0, -1, [397530.86,1]], [0, -1, [183323.91,1]], [0, -1, [87299.317,1]], [0, -1, [42706.731,1]], [0, -1, [21351.254,1]], [0, -1, [10883.187,1]], [0, -1, [5642.9413,1]], [0, -1, [2971.6339,1]], [0, -1, [1587.1535,1]], [0, -1, [858.6781,1]], [0, -1, [470.0627,1]], [0, -1, [258.41934,1]], [0, -1, [144.5214,1]], [0, -1, [81.390237,1]], [0, -1, [44.8666,1]], [0, -1, [26.054094,1]], [0, -1, [14.857134,1]], [0, -1, [8.0188666,1]], [0, -1, [4.412026,1]], [0, -1, [2.2028461,1]], [0, -1, [1.1747053,1]], [0, -1, [0.58038176,1]], [0, -1, [0.20062925,1]], [0, -1, [0.087656027,1]], [0, -1, [0.037707853,1]], [1, 0, [25681628.0,1]], [1, 0, [5208104.3,1]], [1, 0, [1287419.1,1]], [1, 0, [361868.0,1]], [1, 0, [112348.86,1]], [1, 0, [37965.378,1]], [1, 0, [13886.26,1]], [1, 0, [5481.1599,1]], [1, 0, [2321.6748,1]], [1, 0, [1045.6767,1]], [1, 0, [495.08759,1]], [1, 0, [243.80244,1]], [1, 0, [124.04519,1]], [1, 0, [64.324598,1]], [1, 0, [34.404369,1]], [1, 0, [18.460629,1]], [1, 0, [9.6342884,1]], [1, 0, [4.9988583,1]], [1, 0, [2.43708,1]], [1, 0, [1.194136,1]], [1, 0, [0.54650458,1]], [1, 0, [0.18944919,1]], [1, 0, [0.072990782,1]], [1, 0, [0.027478234,1]], [2, 0, [13726.278,1]], [2, 0, [3497.1942,1]], [2, 0, [1231.0132,1]], [2, 0, [511.61232,1]], [2, 0, [234.47388,1]], [2, 0, [114.63,1]], [2, 0, [58.167907,1]], [2, 0, [30.288845,1]], [2, 0, [15.719476,1]], [2, 0, [7.9912638,1]], [2, 0, [3.9867188,1]], [2, 0, [1.8480542,1]], [2, 0, [0.82389625,1]], [2, 0, [0.3400657,1]], [2, 0, [0.12605538,1]], [3, 0, [753.39068,1]], [3, 0, [256.76136,1]], [3, 0, [109.32209,1]], [3, 0, [51.54658,1]], [3, 0, [25.680605,1]], [3, 0, [13.091382,1]], [3, 0, [6.622071,1]], [3, 0, [3.2448099,1]], [3, 0, [1.455748,1]], [3, 0, [0.48555165,1]], ] At = [[0, 0, [6.0348256E+07, 1]], [0, 0, [1.6062187E+07, 1]], [0, 0, [5.4983695E+06, 1]], [0, 0, [2.0938854E+06, 1]], [0, 0, [8.7397731E+05, 1]], [0, 0, [3.8623125E+05, 1]], [0, 0, [1.7922839E+05, 1]], [0, 0, [8.6061821E+04, 1]], [0, 0, [4.2514482E+04, 1]], [0, 0, [2.1466450E+04, 1]], [0, 0, [1.1045500E+04, 1]], [0, 0, [5.7758353E+03, 1]], [0, 0, [3.0646676E+03, 1]], [0, 0, [1.6479440E+03, 1]], [0, 0, [8.9662945E+02, 1]], [0, 0, [4.9214492E+02, 1]], [0, 0, [2.7496500E+02, 1]], [0, 0, [1.5580890E+02, 1]], [0, 0, [8.9322531E+01, 1]], [0, 0, [5.1403858E+01, 1]], [0, 0, [3.0206500E+01, 1]], [0, 0, [1.7630085E+01, 1]], [0, 0, [9.9209803E+00, 1]], [0, 0, [5.7049663E+00, 1]], [0, 0, [3.1798259E+00, 1]], [0, 0, [1.7280434E+00, 1]], [0, 0, [9.2265694E-01, 1]], [0, 0, [4.1308099E-01, 1]], [0, 0, [1.9366504E-01, 1]], [0, 0, [8.5956507E-02, 1]], [1, 0, [4.8082029E+07, 1]], [1, 0, [1.2975956E+07, 1]], [1, 0, [3.8822931E+06, 1]], [1, 0, [1.2615276E+06, 1]], [1, 0, [4.3747176E+05, 1]], [1, 0, [1.6030701E+05, 1]], [1, 0, [6.1733059E+04, 1]], [1, 0, [2.4933585E+04, 1]], [1, 0, [1.0565929E+04, 1]], [1, 0, [4.6991896E+03, 1]], [1, 0, [2.1896979E+03, 1]], [1, 0, [1.0645378E+03, 1]], [1, 0, [5.3640018E+02, 1]], [1, 0, [2.7850004E+02, 1]], [1, 0, [1.4769404E+02, 1]], [1, 0, [7.9030729E+01, 1]], [1, 0, [4.3330235E+01, 1]], [1, 0, [2.3734199E+01, 1]], [1, 0, [1.2673710E+01, 1]], [1, 0, [6.8190161E+00, 1]], [1, 0, [3.5177624E+00, 1]], [1, 0, [1.8070376E+00, 1]], [1, 0, [8.9279827E-01, 1]], [1, 0, [3.7624123E-01, 1]], [1, 0, [1.5747465E-01, 1]], [1, 0, [6.2205718E-02, 1]], [2, 0, [4.3024363E+04, 1]], [2, 0, [1.0418508E+04, 1]], [2, 0, [3.4997410E+03, 1]], [2, 0, [1.4042448E+03, 1]], [2, 0, [6.3128950E+02, 1]], [2, 0, [3.0578892E+02, 1]], [2, 0, [1.5622137E+02, 1]], [2, 0, [8.2504058E+01, 1]], [2, 0, [4.4686721E+01, 1]], [2, 0, [2.4327946E+01, 1]], [2, 0, [1.3054823E+01, 1]], [2, 0, [6.9879667E+00, 1]], [2, 0, [3.6596287E+00, 1]], [2, 0, [1.8569526E+00, 1]], [2, 0, [9.1045074E-01, 1]], [2, 0, [4.2148358E-01, 1]], [2, 0, [1.7153562E-01, 1]], [3, 0, [1.1997393E+03, 1]], [3, 0, [4.0625428E+02, 1]], [3, 0, [1.7260851E+02, 1]], [3, 0, [8.2092879E+01, 1]], [3, 0, [4.1340525E+01, 1]], [3, 0, [2.1511024E+01, 1]], [3, 0, [1.1203968E+01, 1]], [3, 0, [5.7270911E+00, 1]], [3, 0, [2.7467309E+00, 1]], [3, 0, [1.0823341E+00, 1]], [3, 0, [3.7295068E-01, 1]],] I = [[0, 0, [7.6175652E+07, 1]], [0, 0, [1.9849983E+07, 1]], [0, 0, [6.5395721E+06, 1]], [0, 0, [2.3596246E+06, 1]], [0, 0, [9.1352219E+05, 1]], [0, 0, [3.7073402E+05, 1]], [0, 0, [1.5693523E+05, 1]], [0, 0, [6.8905393E+04, 1]], [0, 0, [3.1288540E+04, 1]], [0, 0, [1.4648899E+04, 1]], [0, 0, [7.0539515E+03, 1]], [0, 0, [3.4846093E+03, 1]], [0, 0, [1.7615182E+03, 1]], [0, 0, [9.0920153E+02, 1]], [0, 0, [4.7786933E+02, 1]], [0, 0, [2.5427862E+02, 1]], [0, 0, [1.3385760E+02, 1]], [0, 0, [7.3157057E+01, 1]], [0, 0, [4.0187794E+01, 1]], [0, 0, [2.1892839E+01, 1]], [0, 0, [1.2282452E+01, 1]], [0, 0, [6.9006489E+00, 1]], [0, 0, [3.7685525E+00, 1]], [0, 0, [1.9974585E+00, 1]], [0, 0, [1.0477282E+00, 1]], [0, 0, [4.2646199E-01, 1]], [0, 0, [2.0028304E-01, 1]], [0, 0, [8.8978635E-02, 1]], [1, 0, [7.5310209E+06, 1]], [1, 0, [1.1662681E+06, 1]], [1, 0, [2.5045040E+05, 1]], [1, 0, [6.5445899E+04, 1]], [1, 0, [1.9932240E+04, 1]], [1, 0, [6.9208735E+03, 1]], [1, 0, [2.6846079E+03, 1]], [1, 0, [1.1374703E+03, 1]], [1, 0, [5.1621020E+02, 1]], [1, 0, [2.4693983E+02, 1]], [1, 0, [1.2274916E+02, 1]], [1, 0, [6.2799497E+01, 1]], [1, 0, [3.2487371E+01, 1]], [1, 0, [1.6723605E+01, 1]], [1, 0, [8.7679297E+00, 1]], [1, 0, [4.4589051E+00, 1]], [1, 0, [2.2338061E+00, 1]], [1, 0, [1.0911480E+00, 1]], [1, 0, [4.3929315E-01, 1]], [1, 0, [1.8360774E-01, 1]], [1, 0, [7.2403358E-02, 1]], [2, 0, [8.6279708E+03, 1]], [2, 0, [2.2813047E+03, 1]], [2, 0, [8.2732533E+02, 1]], [2, 0, [3.5190121E+02, 1]], [2, 0, [1.6496856E+02, 1]], [2, 0, [8.2183367E+01, 1]], [2, 0, [4.2729088E+01, 1]], [2, 0, [2.2703366E+01, 1]], [2, 0, [1.2260601E+01, 1]], [2, 0, [6.6400786E+00, 1]], [2, 0, [3.5392069E+00, 1]], [2, 0, [1.8418472E+00, 1]], [2, 0, [9.3488753E-01, 1]], [2, 0, [4.4933710E-01, 1]], [2, 0, [1.8644465E-01, 1]],] Rn = [[0, 0, [5.8479849E+07, 1]], [0, 0, [1.5566145E+07, 1]], [0, 0, [5.3278717E+06, 1]], [0, 0, [2.0283228E+06, 1]], [0, 0, [8.4629773E+05, 1]], [0, 0, [3.7383319E+05, 1]], [0, 0, [1.7339590E+05, 1]], [0, 0, [8.3220642E+04, 1]], [0, 0, [4.1089364E+04, 1]], [0, 0, [2.0733535E+04, 1]], [0, 0, [1.0660059E+04, 1]], [0, 0, [5.5696713E+03, 1]], [0, 0, [2.9528148E+03, 1]], [0, 0, [1.5862087E+03, 1]], [0, 0, [8.6173506E+02, 1]], [0, 0, [4.7095278E+02, 1]], [0, 0, [2.6264365E+02, 1]], [0, 0, [1.4820953E+02, 1]], [0, 0, [8.4401933E+01, 1]], [0, 0, [4.9057850E+01, 1]], [0, 0, [2.8582642E+01, 1]], [0, 0, [1.6459289E+01, 1]], [0, 0, [9.4369669E+00, 1]], [0, 0, [5.4204351E+00, 1]], [0, 0, [3.0780686E+00, 1]], [0, 0, [1.6814451E+00, 1]], [0, 0, [9.0063187E-01, 1]], [0, 0, [4.3544867E-01, 1]], [0, 0, [2.0614433E-01, 1]], [0, 0, [9.2763678E-02, 1]], [1, 0, [4.7770857E+07, 1]], [1, 0, [1.3066778E+07, 1]], [1, 0, [3.9456280E+06, 1]], [1, 0, [1.2913178E+06, 1]], [1, 0, [4.5032579E+05, 1]], [1, 0, [1.6574375E+05, 1]], [1, 0, [6.4036428E+04, 1]], [1, 0, [2.5920573E+04, 1]], [1, 0, [1.0996543E+04, 1]], [1, 0, [4.8918949E+03, 1]], [1, 0, [2.2787363E+03, 1]], [1, 0, [1.1071445E+03, 1]], [1, 0, [5.5749184E+02, 1]], [1, 0, [2.8926378E+02, 1]], [1, 0, [1.5333618E+02, 1]], [1, 0, [8.2060943E+01, 1]], [1, 0, [4.4995535E+01, 1]], [1, 0, [2.4656254E+01, 1]], [1, 0, [1.3176946E+01, 1]], [1, 0, [7.1060325E+00, 1]], [1, 0, [3.6773071E+00, 1]], [1, 0, [1.8984331E+00, 1]], [1, 0, [9.4665972E-01, 1]], [1, 0, [4.1173274E-01, 1]], [1, 0, [1.7431844E-01, 1]], [1, 0, [6.9513636E-02, 1]], [2, 0, [4.6750752E+04, 1]], [2, 0, [1.1284131E+04, 1]], [2, 0, [3.7764933E+03, 1]], [2, 0, [1.5103825E+03, 1]], [2, 0, [6.7737925E+02, 1]], [2, 0, [3.2759566E+02, 1]], [2, 0, [1.6720408E+02, 1]], [2, 0, [8.8294843E+01, 1]], [2, 0, [4.7840134E+01, 1]], [2, 0, [2.6086684E+01, 1]], [2, 0, [1.4043765E+01, 1]], [2, 0, [7.5496008E+00, 1]], [2, 0, [3.9825780E+00, 1]], [2, 0, [2.0379623E+00, 1]], [2, 0, [1.0104144E+00, 1]], [2, 0, [4.7300150E-01, 1]], [2, 0, [1.9507807E-01, 1]], [3, 0, [1.2648343E+03, 1]], [3, 0, [4.2782369E+02, 1]], [3, 0, [1.8169289E+02, 1]], [3, 0, [8.6452888E+01, 1]], [3, 0, [4.3573202E+01, 1]], [3, 0, [2.2710364E+01, 1]], [3, 0, [1.1860330E+01, 1]], [3, 0, [6.0877675E+00, 1]], [3, 0, [2.9409064E+00, 1]], [3, 0, [1.1766074E+00, 1]], [3, 0, [4.3100852E-01, 1]],] U = [ [0, [5.6688627E+07, 1.]], [0, [1.5089297E+07, 1.]], [0, [5.1604752E+06, 1.]], [0, [1.9616143E+06, 1.]], [0, [8.1795253E+05, 1.]], [0, [3.6155803E+05, 1.]], [0, [1.6827256E+05, 1.]], [0, [8.1257576E+04, 1.]], [0, [4.0487578E+04, 1.]], [0, [2.0659489E+04, 1.]], [0, [1.0754051E+04, 1.]], [0, [5.6898498E+03, 1.]], [0, [3.0547388E+03, 1.]], [0, [1.6617106E+03, 1.]], [0, [9.1440113E+02, 1.]], [0, [5.0567265E+02, 1.]], [0, [2.8540399E+02, 1.]], [0, [1.6292889E+02, 1.]], [0, [9.3609383E+01, 1.]], [0, [5.5811596E+01, 1.]], [0, [3.2957255E+01, 1.]], [0, [1.9148698E+01, 1.]], [0, [1.1424216E+01, 1.]], [0, [6.7462725E+00, 1.]], [0, [4.0365190E+00, 1.]], [0, [2.3217313E+00, 1.]], [0, [1.3052333E+00, 1.]], [0, [7.3409234E-01, 1.]], [0, [3.9965415E-01, 1.]], [0, [2.1380868E-01, 1.]], [0, [8.6940003E-02, 1.]], [0, [4.1541136E-02, 1.]], [0, [1.9770412E-02, 1.]], [1, [5.2699704E+07, 1.]], [1, [1.5503102E+07, 1.]], [1, [4.9225272E+06, 1.]], [1, [1.6757629E+06, 1.]], [1, [6.0281298E+05, 1.]], [1, [2.2728619E+05, 1.]], [1, [8.9383515E+04, 1.]], [1, [3.6589535E+04, 1.]], [1, [1.5594049E+04, 1.]], [1, [6.9284886E+03, 1.]], [1, [3.2106020E+03, 1.]], [1, [1.5490141E+03, 1.]], [1, [7.7455359E+02, 1.]], [1, [3.9927892E+02, 1.]], [1, [2.1150500E+02, 1.]], [1, [1.1442300E+02, 1.]], [1, [6.3349266E+01, 1.]], [1, [3.5426175E+01, 1.]], [1, [1.9564577E+01, 1.]], [1, [1.0924289E+01, 1.]], [1, [6.0461422E+00, 1.]], [1, [3.2986304E+00, 1.]], [1, [1.7645466E+00, 1.]], [1, [8.8905399E-01, 1.]], [1, [4.4182761E-01, 1.]], [1, [2.1288694E-01, 1.]], [1, [8.3030571E-02, 1.]], [1, [3.6616079E-02, 1.]], [1, [1.5628926E-02, 1.]], [2, [1.1030949E+05, 1.]], [2, [2.5979209E+04, 1.]], [2, [8.4185541E+03, 1.]], [2, [3.2641000E+03, 1.]], [2, [1.4279053E+03, 1.]], [2, [6.7981618E+02, 1.]], [2, [3.4352647E+02, 1.]], [2, [1.8152057E+02, 1.]], [2, [9.8735517E+01, 1.]], [2, [5.4973074E+01, 1.]], [2, [3.0782635E+01, 1.]], [2, [1.7041311E+01, 1.]], [2, [9.4787015E+00, 1.]], [2, [5.2090831E+00, 1.]], [2, [2.7893130E+00, 1.]], [2, [1.4539969E+00, 1.]], [2, [7.1899480E-01, 1.]], [2, [3.0121159E-01, 1.]], [2, [1.1921203E-01, 1.]], [2, [4.3915110E-02, 1.]], [3, [1.1523569E+03, 1.]], [3, [3.8849177E+02, 1.]], [3, [1.6470953E+02, 1.]], [3, [7.7567896E+01, 1.]], [3, [3.8758229E+01, 1.]], [3, [1.9814017E+01, 1.]], [3, [1.0164770E+01, 1.]], [3, [5.1039559E+00, 1.]], [3, [2.3910278E+00, 1.]], [3, [1.0651646E+00, 1.]], [3, [4.3998357E-01, 1.]], [3, [1.5808424E-01, 1.]], ] # flake8: noqa
{'dir': 'python', 'id': '11091731', 'max_stars_count': '501', 'max_stars_repo_name': 'QuESt-Calculator/pyscf', 'max_stars_repo_path': 'pyscf/gto/basis/dyall_tz.py', 'n_tokens_mistral': 9999, 'n_tokens_neox': 7410, 'n_words': 1494}
import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { BmProcessComponent } from './bm-process/bm-process.component'; import { BmProcessDiagramComponent } from './bm-process-diagram/bm-process-diagram.component'; import { BmProcessesComponent } from './bm-processes/bm-processes.component'; import { DevelopmentMethodComponent } from './development-method/development-method.component'; import { DevelopmentMethodsComponent } from './development-methods/development-methods.component'; import { DevelopmentProcessesRoutingModule } from './development-processes-routing.module'; import { ProcessPatternComponent } from './process-pattern/process-pattern.component'; import { ProcessPatternDiagramComponent } from './process-pattern-diagram/process-pattern-diagram.component'; import { ProcessPatternTypesFormComponent } from './process-pattern-types-form/process-pattern-types-form.component'; import { ProcessPatternsComponent } from './process-patterns/process-patterns.component'; import { ConfirmLeaveModalComponent } from './confirm-leave-modal/confirm-leave-modal.component'; import { SituationalFactorsComponent } from './situational-factors/situational-factors.component'; import { SituationalFactorComponent } from './situational-factor/situational-factor.component'; import { MethodElementListComponent } from './method-element-list/method-element-list.component'; import { MethodElementFormComponent } from './method-element-form/method-element-form.component'; import { ArtifactsComponent } from './artifacts/artifacts.component'; import { ArtifactComponent } from './artifact/artifact.component'; import { StakeholdersComponent } from './stakeholders/stakeholders.component'; import { StakeholderComponent } from './stakeholder/stakeholder.component'; import { ToolComponent } from './tool/tool.component'; import { ToolsComponent } from './tools/tools.component'; import { TypesComponent } from './types/types.component'; import { TypeComponent } from './type/type.component'; import { MethodElementSelectionFormComponent } from './method-element-selection-form/method-element-selection-form.component'; import { MethodElementsSelectionFormComponent } from './method-elements-selection-form/method-elements-selection-form.component'; import { TypesSelectionFormComponent } from './types-selection-form/types-selection-form.component'; import { SituationalFactorsSelectionFormComponent } from './situational-factors-selection-form/situational-factors-selection-form.component'; import { SituationalFactorSelectionFormComponent } from './situational-factor-selection-form/situational-factor-selection-form.component'; import { ArtifactsSelectionFormComponent } from './artifacts-selection-form/artifacts-selection-form.component'; import { StakeholdersSelectionFormComponent } from './stakeholders-selection-form/stakeholders-selection-form.component'; import { ToolsSelectionFormComponent } from './tools-selection-form/tools-selection-form.component'; import { ExamplesFormComponent } from './examples-form/examples-form.component'; import { MethodInfoComponent } from './method-info/method-info.component'; import { MethodElementGroupInfoComponent } from './method-element-group-info/method-element-group-info.component'; import { MethodElementInfoComponent } from './method-element-info/method-element-info.component'; import { ArtifactsGroupInfoComponent } from './artifacts-group-info/artifacts-group-info.component'; import { StakeholdersGroupInfoComponent } from './stakeholders-group-info/stakeholders-group-info.component'; import { SituationalFactorsOverviewComponent } from './situational-factors-overview/situational-factors-overview.component'; import { PatternInfoComponent } from './pattern-info/pattern-info.component'; import { DevelopmentMethodSelectionFormComponent } from './development-method-selection-form/development-method-selection-form.component'; import { DevelopmentMethodsSelectionFormComponent } from './development-methods-selection-form/development-methods-selection-form.component'; import { ProcessPatternSelectionFormComponent } from './process-pattern-selection-form/process-pattern-selection-form.component'; import { ProcessPatternsSelectionFormComponent } from './process-patterns-selection-form/process-patterns-selection-form.component'; import { DevelopmentMethodSummaryComponent } from './development-method-summary/development-method-summary.component'; import { ToolsGroupInfoComponent } from './tools-group-info/tools-group-info.component'; import { RunningProcessComponent } from './running-process/running-process.component'; import { RunningProcessesComponent } from './running-processes/running-processes.component'; import { RunningProcessSelectOutputArtifactsComponent } from './running-process-select-output-artifacts/running-process-select-output-artifacts.component'; import { RunningProcessSelectInputArtifactsComponent } from './running-process-select-input-artifacts/running-process-select-input-artifacts.component'; import { DevelopmentMethodSelectExecutionStepsComponent } from './development-method-select-execution-steps/development-method-select-execution-steps.component'; import { DevelopmentMethodSelectExecutionStepComponent } from './development-method-select-execution-step/development-method-select-execution-step.component'; import { DevelopmentMethodArtifactMappingComponent } from './development-method-artifact-mapping/development-method-artifact-mapping.component'; import { DevelopmentMethodArtifactMappingsComponent } from './development-method-artifact-mappings/development-method-artifact-mappings.component'; import { RunningProcessMethodComponent } from './running-process-method/running-process-method.component'; import { ConfigurationFormPlaceholderDirective } from './configuration-form-placeholder.directive'; import { MethodInfoStepComponent } from './method-info-step/method-info-step.component'; import { MethodInfoStepsComponent } from './method-info-steps/method-info-steps.component'; import { DomainComponent } from './domain/domain.component'; import { DomainsComponent } from './domains/domains.component'; import { SituationalFactorFormComponent } from './situational-factor-form/situational-factor-form.component'; import { ArtifactDefinitionFormComponent } from './artifact-definition-form/artifact-definition-form.component'; import { MethodElementsComponent } from './method-elements/method-elements.component'; import { ConcreteArtifactsComponent } from './concrete-artifacts/concrete-artifacts.component'; import { ConcreteArtifactComponent } from './concrete-artifact/concrete-artifact.component'; import { RunningProcessArtifactExportFormComponent } from './running-process-artifact-export-form/running-process-artifact-export-form.component'; import { ConcreteArtifactFormComponent } from './concrete-artifact-form/concrete-artifact-form.component'; import { RunningProcessArtifactImportFormComponent } from './running-process-artifact-import-form/running-process-artifact-import-form.component'; import { RunningProcessArtifactRenameFormComponent } from './running-process-artifact-rename-form/running-process-artifact-rename-form.component'; import { MultiplePipe } from './pipes/multiple.pipe'; import { ListPipe } from './pipes/list.pipe'; import { QuillModule } from 'ngx-quill'; import { RunningProcessSelectOutputArtifactComponent } from './running-process-select-output-artifact/running-process-select-output-artifact.component'; import { DevelopmentMethodIncompleteModalComponent } from './development-method-incomplete-modal/development-method-incomplete-modal.component'; @NgModule({ declarations: [ BmProcessComponent, BmProcessDiagramComponent, BmProcessesComponent, DevelopmentMethodComponent, DevelopmentMethodsComponent, ProcessPatternComponent, ProcessPatternDiagramComponent, ProcessPatternTypesFormComponent, ProcessPatternsComponent, ConfirmLeaveModalComponent, SituationalFactorsComponent, SituationalFactorComponent, MethodElementListComponent, MethodElementFormComponent, ArtifactsComponent, ArtifactComponent, StakeholdersComponent, StakeholderComponent, ToolComponent, ToolsComponent, TypesComponent, TypeComponent, MethodElementSelectionFormComponent, MethodElementsSelectionFormComponent, TypesSelectionFormComponent, SituationalFactorsSelectionFormComponent, SituationalFactorSelectionFormComponent, ArtifactsSelectionFormComponent, StakeholdersSelectionFormComponent, ToolsSelectionFormComponent, ExamplesFormComponent, MethodInfoComponent, MethodElementGroupInfoComponent, MethodElementInfoComponent, ArtifactsGroupInfoComponent, StakeholdersGroupInfoComponent, SituationalFactorsOverviewComponent, PatternInfoComponent, DevelopmentMethodSelectionFormComponent, DevelopmentMethodsSelectionFormComponent, ProcessPatternSelectionFormComponent, ProcessPatternsSelectionFormComponent, DevelopmentMethodSummaryComponent, ToolsGroupInfoComponent, RunningProcessComponent, RunningProcessesComponent, RunningProcessSelectOutputArtifactsComponent, RunningProcessSelectInputArtifactsComponent, DevelopmentMethodSelectExecutionStepsComponent, DevelopmentMethodSelectExecutionStepComponent, DevelopmentMethodArtifactMappingComponent, DevelopmentMethodArtifactMappingsComponent, RunningProcessMethodComponent, ConfigurationFormPlaceholderDirective, MethodInfoStepComponent, MethodInfoStepsComponent, DomainComponent, DomainsComponent, SituationalFactorFormComponent, ArtifactDefinitionFormComponent, MethodElementsComponent, ConcreteArtifactsComponent, ConcreteArtifactComponent, RunningProcessArtifactExportFormComponent, ConcreteArtifactFormComponent, RunningProcessArtifactImportFormComponent, RunningProcessArtifactRenameFormComponent, MultiplePipe, ListPipe, RunningProcessSelectOutputArtifactComponent, DevelopmentMethodIncompleteModalComponent, ], imports: [DevelopmentProcessesRoutingModule, SharedModule, QuillModule], }) export class DevelopmentProcessesModule {}
{'dir': 'typescript', 'id': '8452192', 'max_stars_count': '0', 'max_stars_repo_name': 'SebastianGTTS/situational-business-modeler-developer', 'max_stars_repo_path': 'src/app/development-processes/development-processes.module.ts', 'n_tokens_mistral': 2492, 'n_tokens_neox': 2441, 'n_words': 380}
<reponame>thunlp/THUTag<filename>basepackage/smt/src/test/org/thunlp/html/EncodingDetectorTest.java<gh_stars>100-1000 package org.thunlp.html; import java.io.FileInputStream; import java.io.IOException; import junit.framework.Assert; import junit.framework.TestCase; public class EncodingDetectorTest extends TestCase { public void testBasic() throws IOException { FileInputStream is = new FileInputStream("src/test/org/thunlp/html/sample-page.html"); byte[] page = new byte[40 * 1024]; is.read(page); is.close(); String charset = EncodingDetector.detect(page); Assert.assertEquals("gb2312", charset); } }
{'dir': 'java', 'id': '16036008', 'max_stars_count': '311', 'max_stars_repo_name': 'thunlp/THUTag', 'max_stars_repo_path': 'basepackage/smt/src/test/org/thunlp/html/EncodingDetectorTest.java', 'n_tokens_mistral': 226, 'n_tokens_neox': 204, 'n_words': 37}
/* eslint-disable react-hooks/rules-of-hooks */ import React from 'react'; import { Card, Chip, CardContent, Typography, makeStyles, createStyles } from '@material-ui/core'; import { grey, deepPurple } from '@material-ui/core/colors'; import clsx from 'clsx'; import Count from 'react-countup'; type CardProps = { title: string; value: number | null; footer?: string | JSX.Element; icon?: string | JSX.Element; style?: string; badge?: boolean; }; const useStyles = makeStyles(theme => createStyles({ title: { fontWeight: 'bold' }, card: { padding: '20px 20px', margin: '0 5%', marginTop: '10px', borderRadius: '10px', boxShadow: '0 0px 20px 0.2px rgba(0, 0, 0, 0.2)' }, cardContent: { padding: '0px 0px !important' }, badge: { float: 'right', fontWeight: 'bold', color: theme.palette.type === 'dark' ? deepPurple[400] : deepPurple[300], background: theme.palette.type === 'dark' ? grey[400] : grey[200] }, side_icon: { float: 'right', width: 'fit-content' }, icon: { color: 'red' }, value: { lineHeight: 1.15, fontFamily: 'Quicksand, sans-serif !important', fontWeight: 700 } }) ); const RenderBigCard = (props: CardProps) => { if (!props.title) return null; const classes = useStyles(); const { title, value, footer, icon, style, badge } = props; return ( <Card className={clsx(style, classes.card)}> <span className={classes.side_icon}> {' '} {badge ? <Chip variant="default" size="small" label="TODAY" className={classes.badge}></Chip> : icon} </span> <CardContent className={classes.cardContent}> <Typography color="textSecondary" variant="overline" gutterBottom className={clsx('title', classes.title)}> {title} </Typography> <Typography className="value" color="textPrimary" variant="h3" style={{ fontFamily: 'Quicksand, sans-serif', fontWeight: 700 }} > {value === null ? ( 'N/A' ) : ( <Count start={0} end={value} duration={(value.toString().length * 10 + parseInt(value.toString()[0])) / 12} separator="," className={classes.value} ></Count> )} </Typography> <Typography className="footer" color="textSecondary" variant="caption"> {footer} </Typography> </CardContent> </Card> ); }; export default RenderBigCard;
{'dir': 'typescript', 'id': '1805491', 'max_stars_count': '2', 'max_stars_repo_name': 'realjesset/Covid-Tracker', 'max_stars_repo_path': 'src/components/common/bigCard.tsx', 'n_tokens_mistral': 859, 'n_tokens_neox': 814, 'n_words': 187}
<reponame>r0m4n27/spready<filename>src/test/kotlin/spready/ui/SheetModelTest.kt package spready.ui import javafx.embed.swing.JFXPanel import org.junit.jupiter.api.Nested import spready.lisp.sexpr.Cell import spready.ui.sheet.SheetModel import spready.ui.status.Err import spready.ui.status.Ok import spready.ui.status.StatusEvent import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull class SheetModelTest { // Must initialise a panel // Otherwise can't use the bus private val panel = JFXPanel() private var model = SheetModel() @BeforeTest fun reset() { model = SheetModel() } @Nested inner class Choose { @Test fun `choose normal`() { model.chooseCell(Cell(1, 1)) model.currentInputProperty.value = "123" model.evalInput() model.chooseCell(Cell(2, 1)) assertEquals("", model.currentInputProperty.value) model.chooseCell(Cell(1, 1)) assertEquals("123", model.currentInputProperty.value) } @Test fun `choose not found`() { model.chooseCell(Cell(-1, -1)) assertEquals("", model.currentInputProperty.value) } } @Nested inner class Eval { @Test fun `eval null`() { model.evalInput() assertEquals(emptySet(), model.changedCellsProperty.value) } @Test fun `eval normal`() { model.chooseCell(Cell(1, 1)) model.currentInputProperty.value = "123" model.evalInput() assertEquals(setOf(Cell(1, 1)), model.changedCellsProperty.value) assertEquals("123", model.allResults[Cell(1, 1)]) } @Test fun `eval fire Ok`() { var event: StatusEvent? = null model.subscribe<StatusEvent> { event = it } model.chooseCell(Cell(1, 1)) model.currentInputProperty.value = "123" model.evalInput() // Wait to receive the event Thread.sleep(50) assertNotNull(event) assertEquals(Ok, event?.result) } @Test fun `eval fire Err`() { var event: StatusEvent? = null model.subscribe<StatusEvent> { event = it } model.chooseCell(Cell(1, 1)) model.currentInputProperty.value = "test" model.evalInput() Thread.sleep(50) assertNotNull(event) assertEquals(Err("Can't find variable test"), event?.result) } @Test fun `remove cell`() { model.chooseCell(Cell(1, 1)) model.currentInputProperty.value = "6" model.evalInput() assertEquals(mapOf(Cell(1, 1) to "6"), model.allResults) model.currentInputProperty.value = "" model.evalInput() assertEquals(false, model.allResults.containsKey(Cell(1, 1))) } @Test fun `remove fail`() { var event: StatusEvent? = null model.subscribe<StatusEvent> { event = it } model.chooseCell(Cell(1, 1)) model.currentInputProperty.value = "6" model.evalInput() model.chooseCell(Cell(2, 1)) model.currentInputProperty.value = "#1.1" model.evalInput() assertEquals(mapOf(Cell(1, 1) to "6", Cell(2, 1) to "6"), model.allResults) model.chooseCell(Cell(1, 1)) model.currentInputProperty.value = "" model.evalInput() Thread.sleep(50) assertNotNull(event) assertEquals(Err("#1.1 influences others!"), event?.result) } } }
{'dir': 'kotlin', 'id': '921998', 'max_stars_count': '0', 'max_stars_repo_name': 'r0m4n27/spready', 'max_stars_repo_path': 'src/test/kotlin/spready/ui/SheetModelTest.kt', 'n_tokens_mistral': 1146, 'n_tokens_neox': 1061, 'n_words': 214}
/* Copyright <2017> <<NAME>> 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. */ using System; using System.Linq; using System.Numerics; using Core.Data; namespace Core.Filtering.Core { public class FilterCore { /// <summary> /// Indicates a crossover section type, HP/BP/LP. /// </summary> public enum Section { HP, BP, LP }; public static double WrapPhaseDegrees(double phase) { if ((phase >= -180.0) && (phase <= 180.0)) { return phase; } while (!(phase >= -180.0) && (phase <= 180.0)) { if ((phase >= 180.0)) { phase -= 2 * 180.0; } // Greater than 180, subtract 360 if ((phase < -180.0)) { phase += 2 * 180.0; } // Less than -180, add 360 } return phase; } // TODO: Determine the algorithm needed public static double UnWrapPhaseDegrees(double phase) { if ((phase >= -180.0) && (phase <= 180.0)) { return phase; } while (!(phase >= -180.0) && (phase <= 180.0)) { if (!(phase < 180.0)) { phase -= 2 * 180.0; } // Greater than 180, subtract 360 if ((phase < -180.0)) { phase += 2 * 180.0; } // Less than -180, add 360 } return phase; } private double ConvertDBToAbsolute(double db) { double absolutePressure; double refPressure = 1E-12; // w/m^2 //if (db == 0) { return 0; }; absolutePressure = refPressure * Math.Pow(10, db / 20); // ref * 10^(db/10) return absolutePressure; } private double ConvertAbsoluteToDB(double abs) { double mydb; double refPressure = 1E-12; // w/m^2 mydb = 20 * Math.Log10(abs / refPressure); // 10log(abs/ref); return mydb; } public static double InvertPhase(double phase) { while ((phase < -Math.PI) || (phase >= Math.PI)) { phase = RotatePhase(phase); } if ( (phase < 0) ) { phase += Math.PI; } else { phase -= Math.PI; } return phase; } public static double RotatePhase(double phase) { if ((phase >= -Math.PI) && (phase <= Math.PI)) { return phase; } while ((phase < -Math.PI) || (phase >= Math.PI)) { if ((phase >= Math.PI)) { phase -= 2.0 * Math.PI; } // Greater than 180, subtract 360 if ((phase < -Math.PI)) { phase += 2.0 * Math.PI; } // Less than -180, add 360 } return phase; } public double[,] SumResponses(double[,] filter1, double[,] filter2) { int count = FrequencyRange.dynamicFreqs.Count(); double absMag1, absMag2, mag, phase; Complex complexAbs1, complexAbs2, complexSumDB; double[] systemSPL = new double[count]; Complex[] complexSum = new Complex[count]; double[,] doubleSum = new double[count, 3]; double wrappedPhase = 0; for (int i = 0; i < count; i++) { // Convert db to absolute, create complex using absolute, sum the drivers if (double.IsNegativeInfinity(filter1[i, 1])) { complexAbs1 = Complex.Zero; } else { absMag1 = ConvertDBToAbsolute(filter1[i, 1]); wrappedPhase = filter1[i, 2] * (Math.PI / 180.0); complexAbs1 = Complex.FromPolarCoordinates(absMag1, wrappedPhase); } if (double.IsNegativeInfinity(filter2[i, 1])) { complexAbs2 = Complex.Zero; } else { absMag2 = ConvertDBToAbsolute(filter2[i, 1]); wrappedPhase = filter2[i, 2] * (Math.PI / 180.0); complexAbs2 = Complex.FromPolarCoordinates(absMag2, wrappedPhase); } complexSumDB = complexAbs1 + complexAbs2; // if (complexSumDB.Magnitude <= 0.0) { continue; } // Skip this one. mag = ConvertAbsoluteToDB(complexSumDB.Magnitude); phase = complexSumDB.Phase; //complexSum[i] = Complex.FromPolarCoordinates(mag, phase); doubleSum[i, 0] = FrequencyRange.dynamicFreqs[i]; doubleSum[i, 1] = mag; doubleSum[i, 2] = phase * (180.0 / Math.PI); } return doubleSum; } } }
{'dir': 'c-sharp', 'id': '9694028', 'max_stars_count': '1', 'max_stars_repo_name': 'davidralph77/WinFilters', 'max_stars_repo_path': 'Core/Filters/FilterCore.cs', 'n_tokens_mistral': 1716, 'n_tokens_neox': 1496, 'n_words': 499}
<gh_stars>100-1000 package ru.vyarus.dropwizard.guice.module.context.bootstrap; import io.dropwizard.Configuration; import io.dropwizard.ConfiguredBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import ru.vyarus.dropwizard.guice.module.context.ConfigurationContext; import ru.vyarus.dropwizard.guice.module.context.info.ItemId; /** * Bundle decorator. Used to track transitive dropwizard bundles registration. * <p> * Bundles tracking is controlled with {@link ru.vyarus.dropwizard.guice.GuiceyOptions#TrackDropwizardBundles} * option. * * @author <NAME> * @since 07.05.2019 * @param <T> configuration type */ public class DropwizardBundleTracker<T extends Configuration> implements ConfiguredBundle<T> { private final ConfiguredBundle<? super T> bundle; private final ConfigurationContext context; public DropwizardBundleTracker(final ConfiguredBundle<? super T> bundle, final ConfigurationContext context) { this.bundle = bundle; this.context = context; } @Override public void initialize(final Bootstrap bootstrap) { final ItemId currentScope = context.replaceContextScope(ItemId.from(bundle)); // initialize with proxy bootstrap object to intercept transitive bundles registration bundle.initialize(context.getBootstrapProxy()); context.replaceContextScope(currentScope); } @Override public void run(final T configuration, final Environment environment) throws Exception { bundle.run(configuration, environment); } }
{'dir': 'java', 'id': '11345618', 'max_stars_count': '219', 'max_stars_repo_name': 'jesims/dropwizard-guicey', 'max_stars_repo_path': 'src/main/java/ru/vyarus/dropwizard/guice/module/context/bootstrap/DropwizardBundleTracker.java', 'n_tokens_mistral': 441, 'n_tokens_neox': 413, 'n_words': 106}
package main import ( "testing" "github.com/stretchr/testify/assert" "github.com/zhaoyuankui/goutil/alg" ) func Test_findMedianSortedArrays(t *testing.T) { assert.Equal(t, 1.0, findMedianSortedArrays(alg.IntSlice(1), alg.IntSlice())) assert.Equal(t, 1.5, findMedianSortedArrays(alg.IntSlice(), alg.IntSlice(1, 2))) assert.Equal(t, 1.0, findMedianSortedArrays(alg.IntSlice(1), alg.IntSlice(1))) assert.Equal(t, 1.5, findMedianSortedArrays(alg.IntSlice(1), alg.IntSlice(2))) assert.Equal(t, 1.5, findMedianSortedArrays(alg.IntSlice(2), alg.IntSlice(1))) assert.Equal(t, 2.0, findMedianSortedArrays(alg.IntSlice(2, 3), alg.IntSlice(1))) assert.Equal(t, 2.0, findMedianSortedArrays(alg.IntSlice(1, 3), alg.IntSlice(2))) assert.Equal(t, 3.5, findMedianSortedArrays(alg.IntSlice(1, 3, 5), alg.IntSlice(2, 4, 6))) assert.Equal(t, 2.0, findMedianSortedArrays(alg.IntSlice(2), alg.IntSlice(1, 3))) assert.Equal(t, 2.5, findMedianSortedArrays(alg.IntSlice(1, 2), alg.IntSlice(3, 4))) assert.Equal(t, 6.5, findMedianSortedArrays(alg.IntSlice(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), alg.IntSlice(8))) } func Benchmark_findMedianSortedArrays(b *testing.B) { // Initializations here. b.ResetTimer() for i := 0; i < b.N; i++ { findMedianSortedArrays(alg.IntSlice(1, 2, 3, 4, 5), alg.IntSlice(3, 4, 5, 6, 7)) } } func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { l1, l2 := len(nums1), len(nums2) if l1 == 0 || l2 == 0 { nums := nums1 if l1 == 0 { nums = nums2 } l := l1 + l2 if l&1 > 0 { return float64(nums[l>>1]) } else { return float64(nums[l>>1]+nums[l>>1-1]) / 2 } } // Find the target in the longer sequence. if l2 > l1 { l1, l2 = l2, l1 nums1, nums2 = nums2, nums1 } half := (l1 + l2) >> 1 p, q, i, j := 0, l1, l1>>1, 0 //for i >= 0 && i <= l1 { for { j = half - i // Avoid exceed boundaries if j < 0 { q = i - 1 i = (p + q) >> 1 continue } if j > l2 { p = i + 1 i = (p + q) >> 1 continue } // Find the target. // The direction of i to move towards. false: left, true:right var d bool if i == 0 { if nums1[0] >= nums2[j-1] { break } else { d = true } } else if i == l1 { if nums1[l1-1] <= nums2[j] { break } else { d = false } } else if j == 0 { if nums2[0] >= nums1[i-1] { break } else { d = false } } else if j == l2 { if nums2[l2-1] <= nums1[i] { break } else { d = true } } else { if nums1[i] >= nums2[j-1] && nums1[i-1] <= nums2[j] { break } else if nums1[i] < nums2[j-1] { d = true } else { d = false } } if d { p = i + 1 i = (p + q) >> 1 } else { q = i - 1 i = (p + q) >> 1 } } // Construct result. if (l1+l2)&1 > 0 { if i == l1 { return float64(nums2[j]) } if j == l2 { return float64(nums1[i]) } if nums1[i] < nums2[j] { return float64(nums1[i]) } return float64(nums2[j]) } var mid1, mid2 int if i == 0 { mid1 = nums2[j-1] } else if j == 0 { mid1 = nums1[i-1] } else if nums1[i-1] > nums2[j-1] { mid1 = nums1[i-1] } else { mid1 = nums2[j-1] } if i == l1 { mid2 = nums2[j] } else if j == l2 { mid2 = nums1[i] } else if nums1[i] > nums2[j] { mid2 = nums2[j] } else { mid2 = nums1[i] } return float64(mid1+mid2) / 2 }
{'dir': 'go', 'id': '3440380', 'max_stars_count': '0', 'max_stars_repo_name': 'zhaoyuankui/acm', 'max_stars_repo_path': 'find_median_sorted_arrays/find_median_sorted_arrays_test.go', 'n_tokens_mistral': 1784, 'n_tokens_neox': 1581, 'n_words': 354}
<?php namespace Networq\Model; use RuntimeException; class Fqnn { protected $owner; protected $package; protected $name; private function __construct() { } public static function byFqnn(string $fqnn) { $part = explode(':', $fqnn); if (count($part)!=3) { throw new RuntimeException("Invalid FQNN: " . $fqnn); } $fqnn = new Fqnn(); $fqnn->owner = $part[0]; $fqnn->package = $part[1]; $fqnn->name = $part[2]; return $fqnn; } public function getOwner() { return $this->owner; } public function getPackage() { return $this->package; } public function getName() { return $this->name; } public function getFqpn() { return $this->owner . ':' . $this->package; } }
{'dir': 'php', 'id': '5042730', 'max_stars_count': '5', 'max_stars_repo_name': 'networq/networq-php', 'max_stars_repo_path': 'src/Model/Fqnn.php', 'n_tokens_mistral': 289, 'n_tokens_neox': 284, 'n_words': 63}
<filename>test/AccuracyTests/AccTestsRegion1.cpp #ifdef _DEBUG #ifndef ACC_TEST_BASE_H #define ACC_TEST_BASE_H #include "AccTestBase.h" #endif class AccTestsRegion1 : public AccTestBase { }; extern "C" { //REGION 1: //properties as a function of temperature and pressure DLL_IMPORT double v_P_T_R1(double,double); DLL_IMPORT double u_P_T_R1(double,double); DLL_IMPORT double s_P_T_R1(double,double); DLL_IMPORT double h_P_T_R1(double,double); DLL_IMPORT double cp_P_T_R1(double,double); DLL_IMPORT double cv_P_T_R1(double,double); DLL_IMPORT double w_P_T_R1(double,double); //properties as a function of pressure and enthalpy DLL_IMPORT double v_P_h_R1(double,double); DLL_IMPORT double u_P_h_R1(double,double); DLL_IMPORT double s_P_h_R1(double,double); DLL_IMPORT double T_P_h_R1(double,double); DLL_IMPORT double cp_P_h_R1(double,double); DLL_IMPORT double cv_P_h_R1(double,double); DLL_IMPORT double w_P_h_R1(double,double); //properties as a function of pressure and entropy DLL_IMPORT double v_P_s_R1(double,double); DLL_IMPORT double u_P_s_R1(double,double); DLL_IMPORT double h_P_s_R1(double,double); DLL_IMPORT double T_P_s_R1(double,double); DLL_IMPORT double cp_P_s_R1(double,double); DLL_IMPORT double cv_P_s_R1(double,double); DLL_IMPORT double w_P_s_R1(double,double); //properties as a function of enthalpy and entropy DLL_IMPORT double v_h_s_R1(double,double); DLL_IMPORT double u_h_s_R1(double,double); DLL_IMPORT double P_h_s_R1(double,double); DLL_IMPORT double T_h_s_R1(double,double); DLL_IMPORT double cp_h_s_R1(double,double); DLL_IMPORT double cv_h_s_R1(double,double); DLL_IMPORT double w_h_s_R1(double,double); } //The temperature and pressure data points for Region1 were //suggested by the IAPWS in "Revised Release on IAPWS //Inductrial Formulation 1997 for the Thermodynamic //Properties of Water and Steam" in Table 5 on page 9. TEST_F(AccTestsRegion1, v_P_T_3MPa_300K) { const double testTemp = 300; const double testPressure = 3; const double vExp = 0.100215168E-02; double v = v_P_T_R1(testPressure,testTemp); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_P_T_3MPa_300K) { const double testTemp = 300; const double testPressure = 3; const double uExp = 0.112324818E+03; double u = u_P_T_R1(testPressure,testTemp); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, s_P_T_3MPa_300K) { const double testTemp = 300; const double testPressure = 3; const double sExp = 0.392294792; double s = s_P_T_R1(testPressure,testTemp); double sErr = AbsRelativeErr(s, sExp); bool sPass = IsAcceptable(sErr); ASSERT_TRUE(sPass); } TEST_F(AccTestsRegion1, h_P_T_3MPa_300K) { const double testTemp = 300; const double testPressure = 3; const double hExp = 0.115331273E+03; double h = h_P_T_R1(testPressure,testTemp); double hErr = AbsRelativeErr(h, hExp); bool hPass = IsAcceptable(hErr); ASSERT_TRUE(hPass); } TEST_F(AccTestsRegion1, cp_P_T_3MPa_300K) { const double testTemp = 300; const double testPressure = 3; const double cpExp = 0.417301218E+01; double cp = cp_P_T_R1(testPressure,testTemp); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_P_T_3MPa_300K) { const double testTemp = 300; const double testPressure = 3; const double cvExp = 4.121201603587; double cv = cv_P_T_R1(testPressure,testTemp); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_P_T_3MPa_300K) { const double testTemp = 300; const double testPressure = 3; const double wExp = 0.150773921E+04; double w = w_P_T_R1(testPressure,testTemp); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_P_T_80MPa_300K) { const double testTemp = 300; const double testPressure = 80; const double vExp = 0.971180894E-03; double v = v_P_T_R1(testPressure,testTemp); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_P_T_80MPa_300K) { const double testTemp = 300; const double testPressure = 80; const double uExp = 0.106448356E+03; double u = u_P_T_R1(testPressure,testTemp); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, s_P_T_80MPa_300K) { const double testTemp = 300; const double testPressure = 80; const double sExp = 0.368563852; double s = s_P_T_R1(testPressure,testTemp); double sErr = AbsRelativeErr(s, sExp); bool sPass = IsAcceptable(sErr); ASSERT_TRUE(sPass); } TEST_F(AccTestsRegion1, h_P_T_80MPa_300K) { const double testTemp = 300; const double testPressure = 80; const double hExp = 0.184142828E+03; double h = h_P_T_R1(testPressure,testTemp); double hErr = AbsRelativeErr(h, hExp); bool hPass = IsAcceptable(hErr); ASSERT_TRUE(hPass); } TEST_F(AccTestsRegion1, cp_P_T_80MPa_300K) { const double testTemp = 300; const double testPressure = 80; const double cpExp = 0.401008987E+01; double cp = cp_P_T_R1(testPressure,testTemp); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_P_T_80MPa_300K) { const double testTemp = 300; const double testPressure = 80; const double cvExp = 3.917366061845; double cv = cv_P_T_R1(testPressure,testTemp); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_P_T_80MPa_300K) { const double testTemp = 300; const double testPressure = 80; const double wExp = 0.163469054E+04; double w = w_P_T_R1(testPressure,testTemp); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_P_T_3MPa_500K) { const double testTemp = 500; const double testPressure = 3; const double vExp = 0.120241800E-02; double v = v_P_T_R1(testPressure,testTemp); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_P_T_3MPa_500K) { const double testTemp = 500; const double testPressure = 3; const double uExp = 0.971934985E+03; double u = u_P_T_R1(testPressure,testTemp); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, s_P_T_3MPa_500K) { const double testTemp = 500; const double testPressure = 3; const double sExp = 0.258041912E+01; double s = s_P_T_R1(testPressure,testTemp); double sErr = AbsRelativeErr(s, sExp); bool sPass = IsAcceptable(sErr); ASSERT_TRUE(sPass); } TEST_F(AccTestsRegion1, h_P_T_3MPa_500K) { const double testTemp = 500; const double testPressure = 3; const double hExp = 0.975542239E+03; double h = h_P_T_R1(testPressure,testTemp); double hErr = AbsRelativeErr(h, hExp); bool hPass = IsAcceptable(hErr); ASSERT_TRUE(hPass); } TEST_F(AccTestsRegion1, cp_P_T_3MPa_500K) { const double testTemp = 500; const double testPressure = 3; const double cpExp = 0.465580682E+01; double cp = cp_P_T_R1(testPressure,testTemp); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_P_T_3MPa_500K) { const double testTemp = 500; const double testPressure = 3; const double cvExp = 3.221392229028; double cv = cv_P_T_R1(testPressure,testTemp); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_P_T_3MPa_500K) { const double testTemp = 500; const double testPressure = 3; const double wExp = 0.124071337E+04; double w = w_P_T_R1(testPressure,testTemp); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_P_h_3MPa_0d115331273Ep03h) { const double testPress = 3; const double testEnthalpy = 0.115331273E+03; const double vExp = 0.100215168E-02; double v = v_P_h_R1(testPress, testEnthalpy); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_P_h_3MPa_0d115331273Ep03h) { const double testPress = 3; const double testEnthalpy = 0.115331273E+03; const double uExp = 0.112324818E+03; double u = u_P_h_R1(testPress, testEnthalpy); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, s_P_h_3MPa_0d115331273Ep03h) { const double testPress = 3; const double testEnthalpy = 0.115331273E+03; const double sExp = 0.392294792; double s = s_P_h_R1(testPress, testEnthalpy); double sErr = AbsRelativeErr(s, sExp); bool sPass = IsAcceptable(sErr); ASSERT_TRUE(sPass); } TEST_F(AccTestsRegion1, T_P_h_3MPa_0d115331273Ep03h) { const double testPress = 3; const double testEnthalpy = 0.115331273E+03; const double tExp = 300; double T = T_P_h_R1(testPress, testEnthalpy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, cp_P_h_3MPa_0d115331273Ep03h) { const double testPress = 3; const double testEnthalpy = 0.115331273E+03; const double cpExp = 0.417301218E+01; double cp = cp_P_h_R1(testPress, testEnthalpy); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_P_h_3MPa_0d115331273Ep03h) { const double testPress = 3; const double testEnthalpy = 0.115331273E+03; const double cvExp = 4.121201603587; double cv = cv_P_h_R1(testPress, testEnthalpy); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_P_h_3MPa_0d115331273Ep03h) { const double testPress = 3; const double testEnthalpy = 0.115331273E+03; const double wExp = 0.150773921E+04; double w = w_P_h_R1(testPress, testEnthalpy); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_P_h_80MPa_0d184142828Ep03h) { const double testPress = 80; const double testEnthalpy = 0.184142828E+03; const double vExp = 0.971180894E-03; double v = v_P_h_R1(testPress, testEnthalpy); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_P_h_80MPa_0d184142828Ep03h) { const double testPress = 80; const double testEnthalpy = 0.184142828E+03; const double uExp = 0.106448356E+03; double u = u_P_h_R1(testPress, testEnthalpy); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, s_P_h_80MPa_0d184142828Ep03h) { const double testPress = 80; const double testEnthalpy = 0.184142828E+03; const double sExp = 0.368563852; double s = s_P_h_R1(testPress, testEnthalpy); double sErr = AbsRelativeErr(s, sExp); bool sPass = IsAcceptable(sErr); ASSERT_TRUE(sPass); } TEST_F(AccTestsRegion1, T_P_h_80MPa_0d184142828Ep03h) { const double testPress = 80; const double testEnthalpy = 0.184142828E+03; const double tExp = 300; double T = T_P_h_R1(testPress, testEnthalpy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, cp_P_h_80MPa_0d184142828Ep03h) { const double testPress = 80; const double testEnthalpy = 0.184142828E+03; const double cpExp = 0.401008987E+01; double cp = cp_P_h_R1(testPress, testEnthalpy); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_P_h_80MPa_0d184142828Ep03h) { const double testPress = 80; const double testEnthalpy = 0.184142828E+03; const double cvExp = 3.917366061845; double cv = cv_P_h_R1(testPress, testEnthalpy); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_P_h_80MPa_0d184142828Ep03h) { const double testPress = 80; const double testEnthalpy = 0.184142828E+03; const double wExp = 0.163469054E+04; double w = w_P_h_R1(testPress, testEnthalpy); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_P_h_3MPa_0d975542239Ep03h) { const double testPress = 3; const double testEnthalpy = 0.975542239E+03; const double vExp = 0.120241800E-02; double v = v_P_h_R1(testPress, testEnthalpy); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_P_h_3MPa_0d975542239Ep03h) { const double testPress = 3; const double testEnthalpy = 0.975542239E+03; const double uExp = 0.971934985E+03; double u = u_P_h_R1(testPress, testEnthalpy); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, s_P_h_3MPa_0d975542239Ep03h) { const double testPress = 3; const double testEnthalpy = 0.975542239E+03; const double sExp = 0.258041912E+01; double s = s_P_h_R1(testPress, testEnthalpy); double sErr = AbsRelativeErr(s, sExp); bool sPass = IsAcceptable(sErr); ASSERT_TRUE(sPass); } TEST_F(AccTestsRegion1, T_P_h_3MPa_0d975542239Ep03h) { const double testPress = 3; const double testEnthalpy = 0.975542239E+03; const double tExp = 500; double T = T_P_h_R1(testPress, testEnthalpy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, cp_P_h_3MPa_0d975542239Ep03h) { const double testPress = 3; const double testEnthalpy = 0.975542239E+03; const double cpExp = 0.465580682E+01; double cp = cp_P_h_R1(testPress, testEnthalpy); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_P_h_3MPa_0d975542239Ep03h) { const double testPress = 3; const double testEnthalpy = 0.975542239E+03; const double cvExp = 3.221392229028; double cv = cv_P_h_R1(testPress, testEnthalpy); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_P_h_3MPa_0d975542239Ep03h) { const double testPress = 3; const double testEnthalpy = 0.975542239E+03; const double wExp = 0.124071337E+04; double w = w_P_h_R1(testPress, testEnthalpy); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_P_s_3MPa_0d392294792s) { const double testPress = 3; const double testEntropy = 0.392294792; const double vExp = 0.100215168E-02; double v = v_P_s_R1(testPress, testEntropy); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_P_s_3MPa_0d392294792s) { const double testPress = 3; const double testEntropy = 0.392294792; const double uExp = 0.112324818E+03; double u = u_P_s_R1(testPress, testEntropy); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, h_P_s_3MPa_0d392294792s) { const double testPress = 3; const double testEntropy = 0.392294792; const double hExp = 0.115331273E+03; double h = h_P_s_R1(testPress, testEntropy); double hErr = AbsRelativeErr(h, hExp); bool hPass = IsAcceptable(hErr); ASSERT_TRUE(hPass); } TEST_F(AccTestsRegion1, T_P_s_3MPa_0d392294792s) { const double testPress = 3; const double testEntropy = 0.392294792; const double tExp = 300; double T = T_P_s_R1(testPress, testEntropy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, cp_P_s_3MPa_0d392294792s) { const double testPress = 3; const double testEntropy = 0.392294792; const double cpExp = 0.417301218E+01; double cp = cp_P_s_R1(testPress, testEntropy); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_P_s_3MPa_0d392294792s) { const double testPress = 3; const double testEntropy = 0.392294792; const double cvExp = 4.121201603587; double cv = cv_P_s_R1(testPress, testEntropy); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_P_s_3MPa_0d392294792s) { const double testPress = 3; const double testEntropy = 0.392294792; const double wExp = 0.150773921E+04; double w = w_P_s_R1(testPress, testEntropy); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_P_s_80MPa_0d368563852s) { const double testPress = 80; const double testEntropy = 0.368563852; const double vExp = 0.971180894E-03; double v = v_P_s_R1(testPress, testEntropy); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_P_s_80MPa_0d368563852s) { const double testPress = 80; const double testEntropy = 0.368563852; const double uExp = 0.106448356E+03; double u = u_P_s_R1(testPress, testEntropy); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, h_P_s_80MPa_0d368563852s) { const double testPress = 80; const double testEntropy = 0.368563852; const double hExp = 0.184142828E+03; double h = h_P_s_R1(testPress, testEntropy); double hErr = AbsRelativeErr(h, hExp); bool hPass = IsAcceptable(hErr); ASSERT_TRUE(hPass); } TEST_F(AccTestsRegion1, T_P_s_80MPa_0d368563852s) { const double testPress = 80; const double testEntropy = 0.368563852; const double tExp = 300; double T = T_P_s_R1(testPress, testEntropy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, cp_P_s_80MPa_0d368563852s) { const double testPress = 80; const double testEntropy = 0.368563852; const double cpExp = 0.401008987E+01; double cp = cp_P_s_R1(testPress, testEntropy); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_P_s_80MPa_0d368563852s) { const double testPress = 80; const double testEntropy = 0.368563852; const double cvExp = 3.917366061845; double cv = cv_P_s_R1(testPress, testEntropy); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_P_s_80MPa_0d368563852s) { const double testPress = 80; const double testEntropy = 0.368563852; const double wExp = 0.163469054E+04; double w = w_P_s_R1(testPress, testEntropy); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_P_s_3MPa_0d258041912Ep01s) { const double testPress = 3; const double testEntropy = 0.258041912E+01; const double vExp = 0.120241800E-02; double v = v_P_s_R1(testPress, testEntropy); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_P_s_3MPa_0d258041912Ep01s) { const double testPress = 3; const double testEntropy = 0.258041912E+01; const double uExp = 0.971934985E+03; double u = u_P_s_R1(testPress, testEntropy); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, h_P_s_3MPa_0d258041912Ep01s) { const double testPress = 3; const double testEntropy = 0.258041912E+01; const double hExp = 0.975542239E+03; double h = h_P_s_R1(testPress, testEntropy); double hErr = AbsRelativeErr(h, hExp); bool hPass = IsAcceptable(hErr); ASSERT_TRUE(hPass); } TEST_F(AccTestsRegion1, T_P_s_3MPa_0d258041912Ep01s) { const double testPress = 3; const double testEntropy = 0.258041912E+01; const double tExp = 500; double T = T_P_s_R1(testPress, testEntropy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, cp_P_s_3MPa_0d258041912Ep01s) { const double testPress = 3; const double testEntropy = 0.258041912E+01; const double cpExp = 0.465580682E+01; double cp = cp_P_s_R1(testPress, testEntropy); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_P_s_3MPa_0d258041912Ep01s) { const double testPress = 3; const double testEntropy = 0.258041912E+01; const double cvExp = 3.221392229028; double cv = cv_P_s_R1(testPress, testEntropy); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_P_s_3MPa_0d258041912Ep01s) { const double testPress = 3; const double testEntropy = 0.258041912E+01; const double wExp = 0.124071337E+04; double w = w_P_s_R1(testPress, testEntropy); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_h_s_0d115331273Ep03h_0d392294792s) { const double testEnthalpy = 0.115331273E+03; const double testEntropy = 0.392294792; const double vExp = 0.100215168E-02; double v = v_h_s_R1(testEnthalpy, testEntropy); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_h_s_0d115331273Ep03h_0d392294792s) { const double testEnthalpy = 0.115331273E+03; const double testEntropy = 0.392294792; const double uExp = 0.112324818E+03; double u = u_h_s_R1(testEnthalpy, testEntropy); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, P_h_s_0d115331273Ep03h_0d392294792s) { const double testEnthalpy = 0.115331273E+03; const double testEntropy = 0.392294792; const double pExp = 3; double P = P_h_s_R1(testEnthalpy, testEntropy); double PErr = AbsRelativeErr(P, pExp); bool PPass = IsAcceptable(PErr); ASSERT_TRUE(PPass); } TEST_F(AccTestsRegion1, T_h_s_0d115331273Ep03h_0d392294792s) { const double testEnthalpy = 0.115331273E+03; const double testEntropy = 0.392294792; const double tExp = 300; double T = T_h_s_R1(testEnthalpy, testEntropy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, cp_h_s_0d115331273Ep03h_0d392294792s) { const double testEnthalpy = 0.115331273E+03; const double testEntropy = 0.392294792; const double cpExp = 0.417301218E+01; double cp = cp_h_s_R1(testEnthalpy, testEntropy); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_h_s_0d115331273Ep03h_0d392294792s) { const double testEnthalpy = 0.115331273E+03; const double testEntropy = 0.392294792; const double cvExp = 4.121201603587; double cv = cv_h_s_R1(testEnthalpy, testEntropy); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_h_s_0d115331273Ep03h_0d392294792s) { const double testEnthalpy = 0.115331273E+03; const double testEntropy = 0.392294792; const double wExp = 0.150773921E+04; double w = w_h_s_R1(testEnthalpy, testEntropy); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_h_s_0d184142828Ep03h_0d368563852s) { const double testEnthalpy = 0.184142828E+03; const double testEntropy = 0.368563852; const double vExp = 0.971180894E-03; double v = v_h_s_R1(testEnthalpy, testEntropy); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_h_s_0d184142828Ep03h_0d368563852s) { const double testEnthalpy = 0.184142828E+03; const double testEntropy = 0.368563852; const double uExp = 0.106448356E+03; double u = u_h_s_R1(testEnthalpy, testEntropy); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, P_h_s_0d184142828Ep03h_0d368563852s) { const double testEnthalpy = 0.184142828E+03; const double testEntropy = 0.368563852; const double pExp = 80; double P = P_h_s_R1(testEnthalpy, testEntropy); double PErr = AbsRelativeErr(P, pExp); bool PPass = IsAcceptable(PErr); ASSERT_TRUE(PPass); } TEST_F(AccTestsRegion1, T_h_s_0d184142828Ep03h_0d368563852s) { const double testEnthalpy = 0.184142828E+03; const double testEntropy = 0.368563852; const double tExp = 300; double T = T_h_s_R1(testEnthalpy, testEntropy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, cp_h_s_0d184142828Ep03h_0d368563852s) { const double testEnthalpy = 0.184142828E+03; const double testEntropy = 0.368563852; const double cpExp = 0.401008987E+01; double cp = cp_h_s_R1(testEnthalpy, testEntropy); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_h_s_0d184142828Ep03h_0d368563852s) { const double testEnthalpy = 0.184142828E+03; const double testEntropy = 0.368563852; const double cvExp = 3.917366061845; double cv = cv_h_s_R1(testEnthalpy, testEntropy); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_h_s_0d184142828Ep03h_0d368563852s) { const double testEnthalpy = 0.184142828E+03; const double testEntropy = 0.368563852; const double wExp = 0.163469054E+04; double w = w_h_s_R1(testEnthalpy, testEntropy); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } TEST_F(AccTestsRegion1, v_h_s_0d975542239Ep03h_0d258041912Ep01s) { const double testEnthalpy = 0.975542239E+03; const double testEntropy = 0.258041912E+01; const double vExp = 0.120241800E-02; double v = v_h_s_R1(testEnthalpy, testEntropy); double vErr = AbsRelativeErr(v, vExp); bool vPass = IsAcceptable(vErr); ASSERT_TRUE(vPass); } TEST_F(AccTestsRegion1, u_h_s_0d975542239Ep03h_0d258041912Ep01s) { const double testEnthalpy = 0.975542239E+03; const double testEntropy = 0.258041912E+01; const double uExp = 0.971934985E+03; double u = u_h_s_R1(testEnthalpy, testEntropy); double uErr = AbsRelativeErr(u, uExp); bool uPass = IsAcceptable(uErr); ASSERT_TRUE(uPass); } TEST_F(AccTestsRegion1, P_h_s_0d975542239Ep03h_0d258041912Ep01s) { const double testEnthalpy = 0.975542239E+03; const double testEntropy = 0.258041912E+01; const double pExp = 3; double P = P_h_s_R1(testEnthalpy, testEntropy); double PErr = AbsRelativeErr(P, pExp); bool PPass = IsAcceptable(PErr); ASSERT_TRUE(PPass); } TEST_F(AccTestsRegion1, T_h_s_0d975542239Ep03h_0d258041912Ep01s) { const double testEnthalpy = 0.975542239E+03; const double testEntropy = 0.258041912E+01; const double tExp = 500; double T = T_h_s_R1(testEnthalpy, testEntropy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, cp_h_s_0d975542239Ep03h_0d258041912Ep01s) { const double testEnthalpy = 0.975542239E+03; const double testEntropy = 0.258041912E+01; const double cpExp = 0.465580682E+01; double cp = cp_h_s_R1(testEnthalpy, testEntropy); double cpErr = AbsRelativeErr(cp, cpExp); bool cpPass = IsAcceptable(cpErr); ASSERT_TRUE(cpPass); } TEST_F(AccTestsRegion1, cv_h_s_0d975542239Ep03h_0d258041912Ep01s) { const double testEnthalpy = 0.975542239E+03; const double testEntropy = 0.258041912E+01; const double cvExp = 3.221392229028; double cv = cv_h_s_R1(testEnthalpy, testEntropy); double cvErr = AbsRelativeErr(cv, cvExp); bool cvPass = IsAcceptable(cvErr); ASSERT_TRUE(cvPass); } TEST_F(AccTestsRegion1, w_h_s_0d975542239Ep03h_0d258041912Ep01s) { const double testEnthalpy = 0.975542239E+03; const double testEntropy = 0.258041912E+01; const double wExp = 0.124071337E+04; double w = w_h_s_R1(testEnthalpy, testEntropy); double wErr = AbsRelativeErr(w, wExp); bool wPass = IsAcceptable(wErr); ASSERT_TRUE(wPass); } //The pressure and enthalpy data points for Region1 were //suggested by the IAPWS in "Revised Release on IAPWS //Inductrial Formulation 1997 for the Thermodynamic //Properties of Water and Steam" in Table 7 on page 11. TEST_F(AccTestsRegion1, T_P_h_3MPa_500h) { const double testPressure = 3; const double testEnth = 500; const double tExp = 0.391798509E+03; double T = T_P_h_R1(testPressure, testEnth); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, T_P_h_80MPa_500h) { const double testPressure = 80; const double testEnth = 500; const double tExp = 0.378108626E+03; double T = T_P_h_R1(testPressure, testEnth); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, T_P_h_80MPa_1500h) { const double testPressure = 80; const double testEnth = 1500; const double tExp = 0.611041229E+03; double T = T_P_h_R1(testPressure, testEnth); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } //The pressure and entropy data points for Region1 were //suggested by the IAPWS in "Revised Release on IAPWS //Inductrial Formulation 1997 for the Thermodynamic //Properties of Water and Steam" in Table 9 on page 12. TEST_F(AccTestsRegion1, T_P_s_3MPa_0d5s) { const double testPressure = 3; const double testEntropy = 0.5; const double tExp = 0.307842258E+03; double T = T_P_s_R1(testPressure, testEntropy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, T_P_s_80MPa_0d5s) { const double testPressure = 80; const double testEntropy = 0.5; const double tExp = 0.309979785E+03; double T = T_P_s_R1(testPressure, testEntropy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } TEST_F(AccTestsRegion1, T_P_s_80MPa_3s) { const double testPressure = 80; const double testEntropy = 3; const double tExp = 0.565899909E+03; double T = T_P_s_R1(testPressure, testEntropy); double TErr = AbsRelativeErr(T, tExp); bool TPass = IsAcceptable(TErr); ASSERT_TRUE(TPass); } //The enthalpy and entropy data points for Region1 were //suggested by the IAPWS in "Revised Supplementary Release //on Backward Equations for Pressure as a Function of Enthalpy //and Entropy p(h,s) for Regions 1 and 2 of the IAPWS Industrial //Formulation 1997 for the Thermodynamic Properties of Water and Steam" //in Table 3 on page 6. TEST_F(AccTestsRegion1, P_h_s_0d001h_0s) { const double testEnth = 0.001; const double testEntr = 0; const double pExp = 9.800980612E-04; double P = (P_h_s_R1(testEnth, testEntr)); double PErr = AbsRelativeErr(P, pExp); bool PPass = IsAcceptable(PErr); ASSERT_TRUE(PPass); } TEST_F(AccTestsRegion1, P_h_s_90h_0s) { const double testEnth = 90; const double testEntr = 0; const double pExp = 9.192954727E+01; double P = (P_h_s_R1(testEnth, testEntr)); double PErr = AbsRelativeErr(P, pExp); bool PPass = IsAcceptable(PErr); ASSERT_TRUE(PPass); } TEST_F(AccTestsRegion1, P_h_s_1500h_34s) { const double testEnth = 1500; const double testEntr = 3.4; const double pExp = 5.868294423E+01; double P = (P_h_s_R1(testEnth, testEntr)); double PErr = AbsRelativeErr(P, pExp); bool PPass = IsAcceptable(PErr); ASSERT_TRUE(PPass); } #endif
{'dir': 'cpp', 'id': '1259183', 'max_stars_count': '0', 'max_stars_repo_name': 'jonathan-rizk/WaterThermodynamicProperties', 'max_stars_repo_path': 'test/AccuracyTests/AccTestsRegion1.cpp', 'n_tokens_mistral': 16380, 'n_tokens_neox': 14261, 'n_words': 2692}
<gh_stars>0 /** * Pulls a data series from a collection by index. */ export function getTripTimeStat(tripTimeValues, index) { if (!tripTimeValues) { return null; } const statValues = {}; Object.keys(tripTimeValues).forEach(endStopId => { statValues[endStopId] = tripTimeValues[endStopId][index]; }); return statValues; } /** * Access of precomputed wait and trip times. * * See https://github.com/trynmaps/metrics-mvp/pull/143 for an overview of the file structure and * json structure. * * Functions taken from the isochrone branch. * * Fetching of the precomputed wait/trip time json is done using Redux. * getWaitTimeAtStop is commented out but left here for usage reference. */ /** * Gets trip times for a given route and direction. * * @param tripTimes * @param routeId * @param directionId * @param stat * @returns */ export function getTripTimesForDirection( tripTimes, routeId, directionId, ) { if (!tripTimes) { //console.log('no trip times'); return null; } const routeTripTimes = tripTimes.routes[routeId]; if (!routeTripTimes) { //console.log('no trip times for route ' + routeId); return null; } const directionTripTimes = routeTripTimes[directionId]; return directionTripTimes; } /** * Gets the downstream trip times for a given route, direction, and stop. * * @param tripTimes * @param routeId * @param directionId * @param startStopId * @param stat "median" * @returns */ export function getTripTimesFromStop( tripTimes, routeId, directionId, startStopId, stat = 'median', ) { const directionTripTimes = getTripTimesForDirection( tripTimes, routeId, directionId, ); if (!directionTripTimes) { // console.log('null trip times'); return null; } const tripTimeValues = directionTripTimes[startStopId]; if (stat === 'median') { // using the median stat group (see getStatPath) return getTripTimeStat(tripTimeValues, 1); // return tripTimeValues; // p10-median-p90 file blocked: } if (stat === 'p10') { // using the p10-median-p90 stat group (see getStatPath) return getTripTimeStat(tripTimeValues, 0); } if (stat === 'p90') { // using the p10-median-p90 stat group (see getStatPath) return getTripTimeStat(tripTimeValues, 2); } return null; } /** * Gets the wait time info for a given route and direction. * * @param waitTimes * @param routeId * @param directionId */ export function getWaitTimeForDirection( waitTimes, routeId, directionId, ) { if (!waitTimes) { return null; } const routeWaitTimes = waitTimes.routes[routeId]; if (!routeWaitTimes) { return null; } const directionWaitTimes = routeWaitTimes[directionId]; if (!directionWaitTimes) { return null; } return directionWaitTimes; } /** * Averages together the median wait in all directions for a route. * * @param {any} waitTimes * @param {any} route */ export function getAverageOfMedianWaitStat( waitTimes, route, stat = 'median', ) { const directions = route.directions; const sumOfMedians = directions.reduce((total, direction) => { const waitForDir = getWaitTimeForDirection( waitTimes, route.id, direction.id, ); if (!waitForDir || !waitForDir.median) { return NaN; } if (stat === 'plt20m') { // statgroup is median-p90-plt20m return total + waitForDir.median[2]; // subscript two is median of per-stop probabilities of < 20m wait } // default to median return total + waitForDir.median[0]; // subscript zero is median of per-stop medians }, 0); return sumOfMedians / directions.length; }
{'dir': 'javascript', 'id': '9731078', 'max_stars_count': '0', 'max_stars_repo_name': 'anujkumar93/metrics-mvp', 'max_stars_repo_path': 'frontend/src/helpers/precomputed.js', 'n_tokens_mistral': 1213, 'n_tokens_neox': 1159, 'n_words': 336}
<reponame>jeremycook/Bridge using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace DataBridge.EF.Internals { /// <summary> /// A value that identifies an inteface that a <see cref="Domain.Class"/> implements. /// </summary> internal class Interface { [Obsolete("Runtime only", true)] public Interface() { } public Interface(string name) { if (name == null) throw new ArgumentNullException("name"); Name = name; } [Key, Column(Order = 1)] public string ClassName { get; protected set; } public virtual Class Class { get; protected set; } [Key, Column(Order = 2)] [Required, StringLength(100)] public string Name { get; protected set; } } }
{'dir': 'c-sharp', 'id': '6633776', 'max_stars_count': '0', 'max_stars_repo_name': 'jeremycook/Bridge', 'max_stars_repo_path': 'DataBridge.EF/Internals/Interface.cs', 'n_tokens_mistral': 237, 'n_tokens_neox': 225, 'n_words': 68}
<?php namespace Database\Seeders; use App\Models\Client; use Illuminate\Database\Seeder; class ClientSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Client::create([ "userName" => "Anas", "email" => "SAMII", "cin" => "Ain chok", "password" => "<PASSWORD>", "address" => "hfjxf", "city" => "Bag", "postalCode" => "test" ]); Client::create([ "userName" => "Anas", "email" => "SAMII", "cin" => "Ain chok", "password" => "<PASSWORD>", "address" => "hdfu", "city" => "Bag", "postalCode" => "test" ]); } }
{'dir': 'php', 'id': '13108178', 'max_stars_count': '0', 'max_stars_repo_name': 'FatimaHMICH/GhadiApp', 'max_stars_repo_path': 'database/seeders/ClientSeeder.php', 'n_tokens_mistral': 248, 'n_tokens_neox': 246, 'n_words': 52}
class Api::V1::LectureGroupsController < ApplicationController def index lecture_groups = LectureGroup.all render json: lecture_groups.to_json({ except: %i[created_at updated_at] }) end end
{'dir': 'ruby', 'id': '414362', 'max_stars_count': '2', 'max_stars_repo_name': 'mricanho/ae-backend', 'max_stars_repo_path': 'app/controllers/api/v1/lecture_groups_controller.rb', 'n_tokens_mistral': 63, 'n_tokens_neox': 62, 'n_words': 15}
define([ "Underscore", "hr/hr", "vendors/markdown", "models/message", "utils/github" ], function(_, hr, markdown, Message, github) { var logging = hr.Logger.addNamespace("messages"); // Collection var Messages = hr.Collection.extend({ model: Message, }); // List Item View var MessageItem = hr.List.Item.extend({ className: "message-item", template: "lists/message.html", events: { "click .message-reply": "open" }, templateContext: function() { return { object: this.model, content: markdown.toHTML(this.model.get("body") || "") } }, render: function() { if (this.model.get("body") == null) { this.model.getBody().done(_.bind(this.render, this)); return this; } if (this.model.get("author") == null) { this.model.getInfos().done(_.bind(this.render, this)); return this; } return MessageItem.__super__.render.apply(this, arguments); }, open: function(e) { if (e != null) { e.preventDefault(); e.stopPropagation(); } var Conversations = require("views/conversation"); var conversation = new Conversations({ "repo": this.model.repo, "path": this.model.get("path") }); this.$(".sub-conversation").empty(); conversation.$el.appendTo(this.$(".sub-conversation")); conversation.render(); } }); // List View var MessagesList = hr.List.extend({ className: "list-messages", Collection: Messages, Item: MessageItem, defaults: _.defaults({ loadAtInit: false }, hr.List.prototype.defaults), }, { Collection: Messages, Item: MessageItem }); hr.View.Template.registerComponent("list.messages", MessagesList); return MessagesList; });
{'dir': 'javascript', 'id': '3238268', 'max_stars_count': '23', 'max_stars_repo_name': 'FriendCode/gitrap', 'max_stars_repo_path': 'views/lists/messages.js', 'n_tokens_mistral': 573, 'n_tokens_neox': 559, 'n_words': 105}
<reponame>cragkhit/elasticsearch<filename>references/bcb_chosen_clones/default#89653#82#211.java @Override public void actionPerformed(ActionEvent event) { if (event.getSource() == btnChange) { Error.log(7002, "Bot�o alterar pressionado por " + login + "."); if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int j = 1; for (j = 1; j < password1.length(); j++) { if (passwordUser1.getPassword()[j] != c) { break; } c = passwordUser1.getPassword()[j]; } if (j == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } Statement stmt; String sql; sql = "update Usuarios set password = '" + <PASSWORD> + "' where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + login + " foi alterado com sucesso."); dispose(); } if (event.getSource() == btnCancel) { Error.log(7003, "Bot�o voltar de alterar para o menu principal pressionado por " + login + "."); dispose(); } }
{'dir': 'java', 'id': '10394325', 'max_stars_count': '23', 'max_stars_repo_name': 'cragkhit/elasticsearch', 'max_stars_repo_path': 'references/bcb_chosen_clones/default#89653#82#211.java', 'n_tokens_mistral': 1635, 'n_tokens_neox': 1483, 'n_words': 317}
''' Created on May 17, 2019 @author: <NAME> ''' import json import sys import jsonschema import warnings from checkers import JSON_SUBTYPE_CHECKERS from _normalizer import lazy_normalize from _utils import print_db class Checker(object): # Change here which validator to use. VALIDATOR = jsonschema.Draft4Validator ''' The checker class constructor accepts two 'valid' json files. ''' def __init__(self, s1, s2): self.s1 = s1 self.s2 = s2 # self.validate_schemas() def validate_schemas(self): ''' Validate given schemas against the pre-defined VALIDATOR schema. ''' print_db("Validating lhs schema ...") Checker.VALIDATOR.check_schema(self.s1) # print_db("Validating rhs schema ...") Checker.VALIDATOR.check_schema(self.s2) def is_subschema(self): return Checker.is_subtype(self.s1, self.s2) @staticmethod def is_subtype(s1, s2): ''' Is s1 <: s2 ? ''' # Trivial cases + normalization # -- case rhs allows anything if s2 is True or s2 == {}: # warnings.warn( # message="Warning: any schema is sub-schema of True or the empty schema {}. This will always be true.", stacklevel=1) return True # -- case lhs == rhs if s1 == s2: # warnings.warn( # message="Warning: any schema is sub-schema of itself. This will always be true.", stacklevel=1) return True # -- case rhs does not allow anything if s2 is False or s2.get("not") == {}: # warnings.warn( # message="Warning: No schema is sub-schema of False or the ~ empty schema 'not': {}. This will always be false.", stacklevel=1) return False # --case lhs does not allow anything if s1 is False: return True # normalization print_db(s1) s1 = lazy_normalize(s1) print_db("normalized --> ", s1) print_db(s2) s2 = lazy_normalize(s2) print_db("normalized --> ", s2) # # from checkers import JSON_SUBTYPE_CHECKERS # Gonna give higher precedence to boolean connectors over # 'type' cuz the connectors condition has to be met anyways. if "anyOf" in s1.keys(): return JSON_SUBTYPE_CHECKERS.get("anyOf")(s1, s2) elif "anyOf" in s2.keys(): return JSON_SUBTYPE_CHECKERS.get("anyOf_rhs")(s1, s2) # else: return JSON_SUBTYPE_CHECKERS.get(s1["type"])(s1, s2) if __name__ == "__main__": ''' Accepts two arguments s1 and s2. Checks wther s1 <: s2 ''' if len(sys.argv) != 3: print("Wrong arguments: accepts two .json schema files.") sys.exit() s1_file = sys.argv[1] s2_file = sys.argv[2] print("Loading json schemas from:\n{}\n{}\n".format(s1_file, s2_file)) with open(s1_file, 'r') as f1: s1 = json.load(f1) with open(s2_file, 'r') as f2: s2 = json.load(f2) checker = Checker(s1, s2) print(checker.is_subschema())
{'dir': 'python', 'id': '1886254', 'max_stars_count': '1', 'max_stars_repo_name': 'lukeenterprise/json-subschema', 'max_stars_repo_path': 'jsonsubschema/old/subschemachecker.py', 'n_tokens_mistral': 1021, 'n_tokens_neox': 993, 'n_words': 288}
<filename>PHP-SRePs-Frontend/MonthlyReport.cs using Grpc.Core; using Grpc.Net.Client; using PHP_SRePS_Backend; using System; using System.IO; using System.Threading.Tasks; using System.Windows.Forms; namespace PHP_SRePS_Frontend { public partial class MonthlyReport : Form { ReportMenu menuForm; public MonthlyReport(ReportMenu form) { _ = Gprc_channel_instance.GetInstance(); InitializeComponent(); menuForm = form; } private async void btnGenerateReport_Click(object sender, EventArgs e) { await getMonthlySale(); } private async Task getMonthlySale() { var client = Gprc_channel_instance.ReportClient; var input = new DateGet { Month = Int32.Parse(txtMonth.Text), Year = Int32.Parse(txtYear.Text) }; var dvg = dvgSalesReport; using(var call = client.GetMonthlyReport(input)) { var total = 0f; while (await call.ResponseStream.MoveNext()) { var currentItemInfo = call.ResponseStream.Current; var itemid = currentItemInfo.ItemId; var itemName = currentItemInfo.ItemName; var qty = currentItemInfo.QtySold; var revenue = currentItemInfo.ItemRevenue; total += revenue; dvg.Rows.Add(itemid, itemName, qty, revenue); } lblTotalPrice.Text = $"${total:0.00}"; } } private async void btnCSV_Click(object sender, EventArgs e) { var client = Gprc_channel_instance.ReportClient; var input = new DateGet { Month = Int32.Parse(txtMonth.Text), Year = Int32.Parse(txtYear.Text) }; var csvInfo = await client.GetMonthlyReportAsCSVAsync(input); using (var w = new StreamWriter($".\\sale-report-{txtMonth.Text}-{txtYear.Text}.csv")) { foreach (var r in csvInfo.CsvRow) { w.WriteLine(r); w.Flush(); } } } private void btnBack_Click(object sender, EventArgs e) { menuForm.Show(); this.Close(); } } }
{'dir': 'c-sharp', 'id': '1595062', 'max_stars_count': '0', 'max_stars_repo_name': 'phillipweinstock/PHP-SRePS', 'max_stars_repo_path': 'PHP-SRePs-Frontend/MonthlyReport.cs', 'n_tokens_mistral': 698, 'n_tokens_neox': 645, 'n_words': 132}
<reponame>MegNieves/BankAppGit package operations; import accounts.Account; public class AccountSummary implements AccountOperations { @Override public void performOperation(Account account) { System.out.println("Account current balance: " + account.getBalance()); } }
{'dir': 'java', 'id': '10822421', 'max_stars_count': '0', 'max_stars_repo_name': 'MegNieves/BankAppGit', 'max_stars_repo_path': 'accountsummary.java', 'n_tokens_mistral': 78, 'n_tokens_neox': 76, 'n_words': 19}
/* _ _ _ ____ _ _____ / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___ / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \ / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | | /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_| Copyright 2015-2017 Łukasz "JustArchi" Domeradzki Contact: <EMAIL> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using ArchiSteamFarm.JSON; using ArchiSteamFarm.Localization; using Newtonsoft.Json; namespace ArchiSteamFarm { [SuppressMessage("ReSharper", "ClassCannotBeInstantiated")] [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")] [SuppressMessage("ReSharper", "ConvertToConstant.Global")] internal sealed class BotConfig { #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool AcceptGifts; #pragma warning restore 649 #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool AutoDiscoveryQueue; #pragma warning restore 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool CardDropsRestricted = true; #pragma warning disable 649 [JsonProperty] internal readonly string CustomGamePlayedWhileFarming; #pragma warning restore 649 #pragma warning disable 649 [JsonProperty] internal readonly string CustomGamePlayedWhileIdle; #pragma warning restore 649 #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool DismissInventoryNotifications; #pragma warning restore 649 #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool Enabled; #pragma warning restore 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly EFarmingOrder FarmingOrder = EFarmingOrder.Unordered; #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool FarmOffline; #pragma warning restore 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly HashSet<uint> GamesPlayedWhileIdle = new HashSet<uint>(); #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool HandleOfflineMessages; #pragma warning restore 649 #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool IdleRefundableGames = true; #pragma warning restore 649 #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool IsBotAccount; #pragma warning restore 649 [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Replace, Required = Required.DisallowNull)] internal readonly HashSet<Steam.Item.EType> LootableTypes = new HashSet<Steam.Item.EType> { Steam.Item.EType.BoosterPack, Steam.Item.EType.FoilTradingCard, Steam.Item.EType.TradingCard }; [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Replace, Required = Required.DisallowNull)] internal readonly HashSet<Steam.Item.EType> MatchableTypes = new HashSet<Steam.Item.EType> { Steam.Item.EType.TradingCard }; [JsonProperty(Required = Required.DisallowNull)] internal readonly CryptoHelper.ECryptoMethod PasswordFormat = CryptoHelper.ECryptoMethod.PlainText; #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool Paused; #pragma warning restore 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly ERedeemingPreferences RedeemingPreferences = ERedeemingPreferences.None; #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool SendOnFarmingFinished; #pragma warning restore 649 #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly byte SendTradePeriod; #pragma warning restore 649 #pragma warning disable 649 [JsonProperty(Required = Required.DisallowNull)] internal readonly bool ShutdownOnFarmingFinished; #pragma warning restore 649 #pragma warning disable 649 [JsonProperty] internal readonly string SteamTradeToken; #pragma warning restore 649 [SuppressMessage("ReSharper", "CollectionNeverUpdated.Global")] [JsonProperty(Required = Required.DisallowNull)] internal readonly Dictionary<ulong, EPermission> SteamUserPermissions = new Dictionary<ulong, EPermission>(); [JsonProperty(Required = Required.DisallowNull)] internal readonly ETradingPreferences TradingPreferences = ETradingPreferences.None; [JsonProperty(PropertyName = GlobalConfig.UlongStringPrefix + nameof(SteamMasterClanID), Required = Required.DisallowNull)] internal string SSteamMasterClanID { set { if (string.IsNullOrEmpty(value) || !ulong.TryParse(value, out ulong result)) { ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorIsInvalid, nameof(SSteamMasterClanID))); return; } SteamMasterClanID = result; } } [JsonProperty] internal string SteamLogin { get; set; } [JsonProperty(Required = Required.DisallowNull)] internal ulong SteamMasterClanID { get; private set; } [JsonProperty] internal string SteamParentalPIN { get; set; } = "0"; [JsonProperty] internal string SteamPassword { get; set; } // This constructor is used only by deserializer private BotConfig() { } // Functions below are used for skipping serialization of sensitive fields in API response public bool ShouldSerializeSteamLogin() => false; public bool ShouldSerializeSteamParentalPIN() => false; public bool ShouldSerializeSteamPassword() => false; internal static BotConfig Load(string filePath) { if (string.IsNullOrEmpty(filePath)) { ASF.ArchiLogger.LogNullError(nameof(filePath)); return null; } if (!File.Exists(filePath)) { return null; } BotConfig botConfig; try { botConfig = JsonConvert.DeserializeObject<BotConfig>(File.ReadAllText(filePath)); } catch (Exception e) { ASF.ArchiLogger.LogGenericException(e); return null; } if (botConfig == null) { ASF.ArchiLogger.LogNullError(nameof(botConfig)); return null; } // Support encrypted passwords if ((botConfig.PasswordFormat != CryptoHelper.ECryptoMethod.PlainText) && !string.IsNullOrEmpty(botConfig.SteamPassword)) { // In worst case password will result in null, which will have to be corrected by user during runtime botConfig.SteamPassword = CryptoHelper.Decrypt(botConfig.PasswordFormat, botConfig.SteamPassword); } // User might not know what he's doing // Ensure that he can't screw core ASF variables if (botConfig.GamesPlayedWhileIdle.Count <= ArchiHandler.MaxGamesPlayedConcurrently) { return botConfig; } ASF.ArchiLogger.LogGenericWarning(string.Format(Strings.WarningTooManyGamesToPlay, ArchiHandler.MaxGamesPlayedConcurrently, nameof(botConfig.GamesPlayedWhileIdle))); HashSet<uint> validGames = new HashSet<uint>(botConfig.GamesPlayedWhileIdle.Take(ArchiHandler.MaxGamesPlayedConcurrently)); botConfig.GamesPlayedWhileIdle.IntersectWith(validGames); botConfig.GamesPlayedWhileIdle.TrimExcess(); return botConfig; } internal enum EFarmingOrder : byte { Unordered, AppIDsAscending, AppIDsDescending, CardDropsAscending, CardDropsDescending, HoursAscending, HoursDescending, NamesAscending, NamesDescending, Random, BadgeLevelsAscending, BadgeLevelsDescending, RedeemDateTimesAscending, RedeemDateTimesDescending } internal enum EPermission : byte { None, FamilySharing, Operator, Master } [Flags] internal enum ERedeemingPreferences : byte { None = 0, Forwarding = 1, Distributing = 2, KeepMissingGames = 4 } [Flags] internal enum ETradingPreferences : byte { None = 0, AcceptDonations = 1, SteamTradeMatcher = 2, MatchEverything = 4, DontAcceptBotTrades = 8 } } }
{'dir': 'c-sharp', 'id': '3966277', 'max_stars_count': '0', 'max_stars_repo_name': 'bcukan/test', 'max_stars_repo_path': 'ArchiSteamFarm/BotConfig.cs', 'n_tokens_mistral': 2947, 'n_tokens_neox': 2570, 'n_words': 625}
<filename>src/rpasdt/algorithm/source_detectors/net_sleuth.py """NetSleuth source detection method.""" import networkx as nx import numpy as np from networkx import Graph from rpasdt.algorithm.source_detectors.common import ( CommunityBasedSourceDetector, ) class NetSleuthCommunityBasedSourceDetector(CommunityBasedSourceDetector): def find_sources_in_community(self, graph: Graph): nodes = np.array(graph.nodes()) L = nx.laplacian_matrix(graph).todense().A w, v = np.linalg.eig(L) v1 = v[np.where(w == np.min(w))][0] max_val = np.max(v1) sources = nodes[np.where(v1 == np.max(v1))] return {source: max_val for source in sources}
{'dir': 'python', 'id': '8586685', 'max_stars_count': '2', 'max_stars_repo_name': 'damianfraszczak/rpasdt', 'max_stars_repo_path': 'src/rpasdt/algorithm/source_detectors/net_sleuth.py', 'n_tokens_mistral': 240, 'n_tokens_neox': 233, 'n_words': 49}
#ifndef INCLUDED_VIEWREAD_STACK_H #define INCLUDED_VIEWREAD_STACK_H #include <stdio.h> #include <stdbool.h> static uint64_t next_func_id = 1; // Enum for types of functions typedef enum { MAIN, CILK, HELPER, } FunctionType_t; // Enum for types of bags typedef enum { SS, SP, P, } BagType_t; typedef struct DisjointSet_t { BagType_t type; uint64_t init_func_id; uint64_t set_func_id; struct DisjointSet_t *parent; uint64_t rank; } DisjointSet_t; // Typedef of viewread stack frame typedef struct viewread_stack_frame_t { FunctionType_t func_type; uint64_t ancestor_spawns; uint64_t local_spawns; DisjointSet_t* ss_bag; DisjointSet_t* sp_bag; DisjointSet_t* p_bag; struct viewread_stack_frame_t *parent; } viewread_stack_frame_t; // Type for a viewread stack typedef struct { /* Flag to indicate whether user code is being executed. This flag is mostly used for debugging. */ bool in_user_code; /* Pointer to bottom of the stack, onto which frames are pushed. */ viewread_stack_frame_t *bot; } viewread_stack_t; void DisjointSet_init(DisjointSet_t *s) { s->parent = s; s->rank = 0; } /* * The only reason we need this function is to ensure that * the _set_node returned for representing this set is the oldest * node in the set. */ void DisjointSet_swap_set_node(DisjointSet_t *s, DisjointSet_t *t) { uint64_t tmp = s->set_func_id; s->set_func_id = t->set_func_id; t->set_func_id = tmp; } void DisjointSet_link(DisjointSet_t *s, DisjointSet_t *t) { if (s->rank > t->rank) { t->parent = s; } else { s->parent = t; if (s->rank == t->rank) { ++t->rank; } DisjointSet_swap_set_node(s, t); } } DisjointSet_t* DisjointSet_find_set(DisjointSet_t *s) { if (s->parent != s) { s->parent = DisjointSet_find_set(s->parent); } return s->parent; } /* * Unions disjoint sets s and t. * * NOTE: implicitly, in order to maintain the oldest _set_node, one * should always combine younger set into this set (defined by * creation time). Since we union by rank, we may end up linking * this set to the younger set. To make sure that we always return * the oldest _node to represent the set, we use an additional * _set_node field to keep track of the oldest node and use that to * represent the set. * * @param s (older) disjoint set. * @param t (younger) disjoint set. */ // Called "combine," because "union" is a reserved keyword in C void DisjointSet_combine(DisjointSet_t *s, DisjointSet_t *t) { assert(t); assert(DisjointSet_find_set(s) != DisjointSet_find_set(t)); DisjointSet_link(DisjointSet_find_set(s), DisjointSet_find_set(t)); assert(DisjointSet_find_set(s) == DisjointSet_find_set(t)); } // Initializes the viewread stack frame *frame void viewread_stack_frame_init(viewread_stack_frame_t *frame, FunctionType_t func_type, uint64_t ancestor_spawns) { frame->parent = NULL; frame->func_type = func_type; frame->ancestor_spawns = ancestor_spawns; frame->local_spawns = 0; frame->ss_bag = (DisjointSet_t*)malloc(sizeof(DisjointSet_t)); DisjointSet_init(frame->ss_bag); frame->ss_bag->type = SS; frame->ss_bag->init_func_id = next_func_id++; frame->ss_bag->set_func_id = frame->ss_bag->init_func_id; frame->sp_bag = NULL; frame->p_bag = NULL; } // Initializes the viewread stack void viewread_stack_init(viewread_stack_t *stack, FunctionType_t func_type) { viewread_stack_frame_t *new_frame = (viewread_stack_frame_t *)malloc(sizeof(viewread_stack_frame_t)); viewread_stack_frame_init(new_frame, func_type, 0); stack->bot = new_frame; stack->in_user_code = false; } // Push new frame of function type func_type onto the stack *stack viewread_stack_frame_t* viewread_stack_push(viewread_stack_t *stack, FunctionType_t func_type) { viewread_stack_frame_t *new_frame = (viewread_stack_frame_t *)malloc(sizeof(viewread_stack_frame_t)); if (HELPER == func_type) { // Function was spawned ++stack->bot->local_spawns; /* fprintf(stderr, "P bag %p, SP bag %p\n", */ /* stack->bot->p_bag, stack->bot->sp_bag); */ if (NULL == stack->bot->p_bag && NULL != stack->bot->sp_bag) { stack->bot->p_bag = DisjointSet_find_set(stack->bot->sp_bag); stack->bot->p_bag->type = P; stack->bot->sp_bag = NULL; } else if (NULL != stack->bot->sp_bag) { DisjointSet_combine(stack->bot->p_bag, stack->bot->sp_bag); stack->bot->p_bag->type = P; stack->bot->sp_bag = NULL; } } // Initialize the new frame, using the current frame's current view // ID as the inital and current view ID of the new frame. viewread_stack_frame_init(new_frame, func_type, stack->bot->ancestor_spawns + stack->bot->local_spawns); new_frame->parent = stack->bot; stack->bot = new_frame; return new_frame; } // Pops the bottommost frame off of the stack *stack, and returns a // pointer to it. viewread_stack_frame_t* viewread_stack_pop(viewread_stack_t *stack) { viewread_stack_frame_t *old_bottom = stack->bot; stack->bot = stack->bot->parent; return old_bottom; } #endif
{'dir': 'c', 'id': '8187992', 'max_stars_count': '3', 'max_stars_repo_name': 'neboat/cilktools', 'max_stars_repo_path': 'viewread/viewread_stack.h', 'n_tokens_mistral': 1935, 'n_tokens_neox': 1876, 'n_words': 464}
package rsc.publisher; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import org.testng.Assert; import rsc.test.TestSubscriber; public class PublisherCollectTest { @Test(expected = NullPointerException.class) public void nullSource() { new PublisherCollect<>(null, () -> 1, (a, b) -> { }); } @Test(expected = NullPointerException.class) public void nullSupplier() { new PublisherCollect<>(PublisherNever.instance(), null, (a, b) -> { }); } @Test(expected = NullPointerException.class) public void nullAction() { new PublisherCollect<>(PublisherNever.instance(), () -> 1, null); } @Test public void normal() { TestSubscriber<ArrayList<Integer>> ts = new TestSubscriber<>(); new PublisherCollect<>(new PublisherRange(1, 10), ArrayList<Integer>::new, (a, b) -> a.add(b)).subscribe(ts); ts.assertValue(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))) .assertNoError() .assertComplete(); } @Test public void normalBackpressured() { TestSubscriber<ArrayList<Integer>> ts = new TestSubscriber<>(0); new PublisherCollect<>(new PublisherRange(1, 10), ArrayList<Integer>::new, (a, b) -> a.add(b)).subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); ts.request(2); ts.assertValue(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))) .assertNoError() .assertComplete(); } @Test public void supplierThrows() { TestSubscriber<Object> ts = new TestSubscriber<>(); new PublisherCollect<>(new PublisherRange(1, 10), () -> { throw new RuntimeException("forced failure"); }, (a, b) -> { }).subscribe(ts); ts.assertNoValues() .assertError(RuntimeException.class) .assertErrorMessage("forced failure") .assertNotComplete(); } @Test public void supplierReturnsNull() { TestSubscriber<Object> ts = new TestSubscriber<>(); new PublisherCollect<>(new PublisherRange(1, 10), () -> null, (a, b) -> { }).subscribe(ts); ts.assertNoValues() .assertError(NullPointerException.class) .assertNotComplete(); } @Test public void actionThrows() { TestSubscriber<Object> ts = new TestSubscriber<>(); new PublisherCollect<>(new PublisherRange(1, 10), () -> 1, (a, b) -> { throw new RuntimeException("forced failure"); }).subscribe(ts); ts.assertNoValues() .assertError(RuntimeException.class) .assertErrorMessage("forced failure") .assertNotComplete(); } @Test public void fusionNoPrematureEmission() { Integer i = Px.just(1) .collect(() -> 1, (a, b) -> { }) .flatMapIterable(a -> Collections.singletonList(2)) .blockingFirst() ; Assert.assertEquals(2, i.intValue()); } }
{'dir': 'java', 'id': '19457793', 'max_stars_count': '364', 'max_stars_repo_name': 'spring-operator/reactive-streams-commons', 'max_stars_repo_path': 'src/test/java/rsc/publisher/PublisherCollectTest.java', 'n_tokens_mistral': 950, 'n_tokens_neox': 900, 'n_words': 192}
<filename>devel/9cc/ld/mod.c #include "l.h" void readundefs(char *f, int t) { int i, n; Sym *s; Biobuf *b; char *l, buf[256], *fields[64]; if(f == nil) return; b = Bopen(f, OREAD); if(b == nil){ diag("could not open %s: %r", f); errorexit(); } while((l = Brdline(b, '\n')) != nil){ n = Blinelen(b); if(n >= sizeof(buf)){ diag("%s: line too long", f); errorexit(); } memmove(buf, l, n); buf[n-1] = '\0'; n = getfields(buf, fields, nelem(fields), 1, " \t\r\n"); if(n == nelem(fields)){ diag("%s: bad format", f); errorexit(); } for(i = 0; i < n; i++){ s = lookup(fields[i], 0); s->type = SXREF; s->subtype = t; if(t == SIMPORT) nimports++; else nexports++; } } Bterm(b); } void undefsym(Sym *s) { int n; n = imports; if(s->value != 0) diag("value != 0 on SXREF"); if(n >= 1<<Rindex) diag("import index %d out of range", n); s->value = n<<Roffset; s->type = SUNDEF; imports++; } void zerosig(char *sp) { Sym *s; s = lookup(sp, 0); s->sig = 0; } void import(void) { int i; Sym *s; for(i = 0; i < NHASH; i++) for(s = hash[i]; s != S; s = s->link) if(s->sig != 0 && s->type == SXREF && (nimports == 0 || s->subtype == SIMPORT)){ undefsym(s); Bprint(&bso, "IMPORT: %s sig=%lux v=%ld\n", s->name, s->sig, (long)s->value); } } void ckoff(Sym *s, long v) { if(v < 0 || v >= 1<<Roffset) diag("relocation offset %ld for %s out of range", v, s->name); } static Prog* newdata(Sym *s, int o, int w, int t) { Prog *p; p = prg(); p->link = datap; datap = p; p->as = ADATA; p->reg = w; p->from.type = D_OREG; p->from.name = t; p->from.sym = s; p->from.offset = o; p->to.type = D_CONST; p->to.name = D_NONE; return p; } void export(void) { int i, j, n, off, nb, sv, ne; Sym *s, *et, *str, **esyms; Prog *p; char buf[NSNAME], *t; n = 0; for(i = 0; i < NHASH; i++) for(s = hash[i]; s != S; s = s->link) if(s->sig != 0 && s->type != SXREF && s->type != SUNDEF && (nexports == 0 || s->subtype == SEXPORT)) n++; esyms = malloc(n*sizeof(Sym*)); ne = n; n = 0; for(i = 0; i < NHASH; i++) for(s = hash[i]; s != S; s = s->link) if(s->sig != 0 && s->type != SXREF && s->type != SUNDEF && (nexports == 0 || s->subtype == SEXPORT)) esyms[n++] = s; for(i = 0; i < ne-1; i++) for(j = i+1; j < ne; j++) if(strcmp(esyms[i]->name, esyms[j]->name) > 0){ s = esyms[i]; esyms[i] = esyms[j]; esyms[j] = s; } nb = 0; off = 0; et = lookup(EXPTAB, 0); if(et->type != 0 && et->type != SXREF) diag("%s already defined", EXPTAB); et->type = SDATA; str = lookup(".string", 0); if(str->type == 0) str->type = SDATA; sv = str->value; for(i = 0; i < ne; i++){ s = esyms[i]; Bprint(&bso, "EXPORT: %s sig=%lux t=%d\n", s->name, s->sig, s->type); /* signature */ p = newdata(et, off, sizeof(long), D_EXTERN); off += sizeof(long); p->to.offset = s->sig; /* address */ p = newdata(et, off, sizeof(long), D_EXTERN); off += sizeof(long); p->to.name = D_EXTERN; p->to.sym = s; /* string */ t = s->name; n = strlen(t)+1; for(;;){ buf[nb++] = *t; sv++; if(nb >= NSNAME){ p = newdata(str, sv-NSNAME, NSNAME, D_STATIC); p->to.type = D_SCONST; p->to.sval = malloc(NSNAME); memmove(p->to.sval, buf, NSNAME); nb = 0; } if(*t++ == 0) break; } /* name */ p = newdata(et, off, sizeof(long), D_EXTERN); off += sizeof(long); p->to.name = D_STATIC; p->to.sym = str; p->to.offset = sv-n; } if(nb > 0){ p = newdata(str, sv-nb, nb, D_STATIC); p->to.type = D_SCONST; p->to.sval = malloc(NSNAME); memmove(p->to.sval, buf, nb); } for(i = 0; i < 3; i++){ newdata(et, off, sizeof(long), D_EXTERN); off += sizeof(long); } et->value = off; if(sv == 0) sv = 1; str->value = sv; exports = ne; free(esyms); }
{'dir': 'c', 'id': '7889740', 'max_stars_count': '14', 'max_stars_repo_name': 'ibara/LiteBSD-Ports', 'max_stars_repo_path': 'devel/9cc/ld/mod.c', 'n_tokens_mistral': 2030, 'n_tokens_neox': 1820, 'n_words': 443}
package com.flightstats.hub.webhook.strategy; import com.flightstats.hub.model.Epoch; import com.flightstats.hub.model.Location; import com.flightstats.hub.model.TimeQuery; import com.flightstats.hub.util.TimeUtil; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; @Slf4j public class QueryGenerator { private DateTime lastQueryTime; private String channel; public QueryGenerator(DateTime startTime, String channel) { lastQueryTime = startTime; this.channel = channel; } TimeQuery getQuery(DateTime latestStableInChannel) { log.trace("iterating last {} stable {} ", lastQueryTime, latestStableInChannel); if (lastQueryTime.isBefore(latestStableInChannel)) { TimeUtil.Unit unit = getStepUnit(latestStableInChannel); Location location = Location.ALL; if (unit.equals(TimeUtil.Unit.SECONDS)) { location = Location.CACHE_WRITE; } else if (unit.equals(TimeUtil.Unit.DAYS)) { log.info("long term query unit={} lastQueryTime={}", unit, lastQueryTime); } TimeQuery query = TimeQuery.builder() .channelName(channel) .startTime(lastQueryTime) .unit(unit) .location(location) .epoch(Epoch.IMMUTABLE) .build(); lastQueryTime = unit.round(lastQueryTime.plus(unit.getDuration())); return query; } else { return null; } } private TimeUtil.Unit getStepUnit(DateTime latestStableInChannel) { if (lastQueryTime.isBefore(latestStableInChannel.minusHours(2))) { return TimeUtil.Unit.HOURS; } else if (lastQueryTime.isBefore(latestStableInChannel.minusMinutes(2))) { return TimeUtil.Unit.MINUTES; } return TimeUtil.Unit.SECONDS; } DateTime getLastQueryTime() { return lastQueryTime; } }
{'dir': 'java', 'id': '8975987', 'max_stars_count': '97', 'max_stars_repo_name': 'flightstats/hub', 'max_stars_repo_path': 'src/main/java/com/flightstats/hub/webhook/strategy/QueryGenerator.java', 'n_tokens_mistral': 571, 'n_tokens_neox': 552, 'n_words': 98}
namespace SqlCrawler.Backend.Core { public class SqlServerInfo: SqlServerInfoPublic { public string DataSource { get; set; } public bool UseIntegratedSecurity { get; set; } public string SqlUsername { get; set; } public string SqlPassword { get; set; } } }
{'dir': 'c-sharp', 'id': '3875656', 'max_stars_count': '10', 'max_stars_repo_name': 'georgemclaughlin/sql-crawler', 'max_stars_repo_path': 'src/SqlCrawler.Backend/Core/SqlServerInfo.cs', 'n_tokens_mistral': 84, 'n_tokens_neox': 83, 'n_words': 26}