text:
<file_sep>rootProject.name = 'rest-counter'

<file_sep>package countries.dto;

import countries.dto.subentity.Translations;

import java.util.List;
import java.util.Objects;

public class CountryDto2 {
	private String name;
	private String capital;
	private List<String> altSpellings;
	private String relevance;
	private String region;
	private String subregion;
	private Translations translations;
	private Long population;
	private List<Float> latlng;
	private String demonym;
	private Long area;
	private Float gini;
	private List<String> timezones;
	private List<String> callingCodes;
	private List<String> topLevelDomain;
	private List<String> currencies;
	private List<String> languages;

	public CountryDto2(String name, String capital, List<String> altSpellings, String relevance, String region, String subregion, Translations translations, Long population, List<Float> latlng, String demonym, Long area, Float gini, List<String> timezones, List<String> callingCodes, List<String> topLevelDomain, List<String> currencies, List<String> languages) {
		this.name = name;
		this.capital = capital;
		this.altSpellings = altSpellings;
		this.relevance = relevance;
		this.region = region;
		this.subregion = subregion;
		this.translations = translations;
		this.population = population;
		this.latlng = latlng;
		this.demonym = demonym;
		this.area = area;
		this.gini = gini;
		this.timezones = timezones;
		this.callingCodes = callingCodes;
		this.topLevelDomain = topLevelDomain;
		this.currencies = currencies;
		this.languages = languages;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCapital() {
		return capital;
	}

	public void setCapital(String capital) {
		this.capital = capital;
	}

	public List<String> getAltSpellings() {
		return altSpellings;
	}

	public void setAltSpellings(List<String> altSpellings) {
		this.altSpellings = altSpellings;
	}

	public String getRelevance() {
		return relevance;
	}

	public void setRelevance(String relevance) {
		this.relevance = relevance;
	}

	public String getRegion() {
		return region;
	}

	public void setRegion(String region) {
		this.region = region;
	}

	public String getSubregion() {
		return subregion;
	}

	public void setSubregion(String subregion) {
		this.subregion = subregion;
	}

	public Translations getTranslations() {
		return translations;
	}

	public void setTranslations(Translations translations) {
		this.translations = translations;
	}

	public Long getPopulation() {
		return population;
	}

	public CountryDto2 setPopulation(Long population) {
		this.population = population;
		return this;
	}

	public List<Float> getLatlng() {
		return latlng;
	}

	public void setLatlng(List<Float> latlng) {
		this.latlng = latlng;
	}

	public String getDemonym() {
		return demonym;
	}

	public void setDemonym(String demonym) {
		this.demonym = demonym;
	}

	public Long getArea() {
		return area;
	}

	public void setArea(Long area) {
		this.area = area;
	}

	public Float getGini() {
		return gini;
	}

	public void setGini(Float gini) {
		this.gini = gini;
	}

	public List<String> getTimezones() {
		return timezones;
	}

	public void setTimezones(List<String> timezones) {
		this.timezones = timezones;
	}

	public List<String> getCallingCodes() {
		return callingCodes;
	}

	public void setCallingCodes(List<String> callingCodes) {
		this.callingCodes = callingCodes;
	}

	public List<String> getTopLevelDomain() {
		return topLevelDomain;
	}

	public void setTopLevelDomain(List<String> topLevelDomain) {
		this.topLevelDomain = topLevelDomain;
	}

	public List<String> getCurrencies() {
		return currencies;
	}

	public void setCurrencies(List<String> currencies) {
		this.currencies = currencies;
	}

	public List<String> getLanguages() {
		return languages;
	}

	public void setLanguages(List<String> languages) {
		this.languages = languages;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;
		CountryDto2 that = (CountryDto2) o;
		return Objects.equals(name, that.name) &&
				Objects.equals(capital, that.capital) &&
				Objects.equals(altSpellings, that.altSpellings) &&
				Objects.equals(relevance, that.relevance) &&
				Objects.equals(region, that.region) &&
				Objects.equals(subregion, that.subregion) &&
				Objects.equals(translations, that.translations) &&
				Objects.equals(population, that.population) &&
				Objects.equals(latlng, that.latlng) &&
				Objects.equals(demonym, that.demonym) &&
				Objects.equals(area, that.area) &&
				Objects.equals(gini, that.gini) &&
				Objects.equals(timezones, that.timezones) &&
				Objects.equals(callingCodes, that.callingCodes) &&
				Objects.equals(topLevelDomain, that.topLevelDomain) &&
				Objects.equals(currencies, that.currencies) &&
				Objects.equals(languages, that.languages);
	}

	@Override
	public int hashCode() {
		return Objects.hash(name, capital, altSpellings, relevance, region, subregion, translations, population, latlng, demonym, area, gini, timezones, callingCodes, topLevelDomain, currencies, languages);
	}
}
<file_sep>package countries.low_level;

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import io.restassured.specification.RequestSpecification;
import org.apache.http.HttpStatus;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.*;

public class GetCountriesByCodeTestWithParams {
	private final String CODES = "co;nor";
	private final String FIRST_COUNTY = "Colombia";
	private final String FIRST_COUNTY_ALT_NAME = "CO";
	private final String SECOND_COUNTY = "Norway";
	private final String INCORRECT_COUNTY = "Russia";

	private final String DOMAIN = "https://restcountries-v1.p.rapidapi.com/";
	private final String COUNTRY_BY_CODE_ENDPOINT = DOMAIN + "alpha/";

	private RequestSpecification REQUEST_SPECIFICATION;

	@BeforeMethod
	public void setup() {
		REQUEST_SPECIFICATION = new RequestSpecBuilder()
				.addHeader("X-RapidAPI-Host", "restcountries-v1.p.rapidapi.com")
				.addHeader("X-RapidAPI-Key", "<KEY>")
				.addFilter(new RequestLoggingFilter())
				.addFilter(new ResponseLoggingFilter()).build();
	}

	@AfterMethod
	public void teardown() {
	}

