language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
1,853
2.546875
3
[ "MIT" ]
permissive
import React, { Component } from "react"; import PropTypes from "prop-types"; import InputBar from "./InputBar"; import styled from "styled-components"; const StyledMessageBar = styled(InputBar)` height: 100%; input { font-size: 1em; } `; class SendMessagesBar extends Component { constructor(props) { super(props); this.state = { typing: false }; this.handleSendMessage = this.handleSendMessage.bind(this); this.componentDidMount = this.componentDidMount.bind(this); } handleSendMessage(e) { e.preventDefault(); var m = document.querySelector("#m"); if (m.value != "") { this.props.socket.emit("chat message", m.value); if (this.state.typing) { this.props.socket.emit("stop typing"); this.setState(() => ({ typing: false })); } m.value = ""; } } componentDidMount() { //Check if user is typing var input = document.getElementById("m"); const TYPING_TIMER_LENGTH = 400; var lastTypingTime; input.addEventListener("input", () => { if (!this.state.typing) { this.props.socket.emit("typing"); this.setState(() => ({ typing: true })); } lastTypingTime = new Date().getTime(); setTimeout(() => { var typingTimer = new Date().getTime(); var timeDiff = typingTimer - lastTypingTime; if (timeDiff >= TYPING_TIMER_LENGTH && this.state.typing) { this.props.socket.emit("stop typing"); this.setState(() => ({ typing: false })); } }, TYPING_TIMER_LENGTH); }); } render() { return ( <StyledMessageBar formID="messaging" inputID="m" onSubmit={this.handleSendMessage} /> ); } } SendMessagesBar.propTypes = { socket: PropTypes.object.isRequired }; export default SendMessagesBar;
Shell
UTF-8
641
2.609375
3
[]
no_license
# Maintainer: pzl pkgname=shivavg _pkgname=ShivaVG pkgver=0.2.1 pkgrel=1 pkgdesc="OpenVG Implementation in OpenGL" arch=('any') url="http://shivavg.sourceforge.net/" license=('LGPL' 'GPL') depends=('glibc' 'libgl') makedepends=('git' 'make') optdepends=('libjpeg-turbo: display jpeg images') provides=('libOpenVG.so') conflicts=() options=() source=('git+https://github.com/ileben/ShivaVG.git') sha256sums=('SKIP') #updpkgsums md5sums=('SKIP') #makepkg -g build() { cd "$srcdir/$_pkgname" sh autogen.sh ./configure --prefix=/usr make } package() { cd "$srcdir/$_pkgname-$pkgver" make DESTDIR="$pkgdir/" install }
C#
UTF-8
657
2.65625
3
[ "MIT" ]
permissive
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReadyEDI.EntityFactory.Elements { [Serializable] public class BaseHash { private Hashtable _hash = new Hashtable(); public BaseHash() { } public Hashtable Hash { get { return _hash; } set { _hash = value; } } protected void InitializeProperties(Type enumerator) { int i = 0; Enum.GetNames(enumerator).ToList().ForEach(e => _hash.Add(i++, null)); } } }
Markdown
UTF-8
3,910
2.515625
3
[]
no_license
# PCI # 参考 https://blog.csdn.net/wstpt/article/details/75331241 https://blog.csdn.net/jmq_0000/article/details/7517594 Linux设备驱动之——PCI 总线 https://blog.csdn.net/WINGCREATE/article/details/6342933 PCI 是外围设备互连(Peripheral Component Interconnect ), 可以在33MHz时钟频率、32 bit数据总线宽度的条件下达到峰值132Mb/s的传输速率;它能支持一种称为线性突发的数据传输模式,可确保总线不断满载数据 PCIE 是外围设备互连(Peripheral Component Interconnect Express)的简称。 PCIE 总线支持3个独立的物理地址空间:存储器空间,IO空间和配置空间。 每个PCIE设备都有一个配置空间,配置空间采用Id寻址方法,用总线号,设备号,功能号和寄存器号来唯一标识一个配置空间。 配置空间只能由host桥来访问。 - PCI总线架构主要被分成三部分 1) PCI 设备。 符合 PCI 总线标准的设备就被称为 PCI 设备,PCI 总线架构中可以包含多个 PCI 设备。 图中的 Audio 、LAN 都是一个 PCI 设备。 PCI 设备同时也分为主设备和目标设备两种,主设备是一次访问操作的发起者,而目标设备则是被访问者。 2) PCI 总线。 PCI 总线在系统中可以有多条,类似于树状结构进行扩展,每条 PCI 总线都可以连接多个 PCI 设备/ 桥。 上图中有两条 PCI 总线。 3) PCI 桥。 当一条 PCI 总线的承载量不够时,可以用新的 PCI 总线进行扩展,而 PCI 桥则是连接 PCI 总线之间的纽带。 图中的 PCI 桥有两个,一个桥用来连接处理器、内存以及 PCI 总线,而另外一条则用来连接另一条 PCI 总线。 <img src="./pic/PCI0.png" width=500><br><br> PCI控制器: struct pci_controller PCI总线: struct pci_bus PCI设备: struct pci_dev PCI驱动: struct pci_driver - PCI 控制器驱动 文件: pci-msm.c subsys_initcall_sync(pcie_init); int __init pcie_init(void) { ... msm_pcie_debugfs_init(); ret = platform_driver_register(&msm_pcie_driver); // return ret; } - PCI设备与驱动关系 PCI设备通常由一组参数唯一地标识,它们被vendorID,deviceID和class nodes所标识,即设备厂商,型号等,这些参数保存在 pci_device_id结构中。 每个PCI设备都会被分配一个pci_dev变量,内核就用这个数据结构来表示一个PCI设备。 PCI驱动程序都必须定义一个pci_driver结构变量,在该变量中包含了这个PCI驱动程序所提供的不同功能的函数。 在注册PCI驱动程序时(pci_register_driver()), pci_driver变量会被链接到pci_bus_type中的驱动链上去。 在pci_driver中有一个成员struct pci_device_id *id_table,它列出了这个设备驱动程序所能够处理的所有PCI设备的ID值。 - PCI设备与驱动的绑定过程 <img src="./pic/PCI1.png" width= 600><br><br> # PCIE # 参考 https://blog.csdn.net/u010872301/article/details/78519371?locationnum=8&fps=1 linux设备驱动之PCIE驱动开发 https://blog.csdn.net/abcamus/article/details/78009865 大话PCIe:实现host驱动 PCIE(PCI Express)是INTEL提出的新一代的总线接口,目前普及的PCIE 3.0的传输速率为8GT/s,下一代PCIE 4.0将翻番为16GT/S, 因为传输速率快广泛应用于数据中心、云计算、人工智能、机器学习、视觉计算、显卡、存储和网络等领域。 PCIE插槽是可以向下兼容的,比如PCIE 1X接口可以插4X、8X、16X的插槽上。 实现基本的PCIE设备驱动程序,实现以下模块: 初始化设备、设备打开、数据读写和控制、中断处理、设备释放、设备卸载。 PCIE驱动开发通用调试的基本框架,对于具体PCIE设备,需要配置相关寄存器才可以使用 ?
Java
UTF-8
744
2.046875
2
[]
no_license
package com.mvvm.kien2111.fastjob.retrofit; import android.support.annotation.Nullable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by WhoAmI on 29/01/2018. */ public class Envelope<T> { @Nullable public String getErrorMessage() { return errorMessage; } public void setErrorMessage(@Nullable String errorMessage) { this.errorMessage = errorMessage; } @Nullable public T getData() { return data; } public void setData(@Nullable T data) { this.data = data; } @SerializedName("message") @Expose private String errorMessage; @SerializedName("data") @Expose private T data; }
Python
UTF-8
4,713
2.75
3
[]
no_license
#!/usr/bin/env python3 import numpy as onp onp.random.seed(453453) import jax import jax.numpy as np import jax.scipy as sp from bnpmodeling import cluster_quantities_lib import unittest import numpy.testing as testing class TestGetMixtureWeights(unittest.TestCase): def test_get_mixture_weights_from_stick_break_propns(self): # tests our vectorized computatation # against a more readable for-loop implementation # of the stick-breaking process # randomly set some stick-breaking proportions n_obs = 3 k_approx = 10 stick_breaking_propn = onp.random.rand(n_obs, k_approx - 1) mixture_weights = \ cluster_quantities_lib.\ get_mixture_weights_from_stick_break_propns(stick_breaking_propn) assert mixture_weights.shape[0] == stick_breaking_propn.shape[0] assert mixture_weights.shape[1] == k_approx testing.assert_allclose(mixture_weights.sum(1), 1, rtol = 1e-6) # use a for-loop to describe the stick-breaking process # check against our vectorized implementation stick_remain = np.ones(n_obs) for k in range(k_approx - 1): x = stick_breaking_propn[:, k] * stick_remain y = mixture_weights[:, k] testing.assert_allclose(x, y, rtol = 0, atol = 1e-8) stick_remain *= (1 - stick_breaking_propn[:, k]) # check last stick testing.assert_allclose(mixture_weights[:, -1], stick_remain, rtol = 0, atol = 1e-8) class TestEzSamples(unittest.TestCase): def test_sample_ez(self): # check the sampling of e_z from uniform samples # randomly set some ezs n_obs = 5 k_approx = 3 e_z = onp.random.rand(n_obs, k_approx) e_z /= e_z.sum(-1, keepdims = True) # now draw e_z conditional on some uniform samples n_samples = 100000 z_samples = cluster_quantities_lib.sample_ez(e_z, n_samples = n_samples, prng_key = jax.random.PRNGKey(33)) empirical_propns = z_samples.mean(0) for n in range(n_obs): for k in range(k_approx): truth = e_z[n,k] emp = empirical_propns[n,k] tol = 3 * np.sqrt(truth * (1 - truth) / n_samples) testing.assert_allclose(truth, emp, rtol = 0, atol = tol) class TestExpectedNumClusters(unittest.TestCase): def test_get_e_num_clusters_from_ez(self): # check that get_e_num_clusters_from_ez, which computes # the expected number of clusters via MCMC matches the # analytic expectation # construct ez n_obs = 5 k_approx = 3 e_z = onp.random.rand(n_obs, k_approx) e_z /= e_z.sum(-1, keepdims = True) # get expected number of clusters via sampling n_samples = 10000 num_clusters_sampled = \ cluster_quantities_lib.\ get_e_num_clusters_from_ez(e_z, n_samples = n_samples, prng_key = jax.random.PRNGKey(89), threshold = 0, return_samples = True) e_num_clusters_sampled = num_clusters_sampled.mean() var_num_clusters_sampled = num_clusters_sampled.var() # get analytic expected nubmer of clusters e_num_clusters_analytic = \ cluster_quantities_lib.get_e_num_clusters_from_ez_analytic(e_z) tol = np.sqrt(var_num_clusters_sampled / n_samples) * 3 testing.assert_allclose(e_num_clusters_analytic, e_num_clusters_sampled, atol = tol, rtol = 0) def test_pred_clusters_from_mixture_weights(self): # TODO need to test this # for now, just make sure it runs k_approx = 8 stick_propn_mean = onp.random.randn(k_approx - 1) stick_propn_info = np.exp(onp.random.randn(k_approx - 1)) _ = cluster_quantities_lib.\ get_e_num_pred_clusters_from_logit_sticks(stick_propn_mean, stick_propn_info, n_obs = 10, threshold = 0, n_samples = 100) if __name__ == '__main__': unittest.main()
C#
UTF-8
531
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using oop2._3.Exceptions; namespace oop2._3.Unit { class CounterSingleton { private static int counter; public CounterSingleton() { counter = 0; } public int GetIdentifer() { if(counter == 36) { throw new ChessException("Singleton > 36"); } return counter++; } } }
JavaScript
UTF-8
1,074
2.765625
3
[]
no_license
//Hace un llamado a las librerias const express = require('express'); //Hace el llamado al módulo express const app = express(); //Llama a la función express y coloca una nueva aplicación Express dentro de la variable app (para iniciar una nueva aplicación Express) const hbs = require('hbs'); //Hace el llamado al módulo hbs require('./hbs/helpers'); //use el puerto 3000 a menos que exista un puerto preconfigurado const port = process.env.PORT || 3000; app.use(express.static(__dirname + '/public')); //Le dice a HBS la ruta donde se encuentran los fragmentos de plantilla para ser usado en la web hbs.registerPartials(__dirname + '/views/parciales'); app.set('view engine', 'hbs'); //Crea una ruta a la página home app.get('/', function(req, res) { res.render('home', { nombre: "joNaThan mAñaY" //Guarda el nombre para ser utilizado en la página home }); }); //Crea una ruta a la pestaña about app.get('/about', (req, res) => { res.render('about'); }); app.listen(port, () => { console.log(`Escuchando peticiones en el puerto ${port}`); });
Markdown
UTF-8
5,988
3.9375
4
[]
no_license
# ES6 features ## class Syntax allows to create objects with the *class* keyword ES5: ``` var Vegetable = function (vegetableName) { this.vegetableName = vegetableName; } var carrot = new Vegetable ('carrot'); ``` ES6: UpperCamelCase should be used to name classes ``` class Vegetable{ constructor (vegetableName) { this.vegetableName = vegetableName; } } const cucumber = new Vegetable ('cucumber'); ``` ## getters and setters allow to get and set the value of the object's private variable without the user directly accessing this private variable: ``` class Book { constructor(author) { this._author = author; } // getter get writer() { return this._author; } // setter set writer(updatedAuthor) { this._author = updatedAuthor; } } const novel = new Book('anonymous'); console.log(novel.writer); //anonymus novel.writer = 'newAuthor'; console.log(novel.writer); //newAuthor ``` More sophisticated example: ``` class Thermostat { constructor(farenheit) { this._temperature = farenheit; } get temperature(farenheit) { return 5/9 * (this._temperature - 32); } set temperature(celsius) { this._temperature = celsius * 9.0 / 5 + 32; } } ``` In the example above the temperture inside the class should be tracked in one scale, either farenheit or celsius. ## Module script to easily share code among JavaScript files, imports and exports are used. To be able to import and export files, you should create a script of type "module": ``` <script type="module" src="fileName.js"></script> ``` # Regular Expressions ## /search/ .test() returns the boolean result of the search ``` let regex = /Search/; let string = 'Search here'; regex.test(string); // true ``` ## /search1|search2|search3/ OR ``` let regex = /here|there|everywhere/; let string = 'Search here, there'; regex.test(string); ``` ## /search/i i flag - ignores the case ``` let regex = /search/i; let string = 'Search here'; regex.test(string); // true ``` ## extract matches .match() returns the string result of the search ``` let regex = /Search/; let string = 'Search here'; string.match(regex); ``` `.match()` is opposite of `.test()`: ``` 'string'.match(/regex/); /regex/.test('string'); ``` ## /search/g g flag - to extract a pattern more than once ``` let regex = /search/g; let string = 'Search, search, search'; string.match(regex); // ['search', 'search'] ``` ## Wildcard period . - matches any character in the place of the dot ``` let regex = /.at/; let stringCat = 'I have a cat'; let stringFat = 'He is fat'; let stringAt = 'Look at him'; stringCat.match(regex); // ['cat'] stringFat.match(regex); // ['fat'] stringAt.match(regex); // [' at'] ``` ## Character classes [ ] - allow to define a group of characters to search for ``` let regex = /[cf]at/gi; let string = 'That cat is so fat'; string.match(regex); // ['cat', 'fat'] 'that' does not count ``` ## Range of characters [ - ] allows to specify the range of characters ``` let regex = /[a-f]at/g; let string = 'The cat is chasing a rat'; string.match(regex); // ['cat'] 'rat' does not count ``` This also works with numbers; letters and numbers can be combined: ``` let regex = /[0-6a-c]/g; let string = '5 bananas and 8 apples'; string.match(regex); // ['5', 'b', 'a', 'a', 'a', 'a', 'a'] ``` ## Negated character set [^thingsThatWillNotBeMatched] - allows to exclude indicated characters/symbols/white spaces from the search ``` let regex = /[^0-9aeiou ]/g; let string = '2 fat cats'; string.match(regex); // ['f', 't', 'c', 't', 's'] ``` ## One or more times in a row [ +] - allows to search for characters/groups that appear consecutively (one after another) ``` let regex = /[s+p+]/g; let string = 'Mississippi'; string.match(regex); // ['s', 's', 's', 's', 'p', 'p'] ``` ## Zero or more times ' *' - allows to match characters that occur 0+ times ``` let regex = /go*/i; let stringGoal = 'Gooooooal'; let stringGummy = 'gummy bear'; let stringNothing = 'no match'; stringGoal.match(regex); // ['Goooooo'] stringGummy.match(regex); // ['g'] stringNothing.match(regex); // null ``` ## Greedy vs Lazy matching *greedy match* finds the longest possible part that fits ``` let regex = /t[a-z]*i/; let string = 'titanic'; string.match(regex); // ['titani'] ``` *lazy match* finds the shortest possible part that fits ? - allows lazy matching ``` let regex = /t[a-z]*?i/; let string = 'titanic'; string.match(regex); // ['ti'] ``` ## Beginning String ^ outside of [ ] allows to search for the pattern only at the beginning of the string ``` let regex = /^Cat/; let stringYes = 'Cat is found here'; let stringNo = 'Unable to find a Cat here'; stringYes.match(regex); // ['Cat'] stringNo.match(regex); // null ``` ## Ending String $ at the end of regex - allows to search for the pattern only at the end of the string ``` let regex = /dog$/; let stringYes = 'I have a dog'; let stringNo = 'Dog is my pet'; stringYes.match(regex); // ['dog'] stringNo.match(regex); // null ``` ## Shorthand charatcter classes [ - ] - allows to specify the range of characters [A-Za-z0-9_] - matches all uppercase and lowercase letters, numbers and underscore \w - shorthand for [A-Za-z0-9_] ## Opposite of the above [^A-Za-z0-9_] - matches everything apart from uppercase and lowercase letters, numbers and underscore \W - shorthand for [^A-Za-z0-9_] ## Match all numbers \d - same as [0-9] ## Match all non-numbers \D - same as [^0-9] ## Whitespace \s - whitespace, carriage return, tab, form feed, new line \S - non-whitespace, [^ \r\t\f\n\v] ## Quantity specifiers { 3,6 } - for the lower and upper number of patterns (how many times the pattern should appear in the search) { 5, } - without second number it sets only lower bound { 5 } - just one number sets the exact nu,ber of matches
Python
UTF-8
682
2.6875
3
[]
no_license
import csv import os from Robot.country.country_repository import CountryRepository from Robot.cycle.objects.color import Color def fill_repository(): file_path = os.path.join(os.path.dirname(__file__), "..", "resources", "flags.csv") with open(file_path, newline='') as csvfile: country_dictionary = {} spamreader = csv.reader(csvfile, delimiter=';', quotechar='|') for country_data in spamreader: country_name = country_data[1] flag_colors = [Color[color] for color in country_data[2:]] country_dictionary[country_name] = flag_colors CountryRepository().store(country_dictionary)
Java
UTF-8
486
2.390625
2
[]
no_license
package uk.co.datadisk.asciiart; import com.godtsoft.diyjava.DIYWindow; /** * Created by vallep on 09/07/2017. */ public class ASCIIAart extends DIYWindow { public ASCIIAart() { print(" @@@@@@@@"); print(" | |"); print(" | (0)(0)"); print("C _)"); print(" | ___|"); print(" | /"); print("/ \\"); print(""); } public static void main(String[] args) { new ASCIIAart(); } }
Python
UTF-8
775
3.890625
4
[]
no_license
# 替换字符串---replace str01 = "www.cctv.com" print(str01.replace("com", "cn")) # 去除空格 str02 = " 我 是 中 过 人 " print(str02.strip()) print(str02.replace(" ", "")) # 如果多处匹配 如何替换 str03 = "abddabjjabllab" print(str03.replace("ab", "12")) # 默认全部替换 print(str03.replace("ab", "12", 2)) # 替换前两个匹配的 # 如果实现第偶数个 替换,怎么做 # 模拟聊天窗口,设定一些关键字,如果发送信息包含关键字,把信息中关键字用*替换 tuple01 = ("我爱你", "我恨你","我想你") send_message = input("请输入信息:") for i in tuple01: if i in send_message: send_message = send_message.replace(i, "*") print("你要发送的信息为:", send_message)
Markdown
UTF-8
4,467
2.78125
3
[ "MIT" ]
permissive
HTML5 Games Dreamengine - What is it =========== The Dreamengine is a library to create HTML5 games by coding. It's not "easy make" or things like that, it's more about "how to make games fast, running everywhere, with good perfs, and without doing boring stuff". So I don't say it's the best HTML5 engine, I know that I can wrote a complex prototype in few hours, and it'll run well everywhere. By Rogliano Antoine, [Dreamirl](http://dreamirl.com) [Inateno](http://inateno.com) The official website [HTML5-Dreamengine](http://dreamengine.dreamirl.com) Follow on [Twitter](http://twitter.com/dreamirlgames) Or [Facebook](https://www.facebook.com/Dreamirl) A little word about "story" (and why) ------- I push this engine on github after one year to work on it at very part time, I worked mainly during GameJams because I didn't wanted to create a "theoric" engine (you think it's great then you code it) but I build the engine around my needs, when you make a games and you know what you would like in the engine. Inputs are boring things, gamepad to, calculating positions and rotations, or thinking about gameObjects and components. I didn't make more complex stuff like physic, good Gui (still wip), I don't care at the moment, I wanted a good architecture for all of my games, now adding features on it is not the most complicated. Who can use it, why use it ------- If you are looking for a "clicking game factory" or if you fear coding, or can't/don't want thinking about "code architecture" this engine isn't for you. I builded it around RequireJS, I think always about "DRY" and architecture, I wanted to create something I will be able to maintain and make it grow with no limit, but at the same time, providing the lightest stuff, to do the most possible. Here we aren't talking about "I take the engine and code my game" but more about "this is a library, now add your stuff on it and make your games", by using the engine like this, you'll be productive at the end. Of course you can make a game directly (like most of examples) and this work well, but this will not maintainable and you'll not be able to make "big games" (you'll suicide before). Si finally I think this engine is for people who want to make "big games" with a base that provide usefull stuff. But of course, everyone can use it! Cool features ------- Ok so there is some cool features * gamepad API for Chrome and compatible with Windows8 (if you bring the XInput component on you project and use the SystemDetection), it should work on Firefox but I tried to use it and it never worked :( * multi-quality (no more stuff required than write you quality settings in the imagesDatas file) * simple Inputs trigger (keyboard and mouse/touch, compatible with multi-touch, and possible to work with interval) * nice GameObjects with hierarchy system, and components (renderers, collider) * thinked to herit from base class as you want (so make plugins for everyone, is very easy) * simple images loader/configuration trough a basic list (but don't manage complex spritesheet yet) * work with an intern dictionnary (LangSystem) to provide an easy way for the localisation * easy to bring on new platforms with the SystemDetection (let you override what you want, and bind stuff on init) When a speak about "bring on platform" I mean, include in a wrapper to make an executable (apk, etc..) Compatible with "native" platforms ------- This part is in early release, I wont make public stuff that's not working well. * Windows8 - 8.1 - VS Express - OK * WP8 - VS Express - WIP (soon) * KindleFire (amazon appstore) - Webapp - WIP (soon) * Tizen - Tizen SDK - WIP (soon) * Android - Phonegap - not yet * iOS - not yet (I don't have stuff for this) Documentation ------- I didn't wrote a documentation, this take lot of time and I preferred use my time to clean and debug the engine as possible. But now it's on Github, I'll did it on the dreamengine website. Contributing ------- You wrote a game ? A plugins ? An editor ? Or other stuff ? You know a better to do something in the engine (physics, loop, inputs, gui...) ? Feel free to contact me: inateno@gmail.com Or send us tweet/pm, or simply pull request. License ------- The Dreamengine is released under the [MIT License](http://opensource.org/licenses/MIT). Finally it's here, for everyone, feel free to use it, share it and contribute. Feel free to contact me, I'm on Twitter @Inateno or the team @DreamirlGames (Dreamirl on Facebook)
C++
UTF-8
218
2.5625
3
[]
no_license
#include<stdio.h> int main(){ int T; scanf("%d",&T); while( T-- ){ int N; scanf("%d",&N); int tot = 0; for( int i = 0; i < N; ++i ){ int a; scanf("%d",&a); tot += a; } printf("%d\n",tot); } }
Java
UTF-8
931
2.5625
3
[]
no_license
package com.cmy.o2o.dto; import lombok.Data; /** * Author : cmy * Date : 2018-03-05 11:48. * desc : 封装json对象,所有返回结果都使用它 */ @Data public class Result<T> { // 是否成功标志 private boolean success; // 成功时返回的数据 private T data; // 错误信息 private String errorMsg; // 错误码 private int errorCode; public Result() { } /** * 成功时的构造器 * * @param success * @param data */ public Result(boolean success, T data) { this.success = success; this.data = data; } /** * 错误时的构造器 * * @param success * @param errorMsg * @param errorCode */ public Result(boolean success, int errorCode, String errorMsg) { this.success = success; this.errorCode = errorCode; this.errorMsg = errorMsg; } }
PHP
UTF-8
2,287
2.875
3
[]
no_license
<?php namespace MVC\Models; use \System\ORM\Model; /** * Class Community * @package MVC\Models * @table(communities) * @updateBy(id) */ class Community extends Model { /** * Unique key for Community * * @columnType(INT(11) UNSIGNED NOT NULL AUTO_INCREMENT KEY) * @var int */ private $id; /** * Creator id * * @columnType(INT(11) UNSIGNED NOT NULL) * @foreignModel(\MVC\Models\User) * @foreignField(id) * @var User */ private $user; /** * Name of community * * @columnType(VARCHAR(400) UNIQUE) * @var String */ private $name; /** * community description and rules * * @columnType(TEXT) * @var string */ private $about; /** * Option, which enables or disables * moderation publications * before attachment to the community * * @columnType(TINYINT(1) UNSIGNED NOT NULL DEFAULT 0) * @var boolean */ private $secured; /** * @param User|int $user * @return $this */ public function setUser($user) { $this->user = $user; return $this; } /** * @return int */ public function getId(): int { return $this->id; } /** * @return User */ public function getUser(): User { return $this->user; } /** * @return String */ public function getName(): String { return $this->name; } /** * @return string */ public function getAbout(): string { return $this->about; } /** * @return bool */ public function isSecured(): bool { return (bool) $this->secured; } /** * @param String $name * @return $this */ public function setName(String $name) { $this->name = $name; return $this; } /** * @param string $about * @return $this */ public function setAbout(string $about) { $this->about = $about; return $this; } /** * @param bool $secured * @return $this */ public function setSecured($secured) { $this->secured = (int) $secured; return $this; } }
Markdown
UTF-8
1,359
2.609375
3
[ "Apache-2.0" ]
permissive
# Fabric Loot API (v2) This module includes APIs for modifying and creating loot tables. ## [Loot table events](src/main/java/net/fabricmc/fabric/api/loot/v2/LootTableEvents.java) This class provides two events for modifying loot tables. `LootTableEvents.REPLACE` runs first and lets you replace loot tables completely. `LootTableEvents.MODIFY` runs after and lets you modify loot tables, including the ones created in `REPLACE`, by adding new loot pools or loot functions to them. ### Loot table sources Both events have access to a [loot table source](src/main/java/net/fabricmc/fabric/api/loot/v2/LootTableSource.java) that you can use to check where a loot table is loaded from. For example, you can use this to check if a loot table is from a user data pack and not modify the user-provided data in your event. ## Enhanced loot table and loot pool builders `LootTable.Builder` and `LootPool.Builder` implement injected interfaces ([`FabricLootTableBuilder`](src/main/java/net/fabricmc/fabric/api/loot/v2/FabricLootTableBuilder.java) and [`FabricLootPoolBuilder`](src/main/java/net/fabricmc/fabric/api/loot/v2/FabricLootPoolBuilder.java)) which have additional methods for dealing with already-built objects and collections of objects. Those interfaces also have `copyOf` methods for creating copies of existing loot tables/pools as builders.
C++
UTF-8
1,174
3.203125
3
[]
no_license
#include<iostream> #include<algorithm> #include<vector> using namespace std; int minPathSum(vector<vector<int> > &grid) { int m=grid.size(); if(m==0) return 0; int n=grid[0].size(); int Paths[m][n]; for(int i=m-1;i>=0;i--){ for(int j=n-1;j>=0;j--){ if(i==m-1&&j==n-1){ Paths[i][j]=grid[i][j]; continue; } Paths[i][j] =grid[i][j]+( (i+1<=m-1&&j+1<=n-1)? min(Paths[i+1][j],Paths[i][j+1]):((i+1>=m)? Paths[i][j+1]:Paths[i+1][j])); } } return Paths[0][0]; } int minPathSum_one_dimensional_array(vector<vector<int> > &grid) { int m=grid.size(); if(m==0) return 0; int n=grid[0].size(); int Paths[n]; for(int i=m-1;i>=0;i--){ for(int j=n-1;j>=0;j--){ if(i==m-1&&j==n-1){ Paths[j]=grid[i][j]; continue; } Paths[j] =grid[i][j]+( (i+1<=m-1&&j+1<=n-1)? min(Paths[j],Paths[j+1]):((i+1>=m)? Paths[j+1]:Paths[j])); } } return Paths[0]; } int main(){ vector<vector<int> > grid; vector<int> a; a.push_back(1); a.push_back(2); vector<int> b(2,1); grid.push_back(a); grid.push_back(b); cout<<minPathSum_one_dimensional_array(grid)<<endl; return 0; }
Java
UTF-8
414
2.640625
3
[]
no_license
package com.vm.training.java.collection; public class Employee { int empId; String name; String address; public Employee(int empId, String name, String address) { super(); this.empId = empId; this.name = name; this.address = address; } @Override public String toString() { return "Employee [empId=" + empId + ", name=" + name + ", address=" + address + "]"; } }
PHP
UTF-8
4,131
2.953125
3
[]
no_license
<?php /* Le controlleur formation qui gère les vues et le model des formation */ class FormationController { public function ajoutFormation() { if (isset($_SESSION['login']) && isset($_SESSION['profile'])) { if (($_SESSION['profile'] == "Responsable Formation") || ($_SESSION['profile'] == "Responsable Administratif")) { $mfac = new ModelFaculte(); $facs = $mfac->getAllFacs(); $functionUrl = "actionAjoutFormation"; $sub_title = "Ajout d'une formation"; include_once VIEWS . DS . 'ajoutformation.php'; } else { header('Location: ' . URL_BASE); } } } /* fonction qui met en relation les données du formulaire d'ajout d'une formation * et la fonction addFormation() du modèle formation pour l'ajout */ public function actionAjoutFormation() { $nom = filter_input(INPUT_POST, 'formaNom', FILTER_SANITIZE_STRING); $facId = filter_input(INPUT_POST, 'facId', FILTER_SANITIZE_STRING); $m = new ModelFormation(); $m->addFormation($nom, $facId); header('Location: ' . URL_BASE . '/Formation/listFormations'); } /* fonction qui met en relation les données * renvoyées par la fonction getAllFormations() * du modèle formation * et la vue qui affihe les formations */ public function listFormations() { if (isset($_SESSION['login']) && isset($_SESSION['profile'])) { if (($_SESSION['profile'] != "Responsable Formation") && ($_SESSION['profile'] != "Responsable Administratif")) { $classe = "hide"; } $m = new ModelFormation(); $list = $m->getAllFormations(); include_once VIEWS . DS . 'listformations.php'; } else { include_once VIEWS . DS . 'connexion.php'; } } /* fonction qui met en relation les donnéss * renvoyées par la fonction getFormation() * du modèle formation * et le formulaire pour modifier une formation */ public function modiFormation() { if (isset($_SESSION['login']) && isset($_SESSION['profile'])) { if (($_SESSION['profile'] == "Responsable Formation") || ($_SESSION['profile'] == "Responsable Administratif")) { $id = filter_input(INPUT_GET, 'formaId', FILTER_SANITIZE_NUMBER_INT); $m = new ModelFormation(); $form = $m->getFormation($id); $mfac = new ModelFaculte(); $facs = $mfac->getAllFacs(); $functionUrl = "actionModiFormation"; $sub_title = "Modification d'une formation"; include_once VIEWS . DS . 'ajoutFormation.php'; } else { header('Location: ' . URL_BASE); } }else { header('Location: ' . URL_BASE); } } /* fonction qui met en relation les données * renvoyées par le formulaire de modification d'une formation * et la fonction updateFormation() du modeèle formation * pour la mise à jour d'une formation */ public function actionModiFormation() { $id = filter_input(INPUT_POST, 'formaId', FILTER_SANITIZE_STRING); $nom = filter_input(INPUT_POST, 'formaNom', FILTER_SANITIZE_STRING); $facId = filter_input(INPUT_POST, 'facId', FILTER_SANITIZE_STRING); $m = new ModelFormation(); $m->updateFormation($id, $nom, $facId); header('Location: ' . URL_BASE . '/Formation/listFormations'); } /* fonction qui appelle la fonction deleteFormation() * du modèle matiere pour supprimer une matière */ public function deleteFormation() { $id = filter_input(INPUT_GET, 'formaId', FILTER_SANITIZE_STRING); $m = new ModelFormation(); $m->deleteFormation($id); header('Location: ' . URL_BASE . '/Formation/listFormations'); } } ?>
C++
GB18030
604
3.078125
3
[]
no_license
#include "OJ.h" /* : : MatrixA,MatrixB : MatrixC : 0 */ int matrix(int **MatrixA, int **MatrixB, int **MatrixC, int N) { if(MatrixA == 0 || MatrixA == 0 || MatrixB == 0) { return 0; } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int sum = 0; for (int k = 0; k < N; k++) { //sum = sum + MatrixA[i][k]*MatrixB[k][j]; sum = sum + (*((int*)MatrixA + i*N + k))*(*((int*)MatrixB + k*N + j)); } //MatrixC[i][j] = sum; (*((int*)MatrixC + i*N+j)) = sum; } } return 0; }
Python
UTF-8
927
3.3125
3
[]
no_license
class Monster: def __init__ (self): self.id = None self.description = None self.hp = None self.trophy = None #Load Monster Information from the Monster Database def load_monster(self,monster_number): __filename = "monster_db.txt" __monster_match = "Monster Num: " + str(monster_number) __switch = False self.id = monster_number #Open Item Database with open(__filename) as fobject: rlist = fobject.read().splitlines() #Scan Item Database for the correct Item Num for data in rlist: if data == __monster_match: __switch = True #Retrieve Item Description if __switch: if data.startswith('Description:'): v,y = data.split(':',1) self.description = y.strip() elif data.startswith('HP:'): v,y = data.split(':',1) self.hp = y.strip() elif data.startswith('Trophy:'): v,y = data.split(':',1) self.trophy = y.strip() elif not data: break
TypeScript
UTF-8
2,026
3.046875
3
[ "MIT" ]
permissive
import EmitterSubscription from './EmitterSubscription' import EventSubscriptionVendor from './EventSubscriptionVendor' export default class BaseEventEmitter { currentSubscription: EmitterSubscription | null subscriber: EventSubscriptionVendor constructor() { this.subscriber = new EventSubscriptionVendor() this.currentSubscription = null } addListener(eventType: string, listener: Function): EmitterSubscription { return this.subscriber.addSubscription( eventType, new EmitterSubscription(this.subscriber, listener) ) } once(eventType: string, listener: Function): EmitterSubscription { return this.addListener(eventType, (...args: any) => { this.removeCurrentListener() listener(...args) }) } removeAllListeners(eventType?: string): void { this.subscriber.removeAllSubscriptions(eventType) } removeCurrentListener(): void { if (!this.currentSubscription) { throw Error('Not in an emitting cycle; there is no current subscription') } this.subscriber.removeSubscription(this.currentSubscription) } listeners(eventType: string): Array<Function> { const subscriptions = this.subscriber.getSubscriptionsForType(eventType) return subscriptions ? subscriptions.map((subscription: EmitterSubscription) => subscription.listener) : [] } emit(eventType: string, ...data: any): void { const subscriptions = this.subscriber.getSubscriptionsForType(eventType) if (subscriptions) { const keys = Object.keys(subscriptions) for (let i = 0; i < keys.length; i++) { const key = keys[i] as any const subscription = subscriptions[key] if (subscription) { this.currentSubscription = subscription this.emitToSubscription(subscription, eventType, ...data) } } this.currentSubscription = null } } protected emitToSubscription(subscription: any, eventType: string, ...data: any): void { subscription.listener(...data) } }
Java
UTF-8
3,171
3.09375
3
[]
no_license
/********************************************************************************** * API: APIFileCipher - Suppose que la clé blowfish a déjà été généré * Description: Utilise ApiBlowfish pour le chiffrement et déchiffrement de fichier * Auteur: Didier Samfat * Date: 28 Mar 2021 * Version: 1.0 *********************************************************************************/ package myBlowfish; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.Key; import java.util.Base64; public class ApiFileCipher { /** * Méthode qui lit un fichier est retourne ce qu'il a lu * @param nomFichier: le fichier à lire * @return : la chaîne lue */ static String read(String nomFichier) { try { // Lit le fichier clair File inFile = new File(nomFichier); FileInputStream inputStream = new FileInputStream(inFile); byte[] inBytes = new byte[(int) inFile.length()]; inputStream.read(inBytes); // lit le fichier clair inputStream.close(); //return Base64.getEncoder().encodeToString(inBytes); return new String(inBytes); } catch (FileNotFoundException e) {} catch (IOException e) {} return null; } /** * Méthode qui chiffre un fichier donné avec une clé blowfish * Créer asussi un nouveau fichier au format nomFichier.cryp * @param nomFichier : fichier qui doit être chiffré * @param clef : doit être généré au prálable * @return : le texte chifré encode en Base64 * @throws Exception */ static String encrypt(String nomFichier, Key clef) throws Exception{ try { // Lit le fichier clair File inFile = new File(nomFichier); FileInputStream inputStream = new FileInputStream(inFile); byte[] inBytes = new byte[(int) inFile.length()]; inputStream.read(inBytes); // lit le fichier clair // creer fichier.txt.cryp String fichierCrypte = nomFichier + ".cryp"; File outFile = new File(fichierCrypte); // creer le fichier de sortie crypté FileOutputStream outputStream = new FileOutputStream(outFile); byte[] texteChiffre = ApiBlowfish.encryptInByte(inBytes, clef); outputStream.write(texteChiffre); // on sauvegarde inputStream.close(); outputStream.close(); // encodage pour lisibilité du texte à l'écran return Base64.getEncoder().encodeToString(texteChiffre); } catch (FileNotFoundException e) {} catch (IOException e) {} return null; } static String decrypt(String nomFichier, Key clef) throws Exception{ try { File inFile = new File(nomFichier); FileInputStream inputStream = new FileInputStream(inFile); byte[] inBytes = new byte[(int) inFile.length()]; inputStream.read(inBytes); byte[] texteDechiffre = ApiBlowfish.decryptInByte(inBytes, clef); String chaine = new String(texteDechiffre); inputStream.close(); return chaine; } catch (FileNotFoundException e) {} catch (IOException e) {} return null; } }
C++
UTF-8
2,311
2.921875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; struct Activity { int id; int startTime; int endTime; char person; }; void solve(string &str, int test) { } bool compStartTime(Activity &a1, Activity &a2) { if(a1.startTime < a2.startTime ) { return true; } return false; } bool compEndTime(Activity &a1, Activity &a2) { if(a1.endTime < a2.endTime ) { return true; } return false; } bool compById(Activity &a1, Activity &a2) { if(a1.id < a2.id ) { return true; } return false; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t,testCase; cin>>t; for( testCase=1;testCase<=t;testCase++) { int n; cin>>n; int lastC=0, lastJ=0; vector<Activity> A(n); for(int i=0;i<n;i++) { A[i].id=i+1; cin>>A[i].startTime>>A[i].endTime; A[i].person='F'; } sort(A.begin(),A.end(),compStartTime); //sort(A.begin()+1,A.end(),compEndTime); A[0].person='C'; lastC=A[0].endTime; for(int i=0;i<n-1;i++) { if(A[i+1].startTime >= lastC) { A[i+1].person='C'; lastC=A[i+1].endTime; } } for(int i=0;i<n;i++) { if(A[i].person=='F') { lastJ=A[i].endTime; A[i].person='J'; break; } } for(int i=0;i<n-1;i++) { if(A[i+1].person=='F' && A[i+1].startTime >= lastJ) { A[i+1].person='J'; lastJ=A[i+1].endTime; } } bool impossible=false; for(int i=0;i<n;i++) { if(A[i].person=='F') { impossible=true; break; } } string soln=""; if(impossible==true) { cout<<"Case #"<<testCase<<": "<<"IMPOSSIBLE"<<endl; } else { sort(A.begin(),A.end(),compById); for(int i=0;i<n;i++) { soln+=A[i].person; } cout<<"Case #"<<testCase<<": "<<soln<<endl; } } return 0; }
Python
UTF-8
404
3.421875
3
[]
no_license
from turtle import Turtle import random class Food(Turtle): def __init__(self): super().__init__() self.shape("circle") self.color("blue") self.penup() # self.goto(random.randint(-290,290),random.randint(-290,290)) self.update_location() def update_location(self): self.goto(random.randint(-260,260),random.randint(-260,260))
Java
UTF-8
60
1.84375
2
[]
no_license
public enum messageType { Text,Image,Video,SoundTrack }
PHP
UTF-8
5,721
2.515625
3
[]
no_license
<?php include 'database_of.php'; include 'calls.php'; $search = "%{$_POST['title']}%"; $title = mysqli_real_escape_string($connect, $search); $tid = mysqli_real_escape_string($connect, $_POST['val']); $cate = mysqli_real_escape_string($connect, $_POST['cate']); $s1 = $cate; $output = ''; if(!empty($cate)) { if($tid == '') { $sort = "SELECT * FROM topics WHERE category_id = ? AND (`topic_title` LIKE ?) ORDER BY `date` DESC"; } elseif($tid == '1') { $sort = "SELECT * FROM topics WHERE category_id = ? AND (`topic_title` LIKE ?) ORDER BY `date` ASC"; } elseif ($tid == '2') { $sort = "SELECT * FROM topics WHERE category_id = ? AND (`topic_title` LIKE ?) ORDER BY `date` DESC"; } elseif($tid == '3') { sorted(); $sort = "SELECT * FROM topics WHERE category_id = ? AND (`topic_title` LIKE ?) ORDER BY `replies` DESC"; } elseif($tid == '4') { sorted(); $sort = "SELECT * FROM topics WHERE category_id = ? AND (`topic_title` LIKE ?) ORDER BY `replies` ASC"; } $st = mysqli_stmt_init($connect); if(!mysqli_stmt_prepare($st, $sort)) { echo ""; exit(); } mysqli_stmt_prepare($st, $sort); if(!empty($cate)) { mysqli_stmt_bind_param($st, "is", $cate, $title); } else{ mysqli_stmt_bind_param($st, "is", $s1, $title); } } else{ if($tid == '') { $sort = "SELECT * FROM topics WHERE (`topic_title` LIKE ?) ORDER BY `date` DESC"; } elseif($tid == '1') { $sort = "SELECT * FROM topics WHERE (`topic_title` LIKE ?) ORDER BY `date` ASC"; } elseif ($tid == '2') { $sort = "SELECT * FROM topics WHERE (`topic_title` LIKE ?) ORDER BY `date` DESC"; } elseif($tid == '3') { sorted(); $sort = "SELECT * FROM topics WHERE (`topic_title` LIKE ?) ORDER BY `replies` DESC"; } elseif($tid == '4') { sorted(); $sort = "SELECT * FROM topics WHERE (`topic_title` LIKE ?) ORDER BY `replies` ASC"; } $st = mysqli_stmt_init($connect); if(!mysqli_stmt_prepare($st, $sort)) { echo ""; exit(); } mysqli_stmt_prepare($st, $sort); mysqli_stmt_bind_param($st, "s", $title); } mysqli_stmt_execute($st); $result = mysqli_stmt_get_result($st); $rowcount = mysqli_num_rows($result); if(mysqli_num_rows($result) < 1) { $output = '<tr > <td style="width: 100%; height: 100%; "> <div style="font-family: monospace; font-size: 12px; font-weight: bold; color: gray;">None !</p> </td> </tr>'; echo $output; exit(); } if($rowcount > 1) { $rowcount = $rowcount.' results'; } else{ $rowcount = $rowcount.' result'; } $output = '<span style="width: 100%; font-size: 12px; color: gray; margin-top: -15px;">'.$rowcount.'</span>'; while($row = mysqli_fetch_assoc($result)) { if($row['category_id'] == '1'){ $col = '#2D4157'; } elseif ($row['category_id'] == '2') { $col = '#38AB26'; } elseif ($row['category_id'] == '3') { $col = '#F4C515'; } elseif ($row['category_id'] == '4') { $col = '#435987'; } elseif ($row['category_id'] == '5') { $col = '#267CAB'; } $row['topic_title'] = str_replace("\'", "'", $row['topic_title']); $row['topic_desc'] = str_replace("\'", "'", $row['topic_desc']); $row['topic_desc'] = str_replace('\n', "\n", $row['topic_desc']); $row['topic_desc'] = str_replace('\r', "\r", $row['topic_desc']); $query = "SELECT * FROM replies WHERE category_id = '1' AND topic_id = '".$row['id']."'"; $submit = mysqli_query($connect, $query); $replies = mysqli_num_rows($submit); $fresh = "SELECT `date` FROM replies WHERE category_id = '1' AND topic_id = '".$row['id']."' ORDER BY `date` DESC LIMIT 1"; $submitf = mysqli_query($connect, $fresh); $output .= '<tr style="line-height: 40px;"> <td style="border-top: 0.5px solid #F0F0F0; width: 100%; height: 100%; "> <span style="height: 100%; width: 65%; float: left;"> <div class="topic_link" id='.$row['id'].' data-cat = '.$row['category_id'].' style="width:100%; cursor:pointer; height: 28px; margin:0px; color: '.$col.'; font-size: 16px; vertical-align: top; overflow:hidden;">'.$row['topic_title'].' </div> <div style="width:100%; height:26px; display:block; color: #B3B3B3; font-size: 13px; vertical-align: top; margin: 0px; padding:0px; overflow:hidden;">'.nl2br($row['topic_desc']).' </div> </span> <span style="width:15%; display:inline; float:left; color: gray; font-size: 14px; ">'.$replies.'</span>'; while($rowf = mysqli_fetch_assoc($submitf)) { $fr = $rowf['date']; $output .= '<span style="width:20%; color: gray; float:right; display:inline; font-size: 14px;">'.agoTime(cut($fr)).'</span>'; } $output .= '</td> </tr>'; } echo $output; function sorted() { include 'database_of.php'; $up = "SELECT * FROM topics WHERE category_id = '1'"; $upts = mysqli_query($connect, $up); while($row = mysqli_fetch_assoc($upts)) { $topic_id = $row['id']; $category_id = $row['category_id']; $sqs = "SELECT * FROM replies WHERE topic_id = ? AND category_id = ?;"; //$result = mysqli_query($connect, $sql); $sts = mysqli_stmt_init($connect); if(!mysqli_stmt_prepare($sts, $sqs)) { exit(); } mysqli_stmt_prepare($sts, $sqs); mysqli_stmt_bind_param($sts, "ii", $topic_id, $category_id); mysqli_stmt_execute($sts); $resultsq = mysqli_stmt_get_result($sts); $rowcountsq = mysqli_num_rows($resultsq); $status = "UPDATE topics SET replies = '$rowcountsq' WHERE id = '".$row['id']."'"; $results = mysqli_query($connect, $status); } } //<tr><td style="border-bottom: 0.5px solid #F0F0F0; width:100%;"><span style="color: #429AA4; font-size: 14px; font-weight:bold; font-family: Calibri;">Results</td></tr> ?>
C++
UTF-8
527
2.828125
3
[]
no_license
#include "../test-prog.h" #if (PNUM == lv02-33) // 폰캣몬 문제 #include <iostream> #include <vector> using namespace std; int arr[200001]; int solution(vector<int> nums) { int answer = 0; for (int i = 0; i < nums.size(); i++) { if (!arr[nums[i]]) { arr[nums[i]]++; if (answer >= nums.size() / 2) break; answer++; } } return answer; } int main() { vector<int> nums = { 3, 3, 3, 2, 2, 4 }; cout << solution(nums); return 0; } #endif
JavaScript
UTF-8
1,976
2.609375
3
[]
no_license
/* O propósito de "use strict" é indicar que o código deve ser executado em "modo estrito". Com o modo estrito, você não pode, por exemplo, usar variáveis ​​não declaradas. */ 'use strict'; //Sequelize = ORM banco relacional //Modelos são definidos com sequelize.define('name', {attributes}, {options}). module.exports = function(sequelize, DataTypes) { return sequelize.define('Usuario', { id: { type: DataTypes.INTEGER, field: 'id', allowNull: false, primaryKey: true, autoIncrement: true, comment: 'Chave primaria' }, email: { type: DataTypes.STRING(80), field: 'email', allowNull: false, comment: 'Email do usuario' }, tipo: { type: DataTypes.INTEGER, field: 'tipo', allowNull: false, comment: 'Tipo de usuario 1- Portaria, 2- Condomino, 3- Administrador' }, senha: { type: DataTypes.STRING(32), field: 'senha', allowNull: false, comment: 'Senha para o login' }, desativado: { type: DataTypes.BOOLEAN, field: 'desativado', allowNull: false, comment: 'Status do usuario' }, criacao: { type: DataTypes.DATE, field: 'criacao', allowNull: false, comment: 'Data e hora da criacao' }, token: { type: DataTypes.STRING, field: 'token', allowNull: true, comment: 'Token para validação' } }, { //schema: 'public', tableName: 'usuario', timestamps: false, name:{ singular:'usuario', plural :'usuarios' } }); }; module.exports.initRelations = function() { delete module.exports.initRelations; };
C#
UTF-8
1,241
2.71875
3
[ "MIT" ]
permissive
using System; using System.Globalization; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using System.Diagnostics; using System.Windows.Input; namespace IDE_WPF.Controls { public class Button : Control { public Button() { this.MouseDown += UIElement_MouseDown; IsHitTestVisible = true; } private void UIElement_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { Debug.WriteLine("Mouse Down"); } public string Text { get; set; } public override void OnDraw() { using(var context = Visual.RenderOpen()) { context.DrawRectangle(Brushes.Silver, new Pen(Brushes.Black, 1.0), new Rect(Position, new Size(Width, Height))); context.DrawText(new FormattedText(Text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Consolas"), 16, Brushes.Black), Position); } } protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); } } }
Java
UTF-8
2,331
2.328125
2
[]
no_license
package frc.robot.subsystems; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import com.revrobotics.CANEncoder; import com.revrobotics.CANPIDController; import com.revrobotics.CANSparkMax; import com.revrobotics.ControlType; import com.revrobotics.CANSparkMaxLowLevel.MotorType; public class ShooterWheels extends SubsystemBase { CANSparkMax ShooterMotorLeft = new CANSparkMax(9, MotorType.kBrushless); CANSparkMax ShooterMotorRight = new CANSparkMax(10, MotorType.kBrushless); CANEncoder ShooterCANEncoderLeft = new CANEncoder(ShooterMotorLeft); CANEncoder ShooterCANEncoderRight = new CANEncoder(ShooterMotorRight); private CANPIDController m_shooterpidControllerLeft = new CANPIDController(ShooterMotorLeft); private CANPIDController m_shooterpidControllerRight = new CANPIDController(ShooterMotorRight); public ShooterWheels() { m_shooterpidControllerLeft.setP(Constants.shooter_kGains.kP); m_shooterpidControllerLeft.setI(Constants.shooter_kGains.kI); m_shooterpidControllerLeft.setD(Constants.shooter_kGains.kD); m_shooterpidControllerLeft.setIZone(Constants.shooter_kGains.kIzone); m_shooterpidControllerLeft.setFF(Constants.shooter_kGains.kFF); m_shooterpidControllerLeft.setOutputRange(Constants.shooter_kGains.kMinOutput, Constants.shooter_kGains.kMaxOutput); m_shooterpidControllerRight.setP(Constants.shooter_kGains.kP); m_shooterpidControllerRight.setI(Constants.shooter_kGains.kI); m_shooterpidControllerRight.setD(Constants.shooter_kGains.kD); m_shooterpidControllerRight.setIZone(Constants.shooter_kGains.kIzone); m_shooterpidControllerRight.setFF(Constants.shooter_kGains.kFF); m_shooterpidControllerRight.setOutputRange(Constants.shooter_kGains.kMinOutput, Constants.shooter_kGains.kMaxOutput); } public void turn (double spinSpeed){ ShooterMotorLeft.set(spinSpeed); } public void spinSpeedPID (double SetPointSpeedLeft,double SetPointSpeedRight){ m_shooterpidControllerLeft.setReference(SetPointSpeedLeft, ControlType.kVelocity); m_shooterpidControllerRight.setReference(SetPointSpeedRight, ControlType.kVelocity); } public CANEncoder getShooterEncoderLeft() { return ShooterCANEncoderLeft; } public CANEncoder getShooterEncoderRight() { return ShooterCANEncoderRight; } }
C++
UTF-8
3,704
3.859375
4
[]
no_license
// // Created by mark on 2019/7/8. // Copyright © 2019年 mark. All rights reserved. // /* 说明: 1. 问题:25.合并两个有序链表 2. 思路:不要断链,且递增;考虑特殊输入(空链表) 1. 用两个指针分别遍历两个链表,每次找到小的节点插入新链表中; 2. 递归方法,相当于每次比较两个头结点 */ #include <iostream> #include <vector> #include <stack> #include <queue> #include <cmath> #include <string> using namespace std; struct ListNode { int val; ListNode* next; }LN,*pLN; // 1. 非递归 ListNode* MergeList(ListNode* pHead1, ListNode* pHead2) { if(pHead1 == nullptr) return pHead2; else if(pHead2 == nullptr) return pHead1; ListNode* newHead = nullptr; // 先生成新的头结点 ListNode* cur = nullptr; // 作为新链表的遍历节点 if(pHead1->val < pHead2->val) { newHead = pHead1; pHead1 = pHead1->next; cur = newHead; } else { newHead = pHead2; pHead2 = pHead2->next; cur = newHead; } while(pHead1 != nullptr && pHead2 != nullptr) // 遍历两个链表 { if(pHead1->val < pHead2->val) { cur->next = pHead1; pHead1 = pHead1->next; } else { cur->next = pHead2; pHead2 = pHead2->next; } cur = cur->next; } while(pHead1 != nullptr) // 继续添加剩下的链表 { cur->next = pHead1; pHead1 = pHead1->next; } while(pHead2 != nullptr) { cur->next = pHead2; pHead2 = pHead2->next; } return newHead; } // 2. 递归,相当于每次比较两个链表的头结点,然后添加;合并的那个链表头结点移动一个再递归 ListNode* MergeList_Recu(ListNode* pHead1, ListNode* pHead2) { if(pHead1 == nullptr) return pHead2; if(pHead2 == nullptr) return pHead1; ListNode* newHead = nullptr; // 定义新的头结点 if( pHead1->val < pHead2->val) { newHead = pHead1; newHead->next = MergeList_Recu(pHead1->next, pHead2); // 递归,从链表1头结点的下个节点开始 } else { newHead = pHead2; newHead->next = MergeList_Recu(pHead2->next, pHead1); } return newHead; } // ------------------------------------------------------------------------------------------------------------------------ // 辅助函数,创建链表 ListNode* CreatListNode(int val) { ListNode* node = new ListNode(); node->val = val; node->next = nullptr; return node; } // 辅助函数,连接两个链表节点 void ConnectListNodes(ListNode* pre, ListNode* cur) { pre->next = cur; } // 遍历链表 void PrintList(ListNode* node) { while(node != nullptr) { cout << node->val << " "; node = node->next; } } int main(){ ListNode* pHead1 = CreatListNode(1); ListNode* p2 = CreatListNode(2); ListNode* p3 = CreatListNode(5); ListNode* pHead2 = CreatListNode(2); ListNode* p5 = CreatListNode(3); ListNode* p6 = CreatListNode(6); ConnectListNodes(pHead1, p2); ConnectListNodes(p2, p3); ConnectListNodes(pHead2, p5); ConnectListNodes(p5, p6); cout << "原链表1是:"; PrintList(pHead1); cout << endl; cout << "原链表2是:"; PrintList(pHead2); cout << endl; cout << "俩合并后是:"; ListNode* pNew = MergeList_Recu(pHead1, pHead2); PrintList(pNew); cout << endl; return 0; }
C
UTF-8
4,298
2.59375
3
[]
no_license
#include <xc.h> #include <stdio.h> #include "main.h" #include "configBits.h" #include "lcd.h" #include "constants.h" #include "macros.h" /* * Written by Ben Schmidel et al., October 4, 2010. * Copyright (c) 2008-2012 Pololu Corporation. For more information, see * * http://www.pololu.com * http://forum.pololu.com * http://www.pololu.com/docs/0J19 * * You may freely modify and share this code, as long as you keep this * notice intact (including the two links above). Licensed under the * Creative Commons BY-SA 3.0 license: * * http://creativecommons.org/licenses/by-sa/3.0/ * * Disclaimer: To the extent permitted by law, Pololu provides this work * without any warranty. It might be defective, in which case you agree * to be responsible for all resulting costs and damages. */ void calibrate(unsigned int * sensor_values) { int i, j; unsigned int calsensor_values[8]; unsigned int max_values[8]; unsigned int min_values[8]; for(j=0;j<10;j++) { read(calsensor_values); for(i=0;i<8;i++) { if(j == 0 || max_values[i] < calsensor_values[i]) max_values[i] = calsensor_values[i]; if(j == 0 || min_values[i] > calsensor_values[i]) min_values[i] = calsensor_values[i]; } } for(i=0;i<8;i++) { /* calibratedMaximum[i] = min_values[i]; calibratedMinimum[i] = max_values[i];*/ calibratedMaximum[i] = 1023; calibratedMinimum[i] = 512; } } // Returns values calibrated to a value between 0 and 1000, where // 0 corresponds to the minimum value read by calibrate() and 1000 // corresponds to the maximum value. Calibration values are // stored separately for each sensor, so that differences in the // sensors are accounted for automatically. void readCalibrated(unsigned int * sensor_values) { int i; read(sensor_values); for(i=0;i<8;i++) { unsigned int calmin,calmax; unsigned int denominator; calmax = calibratedMaximum[i]; calmin = calibratedMinimum[i]; denominator = calmax - calmin; signed int x = 0; if(denominator != 0) { x = (((signed long)sensor_values[i]) - calmin)*1000/denominator; } if(x < 0) { x = 0; } else if(x > 1000) { x = 1000; } sensor_values[i] = x; } } void read(unsigned int * sensor_values) { unsigned int off_values[8]; unsigned char i; EMITTER = 1; __delay_us(100); readValues(sensor_values); EMITTER = 0; } void readValues(unsigned int * sensor_values) { unsigned char i, j; for(i=0;i<8;i++) { sensor_values[i] = 0; } for(j=0;j<4;j++) { for(i=0;i<8;i++) { sensor_values[i] += ADCread(i); } } for (i=0;i<8;i++) { sensor_values[i] = sensor_values[i] / 4; } } // Operates the same as read calibrated, but also returns an // estimated position of the robot with respect to a line. The // estimate is made using a weighted average of the sensor indices // multiplied by 1000, so that a return value of 0 indicates that // the line is directly below sensor 0, a return value of 1000 // indicates that the line is directly below sensor 1, 2000 // indicates that it's below sensor 2000, etc. Intermediate // values indicate that the line is between two sensors. The // formula is: // // 0*value0 + 1000*value1 + 2000*value2 + ... // -------------------------------------------- // value0 + value1 + value2 + ... // // By default, this function assumes a dark line (high values) // surrounded by white (low values). If your line is light on // black, set the optional second argument white_line to true. In // this case, each sensor value will be replaced by (1000-value) // before the averaging. unsigned int readLine(unsigned int * sensor_values) { long avg, i; unsigned int sum; unsigned int lastValue; unsigned int val; readCalibrated(sensor_values); avg = 0; sum = 0; for(i=0;i<8;i++) { val = sensor_values[i]; if(val>50) { avg+=(long)(val) * (i*1000); sum += val; } } lastValue = avg/sum; return lastValue; }
Python
UTF-8
4,399
3.375
3
[]
no_license
""" Definisjon av bolske funksjoner""" from IPython.core.display import display, HTML import digtek.methods.html_karnaugh import digtek.methods.html_tabellmetoden import digtek.util as util import digtek.html import digtek.errors __all__ = ["BoolFunction","LambdaFunction","MintermFunction","MaxtermFunction", "table","karnaugh","tablemethod"] # Definerer hvilke variabler som brukes når en funksjon printes VARS = "xyzwabcdefghijklmnopqrstuvABCDEFGHIJKLMNOPQRSTUVWXYZ" # definerer alle standard funskjonsnavn som skal vises når det ikke er opgitt av bruker FUNCTION_NAMES = tuple(f"$F_{i}$" for i in range(100)) # En superklasse for alle typer bolske funksjoner class BoolFunction: def __init__(self,*args,**kwargs): self.variables = -1 raise digtek.errors.DigtekError("Cannot define function using class BoolFunction! Try Lambda/Minterm/Maxterm-Function instead!") def __eq__(self,other): if isinstance(other,BoolFunction): if self.variables != other.variables: return False for b in [util.number_to_binary(n,self.variables) for n in range(2**self.variables)]: if self(*b) != other(*b): return False return True return False def get_minterms(self): ans = [] for i in range(2**self.variables): n = util.number_to_binary(i,self.variables) if self(*n): ans.append(i) return ans def print(self,*args,**kwargs): return display(HTML(self.__str__(*args,**kwargs))) # denne koden er bare her slik at vs-code ikke blir sur def __call__(self): pass class LambdaFunction(BoolFunction): def __init__(self,func): self.variables = func.__code__.co_argcount self.function = func def __call__(self,*args): return self.function(*args) # Fordi det er vanskilig å konvertere en funskjon til en string vil # denne funskjonen returnere en string av den optimaliserte funskjonen # i stedet. Dette kan fikses ved å bruke moduler som 'inspect'..osv, men # løsningen blir lite elegant, tar tid å implementere. def __str__(self): raise digtek.errors.DigtekWarning("Cannot return string of LambdaFunction") # return self.__repr__() class MintermFunction(BoolFunction): def __init__(self,iterable,variables): self.iterable = set(iterable) self.variables = variables def __call__(self,*args): return 1 if util.binary_to_number(*args) in self.iterable else 0 def __str__(self,name="F",var=VARS): return digtek.html.termfunction(self.iterable,tuple(b for b in (util.number_to_binary(n,self.variables) for n in range(2**self.variables)) if self(*b)),var=var,name=name) class MaxtermFunction(BoolFunction): def __init__(self,iterable,variables): self.iterable = set(iterable) self.variables = variables def __call__(self,*args): return 0 if util.binary_to_number(*args) in self.iterable else 1 def __str__(self,name="F",var=VARS): return digtek.html.termfunction(self.iterable,tuple(b for b in (util.number_to_binary(n,self.variables) for n in range(2**self.variables)) if not self(*b)),var=var,name=name,minterm=False) def table(*args,function_names = FUNCTION_NAMES): variables = args[0].variables for func in args: if func.variables != variables: raise digtek.errors.DigtekError("Can only plot functions with equal number of variable inputs!") rows = [] bin_nums = ( util.number_to_binary(b,variables) for b in range(2**variables) ) for num in bin_nums: row = [] row.extend(num) for func in args: row.append(func(*num)) rows.append(row) digtek.html.table( rows , var = VARS[:variables],function_names=function_names[:len(args)]) def karnaugh(func,var=VARS): digtek.methods.html_karnaugh.run(func.variables, *(1 if func(*util.number_to_binary(i,func.variables)) else 0 for i in range(2**func.variables)), *var[:func.variables]) def tablemethod(func,var=VARS): digtek.methods.html_tabellmetoden.main( [var[i] for i in range(func.variables)], func.get_minterms())
PHP
UTF-8
7,484
2.859375
3
[]
no_license
<?php class Response{ private $content; private $actions; private $callback_id; private $user; private $action_ts; private $original; private $response; private $attachments; private $title; private $text; private $value; private $name; private $channel; private $imageUrl; private $uniqueId; private $shareMessage; public function run(){ $this->content= json_decode(file_get_contents('php://input')); $this->actions= $this->content["actions"]; $this->name= $this->actions[0]["name"]; $this->callback_id=$this->content["callback_id"]; $this->user=$this->content["user"]; $this->action_ts=$this->content["action_ts"]; $this->original=$this->content["original_message"]; $this->value= $this->actions[0]["selected_options"][0]["value"]; $this->attachments= $this->original["attachments"]; $this->title= $this->attachments[0]["title"]; $this->text= $this->attachments[0]["text"]; $this->channel= $this->content["channel"]; $this->imageUrl= $this->attachments[0]["imageUrl"]; $this->uniqueId= $this->attachments[0]["id"]; header("HTTP/1.1 200 OK"); if($this->name=== "decision"){ $this->respondDecision(); }else if($this->name=== "share"){ $this->respondShare(); } } private function respondDecision(){ /* 你可以在这写入数据库,你可以得到uniqueID,这个是你要的六位数字 */ if($this->value==="like"){ $this->response=array( "attachments"=>[array( "title"=>$this->title, "text"=> $this->text, "image_url"=>$this->imageUrl, "callback_id"=> $this->callback_id, "id"=>$this->uniqueId, "color"=> "#3AA3E3", "attachment_type"=> "default", "actions"=> [ array( "name"=>"decision", "text"=>"Like", "type"=>"button", "style"=>"primary", "value"=>"like" ), array( "name"=>"decision", "text"=>"Dislike", "type"=>"button", "value"=>"dislike" ), array( "name"=>"share", "text"=>"Who you want to share this news?", "type"=>"select", "data_source"=>"users" ) ] )] ); $this->_json($this->response); }else{ $this->response=array( "attachments"=>[array( "title"=>$this->title, "text"=> $this->text, "image_url"=>$this->imageUrl, "callback_id"=> $this->callback_id, "id"=>$this->uniqueId, "color"=> "#3AA3E3", "attachment_type"=> "default", "actions"=> [ array( "name"=>"decision", "text"=>"Like", "type"=>"button", "value"=>"like" ), array( "name"=>"decision", "text"=>"Dislike", "type"=>"button", "style"=>"primary", "value"=>"dislike" ), array( "name"=>"share", "text"=>"Who you want to share this news?", "type"=>"select", "data_source"=>"users" ) ] )] ); $this->_json($this->response); } } private function respondShare(){ /* 在这些数据库代码,存谁分享那条消息给谁 */ $this->response=array( $this->shareMessage= "This news has been shared from ".$this->user["name"]." to ".$this->value; "attachments"=>[array( "title"=>$this->title, "text"=> $this->text."\n".$this->shareMessage , "image_url"=>$this->imageUrl, "callback_id"=> $this->callback_id, "id"=>$this->uniqueId, "color"=> "#3AA3E3", "attachment_type"=> "default", "actions"=> [ array( "name"=>"decision", "text"=>"Like", "type"=>"button", "value"=>"like" ), array( "name"=>"decision", "text"=>"Dislike", "type"=>"button", "value"=>"dislike" ), array( "name"=>"share", "text"=>"Who you want to share this news?", "type"=>"select", "data_source"=>"users" ) ] )] ); $this->_json($this->response); } private function _json($array){ echo json_encode($array); } } $obj= new Response(); $obj->run(); ?>
Python
UTF-8
963
3.203125
3
[ "MIT" ]
permissive
import random class Solution: def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if nums is None or len(nums)==0: return nums nums = self.quickSort(nums,0,len(nums)-1) return nums[k-1] def partition(self,nums,p,q): ra = random.randint(p,q) nums[p],nums[ra] = nums[ra],nums[p] x = nums[p] i = p for j in range(p+1,q+1,1): if nums[j]>=x: #左边是nums[j]而不是nums[i] i+=1 nums[i],nums[j] = nums[j],nums[i] nums[p],nums[i] = nums[i],nums[p] return i def quickSort(self,nums,p,q): if p<=q: r = self.partition(nums,p,q) self.quickSort(nums,p,r-1) self.quickSort(nums,r+1,q) return nums list = [3,2,1,5,6,4] k = 2 s = Solution() print(s.findKthLargest(list,k))
C#
ISO-8859-7
2,459
2.859375
3
[]
no_license
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace Jasen.Framework.Reflection { /// <summary> /// /// </summary> public class ColumnPropertyCollection : IEnumerable<PropertyInfo> { private Dictionary<string, PropertyInfo> _columnProperties = new Dictionary<string, PropertyInfo>(); /// <summary> /// /// </summary> /// <param name="type"></param> public ColumnPropertyCollection(Type type) { this.GetConfiguration(type); } /// <summary> /// /// </summary> /// <param name="propertyName"></param> /// <returns></returns> public PropertyInfo this[string propertyName] { get { if (_columnProperties.ContainsKey(propertyName)) { return _columnProperties[propertyName]; } else { return null; } } } #region IEnumerable<ColumnAttribute> Members public IEnumerator<PropertyInfo> GetEnumerator() { foreach (PropertyInfo propertyInfo in _columnProperties.Values) { yield return propertyInfo; } } #endregion #region Custom Methods //public bool ContainsKey(string propertyName) //{ // return _columnProperties.ContainsKey(propertyName); //} public void GetConfiguration(Type type) { if (type == null) { return; } ColumnAttribute columnAttribute = null; foreach (PropertyInfo propertyInfo in type.GetProperties()) { columnAttribute = AttributeUtility.GetColumnAttribute(propertyInfo); if (columnAttribute != null) { if (!_columnProperties.ContainsKey(propertyInfo.Name)) { _columnProperties.Add(propertyInfo.Name, propertyInfo); } } } } #endregion #region IEnumerable Ա IEnumerator IEnumerable.GetEnumerator() { return _columnProperties.GetEnumerator(); } #endregion } }
Markdown
UTF-8
2,533
2.609375
3
[]
no_license
# Applied Data Science Project 3: Can you recognize the emotion from an image of a face? <img src="figs/CE.jpg" alt="Compound Emotions" width="500"/> (Image source: https://www.pnas.org/content/111/15/E1454) ### [Full Project Description](doc/project3_desc.md) Term: Spring 2020 + Group number: 6 + Team members + Lee, Sol + Ni, Jiayun + Petkun, Michael + Schmidle, Daniel + Zhang, Tianshu + Project summary: In this project, we developed multiple classification models to perform facial emotion recognition. Comparing with a baseline model we chose (Gradient Boosting Machine), our models have improved the test accuracy, computational cost, and storage size. The best model out of all models tested is SVM + PCA model, which is to be introduced and explained more thoroughly to the class during the presentation. **Contribution statement**: ([default](doc/a_note_on_contributions.md)) Daniel Schmidle, as a major contributor, involved in every stage of the project’s development and discussion. Daniel built individual base gbm model for project understanding, developed the PCA + SVM model as the advanced model, cross validated the advanced PCA+SVM model, and created/recorded the group’s project presentation. Michael Petkun, another major contributor, involved in every stage of the project’s development and discussion. Michael built the baseline model and compiled the Main.Rmd and Test_Day.Rmd files. Tianshu Zhang actively participated in all meetings, contributed inputs in the model selection process, tested models, and built a CNN Resnet-18 model (Neural Network model). Sol Lee organinzed recurring Zoom meetings, actively participated and contributed inputs in the model selection process, tested models, and built a SVM model. Sol edited Readme.md and organized the Github URL. Jiayun Ni actively participated in all meetings, contributed to the model selection process. Jiayun debugged and tested models, and established classification models by using knn with pca model as well as bagging models and bagging with pca models. All team members contributed to the GitHub repository. All team members approve our work presented in our GitHub repository including this contribution statement. Following [suggestions](http://nicercode.github.io/blog/2013-04-05-projects/) by [RICH FITZJOHN](http://nicercode.github.io/about/#Team) (@richfitz). This folder is orgarnized as follows. ``` proj/ ├── lib/ ├── data/ ├── doc/ ├── figs/ └── output/ ``` Please see each subfolder for a README file.
TypeScript
UTF-8
1,364
2.6875
3
[]
no_license
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'tipcalculator'; billAmount:number; numberOfPeople:number; selectedPercentage:number; percentages:any[]; customInput: number; constructor(){ this.billAmount = 0; this.numberOfPeople = 0; this.selectedPercentage = 5; this.percentages = [5,10,15,25,50]; } setPercentage(percentage:any){ this.selectedPercentage = percentage; } calculateTipPerPerson():number{ if(this.numberOfPeople == 0) return 0; const totalTip = (this.selectedPercentage) / 100 * this.billAmount; const tipPerPerson = totalTip / this.numberOfPeople; return parseFloat(tipPerPerson.toFixed(2)); } calculateTotalBillPerPerson():number{ if(this.numberOfPeople == 0) return 0; const billWithoutTip = this.billAmount / this.numberOfPeople; const tipPerPerson = this.calculateTipPerPerson(); const totalBillPerPerson = billWithoutTip + tipPerPerson; return parseFloat(totalBillPerPerson.toFixed(2)); } reset(){ this.billAmount = 0; this.numberOfPeople = 0; this.selectedPercentage = 5; this.customInput = null; } setCustomPercentage(){ this.selectedPercentage = this.customInput; } }
PHP
UTF-8
352
3.28125
3
[]
no_license
<?php class php{ public static function framework() { echo static::getClass()."</br>"; } public static function getClass() { return __CLASS__; } } class phpChild extends Php{ public static function getClass() { return __CLASS__; } } $obj = new php; echo $obj::framework(); $obj2 = new phpChild; echo $obj2::framework(); ?>
Java
UTF-8
296
2.359375
2
[]
no_license
#include <stdio.h> int main() { int n,i,temp,sum; scanf("%d", &n); temp=n; sum=0; while(temp>0) { int r=temp%10; int f=1; for(int i=1;i<=r;i++) { f=f*i; } sum=sum+f; temp=temp/10; } if(n==sum) { printf("Yes"); } else { printf("No"); } return 0; }
Python
UTF-8
296
3.109375
3
[ "MIT" ]
permissive
from pieces.piece import Piece class King(Piece): alliance = None position = None def __init__(self,alliance,position): self.alliance =alliance self.position = position def toString(self): return "K" if self.alliance == "Black" else "k"
Java
UTF-8
4,447
2.609375
3
[]
no_license
package com.diandian.dubbo.facade.common.constant; /** * 会员常量 * * @author x * @date 2018/9/12 16:13 */ public class MemberConstant { /** * @Author wubc * @Description // 启用 * @Date 11:22 2019/3/13 * @Param * @return **/ public static final Integer NORMAL = 0; /** * @Author wubc * @Description // 禁用 * @Date 11:22 2019/3/13 * @Param * @return **/ public static final Integer DISABLE = 1; /** * 兑换券订单类型(0 商家兑换;) */ public enum MemberExchangeType { /** * 商家兑换 */ MERCHANT_EXCHANGE(0, "兑换券充值"), MEMBER_STORED(1, "会员储值赠送"), MEMBER_INTEGRAL_EXCHANGE(2, "积分兑换"); private Integer value; private String label; MemberExchangeType(Integer value, String label) { this.value = value; this.label = label; } public Integer getValue() { return value; } public String getLabel() { return label; } } /** * 会员兑换状态 */ public enum MemberExchangeState { /** * 商家兑换 */ EXCHANGE_SUCCESS(0, "兑换成功"); private Integer value; private String label; MemberExchangeState(Integer value, String label) { this.value = value; this.label = label; } public Integer getValue() { return value; } public String getLabel() { return label; } } /** * 订单操作类型 */ public enum BillType { /** * 商家兑换 */ MEMBER_STORED(0, "会员储值"), MALL_EXCHANGE(2, "积分兑换"), COUPON_EXCHANGE(1, "兑换券充值"); private Integer value; private String label; BillType(Integer value, String label) { this.value = value; this.label = label; } public Integer getValue() { return value; } public String getLabel() { return label; } } /** * 订单状态 */ public enum BillState { /** * 商家兑换 */ BILL_CONTINUE(0, "进行中"), BILL_SUCCESS(1, "操作成功"); private Integer value; private String label; BillState(Integer value, String label) { this.value = value; this.label = label; } public Integer getValue() { return value; } public String getLabel() { return label; } } public enum ExchangeHistoryType { ISSUE(0, "发放"), EXPEND(1, "消耗"); /** * 值 */ private Integer value; /** * 描述 */ private String lable; ExchangeHistoryType(Integer value, String label) { this.value = value; this.lable = lable; } public Integer value() { return this.value; } public String getLable() { return this.lable; } } /** * 订单状态 */ public enum OrderState { /** * 商家兑换 */ ORDER_CREATE(0, "已创建"), ORDER_PAID_FREIGHT(1, "已付运费"), ORDER_PAID_COUPON(2, "已扣会员兑换券"), ORDER_PAID_AMOUNT(3, "已扣商户储备金"); private Integer value; private String label; OrderState(Integer value, String label) { this.value = value; this.label = label; } public Integer getValue() { return value; } public String getLabel() { return label; } } /** * 运费承担(0 会员, 1 商家) */ public enum AssumeFreight { MEMBER(0, "会员"), MERCHANT(1, "商家"); private Integer value; private String label; AssumeFreight(Integer value, String label) { this.value = value; this.label = label; } public Integer getValue() { return value; } public String getLabel() { return label; } } }
C#
UTF-8
3,983
2.75
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using LowPolyHnS.Inventory; using UnityEngine; namespace LowPolyHnS.Attributes { [Serializable] public class CharacterAttribute { public float BaseValue; protected bool NeedRecalculate = true; protected float LastBaseValue; protected float RecentCalculation; [SerializeField] public virtual float Value { get { if (NeedRecalculate || LastBaseValue != BaseValue) { LastBaseValue = BaseValue; RecentCalculation = CalculateFinalValue(); NeedRecalculate = false; } return RecentCalculation; } } protected readonly List<AttributeModifier> StatModifiersList; public readonly ReadOnlyCollection<AttributeModifier> StatModifiers; public CharacterAttribute() { StatModifiersList = new List<AttributeModifier>(); StatModifiers = StatModifiersList.AsReadOnly(); } public CharacterAttribute(float baseValue) : this() { BaseValue = baseValue; } public virtual void AddModifier(AttributeModifier mod) { NeedRecalculate = true; StatModifiersList.Add(mod); } public virtual bool RemoveModifier(Item item) { if (StatModifiersList.Remove(GetAttributeModifierFromItem(item))) { NeedRecalculate = true; return true; } return false; } public virtual bool RemoveAllModifiersFromSource(Item item) { int numRemovals = StatModifiersList.RemoveAll(mod => mod.Item == item); if (numRemovals <= 0) return false; NeedRecalculate = true; return true; } protected virtual int CompareModifierOrder(AttributeModifier attributeModifierA, AttributeModifier attributeModifierB) { if (attributeModifierA.Order < attributeModifierB.Order) { return -1; } return attributeModifierA.Order > attributeModifierB.Order ? 1 : 0; } protected virtual float CalculateFinalValue() { var finalValue = BaseValue; float sumPercentAdd = 0; StatModifiersList.Sort(CompareModifierOrder); for (var i = 0; i < StatModifiersList.Count; i++) { AttributeModifier mod = StatModifiersList[i]; switch (mod.Type) { case AttributeModifierType.Normal: { finalValue += mod.Value; break; } case AttributeModifierType.Percent: { sumPercentAdd += mod.Value; if (i + 1 >= StatModifiersList.Count || StatModifiersList[i + 1].Type != AttributeModifierType.Percent) { finalValue *= 1 + sumPercentAdd; sumPercentAdd = 0; } break; } case AttributeModifierType.PercentMultiply: { finalValue *= 1 + mod.Value; break; } default: throw new ArgumentOutOfRangeException(); } } return (float) Math.Round(finalValue, 4); } public AttributeModifier GetAttributeModifierFromItem(Item item) { return StatModifiers.FirstOrDefault(modifier => modifier.Item.uuid == item.uuid); } } }
Markdown
UTF-8
5,079
2.984375
3
[]
no_license
--- title: altTitle: SS64 Docs date: 2016-09-04 19:26:55 useGithubLayout: false --- <!-- #BeginLibraryItem "/Library/head_ps.lbi" --><!-- #EndLibraryItem --><h1>Get-Random</h1> <p>Get a random number, or select objects randomly from a collection.</p> <pre>Syntax Get-Random [-InputObject] <i>Object</i>[] [-Count <i>int</i>] [-SetSeed <i>int</i>] [<i>CommonParameters</i>] Get-Random [[-Maximum] <i>Object</i>] [-Minimum <i>Object</i>] [-SetSeed <i>int</i>] [<i>CommonParameters</i>] key -Count <i>int</i> Determines how many objects are returned. If the value of <i>Count</i> exceeds the number of objects in the collection, Get-Random returns all of the objects in random order. The default is 1. -InputObject<i>Object</i> A collection of objects. Get-Random gets randomly selected objects in random order from the collection. Enter the objects, a variable that contains the objects, or a command or expression that gets the objects. A collection of objects may also be piped to Get-Random. -Maximum <i>Object</i> A maximum value for the random number. Get-Random will return a value that is less than the maximum (not equal). Enter a 32-bit integer or a double-precision floating-point number, or an object that can be converted, such as a numeric string ("100"). The value of -Maximum must be greater than (not equal to) the value of -Minimum. If the value of -Maximum or -Minimum is a floating-point number, Get-Random will return a randomly selected floating-point number. If the value of Minimum is a double (a floating-point number), the default value of Maximum is Double.MaxValue. Otherwise, the default value is Int32.MaxValue (2,147,483,647) -Minimum <i>Object</i> A minimum value for the random number. Enter a 32-bit integer or a double-precision floating-point number, or an object that can be converted, such as a numeric string ("100"). The default value is 0 (zero). The value of Minimum must be less than (not equal to) the value of Maximum. If the value of -Maximum or -Minimum is a floating-point number, Get-Random will return a randomly selected floating-point number. -SetSeed <i>int</i> A seed value for the random number generator. This seed value is used for the current command and for all subsequent Get-Random commands in the current session until SetSeed is used again The seed cannot be reset back to its default, clock-based value.<br> <br> -SetSeed is not required. By default, Get-Random uses the system clock to generate a seed value. Using SetSeed will result in non-random behavior, it is typically used to reproduce behavior, such as when debugging or analyzing a script. <a href="common.html">CommonParameters</a>: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable, -OutBuffer -OutVariable.</pre> <p> Get-Random gets a randomly selected number.<br> If a collection of objects is submitted to Get-Random, then one or more randomly selected objects from the collection will be returned.</p> <p>An alternative approach is to create a random object:</p> <p class="code">$objRand = <a href="new-object.html">new-object</a> random<br> $num = $objRand.next(1,500)</p> <p><b>Examples</b></p> <p>Get a random integer between 0 (zero) and Int32.MaxValue:</p> <pre>PS C:&gt; get-random</pre> <p>Get a random integer between 0 (zero) and 99:</p> <pre>PS C:&gt; get-random -maximum 100</pre> <p>Get a random integer between -100 and 99:</p> <pre>PS C:&gt; get-random -minimum -100 -maximum 100</pre> <p>Get four randomly selected numbers in random order from an array:</p> <pre>PS C:&gt; get-random -input 1, 2, 3, 5, 8, 13 -count 4</pre> <p>Get a randomly selected sample of 25 files from the C: drive of the local computer:</p> <pre>PS C:&gt; $files = dir -path c:\* -recurse<br>PS C:&gt; $sample = $files | get-random -count 25</pre> <p class="quote"><i>“Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin” - John von Neumann</i></p> <p><b>Related:</b><br> <br> <a href="get-unique.html">Get-Unique</a> - Return the unique items from a sorted list.<br> <a href="../nt/syntax-random.html">Random Numbers</a> in CMD or .js </p><!-- #BeginLibraryItem "/Library/foot_ps.lbi" --><p> <!-- PowerShell300 --> <ins class="adsbygoogle" style="display:inline-block;width:300px;height:250px" data-ad-client="ca-pub-6140977852749469" data-ad-slot="6253539900"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script></p> <hr> <div id="bl" class="footer"><a href="get-random.html#"><img src="../images/top.png" width="30" height="22" alt="Back to the Top"></a></div> <div id="br" class="footer, tagline">© Copyright <a href="http://ss64.com/">SS64.com</a> 1999-2015<br> Some rights reserved</div><!-- #EndLibraryItem -->
TypeScript
UTF-8
2,701
2.53125
3
[ "MIT" ]
permissive
import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, UseGuards, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { ApiOperation, ApiTags, ApiBearerAuth } from '@nestjs/swagger'; import { GroupDto } from './dto/groups.dto'; import { GroupsService } from './groups.service'; @ApiTags('Permissions') @ApiBearerAuth() @Controller('permissions') export class PermissionsController { constructor(private readonly groupsService: GroupsService) { } @Get('groups') @UseGuards(AuthGuard('jwt')) @ApiOperation({ summary: 'Returns all the groups.' }) async getAllGroups() { const groups = await this.groupsService.findAllGroups(); if (groups.length <= 0) { throw new HttpException({ status: HttpStatus.OK, error: 'No data available' }, HttpStatus.OK); } const response = []; groups.forEach(group => { let temp = { groupId: group.groupId, name: group.name, description: group.description }; response.push(temp); }) return response; } @Post('groups') @UseGuards(AuthGuard('jwt')) @ApiOperation({ summary: 'Create a group.' }) @HttpCode(HttpStatus.CREATED) async createGroup(@Body() group: GroupDto) { try { await this.groupsService.createGroup(group); } catch (error) { throw new HttpException(error.message, HttpStatus.BAD_REQUEST); } } @Put('groups/:groupSlug') @UseGuards(AuthGuard('jwt')) @ApiOperation({ summary: 'Update a group details.' }) @HttpCode(HttpStatus.ACCEPTED) async updateGroup(@Param() params, @Body() body: GroupDto) { try { const groupId = parseInt(params.groupSlug); return await this.groupsService.updateGroup(groupId, body); } catch (error) { throw new HttpException(error.message, HttpStatus.BAD_REQUEST); } } @Delete('groups/:groupSlug') @UseGuards(AuthGuard('jwt')) @ApiOperation({ summary: 'Delete a group.' }) @HttpCode(204) async deleteGroup(@Param() params) { try { const groupId = parseInt(params.groupSlug); if (groupId <= 0) { throw new HttpException('Invalid groupId.', HttpStatus.BAD_REQUEST); } await this.groupsService.deleteById(groupId); } catch (error) { throw new HttpException(error.message, error.status || HttpStatus.INTERNAL_SERVER_ERROR); } } }
JavaScript
UTF-8
600
2.71875
3
[]
no_license
new Vue({ el: '#exercise', data: { value: '' }, methods: { clickAlert: function(){ alert("I\'m clicked!") }, //this function displays e.target.value until a following keydown... // by default wait on key down for 1000 then will show; can circumvent it, but also can do it by keyup keyDownBasic: function(e) { this.value = e.target.value }, keyDownInt: function(e){ this.value = e.target.value } } });
Java
UTF-8
2,243
2.234375
2
[ "Apache-2.0" ]
permissive
/***************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ****************************************************************/ package org.apache.cayenne.modeler.utility; import de.jensd.fx.glyphs.GlyphIcons; import de.jensd.fx.glyphs.GlyphsDude; import javafx.scene.control.TreeItem; @Deprecated // FIXME: I think this whole class can go away soon. public class TreeViewUtilities { public static final String TREE_ICON_SIZE = "16px"; public static TreeItem<Object> addNode(final TreeItem<Object> item, final TreeItem<Object> parent) { return addNode(item, parent, true, null); } public static TreeItem<Object> addNode(final TreeItem<Object> item, final TreeItem<Object> parent, final boolean expanded) { return addNode(item, parent, expanded, null); } public static TreeItem<Object> addNode(final TreeItem<Object> item, final TreeItem<Object> parent, final GlyphIcons icon) { return addNode(item, parent, true, icon); } public static TreeItem<Object> addNode(final TreeItem<Object> item, final TreeItem<Object> parent, final boolean expanded, final GlyphIcons icon) { // TreeItem<String> item = new TreeItem<String>(title); item.setExpanded(expanded); if (icon != null) item.setGraphic(GlyphsDude.createIcon(icon, TREE_ICON_SIZE)); parent.getChildren().add(item); return item; } }
Shell
UTF-8
329
3.015625
3
[]
no_license
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" while read p do echo -n "Exporting to " echo $p cp -apRf $DIR/src/classes/* $p/src/classes cp -apRf $DIR/src/staticresources/* $p/src/staticresources cp -apRf $DIR/src/pages/* $p/src/pages cp -apRf $DIR/src/components/* $p/src/components done <PROJECTPATHS
JavaScript
UTF-8
123
3.40625
3
[ "MIT" ]
permissive
// Prints numbers from 0 to 9 var countNumbers = function(){ for(var i = 0; i < 10; i++){ console.log(`${i}`) } }
Markdown
UTF-8
1,481
3.140625
3
[]
no_license
# clox A bytecode virtual machine for the Lox language Based off the book, Crafting Interpreters by Bob Nystrom, clox is a bytecode virtual machine for the Lox language. ### About Lox (the language) Lox is a programming language used in the book for the main purpose of introducing compilers and interpreters to novices. Lox is a fully-fledged programming language in the OOP vein of languages. Lox is dynamically typed (think JavaScript and Python), not statically typed (think Java). Being an OOP language, Lox supports classes, which can contain state and behaviour in the form of fields and methods respectively. Lox classes can also support constructors/initializers. Besides this, Lox supports all other typical language constructs, including logical operators, if-else blocks, while and for loops, and first-class functions. Without dumping the entire documentation of Lox here, the complete syntax and lexical grammar of the Lox language written in Backus-Naur form (BNF) can be found [here](https://craftinginterpreters.com/appendix-i.html). ### What's this? clox is the sequel to jlox, a tree-walk interpreter for the Lox language written in Java. You can take a look at jlox [here](https://github.com/Silvernitro/jlox). Following the book's progression, jlox is but one half of the Lox journey. jlox is **painfully** slow. As such, the next step is *clox*, a bytecode compiler written in C. I'll also go along with the book and write a VM to execute the bytecode on.
Java
UTF-8
785
2.3125
2
[ "MIT" ]
permissive
package com.cn.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import com.cn.pojo.OTDetail; import com.cn.utils.DbUtils; public class OTDetailDao { public int addOTDetail(OTDetail oTDetail){ Connection conn=null; PreparedStatement stat=null; try { conn=DbUtils.getConnection(); String sql="insert into OT_Detail(odID,touristID) values(?,?)"; stat=conn.prepareStatement(sql); stat.setString(1, oTDetail.getOdID()); stat.setString(2, oTDetail.getTouristID()); return stat.executeUpdate(); }catch (SQLException e) { e.printStackTrace(); }finally{ try { DbUtils.close(null, stat, conn); } catch (SQLException e) { e.printStackTrace(); } } return 0; } }
Shell
UTF-8
2,768
2.890625
3
[ "Apache-2.0" ]
permissive
#! /bin/bash # $1 - R1 fastq file export PATH=/ifs/work/bergerm1/Innovation/software/metagenomics/kraken-0.10.5-beta:/ifs/work/bergerm1/Innovation/software/metagenomics/KronaTools-2.6.1/bin:/opt/common/CentOS_6/gcc/gcc-4.9.3/bin:/ifs/work/bergerm1/Innovation/software/metagenomics/metaphlan2:/opt/common/CentOS_6/perl/perl-5.22.0/bin:/opt/common/CentOS_6/bowtie2/bowtie2-2.2.4:/opt/common/CentOS_6/python/python-2.7.8/bin:/opt/common/CentOS_6/bedtools/bedtools-2.17.0/:/opt/common/CentOS_6/java/jdk1.8.0_31/bin:/opt/common/CentOS_6/samtools/samtools-1.2:/common/lsf/9.1/linux2.6-glibc2.3-x86_64/etc:/common/lsf/9.1/linux2.6-glibc2.3-x86_64/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:$PATH export LD_LIBRARY_PATH=/opt/common/CentOS_6/gcc/gcc-4.9.3/lib64/:/common/lsf/9.1/linux2.6-glibc2.3-x86_64/lib:/common/lsf/9.1/linux2.6-glibc2.3-x86_64/lib:$LD_LIBRARY_PATH mpa_dir=/ifs/work/bergerm1/Innovation/software/metagenomics/metaphlan2 minikrakenDB=/ifs/work/bergerm1/Innovation/software/metagenomics/kraken-0.10.5-beta/minikraken-db-20141208 fastq1=$1 sampleName=`basename $fastq1` sampleName=${sampleName/_IGO_*/} fastq2=${fastq1/_R1_/_R2_} outFile=`basename $fastq1` outFile="${sampleName}_profiled_metagenome.txt" bowtie2outFile="${sampleName}_bowtie2.txt" echo -e "$fastq1 $fastq2 $outFile $bowtie2outFile " # run metaphlan2 #metaphlan2.py $fastq1,$fastq2 --bowtie2out $bowtie2outFile --mpa_pkl ${mpa_dir}/db_v20/mpa_v20_m200.pkl --bowtie2db ${mpa_dir}/db_v20/mpa_v20_m200 --input_type fastq --bt2_ps sensitive-local --min_alignment_len 70 > $outFile #create Krona Plots #${mpa_dir}/utils/metaphlan2krona.py -p $outFile -k krona/$sampleName.krona #ktImportText -o krona/$sampleName.html -n Metagenome krona/$sampleName.krona,$sampleName # run Kraken kraken --fastq-input --gzip-compressed --paired --db $minikrakenDB $fastq1 $fastq2 > $sampleName.kraken kraken-translate --db $minikrakenDB $sampleName.kraken > $sampleName.kraken.labels kraken-report --db $minikrakenDB $sampleName.kraken > $sampleName.kraken.report cat $sampleName.kraken.report | awk '$3>=5' > kraken-short/$sampleName.short.txt echo -e "Innovation Lab Kraken Run" > $sampleName.t echo -e "Sample: $sampleName" >> $sampleName.t printf "PercentReads\t#CladeReads\t#TaxonReads\tRank\tNCBI-ID\tName\n" >> $sampleName.t cat $sampleName.t kraken-short/$sampleName.short.txt > $sampleName.t1 mv $sampleName.t1 kraken-short/$sampleName.short.txt rm $sampleName.t kraken-mpa-report --db $minikrakenDB $sampleName.kraken > $sampleName.kraken.mpa #create Krona Plots ${mpa_dir}/utils/metaphlan2krona.py -p $sampleName.kraken.mpa -k kraken-krona/$sampleName.krona ktImportText -o kraken-krona/$sampleName.html -n Metagenome kraken-krona/$sampleName.krona,$sampleName #
Java
UTF-8
1,063
2.125
2
[]
no_license
/** * JavaCCRootNodeView.java * * @date: Oct 12, 2011 * @author: Xiaoyu Guo * This file is part of the Teaching Machine project. */ package visreed.extension.javaCC.view; import higraph.view.HigraphView; import java.awt.Graphics2D; import tm.backtrack.BTTimeManager; import visreed.model.VisreedEdge; import visreed.model.VisreedEdgeLabel; import visreed.model.VisreedHigraph; import visreed.model.VisreedNode; import visreed.model.VisreedPayload; import visreed.model.VisreedSubgraph; import visreed.model.VisreedWholeGraph; import visreed.view.AlternationNodeView; /** * @author Xiaoyu Guo * */ public class JavaCCRootNodeView extends AlternationNodeView { /** * @param v * @param node * @param timeMan */ public JavaCCRootNodeView( HigraphView<VisreedPayload, VisreedEdgeLabel, VisreedHigraph, VisreedWholeGraph, VisreedSubgraph, VisreedNode, VisreedEdge> v, VisreedNode node, BTTimeManager timeMan) { super(v, node, timeMan); } @Override protected void drawNode(Graphics2D screen) { } }
C#
UTF-8
355
2.828125
3
[]
no_license
Thread.MemoryBarrier(); // read barrier var list = CommandList; if (list != null) { var next = list.Next; if (Interlocked.CompareExchange(ref CommandList, next, list) == list) { // execute code on 'list'. } else { // something changed. Try again. } }
Java
UTF-8
1,134
3.40625
3
[]
no_license
package com.bizleap.training.tutorial32; public class Fruit { private String name; private double price; private double basePrice; private double weight; public Fruit() { } public Fruit(String name) { this.name = name; } public Fruit(String name, double price) { this.name = name; this.price = price; this.basePrice = price; } public Fruit(String name, double price, double weight) { this.name = name; this.price = price; this.basePrice = price; this.weight = weight; } public double getBasePrice() { return basePrice; } public void setBasePrice(double basePrice) { this.basePrice = basePrice; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } @Override public String toString() { return new StringBuffer().append("Fruit name: " + name ).append( ", $ per pound: " + price ).toString(); } }
Python
UTF-8
3,662
3.09375
3
[]
no_license
from django.shortcuts import render, redirect import random # index function initiates the gold count, activity log, and renders our html file def index(request): if "gold" not in request.session: request.session["gold"] = 0 request.session["history"] = [] return render(request, "index.html") # process_gold function calculates how much gold is earned # Additionally, it determines the color of our activity log def process_money(request): # Each buttons in html are named accordingly. # We can find which button was pressed by looking at POST request. earned_gold = 0 if "farm" in request.POST: request.session['count'] +=1 earned_gold = random.randint(10,20) request.session["gold"] += earned_gold elif "cave" in request.POST: request.session['count'] +=1 earned_gold = random.randint(5,10) request.session["gold"] += earned_gold elif "house" in request.POST: request.session['count'] +=1 earned_gold = random.randint(2,5) request.session["gold"] += earned_gold # Extra if statements to check if the payout is positive, negative, or 0 elif "casino" in request.POST: request.session['count'] +=1 earned_gold = random.randint(-50,50) request.session["gold"] += earned_gold request.session["history"].append(earned_gold) # to set for the case when the player didn't yet clicked on "confirm winning condition" if "player_desired_gold" not in request.session: request.session["player_desired_gold"] = 0 if "num_of_move" not in request.session: request.session["num_of_move"] = 0 if request.session['count'] == int(request.session["num_of_move"]) and request.session["gold"] >= int(request.session["player_desired_gold"]): request.session["win_game"] = "True" return redirect("/") if request.session['count'] == int(request.session["num_of_move"]) and request.session["gold"] < int(request.session["player_desired_gold"]): request.session["win_game"] = "False" return redirect("/") print('request.session["win_game"]: ',request.session["win_game"],", request.session['count']: ",request.session['count'],'; request.session["num_of_move"]: ',request.session["num_of_move"]) print('request.session["player_desired_gold"]:',request.session["player_desired_gold"],'; request.session["gold"]: ',request.session["gold"]) return redirect("/") def reset(request): request.session.clear() return redirect("/") def set_condition(request): request.session.clear() # to clear history of desired gold before each new game request.session["win_game"] = "Unknown" request.session['count'] = 0 # to reset the count before each new game request.session["gold"] = 0 # to reset the amount of gold earn before each new game request.session["history"] = [] # to reset the history log before each new game # if the player clicked on "confirm winning condition" without giving any input #then set winning condition = 0; if "player_desired_gold" not in request.POST: request.session["player_desired_gold"] = 0 if "num_of_move" not in request.POST: request.session["num_of_move"] = 0 # set winning condition to be what the player set request.session["num_of_move"] = request.POST["num_of_move"] request.session["player_desired_gold"] = request.POST["desired_gold"] print('request.session["win_game"]: ',request.session["win_game"],'; request.session["count"]:',request.session['count']) return redirect("/")
Python
UTF-8
201
3.0625
3
[]
no_license
from time import sleep import emoji print('*='*15) print(' CONTAGEM REGRESSIVA ') print('*='*15) for c in range(10,0,-1): print(c) sleep(1) print('FELIZ ANO VELHO KCT ') print(emoji.emojize(' :collision:'))
Java
UTF-8
3,232
2.515625
3
[]
no_license
package taskcom.android.manish.searchonrecyclerview.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import java.util.ArrayList; import taskcom.android.manish.searchonrecyclerview.R; import taskcom.android.manish.searchonrecyclerview.adapter.StudentListRecyclerAdapter; import taskcom.android.manish.searchonrecyclerview.model.Student; /** * Created by Manish Kumar on 10/14/2018 */ public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private StudentListRecyclerAdapter adapter; private EditText etSearch; private ArrayList<Student> studentArrayList; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); studentArrayList = getStudentList(); adapter = new StudentListRecyclerAdapter(studentArrayList, this); recyclerView.setAdapter(adapter); etSearch = findViewById(R.id.et_search); etSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { String studentToSearch = s.toString(); findMatchedStudent(studentToSearch); } }); } private void findMatchedStudent(String studentToSearch) { ArrayList<Student> matchedStudentList = new ArrayList<>(); for (Student student : studentArrayList) { if (student.getName().toLowerCase().contains(studentToSearch.toLowerCase())) { matchedStudentList.add(student); } } adapter.modifyList(matchedStudentList); } private ArrayList<Student> getStudentList() { ArrayList<Student> studentArrayList = new ArrayList<>(); studentArrayList.add(new Student("Manish", 1001, "CSE")); studentArrayList.add(new Student("Rahul", 1002, "ME")); studentArrayList.add(new Student("Rakesh", 1003, "EEE")); studentArrayList.add(new Student("Harry", 1004, "ME")); studentArrayList.add(new Student("Vikash", 1005, "ME")); studentArrayList.add(new Student("Pranav", 1006, "EEE")); studentArrayList.add(new Student("Deepak", 1007, "ME")); studentArrayList.add(new Student("Viru", 1008, "IT")); studentArrayList.add(new Student("Gopal", 1009, "IT")); return studentArrayList; } }
Java
UTF-8
16,057
1.773438
2
[]
no_license
package com.snapstory.util; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.annotation.SuppressLint; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import com.snapstory.R; public class DataProvider extends ContentProvider { @SuppressLint("SdCardPath") private static String DB_PATH = "/data/data/com.snapstory/databases/"; private static final UriMatcher uriMatcher; public static final Uri PROJECT_URI = Uri.parse("content://com.snapstory.util.DataProvider/projecturi"); public static final Uri STORY_URI = Uri.parse("content://com.snapstory.util.DataProvider/storyuri"); public static final Uri CHAPTER_URI = Uri.parse("content://com.snapstory.util.DataProvider/chapteruri"); public static final Uri QUESTION_URI = Uri.parse("content://com.snapstory.util.DataProvider/questionuri"); public static final Uri ANSWER_URI = Uri.parse("content://com.snapstory.util.DataProvider/answeruri"); public static final String DATABASE_NAME = "snapstory_db"; private static final int VERSION_NAME = 1; public static SQLiteDatabase myDataBase; public static final String TBL_PROJECT = "project"; public static final String TBL_STORY = "story"; public static final String TBL_CHAPTER = "chapter"; public static final String TBL_QUESTION = "question"; public static final String TBL_ANSWER = "answer"; //Common public static final String ID = "_id"; public static final String NAME = "name"; public static final String IMAGE_URL = "image_url"; public static final String PROJECT_ID = "project_id"; //project table public static final String DESCRIPTION = "description"; public static final String ORGANIZATION_ID = "organization_id"; public static final String CITY = "city"; public static final String LOCATION = "location"; //story table public static final String STORY_UUID = "story_uuid"; public static final String GENDER = "gender"; public static final String IMAGE = "image"; public static final String BIRTH_DATE = "birth_date"; public static final String SIGNATURE = "signature"; public static final String REPORT_TYPE = "report_type"; public static final String REPORT_TEMPLATE_ID = "report_template_id"; //chapter table public static final String STORY_ID = "story_id"; public static final String CHAPTER_UUID = "chapter_uuid"; public static final String SYNCED = "synced"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String RECORDED_AT = "recordedAt"; //question table public static final String QUESTION = "question"; public static final String QUESTION_TYPE = "question_type"; public static final String CHOICES = "choices"; public static final String TYPE = "type"; //answer table public static final String CHAPTER_ID = "chapter_id"; public static final String ANSWER = "answer"; public static final String ANSWER_UUID = "answer_uuid"; public static final String QUESTION_ID = "question_id"; private static final int GETALLPROJECT = 1; private static final int GETPROJECTBYID = 2; private static final int GETALLSTORY = 3; private static final int GETSTORYBYID = 4; private static final int GETALLCHAPTER = 5; private static final int GETCHAPTERBYID = 6; private static final int GETALLQUESTION = 7; private static final int GETQUESTIONBYID = 8; private static final int GETALLANSWER = 9; private static final int GETANSWERBYID = 10; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI("com.snapstory.util.DataProvider", "projecturi", GETALLPROJECT); uriMatcher.addURI("com.snapstory.util.DataProvider", "projecturi/#", GETPROJECTBYID); uriMatcher.addURI("com.snapstory.util.DataProvider", "storyuri", GETALLSTORY); uriMatcher.addURI("com.snapstory.util.DataProvider", "storyuri/#", GETSTORYBYID); uriMatcher.addURI("com.snapstory.util.DataProvider", "chapteruri", GETALLCHAPTER); uriMatcher.addURI("com.snapstory.util.DataProvider", "chapteruri/#", GETCHAPTERBYID); uriMatcher.addURI("com.snapstory.util.DataProvider", "questionuri", GETALLQUESTION); uriMatcher.addURI("com.snapstory.util.DataProvider", "questionuri/#", GETQUESTIONBYID); uriMatcher.addURI("com.snapstory.util.DataProvider", "answeruri", GETALLANSWER); uriMatcher.addURI("com.snapstory.util.DataProvider", "answeruri/#", GETANSWERBYID); } @Override public boolean onCreate() { MyDataBaseHelper myDataHelper = new MyDataBaseHelper(getContext(), DATABASE_NAME, null, VERSION_NAME); myDataHelper.createDataBase(); myDataBase = myDataHelper.getWritableDatabase(); return myDataBase != null ? true : false; } @Override public String getType(Uri paramUri) { switch (uriMatcher.match(paramUri)) { case GETALLPROJECT: case GETALLSTORY: case GETALLCHAPTER: case GETALLQUESTION: case GETALLANSWER: return "vnd.android.cursor.dir/vnd.test.dataturi"; case GETPROJECTBYID: case GETSTORYBYID: case GETCHAPTERBYID: case GETQUESTIONBYID: case GETANSWERBYID: return "vnd.android.cursor.item/vnd.test.datauri"; default: throw new IllegalArgumentException("Invalid URI : " + paramUri); } } @Override public Uri insert(Uri paramUri, ContentValues paramContentValues) { long rowId = -1; switch (uriMatcher.match(paramUri)) { case GETALLPROJECT: rowId = myDataBase.insert(TBL_PROJECT, "projecturi", paramContentValues); if (rowId > 0) { Uri uri = ContentUris.withAppendedId(PROJECT_URI, rowId); getContext().getContentResolver().notifyChange(uri, null); return uri; } case GETALLSTORY: rowId = myDataBase.insert(TBL_STORY, "storyuri", paramContentValues); if (rowId > 0) { Uri uri = ContentUris.withAppendedId(STORY_URI, rowId); getContext().getContentResolver().notifyChange(uri, null); return uri; } case GETALLCHAPTER: rowId = myDataBase.insert(TBL_CHAPTER, "chapteruri", paramContentValues); if (rowId > 0) { Uri uri = ContentUris.withAppendedId(CHAPTER_URI, rowId); getContext().getContentResolver().notifyChange(uri, null); return uri; } case GETALLQUESTION: rowId = myDataBase.insert(TBL_QUESTION, "questionuri", paramContentValues); if (rowId > 0) { Uri uri = ContentUris.withAppendedId(QUESTION_URI, rowId); getContext().getContentResolver().notifyChange(uri, null); return uri; } case GETALLANSWER: rowId = myDataBase.insert(TBL_ANSWER, "answeruri", paramContentValues); if (rowId > 0) { Uri uri = ContentUris.withAppendedId(ANSWER_URI, rowId); getContext().getContentResolver().notifyChange(uri, null); return uri; } } throw new IllegalArgumentException("Invalid URI : " + paramUri); } @Override public Cursor query(Uri paramUri, String[] projection, String selection, String[] selectionArgs, String sort) { SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); switch (uriMatcher.match(paramUri)) { case GETALLPROJECT: queryBuilder.setTables(TBL_PROJECT); break; case GETPROJECTBYID: queryBuilder.setTables(TBL_PROJECT); queryBuilder.appendWhere(ID + "=" + paramUri.getPathSegments().get(1)); break; case GETALLSTORY: queryBuilder.setTables(TBL_STORY); break; case GETSTORYBYID: queryBuilder.setTables(TBL_STORY); queryBuilder.appendWhere(ID + "=" + paramUri.getPathSegments().get(1)); break; case GETALLCHAPTER: queryBuilder.setTables(TBL_CHAPTER); break; case GETCHAPTERBYID: queryBuilder.setTables(TBL_CHAPTER); queryBuilder.appendWhere(ID + "=" + paramUri.getPathSegments().get(1)); break; case GETALLQUESTION: queryBuilder.setTables(TBL_QUESTION); break; case GETQUESTIONBYID: queryBuilder.setTables(TBL_QUESTION); queryBuilder.appendWhere(ID + "=" + paramUri.getPathSegments().get(1)); break; case GETALLANSWER: queryBuilder.setTables(TBL_ANSWER); break; case GETANSWERBYID: queryBuilder.setTables(TBL_ANSWER); queryBuilder.appendWhere(ID + "=" + paramUri.getPathSegments().get(1)); break; default: break; } Cursor c = queryBuilder.query(myDataBase, projection, selection, selectionArgs, null, null, sort); c.setNotificationUri(getContext().getContentResolver(), paramUri); return c; } @Override public int update(Uri paramUri, ContentValues paramContentValues, String where, String[] whereArgs) { int count = 0; String segment; switch (uriMatcher.match(paramUri)) { case GETALLPROJECT: count = myDataBase.update(TBL_PROJECT, paramContentValues, where, whereArgs); break; case GETPROJECTBYID: segment = paramUri.getPathSegments().get(1); count = myDataBase.update(TBL_PROJECT, paramContentValues, ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""), whereArgs); break; case GETALLSTORY: count = myDataBase.update(TBL_STORY, paramContentValues, where, whereArgs); break; case GETSTORYBYID: segment = paramUri.getPathSegments().get(1); count = myDataBase.update(TBL_STORY, paramContentValues, ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""), whereArgs); break; case GETALLCHAPTER: count = myDataBase.update(TBL_CHAPTER, paramContentValues, where, whereArgs); break; case GETCHAPTERBYID: segment = paramUri.getPathSegments().get(1); count = myDataBase.update(TBL_CHAPTER, paramContentValues, ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""), whereArgs); break; case GETALLQUESTION: count = myDataBase.update(TBL_QUESTION, paramContentValues, where, whereArgs); break; case GETQUESTIONBYID: segment = paramUri.getPathSegments().get(1); count = myDataBase.update(TBL_QUESTION, paramContentValues, ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""), whereArgs); break; case GETALLANSWER: count = myDataBase.update(TBL_ANSWER, paramContentValues, where, whereArgs); break; case GETANSWERBYID: segment = paramUri.getPathSegments().get(1); count = myDataBase.update(TBL_ANSWER, paramContentValues, ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""), whereArgs); break; default: throw new IllegalArgumentException("Invalid URI:" + paramUri); } getContext().getContentResolver().notifyChange(paramUri, null); return count; } @Override public int delete(Uri paramUri, String where, String[] whereArgs) { int count = 0; String segment; switch (uriMatcher.match(paramUri)) { case GETALLPROJECT: count = myDataBase.delete(TBL_PROJECT, where, whereArgs); break; case GETPROJECTBYID: segment = paramUri.getPathSegments().get(1); count = myDataBase.delete(TBL_PROJECT, ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""), whereArgs); break; case GETALLSTORY: count = myDataBase.delete(TBL_STORY, where, whereArgs); break; case GETSTORYBYID: segment = paramUri.getPathSegments().get(1); count = myDataBase.delete(TBL_STORY, ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""), whereArgs); break; case GETALLCHAPTER: count = myDataBase.delete(TBL_CHAPTER, where, whereArgs); break; case GETCHAPTERBYID: segment = paramUri.getPathSegments().get(1); count = myDataBase.delete(TBL_CHAPTER, ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""), whereArgs); break; case GETALLQUESTION: count = myDataBase.delete(TBL_QUESTION, where, whereArgs); break; case GETQUESTIONBYID: segment = paramUri.getPathSegments().get(1); count = myDataBase.delete(TBL_QUESTION, ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""), whereArgs); break; case GETALLANSWER: count = myDataBase.delete(TBL_ANSWER, where, whereArgs); break; case GETANSWERBYID: segment = paramUri.getPathSegments().get(1); count = myDataBase.delete(TBL_ANSWER, ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""), whereArgs); break; default: throw new IllegalArgumentException("Invalid URI : " + paramUri); } getContext().getContentResolver().notifyChange(paramUri, null); return count; } private class MyDataBaseHelper extends SQLiteOpenHelper { private Context mContext; public MyDataBaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); mContext = context; } @Override public void onCreate(SQLiteDatabase paramSQLiteDatabase) { } @Override public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int oldVersion, int newVersion) { try { copyDataBaseFiles(); // getCountryData(paramSQLiteDatabase); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void createDataBase() { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist } else { // By calling this method and empty database will be created // into // the default system path // of your application so we are gonna be able to overwrite that // database with our database. try { this.getReadableDatabase(); copyDataBaseFiles(); // getCountryData(dataBase); } catch (IOException e) { Log.e("Exceptiopn", e.getMessage(), e); } } } /** * Check if the database already exist to avoid re-copying the file each * time you open the application. * * @return true if it exists, false if it doesn't */ private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH + DATABASE_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); } catch (SQLiteException e) { // database does't exist yet. } if (checkDB != null) { checkDB.close(); } return checkDB != null ? true : false; } /** * Copies your database from your local assets-folder to the just * created empty database in the system folder, from where it can be * accessed and handled. This is done by transfering bytestream. * */ private void copyDataBaseFiles() throws IOException { InputStream databaseInput = null; String outFileName = DB_PATH + DATABASE_NAME; OutputStream databaseOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int length; int db[] = { R.raw.snapstory_db }; for (int i = 0; i < db.length; i++) { databaseInput = mContext.getResources().openRawResource(db[i]); while ((length = databaseInput.read(buffer)) > 0) { databaseOutput.write(buffer, 0, length); databaseOutput.flush(); } databaseInput.close(); } databaseOutput.flush(); databaseOutput.close(); } } }
Shell
UTF-8
2,617
3.390625
3
[]
no_license
#!/bin/bash QTDIR=$HOME/Qt/5.11.2/clang_64/bin VERSION_H=common/usbtenki_version.h LIBUSB_DYLIB=../../libusb/Xcode/build/Release/libusb-1.0.0.dylib if [ ! -f $VERSION_H ]; then echo "Please run this script from its parent directory." exit 1 fi VERSION=`grep USBTENKI_VERSION $VERSION_H | head -1 | cut -d \" -f 2` APP=qtenki.app PATH=$PATH:$QTDIR #otool -L $(APP) echo "Version: $VERSION" cd client || exit 1 if [ ! -e $LIBUSB_DYLIB ]; then echo "Could not find $LIBUSB_DYLIB" exit 1 fi Make -f Makefile.osx clean all || exit 1 cd .. cd qtenki || exit 1 iconutil --convert icns qtenki.iconset --output qtenki.icns || exit 1 qmake || exit 1 make || exit 1 macdeployqt $APP || exit 1 cp $LIBUSB_DYLIB $APP/Contents/Frameworks || exit 1 rm -rf osx_staging rm tmp.dmg mkdir osx_staging cp -R qtenki.app osx_staging ls osx_staging ln -s /Applications osx_staging/Applications mkdir osx_staging/.background cp osx_install_bg.png osx_staging/.background/bg.png cp ../client/usbtenkiget ./osx_staging/qtenki.app/Contents/MacOS cp ../client/usbtenkiset ./osx_staging/qtenki.app/Contents/MacOS install_name_tool -add_rpath "@executable_path/../Frameworks" ./osx_staging/qtenki.app/Contents/MacOS/usbtenkiget install_name_tool -add_rpath "@executable_path/../Frameworks" ./osx_staging/qtenki.app/Contents/MacOS/usbtenkiset hdiutil create -srcfolder osx_staging -size 60m -fs HFS+ -volname "QTenki" -fsargs "-c c=64,a=16,e=16" -format UDRW tmp.dmg hdiutil attach tmp.dmg sleep 2 echo ' tell application "Finder" tell disk "QTenki" open set current view of container window to icon view set toolbar visible of container window to false set statusbar visible of container window to false set bounds of container window to { 400, 100, 920, 440 } delay 1 set theViewOptions to the icon view options of container window set arrangement of theViewOptions to not arranged set icon size of theViewOptions to 72 set background picture of theViewOptions to file ".background:bg.png" delay 1 set file_list to every file repeat with i in file_list delay 1 if the name of i is "Applications" then set position of i to { 360, 205 } else if the name of i ends with ".app" then set position of i to { 160, 205 } end if end repeat close open update without registering applications delay 4 end tell end tell ' | osascript sync DEVS=$(hdiutil attach tmp.dmg | cut -f 1) DEV=$(echo $DEVS | cut -f 1 -d ' ') hdiutil detach $DEV rm ../qtenki-$VERSION.dmg hdiutil convert tmp.dmg -format UDZO -o ../qtenki-${VERSION}.dmg cd .. echo "OK"
TypeScript
UTF-8
423
3.390625
3
[]
no_license
'use strict'; let currentHours: number = 12; let currentMinutes: number = 12; let currentSeconds: number = 59; let secondsInDay: number = 86400; // Write a program that prints the remaining seconds (as an integer) from a // day if the current time is represented by these variables let day: number = (currentHours*3600) + (currentMinutes*60) + currentSeconds; console.log("Remaining seconds: " + (secondsInDay - day));
Java
UTF-8
4,672
3
3
[]
no_license
package models.logic; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.LinkedList; import java.util.Scanner; /** * From http://www.java2s.com/Code/Java/File-Input-Output/FileSplitter.htm */ public class Splitter { private File f; public Splitter(File f) { if (f == null) throw new IllegalArgumentException("File must be not null!"); this.f = f; //System.out.println("File Length (KB): " + f.length() / 1024.0); } public boolean split(long size) { if (size <= 0) return false; try { int parts = ((int) (f.length() / size)); long flength = 0; if (f.length() % size > 0) parts++; File[] fparts = new File[parts]; FileInputStream fis = new FileInputStream(f); FileOutputStream fos = null; for (int i = 0; i < fparts.length; i++) { fparts[i] = new File(f.getPath() + ".part." + i); fos = new FileOutputStream(fparts[i]); int read = 0; long total = 0; byte[] buff = new byte[1024]; int origbuff = buff.length; while (total < size) { read = fis.read(buff); if (read != -1) { buff = FileEncoder.invertBuffer(buff, 0, read); total += read; flength += read; fos.write(buff, 0, read); } if (i == fparts.length - 1 && read < origbuff) break; } fos.flush(); fos.close(); fos = null; } fis.close(); // f.delete(); f = fparts[0]; //System.out.println("Length Readed (KB): " + flength / 1024.0); return true; } catch (Exception ex) { System.out.println(ex); System.out.println(ex.getLocalizedMessage()); System.out.println(ex.getStackTrace()[0].getLineNumber()); ex.printStackTrace(); return false; } } public boolean split(int parts) { if (parts <= 0) return false; return this.split(f.length() / parts); } public boolean unsplit() { try { LinkedList<File> list = new LinkedList<File>(); boolean exists = true; File temp = null; File dest = new File(f.getPath().substring(0,f.getPath().lastIndexOf(".part"))); FileInputStream fis = null; FileOutputStream fos = new FileOutputStream(dest); int part = 0; long flength = 0; String name = null; while (exists) { name = f.getPath(); name = name.substring(0, name.lastIndexOf(".") + 1) + part; temp = new File(name); exists = temp.exists(); if (!exists) break; fis = new FileInputStream(temp); byte[] buff = new byte[1024]; int read = 0; while ((read = fis.read(buff)) > 0) { buff = FileEncoder.invertBuffer(buff, 0, read); fos.write(buff, 0, read); if (read > 0) flength += read; } fis.close(); fis = null; temp.delete(); part++; } fos.flush(); fos.close(); f = dest; //System.out.println("Length Writed: " + flength / 1024.0); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Split? [true/false]: "); boolean split = Boolean.parseBoolean(scan.next()); if (split) { File file = new File("/home/raphabot/IdeaProjects/DistiCloudCLI/src/com/company/document.txt"); Splitter splitter = new Splitter(file); System.out.println("splitter.split(3): " + splitter.split(6)); } else { File file = new File("/home/raphabot/IdeaProjects/DistiCloudCLI/src/com/company/document.txt.part.0"); Splitter splitter = new Splitter(file); System.out.println("splitter.unsplit(): " + splitter.unsplit()); } } }
Java
UTF-8
764
2.703125
3
[]
no_license
package unidadesGraficas; import java.util.Iterator; import org.apache.log4j.Logger; public class Window { String idparent; private final static Logger logger = Logger.getLogger(Window.class); public void pasarANuevaVentana() { try { Iterator<String> parent=SeleniumSession.driver().getWindowHandles().iterator(); idparent=parent.next(); String child=parent.next(); SeleniumSession.setDriver(SeleniumSession.driver().switchTo().window(child)); } catch (Exception e) { logger.fatal("Error al pasar a ventana"); System.exit(0); } } public void volverAVentanaAnterior() { SeleniumSession.driver().close(); SeleniumSession.setDriver(SeleniumSession.driver().switchTo().window(idparent)); } }
Python
UTF-8
1,370
3.625
4
[ "MIT" ]
permissive
""" Python package: https://github.com/fhirschmann/rdp ist aber nicht schnell (Faktor 10 langsamer) https://en.wikipedia.org/wiki/Ramer–Douglas–Peucker_algorithm Code von hier: https://stackoverflow.com/questions/2573997/reduce-number-of-points-in-line#10934629 """ def _vec2d_dist(p1, p2): return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 def _vec2d_sub(p1, p2): return p1[0]-p2[0], p1[1]-p2[1] def _vec2d_mult(p1, p2): return p1[0]*p2[0] + p1[1]*p2[1] def ramer_douglas(line, dist): """Does Ramer-Douglas-Peucker simplification of a curve with `dist` threshold. `line` is a list-of-tuples, where each tuple is a 2D coordinate Usage is like so: >>> myline = [(0.0, 0.0), (1.0, 2.0), (2.0, 1.0)] >>> simplified = ramer_douglas(myline, dist = 1.0) """ if len(line) < 3: return line begin = line[0] end = line[-1] if line[0] != line[-1] else line[-2] distSq = list() for curr in line[1:-1]: tmp = ( _vec2d_dist(begin, curr) - _vec2d_mult(_vec2d_sub(end, begin), _vec2d_sub(curr, begin)) ** 2 / _vec2d_dist(begin, end)) distSq.append(tmp) maxdist = max(distSq) if maxdist < dist ** 2: return [begin, end] pos = distSq.index(maxdist) return (ramer_douglas(line[:pos + 2], dist) + ramer_douglas(line[pos + 1:], dist)[1:])
Java
UTF-8
3,146
3
3
[]
no_license
package data; import exceptions.InputException; import models.StockOrder; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import static models.StockOrder.Type.BUY; import static models.StockOrder.Type.SELL; import static utils.StringParseUtil.parseToDate; import static utils.StringParseUtil.parseToDouble; import static utils.StringParseUtil.parseToInt; public class StockExchangeDummyData { private static int NUMBER_OF_FIELDS = 6; public static List<StockOrder> getDummyData() throws ParseException { List<StockOrder> stockOrders = new ArrayList<>(); // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm"); stockOrders.add(new StockOrder(1, simpleDateFormat.parse("09:45"), "FK", SELL, 100, 240.10)); stockOrders.add(new StockOrder(2, simpleDateFormat.parse("09:45"), "FK", SELL, 90, 237.45)); stockOrders.add(new StockOrder(3, simpleDateFormat.parse("09:47"), "FK", BUY, 80, 238.10)); stockOrders.add(new StockOrder(5, simpleDateFormat.parse("09:48"), "FK", SELL, 220, 241.50)); stockOrders.add(new StockOrder(6, simpleDateFormat.parse("09:49"), "FK", BUY, 50, 238.50)); stockOrders.add(new StockOrder(7, simpleDateFormat.parse("09:52"), "AZ", BUY, 10, 100.10)); stockOrders.add(new StockOrder(8, simpleDateFormat.parse("10:01"), "FK", SELL, 20, 240.10)); stockOrders.add(new StockOrder(9, simpleDateFormat.parse("10:02"), "FK", BUY, 150, 242.70)); return stockOrders; } public static List<StockOrder> getDummyDataFromFile() throws InputException { List<StockOrder> stockOrders = new ArrayList<>(); try { BufferedReader in = new BufferedReader(new FileReader("data.txt")); String str; while ((str = in.readLine()) != null) { stockOrders.add(getStockOrder(str)); } in.close(); } catch (IOException e) { throw new InputException("Unable to deparse file."); } return stockOrders; } private static StockOrder getStockOrder(String data) throws InputException { String[] fields = data.split(" "); if(fields.length != NUMBER_OF_FIELDS) { throw new InputException("Wrong number of fields"); } else { int id = parseToInt(fields[0]); Date date; try { date = parseToDate(fields[1], "HH:mm"); } catch (ParseException e) { throw new InputException("Failed to parse date."); } String name = fields[2]; StockOrder.Type type = StockOrder.Type.valueOf(fields[3].toUpperCase()); int quantity = parseToInt(fields[4]); double price = parseToDouble(fields[5]); return new StockOrder(id, date, name, type, quantity, price); } } }
C++
UTF-8
1,409
3.109375
3
[]
no_license
#include "ThreadPool.h" #include "Handler.h" #include <utility> ThreadPool::ThreadPool(unsigned int threadLimit, std::string documentRoot) : done(false), documentRoot(std::move(documentRoot)) { threadNumber = threadLimit; if (threadNumber == 0) { threadNumber = 1; } for (int i = 0; i < threadNumber; i++) { threads.emplace_back(&ThreadPool::DoWork, this); } } ThreadPool::~ThreadPool() { done = true; queueConditionalVariable.notify_all(); for (auto &thread : threads) { if (thread.joinable()) { thread.join(); } } } void ThreadPool::AddToQueue(int socket, const std::string &requestString) { std::lock_guard<std::mutex> g(queueMutex); queue.push(std::pair<int, std::string>(socket, requestString)); queueConditionalVariable.notify_one(); } void ThreadPool::DoWork() { while (!done) { std::pair<int, std::string> request; { std::unique_lock<std::mutex> g(queueMutex); queueConditionalVariable.wait(g, [&]{ return !queue.empty() || done; }); request = queue.front(); queue.pop(); } HandleRequest(request.first, request.second); } } void ThreadPool::HandleRequest(int socket, const std::string &requestString) { Handler handler(documentRoot); handler.Handle(socket, requestString); }
C#
UTF-8
1,931
3.53125
4
[]
no_license
using System; using System.Collections.Generic; namespace WP_ShoppingCart { //Draft item is used after selecting an item in the combo box and added to the order when clicking on the Add to Order button. //Gets recreated when the item count gets changed. public class DraftItem { public string ItemName { get; set; } //Name of item public int NumberOfItems { get; set; } //Number of given item in total private double OrderTotal { get; set; } //Total for given Item /// <summary> /// List<TUPLE> /// int - number of items (for non promotional 1, for promotional the number in promotion) /// double - The price of item (for non promotional single price, for promotional the promotion price) /// int - number of items in the draft /// double - total for all items in the draft /// </summary> private List<(int, double, int, double)> Breakdown { get; set; } private DraftItem() { //Should only create a draft item with the Item name } public DraftItem(string itemName) { ItemName = itemName; Breakdown = new List<(int, double, int, double)>(); } //The breakdown, i.e. how many single items, any promotions etc. public List<(int, double, int, double)> GetBreakDown() { return Breakdown; } //Total for all Items in this draft public double GetOrderTotal() { //whatever comment return OrderTotal; } //Adds new items to the draft public void AddToOrder(int number, double price, int totalNumber) { OrderTotal += Math.Round((price * totalNumber), 2); Breakdown.Add((number, price, totalNumber, OrderTotal)); NumberOfItems += number * totalNumber; } } }
Markdown
UTF-8
11,075
2.875
3
[ "Apache-2.0", "MIT" ]
permissive
--- comments: true date: '2016-07-22T18:00:00-05:00' slug: purchasing-an-anonymous-vpn tags: - bitcoin - vpn - experiment title: How I Bought a (Nearly) Anonymous VPN url: /weblog/2016/07/22/purchasing-an-anonymous-vpn --- There's a ton of reasons why nearly everyone should consider using a VPN. They allow to get around various region blocks, secure your traffic when on public wifi networks, and generally can keep annoying prying eyes away from your internet traffic. I'm not one of those people who thinks that you should always use a VPN even when at home - I'm not that paranoid — but I recognize there are reasons why you may want to. A few months ago I had a brief trip across country with some down time and concluded this was a perfect chance to try and purchase a 100% anonymous VPN. ## Step 1: Identify a VPN Host I started out by looking at [That One Privacy Guy's VPN Spreadsheet](https://thatoneprivacysite.net/vpn-comparison-chart/). This recently moved to a dedicated site that isn't nearly as useful as the original Google Spreadsheets version, but it still works. I had a couple of major criteria that I was looking at in a VPN provider: 1. **Jurisdiction:** I'd rather have this not based in one of [the Fourteen Eyes countries](https://en.wikipedia.org/wiki/UKUSA_Agreement#9_Eyes.2C_14_Eyes.2C_and_other_.22third_parties.22). 2. **Anonymous Payment:** If this is going to be anonymous, I really should be able to pay via Bitcoin. While technically Bitcoin isn't anonymous, it's usually a lot better than handing over my credit card. 3. **No Restrictions:** I'm not buying this to do anything illegal. I'm buying it to protect myself online. However, I don't want to ever run into the situation where I can't use the VPN for something I'd like to do. 4. **No Logging:** Logging of anything kinda invalidates a lot of the purpose of a VPN. The less logging the better. 5. **Multiple Hops:** Even with no logging, I want it so I can do multiple hops and further obfuscate my traffic. Looking through the list and browsing a couple of different sites, I decided to use [IVPN](https://www.ivpn.net/) as my host. They're in [Gibraltar, which has strange legal status as a self-governing overseas territory of the United Kingdom](https://en.wikipedia.org/wiki/Gibraltar#Governance). This gives them some protection from various British laws, while still providing a general rule of law that some of the other VPN providers can't provide. I'm not going to do anything illegal with this VPN, so maybe that would change if I were torrenting or something else. IVPN also doesn't keep logs, allows bitcoin payment, and was expensive enough that I don't think they're a fly-by-night operation. I could see it reasonably costing $100/yr to provide a high quality VPN service, as opposed to some fly-by-night operators that offer "lifetime" subscriptions for $49.95. **Privacy Steps:** I viewed this spreadsheet from an wifi access point in city $X that is thousands of miles away from my home. **Mistakes Made:** There were a few mistakes in this step. I opened up the spreadsheet using my normal copy of Chrome on my MacBook Pro. I didn't even use a private browsing session. The same browser was used for looking at multiple VPN providers. I should have used [Tails](https://tails.boum.org/) to anonymous my traffic and use a different session as I looked at each provider. I paid for coffee at the coffee shop with my credit card and didn't scout out the location for security cameras that might have captured me on video. ## Step 2: Acquire Payment There are lots of different ways to get Bitcoin. I have no idea what the most anonymous is, but I'd imagine that mining your own blocks is the way that would be most anonymous as the blocks wouldn't have any history. Unfortunately, mining Bitcoin now seems like a fools errand given the costs of power needed to mine. There are lots of places where you can easily purchase Bitcoin. I frequently use [Coinbase](https://www.coinbase.com/) to buy and spend Bitcoin because it makes it really easy. However, these aren't really anonymous. Luckily, going way back in time from the time in which I used to mine Bitcoin I have a few wallets on my local machine. However, none of these wallets have enough Bitcoin in them to afford the $100/yr for IVPN. This means that I had to supplement my Bitcoin with another source. Enter [localbitcoins.com](https://localbitcoins.com/). I had learned a little bit from my previous step of browsing, and by this point I was using Tails in a virtual machine to browse [localbitcoins.com](https://localbitcoins.com/). I also was smart and scouted out a seat in the coffee house that I'm pretty sure was out of range of their CCTV. To be extra paranoid I also temporarily changed the MAC address of my wifi card. I was fortunate that I was in a bit of tech hub and was able to find someone locally who could meet me in an hour. Unfortunately, I ended up paying a slight premium - to be on the safe side I bought about $150 worth of Bitcoin and paid about $155 for the Bitcoin. I had the coins transferred and verified they were in my wallet within about five minutes. Honestly, I expected this experience to be a lot more sketchy. For some reason I thought that most of the people who used localbitcoin.com would look like paranoid cyberpunks or drug addicts. I met the seller at a major mass transit stop and the guy looked like your normal tech employee and was a pleasure to chat with. I probably chatted a bit too long with him and eventually I blurted out that this was part of an experiment in buying an anonymous VPN. One major challenge with this step is that I didn't know where the Bitcoin came from. I thought I remember seeing something that a very large volume of Bitcoin were implicated in Silk Road, but [Lightspeed Venture Partners did the math and found that it actually underperformed the global average](http://lsvp.com/2013/08/15/about-half-a-percent-of-bitcoin-transactions-are-to-buy-drugs/). I did briefly look at tumbling the Bitcoin through [shapeshift.io](https://shapeshift.io/#/coins), but this was immediately after [the period of one of their insider sabotages](https://news.bitcoin.com/looting-fox-sabotage-shapeshift/). In reality I shouldn't have said that last bit because it can help narrow down the approximate date that I did all these actions. **Privacy Steps:** Buying Bitcoin via localbitcoins ensured a minimal digital trail. Connections to localbitcoins.com were made via a Tails throwaway VM from a different anonymous wifi hotspot with a spoofed MAC address. **Mistakes Made:** I communicated with the seller via text from my regular cell phone number rather than a burner application such as [Hushed](https://hushed.com/). I visited a local ATM to withdraw $200 in cash to pay for the Bitcoin. I chatted far too long with the bitcoin seller in a public location. I didn't tumble the Bitcoin to further anonymize them. ## Step 3: Get an Anonymous Email Address One downside of IVPN is that it requires an email address. Getting an anonymous email address isn't as easy as it once was. I had previously done some research on this and decided that [ProtonMail](https://protonmail.com/) would be a good choice. I went to a different coffee shop (I drink a lot of coffee when travelling cross country alone) and booted up a copy of Tails inside of VM to sign up. I made sure to generate a number of secure passwords with 1Password to complete the signup process. This is a reasonably secure process, but I guess I couldn've gone more secure and done something like a [diceware password](http://world.std.com/~reinhold/diceware.html) that I couldn've generated offline, but this worked well enough. Afterwards I saved the credentials in my encrypted file which is synced to the cloud - that's probably also problematic. **Privacy Steps:** Unique email account in secure third country. High security passwords. Used public wifi with spoofed MAC address to connect via Tails in a VM. **Mistakes Made:** Passwords saved in a password manager. Passwords generated by a computer rather than doing it offline. ## Step 4: Sign Up This was actually a very straight forward mechanism. I already had an anonymous email address and a mechanism to make the payment to IVPN using Bitcoin. It was just a matter of visiting the site to sign up. However, here's where I likely made my biggest mistake. In the rush to get everything going I used the wifi at the Airbnb where I was staying. I still used Tails in a VM, but supposing that somehow that I could be traced back, this would dramatically reduce the number of people that could be identified as using the connection. I also was lazy and used the same Tails session for sending the Bitcoin, checking email, and signing up with IVPN. However, I was now complete. What would normally have been a five minute process of signing up on a website and providing my credit card number and email turned into a multi-day adventure in learning the ins-and-outs of privacy. **Privacy Steps:** Used Tails in a VM. **Mistakes Made:** Reused same Tails session across multiple different purposes. Connected to a wifi network that could easily identify me. ## What would I change in the future? Thinking about this, I realized that a couple of my steps might have more uniquely identified me. Certainly connecting to multiple different coffee shop networks could make it easy to identify me through the use of closed circuit footage. In the future it might be better to do all of this from a single location. That location would have large scale public wifi and a location that I could avoid security cameras. I would enter the location, linger for a while, do the sign up process, linger for a bit more, then leave. This would at least make it harder if someone was looking at the people who were coming and going. Now that I have a VPN, I'd probably use that VPN in conjunction with Tails to sign up for a new VPN. Basically my traffic would first be routed through two different hope on the VPN and then sent out over Tor to anonymize my traffic. Finally, if I wanted to be really secure, I'd probably have done all of this on a burner laptop running a live image of Tails rather than running it inside of a VM. While in general it's believed that you're well isolated running inside of a VM and that you can't break out of a hypervisor, it's not beyond the realm of possibility that a nation-state might have an attack that could work around this. We know that the [FBI has previously cracked Tor](http://www.theinquirer.net/inquirer/news/2458121/mozilla-wants-to-know-how-the-fbi-cracked-tor), so it's probably prudent to assume that it only provides a minimal level of security. ## Final Thoughts I'm not one of those really security paranoid people. I have no intention to use this VPN connection to do anything illegal. I'm sure that there were mistakes made in this process, and I'd love to hear them in the comments below, but for me this was a valuable learning experience.
Java
UTF-8
4,300
2.359375
2
[]
no_license
package GUI; import com.google.gson.Gson; import Communication.ClientConsole; import Defines.API; import Defines.Dimensions; import Defines.ErrorCodes; import Defines.MemLvl; import Defines.MemLvlWorkerdb; import Defines.SceneName; import Dialogs.MessageDialog; import Dialogs.ProgressForm; import Requests.GeneralRequest; import Requests.Request; import javafx.concurrent.Task; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.scene.image.Image; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.BackgroundPosition; import javafx.scene.layout.BackgroundRepeat; import javafx.scene.layout.BackgroundSize; import javafx.scene.layout.StackPane; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.stage.Stage; public class WorkerView extends BaseView { static TextField mName; static TextField mPassword; public WorkerView(ClientConsole aChat) { super(aChat); // Init mName = new TextField(); mPassword = new TextField(); mName.setFont(Font.font("Verdana", FontWeight.BOLD, 12)); mPassword.setFont(Font.font("Verdana", FontWeight.BOLD, 12)); // OnClick Button singIn = new Button("Sign In"); singIn.setOnAction(e->{ if (mName.getText().isEmpty() || mPassword.getText().isEmpty()) { Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Error"); alert.setHeaderText("Some fields are missing"); alert.setContentText("Please fill all fields"); alert.showAndWait(); } else { GeneralRequest accountCheck = new GeneralRequest(mName.getText(), mPassword.getText()); Request request = new Request(API.GET_WORKER, accountCheck); String jsonString = mGson.toJson(request); mChat.SendToServer(jsonString); ProgressForm progressForm = new ProgressForm(); Task<Void> waitTask = new Dialogs.WaitTask(); progressForm.activateProgressBar(waitTask); waitTask.setOnSucceeded(event -> { progressForm.getDialogStage().close(); singIn.setDisable(false); goBack.setDisable(false); if (Main.mServerResponseErrorCode == ErrorCodes.SUCCESS) { MessageDialog alert = new MessageDialog(AlertType.INFORMATION, "Welcome", "You are successfully signed in..", "You are welcome to visit the Reports"); alert.showAndWait(); MemLvlWorkerdb.UpdateWorkerLevel(); Main.changeScene(SceneName.MAIN); } else if (Main.mServerResponseErrorCode == ErrorCodes.USER_NOT_FOUND) { MessageDialog alert = new MessageDialog(AlertType.ERROR, "Error", "Worker details are incorrect", "Please try again"); alert.showAndWait(); } else { MessageDialog alert = new MessageDialog(AlertType.ERROR, "Error", "An unknown error has occurred", "Please try again"); alert.showAndWait(); } Main.mServerResponseErrorCode = ErrorCodes.RESET; }); singIn.setDisable(true); goBack.setDisable(true); progressForm.getDialogStage().show(); Thread thread = new Thread(waitTask); thread.start(); } }); // Position in UI mName.setMaxWidth(Dimensions.mWorkerViewTextWidth); mPassword.setMaxWidth(Dimensions.mWorkerViewTextWidth); mName.setTranslateY(-50); singIn.setTranslateY(100); // Scene StackPane stackPane = new StackPane(); stackPane.setBackground(new Background(myBIW)); stackPane.getChildren().addAll(mName, mPassword, singIn ,goBack); mScene = new Scene(stackPane, Dimensions.mWith, Dimensions.mheight); } public static void refreshScene() { mName.setText("Please enter worker name"); mPassword.setText("Please enter worker password"); } }
Python
UTF-8
905
4.125
4
[]
no_license
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ from p3 import getNextPrime import unittest def primes(n): """ Returns a list of the first n prime numbers """ primes = [2,3] for i in range(len(primes), n): primes.append(getNextPrime(primes)) return primes[-1] class testProblem(unittest.TestCase): def setUp(self): pass def testGetNextPrime(self): self.assertEqual(19, getNextPrime([2,3,5,7,11,13,17])) self.assertEqual(23, getNextPrime([2,3,5,7,11,13,17,19])) def testPrimes(self): self.assertEqual(7, primes(4)) self.assertEqual(13, primes(6)) if __name__ == '__main__': #test suite = unittest.TestLoader().loadTestsFromTestCase(testProblem) unittest.TextTestRunner(verbosity=2).run(suite) #print answer N = 10001 print 'the 10001st prime number is', primes(N)
Python
UTF-8
436
3
3
[]
no_license
import logging logging.info(f"in {__file__}") logger = logging.getLogger(__name__) def add_column_to_dataframe(input_df, results, target_column): if target_column in input_df.columns: logger.info(f"writing to column {target_column}") input_df[target_column] = results else: logger.info(f"append new column {target_column}") input_df.insert(len(input_df.columns), target_column, results, False)
JavaScript
UTF-8
391
3.71875
4
[]
no_license
const user = { name: "John", money: 1000, toString() { return `{name: "${this.name}"}`; }, valueOf() { return this.money; } }; // демонстрация результатов преобразований: console.log(String(user)); // toString -> {name: "John"} console.log(+user); // valueOf -> 1000 console.log(user + 500); // valueOf -> 1500
Python
UTF-8
16,089
4.15625
4
[]
no_license
''' 상하좌우 설계 문제 : 가장 왼쪽 위 좌표 (1, 1) 가장 오른쪽 아래 좌표 (N, N) A는 상하좌우로 움직일 수 있고 시작 좌표는 (1, 1)이다. A가 N x N 범위를 벗어나는 움직임은 무시된다. LRUD 중 하나의 문자가 반복적으로 적혀있는 계획서대로 움직인다. 입력 : 첫째 줄 N (1이상 100이하) 둘째 줄 계획서 (1이상 100이하) 출력 : x y 아이디어 : 리스트를 N*N 길이로 선언해서 나눈 몫과 나머지를 이용하여 행과 열을 표현하자. 몫=행, 나머지=열 temp 좌표와 current 좌표를 추가해서 temp좌표가 범위를 벗어나지 않았으면 갱신 상하좌우에 맞는 이동함수를 만든다. 범위를 벗어났는지 확인하는 함수를 만든다. 설계 : # 1. 입력 받기 # 2. 이동 함수 만들기 # 3. 범위 함수 만들기 # 4. 조건문으로 4가지 경우의 수 만들기 # 5. 경우의 수에 맞게 temp 좌표 조정하기 # 6. temp 좌표가 범위 내에 있는지 확인하기 # 7. 범위 내에 있으면 current 좌표 갱신하기 # 8. 계획서 횟수만큼 반복하기 내가 구현한 코드 : N=int(input()) # 1. 입력 받기 plan=list(input().split()) plan.reverse() def move(direction): # 2. 이동 함수 만들기 if direction=='L': # 4. 조건문으로 4가지 경우의 수 만들기 return_value=[0,-1] return return_value elif direction == 'R': return_value = [0, 1] return return_value elif direction == 'U': return_value = [-1, 0] return return_value else : return_value = [1, 0] return return_value def range_function(x_y_list,n): # 3. 범위 함수 만들기 if(x_y_list[0]>=1 and x_y_list[0]<=n and x_y_list[1]>=1 and x_y_list[1]<=n): return True else : return False temp_xy=[1,1] current_xy=[1,1] x=0 y=0 for i in range(len(plan)): # 8. 계획서 횟수만큼 반복하기 direction = plan.pop() x=move(direction)[0] y=move(direction)[1] temp_xy[0]+=x # 5. 경우의 수에 맞게 temp 좌표 조정하기 temp_xy[1]+=y flag=range_function(temp_xy,N) # 6. temp 좌표가 범위 내에 있는지 확인하기 if(flag==True): # 7. 범위 내에 있으면 current 좌표 갱신하기 current_xy=temp_xy else: temp_xy[0] -= x temp_xy[1] -= y print(current_xy[0],current_xy[1]) 피드백 : 범위를 벗어났다면 temp의 위치도 원상복구 시켜줘야한다. 굳이 나눈 몫과 나눈 나머지를 이용하지 않아도 된다. 연산은 2000만번을 초과하지 않으므로 시간 제한은 신경쓸 필요가 없다. 일련의 명령에 따라서 개체를 차례대로 이동시킨다는 점에서 시뮬레이션 유형으로 분류되며 구현이 중요한 대표적인 문제 유형이다. dx=[0,0,-1,1] dy=[-1,1,0,0] move_types=['L', 'R', 'U', 'D'] 위와 같은 방식으로 구현하는 것이 나중에 명령의 경우의 수가 많아졌을 때 덜 혼동될 것 같다. ''' ''' 시각 설계 문제 : 정수 N이 입력되면 00시 00분 00초부터 N시 59분 59초까지의 모든 시각 중에서 3이 하나라도 포함되어있는 경우의 수를 구하는 프로그램을 작성하시오 입력 : 첫째줄 N (0이상 23이하) 출력 : 경우의 수 출력 아이디어 : 1시간에 3 포함되는 경우의 수를 구하여 N을 곱한다. 시 : 03, 13 ,23 분 : 03, 13, 23, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 53 (15) 초 : 03, 13, 23, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 53 (15) 03, 13, 23 : 60*60 = 3600 나머지 : 15*60 + 45*15 = 1575 ex) 5이면 1575*5 + 3600 = 11475 설계 : 1. 입력 받기 2. 03시 13시 23시에는 3600을 더하고 이외의 시에는 1575를 더한다. 3 .출력한다. 내가 구현한 코드 : N=int(input()) # 1. 입력 받기 # 2. 03시 13시 23시에는 3600을 더하고 이외의 시에는 1575를 더한다. if N<3: result = (N+1)*1575 elif N>=3 and N<13 : result= N*1575 + 3600 elif N>=13 and N<23 : result= (N-1)*1575 +3600*2 elif N==23: result= (N-2)*1575 +3600*3 print(result) 저자의 완전 탐색 구현 : N=int(input()) count=0 for i in range(N+1): for j in range(60): for k in range(60): if '3' in str(i)+str(j)+str(k): count+=1 print(count) 피드백 : 되도록이면 수학적 계산보다는 컴퓨터의 빠른 연산을 이용한 단순한 방법을 이용해라 수학적인 방법은 휴먼에러를 발생시킬 확률이 높다. 그냥 반복문 3개를 겹쳐서 단순하게 하는 것이 휴먼 에러가 안날 확률이 가장 높다. 3중 반복문을 돌면서 모든 경우의 수에 대해서 3이 들어간 수를 카운팅하는 방식이 완전탐색이다. ''' ''' 왕실의 나이트 설계 문제 : 8*8 좌표 평면상에서 나이트의 위치가 주어졌을 때 나이트가 이동할 수 있는 경우의 수를 출력하는 프로그램을 작성하시오 나이트는 좌표평면 상에서 벗어날 수 없고 수직으로 2칸 수평으로 1칸 또는 수직으로 1칸 수평으로 2칸 이동할 수 있다. 최대 8가지 이동경로가 존재한다. 입력 : 첫쨰줄에 좌표가 주어진다. ex) "a1" 출력 : 경우의 수 출력 아이디어 : 완전탐색과 구현으로 이루어진 유형인듯 하다. (유형파악) 8가지의 경우의 수가 있고 이 경우의 수가 범위를 벗어났지 확인하는 함수를 만들자 상하좌우에서의 이동경로 방식을 구현해보자 설계 : # 1. 입력받기 # 2. 입력받은 문자 해석하기 첫번째 글자 열 두번쨰글자 행 # 3. 좌표가 범위를 벗어났는지 확인해주는 함수 구현 # 4. 8가지 경우의 확인하면서 카운트하기 # 5. 카운트 출력하기 내가 구현한 코드 : n=input() # 1. 입력받기 def change_num(col): # 문자를 숫자로 바꾸는 함수 구현 if col == 'a': return 1 elif col == 'b': return 2 elif col == 'c': return 3 elif col == 'd': return 4 elif col == 'e': return 5 elif col == 'f': return 6 elif col == 'g': return 7 elif col == 'h': return 8 col = int(change_num(n[0])) # 2. 입력받은 문자 해석하기 첫번째 글자 열 두번쨰글자 행 row = int(n[1]) def check_TF(row,col): # 3. 좌표가 범위를 벗어났는지 확인해주는 함수 구현 if row<1 or row>8 or col<1 or col>8 : return False else : return True direction_row=[-2,-2,2,2,-1,-1,1,1] direction_col=[1,-1,1,-1,2,-2,2,-2] count=0 # 4. 8가지 경우의 확인하면서 카운트하기 for i in range(len(direction_row)): if check_TF(row+direction_row[i],col+direction_col[i])==True: count+=1 print(count) # 5. 카운트 출력하기 피드백 : ord() 함수를 이용해서 문자의 아스키코드 값을 얻을 수 있다. 이 ord() 함수를 이용하면 굳이 changE_num 이라는 함수를 구현 안해도 된다. 이번 저자는 리스트에 튜플을 담아서 이동방향을 기록하였다. 저자는 두가지 형태 모두 자주 사용되므로 참고하라고 한다. ''' ''' 게임 개발 설계 문제 : NxM 크기의 직사각형으로 각각의 칸은 육지와 바다이고 캐릭터는 동서남북 중 한 곳을 바라본다. 맵 각각의 칸은 (A,B)로 나타내고 북쪽과 서쪽으로부터 떨어진 칸의 개수이다. 캐릭터는 상하좌우로 움직일 수 있고 바다로 되어 있는 공간에는 갈 수 없다. 1. 현재위치 현재방향을 기준으로 왼쪽방향부터 차례대로 갈 곳을 정한다. 2. 캐릭터의 바로 왼쪽 방향에 아직 가보지 않은 칸이 존재한다면 왼쪽 방향으로 회전한 다음 왼쪽으로 한 칸을 전진한다. 왼쪽방향에 아직 가보지 않은 칸이 존재하지 않는다면 왼쪽으로 방향만 회전하고 1단계로 돌아간다. 3. 만약 4방향 모두 가본 칸이거나 바다로 되어있는 경우 바라보는 방향을 유지한 채로 한 칸 뒤로 가고 1단계로 돌아간다. 단 뒤쪽이 바다인 칸이라 뒤로 갈 수 없는 경우에는 움직임을 멈춘다. 위의 3가지 메뉴얼에 따라 이동시킨 후 캐릭터가 방문한 칸의 수를 출력하는 프로그램을 작성하라 입력 : 1. N M [3,50] 2. A B 처음 바라보는 방향(n:0 e:1 s:2 w:3) 시계방향 3~3+N. NXM 모양형태로 바다1인지 육지0인지 정보가 주진다. 출력 : 캐릭터가 방문한 칸 수를 출력 아이디어 : 방문한 곳을 체크하기위한 리스트를 하나 더 만든다. 왼쪽방향에 가보지 않은 칸이 있는지 없는지 확인하는 함수를 만들기 왼쪽방향으로 회전하는 함수 만들기 1칸 앞으로 가는 함수 만들기 4방향이 가본 칸이거나 바다인칸인 경우를 분별하는 함수 만들기 바라보는 방향은 유지한채로 한 칸 뒤로 가는 함수 만들기 뒤쪽이 바다인 칸인지 확인하는 함수 만들기 설계 : 1. 입력받기 2. 왼쪽방향에 가보지 않은 칸이 있는지 없는지 확인하는 함수1를 만들기 3. 왼쪽방향으로 회전하는 함수2 만들기 4. 1칸 앞으로 가는 함수3 만들기 5. 4방향이 가본 칸이거나 바다인 칸인 경우를 분별하는 함수4 만들기 6. 바라보는 방향은 유지한채로 한 칸 뒤로 가는 함수5 만들기 7. 뒤쪽이 바다인 칸인지 확인하는 함수6 만들기 8. 무한 루프를 건다. 9. 조건문의 조건으로 함수1을 설정하고 조건에 해당하면 함수2 함수3을실행한다. 조건에 해당하지 않으면 함수2만 실행한다. 10.9 번을 반복한다. 11. 함수4 가 True이면 함수6이 True인지 확인하고 True이면 멈추고 break하고 False이면 함수5를 실행시킨다. 내가 구현한 코드 : n_row,m_col=map(int,input().split()) current_row, current_col, current_dir =map(int,input().split()) map_array=[] check_array=[] for i in range(n_row): if i==0 : check_list = [] for j in range(m_col+2): check_list.append(100) map_array.append(check_list) check_list=list(map(int,input().split())) check_list.reverse() check_list.append(100) check_list.reverse() check_list.append(100) map_array.append(check_list) if i==n_row-1 : check_list = [] for j in range(m_col+2): check_list.append(100) map_array.append(check_list) # for i in range(n_row+2): # print(map_array[i]) def func1(row,col,dir): when_north=(0,-1) when_east=(-1,0) when_south=(0,1) when_west=(1,0) if dir==0: #가보지 않았으면 트루 if map_array[row+when_north[0]][col+when_north[1]]==0 : return True else : return False elif dir==1: if map_array[row+when_east[0]][col+when_east[1]]==0 : return True else : return False elif dir==2: if map_array[row+when_south[0]][col+when_south[1]]==0 : return True else : return False elif dir==3: if map_array[row+when_west[0]][col+when_west[1]]==0 : return True else : return False def func2(dir): if dir-1<0: return 3 else: return dir-1 def func3(row,col,dir): #앞으로 한칸이동한 좌표 반환 when_north = (-1, 0) when_east = (0, 1) when_south = (1, 0) when_west = (0, -1) if dir==0: return row+when_north[0],col+when_north[1] elif dir==1: return row+when_east[0],col+when_east[1] elif dir==2: return row+when_south[0],col+when_south[1] else: return row+when_west[0],col+when_west[1] def func4(row, col): #4방향이 가본칸이거나 바다인경우 트루 반환 when_north = (-1, 0) when_east = (0, 1) when_south = (1, 0) when_west = (0, -1) if map_array[row+when_north[0]][col+when_north[1]]==0 : return False elif map_array[row+when_east[0]][col+when_east[1]]==0 : return False elif map_array[row+when_south[0]][col+when_south[1]]==0 : return False elif map_array[row+when_west[0]][col+when_west[1]]==0 : return False else: return True def func5(row,col,dir): # 뒤로 한칸 이동한 좌표 반환 when_north = (1, 0) when_east = (0, -1) when_south = (-1, 0) when_west = (0, 1) if dir == 0: return row + when_north[0], col + when_north[1] elif dir == 1: return row + when_east[0], col + when_east[1] elif dir == 2: return row + when_south[0], col + when_south[1] else: return row + when_west[0], col + when_west[1] def func6(row,col,dir): #뒤쪽이 바다인 칸이면 트루 반환 when_north = (1, 0) when_east = (0, -1) when_south = (-1, 0) when_west = (0, 1) if dir == 0: if map_array[row + when_north[0]][col + when_north[1]] == 1: return True else: return False elif dir == 1: if map_array[row + when_east[0]][col + when_east[1]] == 1: return True else: return False elif dir == 2: if map_array[row + when_south[0]][col + when_south[1]] == 1: return True else: return False elif dir == 3: if map_array[row + when_west[0]][col + when_west[1]] == 1: return True else: return False count=0 while True: if func4(current_row,current_col): if func6(current_row,current_col,current_dir): break else: current_row,current_col=func5(current_row,current_col,current_dir) if func1(current_row,current_col,current_dir): current_dir=func2(current_dir) current_row,current_col=func3(current_row,current_col,current_dir) count+=1 map_array[current_row][current_col]=100 else: current_dir = func2(current_dir) print(count) 피드백 : 맵의 테두리를 고려하지 않아서 코드가 설계와는 다르게 조금 꼬였다. 그래도 기능들을 모듈화 해놓아서 금방 재설계 할 수 있었다. 아마 테스트 케이스를 여러개 넣어보지 않았다면 찾지 못했을 것이다. 설계부터 테스트 케이스를 넣을 수 있다면 넣어보는 습관을 들여야겠다. 파이썬에서는 2차원 배열을 구현할때 리스트안에 리스트를 넣는다. 2차원 배열값을 입력받는 방식을 숙지해라 d=[[0]*m for _in range(n)] 이 코드를 숙지둘 것 <저자가 말하는 문제풀이를 위한 중요한 테크닉> 일반적으로 방향을 설정해서 이동하는 문제 유형에서는 dx, dy라는 별도의 리스트를 만들어 방향을 정하는 것이 효과적이라고한다. 북 동 남 서 dx=[-1, 0, 1, 0] dy=[ 0, 1, 0, -1] 나는 해당 함수마다 해당 방향에 따라 움직여야하는 숫자를 정의했는데 위의 방식이 좀 더 효율적인 것 같다. 북쪽방향일 때 뒤로 이동하려면 row-dx[0] , col-dy[0] 해주면 되서 편한 것 같다. '''
Java
UTF-8
383
2.484375
2
[]
no_license
package at.tugraz.ist.qs2021.messageboard.dispatchermessages; import at.tugraz.ist.qs2021.actorsystem.Message; /** * Message sent from client to dispatcher to stop the system. * This message is then forwarded to all workers to stop them. */ public class Stop implements Message { public Stop() { } @Override public int getDuration() { return 2; } }
Markdown
UTF-8
2,193
2.515625
3
[]
no_license
我本以为没有机会再提笔了。2016年12月24日,平安夜,天使用她的翅膀触摸了我。接下来的十多个小时,我游离在天地之间,不省人事。醒来时听到的是丈夫、儿女在医院床头的呼唤,原来我已经试着飞天,没成行是因为我舍不得离开亲人,朋友,舍不得留下这尚未完成的《岁月如歌》,舍不得离开这个美好的世界。 出于支持我抗癌治病的初衷,姜晹团长开设了曾平合唱团歌友群,新朋好友从四面八方而來,踊跃参群。从开始的几句寒暄,几声安慰,到后来敞开胸怀,以诚相见,群友们倾其情尽其心,真诚交流,共同分享过去人生的经历与感悟,讨论今日的机会与挑战。从此这个普通的聊天群不再普通,它不仅传递着关爱与支持,而且也是一个探讨人生价值的平台,群友们心灵撞击出的火花变成了光与热,温暖和激励了群内以至群外的朋友。 借着微信这个奇妙的平台,我们逐渐深入的交谈变成了生动幽默的文字,我和群友们看到了它的价值及可读性,于是便有了写成文章的冲动,继而又萌生了群体出书的愿望。 不愧是新世纪合唱团群,懂得合作的真谛,五十多个歌友拿起了笔,或创作、或评论,人人参与这本《岁月如歌》的写作。在书里我们重访了沉淀多年的记忆,回顾了在美国留学,成家立业,生儿育女,职场拼博的精彩生活。 今天,《岁月如歌》已经排版成册,即將付印。屈指一数,共有三十多位作者,约七十篇文章,几百条微信评论。真是不数不知道,一数吓一跳,有生以来,我从未见过这么浩荡的写作和书评团队。是什么样的目标有如此的凝聚力,是什么样的情感有如此的推动力,又是什么样的群体有如此神奇的组合力?是爱,是对生命的热爱,对朋友的挚爱,这种爱感天动地,这种爱给了我信心、勇气和力量。我相信新世纪歌友之间的友谊会长存,会有更多的人將受到这种爱的鼓舞,在生活的崎岖道路上勇敢前行。
Java
UTF-8
1,341
3.46875
3
[]
no_license
public class RotateMatrix { private static void transpose(int m[][]) { for (int i = 0; i < m.length; i++) { for (int j = i; j < m[0].length; j++) { int temp = m[j][i]; m[j][i] = m[i][j]; m[i][j] = temp; } } } public static boolean rotateWithTranspose(int m[][]) { transpose(m); for (int i = 0; i < m[0].length; i++) { for (int j = 0, k = m[0].length - 1; j < k; j++, k--) { int temp = m[j][i]; m[j][i] = m[k][i]; m[k][i] = temp; } } return true; } public static boolean rotateRing(int[][] m) { int len = m.length; // rotate counterclockwise for (int i = 0; i < len / 2; i++) { for (int j = i; j < len - i - 1; j++) { int temp = m[i][j]; // right -> top m[i][j] = m[j][len - 1 - i]; // bottom -> right m[j][len - 1 - i] = m[len - 1 - i][len - 1 - j]; // left -> bottom m[len - 1 - i][len - 1 - j] = m[len - 1 - j][i]; // top -> left m[len - 1 - j][i] = temp; } } return true; } }
Markdown
UTF-8
1,871
3.9375
4
[ "MIT" ]
permissive
<!-- * @Autor: Guo Kainan * @Date: 2021-09-16 14:48:04 * @LastEditors: Guo Kainan * @LastEditTime: 2021-09-16 14:52:28 * @Description: --> # 题目 [208.前缀树](https://leetcode-cn.com/problems/implement-trie-prefix-tree/) 前缀树是查字典时常用的一种数据结构,用空间换时间,能有效降低大词库中的查询时间。 # 题解 ```js /** * Initialize your data structure here. */ var Trie = function() { // 字母索引的孩子节点 this.children = {} // 当前节点是否为单词末尾 this.isWord = false }; /** * Inserts a word into the trie. * @param {string} word * @return {void} */ Trie.prototype.insert = function(word) { let cur = this for (let i = 0; i < word.length; i++) { const ch = word[i] if (!cur.children[ch]) { cur.children[ch] = new Trie() } cur = cur.children[ch] } cur.isWord = true }; /** * Returns if the word is in the trie. * @param {string} word * @return {boolean} */ Trie.prototype.search = function(word) { let cur = this for (let i = 0; i < word.length; i++) { const ch = word[i] if (!cur.children[ch]) { return false } cur = cur.children[ch] } return cur.isWord }; /** * Returns if there is any word in the trie that starts with the given prefix. * @param {string} prefix * @return {boolean} */ Trie.prototype.startsWith = function(prefix) { let cur = this for (let i = 0; i < prefix.length; i++) { const ch = prefix[i] if (!cur.children[ch]) { return false } cur = cur.children[ch] } return true }; /** * Your Trie object will be instantiated and called as such: * var obj = new Trie() * obj.insert(word) * var param_2 = obj.search(word) * var param_3 = obj.startsWith(prefix) */ ```
JavaScript
UTF-8
1,107
2.765625
3
[]
no_license
const DOMSearch = () => { const getGrandParentElement = (selector, level) => { let parentWanted = null; if (notNull(selector)) { for (let i = 0; i < level; i++) { if (parentWanted === null) { parentWanted = selector.parentElement; } else { parentWanted = parentWanted.parentElement; } } } return parentWanted; }; const getElement = selector => notNull(selector) ? document.querySelector(selector) : null; const getChildren = (element,level) => { if ( notNull(element) ) { return (level != undefined) ? element.children[level] : element.children; } return []; } const getGrandSon = (fromElement, grandSonaWanted) => { if (notNull(fromElement)) { return (grandSonaWanted !== undefined) ? fromElement.querySelector(grandSonaWanted) : null; } return null; } const notNull = element => (element !== undefined && element !== null); return { getGrandParentElement, getElement, getChildren, getGrandSon }; }; export default DOMSearch;
PHP
UTF-8
489
3.5
4
[]
no_license
<?php /* * 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. */ $a=3; $b=4; $c= $a+$b; echo "the result of $a plus $b is equal to $c"; $vec = array (); $vec[1111] = "Danidin Cohen"; $vec[2222] = "Robert Austin"; $vec[3333] = "Big Libovskey"; var_dump($vec); echo "<br>the content of Vec is:"; foreach ($vec as $k => $v){ echo "<br> In <b>$k</b> we have <b>$v</b>"; } ?>
PHP
UTF-8
262
2.84375
3
[]
no_license
<?php namespace Leitom\Role\Contracts; interface RouteScannerInterface { /** * We will call the getRoutes method on an implementation * of this interface to get all available routes for the system * * @return array */ public function getRoutes(); }
Markdown
UTF-8
4,229
2.671875
3
[ "MIT" ]
permissive
# CloudGate ![js-standard-style](https://cdn.rawgit.com/standard/standard/master/badge.svg) CloudGate is a Discord shard cluster microservice built on top of [CloudStorm](https://github.com/DasWolke/CloudStorm) with a REST api to perform gateway actions. CloudGate has a low resource footprint and publishes incoming messages through amqp like RabbitMQ. CloudGate has support for StatsD, DogStatsD, and Telegraf. To get started with CloudGate, you want to `git clone` this repository first Now run `npm install` or `yarn` in the cloned directory to install the necessary dependencies ## Configuration Create a file named `config.json` in the config folder, you can use the `config.example.json` as an example of what the file should contain: The botConfig is directly passed to the CloudStorm instance, so you can apply other options other than what's shown. Check CloudStorm for more info. ```json { "token": "DISCORD BOT TOKEN", "host": "127.0.0.1", "port": 7000, "amqpUrl": "amqp://guest:guest@localhost:56782", "amqpQueue": "test-pre-cache", "identifier": "", "authorization": "", "debug": false, "botConfig": { "firstShardId": 0, "lastShardId": 0, "shardAmount": 1, "initialPresence": { "status": "online", "activities": [ { "name": "Some bot", "type": 0 } ], "since": null, "afk": null } }, "statsD": { "enabled": false, "host": "host", "port": 8125, "prefix": "CloudGate" } } ``` ## Run To run the server, simple type `node index.js` ## Documentation Messages sent to amqp will look like this: ```js { op: 0, // CloudGate only sends op 0 Dispatch events d?: any, s?: number, t?: string, shard_id: number, cluster_id?: string // If CloudGate is configured with an identifier, this property will be present so you can easily route actions even with tons of gates } ``` ### ANY / Returns information about the gate including the Discord gateway version application/json ```json { "version": "0.2.1", "gatewayVersion": 10 } ``` ### POST /gateway/status-update Updates either a shard's status or the entire cluster status post json data: ```js { shard_id?: number, since: number | null, activities: [ { name: string, type: number, url?: string }, ... ], status: "online" | "dnd" | "idle" | "invisible" | "offline", afk: boolean } ``` application/json ```json { "message": "Updated status" } ``` ### POST /gateway/voice-status-update Updates the voice state of a shard in the cluster post json data ```js { shard_id: number, guild_id: string, channel_id: string | null, self_mute?: boolean, self_deaf?: boolean } ``` application/json ```json { "message": "Updated status" } ``` ### POST /gateway/request-guild-members Requests guild members from a guild the cluster watches over through the gateway This route does not return the requested members and instead sends it through a op 0 Dispatch GUILD_MEMBERS_CHUNK payload over the regular gateway amqp channel post json data ```js { shard_id: number, guild_id: string, query?: string, limit: number, presences?: boolean, user_ids?: Array<string>, nonce?: string } ``` application/json ```json { "message": "successfully sent payload" } ``` ### GET /shards/status Returns information about all of the shards in the cluster's status as well as the endpoint the shards are connected to application/json ```json { "shards": { "0": { "id": 0, "status": "ready", "ready": true, "trace": ["an array of long debug strings"], "seq": 1 } }, "endpoint": "wss://gateway.discord.gg?v=10&encoding=json&compress=zlib-stream" } ``` ### GET /shards/queue Returns information about which shards aren't ready and are pending connection It is possible for this list to include shards which have been asked by Discord to resume or have already connected before but are no longer ready application/json ```json { "queue": [ { "id": 0 } ] } ``` ### GET /shards/:id Returns information about a specific shard in the cluster application/json ```json { "id": 0, "status": "ready", "ready": true, "trace": ["an array of long debug strings"], "seq": 1 } ```
Shell
UTF-8
172
2.984375
3
[ "MIT" ]
permissive
#!/bin/sh # # /etc/init.d/rngd # # $Id$ # if [ -f /usr/sbin/rngd ]; then echo "Starting rngd..." /usr/sbin/rngd -r /dev/hwrng exit 0 fi echo "No rngd found. Aborting"
Java
UTF-8
1,713
1.992188
2
[]
no_license
package com.zrht.privilege.controller; import com.cloud.common.bean.ResponseInfo; import com.cloud.common.util.ResultUtils; import com.zrht.privilege.enums.ExceptionEnum; import com.zrht.privilege.exception.PrivilegeException; import com.zrht.privilege.service.MenuService; import com.zrht.privilege.utils.AssertUtil; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * 权限菜单表 前端控制器 * </p> * * @author xdj * @since 2019-07-19 */ @RestController @RequestMapping("/menu") public class MenuController { @Autowired private MenuService menuService; @PostMapping("/menuList/{roleId}") @ApiOperation(value = "获取角色权限菜单列表", notes = "返回菜单列表") @ApiImplicitParam(name = "roleId", value = "角色id", paramType = "query", required = true, dataType = "String", defaultValue = "ealenxie") @ApiResponse(code = 200, message = "获取成功") public ResponseInfo getMenuList(@PathVariable("roleId") String roleId) { AssertUtil.notEmpty(roleId, new PrivilegeException(ExceptionEnum.ROLE_INFO_IS_NULL.getCode(), ExceptionEnum.ROLE_INFO_IS_NULL.getMessage())); // return new ResponseInfo(000,menuService.getMenuList(roleId)); return ResultUtils.success(menuService.getMenuList(roleId)); } }
Java
UTF-8
854
3.171875
3
[]
no_license
package com.nagarro.RouletteAPI.utilities; public class SegmentToNumberChosenRoulette { /** * This method converts the user selected segement to the number to be compared * to the roulette generated number. * * @param segmentChosen * @return */ public static int convertSegmentToNumber(String segmentChosen) { if (("first12").equalsIgnoreCase(segmentChosen)) return 1; if (("second12").equalsIgnoreCase(segmentChosen)) return 2; if (("last12").equalsIgnoreCase(segmentChosen)) return 3; if (("zero").equalsIgnoreCase(segmentChosen)) return 4; if (("first18").equalsIgnoreCase(segmentChosen)) return 5; if (("last18").equalsIgnoreCase(segmentChosen)) return 6; if (("even").equalsIgnoreCase(segmentChosen)) return 7; if (("odd").equalsIgnoreCase(segmentChosen)) return 8; return 0; } }
Java
UTF-8
674
2.921875
3
[]
no_license
package LopStopWatch; import java.util.Arrays; import java.util.Calendar; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { stopWatch st = new stopWatch(); st.start(); int[] arr = stopWatch.creatRandom();//goi phuong thuc static nam trong cho khac thi ghi ten lop.phuongthuc // stopWatch.GTLN(arr); selectionSort.selectionSort(arr); System.out.println("Selection Sort"); for (int i = 0; i <arr.length ; i++) { System.out.print(arr[i]+" "); } st.stop(); System.out.println("time is " + st.getElapsedTime()); } }
Markdown
UTF-8
10,198
2.6875
3
[ "Intel", "Apache-2.0" ]
permissive
# Introduction to nGraph Flow in Inference Engine {#openvino_docs_IE_DG_nGraph_Flow} ## New Run-Time Intermediate Representation (IR): nGraph Starting from the OpenVINO&trade; release 2020.1, the Inference Engine integrates the nGraph Core. That implies that the Inference Engine uses a new way to represent a model in run time underneath of the conventional `CNNNetwork` API, which is an instance of `ngraph::Function`. Besides the representation update, nGraph integration resulted in the following changes and new features: 1. New operations sets. When operations from the nGraph Core were combined with conventional layers from `CNNNetwork`, there were created a [new sets of operations called `opset1`, `opset2` and etc.](../ops/opset.md), which covered both interfaces except several not very important cases. Operations from `opset3` are generated by the Model Optimizer and are accepted in the Inference Engine. 2. New version approach that attaches a version to each operation rather than to the entire IR file format. IR is still versioned but has a different meaning. For details, see [Deep Learning Network Intermediate Representation and Operation Sets in OpenVINO™](../MO_DG/IR_and_opsets.md). 3. Creating models in run-time without loading IR from an xml/binary file. You can enable it by creating `ngraph::Function` passing it to `CNNNetwork`. 4. Run-time reshape capability and constant folding are implemented through the nGraph code for more operations compared to previous releases. As a result, more models can be reshaped. For details, see the [dedicated guide about the reshape capability](ShapeInference.md). 5. Loading model from ONNX format without converting it to the Inference Engine IR. The conventional flow that is not based on nGraph is still available. The complete picture of co-existence of legacy and new flows is presented below. The rest of the document describes the coexistence of legacy and new flows showed in the picture below: ![](img/TopLevelNGraphFlow.png) ## Read the Intermediate Representation to `CNNNetwork` As the new operation set is introduced, the Model Optimizer generates the IR version 10 using the new operations by default. Each layer generated in the IR has a semantics matching to the corresponding operation from the nGraph namespaces `opset1`, `opset2` etc. The IR version 10 automatically triggers the nGraph flow inside the Inference Engine. When such IR is read in an application, the Inference Engine IR reader produces `CNNNetwork` that encapsulates the `ngraph::Function` instance underneath. Thus the OpenVINO IR becomes a new serialization format for the nGraph IR, and it can be deserialized reading the `CNNNetwork`. > **IMPORTANT**: Conventional interfaces are used (`CNNNetwork`, the reader), so no changes required in most applications. > **NOTE**: While you still can use old APIs, there is an independent process of continuous improvements in the Inference Engine API. > These changes are independent of nGraph integration and do not enable or disable new features. Interpretation of the IR version 10 differs from the old IR version. Besides having a different operations set, the IR version 10 ignores the shapes and data types assigned to the ports in an XML file. Both shapes and types are reinferred while loading to the Inference Engine using the nGraph shape and type propagation function that is a part of each nGraph operation. ### Legacy IR Versions Starting from the OpenVINO&trade; release 2021.1 you cannot read IR version 7 and lower in the Inference Engine. ## Build a Model in the Application Alternative method to feed the Inference Engine with a model is to create the model in the run time. It is achieved by creation of the `ngraph::Function` construction using nGraph operation classes and optionally user-defined operations. For details, see [Add Custom nGraph Operations](Extensibility_DG/AddingNGraphOps.md) and [examples](nGraphTutorial.md). At this stage, the code is completely independent of the rest of the Inference Engine code and can be built separately. After you construct an instance of `ngraph::Function`, you can use it to create `CNNNetwork` by passing it to the new constructor for this class. Initializing `CNNNetwork` from the nGraph Function means encapsulating the object and not converting it to a conventional representation. Going to low-level details, technically it is achieved by using another class for the `CNNNetwork` internals. The old representation that is used for former versions of IR before version 10 uses `CNNNetworkImpl`. The new representation that is built around nGraph uses `CNNNetworkNGraphImpl`. ![](img/NewAndOldCNNNetworkImpl.png) ## Automatic Conversion to the Old Representation The old representation is still required in the cases listed below. When old representation is required, the conversion from the `ngraph::Function` to the old representation is called automatically. The following methods lead to the automatic conversion: 1. Using the old API, which is expected to produce an old representation. Guaranteed to be read-only. Once you call such a method, the original nGraph representation is preserved and continues to be used in the successive calls. 1.1. `CNNNetwork::serialize`. Dumps the old representation after automatically called conversion. Cannot be used to dump IR V10. For details, see [Graph Debug Capabilities](Graph_debug_capabilities.md). 2. Calling `CNNNetwork` methods that modify the model. After that nGraph representation is lost and cannot be used afterwards. 1.1. `CNNNetwork::addLayer` 1.2. CNNNetwork::setBatchSize. Still implemented through old logic for backward compatibility without using nGraph capabilities. For details, see [Using Shape Inference](ShapeInference.md). 3. Using methods that return objects inside an old representation. Using these methods does not mean modification of the model, but you are not limited by the API to make read-only changes. These methods should be used in the read-only mode with respect to a model representation. If the model is changed, for example attribute of some layer is changed or layers are reconnected, the modification is lost whenever any method that uses nGraph is called, including methods inside plugins like CNNNetwork::reshape. It is hard to predict whether the nGraph function is used in a plugin or other methods of CNNNetworks, so modifying a network using the following methods is *strongly not recommended*. This is an important limitation that is introduced for the old API calls listed below: 1.1. `Data::getInputTo` 1.2. `Data::getCreatorLayer` 1.3. `CNNNetwork::getLayerByName` 1.4. Iterating over `CNNLayer` objects in `CNNNetwork`: `CNNNetwork::begin`, `details::CNNNetworkIterator` class. 4. Using a conventional plugin that accepts the old representation only. Though the conversion is always a one-way process, which means there is no method to convert back, there are important caveats. In the cases [1] and [3], both representations are held underneath and you should use the old representation in the read-only mode only from the caller side. It is hard to track from the Inference Engine side whether the API is used in the read-only mode or for modification of the model. That is why when using potentially modifying methods listed in section [3] above, you should not modify the model via those methods. Use a direct manipulation of the nGraph function instead. ## Conversion Function Inference Engine implements the conversion function that is used when the nGraph function is transformed to the old `CNNNetworkImpl` representation. This conversion function is hidden and you cannot call it directly from the application. Nevertheless, it is an important component of the model transformation pipeline in the Inference Engine. Some issues of models may be caught during the conversion process in this function. Exceptions are thrown in this function, and you should know what this function does to find a root cause. The conversion function performs the following steps: 1. Convert and decompose some operations as the first step of the nGraph function preparation for optimization. Reduce operation set to easily optimize it at the next stages. For example, decomposing of BatchNormInference happens at this stage. 2. Optimizing transformations that usually happen in the Model Optimizer are called here, because the nGraph function is not always read from an already optimized IR. 3. Changing operation set from `opsetX` to legacy layer semantics described in the [Legacy Layers Catalog](../MO_DG/prepare_model/convert_model/Legacy_IR_Layers_Catalog_Spec.md). The model is still represented as the nGraph function at this stage, but the operation set is completely different. 4. One-to-one conversion of nGraph representation to the corresponding `CNNNetworkImpl` without changing its semantics. You can see the result of the conversion by calling the `CNNNetwork::serialize` method, which produces legacy IR semantics, which is not nGraph-based even if it is applied to `CNNNetwork` constructed from the nGraph Function. It may help in debugging, see [Graph Debug Capabilities](Graph_debug_capabilities.md) to view all options for dumping new and old IR representations. ## Deprecation Notice <table> <tr> <td><strong>Deprecation Begins</strong></td> <td>June 1, 2020</td> </tr> <tr> <td><strong>Removal Date</strong></td> <td>December 1, 2020</td> </tr> </table> *Starting with the OpenVINO™ toolkit 2020.2 release, all of the features previously available through nGraph have been merged into the OpenVINO™ toolkit. As a result, all the features previously available through ONNX RT Execution Provider for nGraph have been merged with ONNX RT Execution Provider for OpenVINO™ toolkit.* *Therefore, ONNX RT Execution Provider for nGraph will be deprecated starting June 1, 2020 and will be completely removed on December 1, 2020. Users are recommended to migrate to the ONNX RT Execution Provider for OpenVINO™ toolkit as the unified solution for all AI inferencing on Intel® hardware.*
C#
UTF-8
612
2.546875
3
[]
no_license
foreach (var dteProject in dte.Solution.Projects.OfType<Project>()) { // You can edit the project through an object of Microsoft.Build.Evaluation.Project var buildProject = new Microsoft.Build.Evaluation.Project(dteProject.FullName); foreach (var item in buildProject.Items.Where(obj => obj.ItemType == "Reference")) { var newPath = SomeMethod(item.GetMetadata("HintPath")); item.SetMetadataValue("HintPath", newPath); } // But you have to save through an object of EnvDTE.Project dteProject.Save(); }
Java
UTF-8
3,741
2.40625
2
[]
no_license
package com.example.tripplanner; import android.os.Parcel; import android.os.Parcelable; import java.io.Serializable; import java.util.List; public class Place implements Parcelable { private String id; private String name; private String category; private String city; private String about; private String location; private double duration; private double rate; private List<String> images; public Place() { } public Place(String id, String name, String category, String city, String about, String location, int duration, double rate, List<String> images) { this.id = id; this.name = name; this.category = category; this.city = city; this.about = about; this.location = location; this.duration = duration; this.rate = rate; this.images = images; } protected Place(Parcel in) { id = in.readString(); name = in.readString(); category = in.readString(); city = in.readString(); about = in.readString(); location = in.readString(); duration = in.readDouble(); rate = in.readDouble(); images = in.createStringArrayList(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(id); dest.writeString(name); dest.writeString(category); dest.writeString(city); dest.writeString(about); dest.writeString(location); dest.writeDouble(duration); dest.writeDouble(rate); dest.writeStringList(images); } @Override public int describeContents() { return 0; } public static final Creator<Place> CREATOR = new Creator<Place>() { @Override public Place createFromParcel(Parcel in) { return new Place(in); } @Override public Place[] newArray(int size) { return new Place[size]; } }; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAbout() { return about; } public void setAbout(String about) { this.about = about; } public double getDuration() { return duration; } public void setDuration(double duration) { this.duration = duration; } public double getRate() { return rate; } public void setRate(double rate) { this.rate = rate; } public List<String> getImages() { return images; } public void setImages(List<String> images) { this.images = images; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } @Override public String toString() { return "Place{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", category='" + category + '\'' + ", city='" + city + '\'' + ", about='" + about + '\'' + ", location='" + location + '\'' + ", duration=" + duration + ", rate=" + rate + ", images=" + images + '}'; } }
Java
UTF-8
1,245
2.1875
2
[]
no_license
package test; import org.junit.*; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import utilities.CommonTestCase; import static org.junit.Assert.fail; public class appLogin extends CommonTestCase { @Test public void login() { driver.get("https://blueprint.meteorapp.com/app/auth/login"); try { WebDriverWait timer = new WebDriverWait(driver, 20); timer.until(ExpectedConditions.elementToBeClickable(By.name("userEmail"))); }catch (NoSuchElementException e) { fail("Login page is not displayed:" + e.getMessage()); } driver.findElement(By.name("userEmail")).clear(); driver.findElement(By.name("userEmail")).sendKeys("admin@showhub.events"); driver.findElement(By.id("userPassword")).clear(); driver.findElement(By.id("userPassword")).sendKeys("abc123"); driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='You are online.'])[1]/following::div[2]")).click(); driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='Password'])[1]/following::button[1]")).click(); } }
Java
UTF-8
922
2.09375
2
[]
no_license
package com.android.test.popularmoviestwo.database.old; import android.net.Uri; public class MoviesContract { public static final String CONTENT_AUTHORITY = "com.android.test.popularmoviestwo"; // Use CONTENT_AUTHORITY to create the base of all URI's which apps will use to contact the content provider. public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); public static final String PATH_FAVOUTIRES = "favourites"; public static Uri URI_FAVOURITES_GET_ALL = MoviesContract.BASE_CONTENT_URI.buildUpon().appendPath(MoviesContract.PATH_FAVOUTIRES).build(); public static Uri URI_FAVOURITES_INSERT = MoviesContract.BASE_CONTENT_URI.buildUpon().appendPath(MoviesContract.PATH_FAVOUTIRES).appendPath("insert").build(); public static Uri URI_FAVOURITES_DELETE = MoviesContract.BASE_CONTENT_URI.buildUpon().appendPath(MoviesContract.PATH_FAVOUTIRES).appendPath("delete").build(); }
Python
UTF-8
1,234
2.5625
3
[ "MIT" ]
permissive
from django.shortcuts import render, redirect from .models import ThoughtModel, SessionModel def get_username_from_session(request): cookie_session = request.COOKIES.get('session') try: session = SessionModel.objects.get(session=cookie_session) except SessionModel.DoesNotExist: return None return session.username def list_thoughts(request): ''' List the user's thoughts ''' username = get_username_from_session(request) if not username: return redirect('login') user_thoughts = (ThoughtModel.objects .filter(username=username) .order_by('-timestamp')) context = { 'thoughts': user_thoughts, 'username': username, } return render(request, 'list_thoughts.html', context) def new_thought(request): ''' Create a new thought for the user ''' username = get_username_from_session(request) if not username: return redirect('login') text = request.POST.get('text') if text: # Only store the thought if there's text in it new_thought = ThoughtModel(text=text, username=username) new_thought.save() return redirect('list-thoughts')
Java
UTF-8
3,012
3.609375
4
[]
no_license
package marshmallows.controller; import marshmallows.model.MarshmallowMonster; import marshmallows.view.MonsterDisplay; import java.util.Scanner; public class MonsterController { private MarshmallowMonster harryMonster; //Declares a Monster called harryMonster. private MarshmallowMonster userMonster; //Declares a Monster called userMonster. private MonsterDisplay myDisplay; private Scanner monsterScanner; public MonsterController() { String name = "Bernie."; int eyes = 3; int noses = 0; double legs = 2.0; double hair = 0.0; boolean hasBellyButton = false; monsterScanner = new Scanner(System.in); myDisplay = new MonsterDisplay(); harryMonster = new MarshmallowMonster(name, eyes, noses, hasBellyButton, legs, hair); } public void start() { myDisplay.displayInfo(harryMonster.toString()); createUserMonster(); myDisplay.displayInfo("User monster info: " + userMonster.toString()); } private void askQuestions() { System.out.println("I want a new name for a monster,type one please!"); String newMonsterName = monsterScanner.next(); harryMonster.setMonsterName(newMonsterName); System.out.println("I want a new number of eyes please!"); int newMonsterEyes = monsterScanner.nextInt(); harryMonster.setMonsterEyes(newMonsterEyes); System.out.println("I want a new number of noses please!"); int newMonsterNoses = monsterScanner.nextInt(); harryMonster.setMonsterNoses(newMonsterNoses); System.out.println("I want to know if it has a bellybutton please!"); boolean newMonsterBellyButton = monsterScanner.nextBoolean(); harryMonster.setMonsterBellyButton(newMonsterBellyButton); System.out.println("I want to know how many legs it has please!"); double newMonsterLegs = monsterScanner.nextDouble(); harryMonster.setMonsterLegs(newMonsterLegs); System.out.println("I want to know if it has hair, please!"); double newMonsterHair = monsterScanner.nextDouble(); harryMonster.setMonsterHair(newMonsterHair); } /** * Creates a MarshmallowMonster instance from user input. */ private void createUserMonster() { //Step one: Gather user information. System.out.println("What is your monster's name?"); String userName; userName = monsterScanner.nextLine(); System.out.println("How many legs will it have?"); double userLegs = monsterScanner.nextDouble(); System.out.println("How much hair does it have?"); double userHair = monsterScanner.nextDouble(); userHair = monsterScanner.nextDouble(); System.out.println("Does it have a belly button?"); boolean hasBellyButton = monsterScanner.nextBoolean(); System.out.println("Number of eyes on the monster?"); int userEyes = monsterScanner.nextInt(); System.out.println("How many noses do I have?"); int userNoses = monsterScanner.nextInt(); //Step two: Build the monster using the constructor. userMonster = new MarshmallowMonster(userName, userEyes, userNoses, hasBellyButton, userLegs, userHair); } }
Java
UTF-8
3,288
4.15625
4
[]
no_license
package com.theo; /** * Divide and Conquer Algorithm * Recursive Algorithm * In place Algorithm * Unstable Algorithm * Time complexity: O(n*log(n)), worst case O(n^2), mostly worst case if it has to do with only a few elements * because of the overhead from the recursion. * Using a pivot element to partition the array into two parts * Elements < pivot to it's left, Elements > pivot to it's right * Pivot will then be in it's correct sorted position * Then do the same for the left and the right array * End up with 1-element arrays (pivots), which will all be at its correct positions. * */ import java.util.Arrays; public class Main { public static void main(String[] args) { int[] myArray = {20, 35, -15, 7, 55, 1, -22}; System.out.println(Arrays.toString(myArray)); quickSort(myArray, 0, 7); // and always array.length (one greater than the last element) System.out.println(Arrays.toString(myArray)); } public static void quickSort(int[] array, int front, int back){ // the back should be one greater than the last valid index in the array if (back - front < 2){ // then we are dealing with 1-el array return; // don't do anything } int pivotIndex = partition(array, front, back); /* * returns the correct position of the pivot element in the array. * at that position, all the elements left from it are smaller and right greater * */ quickSort(array, front, pivotIndex); /* * What this recursive call does is, it works on the left side and when it is done, then and only then, it * moves on with the next tow and next recursion call to do the same thing on the right side. * */ quickSort(array, pivotIndex +1, back); } private static int partition(int[] array, int front, int back) { // this Method uses the first element as the pivot (it affects complexity) int pivot = array[front]; // we choose the first element of the array int i = front; int j = back; while(i < j){ // if i > j they have crossed each other (front > back) // traverse the array from right to left looking for the first element: less < pivot while(i < j && array[--j] >= pivot); // empty loop body, keep decrementing j until you find // an element that is either greater than the pivot or j crosses i. if (i < j){ // make sure j didn't cross i array[i] = array[j]; // move the element we found at the position i (front): i < pivot } // now we want to traverse the array from left to right until we find an element that is greater > pivot while (i < j && array[++i] <= pivot); // i = front = pivot, we want to start with the element after the pivot if (i < j){ // make sure j didn't cross i array[j] = array[i]; // move the element we found at the position j (back): pivot < j } } // at this point the value of j will be the index, where we want to insert the pivot. array[j] = pivot; // or array[i] = pivot; , this would be the same return j; } }
JavaScript
UTF-8
1,196
2.734375
3
[]
no_license
const container = document.querySelector('.container'); const shoes = [ { name: 'Crimson Tint', image: 'images/jordan1.jpg' }, { name: 'NYC to PARIS', image: 'images/jordan2.jpg' }, { name: 'Phantom', image: 'images/jordan3.jpg' }, { name: 'Pine Green', image: 'images/jordan4.jpg' }, { name: 'Reserve Bred', image: 'images/jordan5.jpg' }, { name: 'Shadow', image: 'images/jordan6.jpg' }, { name: 'Travis Scott', image: 'images/jordan7.jpg' }, { name: 'Turbo Green', image: 'images/jordan8.jpg' }, { name: 'Wheat', image: 'images/jordan9.jpg' }, ]; const showShoes = () => { let output = ''; shoes.forEach( ({ name, image }) => (output += ` <div class="card"> <img class="card--avatar" src=${image} /> <h1 class="card--title">${name}</h1> <a class="card--link" href="#">Shop</a> </div> `) ); container.innerHTML = output; }; document.addEventListener('DOMContentLoaded', showShoes); if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker .register('/serviceWorker.js') .then(res => console.log('service worker registered')) .catch(err => console.log('service worker not registered', err)); }); }
C#
UTF-8
660
2.859375
3
[]
no_license
using System.Collections.Generic; namespace CommonShuffleLibrary { public class QueueItemCollection { private readonly IEnumerable<QueueItem> queueItems; public QueueItemCollection(IEnumerable<QueueItem> queueItems) { this.queueItems = queueItems; } public QueueItem GetByChannel(string channel) { foreach (var queueWatcher in queueItems) { if (queueWatcher.Channel == channel || channel.IndexOf(queueWatcher.Channel.Replace("*", "")) == 0) return queueWatcher; } return null; } } }
Java
UTF-8
326
2.28125
2
[]
no_license
package enums.mobile; public enum FieldTitles { CONTACT_PHONE("Contact Phone"), CONTACT_NAME("Contact Name"), IANA_HOMEPAGE_TITLE("Internet Assigned Numbers Authority"); private String name; FieldTitles(String name) { this.name = name; } public String getTitle() { return name; } }
Java
UTF-8
2,127
1.875
2
[]
no_license
// isComment package it.sasabz.android.sasabus.appwidget; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.text.Html; import android.widget.RemoteViews; import it.sasabz.android.sasabus.R; import it.sasabz.android.sasabus.data.model.News; import it.sasabz.android.sasabus.data.network.RestClient; import it.sasabz.android.sasabus.data.network.rest.api.NewsApi; import it.sasabz.android.sasabus.data.network.rest.response.NewsResponse; import it.sasabz.android.sasabus.util.Utils; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * isComment */ public class isClassOrIsInterface extends AppWidgetProvider { @Override public void isMethod(Context isParameter, AppWidgetManager isParameter, int[] isParameter) { for (int isVariable : isNameExpr) { RemoteViews isVariable = new RemoteViews(isNameExpr.isMethod(), isNameExpr.isFieldAccessExpr.isFieldAccessExpr); NewsApi isVariable = isNameExpr.isFieldAccessExpr.isMethod().isMethod(NewsApi.class); isNameExpr.isMethod().isMethod(isNameExpr.isMethod()).isMethod(isNameExpr.isMethod()).isMethod(new Observer<NewsResponse>() { @Override public void isMethod() { } @Override public void isMethod(Throwable isParameter) { isNameExpr.isMethod(isNameExpr); } @Override public void isMethod(NewsResponse isParameter) { String isVariable = "isStringConstant"; for (News isVariable : isNameExpr.isFieldAccessExpr) { isNameExpr += isNameExpr.isMethod("isStringConstant", isNameExpr.isMethod(), isNameExpr.isMethod()); } isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr.isMethod(isNameExpr)); isNameExpr.isMethod(isNameExpr, isNameExpr); } }); } } }
JavaScript
UTF-8
1,930
2.859375
3
[]
no_license
import React, { Component } from 'react'; import Keyboard from "./Keyboard"; import Screen from "./Screen"; class Calculator extends Component { constructor() { super() this.keys = ['7', '8', '9', '+', '4', '5', '6', '-', '1', '2', '3', '*', '0', '.', '%', '/'] this.state = { result: '', inputValue: '', } } keyEvent = (key) => { if (key === 'Enter') { this.calculate() } else if (key === 'Backspace') { this.inputMethods.removeLastChar() } else if (this.keys.includes(key)) { this.inputMethods.addToInput(key) } }; inputMethods = { addToInput: (value) => { this.setState((prevState) => ({ inputValue: prevState.inputValue + value })) }, removeLastChar: () => { this.setState((prevState) => ({ inputValue: prevState.inputValue.slice(0, -1) })) }, clearInput: () => { this.setState({inputValue: ''}) }, }; calculate = () => { try { let result = eval(this.state.inputValue).toString(); this.props.addHistoryItem(this.state.inputValue, result); this.setState({ result: result, inputValue: result }) } catch (error) { this.props.setMessage('error', 'Une erreur est survenue lors de votre calcul') } }; render() { return ( <div id='calculator'> <Screen state={this.state} keyEvent={this.keyEvent} /> <Keyboard keys={this.keys} inputMethods={this.inputMethods} calculate={this.calculate} /> </div> ); } } export default Calculator;