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
496
2.109375
2
[]
no_license
package by.it.dubatovka.project_helpdesk.java; import by.it.dubatovka.project_helpdesk.java.beans.User; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public class CmdLogout extends Action { @Override Action execute(HttpServletRequest req) { HttpSession session=req.getSession(); User user =(User)session.getAttribute("user"); if (user!=null)req.setAttribute(Messages.msgMessage,"Login"); return null; } }
JavaScript
UTF-8
5,389
3.015625
3
[]
no_license
/** * Base object that owns the events subsystem * * usage: after object declaration add: * "ObjectConstructorName.prototype = new BasiinObjectPrototype ();" * At object instantiation call addEvents(obj) where `obj` is an object that * holds the event names eg: {onLoad:fn, onComplete:otherFn} * * whenever an event happens just call event('eventName' [, "metadata"]) * eg: event("AfterInitialize") */ function BasiinObjectPrototype () { /*************************** Hidden Properties ****************************/ var bop = this; /*********************** Utils ******************************/ /** * Uppercase the first char of str */ this.ucFirst = function (str){return str.substr(0,1).toUpperCase()+ str.substr(1);} this.lcFirst = function (str){return str.substr(0,1).toLowerCase()+ str.substr(1);} /*********************** Events subsytem ******************************/ var events = {} /** * return an initialized event funcitonObject listening to all events * its parent object has (only the partens) */ this.addEvents = function (object, forceParrent) { var that = (forceParrent)?forceParrent:this; return new _constructEventSystem(object, that) ; } /** * Constructor for the event function object * */ function _constructEventSystem(eventsObject, parent){ var _events =[] var _parent = parent; var _callerId = "undefined caller Obj"; if (typeof parent.uPhrase=== 'string') _callerId = parent.uPhrase else if (typeof parent.uPhrase=== 'function') _callerId = parent.uPhrase() function _raise (fn, event) { var title=''; title+=(typeof event === 'object' && event.caller)? event.caller+ ' fired ':''; title+= (typeof event === 'object' && event.name)? event.name:'undefined event name'; if (typeof event === 'object' && event.meta) title += meta _log( title , 3); var result = _execfn(fn,event); return result; } /** * returns the value of the event computation or undefined if no * computation happened. returns false if an error ocured */ function _execfn(fn, event){ // try{ if (typeof fn === 'function') return fn(event); else if (typeof fn === 'string') { if ( event.object && event.object["fn"] && typeof event.object["fn"] === 'function') return event.object[fn](event); else return eval(fn); } // }catch(e){ // _log('event failed'); // console.log(e); // return false; // } return undefined; } function _proxy(fn, args) { return eval("("+ fn+ ")")(args); } /** * Raise the on`name` event eg: bop.event("Load") -> onLoad * * will check metadata if an event position is specified (eg: 'BEFORE', "after") * * Returns either the return value of the event's function or undefined * if no function was defined or false if something went wrong * this is being executed in the parent's scope */ function event (name, metadata){ name = bop.ucFirst(name); if(_events['on'+name]) { var event={ 'meta':metadata, 'name':name, 'caller':_callerId, 'object':this, 'basiin':basiin, //allow alien scopes access to basiin 'proxy': _proxy } return _raise(_events['on'+name], event) } //if event doesn't exist _log( _callerId+ ' fired on'+name+ '. No hook!', 4); return undefined; //undefined events return undefined in stead of false } event.add = function(object, force) { //filter event properties out of the rest for (var p in object) if (p.substr(0,2) == 'on' && p.substr(2,1).match(/[A-Z]{1}/)) { var eventName = p; //DEPRECATED: turn "onLoad" to "onAfterLoad" if (!bop.lcFirst(eventName).match(/^onAfter/) && !bop.lcFirst(eventName).match(/^onBefore/)) eventName= 'onAfter'+ bop.ucFirst(p.substr(2)); //append if non existing or forced if ( object[p] && (events[eventName] === undefined || force) ) _events[eventName] = object[p]; } } event.exists = function(str) {return (_events[str] == undefined);} event.events = function (){ var es = {} for(var e in _events) es[e] = _events[e]; return es; } event.add(eventsObject); return event; } }
JavaScript
UTF-8
1,031
2.515625
3
[]
no_license
const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const departmentSchmema = mongoose.Schema({ admin_id:{ type:String, required:true }, department_name:{ type:String, required:true }, department_id:{ type:String, unique:true, required:true, }, department_password:{ type:String, required:true } }) departmentSchmema.pre('save',async function(next){ const hash = await bcrypt.hash(this.department_password,10) this.department_password = hash; next(); }) departmentSchmema.methods.isPasswordValid = async function(password){ user = this; console.log(password); bcrypt.compare(password, department.department_password,(err,result)=>{ if(result){ console.log("hlfkgkfkg"); return result } else { return err; } }); } module.exports = mongoose.model('departments',departmentSchmema);
TypeScript
UTF-8
294
3.640625
4
[]
no_license
interface A<T>{ T1: T } interface B{ T2: number } interface C extends A<string>, B{ T3:number[] } const u:C = { //u变量必须同时实现interface A, interface B, interface C T1:'text', T2:123, T3: [1,2,3] } console.log('123') console.log('456') console.log('789')
C#
UTF-8
1,802
2.96875
3
[ "BSD-3-Clause" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Framework { using System.Web.UI; public static class WebExtensions { public static T FindControlByID<T>(this Control container, string id) where T : Control { return container.FindChildren<T>(c => c.ID.Equals(id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); } public static ICollection<T> FindChildren<T>(this Control element) where T : Control { return FindChildren<T>(element, null); } public static bool HasChildren<T>(this Control element, Func<T, bool> condition) where T : Control { return FindChildren(element, condition).Count != 0; } public static ICollection<T> FindChildren<T>(this Control element, Func<T, bool> condition) where T : Control { List<T> results = new List<T>(); FindChildren(element, condition, results); return results; } private static void FindChildren<T>(Control element, Func<T, bool> condition, ICollection<T> results) where T : Control { if (element != null) { int childrenCount = element.Controls.Count; for (int i = 0; i < childrenCount; i++) { Control child = element.Controls[i]; T t = child as T; if (t != null) { if (condition == null) results.Add(t); else if (condition(t)) results.Add(t); } FindChildren(child, condition, results); } } } } }
Java
UTF-8
1,037
2.28125
2
[]
no_license
package com.my3w.farm.activity.icamera.entity; public class CameraEntity { private String name; private String uid; private String username; private String userpass; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpass() { return userpass; } public void setUserpass(String userpass) { this.userpass = userpass; } @Override public String toString() { return "CameraEntity{" + "name='" + name + '\'' + ", uid='" + uid + '\'' + ", username='" + username + '\'' + ", userpass='" + userpass + '\'' + '}'; } }
C#
UTF-8
4,249
2.6875
3
[]
no_license
using System; using System.IO; using System.Runtime.Serialization; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; namespace SamplesTestProyect.AsyncAwait { [TestClass] public class AsyncAwaitTests { [TestMethod] public async Task UltraSimpleAsyncTest() { var data = await ReadStringAsync(); Assert.AreEqual(data, "Prueba"); Directory.GetCurrentDirectory(); } [TestMethod] public void ReadSync() { var data = ReadStringAsync().Result; Assert.AreEqual(data, "Prueba"); } [TestMethod] public async Task TestReadFileAsync() { var data = await ReadFileAsync(); Assert.AreEqual(data, "Texto de ejemplo"); Directory.GetCurrentDirectory(); } [TestMethod] public async Task HandleExceptionAsyncSinAwait() { bool hapetao = false; try { var data = await PetarAsyncSinAwait(); } catch (MyCustomTestException) { Assert.Fail("Por aqui lamentablemente NO debería pasar"); } catch (Exception ex) { hapetao = true; Assert.IsTrue(ex is AggregateException); Assert.IsTrue(ex.InnerException is MyCustomTestException); } Assert.IsTrue(hapetao); } [TestMethod] [ExpectedException(typeof(AggregateException))] public void HandleExceptionAsync2SinAwait() { var task = PetarAsyncSinAwait(); task.Wait(); var result = task.Result; } [TestMethod] public async Task HandleExceptionAsync() { bool hapetao = false; try { var data = await PetarAsync(); } catch (MyCustomTestException cex) { hapetao = true; Assert.IsTrue(cex is MyCustomTestException); } catch (Exception) { Assert.Fail("Por aqui lamentablemente NO debería pasar"); } Assert.IsTrue(hapetao); } [TestMethod] [ExpectedException(typeof(MyCustomTestException))] public async Task HandleExceptionAsync2() { await PetarAsync(); } private async Task<string> ReadStringAsync() { return await Task.Factory.StartNew(() => "Prueba"); } private async Task<string> PetarAsyncSinAwait() { var task = Task<string>.Factory.StartNew(() => { throw new MyCustomTestException(); }); return task.Result; } private async Task<string> PetarAsync() { return await Task<string>.Factory.StartNew(() => { throw new MyCustomTestException(); }); } private async Task<string> ReadFileAsync() { using (var reader = new StreamReader("AsyncAwait\\ejemplo.txt")) { string data = await reader.ReadToEndAsync(); return data; } } } [Serializable] public class MyCustomTestException : Exception { // // For guidelines regarding the creation of new exception types, see // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp // and // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp // public MyCustomTestException() { } public MyCustomTestException(string message) : base(message) { } public MyCustomTestException(string message, Exception inner) : base(message, inner) { } protected MyCustomTestException( SerializationInfo info, StreamingContext context) : base(info, context) { } } }
C#
UTF-8
806
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domain { public class Customer { private int id; private string name; private string address; private int zip; private string town; private string telephone; public int Id { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; } } public string Address { get { return address; } set { address = value; } } public int ZIP { get { return zip; } set { zip = value; } } public string Town { get { return town; } set { town = value; } } public string Telephone { get { return telephone; } set { telephone = value; } } } }
C
UTF-8
421
3.21875
3
[]
no_license
/*program to diaplay no of days in the month depending on user input*/ #include<stdio.h> int main(){ int a; printf("enter the no of the month"); scanf("%d",&a); switch(a){ case 1: case 3:case 5:case 7:case 8:case 10:case 12:printf("no of days are 31"); break; case 4:case 6:case 9:case 11:printf("no of days are 30"); break; case 2:printf("no of days are 28 or 29"); break; default:printf("wrong no entered"); } }
JavaScript
UTF-8
1,827
3.46875
3
[]
no_license
var parksList = document.querySelector('#parksList'); var searchBox = document.querySelector('#searchBox'); var parksPromise; function makeParksList(data) { data.forEach(park => { console.log("makeParksList Ran") var search = searchBox.textContent; if (search === null) { createAndAppendElement(park) } else if (park.description.includes(search) || park.ParkName.includes(search) ) { createAndAppendElement(park) } }); } function createAndAppendElement(park) { //Create Header var header = document.createElement('H1'); header.classList.toggle('header'); header.textContent = park.parkName; parksList.appendChild(header); //Borough var borough = document.createElement('P'); borough.innerHTML = `<em>Borough</em>: ${park.borough}`; parksList.appendChild(borough); //Acres var acres = document.createElement('P'); acres.innerHTML = `<em>Acres</em>: ${park.acres}`; parksList.appendChild(acres); //Description var description = document.createElement('P'); description.innerHTML = `<em>Description</em><br><br>${park.description}`; parksList.appendChild(description); //Horizontal rule var hr = document.createElement('HR'); parksList.appendChild(hr) } function getParks() { parksList.textContent = '' fetch('parksAJAX') .then(response => response.json()) .then((data) => { console.log(data) makeParksList(data) //searchBox.addEventListener('keyup', makeParksList(data)) }); } parksList.textContent = ""; getParks(); searchBox.addEventListener('keyup', function (e) { if (e.code === 'Enter') { e.preventDefault(); console.log("search function ran") getParks() } });
Java
ISO-8859-1
2,193
2.84375
3
[]
no_license
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import util.Funcoes; public class PedidoPage { private WebDriver driver; // variavel padrao para todas as classes de paginas public PedidoPage(WebDriver driver) { // construtor padro para todas as classes de pginas this.driver = driver; } private By textoPedidoConfirmado = By.cssSelector("#content-hook_order_confirmation h3"); private By email = By.cssSelector("#content-hook_order_confirmation p"); private By totalProdutos = By.cssSelector("div.order-confirmation-table div.order-line div.row div.bold"); private By totalTaxIncl = By.cssSelector("div.order-confirmation-table table tr.total-value td:nth-child(2)"); private By metodoPagamento = By.cssSelector("#order-details ul li:nth-child(2)"); public String obter_textoPedidoConfirmado() { return driver.findElement(textoPedidoConfirmado).getText(); } public String obter_email() { // mtodo // marcelo@teste.com---- texto final que ser devolvido apos a remoo da outra // parte do texto String texto = driver.findElement(email).getText();// String texto ------- variavel que est sendo recuperada texto = Funcoes.removeTexto(texto, "An email has been sent to the "); // texto que vai servir como base ---- // variavel "texto" e texto "inicial " // que ser removido "An email has been // sent to the" ------ texto = Funcoes.removeTexto(texto, " address."); // texto para remover ------ texto "final" --- "address." return texto; // retorna no final o texto esperado ------- email ----- "marcelo@teste.com" } public Double obter_totalProdutos() { // mtodo que retira o $ (Cifrao) e devolve o valor apenas como double ------ // $ 38.24 ----- devolve 38.24 ----- return Funcoes.removeCifraoDevolveDouble(driver.findElement(totalProdutos).getText()); } public Double obter_totalTaxIncl() { return Funcoes.removeCifraoDevolveDouble(driver.findElement(totalTaxIncl).getText()); } public String obter_metodoPagamento() { return Funcoes.removeTexto(driver.findElement(metodoPagamento).getText(), "Payment method: Payments by "); } }
Java
UTF-8
4,149
1.742188
2
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2018 572682 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package us.dot.its.jpo.ode.importer.parser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Test; import mockit.Injectable; import mockit.Tested; import us.dot.its.jpo.ode.importer.parser.FileParser.FileParserException; import us.dot.its.jpo.ode.importer.parser.FileParser.ParserStatus; import us.dot.its.jpo.ode.model.OdeLogMetadata.SecurityResultCode; import us.dot.its.jpo.ode.util.CodecUtils; public class SecResultCodeParserTest { @Tested SecurityResultCodeParser secResultCodeParser; @Injectable long bundleId; /** * Should extract securityResultCode and return ParserStatus.COMPLETE */ @Test public void testAll() { ParserStatus expectedStatus = ParserStatus.COMPLETE; int expectedStep = 0; byte[] buf = new byte[] { (byte)0x00, //0. securityResultCode }; BufferedInputStream testInputStream = new BufferedInputStream(new ByteArrayInputStream(buf)); try { assertEquals(expectedStatus, secResultCodeParser.parseFile(testInputStream, "testLogFile.bin")); assertEquals(SecurityResultCode.success, secResultCodeParser.getSecurityResultCode()); assertEquals(expectedStep, secResultCodeParser.getStep()); ByteArrayOutputStream os = new ByteArrayOutputStream(); secResultCodeParser.writeTo(os); assertEquals(CodecUtils.toHex(buf), CodecUtils.toHex(os.toByteArray())); } catch (FileParserException | IOException e) { fail("Unexpected exception: " + e); } } /** * Test securityResultCode = unknown */ @Test public void testSecurityResultCodeUnknown() { ParserStatus expectedStatus = ParserStatus.COMPLETE; int expectedStep = 0; BufferedInputStream testInputStream = new BufferedInputStream( new ByteArrayInputStream(new byte[] { (byte)0x01, //0. securityResultCode })); try { assertEquals(expectedStatus, secResultCodeParser.parseFile(testInputStream, "testLogFile.bin")); assertEquals(SecurityResultCode.unknown, secResultCodeParser.getSecurityResultCode()); assertEquals(expectedStep, secResultCodeParser.getStep()); } catch (FileParserException e) { fail("Unexpected exception: " + e); } } /** * Test securityResultCode failure */ @Test public void testSecurityResultCodeFailure() { ParserStatus expectedStatus = ParserStatus.COMPLETE; int expectedStep = 0; BufferedInputStream testInputStream = new BufferedInputStream( new ByteArrayInputStream(new byte[] { (byte)0x02, //0. securityResultCode })); try { assertEquals(expectedStatus, secResultCodeParser.parseFile(testInputStream, "testLogFile.bin")); assertEquals(SecurityResultCode.inconsistentInputParameters, secResultCodeParser.getSecurityResultCode()); assertEquals(expectedStep, secResultCodeParser.getStep()); } catch (FileParserException e) { fail("Unexpected exception: " + e); } } }
Java
UTF-8
296
2.171875
2
[]
no_license
package com.mm.zb.utils; import java.math.BigDecimal; /** * Creat by ZB * 2019-02-23 0:48 */ public class EarnUtils { public static BigDecimal yesterdayEarn(BigDecimal b) { BigDecimal a = new BigDecimal(3650.00); BigDecimal c = b.divide(a, 2); return c; } }
PHP
UTF-8
901
2.921875
3
[ "MIT" ]
permissive
<?php namespace Awethemes\Database; use Database\Query\Builder; use Database\Query\Grammars\MySqlGrammar; class Grammar extends MySqlGrammar { /** * {@inheritdoc} */ public function parameter( $value ) { if ( $this->isExpression( $value ) ) { return $this->getValue( $value ); } if ( is_numeric( $value ) ) { return is_float( $value ) ? '%f' : '%d'; } return '%s'; } /** * {@inheritdoc} */ protected function whereBetween( Builder $query, $where ) { $between = $where['not'] ? 'not between' : 'between'; return $this->wrap( $where['column'] ) . ' ' . $between . ' %s and %s'; } /** * {@inheritdoc} */ protected function compileJoinConstraint( array $clause ) { $first = $this->wrap( $clause['first'] ); $second = $clause['where'] ? '%s' : $this->wrap( $clause['second'] ); return "{$clause['boolean']} $first {$clause['operator']} $second"; } }
Java
UTF-8
1,074
2.671875
3
[]
no_license
package com.examplemobileappcompany.projectprep4thread; import android.app.Activity; import org.greenrobot.eventbus.EventBus; /** * Created by admin on 8/11/2017. */ public class ThreadImpl extends Thread { MainActivity activity; public ThreadImpl(MainActivity activity){ this.activity = activity; } @Override public void run() { final String prefix = "used Thread Class, "; Event event = new Event(prefix + "sent by EventBus"); EventBus.getDefault().post(event); activity.runOnUiThread( new Runnable() { @Override public void run() { activity.setRunOnUiText(prefix + "sent by runOnUiThread"); } } ); activity.handler.post( new Runnable() { @Override public void run() { activity.setHandlerText(prefix + "sent by Handler"); } } ); } }
Java
UTF-8
5,173
2.140625
2
[]
no_license
package com.gkzxhn.gkprison.userport.activity; import android.app.ProgressDialog; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import com.gkzxhn.gkprison.R; import com.gkzxhn.gkprison.base.BaseActivity; import com.gkzxhn.gkprison.userport.adapter.ShoppingAdapter; import com.gkzxhn.gkprison.userport.bean.Cart; import com.gkzxhn.gkprison.userport.bean.Commodity; import com.gkzxhn.gkprison.utils.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import rx.Observable; /** * 购物记录 */ public class ShoppingRecoderActivity extends BaseActivity { private ImageView iv_nothing; private ListView lv_shoppingrecoder; private ShoppingAdapter adapter; private List<Cart> carts = new ArrayList<>(); private SQLiteDatabase db = StringUtils.getSQLiteDB(this); private ProgressDialog loading_dialog; @Override protected View initView() { View view = View.inflate(getApplicationContext(), R.layout.activity_shopping_recoder, null); lv_shoppingrecoder = (ListView) view.findViewById(R.id.lv_shopping_recode); iv_nothing = (ImageView) view.findViewById(R.id.iv_nothing); return view; } @Override protected void initData() { setTitle("购物记录"); setBackVisibility(View.VISIBLE); getShoppingRecoder(); } /** * 获取购物记录 */ private void getShoppingRecoder() { initAndShowDialog(); getData(); } private void getData() { new Thread(){ @Override public void run() { carts.clear(); String sql = "select * from Cart where isfinish = 1 and remittance = 0"; Cursor cursor = db.rawQuery(sql, null); while (cursor.moveToNext()) { Cart cart = new Cart(); cart.setId(cursor.getInt(cursor.getColumnIndex("id"))); cart.setCount(cursor.getInt(cursor.getColumnIndex("count"))); cart.setTime(cursor.getString(cursor.getColumnIndex("time"))); cart.setOut_trade_no(cursor.getString(cursor.getColumnIndex("out_trade_no"))); cart.setFinish(cursor.getInt(cursor.getColumnIndex("isfinish"))); cart.setTotal_money(cursor.getString(cursor.getColumnIndex("total_money"))); carts.add(cart); } sort();// 排序 for (int i = 0; i < carts.size(); i++) { List<Commodity> commodities = new ArrayList<>(); int cart_id = carts.get(i).getId(); String sql1 = "select distinct line_items.qty,line_items.price,line_items.title from line_items,Cart where Cart.isfinish = 1 and line_items.cart_id = " + cart_id; Cursor cursor1 = db.rawQuery(sql1, null); while (cursor1.moveToNext()) { Commodity commodity = new Commodity(); commodity.setTitle(cursor1.getString(cursor1.getColumnIndex("title"))); commodity.setPrice(cursor1.getString(cursor1.getColumnIndex("price"))); commodity.setQty(cursor1.getInt(cursor1.getColumnIndex("qty"))); commodities.add(commodity); } carts.get(i).setCommodityList(commodities); } showUI(); } }.start(); } private void showUI() { runOnUiThread(new Runnable() { @Override public void run() { if(loading_dialog.isShowing()) loading_dialog.dismiss(); if(carts.size() == 0){ iv_nothing.setVisibility(View.VISIBLE); }else { iv_nothing.setVisibility(View.GONE); if(adapter == null){ adapter = new ShoppingAdapter(ShoppingRecoderActivity.this, carts); lv_shoppingrecoder.setAdapter(adapter); }else { adapter.notifyDataSetChanged(); } } } }); } /** * 排序 */ private void sort() { Collections.sort(carts, new Comparator<Cart>() { @Override public int compare(Cart lhs, Cart rhs) { int heat1 = lhs.getId(); int heat2 = rhs.getId(); if (heat1 < heat2) { return 1; } return -1; } }); } /** * 初始化并且显示加载对话框 */ private void initAndShowDialog() { loading_dialog = new ProgressDialog(this); loading_dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); loading_dialog.setMessage("加载中..."); loading_dialog.show(); } }
JavaScript
UTF-8
1,013
2.671875
3
[]
no_license
export function jsonParse (value) { if (value) { try { return JSON.parse(value); } catch (e) { return null; } } return value; } export function queryStringParse (locationSearch) { const search = locationSearch.substring(1); const json = '{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}'; return jsonParse(json) || {}; } export function isInViewPort (ref) { if (ref.current === null) return false; const bounding = ref.current.getBoundingClientRect(); return ( bounding.top >= 0 && bounding.top <= (window.innerHeight || document.documentElement.clientHeight) ); } export function isInViewportPercentage (ref, percentage) { if (ref.current === null) return false; const bounding = ref.current.getBoundingClientRect(); const screenPercentage = percentage * (window.innerHeight || document.documentElement.clientHeight); return ( bounding.bottom >= screenPercentage && bounding.top <= screenPercentage ); }
Python
UTF-8
2,498
3.390625
3
[]
no_license
print(''' ******************************************************************************* | | | | _________|________________.=""_;=.______________|_____________________|_______ | | ,-"_,="" `"=.| | |___________________|__"=._o`"-._ `"=.______________|___________________ | `"=._o`"=._ _`"=._ | _________|_____________________:=._o "=._."_.-="'"=.__________________|_______ | | __.--" , ; `"=._o." ,-"""-._ ". | |___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________ | |o`"=._` , "` `; .". , "-._"-._; ; | _________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______ | | |o; `"-.o`"=._`` '` " ,__.--o; | |___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________ ____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____ /______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_ ____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____ /______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_ ____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____ /______/______/______/______/______/______/______/______/______/______/_____ / ******************************************************************************* ''') print("Welcome to Treasure Island.") print("Your mission is to find the treasure.") option_one = input("You are at a cross road, do you want to go left or right?").lower() if option_one == "left": option_two = input("You've arrive at a lake with an island in the middle. Do you want to swim or wait for a boat, remeber time is ticking?").lower() if option_two == "wait": option_three = input("Good decision you made it to the island safely. There is a house with three doors choose between red, blue or yellow?").lower() if option_three == 'red': print("you got burned by fire. Game Over") elif option_three == 'yellow': print("You found the treasure! You Win!") elif choice3 == "blue": print("You enter a room of beasts. Game Over.") else: print("You chose a door that doesn't exist. Game Over.") else: print("Oh no you fell in a hole, Game Over!!") else: print("Yikes you got eatten by sharks, Game Over!!")
TypeScript
UTF-8
2,596
3.046875
3
[ "MIT" ]
permissive
/** * This file is part of spy4js which is released under MIT license. * * The LICENSE file can be found in the root directory of this project. * */ import { Spy } from '../../src/spy'; const IRL = { saveTheWorld: () => 'feed some koalas', doWithTree: (action: string) => `${action} the tree`, giveBanana: (to: string) => `Give ${to} a banana`, }; const Matrix = { tearDown: () => 1337, startup: () => 1 }; // you may and should initialize all mocks outside of your "describe" // the reason is: Once a Mock was created it will be initialized by // any other describe on calling "initMocks". This might lead to // confusion when the mock was created within a certain describe block // the next line does not modify the object IRL, but saves the reference const IRL$Mock = Spy.mock(IRL, 'saveTheWorld', 'giveBanana'); const Matrix$Mock = Spy.mock(Matrix, 'startup'); describe('Spy - Global- Mocks', () => { it('IRL$Mock: did mock the methods and applied spies', () => { IRL$Mock.saveTheWorld.returns('saved it!'); expect(IRL.saveTheWorld()).toBe('saved it!'); expect(IRL.doWithTree('burn')).toBe('burn the tree'); expect(IRL.giveBanana('Mike')).toBe(undefined); expect((IRL$Mock as any).doWithTree).toBe(undefined); IRL$Mock.saveTheWorld.wasCalled(1); IRL$Mock.giveBanana.hasCallHistory('Mike'); }); it('Matrix$Mock: did mock the methods and applied spies', () => { Matrix$Mock.startup.returns('done'); expect(Matrix.startup()).toBe('done'); expect(Matrix.tearDown()).toBe(1337); expect((Matrix$Mock as any).tearDown).toBe(undefined); Matrix$Mock.startup.wasCalled(1); }); }); const Guy = { swim: () => 'fish', goTo: (where: string) => 'go to --> ' + where, }; describe('Spy - Scoped - Mocks - 1', () => { const Guy$Mock = Spy.mock(Guy, 'swim'); it('Guy$Mock: mocks swim to return 42', () => { Guy$Mock.swim.returns(42); expect(Guy.swim()).toBe(42); expect(Guy.goTo('park')).toBe('go to --> park'); expect((Guy$Mock as any).goTo).toBe(undefined); Guy$Mock.swim.wasCalled(1); }); }); describe('Spy - Scoped - Mocks - 2', () => { const Guy$Mock = Spy.mock(Guy, 'swim', 'goTo'); it('Guy$Mock: mocks swim to return 12', () => { Guy$Mock.swim.returns(12); Guy$Mock.goTo.calls((s: any) => s); expect(Guy.swim()).toBe(12); expect(Guy.goTo('park')).toBe('park'); Guy$Mock.swim.wasCalled(1); Guy$Mock.goTo.hasCallHistory('park'); }); });
Python
UTF-8
808
2.875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Jun 27 23:01:45 2019 @author: juan """ import numpy as np import os import matplotlib.pyplot as plt #%% total_mediciones = [] files_list = os.listdir('.') tiempo, davs = [], [] files_list.pop(0) for s in files_list: data = np.load(s) tiempo.append(data[0]) davs.append(data[2]) print(len(davs[0])) #%% #print(tiempo,davs) plt.title ("Medicion de la señal del laser" "\n" "durante 45 minutos") plt.xlabel("Tiempo(s)") plt.ylabel("Voltaje(V)") plt.grid() plt.xlim(-0.006,-0.002) plt.ylim(-0.05,0.11) plt.plot(tiempo[0],davs[0],'-', color ="b") plt.plot(tiempo[20],davs[20],'-', color ="g") plt.plot(tiempo[30],davs[30],'-', color ="r") plt.plot(tiempo[44],davs[44],'-', color ="m") plt.legend(("1 Minuto","20 Minutos","30 Minutos","45 Minutos"))
Java
UTF-8
4,037
2.515625
3
[]
no_license
package com.exclusive.firmansp.crud; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.exclusive.firmansp.crud.domain.Siswa; import java.util.ArrayList; import java.util.List; /** * Created by firmansp on 09/11/15. */ public class DBAdapter extends SQLiteOpenHelper { private static final String DB_NAME = "perpus"; private static final String TABLE_NAME = "m_siswa"; private static final String COL_ID = "id"; private static final String COL_NAME = "nama"; private static final String COL_KELAS = "kelas"; private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME + ";"; private SQLiteDatabase sqliteDatabase = null; public DBAdapter(Context context) { super(context, DB_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { createTable(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(DROP_TABLE); } public void openDB() { if (sqliteDatabase == null) { sqliteDatabase = getWritableDatabase(); } } public void closeDB() { if (sqliteDatabase != null) { if (sqliteDatabase.isOpen()) { sqliteDatabase.close(); } } } public void createTable(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + COL_NAME + " TEXT," + COL_KELAS + " TEXT);"); } public void updateSiswa(Siswa siswa) { sqliteDatabase = getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COL_NAME, siswa.getNama()); cv.put(COL_KELAS, siswa.getKelas()); String whereClause = COL_ID + "==?"; String whereArgs[] = new String[] { siswa.getId() }; sqliteDatabase.update(TABLE_NAME, cv, whereClause, whereArgs); sqliteDatabase.close(); } public void save(Siswa siswa) { sqliteDatabase = getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_NAME, siswa.getNama()); contentValues.put(COL_KELAS, siswa.getKelas()); sqliteDatabase.insertWithOnConflict(TABLE_NAME, null, contentValues, SQLiteDatabase.CONFLICT_IGNORE); sqliteDatabase.close(); } public void delete(Siswa siswa) { sqliteDatabase = getWritableDatabase(); String whereClause = COL_ID + "==?"; String[] whereArgs = new String[] { String.valueOf(siswa.getId()) }; sqliteDatabase.delete(TABLE_NAME, whereClause, whereArgs); sqliteDatabase.close(); } public void deleteAll() { sqliteDatabase = getWritableDatabase(); sqliteDatabase.delete(TABLE_NAME, null, null); sqliteDatabase.close(); } public List<Siswa> getAllSiswa() { sqliteDatabase = getWritableDatabase(); Cursor cursor = this.sqliteDatabase.query(TABLE_NAME, new String[] { COL_ID, COL_NAME, COL_KELAS }, null, null, null, null, null); List<Siswa> siswas = new ArrayList<Siswa>(); if (cursor.getCount() > 0) { while (cursor.moveToNext()) { Siswa siswa = new Siswa(); siswa.setId(cursor.getString(cursor.getColumnIndex(COL_ID))); siswa.setNama(cursor.getString(cursor .getColumnIndex(COL_NAME))); siswa.setKelas(cursor.getString(cursor .getColumnIndex(COL_KELAS))); siswas.add(siswa); } sqliteDatabase.close(); return siswas; } else { sqliteDatabase.close(); return new ArrayList<Siswa>(); } } }
Java
UTF-8
2,247
2.28125
2
[ "MIT" ]
permissive
package jbse.algo.meta; import static jbse.algo.Util.failExecution; import static jbse.bc.Signatures.SUN_UNIXNATIVEDISPATCHER; import static jbse.common.Type.binaryClassName; import java.lang.reflect.Field; import java.util.function.Supplier; import jbse.algo.Algo_INVOKEMETA_Nonbranching; import jbse.algo.StrategyUpdate; import jbse.mem.State; import jbse.tree.DecisionAlternative_NONE; import jbse.val.Simplex; /** * Meta-level implementation of {@link sun.nio.fs.UnixNativeDispatcher#init()}. * * @author Pietro Braione */ public final class Algo_SUN_UNIXNATIVEDISPATCHER_INIT extends Algo_INVOKEMETA_Nonbranching { private Simplex capabilities; //set by cookMore @Override protected Supplier<Integer> numOperands() { return () -> 0; } @Override protected void cookMore(State state) { //we do not metacircularly invoke the method, //rather we ensure that sun.nio.fs.UnixNativeDispatcher //is loaded and initialized and peek the return //value from it try { final Class<?> class_SUN_UNIXNATIVEDISPATCHER = Class.forName(binaryClassName(SUN_UNIXNATIVEDISPATCHER)); final Field capabilitiesField = class_SUN_UNIXNATIVEDISPATCHER.getDeclaredField("capabilities"); capabilitiesField.setAccessible(true); final int capabilitiesInt = capabilitiesField.getInt(null); this.capabilities = this.ctx.getCalculator().valInt(capabilitiesInt); } catch (ClassNotFoundException e) { //this may happen with a badly misconfigured JBSE, which //is using a UNIX JRE but is running on a non-UNIX platform, //breaking the metacircularity hypothesis failExecution(e); } catch (NoSuchFieldException e) { //this may happen if the version of the JRE used by JBSE //is very different from the one we are currently assuming, //i.e., Java 8. AFAIK all Java 8 JREs should have this field failExecution(e); } catch (SecurityException | IllegalAccessException e) { //this should never happen //TODO I'm not quite sure that SecurityException can never be raised failExecution(e); } } @Override protected StrategyUpdate<DecisionAlternative_NONE> updater() { return (state, alt) -> { state.pushOperand(this.capabilities); }; } }
PHP
UTF-8
2,954
2.765625
3
[ "MIT" ]
permissive
<?php namespace ReverseGeocoderCache; class CacheClient { protected $cacheFrontEnd = false; protected $dataProvider = false; protected $profiler = false; public function setDataProvider($dataProvider) { $this->dataProvider = $dataProvider; } public function setCacheFrontEnd($frontEnd) { $this->cacheFrontEnd = $frontEnd; } public function setProfiler($val) { $this->profiler = $val; } protected function getProfiler() { return $this->profiler; } protected function startTimer($name) { $profiler = $this->getProfiler(); if ($profiler) { return $profiler->startTimer($name); } else { $obj = new class() { public function stop() { } }; return $obj; } } public function get($latitude, $longitude) { $timer = $this->startTimer('cache hit retrieval'); $cachedValue = $this->getData($latitude, $longitude); $timer->stop(); if (!$cachedValue) { $value = $this->produceData($latitude, $longitude); return $value; } else { $value = $cachedValue; if ('error' === $value['status']) { if ($value['timestamp'] + 3600 < time()) { return $this->produceData($latitude, $longitude); } else { throw new \Exception('We had stored a place-error in the cache client, and the timeout has not yet allowed for a new retrieval...'); } } else { return $value['payload']; } } } protected function produceData($latitude, $longitude) { $timer = $this->startTimer('producing data for geocache'); try { $data = $this->retrieveData($latitude, $longitude); } catch (\ErrorException $e) { $this->setData($latitude, $longitude, array( 'status' => 'error', 'timestamp' => time(), )); throw new \Exception('we did get a place-error from google'); } finally { $timer->stop(); } $timer = $this->startTimer('storing data in geocache'); $this->setData($latitude, $longitude, array( 'status' => 'ok', 'payload' => $data, )); $timer->stop(); return $data; } protected function setData($latitude, $longitude, $data) { $this->cacheFrontEnd->set($latitude, $longitude, json_encode($data)); } protected function getData($latitude, $longitude) { return json_decode($this->cacheFrontEnd->get($latitude, $longitude), true); } protected function retrieveData($latitude, $longitude) { return $this->dataProvider->retrieveData($latitude, $longitude); } }
C
UTF-8
1,519
3.109375
3
[]
no_license
#include <math.h> #include <trans.h> #pragma function(asinf, acosf, atan2f, atanf, ceilf, expf, fabsf, floorf, fmodf, log10f, logf, powf, sinf, cosf, sinhf, coshf, sqrtf, tanf, tanhf) float __cdecl asinf (float x) {return (float)asin((double) x);} float __cdecl acosf (float x) {return (float)acos((double) x);} float __cdecl atan2f (float v, float u) {return (float)atan2((double) v, (double) u); } float __cdecl atanf (float x) {return (float)atan((double) x);} float __cdecl ceilf (float x) {return (float)ceil((double) x);} float __cdecl expf (float x) {return (float)exp((double) x);} float __cdecl fabsf (float x) {return (float)fabs((double) x);} float __cdecl floorf (float x) {return (float)floor((double) x);} float __cdecl fmodf(float x, float y) {return ((float)fmod((double)x, (double)y));} float __cdecl log10f (float x) {return (float)log10((double) x);} float __cdecl logf (float x) {return (float)log((double) x);} float __cdecl powf (float x, float y) {return (float)pow((double) x, (double) y);} float __cdecl sinf (float x) {return (float)sin((double) x);} float __cdecl cosf (float x) {return (float)cos((double) x);} float __cdecl sinhf (float x) {return (float)sinh((double) x);} float __cdecl coshf (float x) {return (float)cosh((double) x);} float __cdecl sqrtf (float x) {return (float)sqrt((double) x);} float __cdecl tanf (float x) {return (float)tan((double) x);} float __cdecl tanhf (float x) {return (float)tanh((double) x);}
Java
UTF-8
237
1.828125
2
[]
no_license
package controller; import java.util.List; /** * * @author Izaquias */ public interface Controller { public String salvar(); public String atualizar(); public Object buscar(Long chave); public List listarTodos(); }
C++
UTF-8
486
2.671875
3
[]
no_license
#include "gamebutton.h" GameButton::GameButton(QWidget *parent) : QPushButton(parent) { } GameButton::GameButton(int x, int y, QWidget *parent) : QPushButton(parent) { this->setX(x); this->setY(y); } GameButton::~GameButton() { } void GameButton::setX(int x) { this->x = x; } void GameButton::setY(int y) { this->y = y; } int GameButton::getX() { return this->x; } int GameButton::getY() { return this->y; } GameButton *GameButton::teste() { return this; }
Markdown
UTF-8
886
2.90625
3
[ "MIT", "CC-BY-4.0" ]
permissive
--- -api-id: M:Windows.Graphics.Imaging.PixelDataProvider.DetachPixelData -api-type: winrt method --- <!-- Method syntax public byte[] DetachPixelData() --> # Windows.Graphics.Imaging.PixelDataProvider.DetachPixelData ## -description Returns the internally-stored pixel data. ## -returns The pixel data. ## -remarks [PixelDataProvider](pixeldataprovider.md) doesn't retain a copy of the pixel data after a successful call to this method. This means that subsequent calls to the method will fail. The return value is an array of 8 bit unsigned values. However, depending on the requested pixel format, the pixel data may represent another type. For example, if the pixel format is Rgba16, then each color value is a 16 bit unsigned integer that takes up two 8 bit elements of the array. You must convert the array to the correct type before you use it. ## -examples ## -see-also
Java
UTF-8
3,943
2.203125
2
[]
no_license
package com.androidhuman.example.navigationdrawer.basicfragments.app; import android.content.res.Configuration; import android.graphics.Bitmap; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import org.w3c.dom.Text; public class MainActivity extends ActionBarActivity { DrawerLayout dlDrawer; ActionBarDrawerToggle dtToggle; ListView lvDrawerList; ArrayAdapter<String> adtDrawerList; String[] menuItems = new String[]{"TextFragment", "ImageFragment"}; TextFragment fragText; ImageFragment fragImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Fragments fragText = TextFragment.newInstance(); fragImage = new ImageFragment().newInstance(); getSupportFragmentManager().beginTransaction().replace(R.id.fl_activity_main, fragText).commit(); // Navigation drawer : menu lists lvDrawerList = (ListView) findViewById(R.id.lv_activity_main); adtDrawerList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menuItems); lvDrawerList.setAdapter(adtDrawerList); lvDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch(position){ case 0: getSupportFragmentManager().beginTransaction().replace(R.id.fl_activity_main, fragText).commit(); break; case 1: getSupportFragmentManager().beginTransaction().replace(R.id.fl_activity_main, fragImage).commit(); break; } dlDrawer.closeDrawer(lvDrawerList); } }); // Navigation drawer : ActionBar Toggle dlDrawer = (DrawerLayout) findViewById(R.id.dl_activity_main); dtToggle = new ActionBarDrawerToggle(this, dlDrawer, R.drawable.ic_drawer, R.string.app_name, R.string.app_name){ @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); // Hide action items fragText.showActionItems(false); // Refresh action items supportInvalidateOptionsMenu(); //invalidateOptionsMenu(); } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); // Show action items fragText.showActionItems(true); // Refresh action items supportInvalidateOptionsMenu(); //invalidateOptionsMenu(); } }; dlDrawer.setDrawerListener(dtToggle); getSupportActionBar().setDisplayHomeAsUpEnabled(true); //getActionBar().setDisplayHomeAsUpEnabled(true); } @Override protected void onPostCreate(Bundle savedInstanceState){ super.onPostCreate(savedInstanceState); dtToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig){ super.onConfigurationChanged(newConfig); dtToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item){ if(dtToggle.onOptionsItemSelected(item)){ return true; } return super.onOptionsItemSelected(item); } }
Python
UTF-8
831
3.453125
3
[]
no_license
import tkinter as tk window = tk.Tk() window.title('my window') window.geometry('200x200') l = tk.Label(window, bg='yellow', width=20, text='empty') l.pack() canvas = tk.Canvas(window, bg='blue', height=100, width=200) #canvas.pack() image_file = tk.PhotoImage(file='ins.gif') image = canvas.create_image(10, 10, anchor='nw', image=image_file) x0, y0, x1, y1= 50, 50, 80, 80 line = canvas.create_line(x0, y0, x1, y1) oval = canvas.create_oval(x0, y0, x1, y1, fill='red') #创建一个圆,填充色为`red`红色 arc = canvas.create_arc(x0+30, y0+30, x1+30, y1+30, start=0, extent=180) #创建一个扇形 rect = canvas.create_rectangle(100, 30, 100+20, 30+20) #创建一个矩形 canvas.pack() def moveit(): canvas.move(rect, 1, 2) b = tk.Button(window, text='move', command=moveit).pack() window.mainloop()
Python
UTF-8
607
3.203125
3
[]
no_license
""" CP1404/CP5632 Practical 10 - Wiki """ import wikipedia def main(): """Program to search Wikipedia.""" prompt = input("Enter a page title or search phrase: ") while prompt != "": try: # page_title = wikipedia.page(prompt, auto_suggest=False) page_title = wikipedia.page(prompt) print(page_title.title) print(wikipedia.summary(prompt)) print(page_title.url) except wikipedia.exceptions.DisambiguationError as e: print(e.options) prompt = input("Enter a page title or search phrase: ") main()
JavaScript
UTF-8
751
2.703125
3
[]
no_license
function authControl (req, res, next) { let data ='' req.on('data',chunk=>data+=chunk) req.on('end',()=>{ try { if(data) data = JSON.parse(data) else throw 'hech narsa kiritilmadi' let {username,password,contact,age,gender} = data if(!username||username.length<3||username>30) throw 'invalid username' if(!password||!(/[0-9]/).test(password)||!(/[a-z]/).test(password)||!(/[A-Z]/).test(password)||(''+password).length<8 ) throw 'invalid password' if(!age||age<1||age>100) throw 'invalid age' if(!gender) throw 'required gender' if(!contact || (''+contact).length !=12 || typeof +contact != 'number') throw 'invalid phone number' req.body = data next() } catch(e) { res.send(e) } }) } export {authControl}
Python
UTF-8
2,401
2.953125
3
[]
no_license
import argparse parser = argparse.ArgumentParser() parser.add_argument("FileName", help = "Name of the read file.") parser.add_argument("Size_of_truss", help = "What kind of truss we are searching for.") args = parser.parse_args() graphDict = {} with open(args.FileName) as f: line = f.readline() while line: a,b = line.split(' ') if int(a) not in graphDict: graphDict[int(a)] = list() graphDict[int(a)].append(int(b)) else: graphDict[int(a)].append(int(b)) if int(b) not in graphDict: graphDict[int(b)] = list() graphDict[int(b)].append(int(a)) else: graphDict[int(b)].append(int(a)) line = f.readline() f.close() a = [] b = [] def intersection(a,b): commonlist = [] for i in range(len(a)): for j in range(len(b)): if a[i] == b[j] and b[j] != None: commonlist.append(a[i]) return commonlist flag = 0 while flag == 0: flag = 1 for i in range(len(graphDict) + 1): if i in graphDict: for j in range(len(graphDict[i])): if graphDict[i][j] != None: if(len(intersection(graphDict[i],graphDict[graphDict[i][j]]))) < int(args.Size_of_truss) - 2: flag = 0 graphDict[i][j] = None trusslist = [] for i in range(len(graphDict) + 1): if i in graphDict: finder = 1 shortlist = [] for j in range(len(graphDict[i])): if graphDict[i][j] != None and finder == 1: shortlist.append(i) finder = 2 if graphDict[i][j] != None: shortlist.append(graphDict[i][j]) if finder == 2: trusslist.append(shortlist) k = len(trusslist) lastlist = [] for i in range(k): for p in range(k): if trusslist[p] != None and trusslist[i] != None: if len(intersection(trusslist[i],trusslist[p])) == len(trusslist[i]) and p != i: trusslist[p] = None for i in range(len(trusslist)): if trusslist[i] != None: lastlist.append(trusslist[i]) for i in range(len(lastlist)): lastlist[i].sort() prefix = '(' for j in range(len(lastlist[i])): prefix += str(lastlist[i][j]) if j != len(lastlist[i]) - 1: prefix += ', ' prefix += ')' print(prefix)
Python
UTF-8
4,743
2.890625
3
[]
no_license
import numpy as np import math print("Assignment 3.3: Decoupled Power Flow with R = X") # Choose method primal = 0 dual = 0 standard = 1 if primal: print("\nPrimal method:") elif dual: print("\nDual method:") elif standard: print("\nStandard method:") buses = np.array([1, 2, 3]) v = np.ones(3) theta = np.zeros(3) # Network values X12 = 0.2 X13 = 0.1 X23 = 0.15 # Impedances Z12 = complex(X12, X12) Z13 = complex(X13, X13) Z23 = complex(X23, X23) y12 = 1 / Z12 y13 = 1 / Z13 y23 = 1 / Z23 Y_not_bus = np.array([[(y12 + y13), y12, y13], [y12, (y12 + y23), y23], [y13, y23, (y13 + y23)]]) G = Y_not_bus.real B = Y_not_bus.imag # Equivalent impedances for R=0 Z12_eq = complex(0, X12) Z13_eq = complex(0, X13) Z23_eq = complex(0, X23) y12_eq = 1 / Z12_eq y13_eq = 1 / Z13_eq y23_eq = 1 / Z23_eq Y_not_bus_eq = np.array([[(y12_eq + y13_eq), y12_eq, y13_eq], [y12_eq, (y12_eq + y23_eq), y23_eq], [y13_eq, y23_eq, (y13_eq + y23_eq)]]) G_eq = Y_not_bus_eq.real B_eq = Y_not_bus_eq.imag # Load values P1 = -1.0 P2 = -0.5 Q1 = -0.5 Q2 = -0.5 P_spes = ([P1, P2]) Q_spes = ([Q1, Q2]) # Arrays needed for calculations T = np.zeros((3, 3)) U = np.zeros((3, 3)) T_eq = np.zeros((3, 3)) U_eq = np.zeros((3, 3)) # Jacobian matrix H = np.zeros((2, 2)) # Upper left L = np.zeros((2, 2)) # Lower right H_eq = np.zeros((2, 2)) # ser bort fra resistans L_eq = np.zeros((2, 2)) # ser bort fra resistans # Calculated power vectors P_cal = np.zeros(3) Q_cal = np.zeros(3) # Delta vectors delta_theta = np.zeros((2, 1)) delta_v = np.zeros((2, 1)) delta_P = np.zeros((2, 1)) delta_Q = np.zeros((2, 1)) # Defining error and max mismiatch max_mismatch = 1 error = 0.001 it = 0 while max_mismatch > error: print("\nIteration nr.:", it + 1) # Calculating T and U for i in range(buses.size): for j in range(buses.size): T[i][j] = G[i][j] * math.cos(theta[i] - theta[j]) + B[i][j] * math.sin(theta[i] - theta[j]) U[i][j] = G[i][j] * math.sin(theta[i] - theta[j]) - B[i][j] * math.cos(theta[i] - theta[j]) T_eq[i][j] = G_eq[i][j] * math.cos(theta[i] - theta[j]) + B_eq[i][j] * math.sin(theta[i] - theta[j]) U_eq[i][j] = G_eq[i][j] * math.sin(theta[i] - theta[j]) - B_eq[i][j] * math.cos(theta[i] - theta[j]) # Calculating powers for i in range(buses.size): P_cal[i] = v[i] * v[i] * G[i][i] Q_cal[i] = -v[i] * v[i] * B[i][i] for j in range(buses.size): if i != j: P_cal[i] = P_cal[i] - v[i] * v[j] * T[i][j] Q_cal[i] = Q_cal[i] - v[i] * v[j] * U[i][j] print("\nCalculated active power:\n", P_cal) print("\nCalculated reactive power:\n", Q_cal) # Calculating the Jacobian matrix for i in range(2): for j in range(2): if i == j: H[i][j] = 0 L[i][j] = -2 * v[i] * B[i][i] H_eq[i][j] = 0 L_eq[i][j] = -2 * v[i] * B_eq[i][i] for k in range(buses.size): if k != i: H[i][j] = H[i][j] + v[i] * v[k] * U[i][k] L[i][j] = L[i][j] - v[k] * U[i][k] H_eq[i][j] = H_eq[i][j] + v[i] * v[k] * U_eq[i][k] L_eq[i][j] = L_eq[i][j] - v[k] * U_eq[i][k] else: H[i][j] = -v[i] * v[j] * U[i][j] L[i][j] = - v[i] * U[i][j] H_eq[i][j] = -v[i] * v[j] * U_eq[i][j] L_eq[i][j] = - v[i] * U_eq[i][j] print("\nH:\n", H) print("\nL:\n", L) print("\nH_eq:\n", H_eq) print("\nL_eq:\n", L_eq) # Calculating mismatch for i in range(2): delta_P[i] = P_spes[i] - P_cal[i] delta_Q[i] = Q_spes[i] - Q_cal[i] print("\nMismatch:\nDeltaP:\n", delta_P, "\nDeltaQ:\n", delta_Q) if primal: # Primal method delta_theta = np.dot(np.linalg.inv(H), delta_P) delta_v = np.dot(np.linalg.inv(L_eq), delta_Q) elif dual: # Dual method delta_v = np.dot(np.linalg.inv(L), delta_Q) delta_theta = np.dot(np.linalg.inv(H_eq), delta_P) elif standard: # Standard method delta_theta = np.dot(np.linalg.inv(H_eq), delta_P) delta_v = np.dot(np.linalg.inv(L_eq), delta_Q) for i in range(2): theta[i] += delta_theta[i] v[i] += delta_v[i] print("\nCorrection:\nDeltaV:\n", delta_v, "\nDeltaTheta:\n", delta_theta) print("\nVoltage magnitudes:\n", v, "\nVoltage angles:\n", theta) # Calculating maximum mismatch max_P = max(abs(delta_P)) max_Q = max(abs(delta_Q)) max_mismatch = max(max_P, max_Q) # Updating iteration count it += 1
C#
UTF-8
5,243
2.984375
3
[]
no_license
using System; using System.Linq; using Provausio.Testing.Generators.Generators.Names; using Xunit; namespace Provausio.Testing.Generators.Tests.UnitTests.Names { public class NameGeneratorTests { [Fact] public void Generate_MaleNames_GeneratesMaleNames() { // arrange var gen = new NameGenerator(); // act var names = gen.Generate(5, NameType.Given, Gender.Male).ToList(); // assert Assert.All(names, s => Assert.NotNull(NameSource.GivenMale.SingleOrDefault(n => n.Equals(s)))); } [Fact] public void Generate_FemaleNames_GeneratesFemaleNames() { // arrange var gen = new NameGenerator(); // act var names = gen.Generate(5, NameType.Given, Gender.Female).ToList(); // assert Assert.All(names, s => Assert.NotNull(NameSource.GivenFemale.SingleOrDefault(n => n.Equals(s)))); } [Fact] public void Generate_GivenName_BothGenders_ContainsMaleAndFemaleNames() { // arrange var gen = new NameGenerator(); // act var names = gen.Generate(50, NameType.Given, Gender.Both).ToList(); // assert var maleNames = names.Where(fn => NameSource.GivenMale.Contains(fn)); var femaleNames = names.Where(fn => NameSource.GivenFemale.Contains(fn)); Assert.True(maleNames.Any() && femaleNames.Any()); } [Fact] public void Generate_BothNames_BothGenders_ContainsBothNames() { // arrange var gen = new NameGenerator(); // act var names = gen.Generate(5, NameType.Both, Gender.Both).ToList(); // assert Assert.All(names, s => Assert.Equal(2, s.Split(" ").Length)); } [Fact] public void Generate_Surnames_GeneratesSurnames() { // arrange var gen = new NameGenerator(); // act var names = gen.Generate(5, NameType.Surname, Gender.NotApplicable).ToList(); // assert Assert.All(names, s => Assert.Contains(s, NameSource.Surnames)); } [Fact] public void GenerateFull_GeneratesFirstAndLast() { // arrange var gen = new NameGenerator(); // act var names = gen.GenerateFull(5, Gender.Both).ToList(); // assert Assert.All(names, s => { var split = s.Split(" "); Assert.Equal(2, split.Length); Assert.Contains(split[1], NameSource.Surnames); }); } [Fact] public void GenerateFull_Male_FirstNameIsMale() { // arrange var gen = new NameGenerator(); // act var names = gen.GenerateFull(5, Gender.Male).ToList(); // assert Assert.All(names, s => { var split = s.Split(" "); Assert.Contains(split[0], NameSource.GivenMale); }); } [Fact] public void GenerateFull_Female_FirstNameIsFemale() { // arrange var gen = new NameGenerator(); // act var names = gen.GenerateFull(5, Gender.Female).ToList(); // assert Assert.All(names, s => { var split = s.Split(" "); Assert.Contains(split[0], NameSource.GivenFemale); }); } [Fact] public void GenerateFull_Both_ContainsBothMaleAndFemaleNames() { // arrange var gen = new NameGenerator(); // act var names = gen.GenerateFull(50, Gender.Both).ToList(); // assert var firstnames = names.Select(n => n.Split(" ")[0]); var maleNames = firstnames.Where(fn => NameSource.GivenMale.SingleOrDefault(n => n.Equals(fn)) != null); var femaleNames = firstnames.Where(fn => NameSource.GivenFemale.SingleOrDefault(n => n.Equals(fn)) != null); Assert.True(maleNames.Any() && femaleNames.Any()); } [Fact] public void GenerateUsername_GeneratesUsername() { // arrange var gen = new NameGenerator(); // act var username = gen.GenerateUsername(); // assert var surname = username.Substring(1); Assert.Contains(surname, NameSource.Surnames, StringComparer.OrdinalIgnoreCase); } [Theory] [InlineData("Jon", "Snow", "jsnow")] [InlineData("Jeremy", "Stafford", "jstafford")] [InlineData("Bill", " Gates", "bgates")] // contains an extra space public void ToUserName_ConstructsProperUsername(string fname, string lname, string expected) { // arrange var gen = new NameGenerator(); // act var username = gen.ToUsername(fname, lname); // assert Assert.Equal(expected, username); } } }
Markdown
UTF-8
1,807
2.65625
3
[]
no_license
# nc-news - frontend project :newspaper: A Reddit-style React news app. View articles by topic or author.<br /> Sort by newest, top rated and hottest.<br /> View individual articles with more detail and comments. <br /> When logged in, user can post a comment of delete their own comments. Hosted project [here](https://nt-nc-news.netlify.app/) on Netlify<br/> Hosted API available [here](https://nt-nc-news.herokuapp.com/api) and backend repo [here](https://github.com/naomiuna/nc-news). ## Getting Started & Installation ### Prerequisites The minimum version of [Node.js](https://nodejs.org/en/download) you will need to run this app is v12.16.1 ### Installation These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. Clone a copy of the repository on your machine: ```javascript git clone https://github.com/naomiuna/fe-nc-news ``` Install the required dependencies: ```javascript npm install ``` To run the app in development mode: ```javascript npm start ``` Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br /> ## Built With - [React](https://reactjs.org/) - A JavaScript library for building user interfaces - [axios](https://github.com/axios/axios) - Promise based HTTP client - [Reach Router](https://reach.tech/router) - Router for React<br /><br /> This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) ## Future Features - pagination - authentication to allow improved sign-in and ability to register new user - ability to post and delete articles - ability to view most active/popular users - context API for logged in user ## Acknowledgments - Northcoders team 🧑🏻‍💻
Markdown
UTF-8
1,084
2.6875
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "Невозможно преобразовать аргумент &quot;&lt;имя_аргумента&gt;&quot; в числовое значение | Microsoft Docs" ms.date: "2015-07-20" ms.prod: ".net" ms.technology: - "devlang-visual-basic" ms.topic: "article" f1_keywords: - "vbrArgumentNotNumeric1" ms.assetid: 1901c4d4-abbe-462f-a450-5d907d485e94 caps.latest.revision: 8 author: "stevehoag" ms.author: "shoag" caps.handback.revision: 8 --- # Невозможно преобразовать аргумент &quot;&lt;имя_аргумента&gt;&quot; в числовое значение Предпринята попытка преобразовать переменную, например строку, в числовое значение. ### Исправление ошибки 1. Найдите преобразование, имеющее смысл. ## См. также [Преобразование типов в Visual Basic](../../visual-basic/programming-guide/language-features/data-types/type-conversions.md)
Python
UTF-8
566
3.671875
4
[]
no_license
class Node: def __init__(self,val): self.val=val self.next=None def traverse(self): node=self while node!=None: print(node.val) node=node.next def size(self): node=self count=0 while node!=None: count+=1 node=node.next return count node1=Node(1) node2=Node(2) node3=Node(3) node1.next=node2 node2.next=node3 def deleteNode(node): temp=node.next node.val=temp.val node.next=temp.next deleteNode(node1) Node.traverse(node1)
C++
UTF-8
925
3.078125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; void solve() { int no_of_elements, m; cin >> no_of_elements >> m; vector <int> A(no_of_elements + 1); vector <int> frequency(m + 1); for(int i = 1; i <= no_of_elements; i++) { cin >> A[i]; frequency[A[i]%m]++; } int arrays = (frequency[0] > 0 ? 1 : 0); for(int i = 1, j = m - 1; i <= j; i++, j--) { if(frequency[i] == 0 && frequency[j] == 0) { continue; } if(i == j || abs(frequency[i] - frequency[j]) <= 1) { arrays++; } else { arrays += abs(frequency[i] - frequency[j]); } } cout << arrays << "\n"; } int main() { int no_of_test_cases; cin >> no_of_test_cases; while(no_of_test_cases--) solve(); return 0; }
JavaScript
UTF-8
2,225
2.78125
3
[]
no_license
import firebase from '~/plugins/firebase' // firebaseの初期化設定ファイル import { firestoreAction } from 'vuexfire' // vuecfireが用意しているfirestoreActionを呼び出す // データベースの設定 const db = firebase.firestore() const todosRef = db.collection('todos') // "collectionはtodosを使う" という設定 // ステートの定義 // todo一覧を管理するtodosを配列で定義しておく export const state = () => ({ todos: [] }) export const actions = { init: firestoreAction(({ bindFirestoreRef }) => { // Action呼出 引数は、本来なら第一引数にはcontextが入るが、こう書くとこれのみ受け取れる bindFirestoreRef('todos', todosRef) //bind(関連付け)したいデータの名前'todos'とコレクションへの参照(2)を渡すとstate.todos(上のステート)にcloudfirestoreのデータが関連付けされる }), // addは、todoの追加をする時に呼ばれるアクション add: firestoreAction((context, name) => { // 第一引数にcontext(不使用)、第二引数にtodoの名前を受け取る if(name.trim()) { // 入力が空白でないか確認。空白の場合無効に。 todosRef.add({ // todosRefのaddメソッドを使ってデータをfirestoreに登録。 name: name, done: false, // タスクの完了・未完了 created: firebase.firestore.FieldValue.serverTimestamp() // 作成時間。正規化はコンポーネント側で }) } }), // todoを削除するアクション remove: firestoreAction((context, id) => { // idはremoveを呼ぶ時に引数として使用 todosRef.doc(id).delete() // idが一致するデータを削除 }), // チェックボックス操作時のアクション todoの完了・未完了を管理するための機能 toggle: firestoreAction((context, todo) => { todosRef.doc(todo.id).update({ done: !todo.done // 現在の値を反転して使用 }) }) } // ゲッター Firebaseからデータを取ってくるとデフォでID順になるので、createdを基準にしてソート export const getters = { orderdTodos: state => { return _.sortBy(state.todos, 'created') } }
C++
UTF-8
625
3.421875
3
[]
no_license
#include <iostream> #include <cmath> #include <stdlib.h> using namespace std; float norma(float &re, float &im ){ return sqrt(re*re + im*im); } float angulo(float &re, float &im){ return atan2(im,re); } int main( int argc, char** argv ){ // Recordar que la parte real e imaginaria será pasado por parámetros del main. float a, b, nor, ang; a = b = 0.; a = atof( argv[1] ); b = atof( argv[2] ); nor = norma( a, b ); ang = angulo( a, b ); cout << "El número complejo: " << a << " + " << b << "j" ; cout << " tiene de norma= " << nor << " y un ángulo= " << ang << " rad." << endl; return 0; }
Rust
UTF-8
1,942
2.859375
3
[]
no_license
use std::net::{TcpStream, TcpListener}; use std::io::Write; use std::io::Read; use std::thread; //use std::str::FromStr; extern crate ore_http; fn main() { let listener = TcpListener::bind("127.0.0.1:8931").unwrap(); for stream in listener.incoming() { match stream { Ok(stream) => { thread::spawn(move || { response(stream); }); } Err(e) => println!("Error: {}", e), } } drop(listener); } fn response(mut stream: TcpStream) { let mut buf = [0; 1024]; let mut request_header = ""; loop { match stream.read(&mut buf) { Err(e) => panic!("Got an error: {}", e), Ok(0) => { println!("Break now!"); break; } Ok(_) => { request_header = std::str::from_utf8(&mut buf).unwrap().trim(); break; } }; } let mut request_header_lines = request_header.lines(); let path = match request_header_lines.next() { Some(s) => { let mut info = s.split_whitespace(); let _method = info.next(); let path = info.next(); let _protocol = info.next(); match path { Some(p) => p, None => panic!("...?"), } } None => panic!("...??"), }; let body = &ore_http::my_file::read_file(path); let content_length = body.len(); let http_status = "HTTP/1.1 200 OK \r\n"; let http_header = &format!( "{}{}{}{}", "Content-Type: text/html; charset=UTF-8\r\n", "Content-Length: ", content_length, "\r\n" ); let mut msg = String::new(); msg.push_str(http_status); msg.push_str(http_header); msg.push_str("Connection: Close\r\n"); msg.push_str("\r\n"); msg.push_str(body); stream.write(msg.as_bytes()).unwrap(); }
SQL
UTF-8
443
3.21875
3
[]
no_license
### Schema CREATE DATABASE IF NOT EXISTS burgers_db; USE burgers_db; CREATE TABLE burgers ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, devoured BOOLEAN DEFAULT false, PRIMARY KEY (id) ); INSERT INTO burgers (name, devoured) VALUES ('Cheese burger', FALSE); INSERT INTO burgers (name, devoured) VALUES ('Triple burger', FALSE); INSERT INTO burgers (name, devoured) VALUES ('Bison burger', FALSE); SELECT * FROM burgers
JavaScript
UTF-8
5,183
2.75
3
[]
no_license
// Khởi tạo mảng Post var Post = [ { "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, { "id": 3, "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut", "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut" }, { "id": 4, "title": "eum et est occaecati", "body": "ullam et saepe reiciendis voluptatem adipiscisit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit" } ]; function loadPage() { Post.sort(function (a, b) { return b.id - a.id }) for (let index = 0; index < Post.length; index++) { var row = addRow(Post[index].id, Post[index].title, Post[index].body); var add = document.getElementById("title"); add.parentNode.insertBefore(row, add.nextSibling); } } loadPage(); // Hàng được chọn var selectedRow = -1; // Thêm một hàng vào bảng function addRow(id, title, body) { var row = document.createElement("tr"); var valuerow1 = document.createElement("td"); var valuerow2 = document.createElement("td"); var valuerow3 = document.createElement("td"); var valuerow4 = document.createElement("td"); var textvl1 = document.createTextNode(id); var textvl2 = document.createTextNode(title); var textvl3 = document.createTextNode(body); var textvl4 = document.createTextNode("......"); var a = document.createElement("a"); a.appendChild(textvl4); a.setAttribute("href", "#modalDelete"); a.style = "text-decoration:none;width: 100px;height: 100px;text-align: center;line-height:100px"; valuerow1.appendChild(textvl1); valuerow2.appendChild(textvl2); valuerow3.appendChild(textvl3); valuerow4.appendChild(a); row.appendChild(valuerow1); row.appendChild(valuerow2); row.appendChild(valuerow3); row.appendChild(valuerow4); // Gán sự kiện cho hàng: Khi click vào thì hightlight row.addEventListener("click", function () { this.style = "background:yellow;"; selectedRow = this.rowIndex; var nodeList = document.querySelectorAll("tr"); for (let index = 0; index < nodeList.length; index++) { if (index != selectedRow) nodeList[index].style = "background:#FFF"; } }); return row; } // In ra thông báo function message(message, color) { var oldmess = document.getElementById("mess"); if (oldmess) { document.body.removeChild(oldmess); } var container = document.createElement("div"); container.setAttribute("id", "mess"); var tag = document.createElement("span"); var text = document.createTextNode(message); tag.appendChild(text); tag.style.color = "white"; tag.style.fontSize = "24px"; container.appendChild(tag); container.style.opacity = "1"; container.style.paddingTop = "10px"; container.style.paddingBottom = "10px"; container.style.textAlign = "center"; container.style.width = "500px"; container.style.margin = "100px auto"; container.style.background = color; document.body.insertBefore(container, document.body.lastChild); } //Thêm dữ liệu function addData() { var title1 = document.getElementById("titled").value; var body1 = document.getElementById("body").value; if (title1 == null || title1 == "") { alert("Trường này không được để rỗng"); return; } else if (body1 == null || body1 == "") { alert("Trường này không được để rỗng"); return; } else { var idu = Post.length + 1; var us = { id: idu, title: title1, body: body1 }; Post.push(us); var row = addRow(idu, title1, body1); var add = document.getElementById("title"); add.parentNode.insertBefore(row, add.parentNode.lastChild); title1 = ""; closePopup(); message("Add Post Successfully!", "green"); document.getElementById("titled").value=""; document.getElementById("body").value=""; } } // Xoá dữ liệu function deleteData() { if (selectedRow < 0) { alert("Vui lòng chọn một hàng!"); } else { document.getElementById("tb").deleteRow(selectedRow); closePopup(); message("Delete Post Successfully!", "green"); selectedRow = -1; } } // Đóng popup function closePopup() { location.href = "#"; }
Markdown
UTF-8
1,352
2.9375
3
[ "MIT" ]
permissive
# OoooWeeee <p align="center"> <img src="logo.jpeg" width="200" height="200" /> </p> #### Programming using phrases Mr.PoopyButHole Whould Say ## Example ##### Adds 2 and 5 and Displays The Result ``` oow oow eeo oow oow oow oow oow ooo oee oow eeo woo wee oow oow oow oow oow oow oow oow ooo oee oow oow oow oow oow oow eeo woo wee oee eee ``` ###### Output ```7``` [More Examples...](https://github.com/omkarjc27/OooWee/Examples) ## Installation To install, download the repo using:```$ git clone https://github.com/omkarjc27/OooWee```<br> Add To Path using:```$ export PATH=$PATH:/path/to/OooWee``` ## Usage ``` $ Ooo filename.Wee``` ## Syntax | Command | What it does | | --------- | --------------------------------------------------------------------- | | ooo | Opens a loop BFE:"[" | | wee | If the cell's value is 0, break the loop. Else, return to loop start BFE:"]" | | eeo | Moves the current cell one to the right BFE:">" | | oee | Moves the current cell one to the left BFE:"<" | | oow | Adds one to the cell's value BFE:"+" | | woo | Subtracts one from the cell's value BFE:"-" | | eee | Print ASCII Charecter of value of current cell BFE:"." | | eew | Read one Charecter and save the ASCII value to current cell BFE:"," | PS: BFE ‣ Brain Fuck Eqiuvalent
Java
UTF-8
1,359
1.859375
2
[ "AGPL-3.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-commercial-license", "AGPL-3.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package de.adorsys.opba.protocol.xs2a.service.xs2a.dto.oauth2; import de.adorsys.opba.protocol.bpmnshared.dto.DtoMapper; import de.adorsys.opba.protocol.xs2a.context.Xs2aContext; import de.adorsys.xs2a.adapter.api.Oauth2Service; import lombok.Data; import org.mapstruct.Mapper; import javax.validation.constraints.NotBlank; import static de.adorsys.opba.protocol.xs2a.constant.GlobalConst.SPRING_KEYWORD; import static de.adorsys.opba.protocol.xs2a.constant.GlobalConst.XS2A_MAPPERS_PACKAGE; @Data public class Xs2aOauth2WithCodeParameters { @NotBlank private String oauth2RedirectBackLink; @NotBlank private String oauth2Code; @NotBlank private String grantType = Oauth2Service.GrantType.AUTHORIZATION_CODE.toString(); // TODO Xs2a Adapter should set it? public Oauth2Service.Parameters toParameters() { Oauth2Service.Parameters parameters = new Oauth2Service.Parameters(); parameters.setAuthorizationCode(oauth2Code); parameters.setRedirectUri(oauth2RedirectBackLink); parameters.setGrantType(grantType); return parameters; } @Mapper(componentModel = SPRING_KEYWORD, implementationPackage = XS2A_MAPPERS_PACKAGE) public interface FromCtx extends DtoMapper<Xs2aContext, Xs2aOauth2WithCodeParameters> { Xs2aOauth2WithCodeParameters map(Xs2aContext ctx); } }
Java
UTF-8
1,029
2.34375
2
[]
no_license
package com.alienlab.ziranli.service; import com.alienlab.ziranli.domain.ExhibitionNameList; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; /** * Service Interface for managing ExhibitionNameList. */ public interface ExhibitionNameListService { /** * Save a exhibitionNameList. * * @param exhibitionNameList the entity to save * @return the persisted entity */ ExhibitionNameList save(ExhibitionNameList exhibitionNameList); /** * Get all the exhibitionNameLists. * * @param pageable the pagination information * @return the list of entities */ Page<ExhibitionNameList> findAll(Pageable pageable); /** * Get the "id" exhibitionNameList. * * @param id the id of the entity * @return the entity */ ExhibitionNameList findOne(Long id); /** * Delete the "id" exhibitionNameList. * * @param id the id of the entity */ void delete(Long id); }
Python
UTF-8
2,823
2.703125
3
[]
no_license
from kivy.core.window import Window from kivy.graphics import Rectangle from kivy.graphics import Color from kivy.base import EventLoop from .locals import * try: import android except: android = False class DummyDisplay(object): def __init__(self, width, height): self.width = width self.height = height class Display(object): def __init__(self, window=None): self.width = -1 self.height = -1 self.window = None self.app = None self.size = (640, 480) self.resizable = False def get_width(self): return self.width def get_height(self): return self.height def set_mode(self, size=(640,480), flags=0, depth=0): if OPENGL <= flags: flags -= OPENGL if NOFRAME <= flags: flags -= NOFRAME Window.borderless = "1" if RESIZABLE <= flags: flags -= RESIZABLE self.resizable = True if HWSURFACE <= flags: flags -= HWSURFACE if DOUBLEBUF <= flags: flags -= DOUBLEBUF if FULLSCREEN <= flags: flags -= FULLSCREEN Window.fullscreen = True self.size = size self.width, self.height = size if not android: Window.size = size self.width = float(self.width) self.height = float(self.height) canvas = DummyDisplay(self.width, self.height) canvas.blit = self.blit canvas.fill = self.fill canvas.clear = self.clear canvas.get_width = self.get_width canvas.get_height = self.get_height return canvas def set_caption(self, title, icontitle=None): self.app.title = title if icontitle != None: self.app.icon = icontitle def clear(self): self.window.canvas.clear() #to avoid memory leaks def fill(self, color, rect=None, special_flags=0): R = color[0] / 255.0 G = color[1] / 255.0 B = color[2] / 255.0 self.window.canvas.clear() #to avoid memory leaks with self.window.canvas: Color(R, G, B) Rectangle(size=(Window.width, Window.height)) def blit(self, source, dest=(0, 0), area=None, special_flags=0): try: dest = (dest[0], self.height - dest[1] - source.height) except: dest = (dest.x, self.height - dest.y - source.height) ratio = Window.width / self.width, Window.height / self.height size = source.texture.width * ratio[0], source.texture.height * ratio[1] dest = [dest[0] * ratio[0], dest[1] * ratio[1]] with self.window.canvas: Rectangle(texture=source.texture, pos=dest, size=size) def flip(self): return None def update(self): return None
C++
UTF-8
6,622
2.859375
3
[]
no_license
#ifndef UEP_BLOCK_DECODER_HPP #define UEP_BLOCK_DECODER_HPP #include <forward_list> #include <set> #include <vector> #include "counter.hpp" #include "lazy_xor.hpp" #include "log.hpp" #include "message_passing.hpp" #include "packets.hpp" #include "rng.hpp" #include "utils.hpp" namespace uep { /** Converter to evaluate lazy_xors into packets. */ template <std::size_t MAX_SIZE> struct lazy2p_conv { packet operator()(const lazy_xor<buffer_type,MAX_SIZE> &lx) const { if (lx) { packet p; p.buffer() = lx.evaluate(); return p; } else { return packet(); } } }; /** Iterator adaptor that converts from lazy_xors to packets. */ template <class BaseIter, std::size_t MAX_SIZE> using lazy2p_iterator = boost::transform_iterator<lazy2p_conv<MAX_SIZE>, BaseIter>; /** Class to decode a single LT-encoded block of packets. * The LT-code parameters are given by the lt_row_generator passed to * the constructor. The seed is read from the fountain_packets. */ class block_decoder { private: /** Max size for the lazy_xors. */ static constexpr std::size_t LX_MAX_SIZE = 1; /** Type of the symbols used for the mp algorithm. */ typedef lazy_xor<buffer_type,LX_MAX_SIZE> sym_t; /** Type of the underlying message passing context. */ typedef mp::mp_context<sym_t> mp_ctx_t; /** Type of the container used to cache the row generator output. */ typedef std::vector<base_row_generator::row_type> link_cache_t; public: /** Iterator over the input packets, either decoded or empty. */ typedef lazy2p_iterator<mp_ctx_t::inputs_iterator, LX_MAX_SIZE> const_partial_iterator; /** Iterator over the decoded input packets. */ typedef lazy2p_iterator<mp_ctx_t::decoded_iterator, LX_MAX_SIZE> const_block_iterator; /** Type of the seed used by the row generator. */ typedef lt_row_generator::rng_type::result_type seed_t; /** Construct with a copy of the given lt_row_generator. */ explicit block_decoder(const lt_row_generator &rg); /** Construct with the given row generator. */ explicit block_decoder(std::unique_ptr<base_row_generator> &&rg); /** Reset the decoder to the initial state. */ void reset(); /** Add an encoded packet to the current block. * If the packet is a duplicate (same sequence_number), it is * ignored and the method returns false. */ bool push(fountain_packet &&p); /** \sa push(fountain_packet&&) */ bool push(const fountain_packet &p); /** Add many packets to the current block. Try to decode only once * all packets have been pushed. Return the number of unique * packets that were added to the block. To move from the packets * the iterators can be wrapped in std::move_iterator. */ template <class Iter> std::size_t push(Iter in_first, Iter in_last); /** Return the seed used to decode the current block. */ seed_t seed() const; /** Return the current block's block_number. */ std::size_t block_number() const; /** Return true when the entire input block has been decoded. */ bool has_decoded() const; /** Number of input packets that have been successfully decoded. */ std::size_t decoded_count() const; /** Number of received unique packets. */ std::size_t received_count() const; /** Block size. */ std::size_t block_size() const; /** Return an iterator to the beginning of the decoded packets. * The interval [block_begin(), block_end()) always contains the * decoded_count() packets that have been decoded. * \sa block_end() */ const_block_iterator block_begin() const; /** Return an iterator to the end of the decoded packets. * \sa block_begin() */ const_block_iterator block_end() const; /** Return an iterator to the beginning of the partially decoded * block. * The partially decoded block has always size block_size() but * some of the packets may be empty. * \sa partial_end() */ const_partial_iterator partial_begin() const; /** Return an iterator to the end of the partially decoded * block. * \sa partial_begin() */ const_partial_iterator partial_end() const; /** Return the average time to run message passing measured since * the last reset. */ double average_message_passing_time() const; /** Return the average time to setup the mp context measured since * the last reset. */ double average_mp_setup_time() const; /** Return true when the decoder has decoded a full block. */ explicit operator bool() const; /** Return true when the encoder does not have decoded a full block. */ bool operator!() const; const base_row_generator &row_generator() const; private: log::default_logger basic_lg, perf_lg; std::unique_ptr<base_row_generator> rowgen; std::set<std::size_t> received_seqnos; link_cache_t link_cache; std::forward_list<fountain_packet> last_received; mp_ctx_t mp_ctx; /**< Context used to run the mp algorithm and hold * the result. */ mp_ctx_t mp_pristine; /**< Keep a version of the context that was * never "runned". */ std::size_t blockno; std::size_t pktsize; stat::average_counter avg_mp; /**< Average time to run the message * passing algorithm. */ stat::average_counter avg_setup; /**< Average time to setup * mp_ctx before each run. */ /** Check the blockno, seqno and seed of the packet and raise an * exception if they don't match the current block. */ void check_correct_block(const fountain_packet &p); /** Run the message passing algortihm over the currently received * packets. */ void run_message_passing(); }; // block_decoder template definitions template <class Iter> std::size_t block_decoder::push(Iter in_first, Iter in_last) { // Ignore packets after successful decoding if (has_decoded()) { return 0; } std::size_t pushed = 0; std::size_t max_seqno = 0; for (auto i = in_first; i != in_last; ++i) { fountain_packet p(*i); check_correct_block(p); size_t p_seqno = p.sequence_number(); auto ins_ret = received_seqnos.insert(p_seqno); // Ignore duplicates if (!ins_ret.second) { break; } last_received.push_front(std::move(p)); ++pushed; if (max_seqno < p_seqno) max_seqno = p_seqno; } // Generate enough output links if (link_cache.size() <= max_seqno) { size_t prev_size = link_cache.size(); link_cache.resize(max_seqno+1); for (size_t i = prev_size; i < max_seqno+1; ++i) { link_cache[i] = rowgen->next_row(); } } if (pushed > 0) run_message_passing(); return pushed; } } #endif
C++
UTF-8
1,101
2.609375
3
[ "Apache-2.0" ]
permissive
#pragma once #include "JackTokens.hpp" #include <vector> #include <sstream> #include <string> using namespace std; class CompilationEngine { protected: vector<JackToken*> _tokens; int _tokenCounter = 0; ostringstream output; public: CompilationEngine(vector<JackToken*> tokens) : _tokens(tokens) {} void clearOutput() { output = ostringstream{}; } string toString() { return output.str(); } void compile() { compileClass(); } virtual void compileClass() = 0; virtual void compileClassVarDec() = 0; //for implementing subroutineDec on page 208 virtual void compileSubroutine() = 0; //for implementing subroutineCall on page 209 virtual void compileSubroutineCall() = 0; virtual void compileParameterList() = 0; virtual void compileVarDec() = 0; virtual void compileStatement() = 0; virtual void compileDo() = 0; virtual void compileLet() = 0; virtual void compileWhile() = 0; virtual void compileReturn() = 0; virtual void compileIf() = 0; virtual void compileExpression() = 0; virtual void compileTerm() = 0; virtual void compileExpressionList() = 0; };
C
UTF-8
815
2.90625
3
[]
no_license
/* ** my_showmem.c for my_lib in /home/benjamin/Dropbox/func/ ** ** Made by Benjamin ** Login <benjamin.solca@epitech.eu> ** ** Started on Sun Apr 2 19:47:19 2017 Benjamin ** Last update Mon Apr 17 15:36:13 2017 Benjamin */ #include "bs.h" static void print_show_mem(char* str, int size) { int i; my_putptr_base(str, "0123456789ABCDEF"); my_putstr(": "); i = -1; while (++i < size) { if (str[i] < 16) my_putchar('0'); my_putnbr_base(str[i], "0123456789ABCDEF"); if (i % 2 == 1) my_putchar(' '); } i = -1; while (++i < size) { if (is_printable(str[i])) my_putchar(str[i]); else my_putchar('.'); } my_putchar('\n'); } void my_showmem(char *str, int size) { int i; i = -1; while (++i < size) { print_show_mem(str, 16); str += 16; } }
Shell
UTF-8
583
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
#!/bin/sh ###### ## Script to launch Windows NT 3.51 on QEMU without overflow errors _INSTALLER_ISO="install.iso" _INSTALL_DISK1="disk1.img" _TARGET_BLOCK="/dev/adaX" qemu-system-i386 \ -machine type=isapc \ -cpu 486 \ -boot once=a \ -m size=32M \ -k en-us \ -soundhw sb16,adlib \ -name "qemu-nt351" \ -drive file="$_INSTALLER_DISK1",if=floppy,media=disk \ -drive file="$_TARGET_BLOCK",if=ide,index=0,media=disk,format=raw \ -drive file="$_INSTALLER_ISO",if=ide,index=1,media=cdrom
Markdown
UTF-8
1,474
2.953125
3
[]
no_license
# DB_project Zadanie z kursu C++/STL (Coders School/Wrocław/luty 2019) Projekt akademickiej bazy danych bez interfejsu dla użytkownika. Studenci i pracownicy celowo są trzymani w jednym kontenerze(vector), aby pokazać wynikające z tego problemy. Napisz program, który będzie akademicką "bazą danych". Wymagania do 09.02.2019: Przechowywanie rekordów studentów o strukturze: Imię, nazwisko, adres, nr indeksu Dodawanie nowych studentów Sortowanie po numerze indeksu Usuwanie po numerze indeksu Wymagania do 16.02.2019: Przechowywanie rekordów studentów o strukturze: Imię, nazwisko, PESEL, płeć, adres, nr indeksu. Wyszukiwanie po nazwisku Wyszukiwanie po numerze PESEL Wyswietlanie całej bazy danych Sortowanie po PESELu Sortowanie po nazwisku Wypełnianie bazy danych sztucznymi danymi (generowanie danych) Usuwanie po numerze PESEL Modyfikacja adresu po numerze PESEL Walidacja czy numer PESEL jest poprawny Wiki - poprawnosc PESEL (problematyczne) Wczytywanie z pliku i zapisywanie całej bazy w pliku (problematyczne) Wymagania dodatkowe: (jeśli znasz polimorfizm) Przechowywanie rekordów pracowników o strukturze: Imię, nazwisko, PESEL, płeć, adres, zarobki Wszystkie osoby niezależnie czy będa to pracownicy czy studenci mają być trzymani w jednym kontenerze Modyfikacja zarobków po numerze PESEL (problematyczne) Sortowanie po zarobkach (problematyczne)
C#
UTF-8
3,310
2.515625
3
[ "MIT" ]
permissive
using System; using System.Diagnostics; using System.Net.Sockets; using Net.Remote; namespace Megumin.Remote { /// <summary> /// 安全关闭一个socket很麻烦,根本搞不清楚调用那个函数会抛出异常。 /// </summary> public class SocketCloser { readonly object innerlock = new object(); public bool IsDisconnecting { get; internal protected set; } = false; public void SafeClose(Socket socket, SocketError error, IDisconnectHandler handler, bool triggerDisConnectHandle = false, bool waitSendQueue = false, object options = null, TraceListener traceListener = null) { lock (innerlock) { if (IsDisconnecting) { //正在断开就忽略 return; } IsDisconnecting = true; } try { if (triggerDisConnectHandle) { handler?.PreDisconnect(error, options); } //停止收发。 socket.Shutdown(SocketShutdown.Both); } catch (Exception e) { //忽略 traceListener?.WriteLine(e); } finally { try { //等待已接受缓存处理完毕 //await tcpRemote.EndDealRecv(); //关闭接收,这个过程中可能调用本身出现异常。 //也可能导致异步接收部分抛出,由于disconnectSignal只能使用一次,所有这个阶段异常都会被忽略。 socket.Disconnect(false); } catch (Exception e) { //忽略 traceListener?.WriteLine(e); } finally { try { socket.Close(); if (triggerDisConnectHandle) { //触发回调 handler?.OnDisconnect(error, options); } } catch (Exception e) { //忽略 traceListener?.WriteLine(e.ToString()); } finally { if (triggerDisConnectHandle) { handler?.PostDisconnect(error, options); } } } } } public void OnRecv0(Socket client, IDisconnectHandler handler, TraceListener traceListener = null) { SafeClose(client, SocketError.Shutdown, handler, true, traceListener: traceListener); } } public class DisconnectOptions { public ActiveOrPassive ActiveOrPassive { get; set; } = ActiveOrPassive.Active; } }
Java
UTF-8
145
2.15625
2
[]
no_license
package ItemiComanda; public class PutInBottle implements Pachet { @Override public String pachet() { return "In sticla"; } }
C++
UTF-8
2,533
2.515625
3
[ "Apache-2.0" ]
permissive
#include <eosiolib/eosio.hpp> #include <eosiolib/print.hpp> #include <eosiolib/transaction.hpp> #include <eosiolib/crypto.h> #include <string> namespace Oasis { using namespace eosio; using std::string; class Players : public contract { using contract::contract; public: Players(account_name self):contract(self) {} //@abi action void add(account_name account, string& username); //@abi action void update(account_name account, uint64_t level, int64_t healthPoints, int64_t energyPoints); //@abi action void getplayer(const account_name account); //@abi action void addability(const account_name account, string& ability); //@abi action void fight(const account_name player1, const account_name player2); inline int64_t rand(); //@abi table item i64 struct item { uint64_t item_id; string name; uint64_t power; uint64_t health; string ability; uint64_t level_up; uint64_t primary_key() const { return item_id; } EOSLIB_SERIALIZE(item, (item_id)(name)(power)(health)(ability)(level_up)) }; //@abi action void additem(const account_name account, item purchased_item); //@abi table player i64 struct player { uint64_t account_name; string username; uint64_t level; int64_t health_points = 1000; int64_t energy_points = 1000; vector<string> abilities; vector<item> inventory; uint64_t primary_key() const { return account_name; } EOSLIB_SERIALIZE(player, (account_name)(username)(level)(health_points)(energy_points)(abilities)(inventory)) }; typedef multi_index<N(player), player> playerIndex; }; int64_t Players::rand() { checksum256 result; auto mixedBlock = tapos_block_prefix() * tapos_block_num(); const char *mixedChar = reinterpret_cast<const char *>(&mixedBlock); sha256( (char *)mixedChar, sizeof(mixedChar), &result); const char *p64 = reinterpret_cast<const char *>(&result); return int64_t(*p64); } EOSIO_ABI(Players, (add)(update)(getplayer)(addability)(additem)(fight)); }
Python
UTF-8
8,783
2.59375
3
[]
no_license
#-*-coding:utf-8-*- # author: by chenzhen # ============================================================================================= from tkinter import * import tkinter import tkinter.filedialog import os import tkinter.messagebox from PIL import Image, ImageTk from tkinter import ttk import deepdream import scipy import numpy as np import matplotlib.pyplot as plt ########## # 窗口属性 ########## root = tkinter.Tk() root.title('Deep Dream') root.geometry('1200x600') formatImg = ['jpg'] # ============================================================================================= ########## # 支撑函数 ########## def resize(w, h, w_box, h_box, pil_image): # 对一个pil_image对象进行缩放,让它在一个矩形框内,还能保持比例 f1 = 1.0*w_box/w # 1.0 forces float division in Python2 f2 = 1.0*h_box/h factor = min([f1, f2]) width = int(w*factor) height = int(h*factor) return pil_image.resize((width, height), Image.ANTIALIAS) def show_img(img_path): """ 选择背景文件后,显示在窗口中 """ pil_image = Image.open(img_path) # 打开图片 # 期望显示大小 w_box = 400 h_box = 400 # 获取原始图像的大小 w, h = pil_image.size pil_image_resized = resize(w, h, w_box, h_box, pil_image) # 把PIL图像对象转变为Tkinter的PhotoImage对象 tk_image = ImageTk.PhotoImage(pil_image_resized) img = tkinter.Label(image=tk_image, width=w_box, height=h_box) img.image = tk_image img.place(x=50, y=100) def choose_imgfile(): img_path = tkinter.filedialog.askopenfilename(title='选择文件') # 选择文件 if img_path[-3:] not in formatImg: tkinter.messagebox.askokcancel(title='出错', message='未选择图片或图片格式不正确') # 弹出错误窗口 return else: variable_path_bgimg.set(img_path) # 设置变量 show_img(img_path) # 显示图片 def show_new_img(img_array): """ 在窗口中显示生成的图片,(之后进行修改,将选择的背景图片与新生成的图片,使用的show函数写成一致) """ plt.imshow(np.uint8(img_array)) plt.xticks([]) plt.yticks([]) plt.show() class ImageArray(): """ 是为了能够保存新生成的图像数组 """ def __init__(self): self.img_array = None def set_imgarray(self, img_array): self.img_array = img_array def get_imgarray(self): return self.img_array def get_parameter(): """ 从窗口中获取用户设置的参数,并对其检查并返回; :return: """ select_conv_layer = combox_name_convlayer.get() # 选择的卷积层名称,全称 if bool_all_channel.get() == 1: # 判断是否使用全通都 print('bool_var_channel:', 1) select_conv_layer = select_conv_layer.split('_')[0] else: select_conv_layer = select_conv_layer.split('/conv')[0] path_bgimg = entry_path_bgimg.get() # 选择的背景图片路径名 iter_n = combobox_iter_num.get() # 迭代的次数 octave_n = combobox_octave_n.get() # 放大次数 octave_scale = combobox_octave_scale.get() # 放大倍数 channel = combobox_channel.get() # 所选择的通道数 return select_conv_layer, path_bgimg, iter_n, octave_n, octave_scale, channel # 实例化组对象 imgarray = ImageArray() def generate_img(): # 获取参数 select_conv_layer, path_bgimg, iter_n, octave_n, octave_scale, channel = get_parameter() # 判断是否选择卷积层和背景图片 if select_conv_layer is '' or path_bgimg is '': tkinter.messagebox.askokcancel(title='出错', message='shit\n未选择背景图片或卷积层') # 弹出错误窗口 else: # 生成图片 img_array = deepdream.generate_img(path_bgimg, select_conv_layer, int(iter_n), int(octave_n), float(octave_scale), int(channel), int(bool_all_channel.get())) # 将新生成图像赋值给数组对象,用于保存 imgarray.set_imgarray(img_array) # 提示生成成功,并进行显示 tkinter.messagebox.showinfo(title='提示信息', message='生成图片成功,即将显示') # 弹出提示信息 show_new_img(img_array) def save_img(): """ 保存图片,现在不使用了; 因为使用plt显示图片,其中自带的有将图片保存到本地; :return: """ img_array = imgarray.get_imgarray() if np.sum(img_array == None) == 1: tkinter.messagebox.askokcancel(title='出错', message='未正常生成图片') # 弹出错误窗口 else: img_name = tkinter.filedialog.asksaveasfilename(title='保存图片') # 弹出窗口,进行保存,返回文件名 if img_name[-3:] not in formatImg: tkinter.messagebox.askokcancel(title='出错', message='图片格式不正确\n请使用jpg格式') # 弹出错误窗口 return scipy.misc.toimage(img_array).save(img_name) tkinter.messagebox.showinfo(title='提示信息', message='保存图片成功') # 弹出提示信息 # ============================================================================================= ################## # 窗口部件 ################## variable_path_bgimg = tkinter.StringVar() # 字符串变量 ############ # 选择背景图片并显示 ############ # label : 选择文件 label_select_bgimg = tkinter.Label(root, text='选择背景图片:') label_select_bgimg.grid(row=0, column=0) # Entry: 显示图片文件路径地址 entry_path_bgimg = tkinter.Entry(root, width=80, textvariable=variable_path_bgimg) entry_path_bgimg.grid(row=0, column=1) # Button: 选择图片文件 button_select_bgimg = tkinter.Button(root, text="选择", command=choose_imgfile) button_select_bgimg.grid(row=0, column=2) ############ # 选择使用的卷积层 ############ # label : 选择使用的卷积层 label_select_bgimg = tkinter.Label(root, text='选择卷积层:') label_select_bgimg.grid(row=1, column=0) # combobox: 下拉菜单框 combox_name_convlayer = ttk.Combobox(root, width=80, height=20, textvariable='jjjj', state='readonly') combox_name_convlayer.grid(row=1, column=1) combox_name_convlayer["values"] = deepdream.get_convlayer() ############ # 开始生成图片并保存 ############ # Button: 执行识别程序按钮 button_recogImg = tkinter.Button(root, text="开始生成", command=generate_img) button_recogImg.grid(row=1, column=2) # Button: 保存新生成的图片 # button_recogImg = tkinter.Button(root, text="保存", command=save_img) # button_recogImg.grid(row=1, column=3) ############ # 参数设置 ############ # 迭代次数 var_iter_num = tkinter.StringVar(); var_iter_num.set(10) label_iter_num = tkinter.Label(root, text='iter_num:', font=18) label_iter_num.grid(row=8, column=4) combobox_iter_num = ttk.Combobox(root, width=10, height=8, textvariable=var_iter_num) combobox_iter_num.grid(row=8, column=5) combobox_iter_num["values"] = [i+1 for i in range(20)] # 放大倍数 var_octave_scale = tkinter.StringVar(); var_octave_scale.set(1.4) label_octave_scale = tkinter.Label(root, text='octave_scale:', font=18) label_octave_scale.grid(row=12, column=4) combobox_octave_scale = ttk.Combobox(root, width=10, height=5, textvariable=var_octave_scale) combobox_octave_scale.grid(row=12, column=5) combobox_octave_scale["values"] = list(np.linspace(1, 2, 11)) # 放大次数 var_octave_n = tkinter.StringVar(); var_octave_n.set(5) label_octave_n = tkinter.Label(root, text='octave_n:', font=18) label_octave_n.grid(row=16, column=4) combobox_octave_n = ttk.Combobox(root, width=10, height=5, textvariable=var_octave_n) combobox_octave_n.grid(row=16, column=5) combobox_octave_n["values"] = [i+1 for i in range(20)] # 选择通道 var_channel = tkinter.StringVar(); var_channel.set(139) label_channel = tkinter.Label(root, text='channel:', font=18) label_channel.grid(row=20, column=4) combobox_channel = ttk.Combobox(root, width=10, height=20, textvariable=var_channel) combobox_channel.grid(row=20, column=5) combobox_channel["values"] = [i+1 for i in range(150)] label_channel_point = tkinter.Label(root, text='注意:应小于该卷积层通道总数目', font=18) label_channel_point.grid(row=21, column=5) # 是否使用全通道 bool_all_channel = tkinter.IntVar() checkbutton_all_channel = tkinter.Checkbutton(root, text='All Channels?', font=18, variable=bool_all_channel) checkbutton_all_channel.grid(row=22, column=5) root.mainloop()
Java
UTF-8
4,340
2.640625
3
[]
no_license
package com.focaplo.ishout; import java.util.logging.Logger; public class MessageQueue { private static final Logger log = Logger.getLogger(MessageQueue.class.getName()); public static int defaultSize = 1000; public long totalMessage=0; public long getTotalMessage() { return totalMessage; } public void setTotalMessage(long totalMessage) { this.totalMessage = totalMessage; } public int getDefaultSize() { return defaultSize; } public void setDefaultSize(int defaultSize) { this.defaultSize = defaultSize; } @Override public String toString() { StringBuffer buf = new StringBuffer("--------------- queue content p= " + p + "----------"); for(int i=0;i<storage.length;i++){ if(storage[i]!=null && !storage[i].equals("")){ buf.append("\n" + i+"="+storage[i]); } } buf.append("\n------------ end ------------"); return buf.toString(); } public int p = 0; //public List<String> storage = new ArrayList<String>(2000); String[] storage; public String[] getStorage() { return storage; } public void setStorage(String[] storage) { this.storage = storage; } public MessageQueue(int storage){ super(); this.init(); } private void init(){ storage = new String[defaultSize]; for(int i=0; i<storage.length;i++){ storage[i] = ""; } } public void increaseQueueSite(int newSize){ String[] newStorage = new String[newSize]; for(int i=0;i<this.storage.length;i++){ newStorage[i] = this.storage[i]; } this.storage=newStorage; } public String addMessage(String msg){ synchronized(this){ storage[p++] = msg; //p point to the next "space" p%= defaultSize; //[0-1999] } // this.totalMessage++; return ""; } public String addMessagePowerBall(String msg){ for(int i=0;i<10;i++){ this.addMessage(msg); } return ""; } public String getMessages(int lastId){ int currentp = 0; synchronized(this){ currentp=p; } try{ if(lastId==99999){ //first req after listener starts, will return 20 messages from p (p-20->p) if(currentp>=20){ lastId=currentp-21; }else{ lastId=-1; } } if(currentp-1==lastId || currentp==lastId){ //no message? return "SUCCESS|"+((currentp-1)>=0?(currentp-1):99999); } int candidates = 0; if(currentp>lastId){ //pick from lastId+1 to p-1 candidates = currentp-lastId-1; }else{ candidates = defaultSize - lastId -1 + currentp; } if(candidates<0){ log.warning("something wrong,should not happen! candidates<0 with lastId=" + lastId + " currentp="+currentp); return "SUCCESS|" +((currentp-1)>=0?(currentp-1):0); } int maxReturnMessages = 100; if(candidates<100){ maxReturnMessages=100; }else if(candidates<300){ maxReturnMessages=120; }else{ maxReturnMessages=120; } int totalReturnMessage=0; StringBuffer buf = new StringBuffer(); if(currentp>lastId){ int possibleMsgNum = candidates<maxReturnMessages?candidates:maxReturnMessages; //try to get latest message instead of starting from last-id int start = p-possibleMsgNum; if(start<0){ start=0; } totalReturnMessage = totalReturnMessage + this.getMessages(buf, start, currentp); }else if(currentp<lastId){ int possibleMsgNum = candidates<maxReturnMessages?candidates:maxReturnMessages; int start=p-possibleMsgNum; if(start>0){ //grab from start->p totalReturnMessage = totalReturnMessage + this.getMessages(buf, start, currentp); }else{ //2 rounds //grab from 0->p totalReturnMessage = totalReturnMessage + this.getMessages(buf, 0, currentp); //grab from defaultSize+start->defaultSize (start<0) totalReturnMessage = totalReturnMessage + this.getMessages(buf, defaultSize+start, defaultSize); } } return "SUCCESS|" + ((currentp-1)>=0?(currentp-1):0) + "|" + buf.toString(); }catch(Exception e){ log.warning("error:" + e.getMessage()); return "SUCCESS|"+currentp; } } private int getMessages(StringBuffer buf, int start, int end){ int totalReturnMessage = 0; boolean first=true; for(int i=start;i<end;i++){ totalReturnMessage++; if(first){ first=false; buf.append(storage[i]); }else{ buf.append("^" + storage[i]); } } return totalReturnMessage; } }
Shell
UTF-8
361
2.578125
3
[ "MIT" ]
permissive
#!/bin/bash echo "Installing Spotify..." # Add the repository add-repo "deb http://repository.spotify.com stable non-free" # Add the repository signing key to be able to verify downloaded packages apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys D2C19886 # Update list of available packages apt-update # Install apt-install spotify-client
Python
UTF-8
164
3.5
4
[]
no_license
#n_dice task a = input ("Please enter the number dice's sides: ") b = int(a) from random import randint dice = randint (1, b) print ("You have thrown:") print(dice)
Python
UTF-8
255
3.125
3
[]
no_license
class Appliance: month = 30 """cost: float - passed upon initialization. The cost is for a single day""" def __init__(self, cost: float): self.cost = cost def get_monthly_expense(self): return self.cost * Appliance.month
Java
UTF-8
6,720
1.96875
2
[]
no_license
package org.geojsf.model.xml.geojsf; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element ref="{http://www.geojsf.org}scale"/&gt; * &lt;/sequence&gt; * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}long" /&gt; * &lt;attribute name="lat" type="{http://www.w3.org/2001/XMLSchema}double" /&gt; * &lt;attribute name="lon" type="{http://www.w3.org/2001/XMLSchema}double" /&gt; * &lt;attribute name="bottom" type="{http://www.w3.org/2001/XMLSchema}double" /&gt; * &lt;attribute name="left" type="{http://www.w3.org/2001/XMLSchema}double" /&gt; * &lt;attribute name="right" type="{http://www.w3.org/2001/XMLSchema}double" /&gt; * &lt;attribute name="top" type="{http://www.w3.org/2001/XMLSchema}double" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "scale" }) @XmlRootElement(name = "viewPort") public class ViewPort implements Serializable { private final static long serialVersionUID = 1L; @XmlElement(required = true) protected Scale scale; @XmlAttribute(name = "id") protected Long id; @XmlAttribute(name = "lat") protected Double lat; @XmlAttribute(name = "lon") protected Double lon; @XmlAttribute(name = "bottom") protected Double bottom; @XmlAttribute(name = "left") protected Double left; @XmlAttribute(name = "right") protected Double right; @XmlAttribute(name = "top") protected Double top; /** * Gets the value of the scale property. * * @return * possible object is * {@link Scale } * */ public Scale getScale() { return scale; } /** * Sets the value of the scale property. * * @param value * allowed object is * {@link Scale } * */ public void setScale(Scale value) { this.scale = value; } public boolean isSetScale() { return (this.scale!= null); } /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public long getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(long value) { this.id = value; } public boolean isSetId() { return (this.id!= null); } public void unsetId() { this.id = null; } /** * Gets the value of the lat property. * * @return * possible object is * {@link Double } * */ public double getLat() { return lat; } /** * Sets the value of the lat property. * * @param value * allowed object is * {@link Double } * */ public void setLat(double value) { this.lat = value; } public boolean isSetLat() { return (this.lat!= null); } public void unsetLat() { this.lat = null; } /** * Gets the value of the lon property. * * @return * possible object is * {@link Double } * */ public double getLon() { return lon; } /** * Sets the value of the lon property. * * @param value * allowed object is * {@link Double } * */ public void setLon(double value) { this.lon = value; } public boolean isSetLon() { return (this.lon!= null); } public void unsetLon() { this.lon = null; } /** * Gets the value of the bottom property. * * @return * possible object is * {@link Double } * */ public double getBottom() { return bottom; } /** * Sets the value of the bottom property. * * @param value * allowed object is * {@link Double } * */ public void setBottom(double value) { this.bottom = value; } public boolean isSetBottom() { return (this.bottom!= null); } public void unsetBottom() { this.bottom = null; } /** * Gets the value of the left property. * * @return * possible object is * {@link Double } * */ public double getLeft() { return left; } /** * Sets the value of the left property. * * @param value * allowed object is * {@link Double } * */ public void setLeft(double value) { this.left = value; } public boolean isSetLeft() { return (this.left!= null); } public void unsetLeft() { this.left = null; } /** * Gets the value of the right property. * * @return * possible object is * {@link Double } * */ public double getRight() { return right; } /** * Sets the value of the right property. * * @param value * allowed object is * {@link Double } * */ public void setRight(double value) { this.right = value; } public boolean isSetRight() { return (this.right!= null); } public void unsetRight() { this.right = null; } /** * Gets the value of the top property. * * @return * possible object is * {@link Double } * */ public double getTop() { return top; } /** * Sets the value of the top property. * * @param value * allowed object is * {@link Double } * */ public void setTop(double value) { this.top = value; } public boolean isSetTop() { return (this.top!= null); } public void unsetTop() { this.top = null; } }
JavaScript
UTF-8
1,829
2.625
3
[ "MIT" ]
permissive
/** * Created by KlimMalgin on 21.10.2014. */ 'use strict'; var assert = require("assert"); var Morphine = require("../Morphine"); describe('Builder tests', function () { var builder = MorphineShareApi.builder; describe('Проверка сборки объекта', function () { it('Сборка набора вложенных объектов из строкового path. Без операции merge', function () { /** * За merge отвечает третий параметр метода builder */ var morph = new Morphine(); var expected = { root: { l1: { l2: { l3: 45 } } } }; builder.call(morph, 'root.l1.l2.l3', 45, true); assert.deepEqual(morph, expected, 'Morphine-сущность собранная из path "root.l1.l2.l3" и значением 45 совпадает с ожидаемым объектом.'); }); it('Сборка набора вложенных объектов с массивами. Без операции merge', function () { var morph = new Morphine(); var expected = { root: { l1: [ { value: 23 } ] } }; builder.call(morph, 'root.l1.$.value', 23, true); assert.deepEqual(morph.plain(), expected, 'Morphine-сущность собранная из path "root.l1.$.value" и значением 23 совпадает с ожидаемым объектом.'); }); }); });
Java
UTF-8
9,220
1.734375
2
[ "BSD-3-Clause" ]
permissive
/* * This software is distributed under following license based on modified BSD * style license. * ---------------------------------------------------------------------- * * Copyright 2003 The Nimbus Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NIMBUS PROJECT ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL THE NIMBUS PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the Nimbus Project. */ package jp.ossc.nimbus.service.test.stub.http; import java.io.File; import jp.ossc.nimbus.core.ServiceName; import jp.ossc.nimbus.service.http.proxy.HttpProcessServiceBaseMBean; import jp.ossc.nimbus.service.test.TestStub; /** * {@link HttpTestStubService}のMBeanインタフェース<p> * * @author M.Takata * @see HttpTestStubService */ public interface HttpTestStubServiceMBean extends HttpProcessServiceBaseMBean, TestStub{ /** * スタブIDを設定する。<p> * * @param id スタブID */ public void setId(String id); /** * スタブIDを取得する。<p> * * @return スタブID */ public String getId(); /** * リソースファイルの文字エンコーディングを設定する。<p> * * @param encoding 文字エンコーディング */ public void setFileEncoding(String encoding); /** * リソースファイルの文字エンコーディングを取得する。<p> * * @return 文字エンコーディング */ public String getFileEncoding(); /** * {@link jp.ossc.nimbus.service.test.StubResourceManager StubResourceManager}サービスのサービス名を設定する。<p> * * @param name StubResourceManagerサービスのサービス名 */ public void setStubResourceManagerServiceName(ServiceName name); /** * {@link jp.ossc.nimbus.service.test.StubResourceManager StubResourceManager}サービスのサービス名を取得する。<p> * * @return StubResourceManagerサービスのサービス名 */ public ServiceName getStubResourceManagerServiceName(); /** * {@link jp.ossc.nimbus.service.interpreter.Interpreter Interpreter}サービスのサービス名を設定する。<p> * * @param name Interpreterサービスのサービス名 */ public void setInterpreterServiceName(ServiceName name); /** * {@link jp.ossc.nimbus.service.interpreter.Interpreter Interpreter}サービスのサービス名を取得する。<p> * * @return Interpreterサービスのサービス名 */ public ServiceName getInterpreterServiceName(); /** * StubResourceManagerからダウンロードしたリソースファイルを配置するディレクトリを設定する。<p> * デフォルトは、サービス定義ファイルの場所にスタブIDでディレクトリを配置する。<br> * * @param dir ディレクトリ */ public void setResourceDirectory(File dir); /** * StubResourceManagerからダウンロードしたリソースファイルを配置するディレクトリを取得する。<p> * * @return ディレクトリ */ public File getResourceDirectory(); /** * HTTPレスポンスに指定するHTTPバージョンを設定する。<p> * * @param version HTTPバージョン */ public void setHttpVersion(String version); /** * HTTPレスポンスに指定するHTTPバージョンを取得する。<p> * * @return HTTPバージョン */ public String getHttpVersion(); /** * 共通で設定するHTTPレスポンスヘッダを設定する。<p> * * @param name ヘッダ名 * @param values ヘッダ値の配列 */ public void setHttpHeaders(String name, String[] values); /** * 共通で設定するHTTPレスポンスヘッダを取得する。<p> * * @param name ヘッダ名 * @return ヘッダ値の配列 */ public String[] getHttpHeaders(String name); /** * 共通で設定するHTTPレスポンスヘッダ文字列を取得する。<p> * * @return HTTPヘッダ文字列 */ public String getHttpHeader(); /** * バイナリで指定するレスポンスファイルの拡張子を設定する。<p> * * @param exts 拡張子の配列 */ public void setBinaryFileExtensions(String[] exts); /** * バイナリで指定するレスポンスファイルの拡張子を取得する。<p> * * @return 拡張子の配列 */ public String[] getBinaryFileExtensions(); /** * 同じリクエストの繰り返しを許すかどうかを判定する。<p> * * @return trueの場合、許す */ public boolean isAllowRepeatRequest(); /** * 同じリクエストの繰り返しを許すかどうかを設定する。<p> * * @param isAllow 許す場合、true */ public void setAllowRepeatRequest(boolean isAllow); /** * マルチスレッド処理を安全に行うかどうかを判定する。<p> * * @return trueの場合、安全に行う */ public boolean isSafeMultithread(); /** * マルチスレッド処理を安全に行うかどうかを設定する。<p> * デフォルトは、true。<br> * * @param isSafe 安全に行う場合、true */ public void setSafeMultithread(boolean isSafe); /** * リクエストをファイルに保存するかどうかを判定する。<p> * * @return trueの場合、保存する */ public boolean isSaveRequestFile(); /** * リクエストをファイルに保存するかどうかを設定する。<p> * デフォルトは、true。<br> * * @param isSave 保存する場合、true */ public void setSaveRequestFile(boolean isSave); /** * 読み込んだレスポンスをキャッシュするかどうかを判定する。<p> * * @return trueの場合、キャッシュする */ public boolean isCacheResponse(); /** * 読み込んだレスポンスをキャッシュするかどうかを設定する。<p> * デフォルトは、falseで、キャッシュしない。<br> * * @param isCache キャッシュする場合、true */ public void setCacheResponse(boolean isCache); /** * OPTIONリクエストに自動で応答するかどうかを判定する。<p> * * @return trueの場合、自動で応答するか */ public boolean isAutoOptionsResponse(); /** * OPTIONリクエストに自動で応答するかどうかを設定する。<p> * デフォルトは、false。 * * @param isAuto 自動で応答する場合、true */ public void setAutoOptionsResponse(boolean isAuto); /** * OPTIONリクエストに自動応答する場合に返すAllowヘッダを設定する。<p> * CORSの場合は、Access-Control-Allow-Methodsヘッダに設定する。<br> * デフォルトは、"OPTIONS", "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"。<br> * * @param methods HTTPメソッド名の配列 */ public void setAllowMethods(String[] methods); /** * OPTIONリクエストに自動応答する場合に返すAllowヘッダを取得する。<p> * * @return HTTPメソッド名の配列 */ public String[] getAllowMethods(); }
C#
UTF-8
4,358
3.09375
3
[ "MIT" ]
permissive
/////////////////////////////////////////////////////////////////////////// // TestUtilities.cs - aids for testing // // Version 1.0 // // Jim Fawcett, CSE681-OnLine Software Modeling & Analysis, Spring 2017 // /////////////////////////////////////////////////////////////////////////// /* * Package Operations: * ------------------- * This package contains a single class TestUtilities with public functions: * - checkResult : displays pass-fail message * - checkNull : displays message and returns value == null * - handleInvoke : accepts runnable object and invokes it, displays exception message * - title : writes underlined title text to console * - putLine : writes optional message and newline to console * * Required Files: * --------------- * - TestUtilities - Helper class that is used mostly for testing * - IPluggable - Repository interfaces and shared data * * Maintenance History: * -------------------- * ver 2.0 : 19 Oct 2017 * - renamed namespace * ver 1.0 : 31 May 2017 * - first release * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MessagePassingComm { public class TestUtilities { /*----< saves duplicating presentation of results >------------*/ public static void checkResult(bool result, string compName) { //if (!ClientEnvironment.verbose) // return; if (result) Console.Write("\n -- {0} test passed", compName); else Console.Write("\n -- {0} test failed", compName); } /*----< check for null reference >-----------------------------*/ public static bool checkNull(object value, string msg="") { if (value == null && ClientEnvironment.verbose) { Console.Write("\n null reference"); if (msg.Length > 0) Console.Write("\n {0}", msg); return true; } return (value == null); } /*----< saves duplicating exception handling >-----------------*/ /* * - invokes runnable inside try/catch block * - returns true only if no exception is thrown and * runnable returns true; * - intent is that runnable only returns true if * its operation succeeds. */ public static bool handleInvoke(Func<bool> runnable, string msg="") { try { return runnable(); } catch(Exception ex) { if (ClientEnvironment.verbose) { Console.Write("\n {0}", ex.Message); if (msg.Length > 0) Console.Write("\n {0}", msg); } return false; } } /*----< pretty print titles >----------------------------------*/ public static void title(string msg, char ch = '-') { Console.Write("\n {0}", msg); Console.Write("\n {0}", new string(ch, msg.Length + 2)); } /*----< pretty print titles >----------------------------------*/ public static void vbtitle(string msg, char ch = '-') { if(ClientEnvironment.verbose) { Console.Write("\n {0}", msg); Console.Write("\n {0}", new string(ch, msg.Length + 2)); } } /*----< write line of text only if verbose mode is set >-------*/ public static void putLine(string msg="") { if (ClientEnvironment.verbose) { if (msg.Length > 0) Console.Write("\n {0}", msg); else Console.Write("\n"); } } #if(TEST_TESTUTILITIES) /*----< construction test >------------------------------------*/ static void Main(string[] args) { title("Testing TestUtilities", '='); ClientEnvironment.verbose = true; Func<bool> passTest = () => { Console.Write("\n pass test"); return true; }; checkResult(handleInvoke(passTest), "TestUtilities.handleInvoke"); Func<bool> failTest = () => { Console.Write("\n fail test"); return false; }; checkResult(handleInvoke(failTest), "TestUtilities.handleInvoke"); Func<bool> throwTest = () => { Console.Write("\n throw test"); throw new Exception(); return false; }; checkResult(handleInvoke(throwTest), "TestUtilities.handleInvoke"); Console.Write("\n\n"); } } } #endif
Java
UTF-8
2,791
2.40625
2
[]
no_license
package com.sun.mail.imap; import com.sun.mail.iap.ProtocolException; import com.sun.mail.imap.protocol.IMAPProtocol; import com.sun.mail.imap.protocol.ListInfo; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.MethodNotSupportedException; public class DefaultFolder extends IMAPFolder { protected DefaultFolder(IMAPStore var1) { super("", '\uffff', var1); this.exists = true; this.type = 2; } public void appendMessages(Message[] var1) throws MessagingException { throw new MethodNotSupportedException("Cannot append to Default Folder"); } public boolean delete(boolean var1) throws MessagingException { throw new MethodNotSupportedException("Cannot delete Default Folder"); } public Message[] expunge() throws MessagingException { throw new MethodNotSupportedException("Cannot expunge Default Folder"); } public Folder getFolder(String var1) throws MessagingException { return new IMAPFolder(var1, '\uffff', (IMAPStore)this.store); } public String getName() { return this.fullName; } public Folder getParent() { return null; } public boolean hasNewMessages() throws MessagingException { return false; } public Folder[] list(final String var1) throws MessagingException { ListInfo[] var2 = (ListInfo[])null; var2 = (ListInfo[])this.doCommand(new IMAPFolder.ProtocolCommand() { public Object doCommand(IMAPProtocol var1x) throws ProtocolException { return var1x.list("", var1); } }); int var3 = 0; if (var2 == null) { return new Folder[0]; } else { int var4 = var2.length; IMAPFolder[] var5; for(var5 = new IMAPFolder[var4]; var3 < var4; ++var3) { var5[var3] = new IMAPFolder(var2[var3], (IMAPStore)this.store); } return var5; } } public Folder[] listSubscribed(final String var1) throws MessagingException { ListInfo[] var2 = (ListInfo[])null; var2 = (ListInfo[])this.doCommand(new IMAPFolder.ProtocolCommand() { public Object doCommand(IMAPProtocol var1x) throws ProtocolException { return var1x.lsub("", var1); } }); int var3 = 0; if (var2 == null) { return new Folder[0]; } else { int var4 = var2.length; IMAPFolder[] var5; for(var5 = new IMAPFolder[var4]; var3 < var4; ++var3) { var5[var3] = new IMAPFolder(var2[var3], (IMAPStore)this.store); } return var5; } } public boolean renameTo(Folder var1) throws MessagingException { throw new MethodNotSupportedException("Cannot rename Default Folder"); } }
Java
UTF-8
11,020
2.59375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.uan.fis.jeesample.dao.impl; import edu.uan.fis.jeesample.dao.ClienteDao; import edu.uan.fis.jeesample.dto.Cliente; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author lenovo */ public class ClienteDaoJdbc implements ClienteDao { public Cliente create(Cliente cliente) { // Sample code Connection conn = null; PreparedStatement stmt = null; try { // 1. Register the JDBC driver Class.forName("com.mysql.jdbc.Driver"); // 2. Get the connection for the URL jdbc:mysql://address:port/dbname?user=username&password=userpassword conn = DriverManager.getConnection("jdbc:mysql://localhost/catalogotienda?" + "user=root&password=admin"); // 3. Creates the cliente in the database String insertData= "INSERT INTO `tbl_cliente`(`nom_cliente`, `user`, `password`) VALUES (?,?,?)"; stmt = conn.prepareStatement(insertData); //stmt.setInt(1,cliente.getClienteId()); stmt.setString(1,cliente.getName()); stmt.setString(2,cliente.getUser()); stmt.setString(3,cliente.getPassword()); stmt.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } finally { try { stmt.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } try { conn.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } } return cliente; } public Cliente update(Cliente cliente) { Connection conn = null; PreparedStatement stmt = null; try { // 1. Register the JDBC driver Class.forName("com.mysql.jdbc.Driver"); // 2. Get the connection for the URL jdbc:mysql://address:port/dbname?user=username&password=userpassword conn = DriverManager.getConnection("jdbc:mysql://localhost/catalogotienda?" + "user=root&password=admin"); String updateTableSQL = "UPDATE tbl_cliente SET nom_cliente = ? WHERE id_cliente = ?"; stmt = conn.prepareStatement(updateTableSQL); // 3. actualizar cliente en la base de datos PreparedStatement preparedStatement = conn.prepareStatement(updateTableSQL); preparedStatement.setString(1, "Burn uno"); preparedStatement.setInt(2, 4); // execute insert SQL stetement preparedStatement .executeUpdate(); //stmt.executeUpdate("INSERT INTO tbl_cliente VALUES(" + cliente.getClienteId() + ",'" + cliente.getName() + "')"); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } finally { try { stmt.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } try { conn.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } } return cliente; //} //throw new UnsupportedOperationException("Not supported yet."); } public void delete(Cliente cliente) { Connection conn = null; PreparedStatement stmt = null; try { // 1. Register the JDBC driver Class.forName("com.mysql.jdbc.Driver"); // 2. Get the connection for the URL jdbc:mysql://address:port/dbname?user=username&password=userpassword conn = DriverManager.getConnection("jdbc:mysql://localhost/catalogotienda?" + "user=root&password=admin"); String updateTableSQL = "DELETE FROM tbl_cliente WHERE id_cliente = ?"; stmt = conn.prepareStatement(updateTableSQL); // 3. actualizar cliente en la base de datos PreparedStatement preparedStatement = conn.prepareStatement(updateTableSQL); //preparedStatement.setString(1, 1); preparedStatement.setInt(1, 5); // execute insert SQL stetement preparedStatement .executeUpdate(); //stmt.executeUpdate("INSERT INTO tbl_cliente VALUES(" + cliente.getClienteId() + ",'" + cliente.getName() + "')"); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } finally { try { stmt.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } try { conn.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } } } public Cliente findById(Integer clienteId) { Cliente cliente=null; Connection conn = null; ResultSet rs=null; PreparedStatement stmt = null; try { // 1. Register the JDBC driver Class.forName("com.mysql.jdbc.Driver"); // 2. Get the connection for the URL jdbc:mysql://address:port/dbname?user=username&password=userpassword conn = DriverManager.getConnection("jdbc:mysql://localhost/catalogotienda?" + "user=root&password=admin"); String updateTableSQL = "Select * FROM tbl_cliente WHERE id_cliente = ?"; stmt = conn.prepareStatement(updateTableSQL); // 3. actualizar cliente en la base de datos PreparedStatement preparedStatement = conn.prepareStatement(updateTableSQL); //preparedStatement.setString(1, 1); preparedStatement.setInt(1, 2); // execute insert SQL stetement rs=preparedStatement.executeQuery(); while (rs.next()) { cliente=new Cliente(); int idcliente=rs.getInt("id_cliente"); String nombre=rs.getString("nom_cliente"); cliente.setClienteId(idcliente); System.out.println(idcliente); cliente.setName(nombre); System.out.println(nombre); } } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } finally { try { rs.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } try { stmt.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } try { conn.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } } return cliente; } public List<Cliente> findAll() { Cliente cliente=null; Connection conn = null; ResultSet rs=null; PreparedStatement stmt = null; List<Cliente> clientes = new ArrayList<Cliente>(); try { // 1. Register the JDBC driver Class.forName("com.mysql.jdbc.Driver"); // 2. Get the connection for the URL jdbc:mysql://address:port/dbname?user=username&password=userpassword conn = DriverManager.getConnection("jdbc:mysql://localhost/catalogotienda?" + "user=root&password=admin"); String updateTableSQL = "Select * FROM tbl_cliente"; stmt = conn.prepareStatement(updateTableSQL); // 3. actualizar cliente en la base de datos PreparedStatement preparedStatement = conn.prepareStatement(updateTableSQL); preparedStatement.executeQuery(); rs=preparedStatement.executeQuery(); while (rs.next()) { cliente=new Cliente(); cliente.setClienteId(rs.getInt("id_cliente")); cliente.setName(rs.getString("nom_cliente")); clientes.add(cliente); int idcliente=rs.getInt("id_cliente"); String nombre=rs.getString("nom_cliente"); String usuario=rs.getString("user"); cliente.setName(nombre); cliente.setUser(usuario); cliente.setClienteId(idcliente); System.out.println("ID: "+idcliente+" Nombre Cliente: "+nombre+" Nombre de Usuario: "+usuario); } //stmt.executeUpdate("INSERT INTO tbl_cliente VALUES(" + cliente.getClienteId() + ",'" + cliente.getName() + "')"); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } finally { try { rs.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } try { stmt.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } try { conn.close(); } catch (SQLException ex) { Logger.getLogger(ClienteDaoJdbc.class.getName()).log(Level.SEVERE, null, ex); } } return clientes; } }
Python
UTF-8
2,604
3.65625
4
[]
no_license
class DuLNode(object): def __init__(self, k, v, pre, nxt): self.pre = pre self.nxt = nxt self.key = k self.value = v class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self.head = DuLNode(None, 'head', None, None) self.tail = DuLNode(None, 'tail', None, None) self.head.nxt = self.tail self.tail.pre = self.head self.map = dict() def get(self, key): """ :type key: int :rtype: int """ self.show_link() if key not in self.map: return -1 node = self.map[key] self.move_to_first(node) return node.value def put(self, key, value): """ :type key: int :type value: int :rtype: None """ self.show_link() if key in self.map: node = self.map[key] node.value = value self.move_to_first(node) return if len(self.map) == self.capacity: self.remove_tail() new_node = DuLNode(key, value, None, None) self.move_to_first(new_node) self.map[key] = new_node def move_to_first(self, node): if node is None: return node_pre = node.pre node_nxt = node.nxt if node_pre is not None: node_pre.nxt = node_nxt if node_nxt is not None: node_nxt.pre = node_pre head_nxt = self.head.nxt self.head.nxt = node node.pre = self.head node.nxt = head_nxt head_nxt.pre = node def remove_tail(self): tail_pre = self.tail.pre tail_pre_pre = tail_pre.pre if tail_pre_pre is None: return tail_pre_pre.nxt = self.tail self.tail.pre = tail_pre_pre # print('delete map key=%s', tail_pre.key) del self.map[tail_pre.key] def show_link(self): return now = self.head while now is not None: print('now=%s, pre=%s, next=%s', now.pre.value if now.pre else None, now.value, now.nxt.value if now.nxt else None) now = now.nxt # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value) cache = LRUCache(2) print(cache.put(1, 1)) print(cache.put(2, 2)) print(cache.get(1)) print(cache.put(3, 3)) print(cache.get(2)) print(cache.put(4, 4)) print(cache.get(1)) print(cache.get(3)) print(cache.get(4))
Java
UTF-8
640
3.109375
3
[ "NCSA" ]
permissive
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] coinVals = new int[m]; for (int i =0; i<m; i++){ coinVals[i] = sc.nextInt(); } System.out.print(numWays(coinVals, n)); } public static int numWays(int[] coinVals, int n){ int[] numVals = new int[n+1]; numVals[0] = 1; for(int a: coinVals){ for(int j = a; j< numVals.length; j++) numVals[j] = numVals[j] + numVals[j - a]; } return numVals[n]; } }
C++
UTF-8
1,195
3.046875
3
[]
no_license
/** Dragon Dragon Logic Class responsible for creating the light show on the CC3200 Demo Board. created 7 June 2015 by Mitchell McGinnis */ int buttonState = 0; int led1 = 2; int led2 = 3; //Prepare the LED's and Pins for the Dragons void setupDragon() { pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); digitalWrite(led1, LOW); digitalWrite(led2, LOW); pinMode(11, INPUT_PULLUP); } //the main dragon loop void loopDragon() { buttonState = digitalRead(11); if (mode == 'o'){ if(DEBUG) Serial.println("Off"); digitalWrite(led1, LOW); digitalWrite(led2, LOW); } else { if(buttonState || mode == 'd'){ digitalWrite(led1, HIGH); digitalWrite(led2, LOW); delay(40); digitalWrite(led1, LOW); digitalWrite(led2, HIGH); delay(40); }else if(mode == 'p'){ loopPuff(); } if(DEBUG) Serial.println("On"); } } //Slow alternating blinking LED's void loopPuff(){ digitalWrite(led1, HIGH); delay(500); digitalWrite(led1, LOW); digitalWrite(led2, HIGH); delay(500); digitalWrite(led2, LOW); }
C++
UTF-8
419
2.765625
3
[]
no_license
#include "pch.h" #include "Wache.h" Wache::Wache() { _state = new WachePatrouillieren(); } Wache::~Wache() { } void Wache::handleInput(string input) { WacheStatus* state = _state->handleInput(*this, input); if (state != nullptr) { _state->exit(*this); delete _state; _state = state; _state->entry(*this); } } void Wache::update() { _state->update(*this); cout << "Futter count: " << food << endl; }
Python
UTF-8
142
2.859375
3
[]
no_license
def classifica_idade(x): if x<11: return crianca elif 12<x<17: return adolescente else: return adulto
PHP
UTF-8
465
2.828125
3
[]
no_license
<?php namespace App\Commands; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class SayHelloWorld extends Command { public function configure() { $this->setName('say:hello')->setDescription('Say Hello'); } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Hello World'); } }
Python
UTF-8
1,303
2.9375
3
[]
no_license
#This program should be called from the main folder as following # #python -m examples.lstm_example import numpy as np from optimizer.lstm import LSTMNet from core.bot import Bot print "Loading dataset" train_set = np.load("dataset/SP500/train_set.npy") validation_set = np.load("dataset/SP500/validation_set.npy") #very short sequence for debugging purpose train_set = train_set[:,:,:] validation_set = validation_set[:,:,:] n_series = 1 n_features = 1 #timing & volume config = { #Shape (2,10) means 2 layers of 10 neurons "sharedBoxShape" : (1,10), "blocksShape": (1,10), "nLSTMCells": 10, "decisionBlockShape": (1,10), "dropout": 1., "batch_size": 10 } print "Model configuration" opt = LSTMNet(config, train_set, validation_set, n_series, n_features) print "Learning started" for i in xrange(0,1): out_ = opt.learn() print "Epoch" , i, ":", "train gain:", out_[0], "validation gain:", out_[1] suggester = opt.finalize() bot = Bot(suggester,n_series,n_features,False,1000, 0.1) capital = [] for i in range(validation_set.shape[0]): bot.reset() for t in range(validation_set.shape[1]): bot.step(validation_set[i,t,:]) capital.append(bot.getVirtualCapital()) print "you gained:", (sum(capital) /( len(capital) + 0.0))
Shell
UTF-8
400
3.265625
3
[]
no_license
#!/bin/bash echo "what is your name" read name echo "select the operation, $name ************" echo " 1)tell a joke" echo " 2)Show disk usage" echo " 3)Show current dir" echo " 4)exit" read n while true ; do case $n in 1) echo "this is a joke";; 2) df;; 3) pwd;; 4) echo "goodbye, $name" exit;; *) echo "invalid option";; esac echo "choose again" read n done
Java
UTF-8
668
2.109375
2
[]
no_license
package app.flora.Models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Payment { @SerializedName("friendly_name") @Expose private String friendly_name; @SerializedName("system_name") @Expose private String system_name; public String getFriendly_name() { return friendly_name; } public void setFriendly_name(String friendly_name) { this.friendly_name = friendly_name; } public String getSystem_name() { return system_name; } public void setSystem_name(String system_name) { this.system_name = system_name; } }
JavaScript
UTF-8
1,659
3.15625
3
[]
no_license
/** * @param {String} url * @description 从URL中解析参数 */ export const getParams = url => { const keyValueArr = url.split('?')[1].split('&') let paramObj = {} keyValueArr.forEach(item => { const keyValue = item.split('=') paramObj[keyValue[0]] = keyValue[1] }) return paramObj } /** * @returns {String} 当前浏览器名称 */ export const getExplorer = () => { const ua = window.navigator.userAgent const isExplorer = (exp) => { return ua.indexOf(exp) > -1 } if (isExplorer('MSIE')) return 'IE' else if (isExplorer('Firefox')) return 'Firefox' else if (isExplorer('Chrome')) return 'Chrome' else if (isExplorer('Opera')) return 'Opera' else if (isExplorer('Safari')) return 'Safari' } /** * @description 绑定事件 on(element, event, handler) */ export const on = (function () { if (document.addEventListener) { return function (element, event, handler) { if (element && event && handler) { element.addEventListener(event, handler, false) } } } else { return function (element, event, handler) { if (element && event && handler) { element.attachEvent('on' + event, handler) } } } })() /** * @description 解绑事件 off(element, event, handler) */ export const off = (function () { if (document.removeEventListener) { return function (element, event, handler) { if (element && event) { element.removeEventListener(event, handler, false) } } } else { return function (element, event, handler) { if (element && event) { element.detachEvent('on' + event, handler) } } } })()
Shell
UTF-8
870
2.828125
3
[]
no_license
#!/bin/bash source /home/xuemm/software/gromacs-5.0.7/bin/GMXRC GMXGMP='gmx grompp' MDRUN='gmx mdrun' array_ele=(`seq -0.010 0.001 0.010`) CP=/bin/cp RM=/bin/rm MV=/bin/mv for ele in ${array_ele[@]} do DIR="E_$ele" if [ -e $DIR ]; then cd $DIR else mkdir $DIR && cd $DIR fi ELE=$ele $CP ../md.mdp md.mdp $CP ../gmx.qsub gmx.qsub $CP -R ../charmm.ff/ . sed -i "s/0 0.5 0/1 $ele 0/g" md.mdp #n_p=`cat /proc/cpuinfo | grep processor | wc -l` #n_omp=$((n_p/2)) sed -i "s/JOBNAME/E_$ele/g" gmx.qsub #sed -i "s/NUMBEROFPROCESSORS/$n_p/g" gmx.qsub #sed -i "s/NUMBEROFOMPTHREADS/$n_omp/g" gmx.qsub $GMXGMP -f md.mdp -c ../em.gro -n ../system.ndx -p ../system.top -maxwarn 10 -o md.tpr qsub gmx.qsub cd .. done #for ele in ${array_ele[@]} #do #DIR="E_$ele" #cd $DIR #echo "mdrun -deffnm md -v &> md.log" #$MDRUN -deffnm md -v -maxh 240 &> md.log #cd .. #done rm -f \#mdout*
Java
UTF-8
354
2.53125
3
[]
no_license
package models; public class ReTransaction { public Transaction t; public User u; public Transaction getT() { return t; } public void setT(Transaction t) { this.t = t; } public User getU() { return u; } public void setU(User u) { this.u = u; } public ReTransaction(Transaction t, User u) { super(); this.t = t; this.u = u; } }
C#
UTF-8
2,179
3.171875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rock_Paper_Scissors { class Player { public string name; public VARIANTS VARIANTS; private Random rnd = new Random(); private int variants; public Player(VARIANTS variants, string name) { this.name = name; this.VARIANTS = variants; } public Player() { variants = rnd.Next(1, 3); switch (variants) { case 1: VARIANTS = VARIANTS.Rock; break; case 2: VARIANTS = VARIANTS.Scissors; break; case 3: VARIANTS = VARIANTS.Paper; break; } name = "Bot"; } public string whoWins(Player player1, Player player2) { string winner = "Winner is "; if (player1.VARIANTS == VARIANTS.Paper && player2.VARIANTS == VARIANTS.Paper) winner = "Draw"; if (player1.VARIANTS == VARIANTS.Rock && player2.VARIANTS == VARIANTS.Rock) winner = "Draw"; if (player1.VARIANTS == VARIANTS.Scissors && player2.VARIANTS == VARIANTS.Scissors) winner = "Draw"; if (player1.VARIANTS == VARIANTS.Rock && player2.VARIANTS == VARIANTS.Paper) winner += (string)player2.name; if (player1.VARIANTS == VARIANTS.Paper && player2.VARIANTS == VARIANTS.Rock) winner += (string)player1.name; if (player1.VARIANTS == VARIANTS.Paper && player2.VARIANTS == VARIANTS.Scissors) winner += (string)player2.name; if (player1.VARIANTS == VARIANTS.Scissors && player2.VARIANTS == VARIANTS.Paper) winner += (string)player1.name; if (player1.VARIANTS == VARIANTS.Rock && player2.VARIANTS == VARIANTS.Scissors) winner += (string)player1.name; if (player1.VARIANTS == VARIANTS.Scissors && player2.VARIANTS == VARIANTS.Rock) winner += (string)player2.name; return winner; } } }
C
UTF-8
217
3.0625
3
[]
no_license
#include<stdio.h> int main() { long long int dub,num; int power=0; printf("Enter the number \n num="); scanf("%lld",&num); dub=num; while(num!=1) { num=num>>1; power++; } printf("%lld = 2^%d",dub,power); return 0; }
JavaScript
UTF-8
2,486
3.234375
3
[ "MIT" ]
permissive
import FS from "fs"; import Path from "path"; import _ from "lodash-fp"; import { split } from "../helpers"; export const title = "Day 5: Doesn't He Have Intern-Elves For This?"; export function isNiceString(string) { // Contains at least 3 vowels. const vowels = ["a", "e", "i", "o", "u"]; const threeVowels = _.compose(_.gte(3), _.get("length"), _.filter((x) => _.includes(x, vowels)), split("")); // Contains at least one letter that appears twice. const pattern = /([a-z])\1+/; const duplicateLetters = (str) => pattern.test(str); // Doesn't contain 'ab', 'cd', 'pq', or 'xy'. const blacklist = ["ab", "cd", "pq", "xy"]; const getMatches = _.curry((list, string) => _.filter((x) => _.includes(x, string), list)); const blacklistWords = _.compose(_.gte(1), _.get("length"), getMatches(blacklist)); return threeVowels(string) && duplicateLetters(string) && !blacklistWords(string); } function getSandwichDoubles(x) { return _.reduce((counts, l, i, arr) => { if (!i) return counts; const fragment = arr.slice(i - 1, i + 2).join(""); // Contains a pair of any two letters that appears at least twice // in the string without overlapping. const double = fragment.substr(0, 2); const rest = arr.slice(i + 1).join(""); if (rest.indexOf(double) != -1) counts.doubles[double] = null; // Contains at least one letter which repeats with exactly one // letter between them. if (fragment[0] === fragment[2]) counts.sandwiches[fragment] = null; return counts; }, { doubles: {}, sandwiches: {} }, x); } export function isNiceString2(string) { const found = _.compose(_.get("length"), Object.keys); const counts = _.compose(getSandwichDoubles, split("")); const isValid = _.compose(_.isEqual(2), _.get("length"), _.filter(_.gte(1)), _.map(found), counts); return isValid(string); } export function run() { const inputPath = Path.join(__dirname, "input.txt"); const input = FS.readFileSync(inputPath, "utf-8").trim().split("\n"); const niceStrings = _.compose(_.get("length"), _.filter(isNiceString)); const niceStrings2 = _.compose(_.get("length"), _.filter(isNiceString2)); console.log("How many strings are nice?", niceStrings(input)); console.log("How many strings are nice (revision 2)?", niceStrings2(input)); }
JavaScript
UTF-8
140
3.328125
3
[ "MIT" ]
permissive
// Write an expression that calculates trapezoid's // area by given sides a and b and height h. var a=3,b=4,h=5; console.log(((a+b)/2)*h);
Shell
UTF-8
3,984
3.4375
3
[ "MIT" ]
permissive
#!/usr/bin/env bash set -f PATH_SSL="/etc/ssl/certs" # Path to the custom Homestead $(hostname) Root CA certificate. PATH_ROOT_CNF="${PATH_SSL}/ca.homestead.$(hostname).cnf" PATH_ROOT_CRT="${PATH_SSL}/ca.homestead.$(hostname).crt" PATH_ROOT_KEY="${PATH_SSL}/ca.homestead.$(hostname).key" # Path to the custom site certificate. PATH_CNF="${PATH_SSL}/${1}.cnf" PATH_CRT="${PATH_SSL}/${1}.crt" PATH_CSR="${PATH_SSL}/${1}.csr" PATH_KEY="${PATH_SSL}/${1}.key" BASE_CNF=" [ ca ] default_ca = ca_homestead_$(hostname) [ ca_homestead_$(hostname) ] dir = $PATH_SSL certs = $PATH_SSL new_certs_dir = $PATH_SSL private_key = $PATH_ROOT_KEY certificate = $PATH_ROOT_CRT default_md = sha256 name_opt = ca_default cert_opt = ca_default default_days = 365 preserve = no policy = policy_loose [ policy_loose ] countryName = optional stateOrProvinceName = optional localityName = optional organizationName = optional organizationalUnitName = optional commonName = supplied emailAddress = optional [ req ] prompt = no encrypt_key = no default_bits = 2048 distinguished_name = req_distinguished_name string_mask = utf8only default_md = sha256 x509_extensions = v3_ca [ v3_ca ] authorityKeyIdentifier = keyid,issuer basicConstraints = critical, CA:true, pathlen:0 keyUsage = critical, digitalSignature, keyCertSign subjectKeyIdentifier = hash [ server_cert ] authorityKeyIdentifier = keyid,issuer:always basicConstraints = CA:FALSE extendedKeyUsage = serverAuth keyUsage = critical, digitalSignature, keyEncipherment subjectAltName = @alternate_names subjectKeyIdentifier = hash " # Only generate the root certificate when there isn't one already there. if [ ! -f $PATH_ROOT_CNF ] || [ ! -f $PATH_ROOT_KEY ] || [ ! -f $PATH_ROOT_CRT ] then # Generate an OpenSSL configuration file specifically for this certificate. cnf=" ${BASE_CNF} [ req_distinguished_name ] O = Vagrant C = UN CN = Homestead $(hostname) Root CA " echo "$cnf" > $PATH_ROOT_CNF # Finally, generate the private key and certificate. openssl genrsa -out "$PATH_ROOT_KEY" 4096 2>/dev/null openssl req -config "$PATH_ROOT_CNF" \ -key "$PATH_ROOT_KEY" \ -x509 -new -extensions v3_ca -days 3650 -sha256 \ -out "$PATH_ROOT_CRT" 2>/dev/null # Symlink ca to local certificate storage and run update command ln --force --symbolic $PATH_ROOT_CRT /usr/local/share/ca-certificates/ update-ca-certificates fi # Only generate a certificate if there isn't one already there. if [ ! -f $PATH_CNF ] || [ ! -f $PATH_KEY ] || [ ! -f $PATH_CRT ] then # Uncomment the global 'copy_extentions' OpenSSL option to ensure the SANs are copied into the certificate. sed -i '/copy_extensions\ =\ copy/s/^#\ //g' /etc/ssl/openssl.cnf # Generate an OpenSSL configuration file specifically for this certificate. cnf=" ${BASE_CNF} [ req_distinguished_name ] O = Vagrant C = UN CN = $1 [ alternate_names ] DNS.1 = $1 DNS.2 = *.$1 " echo "$cnf" > $PATH_CNF # Finally, generate the private key and certificate signed with the Homestead $(hostname) Root CA. openssl genrsa -out "$PATH_KEY" 2048 2>/dev/null openssl req -config "$PATH_CNF" \ -key "$PATH_KEY" \ -new -sha256 -out "$PATH_CSR" 2>/dev/null openssl x509 -req -extfile "$PATH_CNF" \ -extensions server_cert -days 365 -sha256 \ -in "$PATH_CSR" \ -CA "$PATH_ROOT_CRT" -CAkey "$PATH_ROOT_KEY" -CAcreateserial \ -out "$PATH_CRT" 2>/dev/null fi
SQL
UTF-8
1,773
3.03125
3
[]
no_license
INSERT INTO USERS (name, email, password) VALUES ('User One', 'user.one@ukr.net', 'password'), ('User Two', 'user.two@ukr.net', 'password'), ('Admin One', 'admin.one@gmail.com', 'admin'), ('Admin Two', 'admin.two@gmail.com', 'admin'); INSERT INTO USER_ROLES (role, user_id) VALUES ('ROLE_USER', 1), ('ROLE_USER', 2), ('ROLE_ADMIN', 3), ('ROLE_ADMIN', 4); INSERT INTO RESTAURANTS (name, user_id) VALUES ('Manhattan-skybar', 3), ('Gastro', 3), ('Vinograd', 4); INSERT INTO MENUS (date, restaurant_id) VALUES ('2019-10-31', 1), ('2019-10-31', 2), ('2019-10-31', 3), ('2019-11-01', 1), ('2019-11-01', 2), ('2019-11-01', 3); INSERT INTO DISHES (name, price, menu_id) VALUES ('Шатобріан', 99, 1), ('Червоний борщ', 38, 1), ('Салат з тигровими креветками під кисло-солодким соусом', 146, 1), ('Карпаччо з лосося', 99.98, 2), ('Салат цезар', 110.50, 2), ('Хінкалі з баранини', 97, 3), ('Шашлик із телятини', 85, 3), ('Курча тапака', 70, 3), ('Шатобріан', 99, 4), ('Червоний борщ', 38, 4), ('Салат з тигровими креветками під кисло-солодким соусом', 146, 4), ('Карпаччо з лосося', 99.98, 5), ('Салат цезар', 110.50, 6), ('Хінкалі з баранини', 97, 6), ('Курча тапака', 70, 6); INSERT INTO VOTES (date, restaurant_id, user_id) VALUES ('2019-10-30', 3, 1), ('2019-10-30', 3, 2), ('2019-10-31', 2, 1), ('2019-10-31', 3, 2), ('2019-11-01', 1, 1), ('2019-11-01', 2, 2);
Markdown
UTF-8
3,235
2.671875
3
[ "Apache-2.0" ]
permissive
## Sublime text 3 中Package Control 的安装与使用方法 Package Control插件本身是一个为了方便管理插件的插件,在Sublime text 3中,Package Control 的安装方法一开始出来的方法是要先安装Git,再输入代码来安装,原因说是“sublime text 3更新的python的函数,说白了就是API不同了,导致基于python开发的插件很多都不能工作”。不过后来出了个方便的安装方法,下面介绍一下。 插播:[代码编辑器Sublime Text 3 免费使用方法与简体中文汉化包下载](http://devework.com/sublime-text-3.html) **5月4日更新**:最新安装方式如下: 通过 `ctrl+`` 快捷键或者 `View > Show Console`菜单打开控制台,复制粘贴回车如下代码即可。 ``` import urllib.request,os,hashlib; h = 'df21e130d211cfc94d9b0905775a7c0f' + '1e3d39e33b79698005270310898eea76'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by) ``` 后面内容为旧方法,请无视。 ## Package Control 主文件下载 下载地址:<https://github.com/wbond/sublime_package_control> 托管在github 上,下载直接按 zip 那个按钮。解压之后,把文件夹名称修改为“package control”。 ![Sublime text 3 中Package Control 的安装与使用方法](Package_Control.assets/291815280220130806.jpg) ## 安装Package Control 步骤 1、点击菜单->首选项->浏览程序包,打开一个文件夹,复制刚才的“package control”文件到该目录下面。 ![Sublime text 3 中Package Control 的安装与使用方法](Package_Control.assets/650882404120130806.png) 2、打开sublime text 3编辑器,在菜单->preferences->Package Settings和package control选项,就说明安装package control成功了。 ![Sublime text 3 中Package Control 的安装与使用方法](Package_Control.assets/843914175820130806.png) 因为sublime text 3正式版还未发布,又更新了API,所以sublime text 3相对插件来说和sublime text 2是两个东西,[点击查看](https://github.com/wbond/sublime_package_control/wiki/Sublime-Text-3-Compatible-Packages),在此列表中可以查看能在sublime text 3中工作的插件,少之又少,所以依赖现在的插件工作的朋友不建议更新到sublime text 3。 ## Package Control的使用方法:安装插件 **快捷键 Ctrl+Shift+P**(菜单 – Tools – Command Paletter),输入 install 选中Install Package并回车,输入或选择你需要的插件回车就安装了(注意左下角的小文字变化,会提示安装成功)。 ![Sublime text 3 中Package Control 的安装与使用方法](Package_Control.assets/430773095220130807.png) ![Sublime text 3 中Package Control 的安装与使用方法](Package_Control.assets/400496516120130807.png)
C#
UTF-8
533
3.59375
4
[ "Apache-2.0" ]
permissive
using System; public class PriceCalculator { private decimal totalPrice; public PriceCalculator(decimal price, int days, Enum season, Enum discount) { var priceTemp = days * price * (int)(object)season; TotalPrice = priceTemp - ((priceTemp / 100m) * (int)(object)discount); Console.WriteLine(); } public decimal TotalPrice { get => totalPrice; set => totalPrice = value; } public override string ToString() { return $"{TotalPrice:f2}"; } }
Markdown
UTF-8
3,253
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Quizzo Server > The backend for QUIZZO app. ![[GitHub package.json version]](https://img.shields.io/github/package-json/v/ibtesam123/Quizzo-Server) ![[GitHub last commit]](https://img.shields.io/github/last-commit/ibtesam123/Quizzo-Server) ![GitHub](https://img.shields.io/github/license/ibtesam123/Quizzo) ![[GitHub stars]](https://img.shields.io/github/stars/ibtesam123/quizzo-server?style=social) ![[GitHub forks]](https://img.shields.io/github/forks/ibtesam123/quizzo-server?style=social) REST api made using Express.js and MongoDB as the database. Deployed on Heroku platform. <!-- ![](header.png) --> ## Installation 1. Clone the project 2. Goto the cloned folder 3. Run command ```npm install``` 4. Create ```.env``` file in the root folder and add your credentials as follows: ```sh PORT=8080 MONGO_URI= <YOUR MONGODB URI> WRITE_KEY= <ADD YOUR PREFERRED KEY FOR R/W ACCESS TO DATABASE> ``` 5. Run ```npm run dev``` ## Usage example ##### REST API Endpoints GET: /question - Get 8 random questions /questions/categories - Get all current categories /user - Get a user by email or uid POST: /question - Add a question /question/batch - Add a batch of questions /user - Create a new user or return existing user /user/history - Add a new history to a specific user /user/historyBatch - Add history to a specific user in batch PUT: /user - Update a current user ## Deployment to Heroku ```sh heroku create <Give a name of your choice> git add . git commit -m "Deploy to heroku" git push heroku master ``` ## Meta Ibtesam Ansari – [LinkedIn](https://www.linkedin.com/in/ibtesamansari/) – ibtesamansari070@gmail.com [https://github.com/ibtesam123](https://github.com/ibtesam123) ## Contributing 1. Fork it (<https://github.com/ibtesam123/quizzo-server/fork>) 2. Create your feature branch (`git checkout -b feature/fooBar`) 3. Commit your changes (`git commit -m 'Add some fooBar'`) 4. Push to the branch (`git push origin feature/fooBar`) 5. Create a new Pull Request ## License All the code available under the MIT license. See [LICENSE](LICENSE). ```sh MIT License Copyright (c) 2020 Ibtesam Shaukat Ansari 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. ```
C++
UTF-8
2,598
2.796875
3
[]
no_license
// Ardumower Sunray // Copyright (c) 2013-2020 by Alexander Grau, Grau GmbH /* test pathfinder */ #include "PathFinderTest.h" #include <Arduino.h> #include "../../map.h" #include "../../robot.h" bool PathFinderTest::findValidPoint(Point &pt){ int timeout = 10000; float d = 30.0; while (timeout > 0){ pt.setXY( ((float)random(d*10))/10.0-d/2, ((float)random(d*10))/10.0-d/2 ); if (maps.isInsidePerimeterOutsideExclusions(pt)) return true; timeout--; } CONSOLE.println("findValidPoint failed!"); return false; } // for the current map, run path finder on all perimeter points // the test is considered as failed if path has not length 2 void PathFinderTest::runPerimeterPathTest(){ CONSOLE.println("PathFinderTest::runPerimeterPathTest"); Point src; Point dst; int numTests = 0; int numTestsFailed = 0; for (int i=0; i < maps.perimeterPoints.numPoints-1; i++){ src.assign(maps.perimeterPoints.points[i]); dst.assign(maps.perimeterPoints.points[i+1]); numTests++; bool res = maps.findPath(src, dst); if (res) { if (maps.freePoints.numPoints != 2) numTestsFailed++; } else numTestsFailed++; } CONSOLE.print("PathFinderTest::runPerimeterPathTest #tests "); CONSOLE.print(numTests); CONSOLE.print(" #failed "); CONSOLE.println(numTestsFailed); } // for the current map, generate random source and destination points which are inside perimeter (and outside exclusions) of current map // and run path finder to find a path from source to destination - the test is considered as failed if not path was found void PathFinderTest::runRandomPathTest(){ CONSOLE.println("PathFinderTest::runRandomPathTest"); if (maps.perimeterPoints.numPoints == 0) { CONSOLE.println("PathFinderTest::runRandomPathTest - no map, nothing to test"); return; } Point src; Point dst; int numTests = 0; int numTestsFailed = 0; float d = 30.0; for (int i=0 ; i < 10000; i++){ CONSOLE.print("PathFinderTest::runRandomPathTest loop "); CONSOLE.println(i); for (int j=0 ; j < 20; j++){ //addObstacle( ((float)random(d*10))/10.0-d/2, ((float)random(d*10))/10.0-d/2 ); } //src.setXY(-2.33, 19.41); //dst.setXY(-3.18, 19.39); if (!findValidPoint(src)) break; if (!findValidPoint(dst)) break; numTests++; bool res = maps.findPath(src, dst); if (!res) numTestsFailed++; //clearObstacles(); } CONSOLE.print("PathFinderTest::runRandomPathTest #tests "); CONSOLE.print(numTests); CONSOLE.print(" #failed "); CONSOLE.println(numTestsFailed); }
C++
UTF-8
1,278
2.53125
3
[]
no_license
#ifndef BOARDLAYOUT_H #define BOARDLAYOUT_H #include <QLayout> class BoradLayout : public QLayout { public : enum Position { West, North, South, East, Center }; explicit BoradLayout(QWidget *parent, int margin = 0, int space = 0); BoradLayout(int spaceing = -1); ~BoradLayout(); void addItem(QLayoutItem *)override; void setGeometry(const QRect&) Q_DECL_OVERRIDE; QLayoutItem *itemAt(int index) const override; QLayoutItem *takeAt(int index) override; int count() const override; Qt::Orientations expandingDirections() const override; bool hasHeightForWidth() const override; QSize sizeHint() const override; QSize minimumSize() const override; void addWidget(QWidget *widget, Position position); void add(QLayoutItem *item, Position position); private: struct ItemWrapper { ItemWrapper(QLayoutItem *i, Position p) { item = i; position = p; } QLayoutItem *item; Position position; }; enum SizeType {MinimumSize, SizeHint}; QSize calculteSize(SizeType type) const; QList<ItemWrapper *> list; }; #endif // BOARDLAYOUT_H
Swift
UTF-8
4,902
2.734375
3
[]
no_license
// // RepoDetailsViewModel.swift // GHRepoBrowser // // Created by Andrzej Puczyk on 17/07/2019. // Copyright © 2019 Andrzej Puczyk. All rights reserved. // import UIKit protocol RepoDetailsViewModeling: ViewControllerModeling, UITableViewDataSource, UITableViewDelegate { var onReloadData: (() -> Void)? { get set } var onLoadingStateChange: ((Bool) -> Void)? { get set } func getRepoDetails() } class RepoDetailsViewModel: NSObject, RepoDetailsViewModeling { var title: String { return repo.name } var onReloadData: (() -> Void)? // refresh right after update value var onLoadingStateChange: ((Bool) -> Void)? { didSet { onLoadingStateChange?(isLoading) } } private var repo: Repository private var owner: Owner private var readme: Readme? private var detailViewModels: [DetailsCellViewModel] = [] private var isLoading: Bool = false { didSet { if isLoading != oldValue { onLoadingStateChange?(isLoading) } } } init(repo: Repository) { self.repo = repo self.owner = repo.owner super.init() getRepoDetails() } func getRepoDetails() { // simple responses counter var responsesCount = 3 let performReload = { [weak self] in responsesCount -= 1 guard responsesCount == 0 else { return } self?.onReloadData?() self?.isLoading = false self?.detailViewModels = [] if let url = self?.repo.homepage { self?.detailViewModels.append(DetailsCellViewModel(type: .homepage, url: url)) } if let url = self?.repo.license?.url { self?.detailViewModels.append(DetailsCellViewModel(type: .license, url: url)) } if let url = self?.readme?.htmlUrl { self?.detailViewModels.append(DetailsCellViewModel(type: .readme, url: url)) } } isLoading = true APIMethod.getRepoDetails(repo: repo).perform { [weak self] (repos, response, error) in guard let repo = repos?.first else { performReload() return } self?.repo = repo performReload() } APIMethod.getRepoReadme(repo: repo).perform { [weak self] (readmes, response, error) in self?.readme = readmes?.first performReload() } APIMethod.getUserDetails(user: repo.owner).perform { [weak self] (owners, response, error) in guard let owner = owners?.first else { performReload() return } self?.owner = owner performReload() } } } // MARK: Table View Data Source & Delegate extension RepoDetailsViewModel { func numberOfSections(in tableView: UITableView) -> Int { return 2 + (readme != nil ? 1 : 0) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 2: return detailViewModels.count default: return 1 } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: guard let cell: OwnerCell = tableView.dequeueReusableCell() else { return UITableViewCell() } cell.viewModel = OwnerDetailsCellViewModel(owner: owner) cell.setLoading(isLoading) return cell case 1: guard let cell: RepoDetailsCell = tableView.dequeueReusableCell() else { return UITableViewCell() } cell.viewModel = RepoDetailsCellViewModel(repository: repo) cell.setLoading(isLoading) return cell case 2: guard let cell: DetailsCell = tableView.dequeueReusableCell() else { return UITableViewCell() } cell.viewModel = detailViewModels[safe: indexPath.row] cell.accessoryType = .disclosureIndicator cell.setLoading(isLoading) return cell default: return UITableViewCell() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath.section { case 0: open(owner.htmlUrl) case 1: open(repo.htmlUrl) case 2: open(detailViewModels[safe: indexPath.row]?.url) default: break } } } // MARK: Private extension RepoDetailsViewModel { private func open(_ urlString: String?) { if let urlString = urlString, let url = URL(string: urlString) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } }
C++
UTF-8
1,938
2.859375
3
[]
no_license
#include "helium/type/IOHelper.h" std::string FileIOHelper::GetIntCode() { return R"prefix( int get_int() { int ret; fscanf(int_input_fp, "%d", &ret); return ret; } void input_int(int *a) { *a = get_int(); } void input_int_name(int *a, char *name) { *a = get_int(); fprintf(output_fp, "input: int %s=%d\n", name, *a); } void output_int(int *a, char *name) { fprintf(output_fp, "output: int %s=%d\n", name, *a); } char get_char() { char ret; fscanf(char_input_fp, "%c", &ret); return ret; } void input_char(char *c) { *c = get_char(); } void input_char_name(char *c, char *name) { *c = get_char(); fprintf(output_fp, "input: char %s=%c\n", name, *c); } void output_char(char *c, char *name) { fprintf(output_fp, "output: char %s=%c\n", name, *c); } bool get_bool() { int tmp; fscanf(bool_input_fp, "%d", &tmp); return tmp==1; } void input_bool(bool *b) { *b = get_bool(); } void input_bool_name(bool *b, char *name) { *b = get_bool(); fprintf(output_fp, "input: bool %s=%d\n", name, *b); } void output_bool(bool *b, char *name) { fprintf(output_fp, "output: bool %s=%d\n", name, *b); } )prefix"; } std::string FileIOHelper::GetGlobalFilePointers() { return R"prefix( // global file pointers FILE *int_input_fp; FILE *char_input_fp; FILE *bool_input_fp; FILE *output_fp; )prefix"; } /** * Insert at the beginning of main.c */ std::string FileIOHelper::GetIOCode() { return GetGlobalFilePointers() + GetIntCode(); } /** * input at the beginning of main */ std::string FileIOHelper::GetFilePointersInit() { return R"prefix( int_input_fp = fopen("/home/hebi/.helium.d/input_values/int.txt", "r"); char_input_fp = fopen("/home/hebi/.helium.d/input_values/char.txt", "r"); bool_input_fp = fopen("/home/hebi/.helium.d/input_values/bool.txt", "r"); // this file will not only record the output, but also the input output_fp = fopen("helium_output.txt", "w"); )prefix"; }
Markdown
UTF-8
1,314
2.96875
3
[]
no_license
# TO-DO MERN APP Simple app with auth and crud to add, edit and delete tasks. ## Stack * Node.js 15.9.0 * Nestjs 7.5.5 * MongoDB 4.4.0 # How to run it? ## Prerequisites * Just NodeJS installing in your system and MongoDB (But you can use Atlas) ## Installing ### 1. Clone the repo ``` git clone https://github.com/Jucester/mern-todo-typescript.git ``` ### 2. Configuring backend ``` Run npm install and then make an .env file to store your sensitive data In this file you need to provide this variables: PORT={Your choice} MONGO_URL={Mongo url to production} MONGO_DEV={Mongo url to dev} MONGO_TEST={Mongo url to testing} SECRET_KEY={your json web tokens key} ``` ### 3. Configuring frontend: ``` Run npm install and then make an .env file to store your backend url: REACT_APP_BACKEND_URL={backend url, example: http://localhost:4000/api/1.0} ``` ### 4. Run the frontend and backend ``` Run npm start in the frontend. In the backend you can run in dev mode with npm run dev or in production with npm start You can also execute automated test in backend with npm test ``` The app will be running in the frontend in [http://localhost:3000](http://localhost:3000), and the API will be at [http://localhost:4000](http://localhost:4000). You can change the ports and test the api with postman
Java
UTF-8
4,501
2.25
2
[]
no_license
import java.io.IOException; import java.util.*; import java.text.*; import org.apache.hadoop.fs.Path; import org.apache.hadoop.conf.*; import org.apache.hadoop.io.*; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs; import org.apache.hadoop.mapreduce.lib.partition.*; public static class Map extends Mapper<Object, Text, IntWritable, Text>{ private String filename; private int filetag = -1; public void setup(Context context) throws IOException, InterruptedException { int last_index = -1, start_index = -1; String path = ((FileSplit)context.getInputSplit()).getPath().toString(); last_index = path.lastIndexOf('/'); last_index = last_index - 1; start_index = path.lastIndexOf('/', last_index); filename = path.substring(start_index + 1, last_index + 1); if (filename.compareTo("CUSTOMER") == 0){ filetag = 1; } if (filename.compareTo("ORDERS") == 0){ filetag = 2; } } public void map(Object key, Text value, Context context) throws IOException, InterruptedException{ String line = value.toString(); String[] line_buf= line.split("\\|"); BitSet dispatch = new BitSet(32); if (filetag == 1){ context.write(new IntWritable(Integer.parseInt(line_buf[0])), new Text(1+"||"+Integer.parseInt(line_buf[0])+line_buf[1]+Double.parseDouble(line_buf[5])+line_buf[4]+line_buf[2]+line_buf[7]+Integer.parseInt(line_buf[3]))); } if (filetag == 2){ if (line_buf[4].compareTo("1993-05-01") >= 0 && line_buf[4].compareTo("1993-08-01") < 0){ context.write(new IntWritable(Integer.parseInt(line_buf[1])), new Text(2+"|"+dispatch.toString()+"|"+Integer.parseInt(line_buf[0])+Integer.parseInt(line_buf[1]))); } } } } public static class Reduce extends Reducer<IntWritable, Text, NullWritable, Text> { public void reduce(IntWritable key, Iterable<Text> v, Context context) throws IOExceptiuon, InterruptedException { Iterator values = v.iterator(); ArrayList[] tmp_output = new ArrayList[1]; for (int i = 0; i < 1; i++) { tmp_output[i] = new ArrayList(); } String tmp = ""; ArrayList al_left_0 = new ArrayList(); ArrayList al_right_0 = new ArrayList(); while (values.hasNext()) { String line = values.next().toString(); String dispatch = line.split("\\|")[1]; tmp = line.substring(2+dispatch.length()+1); String[] line_buf = tmp.split("\\|"); if (line.charAt(0) == '1' && (dispatch.length() == 0 || dispatch.indexOf("2") == -1)) al_left_2.add(tmp); if (line.charAt(0) == '2' && (dispatch.length() == 0 || dispatch.indexOf("2") == -1)) al_right_2.add(tmp); } String[] line_buf = tmp.split("\\|"); for (int i = 0; i < al_left_0.size(); i++) { String[] left_buf_0 = ((String) al_left_0.get(i)).split("\\|"); for (int j = 0; j < al_right_0.size(); j++) { String[] right_buf_0 = ((String) al_right_0.get(j)).split("\\|"); tmp_output[0].add(Integer.parseInt(left_buf_0[0])+left_buf_0[1]+Double.parseDouble(left_buf_0[2])+left_buf_0[3]+left_buf_0[4]+left_buf_0[5]+Integer.parseInt(left_buf_0[6])+Integer.parseInt(right_buf_0[0])); } } NullWritable key_op = NullWritable.get(); for (int i = 0; i < tmp_output[0].size(); i++) { String result = (String)tmp_output[0].get(i); context.write(key_op, new Text(result)); } } } public int run(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "testquery4"); job.setJarByClass(testquery4.class); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(Text.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(Text.class); setMapperClass(Map.class); job.setReduceClass(Reduce.class); FileOutputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.addInputPath(job, new Path(args[1])); FileOutput.setOutputPath(job, new Path(args[2])); return (job.waitForCompletion) ? 0 : 1); } public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new testquery4(), args); System.exit(res); }
JavaScript
UTF-8
946
2.75
3
[]
no_license
// $("#country-name").change(function () { $(".arrow").on("click", function () { var apiKey = "9a8f851c653056267377aaa5a4b7723d"; var userQury = $("#country-name option:selected").val(); console.log("user qr: ", userQury); $.ajax({ url: "https://restcountries.eu/rest/v2/alpha/" + userQury, method: "GET" }).then(function (res) { console.log(res); var queryURL = "https://api.openweathermap.org/data/2.5/weather?q=" + res.capital + "&units=imperial&appid=" + apiKey; $.ajax({ url: queryURL, method: "GET" }).then(function (response) { console.log(response); $(".temperature").append("<i>Current temperature (F): </i>", response.main.temp, "<br>"); $(".temperature").append("<i>Current humidity: </i>", response.main.humidity,"<br>"); }); }); }); // });
C++
UTF-8
2,512
3.078125
3
[]
no_license
#include <iostream> #include <cassert> #include "TimeSeries/MetaParameter.hpp" #include "TimeSeries/Optimizable.hpp" class TestOptimizable : public Leph::Optimizable { public: TestOptimizable() : Leph::Optimizable() { Leph::Optimizable::resetParameters(); } virtual inline size_t parameterSize() const override { return 2; } virtual Leph::MetaParameter defaultParameter(size_t index) const override { if (index == 0) { Leph::MetaParameter param("param1", 1.0); return param; } else { Leph::MetaParameter param("param1", 2.0); param.setMinimum(0.0); param.setMaximum(10.0); return param; } } }; int main() { Leph::MetaParameter param1("param1", 41.0); Leph::MetaParameter param2("param2", 42.0); Leph::MetaParameter param3("param3", 43.0); assert(param1.name() == "param1"); assert(param2.name() == "param2"); assert(param3.name() == "param3"); assert(param1.value() == 41.0); assert(param2.value() == 42.0); assert(param3.value() == 43.0); param2.setMinimum(40.0); param3.setMinimum(30.0); param3.setMaximum(100.0); assert(param2.hasMinimum()); assert(!param2.hasMaximum()); assert(param3.hasMinimum()); assert(param3.hasMaximum()); param1.setValue(100.0); assert(param1.value() == 100.0); param2.setValue(0.0); assert(param2.value() == 40.0); param2.setValue(200.0); assert(param2.value() == 200.0); param3.setValue(40.0); assert(param3.value() == 40.0); param3.setValue(20.0); assert(param3.value() == 30.0); param3.setValue(300.0); assert(param3.value() == 100.0); std::cout << param1 << std::endl; std::cout << param2 << std::endl; std::cout << param3 << std::endl; TestOptimizable testOptimizable; assert(testOptimizable.parameterSize() == 2); assert(testOptimizable.getParameter(0).value() == 1.0); assert(testOptimizable.getParameter(1).value() == 2.0); assert(testOptimizable.setParameter(1, 3.0) == true); assert(testOptimizable.setParameter(1, 11.0) == false); testOptimizable.parameterPrint(); testOptimizable.parameterSave("/tmp/testMetaParameter.params"); testOptimizable.parameterLoad("/tmp/testMetaParameter.params"); testOptimizable.parameterPrint(); return 0; }
Java
UTF-8
1,500
2.953125
3
[]
no_license
import java.util.ArrayList; import java.util.List; public class PersonDataLoader { public static List<Person> getPersonList() { Person p1 = new Person(); p1.setPersonNumber(1); p1.setName("Dileepa"); p1.setAge(28); p1.setStatus(Person.SINGLE); p1.setSalary(190.00); Person p2 = new Person(); p2.setPersonNumber(2); p2.setName("Madawa"); p2.setAge(28); p2.setStatus(Person.SINGLE); p2.setSalary(150.00); Person p3 = new Person(); p3.setPersonNumber(3); p3.setName("Janaki"); p3.setAge(30); p3.setStatus(Person.SINGLE); p3.setSalary(120.00); Person p4 = new Person(); p4.setPersonNumber(4); p4.setName("Tharindu"); p4.setAge(30); p4.setStatus(Person.MARRIED); p4.setSalary(100.00); Person p5 = new Person(); p5.setPersonNumber(5); p5.setName("Umesh"); p5.setAge(32); p5.setStatus(Person.MARRIED); p5.setSalary(110.00); Person p6 = new Person(); p6.setPersonNumber(6); p6.setName("Tharani"); p6.setAge(27); p6.setStatus(Person.SINGLE); p6.setSalary(100.00); List<Person> persons = new ArrayList<Person>(); persons.add(p1); persons.add(p2); persons.add(p3); persons.add(p4); persons.add(p5); persons.add(p6); return persons; } }
Java
UTF-8
395
2.3125
2
[]
no_license
/** * Alipay.com Inc. * Copyright (c) 2004-2020 All Rights Reserved. */ package dsa.binaryTree; /** * @author rahul.jaiman * @version $Id: TreeNode.java, v 0.1 2020-05-06 12:04 rahul.jaiman Exp $$ */ public class TreeNode { public int data; public TreeNode left, right; public TreeNode(int data) { this.data = data; left = null; right = null; } }
C++
UTF-8
1,964
3.140625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int countOccurence(int arr[],int key,int start,int end) { int count=0; int mid=(start+end)/2; if(start>end) return -1; if(arr[mid]==key) { int found=mid; while(mid >=0 && arr[mid]==key ) { count++; //cout<<"+1"; mid--; } while(mid<=end && arr[found]==key) { count++; //cout<<"+1"; found++; } } else if(arr[mid]>key) { return countOccurence(arr,key,start,mid-1); } else return countOccurence(arr,key,mid+1,end); return count-1; } int main() { //code int tc,size,key; cin>>tc; while(tc--) { cin>>size>>key; int arr[size]; for(int i=0;i<size;i++) { cin>>arr[i]; } cout<<countOccurence(arr,key,0,size)<<endl; } return 0; }#include<bits/stdc++.h> using namespace std; int countOccurence(int arr[],int key,int start,int end) { int count=0; int mid=(start+end)/2; if(start>end) return -1; if(arr[mid]==key) { int found=mid; while(mid >=0 && arr[mid]==key ) { count++; //cout<<"+1"; mid--; } while(mid<=end && arr[found]==key) { count++; //cout<<"+1"; found++; } } else if(arr[mid]>key) { return countOccurence(arr,key,start,mid-1); } else return countOccurence(arr,key,mid+1,end); return count-1; } int main() { //code int tc,size,key; cin>>tc; while(tc--) { cin>>size>>key; int arr[size]; for(int i=0;i<size;i++) { cin>>arr[i]; } cout<<countOccurence(arr,key,0,size)<<endl; } return 0; }
Java
UTF-8
1,582
4.09375
4
[]
no_license
package com.in28mins.referencetypes; public class ReferenceTypes { @SuppressWarnings("unused") public static void main(String[] args) { // all the primitive types will be stored in Stack memory (specific for each // method) // a primitive type variable is a location & it holds it value // if you assign one variable to other only the value will be assigned int i = 5; int j = 6; i = j; // not i becomes 6 j++; // even though j is now 7 the value of i will be same. // primitive types Reference r1 = new Reference(1);// passing to constructor parameter id Reference r2 = new Reference(1); // here a new object will be stored in HEAP memory (globally common) // the variables r1,r2 will be stored in stack memory // but their values in stack memory wont hold the object // it will hold the memory location of the object in heap memory // since its values is a reference to memory location in HEAP its called // REFERENCE TYPE Reference r3; // creating a new reference variable in stack memory but its value will be null // because we didn't create any object or assign any object to it. r3 = r2; // assigning the location of r2 to r3 r3.id = 5; // i have changed r3's id but the value of r2's id will also change // because they both refer to same memory location in HEAP memory System.out.println(r1 == r2);// even though they both have same id value "1" it will be false // because the value of r1 & r2 are memory locations, since they are separate // objects & have separate memory locations // they wont be the same. } }
Python
UTF-8
73
2.8125
3
[]
no_license
print("Hello IOT") value1 = 15 value2 =15.6 sum= value1+value2 print(sum)