	@Test(description = "Get country by one code")
	void getCountryByOneCodeWitiConfigLogPretty() {

		given(REQUEST_SPECIFICATION)
				.param("codes", CODES)
				.get(COUNTRY_BY_CODE_ENDPOINT)
				.then()
				.statusCode(HttpStatus.SC_OK).and()
				.body("name[0]", is(FIRST_COUNTY))
				.body("name[1]", is(SECOND_COUNTY))
				.body("name", is(asList(FIRST_COUNTY, SECOND_COUNTY)))
				.body("altSpellings[0]", hasItem(FIRST_COUNTY_ALT_NAME))
				.body("name", not(INCORRECT_COUNTY))
				.header("Access-Control-Allow-Headers", "Accept, X-Requested-With");
	}
}

branch_name: refs/heads/master

languages: Java Gradle

repo_language: Java


text:
<file_sep># Graphs.js
A library for drawing interactive graph theory graphs on an html5 canvas
## https://paulfears.github.io/Graphs/ (live version)

## Quick Start

To get started link the Graphs.js into your page like this

```html
<script src="Graphs.js"></script>
```

Then in a seperate Javascript file do this

```javascript
let graph = new Graph("id of canvas element")
```
and just like that you have an interactable graph widget, where a user can draw connect and edit nodes

## Configuration and useage

### Creating nodes

```javascript
let graph = new Graph("canvasid");
// graph.node(xposition : Number, yposition: Number, radius: Number, "text")
let node1 = graph.node(100, 100, 20, "text")
```

### Creating connections
creating an unweighted biDirectional connection
```javascript
  let node1 = graph.node(100, 100, 25, "node1");
  let node2 = graph.node(200, 200, 25, "node2");
  node1.connect(node2);
```
creating a weighted biDirectional connection
```javascript
  let node1 = graph.node(100, 100, 25, "node1");
  let node2 = graph.node(200, 200, 25, "node2");
  node1.connect(node2, 25) //created a connection with a weight of 25
```
creating a directional connection
```javascript
  let node1 = graph.node(100, 100, 25, "node1");
  let node2 = graph.node(200, 200, 25, "node2");
  node1.directional(node2, 15) //created a directional connection with a weight of 15
```

repo_language: Markdown

repo_name: lodka/Graphs


text:
<repo_name>Selich/FYT<file_sep>/ytsearch.py
#!/usr/bin/python3
# coding: utf-8

import bs4
import requests as req
import sys
import shutil
import vlc

def enter_number_link():
    arg = input("Enter the number to view the video: ")
    if arg == '':
        enter_number_link()
    if arg == 'q':
        exit()

if __name__ == '__main__':

    vlcExe = shutil.which("vlc")

    searchTerm = '+'.join(sys.argv[1:])

    print(searchTerm)

    # vars
    url = 'https://www.youtube.com/results?search_query='
    txt = req.get(url+searchTerm).text
    soup = bs4.BeautifulSoup(txt, "lxml")
    # class where search result video link is
    div = [d for d in soup.find_all('div') if d.has_attr('class') and 'yt-lockup-dismissable' in d['class']]

    count = 0
    for d in div:
        img0 = d.find_all('img')[0]
        a0 = d.find_all('a')[0]
        imgL = img0['src'] if not img0.has_attr('data-thumb') else img0['data-thumb']
        a0 = [x for x in d.find_all('a') if x.has_attr('title')][0]
        playUrl = print('http://www.youtube.com/'+a0['href'])
        count += 1
        print((count, a0['title']))
        if count == 10:
            break
    enter_number_link()
    play = vlc.MediaPlayer('playUrl')

repo_language: Python

repo_name: Selich/FYT


text:
<file_sep>#include <iostream>
#include <cstdio>
using namespace std;

int climbStair(int n) {
	if (n == 1)
		return 1;
	int first = 1;
	int second = 2;
	for (int i = 3; i <= n; i++) {
		int third = first + second;
		first = second;
		second = third;
	}
	return second;
}

//int main() {
//	int n = 3;
//	int n1 = 4;
//	int n2 = 5;
//	cout << climbStair(n) << endl;
//	cout << climbStair(n1) << endl;
//	cout << climbStair(n2) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>

using namespace std;

//void sortColor(vector<int>& nums) {
//	vector<int> colors(3);
//	//数组colors三个下标0，1，2，分别存的是三种颜色的个数
//	for (int num : nums) {
//		++colors[num];
//	}
//	//存入个数
//	for (int i = 0, cur = 0; i < 3; ++i) {
//		for (int j = 0; j < colors[i]; ++j) {
//			nums[cur++] = i;
//			//cur是更新后指向的位置
//		}
//	}
//}

void sortColor(vector<int>& nums) {
	int red = 0, blue = (int)nums.size() - 1;
	for (int i = 0; i <= blue ; ++i) {
		if (nums[i] == 0) {
			swap(nums[i], nums[red++]);
		}
		else if (nums[i] == 2) {
			swap(nums[i--], nums[blue--]);
		}
	}
}

//int main() {
//	vector<int> nums = { 2,0,2,1,1,0 };
//	sortColor(nums);
//	for (int i = 0; i < nums.size(); i++) {
//		cout << nums[i] << " ";
//	}
//	cout << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<vector<int>> subsets(vector<int> &S) {
	vector<vector<int>> res(1);
	sort(S.begin(), S.end());
	for (int i = 0; i < S.size(); ++i) {
		int size = res.size();
		for (int j = 0; j < size; ++j) {
			res.push_back(res[j]);
			res.back().push_back(S[i]);
		}
	}
	return res;
}

//int main() {
//	vector<int> S = { 1,2,3 };
//	vector<vector<int>> ans = subsets(S);
//	for (int i = 0; i < ans.size(); ++i) {
//		for (int j = 0; j < ans[i].size(); ++j) {
//			cout << ans[i][j] << " ";
//		}
//		cout << endl;
//	}
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>

using namespace std;

int singleNumber(vector<int>& nums) {
	int res = 0;
	for (auto num : nums) {
		res ^= num;
	}
	return res;
}

//int main() {
//	vector<int> nums = { 4,1,2,1,2 };
//	cout << singleNumber(nums)<<endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>

using namespace std;

int max(int a, int b) {
	return a > b ? a : b;
}
int min(int a, int b) {
	return a < b ? a : b;
}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> merge(vector<vector<int>>& intervals) {
	if (intervals.empty()) {
		return {};
	}
	sort(intervals.begin(), intervals.end());
	vector<vector<int>> res{ intervals[0] };
	for (int i = 1; i < intervals.size(); ++i) {
		if (res.back()[1] < intervals[i][0]) {
			res.push_back(intervals[i]);
		}
		else {
			res.back()[1] = max(res.back()[1], intervals[i][1]);
		}
	}
	return res;
}

//int main() {
//	vector<vector<int>> intervals = { {1,3} ,{2,6},{8,10},{15,18} };
//	vector<vector<int>> res;
//	res = merge(intervals);
//	for (int i = 0; i < res.size(); i++) {
//		for (int j = 0; j < res[i].size(); j++) {
//			cout << res[i][j] << " ";
//		}
//		cout << endl;
//	}
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>

using namespace std;

int mysqrt(int x) {
	long res = x;
	while (res*res > x) {
		res = (res + x / res) / 2;
	}
	return res;
}

//int main() {
//	int x = 8;
//	cout << mysqrt(x) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

