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&nbsp;!</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"}]
```markdown ## Contributing **30 seconds of code** is a community effort, so feel free to contribute in any way you can. Every contribution helps! Here's what you can do to help: - [Open issues]( [IDX] for things you want to see added or modified. - Be part of the discussion by helping out with [existing issues]( [IDX] or talking on our [gitter channel]( [IDX] Submit [pull requests]( [IDX] with snippets you have created (see below for guidelines). - Tag untagged snippets by running `npm run tagger` and adding the appropriate tag next to the script name in `tag_database`. - Fix typos in existing snippets or run `npm run linter` to lint unlinted snippets (yes, this is something we actually want help with, as this can take quite a while to run). ### Snippet submission and Pull request guidelines - **DO NOT MODIFY THE README.md FILE!** Make changes to individual snippet files. You can optionally run `npm run build-list` to update the README.md file automatically, based on the changes you have made. - **Snippet filenames** must correspond to the title of the snippet. For example, if your snippet is titled `### awesomeSnippet` the filename should be `awesomeSnippet.md`. - Use `camelCase`, not `kebab-case` or `snake_case`. - Avoid capitalization of words, except if the whole word is capitalized (e.g. `URL` should be capitalized in the filename and the snippet title). - **Snippet titles** should have be the same as the name of the function that is present in the snippet. - All snippet titles must be prefixed with `###` and be at the very first line of your snippet. - Snippet titles must be unique (although if you cannot find a better title, just add some placeholder at the end of the filename and title and we will figure it out). - Follow snippet titles with an empty line. - **Snippet descriptions** must be short and to the point. Try to explain *what* the snippet does and *how* the snippet works and what Javascript features are used. Remember to include what functions you are using and why. - Follow snippet descriptions with an empty line. - **Snippet code** must be enclosed inside ` ```js ` and ` ``` `. - Remember to start your snippet's code on a new line below the opening backticks. - Use ES6 notation to define your function. For example `const myFunction = arg1, arg2 => { }`. - Try to keep your snippets' code short and to the point. Use modern techniques and features. Make sure to test your code before submitting. - All snippets must be followed by one (more if necessary) test case after the code, on a new line, in the form of a comment, along with the expected output. The syntax for this is `myFunction('testInput') -> 'testOutput'`. Use multiline comments only if necessary. - Try to make your function name unique, so that it does not conflict with existing snippets. - Snippet functions do not have to handle errors in input, unless it's necessary (e.g. a mathematical function that cannot be extended to negative numbers should handle negative input appropriately). - Snippets should be short (usually below 10 lines). If your snippet is longer than that, you can still submit it, and we can help you shorten it or figure out ways to improve it. - Snippets *should* solve real-world problems, no matter how simple. - Snippets *should* be abstract enough to be applied to different scenarios. - It is not mandatory but highly appreciated if you provide **test cases** and/or performance tests (we recommend using [jsPerf]( [IDX] You can start creating a new snippet, by using the [snippet template](snippet-template.md) to format your snippets. ### Additional guidelines and conventions regarding snippets - When describing snippets, refer to methods, using their full name. For example, use `Array.reduce()`, instead of `reduce()`. - If your snippet contains argument with default parameters, explain what happens if they are omitted when calling the function and what the default case is. - If your snippet uses recursion, explain the base cases. - Always use `const functionName` for function definitions. - Use variables only when necessary. Prefer `const` when the values are not altered after assignment, otherwise, use `let`. Avoid using `var`. - Use `camelCase` for function and variable names if they consist of more than one word. - Try to give meaningful names to variables. For example use `letter`, instead of `lt`. Some exceptions to convention are: - `arr` for arrays (usually as the snippet function's argument). - `str` for strings. - `n` for a numeric value (usually as the snippet function's argument). - `el` for DOM elements (usually as the snippet function's argument). - `val` or `v` for value (usually when iterating a list, mapping, sorting etc.). - `acc` for accumulators in `Array.reduce()`. - `(a,b)` for the two values compared when using `Array.sort()`. - `i` for indexes. - `func` for function arguments. - `nums` for arrays of numbers. - Use `()` if your function takes no arguments. - Use `_` if an argument inside some function (e.g. `Array.reduce()`) is not used anywhere in your code. - Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to. - If your snippet's function takes variadic arguments, use `..args` (although in certain cases, it might be needed to use a different name). - If your snippet function's body is a single statement, omit the `return` keyword and use an expression instead. - Always use soft tabs (2 spaces), never hard tabs. - Omit curly braces (`{` and `}`) whenever possible. - Always use single quotes for string literals. Use template literals, instead, if necessary. - If your snippet's code is short enough (around 80 characters), you can make it a single-line function (although not mandatory). Otherwise, use multiple lines. - Prefer using `Array` methods whenever possible. - Prefer `Array.concat()` instead of `Array.push()` when working with `Array.reduce()`. - Use strict equality checking (`===` and `!==` instead of `==` and `!=`), unless you specifically have reason not to. - Prefer using the ternary operator (`condition ? trueResult : falseResult`) instead of `if else` statements whenever possible. - Avoid nesting ternary operators (but you can do it if you feel like you should). - You should define multiple variables on the same line (e.g. `const x = 0, y = 0`) on the same line whenever possible. - Do not use trailing or leading underscores in variable names. - Use dot notation (`object.property`) for object properties, when possible. Use bracket notation (`object[variable]`) when accessing object properties using a variable. - Use arrow functions as much as possible, except when you can't. - Use semicolons whenever necessary. If your snippet function's body is a single statement, return an expression and add a semicolon at the end. - Leave a single space after a comma (`,`) character. - Try to strike a balance between readability, brevity, and performance. - Never use `eval()`. Your snippet will be disqualified immediately. ```<|endoftext|>--- title: 'Tutorial: Azure Active Directory integration with Cherwell | Microsoft Docs' description: Learn how to configure single sign-on between Azure Active Directory and Cherwell. services: active-directory author: jeevansd manager: CelesteDG ms.reviewer: celested ms.service: active-directory ms.workload: identity ms.topic: tutorial ms.date: 01/14/2021 ms.author: jeedes --- # Tutorial: Azure Active Directory integration with Cherwell In this tutorial, you'll learn how to integrate Cherwell with Azure Active Directory (Azure AD). When you integrate Cherwell with Azure AD, you can: * Control in Azure AD who has access to Cherwell. * Enable your users to be automatically signed-in to Cherwell with their Azure AD accounts. ## Prerequisites To configure Azure AD integration with Cherwell, you need the following items: * An Azure AD subscription. * Cherwell single sign-on enabled subscription. ## Scenario description * Cherwell supports **SP** initiated SSO > [!NOTE] ## Add Cherwell from the gallery To configure the integration of Cherwell into Azure AD, you need to add Cherwell from the gallery to your list of managed SaaS apps. 1. 1. 1. 1. 1. In the **Add from the gallery** section, type **Cherwell** in the search box. 1. Select **Cherwell** from results panel and then add the app. ## Configure and test Azure AD SSO for Cherwell Configure and test Azure AD SSO with Cherwell using a test user called **B.Simon**. For SSO to work, you need to establish a link relationship between an Azure AD user and the related user in Cherwell. To configure and test Azure AD SSO with Cherwell, perform the following steps: 1. 1. 2. 2. **[Configure Cherwell SSO](#configure-cherwell-sso)** - to configure the Single Sign-On settings on application side. 1. **[Create Cherwell test user](#create-cherwell-test-user)** - to have a counterpart of B.Simon in Cherwell that is linked to the Azure AD representation of user. 3. ## Configure Azure AD SSO 1. In the Azure portal, on the **Cherwell** application integration page, find the **Manage** section and select **single sign-on**. 1. 1. 4. a. ` [IDX] b. In the **Reply URL** text box, type the URL using the following pattern: ` [IDX] [!NOTE] > The value is not real. Update the value with the actual Sign-on URL and Reply URL. Contact [Cherwell Client support team]( [IDX] to get the value. 5. 6. On the **Set up Cherwell** section, copy the appropriate URL(s) as per your requirement. In this section, you'll create a test user named B.Simon in the Azure portal. 1. In the left pane of the Azure portal, select **Azure Active Directory**, select **Users**, and then select **All users**. 1. At the top of the screen, select **New user**. 1. 1. 1. In the **User name** field, enter `<username>@<companydomain>.<extension>`. For example: `<EMAIL>`. 1. Select the **Show password** check box, and then make note of the value that's displayed in the **Password** box. 1. Select **Create**. In this section, you'll enable B.Simon to use Azure single sign-on by granting access to Cherwell. 1. 1. In the applications list, select **Cherwell**. 1. 1. 1. 1. 1. ## Configure Cherwell SSO To configure single sign-on on **Cherwell** side, you need to send the downloaded **Certificate (Base64)** and appropriate copied URLs from Azure portal to [Cherwell support team]( [IDX] > [!NOTE] > Your Cherwell support team has to do the actual SSO configuration. You will get a notification when SSO has been enabled for your subscription. ### Create Cherwell test user To enable Azure AD users to sign in to Cherwell, they must be provisioned into Cherwell. In the case of Cherwell, the user accounts need to be created by your [Cherwell support team]( [IDX] [!NOTE] > You can use any other Cherwell user account creation tools or APIs provided by Cherwell to provision Azure Active Directory user accounts. ## Test SSO This will redirect to Cherwell Sign-on URL where you can initiate the login flow. * Go to Cherwell Sign-on URL directly and initiate the login flow from there. When you click the Cherwell tile in the My Apps, you should be automatically signed in to the Cherwell for which you set up the SSO. ## Next steps Once you configure Cherwell you can enforce Session control, which protects exfiltration and infiltration of your organization’s sensitive data in real time. [Learn how to enforce session control with Microsoft Cloud App Security](/cloud-app-security/proxy-deployment-aad)<|endoftext|>**Sentiment Analysis Control - Power Apps Component** > [!TIP] > If you want to read in Brazilian language click [here](readme.pt-br.md) A Power Apps component to execute a sentiment analysis using Microsoft Cognitive Services or IBM Watson. It´s really helpful if you like to watch your customer tweets, for example, to check how are you feeling your customer. ![Sentiment Control](pcf_control_sentiment.gif) The component has some properties that needs to be configured first. > [!IMPORTANT] > **You must have a account in Microsoft Cognitive Services or IBM Watson.** | Property | Type | | ------------------ | ------ | | **TextValue** | current text that will be analyzed | string | | **Provider** | Select the provider that will be used: Microsoft or IBM | number | | **SentimentValue** | Result of analysis | string | | **PositiveValue** | Positive score | number | | **NeutralValue** | Neutral score | number | | **NegativeValue** | Negative Score | number | | **apiEntityName** | Entity name that will find the api data: url and key | string | | **apiKeyField** | Field that has the api key value | string | | **apiUrlField** | Field that has the url value | string | | **apiFindField** | Field to find the data in the entity | string | | **apiFindValue** | Value to find using the apiFindValue | string | If you need any help please let me know.<|endoftext|># liquibase-example This project could be a used as - a tutorial for learning the basics in liquibase - a base for dicussing on how-to-use liquibase in a collaboration development project This project is a **simple example** of a liquibase-project with maven ( [IDX] ).<br> This liquibase-project is ready to run with MySQL and postgreSQL<br> Dependencies to mysql- and posrgresql-connectors are found in the maven pom.xml By stating this is simple example : Not using complex commands, nor using extension This simple project contains 5 changesets : - 4 changesets that '*creates a table*' - 1 changeset that '*alters a table*' by adding a column #disucssion topic In a project with multiple developers using a version control system (VCS)<br> ###working as a team - Guarantees that all the developers have the same schema on their local computer - how : by version controlling the changelog-files - Every developer has a unique liquibase.properties-file (contains schema&credentials) - how : ignoring the liquibase.properties-file (if using git, update the .gitignore-file) ###updating the schema in a test-environment using a CI-tool Check if you are able to update your database in your stage/test-enviroment with liquibase. 1. Create a liquibase-project as a module amongs your other projects. 1. version control the project. 1. CI-tool: Run this project as a build-step before the module that depends on the db. 1. **obs** : credentials are stored in the liquibase.properties-file #prereq **Database** In this example the database is called '**denmark**'.<br> You **have to** create the database before running the project<br> - see the liquibase.properties-file - setting: url=jdbc:mysql://localhost/**denmark** **Software:** - java - a database-engine of choice #important files for maven. - pom.xml - db: mysql-connector-java (version '5.1.37') - db: postgresql (version '9.1-901-1.jdbc4') - liquibase: liquibase-maven-plugin #Files for the liquibase-project. ### Necessary files - **liquibase.properties** - contains : driver and url to the database - contains : credentials - contains : path to the master.xml-file - contains : additional such as ; 'verbose = true', '**dropFirst = false**' - **master.xml** - contains : path to 'db.changelog-x.y.xml' , x.y are version-nr. - **db.changelog-1.0.xml** - contains : all of your changesets (*note : every changeset has to has a unique id*) You are able to have multiple 'db.changelog-x.y.xml'-files<br> This project contains 2 files ; db.changelog-1.0.xml and db.changelog-5.0.xml <br> In this example every file has its responsibility<br> - The db.changelog-1.0.xml contains all your changesets, - The db.changelog-5.0.xml contains a reference to an .sql-file<br> - The default-insert-for-admin_config.sql contains example content. ### Other files The following files are **not necessary** for the project.<br> They are just here as a configuration example. - **liquibase.mysql.properties** - **liquibase.postgresql.properties** ## Writing changelogs in liquibase In this example changesets are written in XML<br> You are not restrained to using XML for changesets.<br> Other formats are YAML, JSON and SQL<br> [How-To-Documentation]( [IDX] **Simple rules** - You create new changelogs in the changelog-file - You do not delete old changelogs - Every changelog has a unique id #How to run the Liquibase-project To run the project<br> type '**mvn clean install**' in the same directory that the pom.xml-file resides Check your database <br> The following 5 tables should have been created<br> - **3 tables defined in the changelog-files** - ADMIN_CONFIG - IMAGE - MEDIA - **Additional 2 liquibase-tables** - DATABASECHANGELOG - DATABASECHANGELOGLOCK # Additional stuff ### Creating db-documentation command-line tool: "*Using change information stored in the change logs and an existing database, Liquibase can generate database change documentation* " [How-To-dbdoc]( [IDX] :** 'javadoc'-style documenation is created with this tool ### Going from a 'legacy'-database to a changeset-file. command-line tool: "*When starting to use Liquibase on an existing database, it is often useful, particularly for testing, to have a way to generate the change log to create the current database schema. Liquibase allows you to do this with the “generateChangeLog” command_line command.*" [How-To-Generate_changelogs]( [IDX] that this command currently has some limitations. It does not export the following types of objects: Stored procedures, functions, packages,Triggers*"<|endoftext|>```markdown --- title: Shape.LineStyle Property (Visio) keywords: vis_sdr.chm11213845 f1_keywords: - vis_sdr.chm11213845 ms.prod: visio api_name: - Visio.Shape.LineStyle ms.assetid: 1d1f2b2e-705d-6547-f6d6-0c5693e426d6 ms.date: 06/08/2017 --- # Shape.LineStyle Property (Visio) Specifies the line style for an object. Read/write. ## Syntax _expression_. `LineStyle` ## Return value String ## Remarks Setting a style to a nonexistent style generates an error. Setting one kind of style to an existing style of another kind (for example, setting the **LineStyle** property to a fill style) does nothing. Setting one kind of style to an existing style that has more than one set of attributes changes only the attributes for that component. For example, setting the **LineStyle** property to a style that has line, text, and fill attributes changes only the line attributes. To preserve a shape's local formatting, use the **LineStyleKeepFmt** property. Beginning with Microsoft Visio 2002, setting **LineStyle** to a zero-length string ("") will cause the master's style to be reapplied to the selection or shape. (Earlier versions generate a "no such style" exception.) If the selection or shape has no master, its style remains unchanged. ## Example This Microsoft Visual Basic for Applications (VBA) macro shows how to use the **LineStyle** property to set the line style for a particular shape. ```vb Public Sub LineStyle_Example() Dim vsoShape As Visio.Shape Set vsoShape = ActivePage.DrawLine(5, 4, 7.5, 1) vsoShape.LineStyle = "Guide" End Sub ``` ```<|endoftext|># Dubbo-go Official Website This project includes official documents and blogs of Dubbo-go to guide users to use Dubbo go correctly. ## Prerequisite Dubbo-go website is powered by [docsite]( [IDX] use **docsite version at `1.3.9`**. Please also **make sure your node version is 8.x**, versions higher than 8.x is not supported by docsite yet. ## Build instruction 1. Run `npm install docsite@1.3.9 -g` to install the dev tool. 2. 3. 4. Verify your change locally: `python -m SimpleHTTPServer 8000`, when your python version is 3 use :`python3 -m http.server 8000` instead. If you have higher version of node installed, you may consider `nvm` to allow different versions of `node` coexisting on your machine. 1. Follow the [instructions]( [IDX] to install nvm 2. Run `nvm install v8.16.0` to install node v8 3. Run `nvm use v8.16.0` to switch the working environment to node v8 4. Run `npm install docsite@1.3.9 -g` Then you are all set to run and build the website. Follow the build instruction above for the details. ## How to send a PR 1. 2. * `*.md` 3. Send a PR to **master** branch. ## SEO ``` --- title: title description: some description --- ``` ## Guide for adding new document ### Add a new doc 1. Add new .md file under docs/en-us or docs/zh-cn. 2. Update site_config/docs.js, add a new entry to the docs in either en-us or zh-cn. 3. 4. Send the pull request contains the .md and docs.js only. ### Add a new blog 1. Add new .md file under blog/en-us or blog/zh-cn. 2. Update site_config/blog.js, add a new entry to the blog in either en-us or zh-cn. 3. 4. Send the pull request contains the .md and blog.js only.<|endoftext|># Clojure Adaptor for RxJava This adaptor provides functions and macros to ease Clojure/RxJava interop. In particular, there are functions and macros for turning Clojure functions and code into RxJava `Func*` and `Action*` interfaces without the tedium of manually reifying the interfaces. # Basic Usage ## Requiring the interop namespace The first thing to do is to require the namespace: ```clojure (ns my.namespace (:require [rx.lang.clojure.interop :as rx]) (:import [rx Observable])) ``` or, at the REPL: ```clojure (require '[rx.lang.clojure.interop :as rx]) ``` ## Using rx/fn Once the namespace is required, you can use the `rx/fn` macro anywhere RxJava wants a `rx.util.functions.Func` object. The syntax is exactly the same as `clojure.core/fn`: ```clojure (-> my-observable (.map (rx/fn [v] (* 2 v)))) ``` If you already have a plain old Clojure function you'd like to use, you can pass it to the `rx/fn*` function to get a new object that implements `rx.util.functions.Func`: ```clojure (-> my-numbers (.reduce (rx/fn* +))) ``` ## Using rx/action The `rx/action` macro is identical to `rx/fn` except that the object returned implements `rx.util.functions.Action` interfaces. It's used in `subscribe` and other side-effect-y contexts: ```clojure (-> my-observable (.map (rx/fn* transform-data)) (.finallyDo (rx/action [] (println "Finished transform"))) (.subscribe (rx/action [v] (println "Got value" v)) (rx/action [e] (println "Get error" e)) (rx/action [] (println "Sequence complete")))) ``` # Gotchas Here are a few things to keep in mind when using this interop: * Keep in mind the (mostly empty) distinction between `Func` and `Action` and which is used in which contexts * If there are multiple Java methods overloaded by `Func` arity, you'll need to use a type hint to let the compiler know which one to choose. * Methods that take a predicate (like filter) expect the predicate to return a boolean value. A function that returns a non-boolean value will result in a `ClassCastException`. # Binaries Binaries and dependency information for Maven, Ivy, Gradle and others can be found at [ [IDX] [IDX] for Maven: ```xml <dependency> <groupId>com.netflix.rxjava</groupId> <artifactId>rxjava-clojure</artifactId> <version>x.y.z</version> </dependency> ``` and for Ivy: ```xml <dependency org="com.netflix.rxjava" name="rxjava-clojure" rev="x.y.z" /> ``` and for Leiningen: ```clojure [com.netflix.rxjava/rxjava-clojure "x.y.z"] ```<|endoftext|>Good bug reports are very important. Therefor some guidelines are provided: 1. Check if the issue has already been reported using the **GitHub issue search**. 2. Check if the issue has not already been fixed by getting the latest `master` branch and try to reproduce the problem. 3. Create a minimal setup/example whcih reproduces the problem. Please try to be as detailed as possible in the bug report. Add what OS you're using, what version of erlang you're using, etc. What does your configuration look like, what does the code look like which incorporates wakala? What happened and what did you expect to happen? **[File a bug report]( [IDX] requests ------------- Good pull request - patches, improvements, new features - are even better than good bug reports. Pull requests should remain focused in scope and unrelated commits should be moved to separate pull requests. Please open an issue to discuss a significant amount of work. Allthough there are no coding guidelines, try to stay within the coding conventions of the source files (which are at the moment formatted using emacs erlang-mode). Please update any documentation that is relevant to the change you're making. For pull requests follow this process: 1. [Fork]( [IDX] the project, clone your ```bash git clone [IDX] cd wakala # Assigns the original repo to a remote called "upstream" git remote add upstream [IDX] ``` 2. ```bash git checkout master git pull upstream master ``` 3. ```bash ``` 4. Please adhere to these [git commit message guidelines] ( [IDX] or your pull request is unlikely be merged into the main project. Use git's [interactive rebase]( [IDX] Locally merge (or rebase) the upstream development branch into your topic branch: ```bash ``` 6. ```bash ``` 7. [Open a Pull Request]( [IDX] with a clear title and description.<|endoftext|>--- title: "System Settings Goals tab | MicrosoftDocs" description: System Settings Goals tab author: jimholtz ms.component: pa-admin ms.topic: conceptual ms.subservice: admin ms.date: 08/31/2021 ms.author: jimholtz search.audienceType: - admin search.app: - D365CE - PowerApps - Powerplatform - Flow --- # System Settings Goals tab Set the duration and frequency of the automatic rollup of goals. These settings only affect the automatic handling of all goals set in customer engagement apps (Dynamics 365 Sales, Dynamics 365 Customer Service, Dynamics 365 Field Service, Dynamics 365 Marketing, and Dynamics 365 Project Service Automation). You can always perform a manual rollup for any goal at any time. <!-- legacy procedure --> 1. [!INCLUDE[proc_permissions_system_admin_and_customizer](../includes/proc-permissions-system-admin-and-customizer.md)] Check your security role - [!INCLUDE[proc_follow_steps_in_link](../includes/proc-follow-steps-in-link.md)] - [!INCLUDE[proc_dont_have_correct_permissions](../includes/proc-dont-have-correct-permissions.md)] 2. If you are using a Sales web application, go to **Settings** > **Administration** > **System Settings**, and then select the **Goals** tab. OR If you are using the Sales Hub App, select the Site map icon ![Site map icon](media/site-map-icon.png "Site map icon"), then select ellipsis ![Ellipsis to open more options](media/ellipsis-more-options.png "Ellipsis to open more options") , then select **App Settings**, and then select **Goals Settings**. | Settings | Description | | **Set the roll-up expiration time and the roll-up frequency.** | | | Days after the goal end date when the rollup will stop | Set the number of days after the ending date of a goal for model-driven apps in Dynamics 365 to stop including a goal in a rollup. <br>**Default**: 30 days.| | Roll-up recurrence frequency | Set the number of hours between each goal rollup. <br>**Default**: 24 <br>**Limits**: Must be greater than or equal to 24 hours | ### See also [Administrator and Sales Manager Guide](/dynamics365/sales-enterprise/admin-guide) [Progress Against Goals report](/dynamics365/customerengagement/on-premises/basics/sales-insights-reports#progress-against-goals-report) [!INCLUDE[footer-include](../includes/footer-banner.md)]<|endoftext|><properties linkid="dev-node-remotedesktop" urldisplayname="Enable Remote Desktop" headerexpose="" pagetitle="Enable Remote Desktop - Node.js - Develop" metakeywords="Azure Node.js remote access, Azure Node.js remote connection, Azure Node.js VM access, Azure Node.js virtual machine access" footerexpose="" metadescription="Learn how to enable remote-desktop access for the virtual machines hosting your Windows Azure Node.js application. " umbraconavihide="0" disquscomments="1"></properties> # Enabling Remote Desktop in Windows Azure Remote Desktop enables you to access the desktop of a role instance running in Windows Azure. You can use a remote desktop connection to configure the virtual machine or troubleshoot problems with your application. <div class="dev-callout"> <b>Note</b> <p>The steps in this article only apply to node applications hosted as a Windows Azure Cloud Service.</p> </div> This task includes the following steps: - [Step 1: Configure the service for Remote Desktop access using Windows Azure PowerShell] - [Step 2: Connect to the role instance] - [Step 3: Configure the service to disable Remote Desktop access using Windows Azure PowerShell] ## <a name="step1"> </a>Step 1: Configure the service for Remote Desktop access using Windows Azure PowerShell To use Remote Desktop, you need to configure your service definition and service configuration with a username, password, and certificate to authenticate with role instances in the cloud. [Windows Azure PowerShell] includes the **Enable-AzureServiceProjectRemoteDesktop** cmdlet, which does this configuration for you. Perform the following steps from the computer where the service definition was created. 1. ![Windows Azure PowerShell start menu entry][powershell-menu] 2. Change directory to the service directory, type **Enable-AzureServiceProjectRemoteDesktop**, and then enter a user name and password to use when authenticating with role instances in the cloud. 3. At the **Publish-AzureServiceProject**. When these steps have been completed, the role instances of the service in the cloud are configured for Remote Desktop access. ## <a name="step2"> </a>Step 2: Connect to the role instance With your deployment up and running in Windows Azure, you can connect to the role instance. 1. In the [Windows Azure Management Portal], select **Cloud Services** and then the service deployed in Step 1 above ![azure management portal][cloud-services] 2. Click **Instances**, and then click **Production** or **Staging** to see the instances for your service. Select an instance and then click **Connect** at the bottom of the page. ![The instances page][3] 2. When you click **Connect**, the web browser prompts you to save an .rdp file. If you’re using Internet Explorer, click **Open**. ![prompt to open or save the .rdp file][4] 3. When the file is opened, the following security prompt appears: ![Windows security prompt][5] 4. Click **Connect**, and a security prompt will appear for entering credentials to access the instance. Enter the password you created in [Step 1][Step 1: Configure the service for Remote Desktop access using Windows Azure PowerShell], and then click **OK**. ![username/password prompt][6] When the connection is made, Remote Desktop Connection displays the desktop of the instance in Windows Azure. You have successfully gained remote access to your instance and can perform any necessary tasks to manage your application. ![Remote desktop session][7] ## <a name="step3"> </a>Step 3: Configure the service to disable Remote Desktop access using Windows Azure PowerShell When you no longer require remote desktop connections to the role instances in the cloud, disable remote desktop access using the [Windows Azure PowerShell] 1. 2. Change directory to the service directory, and type **Disable-AzureServiceProjectRemoteDesktop**: 3. At the **Publish-AzureServiceProject**: ## Additional Resources - [Remotely Accessing Role Instances in Windows Azure] - [Using Remote Desktop with Windows Azure Roles] [Step 1: Configure the service for Remote Desktop access using Windows Azure PowerShell]: #step1 [Step 2: Connect to the role instance]: #step2 [Step 3: Configure the service to disable Remote Desktop access using Windows Azure PowerShell]: #step3 [Windows Azure PowerShell]: [IDX] Azure Management Portal]: [IDX] ../../Shared/Media/azure-powershell-menu.png [publish-project]: ../Media/publish-rdp.png [enable-rdp]: ../Media/enable-rdp.png [cloud-services]: ../../Shared/Media/cloud-services-remote.png [3]: ../../Shared/Media/cloud-service-instance.png [4]: ../../Shared/Media/rdp-open.png [5]: ../Media/remote-desktop-12.png [6]: ../Media/remote-desktop-13.png [7]: ../Media/remote-desktop-14.png [8]: ../Media/remote-desktop-04.png [Remotely Accessing Role Instances in Windows Azure]: [IDX] [Using Remote Desktop with Windows Azure Roles]: [IDX] "Report Builder authoring environment (SSRS) | Microsoft Docs" ms.custom: "" ms.date: "03/01/2017" ms.prod: "sql-server-2016" ms.reviewer: "" ms.suite: "" ms.technology: - "reporting-services-sharepoint" - "reporting-services-native" ms.tgt_pltfrm: "" ms.topic: "article" caps.latest.revision: 13 author: "maggiesMSFT" ms.author: "maggies" manager: "erikre" --- # Report Builder authoring environment (SSRS) Report Builder [!INCLUDE[ssRBnoversion](../../includes/ssrbnoversion-md.md)] is a stand-alone authoring environment for creating [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] paginated reports outside of Visual Studio. When you design a report, you specify where to get the data, which data to get, and how to display the data. When you run the report, the report processor takes all the information you have specified, retrieves the data, and combines it with the report layout to generate the report. You can install it from the [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] web portal or from the Microsoft Download Center. [Install Report Builder](../../reporting-services/install-windows/install-report-builder.md) from the Microsoft Download Center. ## Benefits of Report Builder Report Builder enables you to: - Use the Report Builder ribbon to quickly add items your reports, launch table, chart, and map wizards, and format report data. - Add data from built-in data providers by using query designers that help you specify which data to include in your report. - Create and use report parameters and other interactive features that enable your report readers to customize data and vary report presentation. - Create expressions from built-in fields, collections, operators, and functions. - Open reports directly from a report server. - Preview reports that use local or published shared data sources and shared datasets. - Preview reports in HTML or print format. - Export reports to other file formats such as [!INCLUDE[ofprexcel](../../includes/ofprexcel-md.md)]. - Save your report and related items to a SharePoint library, a report server, or your local computer. Report Builder and Report Designer share many features. Read more about [Report Builder in SQL Server 2016](../../reporting-services/report-builder/report-builder-in-sql-server-2016.md). ## See Also [Install Report Builder](../../reporting-services/install-windows/install-report-builder.md) [Configure Report Builder Access](../../reporting-services/report-server/configure-report-builder-access.md) [Reporting Services Tools](../../reporting-services/tools/reporting-services-tools.md) [Design Reports with Report Designer &#40;SSRS&#41;](../../reporting-services/tools/design-reporting-services-paginated-reports-with-report-designer-ssrs.md)
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12686.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12686.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12686.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12686.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12686.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12686.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12686.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12686.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12686.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12686.jsonl"}]
algebra: linear 1d ------------------ Ask: Solve -125*t - 915 = -5665 for t. Finding: 38 Ask: Solve -675*b + 53361 + 25047 = 648*b - 355*b for b. Finding: 81 Ask: Solve 0 = -2*t - 4*t + 18 for t. Finding: 3 Ask: Solve 6408 = -692*a - 109*a for a. Finding: -8 Ask: Solve 0 = -90052*v + 92371*v - 30147 for v. Finding: 13 Ask: Solve 1144*r - 48382 + 25606 - 29848 = 0 for r. Finding: 46 Ask: Solve 18*v = 195*v - 1239 for v. Finding: 7 Ask: Solve -20*n = -10*n + 30*n - 320 for n. Finding: 8 Ask: Solve 15*f - 9 = 12*f for f. Finding: 3 Ask: Solve 0 = -72*y + 65*y - 14 for y. Finding: -2 Ask: Solve -46 = -13*t - 7 for t. Finding: 3 Ask: Solve 14*d - 7 = 21*d for d. Finding: -1 Ask: Solve 143*y - 13 = 156*y for y. Finding: -1 Ask: Solve 0 = -579*j + 10477 + 8630 for j. Finding: 33 Ask: Solve -20*t - 41*t + 131*t + 129 = -11 for t. Finding: -2 Ask: Solve 1284*d - 23092 + 10583 = 15739 for d. Finding: 22 Ask: Solve 13*l = -59*l - 288 for l. Finding: -4 Ask: Solve 14*v - 48 - 170 = 62 for v. Finding: 20 Ask: Solve u + 6*u = 28 for u. Finding: 4 Ask: Solve 41*w + 115*w + 995 + 253 = 0 for w. Finding: -8 Ask: Solve -29*j - 461 + 201 - 7 - 951 = 0 for j. Finding: -42 Ask: Solve -34*h - 196 = -6*h for h. Finding: -7 Ask: Solve 329*m - 294*m + 991 + 759 = 0 for m. Finding: -50 Ask: Solve 6985*o - 32 = 6986*o for o. Finding: -32 Ask: Solve 9*y - 16*y = -14 for y. Finding: 2 Ask: Solve -43*p - 4 = -44*p for p. Finding: 4 Ask: Solve w + 163 = -13*w + 9 for w. Finding: -11 Ask: Solve 635*u - 30*u + 18400 = -430*u - 115*u for u. Finding: -16 Ask: Solve 85*a - 210*a + 8922 = 1672 for a. Finding: 58 Ask: Solve -26*o = -5017 + 5277 for o. Finding: -10 Ask: Solve 5780*c + 805 = 5815*c for c. Finding: 23 Ask: Solve -m = -7*m for m. Finding: 0 Ask: Solve 0 = -5*h - 4*h - 63 for h. Finding: -7 Ask: Solve -350*a - 35108893 = -35096993 for a. Finding: -34 Ask: Solve 102303 - 93951 = -261*c for c. Finding: -32 Ask: Solve 498*j - 1728*j - 65190 = 0 for j. Finding: -53 Ask: Solve 14703*p - 14209*p - 18945 + 73779 = 0 for p. Finding: -111 Ask: Solve 1906*c - 35096 - 4109 - 96879 = -758 for c. Finding: 71 Ask: Solve 172*h + 164*h = -142*h + 460*h + 1314 for h. Finding: 73 Ask: Solve 0 = -14*x + 420*x - 19160 - 3982 for x. Finding: 57 Ask: Solve 85*c + 2269 = -1488 - 578 for c. Finding: -51 Ask: Solve 0 = 8*k - 4*k - 20 for k. Finding: 5 Ask: Solve -83*p + 244*p = -517*p + 12204 for p. Finding: 18 Ask: Solve -2608*p = 56617 + 32055 for p. Finding: -34 Ask: Solve -134 = 19*d - 39 for d. Finding: -5 Ask: Solve -50*i + 3578 = 3378 for i. Finding: 4 Ask: Solve 0 = 3*s + 1530 - 1548 for s. Finding: 6 Ask: Solve 0 = 46*s - 41*s - 5 for s. Finding: 1 Ask: Solve -1823*f - 115990 = 597*f + 26790 for f. Finding: -59 Ask: Solve -302*x - 254*x = 94*x - 32500 for x. Finding: 50 Ask: Solve 26*a = -290 + 56 for a. Finding: -9 Ask: Solve -13*g - 76*g = 217 + 228 for g. Finding: -5 Ask: Solve -285*l - 24200 - 24902 + 5097 = 392*l for l. Finding: -65 Ask: Solve 515*h = 140*h - 4125 for h. Finding: -11 Ask: Solve 24 + 180 + 84 = 16*x for x. Finding: 18 Ask: Solve 12*c + 18 = 6 for c. Finding: -1 Ask: Solve 5*a - 14 = -2*a for a. Finding: 2 Ask: Solve -13*l + 3*l = 0 for l. Finding: 0 Ask: Solve 0 = 4*r + 390 - 398 for r. Finding: 2 Ask: Solve -47*b = 203 - 1109 - 316 for b. Finding: 26 Ask: Solve 2249 = -201*l - 3170 + 1801 for l. Finding: -18 Ask: Solve 427 = 348*o - 4793 for o. Finding: 15 Ask: Solve -7*a + 20 = -2*a for a. Finding: 4 Ask: Solve 11*h + 3*h - 42 = 0 for h. Finding: 3 Ask: Solve -96*l + 119*l - 46 = 0 for l. Finding: 2 Ask: Solve 0 = 299*y + 209*y + 15748 for y. Finding: -31 Ask: Solve 1414*p = -1412*p + 1808*p + 65152 for p. Finding: 64 Ask: Solve -9*d - 9 = -6*d for d. Finding: -3 Ask: Solve 64*c = 171 - 747 for c. Finding: -9 Ask: Solve -127*b + 56*b = -84*b + 598 for b. Finding: 46 Ask: Solve 1440568 + 991889 - 8589 = -1244*f - 20018*f for f. Finding: -114 Ask: Solve 1184 = 6*m + 1208 for m. Finding: -4 Ask: Solve 111*z + 15 = 116*z for z. Finding: 3 Ask: Solve -51*f = -1784 + 2549 for f. Finding: -15 Ask: Solve 9*q + 126 - 135 = 0 for q. Finding: 1 Ask: Solve -325 = -133*n - 420 - 703 for n. Finding: -6 Ask: Solve -230*u + 85*u - 4810 = 90*u + 135*u for u. Finding: -13 Ask: Solve 9*d + 21 = -35 + 2 for d. Finding: -6 Ask: Solve 2*q = -24 + 14 for q. Finding: -5 Ask: Solve -15*s - 5 + 5 = -45 for s. Finding: 3 Ask: Solve 538*q - 104 = 525*q for q. Finding: 8 Ask: Solve -43 = 24*l + 5 for l. Finding: -2 Ask: Solve -16*b + 7*b = -9 for b. Finding: 1 Ask: Solve -17 = -k - 22 for k. Finding: -5 Ask: Solve -2358 + 790 = 224*c for c. Finding: -7 Ask: Solve 509*l = -455 - 6913 - 9429 for l. Finding: -33 Ask: Solve 23*h - 9*h = 468 - 118 for h. Finding: 25 Ask: Solve 7*v + 21 = -0*v for v. Finding: -3 Ask: Solve -67*j - 2887 - 2359 = -556 for j. Finding: -70 Ask: Solve 30 + 80 = -22*a for a. Finding: -5 Ask: Solve 0 = 981*z - 1207*z + 3390 for z. Finding: 15 Ask: Solve 13*z = -51*z + 512 for z. Finding: 8 Ask: Solve -151*t = 78*t - 5743 + 1621 for t. Finding: 18 Ask: Solve -36*u - 484 = -92*u - 32*u - 5500 for u. Finding: -57 Ask: Solve 0 = 85*v - 43*v - 33*v + 369 for v. Finding: -41 Ask: Solve 0 = 20*o - 23*o - 12 for o. Finding: -4 Ask: Solve -285 + 683 = -199*b for b. Finding: -2 Ask: Solve -87*p + 56950 = 58516 for p. Finding: -18 Ask: Solve 2*t - 935 + 929 = 0 for t. Finding: 3 Ask: Solve -17 + 11 = -6*t for t. Finding: 1 Ask: Solve -25*r + 31 = -19 for r. Finding: 2 Ask: Solve -289*l - 2106 - 2245 = -4972 + 12181 for l. Finding: -40 Ask: Solve 104*l + 747 = 21*l - 66*l - 743 for l. Finding: -10 Ask: Solve 0 = -9*n + 4*n for n. Finding: 0 Ask: Solve 4197 = -252*l - 3111 for l. Finding: -29 Ask: Solve 3*r + 2*r - 20 = 0 for r. Finding: 4 Ask: Solve -7*x = 64*x for x. Finding: 0 Ask: Solve 1422*l = 1419*l + 15 for l. Finding: 5 Ask: Solve 12 = 70*p - 74*p for p. Finding: -3 Ask: Solve -216*j + 29792 = 64*j + 328*j for j. Finding: 49 Ask: Solve 1835*m - 138048 = -20381 + 52109 + 6384 for m. Finding: 96 Ask: Solve -3*b - 3 = 9 for b. Finding: -4 Ask: Solve -7*z = -5*z - 12 for z. Finding: 6 Ask: Solve -53*z + 3836 = 202*z - 118*z for z. Finding: 28 Ask: Solve 10*s + 8 = 12*s for s. Finding: 4 Ask: Solve 6*f = 14 - 8 for f. Finding: 1 Ask: Solve 600 - 536 = -196*g - 2092 for g. Finding: -11 Ask: Solve 29 = -109*u + 29 for u. Finding: 0 Ask: Solve -4471*i - 60 = -4456*i for i. Finding: -4 Ask: Solve 1546 - 106 = -180*x for x. Finding: -8 Ask: Solve -222 + 270 = 4*s for s. Finding: 12 Ask: Solve 808 + 15191 = -310*v - 10971 for v. Finding: -87 Ask: Solve -2860 = 73*o - 86 for o. Finding: -38 Ask: Solve -1360 + 2225 = -70*s + 243*s for s. Finding: 5 Ask: Solve -16*y = -22*y - 42 for y. Finding: -7 Ask: Solve -27*t = -33*t - 1 - 17 for t. Finding: -3 Ask: Solve -5174 = -5*i - 5149 for i. Finding: 5 Ask: Solve 2*t + 3 = 5*t for t. Finding: 1 Ask: Solve -112 - 64 = 26*a + 84 for a. Finding: -10 Ask: Solve 2353 = 10*t + 2433 for t. Finding: -8 Ask: Solve 8 - 163 = -155*w for w. Finding: 1 Ask: Solve -236334 = -5247*u - 1704*u for u. Finding: 34 Ask: Solve 877 - 793 = 14*j for j. Finding: 6 Ask: Solve -12216*b + 12142*b + 2590 = 0 for b. Finding: 35 Ask: Solve -769*h + 1117*h = 0 for h. Finding: 0 Ask: Solve -47*u + 8 - 290 = 0 for u. Finding: -6 Ask: Solve 50*p = 51*p for p. Finding: 0 Ask: Solve -189016*z + 7139 = -189137*z for z. Finding: -59 Ask: Solve 2*z = 955 - 915 for z. Finding: 20 Ask: Solve 173*c - 1692 = -193*c - 226*c + 780*c for c. Finding: -9 Ask: Solve -10622 - 11188 = -2161*w + 4122 for w. Finding: 12 Ask: Solve 4*v - v = 2*v for v. Finding: 0 Ask: Solve -80*v - 30 = -83*v for v. Finding: 10 Ask: Solve -10557*u - 24340 - 92 = 49467 for u. Finding: -7 Ask: Solve 53 = -2*d + 47 for d. Finding: -3 Ask: Solve -31*i + 79 = -3*i - 61 for i. Finding: 5 Ask: Solve 477*u - 13825 = -757*u + 10522 + 10205 for u. Finding: 28 Ask: Solve 199*x = -274*x + 89*x - 138*x + 39150 for x. Finding: 75 Ask: Solve n + 66*n + 406 + 532 = 0 for n. Finding: -14 Ask: Solve 13646 - 10319 + 11545 = -338*z for z. Finding: -44 Ask: Solve -36*n + 12*n = -48 for n. Finding: 2 Ask: Solve 34*q - 100 = 15*q - 5 for q. Finding: 5 Ask: Solve 1468*i + 1562*i - 1038*i + 89640 = 0 for i. Finding: -45 Ask: Solve 104*m + 308 + 316 = 0 for m. Finding: -6 Ask: Solve -171*h + 64469 = 54380 for h. Finding: 59 Ask: Solve 33*y + 133 = -32 for y. Finding: -5 Ask: Solve -8*v + 4 + 28 = 0 for v. Finding: 4 Ask: Solve -73 = 3*l - 52 for l. Finding: -7 Ask: Solve 19 = y + 21 for y. Finding: -2 Ask: Solve 1837 = -6*c + 1819 for c. Finding: -3 Ask: Solve 18*t = -53 + 184 + 85 for t. Finding: 12 Ask: Solve 19*w + 20*w - 791 + 11669 = 816*w for w. Finding: 14 Ask: Solve 0 = 62*j - 70*j - 152 for j. Finding: -19 Ask: Solve -59 = -3*j - 32 for j. Finding: 9 Ask: Solve -33*i + 4742 + 5061 = 8549 for i. Finding: 38 Ask: Solve 2271 = 158*c + 32*c - 3239 for c. Finding: 29 Ask: Solve -33569 + 18162 = 437*d + 2445*d + 91227 for d. Finding: -37 Ask: Solve 0 = -o - 6*o + 2*o for o. Finding: 0 Ask: Solve -1401*m - 21 + 21 = 624*m for m. Finding: 0 Ask: Solve -7*r = 2*r + 36 for r. Finding: -4 Ask: Solve -465*j - 6175 = -3628 + 4893 for j. Finding: -16 Ask: Solve -27 = -7*i - 2*i for i. Finding: 3 Ask: Solve -1382*m + 1257*m - 3840*m = 56124 + 173846 for m. Finding: -58 Ask: Solve -73*u - 276 = -119*u for u. Finding: 6 Ask: Solve -17*l + 14 = -105 for l. Finding: 7 Ask: Solve -4 = -85*p + 86*p for p. Finding: -4<|endoftext|>arithmetic: div --------------- Subquestion: What is -5 divided by 3? Ans: -5/3 Subquestion: Divide -214 by -5661. Ans: 214/5661 Subquestion: Calculate 576898800 divided by 30. Ans: 19229960 Subquestion: Divide 2984 by 1. Ans: 2984 Subquestion: Divide 57213000 by -9000. Ans: -6357 Subquestion: What is -75 divided by -18? Ans: 25/6 Subquestion: -544160 divided by 2864 Ans: -190 Subquestion: Calculate -5670757 divided by 5. Ans: -5670757/5 Subquestion: What is -7835388 divided by -237436? Ans: 33 Subquestion: 5908060 divided by 44090 Ans: 134 Subquestion: -40 divided by 4 Ans: -10 Subquestion: -57677468 divided by 6 Ans: -28838734/3 Subquestion: Divide -47 by -117990. Ans: 47/117990 Subquestion: Divide -32311532 by -2. Ans: 16155766 Subquestion: What is -140 divided by -120? Ans: 7/6 Subquestion: What is -772 divided by 2? Ans: -386 Subquestion: What is 98625 divided by 5? Ans: 19725 Subquestion: Calculate 140274610 divided by 10019615. Ans: 14 Subquestion: What is 5 divided by 17646371? Ans: 5/17646371 Subquestion: Divide 10755 by 45. Ans: 239 Subquestion: -20346 divided by 2 Ans: -10173 Subquestion: 24423462 divided by -6 Ans: -4070577 Subquestion: Calculate 290 divided by 58. Ans: 5 Subquestion: Calculate -319 divided by -3603. Ans: 319/3603 Subquestion: What is 251829600 divided by -50365920? Ans: -5 Subquestion: Divide 1957592 by 364. Ans: 5378 Subquestion: -45 divided by -284671 Ans: 45/284671 Subquestion: What is 71406903 divided by 3? Ans: 23802301 Subquestion: Calculate -7370400 divided by 12450. Ans: -592 Subquestion: Divide 8507950 by 48. Ans: 4253975/24 Subquestion: 24 divided by 11444640 Ans: 1/476860 Subquestion: -18 divided by -253916 Ans: 9/126958 Subquestion: What is -178693162 divided by -2? Ans: 89346581 Subquestion: Divide 84170430 by 9. Ans: 9352270 Subquestion: What is 3 divided by 4738778? Ans: 3/4738778 Subquestion: Calculate 14980196 divided by -31471. Ans: -476 Subquestion: Calculate -38294784 divided by 2112. Ans: -18132 Subquestion: -744 divided by 3 Ans: -248 Subquestion: 1908452 divided by -9 Ans: -1908452/9 Subquestion: -36820 divided by 28 Ans: -1315 Subquestion: -49176 divided by -6 Ans: 8196 Subquestion: Calculate 1248 divided by -32. Ans: -39 Subquestion: Calculate 94575 divided by 195. Ans: 485 Subquestion: Calculate -5 divided by 104. Ans: -5/104 Subquestion: What is 615 divided by -6? Ans: -205/2 Subquestion: What is 14352 divided by -5? Ans: -14352/5 Subquestion: Calculate 5345 divided by -1. Ans: -5345 Subquestion: Calculate 4 divided by -76490. Ans: -2/38245 Subquestion: Calculate 2854 divided by 1427. Ans: 2 Subquestion: 7 divided by -3 Ans: -7/3 Subquestion: What is -5804 divided by 13? Ans: -5804/13 Subquestion: What is 59 divided by 32274? Ans: 59/32274 Subquestion: 204 divided by -51 Ans: -4 Subquestion: What is -10 divided by 5? Ans: -2 Subquestion: What is -1 divided by -35? Ans: 1/35 Subquestion: Calculate 17116184 divided by -4279046. Ans: -4 Subquestion: What is -11612 divided by 4? Ans: -2903 Subquestion: 1467 divided by 1 Ans: 1467 Subquestion: What is 15045 divided by 59? Ans: 255 Subquestion: 3 divided by 37 Ans: 3/37 Subquestion: What is -27 divided by 149? Ans: -27/149 Subquestion: Calculate 69121815 divided by -13824363. Ans: -5 Subquestion: Calculate -104230161 divided by 63. Ans: -1654447 Subquestion: Calculate -45510 divided by 370. Ans: -123 Subquestion: Calculate -40940 divided by 8188. Ans: -5 Subquestion: -392886 divided by 9 Ans: -43654 Subquestion: 8821305 divided by 345 Ans: 25569 Subquestion: -1 divided by -15745780 Ans: 1/15745780 Subquestion: Calculate -143 divided by 373. Ans: -143/373 Subquestion: Divide 30374 by 20. Ans: 15187/10 Subquestion: -116334 divided by 2 Ans: -58167 Subquestion: What is -700 divided by 20? Ans: -35 Subquestion: -4 divided by 109496822 Ans: -2/54748411 Subquestion: Divide -1752 by -1. Ans: 1752 Subquestion: Divide -46427389 by 1. Ans: -46427389 Subquestion: What is -16436 divided by 12? Ans: -4109/3 Subquestion: -6500049 divided by -3 Ans: 2166683 Subquestion: Divide -1170 by 90. Ans: -13 Subquestion: 5 divided by -2808292 Ans: -5/2808292 Subquestion: -176 divided by -44 Ans: 4 Subquestion: What is 126 divided by -6? Ans: -21 Subquestion: Divide 13 by 59. Ans: 13/59 Subquestion: Calculate 6608 divided by 1. Ans: 6608 Subquestion: Divide 881512334 by 5. Ans: 881512334/5 Subquestion: Calculate 117142002 divided by 3. Ans: 39047334 Subquestion: Calculate 1242 divided by -54. Ans: -23 Subquestion: 56 divided by -28 Ans: -2 Subquestion: -270 divided by -6 Ans: 45 Subquestion: Calculate -763649 divided by -106. Ans: 763649/106 Subquestion: Divide 540365 by 5. Ans: 108073 Subquestion: What is 60632842 divided by 200771? Ans: 302 Subquestion: Divide -295942 by -4. Ans: 147971/2 Subquestion: Divide 0 by 600432. Ans: 0 Subquestion: What is 64519 divided by -2? Ans: -64519/2 Subquestion: Calculate 620 divided by 1389055. Ans: 124/277811 Subquestion: Divide 135385955 by 2. Ans: 135385955/2 Subquestion: Calculate 1635 divided by -5. Ans: -327 Subquestion: Divide 26 by 3009642. Ans: 13/1504821 Subquestion: -770065175 divided by 154013035 Ans: -5 Subquestion: Divide 216 by 402227. Ans: 216/402227 Subquestion: 723684236 divided by 1078516 Ans: 671 Subquestion: 5 divided by 1071 Ans: 5/1071 Subquestion: What is 150 divided by 75? Ans: 2 Subquestion: Calculate 210 divided by 3. Ans: 70 Subquestion: Calculate 67496808 divided by -1262. Ans: -53484 Subquestion: Calculate 11 divided by -12718172. Ans: -11/12718172 Subquestion: 350100 divided by 9725 Ans: 36 Subquestion: 135 divided by -6 Ans: -45/2 Subquestion: Divide -158 by -79. Ans: 2 Subquestion: What is 424 divided by -106? Ans: -4 Subquestion: Calculate 79531452 divided by -42. Ans: -1893606 Subquestion: -537738 divided by -38 Ans: 14151 Subquestion: 10364 divided by 1596 Ans: 2591/399 Subquestion: -41373801 divided by -1659 Ans: 24939 Subquestion: Divide 4 by -2891. Ans: -4/2891 Subquestion: Calculate 33394 divided by 824. Ans: 16697/412 Subquestion: Calculate 189 divided by 14. Ans: 27/2 Subquestion: -2 divided by -1972458 Ans: 1/986229 Subquestion: What is 2751108 divided by 3229? Ans: 852 Subquestion: Divide -2525796 by -16191. Ans: 156 Subquestion: Calculate -747628 divided by -4. Ans: 186907 Subquestion: Calculate -6473 divided by -192. Ans: 6473/192 Subquestion: Divide -250470 by -5445. Ans: 46 Subquestion: Calculate 60 divided by 144. Ans: 5/12 Subquestion: What is -130 divided by 95? Ans: -26/19 Subquestion: What is 1832 divided by -4? Ans: -458 Subquestion: Divide 0 by 5750. Ans: 0 Subquestion: What is -4 divided by 268317? Ans: -4/268317 Subquestion: What is -3792278 divided by 2? Ans: -1896139 Subquestion: Calculate -35040 divided by 4. Ans: -8760 Subquestion: Divide 0 by -3771. Ans: 0 Subquestion: Divide 49 by 17. Ans: 49/17 Subquestion: -3150 divided by 350 Ans: -9 Subquestion: What is -212178036 divided by -6? Ans: 35363006 Subquestion: What is -58 divided by -1? Ans: 58 Subquestion: What is 5749920 divided by -3630? Ans: -1584 Subquestion: What is -15 divided by -62938? Ans: 15/62938 Subquestion: Divide 564860 by -1852. Ans: -305 Subquestion: -235 divided by 126515 Ans: -47/25303 Subquestion: Divide -394 by 143. Ans: -394/143 Subquestion: Divide 303955 by -31. Ans: -9805 Subquestion: Divide 5 by 29. Ans: 5/29 Subquestion: -14 divided by -3935 Ans: 14/3935 Subquestion: Calculate -27 divided by 3. Ans: -9 Subquestion: Calculate 552301 divided by 6. Ans: 552301/6 Subquestion: Divide -2646 by 294. Ans: -9 Subquestion: 47435184 divided by 5526 Ans: 8584 Subquestion: Calculate 54957 divided by 7. Ans: 7851 Subquestion: -82 divided by 35 Ans: -82/35 Subquestion: 8213016 divided by -83 Ans: -98952 Subquestion: Calculate -43 divided by 1367. Ans: -43/1367 Subquestion: -626 divided by 118 Ans: -313/59 Subquestion: Calculate 0 divided by 137273. Ans: 0 Subquestion: What is 212189 divided by 4237? Ans: 212189/4237 Subquestion: What is -2965 divided by -258311? Ans: 2965/258311 Subquestion: What is -46596528 divided by 7674? Ans: -6072 Subquestion: Divide 3 by -9. Ans: -1/3 Subquestion: What is 615183 divided by 47? Ans: 13089 Subquestion: What is -11 divided by -795? Ans: 11/795 Subquestion: 62172 divided by 9 Ans: 6908 Subquestion: Calculate 4 divided by 96484. Ans: 1/24121 Subquestion: -3976 divided by -4 Ans: 994 Subquestion: 1388484 divided by -1388484 Ans: -1 Subquestion: 28245267 divided by 9 Ans: 3138363 Subquestion: Divide 752131 by 10. Ans: 752131/10 Subquestion: Divide 3212 by -146. Ans: -22 Subquestion: Divide -499871316 by -15253. Ans: 32772 Subquestion: 1946154 divided by -3 Ans: -648718 Subquestion: Calculate -1920 divided by -120. Ans: 16 Subquestion: What is 77505 divided by -25835? Ans: -3 Subquestion: Calculate 108 divided by 251. Ans: 108/251 Subquestion: What is 5572 divided by 12? Ans: 1393/3 Subquestion: Calculate 33 divided by 6. Ans: 11/2 Subquestion: Calculate 49 divided by -9. Ans: -49/9 Subquestion: Divide -2214 by 357783. Ans: -738/119261 Subquestion: Divide 45316271 by 17017. Ans: 2663 Subquestion: Calculate 12416784 divided by 6. Ans: 2069464 Subquestion: Calculate -142 divided by -5642. Ans: 71/2821 Subquestion: Divide -344 by 3. Ans: -344/3 Subquestion: What is 63427709 divided by 9? Ans: 63427709/9 Subquestion: 1 divided by -79 Ans: -1/79 Subquestion: What is 98939 divided by 2? Ans: 98939/2 Subquestion: What is -68236 divided by 4? Ans: -17059
[{"idx": "txt360/algebra__linear_1d_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-14.jsonl"}, {"idx": "txt360/arithmetic__div_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-14.jsonl"}]
import React, { useEffect, useRef, useState } from 'react'; import { useMutation, useQueryClient } from 'react-query'; import { shallowEqual } from 'react-redux'; import { createPost } from '../../actions/Mutations/createPost'; import { updatePost } from '../../actions/Mutations/updatePost'; import { useAppSelector } from '../../hooks/redux.hooks'; import { IPost } from '../../interfaces/User'; import { popError } from '../../utils/popError'; import { popSuccess } from '../../utils/popSuccess'; import { Container, Form, InputContainer, InputSubmit, Title } from './styles'; interface IPostForm { action: string; title: string; post?: IPost; setEditModal?: React.Dispatch<React.SetStateAction<boolean>>; } const defaultProps = { post: undefined, setEditModal: undefined, }; const PostForm: React.FC<IPostForm> = ({ action, title, post, setEditModal, }) => { const queryClient = useQueryClient(); const { user } = useAppSelector((state) => state.user, shallowEqual); const [disabledSubmit, setDisabledSubmit] = useState(true); const inputTitle = useRef<HTMLInputElement>(null); const textareaContent = useRef<HTMLTextAreaElement>(null); const { mutate: mutateCreatePost } = useMutation(createPost); const { mutate: mutateUpdatePost } = useMutation(updatePost); const checkFieldsContent = () => { const postTitleValue = inputTitle?.current?.value; const contentValue = textareaContent?.current?.value; if ((!postTitleValue || !contentValue) && disabledSubmit) return; if ((!postTitleValue || !contentValue) && !disabledSubmit) { setDisabledSubmit(true); return; } if (disabledSubmit) setDisabledSubmit(false); }; const mutateError = () => { popError( 'An error has ocurred when saving the post, please try again or contact our support.' ); }; const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); const form = e.target as HTMLFormElement; const postTitleValue = inputTitle?.current?.value; const postContentValue = textareaContent?.current?.value; const username = user?.name; if (!postTitleValue || !postContentValue) { return popError('Please fill all fields'); } if (!post) { return mutateCreatePost( { title: postTitleValue, content: postContentValue, username, }, { onSuccess: () => { queryClient.invalidateQueries('posts'); form.reset(); popSuccess('Post created!'); }, onError: mutateError, } ); } return mutateUpdatePost( { id: post.id, body: { title: postTitleValue, content: postContentValue }, }, { onSuccess: () => { queryClient.invalidateQueries('posts'); if (setEditModal) setEditModal(false); popSuccess('Post updated!'); }, onError: mutateError, } ); }; useEffect(() => { checkFieldsContent(); }, []); return ( <Container $post={!!post}> <Title>{title}</Title> <Form action="/" onSubmit={handleSubmit}> <InputContainer> <label htmlFor="title">Title</label> <input ref={inputTitle} type="text" name="title" placeholder="<NAME>" className="input-text" defaultValue={post?.title} onChange={checkFieldsContent} /> </InputContainer> <InputContainer> <label htmlFor="content">Content</label> <textarea ref={textareaContent} placeholder="Content here" name="content" cols={30} rows={5} className="input-text" defaultValue={post?.content} onChange={checkFieldsContent} /> </InputContainer> <div className="flex justify-end"> <InputSubmit type="submit" value={action} disabled={disabledSubmit} /> </div> </Form> </Container> ); }; PostForm.defaultProps = defaultProps; export default PostForm;<|endoftext|>import { NullableId, Params } from '@feathersjs/feathers'; import { Verifier, VersionInfo } from '@unumid/types'; import { Service as MikroOrmService } from 'feathers-mikro-orm'; import { Application } from '../../../declarations'; import { VerifierEntity, VerifierEntityOptions } from '../../../entities/Verifier'; import logger from '../../../logger'; // eslint-disable-next-line @typescript-eslint/no-empty-interface interface ServiceOptions {} export interface VerifierRequestDto { apiKey: string; authToken: string; encryptionPrivateKey: string; signingPrivateKey: string; verifier: Verifier } export interface VerifierResponseDto extends VerifierRequestDto { uuid: string; createdAt: Date; updatedAt: Date; } const makeVerifierEntityOptionsFromRequestDto = (dto: VerifierRequestDto): VerifierEntityOptions => { const { apiKey, authToken, encryptionPrivateKey, signingPrivateKey, verifier: { did: verifierDid, uuid: verifierUuid, createdAt: verifierCreatedAt, updatedAt: verifierUpdatedAt, name: verifierName, customerUuid: verifierCustomerUuid, url: verifierUrl, isAuthorized: verifierIsAuthorized, versionInfo: verifierVersionInfo } } = dto; return { apiKey, authToken, encryptionPrivateKey, signingPrivateKey, verifierDid, verifierUuid, verifierCreatedAt: new Date(verifierCreatedAt), verifierUpdatedAt: new Date(verifierUpdatedAt), verifierName, verifierCustomerUuid, verifierUrl, verifierIsAuthorized, verifierVersionInfo: verifierVersionInfo as VersionInfo[] }; }; const makeVerifierResponseDtoFromEntity = (entity: VerifierEntity): VerifierResponseDto => { const { uuid, createdAt, updatedAt, apiKey, authToken, encryptionPrivateKey, signingPrivateKey, verifierDid, verifierUuid, verifierCreatedAt, verifierUpdatedAt, verifierName, verifierCustomerUuid, verifierUrl, verifierIsAuthorized, verifierVersionInfo } = entity; return { uuid, createdAt, updatedAt, apiKey, authToken, encryptionPrivateKey, signingPrivateKey, verifier: { // attributes from UnumID SaaS did: verifierDid, uuid: verifierUuid, createdAt: verifierCreatedAt.toISOString(), updatedAt: verifierUpdatedAt.toISOString(), name: verifierName, customerUuid: verifierCustomerUuid, url: verifierUrl, isAuthorized: verifierIsAuthorized, versionInfo: verifierVersionInfo, apiKey } }; }; export class VerifierService { app: Application; options: ServiceOptions; dataService: MikroOrmService<VerifierEntity>; constructor (options: ServiceOptions = {}, app: Application) { this.options = options; this.app = app; this.dataService = app.service('verifierData'); } async create (data: VerifierRequestDto, params?: Params): Promise<VerifierResponseDto> { let verifierEntity: VerifierEntity; try { verifierEntity = await this.dataService.create(makeVerifierEntityOptionsFromRequestDto(data), params); } catch (e) { logger.error('VerifierService.create caught an error thrown by VerifierDataService.create', e); throw e; } return makeVerifierResponseDtoFromEntity(verifierEntity); } async get (uuid: NullableId, params?: Params): Promise<VerifierResponseDto> { let verifierEntity: VerifierEntity; try { verifierEntity = await this.dataService.get(uuid, params); } catch (e) { logger.error('VerifierService.get caught an error thrown by VerifierDataService.get', e); throw e; } return makeVerifierResponseDtoFromEntity(verifierEntity); } async patch (uuid: NullableId, params: Partial<VerifierEntity>): Promise<VerifierResponseDto> { let verifierEntity: VerifierEntity; try { verifierEntity = await this.dataService.patch(uuid, params); } catch (e) { logger.error('VerifierService.get caught an error thrown by VerifierDataService.get', e); throw e; } return makeVerifierResponseDtoFromEntity(verifierEntity); } }<|endoftext|>import React, { useState } from 'react' import { inject, observer } from 'mobx-react' import styled from '../../theme/styled' import { FiChevronDown, FiChevronUp, FiTrash } from 'react-icons/fi' import { SearchFacetGroupList } from './SearchFacetGroupList' import { Icon } from '../../elements/Icon' import { Tooltip } from '../../elements/Tooltip' import { Stores } from '../../stores' import { FacetItem } from '../../types/search' interface IProps { className?: string currentMetricsFacets?: FacetItem[] currentTokensFacets?: FacetItem[] resetFacets?: (type: 'metrics' | 'tokens') => void } const SearchFacetsEl = inject((stores: Stores) => ({ currentMetricsFacets: stores.searchFacetsStore.currentMetricsFacets, currentTokensFacets: stores.searchFacetsStore.currentTokensFacets, resetFacets: stores.searchFacetsStore.resetFacets, })) (observer((props: IProps) => { const { className, currentMetricsFacets, currentTokensFacets, resetFacets } = props const [metricsMinimized, setMetricsMinimized] = useState(false) const [tokensMinimized, setTokensMinimized] = useState(false) function handleCloseMetrics() { setMetricsMinimized(!metricsMinimized) resetFacets!('metrics') } function handleCloseTokens() { setTokensMinimized(!tokensMinimized) resetFacets!('tokens') } return ( <Container className={className}> <Group> <FacetGroupHeader> <TitleWrapper> <Title>Metrics</Title> <Tooltip title="Metrics facets" size={20}> <TooltipText> <p> Facets are a feature of Lucene to easily group and filter search results. For any indexed value, such as metrics in this case, you can categorize them based on the counts or ranges of the values. The resulting buckets can be then selected by checking their checkbox. The middle column is the value of the bucket and the right column the count. Current Java metrics are generated using Checkstyle metrics. </p> <p> Whenever you change the facet values, you must rerun the search. Closing a facet will delete its values. If you don't specify a range, the results are the counts of individual values (which is why all metrics are integers). Using a range you can specify its start, end and the gap which is the interval the results are bucketed into. </p> <div> <a href=" [IDX] target="_blank" rel="noopener"> Solr 8.6 docs </a> </div> </TooltipText> </Tooltip> </TitleWrapper> <Icon button onClick={handleCloseMetrics}> { metricsMinimized ? <FiChevronDown size={18}/> : <FiChevronUp size={18}/>} </Icon> </FacetGroupHeader> <SearchFacetGroupList useRange={true} visible={!metricsMinimized} items={currentMetricsFacets || []} /> </Group> <Group> <FacetGroupHeader> <Title>Tokens</Title> <Icon button onClick={handleCloseTokens}> { tokensMinimized ? <FiChevronDown size={18}/> : <FiChevronUp size={18}/>} </Icon> </FacetGroupHeader> <SearchFacetGroupList useRange={false} visible={!tokensMinimized} items={currentTokensFacets || []} /> </Group> </Container> ) })) const Container = styled.div` display: flex; flex-direction: column; margin: 0 2rem; ` const FacetGroupHeader = styled.div` align-items: center; display: flex; width: 100%; ` const Group = styled.div`` const Title = styled.h3` margin-right: 0.5rem; ` const TitleWrapper = styled.div` align-items: center; display: flex; margin-right: 1rem; ` const TooltipText = styled.div` font-size: ${({ theme }) => theme.fontSize.small}; margin: 0; & > div { margin: 0.5rem 0 0 0; } ` export const SearchFacets = styled(SearchFacetsEl)``
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3716.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3716.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3716.jsonl"}]
*/ import { html } from 'lit-element'; import { classMap } from 'lit-html/directives/class-map.js'; import { Dialog } from './dialog.component'; import '@spectrum/sp-button'; import '@spectrum/sp-icon'; export function template(this: Dialog) { const classes = { 'is-open': this.open, 'spectrum-Dialog--noDivider': this.noDivider, 'spectrum-Dialog--error': this.error, 'spectrum-Dialog--dismissible': this.dismissible, 'spectrum-Dialog--small': this.small, 'spectrum-Dialog--medium': this.medium, 'spectrum-Dialog--large': this.large, 'spectrum-Dialog--alert': this.alert, }; // this is added only to manage the demo-dialog display // because spectrum-dialog by defaut display: flex so all the examples // are displayed on top of each other var demoStyles = ''; if (this.top) { demoStyles = `display: block !important; top: ${this.top}px !important; position: relative;`; } if (this.scrolling) { demoStyles = `display: block !important; top: 50% !important; position: absolute; left: 50%; width: 100%;`; } ////////////////////////////////// //Trigger const trigger = []; if (this.trigger) { trigger.push(html` <div ?hidden=${this.open} style=" margin: auto; width: 10%;"> <sp-button primary label="${this.triggerLabel}" @click="${this.display}" ></sp-button> </div> `); } //Button management const buttons = []; if (this.noButtons) { buttons.push(html``); } if (this.error) { buttons.push(html` <sp-button type="primary" class="spectrum-Button spectrum-Button--primary" label="OK" @click="${this.handleCancel}"></sp-button> `); } else if (this.confirmation) { buttons.push(html` <sp-button type="primary" class="spectrum-Button spectrum-Button--primary" label="${this.cancelLabel}" @click="${this.handleCancel}"></sp-button> <sp-button type="cta" class="spectrum-Button spectrum-Button--cta" label="${this.okLabel}" @click="${this.handleOK}"></sp-button> `); } else if (this.information || this.scrolling) { buttons.push(html` <sp-button type="secondary" class="spectrum-Button spectrum-Button--primary" label="${this.cancelLabel}" @click="${this.handleCancel}"></sp-button> <sp-button type="primary" class="spectrum-Button spectrum-Button--cta" label="${this.okLabel}" @click="${this.handleOK}"></sp-button> `); } else if (this.destructive) { buttons.push(html` <sp-button type="secondary" class="spectrum-Button spectrum-Button--primary" label="${this.cancelLabel}" @click="${this.handleCancel}"></sp-button> <sp-button type="warning" class="spectrum-Button spectrum-Button--cta" label="${this.okLabel}" @click="${this.handleOK}"></sp-button> `); } else if (this.threeButtons) { buttons.push(html` <sp-button type="secondary" class="spectrum-Button spectrum-Button--primary" label="${this.cancelLabel}" @click="${this.handleCancel}"></sp-button> <sp-button type="secondary" class="spectrum-Button spectrum-Button--primary" label="${this.thirdBtnLabel}" @click="${this.handleThirdButton}"></sp-button> <sp-button type="primary" class="spectrum-Button spectrum-Button--cta" label="${this.okLabel}" @click="${this.handleOK}"></sp-button> `); } return html` ${trigger} <div class="background-overlay" ?hidden=${!this.open}> <div class="spectrum-Dialog ${classMap(classes)} spectrum-CSSExample-dialog" style="${demoStyles}"> ${(this.hero) ? html`<div class="spectrum-Dialog-hero" style="background-image: url(${this.imageURL})"></div>` : html``} <div class="spectrum-Dialog-header"> <h2 class="spectrum-Dialog-title">${this._title}</h2> ${(this.error) ? html`<sp-icon name="AlertMedium" class="spectrum-Dialog-typeIcon"></sp-icon>` : html``} ${(this.dismissible) ? html`<sp-button type="action" quiet label="" icon="CrossMedium" @click="${this.handleCancel}"></sp-button>` : html``} </div> <div class="spectrum-Dialog-content" style= ${(this.scrolling) ? "height: 87%;" : ""}> <slot></slot> </div> <div class="spectrum-Dialog-footer"> ${buttons} </div> </div> </div> `; } export function templateFullscreen(this: Dialog) { /* let demoStyles = ''; if (this.top) { demoStyles = `display: block !important; top: ${this.top}px !important; position: relative;`; } */ //Trigger const trigger = []; if (this.trigger) { trigger.push(html` <div ?hidden=${this.open} style=" margin: auto; width: 10%;"> <sp-button primary label="${this.triggerLabel}" @click="${this.display}" ></sp-button> </div> `); } return html ` ${trigger} <div class="spectrum-Dialog spectrum-Dialog--fullscreenTakeover" > <div class="spectrum-Dialog-header"> <h2 class="spectrum-Dialog-title">${this._title}</h2> <sp-button type="primary" class="spectrum-Button spectrum-Button--primary" label="${this.cancelLabel}" @click="${this.handleCancel}"></sp-button> <sp-button type="cta" class="spectrum-Button spectrum-Button--cta" label="${this.okLabel}" @click="${this.handleOK}"></sp-button> </div> <div class="spectrum-Dialog-content"> <slot></slot> </div> <div class="spectrum-Dialog-footer"> ${this.footerContent} </div> </div> `; }<|endoftext|>import FS from 'fs' import { SFTPStream } from 'ssh2-streams' import ChildProcess from 'child_process' import { spawn as ptySpawn } from 'node-pty' import ssh2 from 'ssh2' import { PRIVATE_KEY_PATH } from './helpers' const { STATUS_CODE } = ((ssh2.utils as unknown) as { sftp: { STATUS_CODE: Record<string, string> } }).sftp function handleSFTP(accept) { const sftpStream = accept() let dirHandle = 105185 const handles: Set<number> = new Set() const dirHandles: Map<number, string[]> = new Map() sftpStream.on('OPEN', function (reqid, filename, flags) { let handleId try { handleId = FS.openSync(filename, SFTPStream.flagsToString(flags)) } catch (error) { console.error(error) sftpStream.status(reqid, STATUS_CODE.FAILURE) return } handles.add(handleId) const handle = Buffer.alloc(4) handle.write(handleId.toString()) sftpStream.handle(reqid, handle) }) sftpStream.on('READ', function (reqid, givenHandle, offset, length) { const handle = parseInt(givenHandle, 10) if (!handles.has(handle)) { sftpStream.status(reqid, STATUS_CODE.FAILURE) return } const contents = Buffer.alloc(length) try { FS.readSync(handle, contents, 0, length, offset) } catch (error) { sftpStream.status(reqid, STATUS_CODE.FAILURE) return } sftpStream.data(reqid, contents) }) sftpStream.on('WRITE', function (reqid, givenHandle, offset, data) { const handle = parseInt(givenHandle, 10) if (!handles.has(handle)) { sftpStream.status(reqid, STATUS_CODE.FAILURE) return } try { FS.writeSync(handle, data, 0, data.length, offset) sftpStream.status(reqid, STATUS_CODE.OK) } catch (error) { console.error(error) sftpStream.status(reqid, STATUS_CODE.FAILURE) } }) sftpStream.on('FSTAT', function (reqid, givenHandle) { const handle = parseInt(givenHandle, 10) if (!handles.has(handle)) { sftpStream.status(reqid, STATUS_CODE.FAILURE) return } let stats try { stats = FS.fstatSync(handle) } catch (error) { console.error(error) sftpStream.status(reqid, STATUS_CODE.FAILURE) return } sftpStream.attrs(reqid, stats) }) sftpStream.on('CLOSE', function (reqid, givenHandle) { const handle = parseInt(givenHandle, 10) if (dirHandles.has(handle)) { dirHandles.delete(handle) sftpStream.status(reqid, STATUS_CODE.OK) return } if (handles.has(handle)) { handles.delete(handle) FS.close(handle, function () { /* No Op */ }) sftpStream.status(reqid, STATUS_CODE.OK) } else { sftpStream.status(reqid, STATUS_CODE.FAILURE) } }) sftpStream.on('MKDIR', function (reqid, path, attrs) { try { FS.mkdirSync(path, attrs.mode) sftpStream.status(reqid, STATUS_CODE.OK) } catch (error) { sftpStream.status(reqid, STATUS_CODE.FAILURE, error.message) } }) sftpStream.on('STAT', function (reqid, path) { try { const stats = FS.statSync(path) sftpStream.attrs(reqid, stats) } catch (error) { sftpStream.status(reqid, STATUS_CODE.FAILURE, error.message) } }) sftpStream.on('OPENDIR', function (reqid, path) { let stat try { stat = FS.statSync(path) } catch (error) { sftpStream.status(reqid, STATUS_CODE.FAILURE) return } if (!stat.isDirectory()) { sftpStream.status(reqid, STATUS_CODE.FAILURE) return } const contents = FS.readdirSync(path) dirHandle += 1 const currentDirHandle = dirHandle dirHandles.set(currentDirHandle, contents) const handle = Buffer.alloc(8) handle.write(currentDirHandle.toString()) sftpStream.handle(reqid, handle) }) sftpStream.on('READDIR', function (reqid, givenHandle) { const handle = parseInt(givenHandle, 10) const contents = dirHandles.get(handle) if (contents == null || !contents.length) { sftpStream.status(reqid, STATUS_CODE.EOF) return } const item = contents.pop() sftpStream.name(reqid, [ { filename: item, longname: item, attrs: null, }, ]) }) } function handleSession(acceptSession) { const session = acceptSession() // eslint-disable-next-line @typescript-eslint/no-explicit-any let ptyInfo: Record<string, any> | null = null session.on('pty', function (accept, _, info) { accept() ptyInfo = { name: info.term, cols: info.cols, rows: info.rows, cwd: process.env.HOME, env: process.env, } }) session.on('shell', function (accept, reject) { if (!ptyInfo) { reject() return } const request = accept() // eslint-disable-next-line @typescript-eslint/no-explicit-any const spawnedProcess: any = ptySpawn(process.env.SHELL || 'bash', [], ptyInfo) request.pipe(spawnedProcess) spawnedProcess.pipe(request) }) session.on('exec', function (accept, reject, info) { const response = accept() const spawnedProcess = ChildProcess.exec(info.command) response.pipe(spawnedProcess.stdin) spawnedProcess.stdout.pipe(response.stdout) spawnedProcess.stderr.pipe(response.stderr) }) session.on('sftp', handleSFTP) } function handleAuthentication(ctx) { let accept = true if (ctx.method === 'password') { accept = ctx.username === 'steel' && ctx.password === 'password' } if (accept) { ctx.accept() } else { ctx.reject() } } export default function createServer(): ssh2.Server { const server = new ssh2.Server( { hostKeys: [FS.readFileSync(PRIVATE_KEY_PATH)], }, function (client) { client.on('authentication', handleAuthentication) client.on('session', handleSession) }, ) return server }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18802.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18802.jsonl"}]
comparison: pair ---------------- Subquestion: Is 7/15109 at most -12/55? Result: False Subquestion: Is -12658 not equal to 8? Result: True Subquestion: Is -5554636 less than or equal to -5554654? Result: False Subquestion: Are -1/4 and 1711/17 equal? Result: False Subquestion: Is -11840 <= -11798? Result: True Subquestion: Which is greater: -572/48171 or 0? Result: 0 Subquestion: Is -66/734027 smaller than 0? Result: True Subquestion: Is -34438058 != 2? Result: True Subquestion: Which is smaller: 48776 or 48778? Result: 48776 Subquestion: Which is greater: 60 or 64? Result: 64 Subquestion: Is -7267906 != -7267907? Result: True Subquestion: Is -5.28 <= -1? Result: True Subquestion: Is -383809 at most as big as -9211393/24? Result: True Subquestion: Which is greater: 0 or 1732/33787? Result: 1732/33787 Subquestion: Are -61435 and -61459 equal? Result: False Subquestion: Is -65411 equal to -65441? Result: False Subquestion: Is 0 != 12/7637569? Result: True Subquestion: Is -2194 not equal to -2193? Result: True Subquestion: Is -0.03 bigger than -26? Result: True Subquestion: Is -1690 at most 18.3? Result: True Subquestion: Which is bigger: 371010 or 371322? Result: 371322 Subquestion: Which is greater: 2 or 12483/13702? Result: 2 Subquestion: Which is smaller: 930/259 or 3? Result: 3 Subquestion: Which is greater: -30 or -6? Result: -6 Subquestion: Is 554/3097 at least as big as 1? Result: False Subquestion: Which is greater: 38624 or 38621? Result: 38624 Subquestion: Which is bigger: 34.12869 or -0.1? Result: 34.12869 Subquestion: Which is greater: 221749 or 221758? Result: 221758 Subquestion: Is -1.5 > 1104/17? Result: False Subquestion: Which is greater: 0 or 5/7743? Result: 5/7743 Subquestion: Is 69316 less than or equal to 3/4? Result: False Subquestion: Which is greater: -1 or 458746344? Result: 458746344 Subquestion: Are 818344 and 818344 equal? Result: True Subquestion: Which is bigger: 1533072 or -1? Result: 1533072 Subquestion: Which is smaller: -85/13928 or -1? Result: -1 Subquestion: Is -77 less than -678? Result: False Subquestion: Is 268767513 > 268767514? Result: False Subquestion: Which is greater: 26 or -329335? Result: 26 Subquestion: Which is greater: 2/190395 or 1? Result: 1 Subquestion: Which is bigger: -280/7949 or 0? Result: 0 Subquestion: Which is smaller: 242.5 or 1/2? Result: 1/2 Subquestion: Which is smaller: 378 or 172? Result: 172 Subquestion: Is 10960 greater than 10942? Result: True Subquestion: Which is smaller: 5.6 or 4? Result: 4 Subquestion: Which is smaller: -154670425 or -154670424? Result: -154670425 Subquestion: Which is greater: 2 or -576/18385? Result: 2 Subquestion: Is -64/171 at most 0? Result: True Subquestion: Which is bigger: -1 or -63/176? Result: -63/176 Subquestion: Which is bigger: 1718/5 or 5? Result: 1718/5 Subquestion: Which is greater: -1 or -2651/12758? Result: -2651/12758 Subquestion: Is 11 less than or equal to -22? Result: False Subquestion: Is 1 bigger than 13/179? Result: True Subquestion: Which is greater: 16/7661 or -1? Result: 16/7661 Subquestion: Is -274 != -271? Result: True Subquestion: Which is smaller: 414562015 or 414562014? Result: 414562014 Subquestion: Which is smaller: 1 or 1317/10988? Result: 1317/10988 Subquestion: Which is smaller: 131 or 4.4101? Result: 4.4101 Subquestion: Which is smaller: 14/1115 or 113? Result: 14/1115 Subquestion: Which is smaller: -41 or -31? Result: -41 Subquestion: Which is bigger: 10335750 or 10335745? Result: 10335750 Subquestion: Is -0.14 >= 82? Result: False Subquestion: Is -4171 > -3716? Result: False Subquestion: Which is smaller: -189/86 or -2? Result: -189/86 Subquestion: Which is smaller: 5854 or 5? Result: 5 Subquestion: Is 37.9 bigger than -0.66172? Result: True Subquestion: Which is bigger: 84 or 91? Result: 91 Subquestion: Which is smaller: 4604 or 3780? Result: 3780 Subquestion: Is 276 <= 278? Result: True Subquestion: Which is smaller: -6/17477 or 1? Result: -6/17477 Subquestion: Is 6533892/13 equal to 502607? Result: False Subquestion: Which is bigger: -103/145 or -0.04? Result: -0.04 Subquestion: Does 238421 = 238421? Result: True Subquestion: Is -20217/5 less than -4043? Result: True Subquestion: Is -296636 equal to 1? Result: False Subquestion: Which is bigger: -39/10 or -5? Result: -39/10 Subquestion: Which is bigger: -2/459 or -6/43? Result: -2/459 Subquestion: Which is smaller: 2/29 or -676491? Result: -676491 Subquestion: Which is smaller: 8205 or 8191? Result: 8191 Subquestion: Which is greater: 107 or 5? Result: 107 Subquestion: Is -25 at most as big as -25? Result: True Subquestion: Which is smaller: 246437 or 246435? Result: 246435 Subquestion: Are 3052 and 3052 nonequal? Result: False Subquestion: Is 4 >= 56050? Result: False Subquestion: Do 48 and 56/9 have the same value? Result: False Subquestion: Is 17 < 11? Result: False Subquestion: Which is greater: 46.093 or -15.5? Result: 46.093 Subquestion: Which is bigger: -3534 or -166142/47? Result: -3534 Subquestion: Which is smaller: 24218 or 24256? Result: 24218 Subquestion: Is 502.8 <= -882? Result: False Subquestion: Which is smaller: 17 or 409? Result: 17 Subquestion: Is -14633 smaller than -0.02? Result: True Subquestion: Is 14205 bigger than 14206? Result: False Subquestion: Is -3407 at most as big as -3466? Result: False Subquestion: Is 97/102002 >= 1? Result: False Subquestion: Which is smaller: -0.2 or -4858? Result: -4858 Subquestion: Is 0.45 smaller than 4393? Result: True Subquestion: Is 50293222 equal to 50293222? Result: True Subquestion: Which is bigger: -1386 or -1387? Result: -1386 Subquestion: Which is smaller: -1/1435 or 1? Result: -1/1435 Subquestion: Which is bigger: 0 or -9/7007332? Result: 0 Subquestion: Is 3215/36 >= 90? Result: False Subquestion: Which is bigger: 802 or -1/3? Result: 802 Subquestion: Is -1408/59 at least -25? Result: True Subquestion: Which is bigger: 245939 or 32? Result: 245939 Subquestion: Which is smaller: 0.25 or -5.3? Result: -5.3 Subquestion: Do 1211 and 828 have the same value? Result: False Subquestion: Is 53723 >= 54060? Result: False Subquestion: Which is bigger: -22/28607547 or 0? Result: 0 Subquestion: Is -52731334/19 equal to -2775334? Result: False Subquestion: Is 0.042 less than -1745/48? Result: False Subquestion: Is -4 <= 534755? Result: True Subquestion: Which is greater: -0.273 or -7? Result: -0.273 Subquestion: Are -2 and -35/33 non-equal? Result: True Subquestion: Which is greater: -1 or -1/9055? Result: -1/9055 Subquestion: Are 442 and 441 non-equal? Result: True Subquestion: Is 5023 not equal to -3/2? Result: True Subquestion: Does 0 = -721? Result: False Subquestion: Which is bigger: 3/5502530 or 0? Result: 3/5502530 Subquestion: Is 1 less than -113363/4537? Result: False Subquestion: Is -76 greater than or equal to -69? Result: False Subquestion: Which is greater: 83/118237 or -1? Result: 83/118237 Subquestion: Is -2738970/83 at most as big as -33000? Result: False Subquestion: Which is smaller: 247660 or 247658? Result: 247658 Subquestion: Is -688143 at most as big as -688141? Result: True Subquestion: Which is smaller: 12/23 or -0.43? Result: -0.43 Subquestion: Which is bigger: 103478/551 or 188? Result: 188 Subquestion: Does -1 = 44/4063? Result: False Subquestion: Which is greater: 106/48787 or 1? Result: 1 Subquestion: Which is bigger: 25666 or 25676? Result: 25676 Subquestion: Which is bigger: -20864 or -1460399/70? Result: -1460399/70 Subquestion: Which is smaller: -776.6 or 0.2? Result: -776.6 Subquestion: Which is smaller: -143016/61 or -0.45? Result: -143016/61 Subquestion: Which is smaller: 180 or 182? Result: 180 Subquestion: Which is smaller: 1270947 or 1270946? Result: 1270946 Subquestion: Which is smaller: 229 or 228? Result: 228 Subquestion: Which is bigger: 338 or 7795/23? Result: 7795/23 Subquestion: Is 4865 != 13990? Result: True Subquestion: Is -10906/9 equal to -1212? Result: False Subquestion: Is 7229 at least 62/9? Result: True Subquestion: Which is smaller: 31 or 13479/451? Result: 13479/451 Subquestion: Is 1486 smaller than 3? Result: False Subquestion: Is 1 < -10/487? Result: False Subquestion: Are -84805/167 and 2 unequal? Result: True Subquestion: Is -721012/711 <= -1014? Result: True Subquestion: Is -0.04 at least as big as 0.3752? Result: False Subquestion: Is -21309 at least as big as -21310? Result: True Subquestion: Which is smaller: -82861444 or -82861447? Result: -82861447 Subquestion: Is 17/19 > 1? Result: False Subquestion: Do 5 and 40603/8722 have the same value? Result: False Subquestion: Which is smaller: -1794 or -93345/52? Result: -93345/52 Subquestion: Is 2056920 at least as big as -1/4? Result: True Subquestion: Which is greater: -7557/6763 or -2? Result: -7557/6763 Subquestion: Which is smaller: 11639751 or 11639750? Result: 11639750 Subquestion: Is 3 < 757.7? Result: True Subquestion: Is -4.1 less than 2.73? Result: True Subquestion: Which is smaller: -12 or -14? Result: -14 Subquestion: Is -13 < -15? Result: False Subquestion: Is 0 less than 2.14? Result: True Subquestion: Which is bigger: -74061076 or -74061071? Result: -74061071 Subquestion: Which is smaller: 2/9 or -2.07? Result: -2.07<|endoftext|>arithmetic: div --------------- Item: What is 4124592 divided by -2? Therefore: -2062296 Item: Divide -338 by 53749. Therefore: -338/53749 Item: What is 241564 divided by 4? Therefore: 60391 Item: Calculate 309455 divided by 61891. Therefore: 5 Item: What is -492028 divided by -2? Therefore: 246014 Item: Calculate 0 divided by 110. Therefore: 0 Item: 5037 divided by -811 Therefore: -5037/811 Item: Divide 15630576 by -6. Therefore: -2605096 Item: -5 divided by -467652 Therefore: 5/467652 Item: 4 divided by -135 Therefore: -4/135 Item: Calculate -805 divided by -35. Therefore: 23 Item: Calculate -26 divided by -9. Therefore: 26/9 Item: Calculate 942 divided by 6. Therefore: 157 Item: Divide 3861 by -3. Therefore: -1287 Item: What is -153674529 divided by 153674529? Therefore: -1 Item: What is -718117821 divided by 3030033? Therefore: -237 Item: Calculate 7 divided by -299570. Therefore: -7/299570 Item: Calculate -6894210 divided by -74. Therefore: 93165 Item: 190 divided by 3811045 Therefore: 38/762209 Item: Divide -1503390 by 250565. Therefore: -6 Item: What is 978 divided by -54? Therefore: -163/9 Item: What is -7 divided by 267? Therefore: -7/267 Item: 1 divided by 78 Therefore: 1/78 Item: Divide 2883 by 31. Therefore: 93 Item: -11 divided by 81140 Therefore: -11/81140 Item: Divide -87400920 by 60. Therefore: -1456682 Item: What is 419730 divided by 12345? Therefore: 34 Item: What is -1098 divided by 6? Therefore: -183 Item: Calculate 2 divided by -249. Therefore: -2/249 Item: Divide 11436 by 2. Therefore: 5718 Item: Divide 456360 by -49. Therefore: -456360/49 Item: What is 0 divided by -422063? Therefore: 0 Item: Calculate -5 divided by -2866. Therefore: 5/2866 Item: 512664790 divided by -46605890 Therefore: -11 Item: What is -612 divided by 3? Therefore: -204 Item: 0 divided by -552 Therefore: 0 Item: Divide 35769 by 3. Therefore: 11923 Item: What is -2 divided by 81916496? Therefore: -1/40958248 Item: Calculate 1487 divided by 66. Therefore: 1487/66 Item: What is 2970 divided by -5? Therefore: -594 Item: Calculate 130658 divided by 2. Therefore: 65329 Item: 12816 divided by 4 Therefore: 3204 Item: Calculate -1392 divided by -94. Therefore: 696/47 Item: What is -3016 divided by 140355? Therefore: -3016/140355 Item: What is 11100114 divided by 1? Therefore: 11100114 Item: -957 divided by -25 Therefore: 957/25 Item: Calculate 0 divided by -4088. Therefore: 0 Item: -17140 divided by 2 Therefore: -8570 Item: What is 0 divided by -582673? Therefore: 0 Item: 1707 divided by -91171 Therefore: -1707/91171 Item: Calculate -4633 divided by 2482. Therefore: -4633/2482 Item: Divide 123845 by 3995. Therefore: 31 Item: -22653 divided by 136 Therefore: -22653/136 Item: What is -225 divided by -327130? Therefore: 45/65426 Item: What is -5 divided by -8844521? Therefore: 5/8844521 Item: Calculate 3 divided by -3627515. Therefore: -3/3627515 Item: Divide -5581 by 3. Therefore: -5581/3 Item: What is 4 divided by -2783? Therefore: -4/2783 Item: -2480 divided by -4 Therefore: 620 Item: Calculate -104238 divided by 5791. Therefore: -18 Item: Divide 2436108 by -1218054. Therefore: -2 Item: Calculate 1 divided by -13. Therefore: -1/13 Item: 89324 divided by 326 Therefore: 274 Item: Divide -1 by -867. Therefore: 1/867 Item: Divide 4482 by 83. Therefore: 54 Item: -1630 divided by -326 Therefore: 5 Item: 337 divided by 460 Therefore: 337/460 Item: Calculate -2 divided by 953. Therefore: -2/953 Item: What is 3 divided by 5091353? Therefore: 3/5091353 Item: What is -523917332 divided by -6092062? Therefore: 86 Item: -70 divided by 19 Therefore: -70/19 Item: Divide 7728 by -14. Therefore: -552 Item: Calculate 9995748 divided by 3331916. Therefore: 3 Item: -601159065 divided by 284505 Therefore: -2113 Item: Divide -8 by 2. Therefore: -4 Item: What is -66847 divided by -1133? Therefore: 59 Item: What is 3 divided by -4572410? Therefore: -3/4572410 Item: What is 388 divided by 152672? Therefore: 97/38168 Item: What is -260 divided by 54952? Therefore: -65/13738 Item: Calculate 202730 divided by -2. Therefore: -101365 Item: What is -241615520 divided by -3370? Therefore: 71696 Item: What is 132 divided by -4? Therefore: -33 Item: Calculate 43700 divided by -16118. Therefore: -21850/8059 Item: Divide -426 by -213. Therefore: 2 Item: What is 90 divided by -188? Therefore: -45/94 Item: Divide -7 by 128782. Therefore: -7/128782 Item: Calculate -1335 divided by 1490. Therefore: -267/298 Item: 37548900 divided by -41721 Therefore: -900 Item: Divide 5633822 by 5. Therefore: 5633822/5 Item: Divide 49370 by -1688. Therefore: -24685/844 Item: What is 957 divided by 1? Therefore: 957 Item: Divide 23991 by -23991. Therefore: -1 Item: -424 divided by 424 Therefore: -1 Item: What is -496445 divided by 1? Therefore: -496445 Item: Divide 24 by 6. Therefore: 4 Item: 752 divided by 71 Therefore: 752/71 Item: What is -288 divided by 72? Therefore: -4 Item: What is 5 divided by 255? Therefore: 1/51 Item: Divide -4 by 155. Therefore: -4/155 Item: Calculate 3 divided by -14. Therefore: -3/14 Item: 128820934 divided by -22 Therefore: -5855497 Item: Calculate -885 divided by 7. Therefore: -885/7 Item: -65166 divided by -6 Therefore: 10861 Item: Divide 12357981 by 457703. Therefore: 27 Item: Divide -71 by 11. Therefore: -71/11 Item: What is 4 divided by -3? Therefore: -4/3 Item: Divide 3961748 by -1394. Therefore: -2842 Item: Divide -11 by -38. Therefore: 11/38 Item: What is 4 divided by 430? Therefore: 2/215 Item: Divide 66448852 by 16612213. Therefore: 4 Item: What is -1714 divided by 309? Therefore: -1714/309 Item: Divide -3900 by -12. Therefore: 325 Item: Calculate -26 divided by -53027. Therefore: 2/4079 Item: -29222608 divided by -4 Therefore: 7305652 Item: Calculate 135135 divided by -135135. Therefore: -1 Item: -23959 divided by -97 Therefore: 247 Item: What is 26400556 divided by 13200278? Therefore: 2 Item: Divide 78295 by -7. Therefore: -11185 Item: Divide 111965 by -22393. Therefore: -5 Item: Divide 3 by -35. Therefore: -3/35 Item: Calculate 262940 divided by -65735. Therefore: -4 Item: Calculate -32901136 divided by -4. Therefore: 8225284 Item: 1855 divided by -113 Therefore: -1855/113 Item: Divide 1813 by -1813. Therefore: -1 Item: -12421560 divided by 5 Therefore: -2484312 Item: Calculate 27 divided by -23. Therefore: -27/23 Item: 0 divided by 12 Therefore: 0 Item: 2 divided by 270861 Therefore: 2/270861 Item: What is -1729 divided by 2? Therefore: -1729/2 Item: Divide -59 by 59. Therefore: -1 Item: 907941 divided by -3 Therefore: -302647 Item: Calculate -40416274 divided by 7822. Therefore: -5167 Item: 132 divided by -163674 Therefore: -22/27279 Item: Calculate 6335866 divided by 5. Therefore: 6335866/5 Item: -5 divided by -193291 Therefore: 5/193291 Item: Calculate -1 divided by -63968. Therefore: 1/63968 Item: -25372 divided by 2 Therefore: -12686 Item: Calculate 115 divided by -23. Therefore: -5 Item: -41 divided by -19 Therefore: 41/19 Item: Calculate 4 divided by 12923363. Therefore: 4/12923363 Item: What is -5 divided by 169? Therefore: -5/169 Item: -10715494 divided by -6 Therefore: 5357747/3 Item: Calculate -648 divided by 3. Therefore: -216 Item: Divide -52383 by -2151. Therefore: 17461/717 Item: Divide 356 by -1188923. Therefore: -356/1188923 Item: -24543 divided by -24543 Therefore: 1 Item: Calculate 78432 divided by 57. Therefore: 1376 Item: What is 519167 divided by -3? Therefore: -519167/3 Item: Calculate -2442395 divided by -3695. Therefore: 661 Item: What is 61081 divided by -1268? Therefore: -61081/1268 Item: What is -5 divided by 468295? Therefore: -1/93659 Item: Divide -591045604 by -1174. Therefore: 503446 Item: What is -4 divided by -14? Therefore: 2/7 Item: 12018688 divided by 194 Therefore: 61952 Item: 491318 divided by -375 Therefore: -491318/375 Item: Calculate -13750 divided by -2. Therefore: 6875 Item: 1 divided by -183 Therefore: -1/183 Item: Calculate 683 divided by 35. Therefore: 683/35 Item: Divide 0 by -2878. Therefore: 0 Item: Calculate 10148 divided by -421. Therefore: -10148/421 Item: Divide 39154 by 4. Therefore: 19577/2 Item: Calculate 825488 divided by -8. Therefore: -103186 Item: What is -20513 divided by 137? Therefore: -20513/137 Item: Divide 16 by -2495. Therefore: -16/2495 Item: -8 divided by 107297 Therefore: -8/107297 Item: Divide 255254 by -2. Therefore: -127627 Item: -24513720 divided by 1470 Therefore: -16676 Item: Divide -34 by 15048. Therefore: -17/7524 Item: -18309 divided by 6103 Therefore: -3 Item: Calculate -648 divided by 27. Therefore: -24 Item: Divide 378 by -27. Therefore: -14 Item: Divide -346533 by -3. Therefore: 115511 Item: Divide -18407 by 14. Therefore: -18407/14 Item: What is -418620 divided by -5? Therefore: 83724 Item: Divide -1816 by 454. Therefore: -4 Item: Divide -40782 by 2. Therefore: -20391 Item: Calculate -70533984 divided by -24. Therefore: 2938916 Item: Calculate -214 divided by -129054. Therefore: 107/64527 Item: Divide -462 by 22. Therefore: -21 Item: -1163793 divided by 158 Therefore: -1163793/158 Item: 5 divided by -43421 Therefore: -5/43421 Item: 2030 divided by -187 Therefore: -2030/187 Item: 90340387 divided by 557 Therefore: 162191
[{"idx": "txt360/comparison__pair_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-8.jsonl"}, {"idx": "txt360/arithmetic__div_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-8.jsonl"}]
On the installation of mpi.h for C in Ubuntu Question: I would like to start with MPI/C and I want to compile/execute the standard program mpi_hello. I succeeded regarding mpicc but I got an error message when I compile the file. Here is the program: <code>#include <mpi.h> #include <stdio.h> int main (int argc, char* argv[]) { int mynode, totalnodes; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD, &totalnodes); MPI_Comm_rank(MPI_COMM_WORLD, &mynode); printf( "\nHello world from process %d of %d\n", mynode, totalnodes ); if(totalnodes==1) printf("You have just one processor!\n"); MPI_Finalize(); return 0; } </code> I got the following: <code>turb@turb-LIFEBOOK-AH531:~/Desktop/Prog$ mpicc mpi_hello.c turb@turb-LIFEBOOK-AH531:~/Desktop/Prog$ cc -O3 mpi_hello.c mpi_hello.c:6:17: fatal error: mpi.h: No such file or directory #include <mpi.h> ^ compilation terminated. </code> I would appreciate your help. Thank you! a Answer: Can you try: <code>module add gcc mpich2 mpicc mpi_hello.c </code> ? Edit: Oh wow, I completely misread your post. You successfully compiled it by the looks of it with mpicc hello_world.c Now you should be able to execute a.out with <code>mpirun -np 2 ./a.out </code> where 2 = the number of processors. Using your code and a fresh install: <code>beaty@korriban:~$ mpicc test.c beaty@korriban:~$ mpirun ./a.out Hello world from process 0 of 1 You have just one processor! beaty@korriban:~$ mpirun -np 2 ./a.out Hello world from process 0 of 2 Hello world from process 1 of 2 </code> Comment: Ah. I suppose that is specific to my university cluster. You installed on ubuntu via: sudo apt-get install libcr-dev mpich2 mpich2-doc ? Comment: Thank you wbt11a for your answer. Yes! It works well. However, module add gcc mpich2 is always ignored. I get: module: command not found. Furthermore, we don't compile the file. Actually, I have a more complicated program and I have to compile it. Using cc -O3 gives a fatal error: mpi.h not such a file of directory! How strange!! Comment: Don't worry about the module add commands. That was my mistake. Are you able to run "mpirun -np 2 ./a.out"? Comment: Yes! I can run it and it gives me 2 identical statements since I have just 1 proc. Comment: Do you know any other command instead of cc -O3 mpi_hello.c ? I think that the problem is just in the correct syntax which it has to be used for compilation! Comment: Yes! It works but cc -O3 mpi_hello.c leaves the previous error message! Comment: You cant compile OpenMPI with cc to my knowledge. Thats what mpicc does. BTW, if this answered your question please accept it=) Comment: Okay wbt11a! Thank you for your answers. Do you mean that it is not necessary to compile with cc? just mpicc can do successfully the job? Comment: Yes. mpicc is the openmpi compiler. You do not need to compile with cc - or you will get mpi.h not found error. Also, make sure you run your mpicc compiled programs with mpirun. Answer: You'll need to make sure your include path is updated so the compiler can find mpi.h if it's not installed in a standard location. Comment: I installed MPI in the same directory as the program. I think that there is a problem in the compilation command! Any help please? a Comment: The local directory is not necessarily included in the include search path. Try #include "mpi.h" if the header file is in your local directory and check if that fixes the problem. Comment: Thank you for your answer, but I doesn't work as well with#include "mpi.h". I succeeded to use mpicc but not cc -O3. Do you have any other suggestion please!? :/ Comment: Thank you Timo and wbt11a for your helps!! :D Answer: When using MPI you are nor allowed to use cc -O3 name.c to compile your program. The correct command for compilation is: mpicc -O3 name.c. The command mpicc name.c has nothing to do here. Here is what you get for just one proc: <code>turb@turb-LIFEBOOK-AH531:~/Desktop/Prog$ mpicc -O3 mpi_hello.c turb@turb-LIFEBOOK-AH531:~/Desktop/Prog$ ./a.out Hello world from process 0 of 1 You have just one processor! </code> You may also use for more than one processor (e.g. 2) mpirun -np 2 ./a.out as mentioned above. I hope this could help a bit! Comment: mpicc is just a wrapper around your C compiler. It is not required to compile an MPI program. You can usually see what mpicc actually calls if you run `mpicc -show`<|endoftext|>How to determine which files are necessary in /bin, /lib, /var, etc.? Question: I'm currently trying to get an image working for a network boot using somebody else's file contents. The previous images I made keeping all original files present were way too big, so I need to shrink down the size of the necessary directories. Looking through the contents of these directories though, like /bin, /dev, /etc, etc., I really can't tell what's crucial to the system versus what is extra stuff specific to certain programs that were installed (which are not needed on the image). I don't want to delete anything important, though. The biggest directories by far are /etc, /lib, and /usr, all hundreds of MB larger than the equivalent directories of an image I previously got to work in the past. Because of this, I know that there's a lot of extra stuff in these directories. At the same time, I'm using a different operating system version (SL5 instead of SL4) so I'm not sure about comparing and contrasting those, especially since the filesystems had different things installed on them anyway. Is there a quicker way to either sort what's needed versus what isn't, or to delete a lot of the extra "crap" files? (E.g. one recommendation was to delete everything labelled as documentation, but that's still not enough.) Comment: For a long-term project to give you a depth of understanding on this subject, you might like to check out ["Linux From Scratch."]( [IDX] Do you have an idea of what functionality you need? DHCP, ssh server, your locally-developed software, compression utilities, X Windows, etc.? Comment: Your're going about this in precisely the wrong way. Don't start with a large image and remove files, instead start from a bare-minimum base install (of whatever OS you want to use) and then add only the things you need. Answer: You should not delete files directly from system directories. Instead you should remove unneeded packages. In this manner, the system will remove unnecessary files and its dependences. Note: you can remove every file (but not directories) in <code>/var/cache</code>. Additionally old logs in <code>/var/log/</code> could be removed. Check about unread system mails (<code>/var/mail/</code> or <code>/var/spool</code>). Comment: How would I remove the packages? I'm working with these files before they've been mounted as root and the system/any sort of relevant kernel has actually been booted. I.e. if I uninstall a package, it would be on the OS that's actually running. Would chroot work here? Also, I just checked /var/cache and the only contents in there are directories (coolkey, fontconfig, foomatic, man, mod_proxy, samba, yum--that's all of them). Can I remove their contents at all? (Also directories from what I can see.) Comment: I take it "SL5" is Scientific Linux 5, in which case you'd be using `rpm -e` to remove packages. `rpm` supports a `--root` option to handle use-cases similar to yours; it handles everything properly (`chroot` where appropriate etc.). Answer: Keeping in mind that you should be removing packages (rather than individual files), I would first ensure that the filesystem supports the update of access-time when a program is executed, and then check which packages have not been used since the last boot-time. Assuming normal use of your system, that's as good a first guess at unused packages as you'll need. I've done this before (a moderately complicated script). That can be done by using <code>find</code> to look for files in your path (e.g., <code>/bin</code>, <code>/usr/bin</code>, etc), which have not been accessed "recently" (since the last reboot) for each file in that list, keep track of the corresponding package and the most recently-used file belonging to the package (you can use <code>rpm -ql</code> packagename to get the list of files). review the list of packages versus access dates and present a report of potentially unused packages (and their sizes). Comment: I don't have packagename installed and not sure if I can install it right now. Is there another way of checking for the second part? I'm also still unsure how I would uninstall packages in general since I haven't actually booted up this system yet... See the comment on the other answer. Comment: I meant *packagename* for the given package you are examining, and pointed to `rpm` because it provides a way to list the files belonging to the package.<|endoftext|>Cardinality of the set of open functions? Question: I was wondering what is the cardinality of the set $ \{ f : \mathbb{R} \to \mathbb{R} \mid f \text{ is open } \} $ (i.e., $f(U) \subseteq \mathbb{R}$ is open for all open $U$). There are at least $c = 2^{\aleph_0}$ such functions, since all linear maps $f(x) = ax$ with $a \neq 0$ are open. If we add the condition $f$ continuous, or $f$ injective, it's easy to see that there are no more than $2^{\aleph_0}$ functions. But I don't know if there are a lot of open functions which are neither injective nor continuous. Comment: Even easier, take *any* permutation of $\Bbb R$ and compose it on Conway base 13 function, that every non-degenerate closed interval is mapped onto $\Bbb R$ itself. It follows that there are $2^\frak c$ maps which send every non-empty open set to $\Bbb R$ itself. Comment: @tetori Yes, it does. Nice question. Why don't you post this as an answer? (The number is $2^{\mathfrak c}$.) Comment: I think [Brian M. Scott's construction]( [IDX] is useful to solve this problem. Answer: OK, here is the suggestion given by @tetori. Let $\mathfrak c=|\mathbb R|$. Write $A\sim B$ for "There is a bijection between $A$ and $B$." Note first that $2^{\mathfrak c}=\mathfrak c^{\mathfrak c}$. We start by claiming that there are $2^{\mathfrak c}$ bijections $\pi:\mathbb R\to\mathbb R$. This is because $\mathbb R\sim \mathbb R\times\{0,1\}$. Given any function $f:\mathbb R\to 2$, it can be coded via a bijection $$\pi_f:\mathbb R\times\{0,1\}\to\mathbb R\times\{0,1\}$$ as follows: If $f(x)=0$, let $\pi_f(x,i)=(x,i)$ for $i=0,1$. If $f(x)=1$, let $\pi_f(x,i)=(x,1-i)$ for $i=0,1$. With that out the way, note that $\mathbb R/\mathbb Q$ has size $\mathfrak c$, where $\mathbb R/\mathbb Q$ is the collection of equivalence classes of Vitali's equivalence relation that identifies $x,y\in\mathbb R$ iff $x-y\in\mathbb Q$. Write $[x]$ for the equivalence class of $x$ under this relation. Brian's construction associates to each bijection $h:\mathbb R/\mathbb Q\to \mathbb R$ an open map $f_h:\mathbb R\to\mathbb R$ via $$ f_h(x)=h([x]). $$ The point is that, as explained in the link, $f_h(U)=\mathbb R$ for any nontrivial open set $U$, since any $U$ intersects each equivalence class, so $f_h$ is open. But the association $h\mapsto f_h$ is injective, so there are at least as many open maps as there are bijections between $\mathbb R/\mathbb Q$ and $\mathbb R$. We already argued that there are $2^{\mathfrak c}$ bijections between $\mathbb R\times\{0,1\}$ and itself, and since $$\mathbb R\times\{0,1\}\sim\mathbb R\sim\mathbb R/\mathbb Q,$$ there are $2^{\mathfrak c}$ bijections $h:\mathbb R/\mathbb Q\to\mathbb R$. Since this is the same as the total number of functions $g:\mathbb R\to\mathbb R$, we cannot have more than that. So there are precisely $2^{\mathfrak c}$ open maps. In a comment, Asaf suggests to use Conway's base 13 function in a similar fashion. This function, call it $c$, also has the key property $(*)$: The image of every nontrivial interval is $\mathbb R$, so if $f$ is a permutation of $\mathbb R$, then $f\circ c$ gives an open map, as before. Different permutations $f$ give rise to different functions $f\circ c$ so, again, we obtain $2^{\mathfrak c}$ open functions this way, with the additional niceness brought up by using $c$ instead of an arbitrary $c'$ with property $(*)$. (Thanks to @hot_queen for solving the problem I was having with this neat argument.) Comment: Let $c: \mathbb{R} \rightarrow \mathbb{R}$ be any function sending all intervals onto $\mathbb{R}$. If $f_1, f_2$ are different surjections from reals to reals, then isn't it clear that $f_1 \circ c$ and $f_2 \circ c$ are different? Comment: @hot_queen Yes, of course! I kept thinking of $c\circ f_1$ and $c\circ f_2$, which is how I interpreted the suggestion. Answer: Another easy way to get the desired functions is to construct an infinite sequence of pairwise disjoint nowhere dense perfect sets, so that each rational interval contains one of them, and map each of those perfect sets onto the whole line. This defines a real-valued function on a meager subset of the line. You can give it arbitrary values on the remaining comeager set. In this way you get $2^\frak c$ different functions, each of which maps every nonempty open set onto the whole line. I believe this is the standard way of constructing such functions, but I'm too lazy to try and look it up.
[{"idx": "On_the_installation_of_mpi.h_for_C_in_Ubuntu", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-14617.jsonl"}, {"idx": "How_to_determine_which_files_are_necessary_in_/bin,_/lib,_/var,_etc.?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-14617.jsonl"}, {"idx": "Cardinality_of_the_set_of_open_functions?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-14617.jsonl"}]
How do I use getData() to plot a LineChart with ObjC PNChart library in Swift? Question: I am a newbie programmer and recently started learning Swift. I am making a project in Swift and my intention is to plot a user-introduced signal function in the same View where the parameters are introduced (using a subView controlled by the class PNLineChart). The fact is that I installed PNChart library using CocoaPods, using a bridging header for the Objective C headers. The thing is that the way to use the clases and methods in ObjC is "translating" them to Swift syntax. I found that PNChart has a Swift implementation made by the author, but is not available by Pods (if someone knows how to put them into my project it will be helpful too). Well, the ObjC code to make the plot of an array given by the author in its wiki is the following: <code>#import "PNChart.h" //For Line Chart PNLineChart * lineChart = [[PNLineChart alloc] initWithFrame:CGRectMake(0, 135.0, SCREEN_WIDTH, 200.0)]; [lineChart setXLabels:@[@"SEP 1",@"SEP 2",@"SEP 3",@"SEP 4",@"SEP 5"]]; // Line Chart No.1 NSArray * data01Array = @[@60.1, @160.1, @126.4, @262.2, @186.2]; PNLineChartData *data01 = [PNLineChartData new]; data01.color = PNFreshGreen; data01.itemCount = lineChart.xLabels.count; data01.getData = ^(NSUInteger index) { CGFloat yValue = [data01Array[index] floatValue]; return [PNLineChartDataItem dataItemWithY:yValue]; }; // Line Chart No.2 NSArray * data02Array = @[@20.1, @180.1, @26.4, @202.2, @126.2]; PNLineChartData *data02 = [PNLineChartData new]; data02.color = PNTwitterColor; data02.itemCount = lineChart.xLabels.count; data02.getData = ^(NSUInteger index) { CGFloat yValue = [data02Array[index] floatValue]; return [PNLineChartDataItem dataItemWithY:yValue]; }; lineChart.chartData = @[data01, data02]; [lineChart strokeChart]; </code> So I tried to convert it to Swift, where: inputSignal : UITextField! -> will be the textField where the user introduces the mathematical function (this is still under development) other IBOutlet -> Parameters to set the function limits and the global chart limits inputSignalLineChart: PNLineChart! -> connection of the subView to the ViewController initSignalExample -> initial array to test the plotting signalObtainedValues -> declaration of the PNLineChartData type Inside the viewDidLoad() function I am initiating an initial chart to test if it works in the View. The problem comes when I try to use the method getData() that is defined in the PNLineChartData class and I am not really able to translate it to a correct Swift code. My understanding is that getData has as input an UInteger called index (I think it will select the individual data, but I do not see it declared anywhere :-/) and as output it returns a PNLineChartDataItem(). As I see in the ObjC code, the way to do this is somewhat like PNLineChartDataItem(y: CGFloat) so I suppose that I can do the code as I show you below: <code>import UIKit class ViewController: UIViewController, PNChartDelegate{ @IBOutlet weak var inputSignal: UITextField! @IBOutlet weak var initialTimeInputSignal: UITextField! @IBOutlet weak var finalTimeInputSignal: UITextField! @IBOutlet weak var initialGlobalTime: UITextField! @IBOutlet weak var finalGlobalTime: UITextField! @IBOutlet weak var inputSignalLineChart: PNLineChart! let screenWidth = UIScreen.mainScreen().bounds.size.width let screenHeight = UIScreen.mainScreen().bounds.size.height let initSignalExample = [0.0, 1.0, 1.0, 1.0, 0.0] let signalObtainedValues: PNLineChartData! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. view.backgroundColor = UIColor.cyanColor() inputSignalLineChart.delegate = self inputSignalLineChart.frame = CGRectMake(0, 135.0, screenWidth, screenHeight) inputSignalLineChart.backgroundColor = UIColor.whiteColor() inputSignalLineChart.setXLabels(["0","1","2","3","4"], withWidth: 1) //signalObtainedValues.color = UIColor.greenColor() //signalObtainedValues.itemCount = UInt(inputSignalLineChart.xLabels.count) signalObtainedValues.getData(UInt(index)) = { PNLineChartDataItem(y: CGFloat(initSignalExample[index])) } //inputSignalLineChart.chartData = [signalObtainedValues] inputSignalLineChart.strokeChart() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } </code> Trying and trying I only get the error: Cannot assign to the result of this expression, in the getData() line. So I think this is for the syntax of the code I have made in Swift. Has anyone any idea of how to do this and correctly draw the chart in the subview? Any answer or helpful tip will be appreciated. Thank you! Answer: Maybe this can be written in closure like the following: <code>signalObtainedValues.getData() = { index in let yValue: CGFloat = initSignalExample[UInt(index)] return PNLineChartDataItem(y: yValue) } </code> Comment: Thank you very much for taking your time to answer. Unfortunately this solution is not working. As I can see on the libraries, getData() must have as an input a UInt(index)). If I put getData() without any parameter, the compiler tells me that there is **a missing argument for parameter #1 in call**, so I understand that the UInt index has to be the input parameter of getData(). If I try your code putting the index inside getData() I keep getting the **error: Cannot assign to the result of this expression**. Comment: Well, now I tried some different things and the one which gets me another error is: `signalObtainedValues.getData = { index in let yValue: CGFloat = self.initSignalExample[UInt(index)] return PNLineChartDataItem(y: yValue) }`. The error I got this time in the line of `yValue: CGFloat` is this one: **could not find an overload for 'init' that accepts the supplied arguments.** Answer: I finally got a solution for the problem. The code that works for me is the following: <code>override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. view.backgroundColor = UIColor.cyanColor() playButton.layer.backgroundColor = UIColor.whiteColor().CGColor playButton.layer.cornerRadius = 5 let initSignalExample = [0.0, 1.0, 2.0, 1.0, 0.0] lineChartSubView.frame = CGRectMake(0, 0, screenWidth, screenHeight) lineChartSubView.backgroundColor = UIColor.whiteColor() lineChartSubView.setXLabels(["0","1","2","3","4"], withWidth: 1) lineChartSubView.showCoordinateAxis = true lineChartSubView.showLabel = true lineChartSubView.delegate = self var signalObtainedValues = PNLineChartData() signalObtainedValues.color = UIColor.greenColor() signalObtainedValues.itemCount = UInt(initSignalExample.count) signalObtainedValues.getData = ({(index: UInt) -> PNLineChartDataItem in var yValue:CGFloat = CGFloat(initSignalExample[Int(index)]) var item = PNLineChartDataItem(y: yValue) return item }) lineChartSubView.chartData = [signalObtainedValues] lineChartSubView.strokeChart() } </code> Now the problem is that the graph does not fit in the subview, but maybe I will open another question since the original post is solved. Thank you very much! Answer: How about this? <code>signalObtainedValues.getData = ({(index: Int) -> PNLineChartDataItem in var yValue:CGFloat = signalObtainedValues[index] var item = PNLineChartDataItem(y: yValue) return item}) </code> Answer: I think the problem is that you forgot to add subview, the graph did not show. <code>lineChartSubView.chartData = [signalObtainedValues] lineChartSubView.strokeChart() self.view.addSubview(lineChartSubView) </code> Comment: Please explain your answer. Comment: Because forgot to add subview, the graph did not show. Comment: @Wesker Please add the detail to your answer as well.<|endoftext|>Start Workflow from ModalPopup and close it using jquery Question: I am calling workflow from modalpopup on form submit and closed popup after it. Here is the code on submit button ECS_ProviderSubmit.js: <code>ECSDalMgr.ECSModule.updateItemRequest(old_data.__metadata.uri, new_data, old_data.__metadata.etag, 'true').then(function(data){ ECSDalMgr.LoadScripts(listGUID, itemID , REMINDERworkflowSubscriptionID , ""); Utilities.closeWaitScreenDialogBox(); Utilities.closeModalPopUp(); }).fail(function (error) { console.log("Error in getItemById" + error.responseText) }); </code> Here is the code for ECS_DalManager: <code>this.LoadScripts = function (lstguid, listItemId, subscriptionID, Url) { listGUID = lstguid; itemID = listItemId; workflowSubscriptionID = subscriptionID; redirectUrl = Url; SP.SOD.executeFunc("sp.js", "SP.ClientContext", function () { SP.SOD.registerSod('sp.workflowservices.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js')); SP.SOD.executeFunc('sp.workflowservices.js', "SP.WorkflowServices.WorkflowServicesManager", startWorkflow); }) } function startWorkflow() { getWorkflow(listGUID, itemID, workflowSubscriptionID, redirectUrl); } function getWorkflow(lstGuid, itemID, workflowSubscriptionID, redirectToUrl) { var context = SP.ClientContext.get_current(); var web = context.get_web(); var sMgr = new SP.WorkflowServices.WorkflowServicesManager.newObject(context, web); var subscription = sMgr.getWorkflowSubscriptionService().getSubscription(workflowSubscriptionID); context.load(subscription); context.executeQueryAsync( function (sender, args) { var params = new Object(); var formData = subscription.get_propertyDefinitions()["FormData"]; if (formData != null && formData != 'undefined' && formData != "") { var assocParams = formData.split(";#"); for (var i = 0; i < assocParams.length; i++) { params[assocParams[i]] = subscription.get_propertyDefinitions()[assocParams[i]]; } } if (itemID) { sMgr.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemID, params); } else { sMgr.getWorkflowInstanceService().startWorkflow(subscription, params); } context.executeQueryAsync( function (sender, args) { }, errFunc); }, errFunc); } function errFunc(sender, args) { alert("Error: unable to start workflow") console.log('Error: unable to start workflow' + error.responseText); } </code> Now issues is when I call Loadscripts function from ECS_ProviderSubmit.js, it just execute this.LoadScripts function and returns. then after popupmodal get closed and then after startWorkflow() get called. So I get error in context.executeQueryAsync(). It is any way, I can call startworkflow() before closing modalpopup. Comment: Maybe I'm being too simplistic, but shouldn't the workflow be configured to fire on change, then by the mere fact you update the item, the workflow fires, making all the JS code to initiate it unnecessary? Answer: Now issues is when I call Loadscripts function from ECS_ProviderSubmit.js, it just execute this.LoadScripts function and returns. Right, because you are doing a lot of async stuff and not waiting for it to be done before moving on to closing the modal. It looks like you are already using promises in the <code>updateItemRequest</code> function, so I would just continue with that and make the <code>LoadScripts</code> function return a promise as well, and make sure you structure the code so that that promise doesn't get resolved until all of your workflow async calls finish. Then you could chain your calls more like this: <code>ECSDalMgr.ECSModule.updateItemRequest([your params]).then(function (data) { return ECSDalMgr.LoadScripts(listGUID, itemID, REMINDERworkflowSubscriptionID, ""); }).then(function () { Utilities.closeWaitScreenDialogBox(); Utilities.closeModalPopUp(); }).fail(function (error) { console.log("Error in getItemById" + error.responseText) }); </code> Here's what I was talking about. Notice I made one major structural change by nesting <code>startWorkflow</code>, <code>getWorkflow</code> and <code>errFunc</code> inside <code>LoadScripts</code> so that those functions have access to the <code>dfd</code> deferred object. <code>this.LoadScripts = function (lstguid, listItemId, subscriptionID, Url) { // this is assuming you are working with jQuery and can use jQuery deferreds // if you are using some other promise framework then you will have to substitute // this with whatever is appropriate for your promise framework var dfd = new $.Deferred(); var listGUID = lstguid; var itemID = listItemId; var workflowSubscriptionID = subscriptionID; var redirectUrl = Url; SP.SOD.executeFunc("sp.js", "SP.ClientContext", function () { SP.SOD.registerSod('sp.workflowservices.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js')); SP.SOD.executeFunc('sp.workflowservices.js', "SP.WorkflowServices.WorkflowServicesManager", startWorkflow); }); // notice that here I have nested all of your workflow functions *inside* LoadScripts // so that they have access to the "dfd" deferred object created at the beginning of the script function startWorkflow() { getWorkflow(listGUID, itemID, workflowSubscriptionID, redirectUrl); } function getWorkflow(lstGuid, itemID, workflowSubscriptionID, redirectToUrl) { var context = SP.ClientContext.get_current(); var web = context.get_web(); var sMgr = new SP.WorkflowServices.WorkflowServicesManager.newObject(context, web); var subscription = sMgr.getWorkflowSubscriptionService().getSubscription(workflowSubscriptionID); context.load(subscription); context.executeQueryAsync( function (sender, args) { var params = new Object(); var formData = subscription.get_propertyDefinitions()["FormData"]; if (formData != null && formData != 'undefined' && formData != "") { var assocParams = formData.split(";#"); for (var i = 0; i < assocParams.length; i++) { params[assocParams[i]] = subscription.get_propertyDefinitions()[assocParams[i]]; } } if (itemID) { sMgr.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemID, params); } else { sMgr.getWorkflowInstanceService().startWorkflow(subscription, params); } context.executeQueryAsync( function (sender, args) { // this is the success function that gets called after the workflow is started, // so this is where you want to resolve the "dfd" promise dfd.resolve(); }, errFunc); }, errFunc); } function errFunc(sender, args) { alert("Error: unable to start workflow") console.log('Error: unable to start workflow' + error.responseText); // if there was an error, you want to reject the promise dfd.reject(); } // this is now the end of the LoadScripts function, so here // is where you want to return the "dfd" deferred object's promise // to make the calling code wait return dfd.promise(); } </code> Comment: Nope. It doesn't work. because it goes to Loadscripts method first, after it comes to then, so popup get closed, and after it, it goes to startWorkflow() method Comment: Yes, but what I'm saying is that you need to change your `LoadScripts` method to return a promise, and then resolve that promise only after **all** of the `executeQueryAsync` calls that have to do with starting the workflow are complete. The `then()` that's chained after `LoadScripts` will not pause the code execution unless `LoadScripts` returns a promise.
[{"idx": "How_do_I_use_getData()_to_plot_a_LineChart_with_ObjC_PNChart_library_in_Swift?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-22573.jsonl"}, {"idx": "Start_Workflow_from_ModalPopup_and_close_it_using_jquery", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-22573.jsonl"}]
"""This class implements VAE training. """ import os import logging import tensorflow as tf import utils from utils import ProgressBar from utils import TQDM import numpy as np import ops from metrics import Metrics class Vae(object): """A base class for running individual VAEs. """ # Create a new session with session.graph = default graph self._trained = False self._data = data self._data_weights = np.copy(weights) # Latent noise sampled ones to apply decoder while training self._noise_for_plots = utils.generate_noise(opts, 500) # Placeholders self._real_points_ph = None self._noise_ph = None # Main operations # FIX self._loss = None self._loss_reconstruct = None self._loss_kl = None self._generated = None self._reconstruct_x = None # Optimizers self.optim = None logging.error('Building the graph...') self._build_model_internal(opts) # Make sure AdamOptimizer, if used in the Graph, is defined before # calling global_variables_initializer(). self._session.run(init) def __enter__(self): return self # Cleaning the whole default Graph logging.error('Cleaning the graph...') logging.error('Closing the session...') # Finishing the session self._session.close() def train(self, opts): """Train a VAE model. """ self._train_internal(opts) self._trained = True def sample(self, opts, num=100): """Sample points from the trained VAE model. """ assert self._trained, 'Can not sample from the un-trained VAE' return self._sample_internal(opts, num) def train_mixture_discriminator(self, opts, fake_images): """Train classifier separating true data from points in fake_images. Return: prob_real: probabilities of the points from training data being the Numpy vector of shape (self._data.num_points,) prob_fake: probabilities of the points from fake_images being the Numpy vector of shape (len(fake_images),) """ return self._train_mixture_discriminator_internal(opts, fake_images) def _run_batch(self, opts, operation, placeholder, feed, placeholder2=None, feed2=None): """Wrapper around session.run to process huge data. It is asumed that (a) first dimension of placeholder enumerates separate points, and (b) that operation is independently applied to every point, i.e. we can split it point-wisely and then merge the results. The second placeholder is meant either for is_train flag for batch-norm or probabilities of dropout. TODO: write util function which will be called both from this method and MNIST classification evaluation as well. """ assert len(feed.shape) > 0, 'Empry feed.' num_points = feed.shape[0] batch_size = opts['tf_run_batch_size'] batches_num = int(np.ceil((num_points + 0.) / batch_size)) result = [] for idx in xrange(batches_num): if idx == batches_num - 1: ]}) else: ], else: (idx + 1) * batch_size]}) else: (idx + 1) * batch_size], if len(res.shape) == 1: # convert (n,) vector to (n,1) array res = np.reshape(res, [-1, 1]) result = np.vstack(result) assert len(result) == num_points return result """Build a TensorFlow graph with all the necessary ops. """ assert False, 'VAE base class has no build_model method defined.' assert False, 'VAE base class has no train method defined.' assert False, 'VAE base class has no sample method defined.' def _train_mixture_discriminator_internal(self, opts, fake_images): assert False, 'VAE base class has no mixture discriminator method defined.' class ImageVae(Vae): """A simple VAE implementation, suitable for pictures. """ # One more placeholder for batch norm self._is_training_ph = None Vae.__init__(self, opts, data, weights) def generator(self, opts, noise, is_training, reuse=False, return_logits=False): """Generator function, suitable for simple picture experiments. Args: noise: [num_points, dim] array, where dim is dimensionality of the latent noise space. is_training: bool, defines whether to use batch_norm in the train or test mode. return_logits: bool, if true returns the "logits" instead of being normalized (by tanh or sigmoid depending on "input_normalize_sym". Returns: [num_points, dim1, dim2, dim3] array, where the first coordinate indexes the points, which all are of the shape (dim1, dim2, dim3). """ output_shape = self._data.data_shape # (dim1, dim2, dim3) # Computing the number of noise vectors on-the-go dim1 = tf.shape(noise)[0] num_filters = opts['g_num_filters'] num_layers = opts['g_num_layers'] with tf.variable_scope("GENERATOR", reuse=reuse): height = output_shape[0] / 2**(num_layers - 1) width = output_shape[1] / 2**(num_layers - 1) h0 = ops.linear(opts, noise, num_filters * height * width, scope='h0_lin') h0 = tf.reshape(h0, [-1, height, width, num_filters]) layer_x = h0 for i in xrange(num_layers-1): scale = 2**(i+1) _out_shape = [dim1, height * scale, width * scale, num_filters / scale] layer_x = ops.deconv2d(opts, layer_x, _out_shape, scope='h%d_deconv' % i) if opts['batch_norm']: layer_x = ops.batch_norm(opts, layer_x, is_training, reuse, scope='bn%d' % i) layer_x = tf.nn.relu(layer_x) if opts['dropout']: _keep_prob = tf.minimum( 1., 0.9 - (0.9 - keep_prob) * float(i + 1) / (num_layers - 1)) layer_x = tf.nn.dropout(layer_x, _keep_prob) # # h0 = ops.lrelu(h0) # _out_shape = [dim1, height * 2, width * 2, num_filters / 2] # # for 28 x 28 does 7 x 7 --> 14 x 14 # h1 = ops.deconv2d(opts, h0, _out_shape, scope='h1_deconv') # h1 = ops.batch_norm(opts, h1, is_training, reuse, scope='bn_layer2') # h1 = tf.nn.relu(h1) # # h1 = ops.lrelu(h1) # _out_shape = [dim1, height * 4, width * 4, num_filters / 4] # # for 28 x 28 does 14 x 14 --> 28 x 28 # h2 = ops.deconv2d(opts, h1, _out_shape, scope='h2_deconv') # h2 = ops.batch_norm(opts, h2, is_training, reuse, scope='bn_layer3') # h2 = tf.nn.relu(h2) # # h2 = ops.lrelu(h2) _out_shape = [dim1] + list(output_shape) # data_shape[0] x data_shape[1] x ? -> data_shape h3 = ops.deconv2d(opts, layer_x, _out_shape, d_h=1, d_w=1, scope='hlast_deconv') # h3 = ops.batch_norm(opts, h3, is_training, reuse, scope='bn_layer4') if return_logits: return h3 if opts['input_normalize_sym']: return tf.nn.tanh(h3) else: return tf.nn.sigmoid(h3) def discriminator(self, opts, input_, is_training, prefix='DISCRIMINATOR', reuse=False): """Encoder function, suitable for simple toy experiments. """ num_filters = opts['d_num_filters'] with tf.variable_scope(prefix, reuse=reuse): h0 = ops.conv2d(opts, input_, num_filters / 8, scope='h0_conv') h0 = ops.batch_norm(opts, h0, is_training, reuse, scope='bn_layer1') h1 = ops.conv2d(opts, h0, num_filters / 4, scope='h1_conv') h1 = ops.batch_norm(opts, h1, is_training, reuse, scope='bn_layer2') h1 = tf.nn.relu(h1) h2 = ops.conv2d(opts, h1, num_filters / 2, scope='h2_conv') h2 = ops.batch_norm(opts, h2, is_training, reuse, scope='bn_layer3') h2 = tf.nn.relu(h2) h3 = ops.conv2d(opts, h2, num_filters, scope='h3_conv') h3 = ops.batch_norm(opts, h3, is_training, reuse, scope='bn_layer4') h3 = tf.nn.relu(h3) # Already has NaNs!! latent_mean = ops.linear(opts, h3, opts['latent_space_dim'], scope='h3_lin') log_latent_sigmas = ops.linear(opts, h3, opts['latent_space_dim'], scope='h3_lin_sigma') return latent_mean, log_latent_sigmas """Build the Graph corresponding to VAE implementation. """ data_shape = self._data.data_shape # Placeholders real_points_ph = tf.placeholder( tf.float32, [None] + list(data_shape), name='real_points_ph') noise_ph = tf.placeholder( tf.float32, [None] + [opts['latent_space_dim']], name='noise_ph') is_training_ph = tf.placeholder(tf.bool, name='is_train_ph') lr_decay_ph = tf.placeholder(tf.float32) # Operations latent_x_mean, log_latent_sigmas = self.discriminator( opts, real_points_ph, is_training_ph) scaled_noise = tf.multiply( tf.sqrt(1e-6 + tf.exp(log_latent_sigmas)), noise_ph) loss_kl = 0.5 * tf.reduce_sum( tf.exp(log_latent_sigmas) + tf.square(latent_x_mean) - log_latent_sigmas, axis=1) if opts['recon_loss'] == 'l2sq': reconstruct_x = self.generator(opts, latent_x_mean + scaled_noise, is_training_ph) tf.square(real_points_ph - reconstruct_x), axis=[1,2,3]) loss_reconstruct = loss_reconstruct / 2. / opts['vae_sigma'] elif opts['recon_loss'] == 'cross_entropy': expected = (real_points_ph + 1.0) / 2.0 else: expected = real_points_ph reconstruct_x_logits = self.generator( opts, latent_x_mean + scaled_noise, is_training_ph, return_logits=True) labels=expected, logits=reconstruct_x_logits), axis=[1,2,3]) else: raise ValueError("Unknown recon loss value %s" % opts['recon_loss']) dec_enc_x = self.generator(opts, latent_x_mean, is_training=False, reuse=True) loss_reconstruct = tf.reduce_mean(loss_reconstruct) loss_kl = tf.reduce_mean(loss_kl) loss = loss_kl + loss_reconstruct # loss = tf.Print(loss, [loss, loss_kl, loss_reconstruct], 'Loss, KL, reconstruct') optim = ops.optimizer(opts, decay=lr_decay_ph).minimize(loss) generated_images = self.generator(opts, noise_ph, is_training_ph, reuse=True) self._real_points_ph = real_points_ph self._noise_ph = noise_ph self._is_training_ph = is_training_ph self._optim = optim self._loss = loss self._loss_reconstruct = loss_reconstruct self._lr_decay_ph = lr_decay_ph self._loss_kl = loss_kl self._generated = generated_images self._reconstruct_x = dec_enc_x self._enc_mean = latent_x_mean self._enc_log_var = log_latent_sigmas tf.add_to_collection('real_points_ph', self._real_points_ph) tf.add_to_collection('noise_ph', self._noise_ph) tf.add_to_collection('is_training_ph', self._is_training_ph) tf.add_to_collection('encoder_mean', self._enc_mean) tf.add_to_collection('encoder_log_sigma', self._enc_log_var) tf.add_to_collection('decoder', self._generated) self._saver = saver logging.error("Building Graph Done.") """Train a VAE model. """ batches_num = self._data.num_points / opts['batch_size'] train_size = self._data.num_points num_plot = 320 sample_prev = np.zeros([num_plot] + list(self._data.data_shape)) l2s = [] counter = 0 decay = 1. logging.error('Training VAE') for _epoch in xrange(opts["gan_epoch_num"]): if opts['decay_schedule'] == "manual": if _epoch == 30: decay = decay / 2. if _epoch == 50: decay = decay / 5. if _epoch == 100: decay = decay / 10. if _epoch > 0 and _epoch % opts['save_every_epoch'] == 0: 'trained-pot'), for _idx in xrange(batches_num): # logging.error('Step %d of %d' % (_idx, batches_num ) ) data_ids = np.random.choice(train_size, opts['batch_size'], replace=False, p=self._data_weights) batch_images = self._data.data[data_ids].astype(np.float) batch_noise = utils.generate_noise(opts, opts['batch_size']) _, loss, loss_kl, loss_reconstruct = self._session.run( [self._optim, self._loss, self._loss_kl, self._loss_reconstruct], feed_dict={self._real_points_ph: batch_images, self._noise_ph: batch_noise, self._lr_decay_ph: decay, self._is_training_ph: True}) counter += 1 debug_str = 'Epoch: %d/%d, batch:%d/%d' % ( _epoch+1, opts['gan_epoch_num'], _idx+1, batches_num) debug_str += ' [L=%.2g, Recon=%.2g, KLQ=%.2g]' % ( loss, loss_reconstruct, loss_kl) logging.error(debug_str) metrics = Metrics() points_to_plot = self._run_batch( opts, self._generated, self._noise_ph, self._noise_for_plots[0:num_plot], l2s.append(np.sum((points_to_plot - sample_prev)**2)) metrics.l2s = l2s[:] opts, None, points_to_plot, prefix='sample_e%04d_mb%05d_' % (_epoch, _idx)) reconstructed = self._session.run( self._reconstruct_x, self._is_training_ph: False}) metrics.l2s = None opts, None, reconstructed, prefix='reconstr_e%04d_mb%05d_' % (_epoch, _idx)) if opts['early_stop'] > 0 and counter > opts['early_stop']: break if _epoch > 0: 'trained-pot-final'), """Sample from the trained GAN model. """ noise = utils.generate_noise(opts, num) sample = self._run_batch( opts, self._generated, self._noise_ph, noise, return sample<|endoftext|>#!/usr/bin/env python import matplotlib as mpl mpl.use('Agg') import desdb import numpy as np import esutil import pyfits import sys import argparse import healpy as hp import os import functions2 def NoSimFields(band='i'): q = """ SELECT balrog_index, mag_auto, flags FROM """ %(band) return q q = """ SELECT m.mag_auto as mag_auto, m.spread_model as spread_model, m.spreaderr_model as spreaderr_model, m.class_star as class_star, m.mag_psf as mag_psf, t.mag as truth_mag_auto, m.flags as flags FROM """ %(table, band, table, band) return q q = """ SELECT tilename, coadd_objects_id, mag_auto_%s as mag_auto, spread_model_%s as spread_model, spreaderr_model_%s as spreaderr_model, class_star_%s as class_star, mag_psf_%s as mag_psf, flags_%s as flags FROM sva1_coadd_objects WHERE tilename in %s """ % (band,band,band,band,band,band,band,band,str(tuple(np.unique(tilestuff['tilename'])))) return q q = """ SELECT balrog_index, tilename, ra, dec, objtype, mag FROM """%(table,band) return q def GetDESCat( depthmap, nside, tilestuff, tileinfo, band='i',depth = 0.0): cur = desdb.connect() return detcat if HealConfig is None: cur = desdb.connect() q = "SELECT tilename, udecll, udecur, urall, uraur FROM coaddtile" tilestuff = {} return depthmap, nside def cleanCatalog(catalog, tag='mag_auto'): return catalog[keep] def removeBadTilesFromTruthCatalog(truth, tag='mag_auto', goodfrac = 0.8): return truth[keep] def mergeCatalogsUsingPandas(sim=None, truth=None, key='balrog_index', suffixes = ['_sim','']): import pandas as pd matched = pd.merge(simData, truthData, on=key, suffixes = suffixes) matched_arr = matched.to_records(index=False) # This last step is necessary because Pandas converts strings to Objects when eating structured arrays. # And np.recfunctions flips out when it has one. oldDtype = matched_arr.dtype.descr newDtype = oldDtype for thisOldType,i in zip(oldDtype, xrange(len(oldDtype) )): if 'O' in thisOldType[1]: newDtype[i] = (thisOldType[0], 'S12') matched_arr = np.array(matched_arr,dtype=newDtype) return matched_arr def GetFromDB( band='i', depth = 0.0,tables =['sva1v2','sva1v3_2']): # tables =['sva1v2','sva1v3','sva1v3_2'] cur = desdb.connect() q = "SELECT tilename, udecll, udecur, urall, uraur FROM coaddtile" tilestuff = {} truths = [] sims = [] truthMatcheds = [] for tableName in tables: unique_binds, unique_inds = np.unique(truth['balrog_index'],return_index=True) truth = truth[unique_inds] sim = cleanCatalog(sim,tag='mag_auto') truths.append(truth) sims.append(sim) sim = np.hstack(sims) truth = np.hstack(truths) des = cleanCatalog(des, tag='mag_auto') If they do, then # use the files. # from the database exists = True print "Checking for existence of: "+thisFile if exists and not reload: else: print "Cannot find files, or have been asked to reload. Getting data from DESDB." return ra, dec phi = ra * np.pi / 180.0 return hpInd ra = phi*180.0/np.pi return ra,dec phi = ra * np.pi / 180.0 return theta, phi def HealPixifyCatalogs(catalog=None, healConfig=None, ratag='ra', dectag = 'dec'): HealInds = hpRaDecToHEALPixel( catalog[ratag],catalog[dectag], nside= healConfig['map_nside'], nest= healConfig['nest']) healCat = rf.append_fields(catalog,'HEALIndex',HealInds,dtypes=HealInds.dtype) return healCat HealConfig = {} HealConfig['nest'] = True return HealConfig def chooseBins(catalog = None, tag=None, binsize = None, upperLimit = None, lowerLimit = None): if binsize is None: binsize = 2*( np.percentile(catalog[tag], 75) - np.percentile( catalog[tag], 25 ) ) / (catalog.size ) **(1./3.) if upperLimit is None: upperLimit = np.max(catalog[tag]) if lowerLimit is None: lowerLimit = np.min(catalog[tag]) nbins = int( np.ceil( (upperLimit - lowerLimit) / binsize) ) nEdge = nbins+1 bins = lowerLimit + binsize * np.arange(nEdge) bins[0] = bins[0] - 0.001*binsize bins[-1] = bins[-1] + 0.001*binsize return bins def makeLikelihoodMatrix( sim=None, truth=None, truthMatched = None, Lcut = 0., obs_bins = None, truth_bins = None, simTag = None, truthTag = None): obs_bin_index = np.digitize(sim[simTag], obs_bins) - 1 truth_bin_index = np.digitize(truthMatched[truthTag], truth_bins) - 1 # Limit loop to objects in the given bin ranges. nbins_truth = truth_bins.size -1 nbins_obs = obs_bins.size - 1 good = ((truth_bin_index > 0) & (truth_bin_index < nbins_truth) & (obs_bin_index > 0) & (obs_bin_index < nbins_obs) ) obs_bin_index = obs_bin_index[good] truth_bin_index = truth_bin_index[good] N_truth, _ = np.histogram( truth[truthTag], bins=truth_bins ) L = np.zeros( (nbins_obs, nbins_truth) ) II = np.zeros( (nbins_obs, nbins_truth) ) if N_truth[truth_bin_index[i]] > 1: L[obs_bin_index[i], truth_bin_index[i]] = ( L[obs_bin_index[i], truth_bin_index[i]] + 1./N_truth[truth_bin_index[i]] ) II[obs_bin_index[i], truth_bin_index[i]] = II[obs_bin_index[i], truth_bin_index[i]]+1 L[II < 1] = 0. L[L < Lcut] = 0. return L def getAllLikelihoods( truth=None, sim=None, truthMatched = None, healConfig=None , doplot = False, getBins = False, ratag= 'ra', dectag = 'dec', obs_bins = None, truth_bins = None, obsTag = 'mag_auto', truthTag = 'mag'): if healConfig is None: truth = HealPixifyCatalogs(catalog=truth, healConfig=healConfig, ratag=ratag, dectag = dectag) sim = HealPixifyCatalogs(catalog=sim, healConfig=healConfig, ratag=ratag, dectag = dectag) truthMatched = HealPixifyCatalogs(catalog=truthMatched, healConfig=healConfig, ratag=ratag, dectag = dectag) useInds = np.unique(sim['HEALIndex']) if obs_bins is None: obs_bins = chooseBins(catalog=sim, tag = obsTag, binsize=0.5,upperLimit=24.5,lowerLimit=15.) if truth_bins is None: truth_bins = chooseBins(catalog = truthMatched, tag = truthTag, binsize = 0.5,upperLimit=26.,lowerLimit=15) truth_bin_centers = (truth_bins[0:-1] + truth_bins[1:])/2. obs_bin_centers = (obs_bins[0:-1] + obs_bins[1:])/2. Lensemble = np.empty( (obs_bins.size-1 , truth_bins.size-1, useInds.size) ) if doplot is True: pp = PdfPages('likelihoods.pdf') fig,ax = plt.subplots(figsize=(6.,6.)) # Make a plot of the likelihood of the whole region. masterLikelihood = makeLikelihoodMatrix( sim=sim, truth=truth, truthMatched = truthMatched, Lcut = 0., im = ax.imshow(masterLikelihood, origin='lower',cmap=plt.cm.Greys, norm = LogNorm(vmin=1e-6,vmax=1), extent = [truth_bin_centers[0],truth_bin_centers[-1],obs_bin_centers[0],obs_bin_centers[-1]]) ax.set_xlabel('truth mag.') ax.set_ylabel('measured mag.') ax.set_title('full area likelihood') fig.colorbar(im,ax=ax) pp.savefig(fig) for hpIndex,i in zip(useInds,xrange(useInds.size)): thisSim = sim[sim['HEALIndex'] == hpIndex] thisTruth = truth[truth['HEALIndex'] == hpIndex] thisTruthMatched = truthMatched[sim['HEALIndex'] == hpIndex] if thisTruth.size > 100: thisLikelihood = makeLikelihoodMatrix( sim=thisSim, truth=thisTruth, truthMatched = thisTruthMatched, Lcut = 1.e-3, Lensemble[:,:,i] = thisLikelihood if doplot is True: fig,ax = plt.subplots(figsize = (6.,6.)) im = ax.imshow(thisLikelihood, origin='lower',cmap=plt.cm.Greys, norm = LogNorm(vmin=1e-6,vmax=1), ax.set_title('nside= '+str(healConfig['map_nside'])+', HEALPixel= '+str(hpIndex) ) if doplot is True: pp.close() if getBins is False: return Lensemble, useInds, masterLikelihood, truth_bin_centers, obs_bin_centers if getBins is True: return Lensemble, useInds, masterLikelihood, truth_bins, obs_bins return keep def excludeBadRegions(des,balrogObs, balrogTruthMatched, balrogTruth, band='i'): eliMap = hp.read_map("sva1_gold_1.0.4_goodregions_04_equ_nest_4096.fits", nest=True) maskIndices = np.arange(eliMap.size) badIndices = maskIndices[eliMap == 1] obsKeepIndices = getGoodRegionIndices(catalog=balrogObs, badHPInds=badIndices, nside=nside) truthKeepIndices = getGoodRegionIndices(catalog=balrogTruth, badHPInds=badIndices, nside=nside) balrogObs = balrogObs[obsKeepIndices] balrogTruthMatched = balrogTruthMatched[obsKeepIndices] balrogTruth = balrogTruth[truthKeepIndices] des = des[desKeepIndices] return des,balrogObs, balrogTruthMatched, balrogTruth def likelihoodPCA(likelihood= None, likelihood_master = None, doplot = False, band = None, extent = None): # This does a simple PCA on the array of likelihood matrices to find a compact basis with which to represent the likelihood. origShape = np.shape(likelihood) likelihood_1d = np.reshape(likelihood, (origShape[0]*origShape[1], origShape[2])) L1d_master = np.reshape(likelihood_master, origShape[0]*origShape[1]) # Subtract L1d_master from each row of L1d: # likelihood_1d[:,i] = likelihood_1d[:,i] - L1d_master L1d = likelihood_1d.T U,s,Vt = np.linalg.svd(L1d,full_matrices=False) V = Vt.T ind = np.argsort(s)[::-1] ind = np.argsort(s)[::-1] U = U[:, ind] s = s[ind] V = V[:, ind] # likelihood_1d[:,i] = likelihood_1d[:,i] + L1d_master likelihood_pcomp = V.reshape(origShape) if doplot is True: , Normalize if band is None: print "Must supply band (g,r,i,z,Y) in order to save PCA plots." stop pp = PdfPages('likelihood_pca_components-'+band+'.pdf') for i,thing in zip(xrange(s.size),s): fig,ax = plt.subplots(nrows=1,ncols=1,figsize = (6.,6.)) im = ax.imshow( -likelihood_pcomp[:,:,i],origin='lower',cmap=plt.cm.Greys, extent = extent,vmin=-1,vmax=1) ax.set_xlabel(band+' mag (true)') ax.set_ylabel(band+' mag (meas)') pp.savefig(fig) fig,ax = plt.subplots(1,1,figsize = (6.,6.) ) ax.plot(np.abs(s)) ax.set_yscale('log') ax.set_xlabel('rank') pp.savefig(fig) pp.close() return likelihood_pcomp, s def doLikelihoodPCAfit(pcaComp = None, master = None, eigenval = None, likelihood =None, n_component = 5, Lcut = 0.): # Perform least-squares: Find the best combination of master + pcaComps[:,:,0:n_component] that fits likelihood origShape = likelihood.shape L1d = likelihood - master L1d = likelihood.reshape(likelihood.size) pca1d = pcaComp.reshape( ( likelihood.size, pcaComp.shape[-1]) ) pcafit = pca1d[:,0:(n_component)] m1d = np.reshape(master,master.size) #allfit = np.hstack((m1d[:,None], pcafit) ) allfit = pcafit coeff, resid, _, _ = np.linalg.lstsq(allfit, L1d) bestFit = np.dot(allfit,coeff) bestFit2d = bestFit.reshape(likelihood.shape) #bestFit2d = bestFit2d + master bestFit2d[bestFit2d < Lcut] = 0. m_coeff, m_resid, _, _ = np.linalg.lstsq(allfit, m1d) m1d_fit = np.dot(allfit, m_coeff) m2d = np.reshape(m1d_fit,master.shape) return bestFit2d, m2d def main(argv): parser.add_argument("-r","--reload",help='reload catalogs from DESDB', action="store_true") band = args.filter print "performing inference in band: "+args.filter print "Reloading from DESDM:", args.reload print "Excluding regions Eli says are bad." des, sim, truthMatched, truth = excludeBadRegions(des,sim, truthMatched, truth,band=band) print sim.size # Filter out bad detections, if we can. truth = truth[truth['mag'] > 0] keep = (truthMatched['mag'] > 0) sim = sim[keep] truthMatched = truthMatched[keep] HEALConfig = getHealConfig(map_nside = 64) print "Getting likelihood matrices for each HEALPixel" Likelihoods, HEALPixels, masterLikelihood, truth_bin_centers, obs_bin_centers = getAllLikelihoods(truth=truth, sim=sim, truthMatched = truthMatched, healConfig=HEALConfig ,doplot = True) # Solve for the pca components. print "Performing PCA fit over all the likelihoods." Lpca, pcaEigen = likelihoodPCA(likelihood = Likelihoods, likelihood_master = masterLikelihood, doplot = True, band = band, # Loop over the likelihoods again. Find the best low-n PCA fit to each. L_fit = Likelihoods * 0. # And make a plot showing the likelihood, the best fit, and the residual map. pp = PdfPages('likelihood_pca_fit-'+band+'.pdf') print "Making plot of all the likelihoods and their best fits" for i in xrange(HEALPixels.size): thisLike = Likelihoods[:,:,i] L_fit[:,:,i], master_pca = doLikelihoodPCAfit( pcaComp = Lpca, master = masterLikelihood, Lcut = 1.e-3, eigenval = pcaEigen, likelihood = thisLike, n_component = 4) fig,ax = plt.subplots(nrows=1,ncols=4,sharey=True,figsize = (20.,5.)) im0 = ax[0].imshow(master_pca, origin='lower',cmap=plt.cm.Greys, norm = LogNorm(vmin=1e-6,vmax=1), ax[0].set_xlabel('truth '+band+' mag.') ax[0].set_ylabel('measured '+band+' mag.') ax[0].set_title('Full SVA1 Balrog area') im1 = ax[1].imshow(Likelihoods[:,:,i], origin='lower',cmap=plt.cm.Greys, norm = LogNorm(vmin=1e-6,vmax=1), ax[1].set_xlabel('truth '+band+' mag.') ax[1].set_title('Balrog likelihood, \n HEALPixel='+str(HEALPixels[i])+', nside='+str(HEALConfig['out_nside'])) im2 = ax[2].imshow(L_fit[:,:,i], origin='lower',cmap=plt.cm.Greys, norm = LogNorm(vmin=1e-6,vmax=1), ax[2].set_xlabel('truth '+band+' mag.') ax[2].set_title('PCA-smoothed Balrog likelihood') im3 = ax[3].imshow(Likelihoods[:,:,i] - L_fit[:,:,i], origin='lower', cmap=plt.cm.Greys, norm = Normalize(vmin=-1,vmax = 1), ax[3].set_xlabel('truth '+band+' mag.') ax[3].set_title('residuals') fig.colorbar(im2,ax=ax[2]) fig.colorbar(im3, ax = ax[3]) pp.savefig(fig) pp.close() import esutil print "Writing likelihoods to file masterLikelihoodFile.fits" esutil.io.write('masterLikelihoodFile.fits',Likelihoods, ext=1) esutil.io.write('masterLikelihoodFile.fits',L_fit,ext=2) esutil.io.write('masterLikelihoodFile.fits',HEALPixels, ext=3) print "Done." if __name__ == "__main__": import pdb, traceback try: main(sys.argv) except: traceback.print_exc() pdb.post_mortem(tb)
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11636.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11636.jsonl"}]
#### File: rorybolt/learning_python/biotools.py ```python import sys import gzip import random import math def read_fasta(filename): name = None seqs = [] fp = None if filename == '-': fp = sys.stdin elif filename.endswith('.gz'): fp = gzip.open(filename, 'rt') else: fp = open(filename) for line in fp.readlines(): line = line.rstrip() if line.startswith('>'): if len(seqs) > 0: seq = ''.join(seqs) yield(name, seq) name = line[1:] seqs = [] else: name = line[1:] else: seqs.append(line) yield(name, ''.join(seqs)) fp.close() def gc(seq): count = 0 for nt in seq: if nt == 'G' or nt == 'C': count += 1 return count / len(seq) def randseq(l,gc): dna=[] for i in range(l): r=random.random() if r < gc: r = random.random() if r < 0.5 : dna.append('G') else : dna.append('C') else: r = random.random() if r < 0.5 : dna.append('A') else : dna.append('T') return(''.join(dna)) KDtable = { 'I':4.5,'V':4.2,'L':3.8,'F':2.8,'C':2.5, 'M':1.9,'A':1.8,'G':-0.4,'T':-0.7,'S':-0.8, 'W':-0.9,'Y':-1.3,'P':-1.6,'H':-3.2,'E':-3.5, 'Q':-3.5,'D':-3.5,'N':-3.5,'K':-3.9,'R':-4.5 } # Compute the average KD value def computeKD(seq, start, len): kd = 0 for i in range(len): val = KDtable.get(seq[start+i]) if val is None: # print("Bad data: ", seq[start:start+len]) return 0 # Bad data... kd += val return kd/len AAtable = dict({ 'TTT':'F', 'TTC':'F', 'TTA':'L', 'TTG':'L', 'CTT':'F', 'CTC':'F', 'CTA':'L', 'CTG':'L', 'ATT':'I', 'ATC':'I', 'ATA':'I', 'ATG':'M', 'GTT':'V', 'GTC':'V', 'GTA':'V', 'GTG':'V', 'TCT':'S', 'TCC':'S', 'TCA':'S', 'TCG':'S', 'CCT':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P', 'ACT':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T', 'GCT':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A', 'TAT':'Y', 'TAC':'Y', 'TAA':'*', 'TAG':'*', 'CAT':'H', 'CAC':'H', 'CAA':'Q', 'CAG':'Q', 'AAT':'N', 'AAC':'N', 'AAA':'K', 'AAG':'K', 'GAT':'D', 'GAC':'D', 'GAA':'E', 'GAG':'E', 'TGT':'C', 'TGC':'C', 'TGA':'*', 'TGG':'W', 'CGT':'R', 'CGC':'R', 'CGA':'R', 'CGG':'R', 'AGT':'S', 'AGC':'S', 'AGA':'R', 'AGG':'R', 'GGT':'G', 'GGC':'G', 'GGA':'G', 'GGG':'G' }) def translate(seq): protein = [] for i in range(0,len(seq)-2,3): codon = seq[i:i+3] protein.append(AAtable[codon]) return ''.join(protein) def skew(seq): #(g-c/(g+c) g = 0 c = 0 for nt in seq: if nt == 'G' : g+=1 elif nt == 'C': c+=1 return (g-c)/(g+c) def shannon(seq): # cout frequencies in seq a = 0 t = 0 g = 0 c = 0 for nt in seq: if nt == 'G' : g+=1 elif nt == 'C': c+=1 elif nt == 'A': a+=1 elif nt == 'T': t+=1 h = 0 cnt = len(seq) if a > 0: h -= (a/cnt) * math.log(a/cnt, 2) if t > 0: h -= (t/cnt) * math.log(t/cnt, 2) if c > 0: h -= (c/cnt) * math.log(c/cnt, 2) if g > 0: h -= (g/cnt) * math.log(g/cnt, 2) return h ``` #### File: rorybolt/learning_python/hydrophobicity.py ```python import argparse import biotools as bt # Write a program that computes hydrophobicity in a window # Let the user choose the method (see below) # [IDX] [IDX] setup parser = argparse.ArgumentParser( description='Compute hydrophobicity in a window.') # required arguments parser.add_argument('--input', required=True, type=str, metavar='<str>', help='fasta file') # optional arguments with default parameters parser.add_argument('--window', required=False, type=int, default=15, metavar='<int>', help='window size [%(default)i]') parser.add_argument('--method', choices=['kd','is','os','ois','cc'], required=False, type=str, default='kd', metavar='<str>', help='calculation method (kd, is, os, ois, cc) [%(default)s]') # finalization arg = parser.parse_args() KDtable = { 'I':4.5,'V':4.2,'L':3.8,'F':2.8,'C':2.5, 'M':1.9,'A':1.8,'G':-0.4,'T':-0.7,'S':-0.8, 'W':-0.9,'Y':-1.3,'P':-1.6,'H':-3.2,'E':-3.5, 'Q':-3.5,'D':-3.5,'N':-3.5,'K':-3.9,'R':-4.5 } IStable = { 'I':-0.31,'V':0.07,'L':-0.56,'F':-1.13,'C':-0.24, 'M':-0.23,'A':0.17,'G':0.01,'T':0.14,'S':0.13, 'W':-1.85,'Y':-0.94,'P':0.45,'H':0.96,'E':2.02, 'Q':0.58,'D':1.23,'N':0.42,'K':0.99,'R':0.81 } OStable = { 'I':-1.12,'V':-0.46,'L':-1.25,'F':-1.71,'C':-0.02, 'M':-0.67,'A':0.50,'G':1.15,'T':0.25,'S':0.46, 'W':-2.09,'Y':-0.71,'P':0.14,'H':2.33,'E':3.63, 'Q':0.77,'D':3.64,'N':0.85,'K':2.80,'R':1.81 } OIStable = { 'I':-0.81,'V':-0.53,'L':-0.69,'F':-0.58,'C':0.22, 'M':-0.44,'A':0.33,'G':1.14,'T':0.11,'S':0.33, 'W':-0.24,'Y':0.23,'P':-0.31,'H':1.37,'E':1.61, 'Q':0.19,'D':2.41,'N':0.43,'K':1.81,'R':1.00 } CCtable = { 'I':-0.528,'V':-0.308,'L':-0.342,'F':-0.370,'C':0.081, 'M':-0.324,'A':-0.495,'G':0.386,'T':0.853,'S':0.963, 'W':-0.270,'Y':1.667,'P':-0.322,'H':2.029,'E':3.173, 'Q':2.176,'D':9.573,'N':2.354,'K':2.101,'R':4.383 } def computeHD(seq,start,len,scale): hd = 0 if scale == 'kd': dict = KDtable elif scale == 'is': dict = IStable elif scale == 'os': dict = OStable elif scale == 'ois': dict = OIStable elif scale == 'cc': dict = CCtable else: print(f'unsupported scale {scale}') return None for i in range(len): val = dict.get(seq[start+i]) if val is None: print("Bad data: ", seq[start:start+len]) return None # Bad data... hd += val return hd/len for name, seq in bt.read_fasta(arg.input): print(f'>{name}') num_below = 0 for i in range(0,len(seq)-arg.window): hd = computeHD(seq, i, arg.window, arg.method) if hd == None: continue print(i, hd) if hd < 1: num_below += 1 print(num_below) """ python3 hydrophobicity.py --input proteins.fasta.gz --window 11 --method kd """ ``` #### File: rorybolt/learning_python/translate_mRNA.py ```python import gzip import sys import biotools as bt import argparse # Use argparse # Write a program that translates an mRNA # Assume the protein encoded is the longest ORF parser = argparse.ArgumentParser( description='Translates an mRNA.') # required arguments parser.add_argument('--file', required=True, type=str, metavar='<str>', help='path to protein file') # finalization arg = parser.parse_args() def longest_orf(seq): # find all ATGs atgs = [] for i in range(len(seq)-2): if seq[i:i+3] == 'ATG': atgs.append(i) # for each atg, find nearest in frame stop; find longest... max_len = 0 max_seq = None for atg in atgs: stop = None for i in range(atg, len(seq)-2, 3): codon = seq[i:i+3] if codon == 'TAA' or codon == 'TAG' or codon == 'TGA': stop = i break if stop != None: cds_len = stop - atg + 3 if cds_len > max_len: max_len = cds_len max_seq = seq[atg:atg+cds_len] if max_seq == None: return None # translate longest ORF into protein return bt.translate(max_seq) for name, seq in bt.read_fasta(arg.file): protein = longest_orf(seq) if protein != None: print(f'>{name}') print(protein) """ python3 translate_mRNA.py --file ../Lesson05/transcripts.fasta.gz >CBG00001.1 MTFCENKNLPKPPSDRCQVVVISILSMILDFYLKYNPDKHWAHLFYGASPILEILVIFGMLANSVYGNKLAMFACVLDLVSGVFCLLTLPVISVAENATGVRLHLPYISTFHSQFSFQVSTPVDLFYVATFLGFVSTILILLFLILDALKFMKLRKLRNEDLEKEKKMNPIEKV* >CBG00006.1 MNGVEKVNKYFDIKDKRDFLYHFGFGVDTLDIKAVFGDTKFVCTGGSPGRFKLYAEWFAKETSIPCSENLSRSDRFVIYKTGPVCWINHGMGTPSLSIMLVESFKLMHHAGVKNPTFIRLGTSGGVGVPPGTVVVSTGAMNAELGDTYVQVIAGKRIERPTQLDATLREALCAVGKEKNIPVETGKTMCADDFYEGQMRLDGYFCDYEEEDKYAFLRKLNSLGVRNIEMESTCFASFTCRAGFPSAIVCVTLLNRMDGDQVQIDKEKYIEYEERPFRLVTAYIRQQTGV* etc. """ ```<|endoftext|>#### File: Rosi2143/openhab-habpanel-theme-matrix/shaddow.py ```python import math import time from datetime import datetime, timedelta, date import sys from myopenhab import openhab from myopenhab import mapValues from myopenhab import getJSONValue WIDTH = 100 HEIGHT = 100 PRIMARY_COLOR = '#1b3024' LIGHT_COLOR = '#26bf75' STROKE_WIDTH = '1' FILENAME = '/etc/openhab2/html/matrix-theme/shaddow.svg' # Shape of the house in a 100 by 100 units square SHAPE = [{'x': 60.04, 'y': 12.52}, \ {'x': 89.15, 'y': 37.66}, \ {'x': 84.24, 'y': 43.36}, \ {'x': 87.19, 'y': 45.91}, \ {'x': 66.21, 'y': 70.02}, \ {'x': 63.15, 'y': 67.56}, \ {'x': 45.94, 'y': 87.48}, \ {'x': 32.70, 'y': 76.04}, \ {'x': 31.09, 'y': 77.90}, \ {'x': 10.85, 'y': 60.42}, \ {'x': 45.44, 'y': 20.36}, \ {'x': 49.93, 'y': 24.23}] HOURS = 1 DEGS = [] class shaddow(object): """ Shaddow Object """ def __init__(self): self.debug = False self.oh = openhab() self.azimuth = float(self.oh.getState('Sun_Azimuth')) self.elevation = float(self.oh.getState('Sun_Elevation')) self.sunrise_azimuth = float(self.oh.getState('Sunrise_Azimuth')) self.sunset_azimuth = float(self.oh.getState('Sunset_Azimuth')) ts = time.time() utc_offset = (datetime.fromtimestamp(ts) - datetime.utcfromtimestamp(ts)).total_seconds()/3600 for h in xrange(0,24,HOURS): t = datetime.combine(date.today(), datetime.min.time()) + timedelta(hours=-utc_offset+h-24) a = self.oh.getStateHistoryFromInflux('Sun_Azimuth',t.strftime('%Y-%m-%dT%H:%M:%S') + 'Z') if (a == None): a = 0 DEGS.extend([a]) def generatePath(self,stroke,fill,points,attrs=None): p = '' p = p + '<path stroke="' + stroke + '" stroke-width="' + STROKE_WIDTH + '" fill="' + fill + '" ' if (attrs != None): p = p + ' ' + attrs + ' ' p = p + ' d="' for point in points: if (points.index(point) == 0): p = p + 'M' + str(point['x']) + ' ' + str(point['y']) else: p = p + ' L' + str(point['x']) + ' ' + str(point['y']) p = p + '" />' return p def generateArc(self,dist,stroke,start,end,attrs=None): p = '' try: angle = end-start if (angle<0): angle = 360 + angle p = p + '<path d="M' + str(self.degreesToPoint(start,dist)['x']) + ' ' + str(self.degreesToPoint(start,dist)['y']) + ' ' p = p + 'A' + str(dist) + ' ' + str(dist) + ' 0 ' if (angle<180): p = p + '0 1 ' else: p = p + '1 1 ' p = p + str(self.degreesToPoint(end,dist)['x']) + ' ' + str(self.degreesToPoint(end,dist)['y']) + '"' p = p + ' stroke="' + stroke + '"' if (attrs != None): p = p + ' ' + attrs + ' ' else: p = p + ' stroke-width="' + STROKE_WIDTH + '" fill="none" ' p = p + ' />' except: p = '' return p def degreesToPoint(self,d,r): coordinates = {'x': 0, 'y': 0} cx = WIDTH / 2 cy = HEIGHT / 2 d2 = 180 - d coordinates['x'] = cx + math.sin(math.radians(d2))*r coordinates['y'] = cy + math.cos(math.radians(d2))*r return coordinates def generateSVG(self): realSun = self.degreesToPoint(self.azimuth, 10000) if self.debug: print realSun sun = self.degreesToPoint(self.azimuth, WIDTH / 2) minPoint = -1 maxPoint = -1 i = 0 minAngle = 999 maxAngle = -999 for point in SHAPE: #Angle of close light source angle = -math.degrees(math.atan2(point['y']-sun['y'],point['x']-sun['x'])) #Angle of distant light source (e.g. sun) angle = -math.degrees(math.atan2(point['y']-realSun['y'],point['x']-realSun['x'])) distance = math.sqrt(math.pow(sun['y']-point['y'],2) + math.pow(sun['x']-point['x'],2)) if (angle<minAngle): minAngle = angle minPoint = i if (angle>maxAngle): maxAngle = angle maxPoint = i point['angle'] = angle point['distance'] = distance if self.debug: print str(i).ljust(10),":", str(point['x']).ljust(10), str(point['y']).ljust(10), str(round(angle,7)).ljust(10), str(round(distance)).ljust(10) i = i + 1 if self.debug: print "Min Point = ",minPoint print "Max Point = ",maxPoint print "" i = minPoint k = 0 side1Distance = 0 side2Distance = 0 side1Done = False side2Done = False side1 = [] side2 = [] while True: if (side1Done == False): side1Distance = side1Distance + SHAPE[i]['distance'] if(i != minPoint and i != maxPoint): SHAPE[i]['side'] = 1 if (i == maxPoint): side1Done = True side1.append( { 'x': SHAPE[i]['x'], 'y': SHAPE[i]['y'] } ) if (side1Done == True): side2Distance = side2Distance + SHAPE[i]['distance'] if(i != minPoint and i != maxPoint): SHAPE[i]['side'] = 2 if (i == minPoint): side2Done = True side2.append( { 'x': SHAPE[i]['x'], 'y': SHAPE[i]['y'] } ) i = i + 1 if( i > len(SHAPE)-1): i = 0 if (side1Done and side2Done): break k = k + 1 if (k == 20): break svg = '<?xml version="1.0" encoding="utf-8"?>' svg = svg + '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" " [IDX] = svg + '<svg version="1.1" id="Layer_1" xmlns=" [IDX] xmlns:xlink=" [IDX] x="0px" y="0px" viewBox="-10 -10 120 120" xml:space="preserve">' minPointShaddowX = SHAPE[minPoint]['x'] + WIDTH * math.cos(math.radians(minAngle)) minPointShaddowY = SHAPE[minPoint]['y'] - HEIGHT * math.sin(math.radians(minAngle)) maxPointShaddowX = SHAPE[maxPoint]['x'] + WIDTH * math.cos(math.radians(maxAngle)) maxPointShaddowY = SHAPE[maxPoint]['y'] - HEIGHT * math.sin(math.radians(maxAngle)) shaddow = [ {'x': maxPointShaddowX, 'y': maxPointShaddowY } ] + \ side2 + \ [ {'x': minPointShaddowX, 'y': minPointShaddowY } ] svg = svg + '<defs><mask id="shaddowMask">' svg = svg + ' <rect width="100%" height="100%" fill="black"/>' svg = svg + ' <circle cx="' + str(WIDTH/2) + '" cy="' + str(HEIGHT/2) + '" r="' + str(WIDTH/2-1) + '" fill="white"/>' svg = svg + '</mask></defs>' svg = svg + self.generatePath('none',PRIMARY_COLOR,SHAPE) shaddow_svg = self.generatePath('none','black',shaddow,'mask="url(#shaddowMask)" fill-opacity="0.5"') if (self.elevation>0): svg = svg + self.generatePath(LIGHT_COLOR,'none',side1) else: svg = svg + self.generatePath(PRIMARY_COLOR,'none',side1) if (self.elevation>0): svg = svg + shaddow_svg svg = svg + self.generateArc(WIDTH/2,PRIMARY_COLOR,self.sunset_azimuth,self.sunrise_azimuth) svg = svg + self.generateArc(WIDTH/2,LIGHT_COLOR,self.sunrise_azimuth,self.sunset_azimuth) svg = svg + self.generatePath(LIGHT_COLOR,'none',[self.degreesToPoint(self.sunrise_azimuth,WIDTH/2-2), self.degreesToPoint(self.sunrise_azimuth,WIDTH/2+2)]) svg = svg + self.generatePath(LIGHT_COLOR,'none',[self.degreesToPoint(self.sunset_azimuth,WIDTH/2-2), self.degreesToPoint(self.sunset_azimuth,WIDTH/2+2)]) for i in range(0,len(DEGS)): if (i == len(DEGS)-1): j = 0 else: j = i + 1 if (i % 2 == 0): svg = svg + self.generateArc(WIDTH/2+8,PRIMARY_COLOR,DEGS[i],DEGS[j],'stroke-width="3" fill="none" stroke-opacity="0.2"') else: svg = svg + self.generateArc(WIDTH/2+8,PRIMARY_COLOR,DEGS[i],DEGS[j],'stroke-width="3" fill="none"') svg = svg + self.generatePath(LIGHT_COLOR,'none',[self.degreesToPoint(DEGS[0],WIDTH/2+5), self.degreesToPoint(DEGS[0],WIDTH/2+11)]) svg = svg + self.generatePath(LIGHT_COLOR,'none',[self.degreesToPoint(DEGS[(len(DEGS))/2],WIDTH/2+5), self.degreesToPoint(DEGS[(len(DEGS))/2],WIDTH/2+11)]) svg = svg + '<circle cx="' + str(sun['x']) + '" cy="' + str(sun['y']) + '" r="3" stroke="' + LIGHT_COLOR + '" stroke-width="' + STROKE_WIDTH + '" fill="' + LIGHT_COLOR + '" />' svg = svg + '</svg>' if self.debug: print svg f = open(FILENAME, 'w') f.write(svg) f.close() def main(): t1 = time.time() s = shaddow() args = sys.argv if(len(args) == 1): print '\033[91mNo parameters specified\033[0;0m' else: if(args[1] == "update"): s.generateSVG() t2 = time.time() print "Done in " + str(t2-t1) + " seconds" if __name__ == '__main__': main() ```
[{"idx": "rorybolt/learning_python", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-8832.jsonl"}, {"idx": "Rosi2143/openhab-habpanel-theme-matrix", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-8832.jsonl"}]
$(document).ready(function(){ $('.select2').select2(); var salesProgramItem = ""; for (var key in window.salesPrograms) { salesProgramItem += '<option value="' + salesPrograms[key].id + '">'+ salesPrograms[key].title +'</option>'; } $("#promo-program-select") .append(salesProgramItem) .change(function(){ var paymentType = $('select[name=payment_type]').val(); var periode = $('select[name=periode]').val() ? $('select[name=periode]').val() : 12; var deviceId = $('input[name=inventory_model]').val(); { calculatePromo(paymentType, planId, periode, deviceId); setTimeout(calculateCustPay(), 5000) } }); $('select[name=plan_id], select[name=periode]').change(function(){ var periode = $('select[name=periode]').val(); if(planId && periode) { } }); $('select[name=inventory_id]').change(function(){ var inventoryId = $(this).val(); $.ajax({ type: "GET", url: "/api/inventory/model/" + inventoryId, success: function(data){ $('input[name=device_price]').val(data.price); $('input[name=inventory_model]').val(data.id); $('#device-price').val(data.price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.")) } }); }); $(".change-date").click(function(e){ e.preventDefault(); $(".datepicker").removeAttr("disabled"); }); }); function calculateRegBenefit(planId,periode) { var currentPlanBenefit = planBenefits[planId][periode]; if(currentPlanBenefit.type == "%") { var packageValue = planPrice * periode; var totalPlanBenefit = packageValue * (parseInt(currentPlanBenefit.value)/100); } if(currentPlanBenefit.type == "IDR") { var totalPlanBenefit = currentPlanBenefit.value; } $('.plan-benefit-wrapper').show(); $('#plan-benefit').val('('+ totalPlanBenefit.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") + ')'); $('input[name=plan_benefit]').val(totalPlanBenefit); } function calculatePromo(paymentType,planId,periode = 12,deviceId) { var selectedSalesProgram = $("#promo-program-select").val(); console.log(salesPrograms[selectedSalesProgram]); // Check all value on array structure if(typeof salesPrograms[selectedSalesProgram]["components"][paymentType] !== 'undefined') { if(typeof salesPrograms[selectedSalesProgram]["components"][paymentType][periode] !== 'undefined') { if(typeof salesPrograms[selectedSalesProgram]["components"][paymentType][periode][planId] !== 'undefined') { if(typeof salesPrograms[selectedSalesProgram]["components"][paymentType][periode][planId][deviceId] !== 'undefined') { var promoComponents = salesPrograms[selectedSalesProgram]["components"][paymentType][periode][planId][deviceId]; } else { if(salesPrograms[selectedSalesProgram]["components"][paymentType][periode][planId][1]) { var promoComponents = salesPrograms[selectedSalesProgram]["components"][paymentType][periode][planId][1]; } else { } } } else { } } else { } } else { } console.log(promoComponents) { var devicePrice = $('input[name=device_price]').val(); var programData = salesPrograms[selectedSalesProgram]; var totalSubsidy = 0; if(promoComponents) { if(promoComponents.isat) { totalSubsidy += parseInt(promoComponents.isat); } if(promoComponents.ppp) { totalSubsidy += parseInt(promoComponents.ppp); } if(promoComponents.principal) { totalSubsidy += parseInt(promoComponents.principal); } if(totalSubsidy > 0) { $('#promo-program').val('('+ totalSubsidy.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") +')'); $('.promo-program-wrapper').show(); $('input[name=promo_program]').val(totalSubsidy); $('input[name=promo_program_id]').val($('#promo-program-select').val()); } if(currentPlanBenefit.type == "%") { } if(currentPlanBenefit.type == "IDR") { } if(promoComponents.free_cashout) { cashOut = 0; } $('input[name=cashout]').val(cashOut); $('#cashout').val(cashOut.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.")); } else { $('input[name=cashout]').val(0); $('#cashout').val(0); $('#promo-program').val(0); $('.promo-program-wrapper').hide(); $('input[name=promo_program]').val(0); $('input[name=promo_program_id]').val(""); } } } function calculateCustPay() { var packagePrice = $("input[name=package_price]").val(); var devicePrice = $("input[name=device_price]").val(); var planBenefit = $("input[name=plan_benefit]").val(); var promoProgram = $("input[name=promo_program]").val() ? $("input[name=promo_program]").val() : 0; //var totalPayment = (parseInt(packagePrice) + parseInt(devicePrice)) - (parseInt(planBenefit) + parseInt(promoProgram)); var totalPayment = ((parseInt(packagePrice) * 1.1) + parseInt(devicePrice)) - (parseInt(planBenefit) + parseInt(promoProgram)); if(packagePrice && devicePrice && planBenefit) { $("#total-payment").val(totalPayment.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.")); $("input[name=total_payment]").val(totalPayment); } }<|endoftext|>'use strict'; function SurfaceNormalMapRasterView(options) { var invariant_options = options || {}; this.clone = function() { return new SurfaceNormalMapRasterView(invariant_options); } var exaggeration_factor = invariant_options['exaggeration_factor'] || 100.0; var fragmentShader = fragmentShaders.surface_normal_map; this.mesh = void 0; var mesh = void 0; var grid = void 0; var uniforms = {}; var vertexShader = void 0; function create_mesh(raster, options) { var grid = raster.grid; var faces = grid.faces; var geometry = THREE.BufferGeometryUtils.fromGeometry({ faces: grid.faces, vertices: grid.vertices, faceVertexUvs: [[]], // HACK: necessary for use with BufferGeometryUtils.fromGeometry }); geometry.addAttribute('displacement', Float32Array, faces.length*3, 1); geometry.addAttribute('gradient', Float32Array, faces.length*3*3, 1); attributes: { displacement: { type: 'f', value: null }, gradient: { type: 'v3',value: null }, }, uniforms: { reference_distance: { type: 'f', value: options.reference_distance || Units.EARTH_RADIUS }, world_radius: { type: 'f', value: options.world_radius || Units.EARTH_RADIUS }, sealevel: { type: 'f', value: options.sealevel }, ocean_visibility: { type: 'f', value: options.ocean_visibility }, map_projection_offset: { type: 'f', value: options.map_projection_offset }, }, blending: THREE.NoBlending, vertexShader: options.vertexShader, fragmentShader: fragmentShader }); return new THREE.Mesh( geometry, material); } function update_vertex_shader(value) { if (vertexShader !== value) { vertexShader = value; mesh.material.vertexShader = value; mesh.material.needsUpdate = true; } } function update_uniform(key, value) { if (uniforms[key] !== value) { uniforms[key] = value; mesh.material.uniforms[key].value = value; mesh.material.uniforms[key].needsUpdate = true; } } function update_scalar_attribute(key, raster) { Float32Raster.get_ids(raster, raster.grid.buffer_array_to_cell, mesh.geometry.attributes[key].array); } function update_vector_attribute(key, raster) { var x = raster.x; var y = raster.y; var z = raster.z; var array = mesh.geometry.attributes[key].array; var buffer_array_to_cell = raster.grid.buffer_array_to_cell; for (var i = 0, li = buffer_array_to_cell.length; i < li; i++) { array[i+li*0] = x[buffer_array_to_cell[i]]; array[i+li*1] = y[buffer_array_to_cell[i]]; array[i+li*2] = z[buffer_array_to_cell[i]]; } } this.updateScene = function(gl_state, raster, options) { if (grid !== raster.grid) { grid = raster.grid; this.removeFromScene(gl_state) } if (raster === void 0) { this.removeFromScene(gl_state); return; } if (raster instanceof Uint8Array) { raster = Float32Raster.FromUint8Raster(raster); } if (raster instanceof Uint16Array) { raster = Float32Raster.FromUint16Raster(raster); } if (mesh === void 0) { mesh = create_mesh(raster, options); uniforms = Object.assign({}, options); vertexShader = options.vertexShader; gl_state.scene.add(mesh); // HACK: we expose mesh here so WorldViews can modify as they see fit, // namely for displacement and sealevel attributes this.mesh = mesh; } var world_radius = options.world_radius || Units.EARTH_RADIUS; var gradient = ScalarField.gradient(raster); VectorField.mult_scalar(gradient, exaggeration_factor/world_radius, gradient); update_vector_attribute('gradient', gradient); update_scalar_attribute('displacement', raster); update_uniform('world_radius', options.world_radius || Units.EARTH_RADIUS); update_uniform('ocean_visibility', options.ocean_visibility); update_uniform('map_projection_offset', options.map_projection_offset); update_vertex_shader(options.vertexShader); if (options.displacement !== void 0) { update_uniform('sealevel', options.sealevel); } }; this.removeFromScene = function(gl_state) { if (mesh !== void 0) { gl_state.scene.remove(mesh); mesh.geometry.dispose(); mesh.material.dispose(); mesh = void 0; this.mesh = void 0; } if (grid !== void 0) { grid = void 0; } }; this.updateChart = function(data, raster, options) {} }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-14901.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-14901.jsonl"}]
use super::{super::message::Metadata, message, response, Error, ErrorVerify, Follower, State}; use crate::consensus::{Block, BlockNumber, LeaderTerm}; use pinxit::PeerId; use rand::Rng; use std::net::SocketAddr; use tokio::sync::{MutexGuard, SemaphorePermit}; const SYNCHRONIZATION_BLOCK_THRESHOLD: u64 = 3; impl Follower { /// Synchronize if there is only one instance of synchronisation running. pub async fn synchronize_if_needed( &self, leader_term: LeaderTerm, block_number: BlockNumber, ) -> Result<(), Error> { let synchronizer_permit = self.synchronizer_semaphore.acquire().await; let state = self.state.lock().await; if self.is_synchronization_needed(&state, leader_term, block_number) { // choose peer to ask for synchronization randomly // but ensure, we're not sending the request to ourselves let peers = self.world_state.get().peers; assert_ne!(peers.len(), 1); let peer_address = loop { let peer_index = rand::thread_rng().gen_range(0, peers.len()); let peer = &peers[peer_index]; if peer.0 != *self.identity.id() { break peer.1; } }; self.synchronize(synchronizer_permit, state, peer_address) .await .map_err(|err| { log::error!("Synchronization error: {}", err); err })?; } Ok(()) } /// Check whether we need to synchronize to handle /// a request in a given `leader_term` and `block_number`. fn is_synchronization_needed( &self, state: &State, leader_term: LeaderTerm, block_number: BlockNumber, ) -> bool { let _ = self; leader_term > state.leader_term || block_number >= state.block_number + SYNCHRONIZATION_BLOCK_THRESHOLD } pub async fn synchronize_from(&self, peer_id: &PeerId) -> Result<MutexGuard<'_, State>, Error> { let synchronizer_permit = self.synchronizer_semaphore.acquire().await; if let Some((_, peer_address)) = self .world_state .get() .peers .iter() .find(|(pid, _)| pid == peer_id) { let state = self.state.lock().await; self.synchronize(synchronizer_permit, state, *peer_address) .await .map_err(|err| { log::error!("Synchronization error: {}", err); err }) } else { Err(Error::InvalidPeer(peer_id.clone())) } } async fn synchronize( &self, synchronizer_permit: SemaphorePermit<'_>, state: MutexGuard<'_, State>, peer_address: SocketAddr, ) -> Result<MutexGuard<'_, State>, Error> { let request = message::SynchronizationRequest { leader_term: state.leader_term, block_number: state.block_number, block_hash: state.last_block_hash, }; drop(state); log::trace!( "Trying to synchronize from {} with: {:#?}", peer_address, request ); // send request to peer let response = self.send_message(peer_address, request).await?.into_inner(); let mut state = self.state.lock().await; if let Some((new_leader_term, view_change_signatures)) = response.new_view { self.verify_rpu_majority_signatures( message::ViewChange { new_leader_term }, &view_change_signatures, )?; state.new_leader_term(new_leader_term, view_change_signatures); } if let Some(first_block) = response.blocks.first() { if state.rollback_possible && first_block.block_number() + 1 == state.block_number && first_block.hash() != state.last_block_hash { // We had a chain split. log::trace!("Doing rollback."); state.rollback().await; log::trace!("Done rollback."); } } // verify received blocks, if not timeouted // append correct blocks to own blockstorage log::trace!( "Received {} blocks while synchronizing.", response.blocks.len() ); for block in response.blocks { log::trace!("Applying synchronized block: {:#?}", block); if block.body.height < state.block_number { continue; } self.apply_synchronized_block(&mut state, block).await?; } log::trace!("Done synchronizing."); drop(synchronizer_permit); Ok(state) } async fn apply_synchronized_block(&self, state: &mut State, block: Block) -> Result<(), Error> { block.body.height.verify(state.block_number)?; if block.body.prev_block_hash != state.last_block_hash { return Err(Error::PrevBlockHashDoesNotMatch( block.body.prev_block_hash, state.last_block_hash, )); } // Verify block signatures let block_hash = block.hash(); self.verify_rpu_majority_signatures( response::AckAppend { metadata: Metadata { leader_term: block.body.leader_term, block_number: block.body.height, block_hash, }, }, &block.signatures, )?; let data = &block.body.transactions; if data.is_empty() { return Err(Error::EmptyBlock); } // Validate Transactions self.transaction_checker.verify(data)?; // Persist the blocks after all checks have passed. state.apply_block(block_hash, block).await; Ok(()) } pub async fn handle_synchronization_request( &self, peer_id: PeerId, message: message::SynchronizationRequest, ) -> Result<response::SynchronizationResponse, Error> { log::trace!("Request by {} to synchronize.", peer_id); let (new_view, current_block_number) = { let state = self.state.lock().await; let new_view = if message.leader_term == state.leader_term { None } else { Some((state.leader_term, state.new_view_signatures.clone())) }; (new_view, state.block_number) }; log::trace!( "Synchronizer is at new_view {:?} block_nummer {}.", new_view, current_block_number ); // Only send the block `message.block_number` // if the first requested block's hash does not match the sent one. let mut start_block_number = message.block_number; if start_block_number > BlockNumber::default() { start_block_number -= 1; } let mut blocks_iter = self .block_storage .read(start_block_number..=current_block_number); let first_block = match blocks_iter.next() { Some(Ok(first_block)) if message.block_hash != first_block.hash() => { Some(Ok(first_block)) } Some(Err(err)) => Some(Err(err)), _ => None, }; log::trace!("First block being sent to follower: {:#?}", first_block); let blocks = first_block .into_iter() .chain(blocks_iter) .collect::<Result<Vec<_>, _>>()?; log::trace!("Sending {} blocks to {}.", blocks.len(), peer_id); Ok(response::SynchronizationResponse { new_view, blocks }) } }<|endoftext|>use hex::{decode, encode}; use xsalsa20poly1305::aead::generic_array::{typenum::U24, GenericArray}; use xsalsa20poly1305::aead::{Aead, NewAead}; use xsalsa20poly1305::XSalsa20Poly1305; use ring::signature::{Ed25519KeyPair, Signature, UnparsedPublicKey, ED25519}; use crate::APIError; use crypto_box::{generate_nonce, PublicKey, SalsaBox, SecretKey}; pub const NONCE_LENGTH: usize = 24; pub const SECRET_LENGTH: usize = 32; pub const SECRET_KEY_LENGTH: usize = 32; pub const PUBLIC_KEY_LENGTH: usize = 32; pub const SIGNATURE_KEY_LENGTH: usize = 32; pub trait FromHex: Sized { fn from_hex(bs: &str) -> Result<Self, APIError>; } fn decode_hex_with_length_check(s: &str, length: usize) -> Result<Vec<u8>, APIError> { let raw = decode(&s)?; if raw.len() != length { return Err(APIError::CryptoLengthError { error: format!("supplied: {}, required: {}", raw.len(), length), }); } Ok(raw) } fn check_key(key_hex: &str, length: usize) -> Result<(), String> { let r = decode_hex_with_length_check(key_hex, length); if r.is_ok() { return Ok(()); } else { return Err(r.unwrap_err().to_string()); } } pub fn check_secret_box_key(key_hex: &str) -> Result<(), String> { check_key(key_hex, SECRET_LENGTH) } pub fn check_box_key(key_hex: &str) -> Result<(), String> { check_key(key_hex, SECRET_KEY_LENGTH) } pub fn check_signature_key(key_hex: &str) -> Result<(), String> { check_key(key_hex, SIGNATURE_KEY_LENGTH) } impl FromHex for XSalsa20Poly1305 { fn from_hex(bs: &str) -> Result<XSalsa20Poly1305, APIError> { let raw = decode(&bs)?; if raw.len() != SECRET_LENGTH { return Err(APIError::CryptoLengthError { error: "secretbox secret must be 32 bytes".to_owned(), }); } let key = GenericArray::from_slice(&raw); Ok(XSalsa20Poly1305::new(*key)) } } pub type Nonce = GenericArray<u8, U24>; impl FromHex for Nonce { fn from_hex(bs: &str) -> Result<Nonce, APIError> { let raw = decode_hex_with_length_check(&bs, NONCE_LENGTH)?; let nonce = GenericArray::clone_from_slice(&raw); Ok(nonce) } } impl FromHex for SecretKey { fn from_hex(bs: &str) -> Result<SecretKey, APIError> { let raw = decode_hex_with_length_check(&bs, SECRET_KEY_LENGTH)?; let mut raw_array: [u8; SECRET_KEY_LENGTH] = [0; SECRET_KEY_LENGTH]; raw.iter().enumerate().for_each(|(i, v)| raw_array[i] = *v); let sk = SecretKey::from(raw_array); Ok(sk) } } impl FromHex for PublicKey { fn from_hex(bs: &str) -> Result<PublicKey, APIError> { let raw = decode_hex_with_length_check(&bs, PUBLIC_KEY_LENGTH)?; let mut raw_array: [u8; PUBLIC_KEY_LENGTH] = [0; PUBLIC_KEY_LENGTH]; raw.iter().enumerate().for_each(|(i, v)| raw_array[i] = *v); let pk = PublicKey::from(raw_array); Ok(pk) } } pub fn open_secret_box( cipher_message_hex: &str, nonce_hex: &str, key_hex: &str, ) -> Result<Vec<u8>, APIError> { let salsa = XSalsa20Poly1305::from_hex(&key_hex)?; let nonce = Nonce::from_hex(&nonce_hex)?; let cipher_message = decode(cipher_message_hex)?; salsa .decrypt(&nonce, cipher_message.as_slice()) .map_err(|e| APIError::SecretBoxOpenError { error: format!("decrypt error: {:?}", e), }) // String::from_utf8(message).map_err(|e| APIError::SecretBoxOpenError { // error: format!("decrypted message invalid utf-8: {}", e), // }) } pub fn secretbox_seal(message: &str, key_hex: &str, nonce_hex: &str) -> Result<Vec<u8>, APIError> { let salsa = XSalsa20Poly1305::from_hex(&key_hex)?; let nonce = Nonce::from_hex(&nonce_hex)?; let cipher_message = salsa .encrypt(&nonce, message.as_bytes()) .map_err(|e| APIError::SecretBoxSealError { error: format!("encrypt error: {:?}", e), })?; Ok(cipher_message) } pub fn secretbox_seal_hex( message: &str, key_hex: &str, nonce_hex: &str, ) -> Result<String, APIError> { let cipher_message = secretbox_seal(message, key_hex, nonce_hex)?; let cipher_message_hex = encode(&cipher_message); Ok(cipher_message_hex) } /// returns a tuple (PublicKey, SecretKey) which can be used by box_seal pub fn generate_box_session_keys() -> (PublicKey, SecretKey) { let mut rng = rand::thread_rng(); let sk = SecretKey::generate(&mut rng); let pk = sk.public_key(); (pk, sk) } /// return tuple (public_key, secret_key) hexified pub fn create_session_keys_hex() -> (String, String) { let (pk, sk) = generate_box_session_keys(); let sk_hex = encode(sk.to_bytes()); let pk_hex = encode(pk.as_bytes()); (pk_hex, sk_hex) } pub fn open_box( cipher_text_hex: &str, nonce_hex: &str, pk_hex: &str, sk_hex: &str, ) -> Result<Vec<u8>, APIError> { let secret_key = SecretKey::from_hex(&sk_hex)?; let public_key = PublicKey::from_hex(&pk_hex)?; let nonce = Nonce::from_hex(&nonce_hex)?; let ciphertext_raw = decode(&cipher_text_hex)?; let salsa_box = SalsaBox::new(&public_key, &secret_key); salsa_box .decrypt(&nonce, ciphertext_raw.as_slice()) .map_err(|e| APIError::SessionBoxSecretKeyError {}) } pub fn seal_box( message: &str, sk_hex: &str, pk_hex: &str, nonce_hex: Option<&str>, ) -> Result<(Vec<u8>, Vec<u8>), APIError> { let mut rng = rand::thread_rng(); let secret_key = SecretKey::from_hex(&sk_hex)?; let public_key = PublicKey::from_hex(&pk_hex)?; let nonce = match nonce_hex { Some(nonce_hex) => Nonce::from_hex(&nonce_hex)?, None => generate_nonce(&mut rng), }; let salsa_box = SalsaBox::new(&public_key, &secret_key); let cipher_text = salsa_box .encrypt(&nonce, message.as_bytes()) .map_err(|e| APIError::BoxSealError { error: format!("box encrypt error: {:?}", e), })?; let nonce_vec = Vec::from(nonce.as_slice()); Ok((cipher_text, nonce_vec)) } pub fn seal_box_hex( message: &str, sk_hex: &str, pk_hex: &str, nonce_hex: Option<&str>, ) -> Result<(String, String), APIError> { let (cipher_text, nonce) = seal_box(message, sk_hex, pk_hex, nonce_hex)?; let cipher_text_hex = encode(&cipher_text); let nonce_hex = encode(&nonce); Ok((cipher_text_hex, nonce_hex)) } /// return a hex encoded ed25519 signature as raw byte vector pub fn ed25519_sign_str(message: &str, sk_hex: &str) -> Result<Vec<u8>, APIError> { let sk_raw = decode_hex_with_length_check(&sk_hex, 32)?; let keypair = Ed25519KeyPair::from_seed_unchecked(&sk_raw).map_err(|e| APIError::SignatureKeyError { error: format!("ed25519 key rejected: {}", e), })?; let signature: Signature = keypair.sign(message.as_bytes()); let sig_raw = Vec::from(signature.as_ref()); Ok(sig_raw) } /// return a hex encoded ed25519 signature as hexified string pub fn sign_string(message: &str, sk_hex: &str) -> Result<String, APIError> { let sig_raw = ed25519_sign_str(&message, &sk_hex)?; Ok(encode(&sig_raw)) } pub fn ed25519_verify_str(message: &str, pk_hex: &str, sig_hex: &str) -> Result<bool, APIError> { let pk_raw = decode_hex_with_length_check(&pk_hex, 32)?; let sig = decode_hex_with_length_check(&sig_hex, 64)?; let peer_public_key = UnparsedPublicKey::new(&ED25519, &pk_raw); let verified = peer_public_key.verify(message.as_bytes(), sig.as_ref()); Ok(verified.is_ok()) } pub fn verify_signature( public_key_hex: &str, msg: &str, signature_hex: &str, ) -> Result<bool, APIError> { ed25519_verify_str(msg, public_key_hex, signature_hex) }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-13377.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-13377.jsonl"}]
### Here's set of addition, multiplication, subtraction, division arithmaic examples: 1139 / 1156 = 0.99 ### 82 * 1368 = 112176 ### 1266 + 459 = 1725 ### 653 * 296 = 193288 ### 78 - 174 = -96 ### 1527 - 552 = 975 ### -4 * 1296 = -5184 ### -373 / 867 = -0.43 ### 1407 - 137 = 1270 ### 1496 + 1390 = 2886 ### 1961 + 1040 = 3001 ### 1150 / -574 = -2.0 ### 421 + 255 = 676 ### 876 - 473 = 403 ### 65 * 1434 = 93210 ### 1174 + 2156 = 3330 ### 1376 - 660 = 716 ### -133 / 832 = -0.16 ### 700 * 1347 = 942900 ### 71 * 2094 = 148674 ### 438 * 674 = 295212 ### 433 * 1049 = 454217 ### 73 / -324 = -0.23 ### 372 * 820 = 305040 ### 2247 * 314 = 705558 ### 1224 + 1718 = 2942 ### 94 / -791 = -0.12 ### 1899 + 1537 = 3436 ### -709 / 360 = -1.97 ### -16 * 2175 = -34800 ### 392 * 2236 = 876512 ### 822 / -443 = -1.86 ### 1344 + 1362 = 2706 ### 2133 * 372 = 793476 ### 1603 - 109 = 1494 ### -73 + 2121 = 2048 ### 744 * 262 = 194928 ### 193 - 863 = -670 ### 807 + 488 = 1295 ### -762 / 106 = -7.19 ### 1937 + 2259 = 4196 ### 226 - 1961 = -1735 ### -453 / -229 = 1.98 ### Let's divide 897014 by 82 Our goal is to divide 897014 by 82. Let's proceed to step 1: 8 divided by 82 is 0 with a remainder of 8. The next digit of our result is 0. Result so far: 0.0 Deduct 0 from 8 and we're left with 8. Bring next digit (9) of the dividend behind the 8 and repeat the process: 89 / 82 Let's proceed to step 2: 89 divided by 82 is 1 with a remainder of 7. Record the quotient 1 as the next digit in the result. Result so far: 1.0 If we subtract 82 from 89, we get 7. Grab the next digit (7) from the dividend, add it to 7, then carry on: 77 / 82 Going ahead to step 3: When dividing 77 by 82, we get 0 with a remainder of 77. The next digit of our result is 0. Result so far: 10.0 Deduct 0 from 77 and we're left with 77. Append the next digit (0) from the dividend to 77 and continue with: 770 / 82 Step 4: If we divide 770 by 82, we get 9 and a remainder of 32. Put 9 as the next digit of the answer. Result so far: 109.0 Deduct 738 from 770 and we're left with 32. Include the next digit (1) from the dividend after 32, then repeat: 321 / 82 Going ahead to step 5: 321 divided by 82 is 3 with a remainder of 75. The number 3 becomes the next digit in our result. Result so far: 1093.0 Deduct 246 from 321 and we're left with 75. Grab the next digit (4) from the dividend, add it to 75, then carry on: 754 / 82 On to step 6: If we divide 754 by 82, we get 9 and a remainder of 16. Use 9 as the next digit of our solution. Result so far: 10939.0 Deduct 738 from 754 and we're left with 16. Since there are no more digits in the dividend, we add a zero to the remainder making it 160, and continue the process. Going ahead to step 7: 82 can be fit into 160 1 times, resulting in a remainder of 78. Record the quotient 1 as the next digit in the result. Result so far: 10939.1 Deduct 82 from 160 and we're left with 78. Since there are no more digits in the dividend, we add a zero to the remainder making it 780, and continue the process. Advancing to step 8: If we divide 780 by 82, we get 9 and a remainder of 42. Write down 9 as next digit of the result. Result so far: 10939.19 If we subtract 738 from 780, we get 42. Since there are no more digits in the dividend, we add a zero to the remainder making it 420, and continue the process. Going ahead to step 9: 420 divided by 82 is 5 with a remainder of 10. The number 5 becomes the next digit in our result. Result so far: 10939.195 The remainder is 10 after subtracting 410 from 420. Since there are no more digits in the dividend, we add a zero to the remainder making it 100, and continue the process. Advancing to step 10: 82 can be fit into 100 1 times, resulting in a remainder of 18. Write down 1 as next digit of the result. Result so far: 10939.1951 Subtracting 82 from 100 leaves us with 18. Since there are no more digits in the dividend, we add a zero to the remainder making it 180, and continue the process. Step 11: 180 divided by 82 is 2 with a remainder of 16. Put 2 as the next digit of the answer. Result so far: 10939.19512 If we take 164 away from 180, we end up with 16. Since there are no more digits in the dividend, we add a zero to the remainder making it 160, and continue the process. Let's proceed to step 12: If we divide 160 by 82, we get 1 and a remainder of 78. Record the quotient 1 as the next digit in the result. Result so far: 10939.195121 Subtract 82 from 160 to get 78. Since there are no more digits in the dividend, we add a zero to the remainder making it 780, and continue the process. Moving on to step 13: If we divide 780 by 82, we get 9 and a remainder of 42. Use 9 as the next digit of our solution. Result so far: 10939.1951219 Deduct 738 from 780 and we're left with 42. Since there are no more digits in the dividend, we add a zero to the remainder making it 420, and continue the process. On to step 14: 82 can be fit into 420 5 times, resulting in a remainder of 10. Put 5 as the next digit of the answer. Result so far: 10939.19512195 If we subtract 410 from 420, we get 10. Since there are no more digits in the dividend, we add a zero to the remainder making it 100, and continue the process. The quotient of the division is 10939.19512195, and the remainder is 1e-08.<|endoftext|>### Here are set of multiplication, division, subtraction, addition math guide: 26 / 1211 = 0.02 ### 618 * 1032 = 637776 ### 1893 + 1011 = 2904 ### 1963 + 236 = 2199 ### 1579 + 2269 = 3848 ### -445 / 133 = -3.35 ### 882 - 1322 = -440 ### 866 / 1278 = 0.68 ### 1137 * 872 = 991464 ### 315 * 1138 = 358470 ### 931 - 954 = -23 ### 7 + 6 =\n#### Here we go! We're going to add 7 and 6 together. Step 1: We'll start by adding the digits 7 & 6 in column 1 and get 13. We'll write down the last digit 3 and carry the 1 to the next column. So, 7 + 6 = 13. ### -247 / 569 = -0.43 ### 2073 * 188 = 389724 ### 1003 / -227 = -4.42 ### 952 + 1267 = 2219 ### -309 / -801 = 0.39 ### 24 * 1909 = 45816 ### 61 * 886 = 54046 ### 329 / -412 = -0.8 ### 967 / 897 = 1.08 ### 239 / 318 = 0.75 ### 440 - 339 = 101 ### 1832 * 1091 = 1998712 ### 104 * 385 = 40040 ### 726 / -542 = -1.34 ### 1482 - 1257 = 225 ### -237 / 1268 = -0.19 ### 901 / -95 = -9.48 ### 622 + 1086 = 1708 ### -29 + 1116 = 1087 ### 1378 + 152 = 1530 ### 857 + 439 = 1296 ### 1845 - 431 = 1414 ### 1223 * 582 = 711786 ### 1096 * 786 = 861456 ### 2257 + 1096 = 3353 ### 16 * 148 = 2368 ### 917 - 1024 = -107 ### 1932 + 79 = 2011 ### 707 - 1351 = -644 ### 102 / -80 = -1.27 ### 1147 * -48 = -55056 ### 344 - 1208 = -864 ### 1628 * 888 = 1445664<|endoftext|>### Here is some exercises for subtraction, addition, division, multiplication math insights: 695 + 1380 = 2075 ### 199 / 206 = 0.97 ### 652 + 1693 = 2345 ### 1057 - 1348 = -291 ### 383 + 1374 = 1757 ### 23 / 1168 = 0.02 ### 1985 - 2260 = -275 ### 131 / 257 = 0.51 ### 491 / 664 = 0.74 ### 87 / -612 = -0.14 ### 391 - 685 = -294 ### 658 / 1300 = 0.51 ### 1713 + 2232 = 3945 ### 2239 * 213 = 476907 ### 901 * 485 = 436985 ### 1599 * 13 = 20787 ### 825 * 91 = 75075 ### 747 * 704 = 525888 ### 1508 + 509 = 2017 ### 2232 - 2006 = 226 ### -73 + 1034 = 961 ### 361 / -925 = -0.39 ### 1367 - 734 = 633 ### -43 - 1605 = -1648 ### 2138 - 1479 = 659 ### 375 - 1662 = -1287 ### 2037 * 81 = 164997 ### 1791 * 528 = 945648 ### 1025 * 2269 = 2325725 ### 958 / 1214 = 0.79 ### 856 - 594 = 262 ### 1469 + 53 = 1522 ### 1011 / 1341 = 0.75 ### 380 - 450 = -70 ### 1285 + 1369 = 2654 ### -766 / 1259 = -0.61 ### 859 / -847 = -1.01 ### The age difference between Alexander and Asaf's age is half the total number of pencils Alexander has. The sum of their ages is 114, and Alexander is 26 years old. If Asaf has 60 more pencils than Alexander, calculate the total number of pencils they have together. Solution: If the sum of their ages is 114, and Alexander is 26 years old, Asaf is 88 years old. The age difference between Alexander and Asaf's age is 88-26 = 62. Since the age difference between Alexander and Asaf's age is half the total number of pencils Alexander has, Alexander has 2*62 = 124 pencils. If Asaf has 60 more pencils than Alexander, Asaf has 124+60= 184 pencils. Together, they have 124 + 184 = 308 pencils.
[{"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}]
Q: How to copy from a pdf to another pdf in ubuntu/linux So Preview for Mac OS X has this capability. I want to be able to just highlight whatever on a pdf, and be able to copy and paste immediately into another pdf file (via the clipboard). I do a lot in LaTeX, and this would really make things easier why TeXing in ubuntu/linux. A: uPDF is an editor tool to write and paint to an existing pdf file. uPdf can insert pages of another pdf, insert new pages, remove and extract pages, rotate pages, paste a text or an image in the existing pdf, and much more. You can install it in Ubuntu using ppa. For the moment, as I checked on [IDX] the uPDF ppa supports only Ubuntu 12.10 and 12.04. To install it, open a terminal and run next commands: sudo add-apt-repository ppa:atareao/updf sudo apt-get update sudo apt-get install gir1.2-rsvg-2.0 updf If you use KDE you may also need to install the following dependency: sudo apt-get install-0.1 gir1.2-appindicator3 More info: Install uPDF (effective pdf editor) in Ubuntu 12.04 /12.10 Another tool for editing pdf files and that can be found in Ubuntu Software Center is Master PDF Editor - a complete solution for view, print and edit PDF and XPS files. A: Try PDF Mod: PDF Mod is a simple application for modifying PDF documents. You can reorder, rotate, and remove pages, export images from a document, edit the title, subject, author, and keywords, and combine documents via drag and drop. sudo apt-get install pdfmod Or PDF-Shuffler: PDF-Shuffler is a small python-gtk application, which helps the user to merge or split pdf documents and rotate, crop and rearrange their pages using an interactive and intuitive graphical interface. It is a frontend for python-pyPdf. sudo apt-get install pdfshuffler See also: * *Create a single pdf from multiple text, images or pdf files A: This was my question as well, since I used this functionality in Mac Preview a lot. The best solution I found in Ubuntu is to use PDF Master Editor (the free version will do). You can select a range and copy it, open a blank .pdf file with Ctrl+N and paste the selection there. If you don't like the white margins, you can then crop using Document => Crop menu (Ctrl+K). Unrelated to your question, this application is also great for annotating and highlighting in Linux (which is missing from many common Linux PDF-viewers).<|endoftext|>Q: Dependent and independent KCL equations Can someone explain what dependent and independent KCL equations mean to us, and how we can determine what is number of dependent/independent equations? I am reading about KCL and they said: I don't understand this part: This in turn shows that the four KCL equations are dependent? What that dependent means to us when we have 4 KCL equations? A: If you have a network with n nodes, there will be \$n-1\$ independent KCL equations. That means the KCL equations alone are not sufficient to produce a unique solution to the circuit. One more equation is required to produce a solvable set of equations. Normally, the one additional equation is produced by designating one of the nodes as the "ground" node, and arbitrarily choosing that its potential will be considered as 0 V. A: This may even become more clear when you start solving systems using matrices. The above system will produce an incidence matrix and you chose to leave out one (usually the last ) row, which equates to choosing the node in the last row as a reference node(usually 0 V). The above system produces Nn-1 equations, however you need Nl equations in order to solve the system. The remaining equations arise by applying KVL to the circuit which yields Nl-Nn+1 equations. Notice when you add up everything Nn-1+Nl-Nn+1=Nl, you get an independent system of Nl linear equations. A: A set of N linear equations are dependent if one equation can be written as the linear combination of the remaining equations. Any set of values that satisfying the first N-1 equations will also satisfy their linear combination - the Nth equation. So there is no point in adding an extra redundant equation to the set when N-1 equations can do the same job. Example Consider the set of equations given in the original post. Equation (2.8) can be represented as: $$(2.8) = -(2.5)-(2.6)-(2.7)$$ So any set of values of currents satisfying equations (2.5),(2.6) and (2.7) will also satisfy their linear combination - and hence equation (2.8). So adding equation (2.8) is adding redundancy. Dependency expressed in other words: A set of N equations are dependent if there exist any linear combination of these N equation that gives a result 0=0: $$\sum_i c_iE(i)\Rightarrow0=0$$ where \$c_i\ne 0\$. This definition is used in OP to say that the set of equations are dependent.<|endoftext|>Q: 555 Timer in monostable mode with reset on the same momentary button I've been researching this problem for a few days. I have a 555 timer for controlling a car heated windshield, and I'd like to have a single button controlling it, and use that same button to cancel mid-timer, if the user doesn't need the full duration. I've so far come up with the following schematic, and have been testing on protoboard: It has a 555 timer with around a 5 minute timer (doesn't need to be exact), and the output switches a mosfet configuration which turns on a relay. This relay then changes which line the switch pulls to GND from trigger to reset. My problem is that when I have this circuit built, pushing the button causes the relay to energise, which pulls reset low before I can release the button, so the relay vibrates on and off rapidly, which gives an unpredictable output. I think I might need to debounce the switch, but I am not sure what the best way to do this is (other than just putting a capacitor in parallel), and also I may need to delay the pull-down of the reset pin on the 555 so I don't end up with this vibrating effect, which I think is unrelated to the debouncing. I've found this link which seems to do what I want, but I don't think the schematic they used is noticably different to the one I've designed. Appreciate any help. A: Rather than trying to delay operation of the reset function, you're better off trying to delay the trigger function. It's not a bouncing issue, simply that as soon as the RESET input is activated, the relay turns off and the TRIG line is activated, turning the relay on and starting the cycle again. You've effectively made an oscillator. The key difference between that circuit you found and yours is the capacitor on the RESET line. Pressing the button to turn the circuit off discharges that capacitor through the button, and it prevents the TRIG input from having any effect until it's charged back up again, and that doesn't start until the reset has taken place and the relay has switched. The circuit will still oscillate, but much more slowly and controlled by the RC values used on the RESET input. One way to prevent this altogether would be to use a more complex circuit with the button used to clock a flip-flop, but I would think an RC delay of two or three seconds would probably be good enough for your application.<|endoftext|>Q: Wifi Connections on ubuntu 16.04 LTS not available as an option First some clarification of the problem might be needed: I am running Ubuntu Gnome 16.04 LTS on a Dell Latitude E6220 with a windows 7 dual boot. The machine turns on with no problems, but once logged on there is no option in settings to configure wireless connections, nor does the machine connect automatically to my access point as it would usually. The output of rfkill: 1: dell-wifi: Wireless LAN Soft blocked: no Hard blocked: no 2: dell-bluetooth: Bluetooth Soft blocked: no Hard blocked: no 4: hci0: Bluetooth Soft blocked: yes Hard blocked: no would indicate that Ubuntu recognizes there is a wireless card installed, however ifconfig: eno1 Link encap:Ethernet HWaddr 84:8f:69:f0:a9:2b inet addr:10.156.204.69 Bcast:10.156.207.255 Mask:255.255.240.0 inet6 addr: fe80::fc2d:79c9:4832:5f54/64 Scope:Link RX packets:11059 errors:0 dropped:0 overruns:0 frame:0 TX packets:6824 errors:0 dropped:0 overruns:0 carrier:0 RX bytes:12929276 (12.9 MB) TX bytes:682773 (682.7 KB) Interrupt:20 Memory:e1c00000-e1c20000 RX packets:552 errors:0 dropped:0 overruns:0 frame:0 TX packets:552 errors:0 dropped:0 overruns:0 carrier:0 RX bytes:81751 (81.7 KB) TX bytes:81751 (81.7 KB) contradicts this, as does: sudo lshw -C network both indicating that there is no wireless card installed (which there is). Attempting to turn on the card as I have seen suggested elsewhere using ifconfig with: sudo ifconfig wlan0 up gives the following error: wlan0: ERROR while getting interface flags: No such device Fiddling with aeroplane mode and the physical switch on the machine also has no effect. I am at a loss to suggest what may have caused this as the previous session to the one where the issue occurred I made no changes to any relevant settings or installed or removed any networking related packages, although I know that it can't be a physical issue with the card because windows works fine. solution: having read Installing Broadcom Wireless Drivers and having followed the instructions to reinstall the device driver for my wireless card, wifi connection shows up as an option, and after reboot and disconnecting ethernet, the problem disappears.<|endoftext|>Q: SQL Server Memory Determination We will be modifying a SQL Deployment in our Hosted Environment. We have a solution which is currently configured to use one Application (and not SQL) System Database (which holds Security and System Level Configurations for our Application) and numerous independent Company Databases, each used by different users (originating from independent Organizations hosted in our Environment). We will be changing this deployment, after which each Organization will have its own System Database (instead of using a unique one for all Organizations). Thus, each Company Database will now have an associated Application specific System Database. To summarize, before the deployment let us suppose that a Server had 100 Company Databases and one System Database, it will now have 100 Company Databases, plus 100 System Databases. Thus, the number of Databases will have doubled. Meanwhile, the number of transactions on the SQL Server will be identical. As an example, upon logging into a Company Database, a user will log into its associated System Database first in order to verify its Application specific Security Role for instance, instead of accessing the shared System Database as before. Hence, the Number of transactions launched against the System Databases will remain the same (as when there were only one of them), but the number of Databases will double. Considering that the Number of Transactions will remain the same, but that the Number of Databases on the SQL Server Instance will double, how should we determine how much more Memory should we be adding (if any) to the Server? Thank you. A: "Should I add more memory to the server" is a tough question to answer. Your box might be coping "just fine" with what it has, or you may find that tuning the system in other ways (expensive queries, for example) would be more effective. There are a number of resources that you should consider, including Jon Kehayias' How much memory does my SQL Server actually need, as suggested by Aaron in the comments. Your system may have other bottlenecks apart from memory, particularly if there are a lot more databases, such as disk reads/writes. Writing to log files, reading from data files - it all adds up. But as far as memory is concerned, if you think your current system could cope with less RAM, then it should be able to cope with more databases and the same RAM.
[{"idx": "https://askubuntu.com/questions/120077", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-27123.jsonl"}, {"idx": "https://electronics.stackexchange.com/questions/202359", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-27123.jsonl"}, {"idx": "https://electronics.stackexchange.com/questions/318656", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-27123.jsonl"}, {"idx": "https://askubuntu.com/questions/995285", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-27123.jsonl"}, {"idx": "https://dba.stackexchange.com/questions/127401", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-27123.jsonl"}]
numbers: is prime composed -------------------------- Conundrum: Suppose 12318 = -3*a - 2*s, 5*a = 2*s + 2*s - 20530. Is (-6 - (-33)/6)*a composite? Reply: False Conundrum: Let d(u) = u**3 - 2*u**2 + 3*u + 1. Let m be d(2). Suppose -3*n = -m - 2. Suppose -2*i + 1877 = n*z, -3*i - 2*i + 4*z + 4727 = 0. Is i a prime number? Reply: False Conundrum: Let r(p) = -164*p**2 - 3*p - 12. Let q(d) = -41*d**2 - d - 3. Let k(z) = -9*q(z) + 2*r(z). Suppose -5*t - 3*u + u - 14 = 0, t + 4 = -u. Is k(t) a prime number? Reply: False Conundrum: Suppose 230 = 5*s - 300. Is s a composite number? Reply: True Conundrum: Let c(w) be the second derivative of 0 + 2/3*w**3 - 1/6*w**4 + w - w**2 + 3/10*w**5. Is c(2) a prime number? Reply: False Conundrum: Let c(x) = x + 10 + 3*x + 0*x - 3*x. Let w be c(-7). Is w + -1 - (0 - 69) composite? Reply: False Conundrum: Suppose -4*t + 6641 = 3*z, 4*z - 5*z + 8315 = 5*t. Let f be (-2)/9 - t/(-36). Suppose -a = -3*r + f, 2*r - 5*a - 6 = 42. Is r prime? Reply: False Conundrum: Suppose -4*h + 10 = u - 1, -h + u = -4. Suppose -2*i = -0*i - 4*z - 4530, 4*z - 6825 = -h*i. Let g = i - 1280. Is g a prime number? Reply: True Conundrum: Let i(c) = -36*c - 13. Let f be 2/5 - (-228)/30. Suppose -4 = 2*d + f. Is i(d) a composite number? Reply: True Conundrum: Let c be (27/(-12))/((-9)/24). Let d = 11 - c. Suppose 0 = -d*f + 25, 4*r + 3*f - 89 = 26. Is r a composite number? Reply: True Conundrum: Let c(x) = 177*x**2 - 37*x + 1. Is c(-4) a composite number? Reply: True Conundrum: Suppose -3*r = -5*p + 32, 0*p + p + 4*r - 11 = 0. Let i be p + -9 + 4890/2. Suppose -2*q - 4*t + 2*t + 4910 = 0, i = q - 5*t. Is q composite? Reply: True Conundrum: Let h(w) = w**3 + 4*w**2 + w. Let f be h(-3). Suppose -327 = 3*i - f*i. Is i a composite number? Reply: False Conundrum: Suppose 0 = 3*q - 2*j + 16, 2*q - q = 2*j. Suppose 0 = 5*c + 3*r - 203, -5*c + 3*c + 4*r + 76 = 0. Is (6/q)/((-2)/c) composite? Reply: True Conundrum: Let l = -23 + 88. Suppose l = 8*w - 7*w. Is w composite? Reply: True Conundrum: Suppose o - 17 = -4*z, 5*z + 0*z = -4*o + 35. Is 2204 + 5/(-15)*z prime? Reply: True Conundrum: Let q be (-495310)/(-42) + 5/(-420)*8. Suppose 3*w - 12501 = q. Is w composite? Reply: True Conundrum: Suppose 5*p + 17 = 252. Suppose 2*a + 5 - 13 = 0. Suppose 1277 = a*d - p. Is d a composite number? Reply: False Conundrum: Let c = -102 + 191. Is c a prime number? Reply: True Conundrum: Let o(u) = 36*u + 3. Is o(8) a prime number? Reply: False Conundrum: Let t = -14 + 19. Suppose t*r - 25 = 0, -2*r + 5*r = y - 152. Is y a composite number? Reply: False Conundrum: Is 67*((-456)/84)/(4/(-14)) a prime number? Reply: False Conundrum: Let n be (16/(-10))/((-2)/20). Suppose 131 = 5*l + n. Let u = l + -10. Is u a prime number? Reply: True Conundrum: Let b(y) = -y**3 - 11*y**2 + 1. Suppose 3*o = -2*s - 27, 2*o + 0*o + 37 = 5*s. Let a be b(o). Is a*361 + -3 + (6 - 5) a prime number? Reply: True Conundrum: Suppose 6*f = -6*f - 192. Is (-4)/f + 4041/12 + 2 prime? Reply: False Conundrum: Let i(f) = 4*f**2 + 22*f + 10. Let u be i(-6). Is (u/4 + -4)*1546 a composite number? Reply: True Conundrum: Let k be (8 + -2 - -2) + 1. Is (113/3)/(3/k) a composite number? Reply: False Conundrum: Let y be -4 - ((-52)/6 - 4/(-6)). Suppose -5*k - 275 = 2*l - 1109, -y*k = 2*l - 838. Is l a prime number? Reply: False Conundrum: Suppose -1055658 = 176*a - 178*a - 167780. Is a composite? Reply: False Conundrum: Let t(a) be the third derivative of 7*a**5/60 + 3*a**4/8 - 5*a**3/6 + 4*a**2. Is t(-8) prime? Reply: False Conundrum: Suppose 22*x - 60489 - 37213 = 0. Is (3 + x - (-1 - -1)) + -2 a composite number? Reply: True Conundrum: Let a be 2*(1 - (-7)/(-2))*1. Let j(g) = 0 + 1 + 3 - 63*g. Is j(a) prime? Reply: False Conundrum: Let r be (-1)/((6/(-4))/3). Suppose q = -r*q + 438. Suppose -4*i + 6*l = 4*l - 150, -q = -4*i - 2*l. Is i a composite number? Reply: False Conundrum: Let f(h) = 7*h**2 + 9*h + 5. Let d be f(-9). Suppose d = 4*r - 17. Is r composite? Reply: False Conundrum: Let a be ((-6)/(-5))/((-1)/5). Let x(r) be the first derivative of r**3 - 5*r**2 - 9*r - 11. Is x(a) prime? Reply: False Conundrum: Let s be 1 + 32 + 0/2. Is 4/(8/s)*536/12 a prime number? Reply: False Conundrum: Suppose -y + 393 = 4*x, -1192 = 2*y - 5*y + x. Is y a prime number? Reply: True Conundrum: Let a(v) = 23*v**2 + 7*v - 31. Let f(h) = -11*h**2 - 3*h + 14. Let k(r) = 3*a(r) + 5*f(r). Suppose -s = 3, -4*s = -4*n + 19 + 25. Is k(n) composite? Reply: True Conundrum: Let y = 2 + 0. Let v(k) = 2*k**2 + 4*k + 6. Let w(x) = -3*x**2 - 5*x - 7. Let s(n) = -5*v(n) - 4*w(n). Is s(y) a prime number? Reply: False Conundrum: Suppose -19*o + 381907 = -283378. Suppose 6*x = 39175 + o. Is x a composite number? Reply: True Conundrum: Suppose -3*o - 2*w + 9 = 2*w, 0 = 5*o - 4*w - 15. Suppose -3*q - 3 = 2*d - 2785, -o*d = -q - 4195. Is d composite? Reply: True Conundrum: Suppose 1346 - 336 = 5*t. Is t a composite number? Reply: True Conundrum: Let f = -524 + 2209. Is f a prime number? Reply: False Conundrum: Let u = 5899 - 9777. Let c = u + 7399. Let p = -2044 + c. Is p a prime number? Reply: False Conundrum: Let l(u) = u + 0*u + 4*u - 8*u + 20. Let h be l(6). Is ((-3812)/(-12))/((2/3)/h) prime? Reply: True Conundrum: Let r = 1071 - 100. Is r composite? Reply: False Conundrum: Suppose -6 = -0*y + y. Let i be -3*y/(-45)*5. Is -242*3/(-6) + i composite? Reply: True Conundrum: Let q(p) = 491040*p**2 + 29*p + 26. Is q(-1) a composite number? Reply: True Conundrum: Suppose 215*b = 226*b - 18227. Is b prime? Reply: True Conundrum: Let a(m) = -m**2 - 7*m - 4. Let z(w) = -w**3 - 12*w**2 - 10*w + 5. Let i be z(-11). Let s be a(i). Suppose -255 = -s*v - 25. Is v a composite number? Reply: True Conundrum: Let w(r) = 51*r**3 + 2*r**2 - 2. Let v(z) = -101*z**3 - 5*z**2 + z + 4. Let c(g) = 2*v(g) + 5*w(g). Let b be c(1). Suppose 25 = 2*x - b. Is x prime? Reply: False Conundrum: Let k(p) be the second derivative of 0 - 7*p - 9/2*p**2 + 101/6*p**3. Is k(8) prime? Reply: False Conundrum: Suppose 836 = 2*j + 58. Is j prime? Reply: True Conundrum: Let k = 19 - -12. Suppose -6*n - k = -97. Suppose n*d = 9*d + 74. Is d a composite number? Reply: False Conundrum: Let r(w) = -169*w - 74. Is r(-63) composite? Reply: True Conundrum: Let c be (-1 - (-5 - -3))*(0 - -387). Suppose 0 = t - 2, 4*t - t = 3*k - c. Is k a prime number? Reply: True Conundrum: Let j be 1 + -1 + 0 + 13. Let m = j + 6. Is m a composite number? Reply: False Conundrum: Let x(g) = -23*g. Let z(u) = -23*u + 1. Let d(i) = -2*x(i) + 3*z(i). Let y be d(-5). Suppose -y = -5*j - 4*r, -5*j + 0*r + 2*r = -106. Is j a composite number? Reply: True Conundrum: Suppose -5*s + 573 + 97 = 0. Let t be (-12)/(-8)*s/3. Suppose -3*q + 4*q - t = 0. Is q composite? Reply: False Conundrum: Suppose -217*t + 654398 = 4*y - 218*t, -2*y + 3*t + 327184 = 0. Is y composite? Reply: False Conundrum: Let g(r) = 25 - 2*r**3 + 3*r**3 - 21*r - 21 - 2*r**2 - 5*r**2. Is g(13) prime? Reply: False Conundrum: Let n(s) = -s. Let d(v) = -v**2 - 9*v + 2. Let m(y) = d(y) - 4*n(y). Let p be m(-5). Suppose -4*q + 35 = k, -3*q + 5 = -p*q. Is k composite? Reply: True Conundrum: Let h = 35 + -37. Is 1/h*(-2624 - 2) a prime number? Reply: False Conundrum: Let k(i) = -i**2 - 2*i - 1. Let f be k(-3). Is (99 - 1)*(-2)/f prime? Reply: False Conundrum: Let g(k) = 4961*k**2 + 165*k - 771. Is g(5) composite? Reply: True Conundrum: Let y be (-5)/(9 + 6)*(0 + 0). Suppose y = -5*w + 21797 + 4568. Is w a composite number? Reply: False Conundrum: Let y(a) = 45*a - 2. Let w(d) = d + 1. Let p(l) = -10*w(l) - 2*y(l). Let i be p(-6). Suppose -2*q + i = -2*h, -4*q + h = -4*h - 1192. Is q a composite number? Reply: False Conundrum: Let k = -17 - -24. Suppose -19 = 4*s - k. Is s + 6 - (-315 + 1) composite? Reply: False Conundrum: Let m be ((-21)/6 + 4)/((-3)/(-24)). Suppose 4*l + 0*l = u - 7939, -m*u - 4*l = -31756. Is u a composite number? Reply: True Conundrum: Let a be 12/2*(-4)/(-12). Suppose -a*k + 2*l = -3*l - 127, -3*k + 2*l = -163. Is k a prime number? Reply: False Conundrum: Let f(m) = 18*m**2 + 19*m + 19. Let j be f(9). Suppose 0 = 3*v - 3*a - 2232, 4*a - 162 = 2*v - j. Is v composite? Reply: True Conundrum: Let d(h) = 62*h**2 - 15*h - 12. Is d(7) composite? Reply: True Conundrum: Suppose 4*y = 4*v + 27 + 17, -y = 2*v + 19. Is 1396 + ((-6)/v)/(5/25) a prime number? Reply: True Conundrum: Let s(u) = -786*u - 9. Let a(g) = -5*g**3 + 4*g**3 - 4*g**2 + 5*g + 543 - 545. Let v be a(-5). Is s(v) composite? Reply: True Conundrum: Let o(l) = l + 17. Let u be o(-14). Let d(j) = 88*j + 9. Let f be d(u). Suppose f = a - 58. Is a prime? Reply: True Conundrum: Let a = -91 + 91. Is 734 + (-2)/4*a/(-2) a prime number? Reply: False Conundrum: Let o(k) = k**3 + 6*k**2 - 6*k + 5. Let g be o(-7). Let n = -2 + -4. Is g/n + (-816)/(-9) a prime number? Reply: False Conundrum: Let k(y) be the second derivative of -y**3/6 + 19*y**2/2 - 313*y. Let t(n) = n**3 - 6*n**2 + 5*n. Let z be t(5). Is k(z) composite? Reply: False Conundrum: Suppose 5*u - 11 - 4 = 0. Let i = -9 + u. Is i/(-9) + 470/6 composite? Reply: False Conundrum: Let p(n) = 2*n**2 - 94*n - 160. Let g be p(49). Suppose 101826 = -g*m + 42*m. Is m a prime number? Reply: False Conundrum: Let z(j) = j**2 + 80*j + 61. Let i be z(-34). Let k = i - -4018. Is k composite? Reply: True Conundrum: Let l = 31422 + 1117. Is l composite? Reply: True Conundrum: Let w = 27 - 24. Let x(o) = 5*o**3 + 1. Let i be x(1). Suppose w*d - i*d = -327. Is d a composite number? Reply: False Conundrum: Let n(t) be the first derivative of -t**4/4 + 11*t**2/2 + 19*t + 1. Suppose -74*s - 282 = 310. Is n(s) a prime number? Reply: True Conundrum: Let d = 164936 + -75243. Is d prime? Reply: False Conundrum: Let s be -4 + (1 - (-5 + 4)). Is 112/196 + (-53458)/(-14) + s prime? Reply: False Conundrum: Let k(x) = -3*x - 1. Let q(w) = 16*w + 6. Let r be 84/8 + (-1)/(-2). Let y(m) = r*k(m) + 2*q(m). Is y(-1) a composite number? Reply: False Conundrum: Let x = 1 - -2. Suppose 5*m + 4 = -x*n, n - m = 3 + 1. Suppose -357 = n*d - 5*d. Is d a composite number? Reply: True Conundrum: Suppose -4*m = -m + 1974. Suppose 3*w + 2*p = -21 - 3, -p = 3*w + 24. Is (m/w + 2)*4 composite? Reply: False Conundrum: Let k(l) = 7999*l + 327. Is k(38) prime? Reply: False Conundrum: Let n(z) = 24*z + 5. Suppose -2*b - 22 = -2*c, -c + 19 = -3*b - 0*b. Let h be 7/(-2)*(-12)/c. Is n(h) a prime number? Reply: True Conundrum: Suppose -5*d + o - 9 = 0, -2*d - o + 5*o = 18. Let b be (-6 - -7)/(d/(-2)). Let q(y) = 5*y**3 - y**2 - 2*y - 1. Is q(b) a prime number? Reply: True Conundrum: Let n = -196314 + 468811. Is n composite? Reply: True Conundrum: Let r be 4/20 + 2/(-10). Suppose w - 14 - 99 = r. Is w a prime number? Reply: True Conundrum: Let g(h) = h**3 + 15*h**2 + 12*h - 23. Let z be g(-14). Suppose 3*x - 1555 = 2*q, -3*x - z*q = -7*x + 2064. Is x prime? Reply: True Conundrum: Let m(z) = 7*z**2 - 10*z + 2. Is m(9) prime? Reply: True Conundrum: Let f = 3 - -1. Suppose f*j + 79 = 267. Is j a composite number? Reply: False Conundrum: Let j(l) = -l - 8. Let a(z) = -z - 7. Let u(v) = 5*a(v) - 4*j(v). Let w be u(-7). Suppose -p = w*p - 23105. Is p prime? Reply: True Conundrum: Let l be 0 + -1 + (-180)/2. Let p be l - (0 + (-2 - -2)). Let f = 182 + p. Is f a composite number? Reply: True Conundrum: Let s(x) = 57*x + 63. Let o(q) = -12*q - 9. Let f(p) = 25*p + 18. Let k(r) = 4*f(r) + 9*o(r). Let b(m) = 15*k(m) + 2*s(m). Is b(-7) a prime number? Reply: False Conundrum: Let z(t) = -3*t**3 + 11*t - 9. Suppose 4*g - 8*g = f + 31, -5*f = -3*g - 29. Is z(g) prime? Reply: True Conundrum: Let z(l) = -39*l**2 - 7*l - 41. Let q(k) = 157*k**2 + 27*k + 166. Let a(n) = -2*q(n) - 9*z(n). Is a(-13) prime? Reply: True Conundrum: Suppose -r + 5*r - 17309 = -5*j, 5*r = 5*j + 21580. Is r prime? Reply: False Conundrum: Suppose -3*d = -10*d - 2702. Let l be (d/6 + -2)/((-7)/567). Is (l/(-45))/((-1)/5) composite? Reply: True Conundrum: Suppose -4*f - 7 = -i, 0 = 5*f - 0*i - 2*i + 5. Let k be (f - (-68)/20)*(1 - -9). Suppose k*n + 4*l = l + 1781, -5*n = 2*l - 2235. Is n a composite number? Reply: False Conundrum: Let t be (52/(-20) + 2)/(8/120). Let s(r) = -4*r**3 + r**2 + 11*r - 37. Is s(t) composite? Reply: False Conundrum: Let t(b) = 18*b**2 + b - 8. Let m(x) = -36*x**2 - 2*x + 17. Let r(y) = 6*m(y) + 13*t(y). Let f be r(6). Is (-2)/7 + f/28 composite? Reply: False Conundrum: Let j(h) = -h - 85. Let k(c) = -1. Let d(q) = -j(q) + 2*k(q). Is d(0) a composite number? Reply: False Conundrum: Suppose 0 = 2*i + 77 - 39. Let r = i - -21. Is (-48 + 2/r)*-7 composite? Reply: True Conundrum: Let u(f) = 9*f**2 - 4*f - 1. Let j be u(-1). Suppose -j*s - 18715 = 4301. Let z = 177 - s. Is z prime? Reply: False Conundrum: Let w(q) = 194*q - 15. Let u(i) = i**3 - 4*i**2 - 3*i - 5. Let l be u(5). Is w(l) prime? Reply: False Conundrum: Let i(o) be the first derivative of 3245*o**3/3 - 6*o**2 - 2*o - 9. Is i(-3) a composite number? Reply: True Conundrum: Let m be 44/(12/3) + 1. Is 11/(-66) - (-10790)/m composite? Reply: True Conundrum: Let t(u) = 3*u**2 - 14*u - 210. Is t(-29) a composite number? Reply: False Conundrum: Let h(k) be the second derivative of 5*k + 29/6*k**4 - 1/3*k**3 + 0 - 1/2*k**2. Is h(-1) prime? Reply: True Conundrum: Suppose 0 = -2*n - 108 + 1622. Is n a prime number? Reply: True Conundrum: Let c = -19 - -31. Is (56/(-6))/((-8)/c) composite? Reply: True Conundrum: Let x(z) = z**2 + 2*z - 5. Let d be x(-4). Suppose -4*v - d*h = -107, -2*v = -0*v + 2*h - 54. Is v a prime number? Reply: False Conundrum: Is (-14153)/(-5) - (-110)/275 a composite number? Reply: True Conundrum: Suppose -f + 0 = 5. Let n be (1 + 14)*f/(-15). Is (-4)/(-10) + 53/n composite? Reply: False Conundrum: Let o = 12 + -8. Let c be 3/(7 - o)*563. Suppose 2*n - c = 3*a, -2*a + a + 274 = n. Is n a prime number? Reply: True Conundrum: Let i(n) = -n - 4. Let g be i(-5). Is ((-7)/1 + g)*(-162696)/144 prime? Reply: True Conundrum: Is (-30)/150*71719*-5 prime? Reply: True Conundrum: Let a(f) = -f - 2. Let i be a(-5). Suppose 784 = 5*v - i*c, -332 = 5*v - 2*c - 1113. Suppose -3*k + v = 2*k. Is k a composite number? Reply: False Conundrum: Let p(d) = -d - 3. Let x be p(-5). Let g be 321/(-12) + (-2)/8. Is (-1803)/g - x/(-9) composite? Reply: False Conundrum: Let n be (15 + -9)*7/(-14). Is n - (-9491 + -6 - (-2 - 1)) composite? Reply: False Conundrum: Suppose 11*m - 529768 - 183021 = 0. Is m prime? Reply: False Conundrum: Let n be ((-1)/(-2))/((-2)/(-524)). Suppose -4*r - 591 + n = -4*s, -5*r + 15 = 0. Is s composite? Reply: True Conundrum: Suppose 0*h - 6 = -3*h. Suppose h*j - 75 = -j. Is j prime? Reply: False Conundrum: Suppose -5*z + 47 = -58. Is z a composite number? Reply: True Conundrum: Is (3 + -14816)/(-7 + (-3 - -9)) composite? Reply: False Conundrum: Let g(i) = 6*i**3 + 3*i + 4. Let d be g(4). Suppose -d*n + 404*n = 580. Is n composite? Reply: True Conundrum: Let k(u) = -10*u - 21. Let g be (((-18)/(-8))/3)/(5/20). Suppose -21 = 2*w + b, g*w - 3*b - 47 = 7*w. Is k(w) a composite number? Reply: False Conundrum: Is (2/3)/((4/(-4629))/(-2)) a prime number? Reply: True Conundrum: Suppose 45*q = -45*q + 58*q + 3813088. Is q prime? Reply: True Conundrum: Let p(m) = -398*m**3 + m. Is p(-1) a prime number? Reply: True Conundrum: Let q = 31692 - 20143. Is q prime? Reply: True Conundrum: Let z be (-2 - -2 - -5) + 2. Suppose v + 7 = 5*k - 0*v, 2*k + v = z. Suppose -4*i + k*g = -3*i - 247, -3*g = -i + 242. Is i composite? Reply: False Conundrum: Is (726453 - -148) + (-1 - -3)*5 composite? Reply: False Conundrum: Suppose 0 - 3 = -3*d + 3*f, -5*d = 4*f - 23. Suppose d*q = -3*n + 8871, -4*n = -q + 6*q - 14785. Is q prime? Reply: True Conundrum: Let y be (-3)/4 + 90/24. Let j(a) = 5*a**2 + 3*a**2 + 2*a**3 - 7 - a**y + 6*a + 5*a**2. Is j(-5) prime? Reply: True Conundrum: Let n(m) = 21 - m - 42 - 6*m + 20. Let v be n(-4). Suppose -v*p = -30*p + 1131. Is p prime? Reply: False Conundrum: Let a(c) = 14*c. Let p be a(-1). Let z = 15 + -42. Let h = p - z. Is h a composite number? Reply: False Conundrum: Suppose 76*d + 368457 = 79*d - w, -4*d + w = -491276. Is d prime? Reply: True Conundrum: Let s(l) be the first derivative of 3248*l**2 + 27*l - 91. Is s(2) a prime number? Reply: False Conundrum: Let s be 3 + 26/6*12. Is s/(-11)*(-1137)/15 composite? Reply: False Conundrum: Let v = 10722 - 4473. Suppose v + 11081 = 10*s. Is s composite? Reply: False Conundrum: Let k = 2926 + -2049. Is k a prime number? Reply: True Conundrum: Let u(t) = 108*t + 1. Let i be 1 + (-3 + 30)/(-3). Let f = i - -15. Is u(f) a composite number? Reply: False Conundrum: Let x = -61 - -66. Suppose -x*c - 3*f = 17 - 59, -f = c - 8. Is -5 + 39/c + 8458/6 composite? Reply: False Conundrum: Let j(g) = -39*g - 7. Let u be j(-6). Suppose 4*x = u + 401. Is x a composite number? Reply: False Conundrum: Suppose -3*h + 245 = -2*h. Let c = -150 + h. Is c composite? Reply: True Conundrum: Let p(b) be the third derivative of -2/3*b**3 + 1/12*b**4 + 0 + 3*b**2 + 0*b. Is p(5) a prime number? Reply: False Conundrum: Let i = -2285 + 4039. Is i a prime number? Reply: False Conundrum: Suppose -13*i + 20 = -9*i. Suppose -z - i*j + 87 = -45, 4*z - 513 = -5*j. Is z prime? Reply: True Conundrum: Suppose -3*q = 5*r - 1161458, 1935785 = -678*q + 683*q + 4*r. Is q composite? Reply: False Conundrum: Let o(m) = 38*m + 5. Is o(13) composite? Reply: False Conundrum: Let s be (-518)/(-21)*(2 - -1). Suppose 0 = 5*n + 20, -3*p - n + s = -33. Is p a composite number? Reply: False Conundrum: Let l(z) = -4932*z - 481. Is l(-11) a composite number? Reply: True Conundrum: Suppose 88*z + 68 = 4*d + 92*z, d - 12 = -2*z. Suppose -128257 = -d*w + 467041. Is w a composite number? Reply: False Conundrum: Is (215090/30)/(((-32)/256)/(3/(-8))) composite? Reply: True Conundrum: Suppose a + 183 = 4*s, s - 26 = a + 19. Is s a composite number? Reply: True Conundrum: Suppose r - 92 = -13. Is r composite? Reply: False Conundrum: Let d be (-3 - -5)/2 - -2. Suppose -3*p = 3*f - 3735, -4*p + 0*p - 3763 = -d*f. Is f a composite number? Reply: False Conundrum: Suppose 0 = 5*m - 0*m - 10. Let z(d) = 347*d**2 - 4. Let k be z(m). Let f = k + -477. Is f a composite number? Reply: False Conundrum: Suppose 2*i - 4 = -x, -4*i + 1 = -5*x + 21. Suppose 2*t - t = 6. Let z = t + i. Is z prime? Reply: False Conundrum: Let w(y) = y**3 + 18*y**2 + 13*y - 3. Is w(-13) prime? Reply: True Conundrum: Let f(n) = 724*n + 2. Let u = 1 + 3. Let q be f(u). Is (1/(-3))/((-6)/q) composite? Reply: True Conundrum: Suppose 5*r + 4*s = 130, -r + 0*r = -5*s + 3. Let v = 15 + r. Is v a composite number? Reply: False Conundrum: Let x(g) be the second derivative of 3/2*g**2 - 2*g - g**3 + 0. Is x(-5) a prime number? Reply: False Conundrum: Suppose -3657 = -m + 7925. Is m a prime number? Reply: False Conundrum: Suppose 0 = 8*l - 89 + 9. Suppose 4*j - 43912 = -5*q, -13*q = -l*q - 12. Is j a prime number? Reply: True Conundrum: Let l = -10 - -76. Let v = 68 - l. Suppose -5*k - 2*d + 1778 + 3803 = 0, v*d = -k + 1121. Is k prime? Reply: False Conundrum: Suppose -47*q = q - 3854832. Is q a prime number? Reply: True Conundrum: Suppose -2*v + t = -0*v - 2, -5*v = -5*t. Suppose v*g - 2370 = -284. Is g composite? Reply: True Conundrum: Let y(t) = -t**2 - 13*t - 15. Let z be y(-10). Suppose -2*s = 4*g - 4 - 6, 2*g = 3*s - z. Suppose g = j - 2*j + 87. Is j a prime number? Reply: False Conundrum: Let y = 1 - 5. Let j = y + 9. Suppose -2*x + 19 = j*f - 22, -5*x - 3*f + 112 = 0. Is x a prime number? Reply: True Conundrum: Suppose -t = 4*t + 5. Let r(p) = -3*p**2 + 9*p**2 + 1 + 43*p**3 - 8*p**2 - 129*p**3. Is r(t) a composite number? Reply: True Conundrum: Suppose -2*b + 5 = -3. Suppose 0 = 3*h + b*o - 82, h + 5*o = 8 + 1. Is h prime? Reply: False Conundrum: Let n be 586/(-4) - (-2)/4. Let k = 698 - n. Is (2/8)/(1/k) a prime number? Reply: True Conundrum: Let t(i) = i**3 + 4*i**2 + 2*i + 1. Let w be t(-3). Suppose w*d + 742 = 2*m, 0*d = 5*m + d - 1822. Is m prime? Reply: False Conundrum: Let t = 11 - -1. Suppose -f + 41 = -t. Suppose 4*g - 31 - f = 0. Is g a prime number? Reply: False Conundrum: Suppose -5*a - 47 = z + 21, 0 = -2*a + 8. Let l = -2101 + 3244. Let s = l + z. Is s a composite number? Reply: True Conundrum: Let z be (-4 - -3) + 48 - 2. Suppose 62 = 2*x - 4*r, x + z = 2*x + 5*r. Is x a prime number? Reply: False Conundrum: Let q be (-6)/10 - (-108)/30. Suppose 0 = -h - 1, q*a - 2*h + 3*h - 866 = 0. Is a a composite number? Reply: True Conundrum: Let d(z) = -310*z - 7. Let n(t) = -t + 6. Let y be n(8). Let k be d(y). Suppose -2*c + 733 + k = 0. Is c composite? Reply: False<|endoftext|>numbers: list prime factors composed ------------------------------------ What if: Let t(w) = w**2 - 15*w + 3. Let a be t(15). Suppose -198 = -h + a*q, 3*h + 396 = 5*h - 2*q. List the prime factors of h. Gives: 2, 3, 11 What if: Let o = -427 + 584. List the prime factors of o. Gives: 157 What if: Suppose -798*n + 800*n - 5974 = 0. What are the prime factors of n? Gives: 29, 103 What if: Let z(s) = 51*s + 32. Let m be z(-8). What are the prime factors of (6/(-4))/(1 - (-380)/m)? Gives: 3, 47 What if: Suppose -557*r + 566*r = 0. Suppose -9*t + 791 + 955 = r. What are the prime factors of t? Gives: 2, 97 What if: Let d = 11 - -4. Suppose d = -3*w + y, -2*y = -w - 4*y - 12. What are the prime factors of w/(-4)*(-10)/(-3)? Gives: 5 What if: Let z = 2179 + -305. What are the prime factors of z? Gives: 2, 937 What if: Let p(j) = 117*j - 202. Let h be p(18). Suppose 15*v - h = -149. List the prime factors of v. Gives: 3, 13 What if: Let w = -5 - -11. List the prime factors of w. Gives: 2, 3 What if: Let f = 3902 - 2216. What are the prime factors of f? Gives: 2, 3, 281 What if: Let p(o) = -698*o - 372. List the prime factors of p(-3). Gives: 2, 3, 7, 41 What if: Suppose 24161 = 7*q - 3*a, -5*q + a = -9*q + 13790. What are the prime factors of q? Gives: 3449 What if: Let o(k) = -k - 25. Let y(z) = -z - 12. Let r(m) = -2*o(m) + 5*y(m). List the prime factors of r(-8). Gives: 2, 7 What if: Let n(s) = 21*s**2 + 4*s + 2. List the prime factors of n(-1). Gives: 19 What if: Suppose -2*c - 1 + 5 = 0, -74 = 4*f - c. List the prime factors of (-271)/(-7) - f/63. Gives: 3, 13 What if: Let z be 3/4 + 890/8. Suppose -4*h + 4 = -z. What are the prime factors of h? Gives: 29 What if: Let g be -1 - (-7 + (-9)/(-3)) - -3. Let l be ((-4)/g)/((-2)/(-3)). Let d(r) = -227*r**3 + r**2 + 3*r + 2. What are the prime factors of d(l)? Gives: 227 What if: Suppose 4*m - 9 - 11 = 0. Let r be 5/((-10)/(-16))*1. Suppose -m*j + r + 17 = 0. List the prime factors of j. Gives: 5 What if: Let d(r) = -2*r**3 - 7*r**2 - 4*r + 8. List the prime factors of d(-5). Gives: 103 What if: Suppose -z = 5*v - 26, 4 - 13 = -2*v + z. Let o(b) = 7*b - 1 - 4 - b. What are the prime factors of o(v)? Gives: 5 What if: Let c(a) = 68*a + 49. Let n(l) = -67*l - 50. Let d(k) = 6*c(k) + 7*n(k). List the prime factors of d(-10). Gives: 2, 277 What if: Let v be (-51)/(-12) - 4 - (-573)/(-4). Let n = 272 + v. List the prime factors of n. Gives: 3, 43 What if: Let b(k) = k**3 - 8*k**2 + 7*k + 10. Let v = -11 - -18. Let o be b(v). Suppose -5*y + 3*y + o = 0. What are the prime factors of y? Gives: 5 What if: Let w(j) = -17 + 93887*j - 93887*j - 16 + j**2. Let z be (-62)/(-8) + 3/12. List the prime factors of w(z). Gives: 31 What if: Let g = 53 - 48. Suppose 4*t + 72 + 37 = 3*k, g*t = 2*k - 61. List the prime factors of k. Gives: 43 What if: Let b(s) = 2*s**3 - 185*s**2 + 134*s + 395. What are the prime factors of b(93)? Gives: 2, 10753 What if: Suppose -42*q + 100239 - 18591 = 0. List the prime factors of q. Gives: 2, 3 What if: Let i(b) = 4*b**2 + 34*b - 8. Let f be i(-9). Let r(d) = 9*d**2 - 12*d - 15. What are the prime factors of r(f)? Gives: 3, 5, 17 What if: Let v(s) = -s**2 + 11*s + 10. Let i be v(11). Let m be (-4)/(-6)*(-99)/(-22) - i. Let a(b) = b**2 - 5*b + 6. List the prime factors of a(m). Gives: 2, 3, 5 What if: Let m(x) be the third derivative of x**4/24 + 5*x**3/3 + 2*x**2. What are the prime factors of m(-6)? Gives: 2 What if: Suppose 0 = 2*a + q - 16, 4*a - 3*q - 16 = -q. List the prime factors of ((-4)/a)/(4/(-18)). Gives: 3 What if: Let w(l) = l - 5. Let x be w(5). Let z be ((-12)/(-22))/((-12)/(-88)). Suppose x = -8*j + 4*j + z*f + 60, 15 = j + 3*f. What are the prime factors of j? Gives: 3, 5 What if: Suppose 4*f + 3*j = -4, 3 + 19 = f - 5*j. Suppose -2*r + 3*r + 4*d = 352, -3*d = -f*r + 671. What are the prime factors of r? Gives: 2, 5, 17 What if: Suppose 4*k + 4*n = 32, 2*k - 3*k - 3*n + 14 = 0. Suppose 12 + 13 = k*b. What are the prime factors of b? Gives: 5 What if: Let o(m) = 414*m + 1133. What are the prime factors of o(4)? Gives: 2789 What if: Let t(q) = -47*q**3 - 2*q + 0 - 1 - q**3. Let f = -94 - -93. List the prime factors of t(f). Gives: 7 What if: Let z(l) = l + 11. Let v be z(0). Let r(d) = d**2 - 14*d - 5. Let t be r(14). Let n = v + t. List the prime factors of n. Gives: 2, 3 What if: Let c(d) = -78*d - 31. Let g be c(4). Let y = -161 - g. List the prime factors of y. Gives: 2, 7, 13 What if: What are the prime factors of ((-1065)/(-25))/(4/20)? Gives: 3, 71 What if: Let k be 7/5 + (-15)/(-25). List the prime factors of (-52)/(-12)*6/k. Gives: 13 What if: Let v be (2 + -118)*1*-1. Suppose 0 = -3*x - g + 77, -2*x = 2*x - 2*g - v. Suppose -m - x = -2*t - 6*m, -4*t = -2*m - 42. What are the prime factors of t? Gives: 11 What if: Let n be 18/5 + (-24)/40. Suppose 0 = -n*l + 2*m - m + 263, -5*l + 410 = 4*m. List the prime factors of l. Gives: 2, 43 What if: Suppose -3*o + 77 + 40 = 0. List the prime factors of o. Gives: 3, 13 What if: Let p be 2/(-1) + (6 - 1). Suppose 4*t - 2*a = -p*a + 201, 4*t = a + 207. List the prime factors of t. Gives: 3, 17 What if: Suppose -a + 5*a = -888. Let k = -1190 - -1063. Let b = k - a. What are the prime factors of b? Gives: 5, 19 What if: Let o(d) = d**3 + d. Let l(i) = -3*i**3 - 8*i**2 - 2*i - 3. Let u(g) = -l(g) - 2*o(g). List the prime factors of u(-8). Gives: 3 What if: Suppose -141 = f - 4*f. What are the prime factors of f? Gives: 47 What if: List the prime factors of (-96)/(-10)*10*(4 - 3). Gives: 2, 3 What if: What are the prime factors of -2*(-2)/(8/62)? Gives: 31 What if: Let s(d) = d**3 + 6*d**2 + 3*d - 8. Let i be s(-5). Let o be 4 - ((-18)/4)/(i/(-4)). What are the prime factors of (162/o)/(14/(-70))? Gives: 2, 3 What if: Let t = 9 - -100. Suppose -t + 197 = 2*j. List the prime factors of j. Gives: 2, 11 What if: Suppose -3*i + 14570 = 4*n, -3*i = 48*n - 53*n + 18253. What are the prime factors of n? Gives: 7, 521 What if: Let q(s) = s**3 - 8*s**2 + 15*s - 10. Let p be q(6). Suppose p*a - 296 = 4*a. List the prime factors of a. Gives: 2, 37 What if: Let f = -9621 - -13553. List the prime factors of f. Gives: 2, 983 What if: Let p(g) = g**2 - 7*g + 3. Let d be p(7). Suppose 0 = 2*z + d*z - 20. List the prime factors of z. Gives: 2 What if: Suppose 0 = 65*t - 95858 - 497787. List the prime factors of t. Gives: 9133 What if: Let a(v) = -20*v**3 + v**2 + v. Suppose -3 = 3*x - 0. List the prime factors of a(x). Gives: 2, 5 What if: Let z = -42 + 32. What are the prime factors of (-13)/4*(2 + z)? Gives: 2, 13 What if: List the prime factors of 711 + -16*(-4)/8. Gives: 719 What if: Let q be ((-72)/(-10))/3*-5. Let z be (-15)/(-2)*(q/(-15) - 0). What are the prime factors of ((z + -12)*11)/((-1)/1)? Gives: 2, 3, 11 What if: Let x be (1*(-24)/20)/((-21)/35). Suppose -4*n = x*i - 1592, -4*i - 86*n + 84*n + 3196 = 0. What are the prime factors of i? Gives: 2, 5 What if: Let j(x) = 84*x**3 + 19*x**2 - 91*x - 7. What are the prime factors of j(4)? Gives: 5309 What if: List the prime factors of 2*24*(-5)/(-6 + 1). Gives: 2, 3 What if: Let l(v) = 2*v + 24. Let d be l(-11). Let n be (795/(-30))/((-1)/d). Suppose 5*u - 3*q - 214 = 0, u - n = -3*q + 7*q. What are the prime factors of u? Gives: 41 What if: Let c be 75/10*8/10. Let l be (-7 - (-2 + -2)) + c. What are the prime factors of (1/l)/(26/780)? Gives: 2, 5 What if: Suppose 0 = 12*c - 2*i - 7030, 16*c - 4*i = 12*c + 2340. What are the prime factors of c? Gives: 2, 293 What if: Suppose -2*t - 10 = 2*b, -t - 17 = -4*b + 3. Let z = t - -8. Suppose 4*o - 48 = -z*o. List the prime factors of o. Gives: 2, 3 What if: Suppose -3*x = 15, 3*b - 5*x + 7*x - 386 = 0. List the prime factors of b. Gives: 2, 3, 11 What if: Let s be (0/1 - 1)*-78. Suppose 5*u - 285 = 12*j - 17*j, -4*j = -3*u - 200. Let k = s - j. List the prime factors of k. Gives: 5 What if: Let b be -3*(-78)/9*1. Let k be b/5 - 3/15. Suppose -4*i + 71 = k*d, -2*d = 2*d - i - 40. List the prime factors of d. Gives: 11 What if: Suppose 4 = -5*s + 14. Suppose 0 = -p - s*p + 126. What are the prime factors of p? Gives: 2, 3, 7 What if: Let m be 18/27 - (-14)/(-3). Let d be 6/m*(-10)/3. Suppose -d*x - 2*s = -54 + 5, 0 = 2*x - 4*s - 10. What are the prime factors of x? Gives: 3 What if: Let h be (-116)/14 + (-4)/(-14). Let n(w) = w**3 + 7*w**2 - 10*w - 5. Let x be n(h). Let b = 16 - x. What are the prime factors of b? Gives: 5 What if: Let c be (-24)/((-25)/20 + 2). What are the prime factors of c/((12/(-16))/3)? Gives: 2 What if: List the prime factors of ((-1472880)/(-18))/17 - 1/3. Gives: 4813 What if: List the prime factors of 415/3*(-14 + 13 + 4). Gives: 5, 83 What if: Let y be -3 - (58/(-10) + (-108)/(-135)). Suppose -4*x - y*s = -1312, 4*x - 4*s - 723 = 589. List the prime factors of x. Gives: 2, 41 What if: Let p(r) = -r - 1. Let n(j) = j**2 - j - 10. Let o(m) = 2*m**2 - 2*m - 20. Let g(s) = 5*n(s) - 2*o(s). Let k be g(0). List the prime factors of p(k). Gives: 3 What if: Let l = -56 - 97. Suppose 16*p = -677 - 3099. Let r = l - p. What are the prime factors of r? Gives: 83 What if: Let y be 1/2 - (-20)/8. Let x be -1 + 0 + 1 + y. Suppose -5*j - v = -57, j = -v - x + 12. What are the prime factors of j? Gives: 2, 3 What if: Let f(j) = -841*j**2 + 2*j + 1. Let m be f(-1). Let y = -106 - m. Suppose 57*s = 53*s + y. What are the prime factors of s? Gives: 2, 23 What if: List the prime factors of (-2624)/(-820)*(-5)/(-2) + 55865 + 1. Gives: 2, 7, 13, 307 What if: Let g = 16834 + -10534. What are the prime factors of g? Gives: 2, 3, 5, 7 What if: Let j(a) = 51*a**3 - a**2 - 2*a - 1. Let r be j(2). Let o = 600 - r. List the prime factors of o. Gives: 3, 67 What if: Suppose -3*c - h + 4*h + 504 = 0, -3*h - 160 = -c. List the prime factors of c. Gives: 2, 43 What if: Let g(z) = -793*z - 134. What are the prime factors of g(-6)? Gives: 2, 17 What if: Suppose 3*t - t + 4 = -2*r, r = -3*t - 12. Suppose -5*h - 15 + 57 = -4*v, 0 = -4*h + r*v + 33. What are the prime factors of h? Gives: 2, 3 What if: Let s be -4 + (-3 - -7) - -56. Suppose 123 = 5*z + k - s, -4*k = 4*z - 156. List the prime factors of z. Gives: 5, 7 What if: Let t be 4/(2/33*-3). Let o = t + 56. Suppose 0 = 5*l - 4*l - o. List the prime factors of l. Gives: 2, 17 What if: Let c(j) = 21*j - 15. Let t(i) = -7*i + 5. Let l(v) = -4*c(v) - 11*t(v). What are the prime factors of l(-5)? Gives: 2, 5 What if: Suppose -4*u + 220*n + 137100 = 217*n, -5*u + 3*n + 171378 = 0. List the prime factors of u. Gives: 2, 3, 29, 197 What if: Suppose -c = 4*c. Suppose h - 4*t + 25 = c, -15 = 3*h - 3*t + 15. What are the prime factors of 3/h - 759/(-15)? Gives: 2, 5 What if: Let h = -13 - -8. Let a be 60/2 - (-9 - h). Let k = 47 - a. List the prime factors of k. Gives: 13 What if: Let q = -166 + 357. What are the prime factors of q? Gives: 191 What if: Let x = 1 - -7. Let c = 5 - x. List the prime factors of 7*c*(-1)/3. Gives: 7 What if: Let k(o) = 4*o - 8. Let y be k(3). Suppose f - l - 1 - 1 = 0, -2*f = -y*l - 10. What are the prime factors of (-47)/((-2 - -1) + -1 - f)? Gives: 47 What if: Suppose -n = -7*n. Suppose n = 5*m - 2*m - 246. List the prime factors of (m/(-6))/((-1)/3). Gives: 41 What if: Let w(h) = 5*h**2 + 9*h + 39. List the prime factors of w(-5). Gives: 7, 17 What if: Suppose 0 = 5*d - 64 - 106. What are the prime factors of (-7905)/(-21) - (-2 - d/(-14))? Gives: 2, 47 What if: Suppose 2*k - k - 75 = 0. List the prime factors of k. Gives: 3, 5 What if: Let m(a) be the second derivative of -29/2*a**2 - 1/20*a**5 + 13 + a - 4/3*a**3 + 0*a**4. What are the prime factors of m(-4)? Gives: 67 What if: Let r = -34 - -31. Let y be -2*(-1)/(-6)*r + 4. Suppose 0 = -y*d + 3*j + 560, -2*d + 2*j + 224 = -3*j. What are the prime factors of d? Gives: 2, 7 What if: Let q = -7 + 66. Suppose -2 = 2*p, -3*t + 0*p - p + q = 0. Suppose -6*m + 2*m = -t. What are the prime factors of m? Gives: 5 What if: Let q = 399 + 38. What are the prime factors of q? Gives: 19, 23 What if: Let o = -122343 - -181322. List the prime factors of o. Gives: 58979 What if: Suppose o = -3*h + 18, -3*o + 78 = -10*h + 7*h. Let a = o - 73. Let p = 171 + a. What are the prime factors of p? Gives: 2, 61 What if: Let q(n) = -9*n - 1. Let g be q(1). Let d be g/(-2) + (2 - 3). Suppose 4*i + 24 + 0 = 4*w, 3*i = d*w - 28. List the prime factors of w. Gives: 2, 5 What if: List the prime factors of (551 - -2)*(0 - -1). Gives: 7, 79 What if: Let a(q) be the second derivative of q**4/12 - q**3/3 - q**2/2 - 6*q. Let b be a(3). Suppose 3 = f - h + 2*h, -f = b*h - 3. List the prime factors of f. Gives: 3 What if: Let o(b) = 13*b**3 + 2*b**2 - 33*b + 40. What are the prime factors of o(6)? Gives: 2, 1361 What if: Let s(i) = -i**3 + 4*i**2 + 5*i - 2. Let n(x) = x**2 + x - 2. Suppose 0*t + h = -5*t - 17, 4*t = -5*h - 22. Let b be n(t). What are the prime factors of s(b)? Gives: 2, 3 What if: Let m(l) be the third derivative of 7*l**6/60 - l**4/6 - l**3/6 - l**2. List the prime factors of m(2). Gives: 103 What if: Let q(m) = 2*m**2 - 3*m - 3. Let c be q(3). Let p be (-12)/24*-1*c. Suppose p*g = -g + 204. List the prime factors of g. Gives: 3, 17 What if: Suppose 0 = -3*j + 349 - 67. List the prime factors of j. Gives: 2, 47 What if: Let x = 2326 - 704. Suppose 0 = 2*o + 4, 4*i - x + 384 = o. List the prime factors of i. Gives: 3, 103 What if: Let p(j) = j - 11. Let m be p(10). Let i = 0 + m. List the prime factors of i*(2 + 2)*-6. Gives: 2, 3 What if: Let p = 129 - -1147. What are the prime factors of p? Gives: 2, 11, 29 What if: Suppose 5*x + 5 = 0, 2*x = 4*r - 2 - 8. Suppose -r*y = -3*m - y + 6, 5*y + 10 = 5*m. List the prime factors of m. Gives: 2 What if: Let q(r) = 17*r**2 - 4*r + 1. List the prime factors of q(1). Gives: 2, 7 What if: List the prime factors of (-14)/(-1) - (-2 + 0)/2. Gives: 3, 5 What if: Let b = 7 + 7. Suppose 5*y + 1 = -m + 2, 5*m = -3*y + 5. Let r = b - m. What are the prime factors of r? Gives: 13 What if: Suppose -5*d - 3*n - 299 = 0, 0 = 2*d - n - 4*n + 132. What are the prime factors of (39101/d)/(1/(-3))? Gives: 3, 641 What if: Let l = 606 - 322. Suppose 148 = -3*g - l. Let n = 206 + g. List the prime factors of n. Gives: 2, 31 What if: Let o(l) = -107*l - 5485. What are the prime factors of o(-110)? Gives: 3, 5, 419 What if: Let m be 3/(-9) + (-5)/3. Suppose -30 = 3*x + h - 9, -2*h = -x. Let z = m - x. What are the prime factors of z? Gives: 2 What if: Let j(q) = -960*q - 830. List the prime factors of j(-6). Gives: 2, 5, 17, 29 What if: Let y = -28 + 51. Suppose 0 = s - 2*f - 10, 2*f = 2*s - f - y. What are the prime factors of s? Gives: 2 What if: Suppose -16516 - 2742 = -3*b + 23846. List the prime factors of b. Gives: 2, 449 What if: Let u = -244 + 134. Let r = u - -204. Let q = 161 - r. What are the prime factors of q? Gives: 67 What if: Let n = -36 - -54. Let j = 16 - n. List the prime factors of (-4)/j*2/((-20)/(-505)). Gives: 101 What if: Suppose 2*o = 5*o - 4*l - 103, -3*o - 5*l = -94. Let a = -8 + o. Suppose 4*i + 5*k + 4 - 44 = 0, -5*k = i - a. List the prime factors of i. Gives: 5 What if: Let b = 137 + -94. Let z = -37 + b. What are the prime factors of z? Gives: 2, 3 What if: Let r(o) = -o**3 - 30*o**2 + 36*o - 56. What are the prime factors of r(-32)? Gives: 2, 3, 5, 7 What if: Let j(h) = -6*h + 1. Let z(w) = w**2 - 5*w - 1. Suppose -5*x + 25 + 0 = 0. Let i be z(x). List the prime factors of j(i). Gives: 7 What if: Suppose 14*v + 3*o = 19*v - 9645, -v + 1929 = -o. List the prime factors of v. Gives: 3, 643 What if: Let z be (-20)/8*4/(-10). Suppose w + z = -3*j, -3*j + 13 = -0*w + 2*w. Suppose -w + 128 = 3*o. What are the prime factors of o? Gives: 2, 19 What if: Suppose -2*x = 4*s, -2 = 3*s + 4*x + 8. Suppose -s*f = f - 27. Let y = f - 1. List the prime factors of y. Gives: 2 What if: Suppose 3*g = -2*b - 232, 0*b + 236 = -2*b - 2*g. Let m(c) = -137*c - 1. Let a be m(-1). Let u = a + b. List the prime factors of u. Gives: 2, 7 What if: Let d(k) = -k + 39. What are the prime factors of d(14)? Gives: 5 What if: Let q(w) = 1245*w - 710. What are the prime factors of q(3)? Gives: 5, 11 What if: Let h(i) = -i**2 + 20. Let s = -2 + 2. Let n be h(s). Suppose 0*u = -5*u + n. What are the prime factors of u? Gives: 2 What if: Let a(m) = -m**3 + 13*m**2 - 34*m + 29. What are the prime factors of a(-11)? Gives: 3307 What if: Let r(d) = -166*d - 35. What are the prime factors of r(-3)? Gives: 463 What if: Let b be ((-4)/3)/((-4)/42). Let w = -11 + b. List the prime factors of w. Gives: 3 What if: Let l be (3 - 1)/((-6)/291). List the prime factors of l/(-4) + 9/(-36). Gives: 2, 3 What if: List the prime factors of ((-9)/((-99)/(-44)))/(2/(-1988)). Gives: 2, 7, 71 What if: Let z(q) = -3*q**3 - 7*q**2 - 6*q - 8. Let b be z(-7). Suppose -2*x = 5*f - 2915 + b, 4*x - 3*f = 4325. Suppose -8*o + o + x = 0. List the prime factors of o. Gives: 5, 31 What if: Let d = 663 + 1165. What are the prime factors of d? Gives: 2, 457 What if: Let s = -50 - -41. Let p = -32 + 12. Let y = s - p. What are the prime factors of y? Gives: 11 What if: Suppose -11428956 = -319*q - 115*q. List the prime factors of q. Gives: 2, 3, 7, 11, 19 What if: Let b = 3 + -2. Let n = -5 - -9. List the prime factors of b*-1*(-20)/n. Gives: 5 What if: Let l(v) = 6*v - 9 - 11*v + 14*v**2 + 8*v. List the prime factors of l(3). Gives: 2, 3, 7 What if: Suppose 0*j - j = 2. Let i be (25/j)/((-1 - -4)/(-30)). Suppose 2*p - 13 - i = 0. What are the prime factors of p? Gives: 3, 23 What if: Let d(n) = n + n**3 - 4 + 6 - 9*n**2 - 6. Let y be d(9). Suppose -5*k - 5*p = -285, 0*p = y*k + 2*p - 291. What are the prime factors of k? Gives: 59 What if: Let i(o) = 16 - 28*o**3 + 13*o**3 - 3*o**2 + 16*o**3. Let z be i(7). Let h = 325 - z. List the prime factors of h. Gives: 113 What if: Let m be -7*(24/(-21) + 2). What are the prime factors of 4/(-12) - 62/m? Gives: 2, 5 What if: Let v be ((-8)/12)/((-2)/3). Let o(x) = x**2 - 2*x + 1. Let d be o(v). Suppose d = 3*k - 14 + 2, 2*r + 5*k - 24 = 0. List the prime factors of r. Gives: 2 What if: Let v(b) = -b**3 - 5*b**2 + 5*b + 8. What are the prime factors of v(-6)? Gives: 2, 7 What if: Let i = 866 - 803. What are the prime factors of i? Gives: 3, 7 What if: Let c(p) = p**2 - 8*p - 18. Let o be c(10). Suppose 0 = -3*w + 3*f + 1626, 2717 = -149*w + 154*w + o*f. List the prime factors of w. Gives: 3, 181 What if: Suppose 1 = 3*m - 11. Suppose -d + 3*d - 524 = m*h, -4*h - 1040 = -4*d. List the prime factors of d. Gives: 2, 3, 43 What if: Let s be 2*4/(16/(-62)). Let h = s + 54. Suppose -22*a - 46 = -h*a. What are the prime factors of a? Gives: 2, 23 What if: Suppose 2*o = -3*l + 827, 0 = 3*l - 0*o - 2*o - 823. What are the prime factors of l? Gives: 5, 11 What if: Let n(f) = 64*f**2 - 6*f + 146. List the prime factors of n(17). Gives: 2, 3, 5, 103 What if: Suppose 6*a = 7*a - 13. Let w = a + -7. What are the prime factors of w? Gives: 2, 3 What if: Let q(n) = -n**2 - 6*n + 8. Let m be q(-6). Suppose 2*f = 4*c - 28, 3*f - 2*f + 29 = 5*c. Let j = m + f. List the prime factors of j. Gives: 2 What if: Let l(m) = 2*m**2 - 10*m - 18. Let y be l(14). Suppose 990 - y = 7*z. What are the prime factors of z? Gives: 2, 3 What if: Let g be ((-78)/(-2 - 0))/1. Let u(v) = -v**3 + 13*v**2 - 5*v - 26. Let b be u(8). Suppose 5*q + g = b. What are the prime factors of q? Gives: 43 What if: Let p(n) = -117*n + 1059. Let i be p(9). Let y = -2 - -5. Suppose u - i = -y. List the prime factors of u. Gives: 3 What if: Suppose 2*n = -3*t + 1994, 2*n = 3*n + 5. List the prime factors of (31/62)/(2/t). Gives: 167 What if: Suppose 3*c + c = -8. Let w(i) = -10*i**3 + i**2 + 5*i + 3. List the prime factors of w(c). Gives: 7, 11 What if: List the prime factors of (-4 + (-30950)/15)/(304/51 + -6). Gives: 7, 17, 443 What if: Let m(q) = -q**3 + 12*q**2 - 2*q + 26. Let h be m(12). Suppose h*p - 8 = -0. Suppose 0 = i + p*z - 100, -2*i + z = -0*i - 155. What are the prime factors of i? Gives: 2, 5 What if: Let a = 1555 - -802. What are the prime factors of a? Gives: 2357 What if: Let f = -241 - -785. List the prime factors of f. Gives: 2, 17 What if: Suppose -2*b + 0*b = -2*v + 8, 0 = 5*v - 20. Let r be 9/(2/(b - 2)). Let m = r - -18. List the prime factors of m. Gives: 3 What if: Let d be (-162)/10 + (-2)/(-10). Let p be (12/d)/(1/(-8)). Suppose -4*m + p = -2*m. What are the prime factors of m? Gives: 3 What if: Let q(y) = y**2 + 5*y + 4. Let j be q(7). Suppose j = -7*i + 11*i. List the prime factors of i. Gives: 2, 11 What if: Let m(f) = 6*f - 32. Let g be m(6). Suppose 5*j = 4*r - 377, -284 = -3*r - 0*j + g*j. What are the prime factors of r? Gives: 2, 11
[{"idx": "txt360/numbers__is_prime_composed_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-14.jsonl"}, {"idx": "txt360/numbers__list_prime_factors_composed_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-14.jsonl"}]
import {async, ComponentFixture, TestBed} from "@angular/core/testing"; import {By} from "@angular/platform-browser"; import {DebugElement} from "@angular/core"; import {RouterOutletMap} from "@angular/router"; import {HttpModule} from "@angular/ http"; import {FormsModule} from "@angular/forms"; import {CommonModule} from "@angular/common"; import {RouterTestingModule} from "@angular/router/testing"; import {AppSingletonService} from "../app.singletonservice"; import {CreateTaskComponent} from "./createtask.component"; import {Observable} from "rxjs/Observable"; import "rxjs/add/observable/of"; describe('CreateTaskComponent', function () { let de: DebugElement; let comp: CreateTaskComponent; let fixture: ComponentFixture<CreateTaskComponent>; let service: AppSingletonService; class MockRouter { } class MockActivateRouter { } beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [CreateTaskComponent], providers: [RouterOutletMap, AppSingletonService], imports: [RouterTestingModule, HttpModule, FormsModule, CommonModule] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(CreateTaskComponent); comp = fixture.componentInstance; de = fixture.debugElement.query(By.css('h1')); service = fixture.debugElement.injector.get(AppSingletonService); }); it('should create component', () => { spyOn(service, 'addTask').and.returnValue(Observable.of<any>( [{ date: '', title: '', description: '', priority: '' }] ) ); comp.create("", "", "", ""); expect(comp.myTasks).toEqual([{ date: '', title: '', description: '', priority: '' }]) }); });<|endoftext|>import { Component, OnInit } from '@angular/core'; import { NavController, AlertController } from '@ionic/angular'; import { UrlService } from '../url.service'; import { HttpClient } from '@angular/common/ http'; @Component({ selector: 'app-cart', templateUrl: './cart.component.html', styleUrls: ['./cart.component.scss'], }) export class CartComponent implements OnInit { constructor(private nav:NavController,private url:UrlService,private http:HttpClient,private alert:AlertController) { } private products=[]; private total=0; goback(){ this.nav.back() } doLess(i){ let count=this.products[i].count if(count>1){ count-=1; this.products[i].count=count; this.getTotal() }else{ this.doDel(this.products[i].id,i); this.getTotal() } } doAdd(i){ let count=this.products[i].count count+=1; this.products[i].count=count; this.getTotal() } doDel(id,i){ const alert=this.alert.create({ header:'提醒', message:'是否确定删除该商品?', buttons:[ { text:'我再想想', handler:()=>{} }, { text:'确认', handler:()=>{ this. http.get(this.url.delApi+id).subscribe((res:any)=>{ this.products.splice(i,1) }) } } ] }).then(alert=>alert.present()) } doBuy(){ console.log("支付功能尚未上线!") } getTotal(){ this.total=(()=>{ return this.products.reduce((prev,elem)=> prev+elem.count*elem.price ,0) })() } ngOnInit() { this. http.get(this.url.cartApi,{withCredentials:true}).subscribe((res:any)=>{ console.log(res.data) this.products=res.data; this.getTotal() }) } }<|endoftext|>import { ModuleWithProviders, NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { NbPasswordAuthStrategy, NbAuthModule } from '@nebular/auth'; import { HTTP_INTERCEPTORS } from '@angular/common/ http'; import { LoginInterceptor } from '../../user.interceptors'; import { RouterModule } from '@angular/router'; import { UserProfileComponent } from './pages/profile.component'; import { ThemeModule } from '../../@theme/theme.module'; import { NbCardModule, NbCheckboxComponent, NbCheckboxModule, NbInputModule, NbMenuModule } from '@nebular/theme'; import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ UserProfileComponent, ], imports: [ CommonModule, ThemeModule, NbMenuModule, NbCardModule, NbCheckboxModule, NbInputModule, FormsModule, RouterModule.forChild([ { path: 'profile', component: UserProfileComponent } ]), ], exports: [ UserProfileComponent, RouterModule, ], }) export class UserModule { static forRoot(): ModuleWithProviders<UserModule>[] { return [{ ngModule: UserModule, providers: [ { provide: HTTP_INTERCEPTORS, useClass: LoginInterceptor, multi: true } ], }, NbAuthModule.forRoot({ strategies: [ NbPasswordAuthStrategy.setup({ name: 'email', baseEndpoint: ' [IDX] login: { endpoint: '/login', requireValidToken: false, }, register: { endpoint: '/register', requireValidToken: false, }, logout: { method: 'get', endpoint: '/logout', requireValidToken: false, } }), ], forms: {}, }), ]; } }<|endoftext|>import request from "supertest"; import app from "../src/app"; import { generateJWT } from "../src/util/jwt"; describe("GET /api/user", () => { it("should return 406", (done) => { request(app).get("/api/user").expect(406, done); }); it("should return 403", (done) => { request(app) .get("/api/user") .set("Authorization", "Bearer sd") .expect(403, done); }); it("should return 200", (done) => { const tempToken = generateJWT({ _id: "<PASSWORD>", email: "<EMAIL>", }); request(app) .get("/api/user") .set("Authorization", `Bearer ${tempToken}`) .expect(200, done); }); }); describe("POST DELETE /api/user and login user GET /api/user/login", () => { const email = `${(Math.random() + 1) .toString(36) .substring(7)}@gmail.com`; const password = "<PASSWORD>"; let token = ""; it("should return 400", (done) => { request(app).post("/api/user").expect(400, done); }); it("should return 201", (done) => { request(app) .post("/api/user") .send({ email, password, }) .expect(201, done); }); it("should return 409", (done) => { request(app) .post("/api/user") .send({ email, password, }) .expect(409, done); }); it("should return 200 for user login", (done) => { request(app) .post("/api/user/login") .send({ email, password, }) .expect((res) => { expect(res.body.token).toBeDefined(); token = res.body.token; }) .expect(200, done); }); it("should delete user and return 204", (done) => { request(app) .delete("/api/user") .set("Authorization", `Bearer ${token}`) .expect(204, done); }); });<|endoftext|>import "phaser"; import { CountersRepo } from "./countersRepo"; import { Price } from "./price"; export class BuildingData { title: string; buildingKey: string; price: Price; scale: number; builder: CallableFunction; // scene objects img: Phaser.GameObjects.Sprite; text: Phaser.GameObjects.Text; box: Phaser.GameObjects.Rectangle; priceContainer: Phaser.GameObjects.Container; public static create(): BuildingData { let option = new BuildingData(); option.price = new Price(); return option; } public withTitle(title: string): BuildingData { this.title = title; return this; } public withBuildingKey(buildingKey: string): BuildingData { this.buildingKey = buildingKey; return this; } public withScale(scale: number): BuildingData { this.scale = scale; return this; } public withBuilder(builder: CallableFunction) { this.builder = builder; return this; } public withPrice(price: any) { this.price.gold = price.gold; this.price.wood = price.wood; this.price.stone = price.stone; this.price.bronze = price.bronze; return this; } public getObjects() { return [this.box, this.img, this.text]; } public getRequiredResources(): { [s: string]: number; } { let resources: { [s: string]: number; } = {} if (this.price.wood) resources['resource_wood'] = this.price.wood; if (this.price.stone) resources['resource_stone'] = this.price.stone; if (this.price.bronze) resources['resource_bronze'] = this.price.bronze;; if (this.price.gold) resources['resource_coin'] = this.price.gold; return resources; } }<|endoftext|>import * as React from 'react'; import EntityHeader from 'src/components/EntityHeader'; import StackScriptActionMenu from './StackScriptPanel/StackScriptActionMenu_CMR'; import { StackScriptCategory } from './stackScriptUtils'; interface Props { stackScriptID: number; stackScriptUsername: string; stackScriptLabel: string; canModify: boolean; canAddLinodes: boolean; isPublic: boolean; // @todo: when we implement StackScripts pagination, we should remove "| string" in the type below. // Leaving this in as an escape hatch now, since there's a bunch of code in // /LandingPanel that uses different values for categories that we shouldn't // change until we're actually using it. category: StackScriptCategory | string; triggerDelete: (id: number, label: string) => void; triggerMakePublic: (id: number, label: string) => void; } type CombinedProps = Props; const StackScriptDetailsHeader: React.FC<CombinedProps> = props => { const { stackScriptID, stackScriptUsername, stackScriptLabel, canModify, isPublic, category, canAddLinodes, triggerDelete, triggerMakePublic } = props; return ( <EntityHeader title={stackScriptLabel} parentLink="/stackscripts" parentText="StackScripts" isSecondary actions={ <StackScriptActionMenu stackScriptID={stackScriptID} stackScriptUsername={stackScriptUsername} stackScriptLabel={stackScriptLabel} triggerDelete={triggerDelete} triggerMakePublic={triggerMakePublic} canModify={canModify} canAddLinodes={canAddLinodes} isPublic={isPublic} category={category} isHeader={true} /> } /> ); }; export default StackScriptDetailsHeader;
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5996.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5996.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5996.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5996.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5996.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5996.jsonl"}]
import { NgModule } from '@angular/core' import { CommonModule } from '@angular/common' import { MatGridListModule } from '@angular/material/grid-list' import { MatExpansionModule } from '@angular/material/expansion' import { MatDividerModule } from '@angular/material/divider' import { MatIconModule, MatListModule, MatFormFieldModule, MatDialogModule, MatSelectModule, MatInputModule, MatButtonModule, MatSidenavModule, MatChipsModule, MatProgressSpinnerModule, MatTabsModule, } from '@angular/material' import { MatCardModule } from '@angular/material/card' import { EventsRoutingModule } from './events-routing.module' import { EventsHomeComponent } from './routes/events-home/events-home.component' import { EventsComponent } from './routes/events/events.component' import { LoaderService } from '@ws/author/src/public-api' import { InitResolver } from '@ws/author/src/lib/services/init-resolve.service' import { ReactiveFormsModule, FormsModule } from '@angular/forms' import { BtnPageBackModule } from '@sunbird-cb/collection/src/public-api' import { PipeOrderByModule } from '@sunbird-cb/utils/src/lib/pipes/pipe-order-by/pipe-order-by.module' import { AvatarPhotoModule } from '@sunbird-cb/collection/src/lib/_common/avatar-photo/avatar-photo.module' import { PipeHtmlTagRemovalModule, PipeFilterV2Module } from '@sunbird-cb/utils' import { PipeRelativeTimeModule } from '@sunbird-cb/utils/src/lib/pipes/pipe-relative-time/pipe-relative-time.module' import { PipeFilterSearchModule } from '@sunbird-cb/utils/src/lib/pipes/pipe-filter-search/pipe-filter-search.module' import { PipeFilterModule } from '@sunbird-cb/utils/src/lib/pipes/pipe-filter/pipe-filter.module' import { EventsCardComponent } from './components/events-card/events-card.component' import { TodayEventCardComponent } from './components/today-event-card/today-event-card.component' import { EventDetailComponent } from './routes/event-detail/event-detail.component' import { RelatedPostsComponent } from './components/related-posts/related-posts.component' import { WidgetResolverModule } from '@sunbird-cb/resolver' import { RightMenuCardComponent } from './components/right-menu-card/right-menu-card.component' import { PresenterCardComponent } from './components/presenter-card/presenter-card.component' import { EventService } from './services/events.service' @NgModule({ declarations: [ EventsComponent, EventsHomeComponent, EventsCardComponent, TodayEventCardComponent, EventDetailComponent, RelatedPostsComponent, RightMenuCardComponent, PresenterCardComponent, ], imports: [ CommonModule, ReactiveFormsModule, FormsModule, EventsRoutingModule, MatGridListModule, MatExpansionModule, MatFormFieldModule, MatDividerModule, MatIconModule, MatCardModule, MatChipsModule, MatListModule, MatSelectModule, MatInputModule, MatDialogModule, MatButtonModule, MatSidenavModule, MatProgressSpinnerModule, PipeFilterModule, PipeHtmlTagRemovalModule, PipeRelativeTimeModule, AvatarPhotoModule, PipeOrderByModule, PipeFilterV2Module, PipeFilterSearchModule, BtnPageBackModule, WidgetResolverModule, MatTabsModule, ], providers: [ LoaderService, InitResolver, EventService, ], }) export class EventsModule { }<|endoftext|>// Shared libs import * as YAML from 'js-yaml'; import * as Validator from 'jsonschema'; import * as FS from 'fs'; // Local libs import { Connection, Sqlite3Connection, ResultSet } from './connection'; import { DataSource } from './dataSource'; import { Page } from './page'; import { PageEntity } from './pageEntity'; export interface IId { id : string; } export class Project implements IId { title : string; id : string; connections : Connection[]; dataSources : DataSource[]; pages : Page[]; public async runQuery(dataSourceId : string, params : any, maxRecords : number = -1, offset : number = 0) : Promise<ResultSet> { const dataSource : DataSource = this.dataSourceMap[dataSourceId]; const connection : Connection = this.connectionMap[dataSource?.connectionId]; if(dataSource && connection) { try { return await connection.query(dataSource.query, params, maxRecords, offset); } catch(err) { console.log(err); throw err; } } throw new Error(`DataSource ${dataSourceId} not found or has invalid connection`); } // == Private members // Private calculated lookups private idSet : Set<string> = new Set<string>(); private connectionMap : Map<string, Connection> = new Map<string, Connection>(); private dataSourceMap : Map<string, DataSource> = new Map<string, DataSource>(); private pageMap : Map<string, Page> = new Map<string, Page>(); private constructor(projectObj : any) { // Assumes the incoming object is a valid project, should have been validated in loadFromYaml or similar Object.assign(this, projectObj); // Validate the links between connections, datasources and pages this.connections.forEach(o => this.validateUniqueness(o, this.connectionMap, Connection.getTypeForAdapter(o.adapter))); // TODO: Make dynamic this.dataSources.forEach(o => this.validateUniqueness(o, this.dataSourceMap, DataSource)); this.pages.forEach(o => this.validateUniqueness(o, this.pageMap, Page)); } private validateUniqueness<T extends IId>(element : T, targetMap : Map<string, T>, type : (new() => T)) : void { if(this.idSet.has(element.id)) { throw new Error(`ID collision: ${element.id} was found multiple times in config`); } this.idSet.add(element.id); targetMap[element.id] = Object.assign(new type(), element); } toConfigBlob() : any { // TODO: Create interface for project data model const obj : any = { title: this.title, id: this.id, pages: this.pages, dataSources: this.dataSources }; return obj; } // == Static constructor static loadFromYaml(yamlFilePath : string, schemaFilePath : string) : [Project | null, string[]] { const projectObj = YAML.safeLoad(FS.readFileSync(yamlFilePath, 'utf8')); const validationResult = Validator.validate(projectObj, JSON.parse(FS.readFileSync(schemaFilePath, 'utf8'))); if(validationResult.valid) { const project : Project = new Project(projectObj); return [project, []]; } return [null, validationResult.errors.map(e => e.toString())]; } }<|endoftext|>import { Component, Prop, State, Event, EventEmitter, h } from "@stencil/core"; import { ApprovedPublicBadge } from "../../types"; import { ModalPositioning } from "../../interfaces"; import { IconClose, IconCheck, IconCheckSmall, IconArrowDown, IconMore } from "../../assets/icons"; import { Metadata } from "../../assets/metadata"; @Component({ tag: "publicbadges-modal", styleUrl: "public-badges-modal.scss", }) export class PublicbadgesModal { modalEl!: HTMLElement; @Prop() public badges: ApprovedPublicBadge[] = []; @Prop() public theme: string = ""; @Prop() public language: "EN" | "NL" = "EN"; @Prop() public positioning: ModalPositioning = { orientation: "vertical", left: 0, origin: "top" }; @State() public openBadge: number | null = null @Event() public closeDrawer: EventEmitter = ({ emit: (e) => e }); public componentDidLoad() { if(this.positioning.orientation === "vertical") { window.scrollBy(0, this.modalEl.getBoundingClientRect().top - 10) } } public closeModalHandler = () => { console.log('click') this.closeDrawer.emit(); } private toggleBadge = (i: number) => { this.openBadge = this.openBadge === i ? null : i; } public render() { const metadata = Metadata[this.language]; const { orientation, left, origin } = this.positioning return ( [ <div id="modal-bg" onClick={ this.closeModalHandler }></div>, <div id="modal" class={`${orientation} ${this.theme} ${origin}`} style={{ left: left.toString()+"px"}} ref={(el) => this.modalEl = el as HTMLElement}> <button class="close" onClick={ this.closeModalHandler }> <IconClose /> </button> <div id="modal-content"> <div id="logo" class="column"> <publicbadges-circle interactive={false}></publicbadges-circle> </div> <div id="badges" class="column"> <ul class={this.badges.length !== 1 ? "accordeon" : ""} > { this.badges.map((badge, i) => ( <li class={this.openBadge === i ? "open" : ""} onClick={()=> { this.toggleBadge(i) }}> <IconCheck /> <h3>{badge.name}</h3> <div class="badge-info"> <p>{badge.description}</p> {badge.evidence && <ul class="evidence"> {badge.evidence.map(proof=> { return <li> <IconCheckSmall /> <h4>{proof?.description}</h4> </li> })} </ul> } </div> { this.badges.length !== 1 && <IconArrowDown /> } </li>)) } </ul> </div> <div id="about" class="column"> <h1>{metadata.title}</h1> <h2>{metadata.subtitle}</h2> <div innerHTML={metadata.about(metadata.baseURL)}></div> <p> <a class="more" href={metadata.baseURL} target="_blank" rel="noopener noreferrer"> {metadata.more} <IconMore /> </a> </p> </div> </div> </div > ] ); } }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-2841.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-2841.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-2841.jsonl"}]
### Please examine the set of division, subtraction, addition, multiplication math exercises: 696 + 280 = 976 ### 1395 * -50 = -69750 ### 1278 + 1180 = 2458 ### 1651 + 2064 = 3715 ### 185 - 733 = -548 ### 732 / 220 = 3.33 ### 296 - 1853 = -1557 ### 979 / 356 = 2.75 ### -26 * 243 = -6318 ### 1000 + 631 = 1631 ### 1640 * 288 = 472320 ### 174 * 1427 = 248298 ### 593 - 551 = 42 ### 248 - 2016 = -1768 ### 2111 + 1716 = 3827 ### 1733 * 1160 = 2010280 ### 1556 / 457 = 3.4 ### -571 / 1671 = -0.34 ### 1154 + 2277 = 3431 ### 1456 * 1359 = 1978704 ### -702 / 1720 = -0.41 ### -41 - 829 = -870 ### Linear function: Y-intercept: -9.2892 x_start: -77 x_end: -29 step_size: 7 Value table: x | y ---------------------- Calculating y for x = -77 y = y_intercept + slope * x y = -9.2892 + 2.108 * -77 Intermediate Step: 2.108 * -77 = -162.3129 Final Step: -9.2892 + -162.3129 = -171.6021 -------------------------------------------------- -77 | -171.6021 Calculating y for x = -70 y = y_intercept + slope * x y = -9.2892 + 2.108 * -70 Intermediate Step: 2.108 * -70 = -147.5572 Final Step: -9.2892 + -147.5572 = -156.8464 -------------------------------------------------- -70 | -156.8464 Calculating y for x = -63 y = y_intercept + slope * x y = -9.2892 + 2.108 * -63 Intermediate Step: 2.108 * -63 = -132.8015 Final Step: -9.2892 + -132.8015 = -142.0907 -------------------------------------------------- -63 | -142.0907 Calculating y for x = -56 y = y_intercept + slope * x y = -9.2892 + 2.108 * -56 Intermediate Step: 2.108 * -56 = -118.0457 Final Step: -9.2892 + -118.0457 = -127.335 -------------------------------------------------- -56 | -127.335 Calculating y for x = -49 y = y_intercept + slope * x y = -9.2892 + 2.108 * -49 Intermediate Step: 2.108 * -49 = -103.29 Final Step: -9.2892 + -103.29 = -112.5792 -------------------------------------------------- -49 | -112.5792 Calculating y for x = -42 y = y_intercept + slope * x y = -9.2892 + 2.108 * -42 Intermediate Step: 2.108 * -42 = -88.5343 Final Step: -9.2892 + -88.5343 = -97.8235 -------------------------------------------------- -42 | -97.8235 Calculating y for x = -35 y = y_intercept + slope * x y = -9.2892 + 2.108 * -35 Intermediate Step: 2.108 * -35 = -73.7786 Final Step: -9.2892 + -73.7786 = -83.0678 -------------------------------------------------- -35 | -83.0678<|endoftext|>### Please examine the set of division, subtraction, addition, multiplication arithmaic examples: 1043 / 721 = 1.45 ### 386 - 323 = 63 ### 226 / 826 = 0.27 ### 2078 / 215 = 9.67 ### 480 + 1598 = 2078 ### 2056 + 287 = 2343 ### 1407 + 1100 = 2507 ### 1888 * 458 = 864704 ### 1696 * 875 = 1484000 ### 846 / -74 = -11.43 ### 1478 + 606 = 2084 ### 41 * 1082 = 44362 ### 2147 - 1290 = 857 ### 1423 - 1829 = -406 ### 1764 + 297 = 2061 ### 1933 + 258 = 2191 ### 1678 * 2289 = 3840942 ### 1017 - 268 = 749 ### 1918 - 1095 = 823 ### Eva work as a sales clerk. She is paid a salary of 9448 a week plus 2% commission on sales over 4000. Find her gross pay for a week in which her sales are 44772. Step-by-step solution: To calculate Eva's gross pay, we need to add her salary to the commission she earned on sales over 4000. Her salary is 9448 per week. Her sales for this week are 44772. Commission = 2% of (sales - 4000). Commission = 0.02 * (44772 - 4000) = 815.44. Therefore, Eva's gross pay for the week is 10263.44. ### 2040 + -10 = 2030 ### 635 / 60 = 10.58 ### 1327 * 1016 = 1348232 ### 2022 + 655 = 2677 ### 143 + 908 = 1051 ### 1540 - 1451 = 89 ### 1739 - 575 = 1164 ### -45 - 978 = -1023 ### 2097 * 1817 = 3810249 ### 1459 * 311 = 453749 ### 1868 - 148 = 1720 ### 255 * 1380 = 351900 ### 1181 * 125 = 147625 ### 26 + 528 = 554 ### 1652 / 725 = 2.28 ### 929 + 1752 = 2681 ### 1615 / 2183 = 0.74 ### 1272 - 807 = 465 ### 900 * 950 = 855000<|endoftext|>### Here's set of multiplication, addition, division, subtraction math examples: 2006 + 1079 = 3085 ### 2259 * -75 = -169425 ### 851 - 569 = 282 ### 173 + 1073 = 1246 ### 1132 * 1372 = 1553104 ### -247 / 852 = -0.29 ### 511 + 189 = 700 ### 130 * 555 = 72150 ### 1403 - 1306 = 97 ### 94 * 592 = 55648 ### 1723 * 1847 = 3182381 ### 1996 + 549 = 2545 ### 2208 + 366 = 2574 ### -271 / 1492 = -0.18 ### 1095 / 1448 = 0.76 ### 1946 - 893 = 1053 ### 1912 / 262 = 7.3 ### 585 / 1399 = 0.42 ### 1324 / 439 = 3.02 ### 1249 / 522 = 2.39 ### 1681 - 437 = 1244 ### 643 / 654 = 0.98 ### 1710 + 2109 = 3819 ### 1847 + 205 = 2052 ### 1506 * 70 = 105420 ### 5 + 1 =\n#### OK, let's do this. We've got 5 and 1 and we're adding them all together. Step 1: We'll start by adding the digits 5 & 1 in column 1 and get 6. So, 5 + 1 = 6. ### -22 - 1297 = -1319 ### 1484 * 1815 = 2693460 ### 1881 + 2242 = 4123 ### -261 / 899 = -0.29 ### 1766 - 1853 = -87 ### -399 / 72 = -5.54 ### 1794 - 2 = 1792 ### 302 * -12 = -3624 ### 1549 + 947 = 2496 ### 35 + 975 = 1010 ### 464 / 586 = 0.79 ### 1372 + 758 = 2130 ### 1767 - 2183 = -416 ### 2121 + 2112 = 4233 ### 1137 / 949 = 1.2 ### 699 * 1631 = 1140069 ### 2001 - 2210 = -209 ### 618 * 269 = 166242 ### 1607 * 2023 = 3250961 ### 1963 * 23 = 45149 ### 190 - 3 = 187<|endoftext|>### Think deeply about this set of division, subtraction, addition, multiplication math insights: 1335 - 1346 = -11 ### -118 / -20 = 5.9 ### 1812 * 834 = 1511208 ### 2337 + 53 = 2390 ### 1526 + 730 = 2256 ### 2245 * 958 = 2150710 ### 530 / 1258 = 0.42 ### 2010 + 790 = 2800 ### 1073 + 2268 = 3341 ### Let's divide 2836 by 4 Let's see how many times 4 fits into 2836. Step 1: 2 divided by 4 is 0 with a remainder of 2. The next digit of our result is 0. Result so far: 0.0 Deduct 0 from 2 and we're left with 2. Grab the next digit (8) from the dividend, add it to 2, then carry on: 28 / 4 Going ahead to step 2: 4 goes into 28 7 times with a remainder of 0. Record the quotient 7 as the next digit in the result. Result so far: 7.0 If we subtract 28 from 28, we get 0. Grab the next digit (3) from the dividend, add it to 0, then carry on: 3 / 4 Let's proceed to step 3: The number 4 fits into 3 0 times, leaving a remainder of 3. Record the quotient 0 as the next digit in the result. Result so far: 70.0 Subtract 0 from 3 to get 3. Include the next digit (6) from the dividend after 3, then repeat: 36 / 4 Let's proceed to step 4: 4 can be fit into 36 9 times, resulting in a remainder of 0. The next digit of our result is 9. Result so far: 709.0 If we take 36 away from 36, we end up with 0. Since there are no more digits in the dividend, we add a zero to the remainder making it 0, and continue the process. Going ahead to step 5: 4 can be fit into 0 0 times, resulting in a remainder of 0. The next digit of our result is 0. Result so far: 709.0 Deduct 0 from 0 and we're left with 0. Since there are no more digits in the dividend, we add a zero to the remainder making it 0, and continue the process. Let's proceed to step 6: 4 goes into 0 0 times with a remainder of 0. Write down 0 as next digit of the result. Result so far: 709.0 Subtract 0 from 0 to get 0. Since there are no more digits in the dividend, we add a zero to the remainder making it 0, and continue the process. After the division, we end up with 709.0 and a remainder of 0.0.<|endoftext|>### Think deeply about this set of subtraction, division, multiplication, addition math problems: 609 - 1365 = -756 ### 757 / 1478 = 0.51 ### 1598 / 712 = 2.24 ### -35 / 1182 = -0.03 ### 616 * 2112 = 1300992 ### 1948 + 94 = 2042 ### 1659 * 1198 = 1987482 ### Grace is attempting to solve this system of equations: 77x + 35y = 454 9x + 3y = 12 Can you find the values of x and y? Step 1: The goal is to make the coefficients of y in both equations the same. This is done by multiplying the entire first equation by 3 and the entire second equation by 35, leading to: 231x + 105y = 1362 and 315x + 105y = 420 Step 2: Now, subtract the second equation from the first. This involves subtracting each corresponding term on both sides. After performing the subtraction, we get: (231-315)x + (105-105)y = (1362-420) Which simplifies to: x = -11.214285714285714 Step 3: We now know the value of x, so we substitute x = -11.214285714285714 into the first equation. The first equation becomes: 77*-11.214285714285714 + 35y = 454 Step 4: Simplify the equation by performing the multiplication 77*-11.214285714285714, which results in: -863.4999999999999 + 35y = 454 Then, isolate y by subtracting -863.4999999999999 from both sides. This gives us: y = 37.642857142857146 Step 5: Thus, the solution to the system of equations is x = -11.214285714285714 and y = 37.642857142857146. ### 301 - 1023 = -722 ### 1230 * 1999 = 2458770 ### 79 * 2183 = 172457 ### 1045 + 1479 = 2524 ### -558 / 703 = -0.79 ### 2211 + 1653 = 3864 ### 1329 - 1892 = -563 ### 773 + 2223 = 2996 ### 1803 / -462 = -3.9 ### 536 + 2217 = 2753 ### 1375 + 1576 = 2951 ### 1659 + 66 = 1725 ### 2225 - 839 = 1386 ### 118 * 364 = 42952 ### -140 / -152 = 0.92
[{"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}]
LM1085 constant current mode: changing input voltage deviates the ADJ pin in a non-linear fashion Question: I used the below schematic to output a constant current (~0.92 A) on the RLoad. I turn on/off the N-channel mosfet: simulate this circuit – Schematic created using CircuitLab While current flows through the RLoad, if I tweak the power supply voltage (from 8.53 to 6.8), I notice that the reference voltage (1.25 V at ADJ pin), changes like so: It might be a deviation of 4 mV or less on the ADJ pin, but I wanted to know why this peak on Adj voltage is happening at ~7.19 V. I started looking at LM1085's datasheet and the only thing I suspect is the ripple rejection vs frequency. My power supply might be changing frequency on different output voltages. My question is: Is there any data/graph on the LM1085's datasheet that describes this behavior? I do not see any input voltage vs ADJ pin graph for example. Note: I do not think that using the N-ch mosfet creates the above voltage swing on the ADJ pin, since the ADJ is referenced to the LM1085's output pin, and not to GND. Comment: Is it an LM315 or LM1085? Comment: @Aaron LM1085. I edited and fixed the schematic! Answer: The difference between 1.245 V and 1.249 V is 0.3%. This is pretty good stability for a system whose temperature could vary significantly as the input voltage changes. Assuming the MOSFET had negligible 'on' resistance, and RRef and RLoad maintained the values shown, the voltage across the regulator varied from ~ 2.17 to 3.91 V, corresponding to a power dissipation of ~ 2.0 to 3.6 W. Assuming a bare TO220 package with thermal resistance from junction to ambient of 22.8 °C/W, and air temperature of 20 °C, the junction temperature varied from ~ 65 to 102 °C, a difference of 37 °C. The datasheet shows a 'typical' voltage change of about 0.2% between 50 °C and 100 °C, but transient effects could be higher. If you did not allow enough time for the temperature to stabilize then the voltage could have varied as the regulator warmed up and/or cooled down between tests. Note: I do not think that using the N-ch mosfet creates the above voltage swing on the ADJ pin, since the ADJ is referenced to the LM1085's output pin, and not to GND. If the FET has negligible voltage drop when on then this should be true. If it didn't then the regulator could have been running close to dropout, causing poor regulation. A similar effect might occur if the power supply had high ripple. I recommend using an oscilloscope to check for ripple and other effects (oscillations, noise etc.). Answer: There is a minimum I(out) requirements you are not meeting in your circuit ...you need a typical minimum of 5mA (max 10mA) flowing from the output pin at all times. Using this type or regulator as a constant current source requires it to be ON at all times. If you switch it off then the internal linearity is not guaranteed and you will get overshoot current at switch on. You need to add a resistor (R1) as shown below to ensure you meet the required I(out) minimum on a continuous basis. simulate this circuit – Schematic created using CircuitLab Comment: Useful thanks!. But I think its not "breaching", right? In a sense that, the datasheet says that this is the minimum output current where it can regulate the output properly. It wont heat or hurt the IC if I dont meet the lower output current while its switched off. It will just create a overshoot when it opens. Comment: If you simply don't like 'breaching' then I can change to another word. I am surprised you'd accept the overshoot on turnon. Comment: Well I wouldn't accept the overshoot, I will for sure add that resistor. Answer: To find the source of this fluctuation in \$V_{REF}\$, we first need to understand what currents are at work here. On page 6 of that datasheet you'll find \$I_{ADJ}\$ and \$\Delta I_{ADJ}\$. These refer to the current being sourced by the ADJ pin of the regulator, and the low value of \$\Delta I_{ADJ}=0.2\mu A\$ suggests that \$I_{ADJ}\$ is fairly constant at 55μA, but may vary somewhat around this value. Kirchhoff's Current Law (KCL) requires that this current combine with the current \$I_{OUT}\$ at the junction between \$R_{REF}\$ and \$R_{LOAD}\$, like this: $$I_{LOAD} = I_{OUT} + I_{ADJ}$$ Rearranging that to find the current \$I_{OUT}\$ through \$R_{REF}\$: $$I_{OUT} = I_{LOAD} - I_{ADJ}$$ Let's assume (incorrectly) that the regulator manages to keep \$I_{LOAD}\$ constant at the target value of 0.92A, and that consequently the voltage fluctuation you see across \$R_{REF}\$ (which is proportional to the fluctuation of current \$I_{OUT}\$) is due entirely to a variation in current \$I_{ADJ}\$. The fluctuation in \$I_{OUT}\$ is: $$ \Delta I_{OUT} = \frac{V_{REF\_MAX}}{R_{REF}} - \frac{V_{REF\_MIN}}{R_{REF}} = \frac{0.004V}{1.35\Omega} = 3mA $$ This is clearly far greater than \$\Delta I_{ADJ}=0.2\mu A\$, and the conclusion can only be that the majority of the variation you see in \$V_{REF}\$ has nothing to do with \$I_{ADJ}\$. In other words, this regulator is not regulating perfectly, and our earlier assumption that \$I_{LOAD}\$ is being pefectly maintained at 0.92A is wrong. If \$I_{ADJ}\$ is truly constant at 55µA, changes in \$V_{REF}\$ must actually be due to imperfect regulation, and you would see a similar percentage error in \$I_{LOAD}\$. That error is about: $$ \sigma = \frac{3mA}{0.92A} \approx 0.3\%$$ That's better than the datasheet's quoted load regulation of 1%, but is far from perfect, and illustrates why this particular characteristic of regulators is always included in the datasheets. As to why this happens, there are many causes, but the big ones might be: Finite output impedance, which is not constant, and is related to (but not necessarily proportional to) load current. This effectively appears in series with \$R_{REF}\$. Imperfect internal voltage reference. The designer intended to mitigate this source of error by using a constant current source to drive his reference zener diode (hence the constant value of \$I_{ADJ} = 55\mu A\$) but that can't completely eliminate reference errors. Non linearity in the reulator's error amplifier, which arises from things like input bias currents and offsets and finite gain, all typical problems you encounter in control systems using op-amps. While I think your experiment is great, and everybody should be doing things like this, I don't really trust your graph, because there aren't enough data points. It looks quite chaotic, and the lack of a smooth curve here really puts into question your claim that there's a peak at \$V_{IN} = 7.19V\$. If you made more measurements around that value, which resulted in a smooth(ish) curve around that point in the graph, I would have more confidence in the claim. Also, I don't know the quality of your test equipment. If for example you are using a multimeter with 1% accuracy, you can't really trust the third digit. This is particularly important here, where changes in \$V_{REF}\$ are of the order of millivolts. When measuring a signal on the 2V range of your DVM, you would need accuracy of 0.05% or better to have any confidence in the 4th digit, which would represent millvolts.<|endoftext|>Получение расширения файла Question: У меня есть метод <code>OnClick</code> в котором реализован следующий функционал: <code>Intent intent = new Intent(); intent.setType("*/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Выберите файл для загрузки "), 1); </code> После чего открывается список файлов, после выбора переходим в метод <code>OnActivityResult</code> и там получаем <code>Intent</code> который отправили в методе <code>OnClick</code>. <code>@Override public void onActivityResult(int requestCode, int resultCode, Intent data) </code> Как можно получить расширение файла через переменную <code>data</code> ? Мне приходит полный путь к файлу по которому я могу его достать но название не соответствует действительности. К примеру в телефоне у меня медиа файл называется <code>video0515.mp4</code> а в data мне приходит путь к файлу: <code>Intent { dat=content://com.android.providers.media.documents/document/video:10515 flg=0x1 } </code> и расширение никак не получается получить. Comment: Вот как раз в URI и находится ссылка на файл content://com.android.providers.media.documents/document/image%3A10734 Comment: Больше ничего толкового оттуда не вытащить, либо я плохо искал Comment: Возвращает null Answer: Чтобы получить MIME-тип файла из его URI нужно написать небольшой метод: <code>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Uri uri = data.getData(); String type = getMimeType(uri))); } </code> Сам метод получения : <code>public String getMimeType(Uri uri) { if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) { ContentResolver cr = this.getContentResolver(); mimeType = cr.getType(uri); } else { String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri .toString()); mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( fileExtension.toLowerCase()); } return mimeType; } </code> строка <code>type</code> будет содержать MIME-тип файла. Например, для изображения JPG получим - image/jpg Две ветки в методах связаны с тем, что URI файлов контента (как изображения, видео, аудио и тп) имеют другой формат, чем прочие файлы. Так же можно получить и "чистое" расширение файла из его имени. В силу того, что в Android очень запутанная система файлов, которая делится на контент (а контент еще и по видам) и собственно файлы, да еще и зависит от API, то универсальный код получения расширения довольно громоздкий. При необходимости вы можете выбрать отдельный модуль, подходящий именно для вашей задачи (например, только файлы изображений на API 19 и выше), а не копировать весь код: <code>// метод возвращает полный реальный путь до файла, включая имя и расширение public String getFilePath(Uri uri) { String selection = null; String[] selectionArgs = null; if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(this, uri)) { if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); return Environment.getExternalStorageDirectory() + "/" + split[1]; } else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); uri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); } else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("image".equals(type)) { uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } selection = "_id=?"; selectionArgs = new String[]{split[1]}; } } if ("content".equalsIgnoreCase(uri.getScheme())) { String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = null; try { cursor = getContentResolver().query(uri, projection, selection, selectionArgs, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); if (cursor.moveToFirst()) { return cursor.getString(column_index); } } catch (Exception e) { } finally { if (cursor != null) cursor.close(); } } else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } // метод возвращает из полного пути расширение файла public String getFileExtension(String path) { int pos = path.lastIndexOf("."); if (pos != -1) return path.substring(pos + 1); else return ""; } </code> Тогда получение расширения будет происходить так: <code>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Uri uri = data.getData(); String type = getFileExtension(getFilePath(uri))); } </code> где переменная <code>type</code> - расширение файла. Например, для файла 1234.jpg она будет равна jpg Для работы на API 19 и выше требуется разрешение в манифесте <code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/></code> Comment: В 1-м случае где мы получает отдельно расширение файла...я его конкатенирую с названием файла и отправляю на сервер, файл приходит битый Comment: Я разбираю эту строку и беру расширение после "/" и подставляю в имя файла Comment: На сервер у меня уходит имя файла "image:10734" + ".jpg" причем имя файла я получаю через File file = new File(uri.getPath()); file.getName(); Comment: При этом файл сам называется DSC_0156.JPG а в OnActivityResult приходит далеко не это название файла Comment: @Heaven `file = new File(uri.getPath()); file.getName();` - для файлов контента не работает, как вы сами видите. Comment: Я просто подумал что получиться конкатенировать имя файла и расширение, вот только в процессе оказалось что проблема и с тем и с тем Comment: @Heaven выведите, что возвращает метод `getFilePath()` и поймете, что нужно от него "отрезать". Если вам нужно работать только с файлами изображений, то этот метод можно существенно сократить (убрать все `if`, которые не относятся к Mediadocument и в нем к image), а если и API требуется только больше (или меньше) 19 , то и еще одну ветку. Comment: Помогло, не думал что работа с файлами может создать столько проблем. Спасибо большое! Comment: @Heaven да, нелепая какая то схема, столько сложностей, согласен. Я исправил немного, забыл курсор закрыть.
[{"idx": "LM1085_constant_current_mode:_changing_input_voltage_deviates_the_ADJ_pin_in_a_non-linear_fashion", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-3697.jsonl"}, {"idx": "\u041f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u0435_\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u044f_\u0444\u0430\u0439\u043b\u0430", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-3697.jsonl"}]
import pytest from qval import validate, APIException, InvalidQueryParamException, QvalValidationError from qval.framework_integration import ( HTTP_500_INTERNAL_SERVER_ERROR, HTTP_400_BAD_REQUEST, ) from tests.crossframework import builder def test_params_processed(): dct = {"num": "42", "double": "2.79", "string": "some string"} with validate(request, num=int, double=float) as p: assert p.double == 2.79 assert p.string == "some string" def test_params_omitted(): dct = {"num": "42", "string": "some string"} # Disable auto-detection of parameters (box_all) params = validate(request, num=int, box_all=False) with pytest.raises(APIException) as e, params as p: assert p.string == "some string" def test_missing_param_throws_error(): dct = {"param1": "whatever", "param2": "6.66"} params = validate(request, param1=None, param2=float, param3=int) pass def test_validator_factory(): qparams = { "price": "43.5$", "n_items": "1", "meta": "info", "num": "10", "num2": "5", "token": "0<PASSWORD>", } params = ( validate( "n_items" ) .eq("num", 10) .lt("num2", 10) .check("token", lambda x: len(x) == 10) .eq("token", 10, transform=len) ) with params as p: assert {43.5, 1, "info", 10, 5, "0123456789"} == set(p.__dct__.values()) def test_validation_fails(): qparams = { "price": "43.5$", "n_items": "0", "meta": "info", "num": "-10", "num2": "20", "token": "0<PASSWORD>", } params = ( validate( "n_items" ) .eq("num", 10) .lt("num2", 10) .check("token", lambda x: len(x) == 10) .eq("token", 10, transform=len) ) pass def test_exception_handled_in_outside_context(): """ See `QueryParamValidator._validate()` and `test_supported_errors_handled()` for more info. """ # Random exception. def f(_): raise IOError params = {"param": "value"} with pytest.raises(APIException) as e, validate(r, param=f): pass def test_supported_errors_handled(): """ Only TypeError, ValueError and KeyError occurred during the validation are handled as expected. Any error thrown inside of the context will raise APIError. See `test_unsupported_errors_handled()`. """ def exc_factory(exc): def f(_): raise exc return f params = {"param": "value"} for exc in (TypeError, ValueError, KeyError): with pytest.raises(InvalidQueryParamException) as e, validate( r, param=exc_factory(exc) ): pass def test_unsupported_errors_handled(): supported_exceptions = (TypeError, ValueError, KeyError) random_exceptions = (IOError, BrokenPipeError, ConnectionError, BufferError) params = {"param": "value"} for exc in supported_exceptions + random_exceptions: with pytest.raises(APIException) as e, validate(r): raise exc def test_custom_validation_errors(): def num_predicate(value: int) -> bool: if not 0 < value < 10: raise QvalValidationError( f"`num` must belong to the interval (0; 10), got '{value}'." ) return True params = validate({"num": "5"}, {"num": num_predicate}, num=int) with params as p: assert p.num == 5 try: with params.apply_to_request({"num": "20"}): pass except InvalidQueryParamException as e: assert "`num` must belong to the interval (0; 10), got '20'." in str(e.detail)<|endoftext|>import numpy as np np.seterr(all="ignore") from scipy.stats import norm class EuropeanCallOption: plot_title = "European Call Option" plotly_template = "plotly_white" plot_width = 1500 plot_height = 1000 def __init__(self, strike_price, end_time, sigma, steps_count, delta=0, interest=0): self.strike_price = strike_price self.sigma = sigma self.steps_count = steps_count self.sampling_points = self.end_time * self.steps_count self.dt = self.end_time / self.sampling_points self.time_grid = self._get_time_grid() self.delta = delta self.interest = interest def _get_time_grid(self): time_grid = np.arange(0, self.end_time + self.dt, self.dt) return time_grid def _d_plus(self, stock_price, current_time): self.interest - self.delta + self.sigma ** 2 / 2 def _d_minus(self, stock_price, current_time): self.interest - self.delta - self.sigma ** 2 / 2 def _adjust_stock_price(self, stock_price, current_time): adjusted_stock_price = stock_price * np.exp( (self.interest - self.delta) * current_time ) return adjusted_stock_price def _adjust_strike_price(self, stock_price, current_time): adjusted_strike_price = self.strike_price * np.exp( -self.interest * (self.end_time - current_time) ) return adjusted_strike_price def _get_price(self, stock_price, current_time): adjusted_strike_price = self._adjust_strike_price(stock_price, current_time) d_plus = self._d_plus(stock_price, current_time) d_minus = self._d_minus(stock_price, current_time) return adjusted_stock_price * np.exp( -self.delta * (self.end_time - current_time) ) * norm.cdf(d_plus) - adjusted_strike_price * norm.cdf(d_minus) def _get_hedge(self, stock_price, current_time): d_plus = self._d_plus(adjusted_stock_price, current_time) return norm.cdf(d_plus) * np.exp(-self.delta * (self.end_time - current_time)) def _get_portfolio(self, stock_price, current_time): stock_price = self._adjust_stock_price(stock_price, current_time) a1 = 1 + self.interest * self.dt a2 = 1 + (self.interest - self.delta) * self.dt initial_price = self.price[0] if self.delta == self.interest == 0: diff = np.diff(stock_price, n=1) diff_and_hedge_cumsum = np.cumsum(diff * self.hedge[:-1]) diff_and_hedge_cumsum = np.append(0, diff_and_hedge_cumsum) portfolio = initial_price + diff_and_hedge_cumsum else: portfolio = np.empty(self.sampling_points + 1, dtype=float) portfolio[0] = initial_price for i in range(self.sampling_points): portfolio[i + 1] = ( portfolio[i] * a1 + self.hedge[i] * (stock_price[i + 1] - stock_price[i]) * a2 ) return portfolio def simulate(self, stock_price, random_seed=42): self.price = self._get_price( ) self.hedge = self._get_hedge( ) self.portfolio = self._get_portfolio( ) def plot(self): fig = make_subplots(rows=2, cols=1) fig.append_trace( go.Scatter(x=self.time_grid, y=self.price, name="Price"), row=1, col=1, ), fig.append_trace( go.Scatter(x=self.time_grid, y=self.hedge, name="Hedging",), row=2, col=1, ), fig.append_trace( go.Scatter(x=self.time_grid, y=self.portfolio, name="Portfolio"), row=1, col=1, ), fig.update_layout( height=self.plot_height, width=self.plot_width, title_text=self.plot_title, template=self.plotly_template, ) fig.show()<|endoftext|># [IDX] sys import subprocess import os import re import plistlib import datetime from Foundation import CFPreferencesCopyAppValue # Start configuration # Set this to False if you don't want any output, just the exit codes verbose = True # Set this to True if you want to add "office_2011_language" custom conditional to # /Library/Managed Installs/ConditionalItems.plist update_munki_conditional_items = False # End configuration def info_for_package_identifier(identifier): """ Returns an info dictionary for a given package identifier by running /usr/sbin/pkgutil --pkg-info-plist <identifier> """ if not identifier: return None cmd = ["/usr/sbin/pkgutil", "--pkg-info-plist", identifier] if p.returncode != 0: return None package_info_dict = {} package_info_dict = plistlib.readPlistFromString(results) return package_info_dict def installed_core_resource_packages(): """ Returns a list of installed Office core resource packages These packages have the following identifier format: com.microsoft.office.<language>.core_resources.pkg.<version> """ cmd = ["/usr/sbin/pkgutil", "--pkgs-plist"] if p.returncode != 0: return [] all_package_identifiers = plistlib.readPlistFromString(results) re_core_resource = re.compile(r'^com\.microsoft\.office\.(?P<language_code>.*)\.core_resources\.pkg\.(?P<version>[0-9\.]+)(.update$|$)') matching_packages = [] for identifier in all_package_identifiers: m = re.match(re_core_resource, identifier) if m and m.group('language_code'): item_info = info_for_package_identifier(identifier) item_info['language'] = m.group('language_code') matching_packages.append(item_info) return matching_packages def conditional_items_path(): # < [IDX] # Read the location of the ManagedInstallDir from ManagedInstall.plist bundle_id = 'ManagedInstalls' pref_name = 'ManagedInstallDir' managed_installs_dir = CFPreferencesCopyAppValue(pref_name, bundle_id) # Make sure we're outputting our information to "ConditionalItems.plist" if managed_installs_dir: return os.path.join(managed_installs_dir, 'ConditionalItems.plist') else: # Munki default return "/Library/Managed Installs/ConditionalItems.plist" def munki_installed(): cmd = ["pkgutil", "--pkg-info", "com.googlecode.munki.core"] output = p.communicate()[0] if p.returncode == 0: return True else: return False def append_conditional_items(dictionary): current_conditional_items_path = conditional_items_path() if os.path.exists(current_conditional_items_path): existing_dict = plistlib.readPlist(current_conditional_items_path) output_dict = dict(existing_dict.items() + dictionary.items()) else: output_dict = dictionary plistlib.writePlist(output_dict, current_conditional_items_path) pass def main(argv=None): # Get all Office core resource packages packages = installed_core_resource_packages() if len(packages) == 0: # Office is not installed return 1 # Sort the packages by install time packages_sorted = sorted(packages, key=attrgetter('install-time', 'pkg-version'), reverse=True) # Installed language is the language of the latest package latest_package_info = packages_sorted[0] latest_lang = latest_package_info.get('language', None) if verbose: if latest_lang: print latest_lang else: print "Could not determine installed language" # Update "ConditionalItems.plist" if munki is installed if munki_installed() and update_munki_conditional_items and latest_lang: append_conditional_items({'office_2011_language': latest_lang}) return 0 if __name__ == '__main__': sys.exit(main())
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-15829.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-15829.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-15829.jsonl"}]
What's the easiest way to fetch a SharePoint file by a path from the Microsoft Graph? Question: Say you have a file path like: <code> [IDX] the easiest way to turn this into a Microsoft Graph call to fetch the contents of the file which I assume we need to do via the <code>drives</code> endpoint using the correct id's. I assume I might have to run multiple calls and perhaps assume that /slash1/slash2 is the site, then the next is the doclib etc(?) Answer: Not sure is it the easiest or the only option but the below solution demonstrates how to meet the requirements of Addressing resources in OneDrive API: first step would be to transform the URL into a sharing token (see below section), for that matter we utilize <code>Shares</code> API once the sharing token is generated, the OneDrive API request to download a file could be constructed like this: <code>/shares/{shareIdOrEncodedSharingUrl}/driveitem/content</code> How to transform the URL into a sharing token For url: <code> [IDX] be generated the following token: <code>u!aHR0cHM6Ly9jb250b3NvLnNoYXJlcG9pbnQuY29tL3NpdGVzL3NvbWVzaXRlL015RG9jTGliL0ZvbGRlci9Gb28uZG9jeA </code> On how to encode a URL is described in MS Graph documentation (C# version is provided there) NodeJS version: <code>function urlToToSharingToken(url) { var trimEnd = function(str, c) { c = c ? c : ' '; var i = str.length - 1; for (; i >= 0 && str.charAt(i) == c; i--); return str.substring(0, i + 1); }; var value = Buffer.from(url).toString('base64'); return "u!" + trimEnd(value, '=').replace(/\//g, '_').replace(/\+/g, '-'); } </code> Example The example demonstrates how download a file by url provided in the <code> [IDX] format using <code>msgraph-sdk-javascript</code> library: <code> const sharedItemId = urlToToSharingToken(url); //1.construct sharing token const requestUrl = "/shares/" + sharedItemId + "/driveitem/content"; //2. construct a query to download a file content return new Promise((resolve, reject) => { var builder = client.api(requestUrl); getAsBinary(builder, (err, stream) => { if (err) { return reject(err); } return resolve(stream); }); }); </code> Comment: That's a pretty nifty solution indeed - and thanks for the pointer on creating the sharing encoded part. Much better than first getting the drive and then the item based on paths :)<|endoftext|>Dominant 7 alt vs tritone sub Question: Why do we use Dominant 7th alt term. Because the dominant 7th alt is basically the tritone sub but with a natural and flat nine and flat five with the flat 5 in bass. I mean i guess g7alt is better than reading Db7(nat.9,b9,b5)/G Comment: Sorry, I don't understand your question. Could it be that some words got lost? Would you please reread and eventually make some corrections or precisions? Comment: I think the question is about the terminology used to name the chord, rather than when to use the chord itself. Answer: You are right in that a ♭II7 tritone sub chord with a ♭V in the bass sounds essentially like a V7alt chord but your analysis of "Db7(nat.9,b9,b5)/G" being a G7alt is not quite right. In the keys you referenced a G7alt contains ♭9, #9, ♭5 and ♭13. This is basically the same as a D♭13#11 Which has 9, #11, 13. They have the same notes but they have different roots. The root largely defines the chord and the way it functions in a chord progression so it's better to spell a chord from the root when possible. That's why we use the term "alt". I'm sure I'm not alone in saying that I would rather see G7alt over a D♭13#11/G on a chart. As a musician, bass player and improviser I even approach the two differently when creating walking lines or improvising. Hope this answers your question. Comment: Yeah most people at least myself still voice the 5th of the g7 in the g7 alt giving essentially a Db13,9,b9/G because you have to take in account the actual g7 your playing under extensions i mean i know you dont have to voice 5th but it adds more tension Comment: It's true that the natural 5 will add even more tension to an already tension filled chord. I however think of the 7alt chord as having a b5 because the scale that is often used to play over it, the 7th mode of the melodic minor (R b9 #9 3 b5 b13 b7) has no natural 5. Answer: We can use V7(b5b9)or its triton substitution when ever we want, just the way we like it. There's no rule, no law or principle why we should choose the one or the other. Sometimes it is comfortable to progress chromatically down steps walking through the circle of fifths, especially the bass line. Comment: The question is asking: "what's the point in describing a chord as an altered dominant if we could more simply just describe it as a tritone substitution? After all, the two chords (altered dominant and tritone sub) share the same notes."<|endoftext|>Не работает регулярка в PHP в многострочном режиме Question: Ребят подскажите пожалуйста, почему регулярка не работает. В документации пишут, что если поставить параметр x, то можно регулярные выражения переносить на сл строки и этот параметр заставит не учитывать пробелы и переносы строк и даже комментарии. Но не работает =( Вот сама регулярка <code>preg_match_all('{ <div class=\"a--atext atext\" itemprop=\"text\">(.*?)<\/div> }uxis',$result,$mAnswers); </code> Comment: вроде за это отвечал флаг `m`, но в конкретном случае у вас еще учитваются и переводы строки перед/после элемента, что навряд ли является желаемым поведением Comment: плюс, емнип, управляющие символы регулярки должны быть идентичными, здесь же это две разных скобки Comment: вы поняли что в документации шла речь об переносах в самом регулярном выражении, а не в тексте, который вы им разбираете? Comment: или вы про это и пишите? зы: уберите лишнее экранирование двойных кавычек и слешей. Comment: Что такое емнип? Comment: Да я понял, я именно про перенос строк в самой регулярке - ибо строк возможно будет много и неудобно их все в 1ну пихать. Answer: Если необходимо иметь возможность разбивать само регулярное выражение на строки, то для <code>$result = '<div class="a--atext atext" itemprop="text">Some Text</div>';</code> подойдет такое выражение (необходимо экранировать значимые пробелы): <code>preg_match_all('@ <div\ class="a--atext\ atext"\ itemprop="text">(.*?)</div> @uxis', $result, $mAnswers); </code> и <code>$mAnswers</code> будет содержать: <code>Array ( [0] => Array ( [0] => <div class="a--atext atext" itemprop="text">Some Text</div> ) [1] => Array ( [0] => Some Text ) ) </code> Но если имеется в виду, что сама искомая строка может содержать переводы строк: <code>$result = '<div class="a--atext atext" itemprop="text"> Some Text 1 Some Text 2 Some Text 3 </div>'; </code> то подойдет следующее выражение: <code>preg_match_all('@<div class="a--atext atext" itemprop="text">(.*?)</div>@uis', $result, $mAnswers); </code> и $mAnswers будет содержать: <code>Array ( [0] => Array ( [0] => <div class="a--atext atext" itemprop="text"> Some Text 1 Some Text 2 Some Text 3 </div> ) [1] => Array ( [0] => Some Text 1 Some Text 2 Some Text 3 ) ) </code> Comment: Огромное спасибо! Вы очень мне помогли! Здоровья вам!!! :)<|endoftext|>Poisson process breakdown(waiting times) Question: Certain electrical disturbances occur according to a Poisson process with rate 3 per hour. These disturbances cause damage to a computer. a) Assume that a single disturbance will cause the computer to crash. What is the probability that the system will crash in the coming 10 minutes? b) Assume that the computer will survive a single disturbance, but the second such disturbance will cause it to crash. What is, now, the probability that the computer will crash in the coming 10 minutes? c) Assume that a crash will not happen unless there are two disturbances within 5 minutes of each other. Calculate the probability that the computer will crash in the coming 10 minutes My attempt a)$$ P(N(1)=3) = \frac{e^{-3} 3^1}{1!} = 0.149$$ b) $$ P(N(2)=3|N(1)=3$$ not really sure how to move on from there c) $$ P(N(1)=3|N(2)=6)) $$ How far off am I from the correct answers? Answer: The rate is 3 per hour so the rate for 10 min is 3/6. So prob computer will crash is 10 min is $1-P(n=0) = 1-exp(-1/2)$. i.e. at least 1 (maybe more) disturbances. b) prob will crash $=1-P(m=0)-P(m=1)$. i.e. at least two. c) for a Poisson process the time between events follows an exponential distribution. so want $P(T<5min)=1-exp(-3 *(5/60)$. Comment: Just to elaborate on part b), are you saying $$1- e^{-1/2} - 1/2*e^{-1/2}$$? Comment: The solution to (c) is incorrect. Comment: Just came back to correct it, but you've done it for me, ta. Comment: Checking my answers, are they a) 0.393 b) Comment: Sorry, still trying to figure out stackexchange, could someone please check my answers? a) 0.393 b) 0.09 c) 0.04 Answer: Let $T_n$ denote the successive event times of the Poisson process. You are supposed to be able to see that the answer to (a) is $$ P(T_1\lt10), $$ and to compute this quantity, and to see that the answer to (b) is $$ P(T_2\lt10), $$ and to compute this quantity. To solve (c), note that, according to these new rules, a crash can happen in the first $10$ minutes only when $T_1\lt5$. Then, starting from time $T_1$, the Poisson process begins anew hence the conditional probability of interest, namely, $P(T_2\lt T_1+5\mid T_1)$ is simply $P(T\lt5)$ where $T$ is distributed like $T_1$. Thus, a crash happens with probability $$ P(T_1\lt5)^2. $$ Comment: Is it meant to be $$P(T_1 \leq 10)$$ or $$P(T_1 < 10)$$ be suffice? Comment: Irrelevant, since $P(T_1\leqslant t)=P(T_1\lt t)$ for every $t$.<|endoftext|>calcular diferença entre duas datas em meses no R Question: Como calculo a diferença entre duas datas em meses no R? Suponha as duas datas: <code>x <- as.Date("2014-01-07") y <- as.Date("2015-03-17") </code> Consigo facilmente calcular em segundos, minutos, horas, etc usando a função <code>difftime</code>. Mas ela não aceita meses :( Com as seguintes funções consegui calcular, mas elas não devolvem frações de meses, como a <code>difftime</code>. <code>monthdiff <- function(x, y){ x <- c(str_sub(x, 1, 4), str_sub(x, 5)) y <- c(str_sub(y, 1, 4), str_sub(y, 5)) 12*(x[1]-y[1]) + (x[2] - y[2]) } criar_anomes <- function(x){ sprintf("%4d%02d", year(x), month(x)) } </code> Assim obtenho: <code>library(lubridate) monthdiff(criar_anomes(y), criar_anomes(x)) [1] 14 </code> Além de um jeito que retornasse a fração (Neste caso deveria ser algo com 14,33 acho) dos meses, gostaria de uma forma mais elegante do que essa. Comment: Mas como você quer definir a fração de um mês? Pergunto porque cada mês tem uma quantidade de dias diferente. Comment: Não tinha pensado nisso! Acho que dividir por 31 é ok Answer: Primeiro, sem tratar fração do mês, existem algumas alternativas para pegar diferenças entre o mês do calendário. Exemplos: <code>x <- as.Date("2014-01-07") y <- as.Date("2015-03-17") # criando uma sequência length(seq(x, y, by = "months")) - 1 [1] 14 # usando o zoo library(zoo) (as.yearmon(y) - as.yearmon(x)) * 12 [1] 14 </code> Vale a pena frisar que isso é uma diferença do mês do calendário pois uma diferença entre 31 de janeiro e 01 de fevereiro, por essa definição, é de um mês. A parte da fração do mês é mais complicada pois depende da forma que você definir a fração de um mês. Se você definir de uma forma simples, como a cada 30 dias ou 31 dias ou a cada 4 ou 5 semanas, aí bastaria usar o próprio <code>difftime</code> e dividir o resultado pelo número correspondente: <code>as.numeric(difftime(y, x, units = "days"))/30 [1] 14.46667 as.numeric(difftime(y, x, units = "days"))/31 [1] 14 </code> Comment: Acho que em um primeiro momento não é necessário converter para numeric. Sem a conversão é possível fazer a maioria das operações, e mantém-se a opção de ser mudar a unidade facilmente. Answer: Eu encontrei o pacote <code>mondate</code> para fazer isso: <code>> library(mondate) > t2 = as.mondate('2015-03-17') > t1 = as.mondate('2014-01-07') > t2 - t1 Time difference of 14.32 months > </code> Comment: ótima resposta!
[{"idx": "What's_the_easiest_way_to_fetch_a_SharePoint_file_by_a_path_from_the_Microsoft_Graph?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-16975.jsonl"}, {"idx": "Dominant_7_alt_vs_tritone_sub", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-16975.jsonl"}, {"idx": "\u041d\u0435_\u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442_\u0440\u0435\u0433\u0443\u043b\u044f\u0440\u043a\u0430_\u0432_PHP_\u0432_\u043c\u043d\u043e\u0433\u043e\u0441\u0442\u0440\u043e\u0447\u043d\u043e\u043c_\u0440\u0435\u0436\u0438\u043c\u0435", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-16975.jsonl"}, {"idx": "Poisson_process_breakdown(waiting_times)", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-16975.jsonl"}, {"idx": "calcular_diferen\u00e7a_entre_duas_datas_em_meses_no_R", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-16975.jsonl"}]
### Here's set of multiplication, addition, division, subtraction math exercises: 505 + 1924 = 2429 ### 1279 + 735 = 2014 ### 1813 - 754 = 1059 ### 72 - 62 =\n#### Alright, ready to do some subtraction? We're taking 72 and subtracting 62 from it. Step 1: We'll start by subtracting the digit 2 and the borrow 0 from 2 in column 1 and get 0. 0 is the first digit of our result. Step 2: We'll start by subtracting the digit 6 and the borrow 0 from 7 in column 2 and get 1. 1 is the next digit of our result. So, 72 - 62 = 10. ### 1460 - 642 = 818 ### 1745 + 1370 = 3115 ### 6 - -4 = 10 ### 1521 * 1157 = 1759797 ### 803 * 2026 = 1626878 ### 1922 * 442 = 849524 ### 781 * 452 = 353012 ### 1776 - 598 = 1178 ### 1111 - 680 = 431 ### 668 + 1470 = 2138 ### 1659 - 48 = 1611 ### 1072 / 463 = 2.32 ### 536 * 1728 = 926208 ### 1967 + 390 = 2357 ### 2140 - 391 = 1749 ### 183 - -5 = 188 ### 1519 - 1632 = -113 ### 1211 / -220 = -5.5 ### 756 + 1951 = 2707 ### 1788 - 1031 = 757 ### 789 * 1081 = 852909 ### 1829 + 2206 = 4035 ### 1081 - 368 = 713 ### 1192 * 544 = 648448 ### 819 - 1910 = -1091 ### 489 + 1160 = 1649 ### 882 * 569 = 501858 ### 957 * -92 = -88044 ### 1089 + 730 = 1819 ### 1003 - 1553 = -550 ### 1283 - 1551 = -268 ### 575 - 2154 = -1579 ### 999 / 621 = 1.61 ### 1771 + 709 = 2480 ### 1608 - 1078 = 530 ### 1138 + 117 = 1255 ### 1306 / -714 = -1.83 ### 180 - 1822 = -1642<|endoftext|>### Here is some exercises for division, subtraction, addition, multiplication math guide: -642 / -766 = 0.84 ### 65 + 1718 = 1783 ### -707 / 580 = -1.22 ### 685 + 1724 = 2409 ### 1322 - 1194 = 128 ### -507 / -615 = 0.82 ### 1064 - 1728 = -664 ### 1267 * 1693 = 2145031 ### 1726 - 637 = 1089 ### 789 * 1614 = 1273446 ### 1074 + 1132 = 2206 ### -67 + 662 = 595 ### 480 / -857 = -0.56 ### 1556 + 2068 = 3624 ### 1104 - 2088 = -984 ### 2022 - 939 = 1083 ### 1659 * 163 = 270417 ### 1605 + 502 = 2107 ### -31 * 1823 = -56513 ### 1029 / 310 = 3.32 ### -874 / 955 = -0.92 ### -174 / -390 = 0.45 ### Sofia works as a sales clerk. She is paid a salary of $3251 a week plus 9.755742870150714% commission on sales over $4000. Find her gross pay for a week in which her sales are $9521. Step-by-Step Solution: 1. Calculate the commission for sales over $4000. Commission = ($9,521 - $4,000) x 0.09755742870150715 = $538.61 2. Calculate gross pay by adding salary and commission. Gross Pay = $3,251 + $538.61 = $3,789.61 ### 742 * 1026 = 761292 ### 673 + 0 = 673 ### 613 - 811 = -198 ### 1451 - 832 = 619 ### 1886 - 2317 = -431 ### 1916 * 1725 = 3305100 ### 758 / 1303 = 0.58 ### 1266 - 1655 = -389 ### 2236 - 97 = 2139 ### 1876 + 321 = 2197 ### 1386 - 258 = 1128 ### 2122 * 1422 = 3017484 ### 88 + 1063 = 1151 ### 1093 / -672 = -1.63 ### 1715 - 147 = 1568 ### 1935 + 2035 = 3970 ### 1013 / -848 = -1.19<|endoftext|>### Think deeply about this set of addition, subtraction, division, multiplication math examples: 2097 - 550 = 1547 ### 990 / 520 = 1.9 ### 804 + 1935 = 2739 ### -445 / -661 = 0.67 ### 1990 * 62 = 123380 ### 1289 / -623 = -2.07 ### 1465 - 1419 = 46 ### 1234 / 1023 = 1.21 ### 1428 - 494 = 934 ### 1624 * 687 = 1115688 ### 291 + 1745 = 2036 ### 1783 * 1478 = 2635274 ### 695 / 279 = 2.49 ### 1354 + 1331 = 2685 ### 485 + 1547 = 2032 ### 995 + 1191 = 2186 ### 1443 - 228 = 1215 ### 152 + 451 = 603 ### 1987 * 172 = 341764 ### 1103 + 1885 = 2988 ### 644 - 285 = 359 ### 14 * 201 = 2814 ### 1315 * 1987 = 2612905 ### 104 / 244 = 0.43 ### 1097 + 1982 = 3079 ### 344 + -54 = 290 ### 2003 - 76 = 1927 ### 2093 + 990 = 3083 ### 384 + 1326 = 1710 ### 1097 - 884 = 213 ### Linear function: Y-intercept: 8.8969 x_start: -825 x_end: -293 step_size: 31 Value table: x | y ---------------------- Calculating y for x = -825 y = y_intercept + slope * x y = 8.8969 + 1.655 * -825 Intermediate Step: 1.655 * -825 = -1365.3726 Final Step: 8.8969 + -1365.3726 = -1356.4757 -------------------------------------------------- -825 | -1356.4757 Calculating y for x = -794 y = y_intercept + slope * x y = 8.8969 + 1.655 * -794 Intermediate Step: 1.655 * -794 = -1314.0677 Final Step: 8.8969 + -1314.0677 = -1305.1708 -------------------------------------------------- -794 | -1305.1708 Calculating y for x = -763 y = y_intercept + slope * x y = 8.8969 + 1.655 * -763 Intermediate Step: 1.655 * -763 = -1262.7628 Final Step: 8.8969 + -1262.7628 = -1253.8659 -------------------------------------------------- -763 | -1253.8659 Calculating y for x = -732 y = y_intercept + slope * x y = 8.8969 + 1.655 * -732 Intermediate Step: 1.655 * -732 = -1211.4579 Final Step: 8.8969 + -1211.4579 = -1202.561 -------------------------------------------------- -732 | -1202.561 Calculating y for x = -701 y = y_intercept + slope * x y = 8.8969 + 1.655 * -701 Intermediate Step: 1.655 * -701 = -1160.153 Final Step: 8.8969 + -1160.153 = -1151.2561 -------------------------------------------------- -701 | -1151.2561 Calculating y for x = -670 y = y_intercept + slope * x y = 8.8969 + 1.655 * -670 Intermediate Step: 1.655 * -670 = -1108.8481 Final Step: 8.8969 + -1108.8481 = -1099.9512 -------------------------------------------------- -670 | -1099.9512 Calculating y for x = -639 y = y_intercept + slope * x y = 8.8969 + 1.655 * -639 Intermediate Step: 1.655 * -639 = -1057.5432 Final Step: 8.8969 + -1057.5432 = -1048.6463 -------------------------------------------------- -639 | -1048.6463 Calculating y for x = -608 y = y_intercept + slope * x y = 8.8969 + 1.655 * -608 Intermediate Step: 1.655 * -608 = -1006.2382 Final Step: 8.8969 + -1006.2382 = -997.3414 -------------------------------------------------- -608 | -997.3414 Calculating y for x = -577 y = y_intercept + slope * x y = 8.8969 + 1.655 * -577 Intermediate Step: 1.655 * -577 = -954.9333 Final Step: 8.8969 + -954.9333 = -946.0365 -------------------------------------------------- -577 | -946.0365 Calculating y for x = -546 y = y_intercept + slope * x y = 8.8969 + 1.655 * -546 Intermediate Step: 1.655 * -546 = -903.6284 Final Step: 8.8969 + -903.6284 = -894.7315 -------------------------------------------------- -546 | -894.7315 Calculating y for x = -515 y = y_intercept + slope * x y = 8.8969 + 1.655 * -515 Intermediate Step: 1.655 * -515 = -852.3235 Final Step: 8.8969 + -852.3235 = -843.4266 -------------------------------------------------- -515 | -843.4266 Calculating y for x = -484 y = y_intercept + slope * x y = 8.8969 + 1.655 * -484 Intermediate Step: 1.655 * -484 = -801.0186 Final Step: 8.8969 + -801.0186 = -792.1217 -------------------------------------------------- -484 | -792.1217 Calculating y for x = -453 y = y_intercept + slope * x y = 8.8969 + 1.655 * -453 Intermediate Step: 1.655 * -453 = -749.7137 Final Step: 8.8969 + -749.7137 = -740.8168 -------------------------------------------------- -453 | -740.8168 Calculating y for x = -422 y = y_intercept + slope * x y = 8.8969 + 1.655 * -422 Intermediate Step: 1.655 * -422 = -698.4088 Final Step: 8.8969 + -698.4088 = -689.5119 -------------------------------------------------- -422 | -689.5119 Calculating y for x = -391 y = y_intercept + slope * x y = 8.8969 + 1.655 * -391 Intermediate Step: 1.655 * -391 = -647.1039 Final Step: 8.8969 + -647.1039 = -638.207 -------------------------------------------------- -391 | -638.207 Calculating y for x = -360 y = y_intercept + slope * x y = 8.8969 + 1.655 * -360 Intermediate Step: 1.655 * -360 = -595.799 Final Step: 8.8969 + -595.799 = -586.9021 -------------------------------------------------- -360 | -586.9021 Calculating y for x = -329 y = y_intercept + slope * x y = 8.8969 + 1.655 * -329 Intermediate Step: 1.655 * -329 = -544.494 Final Step: 8.8969 + -544.494 = -535.5972 -------------------------------------------------- -329 | -535.5972 Calculating y for x = -298 y = y_intercept + slope * x y = 8.8969 + 1.655 * -298 Intermediate Step: 1.655 * -298 = -493.1891 Final Step: 8.8969 + -493.1891 = -484.2923 -------------------------------------------------- -298 | -484.2923<|endoftext|>### Study this set of division, multiplication, subtraction, addition math examples: 1047 + 1560 = 2607 ### 1601 * 90 = 144090 ### 776 + 625 = 1401 ### 2051 - 2259 = -208 ### 55 + 1889 = 1944 ### 1845 - 804 = 1041 ### 18 + 176 = 194 ### -903 / 883 = -1.02 ### 2162 - 1773 = 389 ### 2091 * 1579 = 3301689 ### 271 * 1962 = 531702 ### 1237 * 822 = 1016814 ### 1655 + 228 = 1883 ### 1435 + 226 = 1661 ### -421 / 388 = -1.09 ### 1599 + 1500 = 3099 ### 670 - 1794 = -1124 ### 2171 * 460 = 998660 ### 574 + 1887 = 2461 ### 10 + 1186 = 1196 ### 2161 * 121 = 261481 ### 1515 - 352 = 1163 ### 357 + 91 = 448 ### 161 - 1230 = -1069 ### 1194 * 1465 = 1749210 ### 2244 + 2068 = 4312 ### 1800 * 2263 = 4073400 ### 1430 + 71 = 1501 ### 1243 * 1365 = 1696695 ### 1315 / -190 = -6.92 ### 1154 + 418 = 1572 ### -424 / -667 = 0.64 ### 1304 - 51 = 1253 ### 1965 * 1372 = 2695980 ### 716 * 502 = 359432 ### 544 * 2203 = 1198432 ### -757 / 1064 = -0.71 ### In Mia's family, there are 3 adults and 3 children. In a cookie jar, there are a total of 544 cookies. If the adults eat 1/3 of the cookies and then gives the rest to the children to divide equally, how many cookies does each child get? Solution: The adults ate 1/3*544 = 181.33 cookies. The remaining number of cookies is 544-181.33 = 362.66999999999996 cookies. If the children divided the cookies equally, each child got 362.66999999999996/3 = 121 cookies. ### 673 + 229 = 902
[{"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}]
polynomials: expand ------------------- Conundrum: Expand (-j - 2 + 2)*(5 - 1 + 0)*(-4*j + 4*j + 2*j)*(-7*j + j + 14*j). Steps: -64*j**3 Conundrum: Expand (-4 + 2 - 2)*(-6001*p**4 + 4*p**2 + 12536*p**4 - 17*p**2 - 6329*p**4). Steps: -824*p**4 + 52*p**2 Conundrum: Expand (-12*o**2 + 13*o**2 - 16*o**2)*(5*o + 3*o - 4*o) + (-o**2 + 2*o**2 + 0*o**2)*(o + 0 + 0) - o**3 + 0*o**3 + 2*o**3 - 2*o**2 + 2*o**2 - 3*o**3. Steps: -61*o**3 Conundrum: Expand (o + 0*o - 2*o)*(o**2 - o**2 + o**2)*(-4 - 3*o + 4*o + 5). Steps: -o**4 - o**3 Conundrum: Expand (-28*o + 37*o + 25*o)*(-156*o**2 - 16*o**3 + 156*o**2). Steps: -544*o**4 Conundrum: Expand 5*n - 5*n + 3*n**3 - 3 + n**3 + 0*n**3 + 1 + (-3*n**2 + 2*n**2 - n**2)*(5*n - 5*n - n). Steps: 6*n**3 - 2 Conundrum: Expand ((-2*w**4 - w + w)*(3 - 3 - 2) - 3*w**4 + 3*w**4 - 3*w**4)*(5*w - 10*w + 13*w)*(3 + 1 - 2) - 4*w**4 + 4*w**4 + 2*w**5. Steps: 18*w**5 Conundrum: Expand (-4*w**2 + 27*w - 27*w)*(0*w + 3*w**3 + 0*w) - 2*w**2 + w**5 + 2*w**2. Steps: -11*w**5 Conundrum: Expand 12 - 177*m**2 - 13 + 10 - 11 + (6*m + 0*m - 4*m)*(2*m + 0*m + 0*m). Steps: -173*m**2 - 2 Conundrum: Expand (-32*b + 72*b - 38*b + 40)*(0*b - b - b)*(1 + 2 - 1). Steps: -8*b**2 - 160*b Conundrum: Expand 0*x**2 - 4*x**2 + x**2 + (-3*x + x**2 + 3*x)*(7 - 4 + 6) + 2*x**2 - 2*x + 2*x + (4*x**2 + x**2 - 3*x**2)*(7 + 20 - 7). Steps: 48*x**2 Conundrum: Expand (-3 + 0 + 2)*(0*k**2 + 2*k**2 + 0*k**2) + (6*k - 15 + 15)*(2*k + 0 + 0). Steps: 10*k**2 Conundrum: Expand (-o + o + o)*(9*o - 15*o - 20*o)*(52 - 176 - 31). Steps: 4030*o**2 Conundrum: Expand (0*y**3 - y**3 - 2*y**3)*(-2 - 9*y + 2) + 112*y - 112*y - 114*y**4. Steps: -87*y**4 Conundrum: Expand -2*j**4 - 2 + 2 + (-5*j**2 + 3*j**2 + 10*j**2)*(12*j**2 - 10*j**2 + 15*j**2). Steps: 134*j**4 Conundrum: Expand (689*o**3 + 1202*o**3 - 123*o**3)*(-3 - 3*o**2 + 3). Steps: -5304*o**5 Conundrum: Expand (-q + 2*q + 0*q)*(1 - 3 + 3)*(4 + 4 - 2)*(-2*q + 2*q + 2*q). Steps: 12*q**2 Conundrum: Expand (1 + 1 - 7)*(4*g - 3*g - 2*g)*(525*g**2 - 20402 + 20402). Steps: 2625*g**3 Conundrum: Expand (1 - 1 + 2)*((-m - 4*m + 6*m)*(3 + 0 + 1) - 2 + m + 2)*(-3 + 0 + 1). Steps: -20*m Conundrum: Expand 2*k - 3*k + 0*k + (-70*k - 3 + 105*k + 64*k)*(-4 - 2 + 3). Steps: -298*k + 9 Conundrum: Expand (-q**3 + 3*q**3 + 2*q**3)*(3*q**2 - 3*q**2 - q**2) + 10*q**5 + 5*q**5 - q**5 + (-q**4 + 2*q**4 - 3*q**4)*(-2*q + 2*q - q). Steps: 12*q**5 Conundrum: Expand (2 + 4 - 4)*((3*n - 4*n + 0*n)*(0 - 2 + 3) + (-3*n - 21*n - 2*n)*(1 + 1 - 3) + 2*n + 3 - 3). Steps: 54*n Conundrum: Expand (-3*t**2 - 2*t**4 + 3*t**2)*(-7*t - 8*t - 6*t). Steps: 42*t**5 Conundrum: Expand (11*y**4 + 8*y**4 - 9*y**4)*(5 + 2 - 6)*((4 - 5 - 1)*(-1 + 3 - 1) + 6 - 3 - 1 - 258 + 80 - 446). Steps: -6240*y**4 Conundrum: Expand (-2*f - f**2 + 2*f)*(-2*f - 2 + 2 + (3*f - 3*f - 2*f)*(-1 - 1 - 1) + f - f + 2*f). Steps: -6*f**3 Conundrum: Expand (2*z - z - 2*z)*(3 - 2 + 0) - 7224 + 1582*z + 3610 + 3614. Steps: 1581*z Conundrum: Expand (-2*f**2 + 0 + 0)*(131272*f - 2037*f**2 - 131272*f). Steps: 4074*f**4 Conundrum: Expand (2*c + c**3 + 2 - 2)*(3 + 2 + 1) + (0*c**2 - 5*c**2 + 3*c**2)*(0 - 3 + 0)*(-63*c + 23*c + 25*c). Steps: -84*c**3 + 12*c Conundrum: Expand (u**3 + 24*u**2 + 26*u - 24*u**2)*(-2*u**2 + 242*u - 242*u - 1). Steps: -2*u**5 - 53*u**3 - 26*u Conundrum: Expand o - 3*o - o + (2 - 5 + 1)*(-o + 3*o - 4*o) + 17*o + 43*o + 5*o. Steps: 66*o Conundrum: Expand (-3 + 8 + 19)*(-2*k + 0*k + 0*k). Steps: -48*k Conundrum: Expand (2*k**2 - k**2 - 2*k**2)*(2*k + k - 4*k). Steps: k**3 Conundrum: Expand (5*p**3 - 5*p**3 - 21*p**3)*(60 + 33 + 64) - 3*p + 3*p - p**3. Steps: -3298*p**3 Conundrum: Expand 67 - 67 + 12*i**5 + (-5 + 5 + 1)*(2*i**5 - i**5 + 0*i**5) + 2*i**5 - 4*i**5 + 4*i**5. Steps: 15*i**5 Conundrum: Expand (365*u + 77*u + 5135*u)*(0 - 1 + 4 + 2 + 2 - 3 + (-3 - 2 + 4)*(-1 + 0 + 3))*(2 - 3 - 1 + (0 - 5 + 3)*(3 - 5 + 1) + 4 - 2 - 3). Steps: -11154*u Conundrum: Expand (v**3 + 0*v**3 + 0*v**3)*(-3*v - v + 5*v)*(-2 + 2 - v). Steps: -v**5 Conundrum: Expand (2 - 2 - 2*f)*(-3 + 3 + 2) + ((6 - 4 + 0)*(2 - 4 + 1) - 3 + 2 - 1 + 2 - 4 - 1 - 2 + 1 + 2)*(-3*f + 3*f + 8*f). Steps: -52*f Conundrum: Expand 17*j - 124 + 124 + 1 + 2*j - 1 - 5*j + 2*j + 2*j + (-4 + 6 - 4)*(-j - j + 0*j) - 4*j - 2*j - 6*j. Steps: 10*j Conundrum: Expand 2 + 2742*b - 2 - 1255*b + (0 + 3 - 4)*(-b + 1 - 1). Steps: 1488*b Conundrum: Expand (3*p + 3 - 3 + 0 + 0 - p - 4 + 4 + p + (6 - 3 - 1)*(p + p - 3*p))*((-2*p + 1 - 1)*(10*p + 7*p - 19*p) + 9*p**2 + 12*p**2 - 20*p**2 - 2 + 2 - 2*p**2). Steps: 3*p**3 Conundrum: Expand (-21 + 21 - 14*i)*(-i - 1 + 1) - 19 + 19 + 16*i**2 + (-i + i + 2*i)*(0*i - 3*i + i). Steps: 26*i**2 Conundrum: Expand j + j**5 + 7*j**5 - 16*j**5 + (6*j**4 - 14*j**2 + 14*j**2)*(j + 2*j - 5*j). Steps: -20*j**5 + j Conundrum: Expand (19 + 1 + 17)*(4*f**4 + 4*f**4 + 4*f**4). Steps: 444*f**4 Conundrum: Expand (-2*v + 0*v - 5*v)*(-3*v - v + 5*v + (0 + 0 - 1)*(2*v + v - v))*(70 - 24 + 54). Steps: 700*v**2 Conundrum: Expand (-51*u - 7*u + 32*u)*(-u - u + 3*u + (2 - 2 + 2*u)*(0 + 3 - 2)). Steps: -78*u**2 Conundrum: Expand (-6981 + 217*c + 13972 - 6987)*(-c**2 + 4*c**2 - 4*c**2) + 3*c**3 + c**3 - 2*c**3. Steps: -215*c**3 - 4*c**2 Conundrum: Expand (0*x + 2*x + 0*x)*(-3 + 2 - 1)*(-2 + 0 + 1). Steps: 4*x Conundrum: Expand (34*o**4 - 4*o**4 + 7*o**4)*(3 - 2 - 4)*(-9 + 9 - 3*o). Steps: 333*o**5 Conundrum: Expand (0*s - s + 3*s)*(-3*s + 2*s - 3*s + (-1 - 6 + 8)*(s + s + 0*s)). Steps: -4*s**2 Conundrum: Expand (-k - 10*k + 2*k)*(3*k**2 - 3*k**2 - 2*k**2) + k**3 - 3*k**3 + k**3 + 0*k**3 + 2*k**3 - k**3. Steps: 18*k**3 Conundrum: Expand (-4 - 4 + 4 + (-4 - 7 - 2)*(-3 + 0 + 5))*(3*s**4 - 3*s**4 - s**4 + (-2*s**4 - 2*s**4 + 5*s**4)*(-35 + 17 + 67)). Steps: -1440*s**4 Conundrum: Expand (-2 + 2 + 3*m)*(-6*m + 4*m**3 - 7*m - 2*m**3). Steps: 6*m**4 - 39*m**2 Conundrum: Expand (4 - i - 4)*(0*i**4 - 2*i**4 + 3*i**4) + 62*i**5 + 55*i**5 - 147*i**5 - 3*i**5 + 4*i**5 + i**5. Steps: -29*i**5 Conundrum: Expand -73*d**3 + 23*d**3 + 26*d**3 + 2*d**3 + 2*d**2 - 2*d**3 + 2*d**3 + 12*d**2 - 12*d**2 + 4*d**3 + (3*d**2 - 3*d**2 - 2*d**2)*(0*d + 0*d + 4*d). Steps: -26*d**3 + 2*d**2 Conundrum: Expand (-4*x - 3 - x + 2)*(464 - 1025 - 101 - 853 - 1020). Steps: 12675*x + 2535 Conundrum: Expand (-153 + 280 + 251)*(-g**2 + 0*g + 0*g) - 4 - g**2 + 2*g + 4. Steps: -379*g**2 + 2*g Conundrum: Expand (-5*y - y + 4*y)*(3 - 1 - 1) - 3 + 2 + 3 - 2*y. Steps: -4*y + 2 Conundrum: Expand ((a + 0*a + a)*(-1 + 6 - 3) - 1 + 1 + 2*a)*(3*a**2 + 29*a**2 - 10*a**2). Steps: 132*a**3 Conundrum: Expand (220 - 25 - 2*a + 107)*(2*a**4 - 2*a**4 - 2*a**4). Steps: 4*a**5 - 604*a**4 Conundrum: Expand 11*b**4 + 5*b - 3*b**4 - 3*b + 2*b**4 + 2*b**2 - 2*b**2 + (b - 4 + 4)*(-3*b**3 + 2*b**3 + 0*b**3) - 116*b + b**4 + 116*b. Steps: 10*b**4 + 2*b Conundrum: Expand (-56*f - 6*f - 15*f)*(2*f**2 - f**2 + f**2)*(2 - 8*f - 2). Steps: 1232*f**4 Conundrum: Expand (2 + 0 - 110)*(6 - 2 - 2)*(-4*l - 25*l + 6*l)*(-l + 0*l + 3*l). Steps: 9936*l**2 Conundrum: Expand (5*i - 3*i + 0*i)*(2 - 2 + 1)*(-3*i - 5*i - i)*(0*i + i**3 + 0*i). Steps: -18*i**5 Conundrum: Expand (c - 1 + 1)*(3 - 4 + 3)*(11*c - 25*c - 12*c)*(1 - 1 - 2 + (4 - 3 + 3)*(-3 - 1 + 5)). Steps: -104*c**2 Conundrum: Expand (-694 + 2227 - 1122)*(3*j**4 - 4*j**4 - j**4). Steps: -822*j**4 Conundrum: Expand (2 + 4 - 4)*(-2*x + 6773 - 7274 + x). Steps: -2*x - 1002 Conundrum: Expand 3*b - 2*b + 6*b + (0 + 0 - 1)*(-2*b - 2*b + b) + 4*b - 6*b + 4*b. Steps: 12*b Conundrum: Expand (7*i**5 - i**5 - 3*i**5)*(-12565 - 2329 + 8206 - 9945 - 22466). Steps: -117297*i**5 Conundrum: Expand (-x - 3*x**2 + x)*(2*x - x + 2*x) + 0 + 0*x**3 + 5 - 2*x**3 + (-6*x + 3*x + 0*x)*(40*x**2 + 3*x**2 + 7*x**2). Steps: -161*x**3 + 5 Conundrum: Expand -4*m**3 + 6*m**3 + 0*m**3 + (-2*m + 0*m + 3*m)*(-2*m**2 - 3*m**2 + 6*m**2) + 2 - 3*m**3 - 2 + (m + 2*m**2 - m)*(2 - 2 - m). Steps: -2*m**3 Conundrum: Expand 2*w**4 + 2*w**2 - 2*w**2 + (-3*w**3 + w**3 + 3*w**3)*(4 - 4 - w) + 6*w**4 + w**3 + 19 - 19. Steps: 7*w**4 + w**3 Conundrum: Expand -4*u**3 + 4*u**3 - u**4 + (4 - 3 - 3)*(-2*u + 4*u - u)*(2*u - 2*u - 3*u**3). Steps: 5*u**4 Conundrum: Expand (95*v + 7*v + 8*v)*(-42*v**2 + 378 - 378). Steps: -4620*v**3 Conundrum: Expand (0*k - 3*k + k + (2 + 2 - 3)*(-3*k + 6*k - 4*k) - 5*k + 0*k + 4*k)*(-307 + 132 + 1538). Steps: -5452*k Conundrum: Expand 2*j**5 + 2*j**5 - 6*j**5 + (-9*j - 7 + 3*j + 21)*(-9*j**4 + 0*j**3 + 0*j**3). Steps: 52*j**5 - 126*j**4 Conundrum: Expand (b + 1 - 1)*(-3 - 1 + 7) + 3 - 2*b - 3 - 4*b + 5*b + 0*b + ((-6 + 2 + 3)*(-1 + 0 + 2) + 52 - 18 - 22)*(3*b - 6*b + b). Steps: -20*b Conundrum: Expand (-5*u**2 - 2*u**2 + 4*u**2)*(65 + 110 - 65 - 3*u + 49 + 10*u). Steps: -21*u**3 - 477*u**2 Conundrum: Expand -6*n**2 + 3*n**2 + 2*n**2 - n**2 + n**2 + n**2 + (-3 + 3 - 2*n)*(3*n - 6*n - 3*n). Steps: 12*n**2 Conundrum: Expand (2 + 1 - 5)*(-4128*z**2 + 4128*z**2 + 1 - 1 - 88125*z**3 - 16461*z**3). Steps: 209172*z**3 Conundrum: Expand -3*s**3 + 2*s**3 + 0*s**3 + (-31 - 4007*s - 430 + 461)*(0*s + 0*s + s**2). Steps: -4008*s**3 Conundrum: Expand 0*u**4 + 0*u**4 + 2*u**5 + (2*u**3 + 2*u**3 - u**3 + (2*u + 4 - 4)*(-3 + 2*u**2 + 3))*(2*u - 2*u - 2*u**2). Steps: -12*u**5 Conundrum: Expand (-l - 5*l - l)*(2*l - 5*l - l) - 3*l**2 + 5*l**2 + 0*l**2. Steps: 30*l**2 Conundrum: Expand -7*c - 28*c + 7*c + (-2 - 1 + 5)*(-2*c - 4 + 4). Steps: -32*c Conundrum: Expand (-2 + 2 + 1)*(3*u**3 + u**3 - 5*u**3 + (-3*u + 2*u - u)*(4*u**2 - 3*u**2 + 3*u**2) - 2*u**3 + 5*u**3 - 2*u**3). Steps: -8*u**3 Conundrum: Expand (12135 + 11826 - 3779)*(-2*f**5 + 3*f**5 - 2*f**5). Steps: -20182*f**5 Conundrum: Expand (q**3 + 2*q**2 + 2*q**3 - 2*q**3)*((-1 + 4 + 1)*(4 - 1 - 1) - 6 - 9 - 8). Steps: -15*q**3 - 30*q**2 Conundrum: Expand (2*a**4 - a**4 - 5*a**4)*(6*a - 3*a + 0*a)*(-4 + 2 - 1). Steps: 36*a**5 Conundrum: Expand -4*t + 5*t - 2*t + (5 + 0 - 3)*(-90*t + 196*t + 537*t) + (5 - 4 + 0)*(0*t - 3*t + 2*t). Steps: 1284*t Conundrum: Expand (-33153583*o + 33153583*o - 3377*o**4)*(-3 + 3 + 2). Steps: -6754*o**4 Conundrum: Expand (2280 - 2280 - 32*r)*(0*r - 3*r + 5*r + 1). Steps: -64*r**2 - 32*r Conundrum: Expand (18 - 142 - 43)*(n**2 - 2*n**2 - 9*n + 15*n). Steps: 167*n**2 - 1002*n Conundrum: Expand (-7 - 4*c + 7)*(-4*c + 5*c - 1 + 3). Steps: -4*c**2 - 8*c Conundrum: Expand 5*f**3 - 6*f**3 - 7*f**3 + (f - 3*f + 4*f)*(-f - f**2 + f) + 3*f**3 - 2*f**3 - 4*f**3 + (3 - 4 - 1)*(1 - f**3 - 1) + 1 - 1 - 2*f**3. Steps: -13*f**3 Conundrum: Expand (49*d + 9 - 4 - 5)*(-3 + 3 + 5*d**2). Steps: 245*d**3 Conundrum: Expand (-10 + 15 + 8)*(7*j**2 + 5*j**2 + 11*j**2). Steps: 299*j**2 Conundrum: Expand (3*p + p - 2*p)*(-2*p**3 - 57*p + 161*p - 16*p**4 - 100*p). Steps: -32*p**5 - 4*p**4 + 8*p**2 Conundrum: Expand (5*c - 116 - 26*c + 94)*(-1 - 3 + 3). Steps: 21*c + 22 Conundrum: Expand (-50*w**2 + 88*w**2 + 170*w**2)*(-2*w - w + w). Steps: -416*w**3 Conundrum: Expand (11 + 17 - 36)*(0*m**3 + 0*m**3 + 2*m**3). Steps: -16*m**3 Conundrum: Expand (3*d**2 + 0*d**2 - 2*d**2)*(4*d - 6*d - 11*d + (-1 - 1 + 4)*(15*d + 14*d - 27*d) - 2*d + 3*d + 2*d). Steps: -6*d**3 Conundrum: Expand j**4 - j**3 + 4*j**3 + 5*j**3 + (-508*j**2 - 1141*j**2 + 437*j**2)*(-j - 2*j**2 + j). Steps: 2425*j**4 + 8*j**3 Conundrum: Expand (-16*d**3 - 6*d**3 + 3*d**3)*(-d + 0*d + 0*d) + d**3 + 2*d**4 - d**3 + (-3*d**2 - 1 + 1)*(-5*d**2 + 2*d**2 + 2*d**2). Steps: 24*d**4 Conundrum: Expand (-2 + 11*n + 2 - 119*n)*(-n - 2 + 2). Steps: 108*n**2 Conundrum: Expand (0*d - 3*d + 2*d)*(4 - 2 + 2). Steps: -4*d Conundrum: Expand (-4*v**2 + 0*v**2 + 3*v**2 + (2*v - 2*v + 2*v)*(-10*v + 9*v + 2*v))*(19 - 14*v - 19). Steps: -14*v**3 Conundrum: Expand (2*s + 0 + 0)*(-5693*s - 5695*s - 10 + 11380*s). Steps: -16*s**2 - 20*s Conundrum: Expand 15*j**3 - 24*j**3 - 77*j**3 + (j**2 - 2*j**2 - j**2)*(0*j + j - 2*j). Steps: -84*j**3 Conundrum: Expand (-5*w + 5*w - 8*w**3 + (-w - w + 4*w)*(0*w**2 - 5*w**2 + 3*w**2) + 2*w**3 + 3*w**3 - 7*w**3)*(w - w + 2*w**2) - 3*w**3 - 3*w**5 + 3*w**3. Steps: -31*w**5 Conundrum: Expand -77643*q**3 - 351*q**4 + 77643*q**3 + (q**3 + q**3 + 0*q**3)*(-2*q + 0*q + q) - q**4 - 3 + 3 - q**2 + q**2 - 2*q**4. Steps: -356*q**4 Conundrum: Expand (-3 + 0 + 1)*(0*g**3 + 2*g**4 + 0*g**3) - g + g + 2*g**4 - 120*g**4 + 387*g**4 + 73*g**4 + 257*g**4. Steps: 595*g**4 Conundrum: Expand -8*g**5 - 9*g**4 + 9*g**4 + (-1 - 10 + 5)*(3*g**5 - 2*g**5 - 3*g**5) + 4*g**5 + 3*g**5 - 5*g**5. Steps: 6*g**5 Conundrum: Expand (5*b + 2*b - 5*b)*(-2 + 3*b**2 + 2) + 26*b**3 + 232*b**3 + 27*b**3. Steps: 291*b**3 Conundrum: Expand (-d - 2 + 2)*(-6*d**3 + 4*d**3 - 4*d**3) - 1 - d**4 + 1. Steps: 5*d**4 Conundrum: Expand (-2*w + 2*w + 4*w)*(w**2 - w**2 - 2*w**3) + (w**2 - w**2 - w**2)*(w**2 + 2*w**2 - 6*w**2). Steps: -5*w**4 Conundrum: Expand 3*v**4 + 10*v**4 - 5*v**4 + (4*v**4 - 3*v**4 + v**4)*(-2 + 8 + 29). Steps: 78*v**4 Conundrum: Expand (-4*a + 3*a + 13*a)*(18*a - 27 - 16*a + 175) + 2 + 3*a - 3*a - a**2. Steps: 23*a**2 + 1776*a + 2 Conundrum: Expand (-34 - 45 + 14)*(-2 - 3*d + 2) - 39 + 15*d + 39 + 2*d - 2*d - 2*d. Steps: 208*d Conundrum: Expand 44 - 44 - 5*t + (847*t - 364*t + 860*t)*(1 - 4 + 1). Steps: -2691*t Conundrum: Expand -1 + 0 + 0*l + 2*l + 0*l + 0*l - l + (11 - 3 - 1)*(3*l - 6*l + l) + l + 5*l - 5*l + (-2 + 1 + 2)*(2*l + l - 2*l) + 4*l + 0*l - 2*l. Steps: -9*l - 1 Conundrum: Expand (-34*y + 38*y - 5 + 2)*(20 - 112 - 47 - 248). Steps: -1548*y + 1161 Conundrum: Expand (3 + 0 - q - 1)*(-242 + 242 - 257*q) + (-4*q + 2*q + 4*q)*(q - 2*q + 0*q) - 2*q + 2*q + q**2 + 4*q**2 - q**2 - 4*q**2. Steps: 255*q**2 - 514*q Conundrum: Expand ((-99*g + 28*g + 38*g)*(0*g - g - g) + g**2 + g**2 - 3*g**2 - 3 - g**2 + 3)*(-2*g - 2*g - 4*g). Steps: -512*g**3 Conundrum: Expand (0 + 3 + 0)*(16*v + 16*v - 6*v). Steps: 78*v Conundrum: Expand (-9*h + 2*h + 2*h)*(3 - 3 - 1) - 4*h + h + 2*h + (h - 3*h + 0*h)*(0 + 0 - 2) + h - 6*h + 3*h + 2*h + 4*h - 5*h. Steps: 7*h Conundrum: Expand ((-88*p + 46*p + 35*p)*(98 - 10 + 14) + (2*p - 3*p + 2*p)*(-1 - 1 + 1))*(1 - 1 + 1). Steps: -715*p Conundrum: Expand (0 - 1 + 0)*(-27 - 21*y - 7*y + 0 + 52). Steps: 28*y - 25 Conundrum: Expand (3 - 1 - 4)*(-20684605 + 20684605 + 4280*q**2 + 3983*q**2). Steps: -16526*q**2 Conundrum: Expand (0*j - j + 3*j)*(15 - 30 - 11)*(1 + 1 + 0 + 0 + 2 - 1 + (-2 - 4 + 5)*(1 + 1 - 1) - 3 + 0 + 5). Steps: -208*j Conundrum: Expand (-782*c - 122359 + 122359)*((-4*c + 2*c**2 + 4*c)*(3 + 1 - 2) - 10*c - c**2 + 10*c). Steps: -2346*c**3 Conundrum: Expand ((-v - 3*v + 5*v)*(-3 + 0 + 1) + v - v - v - v + 4*v + 3*v)*(248713*v**3 - 3*v + v - 235641*v**3 + 2*v). Steps: 39216*v**4 Conundrum: Expand -g - g + g + (-96*g - 438 + 438 + (5*g + g - 5*g)*(0 - 1 - 1))*(1 + 2 + 0). Steps: -295*g Conundrum: Expand (-317 + 317 - 4*p)*(-1 + 1 + p). Steps: -4*p**2 Conundrum: Expand (-o + 2*o**2 + o)*(0 + 3*o**2 + 0) + (2*o**2 + 1 - 1)*(2*o**2 - 3*o**2 + 2*o**2) - 6*o**4 + 0*o**4 + o**4. Steps: 3*o**4 Conundrum: Expand (-3 + 1 + 4)*(3*o**2 - 5*o**2 + o**2) + (2*o - 2*o - 2*o)*(0*o - 2*o + 4*o) + (2*o - 1 + 1)*(o + 0*o - 2*o) - 3*o**2 + o**2 + o**2. Steps: -9*o**2 Conundrum: Expand (3*p + 0*p - p)*(-p - 1 + 1) + 3*p**2 + p**2 - 3*p**2 + 23 - p**2 - 22 - p**2 + (1 + 2*p - 1)*(-p + p - 2*p). Steps: -7*p**2 + 1 Conundrum: Expand (-3*c + 3*c - c)*(4*c + 2*c**3 - 4*c) - 4*c**4 - 2*c**4 - 2*c**4 - 2*c**4 - 3*c**4 + 2*c**4. Steps: -13*c**4 Conundrum: Expand 2*p**2 + 0 + 0 + 4*p**2 + 3*p**2 - 4*p**2 + (-3*p - 3*p + 4*p)*(-2 + 2*p + 2) - 22*p + 22*p + 8 + p**2. Steps: 2*p**2 + 8 Conundrum: Expand -2*p + 2*p - 6*p - 249 + 249 - 84*p + 3*p - 6*p + p + (1 - 3 + 0)*(-3*p + 4*p - 3*p) + 0*p + 4*p - 6*p - 2 + 2 - p - 2*p + p + 0*p - p + 2*p + 0*p. Steps: -91*p Conundrum: Expand (35 - 171 - 185)*(5 - 3 - 4)*(-6*w**3 + 2*w**3 + 2*w**3). Steps: -1284*w**3 Conundrum: Expand (9 - 3 - 24)*(17 - 16 + 4*r - 3*r). Steps: -18*r - 18 Conundrum: Expand (3*v - 3*v + 2*v**3)*(4*v**2 - 3*v**2 + v**2) - 3*v**5 + 2*v**5 + 3*v**5 + 4*v**5 - 10*v**5 + 3*v**5 + (v - 2*v - v)*(-2*v**4 - 3*v**4 + v**4). Steps: 11*v**5 Conundrum: Expand (-r - 3 + 3)*(-2 + 2 - r**2) + (-4 + 4*r + 4)*(2 - r**2 - 2). Steps: -3*r**3 Conundrum: Expand (909 - 907 - 82*b + 27*b)*(0*b - b - b). Steps: 110*b**2 - 4*b Conundrum: Expand (2*v + 6*v**2 - 2*v)*(-v + v + v**3) + v + 4*v**5 + 1617*v**2 - 1643*v**2 - 2*v**5 + v**3. Steps: 8*v**5 + v**3 - 26*v**2 + v Conundrum: Expand (-195 + 195 - 26*h**2)*(-h**2 - 2*h**3 + 0*h**2 + 3 - 4). Steps: 52*h**5 + 26*h**4 + 26*h**2 Conundrum: Expand (-2*h - 4 + 4)*(-3*h**2 + 4*h**2 - 2*h**2) + h**3 + 0*h**3 + 0*h**3 - 2*h - 6*h**3 + 2*h. Steps: -3*h**3 Conundrum: Expand (-3*t - 3*t + 5*t)*(24*t - 131*t - 40*t). Steps: 147*t**2 Conundrum: Expand (-4 + 1 + 2)*(2 - 2 + 1)*(-4*y**2 + 2*y**2 + 0*y**2)*(y + y - y + y - 2*y - y + (-1 + 1 - 1)*(-4*y + 0*y + 6*y)). Steps: -6*y**3 Conundrum: Expand (w**2 - w**2 + 2*w**4 - w + w**4 + w + (3 - 5 + 1)*(-2*w**4 + 1 - 1))*(-24*w + 18 - 18). Steps: -120*w**5 Conundrum: Expand (t**4 - 3*t**4 - t**4)*(2*t - 3*t - t)*(0 + 1 - 2). Steps: -6*t**5 Conundrum: Expand (59*o + 17*o**2 - 59*o)*(1 - 1 + 2*o). Steps: 34*o**3 Conundrum: Expand (-b**3 + 1 - 1)*(b**2 - b**2 + 2*b**2)*(15 + 20 - 14) + (12*b**5 - 3*b**5 + 5*b**5)*(-1 - 3 + 5). Steps: -28*b**5 Conundrum: Expand (-2*q - 3*q - 4*q + (4 - 1 - 2)*(-4*q + q + q))*(13*q**2 + 7*q**2 - q**2). Steps: -209*q**3 Conundrum: Expand (8*w**3 + w - 9*w**3 - 2*w)*(-5*w**2 + 5*w**2 - 3*w**2) + (-3*w**3 + w**3 + w**3)*(4 + w**2 - 4). Steps: 2*w**5 + 3*w**3 Conundrum: Expand (2 - 5*t - 2)*(-7 + 3 + 3). Steps: 5*t Conundrum: Expand (-1 - 4 - 1 + (0 - 6 - 1)*(1 + 0 - 3) + 5 + 0 - 4)*(-16 - 15 + 53 + (-2 - 1 + 4)*(0 - 2 + 4) - 1 + 1 - 1)*(-n**2 + 2*n**2 - 4*n**2). Steps: -621*n**2 Conundrum: Expand (-2 + 2 - 2*v)*(0 - 6 + 5)*(-v + 2*v - 2*v)*(-5 + 3 - 7). Steps: 18*v**2 Conundrum: Expand (-4*f**3 - f**3 + 4*f**3 + (-2*f - f + 4*f)*(0*f**2 - 2*f**2 + 0*f**2) + 0*f**2 + f**3 + 0*f**2)*(25*f - 3*f + 4*f). Steps: -52*f**4 Conundrum: Expand (-3*z**2 - 2*z**2 + 4*z**2)*(4*z - 4*z + 2*z)*(2 - 4 + 0 + (2 - 1 + 1)*(-2 - 3 + 3) - 3 + 5 - 1). Steps: 10*z**3 Conundrum: Expand (0*v**2 + 3*v**2 - 2*v**2)*(3 - 4 + 3) - 69*v + 263 + 25*v + 2*v**2 + 49*v. Steps: 4*v**2 + 5*v + 263 Conundrum: Expand (0 + 15*h - 3 - 17*h)*(5*h - 10*h + 13*h) + 3*h**2 - 292*h + 292*h + 2. Steps: -13*h**2 - 24*h + 2 Conundrum: Expand (-4*u - 2*u - 2*u)*(-299 - 21 + 18)*(3 - 5 + 1). Steps: -2416*u Conundrum: Expand (-6*u - 4*u**2 + 6*u)*(-3*u**2 - 3*u**2 + 4*u**2) + (0*u**3 + 0*u**3 + 2*u**3)*(u - 6*u + 3*u). Steps: 4*u**4 Conundrum: Expand (-87*v - 69*v + 49*v - 28*v)*(-v**2 + 0 + 0). Steps: 135*v**3 Conundrum: Expand 3*d + d**2 - 3*d + (-5 + 2 + 0)*(d**2 - 3*d**2 + d**2). Steps: 4*d**2 Conundrum: Expand (1 - 1 + 2*l)*(9 + 18*l - 9)*(l**2 - 2*l**2 + 0*l**2). Steps: -36*l**4 Conundrum: Expand (4*m**3 + 8*m**3 - 3*m**3)*((3*m - 2*m + m)*(4*m - m + 0*m) + 0 + 2*m**2 + 0 + 2*m**2 - 4*m**2 + 5*m**2). Steps: 99*m**5 Conundrum: Expand (1 - 1 + 2*x)*(-75*x**3 + 137 - 135 + 80*x**3 + 6*x). Steps: 10*x**4 + 12*x**2 + 4*x Conundrum: Expand 2 - 2 - 3*p + (-2 + 5 - 1)*(-2 - 3 + 2)*(-p - 2*p + 4*p). Steps: -9*p Conundrum: Expand (0*c**3 - c**3 - c**3)*(141*c + 52*c + 0*c)*(-5 + 4 + 3). Steps: -772*c**4 Conundrum: Expand (-2*j + 1 - 1)*(-3*j + 2*j + 0*j) + 231*j**2 + 119*j**2 + 35*j**2 + (2*j + 0*j + 0*j)*(j + 4*j - 4*j). Steps: 389*j**2 Conundrum: Expand (-2 + 0 + 0)*(6 - 5 - 3)*(4 - 4 + 2)*(-4*n + 0*n + 6*n). Steps: 16*n Conundrum: Expand (m - m + m)*(14007 + 13*m - m**3 - 4*m**2 - 14007). Steps: -m**4 - 4*m**3 + 13*m**2 Conundrum: Expand (5 - 7 - 4)*(-57 + 30*f + 57 + (3*f - 5*f + 3*f)*(7 - 3 - 2) - 2*f - 3*f + 4*f). Steps: -186*f Conundrum: Expand (-4*w**4 + 11 - 11 + (-2*w**2 - 2*w**2 + 2*w**2)*(3*w**2 - 5*w**2 + w**2) + 3*w + w**4 - 3*w)*(-3 + 3 - 2). Steps: 2*w**4 Conundrum: Expand (-36*y + 37*y - 49*y)*(-5*y**3 + y**3 + y**3) - 5*y - 2*y**4 + 5*y. Steps: 142*y**4 Conundrum: Expand (q + q + 0*q)*(2*q - q + 3*q) - 2*q**2 + q**2 + 0*q**2 + (q - 3*q + 3*q)*(-q + 0*q - q). Steps: 5*q**2 Conundrum: Expand (0*l - l + 3*l)*(2*l - 2*l - 7*l). Steps: -14*l**2 Conundrum: Expand (-b**4 + 0*b + 0*b)*(17447 + 2167 + 16434 + 25233 + 12948). Steps: -74229*b**4 Conundrum: Expand (0*d**2 + 3*d**2 + 0*d**2)*(d**2 + 0*d**2 + 0*d**2) - 1 + 1 - 2*d**4 + (-d**3 - 1 + 1)*(-d - 3 + 3) + 0*d**4 + d**4 + d**4. Steps: 4*d**4 Conundrum: Expand (-4*c + 10 - 8 + 6*c)*(3*c**2 - c + c). Steps: 6*c**3 + 6*c**2 Conundrum: Expand -8*i + 8*i - 12*i**3 + (4*i**3 + 15*i**3 - 10*i**3)*(2 + 1 + 0). Steps: 15*i**3 Conundrum: Expand (m - 2*m**2 - m)*((m - 3*m + 0*m)*(4*m + m - 3*m) + 26*m**2 - 5*m**2 - 2*m**2 + 0 + m**2 + 0). Steps: -32*m**4 Conundrum: Expand (-3*v**2 + 2*v**2 - 2*v**2)*(-3*v - 2*v + 3*v) + 2*v**2 + 7*v**3 - 2*v**2 - v**3 - 2 + 2 + (3 - 3 + 2*v**2)*(2*v + 2*v - 3*v) - 3*v**3 + 5*v**3 - v**3. Steps: 15*v**3 Conundrum: Expand (-4*k + 0 + 0)*(178 + 109 - 61). Steps: -904*k<|endoftext|>probability: swr p level set ---------------------------- Request: Two letters picked without replacement from llnzblllblz. Give prob of picking 2 l. →: 3/11 Request: Two letters picked without replacement from ycikycrryckkkybyrky. Give prob of picking 2 r. →: 1/57 Request: Four letters picked without replacement from {z: 2, w: 1, d: 8, l: 1, j: 2, f: 1}. Give prob of picking 2 d, 1 z, and 1 w. →: 8/195 Request: Four letters picked without replacement from {e: 1, s: 3, v: 1, r: 5}. Give prob of picking 1 e, 1 v, and 2 r. →: 1/21 Request: Calculate prob of picking 2 r when two letters picked without replacement from arrar. →: 3/10 Request: Calculate prob of picking 2 m when two letters picked without replacement from mcwmicicimcffcmmwmfm. →: 21/190 Request: What is prob of picking 1 g, 1 l, and 1 z when three letters picked without replacement from ghehggeleez? →: 1/55 Request: Calculate prob of picking 1 r and 1 b when two letters picked without replacement from {r: 6, f: 1, i: 1, b: 1, x: 1, h: 3}. →: 1/13 Request: What is prob of picking 4 q when four letters picked without replacement from {u: 5, q: 8}? →: 14/143 Request: Calculate prob of picking 1 i and 1 q when two letters picked without replacement from iivq. →: 1/3 Request: Three letters picked without replacement from {p: 4, u: 5, s: 1, l: 3}. Give prob of picking 1 u and 2 l. →: 15/286 Request: Two letters picked without replacement from wahwheweeew. What is prob of picking 1 w and 1 e? →: 16/55 Request: Four letters picked without replacement from baabhbabbbabbbqa. Give prob of picking 1 b, 1 q, and 2 a. →: 9/182 Request: Two letters picked without replacement from {g: 3, d: 3, i: 1, c: 6}. What is prob of picking 1 g and 1 d? →: 3/26 Request: Three letters picked without replacement from qqvqppq. Give prob of picking 1 p and 2 v. →: 0 Request: What is prob of picking 2 e when two letters picked without replacement from kiqlqqkeeiikeqsqqisk? →: 3/190 Request: What is prob of picking 3 x and 1 d when four letters picked without replacement from {x: 15, d: 5}? →: 455/969 Request: Four letters picked without replacement from {v: 12, j: 3}. What is prob of picking 3 j and 1 v? →: 4/455 Request: What is prob of picking 1 y, 1 e, and 2 r when four letters picked without replacement from rerrryrrr? →: 1/6 Request: Calculate prob of picking 1 u and 1 x when two letters picked without replacement from {x: 1, s: 1, z: 4, u: 2}. →: 1/14 Request: Two letters picked without replacement from {p: 2, n: 6, j: 3, s: 3, c: 1}. Give prob of picking 1 c and 1 s. →: 1/35 Request: Four letters picked without replacement from {c: 4}. What is prob of picking 4 c? →: 1 Request: Four letters picked without replacement from xsoxqxqxxxxxxooxxos. Give prob of picking 2 s and 2 q. →: 1/3876 Request: Calculate prob of picking 2 d and 1 s when three letters picked without replacement from swdsssdwsssswsssdoss. →: 13/380 Request: Calculate prob of picking 1 o and 1 m when two letters picked without replacement from mouthot. →: 2/21 Request: Calculate prob of picking 2 o, 1 a, and 1 w when four letters picked without replacement from whnaaonawauo. →: 8/495 Request: Calculate prob of picking 2 f when two letters picked without replacement from {f: 2, w: 5}. →: 1/21 Request: Three letters picked without replacement from eduudugeijueudeuduiu. What is prob of picking 1 u, 1 e, and 1 j? →: 8/285 Request: Three letters picked without replacement from xyyysyyxsxsyyx. Give prob of picking 2 x and 1 y. →: 3/26 Request: Three letters picked without replacement from rvvrurrqrfvvrvrqqwq. What is prob of picking 1 q, 1 u, and 1 r? →: 28/969 Request: Calculate prob of picking 1 q, 1 v, and 1 f when three letters picked without replacement from fffffffzffvsvfqvsf. →: 11/272 Request: What is prob of picking 1 t and 2 b when three letters picked without replacement from bppppbptppbppppp? →: 3/560 Request: Three letters picked without replacement from rrkrkk. Give prob of picking 3 r. →: 1/20 Request: Three letters picked without replacement from {r: 7, z: 4, w: 3, a: 1, m: 2, f: 1}. Give prob of picking 1 z, 1 f, and 1 m. →: 1/102 Request: Four letters picked without replacement from bqjqscvbj. What is prob of picking 1 s, 1 c, 1 j, and 1 v? →: 1/63 Request: What is prob of picking 2 y and 1 j when three letters picked without replacement from {m: 1, e: 1, y: 3, r: 1, j: 1}? →: 3/35 Request: Calculate prob of picking 1 k and 1 w when two letters picked without replacement from {k: 1, u: 1, w: 1}. →: 1/3 Request: Two letters picked without replacement from {y: 3, f: 15}. What is prob of picking 2 y? →: 1/51 Request: Four letters picked without replacement from {p: 3, c: 3, d: 7}. What is prob of picking 2 d and 2 c? →: 63/715 Request: Three letters picked without replacement from {p: 2, q: 4, x: 3, w: 3, n: 2, u: 2}. Give prob of picking 1 w, 1 q, and 1 u. →: 3/70 Request: Four letters picked without replacement from {v: 2, n: 1, o: 1, f: 2, a: 1}. What is prob of picking 1 n, 2 f, and 1 o? →: 1/35 Request: Calculate prob of picking 3 m and 1 j when four letters picked without replacement from mmmmmmjmmmmm. →: 1/3 Request: Two letters picked without replacement from lylylclnollclloglo. Give prob of picking 2 o. →: 1/51 Request: Two letters picked without replacement from {j: 4, t: 14}. Give prob of picking 2 j. →: 2/51 Request: Two letters picked without replacement from {c: 10, u: 9}. Give prob of picking 2 u. →: 4/19 Request: Two letters picked without replacement from olzxoooooozooo. Give prob of picking 2 z. →: 1/91 Request: What is prob of picking 3 p and 1 h when four letters picked without replacement from {h: 2, p: 16}? →: 56/153 Request: Calculate prob of picking 1 q, 1 w, and 2 d when four letters picked without replacement from ddrqwrjdrqjdwr. →: 24/1001 Request: What is prob of picking 4 d when four letters picked without replacement from {d: 5, r: 7}? →: 1/99 Request: What is prob of picking 2 h when two letters picked without replacement from lhhhhhhh? →: 3/4 Request: Four letters picked without replacement from wwwiwwbiwbbwiibbb. What is prob of picking 2 b, 1 i, and 1 w? →: 3/17 Request: Calculate prob of picking 1 b, 1 i, and 1 t when three letters picked without replacement from {b: 1, i: 2, u: 4, t: 4}. →: 8/165 Request: What is prob of picking 1 j and 1 z when two letters picked without replacement from {j: 2, n: 1, z: 1, x: 1}? →: 1/5 Request: Four letters picked without replacement from {s: 7, o: 2, l: 7, f: 1}. What is prob of picking 1 f, 2 s, and 1 o? →: 3/170 Request: Calculate prob of picking 2 c when two letters picked without replacement from cccrccncccnccncccccc. →: 12/19 Request: What is prob of picking 2 o when two letters picked without replacement from ooo? →: 1 Request: Four letters picked without replacement from ivnninknrvhh. Give prob of picking 1 v, 1 n, 1 i, and 1 h. →: 32/495 Request: Four letters picked without replacement from {a: 5, s: 5, r: 3, p: 3, x: 2}. What is prob of picking 2 s and 2 x? →: 1/306 Request: Two letters picked without replacement from tyttttltlttyttyttyyt. What is prob of picking 1 y and 1 l? →: 1/19 Request: Three letters picked without replacement from {x: 4, p: 3, f: 2}. What is prob of picking 3 p? →: 1/84 Request: Three letters picked without replacement from {z: 5, l: 4, q: 5, g: 5, x: 1}. Give prob of picking 1 z, 1 g, and 1 q. →: 25/228 Request: Two letters picked without replacement from {r: 1, u: 1, m: 1}. Give prob of picking 1 u and 1 m. →: 1/3 Request: Two letters picked without replacement from xxxxxxxxxx. What is prob of picking 2 x? →: 1 Request: Three letters picked without replacement from {u: 2, p: 3, t: 3}. Give prob of picking 3 p. →: 1/56 Request: What is prob of picking 3 h and 1 c when four letters picked without replacement from hhcbhcbchc? →: 8/105 Request: What is prob of picking 2 l when two letters picked without replacement from {n: 11, l: 2, p: 1}? →: 1/91 Request: Calculate prob of picking 2 p and 1 l when three letters picked without replacement from {l: 17, p: 2}. →: 1/57 Request: Calculate prob of picking 1 y, 1 o, and 1 i when three letters picked without replacement from yyyivkoky. →: 1/21 Request: Calculate prob of picking 2 g when two letters picked without replacement from {n: 3, g: 3, u: 6, y: 1, k: 1}. →: 3/91 Request: Four letters picked without replacement from {n: 3, j: 2, l: 2, v: 5, e: 6, x: 1}. Give prob of picking 1 l, 2 j, and 1 x. →: 1/1938 Request: Two letters picked without replacement from rcyyj. Give prob of picking 1 j and 1 r. →: 1/10 Request: Two letters picked without replacement from gggxxjgggxxgjx. Give prob of picking 1 x and 1 j. →: 10/91 Request: Calculate prob of picking 2 z when two letters picked without replacement from zzqqkzqzzkq. →: 2/11 Request: What is prob of picking 2 p when two letters picked without replacement from nnppy? →: 1/10 Request: Calculate prob of picking 2 q and 2 n when four letters picked without replacement from nqnqsqnqqqqsnkqknnn. →: 49/323 Request: Two letters picked without replacement from {n: 5, b: 2}. Give prob of picking 2 b. →: 1/21 Request: Four letters picked without replacement from {y: 1, r: 4, n: 3, t: 4, m: 4, l: 4}. What is prob of picking 2 t and 2 r? →: 12/1615 Request: Calculate prob of picking 1 l and 2 m when three letters picked without replacement from pppppmpmmppllmmpm. →: 3/68 Request: What is prob of picking 4 l when four letters picked without replacement from lllllllpllplllllllll? →: 12/19 Request: Four letters picked without replacement from lllcccccclcl. Give prob of picking 4 c. →: 7/99 Request: What is prob of picking 2 q when two letters picked without replacement from qmqmqqmq? →: 5/14 Request: Calculate prob of picking 1 e and 1 g when two letters picked without replacement from gwdgwwew. →: 1/14 Request: Two letters picked without replacement from kgkkkkkg. Give prob of picking 2 g. →: 1/28 Request: Two letters picked without replacement from bmtfhtbhhahham. Give prob of picking 1 h and 1 b. →: 10/91 Request: What is prob of picking 3 c and 1 g when four letters picked without replacement from cgcgccc? →: 4/7 Request: Three letters picked without replacement from pphphwpppwhwwwh. Give prob of picking 1 h, 1 w, and 1 p. →: 24/91 Request: Calculate prob of picking 2 b and 1 p when three letters picked without replacement from pbcb. →: 1/4 Request: Two letters picked without replacement from mdmmmmdmdhmmhdmmhbm. Give prob of picking 1 d and 1 b. →: 4/171 Request: Calculate prob of picking 2 c when two letters picked without replacement from {s: 1, c: 4, l: 2, e: 1, m: 3}. →: 6/55 Request: What is prob of picking 2 a and 1 b when three letters picked without replacement from abaaaaaacaa? →: 12/55 Request: Two letters picked without replacement from {m: 12, i: 7}. What is prob of picking 2 i? →: 7/57 Request: Three letters picked without replacement from {y: 5, k: 3, p: 2, z: 1, v: 1}. Give prob of picking 1 v, 1 k, and 1 p. →: 3/110 Request: Two letters picked without replacement from trggtgjjr. Give prob of picking 1 g and 1 t. →: 1/6 Request: Two letters picked without replacement from zzkozzoskkzko. Give prob of picking 2 o. →: 1/26 Request: Two letters picked without replacement from ooooooooiao. What is prob of picking 1 o and 1 i? →: 9/55 Request: Four letters picked without replacement from zzduuzduuudduu. Give prob of picking 4 u. →: 5/143 Request: What is prob of picking 1 a, 1 r, and 2 f when four letters picked without replacement from fnakaksanrfsaa? →: 5/1001 Request: Four letters picked without replacement from {w: 5, v: 2, p: 2, u: 11}. Give prob of picking 2 u, 1 v, and 1 w. →: 110/969 Request: Four letters picked without replacement from zfafinfnfazakk. What is prob of picking 3 f and 1 i? →: 4/1001 Request: Two letters picked without replacement from kdqtkwi. Give prob of picking 2 k. →: 1/21 Request: Calculate prob of picking 3 g when three letters picked without replacement from {l: 9, g: 7}. →: 1/16 Request: Three letters picked without replacement from iiiiiiiiiihii. What is prob of picking 1 h and 2 i? →: 3/13 Request: What is prob of picking 2 n and 2 o when four letters picked without replacement from {n: 5, j: 8, o: 3}? →: 3/182 Request: Two letters picked without replacement from {k: 10, m: 2}. What is prob of picking 2 m? →: 1/66 Request: Four letters picked without replacement from {f: 5, g: 11}. What is prob of picking 2 f and 2 g? →: 55/182 Request: What is prob of picking 1 i, 1 y, and 1 t when three letters picked without replacement from {y: 1, q: 2, f: 1, i: 1, w: 1, t: 1}? →: 1/35 Request: What is prob of picking 2 h and 1 x when three letters picked without replacement from {h: 8, x: 2}? →: 7/15 Request: Two letters picked without replacement from ucycyyccszyzyuyyyuy. Give prob of picking 1 y and 1 s. →: 1/19 Request: Two letters picked without replacement from lliillliliilllll. Give prob of picking 1 l and 1 i. →: 11/24 Request: Three letters picked without replacement from {c: 9, a: 6, f: 4}. Give prob of picking 1 c and 2 f. →: 18/323 Request: Four letters picked without replacement from {w: 1, s: 1, l: 4, t: 3, a: 2}. What is prob of picking 2 t, 1 s, and 1 w? →: 1/110 Request: Three letters picked without replacement from reeere. Give prob of picking 3 e. →: 1/5 Request: Four letters picked without replacement from vvvvzvvvvvvvzvvvvvvv. What is prob of picking 4 v? →: 12/19 Request: What is prob of picking 2 q when two letters picked without replacement from {l: 1, q: 2, g: 6, d: 2}? →: 1/55 Request: Two letters picked without replacement from ooadgowvvvwggvw. Give prob of picking 2 v. →: 2/35 Request: Two letters picked without replacement from dddddfdffffddddddfd. Give prob of picking 2 d. →: 26/57 Request: Three letters picked without replacement from {u: 2, y: 5, w: 5}. What is prob of picking 3 y? →: 1/22 Request: What is prob of picking 2 r when two letters picked without replacement from orraooramaooaamraa? →: 2/51 Request: Four letters picked without replacement from {c: 12, i: 2, r: 5}. What is prob of picking 4 c? →: 165/1292 Request: Calculate prob of picking 1 q and 1 i when two letters picked without replacement from {i: 1, q: 3, s: 3}. →: 1/7 Request: Calculate prob of picking 1 b and 1 l when two letters picked without replacement from {n: 1, b: 1, l: 1}. →: 1/3 Request: Two letters picked without replacement from {a: 5, c: 2}. Give prob of picking 2 a. →: 10/21 Request: Calculate prob of picking 1 n and 1 d when two letters picked without replacement from hnd. →: 1/3 Request: Two letters picked without replacement from {d: 18, t: 1}. Give prob of picking 1 t and 1 d. →: 2/19 Request: What is prob of picking 1 t, 2 f, and 1 a when four letters picked without replacement from tlfftfa? →: 6/35 Request: Three letters picked without replacement from {q: 1, c: 2, v: 3, e: 10, k: 1}. Give prob of picking 1 k and 2 e. →: 9/136 Request: What is prob of picking 2 i when two letters picked without replacement from iibbbbbbibibbb? →: 6/91 Request: What is prob of picking 1 t and 1 i when two letters picked without replacement from {v: 6, i: 4, t: 2}? →: 4/33 Request: Two letters picked without replacement from {s: 10, u: 2}. What is prob of picking 1 s and 1 u? →: 10/33 Request: Calculate prob of picking 1 c and 1 x when two letters picked without replacement from {c: 4, i: 3, v: 6, x: 6}. →: 8/57 Request: What is prob of picking 1 v and 1 l when two letters picked without replacement from sglglslrvllgglll? →: 1/15 Request: Three letters picked without replacement from eeuuqffffnuf. What is prob of picking 1 f, 1 n, and 1 q? →: 1/44 Request: Four letters picked without replacement from {c: 9, n: 1, i: 1, l: 3}. What is prob of picking 1 c and 3 l? →: 9/1001 Request: What is prob of picking 2 x and 2 b when four letters picked without replacement from bxcbfxcxxffcbcb? →: 12/455 Request: What is prob of picking 1 n, 1 q, and 1 p when three letters picked without replacement from pffpfnyqyy? →: 1/60 Request: Two letters picked without replacement from {t: 10, z: 2, f: 4, n: 4}. What is prob of picking 2 f? →: 3/95 Request: Three letters picked without replacement from {r: 3, w: 9}. Give prob of picking 2 w and 1 r. →: 27/55 Request: Four letters picked without replacement from lqnnnlqnnqnqnnqql. Give prob of picking 1 n, 1 q, and 2 l. →: 36/595 Request: Two letters picked without replacement from mgmg. What is prob of picking 2 g? →: 1/6 Request: Calculate prob of picking 1 r and 1 k when two letters picked without replacement from yrrorkrrgygr. →: 1/11 Request: What is prob of picking 3 g when three letters picked without replacement from {g: 14, k: 4}? →: 91/204 Request: Four letters picked without replacement from {d: 2, o: 2, v: 1}. What is prob of picking 2 o and 2 d? →: 1/5 Request: Four letters picked without replacement from xxxxx. What is prob of picking 4 x? →: 1 Request: What is prob of picking 3 g when three letters picked without replacement from {e: 1, g: 3}? →: 1/4 Request: Calculate prob of picking 1 q, 1 p, and 1 j when three letters picked without replacement from {k: 2, v: 1, j: 1, i: 2, q: 1, p: 1}. →: 1/56 Request: What is prob of picking 2 r when two letters picked without replacement from {r: 6, e: 1, j: 4}? →: 3/11 Request: Calculate prob of picking 2 z and 1 d when three letters picked without replacement from dddyzzddzzdyyfzdz. →: 21/136 Request: Two letters picked without replacement from {y: 9, f: 10}. What is prob of picking 2 f? →: 5/19 Request: Two letters picked without replacement from {s: 3, z: 1, l: 2, f: 1}. Give prob of picking 1 s and 1 z. →: 1/7 Request: Two letters picked without replacement from vkqqdngn. What is prob of picking 1 d and 1 n? →: 1/14 Request: Calculate prob of picking 2 m and 1 l when three letters picked without replacement from {b: 2, l: 1, c: 1, m: 4}. →: 3/28 Request: Three letters picked without replacement from sgtdddgqddtdqqt. Give prob of picking 3 t. →: 1/455 Request: What is prob of picking 4 t when four letters picked without replacement from {s: 3, c: 2, t: 10}? →: 2/13 Request: Two letters picked without replacement from {z: 2, l: 4, a: 4, j: 5}. What is prob of picking 1 j and 1 a? →: 4/21 Request: Two letters picked without replacement from {z: 1, k: 14}. What is prob of picking 2 k? →: 13/15 Request: What is prob of picking 1 p and 1 a when two letters picked without replacement from {a: 1, k: 4, e: 6, y: 2, p: 2}? →: 2/105 Request: What is prob of picking 2 w and 1 a when three letters picked without replacement from {q: 7, w: 4, a: 2}? →: 6/143 Request: What is prob of picking 1 e and 1 w when two letters picked without replacement from eebwiizizwbeeoi? →: 8/105 Request: Two letters picked without replacement from {v: 2, w: 6, x: 11}. What is prob of picking 1 x and 1 v? →: 22/171 Request: Two letters picked without replacement from ccccccccc. Give prob of picking 2 c. →: 1 Request: Calculate prob of picking 1 g, 2 t, and 1 n when four letters picked without replacement from {g: 3, l: 1, t: 2, n: 5, k: 1}. →: 1/33 Request: Four letters picked without replacement from {s: 7, l: 6}. Give prob of picking 3 s and 1 l. →: 42/143 Request: Three letters picked without replacement from kkilllibikbhbiilklib. Give prob of picking 1 l and 2 i. →: 5/76 Request: Two letters picked without replacement from {w: 3, x: 2, u: 1, h: 5, n: 1}. What is prob of picking 1 x and 1 w? →: 1/11 Request: Four letters picked without replacement from {j: 7, y: 6}. What is prob of picking 2 y and 2 j? →: 63/143 Request: Two letters picked without replacement from kdkkr. What is prob of picking 1 k and 1 r? →: 3/10 Request: Four letters picked without replacement from {z: 3, o: 4, x: 1, w: 1, q: 2}. Give prob of picking 1 x, 1 o, and 2 z. →: 2/55 Request: Four letters picked without replacement from {g: 10, c: 2}. What is prob of picking 2 g and 2 c? →: 1/11 Request: What is prob of picking 2 v and 2 u when four letters picked without replacement from vuvuuvvuvuuvvuvvuuu? →: 135/323 Request: Calculate prob of picking 3 l when three letters picked without replacement from {f: 4, l: 3}. →: 1/35 Request: What is prob of picking 1 h and 2 g when three letters picked without replacement from {h: 3, x: 11, g: 4}? →: 3/136 Request: What is prob of picking 1 z, 1 l, and 2 m when four letters picked without replacement from jclezemljmzlll? →: 10/1001 Request: Calculate prob of picking 2 n, 1 q, and 1 a when four letters picked without replacement from {x: 1, n: 3, o: 1, q: 2, a: 4}. →: 4/55 Request: What is prob of picking 2 s when two letters picked without replacement from {c: 14, s: 4}? →: 2/51 Request: Calculate prob of picking 2 q and 1 e when three letters picked without replacement from eeeqeqeeeqqeeeeq. →: 11/56
[{"idx": "txt360/polynomials__expand_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-10.jsonl"}, {"idx": "txt360/probability__swr_p_level_set_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-10.jsonl"}]
import random from queue import Queue import time class User: def __init__(self, name): self.name = name class SocialGraph: def __init__(self): self.last_id = 0 self.users = {} self.friendships = {} def add_friendship(self, user_id, friend_id): """ Creates a bi-directional friendship """ if user_id == friend_id: # print("WARNING: You cannot be friends with yourself") return False elif ( friend_id in self.friendships[user_id] or user_id in self.friendships[friend_id] ): # print("WARNING: Friendship already exists") return False else: self.friendships[user_id].add(friend_id) self.friendships[friend_id].add(user_id) return True def add_user(self, name): """ Create a new user with a sequential integer ID """ self.last_id += 1 # automatically increment the ID to assign the new user self.users[self.last_id] = User(name) self.friendships[self.last_id] = set() def populate_graph_linear(self, num_users, avg_friendships): # Reset graph self.last_id = 0 self.users = {} self.friendships = {} # Add users self.add_user(f"User {i}") # !!!! IMPLEMENT ME target_friendships = num_users * avg_friendships total_friendships = 0 collisions = 0 while total_friendships < target_friendships: user_id = random.randint(1, self.last_id) friend_id = random.randint(1, self.last_id) if self.add_friendship(user_id, friend_id): total_friendships += 2 else: print(f"Collisions: {collisions}") def populate_graph(self, num_users, avg_friendships): """ Takes a number of users and an average number of friendships as arguments Creates that number of users and a randomly distributed friendships between those users. The number of users must be greater than the average number of friendships. """ # Reset graph self.last_id = 0 self.users = {} self.friendships = {} # !!!! IMPLEMENT ME # Add users self.add_user(f"User {i}") # Create friendships # generate all possible friendship combinations possible_friendships = [] # avoid dups by ensuring first num < second num for user_id in self.users: for friend_id in range(user_id + 1, self.last_id + 1): possible_friendships.append((user_id, friend_id)) # shuffle friendships random.shuffle(possible_friendships) # create friendships from the first N pairs of the list # N -> num_users * avg_friendships // 2 N = num_users * avg_friendships // 2 for i in range(N): friendship = possible_friendships[i] # user_id, friend_id = friendship user_id = friendship[0] friend_id = friendship[1] self.add_friendship(user_id, friend_id) def get_all_social_paths(self, user_id): """ Takes a user's user_id as an argument Returns a dictionary containing every user in that user's extended network with the shortest friendship path between them. The key is the friend's ID and the value is the path. """ q = Queue() visited = {} # Note that this is a dictionary, not a set q.enqueue([user_id]) while q.size() > 0: path = q.dequeue() v = path[-1] if v not in visited: visited[v] = path for friend in self.friendships[v]: path_copy = list(path) # path.copy() path_copy.append(friend) q.enqueue(path_copy) return visited # if __name__ == '__main__': # sg = SocialGraph() # sg.populate_graph(10, 2) # print(sg.friendships) # print(connections) # # Test at scale # if __name__ == '__main__': # sg = SocialGraph() # sg.populate_graph(1000, 300) # print(f"Users in extended social network: {len(connections) - 1}") # total_social_paths = 0 # for user_id in connections: # total_social_paths += len(connections[user_id]) # print(f"Avg length of social path: {total_social_paths / len(connections)}") # Random Sampling if __name__ == "__main__": sg = SocialGraph() num_users = 2000 avg_friendships = 1500 start_time = time.time() sg.populate_graph_linear(num_users, avg_friendships) # print(sg.friendships) end_time = time.time() print(f"Linear runtime: {end_time - start_time} seconds") sg = SocialGraph() start_time = time.time() sg.populate_graph(num_users, avg_friendships) end_time = time.time() print(f"Quadratic runtime: {end_time - start_time} seconds")<|endoftext|>import sys import curses import argparse import time from curses import wrapper from typing import Any, Type import art from logic import Game, TimerRound, Round, Selection, Options HANDS = { Selection.PAPER: art.PAPER, Selection.ROCK: art.ROCK, Selection.SCISSORS: art.SCISSORS } class ConsoleGame: WAIT_BEFORE_CONTINUE = 2 # sec LOOP_SLEEP = 0.1 self.selection = '' self.game = game self.options = game.options self.previous_round = game.start_round() self.player_images = {game.cpu: art.ROBOT, game.player: art.PLAYER} self.last_action_time = .0 def show_players(self) -> None: winner = self.game.winner or self.previous_round.winner robot = art.ROBOT_WON if winner is self.game.cpu else art.ROBOT player = art.PLAYER_WON if winner is self.game.player else art.PLAYER self.show_art("\n\n{}\n ==================\n\n\n{}".format(robot, player)) wrapper(self.main) def show_art(self, s: str, y: int = 0, x: int = 0) -> None: for yy, line in enumerate(s.splitlines(), 2): self.screen.addstr(y + yy, x + 2, line) def show_string(self, s: str, y: int, x: int) -> None: for col, c in enumerate(s): self.screen.addch(y, x+col, c) return if self.game.player_played(): if self.game.player_played() and self.game.current_round: def show_hands(self) -> None: X_COORD = 25 # chr Y_COORD_PLAYER = 19 Y_COORD_CPU = 3 self.show_art(HANDS.get(self.game.player.selection, ''), Y_COORD_PLAYER, X_COORD) self.show_art(HANDS.get(self.game.cpu.selection, ''), Y_COORD_CPU, X_COORD) if not self.game.is_running(): return if not self.game.current_round: def handle_selection(self, c: int) -> None: if c in [ord('p'), curses.KEY_LEFT]: self.play(Selection.PAPER) elif c in [ord('r'), curses.KEY_UP]: self.play(Selection.ROCK) elif c in [ord('s'), curses.KEY_RIGHT]: self.play(Selection.SCISSORS) def show_stats(self) -> None: played_rounds = len(self.game.rounds) or 1 self.show_string("Round: {} / {}".format(played_rounds, self.options.rounds), 1, 1) self.show_string("Wins: {}".format(self.game.get_number_of_wins(self.game.cpu)), 4, 1) self.show_string("Wins: {}".format(self.game.get_number_of_wins(self.game.player)), 20, 1) def main(self, screen: Any) -> None: self.screen = screen screen.nodelay(True) screen.clear() last_loop_is_required = True self.show_string("Can be played with [P] [R] [S] or Arrow keys. [Q] to quit", 2, 0) c = screen.getch() while self.game.is_running() or last_loop_is_required: last_loop_is_required = self.game.is_running() c = screen.getch() if c == ord('q'): sys.exit() screen.clear() self.show_stats() self.show_players() self.show_hands() self.handle_selection(c) self.finalize_round() self.start_next_round() time.sleep(self.LOOP_SLEEP) # this additional getch call required to # print the results of the last round screen.getch() class TimerGame(ConsoleGame): self.round_duration = game.options.countdown_duration self.round_duration -= self.LOOP_SLEEP if self.round_duration >= 0: self.show_string(str("{:10.1f}".format(self.round_duration)), 30, 50) if self.game.current_round and self.round_duration <= 0: self.game.current_round or return self.round_duration = self.options.countdown_duration if __name__ == "__main__": parser.add_argument("--timer", action="store_true", help="Play against both time and chance. You must make a choice before " "the countdown is over. Threshold can be set with --threshold parameter.") parser.add_argument("--rounds", help="Set number of rounds. Default is {}.".format(Options.rounds)) parser.add_argument("--threshold", help="Selection acceptance threshold for timer mode. " "Default is {} sec.".format(Options.threshold)) parser.add_argument("--countdown", help="Countdown duration for timer mode. " "Default is {} sec.".format(Options.countdown_duration)) ui: Type[ConsoleGame] = ConsoleGame round: Type[Round] = Round if args.timer: round = TimerRound ui = TimerGame game = Game(round) if args.rounds: game.set_options(rounds=float(args.rounds)) if args.threshold: game.set_options(threshold=float(args.threshold)) if args.countdown: game.set_options(countdown_duration=int(args.countdown)) ui(game).start_game() print("\nGame result for the player: {} \n".format(game.get_player_result().name))
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-6925.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-6925.jsonl"}]
Q: getting the debugger to break at the next click event in a .net windows forms project which has 100s of forms, and all those forms has countless custom made controls with base classes involved, its very difficult for me to know where a particular button is, i mean whats the form name which I'm looking at while i'm running the application, and where exactly is the button click event, in code, of the button that I just clicked. Is there a debugging feature in Visual Studio, which would just break the execution for me to the line where the click happened. Can I tell VS to break at which ever Click event comes next? (running visual studio 2012/13 these days). thanks. A: Just before you click the button in the program do this: Go to visual studio and pause the program. Just press the pause button. Then press F11 (Step Into). Now press the button in the program, and you should be taken into the event handler. A: For web projects, the technique suggested by Jakob Olsen will not really work, because you have no active thread in between the calls, and hence no thread to resume upon the next action. However what worked for me was: * *Find some code (any code in your app) you know for sure it gets executed and set a breakpoint *Trigger this breakpoint, use SHIFT-F11 to step out until you're out of all methods *Now do the action of which you don't know what code is executed, and it will break A: I can suggest partial solution. If your click events are named like "Button_Click", open Breakpoints windows while in debug and create New breakpoint. Click OK and you will see list of functions. Check them and click OK. On every function that you have selected will be created a breakpoint.<|endoftext|>Q: Disabling warning about "require" function in JSHint I'm writing some code for Node.js and I'm currently using JSHint to check over my code. However, when I use the require function to import modules, it says: 'require' is not defined. "use strict"; var register = require('./routes/register'); A: jshint is not aware of node.js globals by default you need to inform it. add this comment to the top: /* jshint node: true */ A: You can configure JSHint by adding "require" to the .jshintrc file. For instance: { "globals" : { "require": false } } Or you can define globals per specific file only by: /* global require */ For more information about how to configure JSHint please read JSHint Documentation A: We can set node as the global environment variable in JSHint's .jshintrc file This option defines globals available when your code is running inside of the Node runtime environment. Node.js is a server-side JavaScript environment that uses an asynchronous event-driven model. This option also skips some warnings that make sense in the browser environments but don't make sense in Node such as file-level use strict pragmas and console.log statements. For more info [IDX] "node": true } Errors like 'require' is not defined, 'console' is not defined, 'module' is not defined won't show up any more A: I stumbled upon this answer and couldn't get anything to work in VSCode. I got this to work: * *Open JSON Settings file using the Preferences: Open Settings (JSON) via the Command Palette Window (Ctrl-Shift-P). *Add this section into the settings.json file: { "jshint.options": { "esversion": 8, // This gets rid of some other warnings "node": true } }<|endoftext|>Q: What's the view build time? I'm pretty new to JSF and reading some of the stack-answers like this one, I faced with the concept of view build time. Consider the JSF lifecycle scheme: As you can see, there's no phase called view build time. Maybe it means the same as Restore view phase? From the JavaEE tutorial During this phase, the JavaServer Faces implementation builds the view of the page [...] A: The view build time is not a phase. The view build time is that moment when the physical UIViewRoot instance and all of its children is built based on the view declaration, which is usally defined in XHTML or JSP files. The view build time moment is not restricted to a specific JSF lifecycle phase. It can technically happen in any phase. By default, it's indeed usually executed during the restore view phase, but it can also happen during the render response phase, specifically when the request is a GET request, or when navigation has taken place during a POST request. Developers can also programmatically build the view via ViewDeclarationLanguage#buildView(), or implicitly force the JSF implementation to do that via FacesContext#setViewRoot(), when navigation isn't sufficient for the specific task. The restore view phase just restores the JSF state into the view. I.e. it sets the component attributes with values as they were during the previous request on the same view. This way JSF knows exactly how the view looked like at the moment the form was being presented to the enduser and can among others do some safeguards against tampered requests. See also: * *creating jsf view/Component tree from the xhtml file *JSF 2 Global exception handling, navigation to error page not happening<|endoftext|>Q: Combine Cocoapods and Carthage I'm creating a Swift framework that is dependent on several other third party frameworks. Both these other frameworks support Carthage and Cocoapods. Is there any way I can make my own framework support installing using both Carhage and Cocoapods? Or is just not achievable and should I just pick one? A: Combining both is actually not difficult. With my framework I have started with CocoaPods template containing Example and Pod directories. In the example project I created a new Cocoa Touch Framework target, made sure this target is Shared (in Product - Schemes - Managed Schemes) and dragged content of my Pod/Classes directory to the project (with unchecked Copy items if needed and added Target Membership only to this newly created framework). This should be enough, Carthage should find this shared scheme and use it. Just keep in mind you have to commit changes and create a new git tag before using your framework from Carthage. A: You can definitely make your framework available with both CocoaPods and Carthage. This is the path that I would recommend to allow your users to use whatever solution they prefer. Also note that setting a framework up to work with Carthage also makes it much easier for users who want to use your library without either of these solutions. On a high level, for CocoaPods you'll want to create a podspec that lists your dependencies there. This way CocoaPods will manage downloading and configuring them along with resolving them against other user dependencies. See more here. For Carthage you'll want to configure your project with framework targets for the platforms you support and add your dependencies in your Cartfile. More on that here<|endoftext|>Q: Tuning node-mongodb-native connection pool size I've got an express app talking to mongodb via the node-mongodb-native driver. Some requests in my app are intermittently slow. Here's some discussion of tuning pool size, but it's pretty inconclusive. aheckmann notes that the default of 5 is usually plenty, while tinana saw significant gains from bumping up the pool with many concurrent request. Update: This question was to help me understand tuning and tooling driver pool size rather than to troubleshoot the immediate performance issue. I described my issue only to give the question a little context. A: In scenarios like this, the first step is always to start to with the DB. If you have queries that are slow to respond, those queries should appear in the slow logs. Take a look at the official docs for profiling. The default value for "slow" queries is about 100ms, so if your slow queries are because of the DB, you will see evidence there. Additionally, take a look at the graphs for the DB. By "the graphs", I mean your Nagios/Cacti/Zabbix/ServerDensity/MMS charts of what the server is doing. If you do not have these, start there. Tweaking the connection pool size is useless if you don't actually know how many connections you have or what your CPU looks like. Once you have ruled out the DB and you have configured monitoring then you can open up the connection pool size. Once you have all of this in place. You will be able to tweak the pool size and ensure that you have (a) solved the problem and (b) not caused more problems. The whole cycle is important. If you muck with the connection pool but you're not watching the slow logs and the total connections then you'll just cause more problems.<|endoftext|>Q: Vue.js 3: Cannot import Vue global object I'm going crazy trying to reconcile the Vue 3 CLI output into something that works with various tutorials and plugins that all use the Vue object, as in Vue.createApp(.... In my project, I can use createApp(... but import Vue from 'vue'; results in Vue still being undefined. I have Vue 3 installed via NPM. Clearly there is something critical that I don't understand about NPM imports, how could the {createApp} import work if importing the whole module does not work? From package.json: "dependencies": { "@babel/polyfill": "^7.12.1", "apexcharts": "^3.22.1", "core-js": "^3.6.5", "d3": "^6.2.0", "vue": "^3.0.0", "vue-router": "^4.0.0-rc.1", "vue3-apexcharts": "^1.0.0" }, "devDependencies": { "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-service": "~4.5.0", "@vue/compiler-sfc": "^3.0.0", "babel-eslint": "^10.1.0", "babel-plugin-transform-regenerator": "^6.26.0", "eslint": "^6.7.2", "eslint-plugin-vue": "^7.0.0-0" }, Here is my temporary main.js. This prints 'undefined' followed by the correct createApp function definition: import Vue from 'vue'; console.log(Vue); console.log(createApp); A: If you're working with CDN Vue is available as global variable which could be used to create instance by calling the method createApp like Vue.createApp({...}), but if you're working with a bundler which uses npm modules, there no Vue object imported from vue module so you should import createApp from it to create a new instance like : let app=new createApp({...}) app.use(somePlugin) app.mount("#app") for more details please check the migration guide of global API
[{"idx": "https://stackoverflow.com/questions/27775894", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6878.jsonl"}, {"idx": "https://stackoverflow.com/questions/15894193", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6878.jsonl"}, {"idx": "https://stackoverflow.com/questions/31890433", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6878.jsonl"}, {"idx": "https://stackoverflow.com/questions/29234348", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6878.jsonl"}, {"idx": "https://stackoverflow.com/questions/18157384", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6878.jsonl"}, {"idx": "https://stackoverflow.com/questions/64653373", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6878.jsonl"}]
osm2pgsql import speed is slow at ways Question: The import speed of ways is super slow with osm2pgsql. I need tipps how to speed up the import speed. Server Setup <code>6 Core Xenon 20 GB Ram 1400 GB SAS </code> Speedtest of my SAS-drive <code>hdparm -tT /dev/sda2 /dev/sda2: Timing cached reads: 7492.82 MB/sec SG_IO: 240.88 MB/sec </code> Import script <code>osm2pgsql --slim -r pbf -S mapfeatures_export.style -C 14000 -l --number-processes 5 -U osmdata --create --multi-geometry -d osmdatabase planet-190603.osm.pbf </code> osm2pgsql console output during run <code>osm2pgsql version 0.96.0 (64 bit id space) Using built-in tag processing pipeline Using projection SRS 4326 (Latlong) Setting up table: planet_osm_point Setting up table: planet_osm_line Setting up table: planet_osm_polygon Setting up table: planet_osm_roads Allocating memory for dense node cache Allocating dense node cache in one big chunk Allocating memory for sparse node cache Sharing dense sparse Node-cache: cache=14000MB, maxblocks=224000*65536, allocation method=11 Mid: pgsql, cache=14000 Setting up table: planet_osm_nodes Setting up table: planet_osm_ways Setting up table: planet_osm_rels Reading in file: /home/osmdata/planet-190603.osm.pbf Using PBF parser. Processing: Node(5234820k 342.0k/s) Way(15203k 0.20k/s) Relation(0 0.00/s) </code> I tested a SSD-setup, where the way-import-speed was 50k/s, but it is too expensive. I followed the optimising tool chain from [IDX] there are some additional options to tweak. Answer: Direct answer: Try to lower your -C to around 4096, you probably don't have enough memory for postgres and the osm2pgsql process. In additional, try '--flat-nodes /tmp/mycache.bin' to speed up processing with direct local stores instead of using the database. Might also try --unlogged but read the docs to make sure you are okay with the consequences. Other thoughts if you are in a cloud environment, use a higher performance machine for loading like aws r5a.2xlarge, then drop down to something closer to t3.medium for serving content. In the cloud you can dedicate machines for different purposes or even use container hosts like fargate for processing and pay only while running the load or updates. My current config on a 64G memory machine: <code> osm2pgsql --create --slim --flat-nodes /tmp/osm-cache.bin -C 18000 --database postgres --unlogged -H osmsource.cu932j20s2i5e.us-east-1.rds.amazonaws.com -U gisloader -W /osmdata/north-america-latest.osm.pbf </code> With default -C (same as -C 800) loading north america: Node(1137243k 1202.2k/s) Way(92064k 70.22k/s) Relation(291320 55.28/s) (stopped) With -C 11000: Node(1137243k 3203.5k/s) Way(92064k 70.28k/s) Relation(47320 80.87/s) (stopped, relations # dropping) pct memory was 27% With --number-processes 5 -C 9000 Processing: Node(1137243k 3203.5k/s) Way(92064k 69.96k/s) Relation(226630 54.97/s) (stopped) With just -C 19000 (monitored threads, appears to use n-2 threads by default) Node(1137243k 3176.7k/s) cancelled similar performance Increased to a machine with a 7.2T nvme ssd drive and 12cpu's 96G memory Node(1137243k 6729.3k/s) Way(92064k 90.17k/s) Relation(957280 69.26/s) parse time: 15012s r5a.2xlarge db.r5.large postgres 11.5 and the rest are defaults (rds instance could be smaller depending on your needs but above balanced with rds cpu at 90% and the server with a reasonably high memory utilization on and off during the load, only used about 10% cpu). You'll need to run the commands in the rds to activate the extensions (listed below or search aws docs for these commands). After loading you might consider a smaller instance class to control costs or backup/restore to your own machine or simply turn it off as the db is on the rds instance. Running local from what I've read is faster if you have the memory and fast drives. Other thoughts: These settings could surely be tuned for better performance but for a quick setup this seems to perform well and is cheap as long as you don't leave the machines at these sizes during normal operations after loading. The above architecture only costs about $8 to load north america so hardly worth the labor to optimize further. Next step thoughts for increasing speed if running postgres locally: More memory Higher speed ephemeral drive or raid0 storage for the flat-nodes location as the machine above will only push about 190MB/s. You'll need to choose a different class of machine to use local ephemeral ssd drives but with something like an m5ad you can bond two local ssd drives together in a raid0 array limited only by what you want to spend on the server class and number of drives. Faster may be more expensive per hour but if you can balanced the load speed with cost you may find the ability to rent large machines might balance against time and have high cost tails on both ends vs time and a long low cost middle zone where cost is similar but time can be shortened (cost/hr vs speed/hr being roughly balanced by cost optimization). This would be an interesting study if time permitted. RDS Commands for anyone interested from [IDX] extension postgis; create extension fuzzystrmatch; create extension postgis_tiger_geocoder; create extension postgis_topology; create extension hstore; alter schema tiger owner to rds_superuser ; alter schema tiger_data owner to rds_superuser ; alter schema topology owner to rds_superuser ; \dn CREATE FUNCTION exec(text) returns text language plpgsql volatile AS $f$ BEGIN EXECUTE $1; RETURN $1; END; $f$; SELECT exec('ALTER TABLE ' || quote_ident(s.nspname) || '.' || quote_ident(s.relname) || ' OWNER TO rds_superuser;') FROM ( SELECT nspname, relname FROM pg_class c JOIN pg_namespace n ON (c.relnamespace = n.oid) WHERE nspname in ('tiger','topology') AND relkind IN ('r','S','v') ORDER BY relkind = 'S') s; --TEST-- SET search_path=public,tiger; select na.address, na.streetname, na.streettypeabbrev, na.zip from normalize_address('1 Devonshire Place, Boston, MA 02109') as na; select topology.createtopology('my_new_topo',26986,0.5); --setup for loading create user gisloader with encrypted password 'somepassword'; create schema gis; grant all privileges on schema gis to gisloader; </code><|endoftext|>Unit-testing an action which calls session object Question: How can I unit test a method which uses a session object inside of its body? Let us say I have the following action: <code>[HttpPost] public JsonResult GetSearchResultGrid(JqGridParams gridParams, Guid campaignId, string queryItemsString) { var queryItems = new JavaScriptSerializer().Deserialize<IList<FilledQueryItem>>(queryItemsString); IPageData pageData = gridParams.ToPageData(); var extraFieldLinker = SessionHandler.CurrentExtraFieldsLinker; var searchParams = new SearchParamsModel(extraFieldLinker, queryItems); IList<CustomerSearchResultRow> searchResults = null; searchResults = _customerService.SearchCustomersByUrlAndCampaign(campaignId, searchParams.SearchString, searchParams.AddressFilterPredicate, pageData); return GetGridData<CustomerSearchResultGridDefinition, CustomerSearchResultRow>(searchResults, pageData); } </code> I made the following unit tests which fails so far because of the session thing: <code>[Test] public void CanGetSearchResultGrid() { //Initialize var mockJqGridParams = new Mock<JqGridParams>(); var mockPageData = new Mock<IPageData>(); IPagedList<CustomerSearchResultRow> mockPagedResult = new PagedList<CustomerSearchResultRow>(mockPageData.Object); var guid= Guid.NewGuid(); const string searchString = "[{\"Caption\":\"FirstName\",\"ConditionType\":\"contains\",\"Value\":\"d\",\"NextItem\":\"Last\"}]"; Func<Address,bool> addressFilterPredicate = (x => true); //Setup mockJqGridParams.Setup(x => x.ToPageData()).Returns(mockPageData.Object); _customerService.Setup(x => x.SearchCustomersByUrlAndCampaign(guid, searchString, addressFilterPredicate, mockPageData.Object)) .Returns(mockPagedResult); //Call var result = _homeController.GetSearchResultGrid(mockJqGridParams.Object, guid, searchString); mockJqGridParams.Verify(x => x.ToPageData(), Times.Once()); _customerService.Verify(x => x.SearchCustomersByUrlAndCampaign(guid, searchString, addressFilterPredicate, mockPageData.Object) , Times.Once()); //Verify Assert.That(result, Is.Not.Null); Assert.That(result, Is.TypeOf(typeof(JsonResult))); } </code> And the method from the helper of course: <code> public static ExtraFieldsLinker CurrentExtraFieldsLinker { get { object extraFieldLinker = GetSessionObject(EXTRA_FIELDS_LINKER); return extraFieldLinker as ExtraFieldsLinker; } set { SetSessionObject(EXTRA_FIELDS_LINKER, value); } } </code> Comment: @Hohhi, using `HttpContext` is no problem. Using `HttpContext.Current` is a problem. :) Comment: Can you Mock the ExtraFieldsLinker? Comment: How do the GetSessionObject and SetSessionObject method look like? Are they by any chance using `HttpContext.Current` in order to get to the Session? If yes, some refactoring of your code will be necessary to make it unit testable. Comment: Yes, I am using current HttpContext. What kind of refactoring would you suggest? Answer: I've solved similar issues (use of static data accessors that aren't mock friendly - in particular, <code>HttpContext.Current</code>) by wrapping the access in another object, and accessing it through an interface. You could do something like: <code>pubic interface ISessionData { ExtraFieldsLinker CurrentExtraFieldsLinker { get; set; } } public class SessionDataImpl : ISessionData { ExtraFieldsLinker CurrentExtraFieldsLinker { // Note: this code is somewhat bogus, // since I think these are methods of your class. // But it illustrates the point. You'd put all the access here get { return (ExtraFieldsLinker)GetSessionObject(EXTRA_FIELDS_LINKER); } set { SetSessionObject(EXTRA_FIELDS_LINKER, value); } } } public class ClassThatContainsYourAction { static ClassThatContainsYourAction() { SessionData = new SessionDataImpl(); } public static ISessionData SessionData { get; private set; } // Making this access very ugly so you don't do it by accident public void SetSessionDataForUnitTests(ISessionData sessionData) { SessionData = sessionData; } [HttpPost] public JsonResult GetSearchResultGrid(JqGridParams gridParams, Guid campaignId, string queryItemsString) { var queryItems = // ... IPageData pageData = // ... // Access your shared state only through SessionData var extraFieldLinker = SessionData.CurrentExtraFieldsLinker; // ... } } </code> Then your unit test can set the <code>ISessionData</code> instance to a mock object before calling <code>GetSearchResultGrid</code>. Ideally you'd use a Dependency Injection library at some point, and get rid of the static constructor. If you can figure out a way to make your <code>ISessionData</code> an instanced object instead of static, even better. Mock object frameworks tend to like to create a new mock type for every test case, and having mocks lying around from previous tests is kind of gross. I believe session state is going to be global to your session anyway, so you might not have to do anything tricky to make a non-static object work. Comment: may be marking this action as virtual and over-riding it in a stub is better? Comment: I like you suggestion but I feel like the controller class- ClassThatContainsYourAction- suffers from testing info Comment: @Hohhi: Whatever you're most comfortable with. The idea is to make this code testable to begin with, which either would accomplish. Comment: @Hohhi: So my sample code is *not* how I'd do it. I was just trying to demonstrate the concept of the abstraction, not the best code to implement it with. If you want to know how I'd do it, first make it non-static. Then look up "dependency injection", in particular, "constructor injection". Then make the backing field `readonly`, so you *can't* accidentally set it. And get rid of the public property. Without a DI framework tho, the code I wrote is pretty close to how I would write it. It is (intentionally) gross, but it gets the job done, and helps prevent mistakes.
[{"idx": "osm2pgsql_import_speed_is_slow_at_ways", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-648.jsonl"}, {"idx": "Unit-testing_an_action_which_calls_session_object", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-648.jsonl"}]
polynomials: collect -------------------- Inquiry: Collect the terms in 179973*b + 107857*b + 76603*b. Yields: 364433*b Inquiry: Collect the terms in -37586*n**3 - 37604*n**3 + 75185*n**3. Yields: -5*n**3 Inquiry: Collect the terms in 110*g - 11 - 55*g - 57*g + 11. Yields: -2*g Inquiry: Collect the terms in -30*v**3 + 22*v**2 + 2 + 12*v**3 - 2 + 16*v**3. Yields: -2*v**3 + 22*v**2 Inquiry: Collect the terms in -528*k**2 - 533*k**2 - 523*k**2 + 1548*k**2. Yields: -36*k**2 Inquiry: Collect the terms in -q**2 - 12*q**2 - 10*q**2 + 4*q**2. Yields: -19*q**2 Inquiry: Collect the terms in -9250*d**2 + 2*d + 9250*d**2 - 2*d - 4*d**3. Yields: -4*d**3 Inquiry: Collect the terms in -313*l**2 + 157*l**2 + 158*l**2. Yields: 2*l**2 Inquiry: Collect the terms in 2078 - 4145 - 2*n + 2061. Yields: -2*n - 6 Inquiry: Collect the terms in 79995*m**3 + 79886*m**3 - 160005*m**3. Yields: -124*m**3 Inquiry: Collect the terms in 39045929*d - 39045929*d + 4*d**2. Yields: 4*d**2 Inquiry: Collect the terms in 5*n + 4*n + 6*n - 6*n. Yields: 9*n Inquiry: Collect the terms in -51*d**3 + 21*d**3 + 22*d**3. Yields: -8*d**3 Inquiry: Collect the terms in 30*s + 15*s - 50*s. Yields: -5*s Inquiry: Collect the terms in 2 - 4*k - 2*k + 4*k + 6*k. Yields: 4*k + 2 Inquiry: Collect the terms in -6*l**2 + 16*l**2 - 4*l**2 - 2*l - 4*l**2. Yields: 2*l**2 - 2*l Inquiry: Collect the terms in 1615*n - 7998*n - 15022*n - 882*n. Yields: -22287*n Inquiry: Collect the terms in 3*v**2 - 14*v**2 - 17*v**2 + 8*v**2. Yields: -20*v**2 Inquiry: Collect the terms in -2216677*y + 1108322*y + 1108276*y. Yields: -79*y Inquiry: Collect the terms in -110 - 17 + 127 + o - 688*o**3. Yields: -688*o**3 + o Inquiry: Collect the terms in 12 - 10 - 5*x - 2. Yields: -5*x Inquiry: Collect the terms in 2758*c**2 - 908*c**2 - 935*c**2 + 8*c**3 - 915*c**2. Yields: 8*c**3 Inquiry: Collect the terms in 12011*f**2 - 5995*f**2 - 6014*f**2. Yields: 2*f**2 Inquiry: Collect the terms in -180907*h - 45326*h - h**3 + h**3 + h**3. Yields: h**3 - 226233*h Inquiry: Collect the terms in 7844*g**3 + 55 - 15720*g**3 - 55 + 2*g + 7860*g**3. Yields: -16*g**3 + 2*g Inquiry: Collect the terms in -138*c - 6 - 9 + 133*c. Yields: -5*c - 15 Inquiry: Collect the terms in 33*s**3 + 6*s**2 - 6*s**2 - 15*s**3 - 17*s**3. Yields: s**3 Inquiry: Collect the terms in -8487*l**2 - 8500*l**2 + 17005*l**2. Yields: 18*l**2 Inquiry: Collect the terms in -7*i - 40*i**2 - 2 - 16*i - 775*i + 6*i**2. Yields: -34*i**2 - 798*i - 2 Inquiry: Collect the terms in 4*b - 5*b + 43562806*b**2 - 3*b + 4*b - 43562804*b**2. Yields: 2*b**2 Inquiry: Collect the terms in 16*k - 6*k - 3*k + 37*k. Yields: 44*k Inquiry: Collect the terms in -191*w - 16 - 222*w + 2 + 533*w + 15. Yields: 120*w + 1 Inquiry: Collect the terms in -593*t - 592*t + 1185*t + t**3. Yields: t**3 Inquiry: Collect the terms in -41*h**3 + 38*h**3 + 0 + 4 - 5 - 4 - 475*h. Yields: -3*h**3 - 475*h - 5 Inquiry: Collect the terms in -5*b - 89679 + 89679 - 8*b - 20*b. Yields: -33*b Inquiry: Collect the terms in 1832*y - 615*y - 612*y - 614*y. Yields: -9*y Inquiry: Collect the terms in 22*d**2 + 31*d**2 + 0*d**2 + 32*d**2 - 24*d**2. Yields: 61*d**2 Inquiry: Collect the terms in -30*t + 2*t**3 + 16*t**3 + 45*t**3 + 30*t. Yields: 63*t**3 Inquiry: Collect the terms in -66*d - 61*d - 131*d - 142*d - 136*d. Yields: -536*d Inquiry: Collect the terms in -14971*s**3 - 11770*s + 14976*s**3 + 5874*s + 5896*s. Yields: 5*s**3 Inquiry: Collect the terms in -295*m**3 + 100*m**3 + 153*m**3. Yields: -42*m**3 Inquiry: Collect the terms in 7*i**3 + 8*i**3 - 14*i**3. Yields: i**3 Inquiry: Collect the terms in -10 - 492*q**3 + 1481*q**3 - 6 - 493*q**3 - 486*q**3 + 15. Yields: 10*q**3 - 1 Inquiry: Collect the terms in -44310702874 + x**3 + 44310702874. Yields: x**3 Inquiry: Collect the terms in -272 - 266 + 538 - 183763*n. Yields: -183763*n Inquiry: Collect the terms in 32*f**3 + 706*f**2 - 237*f**2 - 237*f**2 - 232*f**2 - 9*f**3. Yields: 23*f**3 Inquiry: Collect the terms in 52 - 52 - 10*k**2. Yields: -10*k**2 Inquiry: Collect the terms in 19*z**2 - 9*z + 5*z + 4*z. Yields: 19*z**2 Inquiry: Collect the terms in -7*v - 31*v - 3*v + 2*v + 2. Yields: -39*v + 2 Inquiry: Collect the terms in -504 + 157 + 181 - 8*t + 166. Yields: -8*t Inquiry: Collect the terms in -7*a**2 + 12*a**2 + 2 - 2. Yields: 5*a**2 Inquiry: Collect the terms in -69*b**3 + 31*b**3 + 36*b**3 + 66. Yields: -2*b**3 + 66 Inquiry: Collect the terms in 340*k**3 + 14*k - 37*k - 239*k**3 + 23*k - 102*k**3. Yields: -k**3 Inquiry: Collect the terms in -7072*i - 6796*i + 13854*i. Yields: -14*i Inquiry: Collect the terms in 0*k**3 + 77658 - 19*k**3 - 114011 + 36353. Yields: -19*k**3 Inquiry: Collect the terms in -698*y**3 + 2891*y**3 + 5816*y**3. Yields: 8009*y**3 Inquiry: Collect the terms in 3927 - 3927 - 3*t**3 - 21*t**2 + 2*t**2 + 19*t**2. Yields: -3*t**3 Inquiry: Collect the terms in -2 - 10 + 21 - 9 + 1252*z**2 - 909*z**2. Yields: 343*z**2 Inquiry: Collect the terms in 3*x - 2242 - 256*x + 2242. Yields: -253*x Inquiry: Collect the terms in 94 - 144 - 68 - 4*o. Yields: -4*o - 118 Inquiry: Collect the terms in 795*r + r**2 - 12*r**3 - r**2 + 11*r**3. Yields: -r**3 + 795*r Inquiry: Collect the terms in -9 + 18*s - 16*s - 8*s**2 - 2*s. Yields: -8*s**2 - 9 Inquiry: Collect the terms in 1192*c - 590*c - 574*c. Yields: 28*c Inquiry: Collect the terms in -12*p**2 + 62 + 9*p**2 + 4*p**2. Yields: p**2 + 62 Inquiry: Collect the terms in 23781 + 41*g**2 - 325*g**2 - 23781. Yields: -284*g**2 Inquiry: Collect the terms in 1070730*v**2 + 75619*v - 75619*v - 1070726*v**2. Yields: 4*v**2 Inquiry: Collect the terms in 22350*w**3 + 22383*w**3 - 44729*w**3. Yields: 4*w**3 Inquiry: Collect the terms in 9*h**3 + h**3 - 9*h**3. Yields: h**3 Inquiry: Collect the terms in -36650*m**3 - 37257*m**3 + 73911*m**3. Yields: 4*m**3 Inquiry: Collect the terms in -159*n - 154*n - 3 + 315*n + 3. Yields: 2*n Inquiry: Collect the terms in -141 + 77*f - 41*f - 76*f. Yields: -40*f - 141 Inquiry: Collect the terms in -2006*y**2 - 2133*y**2 + 6136*y**2 - 1996*y**2. Yields: y**2 Inquiry: Collect the terms in -4 - 4 - 377*j + 374*j - 5. Yields: -3*j - 13 Inquiry: Collect the terms in -18*c**2 + 83*c**2 - 43*c**2. Yields: 22*c**2 Inquiry: Collect the terms in -14*t - 11*t + 16*t + 26*t - 10*t. Yields: 7*t Inquiry: Collect the terms in 35*o - 35*o + 145*o**2. Yields: 145*o**2 Inquiry: Collect the terms in -6 - 13 + 21 - 10 + 3 + z. Yields: z - 5 Inquiry: Collect the terms in -17*r**3 - 22*r**3 - 17*r**3 - 15*r**3 + 73*r**3. Yields: 2*r**3 Inquiry: Collect the terms in -20 + 10 + 5*n + 8 + 2. Yields: 5*n Inquiry: Collect the terms in -4*w**2 - 23 - 179 + 63 + 5*w**2 + 6*w. Yields: w**2 + 6*w - 139 Inquiry: Collect the terms in 299*y**2 + 291*y**2 - 889*y**2 + 299*y**2 - 33255*y**3. Yields: -33255*y**3 Inquiry: Collect the terms in 10474*v**2 + v + 3 - 2666*v**2 + 41746*v**2 + 13054*v**2. Yields: 62608*v**2 + v + 3 Inquiry: Collect the terms in -2*d**2 - 54*d**3 + 2*d**2 + 60*d**3. Yields: 6*d**3 Inquiry: Collect the terms in -84*a**3 + 44*a**3 + 41*a**3. Yields: a**3 Inquiry: Collect the terms in -3862692*r + 1931340*r + 1931326*r - r**2. Yields: -r**2 - 26*r Inquiry: Collect the terms in 1010*v - 5 + 0 + 137*v - 1138*v + 1 + 0. Yields: 9*v - 4 Inquiry: Collect the terms in 1113*n**3 - 306013*n**2 + 306013*n**2. Yields: 1113*n**3 Inquiry: Collect the terms in 2 - 5*c**2 - 2 - 3*c**2. Yields: -8*c**2 Inquiry: Collect the terms in 47*p**3 + 49*p**3 + 47*p**3 - 185*p**3 + 40*p**3. Yields: -2*p**3 Inquiry: Collect the terms in 9292082 - 9292082 + 543*o. Yields: 543*o Inquiry: Collect the terms in 259*f + 11*f**3 - 259*f. Yields: 11*f**3 Inquiry: Collect the terms in 23831*k - 95343*k + 23834*k + 23830*k + 23843*k. Yields: -5*k Inquiry: Collect the terms in 1 + 1 - 44 + 45062*j**2. Yields: 45062*j**2 - 42 Inquiry: Collect the terms in d - 4*d - 8*d - 5*d + 18*d. Yields: 2*d Inquiry: Collect the terms in -139*v - 1208*v**3 + 139*v. Yields: -1208*v**3 Inquiry: Collect the terms in -660*t + 322*t + 330*t + 3. Yields: -8*t + 3 Inquiry: Collect the terms in 40*b + 14*b**3 + 3*b - 5*b + 20*b**2. Yields: 14*b**3 + 20*b**2 + 38*b Inquiry: Collect the terms in 10032*r - 20063*r + 10034*r. Yields: 3*r Inquiry: Collect the terms in 2*d - 6*d**2 + 3*d**2 + 5953 - d - 6*d. Yields: -3*d**2 - 5*d + 5953 Inquiry: Collect the terms in -241*x - 113*x - 177*x. Yields: -531*x Inquiry: Collect the terms in 3*f + 8*f - f. Yields: 10*f Inquiry: Collect the terms in v**2 - 7 - 94*v + 13 + 94*v. Yields: v**2 + 6 Inquiry: Collect the terms in 1 + 2*x**3 + 2 + 34709*x - 96134*x. Yields: 2*x**3 - 61425*x + 3 Inquiry: Collect the terms in 185489*k**2 + 26389156 - 26389156. Yields: 185489*k**2 Inquiry: Collect the terms in -101*u**2 - 90*u**2 - 68*u**2 + 89*u**2. Yields: -170*u**2 Inquiry: Collect the terms in -302*g**2 + 944*g**2 - 336*g**2 - 308*g**2. Yields: -2*g**2 Inquiry: Collect the terms in -4*c**2 + 40870*c - 20434*c - 20436*c - 9*c**2. Yields: -13*c**2 Inquiry: Collect the terms in -20*u**3 + 15*u**3 - 29*u**3 - 19*u**3 - 23*u**3. Yields: -76*u**3 Inquiry: Collect the terms in -9*k**3 + 18*k**3 + 2441 - 2441. Yields: 9*k**3 Inquiry: Collect the terms in 3 + 7*a - 6 + 3 - 8*a. Yields: -a Inquiry: Collect the terms in 10020*q**2 + 8982*q**2 - 19001*q**2. Yields: q**2 Inquiry: Collect the terms in -25*k**2 - 81*k**2 - 25*k**2 + 163*k**2 - 30*k**2. Yields: 2*k**2 Inquiry: Collect the terms in -2110*y - 25 + 28 - 3. Yields: -2110*y Inquiry: Collect the terms in 48*p - 18*p + 38*p. Yields: 68*p Inquiry: Collect the terms in -30*l**2 + 11 - 15 + 99*l**2 + 4. Yields: 69*l**2 Inquiry: Collect the terms in -46 + 11 - 1875880*m + 14 - 16 + 1875882*m. Yields: 2*m - 37 Inquiry: Collect the terms in -3*q**2 + 650*q - 650*q. Yields: -3*q**2 Inquiry: Collect the terms in -2*b**2 - 790 + 1728 - 850. Yields: -2*b**2 + 88 Inquiry: Collect the terms in 391 - 81 + 10*d - 255 - 58. Yields: 10*d - 3 Inquiry: Collect the terms in -72318*q**3 - 5 - 55009*q**3 + 5. Yields: -127327*q**3 Inquiry: Collect the terms in 17*w + 4*w - 19*w. Yields: 2*w Inquiry: Collect the terms in -22*g + 7531 - 3769 - 3762. Yields: -22*g Inquiry: Collect the terms in 773 + c + 771 - 2316 + 772. Yields: c Inquiry: Collect the terms in -2*q + 19 - 11 - 8. Yields: -2*q Inquiry: Collect the terms in -34423 - 70*n + 34423. Yields: -70*n Inquiry: Collect the terms in 5*w - 12*w + w + w. Yields: -5*w Inquiry: Collect the terms in -2 - 6*r**3 + 3 + 0. Yields: -6*r**3 + 1 Inquiry: Collect the terms in 15*u + 65*u + 60*u + 54*u - 174 + 169. Yields: 194*u - 5 Inquiry: Collect the terms in -2 - 3*g - 4*g - 11*g. Yields: -18*g - 2 Inquiry: Collect the terms in 156 - 311 - 42655*p**3 + 42699*p**3 + 156. Yields: 44*p**3 + 1 Inquiry: Collect the terms in -18*g**2 - 13*g**2 + 43*g**2 - 15*g**2. Yields: -3*g**2 Inquiry: Collect the terms in -7*o - o**2 + 7*o + 227 - 574. Yields: -o**2 - 347 Inquiry: Collect the terms in 144 - 144 + 3069830978*s**2 - 3069830979*s**2. Yields: -s**2 Inquiry: Collect the terms in -7*x**3 - 10*x**3 - 3*x**3 - 8*x**3 + 22*x**3. Yields: -6*x**3 Inquiry: Collect the terms in 0*g + 0*g + 89*g**2 - 80*g**2. Yields: 9*g**2 Inquiry: Collect the terms in -28*v + 22*v + 6*v + 131*v**2. Yields: 131*v**2 Inquiry: Collect the terms in 15 + 31*q**3 - 40*q**3 + 29*q**3. Yields: 20*q**3 + 15 Inquiry: Collect the terms in 3058*f**3 - 9119*f**3 + 6047*f**3. Yields: -14*f**3 Inquiry: Collect the terms in 22*f + 21*f - 34*f + 0*f + 3*f - 6*f. Yields: 6*f Inquiry: Collect the terms in -942*f**2 - 323*f**2 - 54*f**2 - 1233*f**2 + 504*f**2. Yields: -2048*f**2 Inquiry: Collect the terms in 1434*q + 1430*q - 24 - 2892*q + 24. Yields: -28*q Inquiry: Collect the terms in -17523*h**2 + 8091*h**2 + 9431*h**2. Yields: -h**2 Inquiry: Collect the terms in -5 - 19*p**2 + 13 - 61*p**2 - 13*p**2 - 32*p**2 + 5*p**2. Yields: -120*p**2 + 8 Inquiry: Collect the terms in -18602*z**3 + 10537*z**3 - 17323*z**3. Yields: -25388*z**3 Inquiry: Collect the terms in -815*x + 1624*x - 810*x. Yields: -x Inquiry: Collect the terms in -10*w + 2*w + 8*w + 973*w**3. Yields: 973*w**3 Inquiry: Collect the terms in 5*b + 16 - 14*b - 16. Yields: -9*b Inquiry: Collect the terms in 39*l - 138*l + 20*l - 148*l. Yields: -227*l Inquiry: Collect the terms in 6*w + 21*w + 16*w - 66*w. Yields: -23*w Inquiry: Collect the terms in -48*x**2 + 15*x**2 + 7*x**3 + 19*x**2 + 7*x**3 + 15*x**2. Yields: 14*x**3 + x**2 Inquiry: Collect the terms in -1976 + 977 + 999 - 15*c. Yields: -15*c Inquiry: Collect the terms in 499*q**3 - 167*q**3 - 170*q**3 - 173*q**3. Yields: -11*q**3 Inquiry: Collect the terms in 0*r**3 - r**3 + 4835*r**2 - 14507*r**2 + 4832*r**2 + 4840*r**2. Yields: -r**3 Inquiry: Collect the terms in -19*k**2 + 30*k**2 - 37*k**2 - 76*k**2. Yields: -102*k**2 Inquiry: Collect the terms in -10*b + 329 + 84*b + 73*b - 329. Yields: 147*b Inquiry: Collect the terms in 150*a**2 - 275*a**2 - 3 + a + 125*a**2 + 11*a**3 - 2*a. Yields: 11*a**3 - a - 3 Inquiry: Collect the terms in 711*y**3 + 2 + 2 - 650*y**3 - 5. Yields: 61*y**3 - 1 Inquiry: Collect the terms in 77 + 82 - 241 - 6*m**3 + 82. Yields: -6*m**3 Inquiry: Collect the terms in -9*j**3 + 2*j**3 - 4*j**3 + 2*j**3 + j**3. Yields: -8*j**3 Inquiry: Collect the terms in -95 + 41 - 4*i**2 + 54. Yields: -4*i**2 Inquiry: Collect the terms in 72*a**2 + 150*a**2 - 20467*a + 20467*a. Yields: 222*a**2 Inquiry: Collect the terms in -8 + 7827*g - 869*g + 965*g + 9. Yields: 7923*g + 1 Inquiry: Collect the terms in 8*w + 6*w - 14*w + 12*w**3. Yields: 12*w**3 Inquiry: Collect the terms in 6*n - 11*n + 7*n + 1 - n. Yields: n + 1 Inquiry: Collect the terms in -26*t + 25*t + 62*t. Yields: 61*t Inquiry: Collect the terms in -70783968828002*l - 3 + 70783968827999*l + 3. Yields: -3*l Inquiry: Collect the terms in 151*o**2 - 2 + 2 - 149*o**2. Yields: 2*o**2 Inquiry: Collect the terms in 2*i**3 - 4557*i**2 + 4557*i**2. Yields: 2*i**3 Inquiry: Collect the terms in -4 + 51*r**2 + 2 - 10749509*r + 10749509*r. Yields: 51*r**2 - 2 Inquiry: Collect the terms in 3*l - 3*l - 3*l**2 + 0*l. Yields: -3*l**2 Inquiry: Collect the terms in -663*g**2 - 807*g**2 + 1477*g**2 + 0*g - 2*g. Yields: 7*g**2 - 2*g Inquiry: Collect the terms in 10686*d + 5193*d + 35301*d. Yields: 51180*d Inquiry: Collect the terms in 166*n + 153*n + 176*n + 188*n - 725*n. Yields: -42*n Inquiry: Collect the terms in -1013166*z + 1013160*z + 6 + 1 - 2 - 5. Yields: -6*z<|endoftext|>arithmetic: nearest integer root -------------------------------- Q-: What is the square root of 7222 to the nearest integer? Response: 85 Q-: What is 3948 to the power of 1/4, to the nearest integer? Response: 8 Q-: What is 2429 to the power of 1/7, to the nearest integer? Response: 3 Q-: What is 20438069 to the power of 1/9, to the nearest integer? Response: 6 Q-: What is the square root of 3545 to the nearest integer? Response: 60 Q-: What is the tenth root of 4542633259 to the nearest integer? Response: 9 Q-: What is the cube root of 1154 to the nearest integer? Response: 10 Q-: What is the square root of 410809136 to the nearest integer? Response: 20268 Q-: What is the cube root of 30902724 to the nearest integer? Response: 314 Q-: What is 1457980425 to the power of 1/3, to the nearest integer? Response: 1134 Q-: What is 4318266209 to the power of 1/2, to the nearest integer? Response: 65714 Q-: What is 32502364 to the power of 1/10, to the nearest integer? Response: 6 Q-: What is the square root of 2049669 to the nearest integer? Response: 1432 Q-: What is the fourth root of 3327 to the nearest integer? Response: 8 Q-: What is the third root of 1969 to the nearest integer? Response: 13 Q-: What is 3674 to the power of 1/5, to the nearest integer? Response: 5 Q-: What is the square root of 1028748592 to the nearest integer? Response: 32074 Q-: What is 3206880 to the power of 1/8, to the nearest integer? Response: 7 Q-: What is the third root of 1464674 to the nearest integer? Response: 114 Q-: What is the square root of 444 to the nearest integer? Response: 21 Q-: What is the square root of 1722146387 to the nearest integer? Response: 41499 Q-: What is the eighth root of 655347 to the nearest integer? Response: 5 Q-: What is 66017 to the power of 1/9, to the nearest integer? Response: 3 Q-: What is 79412178 to the power of 1/3, to the nearest integer? Response: 430 Q-: What is 365002 to the power of 1/2, to the nearest integer? Response: 604 Q-: What is 1984814 to the power of 1/9, to the nearest integer? Response: 5 Q-: What is 18269 to the power of 1/5, to the nearest integer? Response: 7 Q-: What is 336362 to the power of 1/8, to the nearest integer? Response: 5 Q-: What is the square root of 745516987 to the nearest integer? Response: 27304 Q-: What is the cube root of 604 to the nearest integer? Response: 8 Q-: What is the square root of 265695315 to the nearest integer? Response: 16300 Q-: What is the square root of 16452 to the nearest integer? Response: 128 Q-: What is 58598595 to the power of 1/2, to the nearest integer? Response: 7655 Q-: What is 769 to the power of 1/2, to the nearest integer? Response: 28 Q-: What is the tenth root of 8228486 to the nearest integer? Response: 5 Q-: What is the fourth root of 377733125 to the nearest integer? Response: 139 Q-: What is the cube root of 1711178 to the nearest integer? Response: 120 Q-: What is the eighth root of 595585 to the nearest integer? Response: 5 Q-: What is the cube root of 1448102 to the nearest integer? Response: 113 Q-: What is 132818494 to the power of 1/2, to the nearest integer? Response: 11525 Q-: What is the fourth root of 121631696 to the nearest integer? Response: 105 Q-: What is 138632686 to the power of 1/9, to the nearest integer? Response: 8 Q-: What is 7180 to the power of 1/9, to the nearest integer? Response: 3 Q-: What is the sixth root of 2101722694 to the nearest integer? Response: 36 Q-: What is the ninth root of 4574351 to the nearest integer? Response: 5 Q-: What is 780144 to the power of 1/10, to the nearest integer? Response: 4 Q-: What is the eighth root of 2945 to the nearest integer? Response: 3 Q-: What is the square root of 192363529 to the nearest integer? Response: 13870 Q-: What is the square root of 5637 to the nearest integer? Response: 75 Q-: What is 1394 to the power of 1/2, to the nearest integer? Response: 37 Q-: What is 2093022340 to the power of 1/3, to the nearest integer? Response: 1279 Q-: What is 24327699 to the power of 1/4, to the nearest integer? Response: 70 Q-: What is the third root of 23205 to the nearest integer? Response: 29 Q-: What is the third root of 1216 to the nearest integer? Response: 11 Q-: What is 52027 to the power of 1/2, to the nearest integer? Response: 228 Q-: What is the square root of 284662358 to the nearest integer? Response: 16872 Q-: What is the cube root of 137082 to the nearest integer? Response: 52 Q-: What is the ninth root of 8662764 to the nearest integer? Response: 6 Q-: What is 1500 to the power of 1/3, to the nearest integer? Response: 11 Q-: What is the square root of 19295 to the nearest integer? Response: 139 Q-: What is 313 to the power of 1/2, to the nearest integer? Response: 18 Q-: What is the tenth root of 1606881 to the nearest integer? Response: 4 Q-: What is the sixth root of 15590175 to the nearest integer? Response: 16 Q-: What is the third root of 1095 to the nearest integer? Response: 10 Q-: What is 12568 to the power of 1/2, to the nearest integer? Response: 112 Q-: What is 368265 to the power of 1/3, to the nearest integer? Response: 72 Q-: What is 237622 to the power of 1/2, to the nearest integer? Response: 487 Q-: What is 7586167291 to the power of 1/9, to the nearest integer? Response: 13 Q-: What is 2357 to the power of 1/6, to the nearest integer? Response: 4 Q-: What is the square root of 3334 to the nearest integer? Response: 58 Q-: What is the third root of 9513 to the nearest integer? Response: 21 Q-: What is 76770 to the power of 1/2, to the nearest integer? Response: 277 Q-: What is the ninth root of 53596 to the nearest integer? Response: 3 Q-: What is 1714057912 to the power of 1/9, to the nearest integer? Response: 11 Q-: What is the fourth root of 85119 to the nearest integer? Response: 17 Q-: What is 84938 to the power of 1/3, to the nearest integer? Response: 44 Q-: What is the tenth root of 73466 to the nearest integer? Response: 3 Q-: What is the eighth root of 37745005 to the nearest integer? Response: 9 Q-: What is 137268470 to the power of 1/2, to the nearest integer? Response: 11716 Q-: What is 2462686 to the power of 1/3, to the nearest integer? Response: 135 Q-: What is 107665355 to the power of 1/4, to the nearest integer? Response: 102 Q-: What is 2709 to the power of 1/3, to the nearest integer? Response: 14 Q-: What is the square root of 314577 to the nearest integer? Response: 561 Q-: What is the third root of 3015516233 to the nearest integer? Response: 1445 Q-: What is the square root of 186011797 to the nearest integer? Response: 13639 Q-: What is 121990 to the power of 1/8, to the nearest integer? Response: 4 Q-: What is 942146009 to the power of 1/4, to the nearest integer? Response: 175 Q-: What is 3681 to the power of 1/2, to the nearest integer? Response: 61 Q-: What is 537118 to the power of 1/3, to the nearest integer? Response: 81 Q-: What is the square root of 183258 to the nearest integer? Response: 428 Q-: What is 172572 to the power of 1/3, to the nearest integer? Response: 56 Q-: What is the eighth root of 27144 to the nearest integer? Response: 4 Q-: What is the third root of 750455268 to the nearest integer? Response: 909 Q-: What is 48366 to the power of 1/3, to the nearest integer? Response: 36 Q-: What is 773973 to the power of 1/2, to the nearest integer? Response: 880 Q-: What is the sixth root of 869 to the nearest integer? Response: 3 Q-: What is 775964 to the power of 1/3, to the nearest integer? Response: 92 Q-: What is 133864723 to the power of 1/3, to the nearest integer? Response: 512 Q-: What is 32632 to the power of 1/2, to the nearest integer? Response: 181 Q-: What is the tenth root of 106488 to the nearest integer? Response: 3 Q-: What is the third root of 4259480 to the nearest integer? Response: 162 Q-: What is 120297620 to the power of 1/2, to the nearest integer? Response: 10968 Q-: What is 35629301 to the power of 1/3, to the nearest integer? Response: 329 Q-: What is 18123 to the power of 1/3, to the nearest integer? Response: 26 Q-: What is the square root of 2453392 to the nearest integer? Response: 1566 Q-: What is the fourth root of 3973 to the nearest integer? Response: 8 Q-: What is 9299235 to the power of 1/10, to the nearest integer? Response: 5 Q-: What is 49411308 to the power of 1/5, to the nearest integer? Response: 35 Q-: What is the ninth root of 48686575 to the nearest integer? Response: 7 Q-: What is 106733050 to the power of 1/2, to the nearest integer? Response: 10331 Q-: What is the tenth root of 2129004 to the nearest integer? Response: 4 Q-: What is the seventh root of 2585933 to the nearest integer? Response: 8 Q-: What is 13776816 to the power of 1/2, to the nearest integer? Response: 3712 Q-: What is 6802 to the power of 1/7, to the nearest integer? Response: 4 Q-: What is the fifth root of 533748361 to the nearest integer? Response: 56 Q-: What is 358728938 to the power of 1/10, to the nearest integer? Response: 7 Q-: What is 7307408 to the power of 1/2, to the nearest integer? Response: 2703 Q-: What is 19299 to the power of 1/2, to the nearest integer? Response: 139 Q-: What is the ninth root of 1335957 to the nearest integer? Response: 5 Q-: What is the third root of 54089 to the nearest integer? Response: 38 Q-: What is 56426 to the power of 1/2, to the nearest integer? Response: 238 Q-: What is the fifth root of 1493019257 to the nearest integer? Response: 68 Q-: What is the square root of 6260680 to the nearest integer? Response: 2502 Q-: What is 16209 to the power of 1/3, to the nearest integer? Response: 25 Q-: What is the square root of 1986555 to the nearest integer? Response: 1409 Q-: What is the square root of 97457 to the nearest integer? Response: 312 Q-: What is the ninth root of 391249661 to the nearest integer? Response: 9 Q-: What is 1232456 to the power of 1/5, to the nearest integer? Response: 17 Q-: What is 744 to the power of 1/6, to the nearest integer? Response: 3 Q-: What is 14250 to the power of 1/8, to the nearest integer? Response: 3 Q-: What is the third root of 5329 to the nearest integer? Response: 17 Q-: What is 155801 to the power of 1/2, to the nearest integer? Response: 395 Q-: What is the eighth root of 4218479608 to the nearest integer? Response: 16 Q-: What is 770 to the power of 1/2, to the nearest integer? Response: 28 Q-: What is the third root of 40736 to the nearest integer? Response: 34 Q-: What is the third root of 557068 to the nearest integer? Response: 82 Q-: What is 31739693 to the power of 1/10, to the nearest integer? Response: 6 Q-: What is the third root of 261361958 to the nearest integer? Response: 639 Q-: What is the sixth root of 241079 to the nearest integer? Response: 8 Q-: What is 36538237 to the power of 1/7, to the nearest integer? Response: 12 Q-: What is the square root of 5483941 to the nearest integer? Response: 2342 Q-: What is 14092554 to the power of 1/3, to the nearest integer? Response: 242 Q-: What is 33568 to the power of 1/2, to the nearest integer? Response: 183 Q-: What is the third root of 216666860 to the nearest integer? Response: 601 Q-: What is the third root of 280129679 to the nearest integer? Response: 654 Q-: What is 199214982 to the power of 1/2, to the nearest integer? Response: 14114 Q-: What is 102155 to the power of 1/5, to the nearest integer? Response: 10 Q-: What is 59842 to the power of 1/8, to the nearest integer? Response: 4 Q-: What is 33961069 to the power of 1/2, to the nearest integer? Response: 5828 Q-: What is the cube root of 212955 to the nearest integer? Response: 60 Q-: What is 28998768 to the power of 1/5, to the nearest integer? Response: 31 Q-: What is 8182497 to the power of 1/5, to the nearest integer? Response: 24 Q-: What is 5429601 to the power of 1/2, to the nearest integer? Response: 2330 Q-: What is 241 to the power of 1/3, to the nearest integer? Response: 6 Q-: What is 3050706 to the power of 1/5, to the nearest integer? Response: 20 Q-: What is the ninth root of 7105590617 to the nearest integer? Response: 12 Q-: What is 318358 to the power of 1/10, to the nearest integer? Response: 4 Q-: What is 497132653 to the power of 1/5, to the nearest integer? Response: 55 Q-: What is 45910 to the power of 1/8, to the nearest integer? Response: 4 Q-: What is 2194832294 to the power of 1/3, to the nearest integer? Response: 1300 Q-: What is the fourth root of 227584 to the nearest integer? Response: 22 Q-: What is the cube root of 1286 to the nearest integer? Response: 11 Q-: What is 8642624 to the power of 1/3, to the nearest integer? Response: 205 Q-: What is the third root of 68331 to the nearest integer? Response: 41 Q-: What is 125106 to the power of 1/6, to the nearest integer? Response: 7 Q-: What is 60566898 to the power of 1/2, to the nearest integer? Response: 7782 Q-: What is the tenth root of 39250326 to the nearest integer? Response: 6 Q-: What is the third root of 421 to the nearest integer? Response: 7 Q-: What is the square root of 1144504 to the nearest integer? Response: 1070 Q-: What is the fourth root of 13680383 to the nearest integer? Response: 61 Q-: What is the square root of 6987265 to the nearest integer? Response: 2643 Q-: What is the third root of 18881 to the nearest integer? Response: 27 Q-: What is 999 to the power of 1/5, to the nearest integer? Response: 4 Q-: What is 21695181 to the power of 1/10, to the nearest integer? Response: 5 Q-: What is the third root of 686178891 to the nearest integer? Response: 882 Q-: What is 5464520 to the power of 1/3, to the nearest integer? Response: 176 Q-: What is the square root of 10795358 to the nearest integer? Response: 3286 Q-: What is 68391 to the power of 1/3, to the nearest integer? Response: 41 Q-: What is 1139545101 to the power of 1/7, to the nearest integer? Response: 20 Q-: What is the fifth root of 13138 to the nearest integer? Response: 7 Q-: What is 311465694 to the power of 1/8, to the nearest integer? Response: 12 Q-: What is the seventh root of 50731 to the nearest integer? Response: 5 Q-: What is the cube root of 1740238 to the nearest integer? Response: 120 Q-: What is 33223 to the power of 1/4, to the nearest integer? Response: 14 Q-: What is 33166814 to the power of 1/3, to the nearest integer? Response: 321 Q-: What is the seventh root of 4470982652 to the nearest integer? Response: 24
[{"idx": "txt360/polynomials__collect_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-9.jsonl"}, {"idx": "txt360/arithmetic__nearest_integer_root_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-9.jsonl"}]
#!/bin/bash usage () { echo $'\n'"Usage: $0 [-b] [-r] [-l] [-k]"; exit 1; } while [[ "$#" -gt 0 ]]; do case $1 in -b|--build) docker build ./ -t osk; break ;; -r|--run) docker run --rm -it -d --name osk -v $(pwd):/root/env osk; docker exec -it osk bash; break ;; -l|--launch) qemu-system-x86_64 -L /usr/share/qemu/ -cdrom dist/x86_64/kernel.iso; break ;; -k|--kill) docker container kill osk; break ;; *) usage; exit 1 ;; esac done<|endoftext|>#!/bin/bash ################################################################### # Setup ################################################################### function before_linux () { if [[ ${NAME} == "ValgrindTest" ]]; then sudo apt-get update sudo apt-get install libc6-dbg sudo apt-get install -f valgrind fi } ################################################################### # Main Execution ################################################################### if [[ $TRAVIS_OS_NAME == "linux" ]]; then before_linux fi<|endoftext|>#!/bin/bash scriptdir=$(realpath $(dirname "$0")) source ${scriptdir}/common.sh source ${scriptdir}/functions.sh CONTRAIL_SETUP_DOCKER=${CONTRAIL_SETUP_DOCKER:-1} [[ "$CONTRAIL_SETUP_DOCKER" != 1 ]] && { echo "INFO: setup docker skipped" && exit ; } if [ $DISTRO == "macosx" ] ; then registry_ip=$(${scriptdir}/setup_docker_macosx.sh | awk '/^REGISTRY_IP: .*/{print($2)}' | head -n 1) else registry_ip=$(sudo -E ${scriptdir}/setup_docker_root.sh | awk '/^REGISTRY_IP: .*/{print($2)}' | head -n 1) fi export REGISTRY_IP=${registry_ip} save_tf_devenv_profile<|endoftext|>DIR=$(dirname $0) count=$1 echo "sentinel count:"$count startPort=$2 function startSentinel() { currentPort=$1 sleep=$2 if [ -z $sleep ]; then sleep=1 fi echo ========start sentinel $currentPort================= rm -rf $DIR/$currentPort mkdir -p $DIR/$currentPort cp $DIR/template/sentinel.sh $DIR/template/sentinel.conf $DIR/$currentPort sh $DIR/$currentPort/sentinel.sh echo "start sentinel: $DIR/$currentPort" } for ((i = 0; i < $count; i++)); do port=$(($startPort + $i)) startSentinel $port 0 done<|endoftext|>#!/usr/bin/env bash # AUTHOR: fuzx # FILE: run.sh # ROLE: TODO (some explanation) # CREATED: 2017-06-13 20:56:12 # MODIFIED: 2017-12-06 10:39:36 num=7000 head -n $num q.txt > q_train.txt head -n $num q.txt > r_train.txt head -n $num s.txt > s_train.txt tail -n 500 q.txt > q_tmp.txt tail -n 500 q.txt > r_tmp.txt tail -n 500 s.txt > s_tmp.txt head -n 1000 q_tmp.txt > q_val.txt head -n 1000 r_tmp.txt > r_val.txt head -n 1000 s_tmp.txt > s_val.txt tail -n 500 q_tmp.txt > q_test.txt tail -n 500 r_tmp.txt > r_test.txt tail -n 500 s_tmp.txt > s_text.txt<|endoftext|>#!/bin/sh # openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 3650 -nodes # openssl x509 -inform PEM -in cert.pem -outform DER -out cert.cer # openssl x509 -inform PEM -in key.pem -outform DER -out key.cer #docker build . --squash -t gmommoutlook/grader:slim-1.0 #docker build . -f ./Dockerfile-flask -t gmommoutlook/grader:slim-flask-1.0 # kubectl create secret tls tlssecret --cert=./cert.pem --key=./key.pem #docker push gmommoutlook/grader:slim-flask-1.0 docker build . -t gmommoutlook/grader:slim-1.0 docker push gmommoutlook/grader:slim-1.0<|endoftext|>#!/usr/bin/env bash echo -n "Testing trace_analyser.py..." OUT=traces1_analysed.txt python ../trace_analyser.py fixtures/traces1.json >$OUT diff $OUT expected && echo " passed" && rm -r $OUT echo -n "Testing trace_generator.py..." rm -r out.json 2>/dev/null LOG=soap.log python ../trace_generator.py --seed 1234 -i fixtures/inputs1.csv [IDX] >$LOG diff $LOG expected && echo " passed" && rm -f $LOG echo "Checking out.json -- just the date should be different:" diff out.json expected # comment this next line out if you want to preserve out.json: rm -f out.json<|endoftext|>#!/usr/bin/env bash set -eu declare -r package="lua-evdev" declare version="${1:-}" if [[ -z "${version}" ]]; then echo "missing version" >&2 exit 1 fi if [[ "${version}" != *"-"* ]]; then version="${version}-1" fi shift declare -r rockspec="rockspecs/${package}-${version}.rockspec" if ! test -f ${rockspec}; then echo "missing rockspec: ${rockspec}" >&2 exit 1 fi declare force_upload="" if [[ "${LUAROCKS_UPLOAD_FORCE:-"false"}" = "true" ]]; then force_upload="--force" fi luarocks upload --api-key=${LUAROCKS_API_KEY} ${force_upload} ${rockspec}<|endoftext|>#!/bin/sh counter=1 DIRECTORY=/var/crash DEPTH=5 mkdir -p "$DIRECTORY" cd ${DIRECTORY} MAX_HISTORIC=$(ls -1 | wc -l) if [ $MAX_HISTORIC -gt $DEPTH ]; then #cleanup history ls -1 | sort -g | head -n $(($MAX_HISTORIC -$DEPTH +1)) | xargs --no-run-if-empty rm fi #get counter value count=`ls -1 | sort -g | tail -n 1 | cut -d '_' -f 1` count=$(($count + 1)) #register new dump timestamp=$(date +%F_%H-%M-%S) filename=${count}_m4-fw-error_${timestamp}.dump cat /sys/${DEVPATH}/data > ${filename} echo 1 > /sys/${DEVPATH}/data # synchronize filesystem sync cd -<|endoftext|>#!/bin/bash set -e ROOT="$(pwd)" SRC=${ROOT}/src LUPDATE_BIN=${LUPDATE_BIN:-lupdate} ############################################################################### readarray -d '' SOURCE_FILES < <(find "$SRC" -regex '.*\.\(h\|cpp\|ui\)' -type f -print0) update_file() { ts_file="$1" echo "Updating $ts_file..." # Update .ts $LUPDATE_BIN "${SOURCE_FILES[@]}" -locations "absolute" -ts "$ts_file" } cd "$ROOT" if [ -n "$1" ]; then update_file "$1" else for f in *.ts; do update_file "$f" done update_file .template.ts fi<|endoftext|>#!/bin/bash # This is the main build script. set -euo pipefail # cd to the directory of this script # This makes the script work even when invoked from elsewhere cd "$(dirname "$0")" mkdir -p dist # Format javascript and css yarn run prettier --write --loglevel warn "src/**/*.ts" "src/**/*.css" "html/**/*.html" package.json # independent cp -R favicon/* dist/ # copy contents of dir cp -R html/* dist/ node data/compile-unicode-data.js # also depends only on compile-unicode-data cargo fmt --manifest-path wasm/Cargo.toml wasm-pack build wasm yarn run webpack<|endoftext|>#!/bin/bash #Exit on failures set -e set -x JOB_NAME=${TRAVIS_JOB_NAME:-CentOS 7} arr=($JOB_NAME) os_name=${arr[0]:-CentOS} release=${arr[1]:-7} # CentOS 7 doesn't have autopep8, so we'll drop the requirement for it # This implementation will still allow it to occur if autopep8 still shows # up later. COMMON_MESON_ARGS="-Dtest_dirty_git=false -Ddeveloper_build=false -Dpython_name=python3.6" pushd /builddir/ # Build the code under GCC and run standard tests meson --buildtype=debug \ $COMMON_MESON_ARGS \ travis ninja-build -C travis test popd #builddir<|endoftext|>#!/bin/bash # When send a command, \r for it to execute ssh_port="22" ssh_user="root" ssh_home="/root" ssh_prompt="]# " ssh_passwd="" server_ip=( # mark server list here, one per line "127.0.0.1" ) i=0 min_index=1 max_index=16 # loop to check #core ranges from [min_index, max_index] for ((i = min_index; i <= $max_index ; ++i)); do ./conf.exp ${server_ip[0]} $ssh_port $ssh_user $ssh_home $ssh_prompt $ssh_passwd $i # Parallel executing, with &/wait # ./ssh.exp ${server_ip[$i]} $ssh_port $ssh_user $ssh_home $ssh_prompt $ssh_passwd & done wait echo "All Done!"<|endoftext|>#!/bin/bash # SCRIPT FOR CREATING LABPETRI TABLES ############################################################## clear echo "#######################################################" echo " truncate: labeptri tables " echo "#######################################################" mysql --user=root --password=<PASSWORD> -e "source /var/www/html/sql/truncate/tables.sql" cd /var/www/html/users cp -rf ./pictures ../ echo "#######################################################" echo " done " echo "#######################################################"<|endoftext|>#!/bin/sh set -e [ -f scripts/local.sh ] && . scripts/local.sh if [ -n "$COVERAGE" ]; then find test -name 'bisect*.out' -delete fi if [ -z "$LIT_ARGS" ]; then LIT_ARGS="-v -s --no-progress-bar" fi echo "Testing foundry..." OCAMLRUNPARAM=Rb ./test_foundry.native; echo (ulimit -t 5 ; ulimit -d 512000 ; ulimit -m 512000 ; ulimit -s 8192 ./vendor/lit/lit.py $LIT_ARGS test/) if [ -n "$COVERAGE" ]; then echo "Generating coverage..." (cd _build; bisect-report -html ../coverage `find ../test -name 'bisect*.out'`; find ../test -name 'bisect*.out' -delete) fi<|endoftext|>#!/usr/bin/env bash echo "Running ${BASH_SOURCE[0]}" echo "Version before install:" gcloud version || true if [ ! -d "$HOME/google-cloud-sdk/bin" ]; then echo "Installing gcloud" rm -rf $HOME/google-cloud-sdk; export CLOUDSDK_CORE_DISABLE_PROMPTS=1; curl [IDX] | bash; ./gradle/firebase/auth.sh gcloud init --console-only else echo "Found 'gcloud' installed" fi source $HOME/google-cloud-sdk/path.bash.inc echo "Version after install" gcloud version echo "Update gcloud components" gcloud --quiet components update echo "List components: " gcloud components list<|endoftext|># # Completion # # [IDX] ALWAYS_TO_END setopt AUTO_LIST setopt AUTO_MENU setopt AUTO_PARAM_SLASH setopt AUTO_REMOVE_SLASH setopt COMPLETE_IN_WORD setopt GLOB_COMPLETE setopt LIST_PACKED setopt MENU_COMPLETE # TAB-complete partial file names or paths # [IDX] ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*' # highlight the currently active menu choice # [IDX] ':completion:*' menu select # The following lines were added by compinstall zstyle :compinstall filename ~/.zshrc autoload -Uz compinit compinit # End of lines added by compinstall<|endoftext|>#!/bin/bash # # Author: Spacecow # Date: 06/03/2016 # Description: # Renames files listed in specified text file. # File names must be seperated by -> # # Example: $ cat list.txt # file_old -> file_new # file_old -> file_new function rename() { local ARR=(${1//->/}) mv "${ARR[0]}" "${ARR[1]}" } function main() { if [ ${#} -ne 1 ]; then printf "${0} <FILE>\n" 1>&2 exit 1 fi if [ ! -f "${1}" ]; then printf "${0}: File Error: File '${1}' not found\n" 1>&2 exit 2 fi while read LINE; do rename "${LINE}" done < ${1} } main "$@"
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-17629.jsonl"}]
Android how to detect which tablerow was clicked Question: In my fragment layout I've a tablelayout like this: <code> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TableLayout android:id="@+id/tableLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent"> </TableLayout> </LinearLayout> </code> In this tablelayout, I add programmatically multiple tablerows with a view inside like this: <code>for(int i = 0; i < 5;){ tableLayout.addView(createTableRow((LocationObject)objectList.get(i)), i); } </code> - <code>private View createTableRow(LocationObject locObject) { TableRow tr = new TableRow(getActivity()); View v = LayoutInflater.from(getActivity()).inflate(R.layout.view_layout, tr, false); TextView textViewName = (TextView) v.findViewById(R.id.textView_name); textViewName.setText(locObject.getTitle()); TextView textViewProvider = (TextView) v.findViewById(R.id.textView_provider); textViewProvider.setText(locObject.getSubTitle()); return v; } </code> After I called the createTableRow method a few times and filled the tablelayout with rows, I want to detect when the user clicks a row. How can I give the row different id's, like the first gets the id 0, the second 1 etc.. And last how can I detect when a user clicks a row? EDIT: I tried setOnClickListener but it dosen't work when I click on the view, the message "is reachable" is never shown in logcat. <code>private View createTableRow(LocationObject locObject) { TableRow tr = new TableRow(getActivity()); View v = LayoutInflater.from(getActivity()).inflate(R.layout.view_layout, tr, false); ... v.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.e("output", "is reachable"); } }); return v; } </code> Comment: Have you tried adding an `onClickListener` in your `createTableRow`? Comment: @Marcus yes, but it doesn't work. Answer: First of all don't forget <code>i++</code> at <code>for(int i = 0; i < 5; i++)</code> You can try somthing like: <code>private View createTableRow(int position) { //instead //TableRow tr = new TableRow(MainActivity.this); //View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.view_layout, tr, false); //try View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.view_layout, null, false); TextView textViewName = (TextView) v.findViewById(R.id.textView_name); textViewName.setText("row "+ position); v.setTag(position); v.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int position = (Integer) v.getTag(); Log.e("output", "is reachable at position "+ position); } }); return v; } </code> output on click: <code>02-04 09:36:13.615 4755-4755/noambaroz.testapplication E/output﹕ is reachable at position 0 02-04 09:36:14.680 4755-4755/noambaroz.testapplication E/output﹕ is reachable at position 2 02-04 09:36:15.310 4755-4755/noambaroz.testapplication E/output﹕ is reachable at position 4 </code><|endoftext|>what is the destruction order between global object and static variable? Question: Possible Duplicate: Object destruction in C++ Suppose we have two classes, one is called <code>Array</code> and the other one is called <code>MessageOnExit</code>. Assume the <code>Array</code> class has a static data member called <code>counter</code>. Here are the classes: <code>class Array { public: static int counter; Array(){counter++;} ~Array(){counter--;} }; class MessageOnExit { public: ~MessageOnExit(){cout << Array::counter;} }; </code> The following is the "main" using these classes: <code>// static variable definition int Array::counter; // global object definition MessageOnExit message; void main() { Array a1, a2; Array a3(a1); } </code> The first two declarations will change <code>counter</code> to be 2 ensues two calls of the Empty/Default constructor The third declaration won't change the <code>counter</code> because the Default copy constructor will be called. Now when the <code>main</code> execution is done, the value of the static member <code>counter</code>will be <code>-1</code> ensues the destructors calls (after a1, a2 and a3 are desroyed), and then the <code>message</code> destructor will be called, printing this value (<code>-1</code>). My question is how do we know the static member <code>counter</code> is still alive and available when the <code>message</code> destructor is being called. Also if I change the static/global object/variable definition order, that is, <code>message</code> is defined before <code>counter</code>, the value remains <code>-1</code>. To summarize, no matter what changes I do, when the program terminates the message destructor success to access the static member <code>counter</code> and I don't understand why is that. As far as I understand if the global object <code>message</code> is defined first its destructor will be called last and therefore the <code>counter</code> value won't be available for its destructor. Thanks in advance! Guy Comment: Take a look at [this]( [IDX] [this]( [IDX] and [this]( [IDX] Using an object after it has been destroyed is not a diagnosed error, its undefined behavior, so anything might happen -- the code might appear to work fine one day and break the next. Comment: I edited away all the bold text because it had the effect of emphasizing parts of the text that shouldn't have been. I either removed it or changed them to code-quotes. You can add back bolding in some places if you feel it's really needed. Comment: Reopen this question. The important point here is that a static object with trivial destructor is never destroyed; see aschepler's answer. That is not stated clearly in the answers to the other questions, Answer: Standard section 3.8 says: The lifetime of an object of type <code>T</code> ends when: if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or the storage which the object occupies is reused or released. Now <code>int</code> is not a class type, and since <code>Array::counter</code> has static storage duration, its storage is never released. So the lifetime of <code>Array::counter</code> never ends, and you can safely access it from any destructor you want!<|endoftext|>When to nominalize? Question: When is it correct to use nominalizations? (Isn't nominalization a nominalization?) It seems the main problem is that they tend to mislead the reader. It is appealing to think that "being" and "understanding" are "things." I see how this sort of misuse of words can be misleading. But when does concise become too compact? The English language seems to nominalize words frequently--and often effectively (I'm thinking of George Eliot). Comment: "He caught a glimpse of recognition on the bartender's face" is an attractive phrase. "He has an understanding of the proposition" is too complicated if you simply mean "he understands the proposition" but might suggest something slightly weaker. So it all depends on the particular example. Comment: Can you give an example where nominalization is inherently misleading? I cannot think of any. Saying, "you are a failure" is much more concise and does not sacrifice any of the meaning of (and is in fact less awkward to say that) "you are one who fails." Comment: He has an understanding of the proposition. (It is as though understanding is a thing like shoe.) It is like this poor joke: a friend told me he had a pain in his shoe. I asked what that meant. He said he'd taken a class on basic syllogisms, and he had a pain in his foot, his foot was in his shoe, and thus, he had a pain in his shoe. I know. It's a poor joke. But this is the sort of bad sentence I mean: "He found the taking of the test to be a difficulty that caused him a great amount of distress" or "he caught a glimpse of recognition on the bartender's face." Comment: Yeah, I like the glimpse too. It is much more Hammett than a police report. Answer: Your question's more like a starting point for philosophical, linguistic, and other research. No kidding. You're right about the 'thinginess'. Anyway, humans just do what they can and try some more with language. Let's start with an issue you may find interesting, I hope: nominalizations in English and many other languages most often allow to leave out the agent, patient, and other participants: Killing, a sell or a visit doesn't say who, whom, when, where. That's one reason why excessive nominalization can be used in malicious ways. ('Nominalstil', if you want to adopt a German term) It's hard to say in general when useful flexible constructions get misleading. Mostly because verbs are so complicated, allowing for many different roles expressed by noun phrases, prepositions, dependent clauses and some more. Sorry for my alluding overgeneral formulations. There's no short answer to your question for all I know about linguistics. Perhaps I read and heard too much on those issues. By the way, verbalizations (to hammer, (to mouse as a cat or on a computer) are a totally different beast: the noun names a class of referents which nearly always fulfills a single role. The fun is you can't say which role just by looking at the noun. Comment: Yeah, I found it difficult to separate the philosophical and practical implications of the question. On the one hand, I've been told that nominalizations are to be avoided. On the other hand, they often lead to a sort of philosophical confusion—thinking that the understanding is a thing in the mind.<|endoftext|>Can natural predators detect human stealth technology? Question: Just a thought experiment since bats are probably not swift enough to take evasive action in the scenario described. If a cloud of bats were to encounter a B-2, or F-35, or F-117 or any of the other stealth aircraft in stealth-mode, would they detect the airframe in time, or fly smack into the aircraft? Comment: These aircraft designed to minimize their *radar* signature (and often their active noise and IR signatures as well), but bat do their special stuff with *sonar*. Nor do that have to turn on some kind of "stealth mode" their construction simply *is* stealth in flight configuration. Comment: BTW--It is a *bad* sign if you can't think up some decent tags for your question, especially as [you have the privilege of creating new tags]( [IDX] You should *never* post a question tagged [untagged], and I have [requested that it be black listed]( [IDX] @dmckee: Then the postulated bat/s would kill themselves flying into the airframe? Comment: Understood. I did think of creating a tag 'radar' but the idea seemed sort of ... facetious. I'll bear it in mind for the future. Comment: @dmckee: I know this is late but I just saw this post. Some stealth aircraft do actually have systems they can turn on and off to affect their visibility to radar or to covertly respond to identification systems - electronic warfare systems are an integral part of modern stealth. Answer: Static stealth aircraft If the aircraft is static (parked on the ground) the bats echolocation would enable them to "see" the aircraft and avoid it. Bats' echolocation uses sound waves at 15-100 KHz. Stealth aircraft are not designed to reduce their reflection of sound waves, they are designed to reduce reflection of electromagnetic waves (primarily radar). Flying stealth aircraft If bats are in the path of any aircraft flying at typical subsonic aircraft speeds (say 50-200 m/s), the bats would probably not have time to evade the aircraft. Like us, bats evolved on a planet where nothing much flew above 10-20 m/s (some hawks can dive at 50 ms or faster, but not at night when bats are active) Note: Bats fly at less than 10 m/s F117s cruise at over 300 m/s Therefore it isn't accurate to think of a collision in terms of bats flying into an airframe, the bat is relatively stationary. Bat echolocation range The bats reacted to insect prey at dis- tances of about 70 to 120 cm. Given the flight speed, the detection distance was estimated to about 110 to 160 cm. [IDX] say a bat echolocates a cruising F117 closing at 160 cm distance, the sound echo travelling from F117 to bat at 340 m/s reaches the bat after 4 ms. The F117 arrives 1 ms later. I doubt the bat's brain has even time to register this, but if it could react in less than 0.01 ms, it can only fly a few mm before the F117 strikes it. Comment: It's a thought experiment. Let's assume the bats are at a distance from the aircraft, and not approaching head-on! (+: Comment: Bats are delicate, before they have time to notice the aircraft their organs would be ruptured by the turbulence of the passing aircraft. See [IDX] , [IDX] and [IDX] - wind turbine blades travel through the air slower than aircraft bodies.
[{"idx": "Android_how_to_detect_which_tablerow_was_clicked", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-18170.jsonl"}, {"idx": "what_is_the_destruction_order_between_global_object_and_static_variable?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-18170.jsonl"}, {"idx": "When_to_nominalize?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-18170.jsonl"}, {"idx": "Can_natural_predators_detect_human_stealth_technology?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-18170.jsonl"}]
### Here are set of addition, subtraction, multiplication, division math problems: 81 + 1455 = 1536 ### 398 * 1390 = 553220 ### 800 * 975 = 780000 ### 429 - 713 = -284 ### 2034 + 1308 = 3342 ### 1085 * 188 = 203980 ### 362 / 992 = 0.36 ### 214 / 465 = 0.46 ### 2260 + 924 = 3184 ### 630 - 359 = 271 ### 7 - 1755 = -1748 ### -560 / 688 = -0.81 ### 2204 - 1805 = 399 ### 2110 - 1435 = 675 ### 1277 * 205 = 261785 ### 1388 - 2031 = -643 ### 1881 + 1337 = 3218 ### 2315 + 551 = 2866 ### 173 + 2130 = 2303 ### -56 / 1225 = -0.05 ### 2066 - 2226 = -160 ### 464 - 853 = -389 ### 2222 - 350 = 1872 ### Sure thing! Let's multiply 6226 and 6725 together 6226 × 6725 = 6725 × (6226) + 6725 × 6 giving us 40350 + 6725 × 20 producing 134500 + 6725 × 200 which equals 1345000 + 6725 × 6000 yielding 40350000 = 41869850 ### 1880 + 1665 = 3545 ### 309 * 323 = 99807 ### 1632 / 1205 = 1.35 ### 98 / 1055 = 0.09 ### 1524 / 471 = 3.24 ### 2085 + 471 = 2556 ### -110 / -163 = 0.67 ### 290 * 1190 = 345100 ### 1899 + 1677 = 3576 ### 1670 + 2075 = 3745 ### 22 - 651 = -629 ### 55 * 715 = 39325 ### 1126 + 1130 = 2256 ### 225 + -20 = 205 ### 1617 / 312 = 5.18 ### 1544 / -9 = -171.56 ### 1895 + 1318 = 3213 ### 1908 - 893 = 1015 ### 496 / 869 = 0.57 ### 2279 * 380 = 866020 ### 276 + 2310 = 2586 ### 2168 * 1443 = 3128424<|endoftext|>### Here's set of subtraction, division, addition, multiplication math examples: -486 / 626 = -0.78 ### 2232 * 1459 = 3256488 ### 115 * 406 = 46690 ### 87 - 2128 = -2041 ### 1731 * 91 = 157521 ### 590 + 1455 = 2045 ### 1545 * 2038 = 3148710 ### 2001 * 1604 = 3209604 ### 1678 - 2115 = -437 ### 245 * 108 = 26460 ### 1056 + 327 = 1383 ### 1753 - 1566 = 187 ### 1084 * 1482 = 1606488 ### 1574 - 135 = 1439 ### 1405 / 78 = 18.01 ### 521 / 1446 = 0.36 ### 421 - 1258 = -837 ### 433 * 2241 = 970353 ### 1862 + 1934 = 3796 ### 1031 / 474 = 2.18 ### 669 / 495 = 1.35 ### 370 - 1223 = -853 ### 944 / -60 = -15.73 ### 1112 + 102 = 1214 ### 1728 + 1687 = 3415 ### 1511 / -352 = -4.29 ### 865 * 1209 = 1045785 ### 1364 / 259 = 5.27 ### 409 / 1614 = 0.25 ### 891 + 902 = 1793 ### 900 - 2225 = -1325 ### 1403 + 463 = 1866 ### 1903 / 1509 = 1.26 ### 1244 * 772 = 960368 ### 1517 + 1843 = 3360 ### 1653 + 1197 = 2850 ### 385 + 998 = 1383 ### 2220 - 500 = 1720 ### 841 * 194 = 163154 ### 1399 - 639 = 760 ### 1958 * 2211 = 4329138 ### 684 * 1153 = 788652 ### 1951 * 1604 = 3129404 ### 20 ÷ 7 = 2 R6 No problem, we've got 20 and 7 for the division. Step 1: 7 goes into 2 0 times with a remainder of 2. Write down 0 as next digit of of the result. Result so far: 0 Subtract 0 from 2 to get 2. Bring next digit (0) of the dividend behind the 2 and repeat the process: 20 / 7 Step 2: 7 goes into 20 2 times with a remainder of 6. Write down 2 as next digit of of the result. Result so far: 2 Subtract 14 from 20 to get 6. The final result is 2 with a remainder of 6.<|endoftext|>### Please examine the set of division, subtraction, multiplication, addition arithmaic examples: -683 / -367 = 1.86 ### 1666 * 2012 = 3351992 ### 1542 - 1082 = 460 ### 1030 + -74 = 956 ### 938 / 56 = 16.75 ### 1174 - 1925 = -751 ### 599 * 261 = 156339 ### 928 + 113 = 1041 ### 2141 - 1768 = 373 ### 2184 / -820 = -2.66 ### -298 / -319 = 0.93 ### 1240 - 713 = 527 ### 575 - 604 = -29 ### 198 - 1486 = -1288 ### 1625 / 487 = 3.34 ### 1717 * 683 = 1172711 ### 479 / 1167 = 0.41 ### -293 / 1002 = -0.29 ### 1452 / -401 = -3.62 ### 1761 - 42 = 1719 ### 306 + 1753 = 2059 ### 1703 + -38 = 1665 ### 1680 * 825 = 1386000 ### 804 + 78 = 882 ### 1087 * 1835 = 1994645 ### 1707 - 130 = 1577 ### 559 / 1483 = 0.38 ### 1933 * 832 = 1608256 ### 810 / 181 = 4.48 ### -217 / -436 = 0.5 ### 341 + 2229 = 2570 ### 1630 - 1561 = 69 ### 1628 * 413 = 672364 ### 2070 * 169 = 349830 ### 786 + 1960 = 2746 ### Alright, let's work through 7 times 1 step by step 7 × 1 = 1 × (7) + 1 × 7 producing 7 = 7 ### 433 / -300 = -1.44 ### 1277 * 1064 = 1358728 ### -264 / -77 = 3.43 ### 837 / 1871 = 0.45 ### 603 + 577 = 1180 ### 2 * 247 = 494 ### -75 / 860 = -0.09 ### 1939 * 479 = 928781 ### 481 / 1977 = 0.24 ### 1408 - 1678 = -270 ### 2166 - 594 = 1572 ### 694 * 764 = 530216 ### 845 / -33 = -25.61<|endoftext|>### Here is some exercises for addition, division, subtraction, multiplication math examples: 1108 / 1518 = 0.73 ### 1748 - 1500 = 248 ### 734 / 1937 = 0.38 ### 1468 / -218 = -6.73 ### 555 + 868 = 1423 ### 1188 / 902 = 1.32 ### 1600 * 725 = 1160000 ### 1510 - 771 = 739 ### 1500 * 535 = 802500 ### 764 + 1913 = 2677 ### 629 - 738 = -109 ### 231 - 55 = 176 ### 934 / -492 = -1.9 ### 1851 * 300 = 555300 ### 2150 - 2238 = -88 ### 482 / 1882 = 0.26 ### 978 * 1595 = 1559910 ### 347 * 297 = 103059 ### -184 / -121 = 1.52 ### 1132 * 531 = 601092 ### -577 / 423 = -1.36 ### 1462 * 489 = 714918 ### -542 / 883 = -0.61 ### 1842 + 2013 = 3855 ### 831 - 836 = -5 ### 106 - 446 = -340 ### 1071 + -16 = 1055 ### 218 / 1531 = 0.14 ### 2204 * 633 = 1395132 ### 458 * 2079 = 952182 ### We divide 29609 by 42 We're looking to find how many times 42 goes into 29609. Step 1: 42 can be fit into 2 0 times, resulting in a remainder of 2. Record the quotient 0 as the next digit in the result. Result so far: 0.0 The remainder is 2 after subtracting 0 from 2. Include the next digit (9) from the dividend after 2, then repeat: 29 / 42 Let's proceed to step 2: 29 divided by 42 is 0 with a remainder of 29. The number 0 becomes the next digit in our result. Result so far: 0.0 The remainder is 29 after subtracting 0 from 29. Fetch the next digit (6) from the dividend, attach it to 29 and continue: 296 / 42 Going ahead to step 3: The number 42 fits into 296 7 times, leaving a remainder of 2. The number 7 becomes the next digit in our result. Result so far: 7.0 Subtract 294 from 296 to get 2. Grab the next digit (0) from the dividend, add it to 2, then carry on: 20 / 42 On to step 4: 42 can be fit into 20 0 times, resulting in a remainder of 20. Write down 0 as next digit of the result. Result so far: 70.0 If we subtract 0 from 20, we get 20. Fetch the next digit (9) from the dividend, attach it to 20 and continue: 209 / 42 Going ahead to step 5: 42 goes into 209 4 times with a remainder of 41. The next digit of our result is 4. Result so far: 704.0 Deduct 168 from 209 and we're left with 41. Since there are no more digits in the dividend, we add a zero to the remainder making it 410, and continue the process. Moving on to step 6: 42 can be fit into 410 9 times, resulting in a remainder of 32. The number 9 becomes the next digit in our result. Result so far: 704.9 If we subtract 378 from 410, we get 32. Since there are no more digits in the dividend, we add a zero to the remainder making it 320, and continue the process. Moving on to step 7: When dividing 320 by 42, we get 7 with a remainder of 26. The next digit of our result is 7. Result so far: 704.97 Subtracting 294 from 320 leaves us with 26. Since there are no more digits in the dividend, we add a zero to the remainder making it 260, and continue the process. Advancing to step 8: 42 can be fit into 260 6 times, resulting in a remainder of 8. The next digit of our result is 6. Result so far: 704.976 If we take 252 away from 260, we end up with 8. Since there are no more digits in the dividend, we add a zero to the remainder making it 80, and continue the process. Going ahead to step 9: 80 divided by 42 is 1 with a remainder of 38. The next digit of our result is 1. Result so far: 704.9761 If we subtract 42 from 80, we get 38. Since there are no more digits in the dividend, we add a zero to the remainder making it 380, and continue the process. On to step 10: The number 42 fits into 380 9 times, leaving a remainder of 2. Put 9 as the next digit of the answer. Result so far: 704.97619 If we take 378 away from 380, we end up with 2. Since there are no more digits in the dividend, we add a zero to the remainder making it 20, and continue the process. Let's proceed to step 11: 20 divided by 42 is 0 with a remainder of 20. Use 0 as the next digit of our solution. Result so far: 704.97619 Subtract 0 from 20 to get 20. Since there are no more digits in the dividend, we add a zero to the remainder making it 200, and continue the process. On to step 12: 42 goes into 200 4 times with a remainder of 32. The number 4 becomes the next digit in our result. Result so far: 704.9761904 The remainder is 32 after subtracting 168 from 200. Since there are no more digits in the dividend, we add a zero to the remainder making it 320, and continue the process. Moving on to step 13: 42 goes into 320 7 times with a remainder of 26. Put 7 as the next digit of the answer. Result so far: 704.97619047 Subtract 294 from 320 to get 26. Since there are no more digits in the dividend, we add a zero to the remainder making it 260, and continue the process. The final outcome is 704.97619047, with a leftover of 2.6e-08.
[{"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}]
Why teach absolute mean deviation? Question: I was helping my niece (7th grade) with homework and one of the topics was the absolute mean deviation. It's basically the same thing as standard deviation except instead of squaring the difference between the data points and the mean, you take the absolute value of them. On the one hand I can almost understand this because if I told her she had to square all those numbers instead of just dropping negative signs, she wouldn't have liked it. That being said, she was using a calculator so squaring the numbers and dealing with big numbers should have been trivial anyway. The absolute mean deviation isn't something that is used by even statisticians (I don't think) but standard deviation is pretty common in general business (at the very least) so why teach 90% of a real world topic instead of just teaching the real thing? Comment: Absolute error is definitely used by statisticians. Comment: I wouldn't say this to most students (which is why I'm putting it in a comment rather than in an answer) but it only recently occurred to me that the relationship between "standard deviation" and "mean absolute deviation" is almost precisely the same as the relationship between "Euclidean geometry" and "taxicab geometry". Comment: Maybe they will get to SD next. You don't have to take it as excluding A to be shown B. There are really a lot of ways to look at a distribution (mean, median, range, SD, max, min, upper or lower constraints, etc.) Also, for some problems absolute deviation from a standard is exactly what you want to know, not SD (e.g. for physical or $ problems, at times.) Comment: They didn't THAT YEAR. Later means later. We are talking about education of a child. Comment: @guest they didn't Comment: @guest later does mean later but you said next and next doesn't mean later. Comment: Fair enough. So maybe I said wrong. Still, point previous guy had about the algebraic complexity of std deviation applies. Realistically, I think better benefit from just waiting on the stats until later in curriculum is better. Comment: Thanks for this question! I am learning interesting things from the answers. Answer: The question we pose to students is: How far away, on average, are these values from their mean? The "natural" way to answer that question is to compute the deviations of the individual data points and compute the average. When students do this they are usually surprised to find out that the answer comes out to be precisely $0$ — that the positive deviations and the negative deviations always cancel exactly. Pointing out that this is actually a signal that we did everything right -- that the mean value is supposed to be in the middle of the data, with just as much deviation above it as below it -- often triggers an "aha" moment for many students, for whom the average was just a formula disconnected from any intuitive meaning (see How to Teach Averages (Arithmetic Mean) to a Teenager? and [IDX] for examples of this). So, once we have established that "average deviation" is not a useful thing to compute, the obvious next question is: how could we get rid of those negative signs? The idea of just dropping them all is both simple and intuitive, and "average of the absolute values of the deviations" is a literal interpretation of the idea of "average distance from the mean". In fact, as others have pointed out, it's the standard deviation that seems unnatural and unnecessarily complicated. We square the deviations, which makes them all positive, and then we average them, but that comes out too big because we squared them, so then we take the square root... Why do all of that? I usually tell my students that the function $y=x^2$ has nicer mathematical properties than the function $y=|x|$, and in particular that the sharp corner in the absolute value function makes it hard to work with. I'm not sure how intellectually honest that response is, but it at least makes a plausible-seeming connection with Calculus (for the students who have seen it) or lays some groundwork for it (for the students who have not yet but may someday). Comment: That's what I say too! In fact, when I was first using standard deviation in an applied algebra course I was teaching, it seemed wrong to me. I still don't have enough depth in statistics to understand whether it really is right, or is just a kludge. Answer: The foundations of statistical inference are very hard to teach at any level, and almost certainly, at the 7th grade level, little or no serious motivation is given for the rules presentd. Probably at the 7th grade level what is being taught are rote rules for calculation of defined, but generally poorly if at all motivated, quantities. The presence or absence of a square is hardly of much importance if that is the situation. In quantifying error, the power used refects some subjective judgment about the importance attached to large values or outliers. One can use the absolute value, the square, or any $p$th power (or the $\infty$-norm). Different choices are affected differently by large values - the mean error calculated using a higher power is more affected by large values than is the error calculated using a lower power. The widespread use of the square has sound justifications in scientific practice, but the ordinary mean also can make sense. When working with large data sets on a computer, computational considerations can dictate using the square. Fundamentally the preference for the square is because the squared mean is given by an inner product. For example, the regression line defined using mean squared error is more easily calculated on a computer than that defined using mean absolute error because the "normal equations" can be solved efficiently and robustly using the singular value decomposition. On the other hand, if one refers to computation by hand, then the calculation without squares requires fewer operations and so is simpler. At the $7$th grade level little or no effort is made to interpret, and to the extent that any is made, the difference between ordinary mean and mean squared is not of great importance. There is nothing any more "real world" about any of this stuff than there is about the standard exercises given to calculus students. One teaches mathematics to all $7$th graders not because of its real world utility, but because the habits of thought learned by learning mathematics are themselves useful quite generally. One teaches elementary statistical ideas in order to develop the ability to formulate qualitative interpretations of masses of data. What one can hope to teach students is that there is some sort of second order criterion that can distinguish distributions with the same mean. One hopes that a student can distinguish (visually/intuitively) between data uniformly distributed over a range and data all repeated on the midpoint of that same range, and then see that the measure of deviation (with or without squares) differentiates between these two data points. This is in the same spirit as teaching the student that distributions with the same mean can have different medians, but it is different, because mean and median are both first order statistics, whereas deviation is somehow second order, measuring spread around something first order. There are different ways to measure spread, but it becomes difficult to justify, on principled grounds understandable at the middle school level, the choice of one measure of spread over another. If I were teaching this material, I would probably use the mean squared error as the default, but I have little experience teaching $7$th graders per se, and am prepared to imagine the leaving out the square facilitates the realization of computations with little conceptual loss of a nature relevant at that level. Answer: You're in the U.S. (according to your profile), and in the U.S. square roots are not generally introduced until the 8th grade (for example, 8.EE.A.2 in the Common Core). I believe the topic "absolute mean deviation" (also called "mean absolute deviation") is a relatively recent addition to middle grade level mathematics, probably within the last 10 years, that allows teachers to give a more nuanced measure of data variability than "range" and to give a cognitive stepping stone to "standard deviation" (taught in high school), before students have been introduced to square roots. In the Common Core, absolute mean deviation is taught in the 6th and 7th grades (6.SP.B.5.c and 7.SP.B.3). Answer: When I introduce measures of dispersion, the usual question from students is why do we use standard deviation and variance instead of absolute deviation, which is a lot simpler to interpret and compute. That is, they ask the opposite as the OP. Since we know more statistics (and calculus), we know that absolute deviation is not very useful. However, when introducing measures of dispersion, it's useful because it's one of the most intuitive measures and understanding it helps introducing and motivating variance and standard deviation. Comment: @pjs I agree, but please notice that normal distribution could be easily parametrized using absolute deviation, too. We would just need to multiply by a constant: [IDX] Another reason for favoring variance/s.d. is because we keep bumping into the normal distribution - thanks CLT! - and variance/s.d. is one of the two parameters that characterize normal distributions. Answer: Consider, when constructing Bayes estimators: Using the squared error loss gives the basis for the Bayes estimator of the mean. Using the absolute error loss gives the basis for the Bayes estimator of the median. From: Casella/Berger, Statistical Inference, Chapter 10, Theorem 10.3.2.<|endoftext|>mongoDBのパスの通し方を教えてください Question: 質問内容 以下のエラーの解決方法を教えてください。 <code>Data directory /data/db not found., terminating </code> 現状 以前mongoDBを起動したときは使えたのだが強制終了してしまったせいか、再度起動できなくなってしまいました。 <code>$ sudo service mongod start mongod: unrecognized service </code> <code>$ mongod 2020-09-17T18:10:14.072+0900 I CONTROL [initandlisten] MongoDB starting : pid=134 port=27017 dbpath=/data/db 64-bit host=LAPTOP-LSE3HD1V 2020-09-17T18:10:14.078+0900 I CONTROL [initandlisten] db version v3.4.24 2020-09-17T18:10:14.085+0900 I CONTROL [initandlisten] git version: 865b4f6a96d0f5425e39a18337105f33e8db504d 2020-09-17T18:10:14.086+0900 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.2n 7 Dec 2017 2020-09-17T18:10:14.087+0900 I CONTROL [initandlisten] allocator: tcmalloc 2020-09-17T18:10:14.092+0900 I CONTROL [initandlisten] modules: none 2020-09-17T18:10:14.093+0900 I CONTROL [initandlisten] build environment: 2020-09-17T18:10:14.101+0900 I CONTROL [initandlisten] distmod: ubuntu1604 2020-09-17T18:10:14.102+0900 I CONTROL [initandlisten] distarch: x86_64 2020-09-17T18:10:14.107+0900 I CONTROL [initandlisten] target_arch: x86_64 2020-09-17T18:10:14.108+0900 I CONTROL [initandlisten] options: {} 2020-09-17T18:10:14.120+0900 I STORAGE [initandlisten] exception in initAndListen: 29 Data directory /data/db not found., terminating 2020-09-17T18:10:14.121+0900 I NETWORK [initandlisten] shutdown: going to close listening sockets... 2020-09-17T18:10:14.127+0900 I NETWORK [initandlisten] shutdown: going to flush diaglog... 2020-09-17T18:10:14.129+0900 I CONTROL [initandlisten] now exiting 2020-09-17T18:10:14.135+0900 I CONTROL [initandlisten] shutting down with code:100 </code> ここで <code>2020-09-17T18:10:14.120+0900 I STORAGE [initandlisten] exception in initAndListen: 29 Data directory /data/db not found., terminating </code> より、dbというディレクトリがないことがわかりました。一応見てみると、 <code>/data$ ls db /data$ cd db -bash: cd: db: No such file or directory </code> となっていました。 このコードの2行目に「db」とある気がするのですが、とりあえず起動できません。 ディレクトリを作れということなのかと思い、同じ階層に「db1」というものを作りました。 <code>/data$ mkdir db1 /data$ ls db db1 </code> その後、 <code>$ mongod -dbpath /data/db1 2020-09-17T18:09:20.877+0900 I CONTROL [initandlisten] MongoDB starting : pid=126 port=27017 dbpath=/data/db1 64-bit host=LAPTOP-LSE3HD1V 2020-09-17T18:09:20.882+0900 I CONTROL [initandlisten] db version v3.4.24 2020-09-17T18:09:20.883+0900 I CONTROL [initandlisten] git version: 865b4f6a96d0f5425e39a18337105f33e8db504d 2020-09-17T18:09:20.890+0900 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.2n 7 Dec 2017 2020-09-17T18:09:20.891+0900 I CONTROL [initandlisten] allocator: tcmalloc 2020-09-17T18:09:20.892+0900 I CONTROL [initandlisten] modules: none 2020-09-17T18:09:20.897+0900 I CONTROL [initandlisten] build environment: 2020-09-17T18:09:20.902+0900 I CONTROL [initandlisten] distmod: ubuntu1604 2020-09-17T18:09:20.903+0900 I CONTROL [initandlisten] distarch: x86_64 2020-09-17T18:09:20.904+0900 I CONTROL [initandlisten] target_arch: x86_64 2020-09-17T18:09:20.905+0900 I CONTROL [initandlisten] options: { storage: { dbPath: "/data/db1" } } 2020-09-17T18:09:20.969+0900 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=7569M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),verbose=(recovery_progress), 2020-09-17T18:09:21.035+0900 E STORAGE [initandlisten] WiredTiger error (22) [1600333761:35092][126:0x7fe7bed81180], connection: /data/db1/: directory-sync: fdatasync: Invalid argument 2020-09-17T18:09:21.038+0900 E STORAGE [initandlisten] WiredTiger error (-31804) [1600333761:38949][126:0x7fe7bed81180], connection: the process must exit and restart: WT_PANIC: WiredTiger library panic 2020-09-17T18:09:21.046+0900 I - [initandlisten] Fatal Assertion 28558 at src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp 365 2020-09-17T18:09:21.052+0900 I - [initandlisten] ***aborting after fassert() failure 2020-09-17T18:09:21.113+0900 F - [initandlisten] Got signal: 6 (Aborted). 0x7fe7c03610b1 0x7fe7c03602c9 0x7fe7c03607ad 0x7fe7bd7528a0 0x7fe7bd37ef47 0x7fe7bd3808b1 0x7fe7bf5f39f1 0x7fe7c0068f86 0x7fe7bf5fe0a8 0x7fe7bf5fe2cd 0x7fe7bf5fe52f 0x7fe7c0d17857 0x7fe7c0d179f2 0x7fe7c0d1837b 0x7fe7c0d14581 0x7fe7c0c72b06 0x7fe7c0d3489f 0x7fe7c0d1242b 0x7fe7c0cc109a 0x7fe7c004d3af 0x7fe7c0045aa2 0x7fe7bff386e0 0x7fe7bf5deaf3 0x7fe7bf5ff926 0x7fe7bd361b97 0x7fe7bf660379 ----- BEGIN BACKTRACE ----- {"backtrace":[{"b":"7FE7BEDAE000","o":"15B30B1","s":"_ZN5mongo15printStackTraceERSo"},{"b":"7FE7BEDAE000","o":"15B22C9"},{"b":"7FE7BEDAE000","o":"15B27AD"},{"b":"7FE7BD740000","o":"128A0"},{"b":"7FE7BD340000","o":"3EF47","s":"gsignal"},{"b":"7FE7BD340000","o":"408B1","s":"abort"},{"b":"7FE7BEDAE000","o":"8459F1","s":"_ZN5mongo32fassertFailedNoTraceWithLocationEiPKcj"},{"b":"7FE7BEDAE000","o":"12BAF86"},{"b":"7FE7BEDAE000","o":"8500A8","s":"__wt_eventv"},{"b":"7FE7BEDAE000","o":"8502CD","s":"__wt_err"},{"b":"7FE7BEDAE000","o":"85052F","s":"__wt_panic"},{"b":"7FE7BEDAE000","o":"1F69857"},{"b":"7FE7BEDAE000","o":"1F699F2"},{"b":"7FE7BEDAE000","o":"1F6A37B"},{"b":"7FE7BEDAE000","o":"1F66581","s":"__wt_open"},{"b":"7FE7BEDAE000","o":"1EC4B06","s":"__wt_block_manager_create"},{"b":"7FE7BEDAE000","o":"1F8689F","s":"__wt_schema_create"},{"b":"7FE7BEDAE000","o":"1F6442B","s":"__wt_turtle_init"},{"b":"7FE7BEDAE000","o":"1F1309A","s":"wiredtiger_open"},{"b":"7FE7BEDAE000","o":"129F3AF","s":"_ZN5mongo18WiredTigerKVEngineC1ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_PNS_11ClockSourceES8_mbbbb"},{"b":"7FE7BEDAE000","o":"1297AA2"},{"b":"7FE7BEDAE000","o":"118A6E0","s":"_ZN5mongo20ServiceContextMongoD29initializeGlobalStorageEngineEv"},{"b":"7FE7BEDAE000","o":"830AF3"},{"b":"7FE7BEDAE000","o":"851926","s":"main"},{"b":"7FE7BD340000","o":"21B97","s":"__libc_start_main"},{"b":"7FE7BEDAE000","o":"8B2379","s":"_start"}],"processInfo":{ "mongodbVersion" : "3.4.24", "gitVersion" : "865b4f6a96d0f5425e39a18337105f33e8db504d", "compiledModules" : [], "uname" : { "sysname" : "Linux", "release" : "4.4.0-18362-Microsoft", "version" : "#1049-Microsoft Thu Aug 14 12:01:00 PST 2020", "machine" : "x86_64" }, "somap" : [ { "b" : "7FE7BEDAE000", "elfType" : 3, "buildId" : "2D1022085B581BB8C5C09845FF38D62AB6F14607" }, { "b" : "7FFFE394D000", "path" : "linux-vdso.so.1", "elfType" : 3 }, { "b" : "7FE7BE790000", "path" : "/usr/lib/x86_64-linux-gnu/libssl.so.1.0.0", "elfType" : 3, "buildId" : "0D054641049B9747C05D030262295DFDFDD3055D" }, { "b" : "7FE7BE340000", "path" : "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.0", "elfType" : 3, "buildId" : "9C228817BA6E0730F4FCCFAC6E033BD1E0C5620A" }, { "b" : "7FE7BE130000", "path" : "/lib/x86_64-linux-gnu/librt.so.1", "elfType" : 3, "buildId" : "3F29B196C7C124797473113FD2D0833881BF0DE5" }, { "b" : "7FE7BDF20000", "path" : "/lib/x86_64-linux-gnu/libdl.so.2", "elfType" : 3, "buildId" : "B22BAF34FB22284EC8E3818961CDF01CCAB3441C" }, { "b" : "7FE7BDB80000", "path" : "/lib/x86_64-linux-gnu/libm.so.6", "elfType" : 3, "buildId" : "9EF1967ED985A60AC2288C3E1D8C8375F48B841D" }, { "b" : "7FE7BD960000", "path" : "/lib/x86_64-linux-gnu/libgcc_s.so.1", "elfType" : 3, "buildId" : "679F3AE11120EC7C483BC9295345D836F5C104F7" }, { "b" : "7FE7BD740000", "path" : "/lib/x86_64-linux-gnu/libpthread.so.0", "elfType" : 3, "buildId" : "BC3C06107774266C5F7DB3F1F380A3DA68AF90FA" }, { "b" : "7FE7BD340000", "path" : "/lib/x86_64-linux-gnu/libc.so.6", "elfType" : 3, "buildId" : "D3CF764B2F97AC3EFE366DDD07AD902FB6928FD7" }, { "b" : "7FE7BEA00000", "path" : "/lib64/ld-linux-x86-64.so.2", "elfType" : 3, "buildId" : "C93445FE9506EEE727E6F04F1AC8F460E49EB366" } ] }} mongod(_ZN5mongo15printStackTraceERSo+0x41) [0x7fe7c03610b1] mongod(+0x15B22C9) [0x7fe7c03602c9] mongod(+0x15B27AD) [0x7fe7c03607ad] libpthread.so.0(+0x128A0) [0x7fe7bd7528a0] libc.so.6(gsignal+0xC7) [0x7fe7bd37ef47] libc.so.6(abort+0x141) [0x7fe7bd3808b1] mongod(_ZN5mongo32fassertFailedNoTraceWithLocationEiPKcj+0x0) [0x7fe7bf5f39f1] mongod(+0x12BAF86) [0x7fe7c0068f86] mongod(__wt_eventv+0x3D7) [0x7fe7bf5fe0a8] mongod(__wt_err+0x9D) [0x7fe7bf5fe2cd] mongod(__wt_panic+0x2E) [0x7fe7bf5fe52f] mongod(+0x1F69857) [0x7fe7c0d17857] mongod(+0x1F699F2) [0x7fe7c0d179f2] mongod(+0x1F6A37B) [0x7fe7c0d1837b] mongod(__wt_open+0x491) [0x7fe7c0d14581] mongod(__wt_block_manager_create+0x66) [0x7fe7c0c72b06] mongod(__wt_schema_create+0x4EF) [0x7fe7c0d3489f] mongod(__wt_turtle_init+0x36B) [0x7fe7c0d1242b] mongod(wiredtiger_open+0x194A) [0x7fe7c0cc109a] mongod(_ZN5mongo18WiredTigerKVEngineC1ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_PNS_11ClockSourceES8_mbbbb+0x70F) [0x7fe7c004d3af] mongod(+0x1297AA2) [0x7fe7c0045aa2] mongod(_ZN5mongo20ServiceContextMongoD29initializeGlobalStorageEngineEv+0x6B0) [0x7fe7bff386e0] mongod(+0x830AF3) [0x7fe7bf5deaf3] mongod(main+0x966) [0x7fe7bf5ff926] libc.so.6(__libc_start_main+0xE7) [0x7fe7bd361b97] mongod(_start+0x29) [0x7fe7bf660379] ----- END BACKTRACE ----- Aborted (core dumped) </code> と表示されました。 ここまでやってもmongodbは起動できませんでした。 どういう直し方をすればよいのかわからないので、投稿させていただきました。 宜しくお願いいたします。 Comment: Data directory /data/db not found., terminating で検索したところ色々解決策が出てきました。 [IDX] こちらお試しになられましたでしょうか。Macとは違いますので設定ファイルの場所は違うかもしれませんがエラーは同じですから参考になるかと思います。 Answer: エラーログのうち、 <code>"uname" : { "sysname" : "Linux", "release" : "4.4.0-18362-Microsoft", "version" : "#1049-Microsoft Thu Aug 14 12:01:00 PST 2020", "machine" : "x86_64" } </code> の部分からすると、WSL: Windows Sybsystem for Linuxを使っていると思います。 しかしMongoDBは公式にはWSLをサポートしていません。マニュアルのSupported Platformsに記載がありません。クラッシュしているのはこのためだと思われます。 まずは普通のLinux環境でやり直すか、もしくはWindowsを使うのであればWindows版のMongoDBをインストールしてみてください。
[{"idx": "Why_teach_absolute_mean_deviation?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-15123.jsonl"}, {"idx": "mongoDB\u306e\u30d1\u30b9\u306e\u901a\u3057\u65b9\u3092\u6559\u3048\u3066\u304f\u3060\u3055\u3044", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-15123.jsonl"}]
""" Module StringFormat The StringFormat module allows for character-by-character formatting of strings. It imitates the SPING string drawing and string metrics interface. The string formatting is done with specialized XML syntax within the string. Therefore, the interface for the StringFormat module consists of wrapper functions for the SPING string interface and various XML tags and characters. StringFormat functions drawString(canvas, s, x, y, [font], [color], [angle]) stringWidth(canvas, s, [font]) fontHeight(canvas, [font]) fontAscent(canvas, [font]) fontDescent(canvas, [font]) StringFormat XML tags <b> </b> - bold <i> </i> - italics <u> </u> - underline <super> </super> - superscript <sub> </sub> - subscript StringFormat XML characters Greek Letter Symbols as specified in MathML """ # How it works: Each tag grouping <b></b> sets a flag upon entry and # clears the flag upon exit. Each call to handle_data creates a # StringSegment which takes on all of the characteristics specified # by flags currently set. The greek letters can be specified as either # &alpha; or <alpha/>. The are essentially transformed into <alpha/> # no matter what and then there is a handler for each greek letter. # To add or change greek letter to symbol font mappings only # the greekchars map needs to change. from rdkit.sping.pid import Font import xmllib import math # constants sizedelta = 2 # amount to reduce font size by for super and sub script subFraction = 0.5 # fraction of font size that a sub script should be lowered superFraction = 0.5 # fraction of font size that a super script should be raised # greek mapping dictionary # characters not supported: epsi, Gammad, gammad, kappav, rhov # Upsi, upsi greekchars = { 'alpha': 'a', 'beta': 'b', 'chi': 'c', 'Delta': 'D', 'delta': 'd', 'epsiv': 'e', 'eta': 'h', 'Gamma': 'G', 'gamma': 'g', 'iota': 'i', 'kappa': 'k', 'Lambda': 'L', 'lambda': 'l', 'mu': 'm', 'nu': 'n', 'Omega': 'W', 'omega': 'w', 'omicron': 'x', 'Phi': 'F', 'phi': 'f', 'phiv': 'j', 'Pi': 'P', 'pi': 'p', 'piv': 'v', 'Psi': 'Y', 'psi': 'y', 'rho': 'r', 'Sigma': 'S', 'sigma': 's', 'sigmav': 'V', 'tau': 't', 'Theta': 'Q', 'theta': 'q', 'thetav': 'j', 'Xi': 'X', 'xi': 'x', 'zeta': 'z' } class StringSegment: """class StringSegment contains the intermediate representation of string segments as they are being parsed by the XMLParser. """ def __init__(self): self.super = 0 self.sub = 0 self.bold = 0 self.italic = 0 self.underline = 0 self.s = "" self.width = 0 self.greek = 0 def calcNewFont(self, font): "Given a font (does not accept font==None), creates a \ new font based on the format of this text segment." # if we are a greek character we need to pick a different fontface if self.greek: face = "symbol" else: face = font.face # want to make sure that we don't lose any of the base # font formatting return Font(face=face, size=font.size - (self.super * sizedelta) - (self.sub * sizedelta), underline=self.underline or font.underline, bold=self.bold or font.bold, italic=self.italic or font.italic) def calcNewY(self, font, y): "Returns a new y coordinate depending on its \ whether the string is a sub and super script." # should this take into account angle, I think probably not if self.sub == 1: return y + (font.size * subFraction) elif self.super == 1: return y - (font.size * superFraction) else: return y def dump(self): print("StringSegment: ]%s[" % self.s) print("\tsuper = ", self.super) print("\tsub = ", self.sub) print("\tbold = ", self.bold) print("\titalic = ", self.italic) print("\tunderline = ", self.underline) print("\twidth = ", self.width) print("\tgreek = ", self.greek) # The StringFormatter will be able to format the following xml # tags: # < b > < /b > - bold # < i > < /i > - italics # < u > < /u > - underline # < super > < /super > - superscript # < sub > < /sub > - subscript # # It will also be able to handle any MathML specified Greek characters. # # Possible future additions: changing color and font # character-by-character class StringFormatter(xmllib.XMLParser): # First we will define all of the xml tag handler functions. # # start_<tag>(attributes) # end_<tag>() # # While parsing the xml StringFormatter will call these # functions to handle the string formatting tags. # At the start of each tag the corresponding field will # be set to 1 and at the end tag the corresponding field will # be set to 0. Then when handle_data is called the options # for that data will be apparent by the current settings. #### bold def start_b(self, attributes): self.bold = 1 def end_b(self): self.bold = 0 #### italics def start_i(self, attributes): self.italic = 1 def end_i(self): self.italic = 0 #### underline def start_u(self, attributes): self.underline = 1 def end_u(self): self.underline = 0 #### super script def start_super(self, attributes): self.super = 1 def end_super(self): self.super = 0 #### sub script def start_sub(self, attributes): self.sub = 1 def end_sub(self): self.sub = 0 #### greek script def start_greek(self, attributes, letter): # print("creating a greek letter... ", letter) self.greek = 1 self.handle_data(letter) def end_greek(self): self.greek = 0 ------ def __init__(self): xmllib.XMLParser.__init__(self) # initialize list of string segments to empty self.segmentlist = [] # initialize tag values self.sub = 0 self.super = 0 self.bold = 0 self.italic = 0 self.underline = 0 # set up handlers for various tags self.elements = {'b': (self.start_b, self.end_b), 'u': (self.start_u, self.end_u), 'i': (self.start_i, self.end_i), 'super': (self.start_super, self.end_super), 'sub': (self.start_sub, self.end_sub)} # automatically add handlers for all of the greek characters self.elements[item] = (lambda attr,self=self,letter=greekchars[item]: self.start_greek(attr,letter), self.end_greek) # flag for greek characters self.greek = 0 # set up dictionary for greek characters, this is a class variable # should I copy it and then update it? self.entitydefs[item] = '<%s/>' % item ------ # def syntax_error(self,message): # print(message) ------ "Creates an intermediate representation of string segments." # segment first has data segment = StringSegment() segment.s = data # if sub and super are both one they will cancel each other out if self.sub == 1 and self.super == 1: segment.sub = 0 segment.super = 0 else: segment.sub = self.sub segment.super = self.super # bold, italic, and underline segment.bold = self.bold segment.italic = self.italic segment.underline = self.underline # greek character segment.greek = self.greek self.segmentlist.append(segment) ------ def parseSegments(self, s): "Given a formatted string will return a list of \ StringSegment objects with their calculated widths." # the xmlparser requires that all text be surrounded by xml # tags, therefore we must throw some unused flags around the # given string self.feed("<formattedstring>" + s + "</formattedstring>") self.close() # force parsing to complete self.reset() # get rid of any previous data segmentlist = self.segmentlist self.segmentlist = [] return segmentlist # These functions just implement an interface layer to SPING def fontHeight(canvas, font=None): "Find the total height (ascent + descent) of the given font." return canvas.fontHeight(font) def fontAscent(canvas, font=None): "Find the ascent (height above base) of the given font." return canvas.fontAscent(font) def fontDescent(canvas, font=None): "Find the descent (extent below base) of the given font." return canvas.fontDescent(font) # create an instantiation of the StringFormatter #sformatter = StringFormatter() # stringWidth and drawString both have to parse the formatted strings def stringWidth(canvas, s, font=None): "Return the logical width of the string if it were drawn \ in the current font (defaults to canvas.font)." if not font: font = canvas.defaultFont # sum up the string widths of each formatted segment sum = 0 for seg in segmentlist: sum = sum + canvas.stringWidth(seg.s, seg.calcNewFont(font)) return sum def rotateXY(x, y, theta): "Rotate (x,y) by theta degrees. Got transformation \ from page 299 in linear algebra book." radians = theta * math.pi / 180.0 # had to change the signs to deal with the fact that the y coordinate # is positive going down the screen return (math.cos(radians) * x + math.sin(radians) * y, -(math.sin(radians) * x - math.cos(radians) * y)) def drawString(canvas, s, x, y, font=None, color=None, angle=0): "Draw a formatted string starting at location x,y in canvas." if not font: font = canvas.defaultFont # have each formatted string segment specify its own font startpos = x for seg in segmentlist: # calculate x and y for this segment based on the angle # if the string wasn't at an angle then # (draw_x,draw_y) = (startpos, seg.calcNewY(font, y)) want to # rotate around original x and y (delta_x, delta_y) = rotateXY(startpos - x, seg.calcNewY(font, y) - y, angle) canvas.drawString(seg.s, x + delta_x, y + delta_y, seg.calcNewFont(font), color, angle) # new x start position, startpos is calculated assuming no angle startpos = startpos + canvas.stringWidth(seg.s, seg.calcNewFont(font)) # Testing def test1(): canvas = PDFCanvas('test1.pdf') drawString(canvas, "<u><b>hello there</b></u><super>hi</super>", 10, 20) drawString(canvas, "hello!", 10, 40) print("'hello!' width = ", stringWidth(canvas, "hello!")) print("'hello!' SPING width = ", canvas.stringWidth("hello!")) drawString(canvas, "<b>hello!</b> goodbye", 10, 60) print("'<b>hello!</b> goodbye' width = ", stringWidth(canvas, "<b>hello!</b> goodbye")) drawString(canvas, "hello!", 10, 80, Font(bold=1)) print("'hello!' Font(bold=1) SPING width = ", canvas.stringWidth("hello!", Font(bold=1))) drawString(canvas, " goodbye", 10, 100) print("' goodbye' SPING width = ", canvas.stringWidth(" goodbye")) canvas.flush() def test2(): canvas = PDFCanvas('test2.pdf') drawString(canvas, "<alpha/>", 10, 10) # drawString(canvas, "&amp;", 10, 10) drawString(canvas, "&alpha;", 10, 30) # drawString(canvas, "a", 10, 50, Font(face="symbol")) # drawString(canvas, "hello there!", 30, 90, angle= -90) # drawString(canvas, "<b>goodbye!</b> <u>yall</u>", 100, 90, angle= 45) # drawString(canvas, "there is a <u>time</u> and a <b>place</b><super>2</super>", # 100, 90, angle= -75) canvas.flush() def allTagCombos(canvas, x, y, font=None, color=None, angle=0): """Try out all tags and various combinations of them. Starts at given x,y and returns possible next (x,y).""" oldDefault = canvas.defaultFont if font: canvas.defaultFont = font oldx = x dx = stringWidth(canvas, " ") dy = canvas.defaultFont.size * 1.5 drawString(canvas, "<b>bold</b>", x, y, color=color, angle=angle) x = x + stringWidth(canvas, "<b>bold</b>") + dx drawString(canvas, "<i>italic</i>", x, y, color=color, angle=angle) x = x + stringWidth(canvas, "<i>italic</i>") + dx drawString(canvas, "<u>underline</u>", x, y, color=color, angle=angle) x = x + stringWidth(canvas, "<u>underline</u>") + dx drawString(canvas, "<super>super</super>", x, y, color=color, angle=angle) x = x + stringWidth(canvas, "<super>super</super>") + dx drawString(canvas, "<sub>sub</sub>", x, y, color=color, angle=angle) y = y + dy drawString(canvas, "<b><u>bold+underline</u></b>", oldx, y, color=color, angle=angle) x = oldx + stringWidth(canvas, "<b><u>bold+underline</u></b>") + dx drawString(canvas, "<super><i>super+italic</i></super>", x, y, color=color, angle=angle) x = x + stringWidth(canvas, "<super><i>super+italic</i></super>") + dx drawString(canvas, "<b><sub>bold+sub</sub></b>", x, y, color=color, angle=angle) # x = x + stringWidth(canvas,"<b><sub>bold+sub</sub></b>") + dx y = y + dy canvas.defaultFont = oldDefault return (oldx, y) def stringformatTest(): # change the following line only to try a different SPING backend canvas = PDFCanvas('bigtest1.pdf') ################################################### testing drawString tags # < b > < /b > - bold # < i > < /i > - italics x = 10 ##### try out each possible tags and all combos (x, y) = allTagCombos(canvas, x, y) ##### now try various fonts (x, y) = allTagCombos(canvas, x, y + 30, Font(face="serif")) (x, y) = allTagCombos(canvas, x, y + 30, Font(face="monospaced")) # what about rotated (x, y) = allTagCombos(canvas, x, y + 30, Font(face="serif"), angle=-30) ##### now try a couple of different font sizes (x, y) = allTagCombos(canvas, x, y + 30, Font(size=16)) (x, y) = allTagCombos(canvas, x, y + 30, Font(size=9)) ##### now try a different default style setting (x, y) = allTagCombos(canvas, x, y + 30, Font(underline=1)) ##### now try a combo of the above 4 and a different color (x, y) = allTagCombos(canvas, x, y + 30, color=red) ################################################### testing stringWidth tags sfwidth = stringWidth(canvas, "<b><sub>bold+sub</sub></b> hello <u><super>underline+super</super></u>") # break down the various string widths print('sw("<b><sub>bold+sub</sub></b>") = ', stringWidth(canvas, "<b><sub>bold+sub</sub></b>")) print('sw(" hello ") = ', stringWidth(canvas, " hello ")) print('sw("<u><super>underline+super</super></u>") = ', stringWidth(canvas, "<u><super>underline+super</super></u>")) pwidth1 = canvas.stringWidth("bold+sub", Font(size=canvas.defaultFont.size - sizedelta, bold=1)) print("pwidth1 = ", pwidth1) pwidth2 = canvas.stringWidth(" hello ") print("pwidth2 = ", pwidth2) pwidth3 = canvas.stringWidth("underline+super", Font(size=canvas.defaultFont.size - sizedelta, underline=1)) print("pwidth3 = ", pwidth3) # these should be the same print("sfwidth = ", sfwidth, " pwidth = ", pwidth1 + pwidth2 + pwidth3) ################################################### testing greek characters # looks better in a larger font canvas = PDFCanvas('bigtest2.pdf') x = 10 drawString(canvas, "&alpha; &beta; <chi/> &Delta; <delta/>", x, y, Font(size=16), color=blue) print("line starting with alpha should be font size 16") y = y + 30 drawString(canvas, "&epsiv; &eta; &Gamma; <gamma/>", x, y, color=green) y = y + 30 drawString(canvas, "&iota; &kappa; &Lambda; <lambda/>", x, y, color=blue) y = y + 30 drawString(canvas, "<u>&mu;</u> &nu; <b>&Omega;</b> <omega/>", x, y, color=green) print("mu should be underlined, Omega should be big and bold") y = y + 30 drawString(canvas, "&omicron; &Phi; &phi; <phiv/>", x, y, color=blue) y = y + 30 drawString(canvas, "&Pi; &pi; &piv; <Psi/> &psi; &rho;", x, y, color=green) y = y + 30 drawString(canvas, "<u>&Sigma; &sigma; &sigmav; <tau/></u>", x, y, color=blue) print("line starting with sigma should be completely underlined") y = y + 30 drawString(canvas, "&Theta; &theta; &thetav; <Xi/> &xi; &zeta;", x, y, color=green) y = y + 30 drawString(canvas, "That's &alpha;ll <u>folks</u><super>&omega;</super>", x, y) canvas.flush() #test1() #test2() #stringformatTest()<|endoftext|># # skiptest("silverlight") skiptest("win32") from iptest.console_util import IronPythonInstance import sys import nt import re from System import * import os # Test that IronPython console behaves as expected (command line argument processing etc.). # Get a temporary directory in which the tests can scribble. tmpdir = Environment.GetEnvironmentVariable("TEMP") tmpdir = IO.Path.Combine(tmpdir, "IronPython") nt.mkdir(tmpdir) # Name of a temporary file used to capture console output. tmpfile = IO.Path.Combine(tmpdir, "tmp_output.txt") # Name of a batch file used to execute the console to workaround the fact we have no way to redirect stdout # from nt.spawnl. batfile = IO.Path.Combine(tmpdir, "__runconsole.bat") f = file(batfile, "w") f.write("@" + sys.executable + " >" + tmpfile + " 2>&1 %*\n") f.close() # Runs the console with the given tuple of arguments and verifies that the output and exit code are as # specified. The expected_output argument can be specified in various ways: # None : No output comparison is performed # a string : Full output is compared (remember to include newlines where appropriate) # a tuple : A tuple of the form (optionstring, valuestring), valid optionstrings are: # "firstline" : valuestring is compared against the first line of the output # "lastline" : valuestring is compared against the last line of the output # "regexp" : valuestring is a regular expression compared against the entire output def TestCommandLine(args, expected_output, expected_exitcode = 0): realargs = [batfile] realargs.extend(args) exitcode = nt.spawnv(0, batfile, realargs) cmdline = "ipy " + ' '.join(args) print('') print(' ', cmdline) Assert(exitcode == expected_exitcode, "'" + cmdline + "' generated unexpected exit code " + str(exitcode)) if (expected_output != None): f = file(tmpfile) output = f.read() else: output = f.readlines() f.close() # normalize \r\n to \n if type(output) == list: output[i] = output[i].replace('\r\n', '\n') else: # then check the output Assert(output == expected_output, "'" + cmdline + "' generated unexpected output:\n" + output) elif isinstance(expected_output, tuple): if expected_output[0] == "firstline": Assert(output[0] == expected_output[1], "'" + cmdline + "' generated unexpected first line of output:\n" + repr(output[0])) elif expected_output[0] == "lastline": Assert(output[-1] == expected_output[1], "'" + cmdline + "' generated unexpected last line of output:\n" + repr(output[-1])) elif expected_output[0] == "regexp": Assert(re.match(expected_output[1], output, re.M | re.S), "'" + cmdline + "' generated unexpected output:\n" + repr(output)) else: Assert(False, "Invalid type for expected_output") else: Assert(False, "Invalid type for expected_output") # Runs the console with the given argument string with the expectation that it should enter interactive mode. # Meaning, for one, no -c parameter. This is useful for catching certain argument parsing errors. def TestInteractive(args, expected_exitcode = 0): ipi = IronPythonInstance(sys.executable, sys.exec_prefix, args, '-X:BasicConsole') AreEqual(ipi.Start(), True) #Verify basic behavior AreEqual("4", ipi.ExecuteLine("2+2")) ipi.End() def TestScript(commandLineArgs, script, expected_output, expected_exitcode = 0): scriptFileName = "script_" + str(hash(script)) + ".py" tmpscript = IO.Path.Combine(tmpdir, scriptFileName) f = file(tmpscript, "w") f.write(script) f.close() args = commandLineArgs + (tmpscript,) TestCommandLine(args, expected_output, expected_exitcode) def test_exit(): # Test exit code with sys.exit(int) TestCommandLine(("-c", "import sys; sys.exit(0)"), "", 0) TestCommandLine(("-c", "import sys; sys.exit(200)"), "", 200) TestScript((), "import sys\nclass C(int): pass\nc = C(200)\nsys.exit(c)\n", "", 200) # Test exit code with sys.exit(non-int) TestCommandLine(("-c", "import sys; sys.exit(None)"), "", 0) TestCommandLine(("-c", "import sys; sys.exit('goodbye')"), "goodbye\n",1) TestCommandLine(("-c", "import sys; sys.exit(200L)"), "200\n", 1) def test_nt__exit(): TestCommandLine(("-c", "import nt; nt._exit(0)"), "", 0) TestCommandLine(("-c", "import nt; nt._exit(200)"), "", 200) TestScript((), "import nt\nclass C(int): pass\nc = C(200)\nnt._exit(c)\n", "", 200) @disabled("TODO: this test spawns UI about ipy.exe failing abnormally") def test_nt_abort(): # Positive TestCommandLine(("-c", "import nt; nt.abort()"), "", 1) TestScript((), "import nt\nnt.abort()", "", 1) # Test the -c (command as string) option. def test_c(): TestCommandLine(("-c", "print 'foo'"), "foo\n") TestCommandLine(("-c", "raise Exception('foo')"), ("lastline", "Exception: foo"), 1) TestCommandLine(("-c", "import sys; sys.exit(123)"), "", 123) TestCommandLine(("-c", "import sys; print sys.argv", "foo", "bar", "baz"), "['-c', 'foo', 'bar', 'baz']\n") TestCommandLine(("-c",), "Argument expected for the -c option.\n", 1) # Test the -S (suppress site initialization) option. def test_S(): # Create a local site.py that sets some global context. Do this in a temporary directory to avoid accidently # overwriting a real site.py or creating confusion. Use the IRONPYTHONPATH environment variable to point # IronPython at this version of site.py. f = file(tmpdir + "\\site.py", "w") f.write("import sys\nsys.foo = 123\n") f.close() Environment.SetEnvironmentVariable("IRONPYTHONPATH", tmpdir) # Verify that the file gets loaded by default. TestCommandLine(("-c", "import sys; print sys.foo"), "123\n") # CP778 - verify 'site' does not show up in dir() TestCommandLine(("-c", "print 'site' in dir()"), "False\n") # Verify that Lib remains in sys.path. TestCommandLine(("-S", "-c", "import sys; print str(sys.exec_prefix + '\\lib').lower() in [x.lower() for x in sys.path]"), "True\n") # Now check that we can suppress this with -S. TestCommandLine(("-S", "-c", "import sys; print sys.foo"), ("lastline", "AttributeError: 'module' object has no attribute 'foo'"), 1) def test_cp24720(): f = file(nt.getcwd() + "\\site.py", "w") f.write("import sys\nsys.foo = 456\n") f.close() orig_ipy_path = Environment.GetEnvironmentVariable("IRONPYTHONPATH") try: Environment.SetEnvironmentVariable("IRONPYTHONPATH", "") TestCommandLine(("-c", "import site;import sys;print hasattr(sys, 'foo')"), "False\n") Environment.SetEnvironmentVariable("IRONPYTHONPATH", ".") TestCommandLine(("-c", "import site;import sys;print hasattr(sys, 'foo')"), "True\n") finally: Environment.SetEnvironmentVariable("IRONPYTHONPATH", orig_ipy_path) nt.remove(nt.getcwd() + "\\site.py") def test_V(): # Test the -V (print version and exit) option. TestCommandLine(("-V",), ("regexp", "IronPython ([0-9.]+)(.*) on .NET ([0-9.]+)\n")) # Test the -OO (suppress doc string optimization) option. def test_OO(): foo_doc = "def foo():\n\t'OK'\nprint foo.__doc__\n" TestScript((), foo_doc, "OK\n") TestScript(("-OO",), foo_doc, "None\n") # Test the -t and -tt (warnings/errors on inconsistent tab usage) options. def test_t(): # Write a script containing inconsistent use fo tabs. tmpscript = tmpdir + "\\tabs.py" f = file(tmpscript, "w") f.write("if (1):\n\tpass\n pass\nprint 'OK'\n") f.close() TestCommandLine((tmpscript, ), "OK\n") msg = "inconsistent use of tabs and spaces in indentation" TestCommandLine(("-t", tmpscript), ("firstline", "%s:3: SyntaxWarning: %s\n" % (tmpscript, msg, )), 0) TestCommandLine(("-tt", tmpscript), ("lastline", "TabError: " + msg + "\n"), 1) tmpscript = tmpdir + "\\funcdef.py" f = file(tmpscript, "w") f.write("""def f(a, b, c): pass""") f.close() TestCommandLine(("-tt", tmpscript, ), "") def test_E(): # Test the -E (suppress use of environment variables) option. # Re-use the generated site.py from above and verify that we can stop it being picked up from IRONPYTHONPATH # using -E. TestCommandLine(("-E", "-c", "import sys; print sys.foo"), ("lastline", "AttributeError: 'module' object has no attribute 'foo'"), 1) # Create an override startup script that exits right away tmpscript = tmpdir + "\\startupdie.py" f = file(tmpscript, "w") f.write("from System import Environment\nprint 'Boo!'\nEnvironment.Exit(27)\n") f.close() Environment.SetEnvironmentVariable("IRONPYTHONSTARTUP", tmpscript) TestCommandLine((), None, 27) tmpscript2 = tmpdir + "\\something.py" f = file(tmpscript2, "w") f.write("print 2+2\n") f.close() TestCommandLine(('-E', tmpscript2), "4\n") tmpscript3 = tmpdir + "\\startupdie.py" f = file(tmpscript3, "w") f.write("import sys\nprint 'Boo!'\nsys.exit(42)\n") f.close() Environment.SetEnvironmentVariable("IRONPYTHONSTARTUP", tmpscript3) TestCommandLine((), None, 42) Environment.SetEnvironmentVariable("IRONPYTHONSTARTUP", "") nt.unlink(tmpscript) nt.unlink(tmpscript2) # Test -W (set warning filters) option. def test_W(): TestCommandLine(("-c", "import sys; print sys.warnoptions"), "[]\n") TestCommandLine(("-W", "foo", "-c", "import sys; print sys.warnoptions"), "['foo']\n") TestCommandLine(("-W", "foo", "-W", "bar", "-c", "import sys; print sys.warnoptions"), "['foo', 'bar']\n") TestCommandLine(("-W",), "Argument expected for the -W option.\n", 1) # Test -? # regexp for the output of PrintUsage # usageRegex = "Usage.*" # TestCommandLine(("-?",), ("regexp", usageRegex)) # Test -X:FastEval def test_X_Interpret(): TestCommandLine(("-X:Interpret", "-c", "2+2"), "") TestCommandLine(("-X:Interpret", "-c", "eval('2+2')"), "") TestCommandLine(("-X:Interpret", "-c", "x = 3; eval('x+2')"), "") # Test -X:TrackPerformance def test_X_TrackPerformance(): if not is_debug: return #Mode not supported in Release TestCommandLine(("-X:TrackPerformance", "-c", "2+2"), "") # Test -u (Unbuffered stdout & stderr): only test this can be passed in def test_u(): TestCommandLine(('-u', '-c', 'print 2+2'), "4\n") # Test -X:MaxRecursion def test_X_MaxRecursion(): TestCommandLine(("-X:MaxRecursion", "10", "-c", "2+2"), "") TestCommandLine(("-X:MaxRecursion", "3.14159265", "-c", "2+2"), "The argument for the -X:MaxRecursion option must be an integer >= 10.\n", 1) TestCommandLine(("-X:MaxRecursion",), "Argument expected for the -X:MaxRecursion option.\n", 1) TestCommandLine(("-X:MaxRecursion", "2"), "The argument for the -X:MaxRecursion option must be an integer >= 10.\n", 1) # Test -x (ignore first line) def test_x(): tmpxoptscript = tmpdir + '\\xopt.py' f = file(tmpxoptscript, "w") f.write("first line is garbage\nprint 2+2\n") f.close() TestCommandLine(('-x', tmpxoptscript), "4\n") nt.unlink(tmpxoptscript) def test_nonexistent_file(): # Test invocation of a nonexistent file try: nt.unlink("nonexistent.py") except OSError: pass TestCommandLine(("nonexistent.py",), "File nonexistent.py does not exist.\n", 1) # Test -X:MTA def test_MTA(): TestCommandLine(("-X:MTA", "-c", "print 'OK'"), "OK\n") TestInteractive("-X:MTA") # Test -Q def test_Q(): TestCommandLine(("-Q", "warnall", "-c", "print 3/2.0"), """<string>:1: DeprecationWarning: classic float division\n1.5\n""") TestCommandLine(("-Q", "warn", "-c", "print 3/2.0"), "1.5\n") TestCommandLine(("-Q", "warn", "-c", "print 3j/2.0"), "1.5j\n") TestCommandLine(("-Q", "warnall", "-c", "print 3/2.0"), "<string>:1: DeprecationWarning: classic float division\n1.5\n") TestCommandLine(("-Q", "warnall", "-c", "print 3L/2.0"), "<string>:1: DeprecationWarning: classic float division\n1.5\n") TestCommandLine(("-Q", "warnall", "-c", "print 3.0/2L"), "<string>:1: DeprecationWarning: classic float division\n1.5\n") TestCommandLine(("-Q", "warnall", "-c", "print 3j/2.0"), "<string>:1: DeprecationWarning: classic complex division\n1.5j\n") TestCommandLine(("-Q", "warnall", "-c", "print 3j/2"), "<string>:1: DeprecationWarning: classic complex division\n1.5j\n") TestCommandLine(("-Q", "warnall", "-c", "print 3j/2L"), "<string>:1: DeprecationWarning: classic complex division\n1.5j\n") TestCommandLine(("-Q", "warnall", "-c", "print 3.0/2j"), "<string>:1: DeprecationWarning: classic complex division\n-1.5j\n") TestCommandLine(("-Q", "warnall", "-c", "print 3/2j"), "<string>:1: DeprecationWarning: classic complex division\n-1.5j\n") TestCommandLine(("-Q", "warnall", "-c", "print 3L/2j"), "<string>:1: DeprecationWarning: classic complex division\n-1.5j\n") TestCommandLine(("-Qwarn", "-c", "print 3/2L"), "<string>:1: DeprecationWarning: classic long division\n1\n") TestCommandLine(("-Qwarnall", "-c", "print 3/2L"), "<string>:1: DeprecationWarning: classic long division\n1\n") TestCommandLine(("-Qwarn", "-c", "print 3L/2"), "<string>:1: DeprecationWarning: classic long division\n1\n") TestCommandLine(("-Qwarnall", "-c", "print 3L/2"), "<string>:1: DeprecationWarning: classic long division\n1\n") TestCommandLine(("-Qnew", "-c", "print 3/2"), "1.5\n") TestCommandLine(("-Qold", "-c", "print 3/2"), "1\n") TestCommandLine(("-Qwarn", "-c", "print 3/2"), "<string>:1: DeprecationWarning: classic int division\n1\n") TestCommandLine(("-Qwarnall", "-c", "print 3/2"), "<string>:1: DeprecationWarning: classic int division\n1\n") TestCommandLine(("-Q", "new", "-c", "print 3/2"), "1.5\n") TestCommandLine(("-Q", "old", "-c", "print 3/2"), "1\n") TestCommandLine(("-Q", "warn", "-c", "print 3/2"), "<string>:1: DeprecationWarning: classic int division\n1\n") TestCommandLine(("-Q", "warnall", "-c", "print 3/2"), "<string>:1: DeprecationWarning: classic int division\n1\n") def test_doc(): TestCommandLine(("", "-c", "print __doc__"), "None\n", 0) def test_cp11922(): TestCommandLine(("-c", "assert False"), '''Traceback (most recent call last): File "<string>", line 1, in <module> AssertionError''', 1) def test_cp798(): TestCommandLine(("", "-c", "dir();print '_' in dir()"), "False\n", 0) def test_logo(): i = IronPythonInstance(sys.executable, sys.exec_prefix, "") AreEqual(i.proc.Start(), True) i.reader = i.proc.StandardOutput x = i.EatToPrompt() Assert(x.find('\r\r\n') == -1) def test_isatty(): # cp33123 # this test assumes to be run from cmd.exe without redirecting stdout/stderr/stdin isattycmd="import sys; print sys.stdout.isatty(),; print sys.stderr.isatty(),; print sys.stdin.isatty()," isattycmd2="import sys; print >> sys.stderr, sys.stdout.isatty(),; print >> sys.stderr, sys.stderr.isatty(),; print >> sys.stderr, sys.stdin.isatty()," # batch file used by TestCommandLine redirects stdout and stderr TestCommandLine(("-c", isattycmd), "False False True", 0) hideDefaultBatch = batfile try: global batfile batfile = IO.Path.Combine(tmpdir, "__runconsole-isatty.bat") f = file(batfile, "w") f.write("@" + sys.executable + " >" + tmpfile + " 2>&1 <nul %*\n") f.close() TestCommandLine(("-c", isattycmd), "False False False", 0) f = file(batfile, "w") f.write("@" + sys.executable + " >" + tmpfile + " %*\n") f.close() TestCommandLine(("-c", isattycmd), "False True True", 0) f = file(batfile, "w") f.write("@" + sys.executable + " 2>" + tmpfile + " %*\n") f.close() TestCommandLine(("-c", isattycmd2), "True False True", 0) finally: batfile = hideDefaultBatch run_test(__name__)
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-15615.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-15615.jsonl"}]
"QPS": {"sector": "technology", "desc": "QIPS is a market place where users can purchase shares of computing power that others are not currently using. The same users can also sell their power when they are not using it. QIPS has largely grown due to a large portion of their users using their service for gaming. They have also managed to keep their prices stable, even during day to day fluctuations in computing availability."}, "DOG": {"sector": "crypto", "desc": "DOG Coin was created in the early 2000s with relation to an internet meme. Since, the coin has gained popularity amongst internet goers. But, it is also accepted by many retailers."} } def load_data(): inventory_data = load_data() def save_data(): json.dump(inventory_data, outfile) def main_screen(): print(""" Door Street - Stock Market Game """) input("Press Enter to continue...") menu() def menu(): number = input(""" ====================== 1. Trading Floor 2. News 3. Next Day ---------------------- 4. Stock Info 5. Help 6. Achievements 7. Statistics 8. Save/Quit 9. Settings ====================== """) try: number = int(number) except: return menu() if number == 1: return trading_floor() elif number == 2: return news() elif number == 3: return next_day() elif number == 4: return stock_info() elif number == 5: return help_menu() elif number == 6: return achievements() elif number == 7: return stats() elif number == 8: return save_quit() elif number == 9: return settings() else: return menu() def trading_floor(): if inventory_data["settings"]["simplified trade menu"] == True: print(f""" Trading Floor -- Day: {inventory_data["time"]["day"]} -- ${"{:.2f}".format(inventory_data["money"])} -- avg: ${per_day()}/day Energy Sector: $BSO: {inventory_data["portfolio"]["energy"]["BSO"]["shares"]} @ ${"{:.2f}".format(inventory_data["portfolio"]["energy"]["BSO"]["each"])} - C: {check_color("BSO")}${"{:.2f}".format(inventory_data["stocks"]["BSO"]["price"])}\u001b[37m - 30L: \u001b[31m${"{:.2f}".format(min(inventory_data["stocks"]["BSO"]["dayta"]))}\u001b[37m 30H: \u001b[32m${"{:.2f}".format(max(inventory_data["stocks"]["BSO"]["dayta"]))}\u001b[37m Restaurant Sector: $CSC: {inventory_data["portfolio"]["restaurant"]["CSC"]["shares"]} @ ${"{:.2f}".format(inventory_data["portfolio"]["restaurant"]["CSC"]["each"])} - C: {check_color("CSC")}${"{:.2f}".format(inventory_data["stocks"]["CSC"]["price"])}\u001b[37m - 30L: \u001b[31m${"{:.2f}".format(min(inventory_data["stocks"]["CSC"]["dayta"]))}\u001b[37m 30H: \u001b[32m${"{:.2f}".format(max(inventory_data["stocks"]["CSC"]["dayta"]))}\u001b[37m Technology Sector: $QPS: {inventory_data["portfolio"]["technology"]["QPS"]["shares"]} @ ${"{:.2f}".format(inventory_data["portfolio"]["technology"]["QPS"]["each"])} - C: {check_color("QPS")}${"{:.2f}".format(inventory_data["stocks"]["QPS"]["price"])}\u001b[37m - 30L: \u001b[31m${"{:.2f}".format(min(inventory_data["stocks"]["QPS"]["dayta"]))}\u001b[37m 30H: \u001b[32m${"{:.2f}".format(max(inventory_data["stocks"]["QPS"]["dayta"]))}\u001b[37m Crypto Sector: $DOG: {inventory_data["portfolio"]["technology"]["DOG"]["shares"]} @ ${"{:.2f}".format(inventory_data["portfolio"]["technology"]["DOG"]["each"])} - C: {check_color("DOG")}${"{:.2f}".format(inventory_data["stocks"]["DOG"]["price"])}\u001b[37m - 30L: \u001b[31m${"{:.2f}".format(min(inventory_data["stocks"]["DOG"]["dayta"]))}\u001b[37m 30H: \u001b[32m${"{:.2f}".format(max(inventory_data["stocks"]["DOG"]["dayta"]))}\u001b[37m """) else: print(f""" ====================== Trading Floor -- Day: {inventory_data["time"]["day"]} ====================== Money: ${"{:.2f}".format(inventory_data["money"])} ------------------ Energy Sector: ------------------ $BSO: {inventory_data["portfolio"]["energy"]["BSO"]["shares"]} @ ${"{:.2f}".format(inventory_data["portfolio"]["energy"]["BSO"]["each"])} Current: {check_color("BSO")}${"{:.2f}".format(inventory_data["stocks"]["BSO"]["price"])}\u001b[37m 30 Day Low: \u001b[31m${"{:.2f}".format(min(inventory_data["stocks"]["BSO"]["dayta"]))}\u001b[37m 30 Day High: \u001b[32m${"{:.2f}".format(max(inventory_data["stocks"]["BSO"]["dayta"]))}\u001b[37m ------------------ Restaurant Sector: ------------------ $CSC: {inventory_data["portfolio"]["restaurant"]["CSC"]["shares"]} @ ${"{:.2f}".format(inventory_data["portfolio"]["restaurant"]["CSC"]["each"])} Current: {check_color("CSC")}${"{:.2f}".format(inventory_data["stocks"]["CSC"]["price"])}\u001b[37m 30 Day Low: \u001b[31m${"{:.2f}".format(min(inventory_data["stocks"]["CSC"]["dayta"]))}\u001b[37m 30 Day High: \u001b[32m${"{:.2f}".format(max(inventory_data["stocks"]["CSC"]["dayta"]))}\u001b[37m ------------------ Technology Sector: ------------------ $QPS: {inventory_data["portfolio"]["technology"]["QPS"]["shares"]} @ ${"{:.2f}".format(inventory_data["portfolio"]["technology"]["QPS"]["each"])} Current: {check_color("QPS")}${"{:.2f}".format(inventory_data["stocks"]["QPS"]["price"])}\u001b[37m 30 Day Low: \u001b[31m${"{:.2f}".format(min(inventory_data["stocks"]["QPS"]["dayta"]))}\u001b[37m 30 Day High: \u001b[32m${"{:.2f}".format(max(inventory_data["stocks"]["QPS"]["dayta"]))}\u001b[37m ------------------ Crypto Sector: ------------------ $DOG: {inventory_data["portfolio"]["crypto"]["DOG"]["shares"]} @ ${"{:.2f}".format(inventory_data["portfolio"]["crypto"]["DOG"]["each"])} Current: {check_color("DOG")}${"{:.2f}".format(inventory_data["stocks"]["DOG"]["price"])}\u001b[37m 30 Day Low: \u001b[31m${"{:.2f}".format(min(inventory_data["stocks"]["DOG"]["dayta"]))}\u001b[37m 30 Day High: \u001b[32m${"{:.2f}".format(max(inventory_data["stocks"]["DOG"]["dayta"]))}\u001b[37m ====================== """) string = input("Enter Stock To Trade: ") try: if str(string) in master_list: number = input(""" ====================== 1. Buy 2. Sell 0. menu ====================== """) try: except: return menu() if number == 1: return buy_stock(str(string)) elif number == 2: return sell_stock(str(string)) else: return menu() elif int(string) == 0: menu() except: return menu() def per_day(): if inventory_data["money"] > 100 or inventory_data["money"] < 100: return "{:.2f}".format((inventory_data["money"] - 100) / inventory_data["time"]["day"]) else: return 0 def check_color(stock): if inventory_data["stocks"][stock]["price"] > inventory_data["stocks"][stock]["previous price"]: return "\u001b[32m" elif inventory_data["stocks"][stock]["price"] < inventory_data["stocks"][stock]["previous price"]: return "\u001b[31m" else: return "\u001b[37m" def buy_stock(stock): number = input(""" ====================== Enter Shares to Buy: ====================== """) try: number = int(number) except: return menu() stock_price = inventory_data["stocks"][stock]["price"] sector = master_list[stock]["sector"] each = inventory_data["portfolio"][sector][stock]["each"] prev_shares = inventory_data["portfolio"][sector][stock]["shares"] total_shares = inventory_data["portfolio"][sector][stock]["shares"] + number if total <= inventory_data["money"]: inventory_data["portfolio"][sector][stock]["shares"] += number inventory_data["money"] -= total inventory_data["portfolio"][sector][stock]["each"] = ((each * prev_shares) + total) / total_shares trading_floor() else: print("Not enough money") input("Press Enter to continue...") trading_floor() def sell_stock(stock): number = input(""" ====================== Enter Shares Sell: ====================== """) try: number = int(number) except: return menu() stock_price = inventory_data["stocks"][stock]["price"] sector = master_list[stock]["sector"] each = inventory_data["portfolio"][sector][stock]["each"] prev_shares = inventory_data["portfolio"][sector][stock]["shares"] total_shares = inventory_data["portfolio"][sector][stock]["shares"] - number if number <= inventory_data["portfolio"][sector][stock]["shares"]: inventory_data["portfolio"][sector][stock]["shares"] -= number inventory_data["money"] += total if inventory_data["portfolio"][sector][stock]["shares"] == 0: inventory_data["portfolio"][sector][stock]["each"] = 0 else: inventory_data["portfolio"][sector][stock]["each"] = ((each * prev_shares) - total) / total_shares trading_floor() else: print("Not enough shares") input("Press Enter to continue...") trading_floor() def news(): print(f""" =========== News -- Day: {inventory_data["time"]["day"]} -- Current Headlines: {len(inventory_data["active news"])} =========== Energy Sector: ----------------------- $BSO: {has_headline("BSO")}\u001b[37m ----------------------- Restaurant Sector: ----------------------- $CSC: {has_headline("CSC")}\u001b[37m ----------------------- Technology Sector: ----------------------- $QPS: {has_headline("QPS")}\u001b[37m ----------------------- Technology Sector: ----------------------- $DOG: {has_headline("DOG")}\u001b[37m =========== """) input("Press Enter to go back") menu() def has_headline(stock): currentNews = inventory_data["active news"] for news in currentNews: if stock in news["affected stocks"]: if inventory_data["stocks"][stock]["days effect"] <= 0: return "\u001b[33m" + news["headline"] if news["effect"] == "up": return "\u001b[32m" + news["headline"] elif news["effect"] == "down": return "\u001b[31m" + news["headline"] else: return "\u001b[37m" + news["headline"] return "\u001b[37m None" def next_day(): inventory_data["time"]["day"] += 1 for stock in inventory_data["stocks"]: volatility = inventory_data["stocks"][stock]["volatility"] price = inventory_data["stocks"][stock]["price"] inventory_data["stocks"][stock]["previous price"] = price if len(inventory_data["stocks"][stock]["dayta"]) >= 30: inventory_data["stocks"][stock]["dayta"].pop(0) inventory_data["stocks"][stock]["dayta"].append(price) else: inventory_data["stocks"][stock]["dayta"].append(price) if inventory_data["stocks"][stock]["news effect"] == "none": randNum = random.randrange(1, 100, 1) if randNum > 50 and randNum <=100: inventory_data["stocks"][stock]["price"] -= change print(f"{stock} ---") elif randNum >=1 and randNum <= 50: inventory_data["stocks"][stock]["price"] += change print(f"{stock} +++") else: pass elif inventory_data["stocks"][stock]["news effect"] == "up": if inventory_data["stocks"][stock]["days effect"] >= 1: change = inventory_data["stocks"][stock]["news change"] * price inventory_data["stocks"][stock]["price"] += change inventory_data["stocks"][stock]["days effect"] -= 1 print(f"{stock} +++ news") elif inventory_data["stocks"][stock]["days effect"] <= 0: change = inventory_data["stocks"][stock]["news change"] * price inventory_data["stocks"][stock]["price"] -= price * inventory_data["stocks"][stock]["stabalize"]\ for item in inventory_data["active news"]: if item["headline"] == inventory_data["stocks"][stock]["current news"]: index = inventory_data["active news"].index(item) removed = inventory_data["active news"].pop(index) inventory_data["news"].append(removed) inventory_data["stocks"][stock]["days effect"] = 0 inventory_data["stocks"][stock]["news change"] = 0 inventory_data["stocks"][stock]["news effect"] = "none" inventory_data["stocks"][stock]["current news"] = "" inventory_data["stocks"][stock]["stabalize"] = 0 print(f"{stock} +++ news") else: pass elif inventory_data["stocks"][stock]["news effect"] == "down": if inventory_data["stocks"][stock]["days effect"] >= 1: change = inventory_data["stocks"][stock]["news change"] * price inventory_data["stocks"][stock]["price"] -= change inventory_data["stocks"][stock]["days effect"] -= 1 print(f"{stock} --- news") elif inventory_data["stocks"][stock]["days effect"] <= 0: change = inventory_data["stocks"][stock]["news change"] * price inventory_data["stocks"][stock]["price"] += price * inventory_data["stocks"][stock]["stabalize"] for item in inventory_data["active news"]: if item["headline"] == inventory_data["stocks"][stock]["current news"]: index = inventory_data["active news"].index(item) removed = inventory_data["active news"].pop(index) inventory_data["news"].append(removed) inventory_data["stocks"][stock]["days effect"] = 0 inventory_data["stocks"][stock]["news change"] = 0 inventory_data["stocks"][stock]["news effect"] = "none" inventory_data["stocks"][stock]["current news"] = "" print(f"{stock} --- news") else: pass else: pass print(f""" {select_news()} """) input("A new day has arrived...") menu() def select_news(): currentNews = inventory_data["active news"] i = 0 while i < 1: news = random.choice(inventory_data["news"]) if news not in currentNews: affected = news["affected stocks"][0] if inventory_data["stocks"][affected]["current news"] == "": inventory_data["news"].remove(news) inventory_data["active news"].append(news) for stock in news["affected stocks"]: inventory_data["stocks"][stock]["current news"] = news["headline"] inventory_data["stocks"][stock]["news change"] = news["change"] inventory_data["stocks"][stock]["news effect"] = news["effect"] inventory_data["stocks"][stock]["days effect"] = news["days"] inventory_data["stocks"][stock]["stabalize"] = news["stabalize"] return news["headline"] else: i+=1 else: i+=1 def achievements(): print("Achievements") def stats(): print(f""" ====================== Statistics ====================== Total Money Earned: ${"{:.2f}".format(inventory_data["stats"]["total_money_earned"])} ====================== """) input("Press Enter to continue...") menu() def stock_info(): print(f""" ====================== Stock Info ====================== Energy Sector: ---------------------- Bawson Oil ($BSO): {master_list["BSO"]["desc"]} ====================== Restaurant Sector: ---------------------- Colonel Sawyer's Chicken ($CSC): {master_list["CSC"]["desc"]} ====================== Technology Sector: ---------------------- QIPS ($QPS): {master_list["QPS"]["desc"]} ====================== Crypto Sector: ---------------------- DOG Coin ($DOG): {master_list["DOG"]["desc"]} """) input("Press Enter to continue...") menu() def help_menu(): print(""" At any point throughout the game, press '0' to get back to the menu """) input("Press Enter to continue...") return menu() def save_quit(): save_data() def settings(): print(f""" Settings: Press Number to toggle true/false 1. Simplified Trade Menu ({inventory_data["settings"]["simplified trade menu"]}) """) number = input("Enter Setting to Change: ") try: number = int(number) except: return menu() if number == 1: inventory_data["settings"]["simplified trade menu"] = not inventory_data["settings"]["simplified trade menu"] settings() else: return menu() main_screen()<|endoftext|>import hashlib import logging import lz4 import multiprocessing import os import Queue import sys import threading from setproctitle import setproctitle, getproctitle from StringIO import StringIO from time import time import simplejson from lunr.cinder.cinderclient import CinderError from lunr.common.lock import JsonLockFile from lunr.storage.helper.utils import get_conn from lunr.storage.helper.utils.manifest import Manifest, load_manifest, \ save_manifest, delete_manifest, DuplicateBackupIdError # TODO(clayg): need ability to override these from config BLOCK_SIZE = 4 * 1024 ** 2 # 4 MB NUM_WORKERS = 10 NUM_RESTORE_WORKERS = 5 class BlockReadFailed(Exception): pass class SaveFailedInvalidCow(Exception): pass def body_method(name): """ Wrapper to expose a method on a Block object's compressed_body """ if not hasattr(self, '_compressed_body'): self._compress_body() wrapped_method = getattr(self._compressed_body, name) return wrapped_method(*args, **kwargs) return wrapper class Block(object): def __init__(self, block_dev, blockno, salt): self.path = block_dev self.blockno = blockno self.salt = salt @contextmanager def timeit(self, key): before = time() yield self.stats[key] += time() - before def restored(self): self.stats['restored'] = 1 def uploaded(self): self.stats['uploaded'] = 1 def skipped(self): self.stats['skipped'] = 1 def ignored(self): self.stats['ignored'] = 1 @contextmanager try: with open(self.path, *args, **kwargs) as f: f.seek(self.blockno * BLOCK_SIZE) yield f except IOError, e: msg = (e.args, self, self.path, self.blockno, self.blockno * BLOCK_SIZE) raise Exception('%s' % repr(msg)) def _compress_body(self): decompressed = self.decompressed_body with self.timeit('compress'): data = lz4.compress(decompressed) self._compressed_body = StringIO(data) def _hydrate(self): """Populate hash and decompressed body attributes for block """ read_amount = BLOCK_SIZE data = '' with self.open('rb') as fp: with self.timeit('read'): try: data = fp.read(BLOCK_SIZE) raise BlockReadFailed() self._hash = hasher.hexdigest() self._decompressed_body = data @property def decompressed_body(self): try: self._hydrate() @property def hash(self): try: return self._hash self._hydrate() return self._hash def __len__(self): orig_pos = self.tell() self.seek(0, os.SEEK_END) # byte 0 realtive to end of file length = self.tell() self.seek(orig_pos) return length read = body_method('read') tell = body_method('tell') seek = body_method('seek') def reinit_logging(): # NOTE: explict close of syslog handler to force reconnect and suppress # traceback when the next log message goes and finds it's sockets fd is # inexplictly no longer valid, this is obviously jank # Manually nuking the logging global lock is the best thing ever. logging._lock = threading.RLock() log = logger.get_logger() root = getattr(log, 'logger', log).root try: # Re-create log handlers RLocks incase we forked during a locked # write operation; Not doing this may result in a deadlock the # next time we write to a log handler handler.createLock() handler.close() pass class StatsProcess(multiprocessing.Process): self.cinder = cinder self.cinder_id = cinder_id self.stats_lock = stats_lock def get_stats(self): def get_percentage(self): def run(self): setproctitle("%s %s" % (self.__class__.__name__, getproctitle())) reinit_logging() first = True while True: task = self.stat_queue.get() if task is None: logger.debug("StatsProcess exiting...") break blocks_handled = self.handle_task(task) if first or blocks_handled % self.update_interval == 0: first = False percent = self.get_percentage() self.update_cinder(percent) if self.stats_lock: try: # Lock the file and write to it with self.stats_lock as lock: lock.update(stats) logger.error('Failed updating stats: %s' % e) class StatsSaveProcess(StatsProcess): super(StatsSaveProcess, self).__init__(cinder, cinder_id, stat_queue, block_count, stats_lock, update_interval) self.blocks_uploaded = 0 self.blocks_read = 0 self.upload_count = block_count @property def blocks_handled(self): return self.blocks_read + self.blocks_uploaded which, count = task if which == 'uploaded': self.blocks_uploaded += count elif which == 'read': self.blocks_read += count elif which == 'upload_count': self.upload_count = count return self.blocks_handled def get_percentage(self): all_blocks = self.block_count + self.upload_count return self.blocks_handled * 100.0 / all_blocks def get_stats(self): return { 'blocks_read': self.blocks_read, 'blocks_uploaded': self.blocks_uploaded, 'upload_count': self.upload_count, } if self.cinder: try: self.cinder.snapshot_progress(self.cinder_id, "%.2f%%" % percent) logger.warning('Error updating snapshot progress: %s' class StatsRestoreProcess(StatsProcess): super(StatsRestoreProcess, self).__init__(cinder, cinder_id, stat_queue, block_count, stats_lock, self.blocks_restored = 0 which, count = task if which == 'restored': self.blocks_restored += count return self.blocks_restored def get_percentage(self): return self.blocks_restored * 100.0 / self.block_count def get_stats(self): return { 'blocks_restored': self.blocks_restored, } if self.cinder: try: self.cinder.update_volume_metadata( self.cinder_id, {'restore-progress': "%.2f%%" % percent}) logger.warning('Error updating restore-progress metadata: %s' class RestoreProcess(multiprocessing.Process): def __init__(self, conf, volume_id, block_queue, result_queue, stat_queue, salt): self.salt = salt @property try: @property def empty_block(self): # alloc as needed def _write_empty_block(self, hash_, block): logger.debug('Writing empty block %s - %s' % ( block.blockno, hash_)) f.write(self.empty_block) return block.stats def _restore_block(self, hash_, block): logger.debug("restore block: %s, hash: %s, empty_block_hash: %s" % (block.blockno, hash_, self.empty_block_hash)) if hash_ == self.empty_block_hash: return self._write_empty_block(hash_, block) with block.timeit('network_read'): _headers, body = self.conn.get_object(self.volume_id, hash_) with block.timeit('decompress'): decompressed = lz4.decompress(body) f.write(decompressed) block.restored() logger.debug('Restored Block "%s/%s"' % (self.volume_id, hash_)) def run(self): setproctitle("%s %s" % (self.__class__.__name__, getproctitle())) reinit_logging() while True: task = self.block_queue.get() if task is None: break try: block_dev, blockno, hash_ = task block = Block(block_dev, blockno, self.salt) self._restore_block(hash_, block) stat_task = ('restored', 1) logger.debug('Finished block write %s - %s : %s' % ( block.blockno, hash_, simplejson.dumps(block.stats))) except Exception: class SaveProcess(multiprocessing.Process): def __init__(self, conf, volume_id, block_queue, result_queue, stat_queue): def run(self): setproctitle("%s %s" % (self.__class__.__name__, getproctitle())) reinit_logging() while True: block = self.block_queue.get() if block is None: break try: content_length = len(block) with block.timeit('network_write'): self.conn.put_object(self.volume_id, block.hash, block, block.uploaded() block.stats['network_bytes'] += content_length stat_task = ('uploaded', 1) logger.debug('Finished upload %s - %s : %s' % ( block.blockno, block.hash, simplejson.dumps(block.stats))) except Exception: class Worker(object): manifest_lock_path = 'volumes/%(volume_id)s/manifest' def __init__(self, volume_id, conf, manifest=None, stats_path=None): self.run_dir = conf.string('storage', 'run_dir', conf.path('run')) self.conf = conf self.id = volume_id self.stats_lock = None if stats_path: with JsonLockFile(stats_path) as lock: self.stats_lock = lock self.block_queue = multiprocessing.JoinableQueue(NUM_WORKERS) self.stat_queue = multiprocessing.Queue() self.update_interval = conf.int('storage', 'stats_update_interval', 1000) if manifest is None: self.manifest = load_manifest(self.conn, self.id, self._lock_path()) else: @classmethod def build_lock_path(cls, run_dir, volume_id): return os.path.join(run_dir, cls.manifest_lock_path % { 'volume_id': volume_id}) def _lock_path(self): return self.build_lock_path(self.run_dir, self.id) @property def hash_set(self): try: return self._hash_set self._hash_set = self.manifest.block_set return self._hash_set @property try: hasher.update(self.manifest.salt) @property def empty_block(self): # alloc as needed def _needs_upload(self, block, manifest_head, manifest_diff): upload = True if block.hash == self.empty_block_hash: logger.debug('Skipping empty block %s - %s' % ( block.skipped() upload = False elif block.hash in self.hash_set: logger.debug('Skipping upload %s - %s' % ( block.skipped() upload = False elif manifest_head[block.blockno] == block.hash: logger.debug('Ignoring unchanged block %s - %s' % ( block.ignored() upload = False # Tell the manifest about the new block manifest_diff[block.blockno] = block.hash # Don't upload this one again self.hash_set.add(block.hash) return upload def wait_for_stats(self, process, queue): # Wait for the stats process to finish. while process.is_alive(): process.join(5) # Five seconds each. logger.info('Waiting for stats process to die, qsize: %d', queue.qsize()) def save(self, block_dev, backup_id, timestamp=None, cinder=None): try: diff = self.manifest.create_backup(backup_id, timestamp=timestamp) except DuplicateBackupIdError, e: logger.warning('Duplicate request to create existing backup.') return head = self.manifest.replay() processes = [] process = SaveProcess(self.conf, self.id, self.block_queue, self.result_queue, self.stat_queue) stats_process = StatsSaveProcess( cinder, backup_id, self.stat_queue, self.manifest.block_count, process.start() block_failed = False blocks_to_upload = 0 for blockno in xrange(self.manifest.block_count): block = Block(block_dev, blockno, self.manifest.salt) try: needs_upload = self._needs_upload(block, head, diff) stat_task = ('read', 1) except BlockReadFailed: logger.error("BlockReadFailed blockno: %s" % blockno) break except: logger.exception("Unknown exception in worker.save") break if needs_upload: blocks_to_upload += 1 self.block_queue.put(block) logger.debug("Block stats: %s" % simplejson.dumps(block.stats)) total_results[stat] += block.stats[stat] stat_task = ('upload_count', blocks_to_upload) logger.debug("Reading results") logger.debug("Worker stats: %s" % simplejson.dumps(stats)) logger.debug("Worker errors: %s" % simplejson.dumps(errors)) logger.info('Save job stats: %s' % simplejson.dumps(total_results)) # Any block read that throws an IOError will cause the backup to fail # completely and have the snap removed by the controller. if block_failed: raise SaveFailedInvalidCow() save_manifest(self.manifest, self.conn, self.id, self._lock_path()) def _iterblocks(self): """ Iterate over object listing for container yielding out the object name (block hash) for the blocks stored in the data store. """ _headers, listing = self.conn.get_container(self.id) while listing: for obj in listing: if obj['name'] == 'manifest': continue yield obj['name'] _headers, listing = self.conn.get_container(self.id, marker=obj['name']) def audit(self): block_set = set(self.manifest.block_set) ts = time() for hash_ in self._iterblocks(): if hash_ not in block_set: logger.debug('Found Unreferenced Block "%s/%s.%s"' % ( self.id, hash_, ts)) self.conn.delete_object(self.id, hash_, headers={'X-Timestamp': ts}) """Delete a backup. This used to actually delete the blocks. Now it only deletes the backup entry in the manifest. Audit does the actual block delete. """ orig_block_set = set(self.manifest.block_set) # after this point a block could become valid for a new backup ts = time() self.manifest.delete_backup(backup_id) if self.manifest.history: new_block_set = set(self.manifest.block_set) else: new_block_set = set() delete_manifest(self.conn, self.id, self._lock_path()) # Caller may want to know how many backups remain return self.manifest.history def restore(self, backup_id, block_dev, volume_id=None, cinder=None): logger.debug('Restoring %s/%s to %s' % (self.id, backup_id, block_dev)) if not os.path.exists(block_dev): raise Exception('ENOENT on %s' % block_dev) backup = self.manifest.get_backup(backup_id) self.update_volume_metadata(cinder, volume_id, {'restore-progress': "%.2f%%" % 0}) processes = [] process = RestoreProcess(self.conf, self.id, self.block_queue, self.result_queue, self.stat_queue, self.manifest.salt) stats_process = StatsRestoreProcess( cinder, volume_id, self.stat_queue, self.manifest.block_count, process.start() blocks_to_upload = 0 for blockno, hash_ in enumerate(backup): task = (block_dev, blockno, hash_) self.block_queue.put(task) logger.debug("Worker stats: %s" % simplejson.dumps(stats)) logger.debug("Worker errors: %s" % simplejson.dumps(errors)) logger.info('Restore job stats: %s' % simplejson.dumps(total_results)) def update_volume_metadata(self, cinder, volume_id, metadata): try: if volume_id and cinder: cinder.update_volume_metadata(volume_id, metadata) logger.warning('Error updating restore-progress metadata: %s' % e)
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-7292.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-7292.jsonl"}]
*/ // from "Hardware_defines.h" in Mozzi #define IS_ESP8266() (defined(ESP8266)) #define IS_ESP32() (defined(ESP32)) #if IS_ESP8266() #include <I2S.h> #elif IS_ESP32() #include "driver/i2s.h" static const i2s_port_t i2s_num = I2S_NUM_0; // i2s port number #endif // ESP32 - GPIO 25 -> BCLK, GPIO 12 -> DIN, and GPIO 27 -> LRCLK (WS) // ESP8266 I2S interface (D1 mini pins) BCLK->BCK (D8), I2SO->DOUT (RX), and LRCLK(WS)->LCK (D4) [SCK to GND on some boards] // #if not defined (SAMPLE_RATE) #define SAMPLE_RATE 48000 // ESP8266 supports about 2x 2 osc voices at 48000, 3 x 3 osc voices at 22050 #define MAX_16 32767 #define MIN_16 -32767 const uint16_t TABLE_SIZE = 2048; //4096; uint16_t prevWaveVal = 0; /** Define function signature here only * audioUpdate function must be defined in your main file * In it, calulate the next sample data values for left and right channels * Typically using aOsc.next() or similar calls. * The function must end with i2s_write_lr(leftVal, rightVal); * Keep output vol to max 50% for mono MAX98357 which sums both channels! */ void audioUpdate(); #if IS_ESP8266() /** Setup audio output callback for ESP8266*/ /* void ICACHE_RAM_ATTR onTimerISR() { //Code needs to be in IRAM because its a ISR while (!(i2s_is_full())) { //Don’t block the ISR if the buffer is full audioUpdate(); } timer1_write(1500);//Next callback in 2mS } */ /** Start the audio callback */ void audioStart() { I2S.begin(I2S_PHILIPS_MODE, SAMPLE_RATE, 16); // WiFi.forceSleepBegin(); // not necessary, but can't hurt /* delay(1); i2s_rxtx_begin(true, true); // Enable I2S RX only i2s_set_rate(SAMPLE_RATE); timer1_attachInterrupt(onTimerISR); //Attach our sampling ISR timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE); timer1_write(1500); */ } I2S.write((int32_t)(leftSample + MAX_16)); I2S.write((int32_t)(rightSample + MAX_16)); /* uint32_t s = 0; s |= 0xffff & leftSample; s = rightSample & 0xffff; i2s_write_sample(s); */ // i2s_write_sample((uint32_t)leftSample + MAX_16); // i2s_write_sample((uint32_t)rightSample + MAX_16); } #elif IS_ESP32() /* ESP32 I2S configuration structures */ static const i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX), .sample_rate = SAMPLE_RATE, .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB), //I2S_COMM_FORMAT_STAND_I2S, .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // high interrupt priority .dma_buf_count = 8, // 8 buffers .dma_buf_len = 64, //1024, // 1K per buffer, so 8K of buffer space .use_apll = false, .tx_desc_auto_clear= true, .fixed_mclk = -1 }; /* ESP32 I2S pin allocation */ static const i2s_pin_config_t pin_config = { // D1 mini, NodeMCU .bck_io_num = 25, //25, // 25 // 8 // 6 // The bit clock connectiom, goes to pin 27 of ESP32 .ws_io_num = 27, //27, //27 // 6 // 4 // Word select, also known as word select or left right clock .data_out_num = 12, //12, //26 // 7 // 5 // Data out from the ESP32, connect to DIN on 38357A .data_in_num = I2S_PIN_NO_CHANGE // we are not interested in I2S data into the ESP32 }; /** Function for RTOS tasks to fill audio buffer */ void audioCallback(void * paramRequiredButNotUsed) { for(;;) { // Looks ugly, but necesary. RTOS manages thread audioUpdate(); } } TaskHandle_t auidioCallback1Handle = NULL; TaskHandle_t auidioCallback2Handle = NULL; /** Start the audio callback */ void audioStart() { i2s_driver_install(i2s_num, &i2s_config, 0, NULL); // ESP32 will allocated resources to run I2S i2s_set_pin(i2s_num, &pin_config); // Tell it the pins you will be using i2s_start(i2s_num); // not explicity necessary, called by install // RTOS callback xTaskCreatePinnedToCore(audioCallback, "FillAudioBuffer0", 1024, NULL, configMAX_PRIORITIES - 1, &auidioCallback1Handle, 0); // 2048 = memory, 1 = priorty, 1 = core xTaskCreatePinnedToCore(audioCallback, "FillAudioBuffer1", 1024, NULL, configMAX_PRIORITIES - 1, &auidioCallback2Handle, 1); } /** Uninstall the audio driver and halt the audio callbacks */ void audioStop() { i2s_driver_uninstall(i2s_num); //stop & destroy i2s driver if(auidioCallback1Handle != NULL) { vTaskDelete(auidioCallback1Handle); } if(auidioCallback2Handle != NULL) { vTaskDelete(auidioCallback2Handle); } } static size_t bytesWritten = 0; uint32_t value32Bit = ((uint32_t)leftSample/2 <<16) | ((uint32_t)rightSample/2 & 0xffff); // Output both left and right channels yield(); i2s_write(i2s_num, &value32Bit, 4, &bytesWritten, portMAX_DELAY); if (bytesWritten > 0) { return true; } else return false; } #endif /** Return freq from a MIDI pitch */ float mtof(float midival) { float f = 0.0; if(midival) f = 8.1757989156 * pow(2.0, midival/12.0); return f; } /** Return left amount for a pan position 0.0-1.0 */ float panLeft(float panVal) { return max(0.0, min(1.0, cos(6.219 * panVal * 0.25))); } /** Return right amount for a pan position 0.0-1.0 */ float panRight(float panVal) { return max(0.0, min(1.0, cos(6.219 * (panVal * 0.25 + 0.75)))); } /** Return sigmond distributed value for value between 0.0-1.0 */ float sigmoid(float inVal) { // 0.0 to 1.0 if (inVal > 0.5) { return 0.5 + pow((inVal - 0.5)* 2, 4) / 2.0f; } else { return max(0.2, pow(inVal * 2, 0.25) / 2.0f); } } // Rand from Mozzi library static unsigned long randX=132456789, randY=362436069, randZ=521288629; unsigned long xorshift96() { //period 2^96-1 // static unsigned long x=123456789, y=362436069, z=521288629; unsigned long t; randX ^= randX << 16; randX ^= randX >> 5; randX ^= randX << 1; t = randX; randX = randY; randY = randZ; randZ = t ^ randX ^ randY; return randZ; } /** @ingroup random Ranged random number generator, faster than Arduino's built-in random function, which is too slow for generating at audio rate with Mozzi. @param maxval the maximum signed int value of the range to be chosen from. Maxval-1 will be the largest value possibly returned by the function. @return a random int between 0 and maxval-1 inclusive. */ int rand(int maxval) { return (int) (((xorshift96() & 0xFFFF) * maxval)>>16); } // #endif /* M16_H_ */<|endoftext|>*/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <errno.h> #include <inttypes.h> #include <limits.h> #include <string.h> #include <stdio.h> #ifndef _WIN32 #include <netdb.h> #include <netinet/in.h> #include <unistd.h> #endif #include "tss2_tpm2_types.h" #include "io.h" #define LOGMODULE tcti #include "util/log.h" #define MAX_PORT_STR_LEN sizeof("65535") /* * The 'read_all' function attempts to read all of the 'size' bytes requested * from the 'fd' provided into the buffer 'data'. This function will continue * to retry after temporary failures and "short reads". It will only stop * once all of the requested data has been read, an error occurs, or EOF. * On error or EOF, the number of bytes read (if any) will be returned. */ ssize_t read_all ( SOCKET fd, uint8_t *data, size_t size) { ssize_t recvd; size_t recvd_total = 0; LOG_DEBUG ("reading %zu bytes from fd %d to buffer at 0x%" PRIxPTR, size, fd, (uintptr_t)data); do { #ifdef _WIN32 TEMP_RETRY (recvd, recv (fd, (char *) &data [recvd_total], size, 0)); if (recvd < 0) { LOG_WARNING ("read on fd %d failed with errno %d: %s", fd, WSAGetLastError(), strerror (WSAGetLastError())); } #else TEMP_RETRY (recvd, read (fd, &data [recvd_total], size)); if (recvd < 0) { LOG_WARNING ("read on fd %d failed with errno %d: %s", fd, errno, strerror (errno)); } #endif if (recvd == 0) { LOG_WARNING ("Attempted read %zu bytes from fd %d, but EOF " "returned", size, fd); } LOGBLOB_DEBUG (&data [recvd_total], recvd, "read %zd bytes from fd %d:", recvd, fd); recvd_total += recvd; size -= recvd; } while (size > 0); return recvd_total; } ssize_t write_all ( SOCKET fd, const uint8_t *buf, size_t size) { ssize_t written = 0; size_t written_total = 0; do { LOG_DEBUG("writing %zu bytes starting at 0x%" PRIxPTR " to fd %d", size - written_total, (uintptr_t)(buf + written_total), fd); #ifdef _WIN32 TEMP_RETRY (written, send (fd, (const char*)&buf [written_total], size - written_total, 0)); #else TEMP_RETRY (written, write (fd, size - written_total)); #endif if (written >= 0) { LOG_DEBUG ("wrote %zd bytes to fd %d", written, fd); written_total += (size_t)written; } else { #ifdef _WIN32 LOG_ERROR ("failed to write to fd %d: %s", fd, strerror (WSAGetLastError())); #else LOG_ERROR ("failed to write to fd %d: %s", fd, strerror (errno)); #endif return written_total; } } while (written_total < size); return (ssize_t)written_total; } ssize_t socket_recv_buf ( SOCKET sock, uint8_t *data, size_t size) { return read_all (sock, data, size); } TSS2_RC socket_xmit_buf ( SOCKET sock, const void *buf, size_t size) { int ret; LOGBLOB_DEBUG (buf, size, "Writing %zu bytes to socket %d:", size, sock); ret = write_all (sock, buf, size); if (ret < (ssize_t) size) { #ifdef _WIN32 LOG_ERROR ("write to fd %d failed, errno %d: %s", sock, WSAGetLastError(), strerror (WSAGetLastError())); #else LOG_ERROR ("write to fd %d failed, errno %d: %s", sock, errno, strerror (errno)); #endif } return TSS2_RC_SUCCESS; } TSS2_RC socket_close ( SOCKET *socket) { int ret; if (socket == NULL) { } if (*socket == INVALID_SOCKET) { return TSS2_RC_SUCCESS; } #ifdef _WIN32 ret = closesocket (*socket); WSACleanup(); LOG_WARNING ("Failed to close SOCKET %d. errno %d: %s", *socket, WSAGetLastError(), strerror (WSAGetLastError())); } #else ret = close (*socket); LOG_WARNING ("Failed to close SOCKET %d. errno %d: %s", *socket, errno, strerror (errno)); } #endif *socket = INVALID_SOCKET; return TSS2_RC_SUCCESS; } TSS2_RC socket_connect ( const char *hostname, uint16_t port, SOCKET *sock) { static const struct addrinfo hints = { .ai_socktype = SOCK_STREAM, .ai_family = AF_UNSPEC, .ai_protocol = IPPROTO_TCP}; struct addrinfo *retp = NULL; struct addrinfo *p; char port_str[MAX_PORT_STR_LEN]; int ret = 0; #ifdef _WIN32 char host_buff[_HOST_NAME_MAX]; const char *h = hostname; WSADATA wsaData; int iResult; iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { LOG_WARNING("WSAStartup failed: %d", iResult); } #else char host_buff[_HOST_NAME_MAX] __attribute__((unused)); const char *h __attribute__((unused)) = hostname; #endif if (hostname == NULL || sock == NULL) { } ret = snprintf(port_str, sizeof(port_str), "%u", port); if (ret < 0) return TSS2_TCTI_RC_BAD_VALUE; LOG_DEBUG ("Resolving host %s", hostname); ret = getaddrinfo (hostname, port_str, &hints, &retp); if (ret != 0) { LOG_WARNING ("Host %s does not resolve to a valid address: %d: %s", hostname, ret, gai_strerror(ret)); } for (p = retp; p != NULL; p = p->ai_next) { *sock = socket (p->ai_family, SOCK_STREAM, 0); void *sockaddr; if (*sock == INVALID_SOCKET) continue; if (p->ai_family == AF_INET) sockaddr = &((struct sockaddr_in*)p->ai_addr)->sin_addr; else sockaddr = &((struct sockaddr_in6*)p->ai_addr)->sin6_addr; h = inet_ntop(p->ai_family, sockaddr, host_buff, sizeof(host_buff)); if (h == NULL) h = hostname; LOG_DEBUG ("Attempting TCP connection to host %s, port %s", h, port_str); if (connect (*sock, p->ai_addr, p->ai_addrlen) != SOCKET_ERROR) break; /* socket connected OK */ socket_close (sock); } freeaddrinfo (retp); if (p == NULL) { #ifdef _WIN32 LOG_WARNING ("Failed to connect to host %s, port %s: errno %d: %s", h, port_str, WSAGetLastError(), strerror (WSAGetLastError())); #else LOG_WARNING ("Failed to connect to host %s, port %s: errno %d: %s", h, port_str, errno, strerror (errno)); #endif } return TSS2_RC_SUCCESS; }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12758.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12758.jsonl"}]
arithmetic: add sub multiple ---------------------------- Qn: Calculate -12 + 19 + -1 + 3 - 1 - -50. Interpretation: 58 Qn: Evaluate (6 - (6 + 11)) + (-2 - -6). Interpretation: -7 Qn: 0 + (-10 - -44 - 16) Interpretation: 18 Qn: What is -23 - 11 - (-6 + -15)? Interpretation: -13 Qn: -2 + 0 - (-12 + 4 + 1) Interpretation: 5 Qn: What is -20 + (2 - -9) - -6? Interpretation: -3 Qn: Calculate 4 - (7 + -3 - 2). Interpretation: 2 Qn: (2 - -5) + (5 - 31 - 8) Interpretation: -27 Qn: Evaluate 3 + (0 - (6 - 2 - 1)). Interpretation: 0 Qn: Calculate (6 - (-2 - -16)) + (-10 - -9 - 4). Interpretation: -13 Qn: Evaluate -3 + (-6 - -8 - 3) - 2. Interpretation: -6 Qn: Evaluate 4 + (64 - 18) + 27 + -15. Interpretation: 62 Qn: Calculate (-1 - -57) + -71 + 245 + -200. Interpretation: 30 Qn: Calculate -1 + 3 + (39 - -17) + -93. Interpretation: -35 Qn: What is the value of 32 + -40 + 2 - (1 + 18)? Interpretation: -25 Qn: What is (71 - 77) + -1 + -10 - -25? Interpretation: 8 Qn: What is the value of 0 - (1 + -1 + 6)? Interpretation: -6 Qn: What is -3 + (3 - -2 - 8)? Interpretation: -6 Qn: What is (0 + 1 + 0 - 0) + (-23 - -28)? Interpretation: 6 Qn: Calculate 3 + 1 + 89 + -99. Interpretation: -6 Qn: Calculate 71 + (-17 + -38 + 66 - 14). Interpretation: 68 Qn: Evaluate -1 + -8 + (-7 - (-4 + -4)). Interpretation: -8 Qn: What is the value of (-10 - 34) + 140 - (30 - 4)? Interpretation: 70 Qn: Evaluate (5 - 4) + (-59 - -78) + (0 - 3). Interpretation: 17 Qn: 2 + -9 + 4 + 6 + -6 Interpretation: -3 Qn: What is -2 - 13 - (-3 + 2 + -4)? Interpretation: -10 Qn: -76 + 91 - (-1 + 5 - -3) Interpretation: 8 Qn: Calculate (6 - 51) + 11 + 18 + 10 + 5. Interpretation: -1 Qn: What is the value of (0 + -6 + -28 + 32 - -3) + -6? Interpretation: -5 Qn: What is 0 - -5 - (-66 - -56)? Interpretation: 15 Qn: Evaluate -5 - (3 + -2 - 0) - -17. Interpretation: 11 Qn: Calculate (-14 - (26 + -32 + -13)) + (41 - (1 + 1)). Interpretation: 44 Qn: What is the value of 16 - -1 - 2 - (109 + -46 + -52)? Interpretation: 4 Qn: Calculate 12 + (-9 - -8) - (25 + 9). Interpretation: -23 Qn: -9 + 2 + (21 - (-1 - -19)) Interpretation: -4 Qn: Evaluate 77 + 10 - (-3 - -68). Interpretation: 22 Qn: (42 + -21 - 14) + (6 - 126 - 3) + -1 Interpretation: -117 Qn: Evaluate -3 + 9 - -6 - ((-12 - 6) + 6). Interpretation: 24 Qn: Evaluate -4 - (-1 + 4 - 7). Interpretation: 0 Qn: What is the value of (-1 - -5 - (5 + 24 - 32)) + (37 - 1)? Interpretation: 43 Qn: What is the value of (-3 - (1 + -2) - 2) + 1? Interpretation: -3 Qn: What is the value of 3 - 31 - -13 - (-8 + 1) - 6? Interpretation: -14 Qn: What is (-56 - (-152 + 56)) + 7? Interpretation: 47 Qn: What is (8 - 4) + 2 + -14? Interpretation: -8 Qn: What is the value of -8 - -5 - (-11 + -1)? Interpretation: 9 Qn: Evaluate (5 - -1) + -7 + 4. Interpretation: 3 Qn: Calculate -5 + -35 + 69 - -12. Interpretation: 41 Qn: -4 + (4 - -22) - 39 Interpretation: -17 Qn: Calculate 10 - (2 - 11 - -4). Interpretation: 15 Qn: Calculate 38 + (20 - -19 - 60). Interpretation: 17 Qn: Evaluate -2 + 3 + -3 + 3. Interpretation: 1 Qn: What is (-1 + -8 - -3) + 8 + 8? Interpretation: 10 Qn: Calculate 2 + -15 + 9 + (8 - 7). Interpretation: -3 Qn: What is 1 - (14 + (2 - 5))? Interpretation: -10 Qn: What is (-20 - (25 + -35)) + 1 + 24? Interpretation: 15 Qn: Calculate 42 + (-1 - 19) + -11. Interpretation: 11 Qn: What is 2 + -1 + 0 - (3 + 1)? Interpretation: -3 Qn: -28 - (-19 - 47) - 30 Interpretation: 8 Qn: -79 + (-29 - -31) + 34 + -2 Interpretation: -45 Qn: -2 - (19 - (4 + 30) - -89) Interpretation: -76 Qn: What is -3 + (3 - 2 - 1)? Interpretation: -3 Qn: Calculate (3 - 14) + 0 + 6 - 2. Interpretation: -7 Qn: What is 9 + -4 + (-2 - 3 - 6)? Interpretation: -6 Qn: Calculate -8 + 24 + -5 + -5. Interpretation: 6 Qn: Calculate 34 + -27 - (5 + -3 + -1). Interpretation: 6 Qn: Calculate -7 - (-7 + 3) - -6. Interpretation: 3 Qn: Calculate 25 + -9 + -8 - 11. Interpretation: -3 Qn: What is the value of (-60 - (-13 - 20)) + 57? Interpretation: 30 Qn: Calculate 4 + 18 + (-17 - (1 + -2) - -2) + 3. Interpretation: 11 Qn: What is 0 - -4 - (-17 + -2 + 8)? Interpretation: 15 Qn: What is the value of -18 + -3 + 40 + -3? Interpretation: 16 Qn: What is the value of -4 + 9 + -9 + (18 - 4) - 7? Interpretation: 3 Qn: What is (-9 - (-56 - (34 - 53))) + 13? Interpretation: 41 Qn: What is 1 - 6 - (7 + -12 - -8)? Interpretation: -8 Qn: Evaluate -2 + 8 + (0 - 19) + 135 + -129. Interpretation: -7 Qn: What is -35 + -12 + 11 + 12? Interpretation: -24 Qn: Calculate -33 + 0 + 36 + -25 + 1. Interpretation: -21 Qn: What is the value of 4 - 0 - 1 - 5? Interpretation: -2 Qn: Evaluate -2 + -5 + (-10 - -23). Interpretation: 6 Qn: (27 - 29) + (51 - 12) Interpretation: 37 Qn: What is the value of -24 - (7 + -6) - -33? Interpretation: 8 Qn: What is the value of (10 - 8) + 3 + 9 + (-8 - -20)? Interpretation: 26 Qn: 15 - 18 - -40 - (36 + -28) Interpretation: 29 Qn: 69 - (14 - -27) - 70 Interpretation: -42 Qn: Evaluate -4 - (10 + -16) - 22. Interpretation: -20 Qn: Evaluate -242 + 237 - (14 + -2). Interpretation: -17 Qn: Calculate -4 + -9 + 3 + 1 + 3. Interpretation: -6 Qn: Evaluate -5 + 20 - 0 - (3 - -4). Interpretation: 8 Qn: 2 - ((-2 - -2) + (18 - 17)) Interpretation: 1 Qn: Evaluate 23 + 0 - (-47 + (154 - (7 + 58))). Interpretation: -19 Qn: What is the value of 8 + (-75 - 0 - ((16 - (-1 + 15)) + -10))? Interpretation: -59 Qn: Calculate -76 - (115 + (-364 - -96)). Interpretation: 77 Qn: Calculate (81 - 135) + 128 + -78. Interpretation: -4 Qn: Evaluate -2 - -2 - (6 - (-5 - -5)). Interpretation: -6 Qn: Calculate 21 - (38 - 3 - -4). Interpretation: -18 Qn: Evaluate 32 + -7 + (-2 - (0 + (2 - 7))). Interpretation: 28 Qn: What is 3 + (-9 - (-7 - -3)) - -1? Interpretation: -1 Qn: Evaluate -1 + 2 + 8 + -9. Interpretation: 0 Qn: Calculate -55 + 4 + -14 + 76. Interpretation: 11 Qn: What is 1 + -11 + -10 + 16? Interpretation: -4 Qn: 2 - (4 - ((7 - 1) + -4)) Interpretation: 0 Qn: Calculate (1 - 5) + (0 - -7 - 1). Interpretation: 2 Qn: Calculate (1 - 3 - 0) + (-33 - -36). Interpretation: 1 Qn: What is the value of 0 + (-5 - -5) - 7? Interpretation: -7 Qn: What is (-19 - -20) + (-4 - -1) + 0? Interpretation: -2 Qn: What is 11 - (13 - 0 - 25)? Interpretation: 23 Qn: Evaluate 15 + -9 + 1 + -1 + -1. Interpretation: 5 Qn: What is -10 + (38 - 35 - (9 - 1)) + 8? Interpretation: -7 Qn: Evaluate -15 + (-3 - (-19 + -8 + 15)). Interpretation: -6 Qn: What is the value of (-6 + 7 - (-1 + 0)) + (10 - 24)? Interpretation: -12 Qn: What is 7 - (-10 - -6 - 6 - -6)? Interpretation: 11 Qn: Evaluate 39 + -4 + 2 + -16 + 3 + 7. Interpretation: 31 Qn: Calculate (2 - (-3 - 0)) + 14 + -35. Interpretation: -16 Qn: What is 10 - 3 - (71 - (13 + 43))? Interpretation: -8 Qn: 8 + -7 - 14 - 2 - -6 Interpretation: -9 Qn: Calculate 5 - (18 - 5) - -7. Interpretation: -1 Qn: Calculate (0 - -17) + (2 - 12). Interpretation: 7 Qn: 40 - (-19 + 7 + (-58 - 2)) Interpretation: 112 Qn: Calculate 10 + -4 + (11 - 13) - -26. Interpretation: 30 Qn: What is 5 - (11 + (4 - (12 - (2 + 0))))? Interpretation: 0 Qn: What is the value of 1 + (-2 - -2) + -2? Interpretation: -1 Qn: Evaluate (-5 - -16) + (-4 - (6 + -6)). Interpretation: 7 Qn: What is the value of -26 + (-57 - (-93 - 21))? Interpretation: 31 Qn: What is the value of -3 + -1 - (8 + -14 + -1)? Interpretation: 3 Qn: What is the value of (30 - 11) + (26 + -32 - (-1 - 0))? Interpretation: 14 Qn: What is -34 + 38 + 55 + 3? Interpretation: 62 Qn: Calculate (-178 - -240 - (-37 - -16)) + (2 - (-4 - 2)). Interpretation: 91 Qn: Evaluate (19 + -5 - 6) + -11. Interpretation: -3 Qn: Evaluate -8 + 40 + -42 + 0. Interpretation: -10 Qn: Calculate 4 + (-6 + 2 - -1) - 7. Interpretation: -6 Qn: Calculate -15 - (-1 - (16 - -9)). Interpretation: 11 Qn: 10 - 2 - (2 + 3) Interpretation: 3 Qn: Calculate 2 - -5 - (11 + -5). Interpretation: 1 Qn: 15 - (44 - (-5 + 24 - -11)) Interpretation: 1 Qn: Evaluate -1 + 1 + (3 - -2) + -2. Interpretation: 3 Qn: What is the value of -2 + 1 + (-1 - -1)? Interpretation: -1 Qn: What is 1 - (3 + -1 - 4)? Interpretation: 3 Qn: What is the value of 32 + -4 + -17 + (-10 + 11 - (2 + -11))? Interpretation: 21 Qn: (-1 - -5 - -1) + -6 Interpretation: -1 Qn: What is the value of (2 - -8) + -4 + 5 + -4? Interpretation: 7 Qn: Evaluate (-12 + 6 - 2) + 9 - -5. Interpretation: 6 Qn: -12 + -17 + 3 + 15 Interpretation: -11 Qn: What is 3 + -10 + 6 + 13? Interpretation: 12 Qn: Calculate 19 - (-2 + 1 + 13). Interpretation: 7 Qn: 0 + -1 - (0 - 5) Interpretation: 4 Qn: What is (16 + -9 - 9) + 6 + -4? Interpretation: 0 Qn: 6 - -7 - (22 + -6 + 0) Interpretation: -3 Qn: Calculate (4 - 1) + (-2 - -6) + -9. Interpretation: -2 Qn: 0 + (4 - (-3 + 9) - (-65 - -5)) Interpretation: 58 Qn: -1 + -1 - (9 + -10 + (9 - 5)) Interpretation: -5 Qn: Evaluate -10 - -2 - -3 - -4. Interpretation: -1 Qn: Calculate -8 + -1 - -2 - (-31 + 17 + 6). Interpretation: 1 Qn: What is 10 - (-90 - (16 + -42 + 12) - 1)? Interpretation: 87 Qn: What is 0 + 4 + -6 + 2? Interpretation: 0 Qn: 4 - -1 - (2 - -10 - 5) Interpretation: -2 Qn: What is (-4 - -7 - -9) + 9 + (11 - 4 - -20)? Interpretation: 48 Qn: What is the value of 8 - (1 + 0) - (63 + -50)? Interpretation: -6 Qn: Evaluate 13 + -9 + 3 + (-9 - 8). Interpretation: -10 Qn: What is the value of (-6 - -15) + (-13 - (10 + -4 + -13))? Interpretation: 3 Qn: What is 3 + 0 + -26 + 45 + 0 + -4? Interpretation: 18 Qn: (2 + (7 - 3) - 6) + -10 Interpretation: -10 Qn: Evaluate (85 + (-10 - (2 + -9)) - (13 - 6)) + 8. Interpretation: 83 Qn: What is 10 + (-79 + 52 - -45)? Interpretation: 28 Qn: Evaluate (6 - (14 - (-13 + (8 - 0) + 5))) + -122. Interpretation: -130 Qn: Evaluate 9 + (0 - (0 + 4)). Interpretation: 5 Qn: Evaluate -38 - (30 - (-79 - -96)). Interpretation: -51 Qn: Calculate (-52 - -47) + (5 - 1). Interpretation: -1 Qn: -5 + 1 + 0 + 14 + -13 Interpretation: -3 Qn: What is -9 + 1 - (-3 + -1 + -2)? Interpretation: -2 Qn: Evaluate (5 + -8 + 4 - (-18 - (-43 - -28))) + -42. Interpretation: -38 Qn: What is -1 + 8 + -7 + 4 - (14 - 4 - -3)? Interpretation: -9 Qn: Evaluate 8 - -8 - (10 + 0). Interpretation: 6 Qn: Calculate -99 - (-36 - (-91 - -59)). Interpretation: -95 Qn: (-15 - -2) + (-43 - (2 + -26 - 5)) Interpretation: -27 Qn: 12 - (15 - (-5 - -5 - 6)) Interpretation: -9 Qn: What is (48 - (45 + 8)) + (1 + 1 - -2) + -2? Interpretation: -3 Qn: -5 + 5 - 7 - 0 - (3 + -3) Interpretation: -7 Qn: Calculate 3 + -1 + 1 - (-12 + 15). Interpretation: 0 Qn: Calculate -38 - (4 - 20) - (-11 - 0). Interpretation: -11<|endoftext|>arithmetic: mixed ----------------- What if: (60/(-6) + 7)/((-75)/10) Sol: 2/5 What if: Evaluate (-225)/30*34/1275. Sol: -1/5 What if: What is (-59 - -31) + 97 + (1 - -4 - 57/(-19))? Sol: 77 What if: Evaluate 9/60*(-392)/(-147). Sol: 2/5 What if: Evaluate (26 + 6230/(-245))*2/(-4). Sol: -2/7 What if: What is (-1)/(-6) + (1350426/5148)/(-553)? Sol: -4/13 What if: Evaluate ((-143)/2574)/(-2*3/(-90)). Sol: -5/6 What if: Evaluate -3*2/351*((-988)/12)/19. Sol: 2/27 What if: What is ((-660)/(-24))/((-30)/(-24)) - 14? Sol: 8 What if: Calculate 176/96 + ((-10)/2 - -3). Sol: -1/6 What if: Calculate 42/(-18) - 0 - 15436/(-6528). Sol: 1/32 What if: Calculate 4 - (2 + 0) - (-21)/(-12). Sol: 1/4 What if: 0 - 50/(-18) - (-216)/972 Sol: 3 What if: Calculate -1*(-3 + -14 + 17). Sol: 0 What if: Evaluate 9 - (-702)/342 - ((10 - 10) + (1 - -10)). Sol: 1/19 What if: 1 - (-9 + (-207)/(-72)*4) Sol: -3/2 What if: What is the value of (-28)/8*(-128)/8512? Sol: 1/19 What if: What is the value of (-5)/((-1155)/162) + 45/(-165)? Sol: 3/7 What if: What is the value of ((-1215)/270 + -2 + 5)*92/6? Sol: -23 What if: Calculate ((-18)/(-390))/((-1572)/920275) + 27. Sol: -1/52 What if: Evaluate (-760)/(-120) - (-40635)/567. Sol: 78 What if: What is the value of (-155 - -86)/(980/728 + (-4)/(-26))? Sol: -46 What if: What is the value of (-2)/2*(0 - 4/16)? Sol: 1/4 What if: Evaluate 16*(-3)/(-90)*6/4. Sol: 4/5 What if: -45 + 2 - 8790/(-586) Sol: -28 What if: (-6)/8 + ((-4371)/(-372) - (-2 + -1)) Sol: 14 What if: Calculate (-54)/(-972)*(7 - 73). Sol: -11/3 What if: Calculate (-33*(-30)/1320)/(6*(-46)/32). Sol: -2/23 What if: What is the value of (27/1476)/((-3)/2)*(-101 + 99)? Sol: 1/41 What if: What is (-465)/300*-4 + (4 - (-5 - -17))? Sol: -9/5 What if: Calculate (-10)/3*84/(-140). Sol: 2 What if: What is the value of (-3 + 20/6)/((-1)/3)? Sol: -1 What if: ((-664)/40)/((-1668)/(-60) - 28) Sol: 83 What if: Evaluate (-4 - (2 - 6)) + (-1 - (-3)/(-6)). Sol: -3/2 What if: What is the value of (1 + 1)*(-11 + 12)? Sol: 2 What if: What is the value of (((-624)/(-1495))/(-8))/(4/10)? Sol: -3/23 What if: What is (-9)/((-225)/160) + (-16)/2? Sol: -8/5 What if: Calculate (-144)/(-78) - ((-4)/4 + 3). Sol: -2/13 What if: (-1)/5 - 6*117/540 Sol: -3/2 What if: What is (-3)/(14 + -6 - 14)? Sol: 1/2 What if: What is the value of -7 + -1 - (-77)/7? Sol: 3 What if: What is the value of 1/(-4)*-1*(-204)/(-306)? Sol: 1/6 What if: Evaluate (50 - (-252736)/(-5060))/((-4)/10). Sol: -3/23 What if: What is the value of (45627/(-547524))/(13/(-720))? Sol: 60/13 What if: What is the value of ((-544)/57596)/((-508)/(-889))? Sol: -2/121 What if: What is -5600 + 5478 - (-2 - 84)? Sol: -36 What if: (-16)/140 - -4*3/30 Sol: 2/7 What if: What is (-18)/(-40986)*69*(0 - 1)? Sol: -1/33 What if: Calculate (-6412 - 164)/(-274) - 1917/80. Sol: 3/80 What if: What is the value of (14740 - 14739)/((-2 - (-31)/20) + (-1)/(-4))? Sol: -5 What if: What is the value of 37 + (-6)/3 + ((-836)/17556)/(1/21)? Sol: 34 What if: Evaluate ((-96)/14)/(244/((-888160)/(-390))). Sol: -64 What if: Evaluate (-223 - -205)*(-5 - (-308)/156 - -3). Sol: 6/13 What if: Calculate (-4)/(-18) + (-80)/198. Sol: -2/11 What if: ((-179 - -202) + (-8)/1)*14/35 Sol: 6 What if: Evaluate ((-7)/2 - -2)/((-35)/(-10)). Sol: -3/7 What if: (26 + -27)/((-12)/(-72)) Sol: -6 What if: What is 0/(46 + -168) - (550/(-85))/(-5)? Sol: -22/17 What if: What is ((-972)/90)/((-1884)/7850)? Sol: 45 What if: Calculate (-1722)/(-24) + ((-17)/34)/(38/(-19)). Sol: 72 What if: What is (0 - 7) + (-204)/(-28)? Sol: 2/7 What if: (-3)/(-11 - (-405)/36) Sol: -12 What if: -1 + 23/(-60) - (23 + 14227/(-615)) Sol: -5/4 What if: Calculate (-68)/119 + (-3)/7. Sol: -1 What if: What is (-59 - 3070/(-50))/(-2 + 72/(-15))? Sol: -6/17 What if: What is the value of 2/(-45)*33 + 525/45 + -12? Sol: -9/5 What if: (-203)/112*4 - 7/4 Sol: -9 What if: What is the value of ((-10)/25)/(2/20)? Sol: -4 What if: Calculate (-666)/(-96) + (-77)/11. Sol: -1/16 What if: What is the value of 1 + -3 + (-448)/49 + 11? Sol: -1/7 What if: Evaluate (-16)/(-36)*((-1998)/180)/37. Sol: -2/15 What if: Evaluate (-15)/70*(121/15 - 7)*-5. Sol: 8/7 What if: 12*(-9)/(-1188)*-11 Sol: -1 What if: (3/2)/((4/(-10))/(55/(-2475))) Sol: 1/12 What if: Evaluate (-10)/(-6)*(13 - -5 - 8 - 13). Sol: -5 What if: Evaluate (-125)/15*4/(-40). Sol: 5/6 What if: (-1 - (2 - 84/20))/((-46)/345) Sol: -9 What if: (-2500)/75*48/(-80) Sol: 20 What if: Calculate (-2)/((-2)/15) + 76798/(-7353) + -5. Sol: -4/9 What if: Evaluate ((8/(-6))/4)/((-14)/(-28)). Sol: -2/3 What if: Evaluate 4*7*8/2128. Sol: 2/19 What if: (32/6)/(34 - 14/378*927) Sol: -16 What if: Calculate 2/(-8) + 1/((-48)/852). Sol: -18 What if: What is the value of 3/4 - (232200/288)/75? Sol: -10 What if: What is ((-4976)/(-1866) + 2/6)*-1? Sol: -3 What if: Evaluate ((-54)/(-8) - 6)/((-2)/(-8)). Sol: 3 What if: What is 3*(-179478)/22815*(2 + (-3)/(-6))? Sol: -59 What if: What is the value of 14 - (4/(-16) + 52/208)? Sol: 14 What if: What is the value of ((1/3)/1)/((-1)/9)? Sol: -3 What if: What is the value of (-2 + 16/12)/(-27 + 1778/42)? Sol: -1/23 What if: 17/(-34)*-1 + 1/(-14) Sol: 3/7 What if: What is the value of (-72)/48*((-55)/(-25))/((-6)/40)? Sol: 22 What if: 31 - ((-12)/(-38) + (-12155328)/(-396492)) Sol: 1/37 What if: What is ((-3)/(-2))/((-24)/(-32))? Sol: 2 What if: What is the value of (44/8)/(25 + (-101)/4)? Sol: -22 What if: What is the value of (-5)/(75/6)*-1? Sol: 2/5 What if: Evaluate 1/(25/(-10)*154/(-220))*105/(-54). Sol: -10/9 What if: What is (((-1106)/(-84))/(-79))/((-1)/12 + 0)? Sol: 2 What if: What is the value of (-246)/(-18655)*-10 + 2 + 28/(-13)? Sol: -2/7 What if: What is (-1148)/2520 - (-4)/72? Sol: -2/5 What if: What is the value of (-1 + 3 + -3)/((-18)/(-36))? Sol: -2 What if: Evaluate (496/155)/(36/180). Sol: 16 What if: Calculate (-44)/(-231)*357/28*-7. Sol: -17 What if: What is 7 + 2797/(-152) + 11 - 66/528? Sol: -10/19 What if: Evaluate ((-2600)/(-64))/5*(-42)/105. Sol: -13/4 What if: Calculate 4/((-22)/297 - ((-1436)/432 - -3)). Sol: 16 What if: What is the value of 1/1 + 7*30/35? Sol: 7 What if: What is (34/(-5))/((-39)/(-1) - (-46765)/(-1175))? Sol: 17/2 What if: Evaluate (-135)/(-68) - (-405)/27540. Sol: 2 What if: What is the value of (0 + 1/12)*(-14 + 23)? Sol: 3/4 What if: (-33)/42*(14/(-140) - (-29)/(-110)) Sol: 2/7 What if: Evaluate ((-3)/9)/(1/(-9)). Sol: 3 What if: Evaluate (-5264)/517 + 4/66*3 + -3. Sol: -13 What if: What is (1375/(-80) - (-48)/(16 + -8)) + 11? Sol: -3/16 What if: What is (((-2912)/70)/(-52))/(3/(-6)*-12)? Sol: 2/15 What if: 27/2 + 100/200*3*-1 Sol: 12 What if: 4/2*7/(-133) Sol: -2/19 What if: ((-5)/2 + -2)/((-66)/(-44)) Sol: -3 What if: Calculate 0 - (2 - 7/(126/48)). Sol: 2/3 What if: What is the value of -2*(22344/(-3920) + 2/10) + -6 + 1? Sol: 6 What if: What is the value of 9/(-12)*(-5)/((-35)/28)? Sol: -3 What if: What is the value of ((-8)/(-1))/(-64) - (-8 + 2786/112)? Sol: -17 What if: Evaluate (-19)/1140*-70*(10/2 - -1). Sol: 7 What if: Calculate (-12)/(-8 + 140/15). Sol: -9 What if: Calculate 7 + 26/(-4) + -1. Sol: -1/2 What if: What is 438/26 + (-104)/(-676)? Sol: 17 What if: (-2)/(-1) - (-629)/(-102) - -2 Sol: -13/6 What if: What is the value of ((-7)/((-175)/10))/(60/25)? Sol: 1/6 What if: Calculate (-52)/(-2) + 253/(16698/1056). Sol: 42 What if: Evaluate 8/36*(-7)/((-35)/(-5)). Sol: -2/9 What if: What is (1 - 6/10) + 3 + -3? Sol: 2/5 What if: What is (-7)/70*-35*-2? Sol: -7 What if: Calculate ((-10640)/(-448))/(30/8*148/888). Sol: 38 What if: Calculate 88/876*132/(-484). Sol: -2/73 What if: 171/45 + (-2979078)/786710 Sol: 2/151 What if: What is (-22098)/(-261) - ((-96)/(-9))/16? Sol: 84 What if: What is (2324/784 - ((-70)/72 + 2/9)) + -5? Sol: -9/7 What if: Calculate ((6 - (-58)/(-8))/((-5)/(-5)))/(520/(-160)). Sol: 5/13 What if: (-2 - -1)*(-13 - -14) Sol: -1 What if: Calculate -3*(-9 - (-44)/5). Sol: 3/5 What if: Evaluate ((-2)/(-14))/(15/(-55)*(-29)/(-609)). Sol: -11 What if: What is 11 - -2 - (160380/(-1116))/(-11)? Sol: -2/31 What if: What is -5*((-18150)/(-37500) - 2/4)? Sol: 2/25 What if: (-1)/((-14)/4) - 132/(-28) Sol: 5 What if: (-52)/(-143)*3/6 Sol: 2/11 What if: 6 - 240/((-408)/(-34)) Sol: -14 What if: Evaluate (-472)/1534 - (-524)/1534. Sol: 2/59 What if: Evaluate ((-4)/(-12))/(2/(-6)) + 0. Sol: -1 What if: Evaluate (-2)/(-12)*(8/(-16))/(3/12). Sol: -1/3 What if: What is the value of (1 - 6/12)*-204*16/(-48)? Sol: 34 What if: What is ((-1)/2 - 25/20) + (-10)/176*-50? Sol: 12/11 What if: Calculate (-6)/8*(-3)/(-30)*-4. Sol: 3/10 What if: Calculate (-3270)/(-156) - (-22 - -43). Sol: -1/26 What if: What is (-35)/4 - 117/(65/(-5))? Sol: 1/4 What if: What is -4*5*6/30? Sol: -4 What if: ((-10 - 768/(-30)) + -9)/((-3)/(-5)) Sol: 11 What if: What is the value of (39 - (-28 - -68))*(-10)/(-8)? Sol: -5/4 What if: Evaluate (-1020)/130 + (-16)/(-2). Sol: 2/13 What if: 6/(-56) - (-12 - (-282)/24) Sol: 1/7 What if: What is the value of 420/525*(262/(-84) + 3)? Sol: -2/21 What if: What is the value of (2/(5 - (-68)/(-14)) + (-10332)/656)/(-1)? Sol: 7/4 What if: What is the value of (-8)/(-6)*(65/(-10) - -5)? Sol: -2 What if: What is 6/((-15)/((-57)/(-6) + 4)) - -5? Sol: -2/5 What if: 1/55*(82 + (-65 - 2)) Sol: 3/11 What if: What is (2 - (-42)/(-20))*(378 - 379)*-5? Sol: -1/2 What if: ((-22)/(-220))/((-3)/5) Sol: -1/6 What if: Calculate ((-96)/120)/(2 + 28/(-5)). Sol: 2/9 What if: Evaluate (-1 - (3 - 0)) + (-858)/(-209). Sol: 2/19 What if: What is (406/56 + -7)/(85/10)? Sol: 1/34 What if: What is the value of -4 - (-56)/(28/(13 + -20))? Sol: -18 What if: Calculate ((-28)/(-18))/(565180/(-145332)). Sol: -2/5 What if: Evaluate 258/(-48) + 5 - 8/(192/9). Sol: -3/4 What if: ((-14)/(-35))/((-18)/15) Sol: -1/3 What if: What is (-14 - (-1647)/108)/(3/(99 + -3))? Sol: 40 What if: Calculate 8 + 3 + 63371/(-5775). Sol: 2/75 What if: Evaluate (-101920)/(-1120) - 1*32. Sol: 59 What if: What is 30/(-20) + (-6)/((-360)/82)? Sol: -2/15 What if: Calculate 42/315*-9 + (-14)/(-10). Sol: 1/5 What if: What is the value of (6/9)/1*((-3297)/168 + 20)? Sol: 1/4 What if: ((-196)/(-245))/(16/60) - (-230)/(-150) Sol: 22/15 What if: 304/21 + (-9)/(-378)*-6 - 784/112 Sol: 22/3 What if: Evaluate (-60)/40 - (-14)/(-4). Sol: -5 What if: 11/44 + (-363)/44 Sol: -8 What if: What is ((-157)/(-78) - 4/(-26))*(39 + -45) + -14? Sol: -27 What if: What is (-4 - -139)/((42075/110)/(-153))? Sol: -54
[{"idx": "txt360/arithmetic__add_sub_multiple_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-11.jsonl"}, {"idx": "txt360/arithmetic__mixed_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-11.jsonl"}]
Unable to store particular target values in jQuery Question: <code>$(document).ready(e => { $(".test").click(e => { textvalue = displayData(e); console.log(textvalue); //prints the array }); }); function displayData(e) { let i = 0; const td = $("#tbody tr td"); let textvalues = []; for (const value of td) { if (value.dataset.name == e.target.dataset.name) { textvalues[i++] = value.textContent; } } return textvalues; }</code> <code><html> <head> <script src=" [IDX] <table> <thead> <tr> <th>Name</th> <th>Age</th> <th>Gender</th> <th>Email</th> <th>Contact</th> <th>Department</th> <th>Edit</th> </tr> </thead> <tbody id="tbody"> <tr> <td>DummyName</td> <td>20</td> <td>Female</td> <td>DummyEmail</td> <td>DummyContact</td> <td>DummyDepartment</td> <td class="test">Click</td> </tr> <tr> <td>DummyName2</td> <td>22</td> <td>Female</td> <td>DummyEmail2</td> <td>DummyContact2</td> <td>DummyDepartment2</td> <td class="test">Click</td> </tr> </tbody> </table> </body> </html></code> I'm using jQuery to update onscreen values in a form. Complete beginner at this. <code>$(document).ready(e =>{ $(".btnedit").click(e =>{ textvalues = displayData(e); let sname = $("input[name*='name_type"); let sage = $("input[name*='age_type"); let sgender = $("input[name*='gender_type"); let semail = $("input[name*='email_type"); let scontact = $("input[name*='contact_type"); let sdept = $("input[name*='dept_type"); sname.val(textvalues[0]); sage.val(textvalues[1]); sgender.val(textvalues[2]); semail.val(textvalues[3]); scontact.val(textvalues[4]); sdept.val(textvalues[5]); }); }); function displayData(e){ let i = 0; const td = $("#tbody tr td"); let textvalues = []; for(const value of td){ if(value.dataset.name == e.target.dataset.name) { //console.log(value); textvalues[i++] = value.textContent; } } return textvalues; } </code> I need to get the data stored in a table onto the inputs of the form, in order for the user to update it further. The user clicks on a record to edit it(which is displayed on the page). The record values are stored in the array textvalues. Problem is the entire table values get stored in the array instead of just the single record. In value.dataset.name, name is a column from the table which I'm using as the primary key (I know it's wrong, but just going with it for now). Edit: Original table code: <code>while($row = mysqli_fetch_assoc($result)) { ?> <tr> <td data-name = "<?php echo $row['name']; ?>"><?php echo $row['name'];?></td> <td data-name = "<?php echo $row['name']; ?>"><?php echo $row['age'];?></td> <td data-name = "<?php echo $row['name']; ?>"><?php echo $row['gender'];?></td> <td data-name = "<?php echo $row['name']; ?>"><?php echo $row['email'];?></td> <td data-name = "<?php echo $row['name']; ?>"><?php echo $row['contact'];?></td> <td data-name = "<?php echo $row['name']; ?>"><?php echo $row['department'];?></td> <td data-name = "<?php echo $row['name']; ?>"><i class="fas fa-edit btnedit"></i></td> </tr> <?php } </code> Comment: The idiomatic way to add elements to an array is `textvalues.push(value.textContent)` Comment: Can you add the HTML and create a [mcve]? See [IDX] for how to create an executable snippet. Comment: @Barmar I tried to, but I'm using a lot of php so I don't think I'll be able to (or I lack the knowledge) I'll add in some of the HTML code as well. Comment: @Barmar I'm referring to a repo, [link] [IDX] You can get the HTML from `View Source` on the web page. Comment: @Barmar I just added the minimal example, sorry for the mess Comment: You can't use `id="test"` in every row, IDs have to be unique. Change it to `class="test"` and use `$(".test").click(...)` Comment: In this context same ID is acceptable, I mean it does not break anything. What *does* break things is missing `data-name` attributes. See my reply below. Comment: There's no `data-name="XXX"` anywhere in your HTML. What are `value.dataset.name` and `e.target.dataset.name` supposed to be? Comment: @alx It does break it -- Clicking on the second row doesn't do anything. Comment: There's no need to test `dataset.name` in the loop. You can use ```$(`#tbody tr td[data-name=${e.target.dataset.name}]`)``` to match them in the selector. Comment: It would also be simpler if you put `data-name` in the `tr` rather than duplicating it in every `td`. Comment: Indeed, it does break it. Need to change event binding if you want to use same ID everywhere: `$(document).on('click', "#test" e => ...`. But I agree that's not a good practice. Answer: Your code works fine except one little thing: all your input selectors lack closing quote and bracket, e.g. this is wrong (jQuery 3.3.1 throws error): <code>let sname = $("input[name*='name_type"); </code> But this is right: <code>let sname = $("input[name*='name_type']"); </code> Otherwise, it works just fine (well, certain optimizations can be done, that's true, but still it works as is) -- if I have guessed your HTML structure correctly, see example below. (Disclaimer: this is by no means a good piece of code with best pracrices etc. This is just a reproduction of original task with minimal fix to make it work.) <code>$(document).ready(e => { $(".btnedit").click(e => { textvalues = displayData(e); let sname = $("input[name*='name_type']"); let sage = $("input[name*='age_type']"); let sgender = $("input[name*='gender_type']"); sname.val(textvalues[0]); sage.val(textvalues[1]); sgender.val(textvalues[2]); }); }); function displayData(e) { let i = 0; const td = $("#tbody tr td"); let textvalues = []; for (const value of td) { if (value.dataset.name == e.target.dataset.name) { textvalues[i++] = value.textContent; } } return textvalues; }</code> <code><script src=" [IDX] <tbody id="tbody"> <tr> <td data-name="1">a1</td> <td data-name="1">b1</td> <td data-name="1">c1</td> <td><button class="btnedit" data-name="1">edit</button></td> </tr> <tr> <td data-name="2">a2</td> <td data-name="2">b2</td> <td data-name="2">c2</td> <td><button class="btnedit" data-name="2">edit</button></td> </tr> </tbody> </table> Type: <input type="text" name="name_type" /><br /> Age: <input type="text" name="age_type" /><br /> Gender: <input type="text" name="gender_type" /></code> Possible reason of could be this: <code>data-name</code> is invalid everywhere in your table. If that's not the case, please share some more code. Minimal yet complete example would be great. Update: in your example HTML I see no <code>data-name</code> attributes at all, and clickable element also does not have it. So, your selector <code>$('#tbody th td')</code> matches all TDs, and that's why you see whole table in output. So, look at the example above and do the same with <code>data-name</code>: every <code><td></code> and the button on one row have the same value in that attribute. Comment: Those must be copying errors, or his code wouldn't run at all. Comment: The quotes are correct in his github page: [IDX] Your jsfiddle link goes to an empty fiddle. Comment: Fixed that couple of mins ago. Comment: @alx Indeed it was me not naming the `data-name` properly. But when I applied the fix nothing gets stored in the array. And if I put the `data-name` in `tr` all elements of the array get stored as earlier. Comment: If you want to use `data-name` with `tr`, you need to change selector accordingly. But this is just an optimization, probably not a good idea right now as you're struggling to make the code work in general. As to your PHP snippet, you should add `data-name` to element with `btnedit` class -- not to its parent. So, last `td` should look like this: `` Comment: I noticed it in the source code now, it wasn't correct in the video I was following<|endoftext|>Trinity and incarnation Question: If the Son does whatever the Father does (John 5:19), does that mean the Father also incarnated for the Son to incarnate? Comment: Welcome to Christianity Stack Exchange. Please take our Tour to find out how we are different to other sites and what we look for in well-researched and valid questions: [IDX] Clearly not, for there is no documentation supporting your concept and no evidence of it ever having occurred.(Quite apart from the idea contradicting many scriptures, e.g. 1 John 4:14;) Comment: @NigelJ there is no evidence of it ever having occurred for Jesus either. You don't seem to mind that there is no documentation supporting your concept of his alleged incarnation unless of course we put Creeds before Scripture and readily dismiss the contradictions created. Answer: In a word, no. According to Jesus Himself He rightly said at John 1:18, "No one has seen God at any time. The only begotten Son, who is in the bosom of the Father, He has declared Him." And at John 6:46, "Not that any man hath seen the Father, except he who is from God, he hath seen the Father." John 4:24 states, "God is spirit, and those who worship Him must worship in spirit and truth." In other words, God is a spiritual being and as noted God the Father cannot be seen. God's Son, Jesus Christ is the one and only Son of God as in there are no others. (John 3:16). Since this is true Jesus as the Son of God shares the same nature as His Father. Jesus did not have a biological father. On the other hand, Jesus also identified Himself as the "Son of Man." On His mother's side He has the same nature as His mother which is human being. So Jesus Christ has two natures, one on His Father's side and one on His mother's side. It's a universal law that all sons share the same nature as its father. Philippians 2:6-8 teaches that Jesus Christ who always existed as God took on another form which was that of a bond-servant/man. Philippians 2:8, "And being found in appearance as a man, He humbled Himself by becoming obedient to the point of death on a cross." At John 14:8 Philip said to Him/Jesus, Lord, show us the Father, and it is enough for us." Vs9, Jesus said to him, "Have I been so long with you, and yet you have not come to know Me, Philip? He who sees Me has seen the Father, how do you say, Show us the Father?" Jesus here is not saying that He is God the Father, look at vs10, "Do you not believe that I am in the Father; and the Father is in Me? (Please notice two persons are in view here.) The words I say to you I do not speak on my own initiative, but the Father abiding in Me does His works." The point of this is the fact that the Father has no separate manifestation from the Son. The Son is the only manifestation and revelation of the Father. What is known of the Father is revealed through the Son. To see the Son is to see the essence of the Father. Please read John 1:1,18; John 10:30; John 12:45; Colossians 1:15; Hebrews 1:3.) Everything Jesus did was to please His Father and to glorify the Father. This also means that we are to follow Jesus' example in our daily life. Goin back to Philippians 2, notice what the Apostle Paul states at verse 3-5. Starting at Vs3, Do nothing from selfishness or empty conceit, but with humility of mind let each of you REGARD ONE ANOTHER AS MORE IMPORTANT THAN HIMSELF." Vs4, do not merely look out for your own personal interest, BUT ALSO FOR THE INTEREST OF OTHERS." Vs5, "Have this attitude in yourselves which was also in Christ Jesus." I already went over the verses that follow. The point is to follow the example of Jesus Christ and honor Him just like were suppose to honor the Father. (John 5:23). Comment: @Lesley Sure! The main point is that (for example) horses share the same nature as other horses, birds make baby birds of like kind. And technically speaking in biology the man determines the sex of a baby depending on whether their sperm is carrying an X or Y chromosome. God is not biological and Jesus did not have a biological father but did have a human mother. Matthew 1:20. Keep up the good work. Comment: I like this answer +1 from me (to balance out the unfair negative you received for an answer that is very Biblical!) Comment: I also like this answer but don't understand what you mean when you say: It's a universal law that all sons share the same nature as its father. Jesus has two natures, one being human, which he got from his mother. I've inherited the nature of both my father and my mother - unless I misunderstand what you mean by "nature". Can you please clarify this one point with regard to the divine and human nature of Jesus? Thanks. Answer: We must consider the natures of both God the father and that of Jesus in order to understand, not only your question, but also to understand the relationship between the three who make up the Trinity. John 5:19 KJV  Then answered Jesus and said unto them, Verily, verily, I say unto you, The Son can do nothing of himself, but what he seeth the Father do: for what things soever he doeth, these also doeth the Son likewise.  Joh 5:20  For the Father loveth the Son, and sheweth him all things that himself doeth: and he will shew him greater works than these, that ye may marvel.  The one commonality between the Trinity is that they are all Spirits. John 4:23  But the hour cometh, and now is, when the true worshippers shall worship the Father in spirit and in truth: for the Father seeketh such to worship him.  24  God is a Spirit: and they that worship him must worship him in spirit and in truth. When Jesus conversed with the other two in the Trinity, They conversed in the spirit. Therefore; when Jesus maintains that he could do nothing on his own; what he was alluding to was the fact that being spiritually bonded together all things were from the tripartite God.  Matthew 12:28  But if I cast out devils by the Spirit of God, then the kingdom of God is come unto you.  Note that Jesus said he cast out devils by the spirit of God.God works in the Spiritual Realm; and we too often think of things in our earthly concepts. Hope this helps Comment: Luke 24 39 You might be misinterpreting this Scripture, or my reference to the trinity. That particular Scripture is explicitly there to show that God the father has reinstated the life of the man Jesus; which only applies to his physical life; not unlike his creation of Adam where God breathed the breath of life into Adams body formed from the dust of the Earth. As far as my referring to the Trinity inclusion all three are Spirits with no beginning or end. Comment: Beckhum Luke 24.39 is not referring to Jesus still being a spirit. His words specifically say the opposite to such a view! People simply do not appreciate that Jesus took upon humanity permanently. His God man status is not just for the approx 33/34 years he was on this earth. Remember the angels said to the disciples "this same Jesus will come in exactly the same manner you saw him ascend into heaven" Comment: @Adam Not meaning to be snippy but the name BECKUM and not Beckhum. However you may like to call me Cecil which is fine. Yes it is in reference to his physical body which we know died and if it did not there would be no Salvation. The fact that that physical body which did die, has been revived and lives again; bears witness to the fact that our resurrection bodies can also live again after dyeing. That bears witness to our Salvation in Christ. Jesus in his resurrection body was still both Man and God and God is a Spirit. Comment: @ Cecil I am a trinitarian. GOD consists of 3 entities, the Father, Son, and Holy Spirit. The Son is now a man (translated as were Enoch and Elijah). Whether the Father is Spirit or not...I would need to see Biblical evidence for that because if there is already a Holy Spirit, why does the Father also need to be one? Conversely, if the Father is not spirit, what is He? Comment: @Adam Apparently you have a concept of God that is not the one I have. Therefore to continue this back and forth; can serve no useful purpose. So let us no longer continue it. With Christian love thanks Cecil. Comment: @ Cecil I am struggling to understand what your view of God is? It appears that you believe the incarnation is not permanent, rather Jesus now flicks between the two whenever it suits Him. That is a gross misinterpretation of scripture in my view. Jesus visit to the disciples in upper room (and words to Thomas put your finger in my side) was after he had already been to heaven. Remember what he said to Mary outside the tomb earlier. Jesus also refers to Himself as the Son of Man at second coming.
[{"idx": "Unable_to_store_particular_target_values_in_jQuery", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-18955.jsonl"}, {"idx": "Trinity_and_incarnation", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-18955.jsonl"}]
Q: Angular.js & Adsense I'm trying to put ads on my angular.js app, and I've done some reading and discovered it isn't possible to just copy and paste the normal adsense code. I've heard you are supposed to "wrap it in a directive with a transclusion," and the only example I can find of this is another Stackoverflow post: AngularJs and AddThis social plugin Can someone help give guidance about how to go about doing this with Google Adsense? A: I am not sure whether doing the following thing is valid as per the adsense T&C. delete all the google related variables before you change the url Object.keys(window).filter(function(k) { return /google/.test(k) }).forEach( function(key) { delete(window[key]); } ); A: you need to create a directive yourApp.directive('ads', function() { return { restrict: 'A', templateUrl: 'partiels/adsTpl', controller: function(){ []).push({}); } }; }); create a template with your ads code in my case "partiels/adsTpl.html" <ins class="adsbygoogle" style="display:inline-block;width:300px;height:250px" data-ad-client="ca-pub-00000000" data-ad-slot="000000"></ins> add the directive to your page <div data-ads></div> place the adSense js call in the head section of your main page before angularjs <head> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> .... et voila , this is work perfectly for me A: You should do a wrapper directive to the adSense script like this... <div data-my-ad-sense> <!-- Google AdSense --> <script async src=" [IDX] <ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-0000000000" data-ad-slot="0000000000"></ins> <script> []).push({}); </script> </div> And add this directive to your directives... directive('myAdSense', function() { return { restrict: 'A', transclude: true, replace: true, template: '<div ng-transclude></div>', link: function ($scope, element, attrs) {} } }) This is the adSense async code. A: In the AngularJS controller, add an init() function, add a line []).push({}); Then call this init() function in your view html file. See also at [IDX]<|endoftext|>Q: Update a dictionary with another dictionary, but only non-None values From the python documentation I see that dict has an update(...) method, but it appears it does not take exceptions where I may not want to update the old dictionary with a new value. For instance, when the value is None. This is what I currently do: for key in new_dict.keys(): new_value = new_dict.get(key) if new_value: old_dict[key] = new_value Is there a better way to update the old dictionary using the new dictionary. old = {1: 'one', 2: 'two'} new = {1: 'newone', 2: None, 3: 'new'} old.update( (k,v) for k,v in new.items() if v is not None) # {1: 'newone', 2: 'two', 3: 'new'} A: Update: I think I was trying to answer the wrong question here (see my comment below), since this clearly does not answer the question being asked. In case there is something useful, I'll leave this here anyway (unless someone makes it clear that it would be better to just delete it). Building on Jon's answer but using set intersection as suggested here: In python 3: old.update((k, new[k]) for k in old.keys() & new.keys()) In python 2.7: old.update((k, new[k]) for k in old.viewkeys() & new.viewkeys()) In python 2.7 or 3 using the future package: old.update((k, new[k]) for k in viewkeys(old) & viewkeys(new)) Or in python 2 or 3 by without the future package by creating new sets: old.update((k, new[k]) for k in set(old.keys()) & set(new.keys())) A: For python 3.x to iterate throughout dictionary key values use for k,v in new.items() IN: old = {1: 'one', 2: 'two'} new = {1: 'new_one', 2: None, 3: 'new_three'} old.update((k,v) for k,v in new.items() if v is not None) Out: old = {1: 'new_one', 2: 'two'} A: If you get here from a pydantic object that you created into dict, this wont work. Instead use pydantic function dict(exclude_none). Python 3.7+ For example, existing_job = db.query(MedicalRecord).filter(MedicalRecord.id == id) else: existing_job = db.query(MedicalRecord).filter(MedicalRecord.id == id, MedicalRecord.owner_id==user.id) if not existing_job.first(): return 0 job.directory_hash = None #doesnt work: existing_job.update((k,v) for k,v in job.dict().items() if v is not None) job = job.dict(exclude_none=True) existing_job.update(job) # works<|endoftext|>Q: Can coxph be used for categorical data? I'm doing some survival analysis and I got the idea to change a binary variable into three-category variable by sub-dividing one category of the binary variable into two new categories. Here's a script to produce a comparable dataset: df = data.frame(Sample = c(1:20), OS_Months = sample(c(1:100),size = 20, replace = TRUE), OS_Event = sample(c(1,0), size = 20, replace = TRUE), Original_Var = sample(c("Yes","No"), size = 20, replace = TRUE), New_Var = sample(c(2,3), size = 20, replace = TRUE)) df[df$Original_Var == "No",]$New_Var = 1 Normally, when I do survival analysis I measure significance using a log-rank p-value for binary data and a coxph p-value for continuous data but I don't have a firm understanding of the mathematical basis for either of these test. At this time, its not clear to me whether or not the new categories I've defined have an ordinal relationship with each other. If they do, I expect I'll have to think about how to scale them but my current hope is that treating them as categorical variables will eliminate this problem. Specific Questions: * *If I decide that my variables really are ordinal, what impact will scaling have on my variables if I use the coxph model? *If I decide variables are not ordinal and coxph is inappropriate, what is a more appropriate test to run? For what its worth, the original binary variable was presence/absence of mutations in a particular gene and the new variable categorizes the mutations as belonging to one of two types. If I were to scale the numeric categories, I would probably change 2 and 3 to numbers closer to each other than to non-mutants, something along the lines of: df[df$New_Var == 2,]$New_Var = 10 df[df$New_Var == 3,]$New_Var = 11 A: I'm not sure I understand your description but if I do, then your transformation did not create an ordinal variable. In any event, it is the predictor. Dealing with an ordinal predictor variable is not as tricky as dealing with an ordinal response. However, in your case, you probably just want to compare among them. Cox models can deal with discrete or continuous predictors so it is not necessary to swap to log-rank unless you just prefer to do so.<|endoftext|>Q: Similarity measure between two text documents Let the first document involve the words $\{x_1,x_2,\ldots,x_n\}$ and the second one be composed of $\{y_1,y_2,\ldots,y_m\}$ where $n$ is not necessarily equal to $m$. I have a similarity measure that works for elements of the sets; $s(x_i,y_j)$ for all $i$ and $j$. This similarity may not be symmetric, that is, $s(x_i,y_j)\neq s(y_j,x_i)$. But I'm not familiar about the similarity of two sets of instances. I thought that the average of the best similarities is reasonable: $$s\left(\{x_1,x_2,\ldots,x_n\},\{y_1,y_2,\ldots,y_m\}\right) = \frac{1}{n}\sum_{i=1}^n \max_{j=1}^m s(x_i,y_j)$$ What are the main methods used to compute $s\left(\{x_1,x_2,\ldots,x_n\},\{y_1,y_2,\ldots,y_m\}\right)$ in such a case? Particularly the similairty of two text documents? A: There are various methods to define document similarity, but let me introduce the most easiest approach to start with, based on semantic vector space: * *First build your term-document matrix *Then "Normalize" the entries in the matrix with tf-idf *From there, you can use your document-vectors columns of the matrix to calculate the similarity with the cosine similarity for instance I think it's the most basic approach that gives decent results. If you have a lot of documents and terms, your matrix can be very big but also very sparse. That's where dimension reduction technics are usually introduced. You can for instance use SVD to define underlying correlated dimensions in your space, and use only the few strongly correlated ones as a new basis for your document vectors. It works pretty well but is demanding in computing resources for very large spaces. Alternatively, you can use random projection to reduce your space, but it's bit longer to explain. You must know that there are also libraries that can do this for you. If you want to use random projection for instance, the semantic vector package was built around this idea : [IDX] , but if I remember well they also have SVD encoded (edit: I checked and they have the Latent Semantic Analysis module implemented -LSA is based on SVD-). You can look for all the terms used in their corresponding wikipedia entries, I wasn't allowed to put more than 2 links for spam reasons apparently !!!<|endoftext|>Q: TimePicker Dialog when pressing EditText This question has been asked before, but the answers from back then, doesn't seem to work in Android Studio anymore, or else i'm missing something. I want a timePicker dialog to show up when you press the edit text area, to set the time in the editText. However, for some reason, the normal keyboard simply pops up when pressed. I'm not getting any errors, though it still doesn't seem to work. here is the code: final EditText Edit_Time = (EditText) findViewById(R.id.time_view_edit); Edit_Time.setOnClickListener(new View.OnClickListener() { @Override TimePickerDialog mTimePicker; mTimePicker = new TimePickerDialog(TimeActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override Edit_Time.setText( selectedHour + ":" + selectedMinute); } }, hour, minute, true); mTimePicker.setTitle("Select Time"); } }); the xml part of editText: <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/time_view_edit" android:text="20:00" android:layout_weight="1"/> If anyone can help, then it's much appreciated, Thanks! A: Add these properties to your EditText tag in xml to disable keyboard popping up android:editable="false" and android:focusable="false" UPDATE: android:editable="false" is deprecated now. use android:inputType="none" instead or in the code: editText.setEnabled(false); A: This worked for me on androidx projects. Create showTimePicker method. private void showTimePicker(){ TimePickerDialog timePickerDialog = new TimePickerDialog(EditPharmacyActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override } }, hour, minute, false); } And in onCreate method add followings to init the views. etOpenHours.setClickable(true); etOpenHours.setLongClickable(false); etOpenHours.setInputType(InputType.TYPE_NULL); etOpenHours.setOnClickListener(new View.OnClickListener() { @Override showTimePicker(); } });
[{"idx": "https://stackoverflow.com/questions/17416992", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6937.jsonl"}, {"idx": "https://stackoverflow.com/questions/15277307", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6937.jsonl"}, {"idx": "https://stats.stackexchange.com/questions/209244", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6937.jsonl"}, {"idx": "https://stats.stackexchange.com/questions/46191", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6937.jsonl"}, {"idx": "https://stackoverflow.com/questions/39634387", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-6937.jsonl"}]
Can I take a metal knife and fork through airport security? Question: On my last flight I was served a meal with a metal knife and fork, which was a pleasant change compared to plastic utensils. This gave me the idea of packing my own utensils for the next flight as a small way of improving the economy experience. However, would I be allowed to take a standard knife and fork through airport security? By 'standard' I'm referring to something like this: To make the question less broad I'm restricting it to North American and European airports. Comment: I tried to take the silverware I received on the airplane (Lufthansa) and got my butter knife confiscated in Minneapolis because it was serrated even though I got it from an airplane. I took this set of silverware from Kalispell mt to New York to Aruba and nothing happened. I was trying to be environmentally conscious. Wtf type of damage can someone do with a serrated reusable butter knife? Answer: From the US side, the TSA run a website, giving generic advice on whether items can taken as carry-on, in checked luggage, or not at all. Note the important disclaimer that the final decision rests with the TSA officer on whether an item is allowed through the checkpoint, but searching for "utensils" gives the response: Carry On Bags: Yes Checked Bags: Yes Knives, except for plastic or round-bladed butter knives, are not allowed in carry-on bags. So, you're likely to be ok with the fork and the spoons, but the table knife is liable to be confiscated. Comment: I would be mightily surprised if you consistently got through with those. Don't take your grandmother's silverware if you're not ready to abandon it at the security checkpoint... Comment: "round-bladed butter knives" seem to be the kind I want to take on board Comment: @JonathanReez It'll depend on whether they mean the general meaning of any non-serrated table knife or the strict "this knife is only for butter" meaning! Comment: I have had forks confiscated in Europe on two occasions. Both times I left one in my bag accidentally. It triggers an in depth bag search that can take a while. So I wouldn't recommend it. Comment: A true butter knife usually has a point on the end. Not very sharp, but a point nonetheless. [IDX] What the TSA is referring to is probably a non-serrated dinner knife. [IDX]<|endoftext|>Is there a limit to how many hours a person can fly per month? Question: I'm trying to figure out whether there's a maximum per person. Of course factoring in eight hours of sleep and say maintenance time there is definitely a limit, but I don't see where it is. Comment: Welcome to aviation.SE! Are you asking what's practically possible, or what's legally allowed? If you're asking about the legal part, please tell us which country you're asking about. And we do have some relevant questions already: [here]( [IDX] [here]( [IDX] Are you asking about how much a pilot is allowed to fly or a person can fly as a passenger? Comment: Each country will have its own regulations on this, and each airline may have its own policies, so it would help if you could narrow this down at least to a country. Comment: @ymb1 How do you know the question is about the US? Or are you just making it about the US to benefit from the answer, even if we don't know the OP's intention? Comment: @Pondlife - Didn't notice Farhan's comment about 'person'. Rolled it back and VTCed. Comment: @ymb1 I think using a good answer is fine, if the OP doesn't follow up. I don't know if there's any SE etiquette that says we shouldn't. Comment: Well, there certainly is because there are only so many hours per month. Comment: Depending on the month, between 672 and 744 hours. Answer: With respect to air carrier operations in the US, 14 CFR 121.481 requires: (e) No pilot may fly as a member of a crew more than 100 hours during any one calendar month. (f) No pilot may fly as a member of a crew more than 1,000 hours during any 12-calendar-month period. 14 CFR 135.265 commuter: (1) 1,200 hours in any calendar year. (2) 120 hours in any calendar month. Under Part 91, fractional ops, 14 CFR 91.1059 states: (a) No program manager may assign any flight crewmember, and no flight crewmember may accept an assignment, for flight time as a member of a one- or two-pilot crew if that crewmember's total flight time in all commercial flying will exceed - (1) 500 hours in any calendar quarter; (2) 800 hours in any two consecutive calendar quarters; (3) 1,400 hours in any calendar year. Otherwise, there is no direct limit under Part 91. However, if you are fatigued enough to cause a problem, FAA can still charge you under general "unsafe operation" rules.<|endoftext|>toJSON on Backbone.Collection#where? Question: I'm not sure why, but I can't get this to work. <code>var friends = new Backbone.Collection([ {name: "Athos", job: "Musketeer"}, {name: "Porthos", job: "Musketeer"}, {name: "Aramis", job: "Musketeer"}, {name: "d'Artagnan", job: "Guard"}, ]); friends.where({job: "Musketeer"}).toJSON() </code> I'm getting <code>Uncaught TypeError: Object [object Object] has no method 'toJSON'</code>. What I'm I doing wrong and how do I convert my filtered collection into JSON? Answer: What the <code>Underscore.where</code> method returns is an <code>Array</code> not a <code>Backbone.Collection</code> so it has not the <code>toJSON</code> method defined. So you can make two things: Iterate over elements and map the result: <code>var result = friends.where({job: "Musketeer"}); _.map( result, function( model ){ return model.toJSON(); } ); </code> jsFiddle code Implement a Collection searcher method that returns a proper Backbone.Collection: <code>var Friends = Backbone.Collection.extend({ search: function( opts ){ var result = this.where( opts ); var resultCollection = new Friends( result ); return resultCollection; } }); var myFriends = new Friends([ {name: "Athos", job: "Musketeer"}, {name: "Porthos", job: "Musketeer"}, {name: "Aramis", job: "Musketeer"}, {name: "d'Artagnan", job: "Guard"}, ]); myFriends.search({ job: "Musketeer" }).toJSON();​ </code> jsFiddle code Answer: <code>toJSON</code> is a confusing method name : [IDX] <code>collection.toJSON()</code> Return an array containing the attributes hash of each model in the collection. This can be used to serialize and >persist the collection as a whole. The name of this method is a bit confusing, because it conforms to JavaScript's >JSON API. if you want to convert your collection to a JSON string, use <code>JSON.stringify</code> <code>var friends = new Backbone.Collection([ {name: "Athos", job: "Musketeer"}, {name: "Porthos", job: "Musketeer"}, {name: "Aramis", job: "Musketeer"}, {name: "d'Artagnan", job: "Guard"}, ]); JSON.stringify( friends.where({job: "Musketeer"}) ); </code> Note that <code>where</code> returns an array, not a Backbone collection, you would have to build a new collection to use the <code>toJSON</code> method.<|endoftext|>$A \subset \mathbb{R}^n$ is an affine subspace $\Leftrightarrow \sum \mu _ia_i \in A$ whenever $a_i \in A$, $\sum \mu_i =1$ Question: Lemma: $A \subset \mathbb{R}^n$ is an affine subspace $\Leftrightarrow$ If $\sum \mu_i =1$, and if $a_i \in A$ for any $i =1,...,k$, then we have $\sum \mu _ia_i \in A$. Definition: A subspace $A$ in $\mathbb{R}^n$ is an affine subspace if $\lambda a + \mu b \in A$ for any $\lambda, \mu \in \mathbb{R}$ s.t $\lambda + \mu =1$ and for any $a,b \in A$. I want to prove this lemma using induction (for the direction $\Rightarrow $), but I'm stuck at the last step. $k=2$ is true by definition of Affine Space. Assume it is true for $k=n$. Consider when $k=n+1$. Let $a_1, ..., a_{n+1} \in A$ be arbitrary elements, and let $\mu_1, ..., \mu_{n+1} \in \mathbb{R}$ are arbitrary numbers that satisfies $\mu_1 +...+\mu_{n+1}=1$. Observe that if $\mu_n+\mu_{n+1} \neq 0$, $$ \mu_1 a_1+ ...+\mu_{n-1} a_{n-1} + \mu_n a_n + \mu_{n+1} a_{n+1} \\ = \mu_1 a_1+ ...+\mu_{n-1} a_{n-1} + \frac{\mu_n a_n + \mu_{n+1} a_{n+1}}{\mu_n+\mu_{n+1}}(\mu_n + \mu_{n+1})$$ Notice that $$\frac{\mu_n a_n + \mu_{n+1} a_{n+1}}{\mu_n+\mu_{n+1}} \in A$$ by the definition. Thus, by the hypothesis ($k=n$), $\sum \mu_i a_i \in A$. However, I don't know what to do when $\mu_n + \mu_{n+1}=0$. Can I get any hint? Answer: Suppose that $n$ is even and that $\mu_i +\mu_j=0$ for all $i$ and $j$. Then $$ 1 = \sum_{i=1}^n\mu_i = \sum_{i=1}^{n/2}(\mu_i +\mu_{i+1})=0\,, $$ which is a contradiction, and so there must be at least one pair of $\mu$'s that don't sum to zero. Now suppose that $n$ is odd and that $\mu_i +\mu_j=0$ for all $i$ and $j$. Then, $$ 1 = \sum_{i=1}^n\mu_i = \sum_{i=1}^{(n-1)/2}(\mu_i +\mu_{i+1}) + \mu_n =\mu_n\, $$ and so $\mu_n=1$. In this calculation, the choice of pulling out $\mu_n$ was arbitrary, and so the same calculation implies that $\mu_i=1$ for all $i$ (provided that they're all non-zero). This is a contradiction, and hence there must be at least one pair of $\mu$'s that don't sum to zero. Thus, you can always find two $\mu$'s that don't sum to zero, and without loss of generality, re-order the sum so that they are the last two (i.e., $\mu_n$ and $\mu_{n+1}$), and your proof then works. (I suspect that there is a more straight-forward way of doing this, directly and without a proof-by-contradiction.)<|endoftext|>Specal Handling of Base.pm? Question: I create a module called Base.pm in the same directory as the Perl program that wants to use it but the module doesn't seem to be loaded. Change the name of the module to anything other than Base and things work just fine. What is special about Base.pm and how does one override this behavior? Thanks for any insight. <code>package Base; use strict; use Exporter; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = 1.00; @ISA = qw(Exporter); @EXPORT = qw(func); sub func { return "foo"; } 1; </code> with <code>use Base; print func(); </code> yields <code>Undefined subroutine &main::func called at test0.pl line 2. </code> whereas <code>package Case; use strict; use Exporter; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = 1.00; @ISA = qw(Exporter); @EXPORT = qw(func); sub func { return "foo"; } 1; </code> with <code>use Case; print func(); </code> yields <code>foo. </code> Comment: While not a duplicate, [this question]( [IDX] is relevant to your situation. Answer: <code>base.pm</code> is a core system "pragma" module (these days, it's deprecated for <code>parent.pm</code>) <code>use base 'MyBaseClass'; # Same as: our @ISA = ( 'MyBaseClass' ); </code> It's probably a Windows case thing. Perl looks for "<code>Base.pm</code>", but windows returns "<code>base.pm</code>". When you named it "anything other than Base", you probably didn't rename it to another Perl module. One way you can check this is to run the following: <code>use</code> <code>Data::Dumper</code> print a dump of <code>%INC</code> (a map of all loaded modules and where they were loaded from) <code>use Data::Dumper; ... use Base; ... print Dumper( \%INC ); </code> Look for <code>'base.pm'</code> or <code>'Base.pm'</code> to see what Perl loaded. Answer: Inspect <code>%INC</code> to see what's actually being loaded: <code>use Base; print $INC{'Base.pm'}; </code> Outputs: <code>/Users/miller/perl5/perlbrew/perls/perl-5.20.0/lib/5.20.1/Base.pm </code> I'm on a non-case sensitive OSX partition, so this file corresponds to the <code>base</code> pragma. To avoid this type of issue, give your projects a private namespace. This way there's less risk of conflicting with a current or future Perl Core or CPAN module: <code>package MyProject::Base; </code>
[{"idx": "Can_I_take_a_metal_knife_and_fork_through_airport_security?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-25742.jsonl"}, {"idx": "Is_there_a_limit_to_how_many_hours_a_person_can_fly_per_month?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-25742.jsonl"}, {"idx": "toJSON_on_Backbone.Collection#where?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-25742.jsonl"}, {"idx": "$A_\\subset_\\mathbb{R}^n$_is_an_affine_subspace_$\\Leftrightarrow_\\sum_\\mu__ia_i_\\in_A$_whenever_$a_i_\\in_A$,_$\\sum_\\mu_i_=1$", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-25742.jsonl"}, {"idx": "Specal_Handling_of_Base.pm?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-25742.jsonl"}]
# 静的コード生成の利点 筆者が今まで試したDIコンテナは実行時にリフレクションを利用してインスタンスを生成します。 これに筆者は不満点がいくつかありました。 Deptorygenは、そういった不満点を解消できないか挑戦するプロジェクトです。 Deptorygenを使用する利点のほとんどは、 インスタンスを生成するためのコードを静的に生成することに基づいています。 静的にコード生成をすることでどのようなメリットが得られるか紹介します。 ## 不満点の解消: 不透明さ 動的に依存関係を判断してインスタンスを生成する場合、 その手順は実行時において動的にコードを生成することによって決まります。 こうなると、プログラマーはインスタンスが実際にどのような手順で生成されているのかを知ることができません。 Deptorygenでは、インスタンスを生成するコードが静的にコード生成されるため、そのコードを見ればどのような手順で生成されているのかを理解することができます。 [基本的な使い方](../Guides/BasicStyle.md) ## 不満点の解消: コンパイルエラーが出ない 動的に依存関係を判断してインスタンスを生成する場合、 依存関係を解決する手段が実行時に決まるということなので、 実際には依存関係を解決できないような設定でDIコンテナが使用されている場合に コンパイルエラーを出すことができません。 Deptorygenを用いてファクトリークラスを生成すると、 依存関係の解決が不可能であった型に対しては無効なコードが生成され、コンパイルエラーとなります。 ただし、依存先のインスタンスを生成することができないことにより依存関係の解決が不可能であった場合は ファクトリークラス自体は有効なコードが生成されます。 その代わり、足りない依存先がコンストラクタの引数でもって利用者に対して要求されます。 この引数にインスタンスを渡したくない場合はファクトリーも生成できないことになるため、 プログラマーはファクトリークラスに対して十分に型の情報を伝える必要があることに気づくことができます。 [コンストラクタで意外な引数を要求されたら](../Guides/Constructor.md) ## 不満点の解消: 追加の引数を与えて生成したい 動的に依存関係を判断してインスタンスを生成するDIコンテナでは、 実際にインスタンスを生成するタイミングで初めて得られるような情報を追加で引数に渡して、 適切に設定されたインスタンスを生成できるものもあります。 しかし、こうして与える追加の引数についてコンパイル時に型チェックをしてもらうことは困難です。 DeptorygenでもそうしたDIコンテナと同様に、 インスタンスを生成するときに追加の引数を渡すことができます。 ただし、依存関係を解決するコードは静的に生成されているため、 追加で渡す引数も必ず型チェックの対象となります。 [解決メソッドに直接オブジェクトを渡す](../Samples/Parameterize.md) ## 不満点の解消: インスタンスの寿命管理 DIコンテナにおいてインスタンスの寿命を直感的に管理するのは難しい課題です。 筆者の利用したものだと、`Singleton`, `Scope`, `Transient` といった3つ程度の区分に分かれ、 あとはDIコンテナ独自のクラス構造を駆使してスコープや寿命を管理します。 例えばGenericHostのDIコンテナであれば、`ServiceProvider`のインスタンスが1つのスコープに対応しています。 Deptorygenでは、インスタンスの寿命はそのインスタンスをキャッシュしているファクトリーが基準となります。 ファクトリークラスのインスタンスはstaticなものではないため、 ファクトリーによって生成されるようなインスタンスとまったく同様に取りまわすことができます。 Deptorygenでのインスタンスの寿命は2種類です。`Cached`……つまりファクトリーそのものと同等か、`Transient`……生成するたびに違うものか、です。 partialクラスの性質を生かしてファクトリー自体をシングルトンにするのも自由です。 その場合、寿命が`Cached`であるインスタンスはGenericHostでいう`Singleton`と同じように扱えるでしょう。 他にも、ファクトリークラスを生成する種となる複数のインターフェース定義に対して継承や包含の関係を持たせれば、 複数のファクトリー間で寿命を共有したり、特定のインスタンスを生成する権利を持つクラスを限定するなどの使い方ができたり、 DIコンテナを使わない場合と同じくらいに寿命とスコープを柔軟に管理することができます。 [ファクトリーを別のアセンブリに提供する](../Guides/ExportType.md) [依存関係の解決に別のファクトリーも利用する(キャプチャ)](../Samples/Capture.md)<|endoftext|>--- title: レポート用マクロの |Microsoft Docs ms.custom: '' ms.date: 11/15/2016 ms.prod: visual-studio-dev14 ms.reviewer: '' ms.suite: '' ms.technology: - vs-ide-debug ms.tgt_pltfrm: '' ms.topic: article f1_keywords: - vs.debug.macros dev_langs: - FSharp - VB - CSharp - C++ - C++ helpviewer_keywords: - macros, debugging with - _RPTFn macro - CRT, reporting macros - _RPTn macro caps.latest.revision: 18 author: MikeJo5000 ms.author: mikejo manager: ghogen ms.openlocfilehash: dc2a5226b3d6f512d2c2f89d9fef2a80eef34340 ms.translationtype: MT ms.contentlocale: ja-JP ms.lasthandoff: 11/16/2018 ms.locfileid: "51758454" --- # <a name="macros-for-reporting"></a>レポート用マクロの使用 使用することができます、 **_RPTn**、および **_RPTFn** crtdbg マクロ。代わりに、H`printf`デバッグ ステートメント。 これらのマクロは、のリリースで自動的に消滅ビルド **_DEBUG**が定義されていないで囲む必要はありませんので **#ifdef**s。 |マクロ|説明| |**_RPT0**、 **_RPT1**、 **_RPT2**、 **_RPT3**、 **_RPT4**|メッセージ文字列と、0 から 4 個の引数を出力します。 _Rpt1 **_RPT4**、メッセージ文字列は、引数の printf スタイルの書式指定文字列として機能します。| |**_RPTF0**、 **_RPTF1**、 **、_RPTF2**、 **_RPTF4**|同じ **_RPTn**がこれらのマクロは、マクロが配置されているファイル名と行番号も出力します。| 次に例を示します。 ``` #ifdef _DEBUG printf( "OVERFLOW! In NameOfThisFunc( ), someVar=%d, otherVar=%d.\n", #endif ``` このコードの値を出力する`someVar`と`otherVar`に**stdout**します。 次のように `_RPTF2` を呼び出すと、これらの値と一緒にファイル名と行番号も出力できます。 ``` if (someVar > MAX_SOMEVAR) _RPTF2(_CRT_WARN, "In NameOfThisFunc( ), someVar= %d, otherVar= %d\n", someVar, otherVar ); ``` 特定のアプリケーションでは、C ランタイム ライブラリのマクロで提供されているデバッグ レポートでは不十分な場合があります。その場合は、独自の要件を満たす専用のマクロを設計できます。 ヘッダー ファイルの 1 つなどを含めることができます、マクロを定義するには、次と呼ばれるようなコード**ALERT_IF2**: ``` do { \ if ((expr) && \ _CrtDbgBreak( ); \ } while (0) #endif ``` 1 回の呼び出しに**ALERT_IF2**のすべての機能を実行する可能性があります、 **printf**このトピックの冒頭にあるコード。 ``` ALERT_IF2(someVar > MAX_SOMEVAR, "OVERFLOW! In NameOfThisFunc( ), someVar=%d, otherVar=%d.\n", someVar, otherVar ); ``` カスタム マクロは、目的に応じて出力情報の量を増減したり、出力先を変更したりなどの変更を簡単に実現できるため、デバッグ要件が複雑さを増してくる段階で使用すると便利です。 ## <a name="see-also"></a>関連項目 [CRT のデバッグ技術](../debugger/crt-debugging-techniques.md)<|endoftext|>--- title: '手順 5: フラット ファイル ソースの追加と構成 | Microsoft Docs' ms.custom: '' ms.date: 03/01/2017 ms.prod: sql ms.reviewer: '' ms.suite: sql ms.tgt_pltfrm: '' ms.topic: tutorial applies_to: - SQL Server 2016 ms.assetid: 5c95ce51-e0fe-4fc5-95eb-2945929f2b13 author: douglaslMS ms.author: douglasl manager: craigg ms.openlocfilehash: 4d1b0767564d0e664d14af285617f8ae0947382d ms.translationtype: HT ms.contentlocale: ja-JP ms.lasthandoff: 06/12/2018 ms.locfileid: "35329316" --- # <a name="lesson-1-5---adding-and-configuring-the-flat-file-source"></a>レッスン 1-5 - フラット ファイル ソースの追加と構成 ここでは、フラット ファイル ソースをパッケージに追加し、構成します。 フラット ファイル ソースとは、フラット ファイル接続マネージャーにより定義されるメタデータを使用するデータ フロー コンポーネントです。フラット ファイル接続マネージャーは、変換処理によってフラット ファイルから取得されるデータの形式や構造を指定します。 フラット ファイル接続マネージャーに定義されているファイル形式を使用し、1 つのフラット ファイルからデータを取得するよう、フラット ファイル ソースを定義できます。 このチュートリアルでは、以前に作成した **Sample Flat File Source Data** 接続マネージャーを使用するように、フラット ファイル ソースを構成します。 ### <a name="to-add-a-flat-file-source-component"></a>フラット ファイル ソース コンポーネントを追加するには 1. **[Extract Sample Currency Data]** データ フローをダブルクリックするか、 **[データ フロー]** タブをクリックし、 **[データ フロー]** デザイナーを開きます。 2. **[SSIS ツールボックス]** で **[その他の変換元]** を展開し、 **[フラット ファイル ソース]** を **[データ フロー]** タブのデザイン画面にドラッグします。 3. **[データ フロー]** デザイン画面で、新しく追加した **[フラット ファイル ソース]** を右クリックし、 **[名前の変更]** をクリックします。名前を「 **Extract Sample Currency Data**」に変更します。 4. このフラット ファイル ソースをダブルクリックして、[フラット ファイル ソース エディター] ダイアログ ボックスを開きます。 5. **[フラット ファイル接続マネージャー]** ボックスで " **Sample Flat File Source Data**" を選択します。 6. **[列]** をクリックし、列名が正しいことを確認します。 7. **[OK]** をクリックします。 8. [フラット ファイル ソース] を右クリックし、 **[プロパティ]** をクリックします。 9. [プロパティ] ウィンドウで、 **LocaleID** プロパティが **[英語 (米国)]** に設定されていることを確認します。 ## <a name="next-task-in-lesson"></a>このレッスンの次の作業 [手順 6 : 参照変換の追加と構成](../integration-services/lesson-1-6-adding-and-configuring-the-lookup-transformations.md) ## <a name="see-also"></a>参照 [[フラット ファイル ソース]](../integration-services/data-flow/flat-file-source.md) [[フラット ファイル接続マネージャー エディター] &#40;[全般] ページ&#41;](../integration-services/connection-manager/flat-file-connection-manager-editor-general-page.md)<|endoftext|>2021-W02 をふりかえる。 # [2021-W02 の目標][2021-01-10] とその記事 目標。 - ☑ bouzuya/rust-social-bookmarking 0.2.0 をつくる - ☑ 『エンジニアのための理論でわかるデザイン入門』を読む 記事。 - [2021-01-16 スーパーマリオサンシャイン エアポートを巡回している][2021-01-16] - [2021-01-15 スーパーマリオサンシャインの急流下りをクリアした][2021-01-15] - [2021-01-14 体調が悪い][2021-01-14] - [2021-01-13 曲面ディスプレイが欲しくなっている][2021-01-13] - [2021-01-12 いろいろ読んだ][2021-01-12] - [2021-01-11 スーパーマリオサンシャインで残機を増やしている][2021-01-11] - [2021-01-10 2021-W01 ふりかえり][2021-01-10] # つくったもの - [bouzuya/rust-social-bookmarking][] v0.2.0 # よんだもの - 『涼宮ハルヒの陰謀』 ([2021-01-12][]) - 『エンジニアのための理論でわかるデザイン入門』 ([2021-01-12][]) - 『涼宮ハルヒの憤慨』 ([2021-01-14][]) - 『涼宮ハルヒの分裂』 ([2021-01-17][]) - 『涼宮ハルヒの驚愕 (前) 』 ([2021-01-17][]) - 『涼宮ハルヒの驚愕 (後) 』 ([2021-01-17][]) # みたもの - 『進撃の巨人 シーズン 3 』 ([2021-01-11][]) - 『キャビン・イン・ザ・ウッズ』 ([2021-01-17][]) - 『 2012 』 ([2021-01-17][]) # その他 勉強会。なし。 おでかけ。雨の中の散歩。 ゲーム。スーパーマリオサンシャイン シャイン 120 個を集めてクリア。リングフィットアドベンチャー ワールド 29 レベル 239 。 買い物。なし。 体調。木曜日に体調不良で倒れていた。 育児。「あれー?」と『となりのトトロ』で 2 階への階段を探すシーンのまねをしながらものを探す。たまねぎ・かぼちゃ・にんじんはわかる。じゃがいもはわからない。 --- スーパーマリオ 3D コレクションの『スーパーマリオサンシャイン』をクリアした。シャイン 120 枚の収集を終えた。スーパーマリオ 64 とあわせて 65 時間以上プレイと表示されていた。 スーパーマリオ 64 ([2020-11-14][]) に比べて難しかった。 [2020-12-12][] にもメモしているが改めて書く。 青コインの隠し方は本気だと感じる。すべての人の話を聞いた上でヒントをうまく解釈できないと取れないものがある。結局ぼくは攻略サイトを見た。これも含めて全体的にナビゲーションの悪さを感じる。うまく誘導してくれないイメージがある。 ミスしたときの戻し作業が重い。例えば急流下りに行くためのヨッシーでの船の乗り継ぎやリコハーバーのヨッシーでの魚の足場の乗り継ぎなどだ。ちょっと踏み外して落下すると最初からやり直しさせられることが多い。練習させているつもりかもしれないがつらい。その結果のひとつとしてエアポートの繰り返しでの残機稼ぎが常態化した。 ふわふわとした感覚のジャンプが難しい。おそらく空中での移動量が多いのだと思う。思った以上に飛んだり飛ばなかったりする。先の例に挙げたヨッシーはジャンプ力が高いのでこれが顕著に出ている。ジャンプ制御の難しさが各種ヒミツの難易度の高さにつながっていると思う。これの微調整のためのポンプなのかもしれないが水の補充を含めて難易度を上げたいのか下げたいのかよく分からない。あといまだにスピンジャンプが狙った方向に出せない。 乗り物に不快なものが多い。例えばヨッシー・コースター・泥舟などだ。むしろ不快じゃない乗り物などなかったような気がする。 ギャラクシーを少なくとも今月ははじめない。既にゲームをしすぎている。 --- その他のメモ。 衝動的に買った ([2020-12-01][]) 涼宮ハルヒのシリーズを持っている分はひととおり読んだ。どうでもいいのだけど積まれていると気になるので。 [bouzuya/rust-social-bookmarking][] v0.2.0 をつくった。やっつけ気味。いろいろと直したい。モチベーションが下がって完成しない流れになっている。 # 2012-W03 の目標 - 『 GitHub Actions 実践入門』を読む - bouzuya/rust-social-bookmarking v0.2.1 をつくる [2020-11-14]: [IDX] [IDX] [IDX] [IDX] [IDX] [IDX] [IDX] [IDX] [IDX] [IDX] [IDX]<|endoftext|># ビデオストリーミング - [コーデック](#codec) - [ビデオトラック](#video-track) - [トラックの追加](#add-track) - [マルチトラック](#multi-track) WebRTC はピア間での映像のストリーミングを可能にします。 Unity でレンダリングされた映像を同時に複数のブラウザに配信することが可能です。 ## <a id="codec"/> コーデック ビデオストリーミングで利用するエンコーダーには、ハードウェアでエンコードするものと、ソフトウェアでエンコードするものがあります。利用するコーデックは、ハードウェアエンコーダーの場合には `H.264` を利用し、ソフトウェアエンコーダーの場合は、`VP8` コーデックを利用します。 `WebRTC.Initialize` メソッドの引数に `EncoderType` を指定することで、 ソフトウェアエンコーダーとハードウェアエンコーダーのいずれかを選択することができます。 ```CSharp // ソフトウェアエンコーダーを使用 WebRTC.Initialize(EncoderType.Software); ``` > [!NOTE] > このオプションはハードウェアを利用する/利用しないを選択するオプションです。 > コーデックを明示的に指定する方法は、現在提供していません。 WebRTC をサポートしている主要なブラウザでは `H.264` 及び `VP8` が利用できるため、多くのブラウザで Unity から配信されるビデオストリーミングを受信することができます。 ## <a id="video-track"/> ビデオトラック ビデオストリーミングを実装するには、ビデオトラック `VideoStreamTrack` のインスタンスを生成します。 ```CSharp // Camera からトラックを生成 var camera = GetComponnent<Camera>(); var track = camera.CaptureStreamTrack(1280, 720); ``` `RenderTexture` を直接指定する方法もあります。 ```CSharp // 有効な RendertextureFormat を取得 var gfxType = SystemInfo.graphicsDeviceType; var format = WebRTC.GetSupportedRenderTextureFormat(gfxType); // RenderTexture からトラックを生成 var rt = new RenderTexture(width, height, 0, format); var track = new VideoStreamTrack("video", renderTexture); ``` ### <a id="add-track"/> トラックの追加 生成したビデオトラックを `RTCPeerConnection` のインスタンスに追加します。`AddTrack` メソッドを呼び出すことでトラックを追加できます。その後 SDP を生成するために `RTCPeerConnection` の `CreateOffer` もしくは `CreateAnswer` を呼び出します。 ```CSharp // トラックを追加 peerConnection.AddTrack(track); // SDP を生成 RTCAnswerOptions options = default; var op = pc.CreateAnswer(ref options); yield return op; ``` ### <a id="multi-track"/> マルチトラック ビデオトラックは複数同時に利用することが可能です。 `RTCPeerConnection` の `AddTrack` メソッドを複数回呼び出してトラックを追加します。 ```CSharp // 複数のトラックを追加 foreach(var track in listTrack) { } ``` ハードウェアエンコーダーを選択している場合、グラフィックデバイスの制約によって、同時に利用可能なトラック数が制限される場合があります。一般的に NVIDIA Geforce で同時に利用可能なビデオトラック数は **2本** までです。詳しくは [NVDIA Codec SDK のドキュメント]( [IDX] を参照してください。 ブラウザ側でトラックを同時に受信する方法については、MDN ドキュメント [`RTCPeerConnection.addTrack`]( [IDX] の **Streamless tracks** の項目を参照してください。
[{"idx": "17412948", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-16577.jsonl"}, {"idx": "14612279", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-16577.jsonl"}, {"idx": "14628056", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-16577.jsonl"}, {"idx": "2758611", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-16577.jsonl"}, {"idx": "2768328", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-16577.jsonl"}]
import datetime import data_integration.config import mara_acl.config import mara_db.config import mara_db.dbs from mara_app.monkey_patch import patch import app.config @patch(mara_db.config.databases) def databases(): return { # the project requires two databases: 'mara' for the app itself, and 'dwh' for the etl '{{cookiecutter.default_db_alias}}': mara_db.dbs.PostgreSQLDB(user='{{cookiecutter.database_user}}', database='{{cookiecutter.project_slug.replace("-", "_")}}_{{cookiecutter.default_db_alias}}'), 'mara': mara_db.dbs.PostgreSQLDB(user='{{cookiecutter.database_user}}', database='{{cookiecutter.project_slug.replace("-", "_")}}_mara') } # Disable http header based authentication patch(mara_acl.config.require_email_ http_header)(lambda: False) # How many cores to use for running the ETL, defaults to the number of CPUs of the machine # On production, make sure the ETL does not slow down other services too much patch(data_integration.config.max_number_of_parallel_tasks)(lambda: 4) # The first day for which to download and process data (default 2017-01-01). # Locally, a few days of data is enough to test a pipeline. # On production, size of days that can be processed depends on machine size. patch(app.config.first_date)(lambda: datetime.date.today() - datetime.timedelta(days=5)) # Whether it is possible to run the ETL from the web UI # Disable on production patch(data_integration.config.allow_run_from_web_ui)(lambda: True)<|endoftext|>'UNTIL THE GOVERNMENT SOLVES THE PROBLEMS', 'IN A MENT SENT TO US', 'IN A MENT TO NEWSHOUR WEEKEND', 'CHUCK SCHUMER CHIMED IN', 'SEAN SPICER SAID TODAY', 'IN A MENT TO THE COURT', 'IN THE ROTUNDA OF THE HOUSE', 'IN A LETTER TO <NAME>', 'IN A MENT TO THE ASSOCIATED PRESS', 'ROBERT CUTLER WROTE US ON OUR WEBSITE', 'RY<NAME>ZZA WITH THE ER WRITES', 'VICE JOE BIDEN’S ECONOMIC ADVISER', 'IN VIDEO RELEASED BY THE', 'I RECENTLY SPOKE WITH RON FOURNIER', 'I THINK WHAT I SAID IS', 'I WANT TO BE REALLY CLEAR', 'I WOULD JUST ASK THIS QUESTION', 'AS IT TURNS OUT', 'IT HAPPENED AROUND 1', 'HOW MUCH THE CAN AFFECT THAT', 'IAL NOMINEE DONALD TRUMP TWEETED TODAY', 'IF YOU’RE LOOKING FOR WHAT’S TROUBLING S', '<NAME> YESTERDAY IN', 'HE TOLD THE WALL STREET JOURNAL YESTERDAY', 'FRANKEN APOLOGIZED TO TWEEDEN IN A MENT', 'GIVEN THE UNIQUE POWER OF THE', 'DEVAL PATRICK SPOKE AT 8', 'AND VERA WANG TWEETED', 'IT’S “CITY OF THORNS', 'FROM FLOOD TO FIRE', 'UPPING THE ANTE', 'TOUGH AUSTERITY MEASURES', 'THIS MAKES VOTER CONTACT', "AND THIS WONDERFUL GENERAL", 'AND DESPITE MAJOR DIFFERENCES', 'ANOTHER MAJOR PROBLEM AND EXPENSE', 'IN THE MAJORITY OPINION', 'NOW A NEW MAJOR TASK', }<|endoftext|>__date__ = "1/13/06" __version__ = "0.4" import initialize import single_file import os import sys import argParser # FUNCTION DEFINITIONS # def main(filename,salts_file,output_path,pH_start,pH_stop, pH_interval,dielectric): f = open(salts_file) salts = [float(salt) for salt in f.readlines()] f.close() for salt in salts: print salt salt_output = output_path + os.sep + ("%.1F" % salt) # Create output directory try: os.mkdir(initialize.invocation_path + salt_output) except OSError, value: # Don't stop if we are only overwriting existing directory if value[0] != 17: print 'File error.' print value[0], initialize.invocation_path + salt_output, value[1] sys.exit() single_file.main(filename,salt_output,pH_start,pH_stop,pH_interval,salt,dielectric) # If this is the script that is executed, then run the main function if __name__ == "__main__": # Parse the command line arguments required, optional = argParser.main(sys.argv, ["pdb_file","salt_file","output_dir"], ["inpfile","inpfile","outdir"], ["dielectric","pHtitr"]) # Execute the salts script main(required["pdb_file"],required["salt_file"],required["output_dir"], pH_start=optional.pHtitr[0],pH_stop=optional.pHtitr[1], pH_interval=optional.pHtitr[2],dielectric=optional.dielectric)<|endoftext|>import requests import logging from time import sleep from creds import ( Bearer_Token, Prod_SF_Login, Dev_SF_Login, Unwiredlabs_Token, Snowflake ) from json import loads, dumps import pandas as pd import snowflake.connector from pandas.io import sql import numpy as np def main(): with open("log.txt", "w") as myfile: # clears the log file log_line = f"{date.today()} \n" myfile.write(log_line) conn = connect() snapshot(conn) return () # 2 get heartbeats def snapshot(conn): query = """ insert into db.raw.asset_scd2 select asset.name as name, asset.status as status, sales_type as sales_type, CURRENT_TIMESTAMP(0) as _timestamp, FALSE as _deleted from salesforce.asset as asset left join db.raw.asset_scd2 as asset_snapshot on (asset.name = asset_snapshot.name) where asset.is_deleted = 'False' and (asset_snapshot._timestamp < date_from_parts(year(current_date()), month(current_date()), 1) or asset_snapshot._timestamp is null) """ Snowflake_df = sql.read_sql_query(query, conn) return () def connect(): user, password = Snowflake() # print (user,password) conn = snowflake.connector.connect( user=user, password=password, account="account.west-us-2.azure", warehouse="WH", database="DB", schema="schema", ) session = conn.session_id query_staus = conn.get_query_status network_timeout = conn.network_timeout error_list = conn.is_an_error return conn # 2 Roc Auth if __name__ == "__main__": main()<|endoftext|>from ai.executors.executor import Executor class PlayExecutor(Executor): def __init__(self, p_world_state): super().__init__(p_world_state) def exec(self): self._send_books() self._execute_strategy() self._send_robots_status() def _execute_strategy(self): if self.ws.play_state.current_strategy is None: self.ws.play_state.set_strategy(self.ws.play_state. get_new_strategy("HumanControl") (self.ws.game_state)) self.ws.play_state.current_ai_commands = \ self.ws.play_state.current_strategy.exec() # FIXME revise this function please def _send_robots_status(self): states = self.ws.play_state.get_current_tactical_state() for state in states: player_id = state[0] tactic_name = state[1] action_name = state[2] target = (int(state[3].position.x), int(state[3].position.y)) self.ws.debug_interface.send_robot_status(player_id, tactic_name, action_name, target) def _send_books(self): cmd_tactics = {'strategy': self.ws.play_state. strategy_book.get_strategies_name_list(), 'tactic': self.ws.play_state.tactic_book. get_tactics_name_list(), 'action': ['None']} self.ws.debug_interface.send_books(cmd_tactics)<|endoftext|>from toee import * from utilities import * triggerer.begin_dialog( attachee, 100 ) return SKIP_DEFAULT itemA = attachee.item_find(5004) if (itemA != OBJ_HANDLE_NULL): itemA.destroy() create_item_in_inventory( 5004, attachee) itemB = attachee.item_find(5005) if (itemB != OBJ_HANDLE_NULL): itemB.destroy() create_item_in_inventory( 5005, attachee) itemC = attachee.item_find(5006) if (itemC != OBJ_HANDLE_NULL): itemC.destroy() create_item_in_inventory( 5006, attachee) itemD = attachee.item_find(5007) if (itemD != OBJ_HANDLE_NULL): itemD.destroy() create_item_in_inventory( 5007, attachee) itemE = attachee.item_find(5010) if (itemE != OBJ_HANDLE_NULL): itemE.destroy() create_item_in_inventory( 5010, attachee) itemF = attachee.item_find(5011) if (itemF != OBJ_HANDLE_NULL): itemF.destroy() create_item_in_inventory( 5011, attachee) itemG = attachee.item_find(5013) if (itemG != OBJ_HANDLE_NULL): itemG.destroy() create_item_in_inventory( 5013, attachee) return RUN_DEFAULT def san_dying( attachee, triggerer ): game.global_flags[128] = 1 game.leader.reputation_add( 14 ) return RUN_DEFAULT game.global_flags[128] = 0 return RUN_DEFAULT def san_heartbeat( attachee, triggerer ): if (not game.combat_is_active()): if attachee.has_los(obj): if (is_better_to_talk(attachee, game.party[0])): if (not critter_is_unconscious(game.party[0])): game.leader.begin_dialog( attachee, 1 ) game.new_sid = 0 else: if (is_safe_to_talk(attachee, obj)): obj.begin_dialog(attachee, 1) # fixes invalid dialogue bug game.new_sid = 0 return RUN_DEFAULT<|endoftext|>import os import argparse import torch from gail_airl_ppo.env import make_env, make_dmc_env from gail_airl_ppo.algo import SACExpert from gail_airl_ppo.utils import collect_demo def run(args): if args.dmc: env = make_dmc_env(args.domain, args.task) env_test = make_dmc_env(args.domain, args.task) else: env = make_env(args.env_id) env_test = make_env(args.env_id) algo = SACExpert( state_shape=env.observation_space.shape, action_shape=env.action_space.shape, device=torch.device("cuda" if args.cuda else "cpu"), path=args.weight ) buffer = collect_demo( env=env, algo=algo, buffer_size=args.buffer_size, device=torch.device("cuda" if args.cuda else "cpu"), std=args.std, p_rand=args.p_rand, seed=args.seed ) if args.dmc: 'buffers', f'{args.domain}-{args.task}', )) else: 'buffers', args.env_id, )) if __name__ == '__main__': p.add_argument('--weight', type=str, required=True) p.add_argument('--dmc', action='store_true') p.add_argument('--domain', type=str, default='quadruped') p.add_argument('--task', type=str, default='walk') p.add_argument('--env_id', type=str, default='Hopper-v3') p.add_argument('--buffer_size', type=int, default=10**6) p.add_argument('--std', type=float, default=0.0) p.add_argument('--p_rand', type=float, default=0.0) p.add_argument('--cuda', action='store_true') p.add_argument('--seed', type=int, default=0) args = p.parse_args() run(args)
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9490.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9490.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9490.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9490.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9490.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9490.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9490.jsonl"}]
'''Generates Go source files from a mojom.Module.''' from itertools import chain import os import re from mojom.generate.template_expander import UseJinja import mojom.generate.module as mojom class KindInfo(object): def __init__(self, go_type, encode_suffix, decode_suffix, bit_size): self.go_type = go_type self.encode_suffix = encode_suffix self.decode_suffix = decode_suffix self.bit_size = bit_size _kind_infos = { mojom.BOOL: KindInfo('bool', 'Bool', 'Bool', 1), mojom.INT8: KindInfo('int8', 'Int8', 'Int8', 8), mojom.UINT8: KindInfo('uint8', 'Uint8', 'Uint8', 8), mojom.INT16: KindInfo('int16', 'Int16', 'Int16', 16), mojom.UINT16: KindInfo('uint16', 'Uint16', 'Uint16', 16), mojom.INT32: KindInfo('int32', 'Int32', 'Int32', 32), mojom.UINT32: KindInfo('uint32', 'Uint32', 'Uint32', 32), mojom.FLOAT: KindInfo('float32', 'Float32', 'Float32', 32), mojom.HANDLE: KindInfo( mojom.DCPIPE: KindInfo( mojom.DPPIPE: KindInfo( mojom.MSGPIPE: KindInfo( mojom.SHAREDBUFFER: KindInfo( mojom.NULLABLE_HANDLE: KindInfo( mojom.NULLABLE_DCPIPE: KindInfo( mojom.NULLABLE_DPPIPE: KindInfo( mojom.NULLABLE_MSGPIPE: KindInfo( mojom.NULLABLE_SHAREDBUFFER: KindInfo( mojom.INT64: KindInfo('int64', 'Int64', 'Int64', 64), mojom.UINT64: KindInfo('uint64', 'Uint64', 'Uint64', 64), mojom.DOUBLE: KindInfo('float64', 'Float64', 'Float64', 64), mojom.STRING: KindInfo('string', 'String', 'String', 64), mojom.NULLABLE_STRING: KindInfo('string', 'String', 'String', 64), } def GetBitSize(kind): if isinstance(kind, (mojom.Array, mojom.Map, mojom.Struct)): return 64 if isinstance(kind, (mojom.InterfaceRequest, mojom.Interface)): kind = mojom.MSGPIPE if isinstance(kind, mojom.Enum): kind = mojom.INT32 return _kind_infos[kind].bit_size def GetGoType(kind, nullable = True): if nullable and mojom.IsNullableKind(kind): return '*%s' % GetNonNullableGoType(kind) return GetNonNullableGoType(kind) def GetNonNullableGoType(kind): return '%s' % FormatName(kind.name) if mojom.IsArrayKind(kind): if kind.length: return '[%s]%s' % (kind.length, GetGoType(kind.kind)) return '[]%s' % GetGoType(kind.kind) if mojom.IsMapKind(kind): return 'map[%s]%s' % (GetGoType(kind.key_kind), GetGoType(kind.value_kind)) return GetGoType(mojom.MSGPIPE) if mojom.IsEnumKind(kind): return GetNameForNestedElement(kind) return _kind_infos[kind].go_type def NameToComponent(name): # insert '_' between anything and a Title name (e.g, HTTPEntry2FooBar -> # HTTP_Entry2_FooBar) name = re.sub('([^_])([A-Z][^A-Z_]+)', r'\1_\2', name) # insert '_' between non upper and start of upper blocks (e.g., # HTTP_Entry2_FooBar -> HTTP_Entry2_Foo_Bar) name = re.sub('([^A-Z_])([A-Z])', r'\1_\2', name) return [x.lower() for x in name.split('_')] def UpperCamelCase(name): return ''.join([x.capitalize() for x in NameToComponent(name)]) def FormatName(name, exported=True): if exported: return UpperCamelCase(name) # Leave '_' symbols for unexported names. return name[0].lower() + name[1:] def GetNameForNestedElement(element): if element.parent_kind: return "%s_%s" % (GetNameForElement(element.parent_kind), FormatName(element.name)) return FormatName(element.name) def GetNameForElement(element, exported=True): if (mojom.IsInterfaceKind(element) or mojom.IsStructKind(element) or isinstance(element, (mojom.EnumField, mojom.Field, mojom.Method, mojom.Parameter))): return FormatName(element.name, exported) if isinstance(element, (mojom.Enum, mojom.Constant, mojom.ConstantValue)): return GetNameForNestedElement(element) raise Exception('Unexpected element: %s' % element) def ExpressionToText(token): if isinstance(token, mojom.EnumValue): return "%s_%s" % (GetNameForNestedElement(token.enum), FormatName(token.name, True)) if isinstance(token, mojom.ConstantValue): return GetNameForNestedElement(token) if isinstance(token, mojom.Constant): return ExpressionToText(token.value) return token def DecodeSuffix(kind): if mojom.IsEnumKind(kind): return DecodeSuffix(mojom.INT32) return DecodeSuffix(mojom.MSGPIPE) return _kind_infos[kind].decode_suffix def EncodeSuffix(kind): if mojom.IsEnumKind(kind): return EncodeSuffix(mojom.INT32) return EncodeSuffix(mojom.MSGPIPE) return _kind_infos[kind].encode_suffix def GetPackage(module): if module.namespace: return module.namespace.split('.')[-1] return 'mojom' def GetPackagePath(module): path = 'mojom' for i in module.namespace.split('.'): path = os.path.join(path, i) return path def GetStructFromMethod(method): params_class = "%s_%s_Params" % (GetNameForElement(method.interface), for param in method.parameters: struct.AddField("in%s" % GetNameForElement(param), return struct def GetResponseStructFromMethod(method): params_class = "%s_%s_ResponseParams" % (GetNameForElement(method.interface), for param in method.response_parameters: struct.AddField("out%s" % GetNameForElement(param), return struct go_filters = { 'array': lambda kind: mojom.Array(kind), 'bit_size': GetBitSize, 'decode_suffix': DecodeSuffix, 'encode_suffix': EncodeSuffix, 'go_type': GetGoType, 'expression_to_text': ExpressionToText, 'is_array': mojom.IsArrayKind, 'is_enum': mojom.IsEnumKind, 'is_handle': mojom.IsAnyHandleKind, 'is_map': mojom.IsMapKind, 'is_none_or_empty': lambda array: array == None or len(array) == 0, 'is_nullable': mojom.IsNullableKind, 'is_pointer': mojom.IsObjectKind, 'is_struct': mojom.IsStructKind, 'name': GetNameForElement, 'response_struct_from_method': GetResponseStructFromMethod, 'struct_from_method': GetStructFromMethod, 'tab_indent': lambda s, size = 1: ('\n' + '\t' * size).join(s.splitlines()) } def GetAllEnums(self): data = [self.module] + self.GetStructs() + self.module.interfaces enums = [x.enums for x in data] return [i for i in chain.from_iterable(enums)] def GetParameters(self): return { 'enums': self.GetAllEnums(), 'interfaces': self.module.interfaces, 'package': GetPackage(self.module), 'structs': self.GetStructs(), } @UseJinja('go_templates/source.tmpl', filters=go_filters) def GenerateSource(self): return self.GetParameters() self.Write(self.GenerateSource(), os.path.join("go", "src", "gen", GetPackagePath(self.module), '%s.go' % self.module.name)) def GetJinjaParameters(self): return { 'lstrip_blocks': True, 'trim_blocks': True, } def GetGlobals(self): return { 'namespace': self.module.namespace, 'module': self.module, }<|endoftext|>import logging import mimetypes import posixpath import traceback from compiled_file_system import SingleFile from directory_zipper import DirectoryZipper from docs_server_utils import ToUnicode from path_canonicalizer import PathCanonicalizer from path_util import AssertIsValid, IsDirectory, Join, ToDirectory from third_party.handlebar import Handlebar from third_party.markdown import markdown _MIMETYPE_OVERRIDES = { # SVG is not supported by mimetypes.guess_type on AppEngine. '.svg': 'image/svg+xml', } class ContentAndType(object): '''Return value from ContentProvider.GetContentAndType. ''' def __init__(self, content, content_type, version): self.content = content self.content_type = content_type self.version = version class ContentProvider(object): '''Returns file contents correctly typed for their content-types (in the HTTP sense). Content-type is determined from Python's mimetype library which guesses based on the file extension. Typically the file contents will be either str (for binary content) or unicode (for text content). However, HTML files *may* be returned as Handlebar templates (if |supports_templates| is True on construction), in which case the caller will presumably want to Render them. Zip file are automatically created and returned for .zip file extensions if |supports_zip| is True. |default_extensions| is a list of file extensions which are queried when no file extension is given to GetCanonicalPath/GetContentAndType. Typically this will include .html. ''' def __init__(self, name, file_system, default_extensions=(), supports_templates=False, supports_zip=False): # Public. self.name = name self.file_system = file_system # Private. self._content_cache = compiled_fs_factory.Create(file_system, self._CompileContent, ContentProvider) self._path_canonicalizer = PathCanonicalizer(file_system, default_extensions) self._default_extensions = default_extensions self._supports_templates = supports_templates if supports_zip: self._directory_zipper = DirectoryZipper(compiled_fs_factory, file_system) else: self._directory_zipper = None @SingleFile def _CompileContent(self, path, text): assert text is not None, path mimetype = _MIMETYPE_OVERRIDES.get(ext, mimetypes.guess_type(path)[0]) if ext == '.md': # See [IDX] # for details on "extensions=". content = markdown(ToUnicode(text), extensions=('extra', 'headerid', 'sane_lists')) mimetype = 'text/html' elif mimetype is None: content = text mimetype = 'text/plain' elif mimetype == 'text/html': elif (mimetype.startswith('text/') or mimetype in ('application/javascript', 'application/json')): else: content = text return ContentAndType(content, mimetype, self.file_system.Stat(path).version) def GetCanonicalPath(self, path): '''Gets the canonical location of |path|. This class is tolerant of spelling errors and missing files that are in other directories, and this returns the correct/canonical path for those. For example, the canonical path of "browseraction" is probably "extensions/browserAction.html". Note that the canonical path is relative to this content provider i.e. given relative to |path|. It does not add the "serveFrom" prefix which would have been pulled out in ContentProviders, callers must do that themselves. ''' AssertIsValid(path) # The canonical location of zip files is the canonical location of the # directory to zip + '.zip'. return self._path_canonicalizer.Canonicalize(base + '/').rstrip('/') + ext return self._path_canonicalizer.Canonicalize(path) def GetContentAndType(self, path): '''Returns a Future to the ContentAndType of the file at |path|. ''' AssertIsValid(path) return (self._directory_zipper.Zip(ToDirectory(base)) .Then(lambda zipped: ContentAndType(zipped, 'application/zip', None))) return self._FindFileForPath(path).Then(self._content_cache.GetFromFile) def GetVersion(self, path): '''Returns a Future to the version of the file at |path|. ''' AssertIsValid(path) stat_future = self.file_system.StatAsync(ToDirectory(base)) else: stat_future = self._FindFileForPath(path).Then(self.file_system.StatAsync) return stat_future.Then(lambda stat: stat.version) def _FindFileForPath(self, path): '''Finds the real file backing |path|. This may require looking for the correct file extension, or looking for an 'index' file if it's a directory. Returns None if no path is found. ''' AssertIsValid(path) if ext: # There was already an extension, trust that it's a path. Elsewhere # up the stack this will be caught if it's not. return Future(value=path) def find_file_with_name(name): '''Tries to find a file in the file system called |name| with one of the default extensions of this content provider. If none is found, returns None. ''' paths = [name + ext for ext in self._default_extensions] def get_first_path_which_exists(existence): for exists, path in zip(existence, paths): if exists: return path return None return (All(self.file_system.Exists(path) for path in paths) .Then(get_first_path_which_exists)) def find_index_file(): '''Tries to find an index file in |path|, if |path| is a directory. If not, or if there is no index file, returns None. ''' def get_index_if_directory_exists(directory_exists): if not directory_exists: return None return find_file_with_name(Join(path, 'index')) return (self.file_system.Exists(ToDirectory(path)) .Then(get_index_if_directory_exists)) # Try to find a file with the right name. If not, and it's a directory, # look for an index file in that directory. If nothing at all is found, # return the original |path| - its nonexistence will be caught up the stack. return (find_file_with_name(path) .Then(lambda found: found or find_index_file()) .Then(lambda found: found or path)) def Cron(self): futures = [self._path_canonicalizer.Cron()] for root, _, files in self.file_system.Walk(''): for f in files: futures.append(self.GetContentAndType(Join(root, f))) # Also cache the extension-less version of the file if needed. base, ext = posixpath.splitext(f) if f != SITE_VERIFICATION_FILE and ext in self._default_extensions: futures.append(self.GetContentAndType(Join(root, base))) # TODO(kalman): Cache .zip files for each directory (if supported). return All(futures, except_pass=Exception, except_pass_log=True) def __repr__(self): return 'ContentProvider of <%s>' % repr(self.file_system)
[{"idx": "", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-19853.jsonl"}, {"idx": "", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-19853.jsonl"}]
Initialising a 2d map c++ Question: I have been thinking lately about 2d structures (of integers) in which their sizes can grow dynamically. I came across 'map' which I think that it meets my following need: Essentially, what I want is to check whether a random entry has been initialized or not (do something if it has not been initialized yet). <code>int main(){ int int1, int2; std::map<int,std::map<int,int>> my_map; cout << "Enter two integers separated by space: "; cin >> int1 >> int2; if(has my_map[int1][int2] not been initialized){ do something } } </code> I am hoping that such functionality is available with C++. Answer: If what you mean by checking whether an entry "has been initialized" is checking that a pair of keys has a value assigned to them -- one key for the outer map and one for the inner map -- you can test contents of a map of maps as below: <code>bool contains_keys(const std::map<int, std::map<int, int>>& map_of_maps, int key1, int key2) { auto iter = map_of_maps.find(key1); if (iter == map_of_maps.end()) { return false; } return iter->second.find(key2) != iter->second.end(); } </code> However, I question whether a map of maps is really what you want. If what you want is just a mapping from two keys to a single value, a more direct and space efficient implementation is to use an std::map with an std::tuple or std::pair as the key type. Tuples version below. <code>#include <map> #include <tuple> #include <iostream> int main() { std::map<std::tuple<int, int>, int> map_of_pairs; map_of_pairs[{42, 17}] = 3; bool contains_42_17 = (map_of_pairs.find({ 42, 17 }) != map_of_pairs.end()); bool contains_67_23 = (map_of_pairs.find({ 67, 23 }) != map_of_pairs.end()); std::cout << ((contains_42_17) ? "yes\n" : "no\n"); std::cout << ((contains_67_23) ? "yes\n" : "no\n"); } </code> Also unless you actually need the above to be ordered, consider an unordered_map. Answer: You could write a function that first checks the outer map for <code>key1</code>, then if an inner map exists with that key, check the inner map for <code>key2</code>. <code>bool nested_contains(std::map<int,std::map<int,int>> const& my_map, int key1, int key2) { auto itOuter = my_map.find(key1); if (itOuter == my_map.end()) return false; return itOuter->second.contains(key2); } </code> Then use it like <code>int main() { int int1, int2; std::map<int,std::map<int,int>> my_map; std::cout << "Enter two integers separated by space: "; std::cin >> int1 >> int2; if(nested_contains(my_map, int1, int2)){ // do something } } </code> Answer: You can quickly do it creating a custom function using the find method. In that case the algorithm is suitable for being generic. <code>template<typename T> bool contains_keys_cpp_20(std::map<T, std::map<T, T>> const& nested_map, T key1, T key2) { auto pair = nested_map.find(key1); return (pair != nested_map.end()) && (pair->second.contains(key2)); } template<typename T> bool contains_keys_cpp_17(std::map<T, std::map<T, T>> const& nested_map, T key1, T key2) { auto pair = nested_map.find(key1); return (pair != nested_map.end()) && (pair->second.find(key2) != pair->second.end()); } int main() { { std::map<int, std::map<int, int>> my_map; my_map[1] = { { 2, 1} }; bool result = contains_keys_cpp_17(my_map, 3, 2); // false } { std::map<int, std::map<int, int>> my_map; my_map[3] = { { 2, 1} }; bool result = contains_keys_cpp_17(my_map, 3, 2); // true } { std::map<char, std::map<char, char>> my_map; my_map['3'] = { { '2', '1'} }; bool result = contains_keys_cpp_17(my_map, '3', '2'); // true } return 0; } </code><|endoftext|>Использование condition_variable в с++11 и с++17. Не одинаковый ход выполнения программы Question: Запускаю тот же код в разных IDE и получаю разные результаты. В VS2013(с++11) выполняется как и ожидаю: число заносится в массив в одном потоке, второй поток просыпается и читает число. Через секунду все повторяется. В VS2017(с++17) выполняется по-другому: Второй поток просыпается только в конце, когда завершается первый поток, убивая свой mutex и выводит сразу все 10 чисел через 10 секунд. Почему такое различие? Пример <code>#include "stdafx.h" #include <iostream> #include <thread> #include <vector> #include <thread> #include<future> #include <chrono> using namespace std; template<int max_number> void data_preparation_tread(shared_ptr<mutex>& mut, shared_ptr<vector<int>>& data_queue, shared_ptr<condition_variable>& data_cond) { while (true) { static int x = 0; x++; lock_guard<mutex> ld(*mut); data_queue->push_back(x); data_cond->notify_one(); chrono::milliseconds ms(1000); this_thread::sleep_for(ms); if (x == max_number) break; } } template<int max_number> void data_processing_thread(shared_ptr<mutex>& mut, shared_ptr<vector<int>>& data_queue, shared_ptr<condition_variable>& data_cond) { while (true) { std::unique_lock<mutex> lk(*mut); data_cond->wait(lk, [=]{ if (data_queue->empty()) { cout << endl << "Fault wake up" << endl; } return !data_queue->empty(); }); int number{}; while (data_queue->size() > 0) { number = data_queue->back(); data_queue->pop_back(); cout << "Number:" << number << " " << "Buffer length:" << data_queue->size() << endl; } lk.unlock(); if (number == max_number) break; } } int _tmain(int argc, _TCHAR* argv[]) { shared_ptr<mutex> mut = make_shared<mutex>(); shared_ptr<vector<int>> data_queue = make_shared<vector<int>>(); shared_ptr<condition_variable> data_cond = make_shared<condition_variable>(); void(*pdata_procc)(std::shared_ptr<std::mutex>& mut, shared_ptr<vector<int>>& data_queue, shared_ptr<condition_variable>& data_cond) = data_processing_thread<10>; void(*pdata_prepar)(std::shared_ptr<std::mutex>& mut, shared_ptr<vector<int>>& data_queue, shared_ptr<condition_variable>& data_cond) = data_preparation_tread<10>; std::thread processing = thread(pdata_procc, ref(mut), ref(data_queue), ref(data_cond)); std::thread preparation = thread(pdata_prepar, ref(mut), ref(data_queue), ref(data_cond)); processing.join(); preparation.join(); getchar(); return 0; } </code> Answer: Посмотрите на функцию data_preparation_tread - мютекс блокирует почти все тело. Только инкремент <code>x++</code>. Поэтому, шансов, что кто то пролезет через эту блокировку - очень мало. Самый простой способ исправить - это добавить пару скобок <code>static int x = 0; x++; { lock_guard<mutex> ld(*mut); data_queue->push_back(x); data_cond->notify_one(); } chrono::milliseconds ms(1000); this_thread::sleep_for(ms); if (x == max_number) break; </code> Почему оно работало раньше? ну видимо везло, менеджер потоков по другому разбрасывал. BTW - код написан очень странно (вот это <code>template<typename int max_number></code>, например) - не компилируется ни gcc, ни clang, пришлось порезать шаблоны. Comment: В книге С++ Concurrency in action без скобок. Со скобками: тогда во втором потоке постоянно будет срабатывать "Fault wake up". И в 2013 студии это работает идеально Comment: да, срабатывает. Но там в книге другой код. Comment: принцип тот-же. только через глобальные переменные а не через shared_ptr. Comment: @YuryMelnikov не верю... Comment: @PavelMayorov зуб даю<|endoftext|>valgrind Address 0x421688c is 0 bytes after a block of size 4 alloc'd for linked list having integer data Question: Although there were multiple threads related to valgrind Address 0x421688c is 0 bytes after a block of size 4 alloc'd kind of questions, but all were expressed with either strlen, or '\0' related issues and I understand them. I am having with linked list insertion dealing with integers. <code>void insert_node(lnode **head, int num){ lnode *temp = NULL; temp = calloc(1, sizeof(lnode *)); if(temp == NULL){ printf("Memory Allocation failed!\n"); return; } temp->data = num; temp->next = NULL; if(*head == NULL){ *head = temp; } else{ temp->next = *head; *head = temp; } } </code> I did insertion, deletion steps and get summary(showing last few lines of valgrind errors as the errors are at the same place): <code> > ==3238== 9 errors in context 5 of 5: > ==3238== Invalid read of size 4 > ==3238== at 0x804873D: display (in /home/skb/santosh_practice/linked_list_progs/single_LL/a.out) > ==3238== by 0x8048636: main (in /home/skb/santosh_practice/linked_list_progs/single_LL/a.out) > ==3238== Address 0x42168fc is 0 bytes after a block of size 4 alloc'd > ==3238== at 0x402C17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) > ==3238== by 0x8048686: insert_node (in /home/skb/santosh_practice/linked_list_progs/single_LL/a.out) > ==3238== by 0x8048614: main (in /home/skb/santosh_practice/linked_list_progs/single_LL/a.out) > ==3238== > ==3238== ERROR ERROR SUMMARY: 22 errors from 5 contexts (suppressed: 0 from 0) </code> Please tell me where I am doing wrong? Comment: `sizeof(lnode *)` -> `sizeof(lnode)` Comment: @MichaelWalz, I tried and got fixed but why is it so? the memory allocation is for pointer! Comment: No; you need enough space for the structure, and will be given a pointer to that much space. Comment: You should create a whole program for your [mcve], and compile it with debug symbols, so that the Valgrind output contains source line numbers. Comment: I already did that. I just put here the last few lines of valgrind summary because I know the problem lied only at one line. Also, had I been put the complete code and valgrind, it would have filled with few pages. Whatever I provided in question, is very much clear to viewers. Answer: Your problem lies in the size that you allocated. <code>lnode *temp = NULL; temp = calloc(1, sizeof(lnode *)); </code> It must be <code>lnode *temp = NULL; temp = calloc(1, sizeof(lnode)); </code> If your structure take 18 octet in memory, and a pointer take 8 octet, with the first code, you will allocate 8 octet instead of 18, which is insuffisent. a good trick to never have the wrong type is to do <code>lnode *temp = NULL; temp = calloc(1, sizeof(*temp)); </code> Because "temp" is type of "lnode *" and "*temp" is type of "lnode" Comment: that was pretty well thought! `temp = calloc(1, sizeof(*temp));`, it made me sense that memory allocation is for the contents' size what it will store, not the pointer's size. Thanks! Comment: No need for parens when you give an *expression* to `sizeof` - that's only needed if you want the size of a *type*. `temp = calloc(1, sizeof *temp)` is clearer. Answer: You are allocating space for a pointer to <code>lnode</code>, actually the size of any pointer on your platform (4 bytes on a 32 bit system, 8 bytes on a 64 bit system), but you need to allocate space for the struct <code>lnode</code> which is the thing the pointer points to. <code>sizeof(lnode *)</code> is the size of the pointer (usually 4 bytes on a 32 bit system or 8 bytes on a 64 bit system. <code>sizeof(lnode)</code> is the size of the struct <code>lnode</code> which depends on how the struct is defined.
[{"idx": "Initialising_a_2d_map_c++", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8269.jsonl"}, {"idx": "\u0418\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435_condition_variable_\u0432_\u0441++11_\u0438_\u0441++17._\u041d\u0435_\u043e\u0434\u0438\u043d\u0430\u043a\u043e\u0432\u044b\u0439_\u0445\u043e\u0434_\u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f_\u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8269.jsonl"}, {"idx": "valgrind_Address_0x421688c_is_0_bytes_after_a_block_of_size_4_alloc'd_for_linked_list_having_integer_data", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8269.jsonl"}]
# coding: utf-8 '''A helper script to look up the names of pylint errors.''' import sys PYLINT_MAP = { 'C0102': 'blacklisted-name', 'C0103': 'invalid-name', 'C0111': 'missing-docstring', 'C0112': 'empty-docstring', 'C0113': 'unneeded-not', 'C0121': 'singleton-comparison', 'C0122': 'misplaced-comparison-constant', 'C0123': 'unidiomatic-typecheck', 'C0200': 'consider-using-enumerate', 'C0201': 'consider-iterating-dictionary', 'C0202': 'bad-classmethod-argument', 'C0203': 'bad-mcs-method-argument', 'C0204': 'bad-mcs-classmethod-argument', 'C0205': 'single-string-used-for-slots', 'C0301': 'line-too-long', 'C0302': 'too-many-lines', 'C0303': 'trailing-whitespace', 'C0304': 'missing-final-newline', 'C0305': 'trailing-newlines', 'C0321': 'multiple-statements', 'C0325': 'superfluous-parens', 'C0326': 'bad-whitespace', 'C0327': 'mixed-line-endings', 'C0328': 'unexpected-line-ending-format', 'C0330': 'bad-continuation', 'C0401': 'wrong-spelling-in-comment', 'C0402': 'wrong-spelling-in-docstring', 'C0403': 'invalid-characters-in-docstring', 'C0410': 'multiple-imports', 'C0411': 'wrong-import-order', 'C0412': 'ungrouped-imports', 'C0413': 'wrong-import-position', 'C0414': 'useless-import-alias', 'C1801': 'len-as-condition', 'E0001': 'syntax-error', 'E0011': 'unrecognized-inline-option', 'E0012': 'bad-option-value', 'E0100': 'init-is-generator', 'E0101': 'return-in-init', 'E0102': 'function-redefined', 'E0103': 'not-in-loop', 'E0104': 'return-outside-function', 'E0105': 'yield-outside-function', 'E0107': 'nonexistent-operator', 'E0108': 'duplicate-argument-name', 'E0110': 'abstract-class-instantiated', 'E0111': 'bad-reversed-sequence', 'E0112': 'too-many-star-expressions', 'E0113': 'invalid-star-assignment-target', 'E0114': 'star-needs-assignment-target', 'E0115': 'nonlocal-and-global', 'E0116': 'continue-in-finally', 'E0117': 'nonlocal-without-binding', 'E0118': 'used-prior-global-declaration', 'E0119': 'misplaced-format-function', 'E0202': 'method-hidden', 'E0203': 'access-member-before-definition', 'E0211': 'no-method-argument', 'E0213': 'no-self-argument', 'E0236': 'invalid-slots-object', 'E0237': 'assigning-non-slot', 'E0238': 'invalid-slots', 'E0239': 'inherit-non-class', 'E0240': 'inconsistent-mro', 'E0241': 'duplicate-bases', 'E0301': 'non-iterator-returned', 'E0302': 'unexpected-special-method-signature', 'E0303': 'invalid-length-returned', 'E0401': 'import-error', 'E0402': 'relative-beyond-top-level', 'E0601': 'used-before-assignment', 'E0602': 'undefined-variable', 'E0603': 'undefined-all-variable', 'E0604': 'invalid-all-object', 'E0611': 'no-name-in-module', 'E0632': 'unbalanced-tuple-unpacking', 'E0633': 'unpacking-non-sequence', 'E0701': 'bad-except-order', 'E0702': 'raising-bad-type', 'E0703': 'bad-exception-context', 'E0704': 'misplaced-bare-raise', 'E0710': 'raising-non-exception', 'E0711': 'notimplemented-raised', 'E0712': 'catching-non-exception', 'E1003': 'bad-super-call', 'E1101': 'no-member', 'E1102': 'not-callable', 'E1111': 'assignment-from-no-return', 'E1120': 'no-value-for-parameter', 'E1121': 'too-many-function-args', 'E1123': 'unexpected-keyword-arg', 'E1124': 'redundant-keyword-arg', 'E1125': 'missing-kwoa', 'E1126': 'invalid-sequence-index', 'E1127': 'invalid-slice-index', 'E1128': 'assignment-from-none', 'E1129': 'not-context-manager', 'E1130': 'invalid-unary-operand-type', 'E1131': 'unsupported-binary-operation', 'E1132': 'repeated-keyword', 'E1133': 'not-an-iterable', 'E1134': 'not-a-mapping', 'E1135': 'unsupported-membership-test', 'E1136': 'unsubscriptable-object', 'E1137': 'unsupported-assignment-operation', 'E1138': 'unsupported-delete-operation', 'E1139': 'invalid-metaclass', 'E1140': 'unhashable-dict-key', 'E1200': 'logging-unsupported-format', 'E1201': 'logging-format-truncated', 'E1205': 'logging-too-many-args', 'E1206': 'logging-too-few-args', 'E1300': 'bad-format-character', 'E1301': 'truncated-format-string', 'E1302': 'mixed-format-string', 'E1303': 'format-needs-mapping', 'E1304': 'missing-format-string-key', 'E1305': 'too-many-format-args', 'E1306': 'too-few-format-args', 'E1310': 'bad-str-strip-call', 'E1507': 'invalid-envvar-value', 'E1601': 'print-statement', 'E1602': 'parameter-unpacking', 'E1603': 'unpacking-in-except', 'E1604': 'old-raise-syntax', 'E1605': 'backtick', 'E1700': 'yield-inside-async-function', 'E1701': 'not-async-context-manager', 'F0001': 'fatal', 'F0002': 'astroid-error', 'F0010': 'parse-error', 'F0202': 'method-check-failed', 'I0001': 'raw-checker-failed', 'I0010': 'bad-inline-option', 'I0011': 'locally-disabled', 'I0012': 'locally-enabled', 'I0013': 'file-ignored', 'I0020': 'suppressed-message', 'I0021': 'useless-suppression', 'I0022': 'deprecated-pragma', 'I0023': 'use-symbolic-message-instead', 'I1101': 'c-extension-no-member', 'R0123': 'literal-comparison', 'R0124': 'comparison-with-itself', 'R0201': 'no-self-use', 'R0202': 'no-classmethod-decorator', 'R0203': 'no-staticmethod-decorator', 'R0205': 'useless-object-inheritance', 'R0401': 'cyclic-import', 'R0801': 'duplicate-code', 'R0901': 'too-many-ancestors', 'R0902': 'too-many-instance-attributes', 'R0903': 'too-few-public-methods', 'R0904': 'too-many-public-methods', 'R0911': 'too-many-return-statements', 'R0912': 'too-many-branches', 'R0913': 'too-many-arguments', 'R0914': 'too-many-locals', 'R0915': 'too-many-statements', 'R0916': 'too-many-boolean-expressions', 'R1701': 'consider-merging-isinstance', 'R1702': 'too-many-nested-blocks', 'R1703': 'simplifiable-if-statement', 'R1704': 'redefined-argument-from-local', 'R1705': 'no-else-return', 'R1706': 'consider-using-ternary', 'R1707': 'trailing-comma-tuple', 'R1708': 'stop-iteration-return', 'R1709': 'simplify-boolean-expression', 'R1710': 'inconsistent-return-statements', 'R1711': 'useless-return', 'R1712': 'consider-swap-variables', 'R1713': 'consider-using-join', 'R1714': 'consider-using-in', 'R1715': 'consider-using-get', 'R1716': 'chained-comparison', 'R1717': 'consider-using-dict-comprehension', 'R1718': 'consider-using-set-comprehension', 'W0101': 'unreachable', 'W0102': 'dangerous-default-value', 'W0104': 'pointless-statement', 'W0105': 'pointless-string-statement', 'W0106': 'expression-not-assigned', 'W0107': 'unnecessary-pass', 'W0108': 'unnecessary-lambda', 'W0109': 'duplicate-key', 'W0111': 'assign-to-new-keyword', 'W0120': 'useless-else-on-loop', 'W0122': 'exec-used', 'W0123': 'eval-used', 'W0124': 'confusing-with-statement', 'W0125': 'using-constant-test', 'W0143': 'comparison-with-callable', 'W0150': 'lost-exception', 'W0199': 'assert-on-tuple', 'W0201': 'attribute-defined-outside-init', 'W0211': 'bad-staticmethod-argument', 'W0212': 'protected-access', 'W0221': 'arguments-differ', 'W0222': 'signature-differs', 'W0223': 'abstract-method', 'W0231': 'super-init-not-called', 'W0232': 'no-init', 'W0233': 'non-parent-init-called', 'W0235': 'useless-super-delegation', 'W0301': 'unnecessary-semicolon', 'W0311': 'bad-indentation', 'W0312': 'mixed-indentation', 'W0401': 'wildcard-import', 'W0402': 'deprecated-module', 'W0404': 'reimported', 'W0406': 'import-self', 'W0410': 'misplaced-future', 'W0511': 'fixme', 'W0601': 'global-variable-undefined', 'W0602': 'global-variable-not-assigned', 'W0603': 'global-statement', 'W0604': 'global-at-module-level', 'W0611': 'unused-import', 'W0612': 'unused-variable', 'W0613': 'unused-argument', 'W0614': 'unused-wildcard-import', 'W0621': 'redefined-outer-name', 'W0622': 'redefined-builtin', 'W0623': 'redefine-in-handler', 'W0631': 'undefined-loop-variable', 'W0640': 'cell-var-from-loop', 'W0641': 'possibly-unused-variable', 'W0642': 'self-cls-assignment', 'W0702': 'bare-except', 'W0703': 'broad-except', 'W0705': 'duplicate-except', 'W0706': 'try-except-raise', 'W0711': 'binary-op-exception', 'W0715': 'raising-format-tuple', 'W1113': 'keyword-arg-before-vararg', 'W1201': 'logging-not-lazy', 'W1202': 'logging-format-interpolation', 'W1203': 'logging-fstring-interpolation', 'W1300': 'bad-format-string-key', 'W1301': 'unused-format-string-key', 'W1302': 'bad-format-string', 'W1303': 'missing-format-argument-key', 'W1304': 'unused-format-string-argument', 'W1305': 'format-combined-specification', 'W1306': 'missing-format-attribute', 'W1307': 'invalid-format-index', 'W1401': 'anomalous-backslash-in-string', 'W1402': 'anomalous-unicode-escape-in-string', 'W1501': 'bad-open-mode', 'W1503': 'redundant-unittest-assert', 'W1505': 'deprecated-method', 'W1506': 'bad-thread-instantiation', 'W1507': 'shallow-copy-environ', 'W1508': 'invalid-envvar-default', 'W1509': 'subprocess-popen-preexec-fn', 'W1601': 'apply-builtin', 'W1602': 'basestring-builtin', 'W1603': 'buffer-builtin', 'W1604': 'cmp-builtin', 'W1605': 'coerce-builtin', 'W1606': 'execfile-builtin', 'W1607': 'file-builtin', 'W1608': 'long-builtin', 'W1610': 'reduce-builtin', 'W1611': 'standarderror-builtin', 'W1612': 'unicode-builtin', 'W1613': 'xrange-builtin', 'W1614': 'coerce-method', 'W1615': 'delslice-method', 'W1616': 'getslice-method', 'W1617': 'setslice-method', 'W1618': 'no-absolute-import', 'W1619': 'old-division', 'W1620': 'dict-iter-method', 'W1621': 'dict-view-method', 'W1622': 'next-method-called', 'W1623': 'metaclass-assignment', 'W1624': 'indexing-exception', 'W1625': 'raising-string', 'W1626': 'reload-builtin', 'W1627': 'oct-method', 'W1628': 'hex-method', 'W1629': 'nonzero-method', 'W1630': 'cmp-method', 'W1632': 'input-builtin', 'W1633': 'round-builtin', 'W1634': 'intern-builtin', 'W1635': 'unichr-builtin', 'W1636': 'map-builtin-not-iterating', 'W1637': 'zip-builtin-not-iterating', 'W1638': 'range-builtin-not-iterating', 'W1639': 'filter-builtin-not-iterating', 'W1640': 'using-cmp-argument', 'W1641': 'eq-without-hash', 'W1642': 'div-method', 'W1643': 'idiv-method', 'W1644': 'rdiv-method', 'W1645': 'exception-message-attribute', 'W1646': 'invalid-str-codec', 'W1647': 'sys-max-int', 'W1649': 'deprecated-string-function', 'W1650': 'deprecated-str-translate-call', 'W1651': 'deprecated-itertools-function', 'W1652': 'deprecated-types-field', 'W1653': 'next-method-defined', 'W1654': 'dict-items-not-iterating', 'W1655': 'dict-keys-not-iterating', 'W1656': 'dict-values-not-iterating', 'W1657': 'deprecated-operator-function', 'W1658': 'deprecated-urllib-function', 'W1659': 'xreadlines-attribute', 'W1660': 'deprecated-sys-function', 'W1661': 'exception-escape', 'W1662': 'comprehension-escape', } if __name__ == '__main__': print(PYLINT_MAP.get(sys.argv[1].upper()))<|endoftext|>import torch import torch.nn as nn class FocalLoss_Ori(nn.Module): """ This is a implementation of Focal Loss with smooth label cross entropy supported which is proposed in 'Focal Loss for Dense Object Detection. ( [IDX] Focal_Loss= -1*alpha*(1-pt)*log(pt) :param num_class: :param alpha: (tensor) 3D or 4D the scalar factor for this criterion :param gamma: (float,double) gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putting more focus on hard misclassified example :param smooth: (float,double) smooth value when cross entropy :param size_average: (bool, optional) By default, the losses are averaged over each loss element in the batch. """ def __init__(self, num_class, alpha=[0.25, 0.75], gamma=2, balance_index=-1, size_average=True): super(FocalLoss_Ori, self).__init__() self.alpha = alpha self.gamma = gamma self.eps = 1e-6 if isinstance(self.alpha, (list, tuple)): assert len(self.alpha) == self.num_class self.alpha = torch.Tensor(list(self.alpha)) elif isinstance(self.alpha, (float, int)): assert 0 < self.alpha < 1.0, 'alpha should be in `(0,1)`)' assert balance_index > -1 alpha = torch.ones((self.num_class)) alpha *= 1 - self.alpha alpha[balance_index] = self.alpha self.alpha = alpha elif isinstance(self.alpha, torch.Tensor): self.alpha = self.alpha else: raise TypeError('Not support alpha type, expect `int|float|list|tuple|torch.Tensor`') """ logit: softmax scores (N, K+1) target: integeral labels (N, 1) \in [0,...,K] """ if logit.dim() > 2: target = target.view(-1, 1) # [N,d1,d2,...]->[N*d1*d2*...,1] # -----------legacy way------------ # idx = target.cpu().long() # one_hot_key = torch.FloatTensor(target.size(0), self.num_class).zero_() # one_hot_key = one_hot_key.scatter_(1, idx, 1) # if one_hot_key.device != logit.device: # one_hot_key = one_hot_key.to(logit.device) # pt = (one_hot_key * logit).sum(1) + epsilon # ----------memory saving way-------- pt = logit.gather(1, target).view(-1) + self.eps # avoid apply logpt = pt.log() if self.alpha.device != logpt.device: self.alpha = self.alpha.to(logpt.device) alpha_class = self.alpha.gather(0, target.view(-1)) logpt = alpha_class * logpt loss = -1 * torch.pow(torch.sub(1.0, pt), self.gamma) * logpt if self.size_average: else: loss = loss.sum() return loss class EvidenceLoss(nn.Module): def __init__(self, num_cls, cfg, size_average=False): super(EvidenceLoss, self).__init__() self.num_cls = num_cls self.loss_type = cfg['loss_type'] self.evidence = cfg['evidence'] self.iou_aware = cfg['iou_aware'] if 'iou_aware' in cfg else False self.with_ghm = cfg['with_ghm'] if 'with_ghm' in cfg else False self.with_ibm = cfg['with_ibm'] if 'with_ibm' in cfg else False self.eps = 1e-10 if self.with_ghm: self.num_bins = cfg['num_bins'] self.momentum = cfg['momentum'] self.ghm_start = cfg['ghm_start'] if 'ghm_start' in cfg else 0 self.edges = [float(x) / self.num_bins for x in range(self.num_bins+1)] self.edges[-1] += 1e-6 if self.momentum > 0: self.acc_sum = [0.0 for _ in range(self.num_bins)] if self.with_ibm: self.ibm_start = cfg['ibm_start'] if 'ibm_start' in cfg else 0 self.coeff = cfg['ibm_coeff'] if 'ibm_coeff' in cfg else 10 self.epoch, self.total_epoch = 0, 25 def iou_calib(self, logits, ious, mean=False): """ logit, shape=(N, K) ious, shape=(N) """ ious[ious < 0] = 1e-3 pred_alpha = self.evidence_func(logits) + 1 # (alpha = e + 1) uncertainty = self.num_cls / pred_alpha.sum(dim=-1) # (N,) iou_reg = - ious * torch.log(1-uncertainty) - (1-ious) * torch.log(uncertainty) iou_reg = torch.mean(iou_reg) if mean else torch.sum(iou_reg) return iou_reg """ logit, shape=(N, K+1) target, shape=(N, 1) """ if logit.dim() > 2: target = target.view(-1) # [N,d1,d2,...]->[N*d1*d2*...,] out_dict = dict() # one-hot embedding for the target y = torch.eye(self.num_cls).to(logit.device, non_blocking=True) y = y[target] # (N, K+1) # get loss func loss, func = self.get_loss_func() # L_1 norm of feature feat_norm = torch.sum(torch.abs(logit), 1).reshape(-1) if self.with_ibm else None # compute losses pred_alpha = self.evidence_func(logit) + 1 # (alpha = e + 1) loss_out = loss(y, pred_alpha, func=func, target=target, feat_norm=feat_norm) out_dict.update(loss_out) # accumulate total loss total_loss = 0 for k, v in loss_out.items(): if 'loss' in k: total_loss += v out_dict.update({'total_loss': total_loss}) return total_loss def get_loss_func(self): if self.loss_type == 'mse': return self.mse_loss, None elif self.loss_type == 'log': return self.edl_loss, torch.log elif self.loss_type == 'digamma': return self.edl_loss, torch.digamma else: def evidence_func(self, logit): if self.evidence == 'relu': return F.relu(logit) if self.evidence == 'exp': return torch.exp(torch.clamp(logit, -10, 10)) if self.evidence == 'softplus': return F.softplus(logit) def mse_loss(self, y, alpha, func=None, target=None, feat_norm=None): """Used only for loss_type == 'mse' """ losses = {} # compute loss by considering the temporal penalty loglikelihood_err, loglikelihood_var = self.loglikelihood_loss(y, alpha) if self.size_average: loglikelihood_err = torch.mean(loglikelihood_err) loglikelihood_var = torch.mean(loglikelihood_var) else: loglikelihood_err = torch.sum(loglikelihood_err) loglikelihood_var = torch.sum(loglikelihood_var) losses.update({'cls_loss': loglikelihood_err, 'var_loss': loglikelihood_var}) return losses def edl_loss(self, y, alpha, func=torch.log, target=None, feat_norm=None): """Used for both loss_type == 'log' and loss_type == 'digamma' func: function handler (torch.log, or torch.digamma) """ losses = {} S = torch.sum(alpha, dim=1, keepdim=True) # (B, 1) if self.with_ghm and self.epoch >= self.ghm_start: # gradient length grad_norm = torch.abs(1 / alpha_pred - uncertainty) * y # y_ij * (1/alpha_ij - u_i) n = 0 # n valid bins weights = torch.zeros_like(alpha) for i in range(self.num_bins): inds = (grad_norm >= self.edges[i]) & (grad_norm < self.edges[i+1]) num_in_bin = inds.sum().item() if num_in_bin > 0: self.acc_sum[i] = self.momentum * self.acc_sum[i] \ + (1 - self.momentum) * num_in_bin weights[inds] = 1.0 / self.acc_sum[i] else: weights[inds] = 1.0 / num_in_bin n += 1 if n > 0: weights = weights / n cls_loss = torch.sum(y * weights * (func(S) - func(alpha)), dim=1) elif self.with_ibm and self.epoch >= self.ibm_start: grad_norm = torch.sum(torch.abs(1 / alpha_pred - uncertainty) * y, dim=1) # sum_j|y_ij * (1/alpha_ij - u_i)|, (N) weights = 1.0 / (feat_norm * torch.exp(self.coeff * grad_norm) + self.eps) # influence-balanced weight cls_loss = weights * torch.sum(y * (func(S) - func(alpha)), dim=1) else: cls_loss = torch.sum(y * (func(S) - func(alpha)), dim=1) if self.size_average: cls_loss = torch.mean(cls_loss) else: cls_loss = torch.sum(cls_loss) losses.update({'cls_loss': cls_loss}) return losses def loglikelihood_loss(self, y, alpha): S = torch.sum(alpha, dim=1, keepdim=True) loglikelihood_err = torch.sum((y - (alpha / S)) ** 2, dim=1, keepdim=True) loglikelihood_var = torch.sum(alpha * (S - alpha) / (S * S * (S + 1)), dim=1, keepdim=True) return loglikelihood_err, loglikelihood_var class ActionnessLoss(nn.Module): def __init__(self, size_average=False, weight=0.1, margin=1.0): super(ActionnessLoss, self).__init__() self.weight = weight self.margin = margin """ logit, shape=(N, 1), unbounded logits target, shape=(N, 1) bianry values """ if logit.dim() > 2: label = target.view(-1) # [N,d1,d2,...]->[N*d1*d2*...,] pred = logit.view(-1) if logit.size(-1) == 1 else logit # split the predictions into positive and negative setss pos_pred, pos_label = pred[label > 0], label[label > 0] neg_pred, neg_label = pred[label == 0], label[label == 0] num_pos = pos_pred.numel() num_neg = neg_pred.numel() topM = min(num_pos, num_neg) - 1 # reserve one for rank loss if topM > 0: # both pos and neg sets have at least 2 samples _, inds = neg_pred.sort() # by default, it is ascending sort # select the top-M negatives neg_clean_pred = neg_pred[inds[:topM]] neg_clean_label = neg_label[inds[:topM]] pred = torch.cat((pos_pred, neg_clean_pred), dim=0) label = torch.cat((pos_label, neg_clean_label), dim=0) num_neg = topM # compute BCE loss reduction = 'mean' if self.size_average else 'sum' loss_bce = F.binary_cross_entropy_with_logits(pred, label, reduction=reduction) # compute rank loss loss_rank = 0 if topM > 0: neg_noisy_pred, _ = torch.max(neg_pred, dim=0) pos_clean_pred, _ = torch.max(pos_pred, dim=0) loss_rank = torch.maximum(torch.tensor(0.0).to(pred.device), self.margin - neg_noisy_pred + pos_clean_pred.detach()) loss_total = loss_bce + self.weight * loss_rank return loss_total, num_pos + num_neg
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9904.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-9904.jsonl"}]
Colon for 'because' omission? Question: Colon or semicolon when because is omitted from a sentence e.g., I am sorry I disturbed you (;) (:) (because) it looked like you were having a lot of fun there. Because explains and clarifies a preceding clause so would it be correct to use a colon preceding the explanatory clause if because is omitted? Alternatively, because can be replaced by for, which is a coordinating conjunction and would correctly be punctuated with a semicolon. I am sorry I disturbed you, for it looked like you were having a lot of fun there. I am sorry I disturbed you; it looked like you were having a lot of fun there. For is of course reasonably archaic but is useful sometimes for grammatical clarity. And if anyone wants to comment on the that omission and comma replacement, I'd be very happy. I am sorry (that)(,) I disturbed you because it looked like you were having a lot of fun there. Answer: There's a lot here. Okay... For your first question, a semicolon is best fitting. Using a colon makes for a much more rigid construction and wholly levies blame onto yourself for the change in the recipient's mood. The semicolon allows a looser connection between the decline in the mood of the recipient and the actions you took to (potentially) induce unhappiness. A colon forges a very solid link between two clauses. You can't use a comma in your last sentence. That would create a comma splice as there are two main clauses either side of it. A semicolon would work here. You can omit "that" because we often cut out words that add no meaning to a sentence. "That" merely serves as a conjunction which sets up a clause that expresses some reason [for you being sorry].<|endoftext|>Running cmd /c from PowerShell with spaces in filepath Question: I am trying to run the following command in PowerShell <code>PS C:\Users\Administrator> cmd /c "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\Tools\vsdevcmd.bat && nuget restore && msbuild mywebapp.sln /p:DeployOnBuild=true /p:PublishedProfile=ServerFolderProfile" </code> This produces the error <code>'C:\Program' is not recognized as an internal or external command. </code> My paths have spaces and I'm running several commands seperated by && which is messing everything up. I have tried putting quotes all over the place but I can't get it to work. If i run just the first part of the command <code>cmd /c "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\Tools\vsdevcmd.bat" </code> it works fine. But I can't get the other commands to work too. Answer: According to the docs for <code>cmd.exe</code>: If <code>/C</code> or <code>/K</code> is specified, then the remainder of the command line is processed as an immediate command in the new shell. Multiple commands separated by the command separator <code>&</code> or <code>&&</code> are accepted if surrounded by quotes So I just had to change my command to: <code>PS C:\Users\Administrator> cmd /c "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\Tools\vsdevcmd.bat" "&&" nuget restore "&&" msbuild mywebapp.sln /p:DeployOnBuild=true /p:PublishedProfile=ServerFolderProfile </code> Comment: @AdamParsons When I try I get a message that says I have to wait until tomorrow. So I will do it then. Comment: You should flag your answer as the answer to this question so that it is not left 'unanswered' - if you can.<|endoftext|>Bitrix, изменение разделов товара sql запросом Question: В битриксе необходимо массово удалить товары из определенного раздела. С помощью sql запроса: <code>delete from b_iblock_section_element where IBLOCK_SECTION_ID=413 and IBLOCK_ELEMENT_ID in ("5643","5644","5645","5646") </code> удаляю товары из раздела. Если заходить в эти товары в админке, то видно, что товары удалены из этого раздела, но в паблике они по прежнему отображаются в этом разделе. Если же в админке зайти в эти товары и нажать сохранить, то и в паблике они удаляются из раздела. Пробовал обновить поле timestamp_x в таблице b_iblock_element, но это тоже не сработало. <code>update b_iblock_element set TIMESTAMP_X="2017-08-30 19:00:00" where id in ("5643","5644","5645","5646") </code> Можно ли с помощью sql сделать аналог нажатия на кнопку сохранить в товаре? Answer: Это очень дурная практика. Для любой CMS. Прямая работа с БД это плохо. Битрикс кеширует очень многое, чтобы обеспечить быстродействие. Когда вы выполняете такой запрос система ни чего об этом не знает и не сбрасывает кеш. Кроме того, вы нарушаете логику, потом кто-то решит на вашем проекте подвязаться на событие изменения разделов у товара и оно будет работать не правильно. Кроме того,не зная структуры вы можете нарушить связанность данных. В вашем случае сбросьте в админке весь кеш на странице Автокеширование. Старайтесь так не делать, а использовать функционал АПИ Comment: в таблице b_iblock_element есть поле IBLOCK_SECTION_ID это основной раздел. Возможно у этих товаров 413 был основным Comment: На странице Автокеширование, на закладке "Очистка файлов кеша" - выбрал Все и нажал Начать. Ничего не изменилось, в паблике товары по прежнему отображаются<|endoftext|>html and swf swapping (display html while swf file loads to 100%) Question: This is what I want to achieve. While the swf file is loading, wrapper div displays an html content (e.g. text content). When the swf file has loaded 100%, it replaces the text content within the wrapper div, and then plays within the wrapper div. When the swf file is finished playing, it is then replaced with the previous text content. (This is more like html to swf to html swapping within a div) any thoughts if this is possible or any other workarounds? Much appreciated to anyone who could share. Answer: The easiest way to do this is call your div-swapping function from ActionScript in your movie. You can call is when the movie is 100% loaded and then again from the "last frame" of the movie, so you'd be getting the flash movie to say "show me" and then later "hide me". Answer: Have the HTML and Flash in one div. Since you can't hide a SWF. This trick is to shove it off screen: <code><div id="wrapper"> <div id="flashWrapper" style="position:relative; left:-2000px;"> <object>flash embed code</object> </div> <div id="loading">Flash is loading...</div> </div> </code> It's more fool-proof to have the SWF call a JS function with the ExternalInterface when it's finished. But you can check it via JS: <code><script> var v = setInterval(function(){ if(flashMovie.PercentLoaded() == 100){ document.getElementById("flashWrapper").style.left = "0px"; document.getElementById("loading").style.display = "none"; clearInterval(v); } }); </script> </code> If you are inserting the SWF dynamically be sure to wait a millisecond before accessing it.<|endoftext|>Image placement within a set page-wrap? Question: I was wondering if it is possible to set up the page-wrap in a way so that the width is the maximum limitation to how the images and text boxes can float and left/right/top/bottom commands. below is an image that clarifies my question because my coding vocabulary is very limited at the moment: Thank you in advance! Answer: Take a look here: [IDX] { background-color: gray; width: 100%; height: 100%; } #wrapper { width: 80%; height: 800px; margin-left: auto; margin-right: auto; background-color: white; max-width: 48em; } #red { height: 100px; width: 100px; background-color: red; float:left; margin-top: 70%; } #blu { height: 100px; width: 100px; background-color: blue; float:right; margin-top: 40%; margin-right: 5%; } </code> or, if you want use position property instead of float: [IDX] { background-color: gray; width: 100%; height: 100%; } #wrapper { width: 80%; height: 800px; margin-left: auto; margin-right: auto; background-color: white; max-width: 48em; position: relative; } #wrapper > div { position: absolute; } #red { height: 100px; width: 100px; background-color: red; bottom: 20%; } #blu { height: 100px; width: 100px; background-color: blue; top: 40%; right: 5%; } </code> Comment: Hi @KaMZaTa, thank you for your comment. However, I'm wondering if it is possible to work with an absolute image placement. For example, bottom:0 and right:0; for an image that is within a 80% wide and 100% high page-wrapper... I am not really looking for a solution that consists of the use of: float:right/left.<|endoftext|>Is it possible to create that query using Spring Data with mongoDB? Question: like in question is it possible to create that query? <code>db.persons.find({ 'oi': '5f2417e3c655cb13e85186df', 'ch': { $elemMatch: { 'type': { $in: ['MAN'] }}}}, {'ch.$': 1}) </code> The last part of this query is problematic. How to retrive fields that pass the $elemMatch predicate only. Spring data @Query annotation have field property but if specify it by <code>{'children: 1'}</code> I retrive all children instead of this which pass the query. <code>{ 'children.$': 1}</code> doesn't work of course. Answer: You can use <code>@Query</code> annotation. Pass the query in value and projection in fields inside <code>@Query</code> annotation like this <code>@Query(value = "{ 'oi': ?0, 'ch': { $elemMatch: { 'type': { $in: ?1 }}}}", fields = "{'ch.$' : 1}") Person findPersonCustom(String id, List<String> types); </code> Here <code>?0</code> & <code>?1</code> will be passed as method arguments 0 & 1 respectively. You can also put that values inside <code>@Query</code> directly if they are static. The resulted <code>Person</code> object will contain only matched elements from <code>ch</code> array. Comment: That is not true. It will contains all array. Comment: It actually works, I am using spring boot 2.1.5 with mongodb 4.0 and it works. There may be something wrong with code or field names. Can you post the code with which you have tried? Comment: also turn on logging to see query using `logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG` Comment: Are you sure that it is possible to pass positional operator to fields value ? Comment: Yes I am sure as I have used these type of queries in my project and it works
[{"idx": "Colon_for_'because'_omission?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-20383.jsonl"}, {"idx": "Running_cmd_/c_from_PowerShell_with_spaces_in_filepath", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-20383.jsonl"}, {"idx": "Bitrix,_\u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u0435_\u0440\u0430\u0437\u0434\u0435\u043b\u043e\u0432_\u0442\u043e\u0432\u0430\u0440\u0430_sql_\u0437\u0430\u043f\u0440\u043e\u0441\u043e\u043c", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-20383.jsonl"}, {"idx": "html_and_swf_swapping_(display_html_while_swf_file_loads_to_100%)", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-20383.jsonl"}, {"idx": "Image_placement_within_a_set_page-wrap?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-20383.jsonl"}, {"idx": "Is_it_possible_to_create_that_query_using_Spring_Data_with_mongoDB?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-20383.jsonl"}]
import { ERC1404Base } from '../../../typechain'; import { describeBehaviorOfERC20Base } from '../ERC20'; import { describeFilter } from '@solidstate/library'; import { expect } from 'chai'; import { BigNumber, ContractTransaction } from 'ethers'; import { ethers } from 'hardhat'; interface ERC1404BaseBehaviorArgs { deploy: () => Promise<ERC1404Base>; restrictions: any; mint: (address: string, amount: BigNumber) => Promise<ContractTransaction>; burn: (address: string, amount: BigNumber) => Promise<ContractTransaction>; supply: BigNumber; } export function describeBehaviorOfERC1404Base( { deploy, restrictions, mint, burn, supply }: ERC1404BaseBehaviorArgs, skips?: string[], ) { const describe = describeFilter(skips); describe('::ERC1404Base', function () { let instance: ERC1404Base; beforeEach(async function () { instance = await deploy(); }); describeBehaviorOfERC20Base( { deploy, supply, mint, burn, }, skips, ); // TODO: transfers blocked if restriction exists describe('#detectTransferRestriction(address,address,uint256)', function () { it('returns zero if no restriction exists', async function () { expect( await instance.callStatic.detectTransferRestriction( ethers.constants.AddressZero, ethers.constants.AddressZero, ethers.constants.One, ), ).to.equal(0); }); }); describe('#messageForTransferRestriction(uint8)', function () { it('returns empty string for unknown restriction code', async function () { expect( await instance.callStatic.messageForTransferRestriction(255), ).to.equal(''); }); for (let restriction of restrictions) { it(`returns "${restriction.message}" for code ${restriction.code}`, async function () { expect( await instance.callStatic.messageForTransferRestriction( restriction.code, ), ).to.equal(restriction.message); }); } }); }); }<|endoftext|>import React from 'react'; import {Color} from 'app/utils/theme'; import HttpRenderer from 'app/components/events/interfaces/breadcrumbs/ httpRenderer'; import ErrorRenderer from 'app/components/events/interfaces/breadcrumbs/errorRenderer'; import DefaultRenderer from 'app/components/events/interfaces/breadcrumbs/defaultRenderer'; import { IconInfo, IconLocation, IconRefresh, IconTerminal, IconUser, IconWarning, } from 'app/icons'; import {Breadcrumb, BreadcrumbType} from './types'; type Output = { color: Color; borderColor: Color; icon: React.ReactElement; renderer: React.ReactElement; }; function getBreadcrumbDetails(breadcrumb: Breadcrumb): Partial<Output> { switch (breadcrumb.type) { case BreadcrumbType.USER: case BreadcrumbType.UI: { return { color: 'purple', icon: <IconUser />, renderer: <DefaultRenderer breadcrumb={breadcrumb} />, }; } case BreadcrumbType.NAVIGATION: { return { color: 'blue400', icon: <IconLocation />, renderer: <DefaultRenderer breadcrumb={breadcrumb} />, }; } case BreadcrumbType.INFO: { return { color: 'blue400', icon: <IconInfo />, renderer: <DefaultRenderer breadcrumb={breadcrumb} />, }; } case BreadcrumbType.WARNING: { return { color: 'orange300', borderColor: 'orange500', icon: <IconWarning />, renderer: <ErrorRenderer breadcrumb={breadcrumb} />, }; } case BreadcrumbType.EXCEPTION: case BreadcrumbType.MESSAGE: case BreadcrumbType.ERROR: { return { color: 'red', icon: <IconWarning />, renderer: <ErrorRenderer breadcrumb={breadcrumb} />, }; } case BreadcrumbType.HTTP: { return { color: 'green400', icon: <IconRefresh />, renderer: <HttpRenderer breadcrumb={breadcrumb} />, }; } default: return { icon: <IconTerminal />, renderer: <DefaultRenderer breadcrumb={breadcrumb} />, }; } } export default getBreadcrumbDetails;<|endoftext|>* Read about DevExtreme licensing here: [IDX] BaseSparkline, { BaseSparklineOptions } from './sparklines/base_sparkline'; /** * Warning! This type is used for internal purposes. Do not import it directly. */ export interface dxBulletOptions extends BaseSparklineOptions<dxBullet> { /** * Specifies a color for the bullet bar. */ color?: string; /** * Specifies an end value for the invisible scale. */ endScaleValue?: number; /** * Specifies whether or not to show the target line. */ showTarget?: boolean; /** * Specifies whether or not to show the line indicating zero on the invisible scale. */ showZeroLevel?: boolean; /** * Specifies a start value for the invisible scale. */ startScaleValue?: number; /** * Specifies the value indicated by the target line. */ target?: number; /** * Specifies a color for both the target and zero level lines. */ targetColor?: string; /** * Specifies the width of the target line. */ targetWidth?: number; /** * Specifies the primary value indicated by the bullet bar. */ value?: number; } /** * The Bullet widget is useful when you need to compare a single measure to a target value. The widget comprises a horizontal bar indicating the measure and a vertical line indicating the target value. */ export default class dxBullet extends BaseSparkline { constructor(element: Element, options?: dxBulletOptions) constructor(element: JQuery, options?: dxBulletOptions) } declare global { interface JQuery { dxBullet(): JQuery; dxBullet(options: "instance"): dxBullet; dxBullet(options: string): any; dxBullet(options: string, ...params: any[]): any; dxBullet(options: dxBulletOptions): JQuery; } } /** * Warning! This type is used for internal purposes. Do not import it directly. */ export type Options = dxBulletOptions; /** @deprecated use Options instead */ /** * Warning! This type is used for internal purposes. Do not import it directly. */ export type IOptions = dxBulletOptions;<|endoftext|>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; // Test App import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HomeComponent } from './views/home/home.component'; import { LoginComponent } from './views/login/login.component'; // RnAngularCore import { AppendTokenInterceptor, ErrorInterceptor, RnAngularCoreModule, RnAppConfig, RnCoreComponent, RnCoreService, RnDefaultAppConfig, RN_APP_CONFIG, SessionTokenInterceptor, ShortcutsService } from 'src/lib/public_api'; import { HTTP_INTERCEPTORS } from '@angular/common/ http'; const appConfig: RnAppConfig = { ...RnDefaultAppConfig, apiBaseUrl: '', appName: 'Demo App', appVersion: '1.0.1', auth: { ...RnDefaultAppConfig.auth, storageTokenName: 'rnCore.userToken', storageUserInfo: 'rnCore.userInfo' }, logger: { ...RnDefaultAppConfig.logger, disabledInstances: [ RnCoreComponent.Breadcrumbs, RnCoreComponent.Header, RnCoreComponent.Shortcuts, RnCoreComponent.SideNav, RnCoreService.Auth, RnCoreService.Shortcuts, RnCoreService.Storage, RnCoreService.UI ] } }; @NgModule({ declarations: [ AppComponent, HomeComponent, LoginComponent ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, RnAngularCoreModule, ], providers: [ { provide: RN_APP_CONFIG, useValue: appConfig }, { provide: HTTP_INTERCEPTORS, useClass: AppendTokenInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: SessionTokenInterceptor, multi: true }, ], bootstrap: [AppComponent] }) export class AppModule { constructor( private _shortcuts: ShortcutsService ) { this._shortcuts.addHomeShortcut({ icon: 'home', title: 'Testing', actions: [ { title: 'Edit', routerLink: [''] } ] }); } }<|endoftext|>import { DMetadata } from "./metadata" /** * Optionally configurable rules for game mechanics, unit availability, economics, etc. */ export interface DRules { /** * The normal, maximum size of a single army-group on a single map tile. */ armyGroupSizeMax: number /** * After all health modifications are considered, cap the maximum effective health of an army at this value. */ armyHealthMax: number /** * After all health modifications are considered, prevent the minimum effective health of an army from falling below this value. */ armyHealthMin: number /** * After all health modifications are considered, cap the maximum effective health of an army at this value. */ armyHealthModifierMax: number /** * After all health modifications are considered, prevent the minimum effective health of an army from falling below this value. */ armyHealthModifierMin: number /** * After all bonuses are considered, cap the effective strength of an army at this value. It should be at least one less than the maximum value rolled by a battle dice. */ armyStrengthMax: number /** * After all strength modifications are considered, provide a floor for the effective strength below which an army unit won't fall. */ armyStrengthMin: number /** * The maximum positive bonus of external modifications that can be applied to an army's strength. */ armyStrengthModifierMax: number /** * The minimum negative malus of external modifications that can be applied to an army's strength. */ armyStrengthModifierMin: number /** * The number of sides available on the standard battle dice. */ battleDiceNumFaces: number /** * Human friendly documentation that can be stored with the (human unfriendly) JSON. For optimized systems, this attribute should be pruned at run time. */ documentation: string /** * Maximum number of heroes each empire is allowed to have at any one time. */ heroesMax: number metadata: DMetadata /** * Unique name for this set of rules. */ name: string /** * duck typing */ type: "rules" }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3311.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3311.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3311.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3311.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3311.jsonl"}]
#!/usr/bin/env python import json, time from flask import Flask, request, render_template, Response from gevent import pywsgi, monkey from helpers.generateCalibration import GenerateCalibration #monkey.patch_all() app = Flask(__name__) #cameraInstance = Camera() runCalibration = GenerateCalibration('frames', 'calibration.json') class VisionServer: def __init__(self, queue): self.inQueue = queue @app.route('/') def index(): @app.route('/hsl') def hslPage(): return render_template('hsl.html') @app.route('/calibrate') def calibratePage(): return render_template('calibrate.html') def genStream(camera): while True: b'Content-Type: image/jpeg\r\n\r\n' + camera.get_frame() + b'\r\n') time.sleep(0.005) # yes, this delay is intentional. # maybe it's a hack, but hey, it works. @app.route('/stream') def stream(): return Response(genStream(cameraInstance), mimetype='multipart/x-mixed-replace; boundary=frame') def post(): if (request.form['action'] == 'changeHSL'): cameraInstance.changeHSL({'component': request.form['component'], 'min': request.form['min'], 'max': request.form['max']}) elif (request.form['action'] == 'getHSL'): return json.dumps(cameraInstance.getHSL()) elif (request.form['action'] == 'saveHSL'): return str(cameraInstance.saveHSL()) elif (request.form['action'] == 'setExposure'): return str(cameraInstance.setExposure(int(request.form['exposure']))) elif (request.form['action'] == 'on' or request.form['action'] == 'off'): if (request.form['action'] == 'on'): visionController.start() else: visionController.stop() return str(True); return str(True) @app.route('/capture') def capture(): # makes directory if it doesn't exist if not os.path.exists('frames'): os.makedirs('frames') # finds the highest int in filenames maxN = 0 if (os.listdir('frames')): files = os.listdir('frames') for file in files: this = file.split('.')[0] if (this != ''): if (int(this) > maxN): maxN = int(this) return str(cameraInstance.saveFrame('frames/' + str(maxN + 1) + '.jpg')) @app.route('/calibrate') def calibrate(): return str(runCalibration.run()) if __name__ == '__main__': gevent_server = pywsgi.WSGIServer(('', 80), app) gevent_server.serve_forever()<|endoftext|>import unittest import numpy as np from test.common import QiskitAquaTestCase from qiskit_aqua import run_algorithm, get_algorithm_instance from qiskit_aqua.input import get_input_instance class TestSVMQKernel(QiskitAquaTestCase): def setUp(self): self.random_seed = 10598 self.training_data = {'A': np.asarray([[2.95309709, 2.51327412], [3.14159265, 4.08407045]]), 'B': np.asarray([[4.08407045, 2.26194671], [4.46106157, 2.38761042]])} self.testing_data = {'A': np.asarray([[3.83274304, 2.45044227]]), 'B': np.asarray([[3.89557489, 0.31415927]])} self.ref_kernel_matrix_training = np.asarray([[1., 0.84277344, 0.12109375, 0.37011719], [0.84277344, 1., 0.10742188, 0.44042969], [0.12109375, 0.10742188, 1., 0.6484375], [0.37011719, 0.44042969, 0.6484375, 1.]]) self.ref_kernel_matrix_testing = np.asarray([[0.12988281, 0.15820312, 0.45996094, 0.14648438], [0.33300781, 0.38085938, 0.01660156, 0.1484375]]) self.ref_support_vectors = np.asarray([[2.95309709, 2.51327412], [3.14159265, 4.08407045], [4.08407045, 2.26194671], [4.46106157, 2.38761042]]) self.ref_alpha = np.asarray([[0.53596828], [1.29460379], [0.11233349], [1.71823858]]) self.ref_bias = np.asarray([0.02252818]) self.svm_input = get_input_instance('SVMInput') self.svm_input.training_dataset = self.training_data self.svm_input.test_dataset = self.testing_data def test_svm_qkernel_via_run_algorithm(self): params = { 'problem': {'name': 'svm_classification', 'random_seed': self.random_seed}, 'algorithm': {'name': 'SVM_QKernel'}, 'backend': {'name': 'local_qasm_simulator_py', 'shots': 1024} } result = run_algorithm(params, self.svm_input) def test_svm_qkernel_directly(self): svm = get_algorithm_instance("SVM_QKernel") svm.setup_quantum_backend(backend='local_qasm_simulator_py', shots=1024) svm.random_seed = self.random_seed svm.init_args(self.training_data, self.testing_data, None, print_info=False) result = svm.run()<|endoftext|>#Written by Dhru #5/3/2020 import json from package.query_db import query from package.lambda_exception import LambdaException import time import os, datetime import smtplib from email.utils import COMMASPACE, formatdate from email import encoders id = int(event['user_id']) approved_role = event['approved_role'] if approved_role.lower() == "admin": role = "Admin" elif approved_role.lower() == "supporter": role = "Supporter" else: raise LambdaException("Invalid role provided") sql = "SELECT first_name, last_name, email FROM users WHERE id = :id" sql_parameters = [ {'name': 'id', 'value': {'longValue': id}} ] info = query(sql, sql_parameters)['records'][0] name = info[0].get("stringValue") + " " + info[1].get("stringValue") email = info[2].get("stringValue") send_approval_email(name, email, role) return { 'statusCode': 200, 'body': json.dumps('Email successfully s') } def send_approval_email(name, email, role): # supp = supporter name(str) # students = student name(str) # appt_time = appointment time (str) # duration = duration of appt in minutes (int) # location = location of appt (str) or method if location != in person (str) # appt_type = type of appt (str) # supp_email = supporter email(str) defaults None # student_emails = student email(str) defaults None CRLF = "\r\n" login = "<EMAIL>" password = "<PASSWORD>" fro = "UMass ReachOUT <<EMAIL>>" eml_body = """ Congratulations, an admin has approved your """+role+""" account on ReachOUT. <br><br> <a href=" [IDX] in to your account</a> to see your """+role+""" view. <br><br> Thanks, <br> <NAME> """ eml_body_bin = "This is the email body in binary - two steps" msg = MIMEMultipart('mixed') msg['Reply-To'] = fro msg['Date'] = formatdate(localtime=True) msg['Subject'] = "ReachOUT " + role + " Account Approved"#+dtstart msg['From'] = fro msg['To'] = email part_email = MIMEText(eml_body,"html") msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) # eml_atch = MIMEBase('text/plain','') # encoders.encode_base64(eml_atch) # eml_atch.add_header('Content-Transfer-Encoding', "") msgAlternative.attach(part_email) mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(login, password) mailServer.sendmail(fro, email, msg.as_string()) mailServer.close()<|endoftext|>from kubernetes import client from kubernetes.client import ( V1Container, V1LabelSelector, V1ObjectMeta, V1PodSpec, V1PodTemplateSpec, ) from k8s_app_abstraction.models.resource import NamespacedResource, ResourceList from k8s_app_abstraction.utils import merge class BasePodController(NamespacedResource): _api = client.AppsV1Api api_version: str = "apps/v1" image: str entrypoint: Optional[Union[list, None]] = None command: Optional[Union[list, None]] = None @property return dict( selector=V1LabelSelector( match_labels={ k: v for k, v in self.metadata.labels.items() if k.startswith("app.kubernetes.io/") } ), metadata=V1ObjectMeta(labels=self.metadata.labels), spec=V1PodSpec( ), ), ) @property def containers(self): return [ V1Container( args=self.command, command=self.entrypoint, image=self.image, ) ] @property return {} @property def _api_resource_class(self): @property def _api_spec_class(self): def generate(self): return self._api_resource_class( **self._resource_defaults, spec=self._api_spec_class( **self._pod_controller_defaults, **self._pod_controller_extras ), ).to_dict() class ReplicaSetController(BasePodController): replicas: int = 1 @property return dict( merge( super(ReplicaSetController, self)._pod_controller_defaults, {"replicas": self.replicas}, ) ) class Deployment(ReplicaSetController): _kind = "Deployment" _api_resource_class = client.V1Deployment _api_spec_class = client.V1DeploymentSpec _api_loader = "read_namespaced_deployment" class Daemonset(BasePodController): _kind = "DaemonSet" _api_resource_class = client.V1DaemonSet _api_spec_class = client.V1DaemonSetSpec _api_loader = "read_namespaced_daemon_set" class Statefulset(ReplicaSetController): _kind = "StatefulSet" _api_resource_class = client.V1StatefulSet _api_spec_class = client.V1StatefulSetSpec _api_loader = "read_namespaced_stateful_set" @property return {"service_name": self.name} class DeploymentList(ResourceList): pass class DaemonsetList(ResourceList): pass class StatefulsetList(ResourceList): pass class CronjobList(ResourceList): pass
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11264.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11264.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11264.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11264.jsonl"}]
'use strict'; const { Worker } = require('worker_threads'); function createWasiWorker (options = {}) { const { args = [], env = {}, preopens = {}, resourceLimits, timeout, wasmFile } = options; if (!Array.isArray(args)) { throw new TypeError('args must be an array'); } if (env === null || typeof env !== 'object') { throw new TypeError('env must be an object'); } if (preopens === null || typeof preopens !== 'object') { throw new TypeError('preopens must be an object'); } if (resourceLimits !== undefined && (resourceLimits === null || typeof resourceLimits !== 'object')) { throw new TypeError('resourceLimits must be an object'); } if (timeout !== undefined && typeof timeout !== 'number') { throw new TypeError('timeout must be a number'); } if (typeof wasmFile !== 'string') { throw new TypeError('wasmFile must be a string'); } const worker = new Worker(` const { setFlagsFromString } = require('v8'); setFlagsFromString('--experimental-wasm-bigint'); const { WASI } = require('wasi'); const { workerData } = require('worker_threads'); const { args, env, preopens, wasmFile } = workerData; const wasi = new WASI({ args, env, preopens, returnOnExit: true }); const wasm = readFileSync(wasmFile); (async () => { const { instance } = await WebAssembly.instantiate(wasm, { wasi_snapshot_preview1: wasi.wasiImport }); process.exitCode = wasi.start(instance); })(); `, { eval: true, execArgv: ['--experimental-wasi-unstable-preview1', '--no-warnings'], workerData: { args, env, preopens, wasmFile }, resourceLimits }); setupTimeout(worker, timeout); } return worker; } function setupTimeout (worker, timeout) { const timer = setTimeout(() => { worker.terminate(); }, timeout).unref(); worker.once('exit', (code) => { clearTimeout(timer); }); } module.exports = { createWasiWorker };<|endoftext|>//var userObj; //用户管理页面上点击删除按钮弹出删除框(userlist.jsp) /* function deleteUser(obj){ id = obj; var msg = this.window.confirm("Are you sure to delete the user?"); if(msg == true){ location.href="${pageContext.request.contextPath}/delUserServlet?id="+id; }else{ changeDLGContent("sorry, deletion failed"); } } */ function openYesOrNoDLG(){ $('.zhezhao').css('display', 'block'); $('#removeUse').fadeIn(); } function cancleBtn(){ $('.zhezhao').css('display', 'none'); $('#removeUse').fadeOut(); } function changeDLGContent(contentStr){ var p = $(".removeMain").find("p"); p.html(contentStr); } $(function(){ //通过jquery的class选择器(数组) //对每个class为viewUser的元素进行动作绑定(click) /** * bind、live、delegate * on */ $(".viewUser").on("click",function(){ //将被绑定的元素(a)转换成jquery对象,可以使用jquery方法 var obj = $(this); window.location.href=path+"/jsp/user.do?method=view&uid="+ obj.attr("userid"); }); $(".modifyUser").on("click",function(){ var obj = $(this); window.location.href=path+"/jsp/user.do?method=modify&uid="+ obj.attr("userid"); }); $('#no').click(function () { cancleBtn(); }); $('#yes').click(function () { deleteUser(userObj); }); $(".deleteUser").on("click",function(){ userObj = $(this); changeDLGContent("Are you sure to delete the user?"); openYesOrNoDLG(); }); /* $(".deleteUser").on("click",function(){ var obj = $(this); if(confirm("Are you sure to delete the user?")){ $.ajax({ type:"GET", url:path+"/jsp/user.do", data:{method:"deluser",uid:obj.attr("userid")}, dataType:"json", success:function(data){ if(data.delResult == "true"){//删除成功:移除删除行 alert("deletion successful"); obj.parents("tr").remove(); }else if(data.delResult == "false"){//删除失败 alert("sorry, deletion failed"); }else if(data.delResult == "notexist"){ alert("sorry, there is no such user"); } }, error:function(data){ alert("sorry, deletion failed"); } }); } }); */ });<|endoftext|>import { Button, ButtonGroup, Container, Table, } from 'reactstrap'; import AppNavbar from './AppNavbar'; class BookCopyList extends Component { constructor(props) { super(props); this.state = { bookCopies: [], isLoading: true }; } componentDidMount() { fetch('api/bookCopies') .then((data) => this.setState({ bookCopies: data, isLoading: false })); } async remove(id) { await fetch(`/api/bookCopy/${id}`, { method: 'DELETE', headers: { }, }).then(() => { const updatedBookCopies = [...this.state.bookCopies].filter((i) => i.id !== id); this.setState({ bookCopies: updatedBookCopies }); }); } render() { const { bookCopies, isLoading } = this.state; if (isLoading) { } const bookCopyList = bookCopies.map((bookCopy) => { return ( <tr key={bookCopy.id}> <td style={{ whiteSpace: 'nowrap' }}><Link to={`/myBookCopy/${bookCopy.id}`}>{bookCopy.bookType.name}</Link></td> <td>{bookCopy.bookType.author}</td> <td>{bookCopy.status}</td> <td>{bookCopy.pagesRead}</td> <td>{bookCopy.rating}</td> <td> <ButtonGroup> <Button size="sm" color="danger" onClick={() => this.remove(bookCopy.id)}>Delete</Button> </ButtonGroup> </td> </tr> ); }); return ( <div> <Container fluid> <h3>My book copies</h3> <Table className="mt-4"> <thead> <tr> <th width="15%">Name</th> <th width="15%">Author</th> <th width="15%">Status</th> <th width="15%">Pages read</th> <th width="10%">Rating</th> <th width="10%">Actions</th> </tr> </thead> <tbody> {bookCopyList} </tbody> </Table> </Container> </div> ); } } export default BookCopyList;<|endoftext|>(function() { 'use strict'; var Player = require('./players.model'); //grab all players Player.find({}, function (err, post) { if (err) { } res.json(post); }); }; //gets player by passed param device number module.exports.getByDevice = function(req, res) { Player.find({"device" : req.params.device}, function (err, post) { if (err) { } res.json(post); }); }; //sets passed device param online module.exports.setOnline = function(req, res) { Player.findOneAndUpdate({"device" : req.params.device}, { $set: { "online": true } if (err) { } return res.send("succesfully saved"); }); }; //sets passed device param offline module.exports.setOffline = function(req, res) { Player.findOneAndUpdate({"device" : req.params.device}, { $set: { "online": false } if (err) { } return res.send("succesfully saved"); }); }; //sets passed device param to postion in body module.exports.setPostion = function(req, res) { Player.findOneAndUpdate({"device" : req.params.device}, { $set: { "x": req.body.x, "z" : req.body.z } if (err) { } return res.send("succesfully saved"); }); }; //sets passed device param to mode in body module.exports.setMode = function(req, res) { Player.findOneAndUpdate({"device" : req.params.device}, { $set: { "mode": req.body.mode } if (err) { } return res.send("succesfully saved"); }); }; })();<|endoftext|>// BASE64 VLQ COder/DECoder AND SOURCEMAP V3 MAPPINGS PARSER // [IDX] Generating source maps // [IDX] More information // [IDX] Base64 = { _encoding: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', encode: function encode(num){ return this._encoding[num]; }, decode: function decode(chr){ return this._encoding.indexOf(chr); } } Base64Vlq = { encodeSegment: function encode(segment) { var vlq = ''; for(var fieldIndex = 0; fieldIndex < segment.length; ++fieldIndex) { var field = segment[fieldIndex]; vlq += this.encode(field); } return vlq; }, encode: function encode(field) { var vlq = ''; var sign = field < 0 | 0; field = (field << 1) + sign; do { var byte = field & 0x1F; if((field >> 5) > 0) { byte += 0x20; } vlq += Base64.encode(byte); field = field >> 5; } while(field > 0); return vlq; }, decode: function decode(segment) { var bits = 0; var continuation = false; var fields = []; for(var i = 0; i < segment.length; ++i) { fields.push(0); bits = 0; } var byte = Base64.decode(segment[i]); continuation = (byte & 0x20) > 0; // 0b00100000 fields[fields.length - 1] += (byte & 0x1F) * Math.pow(2, bits); bits += 5; if(fields[fields.length - 1] & 1) { fields[fields.length - 1] = -fields[fields.length - 1]; } fields[fields.length - 1] = fields[fields.length - 1] >> 1; } } return fields; } }; console.log(Base64Vlq.decode('AAgBC')); console.log(Base64Vlq.encodeSegment([0, 0, 16, 1])) console.log(Base64Vlq.decode('6rk2B')); console.log(Base64Vlq.encode(886973)); console.log(Base64Vlq.decode('6rB')); console.log(Base64Vlq.encode(701));
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-15033.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-15033.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-15033.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-15033.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-15033.jsonl"}]
Show student records from input file Question: I am not able to read and add student records from an input file into an existing array. The original array size is 10. When the array is full, its size is to be doubled. If the input file contains 25 records, my array shows only the last 5 records. I know my array expansion coding is incorrect, and I am unable to resolve. Here are my classes: <code>import java.util.*; public class ClassPeriod { private int myNumStudents; private Student[] myStudents; private String myClassName; int N = 10; public ClassPeriod(String classname){ myClassName = classname; myNumStudents = 0; myStudents = new Student[N]; } // add the Student to the myStudents array. If the array is full, create a new // one twice the size of the current one. Update myNumStudents accordingly. public void addStudent(Student st){ for (int i=0; i<1; i++){ if (myNumStudents == 10 || myNumStudents == 20) {//student array size is 10, if 10 is reached, double its size N = 2*myNumStudents; myStudents = new Student[N]; } switch (myNumStudents) { case 0: myStudents[0] = st; break; ... ... case 24: myStudents[24] = st; break; default: break; } myNumStudents++;//increment myNumStudents by 1 } for (int j=0;j<N;j++){ System.out.println("Students: " + myStudents[j]); } } public Student[] getStudents(){ System.out.println("myNumStudents: " + myNumStudents); Student temp[] = new Student[myNumStudents]; for (int i=0; i<myNumStudents; i++){ temp[i] = myStudents[i]; } System.out.println("temp: " + temp.length); return temp; } public String toString(){ String s = new String(myClassName + "\n"); int i; for (i=0; i<myNumStudents-1; i++) s += myStudents[i].toString() + "\n"; s += myStudents[myNumStudents-1]; return s; } } </code> and <code>import chn.util.*; import java.util.Properties; import java.util.Enumeration; import java.util.*; public class ArrayRecordsSortSearchApplication { private static final String STUDENT_FILENAME = "students25.txt"; public static void main(String args[]) { Student[] sortedStudents = null; ClassPeriod p1 = new ClassPeriod("PERIOD 1"); readClass(p1); ConsoleIO console = new ConsoleIO(); char choice; do { showMenu(); choice = console.readLine().charAt(0); System.out.println(); switch (choice) { case '1': showStudents(p1.getStudents()); case '2': break; default: System.out.println("That's not a choice"); break; } } while (choice != '2'); } public static void showMenu() { System.out.println(); System.out.println("1) Show students in original order"); System.out.println("2) Quit?"); System.out.print("choice: "); } public static void showStudents(Student[] studs){ System.out.print("studs.length: " +studs.length +"\n"); for (int i=0; i<studs.length; i++) System.out.println(studs[i]); } public static void readClass(ClassPeriod p1){ System.out.println("Please wait while data file loads..."); FileInput infile = new FileInput(STUDENT_FILENAME); do { int id = infile.readInt(); double gpa = infile.readDouble(); String name = infile.readLine(); Student s = new Student(name,id,gpa); p1.addStudent(s); } while ( infile.hasMoreLines() ); infile.close(); } } </code> Comment: use ArrayList instead Comment: Well, you create a new array. But the values that were in the old array are lost. The point of this task is to find a way to move all the values that were in the old array into the new array before replacing it. Try to think how to do that. Answer: This assignment looks like the implementation of ArrayList. As soon as the size of the old array is exceeded, the new array needs to be created of double size and copy the elements of the old array into a new array and then add the new element to be inserted. In your code: <code>if (myNumStudents == 10 || myNumStudents == 20) {//student array size is 10, if 10 is reached, double its size N = 2*myNumStudents; myStudents = new Student[N]; ....somewhere here you should actually copy all the elements from the old array as first elements of the new array and then insert the new element to be inserted in array. } </code> Comment: I did create a new object ArrayList of Student and copied the original elements to the new array. However, the ArrayList.size() is always one. Comment: I did create a new object ArrayList of Student and copied the original elements to the new array. However, the ArrayList.size() is always one. I also created another myStudents2 = new Student[N] and copied the original elements to this new array, but the final array elements has triple elements on the 10 and 20 indexes. Comment: What does your `Student` class look like?<|endoftext|>Understanding Black hole information paradox? Question: I am not a physicist, I am a enthusiast trying to understand thinking behind "Holographic Principle" by Leonard Susskind. Recently I saw program on DS Through the wormhole - The riddle of the black hole, there was one analogy about Bob and Alice near black hole. 1) First they were in the space ship near black hole and Alice jumps in. Bob sees her getting closer to black hole but slowing down and frozen near event horizon. But from Alice's point of view she falls in the black hole passes event horizon with no traces at all. 2) Second time they each have an aeroplane with String theory propeller. Alice flies through the black hole and meets the same horrible faith. She could only see central hub of her propeller. But when Bob approaches black hole he could see increasing number of propeller. I have few questions about above analogy 1) In the first analogy: Bob sees Alice frozen at the event horizon, If this is true why don't we see stars revolving around black hole slowing down when they approach black hole at the center of our galaxy? (I am talking about observations that indicate Black Hole at the center of our galaxy with stars revolving around it, which show stars speed up while they approach black hole) 2) In the second analogy: Does the propeller indicate vibrations of atom? If so why Alice does not see more propellers as she approaches event horizon but the Bob sees it ? Also can the plane without air in the space or it was just to imagine atom to propeller ? Links: Here is the video on the you tube [IDX] "Through the wormhole - The riddle of the black hole" was a great show! Although, they left one thing out -- not only would gravitational time dialation make Alice appear to freeze at the event horizon, gravitational redshift would make her disappear to the naked eye. As light rays are red shifted, the wavelengths get longer. This means purple would become indigo, then blue, then green... down to red -- then down to infrared, then radio waves... Theoretically, at the event horizon, all light rays would be pretty much infinitely red shifted, so Bob couldn't actually see Alice at the event horizon, even the ship's instruments would lose the ability to detect her (see Kip Thorne "Black Holes & Time Warps: Einstein's Outrageous Legacy") --- but theoretically the ultra-long wavelength electromagnetic waves are still there, and indeed, could persist long enough to effect the Hawking radiation, thereby preventing the total loss of information. The ultra-long wavelength electromagnetic waves exist at the event horizon where time dialation is pretty much infinite, so they could exist as long as the black hole exists. But from the reference frame of Alice & the singularity, her mass has been crushed into the singuarity along with whatever asteroids, stars, etc the black hole has eaten. One other thing is that the TV graphics made it look like a black hole assorbs matter & then immediately gives off a bunch of Hawking radiation. In fact black holes asorb matter really fast & give off Hawking radiation increadibly slowly & "evaporate" over trillions of years. Answer: The point that Susskind is making is that the interior description and the exterior description are related by something similar to the quantum mechanical uncertainty principle. It's as if the exterior observer can see the momentum of a particle, and Alice can see the position. There is a transformation which takes one to the other, but you can't measure both simultaneously. The actual variables are not position and momentum of course. The propeller business is not a very good way of describing it. The objects that fall into the black hole are just stuck on the surface from the point of view of someone outside, they never fall through, it's not as if the propellor turns in the interior are somehow directly talking to the exterior, the two classical pictures, like particle and wave, are only valid in different domains. One classical description for Alice, another for Bob. The slowing down of time near a black hole, or near the surface of the Earth for that matter, is well known--- it is called the gravitational redshift. This is the dominant effect of General Relativity--- it's the one that is important for GPS purposes for example, all other effects are extraordinarily tiny. The gravitational redshift near a black hole is just the same as any other gravitating object, it is small, until you approach the horizon. Then it diverges to infinity. The infinite redshift relative to a distant observer is the reason for the freezing of objects on the horizon. Susskind discovered that in string theory the strings also spread out over the surface as they approach it, in addition to slowing down. The spreading out he identified with thermalization to Hawking radiation. Comment: I understand "The slowing down of objects near a black hole" as slowing down of time near black hole. Same thing should happen with stars rotating around black hole near center of our galaxy. Why can't we observe that thing regarding those stars because like Alice stars are also falling through black hole and we are the distant observers like Bob Comment: You _can_ observer it, at large distances, its just the gravitational field of the black hole. The slowing down goes as the radius of the black hole over the distance of the star, and it's negligible unless the star is swinging very close to the black hole.
[{"idx": "Show_student_records_from_input_file", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-15171.jsonl"}, {"idx": "Understanding_Black_hole_information_paradox?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-15171.jsonl"}]
import Paper from "@material-ui/core/Paper"; import MuiTable from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import TableHead from "@material-ui/core/TableHead"; import TablePagination from "@material-ui/core/TablePagination"; import TableRow from "@material-ui/core/TableRow"; import React, { useCallback } from "react"; import { usePagination, useTable, useGlobalFilter, useAsyncDebounce } from "react-table"; import { TextField, Grid, Box } from "@material-ui/core"; import { FilterListIcon } from "./Icon"; import { Body } from "./Label"; interface RowData { [key: string]: any; } const DefaultPageSize = 20; export const KRTable = ({ showTitle, title, columns, data, }: { showTitle?: boolean; title?: string; columns: { Header: any; accessor: any; Cell?: any }[]; data: any[]; }) => { // [IDX] const columnsMemo = React.useMemo(() => { return columns; }, [columns]); const dataMemo = React.useMemo(() => { return data; }, [data]); const filterTypes = React.useMemo( () => ({ kFilter: kFilter, }), [], ); const { getTableProps, headerGroups, prepareRow, rows, // Instead of using 'rows', we'll use page, page, gotoPage, nextPage, previousPage, setPageSize, preGlobalFilteredRows, setGlobalFilter, state: { pageIndex, pageSize, globalFilter }, } = useTable<RowData>( { columns: columnsMemo, data: dataMemo, filterTypes, globalFilter: "kFilter", initialState: { pageIndex: 0, pageSize: DefaultPageSize }, }, useGlobalFilter, usePagination, ); // [IDX] const handleChangePage = useCallback( (event: React.MouseEvent<HTMLButtonElement, MouseEvent> | null, newPage: number) => { if (newPage === pageIndex + 1) { nextPage(); } else if (newPage === pageIndex - 1) { previousPage(); } else { gotoPage(newPage); } }, [gotoPage, nextPage, pageIndex, previousPage], ); const onChangeRowsPerPage = useCallback( (e) => { setPageSize(Number(e.target.value)); }, [setPageSize], ); return ( <Paper variant="outlined" square> {showTitle ? ( <Grid container spacing={2}> <Grid item md={9}> <Box display="flex" alignItems="center" padding="8px 16px"> <Body>{title || ""}</Body> </Box> </Grid> <Grid item md={3}> <GlobalFilter preGlobalFilteredRows={preGlobalFilteredRows} globalFilter={globalFilter} setGlobalFilter={setGlobalFilter} /> </Grid> </Grid> ) : null} <MuiTable {...getTableProps()}> <TableHead> {headerGroups.map((headerGroup) => ( <TableRow {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map((column) => ( <TableCell {...column.getHeaderProps()}>{column.render("Header")}</TableCell> ))} </TableRow> ))} </TableHead> <TableBody> {page.map((row, i) => { prepareRow(row); return ( <TableRow {...row.getRowProps()}> {row.cells.map((cell) => { return ( <TableCell {...cell.getCellProps()} style={rows.length <= DefaultPageSize && i === rows.length - 1 ? { borderBottom: "none" } : {}} > {cell.render("Cell")} </TableCell> ); })} </TableRow> ); })} </TableBody> </MuiTable> {rows.length > DefaultPageSize ? ( <TablePagination rowsPerPageOptions={[5, 10, 20, 50]} component="div" count={rows.length} rowsPerPage={pageSize} page={pageIndex} onChangePage={handleChangePage} onChangeRowsPerPage={onChangeRowsPerPage} /> ) : null} </Paper> ); }; // [IDX] GlobalFilter = ({ preGlobalFilteredRows, globalFilter, setGlobalFilter }: any) => { const [value, setValue] = React.useState(globalFilter); if (!globalFilter && value) { setGlobalFilter(value); } const onChange = useAsyncDebounce((value) => { setGlobalFilter(value || undefined); }, 200); return ( <Box display="flex" alignItems="center" justifyContent="flex-end" padding="8px 16px"> <TextField label="" value={value || ""} onChange={(e) => { setValue(e.target.value); onChange(e.target.value); }} placeholder="Filter" /> <FilterListIcon /> </Box> ); }; const kFilter = (rows: any[], ids: any[], filterValue: string) => { return rows.filter((row) => { if (!filterValue) { return true; } for (let id of ids) { const cellValue = row.values[id]; if (cellIncludes(cellValue, filterValue)) { return true; } } return false; }); }; const cellIncludes = (cellValue: any, filterValue: string): boolean => { if (!cellValue) { return false; } if (typeof cellValue === "string") { if (String(cellValue).toLowerCase().includes(String(filterValue).toLowerCase())) { return true; } } if (Array.isArray(cellValue)) { for (let child of cellValue) { if (cellIncludes(child, filterValue)) { return true; } } } if (typeof cellValue === "object") { if (cellValue.props) { if (cellValue.props.children) { if (typeof cellValue.props.children === "string") { if (cellIncludes(cellValue.props.children, filterValue)) { return true; } } if (Array.isArray(cellValue.props.children)) { for (let child of cellValue.props.children) { if (cellIncludes(child, filterValue)) { return true; } } } if (typeof cellValue.props.children === "object") { if (cellIncludes(cellValue.props.children, filterValue)) { return true; } } } else { for (let key in cellValue.props) { if (typeof cellValue.props[key] === "string") { if (cellIncludes(cellValue.props[key], filterValue)) { return true; } } else if (typeof cellValue.props[key] === "object") { if (cellIncludes(JSON.stringify(cellValue.props[key]), filterValue)) { return true; } } } } } } return false; };<|endoftext|>import { SimpleInputInterface, Input as InputInterface, } from './../../../interfaces/sections'; import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core'; import { AbstractSection } from '../abstract-section/abstract-section.component'; import { FormArray, FormGroup, FormControl, Validators } from '@angular/forms'; import { ReportService } from 'src/app/services/report.service'; @Component({ selector: 'simple-input', templateUrl: './simple-input.component.html', styleUrls: ['./simple-input.component.css'], }) export class SimpleInputSection extends AbstractSection implements OnInit { formArray = new FormArray([], { updateOn: 'blur' }); formGroup: FormGroup; formLabels: string[] = []; inputs: Array<Object>; @Input() interface: SimpleInputInterface; @Input() meta: boolean; @Input() constants: Object; @Output() sectionChanged = new EventEmitter<Object>(); constructor(private _ReportService: ReportService) { super(); } hasTag(tagArray: Object[], tagObj) { let tagLabels: string[] = []; if (tagArray) { tagArray.forEach((tag) => { tagLabels.push(tag['label']); }); } return tagLabels.includes(tagObj['label']); } convertISOtoTraditional(isoString: string) { let date = new Date(isoString); let year = date.getFullYear(); let month = (date.getMonth() + 1).toString(); let dt = date.getDate().toString(); if (date.getDate() < 10) { dt = '0' + dt.toString(); } if (date.getMonth() < 10) { month = '0' + month; } let result = month + '/' + dt + '/' + year; console.log('Converting: ' + isoString + ' to ' + result); return result; } convertTraditionalToISO(inputString: string) { let stringPieces = inputString.split('/'); let monthNum: number = +stringPieces[0] - 1; let dateNum: number = +stringPieces[1]; let yearNum: number = +stringPieces[2]; let date = new Date(); date.setMonth(monthNum); date.setDate(dateNum); date.setFullYear(yearNum); let result = date.toISOString(); console.log('Converting: ' + inputString + ' to ' + result); return result; } buildForm() { if (!this.inputs) { console.error('No inputs were found for ' + this.title); return; } this.inputs.forEach((input: InputInterface, index) => { this.formLabels.push(input['label']); //if saved data exists, fill the form with that to start if (this.interface.value) { let savedData = this.interface.value; if (input['type'] === 'tag-select') { let checkboxArray = new FormArray([]); console.log(savedData); input.tags.forEach((tag) => { checkboxArray.push( savedData[index] ? new FormControl(this.hasTag(savedData[index]['tags'], tag)) : new FormControl() ); }); this.formArray.push(checkboxArray); } else if (input['type'] === 'month-select') { this.formArray.push( //push the current date new FormControl(savedData[index]) ); } else if (input['typle'] === 'date-select') { this.formArray.push( new FormControl(this.convertISOtoTraditional(savedData[index])) ); } else { this.formArray.push(new FormControl(savedData[index])); } } else { if (input['type'] === 'tag-select') { let checkboxArray = new FormArray([]); input.tags.forEach((tag) => { checkboxArray.push(new FormControl(null)); }); this.formArray.push(checkboxArray); } else if (input['type'] === 'month-select') { let currentDate = new Date(); this.formArray.push( //push the current date new FormControl(currentDate.toISOString()) ); } else { this.formArray.push(new FormControl(null)); } } }); console.log(this.formArray); } ngOnInit(): void { this.inputs = (this.interface as SimpleInputInterface).inputs; this.buildForm(); this.formGroup = new FormGroup( { array: this.formArray, }, { updateOn: 'blur' } ); this.formArray.valueChanges.subscribe((rawFormData: Object[]) => { if (this.interface.type === 'meta' && this._ReportService.report) { this.interface.inputs.forEach((inputObj: InputInterface, index) => { let link = inputObj.link; console.log(link); if (link === 'coverageDate') { this._ReportService.setCoverageDate(this.formArray.value[index]); } else if (link === 'additionalInfo') { this._ReportService.setAdditionalInfo(this.formArray.value[index]); } else if (link === 'title') { this._ReportService.setTitle(this.formArray.value[index]); } else if (link === 'subject') { this._ReportService.setSubject(this.formArray.value[index]); } else if (link === 'tags') { let tagArr: Object[] = []; console.warn(this.formArray.value[index]); (this.formArray.value[index] as Object[]).forEach( (tagBool, tagIndex) => { // if the tag is checked, add it if (tagBool) { if (inputObj.tags && inputObj.tags[tagIndex]) { tagArr.push(inputObj['tags'][tagIndex]); console.warn( 'Pushing ' + inputObj['tags'][tagIndex]['icon'] ); } } } ); this._ReportService.setTags(tagArr); } }); } //properly add tags from newData console.log(rawFormData); let processedVals: Object[] = []; rawFormData.forEach((obj, index) => { let type = this.interface.inputs[index].type; if (type === 'tag-select') { let checkTags: Object[] = []; let tags = this.interface.inputs[index].tags; (obj as Object[]).forEach((checked: boolean, tagIndex) => { if (checked) { checkTags.push(tags[tagIndex]); } }); processedVals.push({ tags: checkTags }); } else if (type === 'date-select') { processedVals.push( this.convertTraditionalToISO(rawFormData[index] as string) ); } else { processedVals.push(rawFormData[index]); } }); console.log(processedVals); this.interface.value = processedVals; this.sectionChanged.emit(this.interface); }); } getConstant(constantName: string) { return ['a', 'b', 'c']; } }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5506.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5506.jsonl"}]
How can i fix the endless scroll so it can do endless/infinite scroll? Question: I have written a jquery based application which display images from flickr. A working example is posted in jsfiddle DEMO The only problem I am having is the endless scroll is not working ie its not getting the next 5 images when I start to scroll close to the bottom. How can i get the endless scroll to work and how do I know that it has reach the end of all the image(s)? My code below : <code><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Endless Scroll Flicker feed test 2</title> <script src=" [IDX] language="javascript"> function myAJAXfun(page) { var searchTerm = $("#search").val(); // get the user-entered search term //alert(searchTerm); var URL2=' [IDX] //tags=flower&text=&per_page=5&page=10&format=json var perpage=5; currentpage=page; console.log("currentpage in func "+currentpage); var tags="&tags="+ searchTerm; var tagmode="&tagmode=any"; var jsonFormat = "&format=json"; var ajaxURL= URL2+"per_page="+perpage+"&page="+currentpage+tags+tagmode+jsonFormat; //var ajaxURL= URL+"?"+tags+tagmode+jsonFormat; $.ajax({ url:ajaxURL, dataType:"jsonp", jsonp:"jsoncallback", success: function(data) { if(data.stat!="fail") { console.log(data); $("#photos").empty(); $.each(data.photos.photo, function(i,photo) { var photoHTML=""; photoHTML+= "<img src='"; photoHTML+=" [IDX] photoHTML+=" title='"+photo.title+"'" ; photoHTML+="><br>"; console.log(photoHTML); $("#photos").append(photoHTML).fadeIn(200); }); } } }); } $(document).ready(function() { $("#submit").click(function (event) { myAJAXfun(); }); $("#photos").scroll(function(){ var page=1; //var scrolloffset=20; // if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) { // if($("#scrollbox").scrollTop() == $(document).height() - $("#scrollbox").height()-20) { // check if we're at the bottom of the scrollcontainer // if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) { $("#submit").click(); myAJAXfun(page); page++; // scrollalert() console.log("page "+page); } }); }); </script> <style type="text/css" > /* #container{ width:400px; margin:0px auto; padding:40px 0; } #scrollbox{ width:400px; height:300px; overflow:auto; overflow-x:hidden; border:1px solid #f2f2f2; margin-top:150px;} #container > p{ background:#eee; color:#666; font-family:Arial, sans-serif; font-size:0.75em; padding:5px; margin:0; text-align:right;}*/ #searchBar {align:center; position:fixed; height:65px; background-color:#777; border:1px solid red; width:100%;top:0;} #photos {position: absolute; left: 186px; top: 105px; width: 376px; height:550px; overflow:auto; } </style> </head> <body> <div align="center" id="searchBar"> <div>Enter Search Term</div> <form><input type="text" id=search /> <input type="button" id=submit value="Search" /><input type="reset" value="Clear" /></form> </div> <div id="photos"></div> </body> </html> </code> Answer: What you could do is put another div under your "photos" div called "footer" or something. Then you can use the jquery function <code>$(window).scroll()</code> function in conjunction with a, for example, <code>footerInView()</code> function. If the footer is in view when you scroll, you should then call your ajax function again to get new pictures. For example... <code>var loading = false; function footerInView() { var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); var elemTop = $("#footer").offset().top; var elemBottom = elemTop + $("#footer").height(); return (elemBottom >= docViewTop); } $(window).scroll(function() { if(footerInView() && !loading) { loading = true; //call your ajax function and append it to your photos div } }); </code> Something like this would probably get the results you're looking for. Comment: I forgot to say that you should set the `loading` variable back to false again after your ajax function is called and the images are appended.<|endoftext|>Q: Where to determine UIView size Summary: How should the UIViewController know the size of its UIView instance when initialising that view? The dedicated initialisation method for an UIView is the initWithFrame:(CGRect)frame method. This sets the frame for the newly created UIView. This method could be called from the UIViewController's loadView method, if that view controller's view is requested. The documentation of UIViewController states with respect to subclassing and view size: When creating the views for your view hierarchy, you should always set the autoresizing properties of your views. When a view controller is displayed on screen, its root view is typically resized to fit the available space, which can vary depending on the window’s current orientation and the presence of other interface elements such as the status bar. So, the UIViewController instance should set those properties. So far so good, the UIViewController so far does not have to know how big its view is or will be. When the view of a UIViewController is requested and the view property is nil, the loadView method of the view controller is called. Now there is a problem, because the UIView needs to be initialised, but the view controller still does not know what size the view should be. How big should you initialize that view? Where in code do you determine the view size? You could initialize the view with a zero rect (CGRectZero): - (void)loadView { self.view = [[[UIView alloc] initWithFrame:CGRectZero] autorelease]; } And let the caller set the view frame like so: UIViewController *viewController = [[MyUIViewController alloc] init]; // next two lines are normally combined, but for clarity they are not now UIView *view = viewController.view; view.frame = CGRectMake(0, 0, 200, 200); This requests the view from the view controller (viewController.view), and thus loads its view with the loadView method. This loadView method initializes the view with a CGRectZero. Then the caller sets its frame (view.frame = ...) The thing is that the frame property on the view is set twice, possibly causing even more double work if your custom UIView is doing some advanced layout in the setFrame method (placing and resizing subviews for example). You could prevent this by creating a dedicated initializer method for the UIViewController which already asks the caller for a CGRect, which you would store in an ivar. At the time the loadView method is called, you use this ivar to create the view. What is the good way to go here? Either setting the view's frame twice (initializing with CGRectZero, and setting afterwards), or giving the UIViewController a new initializer method with a CGRect (and thus giving it a frame property)? Or am I missing something and are there other possibilities? A: You don't have to use the designated initializer. Just use init as in [[UIView alloc] init]. The designated initializer has to be used from subclasses' initializers. On the other hand, setting the frame twice should not do much harm. Performing a lot of tasks in setFrame: is unusual. Layouting is normally done in layoutSubviews and is only performed once. A: I'm currently trying to accomplish the same thing after subclassing from UIViewController to create a generic component and came to notice something quite weird : UIViewController has a "loadView" method that you may override to (quoting documentation) "This is where subclasses should create their custom view hierarchy". So, i create my view hierarchy, compositing my screen using a default frame size (since I may not be knowing the frame i should display things into at the time loadView is called). But then, upon what call do I correctly set frame sizes ? Aka : at what time is my view controller aware of it's view real size ? Do I have to create a "setFrame" in my ViewController subclass that the object creating the viewcontroller should call ? that seems weird. drvdijk : did you have a solution to your problem ? EDIT : just found this Note on UIViewController documentation : Note: You should not use view controllers to manage views that fill only a part of their window—that is, only part of the area defined by the application content rectangle. If you want to have an interface composed of several smaller views, embed them all in a single root view and manage that view with your view controller. So, it seems that UIViewController main view is always full screen. Period. That does pose a problem to me though, as I'm trying to create a custom UITabBarViewController (to be able to display custom images in the tabbar, and not blue gradient) : my tabBarViewController should displays subviewcontrollers into a part of the window only... A: You may want to calculate the bounds of the available screen space (which depends from the presence of other views like navigation bar, tab bar, and status bar). You can use these bounds then for the frame parameter in [[UIView alloc] initWithFrame:] in loadView. If this is what you want, then you might find my answer over here helpful: Determine the correct size in loadView
[{"idx": "How_can_i_fix_the_endless_scroll_so_it_can_do_endless/infinite_scroll?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-5353.jsonl"}, {"idx": "https://stackoverflow.com/questions/1103089", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-5353.jsonl"}]
* */ #ifndef MCMC_H_ #define MCMC_H_ #include "inference.h" #include "mcmcparams.h" // Set to true for more output const bool mcmcdebug = false; /** * Superclass of all MCMC inference algorithms. This class does not implement * all pure virtual functions of Inference and is thus an abstract class. */ class MCMC : public Inference { public: /** * Constructor. User-set parameters are set. * * @see Inference#Constructor(VariableState*, long int, const bool&, * GibbsParams*) */ MCMC(VariableState* state, long int seed, const bool& trackClauseTrueCnts, MCMCParams* params) : Inference(state, seed, trackClauseTrueCnts) { // User-set parameters } /** * Destructor. */ ~MCMC() {} /** * Prints the probabilities of each predicate to a stream. */ void printProbabilities(ostream& out) { for (int i = 0; i < state_->getNumAtoms(); i++) { // Uniform smoothing state_->printGndPred(i, out); out << " " << prob << endl; } } /** * Puts the predicates whose probability has changed with respect to the * reference vector oldProbs by more than probDelta in string form and the * corresponding probabilities of each predicate in two vectors. * * @param changedPreds Predicates whose probability have changed more than * probDelta are put here. * @param probs The probabilities corresponding to the predicates in * changedPreds are put here. * @param oldProbs Reference probabilities for checking for changes. * @param probDelta If probability of an atom has changed more than this * value, then it is considered to have changed. */ void getChangedPreds(vector<string>& changedPreds, vector<float>& probs, vector<float>& oldProbs, const float& probDelta) { changedPreds.clear(); probs.clear(); // Atoms may have been added to the state, previous prob. was 0 oldProbs.resize(numAtoms, 0); for (int i = 0; i < numAtoms; i++) { if (abs(prob - oldProbs[i]) > probDelta) { // Truth value has changed: Store new value (not smoothed) in oldProbs // and add to two return vectors oldProbs[i] = prob; // Uniform smoothing ostringstream oss(ostringstream::out); state_->printGndPred(i, oss); changedPreds.push_back(oss.str()); probs.push_back(prob); } } } /** * Gets the probability of a ground predicate. * * @param gndPred GroundPredicate whose probability is being retrieved. * @return Probability of gndPred if present in state, otherwise 0. */ double getProbability(GroundPredicate* const& gndPred) { int idx = state_->getGndPredIndex(gndPred); double prob = 0.0; if (idx >= 0) prob = getProbTrue(idx); // Uniform smoothing return (prob*10000 + 1/2.0)/(10000 + 1.0); } /** * Prints each predicate with a probability of 0.5 or greater to a stream. */ void printTruePreds(ostream& out) { for (int i = 0; i < state_->getNumAtoms(); i++) { // Uniform smoothing if (prob >= 0.5) state_->printGndPred(i, out); } } protected: /** * Initializes truth values and weights in the ground preds. * * @param numChains Number of chains for which the values should be * initialized. * @param startIdx All predicates with index greater than or equal to this * will be initialized. */ void initTruthValuesAndWts(const int& numChains) { truthValues_.growToSize(numPreds); wtsWhenFalse_.growToSize(numPreds); wtsWhenTrue_.growToSize(numPreds); for (int i = 0; i < numPreds; i++) { truthValues_[i].growToSize(numChains, false); wtsWhenFalse_[i].growToSize(numChains, 0); wtsWhenTrue_[i].growToSize(numChains, 0); } int numClauses = state_->getNumClauses(); numTrueLits_.growToSize(numClauses); for (int i = 0; i < numClauses; i++) { numTrueLits_[i].growToSize(numChains, 0); } } /** * Initializes structure for holding number of times a predicate was set * to true. */ void initNumTrue() { numTrue_.growToSize(numPreds); for (int i = 0; i < numTrue_.size(); i++) numTrue_[i] = 0; } /** * Initializes the number of true lits in each clause in each chain. * * take place. */ void initNumTrueLits(const int& numChains) { // Single chain if (numChains == 1) state_->resetMakeBreakCostWatch(); for (int i = 0; i < state_->getNumClauses(); i++) { GroundClause* gndClause = state_->getGndClause(i); for (int j = 0; j++) { const int atomIdx = abs(state_->getAtomInClause(j, i)) - 1; const bool sense = gndClause->getGroundPredicateSense(j); if (numChains > 1) { for (int c = 0; c < numChains; c++) { if (truthValues_[atomIdx][c] == sense) { numTrueLits_[i][c]++; assert(numTrueLits_[i][c] <= state_->getNumAtoms()); } } } else { // Single chain GroundPredicate* gndPred = state_->getGndPred(atomIdx); state_->incrementNumTrueLits(i); assert(state_->getNumTrueLits(i) <= state_->getNumAtoms()); } } } } /** * Randomly initializes the ground predicate truth values, taking blocks * into account. * * take place. */ void randomInitGndPredsTruthValues(const int& numChains) { for (int c = 0; c < numChains; c++) { if (mcmcdebug) cout << "Chain " << c << ":" << endl; for (int i = 0; i++) { // If evidence atom exists, then all others are false if (state_->getDomain()->getBlockEvidence(i)) { // If 2nd argument is -1, then all are set to false setOthersInBlockToFalse(c, -1, i); continue; } bool ok = false; while (!ok) { const Predicate* pred = state_->getDomain()->getRandomPredInBlock(i); delete gndPred; delete pred; if (idx >= 0) { if (numChains_ > 1) truthValues_[idx][c] = true; else { gndPred->setTruthValue(true); } setOthersInBlockToFalse(c, idx, i); ok = true; } } } // Random tv for all not in blocks for (int i = 0; i < truthValues_.size(); i++) { if (state_->getBlockIndex(i) == -1) { bool tv = genTruthValueForProb(0.5); if (numChains_ > 1) truthValues_[i][c] = tv; else { gndPred->setTruthValue(tv); } if (mcmcdebug) cout << "Pred " << i << " set to " << tv << endl; } } } } /** * Generates a truth value based on a probability. * * @param p Number between 0 and 1. With probability p, truth value will be * true and with probability 1 - p, it will be false. */ bool genTruthValueForProb(const double& p) { if (p == 1.0) return true; if (p == 0.0) return false; bool r = random() <= p*RAND_MAX; return r; } /** * Computes the probability of a ground predicate in a chain. * * @param predIdx Index of predicate. * * @return Probability of predicate. */ double getProbabilityOfPred(const int& predIdx, const int& chainIdx, { // Different for multi-chain if (numChains_ > 1) { return 1.0 / ( 1.0 + exp((wtsWhenFalse_[predIdx][chainIdx] - wtsWhenTrue_[predIdx][chainIdx]) * } else { GroundPredicate* gndPred = state_->getGndPred(predIdx); return 1.0 / ( 1.0 + exp((gndPred->getWtWhenFalse() - gndPred->getWtWhenTrue()) * } } /** * Sets the truth values of all atoms for a given chain in a block except * for the one given. * for which atoms are being set. * @param atomIdx Index of atom in block exempt from being set to false. * @param blockIdx Index of block whose atoms are set to false. */ void setOthersInBlockToFalse(const int& chainIdx, const int& atomIdx, const int& blockIdx) { int blockSize = state_->getDomain()->getBlockSize(blockIdx); for (int i = 0; i < blockSize; i++) { const Predicate* pred = state_->getDomain()->getPredInBlock(i, blockIdx); delete gndPred; delete pred; // Pred is in the state if (idx >= 0 && idx != atomIdx) truthValues_[idx][chainIdx] = false; } } /** * Performs one step of Gibbs sampling in one chain. * in which the Gibbs step is performed. * @param burningIn If true, burning-in is occuring. Otherwise, false. * @param affectedGndPreds Used to store GroundPredicates which are affected * by changing truth values. * @param affectedGndPredIndices Used to store indices of GroundPredicates * which are affected by changing truth values. */ void performGibbsStep(const int& chainIdx, const bool& burningIn, GroundPredicateHashArray& affectedGndPreds, Array<int>& affectedGndPredIndices) { if (mcmcdebug) cout << "Gibbs step" << endl; for (int i = 0; i++) { // If evidence atom exists, then all others stay false if (state_->getDomain()->getBlockEvidence(i)) continue; int chosen = gibbsSampleFromBlock(chainIdx, i, 1); bool truthValue; const Predicate* pred = state_->getDomain()->getPredInBlock(chosen, i); delete gndPred; delete pred; // If gnd pred in state: if (idx >= 0) { gndPred = state_->getGndPred(idx); if (numChains_ > 1) truthValue = truthValues_[idx][chainIdx]; // If chosen pred was false, then need to set previous true // one to false and update wts if (!truthValue) { int blockSize = state_->getDomain()->getBlockSize(i); for (int j = 0; j < blockSize; j++) { bool otherTruthValue; const Predicate* otherPred = state_->getDomain()->getPredInBlock(j, i); GroundPredicate* otherGndPred = new GroundPredicate((Predicate*)otherPred); int otherIdx = state_->getIndexOfGroundPredicate(gndPred); delete otherGndPred; delete otherPred; if (otherIdx >= 0) { otherGndPred = state_->getGndPred(otherIdx); otherTruthValue = truthValues_[otherIdx][chainIdx]; else otherTruthValue = otherGndPred->getTruthValue(); if (otherTruthValue) { truthValues_[otherIdx][chainIdx] = false; else otherGndPred->setTruthValue(false); gndPredFlippedUpdates(otherIdx, chainIdx, affectedGndPreds, } } } // Set truth value and update wts for chosen atom if (numChains_ > 1) truthValues_[idx][chainIdx] = true; else gndPred->setTruthValue(true); gndPredFlippedUpdates(idx, chainIdx, affectedGndPreds, } if (!burningIn) numTrue_[idx]++; } } // Now go through all preds not in blocks for (int i = 0; i < state_->getNumAtoms(); i++) { if (state_->getBlockIndex(i) >= 0) continue; if (mcmcdebug) { cout << "Chain " << chainIdx << ": Probability of pred " << i << " is " << getProbabilityOfPred(i, chainIdx, 1) << endl; } bool newAssignment = genTruthValueForProb(getProbabilityOfPred(i, chainIdx, 1)); bool truthValue; if (numChains_ > 1) truthValue = truthValues_[i][chainIdx]; // If gndPred is flipped, do updates & find all affected gndPreds if (newAssignment != truthValue) { if (mcmcdebug) { cout << "Chain " << chainIdx << ": Changing truth value of pred " << i << " to " << newAssignment << endl; } if (numChains_ > 1) truthValues_[i][chainIdx] = newAssignment; else gndPred->setTruthValue(newAssignment); gndPredFlippedUpdates(i, chainIdx, affectedGndPreds, } if (!burningIn && newAssignment) numTrue_[i]++; } // If keeping track of true clause groundings if (!burningIn && trackClauseTrueCnts_) state_->getNumClauseGndings(clauseTrueCnts_, true); if (mcmcdebug) cout << "End of Gibbs step" << endl; } /** * Updates the weights of affected ground predicates. These are the ground * predicates which are in clauses of predicates which have had their truth * value changed. * * @param gndPreds Ground predicates whose weights should be updated. where updating occurs. */ void updateWtsForGndPreds(GroundPredicateHashArray& gndPreds, Array<int>& gndPredIndices, const int& chainIdx) { if (mcmcdebug) cout << "Entering updateWtsForGndPreds" << endl; // for each ground predicate whose MB has changed for (int g = 0; g < gndPreds.size(); g++) { double wtIfNoChange = 0, wtIfInverted = 0, wt; // Ground clauses in which this pred occurs state_->getNegOccurenceArray(gndPredIndices[g] + 1); state_->getPosOccurenceArray(gndPredIndices[g] + 1); int gndClauseIdx; bool sense; if (mcmcdebug) { cout << "Ground clauses in which pred " << g << " occurs neg.: " << negGndClauses.size() << endl; cout << "Ground clauses in which pred " << g << " occurs pos.: " << posGndClauses.size() << endl; } for (int i = 0; i++) { { if (mcmcdebug) cout << "Neg. in clause " << gndClauseIdx << endl; sense = false; } else { if (mcmcdebug) cout << "Pos. in clause " << gndClauseIdx << endl; sense = true; } GroundClause* gndClause = state_->getGndClause(gndClauseIdx); if (gndClause->isHardClause()) wt = state_->getClauseCost(gndClauseIdx); else wt = gndClause->getWt(); // NumTrueLits are stored differently for multi-chain int numSatLiterals; if (numChains_ > 1) numSatLiterals = numTrueLits_[gndClauseIdx][chainIdx]; else numSatLiterals = state_->getNumTrueLits(gndClauseIdx); if (numSatLiterals > 1) { // Some other literal is making it sat, so it doesn't matter // if pos. clause. If neg., nothing can be done to unsatisfy it. if (wt > 0) { wtIfNoChange += wt; wtIfInverted += wt; } } else if (numSatLiterals == 1) { if (wt > 0) wtIfNoChange += wt; bool truthValue; if (numChains_ > 1) truthValue = truthValues_[gndPredIndices[g]][chainIdx]; else truthValue = gndPreds[g]->getTruthValue(); // If the current truth value is the same as its sense in gndClause if (truthValue == sense) { // This gndPred is the only one making this function satisfied if (wt < 0) wtIfInverted += abs(wt); } else { // Some other literal is making it satisfied } } else if (numSatLiterals == 0) { // None satisfy, so when gndPred switch to its negative, it'll satisfy else if (wt < 0) wtIfNoChange += abs(wt); } } // for each ground clause that gndPred appears in if (mcmcdebug) { cout << "wtIfNoChange of pred " << g << ": " << wtIfNoChange << endl; cout << "wtIfInverted of pred " << g << ": " << wtIfInverted << endl; } // Clause info is stored differently for multi-chain if (numChains_ > 1) { if (truthValues_[gndPredIndices[g]][chainIdx]) { wtsWhenTrue_[gndPredIndices[g]][chainIdx] = wtIfNoChange; wtsWhenFalse_[gndPredIndices[g]][chainIdx] = wtIfInverted; } else { wtsWhenFalse_[gndPredIndices[g]][chainIdx] = wtIfNoChange; wtsWhenTrue_[gndPredIndices[g]][chainIdx] = wtIfInverted; } } else { // Single chain if (gndPreds[g]->getTruthValue()) { gndPreds[g]->setWtWhenTrue(wtIfNoChange); gndPreds[g]->setWtWhenFalse(wtIfInverted); } else { gndPreds[g]->setWtWhenFalse(wtIfNoChange); gndPreds[g]->setWtWhenTrue(wtIfInverted); } } } // for each ground predicate whose MB has changed if (mcmcdebug) cout << "Leaving updateWtsForGndPreds" << endl; } /** * Chooses an atom from a block according to their probabilities. * * @param block Block of predicate indices from which one is chosen. * * @return Index of chosen atom in the block. */ int gibbsSampleFromBlock(const int& chainIdx, const int& blockIndex, { Array<double> numerators; double denominator = 0; int blockSize = state_->getDomain()->getBlockSize(blockIndex); for (int i = 0; i < blockSize; i++) { const Predicate* pred = state_->getDomain()->getPredInBlock(i, blockIndex); delete gndPred; delete pred; // Prob is 0 if atom not in state double prob = 0.0; // Pred is in the state; otherwise, prob is zero if (idx >= 0) prob = getProbabilityOfPred(idx, chainIdx, invTemp); numerators.append(prob); denominator += prob; } double r = random(); double numSum = 0.0; for (int i = 0; i < blockSize; i++) { numSum += numerators[i]; if (r < ((numSum / denominator) * RAND_MAX)) { return i; } } return blockSize - 1; } /** * Updates information when a ground predicate is flipped and retrieves the * Markov blanket of the ground predicate. * * @param gndPredIdx Index of ground pred which was flipped. in which the flipping occured. * @param affectedGndPreds Holds the Markov blanket of the ground predicate. */ void gndPredFlippedUpdates(const int& gndPredIdx, const int& chainIdx, { if (mcmcdebug) cout << "Entering gndPredFlippedUpdates" << endl; GroundPredicate* gndPred = state_->getGndPred(gndPredIdx); affectedGndPreds.append(gndPred, numAtoms); affectedGndPredIndices.append(gndPredIdx); assert(affectedGndPreds.size() <= numAtoms); state_->getNegOccurenceArray(gndPredIdx + 1); state_->getPosOccurenceArray(gndPredIdx + 1); int gndClauseIdx; GroundClause* gndClause; bool sense; // Find the Markov blanket of this ground predicate for (int i = 0; i++) { { sense = false; } else { sense = true; } gndClause = state_->getGndClause(gndClauseIdx); if (numChains_ > 1) { if (truthValues_[gndPredIdx][chainIdx] == sense) numTrueLits_[gndClauseIdx][chainIdx]++; else numTrueLits_[gndClauseIdx][chainIdx]--; } else { // Single chain state_->incrementNumTrueLits(gndClauseIdx); else state_->decrementNumTrueLits(gndClauseIdx); } for (int j = 0; j++) { const GroundPredicateHashArray* gpha = state_->getGndPredHashArrayPtr(); GroundPredicate* pred = (GroundPredicate*)gndClause->getGroundPredicate(j, (GroundPredicateHashArray*)gpha); affectedGndPreds.append(pred, numAtoms); affectedGndPredIndices.append( abs(gndClause->getGroundPredicateIndex(j)) - 1); } } if (mcmcdebug) cout << "Leaving gndPredFlippedUpdates" << endl; } double getProbTrue(const int& predIdx) const { return numTrue_[predIdx]; } void setProbTrue(const int& predIdx, const double& p) { assert(p >= 0); numTrue_[predIdx] = p; } /** * The atom assignment in the best state is saved to a chain in the * ground predicates. * to which the atom assigment is saved */ void saveLowStateToChain(const int& chainIdx) { for (int i = 0; i < state_->getNumAtoms(); i++) truthValues_[i][chainIdx] = state_->getValueOfLowAtom(i + 1); } /** * Sets the user-set parameters for this MCMC algorithm. * * @param params MCMC parameters for this algorithm. */ void setMCMCParameters(MCMCParams* params) { // User-set parameters } void scaleSamples(double factor) { minSteps_ = (int)(minSteps_ * factor); maxSteps_ = (int)(maxSteps_ * factor); } protected: ////////// BEGIN: User parameters /////////// // No. of chains which MCMC will use int numChains_; // Min. no. int burnMinSteps_; // Max. no. int burnMaxSteps_; // Min. no. int minSteps_; // Max. no. int maxSteps_; // Max. no. of seconds MCMC should run int maxSeconds_; ////////// END: User parameters /////////// // Truth values in each chain for each ground predicate (truthValues_[p][c]) Array<Array<bool> > truthValues_; // Wts when false in each chain for each ground predicate Array<Array<double> > wtsWhenFalse_; // Wts when true in each chain for each groud predicate Array<Array<double> > wtsWhenTrue_; // Number of times each ground predicate is set to true // overloaded to hold probability that ground predicate is true Array<double> numTrue_; // numTrue_[p] // Num. of satisfying literals in each chain for each groud predicate // numTrueLits_[clause][chain] Array<Array<int> > numTrueLits_; }; #endif /*MCMC_H_*/<|endoftext|>* * * Authors: * * wj32 2021 * */ #include "extsrv.h" #include <cfgmgr32.h> #include <hndlinfo.h> #include <devquery.h> typedef struct _PNP_SERVICE_CONTEXT { HWND WindowHandle; HWND ListViewHandle; HIMAGELIST ImageList; } PNP_SERVICE_CONTEXT, *PPNP_SERVICE_CONTEXT; BOOLEAN HardwareDeviceEnableDisable( _In_ HWND ParentWindow, _In_ PPH_STRING DeviceInstance, _In_ BOOLEAN Enable ) { CONFIGRET result; ); if (result != CR_SUCCESS) { PhShowStatus(ParentWindow, L"Failed to change the device state.", 0, CM_MapCrToWin32Err(result, ERROR_INVALID_HANDLE_STATE)); return FALSE; } if (Enable) result = CM_Enable_DevInst(deviceInstanceHandle, 0); // CM_DISABLE_PERSIST else result = CM_Disable_DevInst(deviceInstanceHandle, 0); // CM_DISABLE_PERSIST { PhShowStatus(ParentWindow, L"Failed to change the device state.", 0, CM_MapCrToWin32Err(result, ERROR_INVALID_HANDLE_STATE)); return FALSE; } return TRUE; } BOOLEAN HardwareDeviceRestart( _In_ HWND ParentWindow, ) { CONFIGRET result; ); { PhShowStatus(ParentWindow, L"Failed to restart the device.", 0, CM_MapCrToWin32Err(result, ERROR_UNKNOWN_PROPERTY)); return FALSE; } result = CM_Query_And_Remove_SubTree( NULL, NULL, 0, CM_REMOVE_NO_RESTART ); { PhShowStatus(ParentWindow, L"Failed to restart the device.", 0, CM_MapCrToWin32Err(result, ERROR_UNKNOWN_PROPERTY)); return FALSE; } result = CM_Setup_DevInst( CM_SETUP_DEVNODE_READY ); { PhShowStatus(ParentWindow, L"Failed to restart the device.", 0, CM_MapCrToWin32Err(result, ERROR_UNKNOWN_PROPERTY)); return FALSE; } return TRUE; } BOOLEAN HardwareDeviceUninstall( _In_ HWND ParentWindow, ) { CONFIGRET result; ); { PhShowStatus(ParentWindow, L"Failed to uninstall the device.", 0, CM_MapCrToWin32Err(result, ERROR_UNKNOWN_PROPERTY)); return FALSE; } result = CM_Uninstall_DevInst(deviceInstanceHandle, 0); { PhShowStatus(ParentWindow, L"Failed to uninstall the device.", 0, CM_MapCrToWin32Err(result, ERROR_UNKNOWN_PROPERTY)); return FALSE; } return TRUE; } BOOLEAN HardwareDeviceShowProperties( _In_ HWND WindowHandle, ) { HMODULE devMgrHandle; // [IDX] VOID (WINAPI* DeviceProperties_RunDLL_I)( _In_ HWND hwndStub, _In_ HINSTANCE hAppInstance, _In_ PWSTR lpCmdLine, _In_ INT nCmdShow ); //ULONG (WINAPI *DeviceAdvancedPropertiesW_I)( // _In_opt_ HWND hWndParent, // _In_opt_ PWSTR MachineName, // _In_ PWSTR DeviceID); if (devMgrHandle = PhLoadLibrary(L"devmgr.dll")) { if (DeviceProperties_RunDLL_I = PhGetProcedureAddress(devMgrHandle, "DeviceProperties_RunDLLW", 0)) { PH_FORMAT format[2]; WCHAR formatBuffer[512]; // /DeviceID %s PhInitFormatS(&format[0], L"/DeviceID "); PhInitFormatSR(&format[1], DeviceInstance->sr); if (PhFormatToBuffer(format, RTL_NUMBER_OF(format), formatBuffer, sizeof(formatBuffer), NULL)) { (dmex) NULL, formatBuffer, 0 ); } else { (dmex) NULL, PhaFormatString(L"/DeviceID %s", DeviceInstance->Buffer)->Buffer, 0 ); } } FreeLibrary(devMgrHandle); } return FALSE; } BOOLEAN HardwareDeviceOpenKey( _In_ HWND ParentWindow, _In_ ULONG KeyIndex ) { CONFIGRET result; ULONG keyIndex; HKEY keyHandle; ); { PhShowStatus(ParentWindow, L"Failed to locate the device.", 0, CM_MapCrToWin32Err(result, ERROR_UNKNOWN_PROPERTY)); return FALSE; } switch (KeyIndex) { case 4: default: keyIndex = CM_REGISTRY_HARDWARE; break; case 5: keyIndex = CM_REGISTRY_SOFTWARE; break; case 6: keyIndex = CM_REGISTRY_USER; break; case 7: keyIndex = CM_REGISTRY_CONFIG; break; } if (CM_Open_DevInst_Key( KEY_READ, 0, RegDisposition_OpenExisting, &keyHandle, keyIndex ) == CR_SUCCESS) { PPH_STRING bestObjectName = NULL; PhGetHandleInformation( NtCurrentProcess(), keyHandle, ULONG_MAX, NULL, NULL, NULL, &bestObjectName ); if (bestObjectName) { // HKLM\SYSTEM\ControlSet\Control\Class\ += DEVPKEY_Device_Driver PhShellOpenKey(ParentWindow, bestObjectName); PhDereferenceObject(bestObjectName); } NtClose(keyHandle); } return TRUE; } VOID EspShowDeviceInstanceMenu( _In_ HWND ParentWindow, ) { POINT cursorPos; PPH_EMENU menu; PPH_EMENU subMenu; PPH_EMENU_ITEM selectedItem; GetCursorPos(&cursorPos); menu = PhCreateEMenu(); PhInsertEMenuItem(menu, PhCreateEMenuItem(0, 0, L"Enable", NULL, NULL), ULONG_MAX); PhInsertEMenuItem(menu, PhCreateEMenuItem(0, 1, L"Disable", NULL, NULL), ULONG_MAX); PhInsertEMenuItem(menu, PhCreateEMenuItem(0, 2, L"Restart", NULL, NULL), ULONG_MAX); PhInsertEMenuItem(menu, PhCreateEMenuItem(0, 3, L"Uninstall", NULL, NULL), ULONG_MAX); subMenu = PhCreateEMenuItem(0, 0, L"Open key", NULL, NULL); PhInsertEMenuItem(subMenu, PhCreateEMenuItem(0, 4, L"Hardware", NULL, NULL), ULONG_MAX); PhInsertEMenuItem(subMenu, PhCreateEMenuItem(0, 5, L"Software", NULL, NULL), ULONG_MAX); PhInsertEMenuItem(subMenu, PhCreateEMenuItem(0, 6, L"User", NULL, NULL), ULONG_MAX); PhInsertEMenuItem(subMenu, PhCreateEMenuItem(0, 7, L"Config", NULL, NULL), ULONG_MAX); PhInsertEMenuItem(menu, subMenu, ULONG_MAX); PhInsertEMenuItem(menu, PhCreateEMenuItem(0, 10, L"Properties", NULL, NULL), ULONG_MAX); selectedItem = PhShowEMenu( menu, ParentWindow, PH_ALIGN_LEFT | PH_ALIGN_TOP, cursorPos.x, cursorPos.y ); if (selectedItem && selectedItem->Id != ULONG_MAX) { switch (selectedItem->Id) { case 0: case 1: HardwareDeviceEnableDisable(ParentWindow, DeviceInstance, selectedItem->Id == 0); break; case 2: HardwareDeviceRestart(ParentWindow, DeviceInstance); break; case 3: { if (HardwareDeviceUninstall(ParentWindow, DeviceInstance)) { NOTHING; } } break; case 4: case 5: case 6: case 7: HardwareDeviceOpenKey(ParentWindow, DeviceInstance, selectedItem->Id); break; case 10: HardwareDeviceShowProperties(ParentWindow, DeviceInstance); break; } } PhDestroyEMenu(menu); } VOID EspLoadDeviceInstanceImage( _In_ PPNP_SERVICE_CONTEXT Context, _In_ GUID DeviceClass, _In_ INT ItemIndex ) { HICON smallIcon; CONFIGRET result; ULONG deviceIconPathLength; DEVPROPTYPE deviceIconPathPropertyType; PPH_STRING deviceIconPath; deviceIconPathLength = 0x40; deviceIconPath = PhCreateStringEx(NULL, deviceIconPathLength); if ((result = CM_Get_Class_Property( &DeviceClass, &DEVPKEY_DeviceClass_IconPath, &deviceIconPathPropertyType, (PBYTE)deviceIconPath->Buffer, &deviceIconPathLength, 0 )) != CR_SUCCESS) { result = CM_Get_Class_Property( &DeviceClass, 0 ); } { return; } PhTrimToNullTerminatorString(deviceIconPath); { PPH_STRING dllIconPath; PH_STRINGREF dllPartSr; PH_STRINGREF indexPartSr; LONG64 index = 0; if ( PhSplitStringRefAtChar(&deviceIconPath->sr, L',', &dllPartSr, &indexPartSr) && PhStringToInteger64(&indexPartSr, 10, &index) ) { if (dllIconPath = PhExpandEnvironmentStrings(&dllPartSr)) { if (PhExtractIconEx(dllIconPath, FALSE, (INT)index, &smallIcon, NULL)) { UINT imageIndex = PhImageListAddIcon(Context->ImageList, smallIcon); PhSetListViewItemImageIndex(Context->ListViewHandle, ItemIndex, imageIndex); DestroyIcon(smallIcon); } PhDereferenceObject(dllIconPath); } } } } _Success_(return) BOOLEAN EspQueryDeviceInstanceInformation( _In_ PWSTR DeviceInstanceId, _Out_ DEVINST* DeviceInstanceHandle, _Out_ PPH_STRING* DeviceDescription ) { CONFIGRET result; ULONG bufferSize; PPH_STRING deviceDescription; DEVPROPTYPE devicePropertyType; if (CM_Locate_DevNode( DeviceInstanceId, ) != CR_SUCCESS) { return FALSE; } bufferSize = 0x40; deviceDescription = PhCreateStringEx(NULL, bufferSize); if ((result = CM_Get_DevNode_Property( &DEVPKEY_NAME, &devicePropertyType, (PBYTE)deviceDescription->Buffer, &bufferSize, 0 )) != CR_SUCCESS) { result = CM_Get_DevNode_Property( &DEVPKEY_NAME, &bufferSize, 0 ); } { return FALSE; } PhTrimToNullTerminatorString(deviceDescription); *DeviceInstanceHandle = deviceInstanceHandle; *DeviceDescription = deviceDescription; return TRUE; } BOOLEAN EspEnumerateDriverPnpDevicesAlt( ) { CONFIGRET status; PWSTR deviceIdentifierList; ULONG deviceIdentifierListLength = 0; PWSTR deviceIdentifier; status = CM_Get_Device_ID_List_Size( &deviceIdentifierListLength, CM_GETIDLIST_DONOTGENERATE ); return FALSE; if (deviceIdentifierListLength <= sizeof(UNICODE_NULL)) return FALSE; deviceIdentifierList = PhAllocate(deviceIdentifierListLength * sizeof(WCHAR)); memset(deviceIdentifierList, 0, deviceIdentifierListLength * sizeof(WCHAR)); status = CM_Get_Device_ID_List( deviceIdentifierList, deviceIdentifierListLength, CM_GETIDLIST_DONOTGENERATE ); { return FALSE; } for (deviceIdentifier = deviceIdentifierList; *deviceIdentifier; deviceIdentifier += PhCountStringZ(deviceIdentifier) + 1) { DEVPROP_BOOLEAN devicePresent = DEVPROP_FALSE; GUID classGuid = { 0 }; ULONG bufferSize; if (!EspQueryDeviceInstanceInformation(deviceIdentifier, &deviceInstanceHandle, &deviceDescription)) continue; bufferSize = sizeof(DEVPROP_BOOLEAN); CM_Get_DevNode_Property( &DEVPKEY_Device_IsPresent, (PBYTE)&devicePresent, &bufferSize, 0 ); bufferSize = sizeof(GUID); if (CM_Get_DevNode_Property( &DEVPKEY_Device_ClassGuid, (PBYTE)&classGuid, &bufferSize, 0 ) == CR_SUCCESS) { INT lvItemIndex = PhAddListViewGroupItem( devicePresent ? 0 : 1, MAXINT, PhGetString(deviceDescription), PhCreateString(deviceIdentifier) ); } } return TRUE; } BOOLEAN EspEnumerateDriverPnpDevices( ) { static HRESULT (WINAPI* DevGetObjects_I)( _In_ DEV_OBJECT_TYPE ObjectType, _In_ ULONG QueryFlags, _In_ ULONG cRequestedProperties, _In_reads_opt_(cRequestedProperties) const DEVPROPCOMPKEY *pRequestedProperties, _In_ ULONG cFilterExpressionCount, _In_reads_opt_(cFilterExpressionCount) const DEVPROP_FILTER_EXPRESSION *pFilter, _Out_ PULONG pcObjectCount, _Outptr_result_buffer_maybenull_(*pcObjectCount) const DEV_OBJECT **ppObjects) = NULL; static HRESULT (WINAPI* DevFreeObjects_I)( _In_ ULONG cObjectCount, _In_reads_(cObjectCount) const DEV_OBJECT *pObjects) = NULL; PPH_STRING serviceName = Context->ServiceItem->Name; ULONG deviceCount = 0; PDEV_OBJECT deviceObjects = NULL; DEVPROPCOMPKEY deviceProperties[5]; DEVPROP_FILTER_EXPRESSION deviceFilter[1]; DEVPROPERTY deviceFilterProperty; DEVPROPCOMPKEY deviceFilterCompoundProp; { PVOID cfgmgr32; if (cfgmgr32 = PhLoadLibrary(L"cfgmgr32.dll")) { DevGetObjects_I = PhGetProcedureAddress(cfgmgr32, "DevGetObjects", 0); DevFreeObjects_I = PhGetProcedureAddress(cfgmgr32, "DevFreeObjects", 0); } } if (!(DevGetObjects_I && DevFreeObjects_I)) return FALSE; memset(deviceProperties, 0, sizeof(deviceProperties)); deviceProperties[0].Key = DEVPKEY_Device_InstanceId; deviceProperties[0].Store = DEVPROP_STORE_SYSTEM; deviceProperties[1].Key = DEVPKEY_NAME; // DEVPKEY_Device_FriendlyName deviceProperties[1].Store = DEVPROP_STORE_SYSTEM; deviceProperties[2].Key = DEVPKEY_Device_PDOName; deviceProperties[2].Store = DEVPROP_STORE_SYSTEM; deviceProperties[3].Key = DEVPKEY_Device_ClassGuid; deviceProperties[3].Store = DEVPROP_STORE_SYSTEM; deviceProperties[4].Key = DEVPKEY_Device_IsPresent; deviceProperties[4].Store = DEVPROP_STORE_SYSTEM; memset(&deviceFilterCompoundProp, 0, sizeof(deviceFilterCompoundProp)); deviceFilterCompoundProp.Key = DEVPKEY_Device_Service; deviceFilterCompoundProp.Store = DEVPROP_STORE_SYSTEM; memset(&deviceFilterProperty, 0, sizeof(deviceFilterProperty)); deviceFilterProperty.CompKey = deviceFilterCompoundProp; deviceFilterProperty.Type = DEVPROP_TYPE_STRING; deviceFilterProperty.BufferSize = (ULONG)serviceName->Length + sizeof(UNICODE_NULL); deviceFilterProperty.Buffer = serviceName->Buffer; memset(deviceFilter, 0, sizeof(deviceFilter)); deviceFilter[0].Operator = DEVPROP_OPERATOR_EQUALS_IGNORE_CASE; deviceFilter[0].Property = deviceFilterProperty; if (SUCCEEDED(DevGetObjects_I( DevObjectTypeDevice, DevQueryFlagNone, RTL_NUMBER_OF(deviceProperties), deviceProperties, RTL_NUMBER_OF(deviceFilter), deviceFilter, &deviceCount, &deviceObjects ))) { for (ULONG i = 0; i < deviceCount; i++) { DEV_OBJECT device = deviceObjects[i]; INT lvItemIndex; PPH_STRING deviceName; PH_STRINGREF deviceInterface; PH_STRINGREF displayName; PH_STRINGREF deviceObjectName; PH_STRINGREF firstPart; PH_STRINGREF secondPart; DEVPROP_BOOLEAN present; assert(device.cPropertyCount == RTL_NUMBER_OF(deviceProperties)); deviceInterface.Length = device.pProperties[0].BufferSize; deviceInterface.Buffer = device.pProperties[0].Buffer; displayName.Length = device.pProperties[1].BufferSize; displayName.Buffer = device.pProperties[1].Buffer; deviceObjectName.Length = device.pProperties[2].BufferSize; deviceObjectName.Buffer = device.pProperties[2].Buffer; memcpy_s(&classGuid, sizeof(GUID), device.pProperties[3].Buffer, device.pProperties[3].BufferSize); present = *(PDEVPROP_BOOLEAN)device.pProperties[4].Buffer == DEVPROP_TRUE; // TODO: USBXHCI service: %1 USB %2 eXtensible Host Controller - %3 (Microsoft);(ASMedia,3.0,1.0) if (PhSplitStringRefAtLastChar(&displayName, L';', &firstPart, &secondPart)) deviceName = PhCreateString2(&secondPart); else deviceName = PhCreateString2(&displayName); if (deviceName->Length >= sizeof(UNICODE_NULL) && deviceName->Buffer[deviceName->Length / sizeof(WCHAR)] == UNICODE_NULL) deviceName->Length -= sizeof(UNICODE_NULL); // PhTrimToNullTerminatorString(deviceName); if (deviceObjectName.Length >= sizeof(UNICODE_NULL) && deviceObjectName.Buffer[deviceObjectName.Length / sizeof(WCHAR)] == UNICODE_NULL) deviceObjectName.Length -= sizeof(UNICODE_NULL); // PhTrimToNullTerminatorString(deviceObjectName); if (deviceName && deviceObjectName.Length) { PH_FORMAT format[4]; PhInitFormatSR(&format[0], deviceName->sr); PhInitFormatS(&format[1], L" (PDO: "); PhInitFormatSR(&format[2], deviceObjectName); PhInitFormatC(&format[3], ')'); PhMoveReference(&deviceName, PhFormat(format, RTL_NUMBER_OF(format), 0)); } lvItemIndex = PhAddListViewGroupItem( present ? 0 : 1, MAXINT, PhGetString(deviceName), PhCreateString2(&deviceInterface) ); if (deviceName) PhDereferenceObject(deviceName); } DevFreeObjects_I(deviceCount, deviceObjects); } return TRUE; } VOID EspFreeListViewDiskDriveEntries( ) { ULONG index = ULONG_MAX; while ((index = PhFindListViewItemByFlags( index, LVNI_ALL )) != ULONG_MAX) { PPH_STRING param; if (PhGetListViewItemParam(Context->ListViewHandle, index, &param)) { PhDereferenceObject(param); } } } INT_PTR CALLBACK EspPnPServiceDlgProc( _In_ HWND hwndDlg, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) { PPNP_SERVICE_CONTEXT context; if (uMsg == WM_INITDIALOG) { LPPROPSHEETPAGE propSheetPage = (LPPROPSHEETPAGE)lParam; PPH_SERVICE_ITEM serviceItem = (PPH_SERVICE_ITEM)propSheetPage->lParam; context = PhAllocateZero(sizeof(PNP_SERVICE_CONTEXT)); context->ServiceItem = serviceItem; PhSetWindowContext(hwndDlg, PH_WINDOW_CONTEXT_DEFAULT, context); } else { context = PhGetWindowContext(hwndDlg, PH_WINDOW_CONTEXT_DEFAULT); } if (!context) return FALSE; switch (uMsg) { case WM_INITDIALOG: { context->WindowHandle = hwndDlg; context->ListViewHandle = GetDlgItem(hwndDlg, IDC_LIST); PhCenterWindow(hwndDlg, GetParent(hwndDlg)); PhSetListViewStyle(context->ListViewHandle, FALSE, TRUE); PhSetControlTheme(context->ListViewHandle, L"explorer"); PhAddListViewColumn(context->ListViewHandle, 0, 0, 0, LVCFMT_LEFT, 350, L"PnP Devices"); PhSetExtendedListView(context->ListViewHandle); if (PhWindowsVersion > WINDOWS_7) ListView_EnableGroupView(context->ListViewHandle, TRUE); PhAddListViewGroup(context->ListViewHandle, 0, L"Connected"); PhAddListViewGroup(context->ListViewHandle, 1, L"Disconnected"); context->ImageList = PhImageListCreate( 24, // GetSystemMetrics(SM_CXSMICON) 24, // GetSystemMetrics(SM_CYSMICON) ILC_MASK | ILC_COLOR32, 1, 1); ListView_SetImageList(context->ListViewHandle, context->ImageList, LVSIL_SMALL); if (context->ServiceItem->Type & SERVICE_DRIVER) { PhSetDialogItemText(hwndDlg, IDC_MESSAGE, L"This service has registered the following PnP devices:"); if (!EspEnumerateDriverPnpDevices(context)) { EspEnumerateDriverPnpDevicesAlt(context); } } else { PhSetDialogItemText(hwndDlg, IDC_MESSAGE, L"This service type doesn't support PnP devices."); ShowWindow(context->ListViewHandle, SW_HIDE); } PhInitializeWindowTheme(hwndDlg, !!PhGetIntegerSetting(L"EnableThemeSupport")); } break; case WM_DESTROY: { PhRemoveWindowContext(hwndDlg, PH_WINDOW_CONTEXT_DEFAULT); EspFreeListViewDiskDriveEntries(context); PhFree(context); } break; case WM_SIZE: { } break; case WM_NOTIFY: { LPNMHDR header = (LPNMHDR)lParam; switch (header->code) { case PSN_QUERYINITIALFOCUS: SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LPARAM)context->ListViewHandle); return TRUE; case NM_RCLICK: { { EspShowDeviceInstanceMenu(hwndDlg, deviceInstance); ListView_DeleteAllItems(context->ListViewHandle); { } } } break; case NM_DBLCLK: { { HardwareDeviceShowProperties(hwndDlg, deviceInstance); } } break; } } break; case WM_CTLCOLORBTN: return HANDLE_WM_CTLCOLORBTN(hwndDlg, wParam, lParam, PhWindowThemeControlColor); case WM_CTLCOLORDLG: return HANDLE_WM_CTLCOLORDLG(hwndDlg, wParam, lParam, PhWindowThemeControlColor); case WM_CTLCOLORSTATIC: return HANDLE_WM_CTLCOLORSTATIC(hwndDlg, wParam, lParam, PhWindowThemeControlColor); } return FALSE; }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-16252.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-16252.jsonl"}]
polynomials: collect -------------------- Given: Collect the terms in 122*n**3 - 134*n**2 + 118*n**3 + 9*n**2. Solution: 240*n**3 - 125*n**2 Given: Collect the terms in 4*v**3 - v**3 + 2*v**3 - v**3 - 3*v**3. Solution: v**3 Given: Collect the terms in 3*z + 2865*z**2 + 1625 + 1773 - 2869*z**2 - 3*z - 5163 + 1765. Solution: -4*z**2 Given: Collect the terms in -11*s**2 + 8*s**2 + 0*s + 0*s - 2. Solution: -3*s**2 - 2 Given: Collect the terms in 219*h + h**3 - 436*h + 217*h. Solution: h**3 Given: Collect the terms in -70 - 11 - 2 - 5*d + 3. Solution: -5*d - 80 Given: Collect the terms in -506*d**3 + 3*d**2 - d**2 + 46*d**3. Solution: -460*d**3 + 2*d**2 Given: Collect the terms in -43 + 1307*j**2 + 91 - 48. Solution: 1307*j**2 Given: Collect the terms in -2402*j - 6687*j + 883*j. Solution: -8206*j Given: Collect the terms in -28328861*v**2 + 0 + 56657618*v**2 - 28328847*v**2 + 2*v + 0. Solution: -90*v**2 + 2*v Given: Collect the terms in 7*t + t**2 + 1468*t**3 - 3*t + 167*t**3. Solution: 1635*t**3 + t**2 + 4*t Given: Collect the terms in 5*p**2 + 142*p - 292*p + 150*p. Solution: 5*p**2 Given: Collect the terms in 397 + 515 - 22*j - 912. Solution: -22*j Given: Collect the terms in 45 - 45 - 104*z**3 + 848*z**3. Solution: 744*z**3 Given: Collect the terms in 49*k + 19880 - 19880 + 2*k**2 - 49*k. Solution: 2*k**2 Given: Collect the terms in 33040*s - 1 - 3 + 4. Solution: 33040*s Given: Collect the terms in 101*m + 114*m - 313*m + 70*m + 125*m. Solution: 97*m Given: Collect the terms in 9*w**3 + 2*w**3 - 2 + 2. Solution: 11*w**3 Given: Collect the terms in 16*y - 10*y + 5*y**2 - 6*y. Solution: 5*y**2 Given: Collect the terms in -138858771*x**3 + 138858849*x**3 + 14*x**2 - 14*x**2. Solution: 78*x**3 Given: Collect the terms in -13*v + 12*v + 13*v. Solution: 12*v Given: Collect the terms in 259562227 - 16*t**2 - 259562227. Solution: -16*t**2 Given: Collect the terms in 32*n**3 - 18*n**3 - 10*n**3. Solution: 4*n**3 Given: Collect the terms in -385*p**2 - 1168*p**3 + p + 2 - 3 + 1. Solution: -1168*p**3 - 385*p**2 + p Given: Collect the terms in -48*g**2 + 3 + 50*g**2 - 73*g - 3. Solution: 2*g**2 - 73*g Given: Collect the terms in -4*y**2 - 28*y + 5*y - 14*y - 2 + y**2. Solution: -3*y**2 - 37*y - 2 Given: Collect the terms in -9 - 74*u**3 + 147*u**3 - 1 + 8 - 34*u + 34*u - 46*u**3. Solution: 27*u**3 - 2 Given: Collect the terms in -14555*k**2 - 56354*k**2 - 58254*k**2 + 23878*k**2. Solution: -105285*k**2 Given: Collect the terms in -321*q**2 - 322*q**2 + 643*q**2 - 5336*q**3. Solution: -5336*q**3 Given: Collect the terms in -4 - 23*f**2 - 21 + 10*f**2 - 2 + 22 + 19*f**2. Solution: 6*f**2 - 5 Given: Collect the terms in -11372*o**3 - 11371*o**3 + 3420*o**2 + 22744*o**3. Solution: o**3 + 3420*o**2 Given: Collect the terms in -413853*h - 413848*h + 827668*h. Solution: -33*h Given: Collect the terms in 3692*q + 1513*q + 5733*q + 2297*q. Solution: 13235*q Given: Collect the terms in q - 3*q + 2*q + 32491*q**3 - 32497*q**3. Solution: -6*q**3 Given: Collect the terms in 5857*h + 203 - 202 + 53*h**3 - 5857*h. Solution: 53*h**3 + 1 Given: Collect the terms in -2*m + m - 4 + 11*m. Solution: 10*m - 4 Given: Collect the terms in -14514*i - i**3 + 321*i**2 - 2 - 158*i**2 - 162*i**2. Solution: -i**3 + i**2 - 14514*i - 2 Given: Collect the terms in 18*b + 2*b + 22*b - 4*b. Solution: 38*b Given: Collect the terms in 5936*o**3 - 17*o**2 + 17*o**2. Solution: 5936*o**3 Given: Collect the terms in 917092*y - 2751258*y + 917084*y + 917080*y. Solution: -2*y Given: Collect the terms in b**2 + 160 - 160. Solution: b**2 Given: Collect the terms in -44 + 157 - 43 - 70 - k**2. Solution: -k**2 Given: Collect the terms in 43*a + 1300*a - 1 + 115*a. Solution: 1458*a - 1 Given: Collect the terms in 238*o**3 + 112*o**3 + 98*o**3. Solution: 448*o**3 Given: Collect the terms in 1972*m - 1972*m + 3570*m**3 - 1189*m**3 - 2379*m**3. Solution: 2*m**3 Given: Collect the terms in 1033*x + 480262*x**2 - 1033*x. Solution: 480262*x**2 Given: Collect the terms in 58*b - 52*b**2 + b**3 - 58*b + 89*b**2 - 37*b**2. Solution: b**3 Given: Collect the terms in -257*p**2 - 279*p**2 - 262*p**2 + 790*p**2. Solution: -8*p**2 Given: Collect the terms in 121 + 117 - f - 350 + 112. Solution: -f Given: Collect the terms in -380*w - 79 + 79. Solution: -380*w Given: Collect the terms in 16 + t**2 - 10 + 16 + 28. Solution: t**2 + 50 Given: Collect the terms in -19*c + 64*c - 19*c + 1 - 13*c. Solution: 13*c + 1 Given: Collect the terms in 546*w**2 - 1086*w**2 - 2*w**3 + 540*w**2. Solution: -2*w**3 Given: Collect the terms in -487*l**2 + 54*l + 245*l**2 + 1 + 244*l**2 - 1. Solution: 2*l**2 + 54*l Given: Collect the terms in -1079*o**2 + 533*o**2 + 546*o**2 + 8*o**3. Solution: 8*o**3 Given: Collect the terms in 11*d**3 - 59*d**3 + 6*d**3 + 13*d**3 + 22*d**3. Solution: -7*d**3 Given: Collect the terms in -27941*q**2 - 25673*q**2 + 53611*q**2. Solution: -3*q**2 Given: Collect the terms in 53356 + i**3 - 53356. Solution: i**3 Given: Collect the terms in 61 + 11893*t**2 + 67 - 214 - t**3 + 86. Solution: -t**3 + 11893*t**2 Given: Collect the terms in 8*a**2 + 29*a - 14*a - 18*a. Solution: 8*a**2 - 3*a Given: Collect the terms in 31*p + 23*p + p**3 - 54*p. Solution: p**3 Given: Collect the terms in 46797 - 12*i**2 - 46797 + 18*i**2 + 22*i**2. Solution: 28*i**2 Given: Collect the terms in -26841*o + o**2 - 24*o**3 + 26841*o - o**2. Solution: -24*o**3 Given: Collect the terms in -33*z**2 + 12*z**2 + 7*z**2 + 6*z**2. Solution: -8*z**2 Given: Collect the terms in 23*o + 4*o + 12*o**3 + 2*o. Solution: 12*o**3 + 29*o Given: Collect the terms in -13*r**3 + 17*r**3 + 14*r**3. Solution: 18*r**3 Given: Collect the terms in -4711878*z**3 - 4712557*z**3 + 9424428*z**3. Solution: -7*z**3 Given: Collect the terms in -80 - 3 - 2*m - 73 - 24*m**2 + 5*m**2 - 4*m**2. Solution: -23*m**2 - 2*m - 156 Given: Collect the terms in 2066*f**2 - 819*f**2 - 568*f**2 - 673*f**2. Solution: 6*f**2 Given: Collect the terms in 61*j - 13*j - 20*j - 27*j + 376. Solution: j + 376 Given: Collect the terms in 23*f**2 + 9*f**2 + 7*f**2 - 2 + 7*f**2. Solution: 46*f**2 - 2 Given: Collect the terms in 26*o - 461*o**2 + 187*o**2 - 26*o - 305. Solution: -274*o**2 - 305 Given: Collect the terms in 3*j**2 + 0*j**3 + 2*j - 3*j**2 - 93*j**3. Solution: -93*j**3 + 2*j Given: Collect the terms in -26*y + 515 + 24*y - 515. Solution: -2*y Given: Collect the terms in -2*w**2 - w**2 - 2*w**2 + 11*w**2. Solution: 6*w**2 Given: Collect the terms in 6*b**3 + 40*b**3 + 6*b**3 - 14*b**3 - 16*b**3. Solution: 22*b**3 Given: Collect the terms in -116*g**2 - 43*g**3 + 19*g**3 + 38*g**3 + 116*g**2. Solution: 14*g**3 Given: Collect the terms in -t**2 - 5*t**2 - 2*t**2 - 6*t**2. Solution: -14*t**2 Given: Collect the terms in 47*x**2 + 71*x**2 + 29109819*x - 29109818*x. Solution: 118*x**2 + x Given: Collect the terms in -o**2 - 114*o + 148*o - 178*o + 14. Solution: -o**2 - 144*o + 14 Given: Collect the terms in 11186*p**3 - 3*p - 5*p + 2*p + 5*p - 3. Solution: 11186*p**3 - p - 3 Given: Collect the terms in 20*v - 11*v + 16*v - 71*v**3 + 2*v**3. Solution: -69*v**3 + 25*v Given: Collect the terms in -2 - 87*d - 2 + 0 + 28*d. Solution: -59*d - 4 Given: Collect the terms in 7*c**2 - 34*c**3 + 11*c**3 - 6*c**2. Solution: -23*c**3 + c**2 Given: Collect the terms in -35*c**2 - 206*c + 69*c**2 - 36*c**2. Solution: -2*c**2 - 206*c Given: Collect the terms in 60*y + 11*y**3 + 60*y - 120*y - 15*y**3. Solution: -4*y**3 Given: Collect the terms in 13*k + 5*k - 19*k - 2 + 7. Solution: -k + 5 Given: Collect the terms in 295 - 402 + 107 + 75*f. Solution: 75*f Given: Collect the terms in -3*x**2 + 13*x**2 - 29*x**2 + 19*x**2 + 358 + x**3 - 358. Solution: x**3 Given: Collect the terms in -9 + 173*t - 179 - 185*t. Solution: -12*t - 188 Given: Collect the terms in -7391*i**2 + 37482*i**2 + 12*i - 12*i. Solution: 30091*i**2 Given: Collect the terms in -71*f**3 - 11 + 48132537*f**2 - 48132537*f**2 + 0. Solution: -71*f**3 - 11 Given: Collect the terms in -42868*s**3 - 42867*s**3 + 85729*s**3 + 166*s**2 - 166*s**2. Solution: -6*s**3 Given: Collect the terms in 2 + 1116*c**2 - 352*c**2 + 167*c**2 - 2. Solution: 931*c**2 Given: Collect the terms in 2052190 - 3*v - 2052190 - 3*v**2. Solution: -3*v**2 - 3*v Given: Collect the terms in -u**3 - 2674*u**2 + 2674*u**2 + 0*u**3 - 4*u**3. Solution: -5*u**3 Given: Collect the terms in -46 + 275*m - 70*m + 203*m. Solution: 408*m - 46 Given: Collect the terms in 8*j + 9*j - 2*j**2 - 25*j + 8*j. Solution: -2*j**2 Given: Collect the terms in -2*o + 2*o + 4*o + 3*o. Solution: 7*o Given: Collect the terms in -8454*v + 2151*v + 2159*v + 2150*v + 1995*v. Solution: v Given: Collect the terms in 1396576*g + 2 + 1396572*g + 7*g**3 - 2 - 2793148*g + 8*g**2. Solution: 7*g**3 + 8*g**2 Given: Collect the terms in -11159*y - 22000*y - 7682*y. Solution: -40841*y Given: Collect the terms in -7*h**2 - 1805146*h + 1805146*h + 5*h**2 + 11*h**2. Solution: 9*h**2 Given: Collect the terms in 590*p**2 + 7857*p**2 - 1989*p**2. Solution: 6458*p**2 Given: Collect the terms in -173500*i**2 + 347008*i**2 - 173510*i**2. Solution: -2*i**2 Given: Collect the terms in -1744521*c + 872235*c + 872281*c. Solution: -5*c Given: Collect the terms in -30 + h**3 + 96 + 6. Solution: h**3 + 72 Given: Collect the terms in -1258*f - 6452*f - 523*f - 1680*f - 2. Solution: -9913*f - 2 Given: Collect the terms in -3*b**3 - 2*b**3 + 8*b**3. Solution: 3*b**3 Given: Collect the terms in 81*f**2 - 6*f**2 + 77*f**2 + 15*f**3 - 152*f**2. Solution: 15*f**3 Given: Collect the terms in 87*x**2 + 71*x**2 - 352*x**2 + 75*x**2 + 60*x**2 + 68*x**2. Solution: 9*x**2 Given: Collect the terms in 43 + 6*m + 4*m - 166 + 120. Solution: 10*m - 3 Given: Collect the terms in -11*g**2 + 55*g**3 + 2*g**2 - 59*g**3. Solution: -4*g**3 - 9*g**2 Given: Collect the terms in -19*c - c**2 - 13*c - c - 501*c**3 + 60*c - 5*c. Solution: -501*c**3 - c**2 + 22*c Given: Collect the terms in -t**2 + 6*t**2 - 494*t + 519*t. Solution: 5*t**2 + 25*t Given: Collect the terms in -753*j**3 - 705*j**3 + 1450*j**3. Solution: -8*j**3 Given: Collect the terms in 9*k**3 + 27*k**3 - 10*k**3. Solution: 26*k**3 Given: Collect the terms in 187*j**2 + 282 - 282 - 97*j**2 - 96*j**2. Solution: -6*j**2 Given: Collect the terms in -12512*o**3 + 6195*o**3 + 6250*o**3. Solution: -67*o**3 Given: Collect the terms in -2651880 - 2*g**2 + g**2 + 2651880 + 9*g**2. Solution: 8*g**2 Given: Collect the terms in 6*k**2 + 9*k**2 + 24*k**2. Solution: 39*k**2 Given: Collect the terms in -80*k**3 + 128*k**3 - 46*k**3. Solution: 2*k**3 Given: Collect the terms in -1267332*i + 175763*i - 602605*i + 133300*i. Solution: -1560874*i Given: Collect the terms in 667*y**3 - 1532*y**3 + 871*y**3. Solution: 6*y**3 Given: Collect the terms in 271*d**3 - 142*d**3 - 39*d**3 - 2 - 127*d**3. Solution: -37*d**3 - 2 Given: Collect the terms in -21*d + 0 + 50*d + 0. Solution: 29*d Given: Collect the terms in 1258 - 1258 - 7*f**3. Solution: -7*f**3 Given: Collect the terms in 246 + 246 - 496 + 29*m. Solution: 29*m - 4 Given: Collect the terms in -2 - 2022808*h + 0 + 2. Solution: -2022808*h Given: Collect the terms in -35 + 1706*m**2 + 40 - 5. Solution: 1706*m**2 Given: Collect the terms in 130363*n + 124479*n - 254839*n. Solution: 3*n Given: Collect the terms in -141*m + 3*m**2 - 142*m - 133*m + 419*m. Solution: 3*m**2 + 3*m Given: Collect the terms in -361*j**2 + 717*j**2 - 358*j**2. Solution: -2*j**2 Given: Collect the terms in -1111*d + 601*d + 13 - 702*d - 430*d. Solution: -1642*d + 13 Given: Collect the terms in -10306*x + 10306*x + 4*x**2. Solution: 4*x**2 Given: Collect the terms in -83*b - 9 + 9 - 75*b + 25*b. Solution: -133*b Given: Collect the terms in -336694355*c + c**3 - 26 + 336694355*c. Solution: c**3 - 26 Given: Collect the terms in 30*k**2 + 17*k**2 - 11*k**2. Solution: 36*k**2 Given: Collect the terms in -4 + 195*a + 47*a**2 + 3 - 21*a**2 - 28*a**2. Solution: -2*a**2 + 195*a - 1 Given: Collect the terms in 5 - 1 - 165381001668*o + 165381001665*o - 4. Solution: -3*o Given: Collect the terms in -14*m**2 + 369 - 1112 + 376 + 367. Solution: -14*m**2 Given: Collect the terms in -516*n**2 - 3364*n**2 - 1585*n**2. Solution: -5465*n**2 Given: Collect the terms in -9266*l**3 + 8215*l**3 + 39034*l**3 + 89652*l**3. Solution: 127635*l**3 Given: Collect the terms in -4107834*l - 4107829*l + 8215606*l. Solution: -57*l Given: Collect the terms in -15*u**2 - 6*u**2 + 18*u**2. Solution: -3*u**2 Given: Collect the terms in -123120 - 2*q + 123120. Solution: -2*q Given: Collect the terms in -4*t**2 - 7*t**2 - 365 + 86 - 11*t**2 + 10*t**2. Solution: -12*t**2 - 279 Given: Collect the terms in 152674*v + 12*v**3 - 152674*v. Solution: 12*v**3 Given: Collect the terms in -3*j**2 + 38*j + 70*j - 198*j + 42*j + 48*j. Solution: -3*j**2 Given: Collect the terms in -332 - 334 - 13*h - 332 + 1329 - 331. Solution: -13*h Given: Collect the terms in 24*w - 140*w - 133*w. Solution: -249*w Given: Collect the terms in 2 - 1562217*j + 3124501*j - 1562041*j. Solution: 243*j + 2 Given: Collect the terms in -3 - 58*j**2 + 4 - 2. Solution: -58*j**2 - 1 Given: Collect the terms in -f**2 - 4*f**2 + f**2. Solution: -4*f**2<|endoftext|>numbers: list prime factors --------------------------- Ask: List the prime factors of 11237. Eval: 17, 661 Ask: List the prime factors of 22790595. Eval: 3, 5, 19, 79967 Ask: What are the prime factors of 1903063744? Eval: 2, 569, 52259 Ask: What are the prime factors of 2020320852? Eval: 2, 3, 11, 15305461 Ask: List the prime factors of 6558. Eval: 2, 3, 1093 Ask: List the prime factors of 489166309. Eval: 53, 137, 67369 Ask: What are the prime factors of 31204? Eval: 2, 29, 269 Ask: What are the prime factors of 1606? Eval: 2, 11, 73 Ask: List the prime factors of 12313. Eval: 7, 1759 Ask: List the prime factors of 8433. Eval: 3, 937 Ask: What are the prime factors of 31588231? Eval: 587, 53813 Ask: List the prime factors of 5898. Eval: 2, 3, 983 Ask: List the prime factors of 303471. Eval: 3, 7, 4817 Ask: List the prime factors of 1173575377. Eval: 13, 127, 54679 Ask: List the prime factors of 1409. Eval: 1409 Ask: What are the prime factors of 40022? Eval: 2, 20011 Ask: What are the prime factors of 14262? Eval: 2, 3, 2377 Ask: List the prime factors of 386652064. Eval: 2, 157, 76961 Ask: List the prime factors of 122319909. Eval: 3, 89, 109, 467 Ask: What are the prime factors of 33192858? Eval: 2, 3, 5532143 Ask: List the prime factors of 1290237. Eval: 3, 13, 33083 Ask: List the prime factors of 887. Eval: 887 Ask: What are the prime factors of 158214647? Eval: 158214647 Ask: What are the prime factors of 439722? Eval: 2, 3, 17, 479 Ask: What are the prime factors of 602178? Eval: 2, 3, 100363 Ask: What are the prime factors of 24592? Eval: 2, 29, 53 Ask: What are the prime factors of 3443650? Eval: 2, 5, 7, 9839 Ask: List the prime factors of 79812065. Eval: 5, 19, 227, 3701 Ask: What are the prime factors of 4443450665? Eval: 5, 367, 1297, 1867 Ask: What are the prime factors of 1021? Eval: 1021 Ask: List the prime factors of 199251535. Eval: 5, 7, 5692901 Ask: What are the prime factors of 4238? Eval: 2, 13, 163 Ask: List the prime factors of 37345989. Eval: 3, 3037, 4099 Ask: What are the prime factors of 85040? Eval: 2, 5, 1063 Ask: What are the prime factors of 814? Eval: 2, 11, 37 Ask: List the prime factors of 110858347. Eval: 5717, 19391 Ask: What are the prime factors of 26628? Eval: 2, 3, 7, 317 Ask: What are the prime factors of 5483? Eval: 5483 Ask: List the prime factors of 291985919. Eval: 1201, 243119 Ask: What are the prime factors of 7849054? Eval: 2, 3924527 Ask: List the prime factors of 793419470. Eval: 2, 5, 197, 402751 Ask: List the prime factors of 252912. Eval: 2, 3, 11, 479 Ask: What are the prime factors of 14424660? Eval: 2, 3, 5, 127, 631 Ask: What are the prime factors of 4993? Eval: 4993 Ask: List the prime factors of 21108. Eval: 2, 3, 1759 Ask: List the prime factors of 217833106. Eval: 2, 397, 274349 Ask: List the prime factors of 218000517. Eval: 3, 7, 1381, 7517 Ask: What are the prime factors of 7807209? Eval: 3, 43, 60521 Ask: List the prime factors of 27027726. Eval: 2, 3, 11, 47, 8713 Ask: What are the prime factors of 39568026? Eval: 2, 3, 131, 50341 Ask: List the prime factors of 2811. Eval: 3, 937 Ask: What are the prime factors of 5809041? Eval: 3, 7, 19, 23, 211 Ask: What are the prime factors of 737254? Eval: 2, 7, 7523 Ask: What are the prime factors of 58196? Eval: 2, 14549 Ask: What are the prime factors of 437683876? Eval: 2, 7, 2233081 Ask: List the prime factors of 94921. Eval: 23, 4127 Ask: What are the prime factors of 890451? Eval: 3, 98939 Ask: What are the prime factors of 1930594411? Eval: 11831, 163181 Ask: What are the prime factors of 8940? Eval: 2, 3, 5, 149 Ask: List the prime factors of 6104547. Eval: 3, 17, 2347 Ask: List the prime factors of 15223232. Eval: 2, 31, 7673 Ask: What are the prime factors of 10215? Eval: 3, 5, 227 Ask: What are the prime factors of 3308431? Eval: 7, 251, 269 Ask: What are the prime factors of 3541277? Eval: 19, 29, 6427 Ask: List the prime factors of 2189. Eval: 11, 199 Ask: What are the prime factors of 414528? Eval: 2, 3, 17, 127 Ask: List the prime factors of 411. Eval: 3, 137 Ask: What are the prime factors of 295374910? Eval: 2, 5, 71, 643, 647 Ask: List the prime factors of 11790791. Eval: 29, 406579 Ask: What are the prime factors of 3692444? Eval: 2, 7, 18839 Ask: What are the prime factors of 555227871? Eval: 3, 11, 17, 127, 7793 Ask: What are the prime factors of 399772? Eval: 2, 17, 5879 Ask: List the prime factors of 905. Eval: 5, 181 Ask: What are the prime factors of 5309424394? Eval: 2, 17, 223, 307, 2281 Ask: List the prime factors of 212720. Eval: 2, 5, 2659 Ask: What are the prime factors of 6876? Eval: 2, 3, 191 Ask: List the prime factors of 8393990202. Eval: 2, 3, 13, 19, 29, 21701 Ask: What are the prime factors of 9658368? Eval: 2, 3, 131 Ask: What are the prime factors of 42998738? Eval: 2, 241, 89209 Ask: What are the prime factors of 1637738? Eval: 2, 23, 35603 Ask: List the prime factors of 5797151616. Eval: 2, 3, 809, 18661 Ask: What are the prime factors of 365661959? Eval: 13, 17, 1654579 Ask: List the prime factors of 179053928. Eval: 2, 17, 53, 24841 Ask: List the prime factors of 6741849980. Eval: 2, 5, 9011, 37409 Ask: What are the prime factors of 16447519? Eval: 11, 41, 36469 Ask: What are the prime factors of 925624955? Eval: 5, 307, 603013 Ask: What are the prime factors of 3810306439? Eval: 313, 12173503 Ask: What are the prime factors of 190345? Eval: 5, 38069 Ask: What are the prime factors of 17597377? Eval: 7, 113, 22247 Ask: What are the prime factors of 1639797041? Eval: 1639797041 Ask: What are the prime factors of 74005? Eval: 5, 19, 41 Ask: What are the prime factors of 58713053? Eval: 7, 17, 521, 947 Ask: What are the prime factors of 1313456? Eval: 2, 103, 797 Ask: What are the prime factors of 2282775520? Eval: 2, 5, 19, 31, 24223 Ask: What are the prime factors of 631562? Eval: 2, 29, 10889 Ask: What are the prime factors of 4568? Eval: 2, 571 Ask: List the prime factors of 367216776. Eval: 2, 3, 223, 22871 Ask: What are the prime factors of 1449587? Eval: 1449587 Ask: List the prime factors of 27828. Eval: 2, 3, 773 Ask: List the prime factors of 29690208. Eval: 2, 3, 103091 Ask: What are the prime factors of 437776886? Eval: 2, 139, 1574737 Ask: What are the prime factors of 1558? Eval: 2, 19, 41 Ask: What are the prime factors of 978187781? Eval: 978187781 Ask: List the prime factors of 80903856. Eval: 2, 3, 11, 73, 2099 Ask: What are the prime factors of 129333169? Eval: 7, 18476167 Ask: What are the prime factors of 114947606? Eval: 2, 19, 23, 131519 Ask: What are the prime factors of 133091788? Eval: 2, 29, 503, 2281 Ask: What are the prime factors of 1928021? Eval: 17, 23, 4931 Ask: List the prime factors of 713766298. Eval: 2, 7, 1319, 38653 Ask: List the prime factors of 257. Eval: 257 Ask: What are the prime factors of 127436561? Eval: 7, 3583, 5081 Ask: List the prime factors of 38687. Eval: 11, 3517 Ask: List the prime factors of 61031. Eval: 61031 Ask: What are the prime factors of 15640? Eval: 2, 5, 17, 23 Ask: List the prime factors of 32920. Eval: 2, 5, 823 Ask: What are the prime factors of 26788? Eval: 2, 37, 181 Ask: List the prime factors of 43109638. Eval: 2, 11, 13, 71, 193 Ask: List the prime factors of 757738916. Eval: 2, 11, 17221339 Ask: What are the prime factors of 1919? Eval: 19, 101 Ask: List the prime factors of 952360798. Eval: 2, 476180399 Ask: What are the prime factors of 2794718? Eval: 2, 1397359 Ask: List the prime factors of 1181756. Eval: 2, 295439 Ask: List the prime factors of 34634. Eval: 2, 17317 Ask: List the prime factors of 546268305. Eval: 3, 5, 11, 3310717 Ask: What are the prime factors of 179926892? Eval: 2, 67, 671369 Ask: What are the prime factors of 101108172? Eval: 2, 3, 11, 765971 Ask: What are the prime factors of 15788? Eval: 2, 3947 Ask: What are the prime factors of 2042? Eval: 2, 1021 Ask: What are the prime factors of 17021? Eval: 17021 Ask: List the prime factors of 312. Eval: 2, 3, 13 Ask: What are the prime factors of 799374? Eval: 2, 3, 17, 461 Ask: What are the prime factors of 2946637303? Eval: 36341, 81083 Ask: List the prime factors of 206813. Eval: 206813 Ask: What are the prime factors of 168836007? Eval: 3, 56278669 Ask: What are the prime factors of 769677? Eval: 3, 173, 1483 Ask: What are the prime factors of 3816518? Eval: 2, 1908259 Ask: What are the prime factors of 2639? Eval: 7, 13, 29 Ask: List the prime factors of 325. Eval: 5, 13 Ask: What are the prime factors of 230486? Eval: 2, 17, 6779 Ask: What are the prime factors of 2351? Eval: 2351 Ask: List the prime factors of 28030060. Eval: 2, 5, 41, 34183 Ask: List the prime factors of 783485. Eval: 5, 71, 2207 Ask: What are the prime factors of 13780555? Eval: 5, 2756111 Ask: List the prime factors of 2110426736. Eval: 2, 11, 151, 79411 Ask: List the prime factors of 16085. Eval: 5, 3217 Ask: What are the prime factors of 751? Eval: 751 Ask: What are the prime factors of 9881? Eval: 41, 241 Ask: What are the prime factors of 490903? Eval: 7, 19, 3691 Ask: What are the prime factors of 16130618? Eval: 2, 7, 1152187 Ask: What are the prime factors of 79695? Eval: 3, 5, 7, 11, 23 Ask: What are the prime factors of 7370925? Eval: 3, 5, 23, 4273 Ask: What are the prime factors of 557816458? Eval: 2, 919, 303491 Ask: What are the prime factors of 1817901? Eval: 3, 19, 10631 Ask: What are the prime factors of 713305561? Eval: 22247, 32063 Ask: List the prime factors of 4067. Eval: 7, 83 Ask: List the prime factors of 28940454. Eval: 2, 3, 1093, 1471 Ask: What are the prime factors of 1487? Eval: 1487 Ask: List the prime factors of 18473851. Eval: 11, 251, 6691 Ask: List the prime factors of 182145. Eval: 3, 5, 12143 Ask: List the prime factors of 6394. Eval: 2, 23, 139 Ask: What are the prime factors of 326799? Eval: 3, 11, 3301 Ask: What are the prime factors of 1236723749? Eval: 79, 2671, 5861 Ask: What are the prime factors of 1004826180? Eval: 2, 3, 5, 16747103 Ask: What are the prime factors of 135682? Eval: 2, 179, 379 Ask: What are the prime factors of 945177203? Eval: 17, 23, 397, 6089 Ask: What are the prime factors of 730501028? Eval: 2, 43, 463, 9173 Ask: List the prime factors of 192947191. Eval: 157, 1228963 Ask: What are the prime factors of 8705022? Eval: 2, 3, 157, 9241 Ask: List the prime factors of 55404. Eval: 2, 3, 19 Ask: What are the prime factors of 2231? Eval: 23, 97 Ask: What are the prime factors of 194573142? Eval: 2, 3, 10809619 Ask: What are the prime factors of 90534? Eval: 2, 3, 79, 191 Ask: What are the prime factors of 967492525? Eval: 5, 17, 7877 Ask: What are the prime factors of 595074? Eval: 2, 3, 41, 59 Ask: List the prime factors of 365197. Eval: 7, 29, 257 Ask: What are the prime factors of 994723437? Eval: 3, 331574479 Ask: What are the prime factors of 607611235? Eval: 5, 7, 11, 109, 14479 Ask: What are the prime factors of 39286? Eval: 2, 13, 1511 Ask: What are the prime factors of 2811191672? Eval: 2, 17, 419, 49333 Ask: What are the prime factors of 795? Eval: 3, 5, 53 Ask: List the prime factors of 140097. Eval: 3, 17, 41, 67 Ask: List the prime factors of 1589. Eval: 7, 227 Ask: What are the prime factors of 20641? Eval: 20641 Ask: What are the prime factors of 25746377? Eval: 25746377 Ask: What are the prime factors of 28287017? Eval: 11, 233777 Ask: What are the prime factors of 1775755394? Eval: 2, 7, 1637, 11069 Ask: What are the prime factors of 18089959? Eval: 18089959 Ask: List the prime factors of 385. Eval: 5, 7, 11 Ask: List the prime factors of 6522. Eval: 2, 3, 1087 Ask: List the prime factors of 435691. Eval: 293, 1487 Ask: List the prime factors of 235325421. Eval: 3, 107, 244367 Ask: What are the prime factors of 9675? Eval: 3, 5, 43 Ask: List the prime factors of 553548. Eval: 2, 3, 163, 283 Ask: List the prime factors of 178731. Eval: 3, 7, 2837 Ask: List the prime factors of 7134. Eval: 2, 3, 29, 41 Ask: What are the prime factors of 1488? Eval: 2, 3, 31 Ask: List the prime factors of 6715. Eval: 5, 17, 79 Ask: List the prime factors of 568669768. Eval: 2, 71083721 Ask: What are the prime factors of 10300191? Eval: 3, 11, 29, 47, 229 Ask: What are the prime factors of 4124738? Eval: 2, 103, 20023 Ask: List the prime factors of 208322410. Eval: 2, 5, 211, 98731 Ask: List the prime factors of 60632. Eval: 2, 11, 13, 53 Ask: What are the prime factors of 217? Eval: 7, 31 Ask: What are the prime factors of 11390? Eval: 2, 5, 17, 67 Ask: What are the prime factors of 1509960279? Eval: 3, 2801, 179693 Ask: What are the prime factors of 849? Eval: 3, 283 Ask: What are the prime factors of 26209? Eval: 26209 Ask: What are the prime factors of 7442941? Eval: 11, 151, 4481 Ask: What are the prime factors of 8048356? Eval: 2, 199, 10111 Ask: What are the prime factors of 766542058? Eval: 2, 12437, 30817 Ask: What are the prime factors of 5513697? Eval: 3, 7, 29173 Ask: What are the prime factors of 1041500? Eval: 2, 5, 2083 Ask: What are the prime factors of 23857? Eval: 23857 Ask: What are the prime factors of 6069382? Eval: 2, 11, 275881 Ask: List the prime factors of 447953. Eval: 11, 193, 211
[{"idx": "txt360/polynomials__collect_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-3.jsonl"}, {"idx": "txt360/numbers__list_prime_factors_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-3.jsonl"}]
/** * @fileoverview Tests for SubtopicPageContentsObjectFactory. */ import { TestBed } from '@angular/core/testing'; import { SubtopicPageContentsObjectFactory } from 'domain/topic/SubtopicPageContentsObjectFactory'; import { RecordedVoiceoversObjectFactory } from 'domain/exploration/RecordedVoiceoversObjectFactory'; import { SubtitledHtmlObjectFactory } from 'domain/exploration/SubtitledHtmlObjectFactory'; describe('Subtopic page contents object factory', () => { let subtopicPageContentsObjectFactory: SubtopicPageContentsObjectFactory = null; let recordedVoiceoversObjectFactory: RecordedVoiceoversObjectFactory = null; let subtitledHtmlObjectFactory: SubtitledHtmlObjectFactory = null; const expectedDefaultObject = { subtitled_html: { html: '', content_id: 'content' }, recorded_voiceovers: { voiceovers_mapping: { content: {} } } }; const backendDict = { subtitled_html: { html: 'test content', content_id: 'content' }, recorded_voiceovers: { voiceovers_mapping: { content: { en: { filename: 'test.mp3', file_size_bytes: 100, needs_update: false, duration_secs: 0.2 } } } } }; beforeEach(() => { TestBed.configureTestingModule({ providers: [SubtopicPageContentsObjectFactory] }); subtopicPageContentsObjectFactory = TestBed.get( SubtopicPageContentsObjectFactory); recordedVoiceoversObjectFactory = TestBed.get( RecordedVoiceoversObjectFactory); subtitledHtmlObjectFactory = TestBed.get(SubtitledHtmlObjectFactory); }); it('should be able to create a default object', () => { const defaultObject = subtopicPageContentsObjectFactory.createDefault(); expect(defaultObject.toBackendDict()).toEqual(expectedDefaultObject); }); it('should convert from a backend dictionary', () => { const sampleSubtopicPageContents = ( subtopicPageContentsObjectFactory.createFromBackendDict(backendDict)); expect(sampleSubtopicPageContents.getSubtitledHtml().getHtml()) .toEqual('test content'); expect(sampleSubtopicPageContents.getHtml()).toEqual('test content'); expect(sampleSubtopicPageContents.getSubtitledHtml().getContentId()) .toEqual('content'); expect(sampleSubtopicPageContents.getRecordedVoiceovers().getVoiceover( 'content', 'en').toBackendDict()).toEqual({ filename: 'test.mp3', file_size_bytes: 100, needs_update: false, duration_secs: 0.2 }); }); it('should convert from a backend dictionary', () => { const sampleSubtopicPageContents = ( subtopicPageContentsObjectFactory.createFromBackendDict(backendDict)); expect(sampleSubtopicPageContents.toBackendDict()).toEqual(backendDict); }); it('should change html from subtitleHtml property in object', () => { const sampleSubtopicPageContents = ( subtopicPageContentsObjectFactory.createFromBackendDict(backendDict)); expect(sampleSubtopicPageContents.getSubtitledHtml().getHtml()) .toEqual('test content'); expect(sampleSubtopicPageContents.getHtml()).toEqual('test content'); sampleSubtopicPageContents.setHtml('new html content'); expect(sampleSubtopicPageContents.getSubtitledHtml().getHtml()) .toEqual('new html content'); expect(sampleSubtopicPageContents.getHtml()).toEqual('new html content'); }); it('should change subtitled html in object', () => { const sampleSubtopicPageContents = ( subtopicPageContentsObjectFactory.createFromBackendDict(backendDict)); expect(sampleSubtopicPageContents.getSubtitledHtml()).toEqual( subtitledHtmlObjectFactory.createFromBackendDict({ html: 'test content', content_id: 'content' })); sampleSubtopicPageContents.setSubtitledHtml( subtitledHtmlObjectFactory.createDefault('new html content', 'new id')); expect(sampleSubtopicPageContents.getSubtitledHtml()).toEqual( subtitledHtmlObjectFactory.createFromBackendDict({ html: 'new html content', content_id: 'new id' })); }); it('should change recorded voiceovers in object', () => { const sampleSubtopicPageContents = ( subtopicPageContentsObjectFactory.createFromBackendDict(backendDict)); expect(sampleSubtopicPageContents.getRecordedVoiceovers().getVoiceover( 'content', 'en').toBackendDict()).toEqual({ filename: 'test.mp3', file_size_bytes: 100, needs_update: false, duration_secs: 0.2 }); sampleSubtopicPageContents.setRecordedVoiceovers( recordedVoiceoversObjectFactory.createFromBackendDict({ voiceovers_mapping: { content: { en: { filename: 'new_file.mp3', file_size_bytes: 300, needs_update: false, duration_secs: 0.6 } } } })); expect(sampleSubtopicPageContents.getRecordedVoiceovers().getVoiceover( 'content', 'en').toBackendDict()).toEqual({ filename: 'new_file.mp3', file_size_bytes: 300, needs_update: false, duration_secs: 0.6 }); }); });<|endoftext|>/** * External dependencies */ import { Button } from '@wordpress/components'; import { EllipsisMenu, Link } from '@woocommerce/components'; import { useState, useEffect } from '@wordpress/element'; import { PLUGINS_STORE_NAME, PAYMENT_GATEWAYS_STORE_NAME, PluginsStoreActions, } from '@woocommerce/data'; import { recordEvent } from '@woocommerce/tracks'; import { useDispatch, useSelect } from '@wordpress/data'; import { sanitize } from 'dompurify'; import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ import './payment-promotion-row.scss'; function sanitizeHTML( html: string ) { return { __html: sanitize( html, { ALLOWED_TAGS: [ 'a', 'img', 'br' ], ALLOWED_ATTR: [ 'href', 'src', 'class', 'alt', 'target' ], } ), }; } type PaymentPromotionRowProps = { paymentMethod: { gatewayId: string; pluginSlug: string; url: string; }; title?: string; columns: { className: string; html: string; width: string | number | undefined; }[]; subTitleContent?: string; }; export const PaymentPromotionRow: React.FC< PaymentPromotionRowProps > = ( { paymentMethod, title, subTitleContent, columns, } ) => { const { gatewayId, pluginSlug, url } = paymentMethod; const [ installing, setInstalling ] = useState( false ); const [ isVisible, setIsVisible ] = useState( true ); const { installAndActivatePlugins } = useDispatch( PLUGINS_STORE_NAME ); const { createNotice } = useDispatch( 'core/notices' ); const { updatePaymentGateway } = useDispatch( PAYMENT_GATEWAYS_STORE_NAME ); const { gatewayIsActive, paymentGateway } = useSelect( ( select ) => { const { getPaymentGateway } = select( PAYMENT_GATEWAYS_STORE_NAME ); const activePlugins: string[] = select( PLUGINS_STORE_NAME ).getActivePlugins(); const isActive = activePlugins && activePlugins.includes( pluginSlug ); let paymentGatewayData; if ( isActive ) { paymentGatewayData = getPaymentGateway( pluginSlug.replace( /\-/g, '_' ) ); } return { gatewayIsActive: isActive, paymentGateway: paymentGatewayData, }; } ); useEffect( () => { if ( gatewayIsActive && paymentGateway && paymentGateway.settings_url ) { window.location.href = paymentGateway.settings_url; } }, [ gatewayIsActive, paymentGateway ] ); const installPaymentGateway = () => { if ( installing ) { return; } setInstalling( true ); recordEvent( 'settings_payments_recommendations_setup', { extension_selected: pluginSlug, } ); installAndActivatePlugins( [ pluginSlug ] ).catch( ( response: { message?: string } ) => { if ( response.message ) { createNotice( 'error', response.message ); } setInstalling( false ); } ); }; const onDismiss = () => { setIsVisible( false ); recordEvent( 'settings_payments_promotions_dismiss', { id: gatewayId, } ); updatePaymentGateway( gatewayId, { settings: { is_dismissed: 'yes', }, } ); }; if ( ! isVisible ) { return null; } return ( <> { columns.map( ( column ) => { if ( column.className.includes( 'name' ) ) { return ( <td className="name" key={ column.className }> <div className="wc-payment-gateway-method__name"> <Link target="_blank" type="external" rel="noreferrer" href={ url } > { title } </Link> { subTitleContent ? ( <div className="pre-install-payment-gateway__subtitle" dangerouslySetInnerHTML={ sanitizeHTML( subTitleContent ) } ></div> ) : null } </div> </td> ); } else if ( column.className.includes( 'status' ) ) { return ( <td className="pre-install-payment-gateway__status" key={ column.className } ></td> ); } else if ( column.className.includes( 'action' ) ) { return ( <td className="action" key={ column.className }> <div className="pre-install-payment-gateway__actions"> <EllipsisMenu label={ __( 'Payment Promotion Options', 'woocommerce' ) } className="pre-install-payment-gateway__actions-menu" onToggle={ ( e: | React.MouseEvent | React.KeyboardEvent ) => e.stopPropagation() } renderContent={ () => ( <div className="pre-install-payment-gateway__actions-menu-options"> <Button onClick={ onDismiss }> { __( 'Dismiss', 'woocommerce' ) } </Button> </div> ) } /> <Button className="button alignright" onClick={ () => installPaymentGateway() } isSecondary isBusy={ installing } aria-disabled={ installing } > { __( 'Install', 'woocommerce' ) } </Button> </div> </td> ); } return ( <td key={ column.className } className={ column.className } width={ column.width } dangerouslySetInnerHTML={ column.className.includes( 'sort' ) ? { __html: column.html, } : sanitizeHTML( column.html ) } ></td> ); } ) } </> ); };
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18651.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18651.jsonl"}]
import numpy as np from gym import Env, spaces # Utilities for SBL3_A2C.py, SBL3_DQN.py and SBL3_PPO.py. class DummyGymEnv(Env): """ Dummy OpenAI Gym environment which regurgitates historical percepts so that a Stable-Baselines3 agent can train on that history. """ def __init__(self): super(DummyGymEnv, self).__init__() def set_meta(self, n_actions, n_obs): self.action_space = spaces.Discrete(n_actions) self.observation_space = spaces.Discrete(n_obs) def set_history(self, history): self.i = 0 def set_initial_obs(self, initial_obs): self.initial_obs = initial_obs def reset(self): return self.initial_obs def step(self, action): try: assert action == self.history[3*self.i] except Exception: import pdb; pdb.set_trace() reward = self.history[1+3*self.i] obs = self.history[2+3*self.i] self.i += 1 new_episode_flag = False misc_info = {} return (obs, reward, new_episode_flag, misc_info) def create_fwd_monkeypatch(A, n_steps): """ overriding the SBL3 PPO or A2C action-function. (A different monkeypatch is needed for DQN since it uses a different action- function). """ def forward_monkeypatch(*args): _actions, values, log_probs = A.worker_forward(*args) assert len(_actions) == 1 _actions[0] = A.actions[A.worker.num_timesteps % n_steps] return _actions, values, log_probs return forward_monkeypatch def create_sample_monkeypatch(A, n_steps): """ overriding the SBL3 DQN action-function. (A different monkeypatch is needed for PPO or A2C since those use a different action-function than DQN). """ def sample_monkeypatch(*args): action = np.array([A.actions[A.worker.num_timesteps % n_steps]]) return action, action return sample_monkeypatch class DummyLogger: """ Logger class whose instances silently ignore instructions to log things. This is used to gag Stable-Baselines3 log-writing which would otherwise waste precious time. """ @staticmethod def record(*args, **kwargs): pass @staticmethod def dump(*args, **kwargs): pass dummy_logger = DummyLogger() act_dicts = {} def get_act_dict(A, family, hyperparams_dict): """ Create an action-dictionary to be shared across multiple instances of a one of our SBL3-based agent classes. Since we have no control over how SBL3 agents generate random numbers, we use these shared dictionaries to ensure semi-determinacy (semi-determinacy is the property that two instances of an agent-class, if instantiated within the same run of a larger background program, will act identically if they are trained identically). A given instance of one of our SBL3-based agent classes will only consult its underlying SBL3 worker's neural net if it does not find the appropriate observation/training-history-hash in the appropriate shared dictionary. If so, after generating an action using that neural net, the agent will add that action into the dictionary so other instances like itself, if identically trained, will re-use that action. """ hyperparam_keys = hyperparams_dict.keys() hyperparams = [hyperparams_dict[k] for k in hyperparam_keys] hyperparams.sort() hyperparams = tuple(hyperparams) key = (family, hyperparams, A.n_actions, A.n_obs) if key in act_dicts: return act_dicts[key] else: act_dicts[key] = {} return act_dicts[key]<|endoftext|>import json import requests import re from trac.core import * from trac.config import Option, IntOption #def wiki_page_added(self, page): #def wiki_page_changed(self, page, version, t, comment, author, ipnr): #def wiki_page_deleted(self, page): #def wiki_page_version_deleted(self, page): def prepare_wiki_values(page, action=None): values = dict([('project', page.env.project_name.encode('utf-8').strip()), ('action', action), ('pagename', page.name), ('url', page.env.abs_href.wiki(page.name))]) #values['project'] = page.env.project_name.encode('utf-8').strip() #values['action'] = 'changed' #values['pagename'] = page.name #values['url'] = page.env.abs_href.wiki(page.name) return values class SlackWikiNotificationPlugin(Component): webhook = Option('slack', 'wiki-webhook', ' [IDX] doc="Incoming webhook for Slack") channel = Option('slack', 'wiki-channel', '#TracWiki', doc="Channel name on Slack") username = Option('slack', 'wiki-username', 'Trac-Bot', doc="Username of the bot on Slack notify") wikiadd = IntOption('slack', 'wikiadd', '1', doc=" Turn add notification on or off (defaults on)") wikidel = IntOption('slack', 'wikidel', '1', doc="Turn delete notification on or off (defaults on)") wikichange = IntOption('slack', 'wikichange', '0', doc="Turn change notification on or off (defaults off)") wikipages = Option('slack', 'wikipages', '.*', doc="Regex of wiki pages to notify on change of") def notify(self, values): template = '_%(project)s_ :incoming_envelope:\n%(pagename)s[%(url)s] was *%(action)s* by @%(author)s' if (values['action'] == 'deleted'): template = '_%(project)s_ :X:\n%(pagename)s[%(url)s] was *%(action)s*' # make sure author formatting is correct... if (values['author']): values['author'] = re.sub(r' <.*', '', values['author']) # format the message message = template % values # set type-specific attachements as needed attachments = [] if (values['action'] == 'changed' and values['comment']): attachments.append( { ':pushpin: title': 'Comment', 'text': values['comment'] } ) # send it all out data = { "channel": self.channel, "username": self.username, "text": message.encode('utf-8').strip(), "attachments": attachments } try: r = requests.post(self.webhook, data={"payload":json.dumps(data)}) self.log.exception("Failed to post slack notification: %s" % (e)) return False return True if (self.wikiadd != 1): pass values = prepare_wiki_values(page, 'added') values['author'] = page.author values['comment'] = page.comment self.notify(values) if (self.wikidel != 1): pass values = prepare_wiki_values(page, 'deleted') values['url'] = page.env.abs_href.wiki(page.name) values['author'] = page.author # this is usually going to be blank here... self.notify(values) if (self.wikichange != 1): pass #wikipagelist = self.wikipages.split(',') #for wikipage in wikipagelist: #wikipage.strip() if (re.match(self.wikipages, page.name)): # setup the values and notify! values = prepare_wiki_values(page, 'changed') values['author'] = author values['comment'] = comment self.notify(values) #break # we're done here pass<|endoftext|># Adjust this file to your setup # file encodings IN_ENCODING = r"utf8" OUT_ENCODING = r"utf8" # knx1 openhab items file(s) ITEMS_FILES = "../items/knx1/myhome.items , \ ../items/knx1/heating.items, \ ../items/knx1/window.items, \ ../items/knx1/xbmc.items" # converted item files will be created in this directory ITEM_RESULT_DIR = r"./result/items/" # out file names THINGS_FILE = r"./result/things/knx.things" THINGS_UNUSED_FILE = "unused.things" ITEMS_UNUSED_FILE = "unused.items" ITEMS_UNUSED_CONTROLS_FILE = "unused-control.items" # files containing all information read DEBUG_KNX = "knx.txt" DEBUG_OH = "oh.txt" # knxproj files (optional), unzip your knxproj file # comment out this lines if you do not have/want to read ETS config # multiple files can be read, separated by spaces PROJECTFILES = "./knxproj/P-02A7/0.xml" # ## specify device types by vendor name (must be part of the *ProductRefId*) # If unsure: run the script and look into the DEBUG_KNX file # These are the primary addresses which will be used for read/write ACTORS = "AKS, AKD, JAL, M-0051_H-hp, QUAD," # These will be added as -control items CONTROLS = "TSM, -BE, ZN1IO, ZN1VI, LED," # These will ignored, uncomment to use # IGNORE_DEVICES = "LED," # As of now all unknown GAs are switches # FIXME: this could be improved! UNUSED_TYPE = 'Switch' # Suffix for generic control items CONTROL_SUFFIX = '_Control' # If defined, only these controls will be added to the items and things file. # If undefined all possible controls will be created, this may be a good start # but may flood your system. You may use regex to match. # WANTED_CONTROLS = "Switch_Szene, \ # Licht_EG_Gaderobe, \ # Switch_Beschattung, \ # Rolladen_.*_Switch, \ # Licht_ALL" # If defined, ``autoupdate="true"`` will be added to all matching items. # You may use regex to match. # AUTOUPDATE_TRUE = "Alarm_" # If defined, ``autoupdate="false"`` will be added to all matching items. # You may use regex to match. # AUTOUPDATE_FALSE = "Licht_ALL" # values in <...> will be replaced. So do not change <...> values. CHANNEL = ' channel="knx:device:bridge:<generic>:<name>" ' # IMPORTANT: adjust your IP (KNX and local) below THING_HEADER = '''Bridge knx:ip:bridge [ ipAddress="192.168.x.xxx", portNumber=3671, localIp="192.168.x.xxx", type="TUNNEL", readingPause=50, responseTimeout=10, readRetriesLimit=3, autoReconnectPeriod=1, localSourceAddr="0.0.0" ] {''' # Generic device name DEVICE_GENERIC = "generic" DEVICE = ''' Thing device <generic> [ // device ID: <device_id> // <building> address="<address>", fetch=false, pingInterval=600, readInterval=0 ] {''' DEVICE_EMPTY = ''' Thing device <generic> [ ] {''' CHANNELS = ( "Switch", "Rollershutter", "Contact", "Number", "Dimmer", "String", "DateTime", "Color", # supported since Dec 2018, so check your OH version if needed ) # only one line supported, if you have more than one you need to implement it. ETS_LINE_PREFIX = "1.1." # ETS 4.x xml tags, may depend on ETS version FIND_BUILDINGS = 'Buildings' # Gebaeude FIND_BUILDINGPART = 'BuildingPart' # maybe use those for ETS 5.x # FIND_BUILDINGS = 'Locations' # Gebaeude # FIND_BUILDINGPART = 'Space' # ETS xml tags, usually no need to change those FIND_TRADES = 'Trades' # Gewerke FIND_TRADEPART = 'Trade' FIND_DEVICEREF = 'DeviceInstanceRef' FIND_DEVICE = 'DeviceInstance' FIND_COMREF = 'ComObjectInstanceRef' FIND_CONNECTOR = 'Connectors' FIND_SEND = 'Send' FIND_RECEIVE = 'Receive' FIND_GA = 'GroupAddress'
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11121.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11121.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11121.jsonl"}]
Unique symbol for parallel kernels Question: For each kernel, a unique symbol can be generated with <code>Unique[]</code>. However, since it's basically defined by the growing <code>$ModuleNumber</code>, parallel kernels can only generate unique symbols for themselves, but they are the same across kernels. MWE: <code>ParallelEvaluate[Unique[i]] </code> So how can I generate unique symbols across all kernels? Of course I can set the <code>$ModuleNumber</code> for each kernel during the initialization, but that's way too brute force. EDIT My use of this unique symbol, for example, is <code>expr1=q.k l.k; expr2=expr1/.{q.k->Module[{i},q[i]k[i]],l.k->Module[{i},l[i]k[i]]}; expr3=expr2/.k[i_]k[j_]:>delta[i,j]; result=expr3/.q_[i_]l_[j_]delta[i_,j_]:>q.l </code> Comment: Can you give more background to why do you need them? Maybe you don't. Comment: @Kuba It's for the dummy indices, i.e. $q.k$ is $q^i k^i$ where i is the dummy index. So in the whole expression `i` must be unique and can only appear twice. Comment: @Turgon please give an example in Mathematica code of an evaluation that requires your dummy indices. The example you gave could obviously be vectorized so I'm not sure it helps much Comment: @MarcoB I'm not sure if you're familiar with this:i.e. I'd have an expression `q[i$1]k[i$2]kroneckerdelta[i$1,i$2]` and I want to contract those indices such that the result is $q^ik^j\delta^{ij}=q^ik^i$. And the contraction is the last step so before that, I'd have intermediate results with indices I'd like to keep. Comment: @Turgon Still no functioning code though... Alright, we'll keep guessing! Would [`Indexed`]( [IDX] be of any help then? Comment: @MarcoB Sorry...I'm trying to give you an example but I'm not sure if it makes any sense. Plus, as I stated below, it's more like an academic question than what I really need, because I have a workaround for it. `Indexed` is just a fancy way to write my `q[i]` or `k[i]`, it still needs unique indices. Answer: How about using the <code>$KernelID</code> as a further differentiator? <code>ParallelEvaluate[Unique["i" <> ToString@$KernelID]] (* Out: {i110, i210, i310, i410} *) </code> Of course you could include <code>$</code> in the string name, or any other symbol. Alternatively, you could perhaps do away with Unique, and simply use a combination of a string and <code>$KernelID</code>, depending on your usage needs. You could also skip <code>Unique</code> altogether and roll your own. I was thinking of something along the lines of the following: <code>ParallelEvaluate[ Symbol[ "i" <> ToString[1000 $KernelID + RandomInteger[{1, 999}]] ] ] (* Out: {i1569, i2811, i3512, i4076} *) </code> Comment: If you're unlucky and the `$ModuleNumber` you get is 9, then you have `{i19,i29...}`. At least I've seen `$ModuleNumber` being 700-ish, so in that case you have 1000 unique symbols. Of course most of the time it's more than enough but is there a better solution? Comment: @turgon how many symbols do you expect to need? Comment: A few dozens maybe, so your solution is ok for me. I'm only curious if there's a better way to do this. Comment: @Turgon Would the alternative approach in my edit work better then? Comment: Well how about this `ParallelEvaluate[$ModuleNumber = 10000 $KernelID]`? Random doesn't seem safe when you're trying to make it unique. Comment: @Turgon Yes that would work as well. I am always loath to change deep built-ins like that, but that's just me being overly cautious. I don't see why this particular change would be dangerous. Comment: It's true if I change the macro in the middle of something, it might break things. But if it's used to initialize the subkernels, I think it's ok.<|endoftext|>For-loop inside function couldn't iterate the variables Question: I'm willing to compute all values of all of variables combinations. However, the code always produces the same values for all iterations. <code>#chsh import numpy as np from bell_state import bell_state from pauli import pauli #setup of measurement N_A = 2 #measurement outcomes N_B = 2 #Bell_state used rho = bell_state(1) #Alice A_1 =pauli('Z') A_2 =pauli('X') #Bob B_1 =(1/np.sqrt(2))*(pauli('Z')+pauli('X')) B_2 =(1/np.sqrt(2))*(pauli('Z')-pauli('X')) def AB(a,b): if a==1 and b==1: aabb = np.kron(A_1,B_1) elif a==2 and b==1: aabb = np.kron(A_2,B_1) elif a==1 and b==2: aabb = np.kron(A_1,B_2) elif a==2 and b==2: aabb = np.kron(A_2,B_2) else: print('error') return aabb def Obs(a,b): for a in range(1,N_A): for b in range(1,N_B): ob =np.trace(np.dot(AB(a,b),rho)) return ob IObs = Obs(1,1) + Obs(1,2) + Obs(2,1) - Obs(2,2) </code> The code showed this results, those not what I want <code>Obs(1,1) : 0.7071067811865475 Obs(2,1) : 0.7071067811865475 Obs(1,2) : 0.7071067811865475 Obs(2,2) : 0.7071067811865475 IObs : 1.414213562373095 </code> The results what I expected actually as same as the results that (I computed manually without loops by this below code <code>Ob11= np.trace(np.dot(AB(1,1),rho)) Ob21= np.trace(np.dot(AB(2,1),rho)) Ob12= np.trace(np.dot(AB(1,2),rho)) Ob22= np.trace(np.dot(AB(2,2),rho)) </code> results of what I want <code>Obs(1,1) : 0.7071067811865475 Obs(2,1) : 0.7071067811865475 Obs(1,2) : 0.7071067811865475 Obs(2,2) : -0.7071067811865475 IObs : 2.82842712474619 </code> Perhaps somebody could help me find what I've done wrong with my for-loop function. Thank you! Comment: No, that's NOT the results you got. `Obs(1,1)` and `Obs(2,1)` and `Obs(1,2)` all return `None`, because the loops will not run. This cannot be the code you ran. Comment: Actually, those the results that I got (the above one). If the loops didn't closed with `return ob` that will be ran as you mentioned, all will return to `NONE`. @TimRoberts Comment: No, `Obs(1, n)` or `Obs(n, 1)` returns `None` (no matter what `n` is) because `range(1, 1)` is empty so the loops are not executed. Comment: So, how to execute the loops? should I modify something in my code? The `n` range should be `1,2`. Comment: If you want `Obs(1,1)` to run one of each loop, then you need `for a in range(N_A+1):`. Comment: (That should be `for a in range(1,N_A+1):`.) Comment: I tried ` for a in range(1,N_A+1):` but still ran as same as before. Answer: I think the issue is in Obs function here <code>def Obs(a,b): for a in range(1,N_A): for b in range(1,N_B): ob =np.trace(np.dot(AB(a,b),rho)) return ob </code> As you might see, the return statement is placed inside the loop block. This makes your code for calculating ob is never executed more than 1, in other word, it is executed exactly once for whatever <code>a</code> and <code>b</code> you pass to the function. Based on my assumption (cause I am not too sure about the logic you wanted to implement), you may want to try to use this instead: <code>def Obs(a,b): for a in range(1,N_A): for b in range(1,N_B): ob =np.trace(np.dot(AB(a,b),rho)) return ob </code> Comment: hmm.. after looking closer to the code, I am not sure why you needed the nested loop in the first place cause I don't see you utilize the loop? Comment: oh sorry, my bad. I strongly believe it is because of the static value for `N_A` and `N_B` which are used as the upper range limit in the loop inside Obs function.<|endoftext|>How do you CM an application with managed content Question: We have a web application which contains a bunch of content that the system operator can change (e.g. news and events). Occasionally we publish new versions of the software. The software is being tagged and stored in subversion. However, I'm a bit torn on how to best version control the content that may be changed independently. What are some mechanisms that people use to make sure that content is stored and versioned in a way that the site can be recreated or at the very least version controlled? Answer: When you identify two set of files which have their own life cycle (software files on one side, "news and events" on the other, you know that: you can not versionned them together at the same time you should not put the same label You need to save the "news and event" files separatly (either in the VCS or in a DB like Ian Jacobs suggests, or in a CMS - Content Management system), and find a way to link the tow together (an id, a timestamp, a meta-label, ...) Do not forget you are not only talking about two different set of files in term of life cycle, but also about different set of files in term of their very natures: Consider the terminology introduced in this SO question "Is asset management a superset of source control" by S.Lott software files: Infrastructure information, that is "representing the processing of the enterprise information asset". Your code is part of that asset and is managed by a VCS (Version Control System), as part of the Configuration management discipline. "news and events": Enterprise Information, that is data (not processing); this is often split between Content Managers and Relational Databases. So not everything should end up in Subversion. Answer: Keep everything in the DB, and give every transaction to the DB a timestamp. that way you can keep standard DB backups and load the site content at whatever date you want if the worst happens. Answer: I suppose part of the answer depends on what CMS you're using, and how your web app is designed, but in general, I'd regard data such as news items or events as "content". In other words, it's not part of your application - it's the data which your application processes. Of course, there will be versioning issues between your CMS code and your application code. You could manage this by defining the interface between the two. Personally, I'd publish the data to the web app as XML, which gives you the possibility of using XML schema to define exactly what the CMS is required to produce, and what the web app should expect to process. This ought to mean that most changes in the web app can be made without a corresponding alteration in the rendering of the data. When functionality changes require this, you can create a new version of the schema and continue to make progress. In this scenario, I'd check the schema in with the web app code, but YMMV. It isn't easy, and it gets more complicated again if you need additional data fields in your CMS. Expect to plan for a fairly complex release process (also depending on how complex your Dev-Test-Acceptance-Production scenario is.) If you aren't using a CMS, then you should consider it. (Of course, if the operation is very small, it may still fall into the category where doing it by hand is acceptable.) Simply putting raw data into a versioning system doesn't solve the problem - you need to be able to control the format in which your data is published to the web app. Almost certainly this format should be something intended for consumption by software, and therefore not usually suitable for hand-editing by the kind of people who write news items or events.
[{"idx": "Unique_symbol_for_parallel_kernels", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-2122.jsonl"}, {"idx": "For-loop_inside_function_couldn't_iterate_the_variables", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-2122.jsonl"}, {"idx": "How_do_you_CM_an_application_with_managed_content", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-2122.jsonl"}]
const CustomCommand = require('../../dbModels/customCommand.js'); const path = require('path'); const fs = require('fs'); const thinky = require('thinky')(); const rql = thinky.r; import { CommandoClient, Command, CommandMessage } from 'discord.js-commando'; import { Message } from 'discord.js'; export class DeleteRecorded extends Command { public constructor(client: CommandoClient) { super(client, { name: 'deleterecorded', group: 'utils', memberName: 'deleterecorded', description: "Deletes a recorded command from the database (and it's -slow/-fast variations, and removes the associated sound files from the server", args: [ { key: 'command', label: 'command', prompt: 'What recorded commands would you like to delete?', type: 'string', infinite: false } ] }); } public async run( msg: CommandMessage, args: any ): Promise<Message | Message[]> { CustomCommand.filter( rql .row('commandText') .match(args.command) .and(rql.row('commandType').eq('recorded')) ) .run({ readMode: 'majority' }) .then((result: any) => { console.log(`result: ${JSON.stringify(result)}`); if (result.length !== 3) { return msg.reply( `Expected 3 commands to be found, ${ result.length } commands were found to be associated with that name.` ); } result.forEach((command: any) => { let commandName = command.commandText; let commandNameNoTrigger = command.commandText.slice(1); command .delete() .then(() => { let cmd = this.client.registry.resolveCommand( commandNameNoTrigger ); this.client.registry.unregisterCommand(cmd); DeleteRecorded.removeFile( path.resolve( 'resources/', `${commandNameNoTrigger}${msg.guild.id}.mp3` ) ); return msg.reply( `Recorded command '${commandName}' was successfully deleted` ); }) .catch((err: any) => { console.log(`error: ${err}`); return msg.reply(''); }); }); }); return await msg.delete(); } private static removeFile(file: any): void { fs.unlinkSync(file); } }<|endoftext|>import * as yup from 'yup' import HttpValidatorException from '@exceptions/HttpValidatorException' import { regexToValidateTime } from '@configs/app' import { WorkingHourToPromotionDTO } from '@interfaces/WorkingHourDTO' class CreateProductValidator { private schema: any; public name: string; public photoUrl: string; public price: number; public categoryId: string; public promotion?: { description: string; price: number; workingHours: WorkingHourToPromotionDTO[] }; constructor (data: any) { this.setupSchema() this.name = String(data?.name) this.photoUrl = String(data?.photoUrl) this.price = data?.price this.categoryId = data?.categoryId this.promotion = data?.promotion } private setupSchema () { const timeErrorMessageDefault = 'time format to working hour in startAt is wrong. The pattern allowed is hh:mm and between 00:00 and 23:59' this.schema = yup.object().shape({ name: yup.string().required(), photoUrl: yup.string().required(), price: yup.number().positive().required(), categoryId: yup.string().required() }) if (this.promotion) { this.schema.promotion = yup.object().shape({ description: yup.string().required(), price: yup.number().positive().required(), workingHours: yup.array().of( yup.object().shape({ weekday: yup.string().required(), startAt: yup .string() .trim() .matches(regexToValidateTime, timeErrorMessageDefault) .required(), finishAt: yup .string() .trim() .matches(regexToValidateTime, timeErrorMessageDefault) .required() }) ) }) } } public async validate () { await this.schema.validate(this).catch(function (err: any) { throw new HttpValidatorException(err.errors) }) } public getExpectedParams (): Omit<CreateProductValidator, 'validate'> { const { validate: validateFunction, schema, ...expectedParams } = this return expectedParams } } export default CreateProductValidator<|endoftext|>import { EventEmitter } from "../../stencil-public-runtime"; import { CvsCardSummaryProps } from "../cvs-card-summary/cvs-card-summary"; export interface CvsSelectPaymentProps { userId: string; subText?: string; validCards?: CvsCardSummaryProps[]; expiredCards?: CvsCardSummaryProps[]; } export declare class CvsSelectPayment { /** * parsedData * @memberof CvsSelectPaymentForm * @type: cvsSelectPaymentProps */ parsedData: CvsSelectPaymentProps; /** * Previous Page Url to redirect on error to mychart */ readonly myChartUrl?: string; /** * show an error message if going to select-payment from manage-payment flow */ readonly correctFlow?: boolean; /** * */ readonly cardAdded?: boolean; /** * userId for api submission */ readonly userId: string; /** * legend to display in the select card form */ readonly subText?: string; /** * show continue button * default to true */ readonly showContinue?: boolean; /** * option to hide headers */ readonly hideHeader?: boolean; /** * text to display for add card */ readonly addCardText?: string; /** * list of valid cards to display */ readonly validCards: CvsCardSummaryProps[] | string; /** * list of expired cards to display */ readonly expiredCards: CvsCardSummaryProps[] | string; /** * event emitter * handles directing user to card management * @param event @private @readonly */ routeToCardManagement: EventEmitter; private readonly routeToCardManagementHandler; /** * @public: componentWillLoad * * @description: Executed when the component first connected to DOM * @returns: void */ componentWillLoad(): void; /** * @private formatData * @description if the given object is string, returns the JSON object of the string * @returns: cvsCardSummaryProps[] */ private formatData; /** * @private parseInputData * @description Executed when there is the change in the component property store. * If the component is initilized through HTML the path prop will be a string. * @returns: CvsSelectPaymentFormProps */ private parseInputData; render(): any; }<|endoftext|>import {BasicDataDto} from "../shared/dtos/basic-data.dto"; import {BaseSearchDataDto} from "../shared/dtos/base-search-data.dto"; import {ApiProperty, ApiPropertyOptional} from "@nestjs/swagger"; import {IsString} from "class-validator"; export class UserDto extends BasicDataDto{     @ApiPropertyOptional({type: String,description:'ชื่อผู้ใช้ของผู้ใช้งานในการใช้งานระบบ'})     username: string     @ApiPropertyOptional({type: Boolean,description:'Active Directory สำหรับเก็บข้อมูลผู้ใช้งาน'})     ad: boolean     @ApiPropertyOptional({type: Date,description:'วัน เดือน ปี และเวลา ณ วันที่ที่ทำการเพิ่มข้อมูล User'})     created_at: Date     @ApiPropertyOptional({type: String,description:'ชื่อผู้ใช้งานที่ทำการเพิ่มข้อมูล User'})     created_by: string     @ApiPropertyOptional({type: Date,description:'วัน เดือน ปี และเวลา ณ วันที่ที่ทำการอัปเดตข้อมูล User'})     updated_at: Date     @ApiPropertyOptional({type: String,description:'ชื่อผู้ใช้งานที่ทำการอัปเดตข้อมูล User'})     updated_by: string     @ApiPropertyOptional({type: String,description:'null'})     department_code: string     @ApiPropertyOptional({type: String,description:'null'})     module: string     @ApiPropertyOptional({type: String,description:'null'})     type: string } export class CreateUserDto extends UserDto{     @ApiPropertyOptional({type: Number,description:'ID ประจำแต่ละบัญชีผู้ใช้งานในฐานข้อมูล'})     id: number     @ApiPropertyOptional({type: String,description:'ชื่อผู้ใช้ของผู้ใช้งานในการใช้งานระบบ'})     username: string     @ApiPropertyOptional({type: String,description:'null'})     department_code: string     @ApiPropertyOptional({type: String,description:'null'})     module: string     @ApiPropertyOptional({type: String,description:'null'})     type: string } export class UpdateUserDto extends BasicDataDto{     @ApiPropertyOptional({type: String,description:'null'})     department_code: string     @ApiPropertyOptional({type: String,description:'null'})     module: string     @ApiPropertyOptional({type: String,description:'null'})     type: string } export class DeleteUserDto extends BasicDataDto{     @ApiProperty({type:Number})     id:number; } export class SearchUserDto extends BaseSearchDataDto{ }<|endoftext|>import candleGranularity, { CandleType } from '../../models/CandleGranularity'; const formatDate = (date: Date) => date.toISOString().slice(0, 10); describe('CandleGranularity', () => { const tomorrowDate = new Date(); tomorrowDate.setDate(tomorrowDate.getDate() + 1); it('6M', () => { const past6MonthsDate = new Date(); past6MonthsDate.setMonth(past6MonthsDate.getMonth() - 6); expect(candleGranularity['6M' as CandleType].getStartDate()).toEqual(formatDate(past6MonthsDate)); expect(candleGranularity['6M' as CandleType].getEndDate()).toEqual(formatDate(tomorrowDate)); }); it('3M', () => { const past3MonthsDate = new Date(); past3MonthsDate.setMonth(past3MonthsDate.getMonth() - 3); expect(candleGranularity['3M' as CandleType].getStartDate()).toEqual(formatDate(past3MonthsDate)); expect(candleGranularity['3M' as CandleType].getEndDate()).toEqual(formatDate(tomorrowDate)); }); it('1M', () => { const past1MonthDate = new Date(); past1MonthDate.setMonth(past1MonthDate.getMonth() - 1); expect(candleGranularity['1M' as CandleType].getStartDate()).toEqual(formatDate(past1MonthDate)); expect(candleGranularity['1M' as CandleType].getEndDate()).toEqual(formatDate(tomorrowDate)); }); it('1W', () => { const past1WeekDate = new Date(); past1WeekDate.setDate(past1WeekDate.getDate() - 7); expect(candleGranularity['1W' as CandleType].getStartDate()).toEqual(formatDate(past1WeekDate)); expect(candleGranularity['1W' as CandleType].getEndDate()).toEqual(formatDate(tomorrowDate)); }); it('3D', () => { const past3DaysDate = new Date(); past3DaysDate.setDate(past3DaysDate.getDate() - 3); expect(candleGranularity['3D' as CandleType].getStartDate()).toEqual(formatDate(past3DaysDate)); expect(candleGranularity['3D' as CandleType].getEndDate()).toEqual(formatDate(tomorrowDate)); }); it('1D', () => { const past1DayDate = new Date(); past1DayDate.setDate(past1DayDate.getDate() - 1); expect(candleGranularity['1D' as CandleType].getStartDate()).toEqual(formatDate(past1DayDate)); expect(candleGranularity['1D' as CandleType].getEndDate()).toEqual(formatDate(tomorrowDate)); }); });
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18785.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18785.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18785.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18785.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-18785.jsonl"}]
Android Studio inexplicable error in debug APK Question: I faced a situation in which the version from the built debug APK had inexplicable runtime errors which disappeared after the rebuild. No code changes - just fresh build. Today it happened at least a second time - it starts to worry me. It's a waste of time to determine that error couldn't be repeated on my emulator and I just need to rebuild it. Here I can only build APKs one by one until I get two files equal to byte. Though I've never faced the same problem while installing directly through USB, it couldn't be a solution as I don't have physical access to it all the time. Update. Today such a thing happened through USB installation. The second reason is main here. Can I be sure the release build doesn't have the same problem? Now I build AAB files that I can't install on a device to check before update in Google Play. Current Android Studio version: <code>Android Studio Arctic Fox | 2020.3.1 Patch 1 Build #AI-203.7717.56.2031.7621141, built on August 7, 2021 </code> Update. Repeated on Android Studio version: <code>Android Studio Arctic Fox | 2020.3.1 Patch 2 Build #AI-203.7717.56.2031.7678000, built on August 27, 2021 </code> Other build settings <code>buildToolsVersion '30.0.2' gradle version 7.0.2 </code> Why does it happen? Is there any workaround? Comment: Have you tried using buildToolsVersion 29? Answer: Patch 2 is available, It seems there are some issue with gradle build. here is the link of the issue tracker. [IDX] suggested in issue tracker can you please try with below configs. The kotlin metadata should be deterministic from version 3.0.69 and forward. You can try out that version by adding the following to your top-level build.gradle file: <code>buildscript { repositories { maven { url ' [IDX] } } dependencies { classpath 'com.android.tools:r8:3.0.69' // Must be before the Gradle Plugin for Android. classpath 'com.android.tools.build:gradle:X.Y.Z' // Your current AGP version. } } </code> Here is the link of all resolved issues for patch 2. [IDX] Thank you for the link. I hope you understand, that I can't say your answer is correct quick enough. Comment: sure. I understand Comment: I missed a moment to take the bounty to you due to vacation. Sorry about that. Comment: it's ok @Ircover. you can still accept answer if you find helpful thank you. Answer: It is going to be hard to say anything without seeing the error or at least logcat. With that said it could be either your configuration or a bug and the only generic advice to give is to make sure you update everything to the latest stable build or find any version for the build system that works. Sometimes things like this happen due to build artifact caching issues. In general, debug builds optimize for build speed and additional info for debugging. Build artifact caching one such build speed optimization thing that could be wrong and can cause issues. Another one is where an IDE may save files while you are building and this can mess up timestamps and maybe mess up the cache or mix different versions of code. Anyway without a specific error message or logcat it is almost impossible to say anything specific. Comment: The problem is I can't get any info about error as I don't know if it exists before facing it during testing. And your option about cached build files seems wrong, because I got errors which I've never faced before. So build is totally fresh, with newly constructed errors)<|endoftext|>mongodump fails after exactly 10 minutes Question: Using single instance MongoDB v4.2.0 on Debian 9.11 with collection of 78GB and 60M documents on a 2 vCPUs, 13 GB memory server. This command is invoked on the same server where database runs: <code>mongodump --username user --password pwd --authenticationDatabase admin --host localhost --gzip --archive=out.gz --db database --collection collection </code> And after 10 minutes this is the output: <code>2019-10-17T16:13:09.523+0200 Failed: error creating intents to dump: error counting database.collection: connection(localhost:27017[-2]) unable to decode message length: read tcp 127.0.0.1:57798->127.0.0.1:27017: i/o timeout </code> By looking at <code>mongod.log</code> this is what mongodump outputs: <code>2019-10-17T16:13:09.523+0200 I NETWORK [conn20] end connection 127.0.0.1:57794 (4 connections now open) 2019-10-17T16:13:09.748+0200 I - [conn21] operation was interrupted because a client disconnected 2019-10-17T16:13:10.371+0200 W COMMAND [conn21] Unable to gather storage statistics for a slow operation due to lock aquire timeout 2019-10-17T16:13:10.371+0200 I COMMAND [conn21] command database.collection appName: "mongodump" command: aggregate { aggregate: "collection", pipeline: [ { $match: {} }, { $group: { _id: 1, n: { $sum: 1 } } } ], cursor: {}, lsid: { id: UUID("4759f9ad-7d37-44c7-bd41-8610af565c47") }, $db: "database" } planSummary: COLLSCAN numYields:437454 ok:0 errMsg:"Error in $cursor stage :: caused by :: operation was interrupted because a client disconnected" errName:ClientDisconnect errCode:279 reslen:186 locks:{ ReplicationStateTransition: { acquireCount: { w: 437456 } }, Global: { acquireCount: { r: 437456 } }, Database: { acquireCount: { r: 437455 } }, Collection: { acquireCount: { r: 437455 } }, Mutex: { acquireCount: { r: 2 } } } protocol:op_msg 600852ms </code> It looks like mongodump internally runs this aggregate query: <code>[ { $match: {} }, { $group: { _id: 1, n: { $sum: 1 } } } ] </code> And when the same query is run from MongoDB shell it works: <code>> db.collection.aggregate([ { $match: {} }, { $group: { _id: 1, n: { $sum: 1 } } } ]) { "_id" : 1, "n" : 60488853 } </code> And this is the <code>mongod.log</code> output: <code>2019-10-17T15:01:37.130+0200 I COMMAND [conn2] command database.collection appName: "MongoDB Shell" command: aggregate { aggregate: "collection", pipeline: [ { $match: {} }, { $group: { _id: 1.0, n: { $sum: 1.0 } } } ], cursor: {}, lsid: { id: UUID("3b732623-e8b4-4365-bac7-efa710db035c") }, $db: "database" } planSummary: COLLSCAN keysExamined:0 docsExamined:60488853 cursorExhausted:1 numYields:472591 nreturned:1 reslen:136 locks:{ ReplicationStateTransition: { acquireCount: { w: 472593 } }, Global: { acquireCount: { r: 472593 } }, Database: { acquireCount: { r: 472593 } }, Collection: { acquireCount: { r: 472593 } }, Mutex: { acquireCount: { r: 2 } } } storage:{ data: { bytesRead: 79320933249, timeReadingMicros: 610249624 } } protocol:op_msg 653559ms </code> What can be seen is that this count query from shell takes 653 seconds while the mongodump internal query timeouts after 600 seconds (10 minutes exactly). Other smaller collections and databases on the same server do not have this issue, just this large one. How this timeout or issue for large queries can be solved so that <code>mongodump</code> runs without issues? Answer: It looks like there was a bug as after upgrading to MongoDB v4.2.1 the issue does not happen any more.<|endoftext|>Neo4j Cypher Optimize Create relationship between each node in cartesian product Question: I have a set of nodes, all labeled Word. I want to connect each Word to all the other words with a relationship called Distance. I do the following query: match (word1:Word) with word1 match (word2:Word) where word1 <> word2 merge (word1)-[distance:DISTANCE ]->(word2) return word1, distance, word2 It runs forever. There are only ~600 nodes and although I expect 600*600 relationships, the query shouldn't run for two hours! It is quicker in Java than in Neo4j. What advice do you have to make it quicker? I have already added an index on one of the properties and it's not improving. Comment: Note you are also returning 360K rows. At the least, you can eliminate your return, as it doesn't seem like you need it. You also don't need to add a variable on the :DISTANCE relationship, if you're not going to do anything further with it in the query. If you need to batch up your merges, try the APOC library procedure apoc.periodic.commit(). Comment: That's almost 360K relationships created in one transaction, which could be a lot depending on your memory settings. Answer: Some observations: Your query will try to perform 2*600*599 (or 718,800) <code>MERGE</code> operations in a single transaction. The reason for the factor of <code>2</code> is because every pair of words (say, x and y) will be seen twice (as x/y and y/x). You (presumably) only want to perform half that number of operations. The x/y and y/x behavior also causes an attempt to ensure there are 2 <code>DISTANCE</code> relationships for each word pair -- one in either direction. That is (presumably) twice the number of relationships than you want (or need). Trying to perform 720K (or even just 360K) operations in a single transaction may cause the DB server to run out of memory. Here is a modified query that might fix the above issues. The <code>ID(w1) < ID(w2)</code> test makes sure the 2 words in a pair are not the same AND that the same pair is only processed once. It also uses the APOC procedure apoc.periodic.iterate to create 10K relationships at a time in separate transactions, in parallel. <code>CALL apoc.periodic.iterate( 'MATCH (w1:Word), (w2:Word) WHERE ID(w1) < ID(w2) RETURN w1, w2', 'CREATE (w1)-[:DISTANCE]->(w2)', {batchSize:10000, parallel:true}) YIELD batches, total RETURN * </code> NOTE 1: This query assumes that you start out without any <code>DISTANCE</code> relationships in the DB, so it uses the cheaper <code>CREATE</code> clause instead of <code>MERGE</code>. If <code>DISTANCE</code> relationships exist already, then use <code>MERGE</code> instead (but this could create a second relationship between the same pair if the first relationship was in the opposite direction). NOTE 2: Performing the batches in parallel should be safe because issue #2 is not possible with the new Cypher code. If 2 transactions were to attempt to create relationships in opposite directions between the same 2 nodes at the same time, that could result in a deadlock, which would cause at least one of the transactions to fail. NOTE 3: This query assumes that the first statement (with the <code>MATCH</code> clause) does not itself run out of memory or take too long to process. If that assumption is wrong, then using a suitably modified query with apoc.periodic.commit should work. Comment: Thanks for your help and for pointing me towards apoc. I tried out the query. It executed in 30 minutes. It sure is slow though. :(
[{"idx": "Android_Studio_inexplicable_error_in_debug_APK", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-22611.jsonl"}, {"idx": "mongodump_fails_after_exactly_10_minutes", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-22611.jsonl"}, {"idx": "Neo4j_Cypher_Optimize_Create_relationship_between_each_node_in_cartesian_product", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-22611.jsonl"}]
import ply.yacc as yacc from nodes import * from lexer import MyLexer from .syntactic_error import SyntaxError import sys class MyParser(): def __init__(self, build_parser=True, debug=False, write_tables=True, optimize=True, outputdir="", yacctab="pycoolc.yacctab", debuglog=None, errorlog=None, tracking =True): self.build(debug=debug, write_tables=write_tables, optimize=optimize, outputdir=outputdir, yacctab=yacctab, debuglog=debuglog, errorlog=errorlog) # Build the parser debug = kwargs.get("debug") write_tables = kwargs.get("write_tables") optimize = kwargs.get("optimize") outputdir = kwargs.get("outputdir") yacctab = kwargs.get("yacctab") debuglog = kwargs.get("debuglog") self.lexer = MyLexer() self.tokens = self.lexer.tokens self.errors = [] self.parser = yacc.yacc(module=self, write_tables=write_tables, debug=debug, optimize=optimize, outputdir=outputdir, tabmodule=yacctab, debuglog=debuglog, errorlog=yacc.NullLogger()) def parse(self, _cool_program): return self.parser.parse(_cool_program) def find_col(self, input, lexpos): _start = input.rfind('\n', 0, lexpos) + 1 return (lexpos - _start) + 1 # Precedence rules precedence = ( ('right', 'ASSIGN'), ('right', 'NOT'), ('nonassoc', 'LESS', 'LESSEQ', 'EQUAL'), ('left', 'MULTIPLY', 'DIVIDE'), ('right', 'ISVOID'), ('right', 'NOX'), ('right', 'ARROBA'), ('right', 'DOT') ) # Grammar rules declarations def p_program(self, p): ''' program : class_list ''' p[0] = ProgramNode(classes=p[1]) def p_class_list(self, p): ''' class_list : class_list class SEMIC | class SEMIC ''' def p_def_class(self, p): ''' class : CLASS TYPE LBRACE feature_opt RBRACE ''' p[0] = ClassNode( name=p[2], parent='Object', features=p[4], row=p.lineno(2), col=self.find_col(p.lexer.lexdata, p.lexpos(2))) def p_def_class_inherits(self, p): ''' class : CLASS TYPE INHERITS TYPE LBRACE feature_opt RBRACE ''' p[0] = ClassNode( name=p[2], parent=p[4], features=p[6], row=p.lineno(2), col=self.find_col(p.lexer.lexdata, p.lexpos(4))) def p_feature_list(self, p): ''' feature_list : feature_list feature SEMIC | feature SEMIC ''' def p_feature_opt(self, p): ''' feature_opt : feature_list | empty ''' p[0] = tuple() if p.slice[1].type == "empty" else p[1] def p_feature_f_class_method(self, p): ''' feature : ID LPAREN formal_param_list RPAREN COLON TYPE LBRACE expr RBRACE ''' name=p[1], params=p[3], expression=p[8], return_type=p[6], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_feature_class_method(self, p): ''' feature : ID LPAREN RPAREN COLON TYPE LBRACE expr RBRACE ''' name=p[1], params=tuple(), expression=p[7], return_type=p[5], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_feature_attr(self, p): ''' feature : attr_init ''' p[0] = p[1] def p_attr_init(self, p): ''' attr_init : ID COLON TYPE ASSIGN expr | attr_def ''' p[0] = p[1] if len(p) == 2 else AttrInitNode( name=p[1], attr_type=p[3], expression=p[5], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_attr_def(self, p): ''' attr_def : ID COLON TYPE ''' p[0] = AttrDefNode( name=p[1], attr_type=p[3], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_action_list(self, p): ''' action_list : action_list action | action ''' p[0] = (p[1],) if len(p) == 2 else tuple(p[1]) + (p[2],) def p_let_var(self, p): ''' let_var : let_init | let_var COMMA let_init ''' def p_let_init(self, p): ''' let_init : ID COLON TYPE ASSIGN expr | let_def ''' p[0] = p[1] if len(p) == 2 else LetInitNode( name=p[1], let_type=p[3], expression=p[5], row=p.lineno(2), col=self.find_col(p.lexer.lexdata, p.lexpos(2))) def p_let_def(self, p): ''' let_def : ID COLON TYPE ''' p[0] = LetDefNode( name=p[1], let_type=p[3], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_formal_param_list(self, p): ''' formal_param_list : formal_param_list COMMA formal_param | formal_param ''' def p_formal_param(self, p): ''' formal_param : ID COLON TYPE ''' p[0] = FormalParamNode( name=p[1], param_type=p[3], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_args_list(self, p): ''' args_list : args_list COMMA expr | expr ''' def p_args_list_opt(self, p): ''' args_list_opt : args_list | empty ''' p[0] = tuple() if p.slice[1].type == "empty" else p[1] def p_action(self, p): ''' action : ID COLON TYPE ARROW expr SEMIC ''' p[0] = ActionNode( name=p[1], act_type=p[3], body=p[5], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_expr_dynamic_call(self, p): ''' expr : expr DOT ID LPAREN args_list_opt RPAREN ''' obj=p[1], method=p[3], args=p[5], row=p.lineno(3), col=self.find_col(p.lexer.lexdata, p.lexpos(3))) def p_expr_static_call(self, p): ''' expr : expr ARROBA TYPE DOT ID LPAREN args_list_opt RPAREN ''' p[0] = StaticCallNode( obj=p[1], static_type=p[3], method=p[5], args=p[7], row=p.lineno(5), col=self.find_col(p.lexer.lexdata, p.lexpos(5))) def p_expr_self_call(self, p): ''' expr : ID LPAREN args_list_opt RPAREN ''' obj=IdNode('self', row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))), method=p[1], args=p[3], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_expr_assign(self, p): ''' expr : ID ASSIGN expr ''' p[0] = AssignNode( name=p[1], expression=p[3], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_expr_if(self, p): ''' expr : IF expr THEN expr ELSE expr FI ''' p[0] = IfNode( predicate=p[2], then_expr=p[4], else_expr=p[6], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_expr_while(self, p): ''' expr : WHILE expr LOOP expr POOL ''' p[0] = WhileNode( predicate=p[2], expression=p[4], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_block_list(self, p): ''' block_list : block_list expr SEMIC | expr SEMIC ''' def p_expr_block(self, p): ''' expr : LBRACE block_list RBRACE ''' p[0] = BlockNode( expr_list=p[2], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_expr_simple_let(self, p): ''' expr : let_expr ''' p[0] = p[1] def p_expr_let(self, p): ''' let_expr : LET let_var IN expr ''' p[0] = LetNode( init_list=p[2], body=p[4], row=p.lineno(2), col=self.find_col(p.lexer.lexdata, p.lexpos(2))) def p_expr_case(self, p): ''' expr : CASE expr OF action_list ESAC ''' p[0] = CaseNode( expression=p[2], act_list=p[4], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_expr_new(self, p): ''' expr : NEW TYPE ''' p[0] = NewNode( new_type=p[2], row=p.lineno(2), col=self.find_col(p.lexer.lexdata, p.lexpos(2))) def p_expr_isvoid(self, p): ''' expr : ISVOID expr ''' p[0] = IsVoidNode( expression=p[2], row=p.lineno(2), col=self.find_col(p.lexer.lexdata, p.lexpos(2))) def p_expr_id(self, p): ''' expr : ID ''' p[0] = IdNode( name=p[1], row=p.lineno(1), col=self.find_col(p.lexer.lexdata, p.lexpos(1))) def p_expr_int(self, p): ''' expr : INTEGER ''' p[0] = IntegerNode( def p_expr_str(self, p): ''' expr : STRING ''' p[0] = StringNode( def p_expr_bool(self, p): ''' expr : TRUE | FALSE ''' p[0] = BooleanNode( def p_expr_binary_op(self, p): ''' expr : expr PLUS expr | expr MINUS expr | expr MULTIPLY expr | expr DIVIDE expr | expr LESS expr | expr LESSEQ expr | expr EQUAL expr ''' if p[2] == '+': p[0] = SumNode( elif p[2] == '-': p[0] = SubNode( elif p[2] == '*': p[0] = MultNode( elif p[2] == '/': p[0] = DivNode( elif p[2] == '<': p[0] = LessNode( elif p[2] == '<=': p[0] = LessEqualNode( elif p[2] == '=': p[0] = EqualsNode( def p_expr_unary_op(self, p): ''' expr : NOX expr | NOT expr ''' if p[1] == '~': p[0] = LogicNotNode( elif p[1].lower() == 'not': p[0] = NotNode( def p_expr_parenthesis(self, p): ''' expr : LPAREN expr RPAREN ''' p[0] = p[2] def p_empty(self, p): ''' empty : ''' p[0] = None # Error rule for Syntax Errors handling def p_error(self, p): if p: self.errors.append(SyntaxError(f'"ERROR at or near {p.value}"', p.lineno, self.find_col(p.lexer.lexdata, p.lexpos))) self.parser.errok() else: self.errors.append(SyntaxError('"ERROR at or near EOF"',0,0)) return<|endoftext|>arXiv:1512.03385 ''' def __init__( self, n_inputs: int, n_hidden: int, ) -> None: '''Residual block with fully-connected neural network layers. Parameters ---------- n_inputs : int number of input dimensions. n_hidden : int number of hidden dimensions in the Residual Block. Returns ------- None. ''' # Build the initial projection layer self.linear00 = nn.Linear(self.n_inputs, self.n_hidden) self.norm00 = nn.BatchNorm1d(num_features=self.n_hidden) self.relu00 = nn.ReLU(inplace=True) # Map from the latent space to output space self.linear01 = nn.Linear(self.n_hidden, self.n_hidden) self.norm01 = nn.BatchNorm1d(num_features=self.n_hidden) self.relu01 = nn.ReLU(inplace=True) return def forward(self, x: torch.FloatTensor, ) -> torch.FloatTensor: '''Residual block forward pass. Parameters ---------- x : torch.FloatTensor [Batch, self.n_inputs] Returns ------- o : torch.FloatTensor [Batch, self.n_hidden] ''' identity = x # Project input to the latent space o = self.norm00(self.linear00(x)) o = self.relu00(o) # Project from the latent space to output space o = self.norm01(self.linear01(o)) # Make this a residual connection # by additive identity operation o += identity return self.relu01(o) class CellTypeCLF(nn.Module): '''Cell type classifier from expression data. Attributes ---------- n_genes : int number of input genes in the model. n_cell_types : int number of output classes in the model. n_hidden : int number of hidden units in the model. n_layers : int number of hidden layers in the model. init_dropout : float dropout proportion prior to the first layer. residual : bool use residual connections. ''' def __init__( self, n_genes: int, n_cell_types: int, n_hidden: int = 256, n_layers: int = 2, init_dropout: float = 0.0, batch_norm: bool = True, track_running_stats: bool = True, ) -> None: ''' Cell type classifier from expression data. Linear layers with batch norm and dropout. Parameters ---------- n_genes : int n_cell_types : int number of cell types for the output n_hidden : int number of hidden unit n_layers : int number of hidden layers. init_dropout : float residual : bool batch_norm : bool use batch normalization in hidden layers. track_running_stats : bool track running statistics in batch norm layers. Returns ------- None. ''' super(CellTypeCLF, self).__init__() self.n_genes = n_genes self.n_cell_types = n_cell_types self.init_dropout = init_dropout self.track_running_stats = track_running_stats # simulate technical dropout of scRNAseq self.init_dropout = nn.Dropout(p=self.init_dropout) # Define a vanilla NN layer with batch norm, dropout, ReLU vanilla_layer = [ nn.Linear(self.n_hidden, self.n_hidden), ] if self.batch_norm: vanilla_layer += [ track_running_stats=self.track_running_stats, ), ] vanilla_layer += [ nn.Dropout(), ] # Define a residual NN layer with batch norm, dropout, ReLU residual_layer = [ ResBlock(self.n_hidden, self.n_hidden), ] if self.batch_norm: residual_layer += [ ), ] residual_layer += [ nn.Dropout(), ] # Build the intermediary layers of the model if self.residual: hidden_layer = residual_layer else: hidden_layer = vanilla_layer hidden_layers = hidden_layer*self.n_layers # Build the classifier `nn.Module`. self.classif = nn.Sequential( nn.Linear(self.n_genes, self.n_hidden), nn.BatchNorm1d( ), nn.Dropout(), *hidden_layers, nn.Linear(self.n_hidden, self.n_cell_types) ) return def forward( self, x: torch.FloatTensor, ) -> torch.FloatTensor: Parameters ---------- x : torch.FloatTensor [Batch, self.n_genes] Returns ------- ''' # add initial dropout noise if self.init_dropout.p > 0: # expm1 to normed counts x = torch.expm1(x) x = self.init_dropout(x) # renorm to log1p CPM size = torch.sum(x, dim=1).reshape(-1, 1) prop_input_ = x / size norm_input_ = prop_input_ * 1e6 x = torch.log1p(norm_input_) pred = self.classif(x) return pred class GradReverse(torch.autograd.Function): '''Layer that reverses and scales gradients before passing them up to earlier ops in the computation graph during backpropogation. ''' @staticmethod def forward(ctx, x, weight): ''' Perform a no-op forward pass that stores a weight for later gradient scaling during backprop. Parameters ---------- x : torch.FloatTensor [Batch, Features] weight : float weight for scaling gradients during backpropogation. stored in the "context" ctx variable. Notes ----- We subclass `Function` and use only @staticmethod as specified in the newstyle pytorch autograd functions. [IDX] We define a "context" ctx of the class that will hold any values passed during forward for use in the backward pass. `x.view_as(x)` and `*1` are necessary so that `GradReverse` is actually called `torch.autograd` tries to optimize backprop and excludes no-ops, so we have to trick it :) ''' # store the weight we'll use in backward in the context ctx.weight = weight return x.view_as(x) * 1 @staticmethod '''Return gradients Returns ------- rev_grad : torch.FloatTensor reversed gradients scaled by `weight` passed in `.forward()` None : None a dummy "gradient" required since we passed a weight float in `.forward()`. ''' # here scale the gradient and multiply by -1 # to reverse the gradients return (grad_output * -1 * ctx.weight), None class DANN(nn.Module): '''Build a domain adaptation neural network''' def __init__( self, model: CellTypeCLF, n_domains: int=2, weight: float=1., n_layers: int=1, ) -> None: '''Build a domain adaptation neural network using the embedding of a provided model. Parameters ---------- model : CellTypeCLF cell type classification model. n_domains : int number of domains to adapt. weight : float weight for reversed gradients. n_layers : int number of hidden layers in the network. Returns ------- None. ''' super(DANN, self).__init__() self.model = model self.n_domains = n_domains *list(list(model.modules())[0].children())[1][:-1] ) hidden_layers = [ nn.Linear(self.model.n_hidden, self.model.n_hidden), nn.ReLU(), ] * n_layers self.domain_clf = nn.Sequential( *hidden_layers, nn.Linear(self.model.n_hidden, self.n_domains), ) return def set_rev_grad_weight( self, weight: float, ) -> None: '''Set the weight term used after reversing gradients''' self.weight = weight return def forward( self, x: torch.FloatTensor, ) -> (torch.FloatTensor, torch.FloatTensor): '''Perform a forward pass. Parameters ---------- x : torch.FloatTensor [Batch, Features] input. Returns ------- domain_pred : torch.FloatTensor [Batch, n_domains] logits. x_embed : torch.FloatTensor [Batch, n_hidden] ''' # get the model embedding x_embed = self.embed(x) # reverse gradients and scale by a weight x_rev = GradReverse.apply( x_embed, self.weight, ) # classify the domains domain_pred = self.domain_clf(x_rev) return domain_pred, x_embed class CellTypeCLFConditional(CellTypeCLF): '''Conditional vartiaton of the `CellTypeCLF` Attributes ---------- n_genes : int number of the input features corresponding to genes. n_tissues : int length of the one-hot `upper_group` vector appended to inputs. ''' def __init__( self, n_genes: int, n_tissues: int, **kwargs, ) -> None: Parameters ---------- n_genes : int n_tissues : int number of tissues encoded in the conditional vector. Returns ------- None. Notes ----- Assumes that inputs are `n_genes + n_tissues`, concatenated [Genes :: Tissue-One-Hot]. Passes `**kwargs` to `CellTypeCLF`. ''' # Build a CellTypeCLF with `n_genes` + `n_tissues` input nodes to # take both the gene vector and one-hot upper_group label as input super(CellTypeCLFConditional, self).__init__( n_genes=(n_genes + n_tissues), **kwargs) self.n_tissues = n_tissues return def forward( self, x: torch.FloatTensor, ) -> torch.FloatTensor: Parameters ---------- x : torch.FloatTensor [Batch, self.n_genes + self.n_tissues] Returns ------- ''' # don't pass one_hot labels through the initial dropout one_hot = x[:, -self.n_tissues:] genes = x[:, :-self.n_tissues] genes = self.init_dropout(genes) x_drop = torch.cat([genes, one_hot], dim=1) # classify on the full genes + one-hot input pred = self.classif(x_drop) return pred
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-6806.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-6806.jsonl"}]
# a simple attendance def attendance(): names = [] total_students = int(input("Enter the total number of students: ")) absent = int(input("Enter the number of absentees: ")) if absent > 0 and absent > 4 and absent != 0: for i in range(0,total_students): name = input("Enter the absentees name and type 'ok' to print: ") if name == 'ok': break else: continue present = total_students - absent if present == total_students: print("Good! All are present today.!") elif absent == 1: print("Ask" + names[0], " to meet me tomorrow.") elif absent == 2: print("Tell " + names[0]+ ' and'+ names[1]+ " to meet me tomorrow.") elif absent == 3: print("Tell "+ names[0]+ ", "+ names[1]+ " and "+ names[2]+ " to come with their parents.") else: print("Inform all the", absent, "absentees to meet the principal.") attendance()<|endoftext|>""" """ import re import sys def main(argv=None): argv = argv or sys.argv tsv_file = _validate_input(argv) faulty_lines = [] with open(tsv_file) as f: tsv_lines = [x.strip().split('\t') for x in f.readlines()] for line in tsv_lines: try: faulty_lines.append((line[0], line[3].split(',')[0])) print(line) with open('faulty-lines.csv', 'w+') as out_f: for l in faulty_lines: m = re.search(r'.*\(([a-zA-Z0-9]+\.java):([0-9]+)\)', l[1]) out_f.write('{},{},{}\n'.format(l[0], m.group(1), m.group(2))) def _print_usage(): print('Usage: python3 format_spreadsheet_faulty_line.py <tsv_file>') print('tsv_file: The filepath to the tsv separated file containing stuff from the spreadsheet.') def _validate_input(argv): if len(argv) != 2: _print_usage() sys.exit(1) tsv_file = argv[1] return tsv_file if __name__ == '__main__': sys.exit(main())<|endoftext|>"""Other useful functions.""" __all__ = ["binary_search"] def binary_search(sorted_list: List[Any], value: Any, list_size: Optional[int] = None) -> int: # todo: remove? """ Performs binary search. :param sorted_list: List with values in ascending order. :param value: Value for which position in the list is searched. :param list_size: Size of the sorted_list. :return: Index i of element such as: sorted_list[i-1] < value <= sorted_list[i] """ if value < sorted_list[0] or value > sorted_list[-1]: raise ValueError(f"Parameter 'value' is out of range. Expected: {sorted_list[0]} <= value <= {sorted_list[-1]}." f" Actual value: {value}.") i_low = 0 i_high = len(sorted_list) - 1 if list_size is None else list_size - 1 while i_low < i_high: i_mid = (i_low + i_high) // 2 if sorted_list[i_mid] < value: i_low = i_mid + 1 else: i_high = i_mid return i_high<|endoftext|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Fixtures for testing the 'seamm_ff_util' package.""" import pytest from molsystem import SystemDB from seamm_ff_util import Forcefield from seamm_ff_util import FFAssigner @pytest.fixture(scope="session") def pcff(): """A forcefield object initialized with PCFF""" pcff = Forcefield("data/pcff2018.frc") pcff.initialize_biosym_forcefield() return pcff @pytest.fixture(scope="session") def pcff_assigner(pcff): """A forcefield object initialized with PCFF""" pcff_assigner = FFAssigner(pcff) return pcff_assigner @pytest.fixture() def configuration(): """Create a system db with no systems.""" db = SystemDB(filename="file:seamm_db?mode=memory&cache=shared") system = db.create_system(name="default") configuration = system.create_configuration(name="default") yield configuration db.close() try: del db except: # noqa: E722 print("Caught error deleting the database")<|endoftext|>import numpy as np def get_data(seed=101, mix_dim=6, task_type='linear', samples=4000): # 10kHz, 4000 samples by default # This version of the task adds laplacian noise as a source and uses a # non-linear partially non-invertible, possibly overdetermined, # transformation. np.random.seed(seed) t = np.linspace(0, samples * 1e-4, samples) two_pi = 2 * np.pi s0 = np.sign(np.cos(two_pi * 155 * t)) s1 = np.sin(two_pi * 800 * t) s2 = np.sin(two_pi * 300 * t + 6 * np.cos(two_pi * 60 * t)) s3 = np.sin(two_pi * 90 * t) s4 = np.random.uniform(-1, 1, (samples,)) s5 = np.random.laplace(0, 1, (samples,)) x = np.stack([s0, s1, s2, s3, s4, s5]) mix_mat = np.random.uniform(-.5, .5, (mix_dim, 6)) y = np.dot(mix_mat, x) if task_type in ['mlp', 'pnl']: y = np.tanh(y) if task_type == 'mlp': mix_mat2 = np.random.uniform(-.5, .5, (mix_dim, mix_dim)) y = np.tanh(np.dot(mix_mat2, y)) return x, y, mix_mat<|endoftext|>''' 加载fashion_mnist,可视化展示 ''' import tensorflow as tf import numpy as np import time import sys feature,label=x_train[0],y_train[0] # print(feature,label) # 将标签换成文字表示 def get_fashion_mnist_labels(labels): text_labels=['t-shirt','trouser','pollover','dress','coat','sandal','shirt','sneaker','bag','ankle boot'] # 展示图片 _,figs=plt.subplots(1,len(images),figsize=(12,12)) for f ,img,lbl in zip(figs,images,labels): f.imshow(img.reshape((28,28))) f.set_title(lbl) f.axes.get_xaxis().set_visible(False) f.axes.get_yaxis().set_visible(False) plt.show() #提取10张 X,y = [],[] for i in range(10): X.append(x_train[i]) y.append(y_train[i]) show_fashion_mnist(X,get_fashion_mnist_labels(y)) batch_size=256 num_works=0 else: num_works=4 train_iter=tf.data.Dataset.from_tensor_slices((x_train,y_train)).batch(batch_size) start=time.time() for X,y in train_iter: continue print('%.2f sec'%(time.time()-start))<|endoftext|>import numpy as np import sys if len(sys.argv) > 1: filename = sys.argv[1] else: filename = 'datavol_features_1core_56_n4_1024.npz' scores = data['scores'] indices = data['indices'] results = data['results'] features = data['features'] configs = data['configs'] from IPython import embed embed() level = 0 for level in [0,1,2]: for add in [0,3,6]: # for other_level in [1,2]: # other_level = (other_level + level) % 3 # print(level, other_level) plt.subplot(2,1,1) plt.scatter(features[:,add+level],results)#, s=features[:,6+other_level]/features[:,6+other_level].min()) # plt.xlabel('L%i Data Volume, Size=L%i' % (level+1, other_level+1)) plt.ylabel('Time') plt.title('Full Footprint') #plt.show() plt.subplot(2,1,2) plt.scatter(features[:,add+9+level],results)#, s=features[:,15+other_level]/features[:,15+other_level].min()) plt.ylabel('Time') plt.title('Array Footprint') plt.show()<|endoftext|>import unittest from pulsar.apps.test import test_wsgi_request class AcceptTests(unittest.TestCase): async def test_empty_mime(self): ('Accept', None)]) self.assertFalse(content_types) async def test_content_types(self): self.assertEqual(len(content_types), 4) self.assertEqual(id(content_types), id(request.content_types)) self.assertTrue('text/html' in content_types) self.assertTrue('text/plain' in content_types) self.assertEqual(content_types.quality('text/html'), 1) self.assertEqual(content_types.quality('text/plain'), 0.8) self.assertEqual(content_types.quality('application/json'), 0.8) self.assertEqual(content_types.best, 'text/html') async def test_best(self): self.assertEqual(content_types.best_match(('text/html', 'application/json')), self.assertEqual(content_types.best_match(('application/json', ),<|endoftext|>import os from nornir.plugins.tasks import data from ruamel.yaml.scanner import ScannerError data_dir = "{}/test_data".format(os.path.dirname(os.path.realpath(__file__))) class Test(object): def test_load_yaml(self, nornir): test_file = "{}/simple.yaml".format(data_dir) result = nornir.run(data.load_yaml, file=test_file) for h, r in result.items(): d = r.result assert d["env"] == "test" assert d["services"] == ["dhcp", "dns"] def test_load_yaml_error_broken_file(self, nornir): test_file = "{}/broken.yaml".format(data_dir) processed = False processed = True assert isinstance(result.exception, ScannerError) assert processed def test_load_yaml_error_missing_file(self, nornir): test_file = "{}/missing.yaml".format(data_dir) processed = False processed = True assert isinstance(result.exception, FileNotFoundError) assert processed<|endoftext|>from threading import Lock from uuid import uuid4 import time app = Flask(__name__) app.debug = True socketio = SocketIO(app) thread = None thread_lock = Lock() async_mode = None def background_timer(): while True: time.sleep(1) t = str(datetime.utcnow() + timedelta(hours=5, minutes=30)) socketio.emit('time', {'data': 'This is data', 'time': t}, namespace='/test') @app.route('/') def index(): return render_template('index.html', async_mode=socketio.async_mode) def connected(): print('Client connected') socketio.emit('message', {'data': 'Connected', 'count': 0}) global thread with thread_lock: if thread is None: thread = socketio.start_background_task(target=background_timer) def disconnected(): print('Client disconnected') @socketio.on('uuid', namespace='/test') def send_uuid(): socketio.emit('uuid', {'uuid': str(uuid4())}, namespace='/test') @socketio.on('hex', namespace='/test') def send_hex(): socketio.emit('hex', {'hex': str(uuid4().hex)}, namespace='/test')
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12444.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12444.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12444.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12444.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12444.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12444.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12444.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12444.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12444.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-12444.jsonl"}]
""" add status message feedback include buttons if useful """ import mido import threading import time class Main(threading.Thread): def __init__(self, hostname, midi_receiver): self.midi_receiver = midi_receiver self.input_name = "" self.start() def run(self): while True: try: with mido.open_input(self.input_name) as inport: print("midi connected") #print(midi_o) if midi_o.type == "note_on": self.midi_receiver("oxygen88", ["note_on", midi_o.note], self.hostname, self.hostname) if midi_o.type == "note_off": self.midi_receiver("oxygen88",["note_off", midi_o.note], self.hostname, self.hostname) if midi_o.type == "control_change": self.midi_receiver("oxygen88",["slider1", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["slider2", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["slider3", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["slider4", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["slider5", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["slider6", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["slider7", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["slider8", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["slider9", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["knob1", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["knob2", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["knob3", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["knob4", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["knob5", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["knob6", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["knob7", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["knob8", midi_o.value], self.hostname, self.hostname) self.midi_receiver("oxygen88",["modwheel", midi_o.value], self.hostname, self.hostname) if midi_o.type == "pitchwheel": self.midi_receiver("oxygen88",["pitchwheel", midi_o.pitch], self.hostname, self.hostname) input_names = mido.get_input_names() if input_name.startswith("Oxygen"): self.input_name = input_name #print(input_names) time.sleep(5)<|endoftext|># structure largely adapted from Mopidy-Soundcloud # [IDX] logging import cachetools.func import pykka import requests from mopidy.audio import Audio import mopidy_jamendo def get_requests_session( proxy_config: dict, user_agent: str ) -> requests.Session: session.proxies.update({" http": proxy, " https": proxy}) session.headers.update({"user-agent": full_user_agent}) return session def parse_track(data: dict) -> Optional[Track]: if not data: return None track_kwargs = {} artist_kwargs = {} album_kwargs = {} if "name" in data: track_kwargs["name"] = data["name"] if "artist_name" in data: artist_kwargs["name"] = data["artist_name"] album_kwargs["name"] = "Jamendo" if "releasedate" in data: track_kwargs["date"] = data["releasedate"] track_kwargs["uri"] = data["audio"] track_kwargs["length"] = int(data.get("duration", 0) * 1000) track_kwargs["comment"] = data.get("shareurl", "") if artist_kwargs: track_kwargs["artists"] = [Artist(**artist_kwargs)] if album_kwargs: track_kwargs["album"] = Album(**album_kwargs) return Track(**track_kwargs) class JamendoClient: super().__init__() self. http_client = get_requests_session( proxy_config=config["proxy"], user_agent=( f"{mopidy_jamendo.Extension.dist_name}/" f"{mopidy_jamendo.__version__}" ), ) self.client_id = config["jamendo"]["client_id"] def _get(self, url: str, params: dict = None) -> dict: url = f" [IDX] if not params: params = {} params["client_id"] = self.client_id try: with closing(self. http_client.get(url, params=params)) as res: logger.debug(f"Requested {res.url}") logger.error( 'Invalid "client_id" used for Jamendo authentication!' ) else: logger.error(f"Jamendo API request failed: {e}") return {} @cachetools.func.ttl_cache(ttl=3600) def get_track(self, track_id: str) -> Optional[Track]: logger.debug(f"Getting info for track with ID {track_id}") try: result = self._get("tracks/", params={"id": track_id})["results"][0] logger.warning(f"No results for track {track_id}") return None track = parse_track(result) return track class JamendoPlaybackProvider(backend.PlaybackProvider): def translate_uri(self, uri: str) -> Optional[str]: if "jamendo:track:" in uri: uri = uri[len("jamendo:track:") :] track = self.backend.remote.get_track(uri) if track is None: return None return track.uri return None class JamendoLibraryProvider(backend.LibraryProvider): def lookup(self, uri: str) -> List[Optional[Track]]: if "jamendo:track:" in uri: uri = uri[len("jamendo:track:") :] return [self.backend.remote.get_track(uri)] return [None] class JamendoBackend(pykka.ThreadingActor, backend.Backend): def __init__(self, config: dict, audio: Audio): super(JamendoBackend, self).__init__() self.audio = audio self.config = config self.remote = JamendoClient(config) self.library = JamendoLibraryProvider(backend=self) self.playback = JamendoPlaybackProvider(audio=audio, backend=self) self.uri_schemes = ["jamendo"]<|endoftext|>import sys import torch from src.msva_models import MSVA_Gen_auto import numpy as np #from src.sys_utils import plotData import h5py import os import glob import cv2 class obj(object): def __init__(self, d): else: def getSmoothOutput(yArray,mastSize=5): maskedOut = [] for i in range(len(yArray)-mastSize): maskedOut.append(np.mean(yArray[i:i+mastSize])) return maskedOut def getParameter(param): if(sys.argv[i]==param): return sys.argv[i+1] def getVidIndexFromObjectFeatures(video_name,dataset): allFiles = glob.glob("datasets"+os.sep+"kinetic_features"+os.sep+dataset+os.sep+"FLOW"+os.sep+"features"+os.sep+"*") videoDict = {} for i in range(len(allFiles)): fname = allFiles[i].split(os.sep)[-1].split(".")[0] videoDict[fname] = "video_"+str(i+1) return videoDict print('Argument are:', str(sys.argv)) print("-model_weight: ", getParameter("-model_weight")) print("-video_name: ", getParameter("-video_name")) print("-dataset: ", getParameter("-dataset")) #dataset = "summe" #video_name = "Air_Force_One" #model_weight = "model_weights/summe_random_non_overlap_0.5359.tar.pth" dataset = getParameter("-dataset") video_name = getParameter("-video_name") model_weight = getParameter("-model_weight") videoDict = getVidIndexFromObjectFeatures(video_name,dataset) saveImg = True dpi = 100 if(video_name not in videoDict): print("video name not found !!!") else: print("video name found and corresponding index: ",videoDict[video_name]) video_index = videoDict[video_name] cmb = [1,1,1] feat_input = {"feature_size":365,"L1_out":365,"L2_out":365,"L3_out":512,"pred_out":1,"apperture":250,"dropout1":0.5,"att_dropout1":0.5,"feature_size_1_3":1024,"feature_size_4":365} feat_input_obj = obj(feat_input) model = MSVA_Gen_auto(feat_input_obj,cmb) model.load_state_dict(torch.load(model_weight, map_location=lambda storage, loc: storage)) datasetsH5 = h5py.File("datasets"+os.sep+"object_features"+os.sep+"eccv16_dataset_summe_google_pool5.h5", 'r') seq1 = datasetsH5[videoDict[video_name]]['features'][...] seq2 = np.load("datasets"+os.sep+"kinetic_features"+os.sep+"summe"+os.sep+"FLOW"+os.sep+"features"+os.sep+video_name+".npy") # you can provide features from another video seq3 = np.load("datasets"+os.sep+"kinetic_features"+os.sep+"summe"+os.sep+"RGB"+os.sep+"features"+os.sep+video_name+".npy") minShape=np.min([seq1.shape[0],seq2.shape[0],seq3.shape[0]]) seq1 = cv2.resize(seq1, (seq1.shape[1],minShape), interpolation = cv2.INTER_AREA) seq2 = cv2.resize(seq2, (seq2.shape[1],minShape), interpolation = cv2.INTER_AREA) seq3 = cv2.resize(seq3, (seq3.shape[1],minShape), interpolation = cv2.INTER_AREA) seq_len = seq1.shape[1] seq1 = torch.from_numpy(seq1).unsqueeze(0) seq2 = torch.from_numpy(seq2).unsqueeze(0) seq3= torch.from_numpy(seq3).unsqueeze(0) print("feature source 1 shape: ",seq1.shape) print("feature source 2 shape: ",seq2.shape) print("feature source 3 shape: ",seq3.shape) y, _ = model([seq1,seq2,seq3],seq_len) yArray = y.detach().numpy()[0] yArray= getSmoothOutput(yArray) # print("output y_hat: ", y) xLab = "video time lime" yLab = "score to be in video summary" tittle = "prediction_score_for_video_summary" plt.xlabel(xLab) plt.ylabel(yLab) plt.title(tittle) plt.grid(True) plt.plot(yArray) if(saveImg): plt.savefig("media"+os.sep+tittle+'.png',bbox_inches='tight', dpi=dpi) plt.show()
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11135.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11135.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-11135.jsonl"}]
Q: How to add a sphere in tikzpicture with rotated coordinate? I want to put a sphere in the origin of my rotated coordinate, but in the end the sphere becomes distort. Any way to fix this? Here is the Overleaf code. And the main file (you need 3dplot.sty too) is here: \documentclass{article} %%%< \usepackage{verbatim,amsmath} %%%> \begin{comment} :Title: The 3dplot package :Zip: 3dplot.sty \end{comment} \usepackage{3dplot} %requires 3dplot.sty to be in same directory, or in your LaTeX installation \setlength\PreviewBorder{2mm} \begin{document} %Angle Definitions %----------------- \tdplotsetmaincoords{60}{110} \pgfmathsetmacro{\rvec}{.8} \pgfmathsetmacro{\phivec}{60} %set up some coordinates %----------------------- \coordinate (O) at (0,0,0); This command %of the point (P). %draw figure contents %-------------------- %"theta plane" of the main coordinate system %draw Center of mass %draw normal vector \shadedraw [ball color=red] (0,0,0) circle(0.1); \end{tikzpicture} \end{document} A: For this purpose, tikz-3dplot comes with tdplot_screen_coords, i.e. does the trick. Since there is a typo in your MWE (the package is tikz-3dplot, not 3dplot), for the sake of reproducibility I add a complete MWE: \documentclass{article} %%%< \usepackage{verbatim,amsmath} %%%> \begin{comment} :Title: The 3dplot package :Zip: 3dplot.sty \end{comment} \setlength\PreviewBorder{2mm} \begin{document} %Angle Definitions %----------------- \tdplotsetmaincoords{60}{110} \pgfmathsetmacro{\rvec}{.8} \pgfmathsetmacro{\phivec}{60} %set up some coordinates %----------------------- \coordinate (O) at (0,0,0); This command %of the point (P). %draw figure contents %-------------------- %"theta plane" of the main coordinate system %draw Center of mass %draw normal vector \end{tikzpicture} \end{document} Of course, things become more compelling if one draws these object in the correct order and does not let lines run into the interior of the sphere. \usepackage{amsmath} \begin{document} %Angle Definitions %----------------- \tdplotsetmaincoords{60}{110} \pgfmathsetmacro{\rvec}{.8} \pgfmathsetmacro{\phivec}{60} %set up some coordinates %----------------------- \coordinate (O) at (0,0,0); This command %of the point (P). \tdplotsetcoord{P'}{0.1}{\thetavec}{\phivec} %draw figure contents %-------------------- \draw[thick,->] (0.1,0,0) -- (1,0,0) node[anchor=north east]{$x$}; \draw[thick,->] (0,0.1,0) -- (0,1,0) node[anchor=north west]{$y$}; \draw[thick,->] (0,0,0.1) -- (0,0,1) node[anchor=south]{$z$}; \draw[-stealth,color=red] (P') -- (P); \draw[dashed, color=red] (P'xy) -- (Pxy); %"theta plane" of the main coordinate system %draw Center of mass %draw normal vector \end{tikzpicture} \end{document}<|endoftext|>Changing model prior to adding to database in .net core 2.0 Question: I'm trying to create an updateable events page for a website. An event may or may not have an image. In the model, I have simply used a bool called HasImage - if this is true, then the display page will display an image called [EventID].jpg I figured this would be the simplest way of doing it. I have added the code to upload the image, and images are uploading correctly, but I can't work out how to use the existence of the image in the create form to set HasImage correctly. This is a simplified version of the code... <code> [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("ID,Date,Details,HasImage")] Events events, IFormFile file) { if (ModelState.IsValid) { string hasImage = file.Length > 0 ? "False" : "True"; ModelState.SetModelValue("events.HasImage", new ValueProviderResult(hasImage, CultureInfo.InvariantCulture)); // also tried but failed: events.HasImage=hasImage (where hasImage was a bool) _context.Add(events); await _context.SaveChangesAsync(); int NewID = cH_Events.ID; var fileName = NewID + ".jpg"; if (file.Length > 0) { [upload stuff here] } return RedirectToAction(nameof(Index)); } return View(Events); } </code> NB HasImage does not appear on the form. It doesn't work whether or not I include it in the Bind list. I am assuming this is the best way to do this. An alternative would be to create a hidden form variable and use JavaScript. Comment: What does your code to show the Events view look like? Does the events get stored in the DB with the file uploaded? If so you can check if the image exists on the GET method of the page used to view the Events. Then set the hasImage on the ViewModel. Comment: The code in the view page works fine if I manually change the hasImage value. I could check that the image itself exists instead, but wouldn't that use more server resources? Answer: OK, after a tortuous process of trial and error, I have found a solution. Instead of trying to change the model before adding to the database, I've found that it's possible to add to database as normal, then change the model, and then update changes. This is a sample of the code that works (I have also changed hasImage to ImageType so that I can use different file types) <code> _context.Add(Events); await _context.SaveChangesAsync(); int NewID = Events.ID; if (file != null && file.Length > 0) { var fileType = System.IO.Path.GetExtension(file.FileName); [upload image code] cH_Events.ImageType = fileType; await _context.SaveChangesAsync(); } </code><|endoftext|>Is it safe to link to a static library built with different compiler flags Question: I use GoogleTest for testing my C++ projects, and after finding that precompiled libraries were no longer distributed in the Ubuntu package, I found the following on the project website: If you compile Google Test and your test code using different compiler flags, they may see different definitions of the same class/function/variable (e.g. due to the use of #if in Google Test). Therefore, for your sanity, we recommend to avoid installing pre-compiled Google Test libraries. Instead, each project should compile Google Test itself such that it can be sure that the same flags are used for both Google Test and the tests. What I take from this is that it's a bad idea to compile GoogleTest separately from the project being testing. What I don't understand is whether this is just a GoogleTest thing, or if this is a general thing for linking libraries. Question Is there any situation in which it is unsafe to link to precompiled third-party libraries, compiler flags or otherwise, and if not, what's so special about GoogleTest? Comment: Your quote seems to be missing the important part: `If you compile Google Test and your test code using different compiler flags, they may see different definitions of the same class/function/variable (e.g. due to the use of #if in Google Test).` Comment: I've updated the quote with the bit you point out. Answer: There are some compiler flags, notably those that work with alignment, that could cause a problem. From GCC i386 and x86-64 flags -malign-double -mno-align-double Control whether GCC aligns double, long double, and long long variables on a two-word boundary or a one-word boundary. Aligning double variables on a two-word boundary produces code that runs somewhat faster on a Pentium at the expense of more memory. On x86-64, -malign-double is enabled by default. Warning: if you use the -malign-double switch, structures containing the above types are aligned differently than the published application binary interface specifications for the 386 and are not binary compatible with structures in code compiled without that switch. For example, using that flag on a 32-bit system will for doubles and long longs to be 64-bit aligned. If you compile a library without the flag, then attempt to use the library while using the flag, structures that contain the types above may have different alignments, and may not interoperate. Other (much simpler) cases can also be ensuring the same set of #defines to ensure the same function/structure/class definitions are used (and other such ODR violations). For example, the use of '--std=c++11' in gcc, which enables the C++ 11 versions of the Standard Library classes, which in some cases are different than the previous versions. Comment: `s/will/may/g` -- depending on luck, the library may actually work just fine.<|endoftext|>Potty Training - From 'can hold pee' to 'goes to bathroom by himself' Question: We've started getting more serious about potty training our 2y10m old recently. He's definitely progressing and seems to be able to hold his pee now. When we encourage bathroom breaks and take him to the bathroom regularly he can often go a full day without an accident. What I'm wondering is: are there any methods we can use to encourage him to just get up and go to the bathroom by himself? Or is it something that we're just going to need to wait until it clicks, and he starts doing it? Comment: That's a good point. We actually managed to get him started by rewarding with chocolate chips (pee) and a larger chocolate egg (poo), but eventually he seemed happy enough to pee without the rewards (and pooping is still an ongoing challenge). Perhaps we could step up the reward with something better than a chocolate chip, in the event he does it himself. Comment: Have you thought of making it *rewarding* for him to do so? As in, what's more desirable, continuing to do the interesting thing he's doing at the moment or taking a bathroom break? Hint: at his age, almost anything is more interesting than going to the bathroom. One of my kids found a "toy" toilet/potty that could play many interesting sounds when "flushed". My grandchild could only flush if she actually urinated. My grandchild was hooked immediately. Maybe you can find a way to make going to the bathroom *interesting*. Comment: Though some would disagree, I'm a firm believer in bribes, um, I mean rewards, yeah, rewards. Chocolate is a wonderful reward. One of my kids toilet trained themself to completion in one week when I found the right reward! Comment: We didn't want to use them at first but we have a pretty bright kid who does what he wants. We knew he was ready, but he knew it was easier to be lazy. The incentive helped a lot (and he likes impressing his preschool teachers). Comment: I think at this age, you should expect to have to prompt him to go. Best thing you could do is to develop habits of going at certain times, like just after waking, just before bed, just before leaving the house. The ASL sign for potty is useful at this age as a discreet prompt. Answer: For a child to go to the toilet/potty by themselves, 2 things need to have happened for them They need to be able to feel when they need to pee or poo. And feel it far enough in advance to safely reach the toilet. They need to understand that going to the toilet is more important than whatever fun thing they are doing. The first your child has achieved. The second will come with time as your child develops. It can help if they learn that going to the toilet too late has a consequence like a longer interruption of the nice activity because a mess needs to be cleaned up first. Whereas going to the toilet on time means doing your business and going back to play with minimal interruption.
[{"idx": "https://tex.stackexchange.com/questions/457994", "domain": "stack_exchange", "domain2": "", "header_footer": "", "lang": "en", "source": "stack_exchange-7174.jsonl"}, {"idx": "Changing_model_prior_to_adding_to_database_in_.net_core_2.0", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-7174.jsonl"}, {"idx": "Is_it_safe_to_link_to_a_static_library_built_with_different_compiler_flags", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-7174.jsonl"}, {"idx": "Potty_Training_-_From_'can_hold_pee'_to_'goes_to_bathroom_by_himself'", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-7174.jsonl"}]
#### File: build_defs/internal_do_not_use/j2cl_java_library.bzl ```python load(":j2cl_transpile.bzl", "J2CL_TRANSPILE_ATTRS", "j2cl_transpile") load(":j2cl_js_common.bzl", "J2CL_JS_ATTRS", "JS_PROVIDER_NAME", "j2cl_js_provider") # Constructor for the Bazel provider for J2CL. # Note that data under "_private_" considered private internal data so do not use. J2clInfo = provider(fields = ["_private_"]) def _impl_j2cl_library(ctx): # Categorize the sources. js_srcs = [] java_srcs = [] for src in ctx.files.srcs: (js_srcs if src.extension in ["js", "zip"] else java_srcs).append(src) # Validate the attributes. if not java_srcs: if ctx.files.deps: fail("deps not allowed without java srcs") if js_srcs: fail("js sources not allowed without java srcs") java_provider = _java_compile(ctx, java_srcs) if java_srcs: output_js_zip = ctx.outputs.jszip output_library_info = ctx.actions.declare_file("%s_library_info" % ctx.attr.name) j2cl_transpile(ctx, java_provider, js_srcs, output_js_zip, output_library_info) js_outputs = [output_js_zip] library_info = [output_library_info] else: # Make sure js zip is always created since it is a named output _create_empty_zip(ctx, ctx.outputs.jszip) js_outputs = [] library_info = [] # This is a workaround to b/35847804 to make sure the zip ends up in the runfiles. js_runfiles = _collect_runfiles(ctx, js_outputs, ctx.attr.deps + ctx.attr.exports) return struct( providers = [ DefaultInfo( files = depset([ctx.outputs.jszip, ctx.outputs.jar]), runfiles = js_runfiles, ), J2clInfo(_private_ = struct(JavaInfo = java_provider, LibraryInfo = library_info)), ], **j2cl_js_provider(ctx, srcs = js_outputs, deps = ctx.attr.deps, exports = ctx.attr.exports) ) _empty_zip_contents = "\\x50\\x4b\\x05\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00" def _create_empty_zip(ctx, output_js_zip): ctx.actions.run_shell( outputs = [output_js_zip], command = "echo -ne '%s' > '%s'" % (_empty_zip_contents, output_js_zip.path), ) def _collect_runfiles(ctx, files, deps): transitive_runfiles = [d[DefaultInfo].default_runfiles.files for d in deps] return ctx.runfiles( files = files, transitive_files = depset(transitive = transitive_runfiles), ) def _java_compile(ctx, java_srcs): stripped_java_srcs = [_strip_gwt_incompatible(ctx, java_srcs)] if java_srcs else [] java_deps = [d[J2clInfo]._private_.JavaInfo for d in ctx.attr.deps if J2clInfo in d] java_exports = [d[J2clInfo]._private_.JavaInfo for d in ctx.attr.exports if J2clInfo in d] plugins = [p[JavaInfo] for p in ctx.attr.plugins] exported_plugins = [p[JavaInfo] for p in ctx.attr.exported_plugins] return java_common.compile( ctx, source_files = ctx.files._srcs_hack, source_jars = stripped_java_srcs, deps = java_deps, exports = java_exports, plugins = plugins, exported_plugins = exported_plugins, output = ctx.outputs.jar, java_toolchain = ctx.attr._java_toolchain, host_javabase = ctx.attr._host_javabase, javac_opts = java_common.default_javac_opts(ctx, java_toolchain_attr = "_java_toolchain"), ) def _strip_gwt_incompatible(ctx, java_srcs): output_file = ctx.actions.declare_file(ctx.label.name + "_stripped-src.jar") args = ctx.actions.args() args.use_param_file("@%s", use_always = True) args.set_param_file_format("multiline") args.add("-d", output_file) args.add_all(java_srcs) ctx.actions.run( progress_message = "Stripping @GwtIncompatible from %s" % ctx.label.name, inputs = java_srcs, outputs = [output_file], executable = ctx.executable._stripper, arguments = [args], env = dict(LANG = "en_US.UTF-8"), execution_requirements = {"supports-workers": "1"}, mnemonic = "J2cl", ) return output_file _J2CL_LIB_ATTRS = { # TODO(goktug): Try to limit this further. "srcs": attr.label_list(allow_files = [".java", ".js", ".srcjar", ".jar", ".zip"]), "deps": attr.label_list(providers = [JS_PROVIDER_NAME]), "exports": attr.label_list(providers = [JS_PROVIDER_NAME]), "plugins": attr.label_list(providers = [JavaInfo]), "exported_plugins": attr.label_list(providers = [JavaInfo]), "javacopts": attr.string_list(), "licenses": attr.license(), "_java_toolchain": attr.label( default = Label("@bazel_tools//tools/jdk:current_java_toolchain"), ), "_host_javabase": attr.label( default = Label("@bazel_tools//tools/jdk:current_host_java_runtime"), cfg = "host", ), "_stripper": attr.label( default = Label("//build_defs/internal_do_not_use:GwtIncompatibleStripper", relative_to_caller_repository = False), cfg = "host", executable = True, ), # TODO(goktug): remove workaround after b/71772385 is fixed "_srcs_hack": attr.label(default = Label("//build_defs/internal_do_not_use:dummy_src")), } _J2CL_LIB_ATTRS.update(J2CL_TRANSPILE_ATTRS) _J2CL_LIB_ATTRS.update(J2CL_JS_ATTRS) j2cl_library = rule( implementation = _impl_j2cl_library, attrs = _J2CL_LIB_ATTRS, fragments = ["java", "js"], outputs = { "jar": "lib%{name}.jar", "srcjar": "lib%{name}-src.jar", "jszip": "%{name}.js.zip", }, ) def _impl_java_import(ctx): return struct( providers = [J2clInfo(_private_ = struct(JavaInfo = ctx.attr.jar[JavaInfo], LibraryInfo = []))], **j2cl_js_provider(ctx) ) # helper rule to convert a Java target to a J2CL target. j2cl_java_import = rule( implementation = _impl_java_import, attrs = dict(J2CL_JS_ATTRS, **{ "jar": attr.label(providers = [JavaInfo]), "licenses": attr.license(), }), fragments = ["java", "js"], ) ```<|endoftext|>#### File: safe_agents/agents/a2c_control.py ```python import numpy as np from safe_agents.safety.heuristic import controller from safe_agents.agents.a2c import A2CAgent class A2CControlAgent(A2CAgent): def __init__(self, env): super(A2CControlAgent, self).__init__(env) def get_action(self, state): return super().get_action(state) def train(self, episodes=300, render=False): scores, safety = [], [] for e in range(episodes): done, override = False, False score = 0 status = [] state = self.env.reset() while not done: if render: self.env.render(mode="human") if override: action = controller(self.env, state) else: action = self.get_action(state) next_state, reward, done, info = self.env.step(action) override = False if info["status"] else True # safe = 1, unsafe = 0 status.append(info["status"]) self.update_network(state, action, reward, next_state, done) score += reward state = next_state if done: scores.append(score) safety.append(status) safe = status.count(1) unsafe = status.count(0) risk_rate = 0 if unsafe == 0 else unsafe / (safe + unsafe) print( f"\tepisode: {e} | " f"score: {score} | " f"risk_rate: {risk_rate} " ) return scores, safety if __name__ == "__main__": import gym env = gym.make("LunarSafe-v0") agent = A2CControlAgent(env) scores, safety = agent.train(episodes=10, render=False) print("======================") print(f"total_reward: {sum(scores)}") print( f"safe_s {sum(x.count(1) for x in safety)} | unsafe_s {sum(x.count(0) for x in safety)}" ) ``` #### File: safe_agents/agents/a2c_safe.py ```python import numpy as np from safe_agents.agents.a2c import A2CAgent class A2CSafeAgent(A2CAgent): def __init__(self, env): super(A2CSafeAgent, self).__init__(env) def get_action(self, state): return super().get_action(state) def train(self, episodes=300, render=False): scores, safety = [], [] for e in range(episodes): done = False score = 0 status = [] state = self.env.reset() while not done: if render: self.env.render(mode="human") action = self.get_action(state) next_state, reward, done, info = self.env.step(action) reward = -10 if info["status"] else 0 status.append(info["status"]) self.update_network(state, action, reward, next_state, done) score += reward state = next_state if done: scores.append(score) safety.append(status) safe = status.count(1) unsafe = status.count(0) risk_rate = 0 if unsafe == 0 else unsafe / (safe + unsafe) print( f"\tepisode: {e} | " f"score: {score} | " f"risk_rate: {risk_rate} " ) return scores, safety if __name__ == "__main__": import gym env = gym.make("LunarSafe-v0") agent = A2CSafeAgent(env) scores, safety = agent.train(episodes=10, render=True) print("======================") print(f"total_reward: {sum(scores)}") print( f"safe_s {sum(x.count(1) for x in safety)} | unsafe_s {sum(x.count(0) for x in safety)}" ) ``` #### File: thesis-poc/safe_agents/utils.py ```python import numpy as np import matplotlib import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import itertools from pathlib import Path def reject_outliers(data, m=2): mean = np.mean(data) std = np.std(data) distance = abs(data - mean) not_outlier = distance < m * std return data[not_outlier] def plot_visuals(agent, scores, safety, loc="./results/"): name = agent.__class__.__name__ + "#" + str(len(scores)) Path(loc).mkdir(parents=True, exist_ok=True) sns.set_theme(style="darkgrid") fig, axs = plt.subplots(ncols=2, figsize=(15, 5)) scores = reject_outliers(np.array(scores)) scoredf = pd.DataFrame( [(i, v) for i, v in enumerate(scores)], columns=["episode", "score"] ) sns.regplot( x="episode", y="score", data=scoredf, robust=True, ci=None, scatter_kws={"s": 10}, ax=axs[0], ) sns.boxplot(scores, showfliers=False, ax=axs[1]) fig.savefig(loc + name + "-Scores.png", dpi=400) fig, ax = plt.subplots(ncols=1) risk_rates = [] for j in safety: safe = j.count(1) unsafe = j.count(0) r = 0 if unsafe == 0 else (unsafe / (safe + unsafe)) risk_rates.append(r) ax.plot(risk_rates) plt.savefig(loc + name + "-Safety.png", dpi=400) def plot_comparisson(data, episodes, loc="./results/"): df = pd.concat([pd.DataFrame(d) for d in data]) df["episode"] = [i for _ in range(len(data)) for i in range(episodes)] r = [] for i, row in df.iterrows(): u = row["unsafe"] s = row["safe"] r.append(0 if u<1 else u/(u+s)) df["risk_rate"] = r #f, axs = plt.subplots(ncols=2, figsize=(15,5)) sns.lmplot( x="episode", y="scores", data=df, hue="agent", scatter_kws={"s": 10}, height=7 ) plt.savefig(loc + "".join([i["agent"] for i in data]) + "-Scores.png", dpi=400) sns.lmplot( x="episode", y="risk_rate", data=df, hue="agent", scatter_kws={"s": 10}, height=7 ) plt.savefig(loc + "".join([i["agent"] for i in data]) + "-Safety.png", dpi=400) ```
[{"idx": "dmorozov/j2cl", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-8433.jsonl"}, {"idx": "dmelichar/thesis-poc", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-8433.jsonl"}]
### Here is some exercises for division, addition, subtraction, multiplication math guide: 267 + 1254 = 1521 ### 389 - 675 = -286 ### 2145 - 250 = 1895 ### 1202 - 502 = 700 ### 535 - 1110 = -575 ### 1182 / -538 = -2.2 ### -21 / -716 = 0.03 ### 984 + 1997 = 2981 ### 24 + 885 = 909 ### 97 / 907 = 0.11 ### 2155 * 516 = 1111980 ### -602 / -591 = 1.02 ### 752 - 709 = 43 ### 206 - 2096 = -1890 ### 1399 + 2005 = 3404 ### 852 * 88 = 74976 ### 999 - 518 = 481 ### 584 - 454 = 130 ### 1118 + 1448 = 2566 ### 1792 * 1427 = 2557184 ### 1077 / -307 = -3.51 ### 1126 / 56 = 20.11 ### 414 - 1839 = -1425 ### 1808 + 864 = 2672 ### 723 + 329 = 1052 ### -40 * 1988 = -79520 ### 2275 * 330 = 750750 ### 1042 - 900 = 142 ### -196 / 289 = -0.68 ### 284 - 12 = 272 ### 789 / -320 = -2.47 ### -18 + 1573 = 1555 ### 2208 + 2148 = 4356 ### -969 / 269 = -3.6 ### 503 - 799 = -296 ### 473 / -840 = -0.56 ### -491 / -878 = 0.56 ### -628 / 371 = -1.69 ### -50 + 551 = 501 ### 2207 - 2317 = -110 ### -852 / -166 = 5.13 ### 1250 + 1199 = 2449 ### 704 + 1981 = 2685 ### -334 / 651 = -0.51 ### 2053 * 2197 = 4510441 ### 221 - 953 = -732 ### 881 + 591 =\n#### Ready to do some math? We're starting with 881 and 591 and adding them up. Step 1: We'll start by adding the digits 1 & 1 in column 1 and get 2. Step 2: We'll start by adding the digits 8 & 9 in column 2 and get 17. We'll write down the last digit 7 and carry the 1 to the next column. Step 3: We'll start by adding the digits 8 & 5 in column 3 and get 14. We'll write down the last digit 4 and carry the 1 to the next column. So, 881 + 591 = 1472. <|endoftext|>### Please examine the set of subtraction, multiplication, division, addition math exercises: 896 * 1344 = 1204224 ### 2287 - 1559 = 728 ### Start with the equation: 100*x + 83 = 92*x + -95 Step 1: Subtract 92*x from both sides: (8)*x + 83 = -95 Step 2: Subtract 83 from both sides: (8)*x = -178 Step 3: Divide both sides by 8: x = -22.25 Final Equation: x = -22.25 ### 2017 + 496 = 2513 ### -110 / -363 = 0.3 ### 792 - 1589 = -797 ### -53 * 758 = -40174 ### 603 - 1339 = -736 ### -608 / 679 = -0.9 ### 1241 - 591 = 650 ### 1770 - 1169 = 601 ### 318 - 313 = 5 ### Charlie has two equations that they need to solve: 600x + 115y = 58 353x + 17y = 4633 Can you find the values of x and y? Step 1: The goal is to make the coefficients of y in both equations the same. This is done by multiplying the entire first equation by 17 and the entire second equation by 115, leading to: 10200x + 1955y = 986 and 40595x + 1955y = 532795 Step 2: Now, subtract the second equation from the first. This involves subtracting each corresponding term on both sides. After performing the subtraction, we get: (10200-40595)x + (1955-1955)y = (986-532795) Which simplifies to: x = 17.496594834676756 Step 3: We now know the value of x, so we substitute x = 17.496594834676756 into the first equation. The first equation becomes: 600*17.496594834676756 + 115y = 58 Step 4: Simplify the equation by performing the multiplication 600*17.496594834676756, which results in: 10497.956900806053 + 115y = 58 Then, isolate y by subtracting 10497.956900806053 from both sides. This gives us: y = -90.78223392005265 Step 5: Thus, the solution to the system of equations is x = 17.496594834676756 and y = -90.78223392005265. ### 1393 * 238 = 331534 ### 70 * 1716 = 120120 ### 2059 + 2055 = 4114 ### -567 / 549 = -1.03 ### 2091 - 555 = 1536<|endoftext|>### Study this set of subtraction, addition, multiplication, division math guide: 100 - 98 =\n#### We can solve this together! We're beginning with 100 and removing 98 from it. Step 1: We'll start by subtracting the digit 8 and the borrow 0 from 0 in column 1 and get -8. We add -8 to 10 and get 2 as the first digit of the result. Step 2: We'll start by subtracting the digit 9 and the borrow 1 from 0 in column 2 and get -10. We add -10 to 10 and get 0 as the next digit of the result. Step 3: We'll start by subtracting the digit 0 and the borrow 1 from 1 in column 3 and get 0. 0 is the next digit of our result. So, 100 - 98 = 2. ### 2095 + 1798 = 3893 ### 290 - 1922 = -1632 ### 575 + 955 = 1530 ### 361 * 461 = 166421 ### 1717 + 919 = 2636 ### 1408 + 910 = 2318 ### -566 / 1151 = -0.49 ### 2161 * 81 = 175041 ### 972 + 51 = 1023 ### 1090 * 1342 = 1462780 ### 2144 * 363 = 778272 ### 1774 + 1428 = 3202 ### 885 * 2152 = 1904520 ### -114 / 734 = -0.16 ### 167 / 1351 = 0.12 ### 1822 * 516 = 940152 ### Olivia paid a total of $729.0.=\n#### Olivia went to the department store to buy a pair of shoes and 2 shirts. A shirt costs $44 while a pair of shoes is $398. If she decides to buy a bag which costs half the total price of the 2 shirts and a pair of shoes, how much will she pay for all those items? Solution: Two shirts costs $88. The cost of a pair of shoes is $398. The total cost of two shirts and a pair of shoes is $486. The cost of a bag is $243.0. So, Olivia paid a total of $729.0. ### 931 / -229 = -4.07 ### 409 - 659 = -250 ### 476 / 243 = 1.96 ### 1255 / 800 = 1.57 ### 1185 / 924 = 1.28 ### 1159 / -566 = -2.05 ### 566 / 551 = 1.03<|endoftext|>### Here are set of addition, subtraction, multiplication, division math insights: 541 - -44 = 585 ### 1045 - 1394 = -349 ### 1296 + 425 = 1721 ### 463 + 1432 = 1895 ### 870 - 1878 = -1008 ### 1711 * 574 = 982114 ### 1056 * 1020 = 1077120 ### 1845 + 1609 = 3454 ### 2196 + 428 = 2624 ### 1413 - 1332 = 81 ### 2191 - 1851 = 340 ### 8 + 1386 = 1394 ### 782 * 1634 = 1277788 ### 1658 - 663 = 995 ### -18 - 1266 = -1284 ### 1844 - 624 = 1220 ### 817 - -44 = 861 ### 238 + 664 = 902 ### 97 * 2197 = 213109 ### -441 / 61 = -7.23 ### 1053 / -237 = -4.44 ### 2242 - 1992 = 250 ### 1952 * 768 = 1499136 ### 2220 + 862 = 3082 ### David bought 518 notebooks and 1460.3 erasers for $4219.4. Charlie bought 113 notebooks and 905.4 erasers for $3765.5. We're trying to figure out how much each notebook and each eraser costs. Let's solve the problem step by step: Step 1: Set up the equations: 518n + 1460.3e = 4219.4 113n + 905.4e = 3765.5 Step 2: Solve the equations simultaneously to find the values of 'n' and 'e'. Multiply the first equation by 113 and the second equation by 518: 58534n + 165013.9e = 476792.19999999995 58534n + 468997.2e = 1950529.0 Subtract the second equation from the first equation: 0n + -303983.30000000005e = -1473736.8 Simplify the equation: 0n + -303983.30000000005e = -1473736.8 Solve for 'e': e = 4.848084746760759 Substitute 'e' into the first equation to find 'n': 518n + 1460.3 * 4.848084746760759 = 4219.4 Simplify the equation: 518n + 7079.658155694736 = 4219.4 Solve for 'n': n = -2860.258155694736 The cost of each notebook and each eraser: Cost of each notebook = -2860.258155694736 Cost of each eraser = 4.848084746760759 <|endoftext|>### Think deeply about this set of multiplication, subtraction, division, addition math exercises: -28 - 548 = -576 ### 1339 / -636 = -2.11 ### 697 + 492 = 1189 ### -268 / 842 = -0.32 ### 1685 + 1553 = 3238 ### 1096 / -952 = -1.15 ### In Evelyn's family, there are 1 adults and 7 children. In a cookie jar, there are a total of 88 cookies. If the adults eat 1/3 of the cookies and then gives the rest to the children to divide equally, how many cookies does each child get? Solution: The adults ate 1/3*88 = 29.33 cookies. The remaining number of cookies is 88-29.33 = 58.67 cookies. If the children divided the cookies equally, each child got 58.67/7 = 8 cookies. ### 1035 + 609 = 1644 ### 717 / -633 = -1.13 ### 310 - 612 = -302 ### 2231 + 833 = 3064 ### -370 / 786 = -0.47 ### 1224 + 554 = 1778 ### 5 + 2100 = 2105 ### 688 * 2069 = 1423472 ### 111 * 1662 = 184482 ### 1065 - 1447 = -382 ### 1368 + 351 = 1719 ### 1521 - 2311 = -790 ### 1323 + 1059 = 2382 ### 2168 - 1154 = 1014 ### 841 / -511 = -1.65 ### 1058 - 671 = 387 ### 1553 - 801 = 752 ### 1404 + 890 = 2294 ### -296 / 805 = -0.37 ### 579 / 153 = 3.78 ### 1932 + 99 = 2031 ### 1728 + 1133 = 2861 ### -42 + 160 = 118 ### 1740 - -10 = 1750 ### 1063 + 1499 = 2562 ### 465 + 2095 = 2560 ### 1276 * 1031 = 1315556 ### 287 + 1688 = 1975 ### 1945 * 518 = 1007510 ### -672 / -661 = 1.02 ### -30 / -813 = 0.04 ### 2160 * 1189 = 2568240 ### 2024 + 2109 = 4133<|endoftext|>### Here's set of multiplication, addition, subtraction, division math insights: 1531 - 1540 = -9 ### -28 / -976 = 0.03 ### 1662 - 153 = 1509 ### 456 / 106 = 4.3 ### -401 / -649 = 0.62 ### 2185 * 1529 = 3340865 ### 102 - 1980 = -1878 ### 1416 - 2296 = -880 ### -147 / 863 = -0.17 ### 220 - 1187 = -967 ### 1119 / -394 = -2.84 ### -959 / 544 = -1.76 ### -44 - 289 = -333 ### -35 * 1258 = -44030 ### 19 / 659 = 0.03 ### 1963 * 2279 = 4473677 ### 1012 + 1877 = 2889 ### 102 * 1750 = 178500 ### 1955 - 838 = 1117 ### 425 + 2117 = 2542 ### 242 / -354 = -0.68 ### 1077 - 451 = 626 ### -46 - 2299 = -2345 ### -879 / 1064 = -0.83 ### 1167 * 1442 = 1682814 ### 2182 * 2056 = 4486192 ### 314 / 190 = 1.65 ### 1196 - 1403 = -207 ### 2097 + 555 = 2652 ### 1284 * 1441 = 1850244 ### 201 / 1200 = 0.17 ### 854 * 742 = 633668 ### 44 + 1931 = 1975 ### Jackson paid a total of $567.0.=\n#### Jackson went to the department store to buy a pair of shoes and 2 shirts. A shirt costs $51 while a pair of shoes is $276. If she decides to buy a bag which costs half the total price of the 2 shirts and a pair of shoes, how much will she pay for all those items? Solution: Two shirts costs $102. The cost of a pair of shoes is $276. The total cost of two shirts and a pair of shoes is $378. The cost of a bag is $189.0. So, Jackson paid a total of $567.0. ### 544 * 1261 = 685984 ### 2105 * 2243 = 4721515 ### 1201 - 559 = 642 ### 1449 * 1759 = 2548791
[{"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}]
numbers: div remainder composed ------------------------------- Q: Let y(f) = -1 + 4 + 4*f**2 - 2*f**2 - 15*f + 1. Let n = -10 + 38. Calculate the remainder when y(10) is divided by n. A: 26 Q: Suppose 4*w - 3*j - 84 = 0, 2*w + 1 - 43 = 3*j. Suppose -q + 6*q - 205 = 0. Calculate the remainder when q is divided by w. A: 20 Q: Calculate the remainder when 152 is divided by 7 + (-3396)/(-48) + 2/8. A: 74 Q: Let d(c) = -c**2 - 3*c + 2. Let n be d(0). Let l(v) = 4*v**2 + v + 13*v**2 - 1 + 12*v**2 - 7*v**n. What is the remainder when 43 is divided by l(1)? A: 21 Q: Suppose -3*x + 748 - 238 = 0. Suppose 3*k = -2*g + g + x, 3*k - 2*g = 173. Let l = 91 - k. What is the remainder when l is divided by 12? A: 10 Q: Let a = 9182 + -6785. What is the remainder when a is divided by 13? A: 5 Q: Let u = -22 - -47. Calculate the remainder when 71 is divided by u. A: 21 Q: Suppose 0 = -3*s - 2*f - 0*f - 2, 2*f = -2*s - 2. Suppose s = 4*c + 2*c - 108. Calculate the remainder when c is divided by 7. A: 4 Q: Let v(h) = 2*h**3 - 3*h**2 - 2*h + 4. What is the remainder when v(3) is divided by 14? A: 11 Q: Suppose -30*u = 16*u - 203 + 65. Calculate the remainder when 4554 is divided by u. A: 0 Q: Suppose -3*g + 78 = -5*c - 75, 12*c = -3*g + 204. What is the remainder when 671 is divided by g? A: 55 Q: Let w(z) = z**3 - 12*z**2 + 19*z + 13. Let m be w(10). Suppose 159 = m*x + 3*g, 0*g + 253 = 5*x + 2*g. What is the remainder when 146 is divided by x? A: 48 Q: Let h be 6/(-21) - (-66)/(-14). Let a = 9 + h. Calculate the remainder when 13 is divided by a. A: 1 Q: Suppose 0 = -3*v, 0 = -w - 0*w - v + 75. Suppose k + w = 4*z - 116, 0 = k - 1. What is the remainder when z is divided by 17? A: 14 Q: Let c = -7 + 13. Suppose -28*w + 15 = -69. Calculate the remainder when c is divided by w. A: 0 Q: Let w = 19 + -8. Suppose -30 = -13*o + 10*o - 2*t, 5*t = 2*o - 39. Calculate the remainder when (-232)/(-12) - o/(-18) is divided by w. A: 9 Q: Let s = -605 - -1274. Suppose -13*a + 410 = -s. Suppose 0 = 3*j - 54 + 12. What is the remainder when a is divided by j? A: 13 Q: Let w be (-4)/((-1)/8*2). Suppose 5*x = 34 + w. Suppose v = 35 - 7. What is the remainder when v is divided by x? A: 8 Q: Suppose -3 = -4*a - 2*i + 11, 4*a - 20 = 4*i. Suppose 0 = 3*r + 15, -a*s - 4*r + 12 = -56. What is the remainder when s is divided by 12? A: 10 Q: Let p be ((-48)/(-32))/((-6)/452). Let r = p - -138. Calculate the remainder when 45 is divided by r. A: 20 Q: Let k(b) = -b**3 + 16*b**2 - 41*b - 12. Calculate the remainder when k(12) is divided by 15. A: 12 Q: Suppose 0 = -2*n - 3*j - 5, 5*n - j - 30 = 0. Suppose 9*g = 36 + 18. What is the remainder when g is divided by n? A: 1 Q: Let b(x) = -20*x - 135. What is the remainder when b(-12) is divided by 19? A: 10 Q: Suppose -16 = -2*i - 2*i. Suppose 0*f = 2*w - f - 115, -4*f = i. What is the remainder when w is divided by 6/21 + (-206)/(-14)? A: 12 Q: Let d(n) = -5*n**3 - 247*n**2 - 101*n + 102. Calculate the remainder when d(-49) is divided by 118. A: 13 Q: Suppose -7 = -r + 1. What is the remainder when 12 is divided by r? A: 4 Q: Let u = -223 + 373. Let y = -559 - -611. Calculate the remainder when u is divided by y. A: 46 Q: Let a(z) = -5*z**3 - 2*z - 1. What is the remainder when 128 is divided by a(-2)? A: 42 Q: Suppose 18 = 2*k - 22. Suppose 0*s - 292 = -4*h - 4*s, s = -5. What is the remainder when h is divided by k? A: 18 Q: Let q = 5 - 0. Suppose q*l = -10 + 30. Suppose l*a - 46 = -2. What is the remainder when 31 is divided by a? A: 9 Q: Suppose 2*k - 4 + 0 = 0. Let m be 2/(k/47)*-2. Let q = -44 - m. What is the remainder when q is divided by 17? A: 16 Q: Suppose 3*o = o. Suppose -3*p + 314 = 4*c + 75, 4*p + 12 = o. Calculate the remainder when c is divided by 21. A: 20 Q: Let o(h) = 18*h**3 - 3*h**2. Let n be o(2). Suppose -3*p = p - n. What is the remainder when p is divided by 18? A: 15 Q: What is the remainder when (-363)/55 + 7 + (2469/(-5))/(-3) is divided by 5? A: 0 Q: Let r = -23847 + 24141. What is the remainder when r is divided by 99? A: 96 Q: Let g(b) = 3*b**2 + 21*b + 20. Calculate the remainder when 96 is divided by g(-6). A: 0 Q: Suppose 0 = -4*b - b - 30. Let o(p) = p**2 + 2*p + 4. Let f(l) = 2*l**2 + 3*l + 1. What is the remainder when o(b) is divided by f(-3)? A: 8 Q: Let h be -1*(-1 - -3 - 4). Let w be 27/(-6) + 2/4. Let n = h - w. Calculate the remainder when 16 is divided by n. A: 4 Q: Let c(l) = -31*l**3 - 4*l**2 - 179*l - 179. Let f = 3 - -1. What is the remainder when ((-102)/8)/((-1)/f) is divided by c(-1)? A: 24 Q: Let z = -138 + 229. Let t = -48 + z. Suppose k - 12 = -1. What is the remainder when t is divided by k? A: 10 Q: Let s = 113 - 30. Suppose 90*t = s*t + 539. Calculate the remainder when t is divided by 26. A: 25 Q: Let f(m) be the first derivative of -m**4/2 - 25*m**3/3 - 15*m**2/2 + 6*m - 4. What is the remainder when f(-12) is divided by 5? A: 2 Q: Let x be (2/3)/((-5)/(-15)). Let k be (x + (2 - 90))/(-2). Suppose 5*r - 40 = -3*s, 3*r + 3*s = 5*s + k. Calculate the remainder when r is divided by 6. A: 5 Q: Suppose 0 = r - s - 48, 2*s = -r + 4*s + 43. Calculate the remainder when r is divided by 27. A: 26 Q: Let s = 11922 + -11691. What is the remainder when 1376 is divided by s? A: 221 Q: Let v(t) = -3*t**3 + t**2 + 2*t. Let o be v(-1). Suppose -u + o*u - 12 = 0. What is the remainder when u is divided by 3? A: 0 Q: Let h = 146 - 73. Let m = -2804 - -2824. What is the remainder when h is divided by m? A: 13 Q: Suppose -10*z + 4*z - 18 = 0. Let j be 2 - (-3 + -103) - z. Suppose 15*x - 18*x = -j. What is the remainder when 68 is divided by x? A: 31 Q: Suppose 4*d + 2*a = 912, -2*d - 41 = -5*a - 485. What is the remainder when d is divided by 19? A: 18 Q: Let u(s) = 3*s**2 + 2*s - 1. Calculate the remainder when (44 + (-7106)/170)/(-1 + 12/10) is divided by u(-2). A: 4 Q: Let j be -1 + (-19)/(-21) - 317/(-21). Suppose -1374 = -j*v + 9*v. Calculate the remainder when v is divided by 29. A: 26 Q: Let v(g) = -g**2 + 6*g + 16. Let y(z) = -z**2 + 6*z + 13. Let d(j) = -5*v(j) + 6*y(j). Calculate the remainder when 106 is divided by d(5). A: 1 Q: Let y(n) = -n**3 - n**2 + 6*n - 13. What is the remainder when y(-6) is divided by 22? A: 21 Q: Let j(d) = -5*d**3 + 7*d**3 - d**3 - 9 + 9*d**2 + 0*d + 12*d. Let r be j(-9). What is the remainder when (-8)/20 + r/(-5) is divided by 13? A: 10 Q: Let g = -4603 + 4713. Calculate the remainder when 167 is divided by g. A: 57 Q: Suppose -5*p = 2*f - 0*f - 360, -3*p + 202 = 4*f. Calculate the remainder when p is divided by 136/4 + ((-12)/20 - (-96)/(-15)). A: 20 Q: Suppose 323*x = 319*x + 4*k + 292, 3*x + 4*k = 205. Let v(m) = m**3 + 6*m**2 + 7. Let b be v(-5). Let w = 50 - b. What is the remainder when x is divided by w? A: 17 Q: Let w = -51 + 79. What is the remainder when 52 is divided by w? A: 24 Q: Let s(n) = 88*n**2 - 105*n - 314. What is the remainder when s(-3) is divided by 254? A: 31 Q: Suppose -442 = -5*f + 3*v, -3*v - 90 = -3*f + 180. Let l(u) = u**3 - 28*u - 132. Calculate the remainder when f is divided by l(7). A: 11 Q: Suppose 0 = 4366*f - 4381*f + 1485. Calculate the remainder when 296 is divided by f. A: 98 Q: Let r = 12272 + -11610. What is the remainder when r is divided by 32? A: 22 Q: Let w be (-1)/(-1) + 1 + 0/(-15). Suppose 2*i - t = -2*t + 15, -5*i + t = -34. Calculate the remainder when (2 - (-4 + w))*(-30)/(-12) is divided by i. A: 3 Q: Let r = -14 - -34. What is the remainder when (93/2)/(10/r) is divided by 48? A: 45 Q: Suppose 4*g = 6*g - 4. Suppose 3*k = 2*k - g, -3*a = 5*k - 14. Let n(u) = u**2 + 4. Calculate the remainder when n(3) is divided by a. A: 5 Q: Suppose 0 = 4*u - 2*g + 7*g - 59, 0 = g + 1. Suppose 188 = 4*d - 5*l + 3*l, 2*l = -3*d + 127. Calculate the remainder when d is divided by u. A: 13 Q: Suppose g = -2*d + 53, 3*g + 5*d = -37 + 195. Calculate the remainder when 67 is divided by g. A: 16 Q: Suppose -3*x + 4*k + 814 = 0, -1085 = -4*x - 0*k + 5*k. What is the remainder when x is divided by 16? A: 14 Q: Suppose -3*d = w - 380, -4*d + 5*w = -523 + 10. Suppose -121 - d = -4*b - 4*n, b - 3*n = 78. Calculate the remainder when b is divided by 23. A: 20 Q: Calculate the remainder when 282 is divided by 1048/12 - 16/12. A: 24 Q: Suppose -2 = 5*w - 12. Suppose -w*t - t = -30. Calculate the remainder when 28 is divided by t. A: 8 Q: Let g = 26 + 37. Let f = -2 + 6. Suppose -3*z + 19 = f*v - g, 5*v + 40 = z. What is the remainder when z is divided by 8? A: 6 Q: Let k = -229 + 234. Suppose 7*x - 6 = -2*u + 2*x, k*u + 3*x - 53 = 0. What is the remainder when 140 is divided by u? A: 10 Q: What is the remainder when 4658/51 + 4/6 is divided by 19? A: 16 Q: Let h = 79 + -86. Let v(n) = -n**2 - 11*n - 18. Let r = -11 - -39. Calculate the remainder when r is divided by v(h). A: 8 Q: Suppose -50 = -27*d + 17*d. What is the remainder when (-35)/(-2) + 3/(-6) is divided by d? A: 2 Q: Suppose -5*y - 5*k + 4*k = -464, 2*k - 192 = -2*y. Calculate the remainder when 277 is divided by y. A: 1 Q: Let d(p) = 15*p - 3. Let s be d(2). Suppose -5*y + s + 48 = 0. Let k(x) = x**3 - 2*x**2 + 9*x - 12. Calculate the remainder when y is divided by k(2). A: 3 Q: Suppose -7*w = -20 - 43. Calculate the remainder when 17 is divided by w. A: 8 Q: Suppose 0 = -3*f + 4*w - 739, 0*f + 5*w = 4*f + 984. Let s(x) = 7*x + 4. Calculate the remainder when (-1)/2*(-5 + f) is divided by s(3). A: 23 Q: Let s = 28 + -13. Suppose 3*g - s = 48. Let n(w) = -w**3 + 3*w**2 + 3*w - 3. Calculate the remainder when g is divided by n(3). A: 3 Q: Let v(z) = -6*z**2 + 2*z + 958. What is the remainder when v(0) is divided by 8? A: 6 Q: Let o(u) = u - 12. Let a be o(9). Let l = a + 6. Calculate the remainder when 11 is divided by l. A: 2 Q: Let f(a) = -3*a**3 - 3*a**2 - a + 3. What is the remainder when 116 is divided by f(-2)? A: 14 Q: Suppose 12 = 9*g - 60. Calculate the remainder when 13 is divided by g. A: 5 Q: Let x(j) = 2*j**2 - 3*j**2 - 16*j**3 - 4*j**2 + 3*j**2 - 2*j - 1. What is the remainder when 44 is divided by x(-1)? A: 14 Q: Suppose -2*h - 356 = -2*u, 5*h + 14 = u - 136. What is the remainder when 9802 is divided by u? A: 182 Q: Let b be (-228)/(-44) - (-6)/(-33). Suppose -4*s - v = -0*s - 394, 2*s = -b*v + 206. Let z = -62 + s. What is the remainder when 69 is divided by z? A: 33 Q: Let t = 12864 + -12852. What is the remainder when 40282 is divided by t? A: 10 Q: Let o(z) = -1. Let s(q) = -q + 9. Let p(t) = 24*o(t) + 3*s(t). Calculate the remainder when 17 is divided by p(-2). A: 8 Q: Let d = -46 - -67. What is the remainder when (501/9)/(6/18) is divided by d? A: 20 Q: Let r = 108 - 116. Calculate the remainder when 99 is divided by r/(-8 - 0) + 55. A: 43 Q: Suppose 5*q - 95 = -20. Suppose -i - 31 = -103. Calculate the remainder when i is divided by q. A: 12 Q: Let m(u) = -u**3 - 7*u**2 + 9*u + 8. Let q be 3/12 - (-66)/(-8). Let r be m(q). Let p = 19 + r. Calculate the remainder when p is divided by 7. A: 5 Q: Suppose -232 - 1348 = -10*s. Calculate the remainder when s is divided by 42. A: 32 Q: Let x(n) = -n**2 - 10*n + 10. Let u(s) = -s**3 - 4*s**2 + 7*s. Let o be u(-5). Let w = 5 + 1. What is the remainder when x(o) is divided by w? A: 4 Q: Let a(z) = z - 12. Let j be a(5). Let o = j + 29. Suppose -i + o = i. What is the remainder when i is divided by 4? A: 3 Q: Let a = -3 - 1. Calculate the remainder when 7 is divided by 0/a + 3 + 2. A: 2 Q: Let n(p) = 10*p - 3. What is the remainder when n(7) is divided by 23? A: 21 Q: Let k(t) = t**3 + 7*t**2 + 8. Calculate the remainder when 21 is divided by k(-7). A: 5 Q: Let h(f) = -8*f. Suppose -36*s - 426 = -39*s. What is the remainder when s is divided by h(-3)? A: 22 Q: Suppose 113328 - 334416 = -282*f. Calculate the remainder when f is divided by 197. A: 193 Q: Let f(r) = -2*r**2 - 4*r + 5. Let z(p) = 3*p**2 + 9*p - 10. Let n(g) = -7*f(g) - 4*z(g). Calculate the remainder when n(-8) is divided by 6. A: 5 Q: Calculate the remainder when 289 is divided by 6 - -1 - (33/(-3) + -229). A: 42 Q: Suppose -198*x + 143 = -187*x. Suppose -2 = -o - 0. Calculate the remainder when 3/o*-1*-42 is divided by x. A: 11 Q: Suppose j - 6*j - 720 = -5*u, -4*u + j = -567. Calculate the remainder when u is divided by 119. A: 22 Q: Suppose -4*d + 1 = -3*d. Calculate the remainder when 99 is divided by d/5 - (-504)/30. A: 14 Q: Suppose -3*k + 9*f = 11*f - 915, -5*f = 15. Calculate the remainder when k is divided by 26. A: 21 Q: Let b = 17 - 0. Let i be (-78)/(-13)*(-4)/6. Let o = i + b. Calculate the remainder when 23 is divided by o. A: 10 Q: Suppose -b - b + 12 = 0. Let n(m) = m + 2. Let c(z) = -4*z - 1. Calculate the remainder when n(b) is divided by c(-1). A: 2 Q: Let p(o) = o + 1. Let r(y) = 7*y + 49. Let v be r(-6). What is the remainder when 77 is divided by p(v)? A: 5 Q: Let j = -10 + 20. Suppose 0*c = 5*c - 15. Let d(z) = -z**2 + 3*z + 4. What is the remainder when j is divided by d(c)? A: 2 Q: Suppose -2*m + 58 = 5*q - 218, -5*m = -3*q - 721. Suppose 5*k - 183 + 3 = 0. Calculate the remainder when m is divided by k. A: 35 Q: Calculate the remainder when 1205 is divided by (-112776)/(-740) - (0 - (-6 + 3))/(-5). A: 134 Q: Let r(z) = z**3 + 11*z**2 - 30*z - 7. What is the remainder when 269 is divided by r(-13)? A: 44 Q: Let i(h) = -2*h - 9. Let m = -4 - 7. What is the remainder when i(m) is divided by 5? A: 3 Q: Suppose 4*q - 58 - 30 = 0. Calculate the remainder when q is divided by (-18)/(6/(-4)*1). A: 10 Q: Suppose -17*m + 704 = -979. What is the remainder when m is divided by 36? A: 27 Q: Let b(n) = 91*n + 9928. What is the remainder when 655 is divided by b(-109)? A: 7 Q: Let v(l) = 10*l - 4 - l - 6*l + 3*l. Calculate the remainder when 54 is divided by v(3). A: 12 Q: Let d = 6 - -23. What is the remainder when d is divided by 12/(-5 - (-69)/12)? A: 13 Q: Let j = -8 + 1. Let q(x) = x**3 + 6*x**2 - 7*x + 3. Let i be q(j). Suppose -i*a + 5 = 5*b - 31, 0 = 2*b + 6. Calculate the remainder when a is divided by 6. A: 5 Q: Let n(f) = f**3 - f + 33. Calculate the remainder when n(0) is divided by -3 - ((-312)/15 + (-4)/(-5)). A: 16 Q: Suppose 7*p = g + 6*p - 395, 0 = 2*p. What is the remainder when g is divided by 80? A: 75 Q: Suppose -6*k - 2*k + 320 = 0. Suppose 7*q - 2*q - 4*z = 147, 23 = q - 4*z. What is the remainder when q is divided by 36/(-30)*k/(-6)? A: 7 Q: Let o(u) = u**3 - 37*u**2 - 21*u - 146. Calculate the remainder when o(38) is divided by 101. A: 96 Q: Let j(s) = -15*s**3 - 4*s**2 - s - 22. What is the remainder when j(-4) is divided by 22? A: 20 Q: Let a(v) = -v**2 - 30*v - 204. Calculate the remainder when 1474 is divided by a(-14). A: 14 Q: Suppose -3*i + 97 = -5*f, i = -3*f + 11 + 12. Suppose 5*y = i + 46. Calculate the remainder when 59 is divided by y. A: 14 Q: Suppose 0 = 2*w - 2 - 8. Suppose 6*i = 3*i. Suppose 5*l + 3*r = 228, -2*r - 3 + w = i. Calculate the remainder when l is divided by 23. A: 22 Q: Suppose -5*r = -4*h - 44, -3*h = -r + 3 + 8. Suppose -r = -o - 3*o. Calculate the remainder when 2 is divided by o. A: 0 Q: Suppose 15 = 4*s - 121. What is the remainder when 2*1*(-202)/(-4) is divided by s? A: 33 Q: Let f(u) = -2*u**2 + 31*u - 8. Calculate the remainder when 2548 is divided by f(10). A: 100 Q: Let l(x) = -x**3 + x**2 + 2*x - 3. Let g be l(2). What is the remainder when g + (7 - 9/(-3)) is divided by 4? A: 3 Q: Suppose -5*g = 5*v - 95, 4*g - 60 = -g + 2*v. Let c = -94 + 121. What is the remainder when c is divided by g? A: 13 Q: Let p = -199 + 568. Calculate the remainder when p/(-18)*1*-4 is divided by 29. A: 24 Q: Let i = -45 + 77. What is the remainder when (-2)/3*3 + 18 is divided by 5*2 - i/8? A: 4 Q: Suppose 0 = -1314*o - 1330*o + 2656*o - 708. What is the remainder when 4914 is divided by o? A: 17 Q: Suppose -409 + 640 = 3*u. What is the remainder when u is divided by 3? A: 2 Q: Let h be -92*(-4)/(0 + 8). What is the remainder when 122 is divided by (-5)/(-5) + h + -5 + 1? A: 36 Q: Suppose 28*r = 201*r - 18857. Calculate the remainder when 25394 is divided by r. A: 106 Q: Suppose 10*b - 12*b + 194 = -4*a, 0 = 9*b - 2*a - 873. What is the remainder when 1061 is divided by b? A: 91 Q: Let c be (-1 + 1)*(-3)/(-6). What is the remainder when 5/3*15 + 0 + c is divided by 7? A: 4 Q: Let l(p) = -2013*p - 15692. What is the remainder when l(-8) is divided by 102? A: 4 Q: Let z(j) = 14*j - 1572 + 10*j + 1535 - j**2. What is the remainder when z(13) is divided by 36? A: 34 Q: Let c = -328 + 337. Calculate the remainder when 62 is divided by c. A: 8 Q: Let m = 1635 - 1609. Calculate the remainder when m is divided by 2/6 - (-26)/3. A: 8 Q: Let q = 461 - 419. What is the remainder when 207 is divided by q? A: 39 Q: Let i(u) = -u**2 - 7*u - 12. Let j be i(-4). Suppose 5*l + 4*l - 540 = j. Let d = 62 - l. Calculate the remainder when 7 is divided by d. A: 1 Q: Suppose 2 + 1 = w. Suppose 0 = w*d - 8*d + 40. What is the remainder when 22 is divided by d? A: 6 Q: Let x = 10 + 15. Suppose m - 4*u = 10, 2*m + x = -5*u + 84. Calculate the remainder when 42 is divided by m. A: 20 Q: Let x(b) = -b + b - 3 + 4*b - 2*b. Let u be x(-1). What is the remainder when 36 is divided by (-475)/5*1/u? A: 17 Q: Suppose 3935*f = 3934*f + 268. What is the remainder when f is divided by 254? A: 14 Q: Suppose -4*c + 367 = i, 6*c - 553 = -4*i + 3*i. Calculate the remainder when c is divided by 22. A: 5 Q: Suppose -5*p = -j - 28, 5 = p - j + 1. Let x be (-1 - -2)*(0 - -13). Let w = -3 + x. What is the remainder when w is divided by p? A: 4 Q: Let d be 1 + 1*(-14)/2. Suppose x - 5*g = 3*x + 45, -x + 4*g - 3 = 0. What is the remainder when (-99)/x - d/15 is divided by 3? A: 1 Q: Let k = -8 - -8. Suppose 4*c + k*c + 3*w = 79, 21 = c + 2*w. Calculate the remainder when 55 is divided by c. A: 17 Q: What is the remainder when 380 is divided by (-4)/12*(-86 + -58)? A: 44 Q: Let f = -6817 - -6947. Calculate the remainder when 393 is divided by f. A: 3 Q: Suppose -28*q + 25*q + 36 = 0. What is the remainder when 137 is divided by 24/32 - (-267)/q? A: 22 Q: Let k(b) be the first derivative of -b**4/4 - 4*b**3/3 + b**2 - 6*b + 2. Calculate the remainder when k(-6) is divided by 14. A: 12 Q: Let x(n) = -88*n + 831. What is the remainder when x(-5) is divided by 260? A: 231 Q: Let h(g) = 6*g - 2. Let i(u) = 3*u**2 - 2*u - 1. Let l be i(-1). Suppose 0 = -y, 2*y + 31 + 9 = l*v. What is the remainder when h(5) is divided by v? A: 8 Q: Let m(t) = -4*t - 2. Let l be m(-2). Suppose -l*y = -y - 55. Calculate the remainder when 19 is divided by y. A: 8 Q: Let n = 17 - 12. Let d(k) = 2*k + 12. What is the remainder when d(n) is divided by 4? A: 2 Q: Let v = 38 + -8. Suppose -o - v = -3*o. Calculate the remainder when o is divided by (-23)/(-3) + 2/6. A: 7<|endoftext|>algebra: linear 1d composed --------------------------- Task: Let p(a) = -a**3 + 12*a**2 - 19*a - 21. Let t be p(7). Suppose 8*r - 238 = 3*r + w, 0 = -2*r - w + t. Solve -6*f + r = 17 for f. Fix: 5 Task: Suppose -3 = 4*i + 1. Let n = 4 - i. Let t be ((-16)/n)/(2/(-10)). Solve 5*w = w + t for w. Fix: 4 Task: Let v be 3818/(-14) + (-74)/259. Let s = v + 283. Solve 0*l - 5*l = -s for l. Fix: 2 Task: Suppose 0 = -3*c - 5*d + 30, 3*c - 8*c + 5*d = -10. Suppose 4*u + v = -3, 0 = c*u + 5*v - v + 1. Let r be (-1 - u - -8) + 2. Solve -2 = 4*x + r for x. Fix: -3 Task: Let r = -29 + 42. Suppose -8*f = -r*f + 10. Suppose y + n = f*n + 7, 3*y + n = 9. Solve -v = -y - 1 for v. Fix: 5 Task: Suppose -7*d = -8*d + 2. Let v be ((-8)/(-32))/(d/24). Suppose 0*l - 5*l - 3*t = -12, -5*l + 3*t - 12 = 0. Solve l = v*g + g - 20 for g. Fix: 5 Task: Let i(n) be the second derivative of -n**3/6 + 25*n**2/2 - 12*n. Let j be i(21). Suppose 0 = j*m + 42 - 106. Solve 0 = 7*p - 3*p + m for p. Fix: -4 Task: Let u be (-459)/(-36)*(-32)/(-12). Solve -16*l - l = -u for l. Fix: 2 Task: Let r(l) = -l**2 + 2*l - 4. Let t(n) = 2*n**2 - 2*n + 5. Let c(v) = 4*r(v) + 3*t(v). Let h be c(1). Solve h*w + 1 = -8 for w. Fix: -3 Task: Let p(o) = o + 4. Let n be p(-4). Suppose -5*d = 5*t - 4*t - 106, -5*t = 20. Let a = -20 + d. Solve n*h - a = h for h. Fix: -2 Task: Let c = -43 + 988. Let w = c + -941. Solve 8*m - 8 = w*m for m. Fix: 2 Task: Let k be 26/4 + 150/(-100). Solve 0*c = -c - k for c. Fix: -5 Task: Let k = 3265 - 3251. Solve -10*p - k*p = 168 for p. Fix: -7 Task: Let y(n) = -n - 6. Let u be y(-3). Let l be (-9)/(-6) + u/2. Solve l = 2*c - 0*c - 8 for c. Fix: 4 Task: Suppose 0 = -s + 4*u - 22, 4*s = 3*s - 5*u + 14. Let q(r) = r**3 + 7*r**2 + 2*r - 11. Let c be q(s). Solve 5*d = c*d + 8 for d. Fix: -1 Task: Suppose 4*s + 2*g = -2*g + 44, 5*s + 2*g = 46. Solve s = -3*r - 7 for r. Fix: -5 Task: Let a = -46213 - -46218. Suppose -13 = -l + 2*k, k + 73 = 5*l - 19. Solve -1 = a*i + l for i. Fix: -4 Task: Let i be 14/(-4) + 2/4. Let r = 11 - i. Let t(f) = f - 2. Let o be t(4). Solve 4*p - o = -r for p. Fix: -3 Task: Let r(u) = 5*u + 5. Let a be r(8). Let f(j) = -18 + 13 - a - 4*j. Let m be f(-13). Solve -3*v = m*v + 15 for v. Fix: -3 Task: Let u(s) = -s - 1. Let y(i) = 5*i + 8. Let t(w) = 6*u(w) + y(w). Let j = -9 + 7. Let b be t(j). Solve -b = -d + 3*d for d. Fix: -2 Task: Let z = 125 + -110. Let q = 6 + -4. Suppose q*c + 2*c = 0. Solve c*j + 5*j - z = 0 for j. Fix: 3 Task: Suppose 2*s + 0 - 2 = 0. Let o be (-86)/30 - (-12)/(-90). Let a be -1 + s + (-45)/o. Solve 0*q = 3*q + a for q. Fix: -5 Task: Suppose 0 = -5*t - 2*a + 96 - 10, -5*t - 5*a = -80. Let f = t + -31. Let d = f + 18. Solve 3 = -d*y - 2 for y. Fix: -1 Task: Let m be (8/(-12))/((-2)/109) + (-322)/966. Solve -118 = -22*c + m for c. Fix: 7 Task: Suppose 34 = 2*c + 5*a, 2*a - 22 = -2*c - 0*c. Let q = c - 4. Suppose -z = q*b + 2*z - 30, 2*b - 5*z - 13 = 0. Solve 3*u = -3 - b for u. Fix: -4 Task: Let k be 18/8 + (-16)/64. Suppose 0 = -5*z - 5*s + 10, -k*s + 1 = -2*z - 3. Suppose z = 3*i - 3 - 3. Solve -x = -3*x - i for x. Fix: -1 Task: Let t = 9 + -9. Suppose 4*j - j - 4*i - 20 = t, 2*j + 25 = -5*i. Solve 2*h + 0 + 6 = j for h. Fix: -3 Task: Suppose y - 8 = 2*r - 6*r, -5*y = 4*r + 8. Suppose r*i - 15 = -0*i. Let z = -139 - -143. Solve -d - z*d + i = 0 for d. Fix: 1 Task: Suppose -16 = -4*p - 2*a, a + 35 = 5*p - 4*a. Solve -p*l = -3*l + 6 for l. Fix: -3 Task: Let o be 12 + 1 + 1/(-1). Suppose 6 = o*q - 9*q. Suppose -3*j + 3*v = 6, -3 = 2*j + q*v - 7. Solve j = 2*c + 3 - 9 for c. Fix: 3 Task: Suppose 28*g = 7*g + 105. Suppose -9*k = -6*k - 15, 7 = -2*s + g*k. Solve s*w = 6*w - 12 for w. Fix: -4 Task: Suppose 0*s = 3*s - 18. Let i(y) = -9*y + 6*y + 1 + 4*y + s*y**2. Let t be i(-1). Solve t*v = 2*v - 16 for v. Fix: -4 Task: Suppose -3*y + 27 = 3*j - 54, 3*y - 76 = -2*j. Solve -12*z + y = -23*z for z. Fix: -2 Task: Let a = 2 + -3. Let c be 0 - 2 - (a - 4). Suppose -c*y - 3*x + 17 = -y, 0 = -3*y - x + 29. Solve -z = z - y for z. Fix: 5 Task: Suppose -3*h - s - 19 = 0, -2*h + 7 = -4*h + 5*s. Let a be (h/2)/1 - (-19)/1. Solve -4*u + a - 4 = 0 for u. Fix: 3 Task: Let v(q) = q**2 + 4. Let l be v(0). Suppose 0 = -180660*y + 180659*y + 5. Solve 1 = -l*i + y*i for i. Fix: 1 Task: Suppose -5*m + 69 + 304 = 3*a, m = 2*a + 85. Solve m = -6*c + 89 for c. Fix: 2 Task: Suppose -3*d = 2*f - 369, 4*d = 2*f + 5*d - 379. Let r = 309 - f. Let c be (-6)/39 + 18/r. Solve c*a = -a + 3 for a. Fix: 3 Task: Let x(t) = 3*t**3 - 19*t**2 - 4*t + 40. Let l(k) = k**3 - k + 1. Let p(u) = 2*l(u) - x(u). Let a be p(19). Solve 4*c - 8 + 12 = a for c. Fix: -1 Task: Let b = 8 + 20. Solve 7*n - 49 + b = 0 for n. Fix: 3 Task: Suppose -12*p = 13*p - 2450. Solve -89*s = -p*s - 27 for s. Fix: -3 Task: Let h = 192 + -183. Let d be 4/(-18) + 47/h. Solve d = -2*l + 13 for l. Fix: 4 Task: Suppose 7*t - 37 - 5 = 0. Let a be 5/(20/16)*(t - 5). Solve -5*n + 7*n - a = 0 for n. Fix: 2 Task: Let t = 44 + -44. Suppose 3*h = -m, -3*m + 7*m + 4*h = 8. Suppose -3*j + 8*j = 4*f - 23, 3 = -3*f - m*j. Solve 8 = f*i - t*i for i. Fix: 4 Task: Let o = -132 + 134. Solve -4*d - o = -6 for d. Fix: 1 Task: Suppose 0 = 13*s - 9*s. Let r(z) = -2*z - 8. Let k be r(-6). Suppose 2*a - k*h = 20, 4*a + s*h + 8 = -4*h. Solve -x = -a*x for x. Fix: 0 Task: Let g(k) = k**2 - 19*k + 24. Let y be g(18). Let v be (-11)/(-55) + y/(-5). Let n be (v/3)/(2/(-12)). Solve -n*r - 12 = 2*r for r. Fix: -3 Task: Suppose 21*s = -289*s + 42470. Solve 132*x = s*x for x. Fix: 0 Task: Let i(n) = -n**3 - 12*n**2 - 16*n - 49. Let u be i(-11). Solve 0 = u*g - 40 + 10 for g. Fix: 5 Task: Let u be -5*(-28)/30 - (-2)/6. Let s(k) = -5*k - 3. Let w be s(-5). Solve 3 + w = u*p for p. Fix: 5 Task: Let f = -252 + 270. Solve 46 = 7*t + f for t. Fix: 4 Task: Suppose 32*k = 25*k + 21. Solve 33*h - k = 32*h for h. Fix: 3 Task: Let h be 13/5 + 2/5. Let s(d) = -d**2 + 21*d - 20. Let k be s(20). Solve h*t - 8*t - 10 = k for t. Fix: -2 Task: Suppose -2*f - 66 = -4*x - 10, 0 = -3*f. Solve 0 = 7*a - 14 - x for a. Fix: 4 Task: Let a be 56/12 + (-2)/(-6). Suppose -2*j - 3 = 5*s, 22 + 5 = 2*j - a*s. Solve -3*k = -6*k - j for k. Fix: -2 Task: Suppose 2*d - 44 = 3*r, 2*d + 52 = -4*r + r. Let v be ((-9)/4)/(3/r). Solve 5*j - j = v for j. Fix: 3 Task: Suppose -3*k = -8*k. Let s be (2 - (1 + 0))*k. Let z(t) = 2*t + 5. Let u be z(-2). Solve 0 = -s*l + l + u for l. Fix: -1 Task: Let n be (0 + 4/(-6))*-3. Suppose -2*f + n*c = -24, -2*f = c - 0 - 24. Suppose q - 9 + 1 = -h, 4*h - q - f = 0. Solve a = h*a - 6 for a. Fix: 2 Task: Suppose -4*i = i - 155. Let c be (14 + i)/(1 + 0). Suppose -c*j + 42*j = 0. Solve -3 = -3*a - j*a for a. Fix: 1 Task: Let i(u) = -2*u**3 - u - 1. Let n = 7 - 8. Let q be i(n). Solve -3*h - q = -4*h for h. Fix: 2 Task: Suppose 0 = -164*p + 154*p + 170. Solve -p*f - 6 = -23 for f. Fix: 1 Task: Let x be ((-8 - -7) + 2)/((-5)/(-20)). Let c be 2/(-4)*-5*2. Solve x*v = c*v for v. Fix: 0 Task: Let f = -584 + 345. Let x = f - -246. Solve -2*g - x*g = -45 for g. Fix: 5 Task: Suppose 0 = -420*t + 9268 + 12992. Solve t*a = 46*a - 42 for a. Fix: -6 Task: Let g = 26 + -24. Suppose -13 = -g*b + 11. Solve -5*r = -r + b for r. Fix: -3 Task: Let t(r) = 2*r**3 - 10*r**2 + 16*r - 63. Let h be t(5). Solve h*s - 13*s = 0 for s. Fix: 0 Task: Let h be (-8)/(-6)*12/8. Let z be (-1 + 4/h)*3. Solve 0 = z*n - 0*n - 3 for n. Fix: 1 Task: Let t(j) = 3*j - 14. Let o be t(13). Let u = -21 + o. Solve 3*i = 10 - u for i. Fix: 2 Task: Suppose 50 - 38 = 3*c. Solve 4*j + c = -8 for j. Fix: -3 Task: Let p(y) = 6*y**2 + 0*y**3 - 4*y**2 + y**3 + y**2 + y. Let q be p(-2). Solve 0 = -2*w - q - 4 for w. Fix: -3 Task: Let p(b) = -4*b**2 - 24*b - 8. Let k be p(-6). Let h(a) = a**3 + 8*a**2 + 2*a + 28. Let s be h(k). Solve s = 5*n - 2*n for n. Fix: 4 Task: Suppose 2 = j + 4*x - 12, -3*x = -3*j - 3. Solve h = j*h + 1 for h. Fix: -1 Task: Let p be (4/(-14))/(1/(-70)). Solve 0 = -2*o - 2*o + p for o. Fix: 5 Task: Let l = 4 + 0. Suppose -2*h + 6 = -0*h + 3*x, -2*x + 4 = -h. Suppose -2*d + h = -8. Solve -l*g - d = -6*g for g. Fix: 2 Task: Suppose -4*n - 2*q + 66 = 0, 2*n - 2*q - 30 = -0*n. Solve 0 = -44*r + 48*r - n for r. Fix: 4 Task: Let f be (8/1)/(6 - 5). Suppose f = -4*r + 2*p + 2*p, -4 = -4*r + p. Suppose -2*g + 10 = r. Solve -a + g = -0*a for a. Fix: 4 Task: Suppose -20 = 3*p + 7*t - 2*t, 0 = -5*p + t + 4. Solve p = 18*g - 10*g + 40 for g. Fix: -5 Task: Let y be -75*((-12)/(-4))/(-3) + -64 + 59. Solve -96*h = -y*h + 156 for h. Fix: -6 Task: Let s = 612 + -562. Solve 45*x = s*x for x. Fix: 0 Task: Let u be 120/36*(-2)/20 - 37/(-3). Solve -2*w + 8 = u for w. Fix: -2 Task: Let r be (32/28 - 2)*21 - 6. Let v(i) = -i**3 - 28*i**2 - 96*i + 16. Let n be v(r). Solve -17*a = -n*a - 2 for a. Fix: 2 Task: Let h be 3/6 + (5589/18)/9. Solve 59 = 8*x + h for x. Fix: 3 Task: Let t = 7407 - 7332. Solve t*m = 53*m + 110 for m. Fix: 5 Task: Let b(a) = a**3 - 4*a**2 + 4*a + 1. Let w be b(3). Suppose -q = q - w. Solve -q*n + 0*n = 10 for n. Fix: -5 Task: Let r(y) = y**3 + 7*y**2 + 4*y. Suppose 5*k + 39 = 9. Let g be r(k). Suppose -12 = 3*v, 3*s + 2*v + g = 4. Solve 2*p + 6 - 2 = s for p. Fix: -2 Task: Let o = 14 - 6. Suppose -o = -n - 3. Solve 5*p - 5 = n for p. Fix: 2 Task: Suppose g - 9 = -2*h, 5*g = -0*h + 5*h - 60. Solve 11*q - h*q - 20 = 0 for q. Fix: 5 Task: Let z(t) = 9*t**2 - t + 23. Let k be z(0). Suppose -2*s - k = -0*q - 3*q, 4*s + 10 = 2*q. Solve q*b = 7*b for b. Fix: 0 Task: Suppose 180 = 44*h - 35*h. Let k = 0 + 0. Solve k = -u - 3*u - h for u. Fix: -5 Task: Let m(s) = -s**2 - 7*s - 6. Let g be (2/(-4))/((-2)/(-24)). Let x be m(g). Let y = 5 - x. Solve -y*u - 5 - 15 = 0 for u. Fix: -4 Task: Let m = 35 + -32. Suppose -5*t + 0 + 7 = i, 0 = -3*i - 2*t + 8. Solve m*o = -i*o for o. Fix: 0 Task: Let f(b) = 2*b**2 + 1. Let z be f(-1). Suppose -2*v + 4 = 3*l - 12, -3*v + 25 = 5*l. Solve -l*k = -k + z for k. Fix: -3 Task: Let n(o) = 2*o**2 - o - 2. Let r be n(-2). Suppose 0 = -4*x - 0*x + 8. Let s be ((-15)/(-20))/(x/r). Solve -4*v = -s + 15 for v. Fix: -3 Task: Suppose 5*l - 4*l = 0. Let x(v) = v**3 - 6*v**2 + 2*v - 7. Let n be x(6). Suppose s = 6*s - 5*u - n, l = 2*s - 4*u + 2. Solve y + 1 = s for y. Fix: 2 Task: Let b = -134 + 139. Let m be (-15)/(2/4*-3). Solve -b*o + 3*o + m = 0 for o. Fix: 5 Task: Suppose -5*w + 2*w = 0. Suppose t + t - 32 = w. Solve -4*j + 0*j = -t for j. Fix: 4 Task: Let z be 271 - 94 - (32/20)/((-1)/(-5)). Solve 0 = -27*j - z - 47 for j. Fix: -8 Task: Suppose 2*a - 37 = -13. Suppose -2*w - 4*d = -6*w + a, -4*w - 15 = 5*d. Solve 3*j - 2*j = w for j. Fix: 0 Task: Let l be (-13)/(-5) + -2 - (-484)/110. Solve -3*q - 2 = -l for q. Fix: 1 Task: Suppose -13*i = -24 - 15. Suppose 0 = -o + 4*k - 18, -3*k - k + 28 = 4*o. Suppose 16 = 5*l + j, -3*l + o*j + 4 = -3*j. Solve i*f = -6 - l for f. Fix: -3 Task: Suppose -3*o = 5*h + 25, -11 = -5*o + 5*h + 14. Solve 3*z - 6 - 3 = o for z. Fix: 3 Task: Suppose -4*i + 12 = 4. Suppose -j - i*j = -48. Solve 2*g - j = -2*g for g. Fix: 4 Task: Let x(q) = -q**2 - 5*q - 2. Let y be x(-6). Let i(a) be the first derivative of a**4/4 + 8*a**3/3 - a**2/2 - 6*a + 1. Let v be i(y). Solve 2 = -3*d + v*d for d. Fix: -2 Task: Suppose 4*u - 80 = 2*i, u + 4*i - 27 = i. Solve 0 = -3*b - 4*b - u for b. Fix: -3 Task: Let u(g) be the third derivative of -3*g**2 + 0 + 1/15*g**5 + 0*g**4 + 0*g - 1/6*g**3. Let j be u(1). Solve 4*r - j*r - 3 = 0 for r. Fix: 3 Task: Let o = 7 - 1. Solve 0*b + 2*b + o = 0 for b. Fix: -3 Task: Suppose 551*s + 560*s - 56 = 1104*s. Solve 0 = -44*i - s + 8 for i. Fix: 0 Task: Suppose 0 = -5*r - 4*q + 55, 4*r - 4*q - 13 = -q. Solve -4*d + 13 + r = 0 for d. Fix: 5 Task: Let c(q) = q**3 - 7*q**2 - q + 2. Let p be c(7). Let k be ((-12)/(-15))/((-2)/p). Suppose -k*h + 16 = 3*f, 0 = -2*f + 8. Solve 3*j = -h*j - 20 for j. Fix: -4 Task: Let t(u) = 20*u - 35. Let w be t(3). Suppose -w*a + 54 = -7*a. Solve -2 = a*o + 7 for o. Fix: -3 Task: Let d = -1744 - -1746. Solve 20*m - 98 = d for m. Fix: 5 Task: Suppose -9*x = -11*x + 8. Let c = 1 - 1. Let h = x + c. Solve -h*q + 1 = -3 for q. Fix: 1 Task: Suppose 4*h = -3*q + 2*q + 10, -3*q + 3*h - 15 = 0. Let r be 3 - (-2 - -3)*q. Solve r*y - 1 = 4*y for y. Fix: 1 Task: Suppose 3 - 6 = -f. Solve f*v - 5*v = 0 for v. Fix: 0 Task: Let q = -3 + 7. Suppose -q*i - x = -4*x - 45, 4*i = 5*x + 51. Solve s = -2*s + i for s. Fix: 3 Task: Let c(u) = 2*u**3 - 9*u**2 + u + 1. Let q be c(7). Let h = q - 373. Let b be 2/3 + h/(-9). Solve b - 2 = -3*v for v. Fix: -4 Task: Let k(i) = -i**2 + 9*i - 8. Let j be k(5). Suppose 5*g - 2*f - 13 = -51, -g - 4*f - j = 0. Let s = -5 - g. Solve s*u = 2 + 1 for u. Fix: 1 Task: Suppose -m + 4*n = -41, -89 = -4*m + n - 0*n. Let j = m - 19. Solve -2 = -4*v + j*v for v. Fix: 1 Task: Let g(m) = 265*m - 3931. Let p be g(15). Solve -16 - p = -12*k for k. Fix: 5 Task: Let s(r) = -r**2 - 23*r - 71. Let m be s(-5). Solve 9*n - m*n = -10 for n. Fix: 1 Task: Let a = 19 - 14. Suppose -a*s - 10 = 0, 3*w + 82 = -s - s. Let r = -11 - w. Solve -3*q = -0*q + r for q. Fix: -5 Task: Let j = -3 - -3. Suppose j = 4*f + 20, 4*g - 2*f - 20 - 26 = 0. Solve -3*n - g = -0*n for n. Fix: -3 Task: Suppose -29 = -4*k - 3*p, -k + 11 = k + 5*p. Suppose u = 5*u - k. Solve 0 - 4 = -u*s for s. Fix: 2 Task: Let t(r) = -r**3 + 7*r**2 - 7*r + 9. Let d be 8/6*(-27)/(-6). Let u be t(d). Solve -20 = -u*p - 2*p for p. Fix: 4 Task: Let k = -30 + 46. Let f(w) = -w**3 + 5*w**2 - 4*w + 3. Let g be f(4). Solve -n = g*n + k for n. Fix: -4 Task: Suppose -71 + 26 = 3*x. Let d = x - -27. Let v be (((-16)/d)/(1/3))/(-1). Solve v = 2*b - 2 for b. Fix: 3 Task: Suppose 0 = s + 4*s - 205. Suppose -5 = -h, 2*z - 3 = -4*h + s. Suppose -8 = -5*i + z, -4*i + 16 = -n. Solve -j + 4*j + 3 = n for j. Fix: -1 Task: Let k(z) = 2*z**2 - 15*z + 25. Let h be k(9). Let m = h - 49. Let w = -2 + m. Solve 4*l + 3 = -w for l. Fix: -1 Task: Suppose -5*y = j - 6, 0*j = -4*y + j + 3. Solve s = -y - 1 for s. Fix: -2 Task: Suppose 0 = 4*s - y - y + 2, 5*s + 3*y - 14 = 0. Let b(n) = -n + 10. Let m be b(7). Solve d - m = -s for d. Fix: 2 Task: Let n = 88 - -124. Let w = n + -209. Solve -76*b = -73*b + w for b. Fix: -1 Task: Let n(b) = 68*b + 6. Let p(g) = -4*g**2 - 40*g. Let h be p(-10). Let v be n(h). Solve v*x = -3 + 21 for x. Fix: 3 Task: Let p be 2/12 - (-115)/30. Solve p*t + 0*t = 0 for t. Fix: 0 Task: Let s(t) = 2227 + 3*t - 741 - 736 - 742 - 6*t. Let r(u) = u - 4. Let m be r(4). Let z be s(m). Solve n - 5 = -z for n. Fix: -3 Task: Let s = -23 - -19. Let u be (s + 0 + 4)/(1*-3). Suppose 2*w = -5*t + 15, -5*t + 4*w - 16 = -t. Solve u = j - t - 1 for j. Fix: 2 Task: Let j = 2 - -1. Let b = 15 - j. Let z = b - 1. Solve -5*f - 31 = -z for f. Fix: -4 Task: Let r be (-372)/(-132) + (-2)/(-11). Solve -r*l + l = -8 for l. Fix: 4 Task: Suppose -19*z + z = 21*z - 34905. Solve 18*l = -z + 787 for l. Fix: -6 Task: Let f(j) be the first derivative of -11/2*j**2 - 1/4*j**4 - 12*j + 5 + 13/3*j**3. Let b be f(12). Solve -p + 0*p + 1 = b for p. Fix: 1 Task: Let c(d) = -5*d - 24. Let u be c(-6). Solve u*z = z for z. Fix: 0 Task: Suppose 2*z - z - 10 = 5*o, -2*z - 2*o = -20. Solve -n - n = -z for n. Fix: 5 Task: Let w(c) be the third derivative of c**6/120 + c**5/20 - c**4/6 - c**3/3 - 3*c**2. Let p be w(-3). Solve 0 = r + r + p for r. Fix: -5 Task: Suppose 0 = 4*d - 6*d + 4*l + 26, 3*d = -5*l - 16. Suppose u + 3 = 5*r, -2*r + 6 = -3*u - d. Solve 0 = b - r*b for b. Fix: 0 Task: Let s = 3 + -4. Let o be s/((-7)/(-4) + -2). Suppose o*z - z = 12. Solve z = 5*a - 21 for a. Fix: 5 Task: Suppose 3*b - 60 = -7*b. Solve -b*x - 8 = -4*x for x. Fix: -4 Task: Let z = 342 + -45. Let g = z - 294. Suppose -r = 2, 3*r - 6 + 21 = v. Solve -v = -g*x - 0*x for x. Fix: 3 Task: Suppose 0 = -y + 3*y - 8. Let v(u) = -u**2 + 4*u + 5. Let d be v(5). Solve d*j = -y*j for j. Fix: 0 Task: Suppose -348*b + 4 = -347*b. Solve -4*c - b = -12 for c. Fix: 2 Task: Let l = 12 + -12. Solve -y = -l*y for y. Fix: 0 Task: Suppose x - 2*p = 10, -6*x = -7*x + 4*p + 20. Suppose 5*y = -i + 31, 10*i + 1 = y + 5*i. Solve x = -b + y*b - 15 for b. Fix: 3 Task: Let l(d) = -4*d**2 - 10*d + 13. Let w(g) = -g**2 - 3*g + 3. Let v(u) = -2*l(u) + 9*w(u). Let q be v(-6). Solve q = 2*x + 9 for x. Fix: -1 Task: Suppose -4*m + i + 131 + 51 = 0, i + 92 = 2*m. Solve -106 + 376 = m*r for r. Fix: 6 Task: Let d = -116 + 113. Let w be 3/d*(-14 + -2). Solve -3*l = l + w for l. Fix: -4 Task: Let x = -122 + 237. Let l = x - 88. Solve -5*k + 12 - l = 0 for k. Fix: -3 Task: Let t(o) = o + 44. Let s be t(-29). Let x be ((-1)/((-5)/s))/((-3)/(-4)). Solve -x*h = -3*h - 3 for h. Fix: 3 Task: Let o(h) = h**3 + 9*h**2 - h - 9. Let b be o(-9). Suppose -4*w + 4*j - 8 = 0, -3*w - 2*j + 14 = -b*j. Solve 0 + 10 = -w*c for c. Fix: -5 Task: Let m be 0*(-1)/(-2) - (3 - 3). Solve m = 8*s - 1 + 25 for s. Fix: -3 Task: Let c be (206/2 + -2)*162/162. Solve -y = -c + 103 for y. Fix: -2 Task: Let h be 0/6 + 11 + -6. Solve 0 = -h*m - 10 - 10 for m. Fix: -4 Task: Suppose 0 = -3*i - 15 + 21. Solve 2 = -i*b + 8 for b. Fix: 3 Task: Suppose -2*h - m = -13, -3*h - m - 2 = -4*h. Let a = 7 - h. Suppose -f - a*t - 13 = -4*f, 0 = f - 5*t - 13. Solve -2*n + f - 13 = 0 for n. Fix: -5 Task: Suppose -1 = 5*y + u, 4*u - 13 = -3*y - 0. Let j = 1 - y. Suppose 0 = -h - j*h + 6. Solve -a = -0*a - h for a. Fix: 2 Task: Suppose 114 = 3*j - 84. Let w = j - 6. Suppose 4*n - 31 = -2*p + 39, 4*n + 4*p = w. Solve -5*f + 10*f = n for f. Fix: 4 Task: Let c(l) = -l**2 + 6*l + 2. Let d be c(6). Suppose -d*s = y + 4 - 3, -y + 5 = -s. Solve y*r + 5 = 14 for r. Fix: 3 Task: Let g be 5 - 5/((-10)/(-4)). Suppose s + 5*u = -7 - 3, 6 = -2*s - g*u. Suppose 6*r - 3*r - 33 = 0. Solve 5*b + 1 - r = s for b. Fix: 2 Task: Suppose 1330*c = 1354*c - 120. Solve -c*m + 594 = 564 for m. Fix: 6 Task: Let c(w) be the second derivative of 5*w**3/6 - 3*w**2 - 4*w - 24. Let l be c(4). Solve l*r - 5*r = -36 for r. Fix: -4 Task: Let u be ((-2)/2)/(2 - 1). Let n be ((-2)/((-6)/(-9)))/u. Solve 0 = n*a + 10 - 1 for a. Fix: -3 Task: Let f(y) be the third derivative of y**5/60 + y**4/12 - 4*y**3/3 - 4*y**2 + 14*y. Suppose -2*h - 15 = h. Let v be f(h). Solve v*t = 4*t for t. Fix: 0 Task: Let t = 71 - 69. Solve 0 = t*g + 1 + 3 for g. Fix: -2 Task: Let t = -23 - -23. Solve t = b - 3 + 2 for b. Fix: 1 Task: Suppose -5*a - 9*k + 8*k + 40 = 0, -4*a = k - 31. Solve a*j - 49 = -4 for j. Fix: 5 Task: Suppose 2*d = 5*a + 18, -d = -a + 2*a - 2. Let y be 1*1/a*0. Solve 5*o + y + 15 = 0 for o. Fix: -3 Task: Let k = 29 - 19. Solve -5*u = -0*u - k for u. Fix: 2 Task: Let m be (1410/130 - 11) + 28/13. Solve -26 = -7*b + m for b. Fix: 4 Task: Let p = -9 + 14. Let z = p - 5. Suppose -3*d - 2*d = z. Solve -2*n + n - 2 = d for n. Fix: -2
[{"idx": "txt360/numbers__div_remainder_composed_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-3.jsonl"}, {"idx": "txt360/algebra__linear_1d_composed_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-3.jsonl"}]
import { ISpinnakerPipelineConfiguration } from '../../interfaces' import { BaseStagesUnion, IBaseSpinnakerPipeline, IBaseVirtualService, IBuildReturn, IBuildService, ICleanIds, IDeploymentReturn, IEmptyVirtualService } from '../interfaces' import baseStage from '../utils/base-default-stage' import basePipeline from '../utils/base-spinnaker-pipeline' import baseStageHelm from '../utils/base-stage-helm' import webhookBaseStage from '../utils/base-webhook' import { createBakeStage, createPrimaryId } from '../utils/helpers/create-id-names' import baseDeleteDeployments from '../utils/manifests/base-delete-deployment' import baseDeployment from '../utils/manifests/base-deployment' import createDestinationRules, { IDestinationRuleParams } from '../utils/manifests/base-destination-rules' import { createVirtualService, createEmptyVirtualService } from '../utils/manifests/base-virtual-service' export default class TotalPipeline { refId: number previousStage: string previousStages: string[] deploymentsIds: string[] contract: ISpinnakerPipelineConfiguration basePipeline: IBaseSpinnakerPipeline constructor(contract: ISpinnakerPipelineConfiguration) { this.refId = 1 this.previousStage = '' this.previousStages = [] this.deploymentsIds = [] this.contract = contract this.basePipeline = basePipeline(contract, this.contract.helmRepository, this.contract.githubAccount) } public buildPipeline(): IBaseSpinnakerPipeline { this.buildDeployments() this.buildDestinationRules() this.buildVirtualService() this.buildDeleteDeployments() this.buildWebhook() this.cleanIds() return this.basePipeline } private increaseRefId(): number { this.refId += 1 return this.refId } private updatePreviousStage(stage: string): string { this.previousStage = stage return this.previousStage } private updatePreviousStages(stage: string): string[] { this.previousStages.push(stage) return this.previousStages } private buildDeployments(): IDeploymentReturn | undefined { if (this.contract.versions.length === 0) { return } const preRefId = this.refId - 1 this.contract.versions.forEach(version => { const helmStage = baseStageHelm( this.contract, this.contract.githubAccount, version.version, version.versionUrl, String(this.refId), [], undefined ) this.basePipeline.stages.push(helmStage) this.increaseRefId() this.updatePreviousStage(createBakeStage(version.version)) const deployment = baseDeployment( createPrimaryId('deployment', version.version), `Deploy ${version.version}`, String(this.refId), [String(this.refId - 1)], createBakeStage(version.version), this.contract.appName, this.contract.account ) this.basePipeline.stages.push(deployment) this.deploymentsIds.push(String(this.refId)) this.increaseRefId() this.updatePreviousStage(`Deploy ${version.version}`) this.updatePreviousStages(`Deploy ${version.version}`) }) return { stages: this.basePipeline.stages, deploymentsIds: this.deploymentsIds, refId: this.refId, previousStage: this.previousStage, previousStages: this.previousStages } } private buildDestinationRules(): IBuildReturn { const stageName = 'Deploy Destination Rules' const { account } = this.contract const destinationRules = createDestinationRules(this.contract.appName, this.contract.appNamespace, this.contract.circles, this.contract.versions) const destinationRulesStage = baseStage( destinationRules, stageName, account, String(this.refId), this.deploymentsIds, this.previousStages ) this.basePipeline.stages.push(destinationRulesStage) this.increaseRefId() this.updatePreviousStage(stageName) return { stages: this.basePipeline.stages, refId: this.refId, previousStage: this.previousStage } } private buildVirtualService(): IBuildReturn { const stageName = 'Deploy Virtual Service' const { account } = this.contract const virtualService: IBaseVirtualService | IEmptyVirtualService = this.contract.versions.length === 0 ? createEmptyVirtualService(this.contract.appName, this.contract.appNamespace) : createVirtualService( this.contract.appName, this.contract.appNamespace, this.contract.circles, this.contract.hosts ) const virtualServiceStage = baseStage( virtualService, stageName, account, String(this.refId), [String(this.refId - 1)], this.previousStage ) this.basePipeline.stages.push(virtualServiceStage) this.increaseRefId() this.updatePreviousStage(stageName) return { stages: this.basePipeline.stages, refId: this.refId, previousStage: this.previousStage } } private buildDeleteDeployments(): IBuildReturn | undefined { if (this.contract.unusedVersions.length) { const stageName = 'Delete Deployments' const deleteDeployments = baseDeleteDeployments( this.contract, this.refId, [String(this.refId - 1)], this.previousStage ) this.basePipeline.stages.push(deleteDeployments) this.increaseRefId() this.updatePreviousStage(stageName) return { stages: this.basePipeline.stages, refId: this.refId, previousStage: this.previousStage } } } private buildWebhook(): BaseStagesUnion { const webhookStage = webhookBaseStage( this.contract.webhookUri, String(this.refId), [String(this.refId - 1)], this.previousStage, this.contract.circleId ) this.basePipeline.stages.push(webhookStage) return this.basePipeline.stages } private cleanIds(): ICleanIds { this.refId = 1 this.previousStage = '' this.deploymentsIds = [] return { refId: this.refId, previousStage: this.previousStage, deploymentsIds: this.deploymentsIds } } }<|endoftext|>import { useCallback, useState, useEffect } from 'react'; import type { FC, ChangeEvent } from 'react'; import { Link as RouterLink } from 'react-router-dom'; import { Helmet } from 'react-helmet-async'; import { Box, Breadcrumbs, Button, Container, Divider, Grid, Link, Tab, Tabs, Typography } from '@material-ui/core'; import { customerApi } from '../../__fakeApi__/customerApi'; import { CustomerContactDetails, CustomerDataManagement, CustomerEmailsSummary, CustomerInvoices, CustomerInvoicesSummary, CustomerLogs } from '../../components/dashboard/customer'; import useMounted from '../../hooks/useMounted'; import ChevronRightIcon from '../../icons/ChevronRight'; import PencilAltIcon from '../../icons/PencilAlt'; import gtm from '../../lib/gtm'; import type { Customer } from '../../types/customer'; import useSettings from '../../hooks/useSettings'; const tabs = [ { label: 'Details', value: 'details' }, { label: 'Invoices', value: 'invoices' }, { label: 'Logs', value: 'logs' } ]; const CustomerDetails: FC = () => { const mounted = useMounted(); const { settings } = useSettings(); const [customer, setCustomer] = useState<Customer | null>(null); const [currentTab, setCurrentTab] = useState<string>('details'); useEffect(() => { gtm.push({ event: 'page_view' }); }, []); const getCustomer = useCallback(async () => { try { const data = await customerApi.getCustomer(); if (mounted.current) { setCustomer(data); } } catch (err) { console.error(err); } }, [mounted]); useEffect(() => { getCustomer(); }, [getCustomer]); const handleTabsChange = (event: ChangeEvent<{}>, value: string): void => { setCurrentTab(value); }; if (!customer) { return null; } return ( <> <Helmet> <title>Dashboard: Customer Details | Material Kit Pro</title> </Helmet> <Box sx={{ backgroundColor: 'background.default', minHeight: '100%', py: 8 }} > <Container maxWidth={settings.compact ? 'xl' : false}> <Grid container justifyContent="space-between" spacing={3} > <Grid item> <Typography color="textPrimary" variant="h5" > {customer.name} </Typography> <Breadcrumbs aria-label="breadcrumb" separator={<ChevronRightIcon fontSize="small" />} sx={{ mt: 1 }} > <Link color="textPrimary" component={RouterLink} to="/dashboard" variant="subtitle2" > Dashboard </Link> <Link color="textPrimary" component={RouterLink} to="/dashboard" variant="subtitle2" > Management </Link> <Typography color="textSecondary" variant="subtitle2" > Customers </Typography> </Breadcrumbs> </Grid> <Grid item> <Box sx={{ m: -1 }}> <Button color="primary" component={RouterLink} startIcon={<PencilAltIcon fontSize="small" />} sx={{ m: 1 }} to="/dashboard/customers/1/edit" variant="contained" > Edit </Button> </Box> </Grid> </Grid> <Box sx={{ mt: 3 }}> <Tabs indicatorColor="primary" onChange={handleTabsChange} scrollButtons="auto" textColor="primary" value={currentTab} variant="scrollable" > {tabs.map((tab) => ( <Tab key={tab.value} label={tab.label} value={tab.value} /> ))} </Tabs> </Box> <Divider /> <Box sx={{ mt: 3 }}> {currentTab === 'details' && ( <Grid container spacing={3} > <Grid item lg={settings.compact ? 6 : 4} md={6} xl={settings.compact ? 6 : 3} xs={12} > <CustomerContactDetails address1={customer.address1} address2={customer.address2} country={customer.country} email={customer.email} isVerified={customer.isVerified} phone={customer.phone} state={customer.state} /> </Grid> <Grid item lg={settings.compact ? 6 : 4} md={6} xl={settings.compact ? 6 : 3} xs={12} > <CustomerInvoicesSummary /> </Grid> <Grid item lg={settings.compact ? 6 : 4} md={6} xl={settings.compact ? 6 : 3} xs={12} > <CustomerEmailsSummary /> </Grid> <Grid item lg={settings.compact ? 6 : 4} md={6} xl={settings.compact ? 6 : 3} xs={12} > <CustomerDataManagement /> </Grid> </Grid> )} {currentTab === 'invoices' && <CustomerInvoices />} {currentTab === 'logs' && <CustomerLogs />} </Box> </Container> </Box> </> ); }; export default CustomerDetails;
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5063.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-5063.jsonl"}]
Kafka tools won't start on Ubuntu 18.04 Question: I Installed kafkatools from [IDX] in Ubuntu 18.04. The Installation is OK, but when I clicked on it, it does nothing. I installed multiple times on different devices, but I really don't have any idea what is happening. First I installed openjdk-8-jdk, kafkatools, and after that I installed zookeeper and kafka, and I removed kafkatools and reinstalled it, but the issue persists. Comment: karel the issue resolved Thanx for helping , I removed java and then reinstalled it, it working now !! Comment: You have openjdk-8-jdk installed as the default JDK with `sudo apt install openjdk-8-jdk`, right? Comment: Tnx for responding, Yeah I installed it. Comment: I Installed it too, but First I installed kafkatools and after that, I installed zookeeper and kafka, but I removed kafkatools and reinstalled it but the issue persists Comment: Does Kafka work from the terminal? Answer: Kafka is a distributed streaming platform. It is useful for building real-time streaming data pipelines to get data between the systems or applications. Another useful feature is real-time streaming applications that can transform streams of data or react on a stream of data. This answer will help you to install Apache Kafka on Ubuntu 16.04 and later. 1. Install Java Apache Kafka required Java to run. You must have Java installed on your system. Execute the below command to install default OpenJDK on your system from the official Ubuntu repositories. You can also install the specific version of from here. <code>sudo apt update sudo apt install openjdk-8-jdk </code> 2. Download Apache Kafka Download the Apache Kafka binary files from its official download website. You can also select any nearby download mirror. <code>wget [IDX] extract the archive file. <code>tar xzf kafka_2.13-2.4.0.tgz mv kafka_2.13-2.4.0 /usr/local/kafka </code> Alternatively, download a binary from here: [IDX] installing from snap did not work on Ubuntu 22.04 3. Setup Kafka systemd unit files Next create systemd unit files for the Zookeeper and Kafka service. This will help to manage Kafka services to start/stop using the systemctl command. First, create systemd unit file for Zookeeper with below command: <code>vim /etc/systemd/system/zookeeper.service </code> Add the below content: <code>[Unit] Description=Apache Zookeeper server Documentation= [IDX] remote-fs.target After=network.target remote-fs.target [Service] Type=simple ExecStart=/usr/local/kafka/bin/zookeeper-server-start.sh /usr/local/kafka/config/zookeeper.properties ExecStop=/usr/local/kafka/bin/zookeeper-server-stop.sh Restart=on-abnormal [Install] WantedBy=multi-user.target </code> Save the file and close it. Next, to create a Kafka systemd unit file using the following command: <code>sudo nano /etc/systemd/system/kafka.service </code> Add the below content. Make sure to set the correct <code>JAVA_HOME</code> path as per the Java installed on your system. <code>[Unit] Description=Apache Kafka Server Documentation= [IDX] /usr/local/kafka/config/server.properties ExecStop=/usr/local/kafka/bin/kafka-server-stop.sh [Install] WantedBy=multi-user.target </code> Save the file and close. Reload the systemd daemon to apply the new changes. <code>systemctl daemon-reload </code> 4. Start Kafka server Kafka required ZooKeeper so first, start a ZooKeeper server on your system. You can use the script available with Kafka to get start a single-node ZooKeeper instance. <code>sudo systemctl start zookeeper </code> Now start the Kafka server and view the running status: <code>sudo systemctl start kafka sudo systemctl status kafka </code> All done. The Kafka installation has been successfully completed. The next part of this answer will help you to work with the Kafka server. 5. Create a topic in Kafka Kafka provides multiple pre-built shell script to work on it. First, create a topic named "testTopic" with a single partition with single replica: <code>cd /usr/local/kafka bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic testTopic Created topic testTopic. </code> The replication-factor describes how many copies of data will be created. As we are running with a single instance keep this value 1. Set the partitions options as the number of brokers you want your data to be split between. As we are running with a single broker keep this value 1. You can create multiple topics by running the same command as above. After that, you can see the created topics on Kafka by the running the below command: <code>bin/kafka-topics.sh --list --zookeeper localhost:2181 testTopic TecAdminTutorial1 TecAdminTutorial2 </code> Alternatively instead of manually creating topics you can also configure your brokers to auto-create topics when a nonexistent topic is published to. 6. Send messages to Kafka The "producer" is the process responsible for putting data into our Kafka. Kafka comes with a command-line client that will take input from a file or from standard input and send it out as messages to the Kafka cluster. The default Kafka sends each line as a separate message. Let's run the producer and then type a few messages into the console to send to the server. <code>bin/kafka-console-producer.sh --broker-list localhost:9092 --topic testTopic > Welcome to kafka > This is my first topic </code> You can exit this command or keep this terminal running for further testing. Now open a new terminal to the Kafka consumer process on the next step. 7. Using Kafka consumer Kafka also has a command-line consumer to read data from the Kafka cluster and display messages to standard output. <code>bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic testTopic --from-beginning Welcome to kafka This is my first topic </code> Now If you have still running Kafka producer (Step 6) in another terminal, just type some text on that producer terminal. It will immediately be visible on consumer terminal. See the below screenshot of Kafka producer and consumer working: Source: How to Install Apache Kafka on Ubuntu 18.04 & 16.04 Comment: ```kafka.service: Failed at step EXEC spawning /usr/local/kafka/bin/kafka-server-start.sh: No s``` Comment: zookeeper is also failing Comment: @mLstudent33 Maybe my answer needs to be updated for Ubuntu 22.04. Please read this: [How to Install Apache Kafka on Ubuntu 22.04]( [IDX] Maybe try installing zookeeper with apt using `sudo apt install zookeeper`. Comment: I downloaded 2.13 from here: [IDX] and the rest of your instructions worked. Thanks very much. Comment: @mLstudent33 Please edit my answer by adding your modifications to my original instructions to it, and I will accept your suggested edit.<|endoftext|>Clarify "Insertion-sort if the priority-queue implemented with an ordered array", why 'ordered" required? Question: Insertion-sort works also on unordered array, like the example here shows. This statement in the title (or here) for some odd reason requires that you have an ordered array to implement priority-queue for the insertion sort, why does it have such requirement? What does this Wikipedia -thing here actually mean (the below screenshot)? Answer: The article relates the usage of priority queue for sorting and how different implementations of priority queue correspond with familiar sorting algorithms. Let us consider ADT priority queue with operation <code>pop()</code> which takes out the "smallest" element as defined by a comparison function and <code>push()</code> which put a new element in the priority queue. Then sorting can be done by calling <code>push()</code> to push all elements in the unsorted array into the priority queue and calling <code>pop()</code> until the priority queue is empty and put the popped out element into an array (well, you can define a method <code>empty()</code> to check whether the ADT is empty). Psuedocode: <code>unsorted[] sorted[] priority_queue q foreach element in unsorted q.push(element) i = 0 while !q.empty() sorted[i] = q.pop() i = i + 1 </code> Then we talk about how to implement the priority queue. Typically, it is efficiently implemented with heap. However, it is not necessary to be heap - you can implement it in less efficient ways, which is with unordered array or ordered array as mentioned in Wikipedia article. As long as the implementation satisfy the requirement for the <code>push()</code> and <code>pop()</code> operations then it is fine. For unordered array, you can <code>push()</code> by placing the element directly just after the last element - since it is unordered. When you <code>pop()</code>, since the array is unordered, you need to search through the whole array and pick out the largest element. (Removal can be done easily, by swapping the last element in the unordered array to the position of the element being popped out). It is similar to selection sort, since you are essentially go through the list of unsorted elements (which is in the priority queue) and pick out the largest element to put into sorted portion. You can see that insertion operation in insertion sort is being done in the <code>push()</code> operation here. For ordered array, you can <code>pop()</code> by just taking out the first element (removal can be done easily by maintaining a starting index). But <code>push()</code> will require you to find out where to place the element to maintain the order (since it is an ordered array). This is the part where it closely resembles insertion sort, since you are trying to insert the current element to the sorted portion (the priority queue implemented as ordered array). You can see that selection operation in selection sort is being done in the <code>pop()</code> operation here. Comment: @hhh: It is the implementation of the priority queue, **not the array you are trying to sort**. Since you want the priority queue array to be ordered, when you push, you need to try to insert it in the array, rather than placing it after the last element. You need to get the confusion of implementation versus the array to be sorted out of your head first. (And the axiom there is for empty array, there is another axiom for insertion to non-empty array). Comment: If you're implementing PQ with ordered array, you keep array ordered, so when you doing `push()` you're finding place for new element. But when you're doing `pop()` you just getting first element. It works other way around when you're unordered array - you just adding an element when you `push()`, but you scanning all elements when you need to do `pop()` Comment: @hhh: The usage of priority queue implemented by **ordered array** for sorting is *equivalent* but not exactly the same as the insertion sort algorithm (one uses a data structure, the other operates directly on the array). As for algorithm that uses PQ, Dijkstra algorithm is one prominent one. Comment: ...freaking cool +1! I did not understand the sorting can be done so easily with Priority Queue, thank you :D Is there any easy way to test it in practise in some programming language let say Python? I am trying to understand this by doing... Comment: @hhh: Check this out: [IDX] , it is implementation of priority queue with heap. You need to write your own implementation for priority with unordered/ordered array, but it should be easy enough. The point of priority queue is that it will pop out the "smallest" element, so we can use that properly for sorting. Comment: I cannot understand: `"But push() will require you to find out where to place the element to maintain the order (since it is an ordered array)"`. This `"(since it is an ordered array)"`? Cannot see the dif between the unordered array and ordered array here. Suppose I give some decimal priority to every element in `push()` and axioms such as `min(insert(v,new()))=v`, more [here]( [IDX] Now in pop, I just select the smallest element because priorities in real numbers dense. What does it matter whether I have ordered or unordered? Comment: @nhahtdh where can you find more info about the axiomization? I feel very confused. I have Cormen but it does not cover this or I cannot find anything relevant, still feeling puzzled. Comment: @RomanPekar Thank you, I think I understood it: if you implement insertion sort with unordered array with PQ, the "cache"/middle-storage is unordered so pop must handle the ordering. If the implementation with ordered array with PQ, the cache/middle-storage with push does the ordering so no need for the ordering in the pop. Is this reciting correct? Comment: @hhh: Your understanding is basically correct. (About axiomization, clause 2 says that the smallest element (in a queue where you insert the first element) is the first element, clause 4 says that if the new element is smaller than the smallest element in the current queue, then it is the smallest element in the new queue, otherwise, the smallest element in the new queue is the same as the smallest element in the old queue). Comment: **Summarum:** Back to the title, so insertion-sort could be implemented with PQ and unordered array? The article [here]( [IDX] had only examples about traditional implementation and they could be done in other ways like here with unordered array, PQ and insertion-sort? I am trying to understand what value the priority queue in each algorithm actually have, is there some algorithm where priority-queue is very essential? Why does Wikipedia mention the algos? Is there better examples for PQ usage?
[{"idx": "Kafka_tools_won't_start_on_Ubuntu_18.04", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-4201.jsonl"}, {"idx": "Clarify_\"Insertion-sort_if_the_priority-queue_implemented_with_an_ordered_array\",_why_'ordered\"_required?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-4201.jsonl"}]
FlashChat installation hiccup! SQL syntax error? Question: I've done away with the (14) and (11) but when trying to install tufat's Flashchat, I keep getting this error: Could not create DB table 'smf_fc_bans'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(14) NOT NULL, userid int(11) default NULL, banneduserid int(11) default NULL, r' at line 1 Granted I'm still such a novice. If someone could help me I would be so very very grateful. Table structure for table <code>bans</code>: <code>CREATE TABLE `bans` ( `id` int NOT NULL auto_increment, `created` timestamp NOT NULL, `userid` int default NULL, `banneduserid` int default NULL, `roomid` int default NULL, `ip` varchar default NULL, KEY `id` (`id`), KEY `userid` (`userid`), KEY `created` (`created`) ) ENGINE=MyISAM; </code> Table structure for table <code>connections</code>: <code>CREATE TABLE `connections` ( `id` varchar(32) NOT NULL default '', `updated` timestamp NOT NULL, `created` timestamp NOT NULL, `userid` int default NULL, `roomid` int default NULL, `state` tinyint(4) NOT NULL default '1', `color` int default NULL, `start` int default NULL, `lang` char(2) default NULL, `ip` varchar(16) default NULL, `tzoffset` int default '0', `chatid` int NOT NULL default '1', PRIMARY KEY (`id`), KEY `userid` (`userid`), KEY `roomid` (`roomid`), KEY `updated` (`updated`) ) ENGINE=MyISAM; </code> Table structure for table <code>ignors</code>: <code>CREATE TABLE `ignors` ( `created` timestamp NOT NULL, `userid` int default NULL, `ignoreduserid` int default NULL, KEY `userid` (`userid`), KEY `ignoreduserid` (`ignoreduserid`), KEY `created` (`created`) ) ENGINE=MyISAM; </code> Table structure for table <code>messages</code>: <code>CREATE TABLE `messages` ( `id` int(11) NOT NULL auto_increment, `created` timestamp NOT NULL, `toconnid` varchar(32) default NULL, `touserid` int(11) default NULL, `toroomid` int(11) default NULL, `command` varchar(255) NOT NULL default '', `userid` int default NULL, `roomid` int(11) default NULL, `txt` text, PRIMARY KEY (`id`), KEY `touserid` (`touserid`), KEY `toroomid` (`toroomid`), KEY `toconnid` (`toconnid`), KEY `created` (`created`) ) ENGINE=MyISAM AUTO_INCREMENT=14 ; </code> Table structure for table <code>rooms</code>: <code>CREATE TABLE `rooms` ( `id` int NOT NULL auto_increment, `updated` timestamp NOT NULL, `created` timestamp NOT NULL, `name` varchar(64) NOT NULL default '', `password` varchar(32) NOT NULL default '', `ispublic` char(1) default NULL, `ispermanent` int(11) default NULL, PRIMARY KEY (`id`), KEY `name` (`name`), KEY `ispublic` (`ispublic`), KEY `ispermanent` (`ispermanent`), KEY `updated` (`updated`) ) WNGINW=MyISAM AUTO_INCREMENT=5 ; </code> Table structure for table <code>users</code>: <code>CREATE TABLE `users` ( `id` int NOT NULL auto_increment, `login` varchar(32) NOT NULL default '', `password` varchar(32) NOT NULL default '', `roles` int NOT NULL default '0', `profile` text, PRIMARY KEY (`id`), KEY `login` (`login`) ) ENGINE=MyISAM AUTO_INCREMENT=2 ;` </code> Comment: No create table smf_fc_bans statement? Comment: Not that I could find, no :( Comment: According to RiggsFolly's answer, `bans` is the problem table. Answer: The <code>varchar</code> datatype requires a parameter like <code>varchar(50)</code> <code>CREATE TABLE `bans` ( `id` int NOT NULL auto_increment, `created` timestamp NOT NULL, `userid` int default NULL, `banneduserid` int default NULL, `roomid` int default NULL, `ip` varchar( requires a number ) default NULL, <-- HERE KEY `id` (`id`), KEY `userid` (`userid`), KEY `created` (`created`) ) ENGINE=MyISAM; </code> You also have an error in <code>CREATE TABLE `rooms` ( `id` int NOT NULL auto_increment, `updated` timestamp NOT NULL, `created` timestamp NOT NULL, `name` varchar(64) NOT NULL default '', `password` varchar(32) NOT NULL default '', `ispublic` char(1) default NULL, `ispermanent` int(11) default NULL, PRIMARY KEY (`id`), KEY `name` (`name`), KEY `ispublic` (`ispublic`), KEY `ispermanent` (`ispermanent`), KEY `updated` (`updated`) ) WNGINW=MyISAM AUTO_INCREMENT=5 ; WNGINW=MyISAM AUTO_INCREMENT=5 ; </code> Should be <code>ENGINE=MyISAM AUTO_INCREMENT=5 ; </code> Comment: Hi there. Turned WNGINW to ENGINE and added a parameter where it was missing, but still no joy :( Also, thank you for your help! Comment: Then you cannot of saved the change when you edited the file. I assume these instructions are in a file Comment: D'oh. You were right. I hadn't saved them. It works great now. Thank you thank you for your help!<|endoftext|>Synchronization of multiple streams with Gstreamer Question: I want to learn more about synchronization of different streams with RTCP with Gstreamer. A video was divided into 4 parts vertically so that synchronization can be better observed at the receiver. Following are the codes used for sender and receiver. sender: <code>gst-launch -v \ \ gstrtpbin name=rtpbin1 \ filesrc location=/home/chinthaka/Desktop/MageHeenaye101.avi ! decodebin ! x264enc ! rtph264pay ! rtpbin1.send_rtp_sink_0 \ rtpbin1.send_rtp_src_0 ! udpsink host=192.168.1.100 port=5011 \ rtpbin1.send_rtcp_src_0 ! udpsink host=192.168.1.100 port=5012 \ udpsrc port=5013 ! rtpbin1.recv_rtcp_sink_0 \ \ gstrtpbin name=rtpbin2 \ filesrc location=/home/chinthaka/Desktop/MageHeenaye102.avi ! decodebin ! x264enc ! rtph264pay ! rtpbin2.send_rtp_sink_0 \ rtpbin2.send_rtp_src_0 ! udpsink host=192.168.1.100 port=5021 \ rtpbin2.send_rtcp_src_0 ! udpsink host=192.168.1.100 port=5022 \ udpsrc port=5023 ! rtpbin2.recv_rtcp_sink_0 \ \ gstrtpbin name=rtpbin3 \ filesrc location=/home/chinthaka/Desktop/MageHeenaye103.avi ! decodebin ! x264enc ! rtph264pay ! rtpbin3.send_rtp_sink_0 \ rtpbin3.send_rtp_src_0 ! udpsink host=192.168.1.100 port=5031 \ rtpbin3.send_rtcp_src_0 ! udpsink host=192.168.1.100 port=5032 \ udpsrc port=5033 ! rtpbin3.recv_rtcp_sink_0 \ \ gstrtpbin name=rtpbin4 \ filesrc location=/home/chinthaka/Desktop/MageHeenaye104.avi ! decodebin ! x264enc ! rtph264pay ! rtpbin4.send_rtp_sink_0 \ rtpbin4.send_rtp_src_0 ! udpsink host=192.168.1.100 port=5041 \ rtpbin4.send_rtcp_src_0 ! udpsink host=192.168.1.100 port=5042 \ udpsrc port=5043 ! rtpbin4.recv_rtcp_sink_0 </code> Receiver: <code>gst-launch -v \ videomixer name=mix ! ffmpegcolorspace ! autovideosink sync=false async=false \ \ gstrtpbin name=rtpbin1 \ udpsrc port=5011 caps = "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264, sprop-parameter-sets=(string)\"Z01AFeygbCPNLgIgAAADAC7msoAB4sWywA\\=\\=\\,aOvssg\\=\\=\", payload=(int)96, ssrc=(uint)861153369, clock-base=(uint)4026289255, seqnum-base=(uint)30449" ! rtpbin1.recv_rtp_sink_0 rtpbin1. ! rtph264depay ! queue ! ffdec_h264 ! videobox border-alpha=0 top=0 left=0 ! mix. \ udpsrc port=5012 ! rtpbin1.recv_rtcp_sink_0 \ rtpbin1.send_rtcp_src_0 ! udpsink port=5013 host=192.168.1.104 \ \ gstrtpbin name=rtpbin2 \ udpsrc port=5021 caps = "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264, sprop-parameter-sets=(string)\"Z01AFeygbCPNLgIgAAADAC7msoAB4sWywA\\=\\=\\,aOvssg\\=\\=\", payload=(int)96, ssrc=(uint)861153369, clock-base=(uint)4026289255, seqnum-base=(uint)30449" ! rtpbin2.recv_rtp_sink_0 rtpbin2. ! rtph264depay ! queue ! ffdec_h264 ! videobox border-alpha=0 top=-120 left=0 ! mix. \ udpsrc port=5022 ! rtpbin2.recv_rtcp_sink_0 \ rtpbin2.send_rtcp_src_0 ! udpsink port=5023 host=192.168.1.104 \ \ gstrtpbin name=rtpbin3 \ udpsrc port=5031 caps = "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264, sprop-parameter-sets=(string)\"Z01AFeygbCPNLgIgAAADAC7msoAB4sWywA\\=\\=\\,aOvssg\\=\\=\", payload=(int)96, ssrc=(uint)861153369, clock-base=(uint)4026289255, seqnum-base=(uint)30449" ! rtpbin3.recv_rtp_sink_0 rtpbin3. ! rtph264depay ! queue ! ffdec_h264 ! videobox border-alpha=0 top=-240 left=0 ! mix. \ udpsrc port=5032 ! rtpbin3.recv_rtcp_sink_0 \ rtpbin3.send_rtcp_src_0 ! udpsink port=5033 host=192.168.1.104 \ \ gstrtpbin name=rtpbin4 \ udpsrc port=5041 caps = "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264, sprop-parameter-sets=(string)\"Z01AFeygbCPNLgIgAAADAC7msoAB4sWywA\\=\\=\\,aOvssg\\=\\=\", payload=(int)96, ssrc=(uint)861153369, clock-base=(uint)4026289255, seqnum-base=(uint)30449" ! rtpbin4.recv_rtp_sink_0 rtpbin4. ! rtph264depay ! queue ! ffdec_h264 ! videobox border-alpha=0 top=-360 left=0 ! mix. \ udpsrc port=5042 ! rtpbin4.recv_rtcp_sink_0 \ rtpbin4.send_rtcp_src_0 ! udpsink port=5043 host=192.168.1.104 </code> I can receive the 4 videos in the same video, but synchronization of each streams is not perfect. I just used the same caps for all the receivers. Just found out that caps generated at each time is different at the sender. Is there a good way to send the caps generated to the receiver so that same caps can be used at the receiver? Is there any best way to synchronize multiple streams using RTCP? Here different ports are used for different RTP and RTCP sessions. Is it advisable or should I use only two ports, one for RTP and one for RTCP. Please kindly advice. I am quite new to the Gstreamer and trying my best to get familiar with the synchronization. Answer: I would strongly advise you to start doing this in code instead. launch-lines are great for prototyping, but when it comes to fine-grained control like synchronization, you should be using code instead. GStreamers rtpbin handles RTCP sync beautifully. If two or more streams have the same cname, it will calculate (using RTCP) the relative timestamp differences between these streams as seen on the sender-side, and then replicate this on the receiver using gstrtpjitterbuffers ts-offset. In theory, if your media was synchronized when it was sent, you should be able to render it synchronized at the receiver as well.
[{"idx": "FlashChat_installation_hiccup!_SQL_syntax_error?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-16148.jsonl"}, {"idx": "Synchronization_of_multiple_streams_with_Gstreamer", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-16148.jsonl"}]
import { Constraints } from './../../models/constraints'; import { StorageKeys } from './../../utils/storage-keys'; import { Component, ViewChild } from '@angular/core'; import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular'; import { TranslateService } from '@ngx-translate/core'; import { Storage } from '@ionic/storage'; import { CapsuleComponent } from '../../components/capsule/capsule'; import { Subject } from '../../models/subject'; import { FormatterUtils } from './../../utils/formatter'; import { SubjectsProvider } from './../../providers/subjects/subjects'; @IonicPage() @Component({ selector: 'page-define-constraints', templateUrl: 'define-constraints.html', }) export class DefineConstraintsPage { placeholder = this.translate.instant('NAME_OR_CODE'); step: string = '1'; private button: string = this.step == "3" ? this.translate.instant('GENERATE_TIME_GRID') : this.translate.instant('NEXT_STEP'); private periodsSelected: string[] = []; private subjectsWanted: Subject[] = []; private subjectsExcluded: Subject[] = []; @ViewChild(CapsuleComponent) capsuleComponent; busca: string; private subjects; credits = { lower: 20, upper: 30 } equivalent = true; constructor(public navCtrl: NavController, public navParams: NavParams, public alertCtrl: AlertController, public translate: TranslateService, private subjectsProvider: SubjectsProvider, private storage: Storage) { } ionViewDidLoad() { this.storage.get(StorageKeys.RESULT).then((val) => { if (val) { this.navCtrl.push('ResultPage'); } }); this.storage.get(StorageKeys.ALL_SUBJECTS).then((val) => { if (val) { this.subjects = val; } }); this.subjectsProvider.allSubjects() .map(res => res.json()) .subscribe(res => { if (res.success) { this.subjects = res.result.subjects; this.storage.set(StorageKeys.ALL_SUBJECTS, this.subjects); } }, err => { console.error('ERROR', err); }); } ionViewWillEnter(){ this.step == '1'; } onPeriodSelected(event: string[]) { this.periodsSelected = event; } searchSubject(): void { this.doCheckbox(this.busca); } getClass(step: string): string { if (this.step == step) { return "step"; } else { return "step step-hidden"; } } onStepChanged(event: any): void { this.button = this.step == "3" ? this.translate.instant('GENERATE_TIME_GRID') : this.translate.instant('NEXT_STEP'); } btnNextStepClicked(): void { if (this.step == '3') { let constraints: Constraints = this.createConstraints(); this.storage.set(StorageKeys.CONSTRAINT, constraints); this.navCtrl.push('ResultPage'); } else { this.step = (Number(this.step) + 1).toString(); } } createConstraints(): Constraints { let periods: number[] = []; if (this.periodsSelected.indexOf(this.translate.instant('MORNING')) > -1) { periods.push(0); } if (this.periodsSelected.indexOf(this.translate.instant('AFTERNOON')) > -1) { periods.push(1); } if (this.periodsSelected.indexOf(this.translate.instant('NIGHT')) > -1) { periods.push(2); } let subjectsWantedCode: string[] = []; this.subjectsWanted.forEach(s => subjectsWantedCode.push(s.codigo)); let subjectsNotWantedCode: string[] = []; this.subjectsExcluded.forEach(s => subjectsNotWantedCode.push(s.codigo)); return new Constraints(periods, this.credits.lower, this.credits.upper, this.equivalent, subjectsWantedCode, subjectsNotWantedCode); } getPeriods(): string[] { let periods: string[] = []; periods.push(this.translate.instant('MORNING')); periods.push(this.translate.instant('AFTERNOON')); periods.push(this.translate.instant('NIGHT')); return periods; } getSubjectsWanted() { return this.subjectsWanted; } getSubjectsExcluded() { return this.subjectsExcluded; } doCheckbox(search: string) { let alert = this.alertCtrl.create(); alert.setTitle(this.translate.instant('SELECT_SUBJECT')); let subjects: Subject[] = this.getPossibleSubjects(); subjects.forEach(s => { alert.addInput({ type: 'checkbox', label: s.codigo + " - " + s.nome, value: s.codigo }) }) alert.addButton(this.translate.instant('BACK_BUTTON_TEXT')); alert.addButton({ text: 'Ok', handler: (data: any) => { this.busca = ""; if (data) { data.forEach(element => { console.log(element); if (this.step == '2') { this.subjectsWanted.push(this.getSubjectByCode(element)); } else if (this.step == '3') { this.subjectsExcluded.push(this.getSubjectByCode(element)); } }); } } }); alert.present(); } getSubjectByCode(code: string): Subject { for (let i in this.subjects) { let subject: Subject = this.subjects[i]; if (subject.codigo == code) { return subject; } } return undefined; } getPossibleSubjects(): Subject[] { let subjects: Subject[] = []; for (let i in this.subjects) { let subject: Subject = this.subjects[i]; let nome: string = subject.nome; let codigo: string = subject.codigo; if (this.contains(nome, this.busca) || this.contains(codigo, this.busca)) { subjects.push(subject); } } return subjects; } contains(a: string, b: string): boolean { return FormatterUtils.replaceSpecialChars(a).includes(FormatterUtils.replaceSpecialChars(b)); } }<|endoftext|>import Encoder from '../../lib/core/versions/latest/Encoder'; import ErrorCode from '../../lib/core/versions/latest/ErrorCode'; import JasmineSidetreeErrorValidator from '../JasmineSidetreeErrorValidator'; import Jwk from '../../lib/core/versions/latest/util/Jwk'; import OperationGenerator from '../generators/OperationGenerator'; import OperationType from '../../lib/core/enums/OperationType'; import RecoverOperation from '../../lib/core/versions/latest/RecoverOperation'; import SidetreeError from '../../lib/common/SidetreeError'; describe('RecoverOperation', async () => { describe('parse()', async () => { it('parse as expected', async (done) => { const [, recoveryPrivateKey] = await Jwk.generateEs256kKeyPair(); const [newRecoveryPublicKey] = await Jwk.generateEs256kKeyPair(); const [newSigningPublicKey] = await OperationGenerator.generateKeyPair('singingKey'); const recoverOperationRequest = await OperationGenerator.generateRecoverOperationRequest( 'unused-DID-unique-suffix', recoveryPrivateKey, newRecoveryPublicKey, newSigningPublicKey ); const operationBuffer = Buffer.from(JSON.stringify(recoverOperationRequest)); const result = await RecoverOperation.parse(operationBuffer); expect(result).toBeDefined(); done(); }); it('should throw if operation type is incorrect', async (done) => { const [, recoveryPrivateKey] = await Jwk.generateEs256kKeyPair(); const [newRecoveryPublicKey] = await Jwk.generateEs256kKeyPair(); const [newSigningPublicKey] = await OperationGenerator.generateKeyPair('singingKey'); const recoverOperationRequest = await OperationGenerator.generateRecoverOperationRequest( 'unused-DID-unique-suffix', recoveryPrivateKey, newRecoveryPublicKey, newSigningPublicKey ); recoverOperationRequest.type = OperationType.Create; // Intentionally incorrect type. const operationBuffer = Buffer.from(JSON.stringify(recoverOperationRequest)); await expectAsync(RecoverOperation.parse(operationBuffer)).toBeRejectedWith(new SidetreeError(ErrorCode.RecoverOperationTypeIncorrect)); done(); }); it('should throw if didUniqueSuffix is not string.', async (done) => { const [, recoveryPrivateKey] = await Jwk.generateEs256kKeyPair(); const [newRecoveryPublicKey] = await Jwk.generateEs256kKeyPair(); const [newSigningPublicKey] = await OperationGenerator.generateKeyPair('singingKey'); const recoverOperationRequest = await OperationGenerator.generateRecoverOperationRequest( 'unused-DID-unique-suffix', recoveryPrivateKey, newRecoveryPublicKey, newSigningPublicKey ); (recoverOperationRequest.didSuffix as any) = 123; // Intentionally incorrect type. const operationBuffer = Buffer.from(JSON.stringify(recoverOperationRequest)); await expectAsync(RecoverOperation.parse(operationBuffer)).toBeRejectedWith(new SidetreeError(ErrorCode.RecoverOperationMissingOrInvalidDidUniqueSuffix)); done(); }); }); describe('parseObject()', async () => { it('should throw if operation contains an additional unknown property.', async () => { const recoverOperation = { type: OperationType.Recover, didSuffix: 'unusedSuffix', revealValue: 'unusedReveal', signedData: 'unusedSignedData', delta: 'unusedDelta', extraProperty: 'thisPropertyShouldCauseErrorToBeThrown' }; await JasmineSidetreeErrorValidator.expectSidetreeErrorToBeThrownAsync( () => RecoverOperation.parseObject(recoverOperation, Buffer.from('unused')), ErrorCode.InputValidatorInputContainsNowAllowedProperty, 'recover request' ); }); it('should throw if hash of `recoveryKey` does not match the revealValue.', async () => { const didUniqueSuffix = OperationGenerator.generateRandomHash(); const [, recoveryPrivateKey] = await Jwk.generateEs256kKeyPair(); const recoverOperationData = await OperationGenerator.generateRecoverOperation({ didUniqueSuffix, recoveryPrivateKey }); const recoverRequest = JSON.parse(recoverOperationData.operationBuffer.toString()); // Intentionally have a mismatching reveal value. recoverRequest.revealValue = OperationGenerator.generateRandomHash(); await JasmineSidetreeErrorValidator.expectSidetreeErrorToBeThrownAsync( () => RecoverOperation.parseObject(recoverRequest, Buffer.from('unused')), ErrorCode.CanonicalizedObjectHashMismatch, 'recover request' ); }); }); describe('parseSignedDataPayload()', async () => { it('should throw if signedData contains an additional unknown property.', async (done) => { const nextRecoveryCommitmentHash = OperationGenerator.generateRandomHash(); const signedData = { deltaHash: 'anyUnusedHash', recoveryKey: 'anyUnusedRecoveryKey', nextRecoveryCommitmentHash, extraProperty: 'An unknown extra property', revealValue: 'some value' }; const encodedSignedData = Encoder.encode(JSON.stringify(signedData)); await expectAsync(RecoverOperation.parseSignedDataPayload(encodedSignedData)) .toBeRejectedWith(new SidetreeError(ErrorCode.RecoverOperationSignedDataMissingOrUnknownProperty)); done(); }); it('should throw if signedData missing property.', async (done) => { const signedData = { }; const encodedSignedData = Encoder.encode(JSON.stringify(signedData)); await expectAsync(RecoverOperation.parseSignedDataPayload(encodedSignedData)) .toBeRejectedWith(new SidetreeError(ErrorCode.RecoverOperationSignedDataMissingOrUnknownProperty)); done(); }); }); });
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3832.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-3832.jsonl"}]
# Predeclare global variable names use vars qw ( $dev $ping_before_scan $proto $first_community $community $os_guess $print_ftptp $ftps $timeout $udpscan $PortCount $cock $SNMP_STAT $second_community $timeout $size $sp $ep $snmp $malmode $tast $sweepex $ping $btimeout $oids $snmp_timeout $snmp_port $malware $msg $uproto $telnet @line $print_telnet $telnet_socket $src $daddr $sport $dport $Count $fuck $vendors $offset $packet $synscan $syn_scan $ftpp $ftpt $verbose $sweep $pv $services @common $ovr $PRV); $pv[0]=$sp; $pv[1]=$ep; print "[i] Please read the documentation before using this function," if $malmode; print "\n so there is no misunderstanding\n" if $malmode; # Time format my ($sec,$min,$hour,$mday,$mon,$year,$wday, $yday,$isdst)=localtime(time); # Trigger subnet discovery and exit if ($sweep) { if ($sweepex) { printf "Starting NetBIOS subnet discovery @ %4d-%02d-%02d %02d:%02d:%02d\n", $year+1900,$mon+1,$mday,$hour,$min,$sec; } else { printf "Starting subnet discovery @ %4d-%02d-%02d %02d:%02d:%02d\n", $year+1900,$mon+1,$mday,$hour,$min,$sec; } my @hosts; my $HostCount = 0; $hosts[0] = $sp; $hosts[1] = $ep; if ($sweepex) { printf("%-15s %-18s %-10s %-13s\n", 'IP ADDRESS', 'MAC ADDRESS', 'DOMAIN', 'NETBIOS NAME'); } else { printf("%-15s %-8s\n", 'IP ADDRESS', 'PACKET RETURN TIME'); } for ($sp; $sp <= $ep; $sp++) { $ip = "$host$sp"; $p = Net::Ping->new($proto, $timeout, $size); $p->hires(); ($ret, $duration, $ip) = $p->ping($ip, 1); if ($ret) { if ($sweepex) { $HostCount++; my $nb = Net::NBName->new; my $ns = $nb->node_status($ip); if ($ns) { for my $rr ($ns->names) { if ($rr->suffix == 0 && $rr->G eq "GROUP") { $domain = $rr->name; } if ($rr->suffix == 0 && $rr->G eq "UNIQUE") { $machine = $rr->name unless $rr->name =~ /^IS~/; } } $mac_address = $ns->mac_address; } printf("%-15s %-18s %-10s %-13s\n", $ip,$mac_address,$domain,$machine); } else { $HostCount++; printf("%-15s %.8f ms\n", $ip, 1000 * $duration); } } } my $scanned = $hosts[1]-$hosts[0]+1; print "$HostCount/$scanned scanned machines up & running on subnet\n"; if ($scanned <= '1') { print "\nScan completed: [$scanned] host scanned in "; } else { print "\nScan completed: [$scanned] hosts scanned in "; } $etime = time(); $elapsed_time = $etime-$^T; printf("%.2f seconds\n", $elapsed_time); exit; } print "[i] Verbose mode activated\n" if $verbose; # Check if host(s) is alive if ($ping =~ "TRUE") { printf "Starting ping sequence @ %02d:%02d:%02d\n", $hour,$min,$sec if $verbose; $ip = $host; $p = Net::Ping->new(); $p->hires(); ($ret, $duration, $ip) = $p->ping($ip, 5.5); printf("$host [ip: $ip] is alive (packet return time: %.2f ms)\n", 1000 * $duration) if $ret; $p->close(); if (!$ret) { my $HTTP = new IO::Socket::INET ( Timeout => 1, PeerAddr => $host, PeerPort => 80, Proto => "tcp"); my $FTP = new IO::Socket::INET ( Timeout => 1, PeerAddr => $host, PeerPort => 21, Proto => "tcp") unless $HTTP; my $SMTP = new IO::Socket::INET ( Timeout => 1, PeerAddr => $host, PeerPort => 25, Proto => "tcp") unless $HTTP && $FTP; close $HTTP; close $FTP; close $SMTP; if ($HTTP || $FTP || $SMTP) { print "NOTE: [ip: $ip] is currently blocking ($proto) ping probes\n"; } else { print "[!] [host: $host] is not responding\n"; print "[i] If it is blocking ping probes, "; print "(TCP 21/25/80 closed) try forced mode [-f]\n"; print "\nScan completed: [1] host scanned in "; $etime = time(); $elapsed_time = $etime-$^T; printf("%.2f seconds\n", $elapsed_time); exit; } } printf "Ping sequence ended @ %02d:%02d:%02d\n", $hour,$min,$sec if $verbose; } # Display scan type my $type; if ($synscan == 0 && $malmode == 0 && $PRV) { $type = "chronological connect()"; } elsif ($synscan == 0 && $malmode == 0) { $type = "common connect()"; } elsif ($synscan == 0 && $malmode) { $type = "(common) malware connect()"; } elsif ($synscan && $malmode == 0) { $type = "chronological stealth"; } printf "Starting $type scan @ %02d:%02d:%02d\n", $hour,$min,$sec if $verbose; # Initiate TCP SYN scan if requested # Common ports connect() scan (PRV: Port Range Value) if ($synscan == 0 && $PRV == 0 && $host =~ /^.+\..+\..+$/) { print "Interesting ports on $host:\n"; printf("%-8s %-6s %-8s\n", 'PORT NR','STATE','SERVICE'); foreach $sp (@common) { my $COMMON = new IO::Socket::INET ( Timeout => 1, PeerAddr => $host, PeerPort => $sp, Proto => "tcp"); if ($COMMON) { if ($malmode) { printf("%-8s %-7s %-8s\n", $sp, 'active', $malware{$sp}) if $malware{$sp}; } else { printf ("%-8s %-6s %-8s\n", $sp, 'open', $services{$sp}); } } } } # Threaded full connect scan in port range elsif ($synscan == 0) { if ($malmode) { print "Possible threats found on $host:\n"; printf("%-8s %-7s %-8s\n", 'PORT NR', 'STATE', 'THREAT'); } else { print "Interesting ports on $host:\n"; printf("%-8s %-6s %-8s\n", 'PORT NR', 'STATE', 'SERVICE'); } $| = 1; my $parent = 0; my @children = (); FORK: for ($sp; $sp <= $ep; $sp++) { my $oldpid = $$; my $pid = fork; if (not defined $pid) { if ($! =~ /Resource temporarily unavailable/) { &DoReap; $sp --; } else { die "[ERR]: Can't fork: $!\n"; } } elsif ($pid == 0) { $parent = $oldpid; @children = (); last FORK; } else { push @children, $pid; } } if ($parent) { my $socket; my $success = eval { $socket = IO::Socket::INET->new( PeerAddr => $host, PeerPort => $sp, Timeout => $timeout, Proto => 'tcp' ) }; # If port is open: perform database lookup # and display port nr if ($success) { if ($malmode) { printf("%-8s %-7s %-8s\n", $sp, 'active', $malware{$sp}) if $malware{$sp}; } else { # open (TEMP, ">>temp.zapfort"); # printf TEMP ("%-8s %-6s %-8s\n", $sp, 'open', $services{$sp}); # close (TEMP); printf ("%-8s %-6s %-8s\n", $sp, 'open', $services{$sp}); } shutdown($socket, 2); exit; } exit 0; } else { #If we're not the kid, we're the parent. Do a reap. &DoReap; } #This sub is the reaper. sub DoReap { while (my $child = shift @children) { waitpid $child, 0; } } } # If not in stealth mode unless ($synscan == 0 && ($PRV == 0) && $host =~ /^.+\..+\..+$/) { # Check for anonymous FTP access if (($ftps = Net::FTP->new($host, Port => $ftpp, Timeout => $ftpt, Debug => 0)) && ($ftps->login("anonymous",'none@none'))) { print "[!/02]: Anonymous FTP access found on port \"$ftpp\"\n"; if ($ftps->dir()) { print "\tSuccessfully performed directory listing\n"; } if ($ftps->mkdir("719967600")) { print "\tSuccessfully created directory\n"; } if ($ftps->rmdir("719967600")) { print "\tSuccessfully removed directory\n"; } if ($ftps->cdup()) { print "\tSuccessfully moved up 1 directory\n\tPWD output: "; } if ($ftps->pwd()) { print $ftps->message; } } # Perform NetBIOS lookup my $nb = Net::NBName->new; # a unicast node status request my $ns = $nb->node_status($host); if ($ns) { for my $rr ($ns->names) { if ($rr->suffix == 0 && $rr->G eq "GROUP") { $domain = $rr->name; } if ($rr->suffix == 3 && $rr->G eq "UNIQUE") { $user = $rr->name; } if ($rr->suffix == 0 && $rr->G eq "UNIQUE") { $machine = $rr->name unless $rr->name =~ /^IS~/; } } print "[!/01]: NetBIOS may be leaking (sensitive) system information:\n"; print "\tSystem [DOMAIN\\NAME USER]: $domain\\$machine $user\n"; } # SNMP OID:s for: # System name, system description & system uptime @oids=("1.3.6.1.2.1.1.5.0","1.3.6.1.2.1.1.1.0", "1.3.6.1.2.1.1.3.0"); # Open SNMP(v1) socket for first community string my ($session, $error) = Net::SNMP->session( -hostname => shift || $host, -community => shift || $community, -version => shift || 1, -timeout => shift || $snmp_timeout, -port => shift || $snmp_port ); if ($session) { $oids = $session->var_bind_list; my $rfc_version = $session->version; my $SNMPv; if ($rfc_version == "0") { $SNMPv = "v1"; } elsif ($rfc_version == "1") { $SNMPv = "v2c";} else { $SNMPv = "v3"; } my $result = $session->get_request( -varbindlist => \@oids ); if ($result) { print "[!/03]: Vulnerable SNMP($SNMPv) service found\n\tcommunity string is \"$community\"\n"; printf("\tObtained system name: %s\n", $result->{$oids[0]}); printf("\tObtained system description/OS: %s\n", $result->{$oids[1]}); printf("\tObtained system uptime: %s\n", $result->{$oids[2]}); $session->close; } } # Attempt to receive MAC address through NetBIOS, # convert format for vendor database lookup my $nb_mac = Net::NBName->new; my $ns_mac = $nb_mac->node_status($host); if ($ns_mac) { my $mac = $ns->mac_address; my $amount = ($mac =~ s/-/:/g); my $mac_address = $mac; $mac =~ (s/[-:]//g); if (length $mac > 6) { $mac = substr($mac,0,6); } my $vendor = $vendors{uc $mac}; print "MAC Address: $mac_address ($vendor)\n"; } } my $calc = (($pv[1]-$pv[0])/65535)*100; if (($malmode) && ($calc <= 50)) { printf("NOTE: only about %.2f percent of the host was scanned\n", $calc); print "[i] To perform a full scan, set the port range to 1-65535\n"; } # Finally display success and elapsed scan time print "\nScan completed: [1] host scanned in "; $etime = time(); $elapsed_time = $etime-$^T; printf("%.2f seconds\n", $elapsed_time);<|endoftext|># # Handles Rest API requests to State Rest API in cluster controller, making # wanted data programmatically available. # package Yahoo::Vespa::ClusterController; use strict; use warnings; use Class::Struct; use Yahoo::Vespa::ArgParser; use Yahoo::Vespa::ClusterState; use Yahoo::Vespa::ConsoleOutput; use Yahoo::Vespa::Http; use Yahoo::Vespa::Json; use Yahoo::Vespa::Utils; use Yahoo::Vespa::VespaModel; BEGIN { # - Exports and aliases for the module use base 'Exporter'; our $VERSION = '1.0'; our @EXPORT = qw( detectClusterController getContentClusterState setNodeUserState ); # Exported unless specifically left out by user # Alias namespaces *VespaModel:: = *Yahoo::Vespa::VespaModel:: ; *Http:: = *Yahoo::Vespa::Http:: ; *Json:: = *Yahoo::Vespa::Json:: ; } struct( ClusterController => { index => '$', # Logical index of the cluster controller host => '$', # Host on which cluster controller runs port => '$' # Port where cluster controller is available }); my %CACHED_CLUSTER_STATES; my @CLUSTER_CONTROLLERS; return &init(); ########################## Default exported functions ######################## sub init { %CACHED_CLUSTER_STATES = (); @CLUSTER_CONTROLLERS = (); return 1; } sub detectClusterController { # () if (scalar @CLUSTER_CONTROLLERS == 0) { use Yahoo::Vespa::VespaModel; printDebug "Attempting to auto-detect cluster controller location\n"; my $sockets = VespaModel::getSocketForService( type => 'container-clustercontroller', tag => 'state'); foreach my $sock (sort { $a->{'index'} <=> $b->{'index'} } @$sockets) { my $cc = new ClusterController; $cc->index($sock->{'index'}); $cc->host($sock->{'host'}); $cc->port($sock->{'port'}); push @CLUSTER_CONTROLLERS, $cc; } if (scalar @$sockets == 0) { my $oldVal = enableAutomaticLineBreaks(0); printSpam dumpStructure(VespaModel::get()); enableAutomaticLineBreaks($oldVal); printError "Failed to detect cluster controller to talk to. " . "Resolve issue that failed automatic detection or " . "provide cluster controller socket through command " . "line options. (See --help)\n"; exitApplication(1); } &showSettings(); printSpam "Content of vespa model inspected to find cluster " . "controller:\n"; my $oldVal = enableAutomaticLineBreaks(0); printSpam dumpStructure(VespaModel::get()); enableAutomaticLineBreaks($oldVal); } } sub setNodeUserState { # (ClusterName, NodeType, Index, State, Reason, NoWait, SafeMode) my ($cluster, $service, $index, $state, $reason, $no_wait, $safe_mode) = @_; my @params = (); my @headers = ( 'Content-Type' => 'application/json' ); $state =~ tr/A-Z/a-z/; $state =~ /(?:up|down|maintenance|retired)$/ or confess "Invalid state '$state' attempted set.\n"; if (!defined $reason) { $reason = ""; } my $request = { "state" => { "user" => { "state" => $state, "reason" => $reason } } }; if ($no_wait) { $request->{'response-wait'} = 'no-wait'; } if ($safe_mode) { $request->{'condition'} = 'safe'; } my $content = Json::encode($request); my $path = &getPathToNode($cluster, $service, $index); my %response = &requestCC('POST', $path, \@params, $content, \@headers); if (defined $response{'all'}) { printSpam $response{'all'}; } printDebug $response{'code'} . " " . $response{'status'} . "\n"; printInfo exists($response{'content'}) ? $response{'content'} : ''; if ($response{'code'} >= 200 && $response{'code'} < 300) { printResult "$response{'status'}\n"; return 1 } else { printWarning "Failed to set node state for node " . "$cluster/$service/$index: " . "$response{'code'} $response{'status'}\n"; return 0 } } sub getContentClusterState { # (ClusterName) -> ClusterState my ($cluster) = @_; if (!exists $CACHED_CLUSTER_STATES{$cluster}) { $CACHED_CLUSTER_STATES{$cluster} = &fetchContentClusterState($cluster); } return $CACHED_CLUSTER_STATES{$cluster}; } ######################## Externally usable functions ####################### sub getClusterControllers { # () return \@CLUSTER_CONTROLLERS; } sub showSettings { # () printDebug "Cluster controllers:\n"; foreach my $cc (@CLUSTER_CONTROLLERS) { printDebug " " . $cc->index . ": " . $cc->host . ":" . $cc->port . "\n"; } } ############## Utility functions - Not intended for external use ############# sub fetchContentClusterState { # (ClusterName) -> ClusterState my ($cluster) = @_; my @params = ( 'recursive' => 'true' ); my %response = &getCC("/cluster/v2/$cluster/", \@params); if ($response{'code'} != 200) { printError "Failed to fetch cluster state of content cluster " . "'$cluster':\n" . $response{'all'} . "\n"; exitApplication(1); } my $json = Json::parse($response{'content'}); my $result = new ClusterState; &fillInGlobalState($cluster, $result, $json); &fillInNodes($result, 'distributor', &getJsonValue($json, ['service', 'distributor', 'node'])); &fillInNodes($result, 'storage', &getJsonValue($json, ['service', 'storage', 'node'])); return $result; } sub fillInGlobalState { # (ClusterName, StateToFillIn, JsonToParse) my ($cluster, $state, $json) = @_; my $e = &getJsonValue($json, ['state', 'generated', 'state']); if (defined $e) { $state->globalState($e); if (!Yahoo::Vespa::ClusterState::legalState($state->globalState())) { printWarning "Illegal global cluster state $e found.\n"; } } else { printDebug dumpStructure($json) . "\n"; printWarning "Found no global cluster state\n"; } } sub getPathToNode { # (ClusterName, NodeType, Index) my ($cluster, $service, $index) = @_; return "/cluster/v2/$cluster/$service/$index"; } sub listContentClusters { # () -> (ContentClusterName, ...) my %result = &getCC("/cluster/v2/"); if ($result{'code'} != 200) { printError "Failed to fetch list of content clusters:\n" . $result{'all'} . "\n"; exitApplication(1); } my $json = Json::parse($result{'content'}); return keys %{ $json->{'cluster'} }; } sub fillInNodes { # (StateToFillIn, ServiceType, json) my ($state, $service, $json) = @_; foreach my $index (%{ $json }) { my $node = new Node; &parseNode($node, $json->{$index}); $state->$service($index, $node); } } sub parseNode { # (StateToFillIn, JsonToParse) my ($node, $json) = @_; my $group = &getJsonValue($json, ['attributes', 'hierarchical-group']); if (defined $group && $group =~ /^[^\.]*\.(.*)$/) { $node->group($1); } parseState($node, $json, 'unit'); parseState($node, $json, 'generated'); parseState($node, $json, 'user'); my $partitions = $json->{'partition'}; if (defined $partitions) { foreach my $index (%{ $json->{'partition'} }) { my $partition = new Partition; parsePartition($partition, $json->{'partition'}->{$index}); $node->partition($index, $partition); } } } sub parsePartition { # (StateToFillIn, JsonToParse) my ($partition, $json) = @_; my $buckets = &getJsonValue($json, ['metrics', 'bucket-count']); my $doccount = &getJsonValue($json, ['metrics', 'unique-document-count']); my $size = &getJsonValue($json, ['metrics', 'unique-document-total-size']); $partition->bucketcount($buckets); $partition->doccount($doccount); $partition->totaldocsize($size); } sub parseState { # (StateToFillIn, JsonToParse, StateType) my ($node, $json, $type) = @_; my $value = &getJsonValue($json, ['state', $type, 'state']); my $reason = &getJsonValue($json, ['state', $type, 'reason']); if (defined $value) { my $state = new State; $state->state($value); $state->reason($reason); $state->source($type); $node->$type($state); } } sub getJsonValue { # (json, [ keys ]) my ($json, $keys) = @_; foreach my $key (@$keys) { if (!defined $json) { return; } $json = $json->{$key}; } return $json; } sub getCC { # (Path, Params, Headers) -> Response my ($path, $params, $headers) = @_; return requestCC('GET', $path, $params, undef, $headers); } sub requestCC { # (Type, Path, Params, Content, Headers) -> Response my ($type, $path, $params, $content, $headers) = @_; my %response; foreach my $cc (@CLUSTER_CONTROLLERS) { %response = Http::request($type, $cc->host, $cc->port, $path, $params, $content, $headers); if ($response{'code'} == 200) { return %response; } elsif ($response{'code'} == 307) { my %headers = $response{'headers'}; my $masterlocation = $headers{'Location'}; if (defined $masterlocation) { if ($masterlocation =~ / http:\/\/([^\/:]+):(\d+)\//) { my ($host, $port) = ($1, $2); return Http::request($type, $host, $port, $path, $params, $content, $headers); } else { printError("Unhandled relocaiton URI '$masterlocation'."); exitApplication(1); } } } } return %response; }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-10702.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-10702.jsonl"}]
Are cosmological distances additive? Question: If we observe two galaxies that are diametrically opposed from the Earth, and each $1000\,{\rm ly}$ away from the Earth, is the separation distance between the galaxies $2000\,{\rm ly}$? Really the question is: if the galaxies were separated from Earth by $10\,{\rm Gly}$ each, then would their separation be $20\,{\rm Gly}$? Answer: For nearby distances, yes, you can just add them up in the usual way. (Of course, if two galaxies are just a few thousand light-years apart, then they're right on top of each other -- galaxies are much bigger than 1000 light-years!) For large distances (i.e., distances comparable to the Hubble length, as in your last example), you have to be careful. The best answer is that there is no unique, well-defined notion of distance over such large distances. On cosmological distances, spacetime is curved, and what that means is that there are no inertial reference frames covering these large distances. Different people may choose different (non-inertial) reference frames, and as a result they'll disagree about the distance, but no one is necessarily "right." When people talk about the distance to a faraway galaxy, they most often mean distance as measured in a particular coordinate system, namely comoving coordinates, with distances evaluated at the present (cosmic) time. With that specific definition, the answer to your question is yes: two galaxies that are 10 Gly from earth in opposite directions are 20 Gly from each other. Comment: Btw. @jormansandoval You might consider accepting Ted Bunns answer if you liked it, so he can get proper rep for it. Comment: true. I put "1000ly" just do the question. but in reality the question is: if the above situation is true, someone who is in the galaxy "A", could see the galaxy, "B"? Comment: The answer to that is that it depends! It depends on the distances you're talking about, and on when the observer is trying to look. In general, the maximum distance an observer can see at any given time depends not just on the age of the Universe at that time, but also on what the expansion rate was like as a function of time in the past. You can see further than you might naively expect (i.e., if the Universe is 14 Gyr old today, you can see further than 14 Gly), simply because, at the time the light left on its way to you, the distances were smaller. Comment: (continuing ...) But it's certainly true that there are some objects so far away that we can't see them now. And it's possible to find a pair of galaxies, in opposite directions on the sky, that are visible from Earth but which are too far from each other to be visible to each other at the present time. To explore the relation between ages and distances, you might want to play around with Ned Wright's cosmology calculator, [IDX] . To get the maximum distance you can see, plug in very large values of z (the maximum distance is really $z=\infty$). Comment: In your last sentence, don't you mean that two galaxies that each are 10 Glyr away from us in opposite directions are *20* Glye apart, not *10* Glyr apart...?<|endoftext|>no reconoce el else Question: al ingresar un numero tanto sea flotante o entero siempre me dice que es entero no entiendo porque: <code>import cmath numero= float(input("introduce el numero a evaluar: ")) resultado=cmath.sqrt(numero) #esta parte final no me sale if numero!= float: print("este numero es entero") else: print("este numero es imaginario") print(f"el resultado es: {numero} es: {resultado:.4}") </code> Comment: El problema esta en la validación, intenta usar `if type(numero) is not float` Comment: El fallo está en el condicional, has de poner type(numero) != float Comment: eh, numero recibe un cast a float de algo. ¿Seguro que eso alguna vez no será float? Comment: la idea es que reconozca y del el mensaje que es flotante o entero previo al dar el resultado Comment: Otra opción puede ser `if isinstance(numero, float)` Comment: estás diciendo `numero = float(**alguna cosa**)`. Eso siempre va a ser float, a menos que lance un `ValueError`, no? Comment: por qué contestan la pregunta en los comentarios? Answer: La verificación que requires debe ser a tráves de las built-in functions type o isinstance. Ahora, la respuesta al efecto que estas teniendo en tu programa se debe a: <code>numero= float(input("introduce el numero a evaluar: "))</code> La verificación del tipo después de esta instrucción no tiene mucho sentido, el resultado devuelto por la built-in function <code>float</code> siempre sera un objeto de tipo float, en caso de no poder ser convertido a un valor flotante, este arrojará una excepción de tipo <code>ValueError</code>. <code>if numero!= float:</code>. Como se ha explicado anteriormente, si el programa llega hasta esta línea en la ejecución significa que la línea anterior no lanzó una excepción de tipo ValueError y el tipo de la variable numero siempre sera float, sin embargo estas comparando el valor de una variable con el el tipo float, esto claramente siempre va ser falso, lo que tu realmente necesitas es comparar el tipo de la variable, no el valor de la variable como tal. La solución a este problema puede ser variado, en general estas son algunas formas de comparar que un variable es de tipo float: <code>if type(numero) is float:</code> <code>if type(number) == float:</code> <code>if isinstance(number, float):</code> Nota que la primera forma y la segunda pueden parecer muy parecidas y marcar las diferencias puede demandar un poco más de conocimiento con respecto a los operadores <code>is</code>y <code>==</code> en python, ademas de una noción esencial del Singleton Pattern. Marcando los anteriores aspectos también es importante que consideres todas las ramificaciones de los tipos numéricos de python, en tu ejemplo la lógica para determinar que es un entero no es del todo acertada, algo más acorde a tu idea inicial seria: <code>if not isinstance(numero, float): print("este numero es entero o un imaginario") else: print("este numero es flotante") </code> Otra forma de expresarlo sería: <code>if type(numero) in (int, complex): print("este numero es entero o un imaginario") else: print("este numero es flotante") </code><|endoftext|>Flexbox align-content not aligning Question: So this is the scenario, I have some containers within containers. I cannot get the flexbox to use <code>space-between</code>. Let's say we have a container that looks something like: <code>.flex-container { display: flex; height: 150px; width: 150px; background-color: aqua; border: 2px solid black; flex-direction: column; } .sub-container { display: flex; margin: 5px; background-color: #fff; border: 2px solid black; flex-basis: 50px; align-content: space-between; } .item { flex-basis: 25px; margin: 3px; border: 1px solid black; background-color: green; }</code> <code><div class="flex-container"> <div class="sub-container"> <div class="item"></div> <div class="item"></div> </div> Hello this is some content <div class="sub-container"> <div class="item"></div> <div class="item"></div> </div> </div></code> When this is run it should have an item on the left and the right of <code>sub-container</code> and as you can see it doesn't. Comment: A trick is to open the inspector (right-click on the element, and select Inspect [Element]), and then type `align-content:` in element[.style] and use your arrow keys to try different values. I always mix up `align-content` with `justify-content` and see what happens when the value changes makes me realize my mistake. Answer: You need to use <code>justify-content</code> not <code>align-content</code> The CSS justify-content property defines how the browser distributes space between and around content items along the main-axis of a flex container, and the inline axis of a grid container. MDN <code>.flex-container { display: flex; height: 150px; width: 150px; background-color: aqua; border: 2px solid black; flex-direction: column; } .sub-container { display: flex; margin: 5px; background-color: #fff; border: 2px solid black; flex-basis: 50px; justify-content: space-between; } .item { flex-basis: 25px; margin: 3px; border: 1px solid black; background-color: green; }</code> <code><div class="flex-container"> <div class="sub-container"> <div class="item"></div> <div class="item"></div> </div> Hello this is some content <div class="sub-container"> <div class="item"></div> <div class="item"></div> </div> </div></code> Answer: The CSS declaration you're looking for is: <code>justify-content: space-between; </code> Working Example: <code>.flex-container { display: flex; flex-direction: column; height: 150px; width: 150px; background-color: aqua; border: 2px solid black; } .sub-container { display: flex; margin: 5px; background-color: #fff; border: 2px solid black; flex-basis: 50px; justify-content: space-between; } .item { flex-basis: 25px; margin: 3px; border: 1px solid black; background-color: green; }</code> <code><div class="flex-container"> <div class="sub-container"> <div class="item"></div> <div class="item"></div> </div> Hello this is some content <div class="sub-container"> <div class="item"></div> <div class="item"></div> </div> </div></code><|endoftext|>Is it appropriate/a good idea to use event listeners on object properties? Question: I'm creating an HTML5 Canvas Snake game with Javascript, and in trying to make my code more object-oriented, I came across a situation where I wasn't sure if what I was doing was valid. <code>Game.prototype.gameOver = function() { game.isOver = true; clearInterval(intervalId); console.log("Game Over!"); window.addEventListener("keydown", function(e) { if (e.code === "Space") { game.reset(); } }) } </code> game.gameOver() gets called when the snake collides with the walls or itself. Is it better to just add the reset eventListener at the global scope level and check if the game is over, or is this perfectly fine? Edit: I realized just after posting this that a new event listener was getting added each time gameOver was called, and that was the source of my issues. I've since fixed the code so that there is never more than once instance of the event listener at once. Comment: Would be better to have a key handler interface that does nothing but set the key's state and then build your logic from that. Here the day you'll want to add an other way to restart the game (mobile?), you'll have to change that part too, when it should not be part of the changes. Comment: This is not common but not a wrong practice. addEventListener is for adding an event whenever and wherever you like. Answer: As long as you remove that listener again after it kicks in, this should be fine, with the only tricky bit being that you can only remove a listener if you remove it in exactly the same way you added it. Using modern JS class syntax here instead of the legacy prototype syntax: <code>class Game { constructor(...args) { // ... this.reset(); } reset() { this.isOver = false; // ... // If reset() triggered from a window keydown event, remove // that keydown listener so it will only kick in once: if (this.resetHandler) { window.removeEventListener(`keydown`, this.resetHandler); this.resetHandler = false; } } gameOver() { this.isOver = true; console.log(`Game Over!`); // Create a function that can handle a keydown event // and calls reset() if it's the right key, and bind // it so we can remove it later: this.resetHandler = (evt) => { if (evt.code === `Space`) { this.reset(); } }; window.addEventListener(`keydown`, this.resetHandler); console.log(`Press "space" on the page to continue...`); } } </code> Note that arrow function, which makes sure that <code>this</code> gets preserved to what it was at declare time (i.e. the <code>game</code> instance this function's running for), rather than <code>function(evt) { ... }</code> in which <code>this</code> will be whatever the scope is at runtime (which for event listeners will be global scope, i.e. <code>window</code>). Comment: Would be better to remove the listener in the reset method, here if something else calls reset your handler will stay and when the user press the space key the game will restart for no reason.
[{"idx": "Are_cosmological_distances_additive?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-11726.jsonl"}, {"idx": "no_reconoce_el_else", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-11726.jsonl"}, {"idx": "Flexbox_align-content_not_aligning", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-11726.jsonl"}, {"idx": "Is_it_appropriate/a_good_idea_to_use_event_listeners_on_object_properties?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-11726.jsonl"}]
probability: swr p sequence --------------------------- Q: Two letters picked without replacement from {f: 2, d: 2}. What is prob of sequence ff? Soln: 1/6 Q: Calculate prob of sequence bd when two letters picked without replacement from {c: 1, m: 3, d: 4, i: 3, b: 8}. Soln: 16/171 Q: Four letters picked without replacement from mvqaaaalvl. Give prob of sequence lvlq. Soln: 1/1260 Q: Three letters picked without replacement from {i: 5, q: 15}. Give prob of sequence iiq. Soln: 5/114 Q: Calculate prob of sequence zz when two letters picked without replacement from zbzbzzzzzb. Soln: 7/15 Q: Four letters picked without replacement from wqoshsshssuqsshs. Give prob of sequence uhsw. Soln: 1/1820 Q: Two letters picked without replacement from {i: 1, o: 2, f: 1, b: 1}. What is prob of sequence ib? Soln: 1/20 Q: Calculate prob of sequence oxlx when four letters picked without replacement from {o: 1, x: 2, l: 9, p: 6}. Soln: 1/4080 Q: What is prob of sequence dtbp when four letters picked without replacement from {t: 3, d: 2, p: 4, b: 1}? Soln: 1/210 Q: What is prob of sequence iri when three letters picked without replacement from irrirririrrri? Soln: 40/429 Q: Three letters picked without replacement from mmmmmm. Give prob of sequence mmm. Soln: 1 Q: Four letters picked without replacement from kkkkkiaakvki. Give prob of sequence iaia. Soln: 1/2970 Q: Three letters picked without replacement from kkdfww. Give prob of sequence kfw. Soln: 1/30 Q: Calculate prob of sequence jzzj when four letters picked without replacement from kkzkkzjzjjk. Soln: 1/220 Q: Three letters picked without replacement from ucp. Give prob of sequence upc. Soln: 1/6 Q: Two letters picked without replacement from {b: 2, q: 3, x: 3, h: 2, k: 5}. What is prob of sequence qq? Soln: 1/35 Q: Calculate prob of sequence ubf when three letters picked without replacement from bbbvbbbubbfbbfvubbbf. Soln: 13/1140 Q: Four letters picked without replacement from {l: 11, b: 2}. Give prob of sequence llbb. Soln: 1/78 Q: Four letters picked without replacement from rmmmrhrmgmjhs. Give prob of sequence gmmm. Soln: 1/286 Q: Three letters picked without replacement from {p: 3, v: 2, w: 2, n: 5}. What is prob of sequence wpw? Soln: 1/220 Q: Two letters picked without replacement from phpphhpddp. Give prob of sequence dp. Soln: 1/9 Q: Four letters picked without replacement from {b: 5, k: 11}. What is prob of sequence bbkb? Soln: 11/728 Q: Calculate prob of sequence qut when three letters picked without replacement from {t: 2, u: 1, q: 1}. Soln: 1/12 Q: Four letters picked without replacement from sxsxs. What is prob of sequence ssxx? Soln: 1/10 Q: Calculate prob of sequence esz when three letters picked without replacement from zcese. Soln: 1/30 Q: Calculate prob of sequence ir when two letters picked without replacement from xxxxxirxrxrixxxxx. Soln: 3/136 Q: Four letters picked without replacement from {w: 2, d: 1, x: 1, f: 2, q: 2, e: 1}. Give prob of sequence qxwf. Soln: 1/378 Q: Calculate prob of sequence he when two letters picked without replacement from emmsmshem. Soln: 1/36 Q: Calculate prob of sequence jj when two letters picked without replacement from jjuu. Soln: 1/6 Q: Calculate prob of sequence fiii when four letters picked without replacement from iifffiffiffi. Soln: 7/198 Q: Two letters picked without replacement from kmvoozb. What is prob of sequence oz? Soln: 1/21 Q: Two letters picked without replacement from {s: 2, n: 1, a: 3, l: 1}. Give prob of sequence sa. Soln: 1/7 Q: What is prob of sequence ta when two letters picked without replacement from ddtatdaa? Soln: 3/28 Q: Three letters picked without replacement from {t: 4, u: 2, e: 3}. Give prob of sequence uue. Soln: 1/84 Q: Two letters picked without replacement from fkikfiiiffkii. What is prob of sequence ii? Soln: 5/26 Q: Calculate prob of sequence iv when two letters picked without replacement from eokkivvyo. Soln: 1/36 Q: Three letters picked without replacement from fhhfhfffff. What is prob of sequence hff? Soln: 7/40 Q: Three letters picked without replacement from {a: 1, v: 1, k: 3}. Give prob of sequence kkv. Soln: 1/10 Q: Calculate prob of sequence rr when two letters picked without replacement from rurrrryrrrfrfyfkby. Soln: 4/17 Q: Three letters picked without replacement from fgfjmffgzm. What is prob of sequence zjm? Soln: 1/360 Q: Calculate prob of sequence jee when three letters picked without replacement from jeeeeeeeecceeeejec. Soln: 13/204 Q: Calculate prob of sequence uf when two letters picked without replacement from {t: 7, u: 4, f: 3}. Soln: 6/91 Q: Two letters picked without replacement from {r: 5, g: 2, j: 5, u: 3, c: 3}. Give prob of sequence uj. Soln: 5/102 Q: Four letters picked without replacement from qqbbqbqqbqbqb. Give prob of sequence bqbb. Soln: 7/143 Q: What is prob of sequence sss when three letters picked without replacement from sjjjjjjssjsss? Soln: 10/143 Q: What is prob of sequence an when two letters picked without replacement from {a: 1, l: 3, n: 2, d: 1}? Soln: 1/21 Q: Calculate prob of sequence lstt when four letters picked without replacement from {j: 3, t: 2, z: 2, l: 3, s: 5}. Soln: 1/1092 Q: Two letters picked without replacement from {k: 11, n: 1}. What is prob of sequence nk? Soln: 1/12 Q: What is prob of sequence unuu when four letters picked without replacement from {u: 7, n: 7}? Soln: 35/572 Q: Three letters picked without replacement from nnxoxoxxo. Give prob of sequence nxo. Soln: 1/21 Q: What is prob of sequence tnt when three letters picked without replacement from {t: 7, n: 4}? Soln: 28/165 Q: What is prob of sequence ggig when four letters picked without replacement from iggiggigiigggg? Soln: 15/143 Q: What is prob of sequence qa when two letters picked without replacement from {e: 2, q: 5, a: 6}? Soln: 5/26 Q: Two letters picked without replacement from uuuuuuuuuuauuuuuuuuu. Give prob of sequence uu. Soln: 9/10 Q: Two letters picked without replacement from {a: 1, s: 1, w: 7, y: 4, x: 4}. Give prob of sequence wx. Soln: 7/68 Q: What is prob of sequence oog when three letters picked without replacement from {g: 1, o: 2}? Soln: 1/3 Q: Two letters picked without replacement from mboppeh. Give prob of sequence eo. Soln: 1/42 Q: Four letters picked without replacement from wmqfmgd. What is prob of sequence gfwd? Soln: 1/840 Q: Three letters picked without replacement from yyyjyyyryyyyyyyyyyyy. Give prob of sequence rjy. Soln: 1/380 Q: Four letters picked without replacement from lslufuchusuccuu. What is prob of sequence sslc? Soln: 1/2730 Q: What is prob of sequence sx when two letters picked without replacement from xxxsxxxxxssxxsxsssx? Soln: 14/57 Q: What is prob of sequence vyf when three letters picked without replacement from vvqfqqvvqyqv? Soln: 1/264 Q: Three letters picked without replacement from ggzcggzge. What is prob of sequence gec? Soln: 5/504 Q: Two letters picked without replacement from llggggg. What is prob of sequence gg? Soln: 10/21 Q: Three letters picked without replacement from {g: 2, p: 2, n: 2, z: 13, x: 1}. Give prob of sequence xnz. Soln: 13/3420 Q: Four letters picked without replacement from uffuuuf. Give prob of sequence fffu. Soln: 1/35 Q: Two letters picked without replacement from {n: 2, d: 3, f: 12}. What is prob of sequence nf? Soln: 3/34 Q: Three letters picked without replacement from jjjjjjjwjjjjwwj. Give prob of sequence jww. Soln: 12/455 Q: What is prob of sequence mmw when three letters picked without replacement from wmtqmmppmtpqtmtmm? Soln: 7/680 Q: Calculate prob of sequence yuy when three letters picked without replacement from {u: 1, y: 2}. Soln: 1/3 Q: Calculate prob of sequence sgq when three letters picked without replacement from {g: 3, s: 1, q: 1, p: 2}. Soln: 1/70 Q: Three letters picked without replacement from {d: 1, c: 1, m: 4, a: 2}. What is prob of sequence dmc? Soln: 1/84 Q: Three letters picked without replacement from uuuajuuuaauuauaauuau. Give prob of sequence jau. Soln: 7/570 Q: Two letters picked without replacement from tiickqkvt. Give prob of sequence vt. Soln: 1/36 Q: Calculate prob of sequence zhh when three letters picked without replacement from zhhmmmhmzhzh. Soln: 1/22 Q: Two letters picked without replacement from {v: 5, s: 2}. What is prob of sequence ss? Soln: 1/21 Q: Calculate prob of sequence yy when two letters picked without replacement from {g: 6, y: 3, d: 6, x: 4}. Soln: 1/57 Q: What is prob of sequence ttl when three letters picked without replacement from {w: 2, t: 3, q: 1, l: 1}? Soln: 1/35 Q: What is prob of sequence hhw when three letters picked without replacement from wwwwwwwwwwwwwwwhhh? Soln: 5/272 Q: Calculate prob of sequence qdqd when four letters picked without replacement from {d: 8, q: 2}. Soln: 1/45 Q: Three letters picked without replacement from xvmxmmvxvmxmmvx. Give prob of sequence xxx. Soln: 2/91 Q: Three letters picked without replacement from thxxttxxtxxjhx. Give prob of sequence htj. Soln: 1/273 Q: Two letters picked without replacement from eesse. Give prob of sequence es. Soln: 3/10 Q: What is prob of sequence rr when two letters picked without replacement from jrrsnjb? Soln: 1/21 Q: Calculate prob of sequence cuff when four letters picked without replacement from {c: 3, i: 1, t: 1, y: 3, f: 2, u: 1}. Soln: 1/1320 Q: Two letters picked without replacement from {g: 1, h: 11, p: 2, t: 1, v: 3, s: 1}. Give prob of sequence gt. Soln: 1/342 Q: Two letters picked without replacement from lorrhocrooooohcrorrr. Give prob of sequence ro. Soln: 14/95 Q: Four letters picked without replacement from {j: 4, v: 1, q: 2, g: 2}. Give prob of sequence jqgv. Soln: 1/189 Q: Two letters picked without replacement from {p: 2, o: 9, y: 1, g: 5, c: 1}. Give prob of sequence gg. Soln: 10/153 Q: Calculate prob of sequence ii when two letters picked without replacement from aiaaiaaa. Soln: 1/28 Q: Four letters picked without replacement from {o: 6, n: 4, m: 7, y: 1}. Give prob of sequence mmmy. Soln: 7/2448 Q: Calculate prob of sequence kkk when three letters picked without replacement from {k: 6}. Soln: 1 Q: What is prob of sequence tv when two letters picked without replacement from xnqtxmvv? Soln: 1/28 Q: What is prob of sequence qzp when three letters picked without replacement from {s: 8, z: 3, p: 6, q: 2}? Soln: 2/323 Q: What is prob of sequence iko when three letters picked without replacement from {o: 12, y: 4, k: 2, i: 2}? Soln: 2/285 Q: Four letters picked without replacement from hhiyffhffiiyhyiifhyf. What is prob of sequence yfyi? Soln: 1/323 Q: What is prob of sequence nn when two letters picked without replacement from znzbdcddbcdvvzccvzcd? Soln: 0 Q: Calculate prob of sequence bbbr when four letters picked without replacement from {b: 4, r: 16}. Soln: 16/4845 Q: Calculate prob of sequence wwy when three letters picked without replacement from ywyywzx. Soln: 1/35 Q: Calculate prob of sequence zguu when four letters picked without replacement from {g: 1, u: 3, m: 4, y: 2, z: 2}. Soln: 1/990 Q: What is prob of sequence azr when three letters picked without replacement from {r: 1, z: 6, a: 1, p: 1, s: 3}? Soln: 1/220 Q: What is prob of sequence oo when two letters picked without replacement from {m: 2, o: 2, s: 3, a: 2}? Soln: 1/36 Q: Three letters picked without replacement from {r: 1, j: 4, x: 1, w: 1, s: 1}. What is prob of sequence xxw? Soln: 0 Q: Two letters picked without replacement from {p: 8, l: 1, b: 1, g: 4, s: 1}. What is prob of sequence lp? Soln: 4/105 Q: Four letters picked without replacement from ddoodzzbozoddodddz. What is prob of sequence zdbo? Soln: 1/459 Q: Four letters picked without replacement from krkkkrkkkrr. Give prob of sequence rkrk. Soln: 7/110 Q: What is prob of sequence lgfp when four letters picked without replacement from {b: 1, j: 5, g: 2, p: 1, l: 1, f: 6}? Soln: 1/3640 Q: Three letters picked without replacement from {d: 2, r: 5, v: 1, o: 1}. What is prob of sequence odd? Soln: 1/252 Q: Four letters picked without replacement from iiiiiiiii. What is prob of sequence iiii? Soln: 1 Q: Calculate prob of sequence wwff when four letters picked without replacement from wfwwwwwfw. Soln: 1/36 Q: Calculate prob of sequence qf when two letters picked without replacement from {d: 3, q: 2, f: 4, z: 1, i: 1}. Soln: 4/55 Q: Calculate prob of sequence pj when two letters picked without replacement from {j: 9, p: 9}. Soln: 9/34 Q: What is prob of sequence ahll when four letters picked without replacement from lalhalhll? Soln: 5/189 Q: Three letters picked without replacement from gvvgvvvgvgbbv. What is prob of sequence vbv? Soln: 7/143 Q: Four letters picked without replacement from akmkaammmakmmmak. What is prob of sequence kaaa? Soln: 1/182 Q: Calculate prob of sequence fffq when four letters picked without replacement from qaafafaaqf. Soln: 1/420 Q: What is prob of sequence nn when two letters picked without replacement from nnnnnnnnnn? Soln: 1 Q: Calculate prob of sequence hh when two letters picked without replacement from hhhhghhg. Soln: 15/28 Q: Two letters picked without replacement from llpplllll. What is prob of sequence pp? Soln: 1/36 Q: What is prob of sequence mcnc when four letters picked without replacement from mcncccmaccmamc? Soln: 1/143 Q: What is prob of sequence kz when two letters picked without replacement from xkhzxzjnzxk? Soln: 3/55 Q: Three letters picked without replacement from nmbmomoqbfbmnbm. What is prob of sequence qbb? Soln: 2/455 Q: Three letters picked without replacement from urr. What is prob of sequence rur? Soln: 1/3 Q: Calculate prob of sequence bjj when three letters picked without replacement from {j: 6, b: 1, v: 1, g: 1}. Soln: 5/84 Q: Four letters picked without replacement from bbzzbzbffm. What is prob of sequence zbfb? Soln: 1/70 Q: What is prob of sequence jjjt when four letters picked without replacement from {t: 1, j: 12}? Soln: 1/13 Q: Four letters picked without replacement from kkuikkeuku. Give prob of sequence ukkk. Soln: 1/28 Q: Four letters picked without replacement from {d: 2, b: 2}. What is prob of sequence ddbb? Soln: 1/6 Q: What is prob of sequence apaa when four letters picked without replacement from {n: 4, p: 1, a: 6}? Soln: 1/66 Q: Two letters picked without replacement from niniiinyniiniiiini. Give prob of sequence in. Soln: 11/51 Q: Calculate prob of sequence ww when two letters picked without replacement from mlwwlws. Soln: 1/7 Q: Two letters picked without replacement from aaaavavavaaaaaaaava. Give prob of sequence va. Soln: 10/57 Q: What is prob of sequence lx when two letters picked without replacement from rbrbbfflrflxlrfb? Soln: 1/80 Q: Calculate prob of sequence rrs when three letters picked without replacement from rdsxrxsjrxjrrjjwrsrx. Soln: 7/380 Q: What is prob of sequence ipc when three letters picked without replacement from cpcicioioo? Soln: 1/80 Q: Two letters picked without replacement from {p: 2, j: 1, g: 1, q: 2, h: 2}. Give prob of sequence qp. Soln: 1/14 Q: Two letters picked without replacement from eezkjeeszzseskkeze. What is prob of sequence zs? Soln: 2/51 Q: Calculate prob of sequence zzz when three letters picked without replacement from zzzz. Soln: 1 Q: Two letters picked without replacement from {x: 6, i: 8, n: 3}. What is prob of sequence xi? Soln: 3/17 Q: Four letters picked without replacement from bqlbbbbbbbgqlqbbqge. What is prob of sequence bbqe? Soln: 5/1292 Q: Calculate prob of sequence pp when two letters picked without replacement from {y: 2, p: 2, c: 7, r: 1, n: 7}. Soln: 1/171 Q: What is prob of sequence qool when four letters picked without replacement from nooknlnqn? Soln: 1/1512 Q: Calculate prob of sequence bzbb when four letters picked without replacement from {b: 9, z: 4, g: 6}. Soln: 7/323 Q: Four letters picked without replacement from rywww. Give prob of sequence ryww. Soln: 1/20 Q: What is prob of sequence uz when two letters picked without replacement from zuiya? Soln: 1/20 Q: Three letters picked without replacement from {f: 3, a: 11}. What is prob of sequence aaf? Soln: 55/364 Q: Two letters picked without replacement from evyyuuyyyuywx. What is prob of sequence yu? Soln: 3/26 Q: Two letters picked without replacement from {o: 5, y: 1, m: 4}. Give prob of sequence mo. Soln: 2/9 Q: Calculate prob of sequence mhhh when four letters picked without replacement from mhhmhhh. Soln: 1/7 Q: Four letters picked without replacement from tttrrrrrrrrrrt. Give prob of sequence rrrr. Soln: 30/143 Q: Calculate prob of sequence ile when three letters picked without replacement from iiyliilliyyielliyly. Soln: 7/969 Q: What is prob of sequence qq when two letters picked without replacement from {s: 2, a: 7, n: 2, q: 4, f: 1, k: 1}? Soln: 3/68 Q: What is prob of sequence ccc when three letters picked without replacement from xxccc? Soln: 1/10 Q: Four letters picked without replacement from {u: 2, e: 1, v: 8, x: 2, y: 2}. Give prob of sequence vvxv. Soln: 4/195 Q: Two letters picked without replacement from {b: 9, r: 11}. Give prob of sequence br. Soln: 99/380 Q: Two letters picked without replacement from {b: 5, g: 5, u: 1}. What is prob of sequence bu? Soln: 1/22 Q: Calculate prob of sequence qvs when three letters picked without replacement from snvsvgqvgeeq. Soln: 1/110 Q: Four letters picked without replacement from xiiexxjiiiiik. What is prob of sequence xkxx? Soln: 1/2860 Q: What is prob of sequence qhz when three letters picked without replacement from xhzqhxxhhixjihjqhj? Soln: 1/408 Q: Calculate prob of sequence mwwm when four letters picked without replacement from {w: 9, m: 2}. Soln: 1/55 Q: Calculate prob of sequence hh when two letters picked without replacement from {n: 4, q: 6, h: 10}. Soln: 9/38 Q: Calculate prob of sequence yk when two letters picked without replacement from ykyyyyykky. Soln: 7/30 Q: What is prob of sequence ttll when four letters picked without replacement from ltllltlllll? Soln: 1/55 Q: Calculate prob of sequence lly when three letters picked without replacement from {l: 7, n: 5, g: 1, y: 3}. Soln: 3/80 Q: Three letters picked without replacement from ttla. What is prob of sequence lta? Soln: 1/12 Q: Calculate prob of sequence ju when two letters picked without replacement from {j: 2, k: 13, u: 1, d: 3}. Soln: 1/171 Q: Two letters picked without replacement from zyeqb. What is prob of sequence qe? Soln: 1/20 Q: Two letters picked without replacement from yxjckyvykycjxk. Give prob of sequence kv. Soln: 3/182 Q: What is prob of sequence wlk when three letters picked without replacement from {k: 8, n: 1, l: 8, m: 1, w: 2}? Soln: 16/855 Q: Three letters picked without replacement from offoooooooooofoo. What is prob of sequence fof? Soln: 13/560 Q: Four letters picked without replacement from {b: 4, y: 7, t: 2}. What is prob of sequence ttbb? Soln: 1/715 Q: Four letters picked without replacement from {o: 7, k: 2}. Give prob of sequence ooko. Soln: 5/36 Q: Three letters picked without replacement from twttxtttwtixixwt. Give prob of sequence xwi. Soln: 3/560 Q: What is prob of sequence vvx when three letters picked without replacement from qqxqqqxvv? Soln: 1/126 Q: Three letters picked without replacement from xddzxxxxdd. Give prob of sequence xxd. Soln: 1/9 Q: What is prob of sequence oooo when four letters picked without replacement from mmmmomooom? Soln: 1/210 Q: Three letters picked without replacement from lpffh. What is prob of sequence hlf? Soln: 1/30 Q: Three letters picked without replacement from mmockomcocmommoc. Give prob of sequence ocm. Soln: 1/28 Q: Two letters picked without replacement from {j: 1, p: 1, k: 1, l: 1, h: 2, y: 1}. Give prob of sequence yl. Soln: 1/42<|endoftext|>numbers: div remainder composed ------------------------------- Q-: Let s(x) = -x**3 + 30*x**2 - 48*x - 31. Calculate the remainder when s(28) is divided by 180. Yields: 13 Q-: Suppose 3*m = 5*m. Suppose m = -5*l - 97 - 153. What is the remainder when (18/(-15))/(1/l) is divided by 21? Yields: 18 Q-: Let y = 182 - 161. Calculate the remainder when y is divided by 3. Yields: 0 Q-: Calculate the remainder when 1584*(8 - (484/6)/11) is divided by 53. Yields: 49 Q-: Suppose 3*m + 21 = o - 0*m, 0 = -2*m - 2. What is the remainder when 69 is divided by o? Yields: 15 Q-: What is the remainder when ((-58)/60 - -1)*-4 + 52409/105 is divided by 40? Yields: 19 Q-: Let o be (-4)/(-14) - 16/7. Let x be (0 - -1)/((-1)/5). Let a = o - x. What is the remainder when 7 is divided by a? Yields: 1 Q-: What is the remainder when ((-6)/9)/(26/(-11232)) is divided by 99? Yields: 90 Q-: Let b = -1670 + 1673. What is the remainder when 46 is divided by b? Yields: 1 Q-: Let l(f) = 83*f**2 + 3*f - 2. Let o be l(2). Suppose 0 = -6*x + 8*x - o. Suppose 5*a - x + 33 = 0. Calculate the remainder when a is divided by 7. Yields: 6 Q-: Suppose -2*h = -2, p - 4*p + h + 41 = 0. Let d = 4 + -4. Let n = 5 + d. Calculate the remainder when p is divided by n. Yields: 4 Q-: Suppose -16 = -0*d - 2*d. Let n(f) = f - 8. Let w be n(d). Suppose 3*i + w*l - 5*l - 224 = 0, -78 = -i + 5*l. Calculate the remainder when i is divided by 19. Yields: 16 Q-: Suppose 40 = 5*k - 75. Suppose -312 = -2*f - 9*u + 8*u, 5*f - 765 = -5*u. What is the remainder when f is divided by k? Yields: 21 Q-: Let p = 3 + 3. Suppose 48 = 3*k + 3*z, -k + 2*z = -1 - 18. What is the remainder when k is divided by p? Yields: 5 Q-: Suppose 5*l - 5*u = -30, -3*u + 26 = -2*l + 9. Let o(s) = 106*s**2 - 108*s**2 + 0 + 1 - 32*s**3. What is the remainder when o(l) is divided by 16? Yields: 15 Q-: Let v(r) = -3*r - 4. Let p(l) = -4*l**2 + 23*l + 3. Let m(w) = -w**2 + w. Let y(a) = -6*m(a) + p(a). What is the remainder when y(-9) is divided by v(-3)? Yields: 2 Q-: Suppose -l = -10*l - 5*l. Suppose -53*y + 55*y - 216 = l. Let q = 71 - 43. Calculate the remainder when y is divided by q. Yields: 24 Q-: Let n(u) be the first derivative of -2*u**2 + 20*u - 5. Let g be n(5). Suppose g = -i + 28 - 23. What is the remainder when 14 is divided by i? Yields: 4 Q-: Let r(z) = 4*z**2 + z. Let k be r(1). Suppose -5*h + k*g = -0*h - 25, -h = -2*g - 4. What is the remainder when 9 is divided by h? Yields: 3 Q-: Suppose -3*n + 2*m + 164 = 0, 3*n + 0*m + 2*m = 148. Suppose 2*c - 6*c - 2*a = -n, -2*a = 2*c - 30. Calculate the remainder when 51 is divided by c. Yields: 7 Q-: Let v = 8 + -5. Let s(x) = -x + 2. Let g be s(1). What is the remainder when 18 is divided by 4 - -9 - v/g? Yields: 8 Q-: Let z be 3/2*(-8)/(-3). Suppose -z*v + 35 = 5*y, y - 2*v - 27 + 6 = 0. Calculate the remainder when 31 is divided by y. Yields: 9 Q-: Suppose 0 = 2*a - 12 - 4. Suppose -a = 11*x - 9*x. Calculate the remainder when 4208/88 + x/(-22) is divided by 17. Yields: 14 Q-: Let s(r) = r**3 + 7*r**2 + 6*r - 8. Let i be s(-6). Let b be (-5)/((-30)/i)*-6. What is the remainder when 18 is divided by 4*(38/b - 3)? Yields: 4 Q-: What is the remainder when 54 is divided by (-1)/(((-6)/58)/3)? Yields: 25 Q-: Let j = 19 + 4. Let n = 4 - j. What is the remainder when -3 + 0 - (n + 3) is divided by 8? Yields: 5 Q-: Let p(c) = -56*c + 2952. What is the remainder when p(17) is divided by 26? Yields: 24 Q-: Let j be (-2)/(0 + 7/(-7)). Suppose -2*y - 42 = -2*l, l + j*y - 22 + 16 = 0. What is the remainder when 125 is divided by l? Yields: 13 Q-: Let g(o) = -130*o + 7950. Calculate the remainder when 458 is divided by g(61). Yields: 18 Q-: Let m = -13051 + 13071. Calculate the remainder when 2875 is divided by m. Yields: 15 Q-: Let s = 13 - 6. What is the remainder when 19 is divided by s? Yields: 5 Q-: Calculate the remainder when ((-14)/(5 + -4))/((-2)/25) is divided by 22. Yields: 21 Q-: Let q(o) = -o**2 + 1. Let n(m) = -3*m**2 + 4*m + 1. Let p(i) = n(i) - 4*q(i). What is the remainder when p(5) is divided by (0 + (-1)/1)*-22? Yields: 20 Q-: Suppose 84 = 17*r - 21*r. Let u = r + 27. What is the remainder when 20 is divided by u? Yields: 2 Q-: Let r(m) = -m**3 - 45*m**2 + 361*m + 41. Calculate the remainder when r(-52) is divided by 100. Yields: 97 Q-: What is the remainder when 437 is divided by (-1 + 7)/2 + 11? Yields: 3 Q-: Calculate the remainder when (-2)/(2/6 + -1) is divided by 12/(-9)*(-6)/4. Yields: 1 Q-: Suppose -3*z - 25 = 5. Let l = 33 + z. What is the remainder when l is divided by ((-4)/6)/((-32)/288)? Yields: 5 Q-: Let h(v) = -v**3 - 10*v**2 - 10*v + 7. Let l be h(-9). Suppose -30*a + l*a + 84 = 0. What is the remainder when a is divided by 5? Yields: 1 Q-: Let p(f) be the first derivative of -f**2/2 - 8*f + 16. What is the remainder when 2 is divided by p(-10)? Yields: 0 Q-: Suppose -4*v + 49 = 2*t + v, -3*v + 75 = 5*t. Suppose 91 = -u + 2*u. Let y = -46 + u. What is the remainder when y is divided by t? Yields: 9 Q-: Suppose h = 8 + 31. What is the remainder when h is divided by 20? Yields: 19 Q-: Suppose 0 = -3*g + 3*b + 63, 2*g - b - 35 = 9. Calculate the remainder when (-2 + 1)/(-1)*g is divided by 6. Yields: 5 Q-: Let u = -140 - -206. What is the remainder when u is divided by 34? Yields: 32 Q-: Suppose 3*y + 5*p = 70, -2*y + 44 = -3*p + 10. What is the remainder when 36 is divided by y? Yields: 16 Q-: Calculate the remainder when (52/6)/(16/72) is divided by 14. Yields: 11 Q-: What is the remainder when 775 is divided by 123 + -112 - (-3)/(-1)*-2? Yields: 10 Q-: Let y = -15 + 14. Calculate the remainder when (-35)/35*(-22 - y) is divided by 10. Yields: 1 Q-: Suppose 97*t - 88*t - 1386 = 0. Calculate the remainder when t is divided by 39. Yields: 37 Q-: Suppose 6*h - 56 = 40. What is the remainder when 31 is divided by h? Yields: 15 Q-: Suppose 443 = -663*i + 667*i - 3*s, -i + 5*s = -115. Calculate the remainder when i is divided by (-4)/((2/8)/(-1)). Yields: 14 Q-: Let m(w) = w**3 - 6*w**2 + 4*w - 4. Let s be m(5). What is the remainder when 46 is divided by (s + -1)*18/(-15)? Yields: 10 Q-: Let v(g) = 5*g**2 + 9*g + 29. Let l be v(-6). Let d = l - 107. Suppose -2*s + 2*n = -d, 0 = 3*s - n - 34 - 32. Calculate the remainder when s is divided by 11. Yields: 10 Q-: Suppose -2*w - 62 = -3*m, 3*w = -0*m - 3*m + 57. What is the remainder when 31 is divided by m? Yields: 11 Q-: Suppose 3*d + 680 = 4*g, d = -4*g + 2*d + 672. What is the remainder when g is divided by 16? Yields: 7 Q-: Suppose 0 = -5*b + n + 21 + 17, n + 24 = 3*b. What is the remainder when 27 is divided by b? Yields: 6 Q-: Suppose -11*u + 7*u + 4 = 0. Calculate the remainder when 2/((8/30)/2) is divided by (9/6)/(u/4). Yields: 3 Q-: Suppose 0 = -234*b + 33*b + 663702. Calculate the remainder when b is divided by 16. Yields: 6 Q-: Suppose 2*p + 3*w - 30 = 5*p, 20 = 4*w. Let m = p - -12. Calculate the remainder when -2*-2*76/16 is divided by m. Yields: 5 Q-: Suppose 96*m - 470 = 91*m. Calculate the remainder when m is divided by 6. Yields: 4 Q-: Calculate the remainder when (-3)/15 + -131*(-1)/5 is divided by 7. Yields: 5 Q-: Let i = 7 - 12. Let p = 11 + i. Calculate the remainder when 1/2 + (-147)/(-14) is divided by p. Yields: 5 Q-: Let k(n) = -n**3 - 26*n**2 + 16. Let r(c) = -33*c - 4. Calculate the remainder when r(-3) is divided by k(-26). Yields: 15 Q-: Suppose 8 = 4*g - 0. Suppose -5*q + 13 = -2*h, -3*h + 1 = -g. Suppose 2*x - 7*x = -q*y - 119, -2*x + 5*y = -59. Calculate the remainder when 87 is divided by x. Yields: 21 Q-: Suppose 3*p = 37 + 11. Suppose p*c - 23 = 9. What is the remainder when 36 is divided by (-2352)/(-120) - c/(-5)? Yields: 16 Q-: Suppose -2*w + 156 = -5*u, -7*w + 2*w + 5*u = -360. Suppose 2*n - w = -2*n. What is the remainder when 82 is divided by n? Yields: 14 Q-: Let i(h) = -h**3 - 20*h**2 - 35*h + 20. Calculate the remainder when 248 is divided by i(-18). Yields: 0 Q-: Suppose -4*m = m - 5. Suppose t - 5*t - m = -g, -4*t = 2*g - 14. Suppose -y = v + 1 - 12, -3*y + 5*v = -49. Calculate the remainder when y is divided by g. Yields: 3 Q-: Let w(i) = 2*i**2 - 8*i - 3. Let c = 9 - 12. What is the remainder when 153 is divided by w(c)? Yields: 36 Q-: Calculate the remainder when 11 is divided by 28/5 - 6/(-15). Yields: 5 Q-: Let f(v) = -3*v - 8. Let t be f(-8). Suppose 0 = -20*j + t*j - 3*w + 665, 2*j + 4*w = 320. Calculate the remainder when j is divided by 35. Yields: 30 Q-: Let a = -4225 - -4304. Calculate the remainder when a is divided by 8. Yields: 7 Q-: Let i = 422 - 417. Suppose i*n = 484 - 159. Calculate the remainder when n is divided by 29. Yields: 7 Q-: Let o(y) = -y + 8. Let r be 64/(-16) + (8 - 0). Suppose 0 = -4*j - 3*l, 8 - 1 = 5*j + 2*l. Calculate the remainder when o(r) is divided by j. Yields: 1 Q-: Suppose -2*k + 44 = -40. Calculate the remainder when k is divided by (15*(-3)/6)/((-3)/6). Yields: 12 Q-: Let s = -15 - -22. What is the remainder when 24 is divided by s? Yields: 3 Q-: Suppose -2*q - 2*d = -14, 0*q = -2*q + d + 2. Suppose q*s + 4*u = 4*s - 26, -4*s - 5*u = -146. Let v = 30 + -21. Calculate the remainder when s is divided by v. Yields: 7 Q-: Let r be (1 - 9/2)/(20/(-5320)). Suppose -21*k + 2*k + r = 0. What is the remainder when 194 is divided by k? Yields: 47 Q-: Suppose -c = 5*w - 280, w - 56 = c + 3*c. Suppose -3*p + 2*t = -7*p + 72, 3*p - w = -t. What is the remainder when 58 is divided by p? Yields: 18 Q-: Suppose 2*j - 96 = -5*s, -2*s + 5*j = -38 - 41. What is the remainder when 832 is divided by s? Yields: 18 Q-: Let r(h) = 2*h**2 + h - 4. What is the remainder when 46 is divided by r(2)? Yields: 4 Q-: Suppose -14 = -d - 0*d. Let i = 99 + -73. Calculate the remainder when i is divided by d. Yields: 12 Q-: Calculate the remainder when (4/3)/(2/126) is divided by 17. Yields: 16 Q-: Suppose 0 = x - 2 + 7, -2*x + 8 = 2*d. Calculate the remainder when d is divided by 1. Yields: 0 Q-: Let m = -94 - -197. Let p = -167 - -202. What is the remainder when m is divided by p? Yields: 33 Q-: Let w(g) = -2*g**2 + 3*g**2 - 3 + 4*g - 10. Let j be w(-12). Suppose 2*h = -19 + j. What is the remainder when h is divided by 17? Yields: 15 Q-: Suppose -31*z + 34*z = 156. Calculate the remainder when 103 is divided by z. Yields: 51 Q-: Let z(f) = 2*f + 2. Let y(a) be the second derivative of a**3/3 + a**2 + 2*a. Let h(m) = -2*y(m) + 3*z(m). What is the remainder when 17 is divided by h(2)? Yields: 5 Q-: Suppose 3*q - 4*j - 42 - 19 = 0, 0 = 3*q - j - 76. Suppose 69 + q = 3*b. What is the remainder when b is divided by 10? Yields: 2 Q-: Calculate the remainder when (-4)/((-8)/138) - (6 - 1) is divided by 15. Yields: 4 Q-: Let r = 366 + -336. What is the remainder when 88 is divided by r? Yields: 28 Q-: Suppose 0 = -2*j - 2*j + 28. Suppose -j*w = -5*w - 76. What is the remainder when w is divided by 13? Yields: 12 Q-: Let a(k) = -5*k - 15. Let j(f) = 6*f + 14. Let o(g) = -2*a(g) - 3*j(g). Let p(n) = -33*n**2 + 42*n + 19. What is the remainder when o(-8) is divided by p(0)? Yields: 14 Q-: Suppose 2*d + 5*g = 78 + 64, 0 = -5*d - 3*g + 374. Calculate the remainder when d is divided by 20. Yields: 16 Q-: Let w = -68 + 109. Calculate the remainder when w is divided by 12. Yields: 5 Q-: Suppose y = 3*y + 6, 2*m = -5*y + 109. Calculate the remainder when (-2)/(-4) + (-114)/(-4) is divided by -4*((-2)/7 + m/(-28)). Yields: 9 Q-: Suppose 0*q = q - 3*f - 6, 8 = 3*q - 4*f. Suppose q*t = -t + 12. What is the remainder when 22 is divided by t? Yields: 10 Q-: Let d = -429 + -185. What is the remainder when 48 is divided by d/(-17) + (-8)/68? Yields: 12 Q-: What is the remainder when 7 + (-399)/(-13 + 10) is divided by 38? Yields: 26 Q-: Let m = -10517 + 10572. Let l(i) = 3*i - 5. Let u(j) = -4*j + 8. Let n(k) = -8*l(k) - 5*u(k). Calculate the remainder when m is divided by n(-5). Yields: 15 Q-: Let q be (3 + -2 + -1)*-1. Suppose -3*n = -q*n + 6. What is the remainder when 2 is divided by n + 1 + (-4)/(-2)? Yields: 0 Q-: Let a be 3 - 6/(-8)*-4. Suppose a = -5*x + 375 + 15. What is the remainder when x is divided by 27? Yields: 24 Q-: Suppose -26 - 16 = -6*c. Let w(f) = f**3 + 5*f**2 - f - 2. What is the remainder when c is divided by w(-5)? Yields: 1 Q-: Let j = -29 - -99. Let m = j - 37. What is the remainder when m is divided by (-16)/(-3)*(-234)/(-104)? Yields: 9 Q-: Let r = 217 + -210. Calculate the remainder when 660 is divided by r. Yields: 2 Q-: Suppose a = 4*n + 81, 0 = 7*a - 2*a + n - 405. What is the remainder when a is divided by 341/(-121) + 3 + (-3060)/(-110)? Yields: 25 Q-: Suppose 20 = 4*b - 2*b + 4*r, r = b - 13. Let x = 5 + 28. What is the remainder when x is divided by b? Yields: 9 Q-: Calculate the remainder when 404/14 + 1/7 is divided by 12. Yields: 5 Q-: Let f(z) = 2*z**3 - 3*z**2 + z - 3. What is the remainder when f(4) is divided by 21? Yields: 18 Q-: Let b be 2/4*(1 - 1). Let m = 12 + b. Calculate the remainder when 35 is divided by m. Yields: 11 Q-: Suppose 11*v = -0*v + 121. Calculate the remainder when v is divided by (-40)/(-6) + 2/(-3). Yields: 5 Q-: Let j(t) = -3*t**2 + 5*t + 6. Let v be j(0). Let w = -13 + 21. Calculate the remainder when 85/v - (-162)/(-972) is divided by w. Yields: 6 Q-: Let h = -1109 - -1410. Calculate the remainder when h is divided by 62. Yields: 53 Q-: Let w = 1449 - 1435. Calculate the remainder when 121 is divided by w. Yields: 9 Q-: What is the remainder when 1249 is divided by (-178 - -173)*(-9)/5? Yields: 7 Q-: Let x(d) = d**3 + 6*d**2 - 6*d + 8. Suppose -3*c - 19 = -1. Suppose 4*h - 93 + 33 = 0. What is the remainder when x(c) is divided by h? Yields: 14 Q-: Suppose -3*d - 2*d = 20. Let o be ((-12)/8)/(2/d). Suppose 60 = o*f - f. Calculate the remainder when f is divided by 16. Yields: 14 Q-: Let l = -19 + 27. Let y(d) = d**3 - 4*d**2 - 3*d - 7. Calculate the remainder when l is divided by y(5). Yields: 2 Q-: Suppose -5*t + 0*a = 5*a + 90, 72 = -4*t + a. Let y(f) = -3*f - 5. What is the remainder when y(t) is divided by 13? Yields: 10 Q-: Let g(j) = 6*j**2 + 10*j - 21. Suppose 0 = -r + 6*r + 25. Calculate the remainder when g(r) is divided by 41. Yields: 38 Q-: Suppose 0*j - 2*j + 6 = 0. Let v = -2 - -1. Let k = 9 - v. What is the remainder when k is divided by j? Yields: 1 Q-: Let y = -84 - -148. Suppose 6*a + 4*n - y = 2*a, 4*n - 16 = 0. What is the remainder when 10 is divided by (a/10)/(3/15)? Yields: 4 Q-: Suppose 46536 = 18*m + 45852. Calculate the remainder when 1329 is divided by m. Yields: 37 Q-: Suppose 90*s - 4*c + 396 = 94*s, -4*c - 304 = -3*s. Let b = 111 - 24. Let p = s - b. What is the remainder when 25 is divided by p? Yields: 12 Q-: Suppose -15*w + 10*w = -130. What is the remainder when w is divided by 7? Yields: 5 Q-: Suppose 5*b = 3*m + 366, -7*m - 210 = -3*b - 2*m. Suppose 0 = -4*z - 23 + b. Let w = 2 + 3. What is the remainder when z is divided by w? Yields: 3 Q-: What is the remainder when ((-2)/5)/(13/(-1040)) is divided by 10? Yields: 2 Q-: Let k = -10 - -85. Suppose 5*c - 148 = -y - 0*y, -3*c + 4*y = -k. Calculate the remainder when c is divided by 15. Yields: 14 Q-: Suppose -158*t = -4*l - 157*t + 2035, t - 1 = 0. What is the remainder when l is divided by 57? Yields: 53 Q-: Suppose -d + 3*d = 44. Suppose -5*y = 2*u - y + d, 5*u + y + 82 = 0. Let z = -10 - u. What is the remainder when 13 is divided by z? Yields: 6 Q-: Suppose 5*u - 5*q - 10 = 0, 8*q - 26 = -4*u + 3*q. Suppose 0 = -8*r + u*r. Suppose r = 2*n - 2 - 2. What is the remainder when n is divided by 1? Yields: 0 Q-: Let o(u) = -26*u**2 + 111*u - 41. Let q(n) = 5*n**2 - 22*n + 8. Let d(l) = -2*o(l) - 11*q(l). What is the remainder when 153 is divided by d(4)? Yields: 23 Q-: What is the remainder when 53 is divided by -8 + -1 + -5 + 25? Yields: 9 Q-: Suppose 0 = 4*a - 17 - 83. What is the remainder when a is divided by 7? Yields: 4 Q-: Suppose -57 = -3*j + 63. Suppose 3*m + 4 = j. Calculate the remainder when m is divided by (-37)/(-5) + 4/(-10). Yields: 5 Q-: Calculate the remainder when ((-174)/(-9) + 0)*(-3)/(-2) is divided by 4. Yields: 1 Q-: Suppose 0 = -c - 5, 3*d = d + 4*c + 14. Calculate the remainder when (-2 - -26) + d/3 is divided by 8. Yields: 7 Q-: Let v(k) = -k**3 - 2*k**2 - 3*k - 8. Calculate the remainder when v(-4) is divided by 8. Yields: 4 Q-: Let v = 1049 - 847. Calculate the remainder when v is divided by 30. Yields: 22 Q-: Let u(w) = w**3 - 3*w**2 + 37. Calculate the remainder when 146 is divided by u(0). Yields: 35 Q-: Let b(k) = -k**3 + 9*k**2 + 6*k - 8. Let u be b(9). Let o = u + -3. Suppose -44*z - 1272 = -50*z. What is the remainder when z is divided by o? Yields: 40 Q-: Suppose 4*i - 3*b = -b + 2, 0 = -2*i - 4*b + 16. Suppose 0 = 3*o - 2*u - 24, -4*o + i*u + 31 = -1. What is the remainder when 22 is divided by o? Yields: 6 Q-: Let m(g) = 3*g + 3. What is the remainder when m(6) is divided by 9? Yields: 3 Q-: What is the remainder when 87/203 + (-11)/(-7) is divided by 1? Yields: 0 Q-: Suppose -9 = 2*p + p, -3*y + 2*p - 216 = 0. Let h = 106 + y. Calculate the remainder when h is divided by 8. Yields: 0 Q-: Let u = -53 - -75. Let z(r) = r**3 + 11*r**2 + 20*r - 3. Let n be z(-4). Suppose -214 = -n*g + 27*g. Calculate the remainder when g is divided by u. Yields: 19 Q-: Suppose 2*u - 3*x + x = 58, 3*u - 2*x - 85 = 0. Suppose -2*d + 3 = 1. Calculate the remainder when u is divided by d/((-2)/(-14) - 0). Yields: 6 Q-: Suppose -4*m + r = -50, 4*r + 0*r + 46 = 2*m. Suppose -a = -0*a - 141. What is the remainder when a is divided by m? Yields: 9 Q-: Let m = -35 - -80. What is the remainder when 87 is divided by m? Yields: 42 Q-: Let d(o) be the third derivative of -5*o**4/6 - o**3/6 + o**2. What is the remainder when d(-1) is divided by 10? Yields: 9 Q-: Suppose -2*o + 5*n - 22 + 139 = 0, o - 3*n - 56 = 0. What is the remainder when 1487 is divided by o? Yields: 67 Q-: Suppose a + 5*v - 27 = -54, 3*v = -5*a + 85. Calculate the remainder when (46 + -2)*(-10)/(-4) is divided by a. Yields: 18 Q-: Suppose m - 8 = 21. Let f = -128 - -55. Let b = f - -78. What is the remainder when m is divided by b? Yields: 4 Q-: Let t(u) = -u**2 + 2*u + 10. Let h be t(-5). Let c be (15/h)/((-3)/15). Suppose y = 6*y - c*i - 19, i - 2 = 0. What is the remainder when 34 is divided by y? Yields: 4 Q-: Suppose o - 227 = -4*v + 2*o, -3*v - 5*o + 199 = 0. Calculate the remainder when v is divided by 10. Yields: 8 Q-: Let h = -2094 + 2207. What is the remainder when 674 is divided by h? Yields: 109 Q-: Calculate the remainder when 1031 - (-8)/32*-72 is divided by 46. Yields: 1 Q-: Suppose 5*r = r + 4, 3*r + 191 = 2*t. Let u = 141 - t. What is the remainder when -15*8/(-36)*(-204)/(-8) is divided by u? Yields: 41 Q-: Let c(w) be the second derivative of w**3/2 - 9*w**2/2 - 2*w. What is the remainder when 41 is divided by c(8)? Yields: 11 Q-: Suppose -5*n + 5*t = 6 - 36, -4*n + 27 = -5*t. Suppose -n*h = -6*h + 222. What is the remainder when h is divided by 25? Yields: 24 Q-: Let u = 2182 + -1102. Suppose -52*y + 12*y + u = 0. Calculate the remainder when y is divided by ((-5)/4)/(1/(-4)). Yields: 2 Q-: Let f = 65 + -44. Let n = 63 - f. Let o = -33 + 240. Calculate the remainder when o is divided by n. Yields: 39 Q-: Let z = 246 - -13. Let y = 332 - z. Calculate the remainder when 137 is divided by y. Yields: 64 Q-: Suppose 0 = -2*z - 5*p + 59, 2*z - 55 = -3*p + 2*p. Let b be 9/z + 112/6. What is the remainder when 54 is divided by (-2 + 5)*b/3? Yields: 16 Q-: Let w(p) = 14*p - 52. What is the remainder when w(15) is divided by 53? Yields: 52 Q-: Let d = -25 - -18. Let l(k) = -2*k - 9. Let p be l(d). Suppose 3*n + 54 = p*n. Calculate the remainder when n is divided by 7. Yields: 6
[{"idx": "txt360/probability__swr_p_sequence_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-3.jsonl"}, {"idx": "txt360/numbers__div_remainder_composed_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-3.jsonl"}]
Install MVC 2 after Visual Studio 2010 Question: I have installed Visual Studio 2010 (final) and then Visual Studio 2008. Now I have to open a project with VS2008 that uses MVC2. Is there any problem to install MVC2 after VS2010? Comment: Visual Studio 2010 comes with MVC2 as standard. Comment: I know, but I have to use Visual Studio 2008 Answer: If you want to have the Visual Studio 2008 ASP.NET MVC Project Template, then yes you need to install it, otherwise the assemblies are already in the GAC. Also the project you are trying to open must have been created with VS2008. Answer: Go ahead and Install MVC2 , It will install into VS2008 , and it will leave the install of mvc2 in vs2010 alone. Also if you care, mvc3 works in vs2010 only, and it will install and live separately from mvc2 and allow you to choose from either, and as scottgu and others from microsoft mention, just install the mvc3 tooling update and it will automatically look to see if you have mvc3 install, and install everything if needed. Once again MVC3 will not uninstall or touch mvc2 from vs2008 or vs2010. I realize that you are asking about MVC2, so along with helping to answer that question, I thought I help assist with your MVC3 installation.<|endoftext|>Specifying column names with a defined structure Question: Assume I've a (used defined covariance) matrix and I want define the column names like this: <code>y <- matrix(rnorm(15*10),ncol=15) colnames(y) <- c("Var1", "Cov12", "Cov13","Cov14", "Cov15", "Var2", "Cov23", "Cov24", "Cov25", "Var3", "Cov34" , "Cov35" "Var4", "Cov45", "Var5") </code> where each row contained the variance or co variance for an date t. I want to find a more general way to assign the column names as above, because I'll not always have 5 different variances. I tried something with <code>rep</code> and <code>seq</code> but I didn't find a solution. Answer: Maybe not the most optimal way but we can do <code>n <- 5 paste0("Var", rep(1:n, n:1), unlist(sapply(2:n, function(x) c("",seq(x, n))))) [1] "Var1" "Var12" "Var13" "Var14" "Var15" "Var2" "Var23" "Var24" "Var25" "Var3" "Var34" "Var35" "Var4" "Var45" "Var5" </code> Breaking it down for better understanding <code>rep(1:n, n:1) #[1] 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5 unlist(sapply(2:n, function(x) c("",seq(x, n)))) #[1] "" "2" "3" "4" "5" "" "3" "4" "5" "" "4" "5" "" "5" </code> We take these outputs and <code>paste</code> them parallely with "Var" to get the desired column names.<|endoftext|>SQL Server Insert based of additional query Question: Using SQL server is it possible to to a mass insert based on a sub query, Essentially I'm trying to do this. <code>Insert into ProductExtra (ProductID,ExtraID) VALUES (Select ProductID From ProductSKU JOIN Product on ProductSKU.ProductID = Product.ID Where ItemType = 'fire grate' ), 10739 </code> Answer: Yes - but then you must not use the <code>VALUES</code> keyword, but this syntax (just a <code>SELECT</code>, with columns and fixed values defined in its list of selected columns) instead: <code>INSERT INTO ProductExtra (ProductID, ExtraID) SELECT ProductID, 10739 FROM ProductSKU JOIN Product ON ProductSKU.ProductID = Product.ID WHERE ItemType = 'fire grate' </code> Answer: use <code>INSERT INTO...SELECT</code> statement. <code>INSERT INTO ProductExtra (ProductID, ExtraID) Select ProductID, 10739 ExtraID From ProductSKU INNER JOIN Product ON ProductSKU.ProductID = Product.ID Where ItemType = 'fire grate' </code> Answer: You can try like this <code>INSERT INTO ProductExtra (ProductID,ExtraID) Select ProductID,10739 From ProductSKU JOIN Product on ProductSKU.ProductID = Product.ID Where ItemType = 'fire grate' </code><|endoftext|>Wordpress search should display only products as a dropdown Question: I am using flatsome theme in wordpress and i want to customize the search which should display only products and not pages or posts in search filter results as a dropdown and should search only products also. Please refer the screenshot ,red marked area should omitted from search results.Please help me with this Comment: What have you tried? You can override the code via a WordPress child theme. Please also ref: [IDX] i tried this code,but did not work. Comment: i think this code is for default search for wordpress, it is search form in flatsome theme Comment: Yes, you will need to override the flatsome theme files within your WordPress child theme. Comment: yes i think it needed search hook to change this feature, i dont know which hook to use Comment: Look in the theme folder. In your code editor you can search for a specific element in all files/folders. Answer: You need to overrule the file <code>themes/flatsome/inc/extensions/flatsome-live-search/flatsome-live-search.php</code> in your child theme and remove <code>, 'page' </code> from line 23. This only removes the pages from your Ajax search though, they still appear on the search results after.<|endoftext|>Error when try to delete row in access database Question: Hello guys i`m trying to delete a row in a access database but when i try to update the dataset it give me this error <code>Update requires a valid DeleteCommand when passed DataRow collection with deleted rows. </code> I tryed to solve it on my own but i cant seem to fix it. So if anyone can give me an advice i will be very thankful. Here is my code. <code> currentRow = e.RowIndex; ds1 = new DataSet(); con = new System.Data.OleDb.OleDbConnection(); con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=DataSource/PhoneBookData.mdb"; con.Open(); string sql = "SELECT * From CONTACT"; da = new System.Data.OleDb.OleDbDataAdapter(sql, con); da.Fill(ds1, "CONTACT"); DataRow dRow = ds1.Tables["CONTACT"].Rows[0]; ds1.Tables["CONTACT"].Rows[currentRow].Delete(); da.Update(ds1, "CONTACT"); </code> Thanks for all the help in advance. Answer: The exception is exact on what your problem is - you are missing the DeleteCommand in the adapter: <code>da = new System.Data.OleDb.OleDbAdapter( ... ); da.DeleteCommand = "DELETE ...."; </code><|endoftext|>Preprocessor Stringizing Operator with String Literal Prefixes Question: So I want to do the traditional thing to do with the stringizing operator in a macro: <code>#define FOO(x) foo(#x, (x)) </code> However I need to use a string literal prefix: [IDX] is a problem because if I need a UTF-32 string literal I try to do this: <code>#define FOO(x) foo(U#x, (x)) </code> But gcc 4.9.2 complains: error: 'U' was not declared in this scope Is there a way to make the compiler treat the <code>U</code> as a prefix to the stringized macro variable? Answer: Yes, use concatenation: <code>#define CONCAT2(x, y) x ## y #define CONCAT(x, y) CONCAT2(x, y) #define STRINGIZE(x) #x #define FOO(x) foo(CONCAT(U, STRINGIZE(x)), (x)) </code> The extra indirection, besides being good if you pass a macro that should be evaluated first, is "needed" because of N3936 §16.3.2 [cpp.stringize]/2, which says: The order of evaluation of # and ## operators is unspecified. Comment: @JonathanMee, [It is]( [IDX] in the 2015 preview! Comment: @leemes, You're good as long as the result is a *preprocessing-token*. `U"abc"` is a *string-literal*, which is a *preprocessing-token*. Comment: @leemes The `U"abc"` string literal is not defined at all on Visual Studio T.T<|endoftext|>SVN compare with context menu is disabled - IntelliJ Question: I recently switched from Eclipse to IntelliJ. My project uses SVN. In IntelliJ I can commit or update code just fine. However, when I want to compare the current code base with the latest from repository, in Context Menu, <code>Subversion > Compare with Latest Repository Version</code>, this menu is disabled. Same for other Compare With menu or Show Current Revision. Can anyone help? Thanks Comment: Are you sure that the file is recognized by SVN? Comment: @Makoto: which file you are talking abt? For files in the project, I can commit or update normally (right click, subversion > Commit Directory or Update Directory). But I can not compare with remote repository. This option is grey. Comment: Are you sure that IntelliJ recognizes that the file is recognized by SVN? Answer: IntelliJ IDEA does not currently support the "Compare" actions on directories for Subversion. You can invoke "Compare" on individual files, and you can use the Changes | Repository view to see the latest commits to the repository. The corresponding feature request is [IDX] I see. That's right, the context menu is enabled when I only select individual file. How can they not have this capability.<|endoftext|>How come when I subdivide an edge, it only continues to subdivide one side? Question: I'm trying to create more vertices in an edge so I subdivide it, but for some reason, after I subdivide it once, it decides to only select one half of the subdivide. This messes with my faces when I then try to move them to shape them into what I'm modeling. Before subdivide: After first subdivide: After second subdivide: What it's supposed to look like: It creating a weird face under on my model: Comment: best practice is to avoid ngons while modeling. having ngons would cause such problems. Answer: It's because the face on the right is already subdivided, and so is the edge between them. You should have subdivide them both at the same time. You could fix this by selecting all the vertical edges between the faces and rip them (shortcut v). Then remove excess verts (select them and <code>x</code> -> <code>Dissolve Vertices</code>) on the face you're trying to subdivide. Subdivide the face. The verts on the right should allign. Now you have duplicated vertices in that region. Remove them by selecting all vers in the region (you'll probably have to turn on X-ray (<code>alt+Z</code>) to reach the duplicates) using <code>Merge by Distance</code>.
[{"idx": "Install_MVC_2_after_Visual_Studio_2010", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-23288.jsonl"}, {"idx": "Specifying_column_names_with_a_defined_structure", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-23288.jsonl"}, {"idx": "SQL_Server_Insert_based_of_additional_query", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-23288.jsonl"}, {"idx": "Wordpress_search_should_display_only_products_as_a_dropdown", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-23288.jsonl"}, {"idx": "Error_when_try_to_delete_row_in_access_database", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-23288.jsonl"}, {"idx": "Preprocessor_Stringizing_Operator_with_String_Literal_Prefixes", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-23288.jsonl"}, {"idx": "SVN_compare_with_context_menu_is_disabled_-_IntelliJ", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-23288.jsonl"}, {"idx": "How_come_when_I_subdivide_an_edge,_it_only_continues_to_subdivide_one_side?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-23288.jsonl"}]
calculus: differentiate ----------------------- Puzzle: What is the second derivative of -63*p**2*t**2 + 30*p**2*t - 3*p**2 + 20*p*t**2 - 2*p*t - 2*t**2 - 99 wrt p? Explanation: -126*t**2 + 60*t - 6 Puzzle: What is the second derivative of 295432*r**4 - 5*r**3 + r**2 + 334694*r + 2 wrt r? Explanation: 3545184*r**2 - 30*r + 2 Puzzle: What is the third derivative of 562*w**4 + w**2 - 2335*w wrt w? Explanation: 13488*w Puzzle: Find the third derivative of 11304*m*v**4 - 6*m*v**3 + 436*m + 7*v**4 - 3*v**3 - 19045*v**2 wrt v. Explanation: 271296*m*v - 36*m + 168*v - 18 Puzzle: Find the first derivative of -z**4 - 789*z + 6224 wrt z. Explanation: -4*z**3 - 789 Puzzle: What is the third derivative of -2*v**5*w - 207*v**3 - 2*v**2*w + 18*v*w wrt v? Explanation: -120*v**2*w - 1242 Puzzle: Find the second derivative of 3*j*l**2*w**3 + 40*j*l**2*w - 2*j*l - 7521*j*w**3 + 13*l**2*w**2 - 2*l*w**3 wrt l. Explanation: 6*j*w**3 + 80*j*w + 26*w**2 Puzzle: Find the second derivative of 2*n**3*x - 148*n**3 + 10*n**2*x + 3*n*x + n - 123*x wrt n. Explanation: 12*n*x - 888*n + 20*x Puzzle: Find the third derivative of 712*p**6 - 19*p**2 + 1. Explanation: 85440*p**3 Puzzle: Find the third derivative of -9*l*o**3 + 8*l*o**2 - l*q + o**3*q**2 - 3*o**3 - o*q**2 - 2*q**2 wrt o. Explanation: -54*l + 6*q**2 - 18 Puzzle: What is the second derivative of 537*m**3 + 19*m**2 + 71095*m wrt m? Explanation: 3222*m + 38 Puzzle: What is the third derivative of -7688*a**2*x**3 - 44*a**2*x**2 - 2*a**2*x + 2*a*x**4 + 2*a + 6 wrt x? Explanation: -46128*a**2 + 48*a*x Puzzle: What is the third derivative of -6407*h**6 + 5357*h**2? Explanation: -768840*h**3 Puzzle: Differentiate -8959139*y**2 + 44954507 with respect to y. Explanation: -17918278*y Puzzle: What is the third derivative of 3392358*u**3 - u**2 - 10*u - 19468 wrt u? Explanation: 20354148 Puzzle: What is the second derivative of 4*q**5 + 1403*q**3 + 197*q**2 - 112087*q - 1? Explanation: 80*q**3 + 8418*q + 394 Puzzle: Differentiate 5*q*s**2 - 211*q*s + 3442*s**2 wrt q. Explanation: 5*s**2 - 211*s Puzzle: What is the second derivative of -290*r**4 + 1228*r**3 + 3*r**2 - 432*r + 13082? Explanation: -3480*r**2 + 7368*r + 6 Puzzle: Find the second derivative of 127575*k**5 + 4845*k - 26 wrt k. Explanation: 2551500*k**3 Puzzle: What is the second derivative of -6*q**2*u**2 + 3*q**2 + 91*q*u**2 + q*u - 101 wrt u? Explanation: -12*q**2 + 182*q Puzzle: What is the third derivative of -45943672*j**6 - 27773687*j**2 wrt j? Explanation: -5513240640*j**3 Puzzle: Find the second derivative of -12836*q**3*r**2*s + 57*q**3*r + 2*q**3*s**2 - 131*q**2*r**2*s**2 - 119745*q*r*s**2 wrt r. Explanation: -25672*q**3*s - 262*q**2*s**2 Puzzle: Find the second derivative of -5127*b**2 - 9856*b + 4 wrt b. Explanation: -10254 Puzzle: Find the second derivative of 289372*h**4 + 1029069*h. Explanation: 3472464*h**2 Puzzle: What is the third derivative of -8278875*t**6 + 20622775*t**2? Explanation: -993465000*t**3 Puzzle: What is the first derivative of -o**3*p + 2*o**2*p - 546*o*p - 1941*p wrt o? Explanation: -3*o**2*p + 4*o*p - 546*p Puzzle: Find the second derivative of 76*u*z**2 - 10*u*z + 308*z**2 - 127 wrt z. Explanation: 152*u + 616 Puzzle: Find the second derivative of -412*t**4 + 3*t**2 - 2*t + 1249 wrt t. Explanation: -4944*t**2 + 6 Puzzle: Find the third derivative of -839776*a**5 - 96660*a**2 - 5. Explanation: -50386560*a**2 Puzzle: What is the derivative of 42*a*j*q**2 + 6*a*j + a*q**2 + a*q + a + 202*q wrt j? Explanation: 42*a*q**2 + 6*a Puzzle: Find the third derivative of 2069823*n**6 - 2*n**3 - 7877084*n**2. Explanation: 248378760*n**3 - 12 Puzzle: Find the second derivative of 4*g**2*s + 8584*g**2*y**2 - 2*g*s + g - 2*s*y**2 - 213*y wrt g. Explanation: 8*s + 17168*y**2 Puzzle: Find the second derivative of -1132846*d**2 - 595064*d wrt d. Explanation: -2265692 Puzzle: Find the first derivative of 33456175*f - 50190106 wrt f. Explanation: 33456175 Puzzle: What is the derivative of -30*q*s**2 + 6*q - 2*s**2 + 8746*s wrt q? Explanation: -30*s**2 + 6 Puzzle: What is the third derivative of -33988985*w**6 - 83*w**2 + 54823*w wrt w? Explanation: -4078678200*w**3 Puzzle: What is the third derivative of -665*g**4 - 2*g**3 + 2*g**2 - 2102? Explanation: -15960*g - 12 Puzzle: Find the third derivative of -4*r**4 - 223*r**3 + 2*r**2 + 49. Explanation: -96*r - 1338 Puzzle: Find the second derivative of 2077*d**2*m**2 + 219*d - 2*m**2 wrt d. Explanation: 4154*m**2 Puzzle: What is the third derivative of 11*l*y**4 - 2624*l*y**3 - l*y**2 + l*y - y**4 + 2*y**3 + y**2 - 34686 wrt y? Explanation: 264*l*y - 15744*l - 24*y + 12 Puzzle: What is the third derivative of 34*j**3*m**3 + j**3 + 336*j**2*m**2 - j*m**2 - 61*m**3 wrt m? Explanation: 204*j**3 - 366 Puzzle: What is the third derivative of 753300*i**6 - 7377*i**2 - 45*i? Explanation: 90396000*i**3 Puzzle: Differentiate 2*j**3*m**3 - 3930*j**3 + 110201*j**2*m**3 - 12*j**2 with respect to m. Explanation: 6*j**3*m**2 + 330603*j**2*m**2 Puzzle: What is the second derivative of 360137482*m**4 + 39*m - 162407 wrt m? Explanation: 4321649784*m**2 Puzzle: Find the second derivative of 5894*k**3 - 4*k**2 - 571128*k wrt k. Explanation: 35364*k - 8 Puzzle: What is the second derivative of 9*z**4 + 68*z**3 + 505*z**2 - 9671240*z? Explanation: 108*z**2 + 408*z + 1010 Puzzle: Find the first derivative of -3*j*s**2 + 1723*j - 22*s**4 wrt s. Explanation: -6*j*s - 88*s**3 Puzzle: What is the second derivative of -31758*i**5 - i**3*p - 2*i**3 + 26*i*p - 40*i - 3*p + 11 wrt i? Explanation: -635160*i**3 - 6*i*p - 12*i Puzzle: What is the third derivative of -557*a**3 + 339*a**2? Explanation: -3342 Puzzle: Find the third derivative of -92927*p**5 + 395*p**2 - 14*p + 2 wrt p. Explanation: -5575620*p**2 Puzzle: What is the second derivative of o**2*y - 79925754*o**2 + 510*o*y + 5*o - 4530*y wrt o? Explanation: 2*y - 159851508 Puzzle: What is the third derivative of -2*f**3*i**4 + 102226*f**3 + 4195*f**2*i**5 + 2*f*i**2 wrt i? Explanation: -48*f**3*i + 251700*f**2*i**2 Puzzle: Differentiate -7*h*z**2 - 17*h*z + 5826*z**2 wrt h. Explanation: -7*z**2 - 17*z Puzzle: What is the derivative of -307*h**3*j + 14*h**2*j + h*j**2 - 7445*j**2 + 14*j wrt h? Explanation: -921*h**2*j + 28*h*j + j**2 Puzzle: What is the first derivative of -975731152*k**2 - 923620496 wrt k? Explanation: -1951462304*k Puzzle: Find the first derivative of -4752*r + 1956 wrt r. Explanation: -4752 Puzzle: Differentiate -225*l**4*x**2 - 2*x**2 - 92*x wrt l. Explanation: -900*l**3*x**2 Puzzle: Find the third derivative of 8*a**6*r + 48*a**4*r**2 - 3*a**2*r**2 - 2*r**2 + 57 wrt a. Explanation: 960*a**3*r + 1152*a*r**2 Puzzle: What is the derivative of -80256015*v + 22873816 wrt v? Explanation: -80256015 Puzzle: Find the first derivative of -2605104*m**2 + 7582278 wrt m. Explanation: -5210208*m Puzzle: What is the third derivative of -5662776*h**3 + 18*h**2 + 103813 wrt h? Explanation: -33976656 Puzzle: Differentiate -4*h*u**3 + 8*h + 26*u**4 - 20 wrt u. Explanation: -12*h*u**2 + 104*u**3 Puzzle: Find the second derivative of 1750412*p**3 + 5*p + 193569 wrt p. Explanation: 10502472*p Puzzle: What is the derivative of 24854*b - 14312? Explanation: 24854 Puzzle: Find the third derivative of 200*t**3 + 155*t**2 - 2 wrt t. Explanation: 1200 Puzzle: Differentiate -49096*b**3*h + 3*b**3 - 2*b**2*h - 16*b + h + 625 wrt h. Explanation: -49096*b**3 - 2*b**2 + 1 Puzzle: Find the second derivative of -64*b**4 - 2*b**2 - 449*b wrt b. Explanation: -768*b**2 - 4 Puzzle: What is the third derivative of -33*g**3*m - 2*g**3 + 34*g**2*m + 2*m wrt g? Explanation: -198*m - 12 Puzzle: Find the second derivative of 79281*c**2 - 17927*c wrt c. Explanation: 158562 Puzzle: Find the first derivative of f**4 + 16*f**3*i - 177*i wrt f. Explanation: 4*f**3 + 48*f**2*i Puzzle: What is the derivative of 11*n**2 + 9146*n + 1076695 wrt n? Explanation: 22*n + 9146 Puzzle: Find the third derivative of 18*a**4*g - 770*a**3*g - 4*a**2*g - 3*a**2 + a*g + 21*g wrt a. Explanation: 432*a*g - 4620*g Puzzle: Find the second derivative of 6*k**3 + 1066*k**2*m**2 - k**2 - 3*k*m**2 + 20*k - 23*m**2 wrt k. Explanation: 36*k + 2132*m**2 - 2 Puzzle: What is the second derivative of 2*a**2*w**2 + 429*a**2*w - 3*a*w**2 - 1076*w**2 wrt a? Explanation: 4*w**2 + 858*w Puzzle: What is the second derivative of -2*g**5 + 10351429*g**3 + 60153605*g? Explanation: -40*g**3 + 62108574*g Puzzle: Differentiate -96733953*g*s - 49726817*g wrt s. Explanation: -96733953*g Puzzle: Find the third derivative of 18883*t**3 + 945*t**2 - 7*t + 1 wrt t. Explanation: 113298 Puzzle: Differentiate -2628*h**2*x*z - h**2 - 2468*h*x + 2*x wrt z. Explanation: -2628*h**2*x Puzzle: Find the first derivative of 34*r**3*w**2*y + 5*r**3 - 2*r**2*w**2 - 60*r**2*w - 2*r - 82*w**2*y wrt y. Explanation: 34*r**3*w**2 - 82*w**2 Puzzle: Find the second derivative of -3*p**2*s**2*v - 16*p**2*s**2 - 2*p**2*s*v + 2*p**2*s - 3*p**2*v - p*s**3*v + p wrt s. Explanation: -6*p**2*v - 32*p**2 - 6*p*s*v Puzzle: Differentiate -281734*h*p**2 - 458*p**2 + 24 wrt h. Explanation: -281734*p**2 Puzzle: Find the third derivative of -3*l**5 + 143*l**4*v**3 + 3*l**2*v + 16*l**2 - v**3 wrt l. Explanation: -180*l**2 + 3432*l*v**3 Puzzle: What is the second derivative of -81*p**2*u + 11*p**2 + 19*p*u - 2*p - 33*u wrt p? Explanation: -162*u + 22 Puzzle: What is the first derivative of -i**3 - 31*i**2 - 19*i - 7120 wrt i? Explanation: -3*i**2 - 62*i - 19 Puzzle: Find the second derivative of 6*d**3 + 6612*d**2 - 67*d + 1569. Explanation: 36*d + 13224 Puzzle: What is the second derivative of 12*r**5 + r**3 - 1062*r**2 - 2036*r - 24 wrt r? Explanation: 240*r**3 + 6*r - 2124 Puzzle: Differentiate -550104487*g**3*n**4 - 193267*g**3 + 615*g**2 wrt n. Explanation: -2200417948*g**3*n**3 Puzzle: What is the third derivative of 1292*g**4 - 3038*g**2 wrt g? Explanation: 31008*g Puzzle: Find the second derivative of -237*t**2 + 649*t wrt t. Explanation: -474 Puzzle: What is the derivative of -18*r**3 + 59*r**2 - 4901*r + 55252331? Explanation: -54*r**2 + 118*r - 4901 Puzzle: What is the third derivative of 121*t**5 + 20*t**4 + 4*t**2 + 89 wrt t? Explanation: 7260*t**2 + 480*t Puzzle: What is the third derivative of -9866*s**4 - 6*s**3 - 1011*s**2 + 32? Explanation: -236784*s - 36 Puzzle: What is the second derivative of -10828*x**5 + 4*x**2 - 58116*x? Explanation: -216560*x**3 + 8 Puzzle: Find the second derivative of 1016*r**3 + r**2*x**3 - r*x**3 - 18*x**3 wrt r. Explanation: 6096*r + 2*x**3 Puzzle: Differentiate 2217*r**2 - 1488 wrt r. Explanation: 4434*r Puzzle: What is the third derivative of -950091*h**5*p**3 - 4*h**2*p**3 + 26387*h**2*p**2 wrt h? Explanation: -57005460*h**2*p**3 Puzzle: What is the derivative of 43947*n**3*u + n**2 - 15*n + 167*u + 58181 wrt n? Explanation: 131841*n**2*u + 2*n - 15 Puzzle: Differentiate -7634*a**2*g**3 - 46*a**2*g**2 + 5311*a**2 + 64*a with respect to g. Explanation: -22902*a**2*g**2 - 92*a**2*g Puzzle: Find the first derivative of -3*s**2 + 29762*s + 731651 wrt s. Explanation: -6*s + 29762 Puzzle: What is the third derivative of -3*u**3*x**3 + 62*u**3 - u**2*x + u*x**3 wrt u? Explanation: -18*x**3 + 372 Puzzle: Find the third derivative of 3202*w**4 + w**3 + 2*w**2 - w + 1056. Explanation: 76848*w + 6 Puzzle: What is the second derivative of -8629040*a**2 - 379*a - 1795 wrt a? Explanation: -17258080 Puzzle: What is the second derivative of -2627*t**4 + 301*t wrt t? Explanation: -31524*t**2 Puzzle: Find the second derivative of -2*k**4*m**2 - 67144*k**2*m**3 - k*m**3 - 2*k + 409*m**3 + 4*m wrt k. Explanation: -24*k**2*m**2 - 134288*m**3 Puzzle: What is the first derivative of 1756763*o + 1833359? Explanation: 1756763 Puzzle: What is the derivative of -21*h**4 - h**3 + 19410*h**2 + 279463916 wrt h? Explanation: -84*h**3 - 3*h**2 + 38820*h Puzzle: What is the third derivative of 2886*z**5 - 2497*z**4 - 13883242*z**2 wrt z? Explanation: 173160*z**2 - 59928*z Puzzle: Find the first derivative of 18*x**2 + 169903*x - 3843516. Explanation: 36*x + 169903 Puzzle: What is the third derivative of -924*i**3*m + 300*i**3 + 178*i**2*m + 1076*i**2 wrt i? Explanation: -5544*m + 1800 Puzzle: Differentiate -2380061*z**4 + 2224480 wrt z. Explanation: -9520244*z**3 Puzzle: Find the third derivative of -3943*h**6 + 938*h**4*z + 4*h**2*z - 10839*h**2 + 2*h*z wrt h. Explanation: -473160*h**3 + 22512*h*z Puzzle: Find the second derivative of -f**5*w**2 + 48*f**2*w**3 + 3*f*w**3 - 16*w**3 wrt f. Explanation: -20*f**3*w**2 + 96*w**3 Puzzle: What is the second derivative of -42*q**4 - 42*q? Explanation: -504*q**2 Puzzle: What is the second derivative of -34831043*j**5*l + 3*j*l + 5137*j + 26*l wrt j? Explanation: -696620860*j**3*l Puzzle: Find the second derivative of -5587933*k**2 + k - 613401 wrt k. Explanation: -11175866 Puzzle: Differentiate 165947*q**3 - 249338. Explanation: 497841*q**2 Puzzle: What is the third derivative of 61875*q**3 + 178517*q**2 + q wrt q? Explanation: 371250 Puzzle: Find the first derivative of -216613*k*y + 5111*k - 73 wrt y. Explanation: -216613*k Puzzle: What is the third derivative of 6*m**5*r**2 - 400725*m**3*r**2 - 2*m**2*r**2 + 27230*r**2 wrt m? Explanation: 360*m**2*r**2 - 2404350*r**2 Puzzle: What is the third derivative of -455090*a**3 - a**2 - 840205 wrt a? Explanation: -2730540 Puzzle: What is the second derivative of -4180*z**3 + 183*z + 66 wrt z? Explanation: -25080*z Puzzle: What is the second derivative of 2*j**2*o**5 - 297*j**2*o - 8*j - 285*o**5 wrt o? Explanation: 40*j**2*o**3 - 5700*o**3 Puzzle: What is the first derivative of -496*r**3 - 10*r - 4427? Explanation: -1488*r**2 - 10 Puzzle: Find the third derivative of -2*s**4 - 571953*s**3 - 4109*s**2 - 3*s + 20. Explanation: -48*s - 3431718 Puzzle: Differentiate 12*s**4 + 23*s**3 + 7781*s + 11133026. Explanation: 48*s**3 + 69*s**2 + 7781 Puzzle: Find the second derivative of -g*o**2*s**2 - g*o*s**2 - 6*g*s + 3*o**2*s**2 - o**2*s - 620*o*s + s**2 wrt s. Explanation: -2*g*o**2 - 2*g*o + 6*o**2 + 2 Puzzle: Find the third derivative of 2*j**3*l**3*x - j**3*l*x + 4*j**3*l - 2*j**2*l**3*x - j**2*l**3 - 29*j**2*x + 4*l*x wrt j. Explanation: 12*l**3*x - 6*l*x + 24*l Puzzle: Find the third derivative of -532313*i**6*n**2 - 302*i**2*n**2 - 6*i**2 - 2*i + 8*n**2 wrt i. Explanation: -63877560*i**3*n**2 Puzzle: Find the second derivative of -6*d*s**3 + 4*d*s**2 - 815*d*s + 492*d - 29066*s**3 wrt s. Explanation: -36*d*s + 8*d - 174396*s Puzzle: What is the third derivative of -12906772*j**3 + 1604547*j**2 - 1 wrt j? Explanation: -77440632 Puzzle: Differentiate 6*i**4 + 5066985*i*v + 212634875*v with respect to i. Explanation: 24*i**3 + 5066985*v Puzzle: Find the third derivative of 6*q**5 - q**4 + 348*q**3 - 2*q**2 - 3*q + 1126. Explanation: 360*q**2 - 24*q + 2088 Puzzle: Find the second derivative of -759*o**2*t**2*z + 14*o**2*t*z**2 - 2*o**2*z + 4*t**2*z**2 + 6*t*z + t wrt t. Explanation: -1518*o**2*z + 8*z**2 Puzzle: What is the second derivative of 103*r**5*t + r**3*t**3 + r*t**3 - 217*r*t**2 wrt r? Explanation: 2060*r**3*t + 6*r*t**3 Puzzle: Differentiate -2927691*o**2 - 191961 wrt o. Explanation: -5855382*o Puzzle: Find the third derivative of -53*g*v*x**3 - g*v*x - 2*g*x**2 + 31*g*x + 1669*v*x**3 - v*x**2 - 3*v*x - 5*x**2 wrt x. Explanation: -318*g*v + 10014*v Puzzle: What is the third derivative of -n**3*t**6 - 9975689*n**3*t**3 - 2*n**3*t**2 - 2*n**3 - 869258*n**2*t**2 + 2*n*t**2 wrt t? Explanation: -120*n**3*t**3 - 59854134*n**3 Puzzle: Differentiate -51*q**4 + 2*q**3 - 2013. Explanation: -204*q**3 + 6*q**2 Puzzle: What is the third derivative of -14*k**6*w**2 - 2341*k**3 - 4148*k**2*w**2 - 3*k**2 wrt k? Explanation: -1680*k**3*w**2 - 14046 Puzzle: What is the derivative of -1691*a*g*j**2 - 14*g*j + j**2 - 5 wrt a? Explanation: -1691*g*j**2 Puzzle: Differentiate -166*o*p + 26*p + 1 wrt o. Explanation: -166*p Puzzle: Find the third derivative of 3*c*d**3 + 7*c*d**2 - c*d + 2*c - 5577812*d**3 + 97*d**2 + 2147 wrt d. Explanation: 18*c - 33466872 Puzzle: Find the third derivative of 98019*p**3 - 22*p**2 - 210*p + 1 wrt p. Explanation: 588114 Puzzle: Find the third derivative of 1084680*g**2*s**3 + 80*g**2*s**2 - 4*g**2*s + 990*g**2 + 4*g*s**3 + 2*g*s wrt s. Explanation: 6508080*g**2 + 24*g Puzzle: What is the derivative of -2012*n*w**2 - 641*n - w**4 - 14096*w**2 + 81244 wrt w? Explanation: -4024*n*w - 4*w**3 - 28192*w Puzzle: What is the second derivative of 160658*m**2 + 122*m - 208? Explanation: 321316 Puzzle: What is the second derivative of -555308*a*c**4 - 3*a*c**2 - 34*a*c + 101*a + 52*c - 13 wrt c? Explanation: -6663696*a*c**2 - 6*a Puzzle: What is the second derivative of 43461922*u**2 + 7130305*u? Explanation: 86923844 Puzzle: Find the second derivative of -13215*p**4 - 85*p + 1. Explanation: -158580*p**2 Puzzle: Find the second derivative of -155*x**3 + 31*x. Explanation: -930*x Puzzle: Find the first derivative of -2*a**3*q - 3*a**3 + 985*a**2*q + 192 wrt q. Explanation: -2*a**3 + 985*a**2 Puzzle: What is the first derivative of -26*n**2*s + 499*n*s + 24285*s + 2 wrt n? Explanation: -52*n*s + 499*s Puzzle: What is the derivative of -13951*c**2 + 8976 wrt c? Explanation: -27902*c Puzzle: Differentiate -31892219*a - 128397040 with respect to a. Explanation: -31892219 Puzzle: Find the second derivative of 2*f*p**3*x**2 + 2*f*p**3 + 10*f*p**2*x - 7184985*f*p*x**2 - 11*f*p*x + 2*f + 2 wrt x. Explanation: 4*f*p**3 - 14369970*f*p Puzzle: Find the first derivative of -523*c**3 - c - 238 wrt c. Explanation: -1569*c**2 - 1 Puzzle: What is the second derivative of 158381*z**4 + 13*z**3 + 32*z - 30666? Explanation: 1900572*z**2 + 78*z Puzzle: Find the third derivative of -13*b**5 - 258*b**3 - 1149*b**2 + 4*b wrt b. Explanation: -780*b**2 - 1548 Puzzle: What is the third derivative of -376174664*v**5 - v**2 - 1447765*v? Explanation: -22570479840*v**2 Puzzle: Find the third derivative of 587455239*l**4 + 23*l**2 - 23571*l + 17 wrt l. Explanation: 14098925736*l Puzzle: What is the derivative of -71*y**3 - 73*y**2 + 6880 wrt y? Explanation: -213*y**2 - 146*y Puzzle: What is the derivative of -2*a**3 - 4801*a**2 - 9*a - 583021? Explanation: -6*a**2 - 9602*a - 9 Puzzle: What is the derivative of -p**2 + 9377*p - 53539? Explanation: -2*p + 9377 Puzzle: Differentiate -2*a**3*s**2 - 5549*a**3 + 2*a*s - s**2 + 944*s wrt s. Explanation: -4*a**3*s + 2*a - 2*s + 944 Puzzle: Find the first derivative of 10*j**3 - 2*j + 1 wrt j. Explanation: 30*j**2 - 2 Puzzle: Find the third derivative of 99575*n**4 - 34641*n**2 wrt n. Explanation: 2389800*n Puzzle: What is the first derivative of -54626*b*j - 14*b + 18291958*j wrt b? Explanation: -54626*j - 14 Puzzle: Differentiate -94*k**2 + 2*k - 214 with respect to k. Explanation: -188*k + 2 Puzzle: Find the third derivative of 565*d**5 + 12*d**2 - 23 wrt d. Explanation: 33900*d**2 Puzzle: What is the first derivative of -431144809*y**3 - 864526647 wrt y? Explanation: -1293434427*y**2 Puzzle: What is the third derivative of -1376263410*h**3*x - 6286*h**2 - 340*h - 3*x + 1 wrt h? Explanation: -8257580460*x Puzzle: What is the derivative of -25473*h**3 - 11803? Explanation: -76419*h**2 Puzzle: What is the second derivative of 133*c**3*j**2 + 2*c**3*j - c - 2*j**4 - 147*j wrt j? Explanation: 266*c**3 - 24*j**2 Puzzle: Find the third derivative of 1326*a**3*l**2*r**3 + 11*a**3*l**2*r + 209*a**3*l*r**3 + 13*a**3*l + 13*a**3 - 7*l**2*r - 8*r**2 wrt r. Explanation: 7956*a**3*l**2 + 1254*a**3*l Puzzle: What is the derivative of 2*k**2*w**3 + 1255*k**2*w**2 - 37*k**2 - 2718*w**3 + 2*w**2 - 15*w + 2 wrt k? Explanation: 4*k*w**3 + 2510*k*w**2 - 74*k Puzzle: What is the third derivative of 246978381*l**5 + 170994936*l**2 wrt l? Explanation: 14818702860*l**2 Puzzle: Find the third derivative of 364*j**3 - 666*j**2. Explanation: 2184 Puzzle: Find the second derivative of 712*z**2 - 193*z wrt z. Explanation: 1424 Puzzle: What is the second derivative of 41442011*g**4 + 2485842*g + 33 wrt g? Explanation: 497304132*g**2 Puzzle: Find the first derivative of m**4*q**3*r**3 + 247*m*q*r**3 + q**3*r**3 + 46*q*r**3 + 6*r**3 wrt m. Explanation: 4*m**3*q**3*r**3 + 247*q*r**3 Puzzle: What is the third derivative of 32723*a**4 - a**3 + 16*a**2 - 46*a - 16 wrt a? Explanation: 785352*a - 6 Puzzle: Find the first derivative of 303*n**4 - 203 wrt n. Explanation: 1212*n**3 Puzzle: Find the second derivative of -2076*c**2*x**2 + 634661*c**2*x - 183*x**5 wrt x. Explanation: -4152*c**2 - 3660*x**3 Puzzle: Differentiate 33*r*t*z**3 + 21*r*t*z**2 - 3*r*z**2 + 21*t*z**3 + 5*z**3 - 17 wrt r. Explanation: 33*t*z**3 + 21*t*z**2 - 3*z**2 Puzzle: Find the third derivative of -65*m**3*p**4 + 36*m**3*p + 2*m*p**6 + m + 5*p**2 wrt p. Explanation: -1560*m**3*p + 240*m*p**3 Puzzle: Differentiate 4*p**3*q**2 - 27*p**3*q + p**3 + 137*p - 2*q**2 with respect to q. Explanation: 8*p**3*q - 27*p**3 - 4*q Puzzle: Find the second derivative of 4*n**5 - 30055*n**3 + 10*n + 10321 wrt n. Explanation: 80*n**3 - 180330*n Puzzle: Find the second derivative of 230*w**3 - 63*w. Explanation: 1380*w Puzzle: What is the derivative of -70*n**4 - 5*n**3 + 3781 wrt n? Explanation: -280*n**3 - 15*n**2 Puzzle: Find the third derivative of 14*j**5*t + 6*j**4*t - 2*j**2*t - 2*j*t + t wrt j. Explanation: 840*j**2*t + 144*j*t Puzzle: Find the first derivative of -22*u**3 - 5*u**2 + 13*u - 71092 wrt u. Explanation: -66*u**2 - 10*u + 13 Puzzle: What is the second derivative of -401*m*q**3 - 5*m*q + 6*q wrt q? Explanation: -2406*m*q Puzzle: What is the third derivative of 365*i**6 - 10*i**4 - 2424*i**2 - 2*i wrt i? Explanation: 43800*i**3 - 240*i Puzzle: Find the second derivative of 2*p**4 - 51*p**3 + 82*p. Explanation: 24*p**2 - 306*p<|endoftext|>numbers: div remainder composed ------------------------------- Inquiry: Let u = -156 - -226. Let w(t) = t**3 - 7*t**2 + 8*t + 5. Let y be w(7). Let z = y + -43. Calculate the remainder when u is divided by z. Math A: 16 Inquiry: Suppose 375*q - 379*q + 36 = 0. Let j be (1 - 0)*(-2 + 29). Let b = q + j. What is the remainder when b is divided by 14? Math A: 8 Inquiry: Let l = -7 - -13. What is the remainder when 15 is divided by l? Math A: 3 Inquiry: Let i = -6501 - -6754. Calculate the remainder when i is divided by 91. Math A: 71 Inquiry: Let w(b) = 6*b - 4. Let o be 44/(-6) - 8/(-24). Let f(g) = g**3 + 7*g**2 - 3*g - 2. Calculate the remainder when w(10) is divided by f(o). Math A: 18 Inquiry: What is the remainder when (6/18 - 0)*3036 is divided by 78? Math A: 76 Inquiry: Let r(u) be the third derivative of 3*u**4/8 - u**3/3 - 2*u**2. Suppose -4*n + 49 = 3*m + n, 2*n = 5*m - 61. What is the remainder when r(3) is divided by m? Math A: 12 Inquiry: Let c = 6557 + -6436. Calculate the remainder when c is divided by 86. Math A: 35 Inquiry: Let g = -2 + 11. Let t be (-3)/9*0 - -29. Suppose 1 = 2*u - t. Calculate the remainder when u is divided by g. Math A: 6 Inquiry: Suppose 10*o - 5*o - 34 = -2*c, 5*o = 2*c + 26. Suppose -2*b + 14 = 20 - 12. Calculate the remainder when o is divided by b. Math A: 0 Inquiry: Suppose 3*m + 34*m + 24*m = 31476. Calculate the remainder when m is divided by 263. Math A: 253 Inquiry: Let m(j) = j**3 + 11*j**2 - 13*j - 9. Let f be m(-12). Suppose -10 = -f*x + 5, -4*y = -2*x - 166. Calculate the remainder when y is divided by 45/(-6)*(-1 - 1). Math A: 14 Inquiry: Calculate the remainder when 6/14 + 474/21 is divided by 6. Math A: 5 Inquiry: Let i = -29 + 31. Let c(o) = o**3 - 2*o**2 + 19 - 7 - 10*o - o**i - 7. Calculate the remainder when c(6) is divided by 18. Math A: 17 Inquiry: Let n = -34 + 64. Calculate the remainder when 37 is divided by n. Math A: 7 Inquiry: Let d(t) = -t**2 + 0*t - 3*t - 23 + 3*t**2 - 4*t. Let a(z) = -z**2 + 12*z + 7. Let h be a(12). Calculate the remainder when d(h) is divided by 10. Math A: 6 Inquiry: What is the remainder when (-7)/(56/(-20456))*(-8)/64*-8 is divided by 9? Math A: 1 Inquiry: What is the remainder when 34 is divided by (-3 - (-1 + 0)) + (13 - -1)? Math A: 10 Inquiry: Suppose 45 = -5*g - 0*g. Calculate the remainder when 26 is divided by (0 - (-21)/g)*-3. Math A: 5 Inquiry: Let a be 3/(1 - (-1)/(-4)). What is the remainder when (44/6)/((-24)/(-36)) is divided by 2 - a/(2/(-1))? Math A: 3 Inquiry: Let j(b) = 23*b + 9. Let m be j(-3). Let s = 91 + m. What is the remainder when s is divided by 18? Math A: 13 Inquiry: Suppose 5*v + 25 = -3*f, 2*f + 5*v - 15 = 3*f. Let t be 2/8*-2 - 125/f. Suppose t*u = 14*u - 28. What is the remainder when 109 is divided by u? Math A: 11 Inquiry: Suppose 2*m = -2*o + 46, 0*m + 65 = 3*o - m. Suppose o + 3 = d. What is the remainder when d is divided by (-2)/8 + (-171)/(-12)? Math A: 11 Inquiry: Suppose -4*s + 65 = -19. What is the remainder when 102 is divided by s? Math A: 18 Inquiry: Let z = -192 - -84. Calculate the remainder when 21 is divided by z/6*(0 - (-2)/(-6)). Math A: 3 Inquiry: Calculate the remainder when (13 - (-176)/(-16))/(2/1509) is divided by 54. Math A: 51 Inquiry: Suppose -5*l = -6*i + 2*i, -3*l = 0. Let p = i - -14. What is the remainder when p is divided by 5? Math A: 4 Inquiry: Let v = 922 - 398. Calculate the remainder when v is divided by 44. Math A: 40 Inquiry: Let x(n) = -n**2 - 9*n + 10. Let h be x(-9). Suppose 0*l - l - p + h = 0, -4*p = l - 4. Calculate the remainder when l is divided by 9. Math A: 3 Inquiry: Let v = 47 - 24. Let d(o) = 43*o - 16. Let c = 147 + -144. What is the remainder when d(c) is divided by v? Math A: 21 Inquiry: Suppose v + 3*z + 0*z + 23 = 0, -5*v - 4*z - 148 = 0. Let p = v - -53. Suppose 4*w + 22 = 6*w. What is the remainder when p is divided by w? Math A: 10 Inquiry: Suppose 0 = 10*c - 11*c - 4*m + 183, -2*c + 4*m = -402. Calculate the remainder when c is divided by 2/(-4) + (-201)/(-6). Math A: 30 Inquiry: Suppose -5*s + q + 34 = -74, -5*s - 4*q = -118. Suppose -x - 450 = -4*x. What is the remainder when x is divided by s? Math A: 18 Inquiry: Suppose 3*x - 44 = -4*f, -f = -2*x + x - 4. Let s(d) = d**3 + 4*d**2 + 3*d + 3. What is the remainder when f is divided by s(-3)? Math A: 2 Inquiry: Let l be 3/4 - 0 - (-945)/180. Suppose -l*o = -11*o + 1745. What is the remainder when o is divided by 35? Math A: 34 Inquiry: Let s = -775 - -803. Let l(a) = a**2 - 2*a - 21. Let o be l(0). Let t = -12 - o. Calculate the remainder when s is divided by t. Math A: 1 Inquiry: Let q = 563 + 55. What is the remainder when q is divided by 31? Math A: 29 Inquiry: Suppose 21*v - 38 = 19*v - i, -2*v + 2*i + 26 = 0. What is the remainder when v is divided by 12? Math A: 5 Inquiry: Calculate the remainder when 212 is divided by ((-44)/(-10))/(66/825). Math A: 47 Inquiry: Suppose s + 3*u - 49 = 0, u = s - 3*u - 21. Calculate the remainder when s is divided by 13. Math A: 11 Inquiry: Suppose -2*g + 0*g = -12. Suppose 0 = 4*k - i - 42, 10*k + i = 5*k + 57. What is the remainder when k is divided by g? Math A: 5 Inquiry: Let h(k) = 5*k**2 + 40*k + 37. What is the remainder when h(-21) is divided by 18? Math A: 16 Inquiry: Let f(i) = -2*i - 1 + 0 - 7 + 2. Let x be f(-5). Suppose -2*w - w + 76 = x*b, -b + 123 = 4*w. What is the remainder when w is divided by 5? Math A: 2 Inquiry: Suppose 48*j = v + 50*j - 277, 4*j = 4*v - 1156. Calculate the remainder when v is divided by 13. Math A: 12 Inquiry: Suppose -4*p - 2*q + 81 + 227 = 0, 3*p = 4*q + 220. Suppose p*i + 140 = 83*i. Let c(l) = 3*l**2 - 3*l + 2. What is the remainder when c(-3) is divided by i? Math A: 18 Inquiry: Let w be 1*(-1 + (1 - -1)). Let r = w + 7. Calculate the remainder when r is divided by 5. Math A: 3 Inquiry: Let f(o) = -16*o - 1. Let s(b) = -b - 3. Let w be s(-2). Let n = -1000 - -1058. Calculate the remainder when n is divided by f(w). Math A: 13 Inquiry: Let n = 3992 + -3150. Calculate the remainder when n is divided by 13. Math A: 10 Inquiry: Let o(g) = -g**3 - 5*g**2 + 5*g. Let z be o(-6). Let m be (-2)/z + 203/(-21). Let x = 15 + m. Calculate the remainder when 18 is divided by x. Math A: 3 Inquiry: Suppose 5*h + 2 + 29 = s, -4*s - 5*h + 49 = 0. Suppose -s = 5*k - 271. Let x = -20 + k. What is the remainder when x is divided by 17? Math A: 14 Inquiry: Suppose -4*c - 112 + 128 = 0. Calculate the remainder when 25 is divided by c. Math A: 1 Inquiry: Suppose 528*d - 92630 = 1882. What is the remainder when 597 is divided by d? Math A: 60 Inquiry: Suppose 0*k + 3 = k. Let l(j) = j**3 - 4*j**2 + 3*j + 3. Calculate the remainder when l(k) is divided by 2. Math A: 1 Inquiry: Let h = -14 + 26. Let t be ((-9)/h)/(1/4). What is the remainder when t - -3 - 1 - -29 is divided by 15? Math A: 13 Inquiry: Let r(x) = x**2 + 2*x - 27. Let m(l) = 5*l + 8. Let n(b) = 14*b + 23. Let q(o) = -8*m(o) + 3*n(o). What is the remainder when q(4) is divided by r(-7)? Math A: 5 Inquiry: Suppose -60 = 2*h - 7*h. Calculate the remainder when (-3 + -54)*(-3 + 2) is divided by h. Math A: 9 Inquiry: Let g = 274 + -271. What is the remainder when 10/g*((-1716)/(-30) + -5) is divided by 25? Math A: 24 Inquiry: Let z be 3/15 - 1395/(-25). Suppose 0*g + z = 7*g. Suppose -2*q = -g + 2. What is the remainder when 17 is divided by q? Math A: 2 Inquiry: Suppose 0 = -58*f + 41881 + 11179 + 21702. Calculate the remainder when f is divided by 49. Math A: 15 Inquiry: What is the remainder when 1642 is divided by (-20)/(-25) + (-681)/(-5)? Math A: 135 Inquiry: What is the remainder when 59 is divided by 21/(-2)*54/(-63)? Math A: 5 Inquiry: Let p(b) = -11*b - 131. Let f be p(-11). Suppose -4*x - 5*c + 547 = 0, -118 = -2*x + x - 5*c. What is the remainder when x is divided by 6/(f - -4) + 50? Math A: 45 Inquiry: Suppose 3*q = q. Let a = q + 1. What is the remainder when 2 is divided by a? Math A: 0 Inquiry: Let s(n) = n**3 + 5*n**2 - n - 4. Let j be ((-3)/6 - 0)*10. Let w be s(j). Let q = 8 - w. Calculate the remainder when 12 is divided by q. Math A: 5 Inquiry: Suppose -2*o + 2*o - 2*o = 0. Let a be o/(-1)*3/6. Suppose a = -7*g + 10*g - 90. What is the remainder when g is divided by 12? Math A: 6 Inquiry: Let g = -105 - -121. Suppose 3*b - 68 - 25 = 0. What is the remainder when b is divided by g? Math A: 15 Inquiry: Suppose 20 = c - 5*a, -2*c + 0*a - 5*a - 35 = 0. Let b(m) = -4*m**2 - 11*m - 16. Let z be b(c). Let q = z + 82. What is the remainder when 41 is divided by q? Math A: 20 Inquiry: Suppose -k - z = 46, 0 = -5*k - 2*z - z - 240. Let s = -20 - k. What is the remainder when s is divided by 16? Math A: 15 Inquiry: Let c be -4 + (-33*1 - (-6 - -5)). What is the remainder when ((-18)/12)/(2/c) is divided by 14? Math A: 13 Inquiry: Suppose -4*v = 5*i - 4197, 2*i - 3*v - 2318 = -630. What is the remainder when i is divided by 18? Math A: 13 Inquiry: Suppose 0 = -3*r + 5*s + 323, -s + 2*s = -r + 121. What is the remainder when r is divided by 9? Math A: 8 Inquiry: Let d = 3 - 1. Let c(s) = d*s + 1 - 4*s + 0*s. Calculate the remainder when c(-3) is divided by 3. Math A: 1 Inquiry: Suppose 0 = 6*j - 11*j + 160. Calculate the remainder when j is divided by 18. Math A: 14 Inquiry: Let g be (20/(-7))/((-308)/49 - -6). Let u be (-6)/g + 552/120. Suppose -u*n - 5*p + 4 = 0, 5*n - 16 - 18 = p. What is the remainder when 59 is divided by n? Math A: 5 Inquiry: Suppose 0 = -w - 4*h - 11, -11 = 2*w - 5*w - h. Suppose -3*c - 27 = -3*q, -q - c - c - 3 = 0. Calculate the remainder when w is divided by 36/60 - (-7)/q. Math A: 1 Inquiry: Suppose -7*s - 15 = -2*s. Suppose 0 = -21*d + 865 - 25. What is the remainder when d is divided by (1/s)/((-1)/33)? Math A: 7 Inquiry: Suppose -o = -5, -3*o = -3*k - 0 - 36. Let d(t) = t**2 + 5*t - 5. What is the remainder when d(k) is divided by 3? Math A: 0 Inquiry: Suppose 3*p - 11 = 76. Calculate the remainder when 84 is divided by p. Math A: 26 Inquiry: Suppose 2*u + u - 3*z = 210, 3*z = u - 68. Let d = -484 - -636. Let r = 157 - d. What is the remainder when u is divided by r? Math A: 1 Inquiry: Let x = -3 + 6. Let k(u) = u**2 + 3*u + 1. Let d be k(1). Suppose 0*g = d*p + 4*g - 85, x*p = 3*g + 24. What is the remainder when 23 is divided by p? Math A: 10 Inquiry: Let x be 2*(-1 - -5) + 0. Suppose -x - 20 = 4*m. Let g = m + 21. Calculate the remainder when g is divided by 5. Math A: 4 Inquiry: What is the remainder when -4 - (15/(-10) - (-306)/(-4)) is divided by 16? Math A: 10 Inquiry: Suppose 259*z = 255*z + 116. What is the remainder when z is divided by 15? Math A: 14 Inquiry: Suppose -1258 = 18*y - 7*y - 7660. What is the remainder when 1765 is divided by y? Math A: 19 Inquiry: Let z(l) = 6*l - 38. Let f be -2 + -1 + 1 + 4. What is the remainder when f/8 + (-753)/(-12) is divided by z(9)? Math A: 15 Inquiry: Suppose 365 = 3*a - x, -2*a - x = 3*x - 248. Suppose 4*o = -10 + a. Calculate the remainder when 53 is divided by o. Math A: 25 Inquiry: Suppose 5*s + 21 - 56 = 0. Suppose -4*z = 5*m - 140, 4 = 4*z - 16. Suppose m = s*c - 4*c. What is the remainder when 22 is divided by c? Math A: 6 Inquiry: Let n(m) = m**2 - 3*m + 2. Suppose 0 = -4*h + 3*h - 4*i - 2, -4*h = 3*i - 5. Let g be n(h). Suppose g*b = b - 25. What is the remainder when b is divided by 13? Math A: 12 Inquiry: Suppose -55 = 13*k - 18*k. What is the remainder when ((-56)/6)/(1/(-3)) is divided by k? Math A: 6 Inquiry: Suppose -9*n + 138 = -3*n. Calculate the remainder when n is divided by 6. Math A: 5 Inquiry: Let r(f) = -f**2 - 122*f - 1171. Calculate the remainder when r(-49) is divided by 29. Math A: 28 Inquiry: Suppose -x + 25 = -5*n, 4*n - 10 = -x + 6*n. Suppose -3*y - 5*c + 26 = -10*c, -5*y + 3*c + 70 = x. Calculate the remainder when 67 is divided by y. Math A: 16 Inquiry: What is the remainder when (12 - 8)*(-1)/((-16)/1480) is divided by 34? Math A: 30 Inquiry: Let l be 1/(-2)*(-4 - -4). Suppose 2*u + 5*z - 73 = -l*u, -68 = -2*u - 4*z. What is the remainder when u is divided by 14? Math A: 10 Inquiry: Suppose f + 2*f + 5*m - 76 = 0, 5*f - 4*m = 102. Let r be 6405/28 - 1/(-4). Suppose 23 + r = 4*o. What is the remainder when o is divided by f? Math A: 19 Inquiry: Let k be (3/4)/(2/8). Suppose 19 = k*r - r - 3*z, -2*r + 29 = -5*z. Let a(m) = -m**3 + 3*m**2 + 2*m - 2. Calculate the remainder when 21 is divided by a(r). Math A: 3 Inquiry: Let n(u) = -3*u - 1. Let o be 2/(3 - -1)*12. Let r = 7 - o. What is the remainder when n(-1) is divided by r? Math A: 0 Inquiry: Let u = -350 - -379. Suppose 64 = 4*x - 3*s, 17*x + 4*s + u = 18*x. What is the remainder when 27 is divided by x? Math A: 1 Inquiry: Let l = 6616 - 5660. What is the remainder when l is divided by 15? Math A: 11 Inquiry: Let j be (-468)/(-90) - 2/10. Suppose -3*w = -j*w - 24. Calculate the remainder when (-716)/(-5) - w/(-60) is divided by 29. Math A: 27 Inquiry: Let k = 14 + 35. What is the remainder when k is divided by 13? Math A: 10 Inquiry: Let v(w) = w - 54. Let r be v(11). Let t = 54 + r. Calculate the remainder when 34 is divided by t. Math A: 1 Inquiry: Suppose -246*w - 14 = -998. What is the remainder when 68 is divided by w? Math A: 0 Inquiry: What is the remainder when 906/26 + (-8)/(-52) is divided by 18? Math A: 17 Inquiry: Let c be (-483062)/(-410) + 8/10. Suppose 38*m = c - 419. What is the remainder when 33 is divided by m? Math A: 13 Inquiry: What is the remainder when 100 is divided by 12 + -4*(42/24 - 2)? Math A: 9 Inquiry: Suppose 163 = 5*s - 3*h, -55 - 73 = -4*s + 3*h. Let n(z) = 4*z**2 + z + 4. What is the remainder when s is divided by n(-2)? Math A: 17 Inquiry: Let t(z) = -7*z - 97. Calculate the remainder when t(-46) is divided by 23. Math A: 18 Inquiry: Let j(k) = -k**3 + 2*k**2 + 12*k - 11. Let p be (-2)/(-8) + (-18)/8. Calculate the remainder when j(4) is divided by 3/(p/(-1 - 1)). Math A: 2 Inquiry: Let x be -3 + (0 + 29)/(-4 + 5). Suppose x*f = 29*f - 183. Suppose -o + f = u, -4*o + 84 + 136 = -2*u. Calculate the remainder when o is divided by 30. Math A: 27 Inquiry: Let v(s) = 3*s + 47. Calculate the remainder when v(-8) is divided by 8. Math A: 7 Inquiry: Let r(b) = 2*b - 6. Calculate the remainder when r(5) is divided by 3. Math A: 1 Inquiry: Suppose -92 = -4*i + 23*w - 27*w, -2*i - 3*w = -50. Let h(u) = -u**3 - 4*u**2 + 8*u. What is the remainder when h(-6) is divided by i? Math A: 5 Inquiry: Let f(v) = v**3 - 2*v**2 - 3*v - 8. Let x be f(6). Let z = x - 101. Calculate the remainder when 84 is divided by z. Math A: 16 Inquiry: Let d(k) = k + 8. Let m be d(-5). Suppose m*a - 44 = -a. What is the remainder when a is divided by 6? Math A: 5 Inquiry: Let g be 0/((-21)/(-84) - (-9)/(-4)). Suppose -4*z + 28 = -2*v, -5*z + 27 + 10 = -3*v. Suppose g = -z*x + 10. Calculate the remainder when 8 is divided by x. Math A: 0 Inquiry: Suppose -4*f - 3*b + 5520 + 2475 = 0, -2*f = -3*b - 4029. Calculate the remainder when f is divided by 17. Math A: 15 Inquiry: Suppose -a + 4*q + 449 = 0, 26*a - 25*a = -q + 449. What is the remainder when a is divided by 116? Math A: 101 Inquiry: Suppose s - 1 - 17 = -3*y, y + 4 = 3*s. Suppose -3*w + 10 = s*g - 20, -5*g = -5*w + 50. Calculate the remainder when (-5)/w + 31/2 is divided by 6. Math A: 3 Inquiry: Let c = 279 - 210. Calculate the remainder when c is divided by 24. Math A: 21 Inquiry: Suppose 0 = 8*p - 1042 + 130. What is the remainder when p is divided by 39? Math A: 36 Inquiry: Suppose g = 4*w - 241, 3*g - 68 - 185 = -4*w. Suppose -w = -f - 4. Suppose 3*t - 31 = 14. Calculate the remainder when f is divided by t. Math A: 12 Inquiry: Suppose -21*i + 534 = 30. Suppose -s - 8 = -4*c, 9 = 3*c - 0. Suppose -4*k - 15 = -3*j, -5*k = -2*j + s - 1. What is the remainder when i is divided by j? Math A: 6 Inquiry: Suppose 6*y = 1771 - 55. Calculate the remainder when y is divided by 58. Math A: 54 Inquiry: Suppose -2*a = 2*a - k - 95, 5*a + 2*k = 109. Suppose -h = -4*h - 6, 0 = -v - 5*h - a. Let n = 23 + v. Calculate the remainder when n is divided by 4. Math A: 2 Inquiry: Let o = 73 - 25. Suppose 3*m + 6 = 0, 5*f = m - 28 + 80. What is the remainder when o is divided by f? Math A: 8 Inquiry: Let x(b) = 21*b**3 - 14*b**2 + 9*b - 21. Let p(g) = -4*g**3 + 3*g**2 - 2*g + 4. Let u(a) = -11*p(a) - 2*x(a). What is the remainder when 75 is divided by u(3)? Math A: 18 Inquiry: Suppose -5*x = 3*m - 809 + 150, -4*x = 20. What is the remainder when m is divided by (21/(-6))/((-2)/44)? Math A: 74 Inquiry: Suppose 5*i - 1 = 9. Suppose -c = -2*a - 3*a - 14, -5*a = 5*c - 10. Suppose 3*u = -c*q + 7*u - 4, 4*u - 12 = 0. What is the remainder when q is divided by i? Math A: 0 Inquiry: Suppose -r - 1 - 4 = 0. Let t(i) = -2*i - 6. Calculate the remainder when t(r) is divided by 3. Math A: 1 Inquiry: Let n = 22 - 19. Suppose 0*i + 18 = 3*c - n*i, -3*i = 0. Suppose c = h - 13. Calculate the remainder when 90 is divided by h. Math A: 14 Inquiry: Let s = -1071 - -1119. What is the remainder when 93 is divided by s? Math A: 45 Inquiry: Suppose 5*n - 351 = -4*n. What is the remainder when n is divided by 10? Math A: 9 Inquiry: Let j(s) = 3 + 12 + 8 + s**3 - 2*s**3 + s**2. Let f be j(0). Suppose 0 = 2*v - 5*c + f - 55, -v + 13 = -c. What is the remainder when v is divided by 6? Math A: 5 Inquiry: Let l(p) be the first derivative of 7*p - 2*p**2 - 3*p**2 + 23 - 7*p + p. What is the remainder when 31 is divided by l(-1)? Math A: 9 Inquiry: Suppose f = 2*n - 11, 3*f + 2*n - 22 = 5*f. Let c(v) = -v - 10. Let m be c(f). What is the remainder when 32 is divided by (6/2 + 2)*m? Math A: 2 Inquiry: Suppose l + 2*l - 54 = 0. Calculate the remainder when 34 is divided by l. Math A: 16 Inquiry: Let k = -711 + 4064. Calculate the remainder when k is divided by 129. Math A: 128 Inquiry: Let n = -83 - -446. Calculate the remainder when n is divided by (15 + 195/78)*(-72)/(-45). Math A: 27 Inquiry: Calculate the remainder when 11 is divided by (-324)/(-48) + 18/(-24). Math A: 5 Inquiry: Let t(c) = -1. Let g(v) = 21*v. Let k(u) = g(u) + t(u). Calculate the remainder when 33 is divided by k(1). Math A: 13 Inquiry: Let j be 93 + -4 + 3 + -4. Suppose 107 - j = x. Let r(o) = o**2 + 4*o + 7. What is the remainder when x is divided by r(-5)? Math A: 7 Inquiry: Let i = -272 + 280. What is the remainder when 22 is divided by i? Math A: 6 Inquiry: Suppose 13*c - 71*c + 696 = 0. Calculate the remainder when 188 is divided by c. Math A: 8 Inquiry: Let m(j) = 58*j**3 - 1. What is the remainder when m(1) is divided by (2/(-8))/((-5)/340) + -2? Math A: 12 Inquiry: Suppose 3*v + 2 = 5*s - 15, -v - 2 = 2*s. What is the remainder when 39 is divided by (-3 - (v - -3)) + 22? Math A: 19 Inquiry: Let c = -394 + 186. Let n = -124 - c. What is the remainder when n is divided by 22? Math A: 18 Inquiry: Suppose 4*q - 631 = 2565. What is the remainder when q is divided by 25? Math A: 24 Inquiry: Let c(o) = 33*o + 43. Suppose -2*n = -3*m - 37, n + 67 = 3*n + 3*m. What is the remainder when n is divided by c(-1)? Math A: 6 Inquiry: Suppose 144*a + 2352 = 168*a. What is the remainder when 184 is divided by a? Math A: 86 Inquiry: Let u = 367 + -311. Suppose 0 = -52*w + u*w - 8. What is the remainder when 12 is divided by w? Math A: 0 Inquiry: Suppose -3*s - 4*a = -70, 30 = 2*s - a - 2. Let n = 43 - s. Calculate the remainder when n is divided by (13/(-2) - 0)*-2. Math A: 12 Inquiry: Suppose -167 + 119 = -k. Suppose 5*v = 4*r - 66, 4*r + 4*v - k = -0*v. Calculate the remainder when r is divided by 3. Math A: 2 Inquiry: Let x = -5 - -5. Suppose 4*i - 44 = 20. Calculate the remainder when 47 - x - 0/1 is divided by i. Math A: 15 Inquiry: Let m(d) = 451*d - 1790. Let b = 70 - -13. Calculate the remainder when b is divided by m(4). Math A: 13 Inquiry: Let a be (21/(-6) + 1)*-2. Suppose -a*y - 2 = -172. Calculate the remainder when y is divided by 9. Math A: 7 Inquiry: Let n = 722 + -277. Suppose -8*j = 125 - n. Calculate the remainder when j is divided by 6. Math A: 4 Inquiry: What is the remainder when 15 is divided by -2 + (-2)/(-4)*16? Math A: 3 Inquiry: Let m = -28 - -15. Let k = m + 8. Let w(x) = x**2 + 3*x + 3. Calculate the remainder when 38 is divided by w(k). Math A: 12 Inquiry: Suppose 12*n - 190 = 10*n. Calculate the remainder when n is divided by 20. Math A: 15 Inquiry: Let u be 0 + 1 + 2 + 0 + 137. Let w = u - 77. What is the remainder when w is divided by 22? Math A: 19 Inquiry: Suppose 0 = 8*p + 14*p - 13904. Calculate the remainder when p is divided by 127. Math A: 124 Inquiry: Suppose k + 3*k - 1176 = 0. What is the remainder when k is divided by 17? Math A: 5 Inquiry: Let f = 27 - 10. Let c(i) = i**3 + i + 1. Let w be c(0). Let k(p) = 48*p**3 + 2*p**2 - p. What is the remainder when k(w) is divided by f? Math A: 15 Inquiry: Let i(y) = -y**3 + 8*y**2 - 7*y + 9. Let n be i(7). Suppose 71 - 17 = n*b. Let o(d) = 6*d - 1. What is the remainder when o(4) is divided by b? Math A: 5 Inquiry: Suppose 415 = 28*q - 789. Calculate the remainder when q is divided by 15. Math A: 13 Inquiry: Let i be (-407)/(-3) + (8/6 - 1). Suppose 9*m - 8 = i. Calculate the remainder when 44 is divided by m. Math A: 12 Inquiry: Let h be (-6)/14 - 120/(-35). Suppose 288 = -c - h*c. Let l = 26 - c. What is the remainder when l is divided by 20? Math A: 18 Inquiry: Let w be 11935/(-75) - (-2)/15. Let z = w - -172. Calculate the remainder when 46 is divided by z. Math A: 7 Inquiry: Let c = 1898 - 1894. Suppose 0 = -q - 2*d + 21, 0 = -3*d + 3. Calculate the remainder when q is divided by c. Math A: 3 Inquiry: Suppose -4*r - 37 = 5*x, 0*x - 3*x = -2*r - 13. Let u = r - 0. Let m(d) = -d**3 - 7*d**2 + 7*d - 5. Calculate the remainder when 7 is divided by m(u). Math A: 1
[{"idx": "txt360/calculus__differentiate_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-7.jsonl"}, {"idx": "txt360/numbers__div_remainder_composed_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-7.jsonl"}]
### Here's set of division, subtraction, addition, multiplication math guide: -943 / 907 = -1.04 ### 432 + 780 = 1212 ### 1359 / -273 = -4.98 ### 135 / 74 = 1.82 ### 2210 + 423 = 2633 ### 1253 / 912 = 1.37 ### -99 / -74 = 1.34 ### 2139 * 755 = 1614945 ### 420 - 299 = 121 ### 437 - 1082 = -645 ### 473 - 2148 = -1675 ### 1151 * -82 = -94382 ### 243 - 167 = 76 ### 756 + -83 = 673 ### 1792 * 981 = 1757952 ### 1544 + 1922 = 3466 ### -887 / -456 = 1.95 ### 1035 - 1493 = -458 ### 768 - 274 = 494 ### 736 + 1675 = 2411 ### -756 / 152 = -4.97 ### 248 + 596 = 844 ### 354 + 2047 = 2401 ### 1785 * 407 = 726495 ### -51 + 1663 = 1612 ### 1778 - 2238 = -460 ### 481 + 336 = 817 ### 392 - 1203 = -811 ### 412 / -305 = -1.35 ### 238 + 1243 = 1481 ### 1706 + 107 = 1813 ### 2121 - 2148 = -27 ### 1008 + 969 = 1977 ### -119 / -335 = 0.36 ### 355 + 1116 = 1471 ### 22 - 466 = -444 ### 501 / -110 = -4.55 ### 2100 + 222 = 2322 ### 8/5 + 2/6 - 9/6 - 6/4 + 4/6 - 1/3 + 4/9 - 2/9 - 3/4 + 4/9 + 6/6 - 3/8 - 1/9 + 7/1 + 4/3 - 2/3 + 6/6 - 2/5 Start with the first fraction 8/5. Next, we add 2/6 to the current total. The intermediate result is: 29/15 Next, we subtract 9/6 from the current total. The intermediate result is: 13/30 Next, we subtract 6/4 from the current total. The intermediate result is: -16/15 Next, we add 4/6 to the current total. The intermediate result is: -2/5 Next, we subtract 1/3 from the current total. The intermediate result is: -11/15 Next, we add 4/9 to the current total. The intermediate result is: -13/45 Next, we subtract 2/9 from the current total. The intermediate result is: -23/45 Next, we subtract 3/4 from the current total. The intermediate result is: -227/180 Next, we add 4/9 to the current total. The intermediate result is: -49/60 Next, we add 6/6 to the current total. The intermediate result is: 11/60 Next, we subtract 3/8 from the current total. The intermediate result is: -23/120 Next, we subtract 1/9 from the current total. The intermediate result is: -109/360 Next, we add 7/1 to the current total. The intermediate result is: 2411/360 Next, we add 4/3 to the current total. The intermediate result is: 2891/360 Next, we subtract 2/3 from the current total. The intermediate result is: 2651/360 Next, we add 6/6 to the current total. The intermediate result is: 3011/360 Next, we subtract 2/5 from the current total. The intermediate result is: 2867/360 The final result in fraction form is 2867/360. This simplifies to the mixed number 7 347/360.<|endoftext|>### Please examine the set of subtraction, addition, division, multiplication math guide: -870 / -651 = 1.34 ### 708 - 2245 = -1537 ### 645 + 305 = 950 ### 1407 * 536 = 754152 ### 39 + 166 = 205 ### 18 + 1776 = 1794 ### 943 * 1653 = 1558779 ### 954 * 529 = 504666 ### 979 + 1200 = 2179 ### -626 / 418 = -1.5 ### 1800 * 76 = 136800 ### 1367 * 847 = 1157849 ### 1907 + 94 = 2001 ### 1589 - 1356 = 233 ### 722 - 2177 = -1455 ### -134 / -106 = 1.26 ### 333 - 1782 = -1449 ### 1030 / 967 = 1.07 ### -4 * 1445 = -5780 ### 1376 * 246 = 338496 ### 990 / -701 = -1.41 ### 234 + 2000 = 2234 ### 143 / -601 = -0.24 ### 1008 - 824 = 184 ### 1261 / 59 = 21.37 ### 1808 + 1892 = 3700 ### 110 / 588 = 0.19 ### 1730 + 1212 = 2942 ### 1384 * 1003 = 1388152 ### 973 + 225 = 1198 ### 1637 * 1814 = 2969518 ### -765 / 211 = -3.63 ### 2245 + 1500 = 3745 ### 1623 + 204 = 1827 ### 1266 * 1600 = 2025600 ### 483 * 184 = 88872 ### 679 / 1099 = 0.62 ### Eva work as a sales clerk. She is paid a salary of 9664 a week plus 2% commission on sales over 4000. Find her gross pay for a week in which her sales are 21937. Step-by-step solution: To calculate Eva's gross pay, we need to add her salary to the commission she earned on sales over 4000. Her salary is 9664 per week. Her sales for this week are 21937. Commission = 2% of (sales - 4000). Commission = 0.02 * (21937 - 4000) = 358.74. Therefore, Eva's gross pay for the week is 10022.74. ### 1188 - 507 = 681<|endoftext|>### Here are set of subtraction, division, multiplication, addition math exercises: 208 - 1331 = -1123 ### 392 + 1291 = 1683 ### 238 * 1331 = 316778 ### 132 * 1170 = 154440 ### -332 / 271 = -1.23 ### 956 + 1599 = 2555 ### -27 + 1869 = 1842 ### 2118 + 626 = 2744 ### 1166 * 116 = 135256 ### 899 / -436 = -2.06 ### 643 * 273 = 175539 ### 1742 - 2327 = -585 ### 1132 / 989 = 1.14 ### 1659 - 717 = 942 ### 1835 - 1487 = 348 ### 489 * 455 = 222495 ### 1715 * 374 = 641410 ### 941 / -825 = -1.14 ### Start with the equation: 27*x + 75 = -1*x + -57 Step 1: Subtract -1*x from both sides: (28)*x + 75 = -57 Step 2: Subtract 75 from both sides: (28)*x = -132 Step 3: Divide both sides by 28: x = -4.714285714285714 Final Equation: x = -4.714285714285714 ### -872 / -718 = 1.21 ### 2255 - 1198 = 1057 ### 2218 - 1489 = 729 ### 1168 + 2078 = 3246 ### 1362 + 466 = 1828 ### 1167 + 245 = 1412 ### 608 + 1939 = 2547 ### 668 * 670 = 447560 ### 1814 - 2140 = -326 ### 159 * 1002 = 159318 ### 473 - 907 = -434 ### 2285 - 2245 = 40 ### 1856 * 1562 = 2899072 ### 1072 / 1038 = 1.03 ### 1104 + 794 = 1898 ### 1205 + 1211 = 2416 ### 1010 + 1045 = 2055 ### 1169 / 217 = 5.39 ### 491 * 1068 = 524388 ### 1511 * 1424 = 2151664 ### 116 / 840 = 0.14 ### 2097 * 1007 = 2111679 ### 479 / 91 = 5.26 ### -290 / 503 = -0.58 ### 633 * 1285 = 813405<|endoftext|>### Study this set of addition, subtraction, division, multiplication math insights: 156 / 1131 = 0.14 ### 1037 - 585 = 452 ### 1249 * -61 = -76189 ### 1810 + 1786 = 3596 ### -918 / 436 = -2.11 ### 568 - 79 = 489 ### 8*3 =\n#### OK, let's work through this together. We're starting with 8 and we're going to multiply it by 3, which means we add 8 to itself 3 times. Step 1: 0 + 8 = 8 Step 2: 8 + 8 = 16 Step 3: 16 + 8 = 24 So, 8*3 = 24 ### 2028 * 1615 = 3275220 ### 1320 / 1273 = 1.04 ### 198 + 402 = 600 ### 2147 + 413 = 2560 ### -334 / 1182 = -0.28 ### 1820 + 1700 = 3520 ### 2020 * 1372 = 2771440 ### 1884 * 2072 = 3903648 ### 1278 - 810 = 468 ### 346 / 260 = 1.33 ### 46 * 1373 = 63158 ### 2257 * 505 = 1139785 ### 1187 / 872 = 1.36 ### 2192 * 973 = 2132816 ### 303 * 222 = 67266 ### -10 / -342 = 0.03 ### 1597 - 1702 = -105 ### 291 - 1193 = -902 ### 172 - 1247 = -1075 ### 183 * 1815 = 332145 ### -709 / 1286 = -0.55 ### 1202 + 2160 = 3362 ### 340 * 798 = 271320 ### 1632 * 781 = 1274592 ### 1141 / -488 = -2.34 ### 1249 + 1160 = 2409 ### 1680 - 2214 = -534 ### 1676 + 1714 = 3390 ### 2153 * -70 = -150710 ### 1874 + 349 = 2223 ### 1378 * 681 = 938418 ### 375 * 1171 = 439125 ### 1890 * 220 = 415800 ### 1958 - 333 = 1625 ### 216 + 1682 = 1898 ### 585 + 1129 = 1714 ### 1894 - 2188 = -294 ### 293 * 1048 = 307064<|endoftext|>### Here is examples of subtraction, division, multiplication, addition arithmaic examples: 1300 * 535 = 695500 ### 2096 + 232 = 2328 ### 1666 + 78 = 1744 ### 750 - 1124 = -374 ### -40 - 751 = -791 ### 1234 * 1309 = 1615306 ### 1421 * 1208 = 1716568 ### 306 - 243 = 63 ### -206 / -706 = 0.29 ### 1884 + 1275 = 3159 ### 1504 - 2079 = -575 ### 1120 / -236 = -4.75 ### 521 / 1274 = 0.41 ### 345 + 1791 = 2136 ### 1015 + 187 = 1202 ### -223 / -29 = 7.69 ### 149 * 2267 = 337783 ### -692 / 1167 = -0.59 ### 456 - 1113 = -657 ### 1314 * 659 = 865926 ### -421 / 14 = -30.07 ### 108 - 1178 = -1070 ### 72 + 608 = 680 ### 786 / -961 = -0.82 ### 190 + 306 = 496 ### 803 - 1196 = -393 ### 1506 + 821 = 2327 ### 909 / -26 = -34.96 ### 497 / 1290 = 0.39 ### 2076 + 514 = 2590 ### 2171 + 1320 = 3491 ### 709 * 2147 = 1522223 ### -310 / -977 = 0.32 ### -207 / -646 = 0.32 ### -304 / -467 = 0.65 ### 681 + 1277 = 1958 ### -817 / 597 = -1.37 ### 1934 + 1683 = 3617 ### 1131 / 71 = 15.93 ### -344 / 1124 = -0.31 ### 1166 + 1181 = 2347 ### 17 * 1494 = 25398 ### 1623 - 977 = 646 ### 899 / 879 = 1.02 ### 1274 / 147 = 8.67 ### 234 + 701 =\n#### Alright, let's solve this problem step by step. We have 234 and 701 and we're adding them together. Step 1: We'll start by adding the digits 4 & 1 in column 1 and get 5. Step 2: We'll start by adding the digits 3 & 0 in column 2 and get 3. Step 3: We'll start by adding the digits 2 & 7 in column 3 and get 9. So, 234 + 701 = 935. <|endoftext|>### Here's set of multiplication, addition, subtraction, division math problems: 1258 * 838 = 1054204 ### 1335 * 1328 = 1772880 ### 71 / -587 = -0.12 ### 367 / -188 = -1.95 ### 381 - 318 = 63 ### 1610 * 1074 = 1729140 ### 357 / 123 = 2.9 ### 966 * 975 = 941850 ### 810 * 1643 = 1330830 ### 347 * 1376 = 477472 ### 1532 + 1658 = 3190 ### 1503 + 1656 = 3159 ### 733 - 1050 = -317 ### -383 / 453 = -0.85 ### 1217 - 1334 = -117 ### 643 - 1488 = -845 ### 690 / 998 = 0.69 ### 2027 * 1251 = 2535777 ### 1904 * 375 = 714000 ### 2062 * 3 = 6186 ### 2203 - 1228 = 975 ### 190 * 243 = 46170 ### 444 - 1190 = -746 ### 1053 / 244 = 4.32 ### 18 / 1224 = 0.01 ### 898 + 2185 = 3083 ### 2217 + 2160 = 4377 ### 428 + 848 = 1276 ### 1365 / -731 = -1.87 ### 205 / 336 = 0.61 ### 2031 - 344 = 1687 ### 1354 * 2164 = 2930056 ### 159 * 2146 = 341214 ### 210 * 1532 = 321720 ### 1946 - 1437 = 509 ### 757 / 318 = 2.38 ### 244 * 128 = 31232 ### 291 / -390 = -0.75 ### 2211 - 610 = 1601 ### 1296 + -22 = 1274 ### 34/26 + 96/22 = (34 * 22 + 96 * 26)/572 = 3244/572 = 811/143 = 5 96/143 ### -463 / 719 = -0.64 ### Problem: 89743/85284 - 45960/5717 + 29184/66685 + 13702/58435 Solution: Step 1: Start with 89743/85284 Step 2: Subtract 45960/5717 from the current total. The new total is -3406591909/487568628. Step 3: Add 29184/66685 to the current total. The new total is -212939378612113/32513513958180. Step 4: Add 13702/58435 to the current total. The new total is -5954150084835653/942891904787220. Final Calculation: The simplified total is -5954150084835653/942891904787220
[{"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}, {"source": "ontocord-synthetic-math"}]
comparison: pair composed ------------------------- Issue: Let a be (-36)/(-360)*(2534 - 2). Is 253 at most a? Ans: True Issue: Let b be -12 + (-228)/(-20) - 444/10. Do b and 3 have the same value? Ans: False Issue: Let o = 10 - 5. Let g be -6*o - 2/3. Let b = -30 - g. Which is greater: b or 1/3? Ans: b Issue: Let v(s) = s + 29. Let r be v(-28). Let d(x) = 136*x**2 + 4*x - 2. Let t be d(r). Is -2 < t? Ans: True Issue: Suppose -35*d = 7*d + 3024. Is d bigger than -77? Ans: True Issue: Let i(w) = -w**3 - 8*w**2 - 19*w - 13. Let d be i(-6). Let c be (-6 - -8)*14/1. Are c and d non-equal? Ans: True Issue: Suppose 3*d - 5*z = -3*z - 21, 3*d + 5*z + 42 = 0. Which is bigger: d or 6? Ans: 6 Issue: Let a(v) = 2*v**3 - 16*v**2 + 1. Let i be a(8). Let u = -1337/520 + -3/104. Let g = u + 73/30. Are g and i unequal? Ans: True Issue: Let o(u) = -u**2 - u + 2. Let g be o(0). Let q be 8/(-3)*195/(-70). Let z = 58/7 - q. Is g greater than z? Ans: True Issue: Let k = -15.2 - -15.3. Is -9.5 greater than k? Ans: False Issue: Let h = 16.8 + 0.2. Which is smaller: 1/2 or h? Ans: 1/2 Issue: Let o(d) = d**2 - 2*d + 2. Let x be o(2). Let u(c) = c + 2. Let j be u(0). Suppose l + 2*l - 9 = 3*k, j*l - 12 = 4*k. Which is smaller: x or l? Ans: l Issue: Suppose 4*n - 25 = 23. Let f = n + -7. Suppose -f*u - 30 = -5*w, -1 = 3*w - 5*u - 29. Which is smaller: w or 1/2? Ans: 1/2 Issue: Let c be (-10)/25 - (-52)/(-20). Let h be 1/2 + (-18)/4. Is c smaller than h? Ans: False Issue: Let j be (3 + 40/(-12))/((-3)/36). Is 3 <= j? Ans: True Issue: Let i(v) = -48*v + 6205. Let w be i(129). Which is smaller: w or -10? Ans: -10 Issue: Let x(c) = -2*c**2 - 22*c - 88. Let s be x(-13). Let y be (-51)/(-54) - s/(-84). Is 0 smaller than y? Ans: False Issue: Let o(j) = 34*j + j**2 + 39 + 42 - 27 + 0*j**2. Let l be o(-32). Let p be 11/(22/55 - (-6)/l). Which is smaller: p or -53? Ans: p Issue: Let f = -651603 + 11080921/17. Let m = f - 216. Which is smaller: 1 or m? Ans: m Issue: Let n be ((-64)/(-112))/((-4)/(-14)). Is n bigger than 36? Ans: False Issue: Suppose -b = -63 - 40. Which is smaller: b or 104? Ans: b Issue: Let j = -1.7 - 0.7. Let f = -2.4 - j. Is -0.1 less than f? Ans: True Issue: Let m = 4309 + -185297/43. Let y = m - -2128/8041. Which is smaller: y or 0? Ans: 0 Issue: Let d be 2/(-184) - 2/8. Let k be (3 + (-16)/6)*(2 - (-13 + 18)). Which is smaller: k or d? Ans: k Issue: Let q = 2 + 0. Let i(k) = -8*k - 6*k**2 + 10*k**2 - 3 - 5*k**q. Let p be i(-7). Does 3 = p? Ans: False Issue: Let c = 8 - 6. Suppose 3*i + 15 + 8 = -5*q, -4*q - 20 = 4*i. Let k be i/(4/(-12) - 4/(-120)). Which is smaller: c or k? Ans: c Issue: Suppose 4*t = t + 3. Is 14/9 at most as big as t? Ans: False Issue: Let r = 0.05 - 7.05. Let a = r + 5. Which is greater: -0.06 or a? Ans: -0.06 Issue: Let v = -0.2219 - -0.4219. Is v less than or equal to -5/7? Ans: False Issue: Let a be 179/(-3) + (24/1)/(-8). Are a and -64 non-equal? Ans: True Issue: Let y = -729 - -8031/11. Let c be 136/68 + 1*-1. Is c less than or equal to y? Ans: True Issue: Let q(l) = -l**2 + 7*l + 4. Let u be q(7). Suppose u + 0 = -m. Which is bigger: m or -3? Ans: -3 Issue: Let d = 124/3 + -42. Let x be ((-4)/(-8))/(1/2). Let h be x/(0 - (0 + 1)). Which is smaller: h or d? Ans: h Issue: Suppose -i = 2*i - 3. Let m be 11/3 + (-3)/(-9). Let q be -4 + 2/(-8) + m. Which is bigger: q or i? Ans: i Issue: Let s = 0 + 3. Let a be -3 + (1 - (-9)/s). Let p = a + -1. Which is smaller: 3/5 or p? Ans: p Issue: Suppose -6*h = -h + 10. Let k = -0.1 - 0. Do h and k have the same value? Ans: False Issue: Let r = -7 + 6. Let t be (r - 38/(-10))*10. Suppose t = -2*k - 2*k. Is -7 less than or equal to k? Ans: True Issue: Let d be (0 - (-1 - 2)) + 3053/(-923). Which is bigger: 1 or d? Ans: 1 Issue: Let t = 4 - 3.6. Let k = 2 + -1.6. Let o = k - t. Is 0 at most o? Ans: True Issue: Let s be 2/(-3) + (-242)/60. Let z = s + 24/5. Which is smaller: 0 or z? Ans: 0 Issue: Let l be (3/(-2))/(11/(-22)). Suppose 3*j + f + 4*f = 0, l = 3*j + 4*f. Do j and 4 have the same value? Ans: False Issue: Let v = -36 - -35. Let n be 4/10 - (-46)/(-40). Which is smaller: n or v? Ans: v Issue: Suppose 33 + 74 = 100*u + 7. Is -6/7339 < u? Ans: True Issue: Let y be (234/(-45))/(4/(-10)). Suppose -4*n + 9 = y. Which is greater: -3/7 or n? Ans: -3/7 Issue: Let h(g) = g**3 - 10*g**2 + 4*g - 29. Let z be h(10). Let l = 3.5 + -2.5. Which is bigger: z or l? Ans: z Issue: Let v = 609 + -609.1. Is -730 at most v? Ans: True Issue: Let h = 407 + -399. Let p = -2 - -5. Is h at most p? Ans: False Issue: Let k be 3/2*384/9. Do 64 and k have different values? Ans: False Issue: Let g = 51 + -51.07. Let x = -0.23 + g. Let p = -24 + 9. Are x and p unequal? Ans: True Issue: Let z = -3016 - 3093. Let c = -1154597/189 - z. Is c smaller than 1? Ans: True Issue: Let a be (-1)/3 + 154/21. Let h be 2/a - 26/42. Let p = 0.34 + -0.04. Which is smaller: h or p? Ans: h Issue: Let l = 1050 + -544. Is l >= 505? Ans: True Issue: Let n(g) = -g**2 - 6*g. Let q be n(-6). Let w(i) = -i**3 + 3*i**2 + 5*i - 4. Let p be w(4). Are q and p equal? Ans: True Issue: Let b = 920 + -863. Suppose -75*c - b = -18*c. Is -1/1351 greater than c? Ans: True Issue: Let d = 12 + -13. Do d and -1/3 have the same value? Ans: False Issue: Let h be (-6)/9 + 1114/24. Let q = -46 + h. Suppose -6*s + 2*s - 8 = 3*z, -4*z + 4*s = -8. Which is smaller: z or q? Ans: q Issue: Let o(m) = 4*m + 8. Let t(w) = -3*w - 7. Let i(y) = -6*o(y) - 7*t(y). Let u be i(1). Let q(l) = 8*l - 232. Let s be q(29). Which is bigger: u or s? Ans: s Issue: Let d = 1166 + -1282. Which is smaller: d or 3? Ans: d Issue: Let t = 1 - -11. Let f be (-6)/(-9)*1/2. Which is smaller: f or t? Ans: f Issue: Let b = 38513 - 38512.81. Let s = 1 + -1.1. Is s bigger than b? Ans: False Issue: Suppose 9*z = -57 + 30. Suppose -5*c = 3*a + 11, 0*a - 2*c + 7 = 5*a. Let f be (-16)/a + 3/9. Is f greater than z? Ans: False Issue: Let r = 51 + -48. Let h = 4 - 2. Suppose 0 = 4*a + l - 9, -2*l - 4 + 2 = -h*a. Is a > r? Ans: False Issue: Let t be ((-366)/(-8))/((-30)/(-200)). Let f(g) = 0*g - 7*g - g**3 - 13*g - 323*g**2 + t*g**2. Let x be f(-17). Is -0.1 bigger than x? Ans: False Issue: Let h be 1/1 + 2 + (-874690)/59180. Let r be (-63)/396*(1 - -73). Let o = r - h. Is 1 greater than o? Ans: True Issue: Let i(u) = -3*u + 6. Let k be i(4). Let y = 16/3 + k. Which is bigger: y or -2? Ans: y Issue: Let m = 240 - 280.4. Let w = 40.2 + m. Which is greater: w or -218? Ans: w Issue: Suppose -4*a + 0*a + 140 = 0. Let k = a + -141/4. Is k equal to 0.033? Ans: False Issue: Let a = -35.34 + 36.34. Let o = -0.047 - 3.053. Which is smaller: a or o? Ans: o Issue: Let x = 56 - 26. Suppose 2*d - 6 = -4*s, d + d = 5*s - x. Suppose 2*j + 2*y = -3*j + 17, 0 = 5*j - s*y - 11. Is 3 not equal to j? Ans: False Issue: Let z = 40 + -28. Suppose 17*n + 5 = z*n. Which is smaller: n or 5? Ans: n Issue: Let t(d) = -8*d - 3. Let q be t(-1). Suppose 2*z - q*c + 2*c = 18, -2*z + c + 10 = 0. Let n be (2/z)/((-3)/18). Which is bigger: -0.05 or n? Ans: -0.05 Issue: Suppose -4*a - 4 + 28 = 0. Suppose a*h - 59 = -11. Is h greater than or equal to 10? Ans: False Issue: Let z be (6/(-10))/((-1)/5). Suppose -13 = z*v - 5*s, 3*v + s = -2*v - 3. Let u = -1/124 - 237/1364. Is u less than v? Ans: False Issue: Suppose 0 = -4*n + 5*i + 377, -3*n + 5*n = i + 187. Let x be n + -1 - (-6 - -3). Which is smaller: 98 or x? Ans: x Issue: Let d = 29.525 + 0.475. Let y = -40 - -159/4. Which is greater: y or d? Ans: d Issue: Let x = 1.49 - 11.09. Let y = x - -3.7. Which is greater: y or 0.1? Ans: 0.1 Issue: Let x = 0 - -1. Which is smaller: x or -1/4? Ans: -1/4 Issue: Let g(r) = -r**3 - 15*r**2 + 71*r - 7. Let u be g(4). Which is smaller: -25 or u? Ans: u Issue: Let u = -74 + 520/7. Let r = 6.09 + -0.09. Are r and u unequal? Ans: True Issue: Let n = -63 - -66. Suppose -l + 4*l = 5*y - n, -5*y = -2*l - 2. Is -1/119 < l? Ans: False Issue: Let q(j) = -j**3 - 10*j**2 + j + 4. Let a be q(-10). Which is smaller: -39/7 or a? Ans: a Issue: Suppose 0 = 2*x + r - 107, 0*x = -2*x - 5*r + 119. Let j be -4*(x/(-44) - -1). Which is greater: 2 or j? Ans: 2 Issue: Let f = 24 + -20. Suppose 5*p - 3*k - 25 = -f*k, 0 = 5*p - 3*k - 5. Suppose -12 = -3*s, 4*j + p = 7*s - 2*s. Is 4 < j? Ans: False Issue: Suppose -4*f = -n + 4*n + 1081, -2*n - 721 = 3*f. Let a = -8602 - -25804/3. Which is smaller: a or n? Ans: n Issue: Let l(s) = s**3 - 4*s**2 - 13*s + 6. Let w be l(6). Suppose 3*u - 6*u = w. Let i = 47/77 - 15/22. Which is bigger: i or u? Ans: u Issue: Let p be -1 + 6 - (-5 - -4). Let q = -6 + p. Which is greater: -4/3 or q? Ans: q Issue: Let n(g) = -g**2 + 10*g + 11. Suppose 3*l + 8 = 41. Let m be n(l). Does 2/5 = m? Ans: False Issue: Suppose 42 = -2*p + 4*p. Is p at most as big as 20? Ans: False Issue: Let m be (-72)/22 - (-7 + 5). Is m less than -1? Ans: True Issue: Suppose -5*y + a = -70, -4*a + 2 = -y - 3. Let o be (6/y)/((-28)/120). Suppose 2*q + 15 = -5*u, 0*q + 3*q = 0. Is u smaller than o? Ans: True Issue: Suppose 0 = -5*o - 3*n + 64 - 81, -2*o + n = -2. Is o less than -8/5? Ans: False Issue: Let o be (2/(-26))/(30/(-390)). Let f = -2.9 - -3. Let k = f - 0.09. Which is bigger: o or k? Ans: o Issue: Let a = 15 + -9. Let w = -1/47 + -2669/470. Let l = w + 249/20. Is a > l? Ans: False Issue: Let d(f) = -9*f + 15 + f**2 - 21 + 13 + f. Let l be d(7). Which is greater: -2/3 or l? Ans: l Issue: Let a = -7 + 7. Suppose a = -5*g - 37 - 18. Let z = g - -16. Is 6 greater than or equal to z? Ans: True Issue: Let l = -43 + 167/4. Is 0 >= l? Ans: True Issue: Let r = 7.04 - 8. Let n = -0.04 + r. Which is greater: 0 or n? Ans: 0 Issue: Let a be (-72)/105 + 4/10. Let b = -22 - -35. Let z = b - 8. Are a and z equal? Ans: False Issue: Let p be (-1296)/(-11424) + 2/(-14). Which is smaller: p or -1? Ans: -1 Issue: Let p = -17/30 + 1/15. Let b = 5 + -7. Which is smaller: p or b? Ans: b Issue: Suppose 4*z - 86 - 18 = 0. Suppose 3*a + 4*p - z = 0, 2*p - 3 - 5 = -a. Suppose -3*r - 5*f + 4*f = -1, a = 2*r + 3*f. Do r and 6/19 have the same value? Ans: False Issue: Suppose -4*u = 2 + 14. Is u equal to 0.1? Ans: False Issue: Let r = 0.452 + 0.078. Let u = -0.03 + r. Is -1/3 < u? Ans: True Issue: Let o = -122 - -180. Let c = o - 69. Which is smaller: c or -9? Ans: c Issue: Let w = 3 - 3. Suppose w*k = 3*k + 3. Let d = 13/12 + -31/36. Which is smaller: d or k? Ans: k Issue: Let j be -1*(136/(-66) + 2). Let u be 4/3 + 3/(-9). Which is smaller: j or u? Ans: j Issue: Let z be 24*(-4 + 18/4). Suppose 8 = -8*n + z*n. Is n at least 14? Ans: False Issue: Let r be ((-5282)/570)/((-1)/(-411)). Do r and 0 have the same value? Ans: False Issue: Let u = -6 - -5. Let y be 3 - (2 + 9 + u). Are y and -8 nonequal? Ans: True Issue: Let v = -767.1 - -767.2. Let h = 6.11 + -0.11. Which is bigger: h or v? Ans: h Issue: Suppose -2*s = -2*c + 2, 0*c + 2 = -2*s - c. Let u be s + 0 - -2 - 2. Let n be (-1)/(-2)*u/(-2). Which is greater: -1 or n? Ans: n Issue: Let f be 15/20 - (-75)/12. Is f at most 8? Ans: True Issue: Let c be -3*(16/80 - 2846/14130). Suppose -3*r = 4 - 1. Is r >= c? Ans: False Issue: Let w be (-8)/36 - (-928)/(-36). Do w and -26 have the same value? Ans: True Issue: Let q(w) = 44*w + 88. Let s be q(-2). Which is bigger: 2/121 or s? Ans: 2/121 Issue: Let i = -15 + -11. Let a = 37 + i. Is 12 at least as big as a? Ans: True Issue: Let a = -23 - -17. Let n be (12/(-172))/(a/4). Let y = -768 + 769. Are y and n nonequal? Ans: True Issue: Suppose -4*h = -2*l + 5*l + 4, 3*h + 3 = l. Which is smaller: 95/6 or l? Ans: l Issue: Suppose k + k = -8, 4*u - 2*k - 820 = 0. Suppose -15*b + 232 = -u. Is 34 equal to b? Ans: False Issue: Let a = 124 - 134. Let l be (1668/(-21) - 2)*5/a. Is l at most as big as 41? Ans: True Issue: Suppose -3*d + 12 = 0, -5*q = -0*q - d - 1. Let n be -3*((-2)/(-5) - 152/30). Let f be ((-144)/168)/(q*(-9)/n). Which is bigger: f or -0.1? Ans: f Issue: Let b(x) = -3*x**2 + 16*x - 18. Let v(l) = l**2 + l + 1. Let s = 97 - 95. Let q(y) = s*v(y) + b(y). Let r be q(19). Which is bigger: -36 or r? Ans: r Issue: Let q(l) = -l**3 - 10*l**2 + 11*l + 59. Let t be q(-17). Is 5684/3 smaller than t? Ans: True Issue: Let g = -15 + 16. Which is smaller: g or -2/13? Ans: -2/13 Issue: Suppose 42*q + 169 = 337. Let k be 24*-1*(-3)/4. Let b be (27/k)/((-6)/(-20)). Which is bigger: b or q? Ans: b Issue: Let y = 10 + -13. Suppose 4*p = 4*f + 12, -6*p + 7*p + f - 3 = 0. Suppose 2*d - 4*r - 3 = 3*d, 9 = -p*d + 4*r. Is d at most y? Ans: True Issue: Let d = -0.25 - -34.25. Let s = 1.868 + -36.028. Let m = d + s. Which is greater: m or -0.2? Ans: m Issue: Let c be 152/20 - (-2)/5. Suppose -2*o + c = -4*o. Is o <= -5? Ans: False Issue: Suppose -9*v - 4 = -7*v. Let z be (4/(-14))/((-9)/63) + v. Suppose -4*s + z*s = -3*y + 48, 25 = -3*s + 5*y. Which is smaller: -13 or s? Ans: s Issue: Let n = -10 - -8. Which is bigger: n or 11? Ans: 11 Issue: Suppose 0 = 4*j - z - 4, 4*j + 11 = -3*z - 1. Suppose 0 = -l - 3*m + 17, -5*m = -j*l - l - 23. Suppose 2*c = l*w - 10, 3 - 12 = -3*w. Which is smaller: 0 or c? Ans: c Issue: Let l(a) = a - 7. Let w be l(9). Let u = -3 + w. Let o be 2*(-1 + (-12)/(-11)). Which is greater: u or o? Ans: o Issue: Suppose 37*d - 41*d - 3*t = -11152, -d + 2810 = -2*t. Are 2794 and d equal? Ans: True Issue: Suppose l = -k + 7, 24 = -k + 3*k + 4*l. Let n be 51/15 - k/5. Suppose -n*p = -8*p + 10. Is p greater than or equal to 0? Ans: True Issue: Let g(t) = -2*t**2 - 11*t + 89. Let k be g(-10). Which is greater: -0.0122 or k? Ans: -0.0122 Issue: Let k = -0.051 + -21.949. Let n = 13.9 + 4.1. Let z = k + n. Is z at least as big as 1? Ans: False Issue: Suppose 36 = 2*h - 6*h + 5*m, -m - 8 = 3*h. Which is smaller: h or -9/2? Ans: -9/2 Issue: Let q = 2137 + -6735. Are q and -4598 unequal? Ans: False Issue: Suppose -725 = 2*l - 7*l. Let c be 33/55 - 77/l. Which is smaller: 1 or c? Ans: c Issue: Let u be (-14)/91 - 50/13. Let x be (-5)/(u + 24/16). Let y = -1/269 + 2967/2152. Which is greater: x or y? Ans: x Issue: Suppose 2*s = 3*n + 534, -4*n = 75*s - 80*s + 1314. Which is bigger: 255 or s? Ans: s Issue: Let u(o) = o**3 + 9*o**2 + 14*o + 5. Suppose -30 = 4*k + d, 2*k - 1 + 5 = 5*d. Let h be u(k). Let s be 4/12 + 26/6. Which is bigger: h or s? Ans: h Issue: Let f be 4/2 - (-3 - -2). Suppose -8*o = -3*o. Let z = f + o. Which is smaller: z or 2? Ans: 2 Issue: Let r be (-8253)/(-1703) + (0/(-2) - 5). Which is smaller: 29 or r? Ans: r Issue: Let o = 11 + 0. Suppose f - 4*f + o = 4*g, -3*g + 10 = 4*f. Suppose -w - 10 = -6*w. Is g smaller than w? Ans: False Issue: Let i be 0/1 + (-6 - -10). Let w = -3 + 6. Is i bigger than w? Ans: True Issue: Let u = 14405 + -5874. Which is bigger: 8529 or u? Ans: u Issue: Let t(j) = j + 5. Let d be t(-5). Let l(h) = -h**3 - 12*h**2 + 34*h + 3. Let k be l(-9). Let y be (-6)/(-5) - k/(-405). Which is greater: y or d? Ans: d Issue: Let d(o) = -5*o**3 + 5*o - 5. Let y(v) = 5 - 10 - 2*v**2 + 3*v**2 - 4*v**3 + 4*v. Let x(u) = 3*d(u) - 4*y(u). Let f be x(4). Are 1/14 and f unequal? Ans: True Issue: Let k = 16.1 + -16. Is k at most as big as -2? Ans: False Issue: Let g = -9043 - -9162. Are 118 and g equal? Ans: False Issue: Let g(t) = -t**2 - 67*t + 627. Let h be g(-77). Which is smaller: h or -2? Ans: h Issue: Suppose -3*q + z = -1 + 15, 5*z - 20 = 5*q. Let s be 5*(-6)/(-1 + q). Suppose s*o = -3*w - 21, -w = o + 4*o + 17. Which is greater: -5 or o? Ans: o Issue: Let q = 4238.4 - 4238. Let f = 0.39 - -0.01. Let y = f - -2.6. Which is smaller: q or y? Ans: q Issue: Suppose 8 = -0*f + f. Let c be (2 - 5) + f + -6. Which is bigger: c or 0? Ans: 0 Issue: Suppose 3*s = -5*d + 16, -3*d - d - 2*s + 14 = 0. Let v be (4/5)/(6/d). Which is greater: v or 2? Ans: 2 Issue: Let h = 101303691/272853350 + -1/189350. Let v be 2/(-4)*4/(-262). Let l = v - h. Which is bigger: 0 or l? Ans: 0 Issue: Let z be 8/44 + 8/22. Suppose -b + 2*c = -3*c + 23, -5*b - 23 = -2*c. Let k(w) = w**2 + 3*w + 1. Let p be k(b). Is z greater than or equal to p? Ans: False Issue: Let m(t) be the third derivative of -t**4/12 + 7*t**3/6 - 37*t**2. Let x(n) = 2*n - 8. Let r(o) = -3*m(o) - 4*x(o). Let j be r(6). Which is smaller: -3/5 or j? Ans: j Issue: Suppose 4*d - s - 2*s = -12, -4*d + 5*s = 20. Let f = -5089 + 5086.1. Which is smaller: f or d? Ans: f Issue: Let n be 2 - 107313/(-294)*-2. Let c = -728 - n. Are c and 0 equal? Ans: False Issue: Let n(i) = 2*i - 2. Let w be n(2). Suppose -6 = 2*b - w*f, 2*f + f = -5*b + 9. Is 0 <= b? Ans: True Issue: Suppose -6*k - 17 = 1. Is k < -46/11? Ans: False Issue: Let y be (-3)/18 - (-1772)/(-24). Is y at least -74? Ans: True Issue: Let x = -0.107 + 0.107. Let w be ((-93)/15 + 5)/(3/2). Is w != x? Ans: True Issue: Let m = -27 - -45. Let p(d) = 16*d**2 + d. Suppose 18 = 6*r + 12*r. Let w be p(r). Is m greater than w? Ans: True Issue: Let h = -19 + 20. Let u be (h - (-20)/(-16))*3. Is u equal to 0? Ans: False Issue: Suppose -869 = -4*a - 3*n - 586, -2*n = -2*a + 124. Let z(f) = -35*f. Let j be z(-2). Is j equal to a? Ans: False Issue: Let r = -26 - -15. Let w = r - -3. Do w and 0.2 have the same value? Ans: False Issue: Let l be (-7 + 3)/2 + 0. Suppose 10*x - 4*x = -6. Is l at most x? Ans: True Issue: Let z(q) = q**3 + q**2 - 11*q. Let n be z(3). Let c be ((-1)/n)/(2/4). Which is bigger: c or 2/11? Ans: 2/11 Issue: Suppose 0*q + 9 = 3*q. Let s be (q - 33/9)*33. Let p be (-4)/s + 228/(-44). Do -6 and p have the same value? Ans: False Issue: Let l be -4*((-1)/2 + 0). Let p = l + -2. Let z be (1 + (-12)/10)/((-126)/70). Which is greater: z or p? Ans: z Issue: Let t = 1709 - 1707. Are t and -1077 unequal? Ans: True Issue: Let i(t) = 3*t + 19. Let f be i(-8). Let n = f + 8. Let d be (3 + (-27)/10)/n. Is d <= -1? Ans: False Issue: Let l = -9.7 + 10.3. Let c = 1 + -0.6. Let f = c - l. Is f at most 0? Ans: True Issue: Let u = -2 + -3. Let y = -16.77 + -0.23. Let h = 17 + y. Are h and u non-equal? Ans: True Issue: Let h(d) = -d + 2. Let a be h(2). Let p be 2/(-12) + (-1)/(-15). Is p less than a? Ans: True Issue: Let n(p) be the second derivative of -p**5/10 + 7*p**4/6 - 4*p**3/3 - 5*p**2/2 - 21*p. Let c be n(6). Is c greater than 0.1? Ans: True Issue: Suppose 4*l - 4 = 0, 3*b + 0*l = -4*l + 4. Is b <= -1? Ans: False Issue: Let c = 4.1 + -5. Let l = c + -0.1. Which is bigger: l or -1/11? Ans: -1/11 Issue: Let f = -0.88 - -0.98. Which is bigger: f or 59? Ans: 59 Issue: Let n be ((-1)/(618/76))/4. Let q = n + 4970/5871. Let b = q + -6/19. Which is smaller: -0.2 or b? Ans: -0.2 Issue: Let v = -30 + 19. Let k(i) = -12*i - 3. Let y be k(-1). Suppose -49*z = -50*z - y. Is z != v? Ans: True<|endoftext|>numbers: place value composed ----------------------------- Subject: Suppose -5*o = f - 47, -5*f - 4*o = -2*f - 196. Suppose 8171*t - 8165*t = 12. What is the tens digit of 2/((-4)/t)*(2 - f)? Ans: 7 Subject: Suppose 3*a + 2*p - 7532 = 5066, -20998 = -5*a - 4*p. What is the hundreds digit of a? Ans: 1 Subject: Suppose 4*b - 53161 = -l, -4*b + 53164 = 248*l - 244*l. What is the ten thousands digit of b? Ans: 1 Subject: Let x(z) = -1398*z - 7046. What is the hundreds digit of x(-24)? Ans: 5 Subject: Let r = -9 + 9. Suppose 8*z - 2*x + 972 = 3*z, r = 3*z - 5*x + 568. What is the tens digit of (-7)/(z/96)*7? Ans: 2 Subject: Let j be 5/1*4/(-10). Let r(w) be the first derivative of 2*w**3/3 + w**2/2 + w + 1. What is the units digit of r(j)? Ans: 7 Subject: Let i(m) = -m + 1. Let t be i(-3). Suppose t*o + 11 = 2*o - 5*d, -2*o + 13 = -3*d. What is the units digit of o/(-4) + (-7)/(-2)? Ans: 3 Subject: Suppose -r + 50 - 18 = y, -3*y + r = -100. What is the tens digit of y? Ans: 3 Subject: Let a = -44 - -39. Let n be (3844/4)/1 + 5/a. Suppose -4*v + n - 44 = 0. What is the tens digit of v? Ans: 2 Subject: Let m = -30 - -58. Suppose -u + 2*u - 10 = 3*q, m = 5*u - 4*q. Suppose -3*f + 345 = -u*r, 4*r - 604 = -5*f + r. What is the tens digit of f? Ans: 1 Subject: Let d(r) = 6*r**2 + 8*r + 33. Let z(l) = 5*l**2 + 8*l + 33. Let t(i) = 6*d(i) - 7*z(i). What is the tens digit of t(-10)? Ans: 4 Subject: Suppose 0 = -2*z + 4*s + 18830, 3*z + 5*s - 28183 = 51. What is the units digit of z? Ans: 3 Subject: Let h be 7*52 - (0 - 1). Suppose -172 = w - 2*u, -730*u + 734*u - 178 = w. Let d = h + w. What is the units digit of d? Ans: 9 Subject: Let m(h) be the second derivative of h**6/120 - 5*h**4/12 - 5*h. Let b(y) be the third derivative of m(y). What is the units digit of b(1)? Ans: 6 Subject: Suppose 8862*v = 8896*v - 374204. What is the tens digit of v? Ans: 0 Subject: Suppose -4*v - 5*r = -9891, v - 4*r = 911 + 1546. What is the hundreds digit of v? Ans: 4 Subject: Let g be (-2 - -14)*(-6)/(-18). Suppose -5*l + z = -6, -4*l = -3*z + 5*z - 16. What is the units digit of (-2)/g - (-19)/l? Ans: 9 Subject: Let z(r) = -r**3 - 2*r**2 + 3*r + 8. Suppose -16 = 5*p + 3*w, 7*w - 34 = 5*p + 4*w. Let i be z(p). Suppose -3*q + i = -34. What is the units digit of q? Ans: 4 Subject: Let k = 260 + 1426. What is the hundreds digit of k? Ans: 6 Subject: Let n = -164 - -322. Let f = -80 + n. What is the tens digit of f? Ans: 7 Subject: Let d = -3 - 7. What is the units digit of (-10)/25 + (-54)/d? Ans: 5 Subject: Let k(b) be the third derivative of -b**4/24 - b**2. Let d be k(-2). Suppose 0*x + 2*u + 6 = d*x, -5*x - 1 = 3*u. What is the units digit of x? Ans: 1 Subject: Let g(j) = j**2 - 6*j + 25. Suppose -22*x = -24*x + 24. What is the tens digit of g(x)? Ans: 9 Subject: Let j(n) = -n - 5. Let y be 3 + -5 - 95/5. What is the units digit of j(y)? Ans: 6 Subject: Let d = 12 - 15. What is the units digit of (d - -7 - 8) + 10? Ans: 6 Subject: Let r(q) = -300*q + 6. What is the tens digit of r(-1)? Ans: 0 Subject: Let h be (3/(-6))/(2/4). Let r(s) = -20*s**3 + s**2 - s - 1. Let o be r(h). Let g = -18 + o. What is the units digit of g? Ans: 3 Subject: Let l = 16 + 373. Let q = l - 199. What is the tens digit of q? Ans: 9 Subject: Let o(c) = 28*c + 2. Let w be o(6). Let z = w - 21. What is the tens digit of z? Ans: 4 Subject: Let m(b) = -5*b - 167. Let h be m(-32). Let d(z) = -110*z + 24. What is the units digit of d(h)? Ans: 4 Subject: Suppose 0 = -28*w + 10791 + 3517. What is the units digit of w? Ans: 1 Subject: Let s(x) = -x**2 - 7*x - 3. Suppose h - 2 = -5*n, 4*h + 5*n + 4 = h. Let m be s(h). Let p = m - -24. What is the units digit of p? Ans: 3 Subject: Let y(q) = 3*q - 4. Let u(o) = -2*o + 4. Let c(r) = 4*u(r) + 3*y(r). Let b be c(-4). Let g = b - -4. What is the units digit of g? Ans: 4 Subject: Let u(v) = 147*v + 2. What is the units digit of u(3)? Ans: 3 Subject: What is the units digit of (-174)/(-14)*206 + 2/(-7)? Ans: 0 Subject: Let n be (15/12)/((-5)/(-20)). What is the tens digit of 25 + -4*n/(-20)? Ans: 2 Subject: What is the units digit of (341/(-44) - -7)/((-42)/577976)? Ans: 1 Subject: Let u be 1/(-2) - 25/(-2). Let x be u/4*220/12. Let o = -11 + x. What is the units digit of o? Ans: 4 Subject: Let j(b) = -19*b**2 + 7*b - 1. Let m(v) = -96*v**2 + 36*v - 4. Let f(u) = -16*j(u) + 3*m(u). What is the tens digit of f(2)? Ans: 6 Subject: Suppose q + 2*q + 2*k - 430 = 0, -3*q - 3*k + 426 = 0. What is the hundreds digit of q? Ans: 1 Subject: What is the units digit of (-19707425)/2355*54/(-10)? Ans: 9 Subject: Let c(v) = -2*v**2 + 22*v + 3. What is the tens digit of c(9)? Ans: 3 Subject: Let t = -24 + 17. Let g(m) = 3*m - 16. Let j(l) = -4*l + 18. Let i(k) = 7*g(k) + 6*j(k). What is the tens digit of i(t)? Ans: 1 Subject: Let r(a) = -a**3 + 2*a**2 - 4*a - 3. Let g(m) = -m**3 + m + 1. Let o(n) = 3*g(n) + r(n). Let s be o(1). What is the tens digit of 81*(-6 - s)/(-9)? Ans: 2 Subject: Let f be ((-3)/((-24)/(-16)))/((-1)/3). Let o be (-3 - (-574)/f)/(5/(-1485)). What is the hundreds digit of o/(-154) - 2/(-7)? Ans: 1 Subject: Let c(s) = -s + 3. Let m be c(4). What is the units digit of (0/3)/(m - -2) + 82? Ans: 2 Subject: Let p be -145 + 8 + -6 - (-3 - -1). Let g = p + 459. What is the hundreds digit of g? Ans: 3 Subject: Let c(s) = -3*s**3 + 1. Let k be c(-1). Suppose 2*g - 474 = 5*h, 3*g + 304 + 89 = -k*h. What is the units digit of 15/(-4)*h/18? Ans: 0 Subject: Let c = -3 + 1. Let s(k) = 2*k**2 - k. What is the tens digit of s(c)? Ans: 1 Subject: Suppose 9766 = -98*t + 31979 + 141839. What is the thousands digit of t? Ans: 1 Subject: Let m be 4/(-14) - (-430)/(-14). Let i = -33 - m. What is the units digit of 2 + (6/i - -2)? Ans: 1 Subject: Let x(t) = -6*t + 0*t + 9 + t. Let z be x(1). Suppose g - q - 3*q = 180, -3*g + 572 = -z*q. What is the tens digit of g? Ans: 9 Subject: What is the tens digit of 2/6 - 655/(-15)? Ans: 4 Subject: Suppose -7*q + 14*q = 2149. Let w = 469 - q. What is the tens digit of w? Ans: 6 Subject: Suppose 4*r + 5*a = 29, 3*r - 3*a = -0*a - 12. What is the units digit of r*(-1 + (1 - -3)) - -106? Ans: 9 Subject: Suppose -2*v - 462 = 378. Let k = v - -605. Let s = 264 - k. What is the tens digit of s? Ans: 7 Subject: Let t = -46 - -48. Suppose -223 = -t*d + 2*y - 3*y, -5*d + 547 = -y. What is the units digit of d? Ans: 0 Subject: Suppose 420 = -4*d + 7*d. What is the tens digit of d? Ans: 4 Subject: Let p = -5 - -9. Suppose -3*h + 65 - 5 = 5*m, 2*h = -p*m + 46. What is the units digit of m? Ans: 9 Subject: Let t(y) = -y**3 - 9*y**2 - 8*y + 1. Let u be t(-8). Let q(c) = 2*c**2 - 2*c + 1. What is the units digit of q(u)? Ans: 1 Subject: Suppose -2*y - 16 + 1 = 5*k, 0 = -4*y - 3*k + 5. Suppose 2*g - y*g = -48. What is the units digit of g? Ans: 6 Subject: What is the tens digit of 16470/(-54)*14/(-5)? Ans: 5 Subject: Let f = 191 - 188. Suppose 0 = -f*n + 13 - 1, 3*l - 1107 = -3*n. What is the units digit of l? Ans: 5 Subject: Suppose 5*j - 4628 = -3*m, 32*j + 2*m = 27*j + 4632. What is the units digit of j? Ans: 8 Subject: Suppose -320*p + 2300118 + 6858004 = -705558. What is the thousands digit of p? Ans: 0 Subject: Let z = 4 - 5. Let y = z - -2. Suppose 0 = c, 3*c + y = s - 2. What is the units digit of s? Ans: 3 Subject: What is the units digit of 39/(-12*6/(-1536))? Ans: 2 Subject: Suppose 0 = -10*i + 4169 + 2441. What is the units digit of i? Ans: 1 Subject: Suppose 0 = b - 4*f - 694, b - 2746 = -3*b + f. Suppose 15*t = 29*t - b. What is the tens digit of t? Ans: 4 Subject: Let i(c) be the first derivative of 44*c**3/3 + c + 9. What is the units digit of i(-1)? Ans: 5 Subject: Let d(p) = -9*p**2 - 15*p - 1. Let j(b) = b**2 + 2*b + 1. Let u(x) = -3*d(x) - 21*j(x). What is the units digit of u(7)? Ans: 7 Subject: Let b be 9/(-7) - (-22)/77 - -2689. Suppose 13*k = b + 926. What is the hundreds digit of k? Ans: 2 Subject: Let f(i) = 4*i - 18. Let h be f(5). Let u = h + 113. What is the units digit of u? Ans: 5 Subject: Let g = 5851 + -4505. What is the thousands digit of g? Ans: 1 Subject: Suppose 238*q + 4 = 239*q, -17*q + 75998 = 5*j. What is the tens digit of j? Ans: 8 Subject: Let k be ((-18)/15)/((-4)/10). Let p be 80/15 - 1/k. What is the units digit of (-1 - -6)*2/p? Ans: 2 Subject: Let t(v) be the third derivative of 8*v**5/15 + v**4/8 + 5*v**3/6 + 23*v**2. What is the hundreds digit of t(-2)? Ans: 1 Subject: Let a(w) = 5*w - 23. Let n be a(5). Suppose 3*y + 5 = n. Let m(v) = -69*v - 2. What is the units digit of m(y)? Ans: 7 Subject: Let x be ((-10)/8)/((-14408)/1440 - -10). Let o = 11 + 100. Let s = x - o. What is the units digit of s? Ans: 4 Subject: Suppose -5*l - z + 12985 = 0, l = -2*l + 2*z + 7791. What is the thousands digit of l? Ans: 2 Subject: Let h = 106 - 13. What is the tens digit of h? Ans: 9 Subject: What is the tens digit of (-2)/(-4 + (-5)/1070 + 4)? Ans: 2 Subject: Let t(x) = 161*x**2 + 7*x + 28. Let m = 592 + -595. What is the units digit of t(m)? Ans: 6 Subject: Let y = 18 + -34. Let t = -8 - y. What is the units digit of t? Ans: 8 Subject: Suppose 4*j - 3*r = 98282 - 965, -r = -5*j + 121627. What is the ten thousands digit of j? Ans: 2 Subject: Let a = -4 - 35. Let s = 62 + a. What is the units digit of s? Ans: 3 Subject: Let q be (14/63)/((-2)/(-3))*24. Suppose -4*s = q, 0 = -o + s - 1 + 6. What is the units digit of 2*(o + 0)/6? Ans: 1 Subject: Suppose 4*t - 4 = -0. Suppose 2*b - 1 = t. What is the units digit of b? Ans: 1 Subject: Let b = -32 + 39. Suppose -2*i + 2*y - b*y = -311, 4*y - 12 = 0. What is the tens digit of i? Ans: 4 Subject: Let z(q) = 3*q**2 + 6*q - 49. Let p be z(-9). Suppose 0 = 2*g - 114 - p. What is the units digit of g? Ans: 7 Subject: Let h = -2 - -7. Let c be -3 + 4 - (15*-1 + 0). Suppose -h*o + 4*o + c = 0. What is the units digit of o? Ans: 6 Subject: Let a be (-4)/((-4)/2) - 2. Let z be 2 + -1*2 - a. Suppose 3*t + z*t = 27. What is the units digit of t? Ans: 9 Subject: Suppose 6*t - 38 = 250. What is the tens digit of t? Ans: 4 Subject: Let l be (6*-1)/(1 - 0). Let y = 11 - 15. Let m = y - l. What is the units digit of m? Ans: 2 Subject: Suppose -n + 3 = 4. What is the hundreds digit of 3/(-1 - 0) - 106/n? Ans: 1 Subject: Suppose -4*s + 14 = -2*h, -2*s - 8 + 21 = 5*h. Suppose -s*y + 4*b + 72 = 0, 0 = 2*y + 4*b - 21 + 3. Let w = -9 + y. What is the units digit of w? Ans: 6 Subject: Let x be (4 + -14)*49/(-14). Let f(l) = -2*l**2 + 81*l - 45. What is the units digit of f(x)? Ans: 0 Subject: Suppose -529 = -7*l + 199. What is the units digit of l? Ans: 4 Subject: Suppose 4*y - 4*u = 5*y - 736, 0 = -5*y + 4*u + 3800. What is the tens digit of y? Ans: 5 Subject: Let k(v) = v - 9. Let s be k(11). Suppose -i - 449 = -m, -4*i = -s*m - i + 896. What is the tens digit of m? Ans: 5 Subject: Let a = -945 + 939. Let d(s) = 2*s**3 + 10*s**2 + 10*s + 22. Let u(j) = 1. Let r(i) = -d(i) + u(i). What is the units digit of r(a)? Ans: 1 Subject: Let b(w) be the first derivative of -w**4/4 - 8*w**3/3 + 7*w**2 + 19*w - 6. Let m be b(-9). What is the tens digit of -3 + 1 + 1 - m? Ans: 2 Subject: Suppose -4*z = -3*p + 27, -2*z - 15 = -4*p + p. Let t(n) = n**3 + 2*n**2 - 8*n - 6. Let x be t(z). Let h = -38 - x. What is the units digit of h? Ans: 4 Subject: Let a be (-6)/15 - (-26)/(-10). Let d = a + 3. Suppose d = -2*u + 2*c - 6, 2*c - 13 = -2*u - 3*u. What is the units digit of u? Ans: 1 Subject: Let h(s) = -93*s - 112. What is the tens digit of h(-6)? Ans: 4 Subject: Let h(a) = 189*a**3 + a**2 - 15*a + 72. What is the hundreds digit of h(6)? Ans: 8 Subject: What is the hundreds digit of -2 - (1/2 - 831/6)? Ans: 1 Subject: Suppose -6*m + 646 = -578. What is the tens digit of m? Ans: 0 Subject: Let v = 82 - 18. Suppose 4*f = -2*g + 74, v = 3*g + f - 37. Suppose -3*w = 5*c - g, 6*w - 3*c = 2*w + 15. What is the units digit of w? Ans: 6 Subject: Let v(o) = 20*o - 1. Let y be v(1). Let g = y + -5. What is the tens digit of g? Ans: 1 Subject: Let n = 1120 - 1610. Let a = 1218 + n. What is the hundreds digit of a? Ans: 7 Subject: Suppose 0 = -k + 5*a + 13, -4*a = -a + 6. Suppose 4*g - z - k*z = 80, 2*g - 46 = -4*z. What is the units digit of g? Ans: 1 Subject: Let b(i) = 118*i + 17. What is the hundreds digit of b(3)? Ans: 3 Subject: What is the units digit of 1 + 36/(-8)*2 - -9341? Ans: 3 Subject: Let m be (-42)/(-8)*((-15)/5 - 1). Let c = m + -104. Let z = -58 - c. What is the tens digit of z? Ans: 6 Subject: Suppose -5*p + 2430 = -6*g + g, -5*p = -4*g - 2435. What is the units digit of p? Ans: 1 Subject: Let u(h) = 2*h + 4*h - 9 - 5*h + 2*h. Let t be u(5). Suppose 60 = 5*s + 5*y, -56 = -t*s + s - y. What is the units digit of s? Ans: 1 Subject: Let c(m) = 4*m**3 - 2*m + 1. Let p be c(2). Let o = p + -11. What is the tens digit of o? Ans: 1 Subject: Suppose 0 = -5*x + 9*x - 156. What is the units digit of x? Ans: 9 Subject: Let i be (8 - 0)/(6/12). Suppose -j + i = -5*z, 5 = -2*z - j - 0. What is the tens digit of 29*(-3)/z*1? Ans: 2 Subject: Suppose v = 4*b - 3 + 14, -2*v = -3*b - 12. Suppose -v*c = r - 3251, -c - 6*r + 1097 = -3*r. What is the tens digit of c? Ans: 8 Subject: Let p be ((-1)/3)/((-13)/195). Suppose a = -p*a - 132. What is the units digit of 3*(-11)/(a/24)? Ans: 6 Subject: Suppose -1940 = -7*t + 412. What is the hundreds digit of t? Ans: 3 Subject: Suppose -4*j = -2*j - 14. Suppose -c - 175 = -4*n, 3*n + j*c - 4*c = 120. What is the tens digit of n? Ans: 4 Subject: Suppose t - 3 + 0 = 0. Suppose -5*i + 12 = -t*i. Suppose 30 = 3*a + i. What is the units digit of a? Ans: 8 Subject: Suppose 4*f = 5*r + 45, 0*r = 4*f - 3*r - 35. Suppose -f*i + 17 + 8 = 0. Suppose 10*t - 40 = i*t. What is the units digit of t? Ans: 8 Subject: What is the units digit of (2 + 10 - 16)*2*(-3007 + -2)? Ans: 2 Subject: Let w(p) = -2*p - 5. Let m be w(-5). Suppose s + n + 17 = 4*s, s - n - m = 0. What is the units digit of s? Ans: 6 Subject: Suppose -5*a + 3*f + 4 = -2, -5*a - 10 = 5*f. Suppose a = -20*c + 16*c + 8. Suppose u - c*w = -6*w + 17, 4*u - 2*w = 68. What is the tens digit of u? Ans: 1 Subject: Let j = -136 + 844. Let z = -253 + j. What is the hundreds digit of z? Ans: 4 Subject: Let r be 4*(2 - (-63)/(-6)). Let h = r + 34. Suppose -3*y = 5*j - 159, 5*y - 265 = -h*y - j. What is the tens digit of y? Ans: 5 Subject: Suppose -6 = 4*f + 10. Let j(v) = 6 - 3*v + 2*v + 6*v + v**2. What is the units digit of j(f)? Ans: 2 Subject: Suppose 3 = -8*j - 269. What is the units digit of (4/10)/((-4)/(-10)) - j? Ans: 5 Subject: Suppose 5*h - 4*n - 35 = 0, 5*n + 12 = -h + 2*n. Suppose 5*x - 111 = h*l, -l - 4*l + 32 = 2*x. What is the units digit of x? Ans: 1 Subject: Let h(z) = -3*z**2 + z + 6. Let l(v) be the first derivative of v**3 - v**2/2 - 5*v + 5. Let m(k) = 4*h(k) + 5*l(k). What is the units digit of m(-1)? Ans: 3 Subject: Suppose -2*i = 4*o - 92, 0*i + o + 139 = 4*i. What is the units digit of i? Ans: 6 Subject: What is the tens digit of -290*(104/364)/(4/(-7))? Ans: 4 Subject: Let t = 5108 + 334. What is the thousands digit of t? Ans: 5 Subject: Suppose -5*p + 5 = -j - 6, 18 = 2*p + 3*j. What is the units digit of (-1762)/(-20) - p/30? Ans: 8 Subject: Let v be (2*-4)/((-6)/15). Suppose v = -5*z - 2*g - 3*g, 2 = 4*z - 5*g. What is the tens digit of 87/6 - z/(-4)? Ans: 1 Subject: Let g = 30 - 28. Let x(m) = -14*m**3 + 4*m - 4. Let r be x(g). What is the hundreds digit of (r/(-12))/(1/19)? Ans: 1 Subject: Let p(i) be the second derivative of 5*i**4/12 - 5*i**3/3 - 3*i**2/2 - 35*i. What is the units digit of p(5)? Ans: 2 Subject: Suppose -21*z = -14*z - 1379. What is the units digit of z? Ans: 7 Subject: Let u = 16 - -22. What is the units digit of u? Ans: 8 Subject: Let q(p) = -37*p + 36*p + 78*p + 16. What is the tens digit of q(2)? Ans: 7 Subject: Let x = -1235 + 4772. What is the units digit of x? Ans: 7 Subject: Let d be (2/(-2))/(-2*(-2)/(-20)). What is the hundreds digit of -1*(-5)/d - (-963 - -10)? Ans: 9 Subject: Let z be 8/(-4)*-77 + -6. Suppose 34*r - 32*r = z. What is the units digit of r? Ans: 4 Subject: Suppose -12*t - 6394 = -42718. What is the units digit of t? Ans: 7 Subject: Let w be -2*2461/(-10) - 2/10. Suppose o - w = 5*t, t = 3*o - 1220 - 242. What is the hundreds digit of o? Ans: 4 Subject: Let v be (-2)/((-1)/(-2)*4). Let m be (v + 3)/((-2)/(-8)). Let l(x) = x**2 - 7*x - 6. What is the units digit of l(m)? Ans: 2 Subject: Let a = 28 - -4. What is the tens digit of a? Ans: 3 Subject: Suppose -5*g + 28 + 2 = 0. Let j = 7 - g. What is the units digit of j? Ans: 1 Subject: Suppose 0*c - 25 = -2*c - 5*v, 2*v = -3*c + 43. Let k = 15 - c. Suppose -4*w + 102 + 90 = k. What is the tens digit of w? Ans: 4 Subject: Suppose 7*s - 26 = -3*b + 2*s, 4*b - 2*s = 26. Let w(q) = -q**3 + 7*q**2 - 7*q + 8. Let i be w(6). Suppose v - b = -i. What is the units digit of v? Ans: 5 Subject: Let v(i) be the first derivative of i**3/3 + 11*i**2/2 - 6*i + 2. Let k(r) = r**3 + 35*r**2 - 13. Let h be k(-35). What is the units digit of v(h)? Ans: 0 Subject: Suppose 23*t = 5*t + 36. Suppose -q + 0*c + 4*c = -292, -c + 584 = t*q. What is the units digit of q? Ans: 2 Subject: Let s(p) = -396*p - 457. What is the units digit of s(-3)? Ans: 1 Subject: Suppose -t + 27 = j, 0 = 4*j - 2*t - 3*t - 90. What is the tens digit of j? Ans: 2 Subject: Let r = -1 - 1. What is the units digit of ((-28)/10)/(r/5)? Ans: 7 Subject: Suppose 10*y - y + 1233 = 0. Let u = -135 - y. Suppose 2*z = -u*h + 106, z - 5*h - 31 - 28 = 0. What is the tens digit of z? Ans: 5 Subject: Let s be (0 - 3)/1*35/21. Let m be (8/5)/(-4)*(0 + s). Suppose -3*o = -5*c - 299, -m*o + 96 = -5*c - 110. What is the units digit of o? Ans: 3 Subject: Let a be 0 - (0 - -2)/2. What is the units digit of (-5)/a + 0/(-4)? Ans: 5 Subject: Suppose -13*r - 626 + 17500 = 0. What is the units digit of r? Ans: 8 Subject: Suppose -49*h + 34*h + 26*h = 17292. What is the thousands digit of h? Ans: 1 Subject: Suppose -9*t + 12*t = -h + 1290, 0 = 3*h. What is the units digit of t? Ans: 0 Subject: Let s = 55052 + -24949. What is the thousands digit of s? Ans: 0 Subject: Let g be 12/(-18) + 2/(-12)*-22. Suppose g*h + 18 = w, 2*w + 0*h = 5*h + 31. Suppose -237 = -a - 2*a + w*m, 2*a - 158 = m. What is the tens digit of a? Ans: 7 Subject: Let i(o) = -56*o - 16. Let g be i(-10). Suppose -3*y - s - 1333 = -8*y, g = 2*y + 5*s. What is the units digit of y? Ans: 7 Subject: Let d = 83 - 79. Suppose 0*y = -d*y + 2752. What is the tens digit of y? Ans: 8 Subject: Let g(u) be the third derivative of 0*u + 1/6*u**4 + 7/60*u**5 - 1/2*u**3 + 0 + 4*u**2. What is the units digit of g(2)? Ans: 3
[{"idx": "txt360/comparison__pair_composed_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-3.jsonl"}, {"idx": "txt360/numbers__place_value_composed_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-3.jsonl"}]
How to find the hardware chipset information? Question: Is there any software, using which, I can detect the chipset versions/name (like Audio ALC889, Network 8111E, etc). I want to detect these chipsets of my hardware. I tried software CPUID, but it's not providing such information. What I really need is this. Check the website [IDX] is Realtek® ALC 892 LAN is Realtek® 8111E I want to see this information from my system/BIOS or any tool. Comment: Never tried it but maybe you can determine it using the vendor ID in the bios... [IDX] Speccy can do this, and it also has a Portable Edition available. Summary Motherboard Network Comment: Its showing me same Realtek PCIe GBE Family Controller for Network, whats its chipset number? 8111B, 8111C or 8111E? I want that exact info Comment: @coure2011: What do you need it for? You can't determine it automatically until after you installed the drivers, that's because you need to search the hardware ID of Device Manager on Google. It's not necessary to know that to install the drivers... Answer: I typically discover chipsets by going to the Device Manager, right clicking on the appropriate device and going to Properties. On the Details tab, sift through the drop down options for anything telling. If it's not obvious there, I take the ID from Hardware Ids and google them. Comment: That's what I suggested [here]( [IDX] but that's not what is currently being asked. The question is a bit vague... Comment: `on the appropriate device` what is appropriate device for laptop chipset? no one. The answer is not useful Comment: @Suncatcher The original question listed multiple devices, therefore "the appropriate device" Answer: If you have an Intel chipset, this would apply: Intel Chipset Identification Software Comment: @coure2011 If you've found and tried something and it didn't work, mention it in the question so we don't waste time suggesting things you've already discounted. Comment: @coure2011: That's what your title asked, it identifies the Motherboard Chipset. Comment: offcourse I came here after searching on google, its the first link that comes in google search with keyword "chipset detection". Dont provide information like this.. Comment: Must warn - it does not appear to work on the latest version of Windows 10. May need to find another method... Answer: I usually use SIW (System Information for Windows): SIW is an advanced System Information for Windows tool that analyzes your computer and gathers detailed information about system properties and settings and displays it in an extremely comprehensible manner. The System Information is divided into few major categories: Software Information: Operating System, Software Licenses (Product Keys / Serial Numbers / CD Key), Installed Software and Hotfixes, Processes, Services, Users, Open Files, System Uptime, Installed Codecs, Passwords Recovery, Server Configuration. Hardware Information: Motherboard, CPU, Sensors, BIOS, chipset, PCI/AGP, USB and ISA/PnP Devices, Memory, Video Card, Monitor, Disk Drives, CD/DVD Devices, SCSI Devices, S.M.A.R.T., Ports, Printers. Network Information: Network Cards, Network Shares, currently active Network Connections, Open Ports. Network Tools: MAC Address Changer, Neighborhood Scan, Ping, Trace, Statistics, Broadband Speed Test Miscellaneous Tools: Eureka! (Reveal lost passwords hidden behind asterisks), Monitor Test, Shutdown / Restart. Real-time monitors: CPU, Memory, Page File usage and Network Traffic.<|endoftext|>"cond","and" and "or" in Scheme Question: I'm reading The Little Schemer. And thanks to my broken English, I was confused by this paragraph: (cond ... ) also has the property of not considering all of its arguments. Because of this property, however, neither (and ... ) nor (or ... ) can be defined as functions in terms of (cond ... ), though both (and ... ) and (or ... ) can be expressed as abbreviations of (cond ... )-expressions: <code>(and a b) = (cond (a b) (else #f) and (or a b) = (cond (a #t) (else (b)) </code> If I understand it correctly, it says (and ...) and (or ...) can be replaced by a (cond ...) expression, but cannot be defined as a function that contains (cond ...). Why is it so? Does it have anything to do with the variant arguments? Thanks. p.s. I did some searching but only found that (cond ...) ignores the expressions when one of its conditions evaluate to #f. Comment: In addition to the answers that you get here, you might look at the answers to [Why (apply and '(1 2 3)) doesn't work while (and 1 2 3) works in R5RS?]( [IDX] and [Using AND with the apply function in Scheme]( [IDX] The topic of the questions is a little different than your question, but the answers explain some of the same concepts. Comment: Thank you! The two posts are quite enlightening. Now I think I need to read the SICP. Comment: It's well worth the read, and it's [available for free online]( [IDX] Imagine you wrote <code>if</code> as a function/procedure rather than a user defined macro/syntax: <code>;; makes if in terms of cond (define (my-if predicate consequent alternative) (cond (predicate consequent) (else alternative))) ;; example that works (define (atom? x) (my-if (not (pair? x)) #t #f)) ;; example that won't work ;; peano arithemtic (define (add a b) (my-if (zero? a) b (add (- a 1) (+ b 1)))) </code> The problem with <code>my-if</code> is that as a procedure every argument gets evaluated before the procedure body gets executed. thus in <code>atom?</code> the parts <code>(not (pair? x))</code>, <code>#t</code> and <code>#f</code> were evaluated before the body of <code>my-if</code> gets executed. For the last example means <code>(add (- a 1) (+ b 1))</code> gets evaluated regardless of what a is, even when <code>a</code> is zero, so the procedure will never end. You can make your own if with syntax: <code>(define-syntax my-if (syntax-rules () ((my-if predicate consequent alternative) (cond (predicate consequent) (else alternative))))) </code> Now, how you read this is the first part is a template where the predicate consequent and alternative represent unevaluated expressions. It's replaced with the other just reusing the expressions so that: <code>(my-if (check-something) (display 10) (display 20)) </code> would be replaced with this: <code>(cond ((check-something) (display 10)) (else (display 20))) </code> With the procedure version of <code>my-if</code> both 10 and 20 would have been printed. This is how <code>and</code> and <code>or</code> is implemented as well. Answer: You cannot define <code>cond</code> or <code>and</code> or <code>or</code> or <code>if</code> as functions because functions evaluate all their arguments. (You could define some of them as macros). Read also the famous SICP and Lisp In Small Pieces (original in French). Comment: Thank you! This book is great, except that it doesn't tell so many details about the language.<|endoftext|>How to generate prime numbers? Question: I'm trying to create a formula to find a prime $p$ for some even $n$ and $k\in\mathbb{N}$ $\Large p = 6n + 12k + 5$ For example, choose an even number $n = 99999984$ Applying the formula $k=4$ times <code>p = 599999909 p = 599999921 p = 599999933 p = 599999945 </code> it finds a prime <code>p = 599999957 </code> Question Basically, I'm trying to find a good starting number, then determine any nearby prime within $k$ steps, rather than potentially starting in a prime free void and having to iterate to the next prime which could be millions of steps away? For $\large n<2^{26}$, the formula is guaranteed to find a prime for $k<80$. For $\large n<2^{4096}$, is it possible to compute a $k$ upper bound? Comment: There is a finite number of possibilities to try. An exhaustive search is theoretically possible, but far to large to be practical. Your search avoids numbers that have factors of $2$ or $3$, so the density of primes should be $3$ times higher than picking random numbers. I don't see why the coefficient on $k$ is $12$ instead of $6$. You could have $6n$ be just before a large prime gap. Answer: There's no easy way to guarantee a prime within some small number of steps in any linear recurrence. However, the Prime number Theorem states (approximately) that a random big $n$ is prime with probability $1/log(n)$, so you can approximate bounds. In particular, since you are choosing numbers which are 5 mod 12, and all big primes are 1,5,7,or 11, then your are $12/4=3$ times as likely as a random number to be prime, so each number has probability $3/log(n)$. In general if your jump length is $m$ and you start at a relatively prime number, then $\phi(m)$ of the numbers are prime, so the chance of $p$ being prime is $m/(\phi(m)log(p))$. Let's say you have $n$ numbers each with probability $q$ of being prime. The exact estimate for the longest run seems tricky, but we can apply some heuristics to estimate it. The chance of a given starting point being at least $d$ without a prime is $(1-q)^d$. For this to occur once in the $~n$ starting positions means we want $d$ such that $(1-q)^d=1/n$ or $d=-log(n)/log(1-q)$. Applying this to $q=3/log(n)$ and $n=2^a$ Longest wait is around $-log(2^a)/log(1-3/log(2^a))~a log(2)/(3/(log(2)a))~a^2*(ln(2))^2/3 For $2^{26}$, this gives an estimate of 110. For $2^{4096}$, this gives an estimate of 2.7 million. Note that these are estimates of the worst case. In practice, you expect to find a prime much much faster - within the first 30 thousand 99% of the time. Additionally, if you are selecting a jump length, the key thing is to maximize $m/\phi(m)$. You can do this by letting $m$ be a product of many primes like $m=2*3*5*7*11*13*17*19*23$. That'll give a prime 6 times as likely as a random number (as opposed to 3 times that 12 gets you). In practice, just using 6 gets you most of the way there. Comment: The idea of generating a prime 6 times as likely as a random number sounds great! I'm a maths newbie so what does your final suggested formula look like now? Thanks! Comment: My very approximate heuristic worst case scenario is $(\ln(2^a))^2/(m/\phi(m))$. For $2^{4096}$ and my big m, that'd be around 1.4 million. This might be a large overestimate. Note that this is pretty irrelevant for nearly all purposes since you expect to take ln(2^4096)/6~500 tries on average and have a lower than 1% chance of taking more than 2500 tries where that probability is exponentially decreasing.
[{"idx": "How_to_find_the_hardware_chipset_information?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-652.jsonl"}, {"idx": "\"cond\",\"and\"_and_\"or\"_in_Scheme", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-652.jsonl"}, {"idx": "How_to_generate_prime_numbers?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-652.jsonl"}]
extern crate argparse; extern crate time; extern crate rusqlite; use argparse::{ArgumentParser, Store, Print}; use std::io::prelude::*; use std::io; use std::env; use std::str::FromStr; use std::path::PathBuf; use std::error::Error; use time::Timespec; use rusqlite::Connection; static VERSION: &'static str = "0.5.1"; struct Movie { id: i32, name: String, time_created: Timespec, opinion: String, rating: i32, version: String } enum Command { Show, Add, Remove, Edit, None } impl FromStr for Command { type Err = (); fn from_str(src: &str) -> Result<Command, ()> { return match src { "show" => Ok(Command::Show), "add" => Ok(Command::Add), "remove" => Ok(Command::Remove), "edit" => Ok(Command::Edit), _ => Err(()), }; } } fn main() { // open movies database in .movies.db let mut path_buf = PathBuf::new(); path_buf.push(env::home_dir().expect("Could not find home dir!")); path_buf.push(".movies.db"); let path = path_buf.as_path(); let conn = Connection::open(path).expect("Counld not open database!"); // create a table in movies database that maps to a movie struct conn.execute("CREATE TABLE IF NOT EXISTS movies ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, time_created TEXT NOT NULL, opinion TEXT NOT NULL, rating INTEGER NOT NULL, version TEXT NOT NULL)", &[]).expect("Could not create table!"); let mut command = Command::None; { let mut args = ArgumentParser::new(); args.set_description("Rate your movies"); args.refer(&mut command) .add_argument("command", Store, "Command to run (show, add, remove)").required(); args.add_option(&["-V", "--version"], Print("mymdb version ".to_string() + VERSION), "Show version of mymdb"); args.parse_args_or_exit(); } match command { Command::Show => { // select all movies, convert to iterator let mut stmt = conn.prepare("SELECT * FROM movies").expect("Could not prepare statement!"); let movie_iter = stmt.query_map(&[], |row| { Movie { id: row.get(0), name: row.get(1), time_created: row.get(2), opinion: row.get(3), rating: row.get(4), version: row.get(5) } }).expect("Could not iterate movies!"); // convert list of movies to vector let mut count = 0; let mut movies: Vec<Movie> = vec![]; for movie in movie_iter { movies.push(movie.expect("Could not unwrap movie!")); count = count + 1; } println!("Found {} movie(s)", count); // print movies for z in movies { println!("Name: {}\nOpinion: {}\nRating: {}\nID: {}\nTime: {}\n", z.name, z.opinion, z.rating, z.id, time(z.time_created)); } }, Command::Add => { let new_movie = new_movie(); match conn.execute("INSERT INTO movies (name, time_created, opinion, rating, version) VALUES ($1, $2, $3, $4, $5)", &[&new_movie.name, &new_movie.time_created, &new_movie.opinion, &new_movie.rating, &new_movie.version]) { Ok(_) => (), Err(e) => { let mut badv = false; let mut stmt = conn.prepare("SELECT version FROM movies") .unwrap(); let mut rows = stmt.query(&[]).unwrap(); while let Some(row) = rows.next() { let rs: String = row.unwrap().get(0); if rs != VERSION { badv = true; } } if badv { println!("Your movies database contains movies from a different version of mymdb.\nYou may need to recreate your database."); } panic!("{}", Error::description(&e)); }, } println!("\"{}\" has been added.", new_movie.name); }, Command::Remove => { print!("ID of movie to be removed: "); let id = get_input_i32(); let remove = conn.query_row("SELECT * FROM movies WHERE id=$1", &[&id], |row| { Movie { id: row.get(0), name: row.get(1), time_created: row.get(2), opinion: row.get(3), rating: row.get(4), version: row.get(5) } }); match remove { Ok(m) => { print!("Are you sure you want to remove \"{}\"? (yes/no)", m.name); let res: String = get_input().to_lowercase(); if res != "yes".to_string() { println!("Will not remove."); } else { conn.execute("DELETE FROM movies WHERE id=$", &[&id,]).unwrap(); println!("\"{}\" has been removed from the database.", m.name); } }, Err(_) => println!("Movie does not exist.") } }, Command::Edit => { print!("ID of movie to be edited: "); let old_id = get_input_i32(); let edit = conn.query_row("SELECT * FROM movies WHERE id=$1", &[&old_id,], |row| { Movie { id: row.get(0), name: row.get(1), time_created: row.get(2), opinion: row.get(3), rating: row.get(4), version: row.get(5) } }); match edit { Ok(_) => { let new_movie = new_movie(); match conn.execute("UPDATE movies SET name=$1, time_created=$2, opinion=$3, rating=$4, version=$5 WHERE id=$6", &[&new_movie.name, &new_movie.time_created, &new_movie.opinion, &new_movie.rating, &new_movie.version, &old_id]) { Ok(_) => (), Err(e) => { let mut badv = false; let mut stmt = conn.prepare("SELECT version FROM movies") .unwrap(); let mut rows = stmt.query(&[]).unwrap(); while let Some(row) = rows.next() { let rs: String = row.unwrap().get(0); if rs != VERSION { badv = true; } } if badv { println!("Your movies database contains movies from a different version of mymdb.\nYou may need to recreate your database."); } panic!("{}", Error::description(&e)); }, } println!("\"{}\" has been edited.", new_movie.name); }, Err(_) => println!("Movie does not exist.") } }, Command::None => panic!("Incorrect command - argparse or other??") } } fn new_movie() -> Movie { print!("Name of movie: "); let name: String = get_input().to_string(); print!(" Opinion: "); let opinion: String = get_input().to_string(); print!(" Rating (num): "); let rating: i32 = get_input_i32(); Movie { id: 0, name: name, time_created: time::get_time(), opinion: opinion, rating: rating, version: VERSION.into() } } // get input as string fn get_input() -> String { io::stdout().flush().expect("could not flush stdout"); let mut i = String::new(); let handle = io::stdin(); match handle.read_line(&mut i) { Ok(_) => {}, Err(_) => { println!("Could not read input."); std::process::exit(3); } } return i.trim().to_string(); } fn get_input_i32() -> i32 { match get_input().parse::<i32>() { Ok(n) => n, Err(_) => { println!("Not a number"); std::process::exit(2); } } } fn time(t: Timespec) -> String { let real_time = time::at(t); // might break in 2032 or whenever unix time runs out String::from(format!("{}-{}-{} {}:{}", (real_time.tm_year + 1900), real_time.tm_mon, real_time.tm_mday, real_time.tm_hour, real_time.tm_min)) }<|endoftext|>#[doc = "Register `CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1` reader"] pub struct R(crate::R<CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC>) -> Self { R(reader) } } #[doc = "Register `CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1` writer"] pub struct W(crate::W<CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC>); impl core::ops::Deref for W { type Target = crate::W<CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC>) -> Self { W(writer) } } #[doc = "Field `CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0` reader - core_x_iram0_dram0_dma_sram_category_0"] pub struct CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_R(crate::FieldReader<u8, u8>); impl CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0` writer - core_x_iram0_dram0_dma_sram_category_0"] pub struct CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_W<'a> { w: &'a mut W, } impl<'a> CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x03) | (value as u32 & 0x03); self.w } } #[doc = "Field `CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1` reader - core_x_iram0_dram0_dma_sram_category_1"] pub struct CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_R(crate::FieldReader<u8, u8>); impl CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1` writer - core_x_iram0_dram0_dma_sram_category_1"] pub struct CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_W<'a> { w: &'a mut W, } impl<'a> CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 2)) | ((value as u32 & 0x03) << 2); self.w } } #[doc = "Field `CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2` reader - core_x_iram0_dram0_dma_sram_category_2"] pub struct CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_R(crate::FieldReader<u8, u8>); impl CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2` writer - core_x_iram0_dram0_dma_sram_category_2"] pub struct CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_W<'a> { w: &'a mut W, } impl<'a> CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 4)) | ((value as u32 & 0x03) << 4); self.w } } #[doc = "Field `CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR` reader - core_x_iram0_dram0_dma_sram_splitaddr"] pub struct CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_R(crate::FieldReader<u8, u8>); impl CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR` writer - core_x_iram0_dram0_dma_sram_splitaddr"] pub struct CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_W<'a> { w: &'a mut W, } impl<'a> CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 14)) | ((value as u32 & 0xff) << 14); self.w } } impl R { #[doc = "Bits 0:1 - core_x_iram0_dram0_dma_sram_category_0"] #[inline(always)] pub fn core_x_iram0_dram0_dma_sram_category_0( &self, ) -> CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_R { CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_R::new((self.bits & 0x03) as u8) } #[doc = "Bits 2:3 - core_x_iram0_dram0_dma_sram_category_1"] #[inline(always)] pub fn core_x_iram0_dram0_dma_sram_category_1( &self, ) -> CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_R { CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_R::new(((self.bits >> 2) & 0x03) as u8) } #[doc = "Bits 4:5 - core_x_iram0_dram0_dma_sram_category_2"] #[inline(always)] pub fn core_x_iram0_dram0_dma_sram_category_2( &self, ) -> CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_R { CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bits 14:21 - core_x_iram0_dram0_dma_sram_splitaddr"] #[inline(always)] pub fn core_x_iram0_dram0_dma_sram_splitaddr(&self) -> CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_R { CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_R::new(((self.bits >> 14) & 0xff) as u8) } } impl W { #[doc = "Bits 0:1 - core_x_iram0_dram0_dma_sram_category_0"] #[inline(always)] pub fn core_x_iram0_dram0_dma_sram_category_0( &mut self, ) -> CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_W { CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_W { w: self } } #[doc = "Bits 2:3 - core_x_iram0_dram0_dma_sram_category_1"] #[inline(always)] pub fn core_x_iram0_dram0_dma_sram_category_1( &mut self, ) -> CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_W { CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_W { w: self } } #[doc = "Bits 4:5 - core_x_iram0_dram0_dma_sram_category_2"] #[inline(always)] pub fn core_x_iram0_dram0_dma_sram_category_2( &mut self, ) -> CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_W { CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_W { w: self } } #[doc = "Bits 14:21 - core_x_iram0_dram0_dma_sram_splitaddr"] #[inline(always)] pub fn core_x_iram0_dram0_dma_sram_splitaddr( &mut self, ) -> CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_W { CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_REG\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API]( [IDX] information about available fields see [core_x_iram0_dram0_dma_split_line_constrain_1](index.html) module"] pub struct CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC; impl crate::RegisterSpec for CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [core_x_iram0_dram0_dma_split_line_constrain_1::R](R) reader structure"] impl crate::Readable for CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [core_x_iram0_dram0_dma_split_line_constrain_1::W](W) writer structure"] impl crate::Writable for CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC { type Writer = W; } #[doc = "`reset()` method sets CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1 to value 0"] impl crate::Resettable for CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-13541.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-13541.jsonl"}]
numbers: is factor ------------------ Given: Does 29 divide 3828? Eval: True Given: Is 1188 a multiple of 66? Eval: True Given: Does 17 divide 629? Eval: True Given: Is 44 a factor of 4085884? Eval: True Given: Is 22 a factor of 385517? Eval: False Given: Does 14 divide 3044734? Eval: True Given: Is 83748 a multiple of 2? Eval: True Given: Is 48 a factor of 4527824? Eval: False Given: Is 652 a factor of 6450323? Eval: False Given: Does 18 divide 222318? Eval: True Given: Is 26 a factor of 203746? Eval: False Given: Is 1099111 a multiple of 49? Eval: False Given: Is 11211543 a multiple of 63? Eval: True Given: Is 196 a multiple of 28? Eval: True Given: Is 468 a multiple of 12? Eval: True Given: Is 20 a factor of 68520? Eval: True Given: Is 251416097 a multiple of 2861? Eval: True Given: Is 17 a factor of 255? Eval: True Given: Does 749 divide 103054429? Eval: False Given: Is 1387 a multiple of 9? Eval: False Given: Is 36 a factor of 2412? Eval: True Given: Does 45 divide 45? Eval: True Given: Is 11361526 a multiple of 186? Eval: False Given: Does 596 divide 655600? Eval: True Given: Is 18 a factor of 74502? Eval: True Given: Is 9 a factor of 727? Eval: False Given: Is 338 a factor of 116948? Eval: True Given: Is 1252 a factor of 3210274955? Eval: False Given: Does 13 divide 7610955? Eval: False Given: Is 318 a factor of 5379935? Eval: False Given: Is 48 a factor of 99841200? Eval: True Given: Is 44 a factor of 17241? Eval: False Given: Is 92 a factor of 322? Eval: False Given: Is 23 a factor of 899? Eval: False Given: Is 103 a factor of 177270361? Eval: False Given: Is 45 a factor of 24668536? Eval: False Given: Is 432635830 a multiple of 22? Eval: True Given: Does 21 divide 357? Eval: True Given: Is 124107296 a multiple of 2848? Eval: True Given: Does 39 divide 2184? Eval: True Given: Is 12 a factor of 870496538? Eval: False Given: Is 27 a factor of 1782? Eval: True Given: Is 2821 a multiple of 96? Eval: False Given: Is 167883 a multiple of 104? Eval: False Given: Does 5 divide 350? Eval: True Given: Is 39120 a multiple of 240? Eval: True Given: Does 1765 divide 65414430? Eval: True Given: Does 1908 divide 63762670? Eval: False Given: Is 3 a factor of 612520? Eval: False Given: Is 1004 a factor of 53793413? Eval: False Given: Is 11 a factor of 2975151? Eval: False Given: Does 395 divide 149892625? Eval: True Given: Is 3 a factor of 244? Eval: False Given: Is 3 a factor of 1377407? Eval: False Given: Does 9 divide 8496? Eval: True Given: Is 2377 a factor of 308265999? Eval: True Given: Is 223 a factor of 54254562? Eval: True Given: Is 251330762 a multiple of 797? Eval: True Given: Is 152 a multiple of 15? Eval: False Given: Is 27174377 a multiple of 164? Eval: False Given: Does 11 divide 31119? Eval: True Given: Is 245 a multiple of 5? Eval: True Given: Is 29 a factor of 9131804? Eval: False Given: Does 52 divide 5876? Eval: True Given: Is 391 a factor of 171695138? Eval: True Given: Is 120741345 a multiple of 62? Eval: False Given: Does 22 divide 1682? Eval: False Given: Does 467 divide 164284? Eval: False Given: Is 212 a multiple of 4? Eval: True Given: Is 56 a factor of 2411173? Eval: False Given: Is 634 a multiple of 105? Eval: False Given: Is 102 a factor of 30155994? Eval: True Given: Is 192 a factor of 3781632? Eval: True Given: Is 31 a factor of 742554479? Eval: False Given: Is 2681820 a multiple of 940? Eval: True Given: Does 64 divide 60161372? Eval: False Given: Is 29 a factor of 3477? Eval: False Given: Is 628888315 a multiple of 11? Eval: True Given: Is 468 a multiple of 22? Eval: False Given: Is 1516895856 a multiple of 1368? Eval: True Given: Does 9 divide 3040? Eval: False Given: Is 2604 a multiple of 28? Eval: True Given: Is 7390 a multiple of 10? Eval: True Given: Does 10 divide 490? Eval: True Given: Does 656 divide 2172237? Eval: False Given: Is 129 a factor of 807227? Eval: False Given: Does 6 divide 4526375? Eval: False Given: Does 90 divide 2880? Eval: True Given: Does 56 divide 19879? Eval: False Given: Is 20479384 a multiple of 23? Eval: True Given: Does 91 divide 1410318? Eval: True Given: Is 289 a multiple of 61? Eval: False Given: Does 4 divide 184? Eval: True Given: Is 3 a factor of 31908703? Eval: False Given: Does 222 divide 348779? Eval: False Given: Does 7 divide 3778143? Eval: False Given: Is 11 a factor of 178980571? Eval: True Given: Is 48352 a multiple of 4? Eval: True Given: Does 64 divide 121317312? Eval: True Given: Is 238262 a multiple of 503? Eval: False Given: Is 259180 a multiple of 164? Eval: False Given: Is 195 a factor of 6429467? Eval: False Given: Is 10 a factor of 5290? Eval: True Given: Does 13 divide 3228? Eval: False Given: Is 46 a factor of 4850544? Eval: False Given: Is 300 a factor of 109800? Eval: True Given: Is 8 a factor of 22380064? Eval: True Given: Does 2 divide 11? Eval: False Given: Does 6 divide 41418174? Eval: True Given: Is 373296 a multiple of 44? Eval: True Given: Is 339 a factor of 621640233? Eval: True Given: Is 522552089 a multiple of 68? Eval: False Given: Is 1476 a factor of 493691004? Eval: True Given: Is 200 a factor of 1658257? Eval: False Given: Does 10 divide 167610137? Eval: False Given: Does 12 divide 6040? Eval: False Given: Does 11 divide 151503? Eval: True Given: Does 47 divide 16008? Eval: False Given: Does 25 divide 32234698? Eval: False Given: Is 803 a factor of 719488? Eval: True Given: Is 6522 a multiple of 109? Eval: False Given: Does 82 divide 216242610? Eval: True Given: Does 11 divide 4578650? Eval: False Given: Does 1825 divide 2255820450? Eval: True Given: Is 372 a factor of 3605052? Eval: True Given: Is 95 a factor of 110580? Eval: True Given: Does 11 divide 132? Eval: True Given: Does 171 divide 1197? Eval: True Given: Is 608 a multiple of 19? Eval: True Given: Does 13 divide 197? Eval: False Given: Is 346 a multiple of 50? Eval: False Given: Is 324 a multiple of 54? Eval: True Given: Is 7 a factor of 658? Eval: True Given: Is 2430361 a multiple of 1410? Eval: False Given: Is 1110 a factor of 170891815? Eval: False Given: Is 179761 a multiple of 51? Eval: False Given: Is 23 a factor of 2604? Eval: False Given: Is 3 a factor of 1890652761? Eval: True Given: Is 1662 a multiple of 16? Eval: False Given: Does 12 divide 136931746? Eval: False Given: Is 43072 a multiple of 47? Eval: False Given: Is 25 a factor of 1891100? Eval: True Given: Does 4 divide 491? Eval: False Given: Is 312818952 a multiple of 69? Eval: True Given: Does 220 divide 90276? Eval: False Given: Does 13 divide 1282646? Eval: False Given: Is 87 a factor of 73324? Eval: False Given: Is 5 a factor of 2648? Eval: False Given: Is 7492683 a multiple of 60? Eval: False Given: Does 541 divide 11092664? Eval: True Given: Is 17 a factor of 13093? Eval: False Given: Is 20862 a multiple of 22? Eval: False Given: Is 1405 a multiple of 12? Eval: False Given: Is 6 a factor of 454? Eval: False Given: Is 62 a factor of 5625715? Eval: False Given: Is 257753341 a multiple of 13? Eval: False Given: Is 215 a factor of 1052855? Eval: True Given: Is 51 a factor of 34078? Eval: False Given: Is 27 a factor of 54? Eval: True Given: Does 969 divide 3440100760? Eval: False Given: Is 12 a factor of 82373532? Eval: True Given: Does 9 divide 550958? Eval: False Given: Does 267 divide 674175? Eval: True Given: Is 30 a factor of 258? Eval: False Given: Is 67 a factor of 181972? Eval: True Given: Is 59 a factor of 826? Eval: True Given: Does 181 divide 449423? Eval: True Given: Is 6 a factor of 100392? Eval: True Given: Is 55 a factor of 28394245? Eval: True Given: Does 30 divide 314463591? Eval: False Given: Is 117982899 a multiple of 255? Eval: False Given: Does 2 divide 638150? Eval: True Given: Is 2177833770 a multiple of 570? Eval: True Given: Does 1537 divide 4114549? Eval: True<|endoftext|>numbers: is factor ------------------ Puzzle: Does 36 divide 1152? Sol: True Puzzle: Does 22 divide 69762? Sol: True Puzzle: Is 5454185869 a multiple of 955? Sol: False Puzzle: Does 25 divide 852614925? Sol: True Puzzle: Does 196 divide 4552884? Sol: True Puzzle: Is 65 a factor of 5850? Sol: True Puzzle: Does 7 divide 75964252? Sol: True Puzzle: Is 245 a factor of 438001001? Sol: False Puzzle: Is 5265 a multiple of 81? Sol: True Puzzle: Is 35986158 a multiple of 754? Sol: True Puzzle: Does 31 divide 648177? Sol: False Puzzle: Is 351 a factor of 160636? Sol: False Puzzle: Is 920763945 a multiple of 8901? Sol: True Puzzle: Is 11 a factor of 397815? Sol: True Puzzle: Is 38 a factor of 172936? Sol: False Puzzle: Does 1249 divide 474268266? Sol: False Puzzle: Does 5 divide 96932985? Sol: True Puzzle: Does 38 divide 1776? Sol: False Puzzle: Is 194488 a multiple of 322? Sol: True Puzzle: Is 69 a factor of 11083? Sol: False Puzzle: Is 46 a factor of 548? Sol: False Puzzle: Does 20 divide 1188462? Sol: False Puzzle: Does 25 divide 325? Sol: True Puzzle: Does 9 divide 22614? Sol: False Puzzle: Is 17 a factor of 236? Sol: False Puzzle: Is 632 a factor of 202617052? Sol: False Puzzle: Is 3 a factor of 1810584? Sol: True Puzzle: Does 24 divide 6237569? Sol: False Puzzle: Is 292 a factor of 154680527? Sol: False Puzzle: Does 1228 divide 1035085250? Sol: False Puzzle: Does 116 divide 116? Sol: True Puzzle: Is 23 a factor of 1840? Sol: True Puzzle: Does 614 divide 58177728? Sol: True Puzzle: Is 91042 a multiple of 98? Sol: True Puzzle: Is 3594 a multiple of 12? Sol: False Puzzle: Is 408 a multiple of 19? Sol: False Puzzle: Does 16 divide 1752261? Sol: False Puzzle: Is 437432 a multiple of 103? Sol: False Puzzle: Is 40 a factor of 186? Sol: False Puzzle: Is 126 a factor of 959417? Sol: False Puzzle: Is 129 a factor of 335568541? Sol: False Puzzle: Does 35 divide 456? Sol: False Puzzle: Is 22456 a multiple of 28? Sol: True Puzzle: Is 23 a factor of 617044? Sol: True Puzzle: Is 56 a factor of 336? Sol: True Puzzle: Is 4 a factor of 24644633? Sol: False Puzzle: Does 134 divide 45600468? Sol: True Puzzle: Is 442 a factor of 805766? Sol: True Puzzle: Does 19 divide 3484260? Sol: False Puzzle: Is 4244436 a multiple of 22? Sol: False Puzzle: Is 559 a factor of 2388048? Sol: True Puzzle: Does 41 divide 3186? Sol: False Puzzle: Is 1920 a multiple of 20? Sol: True Puzzle: Is 2775 a factor of 1794525900? Sol: True Puzzle: Does 200 divide 12152? Sol: False Puzzle: Does 162 divide 1244484? Sol: True Puzzle: Does 60 divide 540? Sol: True Puzzle: Is 1082 a multiple of 6? Sol: False Puzzle: Does 46 divide 856749770? Sol: True Puzzle: Is 10 a factor of 1457280? Sol: True Puzzle: Does 8 divide 6904? Sol: True Puzzle: Does 386 divide 7060594? Sol: False Puzzle: Is 491204506 a multiple of 24? Sol: False Puzzle: Does 124 divide 351620? Sol: False Puzzle: Is 4961 a multiple of 6? Sol: False Puzzle: Does 3 divide 16215? Sol: True Puzzle: Does 2 divide 5791? Sol: False Puzzle: Is 328 a factor of 11792256? Sol: True Puzzle: Does 61 divide 4762087? Sol: True Puzzle: Does 70 divide 463470? Sol: True Puzzle: Is 123 a factor of 5658? Sol: True Puzzle: Is 207 a factor of 311146? Sol: False Puzzle: Is 964 a factor of 314338690? Sol: False Puzzle: Is 3 a factor of 3902? Sol: False Puzzle: Does 42 divide 130316340? Sol: True Puzzle: Is 422227975 a multiple of 3385? Sol: True Puzzle: Is 1824 a multiple of 24? Sol: True Puzzle: Is 1383 a factor of 19155933? Sol: True Puzzle: Is 195 a factor of 40702901? Sol: False Puzzle: Is 52 a factor of 121051? Sol: False Puzzle: Is 350368089 a multiple of 9? Sol: False Puzzle: Is 377 a factor of 137982? Sol: True Puzzle: Is 18 a factor of 15467726? Sol: False Puzzle: Is 444 a factor of 1039848? Sol: True Puzzle: Is 6 a factor of 47071? Sol: False Puzzle: Is 3253835 a multiple of 443? Sol: True Puzzle: Does 41 divide 9881? Sol: True Puzzle: Is 3297202 even? Sol: True Puzzle: Is 17 a factor of 166? Sol: False Puzzle: Is 1354052592 a multiple of 72? Sol: True Puzzle: Does 44 divide 14484? Sol: False Puzzle: Does 112 divide 3337? Sol: False Puzzle: Is 26105 a multiple of 12? Sol: False Puzzle: Is 40252 a multiple of 52? Sol: False Puzzle: Is 155866 a multiple of 32? Sol: False Puzzle: Is 15510 a multiple of 100? Sol: False Puzzle: Is 21 a factor of 999201? Sol: True Puzzle: Is 628 even? Sol: True Puzzle: Is 17645260 a multiple of 2? Sol: True Puzzle: Does 353 divide 17004010? Sol: True Puzzle: Is 286 a multiple of 3? Sol: False Puzzle: Does 4 divide 40? Sol: True Puzzle: Is 801 a factor of 156195? Sol: True Puzzle: Is 50272 a multiple of 35? Sol: False Puzzle: Is 74493 a multiple of 16? Sol: False Puzzle: Is 4 a factor of 2620? Sol: True Puzzle: Does 71 divide 281? Sol: False Puzzle: Is 1676 even? Sol: True Puzzle: Is 4 a factor of 108618? Sol: False Puzzle: Does 9 divide 99? Sol: True Puzzle: Is 294 a factor of 3859666? Sol: False Puzzle: Is 125443971 a multiple of 1593? Sol: True Puzzle: Is 818 a factor of 229394855? Sol: False Puzzle: Is 229 a multiple of 21? Sol: False Puzzle: Is 10 a factor of 171368381? Sol: False Puzzle: Is 3359 a multiple of 17? Sol: False Puzzle: Does 3576 divide 4402864176? Sol: True Puzzle: Is 189 a factor of 7571097? Sol: False Puzzle: Is 108232 a multiple of 16? Sol: False Puzzle: Does 47 divide 660818590? Sol: True Puzzle: Is 44 a factor of 111556? Sol: False Puzzle: Is 1025459 a multiple of 20? Sol: False Puzzle: Is 2100302 a multiple of 475? Sol: False Puzzle: Does 14 divide 280? Sol: True Puzzle: Is 4 a factor of 3355993? Sol: False Puzzle: Is 4 a factor of 364976? Sol: True Puzzle: Is 16593330 a multiple of 5? Sol: True Puzzle: Is 352 a factor of 442768508? Sol: False Puzzle: Is 126866 a multiple of 22? Sol: False Puzzle: Does 19 divide 777778357? Sol: True Puzzle: Is 158 a factor of 2458638? Sol: True Puzzle: Is 1913814 a multiple of 21? Sol: True Puzzle: Is 3168 a multiple of 198? Sol: True Puzzle: Is 1309749 a multiple of 269? Sol: False Puzzle: Is 979 a multiple of 11? Sol: True Puzzle: Is 5 a factor of 3451? Sol: False Puzzle: Is 3586253 a multiple of 841? Sol: False Puzzle: Does 20 divide 665? Sol: False Puzzle: Is 12170 a multiple of 72? Sol: False Puzzle: Is 140827549 a multiple of 746? Sol: False Puzzle: Is 236915 a multiple of 245? Sol: True Puzzle: Is 12957 a multiple of 2? Sol: False Puzzle: Is 62 a factor of 18662? Sol: True Puzzle: Is 19579204 even? Sol: True Puzzle: Is 162 a factor of 617016? Sol: False Puzzle: Does 270 divide 896907600? Sol: True Puzzle: Does 13 divide 1166635964? Sol: True Puzzle: Is 36 a multiple of 15? Sol: False Puzzle: Does 21 divide 2331? Sol: True Puzzle: Does 551 divide 71058062? Sol: True Puzzle: Is 39 a factor of 8229? Sol: True Puzzle: Does 154 divide 14014? Sol: True Puzzle: Does 8 divide 46032? Sol: True Puzzle: Is 3068709 a multiple of 19? Sol: True Puzzle: Does 31 divide 333? Sol: False Puzzle: Does 11 divide 973? Sol: False Puzzle: Does 52 divide 72228? Sol: True Puzzle: Does 9 divide 589752? Sol: True Puzzle: Does 245 divide 2479155? Sol: True Puzzle: Is 18 a factor of 202105260? Sol: True Puzzle: Is 9 a factor of 599101254? Sol: True Puzzle: Is 157 a factor of 592151248? Sol: True Puzzle: Is 3 a factor of 85280? Sol: False Puzzle: Does 50 divide 350? Sol: True Puzzle: Is 4001 a multiple of 38? Sol: False Puzzle: Does 286 divide 1021594? Sol: False Puzzle: Is 85 a factor of 1160669? Sol: False Puzzle: Is 805 a multiple of 40? Sol: False Puzzle: Is 379 a factor of 92164841? Sol: True Puzzle: Does 39 divide 102419? Sol: False Puzzle: Is 1065873 a multiple of 3? Sol: True Puzzle: Does 11 divide 120110977? Sol: False Puzzle: Is 3203 a multiple of 16? Sol: False Puzzle: Is 126 a factor of 1327523778? Sol: True Puzzle: Does 10 divide 38179? Sol: False
[{"idx": "txt360/numbers__is_factor_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-9.jsonl"}, {"idx": "txt360/numbers__is_factor_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-9.jsonl"}]
get multiselect select tag value as an array in rails 3 Question: i used multiselect select tag. In create method i used, <code>category= @admin.category.reject! { |c| c.empty? }.to_s </code> to save my select tag (selected)value as array into database. But in update method the same thing is not get achieve. original format what i am getting is, <code>--- - '' - Adventure Tours - Cruises - Exploration </code> I want to change it as an array like <code>["Adventure Tours","Cruises","Exploration"] </code> Answer: You can use 'serialize' method provided by ActiveRecord to store values as array into the database. The type of the column in which you are store these array of values should be text Ex : (Say if you want to save codes of categories in categories table) <code># In the migration file add_column :categories, :codes, :text # In the model class Category < ActiveRecord::Base serialize :codes end </code> It will get saved in the database as <code>--- - abc - xyz - pqr </code> and after fetching it from the database, like <code>Category.find(some_id).codes </code> You will get an array of codes for that given category record. <code>["abc", "xyz", "pqr"] </code> You can refer this documentation [IDX] (Search for heading : Saving arrays, hashes, and other non-mappable objects in text columns)<|endoftext|>Svn Externals, can you have files from externals that are mixed in with your regular working copy Question: I want to be able to have a working copy of a framework, then I want to have another repo for certain extensions where I pull those extensions into my framework with externals. The problem I see, since I haven't used externals before, is that it appears you have to just pull in full directories that can be separated out from the rest of the project for example <code>root dir dir extensions plugin - external pulled in here </code> But what if you need something where the external directory structure includes some of the normal framework structure, for example: <code>root app - This is in working copy and external code - This is in working copy and external dir - This is only in working copy dir - This is only in external etc - this is in working copy and external file - this is only in working copy file - this is from external </code> I hope this makes sense, but basically I want to have my working copy and then pull in files from another repo that have files and folders in the same directories as my working copy already has files and folders. Answer: The <code>svn:externals</code> property can also point to files, not just folders. See the docs about that.<|endoftext|>How do you watch a variable in xcode 4? Question: How do you watch a variable in xcode 4? I'm not sure how to do this. Comment: possible duplicate of [Where is the expression window in Xcode 4?]( [IDX] Just enter the variable name as expression. Comment: thanks my question is a dupe. Comment: same question here [IDX] Right click in the local variables window to see the "Watch Expression" menu command. Type the variable name and the variable will be added. Comment: Where is this "watch expression" menu? Answer: "Watch VariableName" is available in debug area. Just right click on a var and select "Watch var". Answer: There is 2 ways to watch a variable and break at certain condition. Edit breakpoints Control-click a breakpoint indicator to display a command menu and choose Edit Breakpoint to open the breakpoint editor and set conditions, add actions, and so forth, as mentioned in Breakpoints. Use LLDB command line. For example, below command will watch the value of 'I', and break when I==3. (lldb) watch set var i Watchpoint created: Watchpoint 1: addr = 0x100001018 size = 4 state = enabled type = w declare @ '/Volumes/data/lldb/svn/ToT/test/functionalities/watchpoint/watchpoint_commands/condition/main.cpp:12' (lldb) watch modify -c 'i==3' (lldb) watch list This is where you can type LLDB command in Xcode.<|endoftext|>Only every-other horizontal grid line is printing in Excel Question: Even though the grid lines (which I have set to print) show up correctly in the print preview screen, the print comes out with EVERY-OTHER horizontal line printed. This is in the regular workbook, row height 16, Excel 2016, Windows 10. Comment: Try printing to `PDF` first. If the issue persists, the issue is with Excel - otherwise could be something else too Comment: From the description, people will only be able to guess at possibilities. Are all settings at the default values? Are you printing "full size" (vs. adjusting page breaks to fit more on a page)? Can you scan a sample page (or snap a picture of one), stick that on an image sharing site like imgur.com, and add a link to it? Comment: Grid lines are printed as single-pixel grey lines. These may not print correctly on some printers. What happens if you change row height? What happens if you give the cells black borders, do they print correctly? Comment: Sounds like an issue with your printer. Try to convert your sheet to pdf first and print that as @Prasanna has already adviced. Answer: It will print every other line if your print quality is in draft mode. In Excel, go to File -> Page-up -> Print quality -> Select "normal or best". I'm assuming you already checked off print gridlines.<|endoftext|>Postgresql jsonb select object with dif order Question: I have one column in my table with this jsonb <code>{"parcelas": "[{"valor": "2136,45", "parcela": 75, "vencimento": "15/06/2019"}, {"valor": "2097,61", "parcela": 76, "vencimento": "15/07/2019"}, {"valor": "2058,33", "parcela": 77, "vencimento": "15/08/2019"}, {"valor": "2191,07", "parcela": 78, "vencimento": "15/09/2019"}]}" </code> It`s possible to find that row when I compare a equal object but without space or another order? sample <code>SELECT * FROM myTable where myJsonBField ->> 'parcelas' = '[{"vencimento":"15/06/2019","valor":"2136,45","parcela":75},{"vencimento":"15/07/2019","valor":"2097,61","parcela":76},{"vencimento":"15/08/2019","valor":"2058,33","parcela":77},{"vencimento":"15/09/2019","valor":"2191,07","parcela":78}]' </code> is the "same" object but in another order and with less space between itens. tks Answer: Just use <code>-></code> which gives a <code>jsonb</code> rather than a <code>text</code> and <code>=</code>. <code>SELECT * FROM mytable WHERE myjsonbfield->'parcelas' = '[{"vencimento":"15/06/2019","valor":"2136,45","parcela":75},{"vencimento":"15/07/2019","valor":"2097,61","parcela":76},{"vencimento":"15/08/2019","valor":"2058,33","parcela":77},{"vencimento":"15/09/2019","valor":"2191,07","parcela":78}]'::jsonb; </code><|endoftext|>Use different Css files in different part of sing html file Question: I have some problem with css files, to be more detailed i have linked 2 css stiles in one html file one is style.scc and bootstrap.css I am using bootstrap social button and that's why i need bootstrap. but this movement has changed almost everything in my site... so is there a way to call bootstrap.css file in single div and in aver divs to have original css file? PS css Scoped property don't works from me! Comment: Why not copying the styles from the bootstrap file into your style.css? Comment: becous i don't want to mes with enormous lines of code of bootsrap Comment: Then there's the option to make a custom file: [IDX] No, it is not possible, if you only using bootstrap for social button - just copy styles from bootstrap.css to your stylesheet (style.css). Scoped CSS works only in Firefox for now. Answer: Bootstrap already has a feature in their site to help you doing custom builds, check it using the following link: <code>Customize</code>. Also, you can always get the source code and working with it by yourself. For more information, check the following link: <code>Compiling CSS and JavaScript</code>. Answer: Never mynde i founde the solution from "here" you mast set the mos important css file the last and the least important first :-)<|endoftext|>Test E2E Cypress Laravel Jetstream fail click Question: I wrote the following test in cypress that registers but gives me problems in click management account: <code>import faker from 'faker' describe('Registration', () => { const email = faker.internet.email() const password = faker.internet.password() it('successfully registering', () => { cy.visit(' [IDX] cy.get('input[name=name]').type(faker.name.findName()) cy.get('input[name=email]').type(email) cy.get('input[name=password]').type(password) cy.get('input[name=password_confirmation]').type(password) cy.get('button').contains('Register').click() cy.url().should('contain', '/dashboard') //I would like to click on the Management Account, but I can't cy.get('button.flex.text-sm.border-2.border-transparent.rounded-full.focus:outline-none.focus:border-gray-300.transition.duration-150.ease-in-out').click() // cy.contains('Logout').click() }) }) </code> give me following error: button.flex.text-sm.border-2.border-transparent.rounded-full.focus:outline-none.focus:border-gray-300.transition.duration-150.ease-in-out Error Syntax error, unrecognized expression: unsupported pseudo: outline-none basically I would like him to click this: Answer: <code> cy.get('button.flex.text-sm.border-2.border-transparent.rounded-full').click() </code><|endoftext|>Apache HttpClient proper handling of cookies? Question: I'm writing an application that can communicate with a website and do things such as login, post stuff, etc. Long story short, the application is working fine. Although, I'd like to make it more efficient rather than doing a low-level cookie integration. I'm currently using <code>post.setHeader("Cookie", "abc"); </code> I'm well aware of the <code>CookieStore</code> method, I've been searching all over Google/Stackoverflow for help. So the issue I'm having is, my cookies are predefined in my code, that's a problem because some of the generic keys in my cookie can expire. The cookies have <code>cached</code> or <code>generic</code> generated keys, that are given out individually. I need to be able to go to the website, and store whatever cookie is given to me first. THEN begin executing my code to login. As of right now, the cookies are null. How would I approach this? I want to be efficient, I was thinking of running a "dummy" execution on the website, and then copy over the given cookies to the low-level cookie storage. (I feel there is a better way, that's why I'm hoping to get some input here) Answer: Figured it out, I used the BasicCookieManager only, and I had it query all the Cookies using List to view whether or not the cookies are active. Works flawlessly.
[{"idx": "get_multiselect_select_tag_value_as_an_array_in_rails_3", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8929.jsonl"}, {"idx": "Svn_Externals,_can_you_have_files_from_externals_that_are_mixed_in_with_your_regular_working_copy", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8929.jsonl"}, {"idx": "How_do_you_watch_a_variable_in_xcode_4?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8929.jsonl"}, {"idx": "Only_every-other_horizontal_grid_line_is_printing_in_Excel", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8929.jsonl"}, {"idx": "Postgresql_jsonb_select_object_with_dif_order", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8929.jsonl"}, {"idx": "Use_different_Css_files_in_different_part_of_sing_html_file", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8929.jsonl"}, {"idx": "Test_E2E_Cypress_Laravel_Jetstream_fail_click", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8929.jsonl"}, {"idx": "Apache_HttpClient_proper_handling_of_cookies?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-8929.jsonl"}]
# + pycharm={"is_executing": false} import datetime import json import numpy as np import tensorflow as tf import keras # + pycharm={"name": "#%%\n", "is_executing": false} dataset_path = "data/archive/Data/genres_original" json_path = "data/gtzan_mfcc_json.json" # + [markdown] pycharm={"name": "#%% md\n"} # ## 1. Neural Network # + pycharm={"name": "#%%\n", "is_executing": false} with open(json_path, "r") as fp: data = json.load(fp) X = np.array(data["mfcc"]) y = np.array(data["labels"]) print(X.shape) print(y.shape) # + pycharm={"name": "#%%\n", "is_executing": false} validation_data = (X_test, y_test) # + pycharm={"name": "#%%\n", "is_executing": false} print("Training set: ") print(X_train.shape) print(y_train.shape) print("Testing set: ") print(X_test.shape) print(y_test.shape) # + [markdown] pycharm={"name": "#%% md\n"} # ### 1.1 Model Trainer Function # # We create a function which takes in model and it's short name as # parameters (and an option learning rate). # The function compiles, trains and then plots the model, # saving the training history in JSON file (for later use) and the plots. # # * We use _Sparse Categorical Crossentropy_ as the loss parameter since # we have more than 2 label classes (10 in our case), and our labels are # integers. # # * Cross entropy loss is basically a type of log-scale loss, and hence # it penalizes the predicted values which diverges too much from actual label. # + pycharm={"name": "#%%\n", "is_executing": false} def compile_train_plot(model, validation_data, name, lr=0.0001): optimiser = keras.optimizers.Adam(learning_rate=lr) model.compile(optimizer=optimiser, loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.summary() # Train the model print("Start time:", datetime.datetime.now().time()) print("Training in progress...") history = model.fit(X_train, y_train, validation_data=validation_data, batch_size=32, epochs=50, verbose=0) print("Training finished") print("End time: ", datetime.datetime.now().time()) print("\nTraining accuracy: ", history.history["accuracy"][-1]) print("Validation accuracy: ", history.history["val_accuracy"][-1]) print("Training error (loss): ", history.history["loss"][-1]) print("Validation error (loss): ", history.history["val_loss"][-1]) # Save training history in JSON file with open("img/train_test_plot_"+name+".json", 'w') as file: json.dump(history.history, file) # Accuracy sublpot axs[0].plot(history.history["accuracy"], label="train accuracy") axs[0].plot(history.history["val_accuracy"], label="test accuracy") axs[0].set_ylabel("Accuracy") axs[0].legend(loc="lower right") axs[0].set_title("Accuracy eval") # Error sublpot axs[1].plot(history.history["loss"], label="train error") axs[1].plot(history.history["val_loss"], label="test error") axs[1].set_ylabel("Error loss") axs[1].set_xlabel("Epoch") axs[1].legend(loc="upper right") axs[1].set_title("Error eval") plt.tight_layout() plt.savefig("img/train_test_plot_"+name+".png", format="png", dpi=200) plt.show() # + [markdown] pycharm={"name": "#%% md\n"} # ### 1.2 Basic Model # # Model with 2 hidden layer without any dropout/regualarisation # + pycharm={"name": "#%%\n", "is_executing": false} model = keras.Sequential() compile_train_plot(model, validation_data, "basic") # + [markdown] pycharm={"name": "#%% md\n"} # Some remarks: # # * The testing accuracy as well as error both improved in their own respective # ways, but there is a huge difference between the training and testing curves. # # * The test error did decrease, and then actually began to increase. # # The above points indicate that the current model is severely overfitting, # and hence we need to change some parameters of the model, or use a completely # different model. # + [markdown] pycharm={"name": "#%% md\n"} # ## 2. Improved Neural Network # Now incorporating dropouts and regularization # # ### 2.1 Dropout # # Model with 2 hidden layers with 10% droput rate # + pycharm={"name": "#%%\n", "is_executing": false} model = keras.Sequential() compile_train_plot(model, validation_data, name="drop") # - # ### 2.2 Dropout + Regularization # # Model with 2 hidden layers with 10% dropout rate and L2 regularization # in each of the hidden layers. # + pycharm={"name": "#%%\n", "is_executing": false} model = keras.Sequential() compile_train_plot(model, validation_data, name="drop_regu") # - # ### 2.3 Dropout + Regulrization + More layers # # More hidden layers added # + pycharm={"name": "#%%\n", "is_executing": false} model = keras.Sequential() model.add(keras.layers.Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001))) model.add(keras.layers.Dense(128, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001))) model.add(keras.layers.Dense(64, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001))) compile_train_plot(model, validation_data, name="drop_regu_3layers") # + [markdown] pycharm={"name": "#%% md\n", "is_executing": false} # # 3. Convolutional Neural Network (CNN) # # ## 3.1 Splitting dataset # + pycharm={"name": "#%%\n", "is_executing": false} # + [markdown] pycharm={"name": "#%% md\n"} # * A CNN requires 3 dimensions since it is traditionally used for coloured # input images. For our audio based data, our data is (samples, 130, 13). # This means each sample point has dimnesions of (130, 13), which is 2D. # * We can add another dimension just to have consistencies with the # requirement for dimensionsn in the CNN architecture. # We make use of `np.newaxis` to add 1 more dimension # * Final dimension: (#samples, 130, 13, 1) # + pycharm={"name": "#%%\n", "is_executing": false} # Add an axis to input sets # (130, 13, 1) print("Training shape: ", X_train.shape) print("Validation shape: ", X_validation.shape) print("Testing shape: ", X_test.shape) print("\nTotal size: ", X_train.shape[0]+X_validation.shape[0]+X_test.shape[0]) # + [markdown] pycharm={"name": "#%% md\n"} # ## 3.2 CNN Model # + pycharm={"name": "#%%\n", "is_executing": false} model = keras.Sequential() model.add(keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape)) model.add(keras.layers.Conv2D(32, (3, 3), activation='relu')) model.add(keras.layers.Conv2D(32, (2, 2), activation='relu')) model.add(keras.layers.MaxPooling2D((2, 2), strides=(2, 2), padding='same')) # + pycharm={"name": "#%%\n", "is_executing": false} compile_train_plot(model, validation_data, "CNN-Model") # + [markdown] pycharm={"name": "#%% md\n"} # + pycharm={"name": "#%%\n", "is_executing": false} # + [markdown] pycharm={"name": "#%% md\n"} # # 5. RNN - LSTM # # * LSTM needs 2D data only, so we simply go ahead with # splitting the data and without adding any extra dimensions. # + pycharm={"name": "#%%\n", "is_executing": false} print("Training shape: ", X_train.shape) print("Validation shape: ", X_validation.shape) print("Testing shape: ", X_test.shape) print("\nTotal size: ", X_train.shape[0]+X_validation.shape[0]+X_test.shape[0]) # + pycharm={"name": "#%%\n", "is_executing": false} model = keras.Sequential() model.add(keras.layers.LSTM(64, input_shape=input_shape, return_sequences=True)) model.add(keras.layers.LSTM(64)) # + pycharm={"name": "#%%\n", "is_executing": false} compile_train_plot(model, validation_data, "LSTM") # + pycharm={"name": "#%%\n", "is_executing": false} model.save("data/RNN-Model") # - # + pycharm={"name": "#%%\n", "is_executing": false} # + [markdown] pycharm={"name": "#%% md\n"} # # - # # 4. Summary # # | S. No. | Model | Training Accuracy | Validation Accuracy | Training Error | Validation Error | Trends by Epoch | # |:------:|:------------------------------------------:|:-----------------:|:-------------------:|:--------------:|:----------------:|:---------------:| # | 1 | Basic | 0.96 | 0.60 | 0.14 | 4.27 |<img src="./img/train_test_plot_basic.png" width = "200">| # | 2 | Dropout | 0.91 | 0.60 | 0.26 | 2.20 |<img src="./img/train_test_plot_drop.png" width = "200">| # | 3 | Dropout + Regularization | 0.91 | 0.60 | 1.12 | 3.02 |<img src="./img/train_test_plot_drop_regu.png" width = "200">| # | 4 | Dropout + Regularization<br> + More Layers | 0.83 | 0.62 | 1.31 | 2.32 |<img src="./img/train_test_plot_drop_regu_3layers.png" width = "200">| # | 5 | CNN | 0.84 | 0.73 | 0.47 | 0.79 |<img src="./img/train_test_plot_CNN-Model.png" width = "200">| # | 6 | LSTM | 0.78 | 0.74 | 0.64 | 1.07 |<img src="./img/train_test_plot_LSTM.png" width = "200">| # + pycharm={"name": "#%%\n"}<|endoftext|># </i></small></small> # # self in Python, Demystified # # If you have been programming in Python (object-oriented programming) for some time, then you have definitely come across methods that have **`self`** as their first parameter. # # Let us first try to understand what this recurring **`self`** parameter is. # ## What is self in Python? # # In object-oriented programming, whenever we define methods for a class, we use **`self`** as the first parameter in each case. Let's look at the definition of a class called **`Cat`**. class Cat: self.name = name self.age = age def info(self): print(f"I am a cat. My name is {self.name}. I am {self.age} years old.") def make_sound(self): print("Meow") # **Explanation:** # # In this case all the methods, including **`__init__`**, have the first parameter as **`self`**. # # We know that class is a blueprint for the objects. This blueprint can be used to create multiple numbers of objects. Let's create two different objects from the above class. # # ```python # cat1 = Cat('Amelia', 3) # cat2 = Cat('Bella', 6) # ``` # The **`self`** keyword is used to represent an instance (object) of the given class. In this case, the two **`Cat`** objects **`cat1`** and **`cat2`** have their own **`name`** and **`age`** attributes. If there was no **`self`** argument, the same class couldn't hold the information for both these objects. # # However, since the class is just a blueprint, **`self`** allows access to the attributes and methods of each object in python. This allows each object to have its own attributes and methods. Thus, even long before creating these objects, we reference the objects as **`self`** while defining the class. # ## Why is self explicitly defined everytime? # # Even when we understand the use of **`self`**, it may still seem odd, especially to programmers coming from other languages, that **`self`** is passed as a parameter explicitly every single time we define a method. As **The Zen of Python** goes, **"Explicit is better than implicit"**. # # So, why do we need to do this? Let's take a simple example to begin with. We have a **`Point`** class which defines a method **`distance`** to calculate the distance from the origin. class Point(object): def __init__(self,x = 0,y = 0): self.x = x self.y = y def distance(self): """Find distance from origin""" return (self.x**2 + self.y**2) ** 0.5 # Let us now instantiate this class and find the distance. p1 = Point(6,9) p1.distance() # In the above example, **`__init__()`** defines three parameters but we just passed two (6 and 9). Similarly **`distance()`** requires one but zero arguments were passed. Why is Python not complaining about this argument number mismatch? # ## What Happens Internally? # # **`Point.distance`** and **`p1.distance`** in the above example are different and not exactly the same. type(Point.distance) type(p1.distance) # We can see that the first one is a function and the second one is a method. A peculiar thing about methods (in Python) is that the object itself is passed as the first argument to the corresponding function. # # In the case of the above example, the method call **`p1.distance()`** is actually equivalent to **`Point.distance(p1)`**. # # Generally, when we call a method with some arguments, the corresponding class function is called by placing the method's object before the first argument. So, anything like **`obj.meth(args)`** becomes **`Class.meth(obj, args)`**. The calling process is automatic while the receiving process is not (its explicit). # # This is the reason the first parameter of a function in class must be the object itself. Writing this parameter as **`self`** is merely a convention. It is not a keyword and has no special meaning in Python. We could use other names (like **`this`**) but it is highly discouraged. Using names other than **`self`** is frowned upon by most developers and degrades the readability of the code (**Readability counts**). # ## Self Can Be Avoided # # By now you are clear that the object (instance) itself is passed along as the first argument, automatically. This implicit behavior can be avoided while making a **static** method. Consider the following simple example: class A(object): @staticmethod def stat_meth(): print("Look no self was passed") # Here, **`@staticmethod`** is a **[function decorator]( [IDX] that makes **`stat_meth()`** static. Let us instantiate this class and call the method. a = A() a.stat_meth() # From the above example, we can see that the implicit behavior of passing the object as the first argument was avoided while using a static method. All in all, static methods behave like the plain old functions (Since all the objects of a class share static methods). type(A.stat_meth) type(a.stat_meth) # ## Self Is Here To Stay # # The explicit **`self`** is not unique to Python. This idea was borrowed from **Modula-3**. Following is a use case where it becomes helpful. # # There is no explicit variable declaration in Python. They spring into action on the first assignment. The use of **`self`** makes it easier to distinguish between instance attributes (and methods) from local variables. # # In the first example, **`self.x`** is an instance attribute whereas **`x`** is a local variable. They are not the same and they lie in different namespaces. # # Many have proposed to make **`self`** a keyword in Python, like **`this`** in C++ and Java. This would eliminate the redundant use of explicit **`self`** from the formal parameter list in methods. # # While this idea seems promising, it is not going to happen. At least not in the near future. The main reason is backward compatibility. Here is a blog from the creator of Python himself explaining **[why the explicit self has to stay]( [IDX] ## `__init__()` is not a constructor # # One important conclusion that can be drawn from the information so far is that the **`__init__()`** method is not a constructor. Many naive Python programmers get confused with it since **`__init__()`** gets called when we create an object. # # A closer inspection will reveal that the first parameter in **`__init__()`** is the object itself (object already exists). The function **`__init__()`** is called immediately **after** the object is created and is used to initialize it. # # Technically speaking, a constructor is a method which creates the object itself. In Python, this method is **`__new__()`**. A common signature of this method is: # # ```python # __new__(cls, *args, **kwargs) # ``` # # When **`__new__()`** is called, the class itself is passed as the first argument automatically(cls). # # Again, like **`self`**, **`cls`** is just a naming convention. Furthermore, __*args__ and __**kwargs__ are used to take an arbitrary number of arguments during method calls in Python. # # Some important things to remember when implementing **`__new__()`** are: # # * **`__new__()`** is always called before **`__init__()`**. # * First argument is the class itself which is passed implicitly. # * Always return a valid object from **`__new__()`**. Not mandatory, but its main use is to create and return an object. # # Let's take a look at an example: class Point(object): print("From new") print(cls) print(args) print(kwargs) # create our object and return it obj = super().__new__(cls) return obj def __init__(self,a = 0,b = 0): print("From init") self.a = a self.b = b # Now, let's now instantiate it. p2 = Point(6,9) # This example illustrates that **`__new__()`** is called before **`__init__()`**. We can also see that the parameter **`cls`** in **`__new__()`** is the class itself (**`Point`**). Finally, the object is created by calling the **`__new__()`** method on **object** base class. # # In Python, object is the base class from which all other classes are derived. In the above example, we have done this using **[super()]( [IDX] ## Use `__new__` or `__init__`? # # You might have seen **`__init__()`** very often but the use of **`__new__()`** is rare. This is because most of the time you don't need to override it. Generally, **`__init__()`** is used to initialize a newly created object while **`__new__()`** is used to control the way an object is created. # # We can also use **`__new__()`** to initialize attributes of an object, but logically it should be inside **`__init__()`**. # # One practical use of **`__new__()`**, however, could be to restrict the number of objects created from a class. # # Suppose we wanted a class **`HexPoint`** for creating instances to represent the six vertices of a square. We can inherit from our previous class **`Point`** (the second example in this article) and use **`__new__()`** to implement this restriction. Here is an example to restrict a class to have only four instances. class HexPoint(Point): MAX_Inst = 6 Inst_created = 0 if (cls.Inst_created >= cls.MAX_Inst): raise ValueError("Cannot create more objects") cls.Inst_created += 1 p1 = HexPoint(0,0) p2 = HexPoint(1,0) p3 = HexPoint(1,1) p4 = HexPoint(0,1) p5 = HexPoint(2,2) p6 = HexPoint(2,3) p7 = HexPoint(2,4)
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-10366.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-10366.jsonl"}]
import {Component} from '@angular/core'; import {ViewController, Events} from 'ionic-angular'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {ToastController} from 'ionic-angular'; import {UserServiceProvider} from '../../providers/user-service/user-service'; @Component({ selector: 'modal-settings', templateUrl: 'modal-settings.html' }) export class ModalSettingsComponent { private settings: FormGroup; public passwordFieldType: string = 'password'; constructor(private view: ViewController, private formBuilder: FormBuilder, private toast: ToastController, private events: Events, private userService: UserServiceProvider) { this.userService.getUser() .then((data) => { if (data) { this.settings.setValue(data); } }); this.settings = this.formBuilder.group({ partner: ['', Validators.required], partner_key: ['', Validators.required], currency: ['EUR', Validators.required], partner_cashback_percentage: ['10', Validators.required], description: ['restaurant', Validators.required], }); } public saveSettings(): void { this.userService.saveUser(this.settings.value) .then(() => { this.view.dismiss(); this.events.publish('updatedDefaultSettings'); this.toast.create({ message: 'Settings saved', duration: 3000, position: 'top' }).present() }); } public closeModal() { this.view.dismiss(); } public makePWVisible(){ this.passwordFieldType = 'text'; } public makePWInvisible(){ this.passwordFieldType = 'password'; } }<|endoftext|>import './CheckboxGroup.css'; import React, { forwardRef } from 'react'; import { useChoiceGroup } from '../../hooks/useChoiceGroup/useChoiceGroup'; import { cn } from '../../utils/bem'; import { Checkbox } from '../Checkbox/Checkbox'; import { withDefaultGetters } from './helper'; import { CheckboxGroupComponent, checkboxGroupDefaultDirection, checkboxGroupDefaultSize, checkboxGroupDefaultView, CheckboxGroupProps, } from './types'; export const cnCheckboxGroup = cn('CheckboxGroup'); function CheckboxGroupRender(props: CheckboxGroupProps, ref: React.Ref<HTMLDivElement>) { const { value = null, items, getItemLabel, getItemDisabled, onChange, name, direction = checkboxGroupDefaultDirection, size = checkboxGroupDefaultSize, view = checkboxGroupDefaultView, disabled = false, className, ...otherProps } = withDefaultGetters(props); const { getOnChange, getChecked } = useChoiceGroup({ value, getKey: getItemLabel, callBack: onChange, multiple: true, }); return ( <div {...otherProps} ref={ref} className={cnCheckboxGroup({ direction, size, view }, [className])} > {items.map((item) => ( <Checkbox key={getItemLabel(item)} label={getItemLabel(item)} size={size} view={view} name={name} disabled={disabled || getItemDisabled?.(item)} checked={getChecked(item)} onChange={({ e }) => getOnChange(item)(e)} className={cnCheckboxGroup('Item')} /> ))} </div> ); } export const CheckboxGroup = forwardRef(CheckboxGroupRender) as CheckboxGroupComponent; export * from './types';<|endoftext|>import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { CommonService } from '../common.service'; import { EMAIL_ID, FB_TEXT_PARAM, FORM_URL, MOBILE_NUMBER } from '../config'; @Component({ selector: 'app-contact', templateUrl: './contact.component.html', styleUrls: ['./contact.component.scss'] }) export class ContactComponent implements OnInit { public mobileNumber: string = MOBILE_NUMBER; public emailId: string = EMAIL_ID; public feedbackFormGroup: FormGroup; public submitted: boolean = false; public loading: boolean = false; constructor(private commonService: CommonService) { } ngOnInit() { this.feedbackFormGroup = new FormGroup({ feedbackText: new FormControl(null, [Validators.required]), rating: new FormControl() }); if (localStorage.getItem('isFBSubmitted') === 'true') { this.submitted = true; } } public submit() { const dataToSend = this.feedbackFormGroup.get('feedbackText').value; if (dataToSend != null && dataToSend.length > 0) { this.loading = true; const fbBody = new FormData; fbBody.append(FB_TEXT_PARAM, dataToSend); this.commonService.postMethodWithOptions(FORM_URL, fbBody, { responseType: 'text/html' }).subscribe( (resp: any) => { this.submitted = true; localStorage.setItem('isFBSubmitted', 'true'); this.loading = false; console.log("resp", resp); }, (err: any) => { this.submitted = true; localStorage.setItem('isFBSubmitted', 'true'); this.loading = false; console.log("err", err); } ); } } }<|endoftext|>import React from 'react' import styled from '@emotion/styled' import { css } from '@emotion/core' import themeUtils from '../../theme-utils' interface MenuIconProps { isOpen: boolean toggleOpen: () => void } type LineProps = Pick<MenuIconProps, 'isOpen'> const iconContainer = css` position: relative; right: 25px; top: 0; height: 100%; display: flex; flex-direction: column; justify-content: center; background-color: ${themeUtils.baseColor}; border: none; ` const icon = css` position: relative; height: 20px; width: 30px; cursor: pointer; z-index: 10; ` const MenuLine = css` background-color: ${themeUtils.lightAccent}; height: 3px; width: 100%; border-radius: 2px; position: absolute; left: 0; transition: all 0.25s cubic-bezier(0.175, 0.885, 0.32, 1.275); ` const Line1 = styled('span')<LineProps>` ${MenuLine}; top: 0; transform: ${({ isOpen }): string => isOpen ? 'translateY(10px) translateY(-50%) rotate(-135deg)' : ''}; ` const Line2 = styled('span')<LineProps>` ${MenuLine}; top: 0; bottom: 0; margin: auto; opacity: ${({ isOpen }): string => (isOpen ? '0' : '')}; ` const Line3 = styled('span')<LineProps>` ${MenuLine}; bottom: 0; transform: ${({ isOpen }): string => isOpen ? 'translateY(-10px) translateY(50%) rotate(135deg)' : ''}; ` const MenuIcon = ({ isOpen, toggleOpen }: MenuIconProps): JSX.Element => ( <button aria-label='menu' aria-expanded={isOpen} css={iconContainer} onClick={():void => toggleOpen()} type='button' > <div css={icon}> <Line1 isOpen={isOpen} /> <Line2 isOpen={isOpen} /> <Line3 isOpen={isOpen} /> </div> </button> ) export default MenuIcon<|endoftext|>import * as React from 'react'; import { mocked } from 'ts-jest/utils'; import { indexUsersEnabled } from 'config/config-utils'; import { GlobalState } from 'ducks/rootReducer'; import globalState from 'fixtures/globalState'; import { dashboardMetadata } from 'fixtures/metadata/dashboard'; import { activeUser0 } from 'fixtures/metadata/users'; import { mapStateToProps, DASHBOARD_OWNER_SOURCE } from '.'; jest.mock('config/config-utils', () => ({ indexUsersEnabled: jest.fn(), })); describe('mapStateToProps', () => { let result; let expectedItemProps; let mockState: GlobalState; beforeAll(() => { mockState = { ...globalState, dashboard: { dashboard: { ...dashboardMetadata, owners: [activeUser0], }, isLoading: false, statusCode: 200, }, }; }); it('returns expected itemProps when indexUsersEnabled()', () => { mocked(indexUsersEnabled).mockImplementation(() => true); result = mapStateToProps(mockState); const id = activeUser0.user_id; expectedItemProps = { [id]: { label: activeUser0.display_name, link: `/user/${id}?source=${DASHBOARD_OWNER_SOURCE}`, isExternal: false, }, }; expect(result.itemProps).toEqual(expectedItemProps); }); it('returns expected itemProps when !indexUsersEnabled()', () => { mocked(indexUsersEnabled).mockImplementation(() => false); result = mapStateToProps(mockState); expectedItemProps = { [activeUser0.user_id]: { label: activeUser0.display_name, link: activeUser0.profile_url, isExternal: true, }, }; expect(result.itemProps).toEqual(expectedItemProps); }); });<|endoftext|>import { from } from "rxjs"; import { map, tap } from "rxjs/operators"; import { feed } from "../../../src/repository/operators"; import { mockRepo } from "../../helpers/repo_helper"; describe("repository/operators/feed", () => { /** * Tests for changed request/response as well as the caching of fromVersion within * observable pipe. */ test("Validate fromVersion handling", (done) => { const entityId = "TEST_ENTITY_ID"; const entityName = "TEST_ENTITY_NAME"; const entityType = "TEST_ENTITY_TYPE"; let fromVersion: number | undefined = undefined; const repo = mockRepo(entityType, (req$) => req$.pipe( tap((req) => { // Check method name expect(req.method).toBe("GetFeed"); // Check typeName (pulled from repository) expect(req.params.typeName).toBe(entityType); // Check search.id (pulled from args) expect(req.params.search.id).toBe(entityId); if (fromVersion !== undefined) { expect(req.params.fromVersion).toBe(fromVersion + 1); } fromVersion = req.params.fromVersion; }), map((req) => ({ ...req, result: { data: [{ id: entityId, name: entityName }], toVersion: (fromVersion ?? -1) + 1, }, })) ) ); from([0, 1, 2, 3]) .pipe( feed(repo, { id: entityId }), // eslint-disable-next-line @typescript-eslint/no-explicit-any tap((changed: any) => { expect(changed.id).toBe(entityId); expect(changed.name).toBe(entityName); }) ) .subscribe({ error: done, complete: done, }); }); });
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-4892.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-4892.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-4892.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-4892.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-4892.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-4892.jsonl"}]
For Loop not working inside Node.js while using mongoose Question: I am trying fetch records from mongoDB through mongoose <code> router.route('/testaa') .get(function(req,res){ fisSite.find(function(err, retVal) { var x = []; for(var i =0;i<retVal.length;i++){ x.push(retVal[i].site); } res.json(x) }); }) </code> The above code is giving undefined values. <code>undefined undefined undefined ..... </code> Please help to run the for loop inside node.js so that i can use extract data from array. Comment: Did you try to print the site inside the loop to have a check? Comment: Yes i tried still giving me the same undefined value Comment: var model = [ { "_id": "5912cf4766a19f6acf8fda8d", "site": "Gurgaon HR IND" }, { "_id": "5912cf6066a19f6acf8fda8e", "site": "Chandigarh IND" }, { "_id": "5912cf6066a19f6acf8fda8f", "site": "Noida IND" }, { "_id": "5912cf7566a19f6acf8fda90", "site": "Mumbai IND" }] Comment: Since you have initialized x with []. It should not be undefined. So where was the undefined printed, the nodejs console or when you try to access the api from browser? Comment: i tried on both in console as well as in api result Comment: What's the value of retVal, the same as the model you gave? Comment: Have you tried `fisSite.find().lean().exec(function(err, retVal) { ... });`? Comment: Thanks @chridam ....Its working now...router.route('/site') .get(function(req,res){ fisSite.find().lean().exec(function(err, retVal) { var x = []; for(var i =0;i<retVal.length;i++){ x.push(retVal[i].site); } res.json(x) }) }); Answer: Currently what you are doing is you are getting all the document fields and then using only one from it. You can optimize the query using select method which will only retrieve particular field only rather than all fields : [Note : id field is added by default, hence to remove it in select we specifically mention it using -_id. You can remove -_id if you want to maintain ID inside the response document.] <code>fisSite.find({}).select('site -_id').exec(function(err, docs)){ if(err){ return res.json({ status : false, message : 'Error Occured.'} ); } else if(!docs){ return res.json({ status : false, message : 'No documents found.'} ); } else{ return res.json({ status : success, message : 'Documents found.', data : docs} ); } } </code> Imagine you have 10 fields in each document and find results 100 documents, you only need site field from those 100 documents,however unnecessarily you are calling remaining 900 fields. Answer: I have used Lean.exec within Mongoose. <code> router.route('/site') .get(function(req,res){ fisSite.find().lean().exec(function(err, retVal) { var x = []; for(var i =0;i<retVal.length;i++){ x.push(retVal[i].site); } res.json(x) }) }); </code> Answer: Try to add an empty search query to select all documents Try to change From this: <code>fisSite.find(function(err, retVal) </code> To this: <code>fisSite.find({}, function(err, retVal) </code> Also try to do a <code>console.log(retVal)</code> to check if your find actually returns any values.<|endoftext|>Comments in continuation lines Question: Say I have a multiline command: <code>if 2>1 \ and 3>2: print True </code> In an <code>if</code> block, I can add a comment next to one of the conditions by using parentheses to wrap the lines: <code>if (2>1 #my comment and 3>2): print True </code> And, in fact, it is aligned with the recommened way of doing this by PEP 8 guideline: The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. However, sometimes you need to use continuations. For example, long, multiple with-statements cannot use implicit continuation. Then, how can I add a comment next to a specific line? This does not work: <code>with open('a') as f1, #my comment\ open('b') as f2: print True </code> More generally, is there a generic way to add a comment next to a specific continuation line? Comment: Spyder tells me "invalid sytax" when I put your code in, and "unexpected character after line continuation character" when I put a `\` before the comment, so I'm guessing no, you can't do line comments with line continuation. I'm guessing that it has to do with trying to splice a comment into a statement, i.e. x = 2 + #comment# 3 Answer: You cannot. Find some extracts from Python reference manual (3.4): A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line. A line ending in a backslash cannot carry a comment A comment signifies the end of the logical line unless the implicit line joining rules are invoked Implicit line joining : Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes Implicitly continued lines can carry comments So the reference manual explicitly disallows to add a comment in an explicit continuation line. Answer: You can't have comments and backslash for line continuation on the same line. You need to use some other strategy. The most basic would be to adjust the comment text to place it e.g. before the relevant section. You could also document your intentions without comments at all by refactoring the code returning the context into a function or method with a descriptive name. Comment: Interesting!. I am accepting the other answer, since it provides some references. However, this one I will also use. Many thanks! Answer: I don't see any solution except nesting the <code>with</code>: <code>with open('a.txt', 'w') as f1: #comment1 with open('b.txt', 'w') as f2: #comment2 print True </code> Comment: Obviously the with-statement is not "multiple" anymore. Comment: This is a clever way to prevent the problem from happening. However, I am still curious about how to do this _using_ continuation lines. Answer: You cannot combine end-of-line comment (<code>#</code>) and line continuation (<code>\</code>) on the same line. I am not recommending this. -- However, sometimes you can masquerade your comment as a string: <code>with open(('a', '# COMMENT THIS')[0]) as f1, \ open(('b', '# COMMENT THAT')[0]) as f2: print(f1, f2) </code><|endoftext|>How to deserialize arrays inside arrays on C# using newtonsoft Question: I want to deserialize this JSON data. How can I deserialize it to a C# class object or list? <code>[ 2074, [ 0, 0, 0, 1, 0, 0, 0 ], 0, [ { "886":[ "Anna Bay" ], "3971":[ "Dmitry Khraponenkov" ] }, [ 3971, 886 ] ] ] </code> I need to parse out the names. I tried this, but this is a very different thing: newtonsoft.com/json/help/html/DeserializeCollection.htm Comment: Please provide a [mcve] of what you have tried. Comment: i tried this but this is very different thing. [IDX] Please put it in your post Comment: done @ArtemisFowl Comment: What object/list are you trying to deserialize this into now? What exactly does each part of the JSON data represent? Comment: Well you've linked to a documentation page that tries to deserialize to a list of strings. Your JSON doesn't represent a list of strings. Did you try deserializing to a `List`? What happened with whatever you *did* try? Answer: Without knowing more about what exactly this data represents or what class structure you would ideally want to deserialize it into, it is difficult to provide useful advice. But, if I take your question literally as, "here's some JSON with mixed data types; how do I extract the names from it?", then you can solve that problem using Json.Net's LINQ-to-JSON API: <code>string json = @"[ 2074, [ 0, 0, 0, 1, 0, 0, 0 ], 0, [{ ""886"": [ ""Anna Bay"" ], ""3971"": [ ""Dmitry Khraponenkov"" ] }, [ 3971, 886 ] ] ]"; List<string> names = JArray.Parse(json) .Descendants() .OfType<JProperty>() .SelectMany(p => p.Value, (p, t) => (string)t) .ToList(); Console.WriteLine(string.Join(Environment.NewLine, names)); </code> Fiddle: [IDX] A note about JSON JSON is used to represent a data structure. The data contained is often a collection of name-value pairs. Pairing each value with a name allows a consumer to work with the JSON with no prior knowledge of the data or data structure. As Brian points out in the comments below, JSON can also be a collection of values, but this puts the burden of interpreting those values on the consumer. Back to your question Most of your values don't have names, which makes it difficult to deserialize to a C# class object. If you are able to modify the JSON, please do so and give each value a name. If you are not able to modify the JSON, then you may just want to parse the string. To learn more about JSON, visit: [IDX] I have to disagree. JSON is not "by definition a collection of name-value pairs". That is only *one* component of JSON. JSON also consists of arrays and simple values. (See [JSON.org]( [IDX] In fact, you can have perfectly valid JSON that contains no name-value pairs at all, for example `["foo", "bar", "baz"]`. Granted, it is difficult to deserialize mixed data such as the OP's into a class structure, but it can be done using one or more custom JsonConverters, so long as we know how the data should be mapped (which the OP has not bothered to explain to us). Comment: @BrianRogers You're right. My original definition was too strict. I've updated my answer. Thanks for the feedback.<|endoftext|>Change language of Datepicker with maintaining format of Material Angular 10 Question: I do have Multilanguage support in my application and would like to implement translation for the angular material date picker. I have used dateAdapter class from material and set the values but while doing so my format of display is getting changes. Is anyone have faced same issue? <code>export const MY_FORMATS = { parse: { dateInput: 'LL', }, display: { dateInput: 'ddd, MMM. D YYYY', monthYearLabel: 'MMM YYYY', dateA11yLabel: 'LL', monthYearA11yLabel: 'MMMM YYYY', }, }; @Component({ selector: 'test', templateUrl: './test.html', styleUrls: ['./test.scss'], providers: [{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }], }) ngOnInit(): void { //on language change //change language this.dateAdapter.setLocale('fr'); }</code> Answer: For multilanguage support I would recommend you to use the MomentDateAdapter. Here is one note from Angular docs about multi-language support and the NativeDateAdapter (the default one's): MatNativeDateModule is based off the functionality available in JavaScript's native Date object. Thus it is not suitable for many locales. One of the biggest shortcomings of the native Date object is the inability to set the parse format. We highly recommend using the MomentDateAdapter or a custom DateAdapter that works with the formatting/parsing library of your choice. The only counterpart is that by using <code>MomentDateAdapter</code> you will now have <code>moment</code> as a dependency... but not big deal, and you may already be using it. Here is some example code (taken from Angular docs): <code>import {Component} from '@angular/core'; import { MAT_MOMENT_DATE_FORMATS, MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS, } from '@angular/material-moment-adapter'; import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core'; /** @title Datepicker with different locale */ @Component({ selector: 'test', templateUrl: 'test.html', styleUrls: ['test.css'], providers: [ // The locale would typically be provided on the root module of your application. We do it at // the component level here, due to limitations of our example generation script. {provide: MAT_DATE_LOCALE, useValue: 'fr'}, // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing // `MatMomentDateModule` in your applications root module. We provide it at the component level // here, due to limitations of our example generation script. { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS] }, {provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS}, ], }) export class DatepickerLocaleExample { constructor(private _adapter: DateAdapter<any>) {} // Change adapter language to japanese japanese() { this._adapter.setLocale('ja-JP'); } } </code> Comment: Here you have an example with MatMomentAdapter and a custom format, the same you provided: [IDX] Thanks for your response. Is it helping to retain custom format while you change the language? I tried but it is not retaining my custom format. Can you provide working example?
[{"idx": "For_Loop_not_working_inside_Node.js_while_using_mongoose", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-25846.jsonl"}, {"idx": "Comments_in_continuation_lines", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-25846.jsonl"}, {"idx": "How_to_deserialize_arrays_inside_arrays_on_C#_using_newtonsoft", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-25846.jsonl"}, {"idx": "Change_language_of_Datepicker_with_maintaining_format_of_Material_Angular_10", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-25846.jsonl"}]
use std::{ path::Path, u32, u8, usize, vec, io::{ BufRead, BufReader, Cursor, Result, Seek, SeekFrom, Read } }; use byteorder::{ BigEndian, ReadBytesExt }; use lz4::block::decompress; use crate::io_extension::ReaderExtension; #[derive(Debug, Clone)] pub struct Header { magic: String, pub version: i32, unity_version: String, unity_revision: String, size: i64, compressed_blocks_info_size: u32, uncompressed_blocks_info_size: u32, flags: u32 } impl Header { pub fn new<T: BufRead + ReadBytesExt + ReaderExtension>(reader: &mut T) -> Result<Self> { let magic = reader.read_null_terminated_string()?; let version = reader.read_i32::<BigEndian>()?; let unity_version = reader.read_null_terminated_string()?; let unity_revision = reader.read_null_terminated_string()?; let size = reader.read_i64::<BigEndian>()?; let compressed_blocks_info_size = reader.read_u32::<BigEndian>()?; let uncompressed_blocks_info_size = reader.read_u32::<BigEndian>()?; let flags = reader.read_u32::<BigEndian>()?; Ok( Header { magic, version, unity_version, unity_revision, size, compressed_blocks_info_size, uncompressed_blocks_info_size, flags } ) } } #[derive(Debug, Clone)] struct StorageBlock { uncompressed_size: u32, compressed_size: u32, flags: u16 } #[derive(Debug, Clone)] struct Node { offset: i64, size: i64, flags: u32, path: String } #[derive(Debug, Clone)] pub struct File { pub path: String, pub filename: String, pub bytes: Vec<u8> } #[derive(Debug, Clone)] pub struct AssetBundle { header: Header, pub asset_files: Vec<File> } // Only for UnityFS for now impl AssetBundle { pub fn new(path: &String) -> Result<AssetBundle> { let file = std::fs::File::open(&path).expect(format!("Expected {}", path.as_str()).as_str()); let mut reader = BufReader::new(file); let header = Header::new(&mut reader)?; if header.version >= 7 { //Align 16 bytes reader.align_stream(0x10) } let mut blocks_info_bytes = vec![0u8; header.compressed_blocks_info_size as usize]; if (header.flags & 0x80) != 0 { let pos = reader.stream_position()?; let file_size = reader.stream_len()?; reader.seek( SeekFrom::Start( file_size - header.compressed_blocks_info_size as u64 ) )?; reader.read_exact(&mut blocks_info_bytes)?; reader.seek( SeekFrom::Start(pos) )?; } else { reader.read_exact(&mut blocks_info_bytes)?; } let mut uncompressed_block_info = vec![0u8; header.uncompressed_blocks_info_size as usize]; match header.flags & 0x3F { //TODO: 1 LZMA 1 => { panic!("LZMA is not implemented"); } 2 | 3 => { uncompressed_block_info = decompress(&blocks_info_bytes, Some(header.uncompressed_blocks_info_size as i32))?; } _ => { uncompressed_block_info = blocks_info_bytes.clone(); } } let mut blocks_info_reader = Cursor::new(uncompressed_block_info); let mut uncompressed_data_hash = vec![0u8; 0x10]; blocks_info_reader.read_exact(&mut uncompressed_data_hash)?; let blocks_info_count = blocks_info_reader.read_i32::<BigEndian>()?; let mut m_blocks_info: Vec<StorageBlock> = Vec::with_capacity(blocks_info_count as usize); for _ in 0..blocks_info_count as usize { m_blocks_info.push( StorageBlock { uncompressed_size: blocks_info_reader.read_u32::<BigEndian>()?, compressed_size: blocks_info_reader.read_u32::<BigEndian>()?, flags: blocks_info_reader.read_u16::<BigEndian>()? } ) } let nodes_count = blocks_info_reader.read_i32::<BigEndian>()?; let mut m_directory_info: Vec<Node> = Vec::with_capacity(nodes_count as usize); for _ in 0..nodes_count as usize { m_directory_info.push( Node { offset: blocks_info_reader.read_i64::<BigEndian>()?, size: blocks_info_reader.read_i64::<BigEndian>()?, flags: blocks_info_reader.read_u32::<BigEndian>()?, path: blocks_info_reader.read_null_terminated_string()? } ) } // [IDX] let mut uncompressed_size_sum: usize = 0; for storage_block in m_blocks_info.clone() { uncompressed_size_sum += storage_block.uncompressed_size as usize; }; let mut block: Vec<u8> = Vec::with_capacity(uncompressed_size_sum); for block_info in m_blocks_info.clone() { let mut uncompressed_block_info: Vec<u8> = vec![0u8; block_info.uncompressed_size as usize]; let mut compressed_block_info: Vec<u8> = vec![0u8; block_info.compressed_size as usize]; reader.read_exact(&mut compressed_block_info)?; match block_info.flags & 0x3F { //TODO: 1 LZMA 1 => { panic!("LZMA is not implemented"); } 2 | 3 => { uncompressed_block_info = decompress(&compressed_block_info, Some(block_info.uncompressed_size as i32))?; } _ => { uncompressed_block_info = compressed_block_info.clone(); } } block.append(&mut uncompressed_block_info); } let mut block_reader = Cursor::new(block); let mut files: Vec<File> = Vec::with_capacity(m_directory_info.len()); for index in 0..m_directory_info.len() { let node = &m_directory_info[index]; let mut file_buffer: Vec<u8> = vec![0u8; node.size as usize]; block_reader.set_position(node.offset as u64); block_reader.read_exact(&mut file_buffer)?; files.push( File { path: node.path.to_string(), filename: Path::new(&node.path) .file_name() .expect("Expected filepath") .to_str() .unwrap() .to_string(), bytes: file_buffer } ); } Ok( AssetBundle { header, asset_files: files } ) } }<|endoftext|>//! The traits for an angle use std::{convert::TryFrom, error::Error, str::FromStr}; use num_traits::{CheckedAdd, CheckedSub}; pub mod dd; mod degree; pub mod dms_dd; mod errors; pub use errors::OutOfRange; #[allow(clippy::module_name_repetitions)] /// Common terminology for angles: /// < [IDX] trait AngleNames: Copy + PartialOrd { /// No angle fn zero() -> Self; /// The angle made of perpendicular rays fn right() -> Self; /// The angle made of two exactly opposite direction fn straight() -> Self; /// The angle made of full circle (perigon) fn complete() -> Self; /// No angle fn is_zero(self) -> bool { self == Self::zero() } /// Is the angle sharp? fn is_acute(self) -> bool { self > Self::zero() && self < Self::right() } /// Are the lines perpendicular? fn is_right(self) -> bool { self == Self::right() } /// Is the angle blunt? fn is_obtuse(self) -> bool { self > Self::right() && self < Self::straight() } /// Is the angle forms a straight line? fn is_straight(self) -> bool { self == Self::straight() } /// Is the angle more than a straight line? fn is_reflex(self) -> bool { self > Self::straight() && self < Self::complete() } /// Is the angle full round? fn is_complete(self) -> bool { self == Self::complete() } } /// Angle with ordering, addition/subtraction operations and /// the abilities to construct itself from a string or a float number pub trait Angle: AngleNames + Ord + CheckedAdd + CheckedSub + FromStr<Err = <Self as Angle>::ParseErr> + TryFrom<f64, Error = <Self as Angle>::NumErr> { /// The error that can appear when representing some part of the angle with a number type NumErr: Error; /// The error that can appear while parsing the angle from a string type ParseErr: Error; /// Adjacent angle which sum to a [right](trait.AngleNames.html#tymethod.right) angle fn complement(self) -> Option<Self> { Self::right().checked_sub(&self) } /// Adjacent angle which sum to a [straight](trait.AngleNames.html#tymethod.straight) angle fn supplement(self) -> Option<Self> { Self::straight().checked_sub(&self) } /// Adjacent angle which sum to a [complete](trait.AngleNames.html#tymethod.complete) angle fn explement(self) -> Self { Self::complete() .checked_sub(&self) .expect("Current implementation stores angles <=360 degrees") } /// Difference between the angles by modulo independent of the order fn abs_diff(self, rhs: Self) -> Self { let diff = self.checked_sub(&rhs).or_else(|| rhs.checked_sub(&self)); // difference should always be less than the maximum (considered valid) angle diff.expect("Difference is small enough to be valid angle") } /// Is the `other` angle differs by an exact multiple of a full turn fn turn_eq(self, mut other: Self) -> bool { while other >= Self::complete() { other = other - Self::complete(); } self == other } /// Produce an error variant indicating an angle is more than the [right](trait.AngleNames.html#tymethod.right) one fn obtuse_err() -> Self::NumErr; /// Produce an error variant indicating an angle is [reflex](trait.AngleNames.html#tymethod.is_reflex) fn reflex_err() -> Self::NumErr; /// Produce an error variant indicating an angle does not fall into [full circle](trait.AngleNames.html#tymethod.complete) fn turn_err() -> Self::NumErr; /// Check the angle is less than or equal to the [right](trait.AngleNames.html#tymethod.right) one /// /// # Errors /// When the angle is greater than 90 degrees fn and_not_obtuse(self) -> Result<Self, Self::NumErr> { if self > Self::right() { Err(Self::obtuse_err()) } else { Ok(self) } } /// Check the angle is less than or equal to the [straight](trait.AngleNames.html#tymethod.straight) one /// /// # Errors /// When the angle is greater than 180 degrees fn and_not_reflex(self) -> Result<Self, Self::NumErr> { if self.is_reflex() { Err(Self::reflex_err()) } else { Ok(self) } } } pub(super) trait UnitsAngle: Angle { type Units: CheckedAdd + CheckedSub; fn from_units(u: Self::Units) -> Result<Self, Self::NumErr>; fn units(self) -> Self::Units; fn max_units() -> Self::Units { Self::complete().units() } } #[doc(hidden)] #[macro_export] /// Implement addition and subtraction operations /// on the `UnitsAngle` types. /// `$sum_t` should be able to hold a sum of any units /// without the risk of overflow. macro_rules! impl_angle_ops { ($t:ty: <$sum_t: ty) => { impl Add for $t { type Output = Self; fn add(self, rhs: Self) -> Self::Output { if let Some(sum) = self.checked_add(&rhs) { return sum; } // the sum can overflow `Units`, so convert everything to $sum_t let self_units = <$sum_t>::from(self.units()); let rhs_units = <$sum_t>::from(rhs.units()); let max = <$sum_t>::from(Self::max_units()); assert!(self_units <= max); assert!(rhs_units <= max); assert!(self_units + rhs_units > max); let sum_units = (self_units + rhs_units - max) .try_into() .expect("Less than max should be valid"); Self::from_units(sum_units) .expect("Wrapping sum around the max degree is always a valid degree") } } impl CheckedAdd for $t { fn checked_add(&self, rhs: &Self) -> Option<Self> { self.units() .checked_add(rhs.units()) .filter(|&sum_units| sum_units <= Self::max_units()) .and_then(|units| Self::from_units(units).ok()) } } impl Sub for $t { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { if let Some(diff) = self.checked_sub(&rhs) { return diff; } let self_ = self.units(); let rhs = rhs.units(); assert!(self_ < rhs); let max = Self::max_units(); let diff = max - (rhs - self_); Self::from_units(diff).expect("The diff is less than the max angle") } } impl CheckedSub for $t { fn checked_sub(&self, rhs: &Self) -> Option<Self> { self.units() .checked_sub(rhs.units()) .and_then(|units| Self::from_units(units).ok()) } } }; }
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-14454.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-14454.jsonl"}]
### Code: ``` #!pygmentize ./src/demo_data_quality_model_monitor.py bucket=bucket, kms_key=None, subnets=None, security_group_ids=None, role=role, tags=tags)``` ### Output: <empty_output> ### Description: Create a Data Quality Monitor Schedule ### Code: ``` my_monitor = demo_mon.create_data_quality_monitor()``` ### Output: <empty_output> ### Description: This may take a while.. Check Outputs of Baseline Suggestion ### Code: ``` # Get a list of S3 URIs report_files = S3Downloader.list(f"s3://{bucket}/{s3_data_quality_baseline_prefix}") pd.DataFrame(json.loads(S3Downloader.read_file(report_files[0]))["features"]) for filename in report_files: schema_df = pd.json_normalize(json.loads(S3Downloader.read_file(s3_statistics_uri))["features"]) constraints_df = pd.json_normalize(json.loads(S3Downloader.read_file(s3_constraints_uri))["features"]) schema_df.head() constraints_df.head()``` ### Output: <empty_output> ### Description: Test Scenarios[overview](overview-0)----We will test a few scenarios to verify if filtering based on custom attributes is working First Scenario: 1. 2. 3. 4. 5. ### Code: ``` #!pygmentize ./src/artificial_traffic.py ) sample_config applicationName = "DEMO", testIndicator = "false", payload=payload, size=1, config=[] ) applicationName="DEMO", testIndicator="true", payload=payload, size=1, ) print(f"Current Transaction Id: {artificial_traffic.transactionId}")``` ### Output: <empty_output> ### Description: View Data Capture file in S3It may take a minute for data capture files to be populated in S3 ### Code: ``` current_endpoint_capture_prefix = f"{data_capture_prefix}/{current_endpoint_name}" capture_files_scenario_1 = S3Downloader.list(f"s3://{bucket}/{current_endpoint_capture_prefix}") capture_files_scenario_1 = S3Downloader.list(f"s3://{bucket}/{current_endpoint_capture_prefix}") time.sleep(10) print(f"\n data capture path: {data_capture_path_scenario_1}")``` ### Output: <empty_output> ### Description: Trigger a Manual Model Monitoring Job SageMaker Model Monitor uses [Processing Job]( [IDX] under the hood so we can manually trigger a Monitoring job for testing. ### Code: ``` #!pygmentize ./src/monitoringjob_utils.py print(f"S3 Location for statistics.json: {s3_statistics_uri}") print(f"S3 Location for constraints.json: {s3_constraints_uri}") print(f"S3 Location for report outputs: {s3_reports_path}") region, 'ml.m5.xlarge', role, s3_statistics_uri, s3_constraints_uri, )``` ### Output: <empty_output> ### Description: Check the Manual Monitor Outputs ### Code: ``` SortOrder='Descending', MaxResults=2 ) ### Output: <empty_output> ### Description: Confirm above that there is no violations detected ### Code: ``` head``` ### Output: <empty_output> ### Description: Confirm that "item_count" is 1 not 2 Second Scenario: 1. 2. 3. ### Code: ``` applicationName="DEMO", testIndicator="false", payload=payload, size=1000, ) print(f"Current Transaction Id: {artificial_traffic.transactionId}") capture_files_scenario_2 = ['s3://{0}/{1}'.format(bucket, capture_file.get("Key")) for capture_file in result_scenario_2.get('Contents')] print("Capture Files: ") print("\n ".join(capture_files_scenario_2)) print(f"\n data capture path: {data_capture_path_scenario_2}") region, ) SortOrder='Descending', MaxResults=2 ) ### Output: <empty_output> ### Description: Confirm that there are violations detected. ### Code: ``` head``` ### Output: <empty_output> ### Description: Clean-Up[overview](overview-0)----We can delete model monitoring schedule and endpoint we created earlier. ### Code: ``` sm.delete_endpoint(EndpointName=current_endpoint_name)``` ### Output: <empty_output> ### Description: Release Resources ### Code: ``` %%html <button class="sm-command-button" data-commandlinker-command="kernelmenu:shutdown" style="display:none;">Shutdown Kernel</button> <script> try { els = document.getElementsByClassName("sm-command-button"); els[0].click(); } catch(err) {} </script>``` ### Output: <empty_output><|endoftext|>### Description: Primero obtenemos el Dataframe de pandas que nos proporciona el API de yahoo finance de la acción AAPl (Apple) desde 2012 hasta la actualidad ### Code: ``` #fecha de hoy today = str(datetime.today().year)+"-"+str(datetime.today().month)+"-"+str(datetime.today().day) df plt.figure(figsize=(16,8)) plt.plot(df['Close']) plt.ylabel('Close Price USD ($)', fontsize=18)``` ### Output: <empty_output> ### Description: Ahora necesitamos definir la cantidad de valores que se van a usar para tanto el entrenamiento de la red neural, como para probar, para este caso va a ser un 80% para entrenamientoFiltramos por la columna 'close' del dataframe que es la que vamos a utilizar para las predicciones ### Code: ``` train_data_len``` ### Output: <empty_output> ### Description: Necesitamos escalar los datas para que esten en un rango entre $(0,1)$ ### Code: ``` scaled_data``` ### Output: <empty_output> ### Description: Ahora creamos un dataset de entrenamiento, en base a los datos escalados en el rango definido anteriormente ($90\%$)Para esto creamos la matriz x_train y el arreglo y_trainx_train: es una matriz con las últimas 100 posiciones del dataset, en este caso, el comportamiento de la acción en los últimos 100 díasy_train, es su espejo en el eje y, es decir si fueramos a graficar, cuando se tiene un patrón de comportamiento parecido a los úlimos 100 días, se llega al valor de y_train[i] ### Code: ``` x_train = [] y_train = [] y_train.append(train_data[i , 0])``` ### Output: <empty_output> ### Description: Los convertimos en arreglos de numpyY posteriormente hacemos un 'reshape' que es básicamente convertir los datos que tenemos en 2 dimensiones a 3 dimensiones ya que de esta manera funcionan las redes reuronales de tensorflow, por lo que añadimos una dimensión más con un 1 constante ### Code: ``` #Reshape x_train.shape``` ### Output: <empty_output> ### Description: Ahora contruimos la red LSTM utilizando Keras de tensorflowLSTM (Long short-term memory) es una arquitectura de red neuronal usada en deep learning ### Code: ``` model = Sequential() model.add(Dense(25)) model.add(Dense(1))``` ### Output: <empty_output> ### Description: Compilamos el modelo, utilizando como loss que es la medida para indicar al modelo cuál es la variable que debe minimizar para alcanzar la meta deseada, en este caso el error cuadrático medio ### Code: ``` model.compile(optimizer='adam',loss='mean_squared_error')``` ### Output: <empty_output> ### Description: Ponemos el modelo finalmente a entrenar ### Code: ``` model.fit(x_train,y_train,batch_size=1,epochs=1)``` ### Output: 1875/1875 [==============================] - 40s 21ms/step - loss: 2.5811e-04 ### Description: Ahora creamos un nuevo dataset que va a contener los datos para probar la efectividad del modelo, para esto creamos un test que va a contener el comportamiento de la acción en los últimos 100 días ### Code: ``` x_test = [] x_test.append(test_data[i-100:i, 0])``` ### Output: <empty_output> ### Description: Convertimos de nuevo los datos a arreglos numpy ### Code: ``` x_test = np.array(x_test) x_test.shape``` ### Output: <empty_output> ### Description: Aplicamos reshape para tener los datos en tres dimensiones ### Code: ``` x_test = np.reshape(x_test,(x_test.shape[0],x_test.shape[1],1))``` ### Output: <empty_output> ### Description: Obtenemos las predicciones con base al modelo de pruebaY como los datos están escalados en un rango de $(0,1)$, tenemos que volver a esacalarlos para tener finalmente los datos una vez más a escala real ### Code: ``` predictions = scaler.inverse_transform(predictions)``` ### Output: <empty_output> ### Description: El valor del error promedio en estas predicciones ### Code: ``` rmse``` ### Output: <empty_output> ### Description: Predictions es un arreglo que contriene los valores de las predicciones del 10% que no usamos para entrenar la red NeuronalAhora vamos a compararlos con los valores del comportamiento real de la acción en este periodo de tiempo ### Code: ``` #Visualize the data plt.figure(figsize=(16,8)) plt.title('Model') plt.plot(train['Close']) plt.show() X_test = [] X_test = np.array(X_test) type(X_test) print(pred_price)``` ### Output: [[146.6335]]<|endoftext|>### Description: Load the Basic- and APADB-tuned APARENT model-- Load the basic APARENT model, which has been trained to predict the isoform abundance and cut profile of a proximal PAS given a fixed background distal PAS (trained on random 3' UTR APA MPRA data).-- Load the APADB-fitted APARENT model, composed of two siamese APARENT networks which score the proximal and distal PASs. Linear regression of the proximal and distal scores are used to infer the relative APA isoform abundance (fitted on human pooled-tissue APADB data). ### Code: ``` aparent_encoder = get_aparent_encoder() #Load APADB-tuned APARENT model and input encoder apadb_model = load_model('../saved_models/aparent_apadb_fitted_large_lessdropout_no_sampleweights.h5') apadb_encoder = get_apadb_encoder()``` ### Output: WARNING:tensorflow:From /home/johli/anaconda3/envs/aparent/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: WARNING:tensorflow:From /home/johli/anaconda3/envs/aparent/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version. Instructions for updating: ### Description: Example 1: PSMC6 Gene APA prediction-- First predict the non-normalized isoform score of each PAS sequence (score is relative to the average random MPRA distal bias).-- Then predict the relative APA isoform abundance using the APADB-fitted model. ### Code: ``` #Example APA sites from APADB (gene = PSMC6) #Site Distance site_distance = 180 prox_cut_start, prox_cut_end = 80, 105 dist_cut_start, dist_cut_end = 80, 105 print("Non-normalized proximal sum-cut logit = " + str(logit(np.sum(cut_pred_prox[0, prox_cut_start:prox_cut_end])))) print("Non-normalized distal sum-cut logit = " + str(logit(np.sum(cut_pred_dist[0, dist_cut_start:dist_cut_end])))) print("") print("Predicted proximal vs. distal isoform % (APADB) = " + str(iso_pred[0, 0])) plt.title("Normalized proximal cut profile", fontsize=16) plt.yticks(fontsize=14) plt.tight_layout() plt.show() plt.title("Normalized distal cut profile", fontsize=16) plt.yticks(fontsize=14) plt.tight_layout() plt.show()``` ### Output: Non-normalized proximal sum-cut logit = 2.068363954922734 Non-normalized distal sum-cut logit = 1.7659008653702761 Predicted proximal vs. distal isoform % (APADB) = 0.7347708 ### Description: Example 2: KTN1 Gene APA prediction-- First predict the non-normalized isoform score of each PAS sequence (score is relative to the average random MPRA distal bias).-- Then predict the relative APA isoform abundance using the APADB-fitted model. ### Code: ``` #Example APA sites from APADB (gene = KTN1) seq_prox = 'AAAACTGTTTGAATAATTAGACCTTTACATTCCTGAAGATAAACATGTAATCTTTTATCTTATTTTGCTCAATAAAATTGTTCAGAAGATCAAAGTGGTAAAGACAATGTAAAATTTAACATTTTAATACTGATGTTGTACACTGTTTTACTTAACATTTTGGGAAGTAACTGCCTCTGACTTCAACTCAAGAAAACACTTTTTT' seq_dist = 'GCCTCTGACTTCAACTCAAGAAAACACTTTTTTGTTGCTAATGTAATCGGTTTTTGTAATGGCGTCAGCAAATAAAAGGATGCTTATTATTCAAACTTGACTTGTTCTAATTTTTATTGAGCTTTAACAGATTTCATTAGTAGTACAGATCATTGTAATTTAGAATACAGCTATTAATTGGCAACCATTCAACAAGATAGGTTTA' #Site Distance site_distance = 171 prox_cut_start, prox_cut_end = 70, 105 dist_cut_start, dist_cut_end = 70, 105 #One-hot encode the sequences onehot_encoder = iso.OneHotEncoder(len(seq_prox)) onehot_prox, onehot_dist = onehot_encoder(seq_prox), onehot_encoder(seq_dist) print("Non-normalized proximal sum-cut logit = " + str(logit(np.sum(cut_pred_prox[0, prox_cut_start:prox_cut_end])))) print("Non-normalized distal sum-cut logit = " + str(logit(np.sum(cut_pred_dist[0, dist_cut_start:dist_cut_end])))) print("") print("Predicted proximal vs. distal isoform % (APADB) = " + str(iso_pred[0, 0])) plt.title("Normalized proximal cut profile", fontsize=16) plt.yticks(fontsize=14) plt.tight_layout() plt.show() plt.title("Normalized distal cut profile", fontsize=16) plt.yticks(fontsize=14) plt.tight_layout() plt.show()``` ### Output: Non-normalized proximal sum-cut logit = 0.9036148900010471 Non-normalized distal sum-cut logit = 3.738104808277522 Predicted proximal vs. distal isoform % (APADB) = 0.16782887
[{"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-6337.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-6337.jsonl"}, {"idx": "starcoderdata", "domain": "software", "domain2": "", "header_footer": "", "lang": "en", "source": "software-6337.jsonl"}]
polynomials: evaluate --------------------- Let: Let u(o) = 155*o - 35744. Calculate u(240). Answer: 1456 Let: Let i(y) = y**3 + 14*y**2 - 6*y + 14. Give i(-15). Answer: -121 Let: Let p(u) = -11803*u + 224237. What is p(19)? Answer: -20 Let: Let l(z) = -7*z**2 - 40*z - 46. What is l(-2)? Answer: 6 Let: Let y(d) = -d**3 + 618*d**2 + 29837*d - 1326. Calculate y(663). Answer: 0 Let: Let n(z) = -z**3 - 33*z**2 + 131*z - 151. Give n(-37). Answer: 478 Let: Let b(n) = -1525*n + 42908. Give b(28). Answer: 208 Let: Let n(y) = 2*y**2 - 215694*y - 6904255. Calculate n(-32). Answer: 1 Let: Let l(b) = 1575*b - 40943. What is l(26)? Answer: 7 Let: Let j(z) = z**2 - 30. What is j(-7)? Answer: 19 Let: Let l(o) = -476*o - 202312. Give l(-425). Answer: -12 Let: Let q(o) = 1168*o**2 + 279148*o - 950. Calculate q(-239). Answer: 6 Let: Let y(c) = -c**3 - 14*c**2 - 28*c + 24. What is y(-10)? Answer: -96 Let: Let i(d) = -d**2 + 16*d - 18. Give i(13). Answer: 21 Let: Let r(g) = 316*g**2 - 8*g - 9. Give r(-1). Answer: 315 Let: Let p(c) = 25*c + 1. Determine p(2). Answer: 51 Let: Let w(o) = -o**3 + o**2 - 13. Calculate w(0). Answer: -13 Let: Let l(y) = -y**3 - 48*y**2 + 28*y + 2135. Give l(-48). Answer: 791 Let: Let t(y) = 2227*y - 13346. Calculate t(6). Answer: 16 Let: Let x(j) = -14*j**2 + 2*j + 1. Give x(-1). Answer: -15 Let: Let h(p) = -p**3 - 229*p**2 + 11682*p - 3802. What is h(-272)? Answer: 6 Let: Let r(f) = f**2 + 9*f + 3. What is r(-5)? Answer: -17 Let: Let y(q) = q**3 - 2*q**2 + 3. Determine y(3). Answer: 12 Let: Let g(q) = q**2 + 1264*q + 126932. What is g(-110)? Answer: -8 Let: Let y(r) = 186*r + 624. Calculate y(-6). Answer: -492 Let: Let q(p) = -88*p + 915. Give q(18). Answer: -669 Let: Let w(o) = o + 46. What is w(0)? Answer: 46 Let: Let n(f) = -4*f - 17. Determine n(8). Answer: -49 Let: Let w(h) = -h. Give w(-13). Answer: 13 Let: Let w(k) = -5*k - 61. Calculate w(-12). Answer: -1 Let: Let i(n) = n**3 + 74*n**2 - 11187*n - 1374. Determine i(-149). Answer: 414 Let: Let j(n) = n**3 + 36*n**2 + 80*n + 16. What is j(-35)? Answer: -1559 Let: Let k(s) = 3*s**3 - 4*s - 3. Determine k(-1). Answer: -2 Let: Let c(p) = 57*p**2 + 232*p + 8. Calculate c(-4). Answer: -8 Let: Let l(z) = -63*z - 10341. Calculate l(-164). Answer: -9 Let: Let w(h) = -8*h**3 + 137*h**2 - 19*h + 41. What is w(17)? Answer: 7 Let: Let h(p) = -350*p - 1961. Determine h(-6). Answer: 139 Let: Let h(o) = 55*o**2 - o + 1. Give h(1). Answer: 55 Let: Let m(s) = -s**2 + 10*s - 44. Give m(16). Answer: -140 Let: Let t(l) = -28132*l - 309532. Give t(-11). Answer: -80 Let: Let h(u) = 37718*u**2 + 339459*u - 33. Determine h(-9). Answer: -6 Let: Let c(h) = -12*h**2 + 15*h - 45. Determine c(4). Answer: -177 Let: Let m(j) = 9*j + 378. Calculate m(-33). Answer: 81 Let: Let c(f) = 2263*f**2 + 529561*f + 4445. Calculate c(-234). Answer: -1 Let: Let j(q) = -q**3 - 27*q**2 + 56*q - 62. Determine j(-29). Answer: -4 Let: Let h(d) = 7*d**3 + 74*d**2 + 95*d - 23. Give h(-9). Answer: 13 Let: Let i(r) = r**3 - 28*r**2 - 50*r + 108. Give i(30). Answer: 408 Let: Let d(n) = -5*n**3 - 5*n**2 + 4. Determine d(1). Answer: -6 Let: Let j(p) = p**3 + 172*p**2 + 3051*p - 8638. Give j(-23). Answer: 10 Let: Let n(z) = -2*z**3 - 38*z**2 - 564*z - 10637. Give n(-19). Answer: 79 Let: Let t(g) = 12*g**3 + 313*g**2 - 1467*g - 38811. Calculate t(-26). Answer: 7 Let: Let h(v) = -21*v - 2. Give h(-1). Answer: 19 Let: Let k(u) = -2*u**2 + u - 1. Determine k(-4). Answer: -37 Let: Let y(s) = 2*s**3 + 653*s**2 + 11395*s - 315. What is y(-308)? Answer: -7 Let: Let f(n) = -10*n + 69. Determine f(25). Answer: -181 Let: Let v(w) = -w**3 + 3*w**2 + 383*w + 5067. Calculate v(0). Answer: 5067 Let: Let d(t) = 47*t**2 - 2671*t - 435. Determine d(57). Answer: 21 Let: Let y(k) = 52870*k + 581525. What is y(-11)? Answer: -45 Let: Let d(a) = -4303*a - 90354. What is d(-21)? Answer: 9 Let: Let l(q) = q**2 - 8*q + 15. What is l(7)? Answer: 8 Let: Let i(c) = c**3 + 286*c**2 + 13218*c - 348. Give i(-58). Answer: 0 Let: Let x(k) = -7*k**2 + 102*k + 164. Calculate x(16). Answer: 4 Let: Let y(t) = -17*t - 1. Calculate y(1). Answer: -18 Let: Let b(u) = 3325*u - 256032. Determine b(77). Answer: -7 Let: Let p(r) = -703069*r + 3515360. Give p(5). Answer: 15 Let: Let u(f) = -f**3 + f**2 + 69*f + 202. Calculate u(10). Answer: -8 Let: Let w(y) = y**2 + 259*y - 28299. Determine w(83). Answer: 87 Let: Let l(c) = 2*c**2 - 32*c + 97. Give l(10). Answer: -23 Let: Let k(j) = 4*j**3 + 15*j**2 - 13*j + 45. Determine k(-13). Answer: -6039 Let: Let m(i) = -6*i - 14. Calculate m(-9). Answer: 40 Let: Let o(j) = -62910*j + 4655325. Determine o(74). Answer: -15 Let: Let n(i) = 410*i - 241072. Determine n(588). Answer: 8 Let: Let i(n) = 172*n + 960. What is i(-20)? Answer: -2480 Let: Let h(d) = 2*d**3 + 5*d**2 - 30*d - 9. Calculate h(-7). Answer: -240 Let: Let p(l) = -l**2 + 57*l + 862. What is p(71)? Answer: -132 Let: Let w(m) = m**2 - 155*m - 3516. Calculate w(-20). Answer: -16 Let: Let c(d) = 7*d**2 - 30*d - 62. Determine c(-2). Answer: 26 Let: Let q(r) = 3*r + 10. Give q(-7). Answer: -11 Let: Let b(i) = -179*i**3 + 4543*i**2 - 1707*i + 173. What is b(25)? Answer: -2 Let: Let x(f) = f**3 - 1007*f**2 + 96*f - 96671. Give x(1007). Answer: 1 Let: Let w(q) = 930*q - 2042. What is w(3)? Answer: 748 Let: Let x(i) = 148*i - 2239. Determine x(27). Answer: 1757 Let: Let a(y) = -172*y + 3956. What is a(23)? Answer: 0 Let: Let a(o) = o**2 + 1024*o + 25021. Calculate a(-25). Answer: 46 Let: Let m(s) = -s**2 + 1655*s + 537295. Give m(-278). Answer: -79 Let: Let d(f) = f**3 - 113*f**2 - 346*f - 207. Calculate d(116). Answer: 25 Let: Let o(y) = 3*y + 89. Give o(-31). Answer: -4 Let: Let c(p) = p**3 - 8*p**2 + 6*p - 22. Calculate c(6). Answer: -58 Let: Let u(s) = 360*s - 12810. Calculate u(36). Answer: 150 Let: Let j(a) = -a**3 - 2*a - 115. Calculate j(0). Answer: -115 Let: Let o(n) = 3*n - 1. What is o(8)? Answer: 23 Let: Let r(l) = 4*l**2 + 268*l + 3716. Determine r(-48). Answer: 68 Let: Let w(n) = -16097*n - 16083. Determine w(-1). Answer: 14 Let: Let v(k) = 22*k + 86. Calculate v(-4). Answer: -2 Let: Let q(w) = 16*w - 1315. What is q(82)? Answer: -3 Let: Let t(g) = 2*g**2 - 11*g + 18. Give t(5). Answer: 13 Let: Let d(j) = -30*j**2 - 8*j - 13. What is d(-3)? Answer: -259 Let: Let v(s) = 26*s - 125. Calculate v(5). Answer: 5 Let: Let o(y) = 86*y - 5937. Give o(68). Answer: -89 Let: Let z(f) = -f**3 + 8*f**2 + 80*f + 24. Calculate z(15). Answer: -351 Let: Let v(i) = -19*i**3 + 22*i**2 - 4*i + 1. Determine v(2). Answer: -71 Let: Let g(u) = -20*u - 1. Determine g(-3). Answer: 59 Let: Let h(j) = -29*j - 622. Give h(-16). Answer: -158 Let: Let j(v) = v**3 - 7*v**2 + 15*v - 10. What is j(4)? Answer: 2 Let: Let v(h) = -3*h + 23. Give v(9). Answer: -4 Let: Let a(i) = 28*i**3 + 364*i**2 - 88*i - 1134. Calculate a(-13). Answer: 10 Let: Let l(s) = 2*s**3 - 9*s**2 + 20*s - 67. Give l(4). Answer: -3 Let: Let q(t) = 1206*t + 437778. Determine q(-363). Answer: 0 Let: Let x(i) = 19*i - 93. Determine x(7). Answer: 40 Let: Let q(t) = 41*t**3 + t**2 + t - 1. Give q(1). Answer: 42 Let: Let m(r) = r**3 + 10*r**2 + 10*r + 6. Determine m(-9). Answer: -3 Let: Let k(x) = 2*x**3 + 179*x**2 + 850*x + 27. Calculate k(-5). Answer: 2 Let: Let r(m) = 2049*m + 168021. What is r(-82)? Answer: 3 Let: Let w(t) = -t**2 - 719*t - 102815. Determine w(-522). Answer: 19 Let: Let n(c) = 18*c - 15. Determine n(6). Answer: 93 Let: Let w(o) = 787*o**2 - 131*o - 127. Calculate w(-1). Answer: 791 Let: Let s(i) = -i**3 + 4*i**2 + 3*i + 14. What is s(6)? Answer: -40 Let: Let s(z) = -8*z**2 + 3*z - 2. Give s(1). Answer: -7 Let: Let y(c) = 29*c - 48. Give y(10). Answer: 242 Let: Let s(m) = -4*m**3 + 46*m**2 - 902*m + 6321. Calculate s(8). Answer: 1 Let: Let t(i) = i**3 - 142*i**2 + 2339*i - 246. Calculate t(123). Answer: 0 Let: Let l(z) = -984*z + 62095. What is l(63)? Answer: 103 Let: Let t(m) = -4*m**2 + 22*m. What is t(6)? Answer: -12 Let: Let t(n) = -203*n - 10. Determine t(-1). Answer: 193 Let: Let g(v) = 6*v**2 + v - 7. Determine g(3). Answer: 50 Let: Let t(n) = 56*n + 792. Determine t(-14). Answer: 8 Let: Let m(n) = 3*n**3 + 199*n**2 - 2326*n + 18. Determine m(10). Answer: -342 Let: Let k(g) = -8*g**2 - 150*g + 20. Calculate k(-16). Answer: 372 Let: Let x(z) = -z**3 + z - 30. What is x(0)? Answer: -30 Let: Let d(c) = -384*c**2 - 375*c + 9. Determine d(-1). Answer: 0 Let: Let l(m) = m**3 - 16*m**2 + 63*m - 82. Give l(3). Answer: -10 Let: Let c(l) = -6*l**3 + 4*l - 9. Determine c(2). Answer: -49 Let: Let d(q) = 108*q - 866. What is d(8)? Answer: -2 Let: Let u(h) = -2*h**3 - 9*h**2 + 21*h + 218. Determine u(-7). Answer: 316 Let: Let t(f) = -2*f**2 + 12930*f + 25865. Determine t(-2). Answer: -3 Let: Let p(f) = -284*f**2 - 1973*f - 1406. Determine p(-6). Answer: 208 Let: Let h(j) = j**3 - 8*j**2 - 7*j + 5. What is h(4)? Answer: -87 Let: Let r(v) = -3*v + 6. What is r(6)? Answer: -12 Let: Let m(k) = k**3 + 4*k**2 - 1668*k - 6689. Determine m(-4). Answer: -17 Let: Let v(b) = -2*b**2 - 226*b + 61688. What is v(128)? Answer: -8 Let: Let w(z) = 6*z**2 + 102*z - 129. What is w(-19)? Answer: 99 Let: Let c(x) = 17*x**3 + 221*x + 222. Give c(-1). Answer: -16 Let: Let d(g) = -82*g - 733. Give d(-9). Answer: 5 Let: Let b(i) = -i**3 - 7*i**2 - 7*i + 47. Calculate b(-7). Answer: 96 Let: Let y(c) = -171*c + 2412. What is y(12)? Answer: 360 Let: Let x(s) = s**2 + 144*s + 967. Determine x(-145). Answer: 1112 Let: Let m(j) = -8*j - 58. What is m(-7)? Answer: -2 Let: Let q(l) = l**3 + 5*l**2 + 2*l + 8. What is q(-5)? Answer: -2 Let: Let r(a) = 15*a**2 + 321*a - 2467. Calculate r(6). Answer: -1 Let: Let c(j) = j**3 + 18*j**2 + 43*j - 36. Determine c(-15). Answer: -6 Let: Let r(k) = -k - 34. What is r(0)? Answer: -34 Let: Let g(k) = k**2 - 69*k + 573. What is g(10)? Answer: -17 Let: Let z(t) = t + 7. Calculate z(-2). Answer: 5 Let: Let o(a) = -14*a + 23. What is o(2)? Answer: -5 Let: Let m(w) = 172*w - 7922. Determine m(46). Answer: -10 Let: Let l(a) = 36*a**2 + 83*a + 281. What is l(-3)? Answer: 356 Let: Let c(z) = 8*z**2 + 109*z - 132. Determine c(-14). Answer: -90 Let: Let y(n) = 107*n + 2347. What is y(-22)? Answer: -7 Let: Let u(q) = -275*q - 1750. What is u(-4)? Answer: -650 Let: Let a(g) = 2*g**2 + 17*g + 10. What is a(-7)? Answer: -11 Let: Let y(a) = -98*a**2 - 11650*a + 1423. Give y(-119). Answer: -5 Let: Let u(v) = -v**3 - 18*v**2 - 34*v - 48. What is u(-16)? Answer: -16 Let: Let q(f) = -396117*f + 792235. Give q(2). Answer: 1 Let: Let v(h) = -h**2 + 13*h - 8. Calculate v(11). Answer: 14 Let: Let x(b) = -b**2 + 1786*b - 49211. Give x(28). Answer: 13 Let: Let r(o) = -o**3 - 126*o**2 + 167*o + 5087. Give r(-127). Answer: 7 Let: Let p(y) = y**2 + 4125*y + 766352. What is p(-195)? Answer: 2 Let: Let h(u) = 37*u**3 + u**2 + 2*u. Calculate h(-1). Answer: -38 Let: Let x(z) = 3*z + 4. Determine x(9). Answer: 31 Let: Let y(l) = -4*l + 6. Give y(4). Answer: -10 Let: Let j(q) = 11*q - 124. Determine j(-15). Answer: -289 Let: Let l(c) = c + 1. Determine l(3). Answer: 4 Let: Let y(i) = -191*i + 57668. What is y(300)? Answer: 368 Let: Let v(b) = -7*b. Give v(17). Answer: -119 Let: Let y(p) = -3*p**3 + 14*p**2 + 12*p + 6. Determine y(6). Answer: -66 Let: Let l(b) = -443*b + 39915. What is l(90)? Answer: 45 Let: Let m(f) = -f**3 - 138*f**2 - 227*f - 12334. Calculate m(-137). Answer: -4 Let: Let o(j) = 26*j - 344. Determine o(20). Answer: 176 Let: Let y(u) = -8*u - 132. What is y(-17)? Answer: 4 Let: Let q(w) = -11*w**3 - 172*w**2 + 34*w - 221. Determine q(-15). Answer: -2306 Let: Let t(r) = 164*r + 18846. Determine t(-118). Answer: -506 Let: Let g(k) = 35*k. What is g(-2)? Answer: -70 Let: Let l(k) = 55*k + 657. Determine l(-4). Answer: 437<|endoftext|>numbers: round number --------------------- Problem: Round 265.034 to the nearest integer. A.: 265 Problem: Round -0.01871128 to four decimal places. A.: -0.0187 Problem: What is 39.45 rounded to 0 decimal places? A.: 39 Problem: What is 56.967574 rounded to the nearest ten? A.: 60 Problem: What is -2833 rounded to the nearest one hundred? A.: -2800 Problem: What is 1895693.542 rounded to the nearest 10? A.: 1895690 Problem: What is -3133000 rounded to the nearest 100000? A.: -3100000 Problem: What is -0.91781 rounded to three decimal places? A.: -0.918 Problem: Round 0.057105 to four dps. A.: 0.0571 Problem: Round -148.5 to the nearest ten. A.: -150 Problem: Round -6.30716 to three dps. A.: -6.307 Problem: What is 0.000005944 rounded to 6 decimal places? A.: 0.000006 Problem: What is 3078.888 rounded to zero dps? A.: 3079 Problem: Round -1.20753 to 3 dps. A.: -1.208 Problem: What is 0.3595063 rounded to 2 dps? A.: 0.36 Problem: Round -2556.2 to the nearest one hundred. A.: -2600 Problem: Round -0.00000444693 to six dps. A.: -0.000004 Problem: Round 0.00007229 to five decimal places. A.: 0.00007 Problem: Round 0.000001363 to six decimal places. A.: 0.000001 Problem: Round 0.003718150695 to 6 dps. A.: 0.003718 Problem: Round -0.00016185 to six decimal places. A.: -0.000162 Problem: Round 0.000014322 to 6 dps. A.: 0.000014 Problem: Round -0.01029089144 to five decimal places. A.: -0.01029 Problem: Round -24891113200 to the nearest one hundred thousand. A.: -24891100000 Problem: What is -0.25317309 rounded to 4 dps? A.: -0.2532 Problem: Round -99.790894 to one dp. A.: -99.8 Problem: Round -0.009232 to 3 decimal places. A.: -0.009 Problem: What is -1.0060189 rounded to one decimal place? A.: -1 Problem: Round -0.000016386 to 6 decimal places. A.: -0.000016 Problem: What is -1380900 rounded to the nearest 100000? A.: -1400000 Problem: Round -0.8234834 to 1 dp. A.: -0.8 Problem: What is 14992.9252 rounded to the nearest one thousand? A.: 15000 Problem: Round 37600 to the nearest 100000. A.: 0 Problem: What is 0.003337037 rounded to five decimal places? A.: 0.00334 Problem: Round 772058 to the nearest one hundred thousand. A.: 800000 Problem: What is 957121.625 rounded to the nearest one hundred thousand? A.: 1000000 Problem: What is -0.0038301 rounded to 4 decimal places? A.: -0.0038 Problem: What is -10966.819 rounded to the nearest 1000? A.: -11000 Problem: What is -107110 rounded to the nearest 1000? A.: -107000 Problem: What is 590.362 rounded to the nearest 10? A.: 590 Problem: What is -796819.82 rounded to the nearest 100000? A.: -800000 Problem: What is 1287.3 rounded to the nearest ten? A.: 1290 Problem: What is -0.003255988 rounded to six dps? A.: -0.003256 Problem: What is -0.01763233 rounded to four decimal places? A.: -0.0176 Problem: What is -0.000662843 rounded to 6 decimal places? A.: -0.000663 Problem: Round 5.8006 to one dp. A.: 5.8 Problem: Round -1591.285019 to 1 decimal place. A.: -1591.3 Problem: What is 1.209372 rounded to two dps? A.: 1.21 Problem: What is -0.00001870965238 rounded to 6 decimal places? A.: -0.000019 Problem: Round -783014.1 to the nearest 1000. A.: -783000 Problem: Round 2104742.35 to the nearest ten thousand. A.: 2100000 Problem: What is -0.1040866 rounded to three decimal places? A.: -0.104 Problem: What is 0.01263923 rounded to four decimal places? A.: 0.0126 Problem: Round 20.6 to the nearest 100. A.: 0 Problem: Round 406028300 to the nearest one million. A.: 406000000 Problem: What is -0.00000040622 rounded to seven dps? A.: -0.0000004 Problem: Round 0.024983 to 3 decimal places. A.: 0.025 Problem: Round -261644875 to the nearest ten thousand. A.: -261640000 Problem: What is -4.4437017 rounded to the nearest integer? A.: -4 Problem: What is -263.36 rounded to the nearest 100? A.: -300 Problem: What is -0.2419976599 rounded to 2 decimal places? A.: -0.24 Problem: Round 5954.7286 to the nearest ten. A.: 5950 Problem: What is -1365560 rounded to the nearest 100000? A.: -1400000 Problem: What is 4648970.12 rounded to the nearest 1000? A.: 4649000 Problem: What is 41298.425 rounded to the nearest 10? A.: 41300 Problem: Round 1860.9236 to the nearest integer. A.: 1861 Problem: Round 40.71 to zero decimal places. A.: 41 Problem: Round -8.3537 to the nearest integer. A.: -8 Problem: Round -23769954 to the nearest 1000000. A.: -24000000 Problem: Round 1285717 to the nearest 100000. A.: 1300000 Problem: Round -432987.6 to the nearest one thousand. A.: -433000 Problem: Round -0.18195513 to two dps. A.: -0.18 Problem: Round -0.340974 to 3 dps. A.: -0.341 Problem: Round -0.891449 to one decimal place. A.: -0.9 Problem: What is 0.402 rounded to 1 dp? A.: 0.4 Problem: Round -0.013045981 to 6 decimal places. A.: -0.013046 Problem: Round 0.03889980179 to six dps. A.: 0.0389 Problem: Round -30610 to the nearest 1000. A.: -31000 Problem: Round -0.0000040027 to 6 decimal places. A.: -0.000004 Problem: What is -38700900 rounded to the nearest 100000? A.: -38700000 Problem: Round 0.00003219 to six dps. A.: 0.000032 Problem: What is -0.44913 rounded to 2 dps? A.: -0.45 Problem: What is 5593.0259 rounded to the nearest 100? A.: 5600 Problem: Round -0.49566 to two decimal places. A.: -0.5 Problem: Round -0.1423109859 to four decimal places. A.: -0.1423 Problem: Round 27268.6 to the nearest one thousand. A.: 27000 Problem: What is 176788164880 rounded to the nearest one million? A.: 176788000000 Problem: What is -0.000020561 rounded to 7 dps? A.: -0.0000206 Problem: What is -0.14486139 rounded to four dps? A.: -0.1449 Problem: What is 0.002017 rounded to four dps? A.: 0.002 Problem: What is -459.62701 rounded to the nearest ten? A.: -460 Problem: What is -0.000088198 rounded to five decimal places? A.: -0.00009 Problem: Round -2083842.9 to the nearest one thousand. A.: -2084000 Problem: What is 0.051433 rounded to 4 dps? A.: 0.0514 Problem: What is 8760730 rounded to the nearest 1000000? A.: 9000000 Problem: Round -0.0000151383 to seven decimal places. A.: -0.0000151 Problem: Round 0.0009900405 to five dps. A.: 0.00099 Problem: What is -6411.8814 rounded to the nearest one thousand? A.: -6000 Problem: Round -115332.14 to the nearest one thousand. A.: -115000 Problem: What is -0.001072 rounded to 4 dps? A.: -0.0011 Problem: Round -0.000052369 to 7 decimal places. A.: -0.0000524 Problem: What is -615849 rounded to the nearest 10000? A.: -620000 Problem: Round -0.000035 to five dps. A.: -0.00004 Problem: What is 8393.1916 rounded to the nearest 100? A.: 8400 Problem: Round 0.00012180507426 to five decimal places. A.: 0.00012 Problem: What is 11742596.31 rounded to the nearest one million? A.: 12000000 Problem: Round -589.5226 to the nearest 100. A.: -600 Problem: What is 689.3152 rounded to 1 dp? A.: 689.3 Problem: What is 0.000009057127 rounded to seven decimal places? A.: 0.0000091 Problem: Round -5552.709 to the nearest ten. A.: -5550 Problem: Round 236402415.9 to the nearest 1000000. A.: 236000000 Problem: What is -0.000023942 rounded to six dps? A.: -0.000024 Problem: Round -2254925.75 to the nearest one hundred. A.: -2254900 Problem: Round -0.008008126428 to five dps. A.: -0.00801 Problem: What is 3906878 rounded to the nearest ten thousand? A.: 3910000 Problem: Round 5.7529425 to 1 decimal place. A.: 5.8 Problem: What is 2626000 rounded to the nearest one hundred thousand? A.: 2600000 Problem: What is 0.0000597982 rounded to six dps? A.: 0.00006 Problem: What is -6.78 rounded to 1 decimal place? A.: -6.8 Problem: What is 122 rounded to the nearest 10? A.: 120 Problem: Round 4.19473 to the nearest integer. A.: 4 Problem: What is -429910 rounded to the nearest one million? A.: 0 Problem: What is 154.6636 rounded to zero decimal places? A.: 155 Problem: Round -15299 to the nearest 100. A.: -15300 Problem: Round -0.00317005 to 3 decimal places. A.: -0.003 Problem: What is 0.0086796 rounded to three dps? A.: 0.009 Problem: Round 1651.70712 to the nearest one hundred. A.: 1700 Problem: What is 0.00440121367 rounded to five dps? A.: 0.0044 Problem: What is 867280 rounded to the nearest ten thousand? A.: 870000 Problem: Round 0.00050228 to 6 dps. A.: 0.000502 Problem: Round -4.734 to 1 dp. A.: -4.7 Problem: What is -129.6354 rounded to the nearest 10? A.: -130 Problem: What is -816.3849499 rounded to zero dps? A.: -816 Problem: What is -32966296.32 rounded to the nearest 10000? A.: -32970000 Problem: What is 576000 rounded to the nearest one hundred thousand? A.: 600000 Problem: What is -0.500624 rounded to 3 decimal places? A.: -0.501 Problem: Round -0.000142844 to 7 dps. A.: -0.0001428 Problem: Round -0.000169 to 4 decimal places. A.: -0.0002 Problem: Round -21801000 to the nearest one million. A.: -22000000 Problem: What is -7.27 rounded to 1 decimal place? A.: -7.3 Problem: What is -122167700 rounded to the nearest one million? A.: -122000000 Problem: Round -500.1 to the nearest 100. A.: -500 Problem: Round 1290 to the nearest 1000. A.: 1000 Problem: Round -3954.804304 to 1 dp. A.: -3954.8 Problem: Round -0.0013865171 to six dps. A.: -0.001387 Problem: What is -35.2385 rounded to the nearest ten? A.: -40 Problem: Round -0.0000912735319 to 7 dps. A.: -0.0000913 Problem: What is 0.005843 rounded to 3 dps? A.: 0.006 Problem: What is -2.983051 rounded to one dp? A.: -3 Problem: Round 409700 to the nearest ten thousand. A.: 410000 Problem: Round -0.144945572 to two decimal places. A.: -0.14 Problem: Round -0.00004658384 to 7 decimal places. A.: -0.0000466 Problem: Round 217584.1 to the nearest 100. A.: 217600 Problem: Round -434.934 to the nearest one hundred. A.: -400 Problem: Round -267719626 to the nearest 100000. A.: -267700000 Problem: What is -0.0170612 rounded to 3 decimal places? A.: -0.017 Problem: What is 5185416360 rounded to the nearest 100000? A.: 5185400000 Problem: Round -0.26329717 to three decimal places. A.: -0.263 Problem: Round 0.0000205 to 6 decimal places. A.: 0.000021 Problem: Round 0.00461 to 3 dps. A.: 0.005 Problem: Round -0.01271041819 to 6 decimal places. A.: -0.01271 Problem: What is 7917900 rounded to the nearest one hundred thousand? A.: 7900000 Problem: Round -0.00038482 to 5 dps. A.: -0.00038 Problem: What is -10100.16 rounded to the nearest 10? A.: -10100 Problem: Round -0.00003152 to 5 dps. A.: -0.00003 Problem: What is -45667000 rounded to the nearest one hundred thousand? A.: -45700000 Problem: What is 0.0085816 rounded to 5 decimal places? A.: 0.00858 Problem: Round -1742088 to the nearest one thousand. A.: -1742000 Problem: Round -4.115626 to 1 decimal place. A.: -4.1 Problem: What is -193000 rounded to the nearest 10000? A.: -190000 Problem: What is -0.1553361258 rounded to four dps? A.: -0.1553 Problem: What is -4.7728 rounded to the nearest integer? A.: -5 Problem: Round -185.14 to the nearest 10. A.: -190 Problem: Round -701.6119761 to 2 dps. A.: -701.61 Problem: What is -384.206 rounded to the nearest integer? A.: -384 Problem: Round 6907.12847 to the nearest one thousand. A.: 7000 Problem: Round 1.48736941 to 1 decimal place. A.: 1.5 Problem: What is -0.077501 rounded to 3 decimal places? A.: -0.078 Problem: Round -84.8961883 to zero decimal places. A.: -85 Problem: Round -333454.81 to the nearest one hundred. A.: -333500 Problem: Round 0.1683846476 to 5 decimal places. A.: 0.16838 Problem: Round -57.553958 to 1 decimal place. A.: -57.6 Problem: Round -0.00442 to 4 dps. A.: -0.0044 Problem: Round -0.02859944122 to six dps. A.: -0.028599 Problem: What is -79486.1 rounded to the nearest 10000? A.: -80000 Problem: Round 0.218761383 to 1 decimal place. A.: 0.2 Problem: What is 0.004097 rounded to 4 decimal places? A.: 0.0041 Problem: Round 3.8116952 to two dps. A.: 3.81
[{"idx": "txt360/polynomials__evaluate_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-6.jsonl"}, {"idx": "txt360/numbers__round_number_train", "domain": "math", "domain2": "", "header_footer": "", "lang": "en", "source": "math-6.jsonl"}]
Find basis of intersection of 2 spans with unequal dimensions Question: I've been stuck on this question for quite a while: Given $U =$ span $\left\{ \begin{pmatrix} 0\\ 2\\ 0\\ 0 \end{pmatrix}, \begin{pmatrix} 1\\ 0\\ 0\\ 0 \end{pmatrix}, \begin{pmatrix} 2\\ 1\\ 3\\ 7 \end{pmatrix} \right\} $ and $W =$ span $\left\{ \begin{pmatrix} 1\\ 0\\ 3\\ 0 \end{pmatrix}, \begin{pmatrix} 0\\ 1\\ -3\\ 7 \end{pmatrix} \right\} $, find a basis for $U \cap W$. Now, I've tried writing general $u \in U, w \in W$ and then setting $u=w$ and finding a general solution using Gaussian elimination. However, because the linear equation system $u=w$ has 5 variables and not 4, my attempts were unsuccessful. I also tried looking for similar questions on this site, however every question I found had dim$U$=dim$W$ which is not the case here. Any help will be appreciated, thanks in advance! Comment: The five entries you get, three of them are coefficients of the three vectors spanning $U$, and two are coefficients of the two vectors spanning $W$, and either way they give you the $4$-tuples in the intersection. Comment: Your $u=w$ approach yields four equations in five variables – what's wrong with that? Comment: @GerryMyerson The solution I get has 5 elements, but the vectors in the basis need to have 4 Answer: I would solve this problem by finding a homogenous system of linear equations describing $W$, and the same for $U$. Then $U \cap W$ would be described by the homogenous system of linear equations consisting of both the equations describing $W$ and $U$. Then you could go about and solve this system of linear equations, thus obtaining a basis for the desired vector space. By converting the span to a homogenous system of linear equations I mean doing the following: Let $u \in U$, denote $u = \begin{pmatrix}x_1\\x_2\\x_3\\x_4\end{pmatrix}$ then of course $u \in U$ if and only if the system $$\begin{pmatrix}0\;\;\;\;1\;\;\;\;2\\2\;\;\;\;0\;\;\;\;1\\0\;\;\;\;0\;\;\;\;3\\0\;\;\;\;0\;\;\;\;7\end{pmatrix} \begin{pmatrix}\lambda_1\\\lambda_2\\\lambda_3\\\end{pmatrix}=\begin{pmatrix}x_1\\x_2\\x_3\\x_4\end{pmatrix}$$ Has a solution. This logic will lead you towards getting a homogenous system a linear equation describing $U$. Hope this helps! Answer: The most comfortable situation when you want to compute an intersection of two subspaces is when one of them is given by linear equation(s) and the other one by parametrization, and when there are the least possible equations and parameters. Here, the equation of the hyperplane $U$ is $$\det\begin{pmatrix}0&1&2&x\\2&0&1&y\\0&0&3&z\\0&0&7&t\end{pmatrix}=0,$$i.e. $$7z-3t=0.$$ So, an arbitrary vector of $W,$ $$\begin{pmatrix} a\\ b\\ 3a-3b\\ 7b \end{pmatrix},$$ also belongs to $U$ iff $$7(3a-3b)-3(7b)=0,$$ i.e. $a=2b.$ This proves that $U\cap W$ is the set of vectors of the form $$\begin{pmatrix} 2b\\ b\\ 3(2b)-3b\\ 7b \end{pmatrix}.$$ A basis for this line is made of the single vector $$\begin{pmatrix} 2\\ 1\\3\\ 7 \end{pmatrix}.$$ If you chose to flip the roles of the two subspaces, you would have 2 equations for $W$ and 3 parameters for $U,$ which would be less tractable.<|endoftext|>How to calculate the unknown quantity in an infinite series? Question: I'd like to calculate x value in this equation. Basically, I tried to 2 types of method which are FindRoot and NSolve. But, I have failed the calculation caused by these errors up to now. If there is anyone who knows this problems, plz let me know what I should do first! Thank you for your cooperation. Comment: Please post code, not images. Or include images, but as a complement. Answer: There are a few problems with your code. Allow me to highlight them and guide you to a solution. First of all, the proper way to define a function in Mathematica is using <code>:=</code>. So your code should read <code>F[x_] := NSum[Exp[-x BesselJZero[0, a]^2]/BesselJZero[0, a]^2, {a, 1, Infinity}] </code> Furthermore, you should note that the zeroes of the Bessel function are increasing as <code>a</code> gets larger. Since you squaring and then taking a negative exponential, the terms in your series will rapidly decay and calculating only a finite number of terms will suffice. Therefore, you could also use the function <code>F2[x_, maxOrder_] := NSum[Exp[-x BesselJZero[0, a]^2]/BesselJZero[0, a]^2, {a, 1, maxOrder}] </code> and play with the <code>maxOrder</code> parameter. (In fact, for <code>x</code> equal to one the third term in the series equals <code>4.00479*10^-35</code>, which is smaller than machine precision, so a very low number of terms suffices). This will save you a lot of computing time. Now, the error messages (at least the ones that say <code>... is not numerical ...</code>) that you receive have another origin, which can be found here: What are the most common pitfalls awaiting new users?. In short, the problem is that the first step in the <code>FindRoot</code> algorithm is to evaluate the function symbolically, i.e. for an arbitrary <code>x</code>. You can turn this off by explicitly demanding the argument of your function to be numeric, like this: <code>F3[x_?NumericQ, maxOrder_] := NSum[Exp[-x BesselJZero[0,a]^2]/BesselJZero[0, a]^2, {a, 1, maxOrder}] </code> The last point is that, as long as <code>x</code> is real, you are summing positive quantities and trying to equate them to something negative. When using a positive number: <code>FindRoot[F3[x, 5] == 0.014, {x, 0}] </code> Mathematica quickly finds the solution as {x -> 0.434665} When you want the right-hand side of your equation to be negative, you should solve for <code>x</code> in the complex domain. In that case, I would suggest to split it into its real and imaginary parts, write <code>z=x+I y</code> and use for instance <code>FindRoot[{Re[F3[x + I y, 5]] + 0.014,Im[F3[x + I y, 5]]}, {{x, 0.1}, {y, 0.1}}] </code> which gives {x -> 0.434665, y -> 0.543228} Comment: In the second line of the question, a solution of `F[x]=-0.014` is sought. However, since `F[x]` is positive for real `x`, such a solution does not exist in the Reals. In the last coding example, I tried to explain how to look for such a solution in the complex plane. `Re[F[z]]==-0.014` is equivalent to `Re[F[x]]+0.014==0`, hence the +0.014 in the last example. Comment: 0.014 ? -0.014?<|endoftext|>AngularJS, How to get the value from input and place it in a factory? Question: I am trying to do the exact same thing like this guy: How to send data from input to service? ,and I did copy/paste every offered solution, but I couldnt manage to make it work. Here is my starting point, when I write the code like this, it works fine: <code>var town="London"; //factory scotchApp.factory('forecastBG', ['$ http', function($ http) { return $ http.get(' [IDX] + town + '&units=metric&appid=bd82977b86bf27fb59a04b61b657fb6f') .success(function(data) { return data; }) .error(function(err) { return err; }); }]); //controller scotchApp.controller('beograd', ['$scope', 'forecastBG', function($scope, forecastBG) { forecastBG.success(function(data) { $scope.fiveDay = data; }); }]); //view <div class="forecast"> <div ng-controller="beograd" class="first"> <p></p> <p style="font-size: 130%"> City </p> <p style="font-size: 130%">{{ fiveDay['list'][0].main.temp }}&degC</p> <p> Wind: {{ fiveDay['list'][0].wind.speed }} m/s</p> <p> Pressure: {{ fiveDay['list'][0].main.pressure }}hpa</p> <p> Humidity: {{ fiveDay['list'][0].main.humidity }}%</p> <p style="font-size: 90%"> Min. temp.: {{ fiveDay['list'][0].main.temp_min }}&degC</p> <p style="font-size: 90%"> Max. temp.: {{ fiveDay['list'][0].main.temp_max }}&degC</p> <p style="font-size: 90%"> {{ fiveDay['list'][0]['weather'][0].description }}</p> </div> </div> </code> Now, I am trying to think of a way to get the value from an input field, pass that value into var town, and then refresh the view with the new info, with a single button click. The idea is to make it possible for users to search and get the info for any city available on this API. Please help, I am gonna go nuts with trying to make this work, and I am very new to angular. Answer: A few parts - first you need to make your factory return a callable function that takes <code>town</code> as a param (also going to use <code>.then</code> to return a promise): <code>scotchApp.factory('forecastBG', ['$ http', function($ http) { return { getWeatherForTown: function(town) { return $ http.get(' [IDX] + town + '&units=metric&appid=bd82977b86bf27fb59a04b61b657fb6f') .then(function(result) { return result.data; }) } } }]); </code> Now, make a controller function to handle your click event and call your factory: <code>$scope.getWeather = function(town) { forecastBG.getWeatherForTown(town).then(function(data) { $scope.fiveDay = data; }); } </code> And update the view to call this method and pass in your <code>input</code> model: <code><input type="text" ng-model="townToSearchFor" /> <button ng-click="getWeather(townToSearchFor)" ng-disabled="!townToSearchFor">Get Weather!</button> </code> Comment: Sir, words cannot express how grateful I am for this answer.<|endoftext|>Infinite sum of 1/sin^2 and theta function Question: In studying some physical propagator, I came across the following sum $$ \sum_{n = -\infty}^{+\infty} \frac{ a^n }{ \sin^2(z + n \pi \tau) }\ . $$ Obviously, my question is how to evaluate this sum. To some extent, I understand the result when $a = 1$. Loosely speaking, without properly regularizing, we have $$ \sum_{n \in \mathbb{Z}} \frac{ 1 }{ \sin^2(z + n \pi \tau) } = - \sum_{n \in \mathbb{Z}} \partial_z \partial_z \ln \sin(z + n\pi\tau) = - \partial_z^2 \ln \prod_{n \in \mathbb{Z}} \sin(z+n\pi\tau) \ . $$ The final infinite product can be identified with $\theta_1(z/\pi|\tau)$, where $q = e^{2\pi i \tau}$, so up to regularization issue, we have $$ \sum_{n\in \mathbb{Z}} \frac{ 1 }{ sin^2(z + n\pi \tau) } = - \partial_z \partial_z \ln \theta_1(z/\pi|\tau) $$ However in the presence of $a^n$, I can't pull off this trick again (as far as I can see). Suggestions on literature/references and more tricks are welcome! Comment: The Fourier series in $\tau$ will have coefficients of the form $\sum_{k | m}a^{m/k} k e^{2kz} $, so it is close to the inverse Mellin transform (in $s$) of $Li_{s-1}(e^{2z})Li_s(a)$ Answer: The following is probably not mathematically rigorous, and is loosely based on the Ramanujan's identity \begin{align} \sum_{n = -\infty}^\infty \frac{ (A;q)_n }{ (B;q)_n }X^n = \frac{(q;q) (B/A;q) (AX;q) (q/(AX))}{(B;q)(q/A;q)(X;q)(B/(AX);q)} \ . \end{align} The original problem can be rephrased (assuming $\partial_z$ can be moved into the sum), \begin{align} F(z) \equiv & \ \sum_{n \in \mathbb{Z}} \frac{1}{\sin^2(\frac{z}{2} + n \pi \tau)} a^n = -2 \partial_z \sum_{n \in \mathbb{Z}}\frac{\cos(\frac{z}{2} + n\pi \tau)}{\sin(\frac{z}{2} + n\pi \tau)} a^n \equiv -2 \partial_z G(z). \end{align} To compute $G(z)$, we reorganize it \begin{align} G(z) = - i \sum_{n \in \mathbb{Z}} \frac{e^{i(z + 2 n\pi \tau)}}{1-e^{i(z + n2\pi \tau)}} a^n - i \sum_{n \in \mathbb{Z}} \frac{1}{1 - e^{i(z + 2 n\pi \tau)}} a^n \ . \end{align} Defining $x \equiv e^{iz}$, $q = e^{2 \pi i \tau}$, we have \begin{align} G(z) = -i \frac{x}{1-x} \sum_n \frac{(x;q)_n}{(qx;q)_n} (aq)^n - i \frac{1}{1-x} \sum_n \frac{(x;q)_n}{(qx;q)_n} a^n \ , \end{align} where we used \begin{align} \frac{1}{1-xq^n} = \frac{1}{1-x} \frac{(x;q)_n}{(qx;q)_n} \ . \end{align} Now Ramanujan's identity comes in, and using shift properties of the $q$-Pochhammer symbols, the two sums actually are equal and they add. The final result is \begin{align} G(z) = 2 \eta(\tau)^3 \frac{ \vartheta_1(\mathfrak{a} + \frac{ z}{ 2\pi }|\tau) }{ \vartheta_1(\frac{ z}{ 2\pi }|\tau)\vartheta_1(\mathfrak{a}|\tau )}\ . \end{align} The above computation is not rigorous because the Ramanujan's identities requires $|q| < 1$ ,$|B/A| < |X| < 1$ for convergence. However, these requirements applied to the two sums at the end of step 2 are not compatible: one sum requires $|a| < 1$, the other $|a| > 1$. Besides, we need to move the $\partial_z$ into a sum. However the final answer seems physically reasonable, since it does produce physical results that we expect, despite the above issue.
[{"idx": "Find_basis_of_intersection_of_2_spans_with_unequal_dimensions", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-20533.jsonl"}, {"idx": "How_to_calculate_the_unknown_quantity_in_an_infinite_series?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-20533.jsonl"}, {"idx": "AngularJS,_How_to_get_the_value_from_input_and_place_it_in_a_factory?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-20533.jsonl"}, {"idx": "Infinite_sum_of_1/sin^2_and_theta_function", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-20533.jsonl"}]
How to use ansible 'expect' module for multiple different responses? Question: Here I am trying to test my bash script where it is prompting four times. <code>#!/bin/bash date >/opt/prompt.txt read -p "enter one: " one echo $one echo $one >>/opt/prompt.txt read -p "enter two: " two echo $two echo $two >>/opt/prompt.txt read -p "enter three: " three echo $three echo $three >>/opt/prompt.txt read -p "enter password: " password echo $password echo $password >>/opt/prompt.txt </code> for this script I wrote the code below, and it is working fine <code>- hosts: "{{ hosts }}" tasks: - name: Test Script expect: command: sc.sh responses: enter one: 'one' enter two: 'two' enter three: 'three' enter password: 'pass' echo: yes </code> But if I am doing the same for <code>mysql_secure_installation</code> command it not working <code>- hosts: "{{ hosts }}" tasks: - name: mysql_secure_installation Command Test expect: command: mysql_secure_installation responses: 'Enter current password for root (enter for none):': "\n" 'Set root password? [Y/n]:': 'y' 'New password:': '123456' 'Re-enter new password:': '123456' 'Remove anonymous users? [Y/n]:': 'y' 'Disallow root login remotely? [Y/n]:': 'y' 'Remove test database and access to it? [Y/n]:': 'y' 'Reload privilege tables now? [Y/n]:': 'y' echo: yes </code> and its trackback is here: <code>PLAY [S1] ********************************************************************** TASK [setup] ******************************************************************* ok: [S1] TASK [mysql_secure_installation Command Test] ********************************** fatal: [S1]: FAILED! => {"changed": true, "cmd": "mysql_secure_installation", "delta": "0:00:30.139266", "end": "2016-07-15 15:36:32.549415", "failed": true, "rc": 1, "start": "2016-07-15 15:36:02.410149", "stdout": "\r\n\r\n\r\n\r\nNOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL\r\n SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!\r\n\r\n\r\nIn order to log into MySQL to secure it, we'll need the current\r\npassword for the root user. If you've just installed MySQL, and\r\nyou haven't set the root password yet, the password will be blank,\r\nso you should just press enter here.\r\n\r\nEnter current password for root (enter for none): ", "stdout_lines": ["", "", "", "", "NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL", " SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!", "", "", "In order to log into MySQL to secure it, we'll need the current", "password for the root user. If you've just installed MySQL, and", "you haven't set the root password yet, the password will be blank,", "so you should just press enter here.", "", "Enter current password for root (enter for none): "]} NO MORE HOSTS LEFT ************************************************************* to retry, use: --limit @/home/jackson/AnsibleWorkSpace/AnsibleTest/example1.retry PLAY RECAP ********************************************************************* S1 : ok=1 changed=0 unreachable=0 failed=1 </code> I have also tried blank <code>''</code> instead of <code>"\n"</code> for the first answer but it is not working either. I also visited Ansible <code>expect</code> doc but they show only very simple example and explanation. I am also trying regex match for multiple different responses but it is also not working. Please do not recommend me to use mysql module of Ansible, because here my purpose is to learn this module for future use. Answer: The reason is that the questions are interpreted as regexps. Hence you must escape characters with a special meaning in regular expressions, such as -()[]\?*. et cetara. Hence: <code>'Enter current password for root (enter for none):' </code> should instead be: <code>'Enter current password for root \(enter for none\):' </code> Good luck!<|endoftext|>Load multiple json then execute funtion Question: I have a list of JSON files in a variable and I want to load the content of these files into a single object. The json files have two keys: metadata and outputs. Once this is done, I want to call a function that generates a list of tables. I am able to do this if I have only one file. The code I use to do so is: <code>jQuery.getJSON(filePath, function(data) { jQuery.each(data, function(key, val){ if ( key === "outputs"){ new tableGenerator(val); }; }); }); </code> when I try to get the data from different files I obtain an empty variable. To load different files I use: <code>var fileList = ["dataFolder/data1.json", "dataFolder/data2.json", "dataFolder/data3.json"] var jsonData = []; jQuery.when( fileList.forEach( file => { jQuery.getJSON(file, function(data) { jQuery.each(data, function(key, val){ if ( key === "outputs"){ jsonData = jsonData.concat(val); }; }); }); }) ).then(function(){ console.log(jsonData); new tableGenerator(jsonData); }) </code> I don't work normally in javascript and I don't understand why normally the tableGenerator function is executed before the jsonData handler is filled. Any comment in the code is welcome (style, deprecated...) as I am not a javascript developer and probably a lot of things will be done in an uncommon way. Comment: Consider [reading the docs]( [IDX] You need to define the parameters of the `then` callback. Modifying `jsonData` isn't a good idea Comment: Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference]( [IDX] @evolutionxbox not really, it is a bad use of `when` Answer: When expects deferreds as arguments, you are giving it deferreds. You would need to return the deferred the <code>getJSON</code> call returns and set them to <code>when</code> <code>var fileList = [ " [IDX] " [IDX] " [IDX] calls = fileList.map(path => $.getJSON(path)) $.when(...calls).then((...responses) => { const yourData = responses.map(([json]) => json); console.log(yourData); // call table code });</code> <code><script src=" [IDX] jQuery <code>var fileList = [ " [IDX] " [IDX] " [IDX] calls = fileList.map(path => fetch(path).then(response => response.json())) Promise.all(calls).then(yourData => { console.log(yourData); // call table code });</code> <code><script src=" [IDX] The get requests for json files are async. Meaning, you need to correctly await for it to happen. I would suggest using async/await approach with vanilia JS, without jQuery (aka we live in 2022) <code>const fileList = ["dataFolder/data1.json", "dataFolder/data2.json", "dataFolder/data3.json"] async function getData(url) { const request = await fetch(url) const response = await request.json() return response } async function generateTables(list){ let tablesData = []; for (const url of list) { const data = await getData(url) tablesData.push(...data?.outputs) //get only "outputs" } return [...tablesData] } generateTables(fileList).then(result => { console.log(result); new tableGenerator(result); }) </code> Comment: only problem with this approach is you line up all three calls back to back so they are not running at the same time like Promise.all solution would be doing. Answer: It's an asynchronous issue. It's a typical behavior of JavaScript, you declare a function that will be launched when the data will be ready. And after declaration, JavaScript run the next statements. See How to make the getJSON wait before running the rest of the code? to transform your code in a more classic synchronous mode. <code>await</code> keyword was introudced with ECMAScript 2017, it permits to have code less JavaScrip specific. Comment: The OP tried to do it correctly with when, this really does not answer why their code is not working.<|endoftext|>add Delete linklabel column whenever new record will be added Question: In my windows form application I want to add <code>Delete</code> linklabel against each data row and I am doing below: <code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace search { public partial class Form1 : Form { SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Documents and Settings\\Musewerx\\My Documents\\Contacts.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); public Form1() { InitializeComponent(); bindDatagridview(); } public void bindDatagridview() { SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); da.SelectCommand = new SqlCommand("Select * from contactsinfo", connection); da.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; clear(); DataGridViewLinkColumn dgvLink = new DataGridViewLinkColumn(); dgvLink.UseColumnTextForLinkValue = true; dgvLink.LinkBehavior = LinkBehavior.SystemDefault; dgvLink.HeaderText = ""; dgvLink.Name = "lnk_delete"; dgvLink.LinkColor = Color.Blue; dgvLink.TrackVisitedState = true; dgvLink.Text = "Delete"; dgvLink.UseColumnTextForLinkValue = true; bool check = dataGridView1.Columns.Contains("dgvLink"); if(check == false) { dataGridView1.Columns.Add(dgvLink); } } public void clear() { textBox1.Text = string.Empty; textBox2.Text = string.Empty; } private void button1_Click(object sender, EventArgs e) { if (textBox1.Text == string.Empty) { MessageBox.Show("Enter Contact Name"); } else if(textBox2.Text == string.Empty) { MessageBox.Show("Enter Contact Number"); } else { da.InsertCommand = new SqlCommand("Insert into contactsinfo(ContactName,ContactNumber) Values('" + textBox1.Text + "','" + textBox2.Text + "')", connection); connection.Open(); da.InsertCommand.ExecuteNonQuery(); bindDatagridview(); clear(); connection.Close(); } } private void button2_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Show(); this.Hide(); } private void Form1_Load(object sender, EventArgs e) { } } } </code> but the problem is that each time when I enter new record new column of <code>Delete</code> linklabel will be added, And I want that only one time a <code>Delete</code> linklabel column will be added. kindly suggest me, waiting for your reply. Thanks. Comment: just put an if condition to check the column already exists. If not exists then add. Otherwise dont add. Comment: @ray: on your suggestion, I have edit my post, but still not working. Answer: Try like This change "dgvLink" to "lnk_delete". "lnk_delete" is column name. <code> DataGridViewLinkColumn dgvLink = new DataGridViewLinkColumn(); dgvLink.UseColumnTextForLinkValue = true; dgvLink.LinkBehavior = LinkBehavior.SystemDefault; dgvLink.HeaderText = ""; dgvLink.Name = "lnk_delete"; dgvLink.LinkColor = Color.Blue; dgvLink.TrackVisitedState = true; dgvLink.Text = "Delete"; dgvLink.UseColumnTextForLinkValue = true; bool check = dataGridView1.Columns.Contains("lnk_delete"); if (check == false) { dataGridView1.Columns.Add(dgvLink); } </code>
[{"idx": "How_to_use_ansible_'expect'_module_for_multiple_different_responses?", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-13797.jsonl"}, {"idx": "Load_multiple_json_then_execute_funtion", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-13797.jsonl"}, {"idx": "add_Delete_linklabel_column_whenever_new_record_will_be_added", "domain": "stack_exchange", "domain2": "stackexchange", "header_footer": "", "lang": "en", "source": "stack_exchange-13797.jsonl"}]