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
3,247
3.546875
4
[]
no_license
package conversormoneda2.pkg0; import javax.swing.JOptionPane; /** * Clase para comvertir una cantidad de dólares, euros o yenes a pesos * * @author Bruno Blas Galeano y Nestor john. * */ public class ConversorMoneda2 { //Constantes con la cotización de las monedas final static double USD = 46.19; final static double EUR = 49.13; final static double YEN = 0.40; final static double LBS = 55.36; final static double BRL = 11.28; /** * Método principal. * * @param arg the command line arguments. */ public static void main(String[] args) { do{ String moneda1 = leerMoneda(); int cantidad1= leerCantidad(); String moneda2= leermoneda(); double cantidad2=convertirMoneda(moneda1,cantidad1,moneda2); String mensaje= moneda1+" "+cantidad1+" "+"equivalen a "+moneda2+" "+String.format("%,2f",cantidad2); JOptionPane.showMessageDialog(null , mensaje); while (!moneda1.equals("SALIR")) { } /** * Lee una moneda por teclado * * @return código de moneda USD, EUR o YEN. */ public static String leerMoneda() { String resultado; do { String texto = JOptionPane.showInputDialog("Indicar la moneda USD,EUR, YEN, LBS, BRL o SALIR"); resultado = texto.trim().toUpperCase(); } while (!resultado.equals("USD") && !resultado.equals("EUR") && !resultado.equals("YEN") && !resultado.equals("LBS") && !resultado.equals("BRL") && !resultado.equals("SALIR")); return resultado; } /** * Lee una cantidd de monedas del teclado. * * @paramoneda USD, EUR, YEN. * @return cantidad de monedas. */ public static int leerCantidad(String moneda) { int resultado = 0; do { String texto = JOptionPane.showInputDialog("indica la cantidad de " + moneda); resultado = Integer.parseInt(texto); } while (resultado <= 0); return resultado; } /** * Convierte una cantidad de moneda a pesos. * * @param moneda USD,EUR,YEN. * @param cantidad de monedas * @return importe en pesos */ public static double convertirMoneda(String moneda, double cantidad2,int moneda1, int moneda2) { double resultado; switch (moneda1) { case "USD": resultado = cantidad2 * moneda1/moneda2; break; case "EUR": resultado = cantidad2 * moneda1/moneda2; break; case "YEN": resultado = cantidad2 * moneda1/moneda2; break; case "LBS": resultado = cantidad2 * moneda1/moneda2; break; case "BRL": resultado = cantidad2 * moneda1/moneda2; break; default: resultado = 0; break; } return resultado; } private static int leerCantidad() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
Ruby
UTF-8
1,349
2.640625
3
[ "MIT" ]
permissive
module ExternalApiWrapper InvalidEndpointParamsError = Class.new(BaseError) class BaseEndpoint include ActsAsCallable def initialize(raw_params) check_raw_params_for_required_keys!(raw_params) @params = process_raw_params(raw_params) end def call http_response = do_http_request parse_response(http_response) end protected def required_params_keys raise NotImplementedError end def process_raw_params(_raw_params) raise NotImplementedError end def endpoint_path raise NotImplementedError end def response_parser raise NotImplementedError end private attr_reader :params def check_raw_params_for_required_keys!(raw_params) raw_params_keys = raw_params.keys required_params_keys.each do |required_key| next if raw_params_keys.include?(required_key) raise InvalidEndpointParamsError, "The entry with a key `#{required_key}` is required!" end end def do_http_request uri = build_uri ExternalApiWrapper::Http::Requester.call(uri: uri, headers: params.headers) end def parse_response(http_response) response_parser.call(http_response) end def build_uri Http::UriBuilder.call(path: endpoint_path, endpoint_params: params) end end end
C#
UTF-8
1,119
3.171875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CommonLibrary.Data { public static class DataPaginationExtension { public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int index, int pageSize) { return new PagedList<T>(source, index, pageSize); } } public class PagedList<T> : List<T> { private readonly int itemsRemaining; public int ItemsRemaining{ get { return itemsRemaining; } } private readonly int totalCount; public int TotalCount{get { return totalCount; }} public PagedList(IQueryable<T> source, int index, int pageSize) { index = index > 1 ? index - 1 : 0; totalCount = source.Count(); itemsRemaining = totalCount - ((index * pageSize) + pageSize); if (itemsRemaining < 0) { index = totalCount/pageSize; itemsRemaining = 0; } AddRange(source.Skip(index * pageSize).Take(pageSize)); } } }
Shell
UTF-8
1,453
2.953125
3
[ "MIT" ]
permissive
#!/bin/bash # register CA certificate CODE=`aws iot get-registration-code --output text` CASJ="/C=JP/ST=Hokkaido/L=Sapporo/O=fitzr/OU=root/CN=ROOTCA" VCSJ="/C=JP/ST=Hokkaido/L=Sapporo/O=fitzr/OU=verification/CN=${CODE}" # generate root CA certificate openssl genrsa -out rootCA.key 2048 openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 10950 -out rootCA.pem -subj "$CASJ" # generate verification certificate openssl genrsa -out verificationCert.key 2048 openssl req -new -key verificationCert.key -out verificationCert.csr -subj "$VCSJ" openssl x509 -req -in verificationCert.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out verificationCert.pem -days 10950 -sha256 # create Just In Time Provisioning policy aws iam create-role --role-name JITP_Role --assume-role-policy-document file://JITPAssumeRolePolicyDocument.json aws iam attach-role-policy --role-name JITP_Role --policy-arn arn:aws:iam::aws:policy/service-role/AWSIoTThingsRegistration aws iam attach-role-policy --role-name JITP_Role --policy-arn arn:aws:iam::aws:policy/service-role/AWSIoTLogging aws iam attach-role-policy --role-name JITP_Role --policy-arn arn:aws:iam::aws:policy/service-role/AWSIoTRuleActions # register certificate aws iot register-ca-certificate \ --ca-certificate file://rootCA.pem \ --verification-cert file://verificationCert.pem \ --set-as-active \ --allow-auto-registration \ --registration-config file://provisioning-template.json
Java
UTF-8
502
2.34375
2
[]
no_license
package com.example.banking; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.context.support.BeanDefinitionDsl; import org.springframework.stereotype.Component; //@Component - not allowed !!! public class Child { private String name; public String getName() { return "I'm CHILD and my name is:" + name; } public Child(String aName) { this.name = aName; } }
C++
UTF-8
3,082
2.671875
3
[]
no_license
#pragma once #include <vector> #include "RandomFactory.h" #include "Building.h" #include "Street.h" #include "TextureFactory.h" #include "BuildingsFactory.h" #include "Plane.h" #include "Lamp.h" #include "TrafficLights.h" #include "Point.h" #include "Vector3.h" std::vector<Building*> generateManhatanStyle(int n, int m); std::vector<Building*> generateParisStyle(int circles); Building* setRandomHeight(Building* building); Building* setRandomWidth(Building* building); std::vector<Building*> getBuildingsAlongStreets(std::vector<Street*> streets, TextureFactory texFactory); void getBuildingsAlongOneSideOfStreet(std::vector<Building*> &vec, MFloatPoint v1, MFloatPoint v2, TextureFactory texFactory, BuildingType bType); bool isBetween(MFloatPoint a, MFloatPoint x1, MFloatPoint x2); double countSegmentLength(const MFloatPoint& a1, const MFloatPoint& a2); MFloatPoint alignAndAdd(const MFloatPoint& v1, const MFloatPoint& v2, Building* b, std::vector<Building*>& vec, const MFloatPoint& curr); bool turningNeeded(MFloatPoint x, MFloatPoint y, MFloatPoint v, MFloatPoint w); BuildingType getBuildingTypeByDistanceFromCentre(int cityWidth, int cityLength, int x, int y); void addParkPoints(std::vector<std::vector<int>> &parkPoints, int x, int y, int vertStreetLength, int vertStreetWidth, int horStreetLength, int horStreetWidth); Primitive* createLamp(TextureFactory texFactory, double x, double y, MFloatPoint v1, MFloatPoint v2, double rotation); //streets std::vector<Street*> getStreetSystem(); std::vector<Street*> getManhatanStreetSystem(TextureFactory texFactory, int cityWidth, int cityLength, int vertStreetWidth, int vertStreetLength, int horStreetWidth, int horStreetLength); std::vector<Primitive*> getAdditives(std::vector<Street*> streets, TextureFactory texFactory, int cityWidth, int cityLength, int vertStreetWidth, int vertStreetLength, int horStreetWidth, int horStreetLength); void addLamp(TextureFactory texFactory, Street* str, std::vector<Primitive*>& res); void addTrafficLight(TextureFactory texFactory, Street* str, std::vector<Primitive*>& res); //basic std::vector<unsigned> range(unsigned count); std::vector<unsigned> randRange(unsigned count); double countDistance(Point p, Point q); double pow2(double a); //vector bool intersects(RoadConnection a, RoadConnection b); Point intersectionPoint(RoadConnection a, RoadConnection b); double vectorProduct(Vector3 v, Vector3 u); void removeDuplicates(std::vector<size_t>& vec); template <typename T> long findElement(std::vector<T> vec, T elem) { for (long i = 0; i < vec.size(); ++i) if (vec[i] == elem) return i; return -1; } template <typename T> void addAll(std::vector<T>& vec, std::vector<T>& vecToAdd) { for (auto elem : vecToAdd) vec.push_back(elem); } template <typename T> void addAllFromIndex(std::vector<T>& vec, std::vector<T>& vecToAdd, unsigned j) { for (unsigned i = j; i < vecToAdd.size(); ++i) vec.push_back(vecToAdd[i]); } //debug void showDebug(std::string a); void showDebug(double a); void printOnTerminal(std::string a); void printOnTerminal(double a);
Java
UTF-8
699
3.53125
4
[]
no_license
import java.util.ArrayList; public class Hand extends ArrayList<Card> implements Comparable<Hand>{ public Hand() { } public int score() { int s = 0; boolean hasAce = false; for(Card c : this) { s += c.getValue(); if(c.getRank() == "ace") { hasAce = true; } } if (s > 21) { if(hasAce) { s -= 10; } else { s = 0; } } return s; } public int compareTo(Hand other) { int sum1 = this.score(); int sum2 = other.score(); if(sum1==sum2) { return 0; } else if(sum1>sum2) { return 1; } else { return -1; } } @Override public String toString() { String s = ""; for(Card c : this) { s += c; s += "\n"; } return s; } }
Java
UTF-8
212
2.03125
2
[]
no_license
package finaltesttask; public class test1 { public static void main(String[] args) { String s = "Hello World"; System.out.println(s); //or, System.out.println("Hello World"); } }
PHP
UTF-8
698
2.765625
3
[]
no_license
<?php // How to convert a webpage to a PDF and stream it to the client browser as an attachment $api_endpoint = "http://selectpdf.com/api2/convert/"; $key = 'your license key here'; $test_url = 'http://selectpdf.com'; $parameters = array ('key' => $key, 'url' => $test_url); // Sample GET $result = @file_get_contents("$api_endpoint?" . http_build_query($parameters)); if (!$result) { echo "HTTP Response: " . $http_response_header[0] . "<br/>"; $error = error_get_last(); echo "Error Message: " . $error['message']; } else { // set HTTP response headers header("Content-Type: application/pdf"); header("Content-Disposition: attachment; filename=\"test.pdf\""); echo ($result); } ?>
Markdown
UTF-8
1,036
2.59375
3
[]
no_license
# Homework 5 by Paul Alves In this project, I examine energy usage in the city of Chicago. Done for my Computing for Social Sciences class. Script / report is under copyright. Do not modify or redistribute. ## Files: clean.r - Script to clean and import the base data included. Run this first to produce the clean data needed for analysis. This may take a while, so be patient while it generates. The resulting file is about 2 / 2.5 GB. Be careful if running on a low end PC or off a USB device as it will be slow and may crash the computer. Energy_Usage_2010.csv - https://data.cityofchicago.org/Environment-Sustainable-Development/Energy-Usage-2010/8yq3-m6wp Data regarding energy usage in Chicago for the year 2010. hw05.(r)md - The report itself. Generate data using clean.r first. Census_Data\_-\_Selected_socioeconomic_indicators_in_Chicago__2008___2012.csv - https://data.cityofchicago.org/Health-Human-Services/Census-Data-Selected-socioeconomic-indicators-in-C/kn9c-c2s2 Data for socioeconomic indicators per community area.
C++
UTF-8
901
3.265625
3
[]
no_license
#include "Player.h" Player::Player(const char* name, char sign) : sign(sign) { this->name = new char[strlen(name) + 1]; strcpy(this->name, name); } Player::Player(const Player& other) { copyData(other); } Player& Player::operator=(const Player& other) { if (this != &other) { deleteData(); copyData(other); } return *this; } Player::~Player() { deleteData(); } void Player::setPlayerName(const char* str) { name = new char[strlen(str) + 1]; strcpy(name, str); } void Player::setPlayerSymbol(const char c) { sign = c; } const char* Player::getPlayerName() const { return name; } char Player::getPlayerSymbol() const { return sign; } void Player::copyData(const Player& other) { sign = other.sign; name = new char[strlen(other.name) + 1]; strcpy(name, other.name); } void Player::deleteData() { delete[] name; }
Markdown
UTF-8
10,677
2.8125
3
[ "MIT" ]
permissive
# Regarding this fork This is a fork of the original [ngQuickDate](https://github.com/gildorwang/ngQuickDate) by [Adam Albrecht](https://github.com/adamalbrecht). There are several improvements over the original version: * Support of UTC timezone * Data-binding of configurations (`timezone`, `disableTimepicker`, `disableClearButton`, more to be supported) * Clicking on a date will not close the calendar pop-out if timepicker is not disabled * Time is set to `defaultTime` when date is inputed (by the textbox or mouse click) * Ability to override template with custom URI/id (thanks [@alexborisov](https://github.com/alexborisov)!) Note: To support the timezone feature, the dependency of Angular is upgraded to 1.3+. --- # ngQuickDate ngQuickDate is an [Angular.js](http://angularjs.org/) Date/Time picker directive. It stresses speed of data entry and simplicity while being highly configurable and easy to re-style. ![ngQuickDate Screenshot](https://raw.github.com/adamalbrecht/ngQuickDate/master/screenshot.png) ## Download * [Version 1.4.0](https://github.com/gildorwang/ngQuickDate/archive/v1.4.0.zip) * Only compatible with Angular 1.3.x. For a version compatible with Angular 1.0.x, checkout the angular-1.0 branch. You can also install the package using [Bower](http://bower.io). ```sh bower install gildorwang-ng-quick-date ``` Or add it to your bower.json file: ```javascript dependencies: { "ngQuickDate": "~1.3.0" } ``` *No dependencies (besides Angular) are required, but its date parsing capabilities can be improved by 3rd party libraries. See [Smarter Date/Time Parsing](#smarter-datetime-parsing) for more info. And it's styling can be improved by using a font icon library like [Font Awesome](http://fontawesome.io/). See the [Styling](#styling) and [Configuration](#configuration-options) sections.* ## Demo You can find some basic examples [here](http://adamalbrecht.github.io/ngQuickDate) ## The Basics To use the library, include the JS file, main CSS file, and (optionally, but recommended) the theme CSS file. Then include the module in your app: ```javascript app = angular.module("myApp", ["ngQuickDate"]) ``` The directive itself is simply called *datepicker*. The only required attribute is ngModel, which should be a date object. ```html <quick-datepicker ng-model='myDate'></quick-datepicker> ``` * Note: This should just be `<datepicker>` before version 1.3 ## Inline Options There are a number of options that be configured inline with attributes. Here are a few: | Option | Default | Description | | -------------------- | ------------------- | ------------------------------------------------------------------------------------------- | | date-format | "M/d/yyyy" | Date Format used in the date input box. Has no effect in UTC mode. | | time-format | "h:mm a" | Time Format used in the time input box. Has no effect in UTC mode. | | label-format | null | Date/Time format used on button. If null, will use combination of date and time formats. | | placeholder | 'Click to Set Date' | Text that is shown on button when the model variable is null. | | required | false | Makes the field required. Will set $invalid on the control and the form otherwise | | hover-text | null | Hover text for button. | | icon-class | null | If set, `<i class='some-class'></i>` will be prepended inside the button | | disable-timepicker | false | If true, the timepicker will be disabled and the default label format will be just the date | | disable-clear-button | false | If true, the clear button will be removed | | on-change | null | Set to a function that will be called when the date is changed | | default-time | null | Time that will be set when you click on a date on the calendar. Must be in 24-hour format. | | init-value | null | Set the initial value of the date inline as a string. Will be immediately parsed and set as the value of your model.| | date-filter | null | Set to a function to enable/disable dates. Useful for disabling weekends, etc. [See more below](#date-filter-function) | | timezone | null | Set to `'UTC'` to use UTC timezone. | **Example:** ```html <quick-datepicker ng-model='myDate' date-format='EEEE, MMMM d, yyyy' placeholder='Pick a Date' disable-timepicker='true'></quick-datepicker> ``` ```html <quick-datepicker ng-model='myDate' placeholder='Pick a Date' disable-timepicker='true' timezone='UTC'></quick-datepicker> ``` ## Configuration Options If you want to use a different default for any of the inline options, you can do so by configuring the datepicker during your app's configuration phase. There are also several options that may only be configured in this way. ```javascript app.config(function(ngQuickDateDefaultsProvider) { ngQuickDateDefaultsProvider.set('option', 'value'); // Or with a hash ngQuickDateDefaultsProvider.set({option: 'value', option2: 'value2'}); }) ``` | Option | Default | Description | | ------------------- | ---------------- | --------------------------------------------------------------------------------------------------- | | all inline options | see above table | Note that they must be in camelCase form. | | buttonIconHtml | null | If you want to set a default button icon, set it to something like `<i class='icon-calendar'></i>` | | closeButtonHtml | 'X' | By default, the close button is just an X character. You may set it to an icon similar to `buttonIconHtml` | | nextLinkHtml | 'Next' | By default, the next month link is just text. You may set it to an icon or image. | | prevLinkHtml | 'Prev' | By default, the previous month link is just text. You may set it to an icon or image. | | dayAbbreviations | (see below) | The day abbreviations used in the top row of the calendar. | | parseDateFunction | (see below) | The function used to convert strings to date objects. | **Default Day Abbreviations:** `["Su", "M", "Tu", "W", "Th", "F", "Sa"]` **Default Parse Date Function:** ```javascript function(str) { var seconds = Date.parse(str); return isNaN(seconds) ? null : new Date(seconds); } ``` ## Smarter Date/Time Parsing By default, dates and times entered into the 2 input boxes are parsed using javascript's built-in `Date.parse()` function. This function does not support many formats and can be inconsistent across platforms. I recommend using either the [Sugar.js](http://sugarjs.com/) or [Date.js](http://www.datejs.com/) library instead. Of the 2, I recommend definitely Sugar. If you'd like to use Sugar, you can configure it to work like so: ```javascript app.config(function(ngQuickDateDefaultsProvider) { ngQuickDateDefaultsProvider.set('parseDateFunction', function(str) { d = Date.create(str); return d.isValid() ? d : null; }); }) ``` And with Date.js: ```javascript parseDateFunction: function(str) { return Date.parse(str); } ``` Of course, you can override this parse function with any code you'd like, so you're also free to swap in another library or write your own parser. ## Date Formatting Note that when displaying dates in a well-formatted manner, Angular's [Date filter](http://docs.angularjs.org/api/ng.filter:date) is used. So if you want to customize these formats, please reference that link to see the formatting syntax. Sugar.js and Date.js have their own formatting syntax that are different from Angular's. ## Date Filter Function If you'd like to prevent the user from choosing certain dates, such as weekends or dates that have already been 'reserved', you can do so with the `date-filter` attribute. For example, if you want to disable weekends, you can do it like so: ```html <quick-datepicker ng-model='myDate' date-filter='onlyWeekdays'></quick-datepicker> ``` ```javascript $scope.onlyWeekdays = function(d) { dayIndex = d.getDay(); return ((dayIndex != 0) && (dayIndex != 6)); } ``` You can also set a default date filter function in the [configuration options](#configuration-options) ## Styling There is a very light set of styles that allow the datepicker to function, but isn't particularly pretty. From there you can either use the default theme that's included or you can easily write your own theme. You can improve it's appearance quite a bit by using a Font Icon library like [Font Awesome](http://fontawesome.io/). To make look like the screenshot above, you'd need Font Awesome 4.0 and the following configuration: ```javascript app.config(function(ngQuickDateDefaultsProvider) { // Configure with icons from font-awesome return ngQuickDateDefaultsProvider.set({ closeButtonHtml: "<i class='fa fa-times'></i>", buttonIconHtml: "<i class='fa fa-calendar'></i>", nextLinkHtml: "<i class='fa fa-chevron-right'></i>", prevLinkHtml: "<i class='fa fa-chevron-left'></i>" }); }); ``` ## Browser Support So far, it has only been tested in Chrome. ## Contributing Contributions are welcome. Whenever possible, please include test coverage with your contribution. 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request To get the project running, you'll need [NPM](https://npmjs.org/) and [Bower](http://bower.io/). Run `npm install` and `bower install` to install all dependencies. Then run `grunt` in the project directory to watch and compile changes. And you can run `karma start` to watch for changes and auto-execute unit tests. ## Potential Features down the road * Optimize for Mobile (It works fine now, but it could be slightly improved)
C#
UTF-8
985
3.1875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using Core.ObjectGraphs; namespace Orange.Library { public static class EnumerationHelper { public static ObjectGraph EnumToGraph<T>(this IEnumerable<T> enumerable, string name, Func<T, string> keyFunc = null, Func<string, T, ObjectGraph> valueFunc = null) { var index = new GraphIndexer(); if (keyFunc == null) { keyFunc = v => index.ToString(); } if (valueFunc == null) { valueFunc = (k, v) => new ObjectGraph(k, v.ToString(), v.GetType().Name); } var graph = new ObjectGraph(name, type: $"IEnumerable<{typeof(T).Name}>"); foreach (var value in enumerable) { var key = keyFunc(value); graph[key] = valueFunc(key, value); } return graph; } public static IEnumerable<T> EnumFromGraph<T>(this ObjectGraph graph, Func<ObjectGraph, T> func) => graph.Children.Select(func); } }
JavaScript
UTF-8
1,263
2.875
3
[]
no_license
$(function() { $.get('/charts', function(charts) { var dataStr=""; var imgStr=""; var gridster = $("section#charts").gridster({ widget_margins: [5, 5], widget_base_dimensions: [255, 155] }).data('gridster'); var carray = $.map(charts, function(value, index) { return [value]; }); // loop through each row for(var i=1; i<carray.length; i++){ var rarray = $.map(carray[i], function(value, index) { return [value]; }); // loop through each column // columns 1 and 2 are skipped - they have meta data, not chart data for(var j=2; j<rarray.length; j++){ // store the values in a string dataStr+=rarray[j].value; if(rarray[j+1]) // append comma to all but last value dataStr+=","; } // generate the Google Charts URL imgStr='<img src="//chart.googleapis.com/chart?cht='+rarray[0].value+'&chtt='+rarray[1].value+'&chs=250x150&chd=t:'+dataStr+'&chxt=x,y&chxs=0,c0c0c0,10,0,lt|1,c0c0c0,10,1,lt&chco=000000" />'; // Add them to the page using gridster api gridster.add_widget('<span id="chart'+i+'">'+imgStr+'</span>', 1, 1); dataStr=""; // clear the data string for next loop } }); });
JavaScript
UTF-8
2,694
2.640625
3
[]
no_license
const express = require('express'); const router = express.Router(); //const fetch = require('node-fetch'); const request = require('request'); router.get('/monthly/celsius', async (req, res) => { const CityStateCountry = req.query.CityStateCountry; const api_key = process.env.API_KEY; const maps_key = process.env.API; request(`https://maps.googleapis.com/maps/api/geocode/json?address=${CityStateCountry}&key=${maps_key}`, function (err, response, body) { if (err) { console.log('error:' , error); } else { let bodydata = JSON.parse(body); console.log('body:', bodydata.results[0].geometry.location); lat = bodydata.results[0].geometry.location.lat; lon = bodydata.results[0].geometry.location.lng; const weather_url = `https://pro.openweathermap.org/data/2.5/forecast/climate?lat=${lat}&lon=${lon}&units=metric&appid=${api_key}` request(weather_url, function (err, response, body) { if (err) { console.log('error:', error); } else { // console.log('body:', body); let data = JSON.parse(body); //console.log('date:', new Date(data.current.dt*1000)); // console.log('date:', moment.unix(data.current.dt).format("MM/DD/YYYY")); // console.log('time:', moment.unix(data.current.dt).format("LTS")); res.status(200).json(data); } }); } }) }) router.get('/monthly/farenheit', async (req, res) => { const CityStateCountry = req.query.CityStateCountry; const api_key = process.env.API_KEY; const maps_key = process.env.API; request(`https://maps.googleapis.com/maps/api/geocode/json?address=${CityStateCountry}&key=${maps_key}`, function (err, response, body) { if (err) { console.log('error:', error); } else { let bodydata = JSON.parse(body); console.log('body:', bodydata.results[0].geometry.location); lat = bodydata.results[0].geometry.location.lat; lon = bodydata.results[0].geometry.location.lng; const weather_url = `https://pro.openweathermap.org/data/2.5/forecast/climate?lat=${lat}&lon=${lon}&units=imperial&appid=${api_key}` request(weather_url, function (err, response, body) { if (err) { console.log('error:', error); } else { // console.log('body:', body); let data = JSON.parse(body); //console.log('date:', new Date(data.current.dt*1000)); // console.log('date:', moment.unix(data.current.dt).format("MM/DD/YYYY")); // console.log('time:', moment.unix(data.current.dt).format("LTS")); res.status(200).json(data); } }); } }) }) module.exports = router;
Python
UTF-8
6,395
2.578125
3
[]
no_license
import textwrap import frida import os import sys import frida.core import argparse import logging import string import re logo = """ ______ _ _ | ___| (_) | | | |_ _ __ _ __| |_ _ _ __ ___ _ __ | _| '__| |/ _` | | | | '_ ` _ \| '_ \\ | | | | | | (_| | |_| | | | | | | |_) | \_| |_| |_|\__,_|\__,_|_| |_| |_| .__/ | | |_| """ # Reading bytes from session and saving it to a file def dump_to_file(session,base,size,error,directory): try: filename = str(hex(base))+'_dump.data' dump = session.read_bytes(base, size) f = open(os.path.join(directory,filename), 'wb') f.write(dump) f.close() return error except: print "Oops, memory access violation!" return error #Read bytes that are bigger than the max_size value, split them into chunks and save them to a file def splitter(session,base,size,max_size,error,directory): times = size/max_size diff = size % max_size if diff is 0: logging.debug("Number of chunks:"+str(times+1)) else: logging.debug("Number of chunks:"+str(times)) global cur_base cur_base = base for time in range(times): logging.debug("Save bytes: "+str(hex(cur_base))+" till "+str(hex(cur_base+max_size))) dump_to_file(session, cur_base, max_size, error, directory) cur_base = cur_base + max_size if diff is not 0: logging.debug("Save bytes: "+str(hex(cur_base))+" till "+str(hex(cur_base+diff))) dump_to_file(session, cur_base, diff, error, directory) # Progress bar function def printProgress (times, total, prefix ='', suffix ='', decimals = 2, bar = 100): filled = int(round(bar * times / float(total))) percents = round(100.00 * (times / float(total)), decimals) bar = '#' * filled + '-' * (bar - filled) sys.stdout.write('%s [%s] %s%s %s\r' % (prefix, bar, percents, '%', suffix)), sys.stdout.flush() if times == total: print("\n") # A very basic implementations of Strings def strings(filename,directory, min=4): strings_file = os.path.join(directory,"strings.txt") path = os.path.join(directory,filename) str_list = re.findall("[A-Za-z0-9/\-:;.,_$%'!()[\]<> \#]+",open(path,"rb").read()) with open(strings_file,"ab") as st: for string in str_list: if len(string)>min: logging.debug(string) st.write(string+"\n") # Main Menu def MENU(): parser = argparse.ArgumentParser( prog='fridump', formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent("")) parser.add_argument('process', help='the process that you will be injecting to') parser.add_argument('-o', '--out', type=str, help='provide full output directory path. (def: \'dump\')', metavar="dir") parser.add_argument('-u', '--usb', action='store_true', help='device connected over usb') parser.add_argument('-v', '--verbose', action='store_true', help='verbose') parser.add_argument('-r','--read-only',action='store_true', help="dump read-only parts of memory. More data, more errors") parser.add_argument('-s', '--strings', action='store_true', help='run strings on all dump files. Saved in output dir.') parser.add_argument('--max-size', type=int, help='maximum size of dump file in bytes (def: 20971520)', metavar="bytes") args = parser.parse_args() return args def pause_exit(retCode, message): print(message) sys.exit(retCode) print logo arguments = MENU() # Define Configurations #APP_NAME = arguments.process try: APP_NAME = int(arguments.process) except: APP_NAME = arguments.process DIRECTORY = "" USB = arguments.usb DEBUG_LEVEL = logging.INFO STRINGS = arguments.strings MAX_SIZE = 20971520 PERMS = 'rw-' if arguments.read_only: PERMS = 'r--' if arguments.verbose: DEBUG_LEVEL = logging.DEBUG logging.basicConfig(format='%(levelname)s:%(message)s', level=DEBUG_LEVEL) # Start a new Session session = None try: if USB: session = frida.get_usb_device().attach(APP_NAME) else: session = frida.attach(APP_NAME) except: print "Can't connect to App. Have you connected the device?" sys.exit(0) # Selecting Output directory if arguments.out is not None: DIRECTORY = arguments.out if not os.path.exists(DIRECTORY): print "Creating directory..." os.makedirs(DIRECTORY) else: print "Current Directory: " + str(os.getcwd()) DIRECTORY = os.path.join(os.getcwd(), "dump") print "Output directory is set to: " + DIRECTORY if not os.path.exists(DIRECTORY): print "Creating directory..." os.makedirs(DIRECTORY) mem_access_viol = "" print "Starting Memory dump..." Memories = session.enumerate_ranges(PERMS) if arguments.max_size is not None: MAX_SIZE = arguments.max_size i = 0 l = len(Memories) # Performing the memory dump for memory in Memories: base = memory.base_address logging.debug("Base Address: " + str(hex(base))) logging.debug("") size = memory.size logging.debug("Size: " + str(size)) if size > MAX_SIZE: logging.debug("Too big, splitting the dump into chunks") mem_access_viol = splitter(session, base, size, MAX_SIZE, mem_access_viol, DIRECTORY) continue mem_access_viol = dump_to_file(session, base, size, mem_access_viol, DIRECTORY) i += 1 printProgress(i, l, prefix='Progress:', suffix='Complete', bar=50) print # Run Strings if selected if STRINGS: files = os.listdir(DIRECTORY) i = 0 l = len(files) print "Running strings on all files:" for f1 in files: strings(f1, DIRECTORY) i += 1 printProgress(i, l, prefix='Progress:', suffix='Complete', bar=50) print "Finished!" raw_input('Press Enter to exit...')
Python
UTF-8
1,545
2.625
3
[ "MIT" ]
permissive
from django.contrib.auth.models import User from django.core.mail import EmailMultiAlternatives from .models import Subscriber, Post, Log def notify_new_content(post_id): """ Sending and email. :param post_id: Post id. """ subscribers = Subscriber.objects.all() post = Post.objects.get(id=post_id) for subscriber in subscribers: html_content = f"¡Hola {subscriber.full_name}! Te informamos que tenemos " \ f"un nuevo contenido: <b>{post.title}<b>" msg = EmailMultiAlternatives(f"¡Nuevo contenido!", html_content, 'from@example.com', [subscriber.email]) msg.attach_alternative(html_content, "text/html") msg.send() log = Log(sent_to=subscriber.email, data=html_content) log.save() def notify_new_subscriber(subscriber_id): """ Sending and email. :param subscriber_id: Subscriber id """ subscriber = Subscriber.objects.get(id=subscriber_id) staffs = User.objects.filter(is_staff=True) for user in staffs: html_content = f"¡Hola {user.first_name}! Te informamos se "\ f"registró una nueva persona:" \ f"<p><b>Nombre:</b> {subscriber.full_name}<br> " \ f"<b>Email:</b> {subscriber.email}</p>" msg = EmailMultiAlternatives(f"¡Nuevo suscriptor!", html_content, 'from@example.com', [user.email]) msg.attach_alternative(html_content, "text/html") msg.send() log = Log(sent_to=user.email, data=html_content) log.save()
Java
UTF-8
819
3.625
4
[]
no_license
package Turma29; import java.util.Scanner; public class AwEx02 { public static void main(String[] args) { int[] a=new int[6]; int par=0,impar=0,somap=0,somai=0; Scanner l =new Scanner(System.in); for(int x=0;x<6;x++) { System.out.println("Entre com o valor "); a[x]=l.nextInt(); if(a[x]%2==0) { somap+=a[x]; } else { somai+=a[x]; } } System.out.println("\nValores pares e sua soma "); for(int x=0;x<6;x++) { if(a[x]%2==0) { System.out.println(a[x]); } } System.out.println("\nAs somas de par"); System.out.println(somap); System.out.println("\nValores impares "); for(int x=0;x<6;x++) { if(a[x]%2==1) { System.out.println(a[x]); } } System.out.println("\nAs somas de impar"); System.out.println(somai); } }
Ruby
UTF-8
563
4.15625
4
[]
no_license
puts "salida" my_variable = 5 if my_variable > 0 puts my_variable end #arrays games_played = [["uno", true], ["dos", false]] puts games_played puts games_played[0][0] #hashes cocktail = {"martini" => { "vodka" => true, "gin" => false, } } puts "------" puts cocktail["martini"]["vodka"] #Array sorting my_array = [1, 2, 3] puts my_array puts my_array.map odd_or_even = my_array.map do |element| element % 2 == 0 ? "even" : "odd" end puts "11111111111" puts odd_or_even
Ruby
UTF-8
2,644
2.953125
3
[]
no_license
# POST is for creating new resource instances # POST to resource URI, Provide JSON payload (optional), Provide MIME type of the payload # in the Content-Type header MoviesWS.post("/movies.json", :body => { :movie => {:id => "54321", :title => "rocky54"}}.to_json, :headers => { "Content-Type" => "application/json"}) # without: :headers => { "Content-Type" => "application/json"} => incorrect parsing # PUT is for replacing the data (update) # client => issues PUT request, issues request to /movies/54321 URI, provides # JSON payload for update and application/json MIME type response = MoviesWS.put("/movies/54321.json", :body => { :movie => { :title => "rocky5400", :foo => "bar"}}.to_json, :headers => { "Content-Type" => "application/json"}) # PUT(update) - action # PUT expects primary key to be in :id param; if the movie is found, processing # continues; builds white-list-checked set of params; supplies values to update # method; returns the result doc # PATCH is for partially updating a resource # update a field vs entire resource MoviesWS.patch("/movies/54321.json", :body => { :movie => { :title => "rocky5402", :foo => "bar"}}.to_json, :headers => { "Content-Type" => "application/json"}) # from rails implementation standpoint (scaffolding and command standpoint) PATCH and PUT # have the same implementation => it's for less bandwith => PATCH will use less bandwith # HEAD # basically GET without response body; useful to retrieve meta-info written in # response headers; issue GET and store Etag for comparison later response = MoviesWS.get("/movies/54321.json") response.header["etag"] doc = response.parsed_response response = MoviesWS.head("/movies/54321.json") response.header["etag"] doc = response.parsed_response # rets nil # HEAD, and then if etag changes, then you fetch actual data with GET # now we'll make a change (can save etag from get or head in var etag_before) response = MoviesWS.patch("/movies/54321.json", :body => { :movie => { :title => "rocky5500", :foo => "bar"}}.to_json, :headers => { "Content-Type" => "application/json"}) etag_after = response.header["etag"] # etag changed # DELETE # for deleting a resource; accepts and :id param from the URI and removes # that doc from the db; no request body response = MoviesWS.delete("/movies/54321.json") response.response response.response.code doc = response.parsed_response # rets nil # GET # get is for data retrieval only; free of side effects, property also known as idempotence MoviesWS.get("/movies.json?title=rocky25&foo=1&bar=2&baz=3").parsed_response # HTTP methods map to CRUD operations; are elegant and easy for the clients
Java
UTF-8
1,222
2.25
2
[]
no_license
package com.cos.controller.member; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.cos.action.Action; import com.cos.dao.MemberDAO; import com.cos.dto.MemberVO; import com.cos.util.SHA256; import com.cos.util.Script; public class MemberAccountAction implements Action{ private static String naming ="MemberAccountAction : "; @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = "member/accountForm.jsp"; HttpSession session = request.getSession(); MemberVO member = new MemberVO(); MemberDAO dao = new MemberDAO(); String id = null; if(session.getAttribute("id") != null){ id = (String)session.getAttribute("id"); } member = dao.account(id); if(member !=null) { request.setAttribute("member", member); RequestDispatcher dis = request.getRequestDispatcher(url); dis.forward(request, response); }else { Script.moving(response, "잘못된 접근입니다."); } } }
Java
UTF-8
8,150
2.171875
2
[]
no_license
/* * * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * MyApp.java * * Created on 5 Feb, 2013, 9:06:40 PM */ package sruds; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JTextArea; /** * * @author UDAY */ public class MyApp extends javax.swing.JFrame { /** Creates new form MyApp */ JFileChooser jfc = new JFileChooser(); public MyApp() { initComponents(); } private MyApp(String string) { super(string); initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { queryLabel = new javax.swing.JLabel(); templateLabel = new javax.swing.JLabel(); queryField = new javax.swing.JTextField(); templateField = new javax.swing.JTextField(); qbrowse = new javax.swing.JButton(); tbrowse = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); check = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); clear = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); queryLabel.setText(" QUERY FILE"); getContentPane().add(queryLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 170, 150, -1)); templateLabel.setText(" TEMPLATE FILE"); getContentPane().add(templateLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 130, 150, -1)); getContentPane().add(queryField, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 170, 160, -1)); getContentPane().add(templateField, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 130, 160, -1)); qbrowse.setText("Browse"); qbrowse.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { qbrowseActionPerformed(evt); } }); getContentPane().add(qbrowse, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 170, 80, -1)); tbrowse.setText("Browse"); tbrowse.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tbrowseActionPerformed(evt); } }); getContentPane().add(tbrowse, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 130, 80, -1)); jLabel1.setFont(new java.awt.Font("Simplified Arabic Fixed", 1, 36)); jLabel1.setText(" Crib Detector"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 30, 530, 80)); check.setText("Check!!!!!"); check.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkActionPerformed(evt); } }); getContentPane().add(check, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 250, -1, -1)); jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jScrollPane1.setAutoscrolls(true); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 290, 1360, 110)); clear.setText("clear"); clear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearActionPerformed(evt); } }); getContentPane().add(clear, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 420, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void qbrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_qbrowseActionPerformed // TODO add your handling code here: jfc.setDialogTitle("Query File"); if(jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File t=jfc.getSelectedFile(); String a=t.getPath(); //t.toString(); queryField.setText(a); //code to handle choosed file here. } }//GEN-LAST:event_qbrowseActionPerformed private void tbrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbrowseActionPerformed // TODO add your handling code here: // JFileChooser jfc = new JFileChooser(); jfc.setDialogTitle("Template File"); if(jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { //code to handle choosed file here. File t=jfc.getSelectedFile(); String a=t.getPath(); //t.toString(); templateField.setText(a); } }//GEN-LAST:event_tbrowseActionPerformed private void checkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkActionPerformed // TODO add your handling code here: String []argument=new String[2]; argument[0]=queryField.getText(); argument[1]=templateField.getText(); //System.out.println("INSIDE my app"+argument[0]); JTextArea textArea = new JTextArea(500, 100); textArea.setVisible(true); PrintStream printStream = new PrintStream(new TextAreaOutputStream(jTextArea1)); System.setOut(printStream); //SmithWaterman.main(argument); try { SmithWaterman.main(argument); } catch (IOException ex) { Logger.getLogger(MyApp.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(MyApp.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_checkActionPerformed private void clearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearActionPerformed jTextArea1.setText(""); queryField.setText(null); templateField.setText(null); // TODO add your handling code here: }//GEN-LAST:event_clearActionPerformed /* public void settext(String b) { /*String buffer=new String(); buffer=Integer.toString(b); //System.out.println(b); jTextArea1.append("b"); }*/ /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { MyApp m=new MyApp("Input Files"); m.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton check; private javax.swing.JButton clear; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JButton qbrowse; private javax.swing.JTextField queryField; private javax.swing.JLabel queryLabel; private javax.swing.JButton tbrowse; private javax.swing.JTextField templateField; private javax.swing.JLabel templateLabel; // End of variables declaration//GEN-END:variables }
Python
UTF-8
203
3.984375
4
[]
no_license
print("Hello world") x=10 print(f"x vale : {x}") for i in range(0,10): #PROGRAMMA DI ESEMPIO if(i%2==0): print(f"{i} è pari") else: print(f"{i} è dispari")
Python
UTF-8
455
4.46875
4
[]
no_license
""" Escreva um programa que, dados dois números inteiros, mostre na tela o maior deles, assim como a diferença existente entre ambos. """ numero1 = int(input("Digite um número inteiro: ")) numero2 = int(input("Digite outro número inteiro: ")) if numero1 > numero2: print(f"Maior: {numero1}") print(f"Diferença entre ambos: {numero1 - numero2}") else: print(f"Maior: {numero2}") print(f"Diferença entre ambos: {numero2 - numero1}")
Java
UTF-8
499
2.078125
2
[ "MIT" ]
permissive
package net.omikron.jtl.visualizer.exceptions; public class JtlMinRequirementsException extends RuntimeException { private static final long serialVersionUID = 1L; public JtlMinRequirementsException() { super(); } public JtlMinRequirementsException(final String message) { super(message); } public JtlMinRequirementsException(final String message, final Throwable cause) { super(message, cause); } public JtlMinRequirementsException(final Throwable cause) { super(cause); } }
Markdown
UTF-8
5,065
2.765625
3
[]
no_license
--- _model: blog-post --- title: Transparencia, claridad y Big Data --- date: 2013-08-14 09:26:57 +0200 --- author: Mario Alberich --- categories: matematica,informatica --- tags: algoritmos,big-data --- body: <p>Un interesante ejemplo de los <a title="Data journalism: the important difference between transparency and clarity" href="http://www.bbc.co.uk/blogs/blogcollegeofjournalism/posts/Data-journalism-the-important-difference-between-transparency-and-clarity">riesgos por el exceso de datos disponibles</a> lo retrataba hace un par de semanas el blog del colegio de periodismo en su blog de la BBC. &nbsp;No comparto al completo la visión, pero sí los efectos primarios (sesgo) y secundarios (toma de decisiones errónea) debido a un problema <em>relativamente</em> nuevo: el exceso de datos.</p><!--more--> <p>Lo cierto es que el Big Data me tiene el corazón dividido. Leyendo un reciente <a title="Data" href="http://www.human-computer.net/blog/2013/06/data/">artículo de Yusef sobre Data</a> (que no sólo me ha valido la pena leer, sino que a su vez referencia artículos muy interesantes), comparto el hecho que el término es puro marqueting, y que el objetivo es vender más <em>hardware</em> para centros de proceso de datos; que los algoritmos no habrán mejorado tanto en los últimos a&ntilde;os. Y que si has llegado al Big Data porque pensaste que era algo totalmente nuevo, te equivocaste.</p> <p>Intento ce&ntilde;irme estrictamente al tema de la utilidad del Big Data. &nbsp;Dejo a un lado las <a title="The net delusion (Evgeny Morozov)" href="http://www.sopadebits.com/the-net-delusion-evgeny-morozov">consecuencias en la privacidad</a>, y otros debates que me parecen relevantes para esta temática. Me gustaría verlo desde el punto de vista más técnico.</p> <p>Porque claro, eso es el mercado. &nbsp;No veo yo ningún sector en el que eso de intentar vender, no suceda. &nbsp;Lo que ahora es&nbsp;Big Data, antes fue <em>data mining</em>, inteligencia artificial,... Y así podríamos ir tirando del hilo hasta llegar al momento en que la informática y las matemáticas (o directamente la estadística) cruzaron sus caminos (y eso fue bastante pronto). Eso, el uso del márqueting para vender más, desde los ojos de un técnico, es ignorable.</p> <p>Tambien, mientras imagino ese volumen de datos, pienso en la cantidad de ruido que habrá. Y aunque no es deseable, también es intrínseco al análisis. &nbsp;Antes de decidir la se&ntilde;al que queremos extraer de los datos, estaba el ruido. La se&ntilde;al no es más que una porción del ruido que responde a nuestras preguntas. &nbsp;Entonces, en ese ruido está el sonido que buscamos. El ruido, a pesar de todo, es deseable. Porque el ruido es contexto.</p> <p>Filtrar ese ruido tiene su intríngulis. Pero por ejemplo, ese filtrado puede ser iterativo. Incluso puede hacerse después de recopilar datos en bruto (con el permiso de las políticas de uso de las APIs). Tener una buena base de datos y que un técnico pueda responder con algunos c&agrave;lculos a las preguntas que le caen <em>al vuelo</em>, formuladas por un responsable de negocio: no veo yo que sea para tirarse de los pelos. Si sólo se dispone de los datos estrictamente necesarios para llevar a cabo un experimento, el resto de preguntas quedan fuera.</p> <p>Por eso, cuando pienso en la parte <em>Big</em> del término, no me sugiere el volumen de datos: más bien pienso en la cantidad de preguntas que pueden responder y que antes no podíamos preguntarle a los datos. Desde mi punto de vista el <em>Big Data</em> es el mar, o el acuario. Es el espacio en el que se desarrolla (o simula, o analiza) todo un ecosistema. No son solo los datos, sino también el contexto que podemos apreciar si podemos aprovechar esos datos. Es lo que permite trabajar con los datos <em>como si</em> estuviéramos en un <em>entorno real</em>.</p> <p>Por eso, es cierto que si un estudio está enfocado (y eso me parece correcto) hacia preguntas muy concretas, este volumen de datos es excesivo. Pero rechazar el Big Data porque tiene ruido, o porque &nbsp;el conjunto de datos no da valor en conjunto, pues no lo comparto. El mar está lleno de espacios vacíos. Y de peces. Es una cuestión de reenfoque.</p> <p>Sería como si el pescador no pescara más porque hoy no ha capturado nada. Ese pescador no se da cuenta que el propio hecho de no haber capturado nada hoy, le está dando información sobre su contexto de pesca, que le puede ayudar a tomar decisiones. Y que sin ese mar, no tendría esa posibilidad. Ese pescador está aprendiendo a pescar. Encontrará más <em>valor</em> buscando las corrientes de agua y los arrecifes. Esto le llevará tiempo. Pero si le gusta pescar, aprenderá.</p> <p>Me planteo una actitud diferente ante el Big Data. Cambio el proceso de análisis a fondo, por un enfoque más contemplativo. Cambio el contraste de hipótesis por un buen análisis exploratorio de los datos. Cambio las respuestas, por las historias que hay detrás.</p> <p>Pero quizá me equivoque. Es probable ;-).</p> ---
Markdown
UTF-8
5,964
2.53125
3
[]
no_license
# Microchip PolarFire SoC Linux Software Development Kit This repository builds a command line only RISC-V Linux image for the Microchip PolarFire SoC Linux Software Development Kits. It first will build the GNU cross-compilation toolchain for RISC-V, which will be installed in the `toolchain/` subdirectory. This toolchain is then used to build a Linux image consisting of the kernel, a Busybox based root file system and the necessary bootloaders for each development platform. Currently the following development platforms are supported: - [MPFS-DEV-KIT](doc/MPFS-DEV-KIT_user_guide.md) (HiFive Unleashed Expansion Board) - [LC-MPFS-DEV-KIT](doc/LC-MPFS-DEV-KIT_user_guide.md) The complete User Guides for each development platform, containing board and boot instructions, are available in the `doc/` subdirectory. ## Building Linux Using Buildroot This section describes the procedure to build the Linux boot image and loading it into an SD card using Buildroot. ### Supported Build Hosts This document assumes you are running on a modern Linux system. The process documented here was tested using Ubuntu 18.04 LTS & Ubuntu 16.04 LTS. It should also work with other Linux distributions if the equivalent prerequisite packages are installed. #### Prerequisite Packages Before starting, use the `apt` command to install prerequisite packages: ``` sudo apt install autoconf automake autotools-dev bc bison \ build-essential curl flex gawk gdisk git gperf libgmp-dev \ libmpc-dev libmpfr-dev libncurses-dev libssl-dev libtool \ patchutils python screen texinfo unzip zlib1g-dev libblkid-dev \ device-tree-compiler mtools ``` ### Checkout Code & Build ##### Supported Build Targets The `DEVKIT` option can be used to set the target board for which Linux is built, and if left blank it will default to `DEVKIT=mpfs`. The following table details the available targets: | `DEVKIT` | Board Name | | --- | --- | | `DEVKIT=mpfs` | MPFS-DEV-KIT, HiFive Unleashed Expansion Board | | `DEVKIT=lc-mpfs` | LC-MPFS-DEV-KIT | The following commands checkout SDK in a new directory: ``` git clone https://github.com/polarfire-soc/polarfire-soc-buildroot-sdk.git cd polarfire-soc-buildroot-sdk git checkout master ``` Before building for the first time, it is required to acquire the contents of the sub-components: ``` git submodule update --init --recursive ``` Then the Linux image can be built in the `work` sub-directory: ``` unset RISCV make all DEVKIT=lc-mpfs ``` Note: The first time the build is run it can take a long time, as it also builds the RISC-V cross compiler toolchain. The output file `work/bbl.bin` contains the bootloader (RISC-V pk/bbl), the Linux kernel, and the device tree blob. A GPT image is also created, with U-Boot as the first stage boot loader that can be copied to an SD card. The option `DEVKIT=<target>` selects the correct device tree for the target board. ### Preparing an SD Card Add an SD card to boot your system (16 GB or 32 GB). If the SD card is auto-mounted, first unmount it manually. The following steps will allow you to check and unmount the card if required: After inserting your SD card, use dmesg to check what your card's identifier is. ``` dmesg | egrep "sd|mmcblk" ``` The output should contain a line similar to one of the below lines: ``` [85089.431896] sd 6:0:0:2: [sdX] 31116288 512-byte logical blocks: (15.9 GB/14.8 GiB) [51273.539768] mmcblk0: mmc0:0001 EB1QT 29.8 GiB ``` `sdX` or `mmcblkX` is the drive identifier that should be used going forwards, where `X` should be replaced with the specific value from the previous command. For these examples the identifier `sdX` is used. #### WARNING: The drive with the identifier `sda` is the default location for your operating system. DO NOT pass this identifier to any of the commands listed here. Check that the size of the card matches the dmesg output before continuing. Next check if this card is mounted: ``` $ mount | grep sdX ``` If any entries are present, then run the following. If not then skip this command: ``` $ sudo umount /dev/sdX ``` The SD card should have a GUID Partition Table (GPT) rather than a Master Boot Record (MBR) without any partitions defined. ### Programming an Image for the First Time To automatically partition and format your SD card, in the top level of mpfs-linux-sdk, type: ``` $ sudo make DISK=/dev/sdX format-boot-loader ``` At this point, your system should be bootable using your new SD card. You can remove it from your PC and insert it into the SD card slot on the HiFive Unleashed board, and then power-on the DEV-KIT. ### Rebuilding the Linux Kernel To rebuild your kernel or to change the machine being targeted, type the following from the top level of polarfire-soc-buildroot-sdk: ``` $ make clean $ make DEVKIT=<devkit> ``` Copy this newly built image to the SD card using the same method as before: ``` $ sudo make DISK=/dev/sdX format-boot-loader ``` The source for the device tree for HiFive Unleashed Expansion board is in `conf/<DEVKIT>.dts`. The configuration options used for the Linux kernel are in `conf/<DEVKIT>linux_defconfig`. Currently, the Microsemi PolarFire Linux SDK for the HiFive Unleashed platform uses a modification to the RISC-V Bootloader startup code to pass in the device tree blob (see `riscv-pk/machine/mentry.S` for the modification.) ## Booting Linux on a simulator Currently spike spike and qemu do not work, due to how the device tree for the expansion board is loaded in bbl. ## Additional Reading [Buildroot User Manual](https://buildroot.org/docs.html) [PolarFire SoC Yocto BSP](https://github.com/polarfire-soc/meta-polarfire-soc-yocto-bsp) [MPFS-DEV-KIT User Guide](doc/MPFS-DEV-KIT_user_guide.md) [LC-MPFS-DEV-KIT User Guide](doc/LC-MPFS-DEV-KIT_user_guide.md) [Kernel Documentation for v4.15](https://www.kernel.org/doc/html/v4.15/)
Java
UTF-8
1,468
2.015625
2
[]
no_license
package com.gdlife.candypie.serivce.user; import com.gdlife.candypie.base.HttpObserver; import com.gdlife.candypie.common.MKey; import com.gdlife.candypie.http.HttpClient; import com.gdlife.candypie.utils.SignUtils; import com.heboot.base.BaseBeanEntity; import com.heboot.bean.user.UserVisitListBean; import java.util.Map; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class FollowService { /** * 点击守护 * * @param uid * @param observer */ public void doFollowLove(String uid, HttpObserver<BaseBeanEntity> observer) { Map params = SignUtils.getNormalParams(); params.put(MKey.TO_UID, uid); String sign = SignUtils.doSign(params); params.put(MKey.SIGN, sign); HttpClient.Builder.getGuodongServer().follow_love(params).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(observer); } public void followList(String uid, int sp, HttpObserver<UserVisitListBean> observer) { Map params = SignUtils.getNormalParams(); params.put(MKey.UID, uid); params.put(MKey.PAGESIZE, 10); params.put(MKey.SP, sp); String sign = SignUtils.doSign(params); params.put(MKey.SIGN, sign); HttpClient.Builder.getGuodongServer().follow_love_list(params).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(observer); } }
C++
UTF-8
725
2.765625
3
[]
no_license
#include "Cannonball.h" Cannonball::Cannonball() { origin = sf::Vector2f(300, 300); setPosition(sf::Vector2f(300, 300)); shoot = 0; press = 0; gravity = 500.f; } Cannonball::~Cannonball() { } void Cannonball::handleInput(float dt) { if (input->isMouseLDown()) { mousepoint = sf::Vector2f(input->getMouseX(), input->getMouseY()); shoot = 1; } if (shoot == 1 && input->isMouseLDown() == 0) { magnit = mousepoint - origin; magnit *= -1.f; velocity = (Vector::normalise(magnit)); velocity *= 500.f; shoot = 0; press = 1; } } void Cannonball::update(float dt) { if (press == 1) { setVelocity(getVelocity().x, getVelocity().y + gravity * dt); setPosition(getPosition() + (velocity * dt)); } }
Markdown
UTF-8
731
2.75
3
[]
permissive
* All pull-request which are merged successfully inside an repository having topic hacktoberfest will be counted in hacktoberfest. * If the repository which you are contributing doesn't have hacktoberfest topic then you can ask the mainter to add "hacktoberfest-accepted" label to your pull request, then also it will counted in hacktoberfest. * I will like to tell all contributers that this repository contains hacktoberfest topic so all your pull request made inside this repository will be counted in hacktoberfest without adding "hactoberfest-accepted" label to your pull request. But still i will add it if you ask. * And for your FAQs regarding hacktoberfest you can refer [here](https://hacktoberfest.digitalocean.com/faq)
Python
UTF-8
11,650
3.78125
4
[]
no_license
""" A great game in which the player has to collect pink hearts! However, the player will lose points if a black heart is collected! If the score goes negative, the player loses. See which of your friends can get the highest score!!! Controls: anything that the player's computer thinks is arrow key input @author: jovanduy """ import pygame import random import time class DrawableSurface(): """ A class that wraps a pygame.Surface and a pygame.Rect """ def __init__(self, surface, rect): """ Initialize the drawable surface """ self.surface = surface self.rect = rect def get_surface(self): """ Get the surface """ return self.surface def get_rect(self): """ Get the rect """ return self.rect class GameModel(): """ Represents the state of the Game """ def __init__(self, width, height): """ Initialize the Game model """ self.width = width self.height = height self.background = Background(height) # put character in middle of screen self.character = Character(width/2 - 15, height/2 - 20) self.score_text = ScoreText(self.character) self.hearts = [] for i in range(20): # more pink hearts than black if random.randint(0, 30) < 17: heart = Heart() self.hearts.append(heart) else: black_heart = BlackHeart() self.hearts.append(black_heart) def is_hit(self, heart, character): if (int(heart.x) in range(int(character.x), int(character.x+14))) and (int(heart.y) in range(int(character.y), int(character.y+48))): character.score += heart.points return True return False def update(self, delta_t, width, height): """ Updates the model and its constituent parts """ self.character.update(delta_t, width, height) self.score_text.update() for heart in self.hearts: if self.is_hit(heart, self.character): heart.reset() heart.update(delta_t) class Background(): def __init__(self, screen_height): """ Initializes the border """ self.image = pygame.image.load('images/full_heart.png') self.tiles = [] for i in range(100): self.tiles.append(DrawableSurface(self.image, pygame.Rect(i*32, screen_height-32, 32, 32))) self.tiles.append(DrawableSurface(self.image, pygame.Rect(i*32, 0, 32, 32))) self.tiles.append(DrawableSurface(self.image, pygame.Rect(0, i*32, 32, 32))) self.tiles.append(DrawableSurface(self.image, pygame.Rect(608, i*32, 32, 32))) def draw(self, screen): """ Draws the border """ for drawable_surface in self.tiles: screen.blit(drawable_surface.get_surface(), drawable_surface.get_rect()) class Character(): """ Represents the player in the game """ def __init__(self,x,y): """ Initialize the character at the specified position x, y """ self.x = x self.y = y # velocities self.vx = 0 self.vy = 0 self.image = pygame.image.load('images/stand.png') self.image.set_colorkey((255,255,255)) self.score = 0 self.score_max = self.score self.is_dead = False def draw(self, screen): """ get the drawables that make up the character """ screen.blit(self.image, self.image.get_rect().move(self.x, self.y)) def update(self, delta_t, width, height): """ Update the character over time. The character is not allowed past the border of hearts """ if self.score > self.score_max: self.score_max = self.score if self.x + self.vx*delta_t <= 30 or self.x + self.vx*delta_t >= width-80: pass else: self.x += self.vx*delta_t if self.y + self.vy*delta_t <= 30 or self.y + self.vy*delta_t >= height-110: pass else: self.y += self.vy*delta_t def score(self, is_pink): """ Updates the score of the Character based on the color of the heart """ if is_pink: self.score += 1 else: self.score -= 1 def move_down(self): """ increases y velocity so the character can move down """ self.vy += 150 def move_up(self): """ decreases y velocity so the character can move up """ self.vy -= 150 def move_right(self): """ increases x velocity so the character can move right """ self.vx += 150 def move_left(self): """ decreases x velocity so the character can move left """ self.vx -= 150 def move_nowhere_horizontal(self): self.vx = 0 def move_nowhere_vertical(self): self.vy = 0 class Heart(object): """ Represents the hearts to be collected in the game """ def __init__(self): self.points = 1 # randomly choose from which side of the screen the heart starts self.side = random.randint(1,4) if self.side == 1 or self.side == 3: self.x = random.randint(50,600) self.vx = 0 if self.side == 1: self.y = 50 self.vy = 150 else: self.y = 480 - 10 self.vy = -150 else: self.y = random.randint(50,400) self.vy = 0 if self.side == 2: self.x = 50 self.vx = 150 else: self.x = 400 self.vx = -150 self.image = pygame.image.load('images/full_heart.png') self.image.set_colorkey((255,255,255)) self.been_hit = False def draw(self, screen): screen.blit(self.image, self.image.get_rect().move(self.x, self.y)) def reach_end_screen(self): if self.side == 1: if self.y >= 470: return True elif self.side == 2: if self.x >= 630: return True elif self.side == 3: if self.y <= 10: return True elif self.side == 4: if self.x <= 0: return True return False def reset(self): self.side = random.randint(1,4) if self.side == 1 or self.side == 3: self.x = random.randint(50,600) self.vx = 0 if self.side == 1: self.y = 50 self.vy = 150 else: self.y = 480 - 10 self.vy = -150 else: self.y = random.randint(50,400) self.vy = 0 if self.side == 2: self.x = 50 self.vx = 150 else: self.x = 400 self.vx = -150 def update(self, delta_t): if self.reach_end_screen(): self.reset() self.x += self.vx*delta_t self.y += self.vy*delta_t class BlackHeart(Heart): def __init__(self): self.points = -1 # randomly choose from which side of the screen the heart starts self.side = random.randint(1,4) if self.side == 1 or self.side == 3: self.x = random.randint(50,600) self.vx = 0 if self.side == 1: self.y = 50 self.vy = 150 else: self.y = 480 - 10 self.vy = -150 else: self.y = random.randint(50,400) self.vy = 0 if self.side == 1: self.x = 50 self.vx = 150 else: self.x = 400 self.vx = -150 self.image = pygame.image.load('images/black_heart.png') self.image.set_colorkey((255,255,255)) self.been_hit = False class ScoreText(object): def __init__(self, character): pygame.font.init() self.font = pygame.font.Font('freesansbold.ttf', 80) self.character = character self.score_text = self.font.render(str(self.character.score), 1, (255, 255, 255)) def update(self): self.score_text = self.font.render(str(self.character.score), 1, (255, 255, 255)) def draw(self, screen): screen.blit(self.score_text, (40,40)) class GameView(object): def __init__(self, model, width, height): """ Initialize the view of the Game """ pygame.init() # to retrieve width and height use screen.get_size() self.screen = pygame.display.set_mode((width, height)) # this is used for figuring out where to draw stuff self.model = model def draw(self): """ draw the game window """ # light blue background color self.screen.fill((68,218,255)) self.model.background.draw(self.screen) self.model.score_text.draw(self.screen) self.model.character.draw(self.screen) for heart in self.model.hearts: heart.draw(self.screen) pygame.display.update() class Game(object): """ The main Game class """ def __init__(self): """ Initialize the Game game. Use Game.run() to start the game """ self.model = GameModel(640, 480) self.view = GameView(self.model, 640, 480) self.controller = Controller(self.model) def run(self): """ the main runloop... loop until character's score is negative """ last_update = time.time() while True: if self.model.character.score < 0: print 'Your highest score was: ' + str(self.model.character.score_max) break self.view.draw() self.controller.process_events() delta_t = time.time() - last_update self.model.update(delta_t, 640, 480) last_update = time.time() class Controller(): def __init__(self, model): """ initialize the (what the computer thinks is) keyboard input controller """ self.model = model self.up_pressed = False self.down_pressed = False self.left_pressed = False self.right_pressed = False def process_events(self): """ process an arrow key press """ pygame.event.pump() if not(pygame.key.get_pressed()[pygame.K_UP]): self.up_pressed = False elif not(self.up_pressed): self.up_pressed = True self.model.character.move_up() if not(pygame.key.get_pressed()[pygame.K_DOWN]): self.down_pressed = False elif not(self.down_pressed): self.down_pressed = True self.model.character.move_down() if not(pygame.key.get_pressed()[pygame.K_LEFT]): self.left_pressed = False elif not(self.left_pressed): self.left_pressed = True self.model.character.move_left() if not(pygame.key.get_pressed()[pygame.K_RIGHT]): self.right_pressed = False elif not(self.right_pressed): self.right_pressed = True self.model.character.move_right() # if both up and down or left and right are pressed, do not move # vertically or horizontally, respectively if not(self.up_pressed) and not(self.down_pressed): self.model.character.move_nowhere_vertical() if not(self.left_pressed) and not(self.right_pressed): self.model.character.move_nowhere_horizontal() if __name__ == '__main__': game = Game() game.run()
Python
UTF-8
158
3.296875
3
[]
no_license
#!/usr/bin/python3 for letter in range(122, 96, -1): print("{:c}".format(letter if (letter % 2 == 0) else (letter - 32)), end="")
PHP
UTF-8
219
4.40625
4
[]
no_license
<?php function plus(int $value) { $num = 0; $num += $value; print("<br>計算結果: ".$num); } print("plusを3で呼出"); plus(3); print("<br>plusを5で呼出"); plus(5); print("<br>plusを7で呼出"); plus(7);
Ruby
UTF-8
5,620
3.09375
3
[]
no_license
#!/usr/bin/ruby19 # # Needleman, Saul B.; and Wunsch, Christian D. (1970). "A general method # applicable to the search for similarities in the amino acid sequence of two # proteins". Journal of Molecular Biology 48 (3): 443–53. # doi:10.1016/0022-2836(70)90057-4. PMID 5420325. # # Necessary libraries require 'narray' # @class class NeedlemanWunsch # {{{ # @brief Needleman Wunsch Algorithm implementation in Ruby class NeedlemanWunsch # @fn def initialize # {{{ # @brief Constructor of NeedlemanWunsch class # # @param [Logger] logger Instantiated Logger class # @param [Integer] gap Gap penalty of when introducing new gaps into the sequences (constant) def initialize logger = nil, genetic_sequence = false @logger = logger @gap, @similarity = ( genetic_sequence ) ? ( init_genetic ) : ( init_generic ) end # @fn def init_genetic # {{{ # @brief Initializes class with similarity matrix and gap penalty suitable for genetic sequences (Bio-Informatics) # # FIXME: These values should be mapped out to a config file etc. def init_genetic puts "-> Genetic" gap = -5 # similarity matrix when using genetic sequences # # A G C T # A 10 -1 -3 -4 # G -1 7 -5 -3 # C -3 -5 9 0 # T -4 -3 0 8 similarity = { 'AA' => 10, 'AG' => -1, 'AC' => -3, 'AT' => -4, 'GA' => -1, 'GG' => 7, 'GC' => -5, 'GT' => -3, 'CA' => -3, 'CG' => -5, 'CC' => 9, 'CT' => 0, 'TA' => -4, 'TG' => -3, 'TC' => 0, 'TT' => 8 } return [ gap, similarity ] end # of def init_genetic # }}} # @fn def init_generic # {{{ # @brief Initializes class with similarity matrix and gap penalty suitable for generic sequences (found outside of Bio-Informatics) # # FIXME: These values should be mapped out to a config file etc. def init_generic puts "Generic" gap = -2 similarity = {} # All permutations e.g. 01, 10 etc. are penalized ["0", "1", "2", "3", "4", "5", "6", "7"].permutation(2) do |x| similarity[ x.join( "" ).to_s ] = -1 end # Matches "00" and same letter matches .. similar are awarded ["0", "1", "2", "3", "4", "5", "6", "7"].each do |x| similarity[ ( x + x ).to_s ] = 1 end return [ gap, similarity ] end # of def init_genetic # }}} # Inspired by: http://snippets.dzone.com/posts/show/2199 -> credits: to ruby bioinformatics alignment by "raaum" on "Thu Jun 15 15:18:08 -0400 2006" def needle sequence, reference gap = @gap s = @similarity puts "Gap: #{gap.to_s}" puts "Similarity Matrix: " p s puts "" rows = reference.length + 1 cols = sequence.length + 1 a = NArray.int( rows, cols ) for i in 0...(rows) do a[i,0] = 0 end for j in 0...(cols) do a[0,j] = 0 end for i in 1...(rows) for j in 1...(cols) #sec = s[ (reference[i-1].chr + sequence[j-1].chr) ] #sec = 0 if( sec.nil? ) # choice1 = a[i-1, j-1] + sec choice1 = a[i-1, j-1] + s[ (reference[i-1].chr + sequence[j-1].chr).upcase ] choice2 = a[i-1, j] + gap choice3 = a[i, j-1] + gap a[i,j] = [choice1, choice2, choice3].max end end ref = '' seq = '' i = reference.length j = sequence.length while (i > 0 and j > 0) score = a[i,j] score_diag = a[i-1, j-1] score_up = a[i, j-1] score_left = a[i-1, j] sec = s[ (reference[i-1].chr + sequence[j-1].chr) ] sec = 0 if( sec.nil? ) if (score == score_diag + sec ) ref = reference[i-1].chr + ref seq = sequence[j-1].chr + seq i -= 1 j -= 1 elsif (score == score_left + gap) ref = reference[i-1].chr + ref seq = '-' + seq i -= 1 elsif (score == score_up + gap) ref = '-' + ref seq = sequence[j-1].chr + seq j -= 1 end end while (i > 0) ref = reference[i-1].chr + ref seq = '-' + seq i -= 1 end while (j > 0) ref = '-' + ref seq = sequence[j-1].chr + seq j -= 1 end [seq, ref] end end # of class NeedlemanWunsch # }}} if __FILE__ == $0 nw = NeedlemanWunsch.new( nil, false ) # sequence = "AGACTAGTTAC" # reference = "CGAGACGT" # result of "AGACTAGTTAC" and "CGAGACGT" should be "CGA---GACGT" according to wikipedia, but we get "CGAGAC--G-T--" # sequence = "001110111" # reference = "0012210122211" sequence = File.open( "../../data/cycle10_directions.gpdata", "r" ).readlines.collect!{ |l| l.strip }.join( "" ) reference = File.open( "../../data/cycle2_directions.gpdata", "r" ).readlines.collect!{ |l| l.strip }.join( "" ) s, r = nw.needle(sequence, reference) ns = [] 0.upto( s.length - 1 ).each do |n| ns << n.to_s end #ss = ns.zip( s.split( "" ) ) ss = s #ss.collect!{ |array| array.join( " " ) } #ss = ss.join( "\n" ) #rs = ns.zip( r.split( "" ) ) rs = r #rs.collect!{ |array| array.join( " " ) } #rs = rs.join( "\n" ) #puts ss #p ss #p rs final_ss = [] 0.upto( rs.length - 1 ) do |n| final_ss << [ n.to_s + " " + rs[n].to_s ] end puts final_ss.join( "\n" ) end
Java
UTF-8
571
3.03125
3
[]
no_license
package secondTry; public class j_58_ReverseString { class Solution{ public String reverseStr(String str){ if (str == null ||str.length() == 0){ return str; } String[] s = str.split(" "); StringBuilder sb = new StringBuilder(); for (int i = s.length - 1 ; i >= 0 ; i--) { if (!s[i].equals(" ")){ sb.append(s[i]); sb.append(" "); } } return sb.toString().trim(); } } }
Java
UTF-8
15,396
1.765625
2
[]
no_license
package com.trascender.contabilidad.gui.abmAsientoContable.abm; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.JLabel; import javax.swing.JTable; import com.trascender.contabilidad.gui.abmAsientoContable.AsientoContableABMModel; import com.trascender.contabilidad.gui.abmLibroDiario.AdminLibroDiario; import com.trascender.contabilidad.gui.abmLineaAsientoContable.LineaAsientoContableTableModel; import com.trascender.contabilidad.gui.main.ContabilidadGUI; import com.trascender.contabilidad.recurso.persistent.AsientoContable; import com.trascender.contabilidad.recurso.persistent.FolioLibroDiario; import com.trascender.contabilidad.recurso.persistent.LibroDiario; import com.trascender.contabilidad.recurso.persistent.LineaAsientoContable; import com.trascender.contabilidad.recurso.persistent.SubdiarioCaja; import com.trascender.contabilidad.system.interfaces.SystemAdministracionConsultaContable; import com.trascender.gui.framework.abmStandard.ABMController; import com.trascender.gui.framework.exception.GuiException; import com.trascender.gui.framework.main.AppManager; import com.trascender.gui.framework.model.TDefaultComboBoxModel; import com.trascender.gui.framework.recursos.Messages; import com.trascender.gui.framework.util.Conversor; import com.trascender.gui.framework.util.Validador; public abstract class ABMAsientoContable extends ABMController<AsientoContable> { public abstract ABMAsientoContableView getView(); public abstract AsientoContableABMModel getAbmModel(); public abstract LineaAsientoContableTableModel getTableModel(); @Override protected void init() { super.init(); this.setModels(); this.setListeners(); this.setCommonProperties(); this.getView().getPnlTabla().getTblDatos().setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(0).setPreferredWidth(310); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(1).setPreferredWidth(140); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(2).setPreferredWidth(140); this.getView().getCbFolioLibroDiario().setEnabled(false); } private void setModels() { this.getView().setAbmModel(this.getAbmModel()); this.getView().getPnlTabla().getTblDatos().setModel(this.getTableModel()); this.getView().getCbTipoSubdiarioCaja().setModel(new TDefaultComboBoxModel(SubdiarioCaja.Tipo.values())); } private void setListeners() { this.getView().getPnlBotonesSeleccionLibroDiario().getBtnSeleccionar().addActionListener(new BtnSeleccionarLibroDiarioListener(this)); this.getView().getPnlBotonesSeleccionLibroDiario().getBtnLimpiar().addActionListener(new BtnLimpiarLibroDiarioListener(this)); this.getView().getBtnGenerarAsientoContable().addActionListener(new BtnGenerarAsientoContableListener(this)); this.getView().getBtnCargarAsientoContable().addActionListener(new BtnCargarAsientoContableListener(this)); } private void setCommonProperties() { this.getView().getPnlBtnTabla().getBtnEliminar().setVisible(false); this.getView().getPnlBtnTabla().getBtnModificar().setVisible(false); this.getView().getPnlBtnTabla().getBtnQuitarTodos().setVisible(false); this.getView().getPnlBtnTabla().getBtnAgregar().setText(Messages.getString("Application.btnQuitar")); this.getView().getPnlBtnTabla().getBtnAgregar().setMnemonic(Messages.getString("Application.btnQuitarMnemonic").charAt(0)); } public boolean validarDatosGenerarAsientoContable() { boolean validacionOK = true; List<Object> attNulos = new ArrayList<Object>(); List<JLabel> lblNulos = new ArrayList<JLabel>(); attNulos.add(this.getView().getFtfFecha().getText()); lblNulos.add(this.getView().getLblFecha()); attNulos.add(this.getView().getCbTipoSubdiarioCaja().getSelectedItem()); lblNulos.add(this.getView().getLblTipoSubdiarioCaja()); List<String> listaErrores = new ArrayList<String>(); try { listaErrores.addAll(Validador.validarNulos(attNulos, lblNulos)); listaErrores.addAll(Validador.validarFechaNoMayorALaActual(this.getView().getFtfFecha().getText(), this.getView().getLblFecha())); } catch (GuiException ex) { ex.printStackTrace(); AppManager.getInstance().showErrorMsg(this.getView(), ex.getMessage()); } if (!listaErrores.isEmpty()) { validacionOK = false; this.mostrarErroresValidacion(listaErrores); } return validacionOK; } private boolean validarDatosAgregarAsientoContable() { boolean validacionOK = true; List<Object> attNulos = new ArrayList<Object>(); List<JLabel> lblNulos = new ArrayList<JLabel>(); attNulos.add(this.getView().getFtfFecha().getText()); lblNulos.add(this.getView().getLblFecha()); List<String> listaErrores = new ArrayList<String>(); try { listaErrores.addAll(Validador.validarNulos(attNulos, lblNulos)); listaErrores.addAll(Validador.validarFechaNoMayorALaActual(this.getView().getFtfFecha().getText(), this.getView().getLblFecha())); } catch (GuiException ex) { ex.printStackTrace(); AppManager.getInstance().showErrorMsg(this.getView(), ex.getMessage()); } if (!listaErrores.isEmpty()) { validacionOK = false; this.mostrarErroresValidacion(listaErrores); } return validacionOK; } @Override public boolean validarDatos() { boolean validacionOK = true; List<Object> attNulos = new ArrayList<Object>(); List<JLabel> lblNulos = new ArrayList<JLabel>(); attNulos.add(this.getView().getTfNumeroAsiento().getText()); lblNulos.add(this.getView().getLblNumeroAsiento()); attNulos.add(this.getView().getTfLibroDiario().getText()); lblNulos.add(this.getView().getLblLibroDiario()); attNulos.add(this.getView().getCbFolioLibroDiario().getSelectedItem()); lblNulos.add(this.getView().getLblFolioLibroDiario()); attNulos.add(this.getView().getFtfFecha().getText()); lblNulos.add(this.getView().getLblFecha()); List<String> listaErrores = new ArrayList<String>(); try { listaErrores.addAll(Validador.validarNulos(attNulos, lblNulos)); } catch (GuiException ex) { ex.printStackTrace(); AppManager.getInstance().showErrorMsg(this.getView(), ex.getMessage()); } if (!listaErrores.isEmpty()) { validacionOK = false; this.mostrarErroresValidacion(listaErrores); } return validacionOK; } @Override protected void actualizarABMModel() { this.getAbmModel().setNumeroAsiento(Conversor.getInteger(this.getView().getTfNumeroAsiento().getText())); Object locFolio = this.getView().getCbFolioLibroDiario().getSelectedItem(); if (locFolio != null) this.getAbmModel().setFolioLibroDiario((FolioLibroDiario)locFolio); else this.getAbmModel().setFolioLibroDiario(null); this.getAbmModel().setObservaciones(Conversor.getNullSiVacio(this.getView().getTaObservaciones().getText())); this.getAbmModel().setFecha(Conversor.getDate(this.getView().getFtfFecha().getText())); Object locTipoSubdiario = this.getView().getCbTipoSubdiarioCaja().getSelectedItem(); if (locTipoSubdiario != null) this.getAbmModel().setTipoSubdiarioCaja((SubdiarioCaja.Tipo)locTipoSubdiario); else this.getAbmModel().setTipoSubdiarioCaja(null); } @Override public void actualizarView() { this.getView().getTfNumeroAsiento().setText(Conversor.getVacioSiNull(this.getAbmModel().getNumeroAsiento())); this.getView().getTfLibroDiario().setText(Conversor.getVacioSiNull(this.getAbmModel().getLibroDiario())); this.getView().getCbFolioLibroDiario().setSelectedItem(this.getAbmModel().getFolioLibroDiario()); this.getView().getTaObservaciones().setText(Conversor.getVacioSiNull(this.getAbmModel().getObservaciones())); this.getView().getFtfFecha().setValue(Conversor.getString(this.getAbmModel().getFecha())); this.getView().getCbTipoSubdiarioCaja().setSelectedItem(this.getAbmModel().getTipoSubdiarioCaja()); this.getView().getPnlTabla().getTblDatos().setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(0).setPreferredWidth(315); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(1).setPreferredWidth(140); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(2).setPreferredWidth(140); } @SuppressWarnings("unchecked") void seleccionarLibroDiario() throws Exception { AdminLibroDiario adminLibroDiario = new AdminLibroDiario(this.getView()); LibroDiario locLibroDiario = adminLibroDiario.openSelect(); if (locLibroDiario != null) { this.getAbmModel().setLibroDiario(locLibroDiario); SystemAdministracionConsultaContable locSystem = ContabilidadGUI.getInstance().getAdminSystemsContabilidad().getSystemAdministracionConsultaContable(); List<FolioLibroDiario> locListaFolios = locSystem.findListaFolioLibroDiario(null, locLibroDiario); Collections.sort(locListaFolios, new Comparator<FolioLibroDiario>() { public int compare(FolioLibroDiario o1, FolioLibroDiario o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); this.getView().getCbFolioLibroDiario().setModel(new TDefaultComboBoxModel(locListaFolios.toArray())); this.getView().getCbFolioLibroDiario().setEnabled(true); this.actualizarABMModel(); this.actualizarView(); } } public void calcularResultados(){ this.getView().getPnlResultados().getLblTotalDebe().setText(this.TotalAsientoContableDebe()); this.getView().getPnlResultados().getLblTotalHaber().setText(this.TotalAsientoContableHaber()); } void limpiarLibroDiario() throws Exception { this.getAbmModel().setLibroDiario(null); this.getAbmModel().setFolioLibroDiario(null); this.getView().getCbFolioLibroDiario().setSelectedItem(null); this.getView().getCbFolioLibroDiario().setEnabled(false); this.actualizarABMModel(); this.actualizarView(); } void generarAsientoContable() throws Exception { System.out.println("------------------------------> " + this.getView().getCbTipoSubdiarioCaja().getSelectedItem()); if(this.getView().getCbTipoSubdiarioCaja().getSelectedItem().equals(SubdiarioCaja.Tipo.PRESUPUESTARIO)){ throw new Exception("Para generar el asiento debe seleccionar un tipo diferente a Presupuestario"); } this.getTableModel().clearTable(); if (this.validarDatosGenerarAsientoContable()) { this.actualizarABMModel(); if (this.getAbmModel().getTipoSubdiarioCaja() != null) { if (this.getAbmModel().getTipoSubdiarioCaja().equals(SubdiarioCaja.Tipo.INGRESO)) { this.getView().getPnlAyudaDevengamiento().setVisible(true); }else { this.getView().getPnlAyudaDevengamiento().setVisible(false); } } this.getAbmModel().generarAsientoContable(); this.getTableModel().addRows(this.getAbmModel().getObjetoABM().getLineasAsientoContable()); //this.actualizarView(); this.getView().getPnlTabla().getTblDatos().setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(0).setPreferredWidth(315); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(1).setPreferredWidth(140); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(2).setPreferredWidth(140); this.calcularResultados(); } } /** * Este método abre la ventana de cargar asiento contable. * @throws Exception */ void cargarAsientoContable() throws Exception { if (this.validarDatosAgregarAsientoContable()) { this.actualizarABMModel(); CargarAsientoContable cargarAsientoContable = new CargarAsientoContable(this.getView(), this.getAbmModel()); cargarAsientoContable.open(); if (cargarAsientoContable.isOperacionRealizada()) { this.getTableModel().clearTable(); this.getTableModel().addRows(this.getAbmModel().getObjetoABM().getLineasAsientoContable()); //this.actualizarView(); } this.getView().getPnlTabla().getTblDatos().setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(0).setPreferredWidth(315); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(1).setPreferredWidth(140); this.getView().getPnlTabla().getTblDatos().getColumnModel().getColumn(2).setPreferredWidth(140); this.calcularResultados(); } } private String TotalAsientoContableDebe(){ Double locTotal = new Double(0); for(LineaAsientoContable cadaLineaAsientoContable: this.getAbmModel().getLineaAsientoContable()){ if(cadaLineaAsientoContable.getImporteDebe() != null){ locTotal+=cadaLineaAsientoContable.getImporteDebe(); } } NumberFormat dispFormat = NumberFormat.getNumberInstance(); dispFormat.setMaximumFractionDigits(2); dispFormat.setMinimumFractionDigits(2); dispFormat.setGroupingUsed(true); return dispFormat.format(locTotal); } private String TotalAsientoContableHaber(){ Double locTotal = new Double(0); for(LineaAsientoContable cadaLineaAsientoContable: this.getAbmModel().getLineaAsientoContable()){ if(cadaLineaAsientoContable.getImporteHaber() != null){ locTotal+=cadaLineaAsientoContable.getImporteHaber(); } } NumberFormat dispFormat = NumberFormat.getNumberInstance(); dispFormat.setMaximumFractionDigits(2); dispFormat.setMinimumFractionDigits(2); dispFormat.setGroupingUsed(true); return dispFormat.format(locTotal); } } /** * * @author marina * */ class BtnSeleccionarLibroDiarioListener implements ActionListener { private ABMAsientoContable controller; public BtnSeleccionarLibroDiarioListener(ABMAsientoContable controller) { this.controller = controller; } public void actionPerformed(ActionEvent e) { try { this.controller.seleccionarLibroDiario(); } catch (Exception ex) { ex.printStackTrace(); AppManager.getInstance().showErrorMsg(this.controller.getView(), ex.getMessage()); } } } class BtnLimpiarLibroDiarioListener implements ActionListener { private ABMAsientoContable controller; public BtnLimpiarLibroDiarioListener(ABMAsientoContable controller) { this.controller = controller; } public void actionPerformed(ActionEvent e) { try { this.controller.limpiarLibroDiario(); } catch (Exception ex) { ex.printStackTrace(); AppManager.getInstance().showErrorMsg(this.controller.getView(), ex.getMessage()); } } } class BtnGenerarAsientoContableListener implements ActionListener { private ABMAsientoContable controller; public BtnGenerarAsientoContableListener(ABMAsientoContable controller) { this.controller = controller; } public void actionPerformed(ActionEvent e) { try { this.controller.generarAsientoContable(); } catch (Exception ex) { ex.printStackTrace(); AppManager.getInstance().showErrorMsg(this.controller.getView(), ex.getMessage()); } } } class BtnCargarAsientoContableListener implements ActionListener { private ABMAsientoContable controller; public BtnCargarAsientoContableListener(ABMAsientoContable controller) { this.controller = controller; } public void actionPerformed(ActionEvent e) { try { this.controller.cargarAsientoContable(); } catch (Exception ex) { ex.printStackTrace(); AppManager.getInstance().showErrorMsg(this.controller.getView(), ex.getMessage()); } } }
C++
UTF-8
3,854
2.578125
3
[]
no_license
#include <unordered_map> #include <algorithm> #define MAXK 500005 using namespace std; unordered_map<int, int> map; int pnts[MAXK<<1], tmp[MAXK<<1]; struct node { int l, r, lo, hi; bool lzylo, lzyhi; node() : l(0), r(0), lo(0), hi(0), lzylo(0), lzyhi(0) {} } node[MAXK<<3]; void build(int u, int l, int r) { node[u].l = l, node[u].r = r; if (l!=r) { int m = (l+r)>>1; build(u<<1, l, m); build(u<<1|1, m+1, r); } } inline void lopush(int u, int w) { if (node[u].lo <= node[w].lo) return; node[w].lo = node[u].lo; if (node[w].hi < node[w].lo) { node[w].hi = node[w].lo; if (node[w].l != node[w].r) node[w].lzyhi = true; } if (node[w].l != node[w].r) node[w].lzylo = true; } inline void hipush(int u, int w) { if (node[u].hi >= node[w].hi) return; node[w].hi = node[u].hi; if (node[w].lo > node[w].hi) { node[w].lo = node[w].hi; if (node[w].l != node[w].r) node[w].lzylo = true; } if (node[w].l != node[w].r) node[w].lzyhi = true; } inline void lzypush(int u) { if (node[u].lzylo) { lopush(u, u<<1); lopush(u, u<<1|1); } if (node[u].lzyhi) { hipush(u, u<<1); hipush(u, u<<1|1); } } // op is 1 for set low, 2 for set high void update(int u, int l, int r, int h, int op) { if (node[u].l > r || node[u].r < l) return; lzypush(u); if ( (op==1 && node[u].lo >= h) || (op==2 && node[u].hi <= h) ) return; if (l <= node[u].l && node[u].r <= r) { if (op==1) { node[u].lo = h; if (node[u].hi < node[u].lo) { node[u].hi = node[u].lo; if (node[u].l != node[u].r) node[u].lzyhi = true; } if (node[u].l != node[u].r) node[u].lzylo = true; } else { node[u].hi = h; if (node[u].lo > node[u].hi) { node[u].lo = node[u].hi; if (node[u].l != node[u].r) node[u].lzylo = true; } if (node[u].l != node[u].r) node[u].lzyhi = true; } } else { update(u<<1, l, r, h, op); update(u<<1|1, l, r, h, op); node[u].lo = min(node[u<<1|1].lo, node[u<<1].lo); node[u].hi = max(node[u<<1|1].hi, node[u<<1].hi); } } int query(int u, int x) { lzypush(u); if (node[u].l==node[u].r) return node[u].lo; int m = (node[u].l+node[u].r) >> 1; if (x <= m) return query(u<<1, x); else return query(u<<1|1, x); } void buildWall(int n, int k, int op[], int left[], int right[], int height[], int finalHeight[]) { for (int i = 0; i < k; ++i) tmp[i] = left[i], tmp[i+k] = right[i]+1; sort(tmp, tmp + 2 * k); int M = 1; pnts[1] = tmp[0]; map[pnts[1]] = 1; for (int i = 1; i < 2*k; ++i) { if (tmp[i] != tmp[i-1]) { pnts[++M] = tmp[i]; map[pnts[M]] = M; } } build(1, 1, M); for (int i = 0; i < k; ++i) update(1, map[left[i]], map[right[i]+1]-1, height[i], op[i]); for (int x = 0; x < pnts[1]; ++x) finalHeight[x] = 0; for (int i = 1; i <= M; ++i) { int h = query(1, i); for (int j = pnts[i]; j < pnts[i+1]; ++j) finalHeight[j] = h; } for (int x = pnts[M]; x < n; ++x) finalHeight[x] = 0; } // int main() { // freopen("data.txt", "r", stdin); // int N, K; // int left[100], right[100], height[100], op[100], finalHeight[100]; // scanf("%d%d", &N, &K); // for (int i = 0; i < K; ++i) scanf("%d%d%d%d", op+i, left+i, right+i, height+i); // buildWall(N, K, op, left, right, height, finalHeight); // printf("finalHeight:\n"); // for (int i = 0; i < N; ++i) { // printf("%d ", finalHeight[i]); // } // printf("\n"); // }
Python
UTF-8
388
2.640625
3
[]
no_license
import unittest from program import task1, task2 class TestMethods(unittest.TestCase): def test_task1(self): self.assertEqual(task1("test.txt"), 1) self.assertEqual(task1("input.txt"), 6611) def test_task2(self): self.assertEqual(task2("test.txt"), 10) self.assertEqual(task2("input.txt"), 6619) if __name__ == '__main__': unittest.main()
Markdown
ISO-8859-2
1,259
2.546875
3
[]
no_license
Authors: Tony Wang, Douglas Frling This is a database program. The database contains key and value pairs which are read from a database file. The database file is written as "key\nvalue\n". So one line where the key is read from and the next line is the key's value. A key and a value may only be 127 characters long. Necessary files: db.c dbmod.h dbmod.c or dbmod2.c or dbmod3.c Database file Different dbmod.c files are used for different database structures. dbmod.c is run initially without any changes. If you would like to use dbmod2.c or dbmod3.c open the Makefile and change dbmod.o on line 4 to your file of choice. Example if you would like to use dbmod2.c change dbmod.o to dbmod2.o. How to run the program: Write make in the buffer when are you are located in the folder with all the files to compile the program. Then write make run with the database file. Example, "make run database.db". Within the databse program you can run different options. Press 1 to query a value of a key. 2 to update a keys value. 3 to create a new entry. 4 to remove an entry and 5 to print out the database. Program extensions: Better ways to store the database. More options for the database. Achievments: A1, A2, D9, E10, G15, H20, I22, I23, K30, O42, R50, M37
Markdown
UTF-8
525
2.59375
3
[]
no_license
# Employee Managment System ## Description - Gives users the ability to view add and update employee, role and department directories using CLI in node ## Installations * NPM inquirer * NPM Express * NPM MySql ## steps * installed dependecies * created inquirer prompts * used switch and cases along with functions to navigate employees departments and roles ## Links * [Video](https://drive.google.com/file/d/16bVhvf2YhjvOkMaef55jN61Wy8vf1e9a/view) * [Github Repo](https://github.com/rrtrenchf/Employee_Managment)
JavaScript
UTF-8
2,552
3
3
[]
no_license
const dataURL = "https://api.myjson.com/bins/jcmhn"; //скрыть правила, формы иконки в начале загрузки страницы $('div#container').hide(); $('div#rules_text').hide(); $('div#var1_label').hide(); $('div#var2_label').hide(); $('div#var3_label').hide(); $('div#var4_label').hide(); $('div#var5_label').hide(); $('div#var6_label').hide(); //показать правила и исходный текст по кнопке Rules $("#rules").click (function() { $("div#rules_text").toggle(1000); }); //показать формы по кнопке TRYIT $("#tryit").click (function() { $("div#container").toggle(1000); }); // взять данные по dataUrl, вытащить их и передать в handleData function handleButton() { $.getJSON(dataURL, handleData); } // присвоить значение каждой формы переменной и проверить значения по кнопке Проверить function handleData (data) { let text=''; let var1=$('input[name=var1]')[0].value; if (var1 == 'Старик') { $('div#var1_label').show();} else { $('div#var1_label').hide(); } let var2=$('input[name=var2]')[0].value; if (var2 == 'Старуха') { $('div#var2_label').show(); } else { $('div#var2_label').hide(); } let var3=$('input[name=var3]')[0].value; if (var3 == 'курочка Ряба') { $('div#var3_label').show(); } else { $('div#var3_label').hide(); } let var4=$('input[name=var4]')[0].value; if (var4 == 'яичко') { $('div#var4_label').show(); } else { $('div#var4_label').hide(); } let var5=$('input[name=var5]')[0].value; if (var5 == 'Мышка') { $('div#var5_label').show();} else { $('div#var5_label').hide(); } let var6=$('input[name=var6]')[0].value; if (var6 == 'хвостиком') { $('div#var6_label').show();} else { $('div#var6_label').hide(); } let speach=$('input[name=speach]')[0].value; //перебираем и заменяем {var} на инпуты data['text'].forEach (function (item) { item=item.replace('{var1}', var1); item=item.replace('{var2}', var2); item=item.replace('{var3}', var3); item=item.replace('{var4}', var4); item=item.replace('{var5}', var5); item=item.replace('{var6}', var6); item=item.replace('{speach}', speach); text=text + item + '<BR>'; }); $('div#result').html(text); } //обработка кнопки button-fetch function init() { $("#button-fetch").click(handleButton); } $(document).ready(init);
Python
UTF-8
574
3.953125
4
[]
no_license
""" Good morning! Here's your coding interview problem for today. This problem was asked by Facebook. Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability. """ import random def randomize(stream): rand_elem = None for i in range(0, len(stream)): if i == 0: rand_elem = stream[i] elif random.randint(1, i+1) == 0: rand_elem = stream[i] return rand_elem _stream = [random.randint(0, 1000000) for x in range(1000000)] print(randomize(_stream))
C
UTF-8
2,544
3
3
[]
no_license
#include "yaush.h" char cmd_list[MAX_CUST_CMD][CUST_CMD_NAME_LEN] = {"cd", "exit", "jobs", "fg", "bg" }; int (*f[MAX_CUST_CMD])(char*, char**) = { yaush_cd, yaush_exit, yaush_jobs, yaush_fg, yaush_bg }; /* @cmd -- the command name, useless in this function, just to uniform the arguments of all custom functions * @arg -- the argumnets of the command, note that arg[0] is the command name * @return: 0 if successful */ int yaush_cd(char* cmd, char** arg) { int ret; if (arg[1] == NULL) // if no parameters, change the current dir to home { char buf[255]; sprintf(buf, "/home/%s", getenv("USER")); ret = chdir(buf); } else ret = chdir(arg[1]); if (ret < 0) perror("cd"); return 0; } int yaush_exit(char* cmd, char** arg) { exit(0); return 0; } //print the jobs list int yaush_jobs(char* cmd, char** arg) { struct list_head *plist; int i = 0; strcpy( process_status_str[0], "Running"); strcpy( process_status_str[1], "Stopped"); strcpy( process_status_str[2], "Done"); list_for_each(plist, jobs_list) { struct node_process *node = list_entry(plist, struct node_process, list); printf("[%d]\tpid:%d\t%s\n", i, node->pid, process_status_str[node->pstatus]); i++; } return 0; } // @return: the pid of the sprcific process int yaush_fg(char* cmd, char** arg) { int idx = 0; int pid = 0; if (arg[1] != NULL) { idx = atoi(arg[1]); } if (idx < -1) pid = -1; struct list_head *plist; int i = 0; list_for_each(plist, jobs_list) { struct node_process *node = list_entry(plist, struct node_process, list); pid = node->pid; if ( i >= idx) break; i++; } return pid; } int yaush_bg(char* cmd, char** arg) { int idx = 0; int pid = 0; if (arg[1] != NULL) { idx = atoi(arg[1]); } if (idx < -1) pid = -1; struct list_head *plist; int i = 0; list_for_each(plist, jobs_list) { struct node_process *node = list_entry(plist, struct node_process, list); pid = node->pid; if ( i >= idx) { if (node->pstatus != Stopped) pid = 0; break; } i++; } return pid; } /* execute_cust_cmd(): execute an custom command * @cmd -- the command name * @arg -- the argumnets of the command, noted that arg[0] is the command name * @return: 0 is successful, or -1 if not found, or > 0 represents the pid */ int execute_cust_cmd(char* cmd, char** arg) { int i; int flag = -1; for (i = 0; i < MAX_CUST_CMD; i++) { if (strlen(cmd_list[i]) > 0 && strcmp(cmd, cmd_list[i]) == 0) { flag = (*f[i])(cmd, arg); break; } } return flag; }
Python
UTF-8
172
3.53125
4
[]
no_license
N = int(input()) can = False for i in range(1,10): for j in range(1,10): if i * j == N: can = True if can: print("Yes") else: print("No")
C
UTF-8
4,935
3.203125
3
[]
no_license
#ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #ifndef MAX_SIZE #define MAX_SIZE (1024) #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <ctype.h> struct Cvor; typedef struct Cvor* Pozicija_cvor; struct Cvor { char* element; Pozicija_cvor Lijevi; Pozicija_cvor Desni; }; struct Stog; typedef struct Stog* Pozicija_stog; struct Stog { Pozicija_cvor element_cvor; Pozicija_stog Next; }; int Ispis(int, Pozicija_cvor); int Brisanje_stoga(Pozicija_stog); int Brisanje_stabla(Pozicija_cvor); int Stvori_cvor_stabla(Pozicija_cvor*); int Pop(Pozicija_stog S, Pozicija_cvor *element); int Push (Pozicija_stog, Pozicija_cvor); int Stvori_cvor_na_stogu (Pozicija_stog*); int Stvori_stablo(char*, Pozicija_stog, Pozicija_cvor*); int main() { char* dat = NULL; Pozicija_stog stack = NULL; Pozicija_cvor root = NULL; Stvori_cvor_na_stogu(&stack); dat = (char*)malloc(sizeof(char)*MAX_SIZE); if (dat == NULL) { printf("\nGreska prilikom otvaranja datoteke."); return -1; } memset(dat, '\0', MAX_SIZE); printf("\nUnesite ime datoteke za citanje: "); scanf(" %s", dat); if (strrchr(dat, '.') == NULL) strcat(dat, ".txt"); Stvori_stablo(dat, stack, &root); printf("\n\nPreorder ispis stabla proracuna:\t"); Ispis(1, root); printf("\n\nInorder ispis stabla proracuna:\t"); Ispis(2, root); printf("\n\nPostorder ispis stabla proracuna:\t"); Ispis(3, root); Brisanje_stoga(stack); Brisanje_stabla(root); return 0; } int Stvori_cvor_na_stogu(Pozicija_stog *S) { Pozicija_stog q = NULL; q = (Pozicija_stog)malloc(sizeof(struct Stog)); if (q == NULL) { printf("Greska prilikom stvaranja cvora na stogu."); return -1; } q->element_cvor = NULL; q->Next = NULL; *S = q; return 0; } int Push(Pozicija_stog S, Pozicija_cvor P) { Pozicija_stog q = NULL; q->element_cvor = P; q->Next = S->Next; S->Next = q; return 0; } int Pop(Pozicija_stog S, Pozicija_cvor *element) { Pozicija_stog temp = NULL; Pozicija_cvor q = NULL; if (S == NULL) { printf("\nGreska sa stogom."); return -1; } temp = S->Next; if (temp == NULL) { printf("\nGreska s elementima stoga."); return -1; } S->Next = temp->Next; q = temp->element_cvor; free(temp); *element = q; return 0; } int Stvori_cvor_stabla(Pozicija_cvor *P) { Pozicija_cvor q = NULL; q = (Pozicija_cvor)malloc(sizeof(struct Cvor)); if (q == NULL) { printf("\nGreska prilikom alokacije memorije za cvor."); return -1; } q->element = NULL; q->Lijevi = NULL; q->Desni = NULL; *P = q; return 0; } int Brisanje_stabla(Pozicija_cvor P) { if (P == NULL) return 0; Brisanje_stabla(P->Lijevi); Brisanje_stabla(P->Desni); free(P); return 0; } int Brisanje_stoga(Pozicija_stog S) { if (S == NULL) return 0; Brisanje_stoga(S->Next); Brisanje_stabla(S->element_cvor); free(S); return 0; } int Ispis(int c, Pozicija_cvor P) { switch (c) { case(1): { if (P != NULL) { if (P->Lijevi != NULL) printf(" ( "); Ispis(c, P->Lijevi); printf(" %s", P->element); Ispis(c, P->Desni); if (P->Desni != NULL) printf(" ) "); } } break; case(2): { if (P != NULL) { printf(" %s", P->element); Ispis(c, P->Lijevi); Ispis(c, P->Desni); } } break; case(3): { if (P != NULL) { Ispis(c, P->Lijevi); Ispis(c, P->Desni); printf(" %s"), P->element; } } break; } return 0; } int Stvori_stablo(char* dat, Pozicija_stog stack, Pozicija_cvor *root) { int brojac_cvorova = 0; int broj = 0; char* buffer = NULL; Pozicija_cvor q = NULL; FILE *f = NULL; buffer = (char*)malloc(sizeof(char) * MAX_SIZE); if (buffer == NULL) { printf("\nGreska prilikom alociranja memorije za medjuspremnik."); return -1; } memset(buffer, '\0', MAX_SIZE); f = fopen(dat, "r"); if (f == NULL) { printf("\nGreska prilikom otvaranja datoteke."); return -1; } while (!feof(f)) { memset(buffer, '\0', MAX_SIZE); Stvori_cvor_stabla(&q); fscanf(f, " %s", buffer); brojac_cvorova = strlen(buffer); brojac_cvorova++; q->element = (char*)malloc(sizeof(char)*brojac_cvorova); if (q->element == NULL) { printf("\nGreska sa cvorom"); free(q); break; } memset(q->element, '\0', brojac_cvorova); brojac_cvorova--; strncpy(q->element, buffer, brojac_cvorova); q->Lijevi = NULL; q->Desni = NULL; brojac_cvorova = sscanf(buffer, " %d", &broj); if (brojac_cvorova == EOF || brojac_cvorova <= 0) { Pop(stack, &q->Desni); Pop(stack, &q->Lijevi); } Push(stack, q); } fclose(f); free(buffer); Pop(stack, &q); *root = q; return 0; }
Markdown
UTF-8
6,315
3.03125
3
[]
no_license
## __Case Study: myRetail RESTful service__ myRetail is a rapidly growing company with HQ in Richmond, VA and over 200 stores across the east coast. myRetail wants to make its internal data available to any number of client devices, from myRetail.com to native mobile apps. The goal for this exercise is to create an end-to-end Proof-of-Concept for a products API, which will aggregate product data from multiple sources and return it as JSON to the caller. Your goal is to create a RESTful service that can retrieve product and price details by ID. The URL structure is up to you to define, but try to follow some sort of logical convention. Build an application that performs the following actions: • Responds to an HTTP GET request at /products/{id} and delivers product data as JSON (where {id} will be a number. • Example product IDs: 15117729, 16483589, 16696652, 16752456, 15643793) • Example response: {"id":13860428,"name":"The Big Lebowski (Blu-ray) (Widescreen)","current_price":{"value": 13.49,"currency_code":"USD"}} • Performs an HTTP GET to retrieve the product name from an external API. (For this exercise the data will come from redsky.target.com, but let’s just pretend this is an internal resource hosted by myRetail) 
 • Example: http://redsky.target.com/v2/pdp/tcin/13860428?excludes=taxonomy,price,promotion,bulk_ship,rating_and_review_reviews,rating_and_review_statistics,question_answer_statistics • Reads pricing information from a NoSQL data store and combines it with the product id and name from the HTTP request into a single response. 
 • BONUS: Accepts an HTTP PUT request at the same path (/products/{id}), containing a JSON request body similar to the GET response, and updates the product’s price in the data store. 
 ********************************************************************************************************************************* # __Solution:__ ## __MyRetail API Solution provides the ability to:__ <ol> <li>Retrieve product and pricing information by Product Id.</li> <li>Update the price information in the mongo database.</li> <li>Secure API with basic authentication.</li> <li>One rest end point is not secure. /products just to show the how implementation without secure can be implemented</li> <li>Implement Swagger2 for API documentation</li> </ol> All the end points are totally secure in this application. I have implemented basic security and method level security as well. Update resource can be accessed by admin/admin user only. Method Request Credentials GET /products/{id} [SECURE -- admin/admin] PUT /products/{id} [SECURE -- admin/admin] GET /products [NOT SECURE] ###### __Technology Stack:__ 1. Spring Boot : 2. Feign: Declarative REST Client: Feign creates a dynamic implementation of an interface decorated with JAX-RS or Spring MVC annotations. 3. MongoDB: 4. Maven: 5. Mokito/Junit: 6. Postman: for testing the secured services ###### __Setup instructions:__ 1. Java 1.8 2. Eclipse 3. Install Mongo DB 4. Install Maven 5. Download project a) Download as a ZIP file OR 6. Import the project into eclipse – File->import ##### Run Mongo Run the Mongo daemon, in one of your terminal windows run "mongod". This should start the Mongo server. Run the Mongo shell, with the Mongo daemon running in one terminal, type "mongo" in another to run the Mongo shell ###### __Test the project:__ Test cases are present on the following directory. I have written some test cases for controller class and service class using mokito. I am using mokito for mockdata. C:\WORK_ENV\workspace\myRetail\src\test\java To run the test Go to project folder and trigger following command on the command prompt or you can also right click on the project click "Run As" > "Maven Test" (Make sure that your are running the mongodb before running the test cases or the application) mvn test. ###### __To run the application:__ Run mongo DB from the command prompt. And test --- http://localhost:27017/ (default port) Go to the project folder and trigger the command: mvn spring-boot:run ###### __Check the http Request:__ ### Secure API The end point of this application is fully secure. There are 3 users in this application. 1. admin/admin --- Can update price information and get the product by prodctId. 2. normaluser/normaluser -- get the product by prodctId. 3. dbuser/dbuser -- get the product by prodctId. ### Swagger2 documentation path http://localhost:8080/swagger-ui.html Some of the requests that could be peformed. GET: With valid product but no credentials (http://localhost:8080/products/13860428) Response: ``` Response Status Code: 401 Unauthorized Response Body: Http Status 401 Bad Credentials. ``` GET: with valid product and admin credentials (http://localhost:8080/products/13860428) ``` Response status: 200K Response Body: { "productId": 13860428, "name": "The Big Lebowski (Blu-ray) (Widescreen)", "current_price": { "value": 40.24, "currency_code": "USD" } } ``` GET: Wrong product ID and valid credentials admin/admin (http://localhost:8080/products/13860428) ``` Response Status Code: 404 Not Found Response Body: { "timestamp": 1525289857658, "status": 404, "error": "Not Found", "exception": "com.myretail.exception.ResourceNotFoundException", "message": "Resource not found. ", "path": "/products/1386042674" } ``` PUT Request: With Valid product Id and admin/admin credentials (http://localhost:8080/products/13860428) ``` Request Body: { "productId": 13860428, "name": "The Big Lebowski (Blu-ray) (Widescreen)", "current_price": { "value": 40.24, "currency_code": "USD" } } Response Status Code: 200 OK Response Body: { "value": 200, "message": "Product price has been updated" } ``` PUT Request: With Valid product Id and normaluser/normaluser credentials (http://localhost:8080/products/13860428) ``` Response Status Code: 401 Unauthorized Response Body: Http Status 401 Bad Credentials. ```
JavaScript
UTF-8
2,652
2.59375
3
[]
no_license
import React, { Component } from 'react'; import axios from '../../myAxios'; import './DropZone.css'; function fileSize(size) { if (size === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(size) / Math.log(k)); return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } export default class DropZone extends Component { constructor() { super(); this.state = { uploadedFiles: [], }; } removeFile(i) { const files = this.state.uploadedFiles; files.splice(i, 1); this.setState({ uploadedFiles: files, }); } fileDrop(e) { e.preventDefault(); const files = e.dataTransfer.files; for (let i = 0; i < files.length; i++) { this.setState({ uploadedFiles: [...this.state.uploadedFiles, files[i]], }); } } validateFile(file) { const validTypes = [ 'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/x-icon', ]; if (validTypes.indexOf(file.type) === -1) return false; return true; } async uploadFiles() { for (let i = 0; i < this.state.uploadedFiles.length; i++) { const file = this.state.uploadedFiles[i], formData = new FormData(); formData.append('file', file); try { const { data: { file }, } = await axios({ method: 'post', url: 'videos', data: formData, }); if (file) this.props.addToContent(file); } catch (error) { console.log('[ERROR_UPLOADING]', error); } } this.props.closeModal(); } render() { const { uploadedFiles } = this.state; return ( <div> <div className="drop-container" onDragOver={(e) => e.preventDefault()} onDrop={(e) => this.fileDrop(e)} > <span>DragAndDrop</span> </div> <div className="file-display-container"> {uploadedFiles.map((file, i) => ( <div className="file-status-bar" key={i}> <span className="file-type">{file.type}</span> <span className="file-name">{file.name}</span> <span className="file-size">{fileSize(file.size)}</span> <button className="btn btn-red" onClick={(e) => this.removeFile(i)} > X </button> </div> ))} </div> <button className="btn btn-green" onClick={(e) => this.uploadFiles()}> Save </button> </div> ); } }
Shell
UTF-8
5,592
3.671875
4
[]
no_license
#!/bin/sh do_setup_admin_password() { dialog --title "Setup admin password" --msgbox "You will be asked to enter a new password." 5 60 passwd admin RET=$? if [ $RET -eq 0 ]; then dialog --title "Setup admin password" --msgbox "Password has been changed succesfully." 5 60 do_main_menu fi } do_setup_concentrator_shield() { FUN=$(dialog --title "Setup LoRa concentrator shield" --menu "Select shield:" 15 60 4 \ 1 "IMST - iC880A" \ 2 "RAK - RAK381 with uBLOX GPS module" \ 3 "RAK - RAK381 without uBLOX GPS module" \ 4 "RisingHF - RHF0M301" \ 3>&1 1>&2 2>&3) RET=$? if [ $RET -eq 1 ]; then do_main_menu elif [ $RET -eq 0 ]; then case "$FUN" in 1) do_prompt_concentrator_reset_pin && do_setup_channel_plan "ic880a" "";; 2) do_set_concentrator_reset_pin 17 && do_setup_channel_plan "rak381" ".gps";; 3) do_set_concentrator_reset_pin 17 && do_setup_channel_plan "rak381" "";; 4) do_set_concentrator_reset_pin 7 && do_setup_channel_plan "rhf0m301" "";; esac fi } do_setup_channel_plan() { # $1: concentrator type # $2: config suffix, eg ".gps" FUN=$(dialog --title "Channel-plan configuration" --menu "Select the channel-plan:" 15 60 2 \ 1 "EU868" \ 2 "US915" \ 3>&1 1>&2 2>&3) RET=$? if [ $RET -eq 1 ]; then do_main_menu elif [ $RET -eq 0 ]; then case "$FUN" in 1) do_copy_global_conf $1 "eu868" $2;; 2) do_copy_global_conf $1 "us915" $2;; esac fi } do_prompt_concentrator_reset_pin() { PIN=$(dialog --inputbox "To which pin is the concentrator reset connected: " 8 60 \ 3>&1 1>&2 2>&3) RET=$? if [ $RET -eq 1 ]; then do_setup_concentrator_shield elif [ $RET -eq 0 ]; then do_set_concentrator_reset_pin $PIN fi } do_set_concentrator_reset_pin() { sed -i "s/^\(CONCENTRATOR_RESET_PIN=\).*$/\1$1/" /etc/default/lora-packet-forwarder } do_copy_global_conf() { cp /etc/lora-packet-forwarder/$1/global_conf.$2.json$3 /etc/lora-packet-forwarder/global_conf.json RET=$? if [ $RET -eq 0 ]; then dialog --title "Channel-plan configuration" --msgbox "Channel-plan configuration has been copied." 5 60 do_set_gateway_id fi } do_set_gateway_id() { /opt/lora-packet-forwarder/update_gwid.sh /etc/lora-packet-forwarder/global_conf.json RET=$? if [ $RET -eq 0 ]; then dialog --title "Set Gateway ID" --msgbox "The Gateway ID has been set." 5 60 do_restart_packet_forwarder fi } do_setup_concentrator_shield_rak_rak381() { FUN=$(dialog --title "RAK - RAK381 configuration" --menu "Select configuration:" 15 60 4 \ eu868.json "EU868 band" \ eu868.json.gps "EU868 band + GPS" \ 3>&1 1>&2 2>&3) RET=$? if [ $RET -eq 1 ]; then do_setup_concentrator_shield elif [ $RET -eq 0 ]; then return 1 fi } do_restart_packet_forwarder() { monit restart lora-packet-forwarder RET=$? if [ $RET -eq 0 ]; then dialog --title "Restart packet-forwarder" --msgbox "The packet-forwarder has been restarted." 5 60 do_main_menu fi } do_restart_lora_gateway_bridge() { monit restart lora-gateway-bridge RET=$? if [ $RET -eq 0 ]; then dialog --title "Restart LoRa Gateway Bridge" --msgbox "The LoRa Gateway Bridge has been restarted." 5 60 do_main_menu fi } do_configure_wifi() { dialog --title "Configure WIFI" --msgbox "This will open the 'connmanctl' utility to configure the WIFI." 5 75 dialog --title "connmanctl quickstart" --msgbox "1) Enable wifi:\n enable wifi\n\n 2) Scan available wifi networks:\n scan wifi\n\n 3) Display available wifi networks:\n services\n\n 4) Turn on agent:\n agent on\n\n 5) Connect to network:\n connect wifi_...\n\n 6) Quit connmanctl:\n quit" 25 60 clear connmanctl RET=$? if [ $RET -eq 0 ]; then do_main_menu fi } do_resize_root_fs() { dialog --title "Resize root FS" --msgbox "This will resize the root FS to utilize all available space. The gateway will reboot after which the resize process will start. Please note that depending the SD Card size, this will take some time during which the gateway cann be less responsive.\n\n To monitor the root FS resize, you can use the following command:\ndf -h" 25 60 clear echo "The gateway will now reboot!" /etc/init.d/resize-rootfs start } do_main_menu() { FUN=$(dialog --title "LoRa Gateway OS" --cancel-label "Quit" --menu "Configuration options:" 15 60 8 \ 1 "Set admin password" \ 2 "Setup LoRa concentrator shield" \ 3 "Edit packet-forwarder config" \ 4 "Edit LoRa Gateway Bridge config" \ 5 "Restart packet-forwarder" \ 6 "Restart LoRa Gateway Bridge" \ 7 "Configure WIFI" \ 8 "Resize root FS" \ 3>&1 1>&2 2>&3) RET=$? if [ $RET -eq 1 ]; then clear return 0 elif [ $RET -eq 0 ]; then case "$FUN" in 1) do_setup_admin_password;; 2) do_setup_concentrator_shield;; 3) nano /etc/lora-packet-forwarder/global_conf.json && do_main_menu;; 4) nano /etc/lora-gateway-bridge/lora-gateway-bridge.toml && do_main_menu;; 5) do_restart_packet_forwarder;; 6) do_restart_lora_gateway_bridge;; 7) do_configure_wifi;; 8) do_resize_root_fs;; esac fi } do_main_menu
Java
UTF-8
2,348
2.28125
2
[]
no_license
package com.chinarewards.metro.domain.user; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Transient; /** * 用户信息 * @author huangshan * */ @Entity public class UserInfo implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO ) private Integer id; private String userName; private String password; private Integer disable; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user") private Set<UserRole> userRoles = new HashSet<UserRole>(0); @Transient private String userRole; @Transient private String roleIds; public String getRoleIds() { return roleIds; } public void setRoleIds(String roleIds) { this.roleIds = roleIds; } public String getUserRole() { return userRole; } public void setUserRole(String userRole) { this.userRole = userRole; } public Set<UserRole> getUserRoles() { return userRoles; } public void setUserRoles(Set<UserRole> userRoles) { this.userRoles = userRoles; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getDisable() { return disable; } public void setDisable(Integer disable) { this.disable = disable; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UserInfo other = (UserInfo) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
C++
UTF-8
605
3.15625
3
[]
no_license
#include "timsort.h" #include <windows.h> #include <iostream> class Timer { public: Timer() { m_dwTime = GetTickCount(); } DWORD GetTime() { return GetTickCount() - m_dwTime; } private: DWORD m_dwTime; }; bool checkSort (double *x, long length) { double *x1=x, *x2=x+1; while (x2<x+length && x1<=x2) { ++x1; ++x2; } return x2==(x+length); } const long size=100000000; double a1[size]; int main(){ for (int i=0; i<size; ++i) a1[i]=rand()%size; Timer time; timsort(&a1[0], size); std::cout << time.GetTime() << " ms" << "\n"; std::cout<<checkSort(a1, size); system("pause"); }
Java
UTF-8
1,128
2.625
3
[]
no_license
package study; import study.admin.Admin; import study.cinemas.CinemaRB; import study.staff.Cassir; import study.staff.Director; import study.staff.Staff; public class Test { public static void main(String[] args) { CinemaRB cinemaMir = new CinemaRB("MIR", new Admin("Vlad", "Pro"), new Staff(new Director("Vasya", "Sidorov"), new Cassir("Elena", "Ivanova"))); CinemaRB cinemaPobeda = new CinemaRB("Pobeda", cinemaMir.getAdmin(), new Staff(new Director("Petya", "Petrov"), new Cassir("Ira", "Smirnova"))); System.out.println(cinemaMir.toString()); System.out.println(cinemaPobeda.toString()); System.out.println("------------------"); Admin admin = cinemaMir.getAdmin(); admin.setNewDirector(cinemaPobeda, new Director("Serega", "Kent")); admin.deleteDirector(cinemaMir); admin.setNewCassir(cinemaPobeda, new Cassir("Luda", "Svanidze")); System.out.println(cinemaMir.toString()); System.out.println(cinemaPobeda.toString()); } }
Java
UTF-8
4,265
3.25
3
[]
no_license
package com.wenhuiliu.EasyEnglishReading; import android.util.Log; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Article { /** * 文章类,描述关于文章的信息 * 标题、内容、时间、分类、级别、难度系数 * 通过构造方法来进行初始化,时间默认为当前时间、难度系数默认为100、级别默认高级 * 通过getWords的方法把文章内容一单个单词的形式存储到链表 */ private String title; private StringBuilder body; private String time; private Catalogy catalogy; private Level level; private int difficultRatio; public Article(){ this.title = "title"; this.body = new StringBuilder("body"); this.catalogy = Catalogy.valueOf("科技"); this.time=new Date().toString(); this.difficultRatio = 100; this.level = Level.valueOf("高级"); } public Article(String title,StringBuilder body,String catalogy){ // Log.d("开始初始化文章对象","..."); if(title==null || body==null || catalogy == null) { throw new IllegalArgumentException("title/body/catalogy not null"); } this.title = title; this.body = body; this.catalogy = Catalogy.valueOf(catalogy); this.time=new Date().toString().substring(0,16); // Log.d("时间",time); this.difficultRatio = 100; this.level = Level.valueOf("高级"); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public StringBuilder getBody() { return body; } public void setBody(String body) { this.body = new StringBuilder(body); } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getCatalogy(){ return catalogy.getDescription(); } public String getLevel(){ return level.getLevel(); } public void setLevel(String alevel){ this.level = Level.valueOf(alevel); } public void setDifficultRatio(int ratio){ this.difficultRatio = ratio; } public int getDifficultRatio(){ return this.difficultRatio; } // 如果不匹配系统自动报错。 public enum Catalogy implements Serializable{ 科技 ( "科技"), 自然 ( "自然"), 健康 ( "健康"), 教育 ( "教育"), 经济 ( "经济"), 今日 ( "今日"), 默认 ( "默认"); // 以后可以加娱乐和理财类 // private final int status; private final String description; // 在构造函数的时候给其赋值 Catalogy(String desc) { // this.status = aStatus; this.description = desc; } // public int getStatus() { // return this.status; // } public String getDescription() { return this.description; } } public enum Level{ 初级 ("初级"), 中级 ("中级"), 高级 ("高级"); private final String level; private Level(String alevel){ this.level = alevel; } public String getLevel(){ return this.level; } } // 把文章内容为String类型的转为Arraylist类型的 public ArrayList<String> getWords(){ ArrayList<String> words = new ArrayList<String>(); //Pattern expression = Pattern.compile("[a-zA-Z,."';:]+"); //定义正则表达式匹配单词 //Pattern expression = Pattern.compile("([\\w]+)|([,.:;\"?!]+)"); //Pattern expression = Pattern.compile("([\\w]+)|([\\pP])"); Pattern expression = Pattern.compile("([\\w]+)|([.,\"\\?!:'$^])"); Matcher matcher = expression.matcher(body); while(matcher.find()){ words.add(matcher.group()); // System.out.println(matcher.group()); } return words; } }
C#
UTF-8
1,250
2.921875
3
[]
no_license
using UnityEngine; using System.Collections; public class checkBox : MonoBehaviour { //Variable which defines what option this particular instance of CheckBox selects (Short, Medium, Long) public string option; //sr is the SpriteRenderer of "checkBoxMark" child object, which shows if the current check box is checked private SpriteRenderer sr; //Start goes through all of the the current instance's child objects, and finds the one with the name "checkBoxMark" //It then sets this instance's "sr" variable to the SpriteRenderer of the "checkBoxMark" object. void Start(){ foreach (Transform t in transform) { if(t.name == "checkBoxMark"){ sr = t.GetComponent<SpriteRenderer>(); } } } //Update checks if the currently selected game size in Static Variables is the same as the current instance's "option" variable //If it is, the current check box's "checkBoxMark" is shown, indicating that it is selected. If not, it is hidden void Update(){ if (staticVariables.gameSize == option) { sr.enabled = true; }else{ sr.enabled = false; } } //When the touched, the current instance's option is set as the game size in Static Variables public void OnTouchDown(){ staticVariables.gameSize = option; } }
Python
UTF-8
469
3.796875
4
[]
no_license
'''from threading import Thread class Mythread(Thread): pass t=Mythread() print(t.name)''' print() #Run Method: '''from threading import Thread class Mythread(Thread): def run(self): print('Run Method') t=Mythread() t.start()''' #Join Method: from threading import Thread class Mythread(Thread): def run(self): for i in range(5): print('Child Thread') t=Mythread() t.start() t.join() for i in range(5): print("Main thread")
Java
UTF-8
3,316
2.453125
2
[]
no_license
package se.lexicon.g33.jpa_assignment.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import se.lexicon.g33.jpa_assignment.data.RecipeRepository; import se.lexicon.g33.jpa_assignment.model.entity.Recipe; import se.lexicon.g33.jpa_assignment.model.entity.RecipeCategory; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; @RestController public class RecipeController { private final RecipeRepository repository; @Autowired public RecipeController(RecipeRepository repository) { this.repository = repository; } @PostMapping("/api/recipe") public ResponseEntity<Recipe> createRecipe(@RequestBody Recipe recipe) { repository.save(recipe); return ResponseEntity.created(URI.create("/api/recipe/" )).body(recipe); } /* @GetMapping("/api/recipe/all") public ResponseEntity<Iterable<Recipe>> findAllRecipes(){ return ResponseEntity.ok(repository.findAll()); } @GetMapping("/api/recipe/name") public ResponseEntity<Collection<Recipe>> findRecipesByName(@RequestParam (name = "value", required = true) String value) { return ResponseEntity.ok(repository.findByRecipeNameContainsIgnoreCase(value)); } @GetMapping("/api/recipe/ingredient") public ResponseEntity<Collection<Recipe>> findByIngredient(@RequestParam (name = "value", required = true) String value) { return ResponseEntity.ok(repository.findByIngredientNameIgnoreCase(value)); } @GetMapping("/api/recipe/category") public ResponseEntity<Collection<Recipe>> findByCategory(@RequestParam (name = "value", required = true) String value) { return ResponseEntity.ok(repository.findByCategoryIgnoreCase(value)); } @GetMapping("/api/recipe/categories") public ResponseEntity<Collection<Recipe>> findByCategories(@RequestParam (name = "values", required = true) Collection<String> values) { return ResponseEntity.ok(repository.findByCategories(values)); } */ @GetMapping("/api/recipe") public ResponseEntity<Collection<Recipe>> findRecipes(@RequestParam (name ="name", required = false ) String name, @RequestParam (name = "ingredient", required = false) String ingredient, @RequestParam (name="category", required = false) String category, @RequestParam (name = "categories", required = false) Collection<String> categories) { if(name != null){ return ResponseEntity.ok(repository.findByRecipeNameContainsIgnoreCase(name)); } else if (ingredient != null) { return ResponseEntity.ok(repository.findByIngredientNameIgnoreCase(ingredient)); } else if (category != null) { return ResponseEntity.ok(repository.findByCategoryIgnoreCase(category)); } else if (categories != null){ return ResponseEntity.ok(repository.findByCategories(categories)); } else { return ResponseEntity.ok(repository.findAll()); } } }
Java
UTF-8
5,062
2.25
2
[ "MIT" ]
permissive
/* The MIT License Copyright (c) 2010-2013 Paul R. Holser, Jr. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.pholser.junit.quickcheck.internal; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.javaruntype.type.Type; public final class Reflection { private Reflection() { throw new UnsupportedOperationException(); } public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } public static Set<Type<?>> supertypes(Type<?> bottom) { Set<Type<?>> supertypes = new HashSet<Type<?>>(); supertypes.add(bottom); supertypes.addAll(bottom.getAllTypesAssignableFromThis()); return supertypes; } public static Object defaultValueOf(Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } public static List<Annotation> markedAnnotations(List<Annotation> annotations, Class<? extends Annotation> marker) { List<Annotation> marked = new ArrayList<Annotation>(); for (Annotation each : annotations) { if (markedWith(each, marker)) marked.add(each); } return marked; } private static boolean markedWith(Annotation a, Class<? extends Annotation> marker) { for (Annotation each : a.annotationType().getAnnotations()) { if (each.annotationType().equals(marker)) return true; } return false; } public static Method findMethodQuietly(Class<?> target, String methodName, Class<?>... argTypes) { try { return target.getMethod(methodName, argTypes); } catch (Exception ex) { throw reflectionException(ex); } } public static Object invokeQuietly(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { throw reflectionException(ex); } } public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (Modifier.isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private static boolean overridesJavaLangObjectMethod(Method method) { return isEquals(method) || isHashCode(method) || isToString(method); } private static boolean isEquals(Method method) { return "equals".equals(method.getName()) && method.getParameterTypes().length == 1 && Object.class.equals(method.getParameterTypes()[0]); } private static boolean isHashCode(Method method) { return "hashCode".equals(method.getName()) && method.getParameterTypes().length == 0; } private static boolean isToString(Method method) { return "toString".equals(method.getName()) && method.getParameterTypes().length == 0; } private static RuntimeException reflectionException(Exception ex) { if (ex instanceof InvocationTargetException) return new ReflectionException(((InvocationTargetException) ex).getTargetException()); if (ex instanceof RuntimeException) return (RuntimeException) ex; return new ReflectionException(ex); } }
C++
UTF-8
1,281
2.65625
3
[ "Apache-2.0" ]
permissive
#pragma once #ifndef CSTHEAD_PAD_TO_HEAD_H_ #define CSTHEAD_PAD_TO_HEAD_H_ #include <vector> namespace CSTHead { class HeadMovement { public: HeadMovement() {} ~HeadMovement() {} public: struct PAD { float P; float A; float D; }; struct SyllableInfo { PAD pad; int start_frame_no; int end_frame_no; bool stressed; int tone; }; public: // Generate FAP stream based on PAD, Tone and Stress static void generateFAPs(const std::vector<SyllableInfo>& sylInfo, const std::vector<int>& pwInfo, std::vector< std::vector<float> >& faps); protected: // set head movement average position and amplitude for each PW static void GetHeadPos(const PAD pad,float &pos,float &amp); // get mean value of a series data of a vector static float GetMeanValue(const std::vector<float> data,const int s,const int e); // get PAD combination TYPE static int GetPADType(const PAD pad); static void smooth(std::vector<float> &data,const int win_len); static unsigned int getRandSeed(); }; } #endif//CSTHEAD_PAD_TO_HEAD_H_
C++
UTF-8
1,689
2.953125
3
[]
no_license
// // Created by Maikol Guzman on 8/2/20. // #ifndef LAB02_OOP_PERSON_H #define LAB02_OOP_PERSON_H #include <string> #include <ostream> #include <vector> #include "Administrative.h" #include "Professor.h" /** * Abstract Class of Person ////// revisar codigo para verificar si relaciones , metodos , clases y etc. funcionarian. */ class Person {//paciente //struct// class Person; // Como el doctor y el paciente tienen una dependencia circular, declaramos Doctor class Administrative { std::string firstname; std::string lastname; std::string documentId; std::vector<Person *> personas; class Professor { std::string firstname; std::string lastname; std::string documentId; std::vector<Person *> personas; public: Person(); Person((firstName:const std::string &firstname : firstname(firstName)),(lastName:const std::string &lastname) : lastname(lastname),(DocumentId:const std::string &documentId) documentid(documentId)) ; virtual ~person(); ////void agregarDoctor(Doctor *_doctor); ////friend std::ostream &operator<<(std::ostream &os, const Paciente &paciente); const std::string &getLastName() const; const std::string &getFirstName() const; const std::string &getDocumentID() const; void setLastName(const std::string &lastname); void setFirstName(const std::string &firstname); void setDocumentId(documentId); const std::vector<Person *> &getPersons() const; void setPersons(const std::vector<Person *> &persons); }; }; #endif //LAB02_OOP_PERSON_H
Java
UTF-8
1,016
2.71875
3
[]
no_license
package server; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import server.exception.NameNotFoundException; public class NicknameQuery extends Query implements Runnable { public NicknameQuery(Socket socket, PrintWriter out, BufferedReader in, String name) { super(socket, out, in, name); } @Override public void run() { String segment; try { segment = in.readLine(); try { String response = nickname.getNickname(name).toString(); if (segment.startsWith("END")) { print("HELO"); print("NAME:" + name); print("NICKNAME_START:" + response); print("NICKNAME_END"); print("END"); out.flush(); } else { wrongProtocol(); } } catch (NameNotFoundException e) { print("HELO"); print("ERR NO_EXIST"); print("ERR_START:Name unknown:" + name); print("ERR_END"); print("END"); out.flush(); } } catch (IOException e1) { e1.printStackTrace(); } } }
Java
UTF-8
417
2.125
2
[]
no_license
package engineers.workshop.common.network.data; import engineers.workshop.common.table.TileTable; import net.minecraft.nbt.NBTTagCompound; public class DataLit extends DataBase { @Override public void save(TileTable table, NBTTagCompound dw, int id) { dw.setBoolean("lit", table.isLit()); } @Override public void load(TileTable table, NBTTagCompound dr, int id) { table.setLit(dr.getBoolean("lit")); } }
Java
UTF-8
2,021
3.8125
4
[]
no_license
//프로그래머스 코딩테스트 연습 <DFS/BFS> - '단어 변환' 문제 public class Programmers43163 { static boolean [] visited; static int answer; public static void main(String[] args) { String begin = "hit"; String target = "cog"; String [] words = {"hot", "dot", "dog", "lot", "log", "cog"}; System.out.println(solution(begin, target, words)); } public static int solution(String begin, String target, String[] words) { visited = new boolean[words.length]; answer = Integer.MAX_VALUE; //words 배열에 target이 있는 지 없는 지 판단하는 isPossible boolean isPossible = false; for(int i=0;i<words.length;i++){ if(words[i].equals(target)) { isPossible = true; break; } } if(isPossible == false) return 0; else dfs(words,begin,target,0); //dfs를 통해 지속적으로 갱신된 최소값 return. return answer; } //두 String의 철자 차이가 1개인지 확인하는 함수 public static boolean oneCharDiff(String s1, String s2){ int alphabet = 0; for(int j=0;j<s1.length();j++){ if(s1.charAt(j) != s2.charAt(j)) alphabet++; if(alphabet > 1){ alphabet = 0; break; } } if(alphabet == 1) return true; else return false; } //dfs로 모든 경우의 수를 다 탐색하여 최소값의 depth를 갱신한다. public static void dfs(String [] words, String word, String target, int depth){ if(word.equals(target)){ answer = Math.min(answer, depth); return; } for(int i=0;i<words.length;i++){ if(!visited[i] && oneCharDiff(word, words[i])){ visited[i] = true; dfs(words, words[i], target, depth + 1); visited[i] = false; } } } }
Markdown
UTF-8
33,767
2.671875
3
[]
no_license
### Paper 37: Dota 2 with Large Scale Deep Reinforcement Learning (OpenAI Five) — Appendix ### A Compute Usage ### B Surgery - #### Changing the architecture - #### Changing the Observation Space - #### Changing the Environment or Action Space - #### Removing Model Parts - #### Smooth Training Restart - #### Benefits of Surgery ### C Hyperparameters #### When we ran Rerun we simplified the hyperparameter schedule based on the lessons we had learned. In the end we made changes to only `four key hyperparameters`: - #### Learning Rate - #### Entropy penalty coefficient - #### Team Spirit - #### GAE time horizon <p align="center"> <img src="/images/674.png"><br/> Figure 1: Hyperparameters </p> ### D Evaluating agents’ understanding #### It is often difficult to `infer the intentions of an RL agent`. Some actions are obviously useful — hitting an enemy that is low on health, or freezing them as they’re trying to escape — but many other decisions can be less obvious. This is tightly coupled with questions on intentionality(意向性): does our agent plan on attacking the tower, or doe it opportunistically deal the most damage possible in next few seconds? #### To assess this, we attempt to `predict future state of various features of the game` from agent’s - #### `Win probability`: Binary label of either 0 or 1 at the end of the game. - #### `Net worth rank(净值排名)`: Which rank among the team (1-5) in terms of total resources collected will this hero be at the end of the game? This prediction is used by scripted item-buying logic to decide which agents buy items shared by the team such as wards. In human play (which the scripted logic is based on) this task is traditionally performed by heroes who will have the lowest net worth at the end of the game. - #### `Team objectives / enemy buildings`: whether this hero will help the team destroy a given enemy building in the near future. #### We added small networks of fully-connected layers that transform LSTM output into predictions of these values. For historical reasons, win probability passes gradients to the main LSTM and rest of the agent with a very small weight; the other auxiliary(辅助的)predictions use Tensorflow’s stop_gradient method to train on their own. <p align="center"> <img src="/images/675.png"><br/> Figure 2: Timescales and Staleness </p> #### One difficulty in training these predictors is that we train our agent on 30-second segments of the game (see Figure 2), and `any given 30-second snippet may not contain the ground truth` (e.g. for win probability and networth position, we only have ground truth on the very last segment of the game). We address this by training these heads in a similar fashion to how we train value functions. If a segment contains the ground truth label, we use the ground truth label for all time steps in that segment; if not, we use the model’s prediction at the end of the segment as the label. For win probability, for example, more precisely the label y for a segment from time t1 to t2 is given by: <p align="center"> <img src="/images/676.png"><br/> </p> #### Where ˆy(t2) is is the model’s predicted win probability at the end of the segment. Although this requires information to travel backward through the game, we find it trains these heads to a degree of calibration and accuracy. For the team objectives, we are additionally interested in whether the event will happen soon. #### For these we apply an additional discount factor with horizon of 2 minutes. This means that the enemy building predictions are not calibrated probabilities, but rather probabilities discounted by the expected time to the event. #### D.1 Understanding OpenAI Five Finals #### We explore the progression of `win probability predictions` over the course of training Rerun, illustrating the `evolution of understanding`. Version 5,000 of the agent (early in the training process and low performance) already has a sense of what situations in the game may lead to eventual win. The prediction continues to get better and better as training proceeds. This matches human performance at this task, where even spectators with relatively little gameplay experience can estimate who is ahead based on simple heuristics, but with more gameplay practice human experts can estimate the winner more and more accurately. #### We also looked at `heroes participation in destroying objectives`. We can see different heroes’ predictions for each of the objectives in the game. In several cases all heroes `predict they will participate in the attack` (and they do). In few cases one or two heroes are left out, and indeed by watching the game replay we see that those heroes are busy in the different part of the map during that time. We illustrate these predictions with more details for two of the events. `Predictions should not be read as calibrated probabilities, because they are trained with a discount factor`. #### D.2 Hero selection #### In the normal game of Dota 2, two teams at the beginning of the game go through the process of selecting heroes. This is a very important step for future strategy, as heroes have different skill sets and special abilities. OpenAI Five is trained purely on learning to play the best game of Dota 2 possible `given randomly selected heroes`. #### Although we could likely train a separate drafting agent to play the draft phase, we do not need to; instead we can use the win probability predictor. Because the main varying observation that agents see at the start of the game is which heroes are on each team, `the win probability at the start of the game estimates the strength of a given matchup`. Because there are only 4,900,896 combinations of two 5-hero teams from the pool of 17 heroes, we can `precompute agent’s predicted win probability from the first few frames of every lineup`. Given these precomputed win probabilities, we apply a dynamic programming algorithm to draft the best hero available on each turn. #### In addition to building a hero selection tool, we also `learned about our agent’s preferences` from this. In many ways OpenAI Five’s preferences match human player’s preferences such as placing a high value (within this pool) on the hero Sniper. In other ways it does not agree with typical human knowledge, for example it places low value on Earthshaker. Our agent had trouble dealing with geometry of this hero’s “Fissure” skill, making this hero worse than others in training rollouts. #### `Another interesting tidbit(趣闻)` is that at the very start of the draft, before any heroes are picked, OpenAI Five believes that the Radiant team has a 54% win chance (if picking first in the draft) or 53% (if picking second). Our agent’s higher estimate for the Radiant side over the Dire agrees with conventional wisdom within the Dota 2 community. Of course, this likely depends on the set of heroes available. ### E Observation Space #### At each time step one of our heroes observes ∼ 16,000 inputs about the game state (mostly real numbers with some integer categorical data as well). #### Instead of using the pixels on the screen, we `approximate the information available to a human player in a set of data arrays`. This approximation is imperfect; there are small pieces of information which humans can gain access to which we have not encoded in the observations. On the flip side, while we were careful to ensure that all the information available to the model is also available to a human, the model does get to see all the information available simultaneously every time step, whereas a human needs to click into various menus and options to get that data. Although these discrepancies are a limitation, we do not believe they meaningfully detract from our ability to benchmark against human players. #### Humans observe the game via a rendered screen, depicted in Figure 3. OpenAI Five `uses a more semantic observation space` than this for two reasons: 1. #### First, because our goal is to study strategic planning and gameplay rather than focus on visual processing. 2. #### Second, it is infeasible for us to render each frame to pixels in all training games; this would multiply the computation resources required for the project manyfold. <p align="center"> <img src="/images/677.png"><br/> Figure 3: Dota 2’s human “Observation Space” </p> #### All float observations (including booleans which are treated as floats that happen to take values 0 or 1) are `normalized before feeding into the neural network`. For each observation, we `keep a running mean and standard deviation of all data ever observed`; at each timestep we subtract the mean and divide by the st dev, clipping the final result to be within (-5, 5). ### F Action Space #### Dota 2 is usually controlled using a mouse and keyboard. `The majority of the actions involve a high-level command` (attack, use a certain spell, or activate a certain item), `along with a target` (which might be an enemy unit for an attack, or a spot on the map for a movement). For that reason we `represent the action our agent can choose at each timestep as a single primary action along with a number of parameter actions`. #### `The number of primary actions available varies from time step to time step`, averaging 8.1 in the games against OG. The primary actions available at a given time include universal actions like noop, move, attack, and others; use or activate one of the hero’s spells; use or activate one of the hero’s items; situational actions such as Buyback (if dead), Shrine (if near a shrine), or Purchase (if near a shop); and more. `For many of the actions we wrote simple action filters, which determine whether the action is available`; these check if there is a valid target nearby, if the ability/item is on cooldown, etc. At each timestep we restrict the set of available actions using these filters and present the final choices to the model. #### In addition to a primary action, `the model chooses action parameters. At each timestep the model outputs a value for each of them`; depending on the primary action, some of them are read and others ignored (when optimizing, we mask out the ignored ones since their gradients would be pure noise). There are 3 parameter outputs, Delay (4 dim), unit selection (189 dim), and offset (81 dim), described in Figure 4. <p align="center"> <img src="/images/678.png"><br/> Figure 4: Action Parameters </p> #### All together this produces `a combined factorized action space size` of up to 30 × 4 × 189 × 81 = 1, 837, 080 dimensions (30 being the maximum number of primary actions we support). This number ignores the fact that the number of primary actions is usually much lower; some parameters are masked depending on the primary action; and some parameter combinations are invalid and those actions are treated as no-ops. #### `The average number of available actions varies significantly across heroes`, as different heroes have different numbers spells and items with larger parameter counts. Across the two games played against Team OG, the average number of actions for a hero varied from 8,000 to 80,000. #### Unit Selection and Offset are actually implemented within the model as several different, mutually exclusive parameters depending on the primary action. For Unit Selection, we found that using a single output head caused that head to learn very well to target tactical spells and abilities. One ability called “teleport,” however, is significantly different from all the others — rather than being used in a tactical fight, it is used to strategically reposition units across the map. Because the action is much more rare, the learning signal for targeting this ability would be drowned out(淹没)if we used a single model output head for both. For this reason the model outputs a normal Unit Selection parameter and a separate Teleport Selection parameter, and one or the other is used depending on the primary action. Similarly, the Offset parameter is split into “Regular Offset,” “Caster Offset” (for actions which only make sense offset from the caster), and “Ward Placement Offset” (for the rare action of placing observer wards). #### We `categorize all primary actions into 6 “Action target types”` which determines which parameters the action uses, listed in Figure 5. <p align="center"> <img src="/images/679.png"><br/> Figure 5: Action Target Types </p> #### F.1 Scripted Actions #### Not all actions that a human takes in a game of Dota 2 are controlled by our RL agent. Some of the actions are scripted, meaning that `we have written a rudimentary(基本的)rules-based system to handle these decisions`. Most of these are for historical reasons — `at the start of the project we gave the model control over a small set of the actions, and we gradually expanded it over time`. Each additional action that we remove from the scripted logic and hand to the model’s control gives the RL system a higher potential skill cap, but comes with an cost measured in engineering effort to set it up and risks associated with learning and exploration. Indeed even when adding these new actions gradually and systematically, we `occasionally encountered instabilities`; for example the agent might quickly learn never to take a new action (and thus fail to explore the small fraction of circumstances where that action helps), and thus moreover fail to learn (or unlearn) the dependent parts of the gameplay which require competent use of the new action. #### In the end there were still `several systems that we had not yet removed from the scripted logic` by the time the agent reached superhuman performance. While we believe the agent could ultimately perform better if these actions were not scripted, we saw no reason to do remove the scripting because superhuman performance had already been achieved. `The full set of remaining scripted actions` is: 1. #### Ability Builds(技能加点) 2. #### Item Purchasing(商店购物) 3. #### Item Swap(商品切换) 4. #### Courier Control(控制信使) ### G Reward Weights #### Our agent’s ultimate goal is to win the game. In order to simplify the credit assignment problem (the task of figuring out which of the many actions the agent took during the game led to the final positive or negative reward), we use `a more detailed reward function`. Our shaped reward is `modeled loosely after potential-based shaping functions`, though the guarantees therein do not apply here. We give the agent reward (or penalty) for a set of actions which humans playing the game generally agree to be good (gaining resources, killing enemies, etc). #### All the results that we reward can be found in Figure 6, with the amount of the reward. Some are given to every hero on the team (“Team”) and some just to the hero who took the action “Solo”. Note that this means that `when team spirit is 1.0, the total amount of reward is five times higher for “Team” rewards than “Solo” rewards`. <p align="center"> <img src="/images/680.png"><br/> Figure 6: Shaped Reward Weights </p> #### In addition to the set of actions rewarded and their weights, our `reward function contains 3 other pieces`: - #### `Zero sum`: The game is zero sum (only one team can win), everything that benefits one team necessarily hurts the other team. We ensure that all our rewards are zero-sum, by `subtracting from each hero’s reward the average of the enemies’ rewards`. - #### `Game time weighting`: Each player’s “power” increases dramatically over the course of a game of Dota 2. A character who struggled to kill a single weak creep early in the game can often kill many at once with a single stroke by the end of the game. This means that the end of the game simply produces more rewards in total (positive or negative). If we do not account for this, the learning procedure focuses entirely on the later stages of the game and ignores the earlier stages because they have less total reward magnitude. We use a simple renormalization to deal with this, multiplying all rewards other than the win/loss reward by a factor which decays exponentially over the course of the game. `Each reward ρi earned a time T since the game began is scaled`: <p align="center"> <img src="/images/681.png"><br/> </p> - #### `Team Spirit`: Because we have multiple agents on one team, we have an additional dimension to the credit assignment problem, where the agents need learn which of the five agent’s behavior cause some positive outcome. The partial rewards defined in Figure 6 are an attempt to make the credit assignment easier, but they may backfire(回火)and in fact add more variance if an agent receives reward when a different agent takes a good action. To attempt dealing with this, we have introduced team spirit. It `measures how much agents on the team share in the spoils(战利品)of their teammates`. If each hero earns raw individual reward ρi, then we compute the hero’s final reward ri as follows: <p align="center"> <img src="/images/682.png"><br/> </p> #### If team spirit is 0, then it’s every hero for themselves; each hero only receives reward for their own actions ri = ρi. If team spirit is 1, then every reward is split equally among all five heroes; ri = ρ. For a team spirit τ in between, team spirit-adjusted rewards are linearly interpolated between the two. #### Ultimately we care about optimizing for team spirit τ = 1; we want the actions to be chosen to optimize the success of the entire team. However we find that lower team spirit reduces gradient variance in early training, ensuring that agents receive clearer reward for advancing their mechanical and tactical ability to participate in fights individually. ### H Neural Network Architecture #### [OpenAI Five Model Architecture](https://github.com/Kiiiiii123/Kiiiiii123.github.io/blob/master/images/688.png) #### A simplified diagram of the joint policy and value network is shown in the main text in Figure 1 (Part 1). The combined policy + value network uses 158,502,815 parameters (in the final version). The policy network is designed to receive observations from our bot-API observation space, and interact with the game using a rich factorized action space. These structured observation and action spaces heavily inform the neural network architecture used. We use `five replica neural networks`, each responsible for the observations and actions of one of the heroes in the team. At a high level, this `network consists of three parts`: 1. #### first the observations are processed and pooled into a single vector summarizing the state (see Figure 7 and Figure 8), 2. #### then that is processed by a single-layer large LSTM, 3. #### then the outputs of that LSTM are projected to produce outputs using linear projections (see Figure 9). #### To provide the full details, we should clarify that Figure 1 in Part 1 is a slight over-simplification in three ways: 1. #### In practice the Observation Processing portion of the model is also cloned 5 times for the five different heroes. The weights are identical and the observations are nearly identical — but there are a handful of derived features which are different for each replica (such as “distance to me” for each unit). Thus the five replicas produce nearly identical, but perhaps not entirely identical, LSTM inputs. These non-identical features form a small portion of the observation space, and were not ablated; it is possible that they are not needed at all. 2. #### The “Flattened Observation” and “Hero Embedding” are processed before being sent into the LSTM (see Figure 8) by a fully-connected layer and a “cross-hero pool” operation, to ensure that the non-identical observations can be used by other members of the team if needed. 3. #### The “Unit Embeddings” from the observation processing are carried along beside the LSTM, and used by the action heads to choose a unit to target (see Figure 9). #### In addition to the action logits, the value function is computed as another linear projection of the LSTM state. Thus our `value function and action policy share a network and share gradients`. <p align="center"> <img src="/images/683.png"><br/> Figure 7: Flattening the observation space </p> #### `First we process the complicated observation space into a single vector`. The observation space has a `tree structure`; the full game state has various attributes such as global continuous data and a set of allied heroes. Each allied hero in turn has a set of abilities, a set of modifiers, etc. We `process each node in the tree according to its data type`. For example for spatial data, we concatenate the data within each cell and then apply a 2 layer conv net. For unordered sets, a common feature of our observations, we use a “Process Set” module. Weights in the Process Set module for processing abilities/items/modifiers are shared across allied and enemy heroes; weights for processing modifiers are shared across allied/enemy/neutral nonheroes. `In addition to the main Game State observation, we extract the the Unit Embeddings` from the “embedding output” of the units’ process sets, for use in the output (see Figure 9). <p align="center"> <img src="/images/684.png"><br/> Figure 8: Preparing for LSTM </p> #### `In order to tell each LSTM which of the team’s heroes it controls, we append the controlled hero’s Unit Embedding` from the Unit Embeddings output of Figure 7 to thse Game State vector. Almost all of the inputs are the same for each of the five replica LSTMs (the only differences are the nearby map, previous action, and a very small fraction of the observations for each unit). In order to allow each replica to respond to the non-identical inputs of other replicas if needed, we add a “cross-hero pool” operation, in which we maxpool the first 25% of the vector across the five replica networks. <p align="center"> <img src="/images/685.png"><br/> Figure 9: The hidden state of the LSTM and unit embeddings are used to parameterize the actions. </p> ### I Human Games ### J TrueSkill: Evaluating a Dota 2 Agent Automatically ### K Dota 2 Gym Environment #### K.1 Data flow between the training environment and Dota 2 #### Dota 2 includes a scripting API designed for building bots. The provided API is exposed through Lua and has methods for `querying the visible state of the game as well as submitting actions for bots to take`. Parts of the map that are out of sight are considered to be in the fog of war and cannot be queried through the scripting API, which prevents us from accidentally “cheating” by observing anything a human player would not be able to see. #### We designed our Dota 2 environment to `behave like a standard OpenAI Gym environment`. This standard respects an API contract where a step method takes action parameters and returns an observation from the next state of the environment. To send actions to Dota 2, we implemented a helper process in Go that we load into Dota 2 through an attached debugger that exposes a gRPC server. `This gRPC server implements methods to configure a game and perform an environment step`. By running the game with an embedded server, we are able to communicate with it over the network from any remote process. #### When the step method is called in the gRPC server, it gets dispatched to the Lua code and then the method blocks until an observation arrives back from Lua to be returned to the caller. In parallel, the Dota 2 engine runs our Lua code on every step, sending the current game state observation to the gRPC server and waiting for it to return the current action. The game blocks until an action is available. These two parallel processes end up meeting in the middle, exchanging actions from gRPC in return for observations from Lua. Go was chosen to make this architecture easy to implement through its channels feature. #### Putting the game environment behind a gRPC server allowed us to `package the game into a Docker image and easily run many isolated game instances per machine`. It also allowed us to easily setup, reset, and use the environment from anywhere where Docker is running. This design choice significantly improved researcher productivity when iterating on and debugging this system. ### L Reaction time #### The Dota 2 game engine runs at 30 steps per second so in theory a bot could submit an action every 33ms. Both to speed up our game execution and in order to bring reactions of our model closer to the human scale we downsample to every 4th frame, which we call `frameskip`. This yields an effective `observation and action rate of 7.5 frames per second`. To allow the model to take precisely timed actions, the action space includes a “delay” which indicates which frame during the frameskip the model wants this action to evaluate on. Thus the model can still take actions at a particular frame if so desired, although in practice we found that the model did not learn to do this and `simply taking the action at the start of the frameskip was better`. #### Moreover, we reduce our computational requirements by `allowing the game and the ML model to run concurrently by asynchronously issuing actions with an action offset`. When the model receives an observation at time T, rather than making the game engine wait for the model to produce an action at time T, we let the game engine carry on running until it produces an observation at time T+1. The game engine then sends the observation at time T+1 to the model, and by this time the model has produced its action choice based on the observation at time T. In this way `the action which the model takes at time T+1 is based upon the observation at time T`. In exchange for this penalty in available “reaction time,” we are able to utilize our compute resources much more efficiently by preventing the two major computations from blocking one another (see Figure 10). #### Taken together, these effects mean that the `agent can react to new information with a reaction time randomly distributed between 5 and 8 frames (167ms to 267ms), depending on when during the frameskip the new information happens to occur`. For comparison, human reaction time has been measured at 250ms in controlled experimental settings. This is likely an underestimate of reaction time during a Dota game. <p align="center"> <img src="/images/686.png"><br/> Figure 10: Reaction Time </p> #### OpenAI Five observes four frames bundled together, so any surprising new information will become available at a random frame in the red region. The model then processes the observation in parallel while the game engine runs forward four more frames. The soonest it can submit an action based on the red observations is marked in yellow. This is between 5 and 8 frames (167-267ms) after the surprising event. ### M Scale and Data Quality Ablation Details #### M.1 Batch Size #### In this section we demonstrate how `large batch-sizes affect optimization time`. #### M.2 Sample Quality — Staleness #### Staleness negatively affects speed of training, and the drop can be quite severe when the staleness is larger than a few versions. For this reason we attempt to `keep staleness as low as possible` in our experiments. #### M.3 Sample Quality — Sampling and Sample Reuse #### We found that `increasing sample reuse causes a significant decrease in performance`. As long as the optimizers are reusing data, adding additional rollout workers appears to be a relatively cheap way to accelerate training. CPUs are often easier and cheaper to scale up than GPUs and this can be a significant performance boost in some setups. #### The fact that our algorithms benefit from extremely low sample reuse underlines how `sample inefficient` they are. Ideally, our training methods could take a small amount of experience and use that to learn a great deal, but currently we cannot even usefully optimize over that experience for more than a couple of gradient steps. Learning to use rollout data more efficiently is one of the major areas for future work in RL research. ### N Self-play #### OpenAI Five is trained without any human gameplay data through a self-improvement process named self-play. This technique was successfully used in prior work to obtain super human performance in a variety of multiplayer games. In self-play training, we `continually pit the current best version of an agent against itself or older versions, and optimize for new strategies that can defeat these past and present opponents`. #### In training OpenAI Five `80% of the games are played against the latest set of parameters, and 20% play against past versions`. We play occasionally against past parameter versions in order to `obtain more robust strategies and avoid strategy collapse` in which the agent forgets how to play against a wide variety of opponents because it only requires a narrow set of strategies to defeat its immediate past version. #### OpenAI Five uses a `dynamic sampling system` in which each past opponent i = 1..N is given a quality score qi. Opponent agents are sampled according to a softmax distribution; agent i is chosen with probability pi proportional to e^qi. Every 10 iterations we add the current agent to past opponent pool and initialize its quality score to the maximum of the existing qualities. After each rollout game is completed, if the past opponent defeats the current agent, no update is applied. If the current agent defeats a past opponent, an update is applied proportional to a learning rate constant η (which we fix at 0.01): <p align="center"> <img src="/images/687.png"><br/> </p> #### We see the opponent distribution at several points in early training. The spread of the distribution gives a good picture of how quickly the agent is improving: `when the agent is improving rapidly, then older opponents are worthless to play against and have very low scores`; when progress is slower the agent plays against a wide variety of past opponents. ### O Exploration #### Exploration is a well-known and well-researched problem in the context of RL. We `encourage exploration in two different ways`: by shaping the loss (entropy and team spirit) and by randomizing the training environment. #### O.1 Loss function #### We use entropy bonus to encourage exploration. This bonus is added to the PPO loss function in the form of cS[πθ](st), where c is a hyperparameter referred to as entropy coefficient. In initial stages of training a long-running experiment like OpenAI Five or Rerun we set it to an initial value and lower it during training. We find that using `entropy bonus prevents premature convergence to suboptimal policy`. We see that entropy bonus of 0.01 (our default) performs best. We also find that setting it to 0 in early training, while not optimal, does not completely prevent learning. We introduced a hyperparameter `team spirit to control whether agents optimize for their individual reward or the shared reward of the team`. From the early training and speedup curves for team spirit, we see evidence that early in training, lower team spirits do better. At the very start team spirit 0 is the best, quickly overtaken by team spirit 0.3 and 0.5. We hypothesize that later in training team spirit 1.0 will be best, as it is optimizing the actual reward signal of interest. #### O.2 Environment Randomization #### We further encouraged exploration through randomization of the environment, with `three simultaneous goals`: 1. #### If a long and very specific series of actions is necessary to be taken by the agent in order to randomly stumble on a reward, and any deviation from that sequence will result in negative advantage, then the longer this series, the less likely is agent to explore this skill thoroughly and learn to use it when necessary. 2. #### If an environment is highly repetitive(重复的), then the agent is more likely to find and stay in a local minimum. 3. #### In order to be robust to various strategies humans employ, our agents must have encountered a wide variety of situations in training. This parallels the success of domain randomization in transferring policies from simulation to real-world robotics. #### We randomize many parts of the environment: - #### Initial State(初始属性) - #### Lane Assignments(兵线分配) - #### Roshan Health(肉山血量) - #### Hero Lineup(英雄阵容) - #### Item Selection(物品选择) ### P Hero Pool Size #### We see that training with more heroes causes only a modest slowdown. Training with 80 heroes has a speedup factor of approximately 0.8, meaning early training runs 20% slower than with the base 17 heroes. From this we hypothesize that an agent trained on the larger set of heroes using the full resources of compute of Rerun would `attain a similar high level of skill with approximately 20% more training time`. ### Q Bloopers #### Q.1 Manually Tuned Hyperparameters #### We ultimately believe that human intuition, especially under time pressure, is not the best way to set hyperparameters. #### Q.2 Zero Team Spirit Embedding #### Q.3 Learning path dependency
C++
UTF-8
2,637
3.4375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; template<typename T> vector<T> cross_product(const vector<T>& A, const vector<T>& B) { vector <T> C(3); C[0] = A[1]*B[2]-A[2]*B[1]; C[1] = -A[0]*B[2]+A[2]*B[0]; C[2] = A[0]*B[1]-A[1]*B[0]; return C; } template<typename T> T dot_product(const vector<T>& A, const vector<T>& B) { int n = B.size(); T sum = 0; for(int i=0;i<n;i++) { sum += A[i]*B[i]; } return sum; } template<typename T> void printvec(vector<T>& A) { cout<<A[0]<<'\n'<<A[1]<<'\n'<<A[2]<<endl; } template<typename T> void printmat(vector<vector<T>>& M) { int n = M.size(); int m = M[0].size(); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(j==n-1){cout<<M[i][j]<<'\n';} else{cout<<M[i][j]<<'\t';} } } } template<typename T> vector<T> matvec(vector<vector<T>>M, vector<T>V) { int n = V.size(); vector<T> P(n); for(int i=0; i<n; i++) { P[i] = dot_product<T>(M[i], V); } return P; } //return y = a*x template<typename T> void ax(T a, vector<T>& x) { int n = x.size(); vector<T> y(n); for(int i=0;i<n;i++) { y[i] = a * x[i]; } } //return y = a*x + y template<typename T> void axpy(T a, vector<T>& x, vector<T>& y) { int n = x.size(); for(int i=0;i<n;i++) { y[i] += y[i] + a*x[i]; } } //return y = M*x + y template<typename T> void mxpy(vector<vector<T>>& M, vector<T>& x, vector<T>& y) { int n = x.size(); for(int i=0;i<n;i++) { axpy(x[i], M[i], y); } } //return C = A*B + C, where A(m*k), B(k*n), C(m*n) template<typename T> void gemm(vector<vector<T>>& A, vector<vector<T>>& B, vector<vector<T>>& C) { int n = C.size(); for(int i=0;i<n;i++) { mxpy(A, B[i], C[i]); } } int main(void) { vector<float> A({1,2,3}); vector<float> B({4,5,6}); vector<float> D({1,2,3}); // cout<<A[0]<<endl; // print_vector<float>(A); // vector<float> C(3); // C = cross_product<float>(A, B); // print_vector<float>(C); // print_vector<float>(D); // cout<<dot_product(A,B)<<endl; vector<vector<float>> M({{1,2,3},{4,5,6},{7,8,9}}); vector<vector<float>> N({{1,2,3},{4,5,6},{7,8,9}}); vector<vector<float>> C({{0,0,0},{0,0,0},{0,0,0}}); gemm(M, N, C); printmat(C); // print_vector<float>(M[0]); // vector<float> P(3); // P = matvec<float>(M, A); // print_vector<float>(P); // float sum = dot_product<float> (M[0],A); // cout<<sum<<endl; // cout<<M.size()<<endl; return 0; }
Java
UTF-8
4,959
2.484375
2
[]
no_license
package authorize; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; /** * This is a single page utility class, that * @author root * */ public class Authorize { public static final String PRODUCTION_URL = "https://secure.authorize.net/gateway/transact.dll"; public static final String SANDBOX_URL = "https://test.authorize.net/gateway/transact.dll"; public static Map<String, String> process(String url, Map<String, String> parameters) throws Exception { String paramArray[] = new String[parameters.size() * 2]; int index = 0; for (String key : parameters.keySet()) { paramArray[index++] = key; paramArray[index++] = parameters.get(key); } String result = post(url, paramArray); String values[] = result.split("[|]"); Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < Math.min(RESPONSE.length, values.length); i++) { map.put(RESPONSE[i], values[i]); } return map; } public static String mapToString(Map<String, String> map) { String result = null; for (String key : map.keySet()) { String value = map.get(key); if (value != null && !value.trim().equals("")) { if (result == null) { result = key + "=" + value; } else { result += "\n" + key + "=" + value; } } } return result; } public static Map<String, String> map(Map base, String... kvs) { Map<String, String> result = new HashMap<String, String>(); result.putAll(base); result.putAll(map(kvs)); return result; } public static Map<String, String> map(String... kvs) { Map<String, String> result = new HashMap<String, String>(); String key = null; String value = null; for (String obj : kvs) { if (key == null) { key = obj; } else { value = obj; result.put(key, value); key = null; value = null; } } return result; } private static String post(final String url, String... args) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String request = null; boolean key = true; for (String string : args) { if (key) { if (request != null) { request += "&" + URLEncoder.encode(string, "UTF-8"); } else { request = URLEncoder.encode(string, "UTF-8"); } key = false; } else { request = request + "=" + URLEncoder.encode(string, "UTF-8"); key = true; } } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(request); wr.flush(); wr.close(); InputStream in = connection.getInputStream(); String result = streamToString(in); connection.disconnect(); return result; } private static String streamToString(InputStream in) throws UnsupportedEncodingException, IOException { Charset charset = Charset.forName("UTF8"); InputStreamReader stream = new InputStreamReader(in, charset); BufferedReader reader = new BufferedReader(stream); StringBuffer buffer = null; String read = ""; while ((read = reader.readLine()) != null) { if (buffer == null) { buffer = new StringBuffer(read); } else { buffer.append("\n").append(read); } } reader.close(); if (buffer == null) return ""; return buffer.toString(); } private static final String RESPONSE[] = { "Response Code", "Response Subcode", "Response Reason Code", "Response Reason Text", "Authorization Code", "AVS Response", "Transaction ID", "Invoice Number", "Description", "Amount", "Method", "Transaction Type", "Customer ID", "First Name", "Last Name", "Company", "Address", "City", "State", "ZIP Code", "Country", "Phone", "Fax", "Email Address", "Ship To First Name", "Ship To Last Name", "Ship To Company", "Ship To Address", "Ship To City", "Ship To State", "Ship To ZIP Code", "Ship To Country", "Tax", "Duty", "Freight", "Tax Exempt", "Purchase Order Number", "MD5 Hash", "Card Code Response", "Cardholder Authentication Verification Response", //40 "", "", "", "", "", "", "", "", "", "", "Account Number", //51 "Card Type", "Split Tender ID", "Requested Amount", "Balance On Card" }; }
C++
UTF-8
1,035
2.984375
3
[ "MIT" ]
permissive
#include "VoxelObject.h" namespace Beans { VoxelObject::VoxelObject(GameObject * owner) : Component(owner), blocks(nullptr), blockSize(1.0f) { } VoxelObject::~VoxelObject() { if (blocks != nullptr) { delete blocks; } } void VoxelObject::SetupObject(unsigned short x, unsigned short y, unsigned short z) { if (blocks != nullptr) { delete blocks; } xSize = x; ySize = y; zSize = z; blocks = new Volume<unsigned short>(x, y, z); } void VoxelObject::DrawObject() { //Add all blocks to the draw queue for (int x = 0; x < xSize; ++x) { for (int y = 0; y < ySize; ++y) { for (int z = 0; z < zSize; ++z) { //TODO add to this condition later to cull blocks that are not visible if (blocks->At(x, y, z) != 0) { positions.push_back(vec3(x, y, z)); materials.push_back(blocks->At(x, y, z)); } } } } //Instanced draw the cube mesh } }
JavaScript
UTF-8
10,177
3.4375
3
[ "MIT" ]
permissive
/** * Finds and remove a given item from a given list. * Does nothing if the item is not in the list. * @param {any[]} array - The array to remove from * @param {*} item The item to be removed */ const removeFromArray = (array, item) => { return array.filter(elt => { return elt !== item }) } /** * Computes the euclidian distance between the two given points. * @param {Point} a - A point with x,y coordinates * @param {Point} b - A point with x,y coordinates * @returns The euclidian distance between the two given points */ const distance = (a, b) => { return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2)) } /** * Orders the points according to the path drawn on the canvas. * @param {Table} data - A p5 table containing points * @returns The oredered data */ // eslint-disable-next-line no-unused-vars const sortDataFromManualPathArray = (data) => { const orderedPoints = [] const newData = [] let error = false // make copy of data for (let i = 0; i < data.getRowCount(); i++) { newData.push({ x: data.getNum(i, 'x'), y: data.getNum(i, 'y') }) } // Map every manual path with the corresponding points of the data let orderedPointsFromPaths = [] // eslint-disable-next-line no-undef manualPath.forEach(path => { orderedPointsFromPaths.push(sortDataFromManualPath(newData, path, false, 7)) if (orderedPointsFromPaths[orderedPointsFromPaths.length - 1].length === 0) error = true }) // Prepare to erase path if overridden const toErase = [] for (let i = 0; i < orderedPointsFromPaths.length; i++) { for (let j = i + 1; j < orderedPointsFromPaths.length; j++) { for (let k = 0; k < orderedPointsFromPaths[j].length; k++) { if (orderedPointsFromPaths[i].includes(orderedPointsFromPaths[j][k]) || orderedPointsFromPaths[i].length === 0) { if (!toErase.includes(i)) toErase.push(i) break } } } } // Erase those paths toErase.forEach((index) => { orderedPointsFromPaths = removeFromArray(orderedPointsFromPaths, orderedPointsFromPaths[index]) // eslint-disable-next-line no-undef manualPath = removeFromArray(manualPath, manualPath[index]) }) if (error) return data // Order all sections of points let remainingPoints = newData const sections = [] let last = orderedPointsFromPaths[0][0] for (let i = 0; i < orderedPointsFromPaths.length; i++) { console.log('begin') const pseudoOrderedPoints = sortPointsInOrder(remainingPoints, last) let currentIndex = -1 let newSection = [] // Get the index of the closest path from the last point in the sections // And prepare the section between two manual paths for (let j = 0; j < pseudoOrderedPoints.length; j++) { for (let k = 0; k < orderedPointsFromPaths.length; k++) { if (pseudoOrderedPoints[j] === orderedPointsFromPaths[k][0]) { currentIndex = k break } } if (currentIndex !== -1) break newSection.push(pseudoOrderedPoints[j]) } if (currentIndex === -1) return data orderedPointsFromPaths.forEach(path => { path.forEach(point => { if (!newSection.includes(point)) return newSection = removeFromArray(newSection, point) }) }) // Append the new sections if (newSection.length > 0) sections.push(newSection) sections.push(orderedPointsFromPaths[currentIndex]) // Remove points which are already in one of the sections orderedPointsFromPaths[currentIndex].forEach((elt) => { remainingPoints = removeFromArray(remainingPoints, elt) }) newSection.forEach((elt) => { remainingPoints = removeFromArray(remainingPoints, elt) }) last = nearestPoint(orderedPointsFromPaths[currentIndex][orderedPointsFromPaths[currentIndex].length - 1], remainingPoints) } // Join the sections for (let i = 0; i < sections.length; i++) { orderedPoints.push(...sections[i]) } // Push the remaining points // eslint-disable-next-line no-unused-vars const endOrderedPoints = sortPointsInOrder(remainingPoints, last) orderedPoints.push(...remainingPoints) data.clearRows() for (let i = 0; i < orderedPoints.length; i++) { const newRow = data.addRow() newRow.setNum('x', orderedPoints[i].x) newRow.setNum('y', orderedPoints[i].y) } return data } /** * Finds the path from a manual input on the canvas. * @param {Table} data - A p5 table containing points * @param {Point[]} path - Path drawn by the user * @param {Boolean} end - * @param {Number} radius - The allowed radius around the manual path * @return {Table | Point[]} The ordered points */ const sortDataFromManualPath = (data, path, end, radius) => { const orderedPoints = [] const newData = [] if (data.getRowCount !== undefined) { for (let i = 0; i < data.getRowCount(); i++) { newData.push({ x: data.getNum(i, 'x'), y: data.getNum(i, 'y') }) } } else newData.push(...data) if (radius === undefined) radius = Infinity const unused = [] const pairs = [] // Map each point of data with the closest point of manual path for (let i = 0; i < newData.length; i++) { let minDist = Infinity let point = { x: 0, y: 0 } let currentDist = 0 // Order local points for (let j = 0; j < path.length; j++) { currentDist = distance(newData[i], path[j]) if (currentDist < minDist && currentDist < radius) { minDist = currentDist point = path[j] } } if (minDist !== Infinity) { pairs.push({ data: newData[i], path: point }) } else { unused.push(newData[i]) } } // Order locals points in localOrder for (let i = 0; i < path.length; i++) { const localOrder = [] for (let j = 0; j < pairs.length; j++) { if (pairs[j].path === path[i]) { localOrder.push(pairs[j]) } } // Sort points in localorder by distance localOrder.sort((a, b) => { if (distance(a.data, a.path) < distance(b.data, b.path)) { return -1 } else return 1 }) // And push the local order for (let j = 0; j < localOrder.length; j++) { orderedPoints.push(localOrder[j].data) } } if (end === true) { const endOrderedPoints = sortPointsInOrder(unused, nearestPoint(orderedPoints[orderedPoints.length - 1], unused)) orderedPoints.push(...endOrderedPoints) } if (data.getRowCount !== undefined) { data.clearRows() for (let i = 0; i < orderedPoints.length; i++) { const newRow = data.addRow() newRow.setNum('x', orderedPoints[i].x) newRow.setNum('y', orderedPoints[i].y) } return data } else return orderedPoints } /** * Finds the nearest point from a given point in a table. * @param {Point} point - The reference point * @param {Point[]} pointsTable - Array containing all points * @return {Point} The nearest point */ const nearestPoint = (point, pointsTable) => { if (pointsTable === undefined || pointsTable.length === 0) return let currentDist = 0 let minDist = Infinity let nearest = { x: 0, y: 0 } for (let i = 0; i < pointsTable.length; i++) { currentDist = distance(point, pointsTable[i]) if (currentDist < minDist) { minDist = currentDist nearest = pointsTable[i] } } return nearest } /** * Gets the total distance of a given closed path. * @param {Point[]} path - The closed path * @return {[type]} The total distance */ // eslint-disable-next-line no-unused-vars const getPathDistance = (path) => { let dist = distance(path[0], path[path.length - 1]) let lastPoint path.forEach((point) => { if (lastPoint === undefined) { lastPoint = point return } dist += distance(lastPoint, point) lastPoint = point }) return dist } /** * Sort points in a dataset so that each point is the nearest from its neighbour. * @param {Point[]} data - Points table * @param {Point} first - Defined start for the sort * @return {Point[]} The ordered points */ const sortPointsInOrder = (data, first) => { const newData = [] if (data.getRowCount !== undefined) { for (let i = 0; i < data.getRowCount(); i++) { newData.push({ x: data.getNum(i, 'x'), y: data.getNum(i, 'y') }) } } else newData.push(...data) if (first === undefined) first = newData[newData.length - 1] const outlineCanvas = document.getElementById('outlineCanvas') let orderedPoints = [] let remainingPoints = newData let lastNearest = first for (let i = 0; i < newData.length; i++) { orderedPoints.push(lastNearest) remainingPoints = removeFromArray(remainingPoints, lastNearest) lastNearest = nearestPoint(lastNearest, remainingPoints) if (lastNearest === undefined) { break } } const meshedOrderedPoints = [] // eslint-disable-next-line no-undef if (!aftermeshed) { const aftermeshSel = document.getElementById('aftermesh') for (let i = 0; i < orderedPoints.length; i++) { // AFTERMESH : drop points after sorting the dataset if (i % aftermeshSel.value) { orderedPoints[i] = undefined } } // eslint-disable-next-line no-undef aftermeshed = true for (let i = 0; i < orderedPoints.length; i++) { if (orderedPoints[i] !== undefined) { orderedPoints[i].x = orderedPoints[i].x - outlineCanvas.width / 2 orderedPoints[i].y = orderedPoints[i].y - outlineCanvas.height / 2 meshedOrderedPoints.push(orderedPoints[i]) } } orderedPoints = meshedOrderedPoints if (orderedPoints.length % 2 === 0 && orderedPoints.length) { orderedPoints.length = orderedPoints.length - 1 } } if (data.getRowCount !== undefined) { data.clearRows() for (let i = 0; i < orderedPoints.length; i++) { if (orderedPoints[i] === undefined) continue const newRow = data.addRow() newRow.setNum('x', orderedPoints[i].x) newRow.setNum('y', orderedPoints[i].y) } return data } else return orderedPoints }
Markdown
UTF-8
2,926
2.875
3
[]
no_license
--- description: "Steps to Prepare Award-winning Balsamic Salmon" title: "Steps to Prepare Award-winning Balsamic Salmon" slug: 151-steps-to-prepare-award-winning-balsamic-salmon date: 2020-09-13T14:18:44.560Z image: https://img-global.cpcdn.com/recipes/5947616958873600/751x532cq70/balsamic-salmon-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/5947616958873600/751x532cq70/balsamic-salmon-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/5947616958873600/751x532cq70/balsamic-salmon-recipe-main-photo.jpg author: Dora Harper ratingvalue: 3.5 reviewcount: 10 recipeingredient: - " Salmon Filet" - " Balsamic Vinegar" - " Olive Oil" - " Garlic" - " Honey" - " Dijon Mustard" recipeinstructions: - "Preheat oven to 400°F." - "Brown garlic in olive oil." - "Then add balsamic vinegar." - "Then add honey and mustard." - "Brush glaze over the salmon." - "Bake for 5 minutes." - "Take it out and add more glaze then bake for another 10 minutes." - "Garnish with parsley and serve." categories: - Recipe tags: - balsamic - salmon katakunci: balsamic salmon nutrition: 199 calories recipecuisine: American preptime: "PT22M" cooktime: "PT32M" recipeyield: "3" recipecategory: Dessert --- ![Balsamic Salmon](https://img-global.cpcdn.com/recipes/5947616958873600/751x532cq70/balsamic-salmon-recipe-main-photo.jpg) Hey everyone, I hope you are having an amazing day today. Today, I will show you a way to prepare a special dish, balsamic salmon. One of my favorites. This time, I will make it a little bit unique. This will be really delicious. Balsamic Salmon is one of the most popular of current trending meals on earth. It is enjoyed by millions daily. It is simple, it is fast, it tastes yummy. They are fine and they look wonderful. Balsamic Salmon is something which I have loved my entire life. To begin with this recipe, we must prepare a few ingredients. You can cook balsamic salmon using 6 ingredients and 8 steps. Here is how you cook it. <!--inarticleads1--> ##### The ingredients needed to make Balsamic Salmon: 1. Make ready Salmon Filet 1. Prepare Balsamic Vinegar 1. Prepare Olive Oil 1. Make ready Garlic 1. Make ready Honey 1. Take Dijon Mustard <!--inarticleads2--> ##### Instructions to make Balsamic Salmon: 1. Preheat oven to 400°F. 1. Brown garlic in olive oil. 1. Then add balsamic vinegar. 1. Then add honey and mustard. 1. Brush glaze over the salmon. 1. Bake for 5 minutes. 1. Take it out and add more glaze then bake for another 10 minutes. 1. Garnish with parsley and serve. So that's going to wrap it up for this exceptional food balsamic salmon recipe. Thank you very much for your time. I'm confident you can make this at home. There is gonna be interesting food at home recipes coming up. Remember to save this page in your browser, and share it to your loved ones, friends and colleague. Thanks again for reading. Go on get cooking!
Shell
UTF-8
992
2.546875
3
[]
no_license
#!/usr/bin/env bash # 拉镜像 ImageName="registry.baidubce.com/paddlepaddle/paddle:2.1.2-gpu-cuda10.2-cudnn7"; docker pull ${ImageName} # 启动镜像后测试单个模型 run_cmd=" cd /workspace/models/gluon-cv/; cp /workspace/scripts/*.sh ./; cp /workspace/scripts/analysis_log.py ./; bash PrepareEnv.sh; bash PrepareData.sh; CUDA_VISIBLE_DEVICES=0 bash run_benchmark.sh sp 64 fp32 500 mobilenet1.0; CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash run_benchmark.sh mp 64 fp32 500 mobilenet1.0; CUDA_VISIBLE_DEVICES=0 bash run_benchmark.sh sp 768 fp32 500 mobilenet1.0; CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash run_benchmark.sh mp 768 fp32 500 mobilenet1.0; mv clas* /workspace/; " # 启动镜像 nvidia-docker run --name test_mxnet -it \ --net=host \ --shm-size=64g \ -v $PWD:/workspace \ ${ImageName} /bin/bash -c "${run_cmd}" nvidia-docker stop test_mxnet nvidia-docker rm test_mxnet
Java
UTF-8
537
2.6875
3
[]
no_license
package com.example.springgeek.lambda; import com.example.springgeek.lambda.bean.Student; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author MR.Wang * @dept * @description TODO * @date 2020/4/12 22:37 **/ public class TestCase { public static void main(String[] args) { List<Student> studentList = Stream.of(new Student("路飞",22,175), new Student("红发",40,180)).collect(Collectors.toList()); System.out.println(studentList); } }
C
UTF-8
1,430
2.6875
3
[]
no_license
#include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, char *argv[]) { int sockfd = 0; int n, index = 0; struct sockaddr_in serv_addr, remaddr; socklen_t addrlen = sizeof(remaddr); char* read_buf; char* send_buf; char* temp_buf; struct timespec t1, t2; double elaspedtime; int buffer_size = atoi(argv[1]); read_buf = (char *)calloc(buffer_size, sizeof(char)); send_buf = (char *)calloc(buffer_size, sizeof(char)); srand(time(NULL)); sockfd = socket(AF_INET, SOCK_DGRAM, 0); memset(&serv_addr, '\0', sizeof(serv_addr)); temp_buf = send_buf; for (n = 0; n < buffer_size - 1; n++) { *temp_buf = 'A' + (random() % 26); temp_buf++; } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(55555); bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); while(1) { int count = 0; int n = 0; while ((n = recvfrom(sockfd, read_buf, buffer_size, 0, (struct sockaddr *)&remaddr, &addrlen)) >= 0) { if (n == (buffer_size)) { sendto(sockfd, send_buf, buffer_size, 0, (struct sockaddr *)&remaddr, sizeof(remaddr)); } } } close(sockfd); return 0; }
Java
UTF-8
388
2.046875
2
[]
no_license
package com.woods.www.scheduletask.quartz; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.util.Date; /** * @author: woods * @date: 2019/12/7 * @description: */ @Component @Slf4j public class SimpleJob { public void sayHello(){ log.info("simple job>>>{}, Thread>>>{}", new Date(), Thread.currentThread().getId()); } }
Python
UTF-8
1,056
4.65625
5
[]
no_license
#Desafio 12 from time import sleep #Decorações def linha1(x): print("\033[1;34m<\033[m"*len(x)) print(f"\033[1;32m{x}\033[m") print("\033[1;34m>\033[m"*len(x)) return x #Chamadas e título linha1("Mestre da matemática") lista1= [] lista2= [] soma= [] #Comandos principais for i in range(1,11): x=int(input(f"Digite o valor {i}: [Deve ser inteiro/\033[32mlista 1\033[m] ")) lista1.append(x) for c in range(1,11): y=int(input(f"Digite o valor {c}: [Deve ser inteiro/\033[34mlista 2\033[m] ")) lista2.append(y) #Operação de soma def somar(l1,l2): pos0=0 pos1=0 while (pos0 < len(l1)): soma.append(l1[pos0]+l2[pos1]) pos0+=1 pos1+=1 return soma #Exibição dos resultados somar(lista1,lista2) print("\033[34mA soma de:\033[m") sleep(1) for a in lista1: print(a, end=' ') print("\033[34m\ncom:\033[m") sleep(1) for b in lista2: print(b,end=' ') print("\033[34m\ndeu:\033[m") sleep(1) for c in soma: print(c, end=' ')
JavaScript
UTF-8
2,091
4.09375
4
[]
no_license
// PALINDROME function isPalindromeEfficient(str) { for (var i = 0, j = str.length - 1; i < j; ++i, --j) { if (str[i] !== str[j]) { return false; } } return true; } //OR function isPalindromeInefficient(str) { return str.split(' ').reverse().join('') ===str; } console.log(isPalindromeEfficient('hannah')); console.log(isPalindromeEfficient('boooo')); //OR function reverseString(str){ return str.split("").reverse().join(""); } function isPalindrome(str) { return str == reverseString(str); } alert(isPalindrome("hannah")); */ // AVERAGE function averageA(arr) { var total = 0; for (var i = 0; i < arr.length; ++i) { arr[i] += total; } return total / arr.length; } //OR function mathAverage() { var count = arguments.length; var total = i++; while (i < count;) total += arguments [i++]; return total / count; } mathAverage(5, 6, 7); // MAKE USER function makeUser(name) { var firstAndLast = name.split(' '); return { firstName: firstAndLast[0], lastName: firstAndLast[1] }; } console.log(makeUser('Joe Shmo')); //// USERIFY function userify(names) { var result = []; for (var i = 0; i < names.length; ++i) { result.push(makeUser(names[i])); } return result; } function userifyP(names) { return names.map(makeUser); } // CSV SUMMATION // use ParseInt function summation(str) { } // FACTORIAL function factorialA (n) { var result = n; while n > 1) { --n; result *= n ; } return result; } // OR This uses a technique known as recursion // (stack of functions) function factorialB(n) { if (n < 2) return 1; return n * factorialB(n - 1); } console.log(factorialB(5)); // returns 120 console.log(factorialA(8)); // return 40320 // LONGEST WORD function longestWord(string) { var str = string.split(" ").sort(function(a,b)(return b.length-a.length;}); console.log(words); console.log(words[0]); } longestWord(); OR function longestWord(st) { var word = ""; splitString = str.split(' '); for (var i = 0; i < splitString.length) }
Python
UTF-8
18,645
2.828125
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ Lower-level and simpler NSID-specific HDF5 utilities that facilitate higher-level data operations Created on Tue Aug 3 21:14:25 2020 @author: Gerd Duscher, and Suhas Somnath """ from __future__ import division, print_function, absolute_import, unicode_literals import sys import h5py import numpy as np import dask.array as da from sidpy.base.num_utils import contains_integers from sidpy.hdf.hdf_utils import get_attr, copy_dataset from sidpy.hdf import hdf_utils as hut from sidpy import Dimension if sys.version_info.major == 3: unicode = str def get_all_main(parent, verbose=False): """ Simple function to recursively print the contents of an hdf5 group Parameters ---------- parent : :class:`h5py.Group` HDF5 Group to search within verbose : bool, optional. Default = False If true, extra print statements (usually for debugging) are enabled Returns ------- main_list : list of h5py.Dataset The datasets found in the file that meet the 'Main Data' criteria. """ if not isinstance(parent, (h5py.Group, h5py.File)): raise TypeError('parent should be a h5py.File or h5py.Group object') main_list = list() def __check(name, obj): if verbose: print(name, obj) if isinstance(obj, h5py.Dataset): if verbose: print(name, 'is an HDF5 Dataset.') ismain = check_if_main(obj) if ismain: if verbose: print(name, 'is a `Main` dataset.') main_list.append(obj) if verbose: print('Checking the group {} for `Main` datasets.'.format(parent.name)) parent.visititems(__check) return main_list def find_dataset(h5_group, dset_name): """ Uses visit() to find all datasets with the desired name Parameters ---------- h5_group : :class:`h5py.Group` Group to search within for the Dataset dset_name : str Name of the dataset to search for Returns ------- datasets : list List of [Name, object] pairs corresponding to datasets that match `ds_name`. """ # print 'Finding all instances of', ds_name datasets = [] for obj in hut.find_dataset(h5_group, dset_name): datasets.append(obj) return datasets def validate_main_dset(h5_main, must_be_h5): """ Checks to make sure that the provided object is a NSID main dataset Errors in parameters will result in Exceptions Parameters ---------- h5_main : h5py.Dataset or numpy.ndarray or Dask.array.core.array object that represents the NSID main data must_be_h5 : bool Set to True if the expecting an h5py.Dataset object. Set to False if expecting a numpy.ndarray or Dask.array.core.array Returns ------- """ # Check that h5_main is a dataset if must_be_h5: if not isinstance(h5_main, h5py.Dataset): raise TypeError('{} is not an HDF5 Dataset object.'.format(h5_main)) else: if not isinstance(h5_main, (np.ndarray, da.core.Array)): raise TypeError('raw_data should either be a np.ndarray or a ' 'da.core.Array') # Check dimensionality if len(h5_main.shape) != len(h5_main.dims): raise ValueError('Main data does not have full set of dimensional ' 'scales. Provided object has shape: {} but only {} ' 'dimensional scales' ''.format(h5_main.shape, len(h5_main.dims))) def validate_anc_h5_dsets(h5_inds, h5_vals, main_shape, is_spectroscopic=True): """ Checks ancillary HDF5 datasets against shape of a main dataset. Errors in parameters will result in Exceptions Parameters ---------- h5_inds : h5py.Dataset HDF5 dataset corresponding to the ancillary Indices dataset h5_vals : h5py.Dataset HDF5 dataset corresponding to the ancillary Values dataset main_shape : array-like Shape of the main dataset expressed as a tuple or similar is_spectroscopic : bool, Optional. Default = True set to True if ``dims`` correspond to Spectroscopic Dimensions. False otherwise. """ if not isinstance(h5_inds, h5py.Dataset): raise TypeError('h5_inds must be a h5py.Dataset object') if not isinstance(h5_vals, h5py.Dataset): raise TypeError('h5_vals must be a h5py.Dataset object') if h5_inds.shape != h5_vals.shape: raise ValueError('h5_inds: {} and h5_vals: {} should be of the same ' 'shape'.format(h5_inds.shape, h5_vals.shape)) if isinstance(main_shape, (list, tuple)): if not contains_integers(main_shape, min_val=1) or \ len(main_shape) != 2: raise ValueError("'main_shape' must be a valid HDF5 dataset shape") else: raise TypeError('main_shape should be of the following types:' 'h5py.Dataset, tuple, or list. {} provided' ''.format(type(main_shape))) if h5_inds.shape[is_spectroscopic] != main_shape[is_spectroscopic]: raise ValueError('index {} in shape of h5_inds: {} and main_data: {} ' 'should be equal'.format(int(is_spectroscopic), h5_inds.shape, main_shape)) def validate_dims_against_main(main_shape, dims, is_spectroscopic=True): """ Checks Dimension objects against a given shape for main datasets. Errors in parameters will result in Exceptions Parameters ---------- main_shape : array-like Tuple or list with the shape of the main data dims : iterable List of Dimension objects is_spectroscopic : bool, Optional. Default = True set to True if ``dims`` correspond to Spectroscopic Dimensions. False otherwise. """ if not isinstance(main_shape, (list, tuple)): raise TypeError('main_shape should be a list or tuple. Provided object' ' was of type: {}'.format(type(main_shape))) if len(main_shape) != 2: raise ValueError('"main_shape" should be of length 2') contains_integers(main_shape, min_val=1) if isinstance(dims, Dimension): dims = [dims] elif not isinstance(dims, (list, tuple)): raise TypeError('"dims" must be a list or tuple of nsid.Dimension ' 'objects. Provided object was of type: {}' ''.format(type(dims))) if not all([isinstance(obj, Dimension) for obj in dims]): raise TypeError('One or more objects in "dims" was not nsid.Dimension') if is_spectroscopic: main_dim = 1 dim_category = 'Spectroscopic' else: main_dim = 0 dim_category = 'Position' # TODO: This is where the dimension type will need to be taken into account lhs = main_shape[main_dim] rhs = np.product([len(x.values) for x in dims]) if lhs != rhs: raise ValueError(dim_category + ' dimensions in main data of size: {} do not match ' 'with product of values in provided Dimension objects' ': {}'.format(lhs, rhs)) def check_if_main(h5_main, verbose=False): """ Checks the input dataset to see if it has all the necessary features to be considered a Main dataset. This means it is dataset has dimensions of correct size and has the following attributes: * quantity * units * main_data_name * data_type * modality * source In addition, the shapes of the ancillary matrices should match with that of h5_main Parameters ---------- h5_main : HDF5 Dataset Dataset of interest verbose : Boolean (Optional. Default = False) Whether or not to print statements Returns ------- success : Boolean True if all tests pass """ try: validate_main_dset(h5_main, True) except Exception as exep: if verbose: print(exep) return False # h5_name = h5_main.name.split('/')[-1] h5_group = h5_main.parent # success = True # Check for Datasets attrs_names = ['dimension_type', 'name', 'nsid_version', 'quantity', 'units', ] attr_success = [] length_success = [] dset_success = [] # Check for Validity of Dimensional Scales for i, dimension in enumerate(h5_main.dims): # check for all required attributes h5_dim_dset = h5_group[dimension.label] attr_success.append(np.all([att in h5_dim_dset.attrs for att in attrs_names])) dset_success.append(np.all([attr_success, isinstance(h5_dim_dset, h5py.Dataset)])) # dimensional scale has to be 1D if len(h5_dim_dset.shape) == 1: # and of the same length as the shape of the dataset length_success.append(h5_main.shape[i] == h5_dim_dset.shape[0]) else: length_success.append(False) # We have the list now and can get error messages according to which dataset is bad or not. if np.all([np.all(attr_success), np.all(length_success), np.all(dset_success)]): if verbose: print('Dimensions: All Attributes: ', np.all(attr_success)) print('Dimensions: All Correct Length: ', np.all(length_success)) print('Dimensions: All h5 Datasets: ', np.all(dset_success)) else: print('length of dimension scale {length_success.index(False)} is wrong') print('attributes in dimension scale {attr_success.index(False)} are wrong') print('dimension scale {dset_success.index(False)} is not a dataset') return False # Check for all required attributes in dataset main_attrs_names = ['quantity', 'units', 'main_data_name', 'data_type', 'modality', 'source'] main_attr_success = np.all([att in h5_main.attrs for att in main_attrs_names]) if verbose: print('All Attributes in dataset: ', main_attr_success) if not main_attr_success: if verbose: print('{} does not have the mandatory attributes'.format(h5_main.name)) return False for attr_name in main_attrs_names: val = get_attr(h5_main, attr_name) if not isinstance(val, (str, unicode)): if verbose: print('Attribute {} of {} found to be {}. Expected a string'.format(attr_name, h5_main.name, val)) return False return main_attr_success def link_as_main(h5_main, dim_dict): """ Attaches datasets as h5 Dimensional Scales to `h5_main` Parameters ---------- h5_main : h5py.Dataset N-dimensional Dataset which will have the references added as h5 Dimensional Scales dim_dict: dictionary with dimensional order as key and items are datasets to be used as h5 Dimensional Scales Returns ------- pyNSID.NSIDataset NSIDataset version of h5_main now that it is a NSID Main dataset """ if not isinstance(h5_main, h5py.Dataset): raise TypeError('h5_main should be a h5py.Dataset object') h5_parent_group = h5_main.parent main_shape = h5_main.shape ###################### # Validate Dimensions ###################### # An N dimensional dataset should have N items in the dimension dictionary if len(dim_dict) != len(main_shape): raise ValueError('Incorrect number of dimensions: {} provided to support main data, of shape: {}' .format(len(dim_dict), main_shape)) if set(range(len(main_shape))) != set(dim_dict.keys()): raise KeyError('') dim_names = [] for index, dim_exp_size in enumerate(main_shape): this_dim = dim_dict[index] if isinstance(this_dim, h5py.Dataset): error_message = validate_dimensions(this_dim, main_shape[index]) if len(error_message) > 0: raise TypeError('Dimension {} has the following error_message:\n'.format(index), error_message) else: # if this_dim.name not in dim_names: if this_dim.name not in dim_names: # names must be unique dim_names.append(this_dim.name) else: raise TypeError('All dimension names must be unique, found {} twice'.format(this_dim.name)) if this_dim.file != h5_parent_group.file: copy_dataset(this_dim, h5_parent_group, verbose=False) else: raise TypeError('Items in dictionary must all be h5py.Datasets !') ################ # Attach Scales ################ for i, this_dim_dset in dim_dict.items(): this_dim_dset.make_scale(this_dim_dset.attrs['name']) h5_main.dims[int(i)].label = this_dim_dset.attrs['name'] h5_main.dims[int(i)].attach_scale(this_dim_dset) return h5_main def get_source_dataset(h5_group): """ Find the name of the source dataset used to create the input `h5_group`, so long as the source dataset is in the same HDF5 file Parameters ---------- h5_group : :class:`h5py.Group` Child group whose source dataset will be returned Returns ------- h5_source : NSIDataset object Main dataset from which this group was generated """ if not isinstance(h5_group, h5py.Group): raise TypeError('h5_group should be a h5py.Group object') h5_parent_group = h5_group.parent group_name = h5_group.name.split('/')[-1] # What if the group name was not formatted according to Pycroscopy rules? name_split = group_name.split('-') if len(name_split) != 2: raise ValueError("The provided group's name could not be split by '-' as expected in " "SourceDataset-ProcessName_000") h5_source = h5_parent_group[name_split[0]] if not isinstance(h5_source, h5py.Dataset): raise ValueError('Source object was not a dataset!') return h5_source def validate_dimensions(this_dim, dim_shape): """ Checks if the provided object is an h5 dataset. A valid dataset to be uses as dimension must be 1D not a compound data type but 'simple'. Such a dataset must have ancillary attributes 'name', quantity', 'units', and 'dimension_type', which have to be of types str, str, str, and bool respectively and not empty If it is not valid of dataset, Exceptions are raised. Parameters ---------- this_dim : h5 dataset with non empty attributes 'name', quantity', 'units', and 'dimension_type' dim_shape : required length of dataset Returns ------- error_message: string, empty if ok. """ if not isinstance(this_dim, h5py.Dataset): error_message = 'this Dimension must be a h5 Dataset' return error_message error_message = '' # Is it 1D? if len(this_dim.shape) != 1: error_message += ' High dimensional datasets are not allowed as dimensions;\n' # Does this dataset have a "simple" dtype - no compound data type allowed! # is the shape matching with the main dataset? if len(this_dim) != dim_shape: error_message += ' Dimension has wrong length;\n' # Does it contain some ancillary attributes like 'name', quantity', 'units', and 'dimension_type' necessary_attributes = ['name', 'quantity', 'units', 'dimension_type'] for key in necessary_attributes: if key not in this_dim.attrs: error_message += 'Missing {} attribute in dimension;\n '.format(key) elif not isinstance(this_dim.attrs[key], str): error_message += '{} attribute in dimension should be string;\n '.format(key) return error_message def validate_main_dimensions(main_shape, dim_dict, h5_parent_group): # Each item could either be a Dimension object or a HDF5 dataset # Collect the file within which these ancillary HDF5 objects are present if they are provided which_h5_file = {} # Also collect the names of the dimensions. We want them to be unique dim_names = [] dimensions_correct = [] for index, dim_exp_size in enumerate(main_shape): this_dim = dim_dict[index] if isinstance(this_dim, h5py.Dataset): error_message = validate_dimensions(this_dim, main_shape[index]) # All these checks should live in a helper function for cleanliness if len(error_message) > 0: print('Dimension {} has the following error_message:\n'.format(index), error_message) else: if this_dim.name not in dim_names: # names must be unique dim_names.append(this_dim.name) else: raise TypeError('All dimension names must be unique, found' ' {} twice'.format(this_dim.name)) # are all datasets in the same file? if this_dim.file != h5_parent_group.file: copy_dataset(this_dim, h5_parent_group, verbose=True) elif isinstance(this_dim, Dimension): # is the shape matching with the main dataset? dimensions_correct.append(len(this_dim.values) == dim_exp_size) # Is there a HDF5 dataset with the same name already in the provided group # where this dataset will be created? if this_dim.name in h5_parent_group: # check if this object with the same name is a dataset and if it satisfies the above tests if isinstance(h5_parent_group[this_dim.name], h5py.Dataset): print('needs more checking') dimensions_correct[-1] = False else: dimensions_correct[-1] = True # Otherwise, just append the dimension name for the uniqueness test elif this_dim.name not in dim_names: dim_names.append(this_dim.name) else: dimensions_correct[-1] = False else: raise TypeError('Values of dim_dict should either be h5py.Dataset ' 'objects or Dimension. Object at index: {} was of ' 'type: {}'.format(index, index)) for dim in which_h5_file: if which_h5_file[dim] != h5_parent_group.file.filename: print('need to copy dimension', dim) for i, dim_name in enumerate(dim_names[:-1]): if dim_name in dim_names[i + 1:]: print(dim_name, ' is not unique') return dimensions_correct
C#
UTF-8
4,223
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BoomaEcommerce.Domain.Policies; namespace BoomaEcommerce.Domain.Discounts { public class CategoryDiscount : Discount { public string Category { get; set; } public CategoryDiscount(int percentage, DateTime startTime, DateTime endTime, string description, Policy policy, string category) : base(percentage, startTime, endTime, description, policy) { Category = category; } public CategoryDiscount() : base(0, DateTime.MinValue, DateTime.MaxValue, "", Policy.Empty) { } public override string ApplyDiscount(StorePurchase sp) { var discountInfo = ""; decimal moneySaved = 0; if (!(ValidateDiscount(sp))) { return "Could not apply discount!\n" + (Policy.CheckPolicy(sp).IsOk ? "Discount validity has expired\n" : Policy.CheckPolicy(sp).PolicyError); } foreach (var pp in sp.PurchaseProducts.Where(pp => pp.Product.Category.Equals(Category))) { var productPriceBeforeDiscount = pp.DiscountedPrice; var discountDecimal = ((100 - (decimal)Percentage) / 100); pp.DiscountedPrice *= discountDecimal; discountInfo += "Applied " + Percentage + "% discount to " + pp.Product.Name + " of the " + Category + " category\n"; moneySaved += productPriceBeforeDiscount - pp.DiscountedPrice; } sp.DiscountedPrice -= moneySaved; return discountInfo; } public override string ApplyDiscount(User user, ShoppingBasket basket) { var discountInfo = ""; if (!(ValidateDiscount(user, basket))) { return "Could not apply discount!\n" + (Policy.CheckPolicy(user, basket).IsOk ? "Discount validity has expired\n" : Policy.CheckPolicy(user, basket).PolicyError); } foreach (var pp in basket.PurchaseProducts) { if (!(pp.Product.Category.Equals(Category))) continue; var discountDecimal = ((100 - (decimal)Percentage) / 100); pp.DiscountedPrice = pp.Price * discountDecimal; discountInfo += "Applied " + Percentage + "% discount to " + pp.Product.Name + " of the " + Category + " category\n"; } return discountInfo; } public override decimal CalculateTotalPriceWithoutApplying(StorePurchase sp, Dictionary<Guid, decimal> updatedPrices) { decimal calculatedDiscount = 0; decimal ppDiscount = 0; if (!ValidateDiscount(sp)) { return decimal.MaxValue; } foreach (var pp in sp.PurchaseProducts.Where(pp => pp.Product.Category.Equals(Category))) { var productPriceBeforeDiscount = updatedPrices[pp.Guid]; var discountDecimal = ((100 - (decimal)Percentage) / 100); ppDiscount = (productPriceBeforeDiscount - productPriceBeforeDiscount * discountDecimal); updatedPrices[pp.Guid] -= ppDiscount; calculatedDiscount += ppDiscount; } return calculatedDiscount; } public override decimal CalculateTotalPriceWithoutApplying(User user, ShoppingBasket basket) { decimal calculatedDiscount = 0; decimal ppDiscount = 0; if (!ValidateDiscount(user, basket)) { return decimal.MaxValue; } foreach (var pp in basket.PurchaseProducts) { if (pp.Product.Category.Equals(Category)) { ppDiscount = pp.Price - (pp.Price * ((100 - (decimal)Percentage) / 100)); calculatedDiscount += ppDiscount; } } return calculatedDiscount; } } }
Python
UTF-8
2,406
2.71875
3
[]
no_license
import firebase_admin from firebase_admin import credentials from firebase_admin import db from pyfirmata import Arduino, util from tkinter import * from PIL import Image from PIL import ImageTk import time placa = Arduino ('COM3') it = util.Iterator(placa) it.start() a_0 = placa.get_pin('a:0:i') a_1 = placa.get_pin('a:1:i') a_2 = placa.get_pin('a:2:i') led1 = placa.get_pin('d:8:o') led2 = placa.get_pin('d:9:p') led3 = placa.get_pin('d:10:p') led4 = placa.get_pin('d:11:p') led5 = placa.get_pin('d:12:o') led6 = placa.get_pin('d:13:o') time.sleep(0.5) ventana = Tk() ventana.geometry('250x250') ventana.title("Punto Uno") # Fetch the service account key JSON file contents cred = credentials.Certificate('key/key.json') # Initialize the app with a service account, granting admin privileges firebase_admin.initialize_app(cred, { 'databaseURL': 'https://parcial-d03bc.firebaseio.com/' }) Frame1 = Frame(ventana, bg="gray", highlightthickness=1, width=1280, height=800, bd= 5) Frame1.place(x = 0,y = 0) valor= Label(Frame1, bg='cadet blue1', font=("Arial Bold", 15), fg="black", width=5) adc_data=StringVar() valor2= Label(Frame1, bg='cadet blue1', font=("Arial Bold", 15), fg="black", width=5) adc_data2=StringVar() valor3= Label(Frame1, bg='cadet blue1', font=("Arial Bold", 15), fg="black", width=5) adc_data3=StringVar() variable=StringVar() def adc_read1(): x=a_0.read() print(x) adc_data.set(x) time.sleep(0.1) ref = db.reference('sensor') ref.update({ 'sensor1/lector1': x }) def adc_read2(): x=a_1.read() print(x) adc_data2.set(x) time.sleep(0.1) ref = db.reference('sensor') ref.update({ 'sensor2/lector2': x }) def adc_read3(): x=a_2.read() print(x) adc_data3.set(x) time.sleep(0.1) ref = db.reference('sensor') ref.update({ 'sensor3/lector3': x }) valor.configure(textvariable=adc_data) valor.place(x=20, y=30) start_button=Button(Frame1,text="lector 1",command=adc_read1) start_button.place(x=95, y=32) valor2.configure(textvariable=adc_data2) valor2.place(x=20, y=80) start_button2=Button(Frame1,text="lector 2",command=adc_read2) start_button2.place(x=95, y=82) valor3.configure(textvariable=adc_data3) valor3.place(x=20, y=130) start_button3=Button(Frame1,text="lector 3",command=adc_read3) start_button3.place(x=95, y=132) ventana.mainloop()
Markdown
UTF-8
5,867
2.953125
3
[]
no_license
--- layout: post title: A base controller for CodeIgniter meta_description: An attempt to generalize a base controller in CodeIgniter. meta_keywords: Controller, CodeIgniter, CI, development, design, oop category: [php] --- After creating several small to medium CodeIgniter projects, I have adopted the habit of creating a base controller with the following methods: {% highlight php %} <?php class MY_Controller extends Controller { private $view = array(); private $view_path = ''; public function __construct() { parent::__construct(); $this->init(); } /** * Override this method in child controllers to call initialization * routines. */ public function init() {} /** * Set a view variable. * * @param string $variable Name of the variable. * @param mixed $value Variable value. */ public function set($variable, $value) { if (!in_array($variable, array('page_title', 'view'))) { $this->view[$variable] = $value; } } /** * It sets the view path. Useful to call it on the init() method. * Do NOT put a trailing slash. * * @param string $path The path. */ public function set_view_path($path) { $this->view_path = $path; } /** * Renders a view. * * @param string $title The page title. * @param string $view Filename of the view without extension. It defaults * to the name of the current controller action. * @param boolean $return If true, returns the translated viewg, otherwise * just renders the view normally. */ public function render($title, $view='', $return=false) { $this->view['page_title'] = $title; $view = empty($view) ? $this->router->fetch_method() : $view; $this->view['view'] = $this->view_path . '/' .$view; $this->view['_front'] = $this->view_path; $this->view['_action'] = $this->router->fetch_method(); $this->renderme(); $output = $this->load->view( 'layout', $this->view, $return ); return $output; } /** * Override this method for custom view initializations that need to be * done all the time. Perhaps not as useful as I thought. */ public function renderme() {} /** * Info discovery method. It's not that pretty. When inspecting CI objects * you can get a lot of recursion. :S * * @param Object $object The object to be inspected. */ public function inspect($object) { $methods = get_class_methods($object); $vars = get_class_vars(get_class($object)); $ovars = get_object_vars($object); $parent = get_parent_class($object); $output = 'Parent class: ' . $parent . "\n\n"; $output .= "Methods:\n"; $output .= "--------\n"; foreach ($methods as $method) { $meth = new ReflectionMethod(get_class($object), $method); $output .= $method . "\n"; $output .= $meth->__toString(); } $output .= "\nClass Vars:\n"; $output .= "-----------\n"; foreach ($vars as $name => $value) { $output .= $name . ' = ' . print_r($value, 1) . "\n"; } $output .= "\nObject Vars:\n"; $output .= "------------\n"; foreach ($ovars as $name => $value) { $output .= $name . ' = ' . print_r($value, 1) . "\n"; } echo '<pre>', $output, '</pre>'; } } {% endhighlight %} With that out of the way, the benefit I get is an improvement in working with views, and some nice view defaults. Let me elaborate a little. Usually, for all projects I will have a main layout file with the following, radically summarized, structure: {% highlight html %} <html> <head> <title><?php echo $page_title; ?> :: <?php echo $this->config->item('site_name'); ?></title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" type="text/css" media="all" href="<?php echo base_url(); ?>css/site.css" /> </head> <body> <div id="wrap"> <div id="header"> <a href="<?php echo base_url(); ?>"><img src="<?php echo base_url(); ?>i/logo.jpg" alt="Logo" /></a> </div> <?php if ($_front == 'admin'): ?> <?php echo $this->load->view('admin/menu'); ?> <?php endif; ?> <div id="content"> <?php $this->load->view($view); ?> </div> <div id="footer"> <img src="<?php echo base_url(); ?>i/footer.gif" alt="" /> </div> </div> </body> </html> {% endhighlight %} You can see in the code pasted above, that I made the assumption that if using this controller, you will have a similar layout file called "layout.php" in the application/views directory. By making this assumption, I can now render templates, and use child controllers in the following way: {% highlight php %} <?php class Test extends MY_Controller { public function init() { /* Load authentication? Start sessions? */ /* Setting the view path could be useful for specific controllers */ $this->set_view_path('admin'); // application/views/admin/ } public function index() { /* Assumes the template application/views/index.php exists */ $this->render('My Home Page'); } public function another() { /* Renders the template application/views/test.php */ $this->render('Another', 'test'); } public function moretest() { /* Setting a view variable */ $this->set('greeting', 'Hello there'); } } {% endhighlight %} Basically, the most interesting method here is <code>render()</code>. You can <a href="/downloads/MY_Controller.txt">download the source</a> as a text file. ^_^
Java
UTF-8
257
1.539063
2
[]
no_license
package com.spring.angular.xfs; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.spring.angular.xfs.Xfs; @Repository public interface XfsRepository extends CrudRepository<Xfs, Long>{}
Java
UTF-8
3,292
2.5
2
[]
no_license
/* Name:- Meet A. Patel Class:- CIS-3515 Assignment:- Assignment 4 Date:- 02/17/2019 */ /* Name:- Meet A. Patel Class:- CIS-3515 Assignment:- Lab 5 */ package temple.edu; import android.content.Intent; import android.content.res.Resources; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.text.Layout; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.Spinner; import android.widget.TextView; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { Spinner spinner; //creating a spinner object String[] myColor = {"White", "Red", "Blue", "Black", "Yellow", "Green", "Gray", "Cyan", "Magenta"}; //creatting array list int colorIntValue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinner = (Spinner)findViewById(R.id.spinner); //Underneath is for lab 4 if you uncommant this then you could go back to lab 4 /* final ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, myColor); // specify the layout to use when the list of choices appears myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item); spinner.setAdapter(myAdapter); */ //ColorAdapter ArrayAdapter = new ColorAdapter(this, myColor); //this is for lab 5 which conevert english to spanish //you have to change the language in the setting to spanich lang Resources res = getResources(); final String[] English= res.getStringArray(R.array.myColorList); final String[] Span = res.getStringArray(R.array.myColor); ColorAdapter ArrayAdapter = new ColorAdapter(this, English, Span); spinner.setAdapter(ArrayAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String color = parent.getItemAtPosition(position).toString(); view.setBackgroundColor(Color.parseColor("White")); View mainll = findViewById(R.id.first); //mainll.setBackgroundColor(Color.parseColor(color)); if(position == -1){ return; }else{ colorIntValue = Color.parseColor(English[position]);//convert to int values //creating new intent Intent nextIntent = new Intent(MainActivity.this, Main2Activity.class); nextIntent.putExtra("newColor", colorIntValue); // nextIntent.putExtra("newColor", English[position]); startActivity(nextIntent);//start the activity } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } }
Markdown
UTF-8
1,099
2.671875
3
[]
no_license
# World of Pets Hack 300k free gems Cheats Mod apk iOS android tips World of Pets Hack 300k free gems Cheats Mod apk iOS android tips - Having said so much, in fact, there are various risks in all the well-designed World of Pets hack. For example, after the official release of a World of Pets cheats, there will be no players to participate, making the whole Arg game "self Hi". The reason why World of Pets developer dares to adopt this plan is that there is a very large group of players in "IOS", among which there are absolutely not a few players who are full of strong curiosity and expectation about the new hero. In addition, although the online time of "World of Pets" game is not long, the community construction of this game is progressing very smoothly. At home and abroad, we can see the forum of "World of Pets mod" with strict layout rules and orderly order. On the one hand, it is due to the efforts of the players themselves, and on the other hand, it is inseparable from Blizzard's correct guidance and help to the third party community. here https://trustmod.top/world-of-pets/
Markdown
UTF-8
558
3.15625
3
[]
no_license
# javascript-examples A simple JavaScript code that checks all numbers from 1-100 and Prints "Fizz" when the number is only divisible by 3, Prints "Buzz" when the number is only divisible by 5, Prints "FizzBuzz" when the number is divisible by both 3 and 5, Prints the number as it is in all other cases Open the index.html file with any text editor and insert the right location of the FizzBuzz.js file in <script src=" ">. After that open the index.html file with any browser and press the F12 key (in most browsers) to view the output in the Console.
Python
UTF-8
782
3.234375
3
[]
no_license
days = {"January" : 31, "February" : 28, "March" : 31, "April" : 30, "May" : 31, "June" : 30, "July" : 31, "August" : 31, "September" : 30, "October" : 31, "November" : 30, "December": 31 } months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] dayOfWeek = 1 num = 0 for year in xrange(1901, 2001): for month in xrange(1, 13): daysInMonth = days[months[month - 1]] if year % 4 == 0 and month == 2: daysInMonth = daysInMonth + 1; for day in xrange(1, daysInMonth + 1): if dayOfWeek == 6 and day == 1: num = num + 1 dayOfWeek = dayOfWeek + 1 dayOfWeek = dayOfWeek % 7 print num
Go
UTF-8
2,562
3.28125
3
[ "MIT" ]
permissive
// Package models is a simple, lightweight ORM built in Go. It aims to provide a simple and clean API to improve testing and code readability in projects dependent on databases. // // Curretly models only supports MongoDB as a database driver. // // Getting started with models is as simple as satisfying the Modeller interface: // type Modeller interface { // BID() bson.ObjectId // The Modellers ID. // C() string // The collection the Modeller belongs to. // } // // With a struct like: // type Dog struct { // ID bson.ObjectId `bson:"_id"` // Name string `bson:"name"` // Owner string `bson:"owner"` // Age int `bson:"age"` // } // func (d Dog) BID() bson.ObjectId { // return d.ID // } // func (d Dog) C() string { // return "dogs" // } // // In order to use the models package a connection to the database (local or remote) has to be made. // models.Init("localhost", "database") // // Creating a model is just like creating a regular struct. // d := Dog{ID: bson.ObjectID, Name: "Bucky", Owner:"Tony", Age: 3} // Once you have a struct that satisfies the Modeller interface you are able to Persist the model. // err := models.Persist(d) // // A persisted version of a model will only update when a models.Update(m, values) called. // The keys in the values parameter should be whatever you tagged that field of the struct with. // Eg. "name" for Dog.Name, "age" for Dog.Age and "_id" for Dog.ID // err := models.Update(&d, bson.M{"age": 4}) // // If you want to restore your model from a persisted record call models.Restore(m, values). // This will use the values as a search query for mgo, and re-hydrate the passed in Pointer. // err := models.Restore(d, bson.M{"name": "Bucky"}) // There is a built-in alias for restoring a model based on ID called models.RestoreByID(m). // err := models.RestoreById(d, bson.NewObjectId()) // // Finally, if you want to remove a persisted model from the database, call models.Remove(m). // err := models.Remove(d) // // Basic options for manipulating groups of retrieving and deleting model groups are available. // Fetching is the recommended way of pulling a group of models from the db. // var dogs []Dog // dog := Dog{} // iter, err := models.Fetch(dog.C(), bson.M{"age": 0}) // if err != nil { // // handle the error // } // for iter.Next(&dog) { // dogs = append(dogs, dog) // } // Removing groups is also doable through the RemoveAll(collection, values) function. // err := models.RemoveAll("collection", bson.M{"x": -1}) package models
C++
UTF-8
649
2.59375
3
[]
no_license
#ifndef THE_LIFT_H_ #define THE_LIFT_H_ #include <iostream> #include <vector> #include <algorithm> #include "floor.h" class TheLift { private: enum direction { UP, DOWN}; direction m_dir; std::vector<FloorQueue> m_floors; std::vector<Human> m_humans; int nr_floors; int m_capacity; int m_current_floor; bool is_exit_floor() const; void exit_people_from_lift(); bool is_enter_floor() const; void enter_people_to_lift(); bool is_lower_call() const; bool is_upper_call() const; int get_next_floor(); public: TheLift (std::vector<std::vector<int>> queues, int capacity); ~TheLift (); std::vector<int> get_floors_queue(); }; #endif
Java
UTF-8
1,296
1.992188
2
[]
no_license
package maxzawalo.c2.free.ui.pc.model.document.bank; import javax.swing.JLabel; import maxzawalo.c2.base.ui.pc.model.ColumnSettings; import maxzawalo.c2.free.bo.bank.BankTP; import maxzawalo.c2.free.bo.document.receiptmoney.ReceiptMoneyTablePart; import maxzawalo.c2.free.bo.document.receiptmoney.ReceiptMoneyTablePart.Payment; public class ReceiptMoneyTablePartModel extends BankTPModel<ReceiptMoneyTablePart.Payment> { public ReceiptMoneyTablePartModel() { // visibleColumns.clear(); ColumnSettings column = AddVisibleColumns(); column.caption = "Договор"; column.name = BankTP.fields.CONTRACT; column.horizontalAlignment = JLabel.LEFT; column = AddVisibleColumns(); column.name = BankTP.fields.SUM; column.horizontalAlignment = JLabel.RIGHT; column = AddVisibleColumns(); column.name = BankTP.fields.RATE_VAT; column.horizontalAlignment = JLabel.RIGHT; column = AddVisibleColumns(); column.name = BankTP.fields.SUM_VAT; column.horizontalAlignment = JLabel.RIGHT; column = AddVisibleColumns(); column.name = ReceiptMoneyTablePart.Payment.fields.SERVICE_SUM; column.horizontalAlignment = JLabel.RIGHT; column = AddVisibleColumns(); column.name = Payment.fields.BILL; column.horizontalAlignment = JLabel.RIGHT; setColumnCaptions(); } }
Java
UTF-8
118
2.46875
2
[ "MIT" ]
permissive
public class LabyrinthException extends Exception { public LabyrinthException(String mssg) { super(mssg); } }
Python
UTF-8
972
2.96875
3
[]
no_license
pret = 0 cret = 0 def print_base(picked): local = [] for i in range(len(picked)): if not picked[i]:continue local.append(i) print(local) def permutation(n, picked, m): if m == 0: global pret pret +=1 print_base(picked) else: for i in range(n): if not picked[i]: picked[i] = True permutation(n, picked, m-1) picked[i] = False def combination(n, picked, toPick): if toPick == 0: global cret cret += 1 print(picked) else: # a if condition else b smallest = 0 if not picked else (picked[-1] + 1) for i in range(smallest, n): picked.append(i) combination(n, picked, toPick-1) picked.pop() n = 4 picked = [False for x in range(n)] m = 2 permutation(n, picked, m) print(pret) combination(n, [], m) print(cret)
PHP
UTF-8
1,388
2.84375
3
[]
no_license
<?php namespace Creuna\ObjectiveWpAdmin\Persistence; use Creuna\ObjectiveWpAdmin\AdminAdapter; use Creuna\ObjectiveWpAdmin\Admin; interface Field { /** * Instantiates the FieldView that will handle * the Field's UI. * * @param Admin $admin - Can be used by the field * to resolve relationships. * * @return FieldView */ public function view(Admin $admin); /** * Returns the name of the field. * * @return string */ public function name(); /** * Sets or gets the default value of this field. * * @param mixed $value * * @return string */ public function defaults($value = null); /** * Tells the PostType whether or not this field * is required to be present on the post. * * @return bool */ public function isRequired(); /** * Tells the PostType that the field holds multiple values. * * @return bool */ public function holdsArray(); /** * Serialize a value to something that can be saved the the DB. * * @param mixed $value * @return mixed */ public function serialize($value); /** * Deserialize a value from its DB representation. * * @param mixed $value * @return mixed */ public function deserialize($value); }
Python
UTF-8
1,220
2.71875
3
[]
no_license
import pandas as pd from os import listdir from os.path import isfile, join import datetime, calendar # this is the path to a folder which has weekly list csv files, here 'files' folder mypath = '/Users/mahdishahbaba/shopofia-db-bucket/files/' def get_last_friday(sanpshot_dt): lastFriday = datetime.datetime.strptime(sanpshot_dt, '%Y-%m-%d')#.date() oneday = datetime.timedelta(days=1) while lastFriday.weekday() != calendar.FRIDAY: lastFriday -= oneday return lastFriday.strftime("%D") onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] df_list = [] for f in onlyfiles: df_list.append(pd.read_csv(mypath+f)) result = pd.concat(df_list, ignore_index=True, axis=0) result.loc[:,'snapshot_date'] = result.loc[:,'snapshot_date'].apply(get_last_friday) result = result.drop(['Unnamed: 0', 'index'], axis=1) result.loc[:,'shopofia'] = 1 print(result.columns) print(result['snapshot_date'].unique()) # path to the final file result.to_csv(r'/Users/mahdishahbaba/shopofia-db-bucket/output/weekly_list_combined.csv', index=False) # just to test the function, you can ignore the following sanpshot_dt = str(datetime.date.today()) print(get_last_friday(sanpshot_dt))
PHP
UTF-8
10,697
2.5625
3
[ "MIT" ]
permissive
<?php //Indication, Copyright Josh Fradley (http://github.com/joshf/Indication) if (!file_exists("../config.php")) { header("Location: ../installer"); exit; } require_once("../config.php"); session_start(); if (!isset($_SESSION["indication_user"])) { header("Location: login.php"); exit; } //Connect to database @$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if (mysqli_connect_errno()) { die("Error: Could not connect to database (" . mysqli_connect_error() . "). Check your database settings are correct."); } $getusersettings = mysqli_query($con, "SELECT `user`, `password`, `email`, `salt` FROM `Users` WHERE `id` = \"" . $_SESSION["indication_user"] . "\""); if (mysqli_num_rows($getusersettings) == 0) { session_destroy(); header("Location: login.php"); exit; } $resultgetusersettings = mysqli_fetch_assoc($getusersettings); //Get current settings $currentwebsite = WEBSITE; $currentpathtoscript = PATH_TO_SCRIPT; $currentadcode = htmlspecialchars_decode(AD_CODE); $currentcountuniqueonlystate = COUNT_UNIQUE_ONLY_STATE; $currentcountuniqueonlytime = COUNT_UNIQUE_ONLY_TIME; $currentignoreadminstate = IGNORE_ADMIN_STATE; if (!empty($_POST)) { //Get new settings from POST $user = $_POST["user"]; $password = $_POST["password"]; $email = $_POST["email"]; $salt = $resultgetusersettings["salt"]; if ($password != $resultgetusersettings["password"]) { //Salt and hash passwords $randsalt = md5(uniqid(rand(), true)); $salt = substr($randsalt, 0, 3); $hashedpassword = hash("sha256", $password); $password = hash("sha256", $salt . $hashedpassword); } $website = $_POST["website"]; $pathtoscript = rtrim($_POST["pathtoscript"], "/"); if (isset($_POST["advertcode"])) { if (get_magic_quotes_gpc()) { $adcode = stripslashes(htmlspecialchars($_POST["advertcode"])); } else { $adcode = htmlspecialchars($_POST["advertcode"]); } } $countuniqueonlystate = $_POST["countuniqueonlystate"]; $countuniqueonlytime = $_POST["countuniqueonlytime"]; $ignoreadminstate = $_POST["ignoreadminstate"]; //Remember previous settings if (empty($adcode)) { $adcode = $currentadcode; } $settingsstring = "<?php\n\n//Database Settings\ndefine('DB_HOST', '" . DB_HOST . "');\ndefine('DB_USER', '" . DB_USER . "');\ndefine('DB_PASSWORD', '" . DB_PASSWORD . "');\ndefine('DB_NAME', '" . DB_NAME . "');\n\n//Other Settings\ndefine('SALT', '" . SALT . "');\ndefine('WEBSITE', " . var_export($website, true) . ");\ndefine('PATH_TO_SCRIPT', " . var_export($pathtoscript, true) . ");\ndefine('AD_CODE', " . var_export($adcode, true) . ");\ndefine('COUNT_UNIQUE_ONLY_STATE', " . var_export($countuniqueonlystate, true) . ");\ndefine('COUNT_UNIQUE_ONLY_TIME', " . var_export($countuniqueonlytime, true) . ");\ndefine('IGNORE_ADMIN_STATE', " . var_export($ignoreadminstate, true) . ");\ndefine('VERSION', '" . VERSION . "');\n\n?>"; //Update Settings mysqli_query($con, "UPDATE Users SET `user` = \"$user\", `password` = \"$password\", `email` = \"$email\", `salt` = \"$salt\" WHERE `user` = \"" . $resultgetusersettings["user"] . "\""); //Write config $configfile = fopen("../config.php", "w"); fwrite($configfile, $settingsstring); fclose($configfile); //Show updated values header("Location: settings.php"); exit; } mysqli_close($con); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Indication &middot; Settings</title> <link href="../assets/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="../assets/bootstrap-notify/css/bootstrap-notify.min.css" rel="stylesheet"> <style type="text/css"> body { padding-top: 30px; padding-bottom: 30px; } /* Fix weird notification appearance */ a.close.pull-right { padding-left: 10px; } </style> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Indication</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="index.php">Home</a></li> <li><a href="add.php">Add</a></li> <li><a href="edit.php">Edit</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><?php echo $resultgetusersettings["user"]; ?> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="settings.php">Settings</a></li> <li><a href="logout.php">Logout</a></li> </ul> </li> </ul> </div> </div> </div> <div class="container"> <div class="page-header"> <h1>Settings</h1> </div> <div class="notifications top-right"></div> <form role="form" method="post" autocomplete="off"> <h4>User Details</h4> <div class="form-group"> <label for="user">User</label> <input type="text" class="form-control" id="user" name="user" value="<?php echo $resultgetusersettings["user"]; ?>" placeholder="Enter a username..." required> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" id="email" name="email" value="<?php echo $resultgetusersettings["email"]; ?>" placeholder="Type an email..." required> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password" name="password" value="<?php echo $resultgetusersettings["password"]; ?>" placeholder="Enter a password..." required> </div> <h4>Site Settings</h4> <div class="form-group"> <label for="website">Website</label> <input type="text" class="form-control" id="website" name="website" value="<?php echo $currentwebsite; ?>" placeholder="Enter your websites name..." required> </div> <div class="form-group"> <label for="pathtoscript">Path to Script</label> <input type="text" class="form-control" id="pathtoscript" name="pathtoscript" value="<?php echo $currentpathtoscript; ?>" placeholder="Type the path to Indication..." pattern="(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-?]*)*\/?" data-validation-pattern-message="Please enter a valid URL" required> </div> <h4>Ad Code</h4> <p>Show an advert before user can continue to their download. This can be changed on a per download basis.</p> <div class="alert alert-warning"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <b>Warning:</b> On some server configurations using HTML code here may produce errors.</div> <div class="form-group"> <textarea class="form-control" id="advertcode" name="advertcode" placeholder="Enter a ad code..."><?php echo $currentadcode; ?></textarea> </div> <h4>Count Unique Visitors Only</h4> <p>This settings allows you to make sure an individual user's clicks are only counted once.</p> <div class="radio"> <?php if ($currentcountuniqueonlystate == "Enabled" ) { echo "<label><input type=\"radio\" id=\"countuniqueonlystateenable\" name=\"countuniqueonlystate\" value=\"Enabled\" checked=\"checked\"> Enabled</label></div> <div class=\"radio\"><label><input type=\"radio\" id=\"countuniqueonlystatedisable\" name=\"countuniqueonlystate\" value=\"Disabled\"> Disabled</label>"; } else { echo "<label><input type=\"radio\" id=\"countuniqueonlystateenable\" name=\"countuniqueonlystate\" value=\"Enabled\"> Enabled</label></div> <div class=\"radio\"><label><input type=\"radio\" id=\"countuniqueonlystatedisable\" name=\"countuniqueonlystate\" value=\"Disabled\" checked=\"checked\"> Disabled</label>"; } ?> </div> <div class="form-group"> <label for="countuniqueonlytime">Time to consider a user unique (hours)</label> <input type="number" class="form-control" id="countuniqueonlytime" name="countuniqueonlytime" value="<?php echo $currentcountuniqueonlytime; ?>" placeholder="Enter a time..." required> </div> <h4>Ignore Admin</h4> <p>This settings prevents downloads being counted when you are logged in to Indication.</p> <div class="radio"> <?php if ($currentignoreadminstate == "Enabled" ) { echo "<label><input type=\"radio\" id=\"ignoreadminstateenable\" name=\"ignoreadminstate\" value=\"Enabled\" checked=\"checked\"> Enabled</label></div> <div class=\"radio\"><label><input type=\"radio\" id=\"ignoreadminstatedisable\" name=\"ignoreadminstate\" value=\"Disabled\"> Disabled</label>"; } else { echo "<label><input type=\"radio\" id=\"ignoreadminstateenable\" name=\"ignoreadminstate\" value=\"Enabled\"> Enabled</label></div> <div class=\"radio\"><label><input type=\"radio\" id=\"ignoreadminstatedisable\" name=\"ignoreadminstate\" value=\"Disabled\" checked=\"checked\"> Disabled</label>"; } ?> </div> <button type="submit" class="btn btn-default">Save</button> </form> </div> <script src="../assets/jquery.min.js"></script> <script src="../assets/bootstrap/js/bootstrap.min.js"></script> <script src="../assets/bootstrap-notify/js/bootstrap-notify.min.js"></script> <script src="../assets/jquery.cookie.min.js"></script> <script src="../assets/nod.min.js"></script> <script type="text/javascript"> $(document).ready(function() { if ($.cookie("settings_updated")) { $(".top-right").notify({ type: "info", transition: "fade", icon: "info-sign", message: { text: "Settings saved!" } }).show(); $.removeCookie("settings_updated"); } $("form").submit(function() { $.cookie("settings_updated", "true"); }); var metrics = [ ["#user", "presence", "User name cannot be empty!"], ["#email", "email", "Enter a valid email address"], ["#password", "presence", "Passwords should be more than 6 characters"], ["#website", "presence", "Website cannot be empty!"], ["#pathtoscript", "presence", "Path to script cannot be empty!"], ["#countuniqueonlytime", "min-num:1", "Time must be higer than 1"] ]; $("form").nod(metrics); }); </script> </body> </html>
Java
UTF-8
3,510
2.75
3
[ "MIT" ]
permissive
package stm; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import java.io.*; // IOException import java.util.*; // Scanner import jssc.*; public class STM { private static SerialPort serialPort; public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException, InterruptedException { Coin bitcoin = new Coin("BTC"); Coin ethereum = new Coin("ETH"); Coin xrp = new Coin("XRP"); Coin bitcoinCash = new Coin("BCH"); Coin eos = new Coin("EOS"); Coin stellar = new Coin("XLM"); Coin X0 = new Coin("ZRX"); Coin neo = new Coin("NEO"); Coin zilliqa = new Coin("ZIL"); Coin monero = new Coin("XMR"); final int time = 5000; while(true){ System.out.println(bitcoin.GETAPI()); Thread.sleep(time); System.out.println(ethereum.GETAPI()); Thread.sleep(time); System.out.println(xrp.GETAPI()); Thread.sleep(time); System.out.println(bitcoinCash.GETAPI()); Thread.sleep(time); System.out.println(eos.GETAPI()); Thread.sleep(time); System.out.println(stellar.GETAPI()); Thread.sleep(time); System.out.println(X0.GETAPI()); Thread.sleep(time); System.out.println(neo.GETAPI()); Thread.sleep(time); System.out.println(zilliqa.GETAPI()); Thread.sleep(time); System.out.println(monero.GETAPI()); Thread.sleep(time); } } public void SentToPort() { String[] portNames = SerialPortList.getPortNames(); if (portNames.length == 0) { System.out.println("Brak wolnych portów."); try { System.in.read(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } System.out.println("Dostępne porty:"); for (int i = 0; i < portNames.length; i++) { System.out.println(portNames[i]); } System.out.println("Wpisz nazwę portu i wciśnij ENTER"); Scanner in = new Scanner(System.in); String portName = in.next(); // writing to port serialPort = new SerialPort(portName); try { // opening port serialPort.openPort(); serialPort.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT); // writing string to port serialPort.writeString("newResponse"); System.out.println("Wysłano wiadomość"); } catch (SerialPortException ex) { System.out.println("Błąd podczas wysyłania: " + ex); } } }
Java
UTF-8
2,487
2.125
2
[]
no_license
package com.platform.api; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; import com.platform.config.RedisUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.IOException; /** * @program: * @Description: * @Author: liweihai * @Date: Created in 2019/2/9 13:19 */ @Controller //@RequestMapping("/kaptcha") public class KaptchaController { @Autowired private Producer producer; @Autowired private RedisUtil redisUtil; //@RequestMapping("/image") public void captcha(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); //this.getLocalIp(request); String sdd = request.getRemoteAddr(); //log.info("request.getRemoteAddr():{}",sdd); //生成文字验证码 String text = producer.createText(); //生成图片验证码 BufferedImage image = producer.createImage(text); redisUtil.set(Constants.KAPTCHA_SESSION_KEY + text, text, 120); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); } public String getLocalIp(HttpServletRequest request) { String remoteAddr = request.getRemoteAddr(); String forwarded = request.getHeader("X-Forwarded-For"); String realIp = request.getHeader("X-Real-IP"); // log.info("forwarded:{}",forwarded); // log.info("realIp:{}",realIp); String ip = null; if (realIp == null) { if (forwarded == null) { ip = remoteAddr; } else { ip = remoteAddr + "/" + forwarded.split(",")[0]; } } else { if (realIp.equals(forwarded)) { ip = realIp; } else { if (forwarded != null) { forwarded = forwarded.split(",")[0]; } ip = realIp + "/" + forwarded; } } return ip; } }
Java
UTF-8
253
1.546875
2
[]
no_license
package com.ml4ai.server.repository; import com.ml4ai.server.domain.Role; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by leecheng on 2018/9/24. */ public interface RoleRepositroy extends JpaRepository<Role, Long> { }
Java
GB18030
1,604
3.96875
4
[]
no_license
import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; //ַַӳ䣬һַӦһַҶӦϵһһĹϵ //Examples: //1.pattern = "abba", str = "dog cat cat dog" should return true. //2.pattern = "abba", str = "dog cat cat fish" should return false. //3.pattern = "aaaa", str = "dog cat cat dog" should return false. //4.pattern = "abba", str = "dog dog dog dog" should return false. public class WordPattern { //˼·Խmapַַһһӳϵ֤ظ private static boolean wordPattern(String pattern, String str) { String[] strs = str.split(" "); if(pattern.length() != strs.length) return false;//patternijӦúַijһ²ܽƥ䣬ƥ Map<Character, String> map = new HashMap<>();//charStringӳ Set<String> unique = new HashSet<>();//Stringֶһ for(int i=0; i<pattern.length(); i++){ char c = pattern.charAt(i); if(map.containsKey(c)){ if(!map.get(c).equals(strs[i])) return false; }else{ if(unique.contains(strs[i])) return false; map.put(c, strs[i]); unique.add(strs[i]); } } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String pattern; String str; while(sc.hasNext()){ pattern = sc.nextLine(); str = sc.nextLine(); System.out.println(wordPattern(pattern, str)); } } }
C#
UTF-8
1,254
2.84375
3
[]
no_license
using System; using System.Collections.Generic; namespace MRAT { [Serializable] public class MratServerMessage: MratAbstractMessage { public string User; public string Token; public List<string> JsonMessages { get; set; } = new List<string>(); public MratServerMessage() { } public MratServerMessage(string user, string token): this(user, token, null) { } public MratServerMessage(string jsonMessage) : this("", "", jsonMessage) { } public MratServerMessage(string user, string token, string jsonMessage) { User = user; Token = token; if (!string.IsNullOrEmpty(jsonMessage)) { JsonMessages.Add(jsonMessage); } } public override Dictionary<string, string> ToDictionary() { var jsonMessage = "{}"; if (JsonMessages.Count == 1) { jsonMessage = JsonMessages[0]; } else if (JsonMessages.Count > 1) { jsonMessage = $"[{string.Join(",", JsonMessages)}]"; } return new Dictionary<string, string> { { "user", User }, { "token", Token }, { "doc", jsonMessage } }; } } }
C++
UTF-8
560
2.859375
3
[]
no_license
#include <iostream> #include <queue> using namespace std; int main() { int n,i,sum,val,cost; while(cin >> n && n>0){ priority_queue<int, vector<int>, greater<int> > queue; cost = 0; for(i=0;i<n;i++) { cin >> val; queue.push(val); } while (queue.size() > 1) { sum = queue.top(); queue.pop(); sum += queue.top(); queue.pop(); cost += sum; queue.push(sum); } cout << cost << endl; } return 0; }
Java
UTF-8
1,643
1.734375
2
[]
no_license
package com.ssm.mall.action.portal; import com.github.pagehelper.PageInfo; import com.ssm.mall.common.ServerRes; import com.ssm.mall.dao.vo.ProductDetailVo; import com.ssm.mall.service.iservice.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; @Controller @RequestMapping("product") public class ProductController { @Autowired ProductService productService; @ResponseBody @RequestMapping("detail.do") public ServerRes<ProductDetailVo> getDetail(Integer id){ return productService.getProductDetail(id); } @ResponseBody @RequestMapping("list.do") public ServerRes<PageInfo> listByKeyCategory(HttpSession session, @RequestParam(value = "keywords",required = false) String keywords, @RequestParam(value = "categoryId",required = false) Integer categoryId, @RequestParam(value = "pageNum",defaultValue = "1" )int pageNum, @RequestParam(value = "pageSize",defaultValue = "10" )int pageSize, @RequestParam(value = "orderBy",defaultValue = "") String orderBy) { return productService.listByKeyCategory(keywords,categoryId,pageNum,pageSize,orderBy); } }
Java
UTF-8
2,277
2.65625
3
[]
no_license
package pool_scheduler.tests; import static org.junit.Assert.*; import java.util.NoSuchElementException; import org.junit.After; import org.junit.Before; import org.junit.Test; import pool_scheduler.resources.Cubicle; import pool_scheduler.resources.CubiclePool; import pool_scheduler.resources.Resource; public class TestResourcePool { protected CubiclePool resourcePool; protected int size = 3; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { resourcePool = new CubiclePool(size); for(int i=0; i<3; i++){ resourcePool.addResource(new Cubicle("cubiclePool "+ i)); } } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { resourcePool = null; } @Test public void testAddResource() { assertTrue(resourcePool.getCapacity() == 3); assertTrue(resourcePool.getResources().size() == 3); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testAddResourceWidthArrayIndexOutOfBoundsException() { resourcePool.addResource(new Cubicle("cubiclePool 42")); } @Test public void testProvideResource() { Resource r = resourcePool.provideResource(resourcePool.getFirstResource()); assertNotNull(r); } @Test(expected = IllegalArgumentException.class) public void testProvideResourceWidthIllegalArgumentException() { resourcePool.provideResource(new Cubicle("cubiclePool 100")); } @Test(expected = NoSuchElementException.class) public void testProvideResourceWidthNoSuchElementException() { Cubicle r = resourcePool.provideResource(resourcePool.getFirstResource()); assertNotNull(r); resourcePool.provideResource(r); } @Test public void testFreeResource() { Cubicle r = resourcePool.provideResource(resourcePool.getFirstResource()); assertNotNull(r); assertTrue(resourcePool.getUsedResources().size() == 1); resourcePool.freeResource(r); assertTrue(resourcePool.getUsedResources().size() == 0); } @Test public void testGetNTotalResource() { assertTrue(resourcePool.getNTotalResource() == 3); } @Test public void testGetNAvailableResource() { assertTrue(resourcePool.getNTotalResource() == 3); } @Test public void testGetNUsedResource() { assertTrue(resourcePool.getNUsedResource() == 0); } }
Python
UTF-8
1,114
2.546875
3
[]
no_license
# coding:utf8 # Time:2020-07-04 20:41 # Author:TSL from selenium import webdriver import time def delAllTeacher(): driver = webdriver.Chrome("D:\\ruanjiananzhuang\chromedriver.exe") driver.get("http://localhost/mgr/login/login.html") driver.implicitly_wait(5) #用户名 # driver.find_element_by_id("username").send_keys("auto") #密码 # driver.find_element_by_id("password").send_keys("sdfsdfsdf") #点击登录 driver.find_element_by_css_selector(".btn.btn-success").click() #点击切换老师界面 driver.find_element_by_css_selector(".nav.navbar-nav li:nth-child(2)").click() #删除按钮列表 del_list = driver.find_elements_by_css_selector("tbody>.ng-scope td:nth-child(6) button:nth-child(2)") for i in range(len(del_list)): del_list1 = driver.find_elements_by_css_selector("tbody>.ng-scope td:nth-child(6) button:nth-child(2)") del_list1[0].click() driver.find_element_by_css_selector(".btn.btn-primary").click() time.sleep(1) driver.quit() delAllTeacher()
Java
UTF-8
6,790
2.375
2
[ "MIT" ]
permissive
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import model.Usuario; import email.Email; public class UsuarioDAO { public int criar(Usuario usuario) { System.out.print(usuario.toString()); String sqlInsert = "INSERT INTO ajudaSJ.usuario(nome, email, cidade, estado, ra, senha, codMateriaBoa, foto) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; // usando o try with resources do Java 7, que fecha o que abriu try (Connection conn = ConnectionFactory.obtemConexao(); PreparedStatement stm = conn.prepareStatement(sqlInsert);) { stm.setString(1, usuario.getNome()); stm.setString(2, usuario.getEmail()); stm.setString(3, usuario.getCidade()); stm.setString(4, usuario.getEstado()); stm.setString(5, usuario.getRa()); System.out.print(usuario.getSenha()); stm.setString(6, usuario.getSenha()); stm.setInt(7, usuario.getCodMateriaBoa()); stm.setString(8, "icone-usuario.png"); stm.execute(); String sqlQuery = "SELECT LAST_INSERT_ID()"; Email.emailBoasVindas(usuario); try (PreparedStatement stm2 = conn.prepareStatement(sqlQuery); ResultSet rs = stm2.executeQuery();) { if (rs.next()) { usuario.setId(rs.getInt(1)); } } catch (SQLException e) { e.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } return usuario.getId(); } public void atualizar(Usuario usuario) { String sqlUpdate = "UPDATE usuario SET nome=?, email=?, cidade=?, estado=?, ra=?, senha=?, codMateriaBoa=?, foto=?, adm=? WHERE codUsuario=?"; // usando o try with resources do Java 7, que fecha o que abriu try (Connection conn = ConnectionFactory.obtemConexao(); PreparedStatement stm = conn.prepareStatement(sqlUpdate);) { System.out.println("Usuario vai ser atualizado para: " +usuario.toString()); stm.setString(1, usuario.getNome()); stm.setString(2, usuario.getEmail()); stm.setString(3, usuario.getCidade()); stm.setString(4, usuario.getEstado()); stm.setString(5, usuario.getRa()); stm.setString(6, usuario.getSenha()); stm.setInt(7, usuario.getCodMateriaBoa()); stm.setString(8, usuario.getFoto()); stm.setString(9, usuario.getAdm()); stm.setInt(10, usuario.getId()); stm.execute(); //Email.alteracaoDados(usuario); } catch (Exception e) { e.printStackTrace(); } } public void excluir(Usuario usuario) { String sqlDelete = "DELETE FROM usuario WHERE usuario.email = ?"; // usando o try with resources do Java 7, que fecha o que abriu try (Connection conn = ConnectionFactory.obtemConexao(); PreparedStatement stm = conn.prepareStatement(sqlDelete);) { stm.setString(1, usuario.getEmail()); stm.execute(); Email.avisoExclusao(usuario); } catch (Exception e) { e.printStackTrace(); } } public Usuario carregar(String email) { Usuario usuario = new Usuario(); usuario.setEmail(email); String sqlSelect = "SELECT nome, codUsuario, senha, cidade, estado, ra, codMateriaBoa, foto, adm FROM usuario WHERE usuario.email = ?"; // usando o try with resources do Java 7, que fecha o que abriu try (Connection conn = ConnectionFactory.obtemConexao(); PreparedStatement stm = conn.prepareStatement(sqlSelect);) { stm.setString(1, usuario.getEmail()); try (ResultSet rs = stm.executeQuery();) { if (rs.next()) { usuario.setNome(rs.getString("nome")); usuario.setId(rs.getInt("codUsuario")); usuario.setCidade(rs.getString("cidade")); usuario.setEstado(rs.getString("estado")); usuario.setRa(rs.getString("ra")); usuario.setCodMateriaBoa(rs.getInt("codMateriaBoa")); usuario.setSenha(rs.getString("senha")); usuario.setFoto(rs.getString("foto")); usuario.setAdm(rs.getString("adm")); } else { usuario.setId(-1); usuario.setNome(null); usuario.setEmail(null); usuario.setCidade(null); usuario.setEstado(null); usuario.setRa(null); usuario.setCodMateriaBoa(-1); } } catch (SQLException e) { e.printStackTrace(); } } catch (SQLException e1) { System.out.print(e1.getStackTrace()); } return usuario; } public Usuario carregar(int id) { Usuario usuario = new Usuario(); usuario.setId(id); String sqlSelect = "SELECT nome, email, senha, cidade, estado, ra, codMateriaBoa, foto, adm FROM usuario WHERE usuario.codUsuario= ?"; try (Connection conn = ConnectionFactory.obtemConexao(); PreparedStatement stm = conn.prepareStatement(sqlSelect);) { stm.setInt(1, usuario.getId()); try (ResultSet rs = stm.executeQuery();) { if (rs.next()) { usuario.setNome(rs.getString("nome")); usuario.setEmail(rs.getString("email")); usuario.setCidade(rs.getString("cidade")); usuario.setEstado(rs.getString("estado")); usuario.setRa(rs.getString("ra")); usuario.setCodMateriaBoa(rs.getInt("codMateriaBoa")); usuario.setSenha(rs.getString("senha")); usuario.setFoto(rs.getString("foto")); usuario.setAdm(rs.getString("adm")); } else { usuario.setId(-1); usuario.setNome(null); usuario.setEmail(null); usuario.setCidade(null); usuario.setEstado(null); usuario.setRa(null); usuario.setCodMateriaBoa(-1); } } catch (SQLException e) { e.printStackTrace(); } } catch (SQLException e1) { System.out.print(e1.getStackTrace()); } return usuario; } public ArrayList<Usuario> buscarAlunosMateria(int codMateriaBoa) { Usuario usuario = new Usuario(); ArrayList<Usuario> colecaoUsuario = new ArrayList<>(); usuario.setCodMateriaBoa(codMateriaBoa); String sqlSelect = "SELECT nome, codUsuario, senha, cidade, estado, ra, codMateriaBoa, foto FROM usuario WHERE usuario.codMateriaBoa = ?"; // usando o try with resources do Java 7, que fecha o que abriu try (Connection conn = ConnectionFactory.obtemConexao(); PreparedStatement stm = conn.prepareStatement(sqlSelect);) { stm.setInt(1, usuario.getCodMateriaBoa()); try (ResultSet rs = stm.executeQuery();) { while (rs.next()) { Usuario u = new Usuario(); u.setNome(rs.getString("nome")); u.setId(rs.getInt("codUsuario")); u.setCidade(rs.getString("cidade")); u.setEstado(rs.getString("estado")); u.setRa(rs.getString("ra")); u.setCodMateriaBoa(rs.getInt("codMateriaBoa")); u.setSenha(rs.getString("senha")); u.setFoto(rs.getString("foto")); System.out.println("Buscando Professores: " + u.toString()); colecaoUsuario.add(u); } } catch (SQLException e) { e.printStackTrace(); } } catch (SQLException e1) { System.out.print(e1.getStackTrace()); } return colecaoUsuario; } }