string minWindow(string s, string t) {
	string res = "";
	unordered_map<char, int> letterCnt;
	int left = 0, cnt = 0, minlen = INT_MAX;
	for (char c : t)
		++letterCnt[c];
	for (int i = 0; i < s.size(); ++i) {
		if (--letterCnt[s[i]] >= 0)
			++cnt;
		while (cnt == t.size()) {
			if (minlen > i - left + 1) {
				minlen = i - left + 1;
				res = s.substr(left, minlen);
			}
			if (++letterCnt[s[left]] > 0)
				--cnt;
			++left;
		}
	}
	return res;
}

//int main() {
//	string s = "ADOBECODEBANC";
//	string t = "ABC";
//	cout << minWindow(s, t) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>

using namespace std;

int uniquePath(int m, int n) {
	vector<int> dp(n, 1);
	for (int i = 1; i < m; ++i) {
		for (int j = 1; j < n; ++j) {
			dp[j] += dp[j - 1];
		}
	}
	return dp[n - 1];
}

//int main() {
//	int m = 3, n = 2;
//	cout << uniquePath(m, n) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>
#include <unordered_set>
#include "maxyw.h"

using namespace std;

int firstMissingPositive(vector<int>& nums) {
	int mx = 0;
	unordered_set<int> s;
	for (int num : nums) {
		if (num <= 0)
			continue;
		s.insert(num);
		mx = max(mx, num);
	}
	for (int i = 1; i <= mx; ++i) {
		if (!s.count(i))
			return i;
	}
	return mx + 1;
}

//int main() {
//	vector<int> nums = { 3,4,-1,1 };
//	cout << firstMissingPositive(nums) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>

using namespace std;

double mypow(double x, int n) {
	double res = 1.0;
	for (int i = n; i != 0; i /= 2) {
		if (i % 2 != 0)
			res *= x;
		x *= x;
	}
	return n < 0 ? 1 / res : res;
}

//int main() {
//	double x = 2.0;
//	int n = 10;
//	cout << mypow(x, n) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>
#include "maxyw.h"
#include <stack>

using namespace std;

//·½·¨Ò»£º£º
//int largeRectangleArea(vector<int>& height) {
//	int res = 0;
//	for (int i = 0; i < height.size(); ++i) {
//		if (i + 1 < height.size() && height[i] <= height[i + 1])
//			continue;
//		int minh = height[i];
//		for (int j = i; j >= 0; --j) {
//			minh = min(minh, height[j]);
//			res = max(res, minh*(i - j + 1));
//		}
//	}
//	return res;
//}

int largestRectangleArea(vector<int>& heights) {
	int res = 0;
	stack<int> s;
	heights.push_back(0);//dummy=0;
	for (int i = 0; i < heights.size(); ++i) {
		while (!s.empty() && heights[s.top()] >= heights[i]) {
			int cur = s.top();
			s.pop();
			res = max(res, heights[cur] * (s.empty() ? i : (i - s.top() - 1)));
		}
		s.push(i);
	}
	return res;
}
//
//int main() {
//	vector<int> height = { 2,1,5,6,2,3 };
//	cout << largestRectangleArea(height) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

int max1(int a, int b) {
	return a > b ? a: b;
}

bool canjump(vector<int>& nums) {
	int n = nums.size(), reach = 0;
	for (int i = 0; i < n; i++) {
		if (i > reach || reach >= n - 1)
			break;
		reach = max1(reach, i + nums[i]);
	}
	return reach >= n - 1;
}

//int main() {
//	vector<int> nums1 = { 2,3,1,1,4 };
//	bool ans1 = canjump(nums1);
//	vector<int> nums2 = { 3,2,1,0,4 };
//	bool ans2 = canjump(nums2);
//	cout << ans1 << endl << ans2 << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>
#include "maxyw.h"

using namespace std;

int maxSubArray(vector<int>& nums) {
	int res = INT_MIN, curSum = 0;
	for (int num : nums) {
		curSum = max(curSum + num, num);
		res = max(res, curSum);
	}
	return res;
}

//int main() {
//	vector<int> nums = { -2,1,-3,4,-1,2,1,-5,4 };
//	int ans = maxSubArray(nums);
//	cout << ans << endl;
//	system("pause");
//	return 0;
//}<file_sep>#pragma once
#include <cstdio>
#include <iostream>

using namespace std;

int max(int a, int b);
int min(int a, int b);<file_sep>#include <cstdio>
#include <iostream>

using namespace std;

int divide(int dividend, int divisor) {
	long long m = abs((long long)dividend), n = abs((long long)divisor), res = 0;
	if (m < n)
		return 0;
	while (m >= n) {
		long long t = n, p = 1;
		while (m > (t << 1)) {
			t <<= 1;
			p <<= 1;
		}
		res += p;
		m -= t;
	}
	if ((dividend < 0) ^ (divisor < 0))
		res = -res;
	return res > INT_MAX ? INT_MAX : res;
}

//int main() {
//	int dividend = 7, divisor = -3;
//	cout << divide(dividend, divisor) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

vector<vector<string>> groupAnagrams(vector<string>& strs) {
	vector<vector<string>> res;
	unordered_map<string, vector<string>> m;
	for (string str : strs) {
		string t = str;
		sort(t.begin(), t.end());
		m[t].push_back(str);
	}
	for (auto a : m) {
		res.push_back(a.second);
	}
	return res;
}

//int main() {
//	vector<string> strs = { "eat", "tea", "tan", "ate", "nat", "bat" };
//	vector<vector<string>> ans;
//	ans = groupAnagrams(strs);
//	for (int i = 0; i < ans.size(); i++) {
//		for (int j = 0; j < ans[i].size(); j++) {
//			printf("%s ", ans[i][j]);
//		}
//		cout << endl;
//	}
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>
#include <string>

using namespace std;

string longestCommonPrefix(vector<string>& strs) {
	if (strs.empty())
		return "";
	for (int j = 0; j < strs[0].size(); ++j) {
		for (int i = 0; i < strs.size(); ++i) {
			if (j >= strs[j].size() || strs[i][j] != strs[0][j]) {
				return strs[i].substr(0, j);
			}
		}
	}
	return strs[0];
}

//int main() {
//	vector<string> strs = { "flower","flow","flight" };
//	cout << longestCommonPrefix(strs) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <vector>

using namespace std;

int majorityElement(vector<int>& nums) {
	int res = 0, cnt = 0;
	for (int num : nums) {
		if (cnt == 0) {
			res = num;
			++cnt;
		}
		else
			(num == res) ? ++cnt : --cnt;
	}
	return res;
}

