text stringlengths 4.4k 422k | metadata stringlengths 39 6.04k |
|---|---|
Coding using arrays and multiple methods giving me errors and cannot figure out why
Question: This is my code and i had thought i had everything typed out correct:
<code>import java.util.*;
import java.io.*;
public class Proj5 {
public static void main(String[] args)throws IOException{
Scanner s = new Scanner(System.in);
int [] quizKey = {1,1,2,2,1,1,3,2,4,1,3,5,4,1,2};
String [] userAnswers = new String[100];
String [] wid = new String[100];
int [][] userIndividualAnswers = new int[quizKey.length][userAnswers.length];
int [] numCorrect = new int[quizKey.length];
int max;
int min;
int lines=0;
readInText();
s = readInText();
while(s.hasNext()){
String line = s.nextLine();
String[] tokens = line.split(",");
wid[lines] = tokens[0];
userAnswers[lines] = tokens[1];
lines ++;
}// end while loop
int[][] userAnswersInt = new int[quizKey.length][lines];
numCorrect = gradeSingleQuiz(lines, quizKey, userAnswers, numCorrect, userAnswersInt);
double[] percentCorrect = new double[lines];
percentCorrect = percentCorrect(lines, numCorrect, quizKey);
char[] grades = new char[lines];
grades = grade(numCorrect, lines);
displayOutput(wid, lines, numCorrect, grades, percentCorrect);
}//end main
public static Scanner readInText()throws IOException{
Scanner inFile = new Scanner(new File("QuizScores.txt"));
return inFile;
}// end readInText
public static String[] userAnswers(String userAnswers[]){
return userAnswers;
}
public static int[] gradeSingleQuiz(int lines, int quizKey[], String userAnswers[], int numCorrect[], int userAnswersInt[][]){
for (int j=0; j<=lines; j++){
numCorrect[j]=0;
long[] ara = new long[lines];
long[] abc = new long[lines];
ara [j] = Long.parseLong(userAnswers[j]);
for(int p=0; p<userAnswersInt.length; p++){
abc [p] = ara[j]%10;
ara[j] = userAnswersInt[j][p];
}
for(int n=0; n<=quizKey.length; n++){
if(userAnswersInt[j][n]==(quizKey[n])){
numCorrect[j]++;
}
}
}//end for loop
return numCorrect;
}// end gradeSingleQuiz
public static int max(int max, int numCorrect[]){
max = numCorrect[0];
for(int r=1; r<numCorrect.length; r++){
if(numCorrect[r]>max){
max=numCorrect[r];
}
}
return max;
}
public static int min(int min, int numCorrect[]){
min = numCorrect[0];
for(int r=1; r<numCorrect.length; r++){
if(numCorrect[r]<min){
min=numCorrect[r];
}
}
return min;
}
public static char[] grade(int numCorrect[], int lines){
char[] grade = new char[lines];
for (int j=0; j<=lines; j++){
if(numCorrect[j]>=14)
grade[j]='A';
else if((numCorrect[j]>=12)&&(numCorrect[j]<14))
grade[j]='B';
else if((numCorrect[j]>=11)&&(numCorrect[j]<12))
grade[j]='C';
else if ((numCorrect[j]>=9)&&(numCorrect[j]<11))
grade[j]='D';
else
grade[j]='F';
}
return grade;
}//end grade
public static double[] percentCorrect(int lines, int numCorrect[], int quizKey[]){
double[] centCorrect = new double[100];
for (int j=0; j<=lines; j++){
centCorrect[j] = numCorrect[j]/quizKey.length;
}
return centCorrect;
}
public static void averageScore(int lines, double percentCorrect[]){
double add=0;
for(int d=0; d<=lines; d++){
add = percentCorrect[d] + add;
}//end for loop
System.out.println("Average: " + add + "%");
}// end averageScore
public static void displayOutput(String wid[], int lines, int numCorrect[], char grades[], double percentCorrect[]){
System.out.println("Student ID # Correct %Correct Grade");
for(int i=0; i<lines; i++){
System.out.println(wid[0] + " " + numCorrect[i] + " " +
(percentCorrect[i]) + " " + grades[i]);
}
}// end display output
}//end class
</code>
but when i try and compile and run it it gives me these errors:
<code>Exception in thread "main" java.lang.NumberFormatException: For input string: "112211324135412"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
at java.lang.Integer.parseInt(Integer.java:527)
at Proj5.gradeSingleQuiz(Proj5.java:52)
at Proj5.main(Proj5.java:27)
</code>
I was thinking maybe i didn't convert the string of that number to an int correct but looking back at it i think i did, i really just don't know what these errors are. according to eclipse there is nothing wrong with the code until it compiles.
The text i am pulling from is this.
<code>4563123,112211324135412
2312311,222121324135211
2312345,112211324135421
5527687,212111313124412
7867567,111111111111111
</code>
the first number is the student id the second number is the answers based on numbers; T=1 F=2 A=1 B=2 etc.
Thanks in advance.
EDIT:
Changed my code above to Long and it fixed those errors but it is now giving me an out of bounds exception of 5 at the line <code>abc [p] = ara[j]%10;</code> i know this isnt my orriginal question but if anyone could tell me why this is i would be very appreciative, i was under the impression that 5 was not out of bounds?
Thanks again
Comment: Your number is to big to be parsed use BigInteger instead.
Answer: <code>112211324135412</code> is not an int number, its clearly outta <code>int range(-2,147,483,648 and a maximum value of 2,147,483,647 (inclusive))</code>, try to use <code>Long.parseLong(str)</code> instead.
<code> long[] ara = new long[lines];
ara [j] = Long.parseLong(userAnswers[j]);
</code>
Comment: @JosephMindrup, array index starts with `0` and I believe your `lines` is the total length of the array, so your for loop should continue till `j < lines`, not `j <= lines`
Comment: Okay thank you very much this did indeed fix it but it is now giving me an out of bound exception of 5 for the line `abc [p] = ara[j]%10` ? I'm not entirely sure how to fix that because 5 shouldn't be out of bounds?
Comment: @PermGenError I do think you are right, and i changed it but unfortunately this didn't have any change. still giving me an out of bounds 5, i know i have five lines so with the change not letting it go to 5 i would think would fix it but i didnt
Answer: "112211324135412" => u can parseInt this string, overflow in int.<|endoftext|>if statement in for loop prints multiple times
Question: I am searching the 2d array for 3 numbers and the third number is not in the array and when it outputs to the user that the number is not in the array it prints it 10 times and im guessing because the for loop goes up to 10. How can I get the statement "8675 is not in the array" to only print out 1 time.
<code>public class MultiDimensionalArray {
public static void main(String[] args) {
int[][] oned = {
{ 1115, 7307, 1004, 8820, 4322, 2286, 6183, 8455, 5569, 9930 },
{ 1155, 7749, 8582, 1180, 4463, 3107, 8838, 9842, 2308, 3453 },
{ 6229, 5449, 1967, 2501, 9610, 5600, 6996, 7375, 5629, 35 },
{ 6677, 2464, 5017, 5881, 639, 2772, 3465, 8718, 7747, 5621 },
{ 1646, 8533, 4250, 8119, 8163, 1236, 4433, 4093, 7834, 3037 },
{ 7069, 6522, 9604, 1609, 5725, 6255, 438, 274, 7978, 3358 },
{ 6631, 3401, 5975, 108, 3696, 2773, 1697, 9803, 7056, 4996 },
{ 7109, 4895, 5930, 7634, 7070, 5265, 7456, 5223, 9725, 368 },
{ 1201, 7776, 9000, 8654, 9635, 922, 2932, 4814, 1624, 1062 },
{ 7561, 6587, 7398, 4254, 5797, 7325, 4368, 5830, 8937, 5726 },
{ 7740, 8238, 7761, 6142, 4643, 7416, 2062, 5563, 1298, 7899 },
{ 1868, 6088, 3071, 7563, 7780, 2714, 7081, 2565, 3086, 766 },
{ 2284, 9931, 8664, 7248, 6768, 5657, 8404, 807, 7357, 2204 },
{ 9911, 6832, 8167, 546, 2709, 2046, 8465, 4171, 1841, 6106 },
{ 2123, 9005, 406, 6873, 3848, 4760, 2912, 1504, 9052, 270 },
{ 8700, 8182, 1153, 1154, 9288, 8227, 6165, 7257, 7908, 1769 },
{ 7355, 3880, 390, 1496, 6984, 7553, 981, 8049, 6948, 7312 },
{ 830, 4777, 5100, 897, 9941, 8513, 9318, 3146, 5298, 8452 },
{ 6678, 6535, 1471, 5225, 5513, 1912, 624, 8802, 5331, 4675 },
{ 4916, 2517, 4604, 4947, 9973, 9347, 9390, 8633, 60, 8983 },
{ 9977, 2505, 8436, 1285, 472, 568, 8696, 5198, 5630, 5087 },
{ 6287, 4834, 6184, 3761, 7922, 3163, 6836, 6621, 3338, 6575 },
{ 7105, 5863, 5113, 1346, 1223, 7733, 1323, 2301, 3021, 8612 },
{ 2976, 282, 271, 8111, 1320, 3441, 7129, 513, 4564, 7278 },
{ 3916, 7150, 9606, 8058, 7533, 8106, 539, 977, 32, 1074 },
{ 5859, 6361, 7489, 8347, 9441, 8281, 7728, 7944, 5272, 1598 },
{ 6078, 4624, 634, 9183, 7772, 6187, 3565, 4912, 2875, 8405 },
{ 1031, 1679, 8287, 689, 4855, 6386, 8616, 8608, 2842, 4986 },
{ 3321, 5150, 1410, 3159, 1328, 30, 191, 7133, 2797, 5334 },
{ 8610, 5512, 8141, 1398, 5918, 2641, 9014, 4475, 4590, 8672 } };
// Is 8227 in the array?
int number = 8227;
for (int row = 0; row < 10; row++) {
for (int column = 0; column < 30; column++) {
if (oned[column][row] == number)
{
System.out.println("8227 is in the array");
}
}
}
// Is 9911 in the array?
int check = 9911;
for (int row = 0; row < 10; row++) {
for (int column = 0; column < 30; column++) {
if (oned[column][row] == check)
{
System.out.println("9911 is in the array");
}
}
}
// Is 8675 in the array?
int look = 8675;
for (int row = 0; row < 10; row++) {
for (int column = 0; column < 30; column++) {
if (oned[column][row] == look)
{
System.out.println("8675 is in the array");
}
else if (oned[column][row] != look)
{
System.out.println("8675 is not in the array");
}
}
}
}
}
</code>
The output that i get is
<code>8227 is in the array
9911 is in the array
8675 is not in the array
8675 is not in the array
8675 is not in the array
8675 is not in the array
8675 is not in the array
8675 is not in the array
8675 is not in the array
8675 is not in the array
8675 is not in the array
8675 is not in the array
</code>
Comment: You only need one loop block to check all the numbers
Answer: Your way:
<code>int look = 8675;
boolean found = false;
outer:
for (int row = 0; row < 10; row++) {
for (int column = 0; column < 30; column++) {
found =(oned[column][row] == look);
if(found){
break outer;
}
}
}
if(found){
System.out.println("8675 is in the array");
}else{
System.out.println("8675 is not in the array");
}
</code>
"found" will only be true, if you found the value. If you found the value you can "leave" your loops using the break command. It quiets the outer for looop using the lable "outer". You can change the lable however you want.
After that, you can just check the boolean, if you found something and print the Text you want.
Better way:
A better way to to it would be to write a function:
<code>public boolean searchInArray(int[][] src, int find){
for(int[] row : src){
for(int num : src){
if(num == find){
return true;
}
}
}
return false;
}
</code>
You can now call that function like this:
<code>boolean hasValue = searchInArray(oned, 8227);
</code>
The function is iterating over every int array in your 2d array using a for loop. Inside the for loop it is iterating over each element of the 1d int array. If the element is equevalent to the one you search it will return true. Otherwise it will return false after it searched the whole 2d array.
You can now use the variable hasValue to print your text:
<code>boolean hasValue = searchInArray(oned, 8227);
if(hasValue ){
System.out.println("8227 is in the array");
}else{
System.out.println("8227 is not in the array");
}
</code>
Comment: A bit of explanation would make this answer even better.
Comment: @tobias_k of course ;) I just pressed enter to early :D
Comment: @Conner no problem.
Answer: Somthing like this :
<code> public void searchInt(int number){
int[][] array= {
{1115, 7307, 1004, 8820, 4322, 2286, 6183, 8455, 5569, 9930},....};
for (int[] nmbres: array) {
for (int num : nmbres) {
if (number== num) {
System.out.println(number +"is in the array");
}
}
}
}
</code>
Answer: You need to add two breaks to the code to break the for loops | [{"idx": "Coding_using_arrays_and_multiple_methods_giving_me_errors_and_cannot_figure_out_why", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-13191.jsonl"}, {"idx": "if_statement_in_for_loop_prints_multiple_times", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-13191.jsonl"}] |
Webscraper in Node.js returns empty array with async and promise
Question: I have problems in getting nodejs async and promise to work with a webscraper using a forloop to visits websites. After looking at several posts and testing different solutions on stackoverflow I can't get my async function to work properly. Thanks!
Code:
<code>var data = {};
async function run() {
console.log("Setup links..");
var links = [' [IDX] ' [IDX] await Promise.all(links.map(async (element) => {
const contents = await scrape(element);
console.log("After call in Promise: " + JSON.stringify(data));
}));
console.log("------------");
console.log(JSON.stringify(data));
return JSON.stringify(data);
}
async function scrape(element) {
request(element, function (error, response, html) {
console.log("Scrape website...");
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
var rowCounter = 0;
var columnCounter = 0;
var dates = [];
var item = [];
var mainTitle = false;
var title;
$('tr td').each(function(i, elem) {
var txt = $(elem).text().trim();
if (rowCounter == 0) {
if (columnCounter != 0) {
dates.push(txt.substring(txt.length - 4, txt.length));
}
} else {
if (txt == "Current Assets" || txt == "Current Liabilities" || txt == "Stockholders' Equity" || txt == "Revenue" || txt == "Operating Expenses" || txt == "Income from Continuing Operations" || txt == "Non-recurring Events" || txt == "Net Income") {
mainTitle = true;
} else {
if (columnCounter == 0) {
title = txt.split(' ').join('');
data[title] = {};
} else {
item.push(txt);
}
}
}
columnCounter++;
if (mainTitle) {
columnCounter = 0;
mainTitle = false;
}
if (columnCounter == 5) {
columnCounter = 0;
if (rowCounter != 0) {
data[title][0] = item[0];
data[title][1] = item[1];
data[title][2] = item[2];
data[title][3] = item[3];
item = [];
}
rowCounter++;
}
});
}
});
}
module.exports.run = run;
</code>
The code above in console:
<code>Server started!
Route called
Setup links..
After call in Promise: {}
After call in Promise: {}
------------
{}
Scrape website...
Scrape website...
</code>
So it's a problem with the promise when using a loop.
Comment: `request` doens't return a promise, does it? You will need to promisify it, so that you can await it in `scrape`.
Answer: I believe this is what you want (not tested, just hacked):
<code>async function scrape(element) {
return new Promise( (resolve, reject ) => {
request(element, function (error, response, html) {
if( error ) return reject( error );
if (response.statusCode != 200) return reject( "Got HTTP code: " + response.statusCode);
console.log("Scrape website...");
var $ = cheerio.load(html);
var rowCounter = 0;
var columnCounter = 0;
var dates = [];
var item = [];
var mainTitle = false;
var title;
$('tr td').each(function(i, elem) {
var txt = $(elem).text().trim();
if (rowCounter == 0) {
if (columnCounter != 0) {
dates.push(txt.substring(txt.length - 4, txt.length));
}
} else {
if (txt == "Current Assets" || txt == "Current Liabilities" || txt == "Stockholders' Equity" || txt == "Revenue" || txt == "Operating Expenses" || txt == "Income from Continuing Operations" || txt == "Non-recurring Events" || txt == "Net Income") {
mainTitle = true;
} else {
if (columnCounter == 0) {
title = txt.split(' ').join('');
data[title] = {};
} else {
item.push(txt);
}
}
}
columnCounter++;
if (mainTitle) {
columnCounter = 0;
mainTitle = false;
}
if (columnCounter == 5) {
columnCounter = 0;
if (rowCounter != 0) {
data[title][0] = item[0];
data[title][1] = item[1];
data[title][2] = item[2];
data[title][3] = item[3];
item = [];
}
rowCounter++;
}
});
resolve();
});
} );
</code>
}
Wrapped the code in a <code>Promise</code>, called <code>resolve</code> and handled errors with <code>reject</code> - but you know best about how to handle the errors.
Comment: Or simply use [async-request]( [IDX]<|endoftext|>How to make element's width decrease inside container
Question: I'm trying to make the summary element inside <code>.container</code> to decrease in size when the page is shrunk.
As seen in the demo below, when the screen size is reduced, the summary/details that is not in <code><div class="container"></code> its width shrinks as the window gets smaller. I am trying to replicate that behavior for the content inside <code><div class="lists"></code>
Can anyone provide some input?
<code>:root {
color: #FFFFFF;
background-color: #0b0b0b;
overflow-y: scroll;
overflow-x: hidden;
}
body,
:root {
margin: 0;
}
*,
::before,
::after {
box-sizing: border-box;
}
.container {
display: flex;
min-height: 100vh;
flex-direction: column;
text-align: center;
}
main {
flex-grow: 1;
max-width: 1050px;
margin-right: auto;
margin-left: auto;
}
a {
text-decoration: none;
color: #2ACA7A;
}
a:hover {
color: #ff0000;
}
/*lists*/
.lists {
width: 100vh;
}
details {
border: 1px solid #aaa;
border-radius: 4px;
padding: .5em .5em 0;
background-color: #222222;
margin: 15px;
}
summary {
font-weight: bold;
margin: -.5em -.5em 0;
padding: .5em;
}
summary:hover {
color: #ff0000;
font-size: 16.2px;
}
details[open] {
padding: .5em;
}
details[open] summary {
border-bottom: 1px solid #aaa;
margin-bottom: .5em;
}
th {
color: #2ACA7A;
}
table {
width: 86%;
}
/*head*/
header {
text-align: center;
max-width: 245px;
margin-left: auto;
margin-right: auto;
font-size: 23px;
}
header>h1 a {
color: #ff0000;
font-weight: normal;
}
header>h1 a:hover {
text-decoration: underline;
}
h2 {
color: #2ACA7A;
font-size: 28px;
font-weight: normal;
}
/*nav*/
nav {
text-align: center;
margin-bottom: 50px;
}
nav>ul li {
display: inline-block;
border-radius: 9px;
padding: 7px 21px;
background-color: #222222;
max-width: 8em;
}
nav li a:hover {
color: red;
border-radius: 10px;
transition: 0.2s;
}
/* larger screens */
@media (min-width: 1200px) {
nav {
top: 200px;
width: 175px;
font-size: 19px;
position: sticky;
margin-top: 100px;
}
nav>ul li {
display: block;
text-align: center;
margin: 18px;
}
nav>ul li {
min-width: 140px;
}
main {
margin-top: -290px;
}
}
/*footer*/
footer {
margin-bottom: 20px;
font-family: arial;
font-size: 15px;
}
footer>p:nth-of-type(1) {
font-size: 18px;
font-weight: 700;
text-decoration: underline;
}
footer>hr {
max-width: 900px;
}
footer>p img {
max-width: 15px;
}
.footer-links-left>*,
.footer-links-right>* {
display: inline-block;
}
.footer-links-left {
margin-top: -50px;
}
.footer-links-left a {
margin: 0px 20px;
}
.footer-links-right {
margin-left: 400px;
}
/* responsive media*/
@media (max-width: 1550px) {
main {
max-width: 980px;
}
}
@media (max-width: 1475px) {
main {
max-width: 900px;
}
}
@media (max-width: 1287px) {
main {
max-width: 860px;
}
nav {
margin-left: -40px;
}
}
@media (max-width: 1200px) {
footer>hr {
max-width: 720px;
}
nav {
margin-bottom: 35px;
}
}
@media (max-width: 882px) {
main {
padding: 0px 20px;
}
}
@media (max-width: 727px) {
.footer-links-left a {
margin: 0 10px;
}
.footer-links-left,
.footer-links-right {
margin: 0px 20px;
margin-top: 10px;
}
footer>hr {
max-width: 650px;
}
}</code>
<code><!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<details>
<summary>content</summary>
<table>
<tr>
<th>Item1</th>
<th>Item2</th>
<th>Item3</th>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</table>
</details>
<div class="container">
<header>
<h1><a href="#">Page</a></h1>
</header>
<nav>
<ul>
<li>
<a href="#"> </a>Link 1</li>
<li>
<a href="#"></a>Link 2</li>
<li>
<a href="#"></a>Link 3</li>
</ul>
</nav>
<main>
<div class="lists">
<details>
<summary>content</summary>
<table>
<tr>
<th>Item1</th>
<th>Item2</th>
<th>Item3</th>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</table>
</details>
</div>
</main>
<footer>
<hr>
<p>
<a href="../rss/rss.xml"><img src="../images/rss.svg"></a> Get updates with <a href="../rss/rss.xml">RSS</a> feed!</p>
<p><b>Updated: July 17, 2022</b></p>
<div class="footer-links-left">
<a href="#">link</a>
<a href="#">link</a>
<div class="footer-links-right">
<a href="#">link</a>
<a href="#">Link</a>
</div>
</div>
</footer>
</div>
</body>
</html></code>
Answer: I can recommend the next few options.
1.Use <code>vw</code> values instead of <code>vh</code> in your <code>.list</code> styles, so it relies on width of the screen instead of the height:
<code>.lists {
width: 90vw;
}
</code>
2.Remove default margin from <code>main</code> element and then you should have a similar behavior for the <code>list</code> to the one you have for <code>content</code>
<code>main {
margin: 0;
}
</code> | [{"idx": "Webscraper_in_Node.js_returns_empty_array_with_async_and_promise", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-19384.jsonl"}, {"idx": "How_to_make_element's_width_decrease_inside_container", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-19384.jsonl"}] |
# coding=utf8
import errno
import logging
import os
import os.path
import time
import shutil
from handlers.base import BaseHandler
from replay import get_provider_by_name
from settings import MEDIA_ROOT
import tornado.web
import tornado. httpclient
logger = logging.getLogger('listenone.' + __name__)
class TrackFileHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
artist = self.get_argument('artist')
album = self.get_argument('album')
title = self.get_argument('title')
sid = self.get_argument('id')
source = self.get_argument('source', '')
download = self.get_argument('download', '')
provider = get_provider_by_name(source)
# local cache hit test
ext = 'mp3'
if url != '':
else:
ext = provider.filetype()[1:]
MEDIA_ROOT, 'music', artist, album, title +
'_' + sid + '.' + ext)
if os.path.isfile(file_path) and download != '1':
redirect_url = os.path.join(
'/static/music/', artist, album,
title + '_' + sid + '.' + ext)
self.redirect(redirect_url, False)
return
if url == '':
sid = sid.split('_')[1]
url = provider.get_url_by_id(sid)
Intel Mac OS X 10_11_1) ' + \
'AppleWebKit/537.36 (KHTML, like Gecko) ' + \
'Chrome/46.0.2490.86 Safari/537.36'
referer = ' [IDX] xwith = 'ShockwaveFlash/19.0.0.245'
headers = {
'X-Requested-With': xwith,
'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2',
}
# read range from request header
req_range = self.request.headers.get('Range', '')
if req_range != '':
headers['Range'] = req_range
self.client = tornado. httpclient.AsyncHTTPClient()
request = tornado. httpclient.HTTPRequest(
url=url, headers=headers,
streaming_callback=self._on_chunk,
header_callback=self._on_header)
self.client.fetch(request, self._on_download)
# self.set_status(206)
self.bytes_so_far = 0
if download == '1':
filename = title + '_' + artist + '.' + ext
self.set_header(
'attachment; filename="%s"' % filename)
if not os.path.exists(os.path.dirname(file_path)):
try:
os.makedirs(os.path.dirname(file_path))
raise
timestamp_string = str(time.time()).replace('.', '')
self.tmp_file_path = file_path + '.' + timestamp_string
self.fd = open(self.tmp_file_path, 'wb')
def _chunk(self, data):
self.write(data)
self.flush()
def _parse_header_string(self, header_string):
comma_index = header_string.find(':')
k = header_string[:comma_index]
v = header_string[comma_index + 1:].strip()
return k, v
def _on_header(self, header):
k, v = self._parse_header_string(header)
if k in [
'Content-Length', 'Accept-Ranges',
'Content-Type', 'Content-Range',
'Accept-Ranges', 'Connection']:
if header.startswith('Content-Length'):
self.total_size = int(header[len('Content-Length:'):].strip())
def _on_chunk(self, chunk):
self.write(chunk)
self.flush()
self.fd.write(chunk)
self.bytes_so_far += len(chunk)
def _on_download(self, response):
self.finish()
self.fd.close()
# check if file size equals to content_length
size = 0
with open(self.tmp_file_path, 'r') as check_fd:
check_fd.seek(0, 2)
size = check_fd.tell()
if size > 2 and size == self.total_size:
'''
why size will less than 2:
safari browser will prerequest url with byte range 2,
so maybe generate temp file with 2 bytes.
'''
timestamp_string = self.tmp_file_path.split('.')[-1]
target_path = self.tmp_file_path[:-(len(timestamp_string) + 1)]
shutil.move(self.tmp_file_path, target_path)
else:<|endoftext|>import os.path as osp
import numpy as np
from ...main import cfg
import json
from ...common import pixel2cam, process_bbox
from MuPoTS_eval import calculate_score
class MuPoTS:
def __init__(self, data_split):
self.img_dir = osp.join('..', 'data', 'MuPoTS', 'data', 'MultiPersonTestSet')
self.annot_path = osp.join('..', 'data', 'MuPoTS', 'data', 'MuPoTS-3D.json')
self.human_bbox_dir = osp.join('..', 'data', 'MuPoTS', 'bbox', 'bbox_mupots_output.json')
# MuCo-3DHP
self.joint_num = 21
self.joints_name = ('Head_top', 'Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'L_Shoulder',
'L_Elbow', 'L_Wrist', 'R_Hip', 'R_Knee', 'R_Ankle', 'L_Hip', 'L_Knee',
'L_Ankle', 'Pelvis', 'Spine', 'Head', 'R_Hand', 'L_Hand', 'R_Toe', 'L_Toe')
# MuPoTS
self.original_joint_num = 17
self.original_joints_name = ('Head_top', 'Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist',
'L_Shoulder', 'L_Elbow', 'L_Wrist', 'R_Hip', 'R_Knee',
'R_Ankle', 'L_Hip', 'L_Knee', 'L_Ankle', 'Pelvis', 'Spine',
'Head')
self.joints_have_depth = True
self.root_idx = self.joints_name.index('Pelvis')
self.data = self.load_data()
def load_data(self):
if self.data_split != 'test':
print('Unknown data subset')
assert 0
data = []
db = COCO(self.annot_path)
if cfg.use_gt_bbox:
print("Get bounding box from groundtruth")
if ann['is_valid'] == 0:
continue
c = np.array([cx, cy])
joint_cam = np.array(ann['keypoints_cam'])
joint_img = np.array(ann['keypoints_img'])
joint_img = np.concatenate([joint_img, joint_cam[:,2:]],1)
joint_vis = np.array(ann['keypoints_vis'])
root_cam = joint_cam[self.root_idx]
root_img = joint_img[self.root_idx]
root_vis = joint_vis[self.root_idx,None]
bbox = np.array(ann['bbox'])
data.append({
'image_id': ann['image_id'],
'root_img': root_img, # [org_img_x, org_img_y, depth - root_depth]
'root_cam': root_cam, # [X, Y, Z] in camera coordinate
'root_vis': root_vis,
'f': f,
'c': c,
})
else:
with open(self.human_bbox_dir) as f:
print("Get bounding box from " + self.human_bbox_dir)
image_id = annot[i]['image_id']
c = np.array([cx, cy])
bbox = np.array(annot[i]['bbox']).reshape(4)
data.append({
'root_img': np.ones((3)), # dummy
'root_cam': np.ones((3)), # dummy
'root_vis': np.ones((1)), # dummy
'f': f,
'c': c,
'score': annot[i]['score']
})
return data
def evaluate(self, preds, result_dir, epoch):
print('Evaluation start...')
pred_save = []
gts = self.data
sample_num = len(preds)
gt = gts[n]
image_id = gt['image_id']
f = gt['f']
c = gt['c']
bbox = gt['bbox'].tolist()
score = gt['score']
# restore coordinates to original space
pred_root = preds[n].copy()
pred_root[0] = pred_root[0] / cfg.output_shape[1] * bbox[2] + bbox[0]
pred_root[1] = pred_root[1] / cfg.output_shape[0] * bbox[3] + bbox[1]
# back project to camera coordinate system
pred_root = pixel2cam(pred_root[None,:], f, c)[0]
pred_save.append({'image_id': image_id, 'root_cam': pred_root.tolist(), 'bbox': bbox, 'score': score})
output_path = osp.join(result_dir, 'bbox_root_mupots_output%d.json' % epoch)
json.dump(pred_save, f)
print("Test result is saved at " + output_path)
calculate_score(output_path, self.annot_path, 250)<|endoftext|>import fitsio
import os
import numpy as np
import sys
import unittest
import shutil, tempfile
class AbstractTest(unittest.TestCase):
"""
Class with Helper functions for the picca unit tests
"""
def compare_fits(self, path1, path2, nameRun=""):
"""
Compares all fits files in 2 directories against each other
Args:
path1 (str): path where first set of fits files lies
path2 (str): path where second set of fits files lies
nameRun (str, optional): A name of the current run for identification. Defaults to "".
"""
m = fitsio.FITS(path1)
self.assertTrue(os.path.isfile(path2), "{}".format(nameRun))
b = fitsio.FITS(path2)
self.assertEqual(len(m), len(b), "{}".format(nameRun))
for i, _ in enumerate(m):
###
r_m = m[i].read_header().records()
ld_m = []
for el in r_m:
if len(name) > 5 and name[:5] == "TTYPE":
ld_m += [el['value'].replace(" ", "")]
###
r_b = b[i].read_header().records()
ld_b = []
for el in r_b:
if len(name) > 5 and name[:5] == "TTYPE":
ld_b += [el['value'].replace(" ", "")]
self.assertListEqual(ld_m, ld_b, "{}".format(nameRun))
for k in ld_m:
d_m = m[i][k][:]
d_b = b[i][k][:]
if d_m.dtype in ['<U23',
d_m = np.char.strip(d_m)
if d_b.dtype in ['<U23',
d_b = np.char.strip(d_b)
self.assertEqual(d_m.size, d_b.size,
"{}: Header key is {}".format(nameRun, k))
if not np.array_equal(d_m, d_b):
diff = d_m - d_b
diff_abs = np.absolute(diff)
w = d_m != 0.
diff[w] = np.absolute(diff[w] / d_m[w])
allclose = np.allclose(d_m, d_b)
allclose,
"{}: Header key is {}, maximum relative difference is {}, maximum absolute difference is {}".
format(nameRun, k, diff.max(), diff_abs.max()))
m.close()
b.close()
return
@classmethod
def load_requirements(cls, picca_base):
"""
Loads reqirements file from picca_base
"""
req = {}
path = picca_base + '/requirements.txt'
else:
path = picca_base + '/requirements-python2.txt'
for l in f:
l = l.replace('\n', '').replace('==', ' ').replace('>=',
' ').split()
assert len(
l) == 2, "requirements.txt attribute is not valid: {}".format(
str(l))
req[l[0]] = l[1]
return req
@classmethod
def send_requirements(cls, req):
"""
Compares requirements in req to currently loaded modules
"""
for req_lib, req_ver in req.items():
try:
local_ver = __import__(req_lib).__version__
if local_ver != req_ver:
print(
"WARNING: The local version of {}: {} is different from the required version: {}"
.format(req_lib, local_ver, req_ver))
print("WARNING: Module {} can't be found".format(req_lib))
return
@classmethod
def setUpClass(cls):
"""
sets up directory structure in tmp
"""
cls._branchFiles = tempfile.mkdtemp() + "/"
cls.produce_folder(cls)
cls.picca_base = resource_filename('picca',
'./').replace('py/picca/./', '')
cls.send_requirements(cls.load_requirements(cls.picca_base))
cls._masterFiles = cls.picca_base + '/py/picca/test/data/'
cls._test=True
@classmethod
def tearDownClass(cls):
"""
removes directory structure in tmp
"""
if os.path.isdir(cls._branchFiles):
shutil.rmtree(cls._branchFiles, ignore_errors=True) | [{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11075.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11075.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11075.jsonl"}] |
// import { jasmine } from 'jasmine';
import { Quackologist } from "./src/observers/Quackoligist";
import { Quackable } from "./src/quackables/Quackable";
import { Flock } from "./src/quackables/Flock";
import { AbstractDuckfactory } from "./src/quackables/factories/AbstractDuckFactory";
import { GooseAdapter } from "./src/quackables/geese/GooseAdapter";
import { Goose } from "./src/quackables/geese/Goose";
import { CountingDuckFactory } from "./src/quackables/factories/CountingDuckFactory";
import { QuackCounter } from "./src/quackables/QuackCounter";
export class CompoundDuckFixture {
private duckFactory: AbstractDuckfactory;
private mallardDuck: Quackable;
private redheadDuck: Quackable;
private duckCall: Quackable;
private rubberDuck: Quackable;
private gooseDuck: Quackable;
private flockOfDucks: Flock;
private flockOfMallards: Flock;
private mallardOne: Quackable;
private mallardTwo: Quackable;
private mallardThree: Quackable;
private mallardFour: Quackable;
private quackologist: Quackologist;
constructor() {
this.duckFactory = new CountingDuckFactory();
//QuackCounter is Decorator Pattern
this.mallardDuck = this.duckFactory.createMallardDuck();
this.redheadDuck = this.duckFactory.createRedheadDuck();
this.duckCall = this.duckFactory.createDuckCall();
this.rubberDuck = this.duckFactory.createRubberDuck();
this.gooseDuck = new GooseAdapter(new Goose());//Adapter Pattern
//Flock is Iterator Pattern
this.flockOfDucks = new Flock();
this.flockOfDucks.add(this.redheadDuck);
this.flockOfDucks.add(this.duckCall);
this.flockOfDucks.add(this.rubberDuck);
this.flockOfDucks.add(this.gooseDuck);
this.flockOfMallards = new Flock();
this.mallardOne = this.duckFactory.createMallardDuck();
this.mallardTwo = this.duckFactory.createMallardDuck();
this.mallardThree = this.duckFactory.createMallardDuck();
this.mallardFour = this.duckFactory.createMallardDuck();
this.flockOfMallards.add(this.mallardOne);
this.flockOfMallards.add(this.mallardTwo);
this.flockOfMallards.add(this.mallardThree);
this.flockOfMallards.add(this.mallardFour);
this.flockOfDucks.add(this.flockOfMallards);
}
duckSimulator(): void {
QuackCounter.quackCount = 0;//set to zero just in case
console.log("Duck Simulator: With Abstract Factory");
console.log("Duck Simulator: Whole Flock Simulation");
console.log(this.simulate(this.flockOfDucks));
console.log("Duck Simulator: Mallard Flock Simulation");
console.log(this.simulate(this.flockOfMallards));
console.log("The ducks quacked ", QuackCounter.getQuacks(), " times");
}
duckSimulatorObserver(): void {
QuackCounter.quackCount = 0;//set to zero just in case
this.quackologist = new Quackologist();
this.flockOfDucks.registerObserver(this.quackologist);
console.log("Duck Simulator: With Observer");
console.log(this.simulate(this.flockOfDucks));
console.log("The ducks quacked ", QuackCounter.getQuacks(), " times");
}
simulate(duck: Quackable): string {
return duck.quack();
}
}<|endoftext|>import React from "react";
import { useUpdateAuthor } from "@/hooks/useUpdateAuthor";
import { MeFragmentFragment } from "@/__generated__/queries/queries.graphql";
import { Button, Form, Input } from "antd";
import ImageUpload from "../ImageUpload";
interface Props {
data: MeFragmentFragment;
}
export const Basic: React.VFC<Props> = ({ data }) => {
const [email, setEmail] = React.useState(data.email);
const [username, setUsername] = React.useState(data.username);
const { debounceUpdateAuthor, updateAuthor } = useUpdateAuthor(data.id);
return (
<>
<Form.Item label="Full Name">
<Input
placeholder="Write you full name"
size="middle"
value={data.name}
onChange={(e) => debounceUpdateAuthor({ name: e.target.value })}
data-testid="name"
/>
</Form.Item>
<Form.Item label="About You (html)">
<Input.TextArea
placeholder="Write about you. This will be displayed in the about me page. (4000 characters)"
value={data.bio}
onChange={(e) => debounceUpdateAuthor({ bio: e.target.value })}
autoSize={{ minRows: 10, maxRows: 80 }}
rows={8}
maxLength={4000}
data-testid="about"
/>
</Form.Item>
<Form.Item label="Occupation">
<Input
placeholder="What do you do ?"
value={data.occupation}
onChange={(e) => debounceUpdateAuthor({ occupation: e.target.value })}
size="middle"
data-testid="occupation"
/>
</Form.Item>
<Form.Item label="Company Name">
<Input
placeholder="Which company do you work for ?"
size="middle"
value={data.company_name}
data-testid="company"
onChange={(e) =>
debounceUpdateAuthor({ company_name: e.target.value })
}
/>
</Form.Item>
<Form.Item label="Email (private)">
<Input.Group compact>
<Input
size="middle"
value={email}
onChange={(e) => setEmail(e.target.value)}
style={{ width: "calc(100% - 100px)" }}
/>
<Button
type="primary"
size="middle"
onClick={(_) => updateAuthor({ email })}
disabled={email === data.email}
>
Save
</Button>
</Input.Group>
</Form.Item>
<Form.Item label="Username">
<Input.Group compact>
<Input
size="middle"
value={username}
onChange={(e) => setUsername(e.target.value)}
style={{ width: "calc(100% - 100px)" }}
/>
<Button
type="primary"
size="middle"
onClick={(_) => updateAuthor({ username })}
disabled={username === data.username}
>
Save
</Button>
</Input.Group>
</Form.Item>
<Form.Item label="Avatar">
<ImageUpload
url={data.avatar || ""}
name="Avatar"
onDone={([res]) => {
debounceUpdateAuthor({ avatar: res.src });
}}
dataTestid="avatar"
// onRemove={() => {
// updateLocalState({ avatar: "" });
// }}
/>
</Form.Item>
</>
);
};<|endoftext|>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { Result } from '../compete/compete';
/**
* Generated class for the ResultPage page.
*
* See [IDX] for more info on
* Ionic pages and navigation.
*/
declare var google;
@IonicPage()
@Component({
selector: 'page-result',
templateUrl: 'result.html',
})
export class ResultPage {
map: any;
results:Array<Result> = new Array<Result>();
currentName:string;
constructor(public navCtrl: NavController, public navParams: NavParams,private storage: Storage, public alertCtrl: AlertController) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad ResultPage');
this.storage.get('results').then((val) => {
this.results = val;
this.loadMap();
});
}
resetResults(){
const alert = this.alertCtrl.create({
title: 'Reset results',
message: 'Do you want to reset results?',
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: () => {
}
},
{
text: 'Ok',
handler: () => {
this.storage.clear();
this.navCtrl.pop();
}
}
]
});
alert.present();
}
reloadMap(result){
let latLng = new google.maps.LatLng(result.markers[0].lat, result.markers[0].lng);
this.currentName = result.name;
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
this.setUpMarkers(result.markers,this.map);
var flightPlanCoordinates = result.runningCords;
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(this.map);
}
loadMap(){
let latLng = new google.maps.LatLng(this.results[0].markers[0].lat, this.results[0].markers[0].lng);
this.currentName = this.results[0].name;
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
this.setUpMarkers(this.results[0].markers,this.map);
var flightPlanCoordinates = this.results[0].runningCords;
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(this.map);
}
setUpMarkers(markers, map){
for (var index = 0; index < markers.length; index++) {
new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(markers[index].lat, markers[index].lng),
draggable: false
});
}
}
} | [{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5054.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5054.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5054.jsonl"}] |
How to use javascript in react component
Question: I'm working on a React component and I found a specific javascript code that modify the content of my html page.
The problem is that I don't know how to merge this script into my component. I know I can call it with an "import" statement but the script works with a "window.onload" function that will be called only one time, but my component is mounted several times and the script won't work anymore
The Component -
<code>import React, { Component } from 'react';
import textRotation from '../../scripts/textRotation';
import './Main.scss';
class Main extends Component {
constructor(props) {
super(props);
this.title = props.title;
this.imgSrc = props.imgSrc;
}
render() {
return (
<div className="Main">
<div className="main-content">
<div className="presentation-caption">
<span>Hello, I'm Jordan, a junior front-end developer, who does a lot of things.</span>
</div>
<div className="description-caption">
<span>Prepare you to encounter various types of projects... but it's ok, just explore !</span>
</div>
<div className="button-container">
<a href="#works"><button>Scroll down</button></a>
</div>
</div>
<div className="side-content">
<span
className="txt-rotate"
data-period="1100"
data-rotate='[ "Web development", "Video editing", "Motion design", "Graphism", "Creativity" ]'></span><span>.</span>
</div>
<div className="side-text-portfolio">
<span>ポ<br />ー<br />ト<br />フ<br />ォ<br />リ<br />オ</span>
</div>
</div>
);
}
}
export default Main;
</code>
The script -
<code>var TxtRotate = function (el, toRotate, period) {
this.toRotate = toRotate;
this.el = el;
this.loopNum = 0;
this.period = parseInt(period, 10) || 2000;
this.txt = '';
this.tick();
this.isDeleting = false;
};
TxtRotate.prototype.tick = function () {
var i = this.loopNum % this.toRotate.length;
var fullTxt = this.toRotate[i];
if (this.isDeleting) {
this.txt = fullTxt.substring(0, this.txt.length - 1);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1);
}
this.el.innerHTML = '<span class="wrap">' + this.txt + '</span>';
var that = this;
var delta = 300 - Math.random() * 100;
if (this.isDeleting) { delta /= 2; }
if (!this.isDeleting && this.txt === fullTxt) {
delta = this.period;
this.isDeleting = true;
} else if (this.isDeleting && this.txt === '') {
this.isDeleting = false;
this.loopNum++;
delta = 500;
}
setTimeout(function () {
that.tick();
}, delta);
};
window.onload = function () {
var elements = document.getElementsByClassName('txt-rotate');
for (var i = 0; i < elements.length; i++) {
var toRotate = elements[i].getAttribute('data-rotate');
var period = elements[i].getAttribute('data-period');
if (toRotate) {
new TxtRotate(elements[i], JSON.parse(toRotate), period);
}
}
// INJECT CSS
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".txt-rotate > .wrap { border-right: 0.08em solid #725070 }";
document.body.appendChild(css);
};
</code>
If you have any solutions for adding the script into my Component, or the properly reload it ... thanks by advance
Answer: Change the script to this:
<code>var TxtRotate = function (el, toRotate, period) {
this.toRotate = toRotate;
this.el = el;
this.loopNum = 0;
this.period = parseInt(period, 10) || 2000;
this.txt = '';
this.tick();
this.isDeleting = false;
};
TxtRotate.prototype.tick = function () {
var i = this.loopNum % this.toRotate.length;
var fullTxt = this.toRotate[i];
if (this.isDeleting) {
this.txt = fullTxt.substring(0, this.txt.length - 1);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1);
}
this.el.innerHTML = '<span class="wrap">' + this.txt + '</span>';
var that = this;
var delta = 300 - Math.random() * 100;
if (this.isDeleting) { delta /= 2; }
if (!this.isDeleting && this.txt === fullTxt) {
delta = this.period;
this.isDeleting = true;
} else if (this.isDeleting && this.txt === '') {
this.isDeleting = false;
this.loopNum++;
delta = 500;
}
setTimeout(function () {
that.tick();
}, delta);
};
loadCall = function () {
var elements = document.getElementsByClassName('txt-rotate');
for (var i = 0; i < elements.length; i++) {
var toRotate = elements[i].getAttribute('data-rotate');
var period = elements[i].getAttribute('data-period');
if (toRotate) {
new TxtRotate(elements[i], JSON.parse(toRotate), period);
}
}
// INJECT CSS
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".txt-rotate > .wrap { border-right: 0.08em solid #725070 }";
document.body.appendChild(css);
};
const loadMyScript = () => window.addEventListener('load', () => loadCall());
export default loadMyScript;
</code>
Then import <code>loadMyScript</code> and call <code>loadMyScript()</code> from the <code>componentDidMount()</code> function within your component.
Comment: Thanks for the help, I applied the code you gave me plus a modification given in the comment left by @tenor528 : I call the function "loadCall" each time in the componentDidMount function and this now works
Answer: If you are able to change the code in the script, you can change it to be callable instead of firing on load, i.e. give the function a name. And then you can call that function in the componentDidMount hook of your component.<|endoftext|>When can we declare an identify-this-question game abandoned, and what should be done about it?
Question:
UPDATE: As of 16/3/2012, Identify this game questions are now prohibited on the site.
Take Mike. Mike joined as an unregistered user February 22nd at 19:25:24 Zulu as he posted this question tagged identify-this-question. He last visited on the same day at 23:11:05 Zulu (ranking him above a real lot of unregistered users who leave one post and never look back again).
For normal questions, this isn't really a problem. For ITGs, it is, because he is the only user who can actually say "yes, this is it." An abandoned ITG is just a game-rec in disguise. That's not very good.
However, I should note unregistered users only are tracked via cookies, for lack of anything better; that's the "price" to pay for allowing anonymous users to post. If When the user clears his cookies, he gets effectively locked out from his account (that's fixable if he requests a merge). This makes, however, the last seen value less useful. For all we know, he could've cleared his cookies on the 23rd and checked the question every day since. It's however quite unlikely, and human exception handlers can probably take care of this situation.
So: when can we declare an ITG question abandoned? What should we do about them?
Keep in mind that the condition must be actually enforceable. If your abandonment condition can't be expressed in (at the very most!) an SQL query, it's probably too complicated to be usable. :)
What about questions that can never have an accepted answer, as they have no owner? This one has a +16 answer with a +50 bounty... I'm kinda hesitant to closing and deleting this one as well. (Other example.)
Comment: yet another reason for me to hate this class of question. But I said my piece at [IDX] Okay, current plan:
Close NARQ and delete identify-this-game posts with no accepted answer (list) if their last activity timestamp is older than a month.
If a question is then undeleted by 10kers and/or moderators (list of deleted posts), this rule should not be applied a second time.
The checkmark merely means that this has been done; it does not mean that the above is set in stone. I'm aware this is not perfect; please contribute ideas for improvement if you have any!
Comment: Please, please, add a condition so that a question with an answer with score ≥4 won't be deleted. For example, it's clear that the Qix/Xonix/… question has worthwhile answers and should stay. (No, I don't really care about Gaming. But you're setting a precedent, that I don't want to have to fight on Scifi.)
Comment: Hold on, this thread is about abandoned questions - i.e. the OP is no longer active. As long as the OP *is* active, the question should remain open (as long as it's not too vague, of course, in which case it needs to be closed as NARQ).
Comment: @Oak Yes, [roughly half of those come from registered users.]( [IDX] However, you must consider that most of the registered users actually come from SO and only own that question; they still _would_ get notified by new answers and they _would_ be able to accept one. However, they don't actually help search engines in matching a game with those search terms, which is one of the (few) saving graces of ITG questions... they do the opposite and pollute search results. They're still poisonous. That said I'm open to suggestions!
Comment: @Gilles I underlined the possibility of manual review by moderators and 10kers; I would rather not make it too easy to game the system my merely voting things up.
Comment: Even if the answers did not help the OP, the answers could easily help someone else in the future who is looking for the same or similar game. I really don't understand what we gain by closing/deleting old questions - that is what Yahoo Answers does, and it is annoying as all-hell.
Comment: @BlueRaja-DannyPflughoeft For the record [SE also removes questions with low score, low views, no answers automatically.]( [IDX] Also, out of 383 `identify-this-game` questions with answers, [31 of them]( [IDX] were given accepted answers more than 28 days after being asked. That's 8% - nearly one out of ten - of them which would have been deleted under this new rule. Deleting even one of them, if it helped someone in the future find what they're looking for, would be unfortunate IMHO.
Comment: @BlueRaja-DannyPflughoeft Yes, but the problem is, yknow, _the other 92%._ I don't think picking up dust being only visible in the list of all questions with that tag is a way to be the 8% of late answered questions. Also. The plan considers a month since _last activity_ - any edit, any new answer, etc. - not time of asking)
Answer: I'd just go for no accepted answer and no activity for a month (meaning no new answers, comments or edits). Something close to this should be possible in the Data Explorer. One could also manually check if the OP commented that it was the right game, in case he didn't know he was supposed to accept the answer.
Any question fitting these criteria should be deleted, they add nothing useful to the site (as LessPop_MoreFizz already mentioned).
Answer: As for the criteria for abandonment, I'll leave that to the folks with a better understanding of what data is availiable.
As for what to do: these questions are broken windows. They include some of the worst questions on the network. They should be closed, and eventually deleted. They offer no value to the site, the network, or the internet as a whole by remaining here.
Comment: Just because I mentioned the data.SE SQL numbo jumbo doesn't mean something simpler than that wouldn't work (say, a [search]( [IDX] would be adequate) | [{"idx": "How_to_use_javascript_in_react_component", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-14066.jsonl"}, {"idx": "When_can_we_declare_an_identify-this-question_game_abandoned,_and_what_should_be_done_about_it?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-14066.jsonl"}] |
How to "shallow" \renewenvironment of \itemize?
Question: I want to patch exactly the outer level of \itemize, whereas the following MWE (expectedly) patches all of them:
<code>\documentclass{article}
\begin{document}
\setlength{\fboxsep}{0pt}
\let\saveditemize=\itemize%
\let\savedenditemize=\enditemize%
\renewenvironment{itemize}
{\begin{minipage}{5cm}
=foo=\saveditemize}
{\savedenditemize\end{minipage}}
\begin{itemize}
\item {External item one\\
\begin{itemize}
\item{Internal item one}
\item{Internal item two}
\end{itemize}
}
\item{External item two}
\end{itemize}
\end{document}
</code>
..which is both evident and expected:
..as =foo= appears twice.
My best attempt so far had the more-or-less direct approach, namely wrapping the contents with <code>\bgroup\let\itemize=..\let\savedenditemize=..} {\egroup</code> or, more precisely, replacing the <code>\renewenvironment</code> piece with:
<code>\renewenvironment{itemize}
{\begin{minipage}{5cm}
=foo=\saveditemize\bgroup\let\itemize=\saveditemize\let\enditemize=\savedenditemize}
{\egroup\savedenditemize\end{minipage}}
</code>
This, however, fails, since the <code>\begin\end</code> environment tracker apparently goes off rails:
<code>! LaTeX Error: \begin{minipage} on input line 14 ended by \end{itemize}.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.22 \end{itemize}
?
! Emergency stop.
...
l.22 \end{itemize}
No pages of output.
</code>
Having approached this problem from multiple angles for quite a while, I'm out of ideas..
Comment: What exactly are you trying to achieve in format? This seems like something better handled with the `enumitem` package.
Comment: I'm sorry, I don't see what you're trying to obtain.
Comment: The general context is this: 0. Beamer, 1. I don't control the TeX file, only the Beamer theme, 2. The (invariant) environment hierarchy is `\frame-\customenv-\itemize-\item-\itemize-\item`, 3. I need to be able to thoroughly rewrite the outer `\itemize`
Comment: Sorry, but that's really too vague. Also, if you're using `beamer` you should have made the example using `beamer`. The lists in `beamer` are not customizable using the same methods as in regular document classes, so this may make a big difference.
Comment: Alan, and you're perfectly right, indeed -- I have failed to port Ulrike's entirely valid answer into my `beamer` problem. Shame on my head! Would it be appropriate for me to ask another, similar question with the extended context?
Comment: ..and indeed, `beamer` is the culprit, as evident from another question: quoting @egreg : "Indeed, \begin{document} resets the category code of @ doing \makeatother, but only in beamer, not in the standard classes." -- [IDX] ..and that was solved through replacing the `\makeatletter` context with escaping `\@listdepth` -> `\csname @listdepth\endcsname` -- as suggested in [IDX] @deepfire If you've managed to solve the `beamer` version of your question yourself, there's no need to ask a new question, but it might be useful to edit the question to show what you did to get the solution to work with `beamer`. If you haven't yet got it to work with `beamer` then another question (linking to this one) is certainly appropriate. P.S. If you precede names in comments with `@` then the person gets notified of the comment.
Answer: The nesting level is stored in \@listdepth, so you could check its value:
<code>\documentclass{article}
\begin{document}
\setlength{\fboxsep}{0pt}
\let\saveditemize=\itemize%
\let\savedenditemize=\enditemize%
\makeatletter
\renewenvironment{itemize}
{\ifnum \@listdepth=0\begin{minipage}{5cm}=foo=\fi\saveditemize}
{\savedenditemize\ifnum \@listdepth=0 \end{minipage}\fi}
\makeatother
\begin{itemize}
\item {External item one
\begin{itemize}
\item{Internal item one}
\item{Internal item two}
\end{itemize}
}
\item{External item two}
\end{itemize}
\end{document}
</code>
Comment: I have failed to transplant the solution to my beamer problem, but this is a good step.<|endoftext|>Determining the branch of the complex argument
Question: I am working on a complex analysis problem and I am stuck at a particular section. Basically, we are given a region in which the argument of a complex number, $\arg(z)$, is defined, and its value at a given point. We are then asked to find the argument of other complex numbers based on this information.
The point in which I am stuck is when working in $\mathbb{C} \setminus \{re^{i\frac{\pi}{4}}: r \geq 0\}$ and I am given $\arg(1)=0$, and I need to find $\arg(i)$. I thought that the "origin line" for measuring the angle of a complex number in this set was the reflection through the origin of the removed line: $\{re^{i(\frac{\pi}{4} + \pi)}: r \geq 0\}$. From there, I calculated the argument of 1 from this line:
$$
\arg(1) = \frac{3\pi}{4} + 2\pi n \quad , n\in \mathbb{Z}
$$
and imposed $\arg(1) = 0$ to find $n$, but I get nonsense: $n = -3/8$.
Where is the flaw in this argument? Perhaps I am wrong when defining the argument in $\mathbb{C} \setminus \{re^{i\frac{\pi}{4}}: r \geq 0\}$ this way? By the way, the answer turns out to be $\arg(i) = -\frac{3\pi}{2}$.
Any help will be appreciated.
Answer: This is really a Euclidean geometry exercise and I would very strongly advise drawing a picture of the Euclidean plane. I'll describe the picture in words.
Draw the complex plane (i.e. the $x,y$ plane).
Draw the ray $\{r e^{i \pi/4} : r \ge 0\}$ as a dotted ray, to indicate that it is omitted (i.e. the portion of the line $y=x$ in the first quadrant of the $x,y$ plane).
Plot the point $1 = 1 + 0i$ (i.e. the point $(1,0)$)
Plot the point $i = 0+1i$ (i.e. the point $(0,1)$)
Connect $1$ to $i$ by circular arc, contained in the unit circle, which misses the dotted ray (i.e. the portion of the unit circle in the $4^{\text{th}}$, $3^{\text{rd}}$ and $2^{\text{nd}}$ quadrants).
Let the radian angle vary continuously along that circular arc, from $0$ radians at $1+0i$, to the appropriate radian value at $0+1i$: From $0$ radians at $1+0i$, the arc goes through the 4th quadrant to $-\pi/2$ radians at $0-1i$, then continues through the 3rd quadrant to $-\pi$ radians at $-1+0i$, and finally continues through the 2nd quadrant to $-3\pi/2$ radians at $0+1i$.
So the argument is $-3\pi/2$.
By the way, I don't know what you mean by "origin line". However if I may borrow that terminology, the key to this problem is that your "original" ray through $1+0i$ is the positive half of the $x$-axis, and then you spin that ray in the clockwise direction (to avoid the removed ray) until reaching the "final" ray through $0+1i$.
Comment: I see, completely visual. Thank you! I have one doubt though: the effect of removing this line has no implication on how we define the "origin line" by which we measure the angles of complex numbers? Is it still the line $[0, \infty)$?
Comment: I added some words about that point. But if this isn't enough then you'll have to explain your understanding of the "origin line" terminology. It's not standard terminology and I would not like to guess what it means in whatever sources you are using.
Comment: What I mean by "origin line" is that we have chosen the line $[0, \infty)$ to measure angles, but we could have chosen any other line through the origin. It is a completely made up term, I apologise for the confusion.
Comment: Well then, my final paragraph is the best thing I can think of saying. In this problem, the given point $1=1+0i$ defines the "origin ray" (I would avoid the terminology "origin line").
Comment: Again, thank you! Very intuitive explanation.
Comment: The reason the point 1=1+0i defines the ray from which the argument is measured (apart from it being the only non-zero point which is canonically given in the definition of C) is that the argument is the imaginary part of the multi-valued function Log, the "inverse" to the exponential function: if $\mathrm{exp}(z) = w$, then $z = \mathrm{log}(|w|) +i \mathrm{arg}(w)$, where $\mathrm{arg}(w)$ is only defined up to multiples of 2$\pi$, and is the angle $w$ makes with the ray through 1+0i.<|endoftext|>Unable to map namespaces to xmlns namespaces in xaml
Question: I'm following a tutorial on MVVM and am having some issues.
I created 4 folders which represent 4 different namespaces. In my <code>MainPage.xaml</code> I'm making a reference to these namespaces using the following code:
<code>xmlns:viewModels="using:ViewModels"
xmlns:converters="using:Converters"
</code>
These properties are in the <code>Page</code> attributes.
Next, I need to use those using the following code:
<code><Page.Resources>
<converters:ObjectExistsToVisible x:Key="ObjectExistsToVisible" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Vertical">
<ListView x:Name="MainList"
ItemsSource="{x:Bind Organization.People, Mode=OneWay}"
SelectedIndex="{x:Bind Organization.SelectedIndex, Mode=TwoWay}"
MinWidth="250" Margin="5">
<ListView.ItemTemplate>
<!-- The error is with x:DataType="" -->
<DataTemplate x:DataType="viewModels:PersonViewModel" >
<TextBlock Text="{x:Bind Name, Mode=OneWay}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Content="Add" Click="{x:Bind Organization.Add}" Margin="5"/>
</StackPanel>
<StackPanel Grid.Column="2" Orientation="Vertical">
<TextBox
Text="{x:Bind Organization.SelectedPerson.Name, Mode=TwoWay, FallbackValue=''}"
Margin="5" />
<TextBox
Text="{x:Bind Organization.SelectedPerson.Age, Mode=TwoWay, FallbackValue='0'}"
Margin="5" />
<Button Content="Delete" Click="{x:Bind Organization.Delete}" Margin="5" />
</StackPanel>
</Grid>
</code>
The tutorial can be found at: this link
The problem is, I'm getting the following errors:
The name "ObjectExistsToVisible" does not exist in the namespace "using:Converters"
The name "PersonViewModel" does not exist in the namespace "using:ViewModels"
I'm pretty sure that they do exist.
As requested:
PersonViewModel:
<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Data;
namespace ViewModels
{
public class PersonViewModel : NotificationBase<Person>
{
public PersonViewModel(Person person = null) : base(person) { }
public String Name
{
get { return This.Name; }
set { SetProperty(This.Name, value, () => This.Name = value); }
}
public int Age
{
get { return This.Age; }
set { SetProperty(This.Age, value, () => This.Age = value); }
}
}
}
</code>
Comment: You're pretty sure they exist? How did you verify? Normally, your namespace would be `MuhApplicationName.SomeNamespace`. Open up PersonViewModel.cs, copy everything from the top of the file down to the class definition (public class PersonViewModel...) and paste it into an [edit].
Comment: No, your namespace is correct. If the errors are within the designer, make sure you clean and build the solution. If it builds correctly and you don't get any runtime errors due to this namespace problem, it's just a problem with the editor. False errors reported in the editor is a common problem, unfortunately.
Comment: You can share details about how you fixed this in an answer and close this question out.
Comment: @Will Updated the post. I tried using `MyApplicationName.SomeNamespace` before, which didn't work. So I followed the tutorial letter by letter which also didn't work.
Comment: @Will Yep, that fixed it! Will have to look out for that in the future. Thanks!
Answer: After a great comment from Will, the solution is as follows:
First, clean the solution via <code>Build > Clean Solution</code>.
Next, rebuild the solution via <code>Build > Rebuild Solution</code>.
This fixed the errors for me. | [{"idx": "How_to_\"shallow\"_\\renewenvironment_of_\\itemize?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-21785.jsonl"}, {"idx": "Determining_the_branch_of_the_complex_argument", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-21785.jsonl"}, {"idx": "Unable_to_map_namespaces_to_xmlns_namespaces_in_xaml", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-21785.jsonl"}] |
import { FpjsProvider } from '@fingerprintjs/fingerprintjs-pro-react'
import { useState } from 'react'
import { Outlet } from 'react-router-dom'
import { Nav } from '../shared/components/Nav'
import { FPJS_API_KEY } from '../shared/utils/env'
import { CacheLocation, LoadOptions } from '@fingerprintjs/fingerprintjs-pro-spa'
function SessionStorageCache() {
const [loadOptions] = useState<LoadOptions>({
apiKey: FPJS_API_KEY,
})
return (
<FpjsProvider loadOptions={loadOptions} cacheLocation={CacheLocation.SessionStorage} cacheTimeInSeconds={60 * 5}>
<div className='App'>
<header className='header'>
<h2>Solution with a custom implementation of a session storage cache</h2>
<div className='subheader'>New API call made after a key expires or is cleared from the local storage</div>
</header>
<Nav />
<Outlet />
</div>
</FpjsProvider>
)
}
export default SessionStorageCache<|endoftext|>import { Component, EventEmitter, OnInit, Output } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
@Component({
selector: "app-create-task",
templateUrl: "./create-task.component.html",
styleUrls: ["./create-task.component.scss"],
})
export class CreateTaskComponent implements OnInit {
toDoForm: FormGroup;
@Output() submittedTask: EventEmitter<any> = new EventEmitter();
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.toDoForm = this.formBuilder.group({
description: ["", [Validators.required, Validators.maxLength(25)]],
label: ["", [Validators.required, Validators.maxLength(25)]],
category: ["", [Validators.required, Validators.maxLength(25)]],
});
}
submitForm() {
if (this.toDoForm.valid) {
let values = this.toDoForm.value;
values.done = false;
values.completedDate = null;
this.submittedTask.emit(values);
}
}
}<|endoftext|>import template from "./teams.component.html";
import style from "./teams.component.less";
import {OnInit, Component} from "@angular/core";
import {Router} from "@angular/router";
import {TeamDataService} from "../teamService.service";
import {Observable} from "rxjs";
import {Team} from "../../../../../both/models/team.model";
@Component({
selector: "teams",
template,
styles: [ style ]
})
export class TeamComponent implements OnInit {
private isLoggedIn: boolean = false;
private user: Meteor.User;
data: Observable<Team[]>;
/*Konstruktor mit der Übergabe von Angulars Router und dem TeamData-Servic zur Verwendung innerhalb der Komponente*/
constructor( private router: Router, private _teamDataService: TeamDataService ) { }
/*Daten werden vom Service angefordert und beim Aufruf der Komponente mit "ngFor" als Liste dargestellt*/
ngOnInit(): void {
this.data = this._teamDataService.getData().zone();
}
}<|endoftext|>import * as React from "react";
import { DiagramEngine } from "../../DiagramEngine";
import { NodeWidget } from "../NodeWidget";
import { NodeModel } from "../../models/NodeModel";
import * as _ from "lodash";
export interface NLWIProps {
diagramEngine: DiagramEngine;
}
export class NodeLayerWidgetInner extends React.Component<NLWIProps> {
public shouldComponentUpdate(nextProps) {
var modelNext = nextProps.diagramEngine.getDiagramModel();
var isCanvasMoving = modelNext.getIsCanvasMoving();
return !isCanvasMoving;
}
public render() {
var diagramModel = this.props.diagramEngine.getDiagramModel();
return (
<React.Fragment>
{_.map(diagramModel.getNodes(), (node: NodeModel) => {
return React.createElement(
NodeWidget,
{
diagramEngine: this.props.diagramEngine,
key: node.id,
node: node
},
this.props.diagramEngine.generateWidgetForNode(node)
);
})}
</React.Fragment>
);
}
}<|endoftext|>import nock from 'nock';
import { tweet } from '../src/twitter';
describe('Tweet tests', () => {
const message = 'Hello World';
const baseUrl = ' [IDX] const path = '/1.1/statuses/update.json';
test('Succeed request', async () => {
nock(baseUrl)
.post(path)
.query({ include_entities: 'true', status: message })
.reply(200);
try {
await tweet(message, 'a', 'b', 'c', 'd');
} catch (err) {
expect(err).toBe(undefined);
}
});
test('Fail request', async () => {
const errorResponse = {
errors: [{ message: 'Sorry, that page does not exist', code: 34 }]
};
nock(baseUrl)
.post(path)
.query({ include_entities: 'true', status: message })
.reply(404, errorResponse);
try {
await tweet(message, 'a', 'b', 'c', 'd');
} catch (err) {
expect(err.message).toMatch(
`Failed to post a tweet: ${JSON.stringify(errorResponse.errors)}`
);
}
});
});<|endoftext|>import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { AuthenticationService } from './../../services/auth.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
public form: FormGroup;
public email = new FormControl('', [Validators.required]);
public password = new FormControl('', [Validators.required]);
constructor(
private authenticationService: AuthenticationService,
private formBuilder: FormBuilder) {
this.form = formBuilder.group({
'email': this.email,
'password': this.password
});
}
ngOnInit(): void {
this.authenticationService.logout();
}
login(): void {
this.authenticationService.login(this.form.value.email, this.form.value.password);
}
}<|endoftext|>import React from 'react';
import { CallTime } from '../callContent/CallTime';
import { Mac } from '../../../components/toolsBar/mac';
import { Windows } from '../../../components/toolsBar/windows'
import { isWin, maxSizeWin, minSizeWin, closeWin } from '../../../utils/tools';
import event from '../event';
export const MeetingHeader = ({ roomId, groupName }) => {
const prefix = `ID: ${roomId} | `;
const isWindowsPlatform = isWin();
const closeWindow = () => {
event.emit('close-window')
}
return <div className="meeting-header">
{!isWindowsPlatform && <Mac maxSizeWin ={maxSizeWin} minSizeWin={minSizeWin} closeWin={closeWindow} />}
<div className="call-time-content">
<CallTime isStart prefix={prefix} />
</div>
<span className="group-name"> {groupName} </span>
{isWindowsPlatform && <Windows maxSizeWin ={maxSizeWin} minSizeWin={minSizeWin} closeWin={closeWindow} />}
</div>
}<|endoftext|>import { expect } from 'chai';
import * as puppeteer from 'puppeteer';
import {config } from '../config';
describe('ViewPublicProfile', function() {
let browser: puppeteer.Browser;
let page: puppeteer.Page;
before(async function() {
browser = await puppeteer.launch({headless: true});
page = await browser.newPage();
});
after(async function() {
if (browser) {
await browser.close();
}
});
describe('Given navigate to public profile', function() {
beforeEach(async function() {
await page.goto(` [IDX] });
it('Then display full name', async function() {
const fullnameSelector = '#profileNameTopHeading';
await page.waitForSelector(fullnameSelector, { visible: true });
const actualFullname = await page.evaluate((selector) => document.querySelector(selector).innerText, fullnameSelector);
expect(actualFullname).to.equal(config.goodreads.publicProfile.expectedFullname);
});
});
});<|endoftext|>import { RoomGrantDto } from 'src/application/roomGrants/interfaces/roomGrants.dto';
import { RoomDto } from 'src/application/rooms/interfaces/rooms.dto';
import { Room } from 'src/domain/model/room/Room.aggregate';
import { RoomGrant } from 'src/domain/model/roomGrant/RoomGrant.aggregate';
export const roomToRoomDto = (room: Room): RoomDto => {
const { id, roomTag, roomName } = room;
const roomDto = new RoomDto();
roomDto.id = id.id;
roomDto.name = roomName.name;
roomDto.tag = roomTag.tag;
return roomDto;
};
export const roomGrantToRoomGrantDto = (roomGrant: RoomGrant): RoomGrantDto => {
const {
id,
roomGrantAuthor,
roomGrantDelegat,
roomGrantRole,
roomId,
} = roomGrant;
const roomGrantDto = new RoomGrantDto();
roomGrantDto.id = id.id;
roomGrantDto.author = roomGrantAuthor.id;
roomGrantDto.delegat = roomGrantDelegat.id;
roomGrantDto.role = roomGrantRole.role;
roomGrantDto.room = roomId.id;
return roomGrantDto;
};<|endoftext|>import {
fetchWebhooksSubscriptions,
fetchWebhooksSubscriptionsSuccess,
fetchWebhooksSubscriptionsFailed,
} from '../webhooks-subscriptions'
import ActionTypes from '@/constants/action-types'
describe('webhookSubscriptions actions', () => {
describe('fetchWebhooksSubscriptions', () => {
it('should create a fetchWebhooksSubscriptions action', () => {
expect(fetchWebhooksSubscriptions.type).toEqual(ActionTypes.FETCH_WEBHOOKS_SUBSCRIPTIONS)
})
})
describe('fetchWebhooksSubscriptionsSuccess', () => {
it('should create a fetchWebhooksSubscriptionsSuccess action', () => {
expect(fetchWebhooksSubscriptionsSuccess.type).toEqual(ActionTypes.FETCH_WEBHOOKS_SUBSCRIPTIONS_SUCCESS)
})
})
describe('fetchWebhooksSubscriptionsFailed', () => {
it('should create a fetchWebhooksSubscriptionsFailed action', () => {
expect(fetchWebhooksSubscriptionsFailed.type).toEqual(ActionTypes.FETCH_WEBHOOKS_SUBSCRIPTIONS_FAILED)
})
})
})<|endoftext|>import React from 'react';
import ReactDOM from 'react-dom';
import { Amplify } from 'aws-amplify';
import './styles/index.css';
import App from './components/App';
import awsConfig from './awsConfig';
Amplify.configure({
Auth: {
mandatorySignIn: true,
region: awsConfig.cognito.REGION,
userPoolId: awsConfig.cognito.USER_POOL_ID,
identityPoolId: awsConfig.cognito.IDENTITY_POOL_ID,
userPoolWebClientId: awsConfig.cognito.APP_CLIENT_ID
},
Storage: {
region: awsConfig.s3.REGION,
bucket: awsConfig.s3.BUCKET,
identityPoolId: awsConfig.cognito.IDENTITY_POOL_ID
},
API: {
endpoints: [
{
name: 'events',
endpoint: awsConfig.apiGateway.URL,
region: awsConfig.apiGateway.REGION
},
]
}
});
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
); | [{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3809.jsonl"}] |
How does one derive this rotation quaternion formula?
Question: given an angle and an axis, the corresponding quaternion can be computed like this.
$w = \cos( Angle/2)$
$x = \text{axis}.x * \sin( Angle/2 )$
$y = \text{axis}.y * \sin( Angle/2 )$
$z = \text{axis}.z * \sin( Angle/2 )$
My question is, how are they formulas derived? I would like to know where they came from to understand quaternions better.
Answer: I'll take a crack at this, hopefully this will shed some light on how this works. First, it's important to remember that if you want to use a quaternion $\bf p$ to rotate some vector, also represented as a quaternion, $\bf a$, then you have to observe some rules.
$\bf a$ is typically represented by a pure imaginary quaternion, that is, $(0, \vec a)$. The rotation, as you observed, is represented by $(c,\vec ps)$, where $\vec p$ is the unit vector representing the axis of rotation, and $c$ and $s$ are the sine and cosine of $\theta/2$.
We'll also take a shortcut and use vector math to do the quaternion multiplication, so ${\bf p}{\bf q} = (p,\vec p)(q,\vec q) = (pq-\vec p\cdot\vec q,p\vec q + q \vec p + (\vec p\times\vec q))$.
If we were just to slap ${\bf p}$ and ${\bf a}$ together, we'd get ${\bf p}{\bf a} = (-s\vec p\cdot\vec a,c\vec a + s(\vec p\times\vec a))$, which isn't what we want. We want something else that's also pure imaginary (we want it to look the same as $\bf a$, after all). The usual trick to preserve properties with matrices is to multiply on the other side by a "conjugate," so we'll do this to preserve the "vectorness" and get $\bf p\bf a\bf p^*$. $\bf p^*$ will just be $(c,-\vec ps)$. Basically like a complex conjugate.
We'll end up with
$$\begin{align*}
{\bf p}{\bf a}{\bf p^*} &= (-s\vec p\cdot\vec a,c\vec a + s(\vec p\times\vec a))(c,-\vec ps)
\\&= (-sc\vec p\cdot\vec a,c^2\vec a + sc(\vec p\times\vec a)) + (0,s^2(\vec p\cdot\vec a)\vec p) \\&\quad- (-sc\vec a\cdot\vec p, sc(\vec a\times\vec p)) - (-s^2(\vec p\times\vec a)\cdot\vec p, s^2(\vec p\times\vec a)\times\vec p)
\\&= (0,c^2\vec a + 2sc(\vec p\times\vec a)) + (0,s^2(\vec p\cdot\vec a)\vec p) + (0, s^2\vec p(\vec p\cdot \vec a)-s^2\vec a)
\\&= (0,(\cos\theta)\vec a + (\sin\theta)(\vec p\times\vec a)+(1-\cos\theta)\vec p(\vec p\cdot\vec a))
\end{align*}$$
This is a lot more like you'd expect. It's pure imaginary, and everything reduces down in terms of $\theta$ instead of $\theta/2$. It also looks a lot closer in terms of how you'd write the rotation of $\vec a$ about $\vec p$.
Comment: how did you get that formula for the multiplication of pq? Also, what do you mean by pure imaginary?
Comment: The multiplication is just a vector expression of the quaternion multiplication. There has to be a scalar part, $pq$, and part of the vector-vector multiplication is scalar, that's $\vec p\cdot \vec q$, and then the other part is vector, that's $\vec p\times \vec q$ (this is what all the cross-terms in the quaternion multiplication do for you), and then there's the scalar-vector bits.
Comment: Pure imaginary means that there's no real part. So in your terminology, $w=0$.<|endoftext|>Asp Mvc Core 2 Identity not setting cookie name when using AddAuthentication().AddCookie()
Question: Currently, and this works, I am doing the following to setup cookie authentication in an ASP MVC Core 2 app using Identity:
<code>services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(1);
options.SlidingExpiration = true;
options.LoginPath = "/Account/LogIn";
options.LogoutPath = "/Account/LogOff";
options.Cookie.Name = "MyCookieName";
options.AccessDeniedPath = "/Account/AccessDenied";
});
</code>
I want to add JWT to this app and according to the documentation here, I do that by using something like this (based on the same configuration as above):
<code>services.AddAuthentication()
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(1);
options.SlidingExpiration = true;
options.LoginPath = "/Account/LogIn";
options.LogoutPath = "/Account/LogOff";
options.Cookie.Name = "MyCookieName";
options.AccessDeniedPath = "/Account/AccessDenied";
})
.AddJwtBearer(options =>
{ // options });
</code>
When I do this (even if I leave off the <code>AddJwtBearer</code> chain) the cookie is no longer given the name I specify. The login process still works and I get a cookie but it is named the default Asp cookie name.
I assume that these two methods of setting the options are the same and the <code>ConfigureApplicationCookie</code> is just a shortcut method to the same thing.
Am I missing something?
Thanks,
Brian
Comment: You need to provide the authentication scheme name on your `AddAuthentication()`. Try `AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)`?
Comment: Thanks David. I did that and I get the same result, the cookie is named '.AspNetCore.Identity.Application' rather than 'MyCookieName'.
Comment: hmm weird, coz I had to specify the authentication scheme. If I leave it blank there, I got "No authenticationScheme was specified, and there was no DefaultChallengeScheme found" error. From the cookie name you got '.AspNetCore.Identity.Application', are you using Identity Server 4?
Comment: I am using the regular asp core identity, not identity server.
Answer: Try the following:
<code>services.AddAuthentication()
.AddJwtBearer(options =>
{
// Jwt options.
});
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
});
</code>
Comment: This compiles and I get the correct cookie name. I have not fully tested whether I can connect using a token but I'll assume for now that I will be able to. The docs made me think both auth methods needed to be chained after the AddAuthentication() call. I'll report back after I get it all working in case anyone else comes across this.
Comment: @Brian: Did you make any progress on this?
Comment: Yes, I have this working. It is setup the way the accepted answer is. One other thing I had to do was to add the [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] attribute to the api controllers to force it to use the correct auth scheme.<|endoftext|>Why am I getting error while using the Boost Library in C++?
Question: I am using the c++ boost library in one code to get large numbers in output.
My code is:
<code>#include <iostream>
#include<cmath>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int main()
{
int a;
cout<<"Enter the value for a:";
cin>>a;
for(int x =1;x<=a;x++)
{
int128_t ans = pow(a,2*x)-pow(a,x)+1;
cout<<ans<<endl ;
}
return 0;
}
</code>
But after running this, I am getting following error:
<code>prog.cc: In function 'int main()':
prog.cc:14:43: error: conversion from '__gnu_cxx::__promote_2<int, int, double, double>::__type' {aka 'double'} to non-scalar type 'boost::multiprecision::int128_t' {aka 'boost::multiprecision::number<boost::multiprecision::backends::cpp_int_backend<128, 128, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void> >'} requested
14 | int128_t ans = pow(a,2*x)-pow(a,x)+1;
| ~~~~~~~~~~~~~~~~~~~^~
</code>
What is the reason for such an error?
Comment: `int128_t n = 1.5` should already trigger this, you have a conversions between a float and an integer there.
Comment: @UlrichEckhardt What should I do then?
Comment: `std::pow()` with two integer parameters will give you a `double` value (verify that by checking cppreference.com though!). Start there, you need to find a replacement operation that does not convert to floats but uses e.g. Boost's `int128_t`internally and as returnvalue.
Comment: @UlrichEckhardt I changed pow(a,2*x)-pow(a,x)+1; to int(pow(a,2*x))-int(pow(a,x))+1; but still getting wrong output for a=10
Answer: The reason is that <code>ans</code> type is not <code>int128_t</code>.
After changing <code>ans</code> type to <code>auto</code> compilation works fine:
<code>cat boost_error.cpp
#include <iostream>
#include<cmath>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int main()
{
int a;
cout<<"Enter the value for a:";
cin>>a;
for(int x =1;x<=a;x++)
{
auto ans = pow(a,2*x)-pow(a,x)+1;
cout<<ans<<endl ;
}
return 0;
}
g++ boost_error.cpp
a.out
Enter the value for a:3
7
73
703
g++ --version
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>
Comment: Please take a step back and read [ask]. Point is, nobody here knows what *you* expect as output. Still, the usual approach is to find out whether `pow(a, 2*x)`, `pow(a, x)` or the combination of the three values is the problem. For that, start with a [mcve].
Comment: I am not getting correct output for a=10. What should I do?!
Comment: That approach keeps the double value which defeats the intended use of 128-bit integers.
Comment: @UlrichEckhardt For a=3, I am getting intended output but for a=10, I shows garbage value. Why !?<|endoftext|>How to merge partitions without losing data?
Question: Simplest question to my query is to how 'Merge 2 Partitions' ?
I have 123 GB of free space(unallocated) and a 115 GB Partition (NTFS) with a lot of data (90 GB to be precise)
I want the 123 GB to be added to my 115 GB Partition without any data loss.
I dont have any External HDDs or any sort of memory that could hold upto 90 GB.
Thanks in Advance.
UPDATE :
GPARTED WAS WHAT I NEEDED. I WAS JUST NOT ABLE TO RESEARCH PROPERLY MAYBE DUE TO DROWSINESS or dunno WHAT HAD HAPPENED. ALSO I WAS CONFUSED b/w WINDOWS n UBUNTU. FINALLY N I AM BACK to XP.
ANYWAYS THANKS GUYZ n sorry for the noobness
Comment: Note that you're not actually merging partitions, if your full question is accurate; you're expanding one partition into unallocated space. A partition is, by definition, allocated space; unallocated space is *not* a partition. The preceding may seem pedantic, but I've seen horribly confused discussions that derive from unclear communication on this point.
Comment: Boot from the Ubuntu Live CD/DVD/USB and select Try without installing option. Open Gparted and take a screenshot of the partition structure window. Upload the screenshot to [IDX] and [edit]( [IDX] your question and add the link to the screenshot.
Comment: There is no need to boot from LiveCD in this case. It is a Windows partition. Maybe it is needed to install gparted.
Comment: Did you do any searching of existing questions at all? You should easily have come across gparted.
Comment: possible duplicate of [How to resize partitions?]( [IDX] If unallocated space is beside your NTFS partition, you can extend it using gparted. If not, you better make a screenshot of you gparted window, then some specific directions can be made.
And noone will give 100% guarantee that the data won't be lost. It is recommended to backup your data. But in most cases it works OK. It is your decision.
Based on your information you can do it, but some moving is needed. Boot from Ubuntu LiveCD, start gparted, do not click any partitions, so they do not mount and do:
Click swap partition and disable swap.
Delete /dev/sda5 partition.
Delete /dev/sda3 partition
Extend your /dev/sda2 partition left.
Press apply button. It will take some time.
We removed your swap partition. It is too small to be relevant (165 MB). It is not needed this small anyway.
Now run
<code>sudo gedit /etc/fstab
</code>
And remove the line with the swap partition and save the file.
Now we are done. If you want to have swap, you can leave some space at the end and create a swap partition. Then you will need to add it to /etc/fstab file with UUID, which you can find in gparted same way as it was made before. Size of swap depends on you ram size, and maybe you don't need it at all. Anyway swap should be not less than 1GB. Smaller makes no sense at all.
Comment: Thanks for ur quick reply, n as you said i m still stuck with gparted.
But i cannot post images it requires 10 reputation. So i'll try to describe my gparted window.
1. /dev/sda1 at the topmost containing ubuntu
2. then comes the unallocated 114 GB | [{"idx": "How_does_one_derive_this_rotation_quaternion_formula?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-24927.jsonl"}, {"idx": "Asp_Mvc_Core_2_Identity_not_setting_cookie_name_when_using_AddAuthentication().AddCookie()", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-24927.jsonl"}, {"idx": "Why_am_I_getting_error_while_using_the_Boost_Library_in_C++?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-24927.jsonl"}, {"idx": "How_to_merge_partitions_without_losing_data?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-24927.jsonl"}] |
Find distance between 2D point and line segment start point
Question: This feels like a simple problem but I am bad at algebra.
I'm trying to find the distance between a point and the start of a line segment at an angle parallel to the segment. I will use the distance to interpolate a value along the line.
I also need to know when the points are outside of the line.
A code example would be appreciated, this is my attempt so far using threejs Vector2D but it isn't behaving as expected.
<code>const lineStartOrig = lineStart.clone()
const lineLength = lineStart.distanceTo(lineEnd)
const dotDiff = point2D.sub(lineStart).dot(lineEnd) / lineEnd.dot(lineEnd)
const pointIntersect = dummyLineStart.add(lineEnd)
.multiplyScalar(dotDiff)
.clamp(lineStartOrig, lineEnd)
const value = pointIntersect.distanceTo(lineStartOrig) / lineLength
</code>
Comment: Hi elliott_l. There's always a few ways to do things :), but I would take the following approach: If we define a line AB, and a test point C, (also I'm assuming in your diagram that the dotted lines are perpendicular to the line) 1) calc angle between vectors AC and AB (using dot product) 2) calc angle between vectors CA and CB (again using dot product). If both angles are less than 90 then the point is within our bounds and we can proceed to calculate the intercept and distance.
Answer: In case it's useful to anyone, I used the following functions (unfortunately not in .js, but should illustrate the idea)
To calc angle between two vectors and a test point C:
<code>float calcAngle(QVector2D& A, QVector2D& B, QVector2D& C)
{
QVector2D v1 = B - A;
QVector2D v2 = C - A;
float v1DotV2 = QVector2D::dotProduct(v1, v2);
float magV1TimesMagV2 = v1.length()* v2.length();
float cosTheta = v1DotV2/magV1TimesMagV2;
float theta = qRadiansToDegrees(acosf(cosTheta));
qInfo() << "Theta " << theta;
return theta;
}
</code>
To get the distance and intersect point which I think the OP is after:
<code>float calcDistAlongParallelLineAndIntersectPoint(const QVector2D& A, const QVector2D& B, const QVector2D& C, QVector2D& intersectPoint)
{
QVector2D v1 = B - A;
QVector2D v2 = C - A;
float v1DotV2 = QVector2D::dotProduct(v1, v2);
float magV1TimesMagV2 = v1.length()* v2.length();
float cosTheta = v1DotV2/magV1TimesMagV2;
float dist = v2.length() * cosTheta;
QVector2D intersectingPoint = C - v1*(dist/v1.length());
intersectPoint.setX(intersectingPoint.x());
intersectPoint.setY(intersectingPoint.y());
return dist;
}
</code>
A little check for some random points gives:
Comment: Thanks! I posted the solution I used in the end but your answer pushed me in the right direction
Comment: Glad you sorted it- there's always a few ways to skin a cat :)
Answer: I went in a slightly different direction but Gremto's answer helped a lot and correctly answered the question so I'm marking that as the solution.
I solved the problem using a gradient function that I found here: [IDX] in GLSL but here's my ts version using three.js's Vector2
<code>interface Line2D {
x1: number,
x2: number,
y1: number,
y2: number
}
const dummyLineStart = new Vector2(0, 0)
const dummyLineEnd = new Vector2(0, 0)
const dummyPoint = new Vector2(0, 0)
const dummyLineEndTranslated = new Vector2(0, 0)
//provides an interpolation value between 0 and 1 for a point depending on its
relative parallel position to a line
//points before the start of the line will return 1
function interpolatePointValueAlongLine(
line: Line2D,
pointX: number,
pointY: number
) {
//use reusable vecs to prevent reinitialising class every call
dummyLineStart.set(line.x1, line.y1)
dummyLineEnd.set(line.x2, line.y2)
dummyPoint.set(pointX, pointY)
//code from: [IDX] dummyLineEndTranslated.set(line.x2, line.y2)
.sub(dummyLineStart)
return dummyPoint.sub(dummyLineStart)
.dot(dummyLineEndTranslated) /
dummyLineEndTranslated.dot(dummyLineEndTranslated)
}
</code><|endoftext|>Printing without a spooler
Question: I have a non-root account on a shared server, on which the system administrators do not support printing because of past experience with stalled and runaway jobs. For the same reason, they do not allow installation of a user-land spooler. How can I set up printing without a local queue?
Comment: It may be easier (and more polite) to ask the system administrator nicely if they could set printing up for you. If you have a good reason for it, they should be quite happy to do it, and there's less risk of them breaking it (intentionally or otherwise) later on.
Answer: I would suggest you start by asking your system administrator (or a more experienced user of the system in question) how to print. If it turns out that printing really isn't set up yet, ask them very nicely if they could please look into it.
(I'm assuming, of course, that your question means "Is there a way for a user without root access to set up printing?")
If printing isn't set up and your sysadmin can't find the time to set it up, then presumably the printer you want to print to is on the network -- it would be pointless to connect a printer directly to a server and then not configure the server to print to it -- and so you could presumably install everything necessary to print to it under your home directory, but it would probably be quite a lot of work to build it all, and it would probably be a bit fragile. (Hence, it should be your last resort.)
A better plan might be to set up a VM in which to discover precisely what must be done to make your printer work from a system running the distro and version that the server is running, and ask your administrator if they could please just do those few things?
Answer: Ask your system administrators to install the client parts of CUPS. (You didn't say which Linux you use, so I can't tell you which package names that would be...)
This will allow you printing without local spooling, provided that a remote CUPS print server allows you access:
<code>lpstat -h remote.cups.host -p
</code>
will then return you the names of available printers on <code>remote.cups.host</code>.
<code>lpoptions -h remote.cups.host -l -p printer33
</code>
will show you which printjob options <code>printer33</code> on that host has on offer.
<code>lp -h remote.cups.host -d printer33 -o [your options go here] filename
</code>
will print filename.
You can also create a file <code>~/.cups/client.conf</code> with this content:
<code>ServerName remote.cups.host
</code>
This way all the GUI print dialogs would know where to look for printers and printoptions, and where to spool their jobs to.
Answer: I'm not completely sure what your set up is. You shouldn't need a spooler (or print server e.g. CUPS) on a machine that doesn't have a printer attached (you would simply submit jobs to the actual print server via something like the Internet Printing Protocol), and a machine with a printer attached would be useless without a spooler. Does the server have a printer attached or is it elsewhere on the network?
That said, if your sysadmin has explicitly said not to do something, don't go trying to do things behind their back - that's a great way to get BOFH mode on. You must talk them round. Explain to them why you need to be able to print on that server (I don't mean "to do my job" - something more specific like "I can only get output from program X by printing"). At the moment you're requesting a particular solution (i.e. enable printing). Try to get right down to the root of your problem - what is it that not being able to print is preventing you doing, and why is that bad? If you present this problem to your system administrator, they may be able to suggest a different solution that solves your problem without causing them extra headaches like printing did. Alternatively, it may help them see that printing is indeed the only solution, and cause them to seek out fixes to the problems they had previously.
Answer: A solution that worked for both me and system administrators was remote printing through ssh:
<code>cat localFile.ps |ssh remoteHost "lpr -PfooPrinter"
</code><|endoftext|>What is the word for two or more people realise that something is happening but when no one will openly express it? A competition or problem, perhaps
Question: I am writing about the competition we have with our friends on who looks the best on social media. I am trying to describe like an unidentified fight or competition with our peers. Like, no one is going to acknowledge that we are competing against each other but everyone knows deep down that it kinda is a competition.
The sentence is
Even on days where I feel particularly confident with myself, I scroll on social media to see my classmates looking so beautiful and skinny in bikinis, no roll or stretch marks in sight, and I immediately feel defeated in the _____ fight for bodily supremacy.
Feel free to help alter this sentence in the best way. Just like an unacknowledged competition...?
EDIT: thanks guys for all your input!! very helpful!! <3
Comment: Things which are understood / assumed by conversants without being explicitly stated are ***implicit***. Other relevant words include ***undertone, inference, subtext,...*** and expressions like ***it goes without saying***.
Comment: Unspoken seems apt: ". . . and I immediately felt defeated in the unspoken fight for bodily supremacy."
Answer: "...and I immediately feel defeated in the undeclared competition for bodily supremacy."
undeclared - not announced or openly acknowledged : not stated or decided in an official way : not declared, an undeclared war. (MW)
"There was an undeclared competition among us."
"I also remember an undeclared competition among the students."
Answer: Tacit would suggest something unspoken but inferred or implied in the situation. Oxford English Dictionary, "tacit, adj.":
Not openly expressed or stated, but implied; understood, inferred.
That has the benefit of suggesting something both not openly expressed and understood or felt by the participants.
Even on days where I feel particularly confident with myself, I scroll on social media to see my classmates looking so beautiful and skinny in bikinis, no roll or stretch marks in sight, and I immediately feel defeated in the tacit fight for bodily supremacy.
Answer: You presumably discounted unacknowledged. Starting from your suggestion that the competition is not acknowledged, there is a range of words that may fit the specification. Here are a couple of other un-... words:
undeclared = Not publicly announced, admitted, or acknowledged
Oxford Lexico
unspoken = not stated, although thought, understood, or felt
Cambridge Dictionary
and here are two other possibilities:
tacit = understood without being expressed directly
Cambridge Dictionary
latent = present and capable of emerging or developing but not now visible, obvious, active
Merriam Webstre
To me, latent and undeclared have slight feelings of a possible future admission of the competition. I feel unstated and tacit are nice because they relate more strongly to the mute understanding of the presence of the competition.
Answer: You may not get closer than palpable.
From Vocabulary.com (amended):
palpable [adjective]
The prototypical meaning is that when something is palpable, you can
touch or handle it. However, the word is often used to describe
things that usually can't be handled or touched, such as emotions or
sensations.
You probably won't see palpable used to describe, say, an egg or a
doorknob or a motorcycle. Palpable is usually reserved for situations
in which something invisible becomes so intense that it feels as
though it has substance or weight. Someone who has experienced a death
in the family might say that her grief feels palpable.
Thus
... I immediately feel defeated in the palpable fight/struggle for bodily supremacy.
Comment: I could understand a downvote for answering a question considered to lack reasonable research.Though I doubt 'palpable' would have been easily found. However, I feel this is not the reason here. I'd appreciate explanation as to why this is considered an inappropriate answer, if the downvoter is really seeking the best interests of the site (to promote the understanding and mastery of English). | [{"idx": "Find_distance_between_2D_point_and_line_segment_start_point", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-22248.jsonl"}, {"idx": "Printing_without_a_spooler", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-22248.jsonl"}, {"idx": "What_is_the_word_for_two_or_more_people_realise_that_something_is_happening_but_when_no_one_will_openly_express_it?_A_competition_or_problem,_perhaps", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-22248.jsonl"}] |
use crate::helpers::math::median;
/// tracks open tokens (e.g. `(`) in sequence of occurence.
type CharacterStack = Vec<char>;
/// error thrown if parser fails to parse a line.
struct ParsingError {
token: char,
}
type ParsingResult = Result<CharacterStack, ParsingError>;
fn opener(c: char) -> Option<char> {
match c {
')' => Some('('),
']' => Some('['),
'}' => Some('{'),
'>' => Some('<'),
_ => None,
}
}
/// go through the line char-by-char.
/// opening chars are added to a stack.
/// when closing char is encountered, pop the first item of the stack.
/// if the closing char can be used to close the pair, continue processing the line.
/// if it does not match, throw a `ParsingError` referencing the offending token.
/// once the line completes parsing without errors, return the rest of the stack.
fn parse(line: &str) -> ParsingResult {
let mut stack: CharacterStack = Vec::new();
let mut offending_token: Option<char> = None;
for c in line.chars() {
let opener = opener(c);
if let Some(opener) = opener {
match stack.pop() {
Some(last_open) => {
if opener != last_open {
offending_token = Some(c);
break;
}
}
// case doesn't seem to occur in puzzle input.
None => {
offending_token = Some(c);
break;
}
}
} else {
stack.push(c);
}
}
match offending_token {
Some(token) => Err(ParsingError { token }),
None => Ok(stack),
}
}
pub fn part_one(input: &str) -> u32 {
input
.lines()
.map(|l| match parse(l) {
Ok(_) => 0,
Err(err) => match err.token {
')' => 3,
']' => 57,
'}' => 1197,
'>' => 25137,
_ => 0,
},
})
.sum()
}
pub fn part_two(input: &str) -> u64 {
let mut scores: Vec<u64> = input
.lines()
.filter_map(|l| match parse(l) {
Ok(stack) => {
let score = stack.iter().rev().fold(0, |acc, char| {
acc * 5
+ match char {
'(' => 1,
'[' => 2,
'{' => 3,
'<' => 4,
_ => 0,
}
});
Some(score)
}
Err(_) => None,
})
.collect();
median(&mut scores)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
use aoc::read_file;
let input = read_file("examples", 10);
assert_eq!(part_one(&input), 26397);
}
#[test]
fn test_part_two() {
use aoc::read_file;
let input = read_file("examples", 10);
assert_eq!(part_two(&input), 288957);
}
}<|endoftext|>use actix::prelude::*;
use tokio::sync::{oneshot, RwLock};
use std::sync::Arc;
use std::cell::RefCell;
use super::value::LocalValue;
pub struct Ptr {
owner: u32,
id: u64
}
#[derive(Debug)]
pub enum CallError {
InvalidResponse,
Failed,
Comm,
UnknownMethod,
InvalidArgument
}
#[derive(Message)]
#[rtype(result = "Result<Return, CallError>")]
pub struct Call {
pub method_id: u64,
pub argument: Option<LocalValue>,
}
impl Call {
pub fn new(method_id: u64, argument: Option<LocalValue>) -> Self {
Self {
method_id,
argument
}
}
}
#[derive(Message)]
#[rtype(result = "Result<Return, CallError>")]
pub struct CallMut {
pub method_id: u64,
pub argument: Option<LocalValue>,
}
pub struct Return {
pub result: Option<LocalValue>,
}
pub struct ProxyInfo {
}
#[async_trait::async_trait]
pub trait Object: std::fmt::Debug + Send {
async fn call(&self, call: Call) -> Result<Return, CallError>;
async fn call_mut(&mut self, call_mut: CallMut) -> Result<Return, CallError>;
fn proxy_info(&self) -> Option<ProxyInfo>;
}
#[derive(Message)]
#[rtype(result = "Option<ProxyInfo>")]
pub struct GetProxyInfo {
}
pub struct ObjectActor {
backing: Arc<RwLock<dyn Object + Send + Sync + 'static>>,
}
impl Actor for ObjectActor {
type Context = Context<Self>;
}
impl ObjectActor {
pub fn new<O: Object + Send + Sync + 'static>(backing: O) -> Self {
Self {
backing: Arc::new(RwLock::new(backing))
}
}
}
impl Handler<Call> for ObjectActor {
type Result = ResponseFuture<Result<Return, CallError>>;
fn handle(&mut self, msg: Call, _: &mut Context<Self>) -> Self::Result {
let backing = self.backing.clone();
Box::pin(async move {
backing.read().await.call(msg).await
})
}
}
impl Handler<CallMut> for ObjectActor {
type Result = ResponseFuture<Result<Return, CallError>>;
fn handle(&mut self, msg: CallMut, _: &mut Context<Self>) -> Self::Result {
let backing = self.backing.clone();
Box::pin(async move {
backing.write().await.call_mut(msg).await
})
}
}
impl Handler<GetProxyInfo> for ObjectActor {
type Result = ResponseFuture<Option<ProxyInfo>>;
fn handle(&mut self, _: GetProxyInfo, _: &mut Context<Self>) -> Self::Result {
let backing = self.backing.clone();
Box::pin(async move {
backing.read().await.proxy_info()
})
}
}
#[async_trait::async_trait]
pub trait ObjectActorHelpers {
async fn call(&self, call: Call) -> Result<Return, CallError>;
async fn call_mut(&self, call: CallMut) -> Result<Return, CallError>;
async fn proxy_info(&self) -> Option<ProxyInfo>;
}
#[async_trait::async_trait]
impl ObjectActorHelpers for Addr<ObjectActor> {
async fn call(&self, call: Call) -> Result<Return, CallError> {
self.send(call).await.unwrap()
}
async fn call_mut(&self, call: CallMut) -> Result<Return, CallError> {
self.send(call).await.unwrap()
}
async fn proxy_info(&self) -> Option<ProxyInfo> {
self.send(GetProxyInfo {}).await.unwrap()
}
}
use std::collections::HashSet;
pub struct Access<T> {
users: HashSet<u64>,
value: T
}<|endoftext|>use crate::codec::{ParseFail, ParseResult, ParseValue};
pub const MAX: u32 = 0x3F_FF_FF_FF;
/// Returns whether the value is encodable into a varint or not.
pub fn is_valid(n: u32) -> Result<(), ()> {
if n > MAX {
Err(())
} else {
Ok(())
}
}
/// Calculate the size in bytes of the value encoded as a varint.
///
/// # Safety
/// Only call this on u32 that are less than 0x3F_FF_FF_FF.
///
/// Calling this on a large integer will return a size of 4 which
/// is technically incorrect because the integer is non-encodable.
pub unsafe fn size(n: u32) -> u8 {
if n <= 0x3F {
1
} else if n <= 0x3F_FF {
2
} else if n <= 0x3F_FF_FF {
3
} else {
4
}
}
/// Encode the value into a varint.
///
/// # Safety
/// Only call this on u32 that are less than 0x3F_FF_FF_FF.
///
/// Calling this on a large integer will return an unpredictable
/// result (it won't crash).
pub unsafe fn encode(n: u32, out: &mut [u8]) -> u8 {
let u8_size = size(n);
let size = u8_size as usize;
for (i, byte) in out.iter_mut().enumerate().take(size) {
*byte = ((n >> ((size - 1 - i) * 8)) & 0xFF) as u8;
}
out[0] |= ((size - 1) as u8) << 6;
u8_size
}
/// Decode a byte array as a varint.
pub fn decode(out: &[u8]) -> ParseResult<u32> {
if out.is_empty() {
return Err(ParseFail::MissingBytes(1));
}
let size = ((out[0] >> 6) + 1) as usize;
if out.len() < size as usize {
return Err(ParseFail::MissingBytes(size as usize - out.len()));
}
let mut ret = (out[0] & 0x3F) as u32;
for byte in out.iter().take(size).skip(1) {
ret = (ret << 8) + *byte as u32;
}
Ok(ParseValue { value: ret, size })
}
#[cfg(test)]
mod test {
use super::*;
use hex_literal::hex;
#[test]
fn test_is_valid() {
assert_eq!(is_valid(0x3F_FF_FF_FF), Ok(()));
assert_eq!(is_valid(0x40_00_00_00), Err(()));
}
#[test]
fn test_unsafe_size() {
unsafe {
assert_eq!(size(0x00), 1);
assert_eq!(size(0x3F), 1);
assert_eq!(size(0x3F_FF), 2);
assert_eq!(size(0x3F_FF_FF), 3);
assert_eq!(size(0x3F_FF_FF_FF), 4);
}
}
#[test]
fn test_encode() {
fn test(n: u32, truth: &[u8]) {
let mut encoded = vec![0u8; truth.len()];
assert_eq!(unsafe { encode(n, &mut encoded[..]) }, truth.len() as u8);
assert_eq!(*truth, encoded[..]);
}
test(0x00, &[0]);
test(0x3F, &hex!("3F"));
test(0x3F_FF, &hex!("7F FF"));
test(0x3F_FF_FF, &hex!("BF FF FF"));
test(0x3F_FF_FF_FF, &hex!("FF FF FF FF"));
}
#[test]
fn test_decode() {
fn test_ok(data: &[u8], value: u32, size: usize) {
assert_eq!(decode(data), Ok(ParseValue { value, size: size }),);
}
test_ok(&[0], 0x00, 1);
test_ok(&hex!("3F"), 0x3F, 1);
test_ok(&hex!("7F FF"), 0x3F_FF, 2);
test_ok(&hex!("BF FF FF"), 0x3F_FF_FF, 3);
test_ok(&hex!("FF FF FF FF"), 0x3F_FF_FF_FF, 4);
}
}<|endoftext|>use std::sync::Arc;
use common_datavalues::DataField;
use common_exception::ErrorCode;
use common_exception::Result;
use common_infallible::RwLock;
use indexmap::IndexMap;
use lazy_static::lazy_static;
use crate::aggregator::AggregatorFunction;
use crate::AggregateFunction;
pub struct AggregateFunctionFactory;
pub type FactoryFunc =
fn(name: &str, arguments: Vec<DataField>) -> Result<Box<dyn AggregateFunction>>;
pub type FactoryCombinatorFunc = fn(
name: &str,
arguments: Vec<DataField>,
nested_func: FactoryFunc,
) -> Result<Box<dyn AggregateFunction>>;
pub type FactoryFuncRef = Arc<RwLock<IndexMap<&'static str, FactoryFunc>>>;
pub type FactoryCombinatorFuncRef = Arc<RwLock<IndexMap<&'static str, FactoryCombinatorFunc>>>;
lazy_static! {
static ref FACTORY: FactoryFuncRef = {
let map: FactoryFuncRef = Arc::new(RwLock::new(IndexMap::new()));
AggregatorFunction::register(map.clone()).unwrap();
map
};
static ref COMBINATOR_FACTORY: FactoryCombinatorFuncRef = {
let map: FactoryCombinatorFuncRef = Arc::new(RwLock::new(IndexMap::new()));
AggregatorFunction::register_combinator(map.clone()).unwrap();
map
};
}
impl AggregateFunctionFactory {
pub fn get(name: &str, arguments: Vec<DataField>) -> Result<Box<dyn AggregateFunction>> {
let not_found_error = || -> ErrorCode {
ErrorCode::UnknownAggregateFunction(format!("Unsupported AggregateFunction: {}", name))
};
let lower_name = name.to_lowercase();
let map = FACTORY.read();
match map.get(lower_name.as_str()) {
Some(creator) => (creator)(name, arguments),
None => {
// find suffix
let combinator = COMBINATOR_FACTORY.read();
if let Some((&k, &combinator_creator)) =
combinator.iter().find(|(&k, _)| lower_name.ends_with(k))
{
let nested_name = lower_name.strip_suffix(k).ok_or_else(not_found_error)?;
return map
.get(nested_name)
.map(|nested_creator| {
combinator_creator(nested_name, arguments, *nested_creator)
})
.unwrap_or_else(|| Err(not_found_error()));
}
Err(not_found_error())
}
}
}
pub fn check(name: &str) -> bool {
let map = FACTORY.read();
let lower_name = name.to_lowercase();
if map.contains_key(lower_name.as_str()) {
return true;
}
// find suffix
let combinator = COMBINATOR_FACTORY.read();
for (k, _) in combinator.iter() {
if let Some(nested_name) = lower_name.strip_suffix(k) {
if map.contains_key(nested_name) {
return true;
}
}
}
false
}
pub fn registered_names() -> Vec<String> {
let map = FACTORY.read();
map.keys().into_iter().map(|x| x.to_string()).collect()
}
} | [{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-13593.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-13593.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-13593.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-13593.jsonl"}] |
import htmlPy
import json
from sample_app import app as htmlPy_app
class ClassName(htmlPy.Object):
# GUI callable functions have to be inside a class.
# The class should be inherited from htmlPy.Object.
def __init__(self):
super(ClassName. self).__init__()
# Initialize the class here, if required.
return
@htmlPy.Slot()
def function_name(self):
# This is the function exposed to GUI events.
# You can change app HTML from here.
# Or, you can do pretty much any python from here.
#
# NOTE: @htmlPy.Slot decorater needs argument and return data-types.
# Refer to API documentation.
return
@htmlPy.Slot(str, result=str)
def form_function_name(self, json_data):
# @htmlPy.Slot(arg1_type, arg2_type, ..., result=return_type)
# This function can be used for GUI forms.
#
form_data = json.loads(json_data)
return json.dumps(form_data)
@htmlPy.Slot()
def javascript_function(self):
# Any function decorated with @htmlPy.Slot decorater can be called
# using javascript in GUI
return
## You have to bind the class instance to the AppGUI instance to be
## callable from GUI
htmlPy_app.bind(ClassName())<|endoftext|>class NiiDataset(Dataset):
def __init__(self, img_path, tgt_path):
# load all nii handle in a list
img_dir = [i for i in os.listdir(img_path) if i[-3:] == "nii"]
tgt_dir = [i for i in os.listdir(tgt_path) if i[-3:] == "nii"]
self.images_list = []
self.transforms = transforms.Normalize((0.5,), (0.5,))
for image_path in img_dir:
tens = self.to_tensor(img_path + '/' + image_path)
self.images_list.append(tens[:,:,j][None, ...])
self.target_list = []
for image_path in tgt_dir:
tens = self.to_tensor(tgt_path + '/' + image_path)
self.target_list.append(tens[:,:,j][None, ...])
print(self.images_list[0].shape,len(self.images_list))
print(self.target_list[0].shape,len(self.target_list))
def __len__(self):
return len(self.images_list)
classes = torch.cat([self.target_list[idx] == 0, self.target_list[idx] == 1, self.target_list[idx] == 2], 0)
return self.transforms((self.images_list[idx], classes))
def to_tensor(self, pth):
return torch.from_numpy(np.asarray(nib.load(pth).dataobj))<|endoftext|>"""Algorithms for calculating the optimization cost for a single request."""
from serving_dataclasses import SessionMetrics
class CostCalculator(ABC):
"""Defines the interface for cost calculating algorithms."""
@abstractmethod
def set_session_cost(session_metrics: SessionMetrics) -> None:
"""Fill in the cost field for a SessionMetrics object based on the other metrics."""
pass
class LESumOfSquaresCost(ABC):
"""Defines the per-request cost as the weighted sum of their squared latency (L) and error rate (E)."""
"""Store the coefficient for weighting the latency in the cost function."""
super().__init__()
"""Set the cost to the weighted sum their squared latency and error rate."""
session_metrics.cost = self.latency_weight * session_metrics.latency**2 + (1 - session_metrics.accuracy)**2
class LESumCost(ABC):
"""Defines the per-request cost as the weighted sum of their latency (L) and error rate (E)."""
"""Store the coefficient for weighting the latency in the cost function."""
super().__init__()
"""Set the cost to the weighted sum their squared latency and error rate."""
session_metrics.cost = self.latency_weight * session_metrics.latency + (1 - session_metrics.accuracy)<|endoftext|>"""
Verifies libraries (in identical-names) are properly handeled by xcode.
The names for all libraries participating in this build are:
libtestlib.a - identical-name/testlib
libtestlib.a - identical-name/proxy/testlib
libproxy.a - identical-name/proxy
The first two libs produce a hash collision in Xcode when Gyp is executed,
because they have the same name and would be copied to the same directory with
Xcode default settings.
For this scenario to work one needs to change the Xcode variables SYMROOT and
CONFIGURATION_BUILD_DIR. Setting these to per-lib-unique directories, avoids
copying the libs into the same directory.
The test consists of two steps. The first one verifies that by setting both
vars, there is no hash collision anymore during Gyp execution and that the libs
can actually be be built. The second one verifies that there is still a hash
collision if the vars are not set and thus the current behavior is preserved.
"""
import TestGyp
import sys
if sys.platform == 'darwin':
test = TestGyp.TestGyp(formats=['xcode'])
test.run_gyp('test.gyp', chdir='identical-name')
test.build('test.gyp', test.ALL, chdir='identical-name')
test.run_gyp('test-should-fail.gyp', chdir='identical-name')
test.built_file_must_not_exist('test-should-fail.xcodeproj')
test.pass_test()<|endoftext|>import boto3
import logging
import os
import json
try:
from alerta.plugins import app # alerta >= 5.0
except ImportError:
from alerta.app import app # alerta < 5.0
from alerta.plugins import PluginBase
LOG = logging.getLogger('alerta.plugins.sns')
DEFAULT_AWS_REGION = 'eu-west-1'
AWS_REGION = os.environ.get('AWS_REGION') or app.config.get(
'AWS_REGION', DEFAULT_AWS_REGION)
AWS_SNS_TOPIC_ARN = os.environ.get('AWS_SNS_TOPIC_ARN') or app.config.get(
'AWS_SNS_TOPIC_ARN', "")
class SnsTopicPublisher(PluginBase):
self.client = boto3.client('sns')
super(SnsTopicPublisher, self).__init__(name)
LOG.info('Configured SNS publisher on topic "%s"', AWS_SNS_TOPIC_ARN)
def pre_receive(self, alert):
return alert
def post_receive(self, alert):
LOG.info('Sending message %s to SNS topic "%s"',
alert.get_id(), AWS_SNS_TOPIC_ARN)
LOG.debug('Message: %s', alert.get_body())
response = self.client.publish(
TopicArn=AWS_SNS_TOPIC_ARN, Message=json.dumps(
alert.get_body(), default=str),
MessageGroupId='alertas', MessageDeduplicationId=alert.get_body()['id'])
LOG.debug('Response: %s', response)
def status_change(self, alert, status, text):
return<|endoftext|>#!/usr/bin/env python
# cartesian joystick waypoint control for quadrotor
import roslib
#roslib.load_manifest('quad_control')
import rospy
import copy
import math
from acl_msgs.msg import ViconState
from gazebo_msgs.msg import ModelState
class QuadJoy:
def __init__(self):
self.gazebo_state = ModelState()
self.pubState = rospy.Publisher('/gazebo/set_model_state', ModelState, queue_size=1)
name = rospy.get_namespace()
def poseCB(self, data):
self.gazebo_state.model_name = self.name
self.gazebo_state.pose = data.pose
self.gazebo_state.twist = data.twist
self.gazebo_state.reference_frame = "world"
self.pubState.publish(self.gazebo_state)
def startNode():
c = QuadJoy()
rospy.Subscriber("vicon", ViconState, c.poseCB)
rospy.spin()
if __name__ == '__main__':
ns = rospy.get_namespace()
try:
rospy.init_node('relay')
if str(ns) == '/':
rospy.logfatal("Need to specify namespace as vehicle name.")
rospy.logfatal("This is tyipcally accomplished in a launch file.")
rospy.logfatal("Command line: ROS_NAMESPACE=mQ01 $ rosrun quad_control joy.py")
else:
print "Starting joystick teleop node for: " + ns
startNode()
pass<|endoftext|>"""
A feature_collection is a set of features that share the same
metadata fields. OTUs would be an example of features that all have the
same metadata for things like tornado_run, species name, etc.
The features in in a feature_collection are normally loaded into the
database (as feature_variables) at the same time as the
feature_collection entry itself.
"""
from nest_py.core.data_types.tablelike_schema import TablelikeSchema
from nest_py.core.data_types.tablelike_entry import TablelikeEntry
COLLECTION_NAME = 'feature_collections'
def generate_schema():
schema = TablelikeSchema(COLLECTION_NAME)
schema.add_categoric_attribute('collection_name')
#while this is no good for querying, will probably be
#important once users are uploading arbitrary spreadsheets
schema.add_categoric_attribute('description')
#an object-blob of a schema. The attributes of the schema
#are the metadata attributes that all feature_variables in
#the feature_collection will contain. E.g. for the
#'otus' feature_collection, each feature_variable is an otu
#and the metadata_schema will have things like 'tornado_run_id'
#and 'otu_number' and maybe 'short_taxa_name'
schema.add_json_attribute('metadata_schema')
schema.add_foreignid_attribute('wix_run_id')
return schema<|endoftext|>from talon.voice import Key, Context
ctx = Context("smartgit", bundle="com.syntevo.smartgit")
ctx.keymap(
{
"commit [changes]": Key("cmd-k"),
"undo last commit": Key("shift-cmd-k"),
"pull it": Key("cmd-p"),
"push it": Key("cmd-u"),
"show log": Key("cmd-l"),
"[(edit | change)] current commit message": Key("cmd-shift-6"),
"(edit | change) commit message": Key("f2"),
"(edit | change) last commit message": Key("shift-f2"),
"check out branch": Key("cmd-g"),
"add branch": Key("f7"),
"add tag": Key("shift-f7"),
"stage": Key("cmd-t"),
"filter files": Key("cmd-f"),
"stash all": Key("cmd-s"),
"apply stash": Key("shift-cmd-s"),
"unstage": Key("shift-cmd-t"),
"undo last commit": Key("shift-cmd-k"),
"(show | hide) unchanged files": Key("cmd-1"),
"(show | hide) unversioned files": Key("cmd-2"),
"(show | hide) ignored files": Key("cmd-3"),
"(show | hide) staged files": Key("cmd-4"),
"next change": Key("f6"),
"(previous | preev) change": Key("shift-f6"),
"toggle compact changes": Key("cmd-."),
"normal mode": Key("alt-cmd-1"),
"review mode": Key("alt-cmd-2"),
"clear output": Key("cmd-backspace"),
}
) | [{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9505.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9505.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9505.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9505.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9505.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9505.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9505.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9505.jsonl"}] |
/**
* Commandline tool for determining latency.
*/
import "source-map-support/register";
import * as tls from "tls";
import * as yargs from "yargs";
import { Headers, Message } from "./message";
import MClient from "./nodeclient";
import { replaceKeyFiles } from "./tlsHelpers";
const usage = [
"Sends a message to the given node, waits for an answer, then sends the next etc.",
"Prints the round-trip time for each message.",
"",
"Make sure you have the `test` node enabled in mhub-server, or provide your own",
"routing to respond with `ping:response` to each `ping:request`",
].join("\n");
function die(fmt: string, ...args: any[]): never {
// tslint:disable-next-line:no-console
console.error(fmt, ...args);
return process.exit(1);
}
const argv = yargs
.usage(usage)
.help("help")
// tslint:disable-next-line:no-require-imports
.version()
.alias("v", "version")
.option("socket", {
type: "string",
alias: "s",
description: "WebSocket to connect to",
default: "localhost:13900",
})
.option("node", {
type: "string",
alias: "n",
description: "Node to subscribe/publish to",
default: "ping",
})
.option("data", {
type: "string",
alias: "d",
description:
'Optional message data as JSON object, e.g. \'"a string"\' or \'{ "foo": "bar" }\'',
})
.option("headers", {
type: "string",
alias: "h",
description:
'Optional message headers as JSON object, e.g. \'{ "my-header": "foo" }\'',
})
.option("count", {
type: "number",
alias: "c",
description: "Number of pings to send",
default: 10,
})
.option("insecure", {
type: "boolean",
description:
"Disable server certificate validation, useful for testing using self-signed certificates",
})
.option("key", {
type: "string",
description: "Filename of TLS private key (in PEM format)",
})
.option("cert", {
type: "string",
description: "Filename of TLS certificate (in PEM format)",
})
.option("ca", {
type: "string",
description: "Filename of TLS certificate authority (in PEM format)",
})
.option("passphrase", {
type: "string",
description: "Passphrase for private key",
})
.option("pfx", {
type: "string",
description:
"Filename of TLS private key, certificate and CA certificates " +
"(in PFX or PKCS12 format). Mutually exclusive with --key, --cert and --ca.",
})
.option("crl", {
type: "string",
description: "Filename of certificate revocation list (in PEM format)",
})
.option("ciphers", {
type: "string",
description: "List of ciphers to use or exclude, separated by :",
})
.option("username", {
type: "string",
alias: "U",
description: "Username",
})
.option("password", {
type: "string",
alias: "P",
description:
"Password. Note: sent in plain-text, so only use on secure connection. " +
"Also note it may appear in e.g. `ps` output.",
})
.strict().argv;
function createClient(): Promise<MClient> {
const tlsOptions: tls.TlsOptions = {};
tlsOptions.pfx = argv.pfx;
tlsOptions.key = argv.key;
tlsOptions.passphrase = argv.passphrase;
tlsOptions.cert = argv.cert;
tlsOptions.ca = argv.ca;
tlsOptions.crl = argv.crl;
tlsOptions.ciphers = argv.ciphers;
tlsOptions.rejectUnauthorized = !argv.insecure;
replaceKeyFiles(tlsOptions, process.cwd());
const client = new MClient(argv.socket, tlsOptions);
client.on("error", (e: Error): void => {
die("Client error:", e);
});
return client
.connect()
.then(() => {
if (argv.username) {
return client.login(argv.username, argv.password || "");
}
})
.then(() => client);
}
let data: any;
try {
data = argv.data && JSON.parse(argv.data);
} catch (e) {
// tslint:disable-next-line:no-console
console.error("Error parsing message data as JSON: " + e.message);
die(
"Hint: if you're passing a string, make sure to put double-quotes around it, " +
"and escape these quotes for your shell with single-quotes, e.g.: '\"my string\"'"
);
}
let headers: Headers;
try {
headers = argv.headers && JSON.parse(argv.headers);
} catch (e) {
die("Error parsing message headers as JSON: " + e.message);
}
const pingCount = argv.count;
/**
* High-res timestamp in milliseconds.
*/
function now(): number {
const hrTime = process.hrtime();
return hrTime[0] * 1000000000 + hrTime[1] / 1000000;
}
createClient()
.then(async (client) => {
async function ping(): Promise<void> {
const response = new Promise<void>((resolve) => {
client.once("message", (msg: Message): void => {
const reply = JSON.stringify(msg.data);
if (argv.data === reply) {
resolve();
}
});
});
const request = client.publish(
argv.node,
"ping:request",
data,
headers
);
let timeoutTimer: NodeJS.Timer;
const timeout = new Promise((_, reject) => {
timeoutTimer = setTimeout(
() => reject(new Error("timeout")),
1000
);
});
try {
await Promise.race([Promise.all([request, response]), timeout]);
} finally {
clearTimeout(timeoutTimer!);
}
}
client.subscribe(argv.node, "ping:response");
for (let i = 0; i < pingCount; i++) {
const start = now();
try {
await ping();
console.log(`pong ${i}: ${(now() - start).toFixed(3)}ms`); // tslint:disable-line:no-console
} catch (err) {
console.warn(err.message || `${err}`); // tslint:disable-line:no-console
}
}
return client.close();
})
.catch(die);<|endoftext|>import chai from "chai";
import chaiAsPromised from "chai-as-promised";
chai.use(chaiAsPromised);
import debugModule from "debug";
const should = chai.should();
const debug = debugModule("azure:eph:negative-spec");
import dotenv from "dotenv";
import {
EventPosition,
OnReceivedError,
PartitionContext,
EventData,
OnReceivedMessage,
EventProcessorHost
} from "../src";
dotenv.config();
describe("negative", function(): void {
before("validate environment", function(): void {
should.exist(
process.env.STORAGE_CONNECTION_STRING,
"define STORAGE_CONNECTION_STRING in your environment before running integration tests."
);
should.exist(
process.env.EVENTHUB_CONNECTION_STRING,
"define EVENTHUB_CONNECTION_STRING in your environment before running integration tests."
);
should.exist(
process.env.EVENTHUB_NAME,
"define EVENTHUB_NAME in your environment before running integration tests."
);
});
const ehConnString = process.env.EVENTHUB_CONNECTION_STRING;
const storageConnString = process.env.STORAGE_CONNECTION_STRING;
const hubName = process.env.EVENTHUB_NAME;
const hostName = EventProcessorHost.createHostName();
let host: EventProcessorHost;
it("should fail when trying to start an EPH that is already started.", function(done: Mocha.Done): void {
const test = async () => {
host = EventProcessorHost.createFromConnectionString(
hostName,
storageConnString!,
EventProcessorHost.createHostName("tc"),
ehConnString!,
{
eventHubPath: hubName!,
initialOffset: EventPosition.fromEnqueuedTime(Date.now())
}
);
const onMessage: OnReceivedMessage = (context: PartitionContext, data: EventData) => {
debug(">>> [%s] Rx message from '%s': '%O'", hostName, context.partitionId, data);
};
const onError: OnReceivedError = (err) => {
debug("An error occurred while receiving the message: %O", err);
throw err;
};
await host.start(onMessage, onError);
try {
debug(">>> [%s] Trying to start second time.", hostName);
await host.start(onMessage, onError);
throw new Error("The second call to start() should have failed.");
} catch (err) {
err.message.should.match(/A partition manager cannot be started multiple times/gi);
} finally {
await host.stop();
should.equal(host["_context"]["partitionManager"]["_isCancelRequested"], true);
}
};
test()
.then(() => {
done();
})
.catch((err) => {
done(err);
});
});
it("should fail when the eventhub name is incorrect.", function(done: Mocha.Done): void {
host = EventProcessorHost.createFromConnectionString(
hostName,
storageConnString!,
EventProcessorHost.createHostName("tc"),
ehConnString!,
{
eventHubPath: "HeloooooooFooooooo",
initialOffset: EventPosition.fromEnqueuedTime(Date.now())
}
);
const onMessage: OnReceivedMessage = (context: PartitionContext, data: EventData) => {
debug(">>> [%s] Rx message from '%s': '%O'", hostName, context.partitionId, data);
};
const onError: OnReceivedError = (err) => {
debug("An error occurred while receiving the message: %O", err);
throw err;
};
host
.start(onMessage, onError)
.then(() => {
return Promise.reject(new Error("This statement should not have executed."));
})
.catch((err) => {
debug(">>>>>>> %s", err.action);
err.action.should.equal("Getting PartitionIds");
done();
});
});
it("should fail when the eventhub namesapce is incorrect.", function(done: Mocha.Done): void {
host = EventProcessorHost.createFromConnectionString(
hostName,
storageConnString!,
EventProcessorHost.createHostName("tc"),
"Endpoint=sb://HelooFooo.servicebus.windows.net/;SharedAccessKeyName=Foo;SharedAccessKey=Bar",
{
eventHubPath: hubName!,
initialOffset: EventPosition.fromEnqueuedTime(Date.now())
}
);
const onMessage: OnReceivedMessage = (context: PartitionContext, data: EventData) => {
debug(">>> [%s] Rx message from '%s': '%O'", hostName, context.partitionId, data);
};
const onError: OnReceivedError = (err) => {
debug("An error occurred while receiving the message: %O", err);
throw err;
};
host
.start(onMessage, onError)
.then(() => {
return Promise.reject(new Error("This statement should not have executed."));
})
.catch((err) => {
debug(">>>>>>> %s", err.action);
err.action.should.equal("Getting PartitionIds");
done();
});
});
it("should fail when the storage connection string is incorrect.", function(done: Mocha.Done): void {
try {
host = EventProcessorHost.createFromConnectionString(
hostName,
"Hello World"!,
EventProcessorHost.createHostName("tc"),
ehConnString!,
{
eventHubPath: hubName!,
initialOffset: EventPosition.fromEnqueuedTime(Date.now()),
consumerGroup: "HelloWorld"
}
);
done(new Error("creating eph should have failed."));
} catch (err) {
should.exist(err);
err.message.should.match(/Connection strings must be of the form/gi);
done();
}
});
}); | [{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18338.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18338.jsonl"}] |
Android 6.0 Marshmallow : Weird error with fragment animation
Question: One of my apps in the app store works perfectly fine with Android 5.0, but since today I have my device upgraded to 6.0 I get strange errors. I narrowed it down to the fragment transition animations.
<code>ftrans.setCustomAnimations(inAnim, outAnim, inAnim, outAnim);
</code>
Without this line, my app also works fine on 6.0, with it I get this error :
<code>10-14 14:36:51.016 23750-23820/? A/libc: Fatal signal 7 (SIGBUS), code 1, fault addr 0xb1 in tid 23820 (hwuiTask1)
10-14 14:36:51.118 200-200/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
10-14 14:36:51.118 200-200/? A/DEBUG: Build fingerprint: 'google/hammerhead/hammerhead:6.0/MRA58K/2256973:user/release-keys'
10-14 14:36:51.118 200-200/? A/DEBUG: Revision: '0'
10-14 14:36:51.118 200-200/? A/DEBUG: ABI: 'arm'
10-14 14:36:51.118 200-200/? A/DEBUG: pid: 23750, tid: 23820, name: hwuiTask1 >>> com.xxx.xxx <<<
10-14 14:36:51.118 200-200/? A/DEBUG: signal 7 (SIGBUS), code 1 (BUS_ADRALN), fault addr 0xb1
10-14 14:36:51.110 200-200/? W/debuggerd: type=1400 audit(0.0:54): avc: denied { search } for name="com.xxx.xxx" dev="mmcblk0p28" ino=1499496 scontext=u:r:debuggerd:s0 tcontext=u:object_r:app_data_file:s0:c512,c768 tclass=dir permissive=0
10-14 14:36:51.136 200-200/? A/DEBUG: r0 00000073 r1 96efeed8 r2 00000002 r3 00000005
10-14 14:36:51.136 200-200/? A/DEBUG: r4 00000006 r5 00000073 r6 00000000 r7 96eff1e8
10-14 14:36:51.136 200-200/? A/DEBUG: r8 00000005 r9 96efebd8 sl 96eff470 fp 00000016
10-14 14:36:51.136 200-200/? A/DEBUG: ip 000000b1 sp 96efebd8 lr 00000006 pc b5d887d2 cpsr 300f0030
10-14 14:36:51.142 200-200/? A/DEBUG: #00 pc 0005a7d2 /system/lib/libhwui.so
10-14 14:36:51.142 200-200/? A/DEBUG: #01 pc 0005b8a3 /system/lib/libhwui.so
10-14 14:36:51.142 200-200/? A/DEBUG: #02 pc 00055e0b /system/lib/libhwui.so
10-14 14:36:51.142 200-200/? A/DEBUG: #03 pc 0005c9fd /system/lib/libhwui.so
10-14 14:36:51.142 200-200/? A/DEBUG: #04 pc 0001fd93 /system/lib/libhwui.so
10-14 14:36:51.142 200-200/? A/DEBUG: #05 pc 0001006d /system/lib/libutils.so (android::Thread::_threadLoop(void*)+112)
10-14 14:36:51.142 200-200/? A/DEBUG: #06 pc 0005ecd3 /system/lib/libandroid_runtime.so (android::AndroidRuntime::javaThreadShell(void*)+70)
10-14 14:36:51.142 200-200/? A/DEBUG: #07 pc 0003f3e7 /system/lib/libc.so (__pthread_start(void*)+30)
10-14 14:36:51.142 200-200/? A/DEBUG: #08 pc 00019b43 /system/lib/libc.so (__start_thread+6)
10-14 14:36:51.500 200-200/? W/debuggerd: type=1400 audit(0.0:55): avc: denied { read } for name="kgsl-3d0" dev="tmpfs" ino=5756 scontext=u:r:debuggerd:s0 tcontext=u:object_r:gpu_device:s0 tclass=chr_file permissive=0
10-14 14:36:52.189 799-25288/? W/ActivityManager: Force finishing activity com.xxx.xxx/.MainActivity
10-14 14:36:52.190 200-200/? E/DEBUG: AM write failed: Broken pipe
10-14 14:36:52.190 799-815/? I/BootReceiver: Copying /data/tombstones/tombstone_01 to DropBox (SYSTEM_TOMBSTONE)
10-14 14:36:52.257 799-901/? I/OpenGLRenderer: Initialized EGL, version 1.4
10-14 14:36:52.286 799-4576/? D/GraphicsStats: Buffer count: 5
10-14 14:36:52.286 799-4576/? I/WindowState: WIN DEATH: Window{d660a8a u0 com.xxx.xxx/com.xxx.xxx.MainActivity}
10-14 14:36:52.321 799-808/? I/art: Background partial concurrent mark sweep GC freed 71211(4MB) AllocSpace objects, 18(1032KB) LOS objects, 33% free, 32MB/48MB, paused 3.554ms total 114.532ms
10-14 14:36:52.372 214-214/? I/Zygote: Process 23750 exited due to signal (7)
10-14 14:36:52.379 799-1413/? I/ActivityManager: Process com.xxx.xxx (pid 23750) has died
10-14 14:36:52.386 799-1418/? I/ActivityManager: Killing 23069:com.android.documentsui/u0a35 (adj 15): empty #17
10-14 14:36:52.864 799-817/? W/WindowAnimator: Failed to dispatch window animation state change.
10-14 14:36:52.864 799-817/? W/WindowAnimator: android.os.DeadObjectException
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.os.BinderProxy.transactNative(Native Method)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.os.BinderProxy.transact(Binder.java:503)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.view.IWindow$Stub$Proxy.onAnimationStopped(IWindow.java:534)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at com.android.server.wm.WindowAnimator.updateWindowsLocked(WindowAnimator.java:286)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at com.android.server.wm.WindowAnimator.animateLocked(WindowAnimator.java:678)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at com.android.server.wm.WindowAnimator.-wrap0(WindowAnimator.java)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at com.android.server.wm.WindowAnimator$1.doFrame(WindowAnimator.java:123)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.view.Choreographer$CallbackRecord.run(Choreographer.java:856)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.view.Choreographer.doCallbacks(Choreographer.java:670)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.view.Choreographer.doFrame(Choreographer.java:603)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.os.Handler.handleCallback(Handler.java:739)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.os.Handler.dispatchMessage(Handler.java:95)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.os.Looper.loop(Looper.java:148)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at android.os.HandlerThread.run(HandlerThread.java:61)
10-14 14:36:52.864 799-817/? W/WindowAnimator: at com.android.server.ServiceThread.run(ServiceThread.java:46)
10-14 14:36:52.983 1889-2087/? W/OpenGLRenderer: Incorrectly called buildLayer on View: ShortcutAndWidgetContainer, destroying layer...
10-14 14:36:52.983 1889-2087/? W/OpenGLRenderer: Incorrectly called buildLayer on View: ShortcutAndWidgetContainer, destroying layer...
</code>
The "in" animation I use looks like this :
<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android=" [IDX] android:fromAlpha="0" android:toAlpha="1"
android:startOffset="@integer/fadein_offset"
android:duration="@integer/fadein_duration"/>
<scale
android:fromXScale="0%" android:toXScale="100%" android:fromYScale="0%" android:toYScale="100%"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="@integer/fadein_offset"
android:duration="@integer/fadein_duration"/>
</code>
The "out" animation looks identical, just reversed.
So my question is, what does this error mean and how do you do fragment transitions in marshmallow?
Edit : my addFragment method, where I use setCustomAnimations(). I added the SDK check as I use scale animations which are problematic on lower Android versions. Note however that this code works on Android <6, the animation runs fine and did so for 3 years.
<code>private void addFragment(Fragment f, boolean addToBackstack, String tag) {
FragmentManager fman = getSupportFragmentManager();
FragmentTransaction ftrans = fman.beginTransaction();
// if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB) {
// ftrans.setCustomAnimations(inAnim, outAnim, inAnim, outAnim);
// }
if(addToBackstack) ftrans.addToBackStack(tag);
ftrans.replace(R.id.content, f, tag);
ftrans.commit();
}
</code>
On button press in fragment 1, I delegate to the activity via interface and there I call
<code>@Override
public void showFacts(DBCategory category) {
addFragment(FragFacts.Instance(category.id(), category.name()), true, FragFacts.TAG);
}
</code>
Edit 2 :
I found out it's not animation in general, it's just the scale animation part of my transition which causes it. I took it out, now it works.
Comment: When do you call `ftrans.setCustomAnimations(inAnim, outAnim, inAnim, outAnim)`? [From Docs]( [IDX] Maybe the view is not attached to the window anymore?
Comment: I added the complete method, plus how I call it. I call it only on button press. As said, all of this works flawlessly in Android < 6.0...
Comment: I am also experiencing some stange issues with Android 6.0, with code that worked before.
Comment: Did you try, if `android.app.Fragment` behaves different from `android.support.v4.app.Fragment`? Maybe it is a bug in the support library?
Comment: @AlbAtNf Didn't try that, but found out it's not animation in general, it's just the scale animation part of my transition which causes it. I took it out, now it works.
Comment: Maybe it is not even the whole scale animation part, only an attribute in that part? Any ways, good to hear you solved it.
Comment: It's still a mystery. Just tried another app, which has exactly the same animations, there everything works as expected. So it's probably not the animation. But then I don't know what is it... :)
Comment: I experienced the same thing. To add some more detail I am using v4 support fragments (ironically to fix graphics glitches with custom fragment animations). Using ObjectAnimator with rotationY anywhere near the fragment transition also crashes. Using fragmentTransaction.add() and hide() instead of replace() also did not help. The only non-solution I came up with was to use a plain vanilla fade in fade out transition.
Comment: This is a particularly difficult one. I've had a similar problem off and on throughout development of my app (always only on my 6.0 device). I tried several things based on what I read here. Now I'm back with my original source (that had the problem) and now there's no problem.
Answer: This is bug on Marshmallow when we do scale animation. For now we found a workaround by setting <code>view.setLayerType(View.LAYER_TYPE_SOFTWARE)</code> see documentation
Comment: but it is not static
Answer: For me it was a NullPointer exception masked as this because of Proguard obfuscation.
Run without Proguard and hopefully you'll see the underlying exception.
Comment: i can see it as "java.lang.NoSuchFieldError: no "J" field "mNativeHandle" in class "Lnet/sqlcipher/database/SQLiteDatabase;".
This is denoting to an aar file.Issue is i couldnt find a way to keep this file in proguard rules. any idea about how to add aar files in proguard?
Answer: I got this exception and same problem <code>Failed to dispatch window animation state change.android.os.DeadObjectException</code>.
apparently this happened because i forgot to mention activity in manifest file.
I was able to fix it by adding activity in <code>AndroidManifest.xml</code> file.
simply added following with activity class name and solved the problem
example :
<code> <activity
android:name="packageName.ClassName"
android:configChanges="orientation|keyboardHidden|screenSize|screenLayout"
android:screenOrientation="portrait"
android:theme="@style/Theme.ActionBarSize_all_view">
</activity>
</code>
Answer: In my case, my app didn't crash but the transition between activities was buggy on >6.0. The reason was that one of the activities had the windowBackground property from its style set to @null. I commented it and it got fixed.
<code><style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
<item name="android:windowBackground">@null</item>
</style>
</code><|endoftext|>IDEA Groovy test class already exists
Question: IDEA is giving my groovy class the warning `class "MyClassTest" already exists in "my.class.package". It also doesn't seem to be doing a very good job of keeping the class updated when I run the test. I'll add an assertion guaranteed to fail, or succeed and it won't recognize it until later (later so far seems arbitrary). Given that I have maven tests passing and running correctly I suspect this is simply an IDEA configuration problem
here's my <code>pom.xml</code>
<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi=" [IDX] xmlns=" [IDX] xsi:schemaLocation=" [IDX] [IDX] <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.9.RELEASE</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.2</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>generateStubs</goal>
<goal>compile</goal>
<goal>testGenerateStubs</goal>
<goal>testCompile</goal>
<goal>removeStubs</goal>
<goal>removeTestStubs</goal>
</goals>
</execution>
</executions>
<configuration>
<testSources>
<testSource>
<directory>${project.basedir}/src/test/groovy</directory>
<includes>
<include>**/*.groovy</include>
</includes>
</testSource>
</testSources>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.DATAJPA-622-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
-->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1102-jdbc41</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.3.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<!-- use UTF-8 for everything -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<start-class>com.xenoterracide.rpf.Application</start-class>
<java.version>1.8</java.version>
</properties>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url> [IDX] <snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-releases</id>
<url> [IDX] </repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url> [IDX] <snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url> [IDX] </pluginRepository>
</pluginRepositories>
</project>
</code>
Answer: I've fixed the issue by marking the <code>target</code> folder of the artifact as "Excluded".
I think the duplication is caused by the stub files generated in <code>target/generated-sources/groovy-stubs</code>. IDEA must be too curious about these files and might add them to the source set.
Comment: This works until I run a `clean compile` which deletes the directory and recreates it... and IntelliJ picks it up again as if I never marked it "excluded". Have you run into a means of making it always excluded?
Comment: @cjstehno, removing generateStubs & testGenerateStubs goals from gmavenplus plugin can fix this permanently. Sorry for very delayed response though :)
Comment: I'd say that up to your build tool plugin (maven, gradle) to exclude files. If your using maven, there are some settings you can apply to do this (like "Exclude build directory" in the Maven > Importing preference panel)
Answer: I had the exact same problem and setting <code>target</code> dir as excluded didn't help either. I noticed that the directory:
<code>/target/generated-sources/groovy-stubs/test
</code>
was getting set as a <code>Sources Root</code> in IDEA. I'd uncheck that in the UI and the error would go away, but as soon as I'd rebuild project it was back to it again. Very frustrating. Until I started looking at all the gmavenplus-plugin execution goals.
It turned out I had a few too many goals listed. If you're only using groovy for testing purposes, like I am (with Spock - I'm so done with JUnit), you should only have the following goals enabled under that plugin:
<code>addTestSources
testGenerateStubs
testCompile
removeTestStubs
</code>
Remove the rest of them. Once you do that IDEA should be all good with your groovy tests (or Specs in my case). Let me know if that really helped.
Answer: This is because of IntelliJ knows groovy by nature, the only thing you have to do is DO NOT activate gmaveplus-plugin in IntelliJ:
<code><profiles>
<profile>
<id>groovy-integration</id>
<!-- profile to incorporate gmaveplus in normal build -->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>generateStubs</goal>
<goal>compile</goal>
<goal>testGenerateStubs</goal>
<goal>testCompile</goal>
<goal>removeStubs</goal>
<goal>removeTestStubs</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>development-in-idea</id>
<!-- suppress `groovy-integration` profile by default in IntelliJ -->
<activation>
<property>
<name>idea.version</name>
</property>
</activation>
</profile>
</profiles>
</code>
One down side is that when you run maven goal from IntelliJ IDEA's Maven Projects tool window directly, the <code>groovy-integration</code> profile will not be activated as usual.
However, you can always navigate to the test folder, click "Run 'Tests in '...''" and have all the benefits brought to you by IntelliJ.
Exclude gmavenplus-plugin within IntelliJ IDEA takes one more advantage, IntelliJ IDEA sometimes add the generated test stubs as Sources instead of Test Sources, and unable to compile them due to lack of test-scoped dependencies.
Answer: I too get the message saying that my groovy class already exists. What I discovered is that it occurs after I Make Project the first time. From then on that error always occurs. If you want to get rid of the error, all you have to do is to delete the jar file produced stored in the app/build/libs directory. And of course, if you re Make Project again, the error comes back. So it's kind of tripping over itself by including it's own output jar lib in detecting that error.
I think its just a nuisance error and it doesn't seem to mess things up. It's certainly annoying to get an error indication when you don't have anything wrong. Perhaps there's someway to prevent this bogus error with some kind of groovy lint option, etc.; I just don't know. I would think that Michel solution of excluding certain files like the output lib file would work. The lack of good, reliable and consistent documentation concerning groovy and gradle builds makes me not interested in wanting to solve this problem; especially since it appears to just be a nuisance error.
Here's a little update. I did solve the problem, but I'm not exactly sure what the exact sequence you need to do to solve it. The best I can do is to explain the things that I dinked with. My solution seems to be centered around the solution posted at "Class already exists" error in IntelliJ on Groovy class . They talk about excluding a file from IntelliJ. I'm using Android Studio 3.1.3 and I couldn't exactly find a way to do what they where saying in that post. If I went into the Project tab and seletected Project Files I was able to navigate to my build folder. That directory was already marked as excluded. I did toggle it to being included and then back to being excluded. That did not seem to fix the problem. I then noticed that one could also load/unload modules. If I unloaded in my case the 'app' module and clicked okay, the error about the class already existing went always. However, the class file still thought their was an error. In other words, the class file name in the tab still had a squiggle line underneath it's name. Note however, there were no lines in error in the actually class file. I then played around with various attempts of unloading and loading of Modules executing them positioned at various other places in the directory file structure and cleaning the project. At the end, I just left things in the state where every module was loaded. I then closed the Android Studio project and reopened it. What I noticed was that the in Project Files tab, I could no longer see or navigate to the build directory as I previously could. And more importantly, the error about the class already existing went away. So something in the sequence of things I dinked with fixed the problem, but it didn't take affect until I closed Android Studio and restarted it. I've noticed in other situations where Android Studio need to be close and restarted to actually correct itself. | [{"idx": "Android_6.0_Marshmallow_:_Weird_error_with_fragment_animation", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-4401.jsonl"}, {"idx": "IDEA_Groovy_test_class_already_exists", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-4401.jsonl"}] |
Q: Something which is not intellectual is visceral?
Some people argue that poverty and misbehave go hand in hand, but I
think that this view is more visceral rather than being intellectually
based on facts.
Did I use the word "visceral" correctly in this sentence? I want to say that some people just say this because they feel so, they do not have any reason to support their claim.
A: Visceral means the instinctive gut feeling (viscera is the name for the cavities in the body, especially the intestines)
He has a visceral fear of spiders.
I don't think this is the right word. I think that you might say that the connection between poverty and crime is a "common-sense notion" or a "folk belief", or even an "urban myth", and it isn't supported by evidence.
A: Your use of visceral falls well within one of its basic meanings, specifically,
Merriam-Wester visceral
2 : not intellectual : instinctive, unreasoning visceral drives
and
American Heritage Dictionary visceral
*Being or arising from impulse or sudden emotion rather than from thought or deliberation
and
Collins visceral
Visceral feelings are feelings that you feel very deeply and find it difficult to control or ignore, and that are not the result of thought.<|endoftext|>Q: Indexed KeyValueMap I have been trying to figure it out and I am probably very close, but I have spent 2 hours without sucess. I have the expression below
MapIndexed[
geg[First[#2],
Total[KeyValueMap[fef[#1, #2, mem] &, #1]]] &, {<|a -> b,
c -> d|>, <|e -> f|>}]
which produces
{geg[1, fef[a, b, mem] + fef[c, d, mem]], geg[2, fef[e, f, mem]]}
I want to have the position of the association in the list {<|a -> b,
c -> d|>, <|e -> f|>} passed both to geg and fef
That is, I want the result to be
{geg[1, fef[a, b, 1, mem] + fef[c, d, 1, mem]], geg[2, fef[e, f, 2, mem]]}
A: MapIndexed[Function[{v, k},
geg[First[k], Total[KeyValueMap[fef[#1, #2, First[k], mem] &, v]]]],
{geg[1, fef[a, b, 1, mem] + fef[c, d, 1, mem]],
geg[2, fef[e, f, 2, mem]]}
Or, slightly more readable version:
MapIndexed[Function[{v, k},
geg[First[k],
Total[KeyValueMap[Function[{key, val}, fef[key, val, First[k], mem]], v]]]],
{<| a -> b, c -> d|>, <|e -> f|>}]
same result
With a minimal change in OP's code:
MapIndexed[geg[i = First[#2], Total[KeyValueMap[fef[#1, #2, i, mem] &, #1]]] &,
same result
and, without KeyValueMap:
MapIndexed[geg[i = First[#2], Total[fef[##, i, mem] & @@@ Normal[#]]] &,
same result<|endoftext|>Q: Preset Color Ramp in ArcGIS Desktop? I am trying to make a custom color ramp by using preset color ramp in ArcGIS 10.5. I need to show 19 colors. The default number of colors that can be input in preset color ramp is 13.
Is there any way to increase the number of this default input value?
A: An underhand trick...from my friend...(I do agree with gisnside)
*
*New > Multi-part Color Ramp
*Add Algorithmic Color Ramp
*Select this Algorithmic Color Ramp and Properties (or, just double-clicking) to open Edit Color Rampwindow.
*Give your first color to both Color 1 and Color 2. Click OK to close the window.
*Again, Add Algorithmic Color Ramp + Properties to give your second color to both Color 1 and Color 2.
*Repeat the above process 19 times.
A: In a color ramp, you don't put all the colors you need, but just the breaks. For example : from red to green = 2 colors, maybe 3 if you need yellow colors too. Some colors exists between breaks, often you don't need to put all the colors, jst find the right breaks.
13 breaks of color is a lot, probably more than what you can see apart with your eyes. Don't forget that in a color ramp you are displaying much more colors. Maybe you should have a look at other symbology types.<|endoftext|>Q: Difference between 'way back then' and 'way back when' Can anyone here please tell me the difference between 'way back then' and 'way back when' ?
Thanks,
Vivek
A: Both informal phrases are used as a phrase of time comparison.
The usage differs though.
Way back then:
"Ah, those good ol' days. The 1960s. Sigh. Way back then, the skies were clearer and the people were kind."
Way back when:
"Do you remember the day we first met? Twas that sunny day, way back when you still used to wear those horn-rimmed glasses!"
In the former case, the "then" shows that the time period has been mentioned before, unlike in the case with the latter, where the "when" specifies the time with some incident.
A: Way back then = long ago at that time
Way back when = long ago
Both are conversational in tone.
A: Way back then - indicates something that happened in the past, but the time is usually specified in some previous instance. So it's like an additional form of wording to the previous already stated time.
Way back when - refers to something that happened in the past, the time is not specified here by previous instances, and the word "when" symbolizes an event or usance that helps us determine the time or at least help us with our perception.<|endoftext|>Q: A question connecting covering spaces, map liftings, and "convex bodies in $\mathbb{R^n}$" I came across the following interesting problem while studying covering spaces for the first time, and was trying to prove it, but was not really able to get a proof off of the ground (i.e., beyond recalling the hypotheses of the problem, I was not really able to gain momentum in my written attempts after an hour and a half):
A convex body is a compact, convex subset of $\mathbb{R^n}$ that contains an interior point. Suppose $p: Y \rightarrow X$ is a covering, $Z$ is a convex body, and $f: Z \rightarrow X$ a continuous mapping. Show that for any $z \in Z$, and any $y \in Y$ such that $p(y) = f(z)$, there is a unique continuous mapping $\tilde{f}: Z \rightarrow Y$ such that $p \circ \tilde{f} = f$ and $\tilde{f}(z) = y$.
I am confident the remark about $Z$ having an interior point really matters here (perhaps suggesting that $Z$ is homeomorphic to another [perhaps nice!] topological subspace of Euclidean space), but I am not sure how. I expect that map lifting results (seen in connection with covering spaces) will factor in. I would like to know if anyone visiting would be up for walking me through a proof of this neat looking exercise.<|endoftext|>Q: Is there an adjective for "Made of Air"? I was trying to think up a name for an ability in a fantasy game which conjures up a shield made of air around oneself, like ____ Shield (analogous to "Earthen Shield", for example). I tried google and came up empty.
The Idea is that strong wind contained in a spherical shape surrounds the user and diverts anything that touches it.
A: How about airy ...
We do say wooden, earthen, golden, etc., but we also say silvery, coppery, brassy, glassy, irony and not silveren, copperen, etc.
airy
ADJECTIVE
Delicate, as though filled with or made of air.
‘airy clouds’
Oxford Dictionaries
A: Aerial would be the best fit with the naming convention you have so far, but if you're looking for more flourish, zephyric or tornadic could apply.
A: In terms of fantasy, a somewhat poetic phrase would be an ethereal shield.
[Merriam-Webster]
1a : of or relating to the regions beyond the earth
b : CELESTIAL, HEAVENLY
c : UNWORLDLY, SPIRITUAL
2a : lacking material substance : IMMATERIAL, INTANGIBLE
c : suggesting the heavens or heaven
In particular association with "air" would be sense 2a.
In actual fantasy games, I've also heard the term spirit shield, which is implied as a synonym in the above.<|endoftext|>Q: What does this quote from The New Yorker mean? What does this bold part mean:
The man who, as one author put it, “ruled the literary world from a fifteen-square-metre office” led a life more full of pain, wonder, and irony than most literary heroes. Born in Poland in 1920, Reich-Ranicki was sent to Berlin to study as a boy. “With every year that he discovered more joy in, and love for, Thomas Mann and Brecht and Gründgens and Goethe, there also grew hate,” wrote Frank Schirrmacher, publisher of the influential F.A.Z., where Reich-Ranicki headed the literature section in the nineteen-seventies and eighties. “The hate of an entire nation and all its bureaucracy for the young Jewish man who just wanted to go to the Deutsche Theatre.”
The New Yorker
A: I think the author of this passage confuses you by breaking a very long but continuous quotation into two parts. It works like this:
With every year
that he discovered more [joy and love for these guys] (this is a relative clause modifying "year")
there also grew hate—
—hate of [those other guys] for [him]
Year by year, while Reich-Ranicki was growing in love for his literary idols, the rest of the nation was growing in hatred for people like Reich-Ranicki.<|endoftext|>Q: Supset proof of invertible functions I'm struggling with the following question:
$M$ is a non-empty set, $G$ is the set of invertible functions $f: M \rightarrow M$. Let $x \in M$ and $G'=\lbrace f \in G: f(x)=x \rbrace$.
Now I have to proove that $G'$ is a subgroup of $G$.
I can use the following lemma:
Let $M$ be a group and $M \supseteq M'$. If
*
*$\forall a,b \in M'$ also $a \circ b \in M'$
*$e \in M$
*$a^{-1} \in M'$
then $M'$ is supgroup of $M$.
Any hints are welcome.
A: I assume that $G$ is intended to be the group of invertible functions $M\to M$ under composition, that you mean $$G'=\{f\in G:f(a)=a\}$$ (where $a$ is some fixed element of $M$), and that you wish to show that $G'$ is a subgroup of $G$.
To show closure under composition, you'll need to show that if $f,g:M\to M$ are invertible functions such that $f(a),g(a)=a,$ then $f\circ g:M\to M$ is invertible (one-to-one and onto) and $f\circ g(a)=a$.
Consider the function $M\to M$ given by $x\mapsto x$ for all $x\in M$. Is this invertible? Does it take $a\mapsto a$? How does it behave under composition with other functions $M\to M$?
To show inverses, take $f:M\to M$ invertible with $f(a)=a$. Show that $f^{-1}:M\to M$ is also invertible and that $f^{-1}(a)=a.$ | [{"idx": "https://ell.stackexchange.com/questions/309608", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-28287.jsonl"}, {"idx": "https://mathematica.stackexchange.com/questions/214136", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-28287.jsonl"}, {"idx": "https://gis.stackexchange.com/questions/271535", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-28287.jsonl"}, {"idx": "https://ell.stackexchange.com/questions/186061", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-28287.jsonl"}, {"idx": "https://math.stackexchange.com/questions/104165", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-28287.jsonl"}, {"idx": "https://english.stackexchange.com/questions/465764", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-28287.jsonl"}, {"idx": "https://ell.stackexchange.com/questions/10690", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-28287.jsonl"}, {"idx": "https://math.stackexchange.com/questions/348331", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-28287.jsonl"}] |
End of preview. Expand in Data Studio
YAML Metadata Warning:empty or missing yaml metadata in repo card
Check out the documentation for more information.
Consists of pretraining corpus from:
"https://huggingface.co/datasets/ontocord/MixtureVitae-211BT/resolve/main/data/math/math-0.jsonl.gz",
- Downloads last month
- 5