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
Ruby
UTF-8
1,233
3.71875
4
[]
no_license
def minilang(str) stack = [] register = 0 str.split(' ').each do |command| begin case command when /\d+/ register = command.to_i when 'PUSH' stack.push register when 'POP' register = stack.pop when 'ADD' register += stack.pop when 'SUB' register -= stack.pop when 'MULT' register *= stack.pop when 'DIV' register /= stack.pop when 'MOD' register = register % stack.pop when 'PRINT' puts register else raise ArgumentError.new("'#{command}' is an invalid command.") end rescue Exception => error puts "Ugh oh. Something went wrong: #{error.message}" end end nil end ## Examples minilang('PRINT') # 0 minilang('5 PUSH 3 MULT PRINT') # 15 minilang('5 PRINT PUSH 3 PRINT ADD PRINT') # 5 # 3 # 8 minilang('5 PUSH POP PRINT') # 5 minilang('3 PUSH 4 PUSH 5 PUSH PRINT ADD PRINT POP PRINT ADD PRINT') # 5 # 10 # 4 # 7 minilang('3 PUSH PUSH 7 DIV MULT PRINT ') # 6 minilang('4 PUSH PUSH 7 MOD MULT PRINT ') # 12 minilang('-3 PUSH 5 SUB PRINT') # 8 minilang('6 PUSH') # (nothing printed; no PRINT commands) minilang('FNORD') # minilang('POP DIV')
Markdown
UTF-8
2,313
2.703125
3
[]
no_license
--- layout: post title: "刷新本地DNS缓存的方法" date: 2012-08-31 19:09:00 author: 司徒正美 categories: program --- ## 刷新本地DNS缓存的方法 ### by 司徒正美 ### at 2012-08-31 19:09:00 ### original <http://www.cnblogs.com/rubylouvre/archive/2012/08/31/2665859.html> <p>常有人问到域名解析了不是即时生效的嘛,怎么还是原来的呢?答案就是在本地DNS有解析缓存,电脑第一次访问后,在一定的时间内就将其缓存下来,下次访问该域名时电脑通过查找本地DNS缓存,就可以直接知道IP了,而不用再进行域名解析了,这就提高了效率,这就是DNS缓存,而域名更改过解析后,虽然DNS服务器上已经更新,但本地还有DNS缓存,造成还是老的IP,可以通过下面的方法来解决:</p><p><strong>刷新DNS缓存的方法一</strong>:</p><p>首先进入命令提示符下(开始——运行——cmd);</p><p>先运行:ipconfig /displaydns这个命令,查看一下本机已经缓存了那些的dns信息的,然后输入下面的命令</p><p>ipconfig /flushdns</p><p>这时本机的dns缓存信息已经清空了,我们可以再次输入第一次输入的命令来看一下,</p><p>ipconfig /displaydns</p><p><strong>刷新DNS缓存的方法二</strong>:</p><p>直接禁用网卡再启用网卡,这样也可以</p><p> </p><div><p><font face="楷体_GB2312" size="4"><strong>学习查看域名ns解析,发现一个简单的命令即可解决,当然首先要确认你的网络正常。<br><br><span>步骤</span>:<br><br>开始--运行,输入cmd,然后键入以下命令,如<br><br>nslookup -q=ns baidu.com<br><br>或者<br><br>nslookup -qt=ns baidu.com<br><br><br><span><span>注意:域名这里要输入根域名,而不是二级域名。</span></span><br><br><br>以下是查看百度的域名dns信息:<br></strong></font></p><font face="楷体_GB2312" size="4"><strong>baidu.com       nameserver = ns3.baidu.com<br>baidu.com       nameserver = ns2.baidu.com<br>baidu.com       nameserver = ns4.baidu.com</strong></font><img src="http://www.cnblogs.com/rubylouvre/aggbug/2665859.html?type=1" width="1" height="1" alt=""><p><a href="http://www.cnblogs.com/rubylouvre/archive/2012/08/31/2665859.html">本文链接</a></p></div>
Java
UTF-8
532
2.21875
2
[ "Apache-2.0" ]
permissive
/** * */ package org.nick.wwwjdic.utils; import android.content.Context; import android.content.Intent; import android.text.style.ClickableSpan; import android.view.View; public class IntentSpan extends ClickableSpan { private Context context; private Intent intent; public IntentSpan(Context context, Intent intent) { this.context = context; this.intent = intent; } @Override public void onClick(View widget) { context.startActivity(intent); } }
C++
UTF-8
2,581
3.203125
3
[ "ISC", "BSL-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <Annealer.hpp> #include <random> #include <catch.hpp> class LinearAnnealer : public simanneal_cpp::Annealer<double> { public: typedef simanneal_cpp::Annealer<double> super; LinearAnnealer(state_t const &initialState) : super(initialState, getEnergy(initialState)), m_gen(), m_randomDistribution(0.7, 1.4) { } public: static energy_t getEnergy(state_t const &state) { return std::abs(state * 0.5); } private: energy_t moveState(state_t &state) const override { state = state * m_randomDistribution(m_gen); return getEnergy(state); } private: mutable std::mt19937 m_gen; std::uniform_real_distribution<state_t> m_randomDistribution; }; TEST_CASE("Creating Annealer test", "[Annealer]") { LinearAnnealer annealer(40.0); CHECK(annealer.bestState() == 40.0); CHECK(annealer.bestEnergy() == LinearAnnealer::getEnergy(40.0)); } TEST_CASE("RunAnnealing tests", "[Annealer][runAnnealing]") { LinearAnnealer annealer(20.0); auto initialState = annealer.bestState(); auto initialEnergy = annealer.bestEnergy(); SECTION("zero steps") { annealer.runAnnealing(2, 1, 0, 0); CHECK(initialState == annealer.bestState()); CHECK(initialEnergy == annealer.bestEnergy()); } SECTION("many steps") { annealer.runAnnealing(1, 1e-2, 100, 0); CHECK(initialState != annealer.bestState()); // 100 steps with low temperature should be // enough to decrease energy CHECK(initialEnergy > annealer.bestEnergy()); } } TEST_CASE("computeRunSchedule tests", "[Annealer][computeRunSchedule]") { LinearAnnealer annealer(30.0); LinearAnnealer::run_schedule schedule1 = annealer.computeRunSchedule(0.02); LinearAnnealer::run_schedule schedule2 = annealer.computeRunSchedule(0.04); double stepsRatio = schedule2.steps / static_cast<double>(schedule1.steps); CHECK(stepsRatio == Approx(2.0).epsilon(0.3)); CHECK(schedule1.maxT == Approx(schedule2.maxT).epsilon(0.5)); CHECK(schedule1.minT == Approx(schedule2.minT).epsilon(0.5)); CHECK(schedule1.minT < schedule1.maxT); std::chrono::system_clock::duration startTime = std::chrono::system_clock::now().time_since_epoch(); annealer.runAnnealing(schedule2, 0); double elapsedMinutes = std::chrono::duration_cast<std::chrono::duration<double>>( std::chrono::system_clock::now().time_since_epoch() - startTime).count() / 60; CHECK(elapsedMinutes == Approx(0.04).epsilon(0.3)); }
Python
UTF-8
1,319
2.515625
3
[]
no_license
def generate_app(apps): apps.create('test', '/tmp', 20) def test_apps(apps): test_apps_app(apps) test_update(apps) test_delete(apps) test_reset(apps) test_clean(apps) def test_apps_app(apps): generate_app(apps) assert len(apps.get_all()) == 1 app = apps.get_all()[0] assert app assert apps.get('test') assert app == apps.get('test') assert app['name'] == 'test' assert app['path'] == '/tmp' assert app['max_count'] == 20 apps.delete('test') def test_update(apps): generate_app(apps) apps.update('test', '/tmp2', 15) assert len(apps.get_all()) == 1 app = apps.get_all()[0] assert app assert app['name'] == 'test' assert app['path'] == '/tmp2' assert app['max_count'] == 15 apps.delete('test') def test_delete(apps): generate_app(apps) apps.delete('test') assert len(apps.get_all()) == 0 assert not apps.get('test') apps.delete('test') def test_reset(apps): generate_app(apps) apps.reset() assert len(apps.get_all()) == 0 assert not apps.get('test') apps.reset() def test_clean(apps): generate_app(apps) apps.clean() assert len(apps.get_all()) == 0 assert not apps.get('test') apps.clean()
Java
UTF-8
3,085
2.34375
2
[]
no_license
package com.zw.malldemo.service.impl; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.zw.malldemo.cache.JedisUtil; import com.zw.malldemo.dao.HeadLineDao; import com.zw.malldemo.entity.HeadLine; import com.zw.malldemo.exceptions.HeadLineOperationException; import com.zw.malldemo.service.HeadLineService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; @Service public class HeadLineServiceImpl implements HeadLineService { @Autowired private HeadLineDao headLineDao; @Autowired private JedisUtil.Keys jedisKeys; @Autowired private JedisUtil.Strings jedisStrings; private static Logger logger= LoggerFactory.getLogger(HeadLineServiceImpl.class); @Override @Transactional public List<HeadLine> getHeadLineList(HeadLine headLineCondition) { // 定义redis的key前缀 String key=HLLISTKEY; // 定义接收对象 List<HeadLine> headLineList = null; // 定义jackson数据转换操作类 ObjectMapper mapper=new ObjectMapper(); // 拼接出redis的key if(headLineCondition!=null && headLineCondition.getEnableStatus()!=null){ key = key + "_" + headLineCondition.getEnableStatus(); } // 判断key是否存在 if(!jedisKeys.exists(key)){ // 若不存在,则从数据库里面取出相应数据 headLineList=headLineDao.queryHeadLineByCondition(headLineCondition); // 将相关的实体类集合转换成string,存入redis里面对应的key中 String jsonString; try { jsonString=mapper.writeValueAsString(headLineList); } catch (JsonProcessingException e) { e.printStackTrace(); logger.error(e.getMessage()); throw new HeadLineOperationException(e.getMessage()); } jedisStrings.set(key,jsonString); }else { // 若存在,则直接从redis里面取出相应数据 String jsonString = jedisStrings.get(key); // 指定要将string转换成的集合类型 JavaType javaType=mapper.getTypeFactory().constructParametricType(ArrayList.class, HeadLine.class); try { // 将相关key对应的value里的的string转换成对象的实体类集合 headLineList=mapper.readValue(jsonString,javaType); } catch (JsonProcessingException e) { e.printStackTrace(); logger.error(e.getMessage()); throw new HeadLineOperationException(e.getMessage()); } } return headLineList; } }
Markdown
UTF-8
2,853
3.1875
3
[ "MIT" ]
permissive
--- title: My Jest Mock Calls Are Missing Data. Now What? desc: Let me save you some time. I spent hours debugging this and another 20 minutes writing up a draft Stack Overflow question before the answer came to me. img: /img/2021/dumbbell.jpg date: 2021-06-03 tags: - learning in public - testing - jest - async --- Yesterday I had an altogether too familiar experience. I spent several hours debugging, and once I believed that the answer was beyond me, I started drafting an explanation and code samples that would eventually become a Stack Overflow question. After 20 minutes of explaining the problem to my hypothetical Stack Overflow helpers, the answer came to me. https://twitter.com/AdamTuttle/status/1400201226625691652 I've already spoiled the solution above, but what was the problem, and how can I share that knowledge in a way to help others who might run into the same situation? - I'm using [Jest][jest] for testing some JavaScript code - The code uses fetch to make HTTP requests, and I'm mocking fetch to make those requests controllable and fast - It appeared that fetch requests _that I knew were happening!_ weren't showing up in the `fetch.mock.calls` array. Wait, what? How can I know that the calls were made and also not see them in the `fetch.mock.calls` array? Well, my mock looks like this: ```js/1 fetch.mockResponse(async (req) => { console.log(req.url); if (req.url === '...') { return JSON.stringify( /* ... */ ); } }); ``` As my test ran, I could see about half a dozen HTTP requests logged by the `console.log` statement. Ok, great, but... ```js/3 const thingDoer = require('./thingDoer'); it('does the thing', () => { thingDoer(); console.log(fetch.mock.calls); expect(fetch).toHaveBeenCalledWith( /* ... */ ); }); ``` How is it, then, that the `console.log` in the test shows only 1 call in the array?! Well, maybe you've already guessed it from the spoiler in the tweet, but the answer was as simple as a missing `await`. Specifically, the `thingDoer` method is async and returns a promise. Since I wasn't awaiting that promise, `thingDoer` returned early and I was running my `console.log` and expectations _while it was still running_. That explains why the log of `fetch.mock.calls` had less data than I could see in the individual logs for each request... they hadn't been made **yet**. Making my test async and awaiting `thingDoer` solved it. ```js/2 const thingDoer = require('./thingDoer'); it('does the thing', async () => { await thingDoer(); expect(fetch).toHaveBeenCalledWith( /* ... */ ); }); ``` Hopefully this helps someone else out there going nuts because things that they can see happening aren't in the list of things that happened. But let's be realistic. It'll be me referring to this article again in 9 months. 🤷‍♂️ [jest]: https://jestjs.io
JavaScript
UTF-8
671
2.890625
3
[ "MIT" ]
permissive
async function commentFormHandler(event) { event.preventDefault(); const comment_text = event.target.querySelector("#comment-body").value.trim(); const offer_id = parseInt(event.target.getAttribute("data-offer-id")); if (comment_text) { const response = await fetch("/api/comments", { method: "POST", body: JSON.stringify({ offer_id, comment_text, }), headers: { "Content-Type": "application/json" }, }); if (response.ok) { document.location.reload(); } else { alert(response.statusText); } } } document .querySelector("#offer-area") .addEventListener("submit", commentFormHandler);
Markdown
UTF-8
2,608
2.859375
3
[]
no_license
# Uninstall Code Ocean The following article describes the process of tearing down a Code Ocean private cloud deployment. ## Export Data Before uninstalling Code Ocean please make sure to preserve any required user generated content in the system. *Uninstalling Code Ocean will delete all data in the system.* To preserve your data, please follow instructions to [export your capsules](https://docs.codeocean.com/onboarding/v/v0.10/faq/faq-general#how-to-export-capsules-and-reproduce-results-on-my-local-machine) [and download your data assets](https://docs.codeocean.com/onboarding/v/v0.10/data-assets-guide/viewing-and-editing-data-assets) (including results) via your Code Ocean application ## Uninstall Steps 1. Unprotect AWS Resources To prevent users from accidently deleting their own data, Pulumi lets us to flag resources as `protected`. A protected resource cannot be destroyed without first removing the protection flag. The following script removes the Pulumi protection flag from Code Ocean persistent storage. ``` pulumi stack export | jq '.deployment.resources[]|select(contains({protect:true})).urn' | xargs -n1 -t pulumi state unprotect -y ``` 2. Empty S3 Buckets During teardown Pulumi needs to empty S3 buckets before deleting them but this is often slow and can lead to a timeout for the entire teardown process. We therefore recommend to empty S3 buckets before initiating a `pulumi destroy`. The following script empty the datasets and access-logs buckets. ``` mkdir /tmp/empty aws s3 sync --delete "/tmp/empty" s3://`pulumi stack export | jq -r '.deployment.resources[]|select(contains({type:"aws:s3/bucket:Bucket",urn:"access-logs"})).id'` aws s3 sync --delete "/tmp/empty" s3://`pulumi stack export | jq -r '.deployment.resources[]|select(contains({type:"aws:s3/bucket:Bucket",urn:"datasets"})).id'` ``` 3. Purge Backup Vault The AWS Backup vault holds your Code Ocean deployment's data volume snapshots. The following shell script deletes all vault recovery points: ``` set -e VAULT_NAME=`pulumi stack export | jq -r '.deployment.resources[]|select(.type == "aws:backup/vault:Vault").id'` for ARN in $(aws backup list-recovery-points-by-backup-vault --backup-vault-name "${VAULT_NAME}" --query 'RecoveryPoints[].RecoveryPointArn' --output text); do echo "deleting ${ARN} ..." aws backup delete-recovery-point --backup-vault-name "${VAULT_NAME}" --recovery-point-arn "${ARN}" done ``` 4. Pulumi Destroy Delete all AWS resources: ``` pulumi destroy ```
Java
UTF-8
1,440
2.359375
2
[]
no_license
package com.sso.yt.commons.utils; import org.junit.Test; /** * Created by yt on 2017-7-10. */ public class UnderlineToCamelUtilsTest { @Test public void underlineToCamel() throws Exception { String s="user_id"; LogUtils.LOGGER.info(UnderlineToCamelUtils.underlineToCamel(s,true)); LogUtils.LOGGER.info(UnderlineToCamelUtils.parseToCamel(s)); s="user_id@name"; LogUtils.LOGGER.info(UnderlineToCamelUtils.underlineToCamel(s,true)); LogUtils.LOGGER.info(UnderlineToCamelUtils.parseToCamel(s)); s="user_id@name_TAO_bao"; LogUtils.LOGGER.info(UnderlineToCamelUtils.underlineToCamel(s,true)); LogUtils.LOGGER.info(UnderlineToCamelUtils.parseToCamel(s)); } @Test public void camelToUnderline() throws Exception { String s="userIdName"; LogUtils.LOGGER.info(UnderlineToCamelUtils.camelToUnderline(s,true)); LogUtils.LOGGER.info(UnderlineToCamelUtils.parseToUnderline(s)); s="user_IdName"; LogUtils.LOGGER.info(urlConversion(s)); LogUtils.LOGGER.info(UnderlineToCamelUtils.camelToUnderline(s,true)); LogUtils.LOGGER.info(UnderlineToCamelUtils.parseToUnderline(s)); s="user_Id@Name"; LogUtils.LOGGER.info(urlConversion(s)); LogUtils.LOGGER.info(UnderlineToCamelUtils.camelToUnderline(s,true)); LogUtils.LOGGER.info(UnderlineToCamelUtils.parseToUnderline(s)); } private String urlConversion(String str) { str = str.replace("_", "@"); return UnderlineToCamelUtils.parseToUnderline(str); } }
JavaScript
UTF-8
312
3.03125
3
[]
no_license
function counter() { var counter = document.createElement('div'); counter.innerHTML = 1; counter.setAttribute('id', 'counter'); counter.onclick = function() { counter.innerHTML = parseInt(counter.innerHTML, 10) + 1; } document.body.appendChild(counter); } export default counter;
C
UTF-8
297
3.265625
3
[]
no_license
#ifndef __BUBBLE_SORT__ #define __BUBBLE_SORT__ void bubble_sort(int a[], int last) { int i, j = 0; int tmp = 0; for (i = last; i >= 1; i--) { for (j = 0; j < i; j++) { if (a[j] > a[j + 1]) { tmp = a[j + 1]; a[j + 1] = a[j]; a[j] = tmp; } } } return; } #endif
C++
UTF-8
2,559
2.859375
3
[ "LicenseRef-scancode-public-domain" ]
permissive
/* Aereo di Daniele Prototipo: F8 Bearcat Output: 2 LED PWM ai lati con lampeggio alternato 2 LED PWM alle estremita ali Input: 2 interrupts per th e alettone PIN 2: alettone PIN 3: throttle PIN A1: interruttore On/Off TODO * Vedere la calibrazione automatica * Min e max a 1000 - 2000 per alettone */ #include <common.h> # define DEBUG // Instanziamo un LED fuori dal loop Lampeggiatore left = 6; Lampeggiatore right = 9; Lampeggiatore codasx = 5; Lampeggiatore codadx = 10; //Pwm pleft = 6; //Pwm pright = 9; //Pwm pcodasx = 5; //Pwm pcodadx = 10; // Variabili per interrupt 0 si PIN 2 volatile unsigned int chValue2 = 1500; // Valore computato volatile unsigned int chStart2 = 1500; // Inizio rilevamento // Variabili per interrupt 1 su PIN 3 volatile unsigned int chValue3 = 1500; // Valore computato volatile unsigned int chStart3 = 1500; // Inizio rilevamento const byte chPin = A1; // PIN interruttore generale // Variabili per autocalibrazione 0 const byte chPin2 = 2; // PIN per la calibrazione alettone int mid_point2 = 1500; // Variabili per autocalibrazione 1 const byte chPin3 = 3; // PIN per la calibrazione int mid_point3 = 1000; void setup() { // I PINs vengono impostati dal constructor al momento // della dichiarazione dell'ogetto. right.Invert(); codadx.Invert(); // HI -> LOW --> LOW -> HI // per avere 2 LED che lampeggiano alternativamente // Funzione relativa a calibrazione con pulsein: //mid_point2 = calibraTrim(chPin2) ; // Calibrazione del TRIM attivo sul canale //mid_point3 = calibraTrim(chPin3) ; // Calibrazione del TRIM attivo sul canale attachInterrupt(0, chRise2, RISING); // PIN 2 su 328p / 168 attachInterrupt(1, chRise3, RISING); // PIN 3 su 328p / 168 #ifdef DEBUG Serial.begin(9600); #endif } void loop() { left.Blink(300); right.Blink(300); codasx.Blink(); codadx.Blink(); #ifdef DEBUG Serial.print("PIN2: "); Serial.print(chValue2); Serial.print(" -base: "); Serial.print(mid_point2); Serial.print(" |-| PIN3:"); Serial.print(chValue3); Serial.print(" -base: "); Serial.println(mid_point3); delay(200); #endif } // Functions void chRise2() { attachInterrupt(0, chFall2, FALLING); chStart2 = micros(); } void chFall2() { attachInterrupt(0, chRise2, RISING); chValue2 = micros() - chStart2; } // Seconod iterrupt void chRise3() { attachInterrupt(1, chFall3, FALLING); chStart3 = micros(); } void chFall3() { attachInterrupt(1, chRise3, RISING); chValue3 = micros() - chStart3; }
C
UTF-8
279
3.390625
3
[]
no_license
int ft_str_is_uppercase(char *str); int ft_str_is_uppercase(char *str) { int i; int count_upper; i = 0; count_upper = 0; while (str[i] != '\0') { if (str[i] >= 'A' && str[i] <= 'Z') count_upper++; i++; } if (count_upper == i) return (1); else return (0); }
Markdown
UTF-8
1,097
3.46875
3
[]
no_license
# 经典题目 > 多线程交替输出12 # 题解 主要思路就是加锁。 ```java package pers.jssd.test; /** * 两个线程交替输出12121212 * * @author wangjingjing@bonc.com.cn * @date 2021/1/6 10:04 */ public class Test01 { public static void main(String[] args) { new Test01().result(); } public void result() { new Thread(new Run(1, this)).start(); new Thread(new Run(2, this)).start(); } static class Run implements Runnable { private int count; private Object lock; public Run(int count, Object lock) { this.count = count; this.lock = lock; } @Override public void run() { while (true) { synchronized (lock) { try { lock.notify(); lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count); } } } } } ```
Markdown
UTF-8
962
2.671875
3
[]
no_license
# Cenário 031 - Criar vídeos sob demanda ## Título * Criar vídeos sob demanda. ## Objetivo * Arquivar um vídeo transmitido anteriormente para que os seguidores do [Streamer](Streamer) possa assistir vídeos perdidos. ## Contexto * O [streamer](Streamer) deseja salvar vídeos para aumentar a popularidade do seu canal. ## Ator(es) * [Streamer](Streamer). * [Viewer](Viewer). ## Recursos * Computador * Internet ## Exceções * [Usuário](User) não estar conectado à internet. ## Episódios * [Streamer](Streamer) entra na sua conta Twitch. * [Streamer](Streamer) vai até o seu painel de controle na página principal do Twitch. * [Streamer](Streamer) clica em configurações. * [Streamer](Streamer) clica na caixa de seleção “Store Past Broadcasts”. * Twitch salva todos os vídeos do streamer por um tempo limitado. Referência: [Videos sob demanda](https://help.twitch.tv/customer/pt_br/portal/articles/1575302-v%C3%ADdeos-sob-demanda)
Python
UTF-8
4,081
3.65625
4
[ "MIT" ]
permissive
# Prompt: # Create a reservation system which books airline seats or hotel rooms. # It charges various rates for particular sections of the plane or hotel. # Example, first class is going to cost more than coach. # Hotel rooms have penthouse suites which cost more. # Keep track of when rooms will be available and can be scheduled. import re # Define an airplane class. Need a list of seats, need a price of seats, and should have tiers of prices (dict) tiers = ('Economy', 'Business', 'First') tier_prices = {'Economy': 100, 'Business': 200, 'First': 500} # Only works with easy numbers, need to figure out an algo for different numbers for added complexity econ_ratio = 0.7 bus_ratio = 0.2 first_ratio = 0.1 #assign variables for plane sizes for testing purposes. Will try to implement user input in future. # Currently only works with multiples of 10. Will try to implement a more complex system for any int space_large = 240 space_medium = 120 space_small = 30 space_bush = 10 class Airplane: def __init__(self, number_of_seats): self.available_seats = [] self.booked_seats = [] self.number_of_seats = number_of_seats self.econ_seat_count = num_of_seat_tier(self.number_of_seats, econ_ratio) self.bus_seat_count = num_of_seat_tier(self.number_of_seats, bus_ratio) self.bus_and_econ_seat_count = self.econ_seat_count + self.bus_seat_count self.first_seat_count = num_of_seat_tier(self.number_of_seats, first_ratio) for tier in tiers: if tier == 'Economy': for i in range(0, self.econ_seat_count): self.available_seats.append([f"Seat {i+1}",Seat(tier)]) elif tier == 'Business': for i in range(self.econ_seat_count, (self.bus_seat_count + self.econ_seat_count)): self.available_seats.append([f"Seat {i+1}",Seat(tier)]) else: # tier == 'First' for i in range(self.bus_and_econ_seat_count, (self.first_seat_count + self.bus_and_econ_seat_count)): self.available_seats.append([f"Seat {i+1}",Seat(tier)]) def __repr__(self): return f'Airplane({self.number_of_seats!r})' def __str__(self): return "This airplane has {} seats.".format(len(self.available_seats)) def book_seat(self): seat_to_book = input("Please select a seat to book. (ex. 'Seat 1')") for seat in self.available_seats: if len(self.booked_seats) > 0 and seat_to_book in self.booked_seats[0]: print("Sorry, this seat is already booked.") break elif seat_to_book == seat[0]: self.booked_seats.append(seat) self.available_seats.remove(seat) Seat.seat_booked(seat[1]) break class Seat: def __init__(self, tier, booked=False): self.tier = tier self.booked = booked def __repr__(self): return f'Seat({self.tier!r},{self.booked!r})' def __str__(self): if not self.booked: return f"This seat is tier {self.tier} and is available" else: return f"This seat is tier {self.tier} and is already booked" def seat_value(self): self.value = tier_prices[self.tier] if not self.booked: return f"This seat costs ${self.value}.00 and is available" else: return f"This seat costs ${self.value}.00 and is already booked" def seat_booked(self): self.booked = True # This is a helper function for calculating the number of seats by ratio. hopefully can edit to allow situations for more # complex seat amounts def num_of_seat_tier(seats, ratio): return int(seats * ratio) def main(): bushplane = Airplane(space_bush) large = Airplane(space_large) med = Airplane(space_medium) bushplane.book_seat() if __name__ == "__main__": main() print(bushplane.booked_seats)
Python
UTF-8
9,130
2.640625
3
[]
no_license
import tensorflow as tf from tensorflow.python.framework import ops import numpy as np def firstExample(): from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) y = tf.matmul(x,W) + b cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_)) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(1000): batch = mnist.train.next_batch(100) train_step.run(feed_dict={x: batch[0], y_: batch[1]}) correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})) def tensorflowExample(): from tensorflow.examples.tutorials.mnist import input_data def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def activation(x): # return tf.nn.relu(x) return re_sinh_module.re_sinh(x) mnist = input_data.read_data_sets('MNIST_data', one_hot=True) x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) x_image = tf.reshape(x, [-1,28,28,1]) # -------------------------------------------------------- h_conv1 = activation(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) # -------------------------------------------------------- W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = activation(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) # -------------------------------------------------------- W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = activation(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # -------------------------------------------------------- keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # -------------------------------------------------------- W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 # -------------------------------------------------------- cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(5000): batch = mnist.train.next_batch(50) if i%100 == 0: train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0}) print("step %d, training accuracy %g"%(i, train_accuracy)) print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) def loopTest(): # Define a single queue with two components to store the input data. q_data = tf.FIFOQueue(100000, [tf.float32, tf.float32]) # We will use these placeholders to enqueue input data. placeholder_x = tf.placeholder(tf.float32, shape=[None]) placeholder_y = tf.placeholder(tf.float32, shape=[None]) enqueue_data_op = q_data.enqueue_many([placeholder_x, placeholder_y]) gs = tf.Variable(0) w = tf.Variable(0.) b = tf.Variable(0.) optimizer = tf.train.AdamOptimizer(0.05) # Construct the while loop. def cond(i): return i < 10000 def body(i): # Dequeue a single new example each iteration. x, y = q_data.dequeue() # Compute the loss and gradient update based on the current example. loss = (tf.add(tf.multiply(x, w), b) - y)**2 train_op = optimizer.minimize(loss) # Ensure that the update is applied before continuing. with tf.control_dependencies([train_op]): return i + 1 loop = tf.while_loop(cond, body, [tf.constant(0)]) data = [k*1. for k in range(10000)] with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for _ in range(1): # NOTE: Constructing the enqueue op ahead of time avoids adding # (potentially many) copies of `data` to the graph. sess.run(enqueue_data_op, feed_dict={placeholder_x: data, placeholder_y: data}) print sess.run([gs, w, b]) # Prints before-loop values. sess.run(loop) print sess.run([gs, w, b]) # Prints after-loop values. def myConvTest(): my_conv_module = tf.load_op_library('../tensorflow/bazel-bin/tensorflow/core/user_ops/my_conv.so') @ops.RegisterGradient("MyConv") def _my_conv_grad(op, grad): x = op.inputs[0] w_out = op.inputs[1] w_in = op.inputs[2] b = op.inputs[3] w_c = op.inputs[4] alpha = tf.reduce_prod(w_out,keep_dims=True) beta = tf.reduce_prod(w_in,1,keep_dims=True) gamma = x+tf.reshape(tf.reduce_sum(tf.div(b,w_in),axis=0,keep_dims=True),x.get_shape()) delta = tf.matmul(w_in,x)+b ones = tf.Variable(np.ones(x.get_shape()),dtype=tf.float32) gamma_pow_2hp1 = tf.pow(gamma,(2*h+1)*ones) gamma_pow_2h = tf.pow(gamma,2*h*ones) reluCond = tf.greater(delta,0) w_ok_a = tf.nn.relu(delta) w_ik_a = tf.cond(reluCond,tf.multiply(x,w_out),tf.zeros([x.get_shape()[0],w_out.get_shape()[1]])) b_k_a = tf.cond(reluCond,w_out,tf.zeros(w_out.get_shape())) w_c_a = alpha w_ok_b = alpha*w_c/w_out w_ik_b = alpha*w_c/w_in*beta b_k_b = w_c*(2*h+1)*alpha w_c_b = reduce_sum(beta*gamma_pow_2hp1) w_ok_c = w_c_b w_ik_c = (2*h+1)*b/w_in*gamma_pow_2h b_k_c = reduce_sum(beta/w_in*gamma_pow_2hp1) w_ik_d = gamma_pow_2hp1-w_ik_c d_w_ok = w_ok_a*w_ok_b*w_ok_c d_w_ik = w_ik_a*w_ik_b*w_ik_c*w_ik_d d_b_k = b_k_a*b_k_b*b_k_c d_w_c = w_c_a*w_c_b # check that this is correct assert 0 return [ans] x = tf.Variable([[1],[3]],dtype=tf.float32) w_in = tf.Variable([[1,2],[3,0.6],[3,6]],dtype=tf.float32) w_out = tf.Variable([[1.5,1.5,1.2]],dtype=tf.float32) b = tf.Variable([[1.3],[1.2],[7]],dtype=tf.float32) w_c = tf.Variable([0.001],dtype=tf.float32) y = my_conv_module.my_conv(x,w_out,w_in,b,w_c) # tf.gradients(y,w_in) y_1 = tf.matmul(w_in,x) y_2 = y_1+b y_3 = tf.nn.relu(y_2) y_4 = tf.matmul(w_out,y_3) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print('\n\ny: '+str(sess.run(y))) print('\n\n\nx: '+str(sess.run([x]))) print('\nw_in: '+str(sess.run([w_in]))) print('\nw_out: '+str(sess.run([w_out]))) print('\nb: '+str(sess.run([b]))) print('\ny_1: '+str(sess.run([y_1]))) print('\ny_2: '+str(sess.run([y_2]))) print('\ny_3: '+str(sess.run([y_3]))) print('\ny_4: '+str(sess.run([y_4]))) myConvTest()
C++
UTF-8
3,537
2.890625
3
[]
no_license
#ifndef DEVICEFINDER_H #define DEVICEFINDER_H #include "interface/IfceSerialFinder.h" #include <QSerialPortInfo> #include <QSerialPort> /** * @brief The DeviceFinder class is responsible for finding serial devices. * * The class seeks for available serial devices. When discovered, it connects * to each other (one by one) and attempts to read the data. Received * data is then parsed with a {@link IfceDevice} that is created by * an instance of {@link IfceDeviceFactory}. The parsing step is of utmost * importance in the initial booting of the system. It allows assinging the serial * device to its model. The model then handles proper data parsing. */ class DeviceFinder : public IfceSerialFinder { Q_OBJECT public: explicit DeviceFinder(IfceDeviceFactory *factory, QObject *parent = nullptr); ~DeviceFinder(); /** * @brief discover Discovers devices based on parsing data engine implemented in {@link IfceDevice} * @return List of found devices */ QList<QSharedPointer<IfceDevice>> discover() override; /** * @brief setSerialSettings Sets serial-related settings. If none is set, default is loaded. * @param settings */ void setSerialSettings(QSharedPointer<IfceSerialSettings> settings); protected: /** * @brief run_serial Runs action of the serial * Runs action of the serial. It tries to identify the ID of the device * based on a single line received from it. * @param serialInfo Information about serial port the method connects to. * @return Instance of {@link SerialDeviceIfce}. If the method cannot create * an instance, returns an empty QSharedPointer */ QSharedPointer<IfceDevice> run_serial(const QSerialPortInfo &serialInfo); private: static const char READ_LINE_ERR_MSG[]; QScopedPointer<IfceDeviceFactory> factory; QSharedPointer<IfceSerialSettings> settings; /** * @brief open_serial Opens serial. * Opens serial. Emits a {@link serialError()} if cannot establish a connection. * Returns appropriate bool values * @param serial Reference to the instance of QSerialPort * @return True if connection is established. False otherwise. */ bool open_serial(QSharedPointer<QSerialPort> &serial); /** * @brief wait_for_connection Waits for connection * Waits for connection for {@link SerialSettings::getWaitForReadLineMs()} period of time * @param serial Reference to the instance of QSerialPort * @return True if new data is available. False if an error occured or timeout. */ bool wait_for_connection(QSharedPointer<QSerialPort> &serial); /** * @brief wait_for_read_line Waits for opportunity to read a line. * The method is responsible for reading a line that is essential in * a protocol implementation. See system documentation for more details. * It waits for {@link SerialSettings::instance()->getWaitForReadLineMs()} period of time. * @param serial Reference to the instance of QSerialPort * @return True if reading of a line is successful. False otherwise. */ bool wait_for_read_line(QSharedPointer<QSerialPort> &serial); /** * @brief handle_error_msg Helper method * @param serial Reference to the instance of QSerialPort * @param msg Error message * @return Empty QSharedPointer<SerialDeviceIfce> */ QSharedPointer<IfceDevice> handle_error_msg(QSharedPointer<QSerialPort> &serial, const QString &msg); }; #endif // DEVICEFINDER_H
C++
UTF-8
1,007
3.59375
4
[ "MIT" ]
permissive
#include<iostream> /** * 初始化不是赋值,而是创建变量时赋予一个初始值,而赋值的含义是把当前值换成另外一个值 * * 程序代码描述:定义一个名为units_sold的int型变量并初始化为0 * * @return [description] */ int main() { //C++11新标准中,使用花括号来初始化变量得到全面的应用,也叫做列表初始化 int units_sold = 0; int units_sold1(0); int units_sold2 {0}; int units_sold3 = {0}; printf("%d \n", units_sold); printf("%d \n", units_sold1); printf("%d \n", units_sold2); printf("%d \n", units_sold3); //当用于内置类型的变量时,如果我们使用列表初始化将会有可能产生丢失信息的风险 long double ld = 3.1415926536; int a{ld}, b = {ld}; //错误:转换未执行,因为存在丢失信息的风险,这里编译器将会爆出警告 int c(ld), d = ld; //正确:转换执行,且确实丢失了部分信息 printf("%d\n", a); return 0; }
C#
UTF-8
2,898
3.0625
3
[]
no_license
using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace Screens.Hosting { public class BufferManager { public Terminal Terminal { get; } public Buffer CurrentBuffer { get; private set; } public Buffer LastBuffer { get; private set; } public BufferManager(Terminal terminal) { Terminal = terminal; } public TerminalChanges GetChanges() { // get changed lines in buffer to the context (console or terminal) var changes = new TerminalChanges(); var xs = 0; var ys = 0; while (ys < CurrentBuffer.Height) { if (IsLineChanged(CurrentBuffer, LastBuffer, ys)) { var line = changes.AddLine(ys); xs = 0; var str = new System.Text.StringBuilder(); var cur_fore = CurrentBuffer[xs, ys].ForeColor; var cur_back = CurrentBuffer[xs, ys].BackColor; var cur_x = 0; while (xs < CurrentBuffer.Width) { var buf_char = CurrentBuffer[xs, ys]; if (buf_char.ForeColor != cur_fore || buf_char.BackColor != cur_back) { line.AddSpan(str.ToString(), cur_fore, cur_back, cur_x); str = new System.Text.StringBuilder(); cur_fore = buf_char.ForeColor; cur_back = buf_char.BackColor; cur_x = xs; } str.Append(buf_char.Ch); xs += 1; } line.AddSpan(str.ToString(), cur_fore, cur_back, cur_x); } ys += 1; } return changes; } public void AcceptChanges() { LastBuffer = (Buffer)CurrentBuffer.Clone(); } private static bool IsLineChanged(Buffer a, Buffer b, int y) { if (b == null || a == null) return true; var x = 0; while (x < a.Width) { if (a[x, y] != b[x, y]) return true; x += 1; } return false; } public void ResetBuffer(Size size) { if (CurrentBuffer == null || CurrentBuffer.Size != size) { CurrentBuffer = new Buffer(size); LastBuffer = new Buffer(size); } else { LastBuffer.Clear(); CurrentBuffer.Clear(); Terminal.Clear(); } } } }
C++
UTF-8
457
2.6875
3
[]
no_license
#pragma once #include "GameObject.h" //Actually used as a player class but renaming it will cause chaos in other files. //The "ball" (player) is capable of moving in all 4 directions and has an associated collision box. //This is used in the dodgeball game. class GameObjectBall : public GameObject { public: //A default constructor to set up basics. GameObjectBall(); //Allows updating movement and collision box position. void tick(double delta); };
Python
UTF-8
1,946
2.703125
3
[]
no_license
from flask import flash, Flask, render_template, request import requests import sqlite3 from flask_mail import Mail, Message app = Flask(__name__) app.secret_key = "super secret key" app.config['MAIL_SERVER']='smtp.gmail.com' app.config['MAIL_PORT'] = 465 #mail id and password fields can be filled up and execution can be checked. app.config['MAIL_USERNAME'] = '<<mail id to send mails from>>' app.config['MAIL_PASSWORD'] = '<<password>>' app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True mail = Mail(app) @app.route('/', methods = ['GET', 'POST']) def enlist(): conn = sqlite3.connect('products') print ("Opened database successfully") conn.row_factory = sqlite3.Row cur = conn.cursor() cur.execute("select * from products order by product_id") rows = cur.fetchall() if request.method == 'POST': search_string = request.form.get("name") conn = sqlite3.connect('products') conn.row_factory = sqlite3.Row cur = conn.cursor() cur.execute("select * from products where product_name='"+search_string+"';") search_data = cur.fetchall() if search_data != []: return render_template("enlist.html", rows=rows, search_data = search_data[0]) return render_template("enlist.html", rows = rows) @app.route('/mailer', methods = ['GET', 'POST']) def mailer(): if request.method=="POST": mail_id = request.form.get("mail_id") msg = Message('Hello', sender = 'clubdanfann@gmail.com', recipients = [mail_id]) product_id=request.form["product_id"] product_name=request.form["product_name"] price=request.form["price"] msg.body = "The product you are intrested in is " + product_name +". It costs "+ price+" rupees. The unique id for the product is "+product_id mail.send(msg) return "Mail sent. Click <a href = '/'> here</a> to go back to home page." if __name__ == "__main__": app.run()
JavaScript
UTF-8
1,307
3.765625
4
[]
no_license
//this is an array which contains two objects!!!! var cars = [ { company: "honda", colors: [ { name: "burntRed", }, { name: "springGreen", }, ], }, { company: "ford", colors: [ { name: "burntOrange", }, { name: "black", }, ], }, ]; for(var i=0;i<cars.length;i++){ var car=cars[i]; for(var j=0;j<car.length;j++){ console.log(car[j]) } } var teamMembers = [ { Region: "east", Members: [ { id: 1, name: "rekha"}, { id: 2, name: "gopi" } ] }, { Region: "west", Members: [ { id: 1, name: "keerthi"}, { id: 2, name: "koti" } ] }, { Region: "north", Members: [ { id: 1, name: "sruthi"}, { id: 2, name: "hanumantha rao" } ] } ]; for(teamMembersGroup of teamMembers){ for(team of teamMembersGroup.Members){ if(team.id==1){ console.log(team.name)} } } for(team of teamMembers){ for(t of team.Members){ console.log(t) } } for(team of teamMembers){ console.log(team); if(team.length!=0){ console.log(team.Members) var teams=Object.entries(team) console.log(teams) } }
JavaScript
UTF-8
6,206
3.59375
4
[]
no_license
var externalContex = this; //window describe("(03) variables declaration: ", function () { it("without 'var', even inside a function, is global", function () { function defineGlobalFoo() { foo = "I'm global!"; } function callFoo() { return foo; } defineGlobalFoo(); expect(callFoo()).toEqual("I'm global!"); }); it("but with 'var', is scoped to the function", function () { delete foo; function defineFooWithVar() { var foo = "I'm global!"; } // does not exist at all expect(window['foo']).toBeUndefined(); }); it("this is how to check not defined variables", function () { // http://stackoverflow.com/questions/858181/how-to-check-a-not-defined-variable-in-javascript expect(typeof thisNotExist).toEqual('undefined'); expect(window['thisNotExist']).toBeUndefined(); }) }); describe("(03) hoisting:", function () { it("variables are always moved to the top", function () { function hoistedTrueFooVar() { if (true) { var fooHoisted = "fooHoisted"; } return fooHoisted; } expect(hoistedTrueFooVar()).toEqual("fooHoisted"); }); it("...even if not reached in runtime", function () { function hoistedFalseFooVar() { if (false) { var fooHoisted = "fooHoisted"; } return fooHoisted; } expect(hoistedFalseFooVar()).toEqual(undefined); }) }); describe("(03) closures:", function () { function outerScope(mustCall) { var outerVar = "outerVar"; function innerScope() { outerVar = "closure variable"; } if (mustCall) { innerScope(); } return outerVar; } it("without calling inner the var not change", function () { expect(outerScope(false), "outerVar"); }); it("but calling inner function, change outer variable", function () { expect(outerScope(true), "closure variable"); }); it("that is not global. Does not exist outside", function () { expect(typeof outerVar).toEqual('undefined'); }) }); describe("(03) immediate functions:", function () { it("you can point your function to a variable", function () { var myFunc = function () { var a = 1; expect(a).toEqual(1); }; myFunc(); }); it("but, to be immediate you have to call it", function () { (function () { var a = 1; expect(a).toEqual(1); })(); }) }); describe("(03) modules:", function () { it("this is a simple module that returns a string", function () { var myModule = (function () { var fooStr; function closureCall() { fooStr = "foo has a value"; } closureCall(); return fooStr; })(); expect(myModule).toEqual("foo has a value") }); it("they can have state", function () { var myModule = (function () { var fooObj = {}; fooObj.count = 0; fooObj.addCount = function () { fooObj.count += 1; }; return fooObj; })(); expect(myModule.count).toEqual(0); myModule.addCount(); expect(myModule.count).toEqual(1); myModule.addCount(); expect(myModule.count).toEqual(2); myModule.addCount(); expect(myModule.count).toEqual(3); }) it("its better to access external things passing then", function () { var externalVar = 10; var myModule = (function (fromOutside) { return fromOutside; })(externalVar); expect(myModule).toEqual(10); }) it("you can attach to the external context", function () { var myModule = (function (context, fullExternal) { // jasmine context.newVar = "I'm at jasmine"; // window fullExternal.newVar = "I'm at window"; })(this, externalContex); // jasmine expect(this.newVar).toEqual("I'm at jasmine"); // window expect(externalContex.newVar).toEqual("I'm at window"); expect(window.newVar).toEqual("I'm at window"); }) }); describe("(03) instances:", function () { var module1; var module2; beforeEach(function () { var MyModule = (function () { var outerConter = 0; var myObj = function (name) { this.name = name; var counter = 0; this.add = function () { counter += 1; outerConter += 1; } this.getCounter = function () { return counter; } this.getOuterCounter = function () { return outerConter; } } return myObj; })(); //IMMEDIATE EXECUTION -> module module1 = new MyModule("mod1"); module2 = new MyModule("mod2"); }) it("diff instance with diff names", function () { expect(module1.name).toEqual("mod1"); expect(module2.name).toEqual("mod2"); }) it("'counter' is inside the object", function () { //module1 expect(module1.getCounter()).toEqual(0); module1.add(); expect(module1.getCounter()).toEqual(1); //module2 expect(module2.getCounter()).toEqual(0); module2.add(); expect(module2.getCounter()).toEqual(1); }) it("'outerCounter' is a shared private variable", function () { expect(module1.getOuterCounter()).toEqual(0); expect(module2.getOuterCounter()).toEqual(0); //module1 module1.add(); expect(module1.getOuterCounter()).toEqual(1); expect(module2.getOuterCounter()).toEqual(1); //module2 module2.add(); expect(module1.getOuterCounter()).toEqual(2); expect(module2.getOuterCounter()).toEqual(2); }) });
Python
UTF-8
527
3.265625
3
[]
no_license
cars=100 space_in_car=4.0 drivers=30 passengers=90 cars_not_driven=cars - drivers cars_driven=drivers carpool_capacity=cars_driven*space_in_car average_passengers_per_car=passengers/cars_driven print("there are {} cars available".format(cars)); print("there are only ",drivers,"drivers available.") print("there will be {} cars undriven".format(cars_not_driven)) print("we can transport {} people today \n we have {} to carpool today\n we need to put about {} ".format(carpool_capacity,passengers,average_passengers_per_car))
C++
UTF-8
359
3.15625
3
[]
no_license
#include <iostream> using namespace std; void selectionSort(int v[], int numItems){ if (numItems>1){ int maxIdx = 0; for (int i = 1; i<numItems; i++){ if (v[i]>v[maxIdx]){ maxIdx = i; } } } } int main() { double v[] = {1, 8, 3, 9, 2}; cout << selectionSort(v,5); return 0; }
C
UTF-8
3,836
2.671875
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
/* * Copyright 2016-2017, 2019 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** @file * @brief takes an optional H3 index and generates all descendant cells at the * specified resolution. * * See `h3ToHier --help` for usage. * * The program generates all cells at the specified resolution, optionally * only the children of the given index. * * `resolution` should be a positive integer. The default is 0 (i.e., only the * base cells). * * `parent` should be an H3Index. By default, all indices at the specified * resolution are generated. */ #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include "args.h" #include "baseCells.h" #include "h3Index.h" #include "h3api.h" #include "kml.h" #include "utility.h" void recursiveH3IndexToHier(H3Index h, int res) { for (int d = 0; d < 7; d++) { H3_SET_INDEX_DIGIT(h, res, d); // skip the pentagonal deleted subsequence if (_isBaseCellPentagon(H3_GET_BASE_CELL(h)) && _h3LeadingNonZeroDigit(h) == 1) { continue; } if (res == H3_GET_RESOLUTION(h)) { h3Println(h); } else { recursiveH3IndexToHier(h, res + 1); } } } int main(int argc, char *argv[]) { int res; H3Index parentIndex = 0; Arg helpArg = ARG_HELP; Arg resArg = {.names = {"-r", "--resolution"}, .scanFormat = "%d", .valueName = "res", .value = &res, .required = true, .helpText = "Resolution, 0-15 inclusive."}; Arg parentArg = { .names = {"-p", "--parent"}, .scanFormat = "%" PRIx64, .valueName = "parent", .value = &parentIndex, .helpText = "Print only indexes descendent from this index."}; Arg *args[] = {&helpArg, &resArg, &parentArg}; const int numArgs = 3; const char *helpText = "Print all indexes at the specified resolution"; if (parseArgs(argc, argv, numArgs, args, &helpArg, helpText)) { return helpArg.found ? 0 : 1; } if (res > MAX_H3_RES) { printHelp(stderr, argv[0], helpText, numArgs, args, "Resolution exceeds maximum resolution.", NULL); return 1; } if (parentArg.found && !H3_EXPORT(h3IsValid)(parentIndex)) { printHelp(stderr, argv[0], helpText, numArgs, args, "Parent index is invalid.", NULL); return 1; } if (parentArg.found) { // parent is the same or higher resolution than the target. if (res <= H3_GET_RESOLUTION(parentIndex)) { h3Println(parentIndex); } else { int rootRes = H3_GET_RESOLUTION(parentIndex); H3_SET_RESOLUTION(parentIndex, res); recursiveH3IndexToHier(parentIndex, rootRes + 1); } } else { // Generate all for (int bc = 0; bc < NUM_BASE_CELLS; bc++) { H3Index rootCell = H3_INIT; H3_SET_MODE(rootCell, H3_HEXAGON_MODE); H3_SET_BASE_CELL(rootCell, bc); if (res == 0) { h3Println(rootCell); } else { H3_SET_RESOLUTION(rootCell, res); recursiveH3IndexToHier(rootCell, 1); } } } }
C++
UTF-8
627
2.78125
3
[]
no_license
#include <local_leetcode.hpp> class Solution { public: vector<vector<int>> minimumAbsDifference(vector<int>& arr) { sort(arr.begin(), arr.end()); vector<vector<int>> res; int diff = INT_MAX; for (size_t i = 1; i < arr.size(); ++i) { if (arr[i] - arr[i-1] > diff) continue; else { if (arr[i] - arr[i-1] < diff) { diff = arr[i] - arr[i-1]; res.clear(); } res.push_back({arr[i-1], arr[i]}); } } return res; } }; int main() { EXECS(Solution::minimumAbsDifference); return 0; }
Markdown
UTF-8
5,654
2.515625
3
[]
no_license
--- title: Co nám může přinést reforma autorského práva? layout: post category: blog author: Jakub Michálek, Jan Loužek image: posts/cats.jpg tags: EU date: 2015-06-26 --- Právní výbor Evropského parlamentu dne 16. 6. hlasoval o zprávě Julie Redy. Kromě shození celoevropské svobody panoramatu ze stolu však výbor rozhodl ještě o některých dalších věcech. Budou-li schváleny v červencovém hlasování na plenárním zasedání Evropského parlamentu, mohou být i nemusí být přínosem pro celou Evropu. Podívejme se nyní, o co se jedná. **1) Díla vytvořená zaměstanci vlády, veřejné správy a soudy jako součást jejich úřední povinnosti by měla být volně šiřitelná** Tento princip bývá často označování také jako PD-GOV. V Česku již platí, a to podle § 3 autorského zákona, ale v některých jiných státech nikoliv. Není jasný důvod, proč si státní instituce v některých zemích osobují copyright a brání využití informací např. v České republice. > V tomto bodě právní výbor nezaujal jasné stanovisko. Přijal pouze obecnou formulaci, a tedy že "výbor vyzývá členské státy, aby snížily bariéry pro opětovné užití". **2) Stejnocení doby trvání copyrightu s mezinárodním standardem 50 let po smrti autora** V Evropské unii byla výlučná ochrana autorských děl dříve prodloužena z 50 let po smrti autora na 70 let, protože se vybrala nejdelší doba copyrightu v celé EU, kterou mělo Německo. Prodloužení nemělo měřitelné pozitivní přínosy, naopak způsobilo výrazný výpadek v dostupnosti literatury. Copyright se prodlužuje prakticky jen kvůli hrstce trvale vydělávajících děl (což je soukromý zájem nositelů práv po již zemřelých autorech, zejména velkých vydavatelů), zatímco u zbytku jen omezuje jejich dostupnost. > V pozměněné zprávě Julie Redy byl přijat kompromisní pozměňovací návrh č. 7, který vyzývá k další harmonizaci trvání výlučné ochrany, nicméně bez jejího dalšího prodlužování nad současnou dobu. **3) Odkaz na dílo pomocí hyperlinku není předmětem výlučných práv.** Nositelé copyrightu jdou neustále dál ve svých nárocích, takže se čas od času objeví absurdní tvrzení, jako že uvedení odkazu na dílo je užitím díla. Pokud bych do tohoto e-mailu vložil odkaz na webovou stránku, např. seznam.cz, konstituovalo by to podle takového absurdního výkladu užití díla. > Z finálního návrhu nakonec tento bod vypadl, a tak i nadále platí rozhodnutí Evropského soudního dvora ze dne 21. února 2014. Tedy, že uvedení odkazu na webovou stránku, není samo o sobě užitím díla. **4) Vyjasnit, že zákonný přístup k datům umožňuje také data mining pomocí automatických analytických technik.** Výzkum v České republice v oblasti lingvistiky je na velmi vysoké úrovni. Na Matematicko-fyzikální fakultě funguje projekt CLARIN LINDAT, který má grant na rozsáhlé analýzy tzv. velkých dat. Díky analýze velkých souborů dat vznikají lepší automatizované technologie pro překlad textu. Přesto nakladatelé tomuto vytěžení dat brání, ačkoliv samo nemá žádný vliv na jejich příjmy. > Automatické zpracování velkých korpusů textů a data mining byl ve zprávě právního výboru schválen. Poprvé tak může Evropa získat právní úpravu v této oblasti, která bude pro jednotlivé uživatele přívětivá. **5) Výjimka pro výzkum a vzdělání vyžaduje společné vymezení na úrovni EU, aby mohla probíhat přeshraniční spolupráce. Měla by se vztahovat i na neformální vzdělávání.** Současná výjimka má různé znění v různých státech. Pro rozvoj projektů zejména v oblasti e-learningu a jejich opětovné užití je třeba sjednotit obsah výjimky a vykládat ji ve všech státech jednotně. > Zpráva legislativního výboru ve svém kompromisním pozměňovacím návrhu č. 19. původní myšlenku značně omezila. Tyto výjimky tak dovolí pouze pro akreditované vzdělávací instituce. **6) Přidat výjimku pro půjčování knih v digitálních formátech.** Knihovny již v současné době půjčují knihy na e-čtečkách. Je vhodné, aby s touto výjimkou počítalo i právo na úrovni EU, neboť tato výjimka zde v současné době není (narozdíl od půjčování v papírové podobě, které je doplněno spravedlivou odměnou). > Tato skutečnost byla výborem posvěcena a jedná se o jedno z větších vítězství Julie Redy. Proces reformy autorského práva je dlouhý; začal již během veřejných konzultací na přelomu let 2013 a 2014. Tyto konzultace jsme se pokusili podporovat rovněž i prostřednictvím billboardové kampaně. Díky tomu se tak mohla veřejnost zapojit. Nakonec bylo Evropské komisi posláno přes 11 tisíc odpovědí. I díky tomu je vypracovaná zpráva prvním návrhem reformy copyrightu, která se snaží vyjít vstříc také uživatelům jednotlivých děl. Přestože není v řadě směrů dokonalá a přestože do ní byly na poslední chvíli přidány značně kontroverzní přílepky, podařilo se Julii Redě zabránit na poslední chvíli prosazení několika špatných nápadů. Mezi ně patřila například odpovědnost za obsah odkazovných stránek, nebo odstranění jakékoliv pozitivní zmínky o přínosu volných děl. Tyto dva i jiné nápady nakonec ve zprávě právního výboru nejsou. Příště se podíváme na příklady, co se v reformě nepovedlo a co bude ještě třeba změnit, abychom měli skutečné autorské právo pro 21. století.
TypeScript
UTF-8
4,376
2.796875
3
[]
no_license
import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { connectableObservableDescriptor } from 'rxjs/internal/observable/ConnectableObservable'; import { Filter } from '../models/filtering.model'; import { Todo } from '../models/todo.model'; import { LocalStorageService } from './local-storage.service'; @Injectable({ providedIn: 'root' }) export class TodoService { private static readonly TodoStoragekey = 'todos'; private todos: Todo[] =[]; //list todo lấy từ localstorage private filterdTodos: Todo[] =[]; // list todo để hiển thị lên trình duyệt private lengthSubject: BehaviorSubject<number> = new BehaviorSubject<number>(0); private displayTodosSubject: BehaviorSubject<Todo[]> =new BehaviorSubject<Todo[]>([]); private currentFilter:Filter = Filter.All; todos$: Observable<Todo[]> = this.displayTodosSubject.asObservable(); //expose length$: Observable<number> = this.lengthSubject.asObservable(); constructor(private storageService:LocalStorageService) { } fetchFromLocalStorage(){ this.todos = this.storageService.getValue<Todo[]>(TodoService.TodoStoragekey) || []; this.filterdTodos = [...this.todos]; //cloneShallow //this.filterdTodos = [...this.todos.map(todo => ({...todo}))]; //cloneDeep // co the dung cloneDeep cua lodash this.updateTodosData(); } updateToLocalStorage(){ this.storageService.setObject(TodoService.TodoStoragekey, this.todos); this.filterTodos(this.currentFilter,false); this.updateTodosData(); } filterTodos(filter: Filter, isFiltering: boolean = true){ this.currentFilter = filter; switch(filter){ case Filter.Active: this.filterdTodos = this.todos.filter(todo => !todo.isCompleted); break; case Filter.Complete: this.filterdTodos = this.todos.filter(todo => todo.isCompleted); break; case Filter.All: this.filterdTodos = [...this.todos]; break; } if(isFiltering) { this.updateTodosData(); } } addToDo(content: string) { const date= new Date(Date.now()).getTime();/// milliseconds. const newTodo = new Todo(date, content); this.todos.unshift(newTodo);//chèn lên đầu mảng. this.updateToLocalStorage(); } changeTodoStatus(id: number, isCompletedNew: boolean) { const index= this.todos.findIndex(t => t.id === id); const todo = this.todos[index]; todo.isCompleted = isCompletedNew; this.todos.splice(index,1,todo); //splice(start, deleteCount, item1, item2, itemN) - removing or replacing existing elements this.updateToLocalStorage(); } editToto(id: number, contentNew: string){ const index= this.todos.findIndex(t => t.id === id); const todo = this.todos[index]; todo.content = contentNew; this.todos.splice(index,1,todo); this.updateToLocalStorage(); } deleteToto(id: number){ const index= this.todos.findIndex(t => t.id === id); this.todos.splice(index,1); this.updateToLocalStorage(); } toggleAll(){ //nếu tất cả các todo đang là complete thì chuyển all thành uncomplete //nếu tất cả là uncomplete thì chuyển all thành complete // nếu có từ 1 todo là complete thì chuyển all thành complete this.todos = this.todos.map(todoItem =>{ return { ...todoItem, isCompleted: !this.todos.every( t => t.isCompleted) }; }); /** * this.todos.every( t => t.isCompleted) - xét giá trị boolean trả về trong callback truyền vào every() * ---xét lần lượt các item của array trong callback mà tất cả callback đều trả về true thì every trả về true * nếu tất cả isCompleted là true trả về true * nếu tất cả là false trả về false * nếu trong tất cả todos có true và false thì trả về false * */ this.updateToLocalStorage(); } clearCompleted() { this.todos = this.todos.filter(todo => !todo.isCompleted); //lấy các todo có isCompleted=false this.updateToLocalStorage(); } //muốn 1 lệnh hoặc nhóm lệnh chuyển thành 1 method mới thì bôi đen nhóm lệnh nhấn 'ctrl .' chọn extract to method.... private updateTodosData() { this.displayTodosSubject.next(this.filterdTodos); this.lengthSubject.next(this.todos.length); } }
Python
UTF-8
1,197
4.28125
4
[]
no_license
# 通过前序遍历(根左右),可以得到root(前序遍历第一个元素); # 通过中序遍历(左根右),root左半部分构成左子树,右半部分构成右子树。 # 递归 class BinaryTree: def __init__(self, root): self.key = root self.leftChild = None self.rightChild = None def preordertree(self): print(self.key) if self.leftChild: self.leftChild.preordertree() if self.rightChild: self.rightChild.preordertree() def inordertree(self): if self.leftChild: self.leftChild.inordertree() print(self.key) if self.rightChild: self.rightChild.inordertree() def reConstructBinaryTree(preorder, inorder): if len(preorder) != len(inorder): return if not preorder or not inorder: return root = BinaryTree(preorder[0]) index = inorder.index(root.key) root.leftChild = reConstructBinaryTree(preorder[1: index + 1], inorder[: index]) root.rightChild = reConstructBinaryTree(preorder[index + 1:], inorder[index + 1:]) return root # test preorder = [1, 2, 4, 7, 3, 5, 6, 8] inorder = [4, 7, 2, 1, 5, 3, 8, 6] r = reConstructBinaryTree(preorder, inorder) print('Preorder is: ') r.preordertree() print('Inorder is: ') r.inordertree()
Markdown
UTF-8
2,263
3.25
3
[ "Apache-2.0" ]
permissive
## 地址族与数据序列 #### 分配给套接字的IP地址与端口号 - IP(Internet Protocol)为收发网络数据而分配给计算机的值。 #### 网络地址 - IP地址分为网络地址和主机地址,分为A、B、C、D、E等类型。 - A类地址:0~127,以0开头 - B类地址:128~191,以10开头 - C类地址:192~223,以110开头 </br> #### 端口号 - IP地址用于区分计算机,端口号用于区分计算机中的应用程序。 - 端口号由同一操作系统内区分不同套接字设置,16位 - 可分配端口号范围:0~65535 - 知名端口号:0~1023,分配给特定应用程序 </br> ### 地址信息表示 - 地址信息结构体 ```C struct sockaddr_in{ sa_family_t sin_family; // 地址族 uint16_t sin_prot; // 16位TCP/UDP端口号 struct in_addr sin_addr; // 32位IP地址 char sin_zero[8]; // 填充0 } ``` - 其中,`in_addr` 定义 ```C struct in_addr{ in_addr_t s_addr; // 32位IPv4地址 } ``` </br> #### 成员`sin_family`:协议族 - 协议族,IPv4使用4字节地址族,IPv6使用16字节地址族 #### 成员 `sin_port`:端口号 - 保存16位端口号,以网络字节序保存 #### 成员 `sin_addr` :IP地址 - 保存32位IP地址信息,以网络字节序保存。结构体 `in_addr` 声明为 `uint32_t` ,可以当作32为整数。 #### 成员 `sin_zero` :填充0 - 为使结构体 `sockaddr_in` 的大小与 bind参数 `sockaddr` 结构体保持一致而插入的成员。 ```C struct sockaddr_in serv_addr; ... if (bind(serv_sock, (struct sockaddr* ) &serv_addr, sizeof(serv_addr)) == -1) error_handling("bind() error"); ... ``` </br> ```C struct sockaddr{ sa_family_t sin_family; // 地址族 char sa_data[14]; // 地址信息 } ``` - `sa_data` 保存的地址信息包含IP地址和端口号,剩余部分填充0 - `struct sockaddr` 与 `struct sockaddr_in` 大小相同,将 `sockaddr_in` 强制转换为 `sockaddr` 。 <br> ### 网络字节序与地址变换 #### 字节序 - 大端序:高位字节存放在低位地址 - 小端序:高位字节存放在高位地址 - 网络字节序统一为大端序。 </br>
Java
UTF-8
1,717
2.046875
2
[ "Apache-2.0" ]
permissive
/** * Copyright (c) 2013-2022 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.datastore.bigtable; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.Connection; import com.google.cloud.bigtable.hbase.BigtableConfiguration; public class BigTableConnectionPool { private static BigTableConnectionPool singletonInstance; public static synchronized BigTableConnectionPool getInstance() { if (singletonInstance == null) { singletonInstance = new BigTableConnectionPool(); } return singletonInstance; } private final Map<String, Connection> connectorCache = new HashMap<>(); private static final String HBASE_CONFIGURATION_TIMEOUT = "timeout"; public synchronized Connection getConnection(final String projectId, final String instanceId) throws IOException { final String key = projectId + "_" + instanceId; Connection connection = connectorCache.get(key); if (connection == null) { final Configuration config = BigtableConfiguration.configure(projectId, instanceId); config.setInt(HBASE_CONFIGURATION_TIMEOUT, 120000); connection = BigtableConfiguration.connect(config); connectorCache.put(key, connection); } return connection; } }
C#
UTF-8
2,019
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace aorc.gatepass { public static class ConvertNumbers { private static char[] baseChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', }; public static string Int64ToBase36( Int64 value ) { string result = string.Empty; int targetBase = baseChars.Length; do { result = baseChars[value%targetBase] + result; value = value/targetBase; } while (value > 0); return result; } private static int findIndex( char c ) { for (int i = 0; i < baseChars.Length; i++) { if (baseChars[i] == c) { return i; } } return -1; } public static Int64 Base36ToInt64( string base34Value ) { //string result = string.Empty; int targetBase = baseChars.Length; Int64 result = 0; for (int i = 0; i < base34Value.Length; i++) { int index = findIndex(base34Value[i]); if (index == -1) { throw new Exception("مقدار ورودی حاوی مشخصه نامعتبری می باشد"); } var t1 = base34Value.Length - i - 1; var t3 = (Int64) Math.Pow(targetBase, t1); var t2 = t3*index; result = t2 + result; } return result; } public static string IntToStringFast( int value , char [] baseChars ) { // 32 is the worst cast buffer size for base 2 and int.MaxValue int i = 32; char[] buffer = new char[i]; int targetBase = baseChars.Length; do { buffer[--i] = baseChars[value%targetBase]; value = value/targetBase; } while (value > 0); char[] result = new char[32 - i]; Array.Copy(buffer, i, result, 0, 32 - i); return new string(result); } } }
Java
UTF-8
1,179
2.4375
2
[]
no_license
package de.kitaggmbhtrier.bistro.portal.controller; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.kitaggmbhtrier.bistro.data.KindergartenChild; @Controller public class AdminController { public static final String URL_ADMIN = "/admin"; @RequestMapping(value=URL_ADMIN) public ModelAndView adminPage() throws JsonProcessingException { ModelAndView mav = new ModelAndView("admin"); mav.addObject("lastNames", (new ObjectMapper().writer().writeValueAsString(new String[] {"Lockman", "Müller"}))); return mav; } public static String getNameList(List<KindergartenChild> children) { StringBuilder sb = new StringBuilder(); for(KindergartenChild child : children) { sb.append(child.getFirstName()); sb.append(" "); sb.append(child.getLastName()); sb.append(", "); } String childrenList = sb.toString(); return childrenList.substring(0, childrenList.length() - 2); } }
Python
UTF-8
2,786
2.75
3
[]
no_license
''' Morgan Strong code from Teachable Machines page edited based on feedback on using tensorflow.lite instead https://heartbeat.fritz.ai/running-tensorflow-lite-image-classification-models-in-python-92ef44b4cd47 some errors encountered, does not fully work. error thrown when executing tensorflow, now has issues with an unknown symbol ImportError: /home/pi/Desktop/tf_pi/env/lib/python3.7/site-packages/tensorflow_core/lite/python/interpreter_wrapper/_tensorflow_wrap_interpreter_wrapper.so: undefined symbol: _ZN6tflite12tensor_utils24NeonVectorScalarMultiplyEPKaifPf unknown how to fix; based on github comments it should be OK... https://github.com/tensorflow/tensorflow/issues/19319 https://github.com/tensorflow/tensorflow/issues/21855 the models (both regular and lite) are attached, which is trained for eyebrows up, down, right wink, left wink, and neutral currently it takes a picture and starts loading the model, but hits the unknown symbol and fails. ''' #import tensorflow.keras import tensorflow as tf from PIL import Image, ImageOps import numpy as np import time import cv2 def select_image(index): # Disable scientific notation for clarity np.set_printoptions(suppress=True) # Load the model #error here first, removed the "tf.contrib" and changed to tf.lite as contrib had no lite, but tf did #https://github.com/tensorflow/tensorflow/issues/15401 model = tf.lite.Interpreter(model_path="model_unquant.tflite") # Create the array of the right shape to feed into the keras model # The 'length' or number of images you can put into the array is # determined by the first position in the shape tuple, in this case 1. data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) # Replace this with the path to your image image = Image.open('image' + str(index) + '.jpg') #resize the image to a 224x224 with the same strategy as in TM2: #resizing the image to be at least 224x224 and then cropping from the center size = (224, 224) image = ImageOps.fit(image, size, Image.ANTIALIAS) #turn the image into a numpy array image_array = np.asarray(image) # display the resized image image.show() # Normalize the image normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1 # Load the image into the array data[0] = normalized_image_array # run the inference prediction = model.predict(data) print(prediction) def take_image(index): cap = cv2.VideoCapture(0) ret, frame = cap.read() cv2.imwrite('image' + str(index) + '.jpg', frame) index = 0 while True: take_image(index) time.sleep(.5) select_image(index) time.sleep(.5) index = index + 1 print(index) ## from here, we would actuate the motors
JavaScript
UTF-8
454
3.453125
3
[]
no_license
console.log("Welcome to Array"); const persondDetails = [ 'Aravinda', 'HB', 35, 'Trainer', ['aru', 'hary', 'gopi'] ]; const pDetails = { firstName: 'Aravinda', lastName: 'HB', age: 35, occupation: 'Trainer', friends: ['aru', 'hary', 'gopi'] }; console.log(pDetails.firstName); console.log(pDetails.lastName); const nameKey = 'Name'; console.log(pDetails['first' + nameKey]); console.log(pDetails['last' + nameKey]);
PHP
UTF-8
940
2.796875
3
[]
no_license
<?php try{ $base = new PDO('mysql:host=localhost; dbname=bursserver_bd', 'root', ''); $retour = $base->query("SELECT * FROM tblLED;"); $x =0; while ($data = $retour->fetch()){ $Ids[$x] = $data['Id']; $Etats[$x] = $data['Etat']; $Emplacements[$x] = $data['Emplacement']; $x++; } AfficherLED($Ids,$Emplacements,$Etats,$x); } catch(PDOException $e){ echo $e->getMessage(); } function AfficherLED($Ids,$Emplacements,$Etats,$x){ for($y=0;$y<$x;$y++){ $message = ('L\'Id est :'.$Ids[$y].' -L\'emplacement est :'.$Emplacements[$y].'. -La LED est présentement '.EtatLed($Etats[$y]).'.'); echo $message; } } function EtatLed($etat){ $retour = 'allumée'; if ($etat){ $retour = 'fermée'; } return $retour; } ?> <form action="insert.php" method="get"> <p>Emplacement de la LED : <input type=text name="Emplacement"></p> <p><input type=submit value="Enregistrer"></p> </form>
Java
UTF-8
1,912
2.1875
2
[]
no_license
package com.gump.service_impl; import java.io.File; import java.sql.SQLException; import java.util.List; import com.gump.dao.IDocumentDao; import com.gump.dao_impl.DocumentDaoImpl; import com.gump.service.IDocumentService; import com.gump.vo.Document; import com.gump.vo.Page; public class DocumentServiceImpl implements IDocumentService { private IDocumentDao d = new DocumentDaoImpl(); /** * 鎻掑叆鍏枃 */ public int insertDoc(Document doc) { // TODO Auto-generated method stub return d.insertDoc(doc); } /** * 鍒犻櫎鍏枃 */ public int removeDoc(int docId) { // TODO Auto-generated method stub Document doc=d.QueryById(docId); String path = doc.getDocContent(); File file = new File(path); if(file.exists()){ file.delete(); } return d.removeDoc(docId); } /** * 閫氳繃鍏抽敭瀛楁煡璇㈠叕鏂� */ public List<Document> QueryByKeyword(String keyword) { // TODO Auto-generated method stub return d.QueryByKeyword(keyword); } /** * 閫氳繃id淇敼鍏枃 */ public Document modifyDoc(int docId) { // TODO Auto-generated method stub return d.modifyDoc(docId); } /** * 閫氳繃id鏌ヨ鍏枃 */ public Document QueryById(int docId) { // TODO Auto-generated method stub return d.QueryById(docId); } public List<Document> QueryAll() { // TODO Auto-generated method stub return d.QueryAll(); } public List<Document> QueryBySender(String docSender) { // TODO Auto-generated method stub return d.QueryBySender(docSender); } public List<Document> QueryByReceiver(String docReceiver) { // TODO Auto-generated method stub return d.QueryByReceiver(docReceiver); } public int count() { return d.count(); } public List<Document> queryByPage(Page page) throws SQLException { // TODO Auto-generated method stub return d.queryByPage(page); } }
Java
UTF-8
1,415
3.71875
4
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Objeto_002; /** * * @author User */ public class TestCercle { public static void main (String [] args) { /*Definicion de variables Cierculo, Prueva de los TRES constructores */ Cercle C1 = new Cercle(); Cercle C2 = new Cercle(2); Cercle C3 = new Cercle(5,"Blau"); System.out.println("el primer element te un color " + C1.getColor()); System.out.println("el segon element te un color " + C2.getColor()); System.out.println("el tercer element te un color " + C3.getColor()); System.out.println("el primer element te una area de " + C1.calculaArea()); System.out.println("el segundo element te una area de " + C2.calculaArea()); System.out.println("el tercer element te una area de " + C3.calculaArea()); /*Se puede imprimir implicitamente (va a buscar el toString de la clase, o implicitamente que, llamando la clase "C2.toString)s */ System.out.println(C1); System.out.println(C2.toString()); } }
Java
UTF-8
1,975
2.671875
3
[]
no_license
/** * */ package me.gorillabo.multimediaanalysis; import org.opencv.core.Mat; import org.opencv.core.MatOfRect; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.objdetect.CascadeClassifier; import java.util.ArrayList; import java.util.List; /** * @author gorillaimo * */ public class ImageDetector { private String lbpCascadePath; public void setLbpCascadePath(String lbpCascadePath) { this.lbpCascadePath = lbpCascadePath; } public String getLbpCascadePath() { return lbpCascadePath; } public ImageDetector(String lbpCascadePath) { this.lbpCascadePath = lbpCascadePath; } public List<Mat> ditectFromImage(Mat src, int margin) { return ditectFromImage(src, margin, lbpCascadePath); } public static List<Mat> ditectFromImage(Mat src, int margin, String lbpCascadePath) { Mat dst = src.clone(); List<Mat> result = new ArrayList<>(); // 正面顔検出 CascadeClassifier objDetector = new CascadeClassifier(lbpCascadePath); MatOfRect matOfRect = new MatOfRect(); objDetector.detectMultiScale(dst, matOfRect); if(matOfRect.toArray().length <= 0) { result.add(src); return result; } System.out.println("Face detection:" + matOfRect.toArray().length); // 正面顔抜き出し for(Rect rect : matOfRect.toArray()) { int x1 = (rect.x - margin) < 0 ? 0 : (rect.x - margin); int y1 = (rect.y - margin) < 0 ? 0 : (rect.y - margin); int x2 = (rect.x + rect.width + margin) > src.width() ? src.width() : (rect.x + rect.width + margin); int y2 = (rect.y + rect.height + margin) > src.height() ? src.height() : (rect.y + rect.height + margin); Rect withdrawRect = new Rect(new Point(x1, y1), new Point(x2, y2)); Mat withdrawMat = new Mat(dst, withdrawRect); result.add(withdrawMat); } return result; } }
PHP
UTF-8
1,051
2.59375
3
[]
no_license
<?php session_start(); function consult($user, $password){ if ( $link = (mysql_connect('localhost:3306', "$user", "$password") )) { $db_selected = mysql_select_db('yogaetcaetera', $link); $requete = "SELECT * FROM adherent"; $reponse = mysql_query($requete); if(!$reponse){ //Si la requête est bien effectuée die('Requête invalide : ' . mysql_error()); } $nbTuples = mysql_num_rows($reponse); //Récupération du nombre de résultats -- if($nbTuples!=0){ //S'il y a des résultats $prenom_adherent = array(); $nom_adherent = array(); while($tupleCourant = mysql_fetch_assoc($reponse)){ array_push($prenom_adherent,$tupleCourant['prenom']); array_push($nom_adherent,$tupleCourant['nom']); } return array($prenom_adherent,$nom_adherent); //Cas où tout va bien } print "Malheureusement le client que vous cherchez n'a pas été trouvé :/ <br/><br/>"; return array(-1,0,0); //Il n'y a pas de résultat } } ?>
Python
UTF-8
4,609
2.90625
3
[]
no_license
import jieba import re from gensim import corpora, models, similarities import time import sys # 1.文件预处理:读取文本文件,构造分词向量 def Get_file(doc): # doc = open(path, 'r', encoding='UTF-8').read()**************** data = jieba.lcut(doc,cut_all=False) data1 = "" for i in data: # 去符号 data1 += i + " " texts = [word for word in data1.split()] return texts # 2.去符号及停用字 def Dis_sig(str,stopwords): # stopwords = [w.strip() for w in open(stop_path, 'r', encoding='UTF-8').readlines()] result = [] for tags in str: if (re.match(u"[a-zA-Z0-9\u4e00-\u9fa5]", tags)): if tags not in stopwords: # print(tags) result.append(tags) else: pass return result # 3.计算相似值 def Com_sim(all_doc_list, doc_test_list): text=[all_doc_list, doc_test_list] dictionary = corpora.Dictionary(text)#构造语料库 corpus = [dictionary.doc2bow(doc) for doc in text] doc_test_vec = dictionary.doc2bow(doc_test_list) lsi = models.LsiModel(corpus)#模型训练 featurenum = len(dictionary.token2id.keys()) similarity = similarities.SparseMatrixSimilarity(lsi[corpus], num_features=featurenum) cosine_sim = similarity[lsi[doc_test_vec]][0] return cosine_sim def main(): # 开始测量程序所需时间 start_time = time.time() try: orig_path, add_path, answer_path, stop_path= sys.argv[1:5] except BaseException: print("Error: 输入命令错误") else: # 判断命令行参数有没有错误 try: orig = open(orig_path, 'r', encoding='UTF-8') orig_context = orig.read() except IOError: print("Error: 没有从该路径:{}找到文件/读取文件失败".format(orig_path)) conditio_one = 0 else: conditio_one = 1 orig.close() # 判断抄袭文件路径等是否出错 try: orig_add = open(add_path, 'r', encoding='UTF-8') add_context = orig_add.read() except IOError: print("Error: 没有从该路径:{}找到文件/读取文件失败".format(add_path)) conditio_two = 0 else: conditio_two = 1 orig_add.close() # 判断答案文件路径等是否出错 try: answer_txt = open(answer_path, 'w', encoding='UTF-8') except BaseException: print("Error: 创建文件:{}失败".format(answer_path)) conditio_three = 0 else: conditio_three = 1 # 判断停用表命令行参数有没有错误 try: stopwords = [w.strip() for w in open(stop_path, 'r', encoding='UTF-8').readlines()] # word_context = stop_word.read() except IOError: print("Error: 没有从该路径:{}找到文件/读取文件失败".format(stop_path)) conditio_four = 0 else: conditio_four = 1 # orig.close() # 如果输入命令行参数没有错误则运行 if (conditio_one & conditio_two & conditio_three & conditio_four): # path = ".\orig.txt" # 论文原文的文件的绝对路径(作业要求) # path_add = ".\orig_0.8_dis_15.txt" # 抄袭版论文的文件的绝对路径 test = Get_file(orig_context) doc = Get_file(add_context) doc = Dis_sig(doc,stopwords) test = Dis_sig(test,stopwords) similarity = Com_sim(doc, test) # 得知程序运行所需时间 end_time = time.time() time_required = end_time - start_time # 控制台输出,方便得知状态和答案 print('查重率:%.2f' % similarity) print("输出文件到:" + answer_path) print('程序所耗时间:%.2f s' % (time_required)) #写入答案文件 answer_txt.write("源文件:"+orig_path+'\n') answer_txt.write("抄袭文件:"+add_path+'\n') answer_txt.write('查重率:%.2f' %similarity+'\n') answer_txt.write('程序所耗时间:%.2f s'%(time_required)+'\n') answer_txt.close() # 4.主函数main if __name__ == '__main__': main()
PHP
UTF-8
1,881
3.109375
3
[]
no_license
<?php class MyDB { private $dblogin = "root"; // логин бд private $dbpass = "123"; // пароль бд private $db = "Main"; // название бд private $dbhost = "localhost";//расположение бд private $link = ''; private $query = ''; private $err = ''; public $result = ''; public $data = ''; public $num = 0; //подключение к базе function connect() { $this -> link = mysqli_connect($this -> dbhost, $this -> dblogin, $this -> dbpass, $this -> db); mysqli_query($this -> link, 'SET NAMES utf8'); } //закрытие подключения к БД function close() { mysqli_close($this -> link); unset($this -> link); } //выполнить запрос function run($query = '') { $this -> query = $query; $this -> result = mysqli_query($this -> link, $this -> query); $this -> num = mysqli_num_rows($this -> result); $this -> err = mysqli_error($this -> link); } //считать строчку function row() { $tmp_q23 = mysqli_fetch_assoc($this -> result) ; if(!$tmp_q23){ exit("Error - ".mysqli_error($this -> link).",".$tmp_q23); } $this -> data = $tmp_q23; } //функция для очистки введенных данных function clean( $value = "") { return mysqli_real_escape_string( $this -> link, strip_tags( stripslashes( trim( htmlspecialchars( $value )))));//добавлена зашита от sql-иньекций(экранирование) } //остановить function stop() { unset($this -> data); unset($this -> result); unset($this -> num); unset($this -> err); unset($this -> query); } }
Java
UTF-8
2,505
2.578125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Entity; /** * * @author RoAnn */ public class Component { private int id; private String name; private float unitPrice; private int quantity; private Unit unit; private PWorks pworks; private Project project; public Component() { } public Component(int id, String name, float unitPrice, int quantity, Unit unit, PWorks pworks, Project project) { this.id = id; this.name = name; this.unitPrice = unitPrice; this.quantity = quantity; this.unit = unit; this.pworks = pworks; this.project = project; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the unitPrice */ public float getUnitPrice() { return unitPrice; } /** * @param unitPrice the unitPrice to set */ public void setUnitPrice(float unitPrice) { this.unitPrice = unitPrice; } /** * @return the quantity */ public int getQuantity() { return quantity; } /** * @param quantity the quantity to set */ public void setQuantity(int quantity) { this.quantity = quantity; } /** * @return the unit */ public Unit getUnit() { return unit; } /** * @param unit the unit to set */ public void setUnit(Unit unit) { this.unit = unit; } /** * @return the pworks */ public PWorks getPworks() { return pworks; } /** * @param pworks the pworks to set */ public void setPworks(PWorks pworks) { this.pworks = pworks; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } }
Markdown
UTF-8
13,314
2.984375
3
[ "Apache-2.0" ]
permissive
[![](https://jitpack.io/v/xinaiz/web-driver-support.svg)](https://jitpack.io/#xinaiz/web-driver-support) # Web Driver Support WebDriver utility library for Kotlin which encapsulates common logic into simple syntax. * Exclude WebDriver reference from code - of course we use WebDriver, no need to write it every time. * Remove verbose syntax like `WebDriverWait(driver, ...).until(ExpectedConditions.xxx(by))`, `driver.findElement(By.xxx(...))`. * Add built-in waitning for presence of element instead of writing waiting code yourself. * Add OCR support - for elements that are not represented by text * Add Template Matching support - for elements that cannot be found by standard `By` implementation ```kotlin class ExampleScenario(driver: WebDriver) : ExtendedWebDriver(driver) { fun execute() { maximize() open("https://github.com/xinaiz/web-driver-support") "commits".className.find().trimmedText val treeFiles = "file-wrap".className.waitUntilClickable().findAll("tr".tag) treeFiles.forEachIndexed { index, elem -> println("$index: ${elem.text}") } // Easily get BufferedScreenshot from element treeFiles[4].getBufferedScreenshot() // Easily find by element attributes "g p".attr("data-hotkey").clickWhenClickable() // Wait until element is clickable then click it "New pull request".linkText.clickWhenClickable() open("$currentUrl/master...develop") println("blankslate".className.textWhenPresent()) } } ``` # Migration guide: ## Search ## | Old syntax | New syntax | | --- | --- | | `driver.findElement(By.xxx("abc"))` | `"abc".xxx.find()` | | `driver.findElements(By.xxx("abc"))` | `"abc".xxx.findAll()` | | `try { driver.findElement(By.xxx("abc")) } catch(ex: Throwable) { null }` | `"abc".xxx.findOrNull()` | ## Child Search ## | Old syntax | New syntax | | --- | --- | | `parentElement.findElement(By.xxx("abc"))` | `parentElement.find("abc".xxx)` or `"abc".xxx.find(parentElement)`| | `parentElement.findElements(By.xxx("abc"))` | `parentElement.findAll("abc".xxx)` or `"abc".xxx.findAll(parentElement)`| | `try { parentElement.findElement(By.xxx("abc")) } catch(ex: Throwable) { null }` | `webElement.findOrNull("abc".xxx)` or `"abc".xxx.findOrNull(parentElement)`| ## Driver Methods ## All `WebDriver` methods are available via `this` context. In addition, many nested method have been flattened for simplier access. For example: | Old syntax | New syntax | | --- | --- | | `driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)` | `implicitWait = 10 to TimeUnit.SECONDS`| | `driver.navigate().back()` | `navigateBack()`| ## Executing JavaScript ## | Old syntax | New syntax | | --- | --- | | `(driver as JavascriptExecutor).executeScript("script", args)` | `executeScript("script", args)`| | `(driver as JavascriptExecutor).executeAsyncScript("script", args)` | `executeScriptAsync("script", args)`| | `(driver as JavascriptExecutor).executeScript("functionName(arguments[0], arguments[1])", 42, "hello")` | `runFunction("functionName", 42, "hello")`| *TODO: document remaining WebElement JavaScript utility functions* ## Waiting ## Note: New wait methods throw just like original `WebDriverWait` does during timeout. To avoid that, it's required to use `.orNull()` syntax. When timeout occurres, instead of exception, `null` will be returned as waiting result. | Old syntax | New syntax | | --- | --- | | `WebDriverWait(webDriver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xxx("abc")))` | `"abc".xxx.waitUntilPresent(10)`| | `try { WebDriverWait(webDriver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xxx("abc"))) } catch(ex: Throwable) { } ` | `"abc".xxx.wait().orNull().untilPresent()`| ## Common tips ## There are many utility functions that simplify common expressions. Of course complex syntaxes are still available. For example: | Full expression | Shorter expression | | --- | --- | | `"avatar".id.findOrNull() != null` | `"avatar".id.isPresent()`| | `"button".id.wait(15).untilClickable().click()"` | `"button".id.clickWhenClickable(15)`| | `"button".id.wait(15).orNull().untilClickable()?.click()"` | `"button".id.clickWhenClickableOrNull(15)`| # Template matching support If you have `canvas` element on your page with inner controls, you can't normally click specific control, because they are not present in the DOM. This library has some support for that case. ### Setup ### To use this functionality, OpenCV library must be present. You can add it yourself to the project, or use dependency that handles that for you. For example https://github.com/openpnp/opencv. ### How to use ### Example below shows how to use this functionality: Let's assume that `canvas` element has id `frame`. To find it, you would write: ```kotlin val canvas = "frame".id.find() canvas.getBufferedScreenshot() ``` The screenshot: ![screenshot 1](https://i.imgur.com/gg5Qau9.png) Let's say you need to find the guy face. You need to take screenshot, and crop it for future use. I will call it "template": ![screenshot 2](https://i.imgur.com/Dgc3PCl.png) Then, you can find that element just like that: ```kotlin val guyFaces = "/images/guy_face.png".template(canvas).findAll() ``` Now you are left with 2 elements: ![screenshot 3](https://i.imgur.com/Dm5wY3B.png) At this point you can click them, or search deeper! Another template: ![screenshot 4](https://i.imgur.com/Ic6FWkL.png) This time search inside first guy face instead of whole canvas: ```kotlin val guySmile = "/images/guy_smile.png".template(guyFaces[0]).find() ``` ![screenshot 5](https://i.imgur.com/x29xk1C.png) ## Using cached screenshot ## By default, when you search using template matching method, a screenshot is taken by WebDriver each time. Taking screenshot may be slow if done often. If you don't need updated state of canvas everytime you search, you can store screenshot in utility class `ScreenCache`: ```kotlin val canvas = "frame".id.find() var screenCache = canvas.cacheScreen() // screenshot taken "/images/notification.png".template(screenCache).click() // close some notification "/images/home_button.png".template(screenCache).click() // click some button // canvas changed (navigated to different content), screenCache is no longer valid // now, depending on canvas content implementation, we might need to wait until new page appears "/images/some_icon_on_home_page.png".template(canvas).waitUntilPresent() screenCache = canvas.cacheScreen() // create new cache if(!"images/statistics_title.png".template(screenCache).isPresent()) { "/images/statistics_button.png".template(screenCache).click() } // etc ``` ## Handling blurry / distorted content ## There are many cases that canvas content is not static - animation, overlay effects, lighting changes. In that case pixel-perfect template matching will fail miserably. To overcome this, image similarity can be specified. There are currently 5 predefined thresholds: | Name | Value | Description | | --- | --- | --- | | `Similarity.EXACT` | 1.0 | Pixel-perfect match | | `Similarity.PRECISE` | 0.9 | A bit distored image, small overlay effects | | `Similarity.DEFAULT` | 0.8 | Default similarity, handles common overlay effects | | `Similarity.DISTORTED` | 0.7 | Highly distored image, but still recognizable | | `Similarity.LOW` | 0.5 | **Danger zone** - might find something else | Custom similarity can be also specified: ```kotlin "/button.png".template(canvas, similarity = Constants.Similarity.EXACT.value).find() "/button.png".template(canvas, similarity = Constants.Similarity.PRECISE.value).find() "/button.png".template(canvas).find() "/button.png".template(canvas, similarity = Constants.Similarity.DISTORTED.value).find() "/button.png".template(canvas, similarity = Constants.Similarity.LOW.value).find() "/button.png".template(canvas, similarity = 0.95).find() "/button.png".template(canvas, similarity = 0.40).find() ``` **Important** If you use similarity lower than `Similarity.LOW`, you might find fish instead of elephant. # Optical Character Recognition (OCR) support There are multiple occastions when text cannot be accessed, because it's rendered inside `canvas` or is part of an image. Because of that, this library also supports recognizing text from images. Currently `Tesseract` API is used by default, but there is also generic support for any API that converts `BufferedImage` to `String`. ### Setup ### As mentioned above, we use `Tesseract` Api as default OCR engine. Installation instructions can be found on Tesseract github page - https://github.com/tesseract-ocr/tesseract. To use it with Web Driver Support, initialization is required: ```kotlin init { ocr.setDatapath("D:\\<tesseract-installation-folder>\\Tesseract-OCR\\tessdata") ocr.setConfigs(listOf("quiet")) // disable logs } ``` Property `ocr` is defined in `ExtendedWebDriver`, and it can be initalized in `init` block of class that extends it. ### How to use ### OCR functionality is exposed by both `ExtendedWebDriver` and `ExtendedWebElement` classes, but latter is preferred. OCR is performed in bounds of target element: Default OCR, no additional image processing is performed: ```kotlin "body".tag.find().doOCR() // perform OCR on whole visible page ``` Treshold OCR. Convert image to binary (black and white). All pixels below lightness treshold 180 (scale 0-255) will be black, all above will be white. ```kotlin "canvas".id.find().doBinaryOCR(treshold = 180) ``` Use case: ![upperbound treshold](https://i.imgur.com/goPZUth.gif) For very indistinguishable text (blending with background) or if parts of background are both brighter and darker than text, both lower and upper lightness bounds can be specified. Pixels between bounds will become white, and other will become black. ```kotlin "canvas".id.find().doBinaryOCR(tresholdMin = 150, tresholdMax = 160) ``` Use case: ![lower and upper bound threshold](https://i.imgur.com/4MiOlxv.gif) ### Using OCRMode ### OCR is not perfect, and might mistake some characters - for example `8` and `B`. For that, `OCRMode` can be specified. It defines which characters are allowed. Currently there are 3 modes: | Name | Description | Allowed characters | | --- | --- | --- | | `OCRMode.TEXT` | All asci characters | All ascii characters | | `OCRMode.DIGITS` | All digits | `0123456789` | | `OCRMode.CUSTOM` | Custom range | For example `OCRMode.CUSTOM("abcde12345")` | It can be used as follows: ``` "image".id.find().doOCR(ocrMode = OCRMode.DIGITS) ``` ## New search methods ## Other than template matching, there are other new search methods. All of them are defined in `ExtendedBy` class, which extends Selenium's `By` class (seriously): | Search method | Description | Example | | --- | --- | --- | | `ExtendedBy.classNameList(String)` | Classic `WebDriver` doesn't allow searching by multiple class names | `ExtendedBy.classNameList("unicode audiolink")` | | `ExtendedBy.attribute(String, String)` | Search by attribute and it's value | `ExtendedBy.attribute("value", "quit")` | | `ExtendedBy.template(...)` | Search by image from resources (string path), or by existing `BufferedImage`| `ExtendedBy.template(Example::class.java, "/images/face.png")` | | `ExtendedBy.value(String)` | Search by value of attribute `value` | `ExtendedBy.value("quit")` | | `ExtendedBy.position(Point)` | Returns element found by position from top left corner (using javascript) | `ExtendedBy.position(Point(100, 200))`| Other than that, there are also methods that return proxy elements which are not actually real `WebElement`'s, but are useful in composition with Template Matching, OCR, and position related code: | Search method | Description | Example | | --- | --- | --- | | `ExtendedBy.rectangle(Rectangle)` | Returns element that is proxy of real WebElement, but is bounded by rectangle inside it. It's very useful when performing Template Matching / OCR is specific area of parent element | `ExtendedBy.rectangle(Rectangle(20, 50, 100, 200))`| | `ExtendedBy.point(Point) ` | Similar to `ExtendedBy.rectangle`, but is defined only by a `Point`. Not suitable for Template Matching / OCR, but suitable for clicking at specific location inside other `WebElement` | `ExtendedBy.point(Point(200, 300))`| | `ExtendedBy.percentRectangle(RectangleF)` | Similar to `ExtendedBy.rectangle`, but is relation to the parent element in a percentage way (all parameters - `x`, `y`, `width` and `height` | `ExtendedBy.percentRectangle(RectangleF(0.1f, 0.2f, 0.5f, 0.3f))` | | `ExtendedBy.percentPoint(PointF)` | Similar to `ExtendedBy.percentRectangle`, but is defined only by a point. `Point(0.5f, 0.5f)` is center of parent element | `ExtendedBy.percentPoint(PointF(0.3f, 0.4f))` | | `ExtendedBy.twoPointRectangle(TwoPointRectangle)` | Results exactly the same as `ExtendedBy.rectangle`, but is defined by two points - top left and bottom right | `ExtendedBy.twoPointRectangle(TwoPointRectangle(Point(100, 200), Point(200, 400)))` | | `ExtendedBy.twoPointPercentRectangle(TwoPointRectangleF)` | Results exactly the same as `ExtendedBy.percentRectangle`, but is defined by two percentage points - top left and bottom right | `ExtendedBy.twoPointRectangle(TwoPointRectangleF(PointF(0.1f, 0.2f), PointF(0.4f, 0.3f)))` |
Java
UTF-8
2,272
1.570313
2
[]
no_license
/** * <copyright> * * Copyright (c) See4sys, itemis and others. * All rights reserved. This program and the accompanying materials are made * available under the terms of the Artop Software License Based on AUTOSAR * Released Material (ASLR) which accompanies this distribution, and is * available at http://www.artop.org/aslr.html * * Contributors: * See4sys - Initial API and implementation * itemis - API & fixed Bug 1582 https://www.artop.org/bugs/show_bug.cgi?id=1582 * * </copyright> */ package org.artop.ecuc.gautosar.xtend.typesystem.metatypes.impl; import gautosar.gecucdescription.GModuleConfiguration; import gautosar.gecucparameterdef.GModuleDef; import java.util.Collections; import java.util.Set; import org.artop.aal.common.resource.AutosarURIFactory; import org.artop.ecuc.gautosar.xtend.typesystem.EcucContext; import org.artop.ecuc.gautosar.xtend.typesystem.metatypes.ARObjectType; import org.artop.ecuc.gautosar.xtend.typesystem.metatypes.ModuleDefType; import org.eclipse.internal.xtend.type.baseimpl.PropertyImpl; import org.eclipse.xtend.typesystem.Type; public class ModuleDefTypeImpl extends AbstractEcucMetaTypeImpl implements ModuleDefType { public ModuleDefTypeImpl(final EcucContext context) { this(context, ModuleDefType.TYPE_NAME); } private ModuleDefTypeImpl(EcucContext context, String typeName) { super(context, typeName); } @Override protected void addBaseFeatures() { super.addBaseFeatures(); addFeature(new PropertyImpl(this, "unresolvedDefinition", getTypeSystem().getStringType()) { //$NON-NLS-1$ public Object get(Object target) { if (target instanceof GModuleConfiguration) { GModuleDef moduleDef = ((GModuleConfiguration) target).gGetDefinition(); if (moduleDef.eIsProxy()) { return AutosarURIFactory.getAbsoluteQualifiedName(moduleDef); } } return null; } }); } @Override public boolean isInstance(Object target) { return target instanceof GModuleConfiguration; } /** * {@inheritDoc} */ @Override protected Set<? extends Type> internalGetSuperTypes() { return Collections.singleton(getContext().getMetaModel().getTypeForName(ARObjectType.TYPE_NAME)); } }
C++
UTF-8
1,553
2.671875
3
[]
no_license
/* ** Audio.cpp for Shared in /Users/gmblucas/Desktop/Shared/cpp_arcade/sources/utils/data ** ** Made by Lucas Gambini ** Login <gmblucas@epitech.net> ** ** Started on Tue Mar 14 02:32:06 2017 Lucas Gambini ** Last update Fri Mar 17 02:34:42 2017 Full Name */ #include "Audio.hpp" Audio::Audio (std::string const & audio, unsigned int intensity, bool repeat) { this->_audio = audio; this->_intensity = intensity; this->_repeat = repeat; this->_shape = DataType::Music; this->_position = Position(); } Audio::~Audio () { } Audio::Audio(const Audio &obj) { this->_audio = obj._audio; this->_repeat = obj._repeat; this->_intensity = obj._intensity; this->_shape = obj._shape; this->_position = obj._position; } Audio &Audio::operator=(const Audio &obj) { this->_audio = obj._audio; this->_repeat = obj._repeat; this->_intensity = obj._intensity; this->_shape = obj._shape; this->_position = obj._position; return *this; } std::string const &Audio::getAudio() const { return this->_audio; } void Audio::setAudio(std::string const &audio) { this->_audio = audio; } bool Audio::getRepeat() const { return this->_repeat; } void Audio::setRepeat(bool repeat) { this->_repeat = repeat; } unsigned int Audio::getIntensity() const { return (this->_intensity); } void Audio::setIntensity(unsigned int intensity) { this->_intensity = intensity; } void Audio::reset(void) { this->_audio = ""; this->_repeat = false; this->_intensity = 0; this->_position = Position(); }
JavaScript
UTF-8
73
2.90625
3
[]
no_license
let sum = 0 for(let i = 0; i < 15; i++) { sum += i } console.log(sum)
Java
UTF-8
4,604
2.078125
2
[]
no_license
package com.epikat.chaipaani; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.HttpHeaderParser; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; public class Login extends AppCompatActivity { Button login; EditText emailid, password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); emailid = (EditText) findViewById(R.id.Login_emailid); password = (EditText) findViewById(R.id.Login_password); login = (Button) findViewById(R.id.Login_loginButton); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new checkLogin().execute(emailid.getText().toString(), password.getText().toString()); } }); } public class checkLogin extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... strings) { try { RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); String URL = "http://chaipani.herokuapp.com/api/login"; JSONObject jsonBody = new JSONObject(); jsonBody.put("email", strings[0]); jsonBody.put("password", strings[1]); final String requestBody = jsonBody.toString(); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.w("response", response); // Log.i("VOLLEY", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.w("error", error.toString()); } }) { @Override public String getBodyContentType() { return "application/json; charset=utf-8"; } @Override public byte[] getBody() throws AuthFailureError { try { return requestBody == null ? null : requestBody.getBytes("utf-8"); } catch (UnsupportedEncodingException uee) { VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8"); return null; } } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String token = ""; if (response != null) { try{ String responseString = new String(response.data); JSONObject obj = new JSONObject(responseString); token = obj.getJSONObject("data").getString("token"); Log.w("token", token); Intent i = new Intent(Login.this, Dashboard.class); i.putExtra("token", token); startActivity(i); finish(); }catch (JSONException e){ } } return Response.success(token, HttpHeaderParser.parseCacheHeaders(response)); } }; requestQueue.add(stringRequest); } catch (JSONException e) { e.printStackTrace(); } return null; } } }
Swift
UTF-8
280
2.984375
3
[]
no_license
// // Point.swift // Swift 3 TestProject // // Created by Maximilian Hünenberger on 27.7.16. // // import Foundation struct Point: Equatable { var x: Double var y: Double // MARK: - Equatable static func == (p1: Point, p2: Point) -> Bool { return p1.x == p2.x && p1.y == p2.y } }
Markdown
UTF-8
566
2.609375
3
[]
no_license
I find myself with an increasing number of bash scripts, and increasing modifications, so I'm creating this git repo to hold them! The nature of these scripts will vary a good bit. Some will be specific to my laptop or current Linux distro, others might be utility scripts I'm using to manage Amazon EC2 instances, etc. I.e., some may be very useful to the public, while others may be less so. If you find something useful that you'd like to fork or contribute to, please let me know and I'd be happy to pull certain pieces into another repo, if that makes sense.
JavaScript
UTF-8
880
4.4375
4
[]
no_license
//Questao - 1 let a = new Number(7) let b = new Number(-55) let c = new Number(389) let d = new Number(1000) let e = new Number(3.1459) let f = new Number(-46.267) console.log(a, b, c, d, e, f) console.log("Somar a primeira variável com a última variável: ") console.log(a + f) console.log("Multiplicar a primeira variável com a terceira variável: ") console.log(a * c) console.log("Dividir a quarta variável pela quinta variável: ") console.log(d / e) //Questao - 2 let num1 = new Number(10) let num2 = new Number(3) let num3 = new Number(9) let num4 = new Number(99.9) let num5 = new Number(721) console.log(num1, num2, num3, num4, num5) if(num1 < Number.MAX_VALUE){ console.log(true) }else{ console.log(false) } if(num2 = NaN){ console.log(true) }else{ console.log(false) } if(num5 <= num3){ console.log(true) }else{ console.log(false) }
Java
UTF-8
653
2.421875
2
[]
no_license
package com.anthony.playstation.calculation.operators; import com.anthony.playstation.calculation.AOperator; import com.anthony.playstation.data.dataseries.DataSeries; import com.anthony.playstation.data.dataseries.UniformType; import com.anthony.playstation.data.dataunit.DataUnitType; import com.anthony.playstation.exceptions.InvalidOperationException; public abstract class ASingleOperator extends AOperator { public ASingleOperator(String name) { super("SingleOperator"); } public abstract boolean isValidData( DataUnitType type ); public abstract DataSeries operate( UniformType type, DataSeries src) throws InvalidOperationException; }
Ruby
UTF-8
180
2.65625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'zipf' max = ARGV[0].to_i i = 0 while line = STDIN.gets if tokenize(line).size <= max puts i else STDERR.write line end i += 1 end
Java
UTF-8
5,055
1.96875
2
[]
no_license
package com.example.johnluu.duan1.adapter; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import com.example.johnluu.duan1.R; import com.example.johnluu.duan1.TheLoaiFragment; import com.example.johnluu.duan1.database.TheLoaiDAO; import com.example.johnluu.duan1.model.TheLoai; import java.util.ArrayList; import static com.example.johnluu.duan1.R.id.xoa_item; public class TheLoaiAdapter extends RecyclerView.Adapter<TheLoaiAdapter.TheLoaiViewHolder>{ Context c; ArrayList<TheLoai> dstl; public TheLoaiAdapter(Context c,ArrayList<TheLoai> dstl) { this.c=c; this.dstl=dstl; } @NonNull @Override public TheLoaiAdapter.TheLoaiViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inf = LayoutInflater.from(c); View v = inf.inflate(R.layout.one_item_theloai,parent,false); return new TheLoaiViewHolder(v); } @Override public void onBindViewHolder(@NonNull TheLoaiAdapter.TheLoaiViewHolder holder, final int position) { holder.tv_idtheloai_one_item.setText(dstl.get(position)._idtheloai+""); holder.tv_tentheloai_one_item.setText(dstl.get(position).tentheloai); holder.iv_option_one_item_theloai.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showMultiPopup(view,position); } }); } public void showMultiPopup(View view, final int position) { PopupMenu popup = new PopupMenu(c, view); popup.inflate(R.menu.del_edit_function); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.xoa_item: AlertDialog.Builder dialog = new AlertDialog.Builder(c); dialog.setTitle("Thông báo"); dialog.setMessage("Bạn có muốn xóa thể loại này không?"); dialog.setNegativeButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { deleteItem(position); Toast.makeText(c, "Thể Loại đã được xóa", Toast.LENGTH_SHORT).show(); } }); dialog.setPositiveButton("Hủy", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.cancel(); } }); dialog.show(); break; case R.id.sua_item: // final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(c); // LayoutInflater inf = ((Activity)c).getLayoutInflater(); // final View vi = inf.inflate(R.layout.dialog_sua_the_loai,null); // TextView tv_id_themTheLoaidialog = vi.findViewById(R.id.tv_id_themTheLoaidialog); // EditText // builder.setView(vi); // final android.app.AlertDialog a = builder.create(); // // TheLoai tl = dstl.get(position); // // // a.show(); } return false; } }); popup.show(); } @Override public int getItemCount() { return dstl.size(); } public class TheLoaiViewHolder extends RecyclerView.ViewHolder{ TextView tv_idtheloai_one_item; TextView tv_tentheloai_one_item; ImageView iv_option_one_item_theloai; public TheLoaiViewHolder(View itemView) { super(itemView); tv_idtheloai_one_item=itemView.findViewById(R.id.tv_idtheloai_one_item); tv_tentheloai_one_item=itemView.findViewById(R.id.tv_tentheloai_one_item); iv_option_one_item_theloai=itemView.findViewById(R.id.iv_option_one_item_theloai); } } public void deleteItem(int position){ TheLoaiDAO theloaiDAO = new TheLoaiDAO(c); theloaiDAO.xoaTheLoai(dstl.get(position)._idtheloai); notifyItemRemoved(position); dstl = theloaiDAO.xemDSTheLoai(); } }
C++
UTF-8
5,109
2.625
3
[]
no_license
#include <iostream> #include <iomanip> #include <algorithm> #include <string> #include <random> #include <mpi.h> // 归并 void multi_merge(int arr[], int arr_len, int offsets[], int size, int output[]) { int *starts[size]; int *ends[size]; for (int i = 0; i < size; ++i) { starts[i] = arr + offsets[i]; } ends[size - 1] = arr + arr_len; for (int i = 0; i < size - 1; ++i) { ends[i] = starts[i + 1]; } for (int i = 0; i < arr_len; ++i) { int min = 0; while (starts[min] >= ends[min]) { min++; } for (int j = min + 1; j < size; ++j) { if (starts[j] < ends[j] && *starts[j] < *starts[min]) { min = j; } } output[i] = *starts[min]; starts[min]++; } } double PSRS(int arr[], int arr_len) { double start_time = MPI_Wtime(); int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); // 数据分段 int offsets[size]; int lengths[size]; for (int i = 0; i < size; ++i) { offsets[i] = i * arr_len / size; lengths[i] = (i + 1) * arr_len / size - offsets[i]; } // 给每个线程分配数据 auto local = new int[lengths[rank]]; auto local_len = lengths[rank]; MPI_Scatterv(arr, lengths, offsets, MPI_INT, local, local_len, MPI_INT, 0, MPI_COMM_WORLD); // 区域排序 std::sort(local, local + local_len); // 采样 int sample[size]; std::sample(local, local + local_len, sample, size, std::mt19937{std::random_device{}()}); // 选取划分元素 int sample_all[size * size]; int fake_pivot[size + 1];// 添加哨兵方便进行划分 int *pivot = fake_pivot + 1; MPI_Gather(sample, size, MPI_INT, sample_all, size, MPI_INT, 0, MPI_COMM_WORLD); if (rank == 0) { std::sort(sample_all, sample_all + size * size); // 此处需要均匀划分 for (int i = 0; i < size - 1; ++i) { pivot[i] = sample_all[(i + 1) * size]; } } MPI_Bcast(pivot, size - 1, MPI_INT, 0, MPI_COMM_WORLD); // 按 pivot 对局部进行划分 pivot[-1] = local[0]; pivot[size - 1] = local[local_len - 1] + 1; int part_offset[size]; // 每一部分的开始位置 int part_len[size]; // 每一部分的长度 part_offset[0] = 0; int now_index = 0; for (int i = 0; i < size; ++i) { while (now_index < local_len && pivot[i - 1] <= local[now_index] && local[now_index] < pivot[i]) { now_index++; } part_len[i] = now_index - part_offset[i]; if (i + 1 < size) { part_offset[i + 1] = now_index; } } // 发送每个划分长度 for (int i = 0; i < size; ++i) { MPI_Gather(&part_len[i], 1, MPI_INT, lengths, 1, MPI_INT, i, MPI_COMM_WORLD); } offsets[0] = 0; for (int i = 1; i < size; ++i) { offsets[i] = offsets[i - 1] + lengths[i - 1]; } local_len = std::accumulate(lengths, lengths + size, 0); auto local_new = new int[local_len]; // 把每个线程的第 i 个划分发送到第 i 个线程 for (int i = 0; i < size; ++i) { MPI_Gatherv(local + part_offset[i], part_len[i], MPI_INT, local_new, lengths, offsets, MPI_INT, i, MPI_COMM_WORLD); } // 每个线程重新排序,可以用归并的方法 delete[] local; local = new int[local_len]; multi_merge(local_new, local_len, offsets, size, local); delete[] local_new; // 所有长度数据汇总到 root MPI_Gather(&local_len, 1, MPI_INT, lengths, 1, MPI_INT, 0, MPI_COMM_WORLD); if (rank == 0) { offsets[0] = 0; for (int i = 1; i < size; ++i) { offsets[i] = offsets[i - 1] + lengths[i - 1]; } } // 所有数据汇总到 root MPI_Gatherv(local, local_len, MPI_INT, arr, lengths, offsets, MPI_INT, 0, MPI_COMM_WORLD); delete[] local; double end_time = MPI_Wtime(); return end_time - start_time; } int main(int argc, char *argv[]) { auto arr_len = std::stoi(argv[1]); MPI_Init(&argc, &argv); int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); int *arr = nullptr; if (rank == 0) { arr = new int[arr_len]; // 初始化 std::generate_n(arr, arr_len, []() { static int i = 0; return i++; }); // 打乱 std::shuffle(arr, arr + arr_len, std::mt19937(std::random_device()())); } if (rank == 0) { std::cout << std::setiosflags(std::ios::fixed); std::cout << "PSRS 排序\n"; std::cout << "线程数\t数组长度\t用时(ms)\t结果检查\n"; } auto time = PSRS(arr, arr_len); if (rank == 0) { std::cout << size << '\t' << arr_len << '\t' << std::setprecision(4) << time * 1e3 << '\t' << (std::is_sorted(arr, arr + arr_len) ? "正确" : "错误") << std::endl; } MPI_Finalize(); return 0; }
Java
UTF-8
601
1.992188
2
[]
no_license
package com.npng.onepiece.user.view; import javax.swing.JFrame; import com.npng.onepiece.battle.view.main.BattleView; import com.npng.onepiece.sound.Playsound; public class MainFrame extends JFrame { public static MainFrame mf; public MainFrame() { super("Random Luffy RPG"); this.setBounds(300, 150, 1200, 850); this.mf = this; new Playsound().playSound("sound/12.wav"); new LoginPageView(this); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
Java
UTF-8
5,090
2.546875
3
[]
no_license
package com.techelevator.model; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.stereotype.Component; @Component public class JdbcTeamDao implements TeamDao { private JdbcTemplate jdbcTemplate; /** * Create a new user dao with the supplied data source and the password hasher * that will salt and hash all the passwords for users. * * @param dataSource an SQL data source */ @Autowired public JdbcTeamDao(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } /** * Save a new team to the database. * * @param teamName the team name provided by the user team captain. * @param game game the team is playing * @param acceptingNewMembers boolean: if true, accept new member requests. * @param teamBio team bio provided by team captain. * @return the new team. */ public Team createTeam(Team newTeam, Long userId) { long newId = jdbcTemplate.queryForObject( "INSERT INTO teams (team_name, game, accepting_members, team_bio) VALUES (?, ?, ?, ?) RETURNING id", Long.class, newTeam.getTeamName(), newTeam.getGame(), newTeam.isAcceptingNewMembers(), newTeam.getTeamBio()); newTeam.setTeamId(newId); String makeCaptain = "INSERT INTO teamroster (user_id,team_id,captain )VALUES (?,?,true)"; jdbcTemplate.update(makeCaptain, userId, newId); return newTeam; } @Override public List<Team> getAllTeams() { List<Team> allTeams = new ArrayList<>(); String sql = "SELECT id, team_name, game, accepting_members, team_bio from teams;"; SqlRowSet results = jdbcTemplate.queryForRowSet(sql); while (results.next()) { Team team = mapResultToTeam(results); allTeams.add(team); } return allTeams; } @Override public Team getTeamById(long id) { String sql = "SELECT id, team_name, game, accepting_members, team_bio from teams " + " WHERE id = ?;"; SqlRowSet results = jdbcTemplate.queryForRowSet(sql, id); if (results.next()) { return mapResultToTeam(results); } else { return null; } } private Team mapResultToTeam(SqlRowSet results) { Team team = new Team(); team.setTeamId(results.getLong("id")); team.setTeamName(results.getString("team_name")); team.setGame(results.getString("game")); team.setAcceptingNewMembers(results.getBoolean("accepting_members")); team.setTeamBio(results.getString("team_bio")); return team; } @Override public List<Team> getTeamsByUser(long id) { List<Team> userTeams = new ArrayList<>(); String sql = "SELECT id, team_name, game, accepting_members, team_bio from teams " + "WHERE id IN (SELECT team_id FROM teamroster WHERE user_id = ?)"; SqlRowSet results = jdbcTemplate.queryForRowSet(sql, id); while (results.next()) { Team team = mapResultToTeam(results); userTeams.add(team); } return userTeams; } @Override public boolean updateTeam(Team team) { String sql = "UPDATE teams SET team_name = ?, game = ?, " + "team_bio = ?, accepting_members = ? WHERE id = ?"; jdbcTemplate.update(sql, team.getTeamName(), team.getGame(), team.getTeamBio(), team.isAcceptingNewMembers(), team.getTeamId()); return true; } @Override public List<Team> getTeamsForCaptain(String game, Long userId) { List<Team> captainsTeams = new ArrayList<>(); String sql = "SELECT teams.id, team_name, game, accepting_members, team_bio from teams " + "JOIN teamroster on teams.id = teamroster.team_id " + "JOIN users on teamroster.user_id = users.id " + "WHERE captain = true AND teams.game = ? AND teamroster.user_id = ?;"; SqlRowSet results = jdbcTemplate.queryForRowSet(sql, game, userId); while (results.next()) { Team newTeam = mapResultToTeam(results); captainsTeams.add(newTeam); } return captainsTeams; } @Override public boolean addMember(Request request, boolean captainStatus) { boolean result = false; String sql = "INSERT into teamRoster(user_id, team_id, captain) VALUES(?,?,?);"; jdbcTemplate.update(sql, request.getSenderId(), request.getRecipientId(), captainStatus); return result; } @Override public boolean deleteMember(long userId, long teamId) { boolean result = false; String sql = "DELETE FROM teamRoster WHERE user_id = ? AND team_id = ?;"; jdbcTemplate.update(sql, userId, teamId); return result; } }
C++
UTF-8
594
2.65625
3
[]
no_license
class Solution { public: int uniquePaths(int m, int n) { vector<vector<int>> nm; for(int i=0;i<m;i++){ vector<int> sm; for(int j=0;j<n;j++){ sm.push_back(-1); } nm.push_back(sm); } nm[0][0]=1; for(int i=0;i<n;i++){ nm[0][i]=1; } for(int i=0;i<m;i++){ nm[i][0]=1; } for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ nm[i][j]=nm[i-1][j]+nm[i][j-1]; } } return nm[m-1][n-1]; } };
JavaScript
UTF-8
1,394
3.125
3
[]
no_license
/* Treehouse FSJS Techdegree * Project 4 - OOP Game App * app.js */ //Dynamic background via css document.body.style.transition = 'all 1s'; //Add a new message box for interactive messages FOR EXCEEDS AND BEYOND? const phraseContainer = document.getElementById('phrase'); const messageBox = document.createElement('div'); messageBox.setAttribute('id', 'message'); messageBox.style.margin = '0 auto'; messageBox.style.width = '100%'; messageBox.style.textAlign = 'center'; messageBox.style.color = 'teal'; messageBox.innerHTML = '<h2>select any key on your keyboard or from the screen below</h2>'; phraseContainer.parentElement.insertBefore(messageBox, phraseContainer); //End Message Box const keyBoard = document.getElementById('qwerty'); //Game is tarted when the 'Start Game' button is pressed const startButton = document.getElementById('btn__reset').addEventListener('click', () => { let game = new Game(); game.startGame(); keyBoard.addEventListener('click', e => { //on screen keyboard if (e.target.className === 'key' && game.gameReady) { game.selectedButton = e.target; game.handleInteraction(); } }); document.addEventListener('keydown', e => { //physical keyboard if (/^[a-z]?$/.test(e.key) && game.gameReady) { game.findButton(e.key); game.handleInteraction(); } }); });
Python
UTF-8
594
3.5625
4
[]
no_license
import pandas as pd from matplotlib import pyplot dataset=pd.read_csv("pollution.csv",header=0,index_col=0)#读入csv文件,行0为头部(标题),索引为第0列 #print(dataset.head(10)) values=dataset.values#获取dateset中的值,返回一个二维矩阵 #print(values) #下面开始对每一列数据进行绘图,以便观察其变化趋势 groups=[0,1,2,3,4,5,6,7] i=1 pyplot.figure()#初始化一个画布空间 for group in groups: pyplot.subplot(8,1,i) pyplot.plot(values[:,group]) pyplot.title(dataset.columns[group],y=0.5,loc="right") i+=1 pyplot.show()
JavaScript
UTF-8
759
3.171875
3
[]
no_license
const readline = require('readline') const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) const maxLine = 2 let input = []; function isRun(year) { if(year % 400 === 0) return true; return year % 4 === 0 && year % 100 !== 0; } function solution(input) { const arr = input.split('-') const year = parseInt(arr[0]); const month = parseInt(arr[1]); const day = parseInt(arr[2]); const map = [0,31,28,31,30,31,30,31,31,30,31,30,31]; let res = 0; if(isRun(year)) { map[2] = 29; } for (let i = 1; i< month; i++ ) { res += map[i]; } res += day; return res; } rl.on('line', (line) => { console.log(solution(line)); })
JavaScript
UTF-8
4,774
2.609375
3
[ "MIT" ]
permissive
function createMeshesFromStoryboard (storyboard, w, h) { var actors = []; var animation; // 1) Colleziono tutti gli attori for (var i in storyboard.segments) { var segment = storyboard.segments[i]; var tmpActors = actors.filter (function (element) { return element.id === segment.actor.id; }); if (tmpActors.length === 0) { actors.push (segment.actor); } } // 2) Per ogni attore processo tutti i suoi segmenti for (var i in actors) { var actor = actors[i]; animation = { id : actor.id, obj : undefined, transitions : [], x0 : actor.startingConfiguration.tx, y0 : actor.startingConfiguration.ty, z0 : actor.startingConfiguration.tz, dx : 0, dy : 0, dz : 0, rx : 0, ry : 0, rz : 0, sx : 1, sy : 1, sz : 1 }; if (actor.model === "Camera") { var camera = new THREE.PerspectiveCamera (45, w / h, 0.1, 10000); camera.lookAt (scene.position); animation.obj = camera; cameras.push (camera); } else if (actor.model === "Cube") animation.obj = new THREE.Mesh (new THREE.CubeGeometry (1, 1, 1)); // , new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } ) else if (actor.model === "Cylinder") animation.obj = new THREE.Mesh (new THREE.CylinderGeometry ()); else if (actor.model === "Icosahedron") animation.obj = new THREE.Mesh (new THREE.IcosahedronGeometry ()); else if (actor.model === "Octahedron") animation.obj = new THREE.Mesh (new THREE.OctahedronGeometry ()); else if (actor.model === "Plane") animation.obj = new THREE.Mesh (new THREE.PlaneGeometry ()); else if (actor.model === "Sphere") animation.obj = new THREE.Mesh (new THREE.SphereGeometry ()); else if (actor.model === "Tetrahedron") animation.obj = new THREE.Mesh (new THREE.TetrahedronGeometry ()); else if (actor.model === "Torus") animation.obj = new THREE.Mesh (new THREE.TorusGeometry ()); else animation.obj = actor.model; // per input da Web3D animation.obj.position.set (actor.startingConfiguration.tx, actor.startingConfiguration.ty, actor.startingConfiguration.tz); animation.obj.rotation.set (actor.startingConfiguration.rx, actor.startingConfiguration.ry, actor.startingConfiguration.rz); animation.obj.scale.set (actor.startingConfiguration.sx, actor.startingConfiguration.sy, actor.startingConfiguration.sz); if (actor.model !== "Camera") scene.add (animation.obj); for (var j in storyboard.segments) { var segment = storyboard.segments[j]; if (segment.actor.id === actor.id) { if (segment.behaviour.position !== undefined) { animation.transitions.push ({ id : segment.id * 10 + 1, t : "translate", t0 : segment.tStart, t1 : segment.duration, dxf : segment.behaviour.position.x, dyf : segment.behaviour.position.y, dzf : segment.behaviour.position.z }); } if (segment.behaviour.rotation !== undefined) { animation.transitions.push ({ id : segment.id * 10 + 2, t : "rotate", t0 : segment.tStart, t1 : segment.duration, dgx : segment.behaviour.rotation.x, dgy : segment.behaviour.rotation.y, dgz : segment.behaviour.rotation.z }); } if (segment.behaviour.scale !== undefined) { animation.transitions.push ({ id : segment.id * 10 + 3, t : "scale", t0 : segment.tStart, t1 : segment.duration, sxf : segment.behaviour.scale.x, syf : segment.behaviour.scale.y, szf : segment.behaviour.scale.z }); } if (segment.easing !== undefined) { // TODO: da fare } } } animations.push (animation); } }
SQL
UTF-8
7,000
4.46875
4
[]
no_license
-- Sub Query -- emp 테이블에서, 전체 직원의 급여의 평균보다 더 많은 급여를 받는 직원들의 레코드를 검색 -- 1) 전체 직원의 급여 평균 select avg(sal) from emp; -- 2) 평균보다 급여를 더 많이 받는 직원 select * from emp where sal > 2073; select * from emp where sal > ( select avg(sal) from emp ); -- emp 테이블에서, ALLEN보다 적은 급여를 받는 직원들의 사번, 이름, 급여를 출력 -- 1) allen의 sal select sal from emp where ename = 'ALLEN'; -- 2) sub query select empno, ename, sal from emp where sal < ( select sal from emp where ename = 'ALLEN' ); -- emp 테이블에서, ALLEN과 같은 직책의 직원들의 사번, 이름, 부서번호, 직책, 급여를 출력 -- 1) allen의 job select job from emp where ename = 'ALLEN'; -- 2) sub query select empno, ename, deptno, job, sal from emp where job = ( select job from emp where ename = 'ALLEN' ); -- SALESMAN의 급여 최댓값보다 더 많은 급여를 받는 직원들의 사번, 이름, 급여, 직책을 출력 -- 1) SALESMAN의 급여 최댓값 select max(sal) from emp where job = 'SALESMAN'; -- 2) sub query select empno, ename, sal, job from emp where sal > ( select max(sal) from emp where job = 'SALESMAN' ); -- 연봉 = sal * 12 + comm -- 연봉을 계산할 때, comm이 null인 경우에는 0으로 변환해서 계산. -- WARD의 연봉보다 더 많은 연봉을 받는 직원들의 -- 사번, 이름, 급여, 수당, 연봉을 출력. -- 연봉의 내림차순 정렬해서 출력. select empno, ename, sal, comm, sal * 12 + nvl(comm, 0) as annual_sal from emp where sal * 12 + nvl(comm, 0) > ( select sal * 12 + nvl(comm, 0) from emp where ename = 'WARD' ) order by annual_sal desc; -- 각 부서에서 급여가 가장 적은 직원들의 레코드를 검색 -- 1) 각 부서의 급여 최솟값 select min(sal) from emp group by deptno; -- 2) 급여가 950 또는 800 또는 1300인 직원들의 레코드 select * from emp where sal in (950, 800, 1300); -- 1), 2)의 결과를 sub query를 사용해서 합침. select * from emp where sal in ( select min(sal) from emp group by deptno ); -- 10번 부서에서 급여가 1300인 직원 -- 또는, 20번 부서에서 급여가 800인 직원 -- 또는, 30번 부서에서 급여가 950인 직원 select deptno, min(sal) from emp group by deptno; select * from emp where (deptno, sal) in ( select deptno, min(sal) from emp group by deptno ); -- 각 부서에서 급여가 최댓값인 직원들의 레코드 검색. -- 부서번호 오름차순으로 정렬 출력. select deptno, max(sal) from emp group by deptno; select * from emp where (deptno, sal) in ( select deptno, max(sal) from emp group by deptno ) order by deptno; -- 1. 20번 부서에서 근무하는 직원들 중에서 -- 30번 부서에 없는 직책을 가진 직원들의 레코드를 출력 select * from emp where deptno = 20 and job not in ( select distinct job from emp where deptno = 30 ); select distinct job from emp where deptno = 30; select * from emp where deptno = 20 minus select * from emp where job in (select job from emp where deptno = 30); select * from emp where job in ( select job from emp where deptno = 20 minus select job from emp where deptno = 30); -- 2. 급여 최댓값인 직원의 이름과 급여를 출력 select ename, sal from emp where sal = ( select max(sal) from emp ); -- 3. JONES보다 급여를 더 많이 받는 직원들의 이름과 급여를 출력 select ename, sal from emp where sal > ( select sal from emp where ename = 'JONES' ); -- 4. SCOTT과 같은 급여를 받는 직원들의 이름과 급여를 출력 select ename, sal from emp where sal = ( select sal from emp where ename = 'SCOTT' ); -- 5. 4번 결과에서 SCOTT은 제외하고 출력 select ename, sal from emp where sal = (select sal from emp where ename = 'SCOTT') and ename != 'SCOTT'; -- 6. DALLAS에서 근무하는 직원들의 이름과 급여를 출력 -- EMP 테이블과 DEPT 테이블을 사용 select ename, sal from emp where deptno = ( select deptno from dept where loc = 'DALLAS' ); -- 7. ALLEN보다 늦게 입사한 사원들의 이름과 입사날짜를 최근 입사일부터 출력 select * from emp where ename = 'ALLEN'; -- ALLEN의 레코드 select ename, hiredate from emp where hiredate > ( select hiredate from emp where ename = 'ALLEN' ) order by hiredate desc; -- 8. 매지저가 KING인 직원들의 사번과 이름을 출력 select * from emp where ename = 'KING'; select empno, ename, mgr from emp where mgr = (select empno from emp where ename = 'KING'); -- 9. 관리자인 직원들의 사번, 이름, 부서번호를 출력 select distinct mgr from emp; select empno, ename, deptno from emp where empno in (select distinct mgr from emp); -- 10. 관리자가 아닌 직원들의 사번, 이름, 부서번호를 출력 select empno, ename, deptno from emp where empno not in (select distinct mgr from emp); -- 0개 row select empno, ename, deptno from emp where empno not in ( select distinct mgr from emp where mgr is not null ); select empno, ename, deptno from emp where empno not in ( select distinct nvl(mgr, -1) from emp ); -- col in (1, 2): col = 1 or col = 2 -- col not in (1, 2): col != 1 and col != 2 -- col in (1, null): col = 1 or col = null select * from emp where comm = null; -- 0개 행 select * from emp where comm is null; -- 10개 행 -- col not in (1, null): col != 1 and col != null select * from emp where comm != null; -- 0개 행 select * from emp where comm is not null; -- 4개 행 select empno, ename, deptno from emp where (empno, ename, deptno) not in ( select empno, ename, deptno from emp where empno in (select mgr from emp)); select empno, ename, deptno from emp where empno not in ( select empno from emp where empno in (select distinct mgr from emp) ); -- 다중행 서브 쿼리에서 ALL과 ANY -- 10번 부서 직원들의 급여 select sal from emp where deptno = 10; select * from emp where sal < (select sal from emp where deptno = 10); -- 에러 발생 select * from emp where sal < all (select sal from emp where deptno = 10); -- where sal < all(2450, 5000, 1300) -- where sal < 2450 and sal < 5000 and sal < 1300 select * from emp where sal < (select min(sal) from emp where deptno = 10); -- all을 사용한 문장과 동일한 결과 select * from emp where sal < any (select sal from emp where deptno = 10); -- where sal < any(2450, 5000, 1300) -- where sal < 2450 or sal < 5000 or sal < 1300 select * from emp where sal < (select max(sal) from emp where deptno = 10); -- any를 사용한 문장과 동일한 결과
Java
UTF-8
11,344
1.992188
2
[]
no_license
package ipcconnect4.ui.home; import DBAccess.Connect4DAOException; import ipcconnect4.Main; import static ipcconnect4.Main.rb; import static ipcconnect4.Main.stage; import static ipcconnect4.Main.styleSheet; import ipcconnect4.model.GameWithAI.Difficulty; import ipcconnect4.ui.auth.RegisterController; import ipcconnect4.util.LocalPreferences; import ipcconnect4.view.CircleImage; import ipcconnect4.view.SelectorIcon; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.ContextMenuEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import model.Player; public class HomeController implements Initializable { @FXML private Label nickNameT1; @FXML private Label pointsT1; @FXML private Label nickNameT2; @FXML private Label pointsT2; @FXML private VBox pvpVB; @FXML private VBox blockpvpVB; @FXML private CircleImage avatarI1; @FXML private CircleImage avatarI2; @FXML private SelectorIcon diff1SI; @FXML private SelectorIcon diff2SI; @FXML private SelectorIcon diff3SI; private final ObjectProperty<Difficulty> difficulty = new SimpleObjectProperty<>(Main.lastAIdifficulty); @Override public void initialize(URL url, ResourceBundle rb) { initTopBar(); bindDifficulties(); bindPvP(); } private void initTopBar() { if (Main.player1 != null) { ContextMenu contextMenu = new ContextMenu(); MenuItem menuItem1 = new MenuItem(Main.rb.getString("edit_profile")); MenuItem menuItem2 = new MenuItem(Main.rb.getString("logout")); Image openIcon = new Image("/resources/img/edit.png"); ImageView openView = new ImageView(openIcon); openView.setFitWidth(20); openView.setFitHeight(20); menuItem1.setGraphic(openView); Image openIcon2 = new Image("/resources/img/exit.png"); ImageView openView2 = new ImageView(openIcon2); openView2.setFitWidth(20); openView2.setFitHeight(20); menuItem2.setGraphic(openView2); menuItem1.setOnAction((event) -> { showProfileEditor(Main.player1); }); menuItem2.setOnAction((event) -> { LocalPreferences.getInstance().setPlayer1(Main.player2); LocalPreferences.getInstance().setPlayer2(null); Main.player1 = Main.player2; Main.player2 = null; if (Main.player1 == null) { Main.goToAuthenticate(1); } else { Main.goToHome(); } }); contextMenu.getItems().addAll(menuItem1, menuItem2); EventHandler handler = (EventHandler<ContextMenuEvent>) (event) -> { contextMenu.show(avatarI1, event.getScreenX(), event.getScreenY()); }; EventHandler handler1 = (EventHandler<MouseEvent>) (event) -> { contextMenu.show(avatarI1, event.getScreenX(), event.getScreenY()); }; avatarI1.setOnContextMenuRequested(handler); avatarI1.setOnMouseClicked(handler1); avatarI1.setImage(Main.player1.getAvatar()); nickNameT1.setText(Main.player1.getNickName()); pointsT1.setText(Main.formatWLang("points", Main.player1.getPoints())); } else { Platform.runLater(() -> Main.goToAuthenticate(1)); } if (Main.player2 != null) { ContextMenu contextMenu = new ContextMenu(); MenuItem menuItem1 = new MenuItem(Main.rb.getString("edit_profile")); MenuItem menuItem2 = new MenuItem(Main.rb.getString("logout")); Image openIcon = new Image("/resources/img/edit.png"); ImageView openView = new ImageView(openIcon); openView.setFitWidth(20); openView.setFitHeight(20); menuItem1.setGraphic(openView); Image openIcon2 = new Image("/resources/img/exit.png"); ImageView openView2 = new ImageView(openIcon2); openView2.setFitWidth(20); openView2.setFitHeight(20); menuItem2.setGraphic(openView2); menuItem1.setOnAction((event) -> { showProfileEditor(Main.player2); }); menuItem2.setOnAction((event) -> { Main.player2 = null; LocalPreferences.getInstance().setPlayer2(null); Main.goToHome(); }); contextMenu.getItems().addAll(menuItem1, menuItem2); EventHandler handler = (EventHandler<ContextMenuEvent>) (event) -> { contextMenu.show(avatarI2, event.getScreenX(), event.getScreenY()); }; EventHandler handler1 = (EventHandler<MouseEvent>) (event) -> { contextMenu.show(avatarI2, event.getScreenX(), event.getScreenY()); }; avatarI2.setOnContextMenuRequested(handler); avatarI2.setOnMouseClicked(handler1); avatarI2.setImage(Main.player2.getAvatar()); nickNameT2.setText(Main.player2.getNickName()); pointsT2.setText(Main.formatWLang("points", Main.player2.getPoints())); } else { ContextMenu contextMenu = new ContextMenu(); MenuItem menuItem1 = new MenuItem(Main.rb.getString("login")); Image openIcon = new Image("/resources/img/login.png"); ImageView openView = new ImageView(openIcon); openView.setFitWidth(20); openView.setFitHeight(20); menuItem1.setGraphic(openView); menuItem1.setOnAction((event) -> { Stage auth2 = new Stage(); auth2.setScene(new Scene(Main.getAuthenticateScene(2))); auth2.initModality(Modality.WINDOW_MODAL); auth2.initOwner(stage); auth2.setTitle(rb.getString("app_name")); auth2.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/img/icon.png"))); auth2.setHeight(500); auth2.setWidth(450); auth2.setResizable(false); auth2.showAndWait(); Main.goToHome(); }); contextMenu.getItems().addAll(menuItem1); EventHandler handler = (EventHandler<ContextMenuEvent>) (event) -> { contextMenu.show(avatarI2, event.getScreenX(), event.getScreenY()); }; EventHandler handler1 = (EventHandler<MouseEvent>) (event) -> { contextMenu.show(avatarI2, event.getScreenX(), event.getScreenY()); }; avatarI2.setOnContextMenuRequested(handler); avatarI2.setOnMouseClicked(handler1); avatarI2.setImage(new Image("/avatars/default.png")); nickNameT2.setText("?"); pointsT2.setText(Main.formatWLang("points", -1)); } } private void bindDifficulties() { diff1SI.selectedProperty().bind(Bindings.equal(difficulty, Difficulty.EASY)); diff2SI.selectedProperty().bind(Bindings.equal(difficulty, Difficulty.NORMAL)); diff3SI.selectedProperty().bind(Bindings.equal(difficulty, Difficulty.HARD)); difficulty.addListener((observable, oldValue, newValue) -> Main.lastAIdifficulty = newValue ); } private void bindPvP() { if (Main.player2 == null) { pvpVB.setDisable(true); blockpvpVB.setVisible(true); } else { pvpVB.setDisable(false); blockpvpVB.setVisible(false); } } private void showProfileEditor(Player player) { Stage auth2 = new Stage(); FXMLLoader loader = new FXMLLoader( getClass().getResource("/resources/fxml/register.fxml"), Main.rb ); RegisterController controller = new RegisterController(new RegisterController.RegisterListener() { @Override public void onCancel() { auth2.close(); } @Override public void onRegister(Player newPlayer) { try { player.setEmail(newPlayer.getEmail()); player.setPassword(newPlayer.getPassword()); player.setAvatar(newPlayer.getAvatar()); player.setBirthdate(newPlayer.getBirthdate()); player.setPoints(newPlayer.getPoints()); auth2.close(); Main.goToHome(); } catch (Connect4DAOException ex) { Logger.getLogger(HomeController.class.getName()).log(Level.SEVERE, null, ex); } } }, player); loader.setController(controller); Parent root; try { root = loader.load(); root.getStylesheets().clear(); root.getStylesheets().add(styleSheet); auth2.setScene(new Scene(root)); } catch (IOException ex) { Logger.getLogger(HomeController.class.getName()).log(Level.SEVERE, null, ex); } auth2.initModality(Modality.WINDOW_MODAL); auth2.initOwner(stage); auth2.setTitle(rb.getString("edit_profile")); auth2.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/img/edit.png"))); auth2.setHeight(500); auth2.setWidth(450); auth2.setResizable(false); auth2.showAndWait(); } @FXML private void difficultyAction(MouseEvent event) { VBox source = (VBox) event.getSource(); switch (source.getId()) { case "diff1SI": difficulty.set(Difficulty.EASY); break; case "diff2SI": difficulty.set(Difficulty.NORMAL); break; case "diff3SI": difficulty.set(Difficulty.HARD); break; } } @FXML private void settingsAction(MouseEvent event) { Main.showSettings((Stage) nickNameT1.getScene().getWindow()); } @FXML private void startVSAIAction(MouseEvent event) { Main.startGameAI(Main.player1, difficulty.get()); } @FXML private void startVSPlayerAction(MouseEvent event) { Main.startGame(Main.player1, Main.player2); } @FXML private void ranksAction(MouseEvent event) { Main.goToRanks(true); } }
Java
UTF-8
684
2.9375
3
[]
no_license
package day04; /** * TODO * * @author admin * @version 1.0 * @date 2021/4/21 9:12 */ //线程中线程栈的大小 public class StackSize { private static int count = 0; public static void main(String[] args) { Thread t1 = new Thread(null, new Runnable() { @Override public void run(){ try { add(1); }catch (Error e){ e.printStackTrace(); System.out.println(count); } } }, "stackSize", 1>>23); t1.start(); } public static void add(int i){ count++; i++; add(i); } }
C++
UTF-8
4,391
2.71875
3
[]
no_license
#include "SkySphere.h" SkySphere::SkySphere(const std::string& material, Ogre::Real r) : radius(r) { Ogre::Entity* skySphereEntity = Game::getScene()->createEntity("SkySphereEntity", "SkySphere"); skySphereEntity->setMaterialName(material); skySphereEntity->setRenderQueueGroup(Ogre::RENDER_QUEUE_WORLD_GEOMETRY_1); skySphereEntity->setCastShadows(false); Game::getScene()->getRootSceneNode()->createChildSceneNode()->attachObject(skySphereEntity); } SkySphere::~SkySphere() { } void SkySphere::loadSphere() { const int rings = 10; const int segments = 18; Ogre::MeshPtr sphere = Ogre::MeshManager::getSingleton().createManual("SkySphere", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); Ogre::SubMesh *sphereVertex = sphere->createSubMesh(); sphereVertex->vertexData = new Ogre::VertexData(); sphereVertex->useSharedVertices = false; Ogre::VertexData* vertexData = sphereVertex->vertexData; Ogre::IndexData* indexData = sphereVertex->indexData; // the vertex format Ogre::VertexDeclaration* vertexDecl = vertexData->vertexDeclaration; size_t currentOffset = 0; // positions vertexDecl->addElement(0, currentOffset, Ogre::VET_FLOAT3, Ogre::VES_POSITION); currentOffset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3); // colors vertexDecl->addElement(0, currentOffset, Ogre::VET_FLOAT1, Ogre::VES_TEXTURE_COORDINATES); currentOffset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT1); // allocate the vertex buffer vertexData->vertexCount = (rings + 1) * (segments + 1); Ogre::HardwareVertexBufferSharedPtr vBuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(vertexDecl->getVertexSize(0), vertexData->vertexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); Ogre::VertexBufferBinding* binding = vertexData->vertexBufferBinding; binding->setBinding(0, vBuf); float* vertex = static_cast<float*>(vBuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); // allocate index buffer indexData->indexCount = 6 * rings * (segments + 1); indexData->indexBuffer = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(Ogre::HardwareIndexBuffer::IT_16BIT, indexData->indexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); Ogre::HardwareIndexBufferSharedPtr iBuf = indexData->indexBuffer; unsigned short* indices = static_cast<unsigned short*>(iBuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); float deltaRingAngle = Ogre::Math::PI / rings; float deltaSegAngle = 2 * Ogre::Math::PI / segments; unsigned short verticeIndex = 0; // Generate the group of rings for the sphere for(int ring = 0; ring <= rings; ring++) { float r0 = radius * std::sin(ring * deltaRingAngle); float y0 = radius * std::cos(ring * deltaRingAngle); // Generate the group of segments for the current ring for(int seg = 0; seg <= segments; seg++) { float x0 = r0 * std::sin(seg * deltaSegAngle); float z0 = r0 * std::cos(seg * deltaSegAngle); // Add one vertex to the strip which makes up the sphere *vertex++ = x0; *vertex++ = y0; *vertex++ = z0; Ogre::Vector3 normal = Ogre::Vector3(x0, y0, z0).normalisedCopy(); // Calculate color const Ogre::Vector3 dirToLight = Ogre::Vector3(0.0f, 1.0f, 0.0f); const float texSize = 512.0f; float factor = (dirToLight.dotProduct(normal) * 0.5f + 0.5f) * (texSize-2)/texSize + 1.0f/texSize; *vertex++ = factor; if (ring != rings) { // each vertex (except the last) has six indices pointing to it *indices++ = verticeIndex + segments + 1; *indices++ = verticeIndex; *indices++ = verticeIndex + segments; *indices++ = verticeIndex + segments + 1; *indices++ = verticeIndex + 1; *indices++ = verticeIndex; verticeIndex ++; } } } // Unlock vBuf->unlock(); iBuf->unlock(); // Set bounds sphere->_setBounds(Ogre::AxisAlignedBox(Ogre::Vector3(-radius, -radius, -radius), Ogre::Vector3(radius, radius, radius) ), false); sphere->_setBoundingSphereRadius(radius); sphere->load(); } void SkySphere::setVisible(bool visible) { Game::getScene()->getEntity("SkySphereEntity")->setVisible(visible); } void SkySphere::update(Ogre::Real radius) { Game::getScene()->getRootSceneNode()->setPosition(Game::camera->getCamera()->getDerivedPosition()); Game::getScene()->getRootSceneNode()->setScale(radius, radius, radius); }
C
UTF-8
430
3.75
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> main() { char str1[20],str2[20]; int x; printf("\n\n\t\t Enter string 1: \t"); gets(str1); printf("\n\n\t\t Enter String 2: \t "); gets(str2); x=strcmp(str1,str2); if(x==0) { printf("\n\n\t\t Strings are equal. "); } else printf("\n\n\t\t Strings are not equal."); printf("\n\n\t\t Difference = %d", x); }
Python
UTF-8
348
3.625
4
[]
no_license
import utility_positive print("Enter 5 integers:") #n1 = n2 = n3 = n4 = n5 = 0 #n = [n1,n2,n3,n4,n5] n1 = int(input("")) n2 = int(input("")) n3 = int(input("")) n4 = int(input("")) n5 = int(input("")) positive_sum = utility_positive.sum_of_positive(n1,n2,n3,n4,n5) print("Sum of positive integers = ", end = "") print(positive_sum)
Java
UTF-8
2,631
2.96875
3
[]
no_license
package agent; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import abstraction.GameAbstraction; import acpc.Action; import acpc.MatchState; public class PureCFRPlayer { public PureCFRPlayer() { } public static void main(String args[]) { // Print usage if (args.length != 4) { System.out .println("Usage: pure_cfr_player <player_file> <server> <port>\n"); } /* Initialize player module and get the abstract game */ File file = new File(args[0]); PlayerModule playerModule = new PlayerModule(file); GameAbstraction gameAbs = playerModule.gameAbs; /* Connect to the dealer */ try { Socket s = new Socket(args[1], Integer.parseInt(args[2])); try { InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); if (in == null || out == null) { System.out.println("ERROR: could not get socket streams"); return; } // TODO PrintWriter pw = new PrintWriter(out); BufferedReader br = new BufferedReader( new InputStreamReader(in)); // Send version string to dealer pw.write("VERSION:" + 2 + "." + 0 + "." + 0 + "\n"); pw.flush(); // play the game String serverStr = null; while ((serverStr = br.readLine()) != null) { System.out.println(serverStr); if (serverStr.charAt(0) == '#' || serverStr.charAt(0) == ';') { continue; } // Read the incoming state MatchState matchState = new MatchState(); matchState.readMatchState(gameAbs.game, serverStr); // Ignore game over message if (matchState.finished) { continue; } // Ignore states that we are not acting in int currentPlayer = gameAbs.game.currentPlayer(matchState); if (currentPlayer != matchState.viewingPlayer) { continue; } /* * Start building the response to the server by adding a * colon (guaranteed to fit because we read a new-line in * fgets) */ StringBuilder serverSb = new StringBuilder(serverStr); serverSb.append(":"); // Get action to the server Action action = playerModule.getAction(matchState); // Send the action to the server serverSb.append(action.toString()); serverSb.append("\r\n"); pw.write(serverSb.toString()); pw.flush(); } } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { System.out.println("Socket error"); e.printStackTrace(); } } }
Java
UTF-8
332
2.625
3
[]
no_license
package top.tinn.Over200.Problem_1342; public class Solution { public int numberOfSteps (int num) { int step = 0; while (num != 0){ if ((num & 1) == 0){ num >>= 1; }else { num ^= 1; } step++; } return step; } }
Python
UTF-8
380
4.15625
4
[]
no_license
num1 = int(input('Enter a value of Day from 1 to 7 ')) if num1 == 1: print("It's Monday") elif num1 == 2: print("It's Tuesday") elif num1 == 3: print("It's Wednesday") elif num1 == 4: print("It's Thursday") elif num1 == 5: print("It's Friday") elif num1 == 6: print("It's Saturday") elif num1 == 7: print("It's Sunday") else: print('Wrong Input')
PHP
UTF-8
1,264
2.5625
3
[]
no_license
<?php class HomeController extends BaseController { public function index() { return View::make('hello'); } public function flash() { Session::flash('message', "It's a flash"); return View::make('flash'); } public function back() { return Redirect::back(); } public function secure() { return View::make('hello'); } public function session($message) { Session::set('message', $message); return Redirect::to('/'); } public function form() { $message = Request::get('message', ''); return View::make('form', compact('message')); } public function specialCharacters() { return View::make('special-characters'); } /** * @return string */ public function domain() { return 'Domain route'; } /** * @return string */ public function subdomain() { return 'Subdomain route'; } /** * @return string */ public function wildcard() { return 'Wildcard route'; } /** * @return string */ public function multipleWildcards() { return 'Multiple wildcards route'; } }
Python
UTF-8
669
3.890625
4
[]
no_license
print('The Invoice Program') cust=input('Enter Customer Type(r/w):') inv=float(input('Enter The Invoice Rate:')) if cust.lower()== "r": if inv>0 and inv<100: discount=0 elif inv>100 and inv<200: discount=.1 elif inv>200 and inv<500: discount=.2 elif inv>500: discount=.25 elif(cust.lower()== "w"): if inv>0 and inv<500: discount=.4 elif inv>500: discount=.5 else : discount=0 discount_amt =float(inv*discount) invoice=inv-round(discount_amt,2) print ('The Discount Percentage:',discount) print('The Discount Amount is:',discount_amt) print('The Total:',invoice)
C++
UTF-8
342
2.671875
3
[ "MIT" ]
permissive
// Abdullah Naveed // ROLL # 18I-0654 (A) // OOP_Project #ifndef POSITION_H_ #define POSITION_H_ class Position { private: int posX; int posY; public: Position(); Position(int x, int y); Position(const Position& rhs); int getPosX() const; void setPosX(int posX); int getPosY() const; void setPosY(int posY); }; #endif /* POSITION_H_ */
Python
UTF-8
3,160
3.34375
3
[]
no_license
class Nodo(object): def __init__(self, dato = None, proximo = None): self.dato = dato self.proximo = proximo def __str__(self): return str(self.dato) class Lista_enlazada(object): def __init__(self): self.primer_elemento = None self.ultimo_elemento = None self.largo = 0 def __str__(self): if(self.largo == 0): return "[]" string_salida = "[ " nodo = self.primer_elemento string_salida += str(nodo.dato) nodo = nodo.proximo while nodo: string_salida += ", " + str(nodo.dato) nodo = nodo.proximo string_salida += " ]" return string_salida def __len__(self): return self.largo def append(self, dato): nodo = Nodo(dato) if(self.primer_elemento == None): self.primer_elemento = nodo else: self.ultimo_elemento.proximo = nodo self.ultimo_elemento = nodo self.largo += 1 def insert(self, indice, nuevo_item): if(not str(indice).isdigit()): raise TypeError if(indice > self.largo and indice < 0): raise IndexError if(indice == self.largo): append(nuevo_item) elif(indice == 0): nodo_nuevo = Nodo(nuevo_item) nodo_nuevo.proximo = self.primer_elemento self.primer_elemento = nodo_nuevo self.largo += 1 else: nodo_nuevo = Nodo(nuevo_item) nodo_anterior = self.primer_elemento nodo_actual = nodo_anterior.proximo contador = 1 while(contador != indice): nodo_anterior = nodo_actual nodo_actual = nodo_actual.proximo contador += 1 nodo_anterior.proximo = nodo_nuevo nodo_nuevo.proximo = nodo_actual self.largo += 1 def remove(self, item): if(self.largo == 0): raise ValueError nodo = self.primer_elemento if(nodo.dato == item): self.primer_elemento = nodo.proximo else: nodo_siguiente = nodo.proximo while( nodo_siguiente.dato != item ): nodo = nodo_siguiente nodo_siguiente = nodo_siguiente.proximo if(nodo_siguiente == None): raise ValueError nodo.proximo = nodo_siguiente.proximo self.largo -= 1 def pop(self, indice = None ): if(indice == None): indice = self.largo-1 if(not str(indice).isdigit()): raise TypeError if(indice >= self.largo and indice < 0): raise IndexError if(indice == 0): valor = self.primer_elemento.dato self.primer_elemento = self.primer_elemento.proximo return valor nodo_anterior = self.primer_elemento nodo_actual = nodo_anterior.proximo contador = 1 while(contador != indice): nodo_anterior = nodo_actual nodo_actual = nodo_actual.proximo contador += 1 valor = nodo_actual.dato nodo_anterior.proximo = nodo_actual.proximo self.largo -= 1 return valor def index(self, item): nodo = self.primer_elemento indice = 0 if(nodo.dato == item): return indice while( not (nodo.proximo == None) ): nodo = nodo.proximo indice += 1 if(nodo.dato == item): return indice raise ValueError def main(): lista = Lista_enlazada() lista.append(1) lista.append(2) lista.append(3) lista.append(4) lista.append(5) lista.append(6) print lista print len(lista) print lista.pop(2) print lista print len(lista) print raw_input() main()
C++
UTF-8
914
2.65625
3
[]
no_license
/* * EventLoopThreadPool.h * * Created on: Jun 23, 2014 * Author: damonhao */ #ifndef SIMPLEV_NET_EVENTLOOPTHREADPOOL_H_ #define SIMPLEV_NET_EVENTLOOPTHREADPOOL_H_ #include <vector> #include <boost/noncopyable.hpp> #include <boost/ptr_container/ptr_vector.hpp> namespace simplev { namespace net { class EventLoop; class EventLoopThread; class EventLoopThreadPool : boost::noncopyable { public: EventLoopThreadPool(EventLoop* baseLoop); ~EventLoopThreadPool(); void setThreadNum(int numThreads) { numThreads_ = numThreads; } void start(); // valid after calling start() EventLoop* getNextLoop(); // valid after calling start() std::vector<EventLoop*> getAllLoops(); private: EventLoop* baseLoop_; bool started_; int numThreads_; int next_; boost::ptr_vector<EventLoopThread> threads_; std::vector<EventLoop*> loops_; }; } } #endif /* SIMPLEV_NET_EVENTLOOPTHREADPOOL_H_ */
Java
UTF-8
2,279
2.25
2
[]
no_license
/** * */ package org.asendar.url.shortener.service.url; import java.util.List; import java.util.Optional; import org.asendar.url.shortener.entity.ShortenedUrlEntity; import org.asendar.url.shortener.entity.UrlAccessEntity; import org.asendar.url.shortener.entity.UserEntity; import org.asendar.url.shortener.repository.ShortenedUrlRepository; import org.asendar.url.shortener.service.common.CommonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.common.collect.Lists; /** * @author asendar * */ @Service public class UrlServiceImpl implements UrlService { @Autowired private ShortenedUrlRepository shortenedUrlRepo; @Autowired private CommonUtils commonUtils; @Override public Optional<ShortenedUrlEntity> saveOrUpdate(ShortenedUrlEntity shortenedUrlEntity) { return Optional.ofNullable(shortenedUrlRepo.saveAndFlush(shortenedUrlEntity)); } @Override public Optional<ShortenedUrlEntity> shortenUrl(String originalUrl, UserEntity user) { ShortenedUrlEntity shortenedUrlEntity = new ShortenedUrlEntity(); shortenedUrlEntity.setUser(user); shortenedUrlEntity.setOriginal(originalUrl); shortenedUrlEntity.setShortened(commonUtils.newUrl()); return Optional.ofNullable(shortenedUrlRepo.saveAndFlush(shortenedUrlEntity)); } @Override public Optional<ShortenedUrlEntity> findOne(long id) { return shortenedUrlRepo.findById(id); } @Override public Optional<ShortenedUrlEntity> findOne(String shortenedUrl) { return shortenedUrlRepo.findByShortened(shortenedUrl); } @Override public Optional<ShortenedUrlEntity> getOriginalUrl(String shortenedUrl, String ipAddress) { ShortenedUrlEntity entity = findOne(shortenedUrl).orElse(null); if (entity != null) { UrlAccessEntity urlAccessEntity = new UrlAccessEntity(); urlAccessEntity.setIpAddress(ipAddress); urlAccessEntity.setShortenedUrl(entity); entity.addAccess(urlAccessEntity); saveOrUpdate(entity); } return Optional.ofNullable(entity); } @Override public int getNumberOfVisits(String shortenedUrl) { List<UrlAccessEntity> access = findOne(shortenedUrl).map(ShortenedUrlEntity::getAccess) .orElse(Lists.newArrayList()); return access.size(); } }
C++
UTF-8
8,444
2.609375
3
[ "BSD-2-Clause-Views" ]
permissive
// Geometric Tools, LLC // Copyright (c) 1998-2014 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.1 (2010/04/18) #include "Wm5MathematicsPCH.h" #include "Wm5VEManifoldMesh.h" #include "Wm5Memory.h" using namespace Wm5; //---------------------------------------------------------------------------- VEManifoldMesh::VEManifoldMesh (VCreator vCreator, ECreator eCreator) { mVCreator = (vCreator ? vCreator : CreateVertex); mECreator = (eCreator ? eCreator : CreateEdge); } //---------------------------------------------------------------------------- VEManifoldMesh::~VEManifoldMesh () { VMapIterator viter = mVMap.begin(); VMapIterator vend = mVMap.end(); for (/**/; viter != vend; ++viter) { Vertex* vertex = viter->second; delete0(vertex); } EMapIterator eiter = mEMap.begin(); EMapIterator eend = mEMap.end(); for (/**/; eiter != eend; ++eiter) { Edge* edge = eiter->second; delete0(edge); } } //---------------------------------------------------------------------------- VEManifoldMesh::VPtr VEManifoldMesh::CreateVertex (int v) { return new0 Vertex(v); } //---------------------------------------------------------------------------- VEManifoldMesh::EPtr VEManifoldMesh::CreateEdge (int v0, int v1) { return new0 Edge(v0, v1); } //---------------------------------------------------------------------------- VEManifoldMesh::EPtr VEManifoldMesh::InsertEdge (int v0, int v1) { std::pair<int,int> ekey(v0, v1); EMapIterator eiter = mEMap.find(ekey); if (eiter != mEMap.end()) { // Edge already exists. return 0; } // Add new edge. EPtr edge = mECreator(v0,v1); mEMap[ekey] = edge; // Add vertices to mesh. for (int i = 0; i < 2; ++i) { int v = edge->V[i]; VPtr vertex; VMapIterator viter = mVMap.find(v); if (viter == mVMap.end()) { // First time vertex encountered. vertex = mVCreator(v); mVMap[v] = vertex; // Update vertex. vertex->E[0] = edge; } else { // Second time vertex encountered. vertex = viter->second; assertion(vertex != 0, "Unexpected condition\n"); // Update vertex. if (vertex->E[1]) { assertion(false, "Mesh must be manifold\n"); return 0; } vertex->E[1] = edge; // Update adjacent edge. EPtr adjacent = vertex->E[0]; assertion(adjacent != 0, "Unexpected condition\n"); for (int j = 0; j < 2; ++j) { if (adjacent->V[j] == v) { adjacent->E[j] = edge; break; } } // Update edge. edge->E[i] = adjacent; } } return edge; } //---------------------------------------------------------------------------- bool VEManifoldMesh::RemoveEdge (int v0, int v1) { std::pair<int,int> ekey(v0, v1); EMapIterator eiter = mEMap.find(ekey); if (eiter == mEMap.end()) { // Edge does not exist. return false; } EPtr edge = eiter->second; for (int i = 0; i < 2; ++i) { // Inform vertices you are going away. VMapIterator viter = mVMap.find(edge->V[i]); assertion(viter != mVMap.end(), "Unexpected condition\n"); Vertex* vertex = viter->second; assertion(vertex != 0, "Unexpected condition\n"); if (vertex->E[0] == edge) { // One-edge vertices always have pointer in slot zero. vertex->E[0] = vertex->E[1]; vertex->E[1] = 0; } else if (vertex->E[1] == edge) { vertex->E[1] = 0; } else { assertion(false, "Unexpected condition\n"); return false; } // Remove vertex if you had the last reference to it. if (!vertex->E[0] && !vertex->E[1]) { mVMap.erase(vertex->V); delete0(vertex); } // Inform adjacent edges you are going away. EPtr adjacent = edge->E[i]; if (adjacent) { for (int j = 0; j < 2; ++j) { if (adjacent->E[j] == edge) { adjacent->E[j] = 0; break; } } } } mEMap.erase(ekey); delete0(edge); return true; } //---------------------------------------------------------------------------- bool VEManifoldMesh::IsClosed () const { VMapCIterator viter = mVMap.begin(); VMapCIterator vend = mVMap.end(); for (/**/; viter != vend; ++viter) { const Vertex* vertex = viter->second; if (!vertex->E[0] || !vertex->E[1]) { return false; } } return true; } //---------------------------------------------------------------------------- void VEManifoldMesh::Print (const char* filename) { std::ofstream outFile(filename); if (!outFile) { return; } // Assign unique indices to the edges. std::map<EPtr,int> edgeIndex; edgeIndex[(EPtr)0] = 0; EMapIterator eiter = mEMap.begin(); EMapIterator eend = mEMap.end(); for (int i = 1; eiter != eend; ++eiter) { if (eiter->second) { edgeIndex[eiter->second] = i; ++i; } } // Print vertices. outFile << "vertex quantity = " << (int)mVMap.size() << std::endl; VMapIterator viter = mVMap.begin(); VMapIterator vend = mVMap.end(); for (/**/; viter != vend; ++viter) { const Vertex& vertex = *viter->second; outFile << 'v' << vertex.V << " <"; if (vertex.E[0]) { outFile << 'e' << edgeIndex[vertex.E[0]]; } else { outFile << '*'; } outFile << ','; if (vertex.E[1]) { outFile << 'e' << edgeIndex[vertex.E[1]]; } else { outFile << '*'; } outFile << '>' << std::endl; } // Print edges. outFile << "edge quantity = " << (int)mEMap.size() << std::endl; for (eiter = mEMap.begin(); eiter != eend; ++eiter) { const Edge& edge = *eiter->second; outFile << 'e' << edgeIndex[eiter->second] << " <" << 'v' << edge.V[0] << ",v" << edge.V[1] << "; "; if (edge.E[0]) { outFile << 'e' << edgeIndex[edge.E[0]]; } else { outFile << '*'; } outFile << ','; if (edge.E[1]) { outFile << 'e' << edgeIndex[edge.E[1]]; } else { outFile << '*'; } outFile << '>' << std::endl; } outFile << std::endl; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // VEManifoldMesh::Vertex //---------------------------------------------------------------------------- VEManifoldMesh::Vertex::Vertex (int v) { V = v; E[0] = 0; E[1] = 0; } //---------------------------------------------------------------------------- VEManifoldMesh::Vertex::~Vertex () { } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // VEManifoldMesh::Edge //---------------------------------------------------------------------------- VEManifoldMesh::Edge::Edge (int v0, int v1) { V[0] = v0; V[1] = v1; E[0] = 0; E[1] = 0; } //---------------------------------------------------------------------------- VEManifoldMesh::Edge::~Edge () { } //----------------------------------------------------------------------------
Java
UTF-8
810
2.015625
2
[]
no_license
package com.example.mmz.englishofcivilengineering; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class add_page_back extends AppCompatActivity { Button a2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_page); a2= (Button) findViewById(R.id.button2); a2.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intocan4= new Intent(add_page_back.this, welcome.class); startActivity(intocan4); } }); } }
Go
UTF-8
871
2.96875
3
[]
no_license
package gochat import ( "flag" log "github.com/sirupsen/logrus" ) // Conf holds all our server config type Conf struct { ListenOn string MaxMsgSize int } // NewConfFromFlags parses CLI flags and returns a config object func NewConfFromFlags() (conf *Conf, err error) { var ( listenOn string logLevel string maxMsgSize int ) flag.StringVar(&listenOn, "listen-on", "0.0.0.0:8080", "Inteface:port to listen on") flag.StringVar(&logLevel, "log-level", "info", "Logrus log level") flag.IntVar(&maxMsgSize, "max-msg-size", 1024, "Websocket messages above this size are dropped") flag.Parse() // Set log level level, err := log.ParseLevel(logLevel) if err != nil { log.WithField("ctx", "Config").Panicf("Error parsing logrus log level: %v", err) } log.SetLevel(level) return &Conf{ ListenOn: listenOn, MaxMsgSize: maxMsgSize, }, nil }
JavaScript
UTF-8
597
2.65625
3
[]
no_license
import * as d3 from 'd3'; export default class ChartBase { constructor(options) { this.data = options.data; const domNode = this._initDomNode(options); this.height = domNode.clientHeight; this.width = domNode.clientWidth; this.element = d3.select(domNode); } _initDomNode(options) { let domNode; if (options.el) { domNode = options.el; } else { domNode = document.querySelector(options.selector); } if (!domNode) { throw new Error('DOM node needs to be specified by `options.el` or `options.selector`.'); } this.domNode = domNode; return domNode; } }
C#
UTF-8
383
3.265625
3
[ "MIT" ]
permissive
using System; namespace Crice_Area { class Program { static void Main(string[] args) { double radius = double.Parse(Console.ReadLine()); double area = Math.PI * radius * radius; double perimeter = 2 * Math.PI * radius; Console.WriteLine(area); Console.WriteLine(perimeter); } } }
JavaScript
UTF-8
870
2.578125
3
[ "MIT" ]
permissive
const Discord = require("discord.js"); module.exports = { name: "ping", aliases: ["🏓"], category: "botinfo", description: "Returns bot and API latency in milliseconds.", usage: "ping", clientPermissions: ["EMBED_LINKS", "SEND_MESSAGES", "VIEW_CHANNEL"], userPermissions: [], clearanceLevel: 0, run: (client, message, _args) => { const latency = Math.floor(new Date().getTime() - message.createdTimestamp); const apiLatency = Math.round(client.ws.ping); const embed = new Discord.MessageEmbed() .setColor(process.env.COLOR) .setTitle("🏓 Pong!") .setDescription( `Bot Latency is **${latency} ms** \nAPI Latency is **${apiLatency} ms**` ) .setTimestamp() .setFooter( `Executed by ${message.author.username}#${message.author.discriminator}`, message.author.avatarURL() ); return message.channel.send(embed); }, };
Swift
UTF-8
1,797
2.625
3
[]
no_license
// // UserDefaultsManager.swift // NetworkExtensions // // Created by Henrik Peters on 31.12.19. // Copyright © 2019 Henrik Peters. All rights reserved. // import Foundation // MARK: - UserDefaults Extension extension UserDefaults { static var group: UserDefaults? { return UserDefaults(suiteName: Constants.appGroupIdentifier)! } } // MARK: - UserDefaultsManager class UserDefaultsManager { // MARK: - UserDefaultsConstants static let keyPrefix = "sharedData_" // MARK: - Public Routines :: Setter static func setSingleString(value v: String, forKey k: String) { NSLog(UserDefaults.group!.dictionaryRepresentation().description ) //NSLog(FileManager().containerURL(forSecurityApplicationGroupIdentifier: "group.com.research.NetworkExtensions")!.appendingPathComponent("Library/Preferences").absoluteString) UserDefaults.group!.set(v, forKey: self.keyPrefix+k) } static func setStringArray(value v: [String], forKey k: String) { UserDefaults.group!.set(v, forKey: self.keyPrefix+k) } // MARK: - Public Routines :: Getter static func getData(forKey k: String) -> Any? { if k.hasPrefix(self.keyPrefix) { return UserDefaults.group!.object(forKey: k) } else { return UserDefaults.group!.object(forKey: self.keyPrefix+k) } } static func getAllValues() -> Dictionary<String, Any>.Values { return (UserDefaults.group?.dictionaryRepresentation().values)! } static func getAllKeys() -> Dictionary<String, Any>.Keys { return (UserDefaults.group?.dictionaryRepresentation().keys)! } static func getAllData() -> Dictionary<String, Any> { return (UserDefaults.group?.dictionaryRepresentation())! } }
Python
UTF-8
4,738
3.171875
3
[]
no_license
import pyautogui def drop_all_ores(self): if self.num_ores >= self.capacity: """Drops all ores from the player's inventory""" cv2.waitKey(4000) first_ore_x, first_ore_y = self.ores[0][0], self.ores[0][1] pyautogui.doubleClick(first_ore_x, first_ore_y) x_coord, y_coord = 793, 800 pyautogui.keyDown('shift') # 1st column pyautogui.moveTo(x_coord, y_coord) pyautogui.click(x_coord, y_coord) pyautogui.moveTo(x_coord, y_coord + 35,0.2) pyautogui.click() pyautogui.moveTo(x_coord, y_coord + 70,0.2) pyautogui.click() pyautogui.moveTo(x_coord, y_coord + 105,0.2) pyautogui.click() pyautogui.moveTo(x_coord, y_coord + 140,0.2) pyautogui.click() pyautogui.moveTo(x_coord, y_coord + 175,0.2) pyautogui.click() pyautogui.moveTo(x_coord, y_coord + 210,0.2) pyautogui.click() #2nd colum pyautogui.moveTo(x_coord + 42, y_coord,0.5) pyautogui.click() pyautogui.moveTo(x_coord+ 42, y_coord + 35,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 42, y_coord + 70,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 42, y_coord + 105,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 42, y_coord + 140,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 42, y_coord + 175,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 42, y_coord + 210,0.2) pyautogui.click() # 3rd column pyautogui.moveTo(x_coord + 84, y_coord, 0.5) pyautogui.click() pyautogui.moveTo(x_coord+ 84, y_coord + 35,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 84, y_coord + 70,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 84, y_coord + 105,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 84, y_coord + 140,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 84, y_coord + 175,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 84, y_coord + 210,0.2) pyautogui.click() #4th column pyautogui.moveTo(x_coord + 126, y_coord, 0.5) pyautogui.click() pyautogui.moveTo(x_coord+ 126, y_coord + 35,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 126, y_coord + 70,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 126, y_coord + 105,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 126, y_coord + 140,0.2) pyautogui.click() pyautogui.moveTo(x_coord+ 126, y_coord + 175,0.2) pyautogui.click() pyautogui.keyUp('shift') #self.num_ores -= 1 #print(self.num_ores) cv2.waitKey(400) self.ores = [] def drop_all_ores(self): if self.num_ores >= self.capacity: """Drops all ores from the player's inventory""" cv2.waitKey(4000) first_ore_x, first_ore_y = self.ores[0][0], self.ores[0][1] pyautogui.doubleClick(first_ore_x, first_ore_y) for ore_coord in self.ores: x_coord, y_coord = pyautogui.center(ore_coord) pyautogui.keyDown('shift') pyautogui.moveTo(x_coord, y_coord) pyautogui.click(x_coord, y_coord) pyautogui.keyUp('shift') self.num_ores -= 1 print(self.num_ores) cv2.waitKey(400) self.ores = [] def ores(): """ Initialize the player's inventory based on its initial state represented by <image> :param image: The initial state of the player's inventory. """ # List of all ores currently in inventory orez = [ore for ore in pyautogui.locateAllOnScreen('oreimg.PNG', confidence=0.9) if 765 <= ore[0] <= 945] print(orez) ores = [] find_iron = list (pyautogui.locateAllOnScreen('oreimg.PNG', confidence=0.9)) find_copper = list (pyautogui.locateAllOnScreen('copper.PNG', confidence=0.9)) for ore in find_iron: ores.append(ore) for ore in find_copper: ores.append(ore) print(ores) ores()
Markdown
UTF-8
617
2.703125
3
[]
no_license
# CookBook ## It is a one stop for all your recipes. - Browse through multiple categories of cuisines/seasonal foods/ingredient special recipes. <br> - You can get a customized diet plan from our experts with recipes of your all day intake.<br> - Find special articles about each ingredient.<br> - Get inspiration to cook.Videos and instructions for everyone to understand.<br> - Go through our customer reviews and ratings.<br> - Contribute a recipe, and get a chance to meet & cook with our partnered master chef's.<br><br> ##### Build with - HTML5, CSS. Used Flexbox,media queries to make it responsive.
Java
UTF-8
1,465
2.34375
2
[]
no_license
package sut.se.G09.Backend.Entity; import javax.persistence.Entity; import javax.persistence.*; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.constraints.NotNull; import lombok.*; @Entity //บอกว่าเป็น class com.okta.developer.demo.Entity class ที่เก็บขอมูล @Data // lombox จะสร้าง method getter setter ให้เอง @Table(name="ReasonMember") //ชื่อตาราง public class ReasonMember { //เหตุผลในการยกเลิกสมาชิก public Long getiD() { return iD; } public void setiD(Long iD) { this.iD = iD; } public String getReasonMemberName() { return reasonMemberName; } public void setReasonMemberName(String reasonMemberName) { this.reasonMemberName = reasonMemberName; } @Id @SequenceGenerator(name = "ReasonMember_seq", sequenceName = "ReasonMember_seq") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ReasonMember_seq") @Column(name = "ReasonMemberId", unique = true, nullable = false, length = 100) private Long iD; @NotNull(message="ReasonMember not be null") private String reasonMemberName; public ReasonMember() {} public ReasonMember(String reasonMemberName){ //constructor this.reasonMemberName = reasonMemberName; } }
Java
GB18030
1,418
2.359375
2
[]
no_license
package com.gyic.claim.dto.custom; import java.io.Serializable; import com.gyic.claim.dto.domain.HousepolicylistDto; import com.sinosoft.claim.dto.domain.PrpCmainDto; /** * HERDPOLICYLISTݴ<br> */ public class IdcardRegistDto implements Serializable{ private static final long serialVersionUID = 1L; private HousepolicylistDto housepolicylistDto = null; private PrpCmainDto prpCmainDto = null; /** * ĬϹ췽,һĬϵHerdpolicylistDto */ public IdcardRegistDto(){ } /** * herdpolicylistDto * @param herdpolicylistDto õherdpolicylistDtoֵ */ public void setHousepolicylistDto(HousepolicylistDto housepolicylistDto){ this.housepolicylistDto = housepolicylistDto; } /** * PrpCmainDto * @param PrpCmainDto õPrpCmainDtoֵ */ public void setPrpCmainDto(PrpCmainDto prpCmainDto){ this.prpCmainDto = prpCmainDto; } /** * ȡhousepolicylistDto * @return housepolicylistDtoֵ */ public HousepolicylistDto getHousepolicylistDto(){ return this.housepolicylistDto; } /** * ȡprpCmainDto * @return prpCmainDtoֵ */ public PrpCmainDto getPrpCmainDto(){ return this.prpCmainDto; } }
C++
UTF-8
3,897
2.96875
3
[]
no_license
#include "Torus.h" #include <cstdio> #include <cmath> #include <gtc/constants.hpp> namespace ShadingCookbook { Torus::Torus(float outerRadius, float innerRadius, int nsides, int nrings) : _rings(nrings), _sides(nsides) { _faces = _sides * _rings; int nVerts = _sides * (_rings + 1); float* v = new float[3 * nVerts]; float* n = new float[3 * nVerts]; float* uv = new float[2 * nVerts]; unsigned int* el = new unsigned int[6 * _faces]; GenerateVerts(v, n, uv, el, outerRadius, innerRadius); unsigned int buffersHandle[4]; glGenBuffers(4, buffersHandle); glBindBuffer(GL_ARRAY_BUFFER, buffersHandle[0]); glBufferData(GL_ARRAY_BUFFER, (3 * nVerts) * sizeof(float), v, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, buffersHandle[1]); glBufferData(GL_ARRAY_BUFFER, (3 * nVerts) * sizeof(float), n, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, buffersHandle[2]); glBufferData(GL_ARRAY_BUFFER, (2 * nVerts) * sizeof(float), uv, GL_STATIC_DRAW); delete[] v; delete[] n; delete[] uv; glGenVertexArrays(1, &_vaoHandle); glBindVertexArray(_vaoHandle); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, buffersHandle[0]); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, buffersHandle[1]); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, buffersHandle[2]); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffersHandle[3]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * _faces * sizeof(unsigned int), el, GL_STATIC_DRAW); delete[] el; glBindVertexArray(0); } void Torus::Render() { glBindVertexArray(_vaoHandle); glDrawElements(GL_TRIANGLES, 6 * _faces, GL_UNSIGNED_INT, ((GLubyte *)NULL + (0))); glBindVertexArray(0); } void Torus::GenerateVerts(float* verts, float* norms, float* tex, unsigned* el, float outerRadius, float innerRadius) { float ringFactor = glm::two_pi<float>() / _rings; float sideFactor = glm::two_pi<float>() / _sides; int idx = 0, tidx = 0; for (int ring = 0; ring <= _rings; ring++) { float u = ring * ringFactor; float cu = cosf(u); float su = sinf(u); for (int side = 0; side < _sides; side++) { float v = side * sideFactor; float cv = cosf(v); float sv = sinf(v); float r = (outerRadius + innerRadius * cv); verts[idx] = r * cu; verts[idx + 1] = r * su; verts[idx + 2] = innerRadius * sv; norms[idx] = cv * su * r; norms[idx + 1] = cv * su * r; norms[idx + 2] = sv * r; tex[tidx] = u / glm::two_pi<float>(); tex[tidx + 1] = v / glm::two_pi<float>(); tidx += 2; float len = sqrt(norms[idx] * norms[idx] + norms[idx + 1] * norms[idx + 1] + norms[idx + 2] * norms[idx + 2]); norms[idx] /= len; norms[idx + 1] /= len; norms[idx + 2] /= len; idx += 3; } } idx = 0; for (int ring = 0; ring < _rings; ring++) { int ringStart = ring * _sides; int nextRingStart = (ring + 1) * _sides; for (int side = 0; side < _sides; side++) { int nextSide = (side + 1) % _sides; el[idx] = (ringStart + side); el[idx + 1] = (nextRingStart + side); el[idx + 2] = (nextRingStart + nextSide); el[idx + 3] = (ringStart + side); el[idx + 4] = (nextRingStart + nextSide); el[idx + 5] = (ringStart + nextSide); idx += 6; } } } int Torus::GetVertexArrayHandle() { return this->_vaoHandle; } }
Java
UTF-8
382
1.867188
2
[]
no_license
package org.dei.perla.context; import java.util.List; public interface IComposerManager { public void composeBlock(Context c); public void addPossibleContext(Context ctx); public Context getPossibleContext(String ctxName); public void removePossibleContext(Context toDetect); public List<Context> getPossibleContexts(); public List<Context> getInvalidContexts(); }
Python
UTF-8
1,311
2.828125
3
[]
no_license
import matplotlib.pyplot as plt import pandas as pd from racing_reference_constants import * racing_data = pd.read_csv('../data/racing_reference2.csv', encoding='latin1', parse_dates=['Date']) def scatter_by_race(column1, column2): for race in racing_data['Race'].unique(): qualifying_data = racing_data[(racing_data[column1] != -1) & (racing_data[column1] != "-1") & (racing_data['Race'] == race)].sort_values(column1) if qualifying_data.size == 0: continue plt.scatter(qualifying_data[column1], qualifying_data[column2]) plt.xlabel(column1) plt.ylabel(column2) plt.show() def hist2d(column1, column2): filtered_data = racing_data[(racing_data[column1] != -1) & (racing_data[column1] != "-1")] plt.hist2d(filtered_data[column1], filtered_data[column2]) plt.xlabel(column1) plt.ylabel(column2) plt.show() def driver_line_graph(driver_name, column): filtered_data = racing_data[racing_data[DRIVER] == driver_name].sort_values(DATE) plt.plot(filtered_data[DATE], filtered_data[column]) plt.title(driver_name) plt.xlabel(DATE) plt.ylabel(column) plt.gca().axes.get_xaxis().set_visible(False) plt.show() pass hist2d(STARTING_POSITION, FANTASY_POINTS)
Markdown
UTF-8
1,066
2.546875
3
[ "MIT" ]
permissive
# httpaccess `httpaccess`服务提供了供设备注册、登录的HTTP[接口](../api-doc/device.md)。 ## 启动参数 * `-etcd` etcd服务的访问地址,必需参数。如`http://localhost:2379`,如果etcd是多副本部署,可以用分号隔开访问地址,如`http://192.168.0.2:2379;http://192.168.0.3:2379`。 * `-httphost` HTTP服务地址,必须参数。格式为`ip:port`如`localhost:443`,强烈建议开启https选项。一般情况下绑定到外网的443端口(https默认端口)。 * `-usehttps` 是否启动https服务,默认不启用。如果启用,则必须提供以下`cafile`和`keyfile`两个参数。如果需要pando设备连接,则必须启用,否则无法连接。 * `-cafile` ssl加密证书的证书文件路径(pem格式)。 * `-keyfile` ssl加密证书的密钥文件路径(pem格式)。 * `-loglevel` 服务打印日志的级别,选填,如果没有指定则默认为`info`级别。 > 说明:ssl证书和密钥的pem文件生成方法可以参考[这里](http://killeraction.iteye.com/blog/858325)
Shell
UTF-8
915
3.5
4
[ "Apache-2.0" ]
permissive
#!/bin/bash echo "Liberty Hello World to OpenShift using UrbanCode Deploy" BUILD_VERSION=0.0.0 echo "Parameters are:" while true; do case $1 in -v | --version ) BUILD_VERSION=$2; echo "Version for new build=$BUILD_VERSION"; shift 2 ;; -- ) echo "-- $1"; shift; break ;; * ) break ;; esac done if [[ "$BUILD_VERSION" == "0.0.0" ]]; then echo "Please enter new Version with -v parameter" exit 1 fi # first step build with maven # mvn clean install # second step build container image, need input variable for version docker build . -t demowltp:"${BUILD_VERSION}" # TODO: first check/test that this version works, then use gh/gitlab cli to create new release on repo, push new version to ucd component! docker tag demowltp:"${BUILD_VERSION}" quay.io/osmanburucuibm/demowltp:"${BUILD_VERSION}" docker push quay.io/osmanburucuibm/demowltp:"${BUILD_VERSION}"
JavaScript
UTF-8
1,378
2.875
3
[]
no_license
const mongoose = require('mongoose'); const { Skill } = require("../models/skill.model"); exports.create = (req, res) => { // Validate request if (!req.body) { res.status(400).send({ message: "Content can not be empty!"}); return; } // Create a skill const skill = new Skill({ name: req.body.name, descriptions: req.body.descriptions, }); // Save skill in the database skill .save() .then(data => { res.send(data); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while creating the user." }); }); }; // Find all exports.get = (req, res) => { Skill.find() .then(data => { if (!data) res.status(404).send({ message: "Not found skills " }); else res.send(data); }) .catch(err => { res .status(500) .send({ message: "Error retrieving skills" }); }); }; // Find a single skill exports.findOne = (req, res) => { const name = req.params.name; Skill.findOne({ name: name }) .then(data => { if (!data) res.status(404).send({ message: "Not found skill with name " + name }); else res.send(data); }) .catch(err => { res .status(500) .send({ message: "Error retrieving skill with name=" + name }); }); };
Python
UTF-8
1,353
2.953125
3
[]
no_license
#!/usr/bin/env python import uuid, random, string from src.main.xsys.core.SuperBase import SuperBase from src.main.xsys.cryptography.CryptoManager import CryptoManager class DelegateCore(SuperBase, CryptoManager): """ [Description] __init__ - Construct a SuperBase Object """ def __init__(self): super(DelegateCore, self).__init__() self._hashkey = None """ [Description] generate_hashed_key - Generate a 16-byte key from a phrase :param -> phrase:str - a key to be hashed :return - a string uuid5 pra-phrase """ def generate_hash_key(self, phrase=None): if phrase is None: return uuid.uuid5(uuid.NAMESPACE_X500, self.randomize()).__str__() else: return uuid.uuid5(uuid.NAMESPACE_X500, phrase).__str__() """ [Description] randomize - Generate a random string with size of 16-bytes """ def randomize(self): return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(self.get_byte_size)) @property def hashkey(self): return self._hashkey @hashkey.getter def get_hash_key(self): return self.hashkey @hashkey.setter def set_hash_key(self, key): self._hashkey = self.generate_hash_key(key)
Python
UTF-8
1,348
3.21875
3
[]
no_license
import matplotlib.pyplot as plt import functions as fn import pandas as pd import numpy as np # Import and format Crypto Price files df_btc = fn.read_format("coin_Bitcoin.csv") df_eth = fn.read_format("coin_Ethereum.csv") df_btc_eth = fn.merge_data(df_btc, df_eth, "Date", "_btc", "_eth") df_btc_eth.index = df_btc_eth["Date"] # Define dates for analysis dates = ["2018-12", "2019-12", "2020-12", "2021-02"] # Extract desired crypto information df_year_end = [] for item in dates: df_year_end.append(df_btc_eth.loc[item, :]) df_year_end = pd.DataFrame(df_year_end) # Define plot parameters x = np.arange(len(dates)) # the label locations width = 0.35 # the width of the bars # Plot the market caps fig, ax = plt.subplots() ax.set_facecolor("gainsboro") ax.yaxis.grid(color="white", zorder=0) bar_btc = ax.bar(x - width/2, df_year_end["Marketcap_btc"]/1000000000, width, color="orange", label="Bitcoin", zorder=3) bar_eth = ax.bar(x + width/2, df_year_end["Marketcap_eth"]/1000000000, width, color="blue", label="Ethereum", zorder=3) plt.title("Bitcoin & Ethereum Market Cap") plt.ylabel("Market Cap $ (Billions)") ax.set_xticks(x) ax.set_xticklabels(dates) plt.yticks(np.arange(0, max(df_year_end["Marketcap_btc"]/1000000000), step=100)) ax.legend() # Save graph plt.savefig("BTC_ETH_Market_Cap.png")
JavaScript
UTF-8
1,922
2.65625
3
[ "MIT" ]
permissive
const initialState = { loading: false, error: null, directories: [] } const HomeReducer = (state=initialState, action) => { switch (action.type) { case 'FETCH_DIRECTORIES_BEGIN': return { ...state, loading: true, error: null, directories: [] } case 'FETCH_DIRECTORIES_SUCCESS': return { ...state, loading: false, error: null, directories: action.payload.directories } case 'FETCH_DIRECTORIES_ERROR': return { ...state, loading: false, error: action.payload.error, directories: [] } case 'REMOVE_DIRECTORIES_BEGIN': return { ...state, loading: true } case 'REMOVE_DIRECTORIES_SUCCESS': return { ...state, loading: false, directories: action.payload.directories } case 'REMOVE_DIRECTORIES_ERROR': return { ...state, loading: false, error: action.payload.error, directories: [] } case 'ADD_DIRECTORY_BEGIN': return { ...state, loading: true, } case 'ADD_DIRECTORY_SUCCESS': return { ...state, loading: false, directories: action.payload.directories } case 'ADD_DIRECTORY_ERROR': return { ...state, loading: false, error: action.payload.error, directories: [] } default: return state } } export default HomeReducer