//int main() {
//	vector<int> nums = { 2,2,1,1,1,2,2 };
//	cout << majorityElement(nums) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <unordered_map>

using namespace std;

int romaToInt(string s) {
	int res = 0;
	unordered_map<char, int> m{ {'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000} };
	for (int i = 0; i < s.size(); ++i) {
		int val = m[s[i]];
		if (i == s.size() - 1 || m[s[i + 1]] <= m[s[i]])
			res += val;
		else
			res -= val;
	}
	return res;
}

//int main() {
//	string s= "MCMXCIV";
//	cout << romaToInt(s) << endl;
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>
#include <string>

using namespace std;

string countAndSay(int n) {
	if (n <= 0)
		return "";
	string res = "1";
	while (--n) {
		string cur = "";
		for (int i = 0; i < res.size(); ++i) {
			int cnt = 1;
			while (i + 1 < res.size() && res[i] == res[i + 1]) {
				cnt++;
				i++;
			}
			cur += to_string(cnt) + res[i];
		}
		res = cur;
	}
	return res;
}

//int main() {
//	for (int i = 1; i < 5; ++i) {
//		cout << countAndSay(i) << endl;
//	}
//	system("pause");
//	return 0;
//}<file_sep>#include <cstdio>
#include <iostream>

using namespace std;

bool isMatchwild(string s, string p) {
	int i = 0, j = 0, jstar = -1, istar = -1;
	while (i < s.size()) {
		if (s[i] == p[j] || p[j] == '?') {
			++i; ++j;
		}
		else if (p[j] == '*') {
			istar = i;
			jstar = j++;
		}
		else if (istar >= 0) {
			i = ++istar;
			j = jstar + 1;
		}
		else
			return false;
	}
	while (j < p.size() && p[j] == '*')
		++j;
	return j == p.size();
}

//int main() {
//	string s;
//	s= "abceb";
//	string p;
//	p= "*a*b";
//	cout << isMatchwild(s, p) << endl;
//	system("pause");
//	return 0;
//}


text:
<file_sep># Algorithms-in-C
This is my repository to store the implementations of basic Data Structures and Algorithms and also answers to some of the exercises in the book - "Algorithms in C" by <NAME>.
<file_sep>#include <stdio.h>
#include <stdlib.h>

int gcd(int u, int v)
{
    int t;
    if(u == 0 || v == 0)
        return 0;
    if(u < v)
    {
        t = u;
        u = v;
        v = t;
    }
    while(u % v != 0)
    {
        t = v;
        v = u % v;
        u = t;
    }
    return v;
}

int main()
{
    int r, c, i, j;
    printf("Enter the number of rows and columns : ");
    scanf("%d %d", &r, &c);
    int a[r][c];
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            if(gcd(i, j) == 1)
                a[i][j] = 1;
            else
                a[i][j] = 0;
        }
    }
    printf("The asked 2d array is :\n");
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
}
<file_sep>Here are my solutions to the problem sets on linked lists provided by Stanford University online. I have also included some other programs where I have implemented linked lists.
<file_sep>#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node * next;
};

void enqueue(struct Node ** head_ref)
{
    struct Node * new_node = (struct Node *) malloc(sizeof(struct Node));
    if(new_node == NULL)
    {
        printf("NO SPACE TO ADD ELEMENTS TO THE QUEUE!\n");
        return;
    }
    int num;
    printf("Enter the element to add to the queue : ");
    scanf("%d", &num);
    struct Node * node = *head_ref;
    if(node == NULL)
    {

        new_node -> data = num;
        new_node -> next = NULL;
        *head_ref = new_node;
        return;
    }
    while(node -> next != NULL)
    {
        node = node -> next;
    }
    new_node -> data = num;
    new_node -> next = NULL;
    node -> next = new_node;
}

void dequeue(struct Node ** head_ref)
{
    struct Node * node = *head_ref;
    if(node == NULL)
    {
        printf("NO ELEMENT TO REMOVE!\n");
        return;
    }
    *head_ref = node -> next;
    printf("The removed element is : %d\n", node -> data);
    free(node);
}

void display(struct Node * head)
{
    if(head == NULL)
    {
        printf("EMPTY QUEUE!\n");
        return;
    }
    while(head != NULL)
    {
        printf("%d ", head -> data);
        head = head -> next;
    }
    printf("\n");
}

int main()
{
    struct Node * head = NULL;
    int ch;
    do
    {
        printf("Press 1 to add an element to the queue\n");
        printf("Press 2 to remove an element from the queue\n");
        printf("Press 3 to display the elements of the queue\n");
        printf("Press 4 to exit the program\n");
        printf("Enter your choice : ");
        scanf("%d", &ch);
        switch(ch)
        {
            case 1 : enqueue(&head);
                     break;
            case 2 : dequeue(&head);
                     break;
            case 3 : display(head);
                     break;
            case 4 : printf("Thanks!");
                     break;
            default: printf("INVALID CHOICE\nPLEASE ENTER A VALID CHOICE (1 - 3)\n");
        }
    }while(ch != 4);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n,num,x,i,first,last,middle;
    printf("Enter the number of elements in the array\n");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("Enter number to be searched\n");
    scanf("%d",&num);
    first=0;
    last=n-1;
    middle=(first + last)/2;
    while(first<=last)
    {
        if(a[middle]<num)
        {
            first = middle + 1;
        }
        else if(a[middle] == num)
        {
            printf("%d is present at position %d\n",num,middle+1);
            break;
        }
        else
        {
            last = middle-1;
        }
        middle = (first + last)/2;
    }
    if(first>last)
    {
        printf("%d is not present in the list");
    }
    return 0;
}
<file_sep>I don't understand what this question means.
<file_sep>For Algorithm 1 :
u, v = gazillion values which would be a pain to write down here ;p

For Algorithm 2 :
u = 56789
v = 12345

u = 12345
v = 7409

u = 7409
v = 4963

u = 4963
v = 2473

u = 2473
v = 2463

u = 2463
v = 10

u = 10
v = 3
<file_sep>#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node * next;
};

void push(struct Node ** head_ref)
{
    struct Node * new_node = (struct Node *)malloc(sizeof(struct Node));
    if(new_node == NULL)
    {
        printf("STACK OVERFLOW!\n");
        return;
    }
    int num;
    printf("Enter the number to push into the list : ");
    scanf("%d", &num);
    new_node -> data = num;
    new_node -> next = *head_ref;
    *head_ref = new_node;
}

void pop(struct Node ** head_ref)
{
    struct Node * node = * head_ref;
    if(node == NULL)
    {
        printf("NO ELMENTS TO POP!\n");
        return;
    }
    *head_ref = node -> next;
    printf("Popped element is : %d\n", node -> data);
    free(node);
}

