language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
331
2.828125
3
[ "MIT" ]
permissive
#https://inf-ege.sdamgia.ru/problem?id=10290&print=true s = '1' + '8' * 80 while s.find('18')!= -1 or s.find('288') != -1 or s.find('3888')!= -1: if s.find('18')!=-1: s = s.replace('18', '2', 1) elif s.find('288') != -1: s = s.replace('288', '3', 1) else: s =s.replace('3888', '1', 1) print(s)
Markdown
UTF-8
6,434
3.34375
3
[]
no_license
--- title: JavaScript - Depuracion description: La utilizacion de una herramienta de depuracion es esencial para trabajar con JavaScript. categories: - Blog - Javascript comments: true --- De vez en cuando, los desarrolladores cometen errores al codificar. Un error en un programa o un script se conoce como error. El proceso de encontrar y corregir errores se llama depuracion y es una parte normal del proceso de desarrollo. Esta seccion cubre herramientas y tecnicas que pueden ayudarlo con las tareas de depuracion. ### Mensajes de error en IE La forma mas basica de rastrear errores es activando la informacion de errores en su navegador. De forma predeterminada, Internet Explorer muestra un icono de error en la barra de estado cuando se produce un error en la pagina. Hacer doble clic en este icono lo lleva a un cuadro de dialogo que muestra informacion sobre el error especifico que ocurrio. Dado que este icono es facil de pasar por alto, Internet Explorer le ofrece la opcion de mostrar automaticamente el cuadro de dialogo Error cada vez que se produce un error. Para habilitar esta opcion, seleccione Herramientas > Opciones de Internet > pestaña Avanzado. y, finalmente, marque la opcion del cuadro "Mostrar una notificacion sobre cada error de script". ### Mensajes de error en Firefox o Mozilla Otros navegadores como Firefox, Netscape y Mozilla envian mensajes de error a una ventana especial llamada JavaScript Console o Error Consol. Para ver la consola, seleccione Herramientas > Consola de errores o Desarrollo web. Desafortunadamente, dado que estos navegadores no dan indicaciones visuales cuando ocurre un error, debe mantener la consola abierta y observar si hay errores mientras se ejecuta el script. ### Notificaciones de error Las notificaciones de error que aparecen en la consola o en los cuadros de dialogo de Internet Explorer son el resultado de errores de sintaxis y de tiempo de ejecucion. Estas notificaciones de error incluyen el numero de linea en el que ocurrio el error. Si esta usando Firefox, puede hacer clic en el error disponible en la consola de error para ir a la linea exacta en el script que tiene el error. ### Como depurar un script Hay varias formas de depurar tu JavaScript: #### Utilice un validador de JavaScript Una forma de verificar si su codigo JavaScript tiene errores extraños es ejecutarlo a traves de un programa que lo verifique para asegurarse de que sea valido y que siga las reglas de sintaxis oficiales del lenguaje. Estos programas se denominan analizadores de validacion o solo validadores para abreviar, y a menudo vienen con editores comerciales de HTML y JavaScript. El validador mas conveniente para JavaScript es la JavaScript Lint de Douglas Crockford, que esta disponible de forma gratuita en la JavaScript Lint de Douglas Crockford. Simplemente visite esa pagina web, pegue el codigo JavaScript (solo JavaScript) en el area de texto proporcionada y haga clic en el boton jslint. Este programa analizara el codigo JavaScript, asegurando que todas las definiciones de variables y funciones sigan la sintaxis correcta. Tambien verificara las declaraciones de JavaScript, como `if` y `while`, para asegurarse de que tambien sigan el formato correcto #### Agregue codigo de depuracion a sus programas Puede usar los metodos `alert()` o `document.write()` en su programa para depurar el codigo. Por ejemplo, puede escribir algo de la siguiente manera: ```javascript var debugging = true; var whichImage = "widget"; if( debugging ) alert( "Calls swapImage() with argument: " + whichImage ); var swapStatus = swapImage( whichImage ); if( debugging ) alert( "Exits swapImage() with swapStatus=" + swapStatus ); ``` Al examinar el contenido y orden de `alert()` cuando aparecen, puede examinar la salud de su programa facilmente. #### Use un depurador JavaScript Un depurador es una aplicacion que pone todos los aspectos de la ejecucion del script bajo el control del programador. Los depuradores proporcionan un control preciso sobre el estado del script a traves de una interfaz que le permite examinar y establecer valores, asi como controlar el flujo de ejecucion. Una vez que se ha cargado un script en un depurador, se puede ejecutar una linea a la vez o indicarle que se detenga en ciertos puntos de interrupcion. Una vez que se detiene la ejecucion, el programador puede examinar el estado del script y sus variables para determinar si algo esta mal. Tambien puede ver las variables para ver los cambios en sus valores. ### Consejos utiles para desarrolladores Puede tener en cuenta los siguientes consejos para reducir la cantidad de errores en sus scripts y simplificar el proceso de depuracion: - Use muchos comentarios. Los comentarios le permiten explicar por que escribio el script de la manera en que lo hizo y explicar secciones de codigo particularmente dificiles. - Utilice siempre sangria para que su codigo sea facil de leer. Las instrucciones con sangria tambien facilitan la combinacion de etiquetas iniciales, finales, llaves y otros elementos HTML y de script. - Escribir codigo modular Siempre que sea posible, agrupe sus declaraciones en funciones. Las funciones le permiten agrupar declaraciones relacionadas y probar y reutilizar partes de codigo con un minimo esfuerzo. - Sea coherente en la forma en que nombra sus variables y funciones. Intente usar nombres que sean lo suficientemente largos para ser significativos y que describan el contenido de la variable o el proposito de la funcion. - Utilice una sintaxis coherente al nombrar variables y funciones. En otras palabras, mantengalos todos en minusculas o en mayusculas; si prefiere la notacion del Camello, usela de manera consistente. - Pruebe guiones largos de forma modular. En otras palabras, no intente escribir el script completo antes de probar cualquier parte del mismo. Escriba una pieza y pongala a trabajar antes de agregar la siguiente porcion de codigo. - Use nombres descriptivos de variables y funciones y evite usar nombres de un solo caracter. - Mira tus comillas. Recuerde que las comillas se usan en pares alrededor de las cadenas y que ambas comillas deben ser del mismo estilo (simple o doble). - Mira tus signos iguales. No debe usar un solo = para fines de comparacion. - Declare variables explicitamente usando la palabra clave `var`. ### Contacto - Envia tus comentarios al correo `henrytorrespo@yahoo.com`
PHP
UTF-8
1,442
2.6875
3
[]
no_license
<?php /** * Operand * * Base class for parsed operand data */ abstract class Operand { public $iKind, $iSize, $value, $aBytes ; const MAPPED = [ OperandKind::LOCAL => 'LocalOperand', OperandKind::INDIR_0 => 'IndirectOperand', OperandKind::INDIR_1 => 'IndirectOperand', OperandKind::IDX_0_PH => 'PlaceholderIndexOperand', OperandKind::IDX_1_PH => 'PlaceHolderIndexOperand', OperandKind::JUMP_8 => 'ResolvedBranchTargetOperand', OperandKind::JUMP_16 => 'ResolvedBranchTargetOperand', OperandKind::SMALL_S8 => 'SmallLiteralIntegerOperand', OperandKind::SMALL_U8 => 'SmallLiteralIntegerOperand', OperandKind::BITPOS => 'SmallLiteralIntegerOperand', OperandKind::LABEL => 'UnresolvedOperand', OperandKind::DATA_SYM => 'UnresolvedOperand', OperandKind::CODE_SYM => 'UnresolvedOperand' ]; public static function create(int $iKind, $value, string $sSource) { if (!isset(self::MAPPED[$iKind])) { throw new Exception("Unmapped Operand Kind"); } $sKind = self::MAPPED[$iKind]; return new $sKind($iKind, $value, $sSource); } protected function __construct(int $iKind, $value, string $sSource) { $this->iKind = $iKind; $this->value = $value; $this->iSize = OperandKind::SIZES[$iKind]; } };
Java
UTF-8
620
2.4375
2
[]
no_license
package mobi.ioio.plotter.shapes; import java.io.Serializable; import mobi.ioio.plotter.CurvePlotter.Curve; import mobi.ioio.plotter.Plotter.MultiCurve; public class SingleCurveMultiCurve implements MultiCurve, Serializable { private static final long serialVersionUID = -8271726700104333260L; private final float[] bounds_; private Curve curve_; public SingleCurveMultiCurve(Curve curve, float[] bounds) { bounds_ = bounds; curve_ = curve; } @Override public Curve nextCurve() { Curve curve = curve_; curve_ = null; return curve; } @Override public float[] getBounds() { return bounds_; } }
Java
UTF-8
579
2.515625
3
[]
no_license
package by.epam.webex.dao; import by.epam.webex.dao.impl.SaxXmlDao; public class XMLDAOFactory { private final static XMLDAOFactory instance = new XMLDAOFactory(); public static XMLDAOFactory getInstance(){ return instance; } public XMLDao getDAO(DAOType type) throws XMLDaoException{ XMLDao dao; switch (type){ case SAX: return SaxXmlDao.getInstance(); default: throw new XMLDaoException("No such DAO"); } } public enum DAOType{ SAX, STAX, DOM; } }
C#
UTF-8
1,539
3.140625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient;// this is to work with database using System.Data;// to use the data set namespace OOP.DL { public class DBHelper { //By making a method as static it can be call by just using the class name (no need to create an object) public static int NonQuery(string query,string connString) { try { //creating a connection to the SQL server SqlConnection conn = new SqlConnection(connString); //create the command using and create connection object SqlCommand comm = new SqlCommand(query, conn); //open the connection conn.Open(); return comm.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } } public static DataSet GetDataSet(string query, string connString) { try { SqlConnection conn = new SqlConnection(connString); SqlDataAdapter dap = new SqlDataAdapter(query, conn); DataSet ds = new DataSet();//this is to store query results conn.Open(); dap.Fill(ds); return ds; } catch (Exception ex) { throw ex; } } } }
Java
UTF-8
1,085
3.375
3
[]
no_license
package hackerrank.implementation; import java.util.*; import java.io.*; import java.math.*; public class BonAppetit { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); String[] firstLine = in.readLine().split(" "); int n = Integer.parseInt(firstLine[0]); int k = Integer.parseInt(firstLine[1]); String[] secondLine = in.readLine().split(" "); int[] a = new int[n]; int b = Integer.parseInt(in.readLine().trim()); for(int i = 0; i < n; i++){ a[i] = Integer.parseInt(secondLine[i]); } int total = 0; for(int i = 0; i < n; i++){ if (i!=k){ total += a[i]; } } if ((total/2) == b) out.write("Bon Appetit"); else out.write(String.valueOf(b-(total/2))); out.close(); } }
Markdown
UTF-8
7,364
2.609375
3
[ "MIT" ]
permissive
# FunctionalStateMachine.jl [![Build Status](https://travis-ci.org/JuliaRobotics/FunctionalStateMachine.jl.svg?branch=master)](https://travis-ci.org/JuliaRobotics/FunctionalStateMachine.jl) [![codecov.io](https://codecov.io/github/JuliaRobotics/FunctionalStateMachine.jl/coverage.svg?branch=master)](https://codecov.io/github/JuliaRobotics/FunctionalStateMachine.jl?branch=master) [![Average time to resolve an issue](https://isitmaintained.com/badge/resolution/JuliaRobotics/FunctionalStateMachine.jl.svg)](https://github.com/JuliaRobotics/FunctionalStateMachine.jl/issues) [![Percentage of issues still open](https://isitmaintained.com/badge/open/JuliaRobotics/FunctionalStateMachine.jl.svg)](https://github.com/JuliaRobotics/FunctionalStateMachine.jl/issues) Build a state machine in Julia based on functions along with stepping and visualization tools ## Video Animation Example Click the Vimeo image as link to a FSM generated video animation of six concurrent state machines (as used in [IncrementalInference.jl](http://www.github.com/JuliaRobotics/IncrementalInference.jl)). [![Clique State Machine Concurrent Animation](https://user-images.githubusercontent.com/6412556/92198487-87b10900-ee42-11ea-8674-4a3867a74b65.png)](https://vimeo.com/454616769 "Clique State Machine Concurrent Animation - Click to Watch!") # Installation ## [OPTIONAL] System Dependencies Visualization tools require a system install of `graphviz`. Do Ubuntu/Debian Linux equivalent of: ```bash sudo apt-get install graphviz ``` ## Install Julia Package Julia ≥ 0.7 add package ```julia julia> ] (v1.5) pkg> add FunctionalStateMachine ``` # Example ## Basic ```julia using FunctionalStateMachine ## User state functions function bar!(usrdata) println("do bar!") return FunctionalStateMachine.exitStateMachine end function foo!(usrdata) println("do foo!") return bar! end # no user data struct defined, so just pass Nothing statemachine = StateMachine{Nothing}(next=foo!) while statemachine(nothing, verbose=true); end # or maybe limit number of steps statemachine = StateMachine{Nothing}(next=foo!) while statemachine(nothing, iterlimit=1); end ``` ### Watchdog Timeout Sometimes it is useful to know that an FSM process will exit, either as intended or by throwing an error on timeout (much like a [Watchdog Timer](https://en.wikipedia.org/wiki/Watchdog_timer)). FSM uses Base.`InterruptException()` as a method of stopping a task that expires a `timeout::Real` [seconds]. Note, this functionality is not included by default in order to preserve a small memory footprint. To use the timeout feature simply call the state machine with a timeout duration: ```julia userdata = nothing # any user data of type T timeout = 3.0 while statemachine(userdata, timeout, verbose=true); end ``` ### Recording Verbose Output to File Experience has shown that when a state machine gets stuck, it is often useful to write the `verbose` steps out to file as a bare minimum guide of where a system might be failing. This can be done by passing in a `::IOStream` handle into `verbosefid`: ```julia fid = open("/tmp/verboseFSM_001.log","w") while statemachine(userdata, verbose=true, verbosefid=fid); end close(fid) ``` This particular structure is chosen so that `@async` or other multithreaded uses of FSM can still write to a common `fid` and also allow the user to `flush(fid)` and `close(fid)` regardless of whether the FSM has stalled. Might seem "boilerplate-esque", but it's much easier for developers to snuff out bugs in highly complicted interdependent and multithreaded, multi-state-machine architectures. ## With User Data and History ```julia ## Passing a data structure mutable struct ExampleUserData x::Vector{Float64} end # or maybe record the state machine history statemachine = StateMachine{ExampleUserData}(next=foo!) eud = ExampleUserData(randn(10)) while statemachine(eud, recordhistory=true); end # recover recorded state transition history, `::Vector{Tuple{DateTime,Int,Function,T}}` hist = statemachine.history # or maybe rerun a step on the data as it was at that time -- does not overwrite previous memory new_eud_at_1 = sandboxStateMachineStep(hist, 1) ``` ## Draw State Pictures with Graphviz ```julia # ]add Graphs # in case the dependency is not installed yet using Graphs # run the state machine statemachine = StateMachine{ExampleUserData}(next=foo!) eud = ExampleUserData(randn(10)) while statemachine(eud, recordhistory=true); end # draw the state machine hist = statemachine.history drawStateMachineHistory(hist, show=true) ``` ## Multiple state machines can be visualized together ```julia using Graphs, FunctionalStateMachine #... # start multiple concurrent FSMs (this is only one) ## they are likely interdependent statemachine = StateMachine{Nothing}(next=foo!) while statemachine(nothing, recordhistory=true); end # add all histories to the `hists::Dict` as follows ## ths example has userdata of type ::Nothing hists = Dict{Symbol,Vector{Tuple{DateTime,Int,Function,Nothing}}}(:first => statemachine.history) # generate all the images that will make up the video animateStateMachineHistoryIntervalCompound(hists, interval=1) # and convert images to video with ffmpeg as shell command fps = 5 run(`ffmpeg -r 10 -i /tmp/caesar/csmCompound/csm_%d.png -c:v libtheora -vf fps=$fps -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" -q 10 /tmp/caesar/csmCompound/out.ogv`) @async run(`totem /tmp/caesar/csmCompound/out.ogv`) ``` can combine multiple concurrent histories of the state machine execution into the same image frames. See function for more details. # Lower Level Visualization tools ## Animate Asyncronous State Machine Transitions The following example function shows several state machines that were run asyncronously can be synchronously animated as separate frames (see below for single frame with multiple information): ```julia using Dates, DocStringExtensions """ $SIGNATURES Draw many images in '/tmp/?/csm_%d.png' representing time synchronized state machine events. Notes - State history must have previously been recorded. """ function animateStateMachines(histories::Vector{<:Tuple}; frames::Int=100) startT = Dates.now() stopT = Dates.now() # get start and stop times across all cliques first = true # hist = somestatemachine.history for hist in histories if hist[1][1] < startT startT = hist[1][1] end if first stopT = hist[end][1] end if stopT < hist[end][1] stopT= hist[end][1] end end # export all figures folders = String[] count = 0 for hist in histories count += 1 retval = animateStateMachineHistoryByTime(hist, frames=frames, folder="sm$count", title="SM-$count", startT=startT, stopT=stopT) push!(folders, "sm$count") end return folders end # animate the time via many png images in `/tmp` animateCliqStateMachines([hist1; hist2], frames=100) ``` This example will result in 100 images for both `hist1, hist` state machine history. Note the timestamps are used to synchronize animations images on concurrent state traversals, and can easily be made into a video with OpenShot or ffmpeg style tools. ## Previous Linear Time Multi-FSM Animation A closely related function ```julia animateStateMachineHistoryByTime ``` # Contribute Contributions and Issues welcome.
C
UTF-8
255
3.734375
4
[ "MIT" ]
permissive
#include <stdio.h> int my_atoi( char* str ) { int res = 0; for (int i = 0; str[i] != '\0'; i ++) { res = res * 10 + str[i] - '0'; } return res; } void main () { char str[] = "1234"; int val = my_atoi(str); printf("%d\n", val); }
C#
UTF-8
930
3.203125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oefening_Events { class Program { static void Main(string[] args) { Tankwagen wagen = new Tankwagen(200, 5000); wagen.LooptOverEvent += Wagen_LooptOver; while (wagen.Inhoud != wagen.MaxInhoud) { Console.WriteLine("Hoeveel wenst u te tanken"); wagen.Tanken(Convert.ToInt32(Console.ReadLine())); Console.WriteLine("Inhoud : {0}", wagen.Inhoud); Console.WriteLine("Maximum inhoud : {0}", wagen.MaxInhoud); } Console.ReadLine(); } private static void Wagen_LooptOver(object sender, LooptOverEventArgs e) { Console.WriteLine("{0} , Er kon nog {1} bij.", e.Melding, e.GetankteHoeveelheid); } } }
PHP
UTF-8
5,578
2.609375
3
[ "Apache-2.0" ]
permissive
<?php declare(strict_types=1); namespace app\command; use app\server\socketio\Simple; use PHPSocketIO\SocketIO; use think\console\Command; use think\console\Input; use think\console\input\Argument; use think\console\input\Option; use think\console\Output; use think\facade\Config; use Workerman\Worker; class SIO extends Command { protected function configure() { // 指令配置 $this->setName('sio') ->addArgument('action', Argument::OPTIONAL, 'start|stop|restart|reload|status|connections', 'start') ->addOption('host', 'H', Option::VALUE_OPTIONAL, 'the host of workerman server.', null) ->addOption('port', 'p', Option::VALUE_OPTIONAL, 'the port of workerman server.', null) ->addOption('daemon', 'd', Option::VALUE_NONE, 'Run the workerman server in daemon mode.') ->setDescription('Workerman Server for ThinkPHP'); } protected function execute(Input $input, Output $output) { // 指令输出 $action = $input->getArgument('action'); if (DIRECTORY_SEPARATOR !== '\\') { if (!in_array($action, ['start', 'stop', 'reload', 'restart', 'status', 'connections'])) { $output->writeln("<error>Invalid argument action:{$action}, Expected start|stop|restart|reload|status|connections .</error>"); return false; } global $argv; array_shift($argv); array_shift($argv); array_unshift($argv, 'think', $action); } elseif ('start' != $action) { $output->writeln("<error>Not Support action:{$action} on Windows.</error>"); return false; } $this->config = Config::get('worker_socketio'); if ('start' == $action) { $output->writeln('Starting PHPStockIO server...'); } // $this->simpleSioServer(); // $this->startServer($this->config['socketio_class']); // $io = new Simple(); // 自定义服务器入口类 if (!empty($this->config['socketio_class'])) { $class = (array) $this->config['socketio_class']; foreach ($class as $server) { $this->startServer($server); } // Run worker Worker::runAll(); return; } if (!empty($this->config['socket'])) { $socket = $this->config['socket']; list($host, $port) = explode(':', $socket); } else { $host = $this->getHost(); $port = $this->getPort(); $protocol = !empty($this->config['protocol']) ? $this->config['protocol'] : 'websocket'; $socket = $protocol.'://'.$host.':'.$port; unset($this->config['host'], $this->config['port'], $this->config['protocol']); } // 避免pid混乱 $this->config['pidFile'] .= '_'.$port; // 开启守护进程模式 if ($this->input->hasOption('daemon')) { Worker::$daemonize = true; } if (!empty($this->config['ssl'])) { $this->config['transport'] = 'ssl'; unset($this->config['ssl']); } // 设置服务器参数 foreach ($this->config as $name => $val) { if (in_array($name, ['stdoutFile', 'daemonize', 'pidFile', 'logFile'])) { Worker::${$name} = $val; } else { $worker->$name = $val; } } // Run worker Worker::runAll(); } protected function simpleSioServer() { $io = new SocketIO(2021); // 当有客户端连接时打印一行文字 $io->on('connection', function ($connection) use ($io) { echo "new connection coming\n"; // 定义chat message事件回调函数 $connection->on('chat message', function ($msg) use ($io) { // 触发所有客户端定义的chat message from server事件 $io->emit('chat message from server', '服务器信息:'.$msg); }); }); } protected function startServer(string $class) { if (class_exists($class)) { $io = new $class(); // if (!$io instanceof SocketServer) { // $this->output->writeln('<error>Worker Server Class Must extends \\think\\worker\\Server</error>'); // } } else { $this->output->writeln("<error>Worker Server Class Not Exists : {$class}</error>"); } } // protected function startServer(string $class) // { // if (class_exists($class)) { // $io = new $class(); // if (!$io instanceof SocketServer) { // $this->output->writeln('<error>Worker Server Class Must extends \\think\\worker\\Server</error>'); // } // } else { // $this->output->writeln("<error>Worker Server Class Not Exists : {$class}</error>"); // } // } protected function getHost() { if ($this->input->hasOption('host')) { $host = $this->input->getOption('host'); } else { $host = !empty($this->config['host']) ? $this->config['host'] : '0.0.0.0'; } return $host; } protected function getPort() { if ($this->input->hasOption('port')) { $port = $this->input->getOption('port'); } else { $port = !empty($this->config['port']) ? $this->config['port'] : 2348; } return $port; } }
Markdown
UTF-8
23,564
2.75
3
[]
no_license
# 212.1. Configuring a router ## **212.1 Configuring a router** **Weight:** 3 **Description:** Candidates should be able to configure a system to forward IP packet and perform network address translation \(NAT, IP masquerading\) and state its significance in protecting a network. This objective includes configuring port redirection, managing filter rules and averting attacks. **Key Knowledge Areas:** * iptables and ip6tables configuration files, tools and utilities * Tools, commands and utilities to manage routing tables. * Private address ranges \(IPv4\) and Unique Local Addresses as well as Link Local Addresses \(IPv6\) * Port redirection and IP forwarding * List and write filtering and rules that accept or block IP packets based on source or destination protocol, port and address * Save and reload filtering configurations **Terms and Utilities:** * /proc/sys/net/ipv4/ * /proc/sys/net/ipv6/ * /etc/services * iptables * ip6tables Like any other moder operating system, liunx has firewall. First lets see how linux firewalling is organized: ![](.gitbook/assets/route-netfilter.jpg) There is a firewalling functionality which is implemented in linux kernel with netfilter. netfilter is a kernel module and any network traffic which kernel forward to any interface\(s\), is pass through netfilter. This way netfilter can make decision wether incomming or out going traffic is allowed or not. The major interface to the netfilter module is iptables. iptables has been around for a long time and it let us to do any advanced configuration on linux firewalls. While being able to do any advanced firewall configuration is count as iptables advantage, the biggest disadvantage of iptables is its complexity. This disadvantage has been caused other solutions have been invented like ufw , firewalld . They both work with iptables behind the sence and make firewall configuration easier for us. For lpic2 exam we just talk about iptables. ## iptables iptables works with tables! There are at present three tables: * **Filter :** The filter table is used for packet filtering. * **NAT :** The nat table is used for address translation. * **Mangle :** The mangle table can be used for special-purpose processing of packets. Within tables there are chains.chains are used to define what kind of packet follow shoud be filtered exactly. ![](.gitbook/assets/route-iptables.jpg) * **PREROUTING:** configured to block, redirect or allow th packet to the next chain.Commonly, used to redirect the packet to another address or/and port. \(DNAT-Destination NAT\). If destination is local \( this machine\) sent to INPUT chain. If bound for another network, sent to the FORWARD chain. * INPUT: Configured to be blocked, logged or sent to the local system to be handled by the appropriate client, application or service. * OUTPUT: packet is sent from the firewall out to the network to its final destination.\(Rules usually are not applied at this chain\) * FORWARD : Configured to block, logged or sent to the POSTROUTING chain. * **POSTROUTING:** make changes to the packet as it exits the firewall, commonly used to do masquerading. How tables and chain are related so ? All three tree tables \(FILTER, NAT, MANGLE\) can be present in chains\(filter points\) but not every chain has all three table represented: ![](.gitbook/assets/route-iptables-tchains.jpg) * **PREROUTING \(** _**NAT**_ **,** MANGLE**\)** * INPUT \(**FILTER** , _**NAT**_ , MANGLE \) * FORWARD \(**FILTER** , MANGLE \) * OUTPUT \(**FILTER** , _**NAT**_ , MANGLE\) * **POSTROUTING \(**_**NAT**_ **,** MANGLE**\)** How rules are broken down within the firewall system? chains are filtering points that we can create rules, and rules are apllied to the packet passing trough. The rules define what exactly should happen to a packet. When packets are filterd trough the iptables firewall it will go tough the rules one by one, and the idea is "exit on match". So if a packet matches specific rule , the rule will be applied and nothing else will be applied in that chain any more. So ordering in iptables is very important. In every rule there us target, The typical target is ACCEPT: * **ACCEPT** : the package is allowed * **DROP** : The package is not allowed, the package will be sileintly dropped and the sender of package doesn't know anything. * **REJECT** : Do not allow package, the sender of package will get an ICMP warnnig message. * **LOG :** just LOGs * **MASQUARATE :** used for NAT. the target indicated with -j option. we will talk about that. In every chain there is a policy. The policy define the default behaviour. The default policy is ACCEPT but its isa good practice to have a policy that will drop every thing that doesn't match specific packet in a chain. to set chain default policy ```text iptables -P drop INPUT ``` please do notice that is upper case "P". ### iptables commands iptables commands can be pretty long, and sometimes hard to understand so lets defualt components in iptables commands to make it easier: ```text iptables -A chain [-i/-o interface] [-s/-d address] -p udp --sport/--dport 80 -j TARGET ``` `-A` appends to the end gollowed by the name of the chain, `[-i/-o interface]` incomming or outgoing interface,`[ -s/-d ]` source address or destination address,`-p` defines the protocol like tcp or udp, `[--sport/--dport]`for setting source or destination port number, `-j TARGET` which define what will happend to the packet that match this rule. iptables command options outside of adding rules to chain: | Option | Description | | :--- | :--- | | -L &lt;chain-name&gt; -t &lt;table-name&gt; | Lists all of the rules in the specified chain and table. If not chain or table specified, shows all. | | -D | Deletes a rule in a particular chain by number | | -F \(or --flush\) | flushes all \(or indicated chain\) of rules | | -P | change the default policy for the chain\(can be set to DROP or ACCEPT\) | | -v | typically used with -F\(or --flush\) to provide additional output | | -n | Display IP address and port in numeric format | For demonstration we use CentOS7, in RedHat the defualt solution is firewalld. We have to first stop and disable firewalld because firewalld interface and iptables can not work together: ```text [root@centos7-1 ~]# systemctl stop firewalld [root@centos7-1 ~]# systemctl disable firewalld Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service. Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service. [root@centos7-1 ~]# systemctl mask firewalld Created symlink from /etc/systemd/system/firewalld.service to /dev/null. ``` Now lets install iptables and iptables-service packages which is required for systemd: ```text [root@centos7-1 ~]# yum install iptables Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.metrocast.net * epel: fedora-epel.mirrors.tds.net * extras: mirror.mojohost.com * updates: mirror.teklinks.com Package iptables-1.4.21-24.1.el7_5.x86_64 already installed and latest version Nothing to do [root@centos7-1 ~]# yum install iptables-services [root@centos7-1 ~]# systemctl start iptables [root@centos7-1 ~]# systemctl enable iptables Created symlink from /etc/systemd/system/basic.target.wants/iptables.service to /usr/lib/systemd/system/iptables.service. ``` okey every thing is ready for starting, lets list everything wich is currently used: ```text [root@centos7-1 ~]# iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED ACCEPT icmp -- anywhere anywhere ACCEPT all -- anywhere anywhere ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh REJECT all -- anywhere anywhere reject-with icmp-host-prohibited Chain FORWARD (policy ACCEPT) target prot opt source destination REJECT all -- anywhere anywhere reject-with icmp-host-prohibited Chain OUTPUT (policy ACCEPT) target prot opt source destination ``` we flush iptables rule : set the default chains policy to DROP for more security and see the results: ```text [root@centos7-1 ~]# iptables -F -v Flushing chain `INPUT' Flushing chain `FORWARD' Flushing chain `OUTPUT' [root@centos7-1 ~]# iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination Chain FORWARD (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination ``` set the default chains policy to DROP for more security and see the results: ```text [root@centos7-1 ~]# iptables -P INPUT DROP [root@centos7-1 ~]# iptables -P FORWARD DROP [root@centos7-1 ~]# iptables -P OUTPUT DROP [root@centos7-1 ~]# iptables -L Chain INPUT (policy DROP) target prot opt source destination Chain FORWARD (policy DROP) target prot opt source destination Chain OUTPUT (policy DROP) target prot opt source destination ``` There is one note that we should never forget, linux uses loopback adapter for internel communication. But we have drope that: ```text [root@centos7-1 ~]# ping localhost PING localhost (127.0.0.1) 56(84) bytes of data. ping: sendmsg: Operation not permitted ping: sendmsg: Operation not permitted ping: sendmsg: Operation not permitted ping: sendmsg: Operation not permitted ^C --- localhost ping statistics --- 4 packets transmitted, 0 received, 100% packet loss, time 3014ms ``` So do not forget to ACCEPT loopback adapter packetes if you want to set chain default policy to drop: ```text [root@centos7-1 ~]# iptables -A INPUT -i lo -j ACCEPT [root@centos7-1 ~]# iptables -A OUTPUT -o lo -j ACCEPT ``` and check: ```text [root@centos7-1 ~]# ping localhost -c3 PING localhost (127.0.0.1) 56(84) bytes of data. 64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.030 ms 64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.117 ms 64 bytes from localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.148 ms --- localhost ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2006ms rtt min/avg/max/mdev = 0.030/0.098/0.148/0.050 ms ``` Now lets ACCEPT ssh coonection to be stablished with our host: ```text [root@centos7-1 ~]# iptables -A INPUT -p tcp --dport 22 -j ACCEPT ``` it seems okey hah? but it doesn't work, check it from another computer\(centos7-2\): ```text [root@centos7-2 ~]# ssh centos7-1 ^C ``` The point is that do not forget to set reverse rules inorder to let incomming traffic to our server\(centos7-1\), can come back: ```text [root@centos7-1 ~]# iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT [root@centos7-1 ~]# iptables -L Chain INPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere ACCEPT tcp -- anywhere anywhere tcp dpt:ssh Chain FORWARD (policy DROP) target prot opt source destination Chain OUTPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere ACCEPT tcp -- anywhere anywhere tcp spt:ssh ``` and check: ```text [root@centos7-2 ~]# ssh centos7-1 The authenticity of host 'centos7-1 (192.168.10.133)' can't be established. ECDSA key fingerprint is SHA256:QtfM2iXh5pxZeFdAUXEBEnRXNSP40MWIhnSYvpOBMoY. ECDSA key fingerprint is MD5:27:db:c1:d0:da:35:80:92:81:fa:8f:1c:e5:d7:f3:2e. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'centos7-1,192.168.10.133' (ECDSA) to the list of known hosts. root@centos7-1's password: Last login: Sun Jul 15 02:41:53 2018 Managed by ansible ``` #### Saving iptables rules iptables rules are not persisyent and they are vanished after reboot. rules are stored in /etc/sysconfig/iptables . for saving rules we use iptables-save command, ```text [root@centos7-1 ~]# iptables-save > /etc/sysconfig/iptables.$(date +%d-%m-%y) [root@centos7-1 ~]# ls /etc/sysconfig | grep iptables iptables iptables.18-07-18 iptables-config [root@centos7-1 ~]# cat /etc/sysconfig/iptables.18-07-18 # Generated by iptables-save v1.4.21 on Wed Jul 18 00:12:18 2018 *filter :INPUT DROP [136:9925] :FORWARD DROP [0:0] :OUTPUT DROP [209:34216] -A INPUT -i lo -j ACCEPT -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT -A OUTPUT -o lo -j ACCEPT -A OUTPUT -p tcp -m tcp --sport 22 -j ACCEPT COMMIT # Completed on Wed Jul 18 00:12:18 2018 ``` now we clear the previous rules: ```text [root@centos7-1 ~]# iptables -F [root@centos7-1 ~]# iptables -L Chain INPUT (policy DROP) target prot opt source destination Chain FORWARD (policy DROP) target prot opt source destination Chain OUTPUT (policy DROP) target prot opt source destination ``` use iptables-restoreto restore the backup: ```text [root@centos7-1 ~]# iptables-restore < /etc/sysconfig/iptables.18-07-18 [root@centos7-1 ~]# iptables -L Chain INPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere ACCEPT tcp -- anywhere anywhere tcp dpt:ssh Chain FORWARD (policy DROP) target prot opt source destination Chain OUTPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere ACCEPT tcp -- anywhere anywhere tcp spt:ssh ``` How to delete a rule ? There are two ways for deleting a rule, using -D option with full lenght of rule that we have specified: ```text [root@centos7-1 ~]# iptables -D OUTPUT -p tcp --sport 22 -j ACCEPT [root@centos7-1 ~]# iptables -L Chain INPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere ACCEPT tcp -- anywhere anywhere tcp dpt:ssh Chain FORWARD (policy DROP) target prot opt source destination Chain OUTPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere ``` or use iptables -L --line-numbers and delete a rule by using its number in the table: ```text [root@centos7-1 ~]# iptables -L --line-numbers Chain INPUT (policy DROP) num target prot opt source destination 1 ACCEPT all -- anywhere anywhere 2 ACCEPT tcp -- anywhere anywhere tcp dpt:ssh Chain FORWARD (policy DROP) num target prot opt source destination Chain OUTPUT (policy DROP) num target prot opt source destination 1 ACCEPT all -- anywhere anywhere [root@centos7-1 ~]# iptables -D INPUT 2 [root@centos7-1 ~]# iptables -L Chain INPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere Chain FORWARD (policy DROP) target prot opt source destination Chain OUTPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere ``` #### Now more iptables examples: Block TCP traffic from Specific IP Address: ```text iptables -A INPUT -p tcp -s xxx.xxx.xxx.xxx -j DROP ``` Allow All tcp xxx incomming port: ```text iptables -A INPUT -p tcp --dport xxx -j ACCEPT ``` some time we need to load special iptables module to do something special. Allow Multiple Ports : ```text iptables -A INPUT -p tcp -m multiport --dports 22,80,443 -j ACCEPT ``` Allow Specific Network Range on Particular Port: ```text iptables -A OUTPUT -p tcp -d 192.168.100.0/24 --dport 22 -j ACCEPT ``` Sometimes IP addresses may requests too many connections towards web ports on our website. This can cause number of issues and to prevent such problems, we can Block Network Flood on Apache Port using this rule: ```text iptables -A INPUT -p tcp --dport 80 -m limit --limit 100/minute --limit-burst 200 -j ACCEPT ``` Some time we want to just monitor network traffic or we want to trouble shoot our iptables firewall, best thing is logging: ```text iptables -A INPUT -i eth0 -j LOG --log-prefix "IPtables DROPPED:" ``` and then see the logs with `grep "IPtables DROPPED:" /var/log/messages` If our firewall has alot of rules, iptables log is used with iptables-save and iptables-restore . The trick is saving current rules, Allowing traffic, log it and then restoring rules and adding new required setting. ### Port Redirection Sometimes we may want to forward one service’s traffic to another port . Lets do this by an example:![](.gitbook/assets/route-portforward.jpg) Here we use two CentOS system, one as a web server which runs on port 80 and the other one as a web client. Every thing is working on port 80 smothly : ```text [root@centos7-1 ~]# elinks http://192.168.10.133 ``` ![](.gitbook/assets/route-ipfwsen1.jpg) but we want to do something whith iptables which redirect requests from port 8080 to port 80 this way clients from CentOS2 should be able to visit out site on port 8080: ```text [root@centos7-1 ~]# iptables -A INPUT -p tcp --dport 80 -j ACCEPT [root@centos7-1 ~]# iptables -t nat -A PREROUTING -i ens33 -p tcp --dport 8080 -j REDIRECT --to-port 80 ``` and check the result from CentOS7-2: ```text [root@centos7-2 ~]# elinks http://192.168.10.133:8080 ``` ![](.gitbook/assets/route-ipfw2.jpg) ### ip6tables The introduction of the next-generation Internet Protocol, called IPv6, expands beyond the 32-bit address limit of IPv4 \(or IP\). IPv6 supports 128-bit addresses and, as such, carrier networks that are IPv6 aware are able to address a larger number of routable addresses than IPv4. Linux supports IPv6 firewall rules using the Netfilter 6 subsystem and the`ip6tables`command. For example, SSH connections on a IPv6-aware network server can be enabled with the following rule: ```text ip6tables -A INPUT -i eth0 -p tcp -s 3ffe:ffff:100::1/128 --dport 22 -j ACCEPT ``` ### NAT IP Forwarding Private \(None-Routable\) Networks have been set aside for use inside corporate networks.They are not able to communicate directly with internet hosts and require a firewall or similar device to translate Network Address. NAT \(Network Address Translation\) is used to originate IP to a public IP that can forward the traffic on their behalf. Ranges are: * 10.0.0.0 to 10.255.255.255 * 172.16.0.0 to 172.31.255.255 * 192.168.0.0 to 192.168.255.255 ![](.gitbook/assets/route-linuxnatrouter.png) How linux does that ? Linux uses Connection tracking, Connection tracking is a mechanism done by Linux machine's to keep track of TCP connections that are going out and coming inside. This connection tracking mechanism enables Linux machine's to accurately send packet's which are NATed to the exact internal machines, who initiated the connection. connection tracking tables consists of the following things. * Ip addresses * Protocols * Port number's * Status of the connection With the help of that table, stateful firewall can filter out traffic based on the status of the connection, Do NAT and many other stuff. There are two different types of NAT: * **Source NAT\(SNAT\)** * **Destination NAT \(DNAT\)** ### Masqueradeand SNAT in Linux This is the most commonly used NAT. SNAT stands for Source Network Address Translation. It rewrites only the source address of the packets while nating. In the previously shown example of NAT many private ip addresses of the range 192.168.0.0/24 gets translated to the public source address of the Linux NAT router\(4.4.7.23\). In this case the internal network hosts, with private ip addresses can reach the internet with the help of SNAT. But hosts from the internet cannot reach those internal hosts directly \(It will only reach the internal hosts, if the source was NATed to the Linux router's public IP address.\) In other words, connection initiated by the internal hosts to the internet will only be fulfilled\(not the reverse\). #### Static SNAT vs DynamicSNAT Even SNAT can be classified into different types based on the translation it does. For example if many internal private IP addresses gets translated to one public ip address assigned to the Linux router, then its called as a**Static SNAT**.If many internal private IP addresses gets translated to many different public IP addresses assigned to the Linux router, then its called as a**Dynamic SNAT.** Please note that If we are using masquerading instead of SNAT, then we will be unable to specify the outgoing ip address. It will use the default IP address assigned to the outgoing interface. ### What is DNAT? In the above shown example of SNAT, the connection was initiated by the host inside the internal network. What if a host on the internet needs to initiate the connection. In that case we need to design our Linux router in such a way that traffic from internet to a particular public IP address on the router will be forwarded to one particular private IP address. Such kind of a configuration is called as DNAT, or destination NAT. It is called a destination NAT because the first address rewriting done by the router is for destination address. Lets make our hands dirty and do some configurations. Here we have two Ubuntu machine, and we want to give internet access to Ubuntu2 using Ubuntu1. ![](.gitbook/assets/route-nat.jpg) First we have to configure kernel to let forward traffic trough this machine: ```text root@server1:~# cat /proc/sys/net/ipv4/ip_forward 0 root@server1:~# echo "1" > /proc/sys/net/ipv4/ip_forward root@server1:~# cat /proc/sys/net/ipv4/ip_forward 1 ``` now lets MASQUERADE: ```text root@server1:~# iptables --table nat --append POSTROUTING --out-interface ens33 -j MASQUERADE root@server1:~# iptables --append FORWARD --in-interface ens38 -j ACCEPT ``` and do not forget if we don't specify any tables by default it appends to "filter" table. Okey lets now checks Ubntu2: ```text root@server2:~# ip a s 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether 00:0c:29:40:b1:ca brd ff:ff:ff:ff:ff:ff inet 192.168.5.129/24 brd 192.168.5.255 scope global ens33 valid_lft forever preferred_lft forever inet6 fe80::47a6:91f0:8edb:9a49/64 scope link valid_lft forever preferred_lft forever root@server2:~# ping 8.8.8.8 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=127 time=161 ms 64 bytes from 8.8.8.8: icmp_seq=2 ttl=127 time=179 ms ^C --- 8.8.8.8 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 1002ms rtt min/avg/max/mdev = 161.904/170.784/179.664/8.880 ms ``` That is all.
Java
UTF-8
154
1.609375
2
[]
no_license
package fr.akharroub.basededonnes.business; import java.util.ArrayList; public interface IAccueilBusiness { public ArrayList<String> getvilles(); }
Java
UTF-8
765
2.265625
2
[]
no_license
package com.example.portfolioapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; public class SplashActivity extends Activity implements android.view.View.OnClickListener { ImageButton gotoMainBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); gotoMainBtn = (ImageButton) findViewById(R.id.gotoMainBtn); } @Override public void onClick(View v) { if(v==gotoMainBtn){ System.out.println("gotoMainBtn pressed"); Intent myintent = new Intent(this, MainActivity.class); startActivity(myintent); } } }
JavaScript
UTF-8
856
2.640625
3
[ "MIT" ]
permissive
export default (state = [], action) => { switch (action.type) { case 'FETCH_CONTRACTS': return action.allContracts case 'USER_LOGOUT': const allContracts = [] return allContracts case 'CREATE_CONTRACT': let contract = action.payload.contract if (contract !== undefined) { contract["url"] = action.payload.url return [...state, contract] } else { return state } case 'ADD_URL_TO_CONTRACT': let filteredContracts = [...state].filter( contract => contract.blockchain_id !== action.payload.contract.blockchain_id) let findContract = [...state].find(contract => action.payload.contract.blockchain_id === contract.blockchain_id) findContract['url'] = action.payload.url return [...filteredContracts, findContract] default: return state } }
C#
UTF-8
1,699
3.109375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.IO; namespace ProjectStart { public class StructureTemplateManager { List<StructureTemplate> structureTemplates; static string templatesPath; public static string TemplatesPath { get { return templatesPath; } } static StructureTemplateManager instance; public static StructureTemplateManager Manager { get { return instance; } } public StructureTemplateManager() { instance = this; templatesPath = Path.Combine(Environment.CurrentDirectory, "Data\\Templates\\Structure"); structureTemplates = new List<StructureTemplate>(); } public void Add(StructureTemplate template) { if (!structureTemplates.Contains(template)) structureTemplates.Add(template); } public void Remove(StructureTemplate template) { if (structureTemplates.Contains(template)) structureTemplates.Remove(template); } public StructureTemplate Find(string name) { foreach (StructureTemplate template in structureTemplates) { if (template.Name == name) return template; } return null; } public string[] GetTemplateNames() { List<string> names = new List<string>(); foreach (StructureTemplate template in structureTemplates) { names.Add(template.Name); } return names.ToArray(); } } }
Rust
UTF-8
3,408
3.625
4
[ "MIT" ]
permissive
//! The `Mammoth` structure contains the general configuration for Mammoth, such as the location of //! the modules and the log settings. use std::path::{Path, PathBuf}; use crate::diagnostics::{Logger, PathValidator, PathValidatorKind, Validator}; use crate::error::Error; use crate::error::severity::Severity; /// Structure that defines the general configuration for the Mammoth application. #[derive(Clone, Debug, Deserialize)] pub struct Mammoth { mods_dir: Option<PathBuf>, log_file: Option<PathBuf>, log_severity: Option<Severity> } impl Mammoth { /// Creates a new, empty `Mammoth` structure. pub fn new() -> Mammoth { Mammoth { mods_dir: None, log_file: None, log_severity: None } } /// Obtains the modules directory. pub fn mods_dir(&self) -> Option<&Path> { if let Some(ref path) = self.mods_dir { Some(path.as_path()) } else { None } } /// Obtains the log file path. pub fn log_file(&self) -> Option<&Path> { if let Some(ref path) = self.log_file { Some(path.as_path()) } else { None } } /// Obtains the log severity. pub fn log_severity(&self) -> Option<Severity> { self.log_severity } /// Sets the modules directory. pub fn set_mods_dir<P>(&mut self, path: P) where P: AsRef<Path> { self.mods_dir = Some(path.as_ref().to_path_buf()); } /// Sets the log file path. pub fn set_log_file<P>(&mut self, path: P) where P: AsRef<Path> { self.log_file = Some(path.as_ref().to_path_buf()); } /// Sets the log severity. pub fn set_log_severity(&mut self, severity: Severity) { self.log_severity = Some(severity); } } impl Validator<Mammoth> for () { fn validate(&self, logger: &mut Logger, item: &Mammoth) -> Result<(), Error> { if let Some(mods_dir) = item.mods_dir() { PathValidator(Severity::Error, PathValidatorKind::ExistingDirectory) .validate(logger, &mods_dir)?; } if let Some(log_file) = item.log_file() { PathValidator(Severity::Error, PathValidatorKind::FilePath) .validate(logger, &log_file)?; } Ok(()) } } #[cfg(test)] mod test { use std::path::Path; use crate::config::Mammoth; use crate::error::severity::Severity; #[test] /// Generic property test. fn test_generic() { let mut mammoth = Mammoth::new(); assert!(mammoth.mods_dir().is_none()); assert!(mammoth.log_file().is_none()); assert!(mammoth.log_severity().is_none()); mammoth.set_mods_dir("./mods/"); assert_eq!(mammoth.mods_dir().unwrap(), Path::new("./mods/")); assert!(mammoth.log_file().is_none()); assert!(mammoth.log_severity().is_none()); mammoth.set_log_file("mammoth.log"); assert_eq!(mammoth.mods_dir().unwrap(), Path::new("./mods/")); assert_eq!(mammoth.log_file().unwrap(), Path::new("mammoth.log")); assert!(mammoth.log_severity().is_none()); mammoth.set_log_severity(Severity::Warning); assert_eq!(mammoth.mods_dir().unwrap(), Path::new("./mods/")); assert_eq!(mammoth.log_file().unwrap(), Path::new("mammoth.log")); assert_eq!(mammoth.log_severity().unwrap(), Severity::Warning); } }
C++
UTF-8
536
3.328125
3
[]
no_license
#ifndef AWEAPON_H #define AWEAPON_H #include <string> #include <iostream> class AWeapon { protected: std::string name; int damage; int APCost; public: AWeapon();//default AWeapon(std::string const & name, int apcost, int damage); AWeapon(AWeapon const & src);//copy AWeapon & operator=(AWeapon const & rhs);//assignation operator virtual ~AWeapon();//destructor std::string const & getName() const; int getAPCost() const; int getDamage() const; virtual void attack() const = 0; }; #endif
Python
UTF-8
186
3.0625
3
[]
no_license
#!/usr/local/bin/python3.3 # -*- coding: utf-8 -*- """ 转换并同时计算数据 """ nums = [1, 2, 3, 4, 5] s = sum((x * x for x in nums)) s = sum(x * x for x in nums) # 更优雅
Markdown
UTF-8
6,548
3.890625
4
[]
no_license
# Storm the Form Forms are handled a little bit differently in React. This is because, unlike most HTML elements, forms inputs have their own internal state stored in the DOM. Ideally we want a single-source of truth in React. We also want to be able to use the input values without having to go into the DOM and get them. ### Controlled components Generally we use a technique called "controlled components" to keep our input state in React instead of the DOM. This involves maintaining an entry in state for each input your form renders: ```jsx class Form extends React.Component { state = { input: '', }; render() { return ( <form> <label htmlFor="name">Name:</label> <input type="text" id="name" value={this.state.input} /> <button type="submit">Submit</button> </form> ); } } ``` We set the `value` prop of our `<input />` to be the correct entry in our state. Unfortunately this means the input is unusable, as we haven't provided any way for that state to change. This is the difference with controlled inputs—everything happens within React/JavaScript. The input is just reflecting our state. ```jsx class Form extends React.Component { state = { input: '', }; handleChange = event => { const value = event.target.value; this.setState({ input: value }); }; render() { return ( <form> <label htmlFor="name">Name:</label> <input type="text" id="name" value={this.state.input} onChange={this.handleChange} /> <button type="submit">Submit</button> </form> ); } } ``` Now our input has an `onChange` event handler that will set the state to the new value every time the user types into the field. #### Different input types Certain types of inputs have to be handled slightly differently. ##### `textarea` `textarea`s usually defines the text inside via its children. React uses a `value` prop to make it consistent with other inputs. ##### `select` A `select` usually contains several `option` elements, of which one will have the `selected` attribute. This is the option shown in the `select` in its unexpanded state. In React this is again controlled with a `value` prop on the parent `select`. This makes it easier to control as you only have to update it in one place. ##### Checkboxes and radios These inputs are controlled with a `checked` prop instead of `value`. `checked` can either be true or false. It's worth remembering that groups of radios should only be able to have a single option selected, so you should have a single entry in state for each group: ```jsx class Form extends React.Component { state = { radioSelected: 'phone', }; handleChange = event => { const value = event.target.value; this.setState({ radioSelected: value }); }; render() { return ( <form> <label htmlFor="phone">Phone</label> <input type="radio" id="phone" name="contact" value="phone" checked={this.state.radioSelected === 'phone'} onChange={this.handleChange} /> <label htmlFor="email">Email</label> <input type="radio" id="email" name="contact" value="email" checked={this.state.radioSelected === 'email'} onChange={this.handleChange} /> <label htmlFor="post">Post</label> <input type="radio" id="post" name="contact" value="post" checked={this.state.radioSelected === 'post'} onChange={this.handleChange} /> <button type="submit">Submit</button> </form> ); } } ``` #### Multiple inputs If we have more than one input it can get annoying writing event handlers for each. It's easier to use the `name` attribute to know which property in state should be updated. We also need to check whether the input is a checkbox, so we update the right prop: ```jsx class Form extends React.Component { state = { name: '', email: '', consent: false, }; handleChange = event => { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; this.setState({ [target.name]: value }); }; render() { return ( <form> <label htmlFor="name">Name:</label> <input type="text" id="name" name="name" value={this.state.name} onChange={this.handleChange} /> <label htmlFor="email">Email:</label> <input type="email" id="email" name="email" value={this.state.email} onChange={this.handleChange} /> <label htmlFor="consent">Can we email you spam?</label> <input type="checkbox" id="consent" name="consent" checked={this.state.consent} onChange={this.handleChange} /> <button type="submit">Submit</button> </form> ); } } ``` ### Form submission Forms take an `onSubmit` event handler. It's much easier to get our input data now that it's all in state—we just have to grab it and do what we want with it. Don't forget to reset everything after you submit! ```jsx class Form extends React.Component { state = { name: '', email: '', consent: false, } handleChange = event => {...} handleSubmit = event => { event.preventDefault(); const data = JSON.stringify(this.state); fetch('https://myserver.com/submit-form', { method: 'post', body: data, }); this.setState({ name: '', email: '', consent: false }); } render() { return ( <form onSubmit={this.handleSubmit}> ... </form> ); } } ``` #### Final note: You may have noticed we've been using `htmlFor` on our labels, instead of `for`. This is another JSX difference you just have to remember—`for` is a reserved word in JS so we can't use it. ## Exercise 1. Open `index.html` in your editor and browser. 2. Open your browser console and then play around with the inputs. See what values get logged. 3. Try removing the `onChange` prop from an input. See how you can't type anything anymore? 4. Try logging different things, like the actual events—you'll see that React events are a bit different to built-in DOM events. ## Further Reading - [Forms | React Docs](https://reactjs.org/docs/forms.html)
Python
UTF-8
1,484
2.8125
3
[]
no_license
from flask import Flask, request, redirect from pymongo import MongoClient import logging logs=logging.getLogger(__name__) app = Flask(__name__) @app.route('/test') def test(): return "Test application" @app.route('/') def alpha(): # Module to Obtain the paramter from the Database. if 'key' in request.args: key = request.args.get('key') obj_id = getRecord(key) link = obj_id.get('value') return redirect("https://"+link) else: return "No input specified" @app.route('/add') def beta(): # Module to load the parameter to the Database. if 'key' in request.args: key = request.args.get('key') value = request.args.get('value') obj_id = addRecord(key, value) return "Value Added to the Database : " + str(obj_id) else: return "No input specified" def addRecord(name, link): client = MongoClient("mongodb://golink_mongodb_2:27017") logs.debug(client) db = client.Test addStr = {"key": name ,"value": link} print '------------------------' print addStr result = db.godataset.insert_one(addStr) client.close() return result.inserted_id def getRecord(name): client = MongoClient("mongodb://golink_mongodb_2:27017") logs.debug(client) db = client.Test findStr = {"key":name} result = db.godataset.find_one(findStr) client.close() return result if __name__=='__main__': app.run(debug=True, port=3134)
Python
UTF-8
39,786
2.546875
3
[]
no_license
#FUNCIONES from maya import cmds from maya.api import OpenMaya def twoInfluencesConstraint(controler, constraint, reverse = False): #FUNCION QUE CONECTA LAS DOBLES INFLUENCIAS DE UN CONSTRAINT AL CONTROL QUE LO GESTIONA name = controler.split('.')[1] side = controler.split('_')[1] name_reverse = '{}_{}_rev'.format(name,side) rever = cmds.shadingNode('reverse', n=name_reverse, au=True) cmds.connectAttr(controler, '{}.inputX'.format(rever)) looking = cmds.listAttr(constraint) for attr in looking: if 'W0' == attr[-2::]: W0 = attr elif 'W1' == attr[-2::]: W1 = attr if reverse == False: cmds.connectAttr('{}.outputX'.format(rever), '{}.{}'.format(constraint, W0)) cmds.connectAttr(controler, '{}.{}'.format(constraint, W1)) else: cmds.connectAttr('{}.outputX'.format(rever), '{}.{}'.format(constraint, W1)) cmds.connectAttr(controler, '{}.{}'.format(constraint, W0)) def locCreator(name='locator', position=None, dad = None): loc = cmds.spaceLocator(n=name)[0] if position == None: pass else: locator_pos = cmds.xform(position, ws=True, t=True, q=True) cmds.xform(loc, t=locator_pos, ws=True) if dad != None: cmds.parent(loc, dad) else: pass return '{}Shape'.format(loc) #Formato Rapido de Creacion de Nofos def clampCreator(name = 'clampNode', MaxG = 0, MaxR = 0, MaxB = 0, MinG = 0, MinR = 0, MinB = 0, InputR = None, InputG = None, InputB = None): clp = cmds.shadingNode('clamp', au=True, n=name) clamp_dic = {'maxG':MaxG, 'maxR':MaxR, 'maxB':MaxB, 'minG':MinG, 'minR': MinR, 'minB': MinB, 'inputR': InputR, 'inputG': InputG, 'inputB': InputB} for element in clamp_dic: input = clamp_dic.get(element) if isinstance(input, str) == True: cmds.connectAttr(input, '{}.{}'.format(clp, element)) elif isinstance(input, int) == True: cmds.setAttr('{}.{}'.format(clp, element), input) else: pass return clp def multiplyCreator(name = 'multiplyNode', linear = True, Input1 = 1, Input2 = 1, Input1X = 0, Input1Y = 0, Input1Z = 0, Input2X = 0, Input2Y = 0, Input2Z = 0, Output = None): mult_dic = {'input1':Input1, 'input2':Input2, 'input1X':Input1X, 'input1Y':Input1Y, 'input1Z':Input1Z, 'input2X':Input2X, 'input2Y':Input2Y, 'input2Z':Input2Z} if linear == True: del mult_dic['input1X'] del mult_dic['input1Y'] del mult_dic['input1Z'] del mult_dic['input2X'] del mult_dic['input2Y'] del mult_dic['input2Z'] mult = cmds.shadingNode('multDoubleLinear', n=name, au=True) else: mult = cmds.shadingNode('multiplyDivide', n=name, au=True) del mult_dic['input1'] del mult_dic['input2'] for element in mult_dic: input = mult_dic.get(element) if isinstance(input, str) == True: cmds.connectAttr(input, '{}.{}'.format(mult, element)) elif isinstance(input, int) == True: cmds.setAttr('{}.{}'.format(mult, element), input) elif isinstance(input, float) == True: cmds.setAttr('{}.{}'.format(mult, element), input) else: pass if Output != None: cmds.connectAttr('{}.output'.format(mult), Output) else: pass return mult def divideCreator(name=None, Input1X = 1, Input1Y = 1, Input1Z = 1, Input2X = 1, Input2Y = 1, Input2Z = 1, Extraction1X = False, Extraction1Y = False, Extraction1Z = False, Extraction2X = False, Extraction2Y = False, Extraction2Z = False, OutputX = None, OutputY = None, OutputZ = None): extract_list = [[Extraction1X, 'input1X'],[Extraction1Y, 'input1Y'],[Extraction1Z, 'input1Z'], [Extraction2X, 'input2X'],[Extraction2Y, 'input2Y'],[Extraction2Z, 'input2Z']] div_dic = {'input1X':Input1X, 'input1Y':Input1Y, 'input1Z':Input1Z, 'input2X':Input2X, 'input2Y':Input2Y, 'input2Z':Input2Z} div = cmds.shadingNode('multiplyDivide', n=name, au=True) cmds.setAttr('{}.operation'.format(div), 2) for element in extract_list: if element[0] == True: number = cmds.getAttr(div_dic.get(element[1])) del div_dic[element[1]] cmds.setAttr('{}.{}'.format(div, element[1]), number) else: pass for element in div_dic: input = div_dic.get(element) if isinstance(input, str) == True: cmds.connectAttr(input, '{}.{}'.format(div, element)) elif isinstance(input, int) == True: cmds.setAttr('{}.{}'.format(div, element), input) elif isinstance(input, float) == True: cmds.setAttr('{}.{}'.format(div, element), input) else: pass div_dic_outs = {'outputX':OutputX, 'outputY':OutputY, 'outputZ':OutputZ} for outs in div_dic_outs: output = div_dic_outs.get(outs) if isinstance(output, str) == True: cmds.connectAttr('{}.{}'.format(div, output), outs) else: pass return div def substractCreator(name=None, InputX0 = 0, InputX1= 0, InputX2 = 0, InputY0 = 0, InputY1 = 0, InputY2 = 0, OutputX = None, OutputY = None): subs_dic = {'input2D[0].input2Dx':InputX0, 'input2D[1].input2Dx':InputX1, 'input2D[2].input2Dx':InputX2, 'input2D[0].input2Dy':InputY0, 'input2D[1].input2Dy':InputY1, 'input2D[2].input2Dy':InputY2} subs = cmds.shadingNode('plusMinusAverage', n=name, au=True) cmds.setAttr('{}.operation'.format(subs), 2) for element in subs_dic: input = subs_dic.get(element) if isinstance(input, str) == True: cmds.connectAttr(input, '{}.{}'.format(subs, element)) elif isinstance(input, int) == True: cmds.setAttr('{}.{}'.format(subs, element), input) if isinstance(OutputX, str) == True: cmds.connectAttr('{}.output2D.output2Dx'.format(subs), OutputX) else: pass if isinstance(OutputY, str) == True: cmds.connectAttr('{}.output2D.output2Dy'.format(subs), OutputY) else: pass return subs def plusCreator(name=None, InputX0 = 0, InputX1= 0, InputX2 = 0, InputY0 = 0, InputY1 = 0, InputY2 = 0, OutputX = None, OutputY = None): plus_dic = {'input2D[0].input2Dx':InputX0, 'input2D[1].input2Dx':InputX1, 'input2D[2].input2Dx':InputX2, 'input2D[0].input2Dy':InputY0, 'input2D[1].input2Dy':InputY1, 'input2D[2].input2Dy':InputY2} plus = cmds.shadingNode('plusMinusAverage', n=name, au=True) for element in plus_dic: input = plus_dic.get(element) if isinstance(input, str) == True: cmds.connectAttr(input, '{}.{}'.format(plus, element)) elif isinstance(input, int) == True: cmds.setAttr('{}.{}'.format(plus, element), input) if isinstance(OutputX, str) == True: cmds.connectAttr('{}.output2D.output2Dx'.format(plus), OutputX) else: pass if isinstance(OutputY, str) == True: cmds.connectAttr('{}.output2D.output2Dy'.format(plus), OutputY) else: pass return plus def distanceCreator(name = None, Input1 = None, Input2 = None): if name == None: name = '{}_{}_distanceBetween'.format(Input1.split('_')[0], Input1.split('_')[1]) else: pass dB = cmds.shadingNode('distanceBetween', n=name, au=True) if Input1 != None: cmds.connectAttr(Input1, '{}.point1'.format(dB)) else: pass if Input1 != None: cmds.connectAttr(Input2, '{}.point2'.format(dB)) else: pass return dB def blendColorsCreator(Name = 'blendColor', Blender = None, Color1R = None, Color1G = None, Color1B = None, Color2R = None, Color2G = None, Color2B = None): blend_dic = {'blender':Blender, 'color1R':Color1R, 'color1G':Color1G, 'color1B':Color1B, 'color2R':Color2R, 'color2G':Color2G, 'color2B':Color2B} blen = cmds.shadingNode('blendColors', au=True, n=Name) for element in blend_dic: input = blend_dic.get(element) if isinstance(input, str) == True: cmds.connectAttr(input, '{}.{}'.format(blen, element)) elif isinstance(input, int) == True: cmds.setAttr('{}.{}'.format(blen, element), input) else: pass return blen def curveInfoCreator(Name = 'curveInfo', Input = None, Length = None, Output = None): iC = cmds.shadingNode('curveInfo', n=Name, au=True) cmds.connectAttr(Input, '{}.inputCurve'.format(iC)) arcLength = cmds.getAttr('{}.arcLength'.format(iC)) if Length: cmds.setAttr(Length, arcLength) else: pass if Output != None: cmds.connectAttr('{}.arcLength'.format(iC), Output) else: pass return iC #Blend function def clusterCreator(Name = 'None', CV1 = None, CV2 = None, Double = False): cmds.select(CV1) if Double == True: cmds.select(CV2, add=True) clust = cmds.cluster(n=Name) cmds.select(cl=True) return clust def blendSystem(CurveU = None, CurveL = None, ClusterName = 'ClusterBlendSystem', upJnt = None, middleJnt = None, upBlend = None, middleBlend = None, lowBlend = None): upName=upBlend[:-6] lowName = lowBlend[:-6] midName = middleBlend[:-6] side= upBlend[-5] upOff = '{}Ctr_{}_offset'.format(upName, side) midOff= '{}Ctr_{}_offset'.format(midName, side) lowOff = '{}Ctr_{}_offset'.format(lowName, side) CV0U = ['{}.cv[0]'.format(CurveU)] CV1U = ['{}.cv[1]'.format(CurveU)] CV2U = ['{}.cv[2]'.format(CurveU)] CV3U = ['{}.cv[3]'.format(CurveU)] CV0L = ['{}.cv[0]'.format(CurveL)] CV1L = ['{}.cv[1]'.format(CurveL)] CV2L = ['{}.cv[2]'.format(CurveL)] CV3L = ['{}.cv[3]'.format(CurveL)] A = clusterCreator( Name='{}A'.format(ClusterName), CV1 = CV0U) cmds.parent(A, upJnt) B = clusterCreator( Name = '{}B'.format(ClusterName), Double = True, CV1 = CV1U, CV2 = CV2U) clusterMatrix = cmds.xform(B, q=1, ws=1, rp=1) cmds.xform(upOff, t=clusterMatrix, ws=True) cmds.parent(B, upBlend) cmds.parent(upOff, upJnt) C = clusterCreator( Name='{}C'.format(ClusterName), Double = True, CV1 = CV3U, CV2 = CV0L) clusterMatrix = cmds.xform(C, q=1, ws=1, rp=1) cmds.xform(midOff, t=clusterMatrix, ws=True) cmds.parent(C, middleBlend) cmds.parentConstraint(upJnt, middleJnt, midOff, mo=True) D = clusterCreator( Name='{}D'.format(ClusterName), Double = True, CV1 = CV1L, CV2 = CV2L) clusterMatrix = cmds.xform(D, q=1, ws=1, rp=1) cmds.xform(lowOff, t=clusterMatrix, ws=True) cmds.parent(D, lowBlend) cmds.parent(lowOff, middleJnt) E = clusterCreator( Name='{}E'.format(ClusterName), CV1 = CV3L) cmds.parent(E, middleJnt) def chainJoint(cantidad, nombre, lado, chin, radio, ini, fin): inicio = '{}_loc_{}_autorig'.format(ini, lado) fin = '{}_loc_{}_autorig'.format(fin, lado) start_point = cmds.xform(inicio, q=True, t=True, ws=True) end_point = cmds.xform(fin, q=True, t=True, ws=True) vector_sta = OpenMaya.MVector(start_point) vector_end = OpenMaya.MVector(end_point) i = 0 all_joints = [] for num in range(cantidad): name = '{}{}_{}_skn'.format(nombre, i, lado) nameEnd = '{}{}_{}_End'.format(nombre, i, lado) dif_point = vector_end-vector_sta offset = 1.0/(cantidad-1) new_point=dif_point*offset final_point = vector_sta + new_point mid_pos=dif_point*(offset*num) final_pos=vector_sta+mid_pos jnt=cmds.joint(n=name, p=list(final_pos), rad=radio) all_joints.append(jnt) if i != 0: cmds.joint(all_joints[i-1],e=True,zso=True,oj='xyz',sao='yup', rad=radio) i += 1 if chin==False: cmds.select(cl=1) if i == cantidad: jnt = cmds.rename(jnt, nameEnd) all_joints[-1] = jnt break return all_joints def posToControl(offset, part = None, X = None, Y = None, Z = None): if part == None: part = offset.split('_')[0] lado = offset.split('_')[1] jnt_pos = '{}_{}_jnt'.format(part, lado) cmds.parent(offset, jnt_pos) cmds.setAttr('{}.rx'.format(offset), X) cmds.setAttr('{}.ry'.format(offset), Y) cmds.setAttr('{}.rz'.format(offset), Z) for axis in 'xyz': cmds.setAttr('{}.t{}'.format(offset, axis), 0) cmds.parent(offset, 'general_c_ctr') def poleLocation(): from maya import cmds , OpenMaya import math for side in 'rl': start = cmds.xform('hip_{}_jnt'.format(side) ,q= 1 ,ws = 1,t =1 ) mid = cmds.xform('knee_{}_jnt'.format(side) ,q= 1 ,ws = 1,t =1 ) end = cmds.xform('legEnd_{}_jnt'.format(side) ,q= 1 ,ws = 1,t =1 ) startV = OpenMaya.MVector(start[0] ,start[1],start[2]) midV = OpenMaya.MVector(mid[0] ,mid[1],mid[2]) endV = OpenMaya.MVector(end[0] ,end[1],end[2]) startEnd = endV - startV startMid = midV - startV dotP = startMid * startEnd proj = float(dotP) / float(startEnd.length()) startEndN = startEnd.normal() projV = startEndN * proj arrowV = startMid - projV arrowV*= 0.5 finalV = arrowV + midV cross1 = startEnd ^ startMid cross1.normalize() cross2 = cross1 ^ arrowV cross2.normalize() arrowV.normalize() matrixV = [arrowV.x , arrowV.y , arrowV.z , 0 , cross1.x ,cross1.y , cross1.z , 0 , cross2.x , cross2.y , cross2.z , 0, 0,0,0,1] matrixM = OpenMaya.MMatrix() OpenMaya.MScriptUtil.createMatrixFromList(matrixV , matrixM) matrixFn = OpenMaya.MTransformationMatrix(matrixM) rot = matrixFn.eulerRotation() loc = 'legPoleCtr_{}_offset'.format(side) cmds.xform(loc , ws =1 , t= (finalV.x , finalV.y ,finalV.z)) cmds.xform ( loc , ws = 1 , rotation = ((rot.x/math.pi*180.0), (rot.y/math.pi*180.0), (rot.z/math.pi*180.0))) ############################################FACIAL FUNCTIONS AUTORIG#################################################### def chainJointFacial(cantidad, nombre, chin, ini, fin): inicio = ini fin = fin start_point = cmds.xform(inicio, q=True, t=True, ws=True) end_point = cmds.xform(fin, q=True, t=True, ws=True) vector_sta = OpenMaya.MVector(start_point) vector_end = OpenMaya.MVector(end_point) i = 0 all_joints = [] for num in range(cantidad): name = '{}{}_c_skn'.format(nombre, i) nameEnd = '{}{}_c_End'.format(nombre, i) dif_point = vector_end-vector_sta offset = 1.0/(cantidad-1) new_point=dif_point*offset final_point = vector_sta + new_point mid_pos=dif_point*(offset*num) final_pos=vector_sta+mid_pos jnt=cmds.joint(n=name, p=list(final_pos)) all_joints.append(jnt) if i != 0: cmds.joint(all_joints[i-1],e=True,zso=True,oj='xyz',sao='yup') i += 1 if chin==False: cmds.select(cl=1) if i == cantidad: jnt = cmds.rename(jnt, nameEnd) all_joints[-1] = jnt break return all_joints def createControlJoint(control_name = None, side = None, jnt_usage = 'skn', position_loc = None, ctr_parent_to = None, jnt_parent_to = None): #Crear hueso jnt_name = '{}_{}_{}'.format(control_name, side, jnt_usage) jnt = cmds.createNode('joint', n= jnt_name) jnt_zero_name = '{}{}_{}_zero'.format(control_name, jnt_usage.capitalize(), side) jnt_zero = cmds.createNode('transform', n=jnt_zero_name) cmds.parent(jnt, jnt_zero)[0] #Crear control ctr_name = '{}_{}_ctr'.format(control_name, side) ctr = cmds.circle(name= ctr_name, constructionHistory=False) ctr_zero_name = '{}Ctr_{}_zero'.format(control_name, side) ctr_zero = cmds.createNode('transform', name=ctr_zero_name) cmds.parent(ctr, ctr_zero)[0] #Engarzar Control y Hueso for attr in 'trs': for axis in 'xyz': cmds.connectAttr('{}.{}{}'.format(ctr[0], attr, axis), '{}.{}{}'.format(jnt, attr, axis), force = True) #Reposicionar zero position_loc_matrix = cmds.xform(position_loc, query=True, matrix=True, worldSpace=True) cmds.xform(jnt_zero, matrix=position_loc_matrix) cmds.xform(ctr_zero, matrix=position_loc_matrix) #Parent elements if ctr_parent_to: ctr_zero = cmds.parent(ctr_zero, ctr_parent_to)[0] if jnt_parent_to: jnt_zero = cmds.parent(jnt_zero, jnt_parent_to)[0] return [ctr_zero, jnt_zero, ctr[0], jnt] def createHold(n=None, side=None, skin = 'skn'): zeroName = 'facial{}Hold{}_{}_zero'.format(n, skin.capitalize(), side) holdName = 'facial{}Hold_{}_{}'.format(n, side, skin) grp = cmds.group(em=True, n=zeroName) jnt = cmds.joint(n=holdName) return grp def duplicateFlip(element=None, descendent=True, side = 'r', dad=None, axis= 'x'): null = cmds.group(em=True) first = element.split('_')[0] third = element.split('_')[2] name = '{}_{}_{}'.format(first, side, third) duplic = cmds.duplicate(element, name, rc=True) duplic = cmds.rename(duplic[0], name) if descendent == True: relatives = cmds.listRelatives(duplic) for relative in relatives: first = relative.split('_')[0] third = relative.split('_')[2] third = third.replace(third[-1], '') name = '{}_{}_{}'.format(first, side, third) cmds.rename(relative, name) cmds.parent(duplic, null) cmds.setAttr('{}.s{}'.format(null, axis), -1) if dad: cmds.parent(duplic, dad) else: cmds.parent(duplic, w=True) cmds.delete(null) result = cmds.listRelatives(duplic, ad=True, s=False) return result def conElement(source=None, subject = None): for attr in 'trs': for axis in 'xyz': cmds.connectAttr('{}.{}{}'.format(source, attr, axis), '{}.{}{}'.format(subject, attr, axis), force = True) def createNurb(uNumber=5, vNumber=5, side=None, name=None, mX=0, mY=0, mZ=0): name= '{}_{}_nurb'.format(name, side) try: crv = cmds.polyToCurve(n='deletableCurve', form=2, degree=3, conformToSmoothMeshPreview=1)[0] degs = cmds.getAttr( '{}.degree'.format(crv) ) spans = cmds.getAttr( '{}.spans'.format(crv) ) cvs = degs+spans # #crv1 = cmds.duplicate(crv, n='deletableCurve1')[0] #cmds.select('{}.cv[0:{}]'.format(crv1, cvs)) #cmds.move(mX, mY, mZ, r=True, os=True, wd=True) #crv2 = cmds.duplicate(crv, n='deletableCurve2')[0] #cmds.select('{}.cv[0:{}]'.format(crv2, cvs)) #mX= mX*(-1) #mY= mY*(-1) #mZ= mZ*(-1) #cmds.move(mX, mY, mZ, r=True, os=True, wd=True) mnX= mX*(-1) offst_curve1 = cmds.offsetCurve(crv, d=mX)[0] offst_curve2 = cmds.offsetCurve(crv, d=mnX)[0] surf = cmds.loft(offst_curve1, offst_curve2, ch=1, u=1, c=0, ar=1, d=3, ss=1, rn=0, po=0, rsn=True, n=name)[0] cmds.rebuildSurface(surf, ch=1, rpo=1, rt=0, end=1, kr=0, kcp=0, kc=0, su=uNumber, du=3, sv=vNumber, dv=3, tol=0.01, fr=0, dir=2) cmds.delete(surf, ch=True) for c in [crv, offst_curve1, offst_curve2]: cmds.delete(c) except: cmds.nurbsPlane(n=name, ax=(0,1,0), w=True, lr= True, d = 3, u = uNumber, v = vNumber, ch=1) def referenceLocators(cuantity = 1, reflection = True, between = 0): reflectionLocators = [] if cuantity == 1: loc = cmds.spaceLocator(n = 'generatingLocator')[0] if reflection == True: flip = cmds.group(em=True, n='locReferenceReflection_builder') ref = cmds.spaceLocator(n = 'reflectLocator')[0] cmds.parent(ref, flip) for axis in 'xyz': for trs in 'trs': cmds.connectAttr('{}.{}{}'.format(loc, trs, axis), '{}.{}{}'.format(ref, trs, axis)) cmds.setAttr('{}.sx'.format(flip), -1) return loc elif cuantity > 1: referencedLocators = [] for c in range(cuantity): loc = cmds.spaceLocator(n = 'generatingLocator{}'.format(c))[0] referencedLocators.append(loc) reflectionLocators.append(loc) if between > 0: i = 0 while len(referencedLocators) != 0: value = float(1)/(between+1) for number in range(between): value1 = value * (number+1) value2 = 1-value1 influence1 = referencedLocators[0] influence2 = referencedLocators[1] bet = cmds.spaceLocator(n='betweenLocator{}'.format(i)) pC = cmds.parentConstraint(influence1, influence2, bet)[0] cmds.setAttr('{}.{}W0'.format(pC, influence1), value1) cmds.setAttr('{}.{}W1'.format(pC, influence2), value2) i += 1 referencedLocators.remove(referencedLocators[0]) if len(referencedLocators) == 1: break if reflection == True: flip = cmds.group(em=True, n='locReferenceReflection_builder') for locator in reflectionLocators: reverse = cmds.duplicate(locator, n='reverseLocator') cmds.parent(reverse, flip) for axis in 'xyz': for trs in 'trs': cmds.connectAttr('{}.{}{}'.format(locator, trs, axis), '{}.{}{}'.format(reverse[0], trs, axis)) cmds.setAttr('{}.sx'.format(flip), -1) def makeRibbon(nurbs = '____nurb', system_name = 'brows'): vertex_list = cmds.ls(flatten = True, orderedSelection=True) fol_number = len(vertex_list) #vertex_list = [u'HeadBrows_c_geo.vtx[334]', u'HeadBrows_c_geo.vtx[335]', u'HeadBrows_c_geo.vtx[337]', u'HeadBrows_c_geo.vtx[341]', u'HeadBrows_c_geo.vtx[342]', u'HeadBrows_c_geo.vtx[344]', u'HeadBrows_c_geo.vtx[346]', u'HeadBrows_c_geo.vtx[348]', u'HeadBrows_c_geo.vtx[350]', u'HeadBrows_c_geo.vtx[352]', u'HeadBrows_c_geo.vtx[359]', u'HeadBrows_c_geo.vtx[360]', u'HeadBrows_c_geo.vtx[522]', u'HeadBrows_c_geo.vtx[1693]', u'HeadBrows_c_geo.vtx[1695]', u'HeadBrows_c_geo.vtx[1697]', u'HeadBrows_c_geo.vtx[1700]', u'HeadBrows_c_geo.vtx[1701]', u'HeadBrows_c_geo.vtx[1703]', u'HeadBrows_c_geo.vtx[1706]', u'HeadBrows_c_geo.vtx[1708]', u'HeadBrows_c_geo.vtx[1710]', u'HeadBrows_c_geo.vtx[1712]', u'HeadBrows_c_geo.vtx[1719]', u'HeadBrows_c_geo.vtx[1875]', u'HeadBrows_c_geo.vtx[3616]', u'HeadBrows_c_geo.vtx[3617]'] # Recover Vertex List vertex_list_ordered = [] vertex_list_disordered = vertex_list[::] vertex_list_disordered_x_positions = [] for vtx in vertex_list_disordered: vtx_x_position = cmds.xform(vtx, query = True, translation = True, worldSpace = True)[0] vertex_list_disordered_x_positions.append(vtx_x_position) while len(vertex_list_disordered)>0: vtx_lower_pos = 10000000000000 vtx_position_in_list = None for i, vtx_x_pos in enumerate(vertex_list_disordered_x_positions): if vtx_x_pos < vtx_lower_pos: vtx_lower_pos = vtx_x_pos vtx_position_in_list = i vertex_list_ordered.append(vertex_list_disordered[vtx_position_in_list]) vertex_list_disordered_x_positions.pop(vtx_position_in_list) vertex_list_disordered.pop(vtx_position_in_list) vertex_right_list = vertex_list_ordered[:fol_number/2][::-1] vertex_left_list = vertex_list_ordered[(fol_number/2)+1:] vertex_center = vertex_list_ordered[fol_number/2] #Create Follicles nurbs_shape = cmds.listRelatives(nurbs, shapes = True, noIntermediate = True)[0] left_follicles_list = [] right_follicle_list = [] for x in nurbs_shape: if not 'Orig' in x: nurbs_shape for side in 'lr': for i in range(0,fol_number/2): follicle_name = '{}{}_{}_fol'.format(system_name, str(i+1).zfill(2), side) follicle = cmds.createNode('transform', name = follicle_name) follicle_shape = cmds.createNode('follicle', name = '{}Shape'.format(follicle_name), parent = follicle) cmds.connectAttr('{}.local'.format(nurbs_shape), '{}.inputSurface'.format(follicle_shape), force = True) cmds.connectAttr('{}.worldMatrix[0]'.format(nurbs_shape), '{}.inputWorldMatrix'.format(follicle_shape), force = True) for axis in 'XYZ': cmds.connectAttr('{}.outTranslate{}'.format(follicle_shape, axis), '{}.translate{}'.format(follicle, axis), force = True) #cmds.connectAttr('{}.outRotate{}'.format(follicle_shape, axis), '{}.rotate{}'.format(follicle, axis), force = True) if side == 'l': left_follicles_list.append(follicle) elif side == 'r': right_follicle_list.append(follicle) center_follicle_name = '{}_c_fol'.format(system_name) center_follicle = cmds.createNode('transform', name = center_follicle_name) center_follicle_shape = cmds.createNode('follicle', name = '{}Shape'.format(center_follicle_name), parent = center_follicle) cmds.connectAttr('{}.local'.format(nurbs_shape), '{}.inputSurface'.format(center_follicle_shape), force = True) cmds.connectAttr('{}.worldMatrix[0]'.format(nurbs_shape), '{}.inputWorldMatrix'.format(center_follicle_shape), force = True) for axis in 'XYZ': cmds.connectAttr('{}.outTranslate{}'.format(center_follicle_shape, axis), '{}.translate{}'.format(center_follicle, axis), force = True) #cmds.connectAttr('{}.outRotate{}'.format(center_follicle_shape, axis), '{}.rotate{}'.format(center_follicle, axis), force = True) for i, r_fol in enumerate(right_follicle_list): temp_closestSuface = cmds.createNode('closestPointOnSurface', name = 'temp_closest') cmds.connectAttr('{}.local'.format(nurbs_shape), '{}.inputSurface'.format(temp_closestSuface), force = True) vtx_position = cmds.xform(vertex_right_list[i], query = True, translation = True, worldSpace = True) cmds.setAttr('{}.inPosition'.format(temp_closestSuface), vtx_position[0], vtx_position[1], vtx_position[2]) parameter_U = cmds.getAttr('{}.parameterU'.format(temp_closestSuface)) parameter_V = cmds.getAttr('{}.parameterV'.format(temp_closestSuface)) follicle_shape = cmds.listRelatives(r_fol, shapes = True)[0] cmds.setAttr('{}.parameterU'.format(follicle_shape), parameter_U) cmds.setAttr('{}.parameterV'.format(follicle_shape), parameter_V) cmds.delete(temp_closestSuface) for i, l_fol in enumerate(left_follicles_list): temp_closestSuface = cmds.createNode('closestPointOnSurface', name = 'temp_closest') cmds.connectAttr('{}.local'.format(nurbs_shape), '{}.inputSurface'.format(temp_closestSuface), force = True) vtx_position = cmds.xform(vertex_left_list[i], query = True, translation = True, worldSpace = True) cmds.setAttr('{}.inPosition'.format(temp_closestSuface), vtx_position[0], vtx_position[1], vtx_position[2]) parameter_U = cmds.getAttr('{}.parameterU'.format(temp_closestSuface)) parameter_V = cmds.getAttr('{}.parameterV'.format(temp_closestSuface)) follicle_shape = cmds.listRelatives(l_fol, shapes = True)[0] cmds.setAttr('{}.parameterU'.format(follicle_shape), parameter_U) cmds.setAttr('{}.parameterV'.format(follicle_shape), parameter_V) cmds.delete(temp_closestSuface) cmds.setAttr('{}.parameterU'.format(center_follicle_shape), 0.5) cmds.setAttr('{}.parameterV'.format(center_follicle_shape), 0.5) #Creacion de Huesos por foliculo follicles_list = left_follicles_list + right_follicle_list + [center_follicle] cmds.group(em=True, n='{}GeoSkin_c_grp'.format(system_name)) cmds.group(em=True, n='{}SystemFols_c_grp'.format(system_name)) for fol in follicles_list: jnt_name = '{}_{}_skn'.format(*fol.split('_')) jnt_zero_name = '{}Skn_{}_zero'.format(*fol.split('_')) jnt = cmds.createNode('joint', name = jnt_name) jnt_zero = cmds.createNode('transform', name = jnt_zero_name) jnt = cmds.parent(jnt, jnt_zero)[0] fol_matrix = cmds.xform(fol, query = True, matrix = True, worldSpace= True) cmds.xform(jnt_zero, matrix = fol_matrix, worldSpace = True) subs_node_name = '{}Fol_{}_subs'.format(*fol.split('_')) subs_node = cmds.createNode('plusMinusAverage', name = subs_node_name) cmds.setAttr('{}.operation'.format(subs_node), 2) for axis in 'xyz': cmds.connectAttr('{}.t{}'.format(fol, axis), '{}.input3D[0].input3D{}'.format(subs_node, axis), force = True) cmds.connectAttr('{}.t{}'.format(fol, axis), '{}.input3D[1].input3D{}'.format(subs_node, axis), force = True) cmds.disconnectAttr('{}.t{}'.format(fol, axis), '{}.input3D[1].input3D{}'.format(subs_node, axis)) cmds.connectAttr('{}.output3D{}'.format(subs_node, axis), '{}.t{}'.format(jnt, axis), force = True) cmds.parent(jnt_zero, '{}GeoSkin_c_grp'.format(system_name)) #Hold bullshit if cmds.objExists('facialControls_c_grp') == False: cmds.group(em=True, n= 'facialControls_c_grp') if cmds.objExists('facialRig_c_grp') == False: cmds.group(em=True, n= 'facialRig_c_grp') if cmds.objExists('facialSystems_c_grp') == False: cmds.group(em=True, n= 'facialSystems_c_grp') cmds.createNode('joint', n='{}_c_Hold'.format(system_name)) cmds.createNode('transform', name = '{}Hold_c_zero'.format(system_name)) cmds.parent('{}_c_Hold'.format(system_name), '{}Hold_c_zero'.format(system_name)) cmds.parent('{}Hold_c_zero'.format(system_name), '{}GeoSkin_c_grp'.format(system_name)) cmds.createNode('transform', n='{}SystemFols_c_grp'.format(system_name)) for fol in follicles_list: cmds.parent(fol, '{}SystemFols_c_grp'.format(system_name)) cmds.parent('{}SystemFols_c_grp'.format(system_name), 'facialSystems_c_grp') def colorKin(color=(0.027, 0.188, 0.678)): list = cmds.ls(sl=True) for i in list: cmds.color(i, rgb=color) def locOnSpot(): selection = cmds.ls(sl=True) def fg_get_center_position_of_objects(objects): # get the bounding box of selected list center_position = (0.0, 0.0, 0.0) if cmds.ls(objects): xmin, ymin, zmin, xmax, ymax, zmax = cmds.exactWorldBoundingBox(objects, ignoreInvisible=True) # look for center point center_position = (.5 * (xmax + xmin), .5 * (ymax + ymin), .5 * (zmax + zmin)) return center_position def create_default_point(point_pos = (0.0, 0.0, 0.0)): # create locator default_point = cmds.spaceLocator(position=(0.0, 0.0, 0.0), name='point_c_loc')[0] default_point_shape = cmds.listRelatives(default_point, shapes=True)[0] # lock scale and set shape size for axis in ['X', 'Y', 'Z']: cmds.setAttr('{0}.scale{1}'.format(default_point, axis), lock=True) cmds.setAttr('{0}.localScale{1}'.format(default_point_shape, axis), 0.1) cmds.setAttr('{0}.translate'.format(default_point), point_pos[0], point_pos[1], point_pos[2]) return [default_point, default_point_shape] def create_default_point_on_place(): # look for the position that we wanna create the point (if nothing is selected the point will be created at origin) selected_list = cmds.ls(sl=True, flatten=True) center_selection_pos = fg_get_center_position_of_objects(selected_list) create_default_point(point_pos = center_selection_pos) def create_multiple_default_point_on_place(): # look for the position that we wanna create the point (if nothing is selected the point will be created at origin) selected_list = cmds.ls(sl=True, flatten=True) for selected in selected_list: center_selection_pos = fg_get_center_position_of_objects(selected) create_default_point(point_pos = center_selection_pos) create_default_point_on_place() def copyShape(): list = cmds.ls(sl=True) extract = list[0] inyect = list[1] pos = cmds.xform(inyect, m=True, ws=True, q=True) extract = cmds.duplicate(extract, rc=True) cmds.xform(extract, m=pos, ws=True) extShape = cmds.listRelatives(extract, typ='shape') inyShape = cmds.listRelatives(inyect, typ='shape') for shape in extShape: cmds.parent(shape, inyect, r=True, s=True) for shape in inyShape: cmds.delete(shape) def folliclesSides(side = 'r', system_name='dwEyelid', nurbs='dwEyelidMain_r_nurbs'): vertex_list = cmds.ls(flatten = True, orderedSelection = True) fol_number = len(vertex_list) #Reorder vertex list vertex_list_ordered = [] vertex_list_disordered = vertex_list[::] vertex_list_disordered_x_positions = [] for vtx in vertex_list_disordered: vtx_x_position = cmds.xform(vtx, query = True, translation = True, worldSpace = True)[0] vertex_list_disordered_x_positions.append(vtx_x_position) while len(vertex_list_disordered)>0: vtx_lower_pos = 100000000000000 vtx_position_in_list = None for i, vtx_x_pos in enumerate(vertex_list_disordered_x_positions): if vtx_x_pos < vtx_lower_pos: vtx_lower_pos = vtx_x_pos vtx_position_in_list = i vertex_list_ordered.append(vertex_list_disordered[vtx_position_in_list]) vertex_list_disordered_x_positions.pop(vtx_position_in_list) vertex_list_disordered.pop(vtx_position_in_list) #Invertir el orden de la lista para el side r if side == 'r': vertex_list_ordered = vertex_list_ordered[::-1] #Create Follicles nurbs_shape = cmds.listRelatives(nurbs, shapes = True, noIntermediate = True) nurbs_shape = [x for x in nurbs_shape if not 'Orig' in x][0] follicle_list = [] for i in range(0,fol_number): follicle_name = '{}{}_{}_fol'.format(system_name, str(i+1).zfill(2), side) follicle = cmds.createNode('transform', name = follicle_name) follicle_shape = cmds.createNode('follicle', name = '{}Shape'.format(follicle_name), parent = follicle) cmds.connectAttr('{}.local'.format(nurbs_shape), '{}.inputSurface'.format(follicle_shape), force = True) cmds.connectAttr('{}.worldMatrix[0]'.format(nurbs_shape), '{}.inputWorldMatrix'.format(follicle_shape), force = True) for axis in 'XYZ': cmds.connectAttr('{}.outTranslate{}'.format(follicle_shape, axis), '{}.translate{}'.format(follicle, axis), force = True) #cmds.connectAttr('{}.outRotate{}'.format(follicle_shape, axis), '{}.rotate{}'.format(follicle, axis), force = True) follicle_list.append(follicle) for i, fol in enumerate(follicle_list): temp_closestSuface = cmds.createNode('closestPointOnSurface', name = 'temp_closest') cmds.connectAttr('{}.local'.format(nurbs_shape), '{}.inputSurface'.format(temp_closestSuface), force = True) vtx_position = cmds.xform(vertex_list_ordered[i], query = True, translation = True, worldSpace = True) cmds.setAttr('{}.inPosition'.format(temp_closestSuface), vtx_position[0], vtx_position[1], vtx_position[2]) parameter_U = cmds.getAttr('{}.parameterU'.format(temp_closestSuface)) parameter_V = cmds.getAttr('{}.parameterV'.format(temp_closestSuface)) follicle_shape = cmds.listRelatives(fol, shapes = True)[0] cmds.setAttr('{}.parameterU'.format(follicle_shape), parameter_U) cmds.setAttr('{}.parameterV'.format(follicle_shape), parameter_V) cmds.delete(temp_closestSuface) for fol in follicle_list: jnt_name = '{}_{}_skn'.format(*fol.split('_')) jnt_zero_name = '{}Skn_{}_zero'.format(*fol.split('_')) jnt = cmds.createNode('joint', name = jnt_name) jnt_zero = cmds.createNode('transform', name = jnt_zero_name) jnt = cmds.parent(jnt, jnt_zero)[0] fol_matrix = cmds.xform(fol, query = True, matrix = True, worldSpace= True) cmds.xform(jnt_zero, matrix = fol_matrix, worldSpace = True) subs_node_name = '{}Fol_{}_subs'.format(*fol.split('_')) subs_node = cmds.createNode('plusMinusAverage', name = subs_node_name) cmds.setAttr('{}.operation'.format(subs_node), 2) for axis in 'xyz': cmds.connectAttr('{}.t{}'.format(fol, axis), '{}.input3D[0].input3D{}'.format(subs_node, axis), force = True) cmds.connectAttr('{}.t{}'.format(fol, axis), '{}.input3D[1].input3D{}'.format(subs_node, axis), force = True) cmds.disconnectAttr('{}.t{}'.format(fol, axis), '{}.input3D[1].input3D{}'.format(subs_node, axis)) cmds.connectAttr('{}.output3D{}'.format(subs_node, axis), '{}.t{}'.format(jnt, axis), force = True)
Java
UTF-8
602
2.515625
3
[]
no_license
package spark; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; public class Example17 { public static void main(String[] args) { Example17 app = new Example17(); app.start(); } private void start() { Logger.getLogger("org").setLevel(Level.ERROR); SparkSession spark = SparkSession.builder().appName("CSV to Dataset").master("local").getOrCreate(); Dataset<Row> df = spark.read().format("csv").option("header", "true").load("in/books.csv"); df.show(5); } }
Markdown
UTF-8
10,195
3.109375
3
[ "MIT" ]
permissive
--- layout: post author: derek image: assets/images/blockchain.jpeg featured: false hidden: false title: 10 Best Blockchain Certification, Training & Courses date: '2018-05-31 10:00:00' comments: true external-url: null categories: Blockchain keywords: Blockchain, Training, Courses, programing, developer excerpt: A global team of 50+ Blockchain experts have compiled this list of 10 Best Blockchain Certification, Training, Course, Classes & Tutorial available online for 2018. These resources will help you Learn Blockchain from scratch, and are suitable for beginners, intermediate learners as well as experts. 9,000+ professionals have already benefited from this compilation. --- A global team of 50+ Blockchain experts have compiled this list of 10 Best Blockchain Certification, Training, Course, Classes & Tutorial available online for 2018. These resources will help you Learn Blockchain from scratch, and are suitable for beginners, intermediate learners as well as experts. 9,000+ professionals have already benefited from this compilation. ## 1. Blockchain Certification : IBM Blockchain Foundation for Developers This highly reputed certification program comes with experienced IBM blockchain developers teaching you concepts and strategies on building blockchain business networks. An ideal choice for software developers who are new to blockchain, this course is taught by Ant Cole, WW Blockchain Enablement at IBM Blockchain and Dave Gorman, Global Blockchain Labs Engagement at IBM Industry Platform. The fact that this training just requires 6 weeks of study with only 2 hours to be dedicated every week makes it an ideal weekend course for those with a full time commitment elsewhere. You will earn a Certificate on successful completion of the course. Key USPs – – Learn about Blockchain fabric development & architecture – Get to know how to transform your business using blockchain – Deep dive into Hyperledger Composer, understand the underlying structures, and use it for a real project – Learn in a community environment with thousands of other learners so you can discuss, debate and master concepts better – High course rating and good reviews Rating : 4.4 out of 5 ## 2. Blockchain Training : Ethereum and Solidity: The Complete Developer’s Guide Stephen Grider is a champion online instructor having taught more than 200,000 students on udemy alone! With a background of working for top corporations in the bay area, he now focuses his energy on training young (and old) minds to get better at all aspects of web development. He is one of the highest rated trainers and all his courses are extremely valuable and knowledgeable. In this program he will teach you how to use Ethereum, Solidity and Smart Contracts to build applications based on the blockchain. We have no doubt in calling this the best Blockchain tutorial. Key USPs – – Comprehensive course spanning 24 hours including 10 articles, all with lifetime access – Trainer help you work on real projects with Ethereum – Learn to design, test and implement secure Smart Contracts – Learn to use the latest version of Ethereum development tools – Learn in depth the capability and scope of Solidity Rating : 4.7 out of 5 ## 3. Blockchain Course : Blockchain and Bitcoin Fundamentals This is one of the best blockchain course, created by George Levy and it will help you demystify the key elements of blockchain and Bitcoin while making you understand how the technology works. This is one quick program that will take under 3 hours to get over. Key USPs – – High rating of 4.7 out of 5 – Learn about what is Blockchain and Bitcoin – Role of Bitcoin miners, How Block Hashes work in a Blockchain – Value of Blockchain – DAOs and DACs – A crisp course that has already been taken up by more than 30,000 students worldwide – Sending and Receiving Bitcoins Rating : 4.7 out of 5 ## 4. Become a Blockchain Developer with Ethereum and Solidity First lets talk about the trainers. Sebastien Arbogast, is a fullstack software developer, consultant, speaker and an entrepreneur. Along with Said Eloudrhiri, he has been working towards getting more developers involved in blockchain and developing better tools for blockchain development. Said has been working in IT for 25+ years and a is a proficient developer, software architect, team leader as well as agile coach. With 2 CVs like that you know you are in very safe hands in this course. Together, this duo will help you develop your first decentralized application from scratch on the Ethereum Blockchain. Key USPs – – Learn how to develop a distributed application, how to unit test them and create a user interface for them – Learn how to use the Truffle build and testing framework – The tutorial goes from the very basics to advanced levels – Learn about the fundamental of the solidity smart contract language – Get lifetime access to 15 hours of online content + 3 articles and 49 supplemental resources Rating : 4.6 out of 5 ## 5. Blockchain Developer Training : Ethereum Blockchain Developer: Build Projects Using Solidity Created by Ravinder Deol and Thomas Wiesner, two renowned experts in this domain, this training is all about building Blockchain projects using Solidity programming. Before you enroll for this course, you should have a basic understanding of either Web Development, JavaScript, Ajax-Requests, AngularJS or other related platforms. Doesn’t mean you need to be an expert in the same. Basic knowledge will be good to go. Key USPs – – Types of blockchain and potential uses of the same – What are Smart Contracts – Using MetaMask plugin – Real time action using Solidity – Learn all about Decentralisation as you work with the technology – Learn how to use Web3 with different projects Rating : 4.2 out of 5 ## 6. Ethereum Developer Masterclass: Build Real World Projects – Blockchain Tutorial Thomas and Ravinder are back with a development project training for Blockchain. This 10 hour course helps you become adept at the programming languages used to create blockchain projects. Most importantly, you will get to create real time projects with the trainers through this program. You should be familiar with Git, HTML, JavaScript and Bootstrap incase you decide to sign up. Key USPs – – Develop using Latest Solidity, Web3js, Truffle, TestRPC and MetaMask – Basic development knowledge will also do, don’t need to be an expert in the domain – Thomas and Ravinder have been involved with Blockchain since 2012 and come with multi disciplinary experience with them – Attendee Raymond Lieu feels “Wow what a course! I’ve learned a lot about how Solidity, Truffle, and Web3 + Javascript work together, building a real project” Rating : 4.3 out of 5 ## 7. Blockchain Developer Training : Getting Started with Ethereum Solidity Development Sebastien Arbogast is a full stack software developer, consultant and trainer with over 12 years of experience. He teams up with Said Eloudrhiri who’s been working in IT for the last 25 years! With a CV like that, you know you are in the safest of hands. They both have decided to share their knowledge on this subject to help you learn and grow in the field of blockchain and ethereum development using Solidity. Key USPs – – Learn to develop a distributed application – Understand how to write smart contracts and creating a user interface for them – Learn how to use Metamask – You will also learn Truffle building and testing framework – Deploying a decentralized app to various Ethereum instances (testrpc, private chain, test chain, main net) – Participant Mohit Shah feels “The course was complete and really good with all the explanations. I had know experience or idea about solidity but this course helped me to really get started with Ethereum DAPP development.” Rating : 4.6 out of 5 ## 8. Blockchain Course for Beginners : The Basics of Blockchain This is only for those wanting to get an overview and introduction to the world of blockchain. A quick 1.5 hour video training takes you through the fundamentals you need to understand this technology. Key USPs – – You will be able to pen down a piece regarding use cases and industry potential of Blockchain. – Help your business or your clients get ready for the emerging decentralized economy – Created by 5 experts on the subject – Tom Serres, Bettina Warburg, John Fitch, Collin Cusce, Tate Ryan-Mosley – 6,000 + people have already attended the training Rating : 4.2 out of 5 ## 9. Blockchain Certification : Blockchain for Business – Hyperledger Technologies This certification by The Linux Foundation will you learn how to start building blockchain applications with Hyperledger frameworks. You will learn how information is generated, stored, and shared in various blockchains, and also understand how to evaluate whether a blockchain solution is suitable for your business or not. Taught by experts in the domain including Navroop Sahdev, FinTech and Blockchain Entrepreneur and Nathalie Salami Blockchain Attorney. Key USPs – – This course is suitable for both nontechnical and technical audiences – You will learn to identify suitable blockchain uses for your business requirements – You will be guided through implementation of various blockchains – An eight week course, with a commitment of 3-4 hours per week making it ideal for weekend study as well Rating : 4.3 out of 5 ## 10. Blockchain Certification : Bitcoin and Cryptocurrency Technologies – Princeton University Princeton University brings you this Bitcoin & Cryptocurrency Certification Course taught by Arvind Narayanan, Assistant Professor at the University. Spread across 11 weeks, this is ideal for those who want to take it a little slow and understand all about crypto in detail from an academic point of view. Key USPs – – Learn how Bitcoin achieves decentralization – Learn How to Store, Use and Mine Bitcoins – Get a Certification from Princeton – Instructor discusses in detail about the future of Bitcoin , Altcoin and Cryptocurrencies in general Rating : 4.7 out of 5
Markdown
UTF-8
959
3.09375
3
[ "ICU", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- title: " DTOJ3991雪人\t\t" tags: - hash - 二分 url: 5057.html id: 5057 categories: - Solution date: 2018-11-05 22:57:16 --- 二哈分析。 考虑题目给出的这个性质,既然两个子串的公共差相等,我们可以将原字符串差分,那么两个子串“相等”,当且仅当两个串的差分数组相等。 由于两个重复的串对于答案的贡献不会比不重复的更优,这个答案相当于对于串长为$|l\_2-l\_1|$的子串的情况,具体画图就可以很容易的看出来。于是我们二分答案也就是子串长,那么就可以哈希然后判定了。 将所有长度为$mid$的子串hash起来,将所有的hash值排序来判断相等。那么就是要判断是否有两个hash值相等的子串,满足其开头之差 大于 mid。 这样子答案就是满足单调性的了。时间效率是$O(n \\log^2 n)$,两个log分别是二分和排序的log,所以跑起来其实很客观。
PHP
UTF-8
2,603
2.578125
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "DOC" ]
permissive
<?php /* * Copyright (c) 2010, Josef Kufner <jk@frozen-doe.net> * * 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. * */ /** * Load INI file using parse_ini_file() function. */ class B_core__ini__load extends \Cascade\Core\Block { protected $inputs = array( 'filename' => null, // Name of the file to load. 'name' => null, // If specified, sprintf(filename, name) is used to compose filename. 'process_sections' => true, // Second argument to parse_ini_file(). 'multi_output' => false, // Use top-level keys of loaded file as output names. 'scan_plugins' => false, // Search for specified file in all plugin directories. ); protected $connections = array( 'filename' => array(), ); protected $outputs = array( 'data' => true, // Data loaded from ini file. 'filename' => true, // Used filename. 'error' => true, // True when loading failed. 'done' => true, '*' => true, ); public function main() { $name = $this->in('name'); $fn = $this->in('filename'); $process_sections = $this->in('process_sections'); if (is_array($name)) { $name = join('/', $name); } if (is_array($fn)) { $fn = join('/', $fn); } if ($name !== null) { $fn = filename_format(sprintf($fn, $name)); } $fn = filename_format($fn); if ($this->in('scan_plugins')) { $data = @parse_ini_file(DIR_APP.$fn, $process_sections); if ($data === FALSE) { $data = @parse_ini_file(DIR_CORE.$fn, $process_sections); if ($data === FALSE) { $data = array(); } } $plugin_data[] = $data; foreach (get_plugin_list() as $plugin) { $d = @parse_ini_file(DIR_PLUGIN.$plugin.'/'.$fn, $process_sections); if ($d !== FALSE) { $plugin_data[] = $d; } } $data = call_user_func_array('array_merge', $plugin_data); } else { $data = parse_ini_file($fn, $process_sections); } if ($data === FALSE) { $this->out('error', true); } else { if ($this->in('multi_output')) { $this->outAll($data); } else { $this->out('data', $data); } } $this->out('filename', $fn); $this->out('done', $data !== FALSE); } }
Python
UTF-8
1,645
3.140625
3
[]
no_license
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns data= pd.read_csv('SampleSuperstore.csv') #checking for null variables print(data.isnull().sum()) # no null variables print(data.shape) #dropping columns whish dont affect data=data.drop(['Ship Mode','Postal Code','Country'],axis=1) print(data.duplicated().sum()) data=data.drop_duplicates() print(data.keys()) x=data['Profit'] y=data['State'] #SP=State & Profit SP=data.groupby('State')['Profit'].sum() SP = SP.to_frame().reset_index() SP=SP.sort_values(by='Profit', ascending=True) sns.barplot(x=SP['State'],y=SP['Profit']) plt.ylabel("Profit") plt.xlabel("State") plt.xticks(rotation = 90) #RPS=Region & Profit & Sales RPS=data.groupby('Region')['Profit','Sales'].sum() RPS.plot(kind='bar',rot=45) #CPS=Category & Profit & Sales CPS=data.groupby('Category')['Profit','Sales'].sum() CPS.plot(kind='bar',rot=45) #SCPS=Sub-Category & Profit & Sales SCPS=data.groupby('Sub-Category')['Profit','Sales'].sum() SCPS=SCPS.sort_values(by='Profit', ascending=True) SCPS.plot(kind='bar',rot=45) #SPS=State & Profit & Sales SPS=data.groupby('State')['Profit','Sales'].sum() SPS=SPS.sort_values(by='Profit', ascending=True) SCPS.plot(kind='bar',rot=45) #SPS=Segment & Profit & Sales SGPS=data.groupby('Segment')['Profit','Sales'].sum() SGPS=SGPS.sort_values(by='Profit', ascending=True) SGPS.plot(kind='bar',rot=45) #SS=State Sales SS=data.groupby('State')['Sales'].sum() SS = SS.to_frame().reset_index() SS=SS.sort_values(by='Sales', ascending=True) sns.barplot(x=SS['State'],y=SS['Sales']) plt.ylabel("Sales") plt.xlabel("State") plt.xticks(rotation = 90) plt.show()
C++
UTF-8
449
2.5625
3
[]
no_license
#include "StaticObject.h" StaticObject::StaticObject(Texture * tex, Vector2f pos) :Object(tex, pos) { } StaticObject::StaticObject(Texture * tex, Vector2f pos, std::string type_name) : Object(tex, pos) { this->type = type_name; } StaticObject::StaticObject(Texture * tex, IntRect rect, Vector2f pos) : Object(tex, rect, pos) { } void StaticObject::update(RenderWindow * win) { win->draw(this->sprite); } void StaticObject::move(moves m) { }
Java
UTF-8
2,019
3.671875
4
[]
no_license
package session4.task1; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int k = scanner.nextInt(); Car[] cars = new Car[100]; Truck[] trucks = new Truck[100]; int numberOfCars = 0; int numberOfTrucks = 0; for (int i = 0; i < k; i++) { int commandNumber = scanner.nextInt(); switch (commandNumber) { case 1: cars[numberOfCars++] = new Car( scanner.nextInt(), scanner.nextBoolean(), scanner.nextInt(), scanner.nextInt()); break; case 2: trucks[numberOfTrucks++] = new Truck( scanner.nextInt(), scanner.nextBoolean(), scanner.nextInt(), scanner.nextFloat()); break; case 3: for (int j = 0; j < numberOfCars; j++) { System.out.println(cars[j].toString()); } break; case 4: for (int j = 0; j < numberOfTrucks; j++) { System.out.println(trucks[j].toString()); } break; case 5: int counter = 0; for (int j = 0; j < numberOfCars; j++) { counter += cars[j].getTopSpeed() > 200 ? 1 : 0; // Solution II // if (cars[j].getTopSpeed() > 200) { // counter++; // } } System.out.println(counter); break; } } } }
Rust
UTF-8
778
3.375
3
[]
no_license
pub fn abbreviate(phrase: &str) -> String { let mut ret = String::new(); let words = phrase.split(|c: char| !c.is_alphabetic() && c != '\''); for word in words { if word.is_empty() { continue; } else if word.ends_with(':') { let i = word.len() - 1; return word[..i].to_string(); } else if word.chars().all(char::is_uppercase) || word.chars().all(char::is_lowercase) { ret.push(word.chars().next().unwrap()); } else { ret.push_str( &word .chars() .into_iter() .filter(char::is_ascii_uppercase) .collect::<String>(), ); } } ret.to_ascii_uppercase() }
Markdown
UTF-8
6,926
2.8125
3
[]
no_license
title: Configure Okta in CITSmart Description: Okta connects any user to any application in any device. This document explains the ideal way to connect this solution to CITSmart. # Configure Okta in CITSmart This authentication method allows you to use the Okta features to authenticate users of your organization in a CITSmart instance. This document explains the steps in configuring this method. To learn more about Okta, visit [okta.com][1]. Before getting started -------------------- The configuration of this solution is a multi-phase process. The first step is the creation of an Okta account. Procedure ---------------- *1st Step: Create an Okta account:* 1. Access the site: https://www.okta.com; 2. Click on "Try Okta" and then on "Sign up today"; 3. Enter the essential data (e-mail, name and last name); ![Create Okta account](images/okta.img1.png) 4. Click on "Get Started" to complete the operation. Then check the registered e-mail (which will send an access link), access the account with the temporary password sent and change it for greater data security; ![Check e-mail](images/okta.img2.png) *2nd Step: Created CITSmart application within Okta:* 1. After completing the previous step, connect to Okta with your newly created account; 2. Click on the "Applications" tab and then on "Add Application"; ![Create application](images/okta.img3.png) 3. Click on "Create New App"; ![Create App](images/okta.img4.png) 4. Select the option "SAML 2.0" and then click on "Create"; ![Option SAML 2.0](images/okta.img5.png) 5. In the field "App name", add the name of the application and soon after, it is necessary to click on "Next"; ![Name Application](images/okta.img6.png) 6. Configure the application path and then click on Next ![Configure path](images/okta.img7.png) !!!Abstract "ATTENTION" In the "Single sign on URL" and "Audience URI (SP Entity ID)" field, the URL addresses on which the CITSmart Application will be executed should be included. 7. Select the options "I'm an Okta customer adding an internal app" and "This is an internal app that we have created". Then, click on "Finish". ![Select the options](images/okta.img8.png) *3rd Step: Assign users to Okta's CITSmart application:* 1. After completing the previous step, you need to click on the "Applications > Applications" tab and then on "Assign Applications" and choose the filter called "People"; ![User assignment](images/okta.img9.png) 2. Then you can choose the user who will be allowed to access the application that is being created. Click on "Assign" and then, to finish, click on "Done"; ![Choosing user](images/okta.img10.png) *4th Step: Include required information in the CITSmart configured on Okta:* 1. You will need to configure some data in the WildFly directory. Access the directory, open the "/standalone/configuration" folder and change the file "citsmart.cfg". ![Wildfly Directory](images/okta.img11.png) 2. Accessed the file, you need to include this information in the file "citsmart.cfg": a) In the line *SAML2_HOST* and *SAML2_PORT* include the address and port of the CITSmart application; b) In the line *SAML2_METADATA* include the SAML metadata of the Okta. This data can be obtained by following the instructions below: - Access the CITSmart application in Okta, click the "Applications > Applications" tab and then on "Sign On". When you click on the "Identity Provider metadata" option, a new tab will be available to the metadata, copy the URL of the browser and insert in the property *SAML2_METADATA*; ![Sign On](images/okta.img12.png) c) In the line *OKTA_URL*, include the main URL in the Okta account. d) In the line *OKTA_TOKEN*, include the token to access through API. To get this token, follow these steps: 3. Access the CITSmart application in Okta, select the "Security > API" menu and then click on "Create Token". Name the token and click on "Create Token". It will be presented the token value to be copied on the line quoted above. ![Token](images/okta.img13.png) e) In the line *OKTA_DOMAIN_ALIAS*, include the domain of users coming from Okta. *5th Step: Synchronize Okta user on CITSmart:* 1. Within CITSmart, access the "Okta Config" menu and register a new configuration by clicking on "New"; ![Okta Confg](images/okta.img14.png) 2. Complete the fields with the necessary information: ![Fields Okta Confg](images/okta.img15.png) * **Description**: introduce a definition of this new setting Okta; * **Alias**: include the user domain that will be saved to the database. Example: okta\administrador@citsmart.com; * **URL domain**: should include the same value (URL) that was entered in the line *OKTA_URL* in the "citsmart.cfg" file; * **Token API**: include the same value of the token inserted in the line *OKTA_TOKEN* in the file "citsmart.cfg"; * **Group**: insert the ID of the group in which the synchronized and registered user will belong in CITSmart; * **Access Profile**: insert the profile ID in which the synchronized and registered user will belong in CITSmart; * **Application ID**: include the application ID. This information can be retrieved from the Okta URL, as shown below: ![URL ID](images/okta.img16.png) 3. Click on "Save" and then on "Synchronize users" to perform the operation. *6th Step: Configure the Logout:* 1. Since Okta does not have a logout screen, in parameter 377 of CITSmart, we can insert some page address to redirect the user to the end of the session; 2. Set up the logout link also at the address **(Admin > Settings > Customization > Sign-Out-Page)**, then check the option "Use the custom sign-out page". Therefore, enter the URL (https://localhost:8443/citsmart/saml/logout) with the appropriate adaptations (host and port), according to the image below: ![Logout](images/okta.img19.png) !!!Abstract "NOTE" When *logout* in CITSmart, do not *logout* from the Okta, since users may have other applications in the Okta session. In contrast, if you do Okta *logout*, the user session in CITSmart will be removed. What to do next ---------------------- Once the Okta integration with CITSmart is complete, some CITSmart parameters can be configured to better customize this integration. They are: - The parameter 445 (Name of the Administrator group in Okta) allows you to choose the administrator group in the Okta solution. If the user belongs to this chosen group, he/she will have the access profile defined as administrator. If this is not the case, your access profile will be the default profile defined by the parameter 39. !!! tip "About" <b>Product/Version:</b> CITSmart | 9.00 &nbsp;&nbsp; <b>Updated:</b>05/30/2019 – Larissa Lourenço [1]: https://www.okta.com/
Java
UTF-8
189
1.5
2
[]
no_license
package property_objects.wrappers; import lombok.Data; import property_objects.AccountProperties; @Data public class AccountPropertiesWrapper { AccountProperties accountProperties; }
Java
UTF-8
1,824
2.890625
3
[]
no_license
package com.bravo.meli.adn.negocio.interfaces; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.bravo.meli.adn.negocio.excepciones.DatosInvalidosException; import com.bravo.meli.adn.negocio.excepciones.ErrorCode; public interface Validable { public static final Pattern patronBasesInvalidas = Pattern.compile("[^CAGT]", Pattern.CASE_INSENSITIVE); default boolean validarCadenas(String[] cadenas) throws DatosInvalidosException { // Se asegura que el arreglo de cadenas contenga información. if (cadenas == null || cadenas.length <= 0) { throw new DatosInvalidosException(ErrorCode.CADENAS_NULAS); } // Se asegura que cada cadena del arreglo no este vacio. for (String cadena : cadenas) { if (cadena == null || cadena.isBlank()) { throw new DatosInvalidosException(ErrorCode.CADENAS_NULAS); } } // Establece el indice de la matriz. En este caso se opto por tomarlo a partir de la cantidad de cadenas. int indiceMatriz = cadenas.length; // Se asegura de que todas las cadenas tengan la misma longitud que el indice de la matriz. for (String cadena : cadenas) { if (indiceMatriz != cadena.length()) { throw new DatosInvalidosException(ErrorCode.CADENAS_TAMANOS_DISPARES); } } // Se asegura que la matriz sea cuadrada if (indiceMatriz != cadenas.length) { throw new DatosInvalidosException(ErrorCode.CADENA_DEBE_SER_CUADRADA); } // Se asegura que todos los valores de la cadena correspondan a las bases nitrogenadas: ATGC Matcher matcher; for (String cadena : cadenas) { matcher = patronBasesInvalidas.matcher(cadena); if (matcher.find()) { throw new DatosInvalidosException(ErrorCode.BASE_NITROGENADA_INVALIDA); } } // Llegados a este punto no se produjo ninguna excepcion, se retorna true return true; } }
C#
UTF-8
652
3.09375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Task01ExtractEmails { class Task01ExtractEmails { static void Main(string[] args) { Regex reg = new Regex(@"(?<=\s)[a-zA-Z0-9][\w\._-]*@[a-zA-Z-]+(\.[a-zA-Z][a-zA-Z-]*[a-zA-Z])+"); var text = Console.ReadLine(); var matches = reg.Matches(text).Cast<Match>().Select(n => n.Value).ToList(); foreach (var match in matches) { Console.WriteLine(match); } } } }
Java
UTF-8
3,523
2.28125
2
[ "MIT" ]
permissive
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. * See License.txt in the project root for license information. */ package com.microsoft.azure.datalake.store.oauth2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * Provides tokens based on Azure VM's Managed Service Identity */ public class MsiTokenProvider extends AccessTokenProvider { private static final Logger log = LoggerFactory.getLogger("com.microsoft.azure.datalake.store.oauth2.MsiTokenProvider"); private final int localPort = -1; private final String tenantGuid; private final String clientId; private long tokenFetchTime =-1; /** * Constructs a token provider that fetches tokens from the MSI token-service running on an Azure IaaS VM. This * only works on an Azure VM with the MSI extansion enabled. */ public MsiTokenProvider() { this(null, null); } /** * Constructs a token provider that fetches tokens from the MSI token-service running on an Azure IaaS VM. This * only works on an Azure VM with the MSI extansion enabled. * * @deprecated localPort is not relevant anymore in the new MSI mechanism * * @param localPort port on localhost for the MSI token service. (the port that was set in the deployment template). * If 0 or negative number is specified, then assume default port number of 50342. */ @Deprecated public MsiTokenProvider(int localPort) { this(null, null); } /** * Constructs a token provider that fetches tokens from the MSI token-service running on an Azure IaaS VM. This * only works on an Azure VM with the MSI extansion enabled. * * @deprecated localPort is not relevant anymore in the new MSI mechanism * * @param localPort port on localhost for the MSI token service. (the port that was set in the deployment template). * If 0 or negative number is specified, then assume default port number of 50342. * @param tenantGuid (optional) AAD Tenant ID {@code guid}. Can be {@code null}. */ @Deprecated public MsiTokenProvider(int localPort, String tenantGuid) { this(tenantGuid, null); } public MsiTokenProvider(String tenantGuid, String clientId) { this.tenantGuid = tenantGuid; this.clientId = clientId; } /** * Checks if the token is about to expire as per base expiry logic. Otherwise try to expire every 1 hour * * * @return true if the token is expiring in next 5 minutes */ @Override protected boolean isTokenAboutToExpire() { if( super.isTokenAboutToExpire()){ return true; } if (tokenFetchTime == -1){ return true; } long offset = ONE_HOUR; if ((tokenFetchTime +offset) < System.currentTimeMillis()) { log.debug("MSIToken: token renewing : " + offset + " milliseconds window"); return true; } return false; } @Override protected AzureADToken refreshToken() throws IOException { log.debug("AADToken: refreshing token from MSI with expiry"); AzureADToken newToken = AzureADAuthenticator.getTokenFromMsi(tenantGuid, clientId, false); tokenFetchTime=System.currentTimeMillis(); return newToken; } private static final long ONE_HOUR = 3600 * 1000; // 5 minutes in milliseconds }
Java
UTF-8
1,792
2.46875
2
[ "MIT" ]
permissive
/*============================================================================== Copyright (c) 2012-2013 Qualcomm Connected Experiences, Inc. All Rights Reserved. ==============================================================================*/ package com.qualcomm.vuforia.samples.VideoPlayback.app.VideoPlayback; public class VideoPlaybackShaders { public static final String VIDEO_PLAYBACK_VERTEX_SHADER = " \n" + "attribute vec4 vertexPosition; \n" + "attribute vec4 vertexNormal; \n" + "attribute vec2 vertexTexCoord; \n" + "varying vec2 texCoord; \n" + "varying vec4 normal; \n" + "uniform mat4 modelViewProjectionMatrix; \n" + "\n" + "void main() \n" + "{ \n" + " gl_Position = modelViewProjectionMatrix * vertexPosition; \n" + " normal = vertexNormal; \n" + " texCoord = vertexTexCoord; \n" + "} \n"; /* * * IMPORTANT: * * The SurfaceTexture functionality from ICS provides the video frames from * the movie in an unconventional format. So we cant use Texture2D but we * need to use the ExternalOES extension. * * Two things that are important in the shader below. The first is the * extension declaration (first line). The second is the type of the * texSamplerOES uniform. */ public static final String VIDEO_PLAYBACK_FRAGMENT_SHADER = " \n" + "#extension GL_OES_EGL_image_external : require \n" + "precision mediump float; \n" + "varying vec2 texCoord; \n" + "uniform samplerExternalOES texSamplerOES; \n" + " \n" + "void main() \n" + "{ \n" + " gl_FragColor = texture2D(texSamplerOES, texCoord); \n" + "} \n"; }
Java
UTF-8
2,635
2.125
2
[]
no_license
package com.java.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.java.model.*; import com.java.service.*; import com.java.utils.CommonUtils; import com.java.utils.PageList; import com.java.utils.StringUtil; @Controller /*@RequestMapping("/line")*/ public class indexController { @Autowired private IntroduceService introduceService; @Autowired private NewsService newsService; @Autowired private NewsTypeService newstypeService; @Autowired private HttpServletRequest request; /** * 用户首页 * @return */ @RequestMapping(value = "/index") public String index(Model model,News n){ Pages p=new Pages(); p.setPagesize(5); int startindex=request.getParameter("startindex")==null?0:Integer.parseInt(request.getParameter("startindex"));//起始页,默认从第1页开始读 p.setStartindex(startindex); n.setPage(p); List<News> news = newsService.Get(n); for(int i=0;i<news.size();i++) { String content=StringUtil.CleanHTML(news.get(i).getContent()); news.get(i).setContent(content); } Introduce intr = introduceService.GetByID(1); List<NewsType> nt = newstypeService.Get(); model.addAttribute("news", news); model.addAttribute("intr", intr); model.addAttribute("newstype", nt); request.getSession().setAttribute("menu", nt); request.setAttribute("pages", PageList.Page(request, newsService.GetCount(n), p.getPagesize(), p.getStartindex(),request.getQueryString())); System.out.println(request.getQueryString()); return "index"; } @RequestMapping(value = "/badge") public String service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); int getTotal = newsService.GetTotals(); StringBuffer json = null; //数据发生改变 将数据响应客户端 json = new StringBuffer("{"); json.append("\"msgNum\":"+getTotal); json.append("}"); out.write(json.toString()); return "top"; } }
TypeScript
UTF-8
3,237
3.125
3
[]
no_license
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity'; import { Attendance } from '../../model/member'; import { AttendanceActionsUnion, AttendanceActionTypes } from '../actions/attendance.actions'; import { AttendanceCollectionActionsUnion, AttendanceCollectionActionTypes, } from '../actions/attendance.collection.actions'; /** * @ngrx/entity provides a predefined interface for handling * a structured dictionary of records. This interface * includes an array of ids, and a dictionary of the provided * model type by id. This interface is extended to include * any additional interface properties. */ export interface State extends EntityState<Attendance> { selectedAttendanceId: string | null; } /** * createEntityAdapter creates an object of many helper * functions for single or multiple operations * against the dictionary of records. The configuration * object takes a record id selector function and * a sortComparer option which is set to a compare * function if the records are to be sorted. */ export const adapter: EntityAdapter<Attendance> = createEntityAdapter<Attendance>({ selectId: (attendance: Attendance) => attendance._id, sortComparer: false, }); /** * getInitialState returns the default initial state * for the generated entity state. Initial state * additional properties can also be defined. */ export const initialState: State = adapter.getInitialState({ selectedAttendanceId: null, }); export function reducer( state = initialState, action: AttendanceActionsUnion | AttendanceCollectionActionsUnion ): State { switch (action.type) { case AttendanceActionTypes.LoadAttendance: { return { ...state, }; } case AttendanceCollectionActionTypes.LoadSuccess: { return adapter.addMany(action.payload, { ...state, selectedAttendanceId: state.selectedAttendanceId, }); } case AttendanceActionTypes.LoadAttendanceSuccess: case AttendanceActionTypes.AddAttendanceSuccess: { return adapter.addOne(action.payload, { ...state, selectedAttendanceId: state.selectedAttendanceId, }); } case AttendanceActionTypes.UpdateAttendanceSuccess: { return adapter.updateOne( { id: action.payload._id, changes: action.payload }, { ...state, selectedAttendanceId: null, }); } case AttendanceActionTypes.DeleteAttendanceSuccess: { return adapter.removeOne(action.payload._id, { ...state, selectedAttendanceId: null, }); } case AttendanceActionTypes.SelectAttendance: { return { ...state, selectedAttendanceId: action.payload, }; } default: { return state; } } } /** * Because the data structure is defined within the reducer it is optimal to * locate our selector functions at this level. If store is to be thought of * as a database, and reducers the tables, selectors can be considered the * queries into said database. Reattendance to keep your selectors small and * focused so they can be combined and composed to fit each particular * use-case. */ export const getSelectedId = (state: State) => state.selectedAttendanceId;
Java
UTF-8
830
2.34375
2
[]
no_license
package com.sonihr.batis.executor.parameter;/* @author 黄大宁Rhinos @date 2019/6/3 - 15:38 **/ import com.sonihr.batis.session.Configuration; import com.sonihr.batis.utils.ParametersUtil; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; public class DefaultParameterHandler implements ParameterHandler { private Configuration configuration; private Object[] args; public DefaultParameterHandler(Configuration configuration,Object[] args) { this.configuration = configuration; this.args = args; } @Override public void setParameters(PreparedStatement ps) throws SQLException { String sql = configuration.getSql(); for(int i=0;i<args.length;i++){ ps.setObject(i+1,args[i]); } } }
C++
UTF-8
23,971
2.515625
3
[ "MIT" ]
permissive
// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #ifndef VSNRAY_MATH_SIMD_GATHER_H #define VSNRAY_MATH_SIMD_GATHER_H 1 #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wignored-attributes" #endif #include <cstddef> #include <cstdint> #include <type_traits> #include "../config.h" #include "avx.h" #include "avx512.h" #include "builtin.h" #include "neon.h" #include "sse.h" // Insert math headers after platform headers to inhibit ADL! #include "../norm.h" #include "../vector.h" namespace MATH_NAMESPACE { namespace simd { //------------------------------------------------------------------------------------------------- // Gather loads from memory to SIMD vectors // // // The gather functions use dedicated hardware instructions when applicable // and resort to software implementations if no instruction is available. // // // Implemented for the following cases: // - base address: unorm<N>, index type: int4 // - base address: unorm<N>, index type: int8 // - base address: unorm<N>, index type: int16 // - base address: float, index type: int4 // - base address: float, index type: int8 // - base address: float, index type: int16 // - base address: Int, index type: int4 // - base address: Int, index type: int8 // - base address: Int, index type: int16 // // - base address: vector<4, float>, index type: int4 // - base address: vector<4, float>, index type: int8 // - base address: vector<4, float>, index type: int16 // - base address: vector<N, float>, index type: int4 // - base address: vector<N, float>, index type: int8 // // - base address: vector<N, unorm<M>>, index type: int4 // - base address: vector<N, unorm<M>>, index type: int8 // - base address: vector<N, unorm<M>>, index type: int16 // - base address: vector<N, Int>>, index type: int4 // - base address: vector<N, Int>>, index type: int8 // - base address: vector<N, Int>>, index type: int16 // // , where I in (u)int{8|16|32|64}_t // // //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- // Gather float4 from N-bit unorm array, N <= 32 // No dedicated AVX2 instruction! // template <unsigned Bits> VSNRAY_FORCE_INLINE float4 gather(unorm<Bits> const* base_addr, int4 const& index) { static_assert(Bits <= 32, "Incompatible unorm type"); VSNRAY_ALIGN(16) int indices[4]; store(&indices[0], index); return float4( static_cast<float>(base_addr[indices[0]]), static_cast<float>(base_addr[indices[1]]), static_cast<float>(base_addr[indices[2]]), static_cast<float>(base_addr[indices[3]]) ); } //------------------------------------------------------------------------------------------------- // Gather float8 from N-bit unorm array, N <= 32 // No dedicated AVX2 instruction! // template <unsigned Bits> VSNRAY_FORCE_INLINE float8 gather(unorm<Bits> const* base_addr, int8 const& index) { static_assert(Bits <= 32, "Incompatible unorm type"); VSNRAY_ALIGN(32) int indices[8]; store(&indices[0], index); return float8( static_cast<float>(base_addr[indices[0]]), static_cast<float>(base_addr[indices[1]]), static_cast<float>(base_addr[indices[2]]), static_cast<float>(base_addr[indices[3]]), static_cast<float>(base_addr[indices[4]]), static_cast<float>(base_addr[indices[5]]), static_cast<float>(base_addr[indices[6]]), static_cast<float>(base_addr[indices[7]]) ); } //------------------------------------------------------------------------------------------------- // Gather float16 from N-bit unorm array, N <= 32 // No dedicated AVX-512 instruction! // template <unsigned Bits> VSNRAY_FORCE_INLINE float16 gather(unorm<Bits> const* base_addr, int16 const& index) { static_assert(Bits <= 32, "Incompatible unorm type"); VSNRAY_ALIGN(64) int indices[16]; store(&indices[0], index); return float16( static_cast<float>(base_addr[indices[ 0]]), static_cast<float>(base_addr[indices[ 1]]), static_cast<float>(base_addr[indices[ 2]]), static_cast<float>(base_addr[indices[ 3]]), static_cast<float>(base_addr[indices[ 4]]), static_cast<float>(base_addr[indices[ 5]]), static_cast<float>(base_addr[indices[ 6]]), static_cast<float>(base_addr[indices[ 7]]), static_cast<float>(base_addr[indices[ 8]]), static_cast<float>(base_addr[indices[ 9]]), static_cast<float>(base_addr[indices[10]]), static_cast<float>(base_addr[indices[11]]), static_cast<float>(base_addr[indices[12]]), static_cast<float>(base_addr[indices[13]]), static_cast<float>(base_addr[indices[14]]), static_cast<float>(base_addr[indices[15]]) ); } //------------------------------------------------------------------------------------------------- // Gather float4 from 32-bit float array // VSNRAY_FORCE_INLINE float4 gather(float const* base_addr, int4 const& index) { #if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX2) return _mm_i32gather_ps(base_addr, index, 4); #else VSNRAY_ALIGN(16) int indices[4]; store(&indices[0], index); return float4( base_addr[indices[0]], base_addr[indices[1]], base_addr[indices[2]], base_addr[indices[3]] ); #endif } //------------------------------------------------------------------------------------------------- // Gather float8 from 32-bit float array // VSNRAY_FORCE_INLINE float8 gather(float const* base_addr, int8 const& index) { #if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX2) return _mm256_i32gather_ps(base_addr, index, 4); #else VSNRAY_ALIGN(32) int indices[8]; store(&indices[0], index); return float8( base_addr[indices[0]], base_addr[indices[1]], base_addr[indices[2]], base_addr[indices[3]], base_addr[indices[4]], base_addr[indices[5]], base_addr[indices[6]], base_addr[indices[7]] ); #endif } //------------------------------------------------------------------------------------------------- // Gather float8 from 32-bit float array // VSNRAY_FORCE_INLINE float16 gather(float const* base_addr, int16 const& index) { #if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX512F) return _mm512_i32gather_ps(index, base_addr, 4); #else VSNRAY_ALIGN(64) int indices[16]; store(&indices[0], index); return float16( base_addr[indices[ 0]], base_addr[indices[ 1]], base_addr[indices[ 2]], base_addr[indices[ 3]], base_addr[indices[ 4]], base_addr[indices[ 5]], base_addr[indices[ 6]], base_addr[indices[ 7]], base_addr[indices[ 8]], base_addr[indices[ 9]], base_addr[indices[10]], base_addr[indices[11]], base_addr[indices[12]], base_addr[indices[13]], base_addr[indices[14]], base_addr[indices[15]] ); #endif } //------------------------------------------------------------------------------------------------- // Gather int4 from any integer array // No dedicated AVX2 instruction (see special case for 32-bit integer arrays)! // template < typename I, typename = typename std::enable_if<std::is_integral<I>::value>::type > VSNRAY_FORCE_INLINE int4 gather(I const* base_addr, int4 const& index) { VSNRAY_ALIGN(16) int indices[4]; store(&indices[0], index); return int4( static_cast<int32_t>(base_addr[indices[0]]), static_cast<int32_t>(base_addr[indices[1]]), static_cast<int32_t>(base_addr[indices[2]]), static_cast<int32_t>(base_addr[indices[3]]) ); } //------------------------------------------------------------------------------------------------- // Gather int8 from any integer array // No dedicated AVX2 instruction (see special case for 32-bit integer arrays)! // template < typename I, typename = typename std::enable_if<std::is_integral<I>::value>::type > VSNRAY_FORCE_INLINE int8 gather(I const* base_addr, int8 const& index) { VSNRAY_ALIGN(32) int indices[8]; store(&indices[0], index); return int8( static_cast<int32_t>(base_addr[indices[0]]), static_cast<int32_t>(base_addr[indices[1]]), static_cast<int32_t>(base_addr[indices[2]]), static_cast<int32_t>(base_addr[indices[3]]), static_cast<int32_t>(base_addr[indices[4]]), static_cast<int32_t>(base_addr[indices[5]]), static_cast<int32_t>(base_addr[indices[6]]), static_cast<int32_t>(base_addr[indices[7]]) ); } //------------------------------------------------------------------------------------------------- // Gather int16 from any integer array // No dedicated AVX-512 instruction (see special case for 32-bit integer arrays)! // template < typename I, typename = typename std::enable_if<std::is_integral<I>::value>::type > VSNRAY_FORCE_INLINE int16 gather(I const* base_addr, int16 const& index) { VSNRAY_ALIGN(64) int indices[16]; store(&indices[0], index); return int16( static_cast<int32_t>(base_addr[indices[ 0]]), static_cast<int32_t>(base_addr[indices[ 1]]), static_cast<int32_t>(base_addr[indices[ 2]]), static_cast<int32_t>(base_addr[indices[ 3]]), static_cast<int32_t>(base_addr[indices[ 4]]), static_cast<int32_t>(base_addr[indices[ 5]]), static_cast<int32_t>(base_addr[indices[ 6]]), static_cast<int32_t>(base_addr[indices[ 7]]), static_cast<int32_t>(base_addr[indices[ 8]]), static_cast<int32_t>(base_addr[indices[ 9]]), static_cast<int32_t>(base_addr[indices[10]]), static_cast<int32_t>(base_addr[indices[11]]), static_cast<int32_t>(base_addr[indices[12]]), static_cast<int32_t>(base_addr[indices[13]]), static_cast<int32_t>(base_addr[indices[14]]), static_cast<int32_t>(base_addr[indices[15]]) ); } //------------------------------------------------------------------------------------------------- // Gather int4 from 32-bit integer array // VSNRAY_FORCE_INLINE int4 gather(int const* base_addr, int4 const& index) { #if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX2) return _mm_i32gather_epi32(base_addr, index, 4); #else VSNRAY_ALIGN(16) int indices[4]; store(&indices[0], index); return int4( base_addr[indices[0]], base_addr[indices[1]], base_addr[indices[2]], base_addr[indices[3]] ); #endif } //------------------------------------------------------------------------------------------------- // Gather int8 from 32-bit integer array // VSNRAY_FORCE_INLINE int8 gather(int const* base_addr, int8 const& index) { #if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX2) return _mm256_i32gather_epi32(base_addr, index, 4); #else VSNRAY_ALIGN(32) int indices[8]; store(&indices[0], index); return int8( base_addr[indices[0]], base_addr[indices[1]], base_addr[indices[2]], base_addr[indices[3]], base_addr[indices[4]], base_addr[indices[5]], base_addr[indices[6]], base_addr[indices[7]] ); #endif } //------------------------------------------------------------------------------------------------- // Gather int16 from 32-bit integer array // VSNRAY_FORCE_INLINE int16 gather(int const* base_addr, int16 const& index) { #if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX512F) return _mm512_i32gather_epi32(index, base_addr, 4); #else VSNRAY_ALIGN(64) int indices[16]; store(&indices[0], index); return int16( base_addr[indices[ 0]], base_addr[indices[ 1]], base_addr[indices[ 2]], base_addr[indices[ 3]], base_addr[indices[ 4]], base_addr[indices[ 5]], base_addr[indices[ 6]], base_addr[indices[ 7]], base_addr[indices[ 8]], base_addr[indices[ 9]], base_addr[indices[10]], base_addr[indices[11]], base_addr[indices[12]], base_addr[indices[13]], base_addr[indices[14]], base_addr[indices[15]] ); #endif } //------------------------------------------------------------------------------------------------- // Gather vector<N, float4> from vector<N, float> array // template <size_t Dim> VSNRAY_FORCE_INLINE vector<Dim, float4> gather(vector<Dim, float> const* base_addr, int4 const& index) { VSNRAY_ALIGN(16) int indices[4]; store(&indices[0], index); array<vector<Dim, float>, 4> arr {{ base_addr[indices[0]], base_addr[indices[1]], base_addr[indices[2]], base_addr[indices[3]] }}; return simd::pack(arr); } template <size_t Dim> VSNRAY_FORCE_INLINE vector<Dim, float8> gather(vector<Dim, float> const* base_addr, int8 const& index) { #if 0 // AVX2 // TODO: check if gather intrinsic can be used here! #else VSNRAY_ALIGN(32) int indices[8]; store(&indices[0], index); array<vector<Dim, float>, 8> arr {{ base_addr[indices[0]], base_addr[indices[1]], base_addr[indices[2]], base_addr[indices[3]], base_addr[indices[4]], base_addr[indices[5]], base_addr[indices[6]], base_addr[indices[7]] }}; return simd::pack(arr); #endif } template <size_t Dim> VSNRAY_FORCE_INLINE vector<Dim, float16> gather(vector<Dim, float> const* base_addr, int16 const& index) { //#if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX512F) // TODO: check if gather intrinsic can be used here! //#endif VSNRAY_ALIGN(64) int indices[16]; store(&indices[0], index); array<vector<Dim, float>, 16> arr {{ base_addr[indices[ 0]], base_addr[indices[ 1]], base_addr[indices[ 2]], base_addr[indices[ 3]], base_addr[indices[ 4]], base_addr[indices[ 5]], base_addr[indices[ 6]], base_addr[indices[ 7]], base_addr[indices[ 8]], base_addr[indices[ 9]], base_addr[indices[10]], base_addr[indices[11]], base_addr[indices[12]], base_addr[indices[13]], base_addr[indices[14]], base_addr[indices[15]] }}; return simd::pack(arr); } //------------------------------------------------------------------------------------------------- // Gather vector<4, float4> from vector<4, float> array // VSNRAY_FORCE_INLINE vector<4, float4> gather(vector<4, float> const* base_addr, int4 const& index) { //----------------------------------------------------- // Optimization for AoS data. // // Data is gathered w/o a context switch to GP // registers by transposing to SoA after memory // lookup. // VSNRAY_ALIGN(16) int indices[4]; store(&indices[0], index * 4); float const* tmp = reinterpret_cast<float const*>(base_addr); vector<4, simd::float4> result( &tmp[0] + indices[0], &tmp[0] + indices[1], &tmp[0] + indices[2], &tmp[0] + indices[3] ); result = transpose(result); return result; } //------------------------------------------------------------------------------------------------- // Gather vector<4, float8> from vector<4, float> array // VSNRAY_FORCE_INLINE vector<4, float8> gather(vector<4, float> const* base_addr, int8 const& index) { #if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX2) float const* tmp = reinterpret_cast<float const*>(base_addr); return vector<4, simd::float8>( _mm256_i32gather_ps(tmp, index * 4 , 4), _mm256_i32gather_ps(tmp, index * 4 + 1, 4), _mm256_i32gather_ps(tmp, index * 4 + 2, 4), _mm256_i32gather_ps(tmp, index * 4 + 3, 4) ); #else VSNRAY_ALIGN(32) int indices[8]; store(&indices[0], index); array<vector<4, float>, 8> arr{{ base_addr[indices[0]], base_addr[indices[1]], base_addr[indices[2]], base_addr[indices[3]], base_addr[indices[4]], base_addr[indices[5]], base_addr[indices[6]], base_addr[indices[7]] }}; return simd::pack(arr); #endif } //------------------------------------------------------------------------------------------------- // Gather vector<4, float16> from vector<4, float> array // VSNRAY_FORCE_INLINE vector<4, float16> gather(vector<4, float> const* base_addr, int16 const& index) { #if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX512F) float const* tmp = reinterpret_cast<float const*>(base_addr); return vector<4, simd::float16>( _mm512_i32gather_ps(index * 4 , tmp, 4), _mm512_i32gather_ps(index * 4 + 1, tmp, 4), _mm512_i32gather_ps(index * 4 + 2, tmp, 4), _mm512_i32gather_ps(index * 4 + 3, tmp, 4) ); #else VSNRAY_ALIGN(64) int indices[16]; store(&indices[0], index); array<vector<4, float>, 16> arr{{ base_addr[indices[ 0]], base_addr[indices[ 1]], base_addr[indices[ 2]], base_addr[indices[ 3]], base_addr[indices[ 4]], base_addr[indices[ 5]], base_addr[indices[ 6]], base_addr[indices[ 7]], base_addr[indices[ 8]], base_addr[indices[ 9]], base_addr[indices[10]], base_addr[indices[11]], base_addr[indices[12]], base_addr[indices[13]], base_addr[indices[14]], base_addr[indices[15]] }}; return simd::pack(arr); #endif } //------------------------------------------------------------------------------------------------- // Gather vector<Dim, int4> from vector<Dim, Int> array // No dedicated AVX2 instruction! // template < size_t Dim, typename I, typename = typename std::enable_if<std::is_integral<I>::value>::type > VSNRAY_FORCE_INLINE vector<Dim, int4> gather(vector<Dim, I> const* base_addr, int4 const& index) { using V = vector<Dim, int32_t>; VSNRAY_ALIGN(16) int indices[4]; store(&indices[0], index); array<V, 4> arr{{ V(base_addr[indices[0]]), V(base_addr[indices[1]]), V(base_addr[indices[2]]), V(base_addr[indices[3]]) }}; return simd::pack(arr); } //------------------------------------------------------------------------------------------------- // Gather vector<Dim, int8> from vector<Dim, Int> array // No dedicated AVX2 instruction! // template < size_t Dim, typename I, typename = typename std::enable_if<std::is_integral<I>::value>::type > VSNRAY_FORCE_INLINE vector<Dim, int8> gather(vector<Dim, I> const* base_addr, int8 const& index) { using V = vector<Dim, int32_t>; VSNRAY_ALIGN(32) int indices[8]; store(&indices[0], index); array<V, 8> arr{{ V(base_addr[indices[0]]), V(base_addr[indices[1]]), V(base_addr[indices[2]]), V(base_addr[indices[3]]), V(base_addr[indices[4]]), V(base_addr[indices[5]]), V(base_addr[indices[6]]), V(base_addr[indices[7]]) }}; return simd::pack(arr); } //------------------------------------------------------------------------------------------------- // Gather vector<Dim, int16> from vector<Dim, Int> array // No dedicated AVX-512 instruction! // template < size_t Dim, typename I, typename = typename std::enable_if<std::is_integral<I>::value>::type > VSNRAY_FORCE_INLINE vector<Dim, int16> gather(vector<Dim, I> const* base_addr, int16 const& index) { using V = vector<Dim, int32_t>; VSNRAY_ALIGN(64) int indices[16]; store(&indices[0], index); array<V, 16> arr{{ V(base_addr[indices[ 0]]), V(base_addr[indices[ 1]]), V(base_addr[indices[ 2]]), V(base_addr[indices[ 3]]), V(base_addr[indices[ 4]]), V(base_addr[indices[ 5]]), V(base_addr[indices[ 6]]), V(base_addr[indices[ 7]]), V(base_addr[indices[ 8]]), V(base_addr[indices[ 9]]), V(base_addr[indices[10]]), V(base_addr[indices[11]]), V(base_addr[indices[12]]), V(base_addr[indices[13]]), V(base_addr[indices[14]]), V(base_addr[indices[15]]) }}; return simd::pack(arr); } //------------------------------------------------------------------------------------------------- // Gather vector<Dim, float8> from vector<Dim, unorm<Bits>> array, Bits <= 32 // No dedicated AVX2 instruction! // template <size_t Dim, unsigned Bits> VSNRAY_FORCE_INLINE vector<Dim, float4> gather(vector<Dim, unorm<Bits>> const* base_addr, int4 const& index) { static_assert(Bits <= 32, "Incompatible unorm type"); using V = vector<Dim, float>; VSNRAY_ALIGN(16) int indices[4]; store(&indices[0], index); array<V, 4> arr{{ V(base_addr[indices[0]]), V(base_addr[indices[1]]), V(base_addr[indices[2]]), V(base_addr[indices[3]]), }}; return simd::pack(arr); } //------------------------------------------------------------------------------------------------- // Gather vector<Dim, float8> from vector<Dim, unorm<Bits>> array, Bits <= 32 // No dedicated AVX2 instruction! // template <size_t Dim, unsigned Bits> VSNRAY_FORCE_INLINE vector<Dim, float8> gather(vector<Dim, unorm<Bits>> const* base_addr, int8 const& index) { static_assert(Bits <= 32, "Incompatible unorm type"); using V = vector<Dim, float>; VSNRAY_ALIGN(32) int indices[8]; store(&indices[0], index); array<V, 8> arr{{ V(base_addr[indices[0]]), V(base_addr[indices[1]]), V(base_addr[indices[2]]), V(base_addr[indices[3]]), V(base_addr[indices[4]]), V(base_addr[indices[5]]), V(base_addr[indices[6]]), V(base_addr[indices[7]]) }}; return simd::pack(arr); } //------------------------------------------------------------------------------------------------- // Gather vector<Dim, float16> from vector<Dim, unorm<Bits>> array, Bits <= 32 // No dedicated AVX-512F instruction! // template <size_t Dim, unsigned Bits> VSNRAY_FORCE_INLINE vector<Dim, float16> gather(vector<Dim, unorm<Bits>> const* base_addr, int16 const& index) { static_assert(Bits <= 32, "Incompatible unorm type"); using V = vector<Dim, float>; VSNRAY_ALIGN(64) int indices[16]; store(&indices[0], index); array<V, 16> arr{{ V(base_addr[indices[ 0]]), V(base_addr[indices[ 1]]), V(base_addr[indices[ 2]]), V(base_addr[indices[ 3]]), V(base_addr[indices[ 4]]), V(base_addr[indices[ 5]]), V(base_addr[indices[ 6]]), V(base_addr[indices[ 7]]), V(base_addr[indices[ 8]]), V(base_addr[indices[ 9]]), V(base_addr[indices[10]]), V(base_addr[indices[11]]), V(base_addr[indices[12]]), V(base_addr[indices[13]]), V(base_addr[indices[14]]), V(base_addr[indices[15]]) }}; return simd::pack(arr); } } // simd } // MATH_NAMESPACE #if defined(__GNUC__) #pragma GCC diagnostic pop #endif #endif // VSNRAY_MATH_SIMD_GATHER_H
C++
UTF-8
2,598
3.984375
4
[]
no_license
//访问和封装控制 #include <string> #include <iostream> class Sales_data //用class,在第一个访问说明符之前的都是private //struct Sales_data //用struct,在第一个访问说明符之前的都是public { friend std::istream &read(std::istream &is, Sales_data &item); //声明为友元函数,就可以不受访问限制 friend std::ostream &print(std::ostream &os, const Sales_data &item); //类内任何位置声明都可以 friend Sales_data add(const Sales_data &s1, const Sales_data &s2); public: Sales_data() = default; Sales_data(const std::string &s, unsigned n, double single_price) : book_number(s), units_sold(n), total_income(single_price * n){}; Sales_data(const std::string &s) : book_number(s){}; Sales_data(std::istream &is) { is >> book_number >> units_sold >> total_income; } std::string isbn() const { return book_number; } Sales_data &combine(const Sales_data &s) { this->units_sold += s.units_sold; this->total_income += s.total_income; return *this; } private: double avg_price() const { return units_sold ? total_income / units_sold : 0; } std::string book_number; unsigned int units_sold = 0; double total_income = 0.0; }; //除了类内部的友元函数声明,函数还需要在类外声明 std::istream &read(std::istream &is, Sales_data &item); std::ostream &print(std::ostream &os, const Sales_data &item); Sales_data add(const Sales_data &sd1, const Sales_data &sd2); //非成员函数定义 std::istream &read(std::istream &is, Sales_data &item) { std::cout << "Please input an item of sales data: book_number, units_sold, single_price" << std::endl; double price = 0; is >> item.book_number >> item.units_sold >> price; item.total_income = price * item.units_sold; return is; } std::ostream &print(std::ostream &os, const Sales_data &item) { os << "ISBN: " << item.isbn() << ", units_sold: " << item.units_sold << " total_income: " << item.total_income << ", avg_price: " << item.avg_price(); return os; } Sales_data add(const Sales_data &sd1, const Sales_data &sd2) { Sales_data ret = sd1; //拷贝 ret.combine(sd2); return ret; } int main(int argc, char const *argv[]) { Sales_data s1; Sales_data s2("3123", 3, 1.5); Sales_data s3(std::cin); // std::cout << s1.book_number << std::endl;//不能访问private print(std::cout, s1); std::cout << std::endl; print(std::cout, s2); std::cout << std::endl; print(std::cout, s3); std::cout << std::endl; return 0; }
Java
UTF-8
3,618
3.171875
3
[]
no_license
package brus.brus_723_System_InputOutput.b782_ZipCompress; //: io/ZipCompress.java // Использование формата ZIP для сжатия любого // количества файлов, указанных в командной строке. // {Параметры. ZipCompress java} import java.util.zip.*; import java.io.*; import java.util.*; public class ZipCompress { public static void main(String[] args) throws IOException { String path = "src\\main\\java\\brus\\brus_723_System_InputOutput\\b782_ZipCompress\\"; FileOutputStream f = new FileOutputStream(path + "test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of Java Zipping"); // No corresponding getComment(), though. BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(out)); for(String arg : args) { arg = path + arg; print("Writing file " + arg); BufferedReader in = new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while((c = in.read()) != -1) bw.write("IIIIII"); in.close(); out.flush(); } out.close(); // Checksum valid only after the file has been closed! print("Checksum: " + csum.getChecksum().getValue()); // Now extract the files: print("Reading file"); FileInputStream fi = new FileInputStream(path+"test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32()); ZipInputStream in2 = new ZipInputStream(csumi); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while((ze = in2.getNextEntry()) != null) { print("Reading file " + ze); int x; while((x = bis.read()) != -1) System.out.write(x); } if(args.length == 1) print("Checksum: " + csumi.getChecksum().getValue()); bis.close(); // Alternative way to open and read Zip files: ZipFile zf = new ZipFile(path+"test.zip"); Enumeration e = zf.entries(); while(e.hasMoreElements()) { ZipEntry ze2 = (ZipEntry)e.nextElement(); print("File: " + ze2); // ... and extract the data as before } /* if(args.length == 1) */ } public static void print(String s) { System.out.println(s); } } // BufferedWriter bw = new BufferedWriter( // new OutputStreamWriter( // new BufferedOutputStream ( // new ZipOutputStream( // // new CheckedOutputStream(new FileOutputStream(filepath.toFile()), new Adler32()) // // // // // ) // ), // "UTF-8" // ) // ); // public void readZIP () throws FileNotFoundException { // try { // BufferedReader rw = new BufferedReader( // new InputStreamReader( // new ZipInputStream(new FileInputStream(filepath.toFile())), // "UTF-8" // ) // ); // String s = ""; // while ( ( s = rw.readLine()) !=null ) System.out.println(s); // } catch (IOException e) { e.printStackTrace(); } // // }
Java
UTF-8
2,993
2.421875
2
[]
no_license
package com.aidankelly.projectmanager.activities; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.aidankelly.projectmanager.R; import com.aidankelly.projectmanager.entities.UserProject; import com.aidankelly.projectmanager.entities.UserProjectItem; import com.google.android.material.snackbar.Snackbar; public class DeleteConfirmationActivity extends AppCompatActivity { private Button deleteButton; private Button cancelButton; private View rootView; UserProject project; UserProjectItem myItem; Integer dataType; private static final Integer PROJECT_FOR_DELETE = 1; private static final Integer ITEM_OF_PROJECT_FOR_DELETE = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_delete_confirmation); deleteButton = findViewById(R.id.deleteConfirmationDeleteButton); cancelButton = findViewById(R.id.deleteConfirmationCancelButton); rootView = findViewById(android.R.id.content).getRootView(); Intent intentThatCalled = getIntent(); if (getIntent().hasExtra(UserProject.USER_PROJECT_KEY)){ project = (UserProject) intentThatCalled.getSerializableExtra(UserProject.USER_PROJECT_KEY); dataType = PROJECT_FOR_DELETE; } else if (getIntent().hasExtra((UserProjectItem.USER_PROJECT_ITEM_KEY))){ //passed the whole class myItem = (UserProjectItem) intentThatCalled.getSerializableExtra(UserProjectItem.USER_PROJECT_ITEM_KEY); dataType = ITEM_OF_PROJECT_FOR_DELETE; } deleteButton.setOnClickListener(new View.OnClickListener() { // if delete return intent @Override public void onClick(View v) { if (dataType == PROJECT_FOR_DELETE){ Intent goingBackDelete = new Intent(); goingBackDelete.putExtra(UserProject.USER_PROJECT_KEY, project); setResult(RESULT_OK,goingBackDelete); finish(); } else if (dataType == ITEM_OF_PROJECT_FOR_DELETE){ Intent goingBackDeleteItem = new Intent(); goingBackDeleteItem.putExtra(UserProjectItem.USER_PROJECT_ITEM_KEY, myItem); setResult(RESULT_OK,goingBackDeleteItem); finish(); } else { Snackbar.make(rootView, " Error unsure of data to be returned " , Snackbar.LENGTH_SHORT).show(); } } }); cancelButton.setOnClickListener(new View.OnClickListener() { // cancel @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); } }
Python
UTF-8
411
4.40625
4
[]
no_license
# 11. Write a Python program to count the occurrences of each word in a given # sentence def occurance_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts usr_input = input("Enter the Sentance to Cout the Occurance of Word: ") print(occurance_count(usr_input))
C
UTF-8
4,623
2.75
3
[]
no_license
#include "localization.h" // buffer for m_wii data //unsigned int blobs[12] = {355,361,0,358,304,0,423,385,0,403,294,0}; unsigned int blobs[12] = {0,0,0,0,0,0,0,0,0,0,0,0}; unsigned int *x1 = &blobs[0]; unsigned int *y1_ = &blobs[1]; unsigned int *s1 = &blobs[2]; unsigned int *x2 = &blobs[3]; unsigned int *y2 = &blobs[4]; unsigned int *s2 = &blobs[5]; unsigned int *x3 = &blobs[6]; unsigned int *y3 = &blobs[7]; unsigned int *s3 = &blobs[8]; unsigned int *x4 = &blobs[9]; unsigned int *y4 = &blobs[10]; unsigned int *s4 = &blobs[11]; int localize(signed char location[]){ int c = m_wii_read(blobs); // place data in buffer // create array of x and y points // flip the x-points to get right hand coordinate system int X[4] = {-1*(*x1), -1*(*x2) , -1*(*x3) ,-1*(*x4)}; int Y[4] = {*y1_, *y2, *y3, *y4}; if(DEBUG == 1) { m_usb_tx_string("\nreturn value: "); m_usb_tx_int(c); m_usb_tx_string("\nblobs: "); m_usb_tx_int(blobs[0]); m_usb_tx_string(" | "); m_usb_tx_int(X[1]); m_usb_tx_string(" | "); m_usb_tx_int(X[2]); m_usb_tx_string(" | "); m_usb_tx_int(X[3]); m_usb_tx_string(" | "); m_usb_tx_int(Y[0]); m_usb_tx_string(" | "); m_usb_tx_int(Y[1]); m_usb_tx_string(" | "); m_usb_tx_int(Y[2]); m_usb_tx_string(" | "); m_usb_tx_int(Y[3]); m_usb_tx_string("\n"); } // count the # of detected blobs int i = 0; int count = 0; static double theta; while (i < 4){ if (X[i] != -1023 && Y[i] != 1023){ count++; } i++; } if (count < 4) // if # of blobs is less than 4 return (don't change position) { if(DEBUG){ m_usb_tx_string("count 4"); //printf("inside count tin"); } return (int)theta; } // find all possible distances between points (in pixels) int p0[6] = {0,0,0,1,1,2}; int p1[6] = {1,2,3,2,3,3}; int d[6] = {}; int x0_temp = 0; int x1_temp = 0; int y0_temp = 0; int y1_temp = 0; for (i=0; i<6; i++){ x0_temp = X[p0[i]]; y0_temp = Y[p0[i]]; x1_temp = X[p1[i]]; y1_temp = Y[p1[i]]; d[i] = sqrt((pow((x0_temp - x1_temp),2)) + (pow((y0_temp - y1_temp),2))); /* printf("\nx0_temp: %d",x0_temp); printf("\ty0_temp: %d",y0_temp); printf("\tx1_temp: %d",x1_temp); printf("\ty1_temp: %d",y1_temp); printf("\tdist: %d",d[i]); */ } // label points based on max and min distances int max = 0; int min = 1024; int max_points[2] = {0,0}; int min_points[2] = {0,0}; for (i=0; i<6; i++){ if (d[i] < min){ min = d[i]; min_points[0] = p0[i]; min_points[1] = p1[i]; } } for(i=0;i<6;i++) { if (d[i] > max){ max = d[i]; max_points[0] = p0[i]; max_points[1] = p1[i]; } } /* printf("\nx_min_point[0]: %d",X[min_points[0]]); printf("\nx_min_point[1]: %d",X[min_points[1]]); printf("\ny_min_point[0]: %d",Y[min_points[0]]); printf("\ny_min_point[1]: %d",Y[min_points[1]]); printf("\nx_max_point[0]: %d",X[max_points[0]]); printf("\nx_max_point[1]: %d",X[max_points[1]]); printf("\ny_max_point[0]: %d",Y[max_points[0]]); printf("\ny_max_point[1]: %d",Y[max_points[1]]); printf("\nmin_point[0]: %d",min_points[0]); printf("\nmin_point[1]: %d",min_points[1]); printf("\nmax_point[0]: %d",max_points[0]); printf("\nmax_point[1]: %d",max_points[1]); */ int j; int N_i=0,S_i=0; for (i=0; i<2; i++){ for (j=0; j<2; j++){ if (max_points[i] == min_points[j]){ N_i = max_points[i]; S_i = max_points[1-i]; /*printf("\ni: %d",i); printf("\tS_i: %d",S_i); printf("\tN_i: %d",N_i); printf("\tX[N_i]: %d",X[N_i]); printf("\tY[N_i]: %d",Y[N_i]); printf("\tX[N_i]: %d",X[S_i]); printf("\tY[S_i]: %d",Y[S_i]);*/ } } } // Find the center of the constellation and orientation int cx, cy, dir_x, dir_y; cx = abs((X[N_i] + X[S_i])/2); cy = abs((Y[N_i] + Y[S_i])/2); dir_x = X[N_i] - X[S_i]; dir_y = Y[N_i] - Y[S_i]; /*printf("\ncx: %d",cx); printf("\ncy: %d",cy); printf("\nx[ni]: %d",X[N_i]); printf("\ny[ni]: %d",Y[N_i]); printf("\nx[si]: %d",X[S_i]); printf("\ny[si]: %d",Y[S_i]); printf("\nni: %d",N_i); printf("\nsi: %d",S_i); printf("\ndir_x: %d",dir_x); printf("\ndir_y: %d",dir_y);*/ theta = (double)atan2(dir_y,dir_x) - M_PI_2; if(theta < 0) { theta += 2*M_PI; } // Calculate the scale for current image double scale = 29.0 / max; // cm / pix // Find location in global frame int dx = -511 + cx; int dy = 383 - cy; location[0] = dx * scale; location[1] = dy * scale; int loc_tmp = location[0]; location[0] = cos(theta) * location[0] + sin(theta) * location[1]; location[1] = -sin(theta) * loc_tmp + cos(theta) * location[1]; theta *= (180 / M_PI); // convert to degrees return (int)theta; }
C#
UTF-8
4,306
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Xml; using System.IO; namespace ProjectBugzilla { public static class Config { private static Dictionary<string, string> _system; private static string _userConfigFile = "Config\\UserConfig.xml"; private static string _systemConfigFile = "Config\\SystemConfig.xml"; private static Dictionary<string, string> _user; private static bool _init = false; #region Init public static void Init() { _system = new Dictionary<string, string>(); _user = new Dictionary<string, string>(); // DataMapper -> System // "SimpleWizardBugzillaXMLFile -> User // "SimpleWizardProjectFile -> User // "LicenseFile -> SYstem // UpdateURL -> System LoadFile(_system, _systemConfigFile); LoadFile(_user, _userConfigFile); _init = true; } #endregion #region LoadFile public static void LoadFile(Dictionary<string, string> dict, string file) { XmlDocument doc = new XmlDocument(); doc.XmlResolver = null; // Prevents it from searching for the bugzilla dtd (incase it is not accessible. doc.Load(Program.CWD + file); foreach (XmlNode node in doc.SelectNodes("/config/pair")) { dict.Add(node.SelectNodes("key")[0].InnerText, node.SelectNodes("value")[0].InnerText); } } #endregion #region Get/Set public static string GetSystem(string key) { if (false == _init) { Init(); } return _system[key]; } public static string GetUser(string key) { if (false == _init) { Init(); } return _user[key]; } public static void SetUser(string key, string val) { if (false == _init) { Init(); } _user[key] = val; } #endregion #region WriteConfig // We only write user data right now. public static void WriteConfig() { WriteConfig(_user, _userConfigFile); } public static void WriteConfig(Dictionary<string, string> dict, string file) { if (System.IO.File.Exists(Program.CWD + file)) { if (System.IO.File.Exists(Program.CWD + file + ".bu")) System.IO.File.Delete(Program.CWD + file + ".bu"); System.IO.File.Copy(Program.CWD + file, Program.CWD + file + ".bu"); System.IO.File.Delete(Program.CWD + file); } XmlTextWriter writer = null; writer = new XmlTextWriter(Program.CWD + file, null); try { writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.Namespaces = false; writer.WriteStartDocument(); writer.WriteComment("File written on: " + System.DateTime.Now.ToString()); writer.WriteStartElement("", "config", ""); foreach (KeyValuePair<string, string> kvp in dict) { writer.WriteStartElement("", "pair", ""); writer.WriteStartElement("", "key", ""); writer.WriteString(kvp.Key); writer.WriteEndElement(); // </key> writer.WriteStartElement("", "value", ""); writer.WriteString(kvp.Value); writer.WriteEndElement(); // </key> writer.WriteEndElement(); // </pair> } writer.WriteEndElement(); // </config> } catch (Exception error) { Console.WriteLine("Exception: {0}", error.ToString()); } finally { if (writer != null) { writer.Close(); } } } #endregion } }
Shell
UTF-8
5,354
4.0625
4
[ "MIT" ]
permissive
#!/bin/sh # -*- coding: utf-8 -*- # # Dieses Skript erzeugt Differenzbilder (diff) für die # Patgen-Eingabelisten zwischen zwei angegebenen Commits. Wird nur ein # Commit angegeben, wird als Zielcommit "master" verwendet. Die # Ausgabedateien werden als Dateien # # dehyph*-x/<Start-Commit-Hash>-<Ziel-Commit-Hash>.diff # # in Verzeichnissen gespeichert, die der jeweiligen Rechtschreibung # entsprechen. Start- und Ziel-Commit können in jeder gültigen # Git-Syntax angegeben werden. Für die Dateinamen werden die # entsprechenden abgekürzten alphanumerischen Commit-Hashes # verwendet. # # Aufruf: sh diff-patgen-input.sh <start commit> [<ziel commit>] # # # Eingabe: <start commit> Ein Start-Commit. # <ziel commit> Ein optionaler Ziel-Commit. # # Ausgabe: # dehyphn-x/<hashes>.diff Differenzbild refromierte Rechtschreibung # dehypht-x/<hashes>.diff Differenzbild traditionelle Rechtschreibung # dehyphts-x/<hashes>.diff Differenzbild traditionelle Rechtschreibung # in der Schweiz. # if test $# -eq 0 then echo 'usage: diff-patgen-input <start commit> [<target commit>]' echo '' echo 'Create diffs for patgen input lists between <start commit> and' echo '<target commit> (by default "master") and save them as files' echo 'dehyph*-x/<start commit hash>-<target commit hash>.diff in' echo 'directories corresponding to the spelling.' exit 1 fi FROMCOMMIT=$1 if test $# -eq 1 then TOCOMMIT=HEAD else TOCOMMIT=$2 fi typeset GITDATA=`git log -1 --format=%ci-%H $FROMCOMMIT --` FROMDATE=${GITDATA:0:10}+${GITDATA:11:2}-${GITDATA:14:2}-${GITDATA:17:2} FROMHASH=${GITDATA:26} if test -z $FROMHASH then echo 'diff-patgen-input.sh: error identifying start commit hash: ' $FROMCOMMIT exit 1 fi typeset GITDATA=`git log -1 --format=%ci-%H $TOCOMMIT --` TODATE=${GITDATA:0:10}+${GITDATA:11:2}-${GITDATA:14:2}-${GITDATA:17:2} TOHASH=${GITDATA:26} if test -z $TOHASH then echo 'diff-patgen-input.sh: error identifying target commit hash: ' $TOCOMMIT exit 1 fi # Change to repository root directory. Double quotes are intentional to # avoid an empty argument to cd. cd "`git rev-parse --show-toplevel`" # Write all output to a single top-level directory. typeset OUTPUTDIR="+++diff-patgen-input+++" # Function definition. If not already present, place a copy of a # commit's working copy in a directory 'wl-<commit hash>'. get_working_copy() { typeset commit=$1 commitdate=$2 typeset commitdir=${OUTPUTDIR}/$commitdate-$commit if test ! -d $commitdir then git archive --format=tar --prefix=$commitdir/ $commit | tar xf - fi } # Function definition. create_patgen_list() { typeset commit=$1 commitdate=$2 patgenlist=$3 typeset commitdir=${OUTPUTDIR}/$commitdate-$commit echo "Making ${commit:0:7} file $patgenlist." if test ! -e $commitdir/$patgenlist then # 'make -C $commitdir $patgenlist' doesn't work reliably on Git # for Windows shell. (cd $commitdir && make $patgenlist > /dev/null) fi } # Function definition. diff_patgen_list() { typeset fromcommit=$1 fromcommitdate=$2 tocommit=$3 tocommitdate=$4 dehyph=$5 spell=$6 typeset fromcommitdir=${OUTPUTDIR}/$fromcommitdate-$fromcommit tocommitdir=${OUTPUTDIR}/$tocommitdate-$tocommit patgenlist=$dehyph/words.hyphenated.$spell difffile=${fromcommit:0:7}-${tocommit:0:7}.diff create_patgen_list $fromcommit $fromcommitdate $patgenlist create_patgen_list $tocommit $tocommitdate $patgenlist if test ! -d ${OUTPUTDIR}/$dehyph; then mkdir ${OUTPUTDIR}/$dehyph; fi diff $fromcommitdir/$patgenlist $tocommitdir/$patgenlist > ${OUTPUTDIR}/$dehyph/$difffile gawk -f skripte/diff-patgen-input.awk -v ftr=daten/german.tr ${OUTPUTDIR}/$dehyph/$difffile } # Function definition. count_differences() { typeset fromcommit=$1 tocommit=$2 dehyph=$3 variety=$4 summaryfile=$5 typeset difffile=${fromcommit:0:7}-${tocommit:0:7}.diff n_added=`wc -l ${OUTPUTDIR}/$dehyph/$difffile.added` n_added=${n_added%% *} n_removed=`wc -l ${OUTPUTDIR}/$dehyph/$difffile.removed` n_removed=${n_removed%% *} n_hyph=`wc -l ${OUTPUTDIR}/$dehyph/$difffile.hyph` n_hyph=${n_hyph%% *} printf " %-21s %11d %8d %10d\n" "${variety}" $n_added $n_removed $n_hyph >> ${summaryfile} } echo "Diff'ing patgen input files." printf "from: %7s %10s %s\n" ${FROMHASH:0:7} ${FROMDATE:0:10} $FROMCOMMIT printf "to: %7s %10s %s\n" ${TOHASH:0:7} ${TODATE:0:10} $TOCOMMIT # Get commit's working copies. get_working_copy $FROMHASH $FROMDATE get_working_copy $TOHASH $TODATE # Diff patgen lists. diff_patgen_list $FROMHASH $FROMDATE $TOHASH $TODATE dehypht-x trad diff_patgen_list $FROMHASH $FROMDATE $TOHASH $TODATE dehyphts-x swiss diff_patgen_list $FROMHASH $FROMDATE $TOHASH $TODATE dehyphn-x refo # Write summary file. typeset SUMMARYFILE=${OUTPUTDIR}/CHANGES.table.txt echo " Rechtschreibung hinzugefügt entfernt korrigiert" > $SUMMARYFILE echo " ---------------------------------------------------------------" >> $SUMMARYFILE count_differences $FROMHASH $TOHASH dehypht-x "traditionell (DE, AT)" $SUMMARYFILE count_differences $FROMHASH $TOHASH dehyphts-x "traditionell (CH)" $SUMMARYFILE count_differences $FROMHASH $TOHASH dehyphn-x "reformiert" $SUMMARYFILE
Shell
UTF-8
313
3.09375
3
[ "BSD-3-Clause" ]
permissive
#!/bin/sh if [ -z "$MMDAPP" ] ; then set -e export MMDAPP="$( cd $(dirname "$0")/../../../../../.. ; pwd )" echo "$0: Working in: $MMDAPP" >&2 [ -d "$MMDAPP/source" ] || ( echo "expecting 'source' directory." >&2 && exit 1 ) fi "$MMDAPP/source/myx/myx.distro-prepare/sh-scripts/RebuildSourceActions.fn.sh"
Java
UTF-8
663
3.921875
4
[]
no_license
package Unit5.ForEach; // Поиск в массиве с использованием расширенного цикла for public class Search { public static void main(String[] args) { int[] num = {6, 8, 3, 7, 5, 6, 1, 4}; int val = 5; boolean found = false; // Использование цикла for-each для поиска // переменной val в массиве num for (int x : num) { if (x == val) { found = true; break; } } if (found) System.out.println("Значение найдено!"); } }
Python
UTF-8
298
2.5625
3
[]
no_license
""" Name : 4375OS_09_02_payoff2.py Book : Python for Finance Publisher: Packt Publishing Ltd. Author : Yuxing Yan Date : 12/26/2013 email : yany@canisius.edu paulyxy@hotmail.com """ s = arange(10,80,5) x=30 y=(abs(s-x)+s-x)/2 ylim(-10,50) plot(s,y) show()
Java
UTF-8
443
3.203125
3
[]
no_license
package ru.geekbrains.lesson1.homework; public class Element<Type> { private Type element; public Element(Type obj) { this.element = obj; } public void setElement(Type element) { this.element = element; } public Type getElement() { return element; } public void showType() { System.out.println("Тип Type: " + element.getClass().getName()); } }
Markdown
UTF-8
1,620
3.125
3
[]
no_license
# Python-Utility-Script-for-INFO-I535 This script is used in the course to download, extract, transform and load NOAA Storm events dataset into MongoDB. It will also create two directories - landDir and extractDir in the script path. Commands: 1. To see its usage, you can also use the following command: > python project_utilities.py help 2. To download the data, you need to specify a year range after the download keyword > python project_utilities.py download <start year> <end year> 3. To extract the CSV files from GZ files into "extractDir" directory. > python project_utilities.py extract 4. The data comes in the CSV format and needs to be converted to JSON to be loaded into MongoDB. We can also specify the columns to keep by prividing a comma separated list of columns as the argument. The argument “chunksize” allows to stage the transformation and work with very large files. Chunk size allows to specify a number of rows that will be transformed per file in one go. For example, a file with 100,000 rows will be transformed into 4 json files if chunk size is set to 25,000. > python project_utilities.py <comma separated list of columns> <chunksize> To keep all the columns, you can run the command as follows: > python project_utilities.py transform <chunksize> 5. To load the data into MongoDB use below command: > python project_utilities.py load <hostname> <port> <database> <collection> <username> <password> 6. To cleanup directories - landDir and extractDir, use below command: > python project_utilities.py cleanup <dirname> or to cleanup both > python project_utilities.py cleanup
Ruby
UTF-8
420
2.8125
3
[]
no_license
class TurntableBot def message user, with pm user.id, with end def someone_messaged phrase, &block on :pmmed do |message| phrase = [phrase] if [String, Regexp].include? phrase.class phrase.each do |listen_for| if listen_for.match message.text message.parts = message.text.match listen_for block.call message break end end end end end
C#
UTF-8
877
2.5625
3
[ "MIT" ]
permissive
using Consul; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Adnc.Infra.Consul.Consumer { public class ServiceConsumer { public static async Task<List<string>> GetServicesAsync(string consulAddress, string serviceName) { var consulClient = new ConsulClient(configuration => { configuration.Address = new Uri(consulAddress); }); var result = await consulClient.Catalog.Service(serviceName); if (result == null || result.Response == null || result.Response.Length < 1) return null; var list = new List<string>(); foreach (var item in result.Response) { list.Add($"{item.ServiceAddress}:{item.ServicePort}"); } return list; } } }
C
UTF-8
22,733
3.34375
3
[]
no_license
#include "stringv.h" #include <assert.h> #include <string.h> /* block_pos is an integral quantity that uniquely determines a block in a * stringv. It is defined in terms of a string_pos because in a one-to-one * stringv (ie. stringv->block_used == stringv->string_count) a string_pos * and block_pos may be used interchangeably. Otherwise, a string_pos must be * converted into a block_pos through the function string_pos_to_block_pos. */ typedef string_pos block_pos; /* A block_ptr is simply a pointer to char, but is distinguished syntactically * with the promise that is points to the start of a block. */ typedef char *block_ptr; /* The following functions are only called in assert expressions. If NDEBUG * is defined, the asserts compile to no-ops but the declarations (and * definitions) of these functions would remain. This may cause strict * compiles to issue a warning for an unused function. This way, these * functions are only present when the corresponding asserts are. */ #ifndef NDEBUG /* Checks that a stringv is valid. */ static int valid_stringv(struct stringv const *s); /* Checks that a block_pos is valid, given the corresponding stringv. */ static int valid_block_pos(struct stringv const *s, block_pos bn); /* Checks that the block range specified by [first, last) is valid */ static int valid_block_range( struct stringv const *s, block_pos first, block_pos last); #endif /* NDEBUG */ /* Checks that a string_pos is valid, given the corresponding stringv. A * string_pos is valid for *reads* if it is in the interval * [0, s->string_count). However, a string_pos is valid for *writes* if it is * in the interval [0, s->string_count], since a write at the * (s->string_count)th position is equivalent to (and treated as) a push back. */ static int valid_string_pos(struct stringv const *s, string_pos sn, int read); /* Given a string_pos, returns the corresponding block pos. */ static block_pos string_pos_to_block_pos( struct stringv const *s, string_pos sn); /* Given a block_pos, returns the corresponding address of the start of that * block. */ static block_ptr block_pos_to_block_ptr(struct stringv const *s, block_pos bn); /* Returns a pointer to the string determined by the given string_pos. This * is essentially a composition of string_pos_to_block_pos and * block_pos_to_block_ptr. */ static block_ptr string_pos_to_block_ptr( struct stringv const *s, string_pos sn); /* Returns 1 if the stringv is one-to-one (ie. string_count == block_used). * Functions operating on stringv work optimally when the stringv is one-to- * one. */ static int is_one_to_one(struct stringv const *s); /* Clears the block range [first, last) by filling each block in the range * with zeros. Returns first. */ static block_pos clear_block_range( struct stringv *s, block_pos first, block_pos last); /* Determines how many blocks would be required to store the given length * of data (in chars; NOT including the NUL terminator) in the given * stringv. */ static int blocks_required(struct stringv const *s, size_t length); /* Determines if a given block is terminal. A block is terminal if it is * terminated with one or more NUL characters. Terminal blocks end multi- * block strings. */ static int is_block_terminal(struct stringv const *s, block_pos bn); /* Determines how many blocks are used by the string located at the given * string_pos. */ static int blocks_used_by(struct stringv const *s, string_pos sn); /* Copies blocks from a source stringv to a destination stringv assuming that * source and destination have identical block sizes and destination has * the same or a higher block total. Returns the number of strings copied * (which is always equal to source->string_count). */ static int copy_blockwise_bijective( struct stringv *STRINGV_RESTRICT dest, struct stringv const *STRINGV_RESTRICT source); /* Copies blocks from a source stringv to a destination stringv assuming that * the source stringv has as many blocks as strings, and the destination * stringv has the same or greater block size. Returns the number of strings * copied (which is always equal to source->string_count). */ static int copy_blockwise_injective( struct stringv *STRINGV_RESTRICT dest, struct stringv const *STRINGV_RESTRICT source); /* Copies strings from a source stringv to a destination stringv. Returns the * number of strings copied, which may be less than the source's string count * depending on the destination stringv's block size and block total. */ static int copy_stringwise( struct stringv *STRINGV_RESTRICT dest, struct stringv const *STRINGV_RESTRICT source); /* Shifts a range of blocks by the given offset. The offset may be negative * (indicating a left shift) or positive (indicating a right shift). In the * case of a right shift, the gap created is zeroed. Note that a right shift * will leave the stringv in an undefined state (due to internal zero blocks) * that must be resolved immediately by writing to this space. For a right * shift, the block position of the start of the gap is returned. For a left * shift, the block position of the end of the block range is returned. */ static block_pos shift_blocks( struct stringv *s, block_pos first, block_pos last, int offset); /* Writes data to the given block position, returning a pointer to that same * block. This function does no bounds checking, nor does it zero the remain- * der of the block. Both of these conditions are assumed. */ static block_ptr block_write( struct stringv *STRINGV_RESTRICT s, char const *STRINGV_RESTRICT string, size_t length, block_pos first, block_pos last); struct stringv *stringv_init( struct stringv *stringv, char *buf, int buf_size, int block_size) { if (!stringv || !buf || buf_size <= 1 || block_size <= 1 || block_size > buf_size) { return NULL; } stringv->buf = buf; stringv->block_total = buf_size / block_size; stringv->block_size = block_size; stringv->block_used = stringv->string_count = 0; clear_block_range(stringv, 0, stringv->block_total); return stringv; } char const *stringv_get(struct stringv const *stringv, string_pos sn) { if (!stringv || !valid_string_pos(stringv, sn, 1)) { return NULL; } assert(valid_stringv(stringv)); return string_pos_to_block_ptr(stringv, sn); } struct stringv *stringv_clear(struct stringv *stringv) { if (stringv) { assert(valid_stringv(stringv)); clear_block_range(stringv, 0, stringv->block_total); stringv->block_used = stringv->string_count = 0; } return stringv; } int stringv_copy(struct stringv *dest, struct stringv const *source) { if (!dest || !source) { return 0; } assert(valid_stringv(dest)); assert(valid_stringv(source)); /* The destination needs to be cleared. */ stringv_clear(dest); /* If the source stringv is empty, then we don't need to do anything. */ if (source->string_count == 0) { return 0; } /* If the destination stringv has the same block size, then we can just * memcpy the entire block over if it also has a greater than or equal * block total. */ if (dest->block_size == source->block_size && dest->block_total >= source->block_used) { return copy_blockwise_bijective(dest, source); } /* If the destination stringv has a block size greater than or equal to the * source's block size, each source string fits in a single source block, * and there are at least as many total destination blocks as there are * used source blocks, then we don't need to compute the length of each * string before copying, as we know all strings will fit. */ if (dest->block_size >= source->block_size && is_one_to_one(source) && dest->block_total >= source->block_used) { return copy_blockwise_injective(dest, source); } return copy_stringwise(dest, source); } char const *stringv_push_back( struct stringv *stringv, char const *string, size_t length) { int blocks_req = 0; if (!stringv || !string || length == 0) { return NULL; } assert(valid_stringv(stringv)); /* push_back can't be implemented in terms of insert because insert defers * to push_back as a special case. Indeed, push_back is far simpler to * implement than insert with the only common code being the block * capacity check. */ blocks_req = blocks_required(stringv, length); if (stringv->block_used + blocks_req > stringv->block_total) { return NULL; } /* If there is enough room, all we need to do is write to the end of the * stringv and bump the string and block counts as appropriate. */ return block_write( stringv, string, length, stringv->block_used, stringv->block_used + blocks_req); } char const *stringv_push_front( struct stringv *stringv, char const *string, size_t length) { return stringv_insert(stringv, string, length, 0); } char const *stringv_insert( struct stringv *stringv, char const *string, size_t length, string_pos sn) { int blocks_req = 0; block_pos write_pos = 0; if (!stringv || !string || length <= 0 || !valid_string_pos(stringv, sn, 0)) { return NULL; } assert(valid_stringv(stringv)); /* An insertion at the end of the stringv is equivalent to a push_back. * This also handles insertions into an empty stringv */ if (sn == stringv->string_count) { return stringv_push_back(stringv, string, length); } /* Ensure there is sufficient room in the stringv */ blocks_req = blocks_required(stringv, length); if (stringv->block_used + blocks_req > stringv->block_total) { return NULL; } assert(blocks_req != 0); /* We know that the insertion is occurring internally, so we will need * to shift blocks *right* to accomodate this. We also know that there * is sufficient space to do so. */ write_pos = shift_blocks( stringv, string_pos_to_block_pos(stringv, sn), stringv->block_used, blocks_req); return block_write( stringv, string, length, write_pos, write_pos + blocks_req); } size_t stringv_split_c( struct stringv *stringv, char const *string, size_t length, int separator) { char const *first = NULL, *last = NULL; char const *const end = string + length; if (!stringv || !string || length <= 0) { return 0; } first = string; while (first != end + 1) { last = strchr(first, separator); if (!last) { last = end; } if (last > first) { if (!stringv_push_back(stringv, first, (size_t)(last - first))) { return (size_t)(first - string); } } first = last + 1; } return length; } size_t stringv_split_s( struct stringv *stringv, char const *string, size_t length, char const *separator, size_t separator_length) { char const *first = NULL, *last = NULL; char const *const end = string + length; if (!stringv || !string || length <= 0 || !separator || separator_length <= 0) { return 0; } if (length == 1) { return stringv_split_c(stringv, string, length, *separator); } first = string; while (first != end + 1) { last = strstr(first, separator); if (!last) { last = end; } if (last > first) { if (!stringv_push_back(stringv, first, (size_t)(last - first))) { return (size_t)(first - string); } } if (last == end) { first = end + 1; } else { first = last + separator_length; } } return length; } int stringv_remove(struct stringv *stringv, string_pos sn) { block_pos bn = 0; int offset = 0; if (!stringv || !valid_string_pos(stringv, sn, 1) || stringv->string_count == 0) { return 0; } /* If there is only one string in the stringv, then it is the one specified * by sn since the string pos is valid for reads. So clear the stringv. */ if (stringv->string_count == 1) { (void)stringv_clear(stringv); return 1; } bn = string_pos_to_block_pos(stringv, sn); assert(valid_block_pos(stringv, bn)); /* Otherwise, if the string position refers to the string at the end of the * stringv, then we can rewind the stringv's block_used field and clear * the end of the buffer. This way we avoid shifting blocks. */ if (sn == stringv->string_count - 1) { /* Clear the last string. clear_block_range returns bn, which * will be the number of used blocks in the stringv after the last * string is removed. */ stringv->block_used = clear_block_range( stringv, bn, stringv->block_used); --stringv->string_count; return 1; } /* Finally, if the insertion is internal (there are strings to the right * of the string we want to remove) then we can shift the blocks over the * string to be removed. We first compute the shift offset, which is the * number of blocks used by the string to remove. */ offset = blocks_used_by(stringv, sn); clear_block_range( stringv, shift_blocks(stringv, bn + offset, stringv->block_used, -offset), stringv->block_used); --stringv->string_count; stringv->block_used -= offset; return 1; } char const *stringv_begin(struct stringv const *stringv) { assert(stringv); assert(valid_stringv(stringv)); return stringv->buf; } char const *stringv_end(struct stringv const *stringv) { assert(stringv); assert(valid_stringv(stringv)); return stringv->buf + (stringv->block_size * stringv->block_used); } char const *stringv_next(struct stringv const *stringv, char const *iter) { assert(stringv); assert(valid_stringv(stringv)); assert(iter); do { iter += stringv->block_size; } while (*(iter - 1) != '\0'); return iter; } #ifndef NDEBUG int valid_stringv(struct stringv const *s) { return s && s->buf && s->block_total > 0 && s->block_size > 0 && s->block_used >= 0 && s->block_used <= s->block_total && s->string_count >= 0 && s->string_count <= s->block_total; } int valid_block_pos(struct stringv const *s, block_pos bn) { /* A block pos is valid if it is in the interval [0, s->block_total]. The * right end of the interval includes the block total since block positions * can be used as ranges, and we want to allow one-past-the-end positions * to make range arithmetic simpler. */ return bn >= 0 && bn <= s->block_total; } int valid_block_range(struct stringv const *s, block_pos first, block_pos last) { return s && valid_block_pos(s, first) && (valid_block_pos(s, last) || last == s->block_used) && (first < last); } #endif /* NDEBUG */ int valid_string_pos(struct stringv const *s, string_pos sn, int read) { return sn >= 0 && (read ? sn < s->string_count : sn <= s->string_count); } block_pos string_pos_to_block_pos(struct stringv const *s, string_pos sn) { block_pos bn = 0; assert(s && valid_stringv(s)); assert(valid_string_pos(s, sn, 0)); /* The first string always starts at the start of the stringv's buffer. */ if (sn == 0) { return 0; } /* If the stringv's string count is equal to the number of used blocks, * then the block position corresponding to any string position is simply * that string position. */ if (is_one_to_one(s)) { return sn; } while (sn > 0) { if (is_block_terminal(s, bn)) { --sn; } ++bn; } assert(sn == 0); return bn; } block_ptr block_pos_to_block_ptr(struct stringv const *s, block_pos bn) { assert(s && valid_stringv(s)); assert(valid_block_pos(s, bn)); return s->buf + bn * s->block_size; } block_ptr string_pos_to_block_ptr(struct stringv const *s, string_pos sn) { return block_pos_to_block_ptr( s, string_pos_to_block_pos(s, sn)); } int is_one_to_one(struct stringv const *s) { assert(s && valid_stringv(s)); return s->string_count == s->block_used; } block_pos clear_block_range(struct stringv *s, block_pos first, block_pos last) { assert(s && valid_stringv(s)); assert(valid_block_range(s, first, last)); memset(block_pos_to_block_ptr(s, first), 0, (last - first) * s->block_size); return first; } int blocks_required(struct stringv const *s, size_t length) { assert(s && valid_stringv(s)); assert(length != 0); /* Increment the length to accomodate the NUL character. All strings * in a stringv are NUL terminated (with at least one NUL terminator, * by design. */ ++length; return (int)((length / (size_t)s->block_size) + (length % (size_t)s->block_size != 0)); } int is_block_terminal(struct stringv const *s, block_pos bn) { assert(s && valid_stringv(s)); assert(valid_block_pos(s, bn)); return is_one_to_one(s) || *(block_pos_to_block_ptr(s, bn) + s->block_size - 1) == '\0'; } int blocks_used_by(struct stringv const *s, string_pos sn) { block_pos bn = 0; int i = 0; assert(s && valid_stringv(s)); assert(valid_string_pos(s, sn, 1)); /* If the stringv has the same number of strings as it does used blocks, * then all strings necessarily occupy a single block */ if (is_one_to_one(s)) { return 1; } /* Otherwise, we iterate through the blocks until we find a terminal block. * This (by definition) ends the string). */ bn = string_pos_to_block_pos(s, sn); while (!is_block_terminal(s, bn + i)) { ++i; } return i; } int copy_blockwise_bijective( struct stringv *dest, struct stringv const *source) { assert(dest && valid_stringv(dest)); assert(source && valid_stringv(source)); assert(source->block_size == dest->block_size); assert(source->block_used <= dest->block_total); memcpy(dest->buf, source->buf, source->block_size * source->block_used); dest->string_count = source->string_count; dest->block_used = source->block_used; return dest->string_count; } int copy_blockwise_injective( struct stringv *dest, struct stringv const *source) { string_pos i = 0; assert(dest && valid_stringv(dest)); assert(source && valid_stringv(source)); assert(is_one_to_one(source)); assert(source->block_size <= dest->block_size); for (i = 0; i < source->string_count; ++i) { /* We know that each string in the source stringv occupies exactly * one block in the destination stringv. So we copy each string * over to each block. Instead of computing the strings length with * strlen, we just copy source->block_size - 1 characters since the * string lengths are bounded by this value. */ memcpy( block_pos_to_block_ptr(dest, i), block_pos_to_block_ptr(source, i), source->block_size - 1); } dest->string_count = dest->block_used = source->string_count; return dest->string_count; } int copy_stringwise(struct stringv *dest, struct stringv const *source) { char const *ith_string = NULL; size_t ith_length = 0; string_pos i = 0; int blocks_req = 0; assert(dest && valid_stringv(dest)); assert(source && valid_stringv(source)); for (i = 0; i < source->string_count; ++i) { /* We don't know whether the source string will fit in the destination * stringv, so we need to compute the length of each string, * determine how many blocks it uses, and bail out if the required * number of blocks is greater than the available blocks in dest. */ ith_string = string_pos_to_block_ptr(source, i); ith_length = strlen(ith_string); blocks_req = blocks_required(dest, ith_length); /* If there is insufficient room, stop copying */ if (dest->block_used + blocks_req > dest->block_total) { break; } /* Otherwise, copy the string over */ memcpy( block_pos_to_block_ptr(dest, dest->block_used), ith_string, ith_length); /* And increment the string and block counters */ dest->block_used += blocks_req; ++dest->string_count; } return dest->string_count; } block_pos shift_blocks( struct stringv *s, block_pos first, block_pos last, int offset) { assert(s && valid_stringv(s)); assert(valid_block_range(s, first, last)); assert(offset != 0); memmove( block_pos_to_block_ptr(s, first + offset), block_pos_to_block_ptr(s, first), (last - first) * s->block_size); if (offset < 0) { /* If the offset is negative, then the shift is a left shift. * We return the block position of the end of the shifted range. */ return last + offset; } else { /* Otherwise, the offset is positive and the shift is a right shift. * We return the block position of the start of the gap that we just * created from the shift after zeroing it out. */ clear_block_range(s, first, first + offset); return first; } } block_ptr block_write( struct stringv *s, char const *string, size_t length, block_pos first, block_pos last) { block_ptr write_ptr = NULL; assert(s && valid_stringv(s)); assert(string); assert(length > 0); assert(valid_block_range(s, first, last)); write_ptr = memcpy(block_pos_to_block_ptr(s, first), string, length); s->block_used += (last - first); ++s->string_count; return write_ptr; }
Python
UTF-8
378
3.671875
4
[]
no_license
def dec2(func9): def wrapper(a,b): print('The first argument is'+str(a)) print('The second argument is'+str(b)) rez = func9(a,b) return rez return wrapper @dec2 def func9(a,b): x = b / a return x a = int(input('input a: ')) b =int(input('input b: ')) res = func9(a,b) print('Result is:'+str(res))
Java
UTF-8
890
2.625
3
[]
no_license
package com.shizuku.mail.core.pop3; import com.shizuku.mail.util.EmailAddress; /** * This is an interface to define some functions about the pop users * who are online. */ public interface Pop3User { /** * Check user is online or not. A user can't login two times at the same * time before logout. * @param emailAddress User emailAddress Object * @return If current user is online, return true. Otherwise return false. */ public boolean isOnline(EmailAddress emailAddress); /** * When a user login, don't lock he or she until it QUIT or connectless. * @param emailAddress User emailAddress Object */ public void lockUser(EmailAddress emailAddress); /** * When a user logout or connectless, unlock it. * @param emailAddress User emailAddress Object */ public void unlockUser(EmailAddress emailAddress); }
C++
UTF-8
2,613
3.46875
3
[]
no_license
/* * @lc app=leetcode.cn id=299 lang=cpp * * [299] 猜数字游戏 * 4.20 每日一题 */ // @lc code=start #include<string> #include<unordered_map> using namespace std; class Solution { public: string getHint(string secret, string guess) { #if 0 /*方法一:hash_map --8ms 解题思路: 情况一:数字相同位置相同,比较容易统计,两string中逐个元素对比就行 情况二:数字相同位置不同,可用map查询来实现 步骤: 1.比较string,统计数字相同位置相同的数量,同时把secret存入map; 2.map查询,统计guess字符在map中出现次数; 3.剔除情况一在步骤2中统计的次数; 步骤2具体操作: 把sectret存入map,每个元素的value置1; guess字符在map中查询,查到就返回1,查不到则返回0; TC:O(n) SC:O(n) */ int acnt = 0; int bcnt = 0; unordered_map<char, int> um; for (int i = 0; i < secret.size(); i++) { um[secret[i]]++; //string每个元素作为key存入map,value均设为1 acnt += (secret[i] == guess[i]); } for (auto& c : guess) { bcnt += (um[c]-- > 0); //字符能否在map中查到,能查到则 } bcnt -= acnt; //注意减去数字相同且位置相同的情况 return to_string(acnt) + "A" + to_string(bcnt) + "B"; #endif #if 1 /*方法二:数组,bucket --4ms 思路:两个长度为10的数组作为两组bucket,对应0~9 除了数字相同且位置相同字符之外(计入An),其它字符放入bucket内进行计数 累加两组bucket的较小计数值,得到Bn 时间复杂度:O(n) 空间复杂度:O(1) */ int aCnt = 0; int bCnt = 0; vector<int> sVec(10, 0); // 0 ~ 9 for secret vector<int> gVec(10, 0); // 0 ~ 9 for guess if (secret.size() != guess.size() || secret.empty()) { return "0A0B"; } for (int i = 0; i < secret.size(); ++i) { char c1 = secret[i]; char c2 = guess[i]; if (c1 == c2) { ++aCnt; } else { ++sVec[c1-'0']; ++gVec[c2-'0']; } } // count b for (int i = 0; i < sVec.size(); ++i) { bCnt += min(sVec[i], gVec[i]); } return to_string(aCnt) + 'A' + to_string(bCnt) + 'B'; #endif } }; // @lc code=end
C#
UTF-8
2,684
3.265625
3
[]
no_license
using MovieListingsApp.Contracts.Services; using MovieListingsApp.Core.Contracts.Repositories; using MovieListingsApp.Entities; using MovieListingsApp.Models.MovieModels; using System; using System.IO; using System.Threading.Tasks; namespace MovieListingsApp.Services { public class MoviesService : IMoviesService { private readonly IMoviesRepository _moviesRepository; public MoviesService(IMoviesRepository moviesRepository) { _moviesRepository = moviesRepository; } /// <summary> /// Creates a Movie Listing and adds the requried Actors and Thumbnails. /// </summary> /// <param name="createViewModel">View Model for a Movie.</param> /// <returns>Movie Id: if succesfully created a movie listing; /// -1: otherwise.</returns> public async Task<int> CreateAsync(CreateViewModel createViewModel) { try { var movie = new TblMovie { Title = createViewModel.Title.Trim(), Description = createViewModel.Description.Trim(), Year = createViewModel.Year.Value, }; foreach(var actor in createViewModel.Actors) { movie.MovieActors.Add(new TblMovieActor { ActorId = actor }); } foreach (var thumbnail in createViewModel.Thumbnails) { if (thumbnail != null) { var fileName = Path.GetFileName(thumbnail.FileName); using (var memoryStream = new MemoryStream()) { thumbnail.InputStream.CopyTo(memoryStream); var movieThumbnail = new TblMovieThumbnail { ContentType = thumbnail.ContentType, FileName = fileName, Content = memoryStream.ToArray(), TimeStampUtc = DateTime.UtcNow, }; movie.Thumbnails.Add(movieThumbnail); } } } _moviesRepository.Add(movie); await _moviesRepository.SaveAsync(); return movie.Id; } catch (Exception) { // log exception return -1; } } } }
C#
UTF-8
1,651
2.5625
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-2-Clause", "MIT" ]
permissive
using System; using System.IO; using System.Text; using Newtonsoft.Json; using Wirehome.Core.Hardware.MQTT; namespace Wirehome.Core.MessageBus; public sealed class MessageBusSender { readonly MemoryStream _buffer = new(); readonly MqttService _mqttService; public MessageBusSender(MqttService mqttService) { _mqttService = mqttService ?? throw new ArgumentNullException(nameof(mqttService)); } public bool PublishToMqtt { get; set; } public void TrySend(MessageBusMessage messageBusMessage) { if (!PublishToMqtt) { return; } if (messageBusMessage == null) { throw new ArgumentNullException(nameof(messageBusMessage)); } try { lock (_buffer) { // _buffer.Seek(0, SeekOrigin.Begin); // _buffer.SetLength(0); // // MessagePackSerializer.Serialize(_buffer, messageBusMessage); // var buffer = _buffer.GetBuffer(); // var bufferLength = (int)_buffer.Length; // // var mqttPayload = new ArraySegment<byte>(buffer, 0, bufferLength).ToArray(); _mqttService.Publish(new MqttPublishParameters { Topic = "wirehome/message_bus", Payload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageBusMessage)) }); } } catch (Exception exception) { // Logging is not possible here! Console.Write(exception); } } }
Java
UTF-8
1,316
3.828125
4
[]
no_license
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; /** * Escribir un programa que en el método main, solicite un nombre y muestre "Hola <nombre * ingresado>" y debajo, la fecha y hora actual con el siguiente formato de ejemplo "viernes * 20/04/2018 18:00". Validar que el mensaje no se muestre hasta tanto no se haya ingresado un * nombre. */ /** * @author Javier Mora * */ public class Main { /** * Main function * @param args */ public static void main(String[] args) { String name = getString("Enter your name: "); System.out.println("Hello " + name); System.out.println("Now is: " + formatDate(new Date())); } /** * Formats the passed date * @param date The date * @return The formatted date */ private static String formatDate(Date date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); return simpleDateFormat.format(date); } /** * Ask the user for a string * @param message The message to show to the user * @return The entered string */ private static String getString(String message) { @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); String str; do { System.out.print(message); str = scanner.nextLine(); } while (str.isEmpty()); return str; } }
Java
UTF-8
9,254
1.789063
2
[]
no_license
package se.kth.livetech.presentation.layout; import java.awt.AlphaComposite; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.JPanel; import se.kth.livetech.blackmagic.MagicComponent; import se.kth.livetech.communication.RemoteTime; import se.kth.livetech.contest.graphics.ICPCColors; import se.kth.livetech.contest.model.Contest; import se.kth.livetech.contest.model.ContestUpdateEvent; import se.kth.livetech.contest.model.ContestUpdateListener; import se.kth.livetech.presentation.graphics.RenderCache; import se.kth.livetech.properties.IProperty; import se.kth.livetech.properties.PropertyListener; import se.kth.livetech.util.DebugTrace; import se.kth.livetech.util.TeamReader; @SuppressWarnings("serial") public class LivePresentation extends JPanel implements ContestUpdateListener, MagicComponent { IProperty base; List<ContestUpdateListener> sublisteners = new ArrayList<ContestUpdateListener>(); Component currentView; List<PropertyListener> propertyListeners; IProperty modeProp, clearProp, oldProp; public static class Blank extends JPanel implements MagicComponent { IProperty base; public Blank(IProperty base) { this.base = base; this.setBackground(ICPCColors.COLOR_KEYING); } @Override public void paintComponent(Graphics gr) { paintComponent(gr, this.getWidth(), this.getHeight()); } public void paintComponent(Graphics gr, int W, int H) { if (!this.base.get("greenscreen").getBooleanValue()) { Graphics2D g = (Graphics2D) gr; g.setPaint(ICPCColors.TRANSPARENT_GREEN); g.setComposite(AlphaComposite.Src); g.fillRect(0, 0, W, H); g.setComposite(AlphaComposite.SrcOver); } else { super.paintComponent(gr); } } } private Blank blankView; public Component getCurrentView() { return this.currentView; } public LivePresentation(Contest c, IProperty base, RemoteTime time, JFrame mainFrame) { this.setLayout(null); //absolute positioning of subcomponents this.blankView = new Blank(base); final ScoreboardPresentation scoreboard = new ScoreboardPresentation(c, time, base); TeamReader teamReader; this.modeProp = base.get("mode"); this.clearProp = base.get("clear"); this.oldProp = base.get("old_views"); try { teamReader = new TeamReader("images/teams2010.txt"); } catch (IOException e) { teamReader = null; } final TeamPresentation teamPresentation = new TeamPresentation(c, base, teamReader); final CountdownPresentation countdown = new CountdownPresentation(time, base); final VNCPresentation vnc = new VNCPresentation(base); final VLCView cam = new VLCView(base, mainFrame); final ClockView clockPanel = new ClockView(base.get("clockrect"), c, time); final LogoPresentation logoPanel = new LogoPresentation(LogoPresentation.Logo.icpc, base); final InterviewPresentation interview = new InterviewPresentation(c, base); final WinnerPresentation winnerPresentation = new WinnerPresentation(base); final JudgeQueueTest judgeQueue = new JudgeQueueTest(); final LayoutPresentation layout = new LayoutPresentation(c, base); this.sublisteners.add(scoreboard); this.sublisteners.add(teamPresentation); this.sublisteners.add(clockPanel); this.sublisteners.add(winnerPresentation); this.sublisteners.add(judgeQueue); this.sublisteners.add(layout); this.add(clockPanel); //always there on top this.add(logoPanel); this.add(judgeQueue); judgeQueue.setVisible(false); this.currentView = scoreboard; this.add(this.currentView); this.validate(); this.base = base; this.propertyListeners = new ArrayList<PropertyListener>(); PropertyListener modeChange = new PropertyListener() { @Override public void propertyChanged(IProperty changed) { DebugTrace.trace("Changed %s -> %s", changed, changed.getValue()); cam.deactivate(); if (LivePresentation.this.currentView != null) { LivePresentation.this.remove(LivePresentation.this.currentView); } String mode = LivePresentation.this.modeProp.getValue(); boolean clear = LivePresentation.this.clearProp.getBooleanValue(); boolean oldViews = LivePresentation.this.oldProp.getBooleanValue(); if (!oldViews) { LivePresentation.this.currentView = layout; if (!layout.setView(mode)) { oldViews = true; } } if (clear) { LivePresentation.this.currentView = LivePresentation.this.blankView; } else if (oldViews) { if (mode.equals("layout")) { LivePresentation.this.currentView = layout; } else if (mode.equals("vnc")) { LivePresentation.this.currentView = vnc; } else if(mode.equals("score")) { LivePresentation.this.currentView = scoreboard; } else if(mode.equals("blank")) { LivePresentation.this.currentView = LivePresentation.this.blankView; } else if(mode.equals("interview")) { LivePresentation.this.currentView = interview; } else if(mode.equals("team")) { LivePresentation.this.currentView = teamPresentation; } else if (mode.equals("logo")) { LivePresentation.this.currentView = logoPanel; } else if(mode.equals("cam")) { cam.activate(); } else if(mode.equals("countdown")) { LivePresentation.this.currentView = countdown; } else if(mode.equals("award")) { LivePresentation.this.currentView = winnerPresentation; } else { LivePresentation.this.currentView = LivePresentation.this.blankView; } } if (LivePresentation.this.currentView != null) { LivePresentation.this.add(LivePresentation.this.currentView); } vnc.connect(); validate(); repaint(); } }; PropertyListener toggleClock = new PropertyListener() { @Override public void propertyChanged(IProperty changed) { boolean visible = changed.getBooleanValue(); clockPanel.setVisible(visible); } }; PropertyListener toggleLogo = new PropertyListener() { @Override public void propertyChanged(IProperty changed) { boolean visible = !changed.getBooleanValue(); logoPanel.setVisible(visible); } }; PropertyListener toggleQueue = new PropertyListener() { @Override public void propertyChanged(IProperty changed) { DebugTrace.trace("toggling queue"); boolean visible = changed.getBooleanValue(); judgeQueue.setVisible(visible); } }; PropertyListener noFps = new PropertyListener() { @Override public void propertyChanged(IProperty changed) { boolean visible = !changed.getBooleanValue(); scoreboard.setShowFps(visible); } }; this.propertyListeners.add(modeChange); this.propertyListeners.add(toggleClock); this.propertyListeners.add(toggleLogo); this.propertyListeners.add(noFps); this.propertyListeners.add(toggleQueue); this.modeProp.addPropertyListener(modeChange); this.clearProp.addPropertyListener(modeChange); base.get("show_clock").addPropertyListener(toggleClock); base.get("show_nologo").addPropertyListener(toggleLogo); base.get("nofps").addPropertyListener(noFps); base.get("show_queue").addPropertyListener(toggleQueue); this.validate(); } @Override public void paintComponent(Graphics g) { RenderCache.setQuality((Graphics2D)g); } @Override public void paintChildren(Graphics gr) { super.paintChildren(gr); repaint(); } @Override public void paintComponent(Graphics gr, int W, int H) { RenderCache.setQuality((Graphics2D)gr); //this.component.setBounds(0, 0, W, H); this.currentView.setSize(W, H); if (!(this.currentView instanceof MagicComponent)) { this.currentView.paint(gr); int n = this.getComponentCount(); for (int i = 0; i < n; ++i) { Component ci = this.getComponent(i); if (ci != null && ci != this.currentView && ci.isVisible()) { //ci.setBounds(0, 0, W, H); ci.setSize(W, H); ci.paint(gr); } } } else { // TODO: de-duplicate code MagicComponent mc = (MagicComponent) this.currentView; Graphics2D g = (Graphics2D) gr; AffineTransform a = (AffineTransform) g.getTransform().clone(); g.setPaint(ICPCColors.TRANSPARENT_GREEN); g.setComposite(AlphaComposite.Src); g.fillRect(0, 0, W, H); g.setComposite(AlphaComposite.SrcOver); //System.err.println("magic paintComponent " + (this.currentView)); mc.paintComponent(gr, W, H); int n = this.getComponentCount(); for (int i = 0; i < n; ++i) { Component ci = this.getComponent(i); if (ci != null && ci != this.currentView && ci.isVisible()) { if (ci instanceof MagicComponent) { MagicComponent mci = (MagicComponent) ci; g.setTransform(a); mci.paintComponent(gr, W, H); } } } } } @Override public void contestUpdated(ContestUpdateEvent e) { for (ContestUpdateListener l : this.sublisteners) { l.contestUpdated(e); } } @Override public void invalidate() { for (Component c : this.getComponents()) { c.setBounds(LivePresentation.this.getBounds()); } this.repaint(); } @Override public boolean isOptimizedDrawingEnabled() { return false; } }
JavaScript
UTF-8
3,439
3
3
[]
no_license
var bgImages= [ 'https://assets.codepen.io/t-1/maksim-larin-jZyacqaR4iI-unsplash.jpg', 'https://assets.codepen.io/t-1/daniel-storek-JM-qKEd1GMI-unsplash.jpg', 'https://assets.codepen.io/t-1/felipepelaquim-6zO5VKogoZE-unsplash.jpg', ]; var offer = document.getElementById("offer"); var offerHeader = document.getElementById("offer-header"); var itemIndex = 1; showItems(itemIndex); function plusItem(n) { showItems(itemIndex += n); } function currentItem(n) { showItems(itemIndex = n); } function showItems(n) { var i; var items = document.getElementsByClassName("item"); var bg = document.getElementById("bg-container"); if (n > items.length) {itemIndex = 1} if (n < 1) {itemIndex = items.length} for (i = 0; i < items.length; i++) { items[i].style.display = "none"; ; } if(itemIndex === 2){ offer.style.color ="black"; offerHeader.style.color ="black"; } else{ offer.style.color ="whitesmoke"; offerHeader.style.color ="whitesmoke"; } items[itemIndex-1].style.display = "flex"; bg.style.backgroundImage = `url(${bgImages[itemIndex-1]})` }; /* Here set the magnify glass */ function magnify(imgID, zoom) { var img, glass, w, h, bw; img = document.getElementById(imgID); /*create magnifier glass:*/ glass = document.createElement("DIV"); glass.setAttribute("class", "img-magnifier-glass"); /*insert magnifier glass:*/ img.parentElement.insertBefore(glass, img); /*set background properties for the magnifier glass:*/ glass.style.backgroundImage = "url('" + img.src + "')"; glass.style.backgroundRepeat = "no-repeat"; glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px"; bw = 3; w = glass.offsetWidth / 2; h = glass.offsetHeight / 2; /*execute a function when someone moves the magnifier glass over the image:*/ glass.addEventListener("mousemove", moveMagnifier); img.addEventListener("mousemove", moveMagnifier); /*and also for touch screens:*/ glass.addEventListener("touchmove", moveMagnifier); img.addEventListener("touchmove", moveMagnifier); function moveMagnifier(e) { var pos, x, y; /*prevent any other actions that may occur when moving over the image*/ e.preventDefault(); /*get the cursor's x and y positions:*/ pos = getCursorPos(e); x = pos.x; y = pos.y; /*prevent the magnifier glass from being positioned outside the image:*/ if (x > img.width - (w / zoom)) {x = img.width - (w / zoom);} if (x < w / zoom) {x = w / zoom;} if (y > img.height - (h / zoom)) {y = img.height - (h / zoom);} if (y < h / zoom) {y = h / zoom;} /*set the position of the magnifier glass:*/ glass.style.left = (x - w) + "px"; glass.style.top = (y - h) + "px"; /*display what the magnifier glass "sees":*/ glass.style.backgroundPosition = "-" + ((x * zoom) - w + bw) + "px -" + ((y * zoom) - h + bw) + "px"; } function getCursorPos(e) { var a, x = 0, y = 0; e = e || window.event; /*get the x and y positions of the image:*/ a = img.getBoundingClientRect(); /*calculate the cursor's x and y coordinates, relative to the image:*/ x = e.pageX - a.left; y = e.pageY - a.top; /*consider any page scrolling:*/ x = x - window.pageXOffset; y = y - window.pageYOffset; return {x : x, y : y}; } } magnify("product-image1",2) // magnify("product-image2",2) // magnify("product-image3",2)
C++
UTF-8
1,648
3.078125
3
[]
no_license
// https://leetcode.com/problems/range-sum-query-mutable/ // segment tree class NumArray { public: vector<int> tree; int get_mid(int a, int b) { return a + (b - a) / 2; } int query(int index, int s, int e, int qs, int qe) { if (s >= qs and e <= qe) return tree[index]; if (e < qs or s > qe) return 0; int mid = get_mid(s, e); int leftAns = query(2 * index + 1, s, mid, qs, qe); int rightAns = query(2 * index + 2, mid + 1, e, qs, qe); return leftAns + rightAns; } void update(int index, int s, int e, int pos, int val) { if (s == e) { tree[index] = val; return;} int mid = get_mid(s, e); if (pos <= mid) update(2 * index + 1, s, mid, pos, val); else update(2 * index + 2, mid + 1, e, pos, val); tree[index] = tree[2 * index + 1] + tree[2 * index + 2]; } void createSortedArray(vector<int>& nums) { long long n = 1e5 + 1, len = nums.size(); for (int i = 0; i < len; i++) update(0, 0, n, i, nums[i]); } NumArray(vector<int>& nums) { tree.clear(); tree.resize(262145); createSortedArray(nums); } void update(int index, int val) { long long n = 1e5 + 1; update(0, 0, n, index, val); } int sumRange(int left, int right) { long long n = 1e5 + 1; return query(0, 0, n, left, right); } }; /** * Your NumArray object will be instantiated and called as such: * NumArray* obj = new NumArray(nums); * obj->update(index,val); * int param_2 = obj->sumRange(left,right); */
Go
UTF-8
3,195
2.609375
3
[]
no_license
package control import ( "net/http" "net/http/httptest" "testing" "github.com/rabelais88/portfolio2020/api/constants" "github.com/rabelais88/portfolio2020/api/app" "github.com/gavv/httpexpect/v2" "github.com/rabelais88/portfolio2020/api/model" ) func TestGetArticle(t *testing.T) { handler, db := mountTestApp() server := httptest.NewServer(handler) defer server.Close() defer db.Close() e := httpexpect.WithConfig(httpexpect.Config{ BaseURL: server.URL, Reporter: httpexpect.NewAssertReporter(t), Printers: []httpexpect.Printer{ httpexpect.NewDebugPrinter(t, true), }, }) p := model.Post{} app.MakeFakeData(db) db.Last(&p) e.GET(`/article`).WithQuery("id", p.ArticleID).Expect().Status(http.StatusOK) e.GET(`/article`).Expect().Status(http.StatusBadRequest) e.GET(`/article`).WithQuery("id", "12$$&A").Expect().Status(http.StatusBadRequest) } func TestGetArticles(t *testing.T) { handler, db := mountTestApp() server := httptest.NewServer(handler) defer server.Close() defer db.Close() e := httpexpect.WithConfig(httpexpect.Config{ BaseURL: server.URL, Reporter: httpexpect.NewAssertReporter(t), Printers: []httpexpect.Printer{ httpexpect.NewDebugPrinter(t, true), }, }) app.MakeFakeData(db) ps := []model.Article{} db.Where(&model.Article{Type: constants.ARTICLES.POST}).Find(&ps) as := []model.Article{} db.Find(&as) e.GET(`/articles`).Expect().Status(http.StatusOK) e.GET(`/articles`).WithQuery("sort", "abce1234").Expect().Status(http.StatusOK) e.GET(`/articles`).WithQuery("order", "asc").Expect().Status(http.StatusOK) e.GET(`/articles`).WithQuery("order", "wrongorder").Expect().Status(http.StatusBadRequest) e.GET(`/articles`).Expect().Status(http.StatusOK).JSON().Object().ValueEqual("count", len(as)) e.GET(`/articles`).WithQuery("type", "POST").Expect().Status(http.StatusOK).JSON().Object().ValueEqual("count", len(ps)) e.GET(`/articles`).WithQuery("type", "MEDIA").Expect().Status(http.StatusOK).JSON().Object().ValueEqual("count", 0) db.Create(&model.Article{ Title: "testTitle", }) e.GET(`/articles`).Expect().Status(http.StatusOK).JSON().Object().Value("list").Array().First().Object().ValueEqual("title", "testTitle") tag := model.Tag{} db.Take(&tag) e.GET(`/articles`).WithQuery("tag", tag.Value).Expect().Status(http.StatusOK) } func TestDeleteArticle(t *testing.T) { handler, db := mountTestApp() server := httptest.NewServer(handler) defer server.Close() defer db.Close() e := httpexpect.WithConfig(httpexpect.Config{ BaseURL: server.URL, Reporter: httpexpect.NewAssertReporter(t), Printers: []httpexpect.Printer{ httpexpect.NewDebugPrinter(t, true), }, }) app.MakeFakeData(db) ps := []model.Post{} var beforeCount int db.Find(&ps).Count(&beforeCount) // db.Limit(2).Find(&ps) e.DELETE(`/auth/article`).WithQuery("articleId", "totallywrongid").Expect().Status(http.StatusBadRequest) e.DELETE(`/auth/article`).WithQuery("articleId", ps[0].ArticleID).Expect().Status(http.StatusOK) var afterCount int db.Find(&ps).Count(&afterCount) if afterCount >= beforeCount { t.Errorf("count before %d count after %d - record not deleted", beforeCount, afterCount) } }
Swift
UTF-8
3,853
2.796875
3
[]
no_license
// // ViewControllerTemp.swift // Nutrient+ // // Created by Huanlei Wu on 10/20/19. // Copyright © 2019 Robert Sato. All rights reserved. // // Followed "iOS Text Field Tutorial - Accepting User Input" by Code Pro // local database tutorial: https:// stackoverflow.com/questions/28628225/how-to-save-local-data-in-a-swift-app // // For birthday date user input tutorial: // https: //www.youtube.com/watch?v=kML_2TkWEsk import Foundation import UIKit //struct defaultsKeys { // static let heightKey = "" // static let weightKey = "" // static let bodyFatKey = "" //} class Startup: UIViewController { @IBOutlet weak var heightField: UITextField! @IBOutlet weak var weightField: UITextField! @IBOutlet weak var bodyFatField: UITextField! @IBOutlet weak var birthdayField: UITextField! @IBOutlet weak var Gender: UISegmentedControl! @IBOutlet weak var heightUnit: UISegmentedControl! @IBOutlet weak var weightUnit: UISegmentedControl! var birthdate: Date! override func viewDidLoad() { super.viewDidLoad() // setting the height, weight, and body fat fields to themselves to be able to manipulate variable heightField.delegate = self weightField.delegate = self bodyFatField.delegate = self // creating instance of date instance let datePicker = UIDatePicker() // set datepicker mode to date to just show date datePicker.datePickerMode = UIDatePicker.Mode.date // whenever datePicker value is changed, datePickerValueChanged function triggered datePicker.addTarget(self, action: #selector(Startup.datePickerValueChanged(sender:)), for: UIControl.Event.valueChanged) // show changed date in text field birthdayField.inputView = datePicker // store birthday to save in Core Data later birthdate = datePicker.date // Do any additional setup after loading the view, typically from a nib } @IBAction func storeVar(_ sender: Any) { // creating a user instance let user = User(context: PersistenceService.context) let savingInfo = SaveUserInfo() // storing data into Core Data only when fields aren't empty savingInfo.saveUserInfo(heightField: heightField, weightField: weightField, bodyFatField: bodyFatField, sex: Gender, birthdayField: birthdayField, heightUnit: heightUnit, weightUnit: weightUnit, userInfo: user, birthdate: birthdate, vc: self, segueIdentifier: "fieldsComplete") UserDefaults.standard.set(true, forKey: "userInfoExists") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // when touch outside number pad field, number pad disappears heightField.resignFirstResponder() weightField.resignFirstResponder() bodyFatField.resignFirstResponder() birthdayField.resignFirstResponder() view.endEditing(true) } @objc func datePickerValueChanged(sender: UIDatePicker) { // create DateFormatter instance let formatter = DateFormatter() formatter.dateStyle = DateFormatter.Style.medium // don't show time, only date formatter.timeStyle = DateFormatter.Style.none birthdayField.text = formatter.string(from: sender.date) birthdate = sender.date } } extension Startup: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { // when text field is tapped, it is a first responder: accepting events, waiting for user input // resignFirstResponder() dismisses action hierarchy: text field disappear from view textField.resignFirstResponder() return true } }
Java
UTF-8
3,687
2.03125
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright 2013-2018 Guardtime, Inc. * * This file is part of the Guardtime client SDK. * * 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, CONDITIONS, OR OTHER LICENSES OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * "Guardtime" and "KSI" are trademarks or registered trademarks of * Guardtime, Inc., and no license to trademarks is granted; Guardtime * reserves and retains all trademark rights. */ package com.guardtime.envelope.signature.ksi; import com.guardtime.envelope.extending.ExtendingPolicy; import com.guardtime.envelope.signature.EnvelopeSignature; import com.guardtime.envelope.signature.SignatureException; import com.guardtime.envelope.signature.SignatureFactory; import com.guardtime.envelope.signature.SignatureFactoryType; import com.guardtime.envelope.util.Util; import com.guardtime.ksi.Reader; import com.guardtime.ksi.Signer; import com.guardtime.ksi.exceptions.KSIException; import com.guardtime.ksi.hashing.DataHash; import com.guardtime.ksi.unisignature.KSISignature; import java.io.InputStream; /** * Implementation of the {@link SignatureFactory} that uses KSI {@link Signer} and {@link Reader} * for the underlying signature handling logic. */ public class KsiSignatureFactory implements SignatureFactory { private static final KsiSignatureFactoryType SIGNATURE_FACTORY_TYPE = new KsiSignatureFactoryType(); private final Signer signer; private final Reader reader; public KsiSignatureFactory(Signer signer, Reader reader) { this.signer = signer; this.reader = reader; } @Override public KsiEnvelopeSignature create(DataHash hash) throws SignatureException { Util.notNull(signer, "Signer"); Util.notNull(hash, "DataHash"); try { KSISignature signature = signer.sign(hash); return new KsiEnvelopeSignature(signature); } catch (KSIException e) { throw new SignatureException(e); } } @Override public KsiEnvelopeSignature read(InputStream input) throws SignatureException { Util.notNull(reader, "Reader"); Util.notNull(input, "Input stream"); try { KSISignature signature = reader.read(input); return new KsiEnvelopeSignature(signature); } catch (KSIException e) { throw new SignatureException(e); } } @Override public void extend(EnvelopeSignature envelopeSignature, ExtendingPolicy extender) throws SignatureException { if (unsupportedEnvelopeSignature(envelopeSignature)) { throw new SignatureException("Unsupported EnvelopeSignature provided for extending."); } KsiEnvelopeSignature ksiEnvelopeSignature = (KsiEnvelopeSignature) envelopeSignature; KSISignature extendedSignature = (KSISignature) extender.getExtendedSignature(ksiEnvelopeSignature.getSignature()); ksiEnvelopeSignature.setExtendedSignature(extendedSignature); } private boolean unsupportedEnvelopeSignature(EnvelopeSignature envelopeSignature) { return !(envelopeSignature instanceof KsiEnvelopeSignature); } @Override public SignatureFactoryType getSignatureFactoryType() { return SIGNATURE_FACTORY_TYPE; } }
PHP
ISO-8859-2
1,498
2.609375
3
[]
no_license
<?php /** * Hunting z Stats Output als XMP-File * @package zorg\Games\HuntingZ */ /** * File includes */ require_once dirname(__FILE__).'/../includes/config.inc.php'; require_once INCLUDES_DIR.'mysql.inc.php'; require_once INCLUDES_DIR.'util.inc.php'; $ge = $db->query( "SELECT g.id, if(sum(a.score)-g.z_score > g.z_score, 'i', 'z') winner, u.username mrz FROM hz_players p, hz_games g, hz_aims a, user u WHERE g.id=p.game AND p.type='z' AND g.state='finished' AND a.map=g.map AND u.id=p.user GROUP BY g.id" , __FILE__, __LINE__ ); $user = array(); while ($g = $db->fetch($ge)) { $t = $db->fetch($db->query("SELECT * FROM hz_tracks WHERE player='z' AND game=$g[id] ORDER BY nr DESC LIMIT 0,1", __FILE__, __LINE__)); if ($g['winner']=='z') $user['wins'][$g['mrz']]++; $user['games'][$g['mrz']]++; $user['turns'][$g['mrz']] += $t['nr']; $user['mrz'][$g['mrz']] = $g['mrz']; } foreach ($user['games'] as $key=>$val) { $user['wins'][$key] = $user['wins'][$key] / $user['games'][$key] * 100; $user['turns'][$key] /= $user['games'][$key]; } array_multisort($user['turns'], SORT_DESC, SORT_NUMERIC); print_array($user); echo '<xmp>'; echo text_width("User", 11).text_width("Siege", 7)."Durchschnittliche Anz. Zge pro Game\n"; echo "==========================================================\n"; foreach ($user['turns'] as $key=>$val) { echo text_width($user['mrz'][$key], 11).text_width(round($user['wins'][$key]).'%', 7).round($user['turns'][$key], 2)."\n"; } echo '</xmp>';
Go
UTF-8
1,693
3.015625
3
[]
no_license
package gojs import ( "fmt" "github.com/dop251/goja" "reflect" ) type JSObject struct { j *JSRunner obj *goja.Object } func (jo *JSObject) Call(method string, args ...interface{}) (goja.Value, error) { met := jo.obj.Get(method) if met == nil { return nil, fmt.Errorf("Got nil value for %s ", method) } var fn goja.Callable err := jo.j.vm.ExportTo(met, &fn) if err != nil { return nil, err } var vargs []goja.Value for _, a := range args { vargs = append(vargs, jo.j.vm.ToValue(a)) } return fn(jo.obj, vargs...) } func (jo *JSObject) CallReturningObj(method string, args ...interface{}) (*JSObject, error) { v, err := jo.Call(method, args...) if err != nil { return nil, err } robj := v.ToObject(jo.j.vm) return &JSObject{jo.j, robj}, nil } func (jo *JSObject) CallReturningStr(method string, args ...interface{}) (string, error) { v, err := jo.Call(method, args...) if err != nil { return "", err } return v.String(), nil } func (jo *JSObject) GetNumber(name string) (int64, error) { v := jo.obj.Get(name) if v == nil { return 0, fmt.Errorf("Got nil value for %s ", name) } if v.ExportType() != reflect.TypeOf(int64(0)) { return 0, fmt.Errorf("The variable %s is not number type", name) } return v.ToInteger(), nil } func (jo *JSObject) GetString(name string) (string, error) { v := jo.obj.Get(name) if v == nil { return "", fmt.Errorf("Got nil value for %s ", name) } return v.String(), nil } func (jo *JSObject) GetObject(name string) (*JSObject, error) { obj := jo.obj.Get(name) if obj == nil { return nil, fmt.Errorf("Got nil value for %s ", name) } robj := obj.ToObject(jo.j.vm) return &JSObject{jo.j, robj}, nil }
Java
UTF-8
1,739
3.859375
4
[ "MIT" ]
permissive
package models.classes; import java.util.Objects; /** * This represents a 2D dimension (X, Y). */ public class Position { private int x, y; /** * Generates a {@link Position} without coordinates. */ public Position() { } /** * Generates a {@link Position} with x and y coordinates. * @param x X coordinate. * @param y Y coordinate. */ public Position(int x, int y) { this.setX(x); this.setY(y); } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(this.getX(),this.getY()); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj instanceof Position) { Position connectionObj = (Position) obj; return (this.getX() == connectionObj.getX() && this.getY() == connectionObj.getY()); } return false; } /* * * GETTERS AND SETTERS * */ /** * Gets the X coordinate of the {@link Position}. * @return The X coordinate of the {@link Position}. */ public int getX() { return x; } /** * Sets the X coordinate of the {@link Position}. * @param x The X coordinate of the {@link Position} to be set. */ public void setX(int x) { this.x = x; } /** * Gets the Y coordinate of the {@link Position}. * @return The Y coordinate of the {@link Position}. */ public int getY() { return y; } /** * Sets the Y coordinate of the {@link Position}. * @param y The Y coordinate of the {@link Position} to be set. */ public void setY(int y) { this.y = y; } }
SQL
UTF-8
582
3.078125
3
[]
no_license
SELECT A.ORDER_ID, A.SERIAL_NUMBER, A.USER_ID, A.ADD_MONTH, A.ADD_DATE, A.ADD_TIME, A.ADD_WHOLE_DATE, A.GIVE_POINT, A.PERIOD_OF_VALIDITY, A.ACTIVITY_ID, A.ACTIVITY_TITLE, A.REMARKS FROM TL_B_WECHAT_SCORE A WHERE A.USER_ID = :USER_ID AND A.ADD_MONTH = TO_NUMBER(TO_CHAR(TO_DATE( :BEGIN_DATE, 'YYYY-MM-DD HH24:MI:SS'),'MM')) AND A.ADD_WHOLE_DATE>= TO_DATE( :BEGIN_DATE, 'YYYY-MM-DD HH24:MI:SS') AND A.ADD_WHOLE_DATE<= TO_DATE( :END_DATE, 'YYYY-MM-DD HH24:MI:SS') ORDER BY A.ADD_WHOLE_DATE DESC
C++
UTF-8
457
2.96875
3
[]
no_license
class Solution { public: int searchInsert(vector<int>& A, int target) { int size = A.size(); if( !size ) return 0; int l,m,r; l = 0; r = size - 1; while(l <= r) { m = (l + r) >> 1; if( A[m] == target ) return m; else if(A[m] > target) r = m - 1; else l = m + 1; } return l; } };
Markdown
UTF-8
17,304
2.984375
3
[ "MIT" ]
permissive
Описание задач, решение которых приведено в данном репозитории: 1. Создать массив 10×10, присвоить его элементам случайные значения в интервале от 0 до 10. Вывести массив на экран. Запросить у пользователя число Х, уточнив, что его значение должно находиться в интервале от 1 до 10. Если пользователь вводит Х меньше 1, либо больше 10 – вывести на экран надпись «некорректный ввод данных» и прервать выполнение программы. Если элемент массива равен Х – возвести этот элемент в квадрат. Если элемент массива меньше Х – возвести этот элемент в степень Х. Если элемент массива больше Х – удвоить этот элемент. Результат – новый массив 10×10 вывести на экран. 2. Программа генерирует 2 последовательности из 20 случайных чисел в диапазоне от 0 до 100 и выводит их на экран. Затем она выводит на экран отсортированные по возрастанию последовательности, сформированные по десяткам из элементов двух исходных (последовательность чисел от 0 до 9, затем – от 10 до 19, затем – от 20 до 29 и т.д.) и подсчитывает количество чисел в каждой последовательности. После этого программа вычисляет процентное соотношение количества чисел в полученных последовательностях к суммарному количеству чисел и выводит результат на экран. 3. Запросить у пользователя координаты опорной точки в трехмерной системе координат. Запросить у пользователя количество вспомогательных точек, уточнив, что оно должно быть не менее 10. Если пользователь вводит число меньше 10 – вывести на экран надпись «некорректный ввод данных» и прервать выполнение программы. Программа генерирует случайным образом координаты вспомогательных точек в трехмерной системе координат и выводит их на экран. Затем программа выбирает две вспомогательные точки, которые образуют с опорной точкой треугольник с наименьшим периметром, и выводит на экран их номера. 4. Создать массив 4×4, присвоить его элементам случайные значения в интервале от 0 до 16. Вывести массив на экран. Подсчитать количество чисел в массиве (количество нулей, единиц, двоек, троек и т.д.) Вывести на экран соответствующий количествам повторов одномерный массив из 17 элементов. Определить число, которое повторяется в исходном массиве наиболее часто. Подсчитать сумму элементов исходного массива и среднеквадратическую величину элементов получившегося одномерного массива. Формула среднеквадратической величины ![equation][1] 5. Создать программу, выполняющую следующие действия: Запросить у пользователя последовательность чисел, значения которых должны находится в интервале от 1 до 10. Если пользователь вводит число меньше 1, либо больше 10 – вывести на экран надпись «некорректный ввод данных» и прервать выполнение программы. Найти среднегеометрическую величину последовательности ![equation][2] и вывести её на экран. Переставить элементы последовательности следующим образом: пара «минимальный элемент – максимальный элемент»; пара «минимальный элемент – максимальный элемент» из оставшихся; пара «минимальный элемент – максимальный элемент» из оставшихся и т.п. 6. Запросить у пользователя координаты опорной точки в трехмерной системе координат. Запросить у пользователя количество вспомогательных точек, уточнив, что оно должно быть не менее 10. Если пользователь вводит число меньше 10 – вывести на экран надпись «некорректный ввод данных» и прервать выполнение программы. Программа генерирует случайным образом координаты вспомогательных точек в трехмерной системе координат и выводит их на экран. Затем программа выбирает вспомогательную точку, наиболее удаленную от опорной. После чего программа выбирает вспомогательную точку, сумма расстояний от которой до двух выбранных - максимальна. На экран выводятся расстояния между тремя выбранными точками. 7. Создать массив А (5×5), присвоить его элементам случайные значения в интервале от 0 до 10. Вывести массив на экран. Создать одномерный массив В из пяти элементов. Запросить у пользователя значения элементов массива В, уточнив, что их значения должны находиться в интервале от 1 до 10. Если пользователь вводит число меньше 1, либо больше 10 – вывести на экран надпись «некорректный ввод данных» и прервать выполнение программы. Создать массив С (5×5), значения элементов которого вычислить по следующей формуле: ![equation][3] Вывести массив С на экран. 8. Создать программу, выполняющую следующие действия: Запросить у пользователя последовательность чисел, значения которых должны находится в интервале от 1 до 20. Если пользователь вводит число меньше 1, либо больше 20 – вывести на экран надпись «некорректный ввод данных» и прервать выполнение программы. Определить количество простых чисел в последовательности. Вывести на экран две подпоследовательности: - последовательность чисел, не являющихся простыми, отсортированных по возрастанию. - последовательность простых чисел, отсортированных по убыванию. 9. Запросить у пользователя координаты опорной точки в трехмерной системе координат. Запросить у пользователя количество вспомогательных точек, уточнив, что оно должно быть не менее 10. Если пользователь вводит число меньше 10 – вывести на экран надпись «некорректный ввод данных» и прервать выполнение программы. Программа генерирует случайным образом координаты вспомогательных точек в трехмерной системе координат и выводит их на экран. Затем программа определяет радиус шара с центром в опорной точке так, чтобы внутри него находилось 50% всех вспомогательных точек. 10. Создать массив 10×10, присвоить его элементам случайные значения в интервале от 0 до 100. Вывести массив на экран. Определить столбец массива с наименьшей суммой элементов и отобразить массив относительно этого столбца. Определить среднеквадратическую величину элементов выбранного столбца. Формула среднеквадратической величины: ![equation][1] 11. Программа генерирует 2 последовательности из 20 случайных чисел в диапазоне от 1 до 30 и выводит их на экран. Затем она объединяет их в одну последовательность, удаляет из неё все числа, которые повторяются более двух раз, и выводит её на экран. Программа определяет среднегармоническую величину элементов получившейся последовательности и выводит её на экран. Формула среднегармонической величины: ![equation][4] 12. Запросить у пользователя координаты опорной точки в двухмерной системе координат и радиус окружности с центром в данной точке. Запросить у пользователя количество вспомогательных точек, уточнив, что оно должно быть не менее 10. Если пользователь вводит число меньше 10 – вывести на экран надпись «некорректный ввод данных» и прервать выполнение программы. Программа генерирует случайным образом координаты вспомогательных точек в двухмерной системе координат, выводит их на экран и запрашивает у пользователя радиусы окружностей с центрами в этих точках. Затем программа определяет количество окружностей, которые пересекают окружность с центром в опорной точке, и сообщает номера этих окружностей. 13. Создать массив10×10, присвоить его элементам случайные значения в интервале от 0 до 100 и вывести массив на экран. Поменять местами строки и столбцы и вывести новый массив на экран. Определить среднегеометрическую величину всех простых чисел в массиве и определить максимальное из них. Вывести на экран результат подсчета. Формула среднегеометрической величины: ![equation][2] 14. Запросить у пользователь количество чисел в последовательности, указав, что их должно быть не менее 20. Если пользователь вводит число меньше 20 – вывести на экран надпись «некорректный ввод данных» и прервать выполнение программы. Программа генерирует последовательность из случайных чисел в диапазоне от 0 до 30 и выводит её на экран. Затем она выводит на экран все подпоследовательности, лежащие между соседними нулями. Если в последовательности нет двух нулей, вывести на экран ноль и прервать выполнение программы. Программа определяет сумму номеров (из исходной последовательности) элементов каждой подпоследовательности и выводит её на экран. 15. Запросить у пользователя координаты опорной точки в двухмерной системе координат. Запросить у пользователя количество вспомогательных точек, уточнив, что оно должно быть не менее 10. Если пользователь вводит число меньше 10 – вывести на экран надпись «некорректный ввод данных» и прервать выполнение программы. Программа генерирует случайным образом координаты вспомогательных точек в двухмерной системе координат и выводит их на экран. Затем программа определяет наименьший угол, образованный двумя векторами из опорной точки в две вспомогательные точки. Формула угла между двумя векторами a и b: ![equation][5] 16. Создать массив10×10, присвоить его элементам случайные значения в интервале от 1 до 100 и вывести массив на экран. Вывести на экран квадраты 2×2 из исходного массива в порядке возрастания сумм их элементов. Определить среднегармоническую величину этих сумм. Формула среднегармонической величины: ![equation][4] [1]: https://latex.codecogs.com/svg.latex?%7B%5Ccolor%7BPink%7Dsqrt%281/n%5Ccdot%28x_1%5E2&plus;x_2%5E2&plus;...&plus;x_n%5E2%29%29%7D [2]: https://latex.codecogs.com/svg.latex?%7B%5Ccolor%7BPink%7D%5Csqrt%5Bn%5D%28x_1%5Ccdot%20x_2%5Ccdot%20...%20%5Ccdot%20x_n%29%7D [3]: https://latex.codecogs.com/svg.latex?%7B%5Ccolor%7BPink%7DC%5Bi%2Cj%5D%3DA%5Bi%2Cj%5D%5Ccdot%28B%5Bj%5D%29%5Ei%7D [4]: https://latex.codecogs.com/svg.latex?%7B%5Ccolor%7BPink%7D%5Cfrac%7Bn%7D%7B%5Cfrac%7B1%7D%7Bx_1%7D&plus;%5Cfrac%7B1%7D%7Bx_2%7D%20&plus;%20...%20&plus;%5Cfrac%7B1%7D%7Bx_n%7D%20%7D%7D [5]: https://latex.codecogs.com/svg.latex?%7B%5Ccolor%7BPink%7D%5Calpha%3Darccos%28%5Cfrac%7B%7Ca_x%20%5Ccdot%20b_x%20&plus;%20a_y%20%5Ccdot%20b_y%7C%7D%7B%5Csqrt%28a_x%5E2&plus;a_y%5E2%29%20%5Ccdot%20%5Csqrt%28b_x%5E2&plus;b_y%5E2%29%7D%29%7D
Python
UTF-8
3,709
3.03125
3
[]
no_license
import csv from appl.domainmodel.movie import Movie from appl.domainmodel.genre import Genre from appl.domainmodel.actor import Actor from appl.domainmodel.director import Director # noinspection DuplicatedCode class MovieFileCSVReader: dataset_of_movies: list dataset_of_actors: set dataset_of_directors: set dataset_of_genres: set filename: str def __init__(self, file_name: str): self.__dataset_of_genres = set() self.__dataset_of_directors = set() self.__dataset_of_actors = set() self.__dataset_of_movies = list self.__file_name = file_name # noinspection PyUnusedLocal def read_csv_file(self): # noinspection SpellCheckingInspection with open(self.__file_name, mode='r', encoding='utf-8-sig') as csvfile: movie_file_reader = csv.DictReader(csvfile) self.__dataset_of_movies = [] self.__dataset_of_actors = set() self.__dataset_of_directors = set() self.__dataset_of_genres = set() index = 0 for row in movie_file_reader: rank = row['Rank'] title = row['Title'] director = row['Director'] actor = row['Actors'] release_year = int(row['Year']) genre = row['Genre'] genre_list = genre.split(",") genre_list = [Genre(item.strip()) for item in genre_list] for item in genre_list: if item not in self.__dataset_of_genres: # or len(self.__dataset_of_genres) == 0: self.__dataset_of_genres.add(item) actor_list = actor.split(",") actor_list = [Actor(item.strip()) for item in actor_list] for item in actor_list: if item not in self.__dataset_of_actors: # or len(self.__dataset_of_actors) == 0: self.__dataset_of_actors.add(item) movie_object = Movie(title, release_year) if movie_object not in self.__dataset_of_movies: # or len(self.__dataset_of_movies) == 0: self.__dataset_of_movies.append(movie_object) director_object = Director(director) if director_object not in self.__dataset_of_directors: # or len(self.__dataset_of_directors) == 0: self.__dataset_of_directors.add(director_object) index += 1 @property def dataset_of_movies(self): return self.__dataset_of_movies # @dataset_of_movies.setter # def dataset_of_movies(self, value): # pass @property def dataset_of_actors(self): return self.__dataset_of_actors # @dataset_of_actors.setter # def dataset_of_actors(self, value): # pass @property def dataset_of_directors(self): return self.__dataset_of_directors # @dataset_of_directors.setter # def dataset_of_directors(self, value): # pass @property def dataset_of_genres(self): return self.__dataset_of_genres # @dataset_of_genres.setter # def dataset_of_genres(self, value): # pass ### Functions below are moved into the code above for efficiency/speed # def add_actors(actors_string): # actor_list = actors_string.split(",") # # for item in actor_list: # # item.strip() # return [Actor(item.strip()) for item in actor_list] # # def add_genres(genre_string): # genre_list = genre_string.split(",") # # for item in genre_list: # # item.strip() # return [Genre(item.strip()) for item in genre_list] # noinspection SpellCheckingInspection
Java
UTF-8
3,808
2.6875
3
[]
no_license
package com.masi4.UI.gameInventory; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.masi4.gamehelpers.resourceHandlers.AssetLoader; import com.masi4.gamehelpers.GamePreferences; import static com.masi4.GUI.GUI.player; import static com.masi4.UI.gameInventory.InventoryWindow.INVENTORY_WIDTH; /** * Created by U1wknUzeU6 on 01.05.2018. */ public class StatsView extends Table { private float defaultScale = 3f; private float statsScale = 2f; int MAX_HP; int HP; /*...*/ ProgressBar healthBar; Label.LabelStyle defaultStyle; Label.LabelStyle statsStyle; Label staminaLabel; Label defenceLabel; Label damageLabel; public StatsView() { LoadStats(); SetStyle(); Create(); } private void SetStyle() { pad(0,30,10,10); } /**Здесь создаются объекты для отображения статов*/ private void Create() { defaultStyle = new Label.LabelStyle(AssetLoader.default18, Color.WHITE); statsStyle = new Label.LabelStyle(AssetLoader.default18, Color.WHITE); Label healthLabel = new Label(GamePreferences.loc.format("Inventory_Health"),defaultStyle); ProgressBar.ProgressBarStyle healthBarStyle = new ProgressBar.ProgressBarStyle( new TextureRegionDrawable(AssetLoader.GameInventory_HealthBarBoundsTextureRegion), new TextureRegionDrawable(AssetLoader.GameInventory_HealthBarFillTextureRegion)); healthBarStyle.knobBefore = new TextureRegionDrawable(AssetLoader.GameInventory_HealthBarFillTextureRegion); healthBarStyle.background.setLeftWidth(3); healthBarStyle.background.setRightWidth(6); healthBarStyle.background.setMinHeight(healthBarStyle.background.getMinHeight() * defaultScale); healthBarStyle.knobBefore.setMinHeight(healthBarStyle.knobBefore.getMinHeight() * defaultScale); healthBarStyle.knob.setMinHeight(healthBarStyle.knob.getMinHeight() * defaultScale); healthBar = new ProgressBar(0,1,0.01f,false,healthBarStyle); healthBar.setValue((float)HP/(float)MAX_HP); healthBar.setScale(defaultScale); healthLabel.setFontScale(defaultScale); staminaLabel = new Label("" ,statsStyle); staminaLabel.setFontScale(statsScale); defenceLabel = new Label("" ,statsStyle); defenceLabel.setFontScale(statsScale); damageLabel = new Label("",statsStyle); damageLabel.setFontScale(statsScale); UpdateStats(); this.add(healthLabel); this.row(); this.add(healthBar).width(INVENTORY_WIDTH/3); this.row(); this.add(staminaLabel).left().padTop(10); this.row(); this.add(defenceLabel).left(); this.row(); this.add(damageLabel).left(); this.pack(); } void LoadStats() { MAX_HP = player.getMaxHP(); HP = player.getCurrentHP(); } public void UpdateHealthBar(float delta) { healthBar.setValue((float)player.getCurrentHP()/(float)player.getMaxHP()); healthBar.act(delta); } // TODO: применение public void UpdateStats() { staminaLabel.setText(GamePreferences.loc.format("Inventory_Stamina") + ": " + player.getStats().getStamina()); defenceLabel.setText(GamePreferences.loc.format("Inventory_Defence") + ": " + player.getStats().getDefence()); damageLabel.setText(GamePreferences.loc.format("Inventory_Damage") + ": " + player.getStats().getDamage()); } }
Python
UTF-8
528
3.78125
4
[]
no_license
#filter,map,lambda # returning only even numbers..another way using lambda print("\n") numbers = [1,56,234,87,4,76,24,69,90,135] new = filter ((lambda x: x%2==0), numbers) print (list(new)) # returning only even numbers..another way using lambda print("\n") numbers = [1,56,234,87,4,76,24,69,90,135] new = map ((lambda x: x%2==0), numbers) print (list(new)) #combinations..adding not to produce odd numbers print("\n") numbers = [1,56,234,87,4,76,24,69,90,135] newlist = [n for n in numbers if not n%2==0] print (newlist)
Python
UTF-8
3,774
2.6875
3
[ "MIT" ]
permissive
from __future__ import print_function import cv2 import numpy as np import argparse from math import sqrt ################################### ## Align equirectangular image ## ## (Get homography matrix) ## ################################### ## [load] # left_img_file = './captured_img/3264x2448_fisheye/640x480_equi/left_infinite_feature_10_result.jpg' # right_img_file = './captured_img/3264x2448_fisheye/640x480_equi/right_infinite_feature_10_result.jpg' left_img_file = "./captured_img/d415_RGB_15.jpg" right_img_file = "./captured_img/perspective_15.jpg" img1 = cv2.imread(right_img_file) # source img2 = cv2.imread(left_img_file) # destination # './sample/graf1.png' # './sample/graf3.png' if img1 is None or img2 is None: print('Could not open or find the images!') exit(0) ## [load] ## [AKAZE] akaze = cv2.AKAZE_create() kpts1, desc1 = akaze.detectAndCompute(img1, None) kpts2, desc2 = akaze.detectAndCompute(img2, None) ## [AKAZE] ## [2-nn matching] matcher = cv2.DescriptorMatcher_create(cv2.DescriptorMatcher_BRUTEFORCE_HAMMING) nn_matches = matcher.knnMatch(desc1, desc2, 2) ## [2-nn matching] ## [ratio test filtering] matched1 = [] matched2 = [] nn_match_ratio = 0.8 # Nearest neighbor matching ratio for m, n in nn_matches: if m.distance < nn_match_ratio * n.distance: matched1.append(kpts1[m.queryIdx]) matched2.append(kpts2[m.trainIdx]) ## [ratio test filtering] ## [calculate homography matrix] src_pts = np.float32([ m.pt for m in matched1 ]).reshape(-1,1,2) dst_pts = np.float32([ m.pt for m in matched2 ]).reshape(-1,1,2) homography, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC) # Is least-square method applied? print(homography) # print(dst_pts[:,:,0].astype(np.int)) # x position ## [calculate homography matrix] ## [save image] img_transed = cv2.warpPerspective(img1, homography, (img2.shape[1],img2.shape[0])) cv2.imwrite('./output/result_projective_transformation.jpg',img_transed) print("A transformed image is saved in \"output\" folder") # cv2.imshow('result', img_transed) # cv2.waitKey() ## [save image] ################################# ## Check mapping ## ## (Check homography matrix) ## ################################# # ## [load] # fs = cv2.FileStorage("./parameters/homography_m.xml", cv2.FILE_STORAGE_READ) # homography = fs.getFirstTopLevelNode().mat() # ## [load] ## [homography check] inliers1 = [] inliers2 = [] good_matches = [] inlier_threshold = 2.5 # Distance threshold to identify inliers with homography check for i, m in enumerate(matched1): col = np.ones((3,1), dtype=np.float64) col[0:2,0] = m.pt col = np.dot(homography, col) col /= col[2,0] dist = sqrt(pow(col[0,0] - matched2[i].pt[0], 2) +\ pow(col[1,0] - matched2[i].pt[1], 2)) if dist < inlier_threshold: good_matches.append(cv2.DMatch(len(inliers1), len(inliers2), 0)) inliers1.append(matched1[i]) inliers2.append(matched2[i]) ## [homography check] ## [draw final matches] res = np.empty((max(img1.shape[0], img2.shape[0]), img1.shape[1]+img2.shape[1], 3), dtype=np.uint8) cv2.drawMatches(img1, inliers1, img2, inliers2, good_matches, res) cv2.imwrite("akaze_result.png", res) inlier_ratio = len(inliers1) / float(len(matched1)) print('A-KAZE Matching Results') print('*******************************') print('# Keypoints 1: \t', len(kpts1)) print('# Keypoints 2: \t', len(kpts2)) print('# Matches: \t', len(matched1)) print('# Inliers: \t', len(inliers1)) print('# Inliers Ratio: \t', inlier_ratio) cv2.imshow('result', res) cv2.imwrite('./result_AKAZE.jpg',res) cv2.waitKey() ## [draw final matches]
Java
UTF-8
4,756
2.34375
2
[]
no_license
package payment; import java.io.IOException; import database.Database; import interceptor.contextObjects.PaymentInfoContext; import interceptor.dispatchers.ClientRequestDispatcher; import media.GameClass; import media.MediaItem; import media.PlatformChoice; import program.I_Receiver; import userInterface.UserInterfaceMenu; import users.CustomerClass; import users.UserClass; public class Payment implements I_Receiver { Database database = Database.getInstance(); //TODO! should take out Credit card functionality altogether and just us wallet public void processPayment(String username_mediaTitle_purchaseType_paymentOption) throws IOException { String[] arr = username_mediaTitle_purchaseType_paymentOption.split(","); String username = arr[0]; String mediaTitle = arr[1]; String purchaseType = arr[2]; String paymentOption = arr[3]; String checkout = arr[4]; I_Receipt receipt= new ReceiptA(); //receipt object created UserClass customer= database.getUserByName(username); int userID = customer.getUserID(); CustomerClass cust= (CustomerClass)customer; //Casting from Userclass to CustomerClass MediaItem item= database.getMediaItemByName(mediaTitle); double oldBalance= Double.parseDouble(cust.getBalance()); double price= item.getPrice(); double newBalance= oldBalance-price; if((newBalance>=0.0 && paymentOption.equalsIgnoreCase("Wallet")) || paymentOption.equalsIgnoreCase("Credit Card") ) //both cases mean their payment is valid { // ENOUGH MONEY! if(purchaseType.equalsIgnoreCase("Store in Online Repository")) { // TRYS TO ADD TO ONLINE REPOSITORY boolean alreadyInRepository = database.updateOnlineMediaRepository(Integer.toString(userID), item.getMediaID()); // ERROR & PAYMENT CANCELLED IF ALREADY IN REPOSITORY if(alreadyInRepository) { String message = ("Payment Cancelled! " + item.getTitle() + " is already in online repository!"); userInterface.UserInterfaceMenu execute = new UserInterfaceMenu(); execute.displayErrorMessage(message); logPaymentSuccessOrFailure(Integer.toString(userID), message, false); return; } receipt= new CustomerDecorator(new OnlineDecorator(receipt)); //receipt decorated so that a customer has bought an item to be stored in online repository } else if(purchaseType.equalsIgnoreCase("Ship to Address")) { receipt= new CustomerDecorator(new ShipmentDecorator(receipt)); //receipt decorated so that a customer has bought an item to be shipped to them } if(paymentOption.equalsIgnoreCase("Wallet")) { // MAKES PAYMENT : UPDATES CUSTOMER BALANCE String updatedBalance= Double.toString(newBalance); cust.setBalance(updatedBalance); //updating customer wallet String message = "Successful payment : Paid: " + price + " for " + mediaTitle; logPaymentSuccessOrFailure(Integer.toString(userID), message, true); //interceptor method?? receipt= new WalletDecorator(receipt); //receipt decorated to show that the customer paid by wallet } if(paymentOption.equalsIgnoreCase("Credit Card")) { receipt= new CreditCardDecorator(receipt); //receipt decorated to show that the customer paid by credit card } userInterface.UserInterfaceMenu execut = new UserInterfaceMenu(); //call to user interface execut.displayReceipt(item,receipt); //displayReceipt method of UI is called which implements the PrintReceipt() method and prints out all the decorators that are dynamically bound to the Receipt // THIS UPDATES USERS.TXT WITH THE NEW BALANCE FOR CUSTOMER database.updateUsers(); //refresh users so that their new wallet balance is updated to the text file } else { String message = ("Payment Cancelled! : Insufficient Funds!"); userInterface.UserInterfaceMenu execute = new UserInterfaceMenu(); execute.displayErrorMessage(message); logPaymentSuccessOrFailure(Integer.toString(userID), message, false); //interceptor?? return; } if(item.getMediaType().equalsIgnoreCase("GAME")) { GameClass itemG= (GameClass)item; PlatformChoice pChoice= new PlatformChoice(); pChoice.nullPLatform(itemG); //When a platform is chosen for a game item the price is changed depending on the platform, nullPlatform is called to reset the game item back to its original price } } public void logPaymentSuccessOrFailure(String userID, String description, boolean isSuccessful) throws IOException { ClientRequestDispatcher.getInstance().dispatchClientRequestInterceptorPaymentLogging(new PaymentInfoContext(userID, description, isSuccessful)); } }
Python
UTF-8
80
3.125
3
[]
no_license
a = input() if 'H'in a or 'Q' in a or '9' in a: print('YES') else: print('NO')
Java
UTF-8
1,190
2.34375
2
[]
no_license
package StepDefinitions; import com.edgenetworks.utilities.TestBase; import cucumber.api.java.en.Then; public class CreateRR_ViaCSVStepdefinition extends TestBase { @Then("^Click on Create RR via csv option in dashboard\\.$") public void click_on_Create_RR_via_csv_option_in_dashboard() throws Throwable { } @Then("^Try to upload the csv file \\.$") public void try_to_upload_the_csv_file() throws Throwable { } @Then("^Once the RR is created click on the View button of respective RR created\\.$") public void once_the_RR_is_created_click_on_the_View_button_of_respective_RR_created() throws Throwable { } @Then("^Wait for the Preview page to appear since other fields are not entered try to enter the details\\.$") public void wait_for_the_Preview_page_to_appear_since_other_fields_are_not_entered_try_to_enter_the_details() throws Throwable { } @Then("^User enters the Resource Requirement details \"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\" and \"([^\"]*)\" click on next button\\.$") public void user_enters_the_Resource_Requirement_details_and_click_on_next_button(String arg1, String arg2, String arg3, String arg4) throws Throwable { } }
PHP
UTF-8
771
2.515625
3
[]
no_license
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSubscriptionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create('subscriptions', function (Blueprint $table) { $table->integer('user_id')->index('subscriptions_user_id'); $table->integer('subscription_id')->index('subscriptions_subscription_id'); $table->primary(['user_id', 'subscription_id']); }); } /** * Reverse the migrations. * * @return void */ public function down(): void { Schema::dropIfExists('subscriptions'); } }
Shell
UTF-8
129
2.5625
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # Wait for Connect to be ready before exiting while [ ! -f $BROWSER_PROVIDER_READY_FILE ]; do sleep .5 done
Java
UTF-8
498
1.71875
2
[ "MIT" ]
permissive
package com.bancoexterior.app.convenio.services; import java.util.List; import com.bancoexterior.app.convenio.dto.MonedasRequest; import com.bancoexterior.app.convenio.model.Moneda; public interface IMonedaService { public List<Moneda> buscarTodas(); public Moneda findById(String codMoneda); public void guardar(Moneda moneda); public List<Moneda> consultaMonedasApiRest(MonedasRequest MonedasRequest); public List<Moneda> consultaMonedasApi(MonedasRequest MonedasRequest); }
Shell
UTF-8
484
3.21875
3
[]
no_license
#!/bin/bash START=$(date +%s) ARG1=${1:-1000} ARG2=${2:-foo} HOST='localhost' PORT='8888' x=1 while [ "$x" -lt "$ARG1" ] ; do payload='{"from": "user", "to": "tester", "quantity": "0.0001 EOS", "memo": "m'"$ARG2""$x"'"}' #echo $payload cleos -H $HOST -p $PORT --wallet-host localhost --wallet-port 8000 push action eosio.token transfer "$payload" -p user let "x++" done END=$(date +%s) DIFF=$(( $END - $START )) echo "It took $DIFF seconds to spam $x transactions"
Java
UTF-8
1,989
2.046875
2
[]
no_license
package com.example.ryan.bottomnavigation.admin.Regist; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.example.ryan.bottomnavigation.R; import java.util.ArrayList; import java.util.List; public class RegistrasiFragment extends Fragment { View v; private RecyclerView nRecyclerView; private List<Regis> regisList; private Button tambahuser; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { v = inflater.inflate(R.layout.fragment_registrasi, container, false); nRecyclerView = (RecyclerView) v.findViewById(R.id.regis_recyclerview); RecyclerViewAdapterRegis recyclerViewAdapterRegis = new RecyclerViewAdapterRegis(getContext(), regisList); nRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); nRecyclerView.setAdapter(recyclerViewAdapterRegis); tambahuser = v.findViewById(R.id.btn_tambahuser); tambahuser.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), TambahUserActivity.class); getActivity().startActivity(intent); } }); return v; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); regisList = new ArrayList<>(); regisList.add(new Regis(R.drawable.foto01, "Michael")); regisList.add(new Regis(R.drawable.foto02, "Ronaldo")); } }
Java
UTF-8
2,321
2.296875
2
[]
no_license
package lili.tesla.lushertest.presentation.screen.table3.presenter; import lili.tesla.lushertest.presentation.application.App; import lili.tesla.lushertest.presentation.screen.table3.view.Table3View; import lili.tesla.lushertest.presentation.screen.base.BasePresenter; /** * Created by Лилия on 02.11.2017. */ public class Table3Presenter extends BasePresenter<Table3View> { public int testNum = 0; public int clickCount = 0; public boolean isSecondTry = false; public boolean isWasSecondTry = false; public void setImagesColors(int testNum) { mView.setImagesColors(testNum); } public void setImagesVisible(int testNum) { mView.setImagesVisible(testNum);} public void onImageClick(int num) { App.arrayTab3[testNum][num] ++; clickCount ++; if (clickCount < 6 ) { mView.setImagesVisible(clickCount); } else { if (!isSecondTry) { if (testNum < 4) { startNewTest(); } else { isSecondTry = true; testNum = 0; } } if (isSecondTry) { while ((testNum < 5)&&(isRightTest()||isWasSecondTry)) { isWasSecondTry = false; testNum ++; } if (testNum < 5) { testNum --; isWasSecondTry = true; startNewTest(); } else { mView.showTable2Screen(); } } } } public void startNewTest() { testNum ++; if (clickCount == 6) { clickCount = 0; } for (int i = 0; i < 4; i ++) { App.arrayTab3[testNum][i] = 0; } setImagesColors(testNum); setImagesVisible(clickCount); } private boolean isRightTest(){ int[] counts = new int[4]; for (int i = 0; i < 4; i ++) { counts[i] = 0; } for (int i = 0; i < 4; i ++) { counts[App.arrayTab3[testNum][i]] ++; } if ((counts[0] > 1)||(counts[1] > 1) ||(counts[2] > 1) ||(counts[3] > 1)) { return false; } else { return true; } } }
C
UTF-8
2,970
2.5625
3
[ "Apache-2.0" ]
permissive
/****************************************************************************** * Copyright (c) 2019 Jason T. Harris. (sirmanlypowers@gmail.com) * * SPDX-License-Identifier: Apache-2.0 * * BiQuad Filter * See: http://www.earlevel.com/main/2003/02/28/biquads/ */ #include "ggm.h" #include "filter/filter.h" /****************************************************************************** * private state */ struct biquad { float a0, a1, a2; /* zero coefficients */ float b1, b2; /* pole coefficients */ float d1, d2; /* delay variables */ }; /****************************************************************************** * module port functions */ static void biquad_port_cutoff(struct module *m, const struct event *e) { // struct biquad *this = (struct biquad *)m->priv; float cutoff = clampf(event_get_float(e), 0.f, 0.5f * AudioSampleFrequency); LOG_INF("set cutoff frequency %f Hz", cutoff); /* TODO */ } static void biquad_port_resonance(struct module *m, const struct event *e) { // struct biquad *this = (struct biquad *)m->priv; float resonance = clampf(event_get_float(e), 0.f, 1.f); LOG_INF("set resonance %f", resonance); /* TODO */ } /****************************************************************************** * module functions */ static int biquad_alloc(struct module *m, va_list vargs) { /* allocate the private data */ struct biquad *this = ggm_calloc(1, sizeof(struct biquad)); if (this == NULL) { return -1; } m->priv = (void *)this; return 0; } static void biquad_free(struct module *m) { struct biquad *this = (struct biquad *)m->priv; ggm_free(this); } static bool biquad_process(struct module *m, float *bufs[]) { struct biquad *this = (struct biquad *)m->priv; float *in = bufs[0]; float *out = bufs[1]; float a0 = this->a0; float a1 = this->a1; float a2 = this->a2; float b1 = this->b1; float b2 = this->b2; float d1 = this->d1; float d2 = this->d2; for (int i = 0; i < AudioBufferSize; i++) { /* direct form 2 */ float d0 = in[i] - (b1 * d1) - (b2 * d2); out[i] = (a0 * d0) + (a1 * d1) + (a2 * d2); d1 = d0; d2 = d1; } /* store the delay variables */ this->d1 = d1; this->d2 = d2; return true; } /****************************************************************************** * module information */ static const struct port_info in_ports[] = { {.name = "in",.type = PORT_TYPE_AUDIO,}, {.name = "cutoff",.type = PORT_TYPE_FLOAT,.pf = biquad_port_cutoff}, {.name = "resonance",.type = PORT_TYPE_FLOAT,.pf = biquad_port_resonance}, PORT_EOL, }; static const struct port_info out_ports[] = { {.name = "out",.type = PORT_TYPE_AUDIO,}, PORT_EOL, }; const struct module_info filter_biquad_module = { .mname = "filter/biquad", .iname = "biquad", .in = in_ports, .out = out_ports, .alloc = biquad_alloc, .free = biquad_free, .process = biquad_process, }; MODULE_REGISTER(filter_biquad_module); /*****************************************************************************/
Java
UTF-8
171
2.3125
2
[]
no_license
package week3.day1.classroom; public class AndriodPhone extends Mobile { public void takeViedo() { System.out.println("taking viedo in Andridphone"); } }
Markdown
UTF-8
859
3.03125
3
[]
no_license
Chitter Challenge ================= This is the week four weekend challenge @ Makers. This weekend I am making a Twitter clone, nicely named 'Chitter', users will post messages, each is called a 'Peep'. The challenge will follow TDD, CRUD and OOD principles, and put to practice this week's learning of databases within a full stack web app. Instructions: ================= - rvm install ruby-2.5.0 - bundle init User stories: ================= As a Maker So that I can let people know what I am doing I want to post a message (peep) to chitter As a maker So that I can see what others are saying I want to see all peeps in reverse chronological order As a Maker So that I can better appreciate the context of a peep I want to see the time at which it was made As a Maker So that I can post messages on Chitter as me I want to sign up for Chitter
PHP
UTF-8
1,183
2.71875
3
[]
no_license
<?php /** * ampinstant-cf Project * @package ampinstant-cf * User: dankerizer * Date: 06/11/2017 / 16.44 */ class ampinstantcf_Filter { var $fromEmail; var $fromName; function wp_mail_from ($orig) { // This is copied from pluggable.php lines 348-354 as at revision 10150 // http://trac.wordpress.org/browser/branches/2.7/wp-includes/pluggable.php#L348 // Get the site domain and get rid of www. $sitename = strtolower( $_SERVER['SERVER_NAME'] ); if ( substr( $sitename, 0, 4 ) == 'www.' ) { $sitename = substr( $sitename, 4 ); } $default_from = 'wordpress@' . $sitename; // End of copied code // If the from email is not the default, return it unchanged if ( $orig != $default_from ) { return $orig; } return $this->fromEmail; } //strip slashes from the name function wp_mail_from_name ($orig) { if ( $orig != 'WordPress') { return $orig; } return stripslashes($this->fromName); } function add($filter, $priority = 10, $args = 1) { add_filter ($filter, array($this,$filter),$priority,$args); } function remove($filter, $priority = 10, $args = 1) { remove_filter ($filter, array($this,$filter),$priority,$args); } }
SQL
UTF-8
3,922
3.140625
3
[]
no_license
SELECT SQ.SHIP_TO_CUST_ID, SQ.SHIP_TO_CUST_NAME, SQ.OWN_CUST_ID, SQ.OWN_CUST_NAME, SQ.FACILITY_ID, SQ.FRDD, SQ.FCDD, SUM( SQ.ORDER_QTY ) AS ORDER_QTY, SUM( SQ.CNFRM_QTY ) AS CNFRM_QTY, SUM( SQ.CNFRM_QTY * SQ.UNIT_WT ) AS WT, SUM( SQ.CNFRM_QTY * SQ.UNIT_COMPRESSED_VOL ) AS CMP_VOL, SQ.VOL_UOM, SQ.WT_UOM, SQ.QTY_UOM FROM ( SELECT Q.SHIP_TO_CUST_ID, Q.SHIP_TO_CUST_NAME, Q.OWN_CUST_ID, Q.OWN_CUST_NAME, Q.FACILITY_ID, Q.FRDD, Q.FCDD, SUM( Q.ORDER_QTY ) AS ORDER_QTY, SUM( Q.CNFRM_QTY ) AS CNFRM_QTY, SUM( Q.OPEN_CNFRM_QTY ) AS OPEN_CNFRM_QTY, SUM( Q.UNCNFRM_QTY ) AS UNCNFRM_QTY, SUM( Q.BACK_ORDER_QTY ) AS BACK_ORDER_QTY, Q.UNIT_WT, Q.UNIT_VOL, Q.UNIT_COMPRESSED_VOL, Q.VOL_UOM, Q.WT_UOM, Q.QTY_UOM FROM ( SELECT ODC.ORDER_ID, ODC.ORDER_LINE_NBR, ODC.SCHED_LINE_NBR, ODC.SHIP_TO_CUST_ID, CUST.CUST_NAME AS SHIP_TO_CUST_NAME, CUST.OWN_CUST_ID, CUST.OWN_CUST_NAME, ODC.SALES_ORG_CD, ODC.DISTR_CHAN_CD, ODC.CO_CD, ODC.DIV_CD, ODC.MATL_ID, CAST( CASE MATL.PBU_NBR || MATL.MKT_AREA_NBR WHEN '0101' THEN 0.75 WHEN '0108' THEN 0.80 WHEN '0305' THEN 1.20 WHEN '0314' THEN 1.20 ELSE 1 END AS DECIMAL(15,3) ) AS COMPRESSION_FACTOR, ODC.FACILITY_ID, ODC.SHIP_PT_ID, ODC.CUST_GRP2_CD, ODC.ORDER_CAT_ID, ODC.ORDER_TYPE_ID, ODC.PO_TYPE_ID, ODC.DELIV_BLK_CD, ODC.ORDER_CREATOR, ODC.SHIP_COND_ID, ODC.PRTL_DLVY_CD, ODC.REJ_REAS_ID, ODC.DELIV_PRTY_ID, ODC.ROUTE_ID, ODC.DELIV_GRP_CD, ODC.CANCEL_DT, ODC.QTY_UNIT_MEAS_ID AS QTY_UOM, ODC.ORDER_QTY, ODC.CNFRM_QTY, OOL.OPEN_CNFRM_QTY, OOL.UNCNFRM_QTY, OOL.BACK_ORDER_QTY, ODC.WT_UNITS_MEAS_ID AS WT_UOM, ODC.NET_WT, ODC.GROSS_WT, SUM( ODC.GROSS_WT ) OVER ( PARTITION BY ODC.MATL_ID ) / SUM( ODC.ORDER_QTY ) OVER ( PARTITION BY ODC.MATL_ID ) AS UNIT_WT, ODC.VOL_UNIT_MEAS_ID AS VOL_UOM, ZEROIFNULL( ODC.VOL ) * COMPRESSION_FACTOR AS COMPRESSED_VOL, ODC.VOL, SUM( ODC.VOL ) OVER ( PARTITION BY ODC.MATL_ID ) / SUM( ODC.ORDER_QTY ) OVER ( PARTITION BY ODC.MATL_ID ) AS UNIT_VOL, SUM( COMPRESSED_VOL ) OVER ( PARTITION BY ODC.MATL_ID ) / SUM( ODC.ORDER_QTY ) OVER ( PARTITION BY ODC.MATL_ID ) AS UNIT_COMPRESSED_VOL, ODC.ORDER_DT, ODC.FRST_RDD AS FRDD, ODC.FRST_PROM_DELIV_DT AS FCDD FROM NA_BI_VWS.ORDER_DETAIL_CURR ODC INNER JOIN GDYR_BI_VWS.NAT_CUST_HIER_DESCR_EN_CURR CUST ON CUST.SHIP_TO_CUST_ID = ODC.SHIP_TO_CUST_ID INNER JOIN GDYR_BI_VWS.NAT_MATL_HIER_DESCR_EN_CURR MATL ON MATL.MATL_ID = ODC.MATL_ID AND MATL.PBU_NBR IN ( '01', '03', '04', '05', '07', '08', '09' ) LEFT OUTER JOIN NA_BI_VWS.OPEN_ORDER_ORDLN_CURR OOL ON OOL.ORDER_ID = ODC.ORDER_ID AND OOL.ORDER_LINE_NBR = ODC.ORDER_LINE_NBR AND ( OOL.OPEN_CNFRM_QTY > 0 OR OOL.UNCNFRM_QTY > 0 OR OOL.BACK_ORDER_QTY > 0 ) WHERE ODC.CUST_GRP2_CD = 'TLB' AND ODC.ORDER_CAT_ID = 'C' AND ODC.ORDER_TYPE_ID NOT IN ( 'ZLS', 'ZLZ' ) AND ODC.PO_TYPE_ID <> 'RO' AND ODC.SHIP_COND_ID NOT IN ( '', 'EG' ) AND FRDD >= DATE '2014-02-01' AND FRDD = FCDD ) Q GROUP BY Q.SHIP_TO_CUST_ID, Q.SHIP_TO_CUST_NAME, Q.OWN_CUST_ID, Q.OWN_CUST_NAME, Q.FACILITY_ID, Q.FRDD, Q.FCDD, Q.UNIT_WT, Q.UNIT_VOL, Q.UNIT_COMPRESSED_VOL, Q.VOL_UOM, Q.WT_UOM, Q.QTY_UOM ) SQ GROUP BY SQ.SHIP_TO_CUST_ID, SQ.SHIP_TO_CUST_NAME, SQ.OWN_CUST_ID, SQ.OWN_CUST_NAME, SQ.FACILITY_ID, SQ.FRDD, SQ.FCDD, SQ.VOL_UOM, SQ.WT_UOM, SQ.QTY_UOM ORDER BY SQ.SHIP_TO_CUST_ID, SQ.SHIP_TO_CUST_NAME, SQ.OWN_CUST_ID, SQ.OWN_CUST_NAME, SQ.FACILITY_ID, SQ.FRDD
JavaScript
UTF-8
770
2.703125
3
[]
no_license
const app = document.getElementById("app") class Task extends React.Component { edit(){ alert("Нажата кнопка редактировать") } remove(){ alert("Нажата кнопка удалить") } render() { return( <div className="box"> <div className="text">{this.props.children}</div> <button onClick={this.edit} className="btn light">Редактировать</button> <button onClick={this.remove} className="btn red">Удалить</button> </div> ) } } ReactDOM.render ( <div className="field"> <Task>Task 1</Task> <Task>Task 2</Task> <Task>Task 3</Task> </div>, app )
Shell
UTF-8
271
3.015625
3
[]
no_license
#!/bin/bash set -e [ ! -n "$1" ] && exit 1 SERVER=$1 shift ARGS=$* PUPPET_TMP=/tmp/hdo-puppet-rsync rsync -a --delete puppet "${SERVER}:${PUPPET_TMP}" ssh -t $SERVER "sudo puppet apply --modulepath=${PUPPET_TMP}/puppet/modules/ ${PUPPET_TMP}/puppet/site.pp ${ARGS}"
Markdown
UTF-8
492
2.609375
3
[ "MIT" ]
permissive
# Banking system Really cheap take on something that should be a banking system. *I used Yarn but npm is fine too.* ## Installing 1. Make sure you have `DATABASE_URL` enviromental variable that points to your local or [Mongo Atlas](https://www.mongodb.com/cloud/atlas) MongoDB. 1. `yarn install` ## Populate DB ``` yarn run seed ``` Will create and seed missing tables once and create 5 users on every run. ## Running Dev server with hot reload: ``` yarn run watch ``` ## License MIT
Python
UTF-8
1,487
3.78125
4
[]
no_license
''' This one line outlines the module content Here we see the detailed Discription of the Module: Make clear how to comment and structure your code so that other can read and use it. Have a look at the content of https://github.com/alnkpa/pycc/wiki/Coding-style ''' # import in the beginning import sys class OurClass: ''' This is one sentence describing the class' use After two new lines the detailed description of the class follows SOME_CONSTANT is used as example for constants and should be described here. The tab makes clear this belongs to the line above. ''' SOME_CONSTANT = "something that will not change is all capital" #this is a comment, regarding the following method def ourMethod(self, a, b, c): ''' ourMethod(a, b, c) sets the value of variable set variable to the sum of a, b, c and return None ''' self.variable = a + b + c # use newlines between methods def getVariable(self): '''getVariable() returns the value of variable as int.''' return int(self.variable) # some things do not need an explanation __all__ = ['OurClass'] if __name__ == '__main__': try: # testing OurClass() on errors during creation o = OurClass() except: errortype, error, traceback = sys.exc_info() print("always show when there is an unexpected error {0}".format(error)) # Rules are made to break them. # And in case you did well you will not get harmed.
Java
UTF-8
1,194
2.21875
2
[]
no_license
package com.run.boot; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.run.boot.config.AuthorSettings; import com.run.spring_boot_starter_hello.HelloService; @RestController @SpringBootApplication //建议DemoApplication类放置在groupID+arctifactId组合的包名下(一般是最根的包下),此项目中为com.run.boot public class BootApplication { @Value("${book.author}") private String bookAuthor; @Value("${book.name}") private String bookName; @Autowired private AuthorSettings authorSettings; @Autowired private HelloService HelloService; @RequestMapping("/") String index() { // return "author name is : "+ authorSettings.getName() + " and author age is :"+ authorSettings.getAge(); return HelloService.sayHello(); } public static void main(String[] args) { SpringApplication.run(BootApplication.class, args); } }
Ruby
UTF-8
885
3.484375
3
[]
no_license
class LinkedListNode attr_accessor :value, :next_node def initialize(value, next_node = nil) @value = value @next_node = next_node end end def print_values(list_node) print "#{list_node.value} --> " if list_node.next_node.nil? print "nil\n" return else print_values(list_node.next_node) end end def reverse_list2 (list, previous = nil) head = Marshal.load(Marshal.dump(list)) next_iter = head.next_node # keep track of next iteration step head.next_node = previous # flip-flip list pointer return head if next_iter.nil? # return results accumulator if done reverse_list2(next_iter, head) # otherwise, recursive traversal end def is_infinite(list) start_node = list while !list.next_node.nil? list = list.next_node if list == start_node return true end end return false end
Java
UTF-8
2,241
3.84375
4
[]
no_license
package fan; import java.util.Iterator; /** * This is the class implementing typical FIFO Queue with that difference that * some parameters are measured in bytes instead of packets as units. * @see FifoQueue */ public class FifoQueueBytes extends FIFOQueue { private int totalSize; /** * Holds the information about the type of the queue - in this case Fifo */ private String type; /** * Constructor for this class * @param size Maximum size of this queue - [needs reviewing] * @param intfce The interface which this queue is assigned to */ public FifoQueueBytes(int size, Interface intfce) { super(size,intfce); totalSize = 0; type = "FIFOBytes"; } /** * Checks if this queue is full. * @return True if it is full, false otherwise */ public boolean isFull() { int totalSize = 0; for (Iterator iter = fifo.iterator(); iter.hasNext();) { Packet p = (Packet) iter.next(); totalSize += p.getLength(); } if(totalSize < maxSize) return false; else return true; } /** * Returns space left in this queue * @return Free bytes left */ public int getFreeBytes() { return maxSize - totalSize; } /** * Method to put packet inside this queue * @param p The Packet that will be inserted in this queue * @return True if the packet was inserted properly, false if the queue was full and there * was no space for this packet. */ public boolean putPacket(Packet p) { if ( getFreeBytes() - p.getLength() >= 0) { fifo.offer(p); totalSize += p.getLength(); recievedBytes += p.getLength(); return true; } else return false; } /** * Remove and return the first packet of this queue * @return First, removed packet of this queue */ public Packet removeFirst() { Packet p = super.removeFirst(); totalSize -= p.getLength(); return p; } /** * Method to get size of the queue (number of bytes inside this queue) * @return Number of bytes currently kept in this queue */ public int getSize() { return totalSize; } /** * Method to return the type of the queue, * in this case "FIFO" */ public String getType(){ return type; } }
SQL
UTF-8
497
2.828125
3
[ "MIT" ]
permissive
DROP TABLE IF EXISTS leagues; CREATE TABLE leagues ( id SERIAL PRIMARY KEY, abbreviation VARCHAR(3), name VARCHAR(255) ); DROP TABLE IF EXISTS divisions; CREATE TABLE divisions ( id SERIAL PRIMARY KEY, league_id SERIAL NOT NULL, name VARCHAR(25) ); DROP TABLE IF EXISTS teams; CREATE TABLE teams ( id SERIAL PRIMARY KEY, division_id SERIAL NOT NULL, name VARCHAR(255) NOT NULL, city VARCHAR(255) NOT NULL, head_coach VARCHAR(255) NOT NULL, mascot VARCHAR(255) NOT NULL );
Markdown
UTF-8
6,477
3.96875
4
[]
no_license
# Testing ## Testing the signup form on `signup.html`: - When the form is submitted with no username, it prompts you to fill in the username. ![Screenshot of no username](static/images/testing/no-username.png) - When the form is submitted with a username that is too short it prompts you to change the length of the username. ![Screenshot of too short username](static/images/testing/username-too-short.png) - The form does not let you type a username longer than 15 characters. - When the form is submitted with a username that already exists a flash message appears saying the username already exists. ![Screenshot of username already exists flash message](static/images/testing/username-exists.png) - When the form is submitted with no email, it prompts you to fill in the email. ![Screenshot of no email](static/images/testing/no-email.png) - When the form is submitted with an invalid email, it prompts you to provide a valid email. ![Screenshot of invalid email](static/images/testing/incorrect-email.png) - When the form is submitted with no password field, it prompts you to fill in the password. ![Screenshot of no password](static/images/testing/no-password.png) - When the form is submitted with a password that is too short, it prompts you to change the length of the password. ![Screenshot of too short password](static/images/testing/password-too-short.png) - The form does not let you type a password longer than 15 characters. - When the form is submitted without filling in the confirm password field it prompts you to fill it in. ![Screenshot of no confirmed password](static/images/testing/no-confirm.png) - When the form is submitted without matching passwords a flash message appears to say this. ![Screenshot of passwords not matching flash message](static/images/testing/passwords-not-match.png) - When the form is submitted with all the correct validation, the new user is added to the database and logged into the page. ## Testing the login form on `login.html`: - When the form is submitted with no username, it prompts you to fill in the username. ![Screenshot of no username](static/images/testing/no-login-username.png) - When the form is submitted with no password, it prompts you to fill in the password. ![Screenshot of no password](static/images/testing/no-login-password.png) - When the form is submitted with a username that does not exist, it provides a flash message and reloads. ![Screenshot of flash message](static/images/testing/incorrect-username-or-password.png) - When the form is submitted with the incorrect password, it provides a flash message and reloads. ![Screenshot of flash message](static/images/testing/incorrect-username-or-password.png) - When the form is submitted with a correct username and password it logs you in and redirects to the home page. ## Testing logout functionality: - When the user is logged in and clicks "logout" they are successfully logged out and redirected to the home page. ![Screenshot of successful logout](static/images/testing/logout-test.png) ## Testing the add book functionality: - When the form is submitted with no book name it prompts you to fill in the book name. ![Screenshot of unfilled book name](static/images/testing/no-book-name.png) - When the form is submitted with no author it prompts you to fill in the author. ![Screenshot of unfilled author](static/images/testing/no-author.png) - If you try to add a book that already exists in the database a flash message appears to tell you this, you are redirected to the `add_review` page with the book field filled in and the book is not added. ![Screenshot of flash message](static/images/testing/book-exists.png) - If you fill in a new book and it's author, you are redirected to the `add_review` page with the book field filled in and a flash message appears to say that you were successful in adding the review. ![Screenshot of flash message](static/images/testing/book-added.png) ## Testing the add review functionality: - When the form is submitted with no book it prompts you to fill in the book. ![Screenshot of unfilled book](static/images/testing/no-book.png) - When the form is submitted with a book that does not exist a flash message appears to tell you this. ![Screenshot of non-existent book](static/images/testing/book-not-found.png) - When the form is submitted with no review text it prompts you to fill in the review text. ![Screenshot of unfilled review text](static/images/testing/no-review-text.png) - When the form is submitted with no star choice it does not let you submit the form. - When the form is submitted with a book you've already reviewed a flash message appears to tell you this. ![Screenshot of flash message](static/images/testing/already-reviewed.png) - When the form is submitted successfully a flash message appears to tell you this, you are redirected to the home page and the review is added to the database. ![Screenshot of flash message](static/images/testing/review-added.png) # Bugs Discovered - Bug with `edit_book` method not editing the book: - While testing the edit_book method, I noticed that for some books the edit_book method was not actually editing the book when the form was submitted despite no errors showing up. - I then realised this was only happening when the title of the book was edited. - This was due to the POST method for the function updating the book in the database according to the book name: ![Screenshot of line in POST method where book is updated according to book_name](static/images/testing/book-name-search.png) - If the book name had been changed, then nothing was getting updated in the database as there was no book in the database with the new book name. - I fixed this by changing the POST method to update the book record according to it's `_id` field: ![Screenshot of line in POST method where book is updated according to _id](static/images/testing/book-id-search.png) - Bug with `add_book` page form submitting when autofill buttons are pressed: - While testing the autofill buttons on the `add_book` page, I noticed that if all the fields were filled the form was submitted when clicking the autofill buttons, not just the submit button. - After some googling, I discovered this was as I had not set the type of the autofill buttons so once I set their type attribute to `button`, the bug was fixed. ![Screenshot of type="button" on autofill button](static/images/testing/type-button.png)