language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
6,577
2.25
2
[]
no_license
package com.ganesh.mahindra.model; import java.util.List; import javax.persistence.Id; public class BreakdownProblemsList { @Id private int id; List<BreakdownProblems> list1; List<BreakdownProblems> list2; List<BreakdownProblems> list3; List<BreakdownProblems> list4; List<BreakdownProblems> list5; List<BreakdownProblems> list6; List<BreakdownProblems> list7; List<BreakdownProblems> list8; List<BreakdownProblems> list9; List<BreakdownProblems> list10; List<BreakdownProblems> list11; List<BreakdownProblems> list12; List<BreakdownProblems> list13; List<BreakdownProblems> list14; List<BreakdownProblems> list15; List<BreakdownProblems> list16; List<BreakdownProblems> list17; List<BreakdownProblems> list18; List<BreakdownProblems> list19; List<BreakdownProblems> list20; List<BreakdownProblems> list21; List<BreakdownProblems> list22; List<BreakdownProblems> list23; List<BreakdownProblems> list24; List<BreakdownProblems> list25; List<BreakdownProblems> list26; List<BreakdownProblems> list27; List<BreakdownProblems> list28; List<BreakdownProblems> list29; List<BreakdownProblems> list30; public int getId() { return id; } public void setId(int id) { this.id = id; } public List<BreakdownProblems> getList1() { return list1; } public void setList1(List<BreakdownProblems> list1) { this.list1 = list1; } public List<BreakdownProblems> getList2() { return list2; } public void setList2(List<BreakdownProblems> list2) { this.list2 = list2; } public List<BreakdownProblems> getList3() { return list3; } public void setList3(List<BreakdownProblems> list3) { this.list3 = list3; } public List<BreakdownProblems> getList4() { return list4; } public void setList4(List<BreakdownProblems> list4) { this.list4 = list4; } public List<BreakdownProblems> getList5() { return list5; } public void setList5(List<BreakdownProblems> list5) { this.list5 = list5; } public List<BreakdownProblems> getList6() { return list6; } public void setList6(List<BreakdownProblems> list6) { this.list6 = list6; } public List<BreakdownProblems> getList7() { return list7; } public void setList7(List<BreakdownProblems> list7) { this.list7 = list7; } public List<BreakdownProblems> getList8() { return list8; } public void setList8(List<BreakdownProblems> list8) { this.list8 = list8; } public List<BreakdownProblems> getList9() { return list9; } public void setList9(List<BreakdownProblems> list9) { this.list9 = list9; } public List<BreakdownProblems> getList10() { return list10; } public void setList10(List<BreakdownProblems> list10) { this.list10 = list10; } public List<BreakdownProblems> getList11() { return list11; } public void setList11(List<BreakdownProblems> list11) { this.list11 = list11; } public List<BreakdownProblems> getList12() { return list12; } public void setList12(List<BreakdownProblems> list12) { this.list12 = list12; } public List<BreakdownProblems> getList13() { return list13; } public void setList13(List<BreakdownProblems> list13) { this.list13 = list13; } public List<BreakdownProblems> getList14() { return list14; } public void setList14(List<BreakdownProblems> list14) { this.list14 = list14; } public List<BreakdownProblems> getList15() { return list15; } public void setList15(List<BreakdownProblems> list15) { this.list15 = list15; } public List<BreakdownProblems> getList16() { return list16; } public void setList16(List<BreakdownProblems> list16) { this.list16 = list16; } public List<BreakdownProblems> getList17() { return list17; } public void setList17(List<BreakdownProblems> list17) { this.list17 = list17; } public List<BreakdownProblems> getList18() { return list18; } public void setList18(List<BreakdownProblems> list18) { this.list18 = list18; } public List<BreakdownProblems> getList19() { return list19; } public void setList19(List<BreakdownProblems> list19) { this.list19 = list19; } public List<BreakdownProblems> getList20() { return list20; } public void setList20(List<BreakdownProblems> list20) { this.list20 = list20; } public List<BreakdownProblems> getList21() { return list21; } public void setList21(List<BreakdownProblems> list21) { this.list21 = list21; } public List<BreakdownProblems> getList22() { return list22; } public void setList22(List<BreakdownProblems> list22) { this.list22 = list22; } public List<BreakdownProblems> getList23() { return list23; } public void setList23(List<BreakdownProblems> list23) { this.list23 = list23; } public List<BreakdownProblems> getList24() { return list24; } public void setList24(List<BreakdownProblems> list24) { this.list24 = list24; } public List<BreakdownProblems> getList25() { return list25; } public void setList25(List<BreakdownProblems> list25) { this.list25 = list25; } public List<BreakdownProblems> getList26() { return list26; } public void setList26(List<BreakdownProblems> list26) { this.list26 = list26; } public List<BreakdownProblems> getList27() { return list27; } public void setList27(List<BreakdownProblems> list27) { this.list27 = list27; } public List<BreakdownProblems> getList28() { return list28; } public void setList28(List<BreakdownProblems> list28) { this.list28 = list28; } public List<BreakdownProblems> getList29() { return list29; } public void setList29(List<BreakdownProblems> list29) { this.list29 = list29; } public List<BreakdownProblems> getList30() { return list30; } public void setList30(List<BreakdownProblems> list30) { this.list30 = list30; } @Override public String toString() { return "BreakdownProblemsList [id=" + id + ", list1=" + list1 + ", list2=" + list2 + ", list3=" + list3 + ", list4=" + list4 + ", list5=" + list5 + ", list6=" + list6 + ", list7=" + list7 + ", list8=" + list8 + ", list9=" + list9 + ", list10=" + list10 + ", list11=" + list11 + ", list12=" + list12 + ", list13=" + list13 + ", list14=" + list14 + ", list15=" + list15 + ", list16=" + list16 + ", list17=" + list17 + ", list18=" + list18 + ", list19=" + list19 + ", list20=" + list20 + ", list21=" + list21 + ", list22=" + list22 + ", list23=" + list23 + ", list24=" + list24 + ", list25=" + list25 + ", list26=" + list26 + ", list27=" + list27 + ", list28=" + list28 + ", list29=" + list29 + ", list30=" + list30 + "]"; } }
Markdown
UTF-8
8,055
3.03125
3
[]
no_license
```python #Analysis: #Observed Trend #1: Rural rides, unsurprisingly, have less rides per city data available, and the greatest range of average fare cost. #Observed Trend #2: While about 78% of drivers are urban drivers, about 68% of rides were urban rides, meaning some urban drivers could be driving in suburban areas. #Observed Trend #3: The median average fare for an urban ride is about $25, or about $5 cheaper than the average fare of about $30 for suburban rides. ``` ```python import pandas as pd import os import numpy as np import matplotlib.pyplot as plt ``` ```python file_one = os.path.join('raw_data', 'ride_data.csv') file_two = os.path.join('raw_data', 'city_data.csv') ``` ```python file_one_df = pd.read_csv(file_one) file_two_df = pd.read_csv(file_two) ``` ```python file_one_df = pd.read_csv(file_one, encoding="utf-8") file_two_df = pd.read_csv(file_two, encoding="utf-8") ``` ```python merge_table = pd.merge(file_one_df, file_two_df,on="city") merge_table=merge_table.sort_values('city',ascending=True) merge_table.count() ``` city 2407 date 2407 fare 2407 ride_id 2407 driver_count 2407 type 2407 dtype: int64 ```python merge_table_rural=merge_table.loc[merge_table['type']=='Rural',:] merge_table_suburban=merge_table.loc[(merge_table['type']=='Suburban')] merge_table_urban=merge_table.loc[(merge_table['type']=='Urban')] ``` ```python unique_rural=merge_table_rural['city'].unique() unique_suburban=merge_table_suburban['city'].unique() unique_urban=merge_table_urban['city'].unique() ``` ```python driver_count_rural=file_two_df.loc[file_two_df['type']=='Rural',:] driver_count_rural=ride_count_xyz.sort_values(['city'],ascending=True) driver_count_suburban=file_two_df.loc[file_two_df['type']=='Suburban',:] driver_count_suburban=ride_count_xyz.sort_values(['city'],ascending=True) driver_count_urban=file_two_df.loc[file_two_df['type']=='Urban',:] driver_count_urban=ride_count_xyz.sort_values(['city'],ascending=True) ``` ```python city_rural=merge_table_rural.groupby('city') ride_count_rural=city_rural['fare'].count() city_suburban=merge_table_suburban.groupby('city') ride_count_suburban=city_suburban['fare'].count() city_urban=merge_table_urban.groupby('city') ride_count_urban=city_urban['fare'].count() ``` ```python rural_df=pd.DataFrame(ride_count_rural) rural_df['try this']='' rural_df['driver city']=unique_rural rural_df['total fare']='' rural_df['driver count']='' rural_fare_sum=city_rural['fare'].sum() rural_df['total fare']=rural_fare_sum average_rural=rural_fare_sum/ride_count_rural rural_df['try this']=average_rural ``` ```python suburban_df=pd.DataFrame(ride_count_suburban) suburban_df['try this']='' rural_df['driver count']='' rural_df['total fare']='' suburban_fare_sum=city_suburban['fare'].sum() suburban_df['total fare']=suburban_fare_sum average_sub=suburban_fare_sum/ride_count_suburban suburban_df['try this']=average_sub ``` ```python urban_df=pd.DataFrame(ride_count_urban) urban_df['try this']='' rural_df['driver count']='' rural_df['total fare']='' urban_fare_sum=city_urban['fare'].sum() average_urban=urban_fare_sum/ride_count_urban urban_df['try this']=average_urban ``` ```python plt.hlines(10,50,100,alpha=1) plt.scatter(rural_df['fare'], rural_df['try this'], marker="o", facecolor="gold",edgecolors='black',sizes=driver_count_rural['driver_count']*25,alpha=0.75, linewidth=1) plt.scatter(ride_count_suburban, average_sub, marker="o", facecolor="#87CEFA",edgecolors='black',sizes=driver_count_suburban['driver_count']*25,alpha=0.75, linewidth=1) plt.scatter(ride_count_urban, average_urban, marker="o", facecolor="#F08080",edgecolors='black',sizes=driver_count_urban['driver_count']*25,alpha=0.75, linewidth=1) plt.ylim(15,55) plt.xlim(0,70) plt.title("Pyber Ride Sharing Data (2016)") plt.xlabel("Total Number of Rides (Per City)") plt.ylabel("Average Fare ($)") plt.text(72,35,'Note:') plt.text(72,32,'Circle size correlates to driver count per city.') plt.legend() plt.rcParams['axes.facecolor'] = 'lightgray' plt.grid() plt.show() ``` ![png](output_13_0.png) ```python #break ``` ```python merge_table_rural=merge_table.loc[(merge_table['type']=='Rural')] merge_table_suburban=merge_table.loc[(merge_table['type']=='Suburban')] merge_table_urban=merge_table.loc[(merge_table['type']=='Urban')] rural_sum=merge_table_rural['fare'].sum() suburban_sum=merge_table_suburban['fare'].sum() urban_sum=merge_table_urban['fare'].sum() total_sum=merge_table['fare'].sum() ``` ```python sizes_fare=[rural_sum/total_sum,suburban_sum/total_sum,urban_sum/total_sum] ``` ```python labels = ['Rural','Suburban','Urban'] plt.title('% of Total Fares by City Type') colors=['Gold', '#87CEFA', '#F08080'] explode=[0,0,0.1] plt.pie(sizes_fare,labels=labels,colors=colors,explode=explode,autopct='{0:1.1f}%'.format,shadow=True,startangle=140) ``` ([<matplotlib.patches.Wedge at 0x121680940>, <matplotlib.patches.Wedge at 0x121688da0>, <matplotlib.patches.Wedge at 0x1216842b0>], [<matplotlib.text.Text at 0x121680748>, <matplotlib.text.Text at 0x12168dfd0>, <matplotlib.text.Text at 0x1216850b8>], [<matplotlib.text.Text at 0x121688400>, <matplotlib.text.Text at 0x12168d588>, <matplotlib.text.Text at 0x1216855f8>]) ```python plt.show() ``` ![png](output_18_0.png) ```python #break ``` ```python rural_sum_ride=merge_table_rural['ride_id'].sum() suburban_sum_ride=merge_table_suburban['ride_id'].sum() urban_sum_ride=merge_table_urban['ride_id'].sum() total_sum_ride=merge_table['ride_id'].sum() ``` ```python sizes_ride=[rural_sum_ride/total_sum_ride,suburban_sum_ride/total_sum_ride,urban_sum_ride/total_sum_ride] ``` ```python labels = ['Rural','Suburban','Urban'] plt.title('% of Total Rides by City Type') size_rural=int(city_type_count_df.loc['Rural']) size_suburban=int(city_type_count_df.loc['Suburban']) size_urban=int(city_type_count_df.loc['Urban']) sizes=[sizes_fare_ride,size_suburban,size_urban] colors=['Gold', '#87CEFA', '#F08080'] explode=[0,0,0.1] plt.pie(sizes_ride,labels=labels,colors=colors,explode=explode,autopct='{0:1.1f}%'.format,shadow=True,startangle=140) ``` ([<matplotlib.patches.Wedge at 0x121153a58>, <matplotlib.patches.Wedge at 0x12116e2e8>, <matplotlib.patches.Wedge at 0x121154a58>], [<matplotlib.text.Text at 0x12116d7f0>, <matplotlib.text.Text at 0x12116ef60>, <matplotlib.text.Text at 0x121184860>], [<matplotlib.text.Text at 0x12116dd30>, <matplotlib.text.Text at 0x1211544e0>, <matplotlib.text.Text at 0x121184da0>]) ```python plt.show() ``` ![png](output_23_0.png) ```python #break ``` ```python city_table_rural=file_two_df.loc[(file_two_df['type']=='Rural')] city_table_suburban=file_two_df.loc[(file_two_df['type']=='Suburban')] city_table_urban=file_two_df.loc[(file_two_df['type']=='Urban')] rural_driver=city_table_rural['driver_count'].sum() suburban_driver=city_table_suburban['driver_count'].sum() urban_driver=city_table_urban['driver_count'].sum() total_driver=file_two_df['driver_count'].sum() ``` ```python sizes_driver=[rural_driver/total_driver,suburban_driver/total_driver,urban_driver/total_driver] ``` ```python labels = ['Rural','Suburban','Urban'] plt.title('% of Total Drivers by City Type') colors=['Gold', '#87CEFA', '#F08080'] explode=[0,0,0.1] plt.pie(sizes_driver,labels=labels,colors=colors,explode=explode,autopct='{0:1.1f}%'.format,shadow=True,startangle=140) ``` ([<matplotlib.patches.Wedge at 0x121084518>, <matplotlib.patches.Wedge at 0x121063dd8>, <matplotlib.patches.Wedge at 0x1210736d8>], [<matplotlib.text.Text at 0x121063320>, <matplotlib.text.Text at 0x121064be0>, <matplotlib.text.Text at 0x12106c4e0>], [<matplotlib.text.Text at 0x121063860>, <matplotlib.text.Text at 0x121073160>, <matplotlib.text.Text at 0x12106ca20>]) ```python plt.show() ``` ![png](output_28_0.png)
C++
UTF-8
1,636
2.8125
3
[]
no_license
#pragma once class Spielfeld; #include <memory> #include <vector> #include "..\Interfaces/Model.h" #include "Spieler.h" #include "Feld.h" #include "Spielfigur.h" #include "Sperrstein.h" class Spielfeld : public Model { private: int width; int height; std::shared_ptr<Feld> zielFeld; std::vector<std::shared_ptr<Feld>> felder; std::vector<std::shared_ptr<Feld>> ausgangspositionen; std::vector<std::shared_ptr<Spielfigur>> spielfiguren; std::vector<std::shared_ptr<Sperrstein>> sperrsteine; public: Spielfeld(const std::vector<std::shared_ptr<Spieler>> &_spieler); std::shared_ptr<Feld> getFeld(int x, int y){ if(x<0 || x>=width || y<0 || y>=height) return nullptr; int i = y*width+x; return felder[i]; } std::shared_ptr<Feld> getAusgangsposition(int i, int n){ if(i<0 || n<0 || i*5+n >= ausgangspositionen.size()) return nullptr; return ausgangspositionen[i*5+n]; } std::shared_ptr<Spielfigur> getSpielfigur(int i, int n){ if(i<0 || n<0 || i*5+n >= spielfiguren.size()) return nullptr; return spielfiguren[i*5+n]; } std::shared_ptr<Sperrstein> getSperrstein(int i){ if(i<0 || i >= sperrsteine.size()) return nullptr; return sperrsteine[i]; } std::shared_ptr<Feld> getZielFeld(){ return zielFeld; } void switchSteine(std::shared_ptr<Feld> A, std::shared_ptr<Feld> B); int getWidth() const {return width;} int getHeight() const {return height;} private: int getIndex(int x, int y){ return y*width+x; } };
Python
UTF-8
1,701
2.65625
3
[]
no_license
# import libraries import requests from bs4 import BeautifulSoup from win10toast import ToastNotifier import schedule import time import json toaster = ToastNotifier() def notify_mobile(name, price, url, ifttt_key, ifttt_event): iftttUrl = 'https://maker.ifttt.com/trigger/'+ifttt_event+'/with/key/'+ifttt_key myobj = {"value1": name,"value2": price,"value3": url} x = requests.post(iftttUrl, data=myobj) print(x.text) def stock_scraper(url, name, threshold, operation, ifttt_key, ifttt_event): page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') result = soup.select( "#div_nse_livebox_wrap > div.nsedata_bx > div.nsbs_bg > div > div.pcnsb.div_live_price_wrap > span.span_price_wrap") price = float(result[0].text) print("price is: "+str(price)) if operation == 'gt': if price > threshold: toaster.show_toast(name+" share price", str(price), icon_path=None, duration=5) notify_mobile(name, price, url, ifttt_key, ifttt_event) if operation == 'lt': if price < threshold: toaster.show_toast(name+" share price", str(price), icon_path=None, duration=5) notify_mobile(name, price, url, ifttt_key, ifttt_event) def get_all_stock_info(): with open('./input.json') as f: data = json.load(f) ifttt_key = data['iftttKey'] ifttt_event = data['iftttEvent'] for stock in data['stocks']: print(stock['name']) stock_scraper(stock['url'], stock['name'], stock['threshold'], stock['operation'], ifttt_key, ifttt_event) schedule.every(1).minutes.do(get_all_stock_info) while True: schedule.run_pending() time.sleep(1)
C++
UTF-8
768
3.03125
3
[]
no_license
#include "plane_axis_calculator.h" #include <fstream> using namespace std; int main() { ifstream inFile; vector<Vector3d> TestPoints; inFile.open("TestPoints.txt"); if(!inFile) { cerr << "Unable to open file"; exit(1); } double PointCoord; Vector3d Point(0.0, 0.0, 0.0); int i = 0; while(inFile >> PointCoord) { Point[i] = PointCoord; i++; if(i == 3) { i = 0; TestPoints.push_back(Point); } } PlaneAxisCalculator TestCalc(TestPoints); cout << "Points being used: " << endl; for(int i = 0; i < TestPoints.size(); i++) { cout << TestPoints[i] << endl; } TestCalc.PrintAxisDetails(); Vector3d DummyAxis; TestCalc.get_normal(DummyAxis); return 0; }
Markdown
UTF-8
545
2.671875
3
[]
no_license
# Sentiment Analysis This is a sentiment analysis program which can find sentiment of the sentence. **Usage** .\program.exe --pos "path/to/positive-sentiment.txt" --neg "path/to/negative-sentiment.txt" **Data** This program require you to have 2 file. One of the file need to contain a positive sentiment and another file need to contain a negative sentiment. Look at the folder in the repo for example. **Dependencies** GSL : Guidelines Support Library (https://github.com/microsoft/GSL) Catch2 (https://github.com/catchorg/Catch2)
Ruby
UTF-8
409
3.453125
3
[]
no_license
class FakeArray def initialize @info = ["puppies", "kittens", "baby sloths", "puppies"] end def each @info.each do |element| yield element if block_given? end end def first @info[0] end def compact new_array = [] @info.each do |element| new_array << element unless new_array.include? element end new_array end end fa = FakeArray.new fa.compact
Java
UTF-8
1,066
2.671875
3
[]
no_license
package com.dyc.model;/** * @Auther: tony_jaa * @Date: 2018/7/23 19:58 * @Description: */ /** * @Auther: tony_jaa * @Date: 2018/7/23 19:58 * @Description: */ public class User { private String name; private String passwaord; private Integer age; public User(String name, String passwaord, Integer age) { this.name = name; this.passwaord = passwaord; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPasswaord() { return passwaord; } public void setPasswaord(String passwaord) { this.passwaord = passwaord; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", passwaord='" + passwaord + '\'' + ", age=" + age + '}'; } }
SQL
UTF-8
1,090
3.6875
4
[]
no_license
DROP DATABASE IF EXISTS gut_app; CREATE DATABASE gut_app; USE gut_app; /*------------- Haupt- Tabellen ---------------*/ CREATE TABLE tbl_abschlüsse( pk_abschluss_id MEDIUMINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(pk_abschluss_id) )ENGINE=InnoDB; CREATE TABLE tbl_bildungsgänge( pk_bildungsgang_id MEDIUMINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(pk_bildungsgang_id) )ENGINE=InnoDB; CREATE TABLE tbl_lehrer( pk_lehrer_id MEDIUMINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(pk_lehrer_id) )ENGINE=InnoDB; /*------------- AUFLÖSUNGS TABELLEN---------------*/ /* Ein bildungsgang kann mehrer Ansprechparter haben und ein lehrer kann für mehrere Bildungsgänge zuständig sein*/ CREATE TABLE tbl_lehrer_bildungsgänge( pk_fk_bildungsgang_id MEDIUMINT NOT NULL, pk_fk_lehrer_id MEDIUMINT NOT NULL, PRIMARY KEY(pk_fk_bildungsgang_id,pk_fk_lehrer_id), FOREIGN KEY (pk_fk_bildungsgang_id) REFERENCES tbl_bildungsgänge(pk_bildungsgang_id), FOREIGN KEy (pk_fk_lehrer_id) REFERENCES tbl_lehrer(pk_lehrer_id) )ENGINE=InnoDB;
Java
UTF-8
1,611
2.453125
2
[]
no_license
package com.mojaz.assignment.util; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.content.Context; import com.mojaz.assignment.R; import com.mojaz.assignment.photo.data.source.PhotosDataSource; import static com.mojaz.assignment.Config.SERVER_ERROR; public class GeneralUtil { /** * helper method to notify the view of data errors * * @param context The context of the view. * @param callback The callback interface. */ public static void showResponseError(Context context, PhotosDataSource.LoadPhotosCallback callback) { String reason = context.getString(R.string.general_err); callback.onDataNotAvailable(SERVER_ERROR, reason); } public static <T> T checkNotNull(T object) { if (object == null) { throw new NullPointerException(); } return object; } public static <T> T checkNotNull(T object, String message) { if (object == null) { throw new NullPointerException(message); } return object; } /** * The {@code fragment} is added to the container view with id {@code frameId} and tag {@code tag}. * The operation is performed by the {@code fragmentManager}. */ public static void replaceFragment(FragmentManager fragmentManager, Fragment fragment, int frameId, String tag) { fragmentManager.beginTransaction() .replace(frameId, fragment, tag) .commit(); } }
Java
UTF-8
400
1.585938
2
[]
no_license
package com.aspire.mirror.alert.server.vo.leakScan; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class SecurityLeakScanReportVo { private String id; private String scanId; private String ip; private String reportPath; private Integer highLeaks; private Integer mediumLeaks; private Integer lowLeaks; private Double riskVal; }
Python
UTF-8
3,985
2.671875
3
[]
no_license
import re from django.core.cache import cache from django.template.defaultfilters import slugify from .exceptions import WikiException from .fix_unicode import fix_unicode from .helpers import get_wiki_objects from .constants import WIKIBRACKETS def make_cache_key(token): return "wiki::%s" % slugify(token) class WikiParse(object): WIKIBRACKETS = WIKIBRACKETS def __init__(self, fail_silently=True, use_cache=True): self.fail_silently = fail_silently self.cache_updates = {} self.cache_map = {} self.use_cache = use_cache self.strikes = [] def parse(self, string): string = string or '' string = fix_unicode(string) if not self.fail_silently: len_lbrack = len([i for i in string.split('[[')]) len_rbrack = len([i for i in string.split(']]')]) if len_lbrack != len_rbrack: raise WikiException("Left bracket count doesn't match right bracket count") brackets = map(make_cache_key, re.findall(self.WIKIBRACKETS, string)) if self.use_cache: self.cache_map = cache.get_many(brackets) content = re.sub('%s(.*?)' % self.WIKIBRACKETS, self.callback, string) if self.cache_updates and self.use_cache: cache.set_many(dict(( make_cache_key(k), v[0]) for k, v in self.cache_updates.items()), 60 * 5) return content def callback(self, match): token, trail = match.groups() if make_cache_key(token) in self.cache_map: result = self.cache_map[make_cache_key(token)] self.strikes.append({ 'from_cache': True, 'match_obj': match, 'token': token, 'trail': trail, 'result': result}) return result try: """ Of course none of this shit is useful if you're using the Caching wiki object """ wiki_obj, token, trail, explicit = get_wiki(match) rendering = wiki_obj.render(token, trail=trail, explicit=explicit) #token_key = '%s%s' % (token, trail or '') self.cache_updates[slugify(token)] = (rendering, wiki_obj, match) self.strikes.append({ 'from_cache': False, 'explicit': explicit, 'match_obj': match, 'wiki_obj': wiki_obj, 'token': token, 'trail': trail, 'result': rendering}) return rendering except WikiException: if not self.fail_silently: raise return match.groups()[0] def get_wiki(match): # Excepts a regexp match token, trail = match.groups() # we track the 'trail' because it may be a plural 's' or something useful """ First we're checking if the text is attempting to find a specific type of object. [[user:Subsume]] [[card:Jack of Hearts]] """ wikis = get_wiki_objects() if ':' in token: name, subtoken = token.split(':', 1) for wiki in wikis: if name == wiki.name: content = wiki.render(subtoken, trail=trail, explicit=True) if content: return wiki, subtoken, trail, True raise WikiException("Type %s didn't return anything for '%s'" % (name, subtoken)) """ Now we're going to try a generic match across all our wiki objects. [[Christopher Walken]] [[Beverly Hills: 90210]] <-- notice ':' was confused earlier as a wiki prefix name [[Cat]]s <-- will try to match 'Cat' but will pass the 'trail' on [[Cats]] <-- will try to match 'Cats' then 'Cat' """ for wiki in wikis: content = wiki.render(token, trail=trail) if content: return wiki, token, trail, False raise WikiException("No item found for '%s'" % (token))
Python
UTF-8
252
4.09375
4
[]
no_license
m = input("Enter values upto: ") n = 1 even = [] odd = [] while n<=m: if n%2==0: even.append(n) else: odd.append(n) n = n+1 print ('Even Numbers are {0}'.format(even, odd)) print ('Odd Numbers are {1}'.format(even, odd))
Java
UTF-8
1,670
2.484375
2
[]
no_license
package com.example.a2019cap_ver2; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MyCafeMenuAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ public class MyViewHolder extends RecyclerView.ViewHolder { TextView tvMenuName, tvMenuPrice; MyViewHolder(View view){ super(view); tvMenuName = view.findViewById(R.id.tvMenuName); tvMenuPrice = view.findViewById(R.id.tvMenuPrice); } } Context mContext; private String[] menuName; private String[] menuPrice; int itemNum = 3; MyCafeMenuAdapter(Context context, String[] menuName, String[] menuPrice){ this.mContext = context; this.menuName = menuName; this.menuPrice = menuPrice; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_cafe_menu, parent, false); MyCafeMenuAdapter.MyViewHolder myView = new MyCafeMenuAdapter.MyViewHolder(v); return myView; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { MyCafeMenuAdapter.MyViewHolder myViewHolder = (MyCafeMenuAdapter.MyViewHolder) holder; myViewHolder.tvMenuName.setText(menuName[position]); myViewHolder.tvMenuPrice.setText(menuPrice[position]); } @Override public int getItemCount() { return itemNum; } }
C#
UTF-8
8,503
2.640625
3
[]
no_license
using System.Text; using System.Threading.Tasks; using TreeStruct; namespace WPFDBApp.Services.TreeServices { /// <summary> /// A class that helps create sql script /// </summary> public class SQLCreateHelper { #region Create Sql Script Async internal static async Task<StringBuilder> CreateSqlScriptAsync(TreeNode<Element> node) { StringBuilder query = new StringBuilder(); StringBuilder queryFK = new StringBuilder(); foreach (var item in node) { switch (item.Data.Name) { case "Database": await TreeStructHelper.LoadChildAsync(item.Data.Name, item); foreach (var it in item.Children) await TreeStructHelper.LoadChildAsync(it.Data.Name, it); query.Append("CREATE DATABASE ").Append(item.Data.Attributes["name"]).Append("\nGO\nUSE ").Append(item.Data.Attributes["name"]).Append("\nGO\n"); break; case "Table": await TreeStructHelper.LoadChildAsync(item.Data.Name, item); foreach (var it in item.Children) await TreeStructHelper.LoadChildAsync(it.Data.Name, it); CreateTable(item, query, queryFK); break; case "View": case "Procedure": await TreeStructHelper.LoadChildAsync(item.Data.Name, item); if(!string.IsNullOrEmpty(item.Data.Attributes["definition"])) query.Append(item.Data.Attributes["definition"].Trim()).Append("\nGO\n"); break; default: break; } } if (queryFK.Length > 0) query.Append(queryFK.ToString()); return query; } #endregion #region Helper Methods private static void CreateTable(TreeNode<Element> item, StringBuilder query, StringBuilder queryFK) { query.Append("CREATE TABLE ").Append(item.Data.Attributes["name"]).Append("\n(\n"); int countCol = 0; bool flag = false; foreach (var tabItem in item) { if (tabItem.Data.Name == "Columns") { continue; } if (tabItem.Data.Name == "Column") { CreateColumn(tabItem, query); if (countCol < item.Children[0].ChildrenCount()) query.Append(",\n"); countCol++; } else if (tabItem.Data.Name != "Table") { if (!flag) { query.Remove(query.Length - 2, 1); query.Append(")\nGO\n"); flag = true; } if ("PrimaryKey" == tabItem.Data.Name) CreatePrimaryKey(tabItem, query, item.Data.Attributes["name"]); if ("CheckConstraint" == tabItem.Data.Name) CreateConstraint(tabItem, query, item.Data.Attributes["name"]); if ("Index" == tabItem.Data.Name) CreateIndex(tabItem, query, item.Data.Attributes["name"]); if ("ForeignKey" == tabItem.Data.Name) CreateForeignKey(tabItem, queryFK, item.Data.Attributes["name"]); } } if (!flag) { query.Remove(query.Length - 2, 1); query.Append(")\nGO\n"); } } private static void CreatePrimaryKey(TreeNode<Element> tabItem, StringBuilder query, string tableName) { query.Append("ALTER TABLE ").Append(tableName).Append("\nADD"); if (tabItem.Data.Attributes["is_system_named"] == "False") { query.Append(" CONSTRAINT ").Append(tabItem.Data.Attributes["name"]); } query.Append(" PRIMARY KEY ").Append(tabItem.Data.Attributes["type_desc"]). Append(" (").Append(tabItem.Data.Attributes["included_columns"]).Append(")\nGO\n"); } private static void CreateForeignKey(TreeNode<Element> tabItem, StringBuilder query, string tableName) { query.Append("ALTER TABLE ").Append(tableName).Append("\nADD "); if (tabItem.Data.Attributes["is_system_named"] == "False") query.Append("CONSTRAINT ").Append(tabItem.Data.Attributes["name"]); query.Append("FOREIGN KEY ("). Append(tabItem.Data.Attributes["constraint_column_name"]).Append(")\nREFERENCES ").Append(tabItem.Data.Attributes["referenced_object"]). Append(" (").Append(tabItem.Data.Attributes["referenced_column_name"]).Append(")"); if (tabItem.Data.Attributes["delete_referential_action_desc"] != "NO_ACTION") query.Append(" ").Append(tabItem.Data.Attributes["delete_referential_action_desc"]).Append(" "); if (tabItem.Data.Attributes["update_referential_action_desc"] != "NO_ACTION") query.Append(" ").Append(tabItem.Data.Attributes["update_referential_action_desc"]).Append(" "); query.Append("\nGO\n"); } private static void CreateConstraint(TreeNode<Element> tabItem, StringBuilder query, string tableName) { query.Append("ALTER TABLE ").Append(tableName).Append(" WITH CHECK ADD CHECK"). Append(tabItem.Data.Attributes["check_value"]).Append("\nGO\n"); } private static void CreateIndex(TreeNode<Element> tabItem, StringBuilder query, string tableName) { if (tabItem.Data.Attributes["is_primary_key"] == "True") return; query.Append("CREATE "); if (tabItem.Data.Attributes["is_unique"] == "True") query.Append("UNIQUE "); query.Append(tabItem.Data.Attributes["type_desc"]).Append(" INDEX "). Append(tabItem.Data.Attributes["name"]).Append(" ON ").Append(tableName). Append("(").Append(tabItem.Data.Attributes["included_columns"]).Append(")\nGO\n"); } private static void CreateColumn(TreeNode<Element> node, StringBuilder query) { string value; query.Append("\t").Append(node.Data.Attributes["name"]).Append("\t").Append(node.Data.Attributes["data_type"]); if (node.Data.Attributes["data_type"] == "datetime2" || node.Data.Attributes["data_type"] == "datetimeoffset" || node.Data.Attributes["data_type"] == "time") query.Append("(").Append(node.Data.Attributes["scale"]).Append(")"); else if (node.Data.Attributes["data_type"] == "decimal" || node.Data.Attributes["data_type"] == "numeric") query.Append("(").Append(node.Data.Attributes["precision"]).Append(",").Append(node.Data.Attributes["scale"]).Append(")"); else if (node.Data.Attributes["data_type"] == "float") query.Append("(").Append(node.Data.Attributes["precision"]).Append(")"); else if (node.Data.Attributes["data_type"] == "uniqueidentifier") { } else if (node.Data.Attributes.TryGetValue("max_length", out value)) { if (node.Data.Attributes["max_length"] == "-1") query.Append("(MAX)"); else if (node.Data.Attributes["max_length"] == "2147483647") query.Append(""); else query.Append("(").Append(value).Append(")"); } if (node.Data.Attributes["is_identity"] == "True") query.Append(" IDENTITY(").Append(node.Data.Attributes["seed_value"]).Append(",").Append(node.Data.Attributes["increment_value"]).Append(")"); if (node.Data.Attributes["is_nullable"] == "NO") query.Append("\tNOT NULL"); else if (node.Data.Attributes["is_nullable"] == "YES") query.Append("\tNULL"); if (node.Data.Attributes.TryGetValue("column_default", out value)) query.Append("\n\t\tDEFAULT\t").Append(value); } #endregion } }
TypeScript
UTF-8
1,232
2.578125
3
[ "MIT" ]
permissive
import { CollectionCache, CollectionKey } from "../../../common"; import { Ancillaries } from "./Ancillaries"; import { AgentSubtypes } from "./AgentSubtypes"; export namespace AncillariesIncludedAgentSubtypes { export const KEY = new CollectionKey("ancillaries_included_agent_subtypes"); export class Entry { private readonly collectionCache: CollectionCache; readonly _ancillary: string; readonly _agentSubtype: string; constructor(collectionCache: CollectionCache, values: any) { this.collectionCache = collectionCache; this._ancillary = values["ancillary"]; this._agentSubtype = values["agent_subtype"]; } get ancillary(): Ancillaries.Entry | undefined { const collection = <Ancillaries.Entry[]>this.collectionCache.getCollection(Ancillaries.KEY, Ancillaries.Entry); return collection.find(entry => entry._key === this._ancillary); } get agentSubtype(): AgentSubtypes.Entry | undefined { const collection = <AgentSubtypes.Entry[]>this.collectionCache.getCollection(AgentSubtypes.KEY, AgentSubtypes.Entry); return collection.find(entry => entry.key === this._agentSubtype); } } } export default AncillariesIncludedAgentSubtypes;
C++
UTF-8
2,955
2.875
3
[]
no_license
// Nombre del alumno: Irene Martin Berlanga // Usuario del Juez: EDA35 #include <iostream> #include <iomanip> #include <fstream> #include <vector> #define INF 1000000000 //==========================> EJERCICIO 28 (SIN ESTIMACION)<==========================// bool esSolucion(int columnas, int indiceProducto){ if(columnas - 1 == indiceProducto){ return true; }else return false; } // función que resuelve el problema void resolver(std::vector<std::vector<int>>const& matriz, std::vector<int>& vector_marcas_supermecados, int indiceProducto, int precioTotal, int& precioMinTotal ) { for(int supermercado = 0; supermercado < matriz.size(); ++supermercado ){ //recorro por filas if(vector_marcas_supermecados[supermercado] < 3){ //esValida() ++vector_marcas_supermecados[supermercado]; precioTotal += matriz[supermercado][indiceProducto]; if(esSolucion(matriz[0].size(), indiceProducto)){ if(precioTotal < precioMinTotal){ precioMinTotal = precioTotal; } }else{ resolver(matriz, vector_marcas_supermecados, indiceProducto + 1, precioTotal, precioMinTotal); } --vector_marcas_supermecados[supermercado]; precioTotal -= matriz[supermercado][indiceProducto]; } } } // Resuelve un caso de prueba, leyendo de la entrada la // configuración, y escribiendo la respuesta void resuelveCaso() { // leer los datos de la entrada int numSupermercadosFilas, numProductosColumnas; std::cin >> numSupermercadosFilas >> numProductosColumnas; int precio; std::vector<std::vector<int>> matriz(numSupermercadosFilas, std::vector<int> (numProductosColumnas, 0)); for(int i = 0; i < matriz.size(); ++i){ for(int j = 0; j < matriz[0].size(); ++j){ std::cin >> precio; matriz[i][j] = precio; } } std::vector<int> vector_marcas_supermecados(numSupermercadosFilas); int indiceProducto = 0; // k int precioTotal = 0, precioMinimoTotal = INF; resolver(matriz, vector_marcas_supermecados, indiceProducto, precioTotal, precioMinimoTotal); // escribir sol std::cout << precioMinimoTotal << std::endl; } int main() { // Para la entrada por fichero. // Comentar para acepta el reto #ifndef DOMJUDGE std::ifstream in("/Users/IRENE/Desktop/EDA EXAMEN/txt/eda28.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt #endif int numCasos; std::cin >> numCasos; for (int i = 0; i < numCasos; ++i) resuelveCaso(); // Para restablecer entrada. Comentar para acepta el reto #ifndef DOMJUDGE // para dejar todo como estaba al principio std::cin.rdbuf(cinbuf); system("PAUSE"); #endif return 0; }
Python
UTF-8
1,192
4.1875
4
[]
no_license
""" The **left shift** operation is similar to **multiplication by powers of two** , thus, the process is _repetitive_ and can be done _recursively_. Sample calculation using the left shift operator (`<<`): 10 << 3 = 10 * 2^3 = 10 * 8 = 80 -32 << 2 = -32 * 2^2 = -32 * 4 = -128 5 << 2 = 5 * 2^2 = 5 * 4 = 20 Write a **recursive** function that **mimics** (without the use of **< <**) the left shift operator and returns the result from the two given integers. ### Examples shift_to_left(5, 2) ➞ 20 shift_to_left(10, 3) ➞ 80 shift_to_left(-32, 2) ➞ -128 shift_to_left(-6, 5) ➞ -192 shift_to_left(12, 4) ➞ 192 shift_to_left(46, 6) ➞ 2944 ### Notes * There will be no negative values for the second parameter `y`. * This challenge is more like recreating of the **left shift** operation, thus, **the use of the operator directly** is **prohibited**. * You are expected to solve this challenge via **recursion**. * An **iterative** version of this challenge can be found via this [link](https://edabit.com/challenge/3xcAQ3CfLAcbEtXys). """ shift_to_left=lambda x,y:shift_to_left(x*2,y-1)if y>0 else x
Go
UTF-8
1,576
3.28125
3
[]
no_license
package pngio import ( "fmt" "image" "testing" ) func TestImagePack_Write(t *testing.T) { type fields struct { Image *image.RGBA offset int } tests := []struct { name string i *ImagePack b []byte wantN int wantErr bool }{ { name: "hello world", i: NewPack(2), b: []byte("hello world"), wantN: len([]byte("hello world")), wantErr: false, }, { name: "hello world 12", i: NewPack(12), b: []byte("hello world"), wantN: len([]byte("hello world")), wantErr: false, }, { name: "hello world 1024", i: NewPack(1024), b: []byte("hello world"), wantN: len([]byte("hello world")), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotN, err := tt.i.Write(tt.b) if (err != nil) != tt.wantErr { t.Errorf("Write() error = %v, wantErr %v", err, tt.wantErr) return } if gotN != tt.wantN { t.Errorf("Write() gotN = %v, want %v", gotN, tt.wantN) } }) } } func TestImagePack_Read(t *testing.T) { d := []byte("hello world") pack := NewDataPack(d) buf := make([]byte, 5) if n, err := pack.Read(buf); err == nil { fmt.Println("read", string(buf[:n])) if string(buf[:n]) != "hello" { t.Errorf("Read() got = %v, want hello", string(buf[:n])) } } buf2 := make([]byte, 6) if n, err := pack.Read(buf2); err == nil { fmt.Println("read", string(buf2[:n])) if string(buf2[:n]) != " world" { t.Errorf("Read() got = %v, want \" world\"", string(buf2[:n])) } } }
TypeScript
UTF-8
623
2.75
3
[]
no_license
namespace Aufgabe10 { export class Tree { x: number; y: number; draw(): void { crc2.beginPath(); crc2.moveTo(this.x, this.y); crc2.lineTo(this.x - 100, this.y); crc2.lineTo(this.x - 50, this.y - 120); crc2.lineTo(this.x, this.y); crc2.fillStyle = "darkgreen"; crc2.fill(); crc2.closePath() crc2.beginPath(); crc2.fillStyle = "#511e12"; crc2.fillRect(this.x - 60, this.y, 20, 30); crc2.closePath(); } } }
C++
UTF-8
8,031
3.96875
4
[]
no_license
//generic programing //Standard Template Library(STL) 主要有两种构建:即容器(container)和泛型算法(generic algorithm) #include<vector> #include<list> #include<map> #include<set> #include<iostream> #include<string> #include<algorithm>//使用泛型算法必须 加入头文件<algorithm> #include<functional>//使用函数对象必须加入头文件 #include<iterator>//使用插入适配器(iterator adapter) 必须加入该头文件 #include<fstream> using namespace std; template<typename Iteratortype,typename elemtype> Iteratortype find_xx(Iteratortype first,Iteratortype last,elemtype elem) { for (; first != last; first++) { if (*first == elem) return first; } return first; }//在这里把Iterator当成一个类型名 写成一个模板 然后后面就可以调用find_xx()函数 bool less_than(int x, int y) { return x < y ? 0 : 1; } bool bigger_than(int x, int y) { return x > y ? 0 : 1; } vector<int> filter_ver1(const vector<int> &vec, int filter_value, bool(*pred)(int, int)) { vector<int> temp_vec; for (vector<int>::const_iterator iter = vec.begin(); iter != vec.end(); iter++) { if (pred(*iter, filter_value)) temp_vec.push_back(*iter); } return temp_vec; }//用函数指针的方法把大于以及小于的函数都整合进了 一个函数当中 template<typename Inputiterator,typename Outputiterator,typename elemtype,typename comp> Outputiterator filter_v(Inputiterator first, Inputiterator last, Outputiterator at,elemtype elem,comp pred) { while ((first = find_if(first, last, bind2nd(pred,elem))) != last) {//bind2nd()函数可以将二元的函数对象转化为一个一元的对象 cout << "found value:" << *first << endl;//本来 像less<int>() 等函数是一个代表 二元 函数对象 比如像大于小于等等 *at++ = *first++; //而经过绑定之后就可以表示诸如 >elem <elem 大于某个数小于某个数的 一元 函数对象 // bind2nd 函数的参数 函数在前 常数在后!!! } //在if,while等需要进行条件判断的地方我们需要注意 条件判断优先级大于赋值 所以先会进行 return at; //条件判断 而条件判断得到的一个bool值会再进行赋值 } //我们还可以加 not操作 对函数对象的真伪去反 int main() { int a1 = 5; int *a2; const int *x = &a1;//const 在*的左侧说明每个指针所指的值是常数无法改变,而指针是可以改变的 int * const y = a2;//const 在*的右侧,紧连变量说明指针是无法改变的,而指针所指的值是可以改变的 int const * const z = &a1;//说明 指针常量都无法改变 vector<string> svec; for (vector<string>::iterator iter = svec.begin(); iter != svec.end(); iter++) cout << iter->size();//可以直接把他当成一个string的指针使用 //iter 是一个泛型指针 他是比底层指针更抽象一层的对象 这是定义的标准容器的iterator 我们也可以自己定义iterator class const vector<int> ivec; for (vector<int>::const_iterator iter = ivec.begin(); iter != ivec.end(); iter++) { cout << *iter << endl; //如果我们定义的是const类型的容器那么我们也要用 const_iterator 来实现迭代操作 }//我们可以直接把 vector<int>::iterator 看成一种数据类型 vector<string>::iterator it; string a = "why do i love you so"; it = find_xx(svec.begin(), svec.end(), a);//这样的话我们就可以不拘泥于数据类型,以及数据的容器;我么也可以如下调用函数: int arr[10]; a2 = find_xx(arr, arr + 10, 3);//这里相当于是寻找数组里的某个元素,而上面的调用是寻找vector内的某个元素 list<double> dlist; list<double>::iterator iter; iter = find_xx(dlist.begin(), dlist.end(), 3.8);/*在vector和array里面寻找下一个元素就是直接指针运算++,而对于list链表类的数据 类型的数据结构 不能直接用底层的指针,而是需要更抽象一层的泛型指针,而该函数的调用就可以使iterator作为一个迭代器 而运算符++重载也就可以 实现我们list也像vector和array一样使用相同的代码即可以实现遍历或者说迭代*/ vector<string>::iterator it1 = svec.begin(); vector<string>::iterator it2 = svec.end(); it = find(it1, it2, a);/*这里find为一个泛型函数 搜索范围由iterator[first,last)标出。如果找到目标, find会返回一个iterator指向目标,否则返回last*/ binary_search(it1, it2, a);//这个函数只能用于对有序集合进行搜索。返回值为 true or false count(it1, it2, a);//该函数用来进行计算集合内参数有多少个与目标相同,返回值为相同的个数 vector<string> svec1 = { "why","do","I","love","you","so" }; search(it1, it2, svec1);//该函数用来搜索 某个容器内是否存在目标即(svec1)子列 若存在返回子列起始处的iterator 否则返回last(it2) it = max_element(it1, it2);//返回容器内的最大值 vector<string> temp; copy(it1, it2, temp.begin());//将容器的值复制一遍存入 temp当中去 vector<int> ivec1; ivec1 = filter_ver1(ivec, 10, less_than);//函数以参数的形式传入 //function object 是某种class的实例对象,这类class对function call运算符做了重载的操作,这样子f-o就能够当成一般函数调用 sort(it1, it2, greater<string>());//这样子函数就像参数一样传进去了 int ia[8] = { 23,11,3,4,9,6,7,8 }; vector<int> ivec2(ia, ia + 8), ivec3(8);//初始化的区间为:[first,last) vector<int>::iterator itr1, itr2; int ia2[8]; filter_v(ia, ia + 8, ia2, 7, less<int>()); //这两个函数即为上面函数模板引用的例子 filter_v(ivec2.begin(), ivec2.end(), ivec3.begin(), 8, less<int>()); /*在这里我们必须事先把要被复制的目标容器大小确定好 比如ivec3大小要先确定好 而现实往往不这样更好 于是我们有*/ filter_v(ivec2.begin(), ivec2.end(), back_inserter(ivec3), 8, less<int>()); /*插入适配器(insertion adapter) 可以把前面函数里的复制变成一个插入函数的形式 比如back_inserter(ivec3) 就是加入一个push_back()函数 而这些适配器 但是参数形式变成了什么呢?*/ map<string, int> word;//map 的基本数据结构是pair map很像python里的dict word["andy"] = 1; for (map<string, int>::iterator iter; iter != word.end(); iter++) { cout << "key: " << iter->first << " " << "value: " << iter->second << endl; //在这里我们可以把map看成一个pair的数组 map本身并没有first或者second的操作 但是他的每个泛型指针都有!! } //map查询操作 int count = 0; if (!(count = word["andy"])) cout << "andy is not in word";//我们可以通过这个方法寻找 map里面是否有“andy” 其实是在word里创一个 //key 为“andy”的实例 map<string, int>::iterator itt; itt = word.find("andy");//而map本身也有一个find函数如果找到了就返回对应pair的泛型指针 没找到返回 word.end() word.count("andy");//查找word里面 key value为 “andy” 的个数然后返回这个个数 set<string> word_exclusion; word_exclusion.count["a"];//如果存在 a 直接返回true 否则返回false 与map相似但是 set的 value限定为bool 只有是否存在的可能性 word_exclusion.insert("a");//插入元素 word_exclusion.insert(it1, it2);//范围插入元素 参数为泛型指针 ifstream in_file("input.txt"); ofstream out_file("output.txt"); istream_iterator<string> is(in_file); istream_iterator<string> eof; vector<string> text; copy(is, eof, back_inserter(text)); sort(text.begin(), text.end()); ostream_iterator<string> os(out_file, "\t"); copy(text.begin(), text.end(), os);//文件标准化输入输出 istream_iterator<string> is(cin); istream_iterator<string> eof; vector<string> text; copy(is, eof, back_inserter(text)); sort(text.begin(), text.end()); ostream_iterator<string> os(cout, " "); copy(text.begin(), text.end(), os);//键入标准化输入输出 }
Java
UTF-8
404
2.390625
2
[]
no_license
package composite; /** * Created by abedormancy@gmail.com on 2018/3/15. * 图片文件 - 充当 Leaf 叶子构件 */ public class ImageFile extends AbstractFile { private final String name; public ImageFile(String name) { this.name = name; } @Override public void killVirus() { System.out.println("对图像文件 '" + name + "' 进行杀毒..."); } }
Python
UTF-8
831
2.890625
3
[]
no_license
import sys sys.setrecursionlimit(500005) #import pypyjit # this is for solving slow issue for pypy when using recursion but python will not need this (test will fail but submit works) #pypyjit.set_param('max_unroll_recursion=-1') import math A, B = list(map(int, input().split())) a2 = 4*(B**2) b2 = B**2 def ch(x): val = (1+x)**3 if a2*val < A**2: return 0 else: return 1 left = 0 right = 10**6+1 # This is the cause. -> too small bigger number can also be available in this case. (video editorial) while True: v = (left+right)//2 if ch(v) == 0: left = v else: right = v if right - left < 2: break def f(g) : return B*(g-1)+(A/(math.sqrt(g))) #print(right, left) ans = 10**18 for i in range(5): ans = min(f(right+i), ans) print(ans)
C#
UTF-8
3,869
2.515625
3
[]
no_license
using Microsoft.Extensions.Configuration; using Pedidos.Core; using Pedidos.Repository.Comun; using System; using System.Collections.Generic; using System.Text; namespace Pedidos.Repository.Productos { public class ProductosRepository : BaseRepository, IProductosRepository { public ProductosRepository(IConfiguration configuration) : base(configuration) { } public ICollection<Producto> GetAllProductos() { var sql = @"select prod.idProducto, prod.nombre, prod.descripcion, prod.precio, prod.activo from Producto prod order by activo desc, prod.nombre asc"; return GetListOf<Producto>(sql); } public ICollection<Producto> GetAllProductos(bool activo) { var sql = @"select prod.idProducto, prod.nombre, prod.descripcion, prod.precio, prod.activo from Producto prod where activo = @activo order by activo desc, prod.nombre asc"; var parameters = new Dictionary<string, object>() { { "activo", activo} }; return GetListOf<Producto>(sql, parameters); } public ICollection<Producto> GetAllNombresProductos() { var sql = "select prod.idProducto, prod.nombre from Producto prod"; return GetListOf<Producto>(sql); } public Producto GetProducto(int idProducto) { var sql = "select prod.* from Producto prod where prod.idProducto = @idProducto"; var parameters = new Dictionary<string, object>() { { "idProducto", idProducto} }; return Get<Producto>(sql, parameters); } public bool InsertarProducto(Producto prod) { var sql = "insert into Producto (nombre, descripcion, precio, activo) values (@nombre, @descripcion, @precio, @activo)"; var parameters = new Dictionary<string, object>() { { "nombre", prod.Nombre }, { "descripcion", prod.Descripcion }, { "precio", prod.Precio}, { "activo", prod.Activo} }; return ExecuteInsertOrUpdate(sql, parameters); } public bool BorrarProducto(int idProducto) { var sql = "Update Producto set activo = 0 where idProducto = @idProducto"; var parameters = new Dictionary<string, object>() { {"idProducto", idProducto } }; return ExecuteInsertOrUpdate(sql, parameters); } public bool ActualizarProducto(Producto prod) { var sql = @"Update Producto set nombre = @nombre, descripcion = @descripcion, precio = @precio, activo = @activo where idProducto = @idProducto"; var parameters = new Dictionary<string, object>() { { "nombre", prod.Nombre }, { "descripcion", prod.Descripcion }, { "precio", prod.Precio}, { "activo", prod.Activo}, { "idProducto", prod.IdProducto } }; return ExecuteInsertOrUpdate(sql, parameters); } public bool ActivarProducto(int idProducto) { var sql = "Update Producto set activo = 1 where idProducto = @idProducto"; var parameters = new Dictionary<string, object>() { {"idProducto", idProducto } }; return ExecuteInsertOrUpdate(sql, parameters); } } }
Python
UTF-8
198
3.5
4
[]
no_license
__author__ = 'Hanzhiyun' a = -6 b = a * a - a - 1 c = a *b if (a < 0): print("a<0") print(c) else: print("a is not less than 0") print(c - a) print("we are done with the program")
Markdown
UTF-8
5,828
2.78125
3
[]
no_license
## About This is a template project demonstrating how to deploy Elrond nodes using our [elrond-cookbook](https://github.com/mr-staker/elrond-cookbook). It uses `cinc-solo`, so no Chef server is required (it's slow and expensive anyway). It also demonstrates the usage of thin wrapper cookbooks to fulfil a role (i.e role cookbooks). While Chef/Cinc have native support for roles, role cookbooks are more flexible, can be versioned, and can even be tested on their own. It also leads to much simpler JSON attributes file on the server itself as all of the code lives in a git repository, so it's part of your development history. Running `cinc-solo` is probably the easiest to get started. It can either work in push mode (Ansible-style) where the cookbooks are pushed from your machine and run on the target server. This is the model demonstrated by this repository. Alternatively, you can push your code to an object storage service (such as AWS S3) and have your server pull the cookbooks from object storage, expand, and invoke `cinc-solo`. In pull mode, `chef-solo` can run from cron. Having your server pull the cookbooks from object storage is very scalable, but it requires the initial setup to be done via something like `cloud-init`. None of these deployment models require `chef-solo` to run as an agent. ## Deploy procedure This repository has a suite of rake tasks to automate the deployment steps. To list the tasks: ```bash rake -T rake build # Builds cookbooks tarball rake cinc_install # Install Cinc Client on remote target rake clean # Cleanup build artefacts rake default # Chain build, sync, run tasks rake install # Invoke berks install rake run # Run cinc-solo on remote target rake setup # Sync setup script rake sync # Sync cookbooks tarball to target host rake update # Invoke berks update ``` ### Install Cinc on target server This must be run once. Installs Cinc Client on your target server. This can be done with the `cinc_install` task: ```bash rake cinc_install version=16.11.7 target=server ``` `target` either the full specification of a ssh endpoint e.g user@host or it can be a Host per SSH config file, so in that example `Host server` is assumed to be specified in `~/.ssh/config` with appropriate values. ### Install cookbooks This must be run once. Pulls down cookbooks from Supermarket / GitHub. ```bash rake install ``` From this point onwards, the `update` task keeps them in sync. ### Run the deployment procedure ```bash rake target=server role=host001 ``` This runs the `role-host001` example role cookbook against the target server. If you look at the default set of attributes, it is configured to deploy a single observer node on testnet. ## Pactical example A Vagrantfile is included in this repository so you can kick the tyres and follow along. This uses Oracle Linux 8.3 as base OS. You need Vagrant and Virtualbox as prerequisites to use this. ```bash vagrant up # to spin up a VM vagrant ssh-config > .vagrant/config # export Vagrant SSH config ``` This should provide an empty box to deploy some cookbooks. Start with cinc_install: ```bash rake cinc_install target=default version=16.11.7 config=.vagrant/config ``` `default` is defined as `Host default` by the SSH config exported by `vagrant ssh-config`. `config` indicates a custom SSH config instead of the default `~/.ssh/config` file. It should produce something like our [example-cinc-install.log](/example-logs/example-cinc-install.log). The next step, is to do the actual config run: ```bash rake target=default config=.vagrant/config role=host001 ``` You get the gist by now. The output should be like in our [example-run.log](/example-logs/example-run.log). To inspect things around, you can: ```bash vagrant ssh ``` To get rid of the Vagrant VM: ```bash rake clean ``` ## Deploying validators The validator nodes require a functioning Hashicorp Vault. A token is necessary for the first config run to seed the node keys or for subsequent runs if new nodes are added to your role cookbook. `vault_token` isn't necessary for anything else (e.g updating a node version). A one time use token can be created using something like: ```bash vault login -address=https://vault.example.com:8200 # followed by supported auth method vault token create -address=https://vault.example.com:8200 -use-limit=1 ``` This expands on the run procedure: ```bash rake target=server role=host001 vault_token=y ``` This instructs the task to prompt for an input token, thus avoiding this token to be saved into your shell history. Please note that the input is not reflected for security reasons, so paste the token and hit return. To [setup a validator node](https://docs.elrond.com/validators/staking/staking/) on the Elrond network: ```bash # n.b https://api.elrond.com - mainnet proxy address! rake validator id=0 keystore=/path/to/keystore.json target=server proxy=https://api.elrond.com ``` This requires `erdpy` to be properly installed in $PATH e.g via [erdpy-up.py](https://docs.elrond.com/sdk-and-tools/erdpy/installing-erdpy/). The `validator` task wraps `erdpy` and it does the following: * Takes node ID and keystore path as arguments (specified as environment variables, see example). * Prompts for keystore password. * Prepares temporary passfile where the keystore password is stored. This is automatically removed after this task runs. * Pulls down node key from remote server for the specified node ID. This is automatically removed after this task runs. * Builds validators file to reference the node key pulled from remote. This is automatically removed after this task runs. Essentially, this wrapper has been created to ensure that no secrets (node key, passfile) are left exposed after `erdpy` runs.
Python
UTF-8
2,321
2.765625
3
[]
no_license
# -*- coding: utf-8 -*- import argparse import glob import sys import logging from os.path import basename from time import strptime, mktime from vehicle_tracker import VehicleTracker logging.basicConfig(level=logging.DEBUG) log = logging.getLogger('vehicle_tracker') def video_start_time(video_source): try: start_time = mktime(strptime(basename(video_source)[:12], '%Y%m%d%H%M')) except ValueError: return None else: return start_time def setup_parser(): parser = argparse.ArgumentParser( description=( 'This is a traffic monitoring system to detect and track \ vehicles by opencv.'), version='1.0') parser.add_argument( 'video_source', action='store', help='the traffic video source, e.g. 20161115093000_20161115100000_P000.mp4') parser.add_argument( 'direction', action='store', choices=('upward', 'downward'), metavar='direction', help='traffic direction: upward/downward') parser.add_argument( '-i', '--interval', action='store', type=int, default=1, metavar='n', help='process every n frames of video to speed up analysis') parser.add_argument( '-d', '--debug', action='store_true', dest='debug', default=False, help='show intermediate result of video processing if debug on', ) return parser def main(): # setup argument parser then parse arguments parser = setup_parser() args = parser.parse_args() log.debug(args) # try to parse the video's start time from video file name, # and log the error message and exit if failed. start_time = video_start_time(args.video_source) if start_time is None: log.error('illegal video source file name: video source file\'s name ' 'should be like 20161115093000_20161115100000_P000.mp4') sys.exit(-1) # find all videos of given video source video_sources = glob.glob(args.video_source.replace('.', '*.')) # init vehicle tracker and run it vehicle_tracker = VehicleTracker( video_sources, start_time, args.direction, args.interval, args.debug) vehicle_tracker.run() if __name__ == '__main__': main() # EOF
TypeScript
UTF-8
1,013
2.859375
3
[]
no_license
import { DraftedTeam } from './DraftedTeam'; import { IDraftedTeamData } from '../DraftedTeams/IDraftedTeamData'; export namespace DraftedTeamData { export async function getDraftedTeamData(): Promise<DraftedTeam[]> { return new Promise<DraftedTeam[]>((resolve, reject) => { const draftedTeamUrl = './FantasyTeams.json'; fetch(draftedTeamUrl) .then((data: Response) => { if (data.status !== 200) { reject( `Looks like there was a problem. Status Code: ${data.status}` ); } // Examine the text in the response data.json().then((draftedTeamData: IDraftedTeamData) => { const draftedTeamList = draftedTeamData.drafted_teams.map( draftedTeam => new DraftedTeam(draftedTeam) ); resolve(draftedTeamList); }); }) .catch((err: Error) => { // Show alert error alert(`fetch error ${err}`); }); }); } }
TypeScript
UTF-8
464
2.53125
3
[]
no_license
import { BASE_IMAGE_PATH, imagePathFor } from './images' describe('imagePathFor', () => { const fakePath = 'abcd1234' test('returns path for a specific width', () => { expect(imagePathFor(fakePath, 185)).toEqual( `${BASE_IMAGE_PATH}/w185/${fakePath}` ) }) test('uses the original image if no width (2nd argument) is passed', () => { expect(imagePathFor(fakePath)).toEqual( `${BASE_IMAGE_PATH}/original/${fakePath}` ) }) })
Python
UTF-8
3,261
2.75
3
[]
no_license
#coding:utf8 from db_util import * import json import sys reload(sys) sys.setdefaultencoding('utf8') from collections import Counter from collections import defaultdict import os def gen_stats(filepath): ## generate gender with degree lines = [] for line in open(filepath): line = line.strip() splits = line.split('====') ad_gender = splits[1] au_gender = splits[2] gender_type='MM' if ad_gender=='male': if au_gender=='male': gender_type='MM' elif au_gender=='female': gender_type='MF' elif ad_gender=='female': if au_gender=='male': gender_type='FM' elif au_gender=='female': gender_type='FF' degree = degree_process(splits[3]) school = school_process(splits[4]) year = year_process(splits[5]) cats = cats_process(splits[6]) country = splits[7] for cat in cats: lines.append([gender_type,degree,school,year,cat,country]) degree_result = generate_dict(lines,1) school_result = generate_dict(lines,2) year_result = generate_dict(lines,3) cat_result = generate_dict(lines,4) coutnry_result = generate_dict(lines,5) if os.path.exists('gender_data.js'): os.remove('gender_data.js') data = open('gender_data.js','a') data.write('var degree_data = {:};\n'.format(degree_result)) data.write('var school_data = {:};\n'.format(school_result)) data.write('var year_data = {:};\n'.format(year_result)) data.write('var cat_data = {:};\n'.format(cat_result)) data.write('var country_data = {:};\n'.format(coutnry_result)) data.close() def year_process(year): if year == '': return '-1111' return int(year)/10*10 def degree_process(degree): return degree def school_process(school): return school def country_process(country): return country def cats_process(cat): cats = cat.split(";") fc =[] for cat in cats: # print cat if '-' in cat: for c in cat.split('-')[1].split(','): fc.append(c.replace('&#124','').replace('&#39','')) return list(set(fc)) def generate_dict(lines,index): attr_dict = defaultdict(list) # attr_count = defaultdict(int) for line in lines: gender_type = line[0] attr = line[index] if attr=='-1111': continue attr_dict[attr].append(gender_type) # attr_count[attr]+=1 # print attr_dict ## 根据属性对应的数量进行排序 count_index=0 results = [] for k,v in sorted(attr_dict.items(),key=lambda x:len(x[1]),reverse=True): result_dict = {} result_dict['State'] = k new_counter = Counter(v) gg_counter = {} for gg in ['MM','MF','FM','FF']: gg_counter[gg] = new_counter.get(gg,0) result_dict['freq'] = gg_counter count_index+=1 if count_index >9: break results.append(result_dict) results = sorted(results,key=lambda x:x['State']) return json.dumps(results) if __name__ == '__main__': gen_stats(sys.argv[1])
C
UTF-8
1,856
2.78125
3
[]
no_license
#include <stdio.h> #include <stdint.h> #include <unistd.h> #include <time.h> #include <stdlib.h> #define N 10000 static char input[40960]; static int inputsize; static int inputpos = 0; static int getsint() { int val = 0, neg = 0; if (input[inputpos]=='-') inputpos++, neg = 1; for(;;) { char c = input[inputpos++]; if (c >= '0' && c <= '9') val = val * 10 + c-'0'; else break; } return neg ? -val : val; } #define SWAP(a,b) { __typeof__(a) temp; temp = a; a = b; b = temp; } static int cnt1, cnt2; static void _read() { inputsize = read(0,input,sizeof(input)); } static char p[1024][1024]; static void _main() { int n = 0, c1 = 0, c2 = 0; while (inputpos < inputsize) { int a = getsint(); int b = getsint(); inputpos+=3; int c = getsint(); int d = getsint(); int dx = a == c ? 0 : a < c ? 1 : -1, dy = b == d ? 0 : b < d ? 1 : -1; int len = abs(a - c) + 1; if (a == c) { if (b > d) SWAP(b,d); for (int y = b; y<=d; y++) { if ((p[a][y]&3)==1) c1++; if ((p[a][y]&3)<2) p[a][y]++; if ((p[a][y]>>2)==1) c2++; if ((p[a][y]>>2)<2) p[a][y]+=4; } } else if (b == d) { if (a > c) SWAP(a,c); for (int x = a; x<=c; x++) { if ((p[x][b]&3)==1) c1++; if ((p[x][b]&3)<2) p[x][b]++; if ((p[x][b]>>2)==1) c2++; if ((p[x][b]>>2)<2) p[x][b]+=4; } } else for (int x = a, y = b, i = 0; i < len; x += dx, y += dy, i++) { if ((p[x][y]&3)==1) c1++; if ((p[x][y]&3)<2) p[x][y]++; } } cnt2 = c1; cnt1 = c2; } static void _print() { printf("%d\n%d\n", cnt1, cnt2); } #include "base.h"
Python
UTF-8
125
3.046875
3
[]
no_license
from turtle import* shape ("turtle") speed(0) a = 30 for i in range (80): forward(a ) a+=10 left(90) mainloop()
Java
UTF-8
2,807
2.59375
3
[]
no_license
package com.huaqin.notes; import java.util.HashMap; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; public class TodoAsyncQuery extends AsyncQueryHandler{ private static final String TAG = "TodoAsyncQuery" ; public static final Uri TODO_URI = Uri.parse("content://com.huaqin.todos/todos"); private static HashMap<Context,TodoAsyncQuery> sInstance = new HashMap<Context,TodoAsyncQuery>(); /** * It suggest to use ApplicationContext to create a TodoAsyncQuery. If the context is not * ApplicaitonContext, it must be freed if the context is not used. * @param context * @return */ public static TodoAsyncQuery getInstance(Context context){ if(!sInstance.containsKey(context)){ TodoAsyncQuery aysnQuery = new TodoAsyncQuery(context); sInstance.put(context, aysnQuery); } return sInstance.get(context); } /** * Remove the context if we don't need it. * @param context */ public static void free(Context context){ if(sInstance.containsKey(context)){ sInstance.remove(context); } } /** * Free all contexts. */ public static void freeAll(){ sInstance.clear(); } public TodoAsyncQuery(Context context) { super(context.getContentResolver()); // TODO Auto-generated constructor stub } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { // TODO Auto-generated method stub LogUtils.d(TAG, "onQueryComplete token=" + token); if(cookie instanceof QueryListener){ QueryListener listener = (QueryListener) cookie ; listener.onQueryComplete(token, cursor); }else{ cursor.close(); LogUtils.e(TAG, "cookie is another object: " + cookie); } } @Override protected void onInsertComplete(int token, Object cookie, Uri uri) { // TODO Auto-generated method stub LogUtils.d(TAG, "onInsertComplete token=" + token + " uri=" + uri); if(cookie instanceof QueryListener){ QueryListener listener = (QueryListener) cookie ; listener.onInsertComplete(token, uri); } } @Override protected void onUpdateComplete(int token, Object cookie, int result) { // TODO Auto-generated method stub LogUtils.d(TAG, "onUpdateComplete token=" + token + " result=" + result); if(cookie instanceof QueryListener){ QueryListener listener = (QueryListener) cookie ; listener.onUpdateComplete(token, result); } } @Override protected void onDeleteComplete(int token, Object cookie, int result) { // TODO Auto-generated method stub LogUtils.d(TAG, "onDeleteComplete token=" + token + " result=" + result); if(cookie instanceof QueryListener){ QueryListener listener = (QueryListener) cookie ; listener.onDeleteComplete(token, result); } } }
C
UTF-8
155
2.53125
3
[]
no_license
#include<stdio.h> int main(){ int s, m = 0; scanf("%d",&s); m = s/60; s = s%60; printf("%d %d",m, s); }
C#
UTF-8
1,695
2.609375
3
[]
no_license
private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits private const int SaltSize = 128 / 8; // 128 bits public static string HashPassword(string password) { byte[] salt; byte[] subkey; using (var deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, PBKDF2IterCount)) { salt = deriveBytes.Salt; subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength); } byte[] outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength]; Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize); Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize, PBKDF2SubkeyLength); return Convert.ToBase64String(outputBytes); } public static bool VerifyHashedPassword(string hashedPassword, string password) { byte[] hashedPasswordBytes = Convert.FromBase64String(hashedPassword); // Wrong length or version header. if (hashedPasswordBytes.Length != (1 + SaltSize + PBKDF2SubkeyLength) || hashedPasswordBytes[0] != 0x00) return false; byte[] salt = new byte[SaltSize]; Buffer.BlockCopy(hashedPasswordBytes, 1, salt, 0, SaltSize); byte[] storedSubkey = new byte[PBKDF2SubkeyLength]; Buffer.BlockCopy(hashedPasswordBytes, 1 + SaltSize, storedSubkey, 0, PBKDF2SubkeyLength); byte[] generatedSubkey; using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, PBKDF2IterCount)) { generatedSubkey = deriveBytes.GetBytes(PBKDF2SubkeyLength); } return storedSubkey.SequenceEqual(generatedSubkey); }
Shell
UTF-8
292
2.609375
3
[]
no_license
#!/usr/bin/env bash readonly FIFO="$MY_RUN/presel" [[ -p "$FIFO" ]] || mkfifo "$FIFO" while read line; do if [[ line =~ '^.*dir.*$' ]]; then echo 'p' >> "$FIFO" elif [[ line =~ '^.*cancel.*$' ]]; then echo 'c' >> "$FIFO" fi done < <(bspc subscribe node_presel)
JavaScript
UTF-8
952
2.71875
3
[]
no_license
import { ADD_FAVORITE,REMOVE_FAVORITE,TOGGLE_FAVORITE } from "../actions/favoriteActions" import { ADD_MOVIE } from "../actions/movieActions" const initialState = { favorites: [], displayFavorites: false } const reducer= (state = initialState, action) =>{ switch(action.type){ case TOGGLE_FAVORITE: //true/false display favorite return { ...state, displayFavorites: !state.displayFavorites } case ADD_FAVORITE: //adds new movie obj into fav list return { ...state, favorites: [...state.favorites, {...action.payload}] } case REMOVE_FAVORITE: // removes movie obj from fav list return{ ...state, favorites: state.favorites.filter(item=>(action.payload !== item.id)) } default: return state; } } export default reducer;
Java
UTF-8
4,763
2.015625
2
[]
no_license
package com.example.djd.fingertest; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.JsResult; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Created by djd on 18-12-18. */ public class WebViewActivitiy extends AppCompatActivity { private WebView mWb; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_webview); mWb = findViewById(R.id.wb_test); final WebSettings webSettings = mWb.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); mWb.loadUrl("file:///android_asset/test.html"); findViewById(R.id.btn_calljs).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWb.post(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT < 18) { mWb.loadUrl("javascript:callJS()"); } else { mWb.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { /* AlertDialog.Builder builder = new AlertDialog.Builder(WebViewActivitiy.this); builder.setTitle("Alert"); builder.setMessage(value+"> 18"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //result.confirm(); } }); builder.setCancelable(false); builder.create().show();*/ } }); } } }); } }); mWb.setWebChromeClient(webChromeClient); mWb.addJavascriptInterface(new CallAndroid(), "test"); mWb.setWebViewClient(webViewClient); } public class CallAndroid extends Object{ @JavascriptInterface public void hello(String mgs) { Log.i("webviewActivity", "hello"+mgs); } } private WebViewClient webViewClient = new WebViewClient(){ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { String url = request.getUrl().toString(); Log.i("webviewActivity", "loading"+request.getUrl()); if (url.contains("js")) { return true; } return super.shouldOverrideUrlLoading(view, request); } }; private WebChromeClient webChromeClient = new WebChromeClient(){ @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { //return super.onJsAlert(view, url, message, result); AlertDialog.Builder builder = new AlertDialog.Builder(WebViewActivitiy.this); builder.setTitle("Alert"); builder.setMessage(message); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); builder.setCancelable(false); builder.create().show(); return true; } @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); } }; }
Python
UTF-8
430
3.078125
3
[]
no_license
n,l=map(int,input().split()) a=list(map(int,input().split())) flag=0 for i in range(n-1): if a[i]+a[i+1]>=l: flag=1 break if flag==0: print("Impossible") else: print("Possible") if i>0: for j in range(1,i+1): print(j) if i+2<n: tmp=[] for j in range(i+2,n): tmp.append(j) for item in tmp[::-1]: print(item) print(i+1)
C#
UTF-8
796
2.859375
3
[]
no_license
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace Restaurant.Converter { public class convDatetime : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var dateTimeValue = value as DateTime?; string returnValue = ""; if (value != null) returnValue = dateTimeValue.Value.ToString("HH:mm dd-MM-yyyy"); return returnValue; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
Java
UTF-8
10,887
1.976563
2
[]
no_license
package com.comino.mavmap.map.map3D.impl.octomap; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import com.comino.mavmap.map.map3D.impl.octomap.esdf.D2.DynamicESDF2D; import com.comino.mavmap.map.map3D.impl.octomap.rule.MAVOccupancyUpdateRule; import georegression.struct.GeoTuple3D_F32; import georegression.struct.GeoTuple3D_F64; import georegression.struct.GeoTuple4D_F32; import georegression.struct.point.Point4D_F32; import georegression.struct.point.Vector3D_F32; import us.ihmc.euclid.tuple3D.Point3D; import us.ihmc.jOctoMap.boundingBox.OcTreeSimpleBoundingBox; import us.ihmc.jOctoMap.iterators.OcTreeIterable; import us.ihmc.jOctoMap.iterators.OcTreeIteratorFactory; import us.ihmc.jOctoMap.key.OcTreeKey; import us.ihmc.jOctoMap.key.OcTreeKeyReadOnly; import us.ihmc.jOctoMap.tools.OcTreeNearestNeighborTools; import us.ihmc.jOctoMap.tools.OcTreeSearchTools; import us.ihmc.jOctoMap.tools.OccupancyTools; public class MAVOctoMap3D { public final static double INDETERMINED = -1; public final static int DELETED = 4; private MAVOccupancyOcTree map; private final Point3D tmp; private final OcTreeKey tmpkey; private final DynamicESDF2D esdf; private final List<OcTreeKeyReadOnly> nodesToBeDeleted; private final List<Long> encodedList = new ArrayList<Long>(); private boolean allowRemoveOutDated; public MAVOctoMap3D() { this(0.2f,true); } public MAVOctoMap3D(double resolution, boolean allowRemoveOutDated) { this.map = new MAVOccupancyOcTree(resolution); this.map.enableChangeDetection(true); this.tmp = new Point3D(); this.tmpkey = new OcTreeKey(); this.nodesToBeDeleted = new ArrayList<OcTreeKeyReadOnly>(); this.allowRemoveOutDated = allowRemoveOutDated; this.map.enableDiscretizePointCloud(true); this.esdf = new DynamicESDF2D(10.0f); } public void updateESDF(GeoTuple4D_F32<?> p) { esdf.update(p,map); } public DynamicESDF2D getLocalEDF2D() { return esdf; } public boolean enableRemoveOutdated(boolean enable) { boolean old = allowRemoveOutDated; this.allowRemoveOutDated = enable; return old; } public boolean isRemoveOutdatedEnabled() { return allowRemoveOutDated; } public void update(GeoTuple3D_F32<?> p, GeoTuple3D_F32<?> o ) { Point3D origin = new Point3D(p.x,p.y,-p.z); Point3D end = new Point3D(o.x,o.y,-o.z); map.insertRay(origin, end); } public void update(GeoTuple3D_F64<?> p, GeoTuple3D_F64<?> o ) { Point3D origin = new Point3D(p.x,p.y,-p.z); Point3D end = new Point3D(o.x,o.y,-o.z); map.insertRay(origin, end); } public MAVOccupancyOcTree getTree() { return map; } public void insert(GeoTuple3D_F64<?> o, boolean occupied) { OcTreeKey key = map.coordinateToKey(o.x, o.y, -o.z); map.updateNode(key,occupied); } public void insert(GeoTuple3D_F64<?> o) { OcTreeKey key = map.coordinateToKey(o.x, o.y, -o.z); map.updateNode(key,true); } public void insert(GeoTuple3D_F32<?> o) { OcTreeKey key = map.coordinateToKey(o.x, o.y, -o.z); map.updateNode(key,true); } public void insert(GeoTuple4D_F32<?> o) { OcTreeKey key = map.coordinateToKey(o.x, o.y, -o.z); map.updateNode(key,o.w); } public void insert(float x, float y, float z) { OcTreeKey key = map.coordinateToKey(x, y, z); map.updateNode(key,true); } public void insert(double x, double y, double z, boolean occupied) { OcTreeKey key = map.coordinateToKey(x, y, z); if(occupied) map.updateNode(key,map.getOccupancyParameters().getHitProbabilityLogOdds()); else map.updateNode(key,map.getOccupancyParameters().getMissProbabilityLogOdds()); } public double search(float x, float y, float z) { tmp.set(x,y,-z); MAVOccupancyOcTreeNode node = map.search(tmp); if(node!=null) return node.getOccupancy(); return INDETERMINED; } public boolean isOccupied(GeoTuple4D_F32<?> p) { return isOccupied(p,map.getResolution(),map.getTreeDepth()); } public boolean isOccupied(GeoTuple4D_F32<?> p, double resolution, int depth) { tmp.set(p.x,p.y,-p.z); MAVOccupancyOcTreeNode node = OcTreeSearchTools.search(map.getRoot(), tmp, resolution, depth); if(node!=null) return map.isNodeOccupied(node); return false; } public boolean isOccupied(GeoTuple3D_F32<?> p, double resolution, int depth) { tmp.set(p.x,p.y,-p.z); MAVOccupancyOcTreeNode node = OcTreeSearchTools.search(map.getRoot(), tmp, resolution, depth); if(node!=null) return map.isNodeOccupied(node); return false; } public double search(GeoTuple3D_F32<?> p) { return search(p.x,p.y,p.z); } public void clearAndChangeResolution(float resolution) { this.map = new MAVOccupancyOcTree(resolution); this.map.enableChangeDetection(true); this.nodesToBeDeleted.clear(); this.encodedList.clear(); } public void clear() { this.map = new MAVOccupancyOcTree(map.getResolution()); this.map.enableChangeDetection(true); this.nodesToBeDeleted.clear(); this.encodedList.clear(); } public float getResolution() { return (float)map.getResolution(); } public long convertTo(OcTreeKeyReadOnly key, GeoTuple4D_F32<?> target) { MAVOccupancyOcTreeNode node = map.search(key); if(node==null) return 0; target.setTo((float)node.getX(), (float)node.getY(), (float)node.getZ(), node.getLogOdds()); return encode(key,1); } public Set<OcTreeKeyReadOnly> getChanged() { Set<OcTreeKeyReadOnly> keys = map.getChangedKeys().keySet(); return keys; } public MAVOccupancyOcTreeNode getRoot() { return map.getRoot(); } public List<Long> getLeafsInBoundingBoxEncoded(OcTreeSimpleBoundingBox box) { encodedList.clear(); OcTreeIteratorFactory.createLeafBoundingBoxIteratable(map.getRoot(), box). forEach((n) -> { if(OccupancyTools.isNodeOccupied(map.getOccupancyParameters(), n)) { encodedList.add(encode(n,1)); } }); return encodedList; } public int getNumberOfNodes() { return map.getNumberOfLeafNodes(); } public void resetChangeDetection() { map.resetChangeDetection(); } public long countOccupiedNodes() { OcTreeIterable<MAVOccupancyOcTreeNode> leaf_nodes = OcTreeIteratorFactory.createLeafIterable(map.getRoot()); return leaf_nodes.toList().parallelStream(). filter(n -> OccupancyTools.isNodeOccupied(map.getOccupancyParameters(), n)).count(); } public List<Long> getChangedEncoded(boolean reset) { List<Long> encodedList = new ArrayList<Long>(); encodedList.clear(); if(map.numberOfChangesDetected()==0) { return encodedList; } Set<OcTreeKeyReadOnly> keys = map.getChangedKeys().keySet(); for(OcTreeKeyReadOnly key : keys) { // System.out.println(key); MAVOccupancyOcTreeNode node = map.search(key); if(node==null) continue; if(OccupancyTools.isNodeOccupied(map.getOccupancyParameters(), node)) encodedList.add(encode(key,1)); else encodedList.add(encode(key,0)); } if(reset) map.resetChangeDetection(); return encodedList; } public void removeOutdatedNodes(long dt_ms) { if(!allowRemoveOutDated) return; deleteOutdatedNodes(); final long tms_free = System.nanoTime()-(dt_ms * 1_000_000L); final long tms_occupied = System.nanoTime()-(dt_ms *10L * 1_000_000L); OcTreeIterable<MAVOccupancyOcTreeNode> leaf_nodes = OcTreeIteratorFactory.createLeafIterable(map.getRoot()); for(MAVOccupancyOcTreeNode node : leaf_nodes) { // Remove outdated non-occuppied nodes if(node.getTimestamp() < tms_free) { OcTreeKey key = new OcTreeKey(); if(!OccupancyTools.isNodeOccupied(map.getOccupancyParameters(), node)) { node.getKey(key); node.outdate(); nodesToBeDeleted.add(key); map.getChangedKeys().put(key, MAVOccupancyUpdateRule.DELETED); } } // Remove outdated occuppied nodes if(node.getTimestamp() < tms_occupied) { OcTreeKey key = new OcTreeKey(); if(OccupancyTools.isNodeOccupied(map.getOccupancyParameters(), node)) { node.getKey(key); node.outdate(); nodesToBeDeleted.add(key); map.getChangedKeys().put(key, MAVOccupancyUpdateRule.DELETED); } } } } public void invalidateAllOccupied() { Iterator<MAVOccupancyOcTreeNode> all_nodes = map.iterator(); while(all_nodes.hasNext()) { MAVOccupancyOcTreeNode node = all_nodes.next(); if(OccupancyTools.isNodeOccupied(map.getOccupancyParameters(), node)) map.getChangedKeys().put(node.getKeyCopy(), MAVOccupancyUpdateRule.UPDATED); } } public List<Long> getTreeEncoded() { List<Long> encodedList = new ArrayList<Long>(); encodedList.clear(); if(map.getNumberOfNodes()==0) return encodedList; Iterator<MAVOccupancyOcTreeNode> all_nodes = map.iterator(); while(all_nodes.hasNext()) { MAVOccupancyOcTreeNode node = all_nodes.next(); if(OccupancyTools.isNodeOccupied(map.getOccupancyParameters(), node)) encodedList.add(encode(node.getKey0(), node.getKey1(), node.getKey2(),1)); else encodedList.add(encode(node.getKey0(), node.getKey1(), node.getKey2(),0)); } return encodedList; } public long encode(MAVOccupancyOcTreeNode k, int value_4bit) { return encode(k.getKey0(), k.getKey1(), k.getKey2(),value_4bit); } public long encode(OcTreeKeyReadOnly k, int value_4bit) { return encode(k.getKey(0), k.getKey(1), k.getKey(2),value_4bit); } public int decode(long encoded, OcTreeKey target) { target.set((int)((encoded >> 40) & 0xFFFFFL), (int)((encoded >> 20) & 0xFFFFFL), (int)(encoded & 0xFFFFFL)); return ((int)((encoded >> 60) & 0xFFFFL)); } private long encode(int k0, int k1, int k2, int value_4bit) { return (((long)(value_4bit) << 60L )| (long)k0 << 40L) | ((long)k1 << 20L) | (long)k2; } public GeoTuple4D_F32<?> decode(long encoded,GeoTuple4D_F32<?> p) { int v = decode(encoded,tmpkey); return get(tmpkey,p,v); } public void insertRandom(int count) { Vector3D_F32 s = new Vector3D_F32(0,0,0); Vector3D_F32 e = new Vector3D_F32(0,0,0); for(int i=0; i < count; i++) { e.setTo((float)Math.random()*20-10, (float)Math.random()*20-10, -(float)Math.random()*4); update(s, e); } map.prune(); } public boolean isNodeOccupied(MAVOccupancyOcTreeNode node) { return map.isNodeOccupied(node); } private GeoTuple4D_F32<?> get(OcTreeKeyReadOnly k,GeoTuple4D_F32<?> p, int value_4bit) { if(p == null) p = new Point4D_F32(); map.keyToCoordinate(k, tmp); p.setTo(tmp.getX32(),tmp.getY32(),-tmp.getZ32(),value_4bit); return p; } private void deleteOutdatedNodes() { if(nodesToBeDeleted.isEmpty()) return; for(int i=0;i<nodesToBeDeleted.size();i++) { OcTreeKeyReadOnly key = nodesToBeDeleted.remove(i); if(key==null) continue; if(!map.getChangedKeys().keySet().contains(key)) { map.deleteNode(key); if(map.getNumberOfNodes()==1) { map.clear(); nodesToBeDeleted.clear(); break; } } } } }
Python
UTF-8
969
2.84375
3
[]
no_license
import unittest import l399 class testSolution( unittest.TestCase ): def setUp( self ): self.s = l399.Solution() def test_solution(self): #import pdb;pdb.set_trace() got = self.s.findStrobogrammatic(1) self.assertItemsEqual(got, ['0', '1', '8']) print got got = self.s.findStrobogrammatic(2) print got got = self.s.findStrobogrammatic(2) self.assertItemsEqual(got, ["11","69","88","96"]) got = self.s.findStrobogrammatic(3) self.assertItemsEqual(got, ['101', '808', '609', '906', '111', '818', '619', '916', '181', '888', '689', '986']) print got got = self.s.findStrobogrammatic(4) self.assertItemsEqual(got, ['1111', '8118', '6119', '9116', '1881', '8888', '6889', '9886', '1001', '8008', '6009', '9006', '1691', '8698', '6699', '9696', '1961', '8968', '6969', '9966']) print got if __name__ == "__main__": unittest.main()
JavaScript
UTF-8
471
2.765625
3
[]
no_license
// import the server var app = require("../server"); // import an assertion // assert => say or do something // test => test its validity var supertest = require("supertest"); // write the test describe(`1. GET requests from Todo API`, function () { // invoke our first test it("1.1 should return HTTP status of 200 and JSON data", function (done) { supertest(app) .get("/todos") .expect("Content-Type", /json/i) .expect(201, done); }); });
TypeScript
UTF-8
700
3.140625
3
[]
no_license
/// <reference path="../../../../references.ts" /> /** @enum * @name CommandType * @desc Specifies what commands can be sent through the system * - i.e. communication that _some_ action has occured */ export enum CommandType { Empty, TaskEdit, TaskSave, TaskCompleteToggle, TaskGetAllStart, TaskGetAllComplete, TaskGetAllError } /** @class * @name Command * @desc Used to communication _some_thing_ has happended in the system * (cross component communication basically) */ export class Command { Type: CommandType = CommandType.Empty; // e.g. "TASK_EDIT" Data: Object = null; constructor(type: CommandType, data: Object) { this.Type = type; this.Data = data; } }
Java
UTF-8
10,155
2.328125
2
[]
no_license
package org.apache.flink; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.core.fs.FileSystem; import org.apache.flink.entities.Comment; import org.apache.flink.entities.CommentSchema; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.datastream.DataStreamSink; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor; import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction; import org.apache.flink.streaming.api.windowing.windows.TimeWindow; import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer; import org.apache.flink.streaming.connectors.redis.RedisSink; import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig; import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand; import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription; import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.util.Collector; import org.apache.flink.utils.JedisPoolFactory; import org.apache.flink.utils.MapFunctionDepth2; import org.apache.flink.utils.MapFunctionDepth3; import java.util.*; public class QueryTre { public static void main(String[] args) throws Exception { final int daily_Window_size = 24; final int weekly_Window_size = 24*7; final int monthly_Window_size = 24*30; final int window_dimension = daily_Window_size; String file_path = "query3_output_"+window_dimension+".txt"; final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); Properties properties = new Properties(); properties.setProperty("bootstrap.servers", "localhost:9092"); properties.setProperty("zookeeper.connect", "localhost:2181"); //properties.setProperty("bootstrap.servers", "broker:29092"); //properties.setProperty("zookeeper.connect", "broker:2181"); properties.setProperty("group.id", "flink"); JedisPoolFactory.init("localhost", 6379); FlinkJedisPoolConfig conf = new FlinkJedisPoolConfig.Builder().setHost("localhost").build(); DataStream<Comment> stream = env.addSource(new FlinkKafkaConsumer<>("flink", new CommentSchema(), properties)) .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Comment>(Time.seconds(1)) { @Override public long extractTimestamp(Comment comment) { return comment.createDate*1000; } }); DataStream<Comment> inputStream = stream.filter(x -> x.userID != 0); DataStream<Comment> originalComments = inputStream.filter(x -> x.depth == 1); /** * SALVATAGGIO COMMENTI DEPTH 1 SU REDIS * output: tuple(id comment, id autore) * redis sink, string set * salvataggio su redis delle informazioni (id commento / id autore) dei commenti depth 1 */ DataStreamSink<Tuple2<String, String>> commentAuthor = originalComments.map(new MapFunction<Comment, Tuple2<String, String>>() { @Override public Tuple2<String, String> map(Comment comment) throws Exception { //id commento , id user return new Tuple2<>(Integer.toString(comment.commentID), Integer.toString(comment.userID)); } }).addSink( new RedisSink<>(conf, new RedisDepthOne())); /** * commenti depth1 * conteggio dei like * output: (autore, likes) * estraggo i like per ciascun commento */ DataStream<Tuple2<String,Double>> directCommentsLikes = originalComments .map(new MapFunction<Comment, Tuple2<String, Double>>() { @Override public Tuple2<String, Double> map(Comment comment) { String author = Integer.toString(comment.userID); Double likes = new Double(comment.recommendations); if(comment.editorsSelection){ double increment = likes*0.1; likes += increment; } return new Tuple2<>(author,likes*0.3); } }).keyBy(0).timeWindow(Time.hours(window_dimension)).sum(1); /** * commenti DEPTH 2 * output: tuple(id commento padre, id user padre, id user nonno * tuple pronte per essere salvate su redis */ DataStream<Tuple3<String,String,String>> twoStream = inputStream.filter(x -> x.depth == 2).flatMap(new MapFunctionDepth2()); /** * salvataggio su redis delle tuple depth 2 */ DataStreamSink<Tuple3<String, String, String>> sinkTwo = twoStream.addSink(new RedisSink<>(conf, new RedisDepthTwo())); /** * output: tuple(autore,count comm) * conteggio dei commenti per le tuple autore/count a partire dai commenti di depth 2 */ DataStream<Tuple2<String,Double>> commCountDepthTwo = twoStream.map(new MapFunction<Tuple3<String, String, String>, Tuple2<String, Double>>() { @Override public Tuple2<String, Double> map(Tuple3<String, String, String> stringStringStringTuple3) throws Exception { return new Tuple2<>(stringStringStringTuple3.f2,1*0.7); } }).keyBy(0).timeWindow(Time.hours(window_dimension)).sum(1); /** * commenti DEPTH 3 * output: tuple(autore,count comm) * conteggio dei commenti per le tuple autore/count a partire dai commenti di depth 3 */ DataStream<Tuple2<String, Double>> commCountDepthThree = inputStream.filter(x -> x.depth == 3) .flatMap(new MapFunctionDepth3()) .keyBy(0) .timeWindow(Time.hours(window_dimension)) .sum(1); /** * output: tuple(autore/count comm totale * peso) * union degli stream riguardanti i count dei commenti * valori finali per i commenti */ DataStream<Tuple2<String, Double>> joinDepthTwoThree = commCountDepthTwo.union(commCountDepthThree) .keyBy(0).timeWindow(Time.hours(window_dimension)) .sum(1); /** * output: tuple(autore/rank) * union e somma dei rank per commenti e like per ciascun user */ DataStream<Tuple2<String, Double>> windowResults = directCommentsLikes.union(joinDepthTwoThree) .keyBy(0).timeWindow(Time.hours(window_dimension)).sum(1); /** * ranking * top 10 */ DataStream<String> resultRanking = windowResults.timeWindowAll(Time.hours(window_dimension)) .apply(new AllWindowFunction<Tuple2<String, Double>, String, TimeWindow>() { @Override public void apply(TimeWindow timeWindow, Iterable<Tuple2<String, Double>> iterable, Collector<String> collector) throws Exception { List<Tuple2<String,Double>> myList = new ArrayList<>(); for(Tuple2<String,Double> t : iterable){ myList.add(t); } //String result = "" + new Date(timeWindow.getStart()) +""; String result = "" + timeWindow.getStart() +""; int i=0; while(myList.size() > 0 && i < 10){ Tuple2<String, Double> t = getMaxTuple(myList); result += ", "+t.f0+", "+t.f1; myList.remove(t); i++; } //System.out.println(result); collector.collect(result); } }); resultRanking.writeAsText(file_path, FileSystem.WriteMode.OVERWRITE).setParallelism(1); env.execute(); } private static Tuple2<String, Double> getMaxTuple(List<Tuple2<String, Double>> myList) { Tuple2<String, Double> maxTuple = myList.get(0); double max = myList.get(0).f1; for (Tuple2<String, Double> t : myList) { if(t.f1 > max){ max = t.f1; maxTuple = t; } } return maxTuple; } public static class RedisDepthTwo implements RedisMapper<Tuple3<String,String,String>>{ @Override public RedisCommandDescription getCommandDescription() { return new RedisCommandDescription(RedisCommand.SET, "SET_NAME"); } @Override public String getKeyFromData(Tuple3<String, String, String> stringStringStringTuple3) { return stringStringStringTuple3.f0; } @Override public String getValueFromData(Tuple3<String, String, String> stringStringStringTuple3) { String v = stringStringStringTuple3.f1 +"_"+stringStringStringTuple3.f2; return v; } } public static class RedisDepthOne implements RedisMapper<Tuple2<String, String>>{ @Override public RedisCommandDescription getCommandDescription() { return new RedisCommandDescription(RedisCommand.SET, "SET_NAME"); } @Override public String getKeyFromData(Tuple2<String, String> data) { return data.f0; } @Override public String getValueFromData(Tuple2<String, String> data) { return data.f1; } } }
Java
UTF-8
1,898
2.59375
3
[]
no_license
package playerTest.Entity; import junit.framework.TestCase; import player.models.Letter; import player.models.RandomLetter; public class testLetter extends TestCase { public void testLetter(){ Letter random = new Letter(""); random.setS("a"); assertEquals(random.getS(), "a"); Letter e = new Letter("e"); Letter t = new Letter("t"); assertEquals(e.getScore(), 1); assertEquals(t.getScore(), 1); Letter a = new Letter("a"); Letter o = new Letter("o"); Letter i = new Letter("i"); Letter n = new Letter("n"); Letter h = new Letter("h"); Letter s = new Letter("s"); Letter r = new Letter("r"); assertEquals(a.getScore(), 2); assertEquals(o.getScore(), 2); assertEquals(i.getScore(), 2); assertEquals(n.getScore(), 2); assertEquals(h.getScore(), 2); assertEquals(s.getScore(), 2); assertEquals(r.getScore(), 2); Letter f = new Letter("f"); Letter g = new Letter("g"); Letter y = new Letter("y"); Letter p = new Letter("p"); Letter b = new Letter("b"); assertEquals(f.getScore(), 4); assertEquals(g.getScore(), 4); assertEquals(y.getScore(), 4); assertEquals(p.getScore(), 4); assertEquals(b.getScore(), 4); Letter v = new Letter("v"); Letter k = new Letter("k"); assertEquals(v.getScore(), 5); assertEquals(k.getScore(), 5); Letter j = new Letter("j"); Letter x = new Letter("x"); assertEquals(j.getScore(), 7); assertEquals(x.getScore(), 7); Letter q = new Letter("q"); Letter z = new Letter("z"); assertEquals(q.getScore(), 8); assertEquals(z.getScore(), 8); Letter qu = new Letter("qu"); assertEquals(qu.getScore(), 11); Letter c = new Letter("c"); assertEquals(c.getScore(), 3); c.setStringEmpty(); assertTrue(c.isEmptyString()); assertFalse(qu.isEmptyString()); } public void testRandomLetter(){ RandomLetter rl = new RandomLetter(); rl.generateLetter(); } }
JavaScript
UTF-8
557
2.640625
3
[]
no_license
module.exports = { post : function(server, list){ server.post('/postAnimal', function(req,res) { const animalKind = req.body.inputAnimalKind; const animalsize = req.body.inputAnimalSize; const animalAge = req.body.inputAnimalDays; if(animalAge > 0 && animalAge < 30) { list.push({animalKind, animalsize, animalAge}) res.send(JSON.stringify(list[list.length -1])); } else { res.send('invalid input data') } }); } }
Python
UTF-8
1,185
3.859375
4
[]
no_license
""" Program to encrypt and decrypt a 'Caesar Code' for a given string. """ def main(): s = input("\nEnter the string you'd like to encrypt: ") while True: n = input("How many characters would you like to shift? (Enter a number): ") try: n = int(n) break except ValueError: print("Must be a number.") print(cipher(s, n)) def shift_car(c, n): if c.islower(): return chr(((ord(c) - 97 + n) % 26) + 97) elif c.isupper(): return chr(((ord(c)- 65 + n) % 26) + 65) else: return c def cipher(s, n): result = '' for c in s: result += shift_car(c, n) return result print('\noutcome of cipher (n = 5): Hello World') print(cipher('Hello World', 5)) print('\noutcome of Cipher (n = -5): Hello World') print(cipher('Hello World', -5)) print('\noutcome of cipher (n = -5): Mjqqt btwqi') print(cipher('Mjqqt btwqi', -5)) print() print(cipher("g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj", 2)) main()
C#
UTF-8
1,159
2.65625
3
[]
no_license
// Copyright(C) 2020 Shawn Hodgson All Rights Reserved using UnityEngine; [CreateAssetMenu(fileName = "GameState", menuName = "ScriptableObjects/GameState", order = 1)] public class GameState : ScriptableObject { // TODO: Naming conventions on proporties. public string State { get; private set; } public string Day { get; private set; } public string Time { get; private set; } private string[] _WeekDays = {"Sunday", "Monday", "Tuesday", "Wednsday", "Thursday", "Friday","Saturday", "End"}; private int _CurDay = 0; private string[] _DayTimes = {"Morning", "Afternoon", "Evening"}; private int _CurTime = 0; public void InitState() { _CurDay = 0; _CurTime = 0; Day = _WeekDays[_CurDay]; Time = _DayTimes[_CurTime]; State = "Select"; } public void UpdateState() { State = "Select"; _CurTime++; if(_CurTime >= 3) { _CurTime = 0; _CurDay++; } Day = _WeekDays[_CurDay]; Time = _DayTimes[_CurTime]; } public void NewState(string newState) { State = newState; } }
TypeScript
UTF-8
1,114
2.59375
3
[]
no_license
import * as HttpStatus from 'http-status-codes'; import logger from '../logger'; import { ResponseErrorCode } from '../common/responseCodes.enum'; import {ErrorResponse, SuccessResponse} from '../common/response.model'; import { AuthManager } from './auth.manager'; export const authenticate = async (req, res) => { let username = req.body.username; let password = req.body.password; if (!username || !password) { return res .status(HttpStatus.BAD_REQUEST) .send(new ErrorResponse(ResponseErrorCode.BadRequest, '"username" and "password" are required.')); } let token = await AuthManager.authenticate(username, password); if (token) { logger.info(`user '${username}' authenticated.`); return res .status(HttpStatus.OK) .send( new SuccessResponse(token) ); } else { logger.error(`user '${username}' failed to authenticate.`); return res .status(HttpStatus.UNAUTHORIZED) .send({ reason: ResponseErrorCode.Unauthorized, message: 'authentication failed.' }); } };
Java
UTF-8
1,390
1.859375
2
[]
no_license
package com.playbasis.pbcore.rest.service; import android.support.annotation.NonNull; import com.playbasis.pbcore.rest.form.ParamsMap; import com.playbasis.pbcore.rest.result.organize.RemovePlayerFromOrganizeApiResult; import com.playbasis.pbcore.rest.result.organize.StoreOrganizeApiResult; import com.playbasis.pbcore.rest.result.organize.UpdatePlayerOrganizationApiResult; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.QueryMap; import rx.Observable; public interface StoreOrganizeService { @GET("StoreOrg/nodes") Observable<StoreOrganizeApiResult> getStoreOrganize( @NonNull @Query("api_key") String apiKey, @QueryMap ParamsMap params ); @FormUrlEncoded @POST("StoreOrg/nodes/{node_id}/addPlayer/{id}") Observable<UpdatePlayerOrganizationApiResult> addPlayerOrganization( @NonNull @Path("id") String userId, @NonNull @Path("node_id") String organizeId, @NonNull @Field("token") String token ); @FormUrlEncoded @POST("StoreOrg/nodes/{node_id}/removePlayer/{id}") Observable<RemovePlayerFromOrganizeApiResult> removePlayerOrganization( @NonNull @Path("id") String userId, @NonNull @Path("node_id") String organizeId, @NonNull @Field("token") String token ); }
C++
UTF-8
2,280
3.21875
3
[]
no_license
//============================================================================ // Name : StudentReportCardCpp.cpp // Author : RonakSuchak // Version : // Copyright : setvbuf(stdout, NULL, _IONBF, 0); // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; class Result { public: float maths, english, sci, outOf, per = 0; Result(float outOf) { this->outOf = outOf; } float getMaths() { return maths; } float getEnglish() { return english; } float getSci() { return sci; } void setMaths(float maths) { this->maths = maths; } void setEnglish(float english) { this->english = english; } void setSci(float sci) { this->sci = sci; } float getTotal() { return maths + english + sci; } float getPer() { return (((maths + english + sci) / (outOf * 3)) * 100); } bool isPass() { return (getPer() > 40) ? true : false; } }; class Student { public: int rollNo; char name[10]; Result result = Result(100.0f); Student() { cout << "Enter Name of Student" << endl; cin >> name; cout << "Enter Roll Number of Student" << endl; cin >> rollNo; cout << "Enter marks......." << endl; cout << "Enter Math marks" << endl; cin >> result.maths; cout << "Enter English marks" << endl; cin >> result.english; cout << "Enter science marks" << endl; cin >> result.sci; } public: void getReportCard() { cout<<endl<<endl<<endl; cout << "Roll NO. : " << rollNo << endl; cout << "Name: " << name << endl; cout << "======================================" << endl; cout << "Math: " << result.getMaths() << endl; cout << "Science: " << result.getSci() << endl; cout << "English: " << result.getEnglish() << endl; cout << "Total: " << result.getTotal() << endl; cout << "Percentage: " << result.getPer() << endl; //cout << "Result : " << result.isPass() << endl; (result.isPass()) ? cout << " PASS "<<endl : cout << " FAIL "<<endl; cout << "======================================" << endl; } }; int main() { Student s1 = Student(); s1.getReportCard(); return 0; }
JavaScript
UTF-8
448
2.65625
3
[]
no_license
const Engineer = require('../lib/Engineer'); describe("Employee", () => { describe("Initialization", () => { it("should create a new Employee class with given information", () => { let eng = new Engineer(1, "Bob", "Bob@bob.com", "Bob"); expect(eng.Id).toBe(1); expect(eng.Name).toBe("Bob"); expect(eng.Email).toBe("Bob@bob.com"); expect(eng.Github).toBe("Bob"); }) }) })
C++
UTF-8
1,666
3.46875
3
[]
no_license
/* Find the max continous series of ones. Zeros can be flipped K times. https://www.interviewbit.com/problems/max-continuous-series-of-1s/ TC: O(n) */ /* Range[j:i] maintains the longest sequence of 1s. If the number of zeros in that range is more than flips, we try shifting the starting index, otherwise try expanding by incrementing i. We track the longest length meanwhile */ vector<int> Solution::maxone(vector<int> &arr, int flips) { int max_ones = 0; int ones_count = 0, zero_count = 0; int i = 0, j = 0; int max_s = 0, max_e = 0; if(arr[0] == 0) ++zero_count; else ++ones_count; while(i < arr.size()) { // if the number of zeros is lesser than no. of flips, increase the // range length if(zero_count <= flips) { ++i; if(i >= arr.size()) break; if(arr[i] == 0) { ++zero_count; } else { ++ones_count; } if(zero_count <= flips && ones_count + zero_count > max_ones) { max_s = j; max_e = i; max_ones = ones_count + zero_count; } } // since no. of zeros is greater than allowed flips, reduce range length else { if(arr[j] == 0) { --zero_count; } else { --ones_count; } ++j; } } vector<int> result; for(int i = max_s; i <= max_e; i++) result.emplace_back(i); return result; }
JavaScript
UTF-8
696
3.78125
4
[]
no_license
Array.prototype.bubbleSort = function() { var sorted = false; while(!sorted) { sorted = true; for(var i = 0; i < (this.length - 1); i++) { if(this[i] > this[i + 1]){ var first = this[i]; var second = this[i + 1]; this[i] = second; this[i + 1] = first; sorted = false; } } } return this; }; // console.log([4, 3, 2, 1].bubbleSort()); String.prototype.substrings = function() { var substringsArray = []; for (var i = 0; i < this.length; i++) { for (var j = i + 1; j <= this.length; j++) { substringsArray.push(this.slice(i, j)); } } return substringsArray; }; console.log("applesauce".substrings());
C#
UTF-8
2,100
2.90625
3
[]
no_license
using System.Collections; namespace AustinsExamples.GameState { // don't want to type out full namespace every time public abstract class UIManager : AustinsExamples.UI.UIManager { } public abstract class GameStateUIManager : UIManager { static GameStateUIManager _main; // base input data still exists // color - still here // tile - still here // additional input data public static bool playRecieved { get; protected set; } public static bool pausedRecieved { get; protected set; } public static bool click { get; protected set; } protected virtual void Awake() { _main = this; } // updated clear protected override void Clear() { base.Clear(); SelfClear(); } // don't clear base signals // usefull if we want to use an existing Base UIManager protected virtual void SelfClear() { playRecieved = false; pausedRecieved = false; click = false; } // Not all UI will be active at once // GameControllers will signal what input it is expecting public static void SetPlayState() { _main.ShowPlayUI(); } public static void SetPauseState() { _main.ShowPausedUI(); } // static class does not have direct access to UI objects // so it will call these methods instead protected abstract void ShowPlayUI(); protected abstract void ShowPausedUI(); // this 'hides' the base register class. That is what the 'new' indicates // if you want to use the base Register, do: // => UIManager.Register.Color(c) protected new static partial class Register { public static void Play() { playRecieved = true; } public static void Pause() { pausedRecieved = true; } public static void Click() { click = true; } } } }
Ruby
UTF-8
4,346
3.359375
3
[]
no_license
require_relative 'spec_helper' require_relative '../player' require_relative '../tilebag' describe Scrabble::Player do describe "#initialize" do jane = Scrabble::Player.new("Jane") it "should create an instance of Player" do jane.must_be_instance_of(Scrabble::Player) end it "should be able to return player's name" do jane.must_respond_to(:name) end it "must be able to return player's plays" do jane.must_respond_to(:plays) end it "must be able to return player's tiles" do jane.must_respond_to(:tiles) end # it "must not have more than 7 tiles" do # kelly = Scrabble::Player.new("Kelly") # proc { kelly.tiles = ["a", "b", "c", "d", "e", "f", "g", "h"] }.must_raise(ArgumentError) # end end describe "#play(word)" do it "should add player's words to @plays array" do john = Scrabble::Player.new("John") played_words = ["hex", "bats", "kittys"] played_words.each do |word| john.play(word) end john.plays.length.must_equal(3) end it "should return score of word" do john = Scrabble::Player.new("John") john.play("fox").must_equal(13) end it "should return false if player has won" do john = Scrabble::Player.new("John") winning_array = ["staring", "zzzzzx"] winning_array.each do |word| john.play(word) end john.play("fox").must_equal(false) end end describe "#total_score" do it "should return sum of all words' scores" do john = Scrabble::Player.new("John") animals = ["kittys", "fox", "cat", "dog"] animals.each do |word| john.play(word) end john.total_score.must_equal(36) end it "should return 0 if no words have been played" do john = Scrabble::Player.new("John") john.total_score.must_equal(0) end end describe "#won?" do it "should return true if score is > 100" do john = Scrabble::Player.new("John") winning_array = ["staring", "zzzzzx"] winning_array.each do |word| john.play(word) end john.won?.must_equal(true) end it "should return false if empty" do john = Scrabble::Player.new("John") john.won?.must_equal(false) end it "should return false if not winning" do john = Scrabble::Player.new("John") losing_array = ["cat", "dog"] losing_array.each do |word| john.play(word) end john.won?.must_equal(false) end end describe "#highest_scoring_word" do it "should return the highest scoring word played" do john = Scrabble::Player.new("John") animals = ["kittys", "fox", "cat", "dog"] # => "fox" animals.each do |word| john.play(word) end john.highest_scoring_word.must_equal("fox") end it "should return 'NO WORDS PLAYED' if no words have been played" do john = Scrabble::Player.new("John") john.highest_scoring_word.must_equal("NO WORDS PLAYED") end end describe "#highest_word_score" do it "must return the numerical score of highest_scoring_word" do john = Scrabble::Player.new("John") animals = ["kittys", "fox", "cat", "dog"] animals.each do |word| john.play(word) end john.highest_word_score.must_equal(13) end it "should return 0 if no words in array" do john = Scrabble::Player.new("John") john.highest_word_score.must_equal(0) end end describe "draw_tiles(tile_bag)" do it "must fill tile array until tiles is seven letters" do noelle = Scrabble::Player.new("Noelle") tile_bag = Scrabble::TileBag.new noelle.draw_tiles(tile_bag) noelle.tiles.length.must_equal(7) end end end
Java
ISO-8859-1
17,722
1.867188
2
[]
no_license
/*COMENTARIO DE NUEVA BRANCH*/ package Views; import java.awt.BorderLayout; import java.awt.EventQueue; import concentrarbdinfys.*; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.JButton; import javax.swing.JMenu; import java.awt.Component; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JMenuBar; import java.awt.GridLayout; import javax.swing.JCheckBoxMenuItem; import Database.ConfigUserConnection; import Database.ExternalConnection; import javax.swing.Box; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.UIManager; import java.awt.event.ActionListener; import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.awt.event.ActionEvent; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JDesktopPane; import javax.swing.JFileChooser; import java.awt.Color; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JTextField; import java.awt.Font; import javax.swing.SwingConstants; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import javax.swing.ImageIcon; import java.awt.Toolkit; import java.awt.event.KeyEvent; public class Index extends JFrame { FrmEstadisticas estadistica; FrmExportar exportar; FrmInformacionPorUPM informacionUpm; FrmCalidad calidad; private JPanel contentPane; private JTable table; public String ruta = ""; private String configUser = "/ConfigUser.db"; private String background = "/Icons/"; private boolean leftPanel = true; private Connection baseDatosConfig; private java.sql.Statement sqlConfig; private ExternalConnection externalConnection = new ExternalConnection(); private ConfigUserConnection configUserConnection = new ConfigUserConnection(); public JButton btnEstadisticas; private JTextField textField; public JButton btnExportar; private JDesktopPane desktopPanelCentral; private JLabel lblBackground; private JPanel panelIzquierdo; private JCheckBoxMenuItem chckboxOcultarPanelIzquierdo; private JButton btnInfPorUpm; private JButton btnCalidad; private JMenuItem mntmConcentrador; private JMenuItem mntmConcentrador_1; private JMenu mnConfiguracin; private Component horizontalStrut_2; private JMenuItem mntmGoogleEarth; String google_earth = ""; private JMenu mnHerramientas; private JMenuItem mntmConversorXy; private Component horizontalStrut_3; /*comentario de prueba*/ /** * Launch the application. */ public static void main(String[] args) { try { UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel"); } catch (Throwable e) { e.printStackTrace(); } EventQueue.invokeLater(new Runnable() { @Override public void run() { try { Index frame = new Index(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Index() { ConfigUserConnection.getConnection(configUser); setIconImage(Toolkit.getDefaultToolkit().getImage(Index.class.getResource("/Icons/g5296.png"))); setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); setTitle("Abies (V_1.5.3)"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1366, 847); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); panelIzquierdo = new JPanel(); panelIzquierdo.setBackground(new Color(0, 0, 0)); contentPane.add(panelIzquierdo, BorderLayout.WEST); btnEstadisticas = new JButton("Estadisticas"); btnEstadisticas.setMnemonic('e'); btnEstadisticas.setEnabled(false); btnEstadisticas.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (estadistica.isVisible() == false) { desktopPanelCentral.add(estadistica); estadistica.setVisible(true); } if (estadistica.isBackgroundSet()) { estadistica.moveToFront(); } try { estadistica.setMaximum(true); } catch (Exception e) { // TODO: handle exception } } }); btnExportar = new JButton("CSV"); btnExportar.setMnemonic('s'); btnExportar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (exportar.isVisible() == false) { exportar.setVisible(true); desktopPanelCentral.add(exportar); // System.out.println("Arbir exportar"); } if (exportar.isBackgroundSet()) { exportar.moveToFront(); } try { exportar.setMaximum(false); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } } }); btnExportar.setEnabled(false); btnInfPorUpm = new JButton("Inf. Por UPM"); btnInfPorUpm.setEnabled(false); btnInfPorUpm.setMnemonic('i'); btnInfPorUpm.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (informacionUpm.isVisible() == false) { informacionUpm.setVisible(true); desktopPanelCentral.add(informacionUpm); } if (informacionUpm.isBackgroundSet()) { informacionUpm.moveToFront(); } try { informacionUpm.setMaximum(true); } catch (Exception e) { e.printStackTrace(); } } }); btnCalidad = new JButton("Ctrl. Calidad"); btnCalidad.setMnemonic('c'); btnCalidad.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (calidad.isVisible() == false) { calidad.setVisible(true); desktopPanelCentral.add(calidad); // System.out.println("Arbir exportar"); } if (calidad.isBackgroundSet()) { calidad.moveToFront(); } try { calidad.setMaximum(true); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } } }); btnCalidad.setEnabled(false); GroupLayout gl_panelIzquierdo = new GroupLayout(panelIzquierdo); gl_panelIzquierdo.setHorizontalGroup(gl_panelIzquierdo.createParallelGroup(Alignment.LEADING) .addGroup(gl_panelIzquierdo.createSequentialGroup() .addGroup(gl_panelIzquierdo.createParallelGroup(Alignment.TRAILING) .addComponent(btnEstadisticas, GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE) .addGroup(gl_panelIzquierdo.createSequentialGroup().addGap(1).addComponent(btnInfPorUpm, GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)) .addGroup(gl_panelIzquierdo.createSequentialGroup().addGap(1).addComponent(btnCalidad, GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)) .addGroup(gl_panelIzquierdo.createSequentialGroup().addContainerGap() .addComponent(btnExportar, GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE))) .addContainerGap())); gl_panelIzquierdo.setVerticalGroup(gl_panelIzquierdo.createParallelGroup(Alignment.LEADING) .addGroup(gl_panelIzquierdo.createSequentialGroup().addGap(30).addComponent(btnEstadisticas) .addPreferredGap(ComponentPlacement.UNRELATED).addComponent(btnInfPorUpm) .addPreferredGap(ComponentPlacement.UNRELATED).addComponent(btnCalidad) .addPreferredGap(ComponentPlacement.RELATED, 605, Short.MAX_VALUE).addComponent(btnExportar) .addGap(39))); panelIzquierdo.setLayout(gl_panelIzquierdo); JPanel panelSuperior = new JPanel(); panelSuperior.setBackground(Color.BLACK); panelSuperior.setAlignmentY(Component.TOP_ALIGNMENT); panelSuperior.setAlignmentX(Component.LEFT_ALIGNMENT); contentPane.add(panelSuperior, BorderLayout.NORTH); panelSuperior.setLayout(new GridLayout(0, 1, 0, 0)); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(Color.BLACK); panelSuperior.add(menuBar); JMenu mnBaseDeDatos = new JMenu("Base de datos"); mnBaseDeDatos.setMnemonic('b'); menuBar.add(mnBaseDeDatos); JMenuItem mntmCargar = new JMenuItem("Cargar"); mntmCargar.setMnemonic(KeyEvent.VK_C); mntmCargar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { cargarBaseDatos(); } }); mnBaseDeDatos.add(mntmCargar); mntmConcentrador_1 = new JMenuItem("Concentrador"); mntmConcentrador_1.setMnemonic(KeyEvent.VK_O); mntmConcentrador_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { // Concentrar concentrador = new Concentrar(); ConcentradorAbies concentrador = new ConcentradorAbies(); concentrador.setVisible(true); } }); mnBaseDeDatos.add(mntmConcentrador_1); Component horizontalStrut = Box.createHorizontalStrut(20); menuBar.add(horizontalStrut); JMenu mnVentana = new JMenu("Ventana"); mnVentana.setMnemonic(KeyEvent.VK_V); menuBar.add(mnVentana); chckboxOcultarPanelIzquierdo = new JCheckBoxMenuItem("Ocultar panel izquierdo"); chckboxOcultarPanelIzquierdo.setState(true); chckboxOcultarPanelIzquierdo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (chckboxOcultarPanelIzquierdo.getState() == true) { panelIzquierdo.setVisible(true); setConfigLeftPanel(configUser, 1); } if (chckboxOcultarPanelIzquierdo.getState() == false) { chckboxOcultarPanelIzquierdo.setText("Mostrar panel izquierdo"); panelIzquierdo.setVisible(false); setConfigLeftPanel(configUser, 0); } } }); mnVentana.add(chckboxOcultarPanelIzquierdo); JMenuItem mntmCambiarFondo = new JMenuItem("Fondo conifera"); mntmCambiarFondo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { setBackground(configUser, "AbiesProject_background2.png"); lblBackground.setIcon(new ImageIcon(Index.class.getResource("/Icons/AbiesProject_background2.png"))); } }); mnVentana.add(mntmCambiarFondo); JMenuItem mntmFondoHoja = new JMenuItem("Fondo cono"); mntmFondoHoja.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { setBackground(configUser, "Abies_background.png"); lblBackground.setIcon(new ImageIcon(Index.class.getResource("/Icons/Abies_background.png"))); } }); mnVentana.add(mntmFondoHoja); Component horizontalStrut_1 = Box.createHorizontalStrut(20); menuBar.add(horizontalStrut_1); mnHerramientas = new JMenu("Herramientas"); mnHerramientas.setMnemonic('h'); menuBar.add(mnHerramientas); mntmConversorXy = new JMenuItem("Conversor X,Y"); mntmConversorXy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { FrmConversorCoordenadas conversor = new FrmConversorCoordenadas(); conversor.setVisible(true); } }); mnHerramientas.add(mntmConversorXy); horizontalStrut_3 = Box.createHorizontalStrut(20); menuBar.add(horizontalStrut_3); mnConfiguracin = new JMenu("Configuraci\u00F3n"); menuBar.add(mnConfiguracin); mntmGoogleEarth = new JMenuItem("Google earth"); mntmGoogleEarth.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { getConfigGoogleEarth(configUser); } }); mnConfiguracin.add(mntmGoogleEarth); horizontalStrut_2 = Box.createHorizontalStrut(20); menuBar.add(horizontalStrut_2); JLabel lblBdActual = new JLabel("BD actual:"); lblBdActual.setEnabled(false); menuBar.add(lblBdActual); textField = new JTextField(); textField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent arg0) { textField.selectAll(); } }); textField.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 12)); menuBar.add(textField); textField.setColumns(10); desktopPanelCentral = new JDesktopPane(); contentPane.add(desktopPanelCentral, BorderLayout.CENTER); lblBackground = new JLabel(""); lblBackground.setHorizontalAlignment(SwingConstants.CENTER); GroupLayout gl_desktopPanelCentral = new GroupLayout(desktopPanelCentral); gl_desktopPanelCentral.setHorizontalGroup(gl_desktopPanelCentral.createParallelGroup(Alignment.LEADING) .addGroup(gl_desktopPanelCentral.createSequentialGroup().addGap(51) .addComponent(lblBackground, GroupLayout.DEFAULT_SIZE, 741, Short.MAX_VALUE).addGap(89))); gl_desktopPanelCentral.setVerticalGroup(gl_desktopPanelCentral.createParallelGroup(Alignment.LEADING) .addGroup(gl_desktopPanelCentral.createSequentialGroup() .addComponent(lblBackground, GroupLayout.DEFAULT_SIZE, 705, Short.MAX_VALUE).addGap(64))); desktopPanelCentral.setLayout(gl_desktopPanelCentral); getUserConfigs(configUser); } public void cargarBaseDatos() { JFileChooser fcBaseDatos = new JFileChooser(ruta); fcBaseDatos.setDialogTitle("Base de datos a importar"); FileNameExtensionFilter filtro = new FileNameExtensionFilter("*.cons", "cons"); fcBaseDatos.setAcceptAllFileFilterUsed(false); fcBaseDatos.setFileFilter(filtro); int returnVal = fcBaseDatos.showOpenDialog(this); // fcBaseDatos.showOpenDialog(Main.main); try { File baseDatos = fcBaseDatos.getSelectedFile(); ruta = baseDatos.getAbsolutePath(); int tamanio = ruta.length(); int cadena = tamanio - 4; String extension = ruta.substring(cadena, tamanio); if (!extension.equals("cons")) { // System.out.println(extension); JOptionPane.showMessageDialog(null, "Debe seleccionar un base de datos valida a importar" + "", "Importacin", JOptionPane.INFORMATION_MESSAGE); } else { if (returnVal == JFileChooser.APPROVE_OPTION) { /* OBJETOS */ ExternalConnection.getConnection(ruta); calidad = new FrmCalidad(ruta); informacionUpm = new FrmInformacionPorUPM(ruta, this.desktopPanelCentral); estadistica = new FrmEstadisticas(ruta); exportar = new FrmExportar(ruta); textField.setText(ruta); enabledLeftPanelButtons(); JOptionPane.showMessageDialog(null, "Se conect satisfactoriamente"); } } } catch (Exception e) { } } public void enabledLeftPanelButtons() { btnEstadisticas.setEnabled(true); btnExportar.setEnabled(true); btnCalidad.setEnabled(true); btnInfPorUpm.setEnabled(true); } public void setGoogleEarth(String ruta, String ruta_earth) { String query = "UPDATE configUserAbies SET google_earth='" + ruta_earth + "'"; Connection configConnection = ConfigUserConnection.getConnection(ruta); // System.out.println("RutaSetGoogle="+ruta_earth); try { java.sql.Statement st = configConnection.createStatement(); st.executeUpdate(query); configConnection.commit(); st.close(); } catch (Exception e) { e.printStackTrace(); } } public void getConfigGoogleEarth(String configUser) { JFileChooser chooser = new JFileChooser("C:\\"); FileNameExtensionFilter filter = new FileNameExtensionFilter("Google earth", "exe"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); google_earth = file.getAbsolutePath(); setGoogleEarth(configUser, google_earth); JOptionPane.showMessageDialog(null, "Se actualiz ruta de Google Earth"); } } public void getUserConfigs(String ruta) { String query = "SELECT idConfig, showLeftPanel, background FROM configUserAbies"; this.baseDatosConfig = ConfigUserConnection.getConnection(ruta); try { sqlConfig = baseDatosConfig.createStatement(); ResultSet rsConfig = sqlConfig.executeQuery(query); while (rsConfig.next()) { lblBackground .setIcon(new ImageIcon(Index.class.getResource("/Icons/" + rsConfig.getString("background")))); panelIzquierdo.setVisible(rsConfig.getBoolean("showLeftPanel")); chckboxOcultarPanelIzquierdo.setSelected(rsConfig.getBoolean("showLeftPanel")); if (chckboxOcultarPanelIzquierdo.getState() == true) { panelIzquierdo.setVisible(true); } if (chckboxOcultarPanelIzquierdo.getState() == false) { chckboxOcultarPanelIzquierdo.setText("Mostrar panel izquierdo"); panelIzquierdo.setVisible(false); } } baseDatosConfig.close(); } catch (Exception e) { e.printStackTrace(); } } public void setBackground(String ruta, String background) { String query = "UPDATE configUserAbies SET background='" + background + "'"; Connection configConnection = ConfigUserConnection.getConnection(ruta); try { java.sql.Statement st = configConnection.createStatement(); st.executeUpdate(query); configConnection.commit(); // System.out.println("Actualizado background"); st.close(); } catch (Exception e) { e.printStackTrace(); } } public void setConfigLeftPanel(String ruta, int visible) { String query = "UPDATE configUserAbies SET showLeftPanel=" + visible; // System.out.println(query); Connection configConnection = ConfigUserConnection.getConnection(ruta); try { java.sql.Statement st = configConnection.createStatement(); st.executeUpdate(query); configConnection.commit(); // System.out.println("Actualizado panel"); st.close(); } catch (Exception e) { e.printStackTrace(); } } }
Python
UTF-8
796
3.21875
3
[]
no_license
def compute(opcode, in1, in2): if opcode == 1: return in1 + in2 if opcode == 2: return in1 * in2 program = [] with open('input.txt', 'r') as f: line = f.readline() program = line.split(',') program[-1] = program[-1].strip() #remove \n program = [int(x) for x in program] #conver to ints original_state = program #to reset state for noun in range(100): for verb in range(100): program = original_state[:] program[1] = noun program[2] = verb #interpret instruction set for i in range(0, len(program), 4): if program[i] == 99: break program[program[i+3]] = compute(program[i], program[program[i+1]], program[program[i+2]]) #check results if program[0] == 19690720: print(noun, verb, 100 * noun + verb) exit() #reset state program = original_state[:]
C
UTF-8
1,286
3.609375
4
[]
no_license
/*Задача 19: Напишете стандартната програма за Linux cat , която приема като аргументи от командния ред имена на файлове и изкарва съдържанието им на стандартния изход. Ако на програмата не са подадени никакви аргументи, то тя да изкара съдържанието подадено от стандартния вход на стандартния изход.*/ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int count; char c; FILE *fp; if(argc < 2){ for(count = 0; count < argc; count++){ printf("argv[%2d]: %s\n", count, argv[count]); } } else{ for(count = 1; count < argc; count++){ fp = fopen(argv[count], "r"); if(fp == NULL){ printf("Error oppening file!\n"); exit(1); } c = fgetc(fp); while (c != EOF){ printf("%c",c); c = fgetc(fp); } printf("\n"); fclose(fp); fp = NULL; } } return 0; }
Python
UTF-8
490
3.3125
3
[]
no_license
#https://leetcode.com/problems/backspace-string-compare/ class Solution(object): def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ def compress(A): stack = list() for c in A: if c != "#": stack.append(c) elif stack: stack.pop() return stack return compress(S) == compress(T)
C
UTF-8
6,080
2.796875
3
[]
no_license
const unsigned char font[96][8] = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // {0xdf, 0xdf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // ! {0x07, 0x07, 0x00, 0x07, 0x07, 0x00, 0x00, 0x00}, // " {0x24, 0x24, 0xff, 0x24, 0x24, 0xff, 0x24, 0x24}, // # {0xdf, 0xdf, 0xdb, 0xff, 0xff, 0xdb, 0xfb, 0xfb}, // $ {0xdf, 0xdf, 0x3b, 0xff, 0xff, 0xdc, 0xfb, 0xfb}, // % {0xff, 0xff, 0xdb, 0xdf, 0xdf, 0x20, 0xd8, 0xd8}, // & {0x07, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // ' {0x3c, 0x3c, 0xc3, 0x00, 0x00, 0x00, 0x00, 0x00}, // ( {0xc3, 0xc3, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00}, // ) {0xc3, 0xc3, 0x24, 0xff, 0xff, 0x24, 0xc3, 0xc3}, // * {0x18, 0x18, 0x18, 0xff, 0xff, 0x18, 0x18, 0x18}, // + {0xc0, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // , {0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18}, // - {0xc0, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // . {0xc0, 0xc0, 0x20, 0x18, 0x18, 0x04, 0x03, 0x03}, // / {0xff, 0xff, 0xe3, 0xdb, 0xdb, 0xc7, 0xff, 0xff}, // 0 {0xc3, 0xc3, 0xff, 0xc0, 0xc0, 0x00, 0x00, 0x00}, // 1 {0xfb, 0xfb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdf, 0xdf}, // 2 {0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xff, 0xff}, // 3 {0x1f, 0x1f, 0x18, 0x18, 0x18, 0x18, 0xff, 0xff}, // 4 {0xdf, 0xdf, 0xdb, 0xdb, 0xdb, 0xdb, 0xfb, 0xfb}, // 5 {0xff, 0xff, 0xdb, 0xdb, 0xdb, 0xdb, 0xfb, 0xfb}, // 6 {0x07, 0x07, 0x03, 0x03, 0x03, 0x03, 0xff, 0xff}, // 7 {0xff, 0xff, 0xdb, 0xdb, 0xdb, 0xdb, 0xff, 0xff}, // 8 {0xdf, 0xdf, 0xdb, 0xdb, 0xdb, 0xdb, 0xff, 0xff}, // 9 {0x24, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // : {0xe4, 0xe4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // ; {0x18, 0x18, 0x24, 0xc3, 0xc3, 0x00, 0x00, 0x00}, // < {0x24, 0x24, 0x24, 0x24, 0x24, 0x24, 0x24, 0x24}, // = {0xc3, 0xc3, 0x24, 0x18, 0x18, 0x00, 0x00, 0x00}, // > {0x07, 0x07, 0x03, 0xdb, 0xdb, 0x1b, 0x1f, 0x1f}, // ? {0xff, 0xff, 0xc3, 0xfb, 0xfb, 0xdb, 0xff, 0xff}, // @ {0xff, 0xff, 0xdb, 0x1b, 0x1b, 0xdb, 0xff, 0xff}, // A {0xff, 0xff, 0xdb, 0xdb, 0xdb, 0xdb, 0xe7, 0xe7}, // B {0xff, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0xe7, 0xe7}, // C {0xff, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0x3c, 0x3c}, // D {0xff, 0xff, 0xdb, 0xdb, 0xdb, 0xc3, 0xe7, 0xe7}, // E {0xff, 0xff, 0xdb, 0x1b, 0x1b, 0x03, 0x07, 0x07}, // F {0xff, 0xff, 0xc3, 0xdb, 0xdb, 0xdb, 0xfb, 0xfb}, // G {0xff, 0xff, 0xdb, 0x18, 0x18, 0xdb, 0xff, 0xff}, // H {0xc3, 0xc3, 0xc3, 0xff, 0xff, 0xc3, 0xc3, 0xc3}, // I {0xe0, 0xe0, 0xc0, 0xc0, 0xc0, 0xc3, 0xff, 0xff}, // J {0xff, 0xff, 0xdb, 0x18, 0x18, 0xdb, 0xe7, 0xe7}, // K {0xff, 0xff, 0xc3, 0xc0, 0xc0, 0xc0, 0xe0, 0xe0}, // L {0xff, 0xff, 0xc3, 0x1f, 0x1f, 0xc3, 0xff, 0xff}, // M {0xff, 0xff, 0xc4, 0x18, 0x18, 0x23, 0xff, 0xff}, // N {0xff, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xff}, // O {0xff, 0xff, 0xdb, 0x1b, 0x1b, 0x1b, 0x1f, 0x1f}, // P {0xff, 0xff, 0xc3, 0xe3, 0xe3, 0xc3, 0xff, 0xff}, // Q {0xff, 0xff, 0xdb, 0x1b, 0x1b, 0xdb, 0xe7, 0xe7}, // R {0xdf, 0xdf, 0xdb, 0xdb, 0xdb, 0xdb, 0xfb, 0xfb}, // S {0x07, 0x07, 0xc3, 0xff, 0xff, 0xc3, 0x07, 0x07}, // T {0xff, 0xff, 0xc3, 0xc0, 0xc0, 0xc3, 0xff, 0xff}, // U {0x1f, 0x1f, 0x23, 0xc0, 0xc0, 0x23, 0x1f, 0x1f}, // V {0xff, 0xff, 0xc3, 0xf8, 0xf8, 0xc3, 0xff, 0xff}, // W {0xe7, 0xe7, 0xdb, 0x18, 0x18, 0xdb, 0xe7, 0xe7}, // X {0x1f, 0x1f, 0xdb, 0xf8, 0xf8, 0xdb, 0x1f, 0x1f}, // Y {0xc7, 0xc7, 0xe3, 0xdb, 0xdb, 0xc7, 0xe3, 0xe3}, // Z {0xff, 0xff, 0xc3, 0x00, 0x00, 0x00, 0x00, 0x00}, // [ {0x03, 0x03, 0x04, 0x18, 0x18, 0x20, 0xc0, 0xc0}, // "\" {0xc3, 0xc3, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00}, // ] {0x04, 0x04, 0x03, 0x04, 0x04, 0x00, 0x00, 0x00}, // ^ {0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0}, // _ {0x03, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00}, // ` {0xff, 0xff, 0xdb, 0x1b, 0x1b, 0xdb, 0xff, 0xff}, // a {0xff, 0xff, 0xdb, 0xdb, 0xdb, 0xdb, 0xe7, 0xe7}, // b {0xff, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0xe7, 0xe7}, // c {0xff, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0x3c, 0x3c}, // d {0xff, 0xff, 0xdb, 0xdb, 0xdb, 0xc3, 0xe7, 0xe7}, // e {0xff, 0xff, 0xdb, 0x1b, 0x1b, 0x03, 0x07, 0x07}, // f {0xff, 0xff, 0xc3, 0xdb, 0xdb, 0xdb, 0xfb, 0xfb}, // g {0xff, 0xff, 0xdb, 0x18, 0x18, 0xdb, 0xff, 0xff}, // h {0xc3, 0xc3, 0xc3, 0xff, 0xff, 0xc3, 0xc3, 0xc3}, // i {0xe0, 0xe0, 0xc0, 0xc0, 0xc0, 0xc3, 0xff, 0xff}, // j {0xff, 0xff, 0xdb, 0x18, 0x18, 0xdb, 0xe7, 0xe7}, // k {0xff, 0xff, 0xc3, 0xc0, 0xc0, 0xc0, 0xe0, 0xe0}, // l {0xff, 0xff, 0xc3, 0x1f, 0x1f, 0xc3, 0xff, 0xff}, // m {0xff, 0xff, 0xc4, 0x18, 0x18, 0x23, 0xff, 0xff}, // n {0xff, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xff}, // o {0xff, 0xff, 0xdb, 0x1b, 0x1b, 0x1b, 0x1f, 0x1f}, // p {0xff, 0xff, 0xc3, 0xe3, 0xe3, 0xc3, 0xff, 0xff}, // q {0xff, 0xff, 0xdb, 0x1b, 0x1b, 0xdb, 0xe7, 0xe7}, // r {0xdf, 0xdf, 0xdb, 0xdb, 0xdb, 0xdb, 0xfb, 0xfb}, // s {0x07, 0x07, 0xc3, 0xff, 0xff, 0xc3, 0x07, 0x07}, // t {0xff, 0xff, 0xc3, 0xc0, 0xc0, 0xc3, 0xff, 0xff}, // u {0x1f, 0x1f, 0x23, 0xc0, 0xc0, 0x23, 0x1f, 0x1f}, // v {0xff, 0xff, 0xc3, 0xf8, 0xf8, 0xc3, 0xff, 0xff}, // w {0xe7, 0xe7, 0xdb, 0x18, 0x18, 0xdb, 0xe7, 0xe7}, // x {0x1f, 0x1f, 0xdb, 0xf8, 0xf8, 0xdb, 0x1f, 0x1f}, // y {0xc7, 0xc7, 0xe3, 0xdb, 0xdb, 0xc7, 0xe3, 0xe3}, // z {0x18, 0x18, 0xff, 0xc3, 0xc3, 0x00, 0x00, 0x00}, // { {0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // | {0xc3, 0xc3, 0xff, 0x18, 0x18, 0x00, 0x00, 0x00}, // } {0x04, 0x04, 0x03, 0x04, 0x04, 0x03, 0x00, 0x00}, // ~ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} };
Markdown
UTF-8
6,931
2.953125
3
[]
no_license
* * * * * **Council Bill Number: [](#h0)[](#h2)112550** **Ordinance Number: 119360** * * * * * AN ORDINANCE relating to the Seattle City Employees' Retirement System; changing the payment schedule of the annual bonus dividend for current retirees; and amending Chapter 4.36 of the Seattle Municipal Code. **Status:** PASSED **Date passed by Full Council:** January 25, 1999 **Vote:** 9-0 **Date filed with the City Clerk:** February 2, 1999 **Date of Mayor's signature:** February 2, 1999 [(about the signature date)](/~public/approvaldate.htm) **Date introduced/referred to committee:** January 19, 1999 **Committee:** Full Council **Sponsor:** CHOE **Index Terms:** PENSIONS, RETIREMENT-SYSTEM **Fiscal Note:** *(No fiscal note available at this time)* * * * * * **Text** AN ORDINANCE relating to the Seattle City Employees' Retirement System; changing the payment schedule of the annual bonus dividend for current retirees; and amending Chapter 4.36 of the Seattle Municipal Code. BE IT ORDAINED BY THE CITY OF SEATTLE AS FOLLOWS: Section Dividend to be paid in monthly installments. Section 4.36.155 of the Seattle Municipal Code is amended as follows: 4.36.155 Annual bonus dividend for current and future retirees. Each January, the Board of Administration shall declare a supplemental monthly dividend payable to all members and beneficiaries who will receive a current benefit during that year as described in subsection I. Each December, the Board of Administration shall declare and pay to all retired members and beneficiaries receiving a current benefit the base annual bonus dividend described in subsections A through H, inclusive, plus the supplemental dividend adjustment described in subsection I, if applicable. Such bonusdividends will be calculated and paid in accordance with the following formula: A. One percent (1%) of the current benefit, payable on behalf of members who retired in the current and immediately preceding year; B. Three percent (3%) of the current benefit, payable on behalf of members who have been retired from two (2) to five (5) years, inclusive; C. Six percent (6%) of the current benefit, payable on behalf of members who have been retired from six (6) to nine (9) years, inclusive; D. Nine percent (9%) of the current benefit, payable on behalf of members who have been retired from ten (10) to thirteen (13) years, inclusive; E. Twelve percent (12%) of the current benefit, payable on behalf of members who have been retired from fourteen (14) to eighteen (18) years, inclusive; F. Fifteen percent (15%) of the current benefit, payable on behalf of members who have been retired from nineteen (19) to twenty-three (23) years, inclusive; G. Eighteen percent (18%) of the current benefit, payable on behalf of members who have been retired from twenty-four (24) to twenty-eight (28) years, inclusive; H. Twenty-one percent (21%) of the current benefit, payable on behalf of members who have been retired for twenty-nine (29) or more years. I. This subsection applies to members, or For beneficiaries receiving payments on behalf of any such member, who retired before January 1, 1998., iI f the sum of that beneficiary's current benefit plus the base annual bonus dividend as established in subsections A through H above is less than sixty percent (60%) of the beneficiary's indexed benefit, then the beneficiary's total annual bonus dividend shall be increased to equal to the difference between the current benefit and sixty percent (60%) of the beneficiary's indexed benefit. However, in no year may the amount of the total annual bonus dividend be less than the amount of the total annual bonus dividend paid in the previous calendar year. The total annual bonus dividend is paid as the base annual bonus dividend plus supplemental monthly dividends and a supplemental dividend adjustment to the base annual bonus dividend. Each year in January the Retirement Board shall compute the supplemental monthly dividend based upon the total supplemental dividends paid during the previous calendar year divided by 12. In December of each year, a supplemental dividend adjustment shall be computed equal to the difference between the sum of the supplemental monthly dividends paid in January through November of that calendar year and the total supplemental dividend payable for that calendar year. Section Section 4.36.215 of the Seattle Municipal Code is amended as follows: 4.36.215 Annual Cost of Living Adjustment. A. Applicability. This section applies to all members, and beneficiaries receiving payment on behalf of any such member, who retired on or after January 1, 1998. B. Annual Adjustment. 1. As of December 1 of each year, a member's or beneficiary's adjusted benefit shall be increased by one and one-half percent (1.5%), except as otherwise provided in this section. 2. For any calendar year, the member or beneficiary shall receive the greater of: a. The adjusted benefit, or b. The sum of the initial benefit plus the base annual bonus dividend provided for in SMC 4.36.155, or c. Sixty percent (60%) of the Indexed Benefit; or d. The benefit paid in the prior calendar year. Section Any act consistent with the authority and prior to the effective date of this ordinance is hereby ratified and confirmed Section This ordinance shall take effect and be in force thirty (30) days from and after its approval by the Mayor, but if not approved and returned by the Mayor within ten (10) days after presentation, it shall take effect as provided by Municipal Code Section 1.04.020. Passed by the City Council the _____ day of ____________, 1999, and signed by me in open session in authentication of its passage this _____ day of _________________, 1999. _____________________________________ President _______ of the City Council Approved by me this _____ day of _________________, 1999. ___________________________________________ Mayor Filed by me this _____ day of ____________________, 1999. ___________________________________________ City Clerk (Seal) MKD:gh January 21, 1999 COLA-ORD.DOC (Ver. 1 )
Python
UTF-8
1,222
2.625
3
[]
no_license
""" This file exists for pre-release version tracking. Please do not edit anything in this file unless you are contributing to the development of InSPy Kit (or this particular sub-package)! """ # What stage of pre-release is this? pr_type = 'pre-alpha' # What build version of the pre-release is it? pr_version = '0.1' # Concatenate the two previous strings into one for easy access to both parts. version = f'{pr_type}_{pr_version}' # Dev Note: 'pr_version' should be incremented any time you push changes code that the program uses to run. # Therefore; one would not increment this version if: # - Pushing new documentation. # - Correcting typo in code comments. # # Since this version information focuses on unstable releases ONLY one shouldn't bother # incrementing 'pr_version' when changing 'pre_release' to False in _version.py when # pushing the final change in a stable application release. # # If you have any comments/questions/concerns/thoughts of any kind please don't hesitate # to file an issue on github (https://github.com/tayjaybabee/sub-dom-scan), or contact me # via email <t.blackstone@inspyre.tech>
Markdown
UTF-8
1,012
2.5625
3
[]
no_license
# Article R814-18 Les élections sont organisées par le conseil d'administration de la caisse de garantie qui détermine les modalités qui leur sont applicables selon des règles soumises à l'approbation du garde des sceaux, ministre de la justice. Le bureau chargé du dépouillement des votes comprend le président, le vice-président, le secrétaire et le trésorier du conseil d'administration de la caisse. Les candidats qui, dans chaque collège, ont obtenu le plus grand nombre de voix sont élus. Les réclamations sont portées devant la cour d'appel de Paris. Les membres de la caisse ne sont rééligibles qu'une fois. Sous réserve des dispositions du présent article, les règles de l'article R. 811-3 sont applicables à l'élection des membres du conseil d'administration. **Liens relatifs à cet article** _Codifié par_: - Décret n°2007-431 2007-03-25 JORF 27 mars 2007 _Cite_: - Code de commerce - art. R811-3 (V) _Cité par_: - Code de commerce. - art. A814-3 (V)
Java
UTF-8
433
1.867188
2
[ "MIT" ]
permissive
package com.boluozhai.snowflake.xgit.http.client.toolkit; import com.boluozhai.snowflake.context.SnowflakeContext; import com.boluozhai.snowflake.xgit.http.client.impl.toolkit.ToolkitImplementation; public interface GitClientToolkit { class Factory { public static GitClientToolkit newInstance(SnowflakeContext context) { return ToolkitImplementation.createToolkit(context); } } RemoteAgent getRemote(String url); }
Java
UTF-8
758
1.90625
2
[]
no_license
package domain.service; public class ServiceProvider { private static BlogPostService blogPostService = new BlogPostService(); private static UserService userService = new UserService(); private static ValidateService validateService = new ValidateService(); private static EmailService emailService = new EmailService(); //TODO fix service provider error when email service is initialized public static BlogPostService getBlogPostService(){ return blogPostService; } public static UserService getUserService(){ return userService; } public static ValidateService getValidateService(){ return validateService; } public static EmailService getEmailService() { return emailService; } }
JavaScript
UTF-8
1,135
3.328125
3
[]
no_license
class Weapon{ /** * Caractéristiques de l'arme. * @param {Number} id - id de l'arme * @param {string} name - nom de l'arme * @param {Number} force - Puissance de l'arme */ constructor(id, name, force){ this.id = id; this.position = false; this.x = Number; this.y = Number; this.name = name; this.force = force; } /** * Initialise le placement aléatoire de l'arme sur la board en vérifiant que la place est disponible. * @param {Array} board - Tableau du board */ init(board) { do { this.x = getRandomInt(0,9); this.y = getRandomInt(0,9); if(board[this.x][this.y] === 0){ board[this.x][this.y] = this.id; this.position = true; } } while (this.position === false); } } /** * Création des armes. */ const stick = new Weapon(4, 'Bâton', 3); const dagger = new Weapon(5, 'Dague', 5); const dualsword = new Weapon(6, 'Double épée', 7); const pugilat = new Weapon(7, 'Pugilat', 5); const sword = new Weapon(8, 'Epée', 6);
JavaScript
UTF-8
2,013
2.765625
3
[]
no_license
// const marvelUrl = 'http://gateway.marvel.com/v1/public/characters' // const publicKey = `apikey=${process.env.REACT_APP_PUBLIC_API_KEY}`; // const privateKey = `apikey=${process.env.REACT_APP_PRIVATE_API_KEY}`; // const timestamp = new Date().getTime(); // const hash = sha256(timestamp + privateKey + publicKey); // const auth = `&ts=${timestamp}&apikey=${publicKey}&hash=${hash}`; //const query = `?nameStartsWith=${name}`; //const url = `${marvelUrl}${query}${auth}`; //http://gateway.marvel.com/v1/public/characters?limit=12&nameStartsWith=${character}&ts=${ts}&apikey=${key}&hash=${hash}` //https://github.com/inglkruiz/react-marvel-api // const getMarvelCharacters = (options) => { // const { // offset, // name, // exactMatch, // sortName, // limit, // } = Object.assign({ // offset: 0, // name: '', // exactMatch: false, // sortName: '', // limit: 20, // }, options); // let url = // `${marvelUrl}characters?${publicKey}&offset=${offset}&orderBy=${sortName}name&limit=${limit}`; // if (name) { // if (exactMatch) { url += `&name=${name}`; } // else { url += `&nameStartsWith=${name}`; } // } // return fetch(url) // .then(res => res.json()) // .then((resObj) => { // try { // if (resObj.code === 200) { // if (offset > resObj.data.total) { // throw new Error('Page does not exist.'); // } else { // const pages = Math.floor(resObj.data.total / limit); // return { // characters: resObj.data.results, // maxPage: resObj.data.total % limit > 0 ? pages + 1 : pages, // }; // } // } else { // throw new Error(`Marvel API bad response. Status code ${resObj.code}.`); // } // } catch (e) { // console.error(e); // return { // characters: [], // maxPage: 0, // }; // } // }); // } // export { // getMarvelCharacters, // };
PHP
UTF-8
1,261
2.96875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: usersio * Date: 15/03/17 * Time: 09:54 */ namespace BDD\Table; class Link { private $_id; private $_startingHarbor; private $_arrivalHarbor; private $_sector; public function __construct($id) { $this->_id = $id; } /** * @param mixed $startingHarbor */ public function setStartingHarbor(Harbor $startingHarbor) { $this->_startingHarbor = $startingHarbor; } /** * @param mixed $arrivalHarbor */ public function setArrivalHarbor(Harbor $arrivalHarbor) { $this->_arrivalHarbor = $arrivalHarbor; } /** * @param mixed $sector */ public function setSector(Sector $sector) { $this->_sector = $sector; } /** * @return mixed */ public function getId() { return $this->_id; } /** * @return mixed */ public function getStartingHarbor() { return $this->_startingHarbor; } /** * @return mixed */ public function getArrivalHarbor() { return $this->_arrivalHarbor; } /** * @return mixed */ public function getSector() { return $this->_sector; } }
C#
UTF-8
1,666
2.53125
3
[]
no_license
using Codebreak.Framework.Database; using Codebreak.Service.World.Database.Structure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Codebreak.Service.World.Database.Repository { /// <summary> /// /// </summary> public sealed class CharacterGuildRepository : Repository<CharacterGuildRepository, CharacterGuildDAO> { /// <summary> /// /// </summary> private Dictionary<long, CharacterGuildDAO> m_characterGuildById; /// <summary> /// /// </summary> public CharacterGuildRepository() { m_characterGuildById = new Dictionary<long, CharacterGuildDAO>(); } /// <summary> /// /// </summary> /// <param name="id"></param> /// <returns></returns> public CharacterGuildDAO GetById(long id) { if (m_characterGuildById.ContainsKey(id)) return m_characterGuildById[id]; return base.Load("Id=@Id", new { Id = id }); } /// <summary> /// /// </summary> /// <param name="characterGuild"></param> public override void OnObjectAdded(CharacterGuildDAO characterGuild) { m_characterGuildById.Add(characterGuild.Id, characterGuild); } /// <summary> /// /// </summary> /// <param name="characterGuild"></param> public override void OnObjectRemoved(CharacterGuildDAO characterGuild) { m_characterGuildById.Remove(characterGuild.Id); } } }
Python
UTF-8
511
3.078125
3
[ "MIT" ]
permissive
#coding=utf8 __author__ = 'WangHaizhen' from w_1_1 import * def my_bin(num): num = int(num) L = [] if num == 0: return('0') else: while(num != 0): L.append(str(num%2)) num=num//2 return(''.join(L[::-1])) while True: s=input('Please enter string:') if IP(' '.join(s.split('.'))): L = map(my_bin, s.split('.')) print(type(L)) print('.'.join(L)) else: print('[Error]: Not an IP address.')
Java
UTF-8
1,075
2.75
3
[]
no_license
/** * Write a description of class Aplicacion here. * * @author (your name) * @version (a version number or a date) */ public class Aplicacion extends Producto { private Categoria categoria; private double pesoEnMB; private static final int DESCARGAS_PARA_SER_POPULAR = 2; private static final double PRECIO_INICIAL = 0.99; public Aplicacion(String identificador, double pesoEnMB, Categoria categoria) { super(identificador); this.categoria = categoria; this.pesoEnMB = pesoEnMB; } public double getTamanoEnMB() { return pesoEnMB; } public String getNombre() { return getIdentificador(); } public String getCategoria() { return categoria.getNombreCategoria(); } @Override public double getPrecio() { double precio = PRECIO_INICIAL; if (getNumeroVecesVendido() >= DESCARGAS_PARA_SER_POPULAR) { precio = categoria.getPrecioSiEsPopular(); } return precio; } }
Python
UTF-8
1,927
3.296875
3
[]
no_license
import pandas as pd df = pd.read_csv("stock_data.csv") print(df) #Removes header print("====") df = pd.read_csv("stock_data.csv", skiprows=1) print(df) #Removes header print("XXXX") df = pd.read_csv("stock_data.csv", header=1) print(df) #New column headers and also removes index df = pd.read_csv("stock_data.csv", header=None, names = ["ticker","eps","revenue","people"]) print(df) #Display just 2 rows df = pd.read_csv("stock_data.csv", nrows=2) print(df) #Identify NaN df = pd.read_csv("stock_data.csv", na_values=["n.a.", "not available"]) print(df) #Identify NaN per column df = pd.read_csv("stock_data.csv", na_values={ 'eps': ['not available'], 'revenue': [-1], 'people': ['not available','n.a.'] }) print(df) #Write to a file, no index df.to_csv("new.csv", index=False) #Write to a file, no header df.to_csv("new.csv",header=False) #Write to a file, just 2 columns df.to_csv("new.csv", columns=["tickers","price"], index=False) df = pd.read_excel("stock_data.xlsx","Sheet1") print(df) def convert_people_cell(cell): if cell=="n.a.": return 'Sam Walton' return cell def convert_price_cell(cell): if cell=="n.a.": return 50 return cell df = pd.read_excel("stock_data.xlsx","Sheet1", converters= { 'people': convert_people_cell, 'price': convert_price_cell }) print(df) df.to_excel("new.xlsx", sheet_name="stocks", index=False, startrow=2, startcol=1) df_stocks = pd.DataFrame({ 'tickers': ['GOOGL', 'WMT', 'MSFT'], 'price': [845, 65, 64 ], 'pe': [30.37, 14.26, 30.97], 'eps': [27.82, 4.61, 2.12] }) df_weather = pd.DataFrame({ 'day': ['1/1/2017','1/2/2017','1/3/2017'], 'temperature': [32,35,28], 'event': ['Rain', 'Sunny', 'Snow'] }) with pd.ExcelWriter('stocks_weather.xlsx') as writer: df_stocks.to_excel(writer, sheet_name="stocks") df_weather.to_excel(writer, sheet_name="weather")
Swift
UTF-8
5,438
2.734375
3
[]
no_license
// // PokemonDetailViewController.swift // Pokesearch // // Created by Nuno Silva on 31/12/2020. // import UIKit class PokemonDetailViewController: UIViewController { private let httpClient = HTTPClient() private var tableView: UITableView = { let table = UITableView(frame: .zero, style: .grouped) table.backgroundColor = .clear table.translatesAutoresizingMaskIntoConstraints = false return table }() let headerImage: UIImageView = { let imageview = UIImageView(image: UIImage(named: "pokemon")) imageview.contentMode = .scaleAspectFit imageview.translatesAutoresizingMaskIntoConstraints = false return imageview }() private var favoriteButton: UIButton = { let button = UIButton() button.setImage(UIImage(systemName: "heart"), for: .normal) button.addTarget(self, action: #selector(handleFavoritePokemon(sender:)), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() private let cellIdentifier = "elementosCell" var selectedPokemon:PokemonVM? override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) tableView.dataSource = self tableView.delegate = self tableView.alwaysBounceHorizontal = false setViews() // Do any additional setup after loading the view. } @objc func handleFavoritePokemon(sender:UIButton) { //Change heart button when touched if sender.tag == 0{ favoriteButton.setImage(UIImage(systemName: "heart.fill"), for: .normal) sender.tag = 1 //Post info httpClient.postFavoritePokemonJSON(pokemondata: selectedPokemon!) }else{ favoriteButton.setImage(UIImage(systemName: "heart"), for: .normal) sender.tag = 0 } } func setViews(){ view.backgroundColor = .systemGroupedBackground //navigationController?.navigationBar.alpha = 0 view.addSubview(tableView) tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 16).isActive = true tableView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true tableView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true } } extension PokemonDetailViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (selectedPokemon?.tableRepresentation.count)! } func numberOfSections(in tableView: UITableView) -> Int { //Retorna apenas o numero de codigos postais filtrados return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .value1, reuseIdentifier: cellIdentifier) cell.backgroundColor = .clear if let pokemonData = selectedPokemon?.tableRepresentation { let row = indexPath.row cell.textLabel!.text = pokemonData[row].title cell.detailTextLabel!.text = pokemonData[row].value } return cell } } extension PokemonDetailViewController: UITableViewDelegate{ func imageFromColor(color: UIColor, size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) var image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() UIGraphicsBeginImageContext(size) image?.draw(in: rect) image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.width/2)) headerView.addSubview(headerImage) headerView.addSubview(favoriteButton) headerImage.topAnchor.constraint(equalTo: headerView.topAnchor, constant: 60).isActive = true headerImage.bottomAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 0).isActive = true headerImage.leftAnchor.constraint(equalTo: headerView.leftAnchor, constant: 0).isActive = true headerImage.rightAnchor.constraint(equalTo: headerView.rightAnchor, constant: 0).isActive = true favoriteButton.topAnchor.constraint(equalTo: headerView.topAnchor, constant: 30).isActive = true favoriteButton.heightAnchor.constraint(equalToConstant: 50).isActive = true favoriteButton.rightAnchor.constraint(equalTo: headerView.rightAnchor, constant: -40).isActive = true return headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return view.frame.width/2 } }
Java
UTF-8
2,899
2.5
2
[]
no_license
package com.example.seekbarwidget; import android.media.AudioManager; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.view.KeyEvent; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import android.widget.SeekBar.OnSeekBarChangeListener; public class SeekbarActivity extends Activity { TextView textview; SeekBar seekbar; private AudioManager audioManager = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_seekbar); textview = (TextView)findViewById(R.id.textView); seekbar = (SeekBar)findViewById(R.id.seekBar1); initControls(); seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { //add here your implementation } @Override public void onStartTrackingTouch(SeekBar seekBar) { //add here your implementation } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0); textview.setText("Media Volume value = " + progress); } }); } private void initControls() { try { audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); seekbar.setMax(audioManager .getStreamMaxVolume(AudioManager.STREAM_MUSIC)); seekbar.setProgress(audioManager .getStreamVolume(AudioManager.STREAM_MUSIC)); } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI); //Raise the Volume Bar on the Screen seekbar.setProgress( audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) ); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: //Adjust the Volume audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI); //Lower the VOlume Bar on the Screen seekbar.setProgress(audioManager .getStreamVolume(AudioManager.STREAM_MUSIC) ); return true; default: return false; } } }
C++
UTF-8
2,309
2.90625
3
[]
no_license
//------------------------------------------------------------------------------ // // Contributors: // 1) Tommy Hinks // //------------------------------------------------------------------------------ #ifndef LAS_VARIABLE_LENGTH_RECORD_HPP_INCLUDED #define LAS_VARIABLE_LENGTH_RECORD_HPP_INCLUDED #include "las_variable_length_record_header.hpp" #include "las_ifstream.hpp" #include "las_ofstream.hpp" #include <vector> //------------------------------------------------------------------------------ namespace las { //------------------------------------------------------------------------------ class variable_length_record { public: const variable_length_record_header& header() const { return _header; } const std::string& data() const { return _data; } public: void read(ifstream &ifs) { ifs.stream().read(reinterpret_cast<char*>(&_header), sizeof(variable_length_record_header)); _data.resize(_header.record_length_after_header() - sizeof(variable_length_record_header) - 2); ifs.stream().read(reinterpret_cast<char*>(&_data[0]), _data.size()); } void write(ofstream &ofs) { ofs.stream().write(reinterpret_cast<const char*>(&_header), sizeof(variable_length_record_header)); ofs.stream().write(reinterpret_cast<const char*>(&_data[0]), _data.size()); } private: // Member variables. variable_length_record_header _header; std::string _data; }; //------------------------------------------------------------------------------ } // Namespace: las. //------------------------------------------------------------------------------ namespace std { template<class CharT, class Traits> basic_ostream<CharT,Traits>& operator<<(basic_ostream<CharT,Traits> &os, const las::variable_length_record &rhs) { os << "las::variable_length_record[0x" << &rhs << "]\n" << rhs.header() << "Data : '" << rhs.data() << "'\n"; return os; } } // Namespace: std. #endif // LAS_VARIABLE_LENGTH_RECORD_HPP_INCLUDED
Java
UTF-8
161
1.507813
2
[ "BSD-3-Clause" ]
permissive
@Test public void override() throws Exception { assertThat(this.dependencies.find("org.sample","sample02").toString(),equalTo("org.sample:sample02:2.0.0")); }
Python
UTF-8
250
3.25
3
[]
no_license
def canVisitAllRooms(rooms): visited = set() stack = [0] while stack: r = stack.pop() visited.add(r) for x in rooms[r]: if x not in visited: stack.append(x) return len(visited) == len(rooms) print(canVisitAllRooms([[1],[2],[3],[]]))
JavaScript
UTF-8
858
2.765625
3
[ "MIT" ]
permissive
function lockedProfile() { let buttons = document.querySelectorAll('.profile > button'); let buttonsArray = Array.from(buttons); buttonsArray.forEach(btn => { btn.addEventListener('click', function () { let lockInput = this.parentNode.querySelector('input[value="lock"]'); let unlockInput = this.parentNode.querySelector('input[value="unlock"]'); let div = this.parentNode.querySelector('div'); if (!lockInput.checked) { if (this.textContent.toLowerCase() === 'show more'.toLocaleLowerCase()) { this.textContent = 'Hide it'; div.style.display = 'block'; } else { this.textContent = 'Show more'; div.style.display = 'none'; } } }); }); }
JavaScript
UTF-8
1,921
3.015625
3
[]
no_license
function calcDistance(origin, destination, outputDest) { var x, y; origin = origin.split(';'); x = parseFloat(origin[0]); y = parseFloat(origin[1]); var service = new google.maps.DistanceMatrixService(); origin = new google.maps.LatLng(x, y); service.getDistanceMatrix( { origins: [origin], destinations: [destination], travelMode: google.maps.TravelMode.DRIVING, avoidHighways: false, avoidTolls: false }, callback ); function callback(response, status) { if (status == "OK" && response.rows[0].elements[0].distance != null) { outputDest.innerHTML = response.rows[0].elements[0].distance.text; } } } function calcDuration(origin, destination, outputTime) { var x, y; origin = origin.split(';'); x = parseFloat(origin[0]); y = parseFloat(origin[1]); var service = new google.maps.DistanceMatrixService(); origin = new google.maps.LatLng(x, y); service.getDistanceMatrix( { origins: [origin], destinations: [destination], travelMode: google.maps.TravelMode.DRIVING, avoidHighways: false, avoidTolls: false }, callback ); function callback(response, status) { if (status == "OK") { outputTime.html(response.rows[0].elements[0].duration.text); } else { alert("Error: " + status); } } } $(function () { $(".distances li .badge ").each(function () { calcDistance($(this).attr("data-coords"), $('#address .text').text(), this); }); calcDuration($(".distances li.active .badge").attr("data-coords"), $('#address .text').text(), $(".duration")); }); $(document).load(function () { $('#restaurants').change(); })
Python
UTF-8
264
4.125
4
[]
no_license
"""Ejercicio 1 Escribe un programa en Python que almacene la cadena ¡Hola Mundo! en una variable y luego muestre por pantalla el contenido de la variable.""" variable = "hola mundo" print(variable) variable = "1234" print(variable) variable2 = "10.4" print(variable2)
Python
UTF-8
11,979
2.59375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python """ Various utility code that gets used throughout the command-line tools. Recent changes - Moved scipy and numpy imports into relevant functions so that other python builds (e.g. PyMOL) can easily use this. """ import os,sys,bz2 from copy import copy from optparse import Option, OptionValueError usage = """usage: %prog [options] Please make sure that you have created the following directories: output-dir output-dir/structure-name output-dir/images """ ############################ # # New Optparse option types # ############################ # Define a new option type, a comma-separated list of integers. def check_zerobasedintlist(option,opt,value): """ This automatically converts one-based indices to zero-based indices. If you don't want that, make sure to convert back yourself!! It also knows about all of our lists of residues. """ # # NOTE: if you want residues 9-24, give # range(8,24) because we're zero-indexed. # standard_residue_lists = { # Loops 'dhfr_fg':list(range(115,132)), 'dhfr_cd':list(range(63,71)), 'dhfr_m20':list(range(8,24)), 'dhfr_gh':list(range(141,150)), 'dhfr_subdomain1':list(range(37)) + list(range(106,159)), 'dhfr_subdomain2':list(range(38,106)), # Beta strands 'dhfr_BA':[i-1 for i in range( 2, 5+1)], 'dhfr_BB':[i-1 for i in range( 39, 43+1)], # 'dhfr_BC':[i-1 for i in range( 58, 62+1)], # 'dhfr_BD':[i-1 for i in range( 73, 75+1)], # 'dhfr_BE':[i-1 for i in range( 91, 95+1)], 'dhfr_BF':[i-1 for i in range(107,115+1)], 'dhfr_BG':[i-1 for i in range(133,135+1)], 'dhfr_BH':[i-1 for i in range(151,158+1)], # Alpha helices 'dhfr_AB':[i-1 for i in range( 25, 35+1)], 'dhfr_AC':[i-1 for i in range( 44, 50+1)], # 'dhfr_AE':[i-1 for i in range( 78, 85+1)], # 'dhfr_AF':[i-1 for i in range( 97,106+1)], # Networks 'dhfr_AgarwalJPhysChemBNetwork':[i-1 for i in (7,14,15,27,28,31,40,41,43,44,46,47,54,61,62,63,100,113,122)], 'dhfr_WatneyHammes-SchifferJPhysChemBNetwork_shared':[i-1 for i in (28,42,44,50,51,52,53,64,77,90)], 'dhfr_WatneyHammes-SchifferJPhysChemBNetwork_ecolionly':[i-1 for i in (19,20,45,47,61,62,63,67,68,72,74,98,99,102,108,129,149,155)], # Mutants 'dhfr_rb_catcorr_mutants':[i-1 for i in (9,44,45,46,54,121,122)], 'dhfr_rb_catnoncorr_mutants':[i-1 for i in (28,31,100,113)], 'dhfr_rb_noncatnoncorr_mutants':[i-1 for i in (85,88,137,145,152,153,155)], 'dhfr_rb_noncatcorr_mutants':[i-1 for i in (49,67,14,22)], # Other DHFR 'dhfr_allosteric_site':[i-1 for i in ( 26, 29,30, 33, 111, 137,139,141,153, 155)], 'dhfr_moe_allosteric_exposed':[i-1 for i in ( 26, 29,30, 33, 137,139,141,153, 155)], 'dhfr_moe_allosteric_tunnel': [i-1 for i in (5,6,7, 27, 30,31, 34,111,112,113, 153,154)], 'dhfr_allosteric_everything': [i-1 for i in (5,6,7,26,27,29,30,31,33,34,111,112,113,137,139,141,153,154,155)], 'dhfr_allosteric_nonexposed': [i-1 for i in (5,6,7, 27, 31, 34, 112,113, 154)], 'dhfr_mtx_contact':[i-1 for i in (5,6,27,31,32,52,57,94,100,160)], 'dhfr_bulge_mutants':[i-1 for i in (137,153,155)], # BACE 'bace_ticks':[i-1 for i in range(4,389,10)], } standard_residue_lists['dhfr_watney_network'] = standard_residue_lists['dhfr_WatneyHammes-SchifferJPhysChemBNetwork_shared'] + standard_residue_lists['dhfr_WatneyHammes-SchifferJPhysChemBNetwork_ecolionly'] + [159,] standard_residue_lists['dhfr_networks'] = standard_residue_lists['dhfr_AgarwalJPhysChemBNetwork'] + standard_residue_lists['dhfr_watney_network'] standard_residue_lists['dhfr_loops'] = standard_residue_lists['dhfr_m20'] + standard_residue_lists['dhfr_gh'] + standard_residue_lists['dhfr_fg'] + standard_residue_lists['dhfr_cd'] standard_residue_lists['dhfr_helices'] = [] for i in 'AB AC AE AF'.split(): standard_residue_lists['dhfr_helices'].extend(standard_residue_lists['dhfr_'+i]) standard_residue_lists['dhfr_rigid_d1'] = [] for i in 'BB BC BD BE AC AE AF'.split(): standard_residue_lists['dhfr_rigid_d1'].extend(standard_residue_lists['dhfr_'+i]) def parse_one_list(value): result = [] for k in value.strip().split(','): if k in standard_residue_lists: result += standard_residue_lists[k] else: if '-' in k: start,stop = k.split('-') result.extend(list(range(int(start)-1,int(stop)))) else: result.append(int(k)-1) result = sorted(list(set(result))) print("Caring about",len(result),"residues",[i+1 for i in result]) return result try: if ':' in value: left,right = value.split(':') return [parse_one_list(left),parse_one_list(right)] else: return parse_one_list(value) except ValueError: raise OptionValueError( "option %s is neither a known range of residues or a valid list of integers: %s"%(opt,value)) # Define a new option type, a 1-based list of integers. Just use # the guts of the zero-based stuff and add one. def check_onebasedintlist(option,opt,value): result = check_zerobasedintlist(option,opt,value) return [i+1 for i in result] # Define a new option type, a comma-separated list of strings. def check_strlist(option,opt,value): try: return [i for i in value.strip().split(',')] except ValueError: raise OptionValueError( "option %s: invalid list of strings: %s"%(opt,value)) class MyOption(Option): TYPES=Option.TYPES + ("zerobasedintlist","onebasedintlist","strlist",) TYPE_CHECKER=copy(Option.TYPE_CHECKER) TYPE_CHECKER["zerobasedintlist"] = check_zerobasedintlist TYPE_CHECKER["onebasedintlist"] = check_onebasedintlist TYPE_CHECKER["strlist"] = check_strlist ####################################### # # Adding options to the Optparse parser # ####################################### def add_window_options(parser): parser.add_option("--start",dest="start",default=500,type="int", help="Time, in ps, to start the windows. [default: %default]") parser.add_option("--stop",dest="stop",default=10500,type="int", help="Time, in ps, to stop the windows. [default: %default]") parser.add_option("--window-size",dest="windowsize",default=1000,type="int", help="Length, in ps, of window size. [default: %default]") parser.add_option("--window-spacing",dest="windowspacing",default=100,type="int", help="Spacing between windows, in ps. [default: %default]") def add_standard_options(parser): parser.add_option("--structure-name",dest="structurename", default="1rx1", help="Name of your structure. E.g. 1RX1 or 1SGZ. [default: %default]") parser.add_option("--output-dir",dest="outputdir", default="ptraj_files/", help="Directory where we will put our results. This should be the same as the directory where we put our ptraj files before, and it should contain the .dat files that ptraj outputs. [default: %default] The images will go to <outputdir>/images and the html file will be in <outputdir>") ####################################### # # Parsing standard options # ####################################### def get_desired(options): starts = list(range(options.start,options.stop-options.windowsize+1,options.windowspacing)) stops = list(range(options.start+options.windowsize,options.stop+1,options.windowspacing)) names = [(starts[i] + options.windowsize/2.0)/1000.0 for i in range(len(starts))] # names is the centers of the windows. start + windowsize/2 converted to NS. desired = [('%sps'%i,'%sps'%j,'NS%05.2f'%k) for (i,j,k) in zip(starts,stops,names)] return desired ####################################### # # Running external programs # ####################################### def run(prog,args,verbose=True): ''' wrapper to handle spaces on windows. prog is the full path to the program. args is a string that we will split up for you. or a tuple. or a list. your call. return value is (retval,prog_out) e.g. (retval,prog_out) = run("/bin/ls","-al /tmp/myusername") ''' try: import subprocess,tempfile if isinstance(args, type('')): args = tuple(args.split()) elif type(args) in (type([]),type(())): args = tuple(args) if os.name in 'nt dos'.split(): # turns out not to be necessary with subprocess #prog = r'"%s"'%prog pass args = (prog,) + args output_file = tempfile.TemporaryFile(mode="w+") if verbose: print("Running",args) retcode = subprocess.call(args,stdout=output_file.fileno(),stderr=subprocess.STDOUT) output_file.seek(0) prog_out = output_file.read() output_file.close() #windows doesn't do this automatically if verbose: print("Results were:") print("Return value:",retcode) print("Output:") print(prog_out) return (retcode,prog_out) except ImportError: # probably python <= 2.4 if not isinstance(args, type('')): args = ' '.join(args) cmd = prog + ' ' + args if verbose: print("Running",cmd) retcode = os.system(cmd) # cannot return prog_out via os.system if verbose: print("Results were:") print("Return value:",retcode) print("Output:") print("\tcould not find subprocess module, so no output reported") return (retcode,'') def read_data(fname): """ Given a filename, try to read in data, paying attention to whatever format it's in. We'll try the following in order - .numpy We assume this is a square numpy array, made with array.tofile() - .dat A .dat file from ptraj. This can be read in with scipy.io.read_array() """ import numpy as np data = None sys.stdout.write("reading "+fname+" ") sys.stdout.flush() if os.path.isfile(fname+'.numpy'): sys.stdout.write("as numpy\n") sys.stdout.flush() f = open(fname+'.numpy') data = np.fromstring(f.read()) f.close() one_side = int(np.sqrt(len(data))) if abs(len(data) - one_side*one_side) >= 0.1: message = "Only square matrices are supported. %s has len %s."%(fname,one_side) sys.stdout.write(message) return None data.shape = one_side,one_side elif os.path.isfile(fname+'.numpy.bz2'): sys.stdout.write("as numpy.bz2\n") sys.stdout.flush() bf = bz2.BZ2File(fname+'.numpy.bz2') data = np.fromstring(bf.read()) bf.close() one_side = int(np.sqrt(len(data))) if abs(len(data) - one_side*one_side) >= 0.1: message = "Only square matrices are supported. %s has len %s."%(fname,one_side) sys.stdout.write(message) return None data.shape = one_side,one_side elif os.path.isfile(fname): sys.stdout.write("as dat\n") sys.stdout.flush() data = np.loadtxt(open(fname)) elif os.path.isfile(fname+'.bz2'): sys.stdout.write("as dat.bz2\n") sys.stdout.flush() data = np.loadtxt(bz2.BZ2File(fname+'.bz2')) else: sys.stdout.write("COULD NOT FIND (1)%s\n"%fname) return data
Markdown
UTF-8
1,943
2.515625
3
[]
no_license
```yaml area: Hertfordshire og: description: "Officers investigating a theft from a shop in Bishop\u2019s Stortford have released an image of a man they would like to speak to as part of their enquiries." publish: date: 9 May 2018 title: "CCTV appeal following theft from shop \u2013 Bishop\u2019s Stortford" url: https://www.herts.police.uk/news-and-appeals/CCTV-appeal-following-theft-from-shop-Bishops-stortford-0189A ``` * ### Do you recognise this man? Police would like to speak to him as part of their enquiries into a theft in Bishop's Stortford. * ### It happened at the Three mobile phone shop in Potter Street between 1pm and 1.25pm on Monday, April 30. * ### If you know the person pictured, please call 101 quoting crime reference A2/18/801. Officers investigating a theft from a shop in Bishop's Stortford have released an image of a man they would like to speak to as part of their enquiries. It happened at the Three mobile phone shop in Potter Street between 1pm and 1.25pm on Monday, April 30. A member of staff was discussing a phone with the offender and while preparing to sell it, left the phone and the box on the counter. The offender took both the phone - an iPhone 8 Plus - and the box before leaving the store without making any attempt to pay. PCSO Tea Prow, from the Bishop's Stortford and Sawbridgeworth Safer Neighbourhood Team, said: "Do you recognise this man? We believe he may have information that could help further progress our investigation. "If you know him, or have any further information that could assist the investigation, please email, report information online or call 101, quoting crime reference number A2/18/801." Alternatively you can contact the independent crime-fighting charity Crimestoppers anonymously on 0800 555 111 or through their Anonymous Online Form. No personal details are taken, information cannot be traced or recorded and you will never need to go to court.
Markdown
UTF-8
396
2.953125
3
[]
no_license
# LinearRegression_2_VS2019 Learnt to handle '.csv' file. Automated certain processes. This linear regression predicts salary based on the experience of the employee. The function used for curve fitting is salary = a0 + a1*experience + a2*experience*experience + a3*experience*experience*experience. The program takes experience as an input and gives salary and regression coefficient as output.
Java
UTF-8
3,105
1.851563
2
[]
no_license
package fr.k2i.adbeback.webapp.controller; import com.google.common.collect.Lists; import fr.k2i.adbeback.dao.ICategoryDao; import fr.k2i.adbeback.webapp.bean.CartBean; import fr.k2i.adbeback.webapp.bean.search.ArtistBean; import fr.k2i.adbeback.webapp.bean.search.MusicBean; import fr.k2i.adbeback.webapp.bean.search.ProductorBean; import fr.k2i.adbeback.webapp.bean.search.SearchCommand; import fr.k2i.adbeback.webapp.facade.MediaFacade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * Created with IntelliJ IDEA. * User: dimitri * Date: 29/10/13 * Time: 13:25 * To change this template use File | Settings | File Templates. */ @Controller public class CatalogController{ @Autowired private MediaFacade mediaFacade; @Autowired private ICategoryDao categoryDao; @Value("${addonf.facebook.api}") private String fbApiKey; @RequestMapping("/catalog.html") public String catalog(Map<String, Object> model,HttpServletRequest request) throws Exception { return "catalog"; } @RequestMapping("/artistPage.html") public String artist(@RequestParam Long artistId, @ModelAttribute("search")SearchCommand searchCommand,Pageable pageable,Map<String, Object> model,HttpServletRequest request) throws Exception { ArtistBean artistBean = mediaFacade.getArtistById(artistId); model.put("nbMusic", mediaFacade.countMusicForArtist(artistId)); model.put("last5", mediaFacade.last5MusicForArtist(artistId)); model.put("top10", mediaFacade.top10MusicForArtist(artistId)); model.put("showmore",false); model.put("musics",mediaFacade.findMusicsForArtist(artistId, searchCommand.getReq(), pageable)); model.put("artist", artistBean); model.put("FBApiKey",fbApiKey); return "artist"; } @RequestMapping("/majorPage.html") public String label(@RequestParam Long majorId, @ModelAttribute("search")SearchCommand searchCommand,Pageable pageable,Map<String, Object> model,HttpServletRequest request) throws Exception { ProductorBean productorBean = mediaFacade.getProductorById(majorId); model.put("nbArtist", mediaFacade.countArtistForLabel(majorId)); model.put("last10", mediaFacade.last10MusicForLabel(majorId)); model.put("showmore",false); model.put("categories",categoryDao.getAll()); model.put("musics",mediaFacade.findMusicsForLabel(majorId,searchCommand.getGenreId(), searchCommand.getReq(), pageable)); model.put("label", productorBean); return "label"; } }
C
UTF-8
748
2.921875
3
[ "MIT" ]
permissive
#include <MLV/MLV_all.h> #include <stdio.h> int main( int argc, char *argv[] ){ int l, h, p, r, dim; printf("Largeur:"); scanf("%d",&l); printf("Hauteur:"); scanf("%d",&h); printf("Rayon du cercle:"); scanf("%d",&r); printf("Pas:"); scanf("%d",&p); MLV_create_window( "beginner - 1 - hello world", "hello world", l, h ); if (l<h){ dim = l; } else { dim = h; } while (r <= (dim/2)){ MLV_draw_filled_circle(l/2,h/2,r,MLV_COLOR_BLUE); MLV_actualise_window(); MLV_wait_seconds(3); r = r+p; } /* Met a jour l'affichage.*/ MLV_actualise_window(); /* Attend 10 secondes avant la fin du programme.*/ MLV_wait_seconds( 10 ); /* Ferme la fenêtre*/ MLV_free_window(); return 0; }
JavaScript
UTF-8
1,565
3.09375
3
[]
no_license
function pass_check() { pass_str = $("#password").val(); if (pass_str.length < 8) { $("#length_error").html("Пароль должен быть не короче 8 символов"); document.getElementById("form_btn").disabled = true; } else { document.getElementById("form_btn").disabled = false; $("#length_error").html(""); } if (pass_str.search(/.*[\d].*/) != -1) { $("#num_error").html(""); document.getElementById("form_btn").disabled = false; } else { $("#num_error").html("Пароль должен содержать хотя бы одну цифру"); document.getElementById("form_btn").disabled = true; } if (pass_str.search(/.*[A-ZА-Я].*/) != -1) { document.getElementById("form_btn").disabled = false; $("#letter_error").html("") } else { $("#letter_error").html("Пароль должен содержать хотя бы одну заглавную букву") document.getElementById("form_btn").disabled = true; } } function email_check() { email_str = $("#email").val(); if ((email_str.search(/.*@.*/) != -1) || (email_str.search(/^(\s*)?(\+)?([- _():=+]?\d[- _():=+]?){10,14}(\s*)?$/) != -1)) { $("#email_error").html(""); document.getElementById("form_btn").disabled = false; } else { $("#email_error").html("Введите валидный email или номер телефона"); document.getElementById("form_btn").disabled = true; } }
Java
UTF-8
1,522
1.976563
2
[]
no_license
/** * 2018-10-15 * Administrator */ package com.axp.service.goods; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.axp.model.AdminUser; import com.axp.model.GameActivity; import com.axp.query.PageResult; /** * @author da * @data 2018-10-15下午5:21:49 */ public interface GameActivityService { /** * 查询所有游戏活动列表 * @param currentPage * @param pageSize * @param searchWord * @return */ PageResult<GameActivity> getAvtivityForList(Integer currentPage,Integer pageSize, String searchWord); /** * 保存翻牌商品 * @param request * @param response * @return */ Map<String, Object> saveDrawinfo( List<String> content,HttpServletRequest request, HttpServletResponse response); /** * 查询某条数据 * @param id * @return */ GameActivity findById(Integer id); /** * 查询代理下的游戏信息 * @param adminUser * @param request * @param currentPage */ void getGameList(AdminUser adminUser, HttpServletRequest request, Integer currentPage); /** * 保存签到奖品 * @param request * @param response * @param content * @param coverPics */ void saveSignInfo(HttpServletRequest request, HttpServletResponse response, List<String> coverPics, List<String> content); /** * 删除某条记录 * @param id */ int delSign(Integer id); }
Python
UTF-8
4,159
2.765625
3
[]
no_license
import tensorflow as tf import keras import pickle import argparse import random import numpy as np from pool import Pool parser = argparse.ArgumentParser() parser.add_argument("-gen", "--generate", help="Generate Workers") parser.add_argument("-sav", "--save", help="Save Directory") parser.add_argument("-rt", "--retrain", help="Retrain Models") parser.add_argument("-plt", "--plot", help="Plot Graphs") parser.add_argument("-eval", "--evaluate", help="Test Pool Models") parser.add_argument("-sim", "--simulate", help="Simulate Activity Models") pool_names = ["Vanguard", "Chase", "Barclay", "Deutsche"] pools = [] tags = ["EOD/DIS", "EOD/HD", "EOD/MSFT", "EOD/BA", "EOD/MMM", "EOD/PFE", "EOD/NKE", "EOD/JNJ", "EOD/MCD", "EOD/INTC", "EOD/V", "EOD/IBM", "EOD/GE", "EOD/KO", "EOD/WMT", "EOD/AAPL"] def main(): global pools args = parser.parse_args() # Generate pools and workers to_train = [] if args.generate == "yes": print("[Pool GEN] Generating pools...") for name in pool_names: pools.append(Pool(name)) print("[Pool GEN] %d pools generated" % (len(pools))) for pool in pools: pool.generate_population() else: print("[Pool LOAD] Loading pools...") with open(args.save,'rb') as f: pools = pickle.load(f) print("[Pool LOAD] %d pools loaded" % (len(pools))) for pool in pools: if not pool.load_model(): to_train.append(pool.pool_name) if args.retrain == "yes": to_train = pool_names print("[Pool TRAIN] Training %d unloaded models" % (len(to_train))) random.shuffle(to_train) for training_pool in to_train: pool = pools[pool_names.index(training_pool)] print("[Pool %s] Train start with diff activation of %d" % (pool.pool_name, pool.diff_activation)) random.shuffle(tags) for tag in tags: print("[Pool %s] Fit on tag %s" % (pool.pool_name, tag)) pool.train(tag) pool.save_model() print("[Pool TRAIN] Unloaded model train finished") if args.evaluate == "yes": print("[Pool EVAL] Evaluating models") for pool in pools: for tag in tags: predict = pool.predict(tag, True) correct = 0 incorrect = 0 total_difference = 0 for i, prediction_X in enumerate(predict[1]): actual_X = predict[0][i] prediction = prediction_X[-1] actual = actual_X[-1] difference = abs(prediction-actual) total_difference += difference previous = actual_X[-2] change = "" if actual > previous: change = "inc" elif actual < previous: change = "dec" else: change = "eq" predicted_change = "" if prediction > previous: predicted_change = "inc" elif prediction < previous: predicted_change = "dec" else: predicted_change = "eq" if change == predicted_change: correct += 1 else: incorrect += 1 print("[Pool EVAL] Pool model %s had %d correct and %d incorrect change predictions, total difference of %f" % (pool.pool_name, correct, incorrect, total_difference)) if args.simulate == "yes": print("[Pool SIM] Starting simulations") for tag in tags: print("[Pool SIM] Starting simulation on tag %s" % tag) for pool in pools: pool.simulate(tag) for pool in pools: total_profit = pool.get_total_profit() print("[Pool SIM] Pool %s has made total profits of %f" % (pool.pool_name, total_profit)) if __name__ == "__main__": main()
C#
UTF-8
1,569
2.640625
3
[]
no_license
using Modelos; using Repositorio; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Logica { public class CiudadLogica { private CiudadRepositorio repositorio = new CiudadRepositorio(); public List<CiudadModel> GetListadoCiudades() { try { return repositorio.GetListadoCiudades(); } catch (Exception e) { return new List<CiudadModel>(); } } public CiudadModel GetCiudad(int id) { try { return repositorio.GetCiudad(id); } catch (Exception e) { return null; } } public void CreateCiudad(CiudadModel ciudad) { try { repositorio.CreateCiudad(ciudad); } catch (Exception e) { return; } } public void UpdateCiudad(int id, CiudadModel ciudad) { try { repositorio.UpdateCiudad(id, ciudad); } catch (Exception e) { return; } } public void DeleteCiudad(int id) { try { repositorio.DeleteCiudad(id); } catch (Exception) { return; } } } }
C++
UTF-8
350
3.0625
3
[ "MIT" ]
permissive
#include "Stack.H" #include <iostream> using namespace std; void Stack::push(T a) { if(stk.empty()) { top = a; } stk.push_back(a); } void Stack::pop_back() { stk.pop_back(); if(stk.empty()) { top = ""; } } int Stack::size() { return stk.size(); } bool Stack::empty() { return stk.empty(); }
Java
UTF-8
640
2.203125
2
[ "MIT" ]
permissive
package jv.freeorm.query; import jv.freeorm.base.DbParameter; /** * * @author Mustafa SACLI */ public class Query implements IQuery { private String text_ = ""; private DbParameter[] prms_ = null; public Query() { text_ = ""; prms_ = new DbParameter[]{}; } @Override public String getText() { return text_; } @Override public void setText(String text) { text_ = text; } @Override public DbParameter[] getParameters() { return prms_; } @Override public void setParameters(DbParameter[] parameters) { prms_ = parameters; } }
PHP
UTF-8
4,224
2.625
3
[ "MIT" ]
permissive
<?php declare(strict_types = 1); namespace XpBar\Sniffs\Namespaces; use PHP_CodeSniffer\Files\File as PHP_CodeSniffer_File; use PHP_CodeSniffer\Sniffs\Sniff as PHP_CodeSniffer_Sniff; use SlevomatCodingStandard\Helpers\ClassHelper; use SlevomatCodingStandard\Helpers\NamespaceHelper; use SlevomatCodingStandard\Helpers\ReferencedName; use SlevomatCodingStandard\Helpers\ReferencedNameHelper; use SlevomatCodingStandard\Helpers\TokenHelper; use SlevomatCodingStandard\Helpers\UseStatement; use SlevomatCodingStandard\Helpers\UseStatementHelper; use XpBar\Helpers\Errors; use XpBar\Helpers\Warnings; /** * Lints Doc blocks, function arguments and return types to make sure they match */ class MissingImportSniff implements PHP_CodeSniffer_Sniff { use Warnings, Errors; /** * Register the tokens to parse in the file for these rules. * * @return array */ public function register(): array { return array( T_OPEN_TAG ); } /** * Processes this test, when one of its tokens is encountered. * * @param PHP_CodeSniffer_File $phpcsFile The current file being processed. * @param int $stackPtr The position of the current token * in the stack passed in $tokens. * @return void */ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr): void { $imports = UseStatementHelper::getUseStatements($phpcsFile, $stackPtr); $referencedNames = ReferencedNameHelper::getAllReferencedNames($phpcsFile, $stackPtr); $missingImports = []; foreach ($referencedNames as $referencedName) { $name = $referencedName->getNameAsReferencedInFile(); if ($name == null) { continue; } $nameParts = NamespaceHelper::getNameParts($name); $nameAsReferencedInFile = $nameParts[0]; $nameReferencedWithoutSubNamespace = count($nameParts) === 1; $uniqueId = $nameReferencedWithoutSubNamespace ? UseStatement::getUniqueId($referencedName->getType(), $nameAsReferencedInFile) : UseStatement::getUniqueId(ReferencedName::TYPE_DEFAULT, $nameAsReferencedInFile); if (NamespaceHelper::isFullyQualifiedName($name)) { continue; } if (isset($imports[$uniqueId])) { continue; } $missingImports[] = $referencedName; } $classPtr = TokenHelper::findNext($phpcsFile, [T_CLASS], $stackPtr); if ($classPtr == false || $classPtr == null) { return; } $className = ClassHelper::getName($phpcsFile, $classPtr); $files = $this->getClassFileNames($phpcsFile); foreach ($missingImports as $reference) { $name = $reference->getNameAsReferencedInFile(); $checkedTypes = ['default']; if (in_array($reference->getType(), $checkedTypes) && !in_array($name, $files) && $name != $className) { $message = "Missing Import for ".$name.", it's not in this directory!"; $phpcsFile->addWarning( $message, $reference->getEndPointer(), "XpBar.Namespaces.MissingImport", [], 6 ); } } }//end process() /** * Parse the current directory so we can compare the filenames against the missing import classes * * @param PHP_CodeSniffer_File $phpcsFile * @return array */ private function getClassFilenames(PHP_CodeSniffer_File $phpcsFile): array { $currentDirectory = dirname($phpcsFile->path); $directory = opendir($currentDirectory); $files = []; while (($item = readdir($directory)) != false) { if ($item == "." || $item == ".." || is_dir($item)) { continue; } preg_match('/^[A-Z].*(?=\.php$)/', $item, $matches); if (count($matches) > 0) { $files[] = $matches[0]; } } return $files; } }//end class
Java
UTF-8
377
1.898438
2
[]
no_license
package sa.com.saib.web.dgi.repository; import sa.com.saib.web.dgi.domain.KycPersonal; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data repository for the KycPersonal entity. */ @SuppressWarnings("unused") @Repository public interface KycPersonalRepository extends JpaRepository<KycPersonal, Long> { }
TypeScript
UTF-8
8,359
3.421875
3
[ "MIT" ]
permissive
const naturalAminoAcids = 'ARNDCEQGHILKMFPSTWYV'; const ambiguousAminoAcids = 'XBZJ'; const baseNucleicAcids = 'ACGTU'; const ambiguousNucleicAcids = 'WSMKRYBDHVNZ'; // Characters unique only to their subset e.g. 'U' is not a valid AA. const aminoAcidsOnly = /[EQILFPXJ]/gi; const nucleicAcidsOnly = /U/gi; export const validAminoAcids = [ naturalAminoAcids, ambiguousAminoAcids, '*', // Stop '.-', // Gaps ].join(''); export const validNucleicAcids = [ baseNucleicAcids, ambiguousNucleicAcids, // No gaps e.g. - and . are not allowed ].join(''); export const errorResponses = Object.freeze({ missingSequence: Object.freeze({ valid: false, message: 'The sequence is missing', }), invalidSequence: Object.freeze({ valid: false, message: 'The sequence is invalid', }), shortSequence: Object.freeze({ valid: false, message: 'The sequence is too short', }), }); export const validResponse = Object.freeze({ valid: true }); // Keep start ^ and end $ anchors in the regex // Matches all alphabet letters, except for the letter O (case-insensitive) // Accepts * . - const validCharacters = /^[A-NP-Z*.-]+$/i; const validCharactersUnderStrictMode = new RegExp( `^[${naturalAminoAcids}*.-]+$`, 'i' ); /** * Very basic check on if a string is likely to be a FASTA-formatted string * * @param {string} seq - Sequence * @return {Boolean} True if it is likely to be FASTA */ const isFASTA = (seq: string) => /.*[>;]+/gm.test(seq); /** * Prepares a string to be digested by the core validation function. * * @param {string} fasta - A FASTA-formatted string * @return {Array<string>} An array of clean sequences */ function prepareFASTAString(fasta: string) { return fasta .split(/^[>;].*\n?$/gm) // split and remove the 'Description' line .map((s) => s.replace(/\s/g, '')) // remove all of the white-space .filter(Boolean); // remove all non-truthy values e.g. null, '', false. } /* * Accepts a sequence of characters and makes a guess if * the sequence is an AA or NA sequence. * Note: This function will always return a guess. * Note: The argument 'threshold' is the frequency of nucliec-acid * bases that has to be repeated in the sequence in order to consider * it a NA sequence. This is a percentage value, represented in * values from 1 to 100. * e.g. with 'threshold' set to 90 * sample sequence: AAAAAZZZZZ -> AA * sample sequence: AAAAAAAAAZ -> NA * * @param {string} sequence - A sequence * @param {Number} threshold - NA threshold from 1 to 100 * @return {string} The likely type either 'aa' or 'na' */ function guessSequenceType(sequence: string, threshold: number) { const typeAA = 'aa'; const typeNA = 'na'; // Check for nucleic-acid only characters if (nucleicAcidsOnly.test(sequence)) { // Make sure it does NOT contain any amino-acid only characters if (!aminoAcidsOnly.test(sequence)) { return typeNA; } } // Check for amino-acid only characters if (aminoAcidsOnly.test(sequence)) { // Make sure it does NOT contain any nucleic-acid only characters if (!nucleicAcidsOnly.test(sequence)) { return typeAA; } } // Counting the characters to determine the percentage of // total occurances of members of each type const counts: Record<string, number> = {}; for (let index = 0; index < sequence.length; index += 1) { const char = sequence.charAt(index); if (!counts[char]) { counts[char] = 1; } else { counts[char] += 1; } } // Keeping track of each individual character's percentage in the // whole sequence, gives flexibility if further logic needs to be // utilised in the future. const percentagePerChar = 100 / sequence.length; const percentages = Object.keys(counts).reduce( (acc, current) => { if (naturalAminoAcids.includes(current)) { acc.aa += counts[current] * percentagePerChar; } if (baseNucleicAcids.includes(current)) { acc.na += counts[current] * percentagePerChar; } return acc; }, { aa: 0, // Amino-Acids na: 0, // Nucleic-Acids } ); // Is this above our arbitrary threshold? if (percentages.na > threshold) { return typeNA; } // If you have reached here and it is not NA, then our guess // would be AA. return typeAA; } /* * Does some ground work before passing the sequence to the * 'guess' function. * * @param {string} sequence - A sequence * @return {string} The likely type either 'aa' or 'na' */ export function findLikelyType(sequence: string) { // 1. Remove all of the non-letter characters, plus N and X // 2. If less than 11 usable characters left: unable to guess // 3. If more than (by default) 90% ACGTU: Nucleic-Acids // 4. Else: Amino-Acids // Note: Removing N and X is fine because 'N' is valid for both AA and NA sequences, // therefore, removing it should equally reduce the sequence length, regardless of the // type of sequence. 'X' can be safely removed since it only exists in AA sequences // and not a valid character in NA sequences. const cleanUpRegEx = /[^A-Z]|[NX]/gi; const cleanSequence = sequence.replace(cleanUpRegEx, '').toUpperCase(); const nucleicAcidBaseThreshold = 90; return guessSequenceType(cleanSequence, nucleicAcidBaseThreshold); } /** * Core internal validation function for a single sequence * * @param {string} sequence - A sequence * @return {object} The result */ export function sequenceValidator( sequence: string, minimumLength?: number, strict?: boolean ) { // Sequence was not passed at all if (!sequence) { return errorResponses.missingSequence; } // Remove all white-spaces and FASTA bits let cleanSequence: string | undefined; if (isFASTA(sequence)) { const cleanSequences = prepareFASTAString(sequence); if (cleanSequences.length > 0) { [cleanSequence] = cleanSequences; } } else { cleanSequence = sequence.replace(/\s/g, ''); } // Nothing left? if (!cleanSequence) { return errorResponses.missingSequence; } if (minimumLength && cleanSequence.length < minimumLength) { return errorResponses.shortSequence; } // Check and fail if there are any invalid characters in the sequence const onlyValidChar = ( strict ? validCharactersUnderStrictMode : validCharacters ).test(cleanSequence); if (!onlyValidChar) { return errorResponses.invalidSequence; } // Attempt to find what type is more likely const likelyType: 'na' | 'aa' = findLikelyType(cleanSequence); // Fail if type can't be detected if (!likelyType) { return errorResponses.invalidSequence; } return { ...validResponse, likelyType, sequence, }; } /** * Main validation function * * @param {Array<string>|string} sequences - An array of sequences or a string * @return {Array<object|null>} The result of validating each sequence * while keeping order intact. */ function validateSequences(input: string | string[], minimumLength?: number) { let sequences: string[] = []; // Is this a string? if (typeof input === 'string') { // Is this a FASTA format? if (isFASTA(input)) { // This is important to happen here, otherwise you will get a result // similar to [[a], [b]] instead of [a, b] sequences = prepareFASTAString(input); } else { // We only work with arrays, so create an array sequences = [input]; } } else { sequences = [...input]; } // This works based on the value of 'sequence', so keep it here instead of top const invalidInputException = `Sequence Validation function expects an Array<string>|string, but received ${typeof sequences}`; // Otherwise, make sure we have an array to work with if (!Array.isArray(sequences)) { throw new Error(invalidInputException); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore } else if (!Object.prototype.toString.call(sequences) === '[object Array]') { throw new Error(invalidInputException); } // If the input is empty, return empty results if (sequences.length === 0) { return []; } // Validate each sequence separately, compile and return the results return sequences.map((sequence) => sequenceValidator(sequence, minimumLength) ); } export default validateSequences;
Java
UTF-8
1,126
3.59375
4
[]
no_license
package com.example.evgsa.androidgraphics.logic; /** * This class describes a 'cell' - one pixel at game table * */ public class Cell { private int timeLeft; //variable that decreases with any tick. When it reaches 0, the cell is no more lit up public boolean isCellActivated = false; /** * This method decreases the time left for cell to be lit up * (that's a realisation of snake's tale to disappear with time) * */ public void update(boolean hasSnakeEaten) { //if snake has eaten food then the time of being lit up shouldn't decrease //(and that's how snake becomes longer) if(!hasSnakeEaten && (timeLeft != 0)) { timeLeft--; } else if (timeLeft == 0) { isCellActivated = false; } } public void activate() { timeLeft = GameBase.snakeLength; isCellActivated = true; } public void deactivate() { isCellActivated = false; } public void activate(int timeLeft) { this.timeLeft = timeLeft; isCellActivated = true; } }
SQL
UTF-8
410
3.40625
3
[]
no_license
-- START:issue SELECT * FROM Bugs AS b JOIN Comments AS c ON (b.issue_id = c.issue_id AND c.issue_type = 'Bugs') WHERE b.issue_id = 1234; -- END:issue -- START:comment SELECT * FROM Comments AS c LEFT OUTER JOIN Bugs AS b ON (b.issue_id = c.issue_id AND c.issue_type = 'Bugs') LEFT OUTER JOIN FeatureRequests AS f ON (f.issue_id = c.issue_id AND c.issue_type = 'FeatureRequests'); -- END:comment
Python
UTF-8
5,430
2.828125
3
[]
no_license
""" This is deployed as a lambda function in AWS. """ import decimal from distutils.util import strtobool from functools import lru_cache import itertools import json from pathlib import Path import boto3 from boto3.dynamodb.conditions import Key print("Loading function") dynamodb = boto3.resource("dynamodb") bibles_table = dynamodb.Table("B3Bibles") search_table = dynamodb.Table("B3Search") resources_dir = Path(__file__).parent / "resources" def handler(event, context): """ Handles all API calls for barebonesbible.com. """ path = event["path"] query = event["queryStringParameters"] print(f"Received path={path} and query={query}") root, *parts = path.strip("/").split("/") if root not in {"books", "search", "strongs"}: return _response(404, {"message": f"Invalid resource '{root}'"}) # 1. User has requested /strongs if root == "strongs": return _response(200, resource("strongs")) # 2. User is searching on a term if root == "search": result = _handle_search(query) code = 404 if "error" in result else 200 return _response(code, result) # 3. User has requested /books books = resource("books") if not parts: return _response(200, _books_by_collection(books)) # 4. User has requested /books/{code} if len(parts) == 1 and parts[0] in books: return _response(200, books[parts[0]]) # 5. User has requested /books/{code}/{start}/{end} if len(parts) == 3 and parts[0] in books and is_cv(parts[1]) and is_cv(parts[2]): result = {"verses": _fetch_verses(parts)} return _response(200, result) # 6. Failed return _response(404, {"message": f"Invalid path: {path}"}) @lru_cache(maxsize=10) def resource(name): """ Load json resource. """ path = (resources_dir / f"{name}.json") with path.open(encoding="utf8") as f: return json.load(f) @lru_cache(maxsize=100) def chapter(chapter_id): """ Load chapter from bibles table """ condition = Key("chapterId").eq(chapter_id) resp = bibles_table.query(KeyConditionExpression=condition) return resp["Items"] @lru_cache(maxsize=500) def references(term): """ Load list of refs and ref counts for a term. """ response = search_table.get_item(Key={"term": term}) return json.loads(response["Item"]["refs"]) def _handle_search(query): term = query["term"] result = {"term": term} # Get references refs = references(term) # Filter for book book = query.get("book") if book: result["book"] = book refs = [ref for ref in refs if ref[0].startswith(book)] result["nrefs"] = sum(count for _, count in refs) result["nverses"] = len(refs) # Do pagination page = int(query.get("page", 1)) size = int(query.get("size", 0)) if size: refs = refs[(page - 1) * size : page * size] result["page"] = page result["pages"] = int((result["nverses"] - 0.1) // size + 1) result["refs"] = refs # Fetch verses refs_only = strtobool(query.get("refsOnly", "false")) if not refs_only: if len(refs) > 100: return {"error": "Please set a page `size` of <= 100"} result["verses"] = _batch_get_verses(refs) return result def _batch_get_verses(refs): """ Batch get a list of verses...this is actually fairly fast. """ key_pairs = [ref.rsplit(".", 1) for ref, _ in refs] key_pairs = [(cid, int(vnum)) for cid, vnum in key_pairs] keys = [{"chapterId": cid, "verseNum": vnum} for cid, vnum in key_pairs] response = dynamodb.batch_get_item( RequestItems={"B3Bibles": {"Keys": keys}}, ReturnConsumedCapacity="TOTAL", ) verses = response["Responses"]["B3Bibles"] # Bleaurgh, need to sort key_to_verse = {(v["chapterId"], v["verseNum"]): v for v in verses} return [key_to_verse[k] for k in key_pairs] def _fetch_verses(parts): code = parts[0] c1, v1 = to_cv(parts[1]) c2, v2 = to_cv(parts[2]) verses = [] for c in range(c1, c2 + 1): items = chapter(f"{code}.{c}") if c == c1: items = [item for item in items if item["verseNum"] >= v1] if c == c2 and v2: items = [item for item in items if item["verseNum"] <= v2] verses.extend(items) return verses def _books_by_collection(books_by_code): return [ { "collection": collection, "books": list(group), } for collection, group in itertools.groupby(books_by_code.values(), key=lambda x: x["collection"]) ] def is_cv(cv): cv = cv.split(".") return len(cv) == 2 and cv[0].isdigit() and (cv[1].isdigit() or cv[1] == "x") def to_cv(cv): c, v = cv.split(".") c = int(c) v = None if v == "x" else int(v) return c, v def _response(code, content): return { "statusCode": str(code), "body": json.dumps(content, cls=DecimalEncoder), "headers": { "Access-Control-Allow-Origin" : "*", "Access-Control-Allow-Credentials" : "true", "Content-Type": "application/json", }, } class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): return int(o) return super().default(o)
Go
UTF-8
971
3.734375
4
[]
no_license
package main import "fmt" func main() { root := &TreeNode{ Val: 1, Left: &TreeNode{ Val: 2, Left: &TreeNode{Val: 3}, Right: &TreeNode{Val: 4}, }, Right: &TreeNode{ Val: 5, Right: &TreeNode{Val: 6}, }, } flatten(root) fmt.Println(root) } func flatten(root *TreeNode) { if root == nil { return } t := &T{} t.recursion(root) root.Right = t.Head.Right root.Val = t.Head.Val root.Left = nil } func (t *T) recursion(root *TreeNode) { if root == nil { return } if root.Val == 5 { fmt.Println("111") } if t.Head == nil { t.Head = &TreeNode{Val: root.Val} t.Next = t.Head } else { t.Next.Right = &TreeNode{Val: root.Val} t.Next = t.Next.Right } t.recursion(root.Left) t.recursion(root.Right) } type T struct { Head *TreeNode Next *TreeNode } type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func (t TreeNode) String() string { return fmt.Sprintf("%v,%v,%v", t.Val, t.Left, t.Right) }