language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
1,835
2.078125
2
[]
no_license
package it.worldpay.fede.offersmanager.dao; import static org.junit.Assert.assertEquals; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; import it.worldpay.fede.offersmanager.dao.product.food.GelatoDao; import it.worldpay.fede.offersmanager.dummy.DummyFactory; import it.worldpay.fede.offersmanager.model.product.food.Gelato; import it.worldpay.fede.offersmanager.model.product.food.Gelato.Flavor; @DataJpaTest @RunWith(SpringRunner.class) public class GelatoDaoTest { @Before public void initializeTestVariable(){ gelatoDummy = (Gelato)dummyFactory.getDummyProduct("GELATO"); } @Autowired private DummyFactory dummyFactory; @Autowired GelatoDao gelatoDao; Gelato gelatoDummy; private Gelato gelatoFound; private Gelato gelatoSaved; @Test public void whenSaveGelato_thenItIsPossibleToFetchIt(){ gelatoDao.save(gelatoDummy); gelatoFound = gelatoDao.findOne(gelatoDummy.getProductId()); assertEquals(gelatoFound.getProductId(), gelatoDummy.getProductId()); } @Test public void whenSaveGelato_thenItIsPossibleToDeleteIt(){ gelatoDao.save(gelatoDummy); gelatoDao.delete(gelatoDummy); gelatoFound = gelatoDao.findOne(gelatoDummy.getProductId()); Assert.assertNull(gelatoFound); } @Test public void whneGelatoIsSaved_thenItIspossibleToFetchItById(){ gelatoSaved =gelatoDao.save(gelatoDummy); Long gleatoSavedId = gelatoSaved.getProductId(); gelatoFound = (Gelato)gelatoDao.findByProductId(gleatoSavedId); } }
SQL
UTF-8
192
3.140625
3
[]
no_license
SELECT DepositGroup, SUM(DepositAmount) AS [Total Sum] FROM WizzardDeposits WHERE MagicWandCreator = 'Ollivander family' GROUP BY DepositGroup HAVING SUM(DepositAmount) < 150000 ORDER BY [Total Sum] DESC
Markdown
UTF-8
1,605
2.59375
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "Définir la base, commande | Microsoft Docs" ms.custom: ms.date: 11/04/2016 ms.reviewer: ms.suite: ms.technology: vs-ide-general ms.tgt_pltfrm: ms.topic: article f1_keywords: debug.setradix helpviewer_keywords: - Set Radix command - Debug.SetRadix command ms.assetid: 6ffd1554-7530-4da4-b5f5-e276a5034f3b caps.latest.revision: "11" author: gewarren ms.author: gewarren manager: ghogen ms.openlocfilehash: 060221e5abe0ff9082a04f8b75561a7e4dec9f64 ms.sourcegitcommit: f40311056ea0b4677efcca74a285dbb0ce0e7974 ms.translationtype: HT ms.contentlocale: fr-FR ms.lasthandoff: 10/31/2017 --- # <a name="set-radix-command"></a>Définir la base, commande Définit ou retourne la base numérique utilisée pour afficher les valeurs entières. ## <a name="syntax"></a>Syntaxe ``` Debug.SetRadix [10 | 16 | hex | dec] ``` ## <a name="arguments"></a>Arguments `10` ou `16` ou `hex` ou `dec` Facultatif. Indique un nombre décimal (10 ou dec) ou hexadécimal (16 ou hex). Si l’argument est omis, la valeur actuelle de la base est retournée. ## <a name="example"></a>Exemple Cet exemple configure l’environnement pour afficher les valeurs entières au format hexadécimal. ``` >Debug.SetRadix hex ``` ## <a name="see-also"></a>Voir aussi [Commandes Visual Studio](../../ide/reference/visual-studio-commands.md) [Fenêtre Commande](../../ide/reference/command-window.md) [Zone Rechercher/Commande](../../ide/find-command-box.md) [Alias de commande Visual Studio](../../ide/reference/visual-studio-command-aliases.md)
Markdown
UTF-8
2,778
3.109375
3
[ "MIT" ]
permissive
--- title: Setting up Development Environment using Vagrant date: '2012-10-03 10:55:05' tags: - cap-abhilash - cap-vimal - technology wp:post_id: '4148' link: http://www.multunus.com/blog/2012/10/setting-up-development-environment-using-vagrant/ --- **Problem** We have some projects which takes lot of effort to set up. As with every projects setting up development environment includes installing git, curl, apache, mysql-server, ruby, rvm, ruby-gems for the app, etc. and also the project specific configurations. Doing all these every time when you need to setup the development environment will be time consuming and takes a lot of effort. **Solution** Setting up the development environment in VM using Vagrant. Vagrant helps to build development environment for projects and rebuild them when needed. And this environment can be shared among the team easily. **How?** Vagrant is primarily a driver for Oracle VirtualBox virtual machines. You can download and install Vagrant from [here](http://downloads.vagrantup.com/) or you can install it as a ruby gem for the rails projects. Vagrant uses a “base box” which is a base install (an OS) for the system you are going to use. Different flavours of base boxes can be downloaded from [http://www.vagrantbox.es/](http://www.vagrantbox.es/). First step is to mark the root directory and setup the basic required files using the following command: vagrant init This will create a file called **Vagrantfile** this will contain the configuration details for the VM. After the project initailization you can download Vagrant boxes from [http://www.vagrantbox.es/](http://www.vagrantbox.es/) and add it to your project: vagrant box add lucid64 lucid64.box You can also add the box from a remote server using: vagrant box add lucid64 http://files.vagrantup.com/lucid64.box To list the boxes that you added you can use: vagrant box list Now you have to edit the Vagrantfile to use the base box that you have added. Vagrant::Config.run do |config| config.vm.box = "lucid64" end Now we can start our new VM: vagrant up This will start a fully functional VM. To access the VM you have to do ssh: vagrant ssh This will log you into the virtual machine. Now you can start setting up the development environment. Once everything is ready we can package this VM to a box. This will help us to share the virtual environment that we created with the other team members. vagrant package This will create a vagrant box with the entire dev environment setup. Now to use this any machine, you have to install Virtualbox and Vagrant. Then add this box using: vagrant box add lucid64_with_dev_setup package.box You can create a VM with this box and all the dev environment setup will be available with this VM.
Swift
UTF-8
1,185
2.90625
3
[]
no_license
// // ConfirmView.swift // RekClient (iOS) // // Created by Ivan C Myrvold on 17/05/2021. // import SwiftUI struct ConfirmView: View { @Environment(\.presentationMode) var presentationMode @State var verificationCode = "" var username: String @ObservedObject var loginHandler: LoginHandler var isConfirmationButtonDisabled: Bool { verificationCode.count != 6 } var body: some View { NavigationView { Form { TextField("Verification Code", text: $verificationCode) .keyboardType(.numberPad) } .navigationTitle("Confirm Verification Code") .toolbar(content: { Button("Confirm") { self.presentationMode.wrappedValue.dismiss() loginHandler.confirmSignup(with: username, and: verificationCode) } .disabled(isConfirmationButtonDisabled) }) } } } struct ConfirmView_Previews: PreviewProvider { static var previews: some View { let loginHandler = LoginHandler() ConfirmView(username: "myuser", loginHandler: loginHandler) } }
C
UTF-8
274
3.046875
3
[]
no_license
#include <stdio.h> int main() { int F, I, contador=0; scanf ("%d%d", &F, &I); if (F >= 140 && I >= 14){ contador++; } if (F >= 150 && I >= 12){ contador++; } if (F >= 170 || I >= 16){ contador++; } printf("%d\n", contador); return 0; }
Java
UTF-8
5,519
3.375
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package cz.salmelu.contests.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; /** * Custom class used for parsing configuration files.<br> * Defines a constructor which parses the file.<br> * Also defines methods that take the parsed values and are used by Config classes to fill the fields. * @author salmelu */ public class ConfigParser { /** holds read properties */ private Map<String, String> properties; /** * Constructs a parser and tries to parse the given file.<br> * Saves the parsed data for later uses or requests. * @param fname File to be parsed */ public ConfigParser(File fname) { properties = new HashMap<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fname)))){ String line; while((line = reader.readLine()) != null) { if(line.startsWith("#")) continue; String[] split = line.split("\\s*=\\s*", 2); if(split.length != 2 || split[0] == null || split[0].equals("") || split[1] == null || split[1] == "") continue; properties.put(split[0], split[1]); } } catch (FileNotFoundException e) { System.err.println("Couldn't find config file. Make sure there is one at config/settings.conf"); System.err.println(e.getMessage()); } catch (IOException e) { System.err.println("Couldn't open config file. Make sure it is readable"); System.err.println(e.getMessage()); } } /** * Gets an integer property parsed from the file, if it exists.<br> * If the property doesn't exist or is an invalid integer, returns default value. * @param name Name of the parsed property * @param defaultValue Value returned if something fails * @return the read property or default value */ public int getIntegerProperty(String name, int defaultValue) { if(!properties.containsKey(name)) { System.err.println("Error parsing config: Property " + name + " was not found."); return defaultValue; } try { int returnValue = Integer.parseInt(properties.get(name)); return returnValue; } catch (NumberFormatException e) { System.err.println("Error parsing config: Property " + name + " doesn't have an integer value."); return defaultValue; } } /** * Gets an integer property parsed from the file, if it exists.<br> * If the property doesn't exist, it is not a valid integer, * or it is not in allowed range returns default value. * @param name Name of the parsed property * @param defaultValue Value returned if something fails * @param min Minimal allowed value * @param max Maximal allowed value * @return the read property or default value */ public int getIntegerProperty(String name, int defaultValue, int min, int max) { int result = getIntegerProperty(name, defaultValue); if(result < min || result > max) { System.err.println("Error parsing config: Property " + name + " must be within range " + min + "-" + max + "."); return defaultValue; } return result; } /** * Gets a string property parsed from the file, if it exists.<br> * If the property doesn't exist, returns default value. * @param name Name of the parsed property * @param defaultValue Value returned if the property doesn't exist * @return the read property or default value */ public String getStringProperty(String name, String defaultValue) { if(!properties.containsKey(name)) { System.err.println("Error parsing config: Property " + name + " was not found."); return defaultValue; } return properties.get(name); } /** * Gets a string property parsed from the file, if it exists.<br> * Checks if the string is in allowed values.<br> * If the property doesn't exist or is not in allowed values, returns default value. * @param name Name of the parsed property * @param defaultValue Value returned if the property doesn't exist or it is not in allowed values * @param allowed An array or enumeration of allowed values * @return the read property or default value */ public String getAllowedStringProperty(String name, String defaultValue, String... allowed) { if(!properties.containsKey(name)) { System.err.println("Error parsing config: Property " + name + " was not found."); return defaultValue; } String loaded = properties.get(name); for(String s : allowed) { if(loaded.equalsIgnoreCase(s)) { return s; } } System.err.println("Error parsing config: Property " + name + " has invalid value " + loaded + "."); return defaultValue; } /** * Gets a boolean property parsed from the file, if it exists.<br> * If the property doesn't exist, or it is not a valid boolean, returns default value. * @param name Name of the parsed property * @param defaultValue Value returned if the property doesn't exist or it's an invalid boolean * @return the read property or default value */ public boolean getBooleanProperty(String name, boolean defaultValue) { if(!properties.containsKey(name)) { System.err.println("Error parsing config: Property " + name + " was not found."); return defaultValue; } if(properties.get(name).equalsIgnoreCase("true")) return true; else if(properties.get(name).equalsIgnoreCase("false")) return false; System.err.println("Error parsing config: Property " + name + " doesn't have a valid boolean value"); return defaultValue; } }
C++
UTF-8
3,759
2.578125
3
[ "Apache-2.0" ]
permissive
#include <stack> #include <algorithm> #include <unordered_set> #include "emptyeisner2ndf_macros.h" namespace emptyeisner2ndf { bool operator<(const ECArc & arc1, const ECArc & arc2) { if (arc1.first() != arc2.first()) { return arc1.first() < arc2.first(); } if (IS_EMPTY(arc1.second())) { if (IS_EMPTY(arc2.second())) { return LESS_EMPTY_EMPTY(arc1.second(), arc2.second()); } else { return LESS_EMPTY_SOLID(arc1.second(), arc2.second()); } } else { if (IS_EMPTY(arc2.second())) { return LESS_SOLID_EMPTY(arc1.second(), arc2.second()); } else { return LESS_SOLID_SOLID(arc1.second(), arc2.second()); } } } bool compareArc(const ECArc & arc1, const ECArc & arc2) { if (DECODE_EMPTY_POS(arc1.second()) != DECODE_EMPTY_POS(arc2.second())) { return DECODE_EMPTY_POS(arc1.second()) < DECODE_EMPTY_POS(arc2.second()); } if (ARC_LEFT(arc1.first(), arc1.second())) { if (ARC_RIGHT(arc2.first(), arc2.second())) { return false; } else { return arc1.first() > arc2.first(); } } else { if (ARC_LEFT(arc2.first(), arc2.second())) { return true; } else { return arc1.first() > arc2.first(); } } } bool operator<(const ScoreWithType & swt1, const ScoreWithType & swt2) { return swt1.getScore() < swt2.getScore(); } void Arcs2BiArcs(std::vector<ECArc> & arcs, std::vector<ECBiArc> & biarcs) { int maxid = -1; for (auto & arc : arcs) { if (!IS_EMPTY(arc.second()) && maxid < arc.second()) { maxid = arc.second(); } } for (auto & arc : arcs) { if (arc.first() == -1) { arc.refer(maxid + 1, arc.second()); break; } } biarcs.clear(); std::sort(arcs.begin(), arcs.end(), [](const ECArc & arc1, const ECArc & arc2) { return arc1 < arc2; }); auto itr_s = arcs.begin(), itr_e = arcs.begin(); while (itr_s != arcs.end()) { while (itr_e != arcs.end() && itr_e->first() == itr_s->first()) { ++itr_e; } int head = itr_s->first(); int last = -1, last_dir = -1; if (itr_e - itr_s > 1) { for (auto itr = itr_s; itr != itr_e; ++itr) { if (ARC_LEFT(head, itr->second())) { if (itr == itr_e - 1 || ARC_RIGHT(head, (itr + 1)->second())) { biarcs.push_back(ECBiArc(head, -1, itr->second())); if (IS_EMPTY(itr->second()) && last != -1) { biarcs.push_back(ECBiArc(head, -1, last)); } } else { biarcs.push_back(ECBiArc(head, (itr + 1)->second(), itr->second())); if (IS_EMPTY(itr->second()) && last != -1) { biarcs.push_back(ECBiArc(head, (itr + 1)->second(), last)); } } } else { if (itr == itr_s || ARC_LEFT(head, (itr - 1)->second())) { biarcs.push_back(ECBiArc(head, -1, itr->second())); } else { biarcs.push_back(ECBiArc(head, (itr - 1)->second(), itr->second())); if (IS_EMPTY((itr - 1)->second())) { if (itr - itr_s > 1 && ARC_RIGHT(head, (itr - 2)->second())) { biarcs.push_back(ECBiArc(head, (itr - 2)->second(), itr->second())); } else { biarcs.push_back(ECBiArc(head, -1, itr->second())); } } } last_dir = 1; } last = itr->second(); } } else { biarcs.push_back(ECBiArc(head, -1, itr_s->second())); } itr_s = itr_e; } for (auto & arc : arcs) { if (arc.first() == maxid + 1) { arc.refer(-1, arc.second()); break; } } } int findInnerSplit(const ScoreAgenda & agendaBeam, const int & split) { int is = -1; for (const auto & agenda : agendaBeam) { if (agenda->getSplit() == split) { is = agenda->getInnerSplit(); break; } } if (is == -1) { std::cout << "bad eisner at " << __LINE__ << std::endl; } return is; } }
C#
UTF-8
5,338
2.546875
3
[]
no_license
using ChatBot.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Data.Linq; using System.Linq; using System.Web; namespace ChatBot.Dac { public class DeskDac : _Dac { /// <summary> /// 取得所有桌子資料 /// </summary> /// <returns></returns> public IEnumerable<DeskModel> getAllDesk() { return DB.ExecuteQuery<DeskModel>("SELECT * FROM Desk"); ; } /// <summary> /// 內用回傳桌號、訂單編號 /// </summary> /// <returns></returns> public object getFitDesk(int peopleNum, DateTime DateTimeNow) { int CustomerID = 0; //取得可入座桌號 int DeskNo = DB.ExecuteQuery<int>(@"SELECT D.DeskNo FROM Desk as D WHERE D.Seat >= {0} AND DeskStatus= '空桌' Order by Seat ", peopleNum).FirstOrDefault(); if (DeskNo != 0) { //新增顧客資料(內用故無需輸入個資預設"內用顧客") DB.ExecuteCommand("Insert into Customer(Name) Values ('內用顧客') select SCOPE_IDENTITY()"); //建立訂單(根據取得之桌號與顧客編號建立訂單) CustomerID = DB.ExecuteQuery<int>("SELECT Customer_ID from Customer order by Customer_ID desc").FirstOrDefault(); DB.ExecuteCommand("Insert into OrderForm Values ({0},{1},{2},{3},{4},{5},{6})", new object[] { peopleNum, "In", "未點餐", DateTimeNow, "", DeskNo, CustomerID }); //更新桌子狀態 DB.ExecuteCommand("Update Desk set DeskStatus = '用餐中' where DeskNo = {0}", DeskNo); //取得訂單編號 int OrderFormID = DB.ExecuteQuery<int>("select OrderForm_ID from OrderForm where Customer_ID = {0} ", CustomerID).FirstOrDefault(); //將桌號、訂單編號存入Json格式並回傳 var DeskOrderNo = new { DeskNo = DeskNo, OrderFormID = OrderFormID }; return DeskOrderNo; } else { return 0; } } /// <summary> /// 預約回傳桌號、訂單編號 /// </summary> /// <returns></returns> public object ReserveGetFitDesk(int peopleNum,string Name, string Phone, DateTime dateTime) { int CustomerID = 0; //取得可入座桌號 int DeskNo = DB.ExecuteQuery<int>(@"SELECT D.DeskNo FROM Desk as D WHERE D.Seat >= {0} AND DeskStatus= '空桌' Order by Seat ", peopleNum).FirstOrDefault(); if (DeskNo != 0) { //新增顧客資料 DB.ExecuteCommand("Insert into Customer (Name,Phone) Values ({0},{1}) select SCOPE_IDENTITY()", Name, Phone); //建立訂單(根據取得之桌號與顧客編號建立訂單) CustomerID = DB.ExecuteQuery<int>("SELECT Customer_ID from Customer order by Customer_ID desc").FirstOrDefault(); DB.ExecuteCommand("Insert into OrderForm Values ({0},{1},{2},{3},{4},{5},{6})", new object[] { peopleNum, "In", "預約", dateTime, "", DeskNo, CustomerID }); //更新桌子狀態 DB.ExecuteCommand("Update Desk set DeskStatus = '已訂位' where DeskNo = {0}", DeskNo); //取得訂單編號 int OrderFormID = DB.ExecuteQuery<int>("select OrderForm_ID from OrderForm where Customer_ID = {0} ", CustomerID).FirstOrDefault(); //將桌號、訂單編號存入Json格式並回傳 var DeskOrderNo = new { DeskNo = DeskNo, OrderFormID = OrderFormID }; return DeskOrderNo; } else { return 0; } } /// <summary> /// 預約報到根據輸入之電話號碼查詢桌號 /// </summary> /// <returns></returns> public int getReserveDesk(string Phone) { return DB.ExecuteQuery<int>(@"select O.DeskNo from Desk D join OrderForm O on D.DeskNo = O.DeskNo join Customer C on O.Customer_ID = C.Customer_ID where OrderStatus = '預約' and Phone = {0}", Phone).FirstOrDefault(); } /// <summary> /// 根據桌號呼叫服務or完成服務 /// </summary> /// <param name="deskNo"></param> /// <returns></returns> public string callServer(int deskNo, string calling) { try { DB.ExecuteCommand("UPDATE Desk SET Calling = {0} WHERE DeskNo = {1}", new object[] { calling, deskNo }); return "執行成功"; } catch { return "執行失敗"; } } } }
Java
UTF-8
10,997
2.0625
2
[]
no_license
package com.wh.interceptor; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.wh.pojo.MemberInfo; import com.wh.util.DateUtil; import com.wh.util.StringUtil; import com.wh.util.UUIDUtil; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.wh.constants.Constants; import com.wh.entity.TbPlatform; import com.wh.entity.TbWchatuser; import com.wh.entity.User; import com.wh.service.rgpp.PlatformService; import com.wh.service.rgpp.WchatuserPlatService; import com.wh.util.WebUtil; import com.wh.util.WeiXinPlatformUtil; import java.util.Date; /** * * * @author 徐优优 * @date 2016年5月6日 */ public class WxInterceptor implements HandlerInterceptor { @Autowired private WchatuserPlatService wchatuserPlatService; @Autowired private PlatformService platformService; private Logger log = LoggerFactory.getLogger(this.getClass()); /** * 该方法将在请求处理之前进行调用 SpringMVC 中的Interceptor * 是链式的调用的,在一个应用中或者说是在一个请求中可以同时存在多个Interceptor 。 每个Interceptor * 的调用会依据它的声明顺序依次执行,而且最先执行的都是Interceptor 中的preHandle 方法, * 所以可以在这个方法中进行一些前置初始化操作或者是对当前请求的一个预处理,也可以在这个方法中进行一些判断来决定请求是否要继续进行下去 * 该方法的返回值是布尔值Boolean 类型的,当它返回为false 时,表示请求结束,后续的Interceptor 和Controller * 都不会再执行;当返回值为true 时就会继续调用下一个Interceptor 的preHandle 方法,如果已经是最后一个Interceptor * 的时候就会是调用当前请求的Controller 方法。 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestPath = WebUtil.getRequestPath(request); // 如果包含个人详情页,直接跳过,因为解绑功能,会去除openId /*if (requestPath.contains("/wmh/wmhUser/wx/userInfo.htm")||requestPath.contains("/wmh/wmhUser/wx/sendMsgCode.htm")) { return true; }*/ if (requestPath.contains("/wx/") && !requestPath.contains("/wchatService/wx/wchatInterface.htm")) { HttpSession session = request.getSession(); // String platformId = "11"; String platformId = request.getParameter("platformId"); if (StringUtils.isEmpty(platformId)) { platformId = Constants.platformId; } log.info("platformId:"+platformId); // 查询id为1的公众号配置信息 TbPlatform tbPlatform = platformService.getPlatFromById(platformId); log.info("________________________1_____________________________"); // session里没有放置openId信息 if (session.getAttribute("openId") == null) { String openId = ""; String code = request.getParameter("code"); if (StringUtils.isEmpty(code)) { log.info("________________________2_____________________________"); WeiXinPlatformUtil.reqeustCode(response, request, tbPlatform); return false; } else { log.info("________________________3_____________________________"); log.info("获取到用户的code:{}", code); JSONObject object = WeiXinPlatformUtil.getOpenIdStrByCode(code, tbPlatform); openId = object.getString("openid"); if (!StringUtils.isEmpty(openId)) { log.info("________________________4_____________________________"); TbWchatuser wchatuser = this.wchatuserPlatService.findWchatUserByOpenId(openId); if (wchatuser == null || (null != wchatuser && wchatuser.getStatus() != 1 && wchatuser.getStatus() != -1)) { // 数据库中没有用户信息 log.info("________________________4.3_____________________________"); if ("snsapi_userinfo".equals(object.getString("scope"))) { log.info("________________________4.1_____________________________"); MemberInfo memberInfo = WeiXinPlatformUtil.getMemberInfoBySNS(openId, platformId, object.getString("access_token"));// 去微信服务器请求数据,查询用户有没有 // 授权 if (null != memberInfo && !StringUtils.isEmpty(memberInfo.getOpenid())) { // 这里是用户授权登陆的处理方法 log.info("________________________4.5_____________________________"); log.info("微信服务器记录,授权登陆的用户:{}", memberInfo.getNickname()); TbWchatuser tbWchatuser = new TbWchatuser(); tbWchatuser.setNickName(memberInfo.getNickname()); tbWchatuser.setHeadImg(memberInfo.getHeadimgurl()); tbWchatuser.setCreatetime(new Date()); tbWchatuser.setSource("-1"); tbWchatuser.setOpenid(memberInfo.getOpenid()); tbWchatuser.setStatus(memberInfo.getSubscribe()); tbWchatuser.setPlatformId(platformId); tbWchatuser.setId(UUIDUtil.getUUID()); wchatuserPlatService.saveOrAddBySns(tbWchatuser); session.setAttribute("openId", openId); session.setAttribute("platformId", platformId); return true; } else {// 尚未关注公众号 log.info("________________________4.6_____________________________"); response.sendRedirect("/resource/wx/unsubscribe.html"); } } else { log.info("________________________4.2_____________________________"); MemberInfo memberInfo = WeiXinPlatformUtil.getMemberInfo(openId, platformId);// 去微信服务器请求数据,查询用户有没有关注 if (null != memberInfo && !StringUtils.isEmpty(memberInfo.getOpenid())) { // 这里是关注过公众号,但是因为一些原因,没有记录到数据库中的处理方法 log.info("微信服务器记录关注,数据库没有及时获取的用户:{}", memberInfo.getNickname()); TbWchatuser tbWchatuser = new TbWchatuser(); log.info("________________________4.7_____________________________"); tbWchatuser.setNickName(memberInfo.getNickname()); tbWchatuser.setHeadImg(memberInfo.getHeadimgurl()); tbWchatuser.setCreatetime(new Date()); tbWchatuser.setSource("-1"); tbWchatuser.setOpenid(memberInfo.getOpenid()); tbWchatuser.setStatus(memberInfo.getSubscribe()); tbWchatuser.setPlatformId(platformId); tbWchatuser.setId(UUIDUtil.getUUID()); wchatuserPlatService.add(tbWchatuser); session.setAttribute("openId", openId); session.setAttribute("platformId", platformId); return true; } else {// 尚未关注公众号,去关注公众号 log.info("________________________4.8_____________________________"); response.sendRedirect("/resource/wx/unsubscribe.html"); } } } else { log.info("________________________4.4_____________________________"); session.setAttribute("openId", openId); session.setAttribute("platformId", platformId); return true; } } else { response.sendRedirect("/resource/wx/unsubscribe.html"); } } } else { log.info("________________________5_____________________________"); String openId = (String) session.getAttribute("openId"); TbWchatuser wchatuser = this.wchatuserPlatService.findWchatUserByOpenId(openId); // 关注过公众号 if (null != wchatuser && (wchatuser.getStatus() == 1 || wchatuser.getStatus() == -1)) { Object userId=null; userId=session.getAttribute("userId"); if (StringUtil.isNotEmpty(userId)) { log.info("________________________5.1_____________________________"); return true; }else{ } log.info("________________________6_____________________________"); return true; } else { log.info("________________________7_____________________________"); // status:0未关注过公众号 MemberInfo memberInfo = WeiXinPlatformUtil.getMemberInfo(openId, platformId);// 去微信服务器请求数据,查询用户有没有关注 if (null != memberInfo && !StringUtils.isEmpty(memberInfo.getOpenid())) { // 这里是关注过公众号,但是因为一些原因,没有记录到数据库中的处理方法 log.info("微信服务器记录关注,数据库没有及时获取的用户:{}", memberInfo.getNickname()); TbWchatuser tbWchatuser = new TbWchatuser(); log.info("________________________4.7_____________________________"); tbWchatuser.setNickName(memberInfo.getNickname()); tbWchatuser.setHeadImg(memberInfo.getHeadimgurl()); tbWchatuser.setCreatetime(new Date()); tbWchatuser.setSource("-1"); tbWchatuser.setOpenid(memberInfo.getOpenid()); tbWchatuser.setStatus(memberInfo.getSubscribe()); tbWchatuser.setPlatformId(platformId); tbWchatuser.setId(UUIDUtil.getUUID()); wchatuserPlatService.add(tbWchatuser); session.setAttribute("openId", openId); session.setAttribute("platformId", platformId); return true; } else {// 尚未关注公众号,去关注公众号 log.info("________________________4.8_____________________________"); response.sendRedirect("/resource/wx/unsubscribe.html"); } //response.sendRedirect("/resource/wx/unsubscribe.html"); } } } else { return true; } log.info("________________________8_____________________________"); return false; } /** * 由preHandle 方法的解释我们知道这个方法包括后面要说到的afterCompletion 方法都只能是在当前所属的Interceptor * 的preHandle 方法的返回值为true 时才能被调用 postHandle * 方法,顾名思义就是在当前请求进行处理之后,也就是Controller 方法调用之后执行, 但是它会在DispatcherServlet * 进行视图返回渲染之前被调用, 所以我们可以在这个方法中对Controller 处理之后的ModelAndView 对象进行操作 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO } /** * 该方法也是需要当前对应的Interceptor 的preHandle 方法的返回值为true 时才会执行。 * 顾名思义,该方法将在整个请求结束之后,也就是在DispatcherServlet 渲染了对应的视图之后执行。 * 这个方法的主要作用是用于进行资源清理工作的 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO } }
C++
UTF-8
800
3.140625
3
[]
no_license
#include "pch.h" #include "TriggerFactory.h" TriggerFactory::TriggerFactory() {} /// @brief Register trigger with its name in factory for later cloning /// @param name /// @param trigger void TriggerFactory::registerTrigger(string name, shared_ptr<BaseTrigger> trigger) { if (triggerMap.count(name) == 0) { triggerMap.insert(pair<std::string, shared_ptr<BaseTrigger>>(name, trigger)); } else { throw exception("identifier already registered"); } } /// @brief Creates an empty triger to clone to /// @param name /// @param id /// @return shared_ptr<BaseTrigger> TriggerFactory::create(string name, int id) { if (triggerMap.count(name) > 0) { shared_ptr<BaseTrigger> clone = triggerMap[name]->clone(id); return clone; } else { throw exception("identifier does not exist"); } }
Python
UTF-8
464
3.203125
3
[]
no_license
#!/usr/bin/env python3 import re with open('input.txt') as _file: input_data = _file.read() passports = re.split(r"\n\n", input_data) valid_passports = 0 for passport in passports: fields = re.split(r"\s|\n", passport) if len(fields) == 8: valid_passports += 1 continue if len(fields) < 7: continue if re.search('cid', passport): continue else: valid_passports += 1 print(valid_passports)
Java
UTF-8
2,187
2.328125
2
[ "MIT" ]
permissive
package org.checkerframework.framework.qual; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.LOCAL_VARIABLE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PACKAGE; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; /** * Applied to a declaration of a package, type, method, variable, etc., * specifies that the given annotation should be the default. The default is * applied to type uses within the declaration for which no other * annotation is explicitly written. * (The default is not applied to the "parametric locations": class * declarations, type parameter declarations, and type parameter uses.) * If multiple DefaultQualifier annotations are in scope, the innermost one * takes precedence. * DefaultQualifier takes precedence over {@link DefaultQualifierInHierarchy}. * <p> * * If you wish to write multiple @DefaultQualifier annotations (for * unrelated type systems, or with different {@code locations} fields) at * the same location, use {@link DefaultQualifiers}. * * @see TypeUseLocation * @see DefaultQualifiers * @see DefaultQualifierInHierarchy * @see DefaultFor */ @Documented @Retention(RetentionPolicy.SOURCE) @Target({PACKAGE, TYPE, CONSTRUCTOR, METHOD, FIELD, LOCAL_VARIABLE, PARAMETER}) public @interface DefaultQualifier { /** * The Class for the default annotation. * * <p> * * To prevent affecting other type systems, always specify an annotation * in your own type hierarchy. (For example, do not set * "org.checkerframework.framework.qual.Unqualified" as the default.) */ Class<? extends Annotation> value(); /** @return the locations to which the annotation should be applied */ TypeUseLocation[] locations() default { TypeUseLocation.ALL }; }
C#
UTF-8
952
2.546875
3
[]
no_license
public partial class FrmItemSearch : Form { private FrmMasterItem f_mb; public FrmItemSearch(FrmMasterItem fmb) { f_mb = fmb; InitializeComponent(); } private void FrmItemSearch_Load(object sender, EventArgs e) { ataGridView1.DataSource = DAL.GetSourceFromDatabase(DAL.query); } } public static class DAL { public static string query = "MyQuery" public static BindingSource GetSourceFromDatabase(string query) { MySqlConnection conn = DBUtils.GetDbConnection(); conn.Open(); MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn); DataTable dt = new DataTable(); adapter.Fill(dt); BindingSource bSource = new BindingSource(); bSource.DataSource = dt; return dt; } }
Rust
UTF-8
2,675
2.625
3
[ "Apache-2.0", "MIT" ]
permissive
// Copyright 2020 Parity Technologies // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! benchmarking for impl_serde //! should be started with: //! ```bash //! cargo bench //! ``` use criterion::{black_box, criterion_group, criterion_main, Criterion, ParameterizedBenchmark}; use serde_derive::{Deserialize, Serialize}; // TODO(niklasad1): use `uint::construct_uint` when a new version of `uint` is released use impl_serde::impl_uint_serde; use uint::*; mod input; construct_uint! { pub struct U256(4); } impl_uint_serde!(U256, 4); #[derive(Debug, Deserialize, Serialize)] struct Bytes(#[serde(with = "impl_serde::serialize")] Vec<u8>); criterion_group!(impl_serde, u256_to_hex, hex_to_u256, bytes_to_hex, hex_to_bytes,); criterion_main!(impl_serde); fn u256_to_hex(c: &mut Criterion) { c.bench( "u256_to_hex", ParameterizedBenchmark::new( "", |b, x| b.iter(|| black_box(serde_json::to_string(&x))), vec![ U256::from(0), U256::from(100), U256::from(u32::max_value()), U256::from(u64::max_value()), U256::from(u128::max_value()), U256([1, 2, 3, 4]), ], ), ); } fn hex_to_u256(c: &mut Criterion) { let parameters = vec![ r#""0x0""#, r#""0x1""#, r#""0x10""#, r#""0x100""#, r#""0x1000000000000000000000000000000000000000000000000000000000000100""#, ]; c.bench( "hex_to_u256", ParameterizedBenchmark::new("", |b, x| b.iter(|| black_box(serde_json::from_str::<U256>(&x))), parameters), ); } fn bytes_to_hex(c: &mut Criterion) { let parameters = vec![ serde_json::from_str::<Bytes>(&input::HEX_64_CHARS).unwrap(), serde_json::from_str::<Bytes>(&input::HEX_256_CHARS).unwrap(), serde_json::from_str::<Bytes>(&input::HEX_1024_CHARS).unwrap(), serde_json::from_str::<Bytes>(&input::HEX_4096_CHARS).unwrap(), serde_json::from_str::<Bytes>(&input::HEX_16384_CHARS).unwrap(), serde_json::from_str::<Bytes>(&input::HEX_65536_CHARS).unwrap(), ]; c.bench( "bytes to hex", ParameterizedBenchmark::new("", |b, x| b.iter(|| black_box(serde_json::to_string(&x))), parameters), ); } fn hex_to_bytes(c: &mut Criterion) { let parameters = vec![ input::HEX_64_CHARS, input::HEX_256_CHARS, input::HEX_1024_CHARS, input::HEX_4096_CHARS, input::HEX_16384_CHARS, input::HEX_65536_CHARS, ]; c.bench( "hex to bytes", ParameterizedBenchmark::new("", |b, x| b.iter(|| black_box(serde_json::from_str::<Bytes>(&x))), parameters), ); }
Ruby
UTF-8
36
2.671875
3
[ "Apache-2.0" ]
permissive
def multiple(p,n) n % p == 0 end
Markdown
UTF-8
1,211
2.5625
3
[ "MIT" ]
permissive
## Project Folder To deploy an app with Dash Enterprise and Conda, three additional files are needed in your **project folder**: 1. A `requirements.txt` file to describe packages to be installed with `pip`. This include Dash Enterprise dependencies like `dash-design-kit` and `dash-snapshots`. 2. A `conda-requirements.txt` file to describe your app's dependencies 3. A `Procfile` to declare what commands & processes should be run to run the Dash app and any other background processes A minimal project structure might look like this: ``` |-- app.py |-- Procfile |-- conda-requirements.txt |-- requirements.txt ``` You may also include optional files such as `apt-packages` file if your app requires additional system-level packages like database drivers, an `app.json` file if you want to call scripts when deploying changes, or a `CHECKS` file if you want to customize pre-release health checks. If you need to specify your conda runtime declare it in a `conda-runtime.txt` file. A more complex project structure might look like this: ``` |-- app.py |-- CHECKS |-- .condarc |-- Procfile |-- conda-requirements.txt |-- conda-runtime.t |-- requirements.txt |-- apt-packages |-- app.json ``` ---
C#
UTF-8
894
3.859375
4
[]
no_license
using System; namespace detyra6 { class Program { static void Main(string[] args) { Console.WriteLine("Enter first number: "); int firstNumber = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter second number: "); int secondNumber = Convert.ToInt32(Console.ReadLine()); Console.WriteLine($"First number is {firstNumber}, second number is {secondNumber}"); if (firstNumber > secondNumber) { Console.WriteLine($"{firstNumber} is greater than {secondNumber}"); } else if (firstNumber == secondNumber) { Console.WriteLine("Numbers are equal"); } else { Console.WriteLine($"{secondNumber} is greater than {firstNumber}"); } } } }
Java
UTF-8
132
1.6875
2
[]
no_license
import java.util.TimerTask; public class AnimPersoChoix extends TimerTask{ public void run(){ Fenetre.panSP.repaint(); } }
C
UTF-8
351
3.484375
3
[]
no_license
#include <stdio.h> int num = 0; unsigned int mask = 1; void Check(unsigned int x) { if (x == 0) printf("1의 개수는 %d개", num); else { if ((mask & x) == mask) num++; return Check(x >> 1); } } int main() { unsigned int argument; printf("1의 개수를 셀 수를 입력하세요:"); scanf("%u", &argument); Check(argument); }
JavaScript
UTF-8
5,242
3.171875
3
[]
no_license
const port = 8000; // node modules 또는 우리가 만든 js 파일: Module const express = require('express'); // express 모듈을 요청 const app = express(); // express 실행 const bodyParser = require('body-parser'); // post방식의 요청시 body를 해석하는 모듈 const db = require("./modules/mysql_conn"); const util = require("./modules/util"); // 서버를 실행한다. app.listen(port, () => { console.log("connected " + port); console.log("http://localhost:8000"); }); // 정적 페이지 처리 및 초기 셋팅 app.set("view engine", "pug"); // pug를 view template engine 으로 지정 app.set("views", "./views"); // pug 파일이 존재하는 폴더를 지정 app.use("/", express.static('./public/')); // 정적 html 파일 루트 지정 app.use(bodyParser.urlencoded({extended: false})); app.locals.pretty = true; // res tag가 줄맞춤 되어 보이게 함 // Routing 작업 app.get("/test", (req, res) => { id = req.query.id; // 조건 ? 참일때 : 거짓일때 - 삼항조건문 id ? res.send(`<h1>Hello Node.js</h1>`) : res.send(`<h1 style="color: red;">Require [id]</h1>`); /* if(id == "0") res.send(`<h1>Hello Node.js</h1>`); else res.send(`<h1 style="color: red;">Require [id]</h1>`); */ }); // 동적페이지 - get - query방식 app.get("/test2", (req, res) => { var books = [ {id: 1, bookName: "홍길동전", desc: "아버지를 아버지라..."}, {id: 2, bookName: "별주부전", desc: "용왕이 나의 간을..."}, {id: 3, bookName: "구운몽전", desc: "한 여름밤의 꿈..."} ]; var id = req.query.id; // 주소줄로 요청이 들어온 변수에 접근 var bookName = books[id].bookName; var desc = books[id].desc; var html = ` <!doctype html> <html> <head> <meta charset="utf-8"> <title>도서정보: ${bookName}</title> </head> <body style="text-align: center;"> <div> <h1>${bookName}</h1> </div> <div> <h3>${desc}</h3> </div> </body> </html>`; res.send(html); }); // 동적페이지 - post - bodyParser가 필요함 app.post("/test_input", (req, res) => { var bookName = req.body.bookName; // 데이터베이스 저장 res.send(`${bookName}이(가) 잘 저장되었습니다.`); }); // 동적페이지 - get - sementic방식 app.get(["/book", "/book/:id"], (req, res) => { var books = [ {id: 1, bookName: "홍길동전", desc: "아버지를 아버지라..."}, {id: 2, bookName: "별주부전", desc: "용왕이 나의 간을..."}, {id: 3, bookName: "구운몽전", desc: "한 여름밤의 꿈..."} ]; // req.query.id -> get /book?id=1 // req.body.id -> post /book id=1 // req.params.id -> get /book/1 var id = req.params.id; var vals = { bookName: books[id].bookName, sample: ["one", "two", "three", "four"] }; res.render("sample", vals); }); // view engine - gen coding (emmet) // jade -> pug, ejs(jsp), jsx(react) app.get("/include", (req, res) => { var sendValues = { docTitle: "Include 샘플페이지", cssName: "include" } res.render("include", sendValues); }); /* // Callback 버전 app.post("/board_save", (req, res) => { var comment = req.body.comment; var sql = "INSERT INTO sample SET comment=?, wdate=?"; var d = new Date(); var values = [comment, d]; db.conn.getConnection((err, connect) => { if(err) res.send("접속이 실패했습니다.") else { connect.query(sql, values, (err, result) => { connect.release(); if(err) res.send("에러가 발생했습니다.") else res.redirect("/board_list"); }); } }); }); */ app.post("/board_save", (req, res) => { const comment = req.body.comment; const sql = "INSERT INTO sample SET comment=?, wdate=?"; const vals = [comment, util.dtChg(new Date())]; const success = data => { res.redirect("/board_list"); }; db.sqlExec(sql, vals).then(success).catch(db.sqlError); }); /* app.get("/board_list", (req, res) => { var sql = "SELECT * FROM sample ORDER BY id DESC"; db.conn.getConnection((err, connect) => { if(err) res.send("에러가 발생했습니다."); else { connect.query(sql, (err, result) => { connect.release(); if(err) res.send("에러가 발생했습니다."); else { // 2019-08-29 22:10:11 var saveResult = []; var tmp = {}; for(var v of result) { tmp = {}; tmp.id = v.id; tmp.comment = v.comment; tmp.wdate = util.dtChg(new Date(v.wdate)); saveResult.push(tmp); } var sendData = {board: saveResult}; res.render("board_list", sendData); } }); } }); }); */ app.get("/board_list", (req, res) => { const sql = "SELECT * FROM sample ORDER BY id DESC"; const success = (data) => { var saveResult = []; var tmp = {}; for(var v of data[0]) { tmp = {}; tmp.id = v.id; tmp.comment = v.comment; tmp.wdate = util.dtChg(new Date(v.wdate)); saveResult.push(tmp); } var sendData = {board: saveResult}; res.render("board_list", sendData); } db.sqlExec(sql).then(success).catch(db.sqlError); });
C#
UTF-8
3,215
2.765625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; namespace TKBase { public sealed class ObjectPools { private static Dictionary<Type, ArrayList> m_dicObject = new Dictionary<Type, ArrayList>(); /** * 回收对象 * @param obj 被回收的对象 */ public static void CheckIn(object obj) { Type t = obj.GetType(); if (obj is GameObject) { (obj as GameObject).SetActive(false); } if(obj is IPoolableObect) { (obj as IPoolableObect).UnInitialize(); } if (false == m_dicObject.ContainsKey(t)) { m_dicObject.Add(t, new ArrayList()); } m_dicObject[t].Add(obj); } public static T CheckOut<T>(params object[] args) where T : IPoolableObect { Type t = typeof(T); IPoolableObect obj; if (false == m_dicObject.ContainsKey(t) || 0 == m_dicObject[t].Count) { try { obj = Activator.CreateInstance(t) as IPoolableObect; obj.Initialize(args); return (T)obj; } catch (Exception ee) { //分配内存失败! throw ee; } } obj = m_dicObject[t][0] as IPoolableObect; m_dicObject[t].RemoveAt(0); obj.Initialize(args); return (T)obj; } /** * 从对象池取一个对象 * @param t 取出对象的类型 * @param args 初始化对象参数 */ public static IPoolableObect CheckOut(Type t, params object[] args) { IPoolableObect obj; if (false == m_dicObject.ContainsKey(t) || 0 == m_dicObject[t].Count) { try { obj = Activator.CreateInstance(t) as IPoolableObect; obj.Initialize(args); return obj; } catch (Exception ee) { //分配内存失败! throw ee; } } obj = m_dicObject[t][0] as IPoolableObect; m_dicObject[t].RemoveAt(0); obj.Initialize(args); return obj; } public static GameObject CheckOut(GameObject output) { Type t = output.GetType(); if (false == m_dicObject.ContainsKey(t) || 0 == m_dicObject[t].Count) { try { output = GameObject.Instantiate(output) as GameObject; return output; } catch (Exception ee) {//分配内存失败! throw ee; } } output = m_dicObject[t][0] as GameObject; m_dicObject[t].RemoveAt(0); return output; } } }
C++
UTF-8
4,316
3.796875
4
[]
no_license
#pragma once #include <string> #include <stdexcept> #include "Baby.h" using namespace std; class MedicalRecord { public: // default constructor MedicalRecord() { record = new Baby[SIZE]; // array created on the heap numOfEntries = 0; // number of babies on record set to 0 } // destructor ~MedicalRecord() { delete[] record; } // Load information from a text file with the given filename. void buildMedicalRecordfromDatafile(string filename) { ifstream myfile(filename); if (myfile.is_open()) { cout << "Successfully opened file " << filename << endl; string name; int weight; while (myfile >> name >> weight) { // cout << name << " " << weight << endl; Baby b(name, weight); addEntry(b); } myfile.close(); } else throw invalid_argument("Could not open file " + filename); } // return the most frequently appearing name in the text file string mostPopularName() { // done in 2 steps //STEP 1: CREATE ARRAY OF UNIQUE NAMES FROM FILE string nameArray[1000]; //initialize array to blank names for (int i = 0; i < 1000; i++) { nameArray[i] = ""; } int uniqueNameTotal = 0; // holds the number of unique names in the record for (int i = 0; i < numOfEntries; i++) // loops through record[] { for (int j = 0; j < 1000; j++) // loop used to compare record[i] to nameArray[j] { // loop through the record[i] and compare to nameArray[j] // if the name is already found in nameArray[j] then break out of loop if (record[i].name == nameArray[j]) { break; } // loop populates nameArray[j] with first name and subsequent empty array slots else if (nameArray[j] == "") { // if name in record[i] is not in nameArray[j] then add it to nameArray[j] // then increment total number of unique names nameArray[j] = record[i].getName(); uniqueNameTotal++; break; } } } //STEP 2: loop through nameArray[] and find name with highest occurance using numberOfBabiesWithName(); int popularCount = 0; // holds the number of babies with name being tested int indexOfPopularName; // holds the index in nameArray[] of the most popular name for (int i = 0; i < uniqueNameTotal; i++) // loops through nameArray[] { int tempCount = numberOfBabiesWithName(nameArray[i]); //if the number of babies with name of the current array index is higher than the popularCount then: // 1. update the popularCount to the number of babies with the name // 2. update the index of the most popular name to this index if (tempCount > popularCount) { popularCount = tempCount; indexOfPopularName = i; } } // return the name located in the most popular index return nameArray[indexOfPopularName]; } // return the number of baby records loaded from the text file int numberOfBirths() { return numOfEntries; //declared as private member variable below, updated in addEntry() } // return the number of babies who had birth weight < 2500 grams int numberOfBabiesWithLowBirthWeight() { int lowCount = 0; // count of babies with low weight for (int i=0; i < numOfEntries; i++) { //if weight is under 2500 increment the count if (record[i].getWeight() < 2500) { lowCount++; } } // return final count return lowCount; } // return the number of babies who have the name contained in string s int numberOfBabiesWithName(string s) { int numWithS = 0; // holds the number of babies with specified name for (int i = 0; i < SIZE; i++) { // if baby has specified name increment the count if (record[i].name == s) { numWithS++; } } // return final count return numWithS; } private: // update the data structure with information contained in Baby object void addEntry(Baby b) { record[numOfEntries].name = b.name; record[numOfEntries].weight = b.weight; numOfEntries++; // keeps track of the number of births } Baby newEntry; //used in addEntry(); Baby * record; //ptr in array of the entire fcn const int SIZE = 1000000; // used for arrazy size int numOfEntries; // for birth count };
TypeScript
UTF-8
1,325
2.875
3
[ "MIT" ]
permissive
import { Channel, GuildChannel, TextBasedChannel } from '../../structures/channels'; import { Snowflake } from '../../types'; import { BaseDeleteController, BaseFetchController } from '../base'; /** * Provides an interface for the bot's channels cache. * The channels are mapped by their IDs */ export declare class BotChannelsController extends BaseFetchController<Channel> implements BaseDeleteController<Channel> { /** * Deletes a channel * @param {Snowflake} id The ID of the channel you wish to delete * @returns {Promise<void | Channel>} */ delete(id: Snowflake): Promise<void | Channel>; /** * Fetches a channel * @param {Snowflake} id The ID of the channel you wish to fetch * @returns {Promise<Channel>} */ fetch(id: Snowflake): Promise<Channel>; /** @inheritDoc */ get(id: Snowflake): Promise<Channel>; /** * Gets or fetches a text channel by its ID * @param {Snowflake} id The ID of the text channel * @returns {Promise<TextBasedChannel>} */ getText(id: Snowflake): Promise<TextBasedChannel>; /** * Gets or fetches a guild channel by its ID * @param {Snowflake} id The ID of the text channel * @returns {Promise<TextBasedChannel>} */ getGuildChannel(id: Snowflake): Promise<GuildChannel>; }
JavaScript
UTF-8
308
2.765625
3
[]
no_license
'use strict'; function createUpdatedCollection(collectionA, objectB) { for(let i = 0;i<collectionA.length;i++){ if(objectB.value.indexOf(collectionA[i].key)!=-1){ collectionA[i].count -= parseInt(collectionA[i].count/3+""); //alert(collectionA[i].count); } } return collectionA; }
Java
UTF-8
216
1.664063
2
[]
no_license
package com.iisi.api.office; import java.util.List; import javax.faces.model.SelectItem; import com.iisi.api.model.Office; public interface OfficeService { public List<SelectItem> getOfficeItems(); }
Python
UTF-8
7,821
2.84375
3
[]
no_license
import pygame pygame.init() win = pygame.display.set_mode((500,480)) pygame.display.set_caption("First Game") walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'), pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'), pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')] walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'), pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'), pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')] bg = pygame.image.load('bg.jpg') char = pygame.image.load('standing.png') clock = pygame.time.Clock() bullsound=pygame.mixer.Sound('gun.wav') hitsound=pygame.mixer.Sound('hit.wav') music=pygame.mixer.music.load('music.mp3') pygame.mixer.music.play(-1) score=0 class player(object): def __init__(self,x,y,width,height): self.x = x self.y = y self.width = width self.height = height self.vel = 5 self.isJump = False self.left = False self.right = False self.walkCount = 0 self.jumpCount = 10 self.standing=True self.hitbox=(self.x+17,self.y+11,29,52) def draw(self, win): if self.walkCount + 1 >= 27: self.walkCount = 0 if not(self.standing): if self.left: win.blit(walkLeft[self.walkCount//3], (self.x,self.y)) self.walkCount += 1 elif self.right: win.blit(walkRight[self.walkCount//3], (self.x,self.y)) self.walkCount +=1 else: if self.right: win.blit(walkRight[0], (self.x,self.y)) else: win.blit(walkLeft[0], (self.x,self.y)) self.hitbox=(self.x+17,self.y+11,29,52) #pygame.draw.rect(win,(255,0,0),self.hitbox,2) def collide(self): self.isJump=False self.jumpCount=10 self.x=60 self.y=410 self.walkCount=0 font1=pygame.font.SysFont('comicsans',100) text=font1.render('-5',1,(255,0,0)) win.blit(text,(250- (text.get_width()/2),200)) pygame.display.update() i=0 while i<10: pygame.time.delay(10) i+=1 for e in pygame.event.get(): if e.type==pygame.QUIT: i=301 pygame.quit() class projectile(object): def __init__(self,x,y,radius,color,facing): self.x=x self.y=y self.radius=radius self.color=color self.facing=facing self.vel=8*facing def draw(self,win): pygame.draw.circle(win,self.color,(self.x,self.y),self.radius) class enemy(object): walkRight = [pygame.image.load('R1E.png'), pygame.image.load('R2E.png'), pygame.image.load('R3E.png'), pygame.image.load('R4E.png'), pygame.image.load('R5E.png'), pygame.image.load('R6E.png'), pygame.image.load('R7E.png'), pygame.image.load('R8E.png'), pygame.image.load('R9E.png'), pygame.image.load('R10E.png'), pygame.image.load('R11E.png')] walkLeft = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'), pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'), pygame.image.load('L7E.png'), pygame.image.load('L8E.png'), pygame.image.load('L9E.png'), pygame.image.load('L10E.png'), pygame.image.load('L11E.png')] def __init__(self,x,y,width,height,end): self.x=x self.y=y self.width=width self.height=height self.end=end self.path=[self.x,self.end] self.walkCount=0 self.vel=3 self.hitbox=(self.x+17,self.y+2,31,57) self.health=10 self.visible=True def draw(self,win): self.move() if self.visible: if self.walkCount+1>=33: self.walkCount=0 if self.vel>0: win.blit(self.walkRight[self.walkCount//3],(self.x,self.y)) self.walkCount+=1 else: win.blit(self.walkLeft[self.walkCount//3],(self.x,self.y)) self. walkCount+=1 pygame.draw.rect(win,(255,0,0),(self.hitbox[0],self.hitbox[1]-20,50,10)) pygame.draw.rect(win,(0,128,0),(self.hitbox[0],self.hitbox[1]-20,50-(5*(10-self.health)),10)) self.hitbox=(self.x+17,self.y+2,31,57) #pygame.draw.rect(win,(255,0,0),self.hitbox,2) def move(self): if self.vel>0: if self.x+self.vel<self.path[1]: self.x+=self.vel else: self.vel=self.vel* (-1) self.walkCount=0 else: if self.x-self.vel>self.path[0]: self.x+=self.vel else: self.vel=self.vel*(-1) self.walkCount=0 def hit(self): if self.health>0: self.health-=1 else: self.visible=False def redrawGameWindow(): win.blit(bg, (0,0)) text=font.render('Score: '+str(score),1,(0,0,0)) win.blit(text,(380,10)) man.draw(win) goblin.draw(win) for b in bullets: b.draw(win) pygame.display.update() #mainloop font=pygame.font.SysFont('comicsans',30,True) man = player(200, 410, 64,64) goblin=enemy(100,410,64,64,450) shoot=0 bullets=[] run = True while run: clock.tick(30) if goblin.visible==True: if man.hitbox[1]<goblin.hitbox[1]+goblin.hitbox[3] and man.hitbox[1]+man.hitbox[3]>goblin.hitbox[1]: if man.hitbox[0]+man.hitbox[2]>goblin.hitbox[0] and man.hitbox[0]<goblin.hitbox[0] +goblin.hitbox[2]: man.collide() score-=5 if shoot>0: shoot+=1 if shoot>3: shoot=0 for event in pygame.event.get(): if event.type == pygame.QUIT: run = False for b in bullets: if goblin.visible==True: if b.y-b.radius<goblin.hitbox[1]+goblin.hitbox[3] and b.y+b.radius>goblin.hitbox[1]: if b.x+b.radius>goblin.hitbox[0] and b.x-b.radius<goblin.hitbox[0] +goblin.hitbox[2]: hitsound.play() goblin.hit() score+=1 bullets.pop(bullets.index(b)) if b.x<500 and b.x>0: b.x+=b.vel else: bullets.pop(bullets.index(b)) keys = pygame.key.get_pressed() if keys[pygame.K_SPACE] and shoot==0: bullsound.play() if man.left: facing=-1 else: facing=1 if len(bullets)<5: bullets.append(projectile(round(man.x+man.width//2),round(man.y+man.height//2),6,(0,0,0),facing)) shoot=1 if keys[pygame.K_LEFT] and man.x > man.vel: man.x -= man.vel man.left = True man.right = False man.standing=False elif keys[pygame.K_RIGHT] and man.x < 500 - man.width - man.vel: man.x += man.vel man.right = True man.left = False man.standing=False else: man.standing=True man.walkCount = 0 if not(man.isJump): if keys[pygame.K_UP]: man.isJump = True man.right = False man.left = False man.walkCount = 0 else: if man.jumpCount >= -10: neg = 1 if man.jumpCount < 0: neg = -1 man.y -= ((man.jumpCount ** 2) //2) * neg man.jumpCount -= 1 else: man.isJump = False man.jumpCount = 10 redrawGameWindow() pygame.quit()
SQL
UTF-8
13,554
3.3125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.9.5deb2 -- https://www.phpmyadmin.net/ -- -- Hôte : localhost:3306 -- Généré le : mar. 30 mars 2021 à 15:15 -- Version du serveur : 8.0.23-0ubuntu0.20.04.1 -- Version de PHP : 7.4.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `evedb` -- -- -------------------------------------------------------- -- -- Structure de la table `activity` -- CREATE TABLE `activity` ( `id` int NOT NULL, `likes` int NOT NULL, `title_activity` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `price_activity` double NOT NULL, `adress_activity` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `category_id` int DEFAULT NULL, `description_activity` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `activity` -- INSERT INTO `activity` (`id`, `likes`, `title_activity`, `price_activity`, `adress_activity`, `category_id`, `description_activity`) VALUES (2, 0, 'az', 120, 'az', 1, 'aaz'), (4, 0, 'az', 120, 'az', 1, 'aaz'), (5, 0, 'az', 120, 'az', 1, 'aaz'); -- -------------------------------------------------------- -- -- Structure de la table `category` -- CREATE TABLE `category` ( `id` int NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `description` varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `category` -- INSERT INTO `category` (`id`, `name`, `description`) VALUES (1, 'Vélo', 'AAh'), (2, 'Camping', 'aa'); -- -------------------------------------------------------- -- -- Structure de la table `categoryactivity` -- CREATE TABLE `categoryactivity` ( `id` int NOT NULL, `name_category_activity` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `categoryactivity` -- INSERT INTO `categoryactivity` (`id`, `name_category_activity`) VALUES (1, 'azaff'); -- -------------------------------------------------------- -- -- Structure de la table `event` -- CREATE TABLE `event` ( `id` int NOT NULL, `category_id` int NOT NULL, `titre` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `description` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL, `nb_persons` int NOT NULL, `price_event` double NOT NULL, `nb_views` int DEFAULT NULL, `start_date` date DEFAULT NULL, `end_date` date DEFAULT NULL, `place_disponible` int NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `event` -- INSERT INTO `event` (`id`, `category_id`, `titre`, `description`, `nb_persons`, `price_event`, `nb_views`, `start_date`, `end_date`, `place_disponible`) VALUES (2, 1, 'Event', 'aaaaaaaaaaaaaaaaaa', 2555, 20, 19, '2021-03-27', '2021-03-31', 2535), (3, 1, 'Event', 'orem Iprem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled i', 255, 10, 67, '2021-03-31', '2021-03-30', 243), (4, 2, 'Eventqq', 'aaaaaaaaaaaaaaaaaa', 144, 30, 24, '2021-04-02', '2021-03-19', 91), (5, 2, '555', 'aaaaaaaaaaaaaaaaaa', 55, 20, NULL, '2021-03-27', '2021-03-18', 55), (6, 2, 'Event', 'aaaaaaaaaaaaaaaaaa', 55, 20, NULL, '2021-03-26', '2021-03-26', 55), (7, 2, 'aaa', 'aaaaaaaaaaaaaaaaaaaaaa', 20, 20, NULL, '2021-03-18', '2021-03-31', 20), (8, 2, 'aaa', 'aaaaaaaaaaaaaaaaaaaaaa', 20, 20, 1, '2021-03-18', '2021-03-31', 20); -- -------------------------------------------------------- -- -- Structure de la table `image` -- CREATE TABLE `image` ( `id` int NOT NULL, `event_id` int DEFAULT NULL, `source` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `image` -- INSERT INTO `image` (`id`, `event_id`, `source`) VALUES (1, 2, 'eve-60619cab70101Mar-2021-png'), (2, 3, 'eve-60619caba51c8Mar-2021-png'), (3, 3, 'eve-60619cabbd9d0Mar-2021-png'), (4, 4, 'eve-6061a52f8b19cMar-2021-png'), (5, 5, 'eve-6062d7926916cMar-2021-png'), (6, 6, 'eve-6062d830d1bbcMar-2021-png'), (7, 7, 'eve-6062dbf081284Mar-2021-png'), (8, 8, 'eve-6062dc0908404Mar-2021-png'); -- -------------------------------------------------------- -- -- Structure de la table `product` -- CREATE TABLE `product` ( `id` int NOT NULL, `name_product` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `description_product` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `category_product` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `price_product` double NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `product` -- INSERT INTO `product` (`id`, `name_product`, `description_product`, `category_product`, `price_product`) VALUES (1, 'test', 'aa', 'aa', 250); -- -------------------------------------------------------- -- -- Structure de la table `promotion` -- CREATE TABLE `promotion` ( `id` int NOT NULL, `event_id` int DEFAULT NULL, `product_id` int DEFAULT NULL, `descriptionpromotion` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `start_date_promotion` date DEFAULT NULL, `end_date_promotion` date DEFAULT NULL, `pourcentage` double NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `promotion` -- INSERT INTO `promotion` (`id`, `event_id`, `product_id`, `descriptionpromotion`, `start_date_promotion`, `end_date_promotion`, `pourcentage`) VALUES (1, 4, 1, 'aa', '2021-03-28', '2021-04-01', 25); -- -------------------------------------------------------- -- -- Structure de la table `publicity` -- CREATE TABLE `publicity` ( `id` int NOT NULL, `start_date_pub` date DEFAULT NULL, `end_date_pub` date DEFAULT NULL, `description_pub` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `picture_pub` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `title_pub` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `position` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `link` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `publicity` -- INSERT INTO `publicity` (`id`, `start_date_pub`, `end_date_pub`, `description_pub`, `picture_pub`, `title_pub`, `position`, `link`) VALUES (1, '2021-03-24', '2021-03-26', 'aaaaa', 'pub-605af7176ae20Mar-2021-png', 'ma', 'BOTTOM', 'http://m'), (2, '2021-03-25', '2021-03-28', 'zz', 'pub-605af9be3411dMar-2021-png', 'm', 'TOP', 'http://m'); -- -------------------------------------------------------- -- -- Structure de la table `reservation` -- CREATE TABLE `reservation` ( `id` int NOT NULL, `event_id` int DEFAULT NULL, `user_id` int DEFAULT NULL, `nb_participants` int NOT NULL, `status` tinyint(1) DEFAULT NULL, `reservation_date` date DEFAULT NULL, `resteapayer` int DEFAULT NULL, `reduction` double DEFAULT NULL, `token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `paid` tinyint(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `reservation` -- INSERT INTO `reservation` (`id`, `event_id`, `user_id`, `nb_participants`, `status`, `reservation_date`, `resteapayer`, `reduction`, `token`, `paid`) VALUES (11, 4, 1, 2, 1, '2021-03-29', 60, 15, '6061e9e61b112', 0), (12, 4, 1, 10, 1, '2021-03-30', 300, 75, '6062d2d1665ac', 0), (13, 4, 1, 20, 0, '2021-03-30', 600, 150, '6062d3c1dc046', 0), (14, 4, 1, 2, 1, '2021-03-30', 60, 15, '6062d400d8296', 1), (15, 4, 1, 10, 1, '2021-03-30', 300, 75, '6062de30a9d3e', 0); -- -------------------------------------------------------- -- -- Structure de la table `user` -- CREATE TABLE `user` ( `id` int NOT NULL, `first_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `last_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `identity` int NOT NULL, `birthday` date NOT NULL, `picture_user` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `phone` int NOT NULL, `role` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `reset_token` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `user` -- INSERT INTO `user` (`id`, `first_name`, `last_name`, `email`, `password`, `identity`, `birthday`, `picture_user`, `phone`, `role`, `reset_token`) VALUES (1, 'Seif Allah', 'Jallali', 'seifallah.jallali@esprit.tn', '$2y$13$SGxwhGH5PNH8E85Tv6lTs.z2VgPat.gbpG1B/p.VVortvreJeNCk.', 13001074, '2021-03-24', 'user-6052115b24e02Mar-2021-jpeg', 21554529, 'ROLE_ADMIN', NULL), (3, 'hhsh', 'hshh', 'saifallah@pentabell.fr', '$2y$13$XnectThaKrZIltkDmy5AkOlMAei9cUHKM5reSBnvi.W6tcffcTk6u', 85978787, '1994-09-28', 'user-6052111ebac31Mar-2021-jpeg', 87878787, 'ROLE_CLIENT', NULL), (13, '787878', '787878', 'seifallah.jallali@esprit.tn', '$2y$13$cv.CUWkcp74uQ6Une83GCO4TUQS6U.pG9p3x4zhLAoaE1awaWhe62', 13001074, '1994-09-28', 'user-6053296050b76Mar-2021-png', 23185019, 'ROLE_CLIENT', NULL); -- -- Index pour les tables déchargées -- -- -- Index pour la table `activity` -- ALTER TABLE `activity` ADD PRIMARY KEY (`id`), ADD KEY `IDX_AC74095A12469DE2` (`category_id`); -- -- Index pour la table `category` -- ALTER TABLE `category` ADD PRIMARY KEY (`id`); -- -- Index pour la table `categoryactivity` -- ALTER TABLE `categoryactivity` ADD PRIMARY KEY (`id`); -- -- Index pour la table `event` -- ALTER TABLE `event` ADD PRIMARY KEY (`id`), ADD KEY `IDX_3BAE0AA712469DE2` (`category_id`); -- -- Index pour la table `image` -- ALTER TABLE `image` ADD PRIMARY KEY (`id`), ADD KEY `IDX_C53D045F71F7E88B` (`event_id`); -- -- Index pour la table `product` -- ALTER TABLE `product` ADD PRIMARY KEY (`id`); -- -- Index pour la table `promotion` -- ALTER TABLE `promotion` ADD PRIMARY KEY (`id`), ADD KEY `IDX_C11D7DD171F7E88B` (`event_id`), ADD KEY `IDX_C11D7DD14584665A` (`product_id`); -- -- Index pour la table `publicity` -- ALTER TABLE `publicity` ADD PRIMARY KEY (`id`); -- -- Index pour la table `reservation` -- ALTER TABLE `reservation` ADD PRIMARY KEY (`id`), ADD KEY `IDX_42C8495571F7E88B` (`event_id`), ADD KEY `IDX_42C84955A76ED395` (`user_id`); -- -- Index pour la table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT pour les tables déchargées -- -- -- AUTO_INCREMENT pour la table `activity` -- ALTER TABLE `activity` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT pour la table `category` -- ALTER TABLE `category` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT pour la table `categoryactivity` -- ALTER TABLE `categoryactivity` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT pour la table `event` -- ALTER TABLE `event` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT pour la table `image` -- ALTER TABLE `image` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT pour la table `product` -- ALTER TABLE `product` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT pour la table `promotion` -- ALTER TABLE `promotion` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT pour la table `publicity` -- ALTER TABLE `publicity` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT pour la table `reservation` -- ALTER TABLE `reservation` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16; -- -- AUTO_INCREMENT pour la table `user` -- ALTER TABLE `user` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- Contraintes pour les tables déchargées -- -- -- Contraintes pour la table `activity` -- ALTER TABLE `activity` ADD CONSTRAINT `FK_AC74095A12469DE2` FOREIGN KEY (`category_id`) REFERENCES `categoryactivity` (`id`); -- -- Contraintes pour la table `event` -- ALTER TABLE `event` ADD CONSTRAINT `FK_3BAE0AA712469DE2` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`); -- -- Contraintes pour la table `image` -- ALTER TABLE `image` ADD CONSTRAINT `FK_C53D045F71F7E88B` FOREIGN KEY (`event_id`) REFERENCES `event` (`id`); -- -- Contraintes pour la table `promotion` -- ALTER TABLE `promotion` ADD CONSTRAINT `FK_C11D7DD14584665A` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON DELETE SET NULL, ADD CONSTRAINT `FK_C11D7DD171F7E88B` FOREIGN KEY (`event_id`) REFERENCES `event` (`id`) ON DELETE SET NULL; -- -- Contraintes pour la table `reservation` -- ALTER TABLE `reservation` ADD CONSTRAINT `FK_42C8495571F7E88B` FOREIGN KEY (`event_id`) REFERENCES `event` (`id`), ADD CONSTRAINT `FK_42C84955A76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Python
UTF-8
188
3.6875
4
[]
no_license
name = "Jyoti" address = "Bangalore" print("My name is {} and my address is {}".format(name, address)) print("-"*45) print(f"My name is {name} and my address is {address}")
C++
UTF-8
10,948
4.09375
4
[]
no_license
/*********************************************************************** * Program: * Project 13, Sudoku * Brother Macbeth, CS124 * Author: * Heather Mason * Summary: * Load a sudoku board from a file. Display instructions with appropriate * prompts, then go to different functions for each prompt. Display * errors when invalid info is entered. make sure all values are correct. * * Estimated: 4.0 hrs * Actual: 5.0 hrs * Working out the loops for checking the values. ************************************************************************/ #include <iostream> #include <fstream> #include <string> using namespace std; /********************************************************************** * Test if the value will violate the Sudoku Row Rule for the specified * row. Return true if the rule is satisfied. * ********************************************************************/ bool testRow(int board[][9], const int size, const int row, const int value) { for (int col = 0; col < size; col++) { if (board[row][col] == value) { return false; } } return true; } /********************************************************************** * Test if the value will violate the Sudoku Column Rule for the specified * column. Return true if the rule is satisfied. * ********************************************************************/ bool testColumn(int board[][9], const int size, const int col, const int value) { for (int row = 0; row < size; row++) { if (board[row][col] == value) { return false; } } return true; } /********************************************************************** * Test if the value will violate the Sudoku Rule for a 3x3 square * containing the specified row and column. Return true if the rule is * satisfied. * ********************************************************************/ bool testSquare(int board[][9], const int size, const int row, const int col, const int value) { int startRow = 0; int startCol = 0; startRow = (row / 3) * 3; startCol = (col / 3) * 3; for (int r = startRow; r < (startRow + 3); r++) { for (int c = startCol; c < (startCol + 3); c++) { if (board[r][c] == value) { return false; } } } return true; } /********************************************************************** * Test if a value can be put into the Sudoku board at the * specified row and column without violating any of the Sudoku Rules. * Return true if all 3 rules are satisfied. * ********************************************************************/ bool testBoard(int board[][9], const int size, const int row, const int col, const int value) { bool testR = testRow(board, size, row, value); bool testC = testColumn(board, size, col, value); bool testS = testSquare(board, size, row, col, value); if (testR == true && testC == true && testS == true) { return true; } else { return false; } } /********************************************************************** * Prompt the user for a filename and then populate the board array with * the values from the file. If there is an error opening the file then * display an error message and return false. * ********************************************************************/ bool loadGame(int board[][9], const int size) { string fileName; cout << "Where is your board located? "; cin >> fileName; ifstream fin(fileName.c_str()); if (fin.fail()) { cout << "Error" << endl; return false; } for (int row = 0; row < size; row++) { for (int col = 0; col < size; col++) { fin >> board[row][col]; } } fin.close(); return true; } /********************************************************************** * Prompt the user for a filename (using the string class) and then * populate that file with the contents of the board array. If there is * an error opening the file then display an error message. Otherwise, * display “Board written successfully” after saving the file. * ********************************************************************/ bool saveGame(int board[][9], const int size) { string fileName; cout << "What file would you like to write your board to: "; cin >> fileName; ofstream fout(fileName.c_str()); if (fout.fail()) { cout << "Error" << endl; return false; } for (int row = 0; row < size; row++) { for (int col = 0; col < size; col++) { fout << board[row][col] << " "; } fout << endl; } cout << "Board written successfully" << endl; return true; } /********************************************************************** * Display the instructions * ********************************************************************/ void displayInstructions() { cout << "Options:" << endl; cout << " ? Show these instructions" << endl; cout << " D Display the board" << endl; cout << " E Edit one square" << endl; cout << " S Show the possible values for a square" << endl; cout << " Q Save and Quit" << endl << endl; } /********************************************************************** * Display the contents of the Sudoku board array * ********************************************************************/ void displayBoard(int board[][9], const int size) { cout << " A B C D E F G H I" << endl; for (int row = 0; row < size; row++) { if (row % 3 == 0 && row != 0) { cout << " -----+-----+-----" << endl; cout << row + 1 << " "; } else { cout << row + 1 << " "; } for (int col = 0; col < size; col++) { if (col % 3 == 0 && col != 0) { cout << "|"; } else { cout << " "; } if (board[row][col] == 0) { cout << " "; } else { cout << board[row][col]; } } cout << endl; } } /********************************************************************** * Convert a 2 character coordinate * ********************************************************************/ void convertCoordinate(const char colChar, const char rowChar, int &row, int &col) { if (colChar == 'A') { col = 0; } else if (colChar == 'B') { col = 1; } else if (colChar == 'C') { col = 2; } else if (colChar == 'D') { col = 3; } else if (colChar == 'E') { col = 4; } else if (colChar == 'F') { col = 5; } else if (colChar == 'G') { col = 6; } else if (colChar == 'H') { col = 7; } else if (colChar == 'I') { col = 8; } else { cout << "Invalid Column Coordinate"; } if (rowChar == '1') { row = 0; } else if (rowChar == '2') { row = 1; } else if (rowChar == '3') { row = 2; } else if (rowChar == '4') { row = 3; } else if (rowChar == '5') { row = 4; } else if (rowChar == '6') { row = 5; } else if (rowChar == '7') { row = 6; } else if (rowChar == '8') { row = 7; } else if (rowChar == '9') { row = 8; } else { cout << "Invalid Row Coordinate"; } } /********************************************************************** * The user provides a coordinate and value to place there. * ********************************************************************/ void editSquare(int board[][9], const int size) { string coordinate; int row = 0; int col = 0; int value = 0; cout << "What are the coordinates of the square: "; cin >> coordinate; coordinate[0] = toupper(coordinate[0]); convertCoordinate(coordinate[0], coordinate[1], row, col); if (board[row][col] == 0) { cout << "What is the value at '" << coordinate << "': "; cin >> value; if (testBoard(board, size, row, col, value) == true) { board[row][col] = value; } else { cout << "ERROR: Value '" << value << "' in square '" << coordinate << "' is invalid" << endl; } } else { cout << "ERROR: Square '" << coordinate << "' is filled" << endl; } } /********************************************************************** * The user provides a coordinate and the possible values are displayed * ********************************************************************/ void showValues(int board[][9], const int size) { bool first = true; string coordinate; int row = 0; int col = 0; cout << "What are the coordinates of the square: "; cin >> coordinate; coordinate[0] = toupper(coordinate[0]); convertCoordinate(coordinate[0], coordinate[1], row, col); cout << "The possible values for '" << coordinate << "' are: "; for (int num = 1; num <= 9; num++) { if (testBoard(board, size, row, col, num) == true) { if (first == false) { cout << ", " << num; } else { cout << num; first = false; } } } cout << endl; } /********************************************************************** * Display the prompt "> " and then return the selection made by the * user. * ********************************************************************/ char prompt() { char selection; cout << "> "; cin >> selection; return selection; } /********************************************************************** * Driver ***********************************************************************/ int main() { int board[9][9]; int size = 9; char selection; loadGame(board, size); displayInstructions(); displayBoard(board, size); cout << endl; do { selection = prompt(); selection = toupper(selection); if (selection == '?') { displayInstructions(); cout << endl; } else if (selection == 'D') { displayBoard(board, size); cout << endl; } else if (selection == 'E') { editSquare(board, size); cout << endl; } else if (selection == 'S') { showValues(board, size); cout << endl; } else if (selection == 'Q') { saveGame(board, size); return 0; } else { cout << "Invalid entry" << endl; } } while (selection != '?' || selection != 'D' || selection != 'E' || selection != 'S' || selection != 'Q'); return 0; }
Python
UTF-8
844
2.578125
3
[]
no_license
import matplotlib import textacy import sys #from nltk.stem.lancaster import LancasterStemmer #from nltk.stem import WordNetLemmatizer st = LancasterStemmer() wnl = WordNetLemmatizer() doc = [] for i in range(1,6): file = open('./rapport{}.txt'.format(i), 'r') with open('./articles{}.txt'.format(i), 'r') as article: doc.append(article.read()) doc[i-1] = doc[i-1].replace('\n', "").replace('.', "").lower().split(" ") article.close() vectorizer = textacy.Vectorizer(tf_type='linear', apply_idf=True, idf_type='smooth', min_df=3, max_df=0.9) doc_term_matrix = vectorizer.fit_transform(doc) model = textacy.tm.TopicModel('lda', n_topics=10) model.fit(doc_term_matrix) model.termite_plot(doc_term_matrix, vectorizer.id_to_term, topics=-1, n_terms=20, sort_terms_by='seriation')
Python
UTF-8
163
3.046875
3
[]
no_license
def primer5(): fBrojevi = open("brojevi.txt", "r") lines = fBrojevi.readlines() sum = 0 for line in lines: sum += eval(line) print(sum/len(lines)) primer5()
Java
UTF-8
3,056
2.265625
2
[ "Apache-2.0" ]
permissive
package com.morgan.server.util.soy; import org.junit.Before; import org.junit.Test; import com.google.common.base.Optional; import com.google.common.truth.Truth; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.safehtml.shared.UriUtils; import com.google.template.soy.data.SoyData; import com.google.template.soy.data.SoyMapData; import com.google.template.soy.data.UnsafeSanitizedContentOrdainer; import com.google.template.soy.data.SanitizedContent.ContentKind; /** * Tests for the {@link DefaultSoyDataConverter} class. * * @author mark@mark-morgan.net (Mark Morgan) */ public class DefaultSoyDataConverterTest { private static final SoyData CONVERTABLE_DATA = SoyData.createFromExistingData(42); private static final SoyConvertable CONVERTABLE = new SoyConvertable() { @Override public SoyData toSoyData() { return CONVERTABLE_DATA; } }; private DefaultSoyDataConverter converter; @Before public void createTestInstances() { converter = new DefaultSoyDataConverter(); } @Test public void addToSoyMapData_optional_absent() { SoyMapData mapData = new SoyMapData(); converter.addToSoyMapData(mapData, "foo", Optional.absent()); Truth.assertThat(mapData.asMap()).isEqualTo(new SoyMapData().asMap()); } @Test public void addToSoyMapData_optional_present() { SoyMapData mapData = new SoyMapData(); converter.addToSoyMapData(mapData, "foo", Optional.of("bar")); Truth.assertThat(mapData.asMap()) .isEqualTo(new SoyMapData("foo", "bar").asMap()); } @Test public void addToSoyMapData_null() { SoyMapData mapData = new SoyMapData(); converter.addToSoyMapData(mapData, "foo", null); Truth.assertThat(mapData.asMap()) .isEqualTo(new SoyMapData("foo", null).asMap()); } @Test public void addToSoyMapData_soyConvertable() { SoyMapData mapData = new SoyMapData(); converter.addToSoyMapData(mapData, "foo", CONVERTABLE); Truth.assertThat(mapData.asMap()) .isEqualTo(new SoyMapData("foo", CONVERTABLE_DATA).asMap()); } @Test public void addToSoyMapData_basicType() { SoyMapData mapData = new SoyMapData(); converter.addToSoyMapData(mapData, "foo", 69); Truth.assertThat(mapData.asMap()) .isEqualTo(new SoyMapData("foo", 69).asMap()); } @Test public void addToSoymapData_safeHtml() { SoyMapData mapData = new SoyMapData(); converter.addToSoyMapData(mapData, "foo", SafeHtmlUtils.fromString("safe string")); Truth.assertThat(mapData.asMap()) .isEqualTo(new SoyMapData("foo", UnsafeSanitizedContentOrdainer.ordainAsSafe("safe string", ContentKind.HTML)).asMap()); } @Test public void addToSoymapData_safeUri() { SoyMapData mapData = new SoyMapData(); converter.addToSoyMapData(mapData, "foo", UriUtils.fromString("safestring")); Truth.assertThat(mapData.asMap()) .isEqualTo(new SoyMapData("foo", UnsafeSanitizedContentOrdainer.ordainAsSafe("safestring", ContentKind.URI)).asMap()); } }
Go
UTF-8
611
3.234375
3
[ "MIT" ]
permissive
package utils import ( "context" "reflect" ) type ListLoadFunc func(ctx context.Context, cursor string) (interface{}, string, error) // LoadList iterates over results of a given load function and appends them to a given list. func LoadList(ctx context.Context, list interface{}, loadFunc ListLoadFunc) (err error) { valuePtr := reflect.ValueOf(list) var items interface{} var cursor string for { if items, cursor, err = loadFunc(ctx, cursor); err != nil { return } valuePtr.Elem().Set(reflect.AppendSlice(valuePtr.Elem(), reflect.ValueOf(items))) if cursor == "" { break } } return }
Java
UTF-8
1,817
3.015625
3
[]
no_license
package codility.MinAvgTwoSlice; public class Main { public static void print(int[] arr) { StringBuilder builder = new StringBuilder(); builder.append("["); for (int i = 0; i < arr.length; i++) { builder.append(arr[i]); if (i != arr.length - 1) { builder.append(", "); } } builder.append("]"); System.out.println(builder.toString()); } static public int solution(int[] A) { int sum[] = new int[A.length]; for (int i = 0; i < A.length; i++) { if (i == 0) { sum[i] = A[0]; continue; } sum[i] = sum[i - 1] + A[i]; } int pos = 0; double avg = 0.0; for (int i = 0; i < A.length - 1; i++) { print(sum); for (int j = i + 1; j < A.length; j++) { double val = (double) sum[j] / (j - i + 1); if (j == 1) { avg = val; pos = 0; } else { if (val < avg) { avg = val; pos = i; } } sum[j] -= sum[i]; // System.out.println(val + ", " + avg + ", " + pos); } // System.out.println(""); // System.out.println(avg + ", " + pos); // System.out.println("---------------------------------------------------"); // System.out.println("---------------------------------------------------"); } return pos; } public static void main(String[] args) { // int[] A = {10000, 10000,-10000,-10000}; // int[] A = {1,2,-100}; // int[] A = {4,2,2,5,1,8}; // int[] A = {4,2,2,5,1,5,8}; // int[] A = {8,1,5,2,2,4}; // int[] A = {4,-2,-2,5,1,8}; // int[] A = {5,4,2,1,0,-12}; int[] A = {-3,-5,-8,-4,-10}; // int[] A = new int[100000]; // for (int i = 0; i < 100000; i++) { // A[i] = -10000; // } System.out.println(solution(A)); } }
Java
UTF-8
7,175
1.890625
2
[ "MIT" ]
permissive
package com.mediamonks.googleflip.pages.game_flow.multiplayer; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.mediamonks.googleflip.GoogleFlipGameApplication; import com.mediamonks.googleflip.R; import com.mediamonks.googleflip.data.constants.ActivityRequestCode; import com.mediamonks.googleflip.data.constants.Fragments; import com.mediamonks.googleflip.data.constants.IntentKeys; import com.mediamonks.googleflip.data.constants.MultiplayerMode; import com.mediamonks.googleflip.data.constants.PrefKeys; import com.mediamonks.googleflip.data.vo.ClientVO; import com.mediamonks.googleflip.pages.game.management.GameClient; import com.mediamonks.googleflip.pages.game.management.GameClientListener; import com.mediamonks.googleflip.pages.game.management.GameClientListenerAdapter; import com.mediamonks.googleflip.pages.game_flow.multiplayer.fragments.gameover.GameOverFragment; import com.mediamonks.googleflip.pages.game_flow.multiplayer.fragments.lobby.ClientLobbyFragment; import com.mediamonks.googleflip.pages.game_flow.multiplayer.fragments.lobby.ServerLobbyFragment; import com.mediamonks.googleflip.pages.game_flow.multiplayer.fragments.scoreboard.ScoreboardFragment; import com.mediamonks.googleflip.pages.home.HomeActivity; import com.mediamonks.googleflip.ui.BaseFragment; import com.mediamonks.googleflip.ui.RegisteredFragmentActivity; import com.mediamonks.googleflip.util.Navigator; import com.pixplicity.easyprefs.library.Prefs; import org.andengine.util.ActivityUtils; import java.util.List; import butterknife.ButterKnife; import temple.multiplayer.net.bluetooth.service.BluetoothClientService; import temple.multiplayer.net.common.device.DeviceChangeListener; import temple.multiplayer.net.common.device.DeviceChangeListenerAdapter; /** * Activity for multiplayer game flow */ public class MultiPlayerGameFlowActivity extends RegisteredFragmentActivity implements Navigator { private static final String TAG = MultiPlayerGameFlowActivity.class.getSimpleName(); private BluetoothClientService _clientService; private DeviceChangeListener _clientDeviceChangedListener; private MultiplayerMode _multiplayerMode; private GameClient _gameClient; private GameClientListener _gameClientListener; private String _currentFragmentName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_frame_container); ButterKnife.bind(this); ActivityUtils.keepScreenOn(this); _gameClient = GoogleFlipGameApplication.getGameClient(); _multiplayerMode = MultiplayerMode.values()[Prefs.getInt(PrefKeys.MULTIPLAYER_MODE, 0)]; if (_multiplayerMode.equals(MultiplayerMode.CLIENT)) { _clientService = GoogleFlipGameApplication.getBluetoothClientService(); _clientDeviceChangedListener = new DeviceChangeListenerAdapter() { @Override public void onDeviceRemoved(String deviceName, String address) { handleConnectionLost(); } }; } _gameClientListener = new GameClientListenerAdapter() { @Override public void onClientsChanged(List<ClientVO> clients) { checkConnectionLost(); } }; String fragment; Bundle extras = getIntent().getExtras(); if (extras != null) { fragment = extras.getString(IntentKeys.FRAGMENT); } else { fragment = Fragments.GAME_FLOW_SCOREBOARD; } navigateTo(fragment); } private void handleConnectionLost() { Log.d(TAG, "handleConnectionLost: "); Toast.makeText(MultiPlayerGameFlowActivity.this, R.string.connection_lost, Toast.LENGTH_SHORT).show(); GoogleFlipGameApplication.stopGame(); startActivity(new Intent(MultiPlayerGameFlowActivity.this, HomeActivity.class)); } public boolean navigateTo(String name) { BaseFragment newFragment = null; switch (name) { case Fragments.GAME_FLOW_LOBBY: newFragment = createLobby(); break; case Fragments.GAME_FLOW_SCOREBOARD: newFragment = ScoreboardFragment.newInstance(); break; case Fragments.GAME_FLOW_GAME_OVER: newFragment = GameOverFragment.newInstance(); break; } if (newFragment != null) { _currentFragmentName = name; newFragment.setNavigator(this); getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, newFragment).commit(); } return newFragment != null; } private BaseFragment createLobby() { switch (MultiplayerMode.values()[Prefs.getInt(PrefKeys.MULTIPLAYER_MODE, 0)]) { case CLIENT: return ClientLobbyFragment.newInstance(); case SERVER: return ServerLobbyFragment.newInstance(); } return null; } @Override protected void onStart() { super.onStart(); if (_multiplayerMode.equals(MultiplayerMode.CLIENT)) { _clientService.getHandler().addDeviceChangeListener(_clientDeviceChangedListener); } _gameClient.addGameClientListener(_gameClientListener); checkConnectionLost(); } private void checkConnectionLost() { // don't check in the lobby, it has its own logic if (_currentFragmentName.equals(Fragments.GAME_FLOW_LOBBY)) { return; } // we've lost connection if the game client isn't connected, or there are 1 or less clients connected List<ClientVO> clients = _gameClient.getConnectedClients(); int clientCount = clients == null ? 0 : clients.size(); if (!_gameClient.isConnected() || (clientCount <= 1)) { handleConnectionLost(); } } @Override protected void onStop() { super.onStop(); if (_multiplayerMode.equals(MultiplayerMode.CLIENT)) { _clientService.getHandler().removeDeviceChangeListener(_clientDeviceChangedListener); } _gameClient.removeGameClientListener(_gameClientListener); } @Override public void onBackPressed() { GoogleFlipGameApplication.stopGame(); Intent intent = new Intent(MultiPlayerGameFlowActivity.this, HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); overridePendingTransition(R.anim.slide_down_in, R.anim.slide_down_out); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ActivityRequestCode.REQUEST_ENABLE_SCAN) { if (resultCode == Activity.RESULT_CANCELED) { GoogleFlipGameApplication.stopGame(); finish(); } } } }
JavaScript
UTF-8
1,200
2.546875
3
[]
no_license
import axios from "axios"; class EventService { constructor() { this.api = axios.create({ baseURL: `${process.env.REACT_APP_API_URL}/api/events`, withCredentials: true, }); } createEvent = (artistId, userId, changes) => { const { title, description, date, participants, location, picture, } = changes; const pr = this.api .post(`${artistId}/create`, { creator: userId, title, description, date, participants, location, picture, }) .then((response) => response.data); return pr; }; // getEvent by Artist ID getEvent = (artistId) => { const pr = this.api.get(`/${artistId}`).then((response) => response.data); return pr; }; //getEvent by Event ID getEventById = (eventId) => { const pr = this.api .get(`/one-event/${eventId}`) .then((response) => response); return pr; }; updateEvent = (id, changes) => { const pr = this.api .put(`/update/${id}`, changes) .then((response) => response); return pr; }; } const eventService = new EventService(); export default eventService;
Java
UTF-8
209
1.601563
2
[]
no_license
package org.alljson.internal; import java.util.List; public interface HandledType<T> { List<HandledType<?>> getParameters(); Class<T> toClass(); boolean isAssignableFrom(HandledType<?> other); }
Markdown
UTF-8
978
2.5625
3
[ "MIT" ]
permissive
# GPU-GEMS-3D-Fluid-Simulation This project is based on the GPU Gems 3D fluid simulation article. This article presents a method for calculating and rendering 3D fluid simulations. The method used for rendering was designed to best integrate the fluid simulation into the scene and have it interact with other scene components. I have gone with a simpler renderer however by using a ray tracer that is attached to a cube and there is no interaction with other scene components. This project was originally written when Unity 4 was current and at that time render textures were not available in the free version. I decided to use compute buffers instead to make it more accessible. The only down side to using compute buffers instead of render textures is that there is no support for filtering. I added the code to the shaders to manually do the bi-linear filtering but its probably not as optimal as using a render texture. ![3D Fluid Simulation](./Media/FluidSim3D.jpg)
Java
UTF-8
1,093
1.671875
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc import android.widget.SeekBar; public final class gal implements gak { public boolean a; private android.widget.SeekBar.OnSeekBarChangeListener b; public gal(android.widget.SeekBar.OnSeekBarChangeListener onseekbarchangelistener) { b = onseekbarchangelistener; } public final void a(SeekBar seekbar) { if (b instanceof gak) { ((gak)b).a(seekbar); } } public final void onProgressChanged(SeekBar seekbar, int i, boolean flag) { b.onProgressChanged(seekbar, i, flag); } public final void onStartTrackingTouch(SeekBar seekbar) { b.onStartTrackingTouch(seekbar); } public final void onStopTrackingTouch(SeekBar seekbar) { if (a) { a = false; return; } else { b.onStopTrackingTouch(seekbar); return; } } }
Markdown
UTF-8
2,848
2.515625
3
[]
no_license
--- title: How Do I Set up the Shipment Tracking Link? --- # How Do I Set up the Shipment Tracking Link? If the **Shipment Tracking** field in your **Shipment Tracking Information** browser (path: From the **Sales Orders** browser or the **Sales Invoices** browser, select **Options** > **Shipment Tracking** **Information** or press **Ctrl + F11**), does not have a URL link, it will need to be configured. {:.steps} To configure the Shipment Tracking field link in the Shipment Tracking Information browser, do the following: - From the main menu bar, select **File** > **Setup** > **Freight** > **Delivery Methods**. You will see the **Delivery Methods** browser. Open the **Delivery Method** profile for your carrier. ![]({{site.sp_baseurl}}/img/delivery_methods_shipment_tracking_url_sal.gif) **Figure: Delivery Method Profile with Shipment Tracking URL** - In the **Shipment Tracking URL** field, enter the URL of the shipment tracking page of your carrier. To find the correct link for your carrier, go to your carrier's website and locate the page for entering web tracking information. Copy the link from the address bar to the Shipment Tracking URL field of your **Delivery Method** profile. UPS and FedEx URL links are shown below and are **subject to change**. - Add the following **UPS** link to the **Shipment Tracking URL** field in your UPS Delivery Methods in **Everest**:[ http://wwwapps.ups.com/WebTracking/processInputRequest?TypeOfInquiryNumber=T&InquiryNumber1=](http://wwwapps.ups.com/WebTracking/processInputRequest?TypeOfInquiryNumber=T&amp;InquiryNumber1=) - Add the following **FedEx** link to the **Shipment Tracking URL** field in your FedEx Delivery Methods in **Everest**: [ http://fedex.com/Tracking?action=track&tracknumber\_list=](http://fedex.com/Tracking?action=track&amp;tracknumber_list=) - Save your changes. Users can now press **Ctrl + Click** the link on the **Shipment Tracking****Information** browser (or the link on the **Shipment Tracking** tab in a sales document) to get the delivery status from the carrier's website. See the example in the following figures. **![]({{site.sp_baseurl}}/img/sales_invoice_sal.jpg)** **Figure: Shipment Tracking Link in a Sales Document** **![]({{site.sp_baseurl}}/img/shipment_tracking_information_dialog_sal.jpg)** **Figure: Shipment Tracking Information Browser** **![]({{site.sp_baseurl}}/img/shipment_tracking_information_sal.jpg)** **Figure: Delivery Status on Carrier Website** {:.see_also} See also : [How do I Get the Delivery Status from within Everest?]({{site.sp_baseurl}}/misc/how_do_i_get_the_delivery_status_from_within_everest_sal.html) : [Shipping Software Integration]({{site.sp_baseurl}}/sales-docs/docs-profile/contents/tab-details/ship-trk/shipping_software_integration_sal.html)
TypeScript
UTF-8
4,827
2.796875
3
[]
no_license
import { State, Store } from "./store" import { Circle } from "ol/geom" import { geometryActions } from "./actions" import { geometryMutations } from "./mutations" const circles = [ new Circle([1, 1], 1), new Circle([2, 2], 2), new Circle([3, 3], 3), new Circle([4, 4], 4), new Circle([5, 5], 5), ] const initialState = (): State => { return { allJobs: [], visibleJobs: [], selectedJobs: [], selectedGeometries: [], allGeometries: circles.slice(0, 1), } } describe("geometry actions", () => { describe("addGeometries()", () => { describe("when the state is empty", () => { it("should handle a single geometry", () => { const store = new Store(geometryActions, geometryMutations, initialState()) const geometries = circles.slice(0, 1) const success = store.dispatch("addGeometries", geometries) expect(success).toBe(true) expect(store.getState().allGeometries).toStrictEqual(geometries) }) it("should handle multiple geometries", () => { const store = new Store(geometryActions, geometryMutations, initialState()) const geometries = circles const success = store.dispatch("addGeometries", geometries) expect(success).toBe(true) expect(store.getState().allGeometries).toStrictEqual(geometries) }) }) describe("when there are geometries before", () => { it("should handle single geometries", () => { const customState = Object.assign(initialState(), { allGeometries: circles.slice(0, 4), }) const store = new Store(geometryActions, geometryMutations, customState) const geometries = circles.slice(4, 5) const want = circles.slice(0, 5) const success = store.dispatch("addGeometries", geometries) expect(success).toBe(true) expect(store.getState().allGeometries).toStrictEqual(want) }) it("should handle multiple geometries", () => { const customState = Object.assign(initialState(), { allGeometries: circles.slice(0, 4), }) const store = new Store(geometryActions, geometryMutations, customState) const geometries = circles.slice(4, 6) const want = circles.slice(0, 6) const success = store.dispatch("addGeometries", geometries) expect(success).toBe(true) expect(store.getState().allGeometries).toStrictEqual(want) }) }) }) describe("selectGeometries()", () => { describe("when the state is empty", () => { it("should handle single geometries", () => { const store = new Store(geometryActions, geometryMutations, initialState()) const geometries = circles.slice(0, 1) const success = store.dispatch("selectGeometries", geometries) expect(success).toBe(true) expect(store.getState().selectedGeometries).toStrictEqual(geometries) }) it("should handle multiple geometries", () => { const store = new Store(geometryActions, geometryMutations, initialState()) const geometries = circles const success = store.dispatch("selectGeometries", geometries) expect(success).toBe(true) expect(store.getState().selectedGeometries).toStrictEqual(geometries) }) }) describe("when there are geometries before", () => { it("should handle single geometries", () => { const customState = Object.assign(initialState(), { selectedGeometries: circles.slice(0, 4), }) const store = new Store(geometryActions, geometryMutations, customState) const geometries = circles.slice(4, 5) const want = circles.slice(0, 5) const success = store.dispatch("selectGeometries", geometries) expect(success).toBe(true) // Workaround because jest cannot match arrays that might have different order of elements. expect(store.getState().selectedGeometries.length).toBe(want.length) expect(new Set(store.getState().selectedGeometries)).toEqual(new Set(want)) }) it("should handle multiple geometries", () => { const customState = Object.assign(initialState(), { selectedGeometries: circles.slice(0, 3), }) const store = new Store(geometryActions, geometryMutations, customState) const geometries = circles.slice(3, 5) const want = circles.slice(0, 5) const success = store.dispatch("selectGeometries", geometries) expect(success).toBe(true) // Workaround because jest cannot match arrays that might have different order of elements. expect(store.getState().selectedGeometries.length).toBe(want.length) expect(new Set(store.getState().selectedGeometries)).toEqual(new Set(want)) }) }) }) })
C
UTF-8
573
2.875
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include<assert.h> #include<stdbool.h> #include<limits.h> int in_nextInt(){ int x; scanf("%d", &x); return x; } int main(){ int G = in_nextInt(); int sin[G]; for (int i=0; i<G; ++i) sin[i] = in_nextInt(); int m = 0; bool ok=false; while(!ok){ ++m; bool used[m]; memset(used, 0, sizeof(used)); ok = true; for(int i = 0; ok && i < G; ++i) if(used[sin[i]%m]) ok = false; else used[sin[i]%m]=true; } printf("%d\n", m); return 0; }
Python
UTF-8
702
4.28125
4
[]
no_license
#!/usr/bin/env python3 # -*- coding:UTF-8 -*- """题目4:输入某年某月某日,判断这一天是这一年的第几天?""" def get_days(year, month, day): months1 = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366] # 闰年 months2 = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] # 平年 if ((year%4==0) and (year%100!=0)) or ((year%100==0) and (year%400==0)): days = months1[month-1] + day else: days = months2[month-1] + day print("该日是该年的{}天".format(days)) if __name__ == '__main__': year = int(input("年:\n")) month = int(input("月:\n")) day = int(input("日:\n")) get_days(year, month, day)
Python
UTF-8
633
3.78125
4
[]
no_license
# угадай число import random a, b = 1, 100 SECRET = random.randint(a, b) if __name__ == '__main__': print(f"<<< УГАДАЙ ЧИСЛО ОТ {a} ДО {b}! >>>") counter, left, right = 0, a, b while True: counter += 1 choice = int(input(f"{counter}) ваш вариант ({left} - {right}): ")) if choice < SECRET: print("недолет") left = choice + 1 if choice > SECRET: print("перелет") right = choice - 1 if choice == SECRET: print("BINGO!") break print("<<< GAME OVER >>>")
C
UTF-8
967
2.609375
3
[]
no_license
#ifndef PROTOCOLE_H #define PROTOCOLE_H // Type de requete #define CONNECT 1 #define DECONNECT 2 #define TIR 3 #define SOUSMARIN 4 #define BATEAU_COULE 5 // Sens de deplacement des bateaux #define DROITE 1 #define GAUCHE 2 #define HAUT 3 #define BAS 4 struct Bateau { int type; int L; int C; int direction; int sens; }; struct RequeteTir { int L; int C; }; struct ReponseTir { int L; int C; int status; // Resultat du tir : valeurs possibles ci-dessous Bateau bateau; // infos completes du bateau coule }; // Valeurs possible de status #define LOCKED 1 // si cible deja verrouillee par un autre joueur #define PLOUF 2 // si aucun bateau touche #define TOUCHE 3 // si bateau touche en (L,C) mais non coule #define DEJA_TOUCHE 4 // si bateau deja touche en (L,C) par un autre joueur (et forcement pas coule) #define COULE 5 // si bateau touche en (L,C) et coule #endif
Java
UTF-8
704
3
3
[]
no_license
import org.junit.Assert; import org.junit.Test; public class Test { final double DELTA = 0.001; @Test public void measurementTest() { Measurement good = new Measurement(0); Measurement bad = new Measurement(-999); Measurement empty = new Measurement(); Assert.assertEquals("Retrieved incorrect value.", 0, good.getValue(), DELTA); Assert.assertEquals("Good case is invalid", true, good.isValid()); Assert.assertEquals("Bad case is valid", false, bad.isValid()); Assert.assertEquals("Bad toString for valid", "0.0000", good.toString()); Assert.assertEquals("Bad toString for invalid", "bad", empty.toString()); } }
Python
UTF-8
1,597
2.546875
3
[]
no_license
from project_app import db class BookMylist(db.Model): __tablename__ = 'bookmylist' title = db.Column(db.String(256), nullable=False) link = db.Column(db.String(256)) image = db.Column(db.String(256)) author = db.Column(db.String(256)) price = db.Column(db.String(256)) discount = db.Column(db.String(256)) publisher = db.Column(db.String(256)) isbn = db.Column(db.String(256),primary_key=True) description = db.Column(db.Text) pubdate = db.Column(db.String(256)) def __repr__(self): return f"User {self.isbn}" def add_mylist(compare_book): title = compare_book.title link = compare_book.link image = compare_book.image author = compare_book.author price = compare_book.price discount = compare_book.discount publisher = compare_book.publisher isbn = compare_book.isbn description = compare_book.description pubdate = compare_book.pubdate if BookMylist.query.filter(BookMylist.isbn == isbn).first() == None : updated = BookMylist(title=title, link=link, image=image, author=author,\ price=price, discount=discount, publisher=publisher, isbn=isbn,\ description=description, pubdate=pubdate) db.session.add(updated) db.session.commit() def get_mylists() : return BookMylist.query.all() def del_mylist(isbn): mylist = BookMylist.query.filter(BookMylist.isbn == isbn).first() db.session.delete(mylist) db.session.commit() def get_mylist(isbn): return BookMylist.query.filter(BookMylist.isbn == isbn).first()
Markdown
UTF-8
1,279
3.640625
4
[]
no_license
# 思路 * 首先删除前面所有的空格; * 使用$minus$记录当前数字的正负; * 遍历字符串,将当前字符加入$ans$ 结果中: * 如果$ans*10+x>INT\_MAX$,则发生溢出; * 如果$-ans*10-x<INT\_MIN$,则发生溢出; * 需要特判负数的最小值,因为其绝对值比整数最大值绝对值大一。 # 时间复杂度 $$ O(n) $$ # 代码 ```java class Solution { public int myAtoi(String s) { int k = 0; char[] str = s.toCharArray(); while (k < str.length && str[k] == ' ') k++; if (k == str.length) return 0; int minus = 1; if (str[k] == '-') { minus = -1; k++; } else if (str[k] == '+') k++; int ans = 0; while (k < str.length && str[k] >= '0' && str[k] <= '9') { int x = str[k] - '0'; if (minus > 0 && ans > (Integer.MAX_VALUE - x) / 10) return Integer.MAX_VALUE; if (minus < 0 && -ans < (Integer.MIN_VALUE + x) / 10) return Integer.MIN_VALUE; if (-ans * 10 - x == Integer.MIN_VALUE) return Integer.MIN_VALUE; ans = ans * 10 + x; k++; if (ans > Integer.MAX_VALUE) break; } ans *= minus; return ans; } } ```
Python
UTF-8
3,222
3.359375
3
[]
no_license
''' Simeon Smith DPW1607 07-09-16 Simple Form ''' #REQUIREMENTS #Collect 5 pieces of information. #One text based #One radio button #One select item #Organize HTML elements in page class. #Use GET method to deliver info gathered. #List information after GET. #Create a polished and professional design. #Comment code. #Make 6 commits to GitHub. #No global variables. #No errors. #No frameworks. import webapp2 #Import the page class. from pages import Page #GOOGLE APP ENGINE CLASS class MainHandler(webapp2.RequestHandler): def get(self): #Pull in the page class and store it. page = Page() #If there is a GET request store the variables from GET and write page. if self.request.GET: #NAME VARIABLES fname = self.request.GET['fname'] #First Name lname = self.request.GET['lname'] #Last Name name = fname + ' ' + lname #Concat first and last name #TITLE VARIABLE title = self.request.GET['job_title'] #Title #If title is empty insert a page break. if title == "": title = "<br>" #CONTACT VARIABLES email = self.request.GET['email'] #Email #PHONE NUMBER PARTS phone1 = self.request.GET['phone1'] #Phone section 1 phone2 = self.request.GET['phone2'] #Phone section 2 phone3 = self.request.GET['phone3'] #Phone section 3 phone_style = self.request.GET['phone_sep'] #Formatting style for phone number #Check for the phone style type and store the results as phone if phone_style == "classic": #Format as classic phone = "(" + str(phone1) + ") " + str(phone2) + "-" + str(phone3) elif phone_style == "dot": #Format with dot phone = str(phone1) + "." + str(phone2) + "." + str(phone3) elif phone_style == "dash": #Format with dash phone = str(phone1) + "-" + str(phone2) + "-" + str(phone3) #ADDRESS PARTS street = self.request.GET['street'] #Street Address city = self.request.GET['city'] #City zip_code = self.request.GET['zip_code'] #Zip Code #Concat city and zip code. city = city + ' ' + zip_code #Pull in the card page template from the page class. card_page = page.card_page #Format the template with the locals provided by GET card_page = card_page.format(**locals()) #Write the card_page variable to the page. self.response.write(card_page) #If no GET write the form page. else: #Pull in the form pagefrom the page class. form_page = page.form_page #Write the form_page variable to the page. self.response.write(form_page) app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True)
Java
UTF-8
975
2.453125
2
[]
no_license
import java.util.ArrayList; import java.util.HashMap; public class Chromosom { String activSystem; HashMap<String, Double> evaluateCritic; public HashMap<String, Double> getEvaluateCritic() { return evaluateCritic; } public void setEvaluateCritic(HashMap<String, Double> evaluateCritic) { this.evaluateCritic = evaluateCritic; } public String getActivSystem() { return activSystem; } public void setActivSystem(String activSystem) { this.activSystem = activSystem; } double cost; double green; double comfort; public double getCost() { return cost; } public void setCost(double evaluate) { this.cost = evaluate; } public double getGreen() { return green; } public void setGreen(double green) { this.green = green; } public double getComfort() { return comfort; } public void setComfort(double comfort) { this.comfort = comfort; } public static void main(String[] args) { // TODO Auto-generated method stub } }
PHP
UTF-8
1,387
2.71875
3
[]
no_license
<?php namespace Yandex\Allure\Adapter\Example; use PHPUnit_Framework_TestCase; use Yandex\Allure\Adapter\Annotation\Title; use Yandex\Allure\Adapter\Support\AttachmentSupport; /** * @package Yandex\Allure\Adapter\Example * @Title("Tests with attachments") */ class AttachmentsTest extends PHPUnit_Framework_TestCase { use AttachmentSupport; /** * @Title("Attachment processing test") */ public function testProcessAttachments() { $filePathFromMethod = $this->outputSomeContentToTemporaryFile(); $this->addAttachment($filePathFromMethod, 'Content from temporary file', 'text/plain'); $this->assertTrue(file_exists($filePathFromMethod)); $contentsFromMethod = $this->outputSomeContentDirectly(); $this->addAttachment($contentsFromMethod, 'Content from method return type', 'text/html'); $this->assertTrue(strlen($contentsFromMethod) > 0); } private function outputSomeContentToTemporaryFile() { $tmpPath = tempnam(sys_get_temp_dir(), 'test'); file_put_contents($tmpPath, 'Some content to be outputted to temporary file.'); return $tmpPath; } private function outputSomeContentDirectly() { return 'Some content to be outputted as method return value.'; } private function getUrl() { return 'http://allure.qatools.ru/'; } }
C++
UTF-8
1,344
3
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #define MAX_N 100000 #define MAX_Q 5000 using namespace std; typedef struct { int s; int e; int k; } Query; int inp(){ char c; int neg = 0; while(1){ c = getchar_unlocked(); if(c == '-'){ neg = 1; } else if (c >= '0' && c <= '9') { break; } else { neg = 0; } } int num = c - '0'; while((c = getchar_unlocked()) >= '0' && c <= '9') num = (num * 10) + (c - '0'); return neg ? -1 * num : num; } int main(){ int n, q; int A[MAX_N]; Query Q[MAX_Q]; // Read Input // cin >> n >> q; n = inp(); q = inp(); // cout << "n:" << n << " q:" << q << endl; // Debug // for (int i=0; i<n; i++) cin >> A[i]; for (int i=0; i<n; i++) A[i] = inp(); // for (int i=0; i<n; i++) cout << "\t" << A[i] << endl; // Debug for (int i=0; i<q; i++){ Q[i].s = inp()-1; Q[i].e = inp()-1; Q[i].k = inp(); // cin >> Q[i].s >> Q[i].e >> Q[i].k; // cout << "s: " << Q[i].s << " e: " << Q[i].e << " k: " << Q[i].k << endl; // Debug } // Process Queries for (int i=0; i<q; i++){ // Sort sub array vector<int> heap(A + Q[i].s, A + Q[i].e + 1); sort(heap.begin(), heap.end()); // for(auto x: heap){ // Debug // cout << x << " "; // } // cout << endl; // Print Kth smallest element printf("%d\n", heap[Q[i].k-1]); } return 0; }
C
UTF-8
2,356
3.421875
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 1024 #define NUM_PAGES 472 typedef struct matrix { int[NUM_PAGES][NUM_PAGES] data; page_t[NUM_PAGES] pages; } matrix_t; typedef struct link { char* link; struct link* next; } link_t; typedef struct list { link_t *head; } list_t; typedef struct page { char * name; char * link; int index; list_t *links; outbound_list_t* numerical_links } page_t; typedef struct outbound_list { int *data; int size; } outbound_list_t; outbound_list_t* parse_data(char *data) { char *number; static int num[NUM_PAGES]; int count = 0; strtok(data, "["); while ((number = strtok(NULL, ",")) != NULL) { num[count] = atoi(number); count++; } outbound_list_t* list = malloc(sizeof(outbound_list_t)); list->data = num; list->size = count; //number = strtok(NULL, "]"); //num[count] = atoi(number); return list; } int main(int argc, char *argv[]) { if (argc != 2) { perror("Invalid syntax: matrix [filename]\n"); exit(2); } // Read csv file address from command line argument char *addr = argv[1]; // Read CSV file FILE *csvStream = fopen(addr, "r"); if (csvStream == NULL) { fprintf(stderr, "Error reading the csv file."); exit(2); } //allocate space for the matrix //page_t* p = (page_t*) malloc(NUM_PAGES*sizeof(page_t)); matrix_t* matrix = (matrix_t*) malloc(sizeof(matrix_t)); matrix->data = {{0}}; // Array of Marvel Character Names char *names[NUM_PAGES]; // Allocate line buffer //char buffer[BUFFER_SIZE]; char *buffer = NULL; size_t linecap = 0; size_t len; int line_count = 0; while ((len = getline(&buffer, &linecap, csvStream)) > 0 && line_count <= 1) { char *data = strtok(buffer, "|"); //printf("%s ", data); names[line_count] = malloc(sizeof(char) * BUFFER_SIZE); strncpy(names[line_count], buffer, BUFFER_SIZE); data = strtok(NULL, "|"); data = strtok(NULL, "|"); //Index of the webpage //printf("\t %s ", data); data = strtok(NULL, "|"); data = strtok(NULL, "|"); //List of outbound links //printf("\t %s \n", data); outbound_list_t* list = parse_data(data); //print for(int i=0;i<list->size;i++) { printf("%d ", *(list->data + i)); } printf("\n\n"); line_count++; } for (int i=0;i<line_count;i++) { printf("%s\n", names[i]); } return 0; }
C++
UTF-8
2,014
2.59375
3
[]
no_license
/* YAP - Yet another PWA toolkit Copyright 2015, Technische Universitaet Muenchen, Authors: Daniel Greenwald, Johannes Rauch This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// \file #ifndef yap_MassShapeWithNominalMass_h #define yap_MassShapeWithNominalMass_h #include "MassShape.h" #include <memory> namespace yap { class DataPoint; class ParticleCombination; /// \class MassShapeWithNominalMass /// \brief Class for MassShape that gets its nominal mass from its owning resonance /// \author Daniel Greenwald /// \ingroup MassShapes class MassShapeWithNominalMass : public MassShape { public: /// Constructor MassShapeWithNominalMass() : MassShape() {} /// Set parameters from ParticleTableEntry /// \param entry ParticleTableEntry containing information to create mass shape object virtual void setParameters(const ParticleTableEntry& entry) override; /// Get mass std::shared_ptr<RealParameter> mass(); /// Get mass (const) const std::shared_ptr<RealParameter> mass() const { return const_cast<MassShapeWithNominalMass*>(this)->mass(); } virtual std::string data_accessor_type() const override {return "MassShapeWithNominalMass"; } protected: /// set dependency on resonance's mass virtual void setDependenciesFromResonance() override; /// set dependency on masses from model virtual void setDependenciesFromModel() override; }; } #endif
Markdown
UTF-8
646
2.984375
3
[]
no_license
# Numerical Problem Solving course - Spring 2017 - Metropolia UAS The aim of this course is to introduce the most common mathematical and numerical methods and tools that are used for solving engineering problems. * Week 1: Preparation and start up (18.1.2017) * Week 2: Approximation and round-off errors * Week 3: Making graphs * Week 4: Gauss elimination * Week 5: LU decompositions * Week 6: Applications of linear algebra * Week 7: Review (8.3.2017) * Week 8: Test (15.3.2017) * Week 9: Root finding * Week 10: Root finding * Week 11: Optimization * Week 12: Curve fitting * Week 13: Numerical integration * Week 14: Review (3.5.2017)
Java
UTF-8
191
1.71875
2
[]
no_license
package behaviors; import athlete.AthleteTracker; import athlete.Race; import communicator.RaceTracker; public interface RaceEvents { public void raceExecute(Race race, String message); }
Java
UTF-8
391
2.046875
2
[ "BSD-2-Clause" ]
permissive
package com.leemon.wushiwan.enums; /** * @description: 推送消息类型 * @author: limeng * @create: 2019-12-12 22:59 **/ public enum PushPayloadType { NONE, TOAST,//在线显示一个toast,离线显示通知 NOTICE//完成任务或者从后台推送的通知,在线会在消息页面多一条消息(通过socialnotice触发),消息会显示角标,离线显示通知 }
Markdown
UTF-8
7,323
2.828125
3
[]
no_license
--- title: Shoen characterId: 12 occupation: "Calligrapher (書道家)" h2: title: "\"Secret Agent\" Shoen" --- {% capture BIO_H01 %} Transforms into a hakama-clad hero who carries a parallel weapon in the shape of a huge brush. Using his tail as an inkwell, the energy extracted from his body can be used as ink to form an embodied "living kanji character" in the air. The letters he writes act according to the meaning of the word, and when they finish their actions, they disperse. Shoen's technique has a particular characteristic that the power of the attack and the effect on the target can change according to different meanings of the characters. {% endcapture %} {% capture BIO_H02 %} His hope is to "write 'living' characters." Every time he sees the letters written in the air gaining life and fulfilling their assigned mission, he becomes keenly aware of his imperfection and regrets it. All of this stems from a supreme book full of incredible writing that he once laid eyes on in a Japanese temple. In the ink marks, he saw a beauty that would never decay no matter how much time passed. He continues to challenge himself with calligraphy, until the day when he can produce such a work with his own hands. {% endcapture %} {% include hero-infobox.html stockId=10121 BIO_H01=BIO_H01 BIO_H02=BIO_H02 %} {% capture BIO_H01 %} Shoen stood up during the calamity in which everyone's secrets are revealed regardless of their intention/desire. Whilst wearing a mantle that hides his body, it resembles an outfit befitting of someone on a mission to infiltrate an enemy organisation, personifying the thought that "There are things that's better if kept hidden". In his hand, he has a brush that is disguised as an umbrella. In the event of an emergency in enemy territory, he pulls out his brush and uses the ink in his suitcase to protect people's secrets. {% endcapture %} {% capture BIO_H02 %} Modesty is a virtue, for a poor talker and cowardly person like him, What he fears most is that others will find out about his greedy side. The root of this is a bitter memory of falling in love with those he work for. Understanding his position and being confused with his gushing feelings, he hold the trauma of saying the last farewell without conveying his feelings. His desire and his cowardice ashamed him greatly, and so he lock this memory deep down in his heart. Telling himself to never expose it again…or so it should be. {% endcapture %} {% include hero-infobox.html stockId=10122 BIO_H01=BIO_H01 BIO_H02=BIO_H02 %} {% capture BIO_S01 %} A calligrapher who owns a small calligraphy one-room school in Orient City. He is also an educator registered as visiting scholar at university's literature department. He is an alien from a different world who has devoted his life pursuing calligraphy ever since he became strongly impressed with the culture of japan, the country of earth he first landed on. Due to his enormous size and the fact that he's taciturn and has an unfriendly face, he tends to come off as scary, but he has an exceedingly gentle personality, He is fond of children He has a habit of giving folded origami figures to the children he meets. {% endcapture %} {% include sidekick-infobox.html stockId=10121 BIO_S01=BIO_S01 %} {% include voice-table.html resourceName="shoen" h_gachaResult = "...I am Shoen,<br>someone who makes good use of characters and spreads them around...<br>that’s the kind of man I am." s_gachaResult = "My name's Shoen, I'm a simple calligrapher.<br>My writing is not really good but,<br>If it help master and the others..<br>I will provide assistance,<br>With all that I can offer" salesStart = "I'm going." salesEnd = "I'm back." battleStart = "Singular focus in each stroke...until the final one.<br>This is the path of my writing." action = "...Alright." attack = "Humph!" skill = "It's fleeting..." special = "Scattered ink, gather to end evil.<br>Depart[^shoen_n1] ...Ninety-nine Ink Marks. [^shoen_n1]: 送筆, Literally:to send the writing; think of it like taomon's ultimate skill i.e.: writing on the air and send it to the enemy" smallDamage = "Nn!" bigDamage = "Uoo!" win = "It will break and disappear again.<br>Born and then gone...an existence like a bubble.<br>...the lives of the characters, are a fleeting one." lose = "I guess this is retribution...My characters...I'm sorry." assist = "Maybe this can help." assisted = "Thank you." APPRECIATION = "It's important to keep your mind calm.<br>You must always find time to attend to your own needs... Do you want to fold origami together?<br>It always puts my heart at ease." DAILY = "... I was just folding origami.<br>Well, if it is time to get to work... I am ready." RELATION = "Toshu is different alien species than I, but our hearts share the same fondness for Japanese culture.<br>This is a secret, but if you give him sweets made from red bean paste he will be greatly pleased." HERO = "The one who changed the flow of time with letters.<br>While using the same means as I, their power is completely different.<br>Their characters…has powers unknown to me." PLAYER = "I…didn't really understand master's job.<br>but…when master is not here, I can't make use of my characters.<br>I understand that much." TOUCH = "Mmm ... you want to touch my belly ...?<br>Is this... what is known as skinship?<br>Hmm ... I see ..." TRAIN = "Will you train together with me?" TRAINED = "This body, move...!" %} {% include voice-table.html resourceName="shoenValentine2102" h_gachaResult = "Let us take back those peaceful days.<br>In order to protect everyone's concealed hearts, I shall use my body as a shield, shaking this brush of mine..." s_gachaResult = "If my brush can save someone's heart then I will gladly wield it.<br>With our hands--let's return the heart's peaceful days." APPRECIATION = "Do you enjoy making tea and spending time in calm tranquility?<br>It will be a good rest for your heart. ...what? What do I want to say? ... I erm, I was inviting you to join me... " DAILY = "The time I spend writing is the most relaxing.<br>...I'm sorry, I made you wait. My heart is ready at last, let's go. " RELATION = "There aren't many people who can speak so frankly and unabashedly as Kyoichi.<br>If I could be like him, I wonder, perhaps I wouldn't worry so much about seeming standoffish..." HERO = "Because I am not well versed in technology, Hisaki's inventions seem so bizarre to me.<br>The world is so vast and filled with things I do not know..." PLAYER = "Have you ever embraced a burning, passionate feeling?<br>…What a rude question to ask.<br>Recent events have gotten me a little sentimental it seems... My apologies." TOUCH = "My goal is acquire a heart as clear and serene as still water.<br>Therefore, even when my true self[^shoen_n2] is touched...kuaagh?! <br>...I want you to say that you didn't hear that sound just now. [^shoen_n2]: 腹, Literally: belly/true self, Shoen is talking about meditating on his inner true self but the word also means belly so we just grabs a handful" TRAIN = "Calm your heart, here i go." TRAINED = "My shame is getting the better of me...!" %} ## Notes - He refers to {% chara_link Subaru %} in his hero line
Python
UTF-8
5,419
3.6875
4
[]
no_license
#!/usr/bin/env python # -*- coding: UTF-8 -*- import random import itertools import time cities = [] def plot_tour(tour): "Plot the cities as circles and the tour as lines between them." plot_lines(list(tour) + [tour[0]]) def plot_lines(points, style='bo-'): "Plot lines to connect a series of points." plt.plot(map(X, points), map(Y, points), style) plt.axis('scaled'); plt.axis('off') def plot_tsp(algorithm, cities): "Apply a TSP algorithm to cities, plot the resulting tour, and print information." # Find the solution and time how long it takes t0 = time.clock() tour = algorithm(cities) t1 = time.clock() assert valid_tour(tour, cities) #plot_tour(tour); plt.show() print("{} city tour with length {:.1f} in {:.3f} secs for {}" .format(len(tour), tour_length(tour), t1 - t0, algorithm.__name__)) return tour def valid_tour(tour, cities): "Is tour a valid tour for these cities?" return set(tour) == set(cities) and len(tour) == len(cities) # Cities are represented as Points, which are represented as complex numbers Point = complex City = Point def X(point): "The x coordinate of a point." return point.real def Y(point): "The y coordinate of a point." return point.imag def distance(A, B): "The distance between two points." dist = A - B return max(abs(dist.real), abs(dist.imag)) def altered_greedy_tsp(cities): "Run greedy TSP algorithm, and alter the results by reversing segments." return alter_tour(greedy_tsp(cities)) def alter_tour(tour): "Try to alter tour for the better by reversing segments." original_length = tour_length(tour) for (start, end) in all_segments(len(tour)): reverse_segment_if_better(tour, start, end) # If we made an improvement, then try again; else stop and return tour. if tour_length(tour) < original_length: return alter_tour(tour) return tour def reverse_segment_if_better(tour, i, j): "If reversing tour[i:j] would make the tour shorter, then do it." # Given tour [...A-B...C-D...], consider reversing B...C to get [...A-C...B-D...] A, B, C, D = tour[i-1], tour[i], tour[j-1], tour[j % len(tour)] # Are old edges (AB + CD) longer than new ones (AC + BD)? If so, reverse segment. if distance(A, B) + distance(C, D) > distance(A, C) + distance(B, D): tour[i:j] = reversed(tour[i:j]) def all_segments(N): "Return (start, end) pairs of indexes that form segments of tour of length N." return [(start, start + length) for length in range(N, 2-1, -1) for start in range(N - length + 1)] def greedy_tsp(cities): """Go through edges, shortest first. Use edge to join segments if possible.""" edges = shortest_edges_first(cities) # A list of (A, B) pairs endpoints = {c: [c] for c in cities} # A dict of {endpoint: segment} for (A, B) in edges: if A in endpoints and B in endpoints and endpoints[A] != endpoints[B]: new_segment = join_endpoints(endpoints, A, B) if len(new_segment) == len(cities): return new_segment def tour_length(tour): "The total of distances between each pair of consecutive cities in the tour." return sum(distance(tour[i], tour[i-1]) for i in range(len(tour))) def shortest_edges_first(cities): "Return all edges between distinct cities, sorted shortest first." edges = [(A, B) for A in cities for B in cities if id(A) < id(B)] return sorted(edges, key=lambda edge: distance(*edge)) def join_endpoints(endpoints, A, B): "Join B's segment onto the end of A's and return the segment. Maintain endpoints dict." Asegment, Bsegment = endpoints[A], endpoints[B] if Asegment[-1] is not A: Asegment.reverse() if Bsegment[0] is not B: Bsegment.reverse() Asegment.extend(Bsegment) del endpoints[A], endpoints[B] endpoints[Asegment[0]] = endpoints[Asegment[-1]] = Asegment return Asegment def Cities(n, width=900, height=600, seed=42): "Make a set of n cities, each with random coordinates within a (width x height) rectangle." random.seed(seed * n) return frozenset(City(random.randrange(width), random.randrange(height)) for c in range(n)) def shortest_tour(tours): "Choose the tour with the minimum tour length." return min(tours, key=tour_length) def tour_length(tour): "The total of distances between each pair of consecutive cities in the tour." return sum(distance(tour[i], tour[i-1]) for i in range(len(tour))) def add_city(x, y): global cities cities.append(City(x, y)) """ def find_start_end(): global cities, city_start, city_end city_start = cities[0] city_end = cities[0] # 左上角的值 city_leftupper = City(0, max([c.imag for c in cities])) city_leftlower = City(0, 0) for city in cities: if distance_raw(city, city_leftlower) < distance_raw(city_start, city_leftlower): city_start = City(city) if distance_raw(city, city_leftupper) < distance_raw(city_end, city_leftupper): city_end = City(city) """ if __name__ == '__main__': #plot_tsp(altered_greedy_tsp, Cities(60*36)) cities = [] for i in range(15*36): add_city(random.randrange(1000), random.randrange(1000)) #find_start_end() #print city_start #print city_end tour = plot_tsp(altered_greedy_tsp, frozenset(cities)) print tour
C++
UTF-8
1,370
2.640625
3
[]
no_license
//In The Name Of God #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef vector<string> vs; typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<vvi> vvvi; typedef vector<vvvi> vvvvi; typedef vector<ii> vii; typedef vector<iii> viii; typedef vector<vii> vvii; typedef vector<vvii> vvvii; typedef vector<vector<viii>> vvviii; typedef vector<vector<iii>> vviii; typedef set<int> si; typedef vector<si> vsi; typedef pair<double, double> dd; typedef vector<dd> vdd; typedef pair<dd, double> ddd; typedef vector<ddd> vddd; #define inf 1000000000 #define eps 1e-9 int main() { ios::sync_with_stdio(0); ll w, l, tc = 0; while(cin >> w >> l && (w || l)) { ll num = 0; double all = 0; for(ll x = l; x <= w / 8 + l; x++) { if((x - l) * 8 <= w && w <= (x - l) * 8 + 7 * l) { all += ((x - l) * 8. + (w - (x - l) * 8 + l)) / x; num++; } } cout << "Case " << ++tc << ":\n"; if(num) { cout << "On Average Bob Reaches Round "; cout << fixed << setprecision(2) << all / num << endl; } else cout << "Situation Impossible." << endl; } return 0; }
Java
UTF-8
3,898
2.234375
2
[]
no_license
package version2.prototype.summary; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import version2.prototype.Config; import version2.prototype.ErrorLog; import version2.prototype.Process; import version2.prototype.PluginMetaData.PluginMetaDataCollection.PluginMetaData; import version2.prototype.ProjectInfoMetaData.ProjectInfoFile; import version2.prototype.ProjectInfoMetaData.ProjectInfoPlugin; import version2.prototype.ProjectInfoMetaData.ProjectInfoSummary; import version2.prototype.Scheduler.ProcessName; import version2.prototype.Scheduler.Scheduler; import version2.prototype.summary.temporal.TemporalSummaryCompositionStrategy; import version2.prototype.summary.temporal.TemporalSummaryRasterFileStore; import version2.prototype.util.DataFileMetaData; import version2.prototype.util.DatabaseCache; /** * The custom Summary framework, Process extending class. Manages SummaryWorker objects. * * @author michael.devos * */ public class Summary extends Process { private Map<Integer, TemporalSummaryRasterFileStore> fileStores; /** * Creates a Summary object with the defined initial TaskState, owned by the given Scheduler, and acquiring its input from the specified * process, inputProcessName. * @param configInstance - Config reference to use and pass on * @param projectMetaData - the current project's information * @param pluginInfo - the current plugin's general information * @param pluginMetaData - the current plugin's xml data mapped * @param scheduler - reference to the controlling Scheduler object * @param inputCache * @param outputCache */ public Summary(Config configInstance, ProjectInfoFile projectMetaData, ProjectInfoPlugin pluginInfo, PluginMetaData pluginMetaData, Scheduler scheduler, DatabaseCache inputCache, DatabaseCache outputCache) { super(configInstance, ProcessName.SUMMARY, projectMetaData, pluginInfo, pluginMetaData, scheduler, outputCache); inputCache.addObserver(this); fileStores = new HashMap<Integer, TemporalSummaryRasterFileStore>(); String temporalSummaryCompositionStrategyClassName; TemporalSummaryRasterFileStore fileStore; Class<?> strategyClass; Constructor<?> ctorStrategy = null; for(ProjectInfoSummary summary : projectMetaData.GetSummaries()) { fileStore = null; temporalSummaryCompositionStrategyClassName = summary.GetTemporalSummaryCompositionStrategyClassName(); if(temporalSummaryCompositionStrategyClassName != null && !temporalSummaryCompositionStrategyClassName.isEmpty()) { try { strategyClass = Class.forName("version2.prototype.summary.temporal.CompositionStrategies." + temporalSummaryCompositionStrategyClassName); ctorStrategy = strategyClass.getConstructor(); fileStore = new TemporalSummaryRasterFileStore((TemporalSummaryCompositionStrategy)ctorStrategy.newInstance()); } catch(ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { ErrorLog.add(processName, scheduler, "Problem instantiating temporal filestore.", e); } } fileStores.put(summary.GetID(), fileStore); } } @Override public void process(ArrayList<DataFileMetaData> cachedFiles) { scheduler.StartNewProcessWorker(new SummaryWorker(configInstance, this, projectInfoFile, pluginInfo, pluginMetaData, cachedFiles, outputCache, fileStores)); } }
C++
UTF-8
977
3.109375
3
[]
no_license
#ifndef ARRAY_MEMORY_MANAGER_HPP #define ARRAY_MEMORY_MANAGER_HPP #include "MemoryManager.hpp" template<class Status> class ArrayMemoryManager : public MemoryManager<Status> { protected: using MemoryManager<Status>::end; using MemoryManager<Status>::size; using MemoryManager<Status>::memory; public: ArrayMemoryManager(const size_t& size) : MemoryManager<Status>{size} {} bool addChildren(Status* node, const size_t& num); Status* allocate(); void reset(); }; template<class Status> bool ArrayMemoryManager<Status>::addChildren(Status* node, const size_t& num) { if (num > size - end) return false; node->setChildren(allocate(), num); for (size_t i = 0; i < num; ++i) resetStatus<Status>(memory + end - 1 + i); end += num - 1; return true; } template<class Status> Status* ArrayMemoryManager<Status>::allocate() { return memory + end++; } template<class Status> void ArrayMemoryManager<Status>::reset() { end = 0; } #endif // ARRAY_MEMORY_MANAGER_HPP
C#
UTF-8
2,739
3.109375
3
[]
no_license
using System; using System.Collections.Specialized; namespace MetaBuilders.Irc.Messages { /// <summary> /// The KillMessage is used to cause a client-server connection to be closed by the server which has the actual connection. /// </summary> /// <remarks> /// KillMessage is used by servers when they encounter a duplicate entry in the list of valid nicknames and is used to remove both entries. /// It is also available to operators. /// </remarks> [Serializable] public class KillMessage : CommandMessage { string nick = ""; string reason = ""; /// <summary> /// Gets or sets the nick of the user killed. /// </summary> public virtual string Nick { get { return nick; } set { nick = value; } } /// <summary> /// Gets or sets the reason for the kill. /// </summary> public virtual string Reason { get { return reason; } set { reason = value; } } /// <summary> /// Gets the Irc command associated with this message. /// </summary> protected override string Command { get { return "KILL"; } } /// <summary> /// Overrides <see cref="IrcMessage.AddParametersToFormat"/>. /// </summary> protected override void AddParametersToFormat(IrcMessageWriter writer) { base.AddParametersToFormat(writer); writer.AddParameter(Nick); if (Reason.Length != 0) { writer.AddParameter(Reason); } else { writer.AddParameter("kill"); } } /// <summary> /// Parses the parameters portion of the message. /// </summary> protected override void ParseParameters(StringCollection parameters) { base.ParseParameters(parameters); if (parameters.Count >= 2) { Nick = parameters[0]; Reason = parameters[1]; } else { Nick = ""; Reason = ""; } } /// <summary> /// Notifies the given <see cref="MessageConduit"/> by raising the appropriate event for the current <see cref="IrcMessage"/> subclass. /// </summary> public override void Notify(MessageConduit conduit) { conduit.OnKill(new IrcMessageEventArgs<KillMessage>(this)); } } }
Java
UTF-8
6,663
2.265625
2
[]
no_license
package com.medica.core.service.perform; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.medica.core.domain.CoreDataPiece; import com.medica.core.domain.DiagnosisCoreData; import com.medica.core.domain.DiagnosisCoreResult; import com.medica.core.domain.rule.DiagnosisCoreRule; import com.medica.core.domain.rule.components.AndContainer; import com.medica.core.domain.rule.components.Operators; import com.medica.core.domain.rule.components.OrContainer; import com.medica.core.domain.rule.components.SimpleExpression; import com.medica.core.service.perform.impl.DefaultPerformService; public class DefaultPerformServiceTest { private static final String ATTRIBUTE_1_VALUE = "ATTRIBUTE_VALUE_1"; private static final String ATTRIBUTE_1_NAME = "ATTRIBUTE_NAME_1"; private static final String ATTRIBUTE_2_VALUE = "ATTRIBUTE_VALUE_2"; private static final String ATTRIBUTE_2_NAME = "ATTRIBUTE_NAME_2"; private static final String ATTRIBUTE_3_VALUE = "ATTRIBUTE_VALUE_3"; private static final String ATTRIBUTE_3_NAME = "ATTRIBUTE_NAME_3"; private static final int CONDITION_2_PROBABILITY = 90; private static final String CONDITION_2_NAME = "CONDITION_2_NAME"; private static final int CONDITION_1_PROBABILITY = 100; private static final String CONDITION_1_NAME = "CONDITION_1_NAME"; DefaultPerformService performService = new DefaultPerformService(); @Test public void shouldWorkForSimpleExample() { List<DiagnosisCoreRule> rules = prepareSimpleRules(); DiagnosisCoreData data = prepareSimpleData(); DiagnosisCoreResult diagnosisResult = performService.performDiagnosis(data, rules); assertThat(diagnosisResult.getConditionProbability().size(), equalTo(1)); assertThat(diagnosisResult.getConditionProbability().get(CONDITION_1_NAME), equalTo(CONDITION_1_PROBABILITY)); } @Test public void shouldWorkForComplexExample() { List<DiagnosisCoreRule> rules = prepareComplexRules(); DiagnosisCoreData validData1 = new DiagnosisCoreData(); validData1.addDataPiece(getSampleCoreDataPiece(ATTRIBUTE_1_NAME, ATTRIBUTE_1_VALUE)); validData1.addDataPiece(getSampleCoreDataPiece(ATTRIBUTE_2_NAME, ATTRIBUTE_2_VALUE)); DiagnosisCoreData validData2 = new DiagnosisCoreData(); validData2.addDataPiece(getSampleCoreDataPiece(ATTRIBUTE_1_NAME, ATTRIBUTE_1_VALUE)); validData2.addDataPiece(getSampleCoreDataPiece(ATTRIBUTE_2_NAME, ATTRIBUTE_2_VALUE)); validData2.addDataPiece(getSampleCoreDataPiece(ATTRIBUTE_3_NAME, ATTRIBUTE_1_VALUE)); DiagnosisCoreData invalidData = new DiagnosisCoreData(); invalidData.addDataPiece(getSampleCoreDataPiece(ATTRIBUTE_1_NAME, ATTRIBUTE_2_VALUE)); invalidData.addDataPiece(getSampleCoreDataPiece(ATTRIBUTE_2_NAME, ATTRIBUTE_2_VALUE)); invalidData.addDataPiece(getSampleCoreDataPiece(ATTRIBUTE_3_NAME, ATTRIBUTE_3_VALUE)); DiagnosisCoreResult validDiagnosisResult1 = performService.performDiagnosis(validData1, rules); DiagnosisCoreResult validDiagnosisResult2 = performService.performDiagnosis(validData2, rules); DiagnosisCoreResult invalidDiagnosisResult = performService.performDiagnosis(invalidData, rules); assertThat(validDiagnosisResult1.getConditionProbability().size(), equalTo(2)); assertThat(validDiagnosisResult1.getConditionProbability().get(CONDITION_1_NAME), equalTo(CONDITION_1_PROBABILITY)); assertThat(validDiagnosisResult1.getConditionProbability().get(CONDITION_2_NAME), equalTo(CONDITION_2_PROBABILITY)); assertThat(validDiagnosisResult2.getConditionProbability().size(), equalTo(2)); assertThat(validDiagnosisResult2.getConditionProbability().get(CONDITION_1_NAME), equalTo(CONDITION_1_PROBABILITY)); assertThat(validDiagnosisResult2.getConditionProbability().get(CONDITION_2_NAME), equalTo(CONDITION_2_PROBABILITY)); assertThat(invalidDiagnosisResult.getConditionProbability().size(), equalTo(1)); assertThat(invalidDiagnosisResult.getConditionProbability().get(CONDITION_2_NAME), equalTo(CONDITION_2_PROBABILITY)); } private List<DiagnosisCoreRule> prepareSimpleRules() { List<DiagnosisCoreRule> rules = new ArrayList<DiagnosisCoreRule>(); DiagnosisCoreRule rule1 = new DiagnosisCoreRule(); rule1.setExpression(getSimpleExpression(ATTRIBUTE_1_NAME, Operators.EQUAL, ATTRIBUTE_1_VALUE)); rule1.setDecision(CONDITION_1_NAME); rule1.setProbability(CONDITION_1_PROBABILITY); rules.add(rule1); return rules; } private DiagnosisCoreData prepareSimpleData() { DiagnosisCoreData data = new DiagnosisCoreData(); CoreDataPiece dataPiece1 = new CoreDataPiece(); dataPiece1.setName(ATTRIBUTE_1_NAME); dataPiece1.setValue(ATTRIBUTE_1_VALUE); data.addDataPiece(dataPiece1); return data; } private List<DiagnosisCoreRule> prepareComplexRules() { List<DiagnosisCoreRule> rules = new ArrayList<DiagnosisCoreRule>(); DiagnosisCoreRule rule1 = new DiagnosisCoreRule(); AndContainer mainExpression = new AndContainer(); mainExpression.addExpression(getSimpleExpression(ATTRIBUTE_1_NAME, Operators.EQUAL, ATTRIBUTE_1_VALUE)); OrContainer internalExpression = new OrContainer(); internalExpression.addExpression(getSimpleExpression(ATTRIBUTE_2_NAME, Operators.EQUAL, ATTRIBUTE_2_VALUE)); internalExpression.addExpression(getSimpleExpression(ATTRIBUTE_3_NAME, Operators.EQUAL, ATTRIBUTE_3_VALUE)); rule1.setExpression(mainExpression); rule1.setDecision(CONDITION_1_NAME); rule1.setProbability(CONDITION_1_PROBABILITY); rules.add(rule1); DiagnosisCoreRule rule2 = new DiagnosisCoreRule(); rule2.setExpression(getSimpleExpression(ATTRIBUTE_2_NAME, Operators.EQUAL, ATTRIBUTE_2_VALUE)); rule2.setDecision(CONDITION_2_NAME); rule2.setProbability(CONDITION_2_PROBABILITY); rules.add(rule2); return rules; } private DiagnosisCoreData prepareComplexData() { DiagnosisCoreData data = new DiagnosisCoreData(); CoreDataPiece dataPiece1 = new CoreDataPiece(); dataPiece1.setName(ATTRIBUTE_1_NAME); dataPiece1.setValue(ATTRIBUTE_1_VALUE); data.addDataPiece(dataPiece1); return data; } private SimpleExpression getSimpleExpression(String name, Operators operator, String value) { SimpleExpression expression = new SimpleExpression(); expression.setAttributeName(name); expression.setOperator(operator); expression.setValue(value); return expression; } private CoreDataPiece getSampleCoreDataPiece(String name, String value) { CoreDataPiece dataPiece = new CoreDataPiece(); dataPiece.setName(name); dataPiece.setValue(value); return dataPiece; } }
PHP
UTF-8
1,239
2.5625
3
[]
no_license
<?php namespace Svbk\WP\Log\Hook; class Post { public $id = 'post'; public static function setup() { add_action( 'wp_insert_post', array( __CLASS__, 'insert_post' ), 100, 3 ); } public static function edit_post( $post_ID, $post ) { do_action( 'log', 'info', 'User {user_id} Updated post: {post_id}/{post_title}', array( 'post_id' => $post_ID, 'post_title' => $post->post_title, 'source' => 'wordpress.post', ) ); } public static function insert_post( $post_ID, $post, $update ) { $context = array( 'post_id' => $post_ID, 'post_title' => $post->post_title, 'post_type' => $post->post_type, 'source' => 'wordpress.post', ); if ( wp_is_post_autosave( $post ) ) { do_action( 'log', 'debug', 'User {user_login} autosave for post: {post_id}/{post_title}', $context ); return; } if ( wp_is_post_revision( $post ) ) { do_action( 'log', 'info', 'User {user_login} created revision for post: {post_id}/{post_title}', $context ); } elseif ( $update ) { do_action( 'log', 'info', 'User {user_login} updated post: {post_id}/{post_title}', $context ); } else { do_action( 'log', 'info', 'User {user_login} created post: {post_id}/{post_title}', $context ); } } }
C
UTF-8
714
3.03125
3
[]
no_license
#include <stdio.h> #define MAX 1000 void digit (int a) { putchar (a+(a<10?48:55)); } int n; void number (int a, int base) { n=1; while (base<a/n+1) n*=base; while (n) { digit (a/n); a%=n; n/=base; } } void puts (char *string) { while (*string) putchar (*string++); putchar (13); putchar (10); } int i; int j; char *table; char *p; char *title="Crivo de Eratostenes"; void main () { puts (title); table=(char *) malloc (MAX); p=table; for (i=0; i<MAX; i++) *p++=1; for (i=2; i<MAX; i++) { if (table[i]) { number (i,10); putchar (','); for (j=i<<1; j<MAX; j+=i) table[j]=0; } } }
Markdown
UTF-8
743
3
3
[ "MIT" ]
permissive
--- layout: post title: First blog post --- This feels like tradition so I'm going to just modify the existing text and not change the title. I want to write a blog because I think (\emph{think}) that I have _something_ to say that interests people. This _something _may have something to do with **baking**, or with programming robots using the Robot Operating System (**[ROS](http://www.ros.org/)**), or it may just be a general rant about **programming**, **Linux**, or **life**. I had an old blog about baking ([Tandoori Spring](http://tandoorispring.wordpress.com)) that unfortunately went nowhere after two posts. Hopefully this time it'll be different. Stay tuned, though I do not really expect anyone to start reading for a while :)
Python
UTF-8
453
2.890625
3
[]
no_license
# -*- coding:utf-8 -*- # 判断'redata.txt'是否有数据损坏 import re with open('redata.txt', 'r') as f: for line_data in f: m = re.match( r'^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s{1,2}\d{1,2}\s\d{2}\:\d{2}\:\d{2}\s\w+', line_data) if m is not None: print 'data integrity!' else: print 'data corruption! data:%s' % line_data
PHP
UTF-8
1,061
3.375
3
[]
no_license
<?php // Stores classes for use on the global scale. namespace ApexDevelopment\PHP; class ClassRegistry { // The instance of the class, if it exists. private static $instance = null; // Container for all classes. private $objs = []; // Empty constructor so class can only be instantiated once. private function __construct() { } // Creates an instance if there isn't one, and returns it. public static function singleton() { if (static::$instance == null) { static::$instance = new static(); } return static::$instance; } // Adds class to container. public function push($obj) { $ref = new \ReflectionClass($obj); if (isset($this -> objs[$ref -> getShortName()])) { unset($obj); return $this -> pull($ref -> getShortName()); } $this -> objs[$ref -> getShortName()] = &$obj; return $this -> objs[$ref -> getShortName()]; } public function pull($obj) { if (isset($this -> objs[$obj])) { return $this -> objs[$obj]; } return 0; } }
Swift
UTF-8
1,223
2.625
3
[]
no_license
// // GoalServices.swift // Adidas // // Created by BOLD on 09/01/2020. // Copyright © 2020 BOLD. All rights reserved. // import RealmSwift class GoalServices { class func getGoalsList(successBlock:@escaping (_ result: [GoalViewModel]) -> Void, errorBlock:@escaping (_ error: Error) -> Void){ if !Connectivity.isConnectedToInternet { do { let realm = try Realm() let result = Array(realm.objects(Goal.self)) let items = toViewModel(goals: result) successBlock(items) } catch let error { errorBlock(error) } return } NetworkService.shared.getGoalsList(successBlock: { (goals) in do { let realm = try Realm() try realm.write { realm.add(goals) } } catch let error as NSError { print("error saving data: \(error.localizedDescription)") } let items = toViewModel(goals: goals) successBlock(items) }) { (error) in errorBlock(error) } } }
Java
ISO-8859-1
3,648
2.46875
2
[ "MIT" ]
permissive
package com.ademarazn.bdescola; import android.app.Activity; import android.app.AlertDialog; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v4.widget.SimpleCursorAdapter; import android.view.View; import android.widget.EditText; import android.widget.ListView; public class MainActivity extends Activity { // nome do banco que ser manipulado String nomeBanco = "bdescola"; // variavel para manipular cdigo SQL SQLiteDatabase bancoDados = null; EditText edtNome; EditText edtFone; EditText edtCurso; ListView mostraDados; Cursor cursor; // para manipular os dados // lista a ser preenchida SimpleCursorAdapter adapterLista; // campo da tabela que ir aparecer public static final String NOME = "nome"; public static final String FONE = "fone"; public static final String CURSO = "curso"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtNome = (EditText) findViewById(R.id.edtNome); edtFone = (EditText) findViewById(R.id.edtFone); edtCurso = (EditText) findViewById(R.id.edtCurso); /* * mostraDados.setOnItemClickListener(new )(new View.OnClickListener() { * * @Override public void onClick(View arg0) { Integer sel = * mostraDados.getCheckedItemPosition(); mensagemAlerta("Telefone: " + * cursor.getString(sel)); } }); */ criaBanco(); carregaDado(); } @SuppressWarnings("deprecation") public void criaBanco() { try { bancoDados = openOrCreateDatabase(nomeBanco, MODE_WORLD_READABLE, null); String sql = "CREATE TABLE IF NOT EXISTS " + "tabalunos " + "(_id INTEGER PRIMARY KEY, " + "nome TEXT, fone TEXT, curso TEXT)"; bancoDados.execSQL(sql); mensagemAlerta("Banco de dados criado/aberto com sucesso"); } catch (SQLException e) { mensagemAlerta("Erro no Banco! " + e); } } public void mensagemAlerta(String msg) { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle("Banco de Dados"); dialog.setMessage(msg); dialog.setNegativeButton("OK", null); dialog.show(); } @SuppressWarnings("deprecation") public void gravarBanco() { try { bancoDados = openOrCreateDatabase(nomeBanco, MODE_WORLD_READABLE, null); String sql = "INSERT INTO tabalunos " + "(nome,fone,curso) " + "values ('" + edtNome.getText().toString() + "'" + ",'" + edtFone.getText().toString() + "'" + ",'" + edtCurso.getText().toString() + "')"; bancoDados.execSQL(sql); mensagemAlerta("Gravado com sucesso!"); } catch (Exception e) { mensagemAlerta("Erro ao gravar. " + e); } } public boolean verificaRegistro() { String sql = "SELECT * FROM tabalunos"; cursor = bancoDados.rawQuery(sql, null); return cursor.moveToFirst(); } @SuppressWarnings("deprecation") public void carregaDado() { mostraDados = (ListView) findViewById(R.id.listaDados); if (verificaRegistro()) { String[] coluna = new String[] { NOME, FONE, CURSO }; adapterLista = new SimpleCursorAdapter(this, R.layout.mostrabanco, cursor, coluna, new int[] { R.id.nome, R.id.fone, R.id.curso }); mostraDados.setAdapter(adapterLista); } else { mensagemAlerta("No h Registros"); } } public void salvar(View v) { if (!edtNome.getText().toString().trim().isEmpty() && !edtFone.getText().toString().trim().isEmpty() && !edtCurso.getText().toString().trim().isEmpty()) { gravarBanco(); carregaDado(); } else { mensagemAlerta("H campos em branco!"); } } }
Swift
UTF-8
1,623
2.984375
3
[]
no_license
// // ViewController.swift // MakeSchoolNotes // // Created by Martin Walsh on 29/05/2015. // Copyright (c) 2015 MakeSchool. All rights reserved. // import UIKit import RealmSwift class NotesViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var notes: Results<Note>! { didSet { // whenever notes update, update the table view tableView?.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let myNote = Note() myNote.title = "Super Simple Test Note" myNote.content = "A long piece of content" let realm = Realm() // 1 realm.write() { // 2 realm.add(myNote) // 3 } notes = realm.objects(Note) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension NotesViewController: UITableViewDataSource { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("NoteCell", forIndexPath: indexPath) as! NoteTableViewCell //1 let row = indexPath.row let note = notes[row] as Note cell.note = note return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Int(notes?.count ?? 0) } }
Java
UTF-8
896
2.390625
2
[]
no_license
package com.example.forager.Misc; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.example.forager.Activities.SettingsActivity; public class CustomReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String broadcastMessage = "Unknown intent action"; String intentAction = intent.getAction(); if( intentAction.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED) ) broadcastMessage = "System Broadcast Message: Airplane Mode has been changed"; else if( intentAction.equals(SettingsActivity.CUSTOM_ACTION_BROADCAST_THEME_CHANGED) ) broadcastMessage = "Custom Broadcast Message: Theme has been changed"; Toast.makeText(context, broadcastMessage, Toast.LENGTH_SHORT).show(); } }
Java
UTF-8
683
3.734375
4
[]
no_license
package Chapter2_1_ElementarySorts; /* * Deck sort. Explain how you would put a deck of cards in orders by suit(in the order spades, hearts, clubs,diamonds) * and by rank within each suit, with the restriction that the cards must be laid out face down in a row, and the only * allowed operations are to check the values of two cards and to exchange two cards(keeping them face down). * * */ public class Ex2_1_13 { public static void deckSort(Comparable[] deck){ int N = deck.length; int h = 1; while (h < N / 3){ h = h * 3 + 1; } while (h >= 1){ for (int i = h; i < N; i++){ } } } }
Java
UTF-8
346
3.4375
3
[]
no_license
package creational.factory.abstractfactory.autos; public abstract class BMWBase implements Auto { @Override public void turnOn() { System.out.println(name() + " is on and running."); } @Override public void turnOff() { System.out.println(name() + " is off."); } protected abstract String name(); }
Java
UTF-8
20,401
1.859375
2
[]
no_license
/* This file is part of Brewzor. Copyright (C) 2010 James Whiddon Brewzor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Brewzor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Brewzor. If not, see <http://www.gnu.org/licenses/>. */ package com.brewzor.calculator; import com.brewzor.calculator.preferences.Preferences; import com.brewzor.calculator.R; import com.brewzor.converters.BeerColor; import com.brewzor.converters.Distance; import com.brewzor.converters.Gravity; import com.brewzor.converters.Mass; import com.brewzor.converters.Pressure; import com.brewzor.converters.Temperature; import com.brewzor.converters.Volume; import com.brewzor.utils.NumberFormat; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.Preference.OnPreferenceChangeListener; import android.widget.Toast; public class BrewzorPreferencesActivity extends PreferenceActivity { private Preference pref; private SharedPreferences sPref; private SharedPreferences.Editor editor; private Volume volume; private Gravity gravity; private Mass mass; private Temperature temperature; private Distance distance; private Pressure pressure; private BeerColor color; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); sPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); editor = sPref.edit(); volume = new Volume(0, Volume.Unit.GALLON, getBaseContext(), sPref); gravity = new Gravity(0, Gravity.Unit.SG, getBaseContext(), sPref); mass = new Mass(0, Mass.Unit.GRAM, getBaseContext(), sPref); temperature = new Temperature(0, Temperature.Unit.FAHRENHEIT, getBaseContext(), sPref); distance = new Distance(0, Distance.Unit.INCH, getBaseContext(), sPref); pressure = new Pressure(0, Pressure.Unit.PSI, getBaseContext(), sPref); color = new BeerColor(0, BeerColor.Unit.SRM, getBaseContext(), sPref); pref = findPreference(Preferences.GLOBAL_UNIT_CHANGE); pref.setOnPreferenceChangeListener(mUnitChangeListener); pref = findPreference(Preferences.GLOBAL_TEMPERATURE_UNIT); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.GLOBAL_GRAVITY_UNIT); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.GLOBAL_BEER_COLOR_UNIT); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.GLOBAL_REFRACTOMETER_CORRECTION_FACTOR); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.GLOBAL_EXTRACT_MASS_UNIT); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.GLOBAL_HYDROMETER_CALIBRATION_TEMPERATURE); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.GLOBAL_PRESSURE_UNIT); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.BATCH_VOLUME_UNIT); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.BATCH_MASH_VOLUME_UNIT); pref.setOnPreferenceChangeListener(mMashVolumeUnitPrefListener); pref = findPreference(Preferences.BATCH_FINAL_VOLUME); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.BATCH_GRAIN_MASS_UNIT); pref.setOnPreferenceChangeListener(mGrainMassUnitPrefListener); pref = findPreference(Preferences.BATCH_WATER_TO_GRAIN_RATIO); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.BATCH_MASH_MINUTES); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.BATCH_BOIL_MINUTES); pref.setOnPreferenceChangeListener(mPrefListener); /* // not yet implemented pref = findPreference(Preferences.BATCH_GRAIN_ABSORPTION_RATIO); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.BATCH_GRAIN_VOLUME_RATIO); pref.setOnPreferenceChangeListener(mPrefListener); */ pref = findPreference(Preferences.BATCH_INFUSION_WATER_TEMPERATURE); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.KETTLE_DISTANCE_UNIT); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.KETTLE_DIAMETER); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.KETTLE_FALSE_BOTTOM_HEIGHT); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.KETTLE_EVAPORATION_RATE); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.KETTLE_EVAPORATION_RATE); pref.setOnPreferenceChangeListener(mPrefListener); pref = findPreference(Preferences.KETTLE_EQUIPMENT_LOSS); pref.setOnPreferenceChangeListener(mPrefListener); } private void updateList() { pref = findPreference(Preferences.GLOBAL_TEMPERATURE_UNIT); temperature.setType(temperature.typeFromPref(Preferences.GLOBAL_TEMPERATURE_UNIT, Temperature.Unit.FAHRENHEIT)); pref.setSummary(temperature.getLabelPlural()); pref = findPreference(Preferences.GLOBAL_GRAVITY_UNIT); gravity.setType(gravity.typeFromPref(Preferences.GLOBAL_GRAVITY_UNIT, Gravity.Unit.SG)); pref.setSummary(gravity.getLabelPlural()); pref = findPreference(Preferences.GLOBAL_BEER_COLOR_UNIT); color.setType(color.typeFromPref(Preferences.GLOBAL_BEER_COLOR_UNIT, BeerColor.Unit.SRM)); pref.setSummary(color.getLabelPlural()); pref = findPreference(Preferences.GLOBAL_REFRACTOMETER_CORRECTION_FACTOR); pref.setSummary(getString(R.string.refractometer_correction_factor_pref_format, sPref.getString(Preferences.GLOBAL_REFRACTOMETER_CORRECTION_FACTOR, "1.04"), volume.getLabelPlural())); pref = findPreference(Preferences.GLOBAL_EXTRACT_MASS_UNIT); mass.setType(mass.typeFromPref(Preferences.GLOBAL_EXTRACT_MASS_UNIT, Mass.Unit.OUNCE)); pref.setSummary(mass.getLabelPlural()); pref = findPreference(Preferences.GLOBAL_HYDROMETER_CALIBRATION_TEMPERATURE); mass.setType(mass.typeFromPref(Preferences.GLOBAL_HYDROMETER_CALIBRATION_TEMPERATURE, Mass.Unit.OUNCE)); pref.setSummary(mass.getLabelPlural()); pref = findPreference(Preferences.GLOBAL_HYDROMETER_CALIBRATION_TEMPERATURE); pref.setSummary(getString(R.string.hydrometer_calibration_temperature_pref_summary_format, sPref.getString(Preferences.GLOBAL_HYDROMETER_CALIBRATION_TEMPERATURE, "60"), temperature.getLabelAbbr())); pref = findPreference(Preferences.GLOBAL_PRESSURE_UNIT); pressure.setType(pressure.typeFromPref(Preferences.GLOBAL_PRESSURE_UNIT, Pressure.Unit.PSI)); pref.setSummary(pressure.getLabelPlural()); pref = findPreference(Preferences.BATCH_VOLUME_UNIT); volume.setType(volume.typeFromPref(Preferences.BATCH_VOLUME_UNIT, Volume.Unit.GALLON)); pref.setSummary(volume.getLabelPlural()); pref = findPreference(Preferences.BATCH_FINAL_VOLUME); pref.setSummary(sPref.getString(Preferences.BATCH_FINAL_VOLUME, "6.00") + " " + volume.getLabelPlural()); pref = findPreference(Preferences.BATCH_MASH_VOLUME_UNIT); volume.setType(volume.typeFromPref(Preferences.BATCH_MASH_VOLUME_UNIT, Volume.Unit.GALLON)); pref.setSummary(volume.getLabelPlural()); pref = findPreference(Preferences.BATCH_GRAIN_MASS_UNIT); mass.setType(mass.typeFromPref(Preferences.BATCH_GRAIN_MASS_UNIT, Mass.Unit.POUND)); pref.setSummary(mass.getLabelPlural()); pref = findPreference(Preferences.BATCH_WATER_TO_GRAIN_RATIO); volume.setType(volume.typeFromPref(Preferences.BATCH_MASH_VOLUME_UNIT, Volume.Unit.GALLON)); pref.setSummary(getString(R.string.water_to_grain_ratio_pref_summary_format, sPref.getString(Preferences.BATCH_WATER_TO_GRAIN_RATIO, ".31"), volume.getLabelPlural(), mass.getLabel())); pref = findPreference(Preferences.BATCH_MASH_MINUTES); pref.setSummary(sPref.getString(Preferences.BATCH_MASH_MINUTES, "60")); pref = findPreference(Preferences.BATCH_BOIL_MINUTES); pref.setSummary(sPref.getString(Preferences.BATCH_BOIL_MINUTES, "60")); /* pref = findPreference(Preferences.BATCH_GRAIN_ABSORPTION_RATIO); pref.setSummary(sPref.getString(Preferences.BATCH_GRAIN_ABSORPTION_RATIO, ".13")); pref = findPreference(Preferences.BATCH_GRAIN_VOLUME_RATIO); pref.setSummary(sPref.getString(Preferences.BATCH_GRAIN_VOLUME_RATIO, ".08")); */ pref = findPreference(Preferences.BATCH_INFUSION_WATER_TEMPERATURE); pref.setSummary(sPref.getString(Preferences.BATCH_INFUSION_WATER_TEMPERATURE, "212") + " " + temperature.getLabelAbbr()); pref = findPreference(Preferences.KETTLE_DISTANCE_UNIT); distance.setType(distance.typeFromPref(Preferences.KETTLE_DISTANCE_UNIT, Distance.Unit.INCH)); pref.setSummary(distance.getLabelPlural()); pref = findPreference(Preferences.KETTLE_DIAMETER); pref.setSummary(sPref.getString(Preferences.KETTLE_DIAMETER, "0.00") + " " + distance.getLabelPlural()); pref = findPreference(Preferences.KETTLE_FALSE_BOTTOM_HEIGHT); pref.setSummary(sPref.getString(Preferences.KETTLE_FALSE_BOTTOM_HEIGHT, "0.00") + " " + distance.getLabelPlural()); pref = findPreference(Preferences.KETTLE_EVAPORATION_RATE); pref.setSummary(sPref.getString(Preferences.KETTLE_EVAPORATION_RATE, "10") + "%"); pref = findPreference(Preferences.KETTLE_COOLING_LOSS); pref.setSummary(sPref.getString(Preferences.KETTLE_COOLING_LOSS, "4") + "%"); pref = findPreference(Preferences.KETTLE_EQUIPMENT_LOSS); volume.setType(volume.typeFromPref(Preferences.BATCH_VOLUME_UNIT, Volume.Unit.GALLON)); pref.setSummary(getString(R.string.equipment_loss_pref_summary_format, sPref.getString(Preferences.KETTLE_EQUIPMENT_LOSS, "0"), volume.getLabelPlural())); } @Override public void onResume() { super.onResume(); updateList(); } private OnPreferenceChangeListener mMashVolumeUnitPrefListener = new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, java.lang.Object newValue) { volume.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.BATCH_WATER_TO_GRAIN_RATIO, "1"), 1)); volume.setType(volume.typeFromPref(Preferences.BATCH_MASH_VOLUME_UNIT, Volume.Unit.GALLON)); editor.putString(preference.getKey(), newValue.toString()); editor.commit(); volume.convert(volume.typeFromPref(Preferences.BATCH_MASH_VOLUME_UNIT, Volume.Unit.GALLON)); editor.putString(Preferences.BATCH_WATER_TO_GRAIN_RATIO, volume.toString()); editor.commit(); updateList(); return true; } }; private OnPreferenceChangeListener mGrainMassUnitPrefListener = new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, java.lang.Object newValue) { volume.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.BATCH_WATER_TO_GRAIN_RATIO, "1"), 1)); volume.setType(volume.typeFromPref(Preferences.BATCH_MASH_VOLUME_UNIT, Volume.Unit.GALLON)); mass.setValue(1); mass.setType(mass.typeFromPref(Preferences.BATCH_GRAIN_MASS_UNIT, Mass.Unit.POUND)); editor.putString(preference.getKey(), newValue.toString()); editor.commit(); volume.convert(volume.typeFromPref(Preferences.BATCH_MASH_VOLUME_UNIT, Volume.Unit.GALLON)); mass.convert(mass.typeFromPref(Preferences.BATCH_GRAIN_MASS_UNIT, Mass.Unit.POUND)); volume.setValue(volume.getValue() / mass.getValue()); editor.putString(Preferences.BATCH_WATER_TO_GRAIN_RATIO, volume.toString()); editor.commit(); updateList(); return true; } }; private OnPreferenceChangeListener mPrefListener = new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, java.lang.Object newValue) { editor.putString(preference.getKey(), newValue.toString()); editor.commit(); updateList(); return true; } }; private OnPreferenceChangeListener mUnitChangeListener = new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, java.lang.Object newValue) { if ("US".equals(newValue.toString()) && "METRIC".equals(sPref.getString(Preferences.GLOBAL_UNIT_CHANGE, "US"))) { volume.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.BATCH_FINAL_VOLUME, "0"), 0)); volume.setType(volume.typeFromPref(Preferences.BATCH_VOLUME_UNIT, Volume.Unit.LITER)); volume.convert(Volume.Unit.GALLON); editor.putString(Preferences.BATCH_FINAL_VOLUME, volume.toString()); volume.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.BATCH_WATER_TO_GRAIN_RATIO, "1"), 1)); volume.setType(volume.typeFromPref(Preferences.BATCH_MASH_VOLUME_UNIT, Volume.Unit.LITER)); mass.setValue(1); mass.setType(mass.typeFromPref(Preferences.BATCH_GRAIN_MASS_UNIT, Mass.Unit.KILOGRAM)); volume.convert(Volume.Unit.GALLON); mass.convert(Mass.Unit.POUND); volume.setValue(volume.getValue() / mass.getValue()); editor.putString(Preferences.BATCH_WATER_TO_GRAIN_RATIO, volume.toString()); temperature.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.BATCH_INFUSION_WATER_TEMPERATURE, "0"), 0)); temperature.setType(temperature.typeFromPref(Preferences.GLOBAL_TEMPERATURE_UNIT, Temperature.Unit.CELSIUS)); temperature.convert(Temperature.Unit.FAHRENHEIT); editor.putString(Preferences.BATCH_INFUSION_WATER_TEMPERATURE, temperature.toString()); distance.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.KETTLE_DIAMETER, "0"), 0)); distance.setType(distance.typeFromPref(Preferences.KETTLE_DISTANCE_UNIT, Distance.Unit.CENTIMETER)); distance.convert(Distance.Unit.INCH); editor.putString(Preferences.KETTLE_DIAMETER, distance.toString()); distance.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.KETTLE_FALSE_BOTTOM_HEIGHT, "0"), 0)); distance.setType(distance.typeFromPref(Preferences.KETTLE_DISTANCE_UNIT, Distance.Unit.CENTIMETER)); distance.convert(Distance.Unit.INCH); editor.putString(Preferences.KETTLE_FALSE_BOTTOM_HEIGHT, distance.toString()); volume.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.KETTLE_EQUIPMENT_LOSS, "0"), 0)); volume.setType(volume.typeFromPref(Preferences.BATCH_VOLUME_UNIT, Volume.Unit.LITER)); volume.convert(Volume.Unit.GALLON); editor.putString(Preferences.KETTLE_EQUIPMENT_LOSS, volume.toString()); temperature.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.GLOBAL_HYDROMETER_CALIBRATION_TEMPERATURE, "60"), 60)); temperature.setType(temperature.typeFromPref(Preferences.GLOBAL_TEMPERATURE_UNIT, Temperature.Unit.CELSIUS)); temperature.convert(Temperature.Unit.FAHRENHEIT); editor.putString(Preferences.GLOBAL_HYDROMETER_CALIBRATION_TEMPERATURE, temperature.toString()); editor.putString(Preferences.GLOBAL_TEMPERATURE_UNIT, "FAHRENHEIT"); editor.putString(Preferences.GLOBAL_GRAVITY_UNIT, "SG"); editor.putString(Preferences.GLOBAL_BEER_COLOR_UNIT, "SRM"); editor.putString(Preferences.GLOBAL_EXTRACT_MASS_UNIT, "OUNCE"); editor.putString(Preferences.GLOBAL_PRESSURE_UNIT, "PSI"); editor.putString(Preferences.BATCH_VOLUME_UNIT, "GALLON"); editor.putString(Preferences.BATCH_MASH_VOLUME_UNIT, "GALLON"); editor.putString(Preferences.BATCH_GRAIN_MASS_UNIT, "POUND"); editor.putString(Preferences.KETTLE_DISTANCE_UNIT, "INCH"); } else if ("METRIC".equals(newValue.toString()) && "US".equals(sPref.getString(Preferences.GLOBAL_UNIT_CHANGE, "METRIC"))) { volume.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.BATCH_FINAL_VOLUME, "0"), 0)); volume.setType(volume.typeFromPref(Preferences.BATCH_VOLUME_UNIT, Volume.Unit.GALLON)); volume.convert(Volume.Unit.LITER); editor.putString(Preferences.BATCH_FINAL_VOLUME, volume.toString()); volume.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.BATCH_WATER_TO_GRAIN_RATIO, "1"), 1)); volume.setType(volume.typeFromPref(Preferences.BATCH_MASH_VOLUME_UNIT, Volume.Unit.GALLON)); mass.setValue(1); mass.setType(mass.typeFromPref(Preferences.BATCH_GRAIN_MASS_UNIT, Mass.Unit.POUND)); volume.convert(Volume.Unit.LITER); mass.convert(Mass.Unit.KILOGRAM); volume.setValue(volume.getValue() / mass.getValue()); editor.putString(Preferences.BATCH_WATER_TO_GRAIN_RATIO, volume.toString()); temperature.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.BATCH_INFUSION_WATER_TEMPERATURE, "0"), 0)); temperature.setType(temperature.typeFromPref(Preferences.GLOBAL_TEMPERATURE_UNIT, Temperature.Unit.FAHRENHEIT)); temperature.convert(Temperature.Unit.CELSIUS); editor.putString(Preferences.BATCH_INFUSION_WATER_TEMPERATURE, temperature.toString()); distance.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.KETTLE_DIAMETER, "0"), 0)); distance.setType(distance.typeFromPref(Preferences.KETTLE_DISTANCE_UNIT, Distance.Unit.INCH)); distance.convert(Distance.Unit.CENTIMETER); editor.putString(Preferences.KETTLE_DIAMETER, distance.toString()); distance.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.KETTLE_FALSE_BOTTOM_HEIGHT, "0"), 0)); distance.setType(distance.typeFromPref(Preferences.KETTLE_DISTANCE_UNIT, Distance.Unit.INCH)); distance.convert(Distance.Unit.CENTIMETER); editor.putString(Preferences.KETTLE_FALSE_BOTTOM_HEIGHT, distance.toString()); volume.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.KETTLE_EQUIPMENT_LOSS, "0"), 0)); volume.setType(volume.typeFromPref(Preferences.BATCH_VOLUME_UNIT, Volume.Unit.GALLON)); volume.convert(Volume.Unit.LITER); editor.putString(Preferences.KETTLE_EQUIPMENT_LOSS, volume.toString()); temperature.setValue(NumberFormat.parseDouble(sPref.getString(Preferences.GLOBAL_HYDROMETER_CALIBRATION_TEMPERATURE, "60"), 60)); temperature.setType(temperature.typeFromPref(Preferences.GLOBAL_TEMPERATURE_UNIT, Temperature.Unit.FAHRENHEIT)); temperature.convert(Temperature.Unit.CELSIUS); editor.putString(Preferences.GLOBAL_HYDROMETER_CALIBRATION_TEMPERATURE, temperature.toString()); editor.putString(Preferences.GLOBAL_TEMPERATURE_UNIT, "CELSIUS"); editor.putString(Preferences.GLOBAL_GRAVITY_UNIT, "SG"); editor.putString(Preferences.GLOBAL_BEER_COLOR_UNIT, "EBC"); editor.putString(Preferences.GLOBAL_PRESSURE_UNIT, "KPA"); editor.putString(Preferences.BATCH_VOLUME_UNIT, "LITER"); editor.putString(Preferences.BATCH_MASH_VOLUME_UNIT, "LITER"); editor.putString(Preferences.BATCH_GRAIN_MASS_UNIT, "KILOGRAM"); editor.putString(Preferences.KETTLE_DISTANCE_UNIT, "CENTIMETER"); editor.putString(Preferences.GLOBAL_EXTRACT_MASS_UNIT, "GRAM"); } editor.putString(preference.getKey(), newValue.toString()); //TODO: don't know how to update the values stored in the listprefs and editprefs. // the values get saved, but if you click on the preference without reloading the activity // the original text is in there. ideally we'd skip the toast and finish() and just update the // preferences. Toast.makeText(getApplicationContext(), "Updating Measurement Units...", Toast.LENGTH_SHORT).show(); editor.commit(); finish(); //updateList(); return true; } }; }
C++
UTF-8
7,890
2.859375
3
[]
no_license
// // projectRunner.cpp // os // // Created by Zeke on 5/12/18. // Copyright © 2018 Zeke. All rights reserved. // #include "projectRunner.hpp" #include "SystemConfig.hpp" #include "Job.hpp" #include "HoldQ2.hpp" #include "HoldQ1.hpp" #include "Process.hpp" #include <string> #include <iostream> #include <fstream> #include <vector> #include <sstream> using namespace std; ProjectRunner::ProjectRunner(){ } string ProjectRunner::readFile(string fileName){ SystemConfig system; cout<<"Filename: " + fileName<<endl; ifstream myFile(fileName.c_str()); Process *runningJob; string line; vector<Job*>jobs; if(myFile.is_open()){ while (myFile >> line){ vector<string> lineSeparated; vector<int> commandValues; string lineSegment; char command = line[0]; switch (command) { //if the line is a system config case 'C':{ //read the next number myFile >> line; int arrivalTime = stoi(line); for(int properties = 0; properties < 3; properties++){ myFile >> line; //separates the Letter=Number string since there's no clean way to do it in c++... stringstream lineToSeparate(line); while(getline(lineToSeparate, lineSegment, '=')){ lineSeparated.push_back(lineSegment); } int value = stoi(lineSeparated[1]); commandValues.push_back(value); lineSeparated.clear(); } //make a new system system = SystemConfig(arrivalTime, commandValues[0], commandValues[1], commandValues[2]); system.hq1 = new HoldQ1(); system.hq2 = new HoldQ2(); break; } //if the line is a job case 'A': { //read the next number myFile >> line; int arrivalTime = stoi(line); for(int properties = 0; properties < 5; properties++){ myFile >> line; //separates the Letter=Number string since there's no clean way to do it in c++... stringstream lineToSeparate(line); while(getline(lineToSeparate, lineSegment, '=')){ lineSeparated.push_back(lineSegment); } int value = stoi(lineSeparated[1]); lineSeparated.clear(); commandValues.push_back(value); } Job *job = new Job(arrivalTime, commandValues[0], commandValues[1], commandValues[2], commandValues[3], commandValues[4]); if(job->getPriority() == 2 && (system.getAvailableMem() > job->getUnitsOfMem() && system.getAvailableDevices() > job->getMaxDevices())){//if there's avaialble memeory and devies?, push to the rq system.useMem(job->getUnitsOfMem()); system.useDevices(job->getMaxDevices()); Process *proc = new Process(job, system.getTime()); system.rq.push_back(proc); jobs.push_back(job); } else if(job->getPriority() == 2 && (system.getMemSize() > job->getUnitsOfMem())) {//push to the hold queue 2 system.hq2->insert(job); jobs.push_back(job); } else if(job->getPriority() == 1 && (system.getAvailableMem() > job->getUnitsOfMem() && system.getAvailableDevices() > job->getMaxDevices())) {// cout<<"push to q1"<<endl; system.useMem(job->getUnitsOfMem()); system.useDevices(job->getMaxDevices()); Process *proc = new Process(job, system.getTime()); system.rq.push_back(proc); jobs.push_back(job); } else if(job->getPriority() == 1 && (system.getMemSize() > job->getUnitsOfMem())) { system.hq1->insertJob(job); jobs.push_back(job); } else {//reject the job if it's memory is too big for the system cout<<"reject job"<<endl; } system.updateSystem(arrivalTime); break; } //if the line is a request case 'Q': { myFile >> line; int arrivalTime = stoi(line); for(int properties = 0; properties < 2; properties++){ myFile >> line; //separates the Letter=Number string since there's no clean way to do it in c++... } system.updateSystem(arrivalTime); break; } //if the line is a display command case 'D':{ myFile >> line; int displayTime = stoi(line); cout<<"Current Time: "; cout<< displayTime<<endl; system.updateSystem(displayTime); cout<<"rq: "; int rqSize = system.rq.size(); for(int i = 0; i < rqSize; i++){ if(i != rqSize - 1){ cout<<"id: " + to_string(system.rq.at(i)->job->getId()) + " Time remaining: " + to_string(system.rq.at(i)->job->getUnitsOfTime()) + " , "; } else { cout<<"id: " + to_string(system.rq.at(i)->job->getId()) + " Time remaining: " + to_string(system.rq.at(i)->job->getUnitsOfTime()); } } cout<<endl; cout<<"Total mem: " + to_string(system.getMemSize())<<endl; cout<<"Available mem: " + to_string(system.getAvailableMem())<<endl; cout<<"Total Devices: " + to_string(system.getDevices())<<endl; cout<<"Available devices: " + to_string(system.getAvailableDevices())<<endl; cout<<"Running: " ; if(system.running == NULL){ cout<<" "<<endl; } else { cout<<system.running->job->getId()<<endl; } cout<<"q1: "; system.hq1->printJobs(); cout<<"q2: "; system.hq2->print(); cout<<"cq: "; if(system.cq.size() > 0){ cout<<system.cq.at(0)->getId()<<endl; } else { cout<< "[]"<<endl; } cout<<"Quantum: "; cout<<system.getQuantum()<<endl; cout<<"---------------------"<<endl; if(displayTime == 9999){ myFile.close(); return "done"; } break; } //if the line is a release request case 'L': { break; } default: { cout<<"error reading a line!"<<endl; break; } } } return "done"; } else { return "error reading file"; } }
Markdown
UTF-8
679
2.53125
3
[]
no_license
# KeyStream This is most likely a terrible idea, but here goes. An agent application will run on a computer and register back with an eureka server. This agent will enable remote users to simulate mouse movement, mouse clicks, mouse wheel and keystrokes. Remote users will be able to access a listing of all available agents. They can acquire a connection to an agent and take control of the machine as they feel necessary. Should probably just use VNC/RDP/TeamViewer/etc. # Usage The modules are all based of Spring-Boot, they must be started in a specific order: 1. configuration 1. discovery 1. agent To start a module run `mvn spring-boot:run` from its directory.
Markdown
UTF-8
3,781
2.765625
3
[]
no_license
# Solid application data discovery (Draft) The following describes application data discovery in the Solid framework using HTTP link following aka "follow your nose". This should not be confused with [application preferences/configuration discovery] (https://github.com/solid/solid/tree/master/proposals/app-discovery.md). ## Starting point -- WebID ### Fetching the Profile The public profile is what you get when you look up someone's WebID directly. Strip off any hash and local id (i.e. #me) part. For example: ``` https://example.databox.me/profile/card#me -> https://example.databox.me/profile/card ``` The starting point of Solid application data discovery is a user's [WebID](http://www.w3.org/2005/Incubator/webid/spec/identity/), which is a hash based URI, typically denoting a (FOAF) Agent. From this profile the user's storage can be found (discovery). The Profile typically contains public name and contact information about someone, and pointers to public data used by various apps. When an application dereferences the public profile, it should also fetch any * owl:sameAs * rdfs:seeAlso * space:preferencesFile links it finds in the public profile document. (one level deep) The preferencesFile is a private file that is linked from the main WebID profile, and contains miscellaneous data that does not belong in the public profile. In general, both the public profile and the preferencesFil will contain triples that share the same subject -- i.e the user's WebID. ## Discoverability Once a complete view of the profile has been created, applications will follow links to discover where relevant data is located in order to read and write data there. ### Type registry configuration The type registry is typically a document holding resources that register a specific resource type and map it to a location on the user's data space. **Note:** The Type Registry is mainly intended as a Library discovery mechanism. Recommend that coarse-grained library types are registered (usually types that match containers as opposed to every RDF Class written by an app) -- e.g. `vcard:AddressBook` and `sioc:Blog` as opposed to `vcard:Contact` and `sioc:Post`. A typical Solid account will have a private type index, where applications will register the top container type. For example, a contacts app will register the type `vcard:AddressBook` and the instance (or data location) as `/contacts/` in a new resource at `/settings/privateTypeIndex.ttl#ab09fd`. If the user decides it wants to make public that she is using a certain application, it can indicate this by registering the same type in a public index document at `/settings/publicTypeIndex.ttl#19da01`. Both registry documents will be linked to from the user's main profile (and from it, the preferences file): In the public profile: ``` <#me> space:TypeIndex </settings/publicTypeIndex.ttl>. ``` In the preferencesFile: ``` <#me> space:TypeIndex </settings/privateTypeIndex.ttl>. ``` The TypeIndex resource `/settings/privateTypeIndex.ttl` will contain things like: ``` <#ab09fd> a solid:TypeRegistration; solid:forClass vcard:AddressBook; solid:instance </contacts/>. ``` Optional: - An app may register a defaultApp URI when creating a data container. - When the user opens that container in the browser, a meshlib-like (thin) app can be loaded first, which in turns fetches the meta file and displays the registered app. ### Storage Discovery * Starting Point: WebID * Type: [pim : storage](http://www.w3.org/ns/pim/space#storage) For example, for a given WebID (https://example.databox.me/card#me), the corresponding storage location URI is https://example.databox.me/. ``` <#me> space:storage <.> . <http://www.w3.org/ns/pim/space#storage> <../> ; ```
C#
UTF-8
3,276
2.625
3
[]
no_license
// Credits to code by GamesplusJames https://www.youtube.com/user/gamesplusjames using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameManager : MonoBehaviour { public GameObject player1; public GameObject player2; public GameObject p1Wins; public GameObject p2Wins; public int P1hp; public int P2hp; public GameObject[] p1Bar; public GameObject[] p2Bar; public KeyCode scorekprShow; public KeyCode scorekprHide; public GameObject ScoreKeeper; // Update is called once per frame public void Update () { // 2 simple button presses to display or hide the ScoreKeeper object if (Input.GetKeyDown(scorekprShow)) { ScoreKeeper.SetActive(true); } if (Input.GetKeyDown(scorekprHide)) { ScoreKeeper.SetActive(false); } // Simple funktion to "kill" the player if hp(Health point) is less or equal to 0 if (P1hp <= 0) { player1.SetActive(false); // The object "player1" isn't destroyed, just hidden p2Wins.SetActive(true); // Activates a screen object in the Canvas displays } if (P2hp <= 0) { player2.SetActive(false); // Same structure as for player one p1Wins.SetActive(true); // Same as for p2Wins structure } } public void HurtP1() // These funktions are used in Weapon.cs { P1hp -= 1; // Takes away 1 value from decided value in unity (Can be set here aswell, just easier to work with values in unity) for(int i = 0; i < p1Bar.Length; i++) // Creates an list object without specific value. Decided in unity by adding objects to list { if (P1hp > i){ p1Bar[i].SetActive(true); //Activates the HPbar's hp values (light green boxes) }else { p1Bar[i].SetActive(false); // Each time P1 takes damage, one box deactivates } } } public void HurtP2() // Same function as above, just different names! { P2hp -= 1; for (int i = 0; i < p2Bar.Length; i++) { if (P2hp > i) { p2Bar[i].SetActive(true); } else { p2Bar[i].SetActive(false); } } } public void KillPlayer1() { P1hp = 0; } public void KillPlayer2() { P2hp = 0; } public void BtnPressRestart() // Resets each players position and Hp value, (Known issue: Boxes don't reactivate until taken one hit damage!) { player1.SetActive(true); // Reactivate player1 Vector3 player1Pos = new Vector3(-4, -10, 0); // Decides player1 starting position player1.transform.position = player1Pos; // Place player1 on starting position P1hp = 10; // Sets player1 hp back to 10 player2.SetActive(true); // Same as player1 Vector3 player2Pos = new Vector3(20, -8, 0); player2.transform.position = player2Pos; P2hp = 10; p1Wins.SetActive(false); //Deactivates victory screens p2Wins.SetActive(false); } }
Java
UTF-8
14,375
2.359375
2
[]
no_license
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright 2003-2007 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; import org.jivesoftware.smack.Connection.ListenerWrapper; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.sasl.SASLMechanism.Challenge; import org.jivesoftware.smack.sasl.SASLMechanism.Failure; import org.jivesoftware.smack.sasl.SASLMechanism.Success; import org.jivesoftware.smack.util.PacketParserUtils; import org.jivesoftware.smack.util.ThreadUtil; import org.jivesoftware.smack.util.XmlPullParserDom; import org.w3c.dom.Element; import org.xmlpull.v1.XmlPullParser; import java.util.concurrent.*; /** * Listens for XML traffic from the XMPP server and parses it into packet objects. * The packet reader also invokes all packet listeners and collectors.<p> * * @see Connection#createPacketCollector * @see Connection#addPacketListener * @author Matt Tucker */ class PacketReader { private Thread readerThread; private ExecutorService listenerExecutor; private XMPPConnection connection; private boolean done; protected PacketReader(final XMPPConnection connection) { this.connection = connection; done = false; } /** * Starts the packet reader thread and returns once a connection to the server * has been established. A connection will be attempted for a maximum of five * seconds. An XMPPException will be thrown if the connection fails. * * @throws XMPPException if the server fails to send an opening stream back * for more than five seconds. */ private Semaphore connectionSemaphore; private XMPPException connectionException; private void connectionEstablished() { connectionSemaphore.release(); } private void connectionEstablishError(XMPPException e) { connectionException = e; connectionSemaphore.release(); } /** * Start the reader thread, blocking until the transport is established. If * an exception is thrown, the caller must shut down the data stream to ensure * the reader thread exits, and call our shutdown() method. * * @throws XMPPException if the connection could not be established */ public void startup() throws XMPPException { if(readerThread != null) throw new RuntimeException("ReaderThread.startup called while already running"); done = false; connectionException = null; connectionSemaphore = new Semaphore(0); // Create an executor to deliver incoming packets to listeners. We'll use a single // thread with an unbounded queue. listenerExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable, "Smack Listener Processor (" + connection.connectionCounterValue + ")"); thread.setDaemon(true); return thread; } }); // Begin connecting. readerThread = new Thread() { public void run() { parsePackets(this); } }; readerThread.setName("Smack Packet Reader (" + connection.connectionCounterValue + ")"); readerThread.setDaemon(true); readerThread.start(); // Wait until the connection is established before returning. int waitTime = SmackConfiguration.getPacketReplyTimeout(); try { if(!connectionSemaphore.tryAcquire(3 * waitTime, TimeUnit.MILLISECONDS)) { /* The connection timed out. */ throw new XMPPException("Connection failed. No response from server."); } } catch (InterruptedException ie) { throw new XMPPException("Connection interrupted", ie); } // If an exception occurred during connection, re-throw it. if (connectionException != null) throw connectionException; } /** * Shuts the packet reader down. * * The caller must first shut down the data stream to ensure the thread will exit. */ public void shutdown() { if(readerThread == Thread.currentThread()) throw new AssertionError("shutdown() can't be called from the packet reader thread"); // The actual shutdown happens due to the caller closing the data stream. done = true; // Do nothing if we're already shut down. if(readerThread == null) return; // Wait for the reader thread to exit. It's the caller's responsibility to ensure // that the underlying reader returns an EOF before calling this function. ThreadUtil.uninterruptibleJoin(readerThread); readerThread = null; // Shut down the listener executor. listenerExecutor.shutdown(); } /** Assert that the current thread is not the reader thread. */ public void assertNotInThread() { if(Thread.currentThread() == readerThread) throw new RuntimeException("Call from within reader thread prohibited"); } /** * Parse top-level packets in order to process them further. * * @param thread the thread that is being used by the reader to parse incoming packets. */ private void parsePackets(Thread thread) { boolean waitingForEstablishedConnection = true; try { try { connection.initializeConnection(); } catch(XMPPException e) { /* Before connection, users can't yet attach error listeners. Errors before * connection are thrown from startup(). */ connectionEstablishError(e); return; } while(!done) { // Read the next packet. Element packet = this.connection.readPacket(); if(packet == null) { // The session has terminated. throw new XMPPException("Connection closed"); } /* Convert the stanza to an XmlPullParser. */ XmlPullParser parser = new XmlPullParserDom(packet, true); for ( ; parser.getEventType() != XmlPullParser.END_DOCUMENT; parser.next() ) { if(parser.getEventType() != XmlPullParser.START_TAG) continue; if (parser.getName().equals("message")) { processPacket(PacketParserUtils.parseMessage(parser)); } else if (parser.getName().equals("iq")) { processPacket(PacketParserUtils.parseIQ(parser, connection)); } else if (parser.getName().equals("presence")) { processPacket(PacketParserUtils.parsePresence(parser)); } else if (parser.getName().equals("error")) { throw new XMPPException(PacketParserUtils.parseStreamError(parser)); } else if (parser.getName().equals("features")) { parseFeatures(parser); if(waitingForEstablishedConnection) { /* When initializeConnection returns, the connection is established and ready to use. * However, don't signal to continue until we receive the first packet, which will * be <features/>. Otherwise, we're not ready for login() to be called. */ connectionEstablished(); waitingForEstablishedConnection = false; } } else if (parser.getName().equals("failure") && parser.getNamespace().equals("urn:ietf:params:xml:ns:xmpp-sasl")) { // SASL authentication has failed. The server may close the connection // depending on the number of retries final Failure failure = PacketParserUtils.parseSASLFailure(parser); processPacket(failure); connection.getSASLAuthentication().authenticationFailed(failure.getCondition()); } else if (parser.getName().equals("challenge") && parser.getNamespace().equals("urn:ietf:params:xml:ns:xmpp-sasl")) { // The server is challenging the SASL authentication made by the client String challengeData = parser.nextText(); processPacket(new Challenge(challengeData)); connection.getSASLAuthentication().challengeReceived(challengeData); } else if (parser.getName().equals("success") && parser.getNamespace().equals("urn:ietf:params:xml:ns:xmpp-sasl")) { processPacket(new Success(parser.nextText())); // After a <success>, the stream is reset. Inform the stream. connection.streamReset(); // The SASL authentication with the server was successful. The next step // will be to bind the resource connection.getSASLAuthentication().authenticated(); } } } } catch (RuntimeException e) { throw e; // don't handle unchecked exceptions below } catch (Exception e) { e.printStackTrace(); if(waitingForEstablishedConnection) { waitingForEstablishedConnection = false; // If waitingForEstablishedConnection is true, startup() is still waiting for // us, so deliver the exception there instead. if(e instanceof XMPPException) connectionEstablishError((XMPPException) e); else connectionEstablishError(new XMPPException(e)); } else if (!done) { // Close the connection and notify connection listeners of the // error. done = true; connection.readerThreadException(e); } } } /** * Processes a packet after it's been fully parsed by looping through the installed * packet collectors and listeners and letting them examine the packet to see if * they are a match with the filter. * * @param packet the packet to process. */ private void processPacket(Packet packet) { if (packet == null) { return; } // Deliver the incoming packet to listeners. listenerExecutor.submit(new ListenerNotification(packet)); } private void parseFeatures(XmlPullParser parser) throws Exception { boolean done = false; while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals("mechanisms")) { // The server is reporting available SASL mechanisms. Store this information // which will be used later while logging (i.e. authenticating) into // the server connection.getSASLAuthentication() .setAvailableSASLMethods(PacketParserUtils.parseMechanisms(parser)); } else if (parser.getName().equals("bind")) { // The server requires the client to bind a resource to the stream connection.getSASLAuthentication().bindingRequired(); } else if (parser.getName().equals("session")) { // The server supports sessions connection.getSASLAuthentication().sessionsSupported(); } else if (parser.getName().equals("register")) { connection.getAccountManager().setSupportsAccountCreation(true); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals("features")) { done = true; } } } } /** * A runnable to notify all listeners of a packet. */ private class ListenerNotification implements Runnable { private Packet packet; public ListenerNotification(Packet packet) { this.packet = packet; } public void run() { // Listeners are run synchronously to this thread. Run them before // collectors, so a collector can be used to wait until all listeners // on a packet have been run. for (ListenerWrapper listenerWrapper : connection.recvListeners.values()) { listenerWrapper.notifyListener(packet); } // Loop through all collectors and notify the appropriate ones. System.out.print("processPacket id " + packet.getPacketID()); for (PacketCollector collector: connection.getPacketCollectors()) { collector.processPacket(packet); } } } }
Markdown
UTF-8
3,249
2.65625
3
[]
no_license
--- description: "Recipe of Favorite Chicken Egg Roll-HCG" title: "Recipe of Favorite Chicken Egg Roll-HCG" slug: 54-recipe-of-favorite-chicken-egg-roll-hcg date: 2021-07-20T14:32:26.816Z image: //assets-global.cpcdn.com/assets/blank-4e0bea6785e03f5e602ec562f230caae08da540cada707380b4fe1bbebba43da.png thumbnail: //assets-global.cpcdn.com/assets/blank-4e0bea6785e03f5e602ec562f230caae08da540cada707380b4fe1bbebba43da.png cover: //assets-global.cpcdn.com/assets/blank-4e0bea6785e03f5e602ec562f230caae08da540cada707380b4fe1bbebba43da.png author: Elmer Lewis ratingvalue: 4.2 reviewcount: 22186 recipeingredient: - "3 Cabbage Leaves" - "1 cup Shredded cabbage" - "1 dash Onion salt garlic powder Chinese 5 spice" - "1/2 packages Stevia" - "2 Melba toast rounds" - "3 1/2 oz Boneless skinless chicken breast cooked and chopped" recipeinstructions: - "Steam big cabbage leaves for 5 minutes." - "Move over to side of steamer to make room for shredded cabbage." - "Steam shredded cabbage for 5 min." - "Remove shredded cabbage to mixing bowl with chicken and spices." - "Wrap in big cabbage leaves and crunch Melba toast on top to give crunch." categories: - Recipe tags: - chicken - egg - rollhcg katakunci: chicken egg rollhcg nutrition: 163 calories recipecuisine: American preptime: "PT19M" cooktime: "PT52M" recipeyield: "3" recipecategory: Dessert --- ![Chicken Egg Roll-HCG](//assets-global.cpcdn.com/assets/blank-4e0bea6785e03f5e602ec562f230caae08da540cada707380b4fe1bbebba43da.png) Hello everybody, I hope you're having an incredible day today. Today, we're going to prepare a distinctive dish, chicken egg roll-hcg. It is one of my favorites. For mine, I will make it a bit tasty. This is gonna smell and look delicious. Chicken Egg Roll-HCG is one of the most well liked of current trending foods on earth. It's easy, it is quick, it tastes delicious. It is enjoyed by millions every day. Chicken Egg Roll-HCG is something that I have loved my whole life. They're nice and they look wonderful. To begin with this recipe, we must prepare a few components. You can have chicken egg roll-hcg using 6 ingredients and 5 steps. Here is how you can achieve that. <!--inarticleads1--> ##### The ingredients needed to make Chicken Egg Roll-HCG: 1. Prepare 3 Cabbage Leaves 1. Get 1 cup Shredded cabbage 1. Make ready 1 dash Onion salt, garlic powder, Chinese 5 spice, 1. Get 1/2 packages Stevia 1. Make ready 2 Melba toast rounds 1. Get 3 1/2 oz Boneless, skinless chicken breast, cooked and chopped <!--inarticleads2--> ##### Instructions to make Chicken Egg Roll-HCG: 1. Steam big cabbage leaves for 5 minutes. 1. Move over to side of steamer to make room for shredded cabbage. 1. Steam shredded cabbage for 5 min. 1. Remove shredded cabbage to mixing bowl with chicken and spices. 1. Wrap in big cabbage leaves and crunch Melba toast on top to give crunch. So that's going to wrap this up with this exceptional food chicken egg roll-hcg recipe. Thank you very much for your time. I'm sure you can make this at home. There's gonna be interesting food in home recipes coming up. Don't forget to bookmark this page in your browser, and share it to your loved ones, friends and colleague. Thanks again for reading. Go on get cooking!
Java
UTF-8
1,073
2.4375
2
[]
no_license
package com.gps.chambee.ui.adaptadores; import android.content.Context; import com.gps.chambee.ui.fragmentos.InicioFragment; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; public class ExploraAdapter extends FragmentPagerAdapter { private Context context; int totalTabs; public ExploraAdapter(Context context, FragmentManager fm,int totalTabs){ super(fm); this.context=context; this.totalTabs=totalTabs; this.totalTabs = totalTabs; } @NonNull @Override public Fragment getItem(int position) { switch (position){ case 0: InicioFragment in = new InicioFragment(); return in; case 1: InicioFragment an = new InicioFragment(); return an; default: return null; } } @Override public int getCount() { return totalTabs; } }
Java
UTF-8
3,567
1.953125
2
[]
no_license
package com.saas.adapter.code.business; import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import com.google.gson.Gson; import com.saas.adapter.clients.TokenClient; import com.saas.adapter.po.HuaBuDianParams; import com.saas.adapter.po.OrderReturn; import com.saas.adapter.po.Parameter; import com.saas.adapter.tools.MD5; import com.saas.adapter.tools.OrderReturnMain; import com.saas.adapter.tools.StringSort; @Service public class AlipayPhoneBusiness { private static Logger LOG = LoggerFactory.getLogger(AlipayPhoneBusiness.class); @Autowired public OrderReturnMain orderReturnMain; @Autowired private TokenClient tokenClient; /** * 统一下单 * * @throws Exception */ public OrderReturn payWap(Parameter parameter, String payType) { Map<String, String> map = new HashMap<String, String>(); StringSort stringSort = new StringSort(); map.put("mch", parameter.merchantChannel.no); if ("aliqrcode".equals(payType)) { map.put("pay_type", payType); } if ("aliwap".equals(payType)) { map.put("pay_type", payType); } if ("alih5".equals(payType)) { map.put("pay_type", payType); } map.put("money", parameter.order.money); String time = String.valueOf(Math.round(new Date().getTime() / 1000)); map.put("time", time); map.put("order_id", parameter.order.no);// map.put("return_url", parameter.order.orderConfig.successUrl); map.put("notify_url", "http://adapter.ivpai.com/huaBuDianController/notify"); tokenClient.savePayParams(parameter.order.id.replaceAll("-", ""), parameter.order.orderConfig.notifyUrl); map.put("extra", parameter.order.id.replaceAll("-", ""));// map.put("longtitude", "36");// map.put("latitude", "18");// map.put("deviceinfo", parameter.order.no);// String str = parameter.order.no + parameter.order.money + payType + time + parameter.merchantChannel.no; String sign = ""; try { sign = MD5.sign(str, MD5.sign(parameter.merchantChannel.key, "", "UTF-8").toLowerCase(), "UTF-8") .toLowerCase(); } catch (Exception e) { e.printStackTrace(); } map.put("sign", sign); String req = stringSort.getUrlParamsByMap(map, true); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); HttpEntity<String> entity = new HttpEntity<String>(headers); String returnParams = restTemplate .exchange("http://api.oba88.cn/waporder/order_add?" + req, HttpMethod.GET, entity, String.class) .getBody(); HuaBuDianParams huaBuDianParams = (new Gson()).fromJson(returnParams, HuaBuDianParams.class); if (huaBuDianParams.net && huaBuDianParams.ok) { return orderReturnMain.successReturn(huaBuDianParams.data, parameter.merchantChannel.no, parameter.order.money);// } return orderReturnMain.failReturn(returnParams); } public static Integer StringToTimestamp(String time) { int times = 0; try { times = (int) ((Timestamp.valueOf(time).getTime()) / 1000); } catch (Exception e) { e.printStackTrace(); } if (times == 0) { LOG.info("String转10位时间戳失败"); } return times; } }
C#
UTF-8
13,005
2.78125
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FImageEditor { public partial class FaceViewControl : UserControl { // モデル private FaceImageEntry entry; // 画像ファイル名 private string imageFileName; // ピクチャがドラッグされているかどうか private bool isPictureDragging; // ピクチャドラッグ時の位置 private Point pictureDragStartPosition; /// <summary> /// 新しいFaceViewControlを構築する。 /// </summary> public FaceViewControl() { entry = null; imageFileName = string.Empty; isPictureDragging = false; pictureDragStartPosition = new Point(); InitializeComponent(); UpdatePicturePosition(); } /// <summary> /// 顔グラフィックエントリ /// </summary> public FaceImageEntry FaceImageEntry { get => entry; set { if (entry != value) { if (entry != null) { entry.PropertyChanged -= OnFaceImageEntryChanged; } entry = value; if (entry != null) { entry.PropertyChanged += OnFaceImageEntryChanged; } UpdateView(); } } } /// <summary> /// データが変更された時に通知を受け取る。 /// </summary> /// <param name="sender">送信元オブジェクト</param> /// <param name="e">イベントオブジェクト</param> private void OnFaceImageEntryChanged(object sender, PropertyChangedEventArgs e) { try { UpdateView(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } } /// <summary> /// 表示を更新する。 /// </summary> private void UpdateView() { if (InvokeRequired) { Invoke((MethodInvoker)UpdateView); } else { if (entry != null) { labelFileName.Text = System.IO.Path.GetFileName(entry.FileName); if (!imageFileName.Equals(entry.FileName)) { SetImage(entry.FileName); } else { facePictureControl.ImageRect = new Rectangle(entry.X, entry.Y, entry.Width, entry.Height); numericUpDownX.Value = ClampNumericUpDownValue(numericUpDownX, entry.X); numericUpDownY.Value = ClampNumericUpDownValue(numericUpDownY, entry.Y); } } else { labelFileName.Text = string.Empty; } } buttonSelect.Enabled = (entry != null); numericUpDownX.Enabled = (entry != null); numericUpDownY.Enabled = (entry != null); } /// <summary> /// valueに対し、numericUpDownのMinimum以上、Maximum以下の値を得る。 /// </summary> /// <param name="numericUpDown">コントロール</param> /// <param name="value">値</param> /// <returns>値</returns> private static Decimal ClampNumericUpDownValue(NumericUpDown numericUpDown, Decimal value) { if (value < numericUpDown.Minimum) { return numericUpDown.Minimum; } else if (value > numericUpDown.Maximum) { return numericUpDown.Maximum; } else { return value; } } /// <summary> /// パネルのサイズが変更されたときに通知を受け取る。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnPanelResized(object sender, EventArgs e) { UpdatePicturePosition(); } /// <summary> /// 画像表示コンポーネントの位置とサイズを更新する。 /// </summary> private void UpdatePicturePosition() { var parentSize = panelPictureParent.Size; var padding = panelPictureParent.Padding; var innerWidth = parentSize.Width - padding.Horizontal; var innerHeight = parentSize.Height - padding.Vertical; var pictureSize = Math.Min(innerWidth, innerHeight); // 正方形にする。 var x = padding.Left + (innerWidth - pictureSize) / 2; var y = padding.Top + (innerHeight - pictureSize) / 2; facePictureControl.SetBounds(x, y, pictureSize, pictureSize); } /// <summary> /// 選択ボタンがクリックされた時の処理を行う。 /// </summary> /// <param name="sender">送信元オブジェクト</param> /// <param name="e">イベントオブジェクト</param> private void OnButtonSelectClick(object sender, EventArgs e) { try { var lastOpenFile = Properties.Settings.Default.LastOpenPath; if (System.IO.File.Exists(lastOpenFile)) { openFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(lastOpenFile); } if (string.IsNullOrEmpty(entry.FileName)) { openFileDialog.FileName = Properties.Settings.Default.LastOpenPath; } else { openFileDialog.FileName = entry.FileName; } if (openFileDialog.ShowDialog(FindForm()) != DialogResult.OK) { return; } SetImage(openFileDialog.FileName); Properties.Settings.Default.LastOpenPath = System.IO.Path.GetDirectoryName(openFileDialog.FileName); } catch (Exception ex) { MessageBox.Show(FindForm(), ex.Message); } } /// <summary> /// 画像をエントリに設定する。 /// </summary> /// <param name="fileName">ファイルパス</param> private void SetImage(string fileName) { if (string.IsNullOrEmpty(fileName)) { imageFileName = string.Empty; facePictureControl.Image = null; } else { using (var image = Image.FromFile(fileName)) { if ((image.Width < entry.Width) || (image.Height < entry.Height)) { throw new Exception($"Image size incorrect. [width={image.Width},height={image.Height}]"); } int width = image.Width; int height = image.Height; var setImage = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (var g = Graphics.FromImage(setImage)) { g.DrawImage(image, 0, 0); } int maxX = width - entry.Width; int maxY = height - entry.Height; entry.X = Math.Min(entry.X, maxX); entry.Y = Math.Min(entry.Y, maxY); entry.FileName = fileName; imageFileName = entry.FileName; numericUpDownX.Maximum = maxX; numericUpDownY.Maximum = maxY; numericUpDownX.Value = entry.X; numericUpDownY.Value = entry.Y; if (facePictureControl.Image != null) { var prevImage = facePictureControl.Image; facePictureControl.Image = null; prevImage.Dispose(); } facePictureControl.Image = setImage; facePictureControl.ImageRect = new Rectangle(entry.X, entry.Y, entry.Width, entry.Height); } } numericUpDownX.Enabled = facePictureControl.Image != null; numericUpDownY.Enabled = facePictureControl.Image != null; } /// <summary> /// 値が変更されたときに通知を受け取る。 /// </summary> /// <param name="sender">送信元オブジェクト</param> /// <param name="e">イベントオブジェクト</param> private void OnNumericUpDownValueChanged(object sender, EventArgs e) { if (sender == numericUpDownX) { entry.X = (int)(numericUpDownX.Value); } else if (sender == numericUpDownY) { entry.Y = (int)(numericUpDownY.Value); } } /// <summary> /// ピクチャボックスでマウスボタンが押されたときに通知を受け取る。 /// </summary> /// <param name="sender">送信元オブジェクト</param> /// <param name="e">イベントオブジェクト</param> private void OnPictureBoxMouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { isPictureDragging = true; pictureDragStartPosition = e.Location; } } /// <summary> /// ピクチャボックスでマウスボタンが放されたときに通知を受け取る。 /// </summary> /// <param name="sender">送信元オブジェクト</param> /// <param name="e">イベントオブジェクト</param> private void OnPictureBoxMouseUp(object sender, MouseEventArgs e) { isPictureDragging = false; } /// <summary> /// ピクチャボックスでマウスが移動したときに通知を受け取る。 /// </summary> /// <param name="sender">送信元オブジェクト</param> /// <param name="e">イベントオブジェクト</param> private void OnPictureBoxMouseMove(object sender, MouseEventArgs e) { if (isPictureDragging) { var mouseLocation = e.Location; int moveX = mouseLocation.X - pictureDragStartPosition.X; int moveY = mouseLocation.Y - pictureDragStartPosition.Y; if (entry != null) { var maxX = (int)(numericUpDownX.Maximum); var maxY = (int)(numericUpDownY.Maximum); var x = entry.X - moveX; var y = entry.Y - moveY; entry.X = (x < 0) ? 0 : ((x > maxX) ? maxX : x); entry.Y = (y < 0) ? 0 : ((y > maxY) ? maxY : y); } pictureDragStartPosition = mouseLocation; } } /// <summary> /// ドラッグ操作された状態でドラッグ対象に移動してきたときに通知を受け取る。 /// </summary> /// <param name="sender">送信元オブジェクト</param> /// <param name="e">イベントオブジェクト</param> private void OnDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } } /// <summary> /// ドラッグ操作された状態でドロップされたときに通知を受け取る。 /// </summary> /// <param name="sender">送信元オブジェクト</param> /// <param name="e">イベントオブジェクト</param> private void OnDragDrop(object sender, DragEventArgs e) { try { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] files = (string[])(e.Data.GetData(DataFormats.FileDrop)); SetImage(files[0]); } } catch (Exception ex) { MessageBox.Show(FindForm(), ex.Message); } } } }
C++
UTF-8
478
3.046875
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <stack> using namespace std; //string getStr(string s) //{ // if (s.size() == 0) // { // return ""; // } // string ans; // stack<char> st1; // for (int i = 0;i < s.size();i++) // { // if (s[i] == '[') // { // st1.push(']'); // } // else if (s[i] == ']') // { // st1.pop(); // } // else if() // } // // return ans; //} int main() { string s; cin >> s; s = getStr(s); cout << s << endl; return 0; }
Java
UTF-8
2,412
2.0625
2
[]
no_license
package com.regismutangana.lostandfound.Found; import android.content.Context; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx; import com.regismutangana.lostandfound.Home.SectionsPagerAdapter; import com.regismutangana.lostandfound.R; import com.regismutangana.lostandfound.Utils.BottomNavigationViewHelper; public class FoundActivity extends AppCompatActivity { private static final String TAG = "FoundActivity"; private static final int ACTIVITY_NUM = 1; private Context mContext = FoundActivity.this; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_found); setupBottomNavigationView(); setupViewPager(); } private void setupViewPager(){ SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager()); adapter.addFragemnt(new FoundFragmentCards()); adapter.addFragemnt(new FoundFragmentAutomobile()); adapter.addFragemnt(new FoundFragmentGadgets()); ViewPager viewPager = (ViewPager)findViewById(R.id.container); viewPager.setAdapter(adapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); tabLayout.getTabAt(0).setIcon(R.drawable.ic_cards); tabLayout.getTabAt(1).setIcon(R.drawable.ic_cars); tabLayout.getTabAt(2).setIcon(R.drawable.ic_gadgets); } /** * BottomNavigationView Setup */ private void setupBottomNavigationView(){ Log.d(TAG, "setupBottomNavigationView: setting up bottomNavigationViewEx"); BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar); BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx); BottomNavigationViewHelper.enableNavigation(mContext,bottomNavigationViewEx); Menu menu = bottomNavigationViewEx.getMenu(); MenuItem menuItem = menu.getItem(ACTIVITY_NUM); menuItem.setChecked(true); } }
Java
UTF-8
23,252
2.125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.awt.Color; import java.util.*; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JList; import javax.swing.DefaultListModel; import javax.swing.ListSelectionModel; /** * * @author Jonas */ public class MusicPlayerGui extends javax.swing.JFrame implements MusicPlayerListener { private MusicPlayer p; private JFileChooser fileC; private int pop; private boolean mouse; private LinkedList<File> playList; private String favorit; private boolean favoritIsSet; private int position; private int oldPositionP; private int gain; private int oldgain; private boolean playListUsed; private int next; private boolean soundOn = true; private File datei; private File favoritFile; private DefaultListModel<String> items; public MusicPlayerGui() { favoritFile = null; items = new DefaultListModel<String>(); datei = null; int next = 0; oldgain = 100; gain = 100; oldPositionP = 0; position = 0; playList = new LinkedList<File>(); mouse = false; pop = 0; p = new MusicPlayer(); p.addListener(this); fileC = new JFileChooser(); favorit = ""; favoritIsSet = false; getContentPane().setBackground(Color.black); initComponents(); items = new DefaultListModel<String>(); PlayListList.setModel(items); // items.addElement("Hi, I'm TheTreibelGuy"); // items.addElement("and welcome to Laura's Ass"); p.setGain(gain); PlayListList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION); pack(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jTabbedPane6 = new javax.swing.JTabbedPane(); jPanel3 = new javax.swing.JPanel(); fastrewButton = new javax.swing.JButton(); playResumeButton = new javax.swing.JButton(); stopButton = new javax.swing.JButton(); fastForwardButton = new javax.swing.JButton(); positionSlider = new javax.swing.JSlider(); positionProgressBar = new javax.swing.JProgressBar(); volumeLabel = new javax.swing.JLabel(); soundButton = new javax.swing.JButton(); playListButton = new javax.swing.JButton(); setButton = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); BirthdayButton = new javax.swing.JButton(); FavoritFile = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); PlayListList = new javax.swing.JList(); jLabel2 = new javax.swing.JLabel(); jButton1.setText("jButton1"); jButton2.setText("jButton2"); jTabbedPane6.addTab("tab1", jPanel3); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("MP3Player"); setAutoRequestFocus(false); setBackground(new java.awt.Color(0, 0, 0)); setBounds(new java.awt.Rectangle(0, 0, 0, 0)); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setFont(new java.awt.Font("Aramis", 3, 18)); // NOI18N setForeground(new java.awt.Color(0, 0, 0)); setPreferredSize(new java.awt.Dimension(800, 321)); setResizable(false); addMouseWheelListener(new java.awt.event.MouseWheelListener() { public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) { formMouseWheelMoved(evt); } }); getContentPane().setLayout(null); fastrewButton.setBackground(new java.awt.Color(0, 0, 0)); fastrewButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Action-arrow-blue-double-right-icon.png"))); // NOI18N fastrewButton.setOpaque(false); fastrewButton.setBackground(new Color(0,0,0,0)); fastrewButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fastrewButtonActionPerformed(evt); } }); getContentPane().add(fastrewButton); fastrewButton.setBounds(300, 230, 60, 60); playResumeButton.setBackground(new java.awt.Color(0, 0, 0)); playResumeButton.setOpaque(false); playResumeButton.setBackground(new Color(0,0,0,0)); playResumeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Play-icon.png"))); // NOI18N playResumeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { playResumeButtonActionPerformed(evt); } }); getContentPane().add(playResumeButton); playResumeButton.setBounds(370, 230, 60, 60); stopButton.setBackground(new java.awt.Color(0, 0, 0)); stopButton.setOpaque(false); stopButton.setBackground(new Color(0,0,0,0)); stopButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Stop-icon.png"))); // NOI18N stopButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stopButtonActionPerformed(evt); } }); getContentPane().add(stopButton); stopButton.setBounds(510, 230, 60, 60); fastForwardButton.setBackground(new java.awt.Color(0, 0, 0)); fastForwardButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Action-arrow.png"))); // NOI18N fastForwardButton.setOpaque(false); fastForwardButton.setBackground(new Color(0,0,0,0)); fastForwardButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fastForwardButtonActionPerformed(evt); } }); getContentPane().add(fastForwardButton); fastForwardButton.setBounds(440, 230, 60, 60); positionSlider.setMajorTickSpacing(1); positionSlider.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); positionSlider.setOpaque(false); positionSlider.setBackground(new Color(0,0,0,0)); positionSlider.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { positionSliderMouseClicked(evt); } }); getContentPane().add(positionSlider); positionSlider.setBounds(0, 180, 800, 40); positionProgressBar.setBackground(new java.awt.Color(0, 0, 0)); positionProgressBar.setForeground(new java.awt.Color(0, 0, 0)); positionProgressBar.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { positionProgressBarStateChanged(evt); } }); getContentPane().add(positionProgressBar); positionProgressBar.setBounds(0, 180, 800, 40); volumeLabel.setForeground(new java.awt.Color(255, 255, 255)); volumeLabel.setText("100"); getContentPane().add(volumeLabel); volumeLabel.setBounds(730, 230, 30, 20); soundButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Status-audio-volume-high-icon.png"))); // NOI18N soundButton.setOpaque(false); soundButton.setBackground(new Color(0,0,0,0)); soundButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { soundButtonActionPerformed(evt); } }); getContentPane().add(soundButton); soundButton.setBounds(730, 230, 60, 60); playListButton.setBackground(new java.awt.Color(0, 0, 0)); playListButton.setOpaque(false); playListButton.setBackground(new Color(0,0,0,0)); playListButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Add-icon.png"))); // NOI18N playListButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { playListButtonMouseClicked(evt); } }); playListButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { playListButtonActionPerformed(evt); } }); getContentPane().add(playListButton); playListButton.setBounds(230, 230, 60, 57); setButton.setBackground(new java.awt.Color(0, 0, 0)); setButton.setOpaque(false); setButton.setBackground(new Color(0,0,0,0)); setButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Music-icon (2).png"))); // NOI18N setButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { setButtonActionPerformed(evt); } }); getContentPane().add(setButton); setButton.setBounds(20, 10, 161, 162); jButton3.setOpaque(false); jButton3.setBackground(new Color(0,0,0,0)); jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/play-icon (2).png"))); // NOI18N jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); getContentPane().add(jButton3); jButton3.setBounds(710, 120, 50, 33); BirthdayButton.setBackground(new java.awt.Color(0, 0, 0)); BirthdayButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Downloads-icon.png"))); // NOI18N BirthdayButton.setOpaque(false); BirthdayButton.setBackground(new Color(0,0,0,0)); BirthdayButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BirthdayButtonActionPerformed(evt); } }); getContentPane().add(BirthdayButton); BirthdayButton.setBounds(200, 10, 160, 160); FavoritFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Burn-icon.png"))); // NOI18N FavoritFile.setOpaque(false); FavoritFile.setBackground(new Color(0,0,0,0)); FavoritFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { FavoritFileActionPerformed(evt); } }); getContentPane().add(FavoritFile); FavoritFile.setBounds(380, 10, 160, 160); PlayListList.setBackground(new java.awt.Color(0, 0, 0)); PlayListList.setForeground(new java.awt.Color(255, 255, 255)); PlayListList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Song1" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jScrollPane1.setViewportView(PlayListList); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(560, 10, 210, 160); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Black Background1.jpg"))); // NOI18N getContentPane().add(jLabel2); jLabel2.setBounds(0, 0, 800, 300); pack(); }// </editor-fold>//GEN-END:initComponents public void positionChanged(int newPosition) { if(newPosition == 99) { next++; if(playListUsed && playList.get(next) != null) { p.open(playList.get(next).getAbsolutePath()); p.play(); } else { p.stop(); pop = 1; playResumeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Refresh-icon.png"))); } } positionProgressBar.setValue(newPosition); } private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed p.stop(); playResumeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Play-icon.png"))); positionProgressBar.setValue(0); pop = 1; }//GEN-LAST:event_stopButtonActionPerformed private void fastForwardButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fastForwardButtonActionPerformed p.fastForward(); }//GEN-LAST:event_fastForwardButtonActionPerformed private void fastrewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fastrewButtonActionPerformed p.rewind(); }//GEN-LAST:event_fastrewButtonActionPerformed private void playResumeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playResumeButtonActionPerformed if(pop != 0) { if(pop == 1) { p.play(); pop = 2; playResumeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Pause-icon.png"))); } else if(pop == 2) { p.pause(); pop = 3; playResumeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Play-icon.png"))); } else if(pop == 3) { p.resume(); pop = 2; playResumeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Pause-icon.png"))); } } }//GEN-LAST:event_playResumeButtonActionPerformed private void positionProgressBarStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_positionProgressBarStateChanged // if(positionProgressBar.getValue() == 100) // { // p.stop(); // if(playl.get(1) != null) // { // p.open(playl.get(1).getAbsolutePath()); // } // } }//GEN-LAST:event_positionProgressBarStateChanged private void positionSliderMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_positionSliderMouseClicked int w = this.getWidth(); System.out.println(w); int x = evt.getX(); System.out.println(x); double newPosition = 100.0/(double)this.getWidth()*evt.getX(); System.out.println(newPosition); p.seek((int)newPosition); }//GEN-LAST:event_positionSliderMouseClicked private void gainChanged() { if(gain > 66) soundButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Status-audio-volume-high-icon.png"))); else if(gain > 33) soundButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Status-audio-volume-medium-icon.png"))); else if(gain > 0) soundButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Status-audio-volume-low-icon.png"))); else soundButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Status-audio-volume-muted-icon.png"))); } private void formMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_formMouseWheelMoved gain -= (evt.getWheelRotation()*2); if (gain > 100) gain = 100; else if(gain < 0) gain = 0; volumeLabel.setText(String.valueOf(gain)); oldgain = gain; soundOn = false; gainChanged(); p.setGain(gain); }//GEN-LAST:event_formMouseWheelMoved private void playListButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playListButtonActionPerformed int returnVal = fileC.showOpenDialog(MusicPlayerGui.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File datei = fileC.getSelectedFile(); if(datei != null) { if(playList.isEmpty()) { p.open(datei.getAbsolutePath()); } items.addElement(datei.getName()); playList.add(datei); pop = 1; playListUsed = true; // for(int i = 0; i < next; i++) // { // System.out.println(playList.get(next).getAbsolutePath()); // } } } }//GEN-LAST:event_playListButtonActionPerformed private void soundButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_soundButtonActionPerformed if(soundOn) { p.setGain(0); oldgain = gain; gain = 0; soundOn = false; volumeLabel.setText(String.valueOf(gain)); gainChanged(); } else { gain = oldgain; p.setGain(gain); soundOn = true; volumeLabel.setText(String.valueOf(gain)); gainChanged(); } }//GEN-LAST:event_soundButtonActionPerformed private void playListButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_playListButtonMouseClicked int returnVal = fileC.showOpenDialog(MusicPlayerGui.this); if (returnVal == JFileChooser.APPROVE_OPTION) { p.stop(); File datei = fileC.getSelectedFile(); playList.add(datei); if(playList.isEmpty()) { p.open(datei.getAbsolutePath()); } pop = 1; next++; playListUsed = true; } }//GEN-LAST:event_playListButtonMouseClicked private void setButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setButtonActionPerformed int returnVal = fileC.showOpenDialog(MusicPlayerGui.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File datei = fileC.getSelectedFile(); p.open(datei.getAbsolutePath()); if(datei != null) { items.removeAllElements(); items.addElement(datei.getName()); playList.add(datei); pop = 1; playListUsed = true; } } }//GEN-LAST:event_setButtonActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed p.open(playList.get(PlayListList.getSelectedIndex()).getAbsolutePath()); next = PlayListList.getSelectedIndex(); p.play(); }//GEN-LAST:event_jButton3ActionPerformed private void FavoritFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FavoritFileActionPerformed int returnVal = fileC.showOpenDialog(MusicPlayerGui.this); if (returnVal == JFileChooser.APPROVE_OPTION) { favoritFile = fileC.getSelectedFile(); } }//GEN-LAST:event_FavoritFileActionPerformed private void BirthdayButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BirthdayButtonActionPerformed if(favoritFile != null) { if(playList.isEmpty()) { p.open(favoritFile.getAbsolutePath()); pop = 1; } else playList.add(favoritFile); items.addElement(favoritFile.getName()); pop = 1; playListUsed = true; // for(int i = 0; i < next; i++) // { // System.out.println(playList.get(next).getAbsolutePath()); // } } }//GEN-LAST:event_BirthdayButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MusicPlayerGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MusicPlayerGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MusicPlayerGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MusicPlayerGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MusicPlayerGui().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BirthdayButton; private javax.swing.JButton FavoritFile; private javax.swing.JList PlayListList; private javax.swing.JButton fastForwardButton; private javax.swing.JButton fastrewButton; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTabbedPane jTabbedPane6; private javax.swing.JButton playListButton; private javax.swing.JButton playResumeButton; private javax.swing.JProgressBar positionProgressBar; private javax.swing.JSlider positionSlider; private javax.swing.JButton setButton; private javax.swing.JButton soundButton; private javax.swing.JButton stopButton; private javax.swing.JLabel volumeLabel; // End of variables declaration//GEN-END:variables }
Shell
UTF-8
766
3.03125
3
[]
no_license
#!/bin/bash set -e # The CentOS 7 lab machines apear to have mvn installed, but snowy does not seem to # a prebuilt maven is available at /home/fe14/as14622/linux/dist/maven/bin/mvn MAVEN=mvn if ! type "$MAVEN" &> /dev/null; then MAVEN=/home/fe14/as14622/linux/dist/maven/bin/mvn echo mvn not found, trying to use prebuilt maven fi PROG=${1:-bubble} echo Compiling $MAVEN package echo Assembling #$MAVEN exec:java@asm -DasmIn=prog/test1.aca -DasmOut=prog/test1.hex java -cp target/ACASim-0.0.1-SNAPSHOT-jar-with-dependencies.jar simulator.core.ACAAssembler prog/$PROG.aca prog/$PROG.hex echo Running simulator #$MAVEN exec:java@sim-nogui -DprogramIn=prog/test1.hex java -jar target/ACASim-0.0.1-SNAPSHOT-jar-with-dependencies.jar prog/$PROG ${2:-nogui}
Java
UTF-8
6,165
1.859375
2
[]
no_license
package com.liferay.test.web.util; import com.google.common.collect.Lists; import com.liferay.portal.kernel.dao.search.DisplayTerms; import com.liferay.portal.kernel.dao.search.SearchContainer; import com.liferay.portal.kernel.dao.search.SearchContainerResults; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.search.Document; import com.liferay.portal.kernel.search.Field; import com.liferay.portal.kernel.search.Hits; import com.liferay.portal.kernel.search.Indexer; import com.liferay.portal.kernel.search.IndexerRegistryUtil; import com.liferay.portal.kernel.search.SearchContext; import com.liferay.portal.kernel.search.SearchContextFactory; import com.liferay.portal.kernel.search.SearchException; import com.liferay.portal.kernel.theme.ThemeDisplay; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.OrderByComparator; import com.liferay.portal.kernel.util.OrderByComparatorFactoryUtil; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.PortalUtil; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.test.model.SampleSB; import com.liferay.test.service.SampleSBLocalService; import com.liferay.test.web.portlet.action.SampleSBConfiguration; import java.util.List; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; @Component(service = SampleSBViewHelper.class) public class SampleSBViewHelper { /** * Order string to boolean * * @param order * @return if true if order is "asc" or false */ protected boolean getOrder(String order) { return ("asc".equalsIgnoreCase(order)) ? true : false; } /** * * Order Comparetor * * @param searchContainer * @return OrderByComparator */ public OrderByComparator<SampleSB> getOrderByComparator( SearchContainer<?> searchContainer) { if (_log.isDebugEnabled()) { _log.debug("searchContainer.getOrderByCol()" + (null != searchContainer.getOrderByCol() ? searchContainer.getOrderByCol() : "null")); _log.debug("searchContainer.getOrderByType()" + (null != searchContainer.getOrderByType() ? searchContainer.getOrderByType() : "null")); } return OrderByComparatorFactoryUtil.create("SampleSB_SampleSB", searchContainer.getOrderByCol(), getOrder(searchContainer.getOrderByType())); } /** * Get Data list from Database * * @param request PortletRequest * @param searchContainer SearchContainer<?> * @return SearchContainerResults<SampleSB> */ public SearchContainerResults<SampleSB> getListFromDB( PortletRequest request, SearchContainer<?> searchContainer) { ThemeDisplay themeDisplay = (ThemeDisplay) request .getAttribute(WebKeys.THEME_DISPLAY); PortletPreferences portletPreferences = request.getPreferences(); // Filter type String prefsViewType = portletPreferences.getValue( SampleSBConfiguration.CONF_PREFS_VIEW_TYPE, SampleSBConfiguration.PREFS_VIEW_TYPE_DEFAULT); long groupId = themeDisplay.getScopeGroupId(); int containerStart = searchContainer.getStart(); int containerEnd = searchContainer.getEnd(); List<SampleSB> results = null; int total = 0; // Get Order OrderByComparator<SampleSB> orderByComparator = getOrderByComparator( searchContainer); if (prefsViewType .equals(SampleSBConfiguration.PREFS_VIEW_TYPE_DEFAULT)) { results = _sampleSBLocalService.findAllInGroup(groupId, containerStart, containerEnd, orderByComparator); total = _sampleSBLocalService.countAllInGroup(groupId); } else if (prefsViewType .equals(SampleSBConfiguration.PREFS_VIEW_TYPE_USER)) { results = _sampleSBLocalService.findAllInUser( themeDisplay.getUserId(), containerStart, containerEnd, orderByComparator); total = _sampleSBLocalService .countAllInUser(themeDisplay.getUserId()); } else { results = _sampleSBLocalService.findAllInUserAndGroup( themeDisplay.getUserId(), groupId, containerStart, containerEnd, orderByComparator); total = _sampleSBLocalService .countAllInUserAndGroup(themeDisplay.getUserId(), groupId); } return new SearchContainerResults<>(results, total); } /** * Get Data list from Index * * @param request PortletRequest * @return searchContainer SearchContainer<?> * @throws SearchException */ public SearchContainerResults<SampleSB> getListFromIndex( PortletRequest request, SearchContainer<?> searchContainer) throws SearchException { // Search Key String searchFilter = ParamUtil.getString(request, DisplayTerms.KEYWORDS); Indexer<SampleSB> indexer = IndexerRegistryUtil .nullSafeGetIndexer(SampleSB.class); SearchContext searchContext = SearchContextFactory .getInstance(PortalUtil.getHttpServletRequest(request)); searchContext.setKeywords(searchFilter); searchContext.setStart(searchContainer.getStart()); searchContext.setEnd(searchContainer.getEnd()); // Search in index Hits results = indexer.search(searchContext); // Initialize return values int total = results.getLength(); List<SampleSB> tempResults = Lists.newArrayList(); for (int i = 0; i < results.getDocs().length; i++) { Document doc = results.doc(i); SampleSB resReg = null; // Entry long entryId = GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK)); try { resReg = _sampleSBLocalService.getSampleSB(entryId); resReg = resReg.toEscapedModel(); tempResults.add(resReg); } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn( "SampleSB search index is stale and contains entry " + entryId); } continue; } } return new SearchContainerResults<>(tempResults, total); } @Reference(unbind = "-") protected void setSampleSBLocalService( SampleSBLocalService samplesblocalservice) { _sampleSBLocalService = samplesblocalservice; } private SampleSBLocalService _sampleSBLocalService; private static Log _log = LogFactoryUtil .getLog(SampleSBViewHelper.class); }
C++
GB18030
3,653
2.765625
3
[]
no_license
#pragma once #include <windows.h> #include <vector> #include <iostream> #include <algorithm> #include <GL/glew.h> #include <GL/freeglut.h> #include <cuda_runtime.h> #include <cuda_gl_interop.h> #include "Common.h" /*check error code of cudaMalloc and print out if needed*/ #define safe_cuda(CODE)\ {\ cudaError_t err = CODE;\ if(err != cudaSuccess) {\ std::cout<<"CUDA error:"<<cudaGetErrorString(err)<<std::endl;\ }\ } template<class Key> class SortAssistant { public: SortAssistant(const std::vector<Key> &keys) : _keys(keys) { } bool operator()(const unsigned int &lhs, const unsigned int &rhs) { return _keys[lhs] < _keys[rhs]; } private: const std::vector<Key> &_keys; }; // vector֧ʵ template<class Containers> void indices_sort(const Containers &keys, std::vector<unsigned int> &indices) { indices.resize(keys.size()); for (int i = 0; i < keys.size(); ++i) { indices[i] = i; } std::sort(indices.begin(), indices.end(), SortAssistant<typename Containers::value_type>(keys)); } // Ϊָ֧ͨõûȷindiceskeysĴС template<class Containers> void remove_redundant(const Containers &keys, std::vector<unsigned int> &indices) { if (indices.empty()) { return; } unsigned int n = 1; typename Containers::value_type current = keys[indices[0]]; for (int i = 1; i < indices.size(); ++i) { if (keys[indices[i]] != current) { indices[n++] = indices[i]; current = keys[indices[i]]; } } indices.resize(n); } // Ϊָ֧ͨõûȷindiceskeysĴС template<class Containers> void filter(const Containers &input, const std::vector<unsigned int> &indices, Containers &ouput) { ouput.resize(indices.size()); for (int i = 0; i < indices.size(); ++i) { unsigned int index = indices[i]; ouput[i] = input[indices[i]]; } } /** *alloc a memory on gpu and copy data from cpu to gpu. */ inline void copyFromCPUtoGPU(void* *dst, void *src, int size) { cudaMalloc(dst, size); safe_cuda(cudaMemcpy(*dst, src, size, cudaMemcpyHostToDevice)); } /** *alloc a memory on cpu and copy data from gpu to cpu. */ inline void copyFromGPUtoCPU(void* *dst, void *src, int size) { *dst = malloc(size); safe_cuda(cudaMemcpy(*dst, src, size, cudaMemcpyDeviceToHost)); } class RefObject { public: RefObject() { ref_create(); } RefObject(const RefObject &rhs) : _reference(rhs._reference) { ++(*_reference); } RefObject &operator=(const RefObject &rhs) { ref_release(); _reference = rhs._reference; ++(*_reference); return *this; } protected: virtual void ref_auto_clean() = 0; void ref_create() { _reference = new int; *_reference = 1; } void ref_release() { if (--(*_reference) == 0) { ref_auto_clean(); delete _reference; } _reference = NULL; } void ref_renew() { ref_release(); ref_create(); } private: int *_reference; }; class StopWatch { public: StopWatch() : _elapsed(0) { QueryPerformanceFrequency(&_freq); } ~StopWatch() { } public: void start() { QueryPerformanceCounter(&_start); } void stop() { LARGE_INTEGER end; QueryPerformanceCounter(&end); _elapsed += (end.QuadPart - _start.QuadPart) * 1000000 / _freq.QuadPart; } void restart() { _elapsed = 0; start(); } //΢ double elapsed() { return double(_elapsed); } // double elapsed_ms() { return double(_elapsed) / 1000.0; } // double elapsed_second() { return double(_elapsed) / 1000000.0; } private: LARGE_INTEGER _freq; LARGE_INTEGER _start; sint64 _elapsed; }; void getFPS();
Shell
UTF-8
355
3.140625
3
[]
no_license
#!/bin/sh # Jake Yeung # run.goterms.all.sh # # 2016-11-06 indir="/home/yeung/projects/tissue-specificity/scripts/gene_enrichment_analysis" for module in kidneyWT liverKO liverWT; do fname=`echo "go_terms_analysis_different_phases."$module".all.R"` inf=$indir/$fname [[ ! -e $inf ]] && echo "$inf not found, exiting" && exit 1 Rscript $inf done
Markdown
UTF-8
2,749
2.9375
3
[]
no_license
---?color=var(--color-light-gray-2) @title[Manifest files] ### Managing Pods --- Pods are the smallest deployable units of computing that can be created and managed in Kubernetes. --- @snap[north] #### Create a new namespace to keep everything neat @snapend ```sh # We will use this namespace during this lesson $ kubectl create namespace pod-lesson ``` --- @snap[north] #### lesson01/pod-nginx.yaml @snapend ```yaml apiVersion: v1 kind: Pod metadata: name: my-nginx labels: app: my-app type: server spec: containers: - name: nginx image: "nginx:latest" ``` @[2](Pod object) @[4](Name of the pod) @[5-7](Labels to identify this pod later) @[10-11](Details of the container to run) --- @snap[north] #### Apply pod-nginx.yaml file @snapend ```sh # Use the apply command to run a manifest file $ kubectl -n pod-lesson apply -f pod-nginx.yaml # Verify your pod is running $ kubectl -n pod-lesson get pods # Get more details of your pod $ kubectl -n pod-lesson describe pod my-nginx ``` --- @snap[north] #### Port forwarding @snapend ```sh # Port forwarding from container (80) to host machine (8080) $ kubectl -n pod-lesson port-forward my-nginx 8080:80 # Leave the above command running, while in another terminal: # Curl to see the HTML of nginx $ curl localhost:8080 # Stop the port forwarding process with ctrl-c ``` --- @snap[north] #### Delete a pod @snapend ```sh # You can delete a pod using the manifest file: $ kubectl -n pod-lesson delete -f pod-nginx.yaml # or # Using the kubectl delete command: $ kubectl -n pod-lesson delete pod my-nginx ``` --- @snap[north] #### lesson01/pod-redis.yaml @snapend ```yaml apiVersion: v1 kind: Pod metadata: name: my-redis labels: app: my-app type: cache spec: containers: - name: redis image: "redis:latest" ports: - containerPort: 6379 protocol: TCP ``` @[11](We use the redis:latest docker image) @[12-14](List of ports to expose from the container) @[12-14](Not specifying a port here DOES NOT prevent that port from being exposed) --- @snap[north] #### Apply pod-redis.yaml file @snapend ```sh # Use the apply command to run a manifest file $ kubectl -n pod-lesson apply -f pod-redis.yaml # Verify your pod is running $ kubectl -n pod-lesson get pods ``` --- @snap[north] #### Interacting with Pod's logs @snapend ```sh # See the logs of the Redis container with the following command $ kubectl -n pod-lesson logs my-redis # If you want to follow the logs use the -f flag, exit with ctrl-c $ kubectl -n pod-lesson logs -f my-redis ``` --- @snap[north] #### Cleaning up namespace @snapend ```sh # Delete the pod-lesson namespace $ kubectl delete namespace pod-lesson ```
C#
UTF-8
702
2.8125
3
[ "LicenseRef-scancode-warranty-disclaimer", "ISC" ]
permissive
using System; using System.IO; namespace MSIRGB.ScriptService { class Log { private StreamWriter _log; public Log(string logPath) { _log = File.CreateText(logPath); // This should just crash if it fails _log.AutoFlush = true; } public void OutputScriptError(string s) { _log.WriteLine(String.Format("[SCRIPT ERROR] {0}", s)); } public void OutputScriptPrint(string s) { _log.WriteLine(String.Format("[SCRIPT OUTPUT] {0}", s)); } public void OutputInfo(string s) { _log.WriteLine(String.Format("[INFO] {0}", s)); } } }
Markdown
UTF-8
746
2.828125
3
[]
no_license
# SEEKr ## Setting up Clone the repository: ```shell $ git clone git@github.com:shravanjeevan/SEEKr.git ``` Navigate into the relevant directory: ```shell $ cd SEEKr ``` Create and activate new Python virtual environment (optional): ```shell $ virtualenv venv $ source venv/bin/activate ``` Install dependencies: ```shell $ pip install -r requirements.txt ``` ## Starting things up! ### Starting up Django server ```shell $ cd backend $ python manage.py runserver ``` ### Starting up React app ```shell $ cd frontend $ npm start ``` ### URLs Once each service has been started, navigate to these URLs to access them. | Service | URL | | :------------- | :----------: | | Django | http://localhost:8000 | | React | http://localhost:3000 |
Markdown
UTF-8
1,733
2.640625
3
[]
no_license
## NC News - Northcoders front end project This is the front end for NC News which is a social news aggregation, web content rating, and discussion website. Northcoders News has articles which are divided into topics. Users can access and submit articles and each article has user curated ratings and can be up or down voted using the API. Users can also add comments about an article. Comments can also be up or down voted. A user can add comments and remove any article or comment which they have added. ### `Getting Started` This is a guide to help you clone the project and run it locally. ### `Prerequisites` - React JS ### `Installing` First cd into the location that you want to store the file and run the following commands in your terminal. ``` git clone https://github.com/Mohamed-Abobaker/NC_knews_FE cd NC_knews_FE npm install ``` Then open the project in your prefered code editor and run the command ``` npm start ``` This will run the development server on a local host and you can then view the project locally. ### `Deployment` Deployed on - https://nc-news777.netlify.com/ ### `Backend` https://nc-knews777.herokuapp.com/api https://github.com/Mohamed-Abobaker/BE2-NCNEWS.git ### `Using the site` When you follow the link you will reach the login page. You can then login in with any username from the current users. For quick reference here are the available usernames: - tickle122 - grumpy19 - happyamy2016 - cooljmessy - weegembump - jessjelly A logged in user can then add and delete their own articles and comments and vote on other users articles and comments. ## `Built With` React JS @16.7.0 Reach Router @1.2.1 ## `Authors` Mohamed Abobaker - https://github.com/Mohamed-Abobaker/NC_knews_FE
Markdown
UTF-8
1,380
3.25
3
[ "MIT" ]
permissive
# 단지번호붙이기 Step03. [단지번호붙이기](https://www.acmicpc.net/problem/2667) --- ## 문제 <그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오. ![img](https://www.acmicpc.net/upload/images/ITVH9w1Gf6eCRdThfkegBUSOKd.png) ## 입력 첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다. ## 출력 첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오. ## 예제 입력 1 ``` 7 0110100 0110101 1110101 0000111 0100000 0111110 0111000 ``` ## 예제 출력 1 ``` 3 7 8 9 ```
C++
UTF-8
1,533
2.578125
3
[]
no_license
#ifndef ABONNEMENT_H #define ABONNEMENT_H #include <QWidget> namespace Ui { class Abonnement; } class Abonnement : public QWidget { Q_OBJECT public: int getID_Abonnement(); void setID_Abonnement(int id_abonnement); int getDuree(); void setDuree(int duree); int getID_Abonne(); void setID_Abonne(int ID_abonne); QString getType(); void setType(QString type); QString getDate_Debut(); void setDate_Debut(QString dated); QString getDate_Fin(); void setDate_Fin(QString datef); double getPrix(); void setPrix(double prix); /*************************************************************************************************************************************************/ explicit Abonnement(QWidget *parent = nullptr); /* Abonnement(); Abonnement(int id_abonnement,int duree,QString dated,QString datef,float prix); Abonnement(const Abonnement &a);*/ ~Abonnement(); void ajouter_Abonnement(int ID_Anonnement,QString Type,double Prix,QString Date_Fin,int Duree,int ID_Abonne); void supprimer_Abonnement(); void modifier_Abonnement(); void afficher_Abonnement(int a); private slots: void on_Back_clicked(); void on_Cours_clicked(); void on_Stock_clicked(); void on_Promotion_clicked(); void on_Abonne_clicked(); private: Ui::Abonnement *ui; int ID_Abonnement; QString Type; double Prix; QString Date_Debut; QString Date_Fin; int Duree; int ID_Abonne; }; #endif // ABONNEMENT_H
Java
UTF-8
1,657
4.09375
4
[]
no_license
/* * testarray is a driver program testing all the methods constructed in Arraylist.java */ public class testarray { public static void main(String[] args) { //Method 1 Arraylist() Arraylist a = new Arraylist(); System.out.println("Default Arraylist Constructed"); //Method 2 Arraylist(n) Arraylist b = new Arraylist(5); System.out.println("Arraylist Constructed with 5 Elements"); //Method 7 isEmpty() System.out.println("The default Arraylist is not populated: " + a.isEmpty()); //Method 3 add() for(int i = 0; i < 15; i++){ a.add(i); } System.out.println(a.toString() + "The add method is successful"); System.out.println("The default array is not populated: " + a.isEmpty()); //Method 4 add( , ) a.add(5, "FIVE!"); a.add(8, "Eight"); System.out.println(a.toString() + "This add method(index, x) is also successful"); //Method 5 get() System.out.println("The get() method clearly works--Index 5: " + a.get(5)); //Method 6 size() System.out.println("The size() method works as well--Size of b: " + b.size()); for(int i = 0; i < 8; i++){ b.add(i); } System.out.println("The size( method now surely works--Size of b: " + b.size()); //Method 8 isIn() System.out.println("The isIn() method works--is the String HI in b? " + b.isIn("HI")); b.add("HI"); System.out.println("Now is the String HI in b? " + b.isIn("HI")); //Method 9 find() System.out.println("At what index is String FIVE! in Arraylist a? " + a.find("FIVE!")); //Method 10 remove() a.remove("FIVE!"); System.out.println("String FIVE! has been removed from Object a: " + a.toString() ); } }