void display(struct Node * head_ref)
{
    struct Node * node = head_ref;
    if(node == NULL)
    {
        printf("EMPTY STACK!\n");
        return;
    }
    while(node != NULL)
    {
        printf("%d ", node -> data);
        node = node -> next;
    }
    printf("\n");
}

int main()
{
    struct Node * head = NULL;
    int ch;
    do
    {
        printf("Press 1 to push an element on top of the stack\n");
        printf("Press 2 to pop an element from the stack\n");
        printf("Press 3 to display the elements of the stack\n");
        printf("Press 4 to exit the program\n");
        printf("Enter your choice : ");
        scanf("%d", &ch);
        switch(ch)
        {
            case 1 : push(&head);
                     break;
            case 2 : pop(&head);
                     break;
            case 3 : display(head);
                     break;
            case 4 : printf("Thanks!");
                     break;
            default: printf("INVALID CHOICE\nPLEASE ENTER A VALID CHOICE (1 - 3)\n");
        }
    }while(ch != 4);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node * next;
};

void push(struct Node ** head_ref)
{
    struct Node * new_node = (struct Node *)malloc(sizeof(struct Node));
    if(new_node == NULL)
    {
        printf("NO MEMORY LEFT TO ALLOCATE TO A NEW NODE!\n");
        return;
    }
    int num;
    printf("Enter the number to insert in the list : ");
    scanf("%d", &num);
   /* if(*head_ref == NULL)
    {
        new_node->data = num;
        new_node->next = NULL;
        *head_ref = new_node;
        return;
    }*/
    new_node -> data = num;
    new_node -> next = * head_ref;
    * head_ref = new_node;
}

void InsertNth(struct Node ** head_ref)
{
    int new_data, index, i = 0;
    printf("Enter the the number to insert into the list and the index at which to insert it : ");
    scanf("%d %d", &new_data, &index);
    struct Node * node = *head_ref;
    struct Node * new_node = (struct Node *)malloc(sizeof(struct Node));
    if(index == 0)
    {
        new_node -> data = new_data;
        new_node -> next = *head_ref;
        *head_ref = new_node;
        return;
    }
    while((i != (index - 1)) && (node != NULL))
    {
        node = node -> next;
        i++;
    }
    if(node == NULL)
    {
        printf("INDEX OUT OF BOUND!\n");
        return;
    }
    new_node -> data = new_data;
    new_node -> next = node -> next;
    node -> next = new_node;
}

void display(struct Node *node)
{
    if(node == NULL)
    {
        printf("LIST IS EMPTY!\n");
        return;
    }
    while(node != NULL)
    {
        printf("%d ", node -> data);
        node = node -> next;
    }
    printf("\n");
}

