language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C++
UTF-8
1,346
3.578125
4
[]
no_license
#include <iostream> #include <vector> #include <numeric> #include <cmath> class RemovedNumbers { public: static unsigned long long Get_Sum_Of_Numbers(long long n) { unsigned long long sum_of_numbers = 0; for(int number = n; number >= 0 ; --number) { sum_of_numbers += number; } return sum_of_numbers; } static std::vector<std::vector<long long>> removNb(long long n) { std::cout << "N = " << n << "\n"; std::vector<std::vector<long long>> returner; unsigned long long sum_of_numbers = Get_Sum_Of_Numbers(n); std::vector<unsigned long long> numbers (n, 0); std::iota(numbers.begin(), numbers.end(), 1); for(long long number : numbers) { for(long long number_2 : numbers) { unsigned long long product_of_a_b = number * number_2; unsigned long long sum_without_a_b = sum_of_numbers - number - number_2; if(product_of_a_b == sum_without_a_b) { /* Add (a, b) and (b, a) */ returner.push_back({number, number_2}); //Try with emplace_back next } } } if(!returner.empty()) return returner; else return {}; } };
Python
UTF-8
10,845
4.6875
5
[ "CC-BY-SA-3.0", "CC-BY-SA-4.0", "MIT" ]
permissive
#!/usr/bin/env python # coding: utf-8 # # An introduction to Regular Expressions in Python # Ian Watt - Aberdeen Python User Group, 13 January 2021 # # Licence: [CC-BY-SA](https://creativecommons.org/licenses/by-sa/4.0/) # ## Finding strings # Finding strings inside longer strings in Python is quite easy __if__ you know what you are looking for. # In[1]: #find where the string 'name' occurs str = 'Hello. My name is Ian' print(str.find('name')) # prints the start position # Q. Why was that not 11? # ### But ... # if we want to find something which we don't know the value of (eg. any name that falls after "my name is") or more general patterns (eg. any date, a four digit year, or a Postcode) where we don't know what the exact value is, we need a better way to do that. Imagine a file containing the following: # # __Date Number of sales__ # # 01 Jan 2019, 47 # # 4 Jun 2019 - 91 # # 15 Dec 2019 - 66 # # 28 Feb 2020, 81 # # 1 March 2021, 100 # # 29 Jul 21: 43 # # etc. # # How would we gather all the datesEnter __Regular Expressions__ (often referred to as _Regexes_ ) # ## Using Regexes for the first time # Let's start by importing the Regular Expressions library # In[2]: import re # Now set up a string in which to search: # In[3]: str = "Today's date is 13 Jan 2021." # Then create a _match object_ # # We give it the _re_ search method, some pattern to match, and our target text string. # # We know that a digit is represented as '\d' so we'll work with that. # # We'll come back to the syntax of the pattern - in this case we say four digits. # In[4]: mo = re.search(r'\d\d\d\d', str) # # The match object is a Python object with properties of its own which we can request and use. # In[5]: print(mo) # In[6]: print(mo.group()) #the matching group of characters found # In[7]: print(f"Start: {mo.start()}, End: {mo.end()}") #start and end positions of the matching group # In[8]: print (mo.string) #the string we are searching in # In[9]: print (mo.span()) #same as start / end # ### Pattern syntax # # In our match object above we ask for '\d\d\d\d' # # '\d' means 'any digit' - so this means any four consecutive digits. # # You'll note that the '13' of the date _didn't_ match our pattern as it has two digits followed by a whitespace character. Only the four consective digits of 2021 matched. # # There is a more elegant way to specify four digits: \d{4} # # Try it: # In[10]: mo = re.search(r'\d{4}', str) print(mo.group()) # In[11]: mo = re.search(r'\d{2,4}', str) #minimum of 2 times, max of 4 times print(mo.group()) # And we can specify a minimum and maximum number by using # '{2,4}' to ask for a minimum of 2 and a maximum of 4 items. # ### Extending our search pattern # How can we find the first two digits of the date (representing the day)? # In[12]: mo = re.search(r'\d{2}', str) print(mo.group()) # #### Adding the month # # We can create a pattern for alphabetic characters thus # # '[A-Za-z]' # # The 'A-Z' asks for capital letters, and 'a-z' for lower case letters. # In[13]: mo = re.search(r'[A-Za-z]', str) print(mo.group()) # That gets the first single alphabetic character of our string ('T'). # # As our query asks for the first instance of an alphabetic character in our _set_ enclosed in square brackets: [ ]. # # What would happen if, instead of '[A-Za-z]' we just said '[a-z]'? # # Applying what we know about groups of characters we can extend that: # In[14]: mo = re.search(r'[A-Za-z]{3}', str) print(mo.group()) # That returns the first three alphabetic characters of the string. # So - putting these together how can we get the full date? # # First we need to know how Regexes handle whitespace. # # We can specify a whitespace as '\s' # In[15]: mo = re.search(r'\s', str) print(mo.span()) # Can you see how that matches the first occurring space after "Today's" in our string? # # Let's put that all together. # # We need # - 2 digits # - a space # - 3 letters # - a space # - 4 digits # # Can you write it? Give it a go before scrollling down # In[16]: #add your code here # In[17]: #this should work mo = re.search(r'\d{2}\s[A-Za-z]{3}\s\d{4}', str) print(mo.group()) # ### Improving our pattern # # How can we improve what we have? What if someone accidentally slips two spaces in, instead of one? Try the following. # In[18]: str2 = "Today's date is 13 Jan 2021." mo = re.search(r'\d{2}\s[A-Za-z]{3}\s\d{4}', str2) print (mo.group()) ''' # The example above fails as the mo has not been created as the search fails. # we can fix this by checking first str2 = "Today's date is 13 Jan 2021." mo = re.search(r'\d{2}\s[A-Za-z]{3}\s\d{4}', str2) if mo: print(mo.group()) else: print("Match Object does not exist as the pattern was not found") ''' # We can improve our search patterns to guard against that by saying look for one or more whitespace characters. # # The syntax for that is: # # - '\s+' # In[19]: #this should work now (note the plus sign after each 's' character) mo = re.search(r'\d{2}\s+[A-Za-z]{3}\s+\d{4}', str2) print(mo.group()) print (" ^ Note the double space after 'Jan'") # ## Some useful things to know. # Special sequences (as we've seen with '\d' and '\s\' # # ### Special Sequences # - \A Returns a match if the specified characters are at the beginning of the string "\AWh" # - \b Returns a match where the specified characters are at the beginning or at the end of a word (the "r" in the beginning is making sure that the string is being treated as a "raw string") r"\band" # - \B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word r"\Bone" # - \d Returns a match where the string contains digits (numbers from 0-9) "\d" # - \D Returns a match where the string DOES NOT contain digits "\D" # - \s Returns a match where the string contains a white space character "\s" # - \S Returns a match where the string DOES NOT contain a white space character "\S" # - \w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) "\w" # - \W Returns a match where the string DOES NOT contain any word characters "\W" # - \Z Returns a match if the specified characters are at the end of the string "Spain\Z" # # And metacharacters. # # ### Metacharacters # * "[ ]" A set of characters "[p-z]" # * "\" used before a special sequence (or to escape special characters) "\d" # * "." ANY character (except newline character) "ba..n" # * "^" Starts with "^Today" # * "$" Ends with "erdeen$" # * "*" Zero or more occurrences "fix*" # * "+" One or more occurrences "fix+" # * "{}" Exactly the specified number of occurrences "iss{2}" # * "|" Either or "cats|dogs" # * "()" Capture group # # [more examples](https://www.w3schools.com/python/python_regex.asp) # ### Looking for other things # # We can look for other characters in a similar way # # In[20]: str3 = "Today's date is 13-Jan-21." mo = re.search(r'\d{2}-[A-Za-z]{3}-\d{2}', str3) #search for date containing "-" character print(mo.group()) str4 = "Today's date is 13/Jan/21." mo = re.search(r'\d{2}/[A-Za-z]{3}/\d{2}', str4) #search for date containing "/" character print(mo.group()) # In[ ]: And we can combine both characters in a group # In[23]: str3 = "Today's date is 13/Jan/21." str4 = "Today's date is 13/Jan/21." mo = re.search(r'\d{2}[-/][A-Za-z]{3}[-/]\d{2}', str3) #search for date containing "-" OR "/" characters print(mo.group()) mo = re.search(r'\d{2}[-/][A-Za-z]{3}[-/]\d{2}', str4) #search for date containing "-" OR "/" characters print(mo.group()) # ## Capture Groups # We can tell RE to give us back only a part of the match - a _capture group_. This is useful if you want to make sure that you match a full postcode, for example, but only the area part before the space, or match a full date but only return the year. # # Capture Groups are denoted by () # # In this example we search for "Number:" followed by numbers or spaces - BUT we only want to capture the numeric group and any spaces within that. We discard "Number:" # In[27]: sc = "Jim's Phone Number: 01224 999999" mo = re.search(r'Number: ([\d\s]+)', sc) #Match "Number: " and a sequence of numbers and spaces but just capture the numbers and space print(mo.group(1)) # In[28]: # A named capture group mo = re.search(r'Number: (?P<number>.+)', sc) #here the capture group is named by the <number> print(mo.group('number')) # Those named goups can then be referenced again. See the additional resources below. # # ### Assertions # # Sometimes we want to find something only if it is followed bye somethis else. So Python needs to _look ahead_. # # For example, what if we want to find "Aberdeen," only if it is followed by "Scotland"? # # We use'?=' to specify what the query must look ahead to. # In[30]: sa = 'Aberdeen, Scotland is a city of 221,091 people.' mo = re.search(r'Aberdeen(?=, Scotland)', sa) print(mo.group()) # In[32]: sb = 'Aberdeen, Washington is a city of 16,896 people.' mo = re.search(r'Aberdeen(?=, Scotland)', sb) print(mo.group()) # this will fail when ', Scotland' is not found # ### Negative assertions # # We can search for a term only if it is NOT followed by a certain term using '?!' # In[36]: sc = 'Aberdeen, Scotland is a city of 16,896 people.' mo = re.search(r'Aberdeen(?!, Washington)', sc) #find Abedreen if it is NOT followed by ", Washington" print(mo.group()) # ', Washington' is not found, so the search succeeds # ## Finding all instances of a set of characters # # We can use the re.findall() function # In[39]: phrase = 'Welcome to Episode 3. In Chapter 2, on page 5, at line 17 you will find what you are looking for' print(re.findall(r'\d+', phrase)) #try changing the '+' to an asterisk "*" What happens? Why? # In[40]: phrase = 'Welcome to Episode 3. In Chapter 2, on page 5, at line 17 you will find what you are looking for.' print(re.findall(r'[A-Z][a-z]+', phrase)) #find a Capital letter followed by one or more alphabetic character # ## Compiling regexes # We can create and save a pattern, and reuse it, for example in a loop. This is much more efficicent than putting the pattern to be used in the loop itself. # In[41]: myRegex = re.compile(r'\d+') # This reads the file line-by-line for line in open("TestFile.txt", 'r'): print(myRegex.findall(line)) # ## More resources # # * An introduction to Python Regular Expressions https://www.pythoncentral.io/introduction-to-python-regular-expressions/ (four parts) # * Python Regex at W£ Schools https://www.w3schools.com/python/python_regex.asp # * Regex101 - test your patterns: https://regex101.com # In[ ]:
Java
UTF-8
6,563
3.046875
3
[]
no_license
import javax.tools.Tool; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Created by Chrono on 19.05.2017. */ public class Toolkit { public void progress(String text) { System.out.println("--- " + text + " ---"); } public void step(String text) { System.out.println("\t> " + text); } public Toolkit() { } public static void drawFields(Graphics g, double scale, int maxFood, int amountFood, int x, int y) { float sizeReal = 4; //if (isNest) { //g.setColor(Color.BLUE); // g.fillRect((int) Math.round(x * scale - sizeReal / 2), (int) Math.round(y * scale - sizeReal / 2), (int) Math.round(sizeReal * 2), (int) Math.round(sizeReal * 2)); //} //g.setColor(Color.getHSBColor(0.3f, 1f * amountFood / maxFood, 0.8f));// je mehr Futter, desto intensiver der Farbton g.setColor(Color.GREEN); g.fillOval((int) Math.round(x * scale), (int) Math.round(y * scale), (int) Math.round(sizeReal), (int) Math.round(sizeReal)); } public void drawCreature(Graphics g, Creature creature, double scale, float sizeReal, int x, int y) { float creature_size = creature.getSize(); g.setColor(Color.BLACK); if(creature.isDead()) { g.setColor(Color.RED); } else { if(creature.getSex() == 0) { g.setColor(creature.getWorld().keys.getCreatureColors()[0]); } else if (creature.getSex() == 1) { if(creature.isPregnant()) { g.setColor(Color.magenta); } else { g.setColor(creature.getWorld().keys.getCreatureColors()[1]); } } } g.fillOval((int) Math.round(x * scale), (int) Math.round(y * scale), (int) Math.round(creature_size), (int) Math.round(creature_size)); } public void drawFood(Graphics g, Food food, double scale, int x, int y) { int food_size = food.getSize(); int dangerous = food.getDangerous(); if(dangerous == 0) { g.setColor(food.getWorld().keys.getFoodColors()[0]); } /*else if(dangerous == 1) { g.setColor(Color.ORANGE); } else if(dangerous == 2) { g.setColor(Color.RED); }*/ else { g.setColor(food.getWorld().keys.getFoodColors()[1]); } g.fillRect((int) Math.round(x * scale), (int) Math.round(y * scale), (int) Math.round(food_size), (int) Math.round(food_size)); } public static int randomPos(int max) {//, int notAllowed) { int x; do { // garantiert, dass keine Futterquelle auf dem Feld des Nestes ist // NEIN! -.- x = (int) (Math.random() * max); } while (x == 2); return x; } // return a random m-by-n matrix with values between 0 and 1 // use to fill matrix with random weights public static double[][] random(int m, int n) { double[][] a = new double[m][n]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) { a[i][j] = Math.random(); } return a; } // return x^T y public static double dot(double[] x, double[] y) { if (x.length != y.length) throw new RuntimeException("Illegal vector dimensions."); double sum = 0.0; for (int i = 0; i < x.length; i++) sum += x[i] * y[i]; return sum; } // return B = A^T public static double[][] transpose(double[][] x) { int m = x.length; int n = x[0].length; double[][] a = new double[n][m]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) a[j][i] = x[i][j]; return a; } //activation function public static double[][] sigmoid(double[][] x) { int m = x.length; int n = x[0].length; double[][] o = new double[n][m]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) o[i][j] = 1 / (1 + Math.exp(-(x[i][j]))); return o; } public int[][] surroundings(Creature creature, List<Creature> all, List<Food> foods) { int size = creature.getSight() * 2 + 1; int[][] surround = new int[size][size]; int[] position = creature.getPosition(); int[] currentPos = new int[2]; int tempx, tempy; for(int i = 0; i < size; i++) { for(int u = 0; u < size; u++) { currentPos[0] = position[0] + (u - creature.getSight()); currentPos[1] = position[1] + (i - creature.getSight()); for (Creature creature1 : all) { if (Arrays.equals(creature1.getPosition(), currentPos)) { if(creature1.getId() == creature.getId()) { surround[u][i] = -1; } else { surround[u][i] = 1; } } } for (Food food : foods) { if (Arrays.equals(food.getPosition(), currentPos)) { surround[u][i] = 2; } } } } return surround; } public static int getID(List<Creature> all) { int id = 0; synchronized (all) { for (Creature creature : all) { if (creature.getId() > id) { id = creature.getId(); } } } return id; } public static int generateSex() { int sex = (int)(Math.random() * 2); return sex; } public static int generateDanger() { int danger = (int) (Math.random() * 2); return danger; } public boolean checkCiv(List<Creature> all) { boolean male = false; boolean female = false; synchronized (all) { for (Creature creature : all) { if(creature.getSex() == 0) { male = true; } else { female = true; } } if(!(male && female)) { return false; } else { return true; } } } }
Python
UTF-8
681
3.78125
4
[]
no_license
from decimal import * def run_timing(): total = [] while s := input("Enter 10 km run time: "): try: total.append(float(s)) except ValueError as e: print("Enter a valid time.") print(f"Average of {sum(total)/len(total)}, over {len(total)} runs") def beyond(*args): f , before , after = args new = str(f).split(".") return float(f"{new[0][-before:]}.{new[1][:after]}") def exact(): first = input("First decimal: ") second = input("Second decimal: ") return float(Decimal(first)+Decimal(second)) if __name__ == "__main__": # run_timing() print(beyond(1234.5678,2,3)) print(exact())
C++
UTF-8
1,199
2.71875
3
[]
no_license
#include <curses.h> #include <iostream> #include "Game.hpp" #include "Player.hpp" #include "Enemy.hpp" #include<unistd.h> int main() { //ncurses shit initscr(); cbreak(); noecho(); keypad(stdscr, TRUE); nodelay(stdscr, TRUE); start_color(); init_pair(1, COLOR_YELLOW, COLOR_GREEN); Game game; game.init(); Player *player = new Player('>', PLAYER); game.addEntity(player, 1, 1); // Enemy *enemy1 = new Enemy('(', ENEMY); // Enemy *enemy2 = new Enemy('(', ENEMY); // Enemy *enemy3 = new Enemy('(', ENEMY); // game.addEntity(enemy1, 80, 5); // game.addEntity(enemy2, 70, 4); // game.addEntity(enemy3, 55, 8); int ch; int time = 0; while (game.isRunning()) { usleep(game.getGameSpeed()); if ((ch = getch()) == ERR) { /* user hasn't responded ... */ } else { game.processInput(ch); } game.update(time); game.render(); time++; if (time > 10) { time = 0; } } endwin(); std::cout << "Final score: " << game.getScore() << std::endl; }
C#
UTF-8
3,270
2.578125
3
[ "MIT" ]
permissive
using System; using System.IO; using System.Net; using System.Text; using JetBrains.Annotations; using Newtonsoft.Json; using Xunit; namespace Http2Sharp { public sealed class IntegrationTest : IDisposable { private const string BASE_URL = "http://localhost:8080"; private readonly HttpServer server = new HttpServer(); public IntegrationTest() { server.AddListener(new HttpListener(server, IPAddress.Loopback, 8080)); server.AddHandler(new GenericHttpHandler(new TestServer())); server.StartListen(); } public void Dispose() { server.Dispose(); } [Fact] public void TestGetEmpty() { var result = SendRequest("GET", BASE_URL + "/"); Assert.Equal("Hello World", result); } [Fact] public void TestGetEcho() { var result = SendRequest("GET", BASE_URL + "/echo?value=TEST"); Assert.Equal("TEST", result); } [Fact] public void TestGetEcho2() { var result = SendRequest("GET", BASE_URL + "/echo2/TEST"); Assert.Equal("TEST", result); } [Fact] public void TestBad() { var exception = Record.Exception(() => { SendRequest("GET", BASE_URL + "/not-found"); }); Assert.IsType<WebException>(exception); var response = (HttpWebResponse)((WebException)exception).Response; Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } [Fact] public void TestPost() { var result = SendRequest("POST", BASE_URL + "/post", new User { Gender = Gender.Male, DateOfBirth = DateTime.Now, Email = "test@test.test", Name = "Name Name", Username = "Username" }); var userResult = JsonConvert.DeserializeObject<User>(result); Assert.Equal(Gender.Male, userResult.Gender); Assert.Equal("test@test.test", userResult.Email); Assert.Equal("Name Name", userResult.Name); Assert.Equal("Username", userResult.Username); } [NotNull] private static string SendRequest([NotNull] string method, [NotNull] string uri, [CanBeNull] object body = default) { var request = WebRequest.CreateHttp(uri); request.Method = method; if (body != null) { var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(body)); request.ContentType = "application/json"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } using (var response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException())) { return reader.ReadToEnd(); } } } } }
Shell
UTF-8
12,486
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
#!/bin/bash ################################################################################ # # Copyright (c) 2016, EURECOM (www.eurecom.fr) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are those # of the authors and should not be interpreted as representing official policies, # either expressed or implied, of the FreeBSD Project. # ################################################################################ # file config-change # brief manage the config changes of oai-enb service, and occurs everytime a new configuration value is updated (juju set) # author navid.nikaein@eurecom.fr set -eux source $CHARM_DIR/utils/common set_env_paths status-set maintenance "Configuring $oaieNB_exec_name" node_func=`config-get node_function` file_config=`cat $CHARM_DIR/.config_file` if [ "$(config-get branch)" != "$(cat $CHARM_DIR/.branch)" ]; then juju-log "branch name changed" $CHARM_DIR/hooks/upgrade-charm fi if [ "$(config-get revision)" != "$(cat $CHARM_DIR/.revision)" ]; then $CHARM_DIR/hooks/upgrade-charm juju-log "revision changed" fi if [ "$(config-get kernel)" != "$(cat $CHARM_DIR/.kernel)" ]; then $CHARM_DIR/hooks/upgrade-charm juju-log "kernel changed" fi if [ "$node_func" != "$(cat $CHARM_DIR/.node_func)" ]; then $CHARM_DIR/hooks/upgrade-charm juju-log "node function changed" fi if [ "$(config-get agent_active)" != "$(cat $CHARM_DIR/.agent_active)" ]; then $CHARM_DIR/hooks/upgrade-charm juju-log "agent active changes" fi if [ "$(config-get target_hardware)" != "$(cat $CHARM_DIR/.hw)" ]; then juju-log "hw name changed" $CHARM_DIR/hooks/upgrade-charm fi if [ "$(config-get remote_monitoring)" != "$(cat $CHARM_DIR/.rtmon)" ]; then $CHARM_DIR/hooks/upgrade-charm juju-log "rtmon changed" fi # The installation runs unnecessarily multiple times for default config file if [ "$(config-get config_file)" != "default" ] ; then if [ "$file_config" != "$(config-get config_file)" ]; then # we don't know what is changed $CHARM_DIR/hooks/upgrade-charm juju-log "config_file changed" fi fi if [ "$node_func" == "eNodeB_3GPP_BBU" ] || [ "$node_func" == "NGFI_RCC_IF4p5" ] ; then echo "yes" > $CHARM_DIR/.rru_active fh_tr_mode=`config-get fh_transport_mode` if [ "$fh_tr_mode" != "$(cat $CHARM_DIR/.fh_tr_mode)" ]; then juju-log "fronthaul tr_mode changed" $CHARM_DIR/hooks/upgrade-charm fi fh_if_name=`config-get fh_if_name` if [ "$fh_if_name" != "$(cat $CHARM_DIR/.fh_if_name)" ]; then sed -r -i "/local_if_name/ s/\".+\"/\"$fh_if_name\"/" $conf_path/$file_config if [ "$fh_tr_mode" == "raw" ] || [ "$fh_tr_mode" == "raw_if4p5" ]; then check_ifup $fh_if_name status=$? if [ "$status" == "0" ] ; then read mac_addr </sys/class/net/$fh_if_name/address echo "$mac_addr" > $CHARM_DIR/.fh_address sed -r -i "/local_address/ s/\".+\"/\"$mac_addr\"/" $conf_path/$config_file else juju-log -l WARNING "fh_if_name interface $fh_if_name does not exist" status-set blocked "fh_if_name interface $fh_if_name does not exist" fi elif [ "$tr_mode" == "udp" ] || [ "$fh_tr_mode" == "udp_if4p5" ]; then if [ -n "$fh_if_name" ]; then check_ifup $fh_if_name status=$? if [ "$status" == "0" ] ; then fh_ipv4=`ifconfig $fh_if_name | egrep -o "inet addr:[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | egrep -o "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"` if [ -n "$fh_ipv4" ]; then echo "$fh_ipv4" > $CHARM_DIR/.fh_address sed -r -i "/local_address/ s/\".+\"/\"$fh_ipv4\"/" $conf_path/$config_file_name else juju-log -l WARNING "The fh_if_name $fh_if_name has to be specified before the relation with MME can be added" status-set blocked "Can't get the ipv4 address of $fh_if_name" fi else juju-log -l WARNING "fh_if_name interface $fh_if_name does not exist" status-set blocked "fh_if_name interface $fh_if_name does not exist" fi else juju-log -l WARNING "fh_if_name undefined" status-set blocked "fh_if_name undefined" fi else status-set blocked "invalide Fronthaul transport mode" fi fi fh_local_port=`config-get fh_local_port` if [ "$fh_local_port" != "$(cat $CHARM_DIR/.fh_local_port)" ]; then sed -r -i "/local_port/ s/\".+\"/\"$fh_local_port\"/" $conf_path/$file_config fi # only used when node is RRU, but setting them does not hurt rru_tx_shift=`config-get rru_tx_shift` if [ "$rru_tx_shift" != "$(cat $CHARM_DIR/.rru_tx_shift)" ]; then sed -r -i "s/(iq_txshift[ ]*=[ ]*)[0-9]+/\1$rru_tx_shift/" $conf_path/$file_config fi rru_tx_sampleadvance=`config-get rru_tx_sampleadvance` if [ "$rru_tx_sampleadvance" != "$(cat $CHARM_DIR/.rru_tx_sampleadvance)" ]; then sed -r -i "s/(tx_sample_advance[ ]*=[ ]*)[0-9]+/\1$rru_tx_sampleadvance/" $conf_path/$file_config fi rru_tx_schedadvance=`config-get rru_tx_schedadvance` if [ "$rru_tx_schedadvance" != "$(cat $CHARM_DIR/.rru_tx_schedadvance)" ]; then sed -r -i "s/(tx_scheduling_advance[ ]*=[ ]*)[0-9]+/\1$rru_tx_schedadvance/" $conf_path/$file_config fi else echo "no" > $CHARM_DIR/.rru_active fi ############################################################################### ############################################################################### juju-log "Setting up configuration in the "$file_config" file" ############################################################################### ############################################################################### #Both the name and the id are sent in the s1 link request setup enb_name=`config-get enb_name` enb_id=`config-get enb_id` if [ -n "$enb_name" ] && [ -n "$enb_id" ]; then #ENB NAME sed -r -i "s/(Active_eNBs[ ]*=[^\"]*)\".*\"/\1\"$enb_name\"/" $conf_path/$file_config sed -r -i "s/(eNB_name[ ]*=[ ]*)\".*\"/\1\"$enb_name\"/" $conf_path/$file_config #go in a file and see whether inside the network there is already this name #if not, you can change and we need to run again to establish the s1 link #ENB ID sed -r -i "s/(eNB_ID[ ]*=[ ]*)[^ ;]*/\1$enb_id/" $conf_path/$file_config #go in a file and see whether inside the network there is already this name else juju-log -l WARNING "The ENB identifiers have to be specified because maybe the default ones inside the conf file have already been assigned to another ENB. So specify it before proceeding" fi ############################################################################### frame_type=`config-get frame_type` tdd_config=`config-get tdd_config` tdd_config_s=`config-get tdd_config_s` eutra_band=`config-get eutra_band` downlink_frequency=`config-get downlink_frequency` uplink_frequency_offset=`config-get uplink_frequency_offset` N_RB_DL=`config-get N_RB_DL` nb_antennas_tx=`config-get nb_antennas_tx` nb_antennas_rx=`config-get nb_antennas_rx` tx_gain=`config-get tx_gain` rx_gain=`config-get rx_gain` [ -z "$frame_type" ] || (sed -r -i "s/(frame_type[ \t]*=[ \t]*)\"[a-zA-Z]+\"/\1\"$frame_type\"/" $conf_path/$file_config) [ -z "$tdd_config" ] || (sed -r -i "s/(tdd_config[ \t]*=[ \t]*)[0-9]+/\1$tdd_config/" $conf_path/$file_config) [ -z "$tdd_config_s" ] || (sed -r -i "s/(tdd_config_s[ \t]*=[ \t]*)[0-9]+/\1$tdd_config_s/" $conf_path/$file_config) [ -z "$eutra_band" ] || (sed -r -i "s/(eutra_band[ \t]*=[ \t]*)[0-9]+/\1$eutra_band/" $conf_path/$file_config) [ -z "$downlink_frequency" ] || (sed -r -i "s/(downlink_frequency[ \t]*=[ \t]*)[0-9a-zA-Z]+/\1$downlink_frequency/" $conf_path/$file_config) [ -z "$uplink_frequency_offset" ] || (sed -r -i "s/(uplink_frequency_offset[ \t]*=[ \t]*)[-0-9]+/\1$uplink_frequency_offset/" $conf_path/$file_config) [ -z "$N_RB_DL" ] || (sed -r -i "s/(N_RB_DL[ \t]*=[ \t]*)[0-9]+/\1$N_RB_DL/" $conf_path/$file_config) [ -z "$nb_antennas_tx" ] || (sed -r -i "s/(nb_antennas_tx[ ]*=[ ]*)[0-9]+/\1$nb_antennas_tx/" $conf_path/$file_config) [ -z "$nb_antennas_rx" ] || (sed -r -i "s/(nb_antennas_rx[ ]*=[ ]*)[0-9]+/\1$nb_antennas_rx/" $conf_path/$file_config) [ -z "$tx_gain" ] || (sed -r -i "s/(tx_gain[ ]*=[ ]*)[0-9]+/\1$tx_gain/" $conf_path/$file_config) [ -z "$rx_gain" ] || (sed -r -i "s/(rx_gain[ ]*=[ ]*)[0-9]+/\1$rx_gain/" $conf_path/$file_config) pdsch_referenceSignalPower_b13=-27 pusch_p0_Nominal_b13=-96 pucch_p0_Nominal_b13=-100 rach_preambleInitialReceivedTargetPower_b13=-104 case $eutra_band in 13) sed -r -i "s/(pdsch_referenceSignalPower[ \t]*=[ \t]*)[0-9]+/\1$pdsch_referenceSignalPower_b13/" $conf_path/$file_config sed -r -i "s/(pusch_p0_Nominal[ \t]*=[ \t]*)[0-9]+/\1$pusch_p0_Nominal_b13/" $conf_path/$file_config sed -r -i "s/(pucch_p0_Nominal[ \t]*=[ \t]*)[0-9]+/\1$pucch_p0_Nominal_b13/" $conf_path/$file_config sed -r -i "s/(rach_preambleInitialReceivedTargetPower[ \t]*=[ \t]*)[0-9]+/\1$rach_preambleInitialReceivedTargetPower_b13/" $conf_path/$file_config ;; *) juju-log "Calibration parameters might not be optimal for band $$eutra_band" ;; esac #for the empty config options there will not be problems becasue in the coinfig file there are #the default values set by the OAI developers. ############################################################################# ##I should change the s1-u and s1-mme iface=`config-get eth` if [ -n "$iface" ]; then check_ifup $iface status=$? if [ "$status" == "0" ] ; then ipv4=`ifconfig $iface | egrep -o "inet addr:[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | egrep -o "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"` if [ -n "$ipv4" ]; then #INTERFACES sed -r -i "/ENB_INTERFACE_NAME_FOR_S1_MME/ s/\".+\"/\"$iface\"/" $conf_path/$file_config sed -r -i "/ENB_INTERFACE_NAME_FOR_S1U/ s/\".+\"/\"$iface\"/" $conf_path/$file_config #ADDRESSES sed -r -i "/ENB_IPV4_ADDRESS_FOR_S1_MME/ s-\".+\"-\"$ipv4/24\"-" $conf_path/$file_config sed -r -i "/ENB_IPV4_ADDRESS_FOR_S1U/ s-\".+\"-\"$ipv4/24\"-" $conf_path/$file_config else juju-log -l WARNING "The S1 ethernet interface has to be specified before the relation with MME can be added" fi else juju-log -l WARNING "eth interface $iface does not exist" status-set blocked "eth interface $iface does not exist" fi else juju-log -l WARNING "The S1 ethernet interface has to be specified before the relation with MME can be added" fi ############################################################################ TAC=`config-get TAC` #TAC in config file [ -z "$TAC" ] || (sed -r -i "s/(tracking_area_code[ ]*=[ ]*)\"[0-9]+\"/\1\"$TAC\"/" $conf_path/$file_config) #if it empty we keep the default already present in the conf file set by the OAI developers ############################################################################ $CHARM_DIR/hooks/start
Java
UTF-8
1,043
3.296875
3
[]
no_license
package oncemore; public class P101 { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } // public boolean isSymmetric(TreeNode root) { // if(root == null) return true; // if(root.left.val == root.right.val) { // return isSymmetric(root.left) && isSymmetric(root.right); // }else{ // return false; // } // if(root == null) return true; // return help(root.left,root.right); // // } // // public boolean help(TreeNode root1,TreeNode root2){ // if(root1.left.val != root2.right.val || root1.right.val != root2.left.val){ // return false; // } // return true; // } public boolean isSymmetric(TreeNode root) { return isMirror(root,root); } public boolean isMirror(TreeNode t1,TreeNode t2){ if(t1 == null && t2 == null) return true; if(t1 == null || t2 == null) return false; return t1.val == t2.val && isMirror(t1.left,t2.right) && isMirror(t1.right,t2.left); } }
Java
UTF-8
1,428
2.046875
2
[]
no_license
package net.greatsoft.main.db.po; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; @Entity public class VisitMedicine extends Entry { private String VISIT_ID; private String MEDICINE_TIMES;// 使用次数 private String MEDICINE_NAME;// 药品名称 private String MEDICINE_DOSAGE;// 用量 public String getMEDICINE_DOSAGE() { return this.MEDICINE_DOSAGE; } public void setMEDICINE_DOSAGE(String MEDICINE_DOSAGE) { this.MEDICINE_DOSAGE = MEDICINE_DOSAGE; } public String getMEDICINE_NAME() { return this.MEDICINE_NAME; } public void setMEDICINE_NAME(String MEDICINE_NAME) { this.MEDICINE_NAME = MEDICINE_NAME; } public String getMEDICINE_TIMES() { return this.MEDICINE_TIMES; } public void setMEDICINE_TIMES(String MEDICINE_TIMES) { this.MEDICINE_TIMES = MEDICINE_TIMES; } public String getVISIT_ID() { return this.VISIT_ID; } public void setVISIT_ID(String VISIT_ID) { this.VISIT_ID = VISIT_ID; } @Generated(hash = 314781811) public VisitMedicine(String VISIT_ID, String MEDICINE_TIMES, String MEDICINE_NAME, String MEDICINE_DOSAGE) { this.VISIT_ID = VISIT_ID; this.MEDICINE_TIMES = MEDICINE_TIMES; this.MEDICINE_NAME = MEDICINE_NAME; this.MEDICINE_DOSAGE = MEDICINE_DOSAGE; } @Generated(hash = 402544993) public VisitMedicine() { } }
C++
UTF-8
888
3.96875
4
[ "Apache-2.0" ]
permissive
#include <iostream> using namespace std; // This creates the class queue. class queue { int q[100]; int sloc, rloc; public: queue(); // constructor ~queue(); // destructor void qput(int i); int qget(); }; // This is the constructor. queue::queue() { sloc = rloc = 0; cout << "Queue initialized.\n"; } // This is the destructor. queue::~queue() { cout << "Queue destroyed.\n"; } // Put an integer into the queue. void queue::qput(int i) { if(sloc==100) { cout << "Queue is full.\n"; return; } sloc++; q[sloc] = i; } // Get an integer from the queue. int queue::qget() { if(rloc == sloc) { cout << "Queue Underflow.\n"; return 0; } rloc++; return q[rloc]; } int main(int argc, char* argv[]) { queue a, b; // create two queue objects a.qput(10); b.qput(19); a.qput(20); b.qput(1); cout<<a.qget()<<" "; cout<<a.qget()<<" "; cout<<b.qget()<<" "; cout<<b.qget()<<"\n"; return 0; }
Python
UTF-8
2,912
2.9375
3
[]
no_license
import pico2d import random width = 1280 heigth = 1024 pico2d.open_canvas(1280, 1024) running = True back_img = pico2d.load_image("KPU_GROUND.png") csr_img = pico2d.load_image("hand_arrow.png") char_img = pico2d.load_image("animation_sheet.png") player_is_view_left = False player_running_i = 0 player_running_i_max = 100 player_anim_frame = 0 player_anim_frame_max = 8 player_anim_frame_delay = 8 player_csr = 0 padding = 50 points = [(random.randrange(0 + padding, width - padding), random.randrange(0 + padding, heigth - padding)) for n in range(10)] player_pos_x = points[0][0] player_pos_y = points[0][1] def get_inter_curve_points(prev, p1, p2, next, i): t = i / 100 x = ((-t ** 3 + 2 * t ** 2 - t) * prev[0] + (3 * t ** 3 - 5 * t ** 2 + 2) * p1[0] + ( -3 * t ** 3 + 4 * t ** 2 + t) * p2[0] + (t ** 3 - t ** 2) * next[0]) / 2 y = ((-t ** 3 + 2 * t ** 2 - t) * prev[1] + (3 * t ** 3 - 5 * t ** 2 + 2) * p1[1] + ( -3 * t ** 3 + 4 * t ** 2 + t) * p2[1] + (t ** 3 - t ** 2) * next[1]) / 2 return x, y def input_handling(): global running events = pico2d.get_events() for event in events: if event.type == pico2d.SDL_KEYDOWN and event.key == pico2d.SDLK_ESCAPE: running = False pass def draw_csr(): global points for pt in points: csr_img.draw(pt[0],pt[1]) def update_move(): global player_pos_x global player_pos_y global player_running_i global player_running_i_max global player_csr global player_is_view_left global points pos = get_inter_curve_points( points[(player_csr - 1) % len(points)], points[(player_csr) % len(points)], points[(player_csr + 1) % len(points)], points[(player_csr + 2) % len(points)], player_running_i ) player_running_i = player_running_i + 1 if player_running_i > player_running_i_max: player_running_i = player_running_i % player_running_i_max player_csr += 1 player_csr %= len(points) if player_pos_x > pos[0]: player_is_view_left = True elif player_pos_x < pos[0]: player_is_view_left = False player_pos_x = pos[0] player_pos_y = pos[1] while running: back_img.draw(width/2, heigth/2) # 디버깅 용 포지션 띄우는 함수 , 포인트 위치 확인 필요 시 주석 해제하시면 됩니다. # draw_csr() if player_is_view_left: char_img.clip_draw(int(player_anim_frame/player_anim_frame_delay) * 100, 0, 100, 100, player_pos_x, player_pos_y) else: char_img.clip_draw(int(player_anim_frame/player_anim_frame_delay) * 100, 100, 100, 100, player_pos_x, player_pos_y) update_move() input_handling() player_anim_frame = (player_anim_frame + 1) % (player_anim_frame_max * player_anim_frame_delay) pico2d.update_canvas() pico2d.delay(0.01) pico2d.close_canvas()
Java
UTF-8
3,572
2.015625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ml.dmlc.xgboost4j.java; import ai.djl.engine.EngineException; import ai.djl.ml.xgboost.XgbNDArray; import ai.djl.ml.xgboost.XgbNDManager; import ai.djl.ml.xgboost.XgbSymbolBlock; import ai.djl.ndarray.types.Shape; import com.sun.jna.Native; import com.sun.jna.PointerProxy; import java.nio.Buffer; /** DJL class that has access to XGBoost JNI. */ @SuppressWarnings("MissingJavadocMethod") public final class JniUtils { private JniUtils() {} public static void checkCall(int ret) { try { XGBoostJNI.checkCall(ret); } catch (XGBoostError e) { throw new EngineException("XGBoost Engine error: ", e); } } public static XgbSymbolBlock loadModel(XgbNDManager manager, String modelPath) { // TODO: add Matrix handle option long handle = createBoosterHandle(null); checkCall(XGBoostJNI.XGBoosterLoadModel(handle, modelPath)); return new XgbSymbolBlock(manager, handle); } public static long createDMatrix(Buffer buf, Shape shape, float missing) { long[] handles = new long[1]; int rol = (int) shape.get(0); int col = (int) shape.get(1); long handle = new PointerProxy(Native.getDirectBufferPointer(buf)).getPeer(); checkCall(XGBoostJNI.XGDMatrixCreateFromMatRef(handle, rol, col, missing, handles)); return handles[0]; } public static long createDMatrix(ColumnBatch columnBatch, float missing, int nthread) { long[] handles = new long[1]; String json = columnBatch.getFeatureArrayInterface(); if (json == null || json.isEmpty()) { throw new IllegalArgumentException( "Expecting non-empty feature columns' array interface"); } checkCall( XGBoostJNI.XGDMatrixCreateFromArrayInterfaceColumns( json, missing, nthread, handles)); return handles[0]; } public static long createDMatrixCSR(long[] indptr, int[] indices, float[] array) { long[] handles = new long[1]; checkCall(XGBoostJNI.XGDMatrixCreateFromCSREx(indptr, indices, array, 0, handles)); return handles[0]; } public static void deleteDMatrix(long handle) { checkCall(XGBoostJNI.XGDMatrixFree(handle)); } public static float[] inference( XgbSymbolBlock block, XgbNDArray array, int treeLimit, XgbSymbolBlock.Mode mode) { float[][] output = new float[1][]; checkCall( XGBoostJNI.XGBoosterPredict( block.getHandle(), array.getHandle(), treeLimit, mode.getValue(), output)); return output[0]; } public static void deleteModel(long handle) { checkCall(XGBoostJNI.XGBoosterFree(handle)); } private static long createBoosterHandle(long[] matrixHandles) { long[] handles = new long[1]; checkCall(XGBoostJNI.XGBoosterCreate(matrixHandles, handles)); return handles[0]; } }
C#
UTF-8
603
2.71875
3
[]
no_license
using Microsoft.EntityFrameworkCore; using news_server.Data; using System.Linq; namespace news_server.Features.Services { public class UserSerivce { private readonly NewsDbContext context; public UserSerivce(NewsDbContext context) { this.context = context; } public string GetUserNameByProfileId(int id) { var username = context .Profiles .Include(p => p.User) .FirstOrDefault(p => p.Id == id).User.UserName; return username; } } }
Ruby
UTF-8
1,808
2.734375
3
[]
no_license
require 'json' module JsonImporters class SenateImporter def initialize @file_path = Rails.root + "app/assets/json/senate.json" end def perform return false unless @file_path senate_json = JSON.parse File.read(@file_path) senate_reps = senate_json['results'][0]['members'] senate_reps.each do |rep| state = State.find_by(abbr: rep['state']) district = District.find_by(state_id: state.id, number: rep['district']) if state.present? if state state.senate_reps.create!( first_name: rep['first_name'], middle_name: rep['middle_name'], last_name: rep['last_name'], party: rep['party'], phone: rep['phone'], twitter_account: rep['twitter_account'], facebook_account: rep['facebook_account'], propublica_id: rep['id'], began_office_at: began_office(rep['next_election'], rep['seniority']), ended_office_at: ended_office(rep['in_office']), reelection_date: reelection_year(rep['next_election']) ) end end true end private def began_office(next_election, seniority) next_election = next_election.to_i case next_election when 2018 term_length = seniority.to_i when 2020 term_length = seniority.to_i + 2 when 2022 term_length = seniority.to_i + 4 else term_length = 0 end year_elected = next_election - term_length term_length > 0 ? Date.new(year_elected) : nil end def ended_office(in_office) return in_office === 'true' ? nil : Date.new(2017) end def reelection_year(next_election) Date.new(next_election.to_i) end end end
JavaScript
UTF-8
1,386
2.828125
3
[]
no_license
export { AnimationType as default} class AnimationType{ construction(akvOptionsIn){ const kvDefaults = { strURL: null, context: null, nCurrentFrame: 0, nRate: 60 }; //Object.assign shallow this.akvOptions = Object.assign({}, kvDefaults, kvOptionsIn); this.Frames = []; this.Image = new Image(); this.Image.src = this.kvOptions.strURL; } appendFrame(x, y){ this.vFrames.push({x, y}); } getNumFrames(){ return this.vFrames.length; } getInterval(){ return this.kvOptions.nRate; } setCurrentFrameIndex(anIndex){ this.kvOptionsnCurrentFrame = anIndex; } getCurrentFrameIndex(){ return this.kvOptions.nCurrentFrame; } draw(x, y, nWidth, nHight, bFlipH){ const { kvOptions: { context: aContext, nCurrentFrame: anCurrentFrame} } = this, aFrame = this.vFrames[anCurrentFrame]; if (bFlipH){ aContext.save(); aContext.scale(-1, 1); aContext.translate(-nWidth + 1, 0); aContext.drawImage(this.Image, aFrame.x, aFrame.y, nWidth, nHight, -x, y, nWidth, nHight); aContext.restore(); }else{ aContext.drawImage(this.Image, aFrame.x, aFrame.y, nWidth, nHight, x, y, nWidth, nHight ); } } }
Java
UTF-8
1,684
2.796875
3
[]
no_license
package net.lectusAPI.utils; import java.util.ArrayList; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public abstract class LectusInventory { public static ArrayList<LectusInventory> inventorries = new ArrayList<>(); private String title; private Integer size; private Inventory inventory; public LectusInventory(String title, int size) { this.title = title; this.size = size; this.inventory = Bukkit.createInventory(null, size, title); LectusInventory.inventorries.add(this); System.out.println("Invetory registred: " + this.title); } public abstract void buildInventory(); public abstract void onClick(Player player, ItemStack item); public abstract ItemStack getRepresenter(); public LectusInventory addItem(LectusItem... items) { for (LectusItem i : items) { addItem(i.getItemStack()); } return this; } public LectusInventory setItem(int index, LectusItem item) { this.inventory.setItem(index, item.getItemStack()); return this; } public LectusInventory addItem(ItemStack... items) { this.inventory.addItem(items); return this; } public LectusInventory setItem(int index, ItemStack item) { this.inventory.setItem(index, item); return this; } public void openInvetory(Player player) { player.openInventory(getInventory()); } public Inventory getInventory() { return inventory; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public void setSize(Integer size) { this.size = size; } public Integer getSize() { return size; } }
Python
UTF-8
2,077
3.578125
4
[]
no_license
# Longest Common Prefix in a given set of strings class Node: def __init__(self, c=None): self.char = c self.children = dict() self.word_end = False self.hit_count = 0 self.depth = -1 # note: root is depth -1 since it does not hold any char class Context: def __init__(self): self.visited = list() self.max_lcp = list() class Trie: def __init__(self): self.root = Node(None) def add(self, word_str): curr = self.root depth = 0 for c in word_str: curr = curr.children.setdefault(c, Node(c)) curr.hit_count += 1 curr.depth = depth depth += 1 curr.word_end = True def allowed(self, node, ctxt): if not node: return False if node.depth == -1: # root return True if not self.addition_check(node, ctxt): return False return True def next_nodes(self, node, ctxt): if len(node.children) == 1: return node.children.values() return list() def traverse(self, node, ctxt): if not self.allowed(node, ctxt): return ctxt.visited.append(node) self.process_node(node, ctxt) for nd in self.next_nodes(node, ctxt): self.traverse(nd, ctxt) ctxt.visited.pop() # rollback def addition_check(self, node, ctxt): return True def process_node(self, node, ctxt): if len(ctxt.max_lcp) < node.depth + 1: ctxt.max_lcp = "".join([nd.char for nd in ctxt.visited if nd.char]) if __name__ == "__main__": t = Trie() for wd in ["code", "coder", "coding", "codable", "codec", "codecs", "coded", "codeless", "codependence", "codependency", "codependent", "codependents", "codes", "codesign", "codesigned", "codeveloped", "codeveloper", "codex", "codify", "codiscovered", "codrive"]: t.add(wd) ct = Context() t.traverse(t.root, ct) print(ct.max_lcp)
Java
UTF-8
1,886
1.976563
2
[]
no_license
package com.ponysdk.spring.servlet; import com.ponysdk.core.server.application.AbstractApplicationManager; import com.ponysdk.core.server.application.ApplicationManagerOption; import com.ponysdk.core.server.application.UIContext; import com.ponysdk.core.ui.main.EntryPoint; import com.ponysdk.impl.webapplication.page.InitializingActivity; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.util.StringUtils; import javax.servlet.ServletException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; class SpringApplicationManager extends AbstractApplicationManager { private String[] configurations; SpringApplicationManager(ApplicationManagerOption options) { super(options); final List<String> files = new ArrayList<>(); final String clientConfigFile = getOptions().getClientConfigFile(); if (StringUtils.isEmpty(clientConfigFile)) files.addAll(Arrays.asList("conf/client_application.inc.xml", "etc/client_application.xml")); else files.add(clientConfigFile); configurations = files.toArray(new String[0]); } @Override protected EntryPoint initializeUIContext(UIContext ponySession) throws ServletException { try (ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(configurations)) { EntryPoint entryPoint = applicationContext.getBean(EntryPoint.class); final Map<String, InitializingActivity> initializingPages = applicationContext.getBeansOfType(InitializingActivity.class); if (initializingPages != null && !initializingPages.isEmpty()) { initializingPages.values().forEach(InitializingActivity::afterContextInitialized); } return entryPoint; } } }
JavaScript
UTF-8
1,266
2.859375
3
[]
no_license
'use strict'; const crypto = require('crypto'); class CryptoMon { constructor(secret){ if (!secret || typeof secret !== 'string') { throw new Error('Cryptr: secret must be a non-0-length string'); } this.secret = secret; this.key = crypto.createHash('sha256').update(String(secret)).digest(); } getSecret(){ return this.secret; } encrypt(value){ if (value == null) { throw new Error('value must not be null or undefined'); } let iv = crypto.randomBytes(16); let cipher = crypto.createCipheriv('aes-256-ctr', this.key, iv); let encrypted = cipher.update(String(value), 'utf8', 'hex') + cipher.final('hex'); return iv.toString('hex') + encrypted; } decrypt(value){ if (value == null) { throw new Error('value must not be null or undefined'); } let stringValue = String(value); let iv = Buffer.from(stringValue.slice(0, 32), 'hex'); let encrypted = stringValue.slice(32); let decipher = crypto.createDecipheriv('aes-256-ctr', this.key, iv); return decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8'); } } module.exports = CryptoMon;
Python
UTF-8
2,618
2.796875
3
[]
no_license
# coding=utf-8 """Define table and operations for users.""" from flask_login import UserMixin from sqlalchemy import Column, Integer, VARCHAR, DATE, BOOLEAN from . import Base, session, handle_db_exception, collections class Users(Base, UserMixin): """Table constructed for users.""" __tablename__ = 'Users' user_id = Column(Integer, primary_key=True, autoincrement=True, unique=True) user_name = Column(VARCHAR(128), nullable=False, unique=True) password = Column(VARCHAR(256), nullable=False) email = Column(VARCHAR(128), nullable=False) birthday = Column(DATE, nullable=True) gender = Column(BOOLEAN, nullable=True) def to_json(self): """Return a json for the record.""" return { 'user_id': self.user_id, 'user_name': self.user_name, 'email': self.email, 'birthday': str(self.birthday) if self.birthday else None, 'gender': int(self.gender) if self.gender else None, 'collections': collections.get_collections_by_user(self.user_id) } def get_id(self): """Override UserMixin.get_id()""" return self.user_id def add_user(user_name, password, email, birthday=None, gender=None): try: user = Users() user.user_name = user_name user.password = password user.email = email user.birthday = birthday user.gender = gender session.add(user) session.commit() return user except Exception as err: handle_db_exception(err) def find_user_by_id(user_id): try: user = session.query(Users).filter(Users.user_id == user_id).first() session.commit() return user except Exception as err: handle_db_exception(err) def find_user_by_name(user_name): try: user = session.query(Users).filter(Users.user_name == user_name).first() session.commit() return user except Exception as err: handle_db_exception(err) def update_user_info(user_id, password=None, email=None, birthday=None, gender=None, **kwargs): try: result = session.query(Users).filter(Users.user_id == user_id).update({ "password": password if password is not None else Users.password, "email": email if email is not None else Users.email, "birthday": birthday if birthday is not None else Users.birthday, "gender": gender if gender is not None else Users.gender }) session.commit() return result except Exception as err: handle_db_exception(err)
Java
UTF-8
374
1.921875
2
[]
no_license
package com.aissure.packet.packet.job; /** * Created by Administrator on 2017/7/14. */ public class JobFactory implements IJobFactory{ // @Override // public BaseAccessibilityJob createWeiXinJob() { // return WeChatJob.getWeChatJob(); // } // // @Override // public BaseAccessibilityJob createQQJob() { // return QQJob.getQQJob(); // } }
Java
UTF-8
8,931
2.09375
2
[]
no_license
package com.example.paulap.crowdsourcing.report; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.StrictMode; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.example.paulap.crowdsourcing.Models.Event; import com.example.paulap.crowdsourcing.Models.Issue; import com.example.paulap.crowdsourcing.R; import com.example.paulap.crowdsourcing.report.HeaderFooter; import com.example.paulap.crowdsourcing.report.PDFCreatorForEvents; import com.example.paulap.crowdsourcing.report.PDFCreatorForIssues; import com.example.paulap.crowdsourcing.util.AppUtil; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.lang.reflect.Method; import java.time.LocalDate; import java.util.ArrayList; import java.util.Date; import java.util.List; public class PdfReportsActivity extends AppCompatActivity { private static final String TITLE_ISSUE = "Issues"; public static final String PDF_EXTENSION = ".pdf"; private static final String TITLE_EVENTS = "Events"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pdf_reports); TextView issueTextView = findViewById(R.id.reports_issues_description); Issue issue = AppUtil.issueList.get(AppUtil.issueList.size()-1); issueTextView.setText(issue.getDescription()); TextView eventTextView = findViewById(R.id.reports_events_description); Event event = AppUtil.eventList.get(AppUtil.eventList.size()-1); eventTextView.setText(event.getTitle() + "\n" +event.getL() + "\n" + event.getData()); } public void exportIssuesPdf(View view) { List<Issue> issues = new ArrayList<>(); Document document = null; issues.add(new Issue("Groapa","Multe gropi pe strazi","Sa se asfalteze","Rutier",0,R.drawable.issue1)); issues.add(new Issue("Mijloc de transport","Autobuzele intarzie foarte multe","Mai multe autobuze","Transport",0,R.drawable.issue2)); issues.add(new Issue("Spatii verzi","Prea putine spatii verzi","Sa se faca mai multe parcuri","Agrement",0,R.drawable.mountain)); try { //Document is not auto-closable hence need to close it separately String extStorageDirectory = Environment.getExternalStorageDirectory() .toString(); System.out.println("extStorageDirectory = " + extStorageDirectory + "\n"); File folder = new File(this.getFilesDir(), "pdf"); folder.mkdir(); document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream( new File(folder, TITLE_ISSUE+PDF_EXTENSION))); HeaderFooter event = new HeaderFooter(); event.setHeader("ISSUES"); writer.setPageEvent(event); document.open(); PDFCreatorForIssues.addMetaData(document, TITLE_ISSUE); PDFCreatorForIssues.addTitlePage(document, TITLE_ISSUE); PDFCreatorForIssues.addContent(document, issues); }catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); System.out.println("FileNotFoundException occurs.." + e.getMessage()); }finally{ if(null != document){ document.close(); } } showIssuesPdf(); } public void showIssuesPdf() { if(Build.VERSION.SDK_INT>=24){ try{ Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure"); m.invoke(null); }catch(Exception e){ e.printStackTrace(); } } String yourFilePath = this.getFilesDir() + "/pdf/" + TITLE_ISSUE+PDF_EXTENSION; File file = new File( yourFilePath ); PackageManager packageManager = getPackageManager(); Intent testIntent = new Intent(Intent.ACTION_VIEW); testIntent.setType("application/pdf"); List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); //Uri uri = Uri.fromFile(file); Uri uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".com.example.paulap.crowdsourcing.provider", file); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(uri, "application/pdf"); startActivity(intent); } public void exportEventsPdf(View view) { List<Event> events = new ArrayList<>(); Document document = null; Location loc1 = new Location(""); loc1.setLatitude(0.0d); loc1.setLongitude(0.0d); Location loc2 = new Location(""); loc2.setLatitude(0.0d); loc2.setLongitude(0.0d); new Event("Strangere fonduri", new Date().toString(), "Cluj-Napoca Daicoviciu 34", "Se vor colecta fundri ptr copii nevoiasi", "Fonduri"); new Event("Donatii oamenii strazi", new Date().toString(), "Cluj-Napoca Daicoviciu 34", "Scopul este de a ajuta oamenii strazii cum puteti. Cu haine, mancare, adapost etc. Orice este binevenit ", "Donati"); new Event("Ajutor oameni cu dizabilitati", new Date().toString(), "Cluj-Napoca Daicoviciu 34", "Vrem sa ajutam oamenii cu dizabilitati de toate felurile. Acest voluntariat se intampla in fiecare zi, puteti participa venind la adresa mentionatat si vom discuta despre cum puteti ajuta si pe cine.", "Voluntariat"); events.add(new Event("Strangere fonduri", new Date().toString(), "Cluj-Napoca Daicoviciu 34", "Se vor colecta fundri ptr copii nevoiasi", "Fonduri")); events.add(new Event("Donatii oamenii strazi", new Date().toString(), "Cluj-Napoca Daicoviciu 34", "Scopul este de a ajuta oamenii strazii cum puteti. Cu haine, mancare, adapost etc. Orice este binevenit ", "Donati")); events.add(new Event("Ajutor oameni cu dizabilitati", new Date().toString(), "Cluj-Napoca Daicoviciu 34", "Vrem sa ajutam oamenii cu dizabilitati de toate felurile. Acest voluntariat se intampla in fiecare zi, puteti participa venind la adresa mentionatat si vom discuta despre cum puteti ajuta si pe cine.", "Voluntariat")); try { File folder = new File(this.getFilesDir(), "pdf"); folder.mkdir(); document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream( new File(folder, TITLE_EVENTS+PDF_EXTENSION))); HeaderFooter event = new HeaderFooter(); event.setHeader("EVENTS"); writer.setPageEvent(event); document.open(); PDFCreatorForEvents.addMetaData(document, TITLE_EVENTS); PDFCreatorForEvents.addTitlePage(document, TITLE_EVENTS); PDFCreatorForEvents.addContent(document, events); }catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); System.out.println("FileNotFoundException occurs.." + e.getMessage()); }finally{ if(null != document){ document.close(); } } showEventsPdf(); } public void showEventsPdf() { if(Build.VERSION.SDK_INT>=24){ try{ Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure"); m.invoke(null); }catch(Exception e){ e.printStackTrace(); } } String yourFilePath = this.getFilesDir() + "/pdf/" + TITLE_EVENTS+PDF_EXTENSION; File file = new File( yourFilePath ); PackageManager packageManager = getPackageManager(); Intent testIntent = new Intent(Intent.ACTION_VIEW); testIntent.setType("application/pdf"); List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); //Uri uri = Uri.fromFile(file); Uri uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".com.example.paulap.crowdsourcing.provider", file); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(uri, "application/pdf"); startActivity(intent); } }
Python
UTF-8
4,090
3.21875
3
[]
no_license
import numpy as np import random as rd from scipy.spatial import distance class Molecule: def __init__(self, coordinates): self.coordinates = coordinates def select_process(constant_list): """ CHOOSE A PATHWAY constant_list: rate constants list return: chosen path index """ r = np.sum(constant_list) * rd.random() list_ = np.where(r > np.cumsum(constant_list)) return len(list_[0]) def time_advance(constant_list): """ TIME ADVANCE constant_list: list of rate constants return: advanced time """ r = rd.random() return -np.log(r)/np.sum(constant_list) def neighbourhood(center, radius, positions): """ :param center: class :param radius: float :param positions: list :return: Elements in positions closer than a distance radius from center """ center_position = np.array(center.coordinates) neighbours = [] for element in positions: element_position = np.array(element.coordinates) if 0 < distance.euclidean(element_position, center_position) <= radius: neighbours.append(element) return neighbours def particular_rates(center, directional_rates, neighbours): """ :param center: class :param directional_rates: array :param neighbours: list of classes :return: Hopping rate to each element of neighbours """ center_position = np.array(center.coordinates) neighbour_rates = [] for element in neighbours: element_position = np.array(element.coordinates) direction = (element_position - center_position) / distance.euclidean(element_position, center_position) element_rate = np.inner(direction, directional_rates) neighbour_rates.append(element_rate) return neighbour_rates """ Proposam una nova implementació del mètode de KMC en aquest cas tractant cada molècula com una classe que es podrà extendre. Per començar només caracteritzada amb les seves coordenades (2D) i sense cap mètode definit. Al no tenir més informació que les posicions prendrem els 'rates' com a dades conegudes. Disposarem les molècules en els nusos d'una xarxa cristal·lina (N, N). """ # Lattice generation molecules = [] for i in range(1, 21): for j in range(1, 21): molecule = Molecule([i, j]) molecules.append(molecule) """ Simulam la propagació d'una excitació. Aquesta pot decaure a l'estat fonamental o passar a una altra molècula. Aquesta probabilitat de transició dependrà de la posició de la molècula. Vendrà donada per l'expressió: k = (vect_k * r_director) / R On r_director és el vector unitari en la direcció que uneix les dues molecules, vect_k és un vector que modela les probabilitats de transició en cada direcció cartesiana (X, Y) privilegiant Y>0 i R és la distància entre les molecules implicades. Amb aquest disseny pensam que podrem passar al cas de distribució no ordenada més fàcilment. """ # Rate vector rate_vector = np.array([1/7, 1/5]) decay_rate = 1/3 maximus_lifetime = 25 effective_radius = 1.05 """ Prenem 10000 casos possibles de simulació. Ens quedarem amb les posicions de les molècules on ha arribat l'excitació i en farem l'estadística. """ exciton_paths = [] shift_list = [] time_list = [] for i in range(1000): path = [] molecule = molecules[rd.randint(0, len(molecules) - 1)] path.append(molecule.coordinates) time = 0.0 while time <= maximus_lifetime: neighbours = neighbourhood(molecule, effective_radius, molecules) neighbour_rates = (particular_rates(molecule, rate_vector, neighbours)) neighbour_rates.insert(0, decay_rate) time = time + time_advance(neighbour_rates) process_index = select_process(neighbour_rates) if process_index == 0: break else: molecule = neighbours[process_index-1] path.append(molecule.coordinates) shift = distance.euclidean(np.array(path[0]), np.array(path[-1])) shift_list.append(shift) time_list.append(time)
Python
UTF-8
1,438
3.1875
3
[]
no_license
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import pandas as pd import mglearn import matplotlib.pyplot as plt # Loading dataset iris_dataset = load_iris() # Printing dataset print("Keys of iris_dataset: \{}".format(iris_dataset.keys())) print(iris_dataset['DESCR'][:193] + "\n...") print("Target names: {}".format(iris_dataset['target_names'])) print("Features names: \n{}".format(iris_dataset['feature_names'])) print("Type of data: {}".format(type(iris_dataset['data']))) print("Shape of data: {}".format(iris_dataset['data'].shape)) print("Five columns of data:\n{}".format(iris_dataset['data'][:5])) print("Target:\n{}".format(iris_dataset['target'])) # Splitting dataset into train and test set X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_state=0) # Visualizing # Create dataframe from data in X_train # label column using strings in iris_dataset.feature_names iris_df = pd.DataFrame(X_train, columns=iris_dataset.feature_names) grr = pd.tools.plotting.scatter_matrix(iris_df, c=y_train, figsize=(15,15), marker='o', hist_kwds={'bins':20}, s=60, alpha=.8, cmap=mglearn.cm3) plt.show() # Designing estimator knn = KNeighborsClassifier(n_neighbors=1) knn.fit(X_train, y_train) print("Test set score: {:.2f}".format(knn.score(X_test, y_test)))
Python
UTF-8
432
2.9375
3
[]
no_license
import serial import sys def send_text(number, text, path='COM5'): ser = serial.Serial(path, 9600,timeout=1) if not ser.isOpen(): ser.open() # set text mode ser.write(('AT+CMGF=%d\r' % 1).encode()) # set number ser.write(('AT+CMGS="%s"\r' % number).encode()) # send message ser.write(("%s\x1a" % text).encode()) print (ser.readlines()) ser.close() send_text(sys.argv[1], sys.argv[2])
Python
UTF-8
2,454
2.765625
3
[]
no_license
import json import redis from django.conf import settings redis_conn = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT) def inc_room_count(room_name): """Увеличивает счетчик участников в комнате чата""" counter_key = create_counter_key(room_name) counter_value = redis_conn.incr(counter_key) def dec_room_count(room_name): """Уменьшает счетчик участников в комнате чата""" counter_key = create_counter_key(room_name) counter_value = redis_conn.decr(counter_key) # Если после выхода участника в чате не осталось других участников - удаляем список сообщений чата if counter_value == 0: redis_conn.delete(counter_key) message_list_key = create_message_list_key(room_name) redis_conn.delete(message_list_key) def add_message(user, room_name, message): """Добавляет сообщение в комнату чата""" message_list_key = create_message_list_key(room_name) redis_conn.rpush(message_list_key, json.dumps({ 'username': user.username, 'message': message })) def get_messages(room_name): """Получает все сообщения для заданного чата""" message_list_key = create_message_list_key(room_name) result = [] for index in range(redis_conn.llen(message_list_key)): result.append(json.loads(redis_conn.lindex(message_list_key, index))) return result def get_room_list(): """Возвращает названия всех комнат чата""" result = [] counters = redis_conn.keys('room:counter:*') for counter in counters: room_name = bytes.decode(counter, 'utf-8').split(':')[2] user_count = bytes.decode(redis_conn.get(counter), 'utf-8') result.append({ 'room_name': room_name, 'user_count': user_count }) return result def create_counter_key(room_name): """Возвращает ключ для счетчика участников в переданной комнате чата""" return f'room:counter:{room_name}' def create_message_list_key(room_name): """Возвращает ключ для списка сообщений комнаты чата""" return f'room:message_list:{room_name}'
C
UTF-8
620
3.234375
3
[]
no_license
#ifndef _STACK_H #define _STACK_H #include "transmitters.h" /* Creates new stack for transmitters and returns pointer to it's top. */ transmitters *t_stack_create_stack(); /* Adds new transmitter value on top of stack **stack. */ void t_stack_push(transmitters **stack, transmitter *value); /* Removes top of stack and saves pointer to this transmitter to given *result. If stack is empty returns 1 otherwise returns 0. */ int t_stack_pop(transmitters **stack, transmitter **result); /* Removes remaining values from stack and frees theirs allocated memory. */ void t_stack_free_stack(transmitters **stack); #endif
Python
UTF-8
767
2.578125
3
[]
no_license
wp=open('wp.php') config = [] wp_full =[] for line in wp: new_val = "" if line.startswith('define'): st1 = line.find("'") sp1= line.find("'",st1+1) par = line[st1+1:sp1] st2 = line.find("'",sp1+1) sp2 = line.find("'", st2 + 1) val = line[st2+1:sp2] new_val = input("Enter "+ par +"[" + val + "]: ") else: par="" val="" config += [[line,par, val, new_val]] wp_new = "" for line in config: txt =str(line[0]) if line[3] !="": #print(txt) txt = txt.replace(line[2],line[3]) #print(txt) wp_new+=txt #print(wp_new) #print(config) try: wp2=open('wp_new.php','x') except: wp2=open('wp_new.php','w') wp2.write(wp_new)
Java
UTF-8
2,013
2.46875
2
[]
no_license
package com.muruw.portfolio.dao; import com.muruw.portfolio.model.Project; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; import java.util.UUID; @Repository("postgres") public class ProjectDAOPostgres implements ProjectDAO{ private final JdbcTemplate jdbcTemplate; @Autowired public ProjectDAOPostgres(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public List<Project> selectAllProjects() { final String sql = "SELECT id, name, stack, description, link FROM project"; List<Project> projects = jdbcTemplate.query(sql, (resultSet, i) -> { UUID id = UUID.fromString(resultSet.getString("id")); String name = resultSet.getString("name"); String stack = resultSet.getString("stack"); String description = resultSet.getString("description"); String link = resultSet.getString("link"); return new Project(id, name, stack, description, link); }); return projects; } @Override public Optional<Project> selectProjectById(UUID id) { String sql = "SELECT id, name, stack, description, link FROM project WHERE id = ?"; Project project = jdbcTemplate.queryForObject(sql, new Object[]{id}, (resultSet, i) -> { UUID projectId = UUID.fromString(resultSet.getString("id")); String name = resultSet.getString("name"); String stack = resultSet.getString("stack"); String description = resultSet.getString("description"); String link = resultSet.getString("link"); return new Project(projectId, name, stack, description, link); }); return Optional.ofNullable(project); } @Override public int insertProject(UUID id, Project project) { return 0; } }
Markdown
UTF-8
2,418
3.640625
4
[]
no_license
--- layout: default_layout title: JavaScript中Promise使用 date: 2019-01-24 17:19:36 tags: --- ## 定义 Promise对象用于包装异步函数执行结果,以便用同步的方式处理其结果。 ```javascript var mypromise = new Promise(function(resolve, reject){ // asynchronous code to run here // call resolve() to indicate task successfully completed // call reject() to indicate task has failed }) ``` ```javascript mypromise.then( function(successurl){ document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />' }, function(errorurl){ console.log('Error loading ' + errorurl) } ) ``` promise 包含3种状态: **pending**: 初始状态 **fulfilled**:  完成状态 **rejected**: 失败状态 ## 链式调用方法 then()返回一个Promise对象 或者构造一个空白的Promise对象(如Promise.resolve()返回一个初始状态是fulfilled的延迟对象) ## 处理延迟对象数组 ```javascript var twodoggypromises = [getImage('dog1.png'), getImage('dog2.png')] Promise.all(twodoggypromises).then(function(urls){ console.log(urls) // logs ['dog1.png', 'dog2.png'] }).catch(function(urls){ // if any image fails to load, then() is skipped and catch is called console.log(urls) // returns array of images that failed to load }) ``` Promise.all([]) 参数传入Promise对象数组 then中得到结果的数组 Promise.all() takes an iterable (array or array-like list) of promise objects, and waits until all of those promises have been fulfilled before moving on to any then() method attached to it. The then() method is passed an array of returned values from each promise. ## 解决Promise数组 有一个执行失败 就进入catch问题 **使用map** ```javascript var doggies = ['dog1.png', 'dog2.png', 'dog3.png', 'dog4.png', 'dog5.png'] var doggypromises = doggies.map(getImage) // call getImage on each array element and return array of promises var sequence = Promise.resolve() doggypromises.forEach(function(curPromise){ // create sequence of promises to act on each one in succession sequence = sequence.then(function(){ return curPromise }).then(function(url){ var dog = document.createElement('img') dog.setAttribute('src', url) doggyplayground.appendChild(dog) }).catch(function(err){ console.log(err + ' failed to load!') }) }) ```
Markdown
UTF-8
19,222
2.59375
3
[]
no_license
import javaLogo from './java-logo.svg' import styles from './document.module.css' <div className={styles["Welcome"]}> <div className={styles["logo"]}> <img src={javaLogo} className={styles["logo-java"]} alt="logo" /> </div> ## Wstęp W swojej karierze trenera oprogramowania przyglądałem się już kilkudziesięciu osobom, które zaczynały swoją przygodę z IT. Pozwoliło mi to na sformułowanie kilku wniosków, które przedstawiłem poniżej. Z tego artykułu dowiesz się: * Dlaczego warto uczyć się Javy? * Co jest ważne przy wyborze ścieżki nauki Javy? * Jakie mogą być “kamienie milowe” w trakcie Twojej nauki, które sprawią, że wkroczysz na zupełnie nowy, wyższy poziom? * Czego jeszcze potrzebujesz, aby zostać deweloperem? ## Zrozum, że czeka Cię długa droga. Twój cel to zdobycie pracy jako Junior Dev. Musisz nauczyć się tego i **tylko tego** co jest Ci potrzebne do osiągnięcia tego celu. Całej reszty nauczysz się później w pracy. Sukces na rozmowie kwalifikacyjnej to dopiero początek. Pracując, będziesz rozwiązywał różnorodne problemy. Począwszy od tych związanych z konfiguracją sprzętu, poprzez trudności natury programistycznej, aż do problemów komunikacyjnych między Tobą i innymi członkami zespołu. Rozwiązanie każdego z tych nich zrobi z Ciebie lepszego programistę, a tym samym lepszego pracownika. Wejść na ścieżkę IT może każdy. Podążanie nie nią jest już dużo trudniejsze. (Wybaczcie te drętwe metafory). Łatwo jest napisać “Hello World”, trudno jest medytować nad pryncypiami paradygmatu obiektowego, aż do momentu pełnego oświecenia. Łatwo jest sklecić projekt i zapomnieć o nim, trudno natomiast wrócić do swojego kodu, sprzed miesiąca, żeby wyciągnąć wnioski i go poprawić. Tak więc programowanie nie jest dla każdego. Programowanie jest dla konsekwentnych. Jeżeli słyszałeś, że trzeba znać matematykę, aby zacząć programować, to jest w tym tylko odrobina prawdy. Jest to matematyka na poziomie 6 klasy podstawówki. Jeżeli nie pamiętasz jak rozwiązać równanie kwadratowe, to nic nie szkodzi. Nie będzie to potrzebne. To natomiast co potrzebujesz, to elementarna umiejętność logicznego myślenia. ## Zrozum, że warto. Zapewniam Cię, że warto się przekwalifikować. Jest wiele powodów. Pierwszy z nich to pieniądze. Jeżeli dobrze rozwiązujesz problemy swojego pracodawcy, to jesteś mocnym ogniwem z jego biznesie, bez którego nie będzie się mógł funkcjonować. Zapłaci Ci za to. Praca programisty jest ciekawa. Zobaczysz, jak wielkim przełomem będzie dla Ciebie nauczenie się, jak korzystać z bibliotek kodu. Programowanie to wielkie intelektualne klocki Lego. Możesz złożyć co Ci się podoba. Za darmo. Umiejętność programowania daje nowe możliwości. Możesz rozwinąć swój własny biznes. Jeżeli jeszcze oprócz problemów technicznych potrafisz dojrzeć okazje na biznes i wykorzystać je, możesz stworzyć protyp systemu i zaszczepić ideę w swoich kolegach a następnie założyć zespół, który wypromuje swój własny produkt. Warto jest poświęcić czas na naukę programowania, pamiętaj jednak że wszystko ma swoją cenę. Przebranżowienie się na dewelopera to duża inwestycja. Musisz zainwestować swój czas (którego każdy ma za mało) i swoje pieniądze. Każda inwestycja obarczona jest ryzykiem. Pamiętaj o tym. Jest jedno ograniczenie, którego moim zdaniem nie da się przeskoczyć - język angielski. Być może da się nauczyć jakichś podstaw programowania w Javie z kursów polskojęzycznych. Kiedy jednak będziesz musiał rozwiązywać problemy, najlepiej jest szukać rozwiązań (googlować) w języku angielskim. Pomijam już fakty, że fachowa literatura, dokumentacja wszystkich bibliotek, [StackOverflow](https://stackoverflow.com/) i większość wartościowych tutoriali jest po angielsku. Z tym angielskim to podobnie jak z matematyką. Słownictwa technicznego związanego z programowaniem nauczysz razem z Javą. Nie trzeba, żebyś znał wszystkie 16 czasów gramatycznych (czy ile ich tam jest). Właściwie to nie musisz znać ani jednego. Wystarczy, że zrozumiesz co czytasz. ## Zrozum, czego będziesz potrzebował, aby zacząć. Każdy ma swoje sposoby na naukę. Jedni wybierają płatne Internetowe kursy, inni oglądają filmy na Youtube, jeszcze inni zapisują się do prywatnych szkół programowania, a są i tacy co kupują książki. Nie jest moim celem, aby przedstawiać wady i zalety tych różnych podejść. Sam musisz wybrać to, co najbardziej będzie pasować do Twojej sytuacji życiowej, preferencji i możliwości. Będziesz potrzebował jednak planu. Musisz dowiedzieć się, co jest ważne i gdzie musisz skoncentrować swoje siły. Są również rzeczy, które możesz na początek zrozumieć tylko koncepcyjnie i w zarysie, z nadzieją, że nauczysz się ich później. Musisz ponać Javę - wiadomo. Czy jest coś jeszcze? “Jak głęboko muszę rozumieć implementacji kolekcji w Javie? Czy powinienem znać algorytmy operujące na drzewach binarnych? Czy muszę znać SQLa? Czy muszę znać wszystkie wzorce projektowe?” - pytań, takich jak te, zadasz sobie po drodze setki. Jest kilka sposobów, żeby szukać na nie odpowiedzi. Najlpszy z nich to znalezienie mentora. Kogoś, do którego możesz zawsze napisać i zapytać się: “Hej! Czego mam się teraz uczyć?”. Może jest ktoś taki w okolicy? Inny sposób to doczytywanie w Internecie (po angielsku). Przeglądnij ogłoszenia o pracę dla Juniorów. Przejrzyj programy kursów, nawet, jeżeli nie zamierzasz ich kupować. Zapytaj na forum jakiejś grupy na facebooku. (nie przejmuj się trollami). ## Poznaj podstawową składnię języka. Nie ważne jaki kurs znajdziesz, to zawsze zaczniesz od tych samych elementów. Na tym etapie nauki najważniejsze jest to żebyś zrozumiał, jak działa w ogóle wykonanie programu przez komputer. Wyświetlisz kilka znaków w konsoli, dodasz kilka liczb do siebie, zaimplementujesz jakiś prosty algorytm, a może nawet wyświetlisz jakieś okienko. Szybko przekonasz się, że podstawy są proste. W gruncie rzeczy komputery to bardzo prymitywne maszyny, które przerzucają dane według dość prostych reguł. Dlatego, żeby osiągnąć coś konkretnego, często trzeba powtórzyć sporo kroków, żeby osiągnąć relatywnie prostą rzecz. Już tutaj możesz pierwszy raz zetknąć się z potworem, któremu na imię Złożoność. Mam tutaj na myśli nie tylko złożoność obliczeniową, ale przede wszystkim złożoność związaną z [naturą problemu i złożoność przypadkową](https://www.quora.com/What-are-essential-and-accidental-complexity). Realizuj cierpliwie kurs, który kupiłeś lub znalazłeś w Internecie, rób zadania i ucz się walczyć ze Złożonością w każdym z jej wcieleń. Trzymaj porządek w plikach i projektach. Naucz się organizować swój kod w taki sposób, żeby się w nim łatwo poruszać. Nazywaj pliki, klasy, metody, zmienne tak, żeby łatwo przypomnieć sobie jaka jest ich odpowiedzialność. Zrozum czym jest algorytm. Algorytmika to bardzo głęboka i zróżnicowania dziedzina wiedzy. Algorytm Euklidesa do wyliczania NWW, możesz zrozumieć i zaimplementować już dziś. Rozwiązanie Sudoku za pomocą “backtrackingu” możesz zrobić już za kilka tygodni, jeśli uprzesz się wystarczająco mocno. Z kolei Szybką Transformatę Fouriera (FFT) pewnie nie prędko zrozumiesz (chyba, że masz jakieś epizody obcowania z matematyką na poziomie akademickim). Nie potrzebujesz rozumieć większości złożonych algorytmów. Pamiętaj co jest twoim celem - zdobycie pracy jako Junior Dev. ## Poznaj paradygmat obiektowy. A więc wiesz już jak napisać pętlę i co to jest tablica wielowymiarowa? Musisz teraz rozszerzyć swoje myślenie. Paradygmat obiektowy - to brzmi tajemniczo. Programując w Javie uczysz się jak modelować jakiś wycinek rzeczywistości za pomocą klas. Twój program będzie instruował specjalnie stworzone przez Ciebie obiekty jak mają się zachowywać i komunikować między sobą. Możesz zapytać: po co to wszystko? Odpowiadam: żeby było łatwiej. Modelowanie pojęć za pomocą hierarchii klas, zamykanie w klasach zachowań i danych oraz inne techniki obiektowe pozwala na ogarnięcie wielu problemów bez popadnięcia w wariactwo. Pozwalają zapanować nad Złożonością. ## Poznaj zaawansowane elementy języka. Kolekcje w Javie, typy generyczne, obsługa wyjątków, interfejsy funkcyjne, wyrażenia lambda i wiele wiele innych… To są rzeczy związane z Javą, które znajdziesz w swoim kursie. Ucząc się tych tematów pamiętaj, że są to takie narzędzia wbudowane w język, które mają Ci pomóc tworzyć kod, który rozwiązuje jakiś problem. Kolekcje w Javie pozwalają na łatwiejsze manipulowanie grupami obiektów. Wyjątki pozwalają na obsługę nieprzewidzianych zachowań programu. Wyrażenia lamda wprowadzone w Java 8 pozwalają inaczej, zwięźlej zapisywać fragmenty kodu. Pamiętaj, że to wszystkie te narzędzia mają swoje przeznaczenie. Staraj się zrozumieć po co one powstały. Używaj ich w swoim kodzie. ## Rozwiązuj problemy. Pewnie będziesz zadawał sobie pytanie. “Dobrze, rozumiem już co to jest zmienna i wiem jak działa pętla ‘for’, co ja teraz mogę z tym zrobić?” Musisz samodzielnie pisać kod. Jeżeli nie będziesz tego robił, już teraz możesz przestać czytać ten tekst. Programowanie to umiejętność bardzo pragmatyczna, która opiera się na doświadczeniu. Oglądając tutoriale, czytając poradniki - nauczysz się tylko jak “wygląda” kod w Javie. Właściwie programowanie to cały zestaw umiejętności: używanie środowiska programistycznego, wydajne posługiwanie się komputerem jako narzędziem, formułowanie problemów, szukanie rozwiązań w Google, aplikowanie znalezionych odpowiedzi do swojego przypadku itd. Nie da się tego nauczyć z filmików, ani nawet od trenera programowania na kursie. Wszystko musi przejść przez Twoją głowę i Twoje palce i skompilować się na Twoim komputerze. “Co mam pisać? Jakie zadania mam rozwiązywać? Jakie projekty mogę zrobić z moją wiedzą?”. To są problemy, które blokują wielu początkujących. Moja odpowiedź brzmi: “Zadania i projekty, które rozwiązujesz muszą być przede wszystkim ciekawe.” Zapewniam Cię, że już od samego początku można robić interesujące rzeczy. Później w miarę poznawania Javy i innych technologii odsłonią się przed Tobą nowe fascynujące obszary. Podaję poniżej "kamienie milowe" w procesie nauczania. Dzięki każdemu z nich znajdziesz się nie jako na “nowym” poziomie. * *Programy w konsoli.* Jeżeli będziesz potrafił pobrać dane od użytkownika przez konsolę, możesz tworzyć, programy, które rozwiązują proste problemy, albo wykorzystują jakiś podstawyowy algorytm, żeby coś policzyć. Są wśród nich pewne “klasyki”, które często pojawiają się na rozmowach kwalifikacyjnych (np. silnia, ciąg Fibonacciego, etc). Możesz zrobić coś, co rozwiązuje jakieś praktyczne problemy: liczy podatek, sprawdza poprawność numery PESEL. Przykładowe zadania i schematy blokowe algorytmów znajdziesz tutaj https://pl.spoj.com/problems/ lub tutaj http://www.algorytm.org/ * *Okienka.* Jeżeli potrafisz wyświetlić coś w okienku Twojego systemu operacyjnego (np. za opmocą JavaFX) i trochę pogooglujesz jesteś w stanie tworzyć już ciekawe gry. (snake, sudoku, kółko i krzyżyk etc.). Jeżeli nie chcesz robić gier, możesz stworzyć przydatne kalkulatory (np. kalorii w posiłkach, kosztów prowadzenia firmy, itp). Twój program jest widoczyny na ekranie, więc możesz pochwalić się nim przed znajomymi, albo zautomatyzować coś, co do tej pory robiłeś ręcznie (np. w pracy) * *Input/Output* Twój kod musi komunikować się ze światem zewnętrznym. Jeżeli nauczysz się jak wczytać dane z pliku możesz zrobić program, który wczytuje książkę i znajduje najczęściej powtarzające się słowo. Możesz zrobić program, który pobiera jakieś dane z pliku wyciąga z nich statystyki i zapisuje do innego pliku. * *Zewnętrzne biblioteki.* Moim zdaniem jest to największa rewolucja w życiu początkującego programisty. Jeżeli potrafisz już w miarę sprawnie pisać swój własny kod, to kolejnym krokiem jest sięgnięcie po zewnętrzne biblioteki. Pozwala Ci to na wykorzystanie “klocków” do zbudowania rzeczy których prawdopodobnie samodzielnie nigdy byś nie stworzył. Możesz dzięki temu zrobić naprawdę dużo. Chcesz analizować obrazy, dźwięk lub pliki? Nie ma problemu! Chcesz przetwarzać dane za pomocą jakiegoś zaawansowanego algorytmu? Żaden problem! Szukaj bibliotek. Żeby wykorzystać bibliotekę musisz najpierw ją znaleźć (po prostu wygooglować), następnie zrozumieć (czytając jej dokumentację, albo kod) i jej użyć. Koniecznie musisz nauczyć się jak korzystać z narzędzi do budowania projektu i zarządzania zależnościami. W świecie Javowym są nimi np. Maven lub Gradle. * *Sieć, TCP/IP, HTTP.* Komputery mogą się ze sobą komunikować. Twój program może “wypytywać” komputery z sieci o jakieś dane lub “serwować” dane dla innych komputerów. Od tego momentu możesz zacząć robić, programy, które korzystają z zewnętrznych interfejsów programistycznych (API) i dzięki temu mieć dostęp do najbardziej zaawansowanych algorytmów (włączając w to sztuczną inteligencję). Chcesz zrobić program do rozpoznawania obrazów? Skorzystaj z [Google Vision API](https://cloud.google.com/vision). Chcesz zrobić program, który analizuje Twitty? Podepnij się pod [API Twittera](https://developer.twitter.com/en/docs). Chcesz analizować dane NASA. Użyj ich API. Jest tego dużo, dużo więcej... (https://any-api.com/). Naucz się podstaw jak działa komunikacja w sieciach i jak wysyłać zapytania HTTP. Na pewno przyda Ci się narzędzie typu [Postman](https://www.postman.com/). Znajdź biblioteki, które to robią i zacznij pisać ciekawe programy. * *Bazy danych, SQL.* Twoje aplikacje będą przechowywać dane. Na początek w zupełności wystarczą np. zwyczajne pliki. Do pracy potrzebujesz jednak wiedzieć jak posługiwać się bazami relacyjnymi. Musisz znać SQL. * *HTML, JS (JavaScript), CSS, Przeglądarka.* Jeżeli chcesz “wystawić” swoją aplikację na świat, to musisz poznać jak działa przeglądarka. Dzięki temu możesz stworzyć appkę dostępną dla użytkowników przez Internet. Poznaj model komunikacji “klient-serwer”. Banki, e-commerce, nawet urzędy - wszystkie z nich wykorzystują ten model. Jeżeli poznasz HTML, CSS, JS, będziesz mógł tworzyć aplikacje webowe. Swoją drogą - nowoczesne przeglądarki to bardzo zaawansowane narzędzia. Naucz się obsługiwać obsługiwać się panel deweloperski Chrome (wciśnij F12). * *Frameworki.* Framework to coś więcej niż biblioteka - to “szkielet” aplikacji. Używa się ich aby nie pisać całych tysięcy linii kodu, które są nudne i trudne. Framework definiuje jak będziesz “układał” swój kod. Dzięki frameworkom (np. Spring) możesz postawić serwer, który komunikuje wyświetla jakąś stronę w przeglądarce internetowej i jest “podpięty” do bazy danych dosłownie w 15 minut. Serio. ## Git i społeczność. Jak najwcześniej poznasz system kontroli wersji - [Git](https://git-scm.com/docs/gittutorial). Znajdz dobry tutorial do nauki Gita. To jest tak samo ważne jak nauka języka programowania. Dzięki Git’owi będziesz mógł łatwo zarządzać zmianami w kodzie, wracać do poprzednich wersji, nie będziesz musiał martwić się, że coś stracisz. Git pozwala na “przechowywanie” kodu i całej historii jego zmian w tzw. repozytoriach. Dzięki system kontroli wersji, takim jak Git, programiści w pracy nad projektami są w stanie równolegle pracować nad tą samą bazą kodu. Załóż konto na [Githubie](https://github.com). Pochwal się tam innym swoim kodem. Programiści to bardzo otwarci ludzie. Lubią dzielić się swoją pracą. Na Githubie są setki tysiący repozytoriów. Szukaj ciekawych projektów i przeglądaj kod rozwijany przez innych. Naucz się czytać dokumentację i przeglądaj fachowe blogi. Dokumentacja to doskonałe źródło wiedzy. Zobacz jak przystępnie napisany jest [tutorial na oficjalnej stronie Javy](https://docs.oracle.com/javase/tutorial/java/index.html). Zaglądaj na blog i szukaj dobrych materiałów na Youtube. * https://www.baeldung.com/ * https://www.javaworld.com/ * https://www.samouczekprogramisty.pl/ * https://kobietydokodu.pl/kurs-javy/ Rozejrzyj się, czy w Twoim mieście nie ma przypadkiem spotkań grup pasjonatów Javy. W każdym większym mieście są takie. Poszukaj grup na Facebooku i Twitterze, Meetupie. ## Poznawaj narzędzia i pamiętaj o podstawach. Musisz poznać najpopularniejsze narzędzia, z którymi będziesz się spotykał. Tutaj lista rzeczy, które prawdopodobnie Ci się przydadzą: * IDE (IntelliJ, Eclipse, VSCode) - nie ważne z jakiego korzystasz. Naucz się debugować programy. Sprawdź jakie są możliwości Twojego IDE. * Linia komend, terminal Twojego systemu operacyjnego * Maven albo Gradle - narzędzia do “budowania” projektów * Bazy danych, SQL * Najważniejsze biblioteki i frameworki w Javie. * Umiejętność pisania testów jednostkowych. * Postman lub inne narzędzia do wysyłania zapytań HTTP Łatwo jest na początku zgubić się w tych wszystkich tematach pobocznych i trudno jest dobrze wyważyć ich priorytety. Z drugiej strony mnogość tematów pozwala na to, że w Twoją naukę nie wkradnie się monotonia. Wracaj w wolnych chwilach do tematów związanych z podstawami nauk o komputerach. Pamiętaj, że są rzeczy, które programista po prostu powinien kiedyś się nauczyć. “Jak zamienić liczbę zapisaną w systemie dziesiętnym na system dwójkowy? Co to jest stos i sterta? Co to jest złożoność obliczeniowa w notacji dużego O?. Co to jest graf?”. Nie pozwól jednak, aby sucha teoria zabiła Twoją chęć do nauki. Znajdź swoje tempo i konsekwentnie realizuj materiał teoretyczny. ## Podsumowanie * Pamiętaj w co jest Twoim celem. Jest to zdobycie pracy jako Junior Dev. Ucz się tego i tylko tego co pomoże Ci w zrealizowaniu tego celu. * Ucz się aktywnie! Pisz samodzielnie. Bez tego ani rusz! * W trakcie nauki korzystaj z tego, że Twoje projekty mogą być dla Ciebie ciekawe. Każdy z “kamieni milowych” o którym pisałem, pozwoli Ci na stworzenie czegoś “swojego”. Czegoś z czego będziesz dumny. To bardzo pomaga w nauce. * Programista pracuje nie tylko z kodem. Programista pracuje też z różnymi narzędziami (i z innymi ludźmi!). Zainwestuj odpowiedni czas na naukę tych narzędzi. * Otwórz się na innych. Poszukaj sobie społeczności, mentora, kolegów z którymi będziesz mógł porozmawiać. Jeżeli nie masz takich obok siebie to na pewno są gdzieś w forach i grupach na Facebooku. Powodzienia! </div>
C++
UTF-8
19,909
2.609375
3
[]
no_license
#include <string> #include <iostream> #include <utility> #include "GL.hpp" #include "gl_errors.hpp" #include "View.hpp" #include "Load.hpp" #include "data_path.hpp" #include "ColorTextureProgram.hpp" namespace view { struct RenderTextureProgram { // constructor and destructor: these are heavy weight functions // creating and freeing OpenGL resources RenderTextureProgram() { GLuint vs{0}, fs{0}; const char *VERTEX_SHADER = "" "#version 410 core\n" "in vec4 in_Position;\n" "out vec2 texCoords;\n" "void main(void) {\n" " gl_Position = vec4(in_Position.xy, 0, 1);\n" " texCoords = in_Position.zw;\n" "}\n"; const char *FRAGMENT_SHADER = "" "#version 410 core\n" "precision highp float;\n" "uniform sampler2D tex;\n" "uniform vec4 color;\n" "in vec2 texCoords;\n" "out vec4 fragColor;\n" "void main(void) {\n" " fragColor = vec4(1, 1, 1, texture(tex, texCoords).r) * color;\n" "}\n"; // Initialize shader vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &VERTEX_SHADER, 0); glCompileShader(vs); fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &FRAGMENT_SHADER, 0); glCompileShader(fs); program_ = glCreateProgram(); glAttachShader(program_, vs); glAttachShader(program_, fs); glLinkProgram(program_); // Get shader uniforms glUseProgram(program_); glBindAttribLocation(program_, 0, "in_Position"); tex_uniform_ = glGetUniformLocation(program_, "tex"); color_uniform_ = glGetUniformLocation(program_, "color"); } ~RenderTextureProgram() {} GLuint program_ = 0; GLuint tex_uniform_ = 0; GLuint color_uniform_ = 0; }; static Load<RenderTextureProgram> program(LoadTagEarly); ViewContext ViewContext::singleton_{}; const ViewContext &ViewContext::get() { if (!singleton_.is_initialized) { std::cerr << "Accessing ViewContext singleton before initialization" << std::endl; std::abort(); } return singleton_; } void ViewContext::set(const glm::uvec2 &logicalSize, const glm::uvec2 &drawableSize) { singleton_.logical_size_ = logicalSize; singleton_.drawable_size_ = drawableSize; singleton_.scale_factor_ = static_cast<float>(drawableSize.x) / logicalSize.x; singleton_.is_initialized = true; } GlyphTextureCache *GlyphTextureCache::singleton_ = nullptr; GlyphTextureCache *GlyphTextureCache::get_instance() { if (!singleton_) { singleton_ = new GlyphTextureCache; } return singleton_; } GlyphTextureCache::GlyphTextureCache() { FT_Error error = FT_Init_FreeType(&ft_library_); if (error != 0) { throw std::runtime_error("Error in initializing FreeType library"); } for (FontFace f : {FontFace::IBMPlexMono, FontFace::ComputerModernRegular, FontFace::IBMPlexSans}) { const std::string font_path = data_path(get_font_filename(f)); FT_Face face = nullptr; error = FT_New_Face(ft_library_, font_path.c_str(), 0, &face); if (error != 0) { throw std::runtime_error("Error initializing font face"); } assert(face != nullptr); font_faces_.emplace(f, face); } } GlyphTextureCache::~GlyphTextureCache() { for (const auto &p : font_faces_) { FT_Done_Face(p.second); } font_faces_.clear(); FT_Done_FreeType(ft_library_); ft_library_ = nullptr; } std::string GlyphTextureCache::get_font_filename(FontFace font_face) { switch (font_face) { case FontFace::IBMPlexMono : return "IBMPlexMono-Regular.ttf"; case FontFace::ComputerModernRegular : return "cmunorm.ttf"; case FontFace::IBMPlexSans : return "IBMPlexSans-Regular.ttf"; default: throw std::runtime_error("unreachable code"); } } void GlyphTextureCache::incTexRef(FontFace font_face, int font_size, hb_codepoint_t codepoint) { // TODO(xiaoqiao): manage the calls to GL_UNPACK_ALIGNMENT more carefully. glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GlyphTextureKey key{font_face, font_size, codepoint}; auto it = map_.find(key); if (it != map_.end()) { it->second.ref_cnt++; return; } else { FT_Face face = font_faces_.at(font_face); if (FT_Set_Pixel_Sizes(face, 0, ViewContext::compute_physical_px(font_size)) != 0) { throw std::runtime_error("Error setting char size"); } if (FT_Load_Glyph(face, codepoint, FT_LOAD_DEFAULT) != 0) { throw std::runtime_error("Error loading glyph"); std::cout << "Error rendering glyph" << std::endl; } if (FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL) != 0) { throw std::runtime_error("Error rendering glyph"); std::cout << "Error rendering glyph" << std::endl; } auto glyph = face->glyph; size_t buffer_len = glyph->bitmap.width * glyph->bitmap.rows; // I haven't figured out a proper way to deal with GlyphTextureEntry // copy / move constructor, as a result, I have to use this std::piecewise_construct // trick to make sure no copy/move constructor is called. auto emplace_result_pair = map_.emplace(std::piecewise_construct, std::forward_as_tuple(font_face, font_size, codepoint), std::forward_as_tuple( std::vector<uint8_t>(glyph->bitmap.buffer, glyph->bitmap.buffer + buffer_len), glyph->bitmap_left, glyph->bitmap_top, glyph->bitmap.width, glyph->bitmap.rows, 1)); glBindTexture(GL_TEXTURE_2D, emplace_result_pair.first->second.gl_texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, glyph->bitmap.width, glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, glyph->bitmap.buffer); glBindTexture(GL_TEXTURE_2D, 0); } } const GlyphTextureCache::GlyphTextureEntry *GlyphTextureCache::getTextRef(FontFace font_face, int font_size, hb_codepoint_t codepoint) { GlyphTextureKey key{font_face, font_size, codepoint}; return &map_.at(key); } void GlyphTextureCache::decTexRef(FontFace font_face, int font_size, hb_codepoint_t codepoint) { GlyphTextureKey key{font_face, font_size, codepoint}; auto it = map_.find(key); assert(it != map_.end()); assert(it->second.ref_cnt > 0); if (it->second.ref_cnt == 1) { map_.erase(it); } else { it->second.ref_cnt--; } } FT_Face GlyphTextureCache::get_free_type_face(FontFace font_face) { return font_faces_.at(font_face); } GlyphTextureCache::GlyphTextureEntry::GlyphTextureEntry(const std::vector<uint8_t> &bitmap, int bitmapLeft, int bitmapTop, int width, int height, int refCnt) : bitmap(bitmap), bitmap_left(bitmapLeft), bitmap_top(bitmapTop), width(width), height(height), ref_cnt(refCnt) { glGenTextures(1, &gl_texture_id); } GlyphTextureCache::GlyphTextureEntry::~GlyphTextureEntry() { glDeleteTextures(1, &gl_texture_id); } bool GlyphTextureCache::GlyphTextureKey::operator<(const GlyphTextureCache::GlyphTextureKey &rhs) const { return std::tie(font_face, font_size, codepoint) < std::tie(rhs.font_face, rhs.font_size, rhs.codepoint); } GlyphTextureCache::GlyphTextureKey::GlyphTextureKey(FontFace fontFace, int fontSize, hb_codepoint_t codepoint) : font_face(fontFace), font_size(fontSize), codepoint(codepoint) {} TextSpan::TextSpan() { scale_factor_ = get_scale_physical(); // initialize opengl resources glGenBuffers(1, &vbo_); glGenVertexArrays(1, &vao_); glGenSamplers(1, &sampler_); glSamplerParameteri(sampler_, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glSamplerParameteri(sampler_, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glSamplerParameteri(sampler_, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glSamplerParameteri(sampler_, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Set some initialize GL state glEnable(GL_BLEND); glDisable(GL_CULL_FACE); // glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); hb_buffer_ = hb_buffer_create(); if (hb_buffer_ == nullptr) { throw std::runtime_error("Error in creating harfbuzz buffer"); } } TextSpan::TextSpan(const TextSpan &that) { set_text(that.text_); set_font(that.font_); set_font_size(that.font_size_); set_position(that.position_); set_color(that.color_); animation_speed_ = that.animation_speed_; callback_ = that.callback_; is_visible_ = that.is_visible_; total_time_elapsed_ = that.total_time_elapsed_; visible_glyph_count_ = that.visible_glyph_count_; } TextSpan &TextSpan::operator=(const TextSpan &that) { if (this == &that) { // skip self assignment return *this; } undo_render(); set_text(that.text_); set_font(that.font_); set_font_size(that.font_size_); set_position(that.position_); set_color(that.color_); animation_speed_ = that.animation_speed_; callback_ = that.callback_; is_visible_ = that.is_visible_; total_time_elapsed_ = that.total_time_elapsed_; visible_glyph_count_ = that.visible_glyph_count_; return *this; } TextSpan::~TextSpan() { undo_render(); hb_buffer_destroy(hb_buffer_); hb_buffer_ = nullptr; glDeleteBuffers(1, &vbo_); glDeleteSamplers(1, &sampler_); glDeleteVertexArrays(1, &vao_); } void TextSpan::update(float elapsed) { if (is_visible_ && animation_speed_.has_value() && visible_glyph_count_ < glyph_count_) { // show "appear letters one by one" animation total_time_elapsed_ += elapsed; visible_glyph_count_ = std::min(static_cast<unsigned>(total_time_elapsed_ * animation_speed_.value()), glyph_count_); if (visible_glyph_count_ == glyph_count_ && callback_.has_value()) { (*callback_)(); } } } void TextSpan::draw() { if (!is_visible_) { return; } do_render(); // Bind Stuff GL_ERRORS(); glBindSampler(0, sampler_); glBindVertexArray(vao_); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vbo_); glUseProgram(program->program_); glm::vec4 color_fp = glm::vec4(color_) / 255.0f; glUniform4f(program->color_uniform_, color_fp.x, color_fp.y, color_fp.z, color_fp.w); glUniform1i(program->tex_uniform_, 0); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GL_ERRORS(); float cursor_x = cursor_.x, cursor_y = cursor_.y - float(font_size_) * 2.0f / ViewContext::get().logical_size_.y; GlyphTextureCache *cache = GlyphTextureCache::get_instance(); size_t shown_glyph_count = animation_speed_.has_value() ? visible_glyph_count_ : glyph_count_; assert(shown_glyph_count <= glyph_count_); for (size_t i = 0; i < shown_glyph_count; ++i) { hb_codepoint_t glyphid = glyph_info_[i].codepoint; float x_offset = glyph_pos_[i].x_offset / 64.0f; float y_offset = glyph_pos_[i].y_offset / 64.0f; float x_advance = glyph_pos_[i].x_advance / 64.0f; float y_advance = glyph_pos_[i].y_advance / 64.0f; auto *glyph_texture = cache->getTextRef(font_, font_size_, glyphid); assert(glyph_texture != nullptr); const float vx = cursor_x + x_offset + glyph_texture->bitmap_left * scale_factor_.x; const float vy = cursor_y + y_offset + glyph_texture->bitmap_top * scale_factor_.y; const float w = glyph_texture->width * scale_factor_.x; const float h = glyph_texture->height * scale_factor_.y; struct { float x, y, s, t; } data[6] = { {vx, vy, 0, 0}, {vx, vy - h, 0, 1}, {vx + w, vy, 1, 0}, {vx + w, vy, 1, 0}, {vx, vy - h, 0, 1}, {vx + w, vy - h, 1, 1} }; glBindTexture(GL_TEXTURE_2D, glyph_texture->gl_texture_id); glActiveTexture(GL_TEXTURE0); glBufferData(GL_ARRAY_BUFFER, 24 * sizeof(float), data, GL_DYNAMIC_DRAW); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_TRIANGLES, 0, 6); glBindTexture(GL_TEXTURE_2D, 0); cursor_x += x_advance * scale_factor_.x; cursor_y += y_advance * scale_factor_.y; } // glPixelStorei(GL_UNPACK_ALIGNMENT, 4); GL_ERRORS(); } void TextSpan::redo_shape() { undo_render(); do_render(); } TextSpan &TextSpan::set_text(std::string text) { if (this->text_ == text) { return *this; } undo_render(); this->text_ = std::move(text); return *this; } TextSpan &TextSpan::set_font(FontFace font_face) { undo_render(); font_ = font_face; return *this; } TextSpan &TextSpan::set_font_size(unsigned font_size) { undo_render(); font_size_ = font_size; return *this; } TextSpan &TextSpan::set_position(int x, int y) { set_position(glm::ivec2(x, y)); return *this; } TextSpan &TextSpan::set_position(glm::ivec2 pos) { position_ = pos; cursor_.x = 2.0f * float(position_.x) / float(ViewContext::get().logical_size_.x) - 1.0f; cursor_.y = -2.0f * float(position_.y) / float(ViewContext::get().logical_size_.y) + 1.0f; return *this; } TextSpan &TextSpan::set_color(glm::u8vec4 color) { color_ = color; return *this; } TextSpan &TextSpan::disable_animation() { animation_speed_ = std::nullopt; callback_ = std::nullopt; return *this; } TextSpan &TextSpan::set_animation(float speed, std::optional<std::function<void()>> callback) { if (speed <= 0.0f) { throw std::invalid_argument("appear_by_letter_speed must be either empty or a positive float"); } animation_speed_ = speed; callback_ = callback; return *this; } TextSpan &TextSpan::set_visibility(bool value) { is_visible_ = value; return *this; } int TextSpan::get_width() { do_render(); float width = 0.0f; for (size_t i = 0; i < glyph_count_; ++i) { float x_advance = glyph_pos_[i].x_advance / 64.0f; width += x_advance / ViewContext::get().scale_factor_; } return (int) lround(width); } void TextSpan::undo_render() { if (!text_is_rendered_) { return; } GlyphTextureCache *cache = GlyphTextureCache::get_instance(); for (size_t i = 0; i < glyph_count_; ++i) { hb_codepoint_t glyphid = glyph_info_[i].codepoint; cache->decTexRef(font_, font_size_, glyphid); } hb_buffer_reset(hb_buffer_); glyph_count_ = 0; glyph_info_ = nullptr; glyph_pos_ = nullptr; text_is_rendered_ = false; } void TextSpan::do_render() { if (text_is_rendered_) { return; } GlyphTextureCache *cache = GlyphTextureCache::get_instance(); // TODO(xiaoqiao): is there a better way to handle font size setting? FT_Face ft_face = cache->get_free_type_face(font_); if (FT_Set_Pixel_Sizes(ft_face, 0, ViewContext::compute_physical_px(font_size_)) != 0) { throw std::runtime_error("Error setting char size"); } hb_font_t *hb_font = hb_ft_font_create_referenced(ft_face); assert(hb_font != nullptr); hb_buffer_reset(hb_buffer_); hb_buffer_add_utf8(hb_buffer_, text_.c_str(), -1, 0, (int)text_.size()); hb_buffer_set_direction(hb_buffer_, HB_DIRECTION_LTR); hb_buffer_set_script(hb_buffer_, HB_SCRIPT_LATIN); hb_buffer_set_language(hb_buffer_, hb_language_from_string("en", -1)); hb_shape(hb_font, hb_buffer_, nullptr, 0); glyph_info_ = hb_buffer_get_glyph_infos(hb_buffer_, &glyph_count_); glyph_pos_ = hb_buffer_get_glyph_positions(hb_buffer_, &glyph_count_); for (size_t i = 0; i < glyph_count_; ++i) { hb_codepoint_t glyphid = glyph_info_[i].codepoint; cache->incTexRef(font_, font_size_, glyphid); } hb_font_destroy(hb_font); text_is_rendered_ = true; } void TextBox::update(float elapsed) { for (auto &line : lines_) { line->update(elapsed); } } void TextBox::draw() { for (auto &line : lines_) { line->draw(); } } TextBox &TextBox::set_contents(std::vector<std::pair<glm::u8vec4, std::string>> contents) { contents_ = std::move(contents); lines_.clear(); for (size_t i = 0; i < contents_.size(); i++) { auto text_line_ptr = std::make_shared<TextSpan>(); text_line_ptr->set_text(contents_.at(i).second) .set_color(contents_.at(i).first) .set_font(font_face_) .set_font_size(font_size_) .set_position(position_.x, position_.y + int(font_size_ + line_space_) * int(i)); lines_.push_back(text_line_ptr); } return *this; } TextBox &TextBox::set_position(glm::ivec2 pos) { position_ = pos; for (size_t i = 0; i < lines_.size(); i++) { auto text_line_ptr = lines_.at(i); text_line_ptr->set_position(position_.x, position_.y + int(font_size_ * i + line_space_ * i)); } return *this; } TextBox &TextBox::set_line_space(int line_space) { line_space_ = line_space; for (size_t i = 0; i < lines_.size(); i++) { auto text_line_ptr = lines_.at(i); text_line_ptr->set_position(position_.x, position_.y + int(font_size_ * i + line_space_ * i)); } return *this; } TextBox &TextBox::set_font_size(unsigned font_size) { font_size_ = font_size; return *this; } TextBox &TextBox::set_font_face(FontFace font_face) { font_face_ = font_face; for (auto &text_line_ptr : lines_) { text_line_ptr->set_font(font_face); } return *this; } TextBox &TextBox::disable_animation() { animation_speed_ = std::nullopt; callback_ = std::nullopt; for (auto &text_line : lines_) { text_line->disable_animation(); } return *this; } TextBox &TextBox::set_animation(float speed, std::optional<std::function<void()>> callback) { animation_speed_ = speed; callback_ = callback; for (size_t i = 0; i < lines_.size(); i++) { auto text_line_ptr = lines_.at(i); std::optional<std::function<void()>> line_callback; if (i + 1 < lines_.size()) { line_callback = [i, this]() { this->lines_.at(i + 1)->set_visibility(true); }; } else { line_callback = callback; } text_line_ptr->set_animation(speed, line_callback); } return *this; } TextBox &TextBox::show() { if (animation_speed_.has_value()) { if (!lines_.empty()) { lines_.at(0)->set_visibility(true); for (size_t i = 1; i < lines_.size(); i++) { lines_.at(i)->set_visibility(false); } } } else { for (auto &line : lines_) { line->set_visibility(true); } } return *this; } Rectangle::Rectangle(glm::ivec2 position, glm::ivec2 size) : visibility_{true}, position_{position}, size_{size} {} void Rectangle::set_visibility(bool value) { visibility_ = value; } void Rectangle::set_position(glm::ivec2 position) { position_ = position; } void Rectangle::set_size(glm::ivec2 size) { size_ = size; } //void Rectangle::draw() { // if (!visibility_) { return; } // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // //don't use the depth test: // glDisable(GL_DEPTH_TEST); // // //upload vertices to vertex_buffer: // glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); //set vertex_buffer as current // glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vertices[0]), vertices.data(), GL_STREAM_DRAW); //upload vertices array // glBindBuffer(GL_ARRAY_BUFFER, 0); // // //set color_texture_program as current program: // glUseProgram(color_texture_program->program); // // //upload OBJECT_TO_CLIP to the proper uniform location: // glUniformMatrix4fv(color_texture_program->OBJECT_TO_CLIP_mat4, 1, GL_FALSE, glm::value_ptr(court_to_clip)); // // //use the mapping vertex_buffer_for_color_texture_program to fetch vertex data: // glBindVertexArray(vertex_buffer_for_color_texture_program); // // //bind the solid white texture to location zero so things will be drawn just with their colors: // glActiveTexture(GL_TEXTURE0); // glBindTexture(GL_TEXTURE_2D, white_tex); // // //run the OpenGL pipeline: // glDrawArrays(GL_TRIANGLES, 0, GLsizei(vertices.size())); // // //unbind the solid white texture: // glBindTexture(GL_TEXTURE_2D, 0); // // //reset vertex array to none: // glBindVertexArray(0); // // //reset current program to none: // glUseProgram(0); // //} }
JavaScript
UTF-8
643
2.578125
3
[]
no_license
const CHANGE_OBJECT_TYPE = Object.freeze({ DELETION: 0, INSERTION: 1, }); const privateProps = new WeakMap(); class ChangeObject { constructor(position, value, CHANGE_OBJECT_TYPE) { privateProps.set(this, {position: position, value: value, type: CHANGE_OBJECT_TYPE}); } getRow() { return this.getPosition().getRow(); }; getColumn() { return this.getPosition().getColumn(); }; getPosition() { return privateProps.get(this).position; }; getValue() { return privateProps.get(this).value; }; getType() { return privateProps.get(this).type; } } export {ChangeObject, CHANGE_OBJECT_TYPE};
C#
UTF-8
4,310
2.5625
3
[]
no_license
using System; using System.Collections.Generic; using System.Web; using System.Web.Caching; using InverGrove.Domain.Exceptions; using InverGrove.Domain.Extensions; using InverGrove.Domain.Interfaces; using InverGrove.Domain.Utils; namespace InverGrove.Domain.Services { public class SermonService : ISermonService { private readonly ISermonRepository sermonRepository; public SermonService(ISermonRepository sermonRepository) { this.sermonRepository = sermonRepository; } /// <summary> /// Adds the sermon. /// </summary> /// <param name="newSermon">The new sermon.</param> /// <returns></returns> /// <exception cref="ParameterNullException">newSermon</exception> public int AddSermon(ISermon newSermon) { if (newSermon == null) { throw new ParameterNullException("newSermon"); } var sermonId = this.sermonRepository.Add(newSermon); newSermon.SermonId = sermonId; if ((HttpContext.Current.Cache != null) && (HttpContext.Current.Cache["Sermons"] != null)) { var sermonsCollection = (List<ISermon>)HttpContext.Current.Cache["Sermons"]; sermonsCollection.Add(newSermon); HttpContext.Current.Cache["Sermons"] = sermonsCollection; } return sermonId; } /// <summary> /// Deletes the sermon. /// </summary> /// <param name="sermonId">The sermon identifier.</param> public void DeleteSermon(int sermonId) { Guard.ParameterNotOutOfRange(sermonId, "sermonId"); this.sermonRepository.Delete(sermonId); this.sermonRepository.Save(); this.RemoveCollectionFromCache(); } /// <summary> /// Gets the sermon. /// </summary> /// <param name="sermonId">The identifier.</param> /// <returns></returns> public ISermon GetSermon(int sermonId) { Guard.ParameterNotOutOfRange(sermonId, "sermonId"); return this.sermonRepository.GetById(sermonId).ToModel(); } /// <summary> /// Gets the sermons. /// </summary> /// <returns></returns> public IEnumerable<ISermon> GetSermons() { var sermons = new List<ISermon>(); if ((HttpContext.Current.Cache != null) && (HttpContext.Current.Cache["Sermons"] != null)) { sermons = (List<ISermon>)HttpContext.Current.Cache["Sermons"]; } else { var sermonsCollection = this.sermonRepository.Get(); sermons.AddRange(sermonsCollection.ToModelCollection()); this.AddCollectionToCache(sermons); } return sermons; } /// <summary> /// Updates the sermon. /// </summary> /// <param name="sermonToUpdate">The sermon to update.</param> /// <returns></returns> /// <exception cref="ParameterNullException">sermonToUpdate</exception> public bool UpdateSermon(ISermon sermonToUpdate) { if (sermonToUpdate == null) { throw new ParameterNullException("sermonToUpdate"); } try { this.sermonRepository.Update(sermonToUpdate); this.RemoveCollectionFromCache(); } catch (Exception) { return false; } return true; } private void AddCollectionToCache(IEnumerable<ISermon> sermons) { if (HttpContext.Current.Cache != null) { HttpContext.Current.Cache.Add("Sermons", sermons, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 12, 0, 0), CacheItemPriority.Normal, null); } } private void RemoveCollectionFromCache() { if ((HttpContext.Current.Cache != null) && (HttpContext.Current.Cache["Sermons"] != null)) { HttpContext.Current.Cache.Remove("Sermons"); } } } }
Python
UTF-8
4,421
2.5625
3
[ "Apache-2.0" ]
permissive
import json import sys import os import glob import click from jsonschema import validate, ValidationError, SchemaError, Draft7Validator stats = { 'validationFailures': 0, 'validationSuccesses': 0, 'skipped': 0, 'successPush': 0, 'failedPush': 0, } timing_groups = [ "1xDaily", "2xDaily", "3xDaily", "7xDaily", "Mondays", "Fridays", "Weekdays", "FirstofMonth", ] def load_schema(schema_json) -> 'jsonschema.validators.create.<locals>.Validator': return Draft7Validator(schema_json) def check_json_contents(schema, json_contents) -> []: try: return sorted(schema.iter_errors(json_contents), key=str) except SchemaError as e: print("There is an error with the schema") raise except Exception as e: print(f'Exception: {e}') raise def display_stats_summary(): click.secho(f'\n\n\n\n### Summary', bold=True) click.secho(f'File validation failure count: {stats["validationFailures"]}', fg='red') click.secho(f'File validation success count: {stats["validationSuccesses"]}', fg='green') click.secho(f'\tSkipped DDB pushes: {stats["skipped"]}', fg='blue') click.secho(f'\tSuccessful pushes: {stats["successPush"]}', fg='green') click.secho(f'\tFailed pushes: {stats["failedPush"]}', fg='red', bold=True) def is_sub_in_ddb(id): return None def validated_workflow(fileContents, timing_group): for i in range(len(fileContents)): ddb = is_sub_in_ddb(fileContents[i]['id']) if ddb is not None: click.secho(f'\nSubscription exists do you want to update it from:') click.secho(f'{json.dumps(ddb, sort_keys=True, indent=4)}', fg='red') click.secho(f'to:') click.secho(f'{json.dumps(fileContents[i], sort_keys=True, indent=4)}', fg='green') check = input(click.style('Do you want to proceed (y/n/exit)? ', bold=True)) if check == "exit": click.secho("Exiting run...", fg='blue') stats['aborts'] += (len(fileContents) - i) return elif check != "y": click.secho("Skipping...", fg='blue') stats['skipped'] += 1 continue item = { "timing_group": {"S": timing_group}, } for key, val in fileContents[i].items(): item[key] = {"S": val} print(f'Pushing to DDB. STUB! {json.dumps(item, indent=4)}') # TODO validity check with exceptions if ddb_works(): else stats['failedPush'] += 1 stats['successPush'] += 1 def validate_file(schema, index, file, timing_group): with open(file, 'r') as js: fileContents = json.load(js) click.secho(f'## Validating file #{index}: {file}', nl=False, bold=True) errors = check_json_contents(schema, fileContents) if len(errors) == 0: click.secho(' - Validated', fg='green', bold=True) stats['validationSuccesses'] += 1 validated_workflow(fileContents, timing_group) else: click.secho(' - Errors present', fg='red', bold=True) stats['validationFailures'] += 1 for index, error in enumerate(errors, start=1): print(f'{index}: {error.message} - {error.relative_path}') print('\n------\n') @click.command() @click.option('--timing_group', '-g', prompt='How often do you wish this file to run?', help='Select the applicable timing for this file/folder.', type=click.Choice(timing_groups, case_sensitive=True)) @click.option('--schema', '-s', default='./schema.json', help='Specifies which schema to validate the inputs against.') @click.option('--json_file_folder', '-j', default='./test_json_files/', help='Specifies the folder or JSON file to be validated.') def main(schema, json_file_folder, timing_group): with open(schema, 'r') as s: schema_json = json.load(s) schema = load_schema(schema_json) if os.path.isfile(json_file_folder): validate_file(schema, 1, json_file_folder, timing_group) else: for index, file in enumerate(sorted(glob.glob(json_file_folder + "/**/*.json", recursive=True)), start=1): # Only processes it if it's a file, rather than a folder. if os.path.isfile(file): validate_file(schema, index, file, timing_group) display_stats_summary() if __name__ == '__main__': main()
Python
UTF-8
1,335
3.40625
3
[]
no_license
''' 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用一次。 说明: 所有数字(包括目标数)都是正整数。 解集不能包含重复的组合。  示例 1: 输入: candidates = [10,1,2,7,6,1,5], target = 8, 所求解集为: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] 示例 2: 输入: candidates = [2,5,2,1,2], target = 5, 所求解集为: [   [1,2,2],   [5] ] ''' class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ def backtrack(i, tmp_sum, tmp): if tmp_sum == target: res.append(tmp) return for j in range(i, n): if tmp_sum + candidates[j] > target: break if j > i and candidates[j] == candidates[j-1]: continue backtrack(j + 1, tmp_sum + candidates[j], tmp + [candidates[j]]) if not candidates: return [] candidates.sort() n = len(candidates) res = [] backtrack(0, 0, []) return res
Python
UTF-8
811
3.21875
3
[]
no_license
class college: def __init__(self,name,place,pincode): self.college_name=name self.college_place=place self.college_pincode=pincode def getCDetails(self): print("College: ",self.college_name,"\nPlace: ",self.college_place,"\nPincode: ",self.college_pincode) class student(college): def __init__(self,name,usn,branch,college_name,college_place,college_pincode): self.name=name self.usn=usn self.branch=branch college.__init__(self,college_name,college_place,college_pincode) def getStdDetails(self): print("name: ",self.name,"\nUsn: ",self.usn,"\nBanch: ",self.branch) s=student("Kannan","4jk17cs025","cse","AJIET","mangaluru",575013) s.getStdDetails() s.getCDetails()
Java
UTF-8
3,481
3.828125
4
[]
no_license
package DAILY_PRACTICE; import java.util.Arrays; public class Frist { /* public static void main(String[] args) { * 석차구하기 : 모든 점수가 1등올 시작해서 다른 점수들과비교해 자신의 점수가 작으면 1씩 증가시키는 방식 * 선택정렬 : 첫번째 숫자부터 그 뒤의 모든 숫자들과 비교해서 작은수와 자리바꾸기를 반복해서 앞에서부터 작은 수를 채워가는 방식 * 버블정렬 : 첫번째 숫자부터 바로 뒷 숫자와 비교해서 작은수와 자리 바꾸기를 반복해 뒤에서부터 큰 수를 채워나가는 방식 * 삽입정렬 : 두번째 숫자부터 그 앞의 모든 숫자들과 비교해서 큰수들을 뒤로 밀고 중간에 삽입하는 방식 int[] numbers = new int[10]; for(int i = 0; i < numbers.length; i++){ numbers[i] = (int)(Math.random() * 100) + 1; } System.out.println(Arrays.toString(numbers)); //석차구하기: 모든 점수가 1등으로 시작해서 다른 점수들과 비교해 자신의 점수가 작으면 1씩 증가시키는 방식 printRank(numbers); //선택정렬: 첫번째 숫자부터 그 뒤의 모든 숫자들과 비교해서 작은 수와 자리바꾸기를 반복해서 앞에서부터 작은 수를 채워가는 방식 selectSort(numbers); //버블정렬: 첫번째 숫자부터 바로 뒷 숫자와 비교해서 작은 수와 자리 바꾸기를 반복해 뒤에서 부터 큰 수를 채워가는 방식 bubbleSort(numbers); //삽입정렬: 두번째 숫자부터 그 앞의 모든 숫자들과 비교해서 큰 수들을 뒤로 밀고 중간에 삽입하는 방식 insertSort(numbers); } private static void insertSort(int[] numbers) { } private static void bubbleSort(int[] numbers) { for(int i = 0; i < numbers.length; i++){ for(int j = 1; j <numbers.length; j++){ if(numbers[j-1] > numbers[j]){ int temp = numbers[j]; numbers[j] = numbers[j-1]; numbers[j-1] = temp; } } } System.out.println(Arrays.toString(numbers)); } private static void selectSort(int[] numbers) { for(int i = 0; i < numbers.length; i++){ for(int j = 0; j < numbers.length; j++){ if(numbers[i] < numbers[j]){ int temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] =temp; } } } System.out.println(Arrays.toString(numbers)); } private static void printRank(int[] numbers) { int[] rank = new int[numbers.length]; for(int i = 0; i < rank.length; i++){ rank[i] = 1; } for(int i = 0; i < numbers.length; i++){ for(int j = 0; j <numbers.length; j++){ if(numbers[i] < numbers[j]){ rank[i] += 1; } } } System.out.println(Arrays.toString(rank)); } } */ public static void main(String[] args) { char[][] star = { {'*','*',' ',' ',' '}, {'*','*',' ',' ',' '}, {'*','*','*','*','*'}, {'*','*','*','*','*'} }; char[][] result = new char[star[0].length][star.length]; for(int i=0; i < star.length;i++) { for(int j=0; j < star[i].length;j++) { System.out.print(star[i][j]); } System.out.println(); } System.out.println(); for(int i=0; i < star.length;i++) { for(int j=0; j < star[i].length;j++) { int x = j; int y = star.length-1-i; result[x][y]=star[i][j]; } } for(int i=0; i < result.length;i++) { for(int j=0; j < result[i].length;j++) { System.out.print(result[i][j]); } System.out.println(); } } // end of main } // end of class
Java
UTF-8
3,230
2.359375
2
[]
no_license
package com.example.springbootmybatis.controller; import com.example.springbootmybatis.annotations.CheckRepeatSubmit; import com.example.springbootmybatis.aop.HttpLister; import com.example.springbootmybatis.entity.User; import com.example.springbootmybatis.service.UserService; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.*; import java.util.concurrent.ExecutionException; @RestController @RequestMapping("/yff") @Slf4j public class UserController { private static Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired UserService userService; //保证幂等性的一种方法, 查询方法本身就是幂等的 private Map<String,Object> map = new HashMap<>(); @GetMapping("/hello") public String hello() { return "hello"; } /** * 登录 */ @PostMapping("/login") public void getUserByUserNameAndPassword(@RequestBody User user, HttpSession session) { String id = String.valueOf(user.getId()); logger.info("用户【"+id+"】登陆开始!"); session.setAttribute(id,id); logger.info("用户【"+id+"】登陆成功!"); } /** *查询在线人数 */ @RequestMapping("/online") public Object online() { return "当前在线人数:" + HttpLister.online + "人"; } /** * 退出登录 */ @RequestMapping("/out") public Object Logout(@RequestBody User user, HttpServletRequest request) { logger.info("用户退出登录开始!"); HttpSession session = request.getSession(false);//防止创建Session if(session != null){ session.removeAttribute(String.valueOf(user.getId())); session.invalidate(); } logger.info("用户退出登录结束!{}",user.getId()); return "退出成功!"; } @CheckRepeatSubmit @PostMapping("/queryinfo") public Object queryInfo(@RequestBody User user){ String id = String.valueOf(user.getId()); if(StringUtils.isEmpty(id)){ return "输入查询参数"; } List<User> list = userService.queryInfo(id); return list; } @PostMapping("/queryall") public Object queryall(@RequestBody User user) throws ExecutionException, InterruptedException { // String id = String.valueOf(user.getId()); // if(StringUtils.isEmpty(id)){ // return "输入查询参数"; // } List<User> list = userService.queryall(); return list; } @PostMapping("/insert") public Object insert(@RequestBody User user){ boolean b = map.containsKey(user.getName()); if(b){ return "新增重复"; }else{ map.put(user.getName(),user.getName()); } // CheckRepeatData.ins().CheckRepeatData(new ArrayList<>()); return userService.insert(user); } }
Python
UTF-8
2,020
2.6875
3
[]
no_license
from collections import deque from copy import deepcopy import heapq from itertools import combinations, permutations from itertools import combinations_with_replacement import sys input = lambda: sys.stdin.readline().rstrip() test = True if test: try: sys.stdin = open('input_data.txt', 'r') print('sys.stdin = input.txt') except FileNotFoundError: pass rr, cc, k = map(int, input().split()) board = [[0] * 100 for _ in range(100)] for i in range(3): a = list(map(int, input().split())) for j in range(3): board[i][j] = a[j] r, c = 3, 3 for t in range(101): if board[rr - 1][cc - 1] == k: print(t) exit(0) if r >= c: nc = 0 for i in range(r): cnt = [0] * 101 for j in range(c): cnt[board[i][j]] += 1 tmp = [] for j in range(1, 101): if cnt[j] > 0: tmp.append((j, cnt[j])) tmp.sort(key=lambda x: x[0]) tmp.sort(key=lambda x: x[1]) ret = [] for x, y in tmp: ret.append(x) ret.append(y) board[i] = ret + ([0] * (100 - len(ret))) nc = max(nc, len(ret)) c = nc else: nr = 0 for j in range(c): cnt = [0] * 101 for i in range(r): if board[i][j] < 0: break cnt[board[i][j]] += 1 tmp = [] for i in range(1, 101): if cnt[i] > 0: tmp.append((i, cnt[i])) tmp.sort(key=lambda x: x[0]) tmp.sort(key=lambda x: x[1]) ret = [] for x, y in tmp: ret.append(x) ret.append(y) nr = max(nr, len(ret)) for i in range(100): if i < len(ret): board[i][j] = ret[i] else: board[i][j] = 0 r = nr print(-1)
Markdown
UTF-8
2,029
4.0625
4
[]
no_license
## Java变量 1. 在程序设计中,变量是指一个包含值的存储地址以及对应的符号名称。 &nbsp; 2. 创建变量:声明变量 >* 给变量命名 >* 定义变量的数据类型 &emsp;&emsp;` DataType 变量名;` &emsp;&emsp;`int a` &emsp;&emsp;`char b` &emsp;&emsp;`int age` &emsp;&emsp;`int number` 3. 给变量赋值 ``` int a; a = 1; ``` ``` int a = 1; ``` &emsp;&emsp;创建多个**类型相同**的变量 ``` int a, b; a = 1; b = 2; ``` int a = 1; b = 2; <br/> &emsp;&emsp;在作用域范围内,变量的值能够随时访问或重新赋值 ## 命名规范 * **变量的名称可以是任何合法的标识符,以字母,美元符号 $ 或下划线_开头。** 但是,按照约定俗成,变量应始终以字母开头,不推荐使用美元符号和下划线开头; * **开头后续的字符可以是字母、数字、美元符号或下划线。** * **变量命名区分大小写** * **变量命名应采用小驼峰命名法。** * **如果变量存储了一个常量值,要将每个字母大写并用下划线字符分隔每个单词。** <br/> ## 常量 &emsp;&emsp; 所谓常量,就是恒常不变的量。我们可以将常量理解成一种特殊的变量。 &emsp;&emsp;与变量不同的是,一旦它被赋值后,在程序的运行过程中不允许被改变。常量使用 final 关键字修饰: &emsp;&emsp;final DataType 常量名 = 常量值; * 常量的命名规范与普通变量有所不同,要将每个字母大写并用下划线字符分隔每个单词。 ## 变量种类 - 实例变量(见代码中 instanceVariable) - 类变量(见代码中 classVariable) - 局部变量(见代码中 localVariable) - 参数(见代码中 parameter 和 args) #### 实例变量 &emsp;&emsp;实例变量用于存储对象的状态,它的值对于类的每个实例都是唯一的,每个对象都拥有自己的变量副本。只要相应的对象存在于内存中,它就占用着存储空间。
Java
UTF-8
976
2.71875
3
[]
no_license
package qf.jdbc.datasource.custom; import qf.jdbc.Utils; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import static qf.jdbc.DatabaseConfiguration.*; public class MyDataSourceTest { public static void main(String[] args) throws SQLException { DataSourceConfig config = new DataSourceConfig( DRIVER, Utils.connectionUrl(HOST, PORT, DATABASE, CONNECTION_PARAMS), USER, PASSWORD ); MyDataSource dataSource = new MyDataSource(config); List<Connection> connections = new ArrayList<>(); for (int i = 0; i < 10; i++) { Connection connection = dataSource.getConnection(); System.out.println(connection); connections.add(connection); } for (Connection connection : connections) { connection.close(); System.out.println(dataSource); } System.out.println(dataSource); System.out.println("close connections: " + dataSource.close()); } }
Java
UTF-8
4,423
2.515625
3
[ "Zlib" ]
permissive
/* * Copyright (C) 2018 Fionn Langhans */ package feder.types; import java.util.LinkedList; import java.util.List; import feder.FederCompiler; /** * @author Fionn Langhans * @ingroup types */ public class FederInterface extends FederBody implements FederArguments, FederHeaderGen { /** * The arguments of the interface */ public List<FederObject> arguments = new LinkedList<>(); /** * The result type of the interface/function */ public FederBinding returnType; /** * False: You can't call the function described by this object * * True: You can call the function described by this object */ private boolean cancall = false; @SuppressWarnings("unchecked") /** * @param compiler0 The compiler instance to use * @param name0 The name of the interface * @param parent The parent of this body */ public FederInterface(FederCompiler compiler0, String name0, FederBody parent) { super(compiler0, name0, parent); } /** * @param compiler0 The compiler instance to use * @param name The name of the callable interface * @param parent The parent of the interface * @return Returns a callable interface from a not callable one */ public FederInterface interfaceFrom(FederCompiler compiler0, String name, FederBody parent) { if (cancall) { throw new RuntimeException("Cannot create interface from" + " already object-interface"); } return new FederInterface(compiler0, name, parent, arguments, returnType); } @SuppressWarnings("unchecked") /** * @param compiler0 The compiler instance to use * @param name0 The name of the interface * @param parent The parent of this body * @param arguments0 The arguments of the interface * @param returnType0 The result type of this interface */ public FederInterface(FederCompiler compiler0, String name0, FederBody parent, List<FederObject> arguments0, FederBinding returnType0) { super(compiler0, name0, parent); arguments = arguments0; returnType = returnType0; cancall = true; } @Override /** * @return Returns the name for C source code */ public String generateCName() { if (canBeCalled()) { String infrontofname = ""; if (getParent() != null && getParent() instanceof FederNamespace) { String namespacestostr = ((FederNamespace) getParent()).getNamespacesToString(); infrontofname = (namespacestostr.isEmpty() ? "" : ("0" + namespacestostr)) + "0"; } return "federobj_" + infrontofname + getName(); } String result = "0" + getName(); return "fdint_" + getNamespacesToString() + result; } @Override /** * @return Returns the arguments required by this interface */ public List<FederObject> getArguments() { return arguments; } @Override /** * @param name If null, every name gets accepted * @param arguments0 The arguments if the function/interface * @return Returns true, if this interface is "the same" as the one described by name and arguments0 */ public boolean isEqual(String name, List<FederBinding> arguments0) { return FederFunction.isEqual(name, arguments0, getArguments(), getName()); } @Override /** * @return Can be null, otherwise this returns what class the function returns */ public FederBinding getReturnType() { return returnType; } @Override /** * @return Set the return type of this interface */ public void setReturnType(FederBinding fc) { returnType = fc; } /** * @return Returns true, if this interface can be called (is an object) */ @Override public boolean canBeCalled() { return cancall; } /** * @return Returns a string, which should be generated * in the header file */ @Override public String generateInHeader() { if (canBeCalled()) { return ""; } String inbetween = ""; if (getReturnType() == null) { inbetween = "void"; } else if (getReturnType () instanceof FederClass) { inbetween = getReturnType().generateCName() + ""; } else { inbetween = getReturnType().generateCName(); } return "typedef " + inbetween + " (*" + generateCName() + ") (" + FederFunction.generateArgumentsListString(getParent(), getArguments()) + ");\n"; } /** * @param args * @return Returns true if the given 'args' are similiar to the * ones of this interface */ public boolean similiarToArguments(FederArguments args) { return isEqual(null, FederFunction.objectListToClassList(args.getArguments())); } }
Python
UTF-8
4,450
2.953125
3
[]
no_license
import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.model_selection import cross_val_score, train_test_split from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt import seaborn as sns import statsmodels.api as sm def import_data(dir): #Import the data set using a pandas frame with condition that area>0 data = pd.read_csv(dir) data = data[data['area'] > 0] return data def add_Class(fileName, skipZeros=False): data = pd.read_csv(fileName) data['Log-area'] = np.log10(data['area']+1) data['category'] = (data['area'] > 0).astype(int) #data.describe().to_csv("data_description/description.csv", float_format="%.2f") data_without = data.where(data['area'] != 0) data_without = data_without[data_without['area'].notnull()] #data_without.describe().to_csv( # "data_description/description_Nozeros.csv", float_format="%.2f") return data_without if skipZeros else data def train_regression(X,y): reg = LinearRegression(fit_intercept=True,normalize=False).fit(X, y) #model = sm.OLS(y, X) #result = model.fit() #print(reg.score(X,y)) return reg def remove_outlier(forest_fire): forest_fire['area_cat'] = pd.cut(forest_fire['area'], bins=[0, 5, 10, 50, 100, 1100], include_lowest=True, labels=['0-5', '5-10', '10-50', '50-100', '>100']) forest_fire.area_cat.value_counts() forest_fire.drop(forest_fire[forest_fire.area >100].index, axis=0, inplace=True) return forest_fire def draw_plot(forest_fire): forest_fire.hist(bins=50, figsize=(30, 20), ec='w', xlabelsize=5, ylabelsize=5) corr_matrix = forest_fire.corr(method='spearman') ax = plt.figure(figsize=(12, 8)) ax = sns.heatmap(corr_matrix, cmap='PiYG') plt.show() print(corr_matrix.area.sort_values(ascending=False)) #visualizing relations of most related attributes attributes = ['area', 'wind', 'temp', 'rain', 'RH'] sns.pairplot(forest_fire[attributes]) plt.show() def fit_model(X,y): num_instances = len(X) models = [] models.append(('LiR', LinearRegression())) models.append(('Ridge', Ridge())) models.append(('Lasso', Lasso())) models.append(('ElasticNet', ElasticNet())) models.append(('Bag_Re', BaggingRegressor())) models.append(('RandomForest', RandomForestRegressor())) models.append(('ExtraTreesRegressor', ExtraTreesRegressor())) models.append(('KNN', KNeighborsRegressor())) models.append(('CART', DecisionTreeRegressor())) models.append(('SVM', SVR())) # Evaluations results = [] names = [] scoring = [] for name, model in models: # Fit the model model.fit(X, Y) predictions = model.predict(X) # Evaluate the model score = explained_v def OLS(x, y): #self OLS w = np.dot(np.linalg.inv(np.dot(np.matrix.transpose(x), x)), np.dot(np.matrix.transpose(x), y)) return w def RSS(x_test, w, y_test): #self RSS RSS = np.dot((y_test - np.dot(x_test, w)), (y_test - np.dot(x_test, w))) if __name__ == "__main__": """ data_without = add_Class('data_Set/train.csv',True) forest_fire = data_without.iloc[:,4:-1] draw_plot(forest_fire) X_train = data_without[data_without.columns[:-3]].values norm = data_without.apply(lambda x: np.sqrt(x**2).sum()/x.shape[0]) X_normal = X_train #X_normal = preprocessing.normalize(X_train, norm='l1',axis=1) y_train = data_without['area'].values model = train_regression(X_normal,y_train) data_test = add_Class('data_Set/test.csv') X_test = data_test[data_test.columns[:-3]].values y_test = data_test['area'].values X_normal_t = X_test/norm #X_normal_t = preprocessing.normalize(X_test, norm='l1', axis=1) """ training = import_data('data_Set/train.csv') testing = import_data('data_Set/test.csv') #get output matrix y_train = np.array(training['area']) y_test = np.array(testing['area']) #get the features matrix del training['area'], testing['area'] norm = training.apply(lambda x: np.sqrt(x**2).sum()/x.shape[0]) training /= norm testing /= norm x_train = np.array(training) x_test = np.array(testing) model = train_regression(x_train, y_train) #print(model.score(X_normal_t,y_test)) print(np.sum(np.power(y_test-model.predict(x_test), 2)))
Java
UTF-8
1,130
2.453125
2
[]
no_license
package com.dev.mark.notes.data.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import static com.dev.mark.notes.data.database.NotesDbSchema.NotesTable.NAME; public class NotesBaseHelper extends SQLiteOpenHelper { private static final int VERSION = 1; private static final String DATABASE_NAME = "weatherBase.db"; public NotesBaseHelper(Context context) { super(context, DATABASE_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + NAME + "(" + " _id integer primary key autoincrement, " + NotesDbSchema.NotesTable.Cols.UUID + ", " + NotesDbSchema.NotesTable.Cols.TITLE + ", " + NotesDbSchema.NotesTable.Cols.TEXT_NOTE + ", " + NotesDbSchema.NotesTable.Cols.DATE_MAKE + ", " + NotesDbSchema.NotesTable.Cols.DATE_REMINDER + ")" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
C++
UTF-8
1,079
2.84375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; const int N = 1e5+2; vector<int> parent(N); vector<int> sz(N); void make_set(int v) { parent[v]=v; sz[v]=1; } int find_set(int v) { if(v==parent[v]) { return v; } //optimisation return parent[v] = find_set(parent[v]); } void union_sets(int a,int b) { a = find_set(a); b = find_set(b); if(a!=b) { if(sz[a]<sz[b]) { swap(a,b); } parent[b]=a; sz[a]+=sz[b]; } } int main() { for(int i=0;i<N;i++) { make_set(i); } int n,m; cin>>n>>m; vector<vector<int>> edges; for(int i=0;i<m;i++) { int u,v; cin>>u>>v; edges.push_back({u,v}); } bool cycle = false; for(auto i : edges) { int u = i[0]; int v = i[1]; int x = find_set(u); int y = find_set(v); if(x==y) { cycle=true; } else{ union_sets(u,v); } } if(cycle) { cout<<"Cycle is present"; } else{ cout<<"Cycle is not present"; } return 0; }
Java
UTF-8
6,684
2.640625
3
[]
no_license
package com.example.bryn.hleonard_cardiobook; import android.icu.util.Measure; import android.os.Parcel; import android.os.Parcelable; import java.net.PasswordAuthentication; import java.security.PrivilegedActionException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Formatter; import java.util.UUID; /** * Measurement class represents a measurement (old or new). It implements the interface Parcelable * in order to transfer/send it across activiities. When initially created, the date and time is * sent to the current date, while a unique identifier is also created. All other fields are * provided through the setters. * This class includes an inner class in order to satisfy the parcelable interface. The methods * readFromParcel and writeToParcel are also implemented heere to satisfy interface requirements. */ public class Measurement implements Parcelable { private String date; private String time; private Integer SystolicPressure; private Integer DiastolicPressure; private Integer HeartRate; private String Comment; private String mID = UUID.randomUUID().toString(); /** * Consructor for parcel sharing */ public Measurement(Parcel in) throws ParseException { mID = in.readString(); date = in.readString(); SystolicPressure = in.readInt(); DiastolicPressure = in.readInt(); HeartRate = in.readInt(); Comment = in.readString(); } /** * Basic constructor */ public Measurement() { DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd"); date = dateFormat.format(new Date()); dateFormat = new SimpleDateFormat("hh:mm:ss"); time = dateFormat.format(new Date()); SystolicPressure = 0; DiastolicPressure = 0; HeartRate = 0; Comment = ""; } /** * readFromParcel collects the parcel information and returns the converted Measurement. * @param in * @return */ public static Measurement readFromParcel(Parcel in){ String mID1 = in.readString(); String Date1 = in.readString(); String Time1 = in.readString(); Integer SystolicPressure1 = in.readInt(); Integer DiastolicPressure1 = in.readInt(); Integer HeartRate1 = in.readInt(); String Comment1 = in.readString(); return new Measurement(Date1, Time1, SystolicPressure1, DiastolicPressure1, HeartRate1, Comment1, mID1); } /** * Constructor used for readFromParcel method * @param date * @param time * @param systolicPressure * @param diastolicPressure * @param heartRate * @param comment * @param mID */ public Measurement(String date, String time, Integer systolicPressure, Integer diastolicPressure, Integer heartRate, String comment, String mID) { this.date = date; this.time = time; SystolicPressure = systolicPressure; DiastolicPressure = diastolicPressure; HeartRate = heartRate; Comment = comment; this.mID = mID; } /** * Getter for the dTate field * @return date */ public String getDate(){ return this.date; } /** * Setter for the date * @param dateString */ public void setDate(String dateString) { this.date = dateString; } /** * Getter for the Time field * @return time */ public String getTime(){ return this.time; } /** * Setter for the Time field * @param timeString */ public void setTime(String timeString) { this.time = timeString; } /** * Getter for the SystolicPressure fjeld * @return SystolicPressure */ public Integer getSystolicPressure() { return SystolicPressure; } /** * Setter for the SystolicPressure field * @param systolicPressure */ public void setSystolicPressure(Integer systolicPressure) { SystolicPressure = systolicPressure; } /** * Getter for the DiastolicPressure field * @return Diasolic Pressure */ public Integer getDiastolicPressure() { return DiastolicPressure; } /** * Setter for the DiasolicPressure field * @param diastolicPressure */ public void setDiastolicPressure(Integer diastolicPressure) { DiastolicPressure = diastolicPressure; } /** * Getter for the HeartRate field * @return HeartRate */ public Integer getHeartRate() { return HeartRate; } /** * Setter for the HeartRate feild * @param heartRate */ public void setHeartRate(Integer heartRate) { HeartRate = heartRate; } /** * Getter for the Comment field * @return Comment */ public String getComment() { return Comment; } /** * Setter for the Comment filed * @param comment */ public void setComment(String comment) { Comment = comment; } /** * Getter for mID field * @return mID */ public String getmID() { return mID; } /** * Necessary for Parceable implementation * @return size */ @Override public int describeContents() { return 0; } /** * Inner class that creates a pareceable parcel for the measurement */ public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { /** * Creates a measurement from the parcel * @param in * @return measurement from parcel */ public Measurement createFromParcel(Parcel in) { return readFromParcel(in); } /** * Creates an array of Masurements of a certain size * @param size * @return the array of measurements */ public Measurement[] newArray(int size) { return new Measurement[size]; } }; /** * This method is part of the implementation of Parceable. It writese the Meaurement data fields * to the parcel * @param dest * @param flags */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mID); dest.writeString(this.date); dest.writeString(this.time); dest.writeInt(SystolicPressure); dest.writeInt(DiastolicPressure); dest.writeInt(HeartRate); dest.writeString(Comment); } }
Java
UTF-8
346
1.851563
2
[]
no_license
package com.maes.lionel.cars; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import java.util.List; @Dao public interface UsersDao { @Insert public void insertUser(Users user); @Query("select * from Users") public List<Users> getUsers(); }
Java
UTF-8
1,226
2.0625
2
[ "MIT" ]
permissive
package ca.gc.aafc.dina.repository.meta; import ca.gc.aafc.dina.mapper.IgnoreDinaMapping; import com.fasterxml.jackson.annotation.JsonInclude; import io.crnk.core.resource.annotations.JsonApiMetaInformation; import io.crnk.core.resource.meta.MetaInformation; import lombok.Builder; import lombok.Getter; import lombok.Setter; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.UUID; /** * Abstract class which can be extended by a resource to add meta information to a resource's JSON response * through Crnk. */ public abstract class AttributeMetaInfoProvider { @JsonApiMetaInformation @IgnoreDinaMapping @Getter @Setter private DinaJsonMetaInfo meta; @Builder @Getter @Setter @JsonInclude(JsonInclude.Include.NON_EMPTY) public static class DinaJsonMetaInfo implements MetaInformation { private String permissionsProvider; private Set<String> permissions; private Map<String, Object> warnings; public void setWarning(String warningKey, Object warningValue) { if (warnings == null) { warnings = Collections.emptyMap(); } this.warnings.put(warningKey, warningValue); } } public abstract UUID getUuid(); }
TypeScript
UTF-8
630
2.953125
3
[ "Apache-2.0" ]
permissive
import { WeekDay } from '@angular/common'; import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'weekDaySort' }) export class WeekDaySortPipe implements PipeTransform { transform(value: string[], startOfWeek: WeekDay): string[] { // ensure start of week is in range startOfWeek = Math.max(WeekDay.Sunday, Math.min(WeekDay.Saturday, startOfWeek)); // create a new array to avoid altering the original const weekdays = [...value]; for (let idx = 0; idx < startOfWeek; idx++) { weekdays.push(weekdays.shift()); } return weekdays; } }
Rust
UTF-8
8,761
3.171875
3
[ "Apache-2.0", "MIT" ]
permissive
use serde::de; use std::fmt; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Encoding { Primitive, Constructed, } impl fmt::Display for Encoding { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Primitive => write!(f, "PRIMITIVE"), Self::Constructed => write!(f, "CONSTRUCTED"), } } } #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum TagClass { Universal, Application, ContextSpecific, Private, } impl fmt::Display for TagClass { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Universal => write!(f, "UNIVERSAL"), Self::Application => write!(f, "APPLICATION"), Self::ContextSpecific => write!(f, "CONTEXT_SPECIFIC"), Self::Private => write!(f, "PRIVATE"), } } } #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Tag(u8); impl Tag { pub const BOOLEAN: Self = Tag(0x01); pub const INTEGER: Self = Tag(0x02); pub const BIT_STRING: Self = Tag(0x03); pub const OCTET_STRING: Self = Tag(0x04); pub const NULL: Self = Tag(0x05); pub const OID: Self = Tag(0x06); pub const REAL: Self = Tag(0x09); pub const UTF8_STRING: Self = Tag(0x0C); pub const RELATIVE_OID: Self = Tag(0xD); pub const NUMERIC_STRING: Self = Tag(0x12); pub const PRINTABLE_STRING: Self = Tag(0x13); pub const TELETEX_STRING: Self = Tag(0x14); pub const VIDEOTEX_STRING: Self = Tag(0x15); pub const IA5_STRING: Self = Tag(0x16); pub const BMP_STRING: Self = Tag(0x1E); pub const UTC_TIME: Self = Tag(0x17); pub const GENERALIZED_TIME: Self = Tag(0x18); pub const SEQUENCE: Self = Tag(0x30); pub const SET: Self = Tag(0x31); pub const GENERAL_STRING: Self = Tag(0x1b); #[inline] pub const fn application_primitive(number: u8) -> Self { Tag(number & 0x1F | 0x40) } #[inline] pub const fn application_constructed(number: u8) -> Self { Tag(number & 0x1F | 0x60) } #[inline] pub const fn context_specific_primitive(number: u8) -> Self { Tag(number & 0x1F | 0x80) } #[inline] pub const fn context_specific_constructed(number: u8) -> Self { Tag(number & 0x1F | 0xA0) } /// Identifier octets as u8 #[inline] pub const fn inner(self) -> u8 { self.0 } /// Tag number of the ASN.1 value (filtering class bits and constructed bit with a mask) #[inline] pub const fn number(self) -> u8 { self.0 & 0x1F } // TODO: need version bump to be made const pub fn class(self) -> TagClass { match self.0 & 0xC0 { 0x00 => TagClass::Universal, 0x40 => TagClass::Application, 0x80 => TagClass::ContextSpecific, _ /* 0xC0 */ => TagClass::Private, } } // TODO: need version bump to be made const pub fn class_and_number(self) -> (TagClass, u8) { (self.class(), self.number()) } // TODO: need version bump to be made const pub fn components(self) -> (TagClass, Encoding, u8) { (self.class(), self.encoding(), self.number()) } #[inline] pub const fn is_application(self) -> bool { self.0 & 0xC0 == 0x40 } #[inline] pub const fn is_context_specific(self) -> bool { self.0 & 0xC0 == 0x80 } #[inline] pub const fn is_universal(self) -> bool { self.0 & 0xC0 == 0x00 } #[inline] pub const fn is_private(self) -> bool { self.0 & 0xC0 == 0xC0 } #[inline] pub const fn is_constructed(self) -> bool { self.0 & 0x20 == 0x20 } #[inline] pub const fn is_primitive(self) -> bool { !self.is_constructed() } // TODO: need version bump to be made const #[inline] pub fn encoding(self) -> Encoding { if self.is_constructed() { Encoding::Constructed } else { Encoding::Primitive } } } impl From<u8> for Tag { fn from(tag: u8) -> Self { Self(tag) } } impl fmt::Display for Tag { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Tag::BOOLEAN => write!(f, "BOOLEAN"), Tag::INTEGER => write!(f, "INTEGER"), Tag::BIT_STRING => write!(f, "BIT STRING"), Tag::OCTET_STRING => write!(f, "OCTET STRING"), Tag::NULL => write!(f, "NULL"), Tag::OID => write!(f, "OBJECT IDENTIFIER"), Tag::REAL => write!(f, "REAL"), Tag::UTF8_STRING => write!(f, "UTF8String"), Tag::RELATIVE_OID => write!(f, "RELATIVE-OID"), Tag::NUMERIC_STRING => write!(f, "NumericString"), Tag::PRINTABLE_STRING => write!(f, "PrintableString"), Tag::TELETEX_STRING => write!(f, "TeletexString"), Tag::VIDEOTEX_STRING => write!(f, "VideotexString"), Tag::IA5_STRING => write!(f, "IA5String"), Tag::BMP_STRING => write!(f, "BMPString"), Tag::UTC_TIME => write!(f, "UTCTime"), Tag::GENERALIZED_TIME => write!(f, "GeneralizedTime"), Tag::SEQUENCE => write!(f, "SEQUENCE"), Tag::SET => write!(f, "SET"), Tag::GENERAL_STRING => write!(f, "GeneralString"), other => write!(f, "{}({:02X}) {}", other.class(), other.number(), other.encoding()), } } } impl fmt::Debug for Tag { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Tag({}[{:02X}])", self, self.0) } } /// Used to peek next tag by using `Deserializer::deserialize_identifier`. /// /// Can be used to implement ASN.1 Choice. /// /// # Examples /// ``` /// use serde::de; /// use picky_asn1::{ /// wrapper::{IntegerAsn1, Utf8StringAsn1}, /// tag::{Tag, TagPeeker}, /// }; /// use std::fmt; /// /// pub enum MyChoice { /// Integer(u32), /// Utf8String(String), /// } /// /// impl<'de> de::Deserialize<'de> for MyChoice { /// fn deserialize<D>(deserializer: D) -> Result<Self, <D as de::Deserializer<'de>>::Error> /// where /// D: de::Deserializer<'de>, /// { /// struct Visitor; /// /// impl<'de> de::Visitor<'de> for Visitor { /// type Value = MyChoice; /// /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { /// formatter.write_str("a valid MyChoice") /// } /// /// fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> /// where /// A: de::SeqAccess<'de>, /// { /// match seq.next_element::<TagPeeker>()?.unwrap().next_tag { /// Tag::INTEGER => { /// let value = seq.next_element::<u32>()?.unwrap(); /// Ok(MyChoice::Integer(value)) /// } /// Tag::UTF8_STRING => { /// let value = seq.next_element::<String>()?.unwrap(); /// Ok(MyChoice::Utf8String(value)) /// } /// _ => Err(de::Error::invalid_value( /// de::Unexpected::Other( /// "[MyChoice] unsupported or unknown choice value", /// ), /// &"a supported choice value", /// )) /// } /// } /// } /// /// deserializer.deserialize_enum("MyChoice", &["Integer", "Utf8String"], Visitor) /// } /// } /// /// let buffer = b"\x0C\x06\xE8\x8B\x97\xE5\xAD\x97"; /// let my_choice: MyChoice = picky_asn1_der::from_bytes(buffer).unwrap(); /// match my_choice { /// MyChoice::Integer(_) => panic!("wrong variant"), /// MyChoice::Utf8String(string) => assert_eq!(string, "苗字"), /// } /// ``` #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TagPeeker { pub next_tag: Tag, } impl<'de> de::Deserialize<'de> for TagPeeker { fn deserialize<D>(deserializer: D) -> Result<TagPeeker, D::Error> where D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { type Value = TagPeeker; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a valid ASN.1 tag") } fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E> where E: de::Error, { Ok(TagPeeker { next_tag: v.into() }) } } deserializer.deserialize_identifier(Visitor) } }
JavaScript
UTF-8
1,566
3.0625
3
[ "Apache-2.0" ]
permissive
/** * Filename: paging.js * Company: Touchdown Delivery, LLC * Author: Darien Tsai * Collaborators: none * Date Created: 12/17/18 * Description: * Manages the transition between the index page and all the others */ //select body let body = document.getElementsByTagName('body')[0]; //Index page links let mobileNavs = document.getElementsByClassName('m-nav-item') let staticNavs = document.getElementsByClassName('nav-item'); let navButton = document.getElementById('head-button'); let footNavs = document.getElementsByClassName('f-nav-item'); //set listeners for mobile navs for( var i = 0; i < mobileNavs.length; i += 1){ mobileNavs[i].addEventListener( 'click', function(e){ transition(e); } ); } //set listeners for static navs for( var i = 0; i < staticNavs.length; i += 1){ staticNavs[i].addEventListener( 'click', function(e){ transition(e); } ); } //set listener for button navButton.addEventListener( 'click', function(e){ transition(e); } ); //set listeners for foot navs for( var i = 0; i < footNavs.length; i += 1){ footNavs[i].addEventListener( 'click', function(e){ e.preventDefault(); transition(e); } ); } /** * * @param e the target object */ function transition(e){ //gets the uri var link = String(e.target.attributes[0].value); //sets the body class to transition class body.className = "transition"; //switches page after animation setTimeout( function(){ location.assign(link); }, 300 ); }
Python
UTF-8
333
2.90625
3
[]
no_license
# Libraries import RPi.GPIO as GPIO from mfrc522 import SimpleMFRC522 # Reader simplification reader = SimpleMFRC522() # To test if it works try: # Type data to write on the tag/card text = input('New data: ') print("Hold tag at reader") reader.write(text) # Confirmation it worked print("Written") finally: GPIO.cleanup()
C#
UTF-8
5,065
2.609375
3
[]
no_license
using Cds.BusinessCustomer.Domain.CustomerAggregate; using Cds.BusinessCustomer.Domain.CustomerAggregate.Abstractions; using Cds.BusinessCustomer.Infrastructure.CustomerRepository.Dtos; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Cds.BusinessCustomer.Infrastructure.CustomerRepository { public class CartegieRepository : ICartegieRepository { private string baseUrl = "https://6037a3775435040017722f92.mockapi.io/api/v1/Company/"; /// <summary> /// Get customer infos by id /// </summary> /// <param name="id"></param> /// <returns></returns> public Task<Customer> GetInfos_IdSearch(string id) { CustomerSingleSearchDTO ConsumerInfo = SingleSearch("ResearchById").Result; return Task.FromResult(new Customer() { Name = ConsumerInfo.Name, Siret = ConsumerInfo.Siret, NafCode = ConsumerInfo.NafCode, Adress = ConsumerInfo.Adress }); } /// <summary> /// Get customer infos by siret /// </summary> /// <param name="siret"></param> /// <returns></returns> public Task<Customer> GetInfos_SiretSearch(string siret) { CustomerSingleSearchDTO ConsumerInfo = SingleSearch("ResearchBySiret").Result; return Task.FromResult(new Customer() { Name = ConsumerInfo.Name, Siret = ConsumerInfo.Siret, NafCode = ConsumerInfo.NafCode, Adress = ConsumerInfo.Adress }); } /// <summary> /// Get customers infos by social number and zipcode /// </summary> /// <param name="socialReason"></param> /// <param name="zipCode"></param> /// <returns></returns> public Task<List<Customer>> GetInfos_MultipleSearch(string socialReason, string zipCode) { List<CustomerMultipleSearchDTO> ConsumerInfo = MultipleSearch("RechercheMultiple").Result; List<Customer> list = ConsumerInfo.Select(e => new Customer { Id = e.Id, Name = e.Name, Adress = e.Adress }).ToList(); return Task.FromResult(list); } /// Communication with API cartégie /// /// <summary> /// Method to handle Cartégie api - searching by id or siret /// </summary> /// <param name="param"></param> /// <returns></returns> private async Task<CustomerSingleSearchDTO> SingleSearch(string param) { CustomerSingleSearchDTO ConsumerInfo = new CustomerSingleSearchDTO(); using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseUrl); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // status code and data : HttpResponseMessage res = await client.GetAsync(param); if (res.IsSuccessStatusCode) { //Storing the response details received from web api var EmpResponse = res.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing it ConsumerInfo = JsonConvert.DeserializeObject<CustomerSingleSearchDTO>(EmpResponse.Substring(1, EmpResponse.Length - 2)); } } return ConsumerInfo; } /// <summary> /// Method to handle Cartégie api - searching by social number and zip code /// </summary> /// <param name="param"></param> /// <returns></returns> private async Task<List<CustomerMultipleSearchDTO>> MultipleSearch(string param) { List<CustomerMultipleSearchDTO> ConsumerInfo = new List<CustomerMultipleSearchDTO>(); using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseUrl); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // status code and data : HttpResponseMessage res = await client.GetAsync(param); if (res.IsSuccessStatusCode) { //Storing the response details recieved from web api var EmpResponse = res.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing it ConsumerInfo = JsonConvert.DeserializeObject<List<CustomerMultipleSearchDTO>>(EmpResponse); } } return ConsumerInfo; } } }
Python
UTF-8
595
2.625
3
[]
no_license
import os ROOT='.' gt=os.path.join(ROOT,'gt') out=os.path.join(ROOT,'out') # print(os.listdir(gt)) for txt in os.listdir(gt): basename= os.path.splitext(txt)[0] # print(basename) with open(out+'/'+txt,'w') as f_o: with open(gt+'/'+txt) as f: lines = [line for line in f.readlines() if line.strip()] for line in lines: line=line.split(' ') print(line) xmin, ymin, xmax, ymax,word =line f_o.write(f'{xmin},{ymin},{xmax},{ymin},{xmax},{ymax},{xmin},{ymax},{word}') # break
Markdown
UTF-8
4,242
3.03125
3
[ "Apache-2.0" ]
permissive
# Tools for creating a basic Infrastructure-as-a-Service (v3.2.27) This is a set of bash-script files for creating a basic single-host IaaS on a Linux server. The purpose is to give every user a personal virtual machine in the form of a docker container (http://docker.com). Users’ containers can be built from any docker image. Users have root privileges inside their containers. User can change and save their container. Users are created on the server machine, every user is assigned one container. Service users are added to dockertest group. When a service user connects to the server with SSH he/she automatically logins into his/her container. It is absolutely seamless for users. Authentication is based on ssh-key and key forwarding. SSH-key authentication and key-forwarding for the server must be enabled on the user side. When host administrator creates a user, the following actions are performed: * A user created on the host (server) and added to groups "dockertest" and "ssh". Every user of IaaS must be a member of "dockertest" group. "ssh" group can be used to restrict ssh login to the server only to this group members. * A docker image for the user is built. For instructions on creating users see [createuser.sh](#createusersh). ## Scheme ![Scheme](docker-IaaS.jpg) ## Demonstration video http://youtu.be/_SvzsBcp5wQ ## Set up on the server machine SSH key forwarding must be enabled on the server. Force command must be set for dockertest group. docker.sh file must be placed in the server root directory. In /etc/ssh/sshd_config: ``` AllowAgentForwarding yes Match Group dockertest ForceCommand /docker.sh ``` ## SSH commands There are special ssh commands, that when run from local computer will not be executed inside the user container but rather on the host. These commands are for manipulating user container. ### commit Commit user container. The user's docker image is updated with the current container state. ### stop Stop user container. ### remove Remove user container. User's docker image is not removed, so when user logs in a new container will be created from user's docker image. ### port Display container ssh port number on the host side. Container must be running. Also port number is saved in SSH_PORT environment variable inside container. ### freeport Display free server port number. Can be used for creating ssh tunnel to container. ## In-container commands ### daemon Enabling “daemon” mode. This command is to be called inside a container to prevent it from stopping when there are no active SSH connections. ### nodaemon Command is to be called inside a container to turn off “daemon” mode: to set the container to be stopped after all SSH sessions are closed. ### stopnow Command is to be run inside a container to stop the container immediately. ## Files ### cleanuser.sh Removes user on the server and removes user's containers. #### Sample usage: ```bash sudo ./cleanuser.sh usernic ``` ### createuser.sh Creates user on the server and builds user's docker image, set up the server for automatic login into container with SSH key. #### Arguments: user name docker image public SSH key file #### Requires: jq #### Sample usage: ```bash sudo ./createuser.sh usernic ubuntu:latest user_ssh_key ``` ### docker.sh Is called every time user logs in with SSH to the host. docker.sh starts user's container if it is stopped, creates SSH connection from the host to the container. It must be placed in the host root directory. ### container.sh This file is called on every SSH connection to a container. It counts SSH connections and stops the container if there are no active connections and the container is not in “daemon” mode. ### dockerwatch.sh Called by container.sh and stop.sh to stop container in due time - when all active SSH connections to the container are closed. ### makeRemote.sh Utility for mounting user local directories into user container on the server and executing commands inside the container. Must be executed on user local computer. Usage: ```makeRemote.sh -u <username> -h <server address> -p <local directory to mount> -k <path to ssh-key> -m <remote command>```
Java
UTF-8
633
3.15625
3
[]
no_license
import java.io.*; import java.util.*; public class DiagonalTraversal { public static void main(String[] args) throws Exception { // write your code here Scanner scn=new Scanner(System.in); int n=scn.nextInt(); int a[][]=new int[n][n]; for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) { a[i][j]=scn.nextInt(); } } for(int g=0;g<a.length;g++) { for(int i=0,j=g;j<a.length;i++,j++) { System.out.println(a[i][j]); } } } }
Java
UTF-8
972
2.859375
3
[]
no_license
package ModelObjects; public class Category { int categoryID; String categoryName; String categoryIcon; public Category(){ } public Category(int _categoryID){ this.categoryID = _categoryID; } public Category(String _categoryName,String _categoryIcon){ this.categoryName = _categoryName; this.categoryIcon = _categoryIcon; } public void setCategoryID(int _categoryID){ this.categoryID = _categoryID; } public void setCategoryName(String _categoryName){ this.categoryName = _categoryName; } public void setCategoryIcon(String _categoryIcon){ this.categoryIcon = _categoryIcon; } public int getCategoryID(){ return this.categoryID; } public String getCategoryName(){ return categoryName; } public String getCategoryIcon(){ return categoryIcon; } }
C#
UTF-8
435
2.609375
3
[]
no_license
using System; using System.Security.Cryptography; using System.Text; namespace OwnID.Extensibility.Extensions { public static class HashExtensions { public static string ToSha256(this string input) { using var sha256 = new SHA256Managed(); var hash = Convert.ToBase64String( sha256.ComputeHash(Encoding.UTF8.GetBytes(input))); return hash; } } }
Java
UTF-8
2,754
2.984375
3
[]
no_license
package com.dualnback.game; class Score { private int countOfRightSoundGuesses; private int countOfWrongSoundGuesses; private int countOfRightLocationGuesses; private int countOfWrongLocationGuesses; private int expectedTotalSoundMatch; private int expectedTotalLocationMatch; private double singlePoint; public Score( int expectedTotalSoundMatch, int expectedTotalLocationMatch ) { this.expectedTotalSoundMatch = expectedTotalSoundMatch; this.expectedTotalLocationMatch = expectedTotalLocationMatch; this.countOfRightSoundGuesses = 0; this.countOfWrongSoundGuesses = 0; this.countOfRightLocationGuesses = 0; this.countOfWrongLocationGuesses = 0; singlePoint = divideIfDivisorOrDefault( 100d, expectedTotalLocationMatch + expectedTotalSoundMatch, 0.0 ); } public Score update( UserInputEvaluation userInputEvaluation ) { switch ( userInputEvaluation ) { case CorrectSound: this.countOfRightSoundGuesses++; return this; case CorrectLocation: this.countOfRightLocationGuesses++; return this; case IncorrectSound: this.countOfWrongSoundGuesses++; return this; case IncorrectLocation: this.countOfWrongLocationGuesses++; return this; default: throw new IllegalArgumentException( "Invalid user input given " + userInputEvaluation ); } } public double calculateScorePercentage( ) { double correctSoundScore = singlePoint * countOfRightSoundGuesses; double correctLocationScore = singlePoint * countOfRightLocationGuesses; double incorrectSoundScore = singlePoint * countOfWrongSoundGuesses; double incorrectLocationScore = singlePoint * countOfWrongLocationGuesses; double correct = correctSoundScore + correctLocationScore; double incorrect = incorrectLocationScore + incorrectSoundScore; return correct - incorrect; } private double divideIfDivisorOrDefault( double numerator, int denom, double defaultNum ) { return denom == 0 || numerator == 0 ? defaultNum : ( numerator / denom ); } @Override public String toString( ) { return "Score{" + "expectedTotalSoundMatch=" + expectedTotalSoundMatch + ", expectedTotalLocationMatch=" + expectedTotalLocationMatch + ", countOfRightLocationGuesses=" + countOfRightLocationGuesses + ", countOfRightSoundGuesses=" + countOfRightSoundGuesses + '}'; } }
Python
UTF-8
124
2.953125
3
[]
no_license
def f(): return 3 def test_function(): a = f() assert a % 2 == 0, "判断a为偶数,当前a的值为:%s"%a
Python
UTF-8
2,828
2.6875
3
[ "MIT" ]
permissive
import os import platform from flac_to_mka.tools import config if platform.system() == "Windows": import win32api import win32con # Handle via config configuration = config.GetConfig() METAFLAC_EXE = configuration['metaflac'] SOX_EXE = configuration['sox'] MKVMERGE_EXE = configuration['mkvmerge'] OUTPUTDIR = configuration['output'] del configuration def DirectoryName(f): if os.path.isdir(f): return f dirname = os.path.dirname(f) if dirname and dirname != ".": return dirname return os.getcwd() def FileName(f): if os.path.isdir(f): raise RuntimeError(f"Can't obtain filename from directory {f}") return os.path.basename(f) def GetFilenames(exts, directory=".", case=False, abspath=True, exclude=()): """Returns a sorted ``list[str]`` containing the file names of all files in the directory ``directory`` with the extension(s) ``exts``. Parameters ---------- exts: str or list[str], required Indicates the extension(s) that are desired directory: str, default='.' Location to search for files case: bool, default=False True to perform a case sensitive search, False for case insensitive abspath: bool, default=True True returns the ``directory`` and file names joined via os.path.join False returns just the file names exclude: list[str] or tuple(str), default=() A list of explicit file names to exclude -- note that if absolute paths are given then the directory is stripped off yielding just the file names. Returns ------- list[str] containing the formatted file names, sorted """ files = os.listdir(directory) if not isinstance(exts, list): exts = [exts] exclude = [FileName(f) for f in exclude] if case: files = [f for f in files if f not in exclude] else: exclude = [e.lower() for e in exclude] files = [f for f in files if not f.lower() in exclude] if case: # Case SENSITIVE files = [f for f in files if any(f.endswith(ext) for ext in exts)] else: # Case INSENSITIVE files = [f for f in files if any(f.lower().endswith(ext) for ext in exts)] if abspath: files = [os.path.join(directory, f) for f in files] files = [f for f in files if not FileIsHidden(f)] files.sort() return files def FileIsHidden(f): """Returns a boolean indicating whether the file ``f`` is hidden or not. This function is Windows/Linux safe. """ if platform.system() == "Windows": # Note this is bitwise and as the RHS is a mask return bool(win32api.GetFileAttributes(f) & win32con.FILE_ATTRIBUTE_HIDDEN) # Linux/Mac hidden files simply have file names that start with a dot return FileName(f).startswith('.')
C#
UTF-8
809
3.015625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FB.Contracts.Services; namespace FB.Infrastructure.Services.Validation { public class StringLengthValidator : IValidator { public int MinimumLength { get; protected set; } public int MaximumLength { get; protected set; } public StringLengthValidator(int minLength, int maxLength) { this.MinimumLength = minLength; this.MaximumLength = maxLength; } public bool IsValid(object value) { string sValue = value as string; if (null != sValue) { return sValue.Length >= MinimumLength && sValue.Length <= MaximumLength; } return true; } } }
JavaScript
UTF-8
566
2.953125
3
[]
no_license
var sea; var ship; var ship_moving; var seaImage; function preload(){ ship_moving= loadAnimation("ship-1.png","ship-2.png","ship-3.png","ship-4.png"); seaImage= loadImage("sea.png"); } function setup(){ createCanvas(800,600); ship= createSprite(400,250,10, 10); ship.addAnimation("moving", ship_moving); ship.scale= 0.5; sea= createSprite(200,180,400,20); sea.addImage("sea", seaImage); createEdgeSprites(); } function draw() { background("grey"); sea.velocityX= -5; if(sea.x < 0){ sea.x= sea.width/2; } console.log(ship.x); drawSprites(); }
C#
UTF-8
10,676
2.5625
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Newtonsoft.Json; using PCLStorage; using SkiaSharp; using SkiaSharp.Views.Forms; using Xamarin.Forms; namespace MEPSLog_Forms { public class FileManager { private static FileManager _instance = null; IFolder rootFolder = FileSystem.Current.LocalStorage; public static FileManager Instance { get { if (_instance == null) { _instance = new FileManager(); } return _instance; } } public FileManager() { } public async void DeleteRun(String dateIn, ListView historyList) { List<MepsRun> runList; MepsRun runToDelete = new MepsRun(); MepsRun averageData; //Create/Open folder and files IFolder mepsFolder = await rootFolder.CreateFolderAsync("MEPS_Data", CreationCollisionOption.OpenIfExists); IFile historyFile = await mepsFolder.CreateFileAsync("Run_History.txt", CreationCollisionOption.OpenIfExists); IFile averageFile = await mepsFolder.CreateFileAsync("Averages.txt", CreationCollisionOption.OpenIfExists); Debug.WriteLine(historyFile.Path); //Retrieve old data and create a list of runs from it String previousJSON = await historyFile.ReadAllTextAsync(); runList = JsonConvert.DeserializeObject<List<MepsRun>>(previousJSON); for (int i = runList.Count - 1; i >= 0; i--) { if (dateIn == runList[i].date.ToString()) { runToDelete = runList[i]; runList.RemoveAt(i); } } //Read from average file into temp average run String averageJSON = await averageFile.ReadAllTextAsync(); if (averageJSON != "") { averageData = JsonConvert.DeserializeObject<MepsRun>(averageJSON); } else { averageData = new MepsRun(0, 0, 0, 0, DateTime.Now); } //subtract values from average data averageData.totalMental -= runToDelete.mental; averageData.totalEmotional -= runToDelete.emotional; averageData.totalPhysical -= runToDelete.physical; averageData.totalSpiritual -= runToDelete.spiritual; //calculate average from all entries if (runList.Count != 0){ averageData.mental = averageData.totalMental / runList.Count; averageData.emotional = averageData.totalEmotional / runList.Count; averageData.physical = averageData.totalPhysical / runList.Count; averageData.spiritual = averageData.totalSpiritual / runList.Count; averageData.total = averageData.mental * averageData.emotional * averageData.physical * averageData.spiritual; averageData.date = DateTime.Now; } else { averageData.mental = 0; averageData.emotional = 0; averageData.physical = 0; averageData.spiritual = 0; averageData.total = 0; averageData.date = DateTime.Now; } //write new list and averages to file String newAveragesJSON = JsonConvert.SerializeObject(averageData); await averageFile.WriteAllTextAsync(newAveragesJSON); String newRunListJSON = JsonConvert.SerializeObject(runList); await historyFile.WriteAllTextAsync(newRunListJSON); //update listView GetRuns(historyList); } public async void SaveRun (MepsRun runIN, Label mLabel, Label eLabel, Label pLabel, Label sLabel, Label totalLabel, SKCanvasView triangleCanvas) { List<MepsRun> runList; MepsRun averageData; //Create/Open folder and files IFolder mepsFolder = await rootFolder.CreateFolderAsync("MEPS_Data", CreationCollisionOption.OpenIfExists); IFile historyFile = await mepsFolder.CreateFileAsync("Run_History.txt", CreationCollisionOption.OpenIfExists); IFile averageFile = await mepsFolder.CreateFileAsync("Averages.txt", CreationCollisionOption.OpenIfExists); Debug.WriteLine(historyFile.Path); //Retrieve old data and create a list of runs from it String previousJSON = await historyFile.ReadAllTextAsync(); if (previousJSON != "") { runList = JsonConvert.DeserializeObject<List<MepsRun>>(previousJSON); } else { runList = new List<MepsRun>(); } //add new run to list runList.Reverse(); runList.Add(runIN); runList.Reverse(); Debug.WriteLine("Run Count: " + runList.Count); //Read from average file into temp average run String averageJSON = await averageFile.ReadAllTextAsync(); if (averageJSON != "") { averageData = JsonConvert.DeserializeObject<MepsRun>(averageJSON); } else { averageData = new MepsRun(0,0,0,0,DateTime.Now); } //Add new values to average totals averageData.totalMental += runIN.mental; averageData.totalEmotional += runIN.emotional; averageData.totalPhysical += runIN.physical; averageData.totalSpiritual += runIN.spiritual; //calculate average from all entries averageData.mental = averageData.totalMental / runList.Count; averageData.emotional = averageData.totalEmotional / runList.Count; averageData.physical = averageData.totalPhysical / runList.Count; averageData.spiritual = averageData.totalSpiritual / runList.Count; averageData.total = averageData.mental * averageData.emotional * averageData.physical * averageData.spiritual; averageData.date = DateTime.Now; //Write new data to history and average files String newAveragesJSON = JsonConvert.SerializeObject(averageData); await averageFile.WriteAllTextAsync(newAveragesJSON); String newRunListJSON = JsonConvert.SerializeObject(runList); await historyFile.WriteAllTextAsync(newRunListJSON); GetAveragesForLabels(mLabel, eLabel, pLabel, sLabel, totalLabel, triangleCanvas); //Debug.WriteLine(previousJSON); //Debug.WriteLine(newRunListJSON); } public async void GetAveragesForLabels(Label mLabel, Label eLabel, Label pLabel, Label sLabel, Label totalLabel, SKCanvasView triangleCanvas) { MepsRun averageRun; //Open Files IFolder mepsFolder = await rootFolder.CreateFolderAsync("MEPS_Data", CreationCollisionOption.OpenIfExists); IFile historyFile = await mepsFolder.CreateFileAsync("Run_History.txt", CreationCollisionOption.OpenIfExists); IFile averageFile = await mepsFolder.CreateFileAsync("Averages.txt", CreationCollisionOption.OpenIfExists); Debug.WriteLine(historyFile.Path); //Get average file JSON and create current average object String averageJSON = await averageFile.ReadAllTextAsync(); if (averageJSON != "") { averageRun = JsonConvert.DeserializeObject<MepsRun>(averageJSON); } else { averageRun = new MepsRun(0, 0, 0, 0, DateTime.Now); } Device.BeginInvokeOnMainThread( () => { mLabel.Text = averageRun.mental.ToString(); eLabel.Text = averageRun.emotional.ToString(); pLabel.Text = averageRun.physical.ToString(); sLabel.Text = averageRun.spiritual.ToString(); totalLabel.Text = averageRun.total.ToString(); triangleCanvas.InvalidateSurface(); }); //return averageRun; } public async Task<MepsRun> GetAveragesForTriangle() { MepsRun averageRun; //Open Files IFolder mepsFolder = await rootFolder.CreateFolderAsync("MEPS_Data", CreationCollisionOption.OpenIfExists); IFile historyFile = await mepsFolder.CreateFileAsync("Run_History.txt", CreationCollisionOption.OpenIfExists); IFile averageFile = await mepsFolder.CreateFileAsync("Averages.txt", CreationCollisionOption.OpenIfExists); Debug.WriteLine(historyFile.Path); //Get average file JSON and create current average object String averageJSON = await averageFile.ReadAllTextAsync(); if (averageJSON != "") { averageRun = JsonConvert.DeserializeObject<MepsRun>(averageJSON); } else { averageRun = new MepsRun(0, 0, 0, 0, DateTime.Now); } return averageRun; } public async void GetRuns(ListView historyList) { List<MepsRun> runList; //Create/Open folder and files IFolder mepsFolder = await rootFolder.CreateFolderAsync("MEPS_Data", CreationCollisionOption.OpenIfExists); IFile historyFile = await mepsFolder.CreateFileAsync("Run_History.txt", CreationCollisionOption.OpenIfExists); IFile averageFile = await mepsFolder.CreateFileAsync("Averages.txt", CreationCollisionOption.OpenIfExists); Debug.WriteLine(historyFile.Path); //Retrieve old data and create a list of runs from it String previousJSON = await historyFile.ReadAllTextAsync(); if (previousJSON != "") { runList = JsonConvert.DeserializeObject<List<MepsRun>>(previousJSON); } else { runList = new List<MepsRun>(); } Device.BeginInvokeOnMainThread(() => { historyList.ItemsSource = runList; }); } } }
Java
UTF-8
4,069
1.507813
2
[]
no_license
package com.facebook.events.permalink.actionbar; import com.facebook.analytics.CurationMechanism; import com.facebook.analytics.CurationSurface; import com.facebook.common.futures.AbstractDisposableFutureCallback; import com.facebook.events.eventsevents.EventsEventBus; import com.facebook.events.eventsevents.EventsEvents.EventSavingEvent; import com.facebook.events.eventsevents.EventsEvents.EventUnsavingEvent; import com.facebook.events.eventsevents.EventsEvents.EventUpdatedEvent; import com.facebook.events.model.Event; import com.facebook.fbservice.service.OperationResult; import com.facebook.feed.server.timeline.TimelineGraphPostService; import com.facebook.inject.InjectorLike; import com.facebook.story.UpdateTimelineAppCollectionParams.Action; import com.facebook.story.UpdateTimelineAppCollectionParams.Builder; import com.facebook.ui.futures.TasksManager; import com.google.common.util.concurrent.ListenableFuture; import javax.inject.Inject; /* compiled from: caller_reason */ public class ActionItemSave { public Event f18047a; public String f18048b; public String f18049c; private TimelineGraphPostService f18050d; private TasksManager f18051e; public EventsEventBus f18052f; /* compiled from: caller_reason */ class C25561 extends AbstractDisposableFutureCallback<OperationResult> { final /* synthetic */ ActionItemSave f18045a; C25561(ActionItemSave actionItemSave) { this.f18045a = actionItemSave; } protected final void m18411a(Object obj) { this.f18045a.f18052f.a(new EventUpdatedEvent(this.f18045a.f18047a.a)); } protected final void m18412a(Throwable th) { } } /* compiled from: caller_reason */ /* synthetic */ class C25572 { static final /* synthetic */ int[] f18046a = new int[Action.values().length]; static { try { f18046a[Action.ADD.ordinal()] = 1; } catch (NoSuchFieldError e) { } try { f18046a[Action.REMOVE.ordinal()] = 2; } catch (NoSuchFieldError e2) { } } } public static ActionItemSave m18413a(InjectorLike injectorLike) { return new ActionItemSave(TimelineGraphPostService.b(injectorLike), TasksManager.b(injectorLike), EventsEventBus.a(injectorLike)); } @Inject public ActionItemSave(TimelineGraphPostService timelineGraphPostService, TasksManager tasksManager, EventsEventBus eventsEventBus) { this.f18050d = timelineGraphPostService; this.f18051e = tasksManager; this.f18052f = eventsEventBus; } public final void m18415a() { m18414a(Action.ADD); } public final void m18416b() { m18414a(Action.REMOVE); } private void m18414a(Action action) { if (this.f18047a != null && this.f18048b != null && this.f18049c != null) { Builder builder = new Builder(); builder.a = this.f18048b; builder = builder; builder.b = this.f18047a.a; builder = builder; builder.c = action; builder = builder; builder.d = CurationSurface.NATIVE_EVENT; builder = builder; builder.e = CurationMechanism.TOGGLE_BUTTON; builder = builder; builder.g = this.f18049c; builder = builder; builder.j = true; ListenableFuture a = this.f18050d.a(builder.a()); C25561 c25561 = new C25561(this); Object obj = null; switch (C25572.f18046a[action.ordinal()]) { case 1: obj = "tasks-saveEvent:" + this.f18047a.a; this.f18052f.a(new EventSavingEvent()); break; case 2: obj = "tasks-removeEvent:" + this.f18047a.a; this.f18052f.a(new EventUnsavingEvent()); break; } this.f18051e.a(obj, a, c25561); } } }
C#
UTF-8
5,502
2.515625
3
[ "Apache-2.0" ]
permissive
using CryptoSQLite.Tests.Tables; using Xunit; namespace CryptoSQLite.Tests { [Collection("Sequential")] public class CountTests : BaseTest { [Fact] public void CountOfAllRecordsInTable() { var item1 = IntNumbers.GetDefault(); var item2 = IntNumbers.GetDefault(); var item3 = IntNumbers.GetDefault(); var item4 = IntNumbers.GetDefault(); foreach (var db in GetConnections()) { try { db.DeleteTable<IntNumbers>(); db.CreateTable<IntNumbers>(); db.InsertItem(item1); db.InsertItem(item2); db.InsertItem(item3); db.InsertItem(item4); var cnt = db.Count<IntNumbers>(); Assert.True(cnt == 4); db.Delete<IntNumbers>(i => i.Id == 4); cnt = db.Count<IntNumbers>(); Assert.True(cnt == 3); db.Delete<IntNumbers>(i => i.Id == 3); cnt = db.Count<IntNumbers>(); Assert.True(cnt == 2); db.Delete<IntNumbers>(i => i.Id == 2); cnt = db.Count<IntNumbers>(); Assert.True(cnt == 1); db.Delete<IntNumbers>(i => i.Id == 1); cnt = db.Count<IntNumbers>(); Assert.True(cnt == 0); } finally { db.Dispose(); } } } [Fact] public void CountOfRecordsInTableForSpecifiedColumn() { var item1 = IntNumbers.GetDefault(); item1.NullAble1 = null; var item2 = IntNumbers.GetDefault(); var item3 = IntNumbers.GetDefault(); item3.NullAble1 = null; var item4 = IntNumbers.GetDefault(); foreach (var db in GetConnections()) { try { db.DeleteTable<IntNumbers>(); db.CreateTable<IntNumbers>(); db.InsertItem(item1); db.InsertItem(item2); db.InsertItem(item3); db.InsertItem(item4); var cnt = db.Count<IntNumbers>("NullAble1"); Assert.True(cnt == 2); db.Delete<IntNumbers>(i => i.Id == 4); cnt = db.Count<IntNumbers>("NullAble1"); Assert.True(cnt == 1); db.Delete<IntNumbers>(i => i.Id == 3); cnt = db.Count<IntNumbers>("NullAble1"); Assert.True(cnt == 1); db.Delete<IntNumbers>(i => i.Id == 2); cnt = db.Count<IntNumbers>("NullAble1"); Assert.True(cnt == 0); db.Delete<IntNumbers>(i => i.Id == 1); cnt = db.Count<IntNumbers>(); Assert.True(cnt == 0); } finally { db.Dispose(); } } } [Fact] public void CountOfDistinctRecordsInTableForSpecifiedColumn() { var item1 = IntNumbers.GetDefault(); var item2 = IntNumbers.GetDefault(); var item3 = IntNumbers.GetDefault(); item3.NullAble1 = null; var item4 = IntNumbers.GetDefault(); foreach (var db in GetConnections()) { try { db.DeleteTable<IntNumbers>(); db.CreateTable<IntNumbers>(); db.InsertItem(item1); db.InsertItem(item2); db.InsertItem(item3); db.InsertItem(item4); var cnt = db.CountDistinct<IntNumbers>("NullAble1"); Assert.True(cnt == 1); } finally { db.Dispose(); } } } [Fact] public void CountOfRecordsWithCondition() { var item1 = IntNumbers.GetDefault(); item1.IntMaxVal = 9; var item2 = IntNumbers.GetDefault(); item2.IntMaxVal = 7; var item3 = IntNumbers.GetDefault(); item3.IntMaxVal = 13; var item4 = IntNumbers.GetDefault(); item4.IntMaxVal = 7; foreach (var db in GetConnections()) { try { db.DeleteTable<IntNumbers>(); db.CreateTable<IntNumbers>(); db.InsertItem(item1); db.InsertItem(item2); db.InsertItem(item3); db.InsertItem(item4); var cnt = db.Count<IntNumbers>(t => t.IntMaxVal < 10); Assert.True(cnt == 3); cnt = db.Count<IntNumbers>(t => t.IntMaxVal > 10); Assert.True(cnt == 1); cnt = db.Count<IntNumbers>(t => t.IntMaxVal == 7); Assert.True(cnt == 2); } finally { db.Dispose(); } } } } }
Python
UTF-8
352
2.765625
3
[]
no_license
class Category: def __init__(self, category_id=0, category_name='', description=''): self.category_id = category_id self.category_name = category_name self.description = description def serialize(self): return{ 'category_id' = self.category_id, 'category_name' = self.category_name, 'description' = self.description }
Java
UTF-8
848
2.375
2
[]
no_license
package com.poc.dao; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "User_Type") public class UserType { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @Column(name = "User_Type_ID") int userTypeId; @Column(name = "User_Type_Name") String name; public UserType() { super(); } public UserType(int userTypeId, String name) { super(); this.userTypeId = userTypeId; this.name = name; } public int getUserTypeId() { return userTypeId; } public void setUserTypeId(int userTypeId) { this.userTypeId = userTypeId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
C++
UTF-8
596
2.828125
3
[]
no_license
#include "Game.hpp" #include "lua.hpp" #include <iostream> #include <memory> #include <string> int main() { std::cout << "Creating game" << std::endl; auto game = std::make_unique<Game>("1st Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, false); std::cout << "Initializing logic" << std::endl; game->init_logic(std::string{"logic.lua"}); std::cout << "Starting game loop" << std::endl; while (game->running()) { game->handle_events(); game->update(); game->render(); } std::cout << "Game complete" << std::endl; return 0; }
Ruby
UTF-8
1,753
3.09375
3
[]
no_license
desc "This task make the scraping of the Relics and add them to the database" require "nokogiri" require "open-uri" task :scraping_potions => :environment do web = "https://slaythespire.gamepedia.com" potions_url = "/Potions" doc = Nokogiri::HTML(open(web + potions_url)) @newImputs = [] table = doc.at("table").search("tr").each do |tr| begin add_potion(tr.search("td")) rescue ActiveRecord::RecordInvalid => ex puts "Exception in trying to get data from a row:\n #{ex}" puts "Jumps to the next row" next rescue NoMethodError => ex puts "Exception in get the TD of the table. This is a normal exception.\n #{ex} \n" next end end printNewRecords end def add_potion(tds) image = tds[0].search("@src") name = tds[1].text.strip effect = tds[2].text.strip begin potion = Potion.create!(image: image, name: name, effect: effect) add_keyword_potions(potion) @newImputs << potion rescue ActiveRecord::RecordInvalid => ex puts "Exception in trying to create new Potion.\n #{ex}" rescue NoMethodError => ex puts "Exception in get info for a new Potion.\n #{ex}" end end def add_keyword_potions(potion) cleanEffect = potion.effect.gsub! ".", "" cleanEffect.downcase! begin cleanEffect.split(" ").each do |word| keyword = Keyword.where("lower(name) like ?", "#{word}").first unless keyword.nil? KeywordPotion.create!(potion_id: potion.id, keyword_id: keyword.id) end end rescue ActiveRecord::RecordInvalid => ex puts "Exception in trying to create keyword relation with #{potion.name}:\n #{ex}" end end def printNewRecords puts "New records added:" @newImputs.each do |input| puts input.name end end
Rust
UTF-8
3,175
3.265625
3
[]
no_license
pub mod value { use std::fmt::{self, Display}; use crate::opcodes::Instruction; #[derive(Debug, Clone, Hash)] pub enum Val { Nil, EmptyList, Cons(Box<Val>, Box<Val>), Num(i32), Bool(bool), String(String), VMFunction(VMFunction), Closure(VMFunction, Vec<Val>), } impl Val { pub fn as_num(&self) -> i32 { match self { Val::Num(i) => *i, _ => panic!("Can't be interpreted as a number"), } } pub fn as_bool(&self) -> bool { match self { Val::Nil => false, Val::EmptyList => false, Val::Num(i) => (i > &0), Val::Bool(b) => b.clone(), Val::String(_) => true, Val::VMFunction(_) => true, Val::Cons(_, _) => true, Val::Closure(_, _) => true, } } pub fn as_string(&self) -> String { match self { Val::String(s) => s.clone(), _ => panic!("Can't make a string from non-string VM Value"), } } pub fn to_num(n: i32) -> Self { Val::Num(n) } } impl Display for Val { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Val::Nil => write!(f, "{}", "nil"), Val::Num(i) => write!(f, "{}", i), Val::Bool(b) => write!(f, "{}", b), Val::String(s) => write!(f, "{}", s), Val::VMFunction(_) => write!(f, "A VM Function"), Val::EmptyList => write!(f, "'()"), Val::Cons(x, xs) => write!(f, "{} {}", x, xs), Val::Closure(_f, _cl) => write!(f, "A Vm Closure {:?}", _cl), } } } impl PartialEq for Val { fn eq(&self, other: &Self) -> bool { match self { Val::Nil => match other { Val::Nil => true, _ => false, }, Val::EmptyList => match other { Val::EmptyList => true, _ => false, }, Val::Num(i) => match other { Val::Num(j) => i == j, _ => false, }, Val::Bool(b) => match other { Val::Bool(b2) => b2 == b, _ => false, }, Val::String(s1) => match other { Val::String(s2) => s1 == s2, _ => false, }, Val::VMFunction(_) => false, Val::Cons(x, xs) => match other { Val::Cons(y, ys) => y == x && xs == ys, _ => false, }, Val::Closure(_, _) => false, } } } impl Eq for Val {} #[derive(Debug, Clone, Hash)] pub struct VMFunction { pub arity: i32, pub nregs: i32, pub size: i32, pub instructions: Vec<Instruction>, } }
Markdown
UTF-8
1,355
3.390625
3
[ "MIT" ]
permissive
# LEARNING REACT 7 - LIST MAPPING React Introduction ## Installation Clone this repository and use `npm start` in your terminal to make it start ## Activities and Objectives You are tasked to create a `MenuBar` component that gets populated from an array of objects including option name, classes, action on click and status as enabled/disabled. Disabled buttons should appear greyscaled and even when associated with an action, that should not be triggered. Examples: ``` const menuItems = [ {title: 'Home', classes: 'menu-main', action: () => {setState({display: 'home'})}, status: 'enabled'}, {title: 'Our products', classes: 'menu-opt', action: () => {setState({display: 'products'})}, status: 'enabled'}, {title: 'About us', classes: 'menu-opt', action: () => {setState({display: 'aboutUs'})}, status: 'enabled'}, {title: 'Special offers', classes: 'menu-opt', action: () => {setState({display: 'specialOffers'})}, status: 'disabled'} ]; ``` ## Extra notes and tips How would you manage different classes bases on the status of the button? How would you implement the change of status for a given item? How would you make the currently active button not clickable again? Can you think of any scenario [ie: multiple clicks on the same button, fast clicks on different buttons, etc] in which this solution would give you troubles?
Shell
UTF-8
1,899
2.90625
3
[]
no_license
#!/bin/bash rm -rf CA rm -rf Server rm -rf Client mkdir CA cd CA echo 'Generating CA Private/Public(Cert) Key Pairs' openssl req -x509 -newkey rsa:4096 -nodes -days 365 -keyout ca-key.pem -passout pass:prvt1Key -out ca-cert.pem -subj "/C=IN/ST=MP/L=INDORE/O=Hackers Inc/OU=Development/CN=shreyasd/emailAddress=shd22@gmail.com" echo "CA's Self-Signed Certificate" openssl x509 -in ca-cert.pem -noout -text cd ../ mkdir Server cd Server echo '' echo 'Generating Server Stuff now' echo '' #Generate Web Server's Private Key and CSR openssl req -newkey rsa:4096 -nodes -keyout server-key.pem -passout pass:prvt1Key -out server-csr.pem -subj "/C=IN/ST=MP/L=INDORE/O=RabbitMQServer/OU=Development/CN=rabbit/emailAddress=rabbitserver22@gmail.com" #Sign Server's Cert with CA openssl x509 -req -in server-csr.pem -days 90 -CA ../CA/ca-cert.pem -CAkey ../CA/ca-key.pem -CAcreateserial -out server-cert.pem #Server certificate openssl x509 -in server-cert.pem -noout -text echo '' echo '===========DONE GENERATING FILES===================' echo '' echo '' echo 'Verifying Server Certificates' #Verify Server's Certificate openssl verify -CAfile ../CA/ca-cert.pem server-cert.pem cd ../ mkdir Client cd Client echo '' echo 'Generating Client Certificates' echo '' #Generate Web client's Private Key and CSR openssl req -newkey rsa:4096 -nodes -keyout client-key.pem -out client-csr.pem -subj "/C=IN/ST=MP/L=INDORE/O=SpBootSTOMPClient/OU=Development/CN=bootStomp/emailAddress=boot22@gmail.com" #Sign client's Cert with CA openssl x509 -req -in client-csr.pem -days 90 -CA ../CA/ca-cert.pem -CAkey ../CA/ca-key.pem -CAcreateserial -out client-cert.pem #Client certificate openssl x509 -in client-cert.pem -noout -text echo '' echo '===========DONE GENERATING FILES===================' echo '' echo '' echo 'Verifying Client Certificates' #Verify Client's Certificate openssl verify -CAfile ../CA/ca-cert.pem client-cert.pem
Java
UTF-8
1,733
2.5
2
[]
no_license
package com.bupt.scs626.entity; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.UpdateTimestamp; import javax.persistence.*; import java.util.Date; /** * Created by cj . */ @Entity @Table(name = "light") public class Light { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") @Column(name = "ID") private String id; @Temporal(TemporalType.TIMESTAMP) @CreationTimestamp @Column(name= "create_time") private Date createTime; @Temporal(TemporalType.TIMESTAMP) @UpdateTimestamp @Column(name= "last_update") private Date lastUpdate; @Column(name = "belongs") private String belongs; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBelongs() { return belongs; } public void setBelongs(String belongs) { this.belongs = belongs; } public int getState() { return state; } public void setState(int state) { this.state = state; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastUpdate() { return lastUpdate; } public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } @Column(name = "state") private int state; public Light() { } public Light(Light light) { this.id =light.getId(); this.state = light.getState(); this.belongs = light.getBelongs(); } }
Python
UTF-8
141
3.46875
3
[]
no_license
height = input("How tall are you? ") if height > 150 : print "wow you`re tall!" if height >= 56 : print "ok!" else : print "too short"
C++
UTF-8
1,532
2.75
3
[]
no_license
/* * split_by_row_test.cpp * * Created on: 2013.12.11. * Author: kisstom */ #include "../../../main/common/graph_converter/split_by_row.h" #include <gtest/gtest.h> #include <stdio.h> #include <vector> #include <iostream> #include <sstream> using std::vector; using std::stringstream; using std::ios_base; using std::stringstream; namespace { class SplitByRowTest: public ::testing::Test { protected: // You can remove any or all of the following functions if its body // is empty. SplitByRowTest() { } virtual ~SplitByRowTest() { // You can do clean-up work that doesn't throw exceptions here. } // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: static void SetUpTestCase() { } static void TearDownTestCase() { } virtual void SetUp() { } virtual void TearDown() { } // Objects declared here can be used by all tests in the test case for Foo. }; TEST(SplitByRowTest, testEdgeCount) { SplitByRow splitByRow; char line[1024] = "1 2 3 4\n"; long count = splitByRow.countEdges(line); ASSERT_EQ(4, count); char line2[1024] = "1 2 3 4"; count = splitByRow.countEdges(line2); ASSERT_EQ(4, count); char line3[1024] = "\n"; count = splitByRow.countEdges(line3); ASSERT_EQ(0, count); char line4[1024] = ""; count = splitByRow.countEdges(line4); ASSERT_EQ(0, count); } } int main (int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
C++
WINDOWS-1251
1,370
3.375
3
[]
no_license
// 5.1.9.3.Obtaining_derived_data_from_object.cpp: . // #include "stdafx.h" #include <iostream> #include <string> using namespace std; class AdHocSquare { public: AdHocSquare(double side) { set_side(side); } void set_side(double side); double get_area(); private: double side; }; void AdHocSquare::set_side(double side) { if(side>=0) this->side = side; else if(this->side == NULL) this->side = 0; } double AdHocSquare::get_area() { return this->side*this->side; } class LazySquare { public: LazySquare(double side) { set_side(side); this->area = this->side*this->side; } void set_side(double side); double get_area(); private: double side; double area; bool side_changed; }; void LazySquare::set_side(double side) { if(side>=0){ this->side = side; this->side_changed = 1; } else if(this->side == NULL) this->side = 0; } double LazySquare::get_area() { if(this->side_changed) { this->area = this->side*this->side; this->side_changed = 0; return this->area; } else return this->area; } int _tmain(int argc, _TCHAR* argv[]) { LazySquare ls(2); cout<<ls.get_area()<<endl; ls.set_side(3); cout<<ls.get_area()<<endl; AdHocSquare ad(4); cout<<ad.get_area()<<endl; ad.set_side(5); cout<<ad.get_area()<<endl; return 0; }
PHP
UTF-8
617
2.609375
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'status', 'nickname', 'music', 'about', 'skype', 'phone', 'avatar' ]; protected $hidden = [ 'password', 'remember_token', ]; public function instruments() { return $this->belongsToMany('App\Models\Instrument')->withPivot('level'); } }
Java
UHC
1,189
3.390625
3
[]
no_license
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MouseWheelFrame extends JFrame { public MouseWheelFrame() { super("콺 Ʈ ũ "); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JLabel label = new JLabel("Love Java"); c.add(label); label.setFont(new Font("Arial", Font.PLAIN, 15)); // 15 ȼ ũ label.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { int n = e.getWheelRotation(); if(n < 0) { // up direction. Ʈ ۰ JLabel la = (JLabel)e.getSource(); Font f = la.getFont(); int size = f.getSize(); if(size <= 5) return; la.setFont(new Font("Arial", Font.PLAIN, size-5)); } else { // down direction. Ʈ ũ JLabel la = (JLabel)e.getSource(); Font f = la.getFont(); int size = f.getSize(); la.setFont(new Font("TimesRoman", Font.PLAIN, size+5)); } } }); setSize(300,150); setVisible(true); } static public void main(String [] args) { new MouseWheelFrame(); } }
C++
UTF-8
1,095
3.140625
3
[]
no_license
#ifndef GPIO_H #define GPIO_H #include <fstream> #include <string> #include <sstream> class GPIO { public: enum DIRECTION {IN, OUT}; protected: unsigned port; DIRECTION dir; public: GPIO(unsigned port, DIRECTION dir); ~GPIO(); // 设置 void set(unsigned port, DIRECTION dir); // 设置方向 void setDirection(DIRECTION dir); // 设置端口 void setPort(unsigned port); // 设置高低电位 void low() const; void high() const; // 产生脉冲 // @lowWidth 低电平时间 // @highWidth 高电平时间 // @times 完整的周期数 void pulse(unsigned lowWidth = 1, unsigned highWidth = 1, unsigned times = 1) const; // 产生上升/下降沿 void up(unsigned times = 1) const; void down(unsigned times = 1) const; // 读取高低电位 bool value() const; // 读取方向 DIRECTION direction() const; // gpio是否已经存在 static bool exist(unsigned gpio); protected: // 导出 void exportPort() const; void unexportPort() const; }; #endif // GPIO_H
C++
UTF-8
609
2.875
3
[ "Apache-2.0" ]
permissive
#ifndef PROCESSH_H #define PROCESSH_H #include <string> // Basic class for Process representation // It contains relevant attributes as shown below // Renamed this file to processh.h cause it was conflicting with process.h found // in Windows Kit class Process { public: Process(int pid); int Pid(); std::string User(); std::string Command(); float CpuUtilization(); std::string Ram(); long int UpTime(); bool operator<(Process const& a) const; private: int _pid = 0; std::string _user; std::string _cmd; float _cpuUtilization; std::string _ram; long int _upTime; }; #endif
C++
UTF-8
6,174
2.8125
3
[ "MIT" ]
permissive
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { // Use GL_TEXTURE_2D Textures (normalized texture coordinates 0..1) ofDisableArbTex(); // FBO with multiple render targets ofFbo::Settings fboSettings; fboSettings.width = ofGetWindowWidth(); fboSettings.height = ofGetWindowHeight(); fboSettings.internalformat = GL_RGBA8; fboSettings.numSamples = 0; fboSettings.useDepth = false; fboSettings.useStencil = false; fboSettings.textureTarget = GL_TEXTURE_2D; fboSettings.minFilter = GL_LINEAR; fboSettings.maxFilter = GL_LINEAR; // this is important to keep clean edges on the blur fboSettings.wrapModeHorizontal = GL_CLAMP_TO_EDGE; fboSettings.wrapModeVertical = GL_CLAMP_TO_EDGE; // create our FBO with the above settings m_fbo.allocate( fboSettings ); // load our single pass shader m_singlePassBoxBlurShader.load( "shaders/passthrough.vert", "shaders/singlePassBoxBlur.frag" ); // load our two pass blur shader m_blurHorizShader.load( "shaders/passthrough.vert", "shaders/blurHorizontal.frag" ); m_blurVerticalShader.load( "shaders/passthrough.vert", "shaders/blurVertical.frag" ); // the image we want to blur ofImage image( "images/image.jpg" ); m_texture = image.getTexture(); m_texture.setTextureMinMagFilter( GL_LINEAR, GL_LINEAR ); m_texture.setTextureWrap( GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE ); // this is important to keep clean edges on the blur createFullScreenQuad(); m_blurRadius = 1.0f; } void ofApp::createFullScreenQuad() { // -1.0 to +1.0 is the full viewport (screen) if you use these as vertices in your vertex shader // (without multiplying by model, view, and projection matrices) ofVec3f vertices[4] = { ofVec3f( 1.0f, 1.0f, 0.0f ), ofVec3f( -1.0f, 1.0f, 0.0f ), ofVec3f( 1.0f, -1.0f, 0.0f ), ofVec3f( -1.0f, -1.0f, 0.0f ) }; ofIndexType indices[6] = { 0, 1, 2, 2, 1, 3 }; // Texture coordinates vary from 0.0 to 1.0 when they are in normalized format // ofDisableArbTex() was called earlier set that we're using normalized texture coordinates ofVec2f texCoords[4] = { ofVec2f( 1.0f, 1.0f ), ofVec2f( 0.0f, 1.0f ), ofVec2f( 1.0f, 0.0f ), ofVec2f( 0.0f, 0.0f ) }; m_fsQuadVbo.addVertices( vertices, 4 ); m_fsQuadVbo.addTexCoords( texCoords, 4 ); m_fsQuadVbo.addIndices( indices, 6 ); } //-------------------------------------------------------------- void ofApp::update() { } //-------------------------------------------------------------- void ofApp::draw() { ofClear( 0, 0, 0, 255 ); ofDisableDepthTest(); glEnable( GL_CULL_FACE ); glCullFace( GL_BACK ); bool bDoSinglePassBlur = true; if ( true == bDoSinglePassBlur ) { // Completing the blur in a single pass instead of separate passes. m_singlePassBoxBlurShader.begin(); m_singlePassBoxBlurShader.setUniform1f( "uBlurRadius", m_blurRadius ); m_singlePassBoxBlurShader.setUniformTexture( "uTexture", m_texture, 0 ); // the size of 1 pixel (texel) in a normalized (0.0 .. 1.0) texture uv space is: // pixel_width: 1.0 / width // pixel_height: 1.0 / height m_singlePassBoxBlurShader.setUniform2f( "uTexelSize", 1.0f / (float)ofGetViewportWidth(), 1.0f / (float)ofGetViewportHeight() ); m_fsQuadVbo.draw(); m_singlePassBoxBlurShader.end(); } else { // Separable 2-pass blur // Horizontal blur pass // render the result to an FBO m_fbo.begin(); { m_blurHorizShader.begin(); m_blurHorizShader.setUniform1f( "uBlurRadius", m_blurRadius ); m_blurHorizShader.setUniformTexture( "uTexture", m_texture, 0 ); m_blurHorizShader.setUniform2f( "uTexelSize", 1.0f / (float)ofGetViewportWidth(), 1.0f / (float)ofGetViewportHeight() ); m_fsQuadVbo.draw(); m_blurHorizShader.end(); } m_fbo.end(); // Vertical blur pass - take the result of the horizontal blur pass and perform the vertical blur on it // This cuts down on the number of samples - a 9x9 tap blur will be 18 samples instead of 81! m_blurVerticalShader.begin(); m_blurVerticalShader.setUniform1f( "uBlurRadius", m_blurRadius ); // use result from horizontal pass as source texture m_blurVerticalShader.setUniformTexture( "uTexture", m_fbo.getTexture(), 0 ); m_blurVerticalShader.setUniform2f( "uTexelSize", 1.0f / (float)ofGetViewportWidth(), 1.0f / (float)ofGetViewportHeight() ); m_fsQuadVbo.draw(); m_blurVerticalShader.end(); // Note - you could render the 2nd pass to another fbo vs. the screen // This would allow you to use the blurred texture elsewhere for further post-processing for example } } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { } //-------------------------------------------------------------- void ofApp::keyReleased(int key) { } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ) { m_blurRadius = (float)x / (float)ofGetWindowWidth() * 4.0f; } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
Python
UTF-8
628
4.3125
4
[]
no_license
# In this lets see about the "Built-in functions" in python. # Built-in function is defined as the functions whose functionality is pre-defined in the python compiler. # Lets see about "ord( ) bilt-in function" in python. # ord( ) - Used to return an unicode value for the given String. # Here is the program for ord( ). print( "\nUnicode value of \"5\" is : " , ord( '5' ) ) print( "\nUnicode value of \"R\" is : " , ord( 'R' ) ) print( "\nUnicode value of \"r\" is : " , ord( 'r' ) ) print( "\nUnicode value of \"@\" is : " , ord( '@' ) ) print( "\nUnicode value of \"#\" is : " , ord( '#' ) )
Markdown
UTF-8
4,275
3.015625
3
[ "MIT" ]
permissive
--- layout: series title: GeoData Training Programme description: A training to help civil servants operationalise geographical data and tools for public health and disaster response. permalink: /series/open-geodata-programme/ --- ### Context Last year, Facebook publicly released the world’s most accurate population density maps for 170+ countries, built with satellite imagery and projected census data. This data has already had impact on life-saving service delivery, such as during the 2016-2017 measles and rubella campaign in Malawi, where the data allowed Missing Maps Program volunteers to reach 95% of children under five with vaccinations. Today these maps are used around the world to help plan local electricity grids, analyse hospital accessibility, or deploy COVID19 interventions. There are vast opportunities for civil servants and non-profits to make use of this public data to improve the delivery of a variety of projects, from vaccination campaigns to pandemic response to infrastructure planning. With a little bit of training and support, civil servants could become much more efficient at using geographical data and tools, thereby multiplying the impact of their agencies on the populations they serve. ### Objectives Objectives To address this need, Facebook’s Data for Good team has partnered with the Open Knowledge Foundation to design a free and open source geographical information system (GIS) training programme for governments around the world. The programme will aim to: - Raise awareness about the free GIS resources available to governments - Teach participants the skills needed to use these resources for public health and disaster response - Familiarize governments with Facebook’s Population Density Map for their country - Create space for governments to innovate in their practices by making use of data ### The Training The training programme will be split into two phases, both delivered remotely: - Two days of live sessions on Zoom where participants will learn about how to use, analyse and share geographical data in a public health and disaster response context - 4 weeks of mentoring, where participants will progress at their pace on small projects allowing them to apply what they’ve learned to their day to day work. The requested time commitment of the nominated participants will thus amount to over the course of five weeks--two days on Zoom and roughly one day per week over the 4 weeks of mentoring. Between 10 to 15 participants are expected. They will receive a certificate at the end of the training and gain access to a supplemental GIS curriculum to further their learning. Ideally, participants should be - working on public health or disaster response programmes, and - directly involved in the planning, coordination or delivery of these programmes The projects that participants take on during the mentoring phase will be decided based on their skill level and the needs of their work. Some example projects: - An updated process for generating COVID19 contamination maps - An analysis of health infrastructure accessibility - A new open dataset related to public health - A report on the gaps in the data needed to improve disaster response ### The team **Facebook’s Data For Good** team makes data available to researchers, non profits, and the public sector, enabling them to address some of the world’s greatest humanitarian issues. Our partners leverage this data to address disaster response, health, connectivity, energy access, and economic growth. Privacy is built into all of our products by default; we use techniques such as aggregation and differential privacy to protect privacy. We have public datasets which are available on the Humanitarian Data Exchange, and private datasets which are only available to vetted non profits and researchers. **Open Knowledge Foundation (OKF)** is a global non-profit organisation focused on realising open data’s value to society by helping individuals and organisations access and use data to take action on social problems. OKF coordinates several global networks of non-profits and individuals aligned with its mission, including School of Data, a network of data trainers spanning more than 30 countries.
Python
UTF-8
4,011
2.859375
3
[ "MIT" ]
permissive
"""Used for generating failure recommendations on the Insights page of the dashboard""" def get_failure_tip(current, previous, last_success): if current.is_success(): return "All good.", "" else: return handle_failure(current, previous, last_success) def handle_failure(current, previous, last_success): last_claim = "" if previous and current: if previous.stage.description and previous.stage.responsible: last_claim = "Last claim: {}: {}".format(previous.stage.responsible, previous.stage.description) if current.stage.failure_stage == "POST": return "All tests passed, but the build failed.", last_claim elif current.stage.failure_stage == "STARTUP": return "Tests failed during STARTUP.", last_claim else: return handle_test_failure(current, previous, last_success), last_claim def handle_test_failure(current, previous, last_success): failure_recommendation = FailureRecommendation(current, previous, last_success) if failure_recommendation.initial_tip_available(): initial_tip = failure_recommendation.get_initial_recommendation() if initial_tip: return initial_tip fallback_tip = failure_recommendation.get_fallback_recommendation() return fallback_tip class FailureRecommendation: def __init__(self, current, previous, last_success): self.current = current self.previous = previous self.last_success = last_success self.statistics_actions = [ ( lambda: self.current.stage.failure_stage == "STARTUP" and self.current.stage.failure_stage == self.previous.stage.failure_stage, "Tests have failed at STARTUP several times in a row. Recommend to rerun after investigation."), ( lambda: len(self.current.test_names) == 1 and 1 in current.test_names, # Very specific for characterize "Recommend to rerun."), ( lambda: self.current.failure_signature == self.previous.failure_signature and self.current.test_names == self.previous.test_names, "Same failure signature and same failure indices as last failure."), (lambda: self.current.failure_signature == self.previous.failure_signature, "Same failure signature as last test. Unlikely flickering."), (lambda: self.current.test_names == self.previous.test_names, "Same failure indices as last test. Unlikely flickering."), (lambda: len(current.test_names) == 1, "Only one test failure. Potential for flickering but needs further investigation."), (lambda: len(self.current.test_names) == len(self.previous.test_names), "Same number of failures as previous test. Unlikely flickering.") ] self.fallback_actions = [ (lambda: self.previous.is_success(), "Last pipeline was a success. Potential for flickering but may need further investigation."), (lambda: self.current.stage.pipeline_counter - last_success >= 3, "Pipeline hasn't been green in a long time."), ] self.default = "Last pipeline was a failure. Recommend to investigate further." def get_initial_recommendation(self): statistics_match = self.any_match() if statistics_match: return statistics_match def get_fallback_recommendation(self): return self.pick_match() def any_match(self): for predicate, string in self.statistics_actions: if predicate(): return string return None def pick_match(self): for predicate, string in self.fallback_actions: if predicate(): return string return self.default def initial_tip_available(self): return self.current.has_error_statistics() and not self.previous.is_success() and self.previous.has_error_statistics()
JavaScript
UTF-8
1,873
3.140625
3
[]
no_license
let request = require('request'); let fs = require('fs'); let secrets = require('./secrets.js'); let args = process.argv.slice(2); function getRepoContributors(repo, callback) { //URL and headers for API request let options = { url: "https://api.github.com/repos/" + repo[0] + "/" + repo[1] + "/contributors", headers: { "Authorization": `token ${secrets.GITHUB_TOKEN}`, "User-Agent": "request" } }; //Perform callback function on response request(options, function(err, result, body) { callback(err, body); }); } function downloadImageByURL(url, dir, filePath) { //If the target directory doesn't exist, create it if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } //Make GET request request.get(url) .on('error', function(err) { console.log(err); }) .on('end', function(response) { console.log(`Avatar download complete`) }) //Write each image to file using given directory and filepath .pipe(fs.createWriteStream(`${dir}/${filePath}`)); } //////////Program start////////// console.log('Welcome to the GitHub Avatar Downloader!'); //If there are more or fewer than 2 arguments, ask for two arguments if (args.length !== 2) { console.log("Please provide the repository owner and name as arguments as such:"); console.log("<repoOwner> <repoName>"); } //Otherwise, call getRepoContributors with callback else { getRepoContributors(args, function(err, result) { const resultObj = JSON.parse(result); //If there is no error //for each avatar, feed the avatar URL, target directory, and username to downloadImageByURL function if (err) { console.log("Errors:", err); } else { for (let obj of resultObj) { downloadImageByURL(obj.avatar_url, './avatars', obj.login); } } }); }
Shell
UTF-8
920
2.796875
3
[]
no_license
#!/bin/bash . ./path.sh || exit 1 . ./cmd.sh || exit 1 nj=1 # number of parallel jobs - 1 is perfect for such a small data set lm_order=1 # language model order (n-gram quantity) - 1 is enough for digits grammar # Safety mechanism (possible running this script with modified arguments) . utils/parse_options.sh || exit 1 [[ $# -ge 1 ]] && { echo "Wrong arguments!"; exit 1; } utils/utt2spk_to_spk2utt.pl data/test/utt2spk > data/test/spk2utt mfccdir=mfcc steps/make_mfcc.sh --nj $nj --cmd "$train_cmd" data/test exp/make_mfcc/test $mfccdir steps/compute_cmvn_stats.sh data/test exp/make_mfcc/test $mfccdir echo echo "===== TRI1 (first triphone pass) DECODING =====" echo utils/mkgraph.sh data/lang exp/tri1 exp/tri1/graph || exit 1 steps/decode.sh --config conf/decode.config --nj $nj --cmd "$decode_cmd" exp/tri1/graph data/test exp/tri1/decode echo echo "===== run.sh script is finished =====" echo
JavaScript
UTF-8
2,886
2.515625
3
[ "MIT" ]
permissive
import React, { useState, useRef, useEffect } from "react"; import { createUseStyles } from "react-jss"; import Color from './color'; import ColorBox from "./colorBox"; import HexBox from "./hexBox"; import utils from "./utils"; import ColorComponentPicker from "./colorComponentPicker"; // Fun fact: this is Pantone Color Institute's color of the year 2019 (Living Coral) const defaultColor = new Color({ r: 255, g: 111, b: 97, a: 255 }); const styles = { root: { display: "inline-block", padding: 8, borderRadius: 4, background: "white", boxShadow: "grey 1px 1px 2px" }, text: { marginLeft: 8, width: "3em", padding: 4, border: "1px solid grey", borderRadius: "0.2em", margin: 0 }, mb8: { marginBottom: 8 } }; const useStyles = createUseStyles(styles); export default function ColorPicker(props) { //TODO: make default color overridable const { className = "", initialColor = defaultColor, callback, exportFormat = "hex", ...other } = props; let initialColorFormat = "hex"; useEffect(() => { initialColorFormat = utils.determineColorFormat(initialColor); }, [initialColor]); const [color, setColor] = useState(initialColor); const { r, g, b, a } = color; const classes = useStyles(color); useEffect(() => { if (props.callback) props.callback(color); }, [color]); return ( <div className={classes.root + " " + className}> <ColorComponentPicker background="linear-gradient(to right, black, red)" from={0} to={255} className={classes.mb8} label="R" value={color.r} callback={v => setColor(new Color({ r: v, g, b, a }))} /> <ColorComponentPicker background="linear-gradient(to right, black, green)" from={0} to={255} className={classes.mb8} label="G" value={color.g} callback={v => setColor(new Color({ r, g: v, b, a }))} /> <ColorComponentPicker background="linear-gradient(to right, black, blue)" from={0} to={255} className={classes.mb8} label="B" value={color.b} callback={v => setColor(new Color({ r, g, b: v, a }))} /> <ColorComponentPicker background="linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 255))" from={0} to={255} className={classes.mb8} label="A" value={color.a} callback={v => setColor(new Color({ r, g, b, a: v }))} /> <div style={{ display: "flex", alignItems: "" }}> <ColorBox color={{ r, g, b, a }} /> <HexBox value={utils.toHexString(r, g, b)} callback={(v) => { const newColor = Color.from(v); if (newColor) setColor(newColor); }} /> </div> </div> ); }
C++
UTF-8
1,471
3.140625
3
[]
no_license
#include "bst_node.h" using namespace std; BSTNode::BSTNode () { left = NULL; right = NULL; } BSTNode::BSTNode (string word, unsigned int freq) { left = NULL; right = NULL; wordObj_.setFreq(freq); wordObj_.setWord(word); } BSTNode::BSTNode (word aWord) { left = NULL; right = NULL; wordObj_ = aWord; } word BSTNode::get_Obj () const { return wordObj_; } string BSTNode::get_Word () const { return wordObj_.getWord(); } unsigned int BSTNode::get_Freq() const { return wordObj_.getFreq(); } BSTNode* BSTNode::left_child () const { return left; } BSTNode* BSTNode::right_child() const { return right; } void BSTNode::set_left_child(BSTNode* node) { left = node; } void BSTNode::set_right_child(BSTNode* node) { right = node; } void BSTNode::set_Word (string word) { wordObj_.setWord(word); } void BSTNode::set_Freq (unsigned int freq) { wordObj_.setFreq(freq); } void BSTNode::set_Obj (word aWord) { wordObj_ = aWord; }
C#
UTF-8
645
3.265625
3
[]
no_license
public interface IClass { int a { get; set; } int b { get; set; } } class First : IClass { public int a { get; set; } public int b { get; set; } public int c = 2; public _second; public First() { _second = new Second(this, c); } } class Second { public Second(IClass ic, int c) { if(c == 0) { ic.a = 1; ic.b = 2; } else { ic.a = -1; ic.b = -2; } } }
PHP
UTF-8
1,039
2.8125
3
[ "MIT" ]
permissive
<?php /* List file names & line numbers for all stack frames; clicking these links/buttons will display the code view for that particular frame */ ?> <?php foreach ($frames as $i => $frame): ?> <div class="frame <?php echo ($i == 0 ? 'active' : '') ?> <?php echo ($frame->isApplication() ? 'frame-application' : '') ?>" id="frame-line-<?php echo $i ?>"> <span class="frame-index"><?php echo (count($frames) - $i - 1) ?></span> <div class="frame-method-info"> <span class="frame-class"><?php echo $tpl->breakOnDelimiter('\\', $tpl->escape($frame->getClass() ?: '')) ?></span> <span class="frame-function"><?php echo $tpl->breakOnDelimiter('\\', $tpl->escape($frame->getFunction() ?: '')) ?></span> </div> <div class="frame-file"> <?php echo $frame->getFile() ? $tpl->breakOnDelimiter('/', $tpl->shorten($tpl->escape($frame->getFile()))) : '<#unknown>' ?><!-- --><span class="frame-line"><?php echo (int) $frame->getLine() ?></span> </div> </div> <?php endforeach;
JavaScript
UTF-8
1,075
2.765625
3
[]
no_license
const bcrypt = require("bcrypt"); const userRouter = require("express").Router(); const User = require("../models/user"); userRouter.get("/", async (request, response) => { const users = await User.find({}); response.json(users); }); userRouter.post("/", async (request, response) => { const { username, name, password } = request.body; console.log((username.length && password.length) < 3); if ((username.length && password.length) < 3) { return response .status(400) .json({ error: "username or password is shorter than minimun allowed length (3)", }); } const saltRounds = 10; const passwordHash = password === undefined ? false : await bcrypt.hash(password, saltRounds); const user = new User({ username, name, passwordHash, }); if (username && name && password) { const savedUser = await user.save(); response.json(savedUser); } else { response .status(401) .json({ error: "please fill out the entire form" }) .end(); } }); module.exports = userRouter;
Python
UTF-8
290
2.921875
3
[]
no_license
data=[ { 'name': 'dipesh shrestha', 'email': 'dipdreaming92@gmail.com' }, { 'name':'dinesh shrestha', 'email': 'dinesh95@gmail.com' } ] print('name:%s' %data[1]['name']) print('name:%s' %data[1]['email']) for(i,item) in enumerate(data): print('\nuser %d' %(i+1)) print('name: %s' %item['name']) print('name: %s' %item['email'])
Java
UHC
1,402
3.484375
3
[]
no_license
package org.comstudy21.ch11ex04; public class { public static void test02(String[] args) { [] aniArr = new [3]; aniArr[0] = new (); aniArr[1] = new (); aniArr[2] = new (); for(int i=0;i<aniArr.length;i++){ if(aniArr[i] instanceof ){ (()aniArr[i]).Դ(); } if(aniArr[i] instanceof ){ (()aniArr[i]).Դ(); } if(aniArr[i] instanceof ){ (()aniArr[i]).Դ(); } } } public static void main(String[] args) { ani = new (""); ani.Ҹ(); if(ani instanceof ){ (()ani).Ҹ(); } ani.Դ(); if(ani instanceof ){ (()ani).Դ(); } ani.̴(); if(ani instanceof ){ (()ani).̴(); } ani = new (""); ani.Ҹ(); if(ani instanceof ){ (()ani).Ҹ(); } ani.Դ(); if(ani instanceof ){ (()ani).Դ(); } ani.̴(); if(ani instanceof ){ (()ani).̴(); } ani = new (""); ani.Ҹ(); if(ani instanceof ){ (()ani).Ҹ(); } ani.Դ(); if(ani instanceof ){ (()ani).Դ(); } ani.̴(); if(ani instanceof ){ (()ani).̴(); } } }
TypeScript
UTF-8
124
2.671875
3
[]
no_license
export class Hello { getName() { return 'Jest' } sayGreeting() { return `Hello, ${this.getName()}!`; } }
JavaScript
UTF-8
1,310
2.546875
3
[ "MIT" ]
permissive
/** * Created with JetBrains WebStorm. * User: admin * Date: 01/08/2013 * Time: 01:50 * To change this template use File | Settings | File Templates. */ var readline = require('readline'), rl = readline.createInterface(process.stdin, process.stdout); var promts = [ 'Enter admin email address: ', 'Enter admin password: '] function setPrompt() { rl.setPrompt(promts[index]); rl.prompt(); index++; } var env = process.env.NODE_ENV || 'development' , config = require('./config/config')[env] , mongoose = require('mongoose'); mongoose.connect(config.db) var User = require('./app/models').User; var user = new User({email:'', password:''}) var index = 0; setPrompt(); rl.on('line', function(line) { switch(index) { case 1 : user.email = line.trim(); break; case 2 : user.password = line.trim(); user.save(function(err, user) { if(err) console.error(err); else console.log('Admin added:', user.email); }); return; break; } console.log('---------'); setPrompt(); }).on('close', function() { console.log('As Buddha said: "Attaching to THINGS brings suffering only. Stay independent."'); process.exit(0); });
Java
UTF-8
518
1.734375
2
[ "Apache-2.0" ]
permissive
package tv.bgm.materialdesgincomponent.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import tv.bgm.materialdesgincomponent.R; /** * Created by Chihiro on 2018/8/7. */ public class ConstraintLayoutActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.material_desgin_constraint_layout); } }
Markdown
UTF-8
1,692
2.796875
3
[ "MIT" ]
permissive
# Cache Middleware The Cache middleware uses the Web Standard's [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache). It caches a given response according to the `Cache-Control` headers. The Cache middleware currently supports Cloudflare Workers projects using custom domains and Deno projects using [Deno 1.26+](https://github.com/denoland/deno/releases/tag/v1.26.0), but doesn't supports Lagon. See [Usage](#usage) below for instructions on each platform. ## Import ::: code-group ```ts [npm] import { Hono } from 'hono' import { cache } from 'hono/cache' ``` ```ts [Deno] import { Hono } from 'https://deno.land/x/hono/mod.ts' import { cache } from 'https://deno.land/x/hono/middleware.ts' ``` ::: ## Usage ::: code-group ```ts [Cloudflare Workers] app.get( '*', cache({ cacheName: 'my-app', cacheControl: 'max-age=3600', }) ) ``` ```ts [Deno] // Must use `wait: true` for the Deno runtime app.get( '*', cache({ cacheName: 'my-app', cacheControl: 'max-age=3600', wait: true, }) ) ``` ::: ## Options - `cacheName`: string - _required_ - The name of the cache. Can be used to store multiple caches with different identifiers. - `wait`: boolean - A boolean indicating if Hono should wait for the Promise of the `cache.put` function to resolve before continuing with the request. _Required to be true for the Deno environment_. Default is `false`. - `cacheControl`: string - A string of directives for the `Cache-Control` header. See the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) for more information. When this option is not provided, no `Cache-Control` header is added to requests.
JavaScript
UTF-8
3,168
2.625
3
[]
no_license
function lollipopPlot() { let margin = {top: 20, right: 20, bottom: 30, left: 40}, width = 600, height = 400, innerWidth = width - margin.left - margin.right, innerHeight = height - margin.top - margin.bottom, xValue = d => d[0], yValue = d => d[1], xScale = d3.scaleLinear(), yScale = d3.scaleLinear(), dayScale = d3.scaleBand().padding(0.92); function chart(selection) { selection.each(function (data) { const svg = d3.select(this).selectAll("svg").data([data]); const svgEnter = svg.enter().append("svg"); const gEnter = svgEnter.append("g"); gEnter.append("g").attr("class", "x axis"); gEnter.append("g").attr("class", "y axis"); svg.merge(svgEnter).attr("width", width) .attr("height", height); const g = svg.merge(svgEnter).select("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); xScale.rangeRound([0, innerWidth]) .domain([-0.97, data.length-0.03]); yScale.rangeRound([innerHeight, 0]) .domain([0, d3.max(data, d => yValue(d))]); dayScale.rangeRound([0, innerWidth]) .domain(data.map(xValue)); g.select(".x.axis") .attr("transform", "translate(0," + innerHeight + ")") .call(d3.axisBottom(dayScale)); g.select(".y.axis") .call(d3.axisLeft(yScale).ticks(10)) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("text-anchor", "middle") .text("Workload"); const points = g.selectAll(".point") .data(data); points.enter().append("circle") .attr("class", "point") .merge(points) .attr("cx", d => xScale(data.indexOf(d))) .attr("cy", d => yScale(yValue(d))) .attr("r", 15) .attr("fill", "#fbd14b") .attr("opacity", 0.8) .on("mouseover", onMouseOver) .on("mouseout", onMouseOut); const bars = g.selectAll(".bar") .data(data); bars.enter().append("rect") .attr("class", "bar") .merge(bars) .attr("x", d => dayScale(xValue(d))) .attr("y", d => yScale(yValue(d))) .attr("width", dayScale.bandwidth()) .attr("height", d => innerHeight - yScale(yValue(d))) .attr('fill', "#fbd14b") .attr("opacity", 0.5) .on("mouseover", onMouseOver) .on("mouseout", onMouseOut); points.exit().remove(); }); } chart.x = function(d) { if (!arguments.length) return xValue; xValue = d; return chart; }; chart.y = function(d) { if (!arguments.length) return yValue; yValue = d; return chart; }; chart.onMouseOver = function(d) { if (!arguments.length) return onMouseOver; onMouseOver = d; return chart; }; chart.onMouseOut = function(d) { if (!arguments.length) return onMouseOut; onMouseOut = d; return chart; }; return chart; }