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
C++
UTF-8
675
3.046875
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main () { string nim[5],nama[5],tanggal_lahir[5]; for (int i = 0; i < 5; ++i) { if (i == 3 || i == 4) { nim[3] = "190030462"; nama[3] = "cahyadi"; tanggal_lahir[3] = "2000-10-22"; nim[4] = "190030461"; nama[4] = "cahyadi2"; tanggal_lahir[4] = "2000-10-22"; }else{ cout << "nim :"; cin >> nim[i]; cout << "nama :"; cin >> nama[i]; cout << "tanggal lahir :"; cin >> tanggal_lahir[i]; } } for (int i = 0; i < 5; ++i) { if (i != 0) { cout << nim[i] << '\n'; cout << nama[i] << '\n'; cout << tanggal_lahir[i] << '\n'; } } return 0; }
Python
UTF-8
2,308
2.640625
3
[]
no_license
from django.core.management.base import BaseCommand, CommandError from lyrics.models import Song, Artist, Lyrics import requests import bs4 from datetime import datetime, timedelta import time from tqdm import tqdm from lyrics.models import Song, Artist class Command(BaseCommand): def handle(self, *args, **options): all_songs = Song.objects.all() error_counter = 0 def format_song(song): punctuation = ['?', ':', ';', '.', '!', '/', '\"', '\'', '&', '*'] song = song.lower().replace(' ', '-').replace('\n', '') song = ''.join(c for c in song if c not in punctuation) return song def format_artist(artist): punctuation = ['?', ':', ';', '.', '!', '/', '\"', '\'', '&', '*'] artist = artist.lower().replace(' ', '-').replace('\n', '') artist = ''.join(c for c in artist if c not in punctuation) return artist def getArtistSong(url, artist_name, song_name, artist_fk, song_fk, error_counter): try: res = requests.get(url) res.raise_for_status() except Exception as e: error_counter += 1 pass soup = bs4.BeautifulSoup(res.text, 'html.parser') #gets all song lyrics and saves to db lyrics = '' for ana in soup.findAll('p', class_='verse'): if ana.text != 'about' and ana.text != 'site map': lyrics += (' ' + ana.text.replace('\ br', '').replace('\n', ' ')) #print (lyrics) Lyrics.objects.update_or_create\ ( artist=artist_fk, song=song_fk, \ defaults={'lyrics': lyrics} ) for song in tqdm(all_songs): time.sleep(1) song_fk = song artist_fk = song.artist song_name = format_song(song.name) artist_name = format_artist(song.artist.name) #print (song_name, artist_name) getArtistSong('http://www.metrolyrics.com/' + song_name\ + '-lyrics-' + artist_name + '.html', song_name, artist_name, artist_fk, song_fk, error_counter) print ('You had a ' + str(error_count/all_songs.count()*100) + ' success rate.')
Markdown
UTF-8
3,236
2.78125
3
[]
no_license
This project contains automated e2e protractor tests that I wrote for a company app. It also contains api calls to our server, that will create an image of the product that our app runs on, and run the tests against it on that platform. It will then fetch and display the data nicely. # When first checking this project from Git, install composer, and run ```composer install``` # Virtualizing the 811 When creating a new test server do the following steps. When updating the existing server, see below "Updates to 811". #### Creating an 811 image The image used to flash 811s in production will not work for our purposed. Create your own image by booting the 811 you’d like to virtualize. Then, from a different computer, run this command: ``` ssh root@192.168.168.50 "dd if=/dev/mmcblk0 | gzip -1 -" | dd of=mnc811.gz ``` ###### Creating the virtual box harddrive The resulting file is a gzipped image (should be around 2GB, decompressed 30G, make sure you have space for this). On the host machine, decompress this file. For convenience, rename the resulting file to include an extension, say ```.img```. Then (install virtualbox) and run this command: ``` VBoxManage convertfromraw -format VDI mnc.img mncVDI.vdi ``` Then, open virtual box using ``` sudo virtualbox ``` Then, 1. Create a new box (64-bit) using the new VDI file (“Use an existing virtual hard drive file”). Call this VM "primary". 2. Give it at least 2GB or RAM (4GB used in test) 3. System > Enable EFI (special OSes only) 4. Boot up the 811, and create a snapshot of the current state. Name this snapshot v1.5.8 (or whatever the version is). 5. Turn off the VM when done (important!) That’s it! ###### Updates to the 811 If you simply want to add a new version of the 811 to the platform, open virtualbox, and select the box called ```primary```. Then, 1. Click on Snapshots, and select that latest Snapshot. 2. Restore it and run it. Ignore warning, and don't create snapshot of current state as prompted 3. In your browser go to 192.168.168.50/mnc, log in and run the MNC update as usual 4. After the update is done, save the current state of the VM under a new snapshot and call it v1.5.9 (or whatever the version is). # Configuring the testing platform In order to set up the automated testing platform, make sure to first install a few things: - Google Chrome - NodeJS - Java - Apache (configure it to host the www folder) - MySQL (install the ```base.sql``` DB in there and configure ```api/DB.php``` with the right MySQL credentials) Then, run ``` npm install -g ionic npm install -g @ionic/v1-toolkit npm install -g protractor-beautiful-reporter npm install -g protractor webdriver-manager update webdriver-manager start ``` For the last line (```webdriver-manager start```) leave this terminal window open. Also this command seems to give problems down the line when run over SSH. Finally from the directory of this project (where you have package.json) run ```npm install```. ### Updating the test specs When making updates to the e2e protractor spec files, manually FTP them over to the server, at ```/var/www/html/tests/e2e``` Any changes to protractor's conf.js should be done in ```do_test.php``` which overrides this file
Shell
UTF-8
2,185
3.8125
4
[ "MIT", "BSD-3-Clause" ]
permissive
#!/bin/bash # Exit with status 1 if any command below fails set -e # Exit if it's not a branch we're interested in being thorough about if echo $(git rev-parse --symbolic-full-name HEAD) | \ egrep -q '^refs/heads/(t/)'; then exit 0 fi # These are the locations I keep my temporary source and build trees in PRODUCTS=$(./acprep products) # generates a build directory name such as # ~/Products/ledger if echo $PRODUCTS | grep -qv ledger; then PRODUCTS=$PRODUCTS/ledger fi TMPDIR=$PRODUCTS/pre-commit MIRROR=$PRODUCTS/pre-commit-mirror # Checkout a copy of the current index into MIRROR git checkout-index --prefix=$MIRROR/ -af # Remove files from MIRROR which are no longer present in the index git diff-index --cached --name-only --diff-filter=D -z HEAD | \ (cd $MIRROR && xargs -0 rm -f --) # Copy only _changed files_ from MIRROR to TMPDIR, without copying # timestamps. This includes copying over new files, and deleting # removed ones. This way, "make check" will only rebuild what is # necessary to validate the commit. rsync -rlpgoDOc --delete --exclude-from=tools/excludes $MIRROR/ $TMPDIR/ # Everything else happens in the temporary build tree if [ ! -f $TMPDIR/lib/utfcpp/source/utf8.h ]; then rsync -a --delete lib/utfcpp/ $TMPDIR/lib/utfcpp/ fi cd $TMPDIR # Make sure there is a current Makefile. Regeneration of Makefile # happens automatically, but if myacprep or acprep changes, we want to # regenerate everything manually. If the user doesn't have acprep, look # for other common autoconf-related script files. if [ ! -f Makefile -o \ Makefile.in -nt Makefile -o \ configure -nt Makefile -o \ tools/Makefile.am -nt Makefile.in -o \ tools/configure.ac -nt configure -o \ \( -f acprep -a acprep -nt Makefile \) ] then if [ -f acprep ]; then echo Will run acprep in a moment elif [ -f autogen.sh ]; then sh autogen.sh && ./configure else autoreconf && ./configure fi fi # Finally, (re)build this proposed source tree and see if it passes # muster. if [ -f acprep ]; then nice -n 20 ./acprep default --warn make check else nice -n 20 make check fi exit 0
C++
UHC
923
3.078125
3
[]
no_license
/* : 踷 ȣ: 10799 Ǯ̹ : stack, ¥ : 18.10.04 Ÿ : */ #include<iostream> #include<vector> #include<algorithm> #include<string> #include<queue> using namespace std; vector<char> v; int main(void) { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); char c,save; int cnt = 0,res = 0; bool chk = false; while (cin >> c) { v.push_back(c); if (c == '(') cnt++; else if (c == ')') { if (cnt > 1) { chk = true; // ִſ ϱؼ if (save == '(') // ٷϱ. ߷ ŭ +=1 res += (cnt - 1); else // ƴ . res += 1; } else if (chk == true) res++; v.pop_back(); v.pop_back(); cnt -= 1; } if (v.size() == 0) chk = false; save = c; } cout << res << endl; return 0; }
Markdown
UTF-8
1,475
2.59375
3
[ "MIT" ]
permissive
--- title: Create --- # Create an Extension Add an ExtensionPackage to Extension to a Property. Installation is an asynchronous action. After performing a request to add an Extension to a Property, an Extension response will be returned with an `installation_status` of `pending`. When the installation task has completed, the Extension will be updated with based on the success or failure of the task. Extensions are processed asynchronously and have an `installation_status` attribute representing the current status of the Extension installation. There are three possible `installation_status` values: #### `pending` When an Extension is created, `installation_status` is set to `pending`. This indicates that DTM received the request to make the ExtensionPackage available as Extension to the specified Property, and will begin the installation process. Extensions with an `installation_status` of `pending` are not available for use. #### `succeeded` When processing of the installation request for the Extension has completed, if the installation was successful, the `installation_status` will change to `succeeded`. #### `failed` When processing of the installation request for the Extension has completed, if the installation was not successful, the `installation_status` will change to `failed`. Extensions with an `installation_status` of `failed` are not available for use. ## Attributes {% form extension.create %} {% scenario extensions.create %}
Java
UTF-8
25,847
1.929688
2
[]
no_license
package com.uuzu.mktgo.service; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Future; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import com.uuzu.mktgo.elasticsearch.PersonaSummary; import com.uuzu.mktgo.elasticsearch.PersonaSummaryppingRepository; import com.uuzu.mktgo.mapper.BrandModelMappingNewMapper; import com.uuzu.mktgo.mapper.DateMonthMapper; import com.uuzu.mktgo.pojo.*; import com.uuzu.mktgo.util.DateUtil; @Service @Slf4j public class OverviewBrandService { private static final String HBASE_TABLE = "persona_summary_prod"; private static final String NULLSRT = "NIL"; private static final String SPLIT_SYMBOL = "@"; // 分子 private static final String SPLIT_SYMBOL2 = "#"; @Autowired BrandModelMappingNewMapper brandModelMappingNewMapper; @Autowired private HbaseService hbaseService; @Autowired DateMonthMapper dateMonthMapper; @Autowired PersonaSummaryppingRepository personaSummaryppingRepository; @Autowired DictInfoService dictInfoService; @Autowired PicService picService; /** * @param brand * @param price * @param country * @param province * @param date * @return * @throws Exception */ public OverviewModel overviewBrand(String brand, String price, String country, String province, String date) throws Exception { // long start = System.currentTimeMillis(); OverviewModel overviewModel = new OverviewModel(); Map<String, Map<String, String>> list = new HashMap<String, Map<String, String>>(); CompletionService completionService = new ExecutorCompletionService(threadPoolTaskExecutor); String[] sixMonths = null; if (StringUtils.isBlank(date)) { date = dateMonthMapper.queryMaxMonth(); // holdingRankRowKey PersonaSummary personaSummary = new PersonaSummary(null, brand, price, country, province, date); // 将查询出的row key在hbase查询出值按imei_count降序 取出brand的所在位置。 completionService.submit(new OverviewBrandService.Task(getHoldingRankBoolQuery(generateBoolQuery(personaSummary, "brand", OperationEnum.EQ.getOperation())), "brand", "imei_count", 1000, list, "holdingRank")); sixMonths = DateUtil.getLastSixMonthDate(date, 6); for (String dateStr : sixMonths) { PersonaSummary personaSummaryByDate = new PersonaSummary(null, brand, price, country, province, dateStr); completionService.submit(new OverviewBrandService.Task(getSumByMonthBoolQuery(generateBoolQuery(personaSummaryByDate, "mnt", OperationEnum.EQ.getOperation())), "mnt", "imei_count", 1000, list, dateStr)); // sumRowKeysByCondition completionService.submit(new OverviewBrandService.Task(getSumByConditionBoolQuery(generateBoolQuery(personaSummaryByDate, "mnt", OperationEnum.EQ.getOperation()), brand), "mnt", "imei_count", 1000, list, dateStr + SPLIT_SYMBOL)); // 计算unknown completionService.submit(new OverviewBrandService.Task(generateBoolForUnknownQuery(personaSummaryByDate, "mnt", OperationEnum.EQ.getOperation()), "mnt", "imei_count", 1000, list, dateStr + SPLIT_SYMBOL2)); } // hot sell rank completionService.submit(new OverviewBrandService.Task(getHotSellRankBoolQuery(generateBoolQuery(personaSummary, "model", OperationEnum.EQ.getOperation()), brand), "model", "imei_count", 1000, list, "hotSellMap")); // px rank completionService.submit(new OverviewBrandService.Task(getPxRankBoolQuery(generateBoolQuery(personaSummary, "screensize", OperationEnum.EQ.getOperation()), brand), "screensize", "imei_count", 10000, list, "pxRank")); // os rank completionService.submit(new OverviewBrandService.Task(getOsRankBoolQuery(generateBoolQuery(personaSummary, "sysver", OperationEnum.EQ.getOperation()), brand), "sysver", "imei_count", 1000, list, "osRank")); } else { PersonaSummary personaSummary = new PersonaSummary(null, brand, price, country, province, date); completionService.submit(new OverviewBrandService.Task(getHoldingRankBoolQuery(generateBoolQuery(personaSummary, "brand", OperationEnum.EQ.getOperation())), "brand", "imei_count_incr", 1000, list, "holdingRank")); sixMonths = DateUtil.getLastSixMonthDate(date, 6); for (String dateStr : sixMonths) { PersonaSummary personaSummaryByDate = new PersonaSummary(null, brand, price, country, province, dateStr); completionService.submit(new OverviewBrandService.Task(getSumByMonthBoolQuery(generateBoolQuery(personaSummaryByDate, "mnt", OperationEnum.EQ.getOperation())), "mnt", "imei_count_incr", 1000, list, dateStr)); // sumRowKeysByCondition completionService.submit(new OverviewBrandService.Task(getSumByConditionBoolQuery(generateBoolQuery(personaSummaryByDate, "mnt", OperationEnum.EQ.getOperation()), brand), "mnt", "imei_count_incr", 1000, list, dateStr + SPLIT_SYMBOL)); completionService.submit(new OverviewBrandService.Task(generateBoolForUnknownQuery(personaSummaryByDate, "mnt", OperationEnum.EQ.getOperation()), "mnt", "imei_count_incr", 1000, list, dateStr + SPLIT_SYMBOL2)); } completionService.submit(new OverviewBrandService.Task(getHotSellRankBoolQuery(generateBoolQuery(personaSummary, "model", OperationEnum.EQ.getOperation()), brand), "model", "imei_count_incr", 1000, list, "hotSellMap")); completionService.submit(new OverviewBrandService.Task(getPxRankBoolQuery(generateBoolQuery(personaSummary, "screensize", OperationEnum.EQ.getOperation()), brand), "screensize", "imei_count_incr", 10000, list, "pxRank")); completionService.submit(new OverviewBrandService.Task(getOsRankBoolQuery(generateBoolQuery(personaSummary, "sysver", OperationEnum.EQ.getOperation()), brand), "sysver", "imei_count_incr", 1000, list, "osRank")); } for (int i = 0; i < 22; i++) { Future<String> future = completionService.take(); // log.info("thread=====" + future.get()); } setOverviewModelAttribute(overviewModel, list, brand, date, sixMonths); return overviewModel; } /** * @param overviewModel * @param resultList * @param brand * @param date * @param sixMonths */ private void setOverviewModelAttribute(OverviewModel overviewModel, Map<String, Map<String, String>> resultList, String brand, String date, String[] sixMonths) { Map<String, String> holdingRankMap = resultList.get("holdingRank"); Map<String, String> hotSellRankMap = resultList.get("hotSellMap"); Map<String, String> pxRankMap = resultList.get("pxRank"); Map<String, String> osRankMap = resultList.get("osRank"); List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(holdingRankMap.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, String>>() { public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { if (Long.valueOf(o2.getValue()) - Long.valueOf(o1.getValue()) > 0) { return 1; } else if (Long.valueOf(o1.getValue()) == Long.valueOf(o2.getValue())) { return 0; } else { return -1; } } }); int holding = 0; for (int i = 0; i < list.size(); i++) { Map.Entry<String, String> entry = list.get(i); if (StringUtils.equals(entry.getKey(), brand)) holding = i + 1; } overviewModel.setHolding(holding); // top 10 此处需要减少一个unknown List<OverviewBaseModel> market_share_brand = new ArrayList<>(); for (String key : sixMonths) { String unknownKey = key + SPLIT_SYMBOL2; Map<String, String> unknownMap = resultList.get(unknownKey); Double unknomnValue = null; if (MapUtils.isEmpty(unknownMap)) { unknomnValue = 0.0; } else { unknomnValue = Double.parseDouble(unknownMap.get(key)); } if (resultList.get(key + SPLIT_SYMBOL).get(key) == null || resultList.get(key).get(key) == null || StringUtils.equals(resultList.get(key + SPLIT_SYMBOL).get(key), "null") || StringUtils.equals(resultList.get(key).get(key), "null")) continue; market_share_brand.add(new OverviewBaseModel(key, Double.valueOf(resultList.get(key + SPLIT_SYMBOL).get(key)) / (Double.valueOf(resultList.get(key).get(key)) - unknomnValue))); } List<OverviewBaseListModel> market_share_brands = new ArrayList<>(); market_share_brands.add(new OverviewBaseListModel(brand, market_share_brand)); overviewModel.setMarket_share_brand(market_share_brands); overviewModel.setMarket_share_rank(resultList.get(date + SPLIT_SYMBOL).get(date) == null || resultList.get(date).get(date) == null || StringUtils.equals(resultList.get(date + SPLIT_SYMBOL).get(date), "null") || StringUtils.equals(resultList.get(date).get(date), "null") ? 0 : Double.valueOf(resultList.get(date + SPLIT_SYMBOL).get(date)) / (Double.valueOf(resultList.get(date).get(date)) - Double.valueOf((resultList.get(date + SPLIT_SYMBOL2) == null || resultList.get(date + SPLIT_SYMBOL2).get(date) == null) ? "0.0" : resultList.get(date + SPLIT_SYMBOL2).get(date)))); // top 10 List<BaseModel> hotSellBaseModels = new ArrayList<BaseModel>(); for (String key : hotSellRankMap.keySet()) { hotSellBaseModels.add(new BaseModel(key, hotSellRankMap.get(key) == null || resultList.get(date + SPLIT_SYMBOL).get(date) == null || StringUtils.equals(resultList.get(date + SPLIT_SYMBOL).get(date), "null") || StringUtils.equals(resultList.get(date + SPLIT_SYMBOL).get(date), "null") ? 0 : Double.valueOf(hotSellRankMap.get(key)) / Double.valueOf(resultList.get(date + SPLIT_SYMBOL).get(date)))); } overviewModel.setHot_selling_rank(getTop10(hotSellBaseModels)); // top 10 List<BaseModel> pxBaseModels = new ArrayList<BaseModel>(); for (String key : pxRankMap.keySet()) { pxBaseModels.add(new BaseModel(key, pxRankMap.get(key) == null || resultList.get(date + SPLIT_SYMBOL).get(date) == null || StringUtils.equals(resultList.get(date + SPLIT_SYMBOL).get(date), "null") || StringUtils.equals(resultList.get(date + SPLIT_SYMBOL).get(date), "null") ? 0 : Double.valueOf(pxRankMap.get(key)) / Double.valueOf(resultList.get(date + SPLIT_SYMBOL).get(date)))); } overviewModel.setPx_rank(getTop10(pxBaseModels)); // top 10 List<BaseModel> osBaseModels = new ArrayList<BaseModel>(); for (String key : osRankMap.keySet()) { osBaseModels.add(new BaseModel(key, osRankMap.get(key) == null || resultList.get(date + SPLIT_SYMBOL).get(date) == null || StringUtils.equals(resultList.get(date + SPLIT_SYMBOL).get(date), "null") || StringUtils.equals(resultList.get(date + SPLIT_SYMBOL).get(date), "null") ? 0 : Double.valueOf(osRankMap.get(key)) / Double.valueOf(resultList.get(date + SPLIT_SYMBOL).get(date)))); } overviewModel.setOs_rank(getTop10(osBaseModels)); overviewModel.setBrand(brand); overviewModel.setBrandPic(picService.getPicUrl(brand)); resultList = null; } /** * @param list * @return */ private List<BaseModel> getTop10(List<BaseModel> list) { if (CollectionUtils.isEmpty(list)) return list; Collections.sort(list, new Comparator<BaseModel>() { @Override public int compare(BaseModel o1, BaseModel o2) { if (o1.getValue() < o2.getValue()) { return 1; } else if (o1.getValue() == o2.getValue()) { return 0; } else { return -1; } } }); if (list.size() > 10) { list = list.subList(0, 10); } return list; } /** * @param boolQueryBuilder * @param brand * @return */ private BoolQueryBuilder getOsRankBoolQuery(BoolQueryBuilder boolQueryBuilder, String brand) { if (org.apache.commons.lang.StringUtils.isNotEmpty(brand)) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", brand)); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", NULLSRT)); } return boolQueryBuilder; } /** * @param boolQueryBuilder * @param brand * @return */ private BoolQueryBuilder getUnknownQuery(BoolQueryBuilder boolQueryBuilder, String brand) { return boolQueryBuilder; } /** * @param boolQueryBuilder * @param brand * @return */ private BoolQueryBuilder getPxRankBoolQuery(BoolQueryBuilder boolQueryBuilder, String brand) { if (org.apache.commons.lang.StringUtils.isNotEmpty(brand)) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", brand)); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", NULLSRT)); } return boolQueryBuilder; } /** * @param boolQueryBuilder * @param brand * @return */ private BoolQueryBuilder getHotSellRankBoolQuery(BoolQueryBuilder boolQueryBuilder, String brand) { if (org.apache.commons.lang.StringUtils.isNotEmpty(brand)) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", brand)); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", NULLSRT)); } boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery("brand", "other")); boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery("brand", "unknown")); boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery("model", "other")); return boolQueryBuilder; } /** * @param boolQueryBuilder * @param brand * @return */ private BoolQueryBuilder getSumByConditionBoolQuery(BoolQueryBuilder boolQueryBuilder, String brand) { if (org.apache.commons.lang.StringUtils.isNotEmpty(brand)) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", brand)); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", NULLSRT)); } return boolQueryBuilder; } /** * @param boolQueryBuilder * @return */ private BoolQueryBuilder getHoldingRankBoolQuery(BoolQueryBuilder boolQueryBuilder) { boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery("brand", NULLSRT)); boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery("brand", "other")); boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery("brand", "unknown")); return boolQueryBuilder; } /** * @param boolQueryBuilder * @return */ private BoolQueryBuilder getSumByMonthBoolQuery(BoolQueryBuilder boolQueryBuilder) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", NULLSRT)); return boolQueryBuilder; } /** * @param personaSummary * @param attrField * @return * @throws Exception */ private String getValueByField(PersonaSummary personaSummary, String attrField) throws Exception { Field field = personaSummary.getClass().getDeclaredField(attrField); field.setAccessible(true); return field.get(personaSummary).toString(); } /** * @param personaSummary * @param groupByField * @param operation * @return */ private BoolQueryBuilder generateBoolQuery(PersonaSummary personaSummary, String groupByField, String operation) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); if (org.apache.commons.lang.StringUtils.isNotEmpty(personaSummary.getMnt()) && OperationEnum.EQ.getOperation().equals(operation)) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("mnt", personaSummary.getMnt())); } else if (org.apache.commons.lang.StringUtils.isNotEmpty(personaSummary.getMnt()) && OperationEnum.GTL.getOperation().equals(operation)) { boolQueryBuilder.must(QueryBuilders.rangeQuery("mnt").gte(personaSummary.getMnt())); } else if (StringUtils.isNotEmpty(personaSummary.getMnt()) && OperationEnum.LTL.getOperation().equals(operation)) { boolQueryBuilder.must(QueryBuilders.rangeQuery("mnt").lte(personaSummary.getMnt())); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("mnt", NULLSRT)); } // if (org.apache.commons.lang.StringUtils.isNotEmpty(personaSummary.getBrand())) { // boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", personaSummary.getBrand())); // } else { // boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand", NULLSRT)); // } if (org.apache.commons.lang.StringUtils.isNotEmpty(personaSummary.getCountry())) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("country", personaSummary.getCountry())); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("country", NULLSRT)); } if (org.apache.commons.lang.StringUtils.isNotEmpty(personaSummary.getProvince())) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("province", personaSummary.getProvince())); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("province", NULLSRT)); } if (org.apache.commons.lang.StringUtils.isNotEmpty(personaSummary.getPrice_range())) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("price_range", personaSummary.getPrice_range())); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("price_range", NULLSRT)); } String[] fields = { "income", "carrier", "segment", "agebin", "network", "occupation", "edu", "price", "house", "screensize", "car", "married", "kids", "gender", "sysver", "brand_name", "model" }; for (String field : fields) { if (field.equals(groupByField)) { boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery(field, NULLSRT)); boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery(field, "-1")); boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery(field, "unknown")); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery(field, NULLSRT)); } } return boolQueryBuilder; } private BoolQueryBuilder generateBoolForUnknownQuery(PersonaSummary personaSummary, String groupByField, String operation) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); if (org.apache.commons.lang.StringUtils.isNotEmpty(personaSummary.getMnt()) && OperationEnum.EQ.getOperation().equals(operation)) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("mnt", personaSummary.getMnt())); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("mnt", NULLSRT)); } if (org.apache.commons.lang.StringUtils.isNotEmpty(personaSummary.getCountry())) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("country", personaSummary.getCountry())); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("country", NULLSRT)); } if (org.apache.commons.lang.StringUtils.isNotEmpty(personaSummary.getProvince())) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("province", personaSummary.getProvince())); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("province", NULLSRT)); } if (org.apache.commons.lang.StringUtils.isNotEmpty(personaSummary.getPrice_range())) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("price_range", personaSummary.getPrice_range())); } else { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("price_range", NULLSRT)); } boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("brand_name", "unknown")); String[] fields = { "income", "carrier", "segment", "agebin", "network", "occupation", "edu", "price", "house", "screensize", "car", "married", "kids", "gender", "sysver", "model", "brand" }; for (String field : fields) { boolQueryBuilder.must(QueryBuilders.matchPhraseQuery(field, NULLSRT)); } return boolQueryBuilder; } @Autowired private ThreadPoolTaskExecutor threadPoolTaskExecutor; /** * task */ class Task implements Callable { private BoolQueryBuilder boolQueryBuilder; private String attrField; private String countField; private int size; private String key; private Map<String, Map<String, String>> resultMap; public Task(BoolQueryBuilder boolQueryBuilder, String attrField, String countField, int size, Map<String, Map<String, String>> resultMap, String key) { this.boolQueryBuilder = boolQueryBuilder; this.attrField = attrField; this.countField = countField; this.size = size; this.resultMap = resultMap; this.key = key; } @Override public String call() { try { Pageable pageable = new PageRequest(0, size); SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(boolQueryBuilder).build(); Page<PersonaSummary> search = personaSummaryppingRepository.search(searchQuery); Map<String, String> result = new HashMap<>(); for (PersonaSummary summary : search) { result.put(getValueByField(summary, attrField), summary.getRow_key().replace("\u0000", "\u0001")); } Map<String, String> hbaseResult = hbaseService.getResultByHbaseTable(result, countField, HBASE_TABLE); resultMap.put(key, hbaseResult); return "success"; } catch (Exception e) { log.error(e.getMessage(), e); } return null; } } }
Python
UTF-8
1,972
2.625
3
[]
no_license
from datetime import datetime import psycopg2 import logging import sys log_filename = "log_{}.log".format(datetime.now().strftime('%d-%m-%Y')) logger = logging.getLogger('converter') hdlr = logging.FileHandler(log_filename) formatter = logging.Formatter('%(asctime)s %(levelname)s %(massage)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) class Connection(): _db=None def __init__(self,nhost,db,usr,pswd): try: self._db = psycopg2.connect( host=nhost, database=db, user=usr, password=pswd ) except Exception as ex: logger.error("Connection error __init__") logger.error(ex) print("Connection error.") sys.exit(-1) def insertion(self,sql,tup): try: cur = self._db.cursor() cur.executemany(sql,tup) cur.close() self._db.commit() except Exception as ex: logger.error(ex) self._db.rollback() return False return True def manipulate(self,sql): try: cur = self._db.cursos() cur.execute(sql) cur.close() self._db.commit() except Exception as ex: logger.error(ex) self._db.rollback() print('Erro on manipulation') return False return True def query(self,sql): rs=None try: cur=self._db.cursor() cur.execute(sql) rs=cur.fetchall() except Exception as ex: logger.error(ex) self._db.rollback() return None return rs def close(self): try: self._db.close() except Exception as ex: logger.error(ex) return None return ">>>closed"
JavaScript
UTF-8
782
2.859375
3
[ "MIT" ]
permissive
'use strict' const choiceMatrix = [ ['multi', 'expanded', 'checkboxes'], ['select', 'expanded', 'radio'], ['multi', 'collapsed', 'select'], ['select', 'collapsed', 'select'] ] module.exports = function (el) { if (el.type === 'boolean') { return el } if (el.options && el.type !== 'checkbox') { const keys = Object.keys(el.options) el.options = keys.reduce((arr, key) => { arr.push({value: el.options[key], id: key.replace(/\s/g, '')}) return arr }, []) let row = 0 while (row < choiceMatrix.length) { const values = choiceMatrix[row] if (el.type === values[0] && el.mode === values[1]) { el.type = values[2] el.multi = values[0] === 'multi' break } row++ } } return el }
JavaScript
UTF-8
1,306
2.53125
3
[ "MIT" ]
permissive
/** * Created by swx on 2018/1/31. * 用来格式化body的样式 */ 'use strict' const TAG = '[BODYFOMAT]' const creatError = require('http-errors') function isApiRequest(path) { return path && (path.indexOf('/api') === 0) } module.exports = options => { return async function (ctx, next) { try { await next() // 不处理非api请求 if (!isApiRequest(ctx.path)) { return } let body = ctx.body let content = {} if (body) { let { code, msg, data } = body if (code || msg || data) { // 已经格式化 if (code) { content.retcode = code } if (msg) { content.retdesc = msg } if (data) { content.data = data } } else { if (typeof body === 'string') { content.retdesc = body } else { content.data = body } } ctx.body = content } } catch (ex) { if (isApiRequest(ctx.path) && ex instanceof creatError.HttpError) { let status = +ex.status if (status > 500 && status < 600) { ctx.logger.error(TAG, ctx.x_request_id, ex) } ctx.status = status } else { throw ex } } } }
C
UTF-8
1,202
3.671875
4
[]
no_license
/* * linkbintree.c * * Created on: 2018年8月27日 * Author: zhoubo */ #include "linkbintree.h" //创建二叉树 //返回:二叉树结构体指针 BinTree *BinTreeCreate(void) { BinTree *r; u8 ch; if((ch=getchar())=='#') return NULL; else { r=(BinTree *)malloc(sizeof(BinTree)); //申请空间 r->data=ch; //生成根节点 r->lchild=BinTreeCreate(); //构造左子树 r->rchild=BinTreeCreate(); //构造右子树 } return r; } //前序遍历二叉树 void PreOrder(BinTree *r) { if(r!=NULL) { printf(" %c",r->data); //当前节点 PreOrder(r->lchild); //先序遍历左子树 PreOrder(r->rchild); //先序遍历右子树 } } //中序遍历二叉树 void InOrder(BinTree *r) { if(r!=NULL) { PreOrder(r->lchild); //中序遍历左子树 printf(" %c",r->data); //当前节点 PreOrder(r->rchild); //中序遍历右子树 } } //后序遍历二叉树 void PostOrder(BinTree *r) { if(r!=NULL) { PostOrder(r->lchild); //中序遍历左子树 PostOrder(r->rchild); //中序遍历右子树 printf(" %c",r->data); //当前节点 } }
Python
UTF-8
522
4.34375
4
[]
no_license
''' Um comerciante comprou um produto e quer vendê-lo com um lucro de 45% se o valor da compra for menor que R$ 20,00; caso contrário, o lucro será de 30%. Elabore um algoritmo em Python que leia o valor do produto e mostre na tela o valor de venda para o produto. ''' valor_produto = float(input('Digite o valor do produto: ')) if valor_produto <= 20: print( 'O valor de venda é R$ {}.'.format((valor_produto * 1.45 ))) else: print( 'O valor de venda é R$ {}.'.format((valor_produto * 1.30 )))
C++
UTF-8
733
2.515625
3
[]
no_license
#include "Collision.h" #include <Engine.h> void thomas::Collision::Update(float aDeltaTime) { m_Sprite.Update(&m_Transform, aDeltaTime); } void thomas::Collision::Draw() { GetGraphic().Draw(m_Collider); m_Sprite.Draw(GetGraphic()); } void thomas::Collision::Start() { std::string tString = "collision.png"; int w, h; m_TextureId = GetGraphic().LoadTexture(tString); m_Transform.SetPosition(150, 45); GetGraphic().GetTextureSize(m_TextureId, &w, &h); m_Transform.SetHeight(h); m_Transform.SetWidth(w); GetGraphic().LoadTexture(tString); m_Sprite.Load(GetGraphic(), tString); m_Collider.Set(m_Transform.X, m_Transform.Y, m_Transform.Width, m_Transform.Height); } void thomas::Collision::Destroy() { delete this; }
Java
UTF-8
696
3.1875
3
[]
no_license
package sec04.exam06; import java.util.Scanner; public class MemberServiceExample { public static void main(String[] args) { MemberService memberService = new MemberService(); Scanner scanner = new Scanner(System.in); System.out.print("아이디를 입력하세요: "); String inputId = scanner.nextLine(); System.out.print("비밀번호를 입력하세요: "); String inpudPw = scanner.nextLine(); boolean login = memberService.login(inputId, inpudPw); if(login == true) { System.out.println("로그인 되었습니다."); memberService.logout(inputId); } else { System.out.println("아이디 또는 비밀번호가 올바르지 않습니다."); } } }
Python
UTF-8
122
3.03125
3
[]
no_license
# -*- coding utf-8 -*- s1 = 72 s2 = 85 result = 'percent:(%d - %d)/100 = %.2f%%' % (s2, s1, (s2-s1)) print(result)
C
UTF-8
894
3.609375
4
[]
no_license
#include<stdio.h> int gap; void christmas_tree(int,int); int main() { int N,i,l=0; scanf("%d",&N); if(N<=1) printf("\nYou cannot generate Christmas tree"); else if(N>20) printf("\nThe Tree is no More\n"); else { // First One pyramid christmas_tree(1,N+1); // Others for(i=2;i<N;i++,l++) christmas_tree(2,N-l); //Stand of the Tree for( i=0;i<=gap;i++) printf(" "); printf("*\n"); for( i=0;i<=gap;i++) printf(" "); printf("*"); } return 0; } void christmas_tree(int a,int N) { int row,Sp,Stars; static int space=0; for(row=a; row<=N; row++) { // Blank Spaces for(Sp=1;Sp<=N+space-row;Sp++) printf(" "); // Stars Printing for(Stars=1;Stars<=2*row-1;Stars++) printf("*"); printf("\n"); } space++; gap=space; }
Markdown
UTF-8
11,215
2.625
3
[]
no_license
![](https://i.imgur.com/emcU0vv.gif) ***Installation:*** ``` npm i -g @halfhelix/kit ``` This is a toolkit that we use internally at Half Helix to develop our frontend Shopify themes. It enables us to develop websites the way that we want to, with a focus on modularity. > This package is currently in Beta. It is likely to change quickly as we prepare it for initial release. #### Core technologies included: - Webpack - Webpack Dev Middleware - Sass - Babel - BrowserSync - Eslint - Stylelint #### Core Benefits: - Compile easily and quickly with Webpack - See Javascript and CSS changes without a round-trip to Shopify - Browser Reloading after Liquid file upload to Shopify - Proxy the Shopify instance with BrowserSync - Lint CSS and Javascript with Eslint and Stylelint - Compile SASS and autoprefix on build (with sourcemaps in dev) - Leverage individual module folders (see below) - Automatic JS module chunking - Concatination of Shopify settings schema from multiple JSON files #### Commands Run these commands from the root of the theme ``` kit build --env [production|staging|development] kit deploy --env [production|staging|development] kit watch --env [production|staging|development] ``` #### Theme architecture We have plans to release the starter theme we use for our Shopify sites over time to sit alongside this toolkit. In the meantime, see here for a little information about how our these are structured. This is the environment in which this toolkit is used. ``` .env .eslintrc.js .stylelintrc.js kit.config.js webpack.config.js ... src |- assets | |- scss | | |- lib | | |- main.scss | | | |- js | | |- lib | | |- main.js | | | |- images | |- fonts | |- config | |- lib | |- section-a.json | |- section-b.json | |- layout |- locales |- sections |- snippets | |- gtm.liquid | |- no-index.liquid | |- templates |- modules |- header | |- header.js | |- header.liquid | |- header.scss | |- footer |- newsletter-signup |- ... ``` Here, the header, footer and newsletter-signup code is encapsulated inside module folders, in this example. These module folders are a concept that helps us reuse code and keep track of logic, markup and styles across complex themes. This toolbelt enables this architecture by supporting glob patterns like the examples provided below. ``` // main.scss // Our Webpack loader takes this glob pattern and injects found // files into the bundle. @import "modules/**/*.scss"; // main.js // Our Webpack loader similarly takes this glob pattern and // injects found files into the bundle. It'll also chunk the // files together based on folder. import 'modules/**/*.js' ``` In addition to style and Javascript files, Liquid is taken out of these module folders and sent to the Snippets, Sections or Templates theme directories. For example: ``` src/modules/header/header.liquid > snippets/header.liquid src/modules/global/header/header.liquid > snippets/header.liquid src/modules/header/header.section.liquid > sections/header.liquid src/modules/cart/cart.template.liquid > templates/header.liquid ``` #### Configuration The toolkit can be configured through a `kit.config.js` file that must be present in the root of the theme. In addition, an `.env` file is supported to store secrets that should not be stored in Git. ``` // .env (Git ignore) THEME_ID=xxxx PASSWORD=xxxx STORE=xxxx.myshopify.com // kit.config.js (store in Git) module.exports = { themes: { development: { theme: process.env.THEME_ID, password: process.env.PASSWORD, store: process.env.STORE, ignore: [ 'config/settings_data.json' ] }, staging: { ... }, production: { ... } }, babel: { plugins: [ '@babel/plugin-proposal-object-rest-spread' ], "sourceMaps": true, "presets": [ "@babel/preset-env" ], }, 'path.cdn': 'https://cdn.shopify.com/s/files/1/0234/4347/2480/t/25/assets/' } ``` #### All kit.config.js options (with defaults) ``` { // Environment-specific theme configuration // The current environment's theme settings are merged // in with the global settings object at runtime 'themes': { development: {}, staging: {}, production: {} }, // Babel configuration 'babel': {}, // Path to Webpack config.js 'path.webpack': `${CWD}/webpack.config.js`, // Path to folder that the built theme will be compiled to 'path.dist': `${CWD}/dist`, // Path to theme src files 'path.src': `${CWD}/src`, // URL root of assets when accessed in the 'watch' command 'path.public': `/dev/`, // The HMR resource that is added to the bundle in 'watch' 'path.hmr': 'webpack-hot-middleware/client?reload=true', // The theme's CDN URL (used in 'watch' only, relates to "addShopifyLoader") 'path.cdn': 'https://cdn.shopify.com/replace-this', // The global variable used in production to reference the Shopify CDN 'cdnPathVar': '__GLOBAL__.cdn', // The log file to use for non-errors (See 'logging') 'path.stdout': `${CWD}/node_modules/.logs/kit-stdout.log`, // The log file to use for errors (See 'logging') 'path.stderr': `${CWD}/node_modules/.logs/kit-stderr.log`, // The function to return the BrowserSync proxy target URL 'target': (settings) => { return `https://${(settings.domain || settings.store)}?preview_theme_id=${settings['theme']}` }, // The Shopify theme custom domain, if enabled on the instance 'domain': false, // e.g 'shop.halfhelix.com' // The local URL that should be used to access the proxy 'local': 'localhost', // Customizes the placement of the BrowserSync snippet in 'watch' 'browserSyncSnippetPlacement' (settings) { return { match: /<\/body>/i, fn: function (snippet, match) { return snippet + match; } } }, // Should Webpack Hot Module Reloading be enabled? 'hmr': true, // Ignore certain files from being uploaded to Shopify // Can be on this global level or on the theme level 'ignore': [ 'config/settings_data.json' ], // Should styles be linted with Stylelint? 'lintStyles': true, // What files should be linted with Stylelint? 'stylelintPaths' (settings) { return [ `src/assets/scss/**/*.scss`, `src/modules/**/*.scss`, `src/sections/**/*.scss` ] }, // Should CSS be autoprefixed in the 'watch' command? 'autoprefixInDev': false, // Should BrowserSync automatically open a new tab in 'watch'? 'open': true, // What files should be watched for changes in 'watch'? 'watch': (settings) => { return `${settings['path.src']}/**/*` }, // What is the name of the CSS file generated in 'build|deploy'? 'cssName': '[name].min.css.liquid', // The delay between the Shopify upload and the browser reload 'reloadDelay': 700, // Customize the order of assets returned in the CSS/ JS globs 'sortFunction': false, // (files = [], javascript?) => {} // Perform replacements of asset strings with 'watch' 'replaceAssets': true, // The theme HTML asset strings to dynamically replace. We do this // to support Hot Module Reloading in 'watch' 'proxyReplacements': [{ 'regex': /<script.*main(?:[.]min)?[.]js.[^>]*><\/script>/ig, 'replacement' () {} },{ 'regex': /<link.*main(?:[.]min)?[.]css.[^>]*>/ig, 'replacement' (settings) { return `<script src="${settings['path.public']}/main.js"></script>` } }], // Auto-chunk the main JS bundle based on module parent directory 'autoChunk': true, // Interpret {{ ... | asset_url }} tags in Sass files, in 'watch' // The 'path.cdn' is used to replace the 'asset_url' filter 'addShopifyLoader': true, // Always log errors and info to the console 'debug': false } ``` #### Webpack configuration This example provides the necessary elements of the Webpack configuration file required in the root of the theme. It is our recommendation to follow this and deviate with care, in these initial versions at least. ``` // webpack.config.js module.exports = { devtool: 'eval-source-map', optimization: { splitChunks: { automaticNameDelimiter: '-', } }, entry: { "main": [ './src/assets/css/main.scss', './src/assets/js/main' ] }, output: { path: path.join(__dirname, 'dist/assets'), filename: '[name].js', chunkFilename: `[name].js?version=${Date.now()}` }, module: { rules: [ { enforce: "pre", test: /\.js$/, exclude: /node_modules/, loader: "eslint-loader", }, { test: /\.js$/, loader: 'babel-loader' }, { test: /\.s?css$/, extract: true, use: [ 'style-loader', { loader: 'css-loader', options: { importLoaders: 1, sourceMap: true } }, { loader: 'sass-loader', options: { sourceMap: true } } ] }, ] }, resolve: { alias: {...}, } } ``` #### NPM Dependencies Most of the dependencies that are used to compile assets with the Webpack configuration above are declared and managed in this package. However, there are some that will need to be dev dependencies of the theme itself. Currently, the theme dev dependencies we use for the configuration above are: ``` "@babel/core": "^7.7.7", "@babel/plugin-proposal-object-rest-spread": "^7.7.7", "@babel/preset-env": "^7.7.7", "eslint-config-standard": "^14.1.0", "standard": "^14.3.1", "stylelint-config-standard": "^19.0.0", ``` #### Logging Most logs from core dependencies are relayed directly to the console. However, there are certain compilation logs that Webpack and other dependencies do not provide configuration access to, and that we occasionally want to silence. When compilation occurs, we redirect these outputs to log files rather than directly to the browser. However, this can be turned off via the `debug` setting. #### Roadmap 1. Renaming of Shopify theme/s upon deployment 2. Theme scaffolding command/s 3. Critical CSS support baked in 4. Liquid linting (in progress...) #### Bugs & Missing Information This package is currently unstable and in it's initial stages. Expect bugs and missing information. We encourage you to submit tickets and let us know the issues you are experiencing! Keep in mind that our current priority is to enable our internal developers so expect delays for general bug reports. #### Testing changes when contributing Currently, the recommended way to test new changes to this repo is via the following steps: - Clone this monorepo - Install lerna globally - In the root of the repo, run `lerna bootstrap` - Uninstall the global @halfhelix/kit package `npm uninstall -g @halfhelix/kit` - Install the local cli package globally `npm i -g /Users/.../packages/cli` - In the root of your theme, run the global Kit commands - When ready, submit a MR with the changes - The changes will be reviewed and released (`lerna publish` or `lerna version && lerna run publish`)
Shell
UTF-8
836
3.5625
4
[]
no_license
#!/bin/bash # PLEASE NOTE # # while this script has some safety measures (won't restart the node if other(s) are down) # you should *always* use `ansible -f 1 ...` for a gentle / rolling restart of the cluster # # Description: hackish rolling upgrade of a riak cluster for Debian/Ubuntu OS # drop the ball if riak/riak-admin are not found [ -f /etc/riak/vm.args ] || exit 1 which riak-admin || exit 1 sudo riak-admin transfer-limit | grep offline &>/dev/null ret=$? # exit if any (riak) nodes are down [ $ret -ne 1 ] && exit 2 sudo /etc/init.d/riak stop # install / upgrade riak but keep the current configs sudo dpkg -E --force-confold -i /binaries/riak1412.deb sudo /etc/init.d/riak start node_name=$(head /etc/riak/vm.args | grep -E '^-name' | tr -s " " | cut -d" " -f2) sudo riak-admin wait-for-service riak_kv $node_name
Python
UTF-8
1,635
3.671875
4
[]
no_license
# # @lc app=leetcode id=264 lang=python3 # # [264] Ugly Number II # # https://leetcode.com/problems/ugly-number-ii/description/ # # algorithms # Medium (35.66%) # Total Accepted: 98.5K # Total Submissions: 275.7K # Testcase Example: '10' # # Write a program to find the n-th ugly number. # # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.  # # Example: # # # Input: n = 10 # Output: 12 # Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 # ugly numbers. # # Note:   # # # 1 is typically treated as an ugly number. # n does not exceed 1690. # # class Solution: def nthUglyNumber(self, n: int) -> int: # ugly = [1] # i2 = i3 = i5 = 0 # # each prime 2, 3, 5 have an index to the next number that # # can be multiplied with the prime to produce a new ugly number # while len(ugly) < n: # while ugly[i2] * 2 <= ugly[-1]: # i2 += 1 # while ugly[i3] * 3 <= ugly[-1]: # i3 += 1 # while ugly[i5] * 5 <= ugly[-1]: # i5 += 1 # ugly.append(min(ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5)) # return ugly[-1] # using heap # keep the store stores a tuple (val, factor) # factor value: the last factor that the number was multiplied to import heapq h = [(1, 1)] for _ in range(n): val, factor = heapq.heappop(h) for p in 2, 3, 5: if factor <= p: heapq.heappush(h, (val * p, p)) return val
Java
UTF-8
939
2.25
2
[]
no_license
package com.example.duongthuhien.kltn.Adapter; import android.app.Activity; import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import java.util.List; /** * Created by Duong Thu Hien on 6/8/2018. */ public class BaiHoc_Minna_adapter extends ArrayAdapter { Activity context; int resource; @NonNull List objects; public BaiHoc_Minna_adapter(@NonNull Activity context, int resource, @NonNull List objects) { super(context, resource, objects); this.context=context; this.resource=resource; this.objects=objects; } public View getView(final int pos, View convertView, ViewGroup parent){ LayoutInflater inflater=this.context.getLayoutInflater(); View row=inflater.inflate(this.resource,null); return row; } }
Go
UTF-8
452
3.390625
3
[]
no_license
package main import "fmt" func asciiReverseString(s []byte) { l := len(s) for i := range s { if l/2 <= i { break } s[i],s[l-i-1] = s[l-i-1],s[i] } fmt.Println(string(s)) } func testReverseInt(s []int) { l := len(s) for i := range s { if l/2 <= i { break } fmt.Println(i,l-i-1) s[i],s[l-i-1] = s[l-i-1],s[i] } fmt.Println((s)) } func main() { asciiReverseString([]byte("hello")) testReverseInt([]int{1,2,3,4}) }
Java
UTF-8
696
1.804688
2
[]
no_license
package com.mit.easyDonationBackendV6.Service; import com.mit.easyDonationBackendV6.Dto.*; import com.mit.easyDonationBackendV6.Model.HospitalRequirement; import java.util.List; public interface AdminService { void acceptRequirement(RequirementIdDto requirementIdDto); void rejectRequirement(RequirementIdDto requirementIdDto); void approveBudget(AdminApprovalBudgetDto adminApprovalBudgetDto); void rejectBudget(AdminApprovalBudgetDto adminApprovalBudgetDto); List<LandingPageViewRequirementDto> getPendingRequirements(); List<DonationDto> viewAllDonations(); List<BudgetDetailsDto> viewAllBudgetDetails(); List<BudgetDetailsDto> viewPendingBudgetDetails(); }
Python
UTF-8
1,077
3.75
4
[]
no_license
# filter map apply reduce array = [-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10] # new_array = filter(lambda x: x > 0, array) # # print(list(new_array)) # new_array = [i for i in array if i > 0] # # print(new_array) # ЗАДАНИЕ # написать функцию, которая на вход принимает массив и возвращает массив чисел, которые делятся на два ########################################################################### # практика ########################################################################## # new_array = map(lambda x: x * x, array) # # print(list(new_array)) ########################################################################### # list1 = [7, 2, 3, 10, 12] # list2 = [-1, 1, -5, 4, 6] # # new_array = map(lambda x, y: x*y, list1, list2) # # print(list(new_array)) ########################################################################### # практика ###########################################################################
Python
UTF-8
1,117
3.6875
4
[]
no_license
from math import sqrt from time import time # ONE LINER (extremely slow) print(sum([x for x in range(2, 2000000) if not [y for y in range(2, int(sqrt(x))+1) if x % y == 0]])) prime_cache = [] def is_prime_dynamic(n): if n == 2: return True if n < 2 or not n % 2: return False for p in prime_cache: if p > sqrt(n): break if n % p == 0: return False prime_cache.append(n) return True def primes_dynamic(n): i = 2 while i < n: if is_prime_dynamic(i): yield i i += 1 + (i % 2) # RUN print(primes_dynamic(2000000)) def is_prime(n): if n == 2: return True if n < 2 or not n % 2: return False for i in range(3, int(sqrt(n)) + 1, 2): if n % i == 0: return False return True def primes(n): i = 2 while i < n: if is_prime(i): yield i i += 1 + (i % 2) #BENCHMARK # def test1(): # sum(primes(2000000)) # # def test2(): # sum(primes_dynamic(2000000)) # # def bm(f, n): # t0 = time() # for _ in range(n): # f() # t1 = time() # print(t1-t0) # # bm(test1, 1) # bm(test2, 1)
PHP
UTF-8
2,552
2.5625
3
[ "Apache-2.0" ]
permissive
<?php class Version_model extends CI_Model { private $db; public function __construct() { parent::__construct(); $this->db = $this->load->database('default', TRUE); } public function removeFlash($id) { return $this->db->delete('client_flash', array('id' => $id)); } public function saveFlash($data) { return $this->db->insert('client_flash', $data); } public function getFlashList($os, $pageNo=1, $pageSize=10) { $sql = "select * from client_flash"; $where = ' WHERE 1 = 1'; if ($os == 'android' OR $os == 'ios') { $where .= " AND os = '" .$os. "'"; } $start = ($pageNo - 1) * $pageSize; $orderBY = " ORDER BY id DESC"; $limit = " LIMIT $start, $pageSize"; $sql .= ($where . $orderBY . $limit); $sql2 = "SELECT count(*) AS totalNum FROM client_flash " . $where; $query2 = $this->db->query($sql2); $totalTmp = $query2->result_array(); $totalNum = $totalTmp[0]['totalNum']; $data['totalPages'] = ceil($totalNum / $pageSize); $data['flashList'] = array(); if ($totalNum > 0) { $query1 = $this->db->query($sql); $data['flashList'] = $query1->result_array(); } return $data; } public function getVersionList($os="android", $pageNo=1, $pageSize=10) { $sql = "select * from client_version"; $where = ' WHERE 1 = 1'; if ($os == 'android' OR $os == 'ios') { $where .= " AND os = '" .$os. "'"; } $start = ($pageNo - 1) * $pageSize; $orderBY = " ORDER BY versionCode DESC"; $limit = " LIMIT $start, $pageSize"; $sql .= ($where . $orderBY . $limit); $sql2 = "SELECT count(*) AS totalNum FROM client_version " . $where; $query2 = $this->db->query($sql2); $totalTmp = $query2->result_array(); $totalNum = $totalTmp[0]['totalNum']; $data['totalPages'] = ceil($totalNum / $pageSize); $data['versionList'] = array(); if ($totalNum > 0) { $query1 = $this->db->query($sql); $data['versionList'] = $query1->result_object(); } return $data; } public function getVersionById($id) { $query = $this->db->get_where('client_version', array('id' => $id)); return $query->row_object(); } public function saveVersion($data) { return $this->db->insert('client_version', $data); } public function updateVersion($id, $data) { $this->db->where('id', $id); return $this->db->update('client_version', $data); } public function delVersion($id) { return $this->db->delete('client_version', array('id' => $id)); } }
Markdown
UTF-8
1,835
2.65625
3
[]
no_license
--- title: C'était la première fois --- Bonjour ! Le vendredi dernier, j'avais une idée pour une petite nouvelle chanson, et une heure plus tard les paroles et la mélodie étaient finies ! La chanson s'appelle "C'était la première fois", je l'ai enregistré avec mon bon ami Ben (guitare) hier. Bon ben. {% include audio.html media="cetait-la-premiere-fois.mp3" %} Paroles ------- > En te quittant > je n'avais pas de sentiments > avoir été si froid > cela me fait mal maintenant. > > Puis ton coeur > a dû prendre tant de douleur > et je suis désolé > je te reverrai tout à l'heure. > > > Refrain: > C'était la première fois > le premier voyage > vers des pays inconnus > on n'était plus si sage. > > On a goûté à tout > ô -- on s'est goûté > pauvre de toi > je ne t'ai pas écouté. > > > J'ai revu > nos instants ah si peu > si souvent > que je les sais tout par coeur. > > Mais ton âme > s'est envolé, juste comme le mien > et tout qui reste > sont les souvenirs de toi -- de nous. > > Refrain > > Je voulais > te revoir juste une fois > pour te dire > que c'était pas ta faute. > > Mais t'étais > tu n'étais plus chez toi > et je ne > me suis plus senti chez moi. > > Refrain > > Comme c'est dur > que les gens qui se adorent > juste un jour > ne veulent plus se voir. > > On se pense > d'être habitué à ça > mais pourquoi ça me fait mal > même après la millième fois ? > > Refrain x2 Version alternative pour la dernière répétition du refrain : > Ça sera la prochaine fois > le prochain voyage > vers des pays étrangérs > on ne sera plus sauvage. > > On va goûter à tout > oui, on s'goûtera > t'es heureuse > car on s'écoutera.
Java
WINDOWS-1252
692
2.078125
2
[]
no_license
package com.icss.entity; public class StCourse { private int scId;// private double scGrade;//ɼ private int coId; private int roId; private int clId; public int getScId() { return scId; } public void setScId(int scId) { this.scId = scId; } public double getScGrade() { return scGrade; } public void setScGrade(double scGrade) { this.scGrade = scGrade; } public int getCoId() { return coId; } public void setCoId(int coId) { this.coId = coId; } public int getRoId() { return roId; } public void setRoId(int roId) { this.roId = roId; } public int getClId() { return clId; } public void setClId(int clId) { this.clId = clId; } }
Java
UTF-8
19,593
2.296875
2
[]
no_license
package com.Stranded.worldGeneration.warIsland; import com.Stranded.Files; import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.block.banner.Pattern; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import java.util.ArrayList; import java.util.List; import static com.Stranded.worldGeneration.regions.GetRegion.*; public class ImportWarIsland { @SuppressWarnings("All") public static void importWarIsland(Files island, Player player) { int y = island.getConfig().getInt("warIsland.y"); int totalWidth = island.getConfig().getInt("warIsland.width"); int totalHeight = island.getConfig().getInt("warIsland.height"); int totalLength = island.getConfig().getInt("warIsland.length"); int width = totalWidth; int height = totalHeight; int length = totalLength; Location temp = player.getLocation().clone(); temp.setY(y); for (String blocksID : island.getConfig().getConfigurationSection("warIsland.region.blocks").getKeys(false)) { String BlockSet = island.getConfig().getString("warIsland.region.blocks." + blocksID); for (String blockData : getBlocks(BlockSet)) { int repeat = 0; if (hasRepeat(blockData)) { repeat = getRepeat(blockData); } Material m = getMaterial(blockData); for (int loop = 0; loop <= repeat; loop++) { if (m.equals(Material.STRUCTURE_VOID)) { length--; if (length == -1) { height--; length = totalLength; } if (height == -1) { width--; height = totalHeight; } continue; } Location l = getLocation(temp, width, height, length); if (!l.getBlock().getType().equals(m)) { l.getBlock().setType(m); } l.getBlock().setData(getData(blockData)); if (hasExtraData(blockData)) { int extraDataID = getExtraDataID(blockData); if (extraDataID >= 0) { switch (m) { case STANDING_BANNER: case WALL_BANNER: Banner banner = (Banner) l.getBlock().getState(); List<Pattern> patterns = (List<Pattern>) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".banner.pattern"); DyeColor color = DyeColor.valueOf(island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".banner.baseColor")); banner.setPatterns(patterns); banner.setBaseColor(color); break; case BEACON: Beacon beacon = (Beacon) l.getBlock().getState(); PotionEffect primary = (PotionEffect) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".beacon.primaryEffect"); PotionEffect secondary = (PotionEffect) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".beacon.secondaryEffect"); String customName = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".beacon.customName"); String lock = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".beacon.lock"); ArrayList<ItemStack> content = (ArrayList<ItemStack>) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".beacon.inventory"); beacon.setPrimaryEffect(primary.getType()); // beacon.setSecondaryEffect(secondary.getType()); beacon.setCustomName(customName); beacon.setLock(lock); int i = 0; for (ItemStack is : content) { beacon.getInventory().setItem(i, is); i++; } break; case BED_BLOCK: Bed bed = (Bed) l.getBlock().getState(); color = DyeColor.valueOf(island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".bed.color")); bed.setColor(color); bed.update(); break; case BREWING_STAND: BrewingStand brewingStand = (BrewingStand) l.getBlock().getState(); int time = island.getConfig().getInt("warIsland.region.extraData." + extraDataID + ".brewingStand.brewingTime"); int level = island.getConfig().getInt("warIsland.region.extraData." + extraDataID + ".brewingStand.fuelLevel"); customName = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".brewingStand.customName"); content = (ArrayList<ItemStack>) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".brewingStand.inventory"); lock = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".brewingStand.lock"); brewingStand.setBrewingTime(time); brewingStand.setFuelLevel(level); brewingStand.setCustomName(customName); brewingStand.setLock(lock); i = 0; for (ItemStack is : content) { brewingStand.getInventory().setItem(i, is); i++; } break; case CHEST: case TRAPPED_CHEST: Chest chest = (Chest) l.getBlock().getState(); customName = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".chest.customName"); content = ((ArrayList<ItemStack>) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".chest.inventory")); lock = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".chest.lock"); chest.setCustomName(customName); chest.setLock(lock); if (chest.getInventory().getSize() >= content.size()) { i = 0; for (ItemStack is : content) { chest.getInventory().setItem(i, is); i++; } } break; case COMMAND_CHAIN: case COMMAND_REPEATING: case COMMAND: CommandBlock commandBlock = (CommandBlock) l.getBlock().getState(); String command = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".commandBlock.command"); String name = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".commandBlock.name"); commandBlock.setCommand(command); commandBlock.setName(name); break; case MOB_SPAWNER: CreatureSpawner creatureSpawner = (CreatureSpawner) l.getBlock().getState(); int delay = island.getConfig().getInt("warIsland.region.extraData." + extraDataID + ".spawner.delay"); String entityType = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".spawner.spawnedType"); creatureSpawner.setDelay(delay); creatureSpawner.setSpawnedType(EntityType.valueOf(entityType)); break; case DISPENSER: Dispenser dispenser = (Dispenser) l.getBlock().getState(); customName = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".dispenser.customName"); lock = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".dispenser.lock"); content = (ArrayList<ItemStack>) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".dispenser.inventory"); dispenser.setCustomName(customName); dispenser.setLock(lock); i = 0; for (ItemStack is : content) { dispenser.getInventory().setItem(i, is); i++; } break; case DROPPER: Dropper dropper = (Dropper) l.getBlock().getState(); customName = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".dropper.customName"); lock = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".dropper.lock"); content = (ArrayList<ItemStack>) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".dropper.inventory"); dropper.setCustomName(customName); dropper.setLock(lock); i = 0; for (ItemStack is : content) { dropper.getInventory().setItem(i, is); i++; } break; case ENCHANTMENT_TABLE: EnchantingTable enchantingTable = (EnchantingTable) l.getBlock().getState(); customName = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".enchantmentTable.customName"); enchantingTable.setCustomName(customName); break; case FLOWER_POT: // FlowerPot flowerPot = (FlowerPot) l.getBlock().getState(); // // ItemStack contentItem = island.getConfig().getItemStack("warIsland.region.extraData." + extraDataID + ".flowerPot.content"); // // flowerPot.setContents(new MaterialData(contentItem.getType(), contentItem.getData().getData())); break; case FURNACE: Furnace furnace = (Furnace) l.getBlock().getState(); short burnTime = Short.parseShort(island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".furnace.burnTime")); short cookTime = Short.parseShort(island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".furnace.cookTime")); customName = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".furnace.customName"); lock = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".furnace.lock"); content = (ArrayList<ItemStack>) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".furnace.inventory"); furnace.setBurnTime(burnTime); furnace.setCookTime(cookTime); furnace.setCustomName(customName); furnace.setLock(lock); i = 0; for (ItemStack is : content) { furnace.getInventory().setItem(i, is); i++; } break; case HOPPER: Hopper hopper = (Hopper) l.getBlock().getState(); customName = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".hopper.customName"); lock = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".hopper.lock"); content = (ArrayList<ItemStack>) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".hopper.inventory"); hopper.setCustomName(customName); hopper.setLock(lock); i = 0; for (ItemStack is : content) { hopper.getInventory().setItem(i, is); i++; } break; case JUKEBOX: Jukebox jukebox = (Jukebox) l.getBlock().getState(); Material disk = Material.getMaterial(island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".jukebox.playing")); jukebox.setPlaying(disk); break; case NOTE_BLOCK: NoteBlock noteBlock = (NoteBlock) l.getBlock().getState(); Note note = (Note) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".noteBlock.note"); noteBlock.setNote(note); case SIGN_POST: case WALL_SIGN: Sign sign = (Sign) l.getBlock().getState(); for (i = 0; i < 4; i++) { String line = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".sign." + i); sign.setLine(i, line); } sign.update(); break; case SKULL: // Skull skull = (Skull) l.getBlock().getState(); // // String skullType = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".skull.skullType"); // String rotation = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".skull.rotation"); //// String owner = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".skull.owner"); // // SkullType skullType1 = SkullType.valueOf(skullType); // BlockFace blockFace = BlockFace.valueOf(rotation); // // skull.setSkullType(skullType1); // skull.setRotation(blockFace); //// skull.setOwner(owner); break; case BLACK_SHULKER_BOX: case SILVER_SHULKER_BOX: case RED_SHULKER_BOX: case BLUE_SHULKER_BOX: case CYAN_SHULKER_BOX: case GRAY_SHULKER_BOX: case LIME_SHULKER_BOX: case PINK_SHULKER_BOX: case BROWN_SHULKER_BOX: case GREEN_SHULKER_BOX: case WHITE_SHULKER_BOX: case ORANGE_SHULKER_BOX: case PURPLE_SHULKER_BOX: case YELLOW_SHULKER_BOX: case MAGENTA_SHULKER_BOX: case LIGHT_BLUE_SHULKER_BOX: ShulkerBox shulkerBox = (ShulkerBox) l.getBlock().getState(); customName = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".shulkerBox.customName"); lock = island.getConfig().getString("warIsland.region.extraData." + extraDataID + ".shulkerBox.lock"); content = (ArrayList<ItemStack>) island.getConfig().get("warIsland.region.extraData." + extraDataID + ".shulkerBox.inventory"); shulkerBox.setCustomName(customName); shulkerBox.setLock(lock); i = 0; for (ItemStack is : content) { shulkerBox.getInventory().setItem(i, is); i++; } break; } } } length--; if (length == -1) { height--; length = totalLength; } if (height == -1) { width--; height = totalHeight; } } } } } }
Go
UTF-8
245
2.84375
3
[]
no_license
func isCovered(ranges [][]int, left int, right int) bool { t := [51]bool{} for _, r := range ranges { for i := r[0]; i <= r[1]; i++ { t[i] = true } } for i := left; i <= right; i++ { if !t[i] { return false } } return true }
Java
UTF-8
453
1.929688
2
[]
no_license
package com.github.experimental.strategy.embedded; import com.github.fluent.hibernate.annotations.FluentName; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Book { @Id private Long pid; @Embedded //@FluentName(prefix="first_auth") private AuthorInfo firstAuthor; @Embedded //@FluentName(prefix="second_auth") private AuthorInfo secondAuthor; }
Java
UTF-8
2,304
2.34375
2
[]
no_license
package com.pisyedilionline.actor; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.google.gson.Gson; import com.pisyedilionline.game.PisYediliOnline; import com.pisyedilionline.message.ChatMessageClient; import com.pisyedilionline.message.Opcode; import com.pisyedilionline.screen.GameScreen; public class ChatButtonGroup extends Group { private final PisYediliOnline game; private final GameScreen gameScreen; private final Label title; public ChatButtonGroup(final PisYediliOnline game, final GameScreen gameScreen) { this.game = game; this.gameScreen = gameScreen; Label.LabelStyle labelStyle = new Label.LabelStyle(); labelStyle.font = game.font; labelStyle.fontColor = Color.WHITE; title = new Label("Quick chat", labelStyle); title.setPosition(0, 0); title.setSize(getWidth(), 80); title.setTouchable(Touchable.disabled); addActor(title); } public void addButton(int messageCode, String message) { TextButton button = new TextButton(message, game.skin); button.setX(getX()); button.getLabel().setFontScale(1f); button.addListener(new ClickListener() { @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { ChatMessageClient message = new ChatMessageClient(messageCode, gameScreen.getMainPlayer().getUsername()); game.nakama.getSocket().sendMatchData(game.matchId, Opcode.CHAT_SEND.id, new Gson().toJson(message).getBytes()); return true; } }); addActorAt(0, button); for (int i = 0; i < getChildren().size; i++) { Actor child = getChild(i); button.setSize(getWidth(), 80); child.setY(80 * i); } title.setPosition(0, (getChildren().size - 1) * 80); } }
PHP
UTF-8
1,189
2.546875
3
[ "MIT" ]
permissive
<?php //single.php – Định dạng trang hiển thị nội dung của tất cả các Post. namespace App\Controllers; use Sober\Controller\Controller; use WP_Query; class Single extends Controller { public function project() { return (object)[ 'name' => get_field('name',get_the_ID()), 'url' => get_field('url',get_the_ID()), 'case_study' => get_field('case_study',get_the_ID()), 'delivery_solution' => get_field('delivery_solution',get_the_ID()), 'feedback' => get_field('feedback',get_the_ID()), 'img' => $this->getImage(get_the_ID(),'large'), ]; } protected function getImage($id,$size = 'medium') { $image = get_field('project_image',$id); $url = $image['url']; $title = $image['title']; $alt = $image['alt']; $caption = $image['caption']; $thumb = $image['sizes'][$size]; $width = $image['sizes'][$size. '-width']; $height = $image['sizes'][$size. '-height']; return (object)[ 'url' => $url, 'title' => $title, 'alt' => $alt, 'caption' => $caption, 'thumb' => $thumb, 'width' => $width, 'height' => $height, ]; } }
Python
UTF-8
987
2.9375
3
[]
no_license
import sys import json import pathlib def main(filename): with open(filename) as f: document = json.load(f) for node in document["nodes"]: del node["html_rep"] with open(filename, "w") as f: json.dump(document, f) def from_directory(directory): path = pathlib.Path(directory) for file in path.iterdir(): print(file) with file.open() as f: root = json.load(f) def recursive_delete(node): if "html_rep" in node: del node["html_rep"] if "children" in node: for child in node["children"]: recursive_delete(child) return True recursive_delete(root) with file.open(mode="w") as f: json.dump(root, f) if __name__ == "__main__": if sys.argv[1] == "-d": directory = sys.argv[2] from_directory(directory) else: filename = sys.argv[1] main(filename)
Java
UTF-8
2,327
1.671875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017-2020 Alfresco Software, Ltd. * * 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.activiti.cloud.common.liquibase; import javax.sql.DataSource; import liquibase.integration.spring.SpringLiquibase; import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.io.ResourceLoader; public abstract class SpringLiquibaseConfigurationSupport implements ResourceLoaderAware { private ResourceLoader resourceLoader; @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } protected SpringLiquibase buildSpringLiquibase(DataSource dataSource, LiquibaseProperties properties) { SpringLiquibase liquibase = new SpringLiquibase(); liquibase.setDataSource(dataSource); liquibase.setResourceLoader(resourceLoader); liquibase.setChangeLog(properties.getChangeLog()); liquibase.setContexts(properties.getContexts()); liquibase.setDefaultSchema(properties.getDefaultSchema()); liquibase.setLiquibaseTablespace(properties.getLiquibaseTablespace()); liquibase.setDropFirst(properties.isDropFirst()); liquibase.setShouldRun(properties.isEnabled()); liquibase.setLabelFilter(properties.getLabelFilter()); liquibase.setChangeLogParameters(properties.getParameters()); liquibase.setRollbackFile(properties.getRollbackFile()); liquibase.setDatabaseChangeLogTable(properties.getDatabaseChangeLogTable()); liquibase.setDatabaseChangeLogLockTable(properties.getDatabaseChangeLogLockTable()); liquibase.setTestRollbackOnUpdate(properties.isTestRollbackOnUpdate()); return liquibase; } }
PHP
UTF-8
1,454
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Models; use CodeIgniter\Model; class Sales extends Model { public function saveBill($data){ $db = \Config\Database::connect(); $db->transBegin(); $bill = array( 'Tanggal' => $data->Tanggal, 'Jam' => $data->Jam, 'NamaPelanggan' => $data->NamaPelanggan, 'Total' => $data->Total, 'BayarTunai' => $data->BayarTunai, 'Kembali' => $data->Kembali, 'TglJamUpdate' => date('Y-m-d H:i:s') ); $db->table('penjualan')->insert($bill); $id = $db->insertID(); foreach($data->DetilPenjualan as $key => $value) { $billDetail = array( 'TransactionID' => $id, 'NamaItem' => $value->Item, 'Quantity' => $value->Qty, 'HargaSatuan' => $value->HargaSatuan, 'SubTotal' => $value->SubTotal, 'TglJamUpdate' => date('Y-m-d H:i:s') ); $db->table('penjualandetil')->insert($billDetail); } //check transaction if ($db->transStatus() === FALSE) { $db->transRollback(); echo 'transaction failed'; } else { $db->transCommit(); echo 'transaction success'; } } }
C++
UTF-8
1,888
3.125
3
[ "CC-BY-4.0" ]
permissive
// Copyright 2020 Zinkov Artem #include <string> #include <sstream> #include <algorithm> #include <vector> #include "include/odd_even_batcher_merge.h" #include "include/merge_batcher_app.h" Merge_Batcher_App::Merge_Batcher_App() : message_("") {} void Merge_Batcher_App::help(const char* appname, const char* message) { message_ = std::string(message) + "This is a merge batcher application.\n\n" + "Please provide arguments in the following format:\n\n" + " $ " + appname + " <v1> " + "<v2>\n\n" + "Where all the arguments are a sequence of integers.\n"; } bool Merge_Batcher_App::validateNumberOfArguments(int argc, const char** argv) { if (argc == 1) { help(argv[0]); return false; } else { if (argc != 3) { help(argv[0], "ERROR: Should be 2 arguments.\n\n"); return false; } } return true; } std::vector<int> parseVector(const char* arg) { std::vector<int> vec; std::string str = arg; std::istringstream in(str); for (auto& s : str) { if (!(isdigit(s) || s == ',' || s == '.' || s == ' ' || s == '-')) throw std::string("ERROR: Wrong format!"); } for (int n; in >> n; vec.push_back(n), in.get()) {} std::sort(vec.begin(), vec.end()); return vec; } std::string Merge_Batcher_App::operator()(int argc, const char** argv) { Arguments args; if (!validateNumberOfArguments(argc, argv)) { return message_; } try { args.v1 = parseVector(argv[1]); args.v2 = parseVector(argv[2]); } catch (std::string & str) { return str; } std::vector<int> res = merge_batcher(args.v1, args.v2); std::ostringstream stream; stream << "result vector ="; for (auto& r : res) stream << " " << r; message_ = stream.str(); return message_; }
C++
UTF-8
747
2.796875
3
[]
no_license
#include <fullscore/actions/Transforms/HalfDuration.hpp> #include <fullscore/models/Note.hpp> #include <fullscore/Transforms/HalfDurationTransform.hpp> Action::Transforms::HalfDuration::HalfDuration(Note *note) : Base("half_duration") , note(note) {} Action::Transforms::HalfDuration::~HalfDuration() {} bool Action::Transforms::HalfDuration::execute() { if (!note) throw std::runtime_error("Cannot HalfDuration on a nullptr note"); std::vector<Note> single_note_as_array; single_note_as_array.push_back(*note); ::Transforms::HalfDuration half_duration_transform; single_note_as_array = half_duration_transform.transform(single_note_as_array); *note = single_note_as_array.at(0); return true; }
Markdown
UTF-8
5,991
2.671875
3
[]
no_license
--- title: TypeSafeで使いやすいJavaのハイレベルRESTクライアントRetrofit tags: ["Java", "Retrofit"] categories: ["Programming", "Java", "retrofit"] date: 2014-05-05T15:49:28+09:00 updated: 2014-05-06T00:12:21+09:00 --- JavaのRESTクライアントといれば * Spring FrameworkのRestClient * JAX-RS 2のClient API あたりがメジャーで使いやすい。 ただし、ちょっとboilerplateなコードが増えてしまう。[この記事][1]のTodoRestRepositoryとか。 最近見つけた[Retrofit][2]がよさげ。Interfaceだけ作れば実装はライブラリが提供してくれる(Proxyを作成してくれる)のが今風な作り。 以下、使用例 ### pom.xml ```xml <dependency> <groupId>com.squareup.retrofit</groupId> <artifactId>retrofit</artifactId> <version>1.5.0</version> </dependency> ``` ### REST Client インタフェースのメソッドに対して、対応するHTTPのアノテーションをつけるだけ。 ```java package restclient; import retrofit.http.GET; import retrofit.http.Path; import retrofit.http.Query; public interface EntryRestRepository { @GET("/entries") Page<Entry> findAll(); @GET("/entries") Page<Entry> findAll(@Query("page") int page, @Query("size") int size); @GET("/entries/{entryId}") Entry findOne(@Path("entryId") Long entryId); } ``` 非同期にも対応している。 入出力に対応するモデルは普通のJavaBeanでOK。 ```java package restclient; @lombok.Data public class Entry { private Long entryId; private String title; private String contents; private String format; } ``` ネストにも対応している。 ```java package restclient; import java.util.List; @lombok.Data public class Page<T> { private List<T> content; private String sort; private long totalPages; private long totalElements; private boolean firstPage; private boolean lastPage; private long numberOfElements; private int size; private int number; } ``` ### 使用例 ```java public static void main(String[] args) { RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint("http://blog.ik.am/api/v1") .build(); EntryRestRepository repository = restAdapter.create(EntryRestRepository.class); System.out.println(repository.findAll()); System.out.println(repository.findAll(0, 2)); System.out.println(repository.findOne(259L)); } ``` ### 非同期処理 返り値をvoidにして引数に`retrofit.Callback`を取ればよい。 ```java @GET("/entries") void findAllAsynnc(@Query("page") int page, @Query("size") int size, Callback<Page> cb); @GET("/entries/{entryId}") void findOneAsync(@Path("entryId") Long entryId, Callback<Entry> cb); ``` 使い方は、↓な感じ。 ```java repository.findOneAsync(260L, new Callback<Entry>() { @Override public void success(Entry entry, Response response) { System.out.println(entry); } @Override public void failure(RetrofitError error) { error.printStackTrace(); } }); ``` JavaFXなどGUIアプリでメインスレッドからHTTPアクセスすると固まちゃう場合にはこっちを使いたい。 FunctionalInterfaceじゃないのでラムダ使えないのが辛い。 ### JSONコンバーターをJacksonに変える RetrofitはデフォルトでJSONコンバーターにGsonを使用する。依存ライブラリ的にJacksonの方が都合がいいって場合もあると思うが、RetrofitではJSONコンバーターを入れ替えることができる。 pom.xmlを以下のように書き換える ```xml <dependency> <groupId>com.squareup.retrofit</groupId> <artifactId>retrofit</artifactId> <version>1.5.0</version> <exclusions> <exclusion> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.squareup.retrofit</groupId> <artifactId>converter-jackson</artifactId> <version>1.5.0</version> </dependency> ``` コンバーターは`RestAdapter`に設定して差し替える。 ```java RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint("http://blog.ik.am/api/v1") .setConverter(new JacksonConverter()) .build(); EntryRestRepository repository = restAdapter.create(EntryRestRepository.class); ``` Jacksonではおなじみの`ObjectMapper`も`JacksonConverter`に設定可能。 ```java ObjectMapper objectMapper = new ObjectMapper(); RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint("http://blog.ik.am/api/v1") .setConverter(new JacksonConverter(objectMapper)) .build(); EntryRestRepository repository = restAdapter.create(EntryRestRepository.class); ``` GsonとJacksonの違いは色々あるけど、GsonだとJavaBeanには存在しないがJSONに存在するフィールドがあると無視するけど、Jacksonの方は`UnrecognizedPropertyException`をスローする。Gson側の挙動に合わせるには、以下のように`@JsonIgnoreProperties(ignoreUnknown = true)`をつける必要がある。 ```java package restclient; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @lombok.Data @JsonIgnoreProperties(ignoreUnknown = true) public class Entry { private Long entryId; private String title; private String contents; private String format; } ``` クライアント側は使いたいフィールドだけ持てば良いのでこちらの方が良いかもしれない。ミスに気づきにくくなるかもだけど。 ---- これから使っていきたいと思った。 JavaFXと相性が良い気がする。 JAX-RSのClientだと[ちょっと辛かった][3]。 コンバーターはProtocol Bufferにも対応しているみたい。 [1]: /#/entries/176 [2]: http://square.github.io/retrofit/ [3]: /#/entries/210
Java
UTF-8
2,043
4.25
4
[]
no_license
package day30_Arrays; public class StudentArray { public static void main(String[] args) { /*id index -0 firstName 1 lastName 2 batchNum 3 phoneNum 4 Declare student array and store5 String values */ String [] student1 = new String[5]; //when you do not know the value student1[0]="1234"; student1[1]= "Adam"; student1[2]="Jordan"; student1[3]="22"; student1[4]="3129185444"; String []studentTWO= {"123","Madam", "Winter", "22","7039185444"};// when you know the value System.out.println("Student id " + student1[0]); System.out.println("Student first " + student1[1]); System.out.println("Student last name " + student1[2]); System.out.println("Student batch " + student1[3]); System.out.println("Student phone number " + student1[4]); System.out.println("student data length"+student1.length); // chekc if student data array contains 5 items // true: student 1 data array has correct length // false : data array has incorect length if(student1.length==5){ System.out.println("true: PASSS data array contains 5 items"); }else{ System.out.println(" FALSEE: data array doesn t contain 5 array"); } /** check if student1 and student2 arrays have same number of data TRUE: PASS: data arrays length match FALSE: FAIL: data arrays length mismatch */ if(student1.length==studentTWO.length){ System.out.println("true: PASS data array contains 5 items"); }else{ System.out.println(" FALSE: data array doesn t contain 5 array"); } // print upper case first and last name System.out.println(studentTWO[1].toUpperCase() +"\t"+ studentTWO[2].toUpperCase()); int [] nume={22,55,11}; for (int i=0 ; i<nume.length; i++) { System.out.println(nume[i]); // output22-55-11 } } }
Markdown
UTF-8
2,352
3
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "/ZH (Hash algorithm for calculation of file checksum in debug info)" description: "Use the /ZH compiler option to enable MD5, SHA-1, or SHA-256 source file checksums in debug info" ms.date: "09/16/2019" f1_keywords: ["/ZH", "/ZH:MD5", "/ZH:SHA1", "/ZH:SHA_256"] helpviewer_keywords: ["/ZH", "/ZH:MD5", "/ZH:SHA1", "/ZH:SHA_256", "/ZH compiler option", "/ZH:MD5 compiler option", "/ZH:SHA1 compiler option", "/ZH:SHA_256 compiler option", "Hash algorithm for file checksum in debug info"] --- # /ZH (Hash algorithm for calculation of file checksum in debug info) Specifies which cryptographic hash algorithm to use to generate a checksum of each source file. ## Syntax > **/ZH:**{**MD5**|**SHA1**|**SHA_256**} ## Arguments **/ZH:MD5**\ Use an MD5 hash for the checksum. This option is the default. **/ZH:SHA1**\ Use an SHA-1 hash for the checksum. **/ZH:SHA_256**\ Use an SHA-256 hash for the checksum. ## Remarks PDB files store a checksum for each source file compiled into the object code in the associated executable. The checksum allows the debugger to verify that the source code it loads matches the executable. The compiler and debugger support MD5, SHA-1, and SHA-256 hash algorithms. By default, the compiler uses an MD5 hash to generate the checksum. You can specify this option explicitly by using the **/ZH:MD5** option. Because of a risk of collision problems in MD5 and SHA-1, Microsoft recommends you use the **/ZH:SHA_256** option. The SHA-256 hash may result in a small increase in compile times. When more than one **/ZH** option is specified, the last option is used. The **/ZH** option is available starting in Visual Studio 2019 version 16.4. ### To set this compiler option in the Visual Studio development environment 1. Open the project's **Property Pages** dialog box. For details, see [Set C++ compiler and build properties in Visual Studio](../working-with-project-properties.md). 1. Set the **Configuration** drop-down to **All Configurations**. 1. Select the **Configuration Properties** > **C/C++** > **Command Line** property page. 1. Modify the **Additional options** property to add a **/ZH:MD5**, **/ZH:SHA1**, or **/ZH:SHA_256** option, and then choose **OK**. ## See also [Compiler options](compiler-options.md)\ [Source server](/windows/win32/debug/source-server-and-source-indexing)
Python
UTF-8
735
2.96875
3
[]
no_license
def mlbph(img1): source=img1 final = source[:] for y in range(len(source)): for x in range(y): final[y, x] = source[y, x] members = [source[0, 0]] * 9 for y in range(1, len(source) - 1): for x in range(1, y - 1): members[0] = source[y - 1, x - 1] members[1] = source[y, x - 1] members[2] = source[y + 1, x - 1] members[3] = source[y - 1, x] members[4] = source[y, x] members[5] = source[y + 1, x] members[6] = source[y - 1, x + 1] members[7] = source[y, x + 1] members[8] = source[y + 1, x + 1] members.sort() final[y, x] = members[5] return final
Java
UTF-8
6,781
2.03125
2
[]
no_license
package com.wanxg.mynotes.database; public class DataBaseQueries { public static final int TOKEN_INITIAL_ID = 100000000; /*************************************************DDL***************************************************/ public static final String SQL_CREATE_TABLE_LOCAL_USER = "CREATE TABLE IF NOT EXISTS local_user (" + "uid VARCHAR(255) NOT NULL, " + "email VARCHAR(255) NOT NULL PRIMARY KEY, " + "password VARCHAR(255) NOT NULL, " + "password_salt VARCHAR(255) NOT NULL, " + "UNIQUE (uid))"; public static final String SQL_CREATE_TABLE_USER_PROFILE = "CREATE TABLE IF NOT EXISTS user_profile (" + "pid INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 100000000, INCREMENT BY 1) PRIMARY KEY, " + "user_id VARCHAR(255), " + "email VARCHAR(255) NOT NULL, " + "username VARCHAR(255) NOT NULL, " + "first_name VARCHAR(255), " + "last_name VARCHAR(255), " + "photo_url VARCHAR(512), " + "gender INTEGER, " + "creation TIMESTAMP(0) DEFAULT NOW, " + "active INTEGER DEFAULT 1 NOT NULL)"; public static final String SQL_ALTER_TABLE_USER_PROFILE_ADD_CONSTRAINT_FOREIGN_KEY_UID = "ALTER TABLE user_profile ADD CONSTRAINT IF NOT EXISTS " + "fk_user_profile_local_user_uid FOREIGN KEY (user_id) REFERENCES local_user(uid)"; public static final String SQL_CREATE_TABLE_SOCIAL_USER = "CREATE TABLE IF NOT EXISTS social_user (" + "sid INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 100000000, INCREMENT BY 1) PRIMARY KEY, " + "profile_id INTEGER NOT NULL, " + "social_provider VARCHAR(32) NOT NULL, " + "external_id VARCHAR(255) NOT NULL, " + "email VARCHAR(255), " + "username VARCHAR(255) NOT NULL, " + "first_name VARCHAR(255), " + "last_name VARCHAR(255), " + "photo_url VARCHAR(512), " + "gender INTEGER, " + "creation TIMESTAMP(0) DEFAULT NOW)"; public static final String SQL_ALTER_TABLE_SOCIAL_USER_ADD_CONSTRAINT_FOREIGN_KEY_PID = "ALTER TABLE social_user ADD CONSTRAINT IF NOT EXISTS " + "fk_social_user_user_profile_pid FOREIGN KEY (profile_id) REFERENCES user_profile(pid)"; public static final String SQL_CREATE_TABLE_AUTH_TOKEN = "CREATE TABLE IF NOT EXISTS auth_token (" + "tid VARCHAR(10) NOT NULL PRIMARY KEY, " + "user_id VARCHAR(255) NOT NULL, " + "token VARCHAR(255) NOT NULL, " + "token_salt VARCHAR(255) NOT NULL, " + "creation TIMESTAMP(0) DEFAULT NOW NOT NULL, " + "valid_to TIMESTAMP(0) NOT NULL, " + "deleted INTEGER DEFAULT 0 NOT NULL)"; public static final String SQL_ALTER_TABLE_AUTH_TOKEN_ADD_CONSTRAINT_FOREIGN_KEY_UID = "ALTER TABLE auth_token ADD CONSTRAINT IF NOT EXISTS " + "fk_auth_token_local_user_uid FOREIGN KEY (user_id) REFERENCES local_user(uid)"; public static final String SQL_CREATE_TABLE_USER_ROLE = "CREATE TABLE IF NOT EXISTS user_role (" + "email VARCHAR(255) NOT NULL, " + "role VARCHAR(255) NOT NULL, " + "PRIMARY KEY (email,role))"; public static final String SQL_CREATE_TABLE_ROLE_PERM = "CREATE TABLE IF NOT EXISTS role_perm (" + "role VARCHAR(255) NOT NULL PRIMARY KEY, " + "permission VARCHAR(255) NOT NULL)"; public static final String SQL_ALTER_TABLE_USER_ROLE_ADD_CONSTRAINT_FOREIGN_KEY_EMAIL = "ALTER TABLE user_role ADD CONSTRAINT IF NOT EXISTS " + "fk_user_role_local_user_email FOREIGN KEY (email) REFERENCES local_user(email)"; public static final String SQL_ALTER_TABLE_USER_ROLE_ADD_CONSTRAINT_FOREIGN_KEY_ROLE = "ALTER TABLE user_role ADD CONSTRAINT IF NOT EXISTS " + "fk_user_role_perm_role FOREIGN KEY (role) REFERENCES role_perm(role)"; /***********************************************DML******************************************************/ public static final String SQL_INSERT_INTO_USER = "INSERT INTO local_user (uid,email,password,password_salt) VALUES (?,?,?,?)"; public static final String SQL_SELECT_USER_BY_EMAIL = "SELECT * FROM local_user WHERE email = ?"; public static final String SQL_SELECT_USER_BY_UID = "SELECT * FROM local_user WHERE uid = ?"; public static final String SQL_UPDATE_USER_SET_ACTIVE = "UPDATE local_user SET ACTIVE = ? WHERE email = ?"; public static final String SQL_UPDATE_USER_PASSWORD = "UPDATE local_user SET password = ?, password_salt = ? WHERE uid = ?"; public static final String SQL_INSERT_INTO_USER_PROFILE = "INSERT INTO user_profile (user_id,email,username,first_name,last_name,photo_url,gender) VALUES (?,?,?,?,?,?,?)"; public static final String SQL_UPDATE_USER_PROFILE = "UPDATE user_profile SET username = ?, first_name = ?, last_name = ?, gender = ? WHERE pid = ?"; public static final String SQL_UPDATE_USER_PROFILE_SET_UID = "UPDATE user_profile SET user_id = ? WHERE pid = ?"; public static final String SQL_SELECT_USER_PROFILE_BY_USER_ID = "SELECT * FROM user_profile WHERE user_id = ?"; public static final String SQL_SELECT_USER_PROFILE_BY_PROFILE_ID = "SELECT * FROM user_profile WHERE pid = ?"; public static final String SQL_SELECT_USER_PROFILE_BY_EMAIL = "SELECT * FROM user_profile RIGHT JOIN local_user on user_profile.user_id = local_user.uid WHERE email = ?"; public static final String SQL_INSERT_INTO_SOCIAL_USER = "INSERT INTO social_user (profile_id,social_provider,external_id,email,username,first_name,last_name,photo_url,gender) VALUES (?,?,?,?,?,?,?,?,?)"; public static final String SQL_UPDATE_SOCIAL_USER = "UPDATE social_user SET email = ?, username = ?, first_name = ?, last_name = ?, photo_url = ?, gender = ? WHERE external_id = ?"; public static final String SQL_SELECT_SOCIAL_USER_BY_EXTERNAL_ID = "SELECT * FROM social_user WHERE external_id = ?"; public static final String SQL_SELECT_SOCIAL_USER_BY_PROFILE_ID = "SELECT * FROM social_user WHERE profile_id = ?"; public static final String SQL_SELECT_MAX_TOKEN_ID = "SELECT max(tid) FROM auth_token"; public static final String SQL_INSERT_INTO_AUTH_TOKEN = "INSERT INTO auth_token (tid,user_id,token,token_salt,valid_to) VALUES (?,?,?,?, TO_TIMESTAMP(?, 'YYYY-MM-DD HH:MI:SS' ))"; public static final String SQL_UPDATE_AUTH_TOKEN_SET_INVALID = "UPDATE auth_token SET deleted = 1 WHERE tid = ?"; public static final String SQL_SELECT_AUTH_TOKEN_BY_USER_ID_AND_TOKEN_ID = "SELECT token, token_salt FROM auth_token LEFT JOIN local_user ON auth_token.email = local_user.email WHERE local_user.uid = ? AND auth_token.tid = ?"; public static final String AUTHENTICATE_QUERY_ON_TOKEN = "SELECT token, token_salt FROM auth_token WHERE tid = ? AND deleted = 0 AND valid_to >= NOW()"; public static final String AUTHENTICATE_QUERY_ON_LOCAL_USER = "SELECT password, password_salt FROM local_user WHERE email = ?"; }
PHP
UTF-8
3,690
2.71875
3
[]
no_license
<?php error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); session_start(); include_once('../classes/Connect.php'); include_once('../classes/Upld.php'); include_once('../classes/FunctionAPI.php'); $api = new functionAPI; if (isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"] == UPLOAD_ERR_OK) { # dirname(dirname(__FILE__)) $upld_dir = dirname(dirname(__FILE__)) . '/up/'; /* Note : You will run into errors or blank page if "memory_limit" or "upload_max_filesize" is set to low in "php.ini". Open "php.ini" file, and search for "memory_limit" or "upload_max_filesize" limit and set them adequately, also check "post_max_size". */ // if not an AJAX request if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){ die("Not a valid ajax request"); } // if directory doesn't exist, make it! if(!is_dir($upld_dir)) { mkdir($upld_dir); } // is file size gibber then max size if ($_FILES["FileInput"]["size"] > 5242880) { die("File size is too big!"); } // allowed file type Server side check switch(strtolower($_FILES['FileInput']['type'])) { // allowed file types case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg': case 'text/plain': case 'text/html': //html file case 'application/x-zip-compressed': case 'application/pdf': case 'application/msword': case 'application/vnd.ms-excel': case 'video/mp4': break; default: die('Unsupported File!'); //output error } // file name $file_name = strtolower($_FILES['FileInput']['name']); // file's original extension $file_ext = substr($file_name, strrpos($file_name, '.')); // random ID $rndm_id = $api->generate_random_UID(10); // new file name $new_file_name = $rndm_id.$file_ext; if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $upld_dir.$new_file_name)) { // paste into DB intoDB($pdo, $rndm_id, $file_ext); # just freaking email them $api->emailOnEvent("jogallegos97@gmail.com", "New update", "Somebody if not you has posted a new update to UPLD. Please review the post!", "http://upld.joeygallegos.com/up/" . $new_file_name); die('Success! File Uploaded. <b>Link to your UPLD:</b> <a href="' . dirname(dirname(__FILE__)) . '/up/' . $new_file_name . '" target="_blank">Here</a>'); } else { die('Error while uploading file! - ' . $upld_dir); } } else { die('Something wrong with upload! Is "upload_max_filesize" set correctly?'); } function intoDB($connection, $rndm_id, $ext) { $pdo = $connection; // id assigned by script, full link, upload timestamp $query = $pdo->prepare('INSERT INTO uplds (uid, ext, created_at) VALUES (?, ?, ?)'); $query->bindValue(1, $rndm_id); $query->bindValue(2, $ext); $query->bindValue(3, time()); try { $query->execute(); } catch (PDOException $e) { $error = "Error: " . $e->getMessage() . "<br />\n" . "Error info" . $e->errorInfo() . "<br />\n"; echo $error; } }
Markdown
UTF-8
599
3.09375
3
[ "MIT" ]
permissive
# Java Programming III Programming Projects Programming projects for Java Programming III, primarily based upon [Y. Daniel Liang's _Introduction to Java Programming and Data Structures_, 11th Edition](https://www.pearson.com/us/higher-education/product/Liang-Introduction-to-Java-Programming-and-Data-Structures-Comprehensive-Version-11th-Edition/9780134670942.html). Feel free to take inspiration from my works; however, usage constitutes attribution. | Chapter | Assignment | | --- | --- | | [17: Binary I/O](ProgrammingExercises/BinaryIO) | [17.09: Address Book](ProgrammingExercises/BinaryIO/17.09) |
Java
UTF-8
127
2.125
2
[]
no_license
package spendingPotential.spendingPotentialStates; public interface StateI { public void yesOrNoItem(String itemOrMoney); }
Java
UTF-8
1,990
2.125
2
[]
no_license
package com.fiuni.sd.bricks_management.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.fiuni.sd.bricks_management.dto.budgetDetail.BudgetDetailDTO; import com.fiuni.sd.bricks_management.dto.budgetDetail.BudgetDetailResult; import com.fiuni.sd.bricks_management.service.budgetDetail.IBudgetDetailService; import com.fiuni.sd.bricks_management.utils.Setting; @RestController @RequestMapping("/budget_details") public class BudgetDetailController { @Autowired private IBudgetDetailService budgetDetailService; @PostMapping() public BudgetDetailDTO save( @Valid @RequestBody BudgetDetailDTO dto ) { return budgetDetailService.save(dto); } @GetMapping("/{id}") public BudgetDetailDTO getById(@PathVariable(value = "id") Integer id) { return budgetDetailService.getById(id); } @GetMapping(path = "/page/{page_num}") public BudgetDetailResult getBudgets(@PathVariable(value = "page_num") Integer pageNum) { return budgetDetailService.getAll(PageRequest.of(pageNum, Setting.PAGE_SIZE)); } @PutMapping("/{id}") public BudgetDetailDTO update(@RequestBody BudgetDetailDTO BudgetDetailDTO ,@PathVariable(value= "id") Integer id) { return budgetDetailService.update(id, BudgetDetailDTO); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void destroy(@PathVariable(value = "id") Integer id) { budgetDetailService.delete(id); } }
C++
UTF-8
2,435
2.765625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* BulletList.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bogoncha <bogoncha@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/27 20:11:32 by bogoncha #+# #+# */ /* Updated: 2019/10/27 21:18:35 by bogoncha ### ########.fr */ /* */ /* ************************************************************************** */ #include "BulletList.hpp" BulletList::BulletList(void) { this->_head = NULL; this->_next = NULL; return ; } BulletList::BulletList(BulletList const & src) { *this = src; return ; } BulletList::~BulletList(void) { return ; } BulletList & BulletList::operator=(BulletList const & rhs) { if (this != &rhs) { this->_head = rhs.getHead(); this->_next = rhs.getNext(); } return *this; } BulletNode* BulletList::createNode(Bullet* bullet) { BulletNode* tmp = new BulletNode; tmp->bullet = bullet; tmp->next = NULL; return (tmp); } void BulletList::addNode(Bullet* bullet) { BulletNode* tmp = this->createNode(bullet); BulletNode* run = this->_head; if (this->_head == NULL) { this->_head = tmp; } else { while(run->next) run = run->next; run->next = tmp; } } void BulletList::delNode(BulletNode* node) { BulletNode* current; BulletNode* previous; BulletNode* tmp; if (this->_head == NULL) return; if (/*this->_head->next == NULL && */node == this->_head) { tmp = this->_head->next; delete this->_head; this->_head = tmp; return ; } current = this->_head; while (current != node && current != NULL) { previous = current; current = current->next; } previous->next = current->next; delete current; } BulletNode* BulletList::getHead(void) const{ return this->_head; } void BulletList::setHead(BulletNode* head) { this->_head = head; } BulletNode* BulletList::getNext(void) const{ return this->_next; } void BulletList::setNext(BulletNode* next) { this->_next = next; }
Java
UTF-8
612
2.984375
3
[]
no_license
package File_Handling; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializeCar { public static void main(String[] args) throws IOException { Engine e = new Engine("AC6098IB",700); Car car1 = new Car(); car1.setEngine(e); Car car = new Car("3152","mahesh",car1.getEngine()); FileOutputStream fos = new FileOutputStream("CarData2"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(car); oos.close(); System.out.println("Done"); } }
JavaScript
UTF-8
686
3.21875
3
[]
no_license
function checkAnswer(id){ if(id=="option5"){ document.getElementById(id).style.backgroundColor = "chartreuse"; } else{ document.getElementById(id).style.backgroundColor = "red"; } } function checkAnswer(){ let answer = document.getElementById("input").nodeValue.toLowerCase(); if(answer=="switzerland"){ document.getElementById("free-answer").innerHTML = "Your answer is Correct!"; document.getElementById("free-answer").style.color = "chartreuse"; } else { document.getElementById("free-answer").innerHTML ="Your answer is incorrect!"; document.getElementById("free-answer").style.visibility = "visible"; } }
C#
UTF-8
1,040
3.015625
3
[]
no_license
namespace Business { public class Tile : ViewModelBase { public static Tile CreateTile(int number, int xAxis, int yAxis) { return new Tile { Number = number, XAxis = xAxis, YAxis = yAxis }; } private int _number; public int Number { get { return _number; } set { _number = value; OnPropertyChanged("Number"); } } private int _xAxis; public int XAxis { get { return _xAxis; } set { _xAxis = value; OnPropertyChanged("XAxis"); } } private int _yAxis; public int YAxis { get { return _yAxis; } set { _yAxis = value; OnPropertyChanged("YAxis"); } } public override string ToString() { return Number.ToString(); } } }
JavaScript
UTF-8
1,861
3.390625
3
[ "MIT" ]
permissive
// Worker designed to generate a map of passable/unpassable terrain. // Send log messages back by message. var log = function(message) { postMessage({ log: "(mapgenerator) "+(new Date())+": "+message }); }; // When the map is done being generated, pass it back in chunks of rows. var sendMap = function(map) { var delay = 50; var numRowsPerBatch = 50; var sendMapRows = function() { var i, rows = [], row; for (i = 0; i < numRowsPerBatch; i++) { var row = map.shift(); if (row) { rows.push(row); } else { break; } } if (rows.length > 0) { postMessage({mapRows: rows}); setTimeout(sendMapRows, delay); } else { postMessage({done: true}); log("Map generation done."); } }; sendMapRows(); }; // Generate a map, favoring passable terrain over unpassable terrain. var generateMap = function(width, height) { var w, h; var map = []; for (h = 0; h < height; h++) { map[h] = []; for (w = 0; w < width; w++) { map[h][w] = (Math.random() > 0.35) ? 0 : 1; } } // Make the origin (upper left) and destination (lower right) of the // map navigable. map[0][0] = 0; map[height-1][width-1] = 0; sendMap(map); }; // Listen for messages passed to us. This needs to be global to the worker // (workers have their own global distinct from window). onmessage = function(event) { log("Starting map generation."); if (event.data.width && event.data.height) { generateMap(event.data.width, event.data.height); } else { log("Expecting a width and a height property."); } };
JavaScript
UTF-8
5,061
2.84375
3
[]
no_license
var grid = require('selenium-grid'); var webdriver = require('selenium-webdriver'); var async = require('async') //storage for all web drivers var drivers = []; //hub config var hub = { ip: 'http://localhost:5000/wd/hub' }; /* * list supported browsers * format: 'browserNameKey': {seleneium_settings_for_browser} */ var browsers = { 'GoogleChrome35.0.1916.153OSX10.9.4': {'browserName': 'chrome'}, 'Mozilla30.0Windows': {'browserName': 'firefox'} }; /* * Initialize browsers from the array of all supported browsers */ exports.init = function() { for (var browser in browsers) { //get settings from browsers array under current key var settings = browsers[browser]; //fill the drivers with key of the browsers array so it is accessible by name drivers[browser] = new webdriver.Builder(). usingServer(hub.ip). withCapabilities(settings). build(); drivers[browser].manage().window().setSize(1280, 720); console.log(" [" + Date.now() + "] " + browser + ' init with settings: ' + JSON.stringify(settings)); } } /* * Navigate the browser to the url * @param url: navigate to url */ exports.surf = function(url, callback) { var taskQuee = {}; //putting functions on quee for async paraller - read the docs for (var driver in drivers) { (function(curDriver) { //create objects with browser keys and functions to be executed taskQuee[curDriver] = function(callback) { drivers[curDriver].get(url).then(function() { callback(null, true); console.log(" [" + Date.now() + "] " + curDriver + ' navigation to url succeed: ' + url); }, function() { callback(null, false); console.log("![" + Date.now() + "] " + curDriver + ' navigation to url FAILED: ' + url); }); } })(driver); } async.parallel(taskQuee, function(err, results) { callback(results); }); } /* * Screenshot the browser * @param callback: function that is called after command executes */ exports.capture = function(requestedBrowsers, callback) { if (requestedBrowsers == undefined) return false; var taskQuee = {}; //putting functions on quee for async paraller - read the docs for (var driver in drivers) { (function(curDriver) { //if current browser is in requested browsers make screenshot for (var curBrowser in requestedBrowsers) { var browserName = this.hashBrowser(requestedBrowsers[curBrowser]); //create objects with browser keys and functions to be executed if (curDriver == browserName) { taskQuee[curDriver] = function(callback) { drivers[curDriver].takeScreenshot().then(function(response) { console.log(" [" + Date.now() + "] taking screenshot with browser: " + curDriver); callback(null, response); }); } } } })(driver); } //execute quee for paralel execution async.parallel(taskQuee, function(err, results) { console.log(" [" + Date.now() + "] Done taking screenshots"); var response = { snapshots: [] }; var index = 0; /* * formatting the result object */ for (var browserResult in results) { //creates response the same as request var item = {}; for (key in requestedBrowsers[index]) item[key] = requestedBrowsers[index][key]; //append image source item.imgSource = results[browserResult]; response.snapshots[index] = item; index ++; } callback(response); }); } /* * Select the webelement on screen with css selector * @param selector: css selector to specify element * @param callback: function to be called after screenshot is taken */ exports.selector = function(selector, callback) { var response = {}; //search for element specified in post.selector drivers[agent].findElement(webdriver.By.css(selector)).then(function(element) { //get the location of element specified in selector element.getLocation().then(function(location) { response.x = location.x; response.y = location.y; }).then(function() { //get the size of element specified in selector element.getSize().then(function(size) { response.width = size.width; response.height = size.height; }); }); response.fail = false; }, function() { //if element is not found response.fail = true; }).then(function() { callback(response); }); } /* * Close the webdrivers */ exports.close = function(callback) { var taskQuee = {}; //putting functions on quee for async paraller - read the docs for (var driver in drivers) { console.log("![" + Date.now() + "] closing browsers and ending sessions"); drivers[driver].close(); drivers[driver].quit(); drivers[driver] = null; } //wait for browsers to shutdown before exit setTimeout(callback, 4000); } hashBrowser = function(browser) { var hash = ""; for (var key in browser) { if (key === "isReferenceBrowser" || key === "checked") continue; var item = browser[key].split(' ').join(''); hash = hash.concat(item); } return hash; }
C++
UTF-8
3,126
2.9375
3
[]
no_license
#include "Probe.h" Probe::Probe(const std::string & port_name, int baud_rate) : sensor(), sensor_data(), last_accel_read{}, acceleration{}, velocity{}, position{}, should_terminate{false}, port_name{port_name}, baud_rate{baud_rate}, connected{false} {} void Probe::run() { if (connect()) { std::cout << "Connected." << std::endl; should_terminate = false; // Spawn new thread with updateLoop update_thread = std::thread(&Probe::update_loop, this); } } void Probe::stop() { if (connected && update_thread.joinable()) { should_terminate = true; update_thread.join(); } } bool Probe::connect() { connected = true; // Start communication with the sensor if(!sensor.start(port_name, baud_rate)) { connected = false; } else { // Set binary output format. Select Quaternion and IMU data. if(!sensor.cmd_binary_data_format("QUATERNION, IMU") ||!sensor.cmd_divider("1") ||!sensor.cmd_mode("BC")) { connected = false; } } return connected; } void Probe::update(float ellapsed_time_in_millis) { float dt = ellapsed_time_in_millis / 1000.0f; sensor.get_data(sensor_data); WithRobot::Quaternion& sensor_orientation = sensor_data.quaternion; WithRobot::ImuData<float>& imu_data = sensor_data.imu; glm::vec3 accel_local(imu_data.ax, imu_data.ay, imu_data.az); glm::quat orientation(sensor_orientation.w, sensor_orientation.x, sensor_orientation.y, sensor_orientation.z); glm::vec3 accel_world = orientation * accel_local; glm::vec3 gravity_vector{0.0, 0.0, -1.0}; accel_world -= gravity_vector; if (std::abs(accel_world.x) < sensitivity_threshold) { accel_world.x = 0.0f; } if (std::abs(accel_world.y) < sensitivity_threshold) { accel_world.y = 0.0f; } if (std::abs(accel_world.z) < sensitivity_threshold) { accel_world.z = 0.0f; } velocity += 9.81f * accel_world * dt; position += velocity * dt; std::cout << position.x << " " << position.y << " " << position.z << std::endl; } void Probe::update_loop() { using namespace std::chrono; std::cout << "update_loop start" << std::endl; to_sleep_time = high_resolution_clock::now(); while (connected && !should_terminate) { // Measure processing time process_start_time = high_resolution_clock::now(); auto time_since_last_process = duration_cast<milliseconds>(process_start_time - to_sleep_time); // Process data update(time_since_last_process.count()); // Put the thread to sleep for the remaining time within the interval to_sleep_time = high_resolution_clock::now(); auto process_duration = duration_cast<milliseconds>(to_sleep_time - process_start_time); std::this_thread::sleep_for(polling_interval_duration - process_duration); } std::cout << "update_loop end" << std::endl; }
Markdown
UTF-8
785
2.796875
3
[]
no_license
# Technical_Analysis_Indicators_with_Python In this repository, I have tried to implement some of the commonly used Technical Analysis Indicators using basic Python programming. Below is the list of Technical Indicators i have added included (Note: I plan on adding some more indicators to the notebook) 1. Moving Average 2. Exponential Moving Average 3. Bollinger Bands 4. Moving Average Convergence Divergence (MACD) All the implementation is dynamic as data for any stock can be imported using the get_data_yahoo API. Moreover, the indicators can also be modified using by changing the parameters in the defined functions for each indicator. Libraries Used: - Pandas - Numpy - Matplotlib - Math - Pandas Datareader <img src = "images/Technical_Indicators.PNG" width = "1000">
JavaScript
UTF-8
1,669
4.25
4
[]
no_license
/* const assertEqual = function(actual, expected) { if (actual === expected) { console.log("Assertion Passed: " + actual + " === " + expected); } else { console.log("Assertion Failed: " + actual + " !== " + expected); } }; const eqArrays = function(arr1, arr2) { if (arr1.length !== arr2.length) { return false; } for (let i = 0; i < arr1.length; i++) { if (arr1[i] !== arr2[i]) { return false; } } return true; }; */ // Returns true if both objects have identical keys with identical values. // Otherwise you get back a big fat false! const eqObjects = function(object1, object2) { let len1 = Object.keys(object1).length; let len2 = Object.keys(object2).length; let value1, value2; let found = false; if (len1 !== len2) return false; for (const key1 in object1) { if (Object.hasOwnProperty.call(object1, key1)) { value1 = object1[key1]; } found = false; for (const key2 in object2) { if (Object.hasOwnProperty.call(object2, key2)) { value2 = object2[key2]; if ((key1 === key2) && (eqArrays(value1, value2))) found = true; } } if (found === false) return false; } return true; }; module.exports = eqObjects; /* const ab = { a: "1", b: "2" }; const ba = { b: "2", a: "1" }; assertEqual(eqObjects(ab, ba), true); // => true const abc = { a: "1", b: "2", c: "3" }; assertEqual(eqObjects(ab, abc), false); // => false const cd = { c: "1", d: ["2", 3] }; const dc = { d: ["2", 3], c: "1" }; assertEqual(eqObjects(cd, dc), true); // => true const cd2 = { c: "1", d: ["2", 3, 4] }; assertEqual(eqObjects(cd, cd2), false); // => false */
Python
UTF-8
332
3.703125
4
[]
no_license
""" Bisect: - "Built-in" binary search method in Python. - Can be used to search for an element in a sorted list. """ import bisect A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] print(bisect.bisect_left(A, 285)) print(bisect.bisect_right(A, 285)) print(bisect.bisect(A, 285)) print(A) bisect.insort_right(A, 108) print(A)
Java
UTF-8
4,948
1.96875
2
[]
no_license
package com.example.taiga.cleapp; import android.annotation.SuppressLint; import android.app.DownloadManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Environment; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.webkit.CookieManager; import android.webkit.DownloadListener; import android.webkit.WebView; import android.webkit.WebViewClient; import java.net.URI; public class MainActivity extends AppCompatActivity { WebView webView; CoordinatorLayout coordinatorLayout; boolean kill=false; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences data = getSharedPreferences("LoginData", Context.MODE_PRIVATE); String userId = data.getString("userId", null); String userPass = data.getString("userPass", null); if (userId != null && userPass != null) { coordinatorLayout = (CoordinatorLayout)findViewById(R.id.first_coordinator_layout); webView = (WebView) findViewById(R.id.web_v); webView.setWebViewClient(new MyWVClient(userId, userPass)); webView.loadUrl("https://cleweb.tsc.u-tokai.ac.jp/campusweb/top.do"); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setDomStorageEnabled(true); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setUseWideViewPort(true); webView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { String[] values = contentDisposition.split("filename="); String filename = values[1].replaceAll("\"", ""); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); String host = URI.create(url).getHost(); //String cookies = CookieManager.getInstance().getCookie(host); request.allowScanningByMediaScanner(); request.addRequestHeader("Cookie", "CLE"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setVisibleInDownloadsUi(false); request.setTitle(filename); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); if (dm != null) { dm.enqueue(request); } else { //失敗? Log.d("SSS", "aa"); } } }); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if(!kill) { kill = true; Snackbar.make(coordinatorLayout,"もう一度押すと終了します", Snackbar.LENGTH_LONG).show(); return false; } return super.onKeyDown(keyCode, event); } else { kill=false; return super.onKeyDown(keyCode, event); } } public void setting(View v) { Intent intent = new Intent(this, LoginActivity.class); intent.putExtra("EditMode", true); startActivity(intent); } } class MyWVClient extends WebViewClient { private static final String LOGIN_URL = "https://cleweb.tsc.u-tokai.ac.jp/campusweb/top.do"; private String id = null; private String pass = null; public MyWVClient(String id, String pass) { this.id = id; this.pass = pass; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (url.startsWith(LOGIN_URL)) { view.loadUrl(String.format( "javascript:document.getElementById('userId').value='" + this.id + "';" + "document.getElementById('password').value='" + this.pass + "';" + "javascript:document.getElementById('loginButton').click();")); // // view.loadUrl(String.format("")); } } }
JavaScript
UTF-8
311
2.890625
3
[ "MIT" ]
permissive
/** * Or logic condition * @param {Cond} cond */ var Cond = function () { this.conds = Array.prototype.slice.call(arguments, 0); } Cond.prototype.evaluate = function(bb) { for (var i = 0, n = this.conds.length; i < n; ++i) { if (this.conds[i].evaluate(bb)) return true; } }; module.exports = Cond;
Java
UTF-8
9,351
2.109375
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2009 Omnidroid - http://code.google.com/p/omnidroid * * 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 edu.nyu.cs.omnidroid.app.model.db; import edu.nyu.cs.omnidroid.app.model.db.DbHelper; import edu.nyu.cs.omnidroid.app.model.db.RuleDbAdapter; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.test.AndroidTestCase; /** * Android Unit Test for {@link RuleDbAdapter} class. */ public class RuleDbAdapterTest extends AndroidTestCase { private RuleDbAdapter dbAdapter; private DbHelper omnidroidDbHelper; // Data for testing private Long[] eventIDs = { Long.valueOf(1), Long.valueOf(2), Long.valueOf(3) }; private String[] ruleNames = { "rule1", "rule2", "rule3" }; private String[] ruleDescs = { "desc1", "desc2", "desc3" }; private static final boolean SEND_NOTIFICATION = true; @Override protected void setUp() throws Exception { super.setUp(); omnidroidDbHelper = new DbHelper(this.getContext()); dbAdapter = new RuleDbAdapter(omnidroidDbHelper.getWritableDatabase()); omnidroidDbHelper.backup(); dbAdapter.deleteAll(); } @Override protected void tearDown() throws Exception { dbAdapter.deleteAll(); // Try to restore the database if (omnidroidDbHelper.isBackedUp()) { omnidroidDbHelper.restore(); } omnidroidDbHelper.close(); super.tearDown(); } public void testPrecondition() { Cursor cursor = dbAdapter.fetchAll(); assertEquals(cursor.getCount(), 0); } public void testInsert() { long id1 = dbAdapter.insert(eventIDs[0], ruleNames[0], ruleDescs[0], true); assertTrue(id1 != -1); long id2 = dbAdapter.insert(eventIDs[1], ruleNames[1], ruleDescs[1], true); assertTrue(id1 != id2); } public void testInsert_illegalArgumentException() { Exception expected = null; try { dbAdapter.insert(null, ruleNames[0], ruleDescs[0], true); } catch (IllegalArgumentException e) { expected = e; } assertNotNull(expected); expected = null; try { dbAdapter.insert(eventIDs[0], null, ruleDescs[0], true); } catch (IllegalArgumentException e) { expected = e; } assertNotNull(expected); try { dbAdapter.insert(eventIDs[0], ruleNames[0], null, true); } catch (IllegalArgumentException e) { expected = e; } assertNotNull(expected); try { dbAdapter.insert(eventIDs[0], ruleNames[0], ruleDescs[0], null); } catch (IllegalArgumentException e) { expected = e; } assertNotNull(expected); } public void testFetch() { long id = dbAdapter.insert(eventIDs[0], ruleNames[0], ruleDescs[0], true); Cursor cursor = dbAdapter.fetch(id); // Validate the inserted record. assertCursorEquals(cursor, eventIDs[0], ruleNames[0], ruleDescs[0], true); // Validate the record count assertEquals(dbAdapter.fetchAll().getCount(), 1); } public void testFetch_notExisting() { long id = dbAdapter.insert(eventIDs[0], ruleNames[0], ruleDescs[0], true); Cursor cursor = dbAdapter.fetch(id + 1); assertEquals(cursor.getCount(), 0); } public void testFetch_illegalArgumentException() { Exception expected = null; try { dbAdapter.fetch(null); } catch (IllegalArgumentException e) { expected = e; } assertNotNull(expected); } public void testDelete() { long id = dbAdapter.insert(eventIDs[0], ruleNames[0], ruleDescs[0], true); assertTrue(dbAdapter.delete(id)); // Validate it cannot be fetched. Cursor cursor = dbAdapter.fetch(id); assertEquals(cursor.getCount(), 0); } public void testDelete_notExisting() { long id = dbAdapter.insert(eventIDs[0], ruleNames[0], ruleDescs[0], true); assertTrue(dbAdapter.delete(id)); assertFalse(dbAdapter.delete(id)); } public void testDelete_illegalArgumentException() { Exception expected = null; try { dbAdapter.delete(null); } catch (IllegalArgumentException e) { expected = e; } assertNotNull(expected); } public void testUpdate() { long id = dbAdapter.insert(eventIDs[0], ruleNames[0], ruleDescs[0], false); assertTrue(dbAdapter.update(id, eventIDs[1], ruleNames[1], ruleDescs[1], true, SEND_NOTIFICATION)); // Validate the updated record. Cursor cursor = dbAdapter.fetch(id); assertCursorEquals(cursor, eventIDs[1], ruleNames[1], ruleDescs[1], true); } public void testUpdate_notExisting() { long id = dbAdapter.insert(eventIDs[0], ruleNames[0], ruleDescs[0], true); dbAdapter.delete(id); assertFalse(dbAdapter.update(id, eventIDs[1], ruleNames[1], ruleDescs[1], false, SEND_NOTIFICATION)); } public void testUpdate_withNullValues() { long id = dbAdapter.insert(eventIDs[1], ruleNames[1], ruleDescs[1], false); assertFalse(dbAdapter.update(id, null, null, null, null, null)); // Validate the updated record. Cursor cursor = dbAdapter.fetch(id); assertCursorEquals(cursor, eventIDs[1], ruleNames[1], ruleDescs[1], false); } public void testUpdate_illegalArgumentException() { Exception expected = null; try { dbAdapter.update(null, eventIDs[0], ruleNames[0], ruleDescs[0], false, SEND_NOTIFICATION); } catch (IllegalArgumentException e) { expected = e; } assertNotNull(expected); } public void testFetchAll() { dbAdapter.insert(eventIDs[0], ruleNames[0], ruleDescs[0], false); dbAdapter.insert(eventIDs[1], ruleNames[1], ruleDescs[1], false); dbAdapter.insert(eventIDs[2], ruleNames[2], ruleDescs[2], false); Cursor cursor = dbAdapter.fetchAll(); assertEquals(cursor.getCount(), 3); } public void testFetchAll_withParameters() { dbAdapter.insert(eventIDs[0], ruleNames[0], ruleDescs[0], true); dbAdapter.insert(eventIDs[0], ruleNames[1], ruleDescs[1], true); dbAdapter.insert(eventIDs[2], ruleNames[1], ruleDescs[2], true); assertTrue(dbAdapter.fetchAll(null, null, null, null, null).getCount() == 3); assertTrue(dbAdapter.fetchAll(eventIDs[0], null, null, null, null).getCount() == 2); assertTrue(dbAdapter.fetchAll(null, ruleNames[1], null, null, null).getCount() == 2); assertTrue(dbAdapter.fetchAll(null, null, ruleDescs[2], null, null).getCount() == 1); assertTrue(dbAdapter.fetchAll(null, null, ruleDescs[2], false, null).getCount() == 0); } public void testFetchAll_withSortOrder() throws InterruptedException { long[] ids = new long[3]; // Insert record 1, 2, 3 for (int i = 0; i <= 2; i++) { ids[i] = dbAdapter.insert(eventIDs[i], ruleNames[i], ruleDescs[i], true); Thread.sleep(1000); // SQLite3 datetime type doesn't support less than 1 second } // Update record 3, 2, 1 for (int i = 2; i >= 0; i--) { dbAdapter.update(ids[i], eventIDs[i], ruleNames[i], ruleDescs[i], true, SEND_NOTIFICATION); Thread.sleep(1000); // SQLite3 datetime type doesn't support less than 1 second } // Sort by latest created, verify the order Cursor cursor1 = dbAdapter .fetchAll(null, null, null, null, RuleDbAdapter.KEY_CREATED + " DESC"); for (int i = 2; i >= 0; i--) { cursor1.moveToNext(); assertCursorEquals(cursor1, eventIDs[i], ruleNames[i], ruleDescs[i], true); } assertFalse(cursor1.moveToNext()); // Sort by latest updated, verify the order Cursor cursor2 = dbAdapter .fetchAll(null, null, null, null, RuleDbAdapter.KEY_UPDATED + " DESC"); for (int i = 0; i <= 2; i++) { cursor2.moveToNext(); assertCursorEquals(cursor2, eventIDs[i], ruleNames[i], ruleDescs[i], true); } assertFalse(cursor2.moveToNext()); } public void testFetchAll_withSQLiteException() { for (int i = 0; i <= 2; i++) { dbAdapter.insert(eventIDs[i], ruleNames[i], ruleDescs[i], true); } Exception expected = null; try { dbAdapter.fetchAll(null, null, null, null, "InvalidOrderBy"); } catch (SQLiteException e) { expected = e; } assertNotNull(expected); } /** * Helper method to assert a cursor pointing to a rule record that matches the parameters */ private void assertCursorEquals(Cursor cursor, long eventID, String ruleName, String ruleDesc, boolean enabled) { assertEquals(cursor.getInt(cursor.getColumnIndex(RuleDbAdapter.KEY_EVENTID)), eventID); assertEquals(cursor.getString(cursor.getColumnIndex(RuleDbAdapter.KEY_RULENAME)), ruleName); assertEquals(cursor.getString(cursor.getColumnIndex(RuleDbAdapter.KEY_RULEDESC)), ruleDesc); assertEquals(cursor.getInt(cursor.getColumnIndex(RuleDbAdapter.KEY_ENABLED)) == 1, enabled); } }
Markdown
UTF-8
312
2.625
3
[]
no_license
Password Generator HW #3 Its tough choosing a new password for all of these new websites and apps. Well I solved that for you with this password generator you'll never have to come up with your own again! Just choose your own length what kind of characters and numbers you want and, BAM! Your passowrd is ready
Swift
UTF-8
564
2.9375
3
[]
no_license
// // StringExtension.swift // FuriganaApp // // Created by 出店 純一 on 2019/02/17. // Copyright © 2019年 出店 純一. All rights reserved. // import Foundation extension String { /// URLエンコード(エスケープ有) var urlEncoded: String { let charset = CharacterSet.alphanumerics.union(.init(charactersIn: "/?-._~")) // URLデコード let removed = removingPercentEncoding ?? self // URLエンコード return removed.addingPercentEncoding(withAllowedCharacters: charset) ?? removed } }
Java
UTF-8
2,029
2.265625
2
[]
no_license
package com.css.bdpfnew.web.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.css.bdpfnew.Message; import com.css.bdpfnew.model.dto.DtoDiaoquParams; import com.css.bdpfnew.service.KsqrJiekouService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; /** * @Author HEYCH * @Date 2018年11月21日 上午14:30:18 * @Description: */ @RestController @RequestMapping("/ksqrJiekou") @Api(value = "残疾人操作") public class KsqrJiekouController { @Autowired private KsqrJiekouService ksqrJiekouService; @PostMapping("/getKsqrCitizenInfo") @ApiOperation(value = "调取接口后初始化残疾人信息", notes = "调取接口后初始化残疾人信息") private Message getCitizenInfo(@Valid @RequestBody DtoDiaoquParams dtoDiaoquParams) { try { String cdpfIdAndrequestId = ksqrJiekouService.getCitizenInfo(dtoDiaoquParams.getCitizenId(), dtoDiaoquParams.getCitizenName()); if(cdpfIdAndrequestId == "1001"){ return Message.error("未调取到此人信息!", Message.ERROR_CODE_EMPTY_DATA); }else if (cdpfIdAndrequestId == "1000"){ return Message.error("调取出错,请联系管理人员!", Message.ERROR_CODE_REQUEST_EXPIRED); }else if (cdpfIdAndrequestId == "1002"){ return Message.error("未生成当天sessionId !", Message.ERROR_CODE_EMPTY_DATA); }else if (cdpfIdAndrequestId == "1003"){ return Message.error("此人已存在于系统中,请勿重复录入!", Message.ERROR_CODE_REQUEST_EXPIRED); }else { return Message.success("调取并保存成功", cdpfIdAndrequestId); } } catch (Exception e) { e.printStackTrace(); return Message.error("持久层异常", Message.ERROR_CODE_SQL); } } }
Python
UTF-8
681
3.40625
3
[]
no_license
import unittest def exchange_bit_pair(input): tmp = input even_mask, odd_mask = 0, 0 while tmp: even_mask <<= 2 odd_mask <<= 2 even_mask |= 1 odd_mask |= 2 tmp >>= 2 return ((input & even_mask) << 1) | ((input & odd_mask) >> 1) def exchange_bit_pair2(input): return ((input & 0xaaaaaaaa) >> 1) | ((input & 0x55555555) << 1) class Test(unittest.TestCase): def test_simple(self): self.assertEquals(exchange_bit_pair(1), 2) self.assertEquals(exchange_bit_pair(10), 5) self.assertEquals(exchange_bit_pair(int('1101001', 2)), int('10010110', 2)) if __name__ == '__main__': unittest.main()
JavaScript
UTF-8
2,674
2.859375
3
[]
no_license
describe('decco.js', function(){ describe('Decco', function(){ it('After', function(){ var decco = new Decco(); var module = { add : function(a,b){ return a+b }, subtract : function(a,b){ return a-b } } var result = ""; var funcName = ""; decco.After(module,function(args,name,val){ result = val; funcName=name; }); module.add(1,2); expect(result).to.equal(3); expect(funcName).to.equal("add"); }); it('Before', function(){ var decco = new Decco(); var module = { add : function(a,b){ return a+b }, subtract : function(a,b){ return a-b } } var args = []; var funcName = ""; decco.Before(module,function(val,name){ args = val; funcName=name; }); module.add(1,2); expect(args).to.include(1); expect(args).to.include(2); expect(funcName).to.equal("add"); }); it('Attach to named function', function(){ var decco = new Decco(); var module = { add : function(a,b){ return a+b }, subtract : function(a,b){ return a-b } } var args = []; var funcName = ""; var options = { decorate: ["add"], }; decco.Before(module,function(val,name){ args = val; funcName = name; },options); module.add(1,2); expect(args).to.include(1); expect(args).to.include(2); expect(funcName).to.equal("add"); args = []; funcName = ""; module.subtract(1,2); expect(args.length).to.equal(0); expect(funcName).to.equal(""); }); }) })
Python
UTF-8
1,390
4.40625
4
[]
no_license
# File: ex_7.9-calculate_Easter.py # Date: 2019-12-19 # Author: "Hannes Thiersen" <hannesthiersen@gmail.com> # Version: 0.1 # Description: # A formula for computing Easter in the years 1982 - 2048, inclusive, is as # follows: let a = year%19, b = year%4, c=year%7, d = (19a + 24)%30, e = (2b # + 4c + 6d + 5)%7, respectively. Write a program that inputs a year, # verifies that it is in the proper range, and then prints out the date of # Easter that year. #------------------------------------------------------------------------------ # FUNCTIONS #------------------------------------------------------------------------------ def easter(year): if not 1982 <= year <= 2048: print("Year is outside valid range 1982 - 2048.") return None a = year%19 b = year%4 c = year%7 d = (19*a + 24)%30 e = (2*b + 4*c + 6*d + 5)%7 date = 22 + d + e if date < 31: print(f"{date} March {year}") else: print(f"{date-31} April {year}") return None #------------------------------------------------------------------------------ # MAIN #------------------------------------------------------------------------------ def main(): year = eval(input("Insert year: ")) easter(year) #------------------------------------------------------------------------------ if __name__ == '__main__': main()
Swift
UTF-8
898
2.921875
3
[]
no_license
// // DetailViewModel.swift // TestingWorkshop // // Created by Konrad Roj on 08/04/2019. // Copyright © 2019 Skyrise. All rights reserved. // import Foundation class DetailViewModel { private let service: MeasurementStationsServiceProtocol let station: Station var measurements = [MeasurementList]() init(service: MeasurementStationsServiceProtocol, station: Station) { self.service = service self.station = station } func getMeasurement(symbol: MeasurementSymbol, completion: @escaping () -> Void) { service.getMeasurement(station: station, symbol: symbol, success: { [weak self] (measurement) in guard let self = self else { return } self.measurements.append(measurement) completion() }) { (error) in print(error?.localizedDescription ?? "Unknown error") } } }
Java
UTF-8
923
2.125
2
[]
no_license
package com.mydataway.demo1.service; import com.mydataway.demo1.dao.Demo1Repo; import com.mydataway.demo1.api.Demo1Api; import com.mydataway.demo2.api.Demo2Api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by yatu on 17/5/8. */ @RestController @RequestMapping("/api") public class Demo1Service implements Demo1Api { @Autowired private Demo1Repo demo1Repo; @Autowired private Demo2Api demo2Api; public String helloDemo1() { // try { // Thread.sleep(10000); // } catch (InterruptedException e) { // e.printStackTrace(); // } return "demo1 service -> " + demo1Repo.getDemo1List(); } public String helloDemo2() { return "demo1 service -> " + demo2Api.helloDemo2(); } }
C++
UTF-8
397
2.828125
3
[]
no_license
#include<iostream> #include<string> using namespace std; int main() { string username,password; for(int i=1;i<=3;i++) { cout<<"Enter Username : "; getline(cin,username); cout<<"Enter pasword : "; getline(cin,password); { if(username=="abcd" && password=="pakistan") { cout<<"Login successul"; i=4; } else { cout<<"Login Failed"<<endl; } } } }
C++
UTF-8
1,107
2.578125
3
[]
no_license
union CheckEndian_ { u32 bits32; u8 bytes[4]; }; inline u8 EndianUtil::GetEndian() { CheckEndian_ val; val.bytes[ 0 ] = 0; val.bytes[ 1 ] = 1; val.bytes[ 2 ] = 0; val.bytes[ 3 ] = 0; return ( val.bits32 == 256 ) ? 0 : 1; } inline void _Swap( u8 *pcA, u8 *pcB ) { skyMString acValue = pcA[ 0 ]; pcA[ 0 ] = pcB[ 0 ]; pcB[ 0 ] = acValue; } inline void EndianUtil::Swap16( u8 *pSrcDest , u32 num ) { for ( u32 i = 0 ; i < num ; i++ ) { _Swap( &pSrcDest[ 0 ] , &pSrcDest[ 1 ] ); pSrcDest += 2; } } inline void EndianUtil::Swap32( u8 *pSrcDest , u32 num ) { for (u32 i = 0; i < num; i++ ) { _Swap( &pSrcDest[ 0 ], &pSrcDest[ 3 ] ); _Swap( &pSrcDest[ 1 ], &pSrcDest[ 2 ] ); pSrcDest += 4; } } inline void EndianUtil::Swap64( u8 *pSrcDest , u32 num ) { for (u32 i = 0; i < num; i++) { _Swap( &pSrcDest[ 0 ] , &pSrcDest[ 7 ] ); _Swap( &pSrcDest[ 1 ] , &pSrcDest[ 6 ] ); _Swap( &pSrcDest[ 2 ] , &pSrcDest[ 5 ] ); _Swap( &pSrcDest[ 3 ] , &pSrcDest[ 4 ] ); pSrcDest += 8; } }
Java
UTF-8
1,941
2.21875
2
[ "Apache-2.0" ]
permissive
package com.yi.github.login.controller; import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.request.AuthGiteeRequest; import me.zhyd.oauth.request.AuthGithubRequest; import me.zhyd.oauth.request.AuthRequest; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * GitHub授权登录 * * @author YI * @date 2019-4-2 10:13:43 */ @RestController @RequestMapping("/oauth") public class GitHubController { /** * 生成授权地址 * @param response * @throws IOException */ @RequestMapping("/render/github") public void rendderAuth(HttpServletResponse response) throws IOException { AuthRequest authRequest = getAuthRequest(); response.sendRedirect(authRequest.authorize()); } /** * 回调 * @param code 用户授权后回调回本地系统时携带的参数 * @return */ @RequestMapping("/callback/github") public Object login(String code){ AuthRequest authRequest = getAuthRequest(); return authRequest.login(code); } /** * 取消授权 * @param token 授权的token * @return */ @RequestMapping("/revoke/github/{token}") public Object revokeAuth(@PathVariable("token") String token){ AuthRequest authRequest = getAuthRequest(); return authRequest.revoke(token); } /** * 创建授权 * @return */ private AuthRequest getAuthRequest(){ return new AuthGithubRequest(AuthConfig.builder() .clientId("d4e48f1e8b60bf90efb1") .clientSecret("67d31e882631a50a0b6c7c1e11a38f39076b0e9a") .redirectUri("http://localhost:8080/oauth/callback/github") .build() ); } }
Shell
UTF-8
3,692
3.75
4
[ "CC-BY-4.0" ]
permissive
# funct_command_value # # Audit command output values # # Depending on the command_name send an appropriate check_command and set_command are set # If the current_value is not the correct_value then it is fixed if run in lockdown mode # A copy of the value is stored in a log file, which can be restored #. funct_command_value () { command_name=$1 parameter_name=$2 correct_value=$3 service_name=$4 total=`expr $total + 1` if [ "$audit_mode" = 2 ]; then restore_file="$restore_dir/$command_name.log" if [ -f "$restore_file" ]; then parameter_name=`cat $restore_file |grep '$parameter_name' |cut -f1 -d','` correct_value=`cat $restore_file |grep '$parameter_name' |cut -f2 -d','` if [ `expr "$parameter_name" : "[A-z]"` = 1 ]; then echo "Returning $parameter_name to $correct_value" if [ "$command_name" = "routeadm" ]; then if [ "$correct_value" = "disabled" ]; then set_command="routeadm -d" else set_command="routeadm -e" fi $set_command $parameter_name else $set_command $parameter_name $correct_value if [ `expr "$parameter_name" : "tcp_trace"` = 9 ]; then svcadm refresh svc:/network/inetd fi fi fi fi else if [ "$parameter_name" = "tcp_wrappers" ]; then echo "Checking: Service $service_name has \"$parameter_name\" set to \"$correct_value\"" else echo "Checking: Output of $command_name \"$parameter_name\" is \"$correct_value\"" fi fi if [ "$command_name" = "inetadm" ]; then check_command="inetadm -l $service_name" set_command="inetadm -m $service_name" current_value=`$check_command |grep "$parameter_name" |awk '{print $2}' |cut -f2 -d'='` fi if [ "$command_name" = "routeadm" ]; then check_command="routeadm -p $parameter_name" current_value=`$check_command |awk '{print $3}' |cut -f2 -d'='` fi log_file="$work_dir/$command_name.log" if [ "$current_value" != "$correct_value" ]; then if [ "$audit_mode" = 1 ]; then insecure=`expr $insecure + 1` echo "Warning: Parameter \"$parameter_name\" not set to \"$correct_value\" [$insecure Warnings]" if [ "$command_name" = "routeadm" ]; then if [ "$correct_value" = "disabled" ]; then set_command="routeadm -d" else set_command="routeadm -e" fi funct_verbose_message "" fix funct_verbose_message "$set_command $parameter_name" fix funct_verbose_message "" fix else funct_verbose_message "" fix funct_verbose_message "$set_command $parameter_name=$correct_value" fix funct_verbose_message "" fix fi else if [ "$audit_mode" = 0 ]; then echo "Setting: $parameter_name to $correct_value" echo "$parameter_name,$current_value" >> $log_file if [ "$command_name" = "routeadm" ]; then if [ "$correct_value" = "disabled" ]; then set_command="routeadm -d" else set_command="routeadm -e" fi $set_command $parameter_name else $set_command $parameter_name=$correct_value fi fi fi else if [ "$audit_mode" != 2 ]; then if [ "$audit_mode" = 1 ]; then secure=`expr $secure + 1` if [ "$parameter_name" = "tcp_wrappers" ]; then echo "Secure: Service $service_name already has \"$parameter_name\" set to \"$correct_value\"" else echo "Secure: Output for command $command_name \"$parameter_name\" already set to \"$correct_value\" [$secure Passes]" fi fi fi fi }
JavaScript
UTF-8
1,484
2.734375
3
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
/* @flow strict-local */ import md5 from 'blueimp-md5'; import type { Message, Outbox, User } from '../types'; import { getFullUrl } from './url'; /** * When selecting the size of a gravatar we can pick any arbitrary * size we want. For server-uploaded avatars this is not the case. * We have only: * * default - image is 100x100 * * medium - image is 500x500 * * This function converts a normal avatar to medium-sized one. */ export const getMediumAvatar = (avatarUrl: string): string => { const matches = new RegExp(/(\w+)\.png/g).exec(avatarUrl); return matches ? avatarUrl.replace(matches[0], `${matches[1]}-medium.png`) : avatarUrl; }; export const getGravatarFromEmail = (email: string = '', size: number): string => `https://secure.gravatar.com/avatar/${md5(email.toLowerCase())}?d=identicon&s=${size}`; export const getAvatarUrl = ( avatarUrl: ?string, email: string, realm: string, size: number = 80, ): string => { if (typeof avatarUrl !== 'string') { return getGravatarFromEmail(email, size); } const fullUrl = getFullUrl(avatarUrl, realm); return size > 100 ? getMediumAvatar(fullUrl) : fullUrl; }; export const getAvatarFromUser = (user: User, realm: string, size?: number): string => getAvatarUrl(user.avatar_url, user.email, realm, size); export const getAvatarFromMessage = ( message: Message | Outbox, realm: string, size?: number, ): string => getAvatarUrl(message.avatar_url, message.sender_email, realm, size);
C#
UTF-8
3,177
2.65625
3
[]
no_license
using CharlyBeck.Mvi.Extensions; using CharlyBeck.Mvi.World; using Mvi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CharlyBeck.Mvi.Models { using CColoredVertex = Tuple<CVector3Dbl, CVector3Dbl>; using CColor = CVector3Dbl; public class COctaeder { public COctaeder(double aW = 1.0d) { W = aW; P0 = new CVector3Dbl(Xc, Yb, Zc); P1 = new CVector3Dbl(Xl, Yc, Zf); P2 = new CVector3Dbl(Xr, Yc, Zf); P3 = new CVector3Dbl(Xr, Yc, Zb); P4 = new CVector3Dbl(Xl, Yc, Zb); P5 = new CVector3Dbl(Xc, Yt, Zc); Ps= new CVector3Dbl[] { P0, P1, P2, P3, P4, P5 }; P0C = CColors.C_Red; P1C = CColors.C_Blue; P2C = CColors.C_Yellow; P3C = CColors.C_Blue; P4C = CColors.C_Yellow; P5C = CColors.C_Green; Colors = new CColor[] { P0C, P1C, P2C, P3C, P4C, P5C }; Tis = new int[] { 0, 1, 2, 0,2,3, 0,3,4, 0,4,1, 1,5,2, 2,5,3, 3, 5, 4 , 4,5,1 }; var aLineListIndexes = new int[] { 0,1, 0,2, 0,3, 0,4, 1,2, 2,3, 3,4, 4,1, 5,1, 5,2, 5,3, 5,4 }; this.LineList = (from aIdx in aLineListIndexes select Ps[aIdx]).ToArray(); this.ColoredTriangleList = (from aIdx in Enumerable.Range(0, TCount * 3) select Ps[Tis[aIdx]].ToColoredVertex(this.Colors[Tis[aIdx]])).ToArray(); this.ColoredLineList = this.ColoredTriangleList.TriangleListToLineList().ToArray(); } public double W; public double L => W / 2.0d; public double Xl => -L; public double Xc => 0; public double Xr => L; public double Yb => -L; public double Yc => 0; public double Yt => L; public double Zf => L; public double Zc => 0; public double Zb => -L; public CVector3Dbl P0; public CVector3Dbl P1; public CVector3Dbl P2; public CVector3Dbl P3; public CVector3Dbl P4; public CVector3Dbl P5; public CVector3Dbl[] Ps; public CColor P0C; public CColor P1C; public CColor P2C; public CColor P3C; public CColor P4C; public CColor P5C; public CColor[] Colors; public int[] Tis; // TriangleIndexes public const int PCount = 6; public const int TCount = 8; public readonly CColoredVertex[] ColoredTriangleList; public readonly CColoredVertex[] ColoredLineList; public readonly CVector3Dbl[] LineList; } }
Java
UTF-8
733
1.945313
2
[]
no_license
package lxs.pojo.qo.mp; import hg.common.component.BaseQo; @SuppressWarnings("serial") public class TouristQO extends BaseQo { /** * 订单ID */ private String orderID; /** * 票号 */ private String ticketNo; /** * 票号 */ private Integer localStatus; public Integer getLocalStatus() { return localStatus; } public void setLocalStatus(Integer localStatus) { this.localStatus = localStatus; } public String getOrderID() { return orderID; } public void setOrderID(String orderID) { this.orderID = orderID; } public String getTicketNo() { return ticketNo; } public void setTicketNo(String ticketNo) { this.ticketNo = ticketNo; } }
Python
UTF-8
1,094
3.453125
3
[]
no_license
# coding: utf-8 from openpyxl import load_workbook, Workbook class Excel: def __init__(self, filename=None, write=False): self.filename = filename if write is False: self.wb = load_workbook(filename=filename) else: self.wb = Workbook() """ get_sheet_by_name、get_sheet_names已废弃,新写法参见: https://stackoverflow.com/questions/51202874/deprecationwarning-call-to-deprecated-function-get-sheet-by-name-use-wbsheetn """ # self.sheet1 = self.wb.get_sheet_by_name(self.wb.get_sheet_names()[0]) self.sheet1 = self.wb[self.wb.sheetnames[0]] def rows(self): """ Usage: for row in rows(): for cell in row: print(cell.value) """ return self.sheet1.rows def write(self, rows): """ write to excel file :param rows: [(row1),(row2)...] :return: None """ for row in rows: self.sheet1.append(row) def save(self): self.wb.save(self.filename)
Java
UTF-8
233
2.671875
3
[]
no_license
package epfl.sweng.util; public class Util { public static boolean isLetterOrDigit(String s) { for (int i=0;i<s.length();++i) { if (!Character.isLetterOrDigit(s.charAt(i))) { return false; } } return true; } }
Java
UTF-8
1,253
3.4375
3
[]
no_license
package IO_study; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class WriteDataUsingStream { public static void main(String[] args) { File dataFile = new File("F:\\javaeasy\\DataFileForOutputStream.txt"); if (dataFile.exists() && dataFile.isFile()) { System.out.println("存在文件"); } else { try { dataFile.createNewFile(); System.out.println("创建文件成功"); } catch (IOException e) { System.out.println("创建文件失败"); e.printStackTrace(); } } try { String context = "天儿"; byte[] contentBytes = context.getBytes(); FileOutputStream fos = new FileOutputStream(dataFile); fos.write(contentBytes); fos.close(); System.out.println("数据写入成功"); } catch (FileNotFoundException e) { System.out.println("找不到文件"); e.printStackTrace(); } catch (IOException e) { System.out.println("输出内容错误"); e.printStackTrace(); } } }
C++
GB18030
930
3.3125
3
[]
no_license
#pragma once class Point { public: Point(float x = 0, float y = 0);//캯 void setPoint(float a, float b);//ֵ float getX()const//ȡx { return _x; } float getY()const//ȡy { return _y; } friend ostream& operator<<(ostream& _cout, const Point& p); protected: float _x; float _y; }; class Circle :public Point { public : Circle(float x = 0, float y = 0, float r = 0);//캯 void setRadius(float r);//ð뾶ֵ float getRadius()const;//ȡ뾶ֵ float area()const; friend ostream& operator<<(ostream& _cout, const Circle& c); protected : float radius; }; class Cylinder :public Circle { public : Cylinder(float x = 0, float y = 0, float r = 0, float h = 0); void setHeight(float h); float getHeight()const; float area()const; float volume()const; friend ostream& operator<<(ostream& _cout, const Cylinder& c); protected : float height; };
Python
UTF-8
2,891
2.890625
3
[]
no_license
''' A (very) basic test of the escaping. This script adapts 'pyduino_example.py' to send a number of different strings to the arduino. The arduino echoes them back and the script checks that they are the same (having been escaped to be sent and then unescaped and reescaped on the arduino and finally unescaped on the PI) The arduino should load protocol.ino which is setup to echo anything which is sent back to the PI ''' from piduino import utils ESCAPE = utils.ESCAPE PACKET_START = utils.PACKET_START PACKET_END = utils.PACKET_END PACKET_DIVIDE = utils.PACKET_DIVIDE escapedValues = { "": "", ESCAPE: ESCAPE + ESCAPE, PACKET_START: ESCAPE + PACKET_START, PACKET_END: ESCAPE + PACKET_END, PACKET_DIVIDE: ESCAPE + PACKET_DIVIDE, ESCAPE + PACKET_START: ESCAPE + ESCAPE + ESCAPE + PACKET_START, ESCAPE + PACKET_END: ESCAPE + ESCAPE + ESCAPE + PACKET_END, ESCAPE + PACKET_DIVIDE: ESCAPE + ESCAPE + ESCAPE + PACKET_DIVIDE, "normal text": "normal text", ESCAPE + PACKET_START + PACKET_DIVIDE + PACKET_END: (ESCAPE + ESCAPE + ESCAPE + PACKET_START + ESCAPE + PACKET_DIVIDE + ESCAPE + PACKET_END) } def run(): global this_device, socket, destination this_device = utils.read_local_bdaddr() print('Searching for Arduinos...') destinations = utils.scan('SCD_ARDUINO') if len(destinations) == 0: print('No Arduinos found!') else: destination = destinations[0] print('Attempting to connect to device at '+destination) socket = utils.connect(destination) print('Connected!') for startOfString in ["", "start"]: # test starting with normal chars for endOfString in ["", "end"]: # test ending with normal chars for testItem, testResponse in escapedValues.items(): fullTest = startOfString + testItem + endOfString # fullResponse = startOfString + testResponse + endOfString actualResponse = send_message_wait_response(fullTest) if actualResponse[2] != fullTest: print("Test failed: {} not {}" .format(fullTest, actualResponse[2])) else: print("Test passed: {}".format(fullTest)) def send_message_wait_response(outgoing_message): outgoing_packaged_message = utils.package(this_device, destination, outgoing_message) success = utils.send_message(socket, outgoing_packaged_message) if success: incoming_packaged_message = utils.listen(socket) if incoming_packaged_message == '': raise IOError("No reply!") else: return utils.unpackage(incoming_packaged_message) else: raise IOError("Message not sent") utils.disconnect(socket) run()
Python
UTF-8
3,678
3.71875
4
[]
no_license
######### Missing Values ######### import pandas as pd import numpy as np import matplotlib.pyplot as plt pip install matplotlib plt.style.use("seaborn") PATH = "./data/burritos.csv" df = pd.read_csv(PATH, header=None) df.info() df.head() #After: PATH = "./data/burritos.csv" df = pd.read_csv(PATH, header=None, na_values="?") df.head() df.head(2) type(df.iloc[1,6]) df.isnull().sum().sort_values().plot(kind="barh", title="Missing Values "); ############# Mean ############# ############ Q: Choose a column and replace NaN values with the mean ############ # - # First Create Hist Plot to show columns 5 df[5].plot(kind="hist", bins=20, title="Histogram of Column 5"); # Then Calculate Variance before handling NaN values df[5].var() # Then Calculate mean c5_mean = df[5].mean() c5_mean # Replace NaN values with the mean: df[5] = df[5].fillna(c5_mean) df[5].isnull().sum() # Create Hist plot after Handled NaN Values df[5].plot(kind="hist", bins=20, title="Histogram of Column 5 with Handled NaN Values"); # Variance after handling NaN values df[5].var() ############# Median ############# ############ Q: Choose a column and replace NaN values with the median ############ # - # Imputing Median in column 8 # First Creatte a histogram plot #with bins=20 to see distribution of data df[8].plot(kind="hist", bins=20, title="Histogram of Column 8 without Handled NaN Values"); # Then Calculate median c8_median = df[8].median() c8_median # Replace NaN values with mode df[8] = df[8].replace(np.NaN, c8_median) # Create Hist plot after Handled NaN Values # with bins=20 to see distribution of data df[8].plot(kind="hist", bins=20, title="Histogram of Column 8 after Handled NaN Values"); ############# Mode ############# ############ Q: Choose a column and replace NaN values with the mode ############ # - # Imputing Mode in column 19 # First Create Plot that shows column 19 df[19].plot(kind="hist", bins=20, title="Histogram of Column 19 before Handled NaN Values"); # Then Calculate mode c19_mode = df[19].mode()[0] c19_mode # Replace NaN values after Calculated mode df[19] = df[19].replace(np.NaN, 19_mode) # Then Create hist After Handled NaN Values # Plot a histogram with bins=20 to see distribution of data df[19].plot(kind="hist", bins=20, title="Histogram of Column 19 After Handled NaN Values"); ############# Choose a column and replace NaN values with your own value ############# # replace NaN values in Address with No Address df["Address"].fillna("No Address", inplace = True) df ############# backwards filling ############# ############ Q: Choose a column and use backwards filling ############ # - # Backward filling will use the next value if it is not a NaN value to replace the NaN value being replaced. # Imputing Mode in column 23 # show a target column df[23] df[23].fillna(method="bfill") ############# forwards filling ############# ############ Q: Choose a column and use forwards filling ############ # - #Forward filling will use the previous value if it is not a NaN value to replace the NaN value being replaced. # Imputing Mode in column 23 # show a target column df[23] df[23].fillna(method="ffill") ########### Q: Determine how many missing values are present in each column ########### # - # Count total NaN at each column in a DataFrame print(" \nCount total NaN at each column in a DataFrame : \n\n", df.isnull().sum()) ########### Q:Determine the total amount of missing values ########### #apply a count over the rows: test_df.apply(lambda x: x.count(), axis=1) # then add the result as a column: test_df['full_count'] = test_df.apply(lambda x: x.count(), axis=1)
Ruby
UTF-8
273
2.796875
3
[]
no_license
class AccessControl def sample1 puts "This is public method" sample3 end protected def sample2 puts "This is protected method" end private def sample3 puts "This is private method" end end obj1=AccessControl.new obj1.sample1 #obj1.sample3
PHP
UTF-8
3,326
2.96875
3
[ "MIT" ]
permissive
<?php function validate($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } function isPica($data) { if (preg_match('/^[0-9]+(?i)p([0-1]?[0-9])?$/i', $data)) { return true; } return false; } function isPoint($data) { if (preg_match('/^[0-9]+(?i)pt$/i', $data)) { return true; } return false; } function makePoints($data) { $data = preg_replace('/^([0-9]+)((?i)p)(([0-1]?[0-9])?)$/i', '$1.$3', $data); $data = explode('.', $data); $points = floor($data[0] * 12); $points = $data[1] + $points; return $points; } function scaleRow($data, $points, $conversion = false, $emBase = false) { $output = '<td class="col"><span'; if ($data == $points) { $output .= ' class="highlight" '; } if ($conversion == 'ems') { if (!$emBase) { $data = round($data / $points, 3); } else { $data = round($data / $emBase, 3); } } else { $data = round($data,2); } $output .= '>' . $data . '</span></td>'; return $output; } /* todo: Make sure entry is a valid number, maybe test for px, pt, p, ems etc and handle accordingly. */ /* todo: Make calculations for ems and percent. */ if (isset( $_POST['submit'] )) { $base = validate($_POST['base']); $alt = validate($_POST['alt']); $ratio = validate($_POST['ratio']); $error = array(); if ($base < 999999) { if (isPica($base)) { $basePoints = makePoints($base); } elseif (isPoint($base)) { $basePoints = $base; } elseif (is_numeric($base)) { $basePoints = $base; } else { $basePoints = 0; $error['base'] = "Data not valid"; } } else { $error['base'] = "Number too large"; } if ($alt < 999999) { if (isPica($alt)) { $altPoints = makePoints($alt); } elseif (isPoint($alt)) { $altPoints = $alt; } elseif (is_numeric($alt)) { $altPoints = $alt; } else { $altPoints = 0; $error['alt'] = "Data not valid"; } } else { $error['alt'] = "Number too large"; } } else { $ratio = 1.618; $basePoints = 11; $altPoints = 210; $base = $basePoints; $alt = $altPoints; } if (empty( $error )) { if ($altPoints >= 9999) { $max = $altPoints; } else { $max = 9999; } $i = $basePoints; while ($i >= 1) { $baseScale[] = $i; $i = $i / $ratio; } $baseScale = array_reverse($baseScale); $i = $basePoints; while ($i <= $max) { $i = $i * $ratio; $baseScale[] = $i; } $i = $altPoints; while ($i >= 1) { $altScale[] = round($i, 1); $i = $i / $ratio; } $altScale = array_reverse($altScale); $i = $altPoints; while ($i <= $max) { $i = $i * $ratio; $altScale[] = $i; } $altScale = new ArrayIterator($altScale); $baseScale = new ArrayIterator($baseScale); $scale = new MultipleIterator(); $scale->attachIterator($baseScale); $scale->attachIterator($altScale); }
Java
UTF-8
192
2.359375
2
[]
no_license
package lessons.innerclasses; /** * Created by user on 06.04.2015. */ public class B extends A { public final void doSomething (){ System.out.println("B class method"); } }
Java
GB18030
1,916
2.171875
2
[]
no_license
package com.hrm.provider; import java.util.Map; import org.apache.ibatis.jdbc.SQL; import com.hrm.domain.Dept; import com.hrm.domain.Job; public class JobDynaSqlProvider { //̬ public String selectJob(final Job job){ return new SQL(){{ SELECT("*"); FROM("job_inf"); if(job.getName()!=null&&!job.getName().equals("")){ WHERE("name like '%'+#{name}+'%'"); } if(job.getRemark()!=null&&!job.getRemark().equals("")){ WHERE("remark like '%'+#{remark}+'%'"); } }}.toString(); } //ҳ //select top pageSize* //from job_inf //where id not in(select top (pageNow-1)*pageSize id from Job_inf) public String countJob(final Map params){ return new SQL(){{ Job job=(Job)params.get("job"); Integer pageSize=(Integer) params.get("pageSize"); Integer pageNow=(Integer) params.get("pageNow"); String sql1=" top "+pageSize+" *"; SELECT(sql1); FROM("job_inf"); if(job!=null){ if(job.getName()!=null&&!job.getName().equals("")){ WHERE("name like '%'+#{job.name}+'%'"); } if(job.getRemark()!=null&&!job.getRemark().equals("")){ WHERE("remark like '%'+#{job.remark}+'%'"); } } String sql2="id not in(select top "+(pageNow-1)*pageSize +" id from Job_inf)"; WHERE(sql2); }}.toString(); } //̬ public String insertJob(final Job job){ return new SQL(){{ INSERT_INTO("job_inf"); if(job.getName()!=null&&!job.getName().equals("")){ VALUES("name","#{name}"); } if(job.getRemark()!=null&&!job.getRemark().equals("")){ VALUES("remark","#{remark}"); } }}.toString(); } //̬ public String updateJob(final Job job){ return new SQL(){{ UPDATE("job_inf"); if(job.getName()!=null&&!job.getName().equals("")){ SET("name=#{name}"); } if(job.getRemark()!=null&&!job.getRemark().equals("")){ SET("remark=#{remark}"); } WHERE("id=#{id}"); }}.toString(); } }
PHP
UTF-8
3,877
2.609375
3
[ "MIT" ]
permissive
<?php namespace app\components; use app\base\Controller; use app\models\User; use Klein\DataCollection\RouteCollection; use Klein\Klein as Router; use Klein\Request; use Klein\Response; use Klein\Route; use PDO; class Application { protected string $name; protected Controller $controller; protected Request $request; protected Response $response; protected Database $db; protected Router $router; protected $user; public function __construct(array $config) { $this->name = $config['name']; $db = $config['db']; $pdo = new PDO('sqlite:' . $db['path']); $this->db = new Database($pdo); $this->request = Request::createFromGlobals(); $this->response = new Response(); $routes = $config['routes']; $routeCollection = new RouteCollection(); foreach ($routes as $name => $params) { $path = $params['path']; $method = $params['method']; $controller = $params['controller']; $action = $params['action']; $callback = function ($request, $response, $service, $app) use ($controller, $action) { return $app->runAction($controller, $action); }; $route = new Route($callback, $path, $method, true, is_string($name) ? $name : null); $routeCollection->addRoute($route); } $this->router = new Router(null, $this, $routeCollection); } public function run() { @session_start(); if (isset($_SESSION['user_id'])) { $userId = $_SESSION['user_id']; $row = $this->getDb()->users()->where('id', $userId)->fetch(); if ($row) { $user = new User($this->getDb()); $user->load($row->getData()); $this->user = $user; } else { unset($_SESSION['user_id']); } } $this->router->dispatch($this->request, $this->response, false); return $this->response->send(); } public function action404() { header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found', true, 404); die(); } public function action403() { header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden', true, 403); die(); } public function runAction(string $controllerName = 'default', string $actionName = 'index') { $controllerClass = 'app\controllers\\' . ucfirst($controllerName) . 'Controller'; $controller = new $controllerClass(strtolower($controllerName), $this); $this->controller = $controller; $controller->action = $actionName; return $controller->runAction($actionName); } public function login(User $user): bool { if ($user) { $_SESSION['user_id'] = $user->id; $this->user = $user; return true; } return false; } public function logout() { if ($this->user) { $this->user = null; } @session_destroy(); } public function getUser(): ?User { return $this->user; } public function isGuest(): bool { return !$this->user; } public function isAdmin(): bool { return (!$this->isGuest() && $this->getUser()->isAdmin()); } public function getRouter(): Router { return $this->router; } public function getRequest(): Request { return $this->request; } public function getResponse(): Response { return $this->response; } public function getController(): Controller { return $this->controller; } public function getDb(): Database { return $this->db; } public function getName(): string { return $this->name; } }
PHP
UTF-8
12,166
2.53125
3
[]
no_license
<?php namespace BREND\AGV\Models; use BREND\Constants\STATUS; use BREND\Constants\AGVSTATUS; use BREND\AGV\Models\AGV_request; use BREND\AGV\Models\AGV_response; use BREND\AGV\Exceptions\AGVException; class AGV{ protected $api_url; protected $AGV_name; protected $_Data = null; public function __construct($name, $url = null){ $this->AGV_name = $name; $this->api_url = ($url == null ? AGV_request::$url : $url); } public function getData(){ $httpResponse = AGV_request::POST($this->AGV_name, "500", array(), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function checkError(){ if(($statusCode = $this->_Data->getStatusCode()) !== AGVSTATUS::SUCCESS){ throw new AGVException($this->_Data->getConfig(), $statusCode); } return false; } public function getPrepareData(){ /* Battery string 電池電量 IsProgress bool 是否在執行 Status string API狀態碼 AGV_x string 電池電量 Battery string 電池電量 Battery string 電池電量 Battery string 電池電量 Battery string 電池電量 Battery string 電池電量 */ $data = $this->getData()->toArray(); $prepareData['StatusCode'] = $data['StatusCode']; $prepareData['Battery'] = $data['Config']['Battery']; $prepareData['Attitude']['Code'] = $data['Config']['Attitude']['Code']; $prepareData['Attitude']['Yaw'] = $data['Config']['Attitude']['Yaw']; $prepareData['Shelves'] = $data['Config']['Shelves']; // $prepareData['Shelves']['Code'] = $data['Config']['Shelves']['Code']; // $prepareData['Shelves']['Yaw'] = $data['Config']['Shelves']['Yaw']; $prepareData['AgvLogIndex']['IsProgress'] = $data['Config']['AgvLogIndex']['IsProgress']; $prepareData['AgvLogIndex']['ScriptIdx'] = $data['Config']['AgvLogIndex']['ScriptIdx']; $prepareData['AgvLogIndex']['RunIdx'] = $data['Config']['AgvLogIndex']['RunIdx']; $prepareData['AgvLogIndex']['ErrorIdx'] = $data['Config']['AgvLogIndex']['ErrorIdx']; $prepareData['Status']['State'] = $data['Config']['Status']['State']; $prepareData['Status']['IsLiftUp'] = $data['Config']['Status']['IsLiftUp']; $prepareData['Status']['IsMoving'] = $data['Config']['Status']['IsMoving']; $prepareData['Status']['IsReady'] = $data['Config']['Status']['IsReady']; $prepareData['Status']['IsChargeing'] = $data['Config']['Status']['IsChargeing']; $prepareData['AgvScript'] = $data['Config']['AgvScript']; return $prepareData; } public function getBattery(){ $this->getData(); $this->_Data->getBattery(); return $this->_Data; } public function getStatus(){ $this->getData(); $this->_Data->getStatus(); return $this->_Data; // return ['StatusCode' => $this->_Data->getStatusCode(), 'Battery' => $this->_Data->getStatus()]; } public function getMapPosition(){ $this->getData(); $this->_Data->getAttitude(); return $this->_Data; // return ['StatusCode' => $this->_Data->getStatusCode(), 'Attitude' => $this->_Data->getAttitude()]; } public function getPosition(){ $this->getData(); $this->_Data->getPos(); return $this->_Data; // return ['StatusCode' => $this->_Data->getStatusCode(), 'Pos' => $this->_Data->getPos()]; } public function getAgvLogIndex(){ $this->getData(); $this->_Data->getAgvLogIndex(); return $this->_Data; // return ['StatusCode' => $this->_Data->getStatusCode(), 'AgvLogIndex' => $this->_Data->getAgvLogIndex()]; } public function getRunPara(){ $this->getData(); $this->_Data->getRunPara(); return $this->_Data; // return ['StatusCode' => $this->_Data->getStatusCode(), 'RunPara' => $this->_Data->getRunPara()]; } public function Script($param = array()){ $httpResponse = AGV_request::POST($this->AGV_name, "30121", $param, $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function DirectSTOP(){ $httpResponse = AGV_request::POST($this->AGV_name, "30310", array(), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function ScriptOVER(){ $httpResponse = AGV_request::POST($this->AGV_name, "30314", array(), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function ScriptContinue(){ $httpResponse = AGV_request::POST($this->AGV_name, "30313", array(), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function ScriptSTOP(){ $httpResponse = AGV_request::POST($this->AGV_name, "30312", array(), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function ServoOn(){ $httpResponse = AGV_request::POST($this->AGV_name, "30100", array(), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function ServoOff(){ $httpResponse = AGV_request::POST($this->AGV_name, "30101", array(), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function move($gap){ $httpResponse = AGV_request::POST($this->AGV_name, "30112", array($gap), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function shelfup(){ if(($isLefuUp = $this->checkIsLeftUp()) == true){ // ob_start(); // var_dump($isLefuUp); // $testData = ob_get_clean(); // throw new \Exception($testData); throw new \Exception("Is Shelf Up"); return $this->getData(); } $httpResponse = AGV_request::POST($this->AGV_name, "30218", array(), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function shelfdown(){ if(($isLefuUp = $this->checkIsLeftUp()) == false){ // ob_start(); // var_dump($isLefuUp); // $testData = ob_get_clean(); throw new \Exception("Is Shelf Down"); return $this->getData(); } $httpResponse = AGV_request::POST($this->AGV_name, "30219", array(), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function PlugIn($gap=700, $enforce = false){ // if($this->checkPosition("060050")){ // throw new AGVException("Position Code is not in the default Code", UNKNOWN_ERROR); // } // if($this->checkYaw(90)==false){ // throw new AGVException("Position Yaw is not in the default Yaw", UNKNOWN_ERROR); // } // if($this->checkIsChargeing()){ // throw new AGVException("isChargeing", UNKNOWN_ERROR); // } $httpResponse = AGV_request::POST($this->AGV_name, "30230", array($gap), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function PlugOut($gap=700, $enforce = false){ // if($this->checkIsChargeing() == false){ // throw new AGVException("AGV is not Chargeing", UNKNOWN_ERROR); // } $httpResponse = AGV_request::POST($this->AGV_name, "30231", array($gap), $this->api_url); $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function Trans2AbsYawSpin($yaw, $lockingDisc = true){ $this->getData(); $attitude = $this->_Data->getAttitude(); // $attitude['Yaw'] = 270; $_yaw = $this->REGAngle($yaw-$attitude['Yaw']); if($_yaw>0){//右轉 echo "右轉: " . $_yaw; return $this->spinRight($_yaw, $lockingDisc); }else if($_yaw<0){//左轉 echo "左轉: " . $_yaw; return $this->spinLeft($_yaw, $lockingDisc); } $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function quickSpin($degree, $lockingDisc = true){ // 旋轉 : lockingDisc鎖定圓盤不動 $_yaw = $this->REGAngle($degree); if($_yaw>0){//右轉 echo "右轉: " . $_yaw; return $this->spinRight($_yaw, $lockingDisc); }else if($_yaw<0){//左轉 echo "左轉: " . $_yaw; return $this->spinLeft($_yaw, $lockingDisc); } return $this->getData(); } public function spinLeft($spin, $lockingDisc = true){ switch($this->absAngle($spin)/90){ case 1: $httpResponse = AGV_request::POST($this->AGV_name, $lockingDisc ? "30210" : "30110", array(), $this->api_url); break; case 2: $httpResponse = AGV_request::POST($this->AGV_name, $lockingDisc ? "30211" : "30111", array(), $this->api_url); break; case 3: $httpResponse = AGV_request::POST($this->AGV_name, $lockingDisc ? "30211" : "30111", array(), $this->api_url); $httpResponse = AGV_request::POST($this->AGV_name, $lockingDisc ? "30210" : "30110", array(), $this->api_url); break; } return $this->getData(); } public function spinRight($spin, $lockingDisc = true){ switch($this->absAngle($spin)/90){ case 1: $httpResponse = AGV_request::POST($this->AGV_name, $lockingDisc ? "30208" : "30108", array(), $this->api_url); break; case 2: $httpResponse = AGV_request::POST($this->AGV_name, $lockingDisc ? "30209" : "30109", array(), $this->api_url); break; case 3: $httpResponse = AGV_request::POST($this->AGV_name, $lockingDisc ? "30209" : "30109", array(), $this->api_url); $httpResponse = AGV_request::POST($this->AGV_name, $lockingDisc ? "30208" : "30108", array(), $this->api_url); break; } $this->_Data = new AGV_response($httpResponse); $this->checkError(); return $this->_Data; } public function REGAngle($angle){ while($angle<-180)$angle+=360; while($angle>180)$angle-=360; $angle = round($angle/90)*90; return $angle; } private function absAngle($angle){ while($angle<0)$angle+=360; $angle = round($angle/90)*90; return $angle%360; } public function checkYaw($yaw){ $this->getData(); $Attitude = $this->_Data->getAttitude(); return $yaw == $this->absAngle($Attitude['Yaw']); } public function checkPosition($code){ $this->getData(); $Attitude = $this->_Data->getAttitude(); return $code == $Attitude['Code']; } public function checkIsChargeing(){ $this->getData(); $status = $this->_Data->getStatus(); return $status['IsChargeing']; } public function checkIsLeftUp(){ $this->getData(); $status = $this->_Data->getStatus(); return $status['IsLiftUp'] == true; } }
C++
UTF-8
3,599
3.390625
3
[]
no_license
//----------------------------------------------------------------------------- // Copyright Ed Keenan 2017 // Optimized C++ //----------------------------------------------------------------------------- #include <vector> #include "Trace.h" #include <string> // Modify This File using std::vector; class Point { public: Point() = default; Point(const float inX, const float inY) : x(inX), y(inY) {} private: float x; float y; }; int main() { vector<int> iVec; iVec.push_back(10); iVec.push_back(20); iVec.push_back(30); iVec.push_back(40); // START vector<int>::iterator iter; printf("%s\n", "Below is iteration through vector"); for (iter = iVec.begin(); iter != iVec.end(); ++iter) { printf("%d ", *iter); } printf("\n"); // END // START printf("%s\n", "Below is reverse iteration through vector"); vector<int>::reverse_iterator riter; for (riter = iVec.rbegin(); riter != iVec.rend(); ++riter) { printf("%d ", *riter); } printf("\n"); // END // START //vector<type> name(n, value) vector<double> xvec(5, 1.5); // 5 copies of 1.5 vector<double>::iterator diter; printf("%s\n", "Below is iteration through vector(double)"); for (diter = xvec.begin(); diter != xvec.end(); ++diter) { printf("%f ", *diter); } printf("\n"); // END // START //vector<type> name(first_iter, last_iter) std::string arr[4] = { "John", "Paul", "George", "Ringo" }; vector<std::string> beatVec(arr, arr + 4); vector<std::string>::iterator siter; printf("%s\n", "Below is iteration through vector(string)"); for (siter = beatVec.begin(); siter != beatVec.end(); ++siter) { std::string myString = *siter; printf("%s ", myString.c_str()); } printf("\n"); // END // START /*vector<Point> pt_vec = { Point(1.0, 3.5), Point(1, 0), Point(1, 3.141592) };*/ // END // START vector<std::string> strVec(5, "hi");\ // assign 3 copies of "hello", replacing old contents strVec.assign(3, "hello"); printf("%s\n", "Below is iteration through assign(string)"); for (siter = strVec.begin(); siter != strVec.end(); ++siter) { std::string myString = *siter; printf("%s ", myString.c_str()); } printf("\n"); // END // START std::string clowns[3] = { "Moe", "Larry", "Curly" }; vector<std::string> clownVec; clownVec.assign(clowns, clowns + 3); printf("%s\n", "Below is iteration through assign2(string)"); /*for (siter = clownVec.begin(); siter != clownVec.end(); ++siter) { std::string myString = *siter; printf("%s ", myString.c_str()); }*/ // another way to get access of the vector for (size_t i = 0; i < clownVec.size(); ++i) { std::string myString = clownVec.at(i); printf("%s ", myString.c_str()); } printf("\n"); std::string myString = clownVec.back(); printf("%s\n", "Below is get the last of assign2(string)"); printf("%s\n", myString.c_str()); // END // START clownVec.clear(); if (clownVec.empty()) { printf("%s\n", "This vector<string> is empty!!"); } // END // START printf("%s\n", "Original before erase"); std::string clowns2[] = { "Moe", "Larry", "Curly" }; vector<std::string> clownVec2(clowns, clowns + 3); for (size_t i = 0; i < clownVec2.size(); ++i) { std::string myString2 = clownVec2.at(i); printf("%s ", myString2.c_str()); } printf("\n"); clownVec2.erase(clownVec2.begin() + 1); printf("%s\n", "Below is to erase"); for (size_t i = 0; i < clownVec2.size(); ++i) { std::string myString2 = clownVec2.at(i); printf("%s ", myString2.c_str()); } printf("\n"); // END getchar(); return 0; } // --- End of File ---------------
Ruby
UTF-8
5,055
3.046875
3
[]
no_license
# encoding: utf-8 $: << File.expand_path('../../lib', __FILE__) require 'set' require 'bundesstrasse' # This example demonstrates how a publisher can detect when there are # subscribers listening. When sending complex messages you may want to avoid # expensive serialization of messages unless there actually is anyone listening # for them. One way this can be achieved is through the use of an xpub socket # in place of a regular pub socket. # This class is an abstraction on top of an xpub socket and exposes the # currently subscribed to topics, so that producers can determine whether or not # it is worth it to publish messages. class SubscriberAwarePublisher attr_reader :subscriptions def initialize(context, bind_address) # We're using an xpub socket, unlike regular pub sockets you can get some # information about subscribers from them @pub_socket = context.xpub_socket @pub_socket.bind(bind_address) @subscriptions = Set.new end def has_subscribers? check_subscriptions! @subscriptions.size > 0 end def publish(topic, message) @pub_socket.write_multipart(topic, message) end private def check_subscriptions! loop do # This is the core piece of code to this example. Here we poll the xpub # socket for new messages about subscriptions and unsubscriptions. # # Read nonblocking until there are no more messages (signalled through a # Bundesstrasse::AgainError). The messages received are prefixed with a # zero byte for unsubscribe or a one for subscribe. The rest of the message # is the topic subscribed to (i.e. the prefix string given to #subscribe). # # A message will be received for the first subscription for a topic, and # for the last unsubscription of a topic. There is no way to count the # number of subscribed sockets with this method. # # To determine if we have a subscriber it would be enough to increment a # counter for each subscription and decrement it for each unsubscription, # but here we also keep track of the topics subscribed to as a set. message = @pub_socket.read_nonblocking code = message.slice!(0) case code.ord when 0 @subscriptions.delete(message) when 1 @subscriptions << message end end rescue Bundesstrasse::AgainError # this means that there were no more messages end end service_port = 4444 mutex = Mutex.new context = Bundesstrasse::Context.create Thread.start do Thread.current.abort_on_exception = true # This is the publisher thread, we use the SubscriberAwarePublisher # abstraction defined above to keep track of when there are subscriptions, and # only send messages when there are. The messages include a counter so you can # see that the subscribers don't miss messages (a single subscriber may miss # a message but all messages should go to at least one subscriber). If we # hadn't checked for subscribers before publishing, messages sent when no # subscribers were connected would go missing. # # The subscriber check is not meant as a reliability feature or any kind of # guaranteed delivery mechanism, and the including a counter in the messages # is just a way of demonstrating that messages are indeed not sent when there # are no subscribers. There may be gaps where the subscriber sockets have # closed down between the publisher checking for unsubscriptions and # publishing the next message, but they should be rare. publisher = SubscriberAwarePublisher.new(context, "tcp://*:#{service_port}") counter = 0 loop do if publisher.has_subscribers? publisher.publish('greetings', "Hello ##{counter}") counter += 1 else mutex.synchronize do puts 'No subscribers!' end end sleep(1) end end 3.times do Thread.start do Thread.current.abort_on_exception = true # This is a subscriber thread, it will connect, subscribe, read three # messages and then disconnect, sleep for a little while and do it over # again. Since we run multiple subscriber threads there can be a different # number of subscribers at any time, or none. loop do sub_socket = context.sub_socket sub_socket.connect("tcp://localhost:#{service_port}") # just to complicate things, we randomly subscribe to a specific topic or # all topics (an empty string means all topics) -- in this example all # messages are sent to the topic "greetings" so either way the same # messages will be received if rand < 0.5 sub_socket.subscribe('') else sub_socket.subscribe('greetings') end 3.times do topic, message = sub_socket.read_multipart mutex.synchronize do puts message end end # you can unsubscribe manually, but that will also happen when you # close the socket # sub_socket.unsubscribe('') sub_socket.close! sleep(rand(10)) end end end sleep
Python
UTF-8
559
2.5625
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- #Note! So far, this is code to initialize a fresh DB to muck with. #I'm usig a DB called "dantest". #Assumes Grid from -1000 to +1000 in x and y directions. import MySQLdb import generalDBQueries class Galaxy: def __init__(self): mydb = GalaxyDB() print mydb.testDBConnection() def blah(self): pass if __name__ == "__main__": mygalaxy = Galaxy() print ("Init DB") mygalaxy.initdb() print ("list Players") mygalaxy.listplayers()
Python
UTF-8
1,128
3.265625
3
[]
no_license
class Solution: def threeSum(self, A): ''' :problem: Given an array of n integers, return all unique triplets [a,b,c] in the array such that a + b + c = 0 :type A: list of int :rtype: list of list of int ''' hashmap = {} for i in range(len(A)): for j in range(i+1, len(A)): key = A[i]+A[j] if key in hashmap: result = hashmap[key] result.append([A[i], A[j]]) hashmap[key] = result else: hashmap[key] = [[A[i], A[j]]] result = set() for each in A: if -1*each in hashmap: output_1 = hashmap[-1*each] for each_pair in output_1: if each in each_pair: continue each_pair.append(each) result.add(tuple(sorted(each_pair))) return [list(each) for each in result] s = Solution() arr = [-3, -1, 1, 0, 2, 10, -2, 8] print(s.threeSum(arr))
Python
UTF-8
271
2.765625
3
[]
no_license
import pygame class Settings(): def __init__(self): self.caption = "Rocket" self.screen_width = 720 self.screen_height = 480 self.bg_color = (0, 0, 59) def screen_size(self): return (self.screen_width, self.screen_height)
Java
UTF-8
933
2.09375
2
[]
no_license
package com.zjj.service.impl; import java.util.Map; import com.zjj.bean.UserBean; import com.zjj.dao.UserDao; import com.zjj.service.UserService; import com.zjj.util.common.Page; public class UserServiceImpl implements UserService { private UserDao userDao; @Override public boolean login(String account, String password) { return userDao.login(account, password); } @Override public UserBean queryUserByInfo(String account, String password) { return userDao.queryUserByInfo(account, password); } @Override public String addUser(UserBean userBean) { return userDao.addUser(userBean); } @Override public Map<String, Object> queryUserList(Map<String, String> requestMap, Page page) { return userDao.queryUserList(requestMap, page); } public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } }
Java
UTF-8
427
2.171875
2
[]
no_license
package com.techprimers.kafka.springbootkafkaconsumerexample.model; public class User { private String meetingId; // private String[] host = meetingId.split(":"); public String getMeetingId() { return meetingId; } public User() { } public User(String meetingId) { this.meetingId = meetingId; } @Override public String toString() { return meetingId; } }
Java
UTF-8
8,203
2.203125
2
[]
no_license
package com.leomara.delivery.doce_sabor.services; import com.leomara.delivery.doce_sabor.domain.Cliente; import com.leomara.delivery.doce_sabor.domain.Endereco; import com.leomara.delivery.doce_sabor.repositories.ClienteRepository; import com.leomara.delivery.doce_sabor.services.exception.DataIntegrityException; import com.leomara.delivery.doce_sabor.services.exception.ObjectNotFoundException; import static com.leomara.delivery.doce_sabor.until.variables.CategoriaVariables.ORDER_BY; import static com.leomara.delivery.doce_sabor.until.variables.ClienteVariables.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import java.util.Arrays; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; @SpringBootTest public class ClienteServiceTest { private static final String MENSAGEM_ID_NULO = "Necessário um id para buscar."; private static final String TEL1 = "(19) 2987-8860"; private static final String TEL2 = "(19) 98386-7407"; @Autowired private ClienteService sut; @MockBean private ClienteRepository repository; private Cliente cliente; private Cliente clienteAux; private Endereco endereco; private Exception exception; @BeforeEach void setUp() { endereco = new Endereco(null, LOGRADOURO, NUMERO, BAIRRO, COMPLEMENTO, CEP, CIDADE, UF, clienteAux); cliente = new Cliente(ID_EXISTENTE, NOME, CPF, EMAIL, SENHA, endereco); cliente.setEndereco(endereco); cliente.getTelefones().addAll(Arrays.asList(TEL1, TEL2)); clienteAux = new Cliente(ID_EXISTENTE, NOME, CPF_EXISTENTE, EMAIL_EXISTENTE, SENHA, null); when(repository.findById(ID_EXISTENTE)).thenReturn(Optional.of(cliente)); when(repository.findById(ID_EXISTENTE + 1)).thenReturn(Optional.of(cliente)); when(repository.save(cliente)).thenReturn(cliente); when(repository.findByCpf(CPF)).thenReturn(Optional.empty()); when(repository.findByEmail(EMAIL)).thenReturn(Optional.empty()); } /** Método find */ @Test public void deve_retornar_um_cliente_pelo_id() { Cliente cl = sut.find(ID_EXISTENTE); verify(repository).findById(ID_EXISTENTE); assertAll("Deve retornar um cliente", () -> assertEquals(NOME, cl.getNome()), () -> assertEquals(ID_EXISTENTE, cl.getId()), () -> assertEquals(CPF, cl.getCpf()), () -> assertEquals(EMAIL, cl.getEmail()), () -> assertEquals(SENHA, cl.getSenha())); } @Test public void deve_retornar_excecao_ao_nao_encontrar_id() { when(repository.findById(ID_INEXISTENTE)).thenReturn(Optional.empty()); exception = assertThrows(ObjectNotFoundException.class, () -> sut.find(ID_INEXISTENTE)); assertEquals(ERRO_CLIENTE_NAO_ENCONTRADO, exception.getMessage()); } @Test public void deve_retornar_excecao_ao_receber_id_nulo() { when((repository.findById(null))).thenThrow(NullPointerException.class); exception = assertThrows(DataIntegrityException.class, () -> sut.find(null)); assertEquals(MENSAGEM_ID_NULO, exception.getMessage()); } /** Método insert */ @Test public void deve_inserir_um_cliente_com_sucesso() { cliente.setId(null); Cliente cl = sut.insert(cliente); verify(repository).save(cliente); assertAll("Deve inserir um cliente com sucesso", () -> assertEquals(CPF, cl.getCpf()), () -> assertEquals(EMAIL, cl.getEmail()), () -> assertThat(cl.getTelefones(), containsInAnyOrder(TEL1,TEL2)), () -> assertEquals(LOGRADOURO, cl.getEndereco().getLogradouro()), () -> assertEquals(NUMERO, cl.getEndereco().getNumero())); } @Test public void deve_retornar_excecao_ao_inserir_cliente_com_o_mesmo_cpf() { when(repository.findByCpf(CPF_EXISTENTE)).thenReturn(Optional.of(clienteAux)); cliente.setCpf(CPF_EXISTENTE); exception = assertThrows(DataIntegrityException.class, () -> sut.insert(cliente)); assertEquals(ERRO_CPF_CADASTRADO, exception.getMessage()); } @Test public void deve_retornar_excecao_ao_inserir_cliente_com_o_mesmo_email() { when(repository.findByEmail(EMAIL_EXISTENTE)).thenReturn(Optional.of(clienteAux)); cliente.setEmail(EMAIL_EXISTENTE); exception = assertThrows(DataIntegrityException.class, () -> sut.insert(cliente)); assertEquals(ERRO_EMAIL_CADASTRADO, exception.getMessage()); } /** Método update */ @Test public void deve_atualizar_com_sucesso() { Cliente cl = sut.update(cliente); verify(repository).save(cliente); assertAll("Deve inserir um cliente com sucesso", () -> assertEquals(ID_EXISTENTE, cl.getId()), () -> assertEquals(CPF, cl.getCpf()), () -> assertThat(cl.getTelefones(), containsInAnyOrder(TEL1,TEL2))); } @Test public void deve_retornar_excecao_ao_tentar_atualizar_com_id_inexistente() { when(repository.findById(ID_INEXISTENTE)).thenReturn(Optional.empty()); cliente.setId(ID_INEXISTENTE); exception = assertThrows(ObjectNotFoundException.class, () -> sut.update(cliente)); assertEquals(ERRO_CLIENTE_NAO_ENCONTRADO, exception.getMessage()); } @Test public void deve_retornar_excecao_ao_atualizar_com_cpf_ja_existente() { when(repository.findByCpf(CPF_EXISTENTE)).thenReturn(Optional.of(clienteAux)); cliente.setId(ID_EXISTENTE + 1); cliente.setCpf(CPF_EXISTENTE); exception = assertThrows(DataIntegrityException.class, () -> sut.update(cliente)); assertEquals(ERRO_CPF_CADASTRADO, exception.getMessage()); } @Test public void deve_retornar_excecao_ao_atualizar_com_email_ja_existente() { when(repository.findByEmail(EMAIL_EXISTENTE)).thenReturn(Optional.of(clienteAux)); cliente.setId(ID_EXISTENTE + 1); cliente.setEmail(EMAIL_EXISTENTE); exception = assertThrows(DataIntegrityException.class, () -> sut.update(cliente)); assertEquals(ERRO_EMAIL_CADASTRADO, exception.getMessage()); } /** Método delete */ @Test public void deve_retornar_excecao_ao_tentar_deletar_com_id_inexistente() { when(repository.findById(ID_INEXISTENTE)).thenReturn(Optional.empty()); exception = assertThrows(ObjectNotFoundException.class, () -> sut.delete(ID_INEXISTENTE)); assertEquals(ERRO_CLIENTE_NAO_ENCONTRADO, exception.getMessage()); } @Test public void deve_chamar_o_metodo_delete_do_repositorio() { sut.delete(ID_EXISTENTE); verify(repository).deleteById(ID_EXISTENTE); } /** Método para filtrar */ @Test public void deve_chamar_a_funcao_filter_no_repositorio() { sut.findPage(PAGE, LINES_PER_PAGE, ORDER_BY, DIRECTION, ""); verify(repository).filter("", PAGE_REQUEST); } @Test public void deve_retornar_um_cliente_filtrado_e_paginado() { Page<Cliente> page = new PageImpl<>(Arrays.asList(cliente)); when(repository.filter(cliente.getNome(), PAGE_REQUEST)).thenReturn(page); Page<Cliente> clientes = sut.findPage(PAGE, LINES_PER_PAGE, ORDER_BY, DIRECTION, cliente.getNome()); assertAll("Deve retornar cliente filtrado e paginado", () -> assertEquals(page.getTotalElements(),clientes.getTotalElements()), () -> assertEquals(page.getContent().get(0).getCpf(), clientes.getContent().get(0).getCpf())); } }
Java
UTF-8
1,048
3.265625
3
[]
no_license
import edu.princeton.cs.algs4.Quick3string; public class SuffixArray { private final String[] sa; private final int N; public SuffixArray(String text){ N=text.length(); sa = new String[N]; for(int i=0;i<N;i++) sa[i]=text.substring(i); Quick3string.sort(sa); } public int length(){ return N; } public String select(int i){ return sa[i]; } public int index(int i){ //return the beginning index of the string in original text with the index i in SuffixArray return N-sa[i].length(); } public int lcp(int i){ return lcp(sa[i],sa[i-1]); } private static int lcp(String a,String b){ int N = Math.min(a.length(), b.length()); for(int i=0;i<N;i++) if(a.charAt(i)!=b.charAt(i)) return i; return N; } public int rank(String key){ int lo=0,hi=N-1; while(lo<=hi){ int mid=lo+(hi-lo)/2; int cmp = key.compareTo(sa[mid]); if(cmp==0) return mid; else if(cmp<0) lo=mid+1; else hi=mid-1; } return N; } public static void main(String[] args) { // TODO Auto-generated method stub } }
JavaScript
UTF-8
6,321
3.75
4
[]
no_license
/*Logic I am using is I create a columns array which takes the first object of previous array as input I call the objects inside recursively using getDeeperKeys function After creating that, i push all this in the table with TH element Then I scan prev array. I create a rowArray which is basically an array of arrays. Each array denotes the row values The first value in each is the index value Now after filling this, I scan the currArray and check if I need to fill the rowArray taking it as a new entry o should I update the already existing entry in the rowArray */ var rowArray;//array of arrays, each array inside has a row var indexArray = [];//maintaines the index in the rowArray to avoid overhead function arrayDiffToHtmlTable( prevArray, currArray) { var table = document.createElement("TABLE"); table.border = "1"; //Get the count of columns. var firstObject = prevArray[0]; //get all keys of the first object in the array, assuming prevarray and currarray have the same structure var keys = Object.keys(firstObject); var colarray = [];//array for maintinaing column headers //this will create the column headers and fill the table for(var i=0;i<keys.length;i++){ //to check for deepness if(typeof prevArray[0][keys[i]] == "object"){ var emptyarr = []; //everytime we pass an empty array to get it fill by deep objec keys var deepArr = getDeeperKeys(firstObject[keys[i]], keys[i], emptyArr); //concatenate the array of column headers to our old header array colarray.concat(deeparr); } else{ //just pushing key to the col array if value if not an object colarray.push(keys[i]); } } //count of rowArray array var columnCount = colarray.length; //Add the header row. /*colarray is of the format ["_id", "meta1sub", "meta2sub", "signature", "value"], these are the column headers*/ var row = table.insertRow(-1); for (var i = 0; i < columnCount; i++) { var headerCell = document.createElement("TH"); headerCell.innerHTML = colarray[i]; row.appendChild(headerCell); } //this will make an array of arrays with each array having a row and each received array for the objects are concatenated to the global array pf column values for(var j=0j<prevArray.length;j++){ var emptyColArray = []; rowarrayfilled = fillTable(prevArray[j], emptyColArray); rowArray.concat(rowarrayfilled); } //call updateTable for currArray for(var k =0;k<currArray.length;k++){ var emptyColArray = []; //this check prevents to scan the whole columnsArray again when considering currArray if(alreadyInTable(currArray[k]["_id"])){ var idx = findIndexInColArray(rowArray, currArray[k]["_id"]); var updatedarray = updateTable(currArray[k], emptyColArray); rowArray[idx] = updatedarray; } else rowArray.concat(fillTable(currArray[k])); } //Add the data rows /*rowArray is an array of arrays == [[1,2,3,4,5][5,6,7,8,9][2,3,4,5,6][9,5,4,3,2][7,8,9,7,5]] -- this is the format where 1, 5, 2, 9, 7 are the id in each row, here there will be five rows*/ for (var i = 1; i < rowArray.length; i++) { row = table.insertRow(-1); for (var j = 0; j < rowArray[i]; j++) { var cell = row.insertCell(-1); cell.innerHTML = rowArray[i][j]; } } var dvTable = document.getElementById("dvTable"); dvTable.innerHTML = ""; dvTable.appendChild(table); } //first filll prevArray /*This function takes the newid of currArray object as input and checks in the indexArray if it exists or not*/ function alreadyInTable(newid){ if(indexArray.indexOf(newid)>-1)//for update return true;//if already exists, so update else return false;//else, for fill table } /*This function finds the index of the row with id as the first value*/ function findIndexInColArray(rowArray, id){ for(var i=0;i<rowArray;i++){ if(rowArray[i][0] == id) return i; } } /*This function takes the object which further has an object as value as an input, key is the string whose value we sent as the first argument, newArray is an empty object to be filled*/ function getDeeperKeys(deeperobj, key, deeperKeys){ var keys = Object.keys(deeperobj); for(var i=0;i<keys.length;i++){ if(typeof prevArray[0][keys[i]] == "object"){ var deeparr = getDeeperKeys(prevArray[0][keys[i]], keys[i], deeperKeys); deeperKeys.concat(deeparr); } else{ deeperKeys.push(key+"_"+keys[i]); } } return deeperKeys; } //update and add using currArray /*This function takes prevArrays individual elements as input and produces arrays of values to update in the table. It does this recursively*/ function updateTable(currArray, idx, emptyColArray){ //search in the columns array and update here var keys = Object.keys(prevArray); for(var i=0;i<keys.length;i++){ if(typeof prevArray[0][keys[i]] == "object"){ var newarray=[]; var deeparr = getDeeperKeys(prevArray[0][keys[i]], keys[i], emptyColArray); emptyColArray.concat(deeparr); } else{ //push values in the order of keys added in getDeeperKeys function emptyColArray.push(keys[i]); } } return emptyColArray; } /*This function takes prevArrays individual elements as input and produces arrays of values to put in the table. It does this recursively*/ function fillTable(prevArray, emptyColArray){ var keys = Object.keys(prevArray); indexArray.push(prevArray["_id"]);//maintain an index array to know if we have to update or fill the table for(var i=0;i<keys.length;i++){ if(typeof prevArray[0][keys[i]] == "object"){ var deeparr = getDeeperKeys(prevArray[0][keys[i]], keys[i], emptyColArray); emptyColArray.concat(deeparr); } else{ //push values in the order of keys added in getDeeperKeys function emptyColArray.push(keys[i]); } } return emptyColArray; }
Python
UTF-8
4,054
3.65625
4
[]
no_license
''' Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order. Example 1: Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]] Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]] Explanation: The first and second John's are the same person as they have the common email "johnsmith@mail.com". The third John and Mary are different people as none of their email addresses are used by other accounts. We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted. Example 2: Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]] Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]] Constraints: 1 <= accounts.length <= 1000 2 <= accounts[i].length <= 10 1 <= accounts[i][j] <= 30 accounts[i][0] consists of English letters. accounts[i][j] (for j > 0) is a valid email. ''' from typing import * import unittest class UF: def __init__(self, n): self.roots = [i for i in range(n)] def union(self,u, v): root_u = self.find(u) root_v = self.find(v) if root_u == root_v: return self.roots[root_u] = root_v def find(self,u): while u != self.roots[u]: self.roots[u] = self.roots[self.roots[u]] u = self.roots[u] return u class Solution: def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: all_emails = set() for account in accounts: for u in account[1:]: all_emails.add((u, account[0])) all_emails = sorted(list(all_emails)) maps = {k[0]: i for i, k in enumerate(all_emails)} uf = UF(len(all_emails)) for account in accounts: u = maps[account[1]] for v in account[2:]: v = maps[v] uf.union(u, v) res = {} for u, _ in all_emails: uf.find(maps[u]) for i in range(len(all_emails)): res.setdefault(uf.find(i), []).append(all_emails[i][0]) ans = [] for k, v in res.items(): item = [] item.append(all_emails[k][1]) item.extend(v) ans.append(item) return ans class TestSolution(unittest.TestCase): def test_case(self): examples = ( (([["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]],), [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["John","johnnybravo@mail.com"],["Mary","mary@mail.com"]]), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().accountsMerge(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
Python
UTF-8
1,731
3.859375
4
[]
no_license
from string import punctuation from string import whitespace Words = [] def ponctuation(s): for c in punctuation : if c in s: s = s.replace(c, "") return s def space(s): for c in whitespace: if c in s: s = s.replace(c, "") return s def frequency(items): """Return count of each item in list of items.""" count = {} for item in items: if item in count: count[item] += 1 else: count[item] = 1 return count def listing(): i = 0 j = 0 print(Words) while True: try: if Words[i] != " ": i = i + 1 elif Words[i] == " ": #print(Words[j: i]) Words[j:i] = [''.join(Words[j:i])] neword = Words[j:i] Words.remove(" ") #print(Words) j = j + 1 i = 1 except IndexError: break try : Words.remove('') except ValueError: print(Words) count = frequency(Words) for key in count: print(str(count.get(key)) + " " + key) word = len(Words) print("number of word") print(word) while True : sentence = str(input("enter a sentence please: ")) + " " if sentence == " ": break else: character_count = str(len(sentence)) sentence = ponctuation(sentence) sentence2 = space(sentence) letter_count = str(len(sentence2)) Words = list(sentence) print("number of character: " + character_count) print("number of letter: " + letter_count) listing() print() input("Press return to continue ...")
Python
UTF-8
1,876
2.703125
3
[]
no_license
from errors import MVMErr class Registers: REGS_SPECIAL = 32 REGS_TOTAL = 35 VALUE_MAX = 2**32 - 1 def __init__(self): self.regs = [0] * self.REGS_TOTAL def number(self,reg): if reg[0] == '$' and reg[1:].isdigit(): return int(reg[1:]) else: try: if reg[0] == '$': return self.number.map.index(reg[1:]) else: return self.number.special.index(reg) + self.REGS_SPECIAL except ValueError: raise KeyError(MVMErr.reg_invalid,reg) raise KeyError(MVMErr.reg_invalid,reg) number.map = [ 'zero','at','v0','v1','a0','a1','a2','a3', 't0','t1','t2','t3','t4','t5','t6','t7', 's0','s1','s2','s3','s4','s5','s6','s7', 't8','t9','k0','k1','gp','sp','fp','ra' ] number.special = ['pc','hi','lo'] def get(self,reg): return self.regs[self.number(reg)] def set(self,reg,val,special = False): if type(val) != int: raise TypeError(MVMErr.operand_type,val) if val > self.VALUE_MAX: raise ValueError(MVMErr.operand_overflow,val) reg = self.number(reg) if reg >= self.REGS_SPECIAL and not special: raise Exception(MVMErr.reg_forbidden,reg) elif reg == 0: raise TypeError(MVMErr.reg_ro,reg) else: self.regs[reg] = val def reset(self): self.__init__() def display(self): print "\033[34m" for i in range(0,self.REGS_SPECIAL): print "%2d\t$%2s\t%10d" % (i,self.number.map[i],self.regs[i]) for i in range(0,3): print "%2d\t %2s\t%10d" % (i + self.REGS_SPECIAL, self.number.special[i],self.regs[i + self.REGS_SPECIAL]) print "\033[0m\n"
C#
UTF-8
1,011
2.734375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CSharp; using System.CodeDom.Compiler; using System.Diagnostics; namespace CSharpCompilerInCode { class Program { static void Main(string[] args) { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.OutputAssembly = "Output.exe"; CompilerResults results = icc.CompileAssemblyFromFile(parameters, @"C:\Users\naynish\Desktop\Dummy Projects\CSharpCompilerInCode\SampleCode.cs"); foreach (var item in results.Output) { Console.WriteLine(item); } Process.Start("Output.exe"); Console.WriteLine("successful"); Console.ReadLine(); } } }