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
JavaScript
UTF-8
282
3.421875
3
[]
no_license
let myFn = async() => { return "Hello there"; }; async function foo() { try { let response = await fetch("http://random.dog/woof.json"); //this replaces .then let json = await response.json(); } catch(err) { console.error(err); } } foo();
Java
UTF-8
1,649
3.234375
3
[]
no_license
package com.company; import com.company.sistema.SistemaMenuLogin; import java.util.InputMismatchException; import java.util.Scanner; public class MenuLogin { Scanner input = new Scanner(System.in); public void MenuLogin() { int opcao = 0; boolean continua = true; SistemaMenuLogin novoSistemaMenuLogin = new SistemaMenuLogin(); while (true) { do { System.out.println("Selecione :\n" + "1 : Fazer Login\n" + "2 : Criar Conta\n" + "0 : Fechar\n"); try { opcao = input.nextInt(); continua = false; } catch (InputMismatchException erro1) { System.out.println("Não é permitido inserir letras ou símbolos, informe apenas números inteiros"); input.nextLine();//descarta entrada errada do usuário continua = true; } } while (continua); switch (opcao) { case 1://Fazer Login novoSistemaMenuLogin.fazerLogin(DadosLojaseContas.Contas); break; case 2://Criar Conta novoSistemaMenuLogin.criarConta(DadosLojaseContas.Contas); break; case 0://Fechar System.out.println("Fechando..."); return; default: System.out.println("Digite uma opção válida"); } } } }
C#
UTF-8
322
2.5625
3
[]
no_license
using System; namespace eXpressionParsing { class PI : RealNumber { public PI() : base("pi") { } public override Operand Copy() { return new PI(); } public override double Calculate(double x) { return Math.PI; } } }
Markdown
UTF-8
7,171
2.765625
3
[]
no_license
TP N°4 Monitoreo Teoria: Maven: Goals: Comandos Para la consola de mvn que realizan distintas acciones. $ mvn compile – compila el proyecto y deja el resultado en target/classes $ mvn test – compila los test y los ejecuta $ mvn package – empaqueta el proyecto y lo dejará en taget/autentiaNegocio-1.0-SNAPSHOT.jar $ mvn install – guarda el proyecto en el repositorio $ mvn clean – borra el directorio de salida (target) Scopes: es una seccion dentro de <dependency> en el archivo pom.xml de maven, el cual es usado para indicar de que tipo de libreria se trata esa dependencia. compile – es el valor por defecto. Se utiliza en todos los casos (compilar, ejecutar, …). provided – también se utiliza en todos los casos, pero se espera que el jar sea suministrado por la JDK o el contenedor. Es decir, no se incluirá al empaquetar el proyecto, ni en el repositorio. runtime – no se utiliza para compilar, pero si es necesario para ejecutar. test – Sólo se utiliza para compilar o ejecutar los test. system – es similar a provided, pero eres tu el que tiene que suministrar el jar. No se incluirá al empaquetar el proyecto, ni en el repositorio. import - Este scope solo es admitido en dependencias de tipo POM, en la sección <dependencyManagement>, Indica la dependencia a reemplazar con la lista efectiva de dependencias en la dependencyManagement. ¿Que es un Arquetype? Podríamos decir que un “arquetipo” para Maven es una plantilla. Es decir, gracias a un arquetipo Maven es capaz de generar una estructura de directorios y ficheros. Es decir que con maven, basta decirle que tipo de proyecto queremos y maven generara automaticamente la estructura base. Defina la estructura base de un proyecto de maven. |-- pom.xml -> Archivo de configuracion de maven, para agregar dependecias, version de programa , etc |-- src -> carpeta que contendra nuestro proyecto |-- main | `-- java | `-- com | `-- autentia -> dentro de esta carpeta (que varia su nombre en base al nombre del proyecto) podremos agregar carpetas, para agregar mvc a nuestro proyecto | `-- demoapp | `-- App.java `-- test -> carpeta que contendra los distintos test de nuestra aplicacion. `-- java `-- com `-- autentia `-- demoapp `-- AppTest.java ¿Cual es la diferencia entre Arquetype y Artefact? Artefact es usualmente un archivo Jar, que se implementa en un repositorio de Maven. Cada artefacto tiene una ID de grupo (generalmente un nombre de dominio invertido, como com.example.foo), una ID de artefacto (solo un nombre) y una cadena de versión. Los tres juntos identifican de forma única el artefacto. Las dependencias de un proyecto se especifican como artefactos. La principal diferencia entre arquetype y artefact es que arquetype es una plantilla, genera la estructura de un proyecto maven para poder empezar a trabajar, mientras que artefact se utiliza para agregar librerias externas a nuestro programa, como por ejemplo cuando agregamos spring a nuestro proyecto maven. Explique los 4 stereotypes basicos y realize un diagrama de cada uno de ellos. ![foto1](https://www.arquitecturajava.com/wp-content/uploads/SpringStereotypes.png) @Component: Es el estereotipo general y permite anotar un bean para que Spring lo considere uno de sus objetos. @Repository: Es el estereotipo que se encarga de dar de alta un bean para que implemente el patrón repositorio que es el encargado de almacenar datos en una base de datos o repositorio de información que se necesite. Al marcar el bean con esta anotación Spring aporta servicios transversales como conversión de tipos de excepciones. ![foto2](https://www.arquitecturajava.com/wp-content/uploads/SpringStereotypesRepository.png) @Service : Este estereotipo se encarga de gestionar las operaciones de negocio más importantes a nivel de la aplicación y aglutina llamadas a varios repositorios de forma simultánea. Su tarea fundamental es la de agregador. ![foto3](https://www.arquitecturajava.com/wp-content/uploads/SpringStereotypesService.png) @Controller : El último de los estereotipos que es el que realiza las tareas de controlador y gestión de la comunicación entre el usuario y el aplicativo. Para ello se apoya habitualmente en algún motor de plantillas o librería de etiquetas que facilitan la creación de páginas. ![foto4](https://www.arquitecturajava.com/wp-content/uploads/SpringStereotypesController.png) REST Explique cada uno de los verbos. GET GET es el tipo más simple de método de solicitud HTTP; La que usan los navegadores cada vez que hace clic en un enlace o escribe una URL en la barra de direcciones. Indica al servidor que transmita los datos identificados por la URL al cliente. Los datos nunca deben ser modificados en el lado del servidor como resultado de una solicitud GET. En este sentido, una petición GET es de sólo lectura, pero por supuesto, una vez que el cliente recibe los datos, es libre de hacer cualquier operación con ella por su cuenta, por ejemplo, formatearla para su visualización. PUT Una petición PUT se utiliza cuando se desea crear o actualizar el recurso identificado por la URL. Por ejemplo, PUT /clients/robin Podría crear un cliente, llamado Robin en el servidor. DELETE DELETE debe realizar lo contrario de PUT; Debe utilizarse cuando desee eliminar el recurso identificado por la URL de la solicitud. POST POST se utiliza cuando el procesamiento que desea que suceda en el servidor debe repetirse, si la solicitud POST se repite (es decir, no son idempotent, más de esto a continuación). Además, las solicitudes POST deben causar el procesamiento del cuerpo de la solicitud como un subordinado de la URL que está publicando. En palabras claras: POST /clients/ No debe causar que el recurso en /clients/, se modifique, sino un recurso cuya URL comience con /clients/. Por ejemplo, podría agregar un nuevo cliente a la lista, con un ID generado por el servidor. HEAD El método HEAD es idéntico a GET, excepto que el servidor NO DEBE devolver un cuerpo del mensaje en la respuesta. La metainformación contenida en los encabezados HTTP en respuesta a una solicitud HEAD DEBERÍA ser idéntica a la información enviada en respuesta a una solicitud GET. Este método se puede usar para obtener metainformación sobre la entidad implicada por la solicitud sin transferir el cuerpo de la entidad en sí. Este método se usa a menudo para probar enlaces de hipertexto para determinar su validez, accesibilidad y modificaciones recientes. OPTIONS El método OPTIONS representa una solicitud de información sobre las opciones de comunicación disponibles en la cadena de solicitud / respuesta identificadas por el URI de solicitud. Este método permite al cliente determinar las opciones y / o requisitos asociados con un recurso, o las capacidades de un servidor, sin implicar una acción de recurso o iniciar una recuperación de recursos.
JavaScript
UTF-8
2,810
3.734375
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* Your Code Here */ /* We're giving you this function. Take a look at it, you might see some usage that's new and different. That's because we're avoiding a well-known, but sneaky bug that we'll cover in the next few lessons! As a result, the lessons for this function will pass *and* it will be available for you to use if you need it! */ function createEmployeeRecord(employeeRecord) { const newRecord = { firstName: employeeRecord[0], familyName: employeeRecord[1], title: employeeRecord[2], payPerHour: employeeRecord[3], timeInEvents: [], timeOutEvents: [] } return Object.assign( {}, newRecord ) } function createEmployeeRecords(records) { return records.map( e => createEmployeeRecord(e) ) } function createTimeInEvent(dateStamp) { const dateArray = dateStamp.split(' ') const newDate = dateArray[0] const hour = parseInt(dateArray[dateArray.length - 1], 10) const timeIn = { type: "TimeIn", hour: hour, date: newDate } this.timeInEvents.push( timeIn ) return this } function createTimeOutEvent(dateStamp) { const [newDate, hour] = dateStamp.split(' ') const timeOut = { type: "TimeOut", hour: parseInt(hour, 10), date: newDate } this.timeOutEvents.push( timeOut ) return this } function hoursWorkedOnDate(dateWorked) { const dateIndex = this.timeInEvents.findIndex( e => e.date === dateWorked ) const punchedInTime = this.timeInEvents[dateIndex].hour const punchedOutTime = this.timeOutEvents[dateIndex].hour return parseInt( ( removeDoubleZeros(punchedOutTime) - removeDoubleZeros(punchedInTime) ), 10) } function wagesEarnedOnDate(dateWorked) { const hoursWorked = hoursWorkedOnDate.call(this, dateWorked) return hoursWorked * this.payPerHour } // function allWagesFor(employeeRecord) { // const wagesArray = employeeRecord.timeInEvents.map( e => { // return wagesEarnedOnDate(employeeRecord, e.date) // }) // return wagesArray.reduce( (a, c) => a + c ) // } function findEmployeeByFirstName(allEmployeeArray, firstName) { return allEmployeeArray.find( e => e.firstName === firstName ) } function calculatePayroll(employeeRecords) { return employeeRecords.map(e => allWagesFor.call(e)).reduce( (a, c) => a + c ) } let allWagesFor = function () { let eligibleDates = this.timeInEvents.map(function (e) { return e.date }) let payable = eligibleDates.reduce(function (memo, d) { return memo + wagesEarnedOnDate.call(this, d) }.bind(this), 0) // <== Hm, why did we need to add bind() there? We'll discuss soon! return payable } function removeDoubleZeros(num) { return num.toString().replace( "00", "") }
PHP
UTF-8
8,919
2.625
3
[ "MIT" ]
permissive
<?php namespace Ipunkt\LaravelJsonApi\Resources; use Illuminate\Contracts\Foundation\Application; use Illuminate\Support\Collection; use Ipunkt\LaravelJsonApi\Contracts\FilterFactories\FilterFactory; use Ipunkt\LaravelJsonApi\Contracts\RelatedRepository; use Ipunkt\LaravelJsonApi\FilterFactories\ArrayFilterFactory; use Ipunkt\LaravelJsonApi\Http\RequestHandlers\DefaultRequestHandler; use Ipunkt\LaravelJsonApi\Serializers\Serializer; use Tobscure\JsonApi\AbstractSerializer; use Tobscure\JsonApi\SerializerInterface; class ResourceManager { /** * definitions * * @var \Illuminate\Support\Collection */ private $definitions; /** * dependency injection * * @var Application */ private $app; /** * current version for fluent interface * * @var int */ private $version; /** * ResourceManager constructor. * @param Application $app */ public function __construct(Application $app) { $this->app = $app; $this->definitions = collect(); } /** * defines a new resource * * @param string $resource * @param int|callable|\Closure $versionOrClosure * @param null|callable|\Closure $closureOrDescription * @param string $description * @return ResourceManager|static */ public function define(string $resource, $versionOrClosure, $closureOrDescription = null, string $description = null) { $version = $this->version; $closure = $closureOrDescription; if ($versionOrClosure instanceof \Closure) { $version = $this->version; $closure = $versionOrClosure; $description = $closureOrDescription; } if (is_numeric($versionOrClosure)) { $version = intval($versionOrClosure); } $this->definitions->push(new ResourceDefinition($version, $resource, $description)); $resourceDefinition = $this->definition($resource, $version); call_user_func_array($closure, [$resourceDefinition]); return $this; } /** * returns definition for resource and version * * @param string $resource * @param int $version * @return ResourceDefinition * @throws ResourceNotDefinedException when no definition found */ public function definition(string $resource, int $version = null) : ResourceDefinition { $version = $version ?? $this->version; if (str_contains($resource, '.')) { list($resource, $related) = explode('.', $resource); $definition = $this->definition($resource, $version); $relatedDefinition = $definition->relations->filter(function (ResourceDefinition $definition) use ($related, $version) { return $definition->version === $version && $definition->resource === $related; }); if($relatedDefinition->isEmpty()) throw ResourceNotDefinedException::resource($resource, 'version ' . $version); return $relatedDefinition->first(); } $found = $this->definitions->filter(function (ResourceDefinition $definition) use ($resource, $version) { return $definition->version === $version && $definition->resource === $resource; }); if ($found->isEmpty()) { throw ResourceNotDefinedException::resource($resource, 'version ' . $version); } return $found->first(); } /** * set version for fluent interface * * @param int $version * @return ResourceManager */ public function version(int $version) : ResourceManager { $this->version = $version; return $this; } /** * returns all available versions * * @return Collection */ public function versions() { return $this->definitions->unique('version')->pluck('version'); } /** * returns all resources * * @param int $version * @return Collection */ public function resources(int $version = null) { $version = $version ?? $this->version; return $this->definitions->filter(function (ResourceDefinition $definition) use ($version) { return $definition->version === $version; })->pluck('resource'); } /** * resolves a definition or related definition * * @param string $type * @param string $resource * @param array $parameters * @param string|null $version * @return mixed|string */ public function resolve(string $type, string $resource, array $parameters = [], $version = null) { $version = $version ?? $this->version; if (str_contains($resource, '.')) { list($resource, $related) = explode('.', $resource); $resourceDefinition = $this->loadRelatedDefinition($version, $resource, $related, $type); } else { $resourceDefinition = $this->loadDefinition($version, $resource, $type); } return $this->app->make($resourceDefinition, $parameters); } /** * resolves a serializer * * @param string $resource * @param array $parameters * @param int $version * @return SerializerInterface|AbstractSerializer|Serializer * @throws ResourceNotDefinedException when no serializer configured */ public function resolveSerializer($resource, array $parameters = [], $version = null) { return $this->resolve('serializer', $resource, $parameters, $version); } /** * resolves a repository * * @param string $resource * @param array $parameters * @param null|string $version * @return \Ipunkt\LaravelJsonApi\Contracts\Repositories\JsonApiRepository|RelatedRepository * @throws ResourceNotDefinedException when no repository configured */ public function resolveRepository($resource, array $parameters = [], $version = null) { return $this->resolve('repository', $resource, $parameters, $version); } /** * resolves a controller * * @param string $resource * @param array $parameters * @param null|string $version * @param bool $resolveDefaultRequestHandler * @return \Ipunkt\LaravelJsonApi\Contracts\RequestHandlers\ApiRequestHandler */ public function resolveRequestHandler( $resource, array $parameters = [], $version = null, $resolveDefaultRequestHandler = true ) { try { return $this->resolve('requestHandler', $resource, $parameters, $version); } catch (ResourceNotDefinedException $e) { if ($resolveDefaultRequestHandler) { return $this->app->make(DefaultRequestHandler::class, $parameters); } throw $e; } } /** * resolves a filter factory * * @param string $resource * @param array $parameters * @param null|string $version * @return \Ipunkt\LaravelJsonApi\Contracts\FilterFactories\FilterFactory */ public function resolveFilterFactory($resource, array $parameters = [], $version = null) { try { return $this->resolve('filterFactory', $resource, $parameters, $version); } catch (ResourceNotDefinedException $e) { return $this->app->make(ArrayFilterFactory::class, $parameters); } } /** * loads a definition * * @param string $version * @param string $resource * @param string $type * @param string $key * @return string */ private function loadDefinition($version, $resource, $type, $key = null) : string { $definition = $this->definition($resource, $version); $classPath = $definition->$type; if (is_array($classPath) && array_key_exists($key, $classPath)) { $classPath = $classPath[$key]; } if ($classPath === null) { throw ResourceNotDefinedException::resource($resource, $type); } return $classPath; } /** * loads a related definition * * @param string $version * @param string $resource * @param string $related * @param string $type * @param string $key * @return string */ private function loadRelatedDefinition($version, $resource, $related, $type, $key = null) : string { $definition = $this->definition($resource, $version); $relationDefinition = $definition->relation($related); $classPath = $relationDefinition->$type; if (is_array($classPath) && array_key_exists($key, $classPath)) { $classPath = $classPath[$key]; } if ($classPath === null) { throw ResourceNotDefinedException::resource($resource, $type); } return $classPath; } }
Markdown
UTF-8
905
2.5625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- description: Page-Space to Device-Space Transformations ms.assetid: 5505cf7a-7b9c-4728-934d-7faa4bdfde30 title: Page-Space to Device-Space Transformations ms.topic: article ms.date: 05/31/2018 --- # Page-Space to Device-Space Transformations The page-space to device-space transformation determines the mapping mode for all graphics output associated with a particular DC. A *mapping mode* is a scaling transformation that specifies the size of the units used for drawing operations. The mapping mode may also perform translation. In some cases, the mapping mode alters the orientation of the x-axis and y-axis in device space. The following topics describe the mapping modes. - [Mapping Modes and Translations](mapping-modes-and-translations.md) - [Predefined Mapping Modes](predefined-mapping-modes.md) - [Application-Defined Mapping Modes](application-defined-mapping-modes.md)    
Python
UTF-8
74
2.734375
3
[]
no_license
x=int(input()) print(sum([x-int(input())for _ in range(int(input()))])+x)
Java
UTF-8
6,276
2.203125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package porto2; /** * * @author newton */ public class EntradaProdutoJPanel extends javax.swing.JPanel { /** * Creates new form AlmoxarifadoJPanel */ public EntradaProdutoJPanel() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { produtojComboBox = new javax.swing.JComboBox<>(); produtojLabel = new javax.swing.JLabel(); quantidadejLabel = new javax.swing.JLabel(); quantidadejTextField = new javax.swing.JTextField(); validadejLabel = new javax.swing.JLabel(); validadejFormattedTextField = new javax.swing.JFormattedTextField(); cadastrarjButton = new javax.swing.JButton(); limparjButton = new javax.swing.JButton(); setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Entrada de produtos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 18))); // NOI18N produtojComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); produtojLabel.setText("Produto:"); quantidadejLabel.setText("Quantidade:"); validadejLabel.setText("Validade:"); validadejFormattedTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter())); cadastrarjButton.setText("Cadastrar"); limparjButton.setText("Limpar"); limparjButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { limparjButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(validadejLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(validadejFormattedTextField)) .addGroup(layout.createSequentialGroup() .addComponent(produtojLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(produtojComboBox, 0, 138, Short.MAX_VALUE))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(quantidadejLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(quantidadejTextField)) .addGroup(layout.createSequentialGroup() .addComponent(cadastrarjButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(limparjButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(produtojComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(produtojLabel) .addComponent(quantidadejLabel) .addComponent(quantidadejTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(validadejLabel) .addComponent(validadejFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cadastrarjButton) .addComponent(limparjButton)) .addGap(0, 13, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void limparjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_limparjButtonActionPerformed // TODO add your handling code here: quantidadejTextField.setText(""); validadejFormattedTextField.setText(""); produtojComboBox.setSelectedIndex(0); }//GEN-LAST:event_limparjButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cadastrarjButton; private javax.swing.JButton limparjButton; private javax.swing.JComboBox<String> produtojComboBox; private javax.swing.JLabel produtojLabel; private javax.swing.JLabel quantidadejLabel; private javax.swing.JTextField quantidadejTextField; private javax.swing.JFormattedTextField validadejFormattedTextField; private javax.swing.JLabel validadejLabel; // End of variables declaration//GEN-END:variables }
Markdown
UTF-8
869
2.9375
3
[]
no_license
# Expenses and Cash Flow - Similar to cash for sales, expenses payment can go out before, at or after the services/goods have been delivered. Acompany pays rent of $1000 ## Case 1: Expense and Payment happens at same time <img src="../Images/S6_Expense_Payment_atsametime.PNG" alt="Expense cash at same time"/> ## Case 2: Firm can delay the payment by 60 days - Expense to be paid after 60 days <img src="../Images/S6_Expense_tobepaid_After_60days.PNG" alt="Services Rendered"/> - Expense paid after 60 days <img src="../Images/S6_Expense_paid_After_60days.PNG" alt="Payment made"/> ## Case 3: Firm has to pay rent before the Expense - When firm pays the rent <img src="../Images/S6_expense_paid_before.PNG" alt="Prepayment made"/> After services were rendered <img src="../Images/S6_Expense_actually_paid.PNG" alt="Services rendered for prepayment made"/>
C
UTF-8
831
2.71875
3
[]
no_license
#ifndef RSF_VLSTACK_H #define RSF_VLSTACK_H #include <stdlib.h> #define ST_E_HEADNULL 10 #define ST_E_GROWUPFAIL 11 #define ST_E_HEADEMPTY 12 #define ST_E_NOERR 0 typedef struct _STACK_BLOCK{ long top; // Point to the top item of stack block long capacity; // Capacity of the stack char *data; // data array struct _STACK_BLOCK* prev; // Previously stack block struct _STACK_BLOCK* next; // Next stack block }STACK_BLOCK; typedef struct{ STACK_BLOCK* first; STACK_BLOCK* tail; // Point to the CURRENTLY used stack block }STACK; STACK* st_init(); char st_push(STACK *st, char data); char st_pop(STACK *st); char st_isemptyb(STACK *st); char st_isempty(STACK *st); char st_freeb(STACK *st); void st_frees(STACK *st); long st_getcapb(STACK *st); long st_gettopb(STACK *st); #endif
Markdown
UTF-8
3,014
2.59375
3
[ "MIT" ]
permissive
--- layout: about title: about permalink: / description: The Lawler group research site seeking breakthroughs in condensed matter physics. profile: align: right image: Michael_Lawler_in_Erice.jpg address: > <p>2012 Smart Energy Building</p> <p>Binghamton University, Vestal, NY 13850</p> <p>523 Clark Hall</p> <p>Cornell University, Ithaca, NY 14850</p> news: true # includes a list of news items selected_papers: true # includes a list of papers marked as "selected={true}" social: true # includes social icons at the bottom of the page --- We are a group of people interested in the physics of strongly correlated systems: system that are composed of many "degrees of freedom" that interactly strongly leading to emergent phenomena. We have historical had expertise in highly frustrated magnetism and strongly correlated electrons such as non-Fermi liquids and high temperature superconductivity. But recently have branched out to study quantum computing and machine learning in the hopes that these new fashionable methods will help us better understand the emergent phenomena we study. ## Pictures of us <img src="/assets/img/Lawler_Group_Graduate Students_Fall_2016.png" alt="Todd, Kyle and Pat in 2015" height = 190 width="388" /> From left to right: - Todd Rutkowski (Binghamton Graduate) - Patrick O'Brien (Binghamton Graduate) - Kyle G. Sherman (Binghamton Graduate) <img src="/assets/img/KrishanuRoyChowdury.jpg" alt="Krishanu Roychowdhury in 2016" height=190 width=189 /> Krishanu Roychowdhury in 2016 (postdoc) ## Our Graduate Students - Eric Aspling (Binghamton Graduate - Mabrur Ahmed (Binghamton Graduate) - Gaurav Gyawali (Cornell Graduate) - Po-Wei Lo (Cornell Graduate) - Kyle G. Sherman (Binghamton Graduate) ## Former Group Members - Kaixiang Su (Peking University Visiting Undergraduate) - Krishanu Roychowdury (Cornell Postdoc) - Todd Rutkowski (Binghamton Graduate) - Patrick O'Brien (Binghamton Graduate) - Junping Shao (Binghamton Graduate) - Ian MacCormack (Cornell Undergraduate) - Benjamin Sung (Cornell Undergraduate) - Ashwathi Iyer (Cornell Undergraduate) - Nina Pikula (Binghamton Undergraduate) - Belinda Pang (Cornell Undergraduate) - Steven Collazos (Binghamton Undergraduate) - Junping Shao (Cornell Undergraduate, Binghamton Graduate) <!-- Write your biography here. Tell the world about yourself. Link to your favorite [subreddit](http://reddit.com). You can put a picture in, too. The code is already in, just name your picture `prof_pic.jpg` and put it in the `img/` folder. Put your address / P.O. box / other info right below your picture. You can also disable any these elements by editing `profile` property of the YAML header of your `_pages/about.md`. Edit `_bibliography/papers.bib` and Jekyll will render your [publications page](/al-folio/publications/) automatically. Link to your social media connections, too. This theme is set up to use [Font Awesome icons](http://fortawesome.github.io/Font-Awesome/) and [Academicons](https://jpswalsh.github.io/academicons/), like the ones below. Add your Facebook, Twitter, LinkedIn, Google Scholar, or just disable all of them. -->
Python
UTF-8
715
3.4375
3
[]
no_license
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxPathSum(self, root: TreeNode) -> int: res = [-float('inf')] self._max_path_sum(root, res) return res[0] def _max_path_sum(self, root, res): """ Returns the max sum between the left and right subtree. """ if not root: return 0 left_sum = max(self._max_path_sum(root.left, res), 0) right_sum = max(self._max_path_sum(root.right, res), 0) res[0] = max(root.val + left_sum + right_sum, res[0]) return root.val + max(left_sum, right_sum)
Markdown
UTF-8
4,454
3.1875
3
[ "MIT" ]
permissive
# caesar _a classic cipher cli_ ## Installation ```shell $ go install github.com/stripedpajamas/caesar/cmd/... $ caesar help ``` generally the syntax is ```shell caesar -c <cipher> -k <key> -t <text> <encrypt|decrypt> ``` leave off `-t <text>` and caesar will read from stdin. optionally you can also provide a `--groups` or `-g` parameter to specify how the output should be grouped. the default value is 5. groups setting is ignored for decrypt operations. ```shell # encrypting using caesar cipher $ caesar -c caesar -k m -t "peter" encrypt BQFQD $ caesar -c caesar -k m -t "BQFQD" decrypt PETER ``` ciphers implemented: - caesar https://en.wikipedia.org/wiki/Caesar_cipher - playfair https://en.wikipedia.org/wiki/Playfair_cipher - vigenere https://en.wikipedia.org/wiki/Vigenère_cipher - ADFGX https://en.wikipedia.org/wiki/ADFGVX_cipher (ADFGVX is not implemented) - Bifid https://en.wikipedia.org/wiki/Bifid_cipher generally all the ciphers operate on english alphabetic letters (a-z). plaintext and keys are both specified as letters (although a number works for the caesar cipher as well, see below). ## Using Different Ciphers ### Caesar - encryption removes all non-alphabetic characters (encrypting `abc123` == encrypting `abc`) - the key can be a letter or a number - the letter _x_ is interpreted as _a = x_ for the shift - the number _n_ is interpreted as _shift the alphabet n places_. concretely, this means keys _a, b, c, ..._ are equivalent to keys _0, 1, 2, ..._. - any number provided is wrapped around mod 26 - if a multi-letter key is provided, all but the first letter is ignored - example: ```shell $ caesar -c caesar -k m -t "peter" encrypt BQFQD $ caesar -c caesar -k m -t "BQFQD" decrypt PETER ``` ### Playfair - encryption removes all non-alphabetic characters (encrypting "abc123" == encrypting "abc") - the key should be a keyword (anything else would be equivalent encrypting without a key) - `j` is merged with `i`, so decrypting an encryption of "Joel" will result in "Ioel" - odd-length plaintext and double-letters are padded with `X`, unless the double letter is an `X`, then it is padded with `Q` - example: ```shell $ caesar -c playfair -k secret -t "peter" encrypt OCSCC Y $ caesar -c playfair -k secret -t "OCSCCY" decrypt PETERX ``` ### Vigenère - encryption removes all non-alphabetic characters (encrypting "abc123" == encrypting "abc") - non-alphabetic characters are ignored if present in the key - an empty key will return an error - example: ```shell $ caesar -c vigenere -k hotsauce -t "let's eat some cheerios" encrypt SSMKE UVWVA XUHYG VPCL $ caesar -c vigenere -k hotsauce -t "SSM KEU VWV AXU HYG VPC L" decrypt LETSEATSOMECHEERIOS ``` ### ADFGX - encryption removes all non-alphabetic characters (encrypting "abc123" == encrypting "abc") - this is not ADFGVX, so numbers are no supported - two keys are required for this cipher, one for the polybius square and one for the transposition step - the keys should be comma delimited when running (e.g. `-k keyOne,keyTwo`) - non-alphabetic characters are ignored if present in either key - if either key is empty, it will return an error - example: ```shell $ caesar -c adfgx -k help,me -t "this is a test" encrypt GAAFA FXGDF GGAFG FGAGA GG $ caesar -c adfgx -k help,me -t "GAAFA FXGDF GGAFG FGAGA GG" decrypt THISISATEST ``` ### Bifid - encryption removes all non-alphabetic characters (encrypting "abc123" == encrypting "abc") - non-alphabetic characters are ignored if present in either key - example: ```shell $ caesar -c bifid -k golden -t spandex encrypt SAGXW DX $ caesar -c bifid -k golden -t sagxwdx decrypt SPANDEX ``` ## Other options - group output in chunks ```shell $ caesar -g 10 -c caesar -k m -t "mary had a little lamb whose fleece was white as snow" encrypt YMDKTMPMXU FFXQXMYNIT AEQRXQQOQI MEITUFQMEE ZAI ``` - read from stdin ```shell $ cat my_love_letter.txt | caesar -c caesar -k 5 encrypt NKDTZ WJWJF INSLY MNXYM FYXUW JYYDH TTQ ``` - chaining (careful when chaining ciphers that use a polybius square with ciphers that don't, as the I/J situation can get wonky) ```shell $ echo "potatoes or potatos" | caesar -c caesar -k 7 e | caesar -c vigenere -k "poptarts" e LJPAA MERKM LOAYT NO $ echo "LJPAA MERKM LOAYT NO" | caesar -c vigenere -k "poptarts" d | caesar -c caesar -k 7 d POTATOESORPOTATOS ``` # License MIT
Markdown
UTF-8
671
2.84375
3
[]
no_license
# Is it possible to break the «curse of dimensionality»? Spatial specifications of multivariate volatility models Code for the paper in [Applied Econometrics](https://econpapers.repec.org/article/risapltrx/0249.htm) journal, 2014. The article is devoted to the estimation of multivariate volatility of a portfolio consisted from twenty American stocks. The six specifications of multivariate volatility models are formulated and estimated. It’s demonstrated that spatial specifications of multivariate volatility models allow not only reduce the dimension of the problem, but in some cases outdo original specifications at in-sample and out-of-sample comparison.
SQL
UTF-8
1,647
3.546875
4
[]
no_license
SET FOREIGN_KEY_CHECKS =0; DROP TABLE IF EXISTS `ers_operation_step`; CREATE TABLE `ers_operation_step` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增编码', `userId` bigint(20) NOT NULL COMMENT '员工编码', `empName` bigint(20) NOT NULL COMMENT '员工名称', `itemId` bigint(20) NOT NULL COMMENT '对象编码', `itemType` varchar(255) NOT NULL COMMENT '对象类型', `type` varchar(255) NOT NULL COMMENT '操作类型', `opTime` datetime DEFAULT NULL COMMENT '日期时间', `memo` varchar(255) DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`), KEY `userId_idx` (`userId`), KEY `itemId_idx` (`itemId`), KEY `itemType_idx` (`itemType`), KEY `opTime_idx` (`opTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='员工操作资料日志' ; -- ******************************************************************************************************************** -- 修改仓库相关属性记录日志 -- ******************************************************************************************************************** DROP PROCEDURE IF EXISTS `p_ers_operation_step_log`; DELIMITER ;; CREATE PROCEDURE `p_ers_operation_step_log`( uid BIGINT(20) -- autopart01_security.sec$user.id userId ,itemId BIGINT(20) -- 修改的数据的id ,itemType VARCHAR(191) -- 代码层entity名 ,type VARCHAR(191) -- c、r、u、d ) BEGIN DECLARE eName VARCHAR(100); SET eName = (SELECT a.name FROM autopart01_crm.erc$staff a WHERE a.userId = uid); INSERT INTO ers_operation_step(userId, empName, itemId, itemType, type, opTime) SELECT uid, eName, itemId, itemType, type, NOW(); END;; DELIMITER ;
Shell
UTF-8
2,272
3.921875
4
[]
no_license
#!/bin/bash rawurlencode() { local string="${1}" local strlen=${#string} local encoded="" for (( pos=0 ; pos<strlen ; pos++ )); do c=${string:$pos:1} case "$c" in [-_.~a-zA-Z0-9] ) o="${c}" ;; * ) printf -v o '%%%02x' "'$c" esac encoded+="${o}" done echo "${encoded}" # You can either set a return variable (FASTER) REPLY="${encoded}" #+or echo the result (EASIER)... or both... :p } USERNAME="admin"; if [ "$#" -ne 1 ]; then echo "Enter please ROUTER IP"; exit; fi clear; echo -e "Script for managment router TP-link by Sergey Zhuravel\n" echo "Connect to $1" IP=$1; IP_ADDRESS=`ping -c 2 $IP | grep -c "icmp"`; # ping ip address if [ $IP_ADDRESS -eq 0 ]; then echo "ping error"; exit; fi # input password printf 'Enter passsword: ' read -s PASSWORD # lenfth pasword PASSWORD_LENGTH=`echo -n $PASSWORD | wc -c` # check on length password if [ $PASSWORD_LENGTH -gt 0 ]; then echo -e "\n---" else echo "You don't enter password" exit 1; fi PASSWORD_MD5=`echo -n $PASSWORD | md5sum | cut -d " " -f 1`; COOKIE_B64_PART=`echo -n $USERNAME":"$(echo -n $PASSWORD_MD5)|base64`; COOKIEVAL_UNENCODED=`echo -n "Basic $COOKIE_B64_PART"`; COOKIEVAL=`rawurlencode "$COOKIEVAL_UNENCODED"` GET_KEY_URL=`echo "http://$IP/userRpm/LoginRpm.htm?Save=Save"` RESPONSE=`curl -s --cookie "Authorization=$COOKIEVAL" $GET_KEY_URL`; KEY=`echo $RESPONSE | head -n 1 | cut -d '/' -f 4` # extract key from post-login-page KEY_LENGTH=`echo -n $KEY | wc -c` # check version tp-link if [ $KEY_LENGTH -gt 0 ]; then # validate password VALIDATE_PASS=`curl -s --user admin:$PASSWORD --referer http://$IP/$KEY/userRpm/StatusRpm.htm http://$IP/$KEY/userRpm/StatusRpm.htm | grep -c Save` if [ $VALIDATE_PASS -gt 0 ]; then echo "PASS OK" echo "---" else echo "PASSWORD ERROR" exit; fi echo "Version type: new" ./conf_tplink.cfg $IP $PASSWORD else # validate password VALIDATE_PASS=`curl -s --user admin:$PASSWORD --referer http://$IP/userRpm/MenuRpm.htm http://$IP/userRpm/MenuRpm.htm | grep -c visible` if [ $VALIDATE_PASS -gt 0 ]; then echo "PASS OK" echo "---" else echo "PASSWORD ERROR" exit; fi echo "Version type: old" ./conf_tplink_old.cfg $IP $PASSWORD fi
C
UTF-8
955
3.359375
3
[]
no_license
#include <stdio.h> #include <setjmp.h> #include <signal.h> jmp_buf env; // 保存待跳转位置的栈信息 /*信号SIGRTMIN+15的处理函数*/ void handler_sigrtmin15(int signo) { printf("recv SIGRTMIN+15\n"); longjmp(env, 1); // 返回到env处,注意第二个参数的值 } /*信号SIGRTMAX-15的处理函数*/ void handler_sigrtmax15(int signo) { printf("recv SIGRTMAX-15\n"); longjmp(env, 2); // 返回到env处,注意第二个参数的值 } int main() { /*设置返回点*/ switch (setjmp(env)) { case 0: break; case 1: printf("return from SIGRTMIN+15\n"); break; case 2: printf("return from SIGRTMAX-15\n"); break; default: break; } /*捕捉信号,安装信号处理函数*/ signal(SIGRTMIN+15, handler_sigrtmin15); signal(SIGRTMAX-15, handler_sigrtmax15); while (1); return 0; }
Python
UTF-8
678
2.78125
3
[]
no_license
import pandas as pd import numpy as np dt = pd.read_csv("train.csv") nv = ['PassengerId','Pclass','Age','SibSp','Parch','Fare'] dt['Age'] = dt['Age'].fillna(dt['Age']).median() y = dt['Survived'] from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(dt[nv],dt['Survived'],test_size=0.2,random_state=0) from sklearn.ensemble import RandomForestClassifier model=RandomForestClassifier(n_estimators=100) model.fit(X_train,Y_train) #test = pd.read_csv('test.csv') #test['Age'] = test['Age'].fillna(test['Age']).median() #test = test[nv].fillna(test.mean()) yp = model.predict(X_test) print(yp) print(model.score(X_test,Y_test))
Go
UTF-8
442
3.109375
3
[]
no_license
package main import "fmt" import "github.com/texttheater/golang-levenshtein/levenshtein" /* Doesn't work, raised ticket https://github.com/texttheater/golang-levenshtein/issues/11 */ func main() { source := "kitten" target := "sitting" distance := levenshtein.DistanceForStrings([]rune(source), []rune(target), levenshtein.DefaultOptions) fmt.Printf("The distance between '%s' and '%s' computed as %d.\n", source, target, distance) }
Markdown
UTF-8
3,166
3.671875
4
[]
no_license
# Angular Visibility API This is an Angular service for interacting with Browser's Visibility API. This API is useful when you want to know whether your application is currently being viewed by the user or if the tab/window is in the background. ## Usage To use this service, the `VisibilityModule` must be imported into your app or dependent module. ```typescript @NgModule({ ... imports: [ ..., VisibilityModule, ... ] }) export class MyModule {} ``` ## VisibilityService The visibility service works in all major browsers. If the browser does not have support for the visibility API, the service will fallback to a legacy method for determining browser visibility. The service has a single public method `onVisibilityChange` which returns an `Observable<Boolean>`. When the caller subscribes to the visibility changes of the `Observable`, the subscribe handler will be called immediately with the current value of the browser's visibility. All future changes to the visibility will be published to all subscribing methods. For more information see the example below. ```typescript @Component({ ... }) export class MyComponent { constructor(private visibility: VisibilityService) {} ... this.visibility.onVisibliltyChange().subscribe((isVisible) => { if (isVisible) { //perform actions that need to be done when browser if visible } else { //perform actions when browser has been hidden } }) } ``` ## Decorators There is also the option to use provided method decorators to decorate methods that should only be run based on a certain browser visibility or when the visibility of the browser changes ### @OnVisibilityChange() Any method decorated with this annotation will be called each time the browser visibility changes. This is very similar to subscribing to events from the `VisibilityService`, just providing another convenience method for interacting with the service. Methods decorated with this annotation should accept one parameter `isVisible` that will be provided to the decorated method when the visibility change fires. ```typescript export class MyComponent { ... @OnVisibilityChange() visibilityChanged(isVisible: Boolean) { if (isVisible) { //perform actions that need to be done when browser if visible } else { //perform actions when browser has been hidden } } } ``` ### @WhenVisibilityIs(isVisible: Boolean) Another method for interacting with the `VisibilityService` is to decorate a method with this decorator. The `@WhenVisibilityIs` decorator takes a boolean value that indicates, based on the provided browser visibility status, whether the decorated method should be invoked or not. ```typescript export class MyComponent { ... @WhenVisibilityIs(true) executeOnlyWhenVisible(someArg: string, anotherArg: number) { //this method only gets invoked (when called) if the application window is determined to be visible to the user. } @WhenVisibilityIs(false) executeOnlyWhenHidden() { //this method only gets invoked (when called) if the application window is determined to be hidden to the user. } } ```
Java
UTF-8
12,476
1.84375
2
[]
no_license
package com.yunma.controller.mapCount; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.sql.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.common.controller.BaseController; import com.common.util.BaiduMapUtils; import com.common.util.Radix; import com.yunma.dao.user.UserDao; import com.yunma.entity.securityCode.SecurityCode; import com.yunma.entity.statAntiFakeCount.StatAntiFakeCount; import com.yunma.model.AntiFake; import com.yunma.model.TotalCount; import com.yunma.service.antiFakeService.AntiFakeService; import com.yunma.service.mapCount.MapCountService; import com.yunma.service.mapCount.MapLogicalCountService; import com.yunma.service.product.ProductOrderService; import com.yunma.service.secutrityCode.SecurityCodeService; import com.yunma.vo.mapCount.MapCountUserScanInfo; @Controller public class MapAntiFakeCountController extends BaseController { @Autowired private MapLogicalCountService countService; @Autowired private UserDao userDao; @Autowired private SecurityCodeService codeService; @Autowired private ProductOrderService orderService; @Autowired private AntiFakeService antiFakeService; @Autowired private MapCountService mapCountService; /** * 商家扫码统计 * * @param userId * @param vendorId * @return */ @RequestMapping("/GET/mapCount/mapAntiProCount.do") @ResponseBody public JSONObject getAntiFakeCount(Integer userId, Integer vendorId) { JSONObject result = new JSONObject(); if (userId != null || vendorId != null) { return countService.getCount(userId, vendorId); } else { result.put("msg", "请输入正确参数"); return result; } } /** * 管理员统计 * * @param userId * @return */ @RequestMapping("/GET/mapCount/sysMapCount.do") @ResponseBody public JSONObject getTotalCount(Integer userId) { JSONObject result = new JSONObject(); Integer userType = userDao.findUserType(userId); if (userType == 99) { return countService.getTotalCount(userId); } else { result.put("msg", "您不是管理员,请重新登录"); return result; } } /** * 商家二维码扫码统计 * * @param userId * @param vendorId * @return */ @RequestMapping("/GET/mapCount/mapSecurityCount.do") @ResponseBody public JSONObject getMapSecurityCount(Integer userId, Integer vendorId) { return countService.getMapSecurityCount(userId, vendorId); } /** * 商家最近七日扫码统计 * * @param userId * @param vendorId * @return */ @RequestMapping("/GET/mapCount/vendorWeekMapCount.do") @ResponseBody public JSONObject getWeekCount(Integer userId, Integer vendorId) { JSONObject result = new JSONObject(); Integer vendorId1 = userDao.getVendorIdByUserId(userId); if (vendorId1 == vendorId) { return countService.getWeekTotalCount(userId, vendorId); } else { result.put("msg", "您不是管理员,请重新登录"); return result; } } /** * 热力图 统计 * * @param vendorId * @return */ @RequestMapping("/GET/mapCount/count.do") @ResponseBody public JSONObject mapCount(Integer vendorId) { JSONObject result = new JSONObject(); JSONArray array = new JSONArray(); BaiduMapUtils util = new BaiduMapUtils(); List<StatAntiFakeCount> list = countService.mapCount(vendorId); if (list != null && list.size() > 0) { for (StatAntiFakeCount statAntiFakeCount : list) { JSONObject object = new JSONObject(); object.put("name", util.getProvinceNick(statAntiFakeCount.getProvince())); object.put("value", statAntiFakeCount.getCount()); object.put("selected", "true"); array.add(object); } } result.put("data", array); return result; } /*** * 扫码明细统计 * * @throws UnsupportedEncodingException * * */ @RequestMapping("/GET/mapCount/countInfo.do") @ResponseBody public JSONObject statisticsSecurityInfo(Integer vendorId) throws UnsupportedEncodingException { JSONObject result = new JSONObject(); JSONArray array = new JSONArray(); if(vendorId == 167){ List<AntiFake> antifakeList = countService.findAntiFakeListInfo(vendorId); if (antifakeList != null && antifakeList.size() > 0) { for (AntiFake antiFake : antifakeList) { JSONObject object = new JSONObject(); String securityCode = antiFake.getSecurityCode(); String nickNameDeco = codeService .getNickNameByOpenId(antiFake.getOpenId()); String nickName = URLDecoder.decode(nickNameDeco, "utf-8"); java.util.Date scanTime = antiFake.getScanTime(); String address = null; int count = codeService.findCodeScanCount(securityCode, vendorId); String productName = antiFake.getProductName(); String vendorName = userDao.getVendorNameByVendorId(vendorId); String picUrl = codeService.getPicUrlByOpenId(antiFake .getOpenId()); // if (count == 1) { object.put("errorCode", 1); } else { object.put("errorCode", -1); } object.put("securityCode", securityCode); object.put("nickName", nickName); object.put("scanTime", scanTime); object.put("address", address); object.put("vendorName", vendorName); object.put("productName", productName); object.put("picUrl", picUrl); object.put("count", count); array.add(object); } } result.put("data", array); return result; } List<StatAntiFakeCount> list = countService .getSucurityScanInfo(vendorId); if (list != null && list.size() > 0) { for (StatAntiFakeCount statAntiFakeCount : list) { String securityCode = statAntiFakeCount.getSecurityCode(); AntiFake antiFake = antiFakeService.getAntiFake(securityCode, vendorId); Integer orderId = Radix.convert62To10(securityCode.substring(0, 4)); JSONObject object = new JSONObject(); String nickNameDeco = codeService .getNickNameByOpenId(statAntiFakeCount.getOpenId()); String nickName = URLDecoder.decode(nickNameDeco, "utf-8"); Date scanTime = statAntiFakeCount.getScanTime(); String address = statAntiFakeCount.getProvince() + " " + statAntiFakeCount.getCity(); int count = codeService.findCodeScanCount(securityCode, vendorId); String productName = antiFake.getProductName(); String vendorName = userDao.getVendorNameByVendorId(vendorId); String picUrl = codeService.getPicUrlByOpenId(statAntiFakeCount .getOpenId()); // if (count == 1) { object.put("errorCode", 1); } else { object.put("errorCode", -1); } object.put("securityCode", securityCode); object.put("nickName", nickName); object.put("scanTime", scanTime); object.put("address", address); object.put("vendorName", vendorName); object.put("productName", productName); object.put("picUrl", picUrl); object.put("count", count); array.add(object); } } result.put("data", array); return result; } @RequestMapping("/GET/mapCount/tracingCountInfo.do") @ResponseBody public JSONObject tracingCodeScanInfo(Integer vendorId) throws UnsupportedEncodingException { JSONObject result = new JSONObject(); JSONArray array = new JSONArray(); List<StatAntiFakeCount> list = countService .getSucurityScanInfo(vendorId); if (list != null && list.size() > 0) { for (StatAntiFakeCount statAntiFakeCount : list) { String securityCode = statAntiFakeCount.getSecurityCode(); SecurityCode code = codeService.getSecurityCode(securityCode); Integer orderId = Radix.convert62To10(securityCode.substring(0, 4)); JSONObject object = new JSONObject(); String nickNameDeco = codeService .getNickNameByOpenId(statAntiFakeCount.getOpenId()); Date scanTime = statAntiFakeCount.getScanTime(); String address = statAntiFakeCount.getProvince() + " " + statAntiFakeCount.getCity(); int count = codeService.getScanCountpri(orderId, securityCode); String productName = code.getProductName(); String vendorName = userDao.getVendorNameByVendorId(vendorId); object.put("vendorName", vendorName); object.put("productName", productName); array.add(object); } } result.put("data", array); return result; } /** * 统计某省中所有城市的扫码数量 * * @param vendorId * @param province * @return */ @RequestMapping("/GET/mapCount/mapCountForCity.do") @ResponseBody public JSONObject mapCountForCity(HttpServletRequest request, Integer vendorId, String province) { try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } JSONObject result = new JSONObject(); JSONArray array = new JSONArray(); logger.debug("某某省::::::::" + province); List<StatAntiFakeCount> list = mapCountService.mapCountForCity( vendorId, province); if (list != null && list.size() > 0) { for (StatAntiFakeCount statAntiFakeCount : list) { JSONObject object = new JSONObject(); object.put("name", statAntiFakeCount.getCity()); object.put("value", statAntiFakeCount.getCount()); object.put("selected", "false"); array.add(object); } } result.put("data", array); return result; } /** * 统计某市各区县的扫码量 * * @param vendorId * @param district * @return */ @RequestMapping("/GET/mapCount/getDistrCount.do") @ResponseBody public JSONObject getDistrCount(HttpServletRequest request, Integer vendorId, String city) { try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } JSONObject result = new JSONObject(); JSONArray array = new JSONArray(); List<StatAntiFakeCount> list = mapCountService.getDistrCount(vendorId, city); if (list != null && list.size() > 0) { for (StatAntiFakeCount statAntiFakeCount : list) { JSONObject object = new JSONObject(); object.put("name", statAntiFakeCount.getDistrict()); object.put("value", statAntiFakeCount.getCount()); object.put("selected", "false"); array.add(object); } } result.put("data", array); return result; } /** * 热力图区县数据统计 * * @param vendorId * @param district * @return */ @RequestMapping("/GET/mapCount/heatMapForDistr.do") @ResponseBody public JSONObject heatMapForDistr(HttpServletRequest request, Integer vendorId, String district) { try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } JSONObject result = new JSONObject(); JSONArray array = new JSONArray(); List<StatAntiFakeCount> list = mapCountService.heatMapForDistr( vendorId, district); if (list != null && list.size() > 0) { for (StatAntiFakeCount statAntiFakeCount : list) { JSONObject object = new JSONObject(); object.put("lng", Double.parseDouble(statAntiFakeCount.getLongitude())); object.put("lat", Double.parseDouble(statAntiFakeCount.getLatitude())); object.put("count", Integer.parseInt(statAntiFakeCount.getCount())); array.add(object); } } result.put("data", array); return result; } /** * 获取所有扫码量 * @return */ @RequestMapping("/GET/mapCount/getAllCount.do") @ResponseBody public JSONObject getAllCount() { return countService.getAllCountList(); } /** * 系统最近七日扫码统计 * * @param userId * @param vendorId * @return */ @RequestMapping("/GET/mapCount/SystemWeekMapCount.do") @ResponseBody public JSONObject getSystemWeekCount(Integer userId, Integer vendorId) { return countService.getSystemWeekTotalCount(userId, vendorId); } }
C#
UTF-8
523
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FINAL.Models { public class Factory { public static ITask create_task(string tasktype) { switch (tasktype) { case "task": return new Task(); case "blogpost": return new BlogPost(); default: throw new Exception("unknown task requested"); } } } }
Java
UTF-8
618
2.359375
2
[]
no_license
package net.cagox.game.entities.components; import com.badlogic.ashley.core.Component; /** * A Component that identifies the Entity as containing map data. * * @author Kenneth M. Burling (burlingk) <burlingk@cagox.net> * @version 0.1 * @since 0.1 */ public class MapComponent implements Component { //TODO: Eventually this will be built up to handle information for loading and unloading the maps. public String mapName; public String mapExtension; public String map_file_name() { String name; name = mapName + "."; name += mapExtension; return name; } }
Python
UTF-8
1,317
3.40625
3
[]
no_license
# 状态:超出时间限制 # 最后执行的输入:[8,2,6,8,9,8,1,4,1,5,3,0,7,7,0,4,2,2,5,5] from copy import copy class Solution: solu_dict = None def maxCoins(self, nums: List[int]) -> int: if self.solu_dict is None: self.solu_dict = {} if len(nums) == 1: return nums[0] # 记忆化搜索,查找结果 str_nums = str(nums) if str_nums in self.solu_dict: return self.solu_dict[str_nums] result = 0 for i, val in enumerate(nums): new_nums = copy(nums) new_nums.pop(i) news_result = self._burst_balloons(i, nums) + self.maxCoins(new_nums) result = max(result, news_result) # 保存记忆化搜索的结果并返回 self.solu_dict[str_nums] = result return result def _burst_balloons(self, index: int, nums: List[int]) -> int: nums_len = len(nums) if not nums or index < 0 or index >= nums_len: return 1 elif len(nums) <= 1: return nums[0] elif index == 0: return nums[index] * nums[index + 1] elif index == nums_len - 1: return nums[index - 1] * nums[index] else: return nums[index - 1] * nums[index] * nums[index + 1]
Markdown
UTF-8
1,957
2.703125
3
[ "MIT" ]
permissive
--- layout: post title: 무료 wildcard DNS 서비스 image: /assets/img/dns-300x300.png --- ## 무료 wildcard DNS 서비스 무료 wildcard DNS 서비스는 사용자가 도메인을 발급 받지 않아도, 서비스 IP 주소와 비슷한 형태로 도메인을 사용할 수 있게끔 해주는 서비스 입니다. Wildcard DNS 서비스는 *.IP주소.{DNS service provider} 와 같은 형태의 도메인 쿼리가 오면, 항상 도메인에 포함된 {IP주소}를 반환하는 서비스 입니다. 사용할 수있는 여러 가지 서비스가 있습니다. lvh.me, sslip.io, traefik.me, xip.io, nip.io등이 있습니다. ## lvh.me 이 서비스는 매우 간단합니다. lvh.me의 하위 도메인에 대한 요청은 127.0.0.1로 해석됩니다. ```bash $ dig myapp.lvh.me +short 127.0.0.1 ``` ## nip.io 확인 된 IP 주소와 관련하여 더 많은 유연성이 필요한 경우 nip.io를 시도하십시오. 도메인 이름의 일부로 IP 주소를 구성 할 수 있습니다. myapp.127.0.0.1.nip.io와 같은 이름은 127.0.0.1로 해석됩니다. - 10.0.0.1.nip.io 에 매핑 10.0.0.1 - 192-168-1-250.nip.io 에 매핑 192.168.1.250 - app.10.8.0.1.nip.io 에 매핑 10.8.0.1 - app-116-203-255-68.nip.io 에 매핑 116.203.255.68 - customer1.app.10.0.0.1.nip.io 에 매핑 10.0.0.1 - customer2-app-127-0-0-1.nip.io 에 매핑 127.0.0.1 - 점 표기법 : magic.127.0.0.1.nip.io - 대시 표기법 : magic-127-0-0-1.nip.io "대시"표기법은 [LetsEncrypt](https://letsencrypt.org/)와 같은 서비스를 사용하는 경우 특히 nip.io의 일반 하위 도메인이므로 유용합니다. ```bash $ dig myapp.127.0.0.1.nip.io +short 127.0.0.1 ``` ## xip.io nip.io의 대안으로 xip.io가 있습니다. 같은 방식으로 작동합니다. ```bash $ dig 127.0.0.1.xip.io +short 127.0.0.1 ``` ## traefik.me traefik.me도 nip.io와 같은 방식으로 작동합니다. ```bash $ dig 127.0.0.1.traefik.me +short 127.0.0.1 ```
Python
UTF-8
4,513
3.078125
3
[]
no_license
import discord from random import randint from random_username.generate import generate_username import string import time import requests randomWordAPI = "https://random-word-api.herokuapp.com/word?number=1" token = "NDM2NTkyNDYzNTI5MTE1NjU4.Wtjeag.RPt5pKP5ItDsCt80T3KlkFWETcU" client = discord.Client() def emptyString(): temp = randint(0, 200) string = "" while temp > 0: temp -= 1 string = string + " " return string @client.event async def on_message(message): ################################################ ROLL NUMBER GAME ################################################ if message.content.startswith("!play"): sender = message.author against = message.content.split(" ")[1] againstId = against.split("!")[1][:-1] temp = await client.fetch_user(againstId) againstUser = temp user1 = randint(0,100) user2 = randint(0,100) winner = sender if user1 < user2: winner = againstUser embed = discord.Embed(title="Result", description="The winner is {}!".format(winner.mention), colour=discord.Color.teal()) embed.set_thumbnail(url=winner.avatar_url_as(size=64)) embed.add_field(name=sender.display_name, value=user1) embed.add_field(name=againstUser.display_name, value=user2) await message.channel.send(content=None, embed=embed) ################################################ RANDOM USERNAME ################################################ elif message.content.startswith("!username"): await message.channel.send(generate_username(1)[0]) ################################################ RANDOM EMOJI IN CHAT ################################################ elif message.content.startswith("!q"): string = emptyString() emoji = str(message.guild.emojis[randint(0, len(message.guild.emojis) - 1)]) #a = await message.channel.send("```{}{{}}{}```".format(string, emoji, string)) a = await message.channel.send(f"|{string}{emoji}{string}|") i = 0 while i < 6: i+=1 string = emptyString() emoji = str(message.guild.emojis[randint(0, len(message.guild.emojis) - 1)]) time.sleep(2) #await a.edit(content="```{}{{}}{}```".format(string, emoji, string)) await a.edit(content=f"|{string}{emoji}{string}|") ################################################ HANGMAN ################################################ elif message.content.startswith("!hangman"): await message.channel.send("Let's play a game!") time.sleep(1) await message.channel.send("Start guessing...") time.sleep(0.5) r = requests.get(randomWordAPI) word = r.json()[0] guesses = "" turns = 10 while turns > 0: failed = 0 temp = "`" for char in word: if char in guesses: temp = temp + char else: temp = temp + " _ " failed += 1 if failed == 0: await message.channel.send(temp + "`") await message.channel.send("You won") break await message.channel.send(temp + "`") guess = await client.wait_for("message") if guess.content == "!stop": await message.channel.send("Game stopped...") break elif len(guess.content) != 1: await message.channel.send("Please input exactly one character!") else: if guess.content not in guesses: guesses += guess.content if guess.content not in word: turns -= 1 await message.channel.send("Wrong") else: await message.channel.send("Correct") await message.channel.send("You have " + str(turns) + " more guesses") if turns == 0: await message.channel.send('You lose, the word was "' + word + '"') else: await message.channel.send("Character '" + guess.content + "' already guessed!") elif message.content.startswith("!test"): a = "a" string = "sd" if a in string: print("A") else: print("B") client.run(token)
Python
UTF-8
2,864
2.90625
3
[ "Apache-2.0" ]
permissive
import torch.nn as nn from torch_fidelity.helpers import vassert class FeatureExtractorBase(nn.Module): def __init__(self, name, features_list): """ Base class for feature extractors that can be used in :func:`calculate_metrics`. Args: name (str): Unique name of the subclassed feature extractor, must be the same as used in :func:`register_feature_extractor`. features_list (list): List of feature names, provided by the subclassed feature extractor. """ super(FeatureExtractorBase, self).__init__() vassert(type(name) is str, 'Feature extractor name must be a string') vassert(type(features_list) in (list, tuple), 'Wrong features list type') vassert( all((a in self.get_provided_features_list() for a in features_list)), f'Requested features {tuple(features_list)} are not on the list provided by the selected feature extractor ' f'{self.get_provided_features_list()}' ) vassert(len(features_list) == len(set(features_list)), 'Duplicate features requested') vassert(len(features_list) > 0, 'No features requested') self.name = name self.features_list = features_list def get_name(self): return self.name @staticmethod def get_provided_features_list(): """ Returns a tuple of feature names, extracted by the subclassed feature extractor. """ raise NotImplementedError @staticmethod def get_default_feature_layer_for_metric(metric): """ Returns a default feature name to be used for the metric computation. """ raise NotImplementedError @staticmethod def can_be_compiled(): """ Indicates whether the subclass can be safely wrapped with torch.compile. """ raise NotImplementedError @staticmethod def get_dummy_input_for_compile(): """ Returns a dummy input for compilation """ raise NotImplementedError def get_requested_features_list(self): return self.features_list def convert_features_tuple_to_dict(self, features): # The only compound return type of the forward function amenable to JIT tracing is tuple. # This function simply helps to recover the mapping. vassert( type(features) is tuple and len(features) == len(self.features_list), 'Features must be the output of forward function' ) return dict(((name, feature) for name, feature in zip(self.features_list, features))) def forward(self, input): """ Returns a tuple of tensors extracted from the `input`, in the same order as they are provided by `get_provided_features_list()`. """ raise NotImplementedError
JavaScript
UTF-8
3,013
3.984375
4
[]
no_license
// for some questions function max_num(num1, num2){ if (num1>num2) console.log(String(num1), 'is greater than', String(num2)); else if (num1===num2) console.log(String(num1), 'is the same as', String(num2)); else console.log(String(num2), 'is greater than', String(num1)); } max_num(115,57) console.log('------------------------------') // the function takes in image width and image height // if width > heigh, the image is landscape function is_landscape(img_width, img_height){ if (img_width > img_height) return true; else return false; } console.log(is_landscape(12,45)) console.log('------------------------------') // the popular fizz_buzz function fizz_buzz(number){ if ((number % 3) == 0 && (number % 5 == 0) ) console.log("fizz_buzz"); else if (number % 3 == 0) console.log('fizz'); else if (number % 5 == 0) console.log('buzz'); else if (number % 1 == 0) console.log(number); else console.log('Not a number'); // we can also use the typeof operator here // if (typeof number != 'number') } fizz_buzz(15) console.log('------------------------------') // check_speed function function check_speed(speed){ const speed_limit = 70; const kms_per_point = 5; let point; // to handle invalid statements if (typeof speed != 'number') return "enter a number"; if (speed <= speed_limit) console.log("ok"); else{ point = Math.floor((speed- speed_limit)/kms_per_point); if (point<12) console.log(String(point),'points'); else console.log('License suspended'); } } check_speed(130) console.log('------------------------------') // count truthy in the given array function count_truthy(array){ let count = 0; for (let item of array){ if (item) count += 1; } console.log(count) } count_truthy(['2', '', 'sdf', NaN, 1]) console.log('------------------------------') // show properties of an object function show_properties(obj){ for (let key in obj){ if (typeof obj[key] === 'string') console.log(obj[key]); } } show_properties({title: 'name', rating: 4.5, director:"i don't know"}) console.log('------------------------------') // function to add multiples of 3 and 5 function add_multiples(num){ let total = 0; for (let i = 1; i <= num; i++){ if (i % 3 == 0 || i % 5 == 0) total += i; } console.log(total); } add_multiples(10); console.log('------------------------------') // show prime numbers upto limit function show_prime(limit){ for (let number = 2; number< limit; number++){ if (isPrime(number)) console.log(number) } } function isPrime(number) { for (let factor = 2; factor < number; factor++){ if ( number % factor === 0){ return false; } } return true; } show_prime(15)
Markdown
UTF-8
1,278
2.703125
3
[]
permissive
--- title: "Schematy Automatyzacji" sidebar_label: Schematy Automatyzacji --- ## Wprowadzenie Schematy automatyzacji to gotowe szablony automatyzacji, które można łatwo dostosować i dodać do swojego Asystenta domowego jako automatyzacje. Czyli są to takie wstępnie skonfigurowane automatyzacje które wystarczy dostosować do własnych potrzeb. ## Przejście do schematów automatyzacji W aplikacji Asystent domowy otwórz menu (klikając ikonę w lewym górnym rogu) a następnie kliknij w konfigurację i wybierz opcję **Schematy** ![Ekran z listą automatyzacji](/img/en/bramka/blueprint1.png) ## Ekran z listą schematów automatyzacji Na ekranie z listą schematów automatyzacji można zarządzać schematami dostępnymi w systemie ![Przejście do automatyzacji](/img/en/bramka/blueprint2.png) ## Tworzenie automatyzacji na podstawie schematu Na schemacie automatyzacji po wybraniu opcji **UTWÓRZ AUTOMATYZACJĘ** zostanie wyświetlony ekran do konfiguracji automatyzacji. ![Dodanie nowej automatyzacji](/img/en/bramka/blueprint3.png) Po dostosowaniu parametrów automatyzacji do naszych potrzeb, wystarczy nacisnąć "ZAPISZ", żeby utworzyć automatyzację na podstawie schematu: ![Ustawienie nazwy automatyzacji](/img/en/bramka/blueprint4.png)
JavaScript
UTF-8
780
3.78125
4
[]
no_license
/** * Дан массив целых неповторяющихся целых * положительных чисел, надо вернуть строку * где отличающиеся на один числа свернуты * * дано [6,1,3,9,2,4,11,7] * вернуть “1-4,6-7,9,11" */ export const collapseNumbers = (numbers) => { numbers = numbers.sort((a, b) => a - b); const chunks = []; let chunk = []; numbers.forEach((num) => { chunk.push(num); const nextNum = numbers.find((n) => n === num + 1); if (!nextNum) { chunks.push(chunk); chunk = []; } }); return chunks .map((chunk) => chunk.length === 1 ? chunk[0] : `${chunk[0]}-${chunk[chunk.length - 1]}` ) .join(', '); };
Java
UTF-8
448
1.757813
2
[]
no_license
package com.makeramen.nowdothis.ui.imgur; import com.makeramen.nowdothis.NowDoThisAppComponent; import com.makeramen.nowdothis.dagger.PerImgurActivity; import com.makeramen.nowdothis.data.imgur.ImgurModule; import dagger.Component; @PerImgurActivity @Component(dependencies = NowDoThisAppComponent.class, modules = {ImgurModule.class}) public interface ImgurActivityComponent { void inject(ImgurUploadActivity imgurUploadActivity); }
PHP
UTF-8
1,615
2.59375
3
[]
no_license
<?php /** * Copyright © EcomDev B.V. All rights reserved. * See LICENSE for license details. */ declare(strict_types=1); namespace EcomDev\BenchmarkMySQLBatchInsert; use Zend\Db\Adapter\Adapter; class PreparedStatementMultiValueInsert implements InsertMethod { public function import(Adapter $adapter, string $tableName, array $columns, int $batchSize, iterable $rows): void { $baseSql = sprintf( 'INSERT INTO %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s', $adapter->platform->quoteIdentifier($tableName), implode(',', array_map([$adapter->platform,'quoteIdentifier'], $columns)), implode(',', array_fill(0, $batchSize, sprintf('(%s)', rtrim(str_repeat('?,', count($columns)), ',')))), implode(',', array_map(function ($column) use ($adapter) { return sprintf('%1$s = VALUES(%1$s)', $adapter->platform->quoteIdentifier($column)); }, $columns)) ); $columnCount = count($columns); $statement = $adapter->createStatement($baseSql); $statement->prepare(); $adapter->driver->getConnection()->beginTransaction(); $parameters = []; foreach ($rows as $row) { $parameters[] = $adapter->platform->quoteValueList($row); if ((count($parameters) / $columnCount) === $batchSize) { $adapter->query('BEGIN'); $statement->execute($parameters); $adapter->query('END'); } $parameters = []; } $adapter->driver->getConnection()->commit(); } }
PHP
UTF-8
11,123
2.515625
3
[]
no_license
<?php # # ss_ipmitool_sensors.php # version 0.5 # June 26, 2009 # # Copyright (C) 2006-2009, Eric A. Hall # http://www.eric-a-hall.com/ # # This software is licensed under the same terms as Cacti itself # # # load the Cacti configuration settings if they aren't already present # $no_http_headers = true; if (isset($config) == FALSE) { if (file_exists(dirname(__FILE__) . "/../include/config.php")) { include_once(dirname(__FILE__) . "/../include/config.php"); } if (file_exists(dirname(__FILE__) . "/../include/global.php")) { include_once(dirname(__FILE__) . "/../include/global.php"); } if (isset($config) == FALSE) { echo ("FATAL: Unable to load Cacti configuration files \n"); return; } } # # call the main function manually if executed outside the Cacti script server # if (isset($GLOBALS['called_by_script_server']) == FALSE) { array_shift($_SERVER["argv"]); print call_user_func_array("ss_ipmitool_sensors", $_SERVER["argv"]); } # # main function # function ss_ipmitool_sensors($protocol_bundle="", $sensor_type="", $cacti_request="", $data_request="", $data_request_key="") { # # 1st function argument contains the protocol-specific bundle # # use '====' matching for strpos in case colon is 1st character # if ((trim($protocol_bundle) == "") || (strpos($protocol_bundle, ":") === FALSE)) { echo ("FATAL: No IPMI parameter bundle provided\n"); ss_ipmitool_sensors_syntax(); return; } $protocol_array = explode(":", $protocol_bundle); if (count($protocol_array) < 3) { echo ("FATAL: Not enough elements in IPMI parameter bundle\n"); ss_ipmitool_sensors_syntax(); return; } if (count($protocol_array) > 3) { echo ("FATAL: Too many elements in IPMI parameter bundle\n"); ss_ipmitool_sensors_syntax(); return; } # # 1st bundle element is $ipmi_hostname # $ipmi_hostname = trim($protocol_array[0]); if ($ipmi_hostname == "") { echo ("FATAL: Hostname not specified in IPMI parameter bundle\n"); ss_ipmitool_sensors_syntax(); return; } # # 2nd bundle element is $ipmi_username (NULL username is okay) # $ipmi_username = trim($protocol_array[1]); # # 3rd bundle element is $ipmi_password (NULL password is okay) # $ipmi_password = trim($protocol_array[2]); # # 2nd function argument is $sensor_type # $sensor_type = strtolower(trim($sensor_type)); if (($sensor_type != "fan") && ($sensor_type != "temperature") && ($sensor_type != "current") && ($sensor_type != "voltage")) { echo ("FATAL: $sensor_type is not a valid sensor type\n"); ss_ipmitool_sensors_syntax(); return; } # # 3rd function argument is $cacti_request # $cacti_request = strtolower(trim($cacti_request)); if ($cacti_request == "") { echo ("FATAL: No Cacti request provided\n"); ss_ipmitool_sensors_syntax(); return; } if (($cacti_request != "index") && ($cacti_request != "query") && ($cacti_request != "get")) { echo ("FATAL: \"$cacti_request\" is not a valid Cacti request\n"); ss_ipmitool_sensors_syntax(); return; } # # remaining function arguments are $data_request and $data_request_key # if (($cacti_request == "query") || ($cacti_request == "get")) { $data_request = strtolower(trim($data_request)); if ($data_request == "") { echo ("FATAL: No data requested for Cacti \"$cacti_request\" request\n"); ss_ipmitool_sensors_syntax(); return; } if (($data_request != "sensordevice") && ($data_request != "sensorname") && ($data_request != "sensorreading")) { echo ("FATAL: \"$data_request\" is not a valid data request\n"); ss_ipmitool_sensors_syntax(); return; } # # get the index variable # if ($cacti_request == "get") { $data_request_key = strtolower(trim($data_request_key)); if ($data_request_key == "") { echo ("FATAL: No index value provided for \"$data_request\" data request\n"); ss_ipmitool_sensors_syntax(); return; } } # # clear out spurious command-line parameters on query requests # else { $data_request_key = ""; } } # # Get data from cache or ipmitool # use apt-get install php-memcache memcached # $MCache_Host = 'localhost'; $MCache_Port = '11211'; $cachekey = 'ss_ipmitool_sensors:'.$ipmi_hostname.'-'.$sensor_type; $Cache = new Memcache; $Cache->connect($MCache_Host, $MCache_Port); $sensor_array=$Cache->get($cachekey); if(!$sensor_array){ $sensor_array=ss_ipmitool_sensors_ipmi($ipmi_hostname, $ipmi_username, $ipmi_password , $sensor_type, $data_request); } # # verify that the sensor_array exists and has data # if ((isset($sensor_array) == FALSE) || (count($sensor_array) == 0)) { $message="FATAL: No matching sensors were returned from IPMI\n"; if(isset($GLOBALS['called_by_script_server'])) cacti_log($message); else echo $message; return; } if(isset($Cache)) $Cache->set($cachekey, $sensor_array, FALSE, 30); # # generate output # foreach ($sensor_array as $sensor) { # # return output data according to $cacti_request # switch ($cacti_request) { # # for "index" requests, dump the device column # case "index": echo ($sensor['index'] . "\n"); break; # # for "query" requests, dump the requested columns # case "query": switch ($data_request) { case "sensordevice": echo ($sensor['index'] . ":" . $sensor['index'] . "\n"); break; case "sensorname": echo ($sensor['index'] . ":" . $sensor['name'] . "\n"); break; case "sensorreading": echo ($sensor['index'] . ":" . $sensor['reading'] . "\n"); break; } break; # # for "get" requests, dump the requested data for the requested sensor # case "get": # # skip the current row if it isn't the requested sensor # if (strtolower($sensor['index']) != $data_request_key) { break; } switch ($data_request) { case "sensordevice": echo ($sensor['index'] . "\n"); break; case "sensorname": echo ($sensor['name'] . "\n"); break; case "sensorreading": if (isset($GLOBALS['called_by_script_server']) == TRUE) { return($sensor['reading']); } else { echo ($sensor['reading'] . "\n"); } break; } break; } } } function ss_ipmitool_sensors_ipmi($ipmi_hostname, $ipmi_username, $ipmi_password , $sensor_type, $data_request) { # # build the ipmitool command, starting with the location of the ipmitool executable # $ipmitool_command = exec('which ipmitool 2>/dev/null'); if ($ipmitool_command == "") { echo ("FATAL: \"ipmitool\" cannot be found in the user path\n"); return; } # # fill in the blanks for ipmitool # $ipmitool_command = "$ipmitool_command -I lanplus -L user -H $ipmi_hostname"; # # check for username and use NULL if not provided # if ($ipmi_username != "") { $ipmitool_command = $ipmitool_command . " -U $ipmi_username"; } else { $ipmitool_command = $ipmitool_command . " -U \"\""; } # # check for password and use NULL if not provided # if ($ipmi_password != "") { $ipmitool_command = $ipmitool_command . " -P $ipmi_password"; } else { $ipmitool_command = $ipmitool_command . " -P \"\""; } # # set the sensor request type # $ipmitool_command = $ipmitool_command . " sdr type $sensor_type"; # # lastly, redirect STDERR to STDOUT so we can trap error text # $ipmitool_command = $ipmitool_command . " 2>&1"; # # execute the command and process the results array # $ipmitool_output = exec($ipmitool_command, $ipmitool_array); # # verify that the response contains expected data structures # if ((isset($ipmitool_array) == FALSE) || (count($ipmitool_array) == "0") || (substr_count($ipmitool_array[0], "|") < 4) || (trim($ipmitool_array[0]) == "")) { $message= "FATAL: Incomplete results from ipmitool"; # # include any response data from ipmitool if available # if (trim($ipmitool_array[0] != "")) { $message.= " (\"" . substr($ipmitool_array[0], 0, 32) . "...\")"; } elseif (trim($ipmitool_output) != "") { $message.= " (\"" . substr($ipmitool_output, 0, 32) . "...\")"; } if(isset($GLOBALS['called_by_script_server'])) cacti_log($message."\n"); else echo $message."\n"; return; } # # create a sensor array from the wmic output # $sensor_count = 0; foreach ($ipmitool_array as $ipmitool_response) { # # empty line means no more sensors of the named type were found # if (trim($ipmitool_response) == "") { $sensor_count++; break; } # # short IDs don't exist in ipmitool, but hardware sequence is static # # create a psuedo-device by adding +1 to $sensor_count # $sensor_array[$sensor_count]['index'] = ($sensor_count + 1); # # use regex to locate the sensor name and value # # exit if no match found (not all text values are errors) # if (preg_match("/^(.+?)\s+\|.+\|.+\|.+\|\s([\-|\.|\d]+)\s/", $ipmitool_response, $scratch) == 0) { $sensor_array[$sensor_count]['name'] = ""; $sensor_array[$sensor_count]['reading']=""; //$sensor_count++; //break; //no ignore text values } # # matches were found so use them # else { # # if the name is unknown, use the device index name # if (trim($scratch[1]) == "") { $scratch[1] = $sensor_type . $sensor_array[$sensor_count]['index']; } # # if the name is long and has dashes, trim it down # while ((strlen($scratch[1]) > 18) && (strrpos($scratch[1], "-") > 12)) { $scratch[1] = (substr($scratch[1],0, (strrpos($scratch[1], "-")))); } # # if the name is long and has spaces, trim it down # while ((strlen($scratch[1]) > 18) && (strrpos($scratch[1], " ") > 12)) { $scratch[1] = (substr($scratch[1],0, (strrpos($scratch[1], " ")))); } # # if the name is still long, chop it manually # if (strlen($scratch[1]) > 18) { $scratch[1] = (substr($scratch[1],0,17)); } $sensor_array[$sensor_count]['name'] = trim($scratch[1]); $sensor_array[$sensor_count]['reading'] = trim($scratch[2]); } # # remove malformed readings from the current row's value field in $sensor_arrayso # # the readings must be removed instead of zeroed, so that RRD will store a NULL # if ($data_request == "sensorreading") { # # remove non-numeric sensor readings # if (!is_numeric($sensor_array[$sensor_count]['reading'])) { $sensor_array[$sensor_count]['reading'] = ""; } # # remove impossibly-high temperature and voltage readings # if ((($sensor_type == "temperature") || ($sensor_type == "voltage")) && ($sensor_array[$sensor_count]['reading'] >= "255")) { $sensor_array[$sensor_count]['reading'] = ""; } } # # increment the sensor counter # $sensor_count++; } return $sensor_array; } # # display the syntax # function ss_ipmitool_sensors_syntax() { echo ("Usage: ss_ipmitool_sensors.php <hostname>:[<ipmi_username>]:[<ipmi_password>] \ \n" . " (FAN|TEMPERATURE|VOLTAGE|CURRENT) (index|query <fieldname>|get <fieldname> <sensor>) \n"); } ?>
Java
UTF-8
1,822
2.734375
3
[ "MIT" ]
permissive
package dsdsse.history; import adf.utils.StandardFonts; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; /** * Created by Admin on 10/4/2016. */ public class TraceLogTitlePanel extends JPanel { private final String TITLE_PART_1 = "\u2193 - Current state \u00B7 "; private final String TITLE_PART_2 = "Log size = "; private final String TITLE_PART_3 = " \u00B7 Trace Log \u2192"; static final int TITLE_HEIGHT = 18; public static final Color TITLE_BACKGROUND = new Color(0x0000AA); private static final Color TITLE_FOREGROUND = new Color(0xFFFFFF); private static final Dimension TITLE_SIZE = new Dimension(1, TITLE_HEIGHT); private final String originalTitle; private final JLabel titleLabel = new JLabel("", JLabel.LEFT); public TraceLogTitlePanel(String text) { super(new BorderLayout()); originalTitle = text; init(text); } private void init(String text) { setPreferredSize(TITLE_SIZE); setMinimumSize(TITLE_SIZE); setMaximumSize(TITLE_SIZE); // init Title Label titleLabel.setText(text); titleLabel.setOpaque(true); titleLabel.setFont(StandardFonts.FONT_HELVETICA_BOLD_11); titleLabel.setBackground(TITLE_BACKGROUND); titleLabel.setForeground(TITLE_FOREGROUND); titleLabel.setPreferredSize(TITLE_SIZE); titleLabel.setMinimumSize(TITLE_SIZE); titleLabel.setMaximumSize(TITLE_SIZE); titleLabel.setBorder(new EmptyBorder(0, 6, 1, 0)); add(titleLabel, BorderLayout.CENTER); } void updateTraceHistorySize(int historySize){ String currentTitle = TITLE_PART_1 + TITLE_PART_2 + historySize + TITLE_PART_3; titleLabel.setText(currentTitle); } }
TypeScript
UTF-8
1,090
2.703125
3
[ "MIT" ]
permissive
import { createDictionaryTransformer } from './transformer/dictionary.transformer'; import { createGeneratorTransformer } from './transformer/generator.transformer'; import { createVariableStoreTransformer } from './transformer/variable-store.transformer'; import { Transformer } from './transformer.interface'; class Transformers { constructor(private availableTransformers: Transformer[]) {} public transform(value: string): any { const transformer = this.findTransformer(value.substr(0, 2)); if (transformer === undefined) { return value; } return transformer.transform(value.substr(2)); } public findTransformer(prefix: string): Transformer { return this.availableTransformers.find(transformer => transformer.isSatisfiedBy(prefix)); } public addTransformer(transformer: Transformer): void { this.availableTransformers.push(transformer); } } const transformers = [createVariableStoreTransformer(), createDictionaryTransformer(), createGeneratorTransformer()]; export const create = (transf = transformers) => new Transformers(transf);
Markdown
UTF-8
2,816
2.921875
3
[]
no_license
# 区块链及初链初识 ## 入行区块链之前 入行之前在一家金融监管自媒体公司。每天关心的是一行三会的各种突发监管政策,接触的是各类相关法律,打交道的是各类有业务创新及合规需求的金融机构。所以,从宏观角度能对金融略知一二,知道货币的发行、信用派生,以及货币对国家经济调节的重要性。没有想过如果,在没有郭嘉做信用背书的前提下,如果建立一个自由流动的货币价值体系,如何可以更高效的实现价值流动和传输。 ## 炒币经历 离职后,一个很偶然的线下交流,接触了一两个虚拟货币的传道者。在我说,好茫然的时候,毅然决然且无比兴奋的告诉我,做区块链啊。于是我开始查一些区块链的相关资料,开始在其卖房炒币的带动下,投入越来越多资金到虚拟货币。并且我也很兴奋的觉得,区块链作为一个去中心化的分布式账本,在不依托信用背书的情况下,如果能实现价值的自然传输,好像真的很炫酷。与此同时,各大自媒体开始进入一段疯狂的区块链讴歌中,越来越多的人开始被迫知道区块链。越来越多的人都在似是而非的谈论着区块链,包括出租车司机和卖菜的大妈。这波高潮随着币价在2017年年底达到顶点,随后便开始无尽的跌跌不休。进入了漫长的熊市。 ## 我对区块链的理解 区块链技术本身其实很早就出现了。分布式账本也是由来已久。早期腾讯没有启用中央服务器的时候,用的就是对等网络。而密码学从最早的军事领域到现在的民用领域也是应用深广。为什么整合了分布式、密码学及共识机制的区块链技术能掀起全民的技术焦虑和未来憧憬。我认为,区块链技术的本质是把全球个体经纪人和机器之间的价值交换壁垒和成本降到几乎为零。例如,早期互联网是把信息搜索和交互成本降到接近0,并在此基础上催生了很多扩展性极高,利润性极高的经济模式。反观区块链亦是如此。它的颠覆不是早就有的区块链里的技术,而是整合了之后的零壁垒价值传输。虽然,这中间可能会有一条非常长的道路要走。但是,价值传输的零壁垒,同时涉及到一个国家的货币政策,外汇管制等等,具体还有待研究。 ## 我对初链的看法 初链实现了permissionless pbft协议,将pbft和pow共识结合在一起能有效解决当前区块链领域最重要的问题之一: 去中心化和性能/可扩展性的矛盾。在2018年各大公链竞争如火如荼的情况下,希望初链,能凭借其创新性混合共识算法,能对后续的生态开发更加友好。
Java
UTF-8
133
1.671875
2
[]
no_license
package com.user.process.dao; public interface IUserDao { String selectUserByUsername(String username) throws Exception; }
Python
UTF-8
626
3
3
[]
no_license
import os import random import re import sys # Complete the countApplesAndOranges function below. c1=0 c2=0 st = map(int,raw_input().split()) s = st[0] t = st[1] ab = map(int,raw_input().split()) a = ab[0] b = ab[1] mn = map(int,raw_input().split()) m = mn[0] n = mn[1] apples = map(int, raw_input().split()) oranges = map(int, raw_input().split()) for i in range(m): apples[i]=a+apples[i] for i in range(n): oranges[i]=b+oranges[i] for i in range(m): if (s<=apples[i] and apples[i]<=t): c1=c1+1 for i in range(n): if(s<=oranges[i] and oranges[i]<=t): c2=c2+1 print(c1) print(c2)
PHP
UTF-8
1,119
3.5625
4
[]
no_license
<?php class Color { public $red; public $green; public $blue; public static $verbose = False; function __construct($rgb_arr) { if (isset($rgb_arr['rgb'])) { $hex = $rgb_arr['rgb']; $int = hexdec($hex); $this->red = ($int >> 16) & 255; $this->green = ($int >> 8) & 255; $this->blue = $int & 255; } else { $this->red = hexdec($rgb_arr['red']); $this->green = hexdec($rgb_arr['green']); $this->blue = hexdec($rgb_arr['blue']); } if (Color::$verbose === True) echo "Color (red: $this->red, green: $this->green, blue: $this->blue) constructed.\n"; return; } function __destruct() { if (Color::$verbose === True) echo "Color (red: $this->red, green: $this->green, blue: $this->blue) constructed.\n"; return; } function __toString() { return "Color (red: $this->red, green: $this->green, blue: $this->blue)"; } public static function doc() { $doc = file_get_contents("Color.doc.txt"); return ($doc); } function add() { return (new Color(1)); } function sub() { return (new Color(1)); } function mult() { return (new Color(1)); } } ?>
Ruby
UTF-8
371
3.265625
3
[]
no_license
n = gets.chomp.to_i cards = {"S" => Array.new(13, false), "H" => Array.new(13, false), "C" => Array.new(13, false), "D" => Array.new(13, false)} while line = gets line = line.chomp.split(/ /) cards[line[0]][line[1].to_i - 1] = true end cards.each do |k,v| if v.count(true) < 13 v.each_with_index do |n, i| print(k, " ", i+1, "\n") if !n end end end
Java
UTF-8
317
1.953125
2
[]
no_license
package org.fish.code.boot.source.context.editor; import java.util.Date; import lombok.Data; import lombok.ToString; /** * Birthday, age, sex, etc. * * @author chenjunfeng1 * */ @Data @ToString public class Person { private Date birthDate; private int age; private int sex; }
Python
UTF-8
146
3.625
4
[]
no_license
def my_func(a, b): a, b = int(a), int(b) print(a+b) print(a-b) print(a*b) print(a//b) print(a%b) a, b = input().split() my_func(a, b)
Java
UTF-8
568
2.984375
3
[]
no_license
package by.bntu.fitr.varabei.javalabs.lab07.model; import java.util.Random; public class Mood { public final static String GOOD_MOOD = "=)"; public final static String FURIOUS = "=("; public final static String NORMAL_MOOD = "=|"; public final static int MAX_SPIRITS = 3; public static String determineSpirits() { String result = GOOD_MOOD; Random random = new Random(); switch (random.nextInt(MAX_SPIRITS)) { case 1: result = NORMAL_MOOD; break; case 2: result = FURIOUS; break; } return result; } }
Markdown
UTF-8
863
2.75
3
[ "Unlicense" ]
permissive
## Project Soul **Project description:** This project is still in development. Its a 2D roguelike game set in Japan during the Edo period. It follows a pair of sibblings battling through enemies utilizing elemental abilities and weapons. **Tasks:** My task for this project was to construct the core game architecture, physics, and weapon mechanics. Much of the mobility was inspired by movement from the Super Smash Brothers Series and each weapon was created with a specific element in mind. Examples: A hammer that shudders the earth creating rows of spikes, shurikens exploding with rings of fire, or a whip generating gusts of wind to give the player a dash of mobility. ### Screenshots <img src="images/ProjectSoul/Movement.gif" border="5"/> <img src="images/ProjectSoul/Rock Rapture.gif" border="5"/> <img src="images/ProjectSoul/RPG.gif" border="5"/>
Java
UTF-8
29,000
1.53125
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.03.03 at 01:06:50 PM CET // package org.plcopen.xml.tc6_0201; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the org.plcopen.xml.tc6_0201 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.plcopen.xml.tc6_0201 * */ public ObjectFactory() { } /** * Create an instance of {@link Project } * */ public Project createProject() { return new Project(); } /** * Create an instance of {@link VarListPlain } * */ public VarListPlain createVarListPlain() { return new VarListPlain(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.Value_ } * */ public org.plcopen.xml.tc6_0201.Value_ createValue() { return new org.plcopen.xml.tc6_0201.Value_(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.Value_.StructValue } * */ public org.plcopen.xml.tc6_0201.Value_.StructValue createValueStructValue() { return new org.plcopen.xml.tc6_0201.Value_.StructValue(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.Value_.ArrayValue } * */ public org.plcopen.xml.tc6_0201.Value_.ArrayValue createValueArrayValue() { return new org.plcopen.xml.tc6_0201.Value_.ArrayValue(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType } * */ public org.plcopen.xml.tc6_0201.DataType createDataType() { return new org.plcopen.xml.tc6_0201.DataType(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType.Enum } * */ public org.plcopen.xml.tc6_0201.DataType.Enum createDataTypeEnum() { return new org.plcopen.xml.tc6_0201.DataType.Enum(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType.Enum.Values } * */ public org.plcopen.xml.tc6_0201.DataType.Enum.Values createDataTypeEnumValues() { return new org.plcopen.xml.tc6_0201.DataType.Enum.Values(); } /** * Create an instance of {@link VarListConfig } * */ public VarListConfig createVarListConfig() { return new VarListConfig(); } /** * Create an instance of {@link AddDataInfo } * */ public AddDataInfo createAddDataInfo() { return new AddDataInfo(); } /** * Create an instance of {@link VarListAccess } * */ public VarListAccess createVarListAccess() { return new VarListAccess(); } /** * Create an instance of {@link Body } * */ public Body createBody() { return new Body(); } /** * Create an instance of {@link Body.SFC } * */ public Body.SFC createBodySFC() { return new Body.SFC(); } /** * Create an instance of {@link Body.SFC.SimultaneousDivergence } * */ public Body.SFC.SimultaneousDivergence createBodySFCSimultaneousDivergence() { return new Body.SFC.SimultaneousDivergence(); } /** * Create an instance of {@link Body.SFC.SelectionConvergence } * */ public Body.SFC.SelectionConvergence createBodySFCSelectionConvergence() { return new Body.SFC.SelectionConvergence(); } /** * Create an instance of {@link Body.SFC.SelectionDivergence } * */ public Body.SFC.SelectionDivergence createBodySFCSelectionDivergence() { return new Body.SFC.SelectionDivergence(); } /** * Create an instance of {@link Body.SFC.Transition } * */ public Body.SFC.Transition createBodySFCTransition() { return new Body.SFC.Transition(); } /** * Create an instance of {@link Body.SFC.Transition.Condition } * */ public Body.SFC.Transition.Condition createBodySFCTransitionCondition() { return new Body.SFC.Transition.Condition(); } /** * Create an instance of {@link Body.SFC.Step } * */ public Body.SFC.Step createBodySFCStep() { return new Body.SFC.Step(); } /** * Create an instance of {@link Body.SFC.LeftPowerRail } * */ public Body.SFC.LeftPowerRail createBodySFCLeftPowerRail() { return new Body.SFC.LeftPowerRail(); } /** * Create an instance of {@link Body.SFC.Block } * */ public Body.SFC.Block createBodySFCBlock() { return new Body.SFC.Block(); } /** * Create an instance of {@link Body.SFC.Block.OutputVariables } * */ public Body.SFC.Block.OutputVariables createBodySFCBlockOutputVariables() { return new Body.SFC.Block.OutputVariables(); } /** * Create an instance of {@link Body.SFC.Block.InOutVariables } * */ public Body.SFC.Block.InOutVariables createBodySFCBlockInOutVariables() { return new Body.SFC.Block.InOutVariables(); } /** * Create an instance of {@link Body.SFC.Block.InputVariables } * */ public Body.SFC.Block.InputVariables createBodySFCBlockInputVariables() { return new Body.SFC.Block.InputVariables(); } /** * Create an instance of {@link Body.SFC.VendorElement } * */ public Body.SFC.VendorElement createBodySFCVendorElement() { return new Body.SFC.VendorElement(); } /** * Create an instance of {@link Body.SFC.VendorElement.OutputVariables } * */ public Body.SFC.VendorElement.OutputVariables createBodySFCVendorElementOutputVariables() { return new Body.SFC.VendorElement.OutputVariables(); } /** * Create an instance of {@link Body.SFC.VendorElement.InOutVariables } * */ public Body.SFC.VendorElement.InOutVariables createBodySFCVendorElementInOutVariables() { return new Body.SFC.VendorElement.InOutVariables(); } /** * Create an instance of {@link Body.SFC.VendorElement.InputVariables } * */ public Body.SFC.VendorElement.InputVariables createBodySFCVendorElementInputVariables() { return new Body.SFC.VendorElement.InputVariables(); } /** * Create an instance of {@link Body.SFC.ActionBlock } * */ public Body.SFC.ActionBlock createBodySFCActionBlock() { return new Body.SFC.ActionBlock(); } /** * Create an instance of {@link Body.SFC.ActionBlock.Action } * */ public Body.SFC.ActionBlock.Action createBodySFCActionBlockAction() { return new Body.SFC.ActionBlock.Action(); } /** * Create an instance of {@link AddData } * */ public AddData createAddData() { return new AddData(); } /** * Create an instance of {@link Project.Instances } * */ public Project.Instances createProjectInstances() { return new Project.Instances(); } /** * Create an instance of {@link Project.Instances.Configurations } * */ public Project.Instances.Configurations createProjectInstancesConfigurations() { return new Project.Instances.Configurations(); } /** * Create an instance of {@link Project.Instances.Configurations.Configuration } * */ public Project.Instances.Configurations.Configuration createProjectInstancesConfigurationsConfiguration() { return new Project.Instances.Configurations.Configuration(); } /** * Create an instance of {@link Project.Instances.Configurations.Configuration.Resource } * */ public Project.Instances.Configurations.Configuration.Resource createProjectInstancesConfigurationsConfigurationResource() { return new Project.Instances.Configurations.Configuration.Resource(); } /** * Create an instance of {@link Project.Types } * */ public Project.Types createProjectTypes() { return new Project.Types(); } /** * Create an instance of {@link Project.Types.Pous } * */ public Project.Types.Pous createProjectTypesPous() { return new Project.Types.Pous(); } /** * Create an instance of {@link Project.Types.Pous.Pou } * */ public Project.Types.Pous.Pou createProjectTypesPousPou() { return new Project.Types.Pous.Pou(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Transitions } * */ public Project.Types.Pous.Pou.Transitions createProjectTypesPousPouTransitions() { return new Project.Types.Pous.Pou.Transitions(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Actions } * */ public Project.Types.Pous.Pou.Actions createProjectTypesPousPouActions() { return new Project.Types.Pous.Pou.Actions(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Interface } * */ public Project.Types.Pous.Pou.Interface createProjectTypesPousPouInterface() { return new Project.Types.Pous.Pou.Interface(); } /** * Create an instance of {@link Project.Types.DataTypes } * */ public Project.Types.DataTypes createProjectTypesDataTypes() { return new Project.Types.DataTypes(); } /** * Create an instance of {@link Project.ContentHeader } * */ public Project.ContentHeader createProjectContentHeader() { return new Project.ContentHeader(); } /** * Create an instance of {@link Project.ContentHeader.CoordinateInfo } * */ public Project.ContentHeader.CoordinateInfo createProjectContentHeaderCoordinateInfo() { return new Project.ContentHeader.CoordinateInfo(); } /** * Create an instance of {@link Project.ContentHeader.CoordinateInfo.Sfc } * */ public Project.ContentHeader.CoordinateInfo.Sfc createProjectContentHeaderCoordinateInfoSfc() { return new Project.ContentHeader.CoordinateInfo.Sfc(); } /** * Create an instance of {@link Project.ContentHeader.CoordinateInfo.Ld } * */ public Project.ContentHeader.CoordinateInfo.Ld createProjectContentHeaderCoordinateInfoLd() { return new Project.ContentHeader.CoordinateInfo.Ld(); } /** * Create an instance of {@link Project.ContentHeader.CoordinateInfo.Fbd } * */ public Project.ContentHeader.CoordinateInfo.Fbd createProjectContentHeaderCoordinateInfoFbd() { return new Project.ContentHeader.CoordinateInfo.Fbd(); } /** * Create an instance of {@link Project.FileHeader } * */ public Project.FileHeader createProjectFileHeader() { return new Project.FileHeader(); } /** * Create an instance of {@link FormattedText } * */ public FormattedText createFormattedText() { return new FormattedText(); } /** * Create an instance of {@link Position } * */ public Position createPosition() { return new Position(); } /** * Create an instance of {@link Connection } * */ public Connection createConnection() { return new Connection(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.ConnectionPointIn } * */ public org.plcopen.xml.tc6_0201.ConnectionPointIn createConnectionPointIn() { return new org.plcopen.xml.tc6_0201.ConnectionPointIn(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.ConnectionPointOut } * */ public org.plcopen.xml.tc6_0201.ConnectionPointOut createConnectionPointOut() { return new org.plcopen.xml.tc6_0201.ConnectionPointOut(); } /** * Create an instance of {@link RangeSigned } * */ public RangeSigned createRangeSigned() { return new RangeSigned(); } /** * Create an instance of {@link PouInstance } * */ public PouInstance createPouInstance() { return new PouInstance(); } /** * Create an instance of {@link RangeUnsigned } * */ public RangeUnsigned createRangeUnsigned() { return new RangeUnsigned(); } /** * Create an instance of {@link VarList } * */ public VarList createVarList() { return new VarList(); } /** * Create an instance of {@link VarListPlain.Variable } * */ public VarListPlain.Variable createVarListPlainVariable() { return new VarListPlain.Variable(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.Value_.SimpleValue } * */ public org.plcopen.xml.tc6_0201.Value_.SimpleValue createValueSimpleValue() { return new org.plcopen.xml.tc6_0201.Value_.SimpleValue(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.Value_.StructValue.Value } * */ public org.plcopen.xml.tc6_0201.Value_.StructValue.Value createValueStructValueValue() { return new org.plcopen.xml.tc6_0201.Value_.StructValue.Value(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.Value_.ArrayValue.Value } * */ public org.plcopen.xml.tc6_0201.Value_.ArrayValue.Value createValueArrayValueValue() { return new org.plcopen.xml.tc6_0201.Value_.ArrayValue.Value(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType.String } * */ public org.plcopen.xml.tc6_0201.DataType.String createDataTypeString() { return new org.plcopen.xml.tc6_0201.DataType.String(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType.Wstring } * */ public org.plcopen.xml.tc6_0201.DataType.Wstring createDataTypeWstring() { return new org.plcopen.xml.tc6_0201.DataType.Wstring(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType.Array } * */ public org.plcopen.xml.tc6_0201.DataType.Array createDataTypeArray() { return new org.plcopen.xml.tc6_0201.DataType.Array(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType.Derived } * */ public org.plcopen.xml.tc6_0201.DataType.Derived createDataTypeDerived() { return new org.plcopen.xml.tc6_0201.DataType.Derived(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType.SubrangeSigned } * */ public org.plcopen.xml.tc6_0201.DataType.SubrangeSigned createDataTypeSubrangeSigned() { return new org.plcopen.xml.tc6_0201.DataType.SubrangeSigned(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType.SubrangeUnsigned } * */ public org.plcopen.xml.tc6_0201.DataType.SubrangeUnsigned createDataTypeSubrangeUnsigned() { return new org.plcopen.xml.tc6_0201.DataType.SubrangeUnsigned(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType.Pointer } * */ public org.plcopen.xml.tc6_0201.DataType.Pointer createDataTypePointer() { return new org.plcopen.xml.tc6_0201.DataType.Pointer(); } /** * Create an instance of {@link org.plcopen.xml.tc6_0201.DataType.Enum.Values.Value } * */ public org.plcopen.xml.tc6_0201.DataType.Enum.Values.Value createDataTypeEnumValuesValue() { return new org.plcopen.xml.tc6_0201.DataType.Enum.Values.Value(); } /** * Create an instance of {@link VarListConfig.ConfigVariable } * */ public VarListConfig.ConfigVariable createVarListConfigConfigVariable() { return new VarListConfig.ConfigVariable(); } /** * Create an instance of {@link AddDataInfo.Info } * */ public AddDataInfo.Info createAddDataInfoInfo() { return new AddDataInfo.Info(); } /** * Create an instance of {@link VarListAccess.AccessVariable } * */ public VarListAccess.AccessVariable createVarListAccessAccessVariable() { return new VarListAccess.AccessVariable(); } /** * Create an instance of {@link Body.FBD } * */ public Body.FBD createBodyFBD() { return new Body.FBD(); } /** * Create an instance of {@link Body.LD } * */ public Body.LD createBodyLD() { return new Body.LD(); } /** * Create an instance of {@link Body.SFC.Comment } * */ public Body.SFC.Comment createBodySFCComment() { return new Body.SFC.Comment(); } /** * Create an instance of {@link Body.SFC.Error } * */ public Body.SFC.Error createBodySFCError() { return new Body.SFC.Error(); } /** * Create an instance of {@link Body.SFC.Connector } * */ public Body.SFC.Connector createBodySFCConnector() { return new Body.SFC.Connector(); } /** * Create an instance of {@link Body.SFC.Continuation } * */ public Body.SFC.Continuation createBodySFCContinuation() { return new Body.SFC.Continuation(); } /** * Create an instance of {@link Body.SFC.InVariable } * */ public Body.SFC.InVariable createBodySFCInVariable() { return new Body.SFC.InVariable(); } /** * Create an instance of {@link Body.SFC.OutVariable } * */ public Body.SFC.OutVariable createBodySFCOutVariable() { return new Body.SFC.OutVariable(); } /** * Create an instance of {@link Body.SFC.InOutVariable } * */ public Body.SFC.InOutVariable createBodySFCInOutVariable() { return new Body.SFC.InOutVariable(); } /** * Create an instance of {@link Body.SFC.Label } * */ public Body.SFC.Label createBodySFCLabel() { return new Body.SFC.Label(); } /** * Create an instance of {@link Body.SFC.Jump } * */ public Body.SFC.Jump createBodySFCJump() { return new Body.SFC.Jump(); } /** * Create an instance of {@link Body.SFC.Return } * */ public Body.SFC.Return createBodySFCReturn() { return new Body.SFC.Return(); } /** * Create an instance of {@link Body.SFC.RightPowerRail } * */ public Body.SFC.RightPowerRail createBodySFCRightPowerRail() { return new Body.SFC.RightPowerRail(); } /** * Create an instance of {@link Body.SFC.Coil } * */ public Body.SFC.Coil createBodySFCCoil() { return new Body.SFC.Coil(); } /** * Create an instance of {@link Body.SFC.Contact } * */ public Body.SFC.Contact createBodySFCContact() { return new Body.SFC.Contact(); } /** * Create an instance of {@link Body.SFC.MacroStep } * */ public Body.SFC.MacroStep createBodySFCMacroStep() { return new Body.SFC.MacroStep(); } /** * Create an instance of {@link Body.SFC.JumpStep } * */ public Body.SFC.JumpStep createBodySFCJumpStep() { return new Body.SFC.JumpStep(); } /** * Create an instance of {@link Body.SFC.SimultaneousConvergence } * */ public Body.SFC.SimultaneousConvergence createBodySFCSimultaneousConvergence() { return new Body.SFC.SimultaneousConvergence(); } /** * Create an instance of {@link Body.SFC.SimultaneousDivergence.ConnectionPointOut } * */ public Body.SFC.SimultaneousDivergence.ConnectionPointOut createBodySFCSimultaneousDivergenceConnectionPointOut() { return new Body.SFC.SimultaneousDivergence.ConnectionPointOut(); } /** * Create an instance of {@link Body.SFC.SelectionConvergence.ConnectionPointIn } * */ public Body.SFC.SelectionConvergence.ConnectionPointIn createBodySFCSelectionConvergenceConnectionPointIn() { return new Body.SFC.SelectionConvergence.ConnectionPointIn(); } /** * Create an instance of {@link Body.SFC.SelectionDivergence.ConnectionPointOut } * */ public Body.SFC.SelectionDivergence.ConnectionPointOut createBodySFCSelectionDivergenceConnectionPointOut() { return new Body.SFC.SelectionDivergence.ConnectionPointOut(); } /** * Create an instance of {@link Body.SFC.Transition.Condition.Reference } * */ public Body.SFC.Transition.Condition.Reference createBodySFCTransitionConditionReference() { return new Body.SFC.Transition.Condition.Reference(); } /** * Create an instance of {@link Body.SFC.Transition.Condition.Inline } * */ public Body.SFC.Transition.Condition.Inline createBodySFCTransitionConditionInline() { return new Body.SFC.Transition.Condition.Inline(); } /** * Create an instance of {@link Body.SFC.Step.ConnectionPointOut } * */ public Body.SFC.Step.ConnectionPointOut createBodySFCStepConnectionPointOut() { return new Body.SFC.Step.ConnectionPointOut(); } /** * Create an instance of {@link Body.SFC.Step.ConnectionPointOutAction } * */ public Body.SFC.Step.ConnectionPointOutAction createBodySFCStepConnectionPointOutAction() { return new Body.SFC.Step.ConnectionPointOutAction(); } /** * Create an instance of {@link Body.SFC.LeftPowerRail.ConnectionPointOut } * */ public Body.SFC.LeftPowerRail.ConnectionPointOut createBodySFCLeftPowerRailConnectionPointOut() { return new Body.SFC.LeftPowerRail.ConnectionPointOut(); } /** * Create an instance of {@link Body.SFC.Block.OutputVariables.Variable } * */ public Body.SFC.Block.OutputVariables.Variable createBodySFCBlockOutputVariablesVariable() { return new Body.SFC.Block.OutputVariables.Variable(); } /** * Create an instance of {@link Body.SFC.Block.InOutVariables.Variable } * */ public Body.SFC.Block.InOutVariables.Variable createBodySFCBlockInOutVariablesVariable() { return new Body.SFC.Block.InOutVariables.Variable(); } /** * Create an instance of {@link Body.SFC.Block.InputVariables.Variable } * */ public Body.SFC.Block.InputVariables.Variable createBodySFCBlockInputVariablesVariable() { return new Body.SFC.Block.InputVariables.Variable(); } /** * Create an instance of {@link Body.SFC.VendorElement.OutputVariables.Variable } * */ public Body.SFC.VendorElement.OutputVariables.Variable createBodySFCVendorElementOutputVariablesVariable() { return new Body.SFC.VendorElement.OutputVariables.Variable(); } /** * Create an instance of {@link Body.SFC.VendorElement.InOutVariables.Variable } * */ public Body.SFC.VendorElement.InOutVariables.Variable createBodySFCVendorElementInOutVariablesVariable() { return new Body.SFC.VendorElement.InOutVariables.Variable(); } /** * Create an instance of {@link Body.SFC.VendorElement.InputVariables.Variable } * */ public Body.SFC.VendorElement.InputVariables.Variable createBodySFCVendorElementInputVariablesVariable() { return new Body.SFC.VendorElement.InputVariables.Variable(); } /** * Create an instance of {@link Body.SFC.ActionBlock.Action.Reference } * */ public Body.SFC.ActionBlock.Action.Reference createBodySFCActionBlockActionReference() { return new Body.SFC.ActionBlock.Action.Reference(); } /** * Create an instance of {@link AddData.Data } * */ public AddData.Data createAddDataData() { return new AddData.Data(); } /** * Create an instance of {@link Project.Instances.Configurations.Configuration.Resource.Task } * */ public Project.Instances.Configurations.Configuration.Resource.Task createProjectInstancesConfigurationsConfigurationResourceTask() { return new Project.Instances.Configurations.Configuration.Resource.Task(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Transitions.Transition } * */ public Project.Types.Pous.Pou.Transitions.Transition createProjectTypesPousPouTransitionsTransition() { return new Project.Types.Pous.Pou.Transitions.Transition(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Actions.Action } * */ public Project.Types.Pous.Pou.Actions.Action createProjectTypesPousPouActionsAction() { return new Project.Types.Pous.Pou.Actions.Action(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Interface.LocalVars } * */ public Project.Types.Pous.Pou.Interface.LocalVars createProjectTypesPousPouInterfaceLocalVars() { return new Project.Types.Pous.Pou.Interface.LocalVars(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Interface.TempVars } * */ public Project.Types.Pous.Pou.Interface.TempVars createProjectTypesPousPouInterfaceTempVars() { return new Project.Types.Pous.Pou.Interface.TempVars(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Interface.InputVars } * */ public Project.Types.Pous.Pou.Interface.InputVars createProjectTypesPousPouInterfaceInputVars() { return new Project.Types.Pous.Pou.Interface.InputVars(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Interface.OutputVars } * */ public Project.Types.Pous.Pou.Interface.OutputVars createProjectTypesPousPouInterfaceOutputVars() { return new Project.Types.Pous.Pou.Interface.OutputVars(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Interface.InOutVars } * */ public Project.Types.Pous.Pou.Interface.InOutVars createProjectTypesPousPouInterfaceInOutVars() { return new Project.Types.Pous.Pou.Interface.InOutVars(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Interface.ExternalVars } * */ public Project.Types.Pous.Pou.Interface.ExternalVars createProjectTypesPousPouInterfaceExternalVars() { return new Project.Types.Pous.Pou.Interface.ExternalVars(); } /** * Create an instance of {@link Project.Types.Pous.Pou.Interface.GlobalVars } * */ public Project.Types.Pous.Pou.Interface.GlobalVars createProjectTypesPousPouInterfaceGlobalVars() { return new Project.Types.Pous.Pou.Interface.GlobalVars(); } /** * Create an instance of {@link Project.Types.DataTypes.DataType } * */ public Project.Types.DataTypes.DataType createProjectTypesDataTypesDataType() { return new Project.Types.DataTypes.DataType(); } /** * Create an instance of {@link Project.ContentHeader.CoordinateInfo.PageSize } * */ public Project.ContentHeader.CoordinateInfo.PageSize createProjectContentHeaderCoordinateInfoPageSize() { return new Project.ContentHeader.CoordinateInfo.PageSize(); } /** * Create an instance of {@link Project.ContentHeader.CoordinateInfo.Sfc.Scaling } * */ public Project.ContentHeader.CoordinateInfo.Sfc.Scaling createProjectContentHeaderCoordinateInfoSfcScaling() { return new Project.ContentHeader.CoordinateInfo.Sfc.Scaling(); } /** * Create an instance of {@link Project.ContentHeader.CoordinateInfo.Ld.Scaling } * */ public Project.ContentHeader.CoordinateInfo.Ld.Scaling createProjectContentHeaderCoordinateInfoLdScaling() { return new Project.ContentHeader.CoordinateInfo.Ld.Scaling(); } /** * Create an instance of {@link Project.ContentHeader.CoordinateInfo.Fbd.Scaling } * */ public Project.ContentHeader.CoordinateInfo.Fbd.Scaling createProjectContentHeaderCoordinateInfoFbdScaling() { return new Project.ContentHeader.CoordinateInfo.Fbd.Scaling(); } }
Java
UTF-8
1,080
2.25
2
[]
no_license
package system.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import system.entity.ContactinformationEntity; import system.service.ContactinformationService; @Controller public class ContactInformationController { @RequestMapping(value="contactInformation", method = RequestMethod.GET) public String contactInformationGet(Model model) { return "contact"; } @RequestMapping(value = "/contact", method = RequestMethod.POST) public String addContactInformation(@ModelAttribute("contactInformation") ContactinformationEntity ContactinformationEntity) { ContactinformationService contactinformationService = new ContactinformationService(); contactinformationService.add(ContactinformationEntity); return "contact"; } }
Markdown
UTF-8
4,727
3.65625
4
[]
no_license
## 1\.Exercice 1 Selon vous, qu'est ce qui s'affiche à l'écran avec le programme suivant ? ``` var i = 0; while (i <= 9) { console.log("One run of the loop"); i ++; } ``` Combien de fois la phrase est-elle affichée ? Pourquoi ? Est-ce le bon nombre de répétition de la boucle ? Remplacez "i ++" par "i += 2". Que se passe-t-il ? Pourquoi ? Que se passe-t-il si on supprime "i ++" ? Pourquoi ? Comment s'appelle ce type de boucle ? **Ne le faites pas, cela ferait buguer votre machine**. ## 2\.Exercice 2 Selon vous, qu'est ce qui s'affiche à l'écran avec le programme suivant ? ``` for (var i=0; i <=9 ; i++) { console.log("One run of the loop"); } ``` Combien de fois la phrase est-elle affichée ? Pourquoi ? Est-ce le bon nombre de répétition de la boucle ? Remplacez "i ++" par "i += 2". Que se passe-t-il ? Pourquoi ? Que se passe-t-il si on supprime "i ++" ? Le fonctionnement et le résultat de cette boucle sont-ils différents de ceux de la boucle while à l'exercice précédent ? D'après vos expérimentations, quels sont selon-vous les avantages et les inconvénients des deux boucles ? ## 3\.Exercice 3 Ecrivez une structure de type boucle qui permet d'afficher les nombres de 0 à 100 avec un retour à la ligne. Résultat attendu : ``` 0 1 2 3 ... 100 ``` Modifiez maintenant votre boucle afin qu'elle n'affiche que les nombres de 1 à 99. Modifiez maintenant votre boucle afin qu'elle n'affiche que les nombres pairs de 0 à 100. ## 4\.Exercice 4 Ecrivez une structure de type boucle qui permet d'afficher les nombres de 0 à 100 avec à côté de chaque nombre sa nature : pair ou impair. Résultat attendu : ``` 0 is even 1 is odd 2 is even 3 is odd ... 100 is even ``` ## 5\.Exercice 5 Déclarez une variable items et assignez lui un tableau contenant les éléments suivants : "First item", "Second item", "Third item", "Fourth item". A la suite, ajoutez la boucle suivante : ``` for (var i=0; i < 4; i++) { console.log(items[i]); } ``` Qu'est ce qui s'affiche à l'écran ? Pourquoi ? A quoi correspond i dans la boucle for ? A quoi correspond i dans le tableau items ? En conséquence que permet de faire ce modèle de boucle associé à un tableau ? Que se passe-t-il si on remplace "i < 4" par "i < 5" ? Quelle sera la dernière valeur de i ? Cela correspond-t-il à quelque chose dans le tableau ? ## 6\.Exercice 6 Le code suivant est censé afficher la liste des clients présents sur notre site. Cependant il ne fonctionne pas. Serez-vous capable de le débuguer ? ``` customers = [ "Albin Term", "Anna Sandgrove", "John Doe"; "Terrance Head", "Yan Mock", "Zoe Durst" ]; console.log("List of all customers : <br>"; for (i=1, i < 4, i++) { console.log(customers . "<br>"; ``` ## 7\.Exercice 7 Déclarez une variable items et assignez lui un tableau contenant les éléments suivants : "First item", "Second item", "Third item", "Fourth item". Utilisez une boucle for/of pour parcourir le tableau et afficher tous les éléments. En l'état a-t-on accès aux indexes ? Selon vous quels sont donc les avantages et inconvénients de la boucle for et for/of ? ## 8\.Exercice 8 Déclarez une variable citizen et assignez lui un tableau associatif. Le tableau contient les indexes et valeurs suivantes : - "firstname" : "John" - "lastname" : "Doe" - "age" : 45 - "income" : 60000 Affichez maintenant à l'écran la carte d'identité de cette personne. C'est à dire l'ensemble des clefs et valeurs qui leur sont associées. Résultat attendu : ``` Citizen identity : firstname : John lastname : Doe age : 45 income : 60000 ``` Rajoutez maintenant une paire index/valeur à votre tableau citizen : - "sexe" : 0 Le sexe est représenté par un boolean. Si sexe vaut 1 alors la personne est une femme, s'il vaut 0 alors la personne est un homme. Rajoutez dans la carte d'identité l'affichage du sexe du citoyen. Cependant vous n'affichez pas un boolean, vous affichez "male" ou "female" selon la valeur stockée. Astuce : vous devrez utiliser plusieurs conditions dans votre boucle. ## 9\.Exercice 9 Voici une variable citizens qui contient un tableau de tableaux : ``` var citizens = [ { "firstname" : "John", "lastname" : "Doe" }, { "firstname" : "Anna", "lastname" : "Molner" }, { "firstname" : "Harry", "lastname" : "Trueman" }, { "firstname" : "Cecile", "lastname" : "Mercier" } ]; ``` Pouvez-vous affichez tous les citoyens ? résultat attendu : ``` Citizen : firstname : John lastname : Doe Citizen : firstname : Anna lastname : Molner etc... ``` Astuce : vous aurez besoin d'une boucle dans une boucle. N'oubliez pas que pour vous aider vous pouvez faire des console.log de votre code pendant que vous le construisez.
Python
UTF-8
98
2.515625
3
[]
no_license
try: print 1/0 except ZeroDivisionError, e: print e except: print "error or exception occured"
Java
UTF-8
2,165
2.3125
2
[]
no_license
package com.infoworks.lab.controllers.rest; import com.infoworks.lab.domain.entities.Passenger; import com.infoworks.lab.rest.models.ItemCount; import com.it.soul.lab.data.simple.SimpleDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.Arrays; import java.util.List; @RestController @RequestMapping("/passenger") public class PassengerController { private SimpleDataSource<String, Passenger> dataSource; @Autowired public PassengerController(SimpleDataSource<String, Passenger> dataSource) { this.dataSource = dataSource; } @GetMapping("/rowCount") public ItemCount getRowCount(){ ItemCount count = new ItemCount(); count.setCount(Integer.valueOf(dataSource.size()).longValue()); return count; } @GetMapping public List<Passenger> query(@RequestParam("limit") Integer limit , @RequestParam("offset") Integer offset){ //TODO: Test with RestExecutor List<Passenger> passengers = Arrays.asList(dataSource.readSync(offset, limit)); return passengers; } @PostMapping @SuppressWarnings("Duplicates") public ItemCount insert(@Valid @RequestBody Passenger passenger){ //TODO: Test with RestExecutor dataSource.put(passenger.getName(), passenger); ItemCount count = new ItemCount(); count.setCount(Integer.valueOf(dataSource.size()).longValue()); return count; } @PutMapping @SuppressWarnings("Duplicates") public ItemCount update(@Valid @RequestBody Passenger passenger){ //TODO: Test with RestExecutor Passenger old = dataSource.replace(passenger.getName(), passenger); ItemCount count = new ItemCount(); if (old != null) count.setCount(Integer.valueOf(dataSource.size()).longValue()); return count; } @DeleteMapping public Boolean delete(@RequestParam("name") String name){ //TODO: Test with RestExecutor Passenger deleted = dataSource.remove(name); return deleted != null; } }
Java
UTF-8
360
2.6875
3
[]
no_license
package moderate; public class Rand{ public int rand7(){ int result = 10; while(result > 6){ int side = rand5(); while(side == 2){ side = rand5(); } if(side < 2){ result = rand5(); }else{ result = rand5() + 5; } } return result; } protected int rand5(){ int result = (int)(Math.random() * 5); return result; } }
C++
UTF-8
901
3.421875
3
[]
no_license
// Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. // Note: // Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? // Example 1: // Input: [2,2,3,2] // Output: 3 // Example 2: // Input: [0,1,0,1,0,1,99] // Output: 99 class Solution { public: int singleNumber(vector<int>& nums) { long long int sum1=0, sum2=0; for(int i=0;i<nums.size();i++) { sum1 = sum1 + nums[i]; } set<int>s; for(int i=0;i<nums.size();i++) { s.insert(nums[i]); } set <int> :: iterator itr; for (itr = s.begin(); itr != s.end(); itr++) { sum2=sum2+*itr; } int result=(sum2*3-sum1)/2; return result; } };
C#
UTF-8
1,618
3.265625
3
[]
no_license
using System; using JetBrains.Annotations; namespace LoggingProxyExample { /// <summary> /// Implementation of the <see cref="ICommand" /> interface. /// </summary> [UsedImplicitly] public class Command : ICommand { public Command(Action action) { if (action == null) throw new ArgumentNullException(nameof(action)); Action = action; } /// <summary> /// Gets the <see cref="Action" /> object. /// </summary> public Action Action { get; } /// <summary> /// Invokes the <see cref="Action" /> object. /// </summary> public virtual void Execute() => Action.Invoke(); } /// <summary> /// Implementaiton of the <see cref="ICommand{T}" /> interface. /// </summary> /// <typeparam name="T">The type parameter taken by the <see cref="Action{T}" /> object.</typeparam> [UsedImplicitly] public class Command<T> : ICommand<T> { public Command(Action<T> action) { if (action == null) throw new ArgumentNullException(nameof(action)); Action = action; } /// <summary> /// Gets the <see cref="Action" /> object. /// </summary> public Action<T> Action { get; } /// <summary> /// Invokes the <see cref="Action{T}" /> object. /// </summary> /// <param name="argument">The argument required for the <see cref="Action{T}" /> object.</param> public virtual void Execute(T argument) => Action.Invoke(argument); } }
Go
UTF-8
594
2.671875
3
[]
no_license
package storage const ( ErrorIfExist OpenOption = "Error If Exist" DefaultOpenOption OpenOption = "Default" ) const ( ErrNotFound KVStorageError = "Not Found" ) type KVStorage interface { Put(key string, value interface{}) (err error) Get(key string, value interface{}) (err error) Has(key string) (ret bool, err error) Delete(key string) (err error) Close() (err error) } type OpenOption string func (opt *OpenOption) ErrorIfExist() bool { return opt != nil && *opt == ErrorIfExist } type KVStorageError string func (e KVStorageError) Error() string { return string(e) }
Java
UTF-8
437
1.515625
2
[]
no_license
package com.kabba.transform; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication @EnableTransactionManagement public class TransformApplication { public static void main(String[] args) { SpringApplication.run(TransformApplication.class, args); } }
Java
UTF-8
107
1.65625
2
[]
no_license
package com.assignment.User.exception; public class NoUserInDatabaseException extends RuntimeException{ }
Go
UTF-8
3,546
2.921875
3
[]
no_license
package main import ( "bytes" "database/sql" "fmt" "net/http" "github.com/gin-gonic/gin" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/apiweb") if err != nil { fmt.Print(err.Error()) } defer db.Close() //membuat koneksi ke database err = db.Ping() if err != nil { fmt.Println(err.Error()) } type Orang struct { ID int NamaPertama string NamaTerakhir string } router := gin.Default() //penghandlean API dari sini //mengambil detail orang router.GET("/orang/:id", func(c *gin.Context) { var ( orang Orang result gin.H ) id := c.Param("id") row := db.QueryRow("select id, nama_pertama, nama_terakhir from orang where id =?;", id) err = row.Scan(&orang.ID, &orang.NamaPertama, &orang.NamaTerakhir) if err != nil { // If no results send null result = gin.H{ "Hasil": nil, "Jumlah Data": 0, } } else { result = gin.H{ "Hasil": orang, "Jumlah Data": 1, } } c.JSON(http.StatusOK, result) }) //mengambil data semua orang router.GET("/orang-orang", func(c *gin.Context) { var ( orang Orang orangorang []Orang ) rows, err := db.Query("select id, nama_pertama, nama_terakhir from orang;") if err != nil { fmt.Print(err.Error()) } for rows.Next() { err = rows.Scan(&orang.ID, &orang.NamaPertama, &orang.NamaTerakhir) orangorang = append(orangorang, orang) if err != nil { fmt.Print(err.Error()) } } defer rows.Close() c.JSON(http.StatusOK, gin.H{ "hasil": orangorang, "jumalah data": len(orangorang), }) }) //menambah data orang-orang // POST new person details router.POST("/orang", func(c *gin.Context) { var buffer bytes.Buffer NamaPertama := c.PostForm("nama_pertama") NamaTerakhir := c.PostForm("nama_terakhir") stmt, err := db.Prepare("insert into orang (nama_pertama, nama_terakhir) values(?,?);") if err != nil { fmt.Print(err.Error()) } _, err = stmt.Exec(NamaPertama, NamaTerakhir) if err != nil { fmt.Print(err.Error()) } // Fastest way to append strings buffer.WriteString(NamaPertama) buffer.WriteString(" ") buffer.WriteString(NamaTerakhir) defer stmt.Close() name := buffer.String() c.JSON(http.StatusOK, gin.H{ "message": fmt.Sprintf(" %s berhasil di tambahkan ke database", name), }) }) // mengubah data yang sudah ada router.PUT("/orang", func(c *gin.Context) { var buffer bytes.Buffer id := c.Query("id") NamaPertama := c.PostForm("nama_pertama") NamaTerakhir := c.PostForm("nama_terakhir") stmt, err := db.Prepare("update orang set nama_pertama= ?, nama_terakhir= ? where id= ?;") if err != nil { fmt.Print(err.Error()) } _, err = stmt.Exec(NamaPertama, NamaTerakhir, id) if err != nil { fmt.Print(err.Error()) } // Fastest way to append strings buffer.WriteString(NamaPertama) buffer.WriteString(" ") buffer.WriteString(NamaTerakhir) defer stmt.Close() name := buffer.String() c.JSON(http.StatusOK, gin.H{ "message": fmt.Sprintf("Data berhasil di rubah %s", name), }) }) //menghapus Data berdasarkan ID router.DELETE("/orang", func(c *gin.Context) { id := c.Query("id") stmt, err := db.Prepare("delete from orang where id= ?;") if err != nil { fmt.Print(err.Error()) } _, err = stmt.Exec(id) if err != nil { fmt.Print(err.Error()) } c.JSON(http.StatusOK, gin.H{ "Pesan": fmt.Sprintf("Anda Telah berhasil menghapus id: %s", id)}) }) router.Run(":8000") } //end
Java
UTF-8
1,345
2.015625
2
[ "Apache-2.0", "LicenseRef-scancode-unknown" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode_examples.listener; import java.util.LinkedList; import java.util.Queue; import org.apache.geode.cache.CacheListener; import org.apache.geode.cache.EntryEvent; import org.apache.geode.cache.RegionEvent; import org.apache.geode.cache.util.CacheListenerAdapter; public class ExampleCacheListener extends CacheListenerAdapter<Integer, String> { public ExampleCacheListener() {} @Override public void afterCreate(EntryEvent<Integer, String> event) { System.out.println("received create for key " + event.getKey()); } }
C
UTF-8
3,662
3.890625
4
[]
no_license
#include <stdio.h> #include <math.h> //MENU void Menu (){ printf("!!!MENU!!!\n"); printf("1 : Cálculo de fatorial\n"); printf("2 : Verificação número primo\n"); printf("3 : Encontrar números primos\n"); printf("4 : Cálculo de potência\n"); printf("5 : Cálculo de raiz\n:"); printf("6 : Verificar se ano é bissexto\n:") printf("7 - 9 :Reexibir Menu\n"); printf("0 -: Terminar execução\n"); } //ANO BISSEXTO void bissexto(int x){ if(x%4 == 0){ printf("\nO ano %i é um ano bissexto.\n",x); }else{ printf("\nO ano %i não é um ano bissexto.\n",x); } } #include <stdio.h> #include <math.h> //MENU void Menu (){ printf("!!!MENU!!!\n"); printf("1 : Cálculo de fatorial\n"); printf("2 : Verificação número primo\n"); printf("3 : Encontrar números primos\n"); printf("4 : Cálculo de potência\n"); printf("5 : Cálculo de raiz\n:"); printf("6 : Verificar se ano é bissexto\n:") printf("7 - 9 :Reexibir Menu\n"); printf("0 -: Terminar execução\n"); } //FATORIAL void Fatorial (int i){ int fatorial = i; int resposta = 1; if (i > 0 ) { for(;fatorial >= 1; --fatorial) { resposta *= fatorial; } printf("o valor do fatorial é %i\n", resposta); } else{ printf("erro!"); } } //PRIMO void Primo (int p) { int num, resposta; while (p <= num) { p = 1; if (num%p == 0) { resposta = resposta + 1; } else { p = p+1; } } if (resposta == 2) { printf("\nO %d número é primo!\n", num); } else { printf("\nO %d número não é primo\n", num); } } //POTENCIA void Potencia (int b) { float a, resposta; resposta = pow(a,b); printf("A potência de %f elevado a %d é igual a:%.2e\n",a, b, resposta); } //RAIZ void Raiz (int c) { float a, resposta; resposta = pow(c, 1/a); printf("O resultado da raiz de %f em %d é igual a %.2e\n", a, c, resposta); } //ANO BISSEXTO void Bissexto(int x){ if(x%4 == 0){ printf("\nO ano %i é um ano bissexto.\n",x); }else{ printf("\nO ano %i não é um ano bissexto.\n",x); } } int main(void) { int opcao, loop =1; int numero; Menu(); scanf("%i", &opcao); while(loop ==1) { switch (opcao) { case 1: printf("1: Cálculo de fatorial\nInforme o valor para calcular o fatorial:"); scanf("%i", &numero); Fatorial(numero); Menu(); break; case 2: printf("2 : Verificação número primo\nInforme um número:"); scanf("%d", &numero); Primo(numero); Menu(); scanf("%d", &opcao); break; case 3: while (numero !=0) { printf("3 : Encontrar números primos\nInforme um número:"); scanf("%d", &numero); Primo(numero); Menu(); scanf("%d", &opcao); } break; case 4: printf("4 : Cálculo de potência\nInforme um número:"); scanf("%d", &numero); Potencia(numero); Menu(); scanf("%d", &opcao); break; case 5: printf("5 : Cálculo de raiz\nInforme um número:"); scanf("%d", &numero); Raiz(numero); Menu(); scanf("%d", &opcao); break; case 6: printf("6 : Verificar se ano é bissexto\nInforme um ano:"); scanf("%d", &numero); Bissexto(numero); Menu(); scanf("%d", &opcao); break; case 7: case 8: case 9: Menu(); scanf("%d", &opcao); break; case 0: printf("Programa encerrado!\n"); loop = 0; break; default: printf("Opção não existe, tente novamente: "); Menu(); scanf("%i", &opcao); break; } } return 0; }
C#
UTF-8
1,089
2.75
3
[ "MIT" ]
permissive
using NBitpayClient; using System.Linq; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace BTCPayServer.Services.Rates { public class BitpayRateProvider : IRateProvider { Bitpay _Bitpay; public BitpayRateProvider(Bitpay bitpay) { if (bitpay == null) throw new ArgumentNullException(nameof(bitpay)); _Bitpay = bitpay; } public async Task<decimal> GetRateAsync(string currency) { var rates = await _Bitpay.GetRatesAsync().ConfigureAwait(false); var rate = rates.GetRate(currency); if (rate == 0m) throw new RateUnavailableException(currency); return (decimal)rate; } public async Task<ICollection<Rate>> GetRatesAsync() { return (await _Bitpay.GetRatesAsync().ConfigureAwait(false)) .AllRates .Select(r => new Rate() { Currency = r.Code, Value = r.Value }) .ToList(); } } }
TypeScript
UTF-8
780
2.609375
3
[]
no_license
import { NegociacaoParcial, Negociacao } from "../models/index"; export class NegociacaoService { getNegociacoes(handleErrors: HandlerFunction): Promise<Negociacao[]> { return fetch("http://localhost:8080/dados") .then(response => handleErrors(response)) .then(response => response.json()) .then((negociacoes: NegociacaoParcial[]) => negociacoes .map(negociacao => new Negociacao(new Date(), negociacao.vezes, negociacao.montante)) ) .catch(error => { console.log(error); throw new Error("Não foi possível importar as negociações."); }); } } export interface HandlerFunction { (response: Response): Response; }
PHP
UTF-8
3,379
3.09375
3
[]
no_license
<?php /** * */ class indexlink { //参照されたことのない置き去りhtm public $notrefs = array(); //参照されてるけど存在しないリンク public $notexist = array(); //存在しないリンクを張ってるhtm public $errorlink = array(); function __construct($workdir) { //カウンタ用のリスト $refDepthCount = array(); //全htmlを取得 $indexfiles = array_filter(explode("\n",shell_exec("ls ".$workdir."/*/index.ht*" )), 'strlen'); $allfiles = array_filter(explode("\n",shell_exec("ls ".$workdir."/*/*htm*" )), 'strlen'); foreach ($indexfiles as $key => $indexfile) { $tmp = explode("/", $indexfile); $dir = $tmp[count($tmp)-2]; $html = $tmp[count($tmp)-1]; $refDepthCount[$dir."/".$html] = 0; } $count = 1; while($count < 5){ foreach (array_keys($refDepthCount) as $htmlile) { $tmp = explode("/", $htmlile); $dir = $tmp[count($tmp)-2]; $html = $tmp[count($tmp)-1]; $reffiles = $this->refer($dir, $html, $workdir); foreach ($reffiles as $reffile) { if(isset($refDepthCount[$reffile]) === false){ $refDepthCount[$reffile] = $count; } } } $count ++; } foreach ($allfiles as $allfile) { //var_dump($allfile); $tmp = explode("/", $allfile); $dir = $tmp[count($tmp)-2]; $html = $tmp[count($tmp)-1]; if(isset($refDepthCount[$dir."/".$html]) === false){ $this->notrefs[] = "{$dir}/{$html}"; } } $this->notexist = array_unique($this->notexist); } function refer( $dir, $html , $workdir){ $contents = @file_get_contents( $workdir . $dir."/".$html); if(!$contents){ $this->notexist[] = $dir."/".$html; } preg_match_all('/.+<?\shref=[\'|"](.*?)[\'|"].*/', $contents, $matches, PREG_PATTERN_ORDER); $add_dir = function($url) use( $dir, $html) { if($dir == "takken" && ( $url == "menkyosetumei.html" || $url == "menkyoyouken.html" || $url == "mumenkyohanbai.html" || $url == "needmenkyo.html" ) ) { $this->errorlink[$dir."/".$html][] = $url; } if(strpos($url, "http", 0) === 0 || strpos($url, "htm", 0) === false || $url === $html) return false; return $dir."/".$url; }; return array_filter(array_map($add_dir, $matches[1])); } } //フォルダ指定 $indexlink = new indexlink($argv[1]); print "参照されてないhtm\n"; foreach ($indexlink->notrefs as $notrefs) { print " ".$notrefs."\n"; } print "存在しないhtm\n"; foreach ($indexlink->notexist as $notexist) { print " ".$notexist."\n"; } print "存在しないhtmを参照しているhtm\n"; foreach ($indexlink->errorlink as $errorlink => $urls ) { print " 参照元:".$errorlink."\n"; $urls = array_unique($urls); foreach ($urls as $url) { print " $url\n"; } } //var_dump($indexlink->notexist); // //var_dump($indexlink->errorlink);
PHP
UTF-8
2,299
2.625
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Jobs\PlaceBet; use App\Models\Contact; use Symfony\Component\HttpFoundation\Response; class TransactController extends Controller { /** * @param string $mobile * @param string $action * @param int $amount * @return Contact|null */ public function transfer(string $mobile, string $action, int $amount) { $contact = Contact::bearing($mobile); $contact->{$action}($amount); return $contact; } /** * @param string $mobile * @param string $otp * @param int $amount * @return Contact|null */ public function debit(string $mobile, string $otp, int $amount) { $contact = Contact::bearing($mobile); if (! $contact) return response('Error: mobile number not found!', Response::HTTP_INTERNAL_SERVER_ERROR); $contact->verify($otp); if (config('mudmod.otp.bypass') == 0) if (! $contact->verified()) return response('Error: mobile number not verified!', Response::HTTP_INTERNAL_SERVER_ERROR); if ($contact->balance < $amount) $amount = $contact->balance; $contact->debit($amount); $message = 'The quick brown fox...'; return response(json_encode(compact('mobile', 'amount', 'message')), Response::HTTP_OK) ->header('Content-Type', 'text/json'); } public function getBet(string $mobile) { $contact = Contact::bearing($mobile); if (! $contact) return response('Error: mobile number not found!', Response::HTTP_INTERNAL_SERVER_ERROR); return response(json_encode($contact->bet), Response::HTTP_OK) ->header('Content-Type', 'text/json'); } public function placeBet(string $mobile, string $date, int $game, string $hand, int $amount) { $contact = Contact::bearing($mobile); if (! $contact) return response('Error: mobile number not found!', Response::HTTP_INTERNAL_SERVER_ERROR); $this->dispatch(new PlaceBet($contact, $date, $game, $hand, $amount)); return response(json_encode(compact('mobile', 'date', 'game', 'hand', 'amount')), Response::HTTP_OK) ->header('Content-Type', 'text/json'); } }
Java
UTF-8
643
3.453125
3
[ "MIT" ]
permissive
package noNeg; import java.util.ArrayList; import java.util.List; public class NoNeg { //Dada a lista numérica "nums", retorne outra em que não haja números abaixo de 0. public List<Integer> noNeg(List<Integer> nums) { nums.removeIf(n -> n < 0); return nums; } //RELEMBRANDO... public List<Integer> noNeg_2(List<Integer> nums) { nums.removeIf(n -> n < 0); return nums; // OR the equivalent stream solution // Note that the boolean logic is opposite // return nums.stream() // .filter(n -> n >= 0) // .collect(Collectors.toList()); } }
C++
UTF-8
2,676
2.953125
3
[ "BSL-1.0" ]
permissive
// Copyright Justinas Vygintas Daugmaudis, 2010. // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE-1.0 or http://www.boost.org/LICENSE-1.0) #ifndef HEADER_DETAIL_LIST_ASSIGNMENT_HPP_INCLUDED #define HEADER_DETAIL_LIST_ASSIGNMENT_HPP_INCLUDED namespace detail { // Forward declaration template<class T, class ForwardIterator> class scalar_or_list_assignment; template<class T, typename ForwardIterator> class list_assignment { private: typedef list_assignment<T, ForwardIterator> self_type; typedef scalar_or_list_assignment<T, ForwardIterator> switch_type; ForwardIterator m_iterator_; public: explicit list_assignment(switch_type& rhs); explicit list_assignment(ForwardIterator pos) : m_iterator_(pos) {} inline self_type operator,(T value) { *m_iterator_ = value; return self_type(++m_iterator_); } }; template<class T, class ForwardIterator> class scalar_or_list_assignment { private: friend class list_assignment<T, ForwardIterator>; typedef scalar_or_list_assignment<T, ForwardIterator> self_t; typedef list_assignment<T, ForwardIterator> assign_from_list; public: explicit scalar_or_list_assignment(ForwardIterator first, ForwardIterator last, T value) : m_first(first) , m_last(last) , m_value(value) { // Immediately initialize the first element // and move iterator position forward. *m_first = value; ++m_first; } scalar_or_list_assignment(const self_t& rhs) : m_first(rhs.m_first) , m_last(rhs.m_last) , m_value(rhs.m_value) { // This is, admitedly, not very pretty, but quite necessary // for optimization purposes; initialization would be O(n^2) // instead of O(n) otherwise. const_cast<self_t *>(&rhs)->disable(); } ~scalar_or_list_assignment() { std::fill(m_first, m_last, m_value); } // Continues initialization of [first + 1, last) // by consecutive assignment of given scalar values // to the underlying data structure. assign_from_list operator,(T value) { *m_first = value; ++m_first; return assign_from_list(*this); } private: void disable() { m_first = m_last; } private: ForwardIterator m_first; ForwardIterator m_last; T m_value; }; //============================================================================= // list_assignment c-tor implementation template<class T, typename Iterator> inline list_assignment<T, Iterator>::list_assignment(scalar_or_list_assignment<T, Iterator>& rhs) : m_iterator_(rhs.m_first) { rhs.disable(); } } // namespace detail #endif // HEADER_DETAIL_LIST_ASSIGNMENT_HPP_INCLUDED
Java
UTF-8
179
2.125
2
[]
no_license
package io.jsd.training.designpattern.book.chap3.ObjetsGraphiques.objetsgraphiquesavecannule; public interface Commande { public void lance(); public void annule(); }
JavaScript
UTF-8
7,380
3.0625
3
[]
no_license
function startBlinkingTextWrapper(){ var typing_simulators = (() => { var typing_simulator_node_list = document.querySelectorAll(".typing-simulator"); var selves = []; Array.prototype.forEach.call(typing_simulator_node_list, self => { var next_character_index = 0; var added_characters = []; var removed_characters = []; var erasure_options = null; var name = (function () { var is_name_token = token => /^typing-simulator--name-/.test(token); var tokens = Array.prototype.filter.call(self.classList, is_name_token); var names = tokens.map(token => token.slice(23)); return names[0]; })(); var text = ((typing_simulator) => { var selector = `.typing-simulator--name-${name}`; selector += " .typing-simulator__text"; var self = document.querySelector(selector); self.addCharacter = function (character) { var typing_simulator_character = document.createElement("div"); typing_simulator_character.classList.add("typing-simulator__character"); typing_simulator_character.innerHTML = character; self.appendChild(typing_simulator_character); }; self.removeCharacter = function () { var removed_character = null; if (!self.lastChild) return null; removed_character = self.lastChild; self.lastChild.remove(); removed_characters.unshift(removed_character); return removed_character; }; self.lastNCharacters = function (n) { return Array.prototype.slice.call(self.children, self.childElementCount - n); }; self.lastNCharactersToString = function (n) { var last_n_characters = self.lastNCharacters(n); var str = ""; last_n_characters.forEach(character => { if (character.innerHTML === "&nbsp;") { str += " "; } else { str += character.innerHTML; } }); return str; }; self.endsWithString = function (str) { console.log(`${self.lastNCharactersToString(str.length)} == ${str}`); return self.lastNCharactersToString(str.length) === str; } return self; })(self); self.cursor = (() => { var selector = `.typing-simulator--name-${name}`; selector += " .typing-simulator__cursor"; var self = document.querySelector(selector); self.blinkInterval = 600; simulate_blinking(); function simulate_blinking() { setInterval(toggle_visibility, self.blinkInterval); }; function toggle_visibility() { self.classList.toggle("typing-simulator__cursor--inactive"); self.classList.toggle("typing-simulator__cursor--active"); } return self; })(self); simulate_typing(); self.name = name; selves.push(self); function simulate_typing() { var options = { rawText: simple_text, characterDelay: 25 }; var { rawText, characterDelay } = options; function callback() { var next_character = rawText.charAt(next_character_index); if (next_character) { next_character_index < rawText.length && ++next_character_index; var new_character = next_character === " " && "&nbsp;" || next_character; text.addCharacter(new_character); added_characters.push(new_character); poll_erasure_signal(); simulate_erasure(simulate_typing); } } setTimeout(callback, characterDelay); }; /* * Define the behaviour of the typing simulation here. * To define a behaviour: * 1. Create an IIFE * 2. Write an if condition evaluating "true" using methods on the typing-simlator "text" object. * 3. Place assign a new options object to predeclared "erasure_options" variable. * That's it! */ function poll_erasure_signal() { var character_delay = 100; (() => { var str = head; if (text.endsWithString(str)) { erasure_options = { numCharacters: str.length, characterDelay: character_delay }; } })(); (() => { var str = des1; if (text.endsWithString(str)) { erasure_options = { numCharacters: str.length, characterDelay: character_delay }; } })(); (() => { var str = des2; if (text.endsWithString(str)) { erasure_options = { numCharacters: str.length, characterDelay: character_delay }; } })(); (() => { var str = des3; if (text.endsWithString(str)) { erasure_options = { numCharacters: str.length, characterDelay: character_delay }; } })(); (() => { var str = des4; if (text.endsWithString(str)) { erasure_options = { numCharacters: str.length, characterDelay: character_delay }; } })(); } function simulate_erasure(callback) { if (erasure_options) { var { numCharacters, characterDelay } = erasure_options; setTimeout(remove_characters, characterDelay); } else { callback(); } function remove_characters() { var invalidNumCharacters = numCharacters >= text.length; if (!invalidNumCharacters && !(removed_characters.length === numCharacters)) { text.removeCharacter(); simulate_erasure(callback); } else { erasure_options = null; removed_characters = []; callback(); } } } }); return selves; })(); } startBlinkingText(); setInterval(startBlinkingText, 20000);
C++
UTF-8
4,330
2.796875
3
[ "BSD-3-Clause" ]
permissive
/*========================================================================= Program: Visualization Toolkit Module: vtkSmartPointerBase.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSmartPointerBase.h" #include "vtkGarbageCollector.h" //---------------------------------------------------------------------------- vtkSmartPointerBase::vtkSmartPointerBase(): Object(0) { // Add a reference to the object. this->Register(); } //---------------------------------------------------------------------------- vtkSmartPointerBase::vtkSmartPointerBase(vtkObjectBase* r): Object(r) { // Add a reference to the object. this->Register(); } //---------------------------------------------------------------------------- vtkSmartPointerBase::vtkSmartPointerBase(vtkObjectBase* r, const NoReference&): Object(r) { // Do not add a reference to the object because we received the // NoReference argument. } //---------------------------------------------------------------------------- vtkSmartPointerBase::vtkSmartPointerBase(const vtkSmartPointerBase& r): Object(r.Object) { // Add a reference to the object. this->Register(); } //---------------------------------------------------------------------------- vtkSmartPointerBase::~vtkSmartPointerBase() { // The main pointer must be set to NULL before calling UnRegister, // so use a local variable to save the pointer. This is because the // garbage collection reference graph traversal may make it back to // this smart pointer, and we do not want to include this reference. vtkObjectBase* object = this->Object; if(object) { this->Object = 0; object->UnRegister(0); } } //---------------------------------------------------------------------------- vtkSmartPointerBase& vtkSmartPointerBase::operator=(vtkObjectBase* r) { // This is an exception-safe assignment idiom that also gives the // correct order of register/unregister calls to all objects // involved. A temporary is constructed that references the new // object. Then the main pointer and temporary are swapped and the // temporary's destructor unreferences the old object. vtkSmartPointerBase(r).Swap(*this); return *this; } //---------------------------------------------------------------------------- vtkSmartPointerBase& vtkSmartPointerBase::operator=(const vtkSmartPointerBase& r) { // This is an exception-safe assignment idiom that also gives the // correct order of register/unregister calls to all objects // involved. A temporary is constructed that references the new // object. Then the main pointer and temporary are swapped and the // temporary's destructor unreferences the old object. vtkSmartPointerBase(r).Swap(*this); return *this; } //---------------------------------------------------------------------------- void vtkSmartPointerBase::Report(vtkGarbageCollector* collector, const char* desc) { vtkGarbageCollectorReport(collector, this->Object, desc); } //---------------------------------------------------------------------------- void vtkSmartPointerBase::Swap(vtkSmartPointerBase& r) { // Just swap the pointers. This is used internally by the // assignment operator. vtkObjectBase* temp = r.Object; r.Object = this->Object; this->Object = temp; } //---------------------------------------------------------------------------- void vtkSmartPointerBase::Register() { // Add a reference only if the object is not NULL. if(this->Object) { this->Object->Register(0); } } //---------------------------------------------------------------------------- ostream& operator << (ostream& os, const vtkSmartPointerBase& p) { // Just print the pointer value into the stream. return os << static_cast<void*>(p.GetPointer()); }
PHP
UTF-8
2,252
2.8125
3
[]
no_license
<?php namespace App\Cms; use App\Entity\CmsPage; use App\Repository\CmsPageRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use RuntimeException; use Twig\Environment; class PageManager { /** @var CmsPageRepository */ private $pageRepository; /** @var Environment */ private $environment; public function __construct(CmsPageRepository $pageRepository, Environment $environment) { $this->pageRepository = $pageRepository; $this->environment = $environment; } /** * Find a page by slug or id. * * @param string|int $slug */ public function findPage($slug): ?CmsPage { return $this->pageRepository->findOneBy(['slug' => $slug]) ?? $this->pageRepository->find($slug); } /** * @return array[] */ public function getSiblings(CmsPage $page, ?bool $published = true): array { $children = $this->getChildren($page->getParent(), $published); $index = $children->indexOf($page); return [$children->slice(0, $index), $children->slice($index + 1)]; } public function getFrontPage(): ?CmsPage { $pages = $this->getChildren(); return $pages->count() > 0 ? $pages->first() : null; } /** * Get a twig view for rendering a page. * * @param Page $page */ public function getPageView(CmsPage $page): string { $loader = $this->environment->getLoader(); foreach ([ 'cms/page/show-'.$page->getType().'.html.twig', 'cms/page/show.html.twig', ] as $view) { if ($loader->exists($view)) { return $view; } } throw new RuntimeException('Cannot find page template'); } /** * @return Collection|CmsPage[] */ private function getChildren(CmsPage $page = null, ?bool $published = true): Collection { $criteria = ['parent' => $page]; if (null !== $published) { $criteria = ['published' => $published]; } return new ArrayCollection($this->pageRepository->findBy($criteria, ['position' => 'ASC'])); } }
Java
UTF-8
1,337
2.453125
2
[]
no_license
package com.twx.transfer; import com.twx.VO.QueryVO; import com.twx.entity.WarnEntity; import com.twx.enums.WarnTypeEnum; import org.springframework.beans.BeanUtils; import java.util.ArrayList; import java.util.List; import java.util.stream.Collector; import java.util.stream.Collectors; public class WarnEntity2QueryVOTransfer { public static QueryVO transfer(WarnEntity warnEntity){ QueryVO queryVO = new QueryVO(); queryVO.setJobMasterId(warnEntity.getJobMasterId()); queryVO.setWarningTitle(warnEntity.getWarningTitle()); String warningType = warnEntity.getWarningType(); if (warningType.equals(WarnTypeEnum.DOING.getType())) { queryVO.setWarningType(WarnTypeEnum.DOING.getDescription()); } if (warningType.equals(WarnTypeEnum.READING.getType())) { queryVO.setWarningType(WarnTypeEnum.READING.getDescription()); } Boolean isActivated = warnEntity.getIsActivated(); if (isActivated) { queryVO.setActivated("启用"); }else{ queryVO.setActivated("禁用"); } return queryVO; } public static List<QueryVO> transfer(List<WarnEntity> warnEntityList){ return warnEntityList.stream().map(e -> transfer(e)) .collect(Collectors.toList()); } }
PHP
UTF-8
1,718
2.765625
3
[]
no_license
<?php namespace vir; class ObjectGroup implements \Iterator, \ArrayAccess, \JsonSerializable { private $position = 0; private $container = []; public function __construct() { Debug::Log(); $this->position = 0; } ///// Iterator functions function rewind() { $this->position = 0; } function current() { return $this->container[$this->position]; } function key() { return $this->container[$this->position]->name; } function next() { ++$this->position; } function valid() { return isset($this->container[$this->position]); } ///// ArrayAccess functions public function offsetSet($offset, $value) { Debug::Log(); $value->setName($offset); $this->container[] = $value; } public function offsetExists($offset) { $item = $this->find($offset); return isset($item); } public function offsetUnset($offset) { return false; } public function offsetGet($offset) { return $this->find($offset); } ///// JsonSerializeable public function jsonSerialize() { return $this->container; } public function __get($name) { Debug::Log(); return $this->find($name); } public function __set($name, $value) { Debug::Log(); $item = $this->find($name); return $item($value); } private function find($name) { Debug::Log(); $filter = function($array) use ($name) { return $array->checkName($name); }; $results = array_filter($this->container, $filter); return array_shift($results); } }
Markdown
UTF-8
4,411
2.890625
3
[]
no_license
+++ date = "2016-08-21T11:26:34+07:00" title = "Hướng dẫn dùng Hugo để viết blog" +++ Trong bài viết này mình sẽ hướng dẫn sử dụng Hugo để viết bài. Các bạn cũng sử dụng Hugo để viết bài cho Golangvn. Mình hoan nghênh mọi sự đóng góp từ các bạn. Các bạn có thể sử dụng chức năng pull requests của Github, mình sẽ merge và phản hồi sớm nhất. <!--more--> ## Bước 1: Cài đặt Hugo Có nhiều cách để cài đặt Hugo. Cách đơn giản nhất là sử dụng sự hỗ trợ có sẵn của hệ điều hành bạn đang sử dụng: - [Cài đặt Hugo trên OS X](https://gohugo.io/tutorials/installing-on-mac/) - [Cài đặt Hugo trên Windown](https://gohugo.io/tutorials/installing-on-windows/) Nếu bạn sử dụng Linux có thể tìm kiếm với Package Manager. Trên máy mình sử dụng Arch, vì vậy có thể sử dụng sự hỗ trợ từ `yaourt` ``` $ yaourt -Ss hugo aur/hugo 0.16-1 (40) (2.46) Fast and Flexible Static Site Generator in Go aur/hugo-git v0.15.r3.g26af48a-1 (1) (0.05) Fast and Flexible Static Site Generator in Go aur/hugo-src 0.16-2 (1) (0.58) Fast and Flexible Static Site Generator in Go — built from source. ``` Cá nhân mình chọn cách cài đặt từ mã nguồn của Hugo từ Github. Bạn chỉ cần có Git và Go ở trên máy và sử dụng lệnh `go get` ``` $ go get -v github.com/spf13/hugo ``` Khi đã cài đặt xong bạn có thể chạy thử lệnh `hugo` ``` $ hugo version Hugo Static Site Generator v0.17-DEV BuildDate: 2016-08-21T00:28:22+07:00 ``` ## Bước 2: Tạo blog > Nếu bạn muốn đóng góp trực tiếp bài viết lên Golangvn, bạn có thể bỏ qua bước 2 và 3. Bạn chỉ cần clone [blog trên Github](https://github.com/golangvn/blog) và chuyển qua bước 4. Khi Hugo đã được cài đặt trên máy của bạn thì mọi chuyện còn lại rất đơn giản. Để tạo một blog mới, bạn sử dụng lệnh `hugo new site`. Ví dụ mình tạo một Hugo site `blog`, mình chạy lệnh ``` $ hugo new site blog ``` Di chuyển vào thư mục `blog` vừa mới tạo, bạn sẽ thấy Hugo tạo cho chúng ta những tập tin cơ bản ``` . |-- archetypes |-- config.toml |-- content |-- data |-- layouts |-- themes `-- static 6 directories, 1 file ``` ## Bước 3: Theme Bước tiếp theo chúng ta chúng ta cần một `Hugo theme` để thể hiện blog của mình. Bạn có thể chọn một theme trên [Hugo themes](https://themes.gohugo.io/). Cộng đồng Hugo có đóng góp rất nhiều theme đẹp và miễn phí. Ở đây mình chọn theme [Beautiful Hugo](http://themes.gohugo.io/beautifulhugo/). Di chuyển vào thư mục themes ``` $ cd themes/ ``` Clone theme ``` $ git clone https://github.com/halogenica/Hugo-BeautifulHugo.git beautifulhugo ``` Trở lại thư mục blog của bạn ``` $ cd .. ``` ## Bước 4: Tạo bài viết và viết bài Để tạo một bài viết, chúng ta sử dụng lệnh `hugo new post/tên-bài-viết.md` Ví dụ: ``` $ hugo new post/huong-dan-hugo.md ``` Hugo sẽ tạo ra tập tin `huong-dan-hugo.md` ``` content `-- post `-- huong-dan-hugo.md 1 directory, 1 file ``` Với nội dung: ``` +++ date = "2016-08-21T11:26:34+07:00" draft = true title = "huong dan hugo" +++ ``` Bạn có thể sửa tiêu đề và viết vài dòng sau dấu `+++` ## Bước 5: Xem thành quả của mình Để xem bài viết sẽ được thể hiện ra sao hãy dùng lệnh `hugo serve` ``` $ hugo serve --theme=beautifulhugo --buildDrafts ``` Vì bài viết của bạn đang là bản nháp(`draft = true`) nên chúng ta cần thêm `--buildDrafts` vào câu lệnh. Bây giờ mở trình duyệt vào xem blog của bạn với link [http://localhost:1313/](http://localhost:1313/) ## Bước 6: Xuất bản bài viết Để chia sẻ bài viết bạn có thể sử dụng Github, Bitbucket hoặc có thể tải lên server của riêng bạn. Ở đây mình sử dụng Github với [Github Pages](https://pages.github.com/) Bạn có thể làm theo hướng dẫn trên trang của Hugo: [Hosting on GitHub Pages](https://gohugo.io/tutorials/github-pages-blog/ ) Và trang bạn đang đọc chính là thành quả của bài viết này.
Shell
UTF-8
1,105
3.5
4
[ "Apache-2.0" ]
permissive
#!/bin/bash set -e PACKER_VERSION=1.0.4 TERRAFORM_VERSION=0.10.2 TERRAGRUNT_VERSION=0.13.0 TOOLS_DIR=$1 mkdir -p ${TOOLS_DIR} BIN_DIR=${TOOLS_DIR}/bin mkdir -p ${BIN_DIR} export PATH=${BIN_DIR}:$PATH ### Install Terraform TERRAFORM_DL=${TOOLS_DIR}/terraform-${TERRAFORM_VERSION} if [ ! -d "${TERRAFORM_DL}" ] then mkdir -p ${TERRAFORM_DL} wget -q -O terraform-${TERRAFORM_VERSION}.zip https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip unzip -q terraform-${TERRAFORM_VERSION}.zip -d ${TERRAFORM_DL} rm terraform-${TERRAFORM_VERSION}.zip fi ln -sf ${TERRAFORM_DL}/terraform ${BIN_DIR} terraform version ### Install packer PACKER_DL=${TOOLS_DIR}/packer-${PACKER_VERSION} if [ ! -d "${PACKER_DL}" ] then mkdir -p ${PACKER_DL} wget -q -O packer-${PACKER_VERSION}.zip https://releases.hashicorp.com/packer/${PACKER_VERSION}/packer_${PACKER_VERSION}_linux_amd64.zip unzip -q packer-${PACKER_VERSION}.zip -d ${PACKER_DL} rm packer-${PACKER_VERSION}.zip fi ln -sf ${PACKER_DL}/packer ${BIN_DIR} packer version exit 0
Python
UTF-8
11,779
2.6875
3
[]
no_license
import numpy import math import DNA_matrix def base_pair_parameters(rotation_1,rotation_2,origin_1,origin_2): z1_v=numpy.array([rotation_1[i][2] for i in range(3)]) z2_v=numpy.array([rotation_2[i][2] for i in range(3)]) if numpy.dot(z1_v,z2_v.T) < 0: for i in range(3): for j in range(1,3): rotation_2[i][j]=-rotation_2[i][j] y1_vector=numpy.array([rotation_1[i][1] for i in range(3)]) y2_vector=numpy.array([rotation_2[i][1] for i in range(3)]) gamma=math.acos(numpy.dot(y1_vector,y2_vector)) #calculate buckleopening angle. b0_vector=numpy.cross(y2_vector,y1_vector) #buckle-opening axis b0_vector=b0_vector/math.sqrt(numpy.dot(b0_vector,b0_vector.T)) # normalize the b0 rotate_matrix_1=DNA_matrix.Rotate_matrix(-gamma/2,b0_vector) rotate_matrix_2=DNA_matrix.Rotate_matrix(gamma/2,b0_vector) #create rotate_matrix_2 trans_orient_1=numpy.matrix(rotate_matrix_1)*numpy.matrix(rotation_1) trans_orient_2=numpy.matrix(rotate_matrix_2)*numpy.matrix(rotation_2) #get the orientation matirx of transformed bases. MBT_matirx=(trans_orient_1+trans_orient_2)/2 #// MBT_origin[i]=(origin_1+origin_2)/2 MBT_matirx=DNA_matrix.Norm_matrix_in_row(MBT_matirx) #normalization the row. x_vector_temp_1=numpy.array([trans_orient_1[i,0] for i in range(3)]) x_vector_temp_2=numpy.array([trans_orient_2[i,0] for i in range(3)]) x_vector_temp_1=x_vector_temp_1/math.sqrt(numpy.dot(x_vector_temp_1,x_vector_temp_1.T)) x_vector_temp_2=x_vector_temp_2/math.sqrt(numpy.dot(x_vector_temp_2,x_vector_temp_2.T)) # print x_vector_temp_1 # print x_vector_temp_2 y_vector_MBT=numpy.array([MBT_matirx[i,1] for i in range(3)]) omega=math.acos(numpy.dot(x_vector_temp_1,x_vector_temp_2.T)) cross_result_temp=numpy.cross(x_vector_temp_2,x_vector_temp_1) if(numpy.dot(cross_result_temp,y_vector_MBT.T)<0): omega=-abs(omega) else: omega=abs(omega) x_vector_MBT=numpy.array([MBT_matirx[i,0] for i in range(3)]) phi=math.acos(numpy.dot(b0_vector,x_vector_MBT.T)) cross_b0_xmat_temp=numpy.cross(b0_vector,x_vector_MBT) if(numpy.dot(cross_b0_xmat_temp,y_vector_MBT)<0): phi= - abs(phi) else: phi=abs(phi) kappa=gamma * math.cos(phi) sigma=gamma * math.sin(phi) #get kappa and sigma displacement=numpy.matrix(numpy.array(origin_1)-numpy.array(origin_2))*MBT_matirx shear=displacement[0,0] stretch=displacement[0,1] stagger=displacement[0,2] buckle=kappa/math.pi * 180 propeller=omega /math.pi * 180 opening=sigma/math.pi * 180 return shear,stretch,stagger,buckle, propeller,opening def base_step_parameters(rotation_1,rotation_2,origin_1,origin_2): z1_vector=numpy.array([rotation_1[i][2] for i in range(3)]) z2_vector=numpy.array([rotation_2[i][2] for i in range(3)]) gamma=math.acos(numpy.dot(z1_vector,z2_vector.T)) # print gamma # //calculate buckleopening angle. rt_vector=numpy.cross(z1_vector,z2_vector) #//buckle-opening axis rt_vector=rt_vector/math.sqrt(numpy.dot(rt_vector,rt_vector.T)) # // normalize the rt_vector b0 rotate_matrix_1=DNA_matrix.Rotate_matrix(gamma/2,rt_vector) rotate_matrix_2=DNA_matrix.Rotate_matrix(-gamma/2,rt_vector) #//create rotate_matrix_1, create rotate_matrix_2 trans_orient_1=numpy.matrix(rotate_matrix_1)*numpy.matrix(rotation_1) trans_orient_2=numpy.matrix(rotate_matrix_2)*numpy.matrix(rotation_2) # print trans_orient_1 # print trans_orient_2 #//get the orientation matirx of transformed bases. MST_matirx=(trans_orient_1+trans_orient_2)/2 MST_matirx=DNA_matrix.Norm_matrix_in_row(MST_matirx) #normalization the row. y_vector_temp_1=numpy.array([trans_orient_1[i,1] for i in range(3)]) y_vector_temp_2=numpy.array([trans_orient_2[i,1] for i in range(3)]) y_vector_temp_1=y_vector_temp_1/math.sqrt(numpy.dot(y_vector_temp_1,y_vector_temp_1.T)) y_vector_temp_2=y_vector_temp_2/math.sqrt(numpy.dot(y_vector_temp_2,y_vector_temp_2.T)) z_vector_MST =numpy.array([MST_matirx[i,2] for i in range(3)]) y_vector_MST =numpy.array([MST_matirx[i,1] for i in range(3)]) omega=math.acos(numpy.dot(y_vector_temp_1,y_vector_temp_2.T)) cross_result_temp=numpy.cross(y_vector_temp_1,y_vector_temp_2) if(numpy.dot(cross_result_temp,z_vector_MST)<0): omega=-abs(omega) else: omega=abs(omega) # // for omega phi=math.acos(numpy.dot(rt_vector,y_vector_MST.T)) cross_rt_ymat_temp=numpy.cross(rt_vector,y_vector_MST) if(numpy.dot(cross_rt_ymat_temp,z_vector_MST)<0): phi= - abs(phi) else: phi=abs(phi) #//for phi kappa=gamma * math.cos(phi) sigma=gamma * math.sin(phi) #//get kappa and sigma displacement=numpy.matrix(origin_2 - origin_1)*MST_matirx shift=displacement[0,0] slide=displacement[0,1] rise=displacement[0,2] roll=kappa/math.pi * 180 twist=omega /math.pi * 180 tilt=sigma/math.pi * 180 return shift,slide,rise,tilt,roll,twist def middle_frame(rotation_1,rotation_2,origin_1,origin_2): z1_v=numpy.array([rotation_1[i][2] for i in range(3)]) z2_v=numpy.array([rotation_2[i][2] for i in range(3)]) if numpy.dot(z1_v,z2_v.T) < 0: for i in range(3): for j in range(1,3): rotation_2[i][j]=-rotation_2[i][j] y1_vector=[rotation_1[i][1] for i in range(3)] y2_vector=[rotation_2[i][1] for i in range(3)] gamma=math.acos(numpy.dot(y1_vector,y2_vector)) # //calculate buckleopening angle. b0_vector=numpy.cross(y2_vector,y1_vector) # //buckle-opening axis b0_vector=b0_vector/math.sqrt(numpy.dot(b0_vector,b0_vector.T)) # // normalize the b0 rotate_matrix_1=DNA_matrix.Rotate_matrix(-gamma/2,b0_vector) rotate_matrix_2=DNA_matrix.Rotate_matrix(gamma/2,b0_vector) #//create rotate_matrix_1 #//create rotate_matrix_2 trans_orient_1=numpy.matrix(rotate_matrix_1)*numpy.matrix(rotation_1) trans_orient_1=DNA_matrix.Norm_matrix_in_row(trans_orient_1) trans_orient_2=numpy.matrix(rotate_matrix_2)*numpy.matrix(rotation_2) trans_orient_2=DNA_matrix.Norm_matrix_in_row(trans_orient_2) #//get the orientation matirx of transformed bases. middle_matirx=(trans_orient_1+trans_orient_2)/2 middle_matirx=DNA_matrix.Norm_matrix_in_row(middle_matirx) #normalization the row. middle_origin=(numpy.array(origin_1)+numpy.array(origin_2))/2 return numpy.array(middle_matirx),middle_origin def Calc_dihedral(atom1, atom2, atom3, atom4): b1=numpy.array([atom2.atom_coor_x-atom1.atom_coor_x,\ atom2.atom_coor_y-atom1.atom_coor_y,\ atom2.atom_coor_z-atom1.atom_coor_z]) b2=numpy.array([atom3.atom_coor_x-atom2.atom_coor_x,\ atom3.atom_coor_y-atom2.atom_coor_y,\ atom3.atom_coor_z-atom2.atom_coor_z]) b3=numpy.array([atom4.atom_coor_x-atom3.atom_coor_x,\ atom4.atom_coor_y-atom3.atom_coor_y,\ atom4.atom_coor_z-atom3.atom_coor_z]) phi=math.atan2( numpy.dot( math.sqrt(numpy.dot(b2,b2))*b1 , numpy.cross(b2,b3) ),\ numpy.dot( numpy.cross(b1,b2) , numpy.cross(b2,b3) )) *180 /math.pi if phi < -120: phi_c="t" elif phi < 0: phi_c="g-" elif phi < 120: phi_c="g+" else: phi_c="t" return phi,phi_c def Get_Dihedral(Atom_list, base_serial): ''' calculate the dihedral from the top file. ''' for i in Atom_list: # print Atom_list[i].atom_name if Atom_list[i].atom_name in ["O3'","O3*"] and Atom_list[i].residue_serial==base_serial-1: index_O3_0=i elif Atom_list[i].atom_name in ["P","H5T"] and Atom_list[i].residue_serial==base_serial: index_P=i elif Atom_list[i].atom_name in ["O5'","O5*"] and Atom_list[i].residue_serial==base_serial: index_O5=i elif Atom_list[i].atom_name in ["C5'","C5*"] and Atom_list[i].residue_serial==base_serial: index_C5=i elif Atom_list[i].atom_name in ["C4'","C4*"] and Atom_list[i].residue_serial==base_serial: index_C4=i elif Atom_list[i].atom_name in ["C3'","C3*"] and Atom_list[i].residue_serial==base_serial: index_C3=i elif Atom_list[i].atom_name in ["O3'","O3*"] and Atom_list[i].residue_serial==base_serial: index_O3=i elif Atom_list[i].atom_name in ["P","H3T"] and Atom_list[i].residue_serial==base_serial+1: index_P_2=i elif Atom_list[i].atom_name in ["O5'","O5*"] and Atom_list[i].residue_serial==base_serial+1: index_O5_2=i elif Atom_list[i].atom_name in ["O4'","O4*"] and Atom_list[i].residue_serial==base_serial: index_O4=i elif Atom_list[i].atom_name in ["C1'","C1*"] and Atom_list[i].residue_serial==base_serial: index_C1=i elif Atom_list[i].atom_name in ["N9"] and Atom_list[i].residue_serial==base_serial and \ ("A" in Atom_list[i].residue_name or "G" in Atom_list[i].residue_name): index_N_base=i elif Atom_list[i].atom_name=="N1" and Atom_list[i].residue_serial==base_serial and \ ("C" in Atom_list[i].residue_name or "T" in Atom_list[i].residue_name): index_N_base=i elif Atom_list[i].atom_name=="C4" and Atom_list[i].residue_serial==base_serial and \ ("A" in Atom_list[i].residue_name or "G" in Atom_list[i].residue_name): index_C_base=i elif Atom_list[i].atom_name=="C2" and Atom_list[i].residue_serial==base_serial and \ ("C" in Atom_list[i].residue_name or "T" in Atom_list[i].residue_name): index_C_base=i dihedral=dict() try: alpha,alpha_c =Calc_dihedral(Atom_list[index_O3_0],Atom_list[index_P ],Atom_list[index_O5 ],Atom_list[index_C5 ]) except: alpha = "-" alpha_c="-" try: beta,beta_c =Calc_dihedral(Atom_list[index_P ],Atom_list[index_O5],Atom_list[index_C5 ],Atom_list[index_C4 ]) except: beta = "-" beta_c = "-" gamma,gamma_c =Calc_dihedral(Atom_list[index_O5 ],Atom_list[index_C5],Atom_list[index_C4 ],Atom_list[index_C3 ]) delta,delta_c =Calc_dihedral(Atom_list[index_C5 ],Atom_list[index_C4],Atom_list[index_C3 ],Atom_list[index_O3 ]) try: epslon,epslon_c=Calc_dihedral(Atom_list[index_C4 ],Atom_list[index_C3],Atom_list[index_O3 ],Atom_list[index_P_2 ]) except: epslon = "-" epslon_c="-" try: zeta,zeta_c =Calc_dihedral(Atom_list[index_C3 ],Atom_list[index_O3],Atom_list[index_P_2],Atom_list[index_O5_2]) except: zeta = "-" zeta_c = "-" chi ,chi_c =Calc_dihedral(Atom_list[index_O4],Atom_list[index_C1],Atom_list[index_N_base],Atom_list[index_C_base]) # print index_O4,index_C1,index_N_base,index_C_base # print Atom_list[index_O4].atom_coor_x if chi < 0 or chi > 90: chi_c="anti" elif chi < 90 and chi > 0: chi_c="syn" dihedral[alpha ] = alpha dihedral[beta ] = beta dihedral[gamma ] = gamma dihedral[delta ] = delta dihedral[zeta ] = zeta dihedral[epslon] = epslon dihedral[chi ] = chi dihedral[alpha_c ] = alpha_c dihedral[beta_c ] = beta_c dihedral[gamma_c ] = gamma_c dihedral[delta_c ] = delta_c dihedral[epslon_c] = epslon_c dihedral[zeta_c ] = zeta_c dihedral[chi_c ] = chi_c return [alpha,beta,gamma,delta,epslon,zeta,chi,alpha_c,beta_c,gamma_c,delta_c,epslon_c,zeta_c,chi_c]
Java
UTF-8
2,993
2.375
2
[]
no_license
package in.ac.iiit.cvit.heritage; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; /** * Created by HOME on 03-11-2016. */ public class InstructionsActivity extends AppCompatActivity { /** * This class provides the instruction for app uasge to the user */ private static final int SLEEP = 5; private static final String LOGTAG = "InstructionsActivity"; private Boolean first_time; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Loading the language preference LocaleManager localeManager = new LocaleManager(InstructionsActivity.this); localeManager.loadLocale(); first_time = getIntent().getExtras().getBoolean(getString(R.string.first_time_instructions)); // Log.v(LOGTAG, "first_time = " + first_time); try { if (first_time) { //This activity is only shown when opened for the first time after installing // Log.v(LOGTAG, "opened Instructions activity for the first time"); setContentView(R.layout.activity_instructions); Button done_with_instructions = (Button) findViewById(R.id.done_with_instructions); done_with_instructions.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent_package_list = new Intent(InstructionsActivity.this, MenuActivity.class); intent_package_list.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent_package_list); finish(); } }); } else { //From second time whenever this app is opened, this activity is shown // Log.v(LOGTAG, "opened Instructions activity not for the first time"); setContentView(R.layout.activity_instructions); Button done_with_instructions = (Button) findViewById(R.id.done_with_instructions); done_with_instructions.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } } catch (Exception e) { Log.e(LOGTAG, e.toString()); } } @Override public void onBackPressed() { if (first_time) { Intent intent_package_list = new Intent(InstructionsActivity.this, MenuActivity.class); intent_package_list.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent_package_list); finish(); } else { super.onBackPressed(); } } }
Java
UTF-8
189
1.976563
2
[ "MIT" ]
permissive
package wraith.quivermd.mixin_interfaces; import net.minecraft.item.ItemStack; public interface IItemStack { void setQuiverStack(ItemStack stack); ItemStack getQuiverStack(); }
Java
UTF-8
1,236
4.5
4
[]
no_license
package com.java.collection; import java.util.Iterator; import java.util.TreeSet; public class TreeSetExample { /** * TreeSet is sorted * How to iterate a TreeSet * How to check empty * How to retrieve first/last element * How to remove an element */ public static void main(String[] args) { TreeSet<Integer> myTree = new TreeSet<>(); myTree.add(35); myTree.add(45); myTree.add(25); myTree.add(35); //Traversal of TreeSet Iterator<Integer> iter = myTree.iterator(); while(iter.hasNext()) { System.out.println(iter.next()); //Output : 25, 35, 45 } //EmptyChecking if (myTree.isEmpty()) { System.out.println("Tree is empty"); } else { System.out.println("Tree is not empty"); } //retrieving First element System.out.println("First Element: "+myTree.first()); System.out.println("Last Element: "+myTree.last()); //Removing an element myTree.remove(35); Iterator<Integer> iter2 = myTree.iterator(); while(iter2.hasNext()) { System.out.println(iter2.next()); //Output : 25, 45 } //Clearing the tree myTree.clear(); if (myTree.isEmpty()) { System.out.println("Tree is empty"); } else { System.out.println("Tree is not empty"); } } }
Java
UTF-8
3,600
2.3125
2
[]
no_license
package com.rexar.islandcraft; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Colors; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.github.czyzby.noise4j.map.Grid; import com.github.czyzby.noise4j.map.generator.noise.NoiseGenerator; import com.github.czyzby.noise4j.map.generator.util.Generators; import com.badlogic.gdx.graphics.*; import com.rexar.islandcraft.screens.GameScreen; import com.rexar.islandcraft.utils.AssetsManager; public class ICraft extends Game { private SpriteBatch batch; private Texture texture; // @Override // public void create() { // final Pixmap grid = new Pixmap(768, 768, Pixmap.Format.RGBA8888); // final Grid grid = new Grid(768); // // final NoiseGenerator noiseGenerator = new NoiseGenerator(); // noiseStage(grid, noiseGenerator, 32, 0.6f); // noiseStage(grid, noiseGenerator, 16, 0.2f); // noiseStage(grid, noiseGenerator, 8, 0.1f); // noiseStage(grid, noiseGenerator, 4, 0.1f); // noiseStage(grid, noiseGenerator, 1, 0.05f); // noiseStage(grid, noiseGenerator, 1, 0.01f); // // for (int x = 0; x < grid.getWidth(); x++) { // for (int y = 0; y < grid.getHeight(); y++) { // final float cell = grid.get(x, y); // if (cell > 0.3f + (0.4f * distanceSquared(x, y, grid))) { // if (cell > 0.5) { // if (cell > 0.61f) { // grid.drawPixel(x, y, Color.rgba8888(0, cell - 0.2f, 0, 1)); // } else // grid.drawPixel(x, y, Color.rgba8888(0, cell, 0, 1)); // } else { // grid.drawPixel(x, y, Color.rgba8888(cell, cell, 0, 1)); // } // } else { // grid.set(x, y, 0f); // grid.drawPixel(x, y, Color.rgba8888(0, 0, cell, 1)); // } // } // } // // texture = new Texture(grid); // batch = new SpriteBatch(); // // // Pixmap print = texture.getTextureData().consumePixmap(); // PixmapIO.writePNG(FileHandle.tempFile("mapNew.png"), print); // // // grid.dispose(); // } private static float distanceSquared(int x, int y, Grid grid) { float dx = 2f * x / grid.getWidth() - 1f; float dy = 2f * y / grid.getHeight() - 1f; return dx * dx + dy * dy; } private static void noiseStage(final Grid grid, final NoiseGenerator noiseGenerator, final int radius, final float modifier) { noiseGenerator.setRadius(radius); noiseGenerator.setModifier(modifier); // Seed ensures randomness, can be saved if you feel the need to // generate the same grid in the future. noiseGenerator.setSeed(Generators.rollSeed()); noiseGenerator.generate(grid); } @Override public void create() { new AssetsManager(); setScreen(new GameScreen(this)); } // @Override // public void render() { // Gdx.gl.glClearColor(0f, 0f, 0f, 1f); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // batch.begin(); // batch.draw(texture, 0f, 0f); // batch.end(); // } // // @Override // public void dispose() { // texture.dispose(); // batch.dispose(); // } }
Rust
UTF-8
2,566
3.015625
3
[ "MIT" ]
permissive
use std::error; use std::fmt; use std::string; use serde_json; use ring; use data_encoding; #[derive(Debug)] pub enum JwtError { Decode, Verify } impl fmt::Display for JwtError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("Token decode error") } } impl error::Error for JwtError { fn description(&self) -> &str { "Token decode error" } fn cause(&self) -> Option<&error::Error> { None } } #[derive(Debug)] pub enum Error { Json(serde_json::Error), Crypto(ring::error::Unspecified), Base64(data_encoding::DecodeError), FromUtf8Error(string::FromUtf8Error), JwtError(JwtError) } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Json(ref err) => write!(f, "Json error: {}", err), Error::Crypto(ref err) => write!(f, "Crypto error: {}", err), Error::Base64(ref err) => write!(f, "Base64 error: {}", err), Error::FromUtf8Error(ref err) => write!(f, "FromUtf8 error: {}", err), Error::JwtError(ref err) => write!(f, "Jwt error: {}", err), } } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Json(ref err) => err.description(), Error::Crypto(ref err) => err.description(), Error::Base64(ref err) => err.description(), Error::FromUtf8Error(ref err) => err.description(), Error::JwtError(ref err) => err.description() } } fn cause(&self) -> Option<&error::Error> { match *self { Error::Json(ref err) => Some(err), Error::Crypto(ref err) => Some(err), Error::Base64(ref err) => Some(err), Error::FromUtf8Error(ref err) => Some(err), Error::JwtError(ref err) => Some(err) } } } impl From<serde_json::Error> for Error { fn from(err: serde_json::Error) -> Self { Error::Json(err) } } impl From<ring::error::Unspecified> for Error { fn from(err: ring::error::Unspecified) -> Self { Error::Crypto(err) } } impl From<data_encoding::DecodeError> for Error { fn from(err: data_encoding::DecodeError) -> Self { Error::Base64(err) } } impl From<string::FromUtf8Error> for Error { fn from(err: string::FromUtf8Error) -> Self { Error::FromUtf8Error(err) } } impl From<JwtError> for Error { fn from(err: JwtError) -> Self { Error::JwtError(err) } }
Python
UTF-8
453
3.328125
3
[]
no_license
class Solution: def issubstring(self,a,b): i,j=0,0 while i<len(a) and j<len(b): if a[i]==b[j]: i+=1 j+=1 else: i+=1 return j==len(b) def findLongestWord(self, s: str, d: List[str]) -> str: d.sort(key=lambda word:(-len(word),word)) for word in d: if self.issubstring(s,word): return word return ''
Ruby
UTF-8
914
2.609375
3
[]
no_license
class Post < ApplicationRecord belongs_to :user has_many :comments has_many :likes has_many :post_categories has_many :categories, through: :post_categories has_many :liked_users, through: :likes, source: :user has_many :commented_users, through: :comments, source: :user has_one_attached :image #Validations validate :image_presence ### Methods # Validates image is attached def image_presence errors.add(:image, "Image must be attached.") unless image.attached? end # Custom setter for category names def category_names=(names) names.each do |name| unless name == "" category = Category.find_or_create_by(name: name) self.categories << category unless self.categories.include?(category) end end end # Custom getter for category names def category_names self.categories.map do |category| category.name end end end
Go
UTF-8
3,017
2.578125
3
[ "BSD-3-Clause", "Apache-2.0", "TCL", "HPND", "LicenseRef-scancode-unknown-license-reference", "OpenSSL", "LicenseRef-scancode-openssl", "MIT", "LicenseRef-scancode-ssleay-windows", "ISC", "BSD-2-Clause" ]
permissive
package server import ( "github.com/gin-gonic/gin" "net/http" "runtime" "sort" "strconv" "fmt" ) const ( RunTime = "info" Health = "health" GC = "gc" Conn = "conn" ) type MonitorResp struct { //Code int `json:"code"` Message string `json:"message"` Data interface{} `json:"data,omitempty"` } var handlerMap= map[string]func(ctx *gin.Context){ RunTime: handleRuntimeInfo, Health:handleHealthCheck, GC:handlerGc, Conn:handleConnectionInfo, } func MonitorHandler(ctx *gin.Context) { option,_:=ctx.Params.Get("option") handler:=handlerMap[option] if handler==nil{ ctx.AbortWithStatusJSON(http.StatusOK,gin.H{ "opts":[]string{RunTime,Health,GC,Conn}, }) return } handler(ctx) } func handleRuntimeInfo(c *gin.Context) { countMap,total:=getActiveClients() resp:=&MonitorResp{ //Code:http.StatusOK, Message:"ok", Data:map[string]interface{}{ "clients":map[string]interface{}{ "total":total, "detail":countMap, }, "go_routine_num":runtime.NumGoroutine(), "num_cpu":runtime.NumCPU(), "num_cgo_call":runtime.NumCgoCall(), }, } c.AbortWithStatusJSON(http.StatusOK,resp) } type ConnInfo struct { Appid string `json:"appid"` ConnNum int `json:"conn_num"` } //获取appid 连接信息 func handleConnectionInfo(ctx *gin.Context) { infoMap:=ConnTransManager.GetConnectionInfo() var infoAs = make([]*ConnInfo, 0,len(infoMap)) for k, v := range infoMap { infoAs = append(infoAs,&ConnInfo{Appid:k,ConnNum:v}) } sort.Slice(infoAs, func(i, j int) bool { return infoAs[i].ConnNum > infoAs[j].ConnNum }) ctx.AbortWithStatusJSON(200,gin.H{ "infos":infoAs, }) } func handleHealthCheck(c *gin.Context) { c.AbortWithStatusJSON(http.StatusOK,nil) } func handlerGc(c *gin.Context) { runtime.GC() c.AbortWithStatusJSON(http.StatusOK,map[string]interface{}{ "message":"gc success", }) } func getActiveClients()(map[string]int,int){ total:=0 var count = map[string]int{} cache.sessionMg.Range(func(key, value interface{}) bool { total++ if s,ok:=value.(*Session);ok{ count[s.Call]++ } return true }) return count,total } //杀掉appid上过多的连接 func HandlerKill(ctx *gin.Context){ appid:=ctx.Param("appid") reverse:=ctx.Param("remain") num,err:=strconv.Atoi(reverse) //剩下 if err !=nil{ ctx.AbortWithStatusJSON(http.StatusBadRequest,gin.H{ "message":"remain num:"+reverse+" is not a vaild number", }) return } ConnTransManager.Kill(appid,num) ctx.AbortWithStatusJSON(http.StatusBadRequest,gin.H{ "message":fmt.Sprintf("success kill connnection of %s,remain connection:%d",appid,ConnTransManager.GetCount(appid)), }) } //获取appid的当前接数 func HandlerGetConncection(ctx *gin.Context) { appid:=ctx.Param("appid") count:=ConnTransManager.GetCount(appid) ctx.AbortWithStatusJSON(http.StatusOK,gin.H{ "appid":appid, "active_conns":count, }) } //
Python
UTF-8
1,432
3.5
4
[]
no_license
import tkinter class Menubutton(tkinter.Tk): def __init__(self): tkinter.Tk.__init__(self) self.title("MenuButton") self.geometry("200x200") menubutton = tkinter.Menubutton(text="Cities") menubutton.pack() self.var = tkinter.StringVar() cities = ["Houston", "Seattle", "San Diego"] def on_menu_item_clicked(self,number): print(cities[number]) menu = tkinter.Menu(menubutton, tearoff=0) menubutton['menu'] = menu menu.add_command(label="Houston", command=self.on_menu_item_clicked(0)) menu.add_command(label="Seattle", command=self.on_menu_item_clicked(1)) menu.add_command(label="San Diego", command=self.on_menu_item_clicked(2)) if __name__ == "__main__": application = Menubutton() application.mainloop() # mb= Menubutton ( root, text=firstext, relief=RAISED ) # mb2= Menubutton ( root, text=firstext, relief=RAISED ) / mb.grid() mb.menu = Menu(mb, tearoff=0) mb["menu"] = mb.menu mb.place(x=500, y=100) mb.pack() mb2.grid() mb2.menu = Menu(mb2, tearoff=0) mb2["menu"] = mb2.menu mb2.place(x=500, y=100) # mb2.pack() def sel(): print("You selected the option " + str(var.get())) se = int(var.get()) g = int(var.get()) updatedropdown(g) def itemselected(int, fightername): firstext = fightername
Python
UTF-8
2,362
3.578125
4
[]
no_license
# extracts only relevant words from frontpage, returns one string # param doc: PDF document to iterate through of type <class 'fitz.fitz.Document'> def get_clean_frontpage_text(doc): page = doc.loadPage(0) text = page.getText('text') # extract text from pdf clean_text = text.split() # removes formatting info etc and returns list of strings remove_unwanted_words(clean_text) index = clean_text.index("Wähleranteile:") relevant_words = clean_text[index:] # only keep words beginning from 'Wähleranteile' joined_words = ' '.join(relevant_words) # join all relevant words back together return joined_words # removes unwanted words from relevant words, like "Steffen Seibert" def remove_unwanted_words(wordlist, unwanted_words=["Steffen", "Seibert"]): for unwanted_word in unwanted_words: if unwanted_word in wordlist: wordlist.remove(unwanted_word) return wordlist # takes (hard coded) key words and returns list of key + their start- and end indices def get_indices(text, keys, end_word): # choose end_word freely, for example 'Ende' indices = [] for key in keys: if key in text: start_index = text.find(key) end_index = text.find(key) + len(key) temp_list = [key, start_index, end_index] indices.append(temp_list) end_list = [end_word, len(text)] indices.append(end_list) return indices # takes clean text (only relevant words as string) and returns dict with # topic as key and content as value def get_frontpage_content(text, keys_with_indices): title_page = {} values = [] counter = 0 endword = keys_with_indices[-1][0] for key in keys_with_indices: if keys_with_indices[counter][0] in text: key = keys_with_indices[counter][0].replace(":", "") start_index = keys_with_indices[counter][2] + 1 if keys_with_indices[counter + 1][0] == endword: end_index = keys_with_indices[counter + 1][1] else: end_index = (keys_with_indices[counter + 1][1]) for item in text[start_index:end_index]: values.append(item) string_values = ''.join(values) title_page[key] = string_values.rstrip() values.clear() counter += 1 return title_page
Python
UTF-8
1,684
3.5
4
[]
no_license
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]: def isLeaf(node:TreeNode) -> bool: return node.left is None and node.right is None def recursiveLeft(node:TreeNode): if node is None: return if isLeaf(node): return self.result.append(node.val) if node.left: recursiveLeft(node.left) else: recursiveLeft(node.right) def recursiveRight(node:TreeNode): if node is None: return if isLeaf(node): return if node.right: recursiveRight(node.right) else: recursiveRight(node.left) # print("right val=", node.val) self.result.append(node.val) def recursiveLeaf(node:TreeNode): if node is None: return if isLeaf(node): # print("leaf val=", node.val) self.result.append(node.val) recursiveLeaf(node.left) recursiveLeaf(node.right) if root is None: return [] self.result = [root.val] if root.left: recursiveLeft(root.left) if root.left or root.right: recursiveLeaf(root) if root.right: recursiveRight(root.right) return self.result
Java
UTF-8
2,294
3.515625
4
[]
no_license
/* @Copyright:LintCode @Author: vadxin @Problem: http://www.lintcode.com/problem/kth-smallest-number-in-sorted-matrix @Language: Java @Datetime: 16-07-18 05:35 */ class Element { public int val; public int row; public int col; public Element(int val, int row, int col) { this.val = val; this.row = row; this.col = col; } } class Order implements Comparator<Element> { public int compare(Element a, Element b) { return a.val - b.val; } } public class Solution { /** * @param matrix: a matrix of integers * @param k: an integer * @return: the kth smallest number in the matrix */ public int kthSmallest(int[][] matrix, int k) { // write your code here if (matrix == null || matrix.length == 0 || matrix[0].length == 0 || k <= 0) { return Integer.MIN_VALUE; } int row = matrix.length; if (matrix[0].length == 1) { return k <= row ? matrix[k - 1][0] : Integer.MAX_VALUE; } int col = matrix[0].length; Queue<Element> heap; int ans = 0; if (row > col) { heap = new PriorityQueue<Element>(row, new Order()); for (int i = 0; i < row; i++) { heap.offer(new Element(matrix[i][0], i, 0)); } int count = k; while (count > 0) { Element tmp = heap.poll(); count--; ans = tmp.val; int x = tmp.row; int y = tmp.col; if (y + 1 < col) { heap.offer(new Element(matrix[x][y + 1], x, y + 1)); } } } else { heap = new PriorityQueue<Element>(col, new Order()); for (int i = 0; i < col; i++) { heap.offer(new Element(matrix[0][i], 0, i)); } int count = k; while (count > 0) { Element tmp = heap.poll(); count--; ans = tmp.val; int x = tmp.row; int y = tmp.col; if (x + 1 < row) { heap.offer(new Element(matrix[x + 1][y], x + 1, y)); } } } return ans; } }
C
UTF-8
311
2.84375
3
[ "0BSD" ]
permissive
#include <stdio.h> int a[50000]; int main(){ int i,j,A=0,B=0; for(i=0;i<50000;i++)a[i]=i*(i+1)/2+1; int v[2]; scanf("%d%d",v,v+1); for(j=0;j<2;j++){ for(i=0;i<50000;i++){ if(a[i]>v[j]){ int x=a[i]-v[j]; A+=x,B+=i+1-x; break; } } } int x=A+B-2; printf("%d\n",a[x]+B-1); return 0; }
Java
UTF-8
318
2.5625
3
[]
no_license
package Factory; public class factory { public static void main(String[] args) { // TODO Auto-generated method stub String str1="CheesePizza"; String str2="PepperoniPizza"; String str3="ClamPizza"; PizzStore ps=new PizzStore(); ps.orderPizza(str1); ps.orderPizza(str2); ps.orderPizza(str3); } }
JavaScript
UTF-8
2,349
3
3
[]
no_license
var weatherObject = new XMLHttpRequest(); weatherObject.open('GET','/EmilyTheApple.github.io/lesson-9/JSON/towndata.JSON',true) weatherObject.send(); weatherObject.onload = function() { var weatherInfo = JSON.parse(weatherObject.responseText); console.log(weatherInfo); document.getElementById('preston').innerHTML = weatherInfo.towns[4].name; console.log(weatherInfo.towns[4].name); document.getElementById('pmotto').innerHTML = weatherInfo.towns[4].motto; console.log(weatherInfo.towns[4].motto); document.getElementById('pyearFound').innerHTML = weatherInfo.towns[4].yearFounded; console.log(weatherInfo.towns[4].yearFounded); document.getElementById('pcurrentPop').innerHTML = weatherInfo.towns[4].currentPopulation; console.log(weatherInfo.towns[4].currentPopulation); document.getElementById('paverageRain').innerHTML = weatherInfo.towns[4].averageRainfall; console.log(weatherInfo.towns[4].averageRainfall); document.getElementById('sodasprings').innerHTML = weatherInfo.towns[5].name; console.log(weatherInfo.towns[5].name); document.getElementById('smotto').innerHTML = weatherInfo.towns[5].motto; console.log(weatherInfo.towns[5].motto); document.getElementById('syearFound').innerHTML = weatherInfo.towns[5].yearFounded; console.log(weatherInfo.towns[5].yearFounded); document.getElementById('scurrentPop').innerHTML = weatherInfo.towns[5].currentPopulation; console.log(weatherInfo.towns[5].currentPopulation); document.getElementById('saverageRain').innerHTML = weatherInfo.towns[5].averageRainfall; console.log(weatherInfo.towns[5].averageRainfall); document.getElementById('fishhaven').innerHTML = weatherInfo.towns[1].name; console.log(weatherInfo.towns[1].name); document.getElementById('fmotto').innerHTML = weatherInfo.towns[1].motto; console.log(weatherInfo.towns[1].motto); document.getElementById('fyearFound').innerHTML = weatherInfo.towns[1].yearFounded; console.log(weatherInfo.towns[1].yearFounded); document.getElementById('fcurrentPop').innerHTML = weatherInfo.towns[1].currentPopulation; console.log(weatherInfo.towns[1].currentPopulation); document.getElementById('faverageRain').innerHTML = weatherInfo.towns[1].averageRainfall; console.log(weatherInfo.towns[1].averageRainfall); }
Markdown
UTF-8
3,137
3.625
4
[]
no_license
# 单例模式 - 系统中被唯一使用 - **一个类只能初始化一个实例** ## 示例 - 登录框 - 购物车 - redux - vuex ## 说明 - 单例模式需要用到Java的特性(private) - ES6中没有(typescript除外) - 只能用Java代码来演示UML图的内容 Java单例实例 ```java public class SingleObject{ // 注意,私有化构造函数,外部不能new,只能内部new private SingleObject() {} // 唯一被 new 出来的对象 private SingleObject instance = null; // 获取对象的唯一接口 public SingleObject getInstance(){ if(instance == null){ // 只 new 一次 instance = new SingleObject(); } return instance; } // 对象方法 public void login(username, password) { System.out.println("login...") } } // ------------测试---------- public class SingletonPatternDemo { public static void main(String[] args) { // 不合法的构造函数 // 编译时报错:构造函数 SingleObject() 是不可见的!!! // SingleObject object = new SingleObject() // 获取唯一可用的对象 SingleObject object = SingleObject.getInstance(); object.login(); } } ``` JS 模拟实例 ```javascript class SingleObject { login() { console.log('login...') } } SingleObject.getInstance = (function() { let instance return function() { if(!instance) { instance = new SingleObject() } return instance } })() // -------测试--------- let obj1 = SingleObject.getInstance() obj1.login() let obj2 = SingleObject.getInstance() obj2.login() console.log('obj1 === obj2', obj1 === obj2) // 两者必须完全相等 console.log('--分隔--') let obj3 = new SingleObject() // 无法完全控制 obj3.login() console.log('obj1 === obj3', obj1 === obj3) // false ``` ## 场景 - jQuery 只有一个 `$` ```javascript if (window.jQuery != null) { return window.jQuery } else { // 初始化... } ``` - 模拟登录框 登录框为单例 ```javascript export class LoginForm { constructor() { this.state = 'hide' } show() { if(this.state === 'show') { alert('已经显示了') return } this.state = 'show' console.log('登录框显示成功') } hide() { if(this.state === 'hide') { alert('已经隐藏了') return } this.state = 'hide' console.log('登录框隐藏成功') } } LoginForm.getInstance = (() => { let instance return () => { if(!instance) { instance = new LoginForm() } return instance } })() // ---------测试----------- const login1 = LoginForm.getInstance() login1.show() const login2 = LoginForm.getInstance() login2.hide() console.log('login1 === login2', login1 === login2) // true ``` - 其他 ## 设计原则验证 - 符合单一职责原则,只实例化唯一的对象 - 没法具体开放封闭原则,但是绝对不违反开放封闭原则
Java
UTF-8
1,672
3.296875
3
[]
no_license
import java.io.*; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; /** * Created by Marvin on 28.11.2014. */ public class Main { public static void main (String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException { int i = 0; String s = null; byte[] hash = null; StringBuilder sb = null; ArrayList<String> dictionary = new ArrayList<String>(); MessageDigest md = MessageDigest.getInstance("MD5"); //Import words into dictionary for (char c = 'A'; c <= 'Z'; c++) { String path = "words/" + c + " Words.csv"; BufferedReader br = null; String line = null; try { br = new BufferedReader(new FileReader(path)); while ((line = br.readLine()) != null) dictionary.add(line); } catch (FileNotFoundException ignored) { } catch (IOException ignored) {} } for (String s1 : dictionary) { for (String s2 : dictionary) { s = s1 + "+" + s2; hash = md.digest(s.getBytes("UTF-8")); sb = new StringBuilder(2*hash.length); for (byte b : hash) { sb.append(String.format("%02x", b&0xff)); } if (sb.toString().equals("68059415b3b24844f9d93d9653a40e29")) { System.out.println("Puzzle Solution: \"" + s + "\""); return; } } System.out.println(i++ + "/" + dictionary.size()); } } }
Java
UTF-8
3,935
2.140625
2
[ "MIT" ]
permissive
package com.example.together.activities; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.together.R; import com.example.together.adapter.PostAdapter; import com.example.together.models.Post; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class PostListActivity extends AppCompatActivity { private static final String TAG = "PostListActivity"; private RecyclerView recyclerView; private RecyclerView.Adapter adapter; private RecyclerView.LayoutManager layoutManager; private ArrayList<Post> postList; private FirebaseAuth mAuth; private FirebaseDatabase mDatabase; private DatabaseReference mRef; private Toolbar mToolbar; public static PostListActivity closePostList; // For finish previous PostListActivity after post @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); mAuth = FirebaseAuth.getInstance(); mDatabase = FirebaseDatabase.getInstance(); mRef = mDatabase.getReference("posts"); setContentView(R.layout.activity_netflix_bbs); closePostList=PostListActivity.this; // For finish previous PostListActivity after post recyclerView = (RecyclerView) findViewById(R.id.recyclerView); // recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); postList = new ArrayList<>(); mDatabase = FirebaseDatabase.getInstance(); mRef = mDatabase.getReference("posts"); mRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { postList.clear(); for(DataSnapshot snap : snapshot.getChildren()) { Log.e(TAG, "success database"); Post post = snap.getValue(Post.class); postList.add(post); } adapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError error) { Log.e(TAG, "에러럴러러러러러러러럴러러ㅓ"); } }); adapter = new PostAdapter(postList, this); recyclerView.setAdapter(adapter); findViewById(R.id.postBtn).setOnClickListener(onClickListener); //게시글 작성 버튼 아이디 findViewById(R.id.arrow).setOnClickListener(onClickListener); //뒤로가기 버튼 아이디 } View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v){ switch(v.getId()){ case R.id.postBtn: startPostActivity(); break; case R.id.arrow: // 뒤로가기 버튼 누를 시 onBackPressed(); break; } } }; private void startPostActivity() { Intent intent = new Intent(PostListActivity.this, PostActivity.class); startActivity(intent); } }
Java
UTF-8
10,361
3.234375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cine; import java.util.Scanner; import java.util.LinkedList; /** * * @author Usuario Estandar */ public class Cine { public static Menu menu = new Menu(null); public static Scanner scanner = new Scanner(System.in); public static LinkedList<Pedido> pedidos = new LinkedList<>(); /** * @param args the command line arguments */ public static void main(String[] args) { while(true){ System.out.println("Bienvenido al sistema de Cine"); menu.set("Que desea hacer?", "Pedido en linea", "Pedido por taquilla"); System.out.println(menu); int eleccion = menu.getEleccion(); System.out.println("Ingrese la cantidad de productos que comprara"); int cantProductos = 0; do { cantProductos = scanner.nextInt(); if (cantProductos < 0 ) System.out.println("No se puede comprar una cantidad negativa de productos"); } while(cantProductos < 0); Pedido pedido = new Pedido(cantProductos); if ( eleccion == 0 ) { System.out.println("Ha escogido pedido en linea"); pedido.setFactorAumento(8); } else System.out.println("Ha escogido pedido por taquilla"); for (int i = 0; i < cantProductos;) { menu.set("Escoja uno de los productos siguientes", "Entradas", "Refrescos", "Cotufas", eleccion == 1 ? "Tequeños" : ""); System.out.println(menu); switch(menu.getEleccion()) { case 0: System.out.println("Introduzca la cantidad de entradas a comprar"); int numEntradas; do { numEntradas = scanner.nextInt(); if (numEntradas < 0) System.out.println("No se puede comprar un numero negativo. Vuelva a intentar"); else if (numEntradas > Entrada.MAX_ENTRADAS) System.out.println("No se pueden comprar mas de 200 entradas! Vuelva a intentar"); else if (numEntradas > cantProductos - i) System.out.println("No puede comprar esta cantidad porque excede el limite de este pedido"); else if (numEntradas > Entrada.restantes()) { System.out.println("No quedan tantas entradas. Se le daran las restantes"); numEntradas = Entrada.restantes(); } } while (numEntradas < 0 || numEntradas > Entrada.MAX_ENTRADAS || numEntradas > cantProductos - i ); // La cantidad de entradas es valida para este punto. Las añadimos al pedido for (int j = 0; j < numEntradas; j++) pedido.addProducto(new Entrada()); i += numEntradas; break; case 1: System.out.println("Introduzca la cantidad de refrescos a comprar"); int numRefrescos; do { numRefrescos = scanner.nextInt(); if (numRefrescos < 0) System.out.println("No se puede comprar un numero negativo. Vuelva a intentar"); else if (numRefrescos > cantProductos - i) System.out.println("No puede comprar esta cantidad porque excede el limite de este pedido"); } while (numRefrescos < 0 || numRefrescos > cantProductos - i); for (int j = 0; j < numRefrescos; j++){ menu.set("Escoja el sabor de su refresco (" + (j+1) + ")", "Pepsi", "7UP", "Nestea"); System.out.println(menu); switch(menu.getEleccion()) { case 0: pedido.addProducto(new Refresco("pepsi")); break; case 1: pedido.addProducto(new Refresco("7up")); break; case 2: pedido.addProducto(new Refresco("nestea")); break; } } i += numRefrescos; break; case 2: System.out.println("Introduzca la cantidad de cotufas a comprar"); int numCotufas; do { numCotufas = scanner.nextInt(); if (numCotufas < 0) System.out.println("No se puede comprar un numero negativo. Vuelva a intentar"); else if (numCotufas > cantProductos - i) System.out.println("No puede comprar esta cantidad porque excede el limite de este pedido"); } while (numCotufas < 0 || numCotufas > cantProductos - i ); for (int j = 0; j < numCotufas; j++) { menu.set("Escoja el tamaño de sus cotufas (" + (j+1) + ")", "Medianas", "Grandes"); System.out.println(menu); pedido.addProducto(new Cotufa( menu.getEleccion() == 0 ? Cotufa.Tamaño.MEDIANA : Cotufa.Tamaño.GRANDE )); } i += numCotufas; break; case 3: System.out.println("Introduzca la cantidad de tequeños a comprar"); int numTequeños; do { numTequeños = scanner.nextInt(); if (numTequeños < 0) System.out.println("No se puede comprar un numero negativo. Vuelva a intentar"); else if (numTequeños > cantProductos - i) System.out.println("No puede comprar esta cantidad porque excede el limite de este pedido"); } while (numTequeños < 0 || numTequeños > cantProductos - i ); for (int j = 0; j < numTequeños; j++) pedido.addProducto(new Tequeño()); i += numTequeños; break; } } if (esFibonacci(pedidos.size())) { System.out.println("Felicidades! Su orden es un numero de Fibonacci. Su compra le salra a mitad de precio"); pedido.setFactorDescuento(50); } System.out.println("Resumen de su compra (#" + pedidos.size() + ")"); System.out.println(pedido); menu.set("Seguro que desea realizar la compra?", "No", "Si"); System.out.println(menu); if ( menu.getEleccion() == 1 ) { if (eleccion == 0) { Estadisticas.ventaOnline(pedido.getPrecioFinal()); Estadisticas.comisionesOnline(pedido.aplicarAumento(pedido.getPrecioNeto())); } else Estadisticas.ventaTaquilla(pedido.getPrecioFinal()); for (Producto producto: pedido.getProductos()) { producto.vender(); double rand = 0; do rand = Math.random() * 100; while (rand > 30); if ( esPrimo((int)rand) ) producto.evento(); else System.out.println("El cliente se llevo a gusto su " + producto.getNombre()); } pedidos.add(pedido); } else System.out.println("Vale! Ha rechazado la compra"); menu.set("Que desea hacer ahora?", "Agregar otro cliente", "Terminar con el dia"); System.out.println(menu); if (menu.getEleccion() == 1) break; } StringBuilder resumen = new StringBuilder("Resumen del dia\n"); resumen.append("Total articulos vendidos").append(Producto.getVentas()); resumen.append("\nEntradas vendidas: ").append(Entrada.getVentas()); resumen.append("\nRefrescos totales vendidos: ").append(Refresco.getVentas()); resumen.append("\nPepsis vendidos: ").append(Refresco.getVentasPepsi()); resumen.append("\n7up vendidos: ").append(Refresco.getVentas7up()); resumen.append("\nNestea vendidos: ").append(Refresco.getVentasNestea()); resumen.append("\nCotufas totales vendidas: ").append(Cotufa.getVentas()); resumen.append("\nCotufas grandes vendidas: ").append(Cotufa.getVentasGrandes()); resumen.append("\nCotufas medianas vendidas: ").append(Cotufa.getVentasMedianas()); resumen.append("\nTequeños vendidos: ").append(Tequeño.getVentas()); System.out.println(resumen.toString()); System.out.println(Estadisticas.resumen()); System.out.println("Hasta luego!"); } public static boolean esFibonacci(int num) { if (num == 0 || num == 1) return true; int fibo1 = 0, fibo2 = 1, fibon = 1; while (fibon < num) { fibon = fibo1 + fibo2; fibo2 = fibo1; fibo1 = fibon; } return fibon == num; } public static boolean esPrimo(int n) { for (int i = 2; i < n/2; i++) if ( i % 2 == 0 ) return false; return true; } }
Markdown
UTF-8
13,192
3.25
3
[]
no_license
**Udacity Self-driving Car NanoDegree Project2** -- **Traffic Sign Recognition** --- ## **Introduction** In this project, a deep convolutional neural network is implemented using Python under TensorFlow framework to classify traffic signs. Deep learning techniques and computer vision methods are employed to do the data pre-precosssing and augmentation. A CNN model is constructed and trained to classify traffic sign images using the German Traffic Sign Dataset. The model performance is evaluated on hold-out test sets as well as new images found separately online. --- ## **Methodology and data pipeline** The goals / steps of this project are the following: * Load the data set (see below for links to the project data set) * Split the data set into Training/Validation/Testing sub-datasets * Explore, summarize and visualize the data set * Pre-process the Data set (normalization, grayscale, etc.) * Data augmentation using random shift and perspective transformation * Design, train and test a CNN model architecture * Use the model to make predictions on new images * Analyze the softmax probabilities of the new images * Summarize the results with a written report [//]: # (Image References) [image1]: ./writeup_images/visualization.png "Visualization" [image2]: ./writeup_images/color.png "Original Color" [image3]: ./writeup_images/after-pre-proccessing.png "Random Noise" [image4]: ./writeup_images/new_traffic_signs.png "Traffic Sign 1" [image5]: ./writeup_images/new_image_predictions.png "Traffic Sign 2" [image6]: ./writeup_images/new_image_probabilities.png "Traffic Sign 3" [image7]: ./writeup_images/new4.png "Traffic Sign 4" [image8]: ./writeup_images/new5.png "Traffic Sign 5" [image9]: ./writeup_images/new6.png "Traffic Sign 6" [image10]: ./writeup_images/new7.png "Traffic Sign 7" [image11]: ./writeup_images/new8.png "Traffic Sign 8" [image12]: ./writeup_images/new9.png "Traffic Sign 9" [image13]: ./writeup_images/new10.png "Traffic Sign 10" ## **Rubric Points** Here I will consider the [rubric points](https://review.udacity.com/#!/rubrics/481/view) individually and describe how I addressed each point in my implementation. --- **Writeup / README** This is the Writeup / README that includes all the rubric points and how each one is addressed. The submission includes the project code. Please find the source code of the project using the following link [project code](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/Traffic_Sign_Classifier.ipynb) **Data Set Summary and Exploration** ####1. Provide a basic summary of the data set. In the code, the analysis should be done using python, numpy and/or pandas methods rather than hardcoding results manually. I used the pandas library to calculate summary statistics of the traffic signs data set: * The size of training set is 34799 * The size of the validation set is 4410 * The size of test set is 12630 * The shape of a traffic sign image is 32x32 after resizing * The number of unique classes/labels in the data set is 43 ####2. Include an exploratory visualization of the dataset. Here is an exploratory visualization of the data set. It is a bar chart showing how the data ![alt text][image1] **Data Pre-processing and augmentation** ####1. Describe how you preprocessed the image data. What techniques were chosen and why did you choose these techniques? Consider including images showing the output of each preprocessing technique. Pre-processing refers to techniques such as converting to grayscale, normalization, etc. (OPTIONAL: As described in the "Stand Out Suggestions" part of the rubric, if you generated additional data for training, describe why you decided to generate additional data, how you generated the data, and provide example images of the additional data. Then describe the characteristics of the augmented training set like number of images in the set, number of images for each class, etc.) Here are examples of a traffic sign image before any preprocessing. ![alt text][image2] As a first step, I decided to convert the images to grayscale because grayscale suppresses some random noise in the color image also is only single channel image, which reduces the size/dimension of the input images. Also, I normalized the image data because normalization bring all the input images into the same scale and this allows the downstream models to work on the data that shares the same range of value, allowing a more stable and meaningful numerical calculations. Lastly, also did a exposure equalization to enhance the contrast of the images before it will highlights the details of the grayscale images. The results are these preprocessing steps are shown below. Additional data are generated during the data augmentation step. The reasons are twofold. First, there are data imbalance in the input images. Certain types of traffic signs are significantly less than some dominating types. If we train the classifier directly with the raw data set, it may be biased towards the classes that have more data. Secondly, by generating more randomly shifted/modified images the neural network gets to see more data and is suppose to generalize better. To add more data to the data set, I used the following techniques. Image Warping (Affine transformation) perspective transformation Random Shift OpenCV and numpy/scipy are used to implement the above procedures. Images after augmentation are presented below ![alt text][image3] Date set after augmentation: * The size of training set is increased from 34799 to 68274 * The size of the validation set is increased from 4410 to 17069 * The size of test set is kept the same as 12630 * The shape of a traffic sign image is still 32x32 * The number of unique classes/labels in the data set is still 43 **Design and Test a Model Architecture** ####2. Describe what your final model architecture looks like including model type, layers, layer sizes, connectivity, etc.) Consider including a diagram and/or table describing the final model. My final model consisted of the following layers: | Layer | Description | |:---------------------:|:---------------------------------------------:| | Input | 32x32x1 grayscale image | | Layer 1 Convolution 5x5 | shape=(5,5,1,6), 1x1 stride, valid padding, outputs 28x28x6 | | RELU | | | Max pooling | 2x2 stride, outputs 14x14x6 | | Layer 2 Convolution 5x5 | shape=(5,5,6,16), 1x1 stride, outputs 10x10x16 | | RELU | | | Max pooling | 2x2 stride, outputs 5x5x16 | | Flatten | Input 5x5x16=400, outputs 120 | | Layer 3 Fully connected | Input = 400, Output = 120 | | RELU | | | Layer 4 Fully connected | Input = 120, Output = 84 | | RELU | | | Layer 5 Fully connected | Input = 84, Output = 43 | | Softmax | Outputs probabilities | ####3. Describe how you trained your model. The discussion can include the type of optimizer, the batch size, number of epochs and any hyperparameters such as learning rate. To train the model, I used * batch size of 64 * number of training epochs is set to 50 * the learning rate is 0.0005 * The neural network weights are randomly generated from a normal distribution with a mean of 0 and sigma of 0.1. ####4. Describe the approach taken for finding a solution and getting the validation set accuracy to be at least 0.93. Include in the discussion the results on the training, validation and test sets and where in the code these were calculated. Your approach may have been an iterative process, in which case, outline the steps you took to get to the final solution and why you chose those steps. Perhaps your solution involved an already well known implementation or architecture. In this case, discuss why you think the architecture is suitable for the current problem. My final model results were: * training set accuracy of 0.997 * validation set accuracy of 0.991 * test set accuracy of 0.946 If an iterative approach was chosen: * What was the first architecture that was tried and why was it chosen? The LeNet architecture is chosen as the starting point since it have been proofed working well with traffic sign recognition problems in the literatures. * What were some problems with the initial architecture? It is giving a decent accuracy around 89%. I modified it into the implementation as shown in previous table, with 2 convolution layers and 3 fully connected layers. * How was the architecture adjusted and why was it adjusted? Typical adjustments could include choosing a different model architecture, adding or taking away layers (pooling, dropout, convolution, etc), using an activation function or changing the activation function. One common justification for adjusting an architecture would be due to overfitting or underfitting. A high accuracy on the training set but low accuracy on the validation set indicates over fitting; a low accuracy on both sets indicates under fitting. The architecture is almost kept the same. Only dimensions of the inputs and outputs are modified accordingly to accommodate the size of the input images (32x32). * Which parameters were tuned? How were they adjusted and why? Batch size, epochs, leaning rate are all tuned to improve the performance. The final values are presented in above paragraphs. I found out that using a relatively small batch size (64) and learning rate (0.0005) help improve the validation accuracy. Also larger number of epochs helps the model to settle to the optimal state. * What are some of the important design choices and why were they chosen? For example, why might a convolution layer work well with this problem? How might a dropout layer help with creating a successful model? Convolution layer work works well because the traffic sign images are translational invariant. As long as we find the signs in the image it can be recognized. Important design choices that affect the final accuracy most is the data pre-precosssing and augmentation. Since it normalizes the images, reduces the noise and class imbalance. These are the key factors that boosts the final validation accuracy to beyond 99%. **Test a Model on New Images** ####1. Choose five German traffic signs found on the web and provide them in the report. For each image, discuss what quality or qualities might be difficult to classify. Here are German traffic signs that I found on the web: ![alt text][image4] The last two images might be difficult to classify because they are not part of the original training data set. ####2. Discuss the model's predictions on these new traffic signs and compare the results to predicting on the test set. At a minimum, discuss what the predictions were, the accuracy on these new predictions, and compare the accuracy to the accuracy on the test set (OPTIONAL: Discuss the results in more detail as described in the "Stand Out Suggestions" part of the rubric). Here are the results of the prediction: ![alt text][image5] "Bumpy road", "General caution" and "Speed limit (60km/h)" are classified corectly. While the others are not. There are quite few possible reasons for this degraded performance compared to the results on the validation and testing data sets (99% and 94%). 1. The newly download images come in different sizes, a downsampling is performed to resize the images to 32 x 32. The OpenCV resize function is used to do the downsampling, which generates aliasing. This could affect the correctness of the model since at a low resolution, aliasing could present noisy features that distracts the model. 2. A Gaussian blurring and sharpening operaiton is carried out and the results shows improvements 3. Moreover, the model could be biased or overfitted to the training examples. When presented with these new traffic images (especially the two complete new ones, which are unseen before), the model could not find the correct labels. 4. Adding dropouts could reduce the overfitting and possibly increase the accuracy here. ####3. Describe how certain the model is when predicting on each of the five new images by looking at the softmax probabilities for each prediction. Provide the top 5 softmax probabilities for each image along with the sign type of each probability. (OPTIONAL: as described in the "Stand Out Suggestions" part of the rubric, visualizations can also be provided such as bar charts) The code for making predictions on my final model is located in second last cell of the Ipython notebook. ![alt text][image6] Again the degraded results suggests that the model could be overfitted, adding dropout layers to CNN and also introducing regularization could alleviates the overfitting and provides better performance here. This is reserved from future studies. ### (Optional) Visualizing the Neural Network (See Step 4 of the Ipython notebook for more details) ####1. Discuss the visual output of your trained network's feature maps. What characteristics did the neural network use to make classifications?
Python
UTF-8
802
3.234375
3
[]
no_license
def memoize(hash_func = lambda args : args): def memoize_wrap(f): mem = {} def memorized(*args): hash_value = hash_func(*args) if hash_value not in mem: # Note args are wrapped as a tuple not list, so it is hashable mem[hash_value] = f(*args) return mem[hash_value] return memorized return memoize_wrap def timer(f): def timed(*args, **kwargs): import time start = time.time() ret = f(*args, **kwargs) end = time.time() print("running time (in secs): " + str(end - start)) return ret return timed class Pipe(object): def __init__(self, func): self.func = func def __ror__(self, other): def generator(): for obj in other: if obj is not None: yield self.func(obj) return generator()
C#
UTF-8
1,124
2.625
3
[]
no_license
using SDL2; public class EndScreen : IScreen { public ScreenType NextScreen { get; set; } private static Image background; private Font font; private Text text; static EndScreen() { background = new Image (Game.LanguageTranslation[Game.GameLanguage + "EndPath"], 800, 600); } public EndScreen() { NextScreen = ScreenType.None; font = new Font(@"resources\fonts\RWFont.ttf", 16); text = new Text(font, Game.EndMessage, 0xFF, 0xFF, 0xFF); } public ScreenType Run() { Hardware.ClearScreen(); Hardware.RenderBackground(background); text.Render(Hardware.ScreenWidth / 2 - text.Width / 2, Hardware.ScreenHeight / 2 - text.Height / 2); Hardware.UpdateScreen(); do { SDL.SDL_Keycode key = Hardware.KeyPressed(); if (key == SDL.SDL_Keycode.SDLK_RETURN) NextScreen = ScreenType.Main; System.Threading.Thread.Sleep(16); } while (NextScreen == ScreenType.None); return NextScreen; } }
Python
UTF-8
511
2.625
3
[]
no_license
#!/usr/bin/env python import sys sys.path.append("../lib/"); sys.path.append("../swig/"); import PyMesh def main(): print("Start!"); filename = "holey.obj" mesh = PyMesh.MeshFactory.create_mesh(filename); vertices = mesh.get_vertices(); faces = mesh.get_faces(); voxels = mesh.get_voxels(); print("# vertices: {}".format(len(vertices)/3)); print("# faces : {}".format(len(faces)/3)); print("# voxels : {}".format(len(voxels)/4)); if __name__ == "__main__": main();
Java
UTF-8
1,521
2.671875
3
[ "Apache-2.0" ]
permissive
package neuralnet.output; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import neuralnet.lossfunctions.LossFunction; import neuralnet.transferfunctions.TransferFunction; import org.jblas.DoubleMatrix; public class ProbabilisticBinaryOutputLayer extends SingleValueOutputLayer implements Externalizable { protected int inputDimension; protected double cachedOutput; public ProbabilisticBinaryOutputLayer(int numInputs, TransferFunction transferFunction, LossFunction lossFunction) { super(numInputs, transferFunction, lossFunction); this.cachedOutput = Double.NaN; } public final double output(DoubleMatrix input) { this.inputDimension = input.length; this.cachedOutput = this.transfer.forward(input).get(0); return this.cachedOutput; } public DoubleMatrix calculateGradientOfLossFunction(double target) { double delta = this.loss.getLoss(cachedOutput, target); DoubleMatrix grad = new DoubleMatrix(this.inputDimension, 1); Arrays.fill(grad.data, delta); return this.transfer.backward(grad); } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeInt(this.inputDimension); out.writeDouble(this.cachedOutput); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); this.inputDimension = in.readInt(); this.cachedOutput = in.readDouble(); } }
PHP
UTF-8
2,264
2.53125
3
[ "MIT" ]
permissive
<?php namespace Omnipay\Pagarme\Message; use Omnipay\Tests\TestCase; class FetchTransactionRequestTest extends TestCase { public function setUp() { $this->request = new FetchTransactionRequest($this->getHttpClient(), $this->getHttpRequest()); $this->request->initialize( array( 'transactionReference' => 123456, ) ); } public function testGetData() { $data = $this->request->getData(); $this->assertSame(array(), $data); } public function testGetQuery() { $data = $this->request->getQuery(); $this->assertArrayHasKey('api_key', $data); } /** * @expectedException \Omnipay\Common\Exception\InvalidRequestException * @expectedExceptionMessage The transactionReference parameter is required */ public function testAmountRequired() { $this->request->setTransactionReference(null); $this->request->getQuery(); } public function testGetHttpMethod() { $this->assertSame('GET', $this->request->getHttpMethod()); } public function testSendSuccess() { $this->setMockHttpResponse('FetchTransactionSuccess.txt'); $response = $this->request->send(); $transactionArray = $response->getData(); $this->assertTrue($response->isSuccessful()); $this->assertFalse($response->isRedirect()); $this->assertSame('transaction', $transactionArray['object'] ); $this->assertSame('paid', $transactionArray['status'] ); $this->assertSame(1537, $transactionArray['amount']); $this->assertNull($response->getMessage()); } public function testSendFailure() { $this->setMockHttpResponse('FetchTransactionFailure.txt'); $response = $this->request->send(); $this->assertFalse($response->isSuccessful()); $this->assertFalse($response->isRedirect()); $this->assertSame('Transaction não encontrado', $response->getMessage()); } public function testEndpoint() { $this->assertSame('https://api.pagar.me/1/transactions/123456', $this->request->getEndpoint()); } }
PHP
UTF-8
2,856
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Vendor; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Models\User; use App\Models\VendorDetail; class RegisterController extends Controller { public function index() { return view('vendor.register'); } public function store(Request $request) { $validated = $request->validate([ 'first_name' => 'required|max:255', 'last_name' => 'required|max:255', 'email' => 'required|unique:users|max:255', 'password' => 'required|confirmed', 'store_address' => 'required|max:255', 'store_description' => 'required', 'contact_number' => 'required', 'profile_picture' => 'required', 'banner_picture' => 'required', 'phone_number' => 'required|regex:/[0-9]{9}/' ]); try { $destinationPath = 'uploads'; //Profile $profile = $request->file('profile_picture'); $profile_name = $profile->getClientOriginalName(); $profile_new_name = time().'.'.$profile->extension(); $profile->move($destinationPath.'/profile',$profile_new_name); //Banner $banner = $request->file('banner_picture'); $file_name = $banner->getClientOriginalName(); $file_new_name = time().'.'.$banner->extension(); $banner->move($destinationPath.'/banner',$file_new_name); $user_name = $request->first_name .' '.$request->last_name; $user = User::create([ 'username' => $user_name, 'first_name' =>$request->first_name, 'last_name' => $request->last_name, 'email' => $request->email, 'password' => Hash::make($request->password), 'role_id' => 2, 'address' => $request->store_address, ]); $VendorDetail = new VendorDetail(); $VendorDetail->user_id = $user->id; $VendorDetail->store_description = $request->store_description; $VendorDetail->contact_number = $request->contact_number; $VendorDetail->profile_picture_name = $profile_name; $VendorDetail->profile_picture_path = $profile_new_name; $VendorDetail->banner_picture_name = $file_name; $VendorDetail->banner_picture_path = $file_new_name; $VendorDetail->phone_number = $file_new_name; $VendorDetail->save(); return redirect()->back()->with('success', 'vendor registerd successfully'); } catch (\Throwable $th) { return redirect()->back()->with('error','Vendorr not registerd'); } } }