int main()
{
    struct Node * head = NULL;
    int ch;
    do
    {
        printf("Press 1 to push an element on top of the list\n");
        printf("Press 2 to insert an element at any index in the list\n");
        printf("Press 3 to display the list\n");
        printf("Press 4 to exit the program\n");
        printf("Enter your choice : ");
        scanf("%d", &ch);
        switch(ch)
        {
            case 1 : push(&head);
                     break;
            case 2 : InsertNth(&head);
                     break;
            case 3 : display(head);
                     break;
            case 4 : printf("Thanks!");
                     break;
            default: printf("INVALID CHOICE!\nPLEASE ENTER A VALID CHOICE (1 - 3)\n");
        }
    }while(ch != 4);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>

void binary(int num)  // void because the function should print and not return according to the question
{
    int r, i = 0, j;
    int bi[10] = {};
    while(num != 0)
    {
        r = num % 2;
        bi[i] = r;
        num = num / 2;
        i++;
    }
    for(j=i-1;j>=0;j--)
    {
        printf("%d", bi[j]);
    }
}

int main()
{
    int n;
    printf("Enter the number : ");
    scanf("%d", &n);
    binary(n);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>

struct Fraction
{
    int numerator;
    int denominator;
};

int gcd(int u, int v)
{
    int t;
    if(u < v)
    {
        t = u;
        u = v;
        v = t;
    }
    while(u % v != 0)
    {
        printf("!");
        t = v;
        v = u % v;
        u = t;
    }
    return v;
}

int main()
{
    struct Fraction frac;
    char ch = 'y';
    int num, den, div,n;
    while(ch == 'y' || ch == 'Y')//ch != 'n' || ch != 'N' not working?!?!?!?!??!/
    {
        printf("Enter the numerator and denominator of a given fraction : ");
        scanf("%d", &frac.numerator);
        scanf("%d", &frac.denominator);
        num = frac.numerator;
        den = frac.denominator;
        div = gcd(num, den);
        printf("The fraction in lowest terms will be : %d/%d\n", num/div, den/div);
        printf("Would you like to continue?\nPress 'y'/'Y' to continue and 'n'/'N' to exit : ");
        scanf(" %c", &ch);
    }
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int gcd(int x, int y)
{
    int t;
    if(x < y)
    {
        t = x;
        x = y;
        y = t;
    }
    while(x % y != 0)
    {
        t = y;
        y = x % y;
        y = t;
    }
    return y;
}

int main()
{
    int a, b, c, gcd1, gcd_final;
    printf("Enter three numbers :  ");
    scanf("%d %d %d", &a, &b, &c);
    gcd1 = gcd(a, b);
    gcd_final = gcd(gcd1, c);
    printf("The gcd of given 3 numbers is : %d", gcd_final);
}

languages: Markdown C


text:
<file_sep>import random
import pytest

from order_book import OrderBook

@pytest.mark.parametrize('order_type', ['ask', 'bid'])
def test_place_first_order(order_type):
    """
    Place a first order into order book
    """
    ob = OrderBook()
    order = {
        'order_id': '1',
        'price': 10.5,
        'quantity': 2
    }
    ob.place_order(**order, order_type=order_type)
    if order_type == 'ask':
        assert ob.asks == [order]
        assert ob.bids == []
    else:
        assert ob.asks == []
        assert ob.bids == [order]

def test_place_order_in_the_middle():
    """
    Place an order in the middle of a full order book
    """
    ob = OrderBook()

    # firstly, place 5 asks and 5 bids with increasing prices
    expected_orders = {'ask': [], 'bid': []}
    for i in range(1, 6):
        for order_type in ('ask', 'bid'):
            order = {
                'order_id': f'{order_type} {i}',
                'price': i,
                'quantity': random.randint(1, 100)
            }
            ob.place_order(**order, order_type=order_type)
            expected_orders[order_type].append(order)

    # place 1 ask and 1 bid in the middle of orders list
    for order_type in ('ask', 'bid'):
        order = {
            'order_id': f'{order_type} 6',
            'price': 3.5,
            'quantity': random.randint(1, 100)
        }
        ob.place_order(**order, order_type=order_type)
        expected_orders[order_type].insert(3, order)
    assert ob.asks == expected_orders['ask']
    assert ob.bids == expected_orders['bid']

@pytest.mark.parametrize('order_type', ['ask', 'bid'])
def test_place_duplicate_order_id(order_type):
    """
    Place an order with an id that already exists in the order book
    """
    ob = OrderBook()
    ob.place_order('1', 10, 2, order_type)
    with pytest.raises(ValueError):
        ob.place_order('1', 11, 3, order_type)

def test_place_unknown_order_type():
    """
    Place an order with an unknown order type
    """
    ob = OrderBook()
    with pytest.raises(ValueError):
        ob.place_order('1', 1, 1, 'bed')

@pytest.mark.parametrize('order_type', ['ask', 'bid'])
def test_place_order_wrong_price_type(order_type):
    """
    Check that price could not be negative or zero
    """
    ob = OrderBook()
    with pytest.raises(ValueError):
        ob.place_order('1', -2, 2, order_type)
    with pytest.raises(ValueError):
        ob.place_order('1', 0, 2, order_type)

@pytest.mark.parametrize('order_type', ['ask', 'bid'])
def test_place_order_wrong_quantity_type(order_type):
    """
    Check that quantity could not be negative, zero or float
    """
    ob = OrderBook()
    with pytest.raises(ValueError):
        ob.place_order('1', 10.5, -4, order_type)
    with pytest.raises(ValueError):
        ob.place_order('1', 10.5, 0, order_type)
    with pytest.raises(ValueError):
        ob.place_order('1', 10.5, 4.4, order_type)

@pytest.mark.parametrize('order_type', ['ask', 'bid'])
def test_cancel_order(order_type):
    """
    Check that order cancels correctly
    """
    ob = OrderBook()

    # firstly, place 5 asks and 5 bids with increasing prices
    expected_orders = {'ask': [], 'bid': []}
    for i in range(1, 6):
        for ot in ('ask', 'bid'):
            order = {
                'order_id': f'{ot} {i}',
                'price': i,
                'quantity': random.randint(1, 100)
            }
            ob.place_order(**order, order_type=ot)
            expected_orders[ot].append(order)

    # cancel order
    ob.cancel_order(f'{order_type} 3')
    del expected_orders[order_type][2]
    assert ob.asks == expected_orders['ask']
    assert ob.bids == expected_orders['bid']

@pytest.mark.parametrize('order_type', ['ask', 'bid'])
def test_cancel_non_existing_order(order_type):
    """
    Check that method raises ValueError if order_id does not exist
    (when there are no other orders, and when there are other orders with
    different order_ids)
    """
    ob = OrderBook()
    with pytest.raises(ValueError):
        ob.cancel_order('1')
    ob.place_order('1', 10, 2, order_type)
    with pytest.raises(ValueError):
        ob.cancel_order('2')

@pytest.mark.parametrize('order_type', ['ask', 'bid'])
def test_get_order_info(order_type):
    """
    Check that method returns correct info about an order
    """
    ob = OrderBook()
    order = {
        'order_id': '10',
        'price': random.randint(1, 10),
        'quantity': random.randint(1, 100),
        'order_type': order_type
    }
    ob.place_order(**order)
    assert ob.get_order_info('10') == order

@pytest.mark.parametrize('order_type', ['ask', 'bid'])
def test_get_info_non_existing_order(order_type):
    """
    Check that method raises ValueError if order_id does not exist
    (when there are no other orders, and when there are other orders with
    different order_ids)
    """
    ob = OrderBook()
    with pytest.raises(ValueError):
        ob.get_order_info('1')
    ob.place_order('1', 10, 2, order_type)
    with pytest.raises(ValueError):
        ob.get_order_info('2')

def test_get_market_data_different_prices():
    """
    Check that method returns correct market data if all prices are different
    """
    ob = OrderBook()

    # firstly, place 5 asks and 5 bids with increasing different prices
    expected_market_data = {'asks': [], 'bids': []}
    for i in range(1, 6):
        for order_type in ('ask', 'bid'):
            order = {
                'price': i,
                'quantity': random.randint(1, 100)
            }
            ob.place_order(**order, order_type=order_type,
                           order_id=f'{order_type} {i}')
            expected_market_data[order_type + 's'].append(order)

    assert ob.get_market_data() == expected_market_data

def place_orders_same_price(ob, price, n_orders, order_type):
    """
    Helper function, place n_orders with given price
    into the order_book instance

    :param ob: order_book instance
    :param price: float
    :param n_orders: number of orders with the same price
    :param order_type: 'ask' or 'bid'
    :return: total quantity of the placed orders
    """
    quantity = 0
    for _ in range(n_orders):
        order = {
            'price': price,
            'quantity': random.randint(1, 100)
        }
        quantity += order['quantity']
        ob.place_order(**order, order_type=order_type,
                       order_id=str(random.random()))
    return quantity

@pytest.mark.parametrize('order_type', ['ask', 'bid'])
def test_get_market_data_same_prices(order_type):
    """
    Check that method returns correct market data if all prices are the same
    """
    ob = OrderBook()
    expected_market_data = {'asks': [], 'bids': []}

    # firstly, place 5 orders with the same price
    price = 10
    quantity = place_orders_same_price(ob, price, 5, order_type)
    expected_market_data[order_type + 's'].append({
        'price': price,
        'quantity': quantity
    })

    assert ob.get_market_data() == expected_market_data

def test_get_market_data():
    """
    Check that method returns correct market data (some prices are different,
    some the same; there are both asks and bids; highest price for bids is
    greater than lowest price for asks)
    """
    ob = OrderBook()
    expected_market_data = {'asks': [], 'bids': []}

    # firstly, place 3 asks with the same price
    price = 10
    quantity = place_orders_same_price(ob, price, 3, 'ask')
    expected_market_data['asks'].append({
        'price': price,
        'quantity': quantity
    })
    # then, place 3 bids with the same price
    price = 5
    quantity = place_orders_same_price(ob, price, 3, 'bid')
    expected_market_data['bids'].append({
        'price': price,
        'quantity': quantity
    })
    # then, place 3 asks with the same price (lower than before)
    price = 7
    quantity = place_orders_same_price(ob, price, 3, 'ask')
    expected_market_data['asks'].insert(0, {
        'price': price,
        'quantity': quantity
    })
    # then, place 3 bids with the same price (greater than before)
    price = 8
    quantity = place_orders_same_price(ob, price, 3, 'bid')
    expected_market_data['bids'].append({
        'price': price,
        'quantity': quantity
    })

    assert ob.get_market_data() == expected_market_data

def test_get_empty_market_data():
    """
    Check that method works correctly if there are no orders
    """
    ob = OrderBook()
    assert ob.get_market_data() == {'asks': [], 'bids': []}
<file_sep>import typing

class OrderBook:
    def __init__(self):
        self.asks: typing.List[typing.Dict] = [] # all asks (sorted by price)
        self.bids: typing.List[typing.Dict] = [] # all bids (sorted by price)

    def place_order(
            self,
            order_id: str,
            price: float,
            quantity: int,
            order_type: str
    ) -> typing.NoReturn:
        """
        Place an order into order book (self.asks or self.bids)

        :param order_id: unique id of an order
        :param price: order price (positive float)
        :param quantity: order quantity
        :param order_type: 'ask' or 'bid'
        :return: None
        """
        if self.order_id_exists(order_id):
            raise ValueError(f'Order_id \'{order_id}\' already exists, '
                             f'please give another one')
        if price <= 0:
            raise ValueError(f'Price should be a positive number, but '
                             f'\'{price}\' was given')
        if quantity <= 0 or not isinstance(quantity, int):
            raise ValueError(f'Quantity should be a positive integer, but '
                             f'\'{quantity}\' was given')

        order = {
            'order_id': order_id,
            'price': price,
            'quantity': quantity
        }
        if order_type == 'ask':
            self.insert_order(self.asks, order)
        elif order_type == 'bid':
            self.insert_order(self.bids, order)
        else:
            raise ValueError(f'Unknown order_type \'{order_type}\', only '
                             f'\'ask\' and \'bid\' are possible')

    def insert_order(self, orders: typing.List[typing.Dict],
                     new_order: typing.Dict) -> typing.NoReturn:
        """
        Insert new_order into the list of orders, so that prices remain sorted

        :param orders: self.asks or self.bids
        :param new_order: new order
        :return: None
        """
        for i, order in enumerate(orders):
            if order['price'] >= new_order['price']:
                orders.insert(i, new_order)
                return

        # if all the prices in the orders list are lower than new_order's price,
        # insert new_order in the end of the orders list
        orders.insert(len(orders), new_order)

    def order_id_exists(self, order_id: str) -> bool:
        """
        Tells if order_id already exists in order_book (self.asks or self.bids)

        :param order_id: new order id
        :return: True if new order_if already exists else False
        """
        for order in self.asks + self.bids:
            if order['order_id'] == order_id:
                return True
        return False

    def cancel_order(self, order_id: str) -> typing.NoReturn:
        """
        Cancels an existing order

        :param order_id: existing order id
        :return: None
        """
        for i, order in enumerate(self.asks):
            if order['order_id'] == order_id:
                del self.asks[i]
                return
        for i, order in enumerate(self.bids):
            if order['order_id'] == order_id:
                del self.bids[i]
                return
        raise ValueError(f'Order_id \'{order_id}\' not found')

    def get_order_info(self, order_id: str) -> typing.Dict:
        """
        Returns info about an order with given order_id

        :param order_id: existing order id
        :return: dict with info about the order
        """
        for order in self.asks:
            if order['order_id'] == order_id:
                return dict({'order_type': 'ask'}, **order)
        for order in self.bids:
            if order['order_id'] == order_id:
                return dict({'order_type': 'bid'}, **order)
        raise ValueError(f'Order_id \'{order_id}\' not found')

    def get_market_data(self) -> typing.Dict:
        """
        Returns aggregated and sorted market data (iterates through self.asks
        and self.bids in increasing order because they are already
        sorted by price)

        :return: market_data, e.g. {
            'asks': [
                {
                    'price': <value>,
                    'quantity': <value>
                },
                ...
            ],
            'bids': [...]
        }
        """
        market_data = {
            'asks': [],
            'bids': []
        }
        for orders_list, order_type in \
                zip((self.asks, self.bids), ('asks', 'bids')):
            i = 0
            while i < len(orders_list):
                price = orders_list[i]['price']
                quantity = orders_list[i]['quantity']
                i += 1
                while i < len(orders_list) and orders_list[i]['price'] == price:
                    quantity += orders_list[i]['quantity']
                    i += 1
                market_data[order_type].append({
                    'price': price,
                    'quantity': quantity
                })
        return market_data
<file_sep># Order book

There's an OrderBook class which implements a simplified [order book](https://en.wikipedia.org/wiki/Order_book) (an electronic list of buy and sell orders for a security or other instrument organized by price level).

It has the following functionality (and tests to all of them):
- placing new orders
- cancelling orders by id
- getting order info by id
- getting aggregated and sorted market data

branch_name: refs/heads/main

languages: Markdown Python


text:
<file_sep>using BlazorAuthIssueRepro.Server.Models;
using IdentityServer4.EntityFramework.Options;
using Microsoft.AspNetCore.ApiAuthorization.IdentityServer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorAuthIssueRepro.Server.Data
{
    public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
    {
        public ApplicationDbContext(
            DbContextOptions options,
            IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ApplyConfiguration(new RoleConfiguration());
        }
    }

    #region Configurations

    public class RoleConfiguration : IEntityTypeConfiguration<IdentityRole>
    {
        public void Configure(EntityTypeBuilder<IdentityRole> modelBuilder)
        {
            var rolesToSeed = new List<IdentityRole>();
            foreach (var roleName in Shared.UserRoles.GetUserRoles())
            {
                var roleID = Shared.UserRoles.GetRoleID(roleName);
                if (Guid.TryParse(roleID, out _))
                    rolesToSeed.Add(new IdentityRole() { Id = roleID, Name = roleName, NormalizedName = roleName.ToUpper() });
            }

            modelBuilder.HasData(rolesToSeed);
        }
    }

    #endregion
}
<file_sep># BlazorAuthIssueRepro
 Barebones Blazor Webasembly solution meant to reproduce web API authorization issues.

 Related to issue: https://github.com/dotnet/aspnetcore/issues/25313

This project uses IdentityServer4 role based authentication.

To use:
1. Register and confirm a new user.
2. Navigate to the "Counter" page and click the "Add to Role2" button.
3. Reload the page to refresh the client.
4. Navigate to the "Fetch Data" page. You should see the default weather forecast data included in the Blazor Webassembly project template. The difference here is that the API call to get the forecast data now verifies the user is in Role2 (see step 2) and it attempts to fetch user data using the ControllerBase.User property.

I left this project deployed to IIS for a few days until eventually when I logged in and navigated to the "Fetch Data" tab it no longer worked. Project logs to C:\ by default in a log file called "BlazorAuthIssueRepro_All.log".
<file_sep>@page "/counter"
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using BlazorAuthIssueRepro.Shared
@inject HttpClient Http

Counter

Current count: @currentCount

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<button class="btn btn-primary" @onclick="AddUserToRole2">Add to Role2</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }

    private async Task AddUserToRole2()
    {
        try
        {
            await Http.PostAsync($"Roles/AddUserToRole?role={UserRoles.Role2}", new StringContent(string.Empty));
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
    }
}
<file_sep>using Microsoft.EntityFrameworkCore.Migrations;

namespace BlazorAuthIssueRepro.Server.Data.Migrations
{
    public partial class RoleSeed : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.InsertData(
                table: "AspNetRoles",
                columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
                values: new object[] { "B6E32223-FA3A-4D0D-8E48-622601BBD044", "b4706ff3-2751-4d4d-b946-b4072faec594", "Administrator", "ADMINISTRATOR" });

            migrationBuilder.InsertData(
                table: "AspNetRoles",
                columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
                values: new object[] { "9340A34A-70ED-4DC0-8EE6-580B2198C088", "be597d6d-b550-49ad-aab5-322685750acf", "Standard", "STANDARD" });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DeleteData(
                table: "AspNetRoles",
                keyColumn: "Id",
                keyValue: "<KEY>");

            migrationBuilder.DeleteData(
                table: "AspNetRoles",
                keyColumn: "Id",
                keyValue: "B6E32223-FA3A-4D0D-8E48-622601BBD044");
        }
    }
}
<file_sep>using BlazorAuthIssueRepro.Server.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorAuthIssueRepro.Server.Controllers
{
    [ApiController]
    public class RoleController : ControllerBase
    {
        private UserManager<ApplicationUser> _userManager;

        public RoleController(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }

        [HttpPost]
        [Route("Roles/AddUserToRole")]
        public async Task<IActionResult> AddUserToRole(string role)
        {
            var currentUser = await _userManager.GetUserAsync(User);

            if (currentUser != null)
            {
                await _userManager.AddToRoleAsync(currentUser, role);
                return Ok();
            }
            else
            {
                return NotFound();
            }
        }
    }
}
<file_sep>using BlazorAuthIssueRepro.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Identity;
using BlazorAuthIssueRepro.Server.Models;

