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
Java
UTF-8
2,535
3.6875
4
[]
no_license
package level3; import java.math.BigInteger; public class Answer2 { public static BigInteger gen = new BigInteger("0"); public static BigInteger f; public static BigInteger m; public static final String IMP = "impossible"; public static String answer(String M, String F) {//compareTo -1 is less, 0 is equal, 1 is we're greater m = new BigInteger(M); f = new BigInteger(F); System.out.println(f + " " + m); while(f.compareTo(BigInteger.ONE) == 1 || m.compareTo(BigInteger.ONE) == 1) { //F > 1 || M > 1 if((f.mod(m).equals(BigInteger.ZERO) || m.mod(f).equals(BigInteger.ZERO)) && //if f%m == 0 (even divide) && f != 1 && m != 1 (!f.equals(BigInteger.ONE) && !m.equals(BigInteger.ONE))) return IMP; if((f.compareTo(m) == 1 && m.equals(BigInteger.ONE)) || (m.compareTo(f) == 1 && f.equals(BigInteger.ONE))) { if(f.compareTo(m) == 1) { f.subtract(BigInteger.ONE); System.out.println("1"); return gen.add(f.subtract(BigInteger.ONE)).toString(); } else { m.subtract(BigInteger.ONE); System.out.println("2"); return gen.add(m.subtract(BigInteger.ONE)).toString(); } } if(f.add(BigInteger.ONE).equals(m)) { return gen.add(f).toString(); } else if(m.add(BigInteger.ONE).equals(f)) { return gen.add(m).toString(); } if(f.compareTo(m) == 1) { //If f > m System.out.print(f + "F " + m + "F " + gen + "G "); BigInteger temp = new BigInteger(f.toString()); f = f.mod(m); gen.add(temp.divide(m)); gen = gen.add(temp.divide(m)); System.out.println(f + "F " + m + "F " + gen + "G "); } if(m.compareTo(f) == 1) { //If m > f System.out.print(f + "F " + m + "F " + gen + "G "); BigInteger temp = new BigInteger(m.toString()); m = m.mod(f); //Get remainder, which is new number gen = gen.add(temp.divide(f)); //Increment gen by times it went in evenly System.out.println(f + "F " + m + "F " + gen + "G "); } } return gen.toString(); } public static String power(int a, int b) { BigInteger temp = new BigInteger(Integer.toString(a)); temp = temp.pow(b); return temp.toString(); } public static String power2(int a, int b) { BigInteger temp = new BigInteger(Integer.toString(a)); temp = temp.pow(b); temp = temp.subtract(BigInteger.ONE); return temp.toString(); } public static void main(String[] args) { System.out.println(answer("2", "3")); } }
Python
UTF-8
1,171
3.4375
3
[ "BlueOak-1.0.0" ]
permissive
class Object: """Represents a generic object. Supported Operations: +-----------+--------------------------------------+ | Operation | Description | +===========+======================================+ | x == y | Checks if two objects are equal. | +-----------+--------------------------------------+ | x != y | Checks if two objects are not equal. | +-----------+--------------------------------------+ | hash(x) | Returns the object's hash. | +-----------+--------------------------------------+ | str(x) | Returns the object's name. | +-----------+--------------------------------------+ Used to make most objects within the library Attributes ---------- id : str The ID of the object """ __slots__ = [ 'id' ] def __init__(self, **kwargs): self.id = kwargs.pop('id') def __eq__(self, other): return isinstance(other, self.__class__) and other.id == self.id def __ne__(self, other): if isinstance(other, self.__class__): return other.id != self.id return True def __hash__(self): return hash(self.id) def __str__(self): return self.name
PHP
UTF-8
1,835
3.015625
3
[ "MIT" ]
permissive
<?php use WP_CLI\Utils; class EvalFile_Command extends WP_CLI_Command { /** * Regular expression pattern to match the shell shebang. * * @var string */ const SHEBANG_PATTERN = '/^(#!.*)$/m'; /** * Loads and executes a PHP file. * * Note: because code is executed within a method, global variables need * to be explicitly globalized. * * ## OPTIONS * * <file> * : The path to the PHP file to execute. Use '-' to run code from STDIN. * * [<arg>...] * : One or more arguments to pass to the file. They are placed in the $args variable. * * [--skip-wordpress] * : Load and execute file without loading WordPress. * * @when before_wp_load * * ## EXAMPLES * * wp eval-file my-code.php value1 value2 */ public function __invoke( $args, $assoc_args ) { $file = array_shift( $args ); if ( '-' !== $file && ! file_exists( $file ) ) { WP_CLI::error( "'$file' does not exist." ); } if ( null === Utils\get_flag_value( $assoc_args, 'skip-wordpress' ) ) { WP_CLI::get_runner()->load_wordpress(); } self::execute_eval( $file, $args ); } /** * Evaluate a provided file. * * @param string $file Filepath to execute, or - for STDIN. * @param mixed $args Array of positional arguments to pass to the file. */ private static function execute_eval( $file, $args ) { if ( '-' === $file ) { eval( '?>' . file_get_contents( 'php://stdin' ) ); } else { $file_contents = file_get_contents( $file ); // Adjust for __FILE__ and __DIR__ magic constants. $file_contents = Utils\replace_path_consts( $file_contents, $file ); // Check for and remove she-bang. if ( 0 === strncmp( $file_contents, '#!', 2 ) ) { $file_contents = preg_replace( static::SHEBANG_PATTERN, '', $file_contents ); } eval( '?>' . $file_contents ); } } }
Python
UTF-8
2,351
2.78125
3
[ "MIT" ]
permissive
import sys from pytaxize import col class Ids(object): ''' ids: A class for taxonomic identifiers Usage:: import pytaxize res = pytaxize.Ids('Poa annua', db='col') res.get_colid() ''' def __init__(self, name, db): # super(ids, self).__init__() self.db = db self.name = name def __repr__(self): return """<%s %s:%s>""" % (type(self).__name__, self.db, self.name) # def get_colid(sciname=self.sciname, ask = True, verbose = True): def get_colid(self, ask = True, verbose = True): ''' pytaxize.get_colid(sciname=['Poa annua']) ''' sciname = self.name def fun(sciname, ask, verbose): sciname = [sciname] df = col.col_search(name=sciname) if(df[0].shape[0] == 0): sys.exit("Retrieving data for taxon '" + sciname + "'") id = 'none' else: df = df[0][['id','name','rank','name_status']] df.columns = ['colid', 'name', 'rank', 'name_status'] id = df['colid'].values.tolist() # not found on col if(len(id) == 0): sys.exit("Not found. Consider checking the spelling or alternate classification") id = 'none' # more than one found on col -> user input if(len(id) > 1): if(ask==True): print("\nMore than one eolid found for taxon '" + sciname[0] + "'\n") print(df) take = input("\n Enter rownumber of taxon:\n\n") if(len(str(take)) == 0): take = 'notake' else: pass if(int(take) in range(df.shape[0])): take = int(take) print("Input accepted, took eolid '" + df['colid'][take] + "'.\n") id = int(df['colid'][take]) else: id = 'none' print("\nReturned 'none'!\n\n") else: id = 'none' return id sciname = converter(sciname) out = [] for i in range(len(sciname)): out.append(fun(sciname[i], ask, verbose)) return out def getcolurl(self): return self.name + 'Boo' def converter(x): if(x.__class__.__name__ == 'str'): return [x] else: return x
Markdown
UTF-8
1,232
2.9375
3
[]
no_license
--- title: 'Healthcare.gov & the Scalability Problem' author: Will type: post date: 2013-11-21T05:13:32+00:00 url: /2013/healthcare-gov-the-scalability-problem/ categories: - Uncategorized --- [Scalability problems][1] plague the creation of large web sites. This is especially poignant, given the Healthcare.gov web site fiasco: <p style="padding-left: 30px;"> Large systems, too complex for individual comprehension, must be subdivided into smaller tasks coordinated between groups. In fact, a large portion of software engineering is devoted to the documentation, notification, and management review needed to coordinate large projects. </p> Thus, it is [not uncommon][2] for large IT projects like this to have overrun costs or fail: <p style="padding-left: 30px;"> <a href="http://www.infoworld.com/t/business/it-myth-5-most-it-projects-fail-008">One study</a> shows that 34 percent of projects are unqualified successes, 15 percent are complete failures which were abandoned before completion, and the remaining 51 percent, like healthcare.gov, fall somewhere in between. </p> [1]: http://www.engr.sjsu.edu/fayad/column/CACM/ACMPub/px-scale.pdf [2]: http://www.informit.com/articles/article.aspx?p=2153660
Java
UTF-8
8,559
2.125
2
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LGPL-3.0-only", "LGPL-2.1-only" ]
permissive
/* Copyright 2018 Samsung SDS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.samsungsds.analyst.code.main; import com.samsungsds.analyst.code.api.ProgressEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.concurrent.atomic.AtomicBoolean; public class SonarProgressEventChecker implements Runnable { private static final Logger LOGGER = LogManager.getLogger(SonarProgressEventChecker.class); private final static int DEFAULT_INTERVAL_MILLISECOND = 7_000; private final static double DEFAULT_INCREASE_RATE = 1.1; private Thread worker; private AtomicBoolean running = new AtomicBoolean(false); private AtomicBoolean stopped = new AtomicBoolean(true); private ObserverManager observerManager; private int intervalMillisecond = DEFAULT_INTERVAL_MILLISECOND; private double increaseRate = DEFAULT_INCREASE_RATE; private AtomicBoolean codeSizeCompleted = new AtomicBoolean(false); private AtomicBoolean duplicationCompleted = new AtomicBoolean(false); private AtomicBoolean sonarJavaCompleted = new AtomicBoolean(false); private AtomicBoolean javascriptCompleted = new AtomicBoolean(false); private AtomicBoolean cssCompleted = new AtomicBoolean(false); private AtomicBoolean htmlCompleted = new AtomicBoolean(false); private AtomicBoolean sonarCSharpCompleted = new AtomicBoolean(false); private AtomicBoolean sonarPythonCompleted = new AtomicBoolean(false); public SonarProgressEventChecker(IndividualMode mode, ObserverManager observerManager, int targetFiles) { this(mode, observerManager); this.intervalMillisecond = (int)(DEFAULT_INTERVAL_MILLISECOND * (targetFiles / 100.0)); if (targetFiles > 1_000) { increaseRate = 1.2; } } public SonarProgressEventChecker(IndividualMode mode, ObserverManager observerManager) { this.observerManager = observerManager; if (!mode.isCodeSize()) { codeSizeCompleted.set(true); } if (!mode.isDuplication()) { duplicationCompleted.set(true); } if (!mode.isSonarJava()) { sonarJavaCompleted.set(true); } if (!mode.isJavascript()) { javascriptCompleted.set(true); } if (!mode.isCss()) { cssCompleted.set(true); } if (!mode.isHtml()) { htmlCompleted.set(true); } if (!mode.isSonarCSharp()) { sonarCSharpCompleted.set(true); } if (!mode.isSonarPython()) { sonarPythonCompleted.set(true); } LOGGER.debug("Sonar Progress Event Start ... (interval : {}ms)", intervalMillisecond); } public void start() { LOGGER.debug("Sonar Progress Event Thread starting..."); worker = new Thread(this); worker.start(); } public void stop() { LOGGER.debug("Sonar Process Event Thread stopping..."); interrupt(); synchronized(codeSizeCompleted) { if (!codeSizeCompleted.get()) { codeSizeCompleted.set(true); observerManager.notifyObservers(ProgressEvent.CODE_SIZE_COMPLETE); } } synchronized(duplicationCompleted) { if (!duplicationCompleted.get()) { duplicationCompleted.set(true); observerManager.notifyObservers(ProgressEvent.DUPLICATION_COMPLETE); } } synchronized(sonarJavaCompleted) { if (!sonarJavaCompleted.get()) { sonarJavaCompleted.set(true); observerManager.notifyObservers(ProgressEvent.SONARJAVA_COMPLETE); } } synchronized(javascriptCompleted) { if (!javascriptCompleted.get()) { javascriptCompleted.set(true); observerManager.notifyObservers(ProgressEvent.JAVASCRIPT_COMPLETE); } } synchronized(cssCompleted) { if (!cssCompleted.get()) { cssCompleted.set(true); observerManager.notifyObservers(ProgressEvent.CSS_COMPLETE); } } synchronized(htmlCompleted) { if (!htmlCompleted.get()) { htmlCompleted.set(true); observerManager.notifyObservers(ProgressEvent.HTML_COMPLETE); } } synchronized(sonarCSharpCompleted) { if (!sonarCSharpCompleted.get()) { sonarCSharpCompleted.set(true); observerManager.notifyObservers(ProgressEvent.SONARCSHARP_COMPLETE); } } synchronized(sonarPythonCompleted) { if (!sonarPythonCompleted.get()) { sonarPythonCompleted.set(true); observerManager.notifyObservers(ProgressEvent.SONARPYTHON_COMPLETE); } } } private void interrupt() { running.set(false); worker.interrupt(); } boolean isRunning() { return running.get(); } boolean isStopped() { return stopped.get(); } @Override public void run() { running.set(true); stopped.set(false); while (running.get()) { try { Thread.sleep(intervalMillisecond); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOGGER.debug("Thread was interrupted..."); } LOGGER.debug("Thread Process Event : {}, {}, {}, {}, {}, {}, {}, {}", codeSizeCompleted, duplicationCompleted, sonarJavaCompleted, javascriptCompleted, cssCompleted, htmlCompleted, sonarCSharpCompleted, sonarPythonCompleted); intervalMillisecond *= increaseRate; processEvent(); } stopped.set(true); } private void processEvent() { synchronized(codeSizeCompleted) { if (!codeSizeCompleted.get()) { codeSizeCompleted.set(true); observerManager.notifyObservers(ProgressEvent.CODE_SIZE_COMPLETE); return; } } synchronized(duplicationCompleted) { if (!duplicationCompleted.get()) { duplicationCompleted.set(true); observerManager.notifyObservers(ProgressEvent.DUPLICATION_COMPLETE); return; } } synchronized(sonarJavaCompleted) { if (!sonarJavaCompleted.get()) { sonarJavaCompleted.set(true); observerManager.notifyObservers(ProgressEvent.SONARJAVA_COMPLETE); return; } } synchronized(javascriptCompleted) { if (!javascriptCompleted.get()) { javascriptCompleted.set(true); observerManager.notifyObservers(ProgressEvent.JAVASCRIPT_COMPLETE); return; } } synchronized(cssCompleted) { if (!cssCompleted.get()) { cssCompleted.set(true); observerManager.notifyObservers(ProgressEvent.CSS_COMPLETE); return; } } synchronized(htmlCompleted) { if (!htmlCompleted.get()) { htmlCompleted.set(true); observerManager.notifyObservers(ProgressEvent.HTML_COMPLETE); return; } } synchronized(sonarCSharpCompleted) { if (!sonarCSharpCompleted.get()) { sonarCSharpCompleted.set(true); observerManager.notifyObservers(ProgressEvent.SONARCSHARP_COMPLETE); return; } } synchronized(sonarPythonCompleted) { if (!sonarPythonCompleted.get()) { sonarPythonCompleted.set(true); observerManager.notifyObservers(ProgressEvent.SONARPYTHON_COMPLETE); return; } } } }
JavaScript
UTF-8
2,565
2.578125
3
[]
no_license
'use strict' const questions = require('../models/index').questions; function register (req, h) { // Si el usuario ya está logeado por lo tanto ya está registrado // No podrá acceder a la página de register y cuando lo intente lo mandaremos a '/' if (req.state.user) { return h.redirect('/'); } // Devuelvo un objeto de respuesta return h.view('register', { title: 'Regsitro', user: req.state.user }); } function login (req, h) { // console.log(req.state); if (req.state.user) { return h.redirect('/'); } // Devuelvo un objeto de respuesta return h.view('login', { title: 'Ingrese', user: req.state.user }); } async function viewQuestion(req, h) { let data; try { // Recojo los datos que me vienen de la ruta data = await questions.getOne(req.params.id); if (!data) { return notFound(req, h); } } catch(error) { console.error(error); } return h.view('question', { title: 'Detalles de la pregunta', user: req.state.user, question: data, key: req.params.id }); } function notFound(req, h) { return h.view('404', {}, {layout: 'error-layout'}).code(404); } // Esta función se ejecuta antes de dar una respuesta // Me perimite capturar los errores de tipo 404 que no caputra notFound // Por ejemplo :3000/assets/algo // Por ejemplo :3000/assets function fileNotFound(req, h) { const response = req.response; // Esto es para que no me muestre la vista de 404 cuando no encuentre un id // Esto es más amigable para el desarrollador if (!req.path.startsWith('/api') && response.isBoom && (response.output.statusCode === 404 || response.output.statusCode === 403)) { return h.view('404', {}, {layout: 'error-layout'}).code(404); } // Continuamos el life cycle return h.continue; } async function home(req, h) { const data = await req.server.methods.getLast(10); // Devuelvo un objeto de respuesta return h.view('index', { title: 'home', user: req.state.user, questions: data }); } function homes(req, h) { return h.redirect('/home'); } function ask(req, h) { // Si no está logeado el usuario no puede hacer preguntas if (!req.state.user) { return h.redirect('/login'); } return h.view('ask', { title: 'Crear pregunta', user: req.state.user }); } module.exports = { register: register, home: home, homes: homes, login: login, notFound:notFound, fileNotFound: fileNotFound, ask: ask, viewQuestion: viewQuestion }
Python
UTF-8
1,273
3.921875
4
[]
no_license
""" https://www.youtube.com/watch?v=XZ2G29ZUaII&index=27&list=PL6lxxT7IdTxGoHfouzEK-dFcwr_QClME_ Produce a GUI using python an tkinter thas has three buttons and a label. Arrange for the clicking of a button to set the background colour of the label to red, gren and blue i.e. clicking one button changes the bakcground of the label to red, clicking the second button changes it to green and clicking the third button changes it to blue. Whe the program furst runs have the background of the label set at white. Have nothing displayed in the label and have the text of the buttons display Red, Gren an Blue respectively. """ from tkinter import * def set_red(): label_1['bg']='red' def set_green(): label_1['bg']='green' def set_blue(): label_1['bg']='blue' my_window = Tk() label_1 = Label(my_window, width='20', height='3', background='white') button_red = Button(my_window, text='Red', width=6, command=set_red) button_green = Button(my_window, text='Green', width=6, command=set_green) button_blue = Button(my_window, text='Blue', width=6, command=set_blue) label_1.grid(row=0, column=1) button_red.grid(row=1, column=0) button_green.grid(row=1, column=1) button_blue.grid(row=1, column=2) my_window.mainloop()
Java
UTF-8
264
1.570313
2
[]
no_license
package com.wntime.customer.repo; import com.wntime.customer.region.BusDriveStationInfo; import org.springframework.data.gemfire.repository.GemfireRepository; public interface BusDriveStationInfoRepository extends GemfireRepository<BusDriveStationInfo,Long> { }
Java
UTF-8
447
2.71875
3
[]
no_license
package duke.exception; public class InvalidDeadlineException extends InvalidTaskException { private static final String ERROR_MESSAGE = "Please input the correct details for the deadline task.\n" + "deadline *description* /by *yyyy-mm-dd* *HH:mm*"; /** * Signals that the deadline task provided by the user is formatted incorrectly. */ public InvalidDeadlineException() { super(ERROR_MESSAGE); } }
SQL
UTF-8
5,014
3.234375
3
[ "Apache-2.0" ]
permissive
-- Generated by Oracle SQL Developer Data Modeler 19.2.0.182.1216 -- at: 2020-09-12 14:34:27 BDT -- site: Oracle Database 12c -- type: Oracle Database 12c DROP TABLE jersey CASCADE CONSTRAINTS; DROP TABLE points_and_time CASCADE CONSTRAINTS; DROP TABLE rider CASCADE CONSTRAINTS; DROP TABLE rider_stages CASCADE CONSTRAINTS; DROP TABLE stages CASCADE CONSTRAINTS; DROP TABLE teams CASCADE CONSTRAINTS; CREATE TABLE jersey ( jersey_colour NVARCHAR2(30) NOT NULL, rider_rider_no_ NUMBER(7) NOT NULL ); ALTER TABLE jersey ADD CONSTRAINT jersey_pk PRIMARY KEY ( jersey_colour ); CREATE TABLE points_and_time ( stage_number NUMBER(2) NOT NULL, point NUMBER(6) NOT NULL, time_hour NUMBER(2) NOT NULL, rider_rider_no_ NUMBER(7) NOT NULL, time_min NUMBER(2) NOT NULL ); CREATE UNIQUE INDEX points_and_time__idx ON points_and_time ( rider_rider_no_ ASC ); ALTER TABLE points_and_time ADD CONSTRAINT points_and_time_pk PRIMARY KEY ( stage_number, rider_rider_no_ ); CREATE TABLE rider ( rider_no_ NUMBER(7) NOT NULL, name VARCHAR2(25) NOT NULL, birth DATE NOT NULL, teams_team_name VARCHAR2(40) NOT NULL ); ALTER TABLE rider ADD CONSTRAINT rider_pk PRIMARY KEY ( rider_no_ ); CREATE TABLE rider_stages ( rider_rider_no_ NUMBER(7) NOT NULL, stages_stage_no_ VARCHAR2(10) NOT NULL ); ALTER TABLE rider_stages ADD CONSTRAINT rider_stages_pk PRIMARY KEY ( rider_rider_no_, stages_stage_no_ ); CREATE TABLE stages ( stage_no_ VARCHAR2(10) NOT NULL, Race_Date DATE NOT NULL, distance VARCHAR2(30) NOT NULL, start_to_end_place VARCHAR2(50) NOT NULL, stage_type VARCHAR2(30) NOT NULL ); ALTER TABLE stages ADD CONSTRAINT stages_pk PRIMARY KEY ( stage_no_ ); CREATE TABLE teams ( team_name VARCHAR2(40) NOT NULL, team_leader VARCHAR2(25) NOT NULL, stages_won NUMBER(5), general_ranking NUMBER(4) NOT NULL, competitors_in_race NUMBER(1) NOT NULL, final_victories NUMBER(3) NOT NULL ); ALTER TABLE teams ADD CONSTRAINT teams_pk PRIMARY KEY ( team_name ); ALTER TABLE jersey ADD CONSTRAINT jersey_rider_fk FOREIGN KEY ( rider_rider_no_ ) REFERENCES rider ( rider_no_ ); ALTER TABLE points_and_time ADD CONSTRAINT points_and_time_rider_fk FOREIGN KEY ( rider_rider_no_ ) REFERENCES rider ( rider_no_ ); ALTER TABLE rider_stages ADD CONSTRAINT rider_stages_rider_fk FOREIGN KEY ( rider_rider_no_ ) REFERENCES rider ( rider_no_ ); ALTER TABLE rider_stages ADD CONSTRAINT rider_stages_stages_fk FOREIGN KEY ( stages_stage_no_ ) REFERENCES stages ( stage_no_ ); ALTER TABLE rider ADD CONSTRAINT rider_teams_fk FOREIGN KEY ( teams_team_name ) REFERENCES teams ( team_name ); -- Oracle SQL Developer Data Modeler Summary Report: -- -- CREATE TABLE 6 -- CREATE INDEX 1 -- ALTER TABLE 11 -- CREATE VIEW 0 -- ALTER VIEW 0 -- CREATE PACKAGE 0 -- CREATE PACKAGE BODY 0 -- CREATE PROCEDURE 0 -- CREATE FUNCTION 0 -- CREATE TRIGGER 0 -- ALTER TRIGGER 0 -- CREATE COLLECTION TYPE 0 -- CREATE STRUCTURED TYPE 0 -- CREATE STRUCTURED TYPE BODY 0 -- CREATE CLUSTER 0 -- CREATE CONTEXT 0 -- CREATE DATABASE 0 -- CREATE DIMENSION 0 -- CREATE DIRECTORY 0 -- CREATE DISK GROUP 0 -- CREATE ROLE 0 -- CREATE ROLLBACK SEGMENT 0 -- CREATE SEQUENCE 0 -- CREATE MATERIALIZED VIEW 0 -- CREATE MATERIALIZED VIEW LOG 0 -- CREATE SYNONYM 0 -- CREATE TABLESPACE 0 -- CREATE USER 0 -- -- DROP TABLESPACE 0 -- DROP DATABASE 0 -- -- REDACTION POLICY 0 -- TSDP POLICY 0 -- -- ORDS DROP SCHEMA 0 -- ORDS ENABLE SCHEMA 0 -- ORDS ENABLE OBJECT 0 -- -- ERRORS 0 -- WARNINGS 0
C#
UTF-8
820
3.0625
3
[ "MIT" ]
permissive
using System; namespace Basement.Common { public class Lazy<T> { public bool isCreated { get; private set; } public Action<T> onCreate { get; set; } private T _value; private Func<T> _initFunc; public Lazy(Func<T> initFunc) { _initFunc = initFunc; } public void Create() { GetValue(); } public T GetValue() { if (isCreated) return _value; _value = _initFunc(); _initFunc = null; isCreated = true; if (onCreate != null) onCreate(_value); return _value; } public void ClearFactory() { _initFunc = null; } } }
Java
UTF-8
3,678
2.0625
2
[ "Elastic-2.0", "Apache-2.0", "SSPL-1.0", "LicenseRef-scancode-other-permissive" ]
permissive
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.benchmark.spatial; import org.elasticsearch.geometry.LinearRing; import org.elasticsearch.geometry.simplify.GeometrySimplifier; import org.elasticsearch.geometry.simplify.SimplificationErrorCalculator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; @Fork(1) @Warmup(iterations = 5) @Measurement(iterations = 5) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Thread) public class GeometrySimplificationBenchmark { @Param({ "cartesiantrianglearea", "triangleArea", "triangleheight", "heightandbackpathdistance" }) public String calculatorName; @Param({ "10", "100", "1000", "10000", "20000" }) public int maxPoints; private GeometrySimplifier<LinearRing> simplifier; private static LinearRing ring; @Setup public void setup() throws ParseException, IOException { SimplificationErrorCalculator calculator = SimplificationErrorCalculator.byName(calculatorName); this.simplifier = new GeometrySimplifier.LinearRingSimplifier(maxPoints, calculator); if (ring == null) { ring = loadRing("us.json.gz"); } } @Benchmark public void simplify(Blackhole bh) { bh.consume(simplifier.simplify(ring)); } private static LinearRing loadRing(@SuppressWarnings("SameParameterValue") String name) throws IOException, ParseException { String json = loadJsonFile(name); org.apache.lucene.geo.Polygon[] lucenePolygons = org.apache.lucene.geo.Polygon.fromGeoJSON(json); LinearRing ring = null; for (org.apache.lucene.geo.Polygon lucenePolygon : lucenePolygons) { double[] x = lucenePolygon.getPolyLons(); double[] y = lucenePolygon.getPolyLats(); if (ring == null || x.length > ring.length()) { ring = new LinearRing(x, y); } } return ring; } private static String loadJsonFile(String name) throws IOException { InputStream is = GeometrySimplificationBenchmark.class.getResourceAsStream(name); if (is == null) { throw new FileNotFoundException("classpath resource not found: " + name); } if (name.endsWith(".gz")) { is = new GZIPInputStream(is); } BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); StringBuilder builder = new StringBuilder(); reader.lines().forEach(builder::append); return builder.toString(); } }
C
UTF-8
732
3.25
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #define bool int #define false 0 #define true 1 struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; struct ListNode { int val; struct ListNode *next; }; int main() { return 0; } bool is_same(struct TreeNode* p,struct TreeNode* q); bool isSymmetric(struct TreeNode* root) { if(root == NULL) return true; return is_same(root->left, root->right); } bool is_same(struct TreeNode* p,struct TreeNode* q) { if(p == NULL && q == NULL) return true; if(p == NULL || q == NULL) return false; if(p->val == q->val) return is_same(p->left,q->right) && is_same(p->right.q->left); return false; }
Java
UTF-8
299
2.765625
3
[]
no_license
import java.util.*; public class 과자 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int k=sc.nextInt(); int n=sc.nextInt(); int m=sc.nextInt(); int ans=(n*k)-m; if(ans<=0) { System.out.println(0); }else { System.out.println(ans); } } }
C#
UTF-8
536
3.046875
3
[]
no_license
using System.ComponentModel; using System.Reflection; public class EnumReflection { public static string GetDescription(Profession val) { FieldInfo fi = val.GetType().GetField(val.ToString()); if (fi != null) { object[] profs = fi.GetCustomAttributes(typeof(DescriptionAttribute), true); if (profs != null && profs.Length > 0) { return ((DescriptionAttribute)profs[0]).Description; } } return val.ToString(); } }
C
UTF-8
1,243
3.921875
4
[]
no_license
// // Created by kevin on 2019/11/19. // #include <stdlib.h> #include <stdio.h> /** * 数组指针 (int (*p)[n] 一个指向整型数组的指针变量) * * * 指针数组 (int *p[n] 一个保存n个整型指针的数组) * []优先级高,先与p结合成为一个数组,再由int*说明这是一个整型指针数组,它有n个指针类型的数组元素。这里执行p+1时,则p指向下一个数组元素 * p=a;因为p是个不可知的表示,只存在p[0]、p[1]、p[2]...p[n-1],而且它们分别是指针变量可以用来存放变量地址。 * 但可以这样 *p=a; 这里*p表示指针数组第一个元素的值,a的首地址的值。 * * * @return */ int main() { int array[2][3] = {{1, 2, 3}, {4, 5, 6}}; int (*p)[3] = array; for (int i = 0; i < 6; i++) { printf("*p = %x\n", p++); } //求数组中的最大值 int *c; int max; /** * 将array的首地址赋给 c * * * 将c的首元素赋值给max * * c的长度不能超过array */ for (c = array[0], max = *c; c < array[0] + 6; c++) { if (*c > max) { max = *c; } } printf("max =%d\n", max); }
Markdown
UTF-8
791
3.578125
4
[]
no_license
Delete one Problem Description Given an integer array A of size N. You have to delete one element such that the GCD(Greatest common divisor) of the remaining array is maximum. Find the maximum value of GCD. Problem Constraints 2 <= N <= 105 1 <= A[i] <= 109 Input Format First argument is an integer array A. Output Format Return an integer denoting the maximum value of GCD. Example Input Input 1: A = [12, 15, 18] Input 2: A = [5, 15, 30] Example Output Output 1: 6 Output 2: 15 Example Explanation Explanation 1: If you delete 12, gcd will be 3. If you delete 15, gcd will be 6. If you delete 18, gcd will 3. Maximum vallue of gcd is 6. Explanation 2: If you delete 5, gcd will be 15. If you delete 15, gcd will be 5. If you delete 30, gcd will be 5.
C++
UTF-8
289
3.09375
3
[]
no_license
//6. Remove Vowels #include<bits/stdc++.h> using namespace std; int main(){ string s; getline(cin,s); char t; //cout<<s.find('a');//cout<<s.length()<<endl; for(int i=0 ; i<s.length() ; i++){ t=s[i]; if(t=='a'||t=='e'||t=='i'||t=='o'||t=='u') { s.erase(i,1); i--; } } cout<<s; }
Markdown
UTF-8
5,244
3
3
[ "MIT" ]
permissive
--- layout: post title: "[컴퓨터 구조] 연산(Multiplication, division, Booth),소수" excerpt: "[컴퓨터 구조] 연산(Multiplication, division, Booth),소수" date: 2019-09-24 14:00:00 categories: [computer architecture] comments: true --- # 곱셈 Multiplication - multiplicand * multiplier = product - 피승수 * 승수 = 곱 - 3 * 2 = 6 - 곱셈의 경우 숫자가 조금만 커도 오버플로우가 발생하므로 32bit 레지스터 2개를 이용하여 계산을 한다. ### 곱셈 알고리즘 ~~~ c++ product=0;  for(int i=0;i<32;i++){ if(Multiplier == 1){ product=Mulriplicand+product; }else if(Multiplier ==0){ //nothing } Multiplicand << 1; Multiplier >> 1; } return product; ~~~ # 나눗셈 Division - dividend / divisor = quorient ... remainder - 피제수 / 제수 = 몫 ... 나머지 - 7 / 3 =2 ... 1 ### 나눗셈 알고리즘 ~~~ c++ Quotient=0000; Remainder=Dividened; for(int i=0;i<33;i++){ Remainder=Remainder-Divisor; if(Remainder >= 0){ Quotient << 1; Q0 = 1; }else if(Remainder < 0){ Recover Remainder; Quotient << 1; Q0 = 0; } Divisor >> 1; } return Quotient, Remainder; ~~~ # Booth Algorightm - 2보수(음수)들 사이에 곱셈 또는 나눗셈을 할때 - https://killkimno.blog.me/70032062208 Booth 알고리즘 코드 참고 # 소수 ## 고정 소수점 - (가수)×(밑수)^(지수) 에서 **밑수와 지수값을 미리 결정**해두고 사용한다. - 소수점이 특정위치에 있다고 가정하고, 정수연산을 한 후, 특정위치에 소수점을 찍는 방식 - 정수 자료형에 대해서는 연산이 굉장히 빠름 - 부호를 제외한 나머지 비트를 절대값으로 나타냄 - 덧셈/뺄셈이 간편하다. - ex) -3.75 -> **1011.1100 (2+1+0.5+0.25)** ``` 16bit---16bit 정수부---소수부 ``` - 문제점 - 좁은 범위의 수만 나타낼 수 있다. - 소수를 표현하는 비트가 정수를 침해할 수 있다. - **정밀도가 부족**하다 ## 부동 소수점(단일 정밀도 && 복수 정밀도) - float double - (가수)×(밑수)^(지수) 에서 밑수만 고정되어 있다. - ex) 132.12234 -> **0.13212234 * 10³** ``` //단일정밀도 1bit---8bit---23bit 부호---지수Exponent---가수Fraction ``` ``` //복수정밀도,2배정밀도 1bit---11bit---52bit 부호---지수Exponent---가수Fraction ``` ### IEEE 754 전기전자기술자 협회(IEEE)에서 개발한 컴퓨터에서 부동소수점을 표현하는 가장 널리쓰이는 표준이다. #### 바이어스 Bias 소수를 정규화 할 경우 지수부가 음수가 될 수 있다. ex) 0.001 -> 0.1*10^(**-2**) 지수부에는 부호비트가 없기 때문에 음수가 들어가면 안된다. 이를 해결하기 위한 방법으로 지수부에 Bias를 더한다. 원래는 8bit 로 **-127~128**의 숫자를 표기할수 있다. 여기다가 +127을 해줌으로 써 -127을 00000000으로 표기하고 128을 11111111으로 표기하여 **0~255**의 양수만을 표기하는 방법이다. #### 예 ) -118.625(십진법)을 IEEE754(32bit)로 표현하기 - 음수이므로 부호부는 1이 된다. - 절대값을 이진법으로 나타낸다. ~~~ 1110110.101(2진법) ~~~ - 소수점을 왼쪽으로 이동시킨다. ==> 정규화된 부동소수점 수 라고 한다. ~~~ 1.110110101(2진법)*2^6 ~~~ - **가수부**는 0을 채워서 23bit로 만든다. 여기서 1.110~~~에서 맨왼쪽의 1을 제거하는데 이는 항상 1이기 때문에 삭제한다. 이를 히든비트라고 한다. ~~~ 11011 01010 00000 00000 000 ~~~ - 지수는 6이므로 bias를 더해야 한다. 32비트 IEEE754형식에서 Bias는 127이므로 6+127 =133이 되고 이진법으로 변환하면 다음과 같다. ~~~ 10000101(2진법) ~~~ - 합친다. ~~~ 1 10000101 11011010100000000000000 ~~~ ### 부동소수점 산술연산 - 덧셈과 뺄셈 - 지수들이 일치되도록 조정하고 가수들 간에 덧셈 혹은 뺄셈을 수행한다. 후에 정규화를 진행 ==> 10^3과 10^5가 있으면 한쪽으로 맞춰서 계산을 하면 된다. - 곱셈 (0.1011*2^3) * (0.1001*2^5) - 가수들을 곱한다 1011 * 1001 = 01100011 - 지수들을 더한다 3+5=8 - 정규화 0.01100011*2^8 ==> 0.1100011*2^7 - 나눗셈 - 가수들을 나눈다. - 피제수의 지수에서 제수의 지수를 뺀다 - 정규화 ### 부동소수점 산술의 파이프라이닝 연산과정을 독립적인 단계로 분리가 가능해서 단계 수 만큼 속도 향상이 가능하다. 그래서 슈퍼컴퓨터에서 사용되는 기법이다. # 의문점들 - 소수연산중 고정소수점이 정수계산이 더 빠른 이유는? - 문제점-> 조정방식에 realignment랑 반올림? # 참고 > 태양정복 스터디 발표자 하OO ppt > https://pcb4.tistory.com/925 프로그래밍 - 고정소수점 연산 > http://blog.naver.com/PostView.nhn?blogId=mildrain0208&logNo=50006907605&widgetTypeCall=true 고정소수점연산 > https://ko.wikipedia.org/wiki/IEEE_754 IEEE 754 > https://infosul.tistory.com/5 [IEEE 754] 부동소수점과 바이어스 표현법
Java
UTF-8
1,737
2.328125
2
[]
no_license
package com.zxg.ssmcurd.tests; import com.zxg.ssmcurd.beans.Department; import com.zxg.ssmcurd.dao.DepartmentMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /** * Created by zxg on 2017/6/10. * 推荐Spring的项目就可以使用Spring的单元测试,可以自动注入我们需要的组件 *1、导入SpringTest模块 *2、@ContextConfiguration指定Spring配置文件的位置 *3、直接autowired要使用的组件即可 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring.xml"}) public class DepartmentMapperTest { @Autowired private DepartmentMapper departmentMapper; /** * 先测试 DepartmentMapper */ @Test public void testDeptAdd() { Department department = new Department(); // department.setDeptName("开发部"); // department.setDeptName("测试部"); department.setDeptName("zzzzzz"); departmentMapper.insertSelective(department); } @Test public void testSelectAll() { Department departments = departmentMapper.selectByPrimaryKey(4); System.out.println("departments = " + departments); } @Test public void testUpdate() { Integer flag = departmentMapper.updateByPrimaryKey(new Department(4, "xxxxx")); System.out.println("flag = " + flag); } @Test public void testDelete() { Integer flag = departmentMapper.deleteByPrimaryKey(4); System.out.println("flag = " + flag); } }
Markdown
UTF-8
2,465
2.84375
3
[]
no_license
# Paintball! I denne oppgaven skal vi lage et multiplayer minigame! Spillet ligner litt på helt vanlig paintball, men vi spiller med egg og snøballer. NB: Her ligger det stortsett bare kode og ingen instruksjoner. # Steg 1: Bygg en arena! Det første vi må gjøre er å bygge en arena vi kan spille på. Bygg en helt flat firkant av snø! ![kode](images/snowbase.png) Men vi trenger jo vegger også! Lag en `wallBuilder` drone som setter opp vegger rundt banen vår. ![](images/wallbuilder.png) # Steg 2: La spillere bli med! Nå trenger vi litt kode som lager Egg- og Snøballag av spillere som blir med! Først legger vi til spillere. Hver spiller skriver `join` for å bli med og legges da til i et lag. ![](images/teams.png) # Steg 3: Gi spillerne våpen når spillet startes! Så når vi skriver `start` starter vi spillet og gir alle spillerene våpen. ![](images/eggsnsnowballs.png) # Steg 4: Lag spawnpoints. Når spillet starter må vi flytte alle spillerne til arenaen vår. Lagene må starte på hver sin side. Lag to nye variabler `eggSpawn` og `snowSpawn` og flytt de til hver sin side av arenaen. ![](images/spawnvar.png) I løkkene hvor vi deler ut våpen teleporterer vi spillerne våre. ![](images/teleport.png) # Steg 5: Tell poeng når spillere bli truffet av snøballer eller egg. Vi trenger å holde styr på når spillere blir truffet av egg eller snøballer. Når en spiller blir truffet vil vi telle opp en poengsum og flytte spilleren tilbake til spawnpointet til laget sitt. Lag en ny funksjon onDama som kjører når `entity_damage_by_entity` eventen kjøres. ![](images/ondamage-event.png) ![](images/ondamage.png) # Steg 6: Stopp spillet når hvert lag har fått 15 poeng. Siden vi teller opp poeng kan vi stoppe spillet når ett av lagene har fått f.eks 15 poeng. Lag en funksjon `pointCheck` som du legger helt neders, under if-testen, i `onDamage` funksjonen din. ![](images/pointcheck.png) # Steg 7: Lag noen kule effekter når noen blir truffet av en snøball eller et egg Det skjer jo ikke mye når noen blir truffet. Lag en tøff effekt når spillere blir truffet av egg eller snøballer. Bruk `launch fireworks`-blokka inne i koden der du håndterer spillere som blir truffet av egg eller snøballer. ![](images/fireworks.png) # Steg 8: BONUS: Lag hinder på arenaen vår. Arenaen vår er jo helt tom. Lag noen hinder her og der for å gjøre banen mer spennende!
JavaScript
UTF-8
564
2.6875
3
[]
no_license
// Routers for every component const usersRouter = require('./components/user/routes') /** * Takes the company identifier from the url parameter ':company' * and put into the req.body object so that next middleware * functions can access its value * * @param {*} req * @param {*} res * @param {*} next */ const companySetter = (req, res, next) => { req.body.company = req.params.company next() } /** * Set the routes for the app * @param {*} app */ module.exports = app => { app.use('/:company/users', companySetter, usersRouter); }
Java
UTF-8
3,502
2.546875
3
[]
no_license
package org.iiitb.facebook.dao.impl; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import org.iiitb.facebook.dao.LoginDAO; import org.iiitb.facebook.model.User; import org.iiitb.facebook.util.ConnectionPool; public class LoginDAOimpl implements LoginDAO { String verifyPassword="select * from user where email_id=? and password=?"; String verifyUser="select * from user where email_id=?"; String updateLogoutTime="update user set last_login=? where user_id=?"; String getPic="select photo from user where user_id=?"; @Override public User isValidUser(String email,String pass) { Connection conn = ConnectionPool.getConnection(); PreparedStatement preStmt; User user=new User(); try { String veriFlag; preStmt = conn.prepareStatement(verifyUser); preStmt.setString(1,email); ResultSet result = preStmt.executeQuery(); if (result.next()) { veriFlag=(String)result.getString("isverified"); if("Y".equalsIgnoreCase(veriFlag)){ preStmt=conn.prepareStatement(verifyPassword); preStmt.setString(1, email); preStmt.setString(2, pass); ResultSet rs=preStmt.executeQuery(); if(rs.next()){ user.setErrorFlag(0); user.setErrorMessage("Successfully Login."); user.setFirstName(rs.getString("first_name")); user.setLastName(rs.getString("last_name")); user.setMobno(rs.getString("mobile_no")); user.setDob(rs.getDate("dob")); user.setGender(rs.getString("gender")); user.setCreateDate(rs.getDate("created_date")); user.setLastLogin(rs.getDate("last_login")); user.setEmail(email); user.setUserId(rs.getString("user_id")); user.setPassword(pass); return user; }else{ user.setErrorFlag(3); user.setErrorMessage("UserId or Password is not correct.Please try again."); return user; } }else{ user.setErrorFlag(2); user.setErrorMessage("You account is not verified.Please verify email for verfication link."); return user; } } else { user.setErrorFlag(1); user.setErrorMessage("There is no user exist with UserId = "+email); return user; } } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionPool.freeConnection(conn); } user.setErrorFlag(4); user.setErrorMessage("Some Error Occurred .Please try again"); return user; } @Override public boolean updateLogoutTime(String userId,String date) { Connection conn = ConnectionPool.getConnection(); PreparedStatement preStmt; try { System.out.println(userId+" "+date); preStmt = conn.prepareStatement(updateLogoutTime); preStmt.setString(1, date); preStmt.setString(2, userId); int n=preStmt.executeUpdate(); System.out.println(n); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionPool.freeConnection(conn); } return true; } public InputStream displayphoto(String userId){ Connection conn = ConnectionPool.getConnection(); InputStream pic=null; try { PreparedStatement stmt = conn.prepareStatement(getPic); stmt.setString(1, userId); ResultSet rs = stmt.executeQuery(); if (rs.next()) { pic=rs.getBinaryStream("photo"); } } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionPool.freeConnection(conn); } return pic; } }
Java
UTF-8
2,084
2.8125
3
[]
no_license
package controller.requests; import controller.Dispatcher; import model.fileHandler.FileHandler; import model.player.Player; import view.gui.ErrorFrame; import view.gui.UI; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Represents a request for saving the scores of the players of the current game session. * @author Tasos Papadopoulos * @version 14.1.2021 */ public class SaveScoresRequest extends Request{ private final UI gamemodeFrame; /** * Creates a {@code SaveScoresRequest} that saves the scores of the players of the current game session. * @param gamemodeFrame the gamemode frame for the current game session */ public SaveScoresRequest(UI gamemodeFrame) { this.gamemodeFrame = gamemodeFrame; } /** * @see Request */ @Override public void execute(Dispatcher dispatcher) { List<Integer> scores = new ArrayList<>(); model.getPlayers().forEach(e-> scores.add(e.getScore())); if(scores.stream().distinct().count()<=1 && model.getPlayers().size()>1) // draw and more than one player return; if(gamemodeFrame.hasMoreThanTwoPlayers()) { List<Player> players = model.getPlayers(); Player maxPlayer = players.get(0); for(int i=1;i< players.size();i++) { if(players.get(i).getScore() > maxPlayer.getScore()) maxPlayer = players.get(i); } for(Player player:players) { if (!player.equals(maxPlayer)) { player.setScore(0); player.setWins(0); } else { player.setWins(player.getWins()+1); player.setScore(0); } } } else { model.getPlayers().get(0).setWins(0); } FileHandler fileHandler = dispatcher.getFileHandler(); try { fileHandler.savePlayers(); } catch(IOException|ClassNotFoundException e) { new ErrorFrame(); } } }
JavaScript
UTF-8
1,195
2.9375
3
[]
no_license
let fs = require("fs"); let path = require("path"); let uuid = require("uuid"); module.exports = function () { let mo = { }; untreefy(arguments[0], arguments[1], mo); fs.writeFile(path.join(arguments[1], "metadata.json"), JSON.stringify(mo), function(){ }); } // this will update the object with correct info, copy all files with proper random names function untreefy(spath, dpath, obj){ let stats = fs.lstatSync(spath); if (stats.isDirectory() == false) { obj.name = path.basename(spath); obj.isFile = true; obj.newname = uuid.v4(); //copy the file var rs = fs.createReadStream(spath); var ws = fs.createWriteStream(path.join(dpath, obj.newname)); rs.pipe(ws); } else { // name, isFile=f, children, recursion obj.name = path.basename(spath); obj.isFile = false; obj.children = []; let children = fs.readdirSync(spath); for (let i = 0; i < children.length; i++) { let cpath = path.join(spath, children[i]); let nco = {}; untreefy(cpath, dpath, nco); obj.children.push(nco); } } }
JavaScript
UTF-8
219
2.984375
3
[]
no_license
let exclamation = "" let sunshine = () => { exclamation +="!" console.log("I miss you too!" + exclamation) } module.exports = () => { for (let i = 0; i < 10; i++){ setTimeout( sunshine, 100* i) } }
JavaScript
UTF-8
1,346
2.671875
3
[]
no_license
const express = require('express'); const morgan = require('morgan'); const app = express(); app.use(morgan('common')); const plays = require('./playstore.js') const playStore = require('./playstore'); app.get('/apps', (req, res) => { const {sort, genre} = req.query; let returnData = [...playStore]; if(genre && genre !== 'action' && genre !== 'puzzle' && genre !== 'strategy' && genre !== 'casual' && genre !== 'arcade' && genre !== 'card') { res .status(400) .send('Genre must be one of the following : action, puzzle, strategy, casual, arcade, card'); } // sort validation if(sort && sort !== 'rating' && sort !== 'app') { res .status(400) .send('Sort must be one of rating or app'); } // genre filtering if(genre) { returnData = returnData.filter(a => { return a.Genres.toLowerCase().includes(genre.toLowerCase()); }); } // sort by rating or app if(sort) { let newSort; if(sort === 'rating'){ newSort = 'Rating'; } else { newSort = 'App'; } returnData.sort((currApp, nextApp) => { console.log('currApp rating', currApp[newSort]); if(currApp[newSort] > nextApp[newSort]) return 1; if(currApp[newSort] < nextApp[newSort]) return -1; return; }); } res.json(returnData); }); module.exports = app
Shell
UTF-8
396
3.125
3
[]
no_license
#!/usr/bin/env bash # Compiles the JAM source code and creates jam.jar JAMDIR=$(pwd) COMPILE_CP="-cp .:$JAMDIR/src:$JAMDIR/lib/junit-4.12.jar:$JAMDIR/lib/hamcrest-core-1.3.jar:$JAMDIR/lib/gson-2.8.5.jar:$JAMDIR/lib/commons-cli-1.4.jar" echo $JAMDIR echo $COMPILE_CP javac $COMPILE_CP $(find src | grep ".java") pushd src jar cf ../lib/jam.jar `find . | grep .class | grep -v "jam.tests"` popd
C#
UTF-8
7,106
3.34375
3
[ "MIT" ]
permissive
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Nvelope.IO { public static class Folder { /// <summary> /// Get the part of the path representing the folder /// </summary> /// <param name="path"></param> /// <returns></returns> public static string Directory(string path) { // If there's no slash in the path, then it's either a filename or a foldername if (!path.Contains("\\") && !path.Contains("/")) { // If it's in the pattern c.c, then it's a filename if (Regex.IsMatch(path, "[^\\.]+\\.[^\\.]+")) return string.Empty; else return path; } var beforeLastSlash = Regex.Replace(path, "([\\\\/])[^\\\\/]+\\.[^\\\\/]+$", "$1"); return beforeLastSlash; } /// <summary> /// Get the part of the path representing the filename /// </summary> /// <param name="path"></param> /// <returns></returns> public static string File(string path) { return Regex.Replace(path, Directory(path).Replace("\\", "\\\\") + "(.*)$", "$1"); } /// <summary> /// Finds the first seperator used in the path - if there is none, return alternate /// </summary> /// <param name="path"></param> /// <param name="alternate"></param> /// <returns></returns> public static string GetSeperator(string path, string alternate) { var match = Regex.Match(path, "([\\\\/])"); if (match.Success) return match.Groups[1].Value; else return alternate; } /// <summary> /// Enforce the use of a given seperator in the path /// </summary> /// <param name="path"></param> /// <param name="seperator"></param> /// <returns></returns> public static string UseSeperator(string path, string seperator) { var alt = seperator == "/" ? "\\" : "/"; return path.Replace(alt, seperator); } /// <summary> /// Finds the first seperator used in the paths, if there is none, return alternate /// </summary> /// <param name="paths"></param> /// <returns></returns> public static string GetSeperator(IEnumerable<string> paths, string alternate) { return paths.Select(p => GetSeperator(p, "")).Where(s => !s.IsNullOrEmpty()).FirstOr(alternate); } /// <summary> /// Creates a path out of the cleaned-up pieces supplied /// </summary> /// <param name="pathParts"></param> /// <returns></returns> public static string ComposePath(params string[] pathParts) { return ComposePath(pathParts as IEnumerable<string>); } /// <summary> /// Creates a path out of the cleaned-up pieces supplied /// </summary> /// <param name="pathParts"></param> /// <returns></returns> public static string ComposePath(IEnumerable<string> pathParts) { if (!pathParts.Any()) return ""; var sep = GetSeperator(pathParts, "\\"); // Normalize the seperators pathParts = pathParts.Select(s => UseSeperator(s, sep)); var parts = pathParts.Where(s => !s.IsNullOrEmpty()); return parts.First().ChopEnd(sep) .And(parts.Rest().Select(s => s.ChopStart(sep).ChopEnd(sep))) .Join(sep); } /// <summary> /// Get sequence of folder names in the path /// </summary> /// <param name="path"></param> /// <returns></returns> public static IEnumerable<string> FolderParts(string path) { return Directory(path).Tokenize("^[\\\\/]?([^\\\\/]+)[\\\\/]?"); } /// <summary> /// Get the file extension /// </summary> /// <param name="path"></param> /// <returns></returns> public static string Extension(string path) { return Regex.Replace(File(path), "^.*\\.([^\\.]+)$", "$1"); } /// <summary> /// Gets the filename without the extension /// </summary> /// <param name="path"></param> /// <returns></returns> public static string FileBaseName(string path) { return Regex.Replace(File(path), "\\.[^\\.]+$", ""); } /// <summary> /// Convert a relative path into one relative to the starting directory /// </summary> /// <param name="startDir"></param> /// <param name="relativePath"></param> /// <returns></returns> public static string ResolvePath(string startDir, string relativePath) { // If the "relative path" starts with a drive letter, it's an absoute path if (Regex.IsMatch(relativePath, "^[A-Za-z]\\:")) return relativePath; var filePart = Folder.File(relativePath); var relPath = FolderParts(relativePath); var seperator = GetSeperator(new string[] { startDir, relativePath }, "\\"); // Work with the directory backwards, since we'll be messing around with // then end of it, which is more efficient to do on the front of lists var res = FolderParts(startDir).Reverse(); while (relPath.Count() > 0) { if (relPath.First() == "..") res = res.Rest(); else if (relPath.IsSameAs(res.Reverse())) // remember, res is backwards break; // exit the loop, since all the rest is the same else if (relPath.First() != ".") res = relPath.First().And(res); relPath = relPath.Rest(); } return Folder.ComposePath(res.Reverse().Join(seperator), filePart); } /// <summary> /// Is this directory top - level (no parents) /// </summary> /// <param name="dir"></param> /// <returns></returns> public static bool IsRoot(string dir) { return FolderParts(dir).Count() == 1; } /// <summary> /// Get the parent directory /// </summary> /// <param name="dir"></param> /// <returns></returns> public static string Parent(string dir) { var seperator = GetSeperator(dir, "\\"); var parts = FolderParts(dir); if (parts.Count() < 2) return ""; return parts.Chop().Join(seperator); } } }
Python
UTF-8
181
3.4375
3
[]
no_license
def solve(): sum = 0 for i in range(1, 1001): sum += (i**i) print(f'The last ten digits of sum are: {str(sum)[-10:]}') if __name__ == '__main__': solve()
Markdown
UTF-8
2,738
3.015625
3
[]
no_license
# A. Interactor - Ограничение времени 1 секунда - Ограничение памяти 256Mb - Ввод стандартный ввод или input.txt - Вывод стандартный вывод или output.txt Лена руководит разработкой тестирующей системы, в которой реализованы интерактивные задачи. До заверщения очередной стадии проекта осталось написать модуль, определяющий итоговый вердикт системы для интерактивной задачи. Итоговый вердикт определяется из кода завершения задачи, вердикта интерактора и вердикта чекера по следующим правилам: - Вердикт чекера и вердикт интерактора — это целые числа от 0 до 7 включительно. - Код завершения задачи — это целое число от -128 до 127 включительно. - Если интерактор выдал вердикт 0, итоговый вердикт равен 3 в случае, если программа завершилась с ненулевым кодом, и вердикту чекера в противном случае. - Если интерактор выдал вердикт 1, итоговый вердикт равен вердикту чекера. - Если интерактор выдал вердикт 4, итоговый вердикт равен 3 в случае, если программа завершилась с ненулевым кодом, и 4 в противном случае. - Если интерактор выдал вердикт 6, итоговый вердикт равен 0. - Если интерактор выдал вердикт 7, итоговый вердикт равен 1. - В остальных случаях итоговый вердикт равен вердикту интерактора. Ваша задача — реализовать этот модуль. ## Формат ввода Входной файл состоит из трёх строк. В первой задано целое число — код завершения задачи, во второй — целое число — вердикт интерактора, в третьей — целое число — вердикт чекера. ## Формат вывода Выведите одно целое число от 0 до 7 включительно — итоговый вердикт системы.
JavaScript
UTF-8
440
4.46875
4
[]
no_license
/* Complete the function below to find the max number of the passing array of numbers. */ function max(numbers) { var max_num = numbers[0]; for (let i = 1; i < numbers.length; i++) { if (numbers[i] > max_num) { max_num = numbers[i]; } } return max_num; } max([1, 2, 4, 5]); // result to 5 max([5, 2, 7, 1, 6]); // result to 7 console.log(max([1, 2, 4, 5])); console.log(max([5, 2, 7, 1, 6]));
Java
UTF-8
7,295
2.578125
3
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package org.irods.jargon.core.pub; import java.util.List; import org.irods.jargon.core.exception.DuplicateDataException; import org.irods.jargon.core.exception.InvalidGroupException; import org.irods.jargon.core.exception.InvalidUserException; import org.irods.jargon.core.exception.JargonException; import org.irods.jargon.core.pub.domain.User; import org.irods.jargon.core.pub.domain.UserGroup; import org.irods.jargon.core.query.JargonQueryException; /** * Interface for an access object dealing with iRODS user groups. Includes * methods to obtain information on, and to manage iRODS user groups. * * @author Mike Conway - DICE (www.irods.org) * */ public interface UserGroupAO extends IRODSAccessObject { /** * Given a user group id, return the {@code UserGroup}, or return null if * not found * * @param userGroupId * {@code String} with the numeric key for the user group * @return {@code UserGroup} domain object * @throws JargonException */ UserGroup find(final String userGroupId) throws JargonException; /** * Given a user name, return the {@code UserGroup}, or return null if not * found * * @param userGroupName * {@code String} with the name of the user group * @return {@code UserGroup} domain object * @throws JargonException */ UserGroup findByName(final String userGroupName) throws JargonException; /** * Provides a convenient way to query for {@code UserGroup}s using the * provided 'WHERE" clause. In usage, provide an iquest compatable condition * omitting the proceeding 'Where" statement. An empty {@code List} will be * returned if no matches were found. * * @param whereClause * {@code String} containing the iquest compatable condition, * omitting the "WHERE" token. * @return {@code List<UserGroup>} containing the UserGroups that match the * given query * @throws JargonException * @throws JargonQueryException * indicates some syntax exception in the provided where clause */ List<UserGroup> findWhere(String whereClause) throws JargonException, JargonQueryException; /** * Given a user name, return the user groups that the given user belongs to, * or an empty {@code List} when no user groups are found. * * @param userName * {@code String} with an IRODS user name * @return {@code List} of {@link UserGroup} * @throws JargonException */ List<UserGroup> findUserGroupsForUser(String userName) throws JargonException; /** * Add the given user group to iRODS * * @param userGroup * {@link UserGroup} to add * @throws DuplicateDataException * if user already exists * @throws JargonException */ void addUserGroup(UserGroup userGroup) throws DuplicateDataException, JargonException; /** * Remove the given user group from iRODS. Note that if the user group is * not found, a warning is logged, and the exception is ignored. * * @param userGroup * {@link UserGroup} to remove * @throws JargonException */ void removeUserGroup(UserGroup userGroup) throws JargonException; /** * List the {@code User}s that are members of an iRODS {@code UserGroup}. * * @param userGroupName * {@code String} with the name of an iRODS user group * @return {@code List} of {@link User} with the group membership. This will * be an empty {@code List} if the group has no members. * @throws JargonException */ List<User> listUserGroupMembers(String userGroupName) throws JargonException; /** * Add the given user to the iRODS user group * * @param userGroupName * {@code String} with the name of the iRODS user group. This * group must exist. * @param userName * {@code String} with the name of the iRODS user to add to the * group. This user must exist. * @param zoneName * {@code String} with the name of the iRODS zone for the user. * This is optional and may be set to blank or {@code null} if * not needed. * @throws DuplicateDataException * if the user is already a group member * @throws InvalidGroupException * @throws InvalidUserException * @throws JargonException */ void addUserToGroup(String userGroupName, String userName, String zoneName) throws InvalidGroupException, InvalidUserException, JargonException; /** * Remove the given user (with optional zone) from the given group. If the * user is valid but not in group, the method will return normally. * * @param userGroupName * {@code String} with the name of the iRODS user group. * @param userName * {@code String} with the name of the iRODS user to add to the * group. * @param zoneName * {@code String} with the name of the iRODS zone for the user. * This is optional and may be set to blank or {@code null} if * not needed. * @throws InvalidUserException * @throws InvalidGroupException * @throws JargonException */ void removeUserFromGroup(String userGroupName, String userName, String zoneName) throws InvalidUserException, InvalidGroupException, JargonException; /** * List all user groups * * @return {@code List} of {@link UserGroup} * @throws JargonException */ List<UserGroup> findAll() throws JargonException; /** * Query the ICAT and see if the given user is in the given group * * @param userName * {@code String} with the user name * @param groupName * {@code String} with the group name * @return {@code boolean} which will be {@code true} if the user is in the * given group * @throws JargonException */ boolean isUserInGroup(String userName, String groupName) throws JargonException; /** * Handy method to remove a user group in the current zone by simply giving * the user group name. This method will treat a non-existent group as if it * had been deleted, logging this situation and proceeding. * * @param userGroupName * {@code String} with the name of the user group to delete. * @throws JargonException */ void removeUserGroup(String userGroupName) throws JargonException; /** * Add a user group as a user with groupadmin privilages * * @param userGroup * {@link UserGroup} to add * @throws DuplicateDataException * @throws JargonException */ void addUserGroupAsGroupAdmin(final UserGroup userGroup) throws DuplicateDataException, JargonException; /** * Add the given user to the group as a user with groupadmin privilages * * @param userGroupName * <code>String</code> of the group to which the user will be * added * @param userName * <code>String</code> with the user name * @param zoneName * <code>String</code> with the zone to which the user will be * added * @throws DuplicateDataException * @throws InvalidGroupException * @throws InvalidUserException * @throws JargonException */ void addUserToGroupAsGroupAdmin(String userGroupName, String userName, String zoneName) throws DuplicateDataException, InvalidGroupException, InvalidUserException, JargonException; }
TypeScript
UTF-8
2,150
2.828125
3
[]
no_license
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ProductService { private products: Product[] = [ new Product(1,"第一个商品",1.99,3.5,"这是第一个商品,是我再学习angular入门实战是创建的",["电子产品","硬件设备"]), new Product(2,"第二个商品",2.99,2.5,"这是第二个商品,是我再学习angular入门实战是创建的",["电子产品","硬件设备"]), new Product(3,"第三个商品",3.99,4.5,"这是第三个商品,是我再学习angular入门实战是创建的",["硬件设备"]), new Product(4,"第四个商品",4.99,1.5,"这是第四个商品,是我再学习angular入门实战是创建的",["电子产品","硬件设备"]), new Product(5,"第五个商品",5.99,3.5,"这是第五个商品,是我再学习angular入门实战是创建的",["电子产品","硬件设备"]), new Product(6,"第六个商品",6.99,2.5,"这是第六个商品,是我再学习angular入门实战是创建的",["电子产品","硬件设备"]), ] private comments:Comment[] = [ new Comment(1,1,"2017-02-23 22:22:22","张三",3,"东西不错1"), new Comment(2,1,"2018-04-05 15:22:22","李四",3,"东西不错2"), new Comment(3,1,"2014-06-03 16:22:22","王五",3,"东西不错3"), new Comment(4,2,"2016-07-02 09:22:22","马六",3,"东西不错4"), ] constructor() { } getProducts() { return this.products; } // 根据商品ID 找出相应商品 getProduct(id:number):Product{ return this.products.find((product)=>product.id == id) } // 获取商品评论的方法 getCommentsForProductId(id:number): Comment[] { return this.comments.filter((comment:Comment) => comment.productId == id) } } export class Product { constructor( public id: number, public title: string, public price: number, public rating: number, public desc: string, public categories: Array<string> ){} } export class Comment { constructor( public id:number, public productId:number, public timestamp:string, public user:string, public rating:number, public content:string ){} }
C#
UTF-8
5,038
2.9375
3
[ "MIT" ]
permissive
using UnityEngine; using System.Collections; using System; namespace CGLA { public struct Mat3x3f { public float m00; public float m01; public float m02; public float m10; public float m11; public float m12; public float m20; public float m21; public float m22; public static Mat3x3f New() { Mat3x3f m; m.m00 = 0; m.m01 = 0; m.m02 = 0; m.m10 = 0; m.m11 = 0; m.m12 = 0; m.m20 = 0; m.m21 = 0; m.m22 = 0; return m; } public Mat3x3f(Vec3f a1, Vec3f a2, Vec3f a3) { m00 = a1.x; m01 = a1.y; m02 = a1.z; m10 = a2.x; m11 = a2.y; m12 = a2.z; m20 = a3.x; m21 = a3.y; m22 = a3.z; } public float this[int row, int column] { get { return this[row * 3 + column]; } set { this[row * 3 + column] = value; } } public float this[int index] { get { float result; switch (index) { case 0: result = this.m00; break; case 1: result = this.m01; break; case 2: result = this.m02; break; case 3: result = this.m10; break; case 4: result = this.m11; break; case 5: result = this.m12; break; case 6: result = this.m20; break; case 7: result = this.m21; break; case 8: result = this.m22; break; default: throw new IndexOutOfRangeException("Invalid matrix index!"); } return result; } set { switch (index) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m02 = value; break; case 3: this.m10 = value; break; case 4: this.m11 = value; break; case 5: this.m12 = value; break; case 6: this.m20 = value; break; case 7: this.m21 = value; break; case 8: this.m22 = value; break; default: throw new IndexOutOfRangeException("Invalid matrix index!"); } } } //MATRIX MULTIPLICATION public static Mat3x3f operator *(Mat3x3f m1, Mat3x3f m2){ Mat3x3f n; n.m00 = m1.m00 * m2.m00; n.m00 += m1.m01 * m2.m10; n.m00 += m1.m02 * m2.m20; n.m01 = m1.m00 * m2.m01; n.m01 += m1.m01 * m2.m11; n.m01 += m1.m02 * m2.m21; n.m02 = m1.m00 * m2.m02; n.m02 += m1.m01 * m2.m12; n.m02 += m1.m02 * m2.m22; n.m10 = m1.m10 * m2.m00; n.m10 += m1.m11 * m2.m10; n.m10 += m1.m12 * m2.m20; n.m11 = m1.m10 * m2.m01; n.m11 += m1.m11 * m2.m11; n.m11 += m1.m12 * m2.m21; n.m12 = m1.m10 * m2.m02; n.m12 += m1.m11 * m2.m12; n.m12 += m1.m12 * m2.m22; n.m20 = m1.m20 * m2.m00; n.m20 += m1.m21 * m2.m10; n.m20 += m1.m22 * m2.m20; n.m21 = m1.m20 * m2.m01; n.m21 += m1.m21 * m2.m11; n.m21 += m1.m22 * m2.m21; n.m22 = m1.m20 * m2.m02; n.m22 += m1.m21 * m2.m12; n.m22 += m1.m22 * m2.m22; return n; } //float MULTIPLICATION public static Mat3x3f operator *(Mat3x3f m, float f) { m.m00 *= f; m.m01 *= f; m.m02 *= f; m.m10 *= f; m.m11 *= f; m.m12 *= f; m.m20 *= f; m.m21 *= f; m.m22 *= f; return m; } public static Mat3x3f operator *(float f, Mat3x3f m) { m.m00 *= f; m.m01 *= f; m.m02 *= f; m.m10 *= f; m.m11 *= f; m.m12 *= f; m.m20 *= f; m.m21 *= f; m.m22 *= f; return m; } //Vector MULTIPLICATION public static Vec3f operator *(Mat3x3f m, Vec3f v) { Vec3f v2; v2.x = m.m00 * v.x + m.m01 * v.y + m.m02 * v.z; v2.y = m.m10 * v.x + m.m11 * v.y + m.m12 * v.z; v2.z = m.m20 * v.x + m.m21 * v.y + m.m22 * v.z; return v2; } //ToSTRING OVERRIDE public override string ToString() { string str = "["; // for(int i = 0; i < 3; i++){ // for(int j = 0; j < 3; j++){ // str += matrix[j][i].ToString(); // str += i*j == 4 ? "]" : ", "; // } // } return str; } public Vec3f MultiplyVector(Vec3f vec){ Vec3f v2; v2.x = m00 * vec.x + m01 * vec.y + m02 * vec.z; v2.y = m10 * vec.x + m11 * vec.y + m12 * vec.z; v2.z = m20 * vec.x + m21 * vec.y + m22 * vec.z; return v2; } public static Mat3x3f Rotation_Mat3x3f(Axis axis, float angle) { Mat3x3f m = Mat3x3f.New(); switch(axis) { case Axis.XAXIS: m.m00 = 1.0f; m.m11 = Mathf.Cos(angle); m.m12 = Mathf.Sin(angle); m.m21 = -Mathf.Sin(angle); m.m22 = Mathf.Cos(angle); break; case Axis.YAXIS: m.m00 = Mathf.Cos(angle); m.m02 = -Mathf.Sin(angle); m.m20 = Mathf.Sin(angle); m.m22 = Mathf.Cos(angle); m.m11 = 1.0f; break; case Axis.ZAXIS: m.m00 = Mathf.Cos(angle); m.m01 = Mathf.Sin(angle); m.m10 = -Mathf.Sin(angle); m.m11 = Mathf.Cos(angle); m.m22 = 1.0f; break; } return m; } public Mat3x3f Transpose(){ Mat3x3f newM; newM.m00 = m00; newM.m01 = m10; newM.m02 = m20; newM.m10 = m01; newM.m11 = m11; newM.m12 = m21; newM.m20 = m02; newM.m21 = m12; newM.m22 = m22; return newM; } } }
Java
UTF-8
478
2.359375
2
[]
no_license
package com.yzblog.datacenter.web.modules.sysmonitor.util; /** * 请求状态 * * @author yuzhou * @create 2017-10-19 17:52 **/ public enum RequestStatus { /** * {@code 0 success}. * 成功 */ SUCCESS((short) 0), /** * {@code 1 fail}. * 异常失败 */ FAIL((short) 1); private short value; RequestStatus(short value) { this.value = value; } public short getValue() { return value; } }
Java
UTF-8
686
2.40625
2
[]
no_license
package com.example.user.glujam; /** * Created by User on 2018-02-24. */ public class MusicDto2 { private String path; private int index; public MusicDto2(){ } public MusicDto2(int index, String path) { this.index = index; this.path = path; } public String getPath() {return path;} public void setPath(String path) {this.path = path;} public int getIndex() {return index;} public void setIndex(int index) {this.index = index;} @Override public String toString() { return "MusicDto{" + "id='" + index + ", " + ", albumId='" + path + '\'' + '}'; } }
Ruby
UTF-8
1,080
2.890625
3
[]
no_license
class App ALL_FORMATS = ['year', 'month', 'day', 'hour', 'min', 'sec'] def call(env) @path = env['PATH_INFO'] @query = env['QUERY_STRING'] [status, headers, body] end private def status if false_path? 404 elsif false_format? 400 else 200 end end def false_path? true if @path != '/time' end def false_format? check_formats true if !@format_error.empty? end def check_formats format = @query.gsub('format=', '').chomp('%').split('%2C') time = Time.now time_hash = {} ALL_FORMATS.each do |form| time_hash[form] = time.send(form) end @time_output = [] @format_error = [] format.each do |form| if time_hash.keys.include?(form) @time_output << time_hash[form] else @format_error << form end end end def headers {'Content-Type' => 'text/plain'} end def body if @format_error.any? ["Unknown time format [#{@format_error.join(',')}]"] else [@time_output.join('-')] end end end
Python
UTF-8
236
3.03125
3
[]
no_license
def f1(x): return x // 3 - 2 def f2(x): a = x // 3 - 2 if a <= 0: return 0 return a + f2(a) def solve(fl, f): return sum(map(lambda x : f(int(x)), open(fl).read().split())) print(solve('in', f1)) print(solve('in', f2))
C#
UTF-8
759
2.71875
3
[ "MIT" ]
permissive
namespace Fun { using System; public struct Unit { public static Unit Value = new Unit (); public override Boolean Equals (Object obj) { var local = this; return If.Else ( obj is Unit, () => local.Equals ((Unit) obj), () => false); } public static Boolean Equals (Unit v1, Unit v2) { return true; } public Boolean Equals (Unit that) { return true; } public static Boolean operator == (Unit v1, Unit v2) { return true; } public static Boolean operator != (Unit v1, Unit v2) { return false; } public override Int32 GetHashCode () { return 0; } public override String ToString () { return "()"; } } }
Shell
UTF-8
591
2.671875
3
[]
no_license
#!/bin/bash for work in get-6k.cnf set-6k.cnf; do for iso in "" "--enable"; do for active in mem udp udp,mem; do file=serv-iso$iso-work$work-active$active.png plot_rate.py -f \ memcached-mtu9000-iso$iso-work$work-active$active/l{1,2,3,4}/net.txt \ -i total -l l1 l2 l3 l4 \ --title "TX rates at $active servers iso$iso" -o $file file=client-iso$iso-work$work-active$active.png plot_rate.py -f \ memcached-mtu9000-iso$iso-work$work-active$active/l{5,6,7,8}/net.txt \ -i total -l l5 l6 l7 l8 \ --rx \ --title "RX rates at $active clients iso$iso" -o $file done done done
Java
UTF-8
6,498
2.421875
2
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
/*- * #%L * Image-Registration * %% * Copyright (C) 2019 Oliver Loeffler, Raumzeitfalle.net * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package net.raumzeitfalle.registration.displacement; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; class DisplacementTest { private Displacement classUnderTest; @Test void undisplaced() { classUnderTest = Displacement.at(1, 2, 10, 20); assertEquals(Category.REG, classUnderTest.getCategory()); assertEquals(10.0, classUnderTest.getX(), 1E-3); assertEquals(20.0, classUnderTest.getY(), 1E-3); assertEquals(10.0, classUnderTest.getXd(), 1E-3); assertEquals(20.0, classUnderTest.getYd(), 1E-3); assertEquals(0.0, classUnderTest.dX(), 1E-3); assertEquals(0.0, classUnderTest.dY(), 1E-3); assertEquals(1, classUnderTest.getIndex()); assertEquals(2, classUnderTest.getId()); } @Test void fromDisplacement() { Displacement source = Displacement.at(1, 2, 10, 20); classUnderTest = Displacement.from(source, 11, 22); assertNotEquals(source, classUnderTest); assertEquals(10.0, classUnderTest.getX(), 1E-3); assertEquals(20.0, classUnderTest.getY(), 1E-3); // actual displaced value assertEquals(11.0, classUnderTest.getXd(), 1E-3); assertEquals(22.0, classUnderTest.getYd(), 1E-3); // the displacement assertEquals(1.0, classUnderTest.dX(), 1E-3); assertEquals(2.0, classUnderTest.dY(), 1E-3); assertEquals(1, classUnderTest.getIndex()); assertEquals(2, classUnderTest.getId()); } @Test void moveBy() { Displacement source = Displacement.at(1, 2, 10, 20, 11, 22, Category.INFO_ONLY); classUnderTest = source.moveBy(-10, -20); assertNotEquals(source, classUnderTest); // the design value - moved assertEquals(0.0, classUnderTest.getX(), 1E-3); assertEquals(0.0, classUnderTest.getY(), 1E-3); // actual displaced value - moved assertEquals(1.0, classUnderTest.getXd(), 1E-3); assertEquals(2.0, classUnderTest.getYd(), 1E-3); // the displacement assertEquals(1.0, classUnderTest.dX(), 1E-3); assertEquals(2.0, classUnderTest.dY(), 1E-3); assertEquals(1, classUnderTest.getIndex()); assertEquals(2, classUnderTest.getId()); assertEquals(Category.INFO_ONLY, classUnderTest.getCategory()); } @Test void correctBy() { Displacement source = Displacement.at(1, 2, 10, 20, 11, 22, Category.INFO_ONLY); classUnderTest = source.correctBy(1, 2); assertNotEquals(source, classUnderTest); assertEquals(10.0, classUnderTest.getX(), 1E-3); assertEquals(20.0, classUnderTest.getY(), 1E-3); // actual displaced value but corrected assertEquals(10.0, classUnderTest.getXd(), 1E-3); assertEquals(20.0, classUnderTest.getYd(), 1E-3); // the displacement, now corrected assertEquals(0.0, classUnderTest.dX(), 1E-3); assertEquals(0.0, classUnderTest.dY(), 1E-3); assertEquals(1, classUnderTest.getIndex()); assertEquals(2, classUnderTest.getId()); assertEquals(Category.INFO_ONLY, classUnderTest.getCategory()); } @Test void belongsTo() { classUnderTest = Displacement.at(1, 2, 10, 20, 11, 22, Category.INFO_ONLY); assertTrue(classUnderTest.belongsTo(Category.INFO_ONLY)); assertFalse(classUnderTest.belongsTo(Category.REG)); classUnderTest = Displacement.at(1, 2, 10, 20, 11, 23); assertTrue(classUnderTest.belongsTo(Category.REG)); assertFalse(classUnderTest.belongsTo(Category.ALIGN)); classUnderTest = Displacement.at(1, 2, 10, 20, 11, 22, Category.ALIGN); assertFalse(classUnderTest.belongsTo(Category.INFO_ONLY)); assertFalse(classUnderTest.belongsTo(Category.REG)); assertTrue(classUnderTest.belongsTo(Category.ALIGN)); } @Test void average() { List<Displacement> displaced = new ArrayList<>(4); displaced.add(Displacement.at(0, 0, 1000, 2000, 1010, 99)); displaced.add(Displacement.at(1, 1, 1000, 9000, 1010, 8990)); displaced.add(Displacement.at(2, 2, 9000, 9000, 9010, 8990)); displaced.add(Displacement.at(3, 3, 9000, 2000, 9010, 99)); double meanX = Displacement.average(displaced, d->true, Displacement::getX); assertEquals(5000, meanX, 1E-1); double meanY = Displacement.average(displaced, d->true, Displacement::getY); assertEquals(5500, meanY, 1E-1); double meanXd = Displacement.average(displaced, d->true, Displacement::getXd); assertEquals(5010, meanXd, 1E-1); double meanYd = Displacement.average(displaced, d->true, Displacement::getYd); assertEquals(4544.5, meanYd, 1E-1); } @Test void summarize() { List<Displacement> displaced = new ArrayList<>(4); displaced.add(Displacement.at(0, 0, 1000, 1000, 1010, 990)); displaced.add(Displacement.at(1, 1, 1000, 9000, 1010, 8990)); displaced.add(Displacement.at(2, 2, 9000, 9000, 9010, 8990)); displaced.add(Displacement.at(3, 3, 9000, 1000, 9010, 990)); DisplacementSummary filtered = Displacement.summarize(displaced, d->d.getIndex()<3); assertNotNull(filtered); assertEquals(3, filtered.sizeX()); assertEquals(3, filtered.sizeY()); DisplacementSummary unfiltered = Displacement.summarize(displaced); assertNotNull(unfiltered); assertEquals(4, unfiltered.sizeX()); assertEquals(4, unfiltered.sizeY()); } @Test void toStringMethod() { classUnderTest = Displacement.at(0, 0, 1000, 1000, 1010, 990); assertEquals("Displacement [type=REG id=0 x=1000.0, y=1000.0, xd=1010.0, yd=990.0, " + System.lineSeparator()+ "\t\tdx=10.0, dy=-10.0]", classUnderTest.toString()); } }
Go
UTF-8
803
3.65625
4
[ "Apache-2.0" ]
permissive
package main import ( "log" "time" ) // coalesce events on a channel within a window, and then call fn() // http://blog.gopheracademy.com/advent-2013/day-24-channel-buffering-patterns/ //TODO this doesnt quite work right... It fires fn() immediately on first event in ch func coalesceEvents(ch <-chan string, window time.Duration, fn func()) { ticker := time.NewTimer(0) var timerCh <-chan time.Time i := 0 for { select { case e := <-ch: // count how many events we coalesce, for fun i = i + 1 log.Printf("Coalescing event %s. (%d events so far)\n", e, i) //log.Printf("%s\n", timerCh) if timerCh == nil { ticker.Reset(window) timerCh = ticker.C } case <-timerCh: log.Printf("Coalesced %d events in %s\n", i, window) fn() i = 0 timerCh = nil } } }
Markdown
UTF-8
2,757
3.265625
3
[]
no_license
# ContextReplacementPlugin _上下文\(Context\)_与一个[带表达式的 require 语句](https://doc.webpack-china.org/guides/dependency-management/#require-with-expression)相关,例如`require('./locale/' + name + '.json')`。遇见此类表达式时,webpack 查找目录 \(`'./locale/'`\) 下符合正则表达式 \(`/^.*\.json$/`\)的文件。由于`name`在编译时\(compile time\)还是未知的,webpack 会将每个文件都作为模块引入到 bundle 中。 上下文替换插件\(`ContextReplacementPlugin`\)允许你覆盖查找规则,该插件有许多配置方式: ## 用法 ```js new webpack.ContextReplacementPlugin( resourceRegExp: RegExp, newContentResource?: string, newContentRecursive?: boolean, newContentRegExp?: RegExp ) ``` 如果资源(或目录)符合`resourceRegExp`正则表达式,插件会替换默认资源为`newContentResource`,布尔值`newContentRecursive`表明是否使用递归查找,`newContextRegExp`用于筛选新上下文里的资源。如果`newContentResource`为相对路径,会相对于前一匹配资源路径去解析。 这是一个限制模块使用的小例子: ```js new webpack.ContextReplacementPlugin( /moment[\/\\]locale$/, /de|fr|hu/ ) ``` 限定查找`moment/locale`上下文里符合`/de|fr|hu/`表达式的文件,因此也只会打包这几种本地化内容(更多详细信息,请查看[这个 issue](https://github.com/moment/moment/issues/2373))。 ## 内容回调函数 ```js new webpack.ContextReplacementPlugin( resourceRegExp: RegExp, newContentCallback: (data) => void ) ``` `newContentCallback`函数的第一形参为[`上下文模块工厂(ContextModuleFactory)`](//API/ModuleFactories.md)的`data`对象,你需要覆写该对象的`request`属性。 使用这个回调函数,我们可以动态地将请求重定向到一个新的位置: ```js new webpack.ContextReplacementPlugin(/^\.\/locale$/, (context) => { if ( !/\/moment\//.test(context.context) ) return; Object.assign(context, { regExp: /^\.\/\w+/, request: '../../locale' // 相对路径解析 }); }), ``` ## 其他选项 `newContentResource`和`newContentCreateContextMap`参数也可用: ```js new webpack.ContextReplacementPlugin( resourceRegExp: RegExp, newContentResource: string, newContentCreateContextMap: object // 将运行时请求(runtime-request)映射到编译时请求(compile-time request) ) ``` 这两个参数可以一起使用,来更加有针对性的重定向请求。`newContentCreateContextMap`允许你将运行时的请求,映射为形式为对象的编译请求: ```js new ContextReplacementPlugin(/selector/, './folder', { './request': './request', './other-request': './new-request' }) ```
Java
UTF-8
470
2.6875
3
[]
no_license
package com.slokam.Stream; public class Mobile { private long mobileNumber; private String network; public Mobile(long mobileNumber, String network) { super(); this.mobileNumber = mobileNumber; this.network = network; } public long getMobileNumber() { return mobileNumber; } public String getNetwork() { return network; } @Override public String toString() { return "Mobile [mobileNumber=" + mobileNumber + ", network=" + network + "]"; } }
Java
UTF-8
9,781
2.390625
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 agp.matricula.modelo; import javax.xml.crypto.Data; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Monik */ public class PrematriculaIT { public PrematriculaIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getPre_id method, of class Prematricula. */ @Test public void testGetPre_id() { System.out.println("getPre_id"); Prematricula instance = null; int expResult = 0; int result = instance.getPre_id(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setPre_id method, of class Prematricula. */ @Test public void testSetPre_id() { System.out.println("setPre_id"); int pre_id = 0; Prematricula instance = null; instance.setPre_id(pre_id); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPre_fech method, of class Prematricula. */ @Test public void testGetPre_fech() { System.out.println("getPre_fech"); Prematricula instance = null; Data expResult = null; Data result = instance.getPre_fech(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setPre_fech method, of class Prematricula. */ @Test public void testSetPre_fech() { System.out.println("setPre_fech"); Data pre_fech = null; Prematricula instance = null; instance.setPre_fech(pre_fech); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPre_valor_neto method, of class Prematricula. */ @Test public void testGetPre_valor_neto() { System.out.println("getPre_valor_neto"); Prematricula instance = null; double expResult = 0.0; double result = instance.getPre_valor_neto(); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setPre_valor_neto method, of class Prematricula. */ @Test public void testSetPre_valor_neto() { System.out.println("setPre_valor_neto"); double pre_valor_neto = 0.0; Prematricula instance = null; instance.setPre_valor_neto(pre_valor_neto); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPre_descuento method, of class Prematricula. */ @Test public void testGetPre_descuento() { System.out.println("getPre_descuento"); Prematricula instance = null; double expResult = 0.0; double result = instance.getPre_descuento(); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setPre_descuento method, of class Prematricula. */ @Test public void testSetPre_descuento() { System.out.println("setPre_descuento"); double pre_descuento = 0.0; Prematricula instance = null; instance.setPre_descuento(pre_descuento); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPre_subtotal method, of class Prematricula. */ @Test public void testGetPre_subtotal() { System.out.println("getPre_subtotal"); Prematricula instance = null; double expResult = 0.0; double result = instance.getPre_subtotal(); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setPre_subtotal method, of class Prematricula. */ @Test public void testSetPre_subtotal() { System.out.println("setPre_subtotal"); double pre_subtotal = 0.0; Prematricula instance = null; instance.setPre_subtotal(pre_subtotal); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPre_IVA method, of class Prematricula. */ @Test public void testGetPre_IVA() { System.out.println("getPre_IVA"); Prematricula instance = null; double expResult = 0.0; double result = instance.getPre_IVA(); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setPre_IVA method, of class Prematricula. */ @Test public void testSetPre_IVA() { System.out.println("setPre_IVA"); double pre_IVA = 0.0; Prematricula instance = null; instance.setPre_IVA(pre_IVA); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPre_total method, of class Prematricula. */ @Test public void testGetPre_total() { System.out.println("getPre_total"); Prematricula instance = null; double expResult = 0.0; double result = instance.getPre_total(); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setPre_total method, of class Prematricula. */ @Test public void testSetPre_total() { System.out.println("setPre_total"); double pre_total = 0.0; Prematricula instance = null; instance.setPre_total(pre_total); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPre_tipo_pago method, of class Prematricula. */ @Test public void testGetPre_tipo_pago() { System.out.println("getPre_tipo_pago"); Prematricula instance = null; String expResult = ""; String result = instance.getPre_tipo_pago(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setPre_tipo_pago method, of class Prematricula. */ @Test public void testSetPre_tipo_pago() { System.out.println("setPre_tipo_pago"); String pre_tipo_pago = ""; Prematricula instance = null; instance.setPre_tipo_pago(pre_tipo_pago); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPre_detalle method, of class Prematricula. */ @Test public void testGetPre_detalle() { System.out.println("getPre_detalle"); Prematricula instance = null; Det_Prematricula expResult = null; Det_Prematricula result = instance.getPre_detalle(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setPre_detalle method, of class Prematricula. */ @Test public void testSetPre_detalle() { System.out.println("setPre_detalle"); Det_Prematricula pre_detalle = null; Prematricula instance = null; instance.setPre_detalle(pre_detalle); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPre_inscripcion method, of class Prematricula. */ @Test public void testGetPre_inscripcion() { System.out.println("getPre_inscripcion"); Prematricula instance = null; Matricula expResult = null; Matricula result = instance.getPre_inscripcion(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setPre_inscripcion method, of class Prematricula. */ @Test public void testSetPre_inscripcion() { System.out.println("setPre_inscripcion"); Matricula pre_inscripcion = null; Prematricula instance = null; instance.setPre_inscripcion(pre_inscripcion); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
Markdown
UTF-8
2,686
3.25
3
[]
no_license
# Machine Learning Project 1 - Higgs Boson Project 1 of the Machine Learning course given at the EPFL Fall 2020. ## Team Members - Marijn VAN DER MEER - Bradley MATHEZ - Timothée DURAN ## Idea: In this project, we implemented simple machine learning models: Least Squares Regression (Normal, with GD/SGD), Ridge Regression (Normal) and (Regularized) Logistic Regression with GD (c.f. `implementations.py`) . Furthermore, we optimized one of them, Logistic Regression to do binary classification on the Higgs Boson experiment challenge data-set (c.f. `run.py`). For this, before optimizing the model, we did some data pre-processing and feature engineering. Those steps can be seen in the helper function `pre_processing` in `helper_functions/helper_functions.py` and in our report. ## Structure of the repository: - `implementations.py`: contains implementations of Least Squares Regression (Normal, with GD/SGD), Ridge Regression (Normal) and (Regularized) Logistic Regression with GD - `run.py`: main executable to recreate our best score on AICrowd - `main.py`: user friendly executable to run other models than the one that gave the best performance - `project_1.ipynb`: notebook with plots for the report - `README.md` - **helper_functions/**: - `helper_functions.py`: helper functions needed to run the project - `losses.py`: different losses (MSE, Logisitic) and their gradients - `ml_methods_labs.py`: methods from the Machine Learning labs - **data/**: - `train.csv`: training data - `test.csv`: test data - `parameters.json`: JSON file with hyper-parameters for running different models in `main.py` - `parameters_best_model.json`: JSON fiel with parameters for best score - **results/**: Attention; the directories listed below could be inexistant if you have not run the `run.py` script. `run.py` creates them, otherwise you can create them on your own. - **predictions/**: labels predicted after training models - **plots/**: plots with evolution of training/validation losses - **weights/**: weights with best loss found during training ## Instructions to run: Python modules requirements: `numpy`, `matplotlib.pyplot`, `datetime`, `json`, `csv` and `os`. Predictions will be saved in `data/results/predictions/` and weights will be saved in `data/results/weights/`. To see plots of evolution of losses during training, see plots saved in `data/results/plots/` There are two methods to run our program. 1. To reproduce our best score with logistic regression that we submitted on [AIcrowd](https://www.aicrowd.com): ``` python run.py ``` 2. We did a small user-friendly interface to run our code with the other models. Please execute: ``` python main.py ```
C++
UTF-8
3,039
3.046875
3
[]
no_license
#include <Adafruit_NeoPixel.h> #define PIN 3 //pixel pin #define BUTTON_PIN 7 // button pin #define NUMPIXELS 16 Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); int helen = 100; // delay for half a second int oldState = 0; int showType = 0; void setup() { pinMode(BUTTON_PIN, INPUT); pixels.begin(); // This initializes the NeoPixel library. Serial.begin(9600); } void loop() { Serial.println(oldState); int newState = digitalRead(BUTTON_PIN); Serial.println(newState); if (newState == LOW && oldState == HIGH) { // Short delay to debounce button. delay(20); // Check if button is still low after debounce. newState = digitalRead(BUTTON_PIN); if (newState == LOW) { showType++; if (showType > 9) showType=0; startShow(showType); } } oldState = newState; } void startShow(int i) { switch(i){ case 0: colourWipe(pixels.Color(0, 0, 0)); // Black/off break; case 1: colourOpposite(255,0,0,0,255,0); // Red/green break; case 2: colourRotate(255,0,0); // Red break; case 3: colourWipe(pixels.Color(0, 0, 255)); // Blue break; case 4: colourOpposite(0,255,0,0,0,255); // green/blue break; case 5: colourWipe(pixels.Color(127,127,0)); //yellow break; case 6: colourRotate(255,255,255); break; case 7: colourOpposite(255,0,255,255,255,0); // purple yellowish break; case 8: colourRotate(0,0,255); break; case 9: colourWipe(pixels.Color(127,0,255)); // hbreak; } } void colourWipe(uint32_t c) { for(uint16_t i=0; i<pixels.numPixels(); i++) { pixels.setPixelColor(i, c); pixels.show(); delay(helen); } } void colourRotate(int r, int g, int b) { for(uint16_t i=0; i<pixels.numPixels(); i++) { pixels.setPixelColor(i, pixels.Color(0,0,0)); pixels.show(); } for(int i=0;i<NUMPIXELS;i++){ // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255 pixels.setPixelColor(i, pixels.Color(r,g,b)); // Moderately bright green color. pixels.show(); // This sends the updated pixel color to the hardware. delay(helen); pixels.setPixelColor(i, pixels.Color(0,0,0)); } } void colourOpposite(int r, int g, int b, int r2, int g2, int b2) { for(uint16_t i=0; i<pixels.numPixels(); i++) { pixels.setPixelColor(i, pixels.Color(0,0,0)); pixels.show(); } int j=NUMPIXELS/2; for(int i=0;i<NUMPIXELS;i++){ // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255 pixels.setPixelColor(i, pixels.Color(r,g,b)); // Moderately bright green color. pixels.setPixelColor(j, pixels.Color(r2,g2,b2)); // Moderately bright green color. pixels.show(); // This sends the updated pixel color to the hardware. delay(helen); pixels.setPixelColor(i, pixels.Color(0,0,0)); pixels.setPixelColor(j, pixels.Color(0,0,0)); j++; if (j>=NUMPIXELS) { j=0; } } }
Markdown
UTF-8
2,219
2.703125
3
[]
no_license
1. 启动 Apache 服务器 ``` sudo apachectl start ``` > 其他命令: > sudo apachectl restart:重启服务器 > sudo apachectl stop:停止服务器 2. 浏览器访问 __http://localhost__,显示 It works!,确认启动成功 ![](../assets/images/itWorks.png) 3. 修改 /etc/apache2/httpd.conf 1. 进入 /etc/apache2/,备份 httpd.conf ``` cd /etc/apache2/ sudo cp httpd.conf httpd.conf.bak ``` 2. 打开并修改 httpd.conf > 这里使用 vim ,可以用其他文本编辑器来打开和修改文件,比如 Sublime Text ``` sudo vim httpd.conf ``` 3. 在打开的 httpd.conf,查找 DocumentRoot,修改服务器根目录 > 可以不修改 DocumentRoot 对应的路径 ``` DocumentRoot "/Library/WebServer/Documents" <Directory "/Library/WebServer/Documents"> 修改为 DocumentRoot "自定义的目录" <Directory "自定义的目录"> ``` 4. 在第 3 步修改的地方下面,找到 “Options FollowSymLinks Multiviews” ``` Options FollowSymLinks Multiviews 插入 Indexes,修改为 Options Indexes FollowSymLinks Multiviews ``` 5. 修改 DocumentRoot 对应目录的 User 和 Group > 第 3 步中没有修改目录,可以略过这步,到第 6 步继续修改 ``` User _www Group _www 修改为 User “DocumentRoot 对应目录的属主” Group “DocumentRoot 对应目录的属主的用户组” ``` 6. 解注释 ``` #LoadModule rewrite_module libexec/apache2/mod_rewrite.so #LoadModule php7_module libexec/apache2/libphp7.so 去掉前面的 # ``` 4. 复制 php.ini 文件 > Mac 没有 php.ini,可以使用 php.ini.default > 拷贝之后,可以配置 php.ini 文件 ``` cp php.ini.default php.ini ``` 5. 最后,重启服务器 ``` sudo apachectl restart ``` 6. 修改成功之后,可以在服务器目录下放文件 ![](../assets/images/localhostDS.png)
Java
UTF-8
1,559
1.96875
2
[ "Apache-2.0" ]
permissive
package com.checkmarx.sdk.dto; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @JsonInclude(JsonInclude.Include.NON_NULL) public class Osa implements Serializable { @JsonProperty("fileExcludes") private String fileExcludes; @JsonProperty("folderExcludes") private String folderExcludes; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); private final static long serialVersionUID = -7121161780560758042L; @JsonProperty("fileExcludes") public String getFileExcludes() { return fileExcludes; } @JsonProperty("fileExcludes") public void setFileExcludes(String fileExcludes) { this.fileExcludes = fileExcludes; } @JsonProperty("folderExcludes") public String getFolderExcludes() { return folderExcludes; } @JsonProperty("folderExcludes") public void setFolderExcludes(String folderExcludes) { this.folderExcludes = folderExcludes; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
C++
UTF-8
442
2.90625
3
[]
no_license
#include<iostream> #include<bits/stdc++.h> using namespace std; void tower_of_h(long long n ,int from ,int dest ,int help) { if(n==1) { cout<<"Move "<<from <<" to "<<dest<<endl; return; } tower_of_h(n-1,from,help,dest); cout<<"Move "<<from <<" to "<<dest<<endl; tower_of_h(n-1,help,dest,from); } int main() { long long n; cin>>n; int f=1,h=3,d=2; tower_of_h(n,f,d,h); return 0; }
Java
UTF-8
157
1.90625
2
[]
no_license
package oob.fingerprinttest.Domain.Main.CheckUsernameStoredUseCase; public interface CheckUsernameStoredUseCaseRepositoryInterface { boolean check(); }
TypeScript
UTF-8
2,216
2.5625
3
[]
no_license
import {Injectable} from '@angular/core'; import {AvailableKurseMap, SetupStore} from './setup.store'; import {Kurs, Kurse} from '../../../../types/Kurs'; import {SetupQuery} from './setup.query'; import {serviceInCypress} from '../../../util'; @Injectable() export class SetupService { constructor(public store: SetupStore, public query: SetupQuery) { serviceInCypress(this); } lockName(name: string) { this.store.update({name}); } setAvailStufen(stufen: string[]) { this.store.update({available_stufen: stufen}); } setStufe(stufe: string) { this.store.update({stufe}); } setAvailableKurse(kurse: Kurse) { // sort array based on title field, where LKs are higher up than GKs kurse = kurse.sort(kurseSortFn); // convert to object // tslint:disable-next-line:variable-name const available_kurse: AvailableKurseMap = {}; kurse.forEach((k: Kurs) => { if (!available_kurse[k.title]) { available_kurse[k.title] = [k]; } else { available_kurse[k.title].push(k); } }); // add FREI Kurs for (const key of Object.keys(available_kurse)) { available_kurse[key] = [{fach: 'Frei', lehrer: '', title: key}, ...available_kurse[key]]; } // generate default indexes // tslint:disable-next-line:variable-name const selected_kurse_indexes = {}; for (const key of Object.keys(available_kurse)) { selected_kurse_indexes[key] = -1; } this.store.update({available_kurse, selected_kurse_indexes}); } changeSelectedStufeIndex(title: string, index: number) { const obj = Object.assign({}, this.query.getValue().selected_kurse_indexes); obj[title] = index; this.store.update({selected_kurse_indexes: obj}); } justRegistered() { this.store.update({justRegistered: true}); } } // sort array based on title field, where LKs are higher up than GKs export const kurseSortFn = (a: Kurs, b: Kurs) => { const AisLK = /^LK/.test(a.title); const BisLK = /^LK/.test(b.title); if (AisLK && !BisLK) { return -1; } else if (BisLK && !AisLK) { return 1; } else { // !AisLK && !BisLK return (a.title > b.title) ? 1 : ((a.title === b.title) ? 0 : -1); } };
C#
UTF-8
9,208
2.515625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using static SemanticType; using static RenderingOptions; class DrawInfo { public Argument Argument { get; } public int X { get; } public int Y { get; } public DrawInfo(Argument argument, int x, int y) { Argument = argument; X = x; Y = y; } } public class ExpressionContainer : MonoBehaviour { public Expression Expression; // Start is called before the first frame update void Start() { GenerateVisual(); } void Update() { transform.Rotate(0, 0, 10 * Mathf.Sin(Time.time * 10) * Time.deltaTime); } // Resizes the quad according to the dimensions of the // expression, and attaches a texture made by // drawing the expression recursively. void GenerateVisual() { int width = GetWidth(Expression); int height = GetHeight(Expression); gameObject.transform.localScale = new Vector3( gameObject.transform.localScale.x * width, gameObject.transform.localScale.y * height, gameObject.transform.localScale.z); // mipmap levels turned off. May want to turn this on later. var texture = new Texture2D(width * Scale, height * Scale); var drawStack = new Stack<DrawInfo>(); drawStack.Push(new DrawInfo(Expression, 0, 0)); bool isFirstLevel = true; while (drawStack.Count != 0) { DrawInfo currentDrawInfo = drawStack.Pop(); int currentWidth; int currentHeight; if (currentDrawInfo.Argument is Expression && !isFirstLevel) { currentWidth = SecondCallGetWidth((Expression) currentDrawInfo.Argument); currentHeight = SecondCallGetHeight((Expression) currentDrawInfo.Argument); } else { currentWidth = GetWidth(currentDrawInfo.Argument); currentHeight = GetHeight(currentDrawInfo.Argument); } int scaledHeight = height * Scale; int scaledCurrentX = currentDrawInfo.X * Scale; int scaledCurrentY = currentDrawInfo.Y * Scale; int scaledCurrentWidth = currentWidth * Scale; int scaledCurrentHeight = currentHeight * Scale; int endingY = scaledHeight - scaledCurrentY; int startingY = endingY - scaledCurrentHeight; int startingX = scaledCurrentX; int endingX = startingX + scaledCurrentWidth; if (ReadVertically) { Debug.Log("ReadVertically: Not yet working. Defaulting to horizontal reading order."); // TODO (the previous code swaps the key variables) } // fill with the color of the expression's semantic type. for (int y = startingY; y < endingY; y++) { for (int x = startingX; x < endingX; x++) { SemanticType fillType = currentDrawInfo.Argument.Type; if (RenderingOptions.FillMode == FillMode.Complete) { // already set } if (RenderingOptions.FillMode == FillMode.Output && fillType is FunctionalType && currentDrawInfo.Argument is Expression && isFirstLevel) { fillType = ((FunctionalType) fillType).Output; } if (RenderingOptions.FillMode == FillMode.Head && currentDrawInfo.Argument is Expression) { fillType = ((Expression) currentDrawInfo.Argument).Head.Type; } Color typeColor = ColorsByType[fillType] - new Color(0, 0, 0, FillTransparency); texture.SetPixel(x, y, typeColor); } } // northern border and southern border for (int y = startingY; y < startingY + BorderSize; y++) { for (int x = startingX; x < endingX; x++) { Color typeColor = ColorsByType[currentDrawInfo.Argument.Type] - new Color(0, 0, 0, BorderTransparency); // northern border texture.SetPixel(x, y + scaledCurrentHeight - BorderSize, typeColor); // southern border texture.SetPixel(x, y, typeColor); } } // eastern and western border for (int y = startingY; y < endingY; y++) { for (int x = startingX; x < startingX + BorderSize; x++) { Color typeColor = ColorsByType[currentDrawInfo.Argument.Type] - new Color(0, 0, 0, BorderTransparency); // west border texture.SetPixel(x, y, typeColor); // east border texture.SetPixel(x + scaledCurrentWidth - BorderSize, y, typeColor); } } // We're at an empty argument slot. Nothing left to do here. // @Note: we could draw the inaccessible argument slot, but that // involves more changes than I want to make. if (currentDrawInfo.Argument is Empty) { continue; } Expression currentExpression = (Expression) currentDrawInfo.Argument; var head = ((Expression) currentDrawInfo.Argument).Head; var nameString = head is Name ? ((Name) head).ID : ""; Texture2D headTexture = Resources.Load<Texture2D>("Textures/Symbols/" + nameString); // if we're an expression, we want to draw the head symbol // @Note this has to be in a specific RGBA format to work. if (headTexture != null) { int symbolSize = Scale - BorderSize * 2; // @Note Unity is being picky about these. // Seems like we just have give a texture of the // right size and format for now. // headTexture.Resize(Scale - BorderSize * 2, Scale - BorderSize * 2); // headTexture.Apply(); int xOffset = 0; if (HeadSymbolPosition == Position.Left) { xOffset = 0; } if (HeadSymbolPosition == Position.Center) { xOffset = (currentWidth / 2) * Scale; if (currentWidth % 2 == 0) { xOffset -= Scale / 2; } } if (HeadSymbolPosition == Position.Right) { xOffset = (currentWidth - 1) * Scale; } for (int y = 0; y < symbolSize; y++) { for (int x = 0; x < symbolSize; x++) { Color headPixelColor = headTexture.GetPixel(x, y) - new Color(0, 0, 0, BorderTransparency); if (headPixelColor.a > 0) { texture.SetPixel( startingX + xOffset + x + BorderSize, -Scale + startingY + scaledCurrentHeight + y + BorderSize, headPixelColor); } } } } if (currentDrawInfo.Argument is Empty) { continue; } // Now, we push the arguments on to the draw stack. var nextX = currentDrawInfo.X; if (DrawFirstArgumentDiagonally && HeadSymbolPosition != Position.Right) { nextX++; } if (DrawInaccessibleArgumentSlot) { Debug.Log("DrawInaccessibleArgumentSlot: not implemented yet. Default to not drawing it."); } // We only skip empties if all arguments are empty. bool canSkipEmpties = true; for (int i = 0; i < currentExpression.NumArgs; i++) { if (currentExpression.GetArg(i) is Expression) { canSkipEmpties = false; break; } } for (int i = 0; i < currentExpression.NumArgs; i++) { var arg = currentExpression.GetArg(i); // we skip moving forward, because we won't draw this empty slot. if (arg is Empty && !isFirstLevel) { if (!canSkipEmpties) { nextX++; } continue; } drawStack.Push(new DrawInfo(arg, nextX, currentDrawInfo.Y + 1)); if (arg is Expression) { nextX += SecondCallGetWidth((Expression) arg); } else { nextX += GetWidth(arg); } } isFirstLevel = false; } texture.Apply(); GetComponent<Renderer>().material.mainTexture = texture; } }
JavaScript
UTF-8
530
2.578125
3
[]
no_license
var url = require('url'); // var urlObj = { // protocol: 'http:', // slashes: true, // hostname: 'baidu.com', // port: 80, // pathname:'index', // hash: '#home', // search: '?search=aiqiyi', // path: '/nodejs?search=aiqiyi' // } /* url字符串 ===> url Object parse url Object ===> url字符串 format */ var u = "http://user:pass@host.com:8080/p/a/t/h?query=string#hash"; var urlObj = url.parse(u) urlObj.hash="#home" // console.log(urlObj) console.log(url.format(urlObj))
JavaScript
UTF-8
2,633
2.65625
3
[]
no_license
import React, { Component } from "react"; import SongForm from "./components/SongForm"; import SongList from "./components/SongList"; import SongFilter from "./components/SongFilter"; import NavBar from "./components/NavBar"; import Background from "./components/Background"; import "./css/SongOverview.css"; class SongOverview extends Component { constructor() { super(); this.state = { songs: [ { id: 100, title: "Therefore I am", artist: "Billie Eilish", genre: "indie", rating: 5, }, { id: 101, title: "Fountain", artist: "Ionnalee", genre: "pop", rating: 2, }, { id: 102, title: "The Rose", artist: "Lakshmi", genre: "indie", rating: 3, }, { id: 103, title: "bla", artist: "BLACKPINK", genre: "rock", rating: 2, }, { id: 104, title: "Therefore I am", artist: "Billie Eilish", genre: "indie", rating: 5, }, ], byGenre: "default", byRating: "default", azArtist: false, azSong: false, }; this.deleteSong = this.deleteSong.bind(this); this.addSong = this.addSong.bind(this); this.onInput = this.onInput.bind(this); } addSong = (song) => { song.id = this.state.songs.length + Math.floor(Math.random() * 10000); this.setState({ songs: this.state.songs.concat(song) }); }; deleteSong = (event) => { let songId = event.target.id; let songToDelete = this.state.songs.filter( (song) => song.id === parseInt(songId) ); let indexOfSong = this.state.songs.indexOf(songToDelete[0]); this.setState((prevState) => { let songsList = [...prevState.songs]; songsList.splice(indexOfSong, 1); let newState = { ...prevState, songs: songsList }; return newState; }); }; onInput = (event) => { const { name, value, type, checked } = event.target; type === "checkbox" ? this.setState({ [name]: checked, }) : this.setState({ [name]: value }); //console.log(this.state); }; render() { return ( <div className="App-body app-grid"> <NavBar /> <Background /> <SongForm addSong={this.addSong} onInput={this.onInput} /> <SongList songsAndFilter={this.state} deleteSong={this.deleteSong} /> <SongFilter filter={this.state} onInput={this.onInput} /> </div> ); } } export default SongOverview;
Java
UTF-8
1,642
2.5
2
[]
no_license
package course.labs.activitylab; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class ActivityTwo extends SuperActivity { // String for LogCat documentation private final static String TAG = "Lab-ActivityTwo"; // Lifecycle counters @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_two); init(savedInstanceState); Button closeButton = (Button) findViewById(R.id.bClose); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); // Emit LogCat message Log.i(TAG, "Entered the onCreate() method"); } // Lifecycle callback methods overrides @Override public void onStart() { super.onStart(); // Emit LogCat message Log.i(TAG, "Entered the onStart() method"); } @Override public void onResume() { super.onResume(); // Emit LogCat message Log.i(TAG, "Entered the onResume() method"); } @Override public void onPause() { super.onPause(); // Emit LogCat message Log.i(TAG, "Entered the onPause() method"); } @Override public void onStop() { super.onStop(); // Emit LogCat message Log.i(TAG, "Entered the onStop() method"); } @Override public void onRestart() { super.onRestart(); // Emit LogCat message Log.i(TAG, "Entered the onRestart() method"); } @Override public void onDestroy() { super.onDestroy(); // Emit LogCat message Log.i(TAG, "Entered the onDestroy() method"); } }
SQL
UTF-8
1,337
4.28125
4
[]
no_license
#table: company #Member_id, Company, Year_Start #1, Microsoft, 2000 #1, Google, 2006 #1, Facebook, 2012 #2, Microsoft, 2001. more info on 1point3acres.com #2, Oracle, 2004 #2, Google, 2007 #... -- how many members ever moved from Microsoft to Google? (both member #1 and member #2 count) SELECT COUNT(DISTINCT c1.Member_id) FROM company c1 AND company c2 WHERE c1.Member_id = c2.Member_id AND c1.Company = 'Microsoft' AND c2.Company = 'Google' AND c1.Year_Start < c2.Year_Start # deal with the cases when years are equal SELECT COUNT(DISTINCT c1.Member_id) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY Company) AS Row_Number FROM company) c1 AND (SELECT *, ROW_NUMBER() OVER (PARTITION BY Company) AS Row_Number FROM company) c2 WHERE c1.Member_id = c2.Member_id AND c1.Company = 'Microsoft' AND c2.Company = 'Google' AND c1.Row_Number < c2.Row_Number -- how many members moved directly from Microsoft to Google? (Member 2 does not count since Microsoft -> Oracle -> Google) SELECT COUNT(DISTINCT c1.Member_id) FROM company c1 AND company c2 WHERE c1.Member_id = c2.Member_id AND c1.Company = 'Microsoft' AND c2.Company = 'Google' AND c1.Year_Start < c2.Year_Start AND NOT EXIST( SELECT c3.Member_id FROM company c3 WHERE c3.Member_id = c1.Member_id AND c3.Year_Start > c1.Year_Start AND c3.Year_Start < c2.Year_Start )
Shell
UTF-8
500
3.390625
3
[ "MIT" ]
permissive
#!/bin/sh # Add a user's IP address to the EdgeOS Firewall # e.g. ./lan-auth.sh 48 oliverw92 192.168.0.82 echo "$@$@" ################ # START CONFIG # AUTH_GROUP=authed_lan_users # END CONFIG # ################ # Execute commands without running configure run=/opt/vyatta/sbin/vyatta-cfg-cmd-wrapper # Go into config mode $run begin # Add users IP to firewall group $run set firewall group address-group $AUTH_GROUP address $3 echo "Added $3 to $AUTH_GROUP" # Commit $run commit $run end
Python
UTF-8
3,717
2.5625
3
[]
no_license
# -*- coding=utf-8 -*- import os import sys import numpy as np import keras from keras.preprocessing import image from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.optimizers import RMSprop import resnet IMG_HEIGHT = 320 IMG_WIDTH = 240 IMG_IS_COLOR = True if IMG_IS_COLOR == True: IMG_COLOR = 3 else: IMG_COLOR = 1 def load_misawa(): path = "../crawler/images/" target_dirs = ["masa(34)", "KAZ(32)", "キング(20)", "ソドム(29)"] x_train, y_train, x_test, y_test = [], [], [], [] for ans, d in enumerate(target_dirs): target_chara = os.path.join(path, d) for i, file in enumerate(os.listdir(target_chara)): p = os.path.join(target_chara,file) img = image.load_img(p, target_size=(IMG_HEIGHT, IMG_WIDTH), grayscale=not(IMG_IS_COLOR)) imgary = image.img_to_array(img) if i%9 == 0: x_test.append(imgary) y_test.append(ans) else: x_train.append(imgary) y_train.append(ans) return (np.array(x_train), np.array(y_train)), (np.array(x_test), np.array(y_test)) (x_train, y_train), (x_test, y_test) = load_misawa() #x_train = x_train.reshape(x_train.shape[0], -1) #x_test = x_test.reshape(x_test.shape[0], -1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') num_classes = 4 y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) # acc: 18 def simple_model(): model = Sequential() model.add(Dense(512, activation='relu', input_shape=(IMG_HEIGHT*IMG_WIDTH*IMG_COLOR,))) model.add(Dropout(0.2)) model.add(Dense(512, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(num_classes, activation='softmax')) return model def conv_model(): model = Sequential() model.add(Conv2D(32, kernel_size=(11, 11), activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH, IMG_COLOR))) model.add(Conv2D(64, (11, 11), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) return model #model = simple_model() #model = conv_model() model = resnet.ResnetBuilder.build_resnet_18((IMG_COLOR, IMG_HEIGHT, IMG_WIDTH), 4) model.summary() model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy']) datagen = image.ImageDataGenerator( width_shift_range=0.2, height_shift_range=0.2 ) datagen.fit(x_train) batch_size = 128 steps_per_epoch = 30 epochs = 10 # history = model.fit(x_train, y_train, # batch_size=batch_size, # epochs=epochs, # verbose=1, # validation_data=(x_test, y_test)) history = model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size), steps_per_epoch=steps_per_epoch, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) model.save("./misawa.h5") # Convolution2Dにする # Data Augument(flip, zoom, move)をする # DeepLearingモデルを使う
PHP
UTF-8
1,206
2.71875
3
[ "MIT" ]
permissive
<?php namespace FSQL\Queries\AlterTableActions; use FSQL\Environment; use FSQL\Functions; class SetDataType extends BaseAction { private $tableName; private $columnName; private $type; public function __construct(Environment $environment, array $tableName, $columnName, $type, Functions $functions) { parent:: __construct($environment); $this->tableName = $tableName; $this->columnName = $columnName; $this->type = $type; $this->functions = $functions; } public function execute() { $table = $this->environment->find_table($this->tableName); if ($table === false) { return false; } $columns = $table->getColumns(); $columnIndex = array_search($this->columnName, array_keys($columns)); $columns[$this->columnName]['type'] = $this->type; $table->setColumns($columns); $cursor = $table->getWriteCursor(); foreach($cursor as $entry) { $newValue = $this->functions->cast($entry[$columnIndex], $this->type); $cursor->updateRow([$columnIndex => $newValue]); } $table->commit(); return true; } }
PHP
UTF-8
1,633
2.9375
3
[ "MIT" ]
permissive
function runQuery() { global $global_data; $runner = new QueryRunner(); $data = $runner->process(); return $data; } class QueryRunner { /** * @var DBBase */ private $db; public function process() { global $jQuery, $window; try { switch($jQuery('#dbtype')->val()) { case 'postgres': $this->db = new PostgreSQL(); break; case 'mysql': default: $this->db = new MySQL(); break; } $this->logMessage('using '.$jQuery('#dbtype')->val()); $this->connect(); $this->logMessage('connected'); $start = microtime(true); $this->execute(); $this->logMessage('query finished in '.round(microtime(true)-$start, 4).' s'); $data = $this->db->getResultAsArray(); return $data; } catch(Exception $e) { $this->logMessage($e->getMessage()); $window->alert('failed'); } } private function execute() { global $jQuery, $window; $query = $jQuery('#sql')->val(); $this->db->execute($query); } /** * connects to the database * * @return bool */ private function connect() { global $jQuery, $window; $dbuser = $jQuery('#dbuser')->val(); $dbpass = $jQuery('#dbpass')->val(); $dbhost = $jQuery('#dbhost')->val(); $dbname = $jQuery('#dbname')->val(); if(empty($dbuser) || empty($dbhost) || empty($dbname)) { throw new Exception('db credentials are invalid'); return false; } return $this->db->connect($dbhost, $dbname, $dbuser, $dbpass); } /** * log message to the console field * * @param $msg */ private function logMessage($msg) { global $jQuery; $jQuery('#console')->append('<span>'.$msg.'</span>'); } }
Python
UTF-8
1,660
3.03125
3
[]
no_license
''' Created on 02.12.2011 @author: christian.winkelmann@plista.com ''' import math import random class histogramm(object): def __init__(self, binnum = 5, min = 0, max = 2 ): self.binnum = binnum self.minx = min self.maxx = max self.histogram = {} def binify_real(self, list): diff = self.maxx - self.minx self.binsize = float(diff) / float(self.binnum) for i in xrange(self.binnum): self.histogram[i] = 0 for l in list: binindex = math.floor( (l / self.binsize)) self.histogram[binindex] += 1 def binify_categorial(self, dict): """@param dict: dictionary of categorial data """ for k,i in dict.items(): try : self.histogram[k] += i except KeyError: self.histogram[k] = i def get_histogramm(self, sorted = False): for k, i in self.histogram.items(): self.histogram[k] = round(i,3) if ( sorted == False ) :return self.histogram else: return self.sortedDictValues2( self.histogram ) # a further slight speed-up on my box # is to map a bound-method: def sortedDictValues3(self, adict): keys = adict.keys() keys.sort() return map(adict.get, keys) # an alternative implementation, which # happens to run a bit faster for large # dictionaries on my machine: def sortedDictValues2(self, adict): keys = adict.keys() keys.sort() return [dict[key] for key in keys] if __name__ == '__main__': """ """
Java
UTF-8
8,804
2.359375
2
[]
no_license
package com.wcedla.wcedlaweather.view; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.animation.LinearInterpolator; import com.wcedla.wcedlaweather.R; import static org.litepal.LitePalBase.TAG; public class SwitchButton extends View { TypedArray array; Paint myPaint; Paint circlePaint; Path myPath; int width, height; float density; int shapeColor; int circleColor; ValueAnimator slideAnimator; float changeLength; float startPosition; float circleRadius; public boolean isSelect() { return isSelect; } public void setSelect(boolean select) { isSelect = select; } boolean isSelect = true; public SwitchButton(Context context) { this(context, null); } public SwitchButton(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SwitchButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SwitchButton, defStyleAttr, 0); initData();//初始化各种属性 array.recycle();//注意回收内存,防止内存泄漏 } private void initData() { shapeColor = array.getColor(R.styleable.SwitchButton_ShapeColor, Color.LTGRAY);//获取底层圆条颜色 circleColor = array.getColor(R.styleable.SwitchButton_CircleColor, Color.GREEN);//获取圆条里面的圆的颜色 Log.d(TAG, "initData: "+circleColor); DisplayMetrics outMetrics = getResources().getDisplayMetrics();//获取屏幕的参数矩阵 width = outMetrics.widthPixels;//获取屏幕宽度 height = outMetrics.heightPixels;//获取屏幕高度 density = outMetrics.density;//获取屏幕像素 myPaint = new Paint();//初始化底层圆条的画笔 circlePaint = new Paint();//初始化圆条里面的圆的画笔 myPath = new Path();//初始化圆条的两条横线 myPaint.setAntiAlias(true); myPaint.setDither(true); myPaint.setColor(shapeColor); myPaint.setStyle(Paint.Style.STROKE); myPaint.setStrokeWidth(5); circlePaint.setStyle(Paint.Style.FILL); circlePaint.setAntiAlias(true); circlePaint.setDither(true); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int mywidth, myheight; mywidth = getMySize(50 * (int) density, widthMeasureSpec); myheight = getMySize(25 * (int) density, heightMeasureSpec);//懒得具体测算了,25px差不多刚好了 mywidth = mywidth + getPaddingLeft() + getPaddingRight(); myheight = myheight + getPaddingTop() + getPaddingBottom(); setMeasuredDimension(mywidth, myheight); } private int getMySize(int defaultSize, int measureSpec) { int mySize = defaultSize; int mode = MeasureSpec.getMode(measureSpec); int size = MeasureSpec.getSize(measureSpec); switch (mode) { case MeasureSpec.UNSPECIFIED: {//如果没有指定大小,就设置为默认大小 mySize = defaultSize; break; } case MeasureSpec.AT_MOST: {//如果测量模式是wrap_content,取值为父view给定最大大小和默认大小的小得那个 mySize = Math.min(defaultSize, size); break; } case MeasureSpec.EXACTLY: {//如果是固定的大小,那就不要去改变它,match_parent和指定具体大小 mySize = size; break; } } return mySize; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawShape(canvas); drawCircle(canvas); } /** * 画底层圆条的方法 * * @param canvas */ private void drawShape(Canvas canvas) { //初始化前面的半圆和后面的半圆的矩形,并使用画椭圆的方法画出两个半圆,然后使用path的lineto连接两个半圆 RectF frontRectf = new RectF(density * 2, density * 2, density * 22, density * 22); canvas.drawArc(frontRectf, 90, 180, false, myPaint); RectF backRectf = new RectF(density * 28, density * 2, density * 48, density * 22); canvas.drawArc(backRectf, 270, 180, false, myPaint); myPath.moveTo(density * 12, density * 2); myPath.lineTo(density * 38, density * 2); myPath.moveTo(density * 12, density * 22); myPath.lineTo(density * 38, density * 22); canvas.drawPath(myPath, myPaint); } /** * 画圆条里面的圆的方法 * * @param canvas */ private void drawCircle(Canvas canvas) { if (startPosition == 0)//就是一开始并未触发动画的时候,就是当前未改变状态时 { if (isSelect)//如果当前状态是打开状态 { circlePaint.setColor(circleColor); canvas.drawCircle(38 * density, 12 * density, 7 * density, circlePaint); } else//如果当前是关闭状态 { circlePaint.setColor(Color.LTGRAY); canvas.drawCircle(12 * density, 12 * density, 7 * density, circlePaint); } } //如果触发了动画,就是需要更改状态了,就开始动态改变圆条里面的圆形的x轴位置以及半径 else if (startPosition > 0) { canvas.drawCircle(changeLength, 12 * density, circleRadius * density, circlePaint); } } /** * 状态改变时的动画 * * @param startPosition 开始x轴位置 * @param destPosition 结束x轴位置 * @param duration 动画时间 */ private void setAnimation(float startPosition, float destPosition, int duration) { if (slideAnimator != null)//如果之前已经有动画了,就先关闭动画,就是你快速切换状态时的情况 slideAnimator.cancel(); slideAnimator = ValueAnimator.ofFloat(startPosition, destPosition); slideAnimator.setDuration(duration); slideAnimator.setTarget(destPosition); slideAnimator.setInterpolator(new LinearInterpolator());//线性差速器 this.startPosition = startPosition;//保存开始x轴位置用来判断是否开启了动画 slideAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { //每次移动结束后的x轴位置 changeLength = (float) animation.getAnimatedValue();//变换的度数 invalidateView();//改变绘制条件 } }); slideAnimator.start();//开启动画 } /** * 计算绘制圆条里面的圆形的位置以及半径 */ private void invalidateView() { //根据位置获取圆的半径,获取两圆心之间的距离的一半,然后在计算成具体的半径值 circleRadius = Math.round(Math.abs((changeLength - 25 * density) / (2 * density))); if (changeLength < 25 * density)//如果是打开状态到关闭状态时画灰色的圆 { circlePaint.setColor(Color.LTGRAY); } else if (changeLength > 25 * density)//如果是从关闭状态到打开状态时,根据设置的颜色绘制圆形 { circlePaint.setColor(circleColor); } //Log.d(TAG, "圆半径"+circleRadius); invalidate();//重绘图形 } /** * 外部接口,用于设置滑动按钮的状态 * * @param checked 状态,true或者false */ public void setCheck(boolean checked) { if (!isSelect)//如果当前是关闭状态 { //更改状态为打开状态 if (checked) { isSelect = true;//置标志位为true setAnimation(12 * density, 38 * density, 300); } } else if (isSelect)//如果当前状态时打开状态 { //更改状态为关闭状态 if (!checked) { isSelect = false;//标志位置false setAnimation(38 * density, 12 * density, 300); } } } }
C++
UTF-8
466
3.734375
4
[]
no_license
#include <iostream> using namespace std; class Stack { private: int* arr; int size; public: Stack() { arr = new int(); size = 0; } ~Stack() { size = -1; delete arr; } void push(int a) { arr[size++] = a; } int pop() { if(size >= 0) { return arr[--size]; } } void dump() { for(int i = 0; i < size; i++) { cout << arr[i] << endl; } } int getSize() { return size; } };
Python
UTF-8
1,783
2.578125
3
[]
no_license
import os import shutil import re # Variables ALL_SUBMISSIONS = 'lab3-submissions.zip' ROLL_LIST = 'Lab3/roll_list.txt' EXTRACT_DIR = 'Lab3/my_batch' # Name of submission archive # Keep as generic as possible unless strictly specified beforehand # ?: is for not capturing that bracket as a group SUBMISSION_NAME = re.compile('(?:la3|lab3)-([a-zA-Z0-9]+)\.(zip|tar\.gz|tgz)', re.IGNORECASE) if __name__ == '__main__': # Read roll numbers to grade with open(ROLL_LIST, 'r') as f: temp = f.readlines() my_roll_numbers = [r.strip() for r in temp] carry_over = {r:1 for r in my_roll_numbers} # Unpack submissions in EXTRACT_DIR shutil.unpack_archive(filename=ALL_SUBMISSIONS, extract_dir=EXTRACT_DIR) # Convert folder names to roll-no for stud_dir in os.listdir(EXTRACT_DIR): for file in os.listdir(os.path.join(EXTRACT_DIR, stud_dir)): m = SUBMISSION_NAME.match(file) if m is not None: roll_no = m.group(1) if roll_no in my_roll_numbers: try: carry_over[roll_no] = 0 shutil.unpack_archive( filename=os.path.join(EXTRACT_DIR, stud_dir, file), extract_dir=EXTRACT_DIR ) shutil.move( src=os.path.join(EXTRACT_DIR, file.split('.')[0]), dst=os.path.join(EXTRACT_DIR, roll_no) ) except: print('Name: %s, Roll no.: %s, error in unpacking/moving' % \ (stud_dir.split('_')[0], roll_no)) break shutil.rmtree(os.path.join(EXTRACT_DIR, stud_dir)) # Write submission status to TSV # By default assumes wrong submission name as no submission # In such a case, manually change this TSV later with open('submission_status.tsv', 'w') as f: f.write('ID\tCarry Over\tWrong Submission\n') for r in my_roll_numbers: f.write('%s\t%d\t%d\n' % (r, carry_over[r], 0))
C
UTF-8
2,505
2.59375
3
[]
no_license
/* * strPool.c * * Created on: 2011-1-18 * Author: wuyulun */ #include "../inc/config.h" #include "strPool.h" #include "str.h" #ifdef NBK_MEM_TEST int strPool_memUsed(const NStrPool* pool) { int size = 0; if (pool) { size += sizeof(NStrPool); if (pool->head) { NSPCell* p = pool->head; do { size += sizeof(NSPCell); p = p->next; } while (p); } if (pool->ls) { char* p = sll_first(pool->ls); while (p) { size += nbk_strlen(p) + 1; p = sll_next(pool->ls); } } } return size; } #endif NStrPool* strPool_create(void) { NStrPool* p = (NStrPool*)NBK_malloc0(sizeof(NStrPool)); N_ASSERT(p); return p; } void strPool_delete(NStrPool** pool) { NStrPool* t = *pool; strPool_reset(t); NBK_free(t); *pool = N_NULL; } void strPool_reset(NStrPool* pool) { NSPCell* c = pool->head; NSPCell* t; while (c) { t = c; c = c->next; NBK_free(t); } pool->head = N_NULL; pool->cur = N_NULL; if (pool->ls) { char* s = sll_first(pool->ls); while (s) { NBK_free(s); s = sll_next(pool->ls); } sll_delete(&pool->ls); } } char* strPool_save(NStrPool* pool, const char* str, int length) { char* tooFar; char* rt; if (pool->head == N_NULL) { pool->head = (NSPCell*)NBK_malloc(sizeof(NSPCell)); pool->head->p = pool->head->s; pool->head->next = N_NULL; pool->cur = pool->head; } tooFar = pool->cur->s + STR_POOL_SIZE; length = (length == -1) ? nbk_strlen(str) : length; if (length >= STR_POOL_SIZE) { char* s; if (pool->ls == N_NULL) pool->ls = sll_create(); s = (char*)NBK_malloc(length + 1); nbk_strcpy(s, str); sll_append(pool->ls, s); return s; } if (tooFar - pool->cur->p < length + 1) { NSPCell* cell = (NSPCell*)NBK_malloc(sizeof(NSPCell)); cell->p = cell->s; cell->next = N_NULL; pool->cur->next = cell; pool->cur = cell; } rt = pool->cur->p; nbk_strncpy(rt, str, length); pool->cur->p += length + 1; return rt; }
Java
UTF-8
178
1.789063
2
[]
no_license
package pokerHelper.strategy; import pokerHelper.core.Card; public class StartPositionHandler { public StartPositionHandler(int Position, Card card1, Card card2){ } }
Java
UTF-8
1,005
4.1875
4
[]
no_license
import java.util.Scanner; public class P6_3 { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.print("Enter a number to see if it is a palindrome: "); int num = input.nextInt(); boolean isPalindrome = isPalindrome(num) ; if (isPalindrome == true) { System.out.print(num + " is a palindrome"); } else { System.out.print(num + " is not a palindrome"); } } //Reverse Method - Reverses number and returns the reversed number public static int reverse(int number) { int palindrome = number; int reversedNum = 0; int remainder = 0; while(palindrome != 0) { remainder = palindrome % 10; reversedNum = reversedNum * 10 + remainder; palindrome = palindrome / 10; } return reversedNum; } //isPalindrome Method - Returns a Boolean Value for whether or not the number is a palindrome public static boolean isPalindrome(int number) { int reversedNum = reverse(number); if (reversedNum == number) { return true; } else { return false; } } }
C++
UTF-8
753
3.25
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: struct pointer { ListNode *node = nullptr; bool has_changed_list = false; }; ListNode *getIntersectionNode(ListNode *l1, ListNode *l2) { if (l1 == nullptr || l2 == nullptr) return nullptr; pointer a{l1}, b{l2}; while (a.node && b.node) { if (a.node == b.node) return a.node; if (!a.node->next && !a.has_changed_list) a = {l2, true}; else a.node = a.node->next; if (!b.node->next && !b.has_changed_list) b = {l1, true}; else b.node = b.node->next; } return nullptr; } };
Java
UTF-8
558
1.882813
2
[]
no_license
package com.kevinguanchedarias.owgejava; import io.restassured.http.ContentType; import io.restassured.module.mockmvc.RestAssuredMockMvc; import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification; import lombok.experimental.UtilityClass; import java.nio.charset.StandardCharsets; @UtilityClass public class RestTestUtils { public static MockMvcRequestSpecification restGiven() { return RestAssuredMockMvc .given() .contentType(ContentType.JSON.withCharset(StandardCharsets.UTF_8)); } }
Java
UTF-8
1,361
2.34375
2
[]
no_license
package com.heverage.zhanyebao.client.model; import android.os.Parcel; import android.os.Parcelable; public class Address implements Parcelable{ private int addressType; private String region; private String address; public int getAddressType() { return addressType; } public void setAddressType(int addressType) { this.addressType = addressType; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int flags) { // TODO Auto-generated method stub dest.writeInt(addressType); dest.writeString(region); dest.writeString(address); } public static final Parcelable.Creator<Address> CREATOR = new Creator<Address>() { public Address createFromParcel(Parcel source) { Address ue = new Address(); ue.addressType = source.readInt(); ue.region = source.readString(); ue.address = source.readString(); return ue; } public Address[] newArray(int size) { return new Address[size]; } }; }
Java
UTF-8
2,467
2.25
2
[ "Apache-2.0" ]
permissive
package com.huangjie.sell.controller; import com.huangjie.sell.VO.ProductInfoVO; import com.huangjie.sell.VO.ProductVO; import com.huangjie.sell.VO.ResultVO; import com.huangjie.sell.dataobject.ProductCategory; import com.huangjie.sell.dataobject.ProductInfo; import com.huangjie.sell.service.ProductCategoryService; import com.huangjie.sell.service.ProductInfoService; import com.huangjie.sell.utils.ResultVOUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Created by huangjie on 2019/7/19. */ @RestController @RequestMapping("buyer/product") public class BuyerProductController { @Autowired private ProductInfoService productInfoService; @Autowired private ProductCategoryService categoryService; @GetMapping("list") public ResultVO list() { //查询所有的上架的商品列表 List<ProductInfo> productInfoList = productInfoService.findUpAll(); List<Integer> categoryList = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList()); List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryList); List<ProductVO> productVOList = new ArrayList<>(); for (ProductCategory productCategory : productCategoryList) { ProductVO productVO = new ProductVO(); productVO.setCategoryName(productCategory.getCategoryName()); productVO.setCategoryType(productCategory.getCategoryType()); List<ProductInfoVO> productInfoVOList = new ArrayList<>(); for (ProductInfo productInfo : productInfoList) { if (productInfo.getCategoryType() == productCategory.getCategoryType()) { ProductInfoVO productInfoVO = new ProductInfoVO(); BeanUtils.copyProperties(productInfo, productInfoVO); productInfoVOList.add(productInfoVO); } } productVO.setProductInfoList(productInfoVOList); productVOList.add(productVO); } return ResultVOUtils.success(productVOList); } }
C++
UTF-8
4,408
3.109375
3
[]
no_license
/* Simple calculator Revision history: Originally written by Mei Shuyao April 2020 Second editon by Mei Shuyao April 2020 Third edition by Mei Shuyao May 2020 This program implements a basic expression calculator. Designed for pyhsics and engineering cases. Support user_defined variable and function. Support solving equation and tabling. Support io to and from file. The grammar for input is: Input: File Claculate Calculate: Statement Print Quit Help Calculation Statement Statement: Declaration variable/function Expression Table Solving equation Sum Declaration: "let" Name "=" Expression "set" Name "=" Expression "delete" Name "let" Function name "=" Expression "delete" Function name Expression: Term Expression"+"Term Expression"-"Term Term: U_primary Term"*"U_primary Term"/"U_primary Term"%"U_primary U_primary: Primary U_primary"^"Primary U_Primary"!" U_Primary"deg" Primary: Number Variable "Function("Expression")" "("Expression")" "-"Primary "+"Primary Input comes from a string through the Token_stream called ts. Variables stored in Dictionary called var_table; Functions stored in a structure called func_table; */ #include "calculate.h" using namespace std; string getstr(istream* ip) //读入一行,以'\n'或';'结尾 { if (ip == nullptr) ip = &cin; string s; char c; while ((c = ip->get()) != '\n'&&c!=';') { if (c == EOF) //or EOF,返回一个flag return "%file end"; s += c; } s += ';'; if (s == ";") s = getstr(ip); //空字符串递归调用 return s; } int main() try { cout << "Welcome to simple calculator.\n"; cout << "Enter to calculate.\nEnter \"help\" for help.\n\n"; ifstream* ip = nullptr; ip = new ifstream("./settings.txt"); if(*ip) while (true) { string s = getstr(ip); if (s== "%file end") break; calculate(s, ip); } delete ip; ip = nullptr; ofstream* op = nullptr; vector<string>error_list; //在文件中遇到错误方便退出 init_error_list(error_list); while (true) { if (ip != nullptr) //判断是否在文件内 { //在文件内 string s = getstr(ip); if (s == "file;") //文件内出现"file"报错 { cout << "can't open a file in a file!!!\n"; ip->close(); delete ip; ip = nullptr; continue; } if (s == "%file end") //文件结尾,关闭文件 { ip->close(); delete ip; ip = nullptr; continue; } string ans = calculate(s, ip); //计算 for (int i = 0; i < error_list.size(); i++) //判断计算返回结果是否为报错 { if (error_list[i] == ans) { ip->close(); delete ip; ip = nullptr; continue; } } if (op == nullptr) //输出 cout <<">>"<< s<<endl<< ans<< endl; //输出到控制台 else { //输出到文件 (*op) << ">>" << s << endl << ans << endl; cout << ">>" << s << endl << ans << endl; } } else //文件外 { cout << ">>"; string s = getstr(ip); if (s == "file;") //判断关键字"file" { cout << "input or output:"; string mode; cin >> mode; if (mode == "i" || mode == "input" || mode == "in") //打开输入文件 { cout << "input path:"; string ipath; cin >> ipath; ip = new ifstream(ipath.c_str()); if (!(*ip)) cout << "can't open file" << endl; } else if (mode == "o" || mode == "output" || mode == "out") //打开或创建输出文件 { cout << "output path:"; string opath; cin >> opath; if (opath == "cout") //若为cout则改回输出到控制台 { op->close(); delete op; op = nullptr; } else //创建输出文件 { op = new ofstream(opath.c_str()); if (!(*op)) cout << "can't open file" << endl; } } else { cout << "unknown mode" << endl; continue; } } else if(op==nullptr) //输出到控制台 cout << calculate(s,nullptr) << endl; else { //输出到文件 string ans = calculate(s, nullptr); (*op) << ">>" << s << endl << ans << endl; cout << ans << endl; } } } return 0; } catch (const std::exception& e) { cerr << e.what() << endl; cin.ignore('\n'); } catch (...) { cerr << "unexpected error" << endl; cin.ignore('\n'); }
Java
UTF-8
183
1.953125
2
[]
no_license
package com.aisino.adapter.objectmode; /** * * @author zhukaishengy * @date 2018-3-13 */ class Source { void method01(){ System.out.println("method01 ..."); } }
Java
UTF-8
712
3.71875
4
[ "MIT" ]
permissive
public class BankAccountClient { public static void main(String[] args) { // Initialize object using constructor (args) BankAccount b1 = new BankAccount("Jake", 40); // Add 500 to object's balance b1.deposit(500); System.out.println(b1); // Subtract 300 from object's balance b1.withdraw(300); System.out.println(b1); // Create object without intializing fields (no args) BankAccount b2 = new BankAccount(); System.out.println(b2); // Set object fields using mutator methods b2.setName("Daisy Buchanan"); b2.setBalance(100); System.out.println(b2); } }
Java
UTF-8
622
2.953125
3
[]
no_license
/** * */ package msb.j2se.common; /** * @author oradba * */ public class TestCountJava { /** * @param args */ public static void main(String[] args) { String s = "sunjavahpjavaokjavajavahahajavajavagoodjava"; int count = countSpecificString(s, "java"); System.out.println(count); } private static int countSpecificString(final String str, final String reg) { int count = 0; int fromIndex = str.indexOf(reg); while (-1 != fromIndex) { count++; fromIndex = str.indexOf(reg, fromIndex + reg.length()); } return count; } }
Markdown
UTF-8
3,922
2.890625
3
[]
no_license
--- layout: post title: Why Must LAMP Setup Suck? date: '2009-11-17T12:15:00-08:00' tags: - lamp - opinion tumblr_url: https://seanmonstar.com/post/708843270/why-must-lamp-setup-suck --- LAMP is common lingo for web developers. It’s an incredibly popular software stack to run dynamic websites. Many hosting companies include the stack for you, already configured and ready to go. But before we get there? That wonderful point where we trust our code to the production server, and then watch something blow up beautifully in a fire-y mess of status codes, fatal errors, and SQLStates. We developers like to test thing before then. So I’m left wondering, **why does setting up a testing environment suck so hard**? Downloading a virtual machine is easy enough, and then you must download your flavor \*nix. Boot it up, apt-get your flavor’s Apache, MySQL, and PHP. Getting Apache to work just the way you want, making sure you set up the right hosts, and run the correct modules. While you’re at it, your apt-get listscould be wrong, or not contain all the files you want. And in the middle of one installation, you may find you hit your memory limit, that simply requires increasing to a supreme value. There are competent, [1-button install programs](http://www.apachefriends.org/en/xampp-windows.html) that setup a [WAMP](http://en.wikipedia.org/wiki/WAMP) environment. No hassles. Of course, the only downside being that the environment differs slightly than your production environment. I recognize anyone needing a Linux server mostly knows how to set one up. But at the same time, the people wanting Linux servers are programmers. Isn’t our job _obsession_ all about automating tasks that can be automated, and forever trying to make every task in that category? Certainly, it must be a common setup to have a Debian (or Ubuntu, or RedHat, etc) Virtual Machine using Apache, SQL, and PHP. Even desiring Python to be installed, with mod\_python or mod\_wsgi. Or how about coming with Ruby set up for you. These would all be excellent downloadable Virtual Machines that programmers would use regularly. #### Only One Solution So Far I’ve seen one installer for a Linux virtual machine, though not in the flavor I regularly use: [SUSE Studio](http://susestudio.com/). > Build an appliance - or your own custom Linux distro - with a few mouse clicks. Customize it to your heart’s content, and share it with the world. The concept is brilliant. If you want a SUSE virtual machine, you just login, select the version, check some packages to include, such as Apache, MySQL, and the like. And then it builds it for you. Check back in a couple minutes, and you can download it to your machine. Or you can start it up right there in the web browser. <figure class="tmblr-full" data-orig-height="500" data-orig-width="500"><img src="https://64.media.tumblr.com/cb298e3393f2b8a6eea9ab8a4da15c64/286dd1b45e2b4148-9a/s540x810/6601d584d56b12c5790199b449f5d9374f081ec3.png" data-orig-height="500" data-orig-width="500"></figure> If I were the technical director at a company, and we were going to be using a new development area for a new project, I could easily customize a box (with clicking, not with tedious command line memorization), and after it’s built, give it out to all the developers. That’d be huge! It certainly is a pain point to make sure all us developers have a virtual machine with the same settings. #### The Way Forward SUSE Studio has the right idea, for all things that should be installed. Anything that requires a specific set of instructions that you’re requiring humans to do, every single time, should likely be programmed instead. Hopefully we’ll see other versions showing up, so the PHP developer wanting to check out Ruby, for example, can just download a virtual machine with it already set up, and get to the important stuff: **writing code and solve problems**.
Markdown
UTF-8
674
2.671875
3
[ "Apache-2.0" ]
permissive
# Node-RED ![Node-RED img](pic/nr-image.png) ***Node-RED***: 是构建物联网(IOT, Internet of Things)应用程序的一个强大工具,其重点是简化代码块的“连接”以执行任务。它使用可视化编程方法,允许开发人员将预定义的代码块(称为“节点”,Node)连接起来执行任务。连接的节点,通常是输入节点、处理节点和输出节点的组合,当它们连接在一起时,构成一个“流”(Flows)。 ## 生态 - 官网: https://nodered.org - Github: https://github.com/node-red - 英文社区: https://discourse.nodered.org - 中文社区: https://www.iotschool.com/topics/node81
JavaScript
UTF-8
491
2.9375
3
[]
no_license
class Poge extends HTMLElement { constructor() { super(); let template = document.querySelector("#poge"); this.append(template.content.cloneNode(true)); } } class Poggers extends HTMLElement { constructor() { super(); let template = document.querySelector("#poggers"); this.append(template.content.cloneNode(true)); } } window.customElements.define("poge-poge", Poge); window.customElements.define("poggers-poggers", Poggers);
Markdown
UTF-8
2,346
2.796875
3
[]
no_license
### 解决 连接问题 提示你:(node:80655) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor. - 添加参数`{useNewUrlParser: true, useUnifiedTopology: true}` - [参考链接](https://stackoverflow.com/questions/57895175/server-discovery-and-monitoring-engine-is-deprecated) ``` var MongoClient = require('mongodb').MongoClient; (async ()=>{ var db = await MongoClient.connect('mongodb://localhost:27017/acfun'); db.collection('customers').findOne({}, function (findErr, result) { if (findErr) throw findErr; console.log(result); client.close(); }); })() .then(r=>{ console.log(r) }) .catch(e=>{ console.log(e) }); ``` ### 解决db.collection is not function - 不能直接连到数据库 而是先连接到 mongodb - 通过 `var client = await MongoClient.connect('mongodb://localhost:27017',{useNewUrlParser: true, useUnifiedTopology: true});` - 然后在连接数据库`var db = client.db('mytestingdb');` - [参考链接](https://stackoverflow.com/questions/47662220/db-collection-is-not-a-function-when-using-mongoclient-v3-0) > 不能直接这样 ``` var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/mytestingdb"; (async ()=>{ var client = await MongoClient.connect('mongodb://localhost:27017',{useNewUrlParser: true, useUnifiedTopology: true}); var db = client.db('acfun'); db.collection('customers').findOne({}, function (findErr, result) { if (findErr) throw findErr; console.log(result); client.close(); }); })() .then(r=>{ console.log(r) }) .catch(e=>{ console.log(e) }); ``` ### How to use findOneAndUpdate in MongoDB in Node - https://stackoverflow.com/questions/38078132/how-to-use-findoneandupdate-in-mongodb-in-node ``` MongoClient.connect(url, function(err,db){ if (err) { throw err; } else { var collection = db.collection("connections"); collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {upsert: true}, function(err,doc) { if (err) { throw err; } else { console.log("Updated"); } }); } }); ```
Java
UTF-8
4,189
2.25
2
[]
no_license
package com.lzh.weatherforecast.widget; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.lzh.weatherforecast.R; /** * Created by lzh on 2016/4/12. */ public class TitleLayout extends RelativeLayout { private Context context; private RelativeLayout relativeLayout; private ImageView leftImageView, rightImageView; private TextView titleTextView, rightTextView; private TitleOnClickListener titleOnClickListener; public TitleLayout(Context context) { super(context); this.context = context; initView(); } public TitleLayout(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; initView(); } public TitleLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; initView(); } //初始化view private void initView() { View view = LayoutInflater.from(context).inflate(R.layout.common_title_layout, null); leftImageView = (ImageView) view.findViewById(R.id.left_imageview); rightTextView = (TextView) view.findViewById(R.id.right_textview); titleTextView = (TextView) view.findViewById(R.id.title); relativeLayout = (RelativeLayout) view.findViewById(R.id.titlelayout); rightImageView = (ImageView) view.findViewById(R.id.right_image); this.addView(view); } //给右边的imageView设置bg public void setRightImageViewBg(int resid) { rightImageView.setBackgroundResource(resid); } //设置右边的imageView是否可见 public void setRightImageViewVisibility(int visibility) { rightImageView.setVisibility(visibility); } // 右边图片点击事件 public void setRightImageViewListener(final TitleOnClickListener titleOnClickListener) { rightImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { titleOnClickListener.OnClick(); } }); } //设置标题栏背景颜色 public void setTitleBackgroundColor(int color) { relativeLayout.setBackgroundColor(color); } //设置标题 public void setTitleMessage(String title) { titleTextView.setText(title); } //标题文字大小 public void setTitleSize(float size) { titleTextView.setTextSize(size); } //设置左边图片 public void setLeftImage(Drawable drawable) { leftImageView.setImageDrawable(drawable); } //设置右边文字 public void setRightTextMessage(String message) { rightTextView.setText(message); } //左边图片是否隐藏 public void setLeftVisibility(int visibility) { leftImageView.setVisibility(visibility); } //右边图片是否隐藏 public void setRightVisibility(int visibility) { rightTextView.setVisibility(visibility); } //标题文字是否隐藏 public void setTitleVisibility(int visibility) { titleTextView.setVisibility(visibility); } //设置标题文字颜色 public void setTitleColor(int color) { titleTextView.setTextColor(color); } //左边点击事件 public void setLeftListener(final TitleOnClickListener titleOnClickListener) { leftImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { titleOnClickListener.OnClick(); } }); } public void setRightListener(final TitleOnClickListener titleOnClickListener) { rightTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { titleOnClickListener.OnClick(); } }); } public interface TitleOnClickListener { void OnClick(); } }
Python
UTF-8
20,883
2.671875
3
[]
no_license
from tkinter import * import random, math,os from tkinter import messagebox class Bill_App(): def __init__(self,screen): self.screen = screen self.screen.geometry("1350x750+0+0") self.screen.title("Garlica Multicusine Restaurant") bg_colour = "deep sky blue" title = Label(self.screen,text = "Garlica Multicusine Restaurant",bd = 8,relief = GROOVE, bg = bg_colour , font = ("arial",30,"bold"),pady = 2).pack(fill = X) #########Variables###### #-------Staters-------- self.Tandoori = IntVar() self.Chilly_Chiken = IntVar() self.Majestic_Chiken = IntVar() self.Peper_Chiken = IntVar() self.Lollypop_Chiken = IntVar() self.Dry_Chilly = IntVar() # -------Main course-------- self.Plain_Briyani = IntVar() self.Chiken_Briyani = IntVar() self.Mutton_Briyani = IntVar() self.Egg_Briyani = IntVar() self.Dry_CB = IntVar() self.Fried_Rice = IntVar() # -------Berverages-------- self.Lassy = IntVar() self.Orange_Jucie= IntVar() self.Apple_Jucie = IntVar() self.Pepsi = IntVar() self.Thumpsup = IntVar() self.Fruit_Lassy = IntVar() # -------Total and Tax of the Iteams-------- self.TStater = StringVar() self.TMcourse = StringVar() self.TBrav = StringVar() self.TaxStater = StringVar() self.TaxMcourse = StringVar() self.TaxBrav = StringVar() # -------Customer Details-------- self.cname = StringVar() self.cphono = StringVar() self.cbillno = StringVar() x= random.randint(1000,9999) self.cbillno.set(str(x)) self.search = StringVar() ###########Customer Label####### F1 = LabelFrame(self.screen, text = "Customer Details", bd = 10,font =("arial",15,"bold"),fg = "yellow",bg = bg_colour) F1.place(x = 0, y = 70, relwidth = 1) cnamelbl = Label(F1,text = "Customer Name",bg = bg_colour,font = ("arial",18,"bold")).grid(row = 0, column = 0) cnametxt = Entry(F1,font = ("arial",15,"bold"),textvariable = self.cname,bd = 7,relief = SUNKEN).grid(padx = 10,pady = 5,row = 0, column = 1) cphnolbl = Label(F1, text="Phone No", bg=bg_colour, font=("arial", 18, "bold")).grid(row=0,column=2) cphnotxt = Entry(F1, font=("arial", 15, "bold"),textvariable = self.cphono, bd=7, relief=SUNKEN).grid(padx=10, pady=5, row=0,column=3) cbillnolbl = Label(F1, text="Bill No", bg=bg_colour, font=("arial", 18, "bold")).grid(row=0,column=4) cbillnotxt = Entry(F1, font=("arial", 15, "bold"),textvariable = self.cbillno, bd=7, relief=SUNKEN).grid(padx=10, pady=5, row=0,column=5) searchbtn = Button(F1,width = 10,text = "Search",command = self.search,font=("arial", 15, "bold"),bd = 8).grid(row = 0, column = 6,padx = 10,pady = 12) ###### Label 2 ##### F2 = LabelFrame(self.screen, text="Staters", bd=10,relief = GROOVE,font=("arial", 15, "bold"), fg="yellow",bg=bg_colour) F2.place(x=5,y=185,width = 325,height = 380) Tlabel = Label(F2,text = "Tandoori",bg = bg_colour,font = ("arial",16 ,"bold")).grid(row = 0, column = 0) Ttxt = Entry(F2, width = 8,textvariable = self.Tandoori,font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=5, pady=10, row=0,column=1) Chilabel = Label(F2, text="Chilly Chiken", bg=bg_colour, font=("arial", 16, "bold")).grid(row=1, column=0) Chitxt = Entry(F2, width=8, textvariable = self.Chilly_Chiken,font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=1, column=1) Majlabel = Label(F2, text="Majestic Chiken", bg=bg_colour, font=("arial", 16, "bold")).grid(row=3,column=0) Majtxt = Entry(F2, width=8,textvariable = self.Majestic_Chiken,font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=3, column=1) peplabel = Label(F2, text="Peper Chiken", bg=bg_colour, font=("arial", 16, "bold")).grid(row=4,column=0) peptxt = Entry(F2, width=8,textvariable = self.Peper_Chiken, font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=4, column=1) lollabel = Label(F2, text="Lollypop Chiken", bg=bg_colour, font=("arial", 16, "bold")).grid(row=5,column=0) loltxt = Entry(F2, width=8, textvariable = self.Lollypop_Chiken,font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=5, column=1) drylabel = Label(F2, text="Dry Chilly", bg=bg_colour, font=("arial", 16, "bold")).grid(row=6,column=0) drytxt = Entry(F2, width=8,textvariable = self.Dry_Chilly, font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=6, column=1) ###### Label 3 ##### F3 = LabelFrame(self.screen, text="Main Course", bd=10, relief=GROOVE, font=("arial", 15, "bold"),fg="yellow", bg=bg_colour) F3.place(x=340, y=185, width=325, height=380) Plabel = Label(F3, text="Plain Biriyani", bg=bg_colour, font=("arial", 16, "bold")).grid(row=0, column=0) Ptxt = Entry(F3, width=10,textvariable = self.Plain_Briyani, font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=0, column=1) CBlabel = Label(F3, text="Chiken Biriyani", bg=bg_colour, font=("arial", 16, "bold")).grid(row=1,column=0) CBtxt = Entry(F3, width=10,textvariable = self.Chiken_Briyani, font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=1, column=1) MBlabel = Label(F3, text="Mutton Biriyani", bg=bg_colour, font=("arial", 16, "bold")).grid(row=3,column=0) MBtxt = Entry(F3, width=10,textvariable = self.Mutton_Briyani, font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=3, column=1) Egglabel = Label(F3, text="Egg Biriyani", bg=bg_colour, font=("arial", 16, "bold")).grid(row=4,column=0) Eggtxt = Entry(F3, width=10, textvariable = self.Egg_Briyani,font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=4, column=1) DCBlabel = Label(F3, text="Dry CB", bg=bg_colour, font=("arial", 16, "bold")).grid(row=5,column=0) DCBtxt = Entry(F3, width=10,textvariable = self.Dry_CB, font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=5, column=1) frylabel = Label(F3, text="Fried Rice", bg=bg_colour, font=("arial", 16, "bold")).grid(row=6,column=0) frytxt = Entry(F3, width=10, textvariable = self.Fried_Rice,font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=6, column=1) ####### Label 4 ###### F4 = LabelFrame(self.screen, text="Beverages", bd=10, relief=GROOVE, font=("arial", 15, "bold"),fg="yellow", bg=bg_colour) F4.place(x=670 , y=185, width=325, height=380) Laslabel = Label(F4, text="Lassy", bg=bg_colour, font=("arial", 16, "bold")).grid(row=0,column=0) Lastxt = Entry(F4, width=10,textvariable = self.Lassy, font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=0, column=1) Orangelabel = Label(F4, text="Orange Juice", bg=bg_colour, font=("arial", 16, "bold")).grid(row=1,column=0) Orangetxt = Entry(F4, width=10,textvariable = self.Orange_Jucie, font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=1, column=1) Applelabel = Label(F4, text="Apple Juice", bg=bg_colour, font=("arial", 16, "bold")).grid(row=3,column=0) Appletxt = Entry(F4, width=10, textvariable = self.Apple_Jucie,font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=3, column=1) Pepsilabel = Label(F4, text="Pepsi", bg=bg_colour, font=("arial", 16, "bold")).grid(row=4,column=0) Pepsitxt = Entry(F4, width=10, textvariable = self.Pepsi,font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=4, column=1) Thumblabel = Label(F4, text="Thumbsup", bg=bg_colour, font=("arial", 16, "bold")).grid(row=5, column=0) Thumbptxt = Entry(F4, width=10, textvariable = self.Thumpsup,font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=5, column=1) fruitlabel = Label(F4, text="Water Bottle", bg=bg_colour, font=("arial", 16, "bold")).grid(row=6,column=0) fruittxt = Entry(F4, width=10,textvariable = self.Fruit_Lassy, font=("arial", 16, "bold"), bd=5, relief=SUNKEN).grid(padx=10, pady=10,row=6, column=1) ##### Bill Area ###### F5 = Frame(self.screen, bd=8, relief=GROOVE) F5.place(x=1010, y=185, width=350, height=380) bill_title = Label(F5,text = "Invoice",font = ("arial", 15, "bold"),bd = 7,relief = GROOVE).pack(fill = X) scrol_y = Scrollbar(F5,orient = VERTICAL) self.textarea = Text(F5,yscrollcommand = scrol_y.set) scrol_y.pack(side = RIGHT, fill = Y) scrol_y.config(command = self.textarea.yview) self.textarea.pack() ####### Button Frame ####### F6 = LabelFrame(self.screen, text="Invoice Menu", bd=8, relief=GROOVE, font=("arial", 15, "bold"), fg="yellow",bg=bg_colour) F6.place(x=0, y=560, relwidth=1, height=140) TStarter = Label(F6, text = "Stater price",bg = bg_colour,font = ("arial",15,"bold")).grid(row= 0,column = 0,padx = 10,pady= 1,sticky = "w") TStartertxt = Entry(F6,width = 18,textvariable = self.TStater, font = ("arial",10,"bold"),bd = 6, relief=SUNKEN).grid(row = 0,column = 1,padx = 10,pady = 1) TMcourse = Label(F6, text="Main Course Price", bg=bg_colour, font=("arial", 15, "bold")).grid(row=1, column=0,padx=10, pady=1,sticky="w") TMcoursetxt = Entry(F6, width=18, textvariable = self.TMcourse,font=("arial", 10, "bold"), bd=6, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=1) TBrav = Label(F6, text="Beverages price", bg=bg_colour, font=("arial", 15, "bold")).grid(row=2, column=0,padx=10, pady=1,sticky="w") TBravtxt = Entry(F6, width=18, textvariable = self.TBrav,font=("arial", 10, "bold"), bd=6, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=1) TaxStarter = Label(F6, text="Stater Tax", bg=bg_colour, font=("arial", 15, "bold")).grid(row=0, column=4,padx=10, pady=1,sticky="w") TStartertxt = Entry(F6, width=18, textvariable = self.TaxStater,font=("arial", 10, "bold"), bd=6, relief=SUNKEN).grid(row=0, column=5, padx=10, pady=1) TaxMcourse = Label(F6, text="Main Course Tax", bg=bg_colour, font=("arial", 15, "bold")).grid(row=1, column=4,padx=10, pady=1,sticky="w") TMcoursetxt = Entry(F6, width=18, textvariable = self.TaxMcourse,font=("arial", 10, "bold"), bd=6, relief=SUNKEN).grid(row=1, column=5, padx=10, pady=1) TaxBrav = Label(F6, text="Beverages Tax", bg=bg_colour, font=("arial", 15, "bold")).grid(row=2, column=4,padx=10, pady=1, sticky="w") TBravtxt = Entry(F6, width=18,textvariable = self.TaxBrav, font=("arial", 10, "bold"), bd=6, relief=SUNKEN).grid(row=2, column=5, padx=10, pady=1) btn_frame = Frame(F6,bd = 7, relief=GROOVE) btn_frame.place(x = 710,width = 620,height = 100) Tbtn = Button(btn_frame,command =self.total,text = "Total",font = ("arial",15,"bold"),fg = "white",bg = "grey",width = 10).grid(row = 0,column = 0,padx = 7,pady = 20) billbtn = Button(btn_frame, text="Bill Generate",command = self.bill_area, font=("arial", 15, "bold"), fg="white", bg="grey", width=12).grid(row=0,column=1,padx=7,pady=20) Clearbtn = Button(btn_frame, text="Clear",command = self.clear,font=("arial", 15, "bold"), fg="white", bg="grey",width=10).grid(row=0, column=2, padx=7, pady=20) Exitbtn = Button(btn_frame, text="Exit",command = self.exit, font=("arial", 15, "bold"), fg="white", bg="grey", width=10).grid(row=0, column=3, padx=7, pady=20) self.welcome_bill() def total(self): self.Tan = self.Tandoori.get()*250 self.chi = self.Chilly_Chiken.get() * 180 self.Maj =self.Majestic_Chiken.get() * 220 self.pep = self.Peper_Chiken.get() * 230 self.lol = self.Lollypop_Chiken.get() * 280 self.dry = self.Dry_Chilly.get() * 180 self.total_staters_price = float((self.Tan)+ ( self.chi)+ (self.Maj)+ (self.pep)+ (self.lol)+ (self.dry) ) self.TStater.set("Rs. "+str(self.total_staters_price)) self.TTax = round((self.total_staters_price * 0.05),2) self.TaxStater.set("Rs. "+str(self.TTax)) self.PB = self.Plain_Briyani.get() * 120 self.CB = self.Chiken_Briyani.get() * 220 self.MB = self.Mutton_Briyani.get() * 300 self.EB = self.Egg_Briyani.get() * 150 self.DB = self.Dry_CB.get() * 280 self.FR = self.Fried_Rice.get() * 130 self.total_Main_course_price = float((self.PB) + (self.CB) + (self.MB) + (self.EB) + (self.DB) + (self.FR) ) self.TMcourse.set("Rs. "+str(self.total_Main_course_price)) self.MTax = round((self.total_Main_course_price * 0.05),2) self.TaxMcourse.set("Rs. " + str(self.MTax)) self.Las = self.Lassy.get() * 70 self.Ora = self.Orange_Jucie.get() * 80 self.App = self.Apple_Jucie.get() * 100 self.Pes = self.Pepsi.get() * 50 self.Thum = self.Thumpsup.get() * 60 self.Fru = self.Fruit_Lassy.get() * 50 self.total_Berverage_price = float((self.Las) + (self.Ora) + (self.App) + (self.Pes) + (self.Thum) + (self.Fru) ) self.TBrav.set("Rs. "+str(self.total_Berverage_price)) self.Tbra = round((self.total_Berverage_price * 0.05),2) self.TaxBrav.set("Rs. " + str(self.Tbra)) self.Total_Bill = float(self.total_staters_price+self.total_Main_course_price+self.total_Berverage_price+self.TTax+self.MTax+self.Tbra) def welcome_bill(self): self.textarea.delete("1.0",END) self.textarea.insert(END,"\t Garlica Invoice") self.textarea.insert(END,f"\n Bill Number : {self.cbillno.get()}") self.textarea.insert(END,f"\n Customer Name : {self.cname.get()}") self.textarea.insert(END,f"\n Phone Number : {self.cphono.get()}") self.textarea.insert(END, f"\n=======================================") self.textarea.insert(END, f"\n Iteams\t\tQTY\t\tPrice") self.textarea.insert(END, f"\n=======================================") def bill_area(self): if self.cname.get() == "" or self.cphono.get() == "": messagebox.showerror("Customer Details"," Please enter customer details") else: self.welcome_bill() #-------- Staters for bill area if self.Tandoori.get()!=0: self.textarea.insert(END,f"\n Tandoori\t\t{self.Tandoori.get()}\t\t{self.Tan}") if self.Chilly_Chiken.get()!=0: self.textarea.insert(END,f"\n Chilly Chiken\t\t{self.Chilly_Chiken.get()}\t\t{self.chi}") if self.Majestic_Chiken.get()!=0: self.textarea.insert(END,f"\n Majestic Chiken\t\t{self.Majestic_Chiken.get()}\t\t{self.Maj}") if self.Peper_Chiken.get()!=0: self.textarea.insert(END,f"\n Peper Chiken\t\t{self.Peper_Chiken.get()}\t\t{self.pep}") if self.Dry_Chilly.get()!=0: self.textarea.insert(END,f"\n Dry Chilly\t\t{self.Dry_Chilly.get()}\t\t{self.dry}") if self.Lollypop_Chiken.get()!=0: self.textarea.insert(END,f"\n Lollypop Chiken\t\t{self.Lollypop_Chiken.get()}\t\t{self.lol}") # -------- Main Course for bill area if self.Plain_Briyani.get()!=0: self.textarea.insert(END,f"\n Plain Briyani\t\t{self.Plain_Briyani.get()}\t\t{self.PB}") if self.Chiken_Briyani.get()!=0: self.textarea.insert(END,f"\n Chiken Briyani\t\t{self.Chiken_Briyani.get()}\t\t{self.CB}") if self.Mutton_Briyani.get()!=0: self.textarea.insert(END,f"\n Mutton Briyani\t\t{self.Mutton_Briyani.get()}\t\t{self.MB}") if self.Egg_Briyani.get()!=0: self.textarea.insert(END,f"\n Egg Briyani\t\t{self.Egg_Briyani.get()}\t\t{self.EB}") if self.Dry_CB.get()!=0: self.textarea.insert(END,f"\n Dry CB\t\t{self.Dry_CB.get()}\t\t{self.DB}") if self.Fried_Rice.get()!=0: self.textarea.insert(END,f"\n Fried Rice\t\t{self.Fried_Rice.get()}\t\t{self.FR}") # -------- Berverages for bill area if self.Lassy.get() != 0: self.textarea.insert(END, f"\n Lassy\t\t{self.Lassy.get()}\t\t{self.Las}") if self.Orange_Jucie.get() != 0: self.textarea.insert(END, f"\n Orange Jucie\t\t{self.Orange_Jucie.get()}\t\t{self.Ora}") if self.Apple_Jucie.get() != 0: self.textarea.insert(END, f"\n Apple Jucie\t\t{self.Apple_Jucie.get()}\t\t{self.App}") if self.Pepsi.get() != 0: self.textarea.insert(END, f"\n Pepsi\t\t{self.Pepsi.get()}\t\t{self.Pes}") if self.Thumpsup.get() != 0: self.textarea.insert(END, f"\n Thumpsup\t\t{self.Thumpsup.get()}\t\t{self.Thum}") if self.Fruit_Lassy.get() != 0: self.textarea.insert(END, f"\n Fruit Lassy\t\t{self.Fruit_Lassy.get()}\t\t{self.Fru}") self.textarea.insert(END, f"\n--------------------------------------") if self.TaxStater.get() != "Rs. 0.0": self.textarea.insert(END, f"\n Staters Tax\t\t\t{self.TaxStater.get()}") if self.TaxMcourse.get() != "Rs. 0.0": self.textarea.insert(END, f"\n Main Course Tax \t\t\t{self.TaxMcourse.get()}") if self.TaxBrav.get() != "Rs. 0.0": self.textarea.insert(END, f"\n Beverages Tax \t\t\t{self.TaxBrav.get()}") self.textarea.insert(END, f"\n--------------------------------------") self.textarea.insert(END,f"\n Total \t\t\t Rs. {self.Total_Bill}") self.textarea.insert(END, f"\n--------------------------------------") self.save_bill() def save_bill(self): key = messagebox.askyesno("Bill","Do you want to save the bill") if key > 0: self.billdata = self.textarea.get(1.0,END) file = open(r"C:\Users\Murugappa\Desktop\bills/"+str(self.cbillno.get())+".txt","w") file.write(self.billdata) file.close() messagebox.showinfo("Saved", f"Bill no : {self.cbillno.get()} saved successfully") else: return def search(self): for i in os.listdir(r"C:\Users\Murugappa\Desktop\bills/"): print(i) def clear(self): key = messagebox.askyesno("Clear","Do you want to clear?") if key > 0: self.Tandoori.set(0) self.Chilly_Chiken.set(0) self.Majestic_Chiken.set(0) self.Peper_Chiken.set(0) self.Lollypop_Chiken.set(0) self.Dry_Chilly.set(0) # -------Main course-------- self.Plain_Briyani.set(0) self.Chiken_Briyani.set(0) self.Mutton_Briyani.set(0) self.Egg_Briyani.set(0) self.Dry_CB.set(0) self.Fried_Rice.set(0) # -------Berverages-------- self.Lassy.set(0) self.Orange_Jucie.set(0) self.Apple_Jucie.set(0) self.Pepsi.set(0) self.Thumpsup.set(0) self.Fruit_Lassy.set(0) # -------Total and Tax of the Iteams-------- self.TStater.set(" ") self.TMcourse.set(" ") self.TBrav.set(" ") self.TaxStater.set(" ") self.TaxMcourse.set(" ") self.TaxBrav.set(" ") # -------Customer Details-------- self.cname.set(" ") self.cphono.set(" ") self.cbillno.set(" ") x = random.randint(1000, 9999) self.cbillno.set(str(x)) self.search.set(" ") else: return def exit(self): key = messagebox.askyesno("Clear","Do you want to exit?") if key > 0: self.screen.destroy() else: return screen = Tk() object = Bill_App(screen) screen.mainloop()
Python
UTF-8
397
4.125
4
[]
no_license
# Takes 2 integer values and returns True if n is multiple of m # so n = mi for some integer i # returns False o/wise print('Is it a multiple') print('Please enter 2 numbers to be evaluated.') def is_multiple(n, m): if n%m ==0: return True else: return False n = int(input("Please enter a number: ")) m = int(input("Please enter a number: ")) print(is_multiple(n, m))
Java
UTF-8
18,398
1.921875
2
[]
no_license
package com.ice.server.dao.model; import java.util.Date; public class IceBase { /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.id * * @mbg.generated */ private Long id; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.name * * @mbg.generated */ private String name; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.app * * @mbg.generated */ private Integer app; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.scenes * * @mbg.generated */ private String scenes; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.status * * @mbg.generated */ private Byte status; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.conf_id * * @mbg.generated */ private Long confId; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.time_type * * @mbg.generated */ private Byte timeType; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.start * * @mbg.generated */ private Date start; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.end * * @mbg.generated */ private Date end; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.debug * * @mbg.generated */ private Byte debug; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.priority * * @mbg.generated */ private Long priority; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.create_at * * @mbg.generated */ private Date createAt; /* * * This field was generated by MyBatis Generator. * This field corresponds to the database column tb_ice_base.update_at * * @mbg.generated */ private Date updateAt; /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.id * * @return the value of tb_ice_base.id * * @mbg.generated */ public Long getId() { return id; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withId(Long id) { this.setId(id); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.id * * @param id the value for tb_ice_base.id * * @mbg.generated */ public void setId(Long id) { this.id = id; } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.name * * @return the value of tb_ice_base.name * * @mbg.generated */ public String getName() { return name; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withName(String name) { this.setName(name); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.name * * @param name the value for tb_ice_base.name * * @mbg.generated */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.app * * @return the value of tb_ice_base.app * * @mbg.generated */ public Integer getApp() { return app; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withApp(Integer app) { this.setApp(app); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.app * * @param app the value for tb_ice_base.app * * @mbg.generated */ public void setApp(Integer app) { this.app = app; } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.scenes * * @return the value of tb_ice_base.scenes * * @mbg.generated */ public String getScenes() { return scenes; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withScenes(String scenes) { this.setScenes(scenes); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.scenes * * @param scenes the value for tb_ice_base.scenes * * @mbg.generated */ public void setScenes(String scenes) { this.scenes = scenes == null ? null : scenes.trim(); } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.status * * @return the value of tb_ice_base.status * * @mbg.generated */ public Byte getStatus() { return status; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withStatus(Byte status) { this.setStatus(status); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.status * * @param status the value for tb_ice_base.status * * @mbg.generated */ public void setStatus(Byte status) { this.status = status; } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.conf_id * * @return the value of tb_ice_base.conf_id * * @mbg.generated */ public Long getConfId() { return confId; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withConfId(Long confId) { this.setConfId(confId); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.conf_id * * @param confId the value for tb_ice_base.conf_id * * @mbg.generated */ public void setConfId(Long confId) { this.confId = confId; } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.time_type * * @return the value of tb_ice_base.time_type * * @mbg.generated */ public Byte getTimeType() { return timeType; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withTimeType(Byte timeType) { this.setTimeType(timeType); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.time_type * * @param timeType the value for tb_ice_base.time_type * * @mbg.generated */ public void setTimeType(Byte timeType) { this.timeType = timeType; } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.start * * @return the value of tb_ice_base.start * * @mbg.generated */ public Date getStart() { return start; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withStart(Date start) { this.setStart(start); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.start * * @param start the value for tb_ice_base.start * * @mbg.generated */ public void setStart(Date start) { this.start = start; } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.end * * @return the value of tb_ice_base.end * * @mbg.generated */ public Date getEnd() { return end; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withEnd(Date end) { this.setEnd(end); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.end * * @param end the value for tb_ice_base.end * * @mbg.generated */ public void setEnd(Date end) { this.end = end; } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.debug * * @return the value of tb_ice_base.debug * * @mbg.generated */ public Byte getDebug() { return debug; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withDebug(Byte debug) { this.setDebug(debug); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.debug * * @param debug the value for tb_ice_base.debug * * @mbg.generated */ public void setDebug(Byte debug) { this.debug = debug; } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.priority * * @return the value of tb_ice_base.priority * * @mbg.generated */ public Long getPriority() { return priority; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withPriority(Long priority) { this.setPriority(priority); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.priority * * @param priority the value for tb_ice_base.priority * * @mbg.generated */ public void setPriority(Long priority) { this.priority = priority; } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.create_at * * @return the value of tb_ice_base.create_at * * @mbg.generated */ public Date getCreateAt() { return createAt; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withCreateAt(Date createAt) { this.setCreateAt(createAt); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.create_at * * @param createAt the value for tb_ice_base.create_at * * @mbg.generated */ public void setCreateAt(Date createAt) { this.createAt = createAt; } /* * This method was generated by MyBatis Generator. * This method returns the value of the database column tb_ice_base.update_at * * @return the value of tb_ice_base.update_at * * @mbg.generated */ public Date getUpdateAt() { return updateAt; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ public IceBase withUpdateAt(Date updateAt) { this.setUpdateAt(updateAt); return this; } /* * This method was generated by MyBatis Generator. * This method sets the value of the database column tb_ice_base.update_at * * @param updateAt the value for tb_ice_base.update_at * * @mbg.generated */ public void setUpdateAt(Date updateAt) { this.updateAt = updateAt; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } IceBase other = (IceBase) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getApp() == null ? other.getApp() == null : this.getApp().equals(other.getApp())) && (this.getScenes() == null ? other.getScenes() == null : this.getScenes().equals(other.getScenes())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getConfId() == null ? other.getConfId() == null : this.getConfId().equals(other.getConfId())) && (this.getTimeType() == null ? other.getTimeType() == null : this.getTimeType().equals(other.getTimeType())) && (this.getStart() == null ? other.getStart() == null : this.getStart().equals(other.getStart())) && (this.getEnd() == null ? other.getEnd() == null : this.getEnd().equals(other.getEnd())) && (this.getDebug() == null ? other.getDebug() == null : this.getDebug().equals(other.getDebug())) && (this.getPriority() == null ? other.getPriority() == null : this.getPriority().equals(other.getPriority())) && (this.getCreateAt() == null ? other.getCreateAt() == null : this.getCreateAt().equals(other.getCreateAt())) && (this.getUpdateAt() == null ? other.getUpdateAt() == null : this.getUpdateAt().equals(other.getUpdateAt())); } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getApp() == null) ? 0 : getApp().hashCode()); result = prime * result + ((getScenes() == null) ? 0 : getScenes().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getConfId() == null) ? 0 : getConfId().hashCode()); result = prime * result + ((getTimeType() == null) ? 0 : getTimeType().hashCode()); result = prime * result + ((getStart() == null) ? 0 : getStart().hashCode()); result = prime * result + ((getEnd() == null) ? 0 : getEnd().hashCode()); result = prime * result + ((getDebug() == null) ? 0 : getDebug().hashCode()); result = prime * result + ((getPriority() == null) ? 0 : getPriority().hashCode()); result = prime * result + ((getCreateAt() == null) ? 0 : getCreateAt().hashCode()); result = prime * result + ((getUpdateAt() == null) ? 0 : getUpdateAt().hashCode()); return result; } /* * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_ice_base * * @mbg.generated */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", app=").append(app); sb.append(", scenes=").append(scenes); sb.append(", status=").append(status); sb.append(", confId=").append(confId); sb.append(", timeType=").append(timeType); sb.append(", start=").append(start); sb.append(", end=").append(end); sb.append(", debug=").append(debug); sb.append(", priority=").append(priority); sb.append(", createAt=").append(createAt); sb.append(", updateAt=").append(updateAt); sb.append("]"); return sb.toString(); } }
Python
UTF-8
666
3.46875
3
[]
no_license
str1='00000000000 my name is sriansha 000000000000000000000' print(str1.lstrip('0')) # print(str1.split()) # print(sorted(str1)) # print(''.join(sorted(str1))) # print(str1.upper()) # str2='\n' # print(str2.join(str1)) # print(str1.count('s')) # print(str1.count('a')) # print(str1.count('n')) # str2='my name is sriansha' # if str2.endswith(str1): # print("true") # else: # print("false") # if (str2end='sriansha'): # print("true") # else: # print("false") # if str1.islower(): # print("true") # else: # print("false") # str2= input("enter the variable to check:") # if str2 in str1: # print("true") # else: # print("false")
PHP
UTF-8
3,757
2.921875
3
[]
no_license
<?php class DB { private static $instance = null; private $pdo, $error=false, $results, $query, $count = 0; private function __construct(){ $host=Config::get('mysql/host'); $db=Config::get('mysql/db'); $username=Config::get('mysql/username'); $password=Config::get('mysql/password'); try{ $this->pdo = new PDO("mysql:host=$host;dbname=$db",$username,$password); //print_r($this->pdo); }catch(PDOException $e){ die($e->getMessage()); } } public static function getInstance(){ if(!isset(self::$instance)){ self::$instance = new DB(); return self::$instance; }; return self::$instance; } public function query($sql,$params=[]){ $this->error = false; if($this->query = $this->pdo->prepare($sql)){ $statement = $this->query; //print_r($statement) ; $i = 1; //print_r($this->query); //echo count($params); if(count($params)){ foreach($params as $p){ //echo $x; $statement->bindValue($i, $p, PDO::PARAM_STR); $i++; //echo $x; } } //print_r($statement); if($statement->execute()){ $this->results = $statement->fetchAll(PDO::FETCH_OBJ); $this->count = $statement->rowCount(); //var_dump($this->results[0]->username); }else{ $this->error = true; } } return $this; } public function action($action,$table, $where = []){ if(count($where===3) && !empty($where)){ $operators = ['=','<','>','<=','>=']; //print_r($where); $field = $where[0]; $operator = $where[1]; $value = $where[2]; if(in_array($operator,$operators)){ $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?"; if(!$this->query($sql, [$value])->error()){ return $this; } } }elseif(empty($where)){ $sql = "{$action} FROM {$table}"; if(!$this->query($sql)->error()){ return $this; } }else{ return false; } } public function get($table, $where =[]){ return $this->action("SELECT*",$table, $where); } public function all($table){ return $this->action("SELECT*",$table); } public function delete($table, $where=[]){ return $this->action("DELETE", $table, $where); } public function insert($table, $fields = []){ if(count($fields)){ $keys = array_keys($fields); $keys = implode('`, `',$keys); $values = ''; $x =1; foreach ($fields as $field) { $values.= '?'; if($x<count($fields)){ $values .= ', '; $x++; } } $sql = "INSERT INTO {$table} (`".$keys."`) VALUES (".$values.")"; //print_r($sql); if(!$this->query($sql,$fields)->error()){ return true; } return false; } } public function update($table, $id, $fields =[]){ $set = ''; $x =1; foreach($fields as $key => $value){ $set .= "{$key}= ?"; if($x<count($fields)){ $set .= ', '; $x++; } } $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}"; //print_r($sql); if(!$this->query($sql,$fields)->error()){ return true; } return false; } public function first(){ return $this->results()[0]; } public function error(){ return $this->error; } public function count(){ return $this->count; } public function results(){ return $this->results; } }
PHP
UTF-8
858
2.515625
3
[]
no_license
<?php $mysqli = new mysqli("mysql.hostinger.es", "u432353203_final", "123456", "u432353203_final"); if ($mysqli->connect_errno) { printf("Falló la conexión: %s\n", $mysqli->connect_error); exit(); } $result =$mysqli->query("SELECT Eposta FROM ERABILTZAILEA WHERE Onartua=0"); if (mysqli_num_rows($result) == 0) echo '<p style="color:green">Momentu honetan ez dago eskaerarik.</p>'; else { while(list($eposta) = mysqli_fetch_row($result)) { echo ' <tr id="'.$eposta.'"> <td>'.$eposta.'</td> <td> <button class="btn btn-success" onclick="onartuErabiltzaile(\''.$eposta.'\')">Onartu</button>&nbsp<button class="btn btn-danger" onclick="baztertuErabiltzaile(\''.$eposta.'\')">Baztertu</button> </td> </tr>'; } } ?>
C
UTF-8
185
2.953125
3
[]
no_license
#include <stdio.h> int main() { float w, h, b; float mb = 0; scanf("%f %f %f", &w, &h, &b); mb = w * h * b /8 /1024 /1024; printf("%.2f MB\n", mb); return 0; }
Python
UTF-8
901
2.609375
3
[ "BSD-3-Clause" ]
permissive
import unittest2 as unittest from celery import states class test_state_precedence(unittest.TestCase): def test_gt(self): self.assertGreater(states.SUCCESS, states.PENDING) self.assertGreater(states.FAILURE, states.RECEIVED) self.assertGreater(states.REVOKED, states.STARTED) self.assertGreater(states.SUCCESS, states.state("CRASHED")) self.assertGreater(states.FAILURE, states.state("CRASHED")) self.assertFalse(states.REVOKED > states.state("CRASHED")) def test_lt(self): self.assertLess(states.PENDING, states.SUCCESS) self.assertLess(states.RECEIVED, states.FAILURE) self.assertLess(states.STARTED, states.REVOKED) self.assertLess(states.state("CRASHED"), states.SUCCESS) self.assertLess(states.state("CRASHED"), states.FAILURE) self.assertTrue(states.REVOKED < states.state("CRASHED"))
Java
UTF-8
2,281
2.3125
2
[ "Apache-2.0" ]
permissive
package tane.mahuta.buildtools.vcs; /** * Configuration for branches in the VCS. * * @author christian.heike@icloud.com * Created on 06.06.17. */ public interface VcsFlowConfig { /** * @return the production branch name */ String getProductionBranch(); /** * Set the production branch name. * * @param production the name of the branch * @return (this) */ VcsFlowConfig setProductionBranch(String production); /** * @return the production branch name */ String getDevelopmentBranch(); /** * Set the development branch name. * * @param development the name of the branch * @return (this) */ VcsFlowConfig setDevelopmentBranch(String development); /** * @return the prefix used for feature branches */ String getFeatureBranchPrefix(); /** * Set the prefix used for feature branches. * * @param featurePrefix the prefix to be set * @return (this) */ VcsFlowConfig setFeatureBranchPrefix(String featurePrefix); /** * @return the prefix used for release branches */ String getReleaseBranchPrefix(); /** * Set the prefix for release branches. * * @param releasePrefix the prefix to be set * @return (this) */ VcsFlowConfig setReleaseBranchPrefix(String releasePrefix); /** * @return the prefix used for support branches */ String getSupportBranchPrefix(); /** * Set the prefix for support branches. * * @param supportPrefix the prefix to be set * @return (this) */ VcsFlowConfig setSupportBranchPrefix(String supportPrefix); /** * @return the prefix used for hotfix branches */ String getHotfixBranchPrefix(); /** * Set the prefix for hotfix branches. * * @param hotfixPrefix the prefix to be set * @return (this) */ VcsFlowConfig setHotfixBranchPrefix(String hotfixPrefix); /** * @return the prefix for version tags */ String getVersionTagPrefix(); /** * Set the prefix for version tags. * * @param versionTagPrefix the prefix to be set * @return (this) */ VcsFlowConfig setVersionTagPrefix(String versionTagPrefix); }
Markdown
UTF-8
8,951
3.453125
3
[]
no_license
# Stage 1 - 가장 간단하게 저장해보자 첫번째 스테이지에서는 간단한 문법으로 쉽게 데이터를 저장할 수 있는 방법에 대해 알아봅니다. 사용이 간단한만큼 저장된 데이터도 복잡한 형태를 가지기 힘든 txt나 csv파일이 되지만, 닭 잡는데 소 잡는 칼을 쓸 필요가 없듯 간단한 형태로 저장하는 경우도 필요할 때가 있습니다. 또한 파이썬이 외부 파일을 다루는 구조에 대해 이해하기 쉬우니 먼저 이 방법으로 시작해 보겠습니다. ## 파이썬코드로 파일 열기 ```python f = open('test.txt', 'w') ``` 시작부터 코드부터 나와 당황하셨겠지만, 위의 한 줄만 실행시켜도 파이썬은 외부 파일을 열게 됩니다. ![](../.gitbook/assets/image%20%28428%29.png) 위 코드를 실행시키면 실행한 폴더에 test.txt가 생성됩니다. open\( \) 함수에 전달되는 두 매개변수 중 첫번째는 당연히 파일의 이름이고, 두번째는 파일을 다룰 모드입니다. ![](../.gitbook/assets/image%20%28467%29.png) 이 모드의 값에 따라 위와 같이 파일에 대해 실행할 수 있는 기능이 다릅니다. ### 쓰기 모드 먼저 쓰기 모드를 사용해 파일 내용을 작성해보겠습니다. ```python f = open('test.txt', 'w') f.write("hello world!") f.close() ``` open의 결과값을 변수 f에 집어넣고 있습니다. 이제 f는 파일 클래스의 변수가 되어 여러 함수를 통해 test.txt 를 컨트롤할 수 있습니다. .write\( \) 함수는 매개변수로 전달된 문자열을 파일에 쓰는 역할을 하고, .close\( \) 함수는 열었던 파일을 닫아 더 이상 컨트롤할 수 없게 만듭니다. 사용이 끝난 파일은 꼭 .close\( \) 를 실행하여 연결을 종료하여야 합니다. ![](../.gitbook/assets/image%20%28372%29.png) 위 코드를 실행하고 코드가 있는 폴더를 열어 생성된 test.txt를 보면, hello world! 가 성공적으로 작성된 것을 볼 수 있습니다. ### 추가 모드 다음으로 위 코드를 바꾸어 파일을 추가 모드 \(append의 'a'\) 로 열어 내용을 작성해 보겠습니다. ```python f = open('test.txt', 'a') f.write("hello world!") f.close() ``` 이 코드를 실행하고 test.txt를 열어보면, 기존 내용에 새로 작성한 내용이 더해진 것이 보입니다. ![](../.gitbook/assets/image%20%28303%29.png) 이처럼 추가 모드에서는 기존 내용을 그대로 두고 내용을 추가합니다. ### 읽기 모드 ![](../.gitbook/assets/image%20%28217%29.png) 읽기 모드를 알아보기에 앞서, test.txt의 내용에 한 줄을 더 추가해 주세요. ```python f = open('test.txt', 'r') lines = f.readlines() for line in lines: print(line) f.close() ``` 읽기 모드를 사용해 파일을 열면, .readlines\( \) 함수를 사용해 내용을 읽어올 수 있습니다. ![](../.gitbook/assets/image%20%28347%29.png) 함수의 결과로 리스트를 돌려주는데, 각 요소는 파일의 한 줄입니다. 따라서 위 코드는 다음 결과를 출력합니다. ![](../.gitbook/assets/image%20%28255%29.png) ![](../.gitbook/assets/image%20%28248%29.png) ## 수집한 데이터 저장해보기 이제 파일에 간단히 저장하는 방법을 알았으니, 네이버 TV TOP 100으로 돌아가 정렬된 결과를 저장해봅시다. 저장된 Dictionary를 정렬하여 sortedList라는 변수에 넣었을 것입니다. ```python f = open('test.txt', 'w') for sortedInfo in sortedList: f.write(sortedInfo[0] + ',' + str(sortedInfo[1]['hit']) + '\n') f.close() ``` 정렬 후에 마지막 부분에 위 코드를 추가하여 결과를 파일에 씁니다. \( 채널명, 조회수 \n \) 의 형식으로 하나씩 파일에 쓰게 됩니다. {% hint style="info" %} \n 은 줄바꿈 문자입니다. 메모장에 직접 쓸 때는 Enter를 눌러 줄을 바꾸지만, 코드 상에서는 이를 표현할 수 없어 대신 '\n' 을 만나면 줄을 바꾸도록 정해져 있습니다. / \(슬래시\) 와 \\(역슬래시\) 헷갈리지 않게 주의하세요! {% endhint %} 위 코드들을 추가하여 실행시키면 다음과 같은 결과 파일을 얻을 수 있습니다. ![](../.gitbook/assets/image%20%28393%29.png) 잘 저장이 되었습니다. 그런데 메모장은 아무래도 열이 맞지 않아 데이터를 확인하기 불편하네요. ### csv 파일로 저장하기 혹시 csv라는 파일 형식을 아시나요? csv는 Comma Seperated Values의 약자로, 쉼표로 구분된 값들을 의미합니다. 마침 저희가 데이터를 쉼표로 구분하여 저장했는데요. ```python f = open('test.csv', 'w') ``` 파일을 열 때 확장자만 .csv로 바꾸어 다시 실행해 봅시다. ![](../.gitbook/assets/image%20%28491%29.png) csv 파일은 이처럼 엑셀을 사용해 열 수 있습니다. 쉼표 부분을 분리 기준으로 인식하여 다른 셀에 값을 집어넣어줍니다. 결과적으로 들어있는 값은 똑같지만 보기가 훨씬 편합니다. \(엑셀이 설치되어있지 않으신 분들은 엑셀 뷰어로 확인해주세요!\) ## 파일명 자동 변경 네이버 TV TOP100의 데이터를 매일 수집한다고 해봅시다. open\( \) 함수를 이용해 파일을 쓰기 모드로 열면, 기존에 있던 데이터는 모두 사라지는데요. 그렇다고 추가 모드로 열기엔 날짜별로 데이터가 구분되지 않아 불편할 것 같네요. ![](../.gitbook/assets/image%20%28456%29.png) 대신 수집하는 날짜마다 파일명을 바꾸어 'TOP100\_2018\_06\_28.csv' 와 같이 저장한다면 잘 구분되겠죠? 그런데 실행할 때마다 날짜를 바꿔서 코드에 넣어주어야 한다면 여간 불편한 일이 아닐 것입니다. 완성된 코드를 계속 수정해야 한다는 것은 설계가 잘못되었다는 말이기도 하구요. 다행히 파이썬에서는 날짜를 확인하고 사용할 수 있는 클래스를 제공합니다. ```python import datetime dt = datetime.datetime.now() print(dt) ``` ![](../.gitbook/assets/image%20%28469%29.png) datetime이라는 클래스를 import하여 다음과 같이 현재 시간을 불러올 수 있습니다. 하지만 이를 그대로 파일명에 사용하기엔 부적합합니다. 하루에 한 번 수집할 것이기 때문에 날짜까지만 필요하고, ':' 문자는 파일명에 사용할 수 없기 때문입니다. ```python df = dt.strftime('%Y_%m_%d') print(df) ``` ![](../.gitbook/assets/image%20%28231%29.png) datetime 클래스의 .strftime\( \) \(**str**ing **f**ormatted **time** 이라는 뜻이겠네요.\) 함수를 사용하면 날짜 데이터를 원하는 형태로 만들 수 있습니다. ![](../.gitbook/assets/image%20%28274%29.png) .strftime\( \) 함수에 전달되는 형식 문자열은 위와 같은 내용으로 구성됩니다. 문자열 안의 %Y가 실제 날짜 데이터의 연도 값으로 대체되는 것이죠. 위 표에 나와있지 않은 \_ 같은 문자는 대체하지 않고 그대로 출력됩니다. 그 결과 우리는 파일명에 사용하고자 하는 2018\_06\_28을 얻을 수 있습니다. ```python dt = datetime.datetime.now() filename = 'TOP100_' + dt.strftime("%Y_%m_%d") f = open(filename + '.csv', 'w') ``` 이 문자열 앞에 'TOP100\_' 을 붙여 파일명으로 전달하면, 매일 코드를 수정하지 않고도 데이터를 날려먹지 않고 수집할 수 있습니다! \(그래도 같은 날짜에 두 번 이상 수집하면 이전 데이터가 날아가겠죠? 이럴 경우 시간, 분, 초 단위까지 필요에 따라 활용해서 파일명을 변경해야겠습니다.\) ```python import requests from bs4 import BeautifulSoup import datetime req = requests.get('https://tv.naver.com/r/') raw = req.text html = BeautifulSoup(raw, 'html.parser') infos = html.select('div.cds') chn_infos = {} for info in infos: chn = info.select_one('dd.chn > a').text hit = int(info.select_one('span.hit').text[4:].replace(',', '')) like = int(info.select_one('span.like').text[5:].replace(',', '')) if chn in chn_infos.keys(): chn_infos[chn]['hit'] += hit chn_infos[chn]['like'] += like else: chn_infos[chn] = {'hit': hit, 'like': like} def sortKey(item): return item[1]['hit'] sortedList = sorted(chn_infos.items(), key=sortKey, reverse=True) dt = datetime.datetime.now() filename = 'TOP100_' + dt.strftime("%Y_%m_%d") f = open(filename + '.csv', 'w') for sortedInfo in sortedList: f.write(sortedInfo[0] + ',' + str(sortedInfo[1]['hit']) + '\n') f.close() ``` 최종 코드입니다. 자신의 코드가 잘 실행되지 않는다면 참고하세요. 그냥 복사 붙여넣기 하는 것보다 자신의 코드와 한줄 한줄 비교하며 어디가 잘못되었는지 파악해보세요.
PHP
UTF-8
444
2.875
3
[]
no_license
<?php include_once "funcs.php"; /** * MapData class to represent maps. Should always match the one in FurkieBot. */ class MapData { public $name = ""; public $id = -1; public $filepath = ""; public $author = ""; public $acceptedBy = ""; public $accepted = false; public function __construct(Array $loadedArray = array()) { foreach($loadedArray as $key => $value){ $this->{$key} = $value; } } } ?>
Markdown
UTF-8
2,387
2.890625
3
[]
no_license
# iOS Sign & Install Bash script for signing and installing iOS 11 apps to Electra JB iOS device. Also can be used to sign and install ATV4 app on 10.2.2 with greenGoblin by NitoTV. ## How this work This bash script sign any ipa file with jtool than copy app to device and install it. Script tested and work only with macOS and Linux. Notice: for iOS 11 apps will be installed to stock apps directory /Applications and if you want to delete it you must manual enter to SSH and do rm -rf /Applications/APPNAME.app && uicache ### Prerequisites 1. You must have iOS 11 JB device with Electra JB and for Apple TV 4 iOS 10.2.2 with greenGoblib JB! 2. You must download [jtool](http://www.newosxbook.com/tools/jtool.tar) by Jonathan Levin ### Install First download jtool and export it, than cd terminal to that path than: **For macOS** ``` sudo chmod +x jtool && sudo mv jtool /usr/local/bin ``` **For Linux** ``` sudo chmod +x jtool.ELF64 && sudo mv jtool.ELF64 /usr/local/bin/jtool ``` Now clone this repo or download raw ipainstall.sh on your computer and use it like ./ipascript.sh ipa_name ip_address os_type. For easy use cd to path of this bash script and copy/paste line below. ``` sudo chmod +x ipainstall.sh && sudo mv ipainstall.sh /usr/local/bin/ipainstall ``` Now you can use it like ipainstall from any dir. on your computer. ### How to use **This script have 3 parameters:** * script name: ipainstall * parameter1: ipa name (app_name.ipa) * parameter2: ip_address (192.168.1.2) * optional * parameter3: os_type (iOS for iPhone, iPod, iPad and tvOS for Apple TV 4) * optional If you don't want to install app after sign than don't provide parameter 2. Use this if you want to sign app and manual upload to your device. 3rd parameter is set by default to iOS, if you use Apple TV you must pass 2 & 3 parameter. Also you can open ipainstall.sh and enter your IP address and OS_TYPE at beginning of script so you don't need to enter IP address every time you want to install app. ### Examples To sign and install app to iOS 11 ``` ipainstall application.ipa 192.168.1.2 ``` To sign only ``` ipainstall application.ipa ``` To sign and install to Apple TV 4 ``` ipainstall application.ipa 192.168.1.2 "tvOS" ``` **I make this script to help myself with testing my application without boring 7 days XCode sign so please don't use this script for piracy!**
Java
UTF-8
3,822
2.8125
3
[]
no_license
package de.beuth_hochschule.s790642.recorder; import android.content.Context; import android.content.pm.PackageManager; import android.media.MediaRecorder; import android.os.Environment; import android.widget.Toast; import java.io.File; import java.io.IOException; /** * Created by Robin on 16.01.2016. */ public class MyRecorder { private final Context parentContext; private MediaRecorder recorder; private boolean isRecording = false; private final String audioPath; private final String AUDIO_FORMAT = ".m4a"; private String audioFilePath; private String audioFileName=""; public MyRecorder(final Context parentContext){ this.parentContext = parentContext; this.audioFilePath = ""; this.audioPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath() + "/recorder/"; //create Folder if its not there File storageFolder = new File(audioPath); storageFolder.mkdirs(); } public void setAudioFileName (final String audioFileName){ this.audioFileName = audioFileName + AUDIO_FORMAT; this.audioFilePath = this.audioPath + audioFileName + this.AUDIO_FORMAT; } public String getAudioFileName (){ return this.audioFileName; } /** * starts Recorder with the given audioFilePath, * if the device has a microphone and this Instance does not record something. */ public void startRecord (final String audioFileName) { if(hasMicrophone()) { if (!isRecording) { this.recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setAudioEncodingBitRate(16); recorder.setAudioSamplingRate(44100); setAudioFileName(audioFileName); recorder.setOutputFile(this.audioFilePath); try { recorder.prepare(); } catch (IOException e) { Toast.makeText(parentContext, "prepare geht nicht", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } recorder.start(); // Recording is now started isRecording = true; } else { Toast.makeText(parentContext, "Already Recording", Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(parentContext, "No Microphone Package installed", Toast.LENGTH_SHORT).show(); } } /** * stops the Recorder and release it. */ public void stopRecord() { if(isRecording) { this.recorder.stop(); isRecording = false; this.recorder.reset(); this.recorder.release(); }else{ Toast.makeText(parentContext, "Nothing is recording", Toast.LENGTH_SHORT).show(); } } /** * Pause the recording */ public void pauseRecord() { //TODO impl this } //TODO if time, impl cancel current record private boolean hasMicrophone() { PackageManager pmanager = parentContext.getPackageManager(); return pmanager.hasSystemFeature( PackageManager.FEATURE_MICROPHONE); } /** * checks if a file already exists with the given Name. * Looking up in default Storage Directory of this app. * returns true if it exists. */ public boolean isFileNameAlreadyExistent(final String fileName){ setAudioFileName(fileName); final File file = new File(this.audioFilePath); return file.exists(); } }
Java
UTF-8
763
2.125
2
[]
no_license
package com.in28minutes.microservices.limitsservice.api; import com.in28minutes.microservices.limitsservice.config.Configuration; import com.in28minutes.microservices.limitsservice.domain.LimitConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; @RestController public class LimitsConfigurationController { @Autowired private Configuration configuration; @GetMapping("/limits") public Mono<LimitConfiguration> retrieveLimitsFromConfiguration() { return Mono.just(new LimitConfiguration(configuration.getMaximum(), configuration.getMinimum())); } }
JavaScript
UTF-8
1,499
3.796875
4
[]
no_license
const sphere = { type: 'sphere', radius: 2, }; // Output: 33.5102; // const cone = { // type: 'cone', // radius: 3, // height: 5, // }; // // Output: 47.12385; const prism = { type: 'prism', height: 3, width: 4, depth: 5, }; // Output: 60; const largeSphere = { type: 'sphere', radius: 40, }; const smallSphere = { type: 'sphere', radius: 10, }; const cone = { type: 'cone', radius: 3, height: 5, }; const duck = [largeSphere, smallSphere, cone]; // Output: 272318.257; // // // Use the value below whenever you need the value of Pi const PI = 3.14159; const sphereVolume = function (radius) { return (4 / 3) * PI * Math.pow(radius, 3); }; const coneVolume = function (radius, height) { return PI * Math.pow(radius, 2) * (height / 3); }; const prismVolume = function (height, width, depth) { return height * width * depth; }; const totalVolume = function (solids) { let total = 0; for (let item of solids) { if (item['type'] === 'sphere') { total = total + sphereVolume(item['radius']); } if (item['type'] === 'cone') { total = total + coneVolume(item['radius'], item['height']); } if (item['type'] === 'prism') { total = total + prismVolume(item['height'], item['width'], item['depth']); } } return total; //add all elements of duck }; // console.log(sphereVolume(sphere.radius)); // console.log(coneVolume(cone.radius, cone.height)); // console.log(prismVolume(prism.height, prism.width, prism.depth)); console.log(totalVolume(duck));
Markdown
UTF-8
2,865
2.921875
3
[]
no_license
# excelVisualBasic Excel Visual Basic information and code snippets ``` Dim lastRow As Long, lastColumn As Long, ws As Worksheet Set ws = ActiveSheet ' Get the number of the last row that has data lastRow = ws.Cells.Find(What:="*", _ After:=ws.Cells(1), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row ' Get the number of the last column that has data lastColumn = ws.Cells.Find(What:="*", _ After:=ws.Cells(1), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Column Dim activeRow As Long, activeColumn As Long ' Get the row and column numbers of the active cell activeRow = ActiveCell.Row activeColumn = ActiveCell.Column ' insert a row below the active cell ActiveCell.Offset(1).EntireRow.Insert Shift:=xlShiftDown ``` Macro to loop through rows in a column and duplicate rows with data ``` Sub Macro1() ' ' Macro1 Macro ' Dim lastRow As Long, lastColumn As Long, ws As Worksheet Dim activeRow As Long, activeColumn As Long Set ws = ActiveSheet ' Get the number of the last row that has data lastRow = ws.Cells.Find(What:="*", _ After:=ws.Cells(1), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row ' Get the number of the last column that has data lastColumn = ws.Cells.Find(What:="*", _ After:=ws.Cells(1), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Column ' get the row and column numbers for the active cell activeRow = ActiveCell.Row activeColumn = ActiveCell.Column ' loop through each row until we hit the last one with data While activeRow < lastRow If ActiveCell.Value = "" Then ' if no data in the cell, move to the next row ActiveCell.Offset(1).Activate Else ' if data is in the cell, duplicate the row ActiveCell.Rows("1:1").EntireRow.Copy ActiveCell.Offset(1).Rows("1:1").EntireRow.Insert ' add one to the last row since we inserted one lastRow = lastRow + 1 ' copy the data block to the main column and clear the contents for current and next row ActiveCell.Range("A1:C1").Cut ActiveCell.Offset(1, -3) ActiveCell.Offset(1).Range("A1:C1").ClearContents ' move to the next row ActiveCell.Offset(1).Activate End If ' update the value for the active row activeRow = ActiveCell.Row Wend 'ActiveCell.Offset(1).EntireRow.Insert Shift:=xlShiftDown 'ws.Cells(startRow + 1, startColumn + 1).Select 'MsgBox "Last row number is " & startRow & " " & startColumn End Sub ```
Java
UTF-8
27,940
1.789063
2
[]
no_license
package cs.controller.management.auxiliaryDecision; import java.net.URLDecoder; import java.text.ParseException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sn.framework.odata.Odata; import cs.model.PageModelDto; import cs.model.Statistics.view.newEdition.GenerateExcelForMoney; import cs.repository.odata.ODataObj; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.quartz.SimpleTrigger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; import cs.common.Util; import cs.model.Statistics.ProjectStatisticsBean; import cs.model.Statistics.sttisticsData; import cs.model.Statistics.view.ApprovalStatisticsView; import cs.model.Statistics.view.PlanStatisticsView; import cs.model.Statistics.view.ProjectStatisticsView; import cs.model.Statistics.view.newEdition.GenerateExcelForApproval; import cs.model.Statistics.view.newEdition.GenerateExcelForPlan; import cs.model.Statistics.view.newEdition.GenerateExcelForProject; import cs.service.interfaces.ProjectService; import cs.service.interfaces.ShenBaoInfoService; import cs.service.interfaces.YearPlanService; /** * * @ClassName: StatisticalAnalysisController * @Description: 统计分析控制器 * @author cx * @date 2018年1月4日 下午3:41:41 * */ @Controller @RequestMapping(name = "后台管理--辅助决策--统计分析", path = "management/auxDeci/statisticalAnalysis") public class StatisticalAnalysisController { private String ctrl ="management/auxDeci/statisticalAnalysis"; @Autowired private ProjectService ProjectService; @Autowired private ShenBaoInfoService shenBaoInfoService; @Autowired private YearPlanService yearPlanService; // @RequiresPermissions("management/auxDeci/statisticalAnalysis#getprojectByHY#get") @RequestMapping(name = "获取项目库中项目投资行业分布数据", path = "getprojectByHY",method=RequestMethod.GET) public @ResponseBody List<sttisticsData> getprojectByHYData(){ return ProjectService.getprojectByHYData(); } // @RequiresPermissions("management/auxDeci/statisticalAnalysis#getprojectInvestSource#get") @RequestMapping(name = "获取项目库中项目投资来源分布数据", path = "getprojectInvestSource",method=RequestMethod.GET) public @ResponseBody List<sttisticsData> getprojectInvestSource(){ return ProjectService.getprojectInvestSourceData(); } // @RequiresPermissions("management/auxDeci/statisticalAnalysis#getyearPlanByHY#get") @RequestMapping(name = "获取年度计划中项目投资行业分布数据", path = "getyearPlanByHY",method=RequestMethod.GET) public @ResponseBody List<sttisticsData> getyearPlanByHYData(){ return yearPlanService.getyearPlanByHYData(); } // @RequiresPermissions("management/auxDeci/statisticalAnalysis#getyearPlanInvestSource#get") @RequestMapping(name = "获取年度计划中项目投资来源数据", path = "getyearPlanInvestSource",method=RequestMethod.GET) public @ResponseBody List<sttisticsData> getyearPlanInvestSourceData(){ return yearPlanService.getyearPlanInvestSourceData(); } @RequestMapping(name="项目总库-项目分类统计数据获取",path="getExcelForProjectData",method=RequestMethod.GET) public @ResponseBody List<ProjectStatisticsBean> getExcelForProjectData(HttpServletRequest request,@RequestParam String classDesc,@RequestParam String isIncludLibrary) throws ParseException{ return ProjectService.getProjectStatistics(classDesc,isIncludLibrary); } @RequestMapping(name="资金类数据获取",path="getExcelForMoneyData",method=RequestMethod.POST) public @ResponseBody List<ProjectStatisticsBean> getExcelForMoneyData(@SuppressWarnings("rawtypes") @RequestBody Map map) throws Exception{ //获取筛选条件 String type = (String) map.get("type"); String isIncludLibrary = (String)map.get("isIncludLibrary"); String stageSelect = StringUtils.strip(map.get("stage").toString(),"[]"); String unitSelect = StringUtils.strip(map.get("unit").toString(),"[]"); String industrySelect = StringUtils.strip(map.get("industry").toString(),"[]"); String categorySelect = StringUtils.strip(map.get("category").toString(),"[]"); String projectStageSelect = StringUtils.strip(map.get("projectStage").toString(),"[]"); String projectName = (String) map.get("projectName"); //处理请求参数 String[] stageSelected = Util.isNotNull(stageSelect)?stageSelect.split(",") : null; String[] unitSelected = Util.isNotNull(unitSelect)?unitSelect.split(",") : null; String[] industrySelected = Util.isNotNull(industrySelect)?industrySelect.split(",") : null; String[] categorySelected = Util.isNotNull(categorySelect)?categorySelect.split(",") : null; String[] projectStageSelected = Util.isNotNull(projectStageSelect)?projectStageSelect.split(",") : null; projectName = Util.isNotNull(projectName) ? projectName.toString() : null; List<ProjectStatisticsBean> list = ProjectService.getMoneyStatistics(isIncludLibrary,stageSelected,projectStageSelected,projectName,unitSelected,industrySelected,categorySelected); //数据处理 Map<String,Integer[]> shenbaoStageNumMaps = new HashMap<String,Integer[]>(); int rowNum = 0; for (int i = 0;i<list.size();i++){ ProjectStatisticsBean bean = list.get(i); String proName = bean.getProjectName(); //申报类型个数处理 Integer stageNum = shenbaoStageNumMaps.get(proName) != null ? shenbaoStageNumMaps.get(proName)[0]+1 : 1; //序号处理 rowNum = shenbaoStageNumMaps.get(proName) != null ? shenbaoStageNumMaps.get(proName)[1] : rowNum+1; Integer[] list1 = {stageNum,rowNum}; shenbaoStageNumMaps.put(proName,list1); } //处理数据展示编号及合并行 if(!list.isEmpty()){ list.stream().forEach(x -> { String proName = x.getProjectName(); Integer[] val = shenbaoStageNumMaps.get(proName); if(val != null){ x.setShenbaoStageNum(val[0]); x.setRowNum(val[1]); shenbaoStageNumMaps.remove(proName); } }); } //查询获取数据 return list; } @RequestMapping(name="资金类统计下载",path="exportExcelForMoney",method=RequestMethod.POST) @ResponseStatus(value = HttpStatus.NO_CONTENT) public void exportExcelForMoney(HttpServletRequest request,HttpServletResponse response) throws Exception{ //获取筛选条件 String type = request.getParameter("type"); String isIncludLibrary = request.getParameter("isIncludLibrary"); String stageSelect = StringUtils.strip(request.getParameter("stage"),"[]"); String unitSelect = StringUtils.strip(request.getParameter("unit"),"[]"); String industrySelect = StringUtils.strip(request.getParameter("industry"),"[]"); String categorySelect = StringUtils.strip(request.getParameter("category"),"[]"); String projectStageSelect = StringUtils.strip(request.getParameter("projectStage"),"[]"); String projectName = request.getParameter("projectName"); //处理请求参数 String[] stageSelected = Util.isNotNull(stageSelect)?stageSelect.split(",") :null; String[] unitSelected = Util.isNotNull(unitSelect)?unitSelect.split(",") :null; String[] industrySelected = Util.isNotNull(industrySelect)?industrySelect.split(",") : null; String[] categorySelected = Util.isNotNull(categorySelect)?categorySelect.split(",") : null; String[] projectStageSelected = Util.isNotNull(projectStageSelect)?projectStageSelect.split(",") : null; projectName = Util.isNotNull(projectName) ? new String(projectName.getBytes("iso-8859-1"),"utf-8") :null; //查询获取数据 List<ProjectStatisticsBean> list = ProjectService.getMoneyStatistics(isIncludLibrary,stageSelected,projectStageSelected,projectName,unitSelected,industrySelected,categorySelected); //数据处理 Map<String,Integer[]> shenbaoStageNumMaps = new HashMap<String,Integer[]>(); int rowNum = 0; for (int i = 0;i<list.size();i++){ ProjectStatisticsBean bean = list.get(i); String proName = bean.getProjectName(); //申报类型个数处理 Integer stageNum = shenbaoStageNumMaps.get(proName) != null ? shenbaoStageNumMaps.get(proName)[0]+1 : 1; //序号处理 rowNum = shenbaoStageNumMaps.get(proName) != null ? shenbaoStageNumMaps.get(proName)[1] : rowNum+1; Integer[] list1 = {stageNum,rowNum}; shenbaoStageNumMaps.put(proName,list1); } //处理数据展示编号及合并行 if(!list.isEmpty()){ list.stream().forEach(x -> { String proName = x.getProjectName(); Integer[] val = shenbaoStageNumMaps.get(proName); if(val != null){ x.setShenbaoStageNum(val[0]); x.setRowNum(val[1]); shenbaoStageNumMaps.remove(proName); } }); } try { String fileName = "光明区政府投资"+"项目资金"+"汇总表.xls"; String newexcelname = new String(fileName.getBytes("utf-8"),"ISO_8859_1"); response.reset(); response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-disposition", "attachment; filename=\"" + newexcelname + "\""); // 实现下载 HSSFWorkbook workbook = new GenerateExcelForMoney().getHSSFWorkBook(list,type,isIncludLibrary);//构建Excel workbook.write(response.getOutputStream());// 实现输出 response.flushBuffer(); }catch (Exception e) { e.printStackTrace(); } } @RequestMapping(name="项目总库-分类统计下载",path="exportExcelForProject",method=RequestMethod.GET) public ModelAndView exportExcelForProject(HttpServletRequest request,@RequestParam String classDesc,@RequestParam String isIncludLibrary) throws ParseException{ List<ProjectStatisticsBean> data = ProjectService.getProjectStatistics(classDesc,isIncludLibrary); return new ModelAndView(new ProjectStatisticsView(classDesc,isIncludLibrary), "data", data); } @RequestMapping(name="审批类-分类统计数据获取",path="getExcelForApprovalData",method=RequestMethod.GET) public @ResponseBody List<ProjectStatisticsBean> getExcelForApprovalData(HttpServletRequest request,@RequestParam String classDesc,@RequestParam String approvalYear) throws ParseException{ return shenBaoInfoService.getApprovalStatistics(classDesc,Integer.parseInt(approvalYear)); } @RequestMapping(name="审批类-分类统计下载",path="exportExcelForApproval",method=RequestMethod.GET) public ModelAndView exportExcelForApproval(HttpServletRequest request,@RequestParam String classDesc,@RequestParam String approvalYear) throws ParseException{ List<ProjectStatisticsBean> data = shenBaoInfoService.getApprovalStatistics(classDesc,Integer.parseInt(approvalYear)); return new ModelAndView(new ApprovalStatisticsView(classDesc,Integer.parseInt(approvalYear)), "data", data); } @RequestMapping(name="计划类-分类统计数据获取",path="getExcelForPlanData",method=RequestMethod.GET) public @ResponseBody List<ProjectStatisticsBean> getExcelForPlanData(HttpServletRequest request,@RequestParam String classDesc,@RequestParam String planYear) throws ParseException{ return shenBaoInfoService.getPlanStatistics(classDesc,Integer.parseInt(planYear)); } @RequestMapping(name="计划类-分类统计下载",path="exportExcelForPlan",method=RequestMethod.GET) public ModelAndView exportExcelForPlan(HttpServletRequest request,@RequestParam String classDesc,@RequestParam String planYear) throws ParseException{ List<ProjectStatisticsBean> data = shenBaoInfoService.getPlanStatistics(classDesc,Integer.parseInt(planYear)); return new ModelAndView(new PlanStatisticsView(classDesc,Integer.parseInt(planYear)), "data", data); } @RequestMapping(name="审批类-自定义条件统计数据获取",path="getApprovalCustomData",method=RequestMethod.POST) public @ResponseBody List<ProjectStatisticsBean> getApprovalCustomData(@SuppressWarnings("rawtypes") @RequestBody Map map) throws ParseException{ //获取筛选条件 String pifuDateBeginStr=map.get("pifuDateBegin").toString(); String pifuDateEndStr=map.get("pifuDateEnd").toString(); String investSumBeginStr=map.get("projectInvestSumBegin").toString(); String investSumEndStr=map.get("projectInvestSumEnd").toString(); String industrySelect=StringUtils.strip(map.get("industry").toString(),"[]"); String stageSelect=StringUtils.strip(map.get("stage").toString(),"[]"); String unitSelect=StringUtils.strip(map.get("unit").toString(),"[]"); //处理请求参数 Integer pifuDateBegin=Util.isNotNull(pifuDateBeginStr)?Integer.parseInt(pifuDateBeginStr,10):null; Integer pifuDateEnd=Util.isNotNull(pifuDateEndStr)?Integer.parseInt(pifuDateEndStr,10):null; Double investSumBegin=Util.isNotNull(investSumBeginStr)?Double.valueOf(investSumBeginStr):null; Double investSumEnd=Util.isNotNull(investSumEndStr)?Double.valueOf(investSumEndStr):null; String[] industrySelected = Util.isNotNull(industrySelect)?industrySelect.split(","):null; String[] stageSelected = Util.isNotNull(stageSelect)?stageSelect.split(","):null; String[] unitSelected = Util.isNotNull(unitSelect)?unitSelect.split(","):null; String projectName=Util.isNotNull(map.get("projectName").toString())?map.get("projectName").toString():null; //查询获取数据 return shenBaoInfoService.getApprovalStatisticsByCustom(pifuDateBegin,pifuDateEnd,industrySelected,stageSelected,unitSelected,investSumBegin,investSumEnd,projectName); } @RequestMapping(name="审批类-自定义条件统计下载",path="exportExcelForApprovalByCustom",method=RequestMethod.POST) @ResponseStatus(value = HttpStatus.NO_CONTENT) public void exportExcelForApprovalByCustom(HttpServletRequest request,HttpServletResponse response) throws Exception{ //获取筛选条件 String pifuDateBeginStr=request.getParameter("pifuDateBegin"); String pifuDateEndStr=request.getParameter("pifuDateEnd"); String investSumBeginStr=request.getParameter("projectInvestSumBegin"); String investSumEndStr=request.getParameter("projectInvestSumEnd"); String industrySelect=request.getParameter("industry"); String stageSelect=request.getParameter("stage"); String unitSelect=request.getParameter("unit"); //处理请求参数 Integer pifuDateBegin=Util.isNotNull(pifuDateBeginStr)?Integer.parseInt(pifuDateBeginStr,10):null; Integer pifuDateEnd=Util.isNotNull(pifuDateEndStr)?Integer.parseInt(pifuDateEndStr,10):null; Double investSumBegin=Util.isNotNull(investSumBeginStr)?Double.valueOf(investSumBeginStr):null; Double investSumEnd=Util.isNotNull(investSumEndStr)?Double.valueOf(investSumEndStr):null; String[] industrySelected = Util.isNotNull(industrySelect)?industrySelect.split(","):null; String[] stageSelected = Util.isNotNull(stageSelect)?stageSelect.split(","):null; String[] unitSelected = Util.isNotNull(unitSelect)?unitSelect.split(","):null; String projectName=Util.isNotNull(request.getParameter("projectName"))?new String(request.getParameter("projectName").getBytes("iso-8859-1"),"utf-8"):null; //查询获取数据 List<ProjectStatisticsBean> data = shenBaoInfoService.getApprovalStatisticsByCustom(pifuDateBegin,pifuDateEnd,industrySelected,stageSelected,unitSelected,investSumBegin,investSumEnd,projectName); try { String fileName="光明区政府投资计划类统计表.xls"; String newexcelname = new String(fileName.getBytes("utf-8"),"ISO_8859_1"); response.reset(); response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-disposition", "attachment; filename=\"" + newexcelname + "\""); // 实现下载 HSSFWorkbook workbook = new GenerateExcelForApproval().getHSSFWorkBook(data);//构建Excel workbook.write(response.getOutputStream());// 实现输出 response.flushBuffer(); }catch (Exception e) { e.printStackTrace(); } } @RequestMapping(name="计划类-自定义条件统计数据获取",path="getPlanCustomData",method=RequestMethod.POST) public @ResponseBody List<ProjectStatisticsBean> getPlanCustomData(@SuppressWarnings("rawtypes") @RequestBody Map map) throws ParseException{ //获取筛选条件 String investSumBeginStr= map.get("projectInvestSumBegin").toString(); String investSumEndStr= map.get("projectInvestSumEnd").toString(); String apPlanReachSumBeginStr=map.get("projectApPlanReachSumBegin").toString(); String apPlanReachSumEndStr=map.get("projectApPlanReachSumEnd").toString(); String industrySelect=StringUtils.strip(map.get("industry").toString(),"[]"); String stageSelect=StringUtils.strip(map.get("stage").toString(),"[]"); String unitSelect=StringUtils.strip(map.get("unit").toString(),"[]"); //处理请求参数 Double investSumBegin = Util.isNotNull(investSumBeginStr)?Double.valueOf(investSumBeginStr):null; Double investSumEnd = Util.isNotNull(investSumEndStr)?Double.valueOf(investSumEndStr):null; Double apPlanReachSumBegin=Util.isNotNull(apPlanReachSumBeginStr)?Double.valueOf(apPlanReachSumBeginStr):null; Double apPlanReachSumEnd=Util.isNotNull(apPlanReachSumEndStr)?Double.valueOf(apPlanReachSumEndStr):null; String[] industrySelected = Util.isNotNull(industrySelect)?industrySelect.split(","):null; String[] stageSelected = Util.isNotNull(stageSelect)?stageSelect.split(","):null; String[] unitSelected = Util.isNotNull(unitSelect)?unitSelect.split(","):null; String projectName=Util.isNotNull(map.get("projectName").toString())?map.get("projectName").toString():null; String planYearBegin=Util.isNotNull(map.get("planYearBegin").toString())?map.get("planYearBegin").toString():null; String planYearEnd=Util.isNotNull(map.get("planYearEnd").toString())?map.get("planYearEnd").toString():null; //查询获取数据 return shenBaoInfoService.getPlanStatisticsByCustom(planYearBegin,planYearEnd,industrySelected,stageSelected, unitSelected,investSumBegin,investSumEnd,apPlanReachSumBegin,apPlanReachSumEnd,projectName); } @RequestMapping(name="计划类-自定义条件统计下载",path="exportExcelForPlanByCustom",method=RequestMethod.POST) @ResponseStatus(value = HttpStatus.NO_CONTENT) public void exportExcelForPlanByCustom(HttpServletRequest request,HttpServletResponse response) throws Exception{ // 读取请求参数 String investSumBeginStr= request.getParameter("projectInvestSumBegin"); String investSumEndStr= request.getParameter("projectInvestSumEnd"); String apPlanReachSumBeginStr=request.getParameter("projectApPlanReachSumBegin"); String apPlanReachSumEndStr=request.getParameter("projectApPlanReachSumEnd"); String industrySelect=request.getParameter("industry"); String stageSelect=request.getParameter("stage"); String unitSelect=request.getParameter("unit"); //处理请求参数 /*Integer planYearBegin=Util.isNotNull(planYearBeginStr)?Integer.parseInt(planYearBeginStr,10):null; Integer planYearEnd=Util.isNotNull(planYearEndStr)?Integer.parseInt(planYearEndStr,10):null;*/ Double investSumBegin = Util.isNotNull(investSumBeginStr)?Double.valueOf(investSumBeginStr):null; Double investSumEnd = Util.isNotNull(investSumEndStr)?Double.valueOf(investSumEndStr):null; Double apPlanReachSumBegin=Util.isNotNull(apPlanReachSumBeginStr)?Double.valueOf(apPlanReachSumBeginStr):null; Double apPlanReachSumEnd=Util.isNotNull(apPlanReachSumEndStr)?Double.valueOf(apPlanReachSumEndStr):null; String[] industrySelected = Util.isNotNull(industrySelect)?industrySelect.split(","):null; String[] stageSelected = Util.isNotNull(stageSelect)?stageSelect.split(","):null; String[] unitSelected = Util.isNotNull(unitSelect)?unitSelect.split(","):null; String projectName=Util.isNotNull(request.getParameter("projectName"))?new String(request.getParameter("projectName").getBytes("iso-8859-1"),"utf-8"):null; String planYearBegin=Util.isNotNull(request.getParameter("planYearBegin"))?request.getParameter("planYearBegin").toString():null; String planYearEnd=Util.isNotNull(request.getParameter("planYearEnd"))?request.getParameter("planYearEnd").toString():null; //查询获取数据 List<ProjectStatisticsBean> data = shenBaoInfoService.getPlanStatisticsByCustom(planYearBegin,planYearEnd,industrySelected,stageSelected, unitSelected,investSumBegin,investSumEnd,apPlanReachSumBegin,apPlanReachSumEnd,projectName); try { String fileName="光明区政府投资计划类统计表.xls"; String newexcelname = new String(fileName.getBytes("utf-8"),"ISO_8859_1"); response.reset(); response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-disposition", "attachment; filename=\"" + newexcelname + "\""); // 实现下载 HSSFWorkbook workbook = new GenerateExcelForPlan().getHSSFWorkBook(data);//构建Excel workbook.write(response.getOutputStream());// 实现输出 response.flushBuffer(); }catch (Exception e) { e.printStackTrace(); } } @RequestMapping(name="项目总库-自定义条件统计数据获取",path="getProjectCustomData",method=RequestMethod.POST) public @ResponseBody List<ProjectStatisticsBean> getProjectCustomData(@SuppressWarnings("rawtypes") @RequestBody Map map) throws Exception{ // 读取请求参数 String investSumBeginStr= map.get("projectInvestSumBegin").toString(); String investSumEndStr= map.get("projectInvestSumEnd").toString(); String industrySelect=StringUtils.strip(map.get("industry").toString(),"[]"); String stageSelect=StringUtils.strip(map.get("stage").toString(),"[]"); String categorySelect=StringUtils.strip(map.get("category").toString(),"[]"); String unitSelect=StringUtils.strip(map.get("unit").toString(),"[]"); //处理请求参数 Double investSumBegin = Util.isNotNull(investSumBeginStr)?Double.valueOf(investSumBeginStr):null; Double investSumEnd = Util.isNotNull(investSumEndStr)?Double.valueOf(investSumEndStr):null; String[] industrySelected = Util.isNotNull(industrySelect)?industrySelect.split(","):null; String[] stageSelected = Util.isNotNull(stageSelect)?stageSelect.split(","):null; String[] categorySelected = Util.isNotNull(categorySelect)?categorySelect.split(","):null; String[] unitSelected = Util.isNotNull(unitSelect)?unitSelect.split(","):null; String projectName=Util.isNotNull(map.get("projectName").toString())?map.get("projectName").toString():null; String projectBegin = Util.isNotNull(map.get("projectBegin").toString())?map.get("projectBegin").toString():null; String projectEnd = Util.isNotNull(map.get("projectEnd").toString())?map.get("projectEnd").toString():null; //查询获取数据 return ProjectService.getProjectStatisticsByCustom(projectBegin,projectEnd,industrySelected,stageSelected, categorySelected,unitSelected,investSumBegin,investSumEnd,projectName); } /*@RequestMapping(name="获取审批类数据", path = "getApprovalAllData", method = RequestMethod.GET) public @ResponseBody PageModelDto<ProjectStatisticsBean> getApprovalAllData(ODataObj oDataObj){ PageModelDto<ProjectStatisticsBean> dto = shenBaoInfoService.getApprovalAllData(oDataObj); return dto; } @RequestMapping(name="获取计划类数据", path = "getPlanAllData", method = RequestMethod.GET) public @ResponseBody PageModelDto<ProjectStatisticsBean> getPlanAllData(ODataObj oDataObj){ PageModelDto<ProjectStatisticsBean> dto = shenBaoInfoService.getPlanAllData(oDataObj); return dto; } @RequestMapping(name="获取项目类数据", path = "getProjectAllData", method = RequestMethod.GET) public @ResponseBody PageModelDto<ProjectStatisticsBean> getProjectAllData(ODataObj oDataObj){ PageModelDto<ProjectStatisticsBean> dto = ProjectService.getProjectAllData(oDataObj); return dto; }*/ @RequestMapping(name = "获取资金类数据", path = "getProjectMoneyData", method = RequestMethod.GET) public @ResponseBody PageModelDto<ProjectStatisticsBean> getProjectMoneyData(ODataObj oDataObj){ PageModelDto<ProjectStatisticsBean> dto = ProjectService.getProjectMoneyData(oDataObj); return dto; } @RequestMapping(name="项目总库-自定义条件统计下载",path="exportExcelForProjectByCustom",method=RequestMethod.POST) @ResponseStatus(value = HttpStatus.NO_CONTENT) public void exportExcelForProjectByCustom(HttpServletRequest request,HttpServletResponse response) throws Exception{ // 读取请求参数 String investSumBeginStr= request.getParameter("projectInvestSumBegin"); String investSumEndStr= request.getParameter("projectInvestSumEnd"); String industrySelect=request.getParameter("industry"); String stageSelect=request.getParameter("stage"); String categorySelect=request.getParameter("category"); String unitSelect=request.getParameter("unit"); //处理请求参数 Double investSumBegin = Util.isNotNull(investSumBeginStr)?Double.valueOf(investSumBeginStr):null; Double investSumEnd = Util.isNotNull(investSumEndStr)?Double.valueOf(investSumEndStr):null; String[] industrySelected = Util.isNotNull(industrySelect)?industrySelect.split(","):null; String[] stageSelected = Util.isNotNull(stageSelect)?stageSelect.split(","):null; String[] categorySelected = Util.isNotNull(categorySelect)?categorySelect.split(","):null; String[] unitSelected = Util.isNotNull(unitSelect)?unitSelect.split(","):null; String projectName=Util.isNotNull(request.getParameter("projectName"))?new String(request.getParameter("projectName").getBytes("iso-8859-1"),"utf-8"):null; String projectBegin = Util.isNotNull(request.getParameter("projectBegin").toString())?request.getParameter("projectBegin").toString():null; String projectEnd = Util.isNotNull(request.getParameter("projectEnd").toString())?request.getParameter("projectEnd").toString():null; //查询获取数据 List<ProjectStatisticsBean> data = ProjectService.getProjectStatisticsByCustom(projectBegin,projectEnd,industrySelected,stageSelected,categorySelected,unitSelected,investSumBegin,investSumEnd,projectName); try { String fileName="光明区政府投资项目总库统计表.xls"; String newexcelname = new String(fileName.getBytes("utf-8"),"ISO_8859_1"); response.reset(); response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-disposition", "attachment; filename=\"" + newexcelname + "\""); // 实现下载 HSSFWorkbook workbook = new GenerateExcelForProject().getHSSFWorkBook(data);//构建Excel workbook.write(response.getOutputStream());// 实现输出 response.flushBuffer(); }catch (Exception e) { e.printStackTrace(); } } // @RequiresPermissions("management/auxDeci/statisticalAnalysis#html/index#get") @RequestMapping(name="统计分析主页",path="html/index",method=RequestMethod.GET) public String index(){ return ctrl+"/index"; } //@RequiresPermissions("management/auxDeci/statisticalAnalysis#html/edit#get") @RequestMapping(name="统计分析条件筛选页面",path="html/edit",method=RequestMethod.GET) public String edit(){ return ctrl+"/edit"; } //@RequiresPermissions("management/auxDeci/statisticalAnalysis#html/show#get") @RequestMapping(name="统计分析数据展示页面",path="html/show",method=RequestMethod.GET) public String show(){ return ctrl+"/show"; } }