title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
Calculating Avg, Max, and Min using a .txt input file with both integers and strings mixed
<p>Please help. I've looked everywhere and am stumped on how to finish this program. I need to calculate the average, max, and min from a data input file. They need to look like this:</p> <pre><code>System.out.println("The average total score of the class is: " + total/27); System.out.println(maxName + "got the maximum score of: " + maxVal); System.out.println(minName + "got the maximum score of: " + minVal); </code></pre> <p>For the average I don't know why the while loop in my main isn't working. It calculates a value of zero. I also don't know how I can make it so the 27 isn't hard coded. For the max and min values, I have no clue about those. i don't even have a guess. A lot of things I've looked at for these use ways we haven't been taught (like a buffered something for instance, or using the Collections class which we haven't learned about that either. I just need a basic way of accomplishing these. I will include everything I have so far. Any help is appreciated. Thank you.</p> <p>Input File:</p> <pre><code>9 Andy Borders 200 250 400 John Smith 120 220 330 Alvin Smith 225 300 278 Mike Borell 250 250 500 Jim Jones 325 325 155 Robert Fennel 200 150 350 Craig Fenner 230 220 480 Bill Johnson 120 150 220 Brent Garland 220 240 350 </code></pre> <p>Main:</p> <pre><code>import java.util.Scanner; import java.io.*; public class Project5 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter the file name: "); String fileName = in.nextLine(); try { File file = new File(fileName); Scanner inputFile = new Scanner(file); String SnumStudents = inputFile.nextLine(); int numStudents = Integer.parseInt(SnumStudents); Student [] studentList = new Student[numStudents]; for (int i = 0; i &lt; numStudents; i++) { String line = inputFile.nextLine(); String score1 = inputFile.nextLine(); String score2 = inputFile.nextLine(); String score3 = inputFile.nextLine(); studentList [i] = new Student(line, Integer.parseInt(score1), Integer.parseInt(score2), Integer.parseInt(score3)); } System.out.println("Name\t\tScore1\tScore2\tScore3\tTotal"); System.out.println("---------------------------------------------"); for (int i=0; i&lt; studentList.length;i++){ System.out.println(studentList[i].getName() + "\t" + studentList[i].getScore1() + "\t" + studentList[i].getScore2() + "\t" + studentList[i].getScore3() + "\t" + studentList[i].getTotal()); } System.out.println("---------------------------------------------"); System.out.println("The total number of students in this class is: " + studentList.length); int total = 0; while (inputFile.hasNextInt()) { int value = inputFile.nextInt(); total = total + value; } System.out.println("The average total score of the class is: " + total/27); System.out.println(maxName + "got the maximum score of: " + maxVal); System.out.println(minName + "got the maximum score of: " + minVal); inputFile.close(); } catch (IOException e) { System.out.println("There was a problem reading from " + fileName); } finally { } in.close(); } } </code></pre> <p>Student Class:</p> <pre><code>public class Student { private String name; private int score1; private int score2; private int score3; private int total; private double average; public Student(String n, int s1, int s2, int s3){ name = n; score1 = s1; score2 = s2; score3 = s3; total = s1 + s2 + s3; } public String getName(){ return name; } public int getScore1(){ return score1; } public int getScore2(){ return score2; } public int getScore3(){ return score3; } public int getTotal(){ return total; } public double computeAverage(){ return average; } } </code></pre>
3
1,479
Globalization 1.x with DevExtreme library
<p>I have a question with the DevExtreme v.16.1 in combination with Globalize 1.x. They upgraded from 0.x to 1.x and I cannot make it work since the update.</p> <p>I put the loading of the librries in an external file, and loaded the rest of the application after the promise is resolved.</p> <p>This is tje importatn part of my localize.js</p> <pre><code>$(function () { MK.localisation.init = $.when( // CLDR libraries for NL-nl $.getJSON("js/localization/nl/ca-gregorian.json"), $.getJSON("js/localization/nl/numbers.json"), $.getJSON("js/localization/nl/currencies.json"), // CLDR libraries for DE-de $.getJSON("js/localization/de/ca-gregorian.json"), $.getJSON("js/localization/de/numbers.json"), $.getJSON("js/localization/de/currencies.json"), // CLDR libraries for EN-uk $.getJSON("js/localization/en/ca-gregorian.json"), $.getJSON("js/localization/en/numbers.json"), $.getJSON("js/localization/en/currencies.json"), //additional CLDR libraries $.getJSON("js/cldr/supplemental/likelySubtags.json"), $.getJSON("js/cldr/supplemental/timeData.json"), $.getJSON("js/cldr/supplemental/weekData.json"), $.getJSON("js/cldr/supplemental/currencyData.json"), $.getJSON("js/cldr/supplemental/numberingSystems.json") ).then(function () { // Normalize $.get results, we only need the JSON, not the request statuses. return [].slice.apply(arguments, [0]).map(function (result) { return result[0]; }); }).then( Globalize.load ).then(function () { return $.when( $.getJSON("js/localization/nl/dx.all.nl.json"), $.getJSON("js/localization/nl/localization.nl.json"), $.getJSON("js/localization/de/dx.all.de.json"), $.getJSON("js/localization/de/localization.de.json"), $.getJSON("js/localization/en/dx.all.en.json"), $.getJSON("js/localization/en/localization.en.json") ).done(function (r1,r2,r3,r4,r5,r6) { Globalize.loadMessages(r1[0]); Globalize.loadMessages(r2[0]); Globalize.loadMessages(r3[0]); Globalize.loadMessages(r4[0]); Globalize.loadMessages(r5[0]); Globalize.loadMessages(r6[0]); Globalize.locale("nl"); $.each(MK.config.navigation, function () { if (this.title.indexOf('@') === 0) { this.title = Globalize.formatMessage(this.title.substring(1)); } }); }); }); </code></pre> <p>If i put a breakpoint at Globalize.locale("nl"), I see that all messages are loaded inside the Globalize object.</p> <p>I call this function at the top of my index.js the following way:</p> <pre><code>$(function () { //setup localisation MK.localisation.init.done(function () { Globalize.locale("de"); //rest of the app decalration follows here }) </code></pre> <p>I can also use the translation within JavaScript without problem</p> <pre><code>Globalize.formatMessage("someString") </code></pre> <p>However, the DevExtreme modules are not translated. They remain in english. It is also possible to let strings be translated directly inside the view with the @someString syntax. This does not work with strings i declared either. It does work with the build in strings though, so the parsing does work.</p> <p>I suspect timing problems, maybe the views are parsed before the strings are loaded? Cannot solve the problem though, followed the manual of devextreme to the point i think...</p> <p><a href="http://js.devexpress.com/Documentation/Guide/SPA_Framework/Localization/?version=16_1&amp;approach=Knockout" rel="nofollow">http://js.devexpress.com/Documentation/Guide/SPA_Framework/Localization/?version=16_1&amp;approach=Knockout</a></p>
3
1,640
facebook chat api, xmpp_connect return false
<p>Facebook chat api, Function xmpp_connect return false on block</p> <pre> // gets challenge from server and decode it send_xml($fp, $AUTH_XML); if (!find_xmpp($fp, 'CHALLENGE', null, $challenge)) { return false; } </pre> <pre><code>I can't understand what is the problem. Please help. </code></pre> <pre> // Copyright 2004-present Facebook. All Rights Reserved. $STREAM_XML = ''; $AUTH_XML = ''; $CLOSE_XML = ''; $RESOURCE_XML = ''. ''. 'fb_xmpp_script'; $SESSION_XML = ''. ''; $START_TLS = ''; function open_connection($server) { print "[INFO] Opening connection... "; $fp = fsockopen($server, 5222, $errno, $errstr); if (!$fp) { print "$errstr ($errno)<br>"; } else { print "connnection open<br>"; } return $fp; } function send_xml($fp, $xml) { fwrite($fp, $xml); } function recv_xml($fp, $size=4096) { $xml = fread($fp, $size); if ($xml === "") { return null; } // parses xml $xml_parser = xml_parser_create(); xml_parse_into_struct($xml_parser, $xml, $val, $index); xml_parser_free($xml_parser); return array($val, $index); } function find_xmpp($fp, $tag, $value=null, &$ret=null) { static $val = null, $index = null; do { if ($val === null && $index === null) { list($val, $index) = recv_xml($fp); if ($val === null || $index === null) { return false; } } foreach ($index as $tag_key => $tag_array) { if ($tag_key === $tag) { if ($value === null) { if (isset($val[$tag_array[0]]['value'])) { $ret = $val[$tag_array[0]]['value']; } return true; } foreach ($tag_array as $i => $pos) { if ($val[$pos]['tag'] === $tag && isset($val[$pos]['value']) && $val[$pos]['value'] === $value) { $ret = $val[$pos]['value']; return true; } } } } $val = $index = null; } while (!feof($fp)); return false; } function xmpp_connect($options, $access_token) { global $STREAM_XML, $AUTH_XML, $RESOURCE_XML, $SESSION_XML, $CLOSE_XML, $START_TLS; $fp = open_connection($options['server']); if (!$fp) { return false; } // initiates auth process (using X-FACEBOOK_PLATFORM) send_xml($fp, $STREAM_XML); if (!find_xmpp($fp, 'STREAM:STREAM')) { return false; } if (!find_xmpp($fp, 'MECHANISM', 'X-FACEBOOK-PLATFORM')) { return false; } // starting tls - MANDATORY TO USE OAUTH TOKEN!!!! send_xml($fp, $START_TLS); if (!find_xmpp($fp, 'PROCEED', null, $proceed)) { return false; } stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); send_xml($fp, $STREAM_XML); if (!find_xmpp($fp, 'STREAM:STREAM')) { return false; } if (!find_xmpp($fp, 'MECHANISM', 'X-FACEBOOK-PLATFORM')) { return false; } // gets challenge from server and decode it send_xml($fp, $AUTH_XML); if (!find_xmpp($fp, 'CHALLENGE', null, $challenge)) { return false; } $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_array); // creates the response array $resp_array = array( 'method' => $challenge_array['method'], 'nonce' => $challenge_array['nonce'], 'access_token' => $access_token, 'api_key' => $options['app_id'], 'call_id' => 0, 'v' => '1.0', ); // creates signature $response = http_build_query($resp_array); // sends the response and waits for success $xml = ''. base64_encode($response).''; send_xml($fp, $xml); if (!find_xmpp($fp, 'SUCCESS')) { return false; } // finishes auth process send_xml($fp, $STREAM_XML); if (!find_xmpp($fp,'STREAM:STREAM')) { return false; } if (!find_xmpp($fp, 'STREAM:FEATURES')) { return false; } send_xml($fp, $RESOURCE_XML); if (!find_xmpp($fp, 'JID')) { return false; } send_xml($fp, $SESSION_XML); if (!find_xmpp($fp, 'SESSION')) { return false; } // we made it! send_xml($fp, $CLOSE_XML); print ("Authentication complete<br>"); fclose($fp); return true; } //Gets access_token with xmpp_login permission function get_access_token($app_id, $app_secret, $my_url){ $code = $_REQUEST["code"]; if(empty($code)) { $dialog_url = "https://www.facebook.com/dialog/oauth?scope=xmpp_login". "&client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) ; echo("top.location.href='" . $dialog_url . "'"); } $token_url = "https://graph.facebook.com/oauth/access_token?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code; $access_token = file_get_contents($token_url); parse_str($access_token, $output); return($output['access_token']); } function _main() { print "Test platform connect for XMPP<br>"; $app_id=''; $app_secret=''; $my_url = ""; $uid = ''; $access_token = get_access_token($app_id,$app_secret,$my_url); print "access_token: ".$access_token."<br>"; $options = array( 'uid' => $uid, 'app_id' => $app_id, 'server' => 'chat.facebook.com', ); // prints options used print "server: ".$options['server']."<br>"; print "uid: ".$options['uid']."<br>"; print "app id: ".$options['app_id']."<br>"; if (xmpp_connect($options, $access_token)) { print "Done<br>"; } else { print "An error ocurred<br>"; } } _main(); </pre> <p>Docs: <a href="https://developers.facebook.com/docs/chat/" rel="nofollow">https://developers.facebook.com/docs/chat/</a></p>
3
3,132
Unable to Build Docker Image for Spring Boot No such property: parentFile
<p>I am trying to build a sample docker image for my helloworld program</p> <pre><code>import com.bmuschko.gradle.docker.tasks.image.Dockerfile import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage plugins { id 'com.bmuschko.docker-remote-api' version '6.7.0' id 'org.springframework.boot' version '2.7.2' id 'io.spring.dependency-management' version '1.0.12.RELEASE' id 'java' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8' configurations { compileOnly { extendsFrom annotationProcessor } } repositories { mavenLocal() mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' } task createDockerfile(type: Dockerfile) { destFile = project.file('build/docker/Dockerfile') from 'openjdk:8-jre-alpine' copyFile &quot;libs/${jar.archiveBaseName}-${jar.archiveVersion}.jar&quot;, &quot;${jar.archiveBaseName}.jar&quot; entryPoint 'java' defaultCommand '-jar', &quot;${jar.archiveBaseName}.jar&quot; exposePort 8080 } task buildImage(type: DockerBuildImage) { dependsOn createDockerfile inputDir = createDockerfile.destFile.parentFile tag = &quot;${jar.archiveBaseName}:latest&quot; } </code></pre> <p>Its giving me this error</p> <pre><code>Caused by: groovy.lang.MissingPropertyException: No such property: parentFile for class: org.gradle.api.internal.file.DefaultFilePropertyFactory$DefaultRegularFileVar at build_dawchkdhtqfn2zzdavoge0cnm$_run_closure5.doCall(/Users/mchavak/Downloads/demo/build.gradle:45) at org.gradle.util.internal.ClosureBackedAction.execute(ClosureBackedAction.java:73) at org.gradle.util.internal.ConfigureUtil.configureTarget(ConfigureUtil.java:155) at org.gradle.util.internal.ConfigureUtil.configureSelf(ConfigureUtil.java:131) at org.gradle.api.internal.AbstractTask.configure(AbstractTask.java:666) at org.gradle.api.DefaultTask.configure(DefaultTask.java:309) at org.gradle.api.internal.project.DefaultProject.task(DefaultProject.java:1294) at org.gradle.internal.metaobject.BeanDynamicObject$MetaClassAdapter.invokeMethod(BeanDynamicObject.java:484) at org.gradle.internal.metaobject.BeanDynamicObject.tryInvokeMethod(BeanDynamicObject.java:196) at org.gradle.internal.metaobject.CompositeDynamicObject.tryInvokeMethod(CompositeDynamicObject.java:98) at org.gradle.internal.extensibility.MixInClosurePropertiesAsMethodsDynamicObject.tryInvokeMethod(MixInClosurePropertiesAsMethodsDynamicObject.java:34) at org.gradle.groovy.scripts.BasicScript$ScriptDynamicObject.tryInvokeMethod(BasicScript.java:135) at org.gradle.internal.metaobject.AbstractDynamicObject.invokeMethod(AbstractDynamicObject.java:163) at org.gradle.groovy.scripts.BasicScript.invokeMethod(BasicScript.java:84) at build_dawchkdhtqfn2zzdavoge0cnm.run(/Users/mchavak/Downloads/demo/build.gradle:43) at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:91) </code></pre>
3
1,192
CarouFredSel sliding issue
<p>I have set up a caroufredsel, and have items inside of it. But when I click on my next and previous buttons, the first time it appears to shift 1 item, every click after that it shifts the entire width of the content and back to the beginning.</p> <p>I have set my scroll items to 3. Does it have something to do with the width of the container?</p> <pre><code>jQuery('#tab-1').find('#carousel').carouFredSel({ responsive : true, circular: false, align: "center", height : 'auto', width : 'auto', auto : false, prev : { button : function() { return jQuery('#tab-1').find('.carousel-pagerLeft'); } }, next : { button : function() { return jQuery('#tab-1').find('.carousel-pagerRight'); } }, scroll : { items : 3, fx : "fade" }, items : { height : 'auto', width: 'auto' }, swipe: { onMouse: true, onTouch: true } }); </code></pre> <p>It also seems that on slide, the height of the carousel changes for some reason. maybe this is related</p>
3
1,166
Trouble printing to a specific Tray (PaperSource) using VB.NET PrinterSettings
<p>I've been having trouble automatically selecting a Tray (PaperSource) to print from on a specific printer (HP OfficeJet Pro 9020 series) using VB.NET. I have reduced my code to a bare minimum below to indicate the process I'm following.</p> <p>After the print dialog has popped up and you select 'Tray 2' from the list. The line of code <code>prn.PrinterSettings = pd.PrinterSettings</code> applies that setting, and it subsequently prints from the correct tray. If, however, you just click ok on the dialog it prints from the wrong tray.</p> <p>The strange thing is that, as you can see, I set the 'Tray 2' option in code, so, in theory that object should be exactly the same. I used <code>Newtonsoft.JSON</code> to serialise the <code>pd.PrinterSettings</code> object before and after I had selected 'Tray 2' in the dialog so I could compare the differences and they were both identical. The only differences at first were the ones I addressed in the code earlier on. They didn't make any difference though. Those being;</p> <pre><code>pd.PrinterSettings.PrintFileName = &quot;IP_192.168.1.50&quot; pd.PrinterSettings.PrinterName = &quot;Dispatch Office&quot; pd.PrinterSettings.Collate = False </code></pre> <p>But for whatever reason, it only works if I explicitly open the dialog and select the desired Tray and click ok. <code>prn.PrinterSettings = pd.PrinterSettings</code> is the only line of code that has any effect on what printer is used, so somewhere in <code>pd.PrinterSettings</code> there must be something missing that I couldn't see in the JSON string. I've had success with this code on other printers, but this specific printer seems to be different, but the problem has to be with VB.NET I would think.</p> <p>Has anyone come across anything like this before? Here is my full code below.</p> <pre><code>Private Sub Print() Dim pd As New PrintDialog pd.PrinterSettings.PrintFileName = &quot;IP_192.168.1.50&quot; pd.PrinterSettings.PrinterName = &quot;Dispatch Office&quot; pd.PrinterSettings.Collate = False For Each paperSource As Printing.PaperSource In pd.PrinterSettings.PaperSources If paperSource.SourceName = &quot;Tray 2&quot; Then pd.PrinterSettings.DefaultPageSettings.PaperSource = paperSource Exit For End If Next If pd.ShowDialog = DialogResult.OK Then Dim prn As New Printing.PrintDocument prn.PrinterSettings = pd.PrinterSettings AddHandler prn.PrintPage, AddressOf Me.PrintPageHandler prn.Print() RemoveHandler prn.PrintPage, AddressOf Me.PrintPageHandler End If End Sub Private Sub PrintPageHandler(ByVal sender As Object, ByVal args As Printing.PrintPageEventArgs) Dim myFont As New Font(&quot;Courier New&quot;, 9) Dim strTextFile = IO.File.ReadAllText(&quot;C:\textfile.txt&quot;) args.Graphics.DrawString(strTextFile, New Font(myFont, FontStyle.Regular), Brushes.Black, 50, 50) End Sub </code></pre> <p>Also, just to confirm, this is independent of the print dialog. The code below which is in the shortest form possible also does not work.</p> <pre><code>Private Sub PrintAuto() Dim ps As New Printing.PrinterSettings With {.PrinterName = &quot;Dispatch Office&quot;} ps.DefaultPageSettings.PaperSource = ps.PaperSources(3) ' Tray 2 Dim prn As New Printing.PrintDocument With {.PrinterSettings = ps} AddHandler prn.PrintPage, AddressOf PrintPageHandler prn.Print() RemoveHandler prn.PrintPage, AddressOf PrintPageHandler End Sub </code></pre>
3
1,087
Create binary of spaCy with PyInstaller
<p>I would like to create a binary of my python code, that contains spaCy.</p> <pre class="lang-py prettyprint-override"><code># main.py import spacy import en_core_web_sm def main() -&gt; None: nlp = spacy.load(&quot;en_core_web_sm&quot;) # nlp = en_core_web_sm.load() doc = nlp(&quot;This is an example&quot;) print([(w.text, w.pos_) for w in doc]) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>Besides my code, I created two PyInstaller-hooks, as described <a href="https://stackoverflow.com/a/64887390/7988528">here</a></p> <p>To create the binary I use the following command <code>pyinstaller main.py --additional-hooks-dir=.</code>.</p> <p>On the execution of the binary I get the following error message:</p> <pre><code>Traceback (most recent call last): File &quot;main.py&quot;, line 19, in &lt;module&gt; main() File &quot;main.py&quot;, line 12, in main nlp = spacy.load(&quot;en_core_web_sm&quot;) File &quot;spacy/__init__.py&quot;, line 47, in load File &quot;spacy/util.py&quot;, line 329, in load_model OSError: [E050] Can't find model 'en_core_web_sm'. It doesn't seem to be a Python package or a valid path to a data directory. </code></pre> <p>If I use <code>nlp = en_core_web_sm.load()</code> instead if <code>nlp = spacy.load(&quot;en_core_web_sm&quot;)</code> to load the spacy model, I get the following error:</p> <pre><code>Traceback (most recent call last): File &quot;main.py&quot;, line 19, in &lt;module&gt; main() File &quot;main.py&quot;, line 13, in main nlp = en_core_web_sm.load() File &quot;en_core_web_sm/__init__.py&quot;, line 10, in load File &quot;spacy/util.py&quot;, line 514, in load_model_from_init_py File &quot;spacy/util.py&quot;, line 389, in load_model_from_path File &quot;spacy/util.py&quot;, line 426, in load_model_from_config File &quot;spacy/language.py&quot;, line 1662, in from_config File &quot;spacy/language.py&quot;, line 768, in add_pipe File &quot;spacy/language.py&quot;, line 659, in create_pipe File &quot;thinc/config.py&quot;, line 722, in resolve File &quot;thinc/config.py&quot;, line 771, in _make File &quot;thinc/config.py&quot;, line 826, in _fill File &quot;thinc/config.py&quot;, line 825, in _fill File &quot;thinc/config.py&quot;, line 1016, in make_promise_schema File &quot;spacy/util.py&quot;, line 137, in get catalogue.RegistryError: [E893] Could not find function 'spacy.Tok2Vec.v1' in function registry 'architectures'. If you're using a custom function, make sure the code is available. If the function is provided by a third-party package, e.g. spacy-transformers, make sure the package is installed in your environment. </code></pre>
3
1,082
Using PHPMailer without Composer
<p>I just tried this example:</p> <pre><code>// for use PHP Mailer without composer : // ex. Create a folder in root/PHPMAILER // Put on this folder this 3 files find in &quot;src&quot; // folder of the distribution : // PHPMailer.php , SMTP.php , Exception.php // include PHP Mailer use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; include dirname(__DIR__) .'/PHPMAILER/PHPMailer.php'; include dirname(__DIR__) .'/PHPMAILER/SMTP.php'; include dirname(__DIR__) .'/PHPMAILER/Exception.php'; // i made a function /* * * Function send_mail_by_PHPMailer($to, $from, $subject, $message); * send a mail by PHPMailer method * @Param $to -&gt; mail to send * @Param $from -&gt; sender of mail * @Param $subject -&gt; suject of mail * @Param $message -&gt; html content with datas * @Return true if success / Json encoded error message if error * !! need -&gt; classes/Exception.php - classes/PHPMailer.php - classes/SMTP.php * */ function send_mail_by_PHPMailer($to, $from, $subject, $message){ // SEND MAIL by PHP MAILER $mail = new PHPMailer(); $mail-&gt;CharSet = 'UTF-8'; $mail-&gt;isSMTP(); // Use SMTP protocol $mail-&gt;Host = 'your_host.com'; // Specify SMTP server $mail-&gt;SMTPAuth = true; // Auth. SMTP $mail-&gt;Username = 'my_mail@your_host.com'; // Mail who send by PHPMailer $mail-&gt;Password = 'your_passord_of_your_box'; // your pass mail box $mail-&gt;SMTPSecure = 'ssl'; // Accept SSL $mail-&gt;Port = 465; // port of your out server $mail-&gt;setFrom($from); // Mail to send at $mail-&gt;addAddress($to); // Add sender $mail-&gt;addReplyTo($from); // Adress to reply $mail-&gt;isHTML(true); // use HTML message $mail-&gt;Subject = $subject; $mail-&gt;Body = $message; // SEND if( !$mail-&gt;send() ){ // render error if it is $tab = array('error' =&gt; 'Mailer Error: '.$mail-&gt;ErrorInfo ); echo json_encode($tab); exit; } else{ // return true if message is send return true; } } /* * * END send_mail_by_PHPMailer($to, $from, $subject, $message) * send a mail by PHPMailer method * */ // use function : send_mail_by_PHPMailer($to, $from, $subject, $message); </code></pre> <p>When calling <code>new PHPMailer()</code> the system throws a error:</p> <blockquote> <p>Can't find class PHPMailer.</p> </blockquote> <p>The include of the files works fine. What is wrong?</p>
3
1,230
timetable for scheduled subjects
<p>i got it right though my problem now is how can i put a style on the table row that has the data inside it and much better if i can put rowspan to it so that it will look like one table row.</p> <p>here is the output: </p> <p><a href="https://i.stack.imgur.com/qRNLz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qRNLz.png" alt="enter image description here"></a></p> <p>and here is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?php $db = new mysqli("localhost", "root", "", "bsu_db"); if($db-&gt;connect_errno &gt; 0){ die('Unable to connect to database [' . $db-&gt;connect_error . ']'); } $times = ["7:00:00", "7:30:00", "8:00:00", "8:30:00", "9:00:00", "9:30:00", "10:00:00", "10:30:00", "11:00:00", "11:30:00", "12:00:00"]; $days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; $SubjDay = array(); $sqlSubjDay = "SELECT * FROM subject_day_tbl"; $qrySubjDay = $db-&gt;query($sqlSubjDay); while($rowSubjDay = $qrySubjDay-&gt;fetch_assoc()){ //array_push($SubjDay, $rowSubjDay['sub_day'], $rowSubjDay['start_time'], $rowSubjDay['end_time']); $SubjDay[] = $rowSubjDay; } json_encode($SubjDay); ?&gt; &lt;table class="table table-bordered table-condensed"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;&lt;/th&gt; &lt;?php foreach ($days as $day ) { echo "&lt;th&gt;$day&lt;/th&gt;"; } ?&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php foreach ($times as $time) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $time; ?&gt;&lt;/td&gt; &lt;?php foreach ($days as $day) { echo "&lt;td&gt;"; foreach($SubjDay as $sd){ if($day == $sd['sub_day'] &amp;&amp; strtotime($time) &gt;= strtotime($sd['start_time']) &amp;&amp; strtotime($time) &lt;= strtotime($sd['end_time'])){ echo $sd['sub_day'] , " " , $sd['start_time'] , " - " , $sd['end_time']; } } echo "&lt;/td&gt;"; } ?&gt; &lt;/tr&gt; &lt;?php } ?&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
3
1,058
New pdf for every different customer number
<p>I have tried to cut down the code as much as possible. The most important part of the code is the second block. There are only two scenarios where I need a different bill to address. These are hard coded in shippercarrierdata,shippercarrierdata1.These create pdfs fine. the problem is creating the default addresses for prepaid customers when there is more than one customer I need it to create a new pdf with a list of all the orders for that customer. I am using TCPDF. Any help would be appreciated. </p> <pre><code>&lt;?php // include('inc/connections.php'); $pickUpDate = $_REQUEST['pickUpDate']; require_once('tcpdf/config/lang/eng.php'); require_once('tcpdf/tcpdf.php'); // Extend the TCPDF class to create custom Header and Footer class ManafestPrint extends TCPDF { //Page header public function Header() { global $pickUpDate; // Set font $this-&gt;SetFont('helvetica', 'B', 20); // Title $titleHTML = ' &lt;table width="100%" border="0" style="font-weight: bold; font-size: 9pt;"&gt; &lt;tr&gt; &lt;td width="25%" align="left"&gt;PICK UP DATE: '.$pickUpDate.'&lt;/td&gt; &lt;td width="50%" align="center" style="font-size: 16pt;"&gt;SHIPPING MANIFEST&lt;/td&gt; &lt;td width="25%" align="right"&gt;Page '.$this-&gt;getPageNumGroupAlias().' of '.$this-&gt;getPageGroupAlias().'&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; '; $this-&gt;writeHTMLCell(280, 25, 7, 5, $titleHTML); } } $orders = explode(',', $_REQUEST['orders']); $infinity = ''; $i = 0; foreach($orders as $order) { $sql = " SELECT oeordhdr_sql.ship_via_cd AS shipper, oeordlin_sql.ord_no AS ordnum, oeordhdr_sql.frt_pay_cd AS thirdparty, oeordhdr_sql.cus_no AS customer FROM oeordhdr_sql JOIN oeordlin_sql ON oeordhdr_sql.ord_no = oeordlin_sql.ord_no WHERE oeordhdr_sql.ord_no = oeordlin_sql.ord_no AND oeordlin_sql.loc IN ('PMD','OM1') AND oeordhdr_sql.shipping_dt&gt;=getdate()-21 AND oeordlin_sql.ord_no = ' $order' ORDER BY oeordlin_sql.ord_no ASC "; $query = odbc_exec($connect, $sql); $row = odbc_fetch_array($query); if (($row['customer']) == '0000' &amp;&amp; ($row['thirdparty']) == 'C' &amp;&amp; ($row['shipper']) == 'EST') { $tablerows= "&lt;tr&gt;&lt;td&gt;'.$row['customer'].'&lt;/td&gt;&lt;td&gt;'.$row['customer'].'&lt;/td&gt;&lt;td&gt;'.$row['ord_num'].'&lt;/td&gt;&lt;td&gt;'.$row['item_no'].'&lt;/td&gt;&lt;td&gt;'.$row['shipper'].'&lt;/td&gt;&lt;td&gt;'.$row['thirdpart'].'&lt;/td&gt;&lt;/tr&gt;"; }elseif (($row['customer']) == '0001' &amp;&amp; ($row['thirdparty']) == 'C' &amp;&amp; ($row['shipper']) == 'EST') { $tablerows1 = "&lt;tr&gt;&lt;td&gt;'.$row['customer'].'&lt;/td&gt;&lt;td&gt;'.$row['customer'].'&lt;/td&gt;&lt;td&gt;'.$row['ord_num'].'&lt;/td&gt;&lt;td&gt;'.$row['item_no'].'&lt;/td&gt;&lt;td&gt;'.$row['shipper'].'&lt;/td&gt;&lt;td&gt;'.$row['thirdpart'].'&lt;/td&gt;&lt;/tr&gt;"; }else{ $tablerows2 = "&lt;tr&gt;&lt;td&gt;'.$row['customer'].'&lt;/td&gt;&lt;td&gt;'.$row['customer'].'&lt;/td&gt;&lt;td&gt;'.$row['ord_num'].'&lt;/td&gt;&lt;td&gt;'.$row['item_no'].'&lt;/td&gt;&lt;td&gt;'.$row['shipper'].'&lt;/td&gt;&lt;td&gt;'.$row['thirdpart'].'&lt;/td&gt;&lt;/tr&gt;"; } } $tableData = ' &lt;style&gt; table#manifestTable tr.odd td{ background-color: #F0F0F0; } div.totalDIV{ vertical-align: bottom; font-weight: bold; } &lt;/style&gt; &lt;table id="manifestTable" width="100%" cellpadding="0" cellspacing="0" border="0" style="font-size: 8pt;"&gt; &lt;thead&gt; &lt;tr style="font-weight: bold; text-decoration: underline;"&gt; &lt;th align="center" style="width: 40px;"&gt;REF#&lt;/th&gt; &lt;th align="center" style="width: 75px;"&gt;PO#&lt;/th&gt; &lt;th align="center" style="width: 75px;"&gt;PRO#&lt;/th&gt; &lt;th align="left" style="width: 125px;"&gt;CONSIGNEE ADDRESS&lt;/th&gt; &lt;th align="center" style="width: 125px;"&gt;SPECIAL INST&lt;/th&gt; &lt;th align="center" style="width: 100px;"&gt;COMMODITY&lt;/th&gt; &lt;th align="center" style="width: 40px;"&gt;NMFC#&lt;/th&gt; &lt;th align="center" style="width: 30px;"&gt;SUB&lt;/th&gt; &lt;th align="center" style="width: 40px;"&gt;CLASS&lt;/th&gt; &lt;th align="center" style="width: 40px;"&gt;UNITS&lt;/th&gt; &lt;th align="center" style="width: 30px;"&gt;PKGS&lt;/th&gt; &lt;th align="RIGHT" style="width: 40px;"&gt;WEIGHT&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; '.$tablerows.' &lt;/tbody&gt; &lt;/table&gt; '; $tableData = ' &lt;style&gt; table#manifestTable tr.odd td{ background-color: #F0F0F0; } div.totalDIV{ vertical-align: bottom; font-weight: bold; } &lt;/style&gt; &lt;table id="manifestTable" width="100%" cellpadding="0" cellspacing="0" border="0" style="font-size: 8pt;"&gt; &lt;thead&gt; &lt;tr style="font-weight: bold; text-decoration: underline;"&gt; &lt;th align="center" style="width: 40px;"&gt;REF#&lt;/th&gt; &lt;th align="center" style="width: 75px;"&gt;PO#&lt;/th&gt; &lt;th align="center" style="width: 75px;"&gt;PRO#&lt;/th&gt; &lt;th align="left" style="width: 125px;"&gt;CONSIGNEE ADDRESS&lt;/th&gt; &lt;th align="center" style="width: 125px;"&gt;SPECIAL INST&lt;/th&gt; &lt;th align="center" style="width: 100px;"&gt;COMMODITY&lt;/th&gt; &lt;th align="center" style="width: 40px;"&gt;NMFC#&lt;/th&gt; &lt;th align="center" style="width: 30px;"&gt;SUB&lt;/th&gt; &lt;th align="center" style="width: 40px;"&gt;CLASS&lt;/th&gt; &lt;th align="center" style="width: 40px;"&gt;UNITS&lt;/th&gt; &lt;th align="center" style="width: 30px;"&gt;PKGS&lt;/th&gt; &lt;th align="RIGHT" style="width: 40px;"&gt;WEIGHT&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; '.$tablerows1.' &lt;/tbody&gt; &lt;/table&gt; '; $tableData = ' &lt;style&gt; table#manifestTable tr.odd td{ background-color: #F0F0F0; } div.totalDIV{ vertical-align: bottom; font-weight: bold; } &lt;/style&gt; &lt;table id="manifestTable" width="100%" cellpadding="0" cellspacing="0" border="0" style="font-size: 8pt;"&gt; &lt;thead&gt; &lt;tr style="font-weight: bold; text-decoration: underline;"&gt; &lt;th align="center" style="width: 40px;"&gt;REF#&lt;/th&gt; &lt;th align="center" style="width: 75px;"&gt;PO#&lt;/th&gt; &lt;th align="center" style="width: 75px;"&gt;PRO#&lt;/th&gt; &lt;th align="left" style="width: 125px;"&gt;CONSIGNEE ADDRESS&lt;/th&gt; &lt;th align="center" style="width: 125px;"&gt;SPECIAL INST&lt;/th&gt; &lt;th align="center" style="width: 100px;"&gt;COMMODITY&lt;/th&gt; &lt;th align="center" style="width: 40px;"&gt;NMFC#&lt;/th&gt; &lt;th align="center" style="width: 30px;"&gt;SUB&lt;/th&gt; &lt;th align="center" style="width: 40px;"&gt;CLASS&lt;/th&gt; &lt;th align="center" style="width: 40px;"&gt;UNITS&lt;/th&gt; &lt;th align="center" style="width: 30px;"&gt;PKGS&lt;/th&gt; &lt;th align="RIGHT" style="width: 40px;"&gt;WEIGHT&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; '.$tablerows2.' &lt;/tbody&gt; &lt;/table&gt; '; $shipperCarierData =' &lt;table width="100%" border="0" cellpadding="0" cellspacing="0" style="font-size: 10pt;"&gt; &lt;tr&gt; &lt;td width="35%" align="left" valign="top" style="padding-left: 25px;"&gt; &lt;table width="250" border="0" cellpadding="0" cellspacing="0"&gt; &lt;tr&gt; &lt;td align="left" valign="top" width="55"&gt;Shipper:&lt;/td&gt; &lt;td align="left" valign="top"&gt; company name&lt;br /&gt; 9000 dummy street&lt;br /&gt; town, usa 01234&lt;br /&gt; Jon doe (123) 456-7890 &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;td align="left" valign="top" width="45"&gt;&lt;strong&gt;Bill To:&lt;/strong&gt;&lt;/td&gt; &lt;td width="25%" align="left" valign="top"&gt; EST&lt;br/&gt; 4444 street name&lt;br/&gt; dummy town, 10004&lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;td align="left" valign="top" width="250"&gt; &lt;strong&gt;Carrier:&lt;/strong&gt; '.$row['shipper'].'&lt;br /&gt; &lt;strong&gt;Trailer#:&lt;/strong&gt; '.$row['trailer'].'&lt;br /&gt; &lt;strong&gt;Service:&lt;/strong&gt; Standard-Bill Accessorial Code WGST&lt;br /&gt; &lt;strong&gt;Terms:&lt;/strong&gt; Prepaid &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; '; $shipperCarierData1 =' &lt;table width="100%" border="0" cellpadding="0" cellspacing="0" style="font-size: 10pt;"&gt; &lt;tr&gt; &lt;td width="35%" align="left" valign="top" style="padding-left: 25px;"&gt; &lt;table width="250" border="0" cellpadding="0" cellspacing="0"&gt; &lt;tr&gt; &lt;td align="left" valign="top" width="55"&gt;Shipper:&lt;/td&gt; &lt;td align="left" valign="top"&gt; company name 2&lt;br /&gt; 9000 dummy street&lt;br /&gt; town, usa 01234&lt;br /&gt; Jon doe (123) 456-7890 &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;td align="left" valign="top" width="45"&gt;&lt;strong&gt;Bill To:&lt;/strong&gt;&lt;/td&gt; &lt;td width="25%" align="left" valign="top"&gt; EST&lt;br/&gt; 4444 street name&lt;br/&gt; dummy town, 10004&lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;td align="left" valign="top" width="250"&gt; &lt;strong&gt;Carrier:&lt;/strong&gt; '.$row['shipper'].'&lt;br /&gt; &lt;strong&gt;Trailer#:&lt;/strong&gt; '.$row['trailer'].'&lt;br /&gt; &lt;strong&gt;Service:&lt;/strong&gt; Standard-Bill Accessorial Code WGST&lt;br /&gt; &lt;strong&gt;Terms:&lt;/strong&gt; Prepaid &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; '; $shipperCarierData2 =' &lt;table width="100%" border="0" cellpadding="0" cellspacing="0" style="font-size: 10pt;"&gt; &lt;tr&gt; &lt;td width="35%" align="left" valign="top" style="padding-left: 25px;"&gt; &lt;table width="250" border="0" cellpadding="0" cellspacing="0"&gt; &lt;tr&gt; &lt;td align="left" valign="top" width="55"&gt;Shipper:&lt;/td&gt; &lt;td align="left" valign="top"&gt; company name&lt;br /&gt; 9000 dummy street&lt;br /&gt; town, usa 01234&lt;br /&gt; Jon doe (123) 456-7890 &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;td align="left" valign="top" width="250"&gt; &lt;strong&gt;Carrier:&lt;/strong&gt; '.$row['shipper'].'&lt;br /&gt; &lt;strong&gt;Trailer#:&lt;/strong&gt; '.$row['trailer'].'&lt;br /&gt; &lt;strong&gt;Service:&lt;/strong&gt; Standard-Bill Accessorial Code WGST&lt;br /&gt; &lt;strong&gt;Terms:&lt;/strong&gt; Prepaid &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; '; </code></pre> <p>This is the pdf creation using TCPDF. I am trying to use a foreach to create a new pdf for each customer. I realize that does not work.</p> <pre><code>if(!empty($tablerows)) { $pdf-&gt;startPageGroup(); $pdf-&gt;SetPrintFooter(false); $pdf-&gt;AddPage(); $pdf-&gt;writeHTMLCell(280, 0, 5, 15, $shipperCarierData, 0, 0, false, true, 'C', true); $pdf-&gt;writeHTMLCell(280, 0, 3, 35, $tableData, 0, 0, false, true, 'C', true); $pdf-&gt;AddPage(); $pdf-&gt;writeHTMLCell(280, 0, 5, 160, $disclaimerHTML, 0, 0, false, true, 'C', true); $pdf-&gt;SetPrintFooter(true); } if(!empty($tablerows1)) { $pdf-&gt;startPageGroup(); $pdf-&gt;SetPrintFooter(false); $pdf-&gt;AddPage(); $pdf-&gt;writeHTMLCell(280, 0, 5, 15, $shipperCarierData1, 0, 0, false, true, 'C', true); #WRITE TABLE ROWS $pdf-&gt;writeHTMLCell(280, 0, 3, 35, $tableData1, 0, 0, false, true, 'C', true); $pdf-&gt;lastPage(); //$pdf-&gt;writeHTMLCell(280, 0, 5, 160, $disclaimerHTML, 0, 0, false, true, 'C', true); $pdf-&gt;AddPage(); $pdf-&gt;writeHTMLCell(280, 0, 5, 160, $disclaimerHTML, 0, 0, false, true, 'C', true); } foreach($row['customer'] as $cus) { if (!empty($tablerows2)) { $pdf-&gt;startPageGroup(); $pdf-&gt;SetPrintFooter(false); $pdf-&gt;AddPage(); $pdf-&gt;writeHTMLCell(280, 0, 5, 15, $shipperCarierData2, 0, 0, false, true, 'C', true); #WRITE TABLE ROWS $pdf-&gt;writeHTMLCell(280, 0, 3, 35, $tableData2, 0, 0, false, true, 'C', true); $pdf-&gt;lastPage(); $pdf-&gt;AddPage(); $pdf-&gt;writeHTMLCell(280, 0, 5, 160, $disclaimerHTML, 0, 0, false, true, 'C', true); } } //Close and output PDF document $pdf-&gt;Output('print_manifest.pdf', 'I'); </code></pre>
3
9,816
Python: Problem fitting the word2vec embeddings into Keras Sequential Model
<p>I have a very simple Sequential Model:</p> <pre><code>embedding_size = 100 model = keras.Sequential([ keras.layers.Flatten(input_shape=(embedding_size,)), keras.layers.Dense(200, activation='relu'), keras.layers.Dense(50, activation='relu'), keras.layers.Dense(4, activation='softmax') ]) adam=keras.optimizers.Adam(learning_rate=0.001) model.compile(optimizer=adam, loss=[&quot;categorical_crossentropy&quot;], metrics=['accuracy']) model.summary() </code></pre> <p><a href="https://i.stack.imgur.com/dLXTv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dLXTv.png" alt="Model" /></a></p> <p>For input I have word2vec encoded vectors of size 1x100 for each sentence.</p> <p>Sample input is like this:</p> <p><a href="https://i.stack.imgur.com/odXAb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/odXAb.png" alt="Input" /></a></p> <p>This means, sentence 0 has the above mentioned vector. Corpus length is 9600 hence train_x is a list of size 9600.</p> <p>train_y is a simple hot_encoded labels class as shown below:</p> <p><a href="https://i.stack.imgur.com/oJr2N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oJr2N.png" alt="Labels" /></a></p> <p>Problem occurs when I try to fit:</p> <pre><code>model.fit(train_x, train_y, epochs= 10, batch_size= 50, verbose=1, shuffle=True, validation_data=(val_x, val_y)) </code></pre> <p>Exception:</p> <p>ValueError: Failed to find data adapter that can handle input: (&lt;class 'list'&gt; containing values of types {&quot;&lt;class 'NoneType'&gt;&quot;, &quot;&lt;class 'numpy.ndarray'&gt;&quot;}), &lt;class 'numpy.ndarray'&gt;</p> <p>Complete stack trace is:</p> <pre><code>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) /Users/raffaysajjad/Library/CloudStorage/OneDrive-Personal/MS Computer Science/Semester 4 (Spring 2022)/CS 5316 - Natural Language Processing/Assignments/Assignment 3/Assignment_3_20030001.ipynb Cell 33' in &lt;module&gt; ----&gt; 1 model.fit(train_x, 2 train_y, 3 epochs= 10, 4 batch_size= 50, 5 verbose=1, 6 shuffle=True, 7 validation_data=(val_x, val_y)) File /usr/local/lib/python3.9/site-packages/keras/utils/traceback_utils.py:67, in filter_traceback.&lt;locals&gt;.error_handler(*args, **kwargs) 65 except Exception as e: # pylint: disable=broad-except 66 filtered_tb = _process_traceback_frames(e.__traceback__) ---&gt; 67 raise e.with_traceback(filtered_tb) from None 68 finally: 69 del filtered_tb File /usr/local/lib/python3.9/site-packages/keras/engine/data_adapter.py:984, in select_data_adapter(x, y) 981 adapter_cls = [cls for cls in ALL_ADAPTER_CLS if cls.can_handle(x, y)] 982 if not adapter_cls: 983 # TODO(scottzhu): This should be a less implementation-specific error. --&gt; 984 raise ValueError( 985 &quot;Failed to find data adapter that can handle &quot; 986 &quot;input: {}, {}&quot;.format( 987 _type_name(x), _type_name(y))) 988 elif len(adapter_cls) &gt; 1: 989 raise RuntimeError( 990 &quot;Data adapters should be mutually exclusive for &quot; 991 &quot;handling inputs. Found multiple adapters {} to handle &quot; 992 &quot;input: {}, {}&quot;.format( 993 adapter_cls, _type_name(x), _type_name(y))) </code></pre> <p>I'm unable to figure out why it is rejecting the values of type ndarray. Can someone please point out how I should pass these values to model.fit correctly?</p>
3
1,623
FlatList not showing up
<p>I am following a tutorial video for React Native. Everything is working well besides the FlatList, I am unable to make it show up on the simulator. I am using expo, while this tutorial is done using bare. Maybe that is causing the issue, but I am not sure how to resolve it.</p> <p>Here is a link to the video: <a href="https://www.youtube.com/watch?v=GPu1ax1Fga0&amp;t=2179s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=GPu1ax1Fga0&amp;t=2179s</a></p> <p>Link to the github for the source code: <a href="https://github.com/mattfrances/FoodAppUI" rel="nofollow noreferrer">https://github.com/mattfrances/FoodAppUI</a></p> <p>This is the code for the FlatList</p> <pre><code> &lt;View style={styles.categoriesWrapper}&gt; &lt;Text style={styles.categoriesTitle}&gt;Categories&lt;/Text&gt; &lt;View style={styles.categoriesListWrapper}&gt; &lt;FlatList data={categoriesData} renderItem={renderCategoryItem} keyExtractor={(item) =&gt; item.id} horizontal={true} /&gt; &lt;/View&gt; &lt;/View&gt; </code></pre> <p>Here is the renderCategoryItem code:</p> <pre><code>const renderCategoryItem = ({ item }) =&gt; { return ( &lt;View style={[ styles.categoryItemWrapper, { backgroundColor: item.selected ? colors.primary : colors.white, marginLeft: item.id == 1 ? 20 : 0, }, ]}&gt; &lt;Image source={item.image} style={styles.categoryItemImage} /&gt; &lt;Text style={styles.categoryItemTitle}&gt;{item.title}&lt;/Text&gt; &lt;View style={[ styles.categorySelectWrapper, { backgroundColor: item.selected ? colors.white : colors.secondary, }, ]}&gt; &lt;Feather name=&quot;chevron-right&quot; size={8} style={styles.categorySelectIcon} color={item.selected ? colors.black : colors.white} /&gt; &lt;/View&gt; &lt;/View&gt; ); }; </code></pre> <p>Any help would be greatly appreciated!</p>
3
1,121
LLVM-C creating object file results in: "TargetMachine can't emit a file of this type"
<p>Trying to generate a very simple object file with LLVM-C. Unfortunately I'm still stuck on "TargetMachine can't emit a file of this type" tried reordering code and various things for CPU (x64-64, generic and LLVMGetHostCPUName()). Clearly something (hopefully obvious) is missing here.</p> <p>The code below is compiled with <code>clang -Wall -O2 test.c LLVM-C.dll -o test</code></p> <p>Output:</p> <pre><code>target: x86-64, [64-bit X86: EM64T and AMD64], 1, 1 triple: x86_64-pc-windows-msvc features: +sse2,+cx16,+sahf,-tbm,-avx512ifma,+sha,-gfni,-fma4,-vpclmulqdq,+prfchw,+bmi2,-cldemote,+fsgsbase,-ptwrite,+xsavec,+popcnt,+aes,-avx512bitalg,-movdiri,+xsaves,-avx512er,-avx512vnni,-avx512vpopcntdq,-pconfig,-clwb,-avx512f,+clzero,-pku,+mmx,-lwp,-rdpid,-xop,+rdseed,-waitpkg,-movdir64b,+sse4a,-avx512bw,+clflushopt,+xsave,-avx512vbmi2,+64bit,-avx512vl,-invpcid,-avx512cd,+avx,-vaes,+cx8,+fma,-rtm,+bmi,-enqcmd,+rdrnd,+mwaitx,+sse4.1,+sse4.2,+avx2,+fxsr,-wbnoinvd,+sse,+lzcnt,+pclmul,-prefetchwt1,+f16c,+ssse3,-sgx,-shstk,+cmov,-avx512vbmi,-avx512bf16,+movbe,+xsaveopt,-avx512dq,+adx,-avx512pf,+sse3 datalayout: e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128 error: (null) error: TargetMachine can't emit a file of this type </code></pre> <p>Module.txt:</p> <pre><code>; ModuleID = 'test' source_filename = "test" target datalayout = "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-pc-windows-msvc" define float @ftest() { ftest: ret float 0x401B333340000000 } </code></pre> <p>Code (test.c):</p> <pre><code>#include &lt;llvm-c/Core.h&gt; #include &lt;llvm-c/Analysis.h&gt; #include &lt;llvm-c/TargetMachine.h&gt; #include &lt;stdio.h&gt; int main(){ LLVMInitializeNativeTarget(); LLVMTargetRef target = LLVMGetFirstTarget(); printf("target: %s, [%s], %d, %d\n", LLVMGetTargetName(target), LLVMGetTargetDescription(target), LLVMTargetHasJIT(target), LLVMTargetHasTargetMachine(target)); printf("triple: %s\n", LLVMGetDefaultTargetTriple()); printf("features: %s\n", LLVMGetHostCPUFeatures()); LLVMTargetMachineRef machine = LLVMCreateTargetMachine(target, LLVMGetDefaultTargetTriple(), "generic", LLVMGetHostCPUFeatures(), LLVMCodeGenLevelDefault, LLVMRelocDefault, LLVMCodeModelDefault); LLVMContextRef context = LLVMContextCreate(); LLVMModuleRef module = LLVMModuleCreateWithNameInContext("test", context); LLVMSetTarget(module, LLVMGetDefaultTargetTriple()); LLVMTargetDataRef datalayout = LLVMCreateTargetDataLayout(machine); char* datalayout_str = LLVMCopyStringRepOfTargetData(datalayout); printf("datalayout: %s\n", datalayout_str); LLVMSetDataLayout(module, datalayout_str); LLVMDisposeMessage(datalayout_str); LLVMTypeRef f32 = LLVMFloatTypeInContext(context); LLVMTypeRef ftype = LLVMFunctionType(f32, 0, 0, 0); LLVMValueRef ftest = LLVMAddFunction(module, "ftest", ftype); LLVMBasicBlockRef bb = LLVMAppendBasicBlockInContext(context, ftest, "ftest"); LLVMBuilderRef builder = LLVMCreateBuilderInContext(context); LLVMPositionBuilderAtEnd(builder, bb); LLVMValueRef v1 = LLVMConstReal(f32, 2.5); LLVMValueRef v2 = LLVMConstReal(f32, 4.3); LLVMValueRef result = LLVMBuildFAdd(builder, v1, v2, "f-add"); LLVMBuildRet(builder, result); LLVMVerifyFunction(ftest, LLVMPrintMessageAction); char* errors = 0; LLVMPrintModuleToFile(module, "module.txt", &amp;errors); printf("error: %s\n", errors); LLVMDisposeMessage(errors); LLVMTargetMachineEmitToFile(machine, module, "result.o", LLVMObjectFile, &amp;errors); printf("error: %s\n", errors); LLVMDisposeMessage(errors); return 0; } </code></pre>
3
1,610
How to access SQLite database in androidRecyclerVIew?
<p>I've created a SQLite database which contains two columns: "title" and "content" and don't have any idea how to display it in my android RecyclerView with two textViews "card_title" and "card_content". please kindly help me with this. Here is my recycler adapter:</p> <pre><code>public class RecyclerAdapter extends RecyclerView.Adapter&lt;RecyclerAdapter.ViewHolder&gt; { private ClipboardManager myClipboard; private ClipData myClip; private Context context; public List&lt;CardItemModel&gt; cardItems; public RecyclerAdapter(List&lt;CardItemModel&gt; cardItems){ this.cardItems = cardItems; } public static class ViewHolder extends RecyclerView.ViewHolder{ ImageView copyButton; ImageView shareButton; ToggleButton favButton; TextView title; TextView content; public ViewHolder(View itemView) { super(itemView); this.title = (TextView)itemView.findViewById(R.id.card_title); this.content = (TextView)itemView.findViewById(R.id.card_content); this.copyButton= (ImageView) itemView.findViewById(R.id.copyButton); this.shareButton=(ImageView) itemView.findViewById(R.id.shareButton); this.favButton=(ToggleButton) itemView.findViewById(R.id.favButton); favButton.setChecked(false); favButton.setBackgroundDrawable(ContextCompat.getDrawable(favButton.getContext(), R.mipmap.ic_launcher)); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item,parent,false); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.title.setText(cardItems.get(position).title); holder.content.setText(cardItems.get(position).content); holder.copyButton.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ myClipboard = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE); myClip = ClipData.newPlainText("label", holder.content.getText().toString()); myClipboard.setPrimaryClip(myClip); Toast.makeText(v.getContext(), "Copied to clipboard" , Toast.LENGTH_SHORT ).show(); } }); holder.shareButton.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ Intent share = new Intent(Intent.ACTION_SEND); share.setType("text/plain"); share.putExtra(Intent.EXTRA_TEXT, holder.content.getText().toString()); v.getContext().startActivity(Intent.createChooser(share, "Share Text")); } }); holder.favButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton favButton, boolean isChecked){ if (isChecked) favButton.setBackgroundDrawable(ContextCompat.getDrawable(favButton.getContext(),R.mipmap.ic_launcher)); else favButton.setBackgroundDrawable(ContextCompat.getDrawable(favButton.getContext(), R.mipmap.ic_cart)); } }); } @Override public int getItemCount() { return cardItems.size(); } } </code></pre>
3
1,500
XSLT element selection based on Choose not working
<p>I have the following XML:</p> <pre><code>&lt;Document&gt; &lt;Row&gt; &lt;KEY&gt;NIKE|JB|APPAREL|MENS&lt;/KEY&gt; &lt;Period&gt;Nov-21&lt;/Period&gt; &lt;/Row&gt; &lt;Row&gt; &lt;KEY&gt;FASCINATE|JB|ACCESSORIES|LADIES&lt;/KEY&gt; &lt;Matches&gt; &lt;Row&gt; &lt;KEY&gt;FASCINATE|JB|ACCESSORIES|LADIES&lt;/KEY&gt; &lt;Period&gt;Nov-22&lt;/Period&gt; &lt;/Row&gt; &lt;/Matches&gt; &lt;/Row&gt; &lt;/Document&gt; </code></pre> <p>I want to use XSLT to return the nested <code>/Matches/Row/Period</code> when the <code>Document/Row/Period</code> is undefined (as it is in the second <code>Row</code> of the XML)</p> <p>So I have the following XSLT:</p> <pre><code>&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot; xmlns:ns=&quot;http://exampleincludednamespace.com/&quot; exclude-result-prefixes=&quot;ns&quot;&gt; &lt;xsl:output method=&quot;xml&quot; omit-xml-declaration=&quot;yes&quot; /&gt; &lt;xsl:template match=&quot;/&quot;&gt; &lt;Document&gt; &lt;xsl:for-each select=&quot;/Document/Row&quot;&gt; &lt;xsl:variable name=&quot;period&quot; select=&quot;/Period&quot; /&gt; &lt;xsl:choose&gt; &lt;xsl:when test=&quot;$period = null&quot;&gt; &lt;xsl:copy&gt; &lt;xsl:copy-of select=&quot;KEY | /Matches/Row/Period&quot; /&gt; &lt;/xsl:copy&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:copy&gt; &lt;xsl:copy-of select=&quot;KEY | Period&quot; /&gt; &lt;/xsl:copy&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:for-each&gt; &lt;/Document&gt; &lt;/xsl:template&gt; </code></pre> <p>&lt;/xsl:stylesheet&gt;</p> <p>But it returns the following output:</p> <pre><code>&lt;Document&gt; &lt;Row&gt; &lt;KEY&gt;NIKE|JB|APPAREL|MENS&lt;/KEY&gt; &lt;Period&gt;Nov-21&lt;/Period&gt; &lt;/Row&gt; &lt;Row&gt; &lt;KEY&gt;FASCINATE|JB|ACCESSORIES|LADIES&lt;/KEY&gt; &lt;/Row&gt; &lt;/Document&gt; </code></pre> <p>(Note how it is not returning the nested <code>/Matches/Row/Period</code> in the second <code>/Row</code>.</p> <p>I expect to get the following output:</p> <pre><code>&lt;Document&gt; &lt;Row&gt; &lt;KEY&gt;NIKE|JB|APPAREL|MENS&lt;/KEY&gt; &lt;Period&gt;Nov-21&lt;/Period&gt; &lt;/Row&gt; &lt;Row&gt; &lt;KEY&gt;FASCINATE|JB|ACCESSORIES|LADIES&lt;/KEY&gt; &lt;Period&gt;Nov-22&lt;/Period&gt; &lt;/Row&gt; &lt;/Document&gt; </code></pre> <p>What am I doing wrong?</p>
3
1,533
Visual Studio 2019 Xamarin Forms Google Ads - Build Problem
<p>I have had an issue for weeks after upgrading to the latest VS2019 and XF versions. Along the way, I have moved from VS 16.3.2 to .5 with no fix. It displays "Unexpected Element found in - AndroidManifest.xml - Line 14. I have also updated many of the NuGet packages and performed clean/build many times. Any ideas?</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.linkemupllc.NYWineryHopper" android:installLocation="auto" android:versionName="release-2.01.02" android:versionCode="20102"&gt; &lt;uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.CALL_PHONE" /&gt; &lt;uses-permission android:name="android.permission.LOCATION_HARDWARE" /&gt; &lt;supports-screens android:largeScreens="true" android:xlargeScreens="true" /&gt; &lt;activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" /&gt; &lt;application android:label="NYWineryHopper.Android" android:icon="@drawable/icon" android:name="android.support.multidex.MultiDexApplication" android:allowBackup="true" android:debuggable="true"&gt; &lt;activity android:icon="@mipmap/icon" android:label="NYWineryHopper" android:screenOrientation="portrait" android:theme="@style/MainTheme" android:name="md5c4b3563624aac5beb34a83ad25365fc4.MainActivity"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;service android:name="md5dcb6eccdc824e0677ffae8ccdde42930.KeepAliveService" /&gt; &lt;receiver android:enabled="true" android:exported="false" android:label="Essentials Battery Broadcast Receiver" android:name="md5d630c3d3bfb5f5558520331566132d97.BatteryBroadcastReceiver" /&gt; &lt;receiver android:enabled="true" android:exported="false" android:label="Essentials Energy Saver Broadcast Receiver" android:name="md5d630c3d3bfb5f5558520331566132d97.EnergySaverBroadcastReceiver" /&gt; &lt;receiver android:enabled="true" android:exported="false" android:label="Essentials Connectivity Broadcast Receiver" android:name="md5d630c3d3bfb5f5558520331566132d97.ConnectivityBroadcastReceiver" /&gt; &lt;provider android:authorities="com.linkemupllc.NYWineryHopper.fileProvider" android:exported="false" android:grantUriPermissions="true" android:name="xamarin.essentials.fileProvider"&gt; &lt;meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/xamarin_essentials_fileprovider_file_paths" /&gt; &lt;/provider&gt; &lt;receiver android:enabled="true" android:exported="false" android:name="md51558244f76c53b6aeda52c8a337f2c37.PowerSaveModeBroadcastReceiver" /&gt; &lt;provider android:name="mono.android.MultiDexLoader" android:exported="false" android:initOrder="1999999999" android:authorities="com.linkemupllc.NYWineryHopper.mono.android.MultiDexLoader.__mono_init__" /&gt; &lt;provider android:name="mono.MonoRuntimeProvider" android:exported="false" android:initOrder="1999999998" android:authorities="com.linkemupllc.NYWineryHopper.mono.MonoRuntimeProvider.__mono_init__" /&gt; &lt;!--suppress ExportedReceiver--&gt; &lt;receiver android:name="mono.android.Seppuku"&gt; &lt;intent-filter&gt; &lt;action android:name="mono.android.intent.action.SEPPUKU" /&gt; &lt;category android:name="mono.android.intent.category.SEPPUKU.com.linkemupllc.NYWineryHopper" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;!-- Include the AdActivity and InAppPurchaseActivity configChanges and themes. --&gt; &lt;activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:exported="false" android:theme="@android:style/Theme.Translucent" /&gt; &lt;provider android:name="com.google.android.gms.ads.MobileAdsInitProvider" android:authorities="com.linkemupllc.NYWineryHopper.mobileadsinitprovider" android:exported="false" android:initOrder="100" /&gt; &lt;meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /&gt; &lt;/application&gt; &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt; &lt;/manifest&gt; </code></pre>
3
1,874
Unable to startActivity from BottomSheetDialog
<p>every thing works fine with this context <code>ctw = ContextThemeWrapper(cont, R.style.AppTheme)</code> but when i want to start any activity my app is crashing. actually this ctw works fine with Toast in this method but when i pass this ctw to Intent for starting activity is gives error. i also trying cont variable directly getApplicationContext also but still have same error. code is in kotlin you can help me in java also. :)</p> <p>Here is complete code</p> <pre><code>fun showBottomSheetDialog(url: String, cont: Context) { ctw = ContextThemeWrapper(cont, R.style.AppTheme) val lin_play: LinearLayout val lin_cancel: LinearLayout dialog = BottomSheetDialog(ctw!!) dialog.setContentView(R.layout.dialog_bottom_dailymotion) dialog.getWindow()!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) dialog.getWindow()!!.setBackgroundDrawableResource(R.color.Transparent) lin_play = dialog.findViewById(R.id.lin_play_d)!! lin_cancel = dialog.findViewById(R.id.lin_cancel_d)!! lin_play.setOnClickListener { if (TextUtils.isEmpty(url)) { Toast.makeText(ctw, "Invalid/Empty URL", Toast.LENGTH_SHORT).show() } else { if (!url!!.isEmpty()) { startActivity(Intent(ctw, MainActivity::class.java).putExtra("url", url)) dialog.dismiss() } } } lin_cancel.setOnClickListener { dialog.dismiss() } try { dialog.show() }catch (e:Exception){ e.printStackTrace() } } </code></pre> <p>and here is my error</p> <pre><code>E/AndroidRuntime: FATAL EXCEPTION: main Process: com.browserforvideodownload, PID: 29839 java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference at android.app.Activity.startActivityForResult(Activity.java:4367) at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54) at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:68) at android.app.Activity.startActivityForResult(Activity.java:4312) at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:751) at android.app.Activity.startActivity(Activity.java:4716) at android.app.Activity.startActivity(Activity.java:4631) at com.browserforvideodownload.browserlighting.browser.activity.BrowserActivity$showBottomSheetDialogDailymotion$1.onClick(BrowserActivity.kt:3970) at android.view.View.performClick(View.java:5740) at android.view.View$PerformClick.run(View.java:22947) at android.os.Handler.handleCallback(Handler.java:836) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:232) at android.app.ActivityThread.main(ActivityThread.java:6661) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1106) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967) </code></pre> <p><strong>Edit:</strong></p> <p>After a long Struggle i have found my mistke.</p> <p>just replace</p> <pre><code> startActivity(Intent(ctw, MainActivity::class.java).putExtra("url", url)) </code></pre> <p>into</p> <pre><code>try{ ctw!!.startActivity(Intent(getActivity(ctw), MainActivity::class.java).putExtra("url", url)) }catch (e:Exception){ e.printStackTrace() } </code></pre>
3
1,643
Optimize Excel VBA Macro for Copy-PasteValues
<p>I'm new in Excel-VBA and I need to improve my macro performance. I have a macro that searches an excel, opens it, then goes through every sheet and copy-pastevalues for all cell with a specific color (yellow). Finally saves and closes the excel. In addition, excels sheets are locked and only those yellow cells are editable. This should be done for a list of excel that I indicate in a main template from where I call the macro. The problem is that it takes a lot of time and even gets blocked when the number of excels is more than 3.</p> <p>I paste my code below and hope anyone can help. Thanks!</p> <pre><code>Sub Button1_Click() Application.ScreenUpdating = False Application.DisplayAlerts = False Dim filePath As String Dim rng As Range Dim cel As Range Dim cartera As String Dim plantilla As String Dim wb As Workbook Dim ws As Worksheet Dim obj_Cell As Range filePath = Application.ThisWorkbook.Path Range(&quot;B9&quot;).Select Set rng = Application.Range(Selection, Selection.End(xlDown)) For Each cel In rng.Cells cartera = cel.Value plantilla = cel.Offset(0, 1).Value If cartera = vbNullString Or plantilla = vbNullString Then GoTo Saltar End If Application.StatusBar = &quot;Ejecutando Cartera: &quot; &amp; cartera &amp; &quot;, Plantilla: &quot; &amp; plantilla Set wb = Workbooks.Open(filePath &amp; &quot;\&quot; &amp; cartera &amp; &quot;\&quot; &amp; plantilla, UpdateLinks:=3) For Each ws In wb.Worksheets If ws.Name &lt;&gt; &quot;Index&quot; And ws.Name &lt;&gt; &quot;Instructions&quot; And ws.Name &lt;&gt; &quot;Glossary&quot; Then Worksheets(ws.Name).Activate For Each obj_Cell In Range(&quot;A1:DW105&quot;) With obj_Cell If obj_Cell.Interior.Color = RGB(255, 255, 153) Then obj_Cell.Select If obj_Cell.MergeCells = True Then obj_Cell.MergeArea.Select End If Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=True, Transpose:=False If obj_Cell.MergeCells = True Then If obj_Cell.MergeArea(1).Value = vbNullString Then obj_Cell.MergeArea.Cells(1, 1).Select Selection.ClearContents End If Else If obj_Cell.Value = vbNullString Then obj_Cell.ClearContents End If End If End If End With Next obj_Cell Range(&quot;A1&quot;).Select End If Next ws Sheets(1).Select wb.Close SaveChanges:=True Saltar: Next cel Application.ScreenUpdating = True Application.DisplayAlerts = True Application.StatusBar = False End Sub </code></pre>
3
1,705
My App is giving the "Register Error 1" - why so?
<p>i am trying to write a class that would collect data from the registration form and send it to an online database, i am doing that through volley, but i keep getting the same error "Registration Error 1", I already checking my database connection and the PHP Registration code and it is okay. i think the problem is from this class. The error now has changed. Now i am getting a "Registration Error 2"</p> <pre><code>private void Register () { loading.setVisibility (View.VISIBLE); signUpBtn.setVisibility (View.GONE); final String firstName = this.firstName.getText ().toString ().trim (); final String lastName = this.lastName.getText ().toString ().trim (); final String userEmail = this.userEmail.getText ().toString ().trim (); final String userPassword = this.userPassword.getText ().toString ().trim (); final String name = firstName + " " + lastName; StringRequest stringRequest = new StringRequest (Request.Method.POST, URL_REGIST, new Response.Listener&lt;String&gt; () { @Override public void onResponse (String response) { try { JSONObject jsonObject = new JSONObject (response); String success = jsonObject.getString ("success"); if (success.equals ("1")) { Toast.makeText (Registration.this, "Registration Successful", Toast.LENGTH_SHORT).show (); } } catch(JSONException e) { e.printStackTrace (); Toast.makeText (Registration.this, "Registration Error 1!", Toast.LENGTH_SHORT).show (); loading.setVisibility (View.GONE); signUpBtn.setVisibility (View.VISIBLE); } } }, new Response.ErrorListener () { @Override public void onErrorResponse (VolleyError error) { Toast.makeText (Registration.this, "Registration Error 2!", Toast.LENGTH_SHORT).show (); loading.setVisibility (View.GONE); signUpBtn.setVisibility (View.VISIBLE); } }) { @Override protected Map&lt;String, String&gt; getParams () throws AuthFailureError { Map&lt;String, String&gt; params = new HashMap&lt;&gt; (); params.put ("name", name); params.put ("userEmail", userEmail); params.put ("userPassword", userPassword); return super.getParams (); } }; RequestQueue requestQueue = Volley.newRequestQueue (this); requestQueue.add (stringRequest); } </code></pre> <p>i checked the logcat and this is what i am getting. 2019-09-23 12:05:46.354 26011-26011/com.scoutfrika.scoutfrika W/IInputConnectionWrapper: getSelectedText on inactive InputConnection</p> <p>2019-09-23 12:05:48.514 26011-26011/com.scoutfrika.scoutfrika W/IInputConnectionWrapper: getSelectedText on inactive InputConnection</p> <p>2019-09-23 12:05:51.422 26011-26011/com.scoutfrika.scoutfrika W/IInputConnectionWrapper: getSelectedText on inactive InputConnection</p> <p>2019-09-23 12:05:52.032 26011-26011/com.scoutfrika.scoutfrika W/IInputConnectionWrapper: getSelectedText on inactive InputConnection 2019-09-23 12:05:56.446 1912-26100/? E/FA: Name must consist of letters, digits or _ (underscores). Type, name: event, isNetworkConnected:false</p> <p>2019-09-23 12:05:56.449 1912-26100/? E/FA: Invalid public event name. Event will not be logged (FE): isNetworkConnected:false</p> <p>2019-09-23 12:05:57.206 26011-26011/com.scoutfrika.scoutfrika W/IInputConnectionWrapper: getSelectedText on inactive InputConnection</p> <p>2019-09-23 12:05:59.335 1912-26100/? E/FA: Name must consist of letters, digits or _ (underscores). Type, name: event, isNetworkConnected:false</p> <p>2019-09-23 12:05:59.337 1912-26100/? E/FA: Invalid public event name. Event will not be logged (FE): isNetworkConnected:false</p>
3
1,674
Need help getting OneToMany association from ManyToOne
<p>Let me start off by saying I asked a similar question before and got it answered. I tried using those principles here but I'm stuck again am am not sure where to go from here. </p> <p>I have a page where I list out all the 'products' along with their respected id's, price, and name. On this same page I want to get a description I created for each of them. Description is its own entity and has it's own controller. </p> <p>In my <code>ProductController</code>, within my <code>indexAction</code>, I'm trying to get the description to appear here. </p> <p>The problem is, I don't reference an id within <code>indexAction</code> (I use findAll). I have tried to loop through all products and reference using <code>$key</code> but I either get the most recent description entered in description or currently:</p> <p><em>Error: Call to a member function getDescriptions() on a non-object.</em></p> <p>EDIT: I should mention $prodEnt is null...</p> <p>I didn't want to come here for help but I have no more thoughts on how to go about getting what I want. </p> <p>Here is <code>ProductController</code> with <code>indexAction</code>:</p> <pre><code>namespace Pas\ShopTestBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Pas\ShopTestBundle\Entity\Product; use Pas\ShopTestBundle\Form\ProductType; /** * Product controller. * * @Route("/product") */ class ProductController extends Controller { /** * Lists all Product entities. * * @Route("/", name="product") * @Method("GET") * @Template() */ public function indexAction() { $em = $this-&gt;getDoctrine()-&gt;getManager(); $entities = $em-&gt;getRepository('PasShopTestBundle:Product')-&gt;findAll(); //$entities = $em-&gt;getRepository('PasShopTestBundle:Product')-&gt;find($id); //var_dump($entities); //dump($entities); die; if (!$entities) { throw $this-&gt;createNotFoundException('Error Nothing in Entities.'); } else { //dump($entities); die; foreach ($entities as $key =&gt; $entity) { //dump($entities); die; //dump($entity); die; //dump($key); die; //needs to be 1 //$entity = $em-&gt;getRepository('PasShopTestBundle:Product')-&gt;findAll($key); $prodEnt = $em-&gt;getRepository('PasShopTestBundle:Product')-&gt;find($key); //dump($entity); die; //dump($prodEnt); die; $descriptions = $prodEnt-&gt;getDescriptions(); //dump($entity); die; } //dump($entities); die; } return array( 'descriptions' =&gt; $descriptions, 'entities' =&gt; $entities, 'entity' =&gt; $entity, ); } </code></pre> <p>Here is <code>indexAction</code>s Route twig file:</p> <pre><code>{% extends '::base.html.twig' %} {% block body -%} &lt;h1&gt;Product List&lt;/h1&gt; &lt;table class="records_list"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Id&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;th&gt;Quantity&lt;/th&gt; &lt;th&gt;Description&lt;/th&gt; &lt;th&gt;Actions&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {% for entity in entities %} &lt;tr&gt; &lt;td&gt;&lt;a href="{{ path('product_show', { 'id': entity.id }) }}"&gt;{{ entity.id }}&lt;/a&gt;&lt;/td&gt; &lt;td&gt;{{ entity.name }}&lt;/td&gt; &lt;td&gt;{{ entity.price }}&lt;/td&gt; &lt;td&gt;{{ entity.quantity }}&lt;/td&gt; {% for key, entity in descriptions %} &lt;pre&gt;{{ dump(entity) }}&lt;/pre&gt; {# &lt;pre&gt;{{ dump(key) }}&lt;/pre&gt; #} &lt;td&gt;{{ entity.productDesciption }}&lt;/td&gt; &lt;pre&gt;{{ dump(entity.productDesciption) }}&lt;/pre&gt; {% endfor %} &lt;td&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="{{ path('product_cart', { 'id': entity.id }) }}"&gt;Add Product To Cart&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="{{ path('product_show', { 'id': entity.id }) }}"&gt;show&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="{{ path('product_edit', { 'id': entity.id }) }}"&gt;edit&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; &lt;/table&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="{{ path('product_new') }}"&gt; Create a new entry &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; {% endblock %} </code></pre> <p>Product Entity:</p> <pre><code>namespace Pas\ShopTestBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; /** * Product * * @ORM\Table(name="products") * @ORM\Entity(repositoryClass="Pas\ShopTestBundle\Entity\ProductRepository") */ class Product { /** * @var ArrayCollection * * @ORM\OneToMany(targetEntity="Description", mappedBy="product") */ private $descriptions; </code></pre> <p>Description Entity:</p> <pre><code>namespace Pas\ShopTestBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collection\ArrayCollection; /** * Description * * @ORM\Table(name="descriptions") * @ORM\Entity(repositoryClass="Pas\ShopTestBundle\Entity\DescriptionRepository") */ class Description { /** * @var string * * @ORM\Column(name="name", type="string") */ private $productDescription; /** * @var Product * * @ORM\ManyToOne(targetEntity="Product", inversedBy="descriptions") * @ORM\JoinColumn(name="product_id", referencedColumnName="id") */ private $product; </code></pre> <p>Any help is really appreciated, Thanks!</p>
3
3,198
registers with the verification email , but when submitted insert double data
<p>still continue the project which I've posted . a bit of trouble on registering with a verification email . currently running normally: registers the verification email, sents to the email destination. but I see there are two inserts with the same data (as submitted) in the database. Is there anything wrong with my script ?</p> <p>this my controllers </p> <pre><code>function submit() { $_POST['dob'] = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day']; $firstname = $this-&gt;input-&gt;post('firstname'); $lastname = $this-&gt;input-&gt;post('lastname'); $password = $this-&gt;input-&gt;post('password'); $email = $this-&gt;input-&gt;post('email'); $dob = $this-&gt;input-&gt;post('dob'); $jkl = $this-&gt;input-&gt;post('jkl'); $lastlogin = $this-&gt;input-&gt;post('lastlogin'); $data = array( 'firstname' =&gt; $firstname, 'lastname' =&gt; $lastname, 'password' =&gt; $password, 'email' =&gt; $email, 'dob' =&gt; $dob, 'jkl' =&gt; $jkl, 'lastlogin' =&gt; $lastlogin, 'active' =&gt; 0 ); $this-&gt;m_register-&gt;add_account($data); $id = $this-&gt;m_register-&gt;add_account($data); $encrypted_id = md5($id); $this-&gt;load-&gt;library('email'); $config = Array( 'protocol' =&gt; 'smtp', 'smtp_host' =&gt; 'ssl://smtp.gmail.com', 'smtp_port' =&gt; 465, 'smtp_user' =&gt; '*******@*****.com ', 'smtp_pass' =&gt; '**********', 'mailtype' =&gt; 'html', 'charset' =&gt; 'utf-8', 'wordwrap' =&gt; TRUE ); $this-&gt;load-&gt;library('email', $config); $this-&gt;email-&gt;set_newline("\r\n"); $email_setting = array('mailtype'=&gt;'html'); $this-&gt;email-&gt;initialize($email_setting); $this-&gt;email-&gt;from('*****@******.COM', 'RRR'); $this-&gt;email-&gt;to($email); $this-&gt;email-&gt;subject('Confirmation Email'); $this-&gt;email-&gt;message("WELCOME TO RRRR &lt;br&gt;&lt;p&gt;&lt;/p&gt;Hallo $firstname $lastname &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;p&gt;Terimakasih telah melakuan registrasi dengan:&lt;br&gt;&lt;br&gt;&lt;p&gt; Username = $email&lt;p&gt; Password = $password &lt;br&gt;&lt;br&gt; &lt;p&gt; untuk memverifikasi akun silahkan klik tautan dibawah ini&lt;/p&gt;&lt;br&gt;&lt;br&gt;" .site_url("login/register/verification/$encrypted_id")." &lt;br&gt;&lt;br&gt;&lt;br&gt; &lt;p&gt;&lt;/p&gt;&lt;br&gt; &lt;p&gt;Thanks&lt;/p&gt;Admin "); if($this-&gt;email-&gt;send()) { $data = array ( 'isi' =&gt; 'login/vsuccess'); $this-&gt;load-&gt;view('layout/wrapper',$data); }else { $data = array ( 'isi' =&gt; 'login/vgagal'); $this-&gt;load-&gt;view('layout/wrapper',$data); } } </code></pre> <p>this my models</p> <pre><code> function add_account($data){ $this-&gt;load-&gt;database(); $this-&gt;db-&gt;insert('user',$data); return mysql_insert_id(); } </code></pre>
3
1,763
i want to keep show social icon with js
<p>i have js script for button when i click it show social icon and when i click back its hide. but i want to keep show all social icons. below is my js scipt.`// Bind the social button to show/hide the social icons box</p> <pre><code> $('#social-pop-out-trigger').click(function() { var $allBoxes = $('.footer-pop-out-box'); if ($allBoxes.is(':animated')) { return false; } var $thisBox = $('.social-pop-out-box'); if ($thisBox.is(':visible')) { $thisBox.slideUp(); } else { if ($allBoxes.is(':visible')) { $allBoxes.filter(':visible').slideUp(function() { $thisBox.slideDown(); }); } else { $thisBox.slideDown(); } } return false; }); </code></pre> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('#social-pop-out-trigger').click(function() { var $allBoxes = $('.footer-pop-out-box'); if ($allBoxes.is(':animated')) { return false; } var $thisBox = $('.social-pop-out-box'); if ($thisBox.is(':visible')) { $thisBox.slideUp(); } else { if ($allBoxes.is(':visible')) { $allBoxes.filter(':visible').slideUp(function() { $thisBox.slideDown(); }); } else { $thisBox.slideDown(); } } return false; });</code></pre> </div> </div> </p> <pre><code> $('#social-pop-out-trigger').click(function() { var $allBoxes = $('.footer-pop-out-box'); if ($allBoxes.is(':animated')) { return false; } var $thisBox = $('.social-pop-out-box'); if ($thisBox.is(':visible')) { $thisBox.slideUp(); } else { if ($allBoxes.is(':visible')) { $allBoxes.filter(':visible').slideUp(function() { $thisBox.slideDown(); }); } else { $thisBox.slideDown(); } } return false; });` </code></pre>
3
1,078
How to draw Color Bands in Flex Chart?
<p>I want to draw a custom background in my flex chart with vertical axis is linear and horizontal axis is category. In background i want to shade the regions according to data given by user. I tried CartesianDataCanvas and gridlines in chart backgroundelements but not getting a good solution. Anyone have an idea? i prefer using script without mxml. Thanks in advance..</p> <p>I am adding my code to show the issue i faced while using CartesianDataCanvas. It is working perfectly in Area chart, but i want to draw in Bubble chart. As bubble series is not starting from the begining of horizontal category axis, CartesianDataCanvas start drawing from the mid point of the first bubble. But i am trying to draw the rectangle in the whole width of chart.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" &gt; &lt;fx:Script&gt;&lt;![CDATA[ import mx.charts.ChartItem; import mx.charts.LinearAxis; import mx.charts.chartClasses.CartesianCanvasValue; import mx.charts.chartClasses.CartesianTransform; import mx.charts.series.items.ColumnSeriesItem; import mx.collections.ArrayCollection; import mx.containers.Box; import mx.containers.HBox; import mx.controls.Alert; import mx.core.INavigatorContent; import mx.events.FlexEvent; [Bindable] public var profits:ArrayCollection = new ArrayCollection([ {Month:'jan', Profit:130}, {Month:'feb', Profit:75}, {Month:'mar', Profit:110}, {Month:'apr', Profit:300} ]); [Bindable] public var ratios:Array=['25','25','25','50']; [Bindable] public var colors:Array=['0xff0000','0x00ff00','0x0000ff','0xc0c0c0'] private function draw():void { canvas.clear(); canvas2.clear(); if(colors.length==ratios.length){ var canvasWidth = canvas.width; var canvasHeight = canvas.height; var sumRatio:Number=getSum(ratios); var nextMax:Number=0; for(var j:int=0, colnum:int=colors.length-1;j&lt;colors.length;j++,colnum--){ canvas.beginFill(uint(colors[colnum])); canvas2.beginFill(uint(colors[colnum])); var minPt:Array; var minimumPoint:Point; if(j==0){ minimumPoint=new Point(0,0); }else{ minimumPoint=new Point(0, canvasHeight*nextMax); } minPt= canvas.localToData(minimumPoint); var division:Number=Number(ratios[colnum])/sumRatio; var maxPt:Array = canvas.localToData(new Point(canvasWidth,minimumPoint.y+canvasHeight*division)); nextMax+=division; canvas.drawRect(minPt[0], maxPt[1], maxPt[0], minPt[1]); canvas.endFill(); canvas2.drawRect(minPt[0], maxPt[1], maxPt[0], minPt[1]); canvas2.endFill(); } } } private function getSum(array:Array):Number{ var sum:Number=0; for(var i:int=0;i&lt;array.length;i++){ if(!isNaN(Number(array[i]))){ sum+=Number(array[i]); } } return sum; } ]]&gt;&lt;/fx:Script&gt; &lt;s:HGroup&gt; &lt;mx:AreaChart id="myChart" showDataTips="true" dataProvider="{profits}" selectionMode="single" creationComplete="draw()" &gt; &lt;mx:annotationElements&gt; &lt;mx:CartesianDataCanvas id="canvas" alpha="0.2" includeInRanges="true"/&gt; &lt;/mx:annotationElements&gt; &lt;mx:horizontalAxis&gt; &lt;mx:CategoryAxis dataProvider="{profits}" categoryField="Month" /&gt; &lt;/mx:horizontalAxis&gt; &lt;mx:series&gt; &lt;mx:AreaSeries id="series1" xField="Month" yField="Profit" displayName="Profit" selectable="true" &gt; &lt;/mx:AreaSeries&gt; &lt;/mx:series&gt; &lt;/mx:AreaChart&gt; &lt;mx:Legend dataProvider="{myChart}"/&gt; &lt;mx:BubbleChart id="mybubChart" showDataTips="true" dataProvider="{profits}" selectionMode="single" creationComplete="draw()" &gt; &lt;mx:annotationElements&gt; &lt;mx:CartesianDataCanvas id="canvas2" alpha="0.2" includeInRanges="true"/&gt; &lt;/mx:annotationElements&gt; &lt;mx:horizontalAxis&gt; &lt;mx:CategoryAxis dataProvider="{profits}" categoryField="Month" /&gt; &lt;/mx:horizontalAxis&gt; &lt;mx:series&gt; &lt;mx:BubbleSeries id="series2" xField="Month" yField="Profit" radiusField="Profit" displayName="Profit" selectable="true" &gt; &lt;mx:fill&gt; &lt;mx:SolidColor color="0x663399"/&gt; &lt;/mx:fill&gt; &lt;/mx:BubbleSeries&gt; &lt;/mx:series&gt; &lt;/mx:BubbleChart&gt; &lt;mx:Legend dataProvider="{mybubChart}"/&gt; &lt;/s:HGroup&gt; &lt;/s:Application&gt; </code></pre>
3
3,393
Remove duplicate rows where col1 and col2 are equal but reversed
<p>I have a query that has the following results. How can I modify this query to remove duplicate rows. In this case, the duplicates would be &quot;row1.antecedent = row2.consequent and row2.antecedent= row1.consequent&quot;. I only need one such row, not both in my results. Also, this logic has to be directly added in the query, not the encompassing programming language.</p> <p><a href="https://i.stack.imgur.com/CAU5m.png" rel="nofollow noreferrer">Query Results</a></p> <p>So let's assume this my table with the data as shown. I would like to select rows from this table such that only rows with rule_id = 943,945 and 979 are selected. That's because 944 gives me same results as 943; 946 is same as 945 and 980 is same as 979, except with the antecedent and consequent reversed. Please ignore the value CONF. That would be different.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>RULE_ID</th> <th>ANTECEDENT</th> <th>CONSEQUENT</th> <th>SUPP</th> <th>CONF</th> <th>LIFT</th> </tr> </thead> <tbody> <tr> <td>943</td> <td>3017</td> <td>3014</td> <td>0.69%</td> <td>65.59%</td> <td>55.78</td> </tr> <tr> <td>944</td> <td>3014</td> <td>3017</td> <td>0.69%</td> <td>58.46%</td> <td>55.78</td> </tr> <tr> <td>945</td> <td>3018</td> <td>3014</td> <td>0.81%</td> <td>55.60%</td> <td>47.29</td> </tr> <tr> <td>946</td> <td>3014</td> <td>3018</td> <td>0.81%</td> <td>68.86%</td> <td>47.29</td> </tr> <tr> <td>979</td> <td>3055</td> <td>3015</td> <td>0.62%</td> <td>60.35%</td> <td>68.9</td> </tr> <tr> <td>980</td> <td>3015</td> <td>3055</td> <td>0.62%</td> <td>70.30%</td> <td>68.9</td> </tr> </tbody> </table> </div> <p>UPDATED QUERY - THIS WORKS</p> <pre><code>select * from ( SELECT RULE_ID, A.ATTRIBUTE_SUBNAME ANTECEDENT, C.ATTRIBUTE_SUBNAME CONSEQUENT, CONCAT(TO_CHAR(RULE_SUPPORT*100,'990.99'),'%') Support_Frequency, CONCAT(TO_CHAR(RULE_CONFIDENCE*100,'990.99'),'%') Confidence_Association, ROUND(RULE_LIFT, 2) Lift_Likelyhood FROM TABLE(DBMS_DATA_MINING.GET_ASSOCIATION_RULES('AR_SH_SAMPLE')) T, TABLE(T.CONSEQUENT) C, TABLE(T.ANTECEDENT) A ) where rule_id in ( select min(rule_id) from ( SELECT RULE_ID, A.ATTRIBUTE_SUBNAME ANTECEDENT, C.ATTRIBUTE_SUBNAME CONSEQUENT, CONCAT(TO_CHAR(RULE_SUPPORT*100,'990.99'),'%') Support_Frequency, CONCAT(TO_CHAR(RULE_CONFIDENCE*100,'990.99'),'%') Confidence_Association, ROUND(RULE_LIFT, 2) Lift_Likelyhood, (CASE WHEN A.ATTRIBUTE_SUBNAME &gt; C.ATTRIBUTE_SUBNAME THEN CONCAT(A.ATTRIBUTE_SUBNAME,C.ATTRIBUTE_SUBNAME) WHEN C.ATTRIBUTE_SUBNAME &gt; A.ATTRIBUTE_SUBNAME THEN CONCAT(C.ATTRIBUTE_SUBNAME,A.ATTRIBUTE_SUBNAME) END) CAT FROM TABLE(DBMS_DATA_MINING.GET_ASSOCIATION_RULES('AR_SH_SAMPLE')) T, TABLE(T.CONSEQUENT) C, TABLE(T.ANTECEDENT) A ) group by CAT ) ORDER BY RULE_ID </code></pre>
3
1,317
Error while compiling with clang/clang++ [-Werror,-Wrange-loop-constrcut]
<p>I'm trying to build a c++ project. While doing so with g++ the project compiles fine. However if I try to compile with clang I get the error:</p> <pre><code>ec_read_plan.h:135:19: error: loop variable 'op' creates a copy from type 'const std::pair&lt;ChunkPartType, ReadPlan::ReadOperation&gt;' [-Werror,-Wrange-loop-construct] for (const auto op : read_operationss_{ ec_read_plan.h:135:8: note: use reference type 'const std:pair&lt;ChunkPartType, ReadPlan::ReadOperation&gt; &amp;' to prevent copying for (const auto op : read_operations) { </code></pre> <p>Code is below, I have put a comment next on the line that is giving the error:</p> <pre><code>protected: void recoverParts(uint8_t *buffer, const std::bitset&lt;Goal::Slice::kMaxPartsCount&gt; &amp;available_parts) const { typedef ReedSolomon&lt;slice_traits::ec::kMaxDataCount, slice_traits::ec::kMaxParityCount&gt; RS; int k = slice_traits::ec::getNumberOfDataParts(slice_type); int m = slice_traits::ec::getNumberOfParityParts(slice_type); int max_parts = k + m; RS::ConstFragmentMap data_parts{{0}}; RS::FragmentMap result_parts{{0}}; RS::ErasedMap erased; RS rs(k, m); int available_count = 0; for (int i = 0; i &lt; max_parts; ++i) { if (!available_parts[i] || available_count &gt;= k) { erased.set(i); } else { available_count++; } } for (const auto op : read_operations) { //ERROR appears to be here data_parts[op.first.getSlicePart()] = buffer + op.second.buffer_offset; } for (int i = 0; i &lt; (int)requested_parts.size(); ++i) { if (!available_parts[requested_parts[i].part]) { result_parts[requested_parts[i].part] = buffer + i * buffer_part_size; } } rs.recover(data_parts, erased, result_parts, buffer_part_size); } </code></pre> <p>Why am I getting such an error with Clang and how can I fix this? Thank you.</p> <p>For anyone who may want to reproduce the error, the source code is here: <a href="https://github.com/lizardfs/lizardfs" rel="nofollow noreferrer">https://github.com/lizardfs/lizardfs</a>. Afterwards do:</p> <pre><code>export CC=/usr/bin/clang export CC=/usr/bin/clang++ cd lizardfs mkdir build cd build cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/opt/lizardfs make </code></pre>
3
1,065
How to count correctly 2 inner levels count?
<p>I have a structure for a university DB wherein I have three tables: <code>room</code>, <code>students</code>, <code>possessions</code></p> <pre><code>CREATE TABLE `rooms` ( `id` INT(10) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL COLLATE 'utf8_general_ci', PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `name` (`name`) USING BTREE ) COLLATE='utf8_general_ci' ENGINE=InnoDB AUTO_INCREMENT=3 ; CREATE TABLE `students` ( `id` INT(10) NOT NULL AUTO_INCREMENT, `ref_room_id` INT(10) NULL DEFAULT NULL, `student_name` VARCHAR(50) NOT NULL COLLATE 'utf8_general_ci', PRIMARY KEY (`id`) USING BTREE, INDEX `FK_students_room` (`ref_room_id`) USING BTREE, CONSTRAINT `FK_students_room` FOREIGN KEY (`ref_room_id`) REFERENCES `university`.`rooms` (`id`) ON UPDATE CASCADE ON DELETE SET NULL ) COLLATE='utf8_general_ci' ENGINE=InnoDB AUTO_INCREMENT=6 ; CREATE TABLE `possessions` ( `id` INT(10) NOT NULL AUTO_INCREMENT, `ref_student_id` INT(10) NOT NULL, `name` VARCHAR(50) NOT NULL DEFAULT '' COLLATE 'utf8_general_ci', PRIMARY KEY (`id`) USING BTREE, INDEX `FK__students` (`ref_student_id`) USING BTREE, CONSTRAINT `FK__students` FOREIGN KEY (`ref_student_id`) REFERENCES `university`.`students` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION ) COLLATE='utf8_general_ci' ENGINE=InnoDB AUTO_INCREMENT=4 ; INSERT INTO rooms (name) VALUES ('a'),('b'); INSERT INTO students (`ref_room_id`, `student_name`) VALUES (3,1), (3,2), (3,3), (3,4); INSERT INTO possessions (ref_student_id, name) VALUES (7,'a') (7,'aa'), (7,'aaa'), (8,'aaaa'), (9,'aaaaa'), (6,'aaaaaa'), (7,'aaaaaaa'); </code></pre> <p>So, in order to present such a table in MySQL, I created the procedure</p> <pre><code>CREATE DEFINER=`root`@`localhost` PROCEDURE `get_data`() LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER COMMENT '' BEGIN SELECT r.id AS room_id, r.name, COUNT(s.id) AS student_num, COUNT(p.id) AS possessions_num FROM rooms r INNER JOIN students s ON s.ref_room_id = r.id INNER JOIN possessions p ON p.ref_student_id = s.id GROUP BY r.name; END </code></pre> <p>but what I get is</p> <p><a href="https://i.stack.imgur.com/hxK4O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hxK4O.png" alt="enter image description here" /></a></p> <p>First of all, it misses the room and secondly instead of 4 students it shows 7...</p> <p>What am I doing wrong?</p>
3
1,036
concatenated relu in caffe using python
<p>I want to implement "concatenated relu" in python using caffe. It defines as ConcRelu = Concat (Relu(x), -Relu(-x))</p> <p>Bellow is a naive implementation, but does not work! I would appreciate any help!</p> <pre><code>def prelu(self,bottom,args): 'prelu layer' return L.PReLU(bottom, in_place=True) def crelu(self,bottom,args): 'crelu layer' negative_slope = 0 if len(args) == 1: negative_slope = float(args[0]) rp = {'negative_slope': negative_slope} sp = { 'bias_term': False, 'filler': {'value': -1} } neg_side = L.Scale(bottom, scale_param=sp) a = [L.ReLU(neg_side, relu_param=rp, in_place=True), L.ReLU(bottom, relu_param=rp, in_place=True)] cp = { 'axis' : 1 } return L.Concat(*a, concat_param=cp) </code></pre> <p>==== The output (with error) I get: ====</p> <pre><code>WARNING: Logging before InitGoogleLogging() is written to STDERR I0130 17:15:01.251324 145276 upgrade_proto.cpp:67] Attempting to upgrade input file specified using deprecated input fields: res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_tmp/CNN_020_deploy.txt I0130 17:15:01.251384 145276 upgrade_proto.cpp:70] Successfully upgraded file specified using deprecated input fields. W0130 17:15:01.251389 145276 upgrade_proto.cpp:72] Note that future Caffe releases will only support input layers and not input fields. I0130 17:15:01.657894 145276 net.cpp:51] Initializing net from parameters: name: "CNN_020" state { phase: TEST level: 0 } layer { name: "input" type: "Input" top: "data" input_param { shape { dim: 1 dim: 2 dim: 1 dim: 2048 } } } layer { name: "conv1" type: "Convolution" bottom: "data" top: "conv1" param { lr_mult: 1 decay_mult: 1 } convolution_param { num_output: 16 bias_term: false pad: 0 pad: 0 kernel_size: 1 kernel_size: 3 group: 1 stride: 1 stride: 1 weight_filler { type: "xavier" } bias_filler { type: "constant" value: 0 } axis: 1 } } layer { name: "Scale1" type: "Scale" bottom: "conv1" top: "Scale1" scale_param { filler { value: -1 } bias_term: false } } layer { name: "ReLU1" type: "ReLU" bottom: "Scale1" top: "Scale1" relu_param { negative_slope: 0 } } layer { name: "ReLU2" type: "ReLU" bottom: "conv1" top: "conv1" relu_param { negative_slope: 0 } } layer { name: "crelu1" type: "Concat" bottom: "Scale1" bottom: "conv1" top: "crelu1" concat_param { axis: 1 } } layer { name: "ampl" type: "InnerProduct" bottom: "crelu1" top: "ampl" param { lr_mult: 1 decay_mult: 1 } inner_product_param { num_output: 20 bias_term: false weight_filler { type: "gaussian" std: 0.01 } bias_filler { type: "constant" value: 0.2 } } } I0130 17:15:01.658027 145276 layer_factory.hpp:77] Creating layer input I0130 17:15:01.658046 145276 net.cpp:84] Creating Layer input I0130 17:15:01.658058 145276 net.cpp:380] input -&gt; data I0130 17:15:01.658095 145276 net.cpp:122] Setting up input I0130 17:15:01.658108 145276 net.cpp:129] Top shape: 1 2 1 2048 (4096) I0130 17:15:01.658113 145276 net.cpp:137] Memory required for data: 16384 I0130 17:15:01.658118 145276 layer_factory.hpp:77] Creating layer conv1 I0130 17:15:01.658131 145276 net.cpp:84] Creating Layer conv1 I0130 17:15:01.658138 145276 net.cpp:406] conv1 &lt;- data I0130 17:15:01.658144 145276 net.cpp:380] conv1 -&gt; conv1 I0130 17:15:01.658269 145276 net.cpp:122] Setting up conv1 I0130 17:15:01.658282 145276 net.cpp:129] Top shape: 1 16 1 2046 (32736) I0130 17:15:01.658287 145276 net.cpp:137] Memory required for data: 147328 I0130 17:15:01.658298 145276 layer_factory.hpp:77] Creating layer conv1_conv1_0_split I0130 17:15:01.658313 145276 net.cpp:84] Creating Layer conv1_conv1_0_split I0130 17:15:01.658318 145276 net.cpp:406] conv1_conv1_0_split &lt;- conv1 I0130 17:15:01.658324 145276 net.cpp:380] conv1_conv1_0_split -&gt; conv1_conv1_0_split_0 I0130 17:15:01.658332 145276 net.cpp:380] conv1_conv1_0_split -&gt; conv1_conv1_0_split_1 I0130 17:15:01.658344 145276 net.cpp:122] Setting up conv1_conv1_0_split I0130 17:15:01.658350 145276 net.cpp:129] Top shape: 1 16 1 2046 (32736) I0130 17:15:01.658355 145276 net.cpp:129] Top shape: 1 16 1 2046 (32736) I0130 17:15:01.658360 145276 net.cpp:137] Memory required for data: 409216 I0130 17:15:01.658365 145276 layer_factory.hpp:77] Creating layer Scale1 I0130 17:15:01.658375 145276 net.cpp:84] Creating Layer Scale1 I0130 17:15:01.658380 145276 net.cpp:406] Scale1 &lt;- conv1_conv1_0_split_0 I0130 17:15:01.658386 145276 net.cpp:380] Scale1 -&gt; Scale1 I0130 17:15:01.658408 145276 net.cpp:122] Setting up Scale1 I0130 17:15:01.658416 145276 net.cpp:129] Top shape: 1 16 1 2046 (32736) I0130 17:15:01.658419 145276 net.cpp:137] Memory required for data: 540160 I0130 17:15:01.658427 145276 layer_factory.hpp:77] Creating layer ReLU1 I0130 17:15:01.658435 145276 net.cpp:84] Creating Layer ReLU1 I0130 17:15:01.658440 145276 net.cpp:406] ReLU1 &lt;- Scale1 I0130 17:15:01.658447 145276 net.cpp:367] ReLU1 -&gt; Scale1 (in-place) I0130 17:15:01.658455 145276 net.cpp:122] Setting up ReLU1 I0130 17:15:01.658462 145276 net.cpp:129] Top shape: 1 16 1 2046 (32736) I0130 17:15:01.658465 145276 net.cpp:137] Memory required for data: 671104 I0130 17:15:01.658469 145276 layer_factory.hpp:77] Creating layer ReLU2 I0130 17:15:01.658474 145276 net.cpp:84] Creating Layer ReLU2 I0130 17:15:01.658479 145276 net.cpp:406] ReLU2 &lt;- conv1_conv1_0_split_1 F0130 17:15:01.658486 145276 net.cpp:375] Top blob 'conv1' produced by multiple sources. *** Check failure stack trace: *** /afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/trainAndTest: line 99: 145276 Aborted $pydir/dumpLayersSize.py ${tmp_root}_deploy.txt ${oroot} Tue Jan 30 17:15:01 CET 2018 /usr/bin/time -v caffe -gpu 0 --log_dir=res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_tmp train -solver res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_tmp/CNN_020_solver.txt Tue Jan 30 17:15:20 CET 2018 cp: missing destination file operand after �~@~Xres/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel�~@~Y Try 'cp --help' for more information. tail: cannot open �~@~Xres/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_solver.log.train�~@~Y for reading: No such file or directory /afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/trainAndTest: line 204: gnuplot: command not found /afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/trainAndTest: line 223: gnuplot: command not found /usr/bin/time -v -o res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_time_train.txt python /afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/python/testdataset.py -eg hist -l label -mf=data/2048_1e5_0.00/2048_1e5_0.00_s_met.txt res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_deploy.txt res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel data/2048_1e5_0.00/2048_1e5_0.00_s_train.h5 res/2048_1e5_0.00_s/CNN_020_bs10/restest/CNN_020_train WARNING: Logging before InitGoogleLogging() is written to STDERR W0130 17:15:26.614568 145537 _caffe.cpp:139] DEPRECATION WARNING - deprecated use of Python interface W0130 17:15:26.614625 145537 _caffe.cpp:140] Use this instead (with the named "weights" parameter): W0130 17:15:26.614630 145537 _caffe.cpp:142] Net('res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_deploy.txt', 1, weights='res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel') ('res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_deploy.txt', 'res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel', 'data/2048_1e5_0.00/2048_1e5_0.00_s_train.h5', 'data/2048_1e5_0.00/2048_1e5_0.00_s_met.txt') Traceback (most recent call last): File "/afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/python/testdataset.py", line 395, in &lt;module&gt; aE = predict(model, weights, data) File "/afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/python/testdataset.py", line 200, in predict net = caffe.Net(modelFile, weightsFile, caffe.TEST) RuntimeError: Could not open file res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel /usr/bin/time -v -o res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_time_val.txt python /afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/python/testdataset.py -eg hist -l label -mf=data/2048_1e5_0.00/2048_1e5_0.00_s_met.txt res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_deploy.txt res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel data/2048_1e5_0.00/2048_1e5_0.00_s_val.h5 res/2048_1e5_0.00_s/CNN_020_bs10/restest/CNN_020_val WARNING: Logging before InitGoogleLogging() is written to STDERR W0130 17:15:32.969283 145545 _caffe.cpp:139] DEPRECATION WARNING - deprecated use of Python interface W0130 17:15:32.969337 145545 _caffe.cpp:140] Use this instead (with the named "weights" parameter): W0130 17:15:32.969341 145545 _caffe.cpp:142] Net('res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_deploy.txt', 1, weights='res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel') ('res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_deploy.txt', 'res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel', 'data/2048_1e5_0.00/2048_1e5_0.00_s_val.h5', 'data/2048_1e5_0.00/2048_1e5_0.00_s_met.txt') Traceback (most recent call last): File "/afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/python/testdataset.py", line 395, in &lt;module&gt; aE = predict(model, weights, data) File "/afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/python/testdataset.py", line 200, in predict net = caffe.Net(modelFile, weightsFile, caffe.TEST) RuntimeError: Could not open file res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel /usr/bin/time -v -o res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_time_test.txt python /afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/python/testdataset.py -eg hist -l label -mf=data/2048_1e5_0.00/2048_1e5_0.00_s_met.txt res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_deploy.txt res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel data/2048_1e5_0.00/2048_1e5_0.00_s_test.h5 res/2048_1e5_0.00_s/CNN_020_bs10/restest/CNN_020_test WARNING: Logging before InitGoogleLogging() is written to STDERR W0130 17:15:38.393525 145552 _caffe.cpp:139] DEPRECATION WARNING - deprecated use of Python interface W0130 17:15:38.393584 145552 _caffe.cpp:140] Use this instead (with the named "weights" parameter): W0130 17:15:38.393587 145552 _caffe.cpp:142] Net('res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_deploy.txt', 1, weights='res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel') ('res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020_deploy.txt', 'res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel', 'data/2048_1e5_0.00/2048_1e5_0.00_s_test.h5', 'data/2048_1e5_0.00/2048_1e5_0.00_s_met.txt') Traceback (most recent call last): File "/afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/python/testdataset.py", line 395, in &lt;module&gt; aE = predict(model, weights, data) File "/afs/in2p3.fr/home/n/nhatami/sps/spectroML/src/python/testdataset.py", line 200, in predict net = caffe.Net(modelFile, weightsFile, caffe.TEST) RuntimeError: Could not open file res/2048_1e5_0.00_s/CNN_020_bs10/CNN_020.caffemodel </code></pre>
3
5,110
Slow camera and app close within less than minute
<p>I'm developing an android application which detect text using OpenCV's MSER algorithm. The application is working just fine and doing what it should do, but it closes after less than 1 minute! note that there is no errors or something. I think the problem is with the memory, I monitored the memory of my device while the application was running and there was memory left in my device still it stop working and return me to my phone's home page and close the music if I'm listening to something. I think that the application is very heavy and doing so much work that why the camera became slow and it close suddenly. </p> <p>I don't know how to solve this problem.. can someone tell me how to solve this?</p> <p>My code:</p> <p>xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.lama.myapplication.MainActivity"&gt; &lt;org.opencv.android.JavaCameraView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:layout_alignParentLeft="true" android:gravity="center" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:id="@+id/java_camera_view" /&gt; &lt;/android.support.constraint.ConstraintLayout&gt; </code></pre> <p>java class:</p> <pre><code> public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 { private static final String TAG = "MainActivity"; JavaCameraView javaCameraView; Mat mRgba; //imgGray, imgCanny; private Mat mGrey,mIntermediateMat; BaseLoaderCallback mLoaderCallBack = new BaseLoaderCallback(this) { @Override public void onManagerConnected(int status) { switch(status){ case BaseLoaderCallback.SUCCESS:{ javaCameraView.enableView(); break; } default:{ super.onManagerConnected(status); break; } } } }; static { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //camera permission String[] perms = {"android.permission.CAMERA"}; int permsRequestCode = 200; requestPermissions(perms, permsRequestCode); javaCameraView=(JavaCameraView) findViewById(R.id.java_camera_view); javaCameraView.setVisibility(SurfaceView.VISIBLE); javaCameraView.setCvCameraViewListener(this); } @Override protected void onPause(){ super.onPause(); if (javaCameraView!=null) javaCameraView.disableView(); } @Override protected void onDestroy(){ super.onDestroy(); if (javaCameraView!=null) javaCameraView.disableView(); System.gc(); } @Override protected void onResume(){ super.onResume(); if(!OpenCVLoader.initDebug()){ Log.d(TAG, "OpenCV not loaded"); mLoaderCallBack.onManagerConnected(LoaderCallbackInterface.SUCCESS); } else { Log.d(TAG, "OpenCV loaded"); OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9,this,mLoaderCallBack); } } /** * A native method that is implemented by the 'native-lib' native library, * which is packaged with this application. */ public native String stringFromJNI(); // Used to load the 'native-lib' library on application startup. static { System.loadLibrary("native-lib"); } @Override public void onCameraViewStarted(int width, int height) { /*mRgba=new Mat(height,width, CvType.CV_8UC4); imgGray=new Mat(height,width, CvType.CV_8UC1); imgCanny=new Mat(height,width, CvType.CV_8UC1);*/ mIntermediateMat = new Mat(); mGrey = new Mat(height, width, CvType.CV_8UC4); mRgba = new Mat(height, width, CvType.CV_8UC4); } @Override public void onCameraViewStopped() { mRgba.release(); } @Override public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) { // mRgba=inputFrame.rgba(); /* Imgproc.cvtColor(mRgba,imgGray,Imgproc.COLOR_RGB2GRAY); return imgGray; Imgproc.Canny(imgGray,imgCanny, 50,150); return imgCanny;*/ // return mRgba; mGrey = inputFrame.gray(); mRgba = inputFrame.rgba(); detectText(); return mRgba; } private void detectText() { Scalar CONTOUR_COLOR = new Scalar(255); MatOfKeyPoint keypoint = new MatOfKeyPoint(); List&lt;KeyPoint&gt; listpoint; KeyPoint kpoint; Mat mask = Mat.zeros(mGrey.size(), CvType.CV_8UC1); int rectanx1; int rectany1; int rectanx2; int rectany2; int imgsize = mGrey.height() * mGrey.width(); Scalar zeos = new Scalar(0, 0, 0); List&lt;MatOfPoint&gt; contour2 = new ArrayList&lt;MatOfPoint&gt;(); Mat kernel = new Mat(1, 50, CvType.CV_8UC1, Scalar.all(255)); Mat morbyte = new Mat(); Mat hierarchy = new Mat(); Rect rectan3; // FeatureDetector detector = FeatureDetector.create(FeatureDetector.MSER); detector.detect(mGrey, keypoint); listpoint = keypoint.toList(); // for (int ind = 0; ind &lt; listpoint.size(); ind++) { kpoint = listpoint.get(ind); rectanx1 = (int) (kpoint.pt.x - 0.5 * kpoint.size); rectany1 = (int) (kpoint.pt.y - 0.5 * kpoint.size); rectanx2 = (int) (kpoint.size); rectany2 = (int) (kpoint.size); if (rectanx1 &lt;= 0) rectanx1 = 1; if (rectany1 &lt;= 0) rectany1 = 1; if ((rectanx1 + rectanx2) &gt; mGrey.width()) rectanx2 = mGrey.width() - rectanx1; if ((rectany1 + rectany2) &gt; mGrey.height()) rectany2 = mGrey.height() - rectany1; Rect rectant = new Rect(rectanx1, rectany1, rectanx2, rectany2); try { Mat roi = new Mat(mask, rectant); roi.setTo(CONTOUR_COLOR); roi.release(); } catch (Exception ex) { Log.d("mylog", "mat roi error " + ex.getMessage()); } } Imgproc.morphologyEx(mask, morbyte, Imgproc.MORPH_DILATE, kernel); Imgproc.findContours(morbyte, contour2, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); for (int ind = 0; ind &lt; contour2.size(); ind++) { // rectan3 = Imgproc.boundingRect(contour2.get(ind)); rectan3 = Imgproc.boundingRect(contour2.get(ind)); if (rectan3.area() &gt; 0.5 * imgsize || rectan3.area() &lt; 100 || rectan3.width / rectan3.height &lt; 2) { Mat roi = new Mat(morbyte, rectan3); roi.setTo(zeos); } else Imgproc.rectangle(mRgba, rectan3.br(), rectan3.tl(), CONTOUR_COLOR); } } //camera permission cont. @Override public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){ switch(permsRequestCode){ case 200: boolean cameraAccepted = grantResults[0]==PackageManager.PERMISSION_GRANTED; break; } } } </code></pre> <p>Can someone tell me how can I optimize my application and solve this problem?</p> <p><strong>EDIT:</strong> I tried to release all of the Mat objects as follow:</p> <pre><code>@Override public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) { if(mRgba != null){ mRgba.release(); } mRgba = inputFrame.rgba().clone(); mGrey = inputFrame.gray(); mRgba = inputFrame.rgba(); detectText(); return mRgba; } private void detectText() { Scalar CONTOUR_COLOR = new Scalar(255); MatOfKeyPoint keypoint = new MatOfKeyPoint(); List&lt;KeyPoint&gt; listpoint; KeyPoint kpoint; Mat mask = Mat.zeros(mGrey.size(), CvType.CV_8UC1); int rectanx1; int rectany1; int rectanx2; int rectany2; int imgsize = mGrey.height() * mGrey.width(); Scalar zeos = new Scalar(0, 0, 0); List&lt;MatOfPoint&gt; contour2 = new ArrayList&lt;MatOfPoint&gt;(); Mat kernel = new Mat(1, 50, CvType.CV_8UC1, Scalar.all(255)); Mat morbyte = new Mat(); Mat hierarchy = new Mat(); Rect rectan3; // FeatureDetector detector = FeatureDetector.create(FeatureDetector.MSER); detector.detect(mGrey, keypoint); listpoint = keypoint.toList(); // for (int ind = 0; ind &lt; listpoint.size(); ind++) { kpoint = listpoint.get(ind); rectanx1 = (int) (kpoint.pt.x - 0.5 * kpoint.size); rectany1 = (int) (kpoint.pt.y - 0.5 * kpoint.size); rectanx2 = (int) (kpoint.size); rectany2 = (int) (kpoint.size); if (rectanx1 &lt;= 0) rectanx1 = 1; if (rectany1 &lt;= 0) rectany1 = 1; if ((rectanx1 + rectanx2) &gt; mGrey.width()) rectanx2 = mGrey.width() - rectanx1; if ((rectany1 + rectany2) &gt; mGrey.height()) rectany2 = mGrey.height() - rectany1; Rect rectant = new Rect(rectanx1, rectany1, rectanx2, rectany2); try { Mat roi = new Mat(mask, rectant); roi.setTo(CONTOUR_COLOR); roi.release(); } catch (Exception ex) { Log.d("mylog", "mat roi error " + ex.getMessage()); } } Imgproc.morphologyEx(mask, morbyte, Imgproc.MORPH_DILATE, kernel); Imgproc.findContours(morbyte, contour2, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); for (int ind = 0; ind &lt; contour2.size(); ind++) { // rectan3 = Imgproc.boundingRect(contour2.get(ind)); rectan3 = Imgproc.boundingRect(contour2.get(ind)); if (rectan3.area() &gt; 0.5 * imgsize || rectan3.area() &lt; 100 || rectan3.width / rectan3.height &lt; 2) { Mat roi = new Mat(morbyte, rectan3); roi.setTo(zeos); roi.release(); } else Imgproc.rectangle(mRgba, rectan3.br(), rectan3.tl(), CONTOUR_COLOR); } mask.release(); kernel.release(); morbyte.release(); hierarchy.release(); mGrey.release(); mIntermediateMat.release(); } </code></pre> <p>Yet still I'm having the same problem! Can someone please help me solve this?</p>
3
4,506
Quote issue in HTML, Javascript, .innerHTML, switch and case
<p>I'm modifying a websense block page to include a few functions based on a variable: $*WS_BLOCKREASON*$. I know the potential output of this variable, and I want to have a specific function for. </p> <p>The issue is that the page is not passing even the default case to the '&lt;'div'>' contents. Essentially I need the contents of the <code>&lt;div id="helpDiv"&gt;</code> to be a whole set of text including the button. Script below:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;Access to this site is blocked&lt;/title&gt; &lt;link rel="stylesheet" href="/en/Custom/master.css" type="text/css"&gt; &lt;script type="text/javascript" language="javascript" src="/en/Default/master.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="javascript" src="/en/Default/base64.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="javascript" src="/en/Custom/security.js"&gt;&lt;/script&gt; &lt;style type="text/css"&gt; .style1 { width: 130px; height: 70px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;!--[if lt IE 7]&gt; &lt;div style="width: 725px; height: 381px;"&gt; &lt;![endif] --&gt; &lt;img alt="BHI" class="style1" src="/en/Custom/other.gif" /&gt;&lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;div style="border: 1px solid #285EA6;width: 99.5%; max-width: 915px; overflow: hidden; margin-left: 1px; background-color: #EEF2F7;"&gt; &lt;iframe src="$*WS_BLOCKMESSAGE_PAGE*$*WS_SESSIONID*$" title="BHI_BLOCK" name="ws_block" frameborder="0" scrolling="no" style="width:100%; height: 200px; margin-bottom: 0px;"&gt; &lt;/iframe&gt; &lt;hr /&gt; &lt;!-- onload=function() possible fix --&gt; &lt;script type="text/javascript"&gt; var blockReason=$*WS_BLOCKREASON*$; switch (blockReason) { case 'This Websense category is filtered: &lt;b&gt;Uncategorized&lt;/b&gt;.': document.getElementById('helpDiv').innerHTML='&lt;p style="margin-left: 10px"&gt;Help:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;INPUT TYPE="button" VALUE="Submit UNCATEGORIZED website to Websense" onClick="parent.location=\'mailto:suggest@websense.com?subject=Uncategorized Website&amp;body=Please review and correctly categorize the website that is listed below:%0A%0A' + $*WS_URL*$ + '%0A%0AThank you.\'"&gt;&lt;/p&gt;\ &lt;hr /&gt;\ &lt;p style="margin-left: 64px"&gt;Clicking on the above button will open your mail client to send an e-mail to Websense for recategorization of the above site.&lt;/p&gt;\ &lt;p style="margin-left: 64px"&gt;You will receive a confirmation e-mail and a case number from Websense indicating your request is proccessing.&lt;/p&gt;\ &lt;p style="margin-left: 64px"&gt;Please note the response time for your request will vary. Allow to three to four (3-4) hours for updates to take effect once approved.&lt;/p&gt;\ &lt;p style="margin-left: 64px"&gt;If you have any questions, please contact SOLV at &lt;a href=tel:+18772222222&gt;+1 877 2222222&lt;a/&gt; or &lt;a href=http://solv:8093/CAisd/pdmweb.exe?OP=JUST_GRONK_IT+HTMPL=about.htmpl target="_blank"&gt;this link.&lt;/a&gt;&lt;/p&gt;'; break; case 'This Websense category is filtered: &lt;b&gt;Parked Domain&lt;/b&gt;.': document.getElementById('helpDiv').innerHTML='&lt;p&gt;Parked domain&lt;/p&gt;'; break; default: document.getElementById('helpDiv').innerHTML='&lt;p&gt;No Block message help.&lt;/p&gt;'; } &lt;/script&gt; &lt;div frameborder="0" scrolling="no" style="width:100%; height: auto; margin-bottom: 0px;" id="helpDiv"&gt; &lt;/div&gt; &lt;iframe src="$*WS_BLOCKOPTION_PAGE*$*WS_SESSIONID*$" name="ws_blockoption" frameborder="0" scrolling="no" style="width:100%; height: auto;"&gt; &lt;p&gt;To enable further options, view this page with a browser that supports iframes&lt;/p&gt; padding: 2px 0px;"&gt; &lt;div style="clear: both; overflow: hidden; height:1px;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!--[if lt IE 7]&gt; &lt;/div&gt; &lt;![endif]--&gt; &lt;div id="light" class="white_content"&gt;&lt;/div&gt; &lt;div id="fade" class="black_overlay"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3
1,926
Hive: predicat pushdown doesn't work on ' where col_name is not null '?
<p><strong>when I running this sql code:</strong></p> <p>explain select count(1) from default.ec_order_info where coupon_discount_info is not null</p> <p><strong>query-plan shows:</strong></p> <pre><code> STAGE DEPENDENCIES: Stage-1 is a root stage Stage-0 depends on stages: Stage-1 STAGE PLANS: Stage: Stage-1 Spark Edges: Reducer 2 &lt;- Map 1 (GROUP, 1) DagName: hadoop_20201214011253_e4bb44b1-5a14-42a5-bc89-c2b99d2d3a4c:1 Vertices: Map 1 Map Operator Tree: TableScan alias: ec_order_info filterExpr: coupon_discount_info is not null (type: boolean) Statistics: Num rows: 105309 Data size: 267756631 Basic stats: COMPLETE Column stats: NONE Filter Operator predicate: coupon_discount_info is not null (type: boolean) Statistics: Num rows: 105309 Data size: 267756631 Basic stats: COMPLETE Column stats: NONE Select Operator Statistics: Num rows: 105309 Data size: 267756631 Basic stats: COMPLETE Column stats: NONE Reduce Output Operator sort order: Statistics: Num rows: 105309 Data size: 267756631 Basic stats: COMPLETE Column stats: NONE Reducer 2 Reduce Operator Tree: Group By Operator aggregations: count(1) mode: complete outputColumnNames: _col0 Statistics: Num rows: 1 Data size: 8 Basic stats: COMPLETE Column stats: NONE File Output Operator compressed: false Statistics: Num rows: 1 Data size: 8 Basic stats: COMPLETE Column stats: NONE table: input format: org.apache.hadoop.mapred.SequenceFileInputFormat output format: org.apache.hadoop.hive.ql.io.HiveSequenceFileOutputFormat serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe Stage: Stage-0 Fetch Operator limit: -1 Processor Tree: ListSink </code></pre> <p><strong>show create-table format :</strong></p> <pre><code>CREATE TABLE `default.ec_order_info`( `coupon_discount_info` string) ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.orc.OrcSerde' STORED AS INPUTFORMAT 'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat' LOCATION </code></pre> <p>Filer operator rownums is 105309 ,equal to full-table rows, why predicate pushdown doesn't work? Ask for your help,thx!</p>
3
1,275
C macro's argument limiting by argument prefix
<p>I have a set of defined macros as follows.</p> <pre><code> #define ARM_FRONT_REG 1 .............. #define ARM_REAR_REG 10 #define MOTOR_MAIN_REG 1 .............. #define MOTOR_AUX_REG 3 #define MOTOR_REGISTER_ADDRESS(register_offset) \ ( \ addr = MOTOR_BASE_ADDR * (1 &lt;&lt; BITS_PER_MODULE) + register_offset) \ ) \ #define ARM_REGISTER_ADDRESS(register_offset) \ ( \ addr = ARM_BASE_ADDR * (1 &lt;&lt; BITS_PER_MODULE) + register_offset) \ ) \ </code></pre> <p>I am using macros like</p> <pre><code>ui_address = ARM_BASE_ADDR (ARM_REAR_REG) ui_address = MOTOR_REGISTER_ADDRESS (MOTOR_MAIN_REG) </code></pre> <p>I want to restrict macro usage which is mixed with each other. Is there a way of aborting compiling if macros used as following?</p> <pre><code>ui_address = ARM_BASE_ADDR (MOTOR_MAIN_REG) ui_address = MOTOR_REGISTER_ADDRESS (ARM_REAR_REG) </code></pre> <p>PS : I have mentioned macros in brief, But actual macros are as below, which used to perform register reads write to Linux driver from user application.</p> <p>actual struct :</p> <pre><code>struct hw_register_struct { int log_level; unsigned int reg_addr; unsigned int reg_value; char reg_name [MAX_REG_NAME_LENGTH]; char application_info [APP_INFO_LENGTH]; }; </code></pre> <p>This macro validates the address is correct per module.</p> <pre><code> #define CHECK_ADDR_SUB_MODULE(module_index, sub_module, sub_module_bits, offset, max_reg_count) ({ unsigned int check_ret = 0; if(offset &gt;= max_reg_count){ hw_register.reg_addr = 0; check_ret = 1; } else { hw_register.reg_addr = (module_index * (1 &lt;&lt; BITS_PER_MODULE) + (1 &lt;&lt; sub_module_bits) * (sub_module) + offset); } check_ret; }) </code></pre> <p>This macro assigns the address to the variable in the struct.</p> <pre><code> #define SEQUENCER_REGISTER_ADDRESS(register_offset) ({ memset((void *)&amp;hw_register, 0, sizeof(struct hw_register_struct)); if(CHECK_ADDR_SUB_MODULE(MODULE_SEQUENCER, 0, register_offset, SEQ_REG_COUNT)){ Logger::Print(ERROR_LEVEL, &quot;Invalid Address | Module : %s | Address : %s&quot;, STR(MODULE_SEQUENCER), #register_offset); } memcpy(hw_register.reg_name, #register_offset, sizeof(#register_offset)); hw_register.reg_addr; }) </code></pre> <p>Perform calling the ioctl to Linux driver</p> <pre><code> #define WRITE_REGISTER_(register_addr, register_value, func, line, log_level_) { register_addr; hw_register.reg_value = register_value; hw_register.log_level = log_level_; snprintf(hw_register.application_info, APP_INFO_LENGTH - 1,&quot;%s:%d&quot;, func, line); long ret_ioctl = p_IOCTL-&gt;IOCTL&lt;struct hw_register_struct&gt;(IOCTL_WRITE, hw_register); if(unlikely(ret_ioctl != 0)) { Logger::Print(ERROR_LEVEL, &quot;IOCTL WRITE_REGISTER Failed | Reg: %u, Reg Name [ %s ]&quot;, hw_register.reg_addr, hw_register.reg_name); } } #define WRITE_REGISTER_INFO(register_addr, register_value) WRITE_REGISTER_(register_addr, register_value, __func__, __LINE__, KERN_INFO_LEVEL) </code></pre>
3
3,602
Inconsistency in UI display between computers
<p>So me and a couple of friends are working on a project using flutter and firebase and all that and this is all of our first time working with flutter. One friend has been working on most of the UI elements and it looks perfectly fine on his end, but when we run it it looks completely different and squashed. We all have flutter up to date, we all have the same code from the same github repo, and we all have the same resolution screens if any of that would matter.</p> <p><a href="https://imgur.com/a/9sMOhON" rel="nofollow noreferrer">https://imgur.com/a/9sMOhON</a></p> <p>The first image is what the person who made the UI sees and the second is what the rest of us see when running it (besides the new graph as that was just added recently)</p> <p><strong>Edit</strong> Here is some of the offending code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>List&lt;Widget&gt; chlds = [ // Placeholder for Image Icon(Icons.account_circle, size: 300), // Professor name and Department Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: EdgeInsets.all(16.0), child: Text( "Name: " + documentId, style: stheme.largeText(), ), ), Padding( padding: EdgeInsets.all(16.0), child: Text( dept, style: stheme.largeText(), ), ), ], ), ), // Aesthetic divider Divider( height: 50, thickness: 10, indent: 65, endIndent: 65, color: stheme.accentOne, ), ]; chlds = chlds + pclasses + [GetCommentSection()]; return ListView( children: chlds, ); }</code></pre> </div> </div> </p> <p>And the themes referenced:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>TextStyle largeText(){ return new TextStyle( fontWeight: FontWeight.w500, fontSize: 36, background: Paint() ..strokeWidth = 30 ..color = this.secondary ..style = PaintingStyle.stroke ..strokeJoin = StrokeJoin.round , color: Colors.black ); } // Medium text object TextStyle medText(){ return new TextStyle( fontSize: 24, background: Paint() ..strokeWidth = 30 ..color = this.accentTwo ..style = PaintingStyle.stroke ..strokeJoin = StrokeJoin.round , color: Colors.black ); }</code></pre> </div> </div> </p>
3
1,465
Can't restore OrientDB Backup
<p>I'm having trouble restoring an OrientDB database from a backup. I'm using OrientDB version 1.2.0 (this backup is from November 2012) and the backup was produced by OrientDB (same version) using the built-in backup utility. I'm trying to restore the backup to a new database using the OrientDB console:</p> <pre><code>create database remote:localhost/dbname root password local graph import database backup.json </code></pre> <p>But when I run those commands, I get the following error in the console:</p> <pre><code>Importing indexes ... - Index 'dictionary'...Error on database import happened just before line 22258, column 6 com.orientechnologies.orient.core.exception.OConcurrentModificationException: Cannot update record #0:1 in storage 'dbname' because the version is not the latest. Probably you are updating an old record or it has been modified by another user (db=v2 your=v1) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary.createException(OChannelBinary.java:429) at com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary.handleStatus(OChannelBinary.java:382) at com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryAsynch.beginResponse(OChannelBinaryAsynch.java:145) at com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryAsynch.beginResponse(OChannelBinaryAsynch.java:59) at com.orientechnologies.orient.client.remote.OStorageRemote.beginResponse(OStorageRemote.java:1556) at com.orientechnologies.orient.client.remote.OStorageRemote.command(OStorageRemote.java:727) at com.orientechnologies.orient.client.remote.OStorageRemoteThread.command(OStorageRemoteThread.java:191) at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:60) at com.orientechnologies.orient.core.index.OIndexManagerRemote.dropIndex(OIndexManagerRemote.java:80) at com.orientechnologies.orient.core.index.OIndexManagerProxy.dropIndex(OIndexManagerProxy.java:80) at com.orientechnologies.orient.core.db.tool.ODatabaseImport.importIndexes(ODatabaseImport.java:687) at com.orientechnologies.orient.core.db.tool.ODatabaseImport.importDatabase(ODatabaseImport.java:127) at com.orientechnologies.orient.console.OConsoleDatabaseApp.importDatabase(OConsoleDatabaseApp.java:1419) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.orientechnologies.common.console.OConsoleApplication.execute(OConsoleApplication.java:238) at com.orientechnologies.common.console.OConsoleApplication.executeCommands(OConsoleApplication.java:127) at com.orientechnologies.common.console.OConsoleApplication.run(OConsoleApplication.java:92) at com.orientechnologies.orient.console.OConsoleDatabaseApp.main(OConsoleDatabaseApp.java:130) </code></pre> <p>All of the records import correctly, but it fails on the indexes. I have 15+ backups of the same database and they all have this issue, so it seems unlikely that they're all corrupted. How can I restore my database? (I'm OK with having to modify the JSON if needbe.)</p> <hr> <p>When trying to use local mode rather than remote mode, I get a different error:</p> <pre><code>Started import of database 'local:dbname' from dbname.json... Importing database info...OK Importing clusters... - Creating cluster 'internal'...OK, assigned id=0 - Creating cluster 'default'...Error on database import happened just before line 13, column 52 com.orientechnologies.orient.core.exception.OConfigurationException: Imported cluster 'default' has id=3 different from the original: 2. To continue the import drop the cluster 'manindex' that has 1 records at com.orientechnologies.orient.core.db.tool.ODatabaseImport.importClusters(ODatabaseImport.java:544) at com.orientechnologies.orient.core.db.tool.ODatabaseImport.importDatabase(ODatabaseImport.java:130) at com.orientechnologies.orient.console.OConsoleDatabaseApp.importDatabase(OConsoleDatabaseApp.java:1414) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.orientechnologies.common.console.OConsoleApplication.execute(OConsoleApplication.java:269) at com.orientechnologies.common.console.OConsoleApplication.executeCommands(OConsoleApplication.java:157) at com.orientechnologies.common.console.OConsoleApplication.run(OConsoleApplication.java:97) at com.orientechnologies.orient.graph.console.OGremlinConsole.main(OGremlinConsole.java:53) Error: com.orientechnologies.orient.core.db.tool.ODatabaseExportException: Error on importing database 'dbname' from file: dbname.json Error: com.orientechnologies.orient.core.exception.OConfigurationException: Imported cluster 'default' has id=3 different from the original: 2. To continue the import drop the cluster 'manindex' that has 1 records </code></pre> <p>It seems like the issue is that my old cluster IDs don't match the ones in the new database. Perhaps there are creation options that affect which clusters are created by default?</p>
3
1,753
using position() in XSLT transformation
<p>I am trying to transform following XML </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;catalog&gt; &lt;cd QualifyingCode="1"&gt; &lt;title&gt;title1&lt;/title&gt; &lt;artist&gt;artist1&lt;/artist&gt; &lt;/cd&gt; &lt;cd QualifyingCode="1"&gt; &lt;title&gt;title2&lt;/title&gt; &lt;artist&gt;artist2&lt;/artist&gt; &lt;/cd&gt; &lt;cd QualifyingCode="2"&gt; &lt;title&gt;title3&lt;/title&gt; &lt;artist&gt;artist3&lt;/artist&gt; &lt;/cd&gt; &lt;cd QualifyingCode="2"&gt; &lt;title&gt;title4&lt;/title&gt; &lt;artist&gt;artist4&lt;/artist&gt; &lt;/cd&gt; &lt;/catalog&gt; </code></pre> <p>Using floowing XSLT</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:template match="/"&gt; &lt;html&gt; &lt;body&gt; &lt;h2&gt;My CD Collection&lt;/h2&gt; &lt;table border="1"&gt; &lt;tr bgcolor="#9acd32"&gt; &lt;th style="text-align:left"&gt;Title&lt;/th&gt; &lt;th style="text-align:left"&gt;Artist&lt;/th&gt; &lt;th style="text-align:left"&gt;ID&lt;/th&gt; &lt;/tr&gt; &lt;xsl:for-each select="catalog/cd"&gt; &lt;tr&gt; &lt;td&gt;&lt;xsl:value-of select="title"/&gt;&lt;/td&gt; &lt;td&gt;&lt;xsl:value-of select="artist"/&gt;&lt;/td&gt; &lt;td&gt;&lt;xsl:value-of select="position()"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/xsl:for-each&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>I am getting the position as 1,2,3,4 using the position(). What I want is output for the position() should be 1,2,1,2 based on "QualifyingCode" attribute.</p> <p>so my current output is :</p> <pre><code>My CD Collection Title Artist ID title1 artist1 1 title2 artist2 2 title3 artist3 3 title4 artist4 4 </code></pre> <p>and my expected output is </p> <pre><code> My CD Collection Title Artist ID title1 artist1 1 title2 artist2 2 title3 artist3 1 title4 artist4 2 </code></pre>
3
1,126
Getting No tests to run on executing pom.xml as maven test but on executing testng.xml its working fine
<p><strong>Getting No tests to run on executing pom.xml as maven test, but on executing testng.xml its working fine.</strong></p> <p><strong>pom.xml - tried including Test case names as well as removing them . nothing is working</strong></p> <pre><code>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;webAutomation&lt;/groupId&gt; &lt;artifactId&gt;webAutomation&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;build&gt; &lt;sourceDirectory&gt;src&lt;/sourceDirectory&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.5.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.8&lt;/source&gt; &lt;target&gt;1.8&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt; 2.14.1&lt;/version&gt; &lt;configuration&gt; &lt;suiteXMLFiles&gt; &lt;suiteXMLFile&gt;testng.xml&lt;/suiteXMLFile&gt; &lt;/suiteXMLFiles&gt; &lt;configuration&gt; &lt;includes&gt; &lt;include&gt;ocs_TestCase.TC_001.java&lt;/include&gt; &lt;include&gt;ocs_TestCase.TC01_OCS_Search.java&lt;/include&gt; &lt;/includes&gt; &lt;/configuration&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p><strong>used Testng.xml file</strong></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;!DOCTYPE suite SYSTEM &quot;http://testng.org/testng-1.0.dtd&quot;&gt; &lt;suite name=&quot;Suite&quot;&gt; &lt;test name=&quot;Test&quot;&gt; &lt;classes&gt; &lt;class name=&quot;ocs_TestCase.TC001&quot;/&gt; &lt;class name=&quot;ocs_TestCase.TC01_OCS_Search&quot;/&gt; &lt;/classes&gt; &lt;/test&gt; &lt;!-- Test --&gt; &lt;/suite&gt; &lt;!-- Suite --&gt; </code></pre> <p><strong>Console log on executing pom.xml as maven test</strong></p> <pre><code> [INFO] No sources to compile [INFO] [INFO] --- maven-surefire-plugin:2.14.1:test (default-test) @ webAutomation --- [INFO] No tests to run. [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.851 s [INFO] Finished at: 2021-02-10T17:17:39+05:30 [INFO] Final Memory: 12M/220M [INFO] ------------------------------------------------------------------------ </code></pre>
3
1,400
Can't get WordPress hook to fire inside embedded class
<p>I am trying to build some nice metabox functionality with some oop.</p> <p>I have my main DazSEO class, which inside contains a Metabox Class.</p> <p>When I set WordPress save data hooks up inside the metabox class, they won't fire, but when I set them up from the root class, they will.</p> <p>Is using hooks inside embedded classes incompatible with the WordPress hook system?</p> <p>Any help would be appreciated here as I have spent a lot of time trying to figure out what is the issue here, I guess it is some object scope issue for the wp engine, but I am not convinced. class DazSEO { public static $plugins = array();</p> <pre><code>public $metaBox; public function __construct() { add_action('admin_init', array($this, 'adminInit') ); add_action('init', array($this, 'init')); } public function adminInit() { $this-&gt;setupMetaBox(); } public function setupMetaBox() { if( $pagenow === 'term.php' ) { // returns true if( isset($_GET['taxonomy']) ) { $term = get_term( $_GET['tag_ID'], $_GET['taxonomy'], OBJECT ); require_once('admin\metabox\TermMetaBox.php'); $this-&gt;metaBox = new TermMetabox( $_GET['taxonomy'] ); // confirmed this does fire DazSEO::$mode = 'term'; DazSEO::$wpID = $_GET['tag_ID']; DazSEO::$typeName = $_GET['taxonomy']; } } } } class TermMetabox extends MetaBoxBase { private $_taxonomy; public function __construct(string $taxonomy) { if( strlen($taxonomy) === 0 ) { echo 'no taxonomy passed'; exit(); } $this-&gt;_taxonomy = $taxonomy; add_action( $this-&gt;_taxonomy . '_edit_form', array($this, 'buildMetaBox') ); add_action('edit_terms', array($this, 'onTermSave')); // SETUP TERM SAVE } public function loadHooks() { } // NOT BEING CALLED public function onTermSave(int $term_id) { echo '&lt;pre&gt;' . print_r($_REQUEST, 1) . '&lt;/pre&gt;'; exit(); if( $this-&gt;onSaveChecks($term_id) ) { return; } foreach(DazSEO::$plugins as $plugin) { $plugin-&gt;onTermSave($term_id, $_REQUEST); } } } </code></pre> <p>The TermMetabox:: onTermSave never gets called</p> <p>If this is called from the root class (DazSEO), and I move the save method in there too it works...</p> <pre><code>add_action('edit_terms', array($this, 'onTermSave')); </code></pre> <p>But it's messy design like that.</p> <p>This plugin is initialized like this...</p> <pre><code>$dazSEO = new DazSEO(); $wpCleanHeader = new RemoveWPHeaderJunk(); $dazSEO-&gt;loadPlugin($wpCleanHeader); </code></pre>
3
1,053
Unable to hit spring mvc controller through ajax call
<p>1.Below is my ajax call in index.jsp</p> <pre><code> &lt;script type="text/javascript"&gt; $(document).ready(function(){ $('#buttonDemo1').click(function(){ $.ajax({ method: "GET", url: '${pageContext.request.contextPath}/ajax/demo1', success: function(result){ $('#result1').html(result); }, error: function(response){ console.log("error"); } }); }); }); &lt;/script&gt; </code></pre> <p>2.Below is controller's code</p> <pre><code> @Controller @RequestMapping("/ajax") public class AjaxController { @RequestMapping(method = RequestMethod.GET) public String index() { return "ajax/index"; } @RequestMapping(value="/demo1", method = RequestMethod.GET) @ResponseBody public String demo1() { return "Demo 1"; } } </code></pre> <p>3. Below is dispatcher's code</p> <pre><code> &lt;?xml version='1.0' encoding='UTF-8' ?&gt; &lt;!-- was: &lt;?xml version="1.0" encoding="UTF-8"?&gt; --&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"&gt; &lt;context:component-scan base-package="demo.controller" /&gt; &lt;mvc:annotation-driven/&gt; &lt;bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/&gt; &lt;!-- Most controllers will use the ControllerClassNameHandlerMapping above, but for the index controller we are using ParameterizableViewController, so we must define an explicit mapping for it. --&gt; &lt;bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&gt; &lt;property name="mappings"&gt; &lt;props&gt; &lt;prop key="index.htm"&gt;indexController&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /&gt; &lt;!-- The index controller. --&gt; &lt;bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController" p:viewName="index" /&gt; </code></pre> <p></p> <ol start="4"> <li><p>Below is web.xml</p> <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/applicationContext.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener- class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener- class&gt; &lt;/listener&gt; &lt;servlet&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;servlet- class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;2&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;session-config&gt; &lt;session-timeout&gt; 30 &lt;/session-timeout&gt; &lt;/session-config&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;redirect.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt; </code></pre></li> </ol> <p>I don't know what's wrong, whenever I'm hitting controller's path in ajax I get "GET <a href="http://localhost:8080/ajax/demo1" rel="nofollow noreferrer">http://localhost:8080/ajax/demo1</a> 404 (Not Found)" error. Please help me out where I'm wrong. I've tried few solutions but they didn't resolve issue.</p>
3
2,162
How to populate treeview in backgroundworker C#
<p>I have those below code that populate a treeview named treeView1 with data from JSON file using JSONnet. If I open a large json file, the UI hang during the populating progress, so how can I make everything happen in a backgroundworker and show a progressbar for populating progress? thanks</p> <pre><code> private void button1_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.Filter = "All files (*.*)|*.*"; openFileDialog1.FilterIndex = 1; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { string jsonfile = File.ReadAllText(openFileDialog1.FileName); try { var jsondata = JObject.Parse(jsonfile); treeView1.Nodes.Clear(); AddObjectNodes(jsondata, "DATA", treeView1.Nodes); } catch (Exception) { MessageBox.Show("Invalid JSON"); } } } private void AddObjectNodes(JObject @object, string name, TreeNodeCollection parent) { var node = new TreeNode(name); parent.Add(node); foreach (var property in @object.Properties()) { AddTokenNodes(property.Value, property.Name, node.Nodes); } } private void AddArrayNodes(JArray array, string name, TreeNodeCollection parent) { var node = new TreeNode(name); parent.Add(node); for (var i = 0; i &lt; array.Count; i++) { AddTokenNodes(array[i], string.Format("[{0}]", i), node.Nodes); } } private void AddTokenNodes(JToken token, string name, TreeNodeCollection parent) { if (token is JValue) { parent.Add(new TreeNode(string.Format("{0}: {1}", name, ((JValue)token).Value))); } else if (token is JArray) { AddArrayNodes((JArray)token, name, parent); } else if (token is JObject) { AddObjectNodes((JObject)token, name, parent); } } </code></pre>
3
1,031
How to apply custom font to multiple TextViews within a fragment?
<p>I am trying to change the default font for multiple TextViews in android fragment by a custom font. The code to accomplish this is in onCreateView of thefragment as shown below:</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_interest, container, false); TextView txt1 = (TextView)v.findViewById(R.id.textView1); TextView txt2 = (TextView)v.findViewById(R.id.textView2); Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/HoneyScript-SemiBold.ttf"); txt1.setTypeface(font); txt2.setTypeface(font); return v; </code></pre> <p>}</p> <p>The code works if I change the font for only a single TextView but attempting to change font for multiple TextViews as in the code above, I am getting NullPointerException error:</p> <pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference at layout.InterestFragment.onCreateView(InterestFragment.java:81) at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613) at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330) at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547) at com.android.niraj.financialcalculator.MainActivity.onStart(MainActivity.java:221) at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237) at android.app.Activity.performStart(Activity.java:6253) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  </code></pre> <p>I am newbie to java and android programming. Please help me find a solution in changing all the TextViews in the fragment with custom font. Thanks in advance !!</p>
3
2,719
One session design pattern for EJB JPA and GWT RequestFactory aka keeping JPA session between multiple method calls
<p>The setup is like this:</p> <p><strong>Front-end:</strong> <code>GWT</code> using <code>RequestFactory</code> for sending data objects<br> <strong>Back-end:</strong><br> <em>Web-layer:</em><br> <code>GWT</code> server side code which has injected EJB<br> <em>EJB-layer:</em><br> Stateless sesion beans: </p> <p><strong>Data access bean</strong> (<code>DAB</code>)=> has injected <code>EntityManager</code> for <code>JPA</code> operations and provides methods for merging and retrieving of entities<br> <strong>Facade bean</strong> (<code>FB</code>) => calls methods of DAB and is interface between EJB and web layer</p> <p>When an entity object (lets say <code>MyEntity</code>) is to be saved after it has been modified at the client side, the flow is like this:<br> 1. Initiated by the client<br> 2. Server side <code>GWT</code> code is run and invokes the following methods:<br> 3. The <code>find()</code> method looks up the instance of <code>MyEntity</code> using <code>FB.findMyEntity()</code> which calls <code>DAB.findMyEntity()</code> which in turn uses <code>EntityManager</code> to do the look-up. The <code>find()</code> method must be invoked as its part of <code>RequestFactory</code> flow in <code>GWT</code>.<br> 4. The <code>save()</code> leads to <code>FB.saveMyEntity()</code> --> <code>DAB.saveMyEntity()</code> --> <code>EntityManager.merge()</code> and the changed entity object is persisted.</p> <p>It is obvious that each of <code>find()</code> and <code>save()</code> methods run in different <code>JPA</code> transaction which is ineffective and bad design. </p> <p>With regards to keeping the facade bean interface with simple look-up and saving methods:</p> <ol> <li>What is the best design to handle this situation? - preferably with having both method calls in one <code>JPA</code> transaction.</li> <li>What are alternatives? With pros and cons.</li> </ol> <p>EDIT: Including simplified examples of the code for <code>FB</code> and <code>DAB</code>. </p> <p>Facade bean (<code>FB</code>):</p> <pre><code> @Stateless public class MyFacadeBean implements MyFacade{ @EJB private DataAccessBean dab; @Override public void saveMyEntity(MyEntity entity) { dab.saveMyEntity(entity); } @Override public void findMyEntity(int id) { dab.saveMyEntity(id); } } </code></pre> <p>Data access bean (<code>DAB</code>):</p> <pre><code> @Stateless public class DataAccesseBean implements DataAccessBeanInterface{ @PersistenceContext private EntityManager entityManager; @Override public void saveMyEntity(MyEntity entity) { entityManager.merge(entity); } @Override public void findMyEntity(int id) { entityManager.find(MyEntity.class,id); } } </code></pre>
3
1,224
Loosing setted instance / null after method ending (@Autowire)
<p>Im trying to set parser depend on URI. I was debugging it. When condition is OK my parserParent is setted, but at the end of setParser() method, parserParent is again null. I was trying to combine with asigning @Autowired annotation in inherit class, but always Im getting the same NullPointer error. How to fix it ? </p> <p>CLASS WHERE PROBLEM IS</p> <pre><code>import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import pl.manciak.excelparser.ParseAndSave.ParseCsvAndSaveToDB; import pl.manciak.excelparser.ParseAndSave.ParseXlsxAndSaveToDb; import pl.manciak.excelparser.ParseAndSave.ParserParent; import java.io.IOException; @RestController public class RestClientSave { private ParserParent parserParent; private ParseCsvAndSaveToDB parseCsvAndSaveToDB; private ParseXlsxAndSaveToDb parseXlsxAndSaveToDb; private String whichParser= "csv"; //HARDCODED FOR SIMPLICITY @Autowired public void setParser( ParseCsvAndSaveToDB parseCsvAndSaveToDB, ParseXlsxAndSaveToDb parseXlsxAndSaveToDb) { if (whichParser.equals("csv")) { parserParent = parseCsvAndSaveToDB; // HERE PARSER IS SETTED }else if(whichParser.equals("xlsx")) { this.parserParent = parseXlsxAndSaveToDb; } } @GetMapping("/save/{whichParser}") public String save(@PathVariable String whichParser) throws IOException { this.whichParser= whichParser; setParser( parseCsvAndSaveToDB, parseXlsxAndSaveToDb); // HERE IS AGAIN NULL parserParent.save(); return "data saved"; } } </code></pre> <p>PARENT CLASS FOR PARSER</p> <pre><code>import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.manciak.excelparser.DataService; import pl.manciak.excelparser.Entity.LinesEntity; import pl.manciak.excelparser.Entity.MapEntity; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @Service public class ParserParent { protected DataService dataService; protected LinesEntity linesEntity; protected ArrayList&lt;String&gt; list; protected HashMap&lt;Long, LinesEntity&gt; xlsMapped = new HashMap&lt;&gt;(); protected MapEntity mapEntity = new MapEntity(); @Autowired public ParserParent(DataService dataService ) { this.dataService = dataService; } public void save() throws IOException {} } </code></pre> <p>CHILD CLASS</p> <pre><code>package pl.manciak.excelparser.ParseAndSave; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.manciak.excelparser.DataService; import pl.manciak.excelparser.Entity.LinesEntity; import java.io.*; import java.util.ArrayList; import java.util.Collections; @Service public class ParseCsvAndSaveToDB extends ParserParent{ @Autowired public ParseCsvAndSaveToDB(DataService dataService) { super(dataService); } public void save() throws IOException { //Stream to Read Csv file FileReader fileReader = new FileReader("usda_sample.csv"); BufferedReader br = new BufferedReader(fileReader); //read first line String line = br.readLine(); long mapKey = 0; while (line != null) { linesEntity = new LinesEntity(); // create a new LinesEntity for this loop execution list = new ArrayList&lt;&gt;(); Collections.addAll(list, line.split(",")); line = br.readLine(); linesEntity.setSingleLine(new ArrayList&lt;&gt;(list)); dataService.saveOne(linesEntity); xlsMapped.put(mapKey, linesEntity); mapKey++; } mapEntity.setMapa(xlsMapped); System.out.println(xlsMapped); dataService.save(mapEntity); } </code></pre>
3
1,602
ajax load posts as full page slides
<p>I've been scratching my head over this and wondering if anyone has a solution. Effectively I'm creating a full viewport slider that dynamically loads the posts into a hidden div that is then animated into the page based on the direction the arrow is clicked. I can get the hidden div to animate in, however the script stops running after the first click so all other posts are not getting pulled in.</p> <p>HTML/PHP:</p> <pre><code>// First Div that hold all loaded data &lt;div id="Default" class="main"&gt; &lt;div id="fullContent"&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;?php the_title(); ?&gt; &lt;?php the_content(); ?&gt; &lt;?php endwhile; ?&gt; &lt;div class="leftArrow"&gt; &lt;?php previous_post_link_plus( array('format' =&gt; '%link', 'order_by' =&gt; 'menu_order', 'loop' =&gt; true) ); ?&gt; &lt;/div&gt; &lt;div class="rightArrow"&gt; &lt;?php next_post_link_plus( array('format' =&gt; '%link', 'order_by' =&gt; 'menu_order', 'loop' =&gt; true) ); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; // Second div where new content will be loaded &lt;div id="LoadAjax" class="direction"&gt;&lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"&gt;&lt;/script&gt; </code></pre> <p>JQUERY</p> <pre><code>$.ajaxSetup({cache:false}); $('body').on('click', '.rightArrow a', function(e){ e.preventDefault(); history.pushState({ path: this.path }, '', this.href); $('.direction').hide(); RightSlide(this); return false; }); $('body').on('click', '.leftArrow a', function(e){ e.preventDefault(); $('.direction').hide(); history.pushState({ path: this.path }, '', this.href); LeftSlide(this); return false; }); function RightSlide(that) { var post_id = $(that).attr('href'); $('.direction').load(post_id + ' #fullContent', function(){ // Animate Slides In &amp; Out setTimeout(function(){ $('.direction').show('slide',{direction: 'right'},600); },50); setTimeout(function(){ $('#Default').addClass('direction').removeClass('main').empty(); $('#LoadAjax').addClass('main').removeClass('direction'); },650); return false; }); }; function LeftSlide(that) { var post_id = $(that).attr('href'); $('.direction').load(post_id + ' #fullContent', function(){ // Animate Slides In &amp; Out setTimeout(function(){ $('.direction').show('slide',{direction: 'left'},600); },50); setTimeout(function(){ $('#Default').addClass('direction').removeClass('main').empty(); $('#LoadAjax').addClass('main').removeClass('direction'); },650); return false; }); }; </code></pre> <p>As you can see on initial load it all works as expected, however if I then go to click right again nothing executes.</p> <p>My question, is there a way to reset the function on the second click? And what is the reason that it doesn't run on the second click through?</p> <p>Thanks for your help in advanced. Absolute amateur in this subject so any feedback will be appreciated to help me learn.</p> <p>Cheers,</p> <p>A</p> <p>Edit: Added addition scripts</p> <p>Solution:</p> <pre><code>$.ajaxSetup({cache:false}); $('body').on('click', '.rightArrow a', function(e){ e.preventDefault(); history.pushState({ path: this.path }, '', this.href); $('.disableClicks').show(); RightSlide(this); return false; }); $('body').on('click', '.leftArrow a', function(e){ e.preventDefault(); $('.disableClicks').show(); history.pushState({ path: this.path }, '', this.href); LeftSlide(this); return false; }); function RightSlide(that) { var post_id = $(that).attr('href'); $('.direction').load(post_id + ' #fullContent', function(){ // Animate Slides In &amp; Out setTimeout(function(){ $('.direction').show('slide',{direction: 'right'},250); },50); setTimeout(function(){ if($('#Default').hasClass('main')) { $('#Default').addClass('direction').removeClass('main'); } else { $('#Default').addClass('main').removeClass('direction'); } if($('#LoadAjax').hasClass('main')) { $('#LoadAjax').addClass('direction').removeClass('main'); } else { $('#LoadAjax').addClass('main').removeClass('direction'); } $('.direction').empty().hide(); $('.disableClicks').hide(); },310); return false; }); }; function LeftSlide(that) { var post_id = $(that).attr('href'); $('.direction').load(post_id + ' #fullContent', function(){ // Animate Slides In &amp; Out setTimeout(function(){ $('.direction').show('slide',{direction: 'left'},250); },50); setTimeout(function(){ if($('#Default').hasClass('main')) { $('#Default').addClass('direction').removeClass('main'); } else { $('#Default').addClass('main').removeClass('direction'); } if($('#LoadAjax').hasClass('main')) { $('#LoadAjax').addClass('direction').removeClass('main'); } else { $('#LoadAjax').addClass('main').removeClass('direction'); } $('.direction').empty().hide(); $('.disableClicks').hide(); },310); return false; }); }; </code></pre>
3
2,875
How to make my code with ellipsoidhull and for/if loop more efficient
<p>My code is structured so that I create an ellipse through my first three points of data. Then I go through each next row, and if the point falls outside the ellipse, I record the minimum distance between the point and ellipse. These points have datetime associated with it so I can only keep points 10 minutes old in my ellipse (so it doesn't get too big). The code works great until I have to process 100K+ of observations. Then the process time goes from minutes to hours. My question is, is there any part of my for loop portion of code that I can restructure to cut process time? Code below for reference. Any help is greatly appreciated.</p> <pre><code>library(sp) library(cluster) #create new empty column in dataframe df$Distances &lt;- NA #get first three points and fit an ellipse around it FlashPoints &lt;- cbind(df$Lat[1:3],df$Long[1:3]) EllipseShape &lt;- ellipsoidhull(FlashPoints) EllipseShape #get set of points that represent ellipse EllipsePoints &lt;- predict(EllipseShape) EllipseGroup &lt;- cbind(EllipsePoints[,2],EllipsePoints[,1]) #function to check if the next flashpoint (xp, yp) belongs to the ellipse with parameters a,b,... with tolerance eps onEllipse &lt;- function (xp, yp, a, b, x0, y0, alpha, eps=1e-3) { return(abs((cos(alpha)*(xp-x0)+sin(alpha)*(yp-y0))^2/a^2+(sin(alpha)*(xp-x0)-cos(alpha)*(yp-y0))^2/b^2 - 1) &lt;= eps) } #function to check if the point (xp, yp) is inside the ellipse with parameters a,b,... insideEllipse &lt;- function (xp, yp, a, b, x0, y0, alpha) { return((cos(alpha)*(xp-x0)+sin(alpha)*(yp-y0))^2/a^2+(sin(alpha)*(xp-x0)-cos(alpha)*(yp-y0))^2/b^2 &lt;= 1) } #loop from row 4 to last row for (i in 4:nrow(df)){ #get location of next point nextFlash &lt;- cbind(df$Long[i],df$Lat[i]) #Establish/Re-establish parameters xp &lt;- df$Lat[i] yp &lt;- df$Long[i] x0 &lt;- EllipseShape$loc[1] # centroid locations y0 &lt;- EllipseShape$loc[2] eg &lt;- eigen(EllipseShape$cov) axes &lt;- sqrt(eg$values) alpha &lt;- atan(eg$vectors[1,1]/eg$vectors[2,1]) # angle of major axis with x axis a &lt;- sqrt(EllipseShape$d2) * axes[1] # major axis length b &lt;- sqrt(EllipseShape$d2) * axes[2] # minor axis length #Check to see if next point is outside the ellipse, then get distance. If it is, add to distance list if((insideEllipse(xp, yp, a, b, x0, y0, alpha)==FALSE) &amp;&amp; onEllipse(xp, yp, a, b, x0, y0, alpha)==FALSE){ nextDist &lt;- min(spDistsN1(EllipseGroup, nextFlash, longlat = TRUE)) df$Distances[i] &lt;- nextDist #Omit points 10 minutes old from group movingGroup &lt;- subset(df[1:i,], difftime(df$DateTime[1:i],df$DateTime[i],units = &quot;mins&quot;)&lt;10) movingTstorm FlashPoints &lt;- cbind(movingGroup$Lat[1:i],movingGroup$Long[1:i]) FlashPoints #Fit an ellipse around flashpoints EllipseShape &lt;- ellipsoidhull(FlashPoints) EllipseShape #Get set of points that make an ellipse EllipsePoints &lt;- predict(EllipseShape) EllipseGroup &lt;- cbind(EllipsePoints[,2],EllipsePoints[,1]) } next(i) } </code></pre>
3
1,192
crash when i try to create a path between two points in osmdroid
<p>I have recently started studying android and kotlin programming, I'm trying to create an application that allows you to create one or more routes on a map, save it and then retrieve it when necessary. I chose to use osmDroid and osmBonusPack because open source but I don't find much documentation online, I'm trying to visualize a path between two Markers, I was able to visualize two markers and draw a straight line between two other points, now I'm trying to make the path but I don't understand how to proceed. Following the tutorial:</p> <p><a href="https://github.com/MKergall/osmbonuspack/wiki/Tutorial_1" rel="nofollow noreferrer">https://github.com/MKergall/osmbonuspack/wiki/Tutorial_1</a></p> <p>trying to put some println(&quot;check&quot;) i understand that the app crashes when it gets to the line:</p> <pre><code>val road: Road = roadManager.getRoad(waypoints) </code></pre> <p>what's my problem? what is the error:</p> <p>E/AndroidRuntime: FATAL EXCEPTION: main Process: uk.co.lorenzopulcinelli.trackapp, PID: 28815 java.lang.NoClassDefFoundError: Failed resolution of: Lokhttp3/Request$Builder;</p> <p>?</p> <pre><code> package uk.co.lorenzopulcinelli.trackapp import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.util.DisplayMetrics import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.preference.PreferenceManager import org.osmdroid.api.IMapController import org.osmdroid.bonuspack.routing.OSRMRoadManager import org.osmdroid.bonuspack.routing.Road import org.osmdroid.bonuspack.routing.RoadManager import org.osmdroid.config.Configuration import org.osmdroid.config.Configuration.* import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.views.CustomZoomButtonsController import org.osmdroid.views.MapView import org.osmdroid.views.overlay.compass.CompassOverlay import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider import org.osmdroid.views.overlay.* import org.osmdroid.views.overlay.gestures.RotationGestureOverlay import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay import org.osmdroid.views.overlay.Marker class MainActivity : AppCompatActivity() { private lateinit var mapView : MapView private lateinit var myLocationNewOverlay: MyLocationNewOverlay private lateinit var compassOverlay: CompassOverlay private lateinit var mapController: IMapController private lateinit var userAgent: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestPermission() getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this)) setContentView(R.layout.activity_main) mapView = findViewById&lt;MapView&gt;(R.id.map) mapView.setTileSource(TileSourceFactory.MAPNIK) mapView.zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER) mapController = mapView.controller myLocationNewOverlay = MyLocationNewOverlay(GpsMyLocationProvider(this), mapView) myLocationNewOverlay.enableMyLocation() myLocationNewOverlay.enableMyLocation() myLocationNewOverlay.isDrawAccuracyEnabled = true myLocationNewOverlay.runOnFirstFix { runOnUiThread { mapController.animateTo(myLocationNewOverlay.myLocation) mapController.setZoom(9.5) } } mapView.overlays.add(myLocationNewOverlay) Configuration.getInstance().userAgentValue = &quot;lolloMaps&quot; println(myLocationNewOverlay.myLocation) println(&quot;creato&quot;) compassOverlay = CompassOverlay(this, InternalCompassOrientationProvider(this), mapView) compassOverlay.enableCompass() mapView.overlays.add(compassOverlay) // val overlay = LatLonGridlineOverlay2() // mapView.overlays.add(overlay) val rotationGestureOverlay = RotationGestureOverlay(mapView) rotationGestureOverlay.isEnabled mapView.setMultiTouchControls(true) mapView.overlays.add(rotationGestureOverlay) myLocationNewOverlay = MyLocationNewOverlay(GpsMyLocationProvider(this), mapView) myLocationNewOverlay.enableMyLocation() mapView.overlays.add(myLocationNewOverlay) val dm : DisplayMetrics = resources.displayMetrics val scaleBarOverlay = ScaleBarOverlay(mapView) scaleBarOverlay.setCentred(true) scaleBarOverlay.setScaleBarOffset(dm.widthPixels / 2, 10) mapView.overlays.add(scaleBarOverlay) mioMarker(55.45, 22.48, 1) mioMarker(47.22, 15.48, 2) val pnt1: GeoPoint = GeoPoint(52.50, 13.40) val pnt2: GeoPoint = GeoPoint(42.54, 27.40) val polyline: Polyline = Polyline(mapView) polyline.addPoint(pnt1) polyline.addPoint(pnt2) mapView.overlays.add(polyline) mapView.invalidate() val roadManager:RoadManager = OSRMRoadManager(this, ) val waypoints = ArrayList&lt;GeoPoint&gt;() val startPoint: GeoPoint = GeoPoint(66.7, -14.6) waypoints.add(startPoint) val endPoint: GeoPoint = GeoPoint(48.4, -1.9) waypoints.add(endPoint) val road: Road = roadManager.getRoad(waypoints) val roadOverlay: Polyline = RoadManager.buildRoadOverlay(road) mapView.overlays.add(roadOverlay) mapView.invalidate() } override fun onResume() { super.onResume() mapView.onResume() } override fun onPause() { super.onPause() mapView.onPause() } private fun hasPermission() : Boolean { return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED } private fun requestPermission() { val permission = mutableListOf&lt;String&gt;() if (!hasPermission()) { permission.add(Manifest.permission.ACCESS_FINE_LOCATION) } if (permission.isNotEmpty()) { ActivityCompat.requestPermissions(this, permission.toTypedArray(), 0) } } // fun add Marker private fun mioMarker(lati: Double, longi: Double, i: Int) { val pinMarker = Marker(mapView) val geoPoint = GeoPoint(lati, longi) pinMarker.position = geoPoint pinMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER) pinMarker.title = &quot;Title&quot; pinMarker.subDescription = &quot;i'm pin #$i, my coordinate $lati, $longi.&quot; pinMarker.isDraggable = true mapView.overlays.add(pinMarker) mapView.invalidate() } } </code></pre> <p>this is my manifest:</p> <pre><code> &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; package=&quot;uk.co.lorenzopulcinelli.trackapp&quot;&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot;/&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot;/&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_BACKGROUND_LOCATION&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt; &lt;uses-feature android:name=&quot;android.hardware.location.network&quot; android:required=&quot;false&quot; /&gt; &lt;uses-feature android:name=&quot;android.hardware.location.gps&quot; android:required=&quot;false&quot; /&gt; &lt;uses-feature android:name=&quot;android.hardware.telephony&quot; android:required=&quot;false&quot; /&gt; &lt;uses-feature android:name=&quot;android.hardware.wifi&quot; android:required=&quot;false&quot; /&gt; &lt;application android:allowBackup=&quot;true&quot; android:dataExtractionRules=&quot;@xml/data_extraction_rules&quot; android:fullBackupContent=&quot;@xml/backup_rules&quot; android:icon=&quot;@mipmap/ic_launcher&quot; android:label=&quot;@string/app_name&quot; android:roundIcon=&quot;@mipmap/ic_launcher_round&quot; android:supportsRtl=&quot;true&quot; android:theme=&quot;@style/Theme.TrackApp&quot; tools:targetApi=&quot;31&quot;&gt; &lt;activity android:name=&quot;.MainActivity&quot; android:exported=&quot;true&quot;&gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt; &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>and this is my buil.gradle:</p> <pre><code> plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' } android { compileSdk 32 defaultConfig { applicationId &quot;uk.co.lorenzopulcinelli.trackapp&quot; minSdk 21 targetSdk 32 versionCode 1 versionName &quot;1.0&quot; testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot; } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } } dependencies { implementation 'androidx.preference:preference:1.2.0' //aggiunta per utilizzare import androidx.preference.PreferenceManager implementation 'com.google.android.gms:play-services-location:20.0.0' //aggiunta per richiedere permessi localizzazione implementation 'androidx.core:core-ktx:1.8.0' implementation 'androidx.appcompat:appcompat:1.4.2' implementation 'com.google.android.material:material:1.6.1' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation files('/home/acer/AndroidStudioProjects/TrackApp/app/libs/osmbonuspack_6.9.0.aar') implementation files('/home/acer/AndroidStudioProjects/TrackApp/app/libs/osmdroid-android-6.1.13.aar') androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' } </code></pre> <p>below my Logcat:</p> <pre><code>07/01 17:42:05: Launching 'app' on Xiaomi Redmi Note 7. Install successfully finished in 4 s 662 ms. $ adb shell am start -n &quot;uk.co.lorenzopulcinelli.trackapp/uk.co.lorenzopulcinelli.trackapp.MainActivity&quot; -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Connected to process 28815 on device 'xiaomi-redmi_note_7-16dccaa4'. Capturing and displaying logcat messages from application. This behavior can be disabled in the &quot;Logcat output&quot; section of the &quot;Debugger&quot; settings page. I/Perf: Connecting to perf service. I/FeatureParser: can't find lavender.xml in assets/device_features/,it may be in /system/etc/device_features E/libc: Access denied finding property &quot;ro.vendor.df.effect.conflict&quot; W/inelli.trackapp: type=1400 audit(0.0:93235): avc: denied { read } for name=&quot;u:object_r:vendor_displayfeature_prop:s0&quot; dev=&quot;tmpfs&quot; ino=17716 scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:object_r:vendor_displayfeature_prop:s0 tclass=file permissive=0 E/Perf: Fail to get file list uk.co.lorenzopulcinelli.trackapp E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array I/StorageUtils: /data/user/0/uk.co.lorenzopulcinelli.trackapp/files is writable I/StorageUtils: /storage/emulated/0/Android/data/uk.co.lorenzopulcinelli.trackapp/files is writable I/StorageUtils: /storage/4A6A-676E/Android/data/uk.co.lorenzopulcinelli.trackapp/files is writable I/StorageUtils: /data/user/0/uk.co.lorenzopulcinelli.trackapp/files is writable I/StorageUtils: /storage/emulated/0/Android/data/uk.co.lorenzopulcinelli.trackapp/files is writable I/StorageUtils: /storage/4A6A-676E/Android/data/uk.co.lorenzopulcinelli.trackapp/files is writable D/ForceDarkHelper: updateByCheckExcludeList: pkg: uk.co.lorenzopulcinelli.trackapp activity: uk.co.lorenzopulcinelli.trackapp.MainActivity@148f695 D/ForceDarkHelper: updateByCheckExcludeList: pkg: uk.co.lorenzopulcinelli.trackapp activity: uk.co.lorenzopulcinelli.trackapp.MainActivity@148f695 W/inelli.trackap: Accessing hidden method Landroid/view/View;-&gt;computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed) W/inelli.trackap: Accessing hidden method Landroid/view/ViewGroup;-&gt;makeOptionalFitsSystemWindows()V (greylist, reflection, allowed) D/ForceDarkHelper: updateByCheckExcludeList: pkg: uk.co.lorenzopulcinelli.trackapp activity: uk.co.lorenzopulcinelli.trackapp.MainActivity@148f695 D/ForceDarkHelper: updateByCheckExcludeList: pkg: uk.co.lorenzopulcinelli.trackapp activity: uk.co.lorenzopulcinelli.trackapp.MainActivity@148f695 I/OsmDroid: Using tile source specified in layout attributes: Mapnik I/OsmDroid: Using tile source: Mapnik I/OsmDroid: Tile cache increased from 0 to 9 I/System.out: null I/System.out: creato D/ForceDarkHelper: updateByCheckExcludeList: pkg: uk.co.lorenzopulcinelli.trackapp activity: uk.co.lorenzopulcinelli.trackapp.MainActivity@148f695 D/ForceDarkHelper: updateByCheckExcludeList: pkg: uk.co.lorenzopulcinelli.trackapp activity: uk.co.lorenzopulcinelli.trackapp.MainActivity@148f695 I/chatty: uid=10424(uk.co.lorenzopulcinelli.trackapp) identical 5 lines D/ForceDarkHelper: updateByCheckExcludeList: pkg: uk.co.lorenzopulcinelli.trackapp activity: uk.co.lorenzopulcinelli.trackapp.MainActivity@148f695 D/ForceDarkHelper: updateByCheckExcludeList: pkg: uk.co.lorenzopulcinelli.trackapp activity: uk.co.lorenzopulcinelli.trackapp.MainActivity@148f695 I/chatty: uid=10424(uk.co.lorenzopulcinelli.trackapp) identical 6 lines D/ForceDarkHelper: updateByCheckExcludeList: pkg: uk.co.lorenzopulcinelli.trackapp activity: uk.co.lorenzopulcinelli.trackapp.MainActivity@148f695 I/System.out: inizio I/System.out: passo1 - creoArrayList I/System.out: passo2 - CreoPuntiEAggiungoInArrayList I/System.out: passo3 - CreoStrada D/BONUSPACK: OSRMRoadManager.getRoads:https://routing.openstreetmap.de/routed-car/route/v1/driving/-14.6000000000,66.7000000000;-1.9000000000,48.4000000000?alternatives=false&amp;overview=full&amp;steps=true D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION: main Process: uk.co.lorenzopulcinelli.trackapp, PID: 28815 java.lang.NoClassDefFoundError: Failed resolution of: Lokhttp3/Request$Builder; at org.osmdroid.bonuspack.utils.HttpConnection.doGet(HttpConnection.java:65) at org.osmdroid.bonuspack.utils.BonusPackHelper.requestStringFromUrl(BonusPackHelper.java:59) at org.osmdroid.bonuspack.routing.OSRMRoadManager.getRoads(OSRMRoadManager.java:194) at org.osmdroid.bonuspack.routing.OSRMRoadManager.getRoad(OSRMRoadManager.java:286) at uk.co.lorenzopulcinelli.trackapp.MainActivity.onCreate(MainActivity.kt:132) at android.app.Activity.performCreate(Activity.java:7893) at android.app.Activity.performCreate(Activity.java:7880) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3286) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3460) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2047) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:224) at android.app.ActivityThread.main(ActivityThread.java:7590) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) Caused by: java.lang.ClassNotFoundException: Didn't find class &quot;okhttp3.Request$Builder&quot; on path: DexPathList[[zip file &quot;/data/app/uk.co.lorenzopulcinelli.trackapp-jx1_0YR4HzgrzlHgIcGy8w==/base.apk&quot;],nativeLibraryDirectories=[/data/app/uk.co.lorenzopulcinelli.trackapp-jx1_0YR4HzgrzlHgIcGy8w==/lib/arm64, /system/lib64, /system/product/lib64]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:230) at java.lang.ClassLoader.loadClass(ClassLoader.java:379) at java.lang.ClassLoader.loadClass(ClassLoader.java:312) at org.osmdroid.bonuspack.utils.HttpConnection.doGet(HttpConnection.java:65)  at org.osmdroid.bonuspack.utils.BonusPackHelper.requestStringFromUrl(BonusPackHelper.java:59)  at org.osmdroid.bonuspack.routing.OSRMRoadManager.getRoads(OSRMRoadManager.java:194)  at org.osmdroid.bonuspack.routing.OSRMRoadManager.getRoad(OSRMRoadManager.java:286)  at uk.co.lorenzopulcinelli.trackapp.MainActivity.onCreate(MainActivity.kt:132)  at android.app.Activity.performCreate(Activity.java:7893)  at android.app.Activity.performCreate(Activity.java:7880)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3286)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3460)  at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2047)  at android.os.Handler.dispatchMessage(Handler.java:107)  at android.os.Looper.loop(Looper.java:224)  at android.app.ActivityThread.main(ActivityThread.java:7590)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)  I/Process: Sending signal. PID: 28815 SIG: 9 </code></pre>
3
8,589
Placing an <h3> over a form/div
<p>I've got this HTML code and i want to place an above this but, whatever i am doing, it is always placed to left side of the form.</p> <p>I know it's a very basic question but i am not that experienced in CSS. How am i supposed to do this? Is there a w3-class that will do this for me? </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.bookbox{ padding-top: 10px !important; padding-bottom: 10px !important; display: flex !important; align-items: center !important; justify-content: center !important; background-color: #FFFFFF; margin: 16px !important; box-shadow:0 4px 10px 0 rgba(0,0,0,0.2),0 4px 20px 0 rgba(0,0,0,0.19); } .bookcard{ margin-top: 120px !important; margin-bottom: 120px !important; display: flex !important; align-items: center !important; justify-content: center !important; background-color: #FFFFFF; clear: both; } .float-left { float: left !important; } .m-1 { margin: 0.25rem !important; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="bookbox"&gt; &lt;h3&gt;I'd like this to place above the bookcard&lt;/h3&gt; &lt;div class="bookcard"&gt; &lt;form class="w3-container" method="GET" action="{{config('app.PATH_TO_INDEX', '')}}/findCar"&gt; &lt;div class="float-left m-1"&gt; &lt;input type="text" name="Standort" list="Standorte" class="w3-input w3-border" placeholder="Standort"&gt; &lt;datalist id="Standorte"&gt; &lt;option value="example"&gt;&lt;/option&gt; &lt;/datalist&gt; &lt;/div&gt; &lt;div class="float-left m-1"&gt; &lt;input type="text" name="Startdatum" class="date w3-input w3-border" id="f0date" placeholder="Startdatum"&gt; &lt;/div&gt; &lt;div class="float-left m-1"&gt; &lt;input type="text" name="Enddatum" class="date w3-input w3-border {{ $errors-&gt;has('Enddatum') ? 'border-danger' : '' }}" id="f1date" placeholder="Enddatum"&gt; &lt;/div&gt; &lt;div class="float-left m-1"&gt; &lt;button type="submit" class="w3-button margin-small signalButton w3-hover-text-blue w3-blue-grey w3-hover-blue-grey w3-hover-opacity" id="submit0"&gt;Fahrzeug finden&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Thanks for your help</p>
3
1,183
The dropdown menu button stays open and won't close
<p>I have got a dropdown menu button and when clicked on the icon it should open and when clicking off the icon or on the icon then it should close again, but instead it stays open.</p> <p>Here is a screenshot, to what i am referring too.</p> <p><a href="https://imgur.com/VbU5nit" rel="nofollow noreferrer">https://imgur.com/VbU5nit</a></p> <p>I have researched regarding this issue, but i am unable to find a solution.</p> <p>My CSS is on paste bin at <a href="https://pastebin.com/BHXNjtWJ" rel="nofollow noreferrer">https://pastebin.com/BHXNjtWJ</a></p> <p>This is because the CSS is to long to fit on here.</p> <p>My HTML is:</p> <pre><code>&lt;body class="twoCol react menuOpen" data-tippy-delegate=""&gt; &lt;div id="fb-root"&gt;&lt;/div&gt; &lt;div id="app-root" class="notranslate" data-tippy-delegate=""&gt; &lt;div class="Master__wrap__22Bnx en-US"&gt; &lt;div class="NavigationTop__wrap__fQdBR"&gt; &lt;div class="NavigationTop__inner__1LxZ7" data-ui-name="headerNavigation"&gt; &lt;ul class="NavigationMain__nav__3NRm2"&gt; &lt;li class="NavigationMain__signUp__2YtN8"&gt;&lt;a href="https://signin.rockstargames.com/create/?cid=socialclub&amp;amp;lang=en-US&amp;amp;returnUrl=%2F" class="NavigationMain__navLink__1xmUY NavigationMain__navLinkHighlight__pgt2K" data-ui-name="signUp"&gt;Sign Up&lt;/a&gt;&lt;/li&gt; &lt;li class="NavigationMain__signIn__3thGS"&gt;&lt;a href="https://signin.rockstargames.com/connect/authorize/socialclub?lang=en-US&amp;amp;returnUrl=%2F" class="NavigationMain__navLink__1xmUY" data-ui-name="signIn"&gt;Sign In&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLink__1xmUY" data-ui-name="games" href="/games"&gt;Games&lt;span&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" height="16" width="16" class="NavigationMain__navLinkToggle__2xOGg"&gt;&lt;path d="M16 25.9c-.4 0-.8-.2-1-.5L.3 8.4c-.5-.6-.4-1.4.2-1.9.6-.5 1.4-.5 1.9.1L16 22.4 29.6 6.6c.5-.6 1.3-.6 1.9-.1.6.5.6 1.4.1 1.9L17 25.4c-.2.3-.6.5-1 .5z"&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="NavigationMain__navSub__3W27M"&gt;&lt;li&gt;&lt;a class="NavigationMain__navLinkSub__2T3V5" data-ui-name="rdr2" href="#"&gt;Title&lt;span&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" height="16" width="16" class="NavigationMain__navLinkToggle__2xOGg"&gt; &lt;path d="M16 25.9c-.4 0-.8-.2-1-.5L.3 8.4c-.5-.6-.4-1.4.2-1.9.6-.5 1.4-.5 1.9.1L16 22.4 29.6 6.6c.5-.6 1.3-.6 1.9-.1.6.5.6 1.4.1 1.9L17 25.4c-.2.3-.6.5-1 .5z"&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="NavigationMain__navSubSub__2bkYi"&gt; &lt;li&gt;&lt;a class="NavigationMain__navLinkSub__2T3V5" href="#"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLinkSub__2T3V5" href="#"&gt;Story&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLinkSub__2T3V5" href="#"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLinkSub__2T3V5" href="#"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLinkSub__2T3V5" href="Title"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLinkSub__2T3V5" href="#"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLinkSub__2T3V5" href="#"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLinkSub__2T3V5" data-ui-name="gtav"&gt;Title&lt;span&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" height="16" width="16" class="NavigationMain__navLinkToggle__2xOGg"&gt;&lt;path d="M16 25.9c-.4 0-.8-.2-1-.5L.3 8.4c-.5-.6-.4-1.4.2-1.9.6-.5 1.4-.5 1.9.1L16 22.4 29.6 6.6c.5-.6 1.3-.6 1.9-.1.6.5.6 1.4.1 1.9L17 25.4c-.2.3-.6.5-1 .5z"&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="NavigationMain__navSubSub__2bkYi"&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLinkSub__2T3V5" data-ui-name="gtavCareer"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLinkSub__2T3V5" data-ui-name="gtavAccomplishments"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLinkSub__2T3V5" data-ui-name="gtavTutorials"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLinkSub__2T3V5" data-ui-name="playlists"&gt;Playlists&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLinkSub__2T3V5" data-ui-name="lan"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLinkSub__2T3V5" data-ui-name="lanvr"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLinkSub__2T3V5" data-ui-name="bully"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLinkSub__2T3V5" data-ui-name="allGames" href="/games"&gt;All Games&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="NavigationMain__overlay__3SibJ"&gt;&lt;/div&gt;&lt;/li&gt;&lt;li&gt;&lt;a class="NavigationMain__navLink__1xmUY" data-ui-name="crews" href="/crews"&gt;Title&lt;span&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" height="16" width="16" class="NavigationMain__navLinkToggle__2xOGg"&gt;&lt;path d="M16 25.9c-.4 0-.8-.2-1-.5L.3 8.4c-.5-.6-.4-1.4.2-1.9.6-.5 1.4-.5 1.9.1L16 22.4 29.6 6.6c.5-.6 1.3-.6 1.9-.1.6.5.6 1.4.1 1.9L17 25.4c-.2.3-.6.5-1 .5z"&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="NavigationMain__navSub__3W27M"&gt;&lt;li&gt;&lt;a class="NavigationMain__navLinkSub__2T3V5" data-ui-name="crewSearch" href="/crews"&gt;Search&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLinkSub__2T3V5" data-ui-name="myCrews"&gt;Create a Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLinkSub__2T3V5" data-ui-name="emblemEditor"&gt;Title Editor&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="NavigationMain__overlay__3SibJ"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLink__1xmUY" data-ui-name="jobs" href="/jobs"&gt;Jobs&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLink__1xmUY" data-ui-name="photos" href="/photos"&gt;Photos&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="NavigationMain__navLink__1xmUY" data-ui-name="videos" href="/videos"&gt;Videos&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/events" class="NavigationMain__navLink__1xmUY" data-ui-name="events"&gt;Events&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationMain__navLink__1xmUY" data-ui-name="news" target="_blank"&gt;News&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="NavigationTop__groupLeft__3lTQW"&gt; &lt;a href="#" class="NavigationTop__icon__32Kg3 NavigationTop__hamburger__KU-ur"&gt; &lt;span class="NavigationTop__iconBg__3nlrW"&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" height="16" width="16" class="UI__Icon__icon"&gt;&lt;path d="M24.8 10.6H7.3c-.8 0-1.4-.6-1.4-1.4 0-.8.6-1.4 1.4-1.4h17.5c.8 0 1.4.6 1.4 1.4 0 .8-.6 1.4-1.4 1.4zM24.9 17.3H7.4c-.8 0-1.4-.6-1.4-1.4s.6-1.4 1.4-1.4h17.5c.8 0 1.4.6 1.4 1.4s-.7 1.4-1.4 1.4zM24.9 24H7.4c-.8 0-1.4-.6-1.4-1.4s.6-1.4 1.4-1.4h17.5c.8 0 1.4.6 1.4 1.4s-.7 1.4-1.4 1.4z"&gt;&lt;/path&gt;&lt;path d="M25.1 32H3.3C1.5 32 0 30.5 0 28.7V3.3C0 1.5 1.5 0 3.3 0h25.3C30.5 0 32 1.5 32 3.3v21.9c0 .8-.6 1.4-1.4 1.4-.8 0-1.4-.6-1.4-1.4V3.3c0-.3-.3-.6-.6-.6H3.3c-.3 0-.6.3-.6.6v25.3c0 .3.3.6.6.6h21.8c.8 0 1.4.6 1.4 1.4 0 .8-.6 1.4-1.4 1.4z"&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/span&gt;&lt;/a&gt;&lt;ul class="NavigationTop__nav__1InFQ NavigationTop__navSignedOut__2qibz"&gt; &lt;li&gt;&lt;a href="#" class="NavigationTop__navLink__k_LuP" data-ui-name="signIn"&gt;Sign In&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationTop__navLink__k_LuP NavigationTop__navLinkHighlight__2uEEp" data-ui-name="signUp"&gt;Sign Up&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;a href="#" class="NavigationTop__icon__32Kg3 NavigationTop__search__UDzfT" data-ui-name="scSearch"&gt;&lt;span class="NavigationTop__iconBg__3nlrW"&gt;&lt;svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" height="16" width="16" class="UI__Icon__icon"&gt;&lt;path d="M30.5 32c-.4 0-.8-.1-1.1-.4l-9.3-9.3c-.6-.6-.6-1.5 0-2.1 3.9-4 3.9-10.3 0-14.2-1.9-1.9-4.4-3-7.1-3-2.6 0-5.1 1.1-7 3-3.9 3.9-3.9 10.2 0 14.1 2.4 2.4 5.7 3.4 9 2.7.8-.1 1.6.4 1.8 1.2.2.8-.4 1.6-1.2 1.8-4.3.8-8.7-.5-11.7-3.6-5.1-5.1-5.1-13.4 0-18.5C6.3 1.4 9.6 0 13 0c3.5 0 6.8 1.4 9.2 3.8 4.7 4.7 5.1 12.2 1 17.3l8.3 8.3c.6.6.6 1.5 0 2.1-.2.4-.6.5-1 .5z"&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;a class="NavigationTop__logo__3GmAs" data-ui-name="logo" href="/"&gt; &lt;div class="NavigationTop__logoRockstar__1m1Ou"&gt; &lt;/div&gt; &lt;div class="NavigationTop__logoSocialClub__1EfPy"&gt; &lt;/div&gt; &lt;/a&gt; &lt;div class="NavigationTop__groupRight__3UIqi"&gt;&lt;span class="NavigationTop__navPlayer__2TGn7"&gt;&lt;a href="#" class="NavigationTop__icon__32Kg3" data-ui-name="info"&gt;&lt;span class="NavigationTop__iconBg__3nlrW"&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" height="16" width="16" class="UI__Icon__icon"&gt;&lt;path d="M15.6 32s-.1 0 0 0h-.8c-2.7 0-5.6 0-8.4-.8-3-.9-4.6-2.4-4.7-4.7-.1-1.1.3-2.2 1-3.1 1.1-1.5 2.7-2.4 4.1-3.1.5-.3 1-.5 1.5-.8.6-.4 2-1.4 2.1-2.7 0-.6-.2-1.3-.8-2.1l-.6-.9c-.4-.6-.8-1.2-1.2-1.9-1.2-2.5-1-5.6.4-7.9.2-.3.4-.6.7-.9 1.8-2 4.3-3.1 7-3.1 2.7-.1 5.3 1.1 7.2 3 .3.3.6.7.8 1 1.4 2.3 1.5 5.4.3 7.9-.4.7-.8 1.3-1.2 1.9l-.6.9c-.5.8-.8 1.5-.8 2.1.1 1.3 1.5 2.3 2.1 2.7.5.3 1 .6 1.5.8 1.4.7 3 1.5 4.1 3.1.7.9 1 2.1 1 3.1-.1 2.2-1.7 3.8-4.7 4.7-.7.2-1.4.3-2 .5-.7.1-1.5-.4-1.6-1.1-.1-.7.4-1.5 1.1-1.6.6-.1 1.2-.2 1.7-.4 2.4-.7 2.7-1.5 2.7-2.2 0-.5-.1-.9-.5-1.4-.7-1-1.9-1.6-3.1-2.3-.6-.3-1.1-.6-1.7-.9-2.1-1.3-3.3-3-3.4-4.9-.1-1.2.3-2.4 1.2-3.8.2-.3.4-.7.7-1 .4-.5.7-1 1-1.5.8-1.6.7-3.6-.2-5.2-.1-.1-.2-.2-.4-.5-1.3-1.4-3.2-2.2-5.2-2.2-1.9 0-3.7.8-5 2.2-.2.2-.3.4-.4.5-.9 1.6-1 3.6-.2 5.2.3.5.6 1 1 1.5.2.3.5.6.7 1 .9 1.3 1.3 2.6 1.2 3.8-.1 1.9-1.3 3.6-3.4 4.9-.5.3-1.1.6-1.7.9C6.9 23.4 5.7 24 5 25c-.3.4-.5.9-.5 1.4 0 .7.4 1.5 2.7 2.2 2.4.7 4.9.7 7.6.7h.8c.4 0 .8.2 1 .5.3.3.4.7.3 1.1 0 .6-.6 1.1-1.3 1.1z"&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/span&gt;&lt;/a&gt; &lt;div class="NavigationPlayer__nav__1GtYE NavigationPlayer__navOpen__kmIqC"&gt;&lt;ul class="NavigationPlayer__navSub__SIRkf"&gt;&lt;li class="NavigationPlayer__signUp__2AOMK"&gt;&lt;a href="https://signin.rockstargames.com/create/?cid=socialclub&amp;amp;lang=en-US&amp;amp;returnUrl=%2F" class="NavigationPlayer__navLink__2oeuj NavigationPlayer__highlight__2lzxA" data-ui-name="signUp"&gt;Sign Up&lt;/a&gt;&lt;/li&gt; &lt;li class="NavigationPlayer__signIn__3qaVH"&gt;&lt;a href="#" class="NavigationPlayer__navLink__2oeuj" data-ui-name="signIn"&gt;Sign In&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#" class="NavigationPlayer__navLink__2oeuj" data-ui-name="legal"&gt;Legal&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#" class="NavigationPlayer__navLink__2oeuj" data-ui-name="privacy"&gt;Privacy&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationPlayer__navLink__2oeuj" data-ui-name="support"&gt;Support&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationPlayer__navLink__2oeuj" data-ui-name="cookies"&gt;Cookies&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;div class="NavigationPlayer__languageWrap__2jmcz"&gt; &lt;div class="UI__DropDown__custom-select LanguageSelector__dropdown__2uNdg"&gt; &lt;select class="select" data-ui-name="languageSelector"&gt; &lt;option value="de-DE"&gt;Deutsch&lt;/option&gt; &lt;option value="en-US"&gt;English&lt;/option&gt; &lt;option value="es-ES"&gt;Español&lt;/option&gt; &lt;option value="es-MX"&gt;Español Latinoamérica&lt;/option&gt; &lt;option value="fr-FR"&gt;Français&lt;/option&gt; &lt;option value="it-IT"&gt;Italiano&lt;/option&gt; &lt;option value="ja-JP"&gt;日本語&lt;/option&gt; &lt;option value="ko-KR"&gt;한국어&lt;/option&gt; &lt;option value="pl-PL"&gt;Polski&lt;/option&gt; &lt;option value="pt-BR"&gt;Português do Brasil&lt;/option&gt; &lt;option value="ru-RU"&gt;Русский&lt;/option&gt; &lt;option value="zh-TW"&gt;繁體中文&lt;/option&gt; &lt;option value="zh-CN"&gt;简体中文&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>Updated code below:</p> <pre><code>&lt;div class="dropdown"&gt; &lt;div class="NavigationTop__groupRight__3UIqi"&gt;&lt;span class="NavigationTop__navPlayer__2TGn7"&gt;&lt;a onclick="myFunction()" href="#" class="NavigationTop__icon__32Kg3" data-ui-name="info"&gt;&lt;span class="NavigationTop__iconBg__3nlrW" class="dropbtn"&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" height="16" width="16" class="UI__Icon__icon"&gt;&lt;path d="M15.6 32s-.1 0 0 0h-.8c-2.7 0-5.6 0-8.4-.8-3-.9-4.6-2.4-4.7-4.7-.1-1.1.3-2.2 1-3.1 1.1-1.5 2.7-2.4 4.1-3.1.5-.3 1-.5 1.5-.8.6-.4 2-1.4 2.1-2.7 0-.6-.2-1.3-.8-2.1l-.6-.9c-.4-.6-.8-1.2-1.2-1.9-1.2-2.5-1-5.6.4-7.9.2-.3.4-.6.7-.9 1.8-2 4.3-3.1 7-3.1 2.7-.1 5.3 1.1 7.2 3 .3.3.6.7.8 1 1.4 2.3 1.5 5.4.3 7.9-.4.7-.8 1.3-1.2 1.9l-.6.9c-.5.8-.8 1.5-.8 2.1.1 1.3 1.5 2.3 2.1 2.7.5.3 1 .6 1.5.8 1.4.7 3 1.5 4.1 3.1.7.9 1 2.1 1 3.1-.1 2.2-1.7 3.8-4.7 4.7-.7.2-1.4.3-2 .5-.7.1-1.5-.4-1.6-1.1-.1-.7.4-1.5 1.1-1.6.6-.1 1.2-.2 1.7-.4 2.4-.7 2.7-1.5 2.7-2.2 0-.5-.1-.9-.5-1.4-.7-1-1.9-1.6-3.1-2.3-.6-.3-1.1-.6-1.7-.9-2.1-1.3-3.3-3-3.4-4.9-.1-1.2.3-2.4 1.2-3.8.2-.3.4-.7.7-1 .4-.5.7-1 1-1.5.8-1.6.7-3.6-.2-5.2-.1-.1-.2-.2-.4-.5-1.3-1.4-3.2-2.2-5.2-2.2-1.9 0-3.7.8-5 2.2-.2.2-.3.4-.4.5-.9 1.6-1 3.6-.2 5.2.3.5.6 1 1 1.5.2.3.5.6.7 1 .9 1.3 1.3 2.6 1.2 3.8-.1 1.9-1.3 3.6-3.4 4.9-.5.3-1.1.6-1.7.9C6.9 23.4 5.7 24 5 25c-.3.4-.5.9-.5 1.4 0 .7.4 1.5 2.7 2.2 2.4.7 4.9.7 7.6.7h.8c.4 0 .8.2 1 .5.3.3.4.7.3 1.1 0 .6-.6 1.1-1.3 1.1z"&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/span&gt;&lt;/a&gt; &lt;div class="NavigationPlayer__nav__1GtYE NavigationPlayer__navOpen__kmIqC"&gt;&lt;ul class="NavigationPlayer__navSub__SIRkf"&gt;&lt;li class="NavigationPlayer__signUp__2AOMK"&gt;&lt;a href="https://signin.rockstargames.com/create/?cid=socialclub&amp;amp;lang=en-US&amp;amp;returnUrl=%2F" class="NavigationPlayer__navLink__2oeuj NavigationPlayer__highlight__2lzxA" data-ui-name="signUp"&gt;Sign Up&lt;/a&gt;&lt;/li&gt; &lt;li class="NavigationPlayer__signIn__3qaVH"&gt;&lt;a href="https://signin.rockstargames.com/connect/authorize/socialclub?lang=en-US&amp;amp;returnUrl=%2F" class="NavigationPlayer__navLink__2oeuj" data-ui-name="signIn"&gt;Sign In&lt;/a&gt;&lt;/li&gt; &lt;div id="myDropdown" class="dropdown-content" &lt;li&gt;&lt;a href="https://www.rockstargames.com/legal" class="NavigationPlayer__navLink__2oeuj" data-ui-name="legal"&gt;Legal&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="https://www.rockstargames.com/privacy" class="NavigationPlayer__navLink__2oeuj" data-ui-name="privacy"&gt;Privacy&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationPlayer__navLink__2oeuj" data-ui-name="support"&gt;Support&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="NavigationPlayer__navLink__2oeuj" data-ui-name="cookies"&gt;Cookies&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;div class="NavigationPlayer__languageWrap__2jmcz"&gt; &lt;div class="UI__DropDown__custom-select LanguageSelector__dropdown__2uNdg"&gt; &lt;select class="select" data-ui-name="languageSelector"&gt; &lt;option value="de-DE"&gt;Deutsch&lt;/option&gt; &lt;option value="en-US"&gt;English&lt;/option&gt; &lt;option value="es-ES"&gt;Español&lt;/option&gt; &lt;option value="es-MX"&gt;Español Latinoamérica&lt;/option&gt; &lt;option value="fr-FR"&gt;Français&lt;/option&gt; &lt;option value="it-IT"&gt;Italiano&lt;/option&gt; &lt;option value="ja-JP"&gt;日本語&lt;/option&gt; &lt;option value="ko-KR"&gt;한국어&lt;/option&gt; &lt;option value="pl-PL"&gt;Polski&lt;/option&gt; &lt;option value="pt-BR"&gt;Português do Brasil&lt;/option&gt; &lt;option value="ru-RU"&gt;Русский&lt;/option&gt; &lt;option value="zh-TW"&gt;繁體中文&lt;/option&gt; &lt;option value="zh-CN"&gt;简体中文&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;script&gt; /* When the user clicks on the button, toggle between hiding and showing the dropdown content */ function myFunction() { document.getElementById("dropdown").classList.toggle("show"); } // Close the dropdown if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i &lt; dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } &lt;/script&gt; </code></pre> <p>Any help appreciated and thanks in advance</p>
3
11,980
Django 3 ModelForm NameError? I'm sure there's a glaring error but I just cannot see it?
<p>Hoping for a bit of help, I've been trying to deal with this error for about 3hrs and I'm going around in circles.</p> <p>Django 3 project. It's a simple app for leaving a review for a product and I keep getting a NameError and I just can't figure out what it is?</p> <h1>models.py</h1> <pre><code>from django.db import models from django.forms import ModelForm, Textarea, CharField from django.conf import settings from django.contrib.auth.models import User from products.models import Product SCORE_CHOICES = [ ('1', 'One'), ('2', 'Two'), ('3', 'Three'), ('4', 'Four'), ('5', 'Five'), ] class Review(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) date = models.DateField() review_title = models.CharField(max_length=100, blank=False) review_text = models.TextField(default='') score = models.CharField(max_length=3, choices=SCORE_CHOICES) def __str__(self): return f'Review for user {self.user.username}' class ReviewForm(ModelForm): class Meta: model = Review fields = ['user', 'product', 'date', 'review_title', 'review_text', 'score'] widgets = { 'review_text': Textarea(attrs={'cols': 100, 'rows': 20}), } </code></pre> <h1>forms.py</h1> <pre><code>from django import forms from django.forms import ModelForm from products.models import Product from review.models import Review, ReviewForm class ReviewForm(forms.Form): product = forms.ModelMultipleChoiceField(queryset=Product.objects.all()) review_title = forms.CharField(max_length=100) review_text = forms.CharField(max_length=100, widget=forms.Textarea) score = forms.CharField( max_length=3, widget=forms.Select(choices=SCORE_CHOICES), ) date = forms.DateField(auto_now=True, editable=False, null=False, blank=False) user = forms.CharField(max_length=100) </code></pre> <h1>views.py</h1> <pre><code>from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from .forms import * @login_required def writeReview(request): if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks') else: form = ReviewForm() context = {'form': form, 'menu_class': 'menu-login'} return render(request, 'review/displayWriteReview.html', context) </code></pre> <p>I keep getting the following error and just cannot see it. Calling it a day but if anyone can point me in the right direction where I've gone wrong I'd be so very appreciative.</p> <h1>Error</h1> <pre><code>Traceback (most recent call last): File &quot;manage.py&quot;, line 21, in &lt;module&gt; main() File &quot;manage.py&quot;, line 17, in main execute_from_command_line(sys.argv) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/core/management/__init__.py&quot;, line 401, in execute_from_command_line utility.execute() File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/core/management/__init__.py&quot;, line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/core/management/base.py&quot;, line 328, in run_from_argv self.execute(*args, **cmd_options) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/core/management/base.py&quot;, line 369, in execute output = self.handle(*args, **options) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/core/management/commands/check.py&quot;, line 64, in handle fail_level=getattr(checks, options['fail_level']), File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/core/management/base.py&quot;, line 395, in check include_deployment_checks=include_deployment_checks, File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/core/management/base.py&quot;, line 382, in _run_checks return checks.run_checks(**kwargs) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/core/checks/registry.py&quot;, line 72, in run_checks new_errors = check(app_configs=app_configs) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/core/checks/urls.py&quot;, line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/core/checks/urls.py&quot;, line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/utils/functional.py&quot;, line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/urls/resolvers.py&quot;, line 588, in url_patterns patterns = getattr(self.urlconf_module, &quot;urlpatterns&quot;, self.urlconf_module) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/utils/functional.py&quot;, line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/urls/resolvers.py&quot;, line 581, in urlconf_module return import_module(self.urlconf_name) File &quot;/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/importlib/__init__.py&quot;, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1006, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 983, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 967, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 677, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 728, in exec_module File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 219, in _call_with_frames_removed File &quot;/Users/peggy/candles/candles/urls.py&quot;, line 29, in &lt;module&gt; path('review/', include('review.urls')), File &quot;/Users/peggy/candles/.env/lib/python3.7/site-packages/django/urls/conf.py&quot;, line 34, in include urlconf_module = import_module(urlconf_module) File &quot;/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/importlib/__init__.py&quot;, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1006, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 983, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 967, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 677, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 728, in exec_module File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 219, in _call_with_frames_removed File &quot;/Users/peggy/candles/review/urls.py&quot;, line 3, in &lt;module&gt; from review import views File &quot;/Users/peggy/candles/review/views.py&quot;, line 4, in &lt;module&gt; from .forms import * File &quot;/Users/peggy/candles/review/forms.py&quot;, line 6, in &lt;module&gt; class ReviewForm(forms.Form): File &quot;/Users/peggy/candles/review/forms.py&quot;, line 12, in ReviewForm widget=forms.Select(choices=SCORE_CHOICES), NameError: name 'SCORE_CHOICES' is not defined </code></pre> <p>Sincerest of thanks in advance for any help.</p> <p>Wayne :)</p>
3
3,081
Retrofit response returning null in Android Studio
<p>I want to fetch live data from coinbase api. I'm using Retrofit to make API call I got a null response when i tried returning displaying the data</p> <p>the json response from the api <strong>JSON</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>{"data":{"base":"BTC","currency":"USD","amount":"9510.915"}}</code></pre> </div> </div> </p> <p>The retrofit class for the returned data <strong>RETROFIT</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> myC2C = RetrofitClient.getInstance("https://api.coinbase.com/v2/prices/").create(IMyC2C.class); Call&lt;DataList&gt; call = myC2C.getPrice("USD"); call.enqueue(new Callback&lt;DataList&gt;() { @Override public void onResponse(Call&lt;DataList&gt; call, Response&lt;DataList&gt; response) { if (!response.isSuccessful()){ usd_price.setText("Code: " + response.code()); return; } Log.d("resedatasync", new Gson().toJson(response.body().getDatas())); } @Override public void onFailure(Call&lt;DataList&gt; call, Throwable t) { usd_price.setText(t.getMessage()); }</code></pre> </div> </div> </p> <p>The endpoint that calls get methods and parse the type of currency <strong>ENDPOINT</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>@GET("spot") Call&lt;DataList&gt; getPrice(@Query("currency") String currency);</code></pre> </div> </div> </p> <p>the java model class here **JAVA CLASS</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>import java.util.List; public class DataList { private Datas Datas; public Datas getDatas() { return Datas; } public void setDatas(Datas datas) { this.Datas = datas; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>package com.example.c2c.Model; public class Datas { private String base; private String currency; private float amount; public String getBase() { return base; } public void setBase(String base) { this.base = base; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public float getAmount() { return amount; } public void setAmount(float amount) { this.amount = amount; } }</code></pre> </div> </div> </p> <p>**</p>
3
1,304
header position of the grid not fixed while printing,
<p>there is a grid that populates data,</p> <pre><code>&lt;asp:Panel ID="Panel1" runat="server" ScrollBars="Auto" Width="1000px" Height="8000px" BorderColor="Black" BorderWidth="1px" Visible="true" BackColor="LightGray"&gt; &lt;asp:GridView ID="List" runat="server" Visible="False" OnRowDataBound="List_RowDataBound" AutoGenerateColumns="true"&gt; &lt;HeaderStyle CssClass="gridstyleHead" /&gt; &lt;RowStyle CssClass="gridRowstyle" /&gt; &lt;/asp:GridView&gt; </code></pre> <p>and there is a style sheet that applies to grid </p> <pre><code>.gridstyleHead { white-space: nowrap; text-align: left; font-family: Arial; font-size: 10pt; font-weight: lighter; padding-left: 3px; position: relative; top: expression(this.offsetParent.scrollTop); z-index: 10; } .gridRowstyle { white-space: nowrap; border-width: 1px; background-color: white; font-family: Arial; font-size: 9pt; height: 29px; </code></pre> <p>}</p> <p>i am trying to print the data that is in grid</p> <pre><code>function btnPrint_Click() { varfoo="toolbar=yes,location=no,directories=yes,menubar=yes,scrollbars=yes, width=500,height=600,left=50,top=25"; varprintdata=document.getElementById('&lt;%=Panel1.ClientID%&gt;').innerHTML; var printWindow = window.open('', 'PRINT', foo); var radioButtons = document.getElementsByName("ordrcvd"); var ord = ''; for (var x = 0; x &lt; radioButtons.length; x++) { if (radioButtons[x].checked) { ord = radioButtons[x].value; } } printWindow.document.write('&lt;html&gt;&lt;head&gt;&lt;link rel="stylesheet" href="css/invoice.css" /&gt;'); printWindow.document.write(' &lt;/head&gt;&lt;body&gt;'); printWindow.document.write('&lt;table&gt;'); printWindow.document.write('&lt;tr&gt;&lt;td style = "font-weight:bold;font-family:arial;font-size:12"&gt; order Received' + '&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; : '); printWindow.document.write('&lt;/td&gt;&lt;td style = "font-weight:normal;font-family:arial;font-size:12"&gt;'); printWindow.document.write(document.getElementById('&lt;%= txtordRcvd.ClientID%&gt;').value); printWindow.document.write('&lt;/td&gt;&lt;/tr&gt;'); printWindow.document.write('&lt;tr&gt;&lt;td&gt; &lt;/br&gt;'); printWindow.document.write('&lt;/td&gt;&lt;/tr&gt;'); printWindow.document.write(' &lt;/table&gt;'); printWindow.document.write(printContent); printWindow.document.write('&lt;/body&gt;&lt;/html&gt;'); printWindow.document.close(); printWindow.focus(); return false; } </code></pre> <p>but the problem is header in the grid is not fixed and the one am printing is showing the grid with header not fixed.</p> <p>Header in the grid being not fixed is fine but when am trying to print that grid and scroll down, the header position is misplaced.</p> <p>can anyone suggest how to apply stylesheet for the grid that am printing, so that header will be fixed </p> <p>Thanks in advance,</p>
3
1,265
How to speed up document append to existing array in elasticsearch?
<p>I am using elasticsearch version 6.3.1. And I am creating a nested type field,I have created this field to append all the documents of same ID.</p> <p>Here is my schema for index:-</p> <pre><code>curl -XPUT 'localhost:9200/axes_index_test12?pretty' -H 'Content-Type: application/json' -d' { "mappings": { "axes_type_test12": { "properties": { "totalData": { "type": "nested", "properties": { "gpsdt": { "type": "date", "format":"dateOptionalTime" }, "extbatlevel": { "type": "integer" }, "intbatlevel" : { "type" : "integer" }, "lastgpsdt": { "type": "date", "format":"dateOptionalTime" }, "satno" : { "type" : "integer" }, "srtangle" : { "type" : "integer" } } }, "imei": { "type": "long" }, "date": { "type": "date", "format":"dateOptionalTime" }, "id" : { "type" : "long" } } } } }' </code></pre> <p>And to append into existing array I call following API : -</p> <p>Here is the documents which I have to append:-</p> <pre><code>data={ "script" : {"source": "ctx._source.totalData.add(params.count)", "lang": "painless", "params" : {"count" : { "gpsdt" : gpsdt, "analog1" : analog1, "analog2" : analog2, "analog3" : analog3, "analog4" : analog4, "digital1" : digital1, "digital2" : digital2, "digital3" : digital3, "digital4" : digital4, "extbatlevel" : extbatlevel, "intbatlevel" : intbatlevel, "lastgpsdt" : lastgpsdt, "latitude" : latitude, "longitude" : longitude, "odo" : odo, "odometer" : odometer, "satno" : satno, "srtangle" : srtangle, "speed" : speed } } } } </code></pre> <p>Document Parsing:-</p> <pre><code>json_data = json.dumps(data) </code></pre> <p>And API url is: -</p> <pre><code>API_ENDPOINT = "http://localhost:9200/axes_index_test12/axes_type_test12/"+str(documentId)+"/_update" </code></pre> <p>And Finnaly I call this API:-</p> <pre><code>headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url = API_ENDPOINT, data = json_data,headers=headers </code></pre> <p>Everything is fine with this but I am not getting good performance when I append new documents in existing array.</p> <p>So please suggest me what changes I should make? And I have 4 node cluster, 1 master, 2 data nodes and one cordinator node.</p>
3
2,353
Generate new matrix from old matrix with specific conditions
<p>I have matrix <code>R(100*100)</code> and I want to generate new matrix <code>A(100*100)</code> as below conditions</p> <p>If I have a frequency to add a new condition<code>(let us say frequency = 20)</code>. This mean I will have five conditions inside my domain `(100/20)=5</p> <pre><code>From 1 to 20, from 21 to 40, from 41 to 60, from 61 to 80, and from 81 to 100. </code></pre> <p>Let us assume my original matrix is</p> <pre><code> [1 1 1……..1] [2 2 2 …….2] [3 3 3 ………3] And so on [100 100 100 …..100] </code></pre> <p>The new matrix must be</p> <pre><code>From 1 to 20 same as old matrix [1 1 1……..1] [2 2 2 …….2] [3 3 3………3] From 21 to 40 A(21,j)=R(21,j)+R(1,j) (row 21 + row 1) A(22,j)=R(22,j)+R(2,j) (row 22 + row 2) A(23,j)=R(23,j)+R(3,j) (row 23 + row 3) And so on From 41 to 60 A(41,j)=R(41,j)+R(21,j) +R(1,j) (row 41+row 21 + row 1) A(42,j)=R(42,j)+R(22,j) +R(2,j) (row 42+row 22 + row 2) And so on A(81,j)=R(81,j)+R(61,j)+R(41,j)+R(21,j)+R(1,j) (row 81+row 61 + row 41 + row 21+ row 1) </code></pre> <p>At each time that I reach to the frequency, I will have a new condition. My question is there any sufficient way to do that? I wrote my code and its work fine but each time I change frequency I will have a new condition. For the case above I have <code>5 conditions</code> but if I use <code>frequency 5</code> I will have <code>20 conditions</code> and I need to change all equations. I mean I need code to be able to handle any frequency</p> <p>I wrote below code</p> <pre><code>clc; clear; prompt = 'Enter Frequency='; %Frequency=20 N= input(prompt); Frequency=N; one_step=1/Frequency; %Frequency time=Frequency*one_step; number_of_steps=time/one_step; %Number of steps until next condition total_steps=100; R1 = rand(100,100); Number_of_Lines=(total_steps/number_of_steps)+1; %100/20 A(100,100)=0; for i=1:100 for j=1:100 if i&gt;=1 &amp;&amp; i&lt;=number_of_steps A(i,j)=R1(i,j); elseif i&gt;number_of_steps &amp;&amp; i&lt;= 2*number_of_steps A(i,j)=R1(i,j)+R1(i-number_of_steps,j); elseif i&gt;2*number_of_steps &amp;&amp; i&lt;= 3*number_of_steps A(i,j)=R1(i,j)+R1(i-number_of_steps,j)+R1(i-2*number_of_steps,j); elseif i&gt;3*number_of_steps &amp;&amp; i&lt;= 4*number_of_steps A(i,j)=R1(i,j)+R1(i-number_of_steps,j)+R1(i-2*number_of_steps,j)... +R1(i-3*number_of_steps,j); elseif i&gt;4*number_of_steps &amp;&amp; i&lt; 5*number_of_steps A(i,j)=R1(i,j)+R1(i-number_of_steps,j)+R1(i-2*number_of_steps,j)... +R1(i-3*number_of_steps,j)+R1(i-4*number_of_steps,j); end end end </code></pre>
3
1,342
Too many redirect
<p>I have this php script ( phpfanlist ) with an admin section that refused to work one day. I guess it came with a php update or something. I didn't mind at the time but now it's bugging me big time.</p> <p>I made research, I checked the log and all ( there was a depreciate <strong>=&amp; new</strong> in front.inc.php but I corrected it, so that's fine ) but the login page still redirect to a blank page after successful login. If the login is not successful, it throws back an error message. If I manually try to enter the admin section ( admin.php ) <strong>after</strong> successfully login-in, I get into the admin without problem.</p> <p>I checked the log and I don't get any message, at all. How can I make that login page work ? I just want to enter the admin without typing it manually ... Is the code too old ?</p> <p>So, <code>login.php</code> gives a form to enter login/pass</p> <ul> <li>Successful login : reload <code>login.php</code> to blank page of <code>login.php</code></li> <li>Unsuccessful login : reload <code>login.php</code> with unsuccessful message</li> <li>What it's suppose to do on successful login : open <code>admin.php</code></li> </ul> <p>This is login.php : </p> <pre><code>require_once('includes/front.inc.php'); $passok = true; if (isset($_POST['user']) &amp;&amp; isset($_POST['pass']) &amp;&amp; (strcasecmp($_POST['user'], $fanlisting-&gt;settings['admin_name']) == 0) &amp;&amp; (strcmp($_POST['pass'], $fanlisting-&gt;settings['admin_pass']) == 0)) { session_start(); header("Cache-control: private"); // IE fix!!! $_SESSION['loggedin'] = 1; if (!isset($fanlisting-&gt;settings['cookie_lifetime'])) { $fanlisting-&gt;settings['cookie_lifetime'] = 60; } if (isset($_POST['rememberme']) &amp;&amp; ($_POST['rememberme'] == 'yes')) { setcookie('phpfanlist_rememberme', 'yesplease', time()+60*60*24*$fanlisting-&gt;settings['cookie_lifetime'], '/'); setcookie('phpfanlist_username', $_POST['user'], time()+60*60*24*$fanlisting-&gt;settings['cookie_lifetime'], '/'); } else { setcookie('phpfanlist_rememberme', FALSE, time()+60*60*24*$fanlisting-&gt;settings['cookie_lifetime'], '/'); setcookie('phpfanlist_username', FALSE, time()+60*60*24*$fanlisting-&gt;settings['cookie_lifetime'], '/'); } if (isset($_SESSION['previous_url'])) { $url = $_SESSION['previous_url']; unset($_SESSION['previous_url']); } else { $url = 'admin.php'; } header('Location: ' . $url); exit; } else { (isset($_POST['pass'])) ? $passok = false : $passok = true; } </code></pre> <p>EDIT : so, it looks like there's too many redirect from admin.php Looking at admin.php doesn't seem to give much info</p> <pre><code>// Password protect it \\ session_start(); header("Cache-control: private"); // IE fix!!! if (isset($_GET['action']) &amp;&amp; ($_GET['action'] == 'logout')) { $_SESSION = array(); } if ((!isset($_SESSION['loggedin'])) || ($_SESSION['loggedin'] != 1)) { header('Location:admin.php'); exit; } /***********************/ require_once('includes/inc.php'); require_once(realpath(PHPFANLIST_INCLUDES . 'admin.inc.php')); </code></pre> <p>Header of admin.inc.php is just asking for </p> <pre><code>require_once('./includes/inc.php'); // Get the actions require_once('admin.scripts.inc.php'); $fanlisting-&gt;LastChecked(); </code></pre>
3
1,350
Trying to understand lists of dictionaries
<p>This is my looping code</p> <pre><code>for netid,email,first,last in notification_list: # put list data in usable format suspend_stat_dict['netid'] = netid # fill dictionary suspend_stat_dict['email'] = email # fill dictionary suspend_stat_dict['added_day'] = added_day # fill dictionary suspend_stat_dict['deletion_date'] = suspend_day # fill dictionary pername_addy = convert_address(email) # make sure email in @uconn.edu form for google_data in user_emails: if google_data['userEmail'] == pername_addy: suspend_stat_dict['suspend_status'] = google_data['isSuspended'] # fill dictionary break print " each dictionary",suspend_stat_dict Suspended_database.append(suspend_stat_dict) # create list of dictionaries print " each list", Suspended_database wait = raw_input("PRESS ENTER TO CONTINUE.") </code></pre> <p>this is the output…. I would have expected the list I am creating to be each dictionary item, not the current dictionary item duplicated ?? I don’t even understand how it is doing this….? Any help or guidance would be awesome !</p> <pre><code>each dictionary {'added_day': 'August 18, 2014', 'suspend_status': 'false', 'deletion_date': 'September 10, 2014', 'email': 'deanna.tripp@gapps.uconn.edu', 'netid': 'ddt04001'} each list [{'added_day': 'August 18, 2014', 'suspend_status': 'false', 'deletion_date': 'September 10, 2014', 'email': 'deanna.tripp@gapps.uconn.edu', 'netid': 'ddt04001'}] PRESS ENTER TO CONTINUE. each dictionary {'added_day': 'August 18, 2014', 'suspend_status': 'false', 'deletion_date': 'September 10, 2014', 'email': 'alexander.vitruk@gapps.uconn.edu', 'netid': 'alv13010'} each list [{'added_day': 'August 18, 2014', 'suspend_status': 'false', 'deletion_date': 'September 10, 2014', 'email': 'alexander.vitruk@gapps.uconn.edu', 'netid': 'alv13010'}, {'added_day': 'August 18, 2014', 'suspend_status': 'false', 'deletion_date': 'September 10, 2014', 'email': 'alexander.vitruk@gapps.uconn.edu', 'netid': 'alv13010'}] PRESS ENTER TO CONTINUE. each dictionary {'added_day': 'August 18, 2014', 'suspend_status': 'false', 'deletion_date': 'September 10, 2014', 'email': 'simon.barres@gapps.uconn.edu', 'netid': 'sib14004'} each list [{'added_day': 'August 18, 2014', 'suspend_status': 'false', 'deletion_date': 'September 10, 2014', 'email': 'simon.barres@gapps.uconn.edu', 'netid': 'sib14004'}, {'added_day': 'August 18, 2014', 'suspend_status': 'false', 'deletion_date': 'September 10, 2014', 'email': 'simon.barres@gapps.uconn.edu', 'netid': 'sib14004'}, {'added_day': 'August 18, 2014', 'suspend_status': 'false', 'deletion_date': 'September 10, 2014', 'email': 'simon.barres@gapps.uconn.edu', 'netid': 'sib14004'}] PRESS ENTER TO CONTINUE. </code></pre>
3
1,151
angularjs multiple countdown
<p>Im in need to make a countdown like this:</p> <pre><code>&lt;div class="countdown" countdown="1482400417"&gt;00:10:02&lt;/div&gt; </code></pre> <p>where the countdown attribute is the time when its finished. the difference is showed in hours:minutes:secs , and it updates each second.</p> <p>How would i do this in angularjs, when i have multiple countdowns like that?</p> <p>I did a little digging, and i found something that did something simular, but i couldnt understand the code. So ill post the code i found:</p> <pre><code>Travian.Directive.countdown = function(a) { return function(c, b, l) { function g() { if ("undefined" != typeof a.K()) { h = b.attr("countdown"); var c = h - a.K(); if (0 &gt; c || isNaN(c)) { return Travian.tick.unbind(e), e = null, b.text( la(0)), !1 } var g = ""; l.showDaysLimit &amp;&amp; c &gt;= l.showDaysLimit ? (c = Math .round(c / 86400), c == f ? g = m : (g = Travian.translate("ForDays", { x: c }), f = c)) : g = la(c, l.countdownShort &amp;&amp; c &lt; l.countdownShort); m != g &amp;&amp; (m = g, b.text(g)) } } var h, e = null, m = "", f = 0; l.showDaysLimit &amp;&amp; c.$on("newTranslation", function() { f = 0 }); l.$observe("countdown", function(a) { "undefined" != typeof a &amp;&amp; null == e &amp;&amp; (e = Travian.tick.bind(g)) }); b.bind("$destroy", function() { Travian.tick.unbind(e) }) } }; Travian.tick = new function() { var a = {}; (function B() { window.setTimeout(B, 100); var b = {}, c; for(c in a) { a.hasOwnProperty(c) &amp;&amp; "function" === typeof a[c] &amp;&amp; (a[c](), b[c] = a[c]) } a = b })(); return{bind:function(b, c) { "function" === typeof b &amp;&amp; (c = b, b = na("tick")); c(); a[b] = c; return b }, unbind:function(b) { a[b] = null }} }; </code></pre>
3
1,229
My button doesn't work
<blockquote> <p>This is the main activity, where I click the button</p> </blockquote> <pre><code> public class NewAddMarketingProg extends Activity implements OnClickListener { private StartAppAd startAppAd; String note_detail; ListView lvNote; String[] data; private int mIndex; private MarketingProgramsAdapter adapter; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* StartAppSDK.init(this, getString(R.string.account_id), getString(R.string.app_id), true);*/ setContentView(R.layout.newaddmarketingprog); context = this; init(); lvNote.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int position, long arg3) { mIndex = position; arg1.showContextMenu(); } }); registerForContextMenu(lvNote); startAppAd = new StartAppAd(this); startAppAd.showAd(); // show the ad startAppAd.loadAd(); // load the next ad } private void init() { MarketingPrograms.listOfMarketingPrograms.clear(); lvNote = (ListView) findViewById(R.id.lvNotes); getDataFromDB(); Button bAddNote = (Button) findViewById(R.id.btnAdd); bAddNote.setOnClickListener(this); } private void getDataFromDB() { DatabaseMarketingPrograms infoNote = new DatabaseMarketingPrograms(this); infoNote.openNote(); infoNote.getDataNote(); infoNote.getRowDataNote(); infoNote.closeNote(); adapter = new MarketingProgramsAdapter(context); lvNote.setAdapter(adapter); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.bAddNote: Intent i = new Intent(this, AddMarketingProgram.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); finish(); break; } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { MenuInflater m = getMenuInflater(); m.inflate(R.menu.noteotions, menu); super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(MenuItem item) { if (item.getItemId() == R.id.view) { int id = MarketingPrograms.listOfMarketingPrograms.get(mIndex).getId(); Intent e = new Intent(this, ViewMarketingPrograms.class); e.putExtra("id", id); startActivity(e); } else if (item.getItemId() == R.id.update) { int id = MarketingPrograms.listOfMarketingPrograms.get(mIndex).getId(); Intent e = new Intent(this, AddMarketingProgram.class); e.putExtra("mIsUpdate", true); e.putExtra("mIndex", mIndex); e.putExtra("id", id); startActivity(e); } else if (item.getItemId() == R.id.delete) { int id = MarketingPrograms.listOfMarketingPrograms.get(mIndex).getId(); DatabaseMarketingPrograms delete = new DatabaseMarketingPrograms(NewAddMarketingProg.this); int flag = delete.deleteEntry(id); if (flag &gt; 0) { Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show(); MarketingPrograms.listOfMarketingPrograms.remove(mIndex); adapter.notifyDataSetChanged(); } else { Toast.makeText(getApplicationContext(), "Could n't be Deleted", Toast.LENGTH_SHORT).show(); } } return super.onContextItemSelected(item); } @Override protected void onResume() { super.onResume(); startAppAd.onResume(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); startAppAd.onPause(); } @Override public void onBackPressed() { startAppAd.onBackPressed(); Intent i=new Intent(NewAddMarketingProg.this,MainActivity.class); startActivity(i); finish(); super.onBackPressed(); } } </code></pre> <blockquote> <p>This is the activity, which I want to open on click of the button</p> </blockquote> <pre><code>public class AddMarketingProgram extends Activity implements OnClickListener { TextView /* tvDate, */tvSelectDate; EditText etName,etBudget; Button btnSave; boolean mIsUpdate = false; Context context; private int id; private int mIndex; private DatePickerDialog fromDatePickerDialog; private SimpleDateFormat dateFormatter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.addmarketingprograms); context = this; etName = (EditText) findViewById(R.id.etName); etBudget = (EditText) findViewById(R.id.etBudget); tvSelectDate = (TextView) findViewById(R.id.tvSelectDate); tvSelectDate.setOnClickListener(this); btnSave = (Button) findViewById(R.id.btnSave); btnSave.setOnClickListener(this); Bundle bundle = getIntent().getExtras(); if (bundle != null) { mIsUpdate = bundle.getBoolean("mIsUpdate", false); if (mIsUpdate) { mIndex = bundle.getInt("mIndex"); MarketingPrograms note = MarketingPrograms.listOfMarketingPrograms.get(mIndex); String name = note.getName(); String date = note.getDate(); int budget=note.getBudget(); etName.setText(name); tvSelectDate.setText(date); etBudget.setText(String.valueOf(budget)); btnSave.setText("Update"); } } // Get Current Date and time Calendar c = Calendar.getInstance(); dateFormatter = new SimpleDateFormat("dd,MMM yyyy"); tvSelectDate.setText(dateFormatter.format(c.getTime())); // Initrialize date picker setDateTimeField(); } @Override public void onBackPressed() { Intent i = new Intent(context, NewAddClassNotes.class); startActivity(i); finish(); } @Override public void onClick(View arg0) { switch (arg0.getId()) { case R.id.btnSave: if (mIsUpdate) { updateNote(); } else { saveNote(); } break; case R.id.tvSelectDate: fromDatePickerDialog.show(); } } private void updateNote() { DatabaseMarketingPrograms update = new DatabaseMarketingPrograms(context); update.openNote(); String name = etName.getText().toString(); String date = tvSelectDate.getText().toString(); int Budget=Integer.parseInt(etBudget.getText().toString()); boolean flag = update.editEntry(name, Budget, date, MarketingPrograms.listOfMarketingPrograms.get(mIndex).getId()); update.closeNote(); if (flag) { Toast.makeText(getApplicationContext(), "Update Successfully", Toast.LENGTH_LONG).show(); onBackPressed(); } else { Toast.makeText(getApplicationContext(), "Unable to update.", Toast.LENGTH_LONG).show(); } } private void saveNote() { try { String name = etName.getText().toString(); int budget=Integer.parseInt(etBudget.getText().toString()); String date = tvSelectDate.getText().toString(); DatabaseMarketingPrograms entry = new DatabaseMarketingPrograms(context); entry.openNote(); long flag = entry.createEntryNote(name, budget, date); entry.closeNote(); if (flag &gt; 0) { Toast.makeText(getApplicationContext(), "Save Successfully", Toast.LENGTH_LONG).show(); onBackPressed(); } else { Toast.makeText(getApplicationContext(), "Unable to Save.", Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(getApplicationContext(), "Unable to Save.", Toast.LENGTH_LONG).show(); } } private void setDateTimeField() { Calendar newCalendar = Calendar.getInstance(); fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); tvSelectDate.setText(dateFormatter.format(newDate .getTime())); } }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); } </code></pre> <p>}</p>
3
3,899
sed second occurrence of a string - for all lines in external file (Linux)
<p>I have a file that has duplicate values in column 2 that need to be renamed. There are ~8k duplicate values (in file <strong>list.of.duplicates</strong>) throughout the ~5m line file (<strong>with.duplicates</strong>).</p> <h2>Data set inputs:</h2> <p><strong>with.duplicates</strong></p> <p>1 rs143225517 0 751756 C T</p> <p>1 rs146277091 0 752478 A G</p> <p>1 rs3094315 0 752566 G A</p> <p>1 rs149886465 0 752617 A C</p> <p>1 <strong>rs3131972</strong> 0 752721 A G</p> <p>1 <strong>rs3131972</strong> 0 752721 AT G</p> <p>1 rs3131971 0 752894 T C</p> <p>1 rs61770173 0 753405 C A</p> <p>1 rs2073814 0 753474 C G</p> <p>1 rs2073813 0 753541 A G</p> <p>1 rs12184325 0 754105 T C</p> <p><strong>list.of.duplicates</strong></p> <p>rs3131972</p> <p>rs4310388</p> <p>rs7529459</p> <p>rs905135</p> <p>rs9786995</p> <p>rs12065710</p> <p>rs6426404</p> <p>rs12759849</p> <p>rs6603823</p> <h2>Code I tried</h2> <p>This does exactly what I want - but inefficiently and for only one substitution</p> <pre><code>sed -i '0,/rs3131972/! s/rs3131972/qrs3131972/' with.duplicates </code></pre> <p>But I can't figure out how to iterate through the entire list of duplicate values</p> <pre><code>i=0 while ((i++)); read -r snp do sed -i '0,/${snp}/! s/${snp}/q${snp}/' with.duplicates done &lt; list.of.duplicates </code></pre> <p>I've found partial answers throughout the site but none that get everything together into an efficient script. </p> <p>Thanks in advance for any help!</p> <p>Looking for a solution in Linux or R</p> <p>edit:</p> <p><strong>Desired output</strong></p> <p>1 rs143225517 0 751756 C T</p> <p>1 rs146277091 0 752478 A G</p> <p>1 rs3094315 0 752566 G A</p> <p>1 rs149886465 0 752617 A C</p> <p>1 <strong>rs3131972</strong> 0 752721 A G</p> <p>1 <strong>qrs3131972</strong> 0 752721 AT G</p> <p>1 rs3131971 0 752894 T C</p> <p>1 rs61770173 0 753405 C A</p> <p>1 rs2073814 0 753474 C G</p> <p>1 rs2073813 0 753541 A G</p> <p>1 rs12184325 0 754105 T C</p>
3
1,483
jQuery datatables loaded from JSON, row click event only firing on sort
<p>In part of my Rails 3.2 app I am loading a datatable from server side JSON similar to <a href="http://railscasts.com/episodes/340-datatables?view=asciicast" rel="nofollow">Railscast #340</a>. </p> <p>I'm trying to call a row click event on the row to load a separate detailed view next to the table and the jQuery click event doesn't fire on tr click, but does fire when a column is sorted. I use similar code elsewhere on the app, but those tables are from smaller datasets and don't use a JSON API. </p> <p>My code is pretty simple.</p> <h2>the view</h2> <pre><code>&lt;div id="leads-wrapper"&gt; &lt;h1&gt;Listing all leads&lt;/h1&gt; &lt;table id="leads_table" class="table" data-source="&lt;%= leads_url(format: "json") %&gt;"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Lead ID&lt;/th&gt; &lt;th&gt;First name&lt;/th&gt; &lt;th&gt;Last name&lt;/th&gt; &lt;th&gt;Company&lt;/th&gt; &lt;th&gt;Rating&lt;/th&gt; &lt;th&gt;Email&lt;/th&gt; &lt;th&gt;Phone&lt;/th&gt; &lt;th&gt;Job Title&lt;/th&gt; &lt;th&gt;Date Added&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <h2>jQuery</h2> <pre><code>$(document).ready(function () { $('#leads_table').find("tr").on("click", function (e) { console.log('clicked'); var link; link = $(this).children('.id').first(); e.preventDefault(); var url = '/lead_detail/' + $(link).data("id"); $.ajax(url, { beforeSend: function () { $('#wait').show(); $("#lead-information").hide(); }, dataType: 'script', type: 'GET', complete: function (response) { $('#lead-information').empty().append(response["responseText"]); $("#lead-information").show(); //other stuff... } }); }); </code></pre> <p>Everything loads correctly and this code has been working in production for over a year, but adding the new detail view to it is the change. I know I can exclude the sort event from my click jQuery above, but I'm more worried about why the click event doesn't fire for tbody rows right now. </p> <p>In case anyone is interested, the generated code is what you'd expect: </p> <pre><code>&lt;table id="leads_table" class="table dataTable" data-source="http://localhost:3000/leads.json" aria-describedby="leads_table_info"&gt; &lt;thead&gt; &lt;tr role="row"&gt;&lt;th class="sorting" role="columnheader" tabindex="0" aria-controls="leads_table" rowspan="1" colspan="1" style="width: 96px;" aria-label="Lead ID: activate to sort column ascending"&gt;Lead ID&lt;/th&gt;&lt;th class="sorting" role="columnheader" tabindex="0" aria-controls="leads_table" rowspan="1" colspan="1" style="width: 130px;" aria-label="First name: activate to sort column ascending"&gt;First name&lt;/th&gt;&lt;th class="sorting" role="columnheader" tabindex="0" aria-controls="leads_table" rowspan="1" colspan="1" style="width: 128px;" aria-label="Last name: activate to sort column ascending"&gt;Last name&lt;/th&gt;&lt;th class="sorting_asc" role="columnheader" tabindex="0" aria-controls="leads_table" rowspan="1" colspan="1" style="width: 118px;" aria-label="Company: activate to sort column ascending"&gt;Company&lt;/th&gt;&lt;th class="sorting" role="columnheader" tabindex="0" aria-controls="leads_table" rowspan="1" colspan="1" style="width: 85px;" aria-label="Rating: activate to sort column ascending"&gt;Rating&lt;/th&gt;&lt;th class="sorting" role="columnheader" tabindex="0" aria-controls="leads_table" rowspan="1" colspan="1" style="width: 75px;" aria-label="Email: activate to sort column ascending"&gt;Email&lt;/th&gt;&lt;th class="sorting" role="columnheader" tabindex="0" aria-controls="leads_table" rowspan="1" colspan="1" style="width: 81px;" aria-label="Phone: activate to sort column ascending"&gt;Phone&lt;/th&gt;&lt;th class="sorting" role="columnheader" tabindex="0" aria-controls="leads_table" rowspan="1" colspan="1" style="width: 112px;" aria-label="Job Title: activate to sort column ascending"&gt;Job Title&lt;/th&gt;&lt;th class="sorting" role="columnheader" tabindex="0" aria-controls="leads_table" rowspan="1" colspan="1" style="width: 147px;" aria-label="Date Added: activate to sort column ascending"&gt;Date Added&lt;/th&gt;&lt;/tr&gt; &lt;/thead&gt; &lt;tbody role="alert" aria-live="polite" aria-relevant="all"&gt; &lt;tr class="odd"&gt; &lt;td class="id"&gt;256&lt;/td&gt; &lt;td class=""&gt;Mark&lt;/td&gt; &lt;td class=""&gt;Example&lt;/td&gt; &lt;td class=" sorting_1"&gt;&lt;/td&gt; &lt;td class=""&gt;&lt;div class="star" data-score="5" data-lead-id="256" style="cursor: pointer; width: 100px;"&gt;&lt;img src="/assets/star-on.png" alt="1" title="bad"&gt;&amp;nbsp;&lt;img src="/assets/star-on.png" alt="2" title="poor"&gt;&amp;nbsp;&lt;img src="/assets/star-on.png" alt="3" title="regular"&gt;&amp;nbsp;&lt;img src="/assets/star-on.png" alt="4" title="good"&gt;&amp;nbsp;&lt;img src="/assets/star-on.png" alt="5" title="gorgeous"&gt;&lt;input type="hidden" name="score" value="5"&gt;&lt;/div&gt;&lt;/td&gt; &lt;td class=""&gt;mark.example@example.net&lt;/td&gt; &lt;td class=""&gt;3145551212&lt;/td&gt; &lt;td class=""&gt;&lt;/td&gt; &lt;td class=""&gt;March 21, 2013&lt;/td&gt; &lt;/tr&gt;... &lt;/tbody&gt; &lt;/table&gt; </code></pre>
3
2,387
If cell value the same as above, then
<p>I am trying to check if the value in a cell in Column B is the same as a cell in Column B in another row, Y places lower/higher. Y being a value in cell &quot;A8&quot;.</p> <p>IF the values are the same then the value in Column P of the same row has to get the same value as in Column R of the same row.<br /> ELSE Column Q of that row has to get the same value as in Colom R of the same row.</p> <p>In the schematic below, Y=2, so column B1 check 2 places lower B3 is the same so data in R1 should also be in P1.<br /> Continuing the same idea B4 compared with B6 does not have the same value so the Q4 should have the same value as R4.</p> <p>Representation of the input</p> <pre><code>ColumnA ColumnB ColumnP ColumnQ Column R 1 x 2 x 2 1 x 2 x 30 x 40 x 50 x 60 x </code></pre> <p>Desired result</p> <pre><code>ColumnA ColumnB ColumnP ColumnQ ColumnR 1 x x 2 x x 2 1 x x 2 x x 30 x x 40 x x 60 x x </code></pre> <p>I tried multiple things. The last I tried below.</p> <pre class="lang-vb prettyprint-override"><code>For iRow = Range(&quot;B3:B2502&quot;).Rows.Count To 1 Step -1 If Cells(iRow + 2, 2).Value = Cells(iRow + Y, 2) Then Cells(iRow + 2, 15).Value = Cells(iRow + 2, 17) Else Cells(iRow + 2, 16).Value = Cells(iRow + 2, 17) End If Next End Sub </code></pre> <p>And some variations with ranges.</p>
3
1,049
MS Access syntax error when updating on join
<p>I am receiving </p> <blockquote> <p>Run-time error '3075' - "Syntax error (missing operator) in query expression 'ct.ContainerID FROM tblCrossarm AS mt INNER JOIN tblContainerTemp AS ct ON mt.SerialNumber = ct.SerialNumber</p> </blockquote> <p>At the time of the failure, the strSQL variable looks like: </p> <pre><code>UPDATE mt SET mt.ContainerID = ct.ContainerID FROM tblCrossarm AS mt INNER JOIN tblContainerTemp AS ct ON mt.SerialNumber = ct.SerialNumber </code></pre> <p><strong>Code</strong></p> <pre><code>Private Sub btnSave_Click() Dim dbs As DAO.Database: Set dbs = CurrentDb Dim i As Integer Dim strSQL As String Dim arrMaterialType() As String Dim rstContainerTemp As DAO.Recordset Dim rstMaterialType As DAO.Recordset Dim strContainerID As Variant: strContainerID = Null If IsNull(cboContainerID.Column(0)) Or cboContainerID.Column(0) = "" Then If MsgBox("You have not selected a Container ID." &amp; vbCr &amp; vbLf &amp; "Press OK to Delete the Container IDs of all materials in the Container Table or press cancel to abort.", vbOKCancel, "Delete Container IDs?") = vbCancel Then Exit Sub End If Else strContainerID = Chr$(39) &amp; cboContainerID.Column(0) &amp; Chr$(39) End If Set rstMaterialType = dbs.OpenRecordset("qryDistinctMaterialType") Set rstContainerTemp = dbs.OpenRecordset("tblContainerTemp") If Not (rstContainerTemp.EOF And rstContainerTemp.BOF) And Not (rstMaterialType.EOF And rstMaterialType.EOF) Then rstContainerTemp.MoveFirst rstMaterialType.MoveFirst Do Until rstMaterialType.EOF = True Do Until rstContainerTemp.EOF = True If rstMaterialType.Fields(0) = rstContainerTemp!MaterialType Then ' rstContainerTemp.Edit ' rstContainerTemp!ContainerID = strContainerID ' rstContainerTemp.Update strSQL = "UPDATE tblContainerTemp AS ct SET ct.ContainerID = " &amp; strContainerID &amp; " WHERE ct.SerialNumber = " &amp; Chr$(39) &amp; rstContainerTemp!SerialNumber &amp; Chr$(39) &amp; ";" dbs.Execute strSQL, dbFailOnError End If rstContainerTemp.MoveNext Loop rstMaterialType.MoveNext Loop End If strSQL = "UPDATE mt SET mt.ContainerID = ct.ContainerID FROM " &amp; cboMaterialType.Column(0) &amp; " AS mt INNER JOIN tblContainerTemp AS ct ON mt.SerialNumber = ct.SerialNumber;" dbs.Execute strSQL, dbFailOnError dbs.Close Set dbs = Nothing End Sub </code></pre>
3
1,067
How to properly detach and remove shared memory between 2 processes in PHP?
<p>I developed a way to make async tasks with PHP and it's working very well, until now.</p> <p>The logic based in 3 extensions <a href="http://php.net/manual/en/book.pcntl.php" rel="noreferrer">PCNTL</a>, <a href="http://php.net/manual/en/book.posix.php" rel="noreferrer">POSIX</a> e <a href="http://php.net/manual/en/book.sem.php" rel="noreferrer">Semaphore</a>.</p> <p>To have a full control of the master process and child process I must share the status of the task and the PID between them. These 2 variables are shared using <a href="http://php.net/manual/en/function.shm-attach.php" rel="noreferrer">shm_attach</a>, the fork uses <a href="http://php.net/manual/en/function.pcntl-fork.php" rel="noreferrer">pcntl_fork</a>.</p> <p>The problem described in the title of this questions is related to the status of the task and the PID between them. These 2 variables are shared using <a href="http://php.net/manual/en/function.shm-attach.php" rel="noreferrer">shm_attach</a> method because there is no more space available to share create a <a href="https://gerardnico.com/wiki/linux/shared_memory" rel="noreferrer">shared memory</a>.</p> <p>I use it for 2 moments: At constructor to create the shared memory</p> <pre><code>&lt;?php //... final public function __construct() { self::$shmId = shm_attach((int) (ftok(self::$file, 'A') . self::$line), self::SHARED_MEMORY_SIZE); $this-&gt;var_key_pid = $this-&gt;alocatesharedMemory(getmypid(), 112112105100); //112112105100; $this-&gt;var_key_status = $this-&gt;alocatesharedMemory('PENDING', 11511697116117115); //11511697116117115; } </code></pre> <p>And on the <code>run</code> method after forking the process</p> <pre><code>&lt;?php final public function run($parameters) { //... } else { //Frok process ignore_user_abort(); //I dont know why but must be set again. $sid = posix_setsid(); self::$shmId = shm_attach((int) (ftok(self::$file, 'A') . self::$line), self::SHARED_MEMORY_SIZE); </code></pre> <blockquote> <p>NOTE: The code is a little extensive and I put it into a gist <a href="https://gist.github.com/LeonanCarvalho/62c6fe0b62db8a478f502f84c5734c83" rel="noreferrer">https://gist.github.com/LeonanCarvalho/62c6fe0b62db8a478f502f84c5734c83</a></p> </blockquote> <p>I think I'm doing something wrong because even though I'm using <a href="http://php.net/manual/en/function.shm-detach.php" rel="noreferrer">shm_detach</a> and <a href="http://php.net/manual/en/function.shm-remove.php" rel="noreferrer">shm_remove</a> the process sometimes returns the error <strong>PHP Warning: "shm_attach" failed for key No space left on the device in</strong> when I try to attach a new shared memory.</p> <p>It is happening because some shared memory is detached and not removed from Shared memory segments, its the result of command <code>ipcs -m</code> :</p> <p><a href="https://i.stack.imgur.com/ldMAr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ldMAr.png" alt="ipcs -m result"></a></p> <p>The tasks are running for months before start doing this, so the one way to work around this problem I removed all shared memory identifiers with the command </p> <pre><code>ipcrm --all=shm </code></pre> <p>But I think it's silently growing and for sure it going to happen again.</p> <p>How to prevent it?</p>
3
1,254
HDFS IO error (hadoop 2.8) with Flume
<p>I am getting the below error when I try to get a streaming data into hadoop through Flume.</p> <p>I have created link in flume/lib that point to the <code>.jar</code> files in hadoop/share/hadoop/</p> <p>I double checked the URL and I think they are all correct. Thought of posting to get some more eyes and some feedback.</p> <pre><code> 2017-07-20 10:53:18,959 (SinkRunner-PollingRunner-DefaultSinkProcessor) [WARN -org.apache.flume.sink.hdfs.HDFSEventSink.process HDFSEventSink.java:455)] HDFS IO error java.io.IOException: No FileSystem for scheme: hdfs at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2798) at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2809) at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:100) at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2848) at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2830) at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:389) at org.apache.hadoop.fs.Path.getFileSystem(Path.java:356) at org.apache.flume.sink.hdfs.BucketWriter$1.call(BucketWriter.java:243) at org.apache.flume.sink.hdfs.BucketWriter$1.call(BucketWriter.java:235) at org.apache.flume.sink.hdfs.BucketWriter$9$1.run(BucketWriter.java:679) at org.apache.flume.auth.SimpleAuthenticator.execute(SimpleAuthenticator.java:50) at org.apache.flume.sink.hdfs.BucketWriter$9.call(BucketWriter.java:676) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:748) </code></pre> <p>Here is the Flume Sink Config</p> <pre><code>agent1.sinks.PurePathSink.type = hdfs agent1.sinks.PurePathSink.hdfs.path = hdfs://127.0.0.1:9000/User/bts/pp agent1.sinks.PurePathSink.hdfs.fileType = DataStream agent1.sinks.PurePathSink.hdfs.filePrefix = export agent1.sinks.PurePathSink.hdfs.fileSuffix = .txt agent1.sinks.PurePathSink.hdfs.rollInterval = 120 agent1.sinks.PurePathSink.hdfs.rollSize = 131072 </code></pre> <p>core-site.xml - Hadoop 2.8</p> <pre><code>&lt;configuration&gt; &lt;property&gt; &lt;name&gt;hadoop.tmp.dir&lt;/name&gt; &lt;value&gt;/home1/tmp&lt;/value&gt; &lt;description&gt;A base for other temporary directories&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;fs.default.name&lt;/name&gt; &lt;value&gt;hdfs://127.0.0.1:9000&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;fs.file.impl&lt;/name&gt; &lt;value&gt;org.apache.hadoop.fs.LocalFileSystem&lt;/value&gt; &lt;description&gt;The FileSystem for file: uris.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;fs.hdfs.impl&lt;/name&gt; &lt;value&gt;org.apache.hadoop.hdfs.DistributedFileSystem&lt;/value&gt; &lt;description&gt;The FileSystem for hdfs: uris.&lt;/description&gt; &lt;/property&gt; </code></pre>
3
1,442
Python Error: 'float' object cannot be interpreted as an integer
<p>I am trying to build this tax calculator and keep receiving this error:</p> <blockquote> <p>'float' object cannot be interpreted as an integer</p> </blockquote> <p>The problem seems to be my <code>range</code> line, but I can't figure out how to fix it.</p> <pre><code>class taxCalc: def __init__(self): self.brackets_single = {(0,10000):0.15, (10000,45000):.18, (45000,72000):.23, (72000, sys.maxsize):.38} self.brackets_joint = {(0,20000):0.15, (20000,90000):.18, (90000,144000):.23, (144000, sys.maxsize):.38} def taxcal(self, income, fil_stat, depen, stdeduc): if stdeduc == 'TRUE': if fil_stat == 'single': agincome = income - 1000 elif fil_stat == 'joint': agincome = income - 2000 else: agincome = income if depen == 1: agincome -= 1000 elif depen == 2: agincome -= 2000 else: agincome = income PEP = .02 if agincome &gt;= 45000 : amount = agincome - 45000 amount /= 1000 amount *= PEP amount *= (1000*depen) if 1000*depen - amount &gt; 0: agincome += amount else: agincome += (1000*depen) else: agincome = agincome tax = 0 if fil_stat == 'single': for bracket in self.brackets_single: if agincome &gt; bracket[0]: for _ in range(bracket[0], min(agincome, bracket[1])): tax += self.brackets_single[bracket] elif fil_stat == 'joint': for bracket in self.brackets_joint: if agincome &gt; bracket[0]: for _ in range(bracket[0], min(agincome, bracket[1])): tax += self.brackets_joint[bracket] return tax mytest=taxCalc() print(mytest.taxcal(75000, 'single', 1, 'TRUE')), format(round(mytest.taxcal(75000, 'single', 1, 'TRUE'),2)) </code></pre>
3
1,038
Android Firebase : Second Connected Database not allowing auth in rules
<p>I've connected two Databases from the same firebase project like below.</p> <pre><code> //init the default db; FirebaseApp.initializeApp(this); //init the second db; FirebaseOptions.Builder builder = new FirebaseOptions.Builder(); builder.setApplicationId("id"); //Same as default builder.setApiKey("key"); //Same as default builder.setDatabaseUrl("https://second-db.firebaseio.com"); try { FirebaseApp.initializeApp(this, builder.build(), "second-db"); } catch (IllegalStateException e) { e.printStackTrace(); } </code></pre> <p>Getting Reference. </p> <pre><code>public static DatabaseReference getSecondDbRef(String child) { FirebaseApp app = FirebaseApp.getInstance("second-db"); return FirebaseDatabase.getInstance(app).getReference(child); } </code></pre> <p>With the above, it works, but the rules in the second database don't seem to be getting auth. if I do.</p> <pre><code> { "rules":{ "users":{ "$uid":{ ".read":"auth.uid !== null", // ".read":true // This works, so the issue is auth } } } } </code></pre> <p>The read fails, even though the user is authenticated, also, this problem isn't there with the default database. Is there anything I'm missing with the init?</p> <p>Ok, because of highlights below, here's the code as it is on the app.</p> <pre><code> private static final String TEAMS_BD_ID = "second-db" public void initFirebase() { FirebaseApp.initializeApp(this); FirebaseOptions.Builder builder = new FirebaseOptions.Builder(); builder.setApplicationId("appId"); // //Same as default builder.setApiKey("key"); // //Same as default builder.setDatabaseUrl("https://teams-db.firebaseio.com");//Second Db try { FirebaseApp.initializeApp(this, builder.build(), TEAMS_BD_ID); } catch (IllegalStateException e) { e.printStackTrace(); } } public static FirebaseApp getTeamsApp() { return FirebaseApp.getInstance(TEAMS_BD_ID); } public static String getTeamsUserUid() { return FirebaseAuth.getInstance(getTeamsApp()).getCurrentUser().getUid(); } public static DatabaseReference getTeamsRef(String child) { return FirebaseDatabase.getInstance(getTeamsApp()).getReference(child); } public static DatabaseReference getTeamsRef() { return FirebaseDatabase.getInstance(getTeamsApp()).getReference(); } </code></pre> <p>Then trying to read.</p> <pre><code>DatabaseReference r = getTeamsRef().child("users/" + getTeamsUserUid() + "/teams") // getTeamsUserUid() This is null. </code></pre>
3
1,066
Rails: how to save a gem's class as a model in my database?
<p>I've been building a Google Tasks integration app and just switched to using the Google API Client (<code>gem 'google-api-client', '~&gt; 0.34'</code>)</p> <p>This gives me some classes that I'm really starting to like:</p> <pre class="lang-rb prettyprint-override"><code>Google::Apis::TasksV1::Task Google::Apis::TasksV1::TaskList Google::Apis::TasksV1::Tasks # (for multiple records) Google::Apis::TasksV1::TaskLists # (for multiple records) </code></pre> <p>These classes come with all the attributes I want and I'm thinking it would be nice to actually have these records in my database instead of what I'm doing now, which is HTTP requests with OAuth (using methods provided by the gem)</p> <p>With their gem integrated into a custom class, I can do things like:</p> <pre class="lang-rb prettyprint-override"><code>&gt; ts = TaskService.new(user) =&gt; #&lt;TasksService:0x00007f973be03bc8 @user=#&lt;User #userstuff&gt;, @service=#&lt;Google::Apis::TasksV1::TasksService:0x00007f973be03b28 @root_url="https://www.googleapis.com/", @base_path="tasks/v1/", @upload_path="upload/tasks/v1/", @batch_path="batch/tasks/v1", @client_options=#&lt;struct Google::Apis::ClientOptions #morestuff&gt;, @request_options=#&lt;struct Google::Apis::RequestOptions authorization=#&lt;Signet::OAuth2::Client:0x00007f973be02020 @authorization_uri=#&lt;Addressable::URI:0x3fcb9df05304 URI:https://accounts.google.com/o/oauth2/auth&gt;, @token_credential_uri=#&lt;Addressable::URI:0x3fcb9db99f08 URI:https://accounts.google.com/o/oauth2/token&gt;, @client_id="secret", @client_secret="secret", @code=nil, @expires_at=nil, @issued_at=nil, @issuer=nil, @password=nil, @principal=nil, @redirect_uri=nil, @scope=nil, @state=nil, @username=nil, @access_type=:offline, @expiry=60, @extension_parameters={}, @additional_parameters={}, @access_token="secret", @id_token=nil&gt;, retries=0, header=nil, normalize_unicode=false, skip_serialization=false, skip_deserialization=false, api_format_version=nil, use_opencensus=true&gt;&gt;&gt; &gt; ts.service.list_tasklists Sending HTTP get https://www.googleapis.com/tasks/v1/users/@me/lists? 200 #&lt;HTTP::Message:0x00007f973b79ceb0 #all the stuff&gt; Success - #&lt;Google::Apis::TasksV1::TaskLists:0x00007f973e032168 @etag="\"LTY2NzExNzU1Mg\"", @items= [#&lt;Google::Apis::TasksV1::TaskList:0x00007f973e0a2a58 @etag="\"Mzk0NzU3MDky\"", @id="MDc1MjQ5ODU0NzUwMjI4NDkwMTM6MDow", @kind="tasks#taskList", @self_link= "https://www.googleapis.com/tasks/v1/users/@me/lists/MDc1MjQ5ODU0NzUwMjI4NDkwMTM6MDow", @title="My list", @updated=Wed, 18 Dec 2019 05:42:34 +0000&gt;, #&lt;Google::Apis::TasksV1::TaskList:0x00007f973bf298b8 @etag="\"Mzk0OTEzMTI0\"", @id="eHFkTG9UUkl3d1ZQcTdCOA", @kind="tasks#taskList", @self_link= "https://www.googleapis.com/tasks/v1/users/@me/lists/eHFkTG9UUkl3d1ZQcTdCOA", @title="Another List", @updated=Wed, 18 Dec 2019 05:45:10 +0000&gt;, ... # brevity is the soul of ... =&gt; #&lt;Google::Apis::TasksV1::TaskLists:0x00007f973e032168 @etag="\"LTY2NzExNzU1Mg\"", @items=[#&lt;Google::Apis::TasksV1::TaskList:0x00007f973e0a2a58 @etag="\"Mzk0NzU3MDky\"", @id="MDc1MjQ5ODU0NzUwMjI4NDkwMTM6MDow", @kind="tasks#taskList", @self_link="https://www.googleapis.com/tasks/v1/users/@me/lists/MDc1MjQ5ODU0NzUwMjI4NDkwMTM6MDow", @title="FamilyPromiseGR's list", @updated=Wed, 18 Dec 2019 05:42:34 +0000&gt;, #&lt;Google::Apis::TasksV1::TaskList:0x00007f973bf298b8 @etag="\"Mzk0OTEzMTI0\"", @id="eHFkTG9UUkl3d1ZQcTdCOA", @kind="tasks#taskList", @self_link="https://www.googleapis.com/tasks/v1/users/@me/lists/eHFkTG9UUkl3d1ZQcTdCOA", @title="Vinewood Ave NE", @updated=Wed, 18 Dec 2019 05:45:10 +0000&gt;, ... # brevity is the soul of ... </code></pre> <p>The items come back as structured classes! It's great!</p> <p>However, there's a good amount of latency with every call. </p> <p>I'm running these commands in jobs, but I'm also thinking about saving these to my database (postgresql) and just comparing <code>updated</code> timestamps instead of pulling the information every single time I need it.</p> <p>So, here's my question:</p> <h1>How can I take the class as-is and make it a model in my database?</h1> <p>I want to be able to call <code>Google::Apis::TasksV1::Task.create(tasklist_attrs)</code> and other such model-type methods.</p> <p>I have noticed that they don't respond exactly like my own classes (that inherit from <code>ActiveRecord::Base</code>):</p> <pre class="lang-rb prettyprint-override"><code>2.6.3 :008 &gt; User.new =&gt; #&lt;User id: nil, name: nil, title: nil, phone: nil, admin: false, staff: false, client: false, volunteer: false, contractor: false, email: "", oauth_provider: nil, oauth_id: nil, oauth_image_link: nil, oauth_token: nil, oauth_refresh_token: nil, oauth_expires_at: nil, created_at: nil, updated_at: nil, discarded_at: nil&gt; 2.6.3 :009 &gt; Google::Apis::TasksV1::Task.new =&gt; #&lt;Google::Apis::TasksV1::Task:0x00007f973e2d8908&gt; # no nil attributes by default? </code></pre>
3
2,082
Wizard page resize
<p>I'm developing a application which has a multi-page wizard. And we want it to perform like the Preferences page in Eclipse. When you are dragging the left side, only the right side will be resized. The below shows the BasePage of the wizard. Each page in this wizard extends this BasePage. How can I modify the BasePage? </p> <pre><code>import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BasePage extends WizardPage { private Logger log = LoggerFactory.getLogger(getClass()); //Color blue = SWTResourceManager.getColor(65, 105, 225); //Color black = SWTResourceManager.getColor(0, 0, 0); //Button rbtnIntroduce; Button rbtnSourcedb; Button rbtnTargetdb; Button rbtnDatatype; Button rbtnSelectObjects; Button rbtnMigrate; Composite compositeContent; SashForm sashContainer; public BasePage(String name) { super(name); } @Override public void createControl(Composite parent) { log.debug("BasePage.createControl"); sashContainer = new SashForm(parent, SWT.NONE); setControl(sashContainer);// must set control for wizard page GridLayout layout = new GridLayout(); layout.numColumns = 2; sashContainer.setLayout(layout); Composite compositeNavigator = new Composite(sashContainer, SWT.BORDER); /* rbtnIntroduce = new Button(compositeNavigator, SWT.RADIO); //rbtnIntroduce.setForeground(blue); rbtnIntroduce.setBounds(10, 10, 110, 20); rbtnIntroduce.setText("Introduce"); */ rbtnTargetdb = new Button(compositeNavigator, SWT.RADIO); rbtnTargetdb.setBounds(10, 35, 110, 20); rbtnTargetdb.setText("Target DB"); rbtnSourcedb = new Button(compositeNavigator, SWT.RADIO); rbtnSourcedb.setBounds(10, 60, 110, 20); rbtnSourcedb.setText("Source DB"); rbtnDatatype = new Button(compositeNavigator, SWT.RADIO); rbtnDatatype.setBounds(10, 110, 110, 20); rbtnDatatype.setText("Datatype Cast"); rbtnSelectObjects = new Button(compositeNavigator, SWT.RADIO); rbtnSelectObjects.setBounds(10, 85, 110, 20); rbtnSelectObjects.setText("Object Choose"); rbtnMigrate = new Button(compositeNavigator, SWT.RADIO); rbtnMigrate.setBounds(10, 135, 110, 20); rbtnMigrate.setText("Migrate"); compositeContent = new Composite(sashContainer, SWT.NONE); sashContainer.setWeights(new int[] { 1, 3 }); } /* private Button getRadioButton(Composite compositeNavigator, String name) { Button rbtn = new Button(compositeNavigator, SWT.RADIO); rbtn.setText(name); return rbtn; } */ void updatePage(Button btn) { /* rbtnIntroduce.setSelection(rbtnIntroduce==btn); rbtnIntroduce.setEnabled(rbtnIntroduce==btn); //rbtnIntroduce.setForeground(rbtnIntroduce==btn? blue:black); */ rbtnTargetdb.setSelection(rbtnTargetdb==btn); rbtnTargetdb.setEnabled(rbtnTargetdb==btn); //rbtnTargetdb.setForeground(rbtnTargetdb==btn? blue:black); rbtnSourcedb.setSelection(rbtnSourcedb==btn); rbtnSourcedb.setEnabled(rbtnSourcedb==btn); //rbtnSourcedb.setForeground(rbtnSourcedb==btn? blue:black); rbtnTargetdb.setSelection(rbtnTargetdb==btn); rbtnTargetdb.setEnabled(rbtnTargetdb==btn); //rbtnTargetdb.setForeground(rbtnTargetdb==btn? blue:black); rbtnDatatype.setSelection(rbtnDatatype==btn); rbtnDatatype.setEnabled(rbtnDatatype==btn); //rbtnDatatype.setForeground(rbtnDatatype==btn? blue:black); rbtnSelectObjects.setSelection(rbtnSelectObjects==btn); rbtnSelectObjects.setEnabled(rbtnSelectObjects==btn); //rbtnSelectObjects.setForeground(rbtnSelectObjects==btn? blue:black); rbtnMigrate.setSelection(rbtnMigrate==btn); rbtnMigrate.setEnabled(rbtnMigrate==btn); //rbtnMigrate.setForeground(rbtnMigrate==btn? blue:black); } } </code></pre>
3
1,827
JPA/ JPQL: How to use member-of with an hash-map
<p>I have problem using the member-of Statement. The problem I think is, that I made a mistake with the elements --> parameter.get("" i + anlass) but I don't know how to do it right. Are there any other possibilities to ask if a certain element is an <code>@ManyToMany</code> List from another Object? </p> <p>Here's my Code: </p> <pre><code> /*My Beans: @Entity public class Rezept implements Serializable { ........... @ManyToMany(mappedBy="rezepten", cascade = {CascadeType.PERSIST}) List&lt;Allergie&gt; allergien = new ArrayList&lt;&gt;(); @ManyToMany(mappedBy="rezepten", cascade = {CascadeType.PERSIST}) List&lt;Anlass&gt; anlässe = new ArrayList&lt;&gt;(); @ManyToMany(mappedBy="rezepten", cascade = {CascadeType.PERSIST}) List&lt;Grundzutat&gt; grundzutaten = new ArrayList&lt;&gt;();*/ //The method is in the RezeptBean public List&lt;Rezept&gt; searchByFilters(List&lt;Anlass&gt; anlaesse, List&lt;Grundzutat&gt; grundzutaten, List&lt;Allergie&gt; allergien) { // WHERE-Bedingungen für die Filteroptionen zusammenbauen String select = "SELECT r FROM Rezept r"; String where = ""; Map&lt;String, Object&gt; parameters = new HashMap&lt;&gt;(); int i = 0; for (Anlass anlass : anlaesse) { i++; parameters.put("" + i, anlass); if (!where.isEmpty()) { where += " AND "; } //Here I want to see if the element parameters.get("" + i) is member of r.anlässe where += ":" + parameters.get("" + i) + " MEMBER OF r.anlässe"; } for (Grundzutat grundzutat : grundzutaten) { i++; parameters.put("" + i, grundzutat); if (!where.isEmpty()) { where += " AND "; } where += ":" + parameters.get("" + i) + " MEMBER OF r.grundzutaten"; } for (Allergie allergie : allergien) { i++; parameters.put("" + i, allergie); if (!where.isEmpty()) { where += " AND "; } where += ":" + parameters.get("" + i) + " MEMBER OF r.allergien"; } // Finalen SELECT-String zusammenbauen und Suche ausführen if (!where.isEmpty()) { select += " WHERE " + where; } Query query = em.createQuery(select); for (String key : parameters.keySet()) { query.setParameter(key, parameters.get(key)); } return query.getResultList(); } } </code></pre> <p>This is the log file: </p> <pre><code> Warnung: A system exception occurred during an invocation on EJB RezeptBean, method: public java.util.List rezept.ejb.RezeptBean.searchByFilters(java.util.List,java.util.List,java.util.List) Warnung: javax.ejb.EJBException at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:752) at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:702) at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507) at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220) at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88) at com.sun.proxy.$Proxy1243.searchByFilters(Unknown Source) at rezept.ejb.__EJB31_Generated__RezeptBean__Intf____Bean__.searchByFilters(Unknown Source) at rezept.web.SuchServlet.doGet(SuchServlet.java:125) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at rezept.web.JavaFilter.doFilter(JavaFilter.java:48) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283) at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571) at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: Exception Description: Syntax error parsing [SELECT r FROM Rezept r WHERE :rezept.jpa.Anlass@2c9e9a75 MEMBER OF r.anlässe AND :rezept.jpa.Grundzutat@3c634785 MEMBER OF r.grundzutaten AND :rezept.jpa.Grundzutat@3c30782 MEMBER OF r.grundzutaten AND :rezept.jpa.Allergie@4f608eda MEMBER OF r.allergien AND :rezept.jpa.Allergie@1482f49f MEMBER OF r.allergien]. [29, 56] The named input parameter ''{0}'' is not following the rules for a Java identifier. [81, 112] The named input parameter ''{0}'' is not following the rules for a Java identifier. [142, 172] The named input parameter ''{0}'' is not following the rules for a Java identifier. [202, 231] The named input parameter ''{0}'' is not following the rules for a Java identifier. [258, 287] The named input parameter ''{0}'' is not following the rules for a Java identifier. at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1616) .................... </code></pre> <p>Has somebody an idea what I can do different? </p>
3
3,085
SES Boost Mail Speed
<p>I am using SES and trying to send emails to almost 2000 people at one go. The code which I am using is written in JAVA using javamail library and it takes around 28 seconds to deliver 22 mails. </p> <p>Is there any way I can boost the speed up by changing language or library or any alternate way. Here is my code for reference, I am already using threads:</p> <pre><code>import java.util.ArrayList; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class AmazonSESSample implements Runnable { private String to = ""; public static Properties props = System.getProperties(); public static Session session = Session.getDefaultInstance(props); static final String FROM = "info@domain.com"; static final String BODY = "This email was sent through the Amazon SES SMTP interface by using Java."; static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)"; static final String SMTP_USERNAME = "username"; static final String SMTP_PASSWORD = "password"; static final String HOST = "ses_host"; static final int PORT = 000; public static Transport transport; @Override public void run() { try { this.sendMail(); } catch (MessagingException e) { e.printStackTrace(); } } public void setParameters(String to) { this.to = to; } private void sendMail() throws MessagingException { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(FROM)); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(SUBJECT); msg.setContent(BODY, "text/plain"); try { System.out.println("Attempting to send an email through the Amazon SES SMTP interface..."); msg.saveChanges(); transport.sendMessage(msg, msg.getAllRecipients()); Date date = new Date(); System.out.println("Email sent!" + date.toString()); } catch (Exception ex) { System.out.println("The email was not sent."); System.out.println("Error message: " + ex.getMessage()); } } public static void main(String[] args) throws MessagingException { props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.port", PORT); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.starttls.required", "true"); ArrayList&lt;String&gt; emails = new ArrayList&lt;String&gt;(); // String list of emails transport = session.getTransport(); transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD); Date date = new Date(); System.out.println(date.toString()); for (int i = 0; i &lt; emails.size(); i++) { AmazonSESSample sendmail = new AmazonSESSample(); sendmail.setParameters(emails.get(i).toString()); Thread t = new Thread(sendmail); t.start(); } // transport.close(); } } </code></pre>
3
1,254
Jquery incompatibility issue with Chrome
<p>I ran into a headache situation. When I checked the selection option (05/30/2012 EQ), I can't click select button to submit the action, but I am supposed to be able to click it. The issue happens with Chrome and I.E, but it is good with FF. I think it is a Jquery incompatibility issue. I attached some of my code as follows:</p> <pre><code> function $recalcSelection($checkbox) { $selectActionList.find("option").each(function() { $optionLength = $table.find("td.actioncolumn input:checked").length; if($optionLength &lt;= 0) { $(this).attr("disabled", true); } else if($optionLength == 1) { $(this).attr("disabled", false); } else { if( $(this).val() == "editAppointment" || $(this).val() == "copyAppointment" || $(this).val() == "viewShowList" || $(this).val() == "viewScheduledTimes") { $(this).attr("disabled", true); } else { $(this).attr("disabled", false); } } }); if($selectActionList.find("option:selected").attr('disabled')) { $selectActionList.find("option:enabled").eq(0).attr("selected", true); } if($selectActionList.find("option:enabled").length &lt;= 0) { $selectActionButton.attr("disabled", true); } else { $selectActionButton.attr("disabled", false); } } </code></pre> <p>$selectActionButton is the submit button, and $selectactionlist is the select list. I tried to print ($selectActionList.find("option:enabled").length in Chrome, it is 0. But when I was printing it in FF, it is 7. Can anyone help me to figure out why? I would so appreciate it. thanks</p> <p><img src="https://i.stack.imgur.com/RNKKv.png" alt="enter image description here"></p> <p>I attached some of the HTML table as follows:</p> <pre><code>&lt;table id="appointmentTable"&gt; &lt;thead&gt; &lt;tr class="headerrow"&gt; &lt;th class="actioncolumn"&gt;&lt;/th&gt; &lt;th class="datecolumn"&gt;Date&lt;/th&gt; &lt;th class="earliesttimecolumn"&gt;Start Time&lt;/th&gt; &lt;th class="clientnamecolumn"&gt;Client&lt;/th&gt; &lt;th class="locationcolumn"&gt;Location&lt;/th&gt; &lt;th class="roomcolumn"&gt;Rooms&lt;/th&gt; &lt;th class="typecolumn"&gt;Type&lt;/th&gt; &lt;th class="filledtimescolumn"&gt;Filled Times&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr class=" hiddenrow" appointmentid="15166"&gt; &lt;td class="actioncolumn"&gt;&lt;input type="checkbox" name="appointmentids[]" value="15166" /&gt;&lt;/td&gt; &lt;td class="datecolumn"&gt;&lt;span title="1338094800"&gt;&lt;/span&gt;&lt;a href="?action=viewDailyUsers&amp;date=05/27/2012&amp;clients[]=8" title="View Appointments on 05/27/2012"&gt;05/27/2012&lt;/a&gt;&lt;/td&gt; &lt;td class="earliesttimecolumn"&gt;&lt;/td&gt; &lt;td class="clientnamecolumn"&gt;CPH&lt;/td&gt; &lt;td class="locationcolumn"&gt;New Location&lt;/td&gt; &lt;td class="roomcolumn"&gt;&lt;/td&gt; &lt;td class="typecolumn"&gt;Screening&lt;/td&gt; &lt;td class="filledtimescolumn"&gt;0/0&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;tfoot&gt; &lt;tr class="actionrow"&gt; &lt;td colspan="2" class="actioncolumn"&gt;&lt;/td&gt; &lt;td colspan="6"&gt;With Selected:&lt;/td&gt; &lt;/tr&gt; &lt;tr class="actionrow"&gt; &lt;td colspan="2" class="actioncolumn"&gt; &lt;input type="submit" name="button" value="Create New" /&gt; &lt;/td&gt; &lt;td colspan="6"&gt; &lt;select id="selectactionlist" name="selectaction"&gt; &lt;optgroup label="Adjustments"&gt; &lt;option value="editAppointment"&gt;Edit&lt;/option&gt; &lt;option value="copyAppointment"&gt;Copy&lt;/option&gt; &lt;option value="deleteAppointment"&gt;Delete&lt;/option&gt; &lt;/optgroup&gt; &lt;optgroup label="Lists"&gt; &lt;option value="viewShowList"&gt;Show/No Show List&lt;/option&gt; &lt;option value="viewScheduledTimes"&gt;Schedule List&lt;/option&gt; &lt;/optgroup&gt; &lt;optgroup label="Hidden"&gt; &lt;option value="hideAppointment"&gt;Hide&lt;/option&gt; &lt;option value="showAppointment"&gt;Show&lt;/option&gt; &lt;/optgroup&gt; &lt;/select&gt; &lt;input id="selectactionbutton" type="submit" name="button" value="Select" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tfoot&gt; </code></pre>
3
2,192
here api shows smaller trafficTime for route with same start and end points but via addtional waypoint
<p>How come trafficTime (fastest) from A to B is longer than trafficTime from A to B via C, in the same arrival/departure times?</p> <p>V7 requests: A to B: trafficTime = 4979 seconds <a href="https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey=KEY&amp;waypoint0=32.6289624435649%2C35.079885159610136&amp;waypoint1=32.0155%2C34.7505&amp;mode=fastest%3Bcar&amp;combineChange=true&amp;language=he&amp;instructionformat=text&amp;departure=2020-05-21T10:00:00.000Z" rel="nofollow noreferrer">https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey=KEY&amp;waypoint0=32.6289624435649%2C35.079885159610136&amp;waypoint1=32.0155%2C34.7505&amp;mode=fastest%3Bcar&amp;combineChange=true&amp;language=he&amp;instructionformat=text&amp;departure=2020-05-21T10:00:00.000Z</a></p> <p>A to B via C: trafficTime = 4936 seconds <a href="https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey=KEY&amp;waypoint0=32.6289624435649%2C35.079885159610136&amp;waypoint1=32.119485%2C34.938341&amp;waypoint2=32.0155%2C34.7505&amp;mode=fastest%3Bcar&amp;combineChange=true&amp;language=he&amp;instructionformat=text&amp;departure=2020-05-21T10:00:00.000Z" rel="nofollow noreferrer">https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey=KEY&amp;waypoint0=32.6289624435649%2C35.079885159610136&amp;waypoint1=32.119485%2C34.938341&amp;waypoint2=32.0155%2C34.7505&amp;mode=fastest%3Bcar&amp;combineChange=true&amp;language=he&amp;instructionformat=text&amp;departure=2020-05-21T10:00:00.000Z</a></p> <p>V8 also A to B: duration = 3987 seconds <a href="https://router.hereapi.com/v8/routes?transportMode=car&amp;return=travelSummary,summary,polyline,actions&amp;origin=32.6289624435649,35.079885159610136&amp;destination=32.0155,34.7505&amp;apikey=KEY" rel="nofollow noreferrer">https://router.hereapi.com/v8/routes?transportMode=car&amp;return=travelSummary,summary,polyline,actions&amp;origin=32.6289624435649,35.079885159610136&amp;destination=32.0155,34.7505&amp;apikey=KEY</a></p> <p>A to B via C: duration = 3955 seconds <a href="https://router.hereapi.com/v8/routes?transportMode=car&amp;return=travelSummary,summary,polyline,actions&amp;origin=32.6289624435649,35.079885159610136&amp;destination=32.0155,34.7505&amp;via=32.119485,34.938341!stopDuration=0&amp;apikey=KEY" rel="nofollow noreferrer">https://router.hereapi.com/v8/routes?transportMode=car&amp;return=travelSummary,summary,polyline,actions&amp;origin=32.6289624435649,35.079885159610136&amp;destination=32.0155,34.7505&amp;via=32.119485,34.938341!stopDuration=0&amp;apikey=KEY</a></p> <p>If I request to show several alternatives (available only without "arrival" param) I get even faster and shorter route: V7 A to B with alternatives: fastest trafficTime = 4765 <a href="https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey=KEY&amp;waypoint0=32.6289624435649%2C35.079885159610136&amp;waypoint1=32.0155%2C34.7505&amp;mode=fastest%3Bcar&amp;combineChange=true&amp;language=he&amp;instructionformat=text&amp;departure=2020-05-21T10:00:00.000Z&amp;alternatives=9" rel="nofollow noreferrer">https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey=KEY&amp;waypoint0=32.6289624435649%2C35.079885159610136&amp;waypoint1=32.0155%2C34.7505&amp;mode=fastest%3Bcar&amp;combineChange=true&amp;language=he&amp;instructionformat=text&amp;departure=2020-05-21T10:00:00.000Z&amp;alternatives=9</a></p>
3
1,460
Combing scatterplots on Vegalite
<p>I'm trying to combine 3 scatterplots to look something like this <a href="https://i.stack.imgur.com/Cu1z8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Cu1z8.png" alt="Example" /></a> the code for the example</p> <pre><code>{ &quot;$schema&quot;: &quot;https://vega.github.io/schema/vega-lite/v5.json&quot;, &quot;repeat&quot;: { &quot;row&quot;: [&quot;Horsepower&quot;, &quot;Acceleration&quot;, &quot;Miles_per_Gallon&quot;], &quot;column&quot;: [&quot;Miles_per_Gallon&quot;, &quot;Acceleration&quot;, &quot;Horsepower&quot;] }, &quot;spec&quot;: { &quot;data&quot;: {&quot;url&quot;: &quot;data/cars.json&quot;}, &quot;mark&quot;: &quot;point&quot;, &quot;params&quot;: [ { &quot;name&quot;: &quot;brush&quot;, &quot;select&quot;: { &quot;type&quot;: &quot;interval&quot;, &quot;resolve&quot;: &quot;union&quot;, &quot;on&quot;: &quot;[mousedown[event.shiftKey], window:mouseup] &gt; window:mousemove!&quot;, &quot;translate&quot;: &quot;[mousedown[event.shiftKey], window:mouseup] &gt; window:mousemove!&quot;, &quot;zoom&quot;: &quot;wheel![event.shiftKey]&quot; } }, { &quot;name&quot;: &quot;grid&quot;, &quot;select&quot;: { &quot;type&quot;: &quot;interval&quot;, &quot;resolve&quot;: &quot;global&quot;, &quot;translate&quot;: &quot;[mousedown[!event.shiftKey], window:mouseup] &gt; window:mousemove!&quot;, &quot;zoom&quot;: &quot;wheel![!event.shiftKey]&quot; }, &quot;bind&quot;: &quot;scales&quot; } ], &quot;encoding&quot;: { &quot;x&quot;: {&quot;field&quot;: {&quot;repeat&quot;: &quot;column&quot;}, &quot;type&quot;: &quot;quantitative&quot;}, &quot;y&quot;: { &quot;field&quot;: {&quot;repeat&quot;: &quot;row&quot;}, &quot;type&quot;: &quot;quantitative&quot;, &quot;axis&quot;: {&quot;minExtent&quot;: 30} }, &quot;color&quot;: { &quot;condition&quot;: { &quot;param&quot;: &quot;brush&quot;, &quot;field&quot;: &quot;Origin&quot;, &quot;type&quot;: &quot;nominal&quot; }, &quot;value&quot;: &quot;grey&quot; } } } } </code></pre> <p>Currently, I have 3 separate scatterplots that all you the same data set. After numerous attempts I still can't figure out how to put them together / link them. I know mine is a little more complicated because my axis aren't the same. I've really been struggling with this, any help would be GREATLY appreciated as I need it for uni. Thank you!</p> <p><a href="https://i.stack.imgur.com/9h29u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9h29u.png" alt="my charts" /></a></p> <p>chart 1</p> <pre><code>{ &quot;$schema&quot;: &quot;https://vega.github.io/schema/vega-lite/v4.json&quot;, &quot;title&quot;: { &quot;text&quot;: &quot;Number of Billionaires and Education Attainment&quot;, &quot;subtitle&quot;: &quot;From 2015-2020. Sources: Forbes &amp; World Bank&quot;, &quot;subtitleFontStyle&quot;: &quot;italic&quot;, &quot;subtitleFontSize&quot;: 10, &quot;anchor&quot;: &quot;start&quot;, &quot;color&quot;: &quot;black&quot; }, &quot;height&quot;: 100, &quot;width&quot;: 100, &quot;data&quot;: { &quot;url&quot;: &quot;https://raw.githubusercontent.com/jamieprince/jamieprince.github.io/main/correlation.csv&quot; }, &quot;transform&quot;: [ {&quot;calculate&quot;: &quot;datum.Educationalattainment/100&quot;, &quot;as&quot;: &quot;percent&quot;}, {&quot;filter&quot;: {&quot;field&quot;: &quot;Educationalattainment&quot;, &quot;gt&quot;: 0}} ], &quot;selection&quot;: { &quot;paintbrush&quot;: {&quot;type&quot;: &quot;multi&quot;, &quot;on&quot;: &quot;mouseover&quot;, &quot;nearest&quot;: true}, &quot;grid&quot;: {&quot;type&quot;: &quot;interval&quot;, &quot;bind&quot;: &quot;scales&quot;} }, &quot;mark&quot;: {&quot;type&quot;: &quot;circle&quot;, &quot;opacity&quot;: 0.5, &quot;color&quot;: &quot;#C96E11&quot;}, &quot;encoding&quot;: { &quot;x&quot;: { &quot;field&quot;: &quot;Number of Billionaires&quot;, &quot;type&quot;: &quot;quantitative&quot;, &quot;axis&quot;: { &quot;title&quot;: &quot;Number of Billionaires&quot;, &quot;grid&quot;: false, &quot;tickCount&quot;: 10 } }, &quot;y&quot;: { &quot;field&quot;: &quot;percent&quot;, &quot;type&quot;: &quot;quantitative&quot;, &quot;axis&quot;: {&quot;title&quot;: &quot;Educational Attainment&quot;, &quot;grid&quot;: false, &quot;format&quot;: &quot;%&quot;} }, &quot;size&quot;: { &quot;condition&quot;: { &quot;selection&quot;: &quot;paintbrush&quot;, &quot;value&quot;: 300, &quot;init&quot;: {&quot;value&quot;: 70} }, &quot;value&quot;: 70 }, &quot;tooltip&quot;: [ {&quot;field&quot;: &quot;Year&quot;, &quot;type&quot;: &quot;nominal&quot;, &quot;title&quot;: &quot;Year&quot;}, {&quot;field&quot;: &quot;Country&quot;, &quot;type&quot;: &quot;ordinal&quot;, &quot;title&quot;: &quot;Country&quot;}, { &quot;field&quot;: &quot;Number of Billionaires&quot;, &quot;type&quot;: &quot;nominal&quot;, &quot;title&quot;: &quot;No of Billionaires&quot; }, { &quot;field&quot;: &quot;Educationalattainment&quot;, &quot;type&quot;: &quot;nominal&quot;, &quot;title&quot;: &quot;Educational attainment at least completed short-cycle tertiary population 25+ total (%) (cumulative)&quot; } ] } } </code></pre> <p>chart 2</p> <pre><code>{ &quot;$schema&quot;: &quot;https://vega.github.io/schema/vega-lite/v4.json&quot;, &quot;title&quot;: { &quot;text&quot;: &quot;GDP per capita and Education Attainment&quot;, &quot;subtitle&quot;: &quot;From 2015-2020. Sources: World Bank&quot;, &quot;subtitleFontStyle&quot;: &quot;italic&quot;, &quot;subtitleFontSize&quot;: 10, &quot;anchor&quot;: &quot;start&quot;, &quot;color&quot;: &quot;black&quot; }, &quot;height&quot;: 100, &quot;width&quot;: 100, &quot;data&quot;: { &quot;url&quot;: &quot;https://raw.githubusercontent.com/jamieprince/jamieprince.github.io/main/correlation.csv&quot; }, &quot;transform&quot;: [ {&quot;calculate&quot;: &quot;datum.Educationalattainment/100&quot;, &quot;as&quot;: &quot;percent&quot;}, {&quot;filter&quot;: {&quot;field&quot;: &quot;Educationalattainment&quot;, &quot;gt&quot;: 0}} ], &quot;selection&quot;: { &quot;paintbrush&quot;: {&quot;type&quot;: &quot;multi&quot;, &quot;on&quot;: &quot;mouseover&quot;, &quot;nearest&quot;: true}, &quot;grid&quot;: {&quot;type&quot;: &quot;interval&quot;, &quot;bind&quot;: &quot;scales&quot;} }, &quot;mark&quot;: {&quot;type&quot;: &quot;circle&quot;, &quot;opacity&quot;: 0.5, &quot;color&quot;: &quot;#EC9D3E&quot;}, &quot;encoding&quot;: { &quot;x&quot;: { &quot;field&quot;: &quot;GDP per capita&quot;, &quot;type&quot;: &quot;quantitative&quot;, &quot;axis&quot;: { &quot;title&quot;: &quot;GDP per capita&quot;, &quot;grid&quot;: false, &quot;tickCount&quot;: 10, &quot;labelOverlap&quot;: &quot;greedy&quot; } }, &quot;y&quot;: { &quot;field&quot;: &quot;percent&quot;, &quot;type&quot;: &quot;quantitative&quot;, &quot;axis&quot;: {&quot;title&quot;: &quot;Educational Attainment&quot;, &quot;grid&quot;: false, &quot;format&quot;: &quot;%&quot;} }, &quot;size&quot;: { &quot;condition&quot;: { &quot;selection&quot;: &quot;paintbrush&quot;, &quot;value&quot;: 300, &quot;init&quot;: {&quot;value&quot;: 70} }, &quot;value&quot;: 70 }, &quot;tooltip&quot;: [ {&quot;field&quot;: &quot;Year&quot;, &quot;type&quot;: &quot;nominal&quot;, &quot;title&quot;: &quot;Year&quot;}, {&quot;field&quot;: &quot;Country&quot;, &quot;type&quot;: &quot;ordinal&quot;, &quot;title&quot;: &quot;Country&quot;}, {&quot;field&quot;: &quot;GDP per capita&quot;, &quot;type&quot;: &quot;nominal&quot;, &quot;title&quot;: &quot;GDP per capita&quot;}, { &quot;field&quot;: &quot;Educationalattainment&quot;, &quot;type&quot;: &quot;nominal&quot;, &quot;title&quot;: &quot;Educational attainment at least completed short-cycle tertiary population 25+ total (%) (cumulative)&quot; } ] } } </code></pre> <p>chart 3</p> <pre><code>{ &quot;$schema&quot;: &quot;https://vega.github.io/schema/vega-lite/v4.json&quot;, &quot;title&quot;: { &quot;text&quot;: &quot;No of billionaires and GDP per capita&quot;, &quot;subtitle&quot;: &quot;From 2015-2020. Sources: Forbes &amp; World Bank&quot;, &quot;subtitleFontStyle&quot;: &quot;italic&quot;, &quot;subtitleFontSize&quot;: 10, &quot;anchor&quot;: &quot;start&quot;, &quot;color&quot;: &quot;black&quot; }, &quot;height&quot;: 100, &quot;width&quot;: 100, &quot;data&quot;: { &quot;url&quot;: &quot;https://raw.githubusercontent.com/jamieprince/jamieprince.github.io/main/correlation.csv&quot; }, &quot;selection&quot;: { &quot;paintbrush&quot;: {&quot;type&quot;: &quot;multi&quot;, &quot;on&quot;: &quot;mouseover&quot;, &quot;nearest&quot;: true}, &quot;grid&quot;: {&quot;type&quot;: &quot;interval&quot;, &quot;bind&quot;: &quot;scales&quot;} }, &quot;mark&quot;: {&quot;type&quot;: &quot;circle&quot;, &quot;opacity&quot;: 0.5, &quot;color&quot;: &quot;#FBCA8B&quot;}, &quot;encoding&quot;: { &quot;x&quot;: { &quot;field&quot;: &quot;Number of Billionaires&quot;, &quot;type&quot;: &quot;quantitative&quot;, &quot;axis&quot;: { &quot;title&quot;: &quot;Number of Billionaires&quot;, &quot;grid&quot;: false, &quot;tickCount&quot;: 14 } }, &quot;y&quot;: { &quot;field&quot;: &quot;GDP per capita&quot;, &quot;type&quot;: &quot;quantitative&quot;, &quot;axis&quot;: {&quot;title&quot;: &quot;GDP per capita&quot;, &quot;grid&quot;: false} }, &quot;size&quot;: { &quot;condition&quot;: { &quot;selection&quot;: &quot;paintbrush&quot;, &quot;value&quot;: 300, &quot;init&quot;: {&quot;value&quot;: 70} }, &quot;value&quot;: 70 }, &quot;tooltip&quot;: [ {&quot;field&quot;: &quot;Year&quot;, &quot;type&quot;: &quot;nominal&quot;, &quot;title&quot;: &quot;Year&quot;}, {&quot;field&quot;: &quot;Country&quot;, &quot;type&quot;: &quot;ordinal&quot;, &quot;title&quot;: &quot;Country&quot;}, {&quot;field&quot;: &quot;GDP per capita&quot;, &quot;type&quot;: &quot;nominal&quot;, &quot;title&quot;: &quot;GDP per capita&quot;}, { &quot;field&quot;: &quot;Number of Billionaires&quot;, &quot;type&quot;: &quot;nominal&quot;, &quot;title&quot;: &quot;Number of Billionaires&quot; } ] } } </code></pre>
3
5,851
Unexpected static counter variable behaviour
<p>Lately I tried getting my head around the static keyword and here I attempt to simply use the static keyword for a variable declaration within a function. Like so:</p> <pre><code>void counter() { static int counter = 0; //should be initialized only once and once only counter++; //increment for every call of this function } </code></pre> <p>I understand that due to the variable being static, it will live outside the function and therefore from wherever I decide to print out counter, it should give me the number of times the function <code>counter()</code> was called. So I did a simple test as shown:</p> <pre><code>int main() { for(unsigned int i = 0; i &lt; 10; i++){ counter(); } std::cout &lt;&lt; counter &lt;&lt; std::endl; return 0; } </code></pre> <p>From this test I expected to get number 10... but instead the number of counts the code returned was 1. </p> <p>Please, what am I missing here?</p> <p>I found other submissions to "similar" issues such as this one: <a href="https://stackoverflow.com/questions/10881410/static-counter-in-c">static counter in c++</a> But they mostly revolve around the static keyword being used in classes.</p>
3
1,219
maven-embedded-glassfish-plugin not work with logback
<p>I am encountering a problem when using maven-embedded-glassfish-plugin(3.1.2.2) with logback that the configuration of logback is NOT used in embedded glassfish.</p> <p>And, I found <a href="https://stackoverflow.com/questions/21645652/configure-glassfish-embedded-server-with-logback-logging">this</a> and <a href="https://stackoverflow.com/questions/16335091/specify-logging-properties-in-embedded-glassfish-with-maven-embedded-glassfish-p">that</a> are similar posts with NO solution found. Anyone can help? This is my pom.xml</p> <pre><code>&lt;properties&gt; &lt;!-- JEE --&gt; &lt;jee.version&gt;6.0&lt;/jee.version&gt; &lt;!-- logger --&gt; &lt;logback.version&gt;1.0.13&lt;/logback.version&gt; &lt;slf4j.version&gt;1.7.5&lt;/slf4j.version&gt; &lt;!-- maven plugin --&gt; &lt;maven-embedded-glassfish-plugin.version&gt;3.1.2.2&lt;/maven-embedded-glassfish-plugin.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;!-- JEE --&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-api&lt;/artifactId&gt; &lt;version&gt;${jee.version}&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- logger --&gt; &lt;dependency&gt; &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt; &lt;artifactId&gt;logback-classic&lt;/artifactId&gt; &lt;version&gt;${logback.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt; &lt;version&gt;${slf4j.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;log4j-over-slf4j&lt;/artifactId&gt; &lt;version&gt;${slf4j.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;jul-to-slf4j&lt;/artifactId&gt; &lt;version&gt;${slf4j.version}&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.glassfish.embedded&lt;/groupId&gt; &lt;artifactId&gt;maven-embedded-glassfish-plugin&lt;/artifactId&gt; &lt;version&gt;${maven-embedded-glassfish-plugin.version}&lt;/version&gt; &lt;configuration&gt; &lt;app&gt;target/${project.artifactId}-${project.version}&lt;/app&gt; &lt;port&gt;8080&lt;/port&gt; &lt;ports&gt; &lt;https-listener&gt;8181&lt;/https-listener&gt; &lt;/ports&gt; &lt;name&gt;${project.artifactId}&lt;/name&gt; &lt;contextRoot&gt;/&lt;/contextRoot&gt; &lt;autoDelete&gt;true&lt;/autoDelete&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre>
3
1,577
Update mysql data via json
<p>Hey all So I am able to update the records from a json url and put it into Mysql now I am trying to update the records and it only grabs 1 value and updates all the records to the new value so its updating the existing records with only 1 record here is what I am using</p> <pre><code>$ApiLink = "JSON URL HERE"; $json_decode = (json_decode(file_get_contents($ApiLink), true)); $output = $json_decode["character_list"]; /************************************************/ $do_stuff = $dbh-&gt;prepare("UPDATE damage_given_vehicle SET veh_id=:veh_id, veh_name=:veh_name, veh_total=:total_value, veh_faction_nc=:veh_faction_nc, veh_faction_tr=:veh_faction_tr, veh_faction_vs=:veh_faction_vs WHERE character_number = :char_id"); foreach ($output as $key =&gt; $value) { $character_id[$key] = $output[$key]["id"]; if (isset($output[$key]["stats"]["vehicle_kills"]["vehicle"])) { $vehicle_kills[$key] = $output[$key]["stats"]["vehicle_kills"]["vehicle"]; foreach ($vehicle_kills[$key] as $row) { $do_stuff-&gt;bindValue(':char_id', $update_id); $do_stuff-&gt;bindValue(':veh_id', $row["id"]); $do_stuff-&gt;bindValue(':veh_name', $row["name"]); $do_stuff-&gt;bindValue(':total_value', $row["value"]); $do_stuff-&gt;bindValue(':veh_faction_nc', $row["faction"]["nc"]); $do_stuff-&gt;bindValue(':veh_faction_tr', $row["faction"]["tr"]); $do_stuff-&gt;bindValue(':veh_faction_vs', $row["faction"]["vs"]); $do_stuff-&gt;execute(); } } } </code></pre> <p>the database looks like this at first:</p> <pre><code>key | id | name | value 1 | value 2 | value 3 | value 4 | 5428029729515051201 11 name_1 6 45 23 34 5428029729515051201 11 name_2 2 34 63 63 5428029729515051201 11 name_3 34 0 17 17 </code></pre> <p>after I use the update script it turns those values into:</p> <pre><code>5428029729515051201 11 name 34 0 17 17 5428029729515051201 11 name 34 0 17 17 5428029729515051201 11 name 34 0 17 17 </code></pre> <p>if you are curious how the script enters the json data here you go:</p> <pre><code>$stmt = $dbh-&gt;prepare(" INSERT INTO damage_given_vehicle ( character_number, veh_id, veh_name, veh_total, veh_faction_nc, veh_faction_tr, veh_faction_vs) VALUES( :char_id, :veh_id, :veh_name, :total_value, :veh_faction_nc, :veh_faction_tr, :veh_faction_vs) "); foreach ($output as $key =&gt; $value) { $character_id[$key] = $output[$key]["id"]; if (isset($output[$key]["stats"]["vehicle_kills"]["vehicle"])) { $vehicle_kills[$key] = $output[$key]["stats"]["vehicle_kills"]["vehicle"]; foreach ($vehicle_kills[$key] as $row) { $stmt-&gt;bindValue(':char_id', $character_id[$key]); $stmt-&gt;bindValue(':veh_id', $row["id"]); $stmt-&gt;bindValue(':veh_name', $row["name"]); $stmt-&gt;bindValue(':total_value', $row["value"]); $stmt-&gt;bindValue(':veh_faction_nc', $row["faction"]["nc"]); $stmt-&gt;bindValue(':veh_faction_tr', $row["faction"]["tr"]); $stmt-&gt;bindValue(':veh_faction_vs', $row["faction"]["vs"]); $stmt-&gt;execute(); } } } </code></pre> <p>How do I get it to update every array seperately, If I do a var_dump on any of the $row[""] they produce the array how it should be displayed but when it goes through and enters into mysql it only grabs 1 value </p> <p>THANKS!</p>
3
1,626
Typescript: Compilation Error only when using Docker
<p>So I have this weird error when Typescript would throw a Compilation Error when I try to to run my app using Docker. This error does not happen when I run it locally on my computer.</p> <p>My Dockerfile</p> <pre><code>FROM node:alpine WORKDIR /app COPY package.json . RUN npm install --only=prod COPY ./ ./ CMD [&quot;npm&quot;, &quot;start&quot;] </code></pre> <p>Package.json</p> <pre><code>{ &quot;name&quot;: &quot;auth&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;description&quot;: &quot;Authorization Service for Ticketting&quot;, &quot;main&quot;: &quot;index.js&quot;, &quot;type&quot;: &quot;module&quot;, &quot;scripts&quot;: { &quot;start&quot;: &quot;ts-node-dev --no-deps --respawn --poll --interval 1000 src/index.ts&quot;, &quot;test&quot;: &quot;jest --watchAll --no-cache&quot; }, &quot;jest&quot;: { &quot;preset&quot;: &quot;ts-jest&quot;, &quot;testEnvironment&quot;: &quot;node&quot;, &quot;setupFilesAfterEnv&quot;: [ &quot;./src/test/setup.ts&quot; ] }, &quot;author&quot;: &quot;Nam Nguyen&quot;, &quot;license&quot;: &quot;ISC&quot;, &quot;devDependencies&quot;: { &quot;@types/jest&quot;: &quot;^26.0.15&quot;, &quot;@types/supertest&quot;: &quot;^2.0.10&quot;, &quot;jest&quot;: &quot;^26.6.3&quot;, &quot;mongodb-memory-server&quot;: &quot;^6.9.2&quot;, &quot;supertest&quot;: &quot;^6.0.1&quot;, &quot;ts-jest&quot;: &quot;^26.4.4&quot; }, &quot;dependencies&quot;: { &quot;@nnticketting/common&quot;: &quot;^1.0.5&quot;, &quot;@types/cookie-session&quot;: &quot;^2.0.41&quot;, &quot;@types/cors&quot;: &quot;^2.8.8&quot;, &quot;@types/express&quot;: &quot;^4.17.8&quot;, &quot;@types/jsonwebtoken&quot;: &quot;^8.5.0&quot;, &quot;@types/mongoose&quot;: &quot;^5.10.0&quot;, &quot;cookie-session&quot;: &quot;^1.4.0&quot;, &quot;cors&quot;: &quot;^2.8.5&quot;, &quot;dotenv&quot;: &quot;^8.2.0&quot;, &quot;express&quot;: &quot;^4.17.1&quot;, &quot;express-async-errors&quot;: &quot;^3.1.1&quot;, &quot;express-validator&quot;: &quot;^6.6.1&quot;, &quot;jsonwebtoken&quot;: &quot;^8.5.1&quot;, &quot;mongoose&quot;: &quot;^5.10.13&quot;, &quot;ts-node&quot;: &quot;^9.1.0&quot;, &quot;ts-node-dev&quot;: &quot;^1.0.0&quot;, &quot;typescript&quot;: &quot;^4.1.2&quot; } } </code></pre> <p><a href="https://i.stack.imgur.com/l0hg3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l0hg3.png" alt="Error" /></a></p> <p>And these are the codes that Typescript is complaining about. Apparently Typescript is expecting 1 argument for the &quot;done()&quot; callback which makes no sense.</p> <pre><code>userSchema.pre('save', async function (done) { if (this.isModified('password')) { const hashed = await Password.toHash(this.get('password')); this.set('password', hashed); } done(); }); </code></pre>
3
1,509
Conditional merging with many variables
<p>I am wondering if there was a faster, more elegant data.table solution to my following question.</p> <p>Suppose we have two datasets</p> <pre><code>set.seed(1) library(data.table) DT1 &lt;- data.table(income = runif(10, 0,1), ID = 1:10) DT2 &lt;- data.table(height = runif(20,0,1), weight = runif(20,0,1), V1 = runif(20,0,1), V2 = runif(20,0,2), type = rep(c(&quot;Parents&quot;, &quot;Children&quot;),10)) DT2 &lt;- DT2[order(type)][, ID := rep(1:10,2)] </code></pre> <p>The first dataset is a &quot;household&quot; level dataset with household identifiers given by ID, from 1:10.</p> <p>There is a second dataset, <code>DT2</code> which has four variables for each parent and child, for each household ID. What I want to do is merge all the variables (height, weight, V1, V2) of the Parents and Children in each row/observation of DT1. So we would have eight variables to merge, four for the parents and four for the children.</p> <p>To do so, I can simply write the following:</p> <pre><code> DT1[DT2[type == &quot;Parents&quot;], c(&quot;height_parents&quot;, &quot;weight_parents&quot;, &quot;V1_parents&quot;, &quot;V2_parents&quot;) := list(i.height, i.weight, i.V1, i.V2), on = c(ID = &quot;ID&quot;)] DT1[DT2[type == &quot;Children&quot;], c(&quot;height_children&quot;, &quot;weight_children&quot;, &quot;V1_children&quot;, &quot;V2_children&quot;) := list(i.height, i.weight, i.V1, i.V2), on = c(ID = &quot;ID&quot;)] </code></pre> <p>The output looks like:</p> <pre><code> income ID height_parents weight_parents V1_parents V2_parents height_children 1: 0.70647001 1 0.49163534 0.164385214 0.6806198 1.72937701 0.04655907 2: 0.07658058 2 0.06776809 0.234182275 0.4456820 1.76814822 0.45665042 3: 0.49770601 3 0.23255515 0.709256017 0.3514867 1.83387012 0.24395311 4: 0.51944306 4 0.30555999 0.974742471 0.0529102 0.06094086 0.22356168 5: 0.23075737 5 0.51104028 0.007269433 0.4157508 1.00207079 0.98915308 6: 0.86449990 6 0.75420198 0.211342425 0.9837331 0.03520897 0.86080818 weight_children V1_children V2_Children 1: 0.3398447 0.7454582 0.6761706 2: 0.8475106 0.4716267 1.5231691 3: 0.8895790 0.1561395 1.8721056 4: 0.3503219 0.2663775 0.2408758 5: 0.3902352 0.9332958 1.3532260 6: 0.7648748 0.6969372 1.3289579 </code></pre> <p>Note that if I had many different &quot;types&quot; (here there is only two) and/or many different variables to merge (here there is only 4), the above would get quickly laborious and verbose. The dataset I am using has many different variables and types. Thus, I am looking to do this in a more efficient way. In particular, I want to be able to define a vector:</p> <pre><code>merge_variables = c(&quot;height&quot;, &quot;weight&quot;, &quot;V1&quot;, &quot;V2&quot;) </code></pre> <p>and in a data.table fashion, have all of these variables merge for both parents and children. I want the new variables to have an underscore in them with the types name (e.g.<code>height_parents</code> and <code>height_children</code>).</p> <p>I hope I've communicated my request clearly.</p> <p>Thanks!</p>
3
1,645
Why the strings sticks out from the Bubble window?
<p>Strings has to go to next line if it's long. How can I do this?</p> <p><a href="http://jsfiddle.net/Yu6dD/" rel="nofollow">Demo</a></p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="chat"&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;Body&lt;/th&gt; &lt;/tr&gt; &lt;tr id="comment_617"&gt; &lt;td&gt;&lt;div class="bubble me"&gt;&lt;span class="text-error"&gt;01-10 03:29&lt;/span&gt;:Person A&lt;br&gt; bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &lt;form action="/shop/walmart/posts/617" class="button_to" data-remote="true" method="post"&gt;&lt;div&gt;&lt;input name="_method" value="delete" type="hidden"&gt;&lt;input data-confirm="Are you sure?" data-disable-with="deleting..." value="destroy" type="submit"&gt;&lt;input name="authenticity_token" value="aoLKQnl4M2SWVlOrXGR+qIMLSeY5m1tKiC/PSnYQjmw=" type="hidden"&gt;&lt;/div&gt;&lt;/form&gt; &lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr id="comment_615"&gt; &lt;td&gt;&lt;div class="bubble me"&gt;&lt;span class="text-error"&gt;01-10 03:25&lt;/span&gt;:Person A&lt;br&gt; bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &lt;form action="/shop/walmart/posts/615" class="button_to" data-remote="true" method="post"&gt;&lt;div&gt;&lt;input name="_method" value="delete" type="hidden"&gt;&lt;input data-confirm="Are you sure?" data-disable-with="deleting..." value="destroy" type="submit"&gt;&lt;input name="authenticity_token" value="aoLKQnl4M2SWVlOrXGR+qIMLSeY5m1tKiC/PSnYQjmw=" type="hidden"&gt;&lt;/div&gt;&lt;/form&gt; &lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.chat { width: 400px; } .bubble{ background-color: #F2F2F2; border-radius: 5px; box-shadow: 0 0 6px #B2B2B2; display: inline-block; padding: 10px 18px; position: relative; vertical-align: top; } .bubble::before { background-color: #F2F2F2; content: "\00a0"; display: block; height: 16px; position: absolute; top: 11px; transform: rotate( 29deg ) skew( -35deg ); -moz-transform: rotate( 29deg ) skew( -35deg ); -ms-transform: rotate( 29deg ) skew( -35deg ); -o-transform: rotate( 29deg ) skew( -35deg ); -webkit-transform: rotate( 29deg ) skew( -35deg ); width: 20px; } .me { float: left; margin: 5px 45px 5px 5px; width: 200px; } .me::before { box-shadow: -2px 2px 2px 0 rgba( 178, 178, 178, .4 ); left: -9px; } .you { float: left; margin: 5px 10px 5px 5px; width: 200px; } .you::before { box-shadow: 2px -2px 2px 0 rgba( 178, 178, 178, .4 ); right: -9px; } </code></pre>
3
1,451
Keep prompt at bottom of screen for messaging app
<p>I'm trying to develop a CLI messaging app in C on mac for network programming practice but I'm not sure how to effectively manipulate the command line to make it usable. Currently the prompt will display "Enter a message: " but if a message comes in before the user finished typing their message something like this could happen: "Enter a message: Hello wClient: I'm interupting youorld".</p> <p>The solution I'd like to have would be to have the "Enter a message" prompt always at the bottom of the screen with the incoming and outgoing messages coming down from the top as you'd have in basically any messenger, though I have no idea how to glue something to the bottom of the terminal or how to visually affect the terminal in any way.</p> <p>Here's the entirety of the code so far:</p> <p>Server</p> <pre><code>#include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;errno.h&gt; #include &lt;string.h&gt; #include &lt;sys/types.h&gt; int main() { int listenfd = 0, connfd = 0; struct sockaddr_in serv_addr; char sendBuff[1025]; char recvBuff[1025] = "test"; listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&amp;serv_addr, '0', sizeof(serv_addr)); memset(sendBuff, '0', sizeof(sendBuff)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(5000); bind(listenfd, (struct sockaddr*)&amp;serv_addr, sizeof(serv_addr)); if (listen(listenfd, 10) == -1) { printf("Failed to listen\n"); return -1; } connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL); pid_t pid = fork(); if (pid) { while (strncmp(recvBuff, "exit", 4) != 0) { if(recv(connfd, recvBuff, sizeof(recvBuff)-1, 0) &lt; 0) printf("Error: Recieve\nErrno: %d\n", errno); recvBuff[1024] = 0; printf("Client: %s", recvBuff); } wait(&amp;pid); close(connfd); } else { while (strncmp(sendBuff, "exit", 4) != 0) { fputs("Enter a message: ", stdout); fgets(sendBuff, sizeof(sendBuff), stdin); if(send(connfd, sendBuff, sizeof(sendBuff), 0) &lt; 0) printf("Error: Send\nErrno: %d\n", errno); } close(connfd); exit(0); } close(listenfd); return 0; } </code></pre> <p>Client</p> <pre><code>#include &lt;sys/socket.h&gt; #include &lt;sys/types.h&gt; #include &lt;netinet/in.h&gt; #include &lt;netdb.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;errno.h&gt; #include &lt;arpa/inet.h&gt; int main(void) { int sockfd = 0; char recvBuff[1024]; char sendBuff[1024] = ""; struct sockaddr_in serv_addr; memset(recvBuff, '0' ,sizeof(recvBuff)); if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) &lt; 0) { printf("\n Error : Could not create socket \n"); return 1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(5000); serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); if(connect(sockfd, (struct sockaddr *)&amp;serv_addr, sizeof(serv_addr)) &lt; 0) { printf("\n Error : Connect Failed \n"); return 1; } pid_t pid = fork(); if (pid) { while (strncmp(recvBuff, "exit", 4) != 0) { if(recv(sockfd, recvBuff, sizeof(recvBuff)-1, 0) &lt; 0) printf("Error: Receive\nErrno: %d\n", errno); recvBuff[1024] = 0; printf("Server: %s", recvBuff); } wait(&amp;pid); close(sockfd); } else { while (strncmp(sendBuff, "exit", 4) != 0) { fputs("Enter a message: ", stdout); fgets(sendBuff, sizeof(sendBuff), stdin); if(send(sockfd, sendBuff, sizeof(sendBuff), 0) &lt; 0) printf("Error: Send\nErrno: %d\n", errno); } close(sockfd); exit(0); } return 0; } </code></pre> <p>Also any side notes about coding style or networking techniques are appreciated too. Thanks.</p>
3
1,650
how do I use variables from functions in other functions without putting the variable in the __init__ method of a class?
<p>I am new level coder, and I making a game that has different kinds of attacks, and I want to be able to combo into attacks seemlessly, but I cannot figure out how to make a delay between different attacks. So far I have tried to use to the same value that is the attack delay so that if the delay is reset, you can use a different attack, but it is not letting me do that because it doesn't know what the variable "now" is because I need "now" needs to be specifically in that function. Here is the code: </p> <pre class="lang-python prettyprint-override"><code>class Player(pg.sprite.Sprite): def __init__(self, game): self.game = game pg.sprite.Sprite.__init__(self) self.image = pg.Surface((30, 35)) self.image.fill(RED) self.rect = self.image.get_rect() self.rect.center = (WIDTH / 2, HEIGHT / 2) self.pos = vec(WIDTH / 2, HEIGHT / 2) self.vel = vec(0, 0) self.acc = vec(0, 0) self.attack_counter = 0 self.dt = 0.2 # this is all the attack delay stuff self.last_attack = 100 self.last_attack_n_light_right = 700 self.last_attack_s_light_right = 425 self.last_attack_d_light_right = 700 self.last_attack_s_air_right = 425 self.last_attack_n_light_left = 700 self.last_attack_s_light_left = 425 self.last_attack_d_light_left = 700 self.last_attack_n_air = 425 self.last_attack_s_air_left = 425 self.last_attack_d_air = 425 self.attack_delay = pg.time.get_ticks() self.attack_delay_n_light_right = pg.time.get_ticks() self.attack_delay_s_light_right = pg.time.get_ticks() self.attack_delay_d_light_right = pg.time.get_ticks() self.attack_delay_s_air_right = pg.time.get_ticks() self.attack_delay_n_light_left = pg.time.get_ticks() self.attack_delay_s_light_left = pg.time.get_ticks() self.attack_delay_d_light_left = pg.time.get_ticks() self.attack_delay_n_air = pg.time.get_ticks() self.attack_delay_s_air_left = pg.time.get_ticks() self.attack_delay_d_air = pg.time.get_ticks() self.move_delay = pg.time.get_ticks() def jump(self): # jump if jump key is pressed, and triple jumps are recharged when touching platforms global player_jump_count self.rect.x += 1 self.rect.x -= 1 player_jump_count -= 1 self.vel.y = -PLAYER_JUMP hits = pg.sprite.spritecollide(self, self.game.platforms, False) if hits: player_jump_count = 3 if player_jump_count &lt; 1: self.vel.y = PLAYER_GRAV def s_light_right(self): keys = pg.key.get_pressed() now = pg.time.get_ticks() # print(now, " ", self.attack_delay_s_light_right) if self.s_light_left.now - self.attack_delay_s_light_left &gt; self.last_attack_s_light_left: if keys[pg.K_d]: if now - self.attack_delay_s_light_right &gt; self.last_attack_s_light_right: # this is where the problem is self.attack_delay_s_light_right = now bullet = Bullet(self.rect.centerx + 20, self.rect.centery - 10, self.vel.x + 10, 0, 20, 20, self.dt) self.game.all_sprites.add(bullet) self.game.bullets.add(bullet) def s_light_left(self): keys = pg.key.get_pressed() now = pg.time.get_ticks() if keys[pg.K_a]: if now - self.attack_delay_s_light_left &gt; self.last_attack_s_light_left: self.attack_delay_s_light_left = now bullet = Bullet(self.rect.centerx - 20, self.rect.centery - 10, self.vel.x - 10, 0, 20, 20, self.dt) self.game.all_sprites.add(bullet) self.game.bullets.add(bullet) def n_light_right(self): keys = pg.key.get_pressed() now = pg.time.get_ticks() if not keys[pg.K_a] and not keys[pg.K_d] and not keys[pg.K_s]: if now - self.attack_delay_n_light_right &gt; self.last_attack_n_light_right: self.attack_delay_n_light_right = now bullet = Bullet(self.rect.centerx + 40, self.rect.centery - 40, 0, 0, 20, 20, self.dt) self.game.all_sprites.add(bullet) self.game.bullets.add(bullet) def n_light_left(self): keys = pg.key.get_pressed() now = pg.time.get_ticks() if not keys[pg.K_a] and not keys[pg.K_d] and not keys[pg.K_s]: if now - self.attack_delay_n_light_left &gt; self.last_attack_n_light_left: self.attack_delay_n_light_left = now bullet = Bullet(self.rect.centerx - 60, self.rect.centery - 40, 0, 0, 20, 20, self.dt) self.game.all_sprites.add(bullet) self.game.bullets.add(bullet) def d_light_right(self): keys = pg.key.get_pressed() now = pg.time.get_ticks() if keys[pg.K_s]: if not keys[pg.K_a] and not keys[pg.K_d]: if now - self.attack_delay_d_light_right &gt; self.last_attack_d_light_right: self.attack_delay_d_light_right = now bullet = Bullet(self.rect.centerx + 40, self.rect.centery + 3.5, 0, 0, 30, 15, self.dt) self.game.all_sprites.add(bullet) self.game.bullets.add(bullet) def d_light_left(self): keys = pg.key.get_pressed() now = pg.time.get_ticks() if keys[pg.K_s]: if not keys[pg.K_a] and not keys[pg.K_d]: if now - self.attack_delay_d_light_left &gt; self.last_attack_d_light_left: self.attack_delay_d_light_left = now bullet = Bullet(self.rect.centerx - 60, self.rect.centery + 3.5, 0, 0, 30, 15, self.dt) self.game.all_sprites.add(bullet) self.game.bullets.add(bullet) def s_air_right(self): keys = pg.key.get_pressed() now = pg.time.get_ticks() if keys[pg.K_d]: if now - self.attack_delay_s_air_right &gt; self.last_attack_s_air_right: self.attack_delay_s_air_right = now bullet = Bullet(self.rect.centerx + 20, self.rect.centery - 10, self.vel.x + 10, 0, 20, 20, self.dt) self.game.all_sprites.add(bullet) self.game.bullets.add(bullet) def s_air_left(self): keys = pg.key.get_pressed() now = pg.time.get_ticks() if keys[pg.K_a]: if now - self.attack_delay_s_air_left &gt; self.last_attack_s_air_left: self.attack_delay_s_air_left = now bullet = Bullet(self.rect.centerx - 20, self.rect.centery - 10, self.vel.x - 10, 0, 20, 20, self.dt) self.game.all_sprites.add(bullet) self.game.bullets.add(bullet) def n_air(self): keys = pg.key.get_pressed() now = pg.time.get_ticks() if not keys[pg.K_a] and not keys[pg.K_d] and not keys[pg.K_s]: if now - self.attack_delay_n_air &gt; self.last_attack_n_air: self.attack_delay_n_air = now bullet = Bullet(self.rect.centerx + 5, self.rect.centery - 60, 0, 0, 20, 20, self.dt) bullet2 = Bullet(self.rect.centerx - 25, self.rect.centery - 60, 0, 0, 20, 20, self.dt) self.game.all_sprites.add(bullet) self.game.bullets.add(bullet) self.game.all_sprites.add(bullet2) self.game.bullets.add(bullet2) def d_air(self): keys = pg.key.get_pressed() now = pg.time.get_ticks() if keys[pg.K_s]: if not keys[pg.K_a] and not keys[pg.K_d]: if now - self.attack_delay_d_air &gt; self.last_attack_d_air: self.attack_delay_d_air = now bullet = Bullet(self.rect.centerx + 5, self.rect.centery + 60, 0, 12, 20, 20, self.dt) bullet2 = Bullet(self.rect.centerx - 25, self.rect.centery + 60, 0, 12, 20, 20, self.dt) self.game.all_sprites.add(bullet) self.game.bullets.add(bullet) self.game.all_sprites.add(bullet2) self.game.bullets.add(bullet2) def update(self): self.acc = vec(0, PLAYER_GRAV) keys = pg.key.get_pressed() if keys[pg.K_a]: self.acc.x = -PLAYER_ACC if keys[pg.K_d]: self.acc.x = PLAYER_ACC # apply friction self.acc.x += self.vel.x * PLAYER_FRICTION # equations of motion self.vel += self.acc self.pos += self.vel + 0.5 * self.acc self.rect.midbottom = self.pos </code></pre>
3
4,445
AWS Lightsail can't update Route53 for Let'sEncrypt certs
<p>I'm trying to get Let's Encrypt automatic cert update on a AWS Lightsail wordpress instance and Route53.</p> <p>I used <a href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-using-lets-encrypt-certificates-with-wordpress" rel="nofollow noreferrer">these official instructions</a> for adding a SSL certs to a AWS Lightsail wordpress website.</p> <p>Site SSL is working fine, but I was looking for a way to automate the re-issue and found the certbot plugin - <a href="https://certbot-dns-route53.readthedocs.io/en/stable/" rel="nofollow noreferrer">certbot-dns-route53</a></p> <p>I created a separate AWS non-admin user just for the updates, and added the policy as suggested by the certbot official docs</p> <pre><code>{ &quot;Version&quot;: &quot;2012-10-17&quot;, &quot;Id&quot;: &quot;certbot-dns-route53 sample policy&quot;, &quot;Statement&quot;: [ { &quot;Effect&quot;: &quot;Allow&quot;, &quot;Action&quot;: [ &quot;route53:ListHostedZones&quot;, &quot;route53:GetChange&quot; ], &quot;Resource&quot;: [ &quot;*&quot; ] }, { &quot;Effect&quot; : &quot;Allow&quot;, &quot;Action&quot; : [ &quot;route53:ChangeResourceRecordSets&quot; ], &quot;Resource&quot; : [ &quot;arn:aws:route53:::hostedzone/MYZONEID&quot; ] } ] } </code></pre> <p>I placed the API access information in both a environment variable and ~/.aws.config file.</p> <p>I executed the command -</p> <pre><code> sudo certbot certonly --dns-route53 --dns-route53-propagation-seconds 30 --dry-run -d 'domain. com,*.domain.com' </code></pre> <p>And I get the following error -</p> <blockquote> <p>An error occurred (AccessDenied) when calling the ListHostedZones operation: User: arn:aws:sts::548507530525:assumed-role/Amaz onLightsailInstanceRole/i-00ff79ff762ac0576 is not authorized to perform: route53:ListHostedZones To use certbot-dns-route53, configure credentials as described at <a href="https://boto3.readthedocs.io/en/latest/guide/configuration.h" rel="nofollow noreferrer">https://boto3.readthedocs.io/en/latest/guide/configuration.h</a> tml#best-practices-for-configuring-credentials and add the necessary permissions for Route53 access</p> </blockquote> <p>I attempted a ~.aws/config &amp; credentials file as well -</p> <p>config-</p> <pre><code>[profile cross-account] role_arn=arn:aws:iam::XXXXXXXXXXX:user/domain_cert_update source_profile=default </code></pre> <p>credentials -</p> <pre><code>[default] aws_access_key_id=ACCESSKEY aws_secret_access_key=SECRETKEYHERE </code></pre> <p>I'm not sure how to get the lightsail instance of /i-00ff79ff762ac0576 assigned to the policy correctly. I've read through the config guide it links and it doesn't help.</p>
3
1,230
How to track and move String from left to right?
<p>I'm making a racing game using Strings and I'm having trouble making them move to the right. How would I go about moving the Strings? Methods JamesMove() &amp; KeithMove() are the same as SusanMove(), just with the name of the variable are different.</p> <pre><code>public class NameRacer { public static void nameRaces() { Scanner scan = new Scanner(System.in); String response; int SusanFront, SusanBack, JamesFront, JamesBack, KeithFront, KeithBacck; boolean raceIsDone; int move = (int)((Math.random() * 5) + 1); introduction(); scan.nextLine(); do { SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); SusanMove(); JamesMove(); KeithMove(); System.out.println("Would you like to watch the race again?"); response=scan.next(); } while(response.equalsIgnoreCase("yes")); } private static void introduction() { System.out.println("This game races three names. The random number generator"); System.out.println("from the Math class repeatedly gives each name a random number"); System.out.println("between 1 and 5. As the names move these random distances"); System.out.println("we see which name gets to the finish line first."); System.out.println("Press a key to begin the race."); } private static void SusanMove() { String SusanFrontString=""; String SusanBackString=""; int SusanFront=50,SusanBack=0; int move = (int)((Math.random() * 5) + 1); SusanFront=SusanFront-move; SusanBack=SusanBack+move; for(int back = 0; back&lt;SusanBack;back++) { SusanBackString = SusanBackString+" "; } for(int front = 0; front&lt;SusanFront;front++) { SusanFrontString = SusanFrontString+" "; } String SusanRace = SusanBackString+"Susan"+SusanFrontString+"|"; System.out.println(SusanRace); } </code></pre> <p>I expected an output something like this:</p> <pre><code>Susan | James | Keith | Susan | James | Keith | Susan | James | Keith | </code></pre> <p>But instead I got:</p> <pre><code> Susan | James | Keith | Susan | James | Keith | Susan | James | Keith | Susan | James | Keith | </code></pre>
3
1,952
Babel config in a MERN app
<p>I have given up at trying to learn rails. I'm now focusing my energy on trying to get started with node, using the MERN stack. I have done both Stephen Grider and Andrew Mead's udemy course as well as all of the code school js courses. I'm afraid I'm not off to a promising start.</p> <p>I'm stuck at getting my import statements to work. So far, I have tried to import files. For that I need babel. My package.json has:</p> <pre><code>"scripts": { "test": "mocha test/**/*-test.js --compilers js:babel-core/register --recursive", "start": "nodemon -w server.js server.js --source-maps" }, "author": "Ol", "license": "MIT", "dependencies": { "axios": "^0.16.1", "babel-cli": "^6.24.1", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "babel-polyfill": "^6.13.0", "body-parser": "^1.17.1", "caniuse-api": "^2.0.0", "express": "^4.13.4", "lodash": "^4.17.4", "material-ui": "^0.18.0", "nodemon": "^1.11.0", "react": "^15.5.4", "react-dom": "^15.5.4", "react-promise": "^1.1.2", "react-redux": "^5.0.4", "react-router": "^4.1.1", "react-tap-event-plugin": "^2.0.1", "redux": "^3.6.0", "redux-devtools": "^3.4.0", "redux-form": "^6.7.0", "redux-thunk": "^2.2.0", "socket.io": "^2.0.1", "source-map-support": "^0.4.15" }, "devDependencies": { "babel": "^6.23.0", "babel-core": "^6.24.1", "babel-loader": "^7.0.0", "babelify": "^7.3.0", "enzyme": "^2.8.2", "mocha": "^3.3.0", "react-addons-test-utils": "^15.5.1", "webpack": "^2.5.1" } } </code></pre> <p>My .babelrc has:</p> <pre><code>{ "presets": ["react", "es2015"] } </code></pre> <p>My server.js has:</p> <pre><code>import express from 'express'; import bodyParser from 'body-parser'; import { MongoClient } from 'mongodb'; import 'babel-polyfill'; import SourceMapSupport from 'source-map-support'; SourceMapSupport.install(); //to get line numbers with file refs rather than compiled code line numbers // const app = express(); app.use(express.static('open')); app.use(bodyParser.json()); app.listen(3000, function(){ console.log('listening on 3000'); }); </code></pre> <p>My webpack.config.js has:</p> <pre><code>module :{ rules:[{ // use : 'babel-loader', loader: 'babel-loader', query :{ presets:['react','es2015'] // ,'es2017' }, test: /\.jsx?$/, exclude: /(node_modules|bower_components)/ }] </code></pre> <p>When I try to use npm start, I get an error with my import statements. It says:</p> <pre><code>{ import express from 'express'; ^^^^^^ SyntaxError: Unexpected token import at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10) at Module._compile (module.js:542:28) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:390:7) at startup (bootstrap_node.js:150:9) [nodemon] app crashed - waiting for file changes before starting... </code></pre> <p>Can anyone give me a clue on how to get babel setup to work with a node app. I noticed that even when I run npm install in my console, I don't get a node_modules folder in my app. I used yarn to add dependencies to package.json, but don't seem to have the ability to generate an node_modules folder.</p> <p><strong>Next attempt</strong></p> <p>I then tried npm init and then npm upgrade (even though I use yarn for adding modules).</p> <p>The output of npm upgrade is below, but I still don't end up with a node modules folder. I think the reason babel isn't working to recognise my import statements is because I don't have the module in my app. Does anyone know how to get a node modules file to be created in the setup? I thought that happened automatically.</p> <pre><code>npm update npm WARN deprecated isarray@2.0.1: Just use Array.isArray directly &gt; uws@0.14.5 install /Users/mlc/may/node_modules/uws &gt; node-gyp rebuild &gt; build_log.txt 2&gt;&amp;1 || exit 0 - ms@0.7.3 node_modules/engine.io-client/node_modules/ms - debug@2.6.4 node_modules/engine.io-client/node_modules/debug - ms@0.7.3 node_modules/finalhandler/node_modules/ms - react-addons-create-fragment@15.5.4 node_modules/react-addons-create-fragment - react-addons-transition-group@15.5.2 node_modules/react-addons-transition-group - ms@0.7.3 node_modules/socket.io-client/node_modules/ms - debug@2.6.4 node_modules/socket.io-client/node_modules/debug - camelcase@1.2.1 node_modules/uglify-js/node_modules/camelcase - cliui@2.1.0 node_modules/uglify-js/node_modules/cliui cr@1.0.0 /Users/mlc/may ├── axios@0.16.2 ├── body-parser@1.17.2 ├── express@4.15.3 ├── material-ui@0.18.2 ├── mocha@3.4.2 ├── react-promise@1.1.3 ├── react-redux@5.0.5 ├── socket.io@2.0.2 └── webpack@2.6.1 </code></pre>
3
2,129
Android Parcelable Unmarshalling prob
<p>I have two class named <code>AlacarteCategory</code> and <code>AlacartePack</code></p> <p><strong>Class AlacartePack</strong> </p> <pre><code>public class AlacartePack implements Parcelable { private int alacartePackId; private String alacartePackName; private double price; private String smsCode;// no need to pass private Boolean isSelected;// no need to pass private List&lt;Channel&gt; channelList;// no need to pass public AlacartePack(){ channelList = new ArrayList&lt;Channel&gt;(); isSelected = false; } //// getter &amp; setter @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int i) { dest.writeString(alacartePackName); dest.writeInt(alacartePackId); dest.writeDouble(price); } private AlacartePack(Parcel in){ this.alacartePackId = in.readInt(); this.alacartePackName = in.readString(); this.price = in.readDouble(); } public static final Parcelable.Creator&lt;AlacartePack&gt; CREATOR = new Parcelable.Creator&lt;AlacartePack&gt;() { @Override public AlacartePack createFromParcel(Parcel source) { return new AlacartePack(source); } @Override public AlacartePack[] newArray(int size) { return new AlacartePack[size]; } }; } </code></pre> <p><strong>Class AlacarteCategory</strong></p> <pre><code>public class AlacarteCategory implements Parcelable { private int categoryId; private String categoryName; private List&lt;AlacartePack&gt; alacartePackList; public int getCategoryId() { return categoryId; } public AlacarteCategory(){ alacartePackList = new ArrayList&lt;AlacartePack&gt;(); } public void setCategoryId(int categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public List&lt;AlacartePack&gt; getAlacartePackList() { return alacartePackList; } public void setAlacartePackList(List&lt;AlacartePack&gt; alacartePackList) { this.alacartePackList = alacartePackList; } public void addPack(AlacartePack mAlacartePack){ alacartePackList.add(mAlacartePack); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int i) { dest.writeString(categoryName); dest.writeInt(categoryId); dest.writeTypedList(alacartePackList); } private AlacarteCategory(Parcel in){ this.categoryId = in.readInt(); this.categoryName = in.readString(); this.alacartePackList = in.readArrayList(AlacartePack.class.getClassLoader()); //in.readTypedList(alacartePackList,AlacartePack.CREATOR); } public static final Parcelable.Creator&lt;AlacarteCategory&gt; CREATOR = new Parcelable.Creator&lt;AlacarteCategory&gt;() { @Override public AlacarteCategory createFromParcel(Parcel source) { return new AlacarteCategory(source); } @Override public AlacarteCategory[] newArray(int size) { return new AlacarteCategory[size]; } }; } </code></pre> <p>Now I want to pass a ArrayList of AlacarteCategory with my intent. It is giving Unmarshalling problem:</p> <pre><code>FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{Dishtv.Dynamic/dishtv.dynamic.RechargePaymentActivity}: java.lang.RuntimeException: Parcel android.os.Parcel@b5903448: Unmarshalling unknown type code 4980781 at offset 152 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) at android.app.ActivityThread.access$600(ActivityThread.java:123) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4424) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.RuntimeException: Parcel android.os.Parcel@b5903448: Unmarshalling unknown type code 4980781 at offset 152 at android.os.Parcel.readValue(Parcel.java:1921) at android.os.Parcel.readListInternal(Parcel.java:2103) at android.os.Parcel.readArrayList(Parcel.java:1544) at dishtv.dynamic.model.AlacarteCategory.&lt;init&gt;(AlacarteCategory.java:66) at dishtv.dynamic.model.AlacarteCategory.&lt;init&gt;(AlacarteCategory.java:12) at dishtv.dynamic.model.AlacarteCategory$1.createFromParcel(AlacarteCategory.java:74) at dishtv.dynamic.model.AlacarteCategory$1.createFromParcel(AlacarteCategory.java:70) at android.os.Parcel.readParcelable(Parcel.java:1992) at android.os.Parcel.readValue(Parcel.java:1854) at android.os.Parcel.readListInternal(Parcel.java:2103) at android.os.Parcel.readArrayList(Parcel.java:1544) at android.os.Parcel.readValue(Parcel.java:1875) at android.os.Parcel.readMapInternal(Parcel.java:2094) at android.os.Bundle.unparcel(Bundle.java:223) at android.os.Bundle.getString(Bundle.java:1048) at android.content.Intent.getStringExtra(Intent.java:3923) at dishtv.dynamic.RechargePaymentActivity.onCreate(RechargePaymentActivity.java:52) at android.app.Activity.performCreate(Activity.java:4465) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)             at android.app.ActivityThread.access$600(ActivityThread.java:123)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)             at android.os.Handler.dispatchMessage(Handler.java:99)             at android.os.Looper.loop(Looper.java:137)             at android.app.ActivityThread.main(ActivityThread.java:4424)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:511) </code></pre> <p>What is problem in my code?</p>
3
2,835
Python TCP Payload Duplication - Passing through data to multiple endpoints concurrently
<p>this is my first post here!</p> <p>My goal is to duplicate the payload of a unidirectional TCP stream and send this payload to multiple endpoints concurrently. I have a working prototype written in Python, however I am new to Python, and to Socket programming. Ideally the solution is capable of running in both Windows and *nix environments.</p> <p>This prototype works, however it creates a new send TCP connection for each Buffer length (currently set to 4096 bytes). The main problem with this is I will eventually run out of local ports to send from, and ideally I would like the data to pass from each single incoming TCP stream to one single TCP stream out (for each endpoint). The incoming data can vary from less than 1024 bytes to hundreds of megabytes.</p> <p>At the moment a new outgoing TCP stream is initiated for every 4096 bytes. I am not sure if the problem is in my implementation of threading, or if I have missed something else really obvious.</p> <p>In my research I have found that select() could help, however I am not sure if it would be appropriate because I may need to process some of the incoming data and respond to the sending client for certain cases in the future.</p> <p>Here is the code I have so far (some of the code variations I have tried are commented out):</p> <pre><code>#!/usr/bin/python #One way TCP payload duplication import sys import threading from socket import * bufsize = 4096 host= '' # Methods: #handles sending the data to the endpoints def send(endpoint,port,data): sendSocket = socket(AF_INET, SOCK_STREAM) #sendSocket.setblocking(1) sendSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) #sendport = sendSocket.getsockname #print sendport try: sendSocket.connect((endpoint, port)) sendSocket.sendall(data) except IOError as msg: print "Send Failed. Error Code: " + str(msg[0]) + ' Message: ' + msg[1] sys.exit() #handles threading for sending data to endpoints def forward(service, ENDPOINT_LIST, port, data): #for each endpoint in the endpoint list start a new send thread for endpoint in ENDPOINT_LIST: print "Forwarding data for %s from %s:%s to %s:%s" % (service,host,port,endpoint,port) #send(endpoint,port,data) ethread = threading.Thread(target=send, args=(endpoint,port,data)) ethread.start() #handles threading for incoming clients def clientthread(conn,service,ENDPOINT_LIST,port): while True: #receive data form client data = conn.recv(bufsize) if not data: break cthread = threading.Thread(target=forward, args=(service, ENDPOINT_LIST, port, data)) cthread.start() #no data? then close the connection conn.close() #handles listening to sockets for incoming connections def listen(service, ENDPOINT_LIST, port): #create the socket listenSocket = socket(AF_INET, SOCK_STREAM) #Allow reusing addresses - I think this is important to stop local ports getting eaten up by never-ending tcp streams that don't close listenSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) #try to bind the socket to host and port try: listenSocket.bind((host, port)) #display an error message if you can't except IOError as msg: print "Bind Failed. Error Code: " + str(msg[0]) + ' Message: ' + msg[1] sys.exit() #start listening on the socket listenSocket.listen(10) print "Service %s on port %s is listening" %(service,port) while True: #wait to accept a connection conn, addr = listenSocket.accept() print 'Connected to ' + addr[0] + ':' + str(addr[1]) + ' on port ' + str(port) #start new thread for each connection lthread = threading.Thread(target=clientthread , args=(conn,service,ENDPOINT_LIST,port)) lthread.start() #If no data close the connection listenSocket.close() service = "Dumb-one-way-tcp-service-name1" ENDPOINT_LIST = ["192.168.1.100","192.168.1.200"] port = 55551 listen(service,ENDPOINT_LIST,port) </code></pre> <p>I have looked into other libraries to try to achieve my goal, including using:</p> <ul> <li>Twisted </li> <li>Asyncore </li> <li>Scapy</li> </ul> <p>However I found them quite complicated for my modest needs and programming skill level.</p> <p>If anyone has any suggestions on how I could refine the approach I have, or any other ways this goal could be achieved, please let me know!</p>
3
1,515
Can not find new elements after javascript append using chrome webdriver
<p>Here's the simple HTML generated from a c# dotnet core asp pages, application. I'm trying to get the number of input boxes from colorList div using a webdriver test. The initial count of two works, but once i simulate the clicking the button labeled "+" i still only get two, where i expected to get three. I've tried all kinds of different waits both implicit and explicit, but can't seem to get it to work. </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Home page - SeleniumWebTest&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container body-content"&gt; &lt;body&gt; &lt;form method="post" id="Form" action="/?handler=saveall"&gt; &lt;div&gt;&lt;h4&gt;Colors&lt;/h4&gt;&lt;button type="button" onclick="CreateColor();" value="create" class="btn-sm"&gt;+&lt;/button&gt;&lt;/div&gt; &lt;div class="indent" id="colorlist"&gt; &lt;input value="Red" type="text" id="Colors" name="Colors" /&gt;&lt;br /&gt; &lt;input value="Blue" type="text" id="Colors" name="Colors" /&gt;&lt;br /&gt; &lt;/div&gt; &lt;br /&gt; &lt;div&gt; &lt;h1&gt;More Stuff&lt;/h1&gt; &lt;/div&gt; &lt;br /&gt; &lt;button type="submit" value="SaveAll" class="btn btn-primary"&gt;Save All&lt;/button&gt; &lt;input name="__RequestVerificationToken" type="hidden" value="CfDJ8Ps9gVily6NMr7L9g0lJf0cQzaqUzEq26TUrHCT4rH1GQIY0QLmjjc6cnQBE8aBvQlWdXAQZ2ub08pm2yIMWkUICO51XkWH6d11pf7y3pr3HwqRgBkiFdpaHSFYQsJsWdLba01RGCL8yYsUad9Vn2JQ" /&gt;&lt;/form&gt; &lt;/body&gt; &lt;script type="text/javascript"&gt; function CreateColor() { var form = document.getElementById("colorlist"); var input = document.createElement("input"); input.type = "text"; input.id = "ColorId"; input.name = "ColorName"; form.appendChild(input); linebreak = document.createElement("br"); form.appendChild(linebreak); }; &lt;/script&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here's my test</p> <pre><code> [Fact] public void ColorTest() { var _driver = new ChromeDriver(); _driver.Navigate().GoToUrl("https://localhost:44394/"); Assert.Equal("Home page - SeleniumWebTest", _driver.Title); var colorInputs = _driver.FindElements(By.Id("Colors")); Assert.Equal(2, colorInputs.Count); var plusButton = _driver.FindElement(By.XPath("//button[text()='+']")); plusButton.Click(); var colorInputs2 = _driver.FindElements(By.Id("Colors")); Assert.Equal(colorInputs.Count+1,colorInputs2.Count); // &lt;-- Fails _driver.Close(); _driver.Quit(); } </code></pre>
3
1,403
How can I design this layout in FLUTTER
<p>I am developing a clone of functionality where shopkeepers can enter their daily Cashoutgoings and cash incomings but I am having trouble designing the layout. Basically, I want to show different entries in their respective columns. Here is the code and the snapshots of my project</p> <pre><code>class CashInCashOut extends StatefulWidget { const CashInCashOut({Key? key}) : super(key: key); @override _CashInCashOutState createState() =&gt; _CashInCashOutState(); } class _CashInCashOutState extends State&lt;CashInCashOut&gt; { final _firestore = FirebaseFirestore.instance; DateTime date = DateTime.now(); late var formattedDate = DateFormat('d-MMM-yy').format(date); late String amountCashout; late String detailCashOut; late String dateCashOut; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(&quot;Cash Out&quot;), ), body: Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ TextField( onChanged: (value) { amountCashout = value; }, keyboardType: TextInputType.phone, decoration: InputDecoration(labelText: &quot;Amount&quot;), ), TextField( onChanged: (value) { detailCashOut = value; }, decoration: InputDecoration(labelText: &quot;Detail (optional)&quot;), ), const SizedBox( height: 28.0, ), Row( children: [ ElevatedButton.icon( label: Text(formattedDate), icon: const Icon(Icons.date_range_outlined), onPressed: () async { DateTime? _newDate = await showDatePicker( context: context, initialDate: date, firstDate: DateTime(2022), lastDate: DateTime(2030), ); setState(() { if (_newDate == null) { return; } else { formattedDate = DateFormat('d-MMM-yy').format(_newDate); } }); }, ), const Spacer(), // ReusableButton(text: &quot;Add bills&quot;), ], ), const Spacer(), ReusableButton( text: 'Save', onpress: () =&gt; _firestore.collection('cashOut').add( { 'amount': amountCashout, 'optionalDetail': detailCashOut, 'datereceived': formattedDate }, ), ), ], ), ), ); } } class CaShBookRegister extends StatefulWidget { const CaShBookRegister({Key? key}) : super(key: key); @override _CaShBookRegisterState createState() =&gt; _CaShBookRegisterState(); } class _CaShBookRegisterState extends State&lt;CaShBookRegister&gt; { final _firestore = FirebaseFirestore.instance; void streamFromFirebase() async { await for (var snapshot in _firestore.collection('cashOut').snapshots()) { for (var receivedStream in snapshot.docs) { print(receivedStream.data()); } } } DateTime date = DateTime.now(); late var formattedDate = DateFormat('d-MMM-yy').format(date); @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.symmetric(vertical: 18.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ const SizedBox( height: 16.0, ), Padding( padding: const EdgeInsets.all(14.0), child: Row( children: [ Expanded( child: ReuseableCard( textcolour: Colors.white, buttonColour: Colors.green, text: &quot;Cash in hand&quot;, ), ), const SizedBox( width: 8.0, ), Expanded( child: ReuseableCard( buttonColour: Colors.red, textcolour: Colors.white, text: &quot;Today's balance&quot;, ), ), ], ), ), Padding( padding: const EdgeInsets.all(14.0), child: Row( children: [ Column( children: [ Text(formattedDate), ], ), const Spacer(), const Text('Cash in'), const Spacer(), const Text('Cash out'), ], ), ), const Divider( thickness: 1, ), const Spacer(), Padding( padding: const EdgeInsets.all(14.0), child: Row( children: [ Expanded( child: ReusableButton( onpress: streamFromFirebase, text: &quot;Cash out&quot;, )), const SizedBox( width: 8.0, ), Expanded( child: ReusableButton( text: &quot;Cash in&quot;, ), ), ], ), ), ], ), ), ); } } </code></pre> <p>I am using cloud fire store for storing my data and then retrieving it using STREAM Builder, but not being able to figure out how to display the respective entries in their respective columns. The first two snapshots are of my project and the third one is the functionality i want to acheive</p> <p>Snap shot of my project</p> <p><a href="https://i.stack.imgur.com/aK3pg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aK3pg.jpg" alt="Snap shot of my project" /></a></p> <p><a href="https://i.stack.imgur.com/2YkiE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2YkiE.jpg" alt="Snap shot of my project" /></a></p> <p>Snapshot of functionality I want to achieve</p> <p><a href="https://i.stack.imgur.com/31joB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/31joB.jpg" alt="Snapshot of functionality I want to achieve" /></a></p>
3
3,667
verbose stack Error: ENOENT: no such file or directory, open
<p>I am trying to run the local server using <code>npm start</code> for my React app that I am working on. Which worked fine yesterday. But when I try to run it today I get the following error message see below. I tried some solution son internet, like reinstalling <code>npm install</code>, deleting <code>package-lock.json</code> file and <code>package.json</code>, recreating those files, installing missing modules <code>npm-install-missing</code> but no luck. Please help :)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> 0 info it worked if it ends with ok 1 verbose cli [ '/Applications/anaconda3/bin/node', 1 verbose cli '/Applications/anaconda3/bin/npm', 1 verbose cli 'start' ] 2 info using npm@6.14.8 3 info using node@v11.14.0 4 verbose run-script [ 'prestart', 'start', 'poststart' ] 5 info lifecycle amazon-clone@0.1.0~prestart: amazon-clone@0.1.0 6 info lifecycle amazon-clone@0.1.0~start: amazon-clone@0.1.0 7 verbose lifecycle amazon-clone@0.1.0~start: unsafe-perm in lifecycle true 8 verbose lifecycle amazon-clone@0.1.0~start: PATH: /Applications/anaconda3/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/joseftichanek/Desktop/React_Amazon/node_modules/.bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/anaconda3/bin:/Applications/anaconda3/condabin:/Library/Frameworks/Python.framework/Versions/3.7/bin 9 verbose lifecycle amazon-clone@0.1.0~start: CWD: /Users/josef/Desktop/React_Amazon 10 silly lifecycle amazon-clone@0.1.0~start: Args: [ '-c', 'react-scripts start' ] 11 silly lifecycle amazon-clone@0.1.0~start: Returned: code: 1 signal: null 12 info lifecycle amazon-clone@0.1.0~start: Failed to exec start script 13 verbose stack Error: amazon-clone@0.1.0 start: `react-scripts start` 13 verbose stack Exit status 1 13 verbose stack at EventEmitter.&lt;anonymous&gt; (/Applications/anaconda3/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16) 13 verbose stack at EventEmitter.emit (events.js:193:13) 13 verbose stack at ChildProcess.&lt;anonymous&gt; (/Applications/anaconda3/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14) 13 verbose stack at ChildProcess.emit (events.js:193:13) 13 verbose stack at maybeClose (internal/child_process.js:999:16) 13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:266:5) 14 verbose pkgid amazon-clone@0.1.0 15 verbose cwd /Users/josef/Desktop/React_Amazon 16 verbose Darwin 19.6.0 17 verbose argv "/Applications/anaconda3/bin/node" "/Applications/anaconda3/bin/npm" "start" 18 verbose node v11.14.0 19 verbose npm v6.14.8 20 error code ELIFECYCLE 21 error errno 1 22 error amazon-clone@0.1.0 start: `react-scripts start` 22 error Exit status 1 23 error Failed at the amazon-clone@0.1.0 start script. 23 error This is probably not a problem with npm. There is likely additional logging output above. 24 verbose exit [ 1, true ]</code></pre> </div> </div> </p>
3
1,132
Intentional friend class redifinition and -fstack-protector
<p>I have been trying testing if multiple definition of a friend class in different <code>.cpp</code> files would work. To do that I defined a main class inside <code>main_class.hpp</code> file:</p> <pre><code>class main_class { private: int a; int b; int gimme_a() { return a; } public: main_class(int a, int b) : a(a), b(b) {} int gimme_b() { return b; } friend class main_class_friend; }; </code></pre> <p>Then I defined <code>main_class_friend</code> two times, firstly within <code>main_friend_class1.cpp</code> file:</p> <pre><code>class main_class_friend { main_class c; public: main_class_friend() : c(10, 10) {} int gimme_a() { return c.gimme_a(); } int gimme_b() { return c.gimme_b(); } }; </code></pre> <p>and a corresponding public test function:</p> <pre><code>void test1() { main_class_friend ff; std::cout &lt;&lt; "Gimme a: " &lt;&lt; ff.gimme_a() &lt;&lt; " and gimme b: " &lt;&lt; ff.gimme_b() &lt;&lt; std::endl; } </code></pre> <p>and then I defined the second <code>main_class_friend</code> within <code>main_friend_class2.cpp</code> and a corresponding public test function:</p> <pre><code>class main_class_friend { private: main_class ca; int c; public: main_class_friend() : ca(9 ,9), c(11) {} int gimme_a() { return ca.gimme_a(); } int gimme_b() { return ca.gimme_b(); } int gimme_c() { return c; } }; void test2() { main_class_friend ff; std::cout &lt;&lt; "Gimme a: " &lt;&lt; ff.gimme_a() &lt;&lt; " and gimme b: " &lt;&lt; ff.gimme_b() &lt;&lt; " and gimme c: " &lt;&lt; ff.gimme_c() &lt;&lt; std::endl; } </code></pre> <p>Finally I called <code>test1</code> and <code>test2</code> function inside main:</p> <pre><code>int main() { test1(); test2(); return 0; } </code></pre> <p>compiled the program (no errors from <code>g++</code>), and run it. The output was:</p> <pre><code>Gimme a: 9 and gimme b: 9 *** stack smashing detected ***: ./a.out terminated Aborted (core dumped) </code></pre> <p>What's really weird for me is that <code>a</code> and <code>b</code> were initialized by the constructor inside <code>main_friend_class2.cpp</code> and not the one from <code>main_friend_class1.cpp</code> where <code>test1</code> function is defined.</p> <p>Then I found that stack smashing can be easily debugged when a program is compiled with <code>-fstack-protector</code> flag. So I compiled it once again and the output from the program was then:</p> <pre><code>Gimme a: 9 and gimme b: 9 Gimme a: 9 and gimme b: 9 and gimme c: 11 </code></pre> <p>so no more stack smashing problems, but both <code>test1</code> and <code>test2</code> functions use constructor from <code>main_friend_class2.cpp</code> file. </p> <p>What's going on around here? I don't get it. Why there is a stack smashing error if there is no buffer overflow, because there isn't any buffer used?</p> <p>My second question is: is there a way to define multiple times <code>main_class_friend</code>, but to use them in different files to make them "private" for the file inside which the class is used?</p>
3
1,351
sqlite not saving french accents like à as $agrave
<p>When i will save into my database "C&#39;est tout &agrave; fait juste.", sqlite will remove the &amp; from &amp;agrave, becouse it can't maybe handle utf-8.</p> <p>var sql += "INSERT INTO Test(TestId,Text) Values(1, "C&#39;est tout &agrave; fait juste.");</p> <p>I tried for every insert to replace the $agrave with à, but I think there will be a better solution.</p> <p>Is there a better way to solve this?</p> <p>Thanks for any help...</p> <p><strong>UPDATE</strong></p> <p>This is my code to create my sqlite database:</p> <pre><code> function initDb($cordovaSQLite, logService) { var defcorrect = $.Deferred(); try { logger = logService; db = window.sqlitePlugin.openDatabase({ name: "xxx.db", location: 0 }, successCB, errorCB); $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS Card(CardId UNIQUEIDENTIFIER PRIMARY KEY, CardSetId UNIQUEIDENTIFIER NOT NULL, FrontText NVARCHAR(4000) NOT NULL, BackText NVARCHAR(4000) NULL, ControlType INT NOT NULL, CardLevel INT NOT NULL, IsDirty bit NOT NULL, ChangedAt INT NOT NULL, Active bit default 'true')").catch(function (err) { logService.writeAppError("00000000-0000-0000-0000-000000000000", "Could not init Table Card: ErrorNo: " + startGUIDLog + " ErrorMessage: " + err.message); window.location = "#/error/" + startGUIDLog; }); $cordovaSQLite.execute(db, "CREATE UNIQUE INDEX IF NOT EXISTS Card_Index on Card (CardId)").catch(function (err) { logService.writeAppError("00000000-0000-0000-0000-000000000000", "Could not init INDEX Card_Index on Card: ErrorNo: " + startGUIDLog + " ErrorMessage: " + err.message); window.location = "#/error/" + startGUIDLog; }); defcorrect.resolve(db); } catch (err) { logService.writeAppError("00000000-0000-0000-0000-000000000000", "Could not init Database: ErrorNo: " + startGUIDLog + " ErrorMessage: " + err.message); window.location = "#/error/" + startGUIDLog; } return defcorrect.promise(); } </code></pre> <p>And with this code I insert the data</p> <pre><code> function saveCard(cardList, userId, db) { var defcorrect = $.Deferred(); truncateTable("Card", db, userId).done(function () { if (cardList.length !== 0) { var sql = ""; cardList.forEach(function (card) { sql += "INSERT INTO Card(CardId,CardSetId,FrontText,BackText,ControlType,CardLevel,IsDirty,ChangedAt,Active) VALUES (" + JSON.stringify(card.CardId) + "," + JSON.stringify(card.CardSetId) + "," + JSON.stringify(Card.FrontText) + "," + JSON.stringify(Card.BackText) + "," + card.ControlType + ", " + card.CardLevel + ",'" + card.IsDirty + "'," + card.ChangedAt + ",'" + card.Active + "');"; }); var successFn = function (count) { logService.writeAppInfo(userId, "Sync Save Card Successfully imported " + count + " SQL statements to DB"); defcorrect.resolve(); }; var errorFn = function (error) { logService.writeAppError(userId, "Sync Save Card Error: " + error); $('#statusOverview').hide(); $('#syncError').show(); }; var progressFn = function (current, total) { $("#statusText").text("Importiere " + current + "/" + total + " Karten"); }; cordova.plugins.sqlitePorter.importSqlToDb(db, sql, { successFn: successFn, errorFn: errorFn, progressFn: progressFn, batchInsertSize: 500 }); } else { defcorrect.resolve(); } }); return defcorrect.promise(); } </code></pre> <p>In the debug mode I can see, that the data comes in the right way like "C&#39;est tout &agrave; fait juste." and after insert when i read out this data it comes like this: "C&#39;est toutagrave; fait juste."</p>
3
1,766
How to display sqlite database in the form of cards in android?
<p>This is my code how i store the data in sqlite database.Now i want that all the data from the database display in the form of cards in other activity suppose when i press showdb button then the data displayed.</p> <pre><code>public class ConfigureNode extends AppCompatActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static final String TAG = "LocationActivity"; private static final long INTERVAL = 1000 * 10; private static final long FASTEST_INTERVAL = 1000 * 5; private SQLiteDatabase db; Button btnFusedLocation, btnPushData; TextView tvLocation; EditText Latval, LongVal,NodeId; LocationRequest mLocationRequest; GoogleApiClient mGoogleApiClient; Location mCurrentLocation; String mLastUpdateTime; public String DBPath; public static String DBName = "sample"; public static final int version = '1'; public static Context currentContext; protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(INTERVAL); mLocationRequest.setFastestInterval(FASTEST_INTERVAL); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); createDatabase(); Log.d(TAG, "onCreate ..............................."); //show error dialog if GoolglePlayServices not available if (!isGooglePlayServicesAvailable()) { finish(); } createLocationRequest(); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); setContentView(R.layout.activity_configure_node); tvLocation = (TextView) findViewById(R.id.tvLocation); btnFusedLocation = (Button) findViewById(R.id.btnShowLocation); Latval = (EditText) findViewById(R.id.latVal); LongVal = (EditText) findViewById(R.id.longVal); NodeId=(EditText)findViewById(R.id.NodeId); btnPushData = (Button) findViewById(R.id.btnPushLoc); btnPushData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { insertIntoDB(); } }); btnFusedLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateUI(); } }); } @Override public void onStart() { super.onStart(); Log.d(TAG, "onStart fired .............."); mGoogleApiClient.connect(); } @Override public void onStop() { super.onStop(); Log.d(TAG, "onStop fired .............."); mGoogleApiClient.disconnect(); Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected()); } private boolean isGooglePlayServicesAvailable() { int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (ConnectionResult.SUCCESS == status) { return true; } else { GooglePlayServicesUtil.getErrorDialog(status, this, 0).show(); return false; } } @Override public void onConnected(Bundle bundle) { Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected()); startLocationUpdates(); } protected void startLocationUpdates() { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp; ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } PendingResult&lt;Status&gt; pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this); Log.d(TAG, "Location update started ..............: "); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { Log.d(TAG, "Connection failed: " + connectionResult.toString()); } @Override public void onLocationChanged(Location location) { Log.d(TAG, "Firing onLocationChanged.............................................."); mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateUI(); } private void updateUI() { Log.d(TAG, "UI update initiated ............."); if (null != mCurrentLocation) { String lat = String.valueOf(mCurrentLocation.getLatitude()); String lng = String.valueOf(mCurrentLocation.getLongitude()); tvLocation.setText("At Time: " + mLastUpdateTime + "\n" + "Latitude: " + lat + "\n" + "Longitude: " + lng + "\n" + "Accuracy: " + mCurrentLocation.getAccuracy() + "\n" + "Provider: " + mCurrentLocation.getProvider()); LongVal.setText(lng); Latval.setText(lat); } else { Toast.makeText(ConfigureNode.this,"location not detected ",Toast.LENGTH_SHORT).show(); } } @Override protected void onPause() { super.onPause(); stopLocationUpdates(); } protected void stopLocationUpdates() { LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, (LocationListener) this); Log.d(TAG, "Location update stopped ......................."); } @Override public void onResume() { super.onResume(); if (mGoogleApiClient.isConnected()) { startLocationUpdates(); Log.d(TAG, "Location update resumed ....................."); } } protected void createDatabase(){ db=openOrCreateDatabase("PersonDB", Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS persons(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR,address VARCHAR,NodeId VARCHAR);"); } protected void insertIntoDB(){ String name = Latval.getText().toString().trim(); String add = LongVal.getText().toString().trim(); String Nodid=NodeId.getText().toString().trim(); if(name.equals("") || add.equals("")||Nodid.equals("")){ Toast.makeText(getApplicationContext(),"Please fill all fields", Toast.LENGTH_LONG).show(); return; } String query = "INSERT INTO persons (name,address,NodeId) VALUES('"+name+"', '"+add+"', '"+Nodid+"');"; db.execSQL(query); Toast.makeText(getApplicationContext(),"Saved Successfully", Toast.LENGTH_LONG).show(); } } </code></pre>
3
3,101
OrientationSensor / Inclinometer weird, undocumented sensor reading jump when facing horizon
<p>I'm trying to upgrade an app of mine to use Windows 10 Mobile device sensors as a VR device for the pc (like Google Cardboard). I'm experiencing a problem with the sensor readouts when the device changes from pointing below the horizon to above the horizon (happens for both landscape and portrait, however in this case only landscape is important). A small sketch: <a href="https://i.stack.imgur.com/V2MUg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V2MUg.png" alt="Switch over point causing major sensor reading change"></a></p> <p>Raw sensor readouts (pointing downward):</p> <p>Inclinometer Pitch: -000.677 , Roll: -055.380 , Yaw: +013.978</p> <p>Now after changing to pointing upward:</p> <p>Inclinometer Pitch: -178.550 , Roll: +083.841 , Yaw: +206.219</p> <p>As you can see, all 3 values changed, by a significant amount. In reality only one axis should have changed, roll or pitch (depending on sensor orientation)</p> <p>I'm 95% sure, this problem didn't exist in Windows Phone 8. I'm unable to find any documentation about this weird behaviour of the sensors and it's stopping me from creating Augmented Reality and Virtual Reality apps.</p> <p>Here are 2 pictures of the problem: <a href="https://i.stack.imgur.com/Sv9ah.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sv9ah.jpg" alt="Pointing downward"></a> <a href="https://i.stack.imgur.com/45HGG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/45HGG.jpg" alt="Pointing upward"></a></p> <p>Here is the code for this demonstration:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"&gt; &lt;TextBlock Style="{StaticResource BodyTextBlockStyle}" x:Name="output" FontFamily="Consolas" Foreground="Black" Text="test"/&gt; &lt;/Grid&gt; </code></pre> <p>Code behind:</p> <pre class="lang-cs prettyprint-override"><code>public MainPage() { this.InitializeComponent(); timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(250); timer.Tick += Timer_Tick; } private void Timer_Tick(object sender, object e) { output.Text = ""; output.Text = DateTime.Now.ToString("HH:mm:ss.fff") + Environment.NewLine; Print(); } DispatcherTimer timer; public void WriteValue(String desc, String val) { StringBuilder b = new StringBuilder(); int length = desc.Length + val.Length; int topad = 40 - length; if (topad &lt; 0) topad = length - 40; output.Text += desc + val.PadLeft(topad + val.Length) + Environment.NewLine; } public String ValueToString(double value) { String ret = value.ToString("000.00000"); if (value &gt; 0) ret = " +" + ret; else if (value == 0) ret = " " + ret; else ret = " " + ret; return ret; } public static double RadianToDegree(double radians) { return radians * (180 / Math.PI); } public void Print() { WriteValue("DisplayOrientation", LastDisplayOrient.ToString()); WriteValue("Inclinometer", ""); WriteValue("Pitch", ValueToString(LastIncline.PitchDegrees)); WriteValue("Roll", ValueToString(LastIncline.RollDegrees)); WriteValue("Yaw", ValueToString(LastIncline.YawDegrees)); WriteValue("YawAccuracy", LastIncline.YawAccuracy.ToString()); WriteValue("OrientationSensor", ""); var q = LastOrient.Quaternion; double ysqr = q.Y * q.Y; // roll (x-axis rotation) double t0 = +2.0f * (q.W * q.X + q.Y * q.Z); double t1 = +1.0f - 2.0f * (q.X * q.X + ysqr); double Roll = RadianToDegree(Math.Atan2(t0, t1)); // pitch (y-axis rotation) double t2 = +2.0f * (q.W * q.Y - q.Z * q.X); t2 = t2 &gt; 1.0f ? 1.0f : t2; t2 = t2 &lt; -1.0f ? -1.0f : t2; double Pitch = RadianToDegree(Math.Asin(t2)); // yaw (z-axis rotation) double t3 = +2.0f * (q.W * q.Z + q.X * q.Y); double t4 = +1.0f - 2.0f * (ysqr + q.Z * q.Z); double Yaw = RadianToDegree(Math.Atan2(t3, t4)); WriteValue("Roll", ValueToString(Roll)); WriteValue("Pitch", ValueToString(Pitch)); WriteValue("Yaw", ValueToString(Yaw)); } Inclinometer sIncline; DisplayInformation sDisplay; OrientationSensor sOrient; protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); sIncline = Inclinometer.GetDefault(SensorReadingType.Absolute); sDisplay = DisplayInformation.GetForCurrentView(); sOrient = OrientationSensor.GetDefault(SensorReadingType.Absolute); sOrient.ReadingChanged += SOrient_ReadingChanged; sDisplay.OrientationChanged += SDisplay_OrientationChanged; sIncline.ReadingChanged += SIncline_ReadingChanged; LastDisplayOrient = sDisplay.CurrentOrientation; LastIncline = sIncline.GetCurrentReading(); LastOrient = sOrient.GetCurrentReading(); timer.Start(); } private void SOrient_ReadingChanged(OrientationSensor sender, OrientationSensorReadingChangedEventArgs args) { LastOrient = args.Reading; } private void SDisplay_OrientationChanged(DisplayInformation sender, object args) { LastDisplayOrient = sDisplay.CurrentOrientation; } OrientationSensorReading LastOrient; InclinometerReading LastIncline; DisplayOrientations LastDisplayOrient; private void SIncline_ReadingChanged(Inclinometer sender, InclinometerReadingChangedEventArgs args) { LastIncline = args.Reading; } protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { base.OnNavigatingFrom(e); sIncline.ReadingChanged -= SIncline_ReadingChanged; sDisplay.OrientationChanged -= SDisplay_OrientationChanged; sOrient.ReadingChanged -= SOrient_ReadingChanged; timer.Stop(); } </code></pre> <p><strong>edit: Added the following sketch and more description</strong></p> <p>Take a look at this following, more in depth sketch: <a href="https://i.stack.imgur.com/mJvTy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mJvTy.png" alt="More indepth sketch"></a></p> <p>Position the phone as seen in step (1). Phone in landscape mode, camera facing slightly downward, screen facing slightly upward.</p> <p>Change to step (2). You slightly tilt it forward, only one axis should change (in this case Inclinometer will show you only "Roll" changing. <strong>THIS IS CORRECT</strong>)</p> <p>Change to step (3). You now tilt your phone back. As soon as the switch over point comes, where the camera is no longer facing the ground, but now the sky and the screen is now facing slightly downward, all 3 values change by a significant amount. Pitch will jump by about -180°, Roll will jump by about 90° additionally to the amount you actually changed, and Yaw will jump by about +180°. </p> <p><strong>As long as the camera is ONLY pointing to EITHER the earth or the sky, the sensors behave fine! ONLY when switch from one to the other does this problem occur! (This scenario happens all the time with VR and AR, so this is a big problem)</strong></p>
3
2,492
Hibernate list mapping constraint violation
<p>These are my postresql tables :</p> <pre><code>CREATE TABLE "user" ( "id" int4 NOT NULL, "activated" bool NOT NULL DEFAULT True, CONSTRAINT "user_pkey" PRIMARY KEY("id") ); CREATE TABLE "user_data" ( "id" int4 NOT NULL, "user_id" int4 NOT NULL, "idx" int4 DEFAULT NULL, "first_name" text NOT NULL, "last_name" text NOT NULL, CONSTRAINT "user_data_pkey" PRIMARY KEY("id") ); </code></pre> <p>My goal is to have in my "User" hibernate bean a direct reference to user's data, like this <code>List&lt;UserData&gt;</code>. Here is my hibernate mapping :</p> <pre><code>&lt;hibernate-mapping package="mypackage"&gt; &lt;class name="User" table="user"&gt; &lt;id name="id" type="long" column="id"&gt; &lt;generator class="sequence"&gt; &lt;param name="sequence"&gt;user_id_seq&lt;/param&gt; &lt;/generator&gt; &lt;/id&gt; &lt;property name="activated" column="activated" type="boolean" /&gt; &lt;list name="data" table="user_data" cascade="all"&gt; &lt;key column="user_id" /&gt; &lt;list-index column="idx" /&gt; &lt;one-to-many class="UserData" /&gt; &lt;/list&gt; &lt;/class&gt; &lt;class name="UserData" table="user_data"&gt; &lt;id name="id" type="long" column="id"&gt; &lt;generator class="sequence"&gt; &lt;param name="sequence"&gt;user_data&lt;/param&gt; &lt;/generator&gt; &lt;/id&gt; &lt;many-to-one name="user" column="user_id" class="User" /&gt; &lt;property name="firstName" column="first_name" type="text" /&gt; &lt;property name="lastName" column="last_name" type="text" /&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>I ran some tests. When I add a new "UserData" to my list and then execute <code>session.saveOrUpdate(myUser)</code> it works, but when I remove an entry from my list and execute the same line, it throws <code>ERROR [JDBCExceptionReporter] ERROR: null value in column "user_id" violates not-null constraint</code> just after telling me that <code>batch update user_data set user_id=null, idx=null where user_id='20' and id='46' was canceled</code></p> <p>What is the right usage of this type of mapping? Thank you</p> <p><strong>EDIT:</strong> Adding "inverse=true" isn't adapted to my usage because I need my update on user trigger an update on UserData. Again, maybe I didn't understand the right usage of this type of usage.</p>
3
1,118
CSS Hover and Display Inline Block not working properly
<p>Problem is when I hover, the overlay affects all the items, i would like it to do one at a time, not all at once and also I can't get the display to show Inline-Block, items seem to be taking up the whole row, once it's fixe i know i will have to adjust the figcaption because ideally that would need to be centered under each image... anything helps. THanks!</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const productData = document.querySelector('.wrap'); const productsOne = [{ Name: "Almonds", id: 1, src: "https://happywellbox.com/wp-content/uploads/2022/04/HAPPY-hellbox-01.png", href: "https://happywellbox.com/wp-content/uploads/2022/04/HAPPY-hellbox-01.png" }, { Name: "Kit Kat", id: 2, src: "https://happywellbox.com/wp-content/uploads/2022/04/HAPPY-hellbox-01.png", href: "https://happywellbox.com/wp-content/uploads/2022/04/HAPPY-hellbox-01.png" }, { Name: "PopCorn", id: 3, src: "https://happywellbox.com/wp-content/uploads/2022/04/HAPPY-hellbox-01.png", href: "https://happywellbox.com/wp-content/uploads/2022/04/HAPPY-hellbox-01.png" }, { Name: "Peanuts", id: 4, src: "https://happywellbox.com/wp-content/uploads/2022/04/HAPPY-hellbox-01.png", href: "https://happywellbox.com/wp-content/uploads/2022/04/HAPPY-hellbox-01.png" }, { Name: "Oreos", id: 5, src: "https://happywellbox.com/wp-content/uploads/2022/04/HAPPY-hellbox-01.png", href: "https://happywellbox.com/wp-content/uploads/2022/04/HAPPY-hellbox-01.png" }, ] document.getElementById('productspage1').innerHTML = productsOne.map(products =&gt; ` &lt;div id="${products.id}"&gt; &lt;a href="${products.href}"&gt; &lt;img src="${products.src}" width="260" height="195"&gt; &lt;div class="text"&gt;${products.Name}&lt;/div&gt; &lt;/a&gt; &lt;br&gt; &lt;center&gt; &lt;figcaption&gt; &lt;center&gt; &lt;label class="switch"&gt; &lt;input type="checkbox"name="${products.id}"class="single-checkbox"&gt; &lt;span class="slider round"&gt; &lt;/span&gt; &lt;/label&gt; &lt;/center&gt; &lt;/figcaption&gt; &lt;/center&gt; &lt;/div&gt; ` ).join('&lt;br&gt;&lt;br&gt;')</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>figcaption { left: 200%; } .wrap *{ display: inline-block; max-height: 195px; max-width: 260px; position: relative; background: #fff; } .text { background: rgba(0,0,0,0.8); color: #fff; transition: opacity .5s; opacity: 0; position: absolute; top: 0em; bottom: 0em; left: 0em; right: 0em; display: flex; justify-content: center; align-items: center; } .wrap div:hover .text { opacity: 1; } img { max-width: 100%; display: inline-block; } /* The switch - the box around the slider */ .switch { position: relative; display: inline-block; width: 50px; height: 24px; } /* Hide default HTML checkbox */ .switch input { opacity: 0; width: 0; height: 0; } /* The slider */ .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 17px; width: 17px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #49ba14; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;div class="wrap"&gt; &lt;div id="productspage1"&gt; &lt;/div&gt;&lt;/div&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
3
1,771
React - Input fields not editable even after I set the state
<p>I am trying to type on the inputs but it is not allowing me too. My state changes but it doesn't show. I am using props to show an event OR and empty event if there is no props (no event selected). </p> <p>Im sorry but Stack is telling me to add more details but I don't know what else to add, I already described my problem</p> <pre><code>class EventForm extends PureComponent { state = { event: this.props.selectedEvt, query: "" }; onFormSubmit = e =&gt; { e.preventDefault(); this.props.addEvent(this.state.event); }; onInputChange = evt =&gt; { console.log(evt); evt.persist(); let newEvt = this.state.event; newEvt[evt.target.name] = evt.target.value; this.setState({ event: newEvt }); }; componentDidUpdate(prevProps) { this.props.selectedEvt &amp;&amp; this.setState({ event: this.props.selectedEvt }); } render() { const { event } = this.state; return ( &lt;form className="card" onSubmit={this.onFormSubmit}&gt; &lt;div className="form-row card-body"&gt; &lt;div className="form-group col-md-12"&gt; &lt;label hmtlfor="inputName"&gt;Event Name&lt;/label&gt; &lt;input name="title" type="text" className="form-control" id="inputEventName" onChange={this.onInputChange} value={event.title} /&gt; &lt;label hmtlfor="inputDate"&gt;Event Date&lt;/label&gt; &lt;input name="date" type="date" className="form-control" id="inputEventDate" onChange={this.onInputChange} value={event.date} /&gt; &lt;label hmtlfor="inputDate"&gt;Event Time&lt;/label&gt; &lt;input name="time" type="time" className="form-control" id="inputEventTime" onChange={this.onInputChange} value={event.time} /&gt; &lt;label hmtlfor="inputAddress"&gt;Address&lt;/label&gt; &lt;input name="address" type="text" className="form-control" id="autocomplete" onChange={this.onInputChange} value={event.address} autoComplete="new-password" /&gt; &lt;label hmtlfor="inputHost"&gt;Hosted By&lt;/label&gt; &lt;input name="host" type="text" className="form-control" id="inputHost" onChange={this.onInputChange} value={event.host} /&gt; &lt;label hmtlfor="inputDesc"&gt;Description&lt;/label&gt; &lt;textarea name="desc" className="form-control" rows="5" id="inputDesc" wrap="soft" onChange={this.onInputChange} value={event.description} /&gt; &lt;button type="submit" className="btn btn-primary mt-2"&gt; Submit &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; ); } } export default EventForm; </code></pre>
3
1,679
unreachable code after return stmt
<p>I have the below sample code and I get - "Unreachable code after return stmt"..</p> <pre><code>removed https:// from first and second line </code></pre> <p>HTML</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="fb.me/react-0.13.3.min.js"&gt;&lt;/script&gt; &lt;script src=":cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.29/browser.js"&gt;&lt;/script&gt; &lt;!-- Latest compiled and minified CSS --&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"&gt; &lt;!-- Optional theme --&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous"&gt; &lt;!-- Latest compiled and minified JavaScript --&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;title&gt;React Components&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="react-container"&gt;&lt;/div&gt; &lt;script type="text/babel" src="./createpanel.js"&gt; &lt;script type="text/babel" src="./filterpanel.js"&gt; &lt;script type="text/babel" src="./myscript.js"&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>createpanel.js</p> <pre><code>var CreatePanel = React.createClass({ render: function(){ return &lt;div className="row"&gt; &lt;div className = "col-xs-6 col-sm-3"&gt; &lt;input type="text"&gt;&lt;/input&gt; &lt;select&gt;&lt;/select&gt; &lt;/div&gt; &lt;/div&gt;; } }); </code></pre> <p>myscript.js</p> <pre><code>React.render(&lt;div class="container"&gt; &lt;CreatePanel/&gt; &lt;FilterPanel/&gt; &lt;/div&gt; , document.getElementById('react-container')); </code></pre> <p>filterpanel.js</p> <pre><code>var FilterPanel = React.createClass({ render: function(){ return &lt;div className="row"&gt;Filter Panel&lt;/div&gt;; } }); </code></pre>
3
1,147
Cannot make TextView's change color while user types
<p>I'm very very new to android dev, but I really enjoy it :) I am wanting to make a calculator app for a game I play to work out how long it'll take to get from level a to level b using the various methods. I'm doing pretty good with it so far, but now have encountered this error which is reallllly bugging me.<br> I want to turn my text color to red if they input a number thats lower than the required experience to use ingame. For example, mahogany logs require 400000xp to be able to use, so if they enter &lt;400000 I want the TextView with mahogany logs to turn red. Hope I made sense haha :) currently when i enter any number they all just change red and dont change with user input :(any help would be appreciated! :) Here is a screenshot of the app interface so you can see what I mean <a href="https://puu.sh/xdRfZ/a4651025d0.png" rel="nofollow noreferrer">https://puu.sh/xdRfZ/a4651025d0.png</a></p> <pre><code>numspace1.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { Double numb1 = Double.parseDouble(numspace1.getText().toString()); if (numb1 &gt;= 6517253 &amp;&amp; numb1 &lt;= 10692628) { p15.setTextColor(Color.RED); } else if (numb1 &gt;= 5346332 &amp;&amp; numb1 &lt;= 6517252) { p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } else if (numb1 &gt;= 3972294 &amp;&amp; numb1 &lt;= 5346331) { p13.setTextColor(Color.RED); p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } else if (numb1 &gt;= 3258594 &amp;&amp; numb1 &lt;= 3972293) { p12.setTextColor(Color.RED); p13.setTextColor(Color.RED); p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } else if (numb1 &gt;= 2421087 &amp;&amp; numb1 &lt;= 3258593) { p11.setTextColor(Color.RED); p12.setTextColor(Color.RED); p13.setTextColor(Color.RED); p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } else if (numb1 &gt;= 1475581 &amp;&amp; numb1 &lt;= 2421086) { p10.setTextColor(Color.RED); p11.setTextColor(Color.RED); p12.setTextColor(Color.RED); p13.setTextColor(Color.RED); p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } else if (numb1 &gt;= 273742 &amp;&amp; numb1 &lt;= 1475580) { p9.setTextColor(Color.RED); p10.setTextColor(Color.RED); p11.setTextColor(Color.RED); p12.setTextColor(Color.RED); p13.setTextColor(Color.RED); p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } else if (numb1 &gt;= 123660 &amp;&amp; numb1 &lt;= 273741) { p7.setTextColor(Color.RED); p8.setTextColor(Color.RED); p9.setTextColor(Color.RED); p10.setTextColor(Color.RED); p11.setTextColor(Color.RED); p12.setTextColor(Color.RED); p13.setTextColor(Color.RED); p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } else if (numb1 &gt;= 83014 &amp;&amp; numb1 &lt;= 123659) { p6.setTextColor(Color.RED); p7.setTextColor(Color.RED); p8.setTextColor(Color.RED); p9.setTextColor(Color.RED); p10.setTextColor(Color.RED); p11.setTextColor(Color.RED); p12.setTextColor(Color.RED); p13.setTextColor(Color.RED); p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } else if (numb1 &gt;= 22406 &amp;&amp; numb1 &lt;= 83013) { p5.setTextColor(Color.RED); p6.setTextColor(Color.RED); p7.setTextColor(Color.RED); p8.setTextColor(Color.RED); p9.setTextColor(Color.RED); p10.setTextColor(Color.RED); p11.setTextColor(Color.RED); p12.setTextColor(Color.RED); p13.setTextColor(Color.RED); p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } else if (numb1 &gt;= 13363 &amp;&amp; numb1 &lt;= 22405) { p4.setTextColor(Color.RED); p5.setTextColor(Color.RED); p6.setTextColor(Color.RED); p7.setTextColor(Color.RED); p8.setTextColor(Color.RED); p9.setTextColor(Color.RED); p10.setTextColor(Color.RED); p11.setTextColor(Color.RED); p12.setTextColor(Color.RED); p13.setTextColor(Color.RED); p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } else if (numb1 &gt;= 0 &amp;&amp; numb1 &lt;= 13362) { p2.setTextColor(Color.RED); p3.setTextColor(Color.RED); p4.setTextColor(Color.RED); p5.setTextColor(Color.RED); p6.setTextColor(Color.RED); p7.setTextColor(Color.RED); p8.setTextColor(Color.RED); p9.setTextColor(Color.RED); p10.setTextColor(Color.RED); p11.setTextColor(Color.RED); p12.setTextColor(Color.RED); p13.setTextColor(Color.RED); p14.setTextColor(Color.RED); p15.setTextColor(Color.RED); } } </code></pre>
3
3,161
JavaFX: avoid specifying absolute width
<p>I have got a <code>SplitPane</code> in a <code>SplitPane</code> -- both horizontal. I would like to avoid specifying absolute width/height. When I don't specify width/height, the second <code>SplitPane</code> is not shown:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?import javafx.scene.control.*?&gt; &lt;?import javafx.scene.Group?&gt; &lt;?import javafx.scene.layout.*?&gt; &lt;BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="500.0" style="-fx-background-color: cornsilk;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"&gt; &lt;left&gt; &lt;ToolBar orientation="VERTICAL"&gt; &lt;items&gt; &lt;Group&gt; &lt;children&gt; &lt;Button rotate="-90.0" text="Project" /&gt; &lt;/children&gt; &lt;/Group&gt; &lt;Group&gt; &lt;children&gt; &lt;Button rotate="-90.0" text="Structure" /&gt; &lt;/children&gt; &lt;/Group&gt; &lt;/items&gt; &lt;/ToolBar&gt; &lt;/left&gt; &lt;center&gt; &lt;SplitPane dividerPositions="0.25" style="-fx-background-color:red;"&gt; &lt;items&gt; &lt;AnchorPane style="-fx-background-color:darkblue;"/&gt; &lt;AnchorPane style="-fx-background-color:gold;"&gt; &lt;children&gt; &lt;SplitPane dividerPositions="0.25"&gt; &lt;items&gt; &lt;AnchorPane style="-fx-background-color:khaki;"/&gt; &lt;AnchorPane style="-fx-background-color:lime;"/&gt; &lt;/items&gt; &lt;/SplitPane&gt; &lt;/children&gt; &lt;/AnchorPane&gt; &lt;/items&gt; &lt;/SplitPane&gt; &lt;/center&gt; &lt;/BorderPane&gt; </code></pre>
3
1,131
Deploying Jenkins Sectioned View Plugin extension
<p>I want to create new view for Sectioned View Plugin for Jenkins. How should I deploy my extension? I was trying to deploy it as new plugin in .jpi file but it didn't work. Where should I put my class/jar/jpi (I don't know which is right) file?</p> <p>UPD: I tried to put jar to \jenkins\plugin\sectioned-view\WEB-INF\lib directory and it works but I doubt it's a right way to deploy that extension</p> <p>UPD2: When I try to deploy extension as a new plugin I get these exception on startup:</p> <pre><code>WARNING: Failed to load &lt;packageName&gt;.&lt;mainExtensionClassName&gt;$DescriptorImpl java.lang.InstantiationException:&lt;jenkinsDirectory&gt;\plugins\installedapplicationssection\WEB-INF\lib\classes.jar might need to be rebuilt: java.lang.ClassNotFoundException: &lt;packageName&gt;.&lt;mainExtensionClassName&gt;$DescriptorImpl at net.java.sezpoz.IndexItem.element(IndexItem.java:144) at hudson.ExtensionFinder$Sezpoz._find(ExtensionFinder.java:628) at hudson.ExtensionFinder$Sezpoz.find(ExtensionFinder.java:617) at hudson.ExtensionFinder._find(ExtensionFinder.java:151) at hudson.ClassicPluginStrategy.findComponents(ClassicPluginStrategy.java:316) at hudson.ExtensionList.load(ExtensionList.java:295) at hudson.ExtensionList.ensureLoaded(ExtensionList.java:248) at hudson.ExtensionList.iterator(ExtensionList.java:138) at hudson.ClassicPluginStrategy.findComponents(ClassicPluginStrategy.java:309) at hudson.ExtensionList.load(ExtensionList.java:295) at hudson.ExtensionList.ensureLoaded(ExtensionList.java:248) at hudson.ExtensionList.get(ExtensionList.java:153) at hudson.PluginManager$PluginUpdateMonitor.getInstance(PluginManager.java:1109) at hudson.maven.PluginImpl.init(PluginImpl.java:54) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at hudson.init.InitializerFinder.invoke(InitializerFinder.java:120) at hudson.init.InitializerFinder$TaskImpl.run(InitializerFinder.java:184) at org.jvnet.hudson.reactor.Reactor.runTask(Reactor.java:259) at jenkins.model.Jenkins$7.runTask(Jenkins.java:906) at org.jvnet.hudson.reactor.Reactor$2.run(Reactor.java:187) at org.jvnet.hudson.reactor.Reactor$Node.run(Reactor.java:94) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.ClassNotFoundException: &lt;packageName&gt;.&lt;mainExtensionClassName&gt;$DescriptorImpl at hudson.PluginManager$UberClassLoader.findClass(PluginManager.java:985) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at net.java.sezpoz.IndexItem.element(IndexItem.java:134) </code></pre> <p>But I already have this in my class: @Extension public static final class DescriptorImpl extends SectionedViewSectionDescriptor {</p> <pre><code> @Override public String getDisplayName() { return "My Section"; } } </code></pre>
3
1,091
Object function work first time but return undefined the second time
<p>My code works fine for the first time but the second time, my object functions returns undefined.</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>_MANAGE = new Object() //----------------------------- BG ------------------------------// var saveBg = { name : "bg", url : "AN URL", data : { ID :function($this){ return $this.parents("tr").data("id") }, name :function($this){ return $this.parents("tr").find(".name").val() } } } //----------------------------------------------------------------------// //------------------------- SAVE FUNCTION ------------------------------// var saveButton = [saveBg]; $(".buttonSave").on("click", function(){ console.log(saveBg); var buttonName = $(this).data("name"); _MANAGE.saveButton(saveButton, buttonName, $(this)); }) //----------------------------------------------------------------------// //------------------------- SAVE BUTTON ------------------------------// _MANAGE.saveButton = function(saveButton, buttonName, $this_button){ for(var i = 0; i &lt; saveButton.length; i++){ if(buttonName == saveButton[i]["name"]){ for(var param in saveButton[i]["data"]){ if(typeof(saveButton[i]["data"][param]) == "function"){ saveButton[i]["data"][param] = saveButton[i]["data"][param]($this_button); } else { saveButton[i]["data"][param] = $(saveButton[i]["data"][param]).val(); } } if(!saveButton[i]["success"]){ saveButton[i]["success"] = function() { $this_button.children() .hide() .replaceWith("&lt;span style='font-size:0.7em;''&gt;Saved&lt;/span&gt;").fadeIn("slow"); setInterval(function(){ $this_button.children().hide().replaceWith('&lt;span class="icon-floppy"&gt; &lt;/span&gt;').fadeIn("slow"); }, 1500); } } _MANAGE.ajaxButton(saveButton[i]); } } } //----------------------------------------------------------------------// //------------------------- ASYNC FUNCTION ------------------------------// _MANAGE.ajaxButton = function(ajaxButton) { var stringData = ""; if(ajaxButton.data){ var loop = 0; for(var param in ajaxButton["data"]){ if(loop == 0){ stringData += param + "=" + ajaxButton["data"][param]; } else { stringData += "&amp;" + param + "=" + ajaxButton["data"][param]; } loop++; } } if(ajaxButton.url &amp;&amp; ajaxButton.success &amp;&amp; stringData != "") { $.ajax({ url : ajaxButton.url, data : stringData, dataType : "text", success : ajaxButton.success }); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!--THE TABLE --&gt; &lt;tr data-id="4"&gt; &lt;td&gt;&lt;b&gt;4&lt;/b&gt;&lt;/td&gt; &lt;td&gt;&lt;input class="name" type="text" value="A VALUE"&gt;&lt;/td&gt; &lt;td&gt; &lt;!-- THE BUTTON --&gt; &lt;div class="buttonSave" data-name="bg"&gt; &lt;span class="icon-floppy"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt;</code></pre> </div> </div> </p>
3
1,881
Kubernetes warning for clashes while using env variable in docker? why?
<p>We're using Gitlab for CI/CD. I'll include the script which we're using <strong>gitlab ci-cd file</strong></p> <pre><code> services: - docker:19.03.11-dind before_script: - apk update &amp;&amp; apk add bash - apk update &amp;&amp; apk add gettext workflow: rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH || $CI_COMMIT_BRANCH == &quot;developer&quot; || $CI_COMMIT_BRANCH == &quot;stage&quot;|| ($CI_COMMIT_BRANCH =~ (/^([A-Z]([0-9][-_])?)?SPRINT(([-_][A-Z][0-9])?)+/i)) when: always - if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH || $CI_COMMIT_BRANCH != &quot;developer&quot; || $CI_COMMIT_BRANCH != &quot;stage&quot;|| ($CI_COMMIT_BRANCH !~ (/^([A-Z]([0-9][-_])?)?SPRINT(([-_][A-Z][0-9])?)+/i)) when: never stages: - build - Publish - deploy cache: paths: - .m2/repository - target build_jar: image: maven:3.8.3-jdk-11 stage: build script: - mvn clean install package -DskipTests=true artifacts: paths: - target/*.jar docker_build_dev: stage: Publish image: docker:19.03.11 services: - docker:19.03.11-dind variables: IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY - docker build -t $IMAGE_TAG . - docker push $IMAGE_TAG only: - /^([A-Z]([0-9][-_])?)?SPRINT(([-_][A-Z][0-9])?)+/i - developer docker_build_stage: stage: Publish image: docker:19.03.11 services: - docker:19.03.11-dind variables: IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY - docker build -t $IMAGE_TAG . - docker push $IMAGE_TAG only: - stage deploy_dev: stage: deploy image: stellacenter/aws-helm-kubectl variables: ENV_VAR_NAME: development before_script: - aws configure set aws_access_key_id ${DEV_AWS_ACCESS_KEY_ID} - aws configure set aws_secret_access_key ${DEV_AWS_SECRET_ACCESS_KEY} - aws configure set region ${DEV_AWS_DEFAULT_REGION} script: - sed -i &quot;s/&lt;VERSION&gt;/${CI_COMMIT_SHORT_SHA}/g&quot; patient-service.yml - mkdir -p $HOME/.kube - cp $KUBE_CONFIG_DEV $HOME/.kube/config - chown $(id -u):$(id -g) $HOME/.kube/config - export KUBECONFIG=$HOME/.kube/config - cat patient-service.yml | envsubst | kubectl apply -f patient-service.yml -n ${KUBE_NAMESPACE_DEV} only: - /^([A-Z]([0-9][-_])?)?SPRINT(([-_][A-Z][0-9])?)+/i - developer deploy_stage: stage: deploy image: stellacenter/aws-helm-kubectl variables: ENV_VAR_NAME: stage before_script: - aws configure set aws_access_key_id ${DEV_AWS_ACCESS_KEY_ID} - aws configure set aws_secret_access_key ${DEV_AWS_SECRET_ACCESS_KEY} - aws configure set region ${DEV_AWS_DEFAULT_REGION} script: - sed -i &quot;s/&lt;VERSION&gt;/${CI_COMMIT_SHORT_SHA}/g&quot; patient-service.yml - mkdir -p $HOME/.kube - cp $KUBE_CONFIG_STAGE $HOME/.kube/config - chown $(id -u):$(id -g) $HOME/.kube/config - export KUBECONFIG=$HOME/.kube/config - cat patient-service.yml | envsubst | kubectl apply -f patient-service.yml -n ${KUBE_NAMESPACE_STAGE} only: - stage </code></pre> <p>According to the script, we just merged the script not to face conflicts/clashes for stage and development while deployment. Previously, we having each docker files for each environment(stage and developer). Now I want to merge the dockerfile also, I merged, but the dockerfile is not fetching. Having clashes (warning shows after pipeline succeeds) in Kubernetes. I don't know how to clear the warning in Kubernetes. I'll enclose the docker file which I merged.</p> <pre><code>FROM maven:3.8.3-jdk-11 AS MAVEN_BUILD COPY pom.xml /build/ COPY src /build/src/ WORKDIR /build/ RUN mvn clean install package -DskipTests=true FROM openjdk:11 ARG environment_name WORKDIR /app COPY --from=MAVEN_BUILD /build/target/patient-service-*.jar /app/patient-service.jar ENV PORT 8094 ENV env_var_name=$environment_name EXPOSE $PORT ENTRYPOINT [&quot;java&quot;,&quot;-Dspring.profiles.active= $env_var_name&quot;,&quot;-jar&quot;,&quot;/app/patient-service.jar&quot;] </code></pre> <p>the last line, we used before,</p> <pre><code>ENTRYPOINT [&quot;java&quot;,&quot;-Dspring.profiles.active=development&quot;,&quot;-jar&quot;,&quot;/app/patient-service.jar&quot;] -for developer dockerfile ENTRYPOINT [&quot;java&quot;,&quot;-Dspring.profiles.active=stage&quot;,&quot;-jar&quot;,&quot;/app/patient-service.jar&quot;] - for stage dockerfile </code></pre> <p>At the time, its working fine, I'm not facing any issue on Kubernetes. I'd just add environment variable to fetch along with whether development or stage. You can check ,my script after the docker build. After adding the variable only, we began facing the clashes. Please help me to sort this out. Thanks in advance.</p> <p><strong>Yaml file</strong></p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: patient-app labels: app: patient-app spec: replicas: 1 selector: matchLabels: app : patient-app template: metadata: labels: app: patient-app spec: containers: - name: patient-app image: registry.gitlab.com/stella-center/backend-services/patient-service:&lt;VERSION&gt; imagePullPolicy: Always ports: - containerPort: 8094 imagePullSecrets: - name: gitlab-registry-token-auth --- apiVersion: v1 kind: Service metadata: name: patient-service spec: type: NodePort selector: app: patient-app ports: - port: 8094 targetPort: 8094 </code></pre>
3
2,448
Video Streaming: Could not deserialize image after using pickle
<p>I'm trying to create a video streaming application, which has 3 components:</p> <ol> <li>An streaming application which streams via UDP the image received from camera </li> <li>The UDP server which reads for data, puts it in a local file</li> <li>HTTP Server, with a /cam.mjpg API, whose handler reads every 0.05 seconds from that pickle file, and transmits it (content type multipart)</li> </ol> <p>I'm getting the following error:</p> <pre><code>---------------------------------------- Exception happened during processing of request from ('192.168.43.251', 54236) Traceback (most recent call last): File "/usr/lib/python3.4/socketserver.py", line 613, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.4/socketserver.py", line 344, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.4/socketserver.py", line 669, in __init__ self.handle() File "/usr/lib/python3.4/http/server.py", line 398, in handle self.handle_one_request() File "/usr/lib/python3.4/http/server.py", line 386, in handle_one_request method() File "streaming_video_server2.py", line 25, in do_GET img = cv2.imdecode(img, x) TypeError: only size-1 arrays can be converted to Python scalars ---------------------------------------- </code></pre> <p>Here are my files, one by one (1, 2, 3)</p> <pre><code>#!/usr/bin/python import cv2 from PIL import Image import time import datetime import numpy as np import socket import sys import _pickle as cPickle import struct def StartStreamSending(): UDP_IP = "127.0.0.1" UDP_PORT = 8012 capture=cv2.VideoCapture(0) capture.set(cv2.CAP_PROP_FRAME_WIDTH, 320); capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 240); clientsocket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) fourcc = cv2.VideoWriter_fourcc(*'MPEG') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (320,240)) while True: ret,img=capture.read() timestamp = datetime.datetime.now() ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p") cv2.putText(img, ts, (10, img.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1) #Store the frame into the output file out.write(img) #Some processing before sending the frame to webserver imgRGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) jpg = Image.fromarray(imgRGB) size = sys.getsizeof(imgRGB) print(size) result, img_str = cv2.imencode('.jpeg', img) #data = np.array(img_str) data = img_str dataToSend = cPickle.dumps(data) size = sys.getsizeof(dataToSend) print(size) print(type(dataToSend)); clientsocket.sendto(dataToSend, (UDP_IP, UDP_PORT)) StartStreamSending() </code></pre> <p>File 2 : The UDP server which reads for data, puts it in a local file</p> <pre><code>import socket import sys import cv2 import _pickle as cPickle import numpy as np import struct HOST='localhost' PORT=8012 def WaitAndReceiveVideoStream(_strHOST, _iPORT): s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) print('Socket created') s.bind((_strHOST,_iPORT)) print('Socket bind complete') data = "" #payload_size = struct.calcsize("L") i = 0 while True: data, addr = s.recvfrom(66512) print(data) frame=cPickle.loads(data) i = i + 1 print('coming frame' + str(i)) with open('cam0.pickle', 'wb') as handle: cPickle.dump(frame, handle) WaitAndReceiveVideoStream(HOST, PORT) </code></pre> <p>And the HTTP Server (File 3):</p> <pre><code>#!/usr/bin/python import cv2 from PIL import Image import numpy as np import threading from http.server import BaseHTTPRequestHandler,HTTPServer import _pickle as cPickle from socketserver import ThreadingMixIn from io import StringIO,BytesIO import time import datetime class CamHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path.endswith('.mjpg'): self.send_response(200) self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary') self.end_headers() while True: try: with open('cam0.pickle', 'rb') as handle: img = cPickle.load(handle) #use numpy to construct an array from the bytes x = np.fromstring(img, dtype='uint8') img = cv2.imdecode(img, x) #Some processing before sending the frame to webserver ##imgRGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) ##jpg = Image.fromarray(imgRGB) jpg = Image.fromarray(img) tmpFile = BytesIO() jpg.save(tmpFile,'JPEG') self.wfile.write("--jpgboundary".encode()) self.send_header('Content-type','image/jpeg') self.send_header('Content-length',str(tmpFile.getbuffer().nbytes)) print(str(tmpFile.getbuffer().nbytes)) self.end_headers() jpg.save(self.wfile,'JPEG') time.sleep(0.05) print("Still inside mjpg") except KeyboardInterrupt: break except ConnectionResetError: break return if self.path.endswith('.html'): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write('&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;'.encode()) self.wfile.write('&lt;img src="http://127.0.0.1:8080/cam.mjpg"/&gt;'.encode()) self.wfile.write('&lt;/body&gt;&lt;/html&gt;'.encode()) return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" def main(): try: server = ThreadedHTTPServer(('0.0.0.0', 8080), CamHandler) print( "server started") server.serve_forever() except KeyboardInterrupt: server.socket.close() if __name__ == '__main__': main() </code></pre> <p>I believe the data I'm sending could be sent as a numpy array, not too sure, please suggest.</p>
3
2,867