namespace BlazorAuthIssueRepro.Server.Controllers
{
    [Authorize(Roles = UserRoles.Role2)]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly UserManager<ApplicationUser> _userManager;

        public WeatherForecastController(ILogger<WeatherForecastController> logger,
            UserManager<ApplicationUser> userManager)
        {
            _logger = logger;
            _userManager = userManager;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<WeatherForecast>>> Get()
        {
            if (User == null)
            {
                _logger.LogInformation($"User is null");
            }
            else
            {
                string logMsg = $"User Data: Primary Identity: {User.Identity?.Name}; Claims:";
                foreach (var claim in User.Claims)
                {
                    if (claim != null)
                        logMsg += $"\n\tType: {claim.Type}; Value: {claim.Value}";
                }

                logMsg += "\tIdentities:";
                foreach (var identity in User.Identities)
                {
                    if (identity != null)
                        logMsg += $"\n\tName: {identity.Name}; IsAuthenticated: {identity.IsAuthenticated}; RoleClaimType: {identity.RoleClaimType}; NameClaimType: {identity.NameClaimType}; Label: {identity.Label}; AuthenticationType: {identity.AuthenticationType}";
                }

                _logger.LogInformation(logMsg);
            }

            var currentUser = await _userManager.GetUserAsync(User);
            if (currentUser != null)
            {
                var rng = new Random();
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                .ToArray();
            }
            else
            {
                _logger.LogInformation($"User not found.");
                return NotFound();
            }
        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;

namespace BlazorAuthIssueRepro.Shared
{
    public class UserRoles
    {
        public const string Role1 = "Administrator";
        public const string Role1ID = "B6E32223-FA3A-4D0D-8E48-622601BBD044";

        public const string Role2 = "Standard";
        public const string Role2ID = "9340A34A-70ED-4DC0-8EE6-580B2198C088";

        public static List<string> GetUserRoles()
        {
            return new List<string>() { Role1, Role2 };
        }

        public static string GetRoleID(string role)
        {
            switch (role)
            {
                case Role1:
                    return Role1ID;
                case Role2:
                    return Role2ID;
            }

            return null;
        }
    }
}

languages: HTML+Razor C# Markdown

repo_language: HTML+Razor

repo_name: pantoast/BlazorAuthIssueRepro


text:
<file_sep>class User < ApplicationRecord
  has_many :groups, through: :group_users
  has_many :group_users
  has_many :schedules

end
<file_sep>class AddDetailsToSchedule < ActiveRecord::Migration[5.1]
  def change
    add_column :schedules, :date, :integer
    add_column :schedules, :time, :integer
    add_column :schedules, :place, :string
    add_column :schedules, :importance, :integer

  end
end
<file_sep>class Group < ApplicationRecord
  has_many :users, through: :group_users
  has_many :group_users
  accepts_nested_attributes_for :group_users
  #has_many :schedules, through: :user
end
<file_sep>class ScheduleController < ApplicationController

skip_before_action :verify_authenticity_token

def index
  @schedule = Schedule.all
  render json: @schedule
end

def save
  @schedule = Schedule.create(schedule_params)
  render json: @schedule
end

def schedule_params
   # whitelist params
   params.permit(:title, :date, :time, :place, :importance)
end

def delete
  if @schedule = Schedule.find(params[:id])
   @schedule.delete
   render json: @schedule
  else
   render json: "data not found"
  end
end

def update
  if  @schedule = Schedule.find(params[:id])
   @schedule.update(schedule_params)
   render json: @schedule
  else
    render json: "data not found"
  end
end

end
<file_sep>Rails.application.routes.draw do

post "/schedule" => "schedule#save"
get "/schedule" => "schedule#index"
delete "/schedule" => "schedule#delete"
put "/schedule" => "schedule#update"

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

repo_language: Ruby


text:
<repo_name>pereau/ipi-java-220-ex<file_sep>/src/main/java/com/ipiecoles/java/java220/Entreprise.java
package com.ipiecoles.java.java220;

import java.time.LocalDate;

public class Entreprise {
    public static final Double SALAIRE_BASE=1480.27;
    public static final Integer NB_CONGES_BASE=25;
    public static final Double INDICE_MANAGER=1.3;
    public static final Double PRIME_MANAGER_PAR_TECHNICIEN=250d;
    public static final Double PRIME_ANCIENNETE=100d;

    public static Double primeAnnuelleBase(){
        int annee=LocalDate.now().getYear();
        return annee*0.5;
    }
}