title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
How does the Scala compiler perform implicit conversion?
<p>I have a custom class, <code>A</code>, and I have defined some operations within the class as follows:</p> <pre class="lang-scala prettyprint-override"><code>def +(that: A) = ... def -(that: A) = ... def *(that: A) = ... def +(that: Double) = ... def -(that: Double) = ... def *(that: Double) = ... </code></pre> <p>In order to have something like <code>2.0 + x</code> make sense when <code>x</code> is of type <code>A</code>, I have defined the following implicit class:</p> <pre class="lang-scala prettyprint-override"><code>object A { implicit class Ops (lhs: Double) { def +(rhs: A) = ... def -(rhs: A) = ... def *(rhs: A) = ... } } </code></pre> <p>This all works fine normally. Now I introduce a compiler plugin with a <code>TypingTransformer</code> that performs some optimizations. Specifically, let's say I have a <code>ValDef</code>:</p> <pre class="lang-scala prettyprint-override"><code>val x = y + a * z </code></pre> <p>where <code>x</code>, <code>y</code>, and <code>z</code> are of type <code>A</code>, and <code>a</code> is a <code>Double</code>. Normally, this compiles fine. I put it through the optimizer, which uses quasiquotes to change <code>y + a * z</code> into something else. <strong>BUT</strong> in this particular example, the expression is unchanged (there are no optimizations to perform). Suddenly, the compiler no longer does an implicit conversion for <code>a * z</code>.</p> <p>To summarize, I have a compiler plugin that takes an expression that would normally have implicit conversions applied to it. It creates a new expression via quasiquotes, which syntactically appears the same as the old expression. But for this new expression, the compiler fails to perform implicit conversion.</p> <p>So my question — how does the compiler determine that an implicit conversion must take place? Is there a specific flag or something that needs to be set in the AST that quasiquotes are failing to set?</p> <hr> <p><strong>UPDATE</strong></p> <p>The plugin phase looks something like this:</p> <pre class="lang-scala prettyprint-override"><code>override def transform(tree: Tree) = tree match { case ClassDef(classmods, classname, classtparams, impl) if classname.toString == "Module" =&gt; { var implStatements: List[Tree] = List() for (node &lt;- impl.body) node match { case DefDef(mods, name, tparams, vparamss, tpt, body) if name.toString == "loop" =&gt; { var statements: List[Tree] = List() for (statement &lt;- body.children.dropRight(1)) statement match { case Assign(opd, rhs) =&gt; { val optimizedRHS = optimizeStatement(rhs) statements = statements ++ List(Assign(opd, optimizedRHS)) } case ValDef(mods, opd, tpt, rhs) =&gt; { val optimizedRHS = optimizeStatement(rhs) statements = statements ++ List(ValDef(mods, opd, tpt, optimizedRHS)) } case Apply(Select(src1, op), List(src2)) if op.toString == "push" =&gt; { val optimizedSrc2 = optimizeStatement(src2) statements = statements ++ List(Apply(Select(src1, op), List(optimizedSrc2))) } case _ =&gt; statements = statements ++ List(statement) } val newBody = Block(statements, body.children.last) implStatements = implStatements ++ List(DefDef(mods, name, tparams, vparamss, tpt, newBody)) } case _ =&gt; implStatements = implStatements ++ List(node) } val newImpl = Template(impl.parents, impl.self, implStatements) ClassDef(classmods, classname, classtparams, newImpl) } case _ =&gt; super.transform(tree) } def optimizeStatement(tree: Tree): Tree = { // some logic that transforms // 1.0 * x + 2.0 * (x + y) // into // 3.0 * x + 2.0 * y // (i.e. distribute multiplication &amp; collect like terms) // // returned trees are always newly created // returned trees are create w/ quasiquotes // something like // 1.0 * x + 2.0 * y // will return // 1.0 * x + 2.0 * y // (i.e. syntactically unchanged) } </code></pre> <hr> <p><strong>UPDATE 2</strong></p> <p>Please refer to this GitHub repo for a minimum working example: <a href="https://github.com/darsnack/compiler-plugin-demo" rel="noreferrer">https://github.com/darsnack/compiler-plugin-demo</a></p> <p>The issue is that <code>a * z</code> turns into <code>a.&lt;$times: error&gt;(z)</code> after I optimize the statement.</p>
3
1,639
Getx() and hide bottomnavigation bar - error with stateful widget rendering
<p>I have a stateful widget (<a href="https://pub.dev/packages/miniplayer" rel="nofollow noreferrer">miniplayer</a>) in my stateless widget. I am trying to hide the bottomnavigation bar and getting the below error when I use Obx... Any idea how to fix this?</p> <p>I/flutter ( 9567): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter ( 9567): The following assertion was thrown building ValueListenableBuilder(dirty, dependencies: I/flutter ( 9567): [_LocalizationsScope-[GlobalKey#87424], _InheritedTheme], state: I/flutter ( 9567): _ValueListenableBuilderState#23ae3): I/flutter ( 9567): setState() or markNeedsBuild() called during build. I/flutter ( 9567): This Obx widget cannot be marked as needing to build because the framework is already in the process I/flutter ( 9567): of building widgets. A widget can be marked as needing to be built during the build phase only if I/flutter ( 9567): one of its ancestors is currently building. This exception is allowed because the framework builds I/flutter ( 9567): parent widgets before children, which means a dirty descendant will always be built. Otherwise, the I/flutter ( 9567): framework might not visit this widget during this build phase. I/flutter ( 9567): The widget on which setState() or markNeedsBuild() was called was: I/flutter ( 9567): Obx I/flutter ( 9567): The widget which was currently being built when the offending call was made was: I/flutter ( 9567): ValueListenableBuilder I/flutter ( 9567): I/flutter ( 9567): The relevant error-causing widget was: I/flutter ( 9567): <strong>Miniplayer</strong></p> <p>Code for bottomnavigation</p> <pre><code> bottomNavigationBar: Container( child: Obx( () =&gt; !_videoController.showBottomNavigation.value ? SizedBox.shrink() : BottomNavigationBar( currentIndex: 0, fixedColor: Colors.blue, items: [ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.mail), label: 'Messages', ), BottomNavigationBarItem( icon: Icon(Icons.person), label: 'Profile', ) ], ), ), </code></pre>
3
1,095
Programatically added picture in PDF picture field not being displayed
<p>I have created a PDF with Adobe, which contains an image field called "logo"</p> <p>Now if i want to add a picture using PDFBox it won't be displayed in the created pdf. </p> <p>However no error message is thrown and debugging looks completely fine with a correctly created PDImageXObject object.</p> <p>The used code is mostly adapted from this <a href="https://stackoverflow.com/questions/46799087/how-to-insert-image-programmatically-in-to-acroform-field-using-java-pdfbox/46820098#46820098">question</a>:</p> <pre><code> public static void setImageField(PDDocument pdfDocument, PDAcroForm acroForm, String fieldKey, byte[] imageData) { final PDField retrievedField = acroForm.getField(fieldKey); if (!(retrievedField instanceof PDPushButton)) { throw new RuntimeException("The field: " + fieldKey + " is not of the correct type"); } LOGGER.info("Received field: " + retrievedField.getPartialName()); // correct field is being logged final PDPushButton imageField = (PDPushButton) retrievedField; final List&lt;PDAnnotationWidget&gt; fieldWidgets = imageField.getWidgets(); // it has exactly one widget, which would be the action to set the image if (fieldWidgets == null || fieldWidgets.size() &lt;= 0) { throw new RuntimeException("Misconfiguration for field: " + fieldKey + ", it has no widgets(actions)"); } final PDAnnotationWidget imageWidget = fieldWidgets.get(0); PDImageXObject imageForm; try { // This test data is resized to be smaller than the bounding box of the image element in the PDF. Just for testing purposes final String testImage = "iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAARUlEQVR42u3PMREAAAgEIO2fzkRvBlcPGtCVTD3QIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIXC7VGjKHva+IvAAAAAElFTkSuQmCC"; final byte[] testData = Base64.getDecoder().decode(testImage); imageForm = PDImageXObject.createFromByteArray(pdfDocument, testData, "logo"); // imageForm is being populated with data and no error thrown } catch (IOException e) { throw new RuntimeException("Error creating Image from image data", e); } final float imageScaleRatio = (float) (imageForm.getHeight() / imageForm.getWidth()); final PDRectangle imagePosition = getFieldArea(imageField); LOGGER.info("Received image position: " + imagePosition.toString()); // Retrieve the height and width and position of the rectangle where the picture will be final float imageHeight = imagePosition.getHeight(); LOGGER.info("Image height: " + imageHeight); final float imageWidth = imageHeight / imageScaleRatio; LOGGER.info("Image width: " + imageWidth); final float imageXPosition = imagePosition.getLowerLeftX(); LOGGER.info("Image X position: " + imageXPosition); final float imageYPosition = imagePosition.getLowerLeftY(); LOGGER.info("Image Y position: " + imageYPosition); final PDAppearanceStream documentAppearance = new PDAppearanceStream(pdfDocument); documentAppearance.setResources(new PDResources()); // not sure why this is done // Weird "bug" in pdfbox forces to create the contentStream always after the object to add try (PDPageContentStream documentContentStream = new PDPageContentStream(pdfDocument, documentAppearance)) { documentContentStream.drawImage(imageForm, imageXPosition, imageYPosition, imageWidth, imageHeight); } catch (IOException e) { throw new RuntimeException("Error drawing the picture in the document", e); } // Setting the boundary box is mandatory for the image field! Do not remove or the flatten call on the acroform will NPE documentAppearance.setBBox(new PDRectangle(imageXPosition, imageYPosition, imageWidth, imageHeight)); // Apply the appearance settings of the document onto the image widget ( No border ) setImageAppearance(imageWidget, documentAppearance); // This code is normally somewhere else but for SO copied in this method to show how the pdf is being created acroForm.flatten(); AccessPermission ap = new AccessPermission(); ap.setCanModify(false); ap.setCanExtractContent(false); ap.setCanFillInForm(false); ap.setCanModifyAnnotations(false); ap.setReadOnly(); StandardProtectionPolicy spp = new StandardProtectionPolicy("", "", ap); spp.setEncryptionKeyLength(PdfBuildConstants.ENCRYPTION_KEY_LENTGH); pdfDocument.protect(spp); pdfDocument.save(pdfFile); pdfDocument.close(); } /** * Applies the appearance settings of the document onto the widget to ensure a consistent look of the document. * * @param imageWidget The {@link PDAnnotationWidget Widget} to apply the settings to * @param documentAppearance The {@link PDAppearanceStream Appearance settings} of the document */ private static void setImageAppearance(final PDAnnotationWidget imageWidget, final PDAppearanceStream documentAppearance) { PDAppearanceDictionary widgetAppearance = imageWidget.getAppearance(); if (widgetAppearance == null) { widgetAppearance = new PDAppearanceDictionary(); imageWidget.setAppearance(widgetAppearance); } widgetAppearance.setNormalAppearance(documentAppearance); } /** * Retrieves the dimensions of the given {@link PDField Field} and creates an {@link PDRectangle Rectangle} with the * same dimensions. * * @param field The {@link PDField Field} to create the rectangle for * @return The created {@link PDRectangle Rectangle} with the dimensions of the field */ private static PDRectangle getFieldArea(PDField field) { final COSDictionary fieldDictionary = field.getCOSObject(); final COSBase fieldAreaValue = fieldDictionary.getDictionaryObject(COSName.RECT); if (!(fieldAreaValue instanceof COSArray)) { throw new RuntimeException("The field: " + field.getMappingName() + " has no position values"); } final COSArray fieldAreaArray = (COSArray) fieldAreaValue; return new PDRectangle(fieldAreaArray); } </code></pre> <p>I also looked at other questions such as <a href="https://stackoverflow.com/questions/8521290/cant-add-an-image-to-a-pdf-using-pdfbox?rq=1">this</a>, but I can't use PDJpeg since it is not available in the current version. Additionally the original image to use can be anything from jpeg,png to gif.</p> <p>I validated that the position and dimension variables being logged have the same value as the image field in the pdf file. (properties of the field)</p> <p>UPDATE: Here is an example zip containing the template pdf and the generated pdf which fills in the form fields: <a href="https://www.file-upload.net/download-13732606/pdfBox-example.zip.html" rel="nofollow noreferrer">file upload</a> or <a href="https://www.dropbox.com/s/pa5q7cwqcieeusx/pdfBox-example.zip?dl=0" rel="nofollow noreferrer">Dropbox</a></p> <p>The example picture was a 50x50 png with plain green color generated from <a href="http://png-pixel.com/" rel="nofollow noreferrer">online png pixel</a></p>
3
2,254
Three reads with the same name in the BAM file
<p>I am dealing with the paired-end BAM file, and come up with many warnings like this: </p> <pre><code>WARNING: Could not find pair for HWI-ST430:177:2:1:4979:15503#0 WARNING: Could not find pair for HWI-ST430:177:2:1:5127:13427#0 WARNING: Could not find pair for HWI-ST430:177:2:1:6521:21452#0 </code></pre> <p>I check the warning reads in the BAM file, and find all the warning reads have three reads with the same name. For example:</p> <pre><code>HWI-ST430:177:2:1:4979:15503#0 65 chr32 26100696 60 79M21S chr5 36697147 0 ACTTTGCAATTTAAGTTTTACTTACTTTTTAACTAATATACATGCCTAAAATTTACAAAAACAATAATAAAAACAACAGAACACTGGAAACATTTTTAAA &gt;;=&lt;&gt;=&lt;&lt;=======&lt;====;===;=======&lt;=&gt;&gt;&gt;&gt;&gt;&gt;&lt;=&gt;&gt;==&gt;&gt;&gt;&gt;=&gt;&gt;&gt;&gt;==&gt;?&gt;=&lt;&lt;==&gt;?&gt;&gt;&gt;?&gt;?==&gt;&lt;=?&gt;&gt;&lt;=&lt;&gt;&gt;&gt;?&gt;?=&gt;??&gt;?===&gt; BD:Z:FFHFCIKKIHG@EEEHF??DGGEDGGE???DEEGGEFFFFGDHHHHGGE??FF?DGDG???EDGFGFGGF@@@FEHFEIEGFEEIJJIHBHGLJDD@EF@ MD:Z:79 PG:Z:MarkDuplicates RG:Z:Basenji BI:Z:FFIECHGIHFEAFEEHEAAFFHDFFHDAAAFEEIHFGGHGGGHHGHHHFBBGFBGGGHBBBFGHGGFGGFBBBGHIGHJGHGHFKJJJJEIKLJGHBGFB NM:i:0 AS:i:79 XS:i:19 HWI-ST430:177:2:1:4979:15503#0 129 chr5 36697147 60 72M28S chr32 26100696 0 ATTTGCCCCTGGGCTATTTTTTTCCTNCCATGTAAGATTCCGTTTTAAAAATGTTTCCAGTGTTCTGTTGTTTTTATTATTGTTTTTGTAAATTTTAGGC ===&lt;=&lt;&lt;&lt;&lt;====&lt;=&gt;========&lt;&lt;!&lt;&lt;&lt;=&gt;&lt;&lt;=&gt;&gt;&gt;&gt;&gt;=5=&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;=&gt;&gt;&gt;==&gt;=&gt;=&gt;&gt;&gt;&gt;=?&gt;=&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;=?&gt;=&gt;&gt;&gt;?&gt;&gt;&gt;??&gt;??&gt;;&lt;=&gt; SA:Z:chr32,26100739,-,36M64S,60,0; BD:Z:FFG@JKKFFHIIEHIGFF?????EGGEEEGHHEGEEDGFEGEGF??DE???FHEF?EGGHIFFGFEIFGGFG@@@EGGEGGGFHAAAHGJHBJJDDEHHI MD:Z:26T37T7 PG:Z:MarkDuplicates RG:Z:Basenji BI:Z:FFFBHHHFFHGGDGHGGEAAAAADFGEEEIHHGHFFFGFEGHHFBBGFBBBGHGFBEGIIIFGFEFHGFHHGCCCHIGHIGHHGDDDIIKIFKJGHGHGH NM:i:2 AS:i:65 XS:i:21 HWI-ST430:177:2:1:4979:15503#0 401 chr32 26100739 60 36M64H = 26100696 -79 GCCTAAAATTTACAAAAACAATAATAAAAACAACAG ===&lt;=&gt;&gt;=&gt;&gt;===&gt;===&lt;=&gt;===========&gt;;=== SA:Z:chr5,36697147,+,72M28S,60,2; BD:Z:IHHE??FF?EGEF???FEFFFDFGE@@AHHIJFIFF MD:Z:36 PG:Z:MarkDuplicates RG:Z:Basenji BI:Z:HGHGBBFFAEGFFAAAEFFEGFEGFABBFGHGGHFF NM:i:0 AS:i:36 XS:i:22 </code></pre> <p>The BAM file is alignment of HiSeq reads aligned to the reference genome using bwa, and use picard to remove redundancy. Base realignments were done using gatk.</p> <p>My confusion is:</p> <p>1、Why there are three reads with the same name, but have no relation?</p> <p>2、Maybe the first two are treated as mate pairs and the third as a single read. So could I just ignore it?</p> <p>Could eveyone help me? Many thanks for your help!</p>
3
1,496
How can I create a table from answers in a Google Form, in Google Sheets?
<p>So I'm really new to JavaScript, and I've been trying to organise, in a automated way, the answers that I get from a Google Form in a Google Sheet.</p> <p>I need to organise it in a table, with categories as lines and dates as rows, and with every new answer I need that table to updates itself. The date could only update once a day, and if a person answers in that day, the answer would fall on the row of that day, and on the line of the category that the person chose, and in the cell that cross's both of them an 'X'.</p> <p>I know how to work the update part with triggers in Google's AppScript, but I don't know how to design the table.</p> <p>If somebody could help me, even if with the most basic table design, I would really appreciate it.</p> <p>Here's my sample spreadsheet:</p> <p><a href="https://docs.google.com/spreadsheets/d/1zgqldnuXHWGe6LImgfg3nJGyUfNZAd6P1Q1RP-GlYXY/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1zgqldnuXHWGe6LImgfg3nJGyUfNZAd6P1Q1RP-GlYXY/edit?usp=sharing</a></p> <p>Thank you</p> <p>What I've done to organise a little the answears I got:</p> <pre><code>function check_data() { var num_rows = SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;Respostas do Formulário 1&quot;) .getLastRow(); for (i = 2; i &lt; num_rows + 1; i++) { var colA = SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;Respostas do Formulário 1&quot;) .getRange(&quot;A&quot; + i) .getValue() var colB = SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;Respostas do Formulário 1&quot;) .getRange(&quot;B&quot; + i) .getValue() var colC = SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;Respostas do Formulário 1&quot;) .getRange(&quot;C&quot; + i) .getValue() var colD = SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;Respostas do Formulário 1&quot;) .getRange(&quot;D&quot; + i) .getValue() var colE = SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;Respostas do Formulário 1&quot;) .getRange(&quot;E&quot; + i) .getValue() SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;script&quot;) .getRange(&quot;A&quot; + i) .setValue(colA) SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;script&quot;) .getRange(&quot;B&quot; + i) .setValue(colB) SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;script&quot;) .getRange(&quot;C&quot; + i) .setValue(colC) if (colD == 0) { SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;script&quot;) .getRange(&quot;D&quot; + i) .setValue(colE) } else { SpreadsheetApp.getActiveSpreadsheet() .getSheetByName(&quot;script&quot;) .getRange(&quot;D&quot; + i) .setValue(colD) } } } </code></pre>
3
1,253
BaGet with Apache2 Reverse Proxy on Docker Compose not working
<p>I'm trying to setup <a href="https://loic-sharma.github.io/BaGet/" rel="nofollow noreferrer">BaGet</a> in Docker with Docker Compose behind an Apache2 reverse proxy, where Apache2 is also running in Docker from Docker Compose.</p> <p>I've done this successful with Jenkins and Sonar, but with BaGet (http://localhost:8000/baget) I get &quot;Service Unavailable&quot; even though it's available directly on its own port, e.g.: http://localhost:5555/.</p> <p>My Docker Compose file looks like this:</p> <pre><code>version: &quot;3&quot; services: smtp: container_name: smtp image: namshi/smtp jenkins: container_name: jenkins build: ./jenkins/ environment: - JENKINS_OPTS=&quot;--prefix=/jenkins&quot; sonar: container_name: sonar image: sonarqube:latest environment: - SONAR_WEB_CONTEXT=/sonar baget: container_name: baget image: loicsharma/baget:latest ports: - &quot;5555:80&quot; environment: - PathBase=/baget apache: container_name: apache build: ./apache/ ports: - &quot;8000:80&quot; </code></pre> <p>My Apache2 Docker File looks like this:</p> <pre><code>FROM debian:stretch RUN apt-get update RUN apt-get install -y apache2 &amp;&amp; apt-get clean RUN a2enmod proxy RUN a2enmod proxy_http RUN a2dissite 000-default.conf COPY devenv.conf /etc/apache2/sites-available/devenv.conf RUN a2ensite devenv EXPOSE 80 CMD apachectl -D FOREGROUND </code></pre> <p>And my Apache2 config file like this:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerAdmin ... ServerName ... ServerAlias devenv ProxyRequests Off AllowEncodedSlashes NoDecode &lt;Proxy *&gt; Order deny,allow Allow from all &lt;/Proxy&gt; ProxyPreserveHost on ProxyPass /jenkins http://jenkins:8080/jenkins nocanon ProxyPassReverse /jenkins http://jenkins:8080/jenkins nocanon ProxyPass /sonar http://sonar:9000/sonar nocanon ProxyPassReverse /sonar http://sonar:9000/sonar nocanon ProxyPass /baget http://baget:5555/baget nocanon ProxyPassReverse /baget http://baget:5555/baget nocanon &lt;/VirtualHost&gt; </code></pre> <p>I've tried various different compinations of ProxyPass URLs, I've tried using localhost instead of the internal Docker Compose serivces names, I've tried different ports and I've tried running BaGet without the PathBase environment variable and nothing works!</p> <p>I'm hoping it's something obvious with my configuration and not something odd goign on with BaGet.</p>
3
1,073
Add unique items to recyclerView from geoQuery
<p>I created an app that shows items of users near me.</p> <p>I find the people who near me by using <code>geoQuery</code> and if they are near me, I search in the database what items they have and I populate a <code>RecyclerView</code> with them.</p> <p>I do so by using:</p> <pre><code>List&lt;DiscoverItems&gt; items = new ArrayList&lt;&gt;(); GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(Lat, Lon), Radius); geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() { @Override public void onKeyEntered(String key, GeoLocation location) { String UserID = key; if (!UserID.equals(auth.getUid())) { db.collection("Users").document(UserID).collection("MyItems").get().addOnCompleteListener(task_count -&gt; { if (task_count.isSuccessful()) { for (DocumentSnapshot document_near : task_count.getResult()) { items.add(new DiscoverItems(document_near.getString("ItemID"))); } } }); } discoverItemAdapter = new DiscoverItemAdapter(items, listener); rv_NearMeItems.setAdapter(discoverItemAdapter); } @Override public void onKeyExited(String key) { } @Override public void onKeyMoved(String key, GeoLocation location) { } @Override public void onGeoQueryReady() { } @Override public void onGeoQueryError(DatabaseError error) { } }); </code></pre> <p>However, my problem is if some users have the same item, because then it will appear twice in the recyclerView while I had liked it to have unique items.</p> <p>Is there any solution where I can first check my items list for duplicate and only then to add them?</p> <p>I tried to do the following:</p> <pre><code>List&lt;DiscoverItems&gt; items= new ArrayList&lt;&gt;(); Set&lt;DiscoverItems&gt; itemkset = new HashSet&lt;&gt;(); GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(Lat, Lon), Radius); geoQuery.addGeoQueryEventListener( new GeoQueryEventListener() { @Override public void onKeyEntered(String key, GeoLocation location) { String UserID = key; if (!UserID.equals( auth.getUid() )) { db.collection( "Users" ).document( UserID ).collection( "MyItems" ).get().addOnCompleteListener( task_count -&gt; { if (task_count.isSuccessful()) { for (DocumentSnapshot document_near : task_count.getResult()) { itemset.add( new DiscoverItems( document_near.getString( "ItemID" ) ) ); } } } ); } List&lt;DiscoverItems&gt; itemsWithoutDuplicates = new ArrayList&lt;&gt;(new HashSet&lt;&gt;(itemset)); for (DiscoverItems item: itemsWithoutDuplicates){ items.add(item); } discoverItemAdapter = new DiscoverItemAdapter(items, listener); rv_NearMeItems.setAdapter(discoverItemAdapter); } </code></pre> <p>But it doesn't work since if for example, I have 2 users, <code>onKeyEntered</code> will be called twice. For the first user it will add to <code>itemset</code> let say 4 items which are not identical and everything will be ok. Then it will call the second user which will add also 3 items to itemset which are not identical and it will be ok.</p> <p>Am I missing something? Because with the code above I'm getting multiple items.</p> <p>Thank you</p>
3
1,339
PowerShell different services to run in particular sequence (Remotely)
<p>First post! I apologize in advance for formatting. I'm just getting familiar with PowerShell and I'm wanting to Stop a service first, restart another service, and start the initial service. Before moving onto the next next service, I want to make sure that the service has stopped before proceeding.</p> <p>I'm using this function that was mentioned <a href="https://stackoverflow.com/questions/28186904/powershell-wait-for-service-to-be-stopped-or-started">here</a> and tried to tailor it for my code.</p> <p>Workflow Goal:</p> <ol> <li>Stop Service A</li> <li>Restart Service B</li> <li>Start Service A</li> </ol> <p>Code:</p> <pre><code>#Stops Service A and validates its in &quot;Stopped&quot; status Get-Service 'ServiceNameA' -ComputerName 'ExampleServerA' | Stop-Service -force -PassThru function WaitUntilServices1($searchString, $status) { # Get all services where DisplayName matches $searchString and loop through each of them. foreach($service in (Get-Service -DisplayName $searchString)) { # Wait for the service to reach the $status or a maximum of 30 seconds $service.WaitForStatus($status, '00:00:30') } } WaitUntilServices1 &quot;ServiceDisplayNameA&quot; &quot;Stopped&quot; #Restarts Service B and validates its in &quot;Running&quot; status Get-Service 'ServiceNameB' -ComputerName 'ExampleServerB' | Restart-Service -force -PassThru function WaitUntilServices2($searchString, $status) { # Get all services where DisplayName matches $searchString and loop through each of them. foreach($service in (Get-Service -DisplayName $searchString)) { # Wait for the service to reach the $status or a maximum of 30 seconds $service.WaitForStatus($status, '00:00:30') } } WaitUntilServices2 &quot;ServiceDisplayNameB&quot; &quot;Running&quot; #Start Service A and validates its in &quot;Running&quot; status Get-Service 'ServiceA' -ComputerName 'ExampleServerA' | Start-Service -force -PassThru Read-Host -Prompt &quot;Press Enter to exit&quot; </code></pre> <p>The Code I have above is giving me the following Errors for both of the functions.</p> <pre><code>Exception calling &quot;WaitForStatus&quot; with &quot;2&quot; argument(s): &quot;Time out has expired and the operation has not been completed.&quot; At C:\PowerShell\ScriptExample\ScriptExampleFix.ps1:10 char:9 $service.WaitForStatus($status, '00:00:30') + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : TimeoutException </code></pre> <p>Then for the very last portion to start the service I'm getting 1 more error:</p> <pre><code>Start-Service : A parameter cannot be found that matches parameter name 'force'. At C:\PowerShell\ScriptExample\ScriptExampleFix.ps1:32 char:85 + ... erName 'ServerNameExample' | Start-Service -force -PassTh ... + ~~~~~~ + CategoryInfo : InvalidArgument: (:) [Start-Service], ParameterBindingException + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.StartServiceCommand </code></pre> <p>Any help would get greatly appreciated :)</p>
3
1,054
Get pixel value of image draw through onPaint methode
<p>I am developping a custom C# UserControl WinForm to display an image on background and display scrollbars when I zoom with the mouse. For this, I overrided the <code>OnPaint</code> method. In it, if I have an image loaded, according some parameters I know the source and destination rectangle sizes. In the same way, I know what scale and translation apply to always keeping the top left corner on screen when zooming. And for the zoom, I use the scrollmouse event to update the zoom factory.</p> <p>Here is my code related to this override method.</p> <pre><code>protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // Draw image if(image != null) { // Rectangle srcRect, destRect; Point pt = new Point((int)(hScrollBar1.Value/zoom), (int)(vScrollBar1.Value/zoom)); if (canvasSize.Width * zoom &lt; viewRectWidth &amp;&amp; canvasSize.Height * zoom &lt; viewRectHeight) srcRect = new Rectangle(0, 0, canvasSize.Width, canvasSize.Height); // view all image else if (canvasSize.Width * zoom &lt; viewRectWidth) srcRect = new Rectangle(0, pt.Y, canvasSize.Width, (int)(viewRectHeight / zoom)); // view a portion of image but center on width else if (canvasSize.Height * zoom &lt; viewRectHeight) srcRect = new Rectangle(pt.X, 0, (int)(viewRectWidth / zoom), canvasSize.Height); // view a portion of image but center on height else srcRect = new Rectangle(pt, new Size((int)(viewRectWidth / zoom), (int)(viewRectHeight / zoom))); // view a portion of image destRect = new Rectangle((int)(-srcRect.Width/2), (int)-srcRect.Height/2, srcRect.Width, srcRect.Height); // the center of apparent image is on origin Matrix mx = new Matrix(); // create an identity matrix mx.Scale(zoom, zoom); // zoom image // Move image to view window center mx.Translate(viewRectWidth / 2.0f, viewRectHeight / 2.0f, MatrixOrder.Append); // Display image on widget Graphics g = e.Graphics; g.InterpolationMode = interMode; g.Transform = mx; g.DrawImage(image, destRect, srcRect, GraphicsUnit.Pixel); } } </code></pre> <p>My question is how to get the pixel value when I am on the MouseMove override method of this WinForm ?</p> <p>I think understand that it is possible only in method with PaintEventArgs but I am not sure how to deal with it. I tried a lot of things but for now the better I got is use the mouse position on the screen and find the pixel value in the original bitmap with these &quot;wrong&quot; coordinates. I can't link this relative position on the screen with the real coordinates of the pixel of the image display at this place. Maybe there is method to &quot;just&quot; get the pixel value not passing through the image bitmap I use for the paint method ? Or maybe not.</p> <p>Thank you in advance for your help. Best regards.</p>
3
1,028
How to use private registry provider, Service Account - from Kubernertes deployments
<p><strong>Update</strong> I suspect this to be a google issue, I have created a new more clean question <a href="https://stackoverflow.com/questions/55416886/authentication-methods-using-a-json-key-file-unauthorized-gcr-login-failed">here</a>.</p> <p><strong>Update</strong>: yes this is different than the suggested "This question may already have an answer here:", as this is about a "Service Account" - not a "User accounts".</p> <p>Do you now how to use a private registry like Google Container Registry from DigitalOcean or any other Kubernetes not running on the same provider?</p> <p>I tried following <a href="http://docs.heptio.com/content/private-registries/pr-gcr.html" rel="nofollow noreferrer">this</a>, but unfortunately it did not work for me.<br></p> <p><strong>Update</strong>: I suspect it to be a Google SA issue, I will go and try using Docker Hub and get back if that succeeds. I am still curious to see the solution for this, so please let me know - thanks!<br> <strong>Update</strong>: Also tried <a href="https://docs.openstack.org/kolla-kubernetes/0.3.0/private-registry.html" rel="nofollow noreferrer">this</a> <strong>Update</strong>: tried to activate <a href="https://cloud.google.com/sdk/gcloud/reference/auth/activate-service-account" rel="nofollow noreferrer">Google</a> Service Account<br> <strong>Update</strong>: tried to <a href="https://container-solutions.com/using-google-container-registry-with-kubernetes/" rel="nofollow noreferrer">download</a> Google Service Account key<br> <strong>Update</strong>: in the linked description is says: </p> <pre><code>kubectl create secret docker-registry $SECRETNAME \ --docker-server=https://gcr.io \ --docker-username=_json_key \ --docker-email=user@example.com \ --docker-password="$(cat k8s-gcr-auth-ro.json)" </code></pre> <p>Is the <code>--docker-password="$(cat k8s-gcr-auth-ro.json)"</code> really the password?</p> <p>If I do <code>cat k8s-gcr-auth-ro.json</code> the format is:</p> <pre><code>{ "type": "service_account", "project_id": "&lt;xxx&gt;", "private_key_id": "&lt;xxx&gt;", "private_key": "-----BEGIN PRIVATE KEY-----\&lt;xxx&gt;\n-----END PRIVATE KEY-----\n", "client_email": "k8s-gcr-auth-ro@&lt;xxx&gt;.iam.gserviceaccount.com", "client_id": "&lt;xxx&gt;", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/k8s-gcr-auth-ro%&lt;xxx&gt;.iam.gserviceaccount.com" } </code></pre> <p><strong>kubectl get pods</strong> I get: .<code>..is waiting to start: image can't be pulled</code></p> <p>from a deployment with:</p> <pre><code>image: gcr.io/&lt;project name&gt;/&lt;image name&gt;:v1 </code></pre> <p>deployment.yaml</p> <pre><code># K8s - Deployment apiVersion: extensions/v1beta1 kind: Deployment metadata: name: &lt;image-name&gt;-deployment-v1 spec: replicas: 1 template: metadata: labels: app: &lt;image-name&gt;-deployment version: v1 spec: containers: - name: &lt;image-name&gt; image: gcr.io/&lt;project-name&gt;/&lt;image-name&gt;:v1 imagePullPolicy: Always ports: - containerPort: 80 imagePullSecrets: - name: &lt;name-of-secret&gt; </code></pre> <p>I can see from the following that it logs: <code>repository does not exist or may require 'docker login'</code></p> <p>kubectl describe pod :</p> <pre><code>k describe pod &lt;image-name&gt;-deployment-v1-844568c768-5b2rt Name: &lt;image-name&gt;-deployment-v1-844568c768-5b2rt Namespace: default Priority: 0 PriorityClassName: &lt;none&gt; Node: my-cluster-digitalocean-1-7781/10.135.153.236 Start Time: Mon, 25 Mar 2019 15:51:37 +0100 Labels: app=&lt;image-name&gt;-deployment pod-template-hash=844568c768 version=v1 Annotations: &lt;none&gt; Status: Pending IP: &lt;ip address&gt; Controlled By: ReplicaSet/&lt;image-name&gt;-deployment-v1-844568c768 Containers: chat-server: Container ID: Image: gcr.io/&lt;project-name/&lt;image-name&gt;:v1 Image ID: Port: 80/TCP Host Port: 0/TCP State: Waiting Reason: ImagePullBackOff Ready: False Restart Count: 0 Environment: &lt;none&gt; Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-dh8dh (ro) Conditions: Type Status Initialized True Ready False ContainersReady False PodScheduled True Volumes: default-token-dh8dh: Type: Secret (a volume populated by a Secret) SecretName: default-token-dh8dh Optional: false QoS Class: BestEffort Node-Selectors: &lt;none&gt; Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s node.kubernetes.io/unreachable:NoExecute for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 50s default-scheduler Successfully assigned default/&lt;image-name&gt;-deployment-v1-844568c768-5b2rt to my-cluster-digitalocean-1-7781 Normal Pulling 37s (x2 over 48s) kubelet, my-cluster-digitalocean-1-7781 pulling image "gcr.io/&lt;project-name&gt;&lt;image-name&gt;:v1" Warning Failed 37s (x2 over 48s) kubelet, my-cluster-digitalocean-1-7781 Failed to pull image "gcr.io/&lt;project-name&gt;/&lt;image-name&gt;:v1": rpc error: code = Unknown desc = Error response from daemon: pull access denied for gcr.io/&lt;project-name&gt;/&lt;image-name&gt;, repository does not exist or may require 'docker login' Warning Failed 37s (x2 over 48s) kubelet, my-cluster-digitalocean-1-7781 Error: ErrImagePull Normal SandboxChanged 31s (x7 over 47s) kubelet, my-cluster-digitalocean-1-7781 Pod sandbox changed, it will be killed and re-created. Normal BackOff 29s (x6 over 45s) kubelet, my-cluster-digitalocean-1-7781 Back-off pulling image "gcr.io/&lt;project-name&gt;/&lt;image-name&gt;:v1" Warning Failed 29s (x6 over 45s) kubelet, my-cluster-digitalocean-1-7781 Error: ImagePullBackOff </code></pre> <p>Just a note: docker pull on local machine pulls the image alright</p>
3
2,899
How do I show a figcaption in a thumbnail gallery using JavaScript?
<p>I made a thumbnail gallery with JS, and I am trying to show the current image's figcaption when a thumbnail is clicked. JS is working fine for retrieving and showing the thumbnails themselves, but I'm stumped on how to display their figcaptions along with it. (Thumbnail figcaptions are currently set to 'display: none'). <br><br> Is a way to do this with CSS alone, or is a job for JS? Thanks in advance!</p> <p><a href="https://codepen.io/colinjalbert/pen/OJMBOMg" rel="nofollow noreferrer">https://codepen.io/colinjalbert/pen/OJMBOMg</a></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>let current = document.querySelector("#current"); let photos = document.getElementsByClassName("thumb"); for (let i = 0; i &lt; photos.length; i++) { photos[i].addEventListener("click", display); } function display() { let prev = this.getAttribute("src"); current.setAttribute("src", prev); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0px; padding: 0px; box-sizing: border-box; } body { font-family: sans-serif; margin-bottom: 4em; background-color: #1c1c1c; } figure { margin: 0px; text-align: center; float: right; } figcaption { position: relative; float: center; font-family: "Raleway"; font-size: 1em; font-weight: 400; text-align: left; top: -35px; padding: 0.5em; color: #f9f9f9; background-color: black; opacity: 0.8; } .gallery-container { display: flex; margin: 2em 2em; background-color: transparent; } .gallery { display: flex; margin-top: -5px; width: 50%; height: auto; flex-flow: row wrap; justify-content: flex-start; align-items: flex-start; align-content: flex-start; } .gallery-item { display: flex; width: 10em; height: 10em; margin: 8px; overflow: hidden; border-radius: 5px; } .gallery-item img { display: block; width: 100%; height: auto; object-fit: cover; transform: scale(1.2); transition: transform 400ms ease-out; -webkit-transition: transform 400ms ease-out; -moz-transition: transform 400ms ease-out; } .gallery-item img:hover { transform: scale(1.18); -webkit-transform: scale(1.18); cursor: pointer; } .preview-container { display: block; width: 50%; height: auto; margin-left: 1em; } .preview { display: block; width: 100%; height: auto; } .thumbcaption { display: none; } #current { display: block; width: 100%; height: auto; border-radius: 5px; } #caption { display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;div class="gallery-container"&gt; &lt;div class="gallery"&gt; &lt;div class="gallery-item"&gt; &lt;img src="http://seymourchwastarchive.com/wp-content/uploads/2015/03/Chwast_PPG81_001d-1600x1073.jpg" alt="" class="thumb"&gt; &lt;figcaption class="thumbcaption"&gt;Blue (1979)&lt;/figcaption&gt; &lt;/div&gt; &lt;div class="gallery-item"&gt; &lt;img src="http://seymourchwastarchive.com/wp-content/uploads/2015/03/Chwast_Monkey_001_SOI85-1230x1600.jpg" alt="" class="thumb"&gt; &lt;figcaption class="thumbcaption"&gt;No Evil (2003)&lt;/figcaption&gt; &lt;/div&gt; &lt;div class="gallery-item"&gt; &lt;img src="http://seymourchwastarchive.com/wp-content/uploads/2014/12/Chwast_FAG_008-1287x1600.jpg" alt="" class="thumb"&gt; &lt;figcaption class="thumbcaption"&gt;Self Portrait (1980s)&lt;/figcaption&gt; &lt;/div&gt; &lt;div class="gallery-item"&gt; &lt;img src="http://seymourchwastarchive.com/wp-content/uploads/2014/12/Chwast_Fader_001.jpg" alt="" class="thumb"&gt; &lt;figcaption class="thumbcaption"&gt;The Notorious B.I.G. (2011)&lt;/figcaption&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="preview-container"&gt; &lt;figure class="preview"&gt; &lt;img src="http://seymourchwastarchive.com/wp-content/uploads/2015/03/Chwast_Monkey_001_SOI85-1230x1600.jpg" alt="" id="current"&gt; &lt;figcaption id="previewcaption"&gt;No Evil (2003)&lt;/figcaption&gt; &lt;/figure&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
3
1,813
java.lang.NullPointerException while trying to add data to object of class in Android
<p>I am facing a silly problem. I am simply trying to add data to an object of my class, and not succeeding.</p> <p>I am fetching data via an Asynchronous task inside my fragment and want to use the resulting JSON to fill my ListView. I am using an ArrayAdapter and have created a class for this purpose.</p> <p>I have parsed the JSON String and now I am trying to add the data retrieved from the API to the object of my class, but it gives me 'java.lang.NullPointerException'.</p> <p>I guess I am not being able to add data to the object of my class. But I fail to understand the reason, I am more used to cding in C#, but JAVA being Object_Oriented, it should be the same, right? The code being used is as below...</p> <pre><code> JSONArray jsonArrayPendingBills = new JSONArray(); jsonArrayPendingBills = jsonObjectPendingBills.getJSONArray(TAG_RESPONSE_MESSAGE); ArrayList&lt;HashMap&lt;String, String&gt;&gt; arrayPendingBills = new ArrayList&lt;HashMap&lt;String,String&gt;&gt;(); ArrayList&lt;PendingBills&gt; arrayClassPendingBills = new ArrayList&lt;PendingBills&gt;(); for(int i = 0;i &lt; jsonArrayPendingBills.length(); i++){ JSONObject jsonObjectPendingBill = jsonArrayPendingBills.getJSONObject(i); String strDate = jsonObjectPendingBill.getString(TAG_PENDING_BILLS_DATE); String strTxCode = jsonObjectPendingBill.getString(TAG_PENDING_BILLS_TX_CODE); String strFromAccount = jsonObjectPendingBill.getString(TAG_PENDING_BILLS_FROM_ACCOUNT); String strAmount = jsonObjectPendingBill.getString(TAG_PENDING_BILLS_AMOUNT); String strDetails = jsonObjectPendingBill.getString(TAG_PENDING_BILLS_DETAILS); String strBillCode = jsonObjectPendingBill.getString(TAG_PENDING_BILLS_BILL_CODE); PendingBills objPendingBills = new PendingBills(); objPendingBills.setBillAmount(strAmount); objPendingBills.setBillDate(strDate); objPendingBills.setBillName(strFromAccount); //arrayClassPendingBills.add(new PendingBills(strAmount, strDate, strFromAccount)); arrayClassPendingBills.add(objPendingBills); } PendingBillsAdapter pendingBillsAdapter = new PendingBillsAdapter(getActivity(), R.layout.pending_bills_list_view_row, arrayClassPendingBills); listViewPendingBills.setAdapter(pendingBillsAdapter); progressDialogPendingBills.dismiss(); } catch (Exception e){ e.printStackTrace(); Log.i("Error", "Error", e); } </code></pre> <p>This is the code for my class:</p> <pre><code>public class PendingBills { // Declaring the strings for the class public String BillAmount; public String BillDate; public String BillName; // Writing down the constructor for this class public PendingBills(String BillAmount, String BillDate, String BillName){ this.BillAmount = BillAmount; this.BillDate = BillDate; this.BillName = BillName; } public PendingBills(){ } // Getter for BillAmount public String getBillAmount(){ return BillAmount; } // Setter for BillAmount public void setBillAmount(String BillAmount){ this.BillAmount = BillAmount; } public String getBillDate(){ return BillDate; } public void setBillDate(String BillDate){ this.BillDate = BillDate; } public String getBillName(){ return BillName; } public void setBillName(String BillName){ this.BillName = BillName; } } </code></pre> <p>I think I am missing something. I am not sure what? I have looked up a few questions on StackOverflow relating to this. I found many of them, but the solutions did not work for me.</p> <p><a href="https://stackoverflow.com/questions/13670403/adding-data-to-an-array-list">Adding data to an array list</a></p> <p><a href="https://stackoverflow.com/questions/18388629/how-to-properly-add-data-to-arraylist-android">How to properly add data to ArrayList - Android</a></p> <p>Any help will be appreciated. Thank you.</p> <p>Here is the LogCat....</p> <pre><code>12-02 07:02:04.235: E/AndroidRuntime(4648): FATAL EXCEPTION: main 12-02 07:02:04.235: E/AndroidRuntime(4648): java.lang.NullPointerException 12-02 07:02:04.235: E/AndroidRuntime(4648): at com.zipcash.zipcashbetaversion.PendingBillsAdapter.getView(PendingBillsAdapter.java:43) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.AbsListView.obtainView(AbsListView.java:2159) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.ListView.measureHeightOfChildren(ListView.java:1246) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.ListView.onMeasure(ListView.java:1158) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.View.measure(View.java:15518) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.View.measure(View.java:15518) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.View.measure(View.java:15518) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.View.measure(View.java:15518) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.View.measure(View.java:15518) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1029) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.View.measure(View.java:15518) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.View.measure(View.java:15518) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.View.measure(View.java:15518) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.LinearLayout.measureVertical(LinearLayout.java:847) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.View.measure(View.java:15518) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 12-02 07:02:04.235: E/AndroidRuntime(4648): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.View.measure(View.java:15518) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.Choreographer.doCallbacks(Choreographer.java:562) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.Choreographer.doFrame(Choreographer.java:532) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.os.Handler.handleCallback(Handler.java:725) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.os.Handler.dispatchMessage(Handler.java:92) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.os.Looper.loop(Looper.java:137) 12-02 07:02:04.235: E/AndroidRuntime(4648): at android.app.ActivityThread.main(ActivityThread.java:5041) 12-02 07:02:04.235: E/AndroidRuntime(4648): at java.lang.reflect.Method.invokeNative(Native Method) 12-02 07:02:04.235: E/AndroidRuntime(4648): at java.lang.reflect.Method.invoke(Method.java:511) 12-02 07:02:04.235: E/AndroidRuntime(4648): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 12-02 07:02:04.235: E/AndroidRuntime(4648): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 12-02 07:02:04.235: E/AndroidRuntime(4648): at dalvik.system.NativeStart.main(Native Method) </code></pre>
3
3,869
How to derive multiple classes from a single nib
<p>I’m trying to create a nib for a generic SectionHeader for a TableView as I need several similar SectionHeaders. I’m trying to follow this SO post:</p> <p><a href="https://stackoverflow.com/questions/3117753/how-to-create-multiple-windows-with-the-same-nib-file-in-xcode">How to create multiple windows with the same nib file in xcode</a></p> <p>The view defined in my nib file is assigned a base class of BaseSectionHeader. Here’s its initializer:</p> <pre><code>BaseSectionHeader.m - (id) initWithController:(MasterViewController*)ctlr; { self = [[[UINib nibWithNibName:@"SectionHeader" bundle:nil] instantiateWithOwner:ctlr options:nil] objectAtIndex:0]; if (self) { _controller = ctlr; } return self; } </code></pre> <p>Here’s the initializer of a subclass I’d like to derive:</p> <p>SectionHeader.h</p> <pre><code>@interface SectionHeader : BaseSectionHeader &lt;UIAlertViewDelegate&gt; … @end </code></pre> <p>SectionHeader.m</p> <pre><code>- (id) initWithController:(MasterViewController*)ctlr { if (self = [super initWithController:ctlr]) { _deleteConfirmButtonWidth = 70.0; } return self; } </code></pre> <p>And here’s how I instantiate a section header:</p> <pre><code>MasterViewController.m … SectionHeader* hdr = [[SectionHeader alloc] initWithController:self]; … </code></pre> <p>The problem is hdr is returned as a BaseSectionHeader, not a SectionHeader. This works correctly if I don't use the nib and construct BaseSectionHeader manually in code. But I’d like to use IB to construct the BaseSectionHeader if I can.</p> <p>Why is hdr a BaseSectionHeader instead of a SectionHeader when I use a nib? Is there a way use the nib and get the subclass I want for hdr?</p> <p>FWIW here’s my manual code:</p> <pre><code>BaseSectionHeader.m - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { _label = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0, 275.0, 40.0)]; [_label setTextColor:TanColor]; [_label setNumberOfLines:2]; [_label setLineBreakMode:NSLineBreakByTruncatingTail]; [_label setAdjustsFontSizeToFitWidth:YES]; [self addSubview:_label]; } return self; } SectionHeader.m - (id)initWithFrame:(CGRect)frame Controller:(MasterViewController*)ctlr { if (self = [super initWithFrame:frame]) { _controller = ctlr; _deleteConfirmButtonWidth = 70.0; _titleButton = [UIButton buttonWithType:UIButtonTypeCustom]; _titleButton.frame = CGRectMake(10.0, 0.0, 275.0, 40.0); _titleButton.alpha = 0.3; [self addSubview:_titleButton]; } return self; } </code></pre> <p>Thanks </p>
3
1,050
Parse URL using Regex
<p>I have Youtube and Dailymotion Video URL as follows:</p> <p>For Youtube</p> <ul> <li><a href="http://www.youtube.com/v/0PsnoiwMrhA" rel="nofollow">http://www.youtube.com/v/0PsnoiwMrhA</a></li> <li><a href="http://www.youtube.com/watch?v=ok_VQ8I7g6I" rel="nofollow">http://www.youtube.com/watch?v=ok_VQ8I7g6I</a></li> <li><a href="http://www.youtube.com/watch?v=1taai0d1FXw&amp;list=PL1uGXsv9VLdCm_LYVa9c7Rv8DPdflJZfT" rel="nofollow">http://www.youtube.com/watch?v=1taai0d1FXw&amp;list=PL1uGXsv9VLdCm_LYVa9c7Rv8DPdflJZfT</a></li> </ul> <p>For Dailymotion</p> <ul> <li><a href="http://www.dailymotion.com/video/x21a1i8_brazil-1-7-germany-a-world-cup-2014-brick-by-brick-video-animation_news" rel="nofollow">http://www.dailymotion.com/video/x21a1i8_brazil-1-7-germany-a-world-cup-2014-brick-by-brick-video-animation_news</a></li> <li><a href="http://www.dailymotion.com/video/x2148xg_brazil-1-7-germany-brazil-player-ratings-from-a-shocking-defeat_sport" rel="nofollow">http://www.dailymotion.com/video/x2148xg_brazil-1-7-germany-brazil-player-ratings-from-a-shocking-defeat_sport</a></li> </ul> <p>I want to get the Preview image of these video, So i have to parse these link as follows:</p> <p>For Youtube</p> <ul> <li><a href="http://img.youtube.com/vi/0PsnoiwMrhA/default.jpg" rel="nofollow">http://img.youtube.com/vi/0PsnoiwMrhA/default.jpg</a></li> <li><a href="http://img.youtube.com/vi/ok_VQ8I7g6I/default.jpg" rel="nofollow">http://img.youtube.com/vi/ok_VQ8I7g6I/default.jpg</a></li> <li><a href="http://img.youtube.com/vi/1taai0d1FXw/default.jpg" rel="nofollow">http://img.youtube.com/vi/1taai0d1FXw/default.jpg</a></li> </ul> <p>For Dailymotion</p> <ul> <li><a href="http://www.dailymotion.com/thumbnail/video/x21a1i8_brazil-1-7-germany-a-world-cup-2014-brick-by-brick-video-animation_news" rel="nofollow">http://www.dailymotion.com/thumbnail/video/x21a1i8_brazil-1-7-germany-a-world-cup-2014-brick-by-brick-video-animation_news</a></li> <li><a href="http://www.dailymotion.com/thumbnail/video/x2148xg_brazil-1-7-germany-brazil-player-ratings-from-a-shocking-defeat_sport" rel="nofollow">http://www.dailymotion.com/thumbnail/video/x2148xg_brazil-1-7-germany-brazil-player-ratings-from-a-shocking-defeat_sport</a></li> </ul> <p>Please help me. I'm newbie in regex...</p>
3
1,055
Why is my graph not showing every Month? Facetgrid, Seaborn
<p>My <strong>sample dataset</strong> is the following:</p> <pre class="lang-py prettyprint-override"><code>dataset = { &quot;ClientId&quot;: [ 10, 20, 20, 20, 10, 5, 3, 7, 5, 20, 12, 5, 3, 20, 5, 8, 10, 9, 7, 20, 21, 5, 3, 10, ], &quot;Year&quot;: [ 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, ], &quot;Month&quot;: [ &quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;, &quot;Apr&quot;, &quot;Mai&quot;, &quot;Jun&quot;, &quot;Jul&quot;, &quot;Aug&quot;, &quot;Sep&quot;, &quot;Oct&quot;, &quot;Nov&quot;, &quot;Dec&quot;, &quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;, &quot;Apr&quot;, &quot;Mai&quot;, &quot;Jun&quot;, &quot;Jul&quot;, &quot;Aug&quot;, &quot;Sep&quot;, &quot;Oct&quot;, &quot;Nov&quot;, &quot;Dec&quot;, ], &quot;Sector&quot;: [ &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, ], &quot;Quantity&quot;: [ 100, 50, 25, 30, 40, 50, 200, 600, 20, 40, 100, 20, 50, 400, 250, 300, 125, 75, 90, 10, 225, 550, 450, 55, ], &quot;Regions&quot;: [ &quot;Europe&quot;, &quot;Asia&quot;, &quot;Africa&quot;, &quot;Africa&quot;, &quot;Other&quot;, &quot;Asia&quot;, &quot;Africa&quot;, &quot;Other&quot;, &quot;America&quot;, &quot;America&quot;, &quot;Europe&quot;, &quot;Europe&quot;, &quot;Other&quot;, &quot;Europe&quot;, &quot;Asia&quot;, &quot;Africa&quot;, &quot;Asia&quot;, &quot;Europe&quot;, &quot;Other&quot;, &quot;Africa&quot;, &quot;Europe&quot;, &quot;Asia&quot;, &quot;Africa&quot;, &quot;Europe&quot;, ], } df = pd.DataFrame(data=dataset) </code></pre> <p>I want to produce a <code>Facetgrid</code> of bar plots for each Year and Sector. I have managed to create the plot:</p> <pre><code>g = sns.FacetGrid(df, col='Year', row='Sector', margin_titles=True) g.map_dataframe(sns.barplot, x='Month', y='Quantity', color='orange') g.set_axis_labels('Months','Quantity') </code></pre> <p><strong>The Problem:</strong> The bar plots don't display every Months, only a few. What I would like is to see one bar per Month but I'm stuck.</p> <p>The graph looks like this currently: <a href="https://i.stack.imgur.com/jb3zc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jb3zc.png" alt="enter image description here" /></a></p>
3
1,469
Navbar menu not collapsing in each page
<p>I'm using Boostrap and my navigation menu is collapsing well in my index.html but not in my second page. I use exactly the same code for the header in both pages. Where does it come from ?</p> <pre><code>&lt;nav class=&quot;navbar navbar-expand-md navbar-light justify-content-between&quot;&gt; &lt;h1 class=&quot;navbar-brand top-title&quot;&gt; &lt;img src=&quot;img/title-logo.svg&quot; alt=&quot;&quot; style=&quot;width: 30px&quot; /&gt; Title &lt;/h1&gt; &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#navbarMenu&quot; &gt; &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarMenu&quot;&gt; &lt;ul class=&quot;navbar-nav text-center&quot;&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;index.html&quot; class=&quot;nav-link&quot;&gt;Example&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;nav-link&quot;&gt;Example&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;nav-link&quot;&gt;Example&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;nav-link&quot;&gt;Example&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; </code></pre> <p>Bootstrap link</p> <pre><code>&lt;link rel=&quot;stylesheet&quot; href=&quot;css/bootstrap.min.css&quot; /&gt; </code></pre> <p>Scripts</p> <pre><code> &lt;script src=&quot;/js/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/js/bootstrap.bundle.min.js&quot;&gt;&lt;/script&gt; </code></pre>
3
1,056
Change columns presentation based on available size
<p>Im trying to have a layout like in the image. In desktop show 4 items, but if the browser is resized and there is less space show 2 items above 2 below. And if the browser is even more rezied on mobile for example show only 1 item per row.</p> <p>Im trying with this code but its not working. Do you know how to achieve that? Thanks!</p> <pre><code>&lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;item&quot;&gt; text &lt;/div&gt; &lt;div class=&quot;item&quot;&gt; text &lt;/div&gt; &lt;div class=&quot;item &quot;&gt; text &lt;/div&gt; &lt;div class=&quot;item&quot;&gt; text &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>.container { display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: wrap; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; -webkit-align-content: center; -ms-flex-line-pack: center; align-content: center; -webkit-align-items: flex-start; -ms-flex-align: start; align-items: flex-start; } .item:nth-child(1) { width:33%; -webkit-order: 0; -ms-flex-order: 0; order: 0; -webkit-flex: 0 1 auto; -ms-flex: 0 1 auto; flex: 0 1 auto; -webkit-align-self: auto; -ms-flex-item-align: auto; align-self: auto; } .item:nth-child(2) { width:33%; -webkit-order: 0; -ms-flex-order: 0; order: 0; -webkit-flex: 0 1 auto; -ms-flex: 0 1 auto; flex: 0 1 auto; -webkit-align-self: auto; -ms-flex-item-align: auto; align-self: auto; } .item:nth-child(3) { width:33%; -webkit-order: 0; -ms-flex-order: 0; order: 0; -webkit-flex: 0 1 auto; -ms-flex: 0 1 auto; flex: 0 1 auto; -webkit-align-self: auto; -ms-flex-item-align: auto; align-self: auto; } .item:nth-child(4) { width:33%; -webkit-order: 0; -ms-flex-order: 0; order: 0; -webkit-flex: 0 1 auto; -ms-flex: 0 1 auto; flex: 0 1 auto; -webkit-align-self: auto; -ms-flex-item-align: auto; align-self: auto; } </code></pre> <p><a href="https://jsfiddle.net/y809xwfj/" rel="nofollow noreferrer">https://jsfiddle.net/y809xwfj/</a></p> <p><a href="https://i.stack.imgur.com/ktNFE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ktNFE.png" alt="enter image description here" /></a></p>
3
1,038
r- install package returned non-zero exit status warning
<p>I am trying to install gdeltr2 in r but I keep getting an error. I got the following error:Downloading GitHub repo abresler/gdeltr2@HEAD √ checking for file 'C:\Users\pales\AppData\Local\Temp\RtmpI36nL8\remotes14045d19d07\abresler-gdeltr2-1110b37/DESCRIPTION' ...</p> <ul> <li>preparing 'gdeltr2': (1.5s) √ checking DESCRIPTION meta-information ...</li> <li>checking for LF line-endings in source and make files and shell scripts</li> <li>checking for empty or unneeded directories Omitted 'LazyData' from DESCRIPTION</li> <li>building 'gdeltr2_0.3.1193.tar.gz'</li> </ul> <p>Installing package into ‘C:/Users/pales/Documents/R/win-library/4.1’ (as ‘lib’ is unspecified)</p> <ul> <li>installing <em>source</em> package 'gdeltr2' ... ** using staged installation ** R ** inst ** byte-compile and prepare package for lazy loading Warning: replacing previous import 'data.table::last' by 'dplyr::last' when loading 'gdeltr2' Warning: replacing previous import 'data.table::first' by 'dplyr::first' when loading 'gdeltr2' Warning: replacing previous import 'data.table::between' by 'dplyr::between' when loading 'gdeltr2' Warning: replacing previous import 'curl::handle_reset' by 'httr::handle_reset' when loading 'gdeltr2' Warning: replacing previous import 'data.table::month' by 'lubridate::month' when loading 'gdeltr2' Warning: replacing previous import 'data.table::hour' by 'lubridate::hour' when loading 'gdeltr2' Warning: replacing previous import 'data.table::quarter' by 'lubridate::quarter' when loading 'gdeltr2' Warning: replacing previous import 'data.table::week' by 'lubridate::week' when loading 'gdeltr2' Warning: replacing previous import 'data.table::year' by 'lubridate::year' when loading 'gdeltr2' Warning: replacing previous import 'data.table::wday' by 'lubridate::wday' when loading 'gdeltr2' Warning: replacing previous import 'data.table::second' by 'lubridate::second' when loading 'gdeltr2' Warning: replacing previous import 'data.table::minute' by 'lubridate::minute' when loading 'gdeltr2' Warning: replacing previous import 'data.table::mday' by 'lubridate::mday' when loading 'gdeltr2' Warning: replacing previous import 'data.table::yday' by 'lubridate::yday' when loading 'gdeltr2' Warning: replacing previous import 'data.table::isoweek' by 'lubridate::isoweek' when loading 'gdeltr2' Warning: replacing previous import 'httr::timeout' by 'memoise::timeout' when loading 'gdeltr2' Warning: replacing previous import 'jsonlite::flatten' by 'purrr::flatten' when loading 'gdeltr2' Warning: replacing previous import 'data.table::transpose' by 'purrr::transpose' when loading 'gdeltr2' Warning: replacing previous import 'curl::parse_date' by 'readr::parse_date' when loading 'gdeltr2' Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) : there is no package called 'readxl' Calls: ... loadNamespace -&gt; withRestarts -&gt; withOneRestart -&gt; doWithOneRestart Execution halted ERROR: lazy loading failed for package 'gdeltr2'</li> <li>removing 'C:/Users/pales/Documents/R/win-library/4.1/gdeltr2' Warning message: In i.p(...) : installation of package ‘C:/Users/pales/AppData/Local/Temp/RtmpI36nL8/file14046e31359/gdeltr2_0.3.1193.tar.gz’ had non-zero exit status. How can I get around this?</li> </ul>
3
1,103
Grouping JSON data on multiple keys and retaining the keys
<p>I have a flat JSON file that looks like this:</p> <pre><code>{"dataSet": {"dataTable": [{ "id": "List1", "row": [ { "pagenumber": "7", "pageversion": "HE; K12", "category": "3D Print - K12;HE", "pagetype": "Product", "PtrChild": "MakerBot - 10771", "Allocation": "0.500", "catext": "Text goes here" }, { "pagenumber": "7", "pageversion": "SL", "category": "3D Print - SL", "pagetype": "Product", "PtrChild": "AUTODESK - 10032", "Allocation": "0.500", "catext": "Text goes here" }, { "pagenumber": "10", "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Brand", "PtrChild": null, "Allocation": "1.000", "catext": "Text goes here" }, { "pagenumber": "11", "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Product", "PtrChild": "EPSON INK JET** - 10082", "Allocation": "0.200", "catext": "Text goes here" }, { "pagenumber": "11", "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Product", "PtrChild": "EPSON INK JET** - 10082", "Allocation": "0.200", "catext": "Text goes here" }, { "pagenumber": "11", "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Product", "PtrChild": "EPSON INK JET** - 10082", "Allocation": "0.500", "catext": "Text goes here" }, { "pagenumber": "11", "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Product", "PtrChild": "LEXMARK** - 10151", "Allocation": "0.200", "catext": "Text goes here" } ] }]}} </code></pre> <p>I need to group the data by pagenumber, then by pageversion, then by PtrChild, then by Allocation, so that it looks like this when finished:</p> <pre><code>{"pages": [ { "pagenumber": "7", "versions": [ { "pageversion": "HE; K12", "category": "3D Print - K12;HE", "pagetype": "Product", "partners": [{ "PtrChild": "MakerBot - 10771", "allocations": [{ "Allocation": "0.500", "ads": [{"catext": "Text goes here"}] }] }] }, { "pageversion": "SL", "category": "3D Print - SL", "pagetype": "Product", "partners": [{ "PtrChild": "AUTODESK - 10032", "allocations": [{ "Allocation": "0.500", "ads": [{"catext": "Text goes here"}] }] }] } ] }, { "pagenumber": "10", "versions": [{ "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Brand", "partners": [{ "PtrChild": null, "allocations": [{ "Allocation": "1.500", "ads": [{"catext": "Text goes here"}] }] }] }] }, { "pagenumber": "11", "versions": [{ "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Product", "partners": [ { "PtrChild": "EPSON INK JET** - 10082", "allocations": [ { "Allocation": "0.250", "ads": [ {"catext": "Text goes here"}, {"catext": "Text goes here"} ] }, { "Allocation": "0.500", "ads": [{"catext": "Text goes here"}] } ] }, { "PtrChild": "LEXMARK** - 10151", "allocations": [{ "Allocation": "0.200", "ads": [{"catext": "Text goes here"}] }] } ] }] } ]} </code></pre> <p>Running this:</p> <pre><code>var myGroupedData = nest(myCatalog, ["pagenumber", "pageversion", "PtrChild", "Allocation"]); // Reorganize JSON data function nest(collection, keys) { if (!keys.length) { return collection; } else { return _(collection).groupBy(keys[0]).mapValues(function(values) { return nest(values, keys.slice(1)); }).value(); } } </code></pre> <p>...gets the grouping right, but eliminates the Keys for each group:</p> <pre><code>{ "7": { "HE; K12": {"MakerBot - 10771": {"0.500": [{ "pagenumber": "7", "pageversion": "HE; K12", "category": "3D Print - K12;HE", "pagetype": "Product", "PtrChild": "MakerBot - 10771", "Allocation": "0.500", "catext": "Text goes here" }]}}, "SL": {"AUTODESK - 10032": {"0.500": [{ "pagenumber": "7", "pageversion": "SL", "category": "3D Print - SL", "pagetype": "Product", "PtrChild": "AUTODESK - 10032", "Allocation": "0.500", "catext": "Text goes here" }]}} }, "10": {"Apply to All": {"null": {"1.000": [{ "pagenumber": "10", "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Brand", "PtrChild": null, "Allocation": "1.000", "catext": "Text goes here" }]}}}, "11": {"Apply to All": { "EPSON INK JET** - 10082": { "0.200": [ { "pagenumber": "11", "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Product", "PtrChild": "EPSON INK JET** - 10082", "Allocation": "0.200", "catext": "Text goes here" }, { "pagenumber": "11", "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Product", "PtrChild": "EPSON INK JET** - 10082", "Allocation": "0.200", "catext": "Text goes here" } ], "0.500": [{ "pagenumber": "11", "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Product", "PtrChild": "EPSON INK JET** - 10082", "Allocation": "0.500", "catext": "Text goes here" }] }, "LEXMARK** - 10151": {"0.200": [{ "pagenumber": "11", "pageversion": "Apply to All", "category": "Secure Printers", "pagetype": "Product", "PtrChild": "LEXMARK** - 10151", "Allocation": "0.200", "catext": "Text goes here" }]} }} } </code></pre> <p>How can I retain the keys and group on multiple keys?</p> <p>I'm forced to use ExtendScript, so can't use Lodash beyond version 3.10.1.</p>
3
4,807
"AttributeError: 'list' object has no attribute 'SMSMessage'"
<p>I have tried many ways but can't seem to get the length of my list through the method in my class my code:</p> <pre><code>SMSStore = [] unreadMessage = [] class SMSMessage(object): def __init__(self, hasBeenRead, messageText, fromNumber): self.hasBeenRead = hasBeenRead self.messageText = messageText self.fromNumber = fromNumber hasBeenRead = False def markAsRead(self, hasBeenRead): hasBeenRead = True def add_sms(self): newMessage = (self.hasBeenRead, self.messageText, self.fromNumber) return SMSStore.append(newMessage) def get_count(): return len(SMSStore) def get_message(self, i): hasBeenRead = True return SMSStore[i][1] def get_unread_messages(i): for i in SMSStore: if SMSStore[i][0] == False: unreadMessage.append(SMSStore[i]) print unreadMessage def remove(self, i): return SMSStore.remove(i) </code></pre> <p>This is how a message in the list would ideally look like:</p> <pre><code>#sample = SMSMessage(False, "Hello friend!", 0742017560) </code></pre> <p>And here is how the class is used</p> <pre><code>userChoice = "" while userChoice != "quit": userChoice = raw_input("What would you like to do - read/send/quit?") if userChoice == "read": print len(SMSStore)#this way i can get the length of the list anyway without using get_count SMSStore(get_count() unreadChoice = raw_input("Would you like to retrieve all unread messages or one of your own choice? - all unread/custom ") if unreadChoice == "custom": i = int(raw_input("Please enter which message number you want to read: ")) print get_message(i) #I dont understand how i works and how to get it working with the object definition elif userChoice == "send": messageText = raw_input("Please type in your message: ") fromNumber = raw_input("Please type in the number it was sent from ") newObject = SMSMessage(False, messageText, fromNumber) newObject.add_sms() print SMSStore elif userChoice == "quit": print "Goodbye" else: print "Oops - incorrect input" </code></pre> <p>I can just use <code>len(SMSStore)</code> but I want to be able to use the method inside the class to get it. Can point out any mistakes?</p> <p>This was the question asked:</p> <pre><code>Open the file called​  sms.py​ Create a class definition for an SMSMessage which has three variables: hasBeenRead, messageText, and fromNumber.  The constructor should initialise the sender’s number.  The constructor should also initialise hasBeenRead  to false Create a method in this class called MarkAsRead which should change hasBeenRead to true. Create a list called SMSStore to be used as the inbox. Then create the following methods: add_sms - which takes in the text and number from the received sms to make a new SMSMessage object.  get_count - returns the number of messages in the store. get_message - returns the text of a message in the list.Forthis, allow the user to input an index i.e. GetMessage(i) returns the message stored at position i in the list. Once this has been done, hasBeenRead should now be true.  get_unread_messages - should return a list of all the messages which haven’t been read.  remove - removes a message in the SMSStore.  Now that you have these set up, let’s get everything working!  </code></pre>
3
1,421
AdobeFlashCS6 Actionscript3 JSON: Exported SWF and HTML banner don't show JSON information
<p>I have a <em>.swf</em> banner that in adobe FlashCS6 plays fine, but when I export it ( <em>.swf</em> and <em>.html</em>) the banner looses JSON information taken from online JSON file.</p> <p>What am I doing wrong?</p> <p>ActionScript Code:</p> <pre><code>play(); import flash.display.Sprite; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; var _jsonPath:String = yourURL; function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest(); request.url = _jsonPath; loader.addEventListener(Event.COMPLETE, onLoaderComplete); loader.load(request); } init(); function onLoaderComplete(e:Event):void { var loader:URLLoader = URLLoader(e.target); var jsonObject:Object = JSON.parse(loader.data); //JsonMan.decode(s:String):Object trace("loader.data: " + loader.data); trace(jsonObject[3].object.bets[0].title); if(i&lt;10){ country1.text = String(jsonObject[i].object.bets[0].title).toUpperCase(); country2.text = String(jsonObject[i].object.bets[2].title).toUpperCase(); country1_odds.htmlText = String("&lt;b&gt;"+ jsonObject[i].object.bets[0].odds + "&lt;/b&gt;"); country2_odds.htmlText = String("&lt;b&gt;"+jsonObject[i].object.bets[2].odds + "&lt;/b&gt;"); x_odds.htmlText = String("&lt;b&gt;"+jsonObject[i].object.bets[1].odds + "&lt;/b&gt;"); var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd&lt;10) { dd='0'+dd } if(mm&lt;10) { mm='0'+mm } today = mm+'-'+dd+'-'+yyyy; trace(today); obj_date.htmlText = String("&lt;b&gt;" + jsonObject[i].object.date + "&lt;/b&gt;"); i++; if(i==9){ i=0; } } } </code></pre> <p>Edit:</p> <p>In Chrome console it says: </p> <blockquote> <p>Failed to load resource: net::ERR_NAME_NOT_RESOLVED cloudssl.my.phpcloud.com/super/contentScript.js 2. Failed to load resource: the server responded with a status of 404 (Not Found) api.topsport.lt/crossdomain.xml. GET api.topsport.lt/crossdomain.xml 404 (Not Found) crossdomain.xml:1</p> </blockquote> <p>In output I receive this text:</p> <pre><code> `TypeError: Error #1010: A term is undefined and has no properties.` `at TOPSPORT2_fla::MainTimeline/onLoaderComplete()` `at flash.events::EventDispatcher/dispatchEventFunction()` `at flash.events::EventDispatcher/dispatchEvent()` `at flash.net::URLLoader/onComplete()` `TypeError: Error #1010: A term is undefined and has no properties.` `at TOPSPORT2_fla::MainTimeline/onLoaderComplete()` `at flash.events::EventDispatcher/dispatchEventFunction()` `at flash.events::EventDispatcher/dispatchEvent()` `at flash.net::URLLoader/onComplete()` </code></pre>
3
1,284
Firebase doesn't update the query
<p>I have this code for retrieve my data from database and show it in my recyclerview, but I have no idea how update the query to make an endless list of my data. I search in many posts but I'm new on android and firebase and it's complicated for me.</p> <p>The toast in the scrolllistener only shows the first time(the code works in that part) but the others not, because the int page change his value, and the recyclerview doesn't show the other elements. I hope you can help me, thanks in advance and sorry for my bad english.</p> <pre><code>public class FragmentPrincipal extends Fragment { private RecyclerView recyclerView; private DatabaseReference dReference, mReference; private GridLayoutManager gridLayoutManager; private FirebaseRecyclerAdapter&lt;GuardarReview, ReviewViewHolder&gt; firebaseRecyclerAdapter; private int itemsPerPage = 6, page = 1; private int visibleItemCount; private boolean loading; private Query query; public FragmentPrincipal(){ } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); gridLayoutManager = new GridLayoutManager(getContext(), 2); recyclerView.setLayoutManager(gridLayoutManager); dReference = FirebaseDatabase.getInstance().getReference(); mReference = dReference.child("Reviews"); query = mReference.orderByChild("date").limitToFirst(page * itemsPerPage); firebaseRecyclerAdapter = new FirebaseRecyclerAdapter&lt;GuardarReview, ReviewViewHolder&gt; (GuardarReview.class, R.layout.columna_reviews, ReviewViewHolder.class, query ) { @Override protected void populateViewHolder(ReviewViewHolder viewHolder, GuardarReview model, int position) { final String post_key = getRef(position).getKey(); viewHolder.setTitle(model.titulo); viewHolder.setImage(getContext(), model.imagenURL); viewHolder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), VerReview.class); intent.putExtra("review_id", post_key); startActivity(intent); } }); } }; recyclerView.setAdapter(firebaseRecyclerAdapter); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (dy &gt;= 0) { if(!loading){ visibleItemCount = gridLayoutManager.getChildCount(); if(visibleItemCount &gt;= (page * itemsPerPage)){ page++; Toast.makeText(getContext(), "Fin de la lista", Toast.LENGTH_SHORT).show(); loading = true; recyclerView.post(new Runnable() { public void run() { firebaseRecyclerAdapter.notifyDataSetChanged(); } }); } } loading = false; } } }); } @Override public View onCreateView(LayoutInflater inflador, ViewGroup contenedor, Bundle savedInstanceState){ View vista = inflador.inflate(R.layout.inicio_fragment, contenedor, false); recyclerView = (RecyclerView) vista.findViewById(R.id.recycler_view); recyclerView.setHasFixedSize(true); return vista; } public static class ReviewViewHolder extends RecyclerView.ViewHolder { View mView; public ReviewViewHolder(View itemView) { super(itemView); mView = itemView; } public void setTitle(String title){ TextView review_titulo = (TextView) mView.findViewById(R.id.review_titulo); review_titulo.setText(title); } public void setImage(Context context, String imagenURL){ ImageView review_imagen = (ImageView) mView.findViewById(R.id.review_imagen); Picasso.with(context).load(imagenURL).placeholder(R.drawable.loading3).into(review_imagen); } } @Override public void onDestroy() { super.onDestroy(); firebaseRecyclerAdapter.cleanup(); } } </code></pre>
3
1,772
UIScrollView and UIViews
<p>I want to use a UIScrollView to display multiple UIViews as the user scrolls through the UIScrollView control. I'm not worried about showing Pagination just yet.</p> <p>I already managed to implement some of it, but is not working the way I want it to. </p> <p>Currently:</p> <p>I have 3 ViewControllers with different nib files. The root view controller is the one with the UIScrollView, and it to load the rest of the view controllers.</p> <pre><code>NSMutableArray *controllers = [[NSMutableArray alloc] init]; for (unsigned i = 0; i &lt; kNumberOfPages; i++) { [controllers addObject:[NSNull null]]; } self.viewControllers = controllers; [controllers release]; scrollView.pagingEnabled = YES; scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * kNumberOfPages, scrollView.frame.size.height); scrollView.showsHorizontalScrollIndicator = NO; scrollView.showsVerticalScrollIndicator = NO; scrollView.scrollsToTop = NO; scrollView.delegate = self; pageControl.numberOfPages = kNumberOfPages; pageControl.currentPage = 0; [self loadScrollViewWithPage:0]; - (void)loadScrollViewWithPage:(int)page { if (page == 0) { PageTwo *controller2 = [viewControllers objectAtIndex:page]; if ((NSNull *)controller2 == [NSNull null]) { controller2 = [[PageTwo alloc] initWithPageNumber:page]; [viewControllers replaceObjectAtIndex:page withObject:controller2]; [controller2 release]; } // add the controller's view to the scroll view if (nil == controller2.view.superview) { CGRect frame = scrollView.frame; frame.origin.x = frame.size.width * page; frame.origin.y = 0; controller2.view.frame = frame; [scrollView addSubview:controller2.view]; } } if (page == 1) { // replace the placeholder if necessary NewController *controller = [viewControllers objectAtIndex:page]; if ((NSNull *)controller == [NSNull null]) { controller = [[NewController alloc] initWithPageNumber:page]; [viewControllers replaceObjectAtIndex:page withObject:controller]; [controller release]; } // add the controller's view to the scroll view if (nil == controller.view.superview) { CGRect frame = scrollView.frame; frame.origin.x = frame.size.width * page; frame.origin.y = 0; controller.view.frame = frame; [scrollView addSubview:controller.view]; } } </code></pre> <p>That's all fine... However, what I want it to do is to load the root nib first. But I'm not sure how to go about this. I know I have to increase the number of pages to 3, but when I initialize the controllers I don't know how to tell it that page == 0 should be the current view.</p> <p>Any ideas? </p> <p>Update:</p> <p>Sigh, I overlooked something.. Didn't notice that if don't specify a page at level 0 it just shows the current view hah!</p> <p>Silly me.</p>
3
1,101
PostgreSQL not using index for very big table
<p>A table <code>raw_data</code> has an index <code>ix_raw_data_timestamp</code>:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE IF NOT EXISTS public.raw_data ( ts timestamp without time zone NOT NULL, log_msg character varying COLLATE pg_catalog.&quot;default&quot;, log_image bytea ) CREATE INDEX IF NOT EXISTS ix_raw_data_timestamp ON public.raw_data USING btree (ts ASC NULLS LAST) TABLESPACE pg_default; </code></pre> <p>For some reason the index is not used for the following query (and therefore is very slow):</p> <pre class="lang-sql prettyprint-override"><code>SELECT ts, log_msg FROM raw_data ORDER BY ts ASC LIMIT 5e6; </code></pre> <p>The result of <code>EXPLAIN (analyze, buffers, format text)</code> for the query above:</p> <pre><code> QUERY PLAN -------------------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=9752787.07..10336161.14 rows=5000000 width=50) (actual time=789124.600..859046.614 rows=5000000 loops=1) Buffers: shared hit=12234 read=888521, temp read=2039471 written=2664654 -&gt; Gather Merge (cost=9752787.07..18421031.89 rows=74294054 width=50) (actual time=789085.442..822547.099 rows=5000000 loops=1) Workers Planned: 2 Workers Launched: 2 Buffers: shared hit=12234 read=888521, temp read=2039471 written=2664654 -&gt; Sort (cost=9751787.05..9844654.62 rows=37147027 width=50) (actual time=788203.880..795491.054 rows=1667070 loops=3) Sort Key: &quot;ts&quot; Sort Method: external merge Disk: 1758904kB Worker 0: Sort Method: external merge Disk: 1762872kB Worker 1: Sort Method: external merge Disk: 1756216kB Buffers: shared hit=12234 read=888521, temp read=2039471 written=2664654 -&gt; Parallel Seq Scan on raw_data (cost=0.00..1272131.27 rows=37147027 width=50) (actual time=25.436..119352.861 rows=29717641 loops=3) Buffers: shared hit=12141 read=888520 Planning Time: 5.240 ms JIT: Functions: 7 Options: Inlining true, Optimization true, Expressions true, Deforming true Timing: Generation 0.578 ms, Inlining 76.678 ms, Optimization 24.578 ms, Emission 13.060 ms, Total 114.894 ms Execution Time: 877489.531 ms (20 rows) </code></pre> <p>But it is used for this one:</p> <pre class="lang-sql prettyprint-override"><code>SELECT ts, log_msg FROM raw_data ORDER BY ts ASC LIMIT 4e6; </code></pre> <p><code>EXPLAIN (analyze, buffers, format text)</code> of the query above is:</p> <pre><code> QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=0.57..9408157.15 rows=4000000 width=50) (actual time=15.081..44747.127 rows=4000000 loops=1) Buffers: shared hit=24775 read=61155 -&gt; Index Scan using ix_raw_data_timestamp on raw_data (cost=0.57..209691026.73 rows=89152864 width=50) (actual time=2.218..16077.755 rows=4000000 loops=1) Buffers: shared hit=24775 read=61155 Planning Time: 1.306 ms JIT: Functions: 3 Options: Inlining true, Optimization true, Expressions true, Deforming true Timing: Generation 0.406 ms, Inlining 1.121 ms, Optimization 7.917 ms, Emission 3.721 ms, Total 13.165 ms Execution Time: 59028.951 ms (10 rows) </code></pre> <p>Needless to say that the aim is to get all queries to use the index no matter the size, but I cannot seem to find a solution.</p> <p>PS:</p> <ul> <li>There's about <code>89152922</code> rows in the database.</li> </ul> <p>Edit:</p> <p>After increasing the memory to 2G (<code>SET work_mem = '2GB';</code>), the query is a little faster (doesn't use disk anymore) but still nowhere as fast:</p> <pre><code> QUERY PLAN -------------------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=5592250.54..6175624.61 rows=5000000 width=50) (actual time=215887.445..282393.743 rows=5000000 loops=1) Buffers: shared hit=12224 read=888531 -&gt; Gather Merge (cost=5592250.54..14260731.75 rows=74296080 width=50) (actual time=215874.072..247030.062 rows=5000000 loops=1) Workers Planned: 2 Workers Launched: 2 Buffers: shared hit=12224 read=888531 -&gt; Sort (cost=5591250.52..5684120.62 rows=37148040 width=50) (actual time=215854.323..221828.921 rows=1667147 loops=3) Sort Key: &quot;ts&quot; Sort Method: top-N heapsort Memory: 924472kB Worker 0: Sort Method: top-N heapsort Memory: 924379kB Worker 1: Sort Method: top-N heapsort Memory: 924281kB Buffers: shared hit=12224 read=888531 -&gt; Parallel Seq Scan on raw_data (cost=0.00..1272141.40 rows=37148040 width=50) (actual time=25.899..107034.903 rows=29717641 loops=3) Buffers: shared hit=12130 read=888531 Planning Time: 0.058 ms JIT: Functions: 7 Options: Inlining true, Optimization true, Expressions true, Deforming true Timing: Generation 0.642 ms, Inlining 53.860 ms, Optimization 23.848 ms, Emission 11.768 ms, Total 90.119 ms Execution Time: 300281.654 ms (20 rows) </code></pre>
3
2,476
Memory leaking after `tf.keras.Model.fit` is called and training doesn't start
<p>I'm using my yolo <a href="https://github.com/alternativebug/yolo-tf2" rel="nofollow noreferrer">implementation</a> which used to work fine on tensorflow versions prior to 2.5. I tried recently training yolo3 on a small dataset (which uses <code>tf.keras.Model.fit</code>). Here's a colab <a href="https://colab.research.google.com/drive/18jCTQajjgBO2bmKekaI5frrluJ2CX4NN?usp=sharing" rel="nofollow noreferrer">notebook</a> which you can use to reproduce the issue. Shortly after <code>model.fit</code> is called, the messages below keep repeating:</p> <pre><code>/usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) </code></pre> <p>and</p> <pre><code>INFO:tensorflow:Assets written to: ram://eefa3127-ad7d-4445-a186-75fd8f0b81e1/assets </code></pre> <p>Then memory usage keeps growing for no apparent reason and eventually a memory crash occurs. (which doesn't happen in earlier tensorflow versions &lt;= 2.5). You can verify so using this other <a href="https://colab.research.google.com/drive/1a3RAhVA3pCTQj2FyGY2df7vum27pj69a?usp=sharing" rel="nofollow noreferrer">notebook</a> which uses tensorflow 2.5 instead, things should go perfectly fine and training goes as expected. I also tried installing tensorflow 2.8 instead of colab's default version (2.7) and the issue persists.</p> <p>Here's the output containing problems (tensorflow &gt; 2.5):</p> <pre><code>2022-02-07 05:52:00,476 yolo_tf2.utils.common.activate_gpu +325: INFO [260] GPU activated 2022-02-07 05:52:00,477 yolo_tf2.utils.common.train +468: INFO [260] Starting training ... 2022-02-07 05:52:04,293 yolo_tf2.utils.common.create_models +447: INFO [260] Training and inference models created 2022-02-07 05:52:04,295 yolo_tf2.utils.common.wrapper +64: INFO [260] create_models execution time: 3.8118433569999866 seconds 2022-02-07 05:52:04,301 yolo_tf2.utils.common.create_new_dataset +366: INFO [260] Generating new dataset ... 2022-02-07 05:52:07,014 yolo_tf2.utils.common.adjust_non_voc_csv +184: INFO [260] Adjustment from existing received 10107 labels containing 16 classes 2022-02-07 05:52:07,022 yolo_tf2.utils.common.adjust_non_voc_csv +187: INFO [260] Added prefix to images: /content/yolo-data/images Parsed labels: Car 3153 Pedestrian 1418 Palm Tree 1379 Traffic Lights 1269 Street Sign 1109 Street Lamp 995 Road Block 363 Flag 124 Trash Can 90 Minivan 68 Fire Hydrant 52 Bus 43 Pickup Truck 20 Bicycle 17 Delivery Truck 4 Motorcycle 3 Name: object_name, dtype: int64 2022-02-07 05:52:09,513 yolo_tf2.utils.common.save_fig +33: INFO [260] Saved figure /content/output/plots/Relative width and height for 10107 boxes..png /usr/local/lib/python3.7/dist-packages/yolo_tf2/utils/dataset_handlers.py:209: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray groups = np.array(data.groupby('image_path')) Processing beverly_hills_train.tfrecord Building example: 406/411 ... Beverly_hills184.jpg 99% completed2022-02-07 05:52:12,922 yolo_tf2.utils.common.save_tfr +227: INFO [260] Saved training TFRecord: /content/data/tfrecords/beverly_hills_train.tfrecord Building example: 411/411 ... Beverly_hills365.jpg 100% completed Processing beverly_hills_test.tfrecord Building example: 31/46 ... Beverly_hills335.jpg 67% completed2022-02-07 05:52:13,175 yolo_tf2.utils.common.save_tfr +229: INFO [260] Saved validation TFRecord: /content/data/tfrecords/beverly_hills_test.tfrecord 2022-02-07 05:52:13,271 yolo_tf2.utils.common.read_tfr +263: INFO [260] Read TFRecord: /content/data/tfrecords/beverly_hills_train.tfrecord Building example: 46/46 ... Beverly_hills186.jpg 100% completed 2022-02-07 05:52:18,892 yolo_tf2.utils.common.read_tfr +263: INFO [260] Read TFRecord: /content/data/tfrecords/beverly_hills_test.tfrecord /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) 2022-02-07 05:52:50.575910: W tensorflow/python/util/util.cc:368] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them. INFO:tensorflow:Assets written to: ram://eefa3127-ad7d-4445-a186-75fd8f0b81e1/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) INFO:tensorflow:Assets written to: ram://cbe6d5a4-5322-494b-ba91-3fd34131cdd9/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) INFO:tensorflow:Assets written to: ram://f15f3f25-9adb-4eb0-aa0d-83fa874bc74e/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) INFO:tensorflow:Assets written to: ram://86dd6f5f-4416-4465-99c0-928fd88e8a93/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) INFO:tensorflow:Assets written to: ram://ca08220f-cabc-4017-96d3-383557342388/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) INFO:tensorflow:Assets written to: ram://0f634207-e822-4d6c-a805-3cfeab37532f/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) INFO:tensorflow:Assets written to: ram://a971d021-3da4-402a-a004-4ae4aa67148a/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) INFO:tensorflow:Assets written to: ram://31d72fdf-1ce6-4131-a7e6-f6444747e9c9/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) INFO:tensorflow:Assets written to: ram://dac323b6-591a-481c-bbe6-85bb82bef38c/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) INFO:tensorflow:Assets written to: ram://99b029f7-11d1-40f2-b459-fd1d8dca5ba1/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) INFO:tensorflow:Assets written to: ram://210489fb-0895-4769-8be3-effd01d92695/assets /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:1410: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. layer_config = serialize_layer_fn(layer) </code></pre> <p>Here's the output without the problem (tensorflow 2.5):</p> <pre><code>2022-02-07 06:09:53.125735: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudart.so.11.0 2022-02-07 06:09:55.370728: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcuda.so.1 2022-02-07 06:09:55,387 yolo_tf2.utils.common.train +468: INFO [269] Starting training ... 2022-02-07 06:09:55.387211: E tensorflow/stream_executor/cuda/cuda_driver.cc:328] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected 2022-02-07 06:09:55.387252: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (de0312867ce7): /proc/driver/nvidia/version does not exist 2022-02-07 06:09:55.427963: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2022-02-07 06:10:00,078 yolo_tf2.utils.common.create_models +447: INFO [269] Training and inference models created 2022-02-07 06:10:00,080 yolo_tf2.utils.common.wrapper +64: INFO [269] create_models execution time: 4.689235652999997 seconds 2022-02-07 06:10:00,081 yolo_tf2.utils.common.create_new_dataset +366: INFO [269] Generating new dataset ... 2022-02-07 06:10:02,572 yolo_tf2.utils.common.adjust_non_voc_csv +184: INFO [269] Adjustment from existing received 10107 labels containing 16 classes 2022-02-07 06:10:02,574 yolo_tf2.utils.common.adjust_non_voc_csv +187: INFO [269] Added prefix to images: /content/yolo-data/images Parsed labels: Car 3153 Pedestrian 1418 Palm Tree 1379 Traffic Lights 1269 Street Sign 1109 Street Lamp 995 Road Block 363 Flag 124 Trash Can 90 Minivan 68 Fire Hydrant 52 Bus 43 Pickup Truck 20 Bicycle 17 Delivery Truck 4 Motorcycle 3 Name: object_name, dtype: int64 2022-02-07 06:10:04,900 yolo_tf2.utils.common.save_fig +33: INFO [269] Saved figure /content/output/plots/Relative width and height for 10107 boxes..png /usr/local/lib/python3.7/dist-packages/yolo_tf2/utils/dataset_handlers.py:209: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray groups = np.array(data.groupby('image_path')) Processing beverly_hills_train.tfrecord Building example: 392/411 ... Beverly_hills294.jpg 95% completed2022-02-07 06:10:10,341 yolo_tf2.utils.common.save_tfr +227: INFO [269] Saved training TFRecord: /content/data/tfrecords/beverly_hills_train.tfrecord Building example: 411/411 ... Beverly_hills94.jpg 100% completed Processing beverly_hills_test.tfrecord Building example: 25/46 ... Beverly_hills334.jpg 54% completed2022-02-07 06:10:10,730 yolo_tf2.utils.common.save_tfr +229: INFO [269] Saved validation TFRecord: /content/data/tfrecords/beverly_hills_test.tfrecord Building example: 46/46 ... Beverly_hills251.jpg 100% completed 2022-02-07 06:10:10,843 yolo_tf2.utils.common.read_tfr +263: INFO [269] Read TFRecord: /content/data/tfrecords/beverly_hills_train.tfrecord 2022-02-07 06:10:15,264 yolo_tf2.utils.common.read_tfr +263: INFO [269] Read TFRecord: /content/data/tfrecords/beverly_hills_test.tfrecord 2022-02-07 06:10:15.676352: I tensorflow/core/profiler/lib/profiler_session.cc:126] Profiler session initializing. 2022-02-07 06:10:15.676423: I tensorflow/core/profiler/lib/profiler_session.cc:141] Profiler session started. 2022-02-07 06:10:15.701051: I tensorflow/core/profiler/lib/profiler_session.cc:159] Profiler session tear down. /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/utils/generic_utils.py:497: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. category=CustomMaskWarning) 2022-02-07 06:10:17.064324: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:176] None of the MLIR Optimization Passes are enabled (registered 2) 2022-02-07 06:10:17.081408: I tensorflow/core/platform/profile_utils/cpu_utils.cc:114] CPU Frequency: 2199995000 Hz Epoch 1/100 1/Unknown - 40s 40s/step - loss: 7333.2617 - layer_205_lambda_loss: 403.8862 - layer_230_lambda_loss: 1509.9465 - layer_255_lambda_loss: 5407.68902022-02-07 06:10:59.974130: I tensorflow/core/profiler/lib/profiler_session.cc:126] Profiler session initializing. 2022-02-07 06:10:59.974196: I tensorflow/core/profiler/lib/profiler_session.cc:141] Profiler session started. 2/Unknown - 50s 11s/step - loss: 7819.7124 - layer_205_lambda_loss: 697.4546 - layer_230_lambda_loss: 1647.7856 - layer_255_lambda_loss: 5462.71582022-02-07 06:11:10.059899: I tensorflow/core/profiler/lib/profiler_session.cc:66] Profiler session collecting data. 2022-02-07 06:11:10.088821: I tensorflow/core/profiler/lib/profiler_session.cc:159] Profiler session tear down. 2022-02-07 06:11:10.133747: I tensorflow/core/profiler/rpc/client/save_profile.cc:137] Creating directory: /content/data/tfrecords/train/plugins/profile/2022_02_07_06_11_10 2022-02-07 06:11:10.157875: I tensorflow/core/profiler/rpc/client/save_profile.cc:143] Dumped gzipped tool data for trace.json.gz to /content/data/tfrecords/train/plugins/profile/2022_02_07_06_11_10/de0312867ce7.trace.json.gz 2022-02-07 06:11:10.189438: I tensorflow/core/profiler/rpc/client/save_profile.cc:137] Creating directory: /content/data/tfrecords/train/plugins/profile/2022_02_07_06_11_10 2022-02-07 06:11:10.189678: I tensorflow/core/profiler/rpc/client/save_profile.cc:143] Dumped gzipped tool data for memory_profile.json.gz to /content/data/tfrecords/train/plugins/profile/2022_02_07_06_11_10/de0312867ce7.memory_profile.json.gz 2022-02-07 06:11:10.192796: I tensorflow/core/profiler/rpc/client/capture_profile.cc:251] Creating directory: /content/data/tfrecords/train/plugins/profile/2022_02_07_06_11_10Dumped tool data for xplane.pb to /content/data/tfrecords/train/plugins/profile/2022_02_07_06_11_10/de0312867ce7.xplane.pb Dumped tool data for overview_page.pb to /content/data/tfrecords/train/plugins/profile/2022_02_07_06_11_10/de0312867ce7.overview_page.pb Dumped tool data for input_pipeline.pb to /content/data/tfrecords/train/plugins/profile/2022_02_07_06_11_10/de0312867ce7.input_pipeline.pb Dumped tool data for tensorflow_stats.pb to /content/data/tfrecords/train/plugins/profile/2022_02_07_06_11_10/de0312867ce7.tensorflow_stats.pb Dumped tool data for kernel_stats.pb to /content/data/tfrecords/train/plugins/profile/2022_02_07_06_11_10/de0312867ce7.kernel_stats.pb 15/Unknown - 181s 10s/step - loss: 3493.4009 - layer_205_lambda_loss: 232.7220 - layer_230_lambda_loss: 629.6332 - layer_255_lambda_loss: 2618.9722 </code></pre> <p>I also tried (same results):</p> <ul> <li>python versions: 3.8, 3.9, 3.10</li> <li>Ubuntu 18, and OSX</li> <li>tensorflow versions: 2.7, 2.8, 2.9.0-dev20220203</li> </ul>
3
5,959
group by result not exist in join other tabel laravel?
<p>i have two table and one pivot table. settlement table is this:</p> <pre><code> $table-&gt;ulid(); $table-&gt;string('track_id', 36); $table-&gt;string('payee_user_id', 36); $table-&gt;string('terminal_type', 36)-&gt;nullable(); $table-&gt;string('terminal_provider', 36)-&gt;nullable(); $table-&gt;string('terminal_psp', 36)-&gt;nullable(); $table-&gt;string('terminal_id', 36)-&gt;nullable(); $table-&gt;string('acceptor_id', 36)-&gt;nullable(); $table-&gt;string('terminal_no', 36)-&gt;nullable(); $table-&gt;string('account_bank_id', 36)-&gt;nullable(); $table-&gt;string('account_id', 36)-&gt;nullable(); $table-&gt;string('account_deposit', 36)-&gt;nullable(); $table-&gt;string('account_iban', 36)-&gt;nullable(); $table-&gt;integer('count')-&gt;nullable(); $table-&gt;decimal('amount_settle', 15, 2); $table-&gt;decimal('amount_wage', 15, 2); $table-&gt;timestamps(6); </code></pre> <p>transaction table is this</p> <pre><code> $table-&gt;ulid(); $table-&gt;string('payee_user_id', 36); $table-&gt;string('type', 36); $table-&gt;string('terminal_id', 36); $table-&gt;string('terminal_no', 36); $table-&gt;string('terminal_type', 36); $table-&gt;string('acceptor_id', 36); $table-&gt;string('terminal_psp', 36); $table-&gt;string('terminal_provider', 36); $table-&gt;decimal('amount_settle', 15, 2); $table-&gt;decimal('amount_wage', 15, 2); $table-&gt;string('account_id', 36)-&gt;nullable();; $table-&gt;string('account_bank_id', 36)-&gt;nullable();; $table-&gt;string('account_deposit', 26)-&gt;nullable(); $table-&gt;string('account_iban', 26)-&gt;nullable(); $table-&gt;string('wallet_id', 36)-&gt;nullable(); $table-&gt;timestamp('paid_at', 6); </code></pre> <p>settlements_transactions table is this:</p> <pre><code> $table-&gt;string('transaction_id')-&gt;index(); $table-&gt;string('settlement_id')-&gt;index(); $table-&gt;foreign('transaction_id', 'fk_transaction_id') -&gt;on('transactions')-&gt;references('id'); $table-&gt;foreign('settlement_id', 'fk_settlement_id') -&gt;on('settlements')-&gt;references('id'); </code></pre> <p>I am inserting group by of transaction in settlement table If I have not saved before.</p> <pre><code>$transactions = DB::table('transactions') -&gt;where('paid_at', '&lt;', $date) -&gt;where('terminal_type', Transaction::PRIVATE) -&gt;where('terminal_provider', Transaction::SHAPARAK) -&gt;distinct()-&gt;selectRaw( 'account_iban, account_deposit, account_bank_id, payee_user_id, account_id, terminal_psp, terminal_id, terminal_no, acceptor_id, account_id, SUM(amount_settle) as amount_settle, SUM(amount_wage) as amount_wage, COUNT(id) as count' )-&gt;groupBy( 'payee_user_id', 'account_id', 'account_iban', 'terminal_psp', 'terminal_no', 'terminal_id', 'acceptor_id', 'account_id', 'account_deposit', 'account_bank_id', )-&gt;orderBy('payee_user_id') -&gt;orderBy('account_id') -&gt;orderBy('terminal_psp') -&gt;orderBy('terminal_id') -&gt;orderBy('account_id') -&gt;orderBy('account_deposit') -&gt;orderBy('account_bank_id') -&gt;orderBy('account_iban') -&gt;orderBy('terminal_no') -&gt;orderBy('acceptor_id') -&gt;get(); foreach ($transactions as $transaction) { $exist = DB::table('settlements') -&gt;where('payee_user_id', $transaction-&gt;payee_user_id) -&gt;where('account_id', $transaction-&gt;account_id) -&gt;where('account_deposit', $transaction-&gt;account_deposit) -&gt;where('terminal_id', $transaction-&gt;terminal_id) -&gt;where('terminal_psp', $transaction-&gt;terminal_psp) -&gt;where('account_bank_id', $transaction-&gt;account_bank_id) -&gt;where('terminal_provider', Transaction::SHAPARAK) -&gt;where('terminal_type', Transaction::PRIVATE) -&gt;where('settlements.created_at', '&gt;=', Carbon::today()) -&gt;join('settlement_statuses', 'settlement_statuses.settlement_id', 'settlements.id') -&gt;applySettlementLastStatusSubJoin('settlement_statuses') -&gt;applySettlementLastAccepted('settlements') -&gt;exists(); if ($exist) { continue; } //insert in settlements table } </code></pre> <p>I do not want to check exist in the loop. i need to get transactions group by result if not exist in settlement table.</p>
3
2,505
Gradle sets incorrect (unexpected?) classpath on running task
<p>I have my project structured in this way:</p> <pre><code>projectRoot +-src +-main | +-java | | +-package/java files go here | +-resources | +-config | +-files go here +-test +-java | +-package/java files go here +-resources +-config | +-files go here +-features +-files go here </code></pre> <p>When this project is built, it produces the following output structure:</p> <pre><code>projectRoot +-out +-production | +-classes | | +-package/classes in here | +-resources | +-config | +-files in here +-test +-classes | +-package/classes in here +-resources +-config | +-files in here +-features +-files in here </code></pre> <p>This is all as expected. I have a task defined to run cucumber tests, which looks like this:</p> <pre><code>task runCucumber() { doLast { javaexec { main = "cucumber.api.cli.Main" args += ['--plugin', 'pretty', '--plugin', 'html:out/reports/cucumber/', '--plugin', 'json:out/reports/cucumber/report.json', '--glue', 'com.example.mypackage.cucumber', 'classpath:features' , '--tags', 'not @ignore'] systemProperties['http.keepAlive'] = 'false' systemProperties['http.maxRedirects'] = '20' systemProperties['env'] = System.getProperty("env") systemProperties['envType'] = System.getProperty("envType") classpath = configurations.cucumber + configurations.compile + configurations.testCompile + sourceSets.main.runtimeClasspath + sourceSets.test.runtimeClasspath } } } </code></pre> <p>When I execute this task, my classes are not found and neither are features. Clearly, this is due to classpath not being set correctly. If I run the task with <code>--info</code>, I can see that the classpath is set using the parameter I indicated, however instead of <code>out</code> directories, it contains <code>build</code> directories. I expected the classpath to be:</p> <pre><code>&lt;all dependencies&gt;:/projectRoot/out/production/classses:/projectRoot/out/production/resources:/projectRoot/out/test/classes:/projectRoot/out/test/resources </code></pre> <p>Yet, the classpath contains the following:</p> <pre><code>&lt;all dependencies&gt;:/projectRoot/build/classes/java/main:/projectRoot/build/classes/java/test: </code></pre> <p>Interestingly, directory <code>build</code> is not produced at all under the project root. How can I set the classpath so that classes and resources can be found?</p>
3
1,209
Executing a file too many times?
<p><strong>EDIT:</strong> <em>I still have a bug where if I use the command watchit by itself without filtering in an argument I get an endless loop of processes opening without being killed. I think this could be because of the way I set up the binary for watchit to run index.js while also inside of the the watch() I set the file name to index.js by default if none is provided</em></p> <p>So I was trying to create a program similar to nodemon where it can continuously watch your the program for changes and additions/deletions of files.</p> <p>I am using 2 libraries I installed via npm, <a href="https://www.npmjs.com/package/chokidar" rel="nofollow noreferrer">chokidar</a> for the actual watching of the program, then I used <a href="https://www.npmjs.com/package/caporal" rel="nofollow noreferrer">caporal</a> to create a CLI. I am also using <a href="https://www.npmjs.com/package/lodash.debounce" rel="nofollow noreferrer">lodash.debounce</a> as well as <a href="https://www.npmjs.com/package/chalk" rel="nofollow noreferrer">chalk</a>. Chalk is simply just to change the color of the output to make it look a little cleaner</p> <p>Inside the folder I have <em>index.js, package.json, package-lock.json, node modules folder</em>, then a <em>test.js</em> which I used to just test the program with a simple console.log();</p> <p>inside <strong>package.json</strong> I have the bin set as: </p> <pre><code>"bin": { "watchit": "index.js" } </code></pre> <p><strong>index.js</strong></p> <pre><code>#!/usr/bin/env node const debounce = require('lodash.debounce'); const chokidar = require('chokidar'); const prog = require('caporal'); const chalk = require('chalk'); const fs = require('fs'); const { spawn } = require('child_process'); prog .version('0.0.1') .argument('[filename]', 'Name of a file to execute') .action(async ({ filename }) =&gt; { const name = filename || 'index.js'; try { await fs.promises.access(name); } catch (err) { throw new Error(`Could not find the file: ${name}`); } let pid; const start = debounce(() =&gt; { if (pid) { console.log(chalk.red('------- Ending Process -------')); pid.kill(); } console.log(chalk.green('------- Starting Process -------')); pid = spawn('node', [name], { stdio: 'inherit' }); }, 100); chokidar .watch('.') .on('add', start) .on('change', start) .on('unlink', start); }); prog.parse(process.argv); </code></pre> <p><strong>test.js</strong></p> <pre><code>console.log('how many times do i run this'); </code></pre> <p><strong>from terminal</strong></p> <pre><code>$ watchit test.js ------- Starting Process ------- how many times do i run this ------- Ending Process ------- ------- Starting Process ------- how many times do i run this ------- Ending Process ------- ------- Starting Process ------- how many times do i run this </code></pre> <p>I am clearly creating a new process and running the program more than I should be since there are no tracked changes when the previous output was shown. That was from a single execution of test.js without ever editing it.</p> <p>Also when I simply run the command <em>watchit</em> from the directory I have this project on my computer, I get some of the above output then a large error about an unhandled promise rejection warning: <code>"UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 27)"</code></p> <p>Can anyone share some insight on WHY it's being ran too many times. Is the debounce timer just too low or is it something bigger than that?</p> <p><em>---edit---</em> after adding <code>event</code> into the <code>start</code> function and <code>console.log(event)</code> after I <code>console.log(-----start process-----)</code> I receive </p> <pre><code>------- Starting Process ------- .git/packed-refs how many times do i run this ------- Ending Process ------- ------- Starting Process ------- node_modules/winston/package.json how many times do i run this ------- Ending Process ------- ------- Starting Process ------- node_modules/winston/node_modules/colors/lib/system/supports-colors.js how many times do i run this </code></pre> <p><strong><em>after ignoring .git and node_modules</em></strong> To ignore the files/folders I changed passed in the options obj:</p> <pre><code>chokidar .watch('.', { ignored: '*.git', ignored: 'node_modules' }) .on('add', start) .on('change', start) .on('unlink', start); }); $ watchit test.js ------- Starting Process ------- .git/logs/HEAD how many times do i run this ------- Ending Process ------- ------- Starting Process ------- .git/logs/refs/remotes/origin/HEAD how many times do i run this </code></pre>
3
1,598
node js app works locally but display weirdly on heroku
<p><strong>solved</strong></p> <p>I've got nodejs app that works fine locally <a href="https://i.stack.imgur.com/QKRIr.png" rel="nofollow noreferrer">how it's suppose to look</a></p> <p>but when run with heroku all I've got was angular braces</p> <pre><code>Total Registered Devices : {{deviceCount}} {{ device.deviceName }} IMEI : {{ device.deviceId }} delete </code></pre> <p>with no error on logs</p> <pre><code>2017-05-17T14:00:37.000000+00:00 app[api]: Build started by user shira@bd-el.com 2017-05-17T14:00:52.540172+00:00 app[api]: Release v11 created by user shira@bd-el.com 2017-05-17T14:00:52.540172+00:00 app[api]: Deploy d1f297f by user shira@bd-el.com 2017-05-17T14:00:53.110060+00:00 heroku[web.1]: State changed from down to starting 2017-05-17T14:00:37.000000+00:00 app[api]: Build succeeded 2017-05-17T14:00:55.758955+00:00 heroku[web.1]: Starting process with command `node server.js` 2017-05-17T14:01:00.294554+00:00 heroku[web.1]: State changed from starting to up 2017-05-17T14:01:00.794336+00:00 app[web.1]: 7163 is the magic port 2017-05-17T14:01:01.254442+00:00 app[web.1]: db is open 2017-05-17T14:01:01.258895+00:00 app[web.1]: db is mongodb://heroku_090x9gxv:rkk64dlhd8mifkd08og359ti44@ds143181.mlab.com:43181/heroku_090x9gxv 2017-05-17T14:02:04.932689+00:00 heroku[router]: at=info method=GET path="/" host=afternoon-stream-95096.herokuapp.com request_id=753b228e-ed70-474e-a0f1-8c3001ba980f fwd="185.3.147.160" dyno=web.1 connect=0ms service=80ms status=200 bytes=2732 protocol=https 2017-05-17T14:02:05.197980+00:00 heroku[router]: at=info method=GET path="/main.js" host=afternoon-stream-95096.herokuapp.com request_id=13faf8b3-8c86-4e2f-9787-2912b6b50816 fwd="185.3.147.160" dyno=web.1 connect=0ms service=20ms status=200 bytes=3211 protocol=https </code></pre> <p>and my package.json file is-</p> <pre><code>{ "name": "nodejs-web-app1", "version": "0.0.0", "description": "NodejsWebApp1", "main": "server.js", "scripts": { "start": "node server.js" }, "author": { "name": "ddfps" }, "dependencies": { "body-parser": "^1.17.1", "ejs": "^2.5.6", "express": "^4.15.2", "mongoose": "^4.9.9", "morgan": "^1.8.1", "node-gcm": "^0.14.6", "socket.io": "^1.7.4" } } </code></pre> <p><strong>edit:</strong> console logs</p> <pre><code>&gt; Blocked loading mixed active content &gt; “http://fonts.googleapis.com/icon?family=Material+Icons”[Learn More] &gt; afternoon-stream-95096.herokuapp.com Blocked loading mixed active &gt; content &gt; “http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.css”[Learn &gt; More] afternoon-stream-95096.herokuapp.com Blocked loading mixed &gt; active content &gt; “http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js”[Learn &gt; More] afternoon-stream-95096.herokuapp.com Blocked loading mixed &gt; active content &gt; “http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.min.js”[Learn &gt; More] afternoon-stream-95096.herokuapp.com Blocked loading mixed &gt; active content &gt; “http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-aria.min.js”[Learn &gt; More] afternoon-stream-95096.herokuapp.com Blocked loading mixed &gt; active content &gt; “http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-messages.min.js”[Learn &gt; More] afternoon-stream-95096.herokuapp.com Blocked loading mixed &gt; active content &gt; “http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.js”[Learn &gt; More] afternoon-stream-95096.herokuapp.com ReferenceError: angular is &gt; not defined[Learn More] </code></pre> <p>or in short - angular is not defined. what could cause the problem?</p> <p>p.s I've got the exact same error when ran through cloud.9</p> <p><strong>edit 2 - solution</strong> angular was not defined because it's href was to http and heroku runs on https which caused the packages not to be loaded. I removed the 'http:' from the hrefs and that solved the problem.</p>
3
1,677
C# Duplicating fields in DataGridView after reading data from multiple files
<p>I'm making a program that downloads zip files from an SFTP server, unzips the files and reads the text file to display certain data in a DataGridView but for some reason its duplicating the values after 10-15 files</p> <p>Result:</p> <p><a href="https://i.stack.imgur.com/tMpr5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tMpr5.png" alt="Result" /></a></p> <p>Here is the code:</p> <pre><code>public partial class Form1 : Form { private DataGridView dexRead; public Form1() { InitializeComponent(); //this is the Designer.cs code... dexRead = new DataGridView(); ((ISupportInitialize)(this.dexRead)).BeginInit(); SuspendLayout(); dexRead.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dexRead.Location = new Point(12, 12); dexRead.Name = &quot;dexRead&quot;; dexRead.Size = new Size(606, 400); dexRead.TabIndex = 0; AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(630, 434); Controls.Add(dexRead); Name = &quot;Form1&quot;; Text = &quot;Form1&quot;; ((ISupportInitialize)(this.dexRead)).EndInit(); ResumeLayout(false); string zipTemp = (@&quot;C:\Users\mark\Desktop\Project Dex\zipTemp\&quot;); string machineCashCount = (&quot;&quot;); string hostIP = (&quot;0.0.0.0&quot;); string userName = (&quot;un&quot;); string passWord = (&quot;pw&quot;); string remotePath = (@&quot;/home/dex/RESPONSE/PROCESSED&quot;); string localPath = (@&quot;C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\&quot;); IList&lt;Machine&gt; machines = new BindingList&lt;Machine&gt;(); dexRead.DataSource = machines; SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = hostIP, UserName = userName, Password = passWord, PortNumber = 22, SshHostKeyFingerprint = &quot;ssh-rsa 2048 96:48:96:52:8c:e7:de:c6:e1:00:08:7e:db:ad:e4:06&quot; }; using (Session session = new Session()) { session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; session.GetFiles(remotePath, @&quot;C:\Users\mark\Desktop\Project Dex\Temp\&quot;).Check(); } DirectoryInfo directorySelected = new DirectoryInfo(@&quot;C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\&quot;); List&lt;string&gt; fileNames = new List&lt;string&gt;(); foreach (FileInfo fileInfo in directorySelected.GetFiles(&quot;*.zip&quot;)) { fileNames.Add(fileInfo.Name); } foreach (string fileName in fileNames) { string zipFilePath = localPath + fileName; string[] timeDate = fileName.Split('_'); string Date = timeDate[1]; string Time = timeDate[2]; string[] tme = Time.Split('.'); string tm = tme[0]; string dateTime = Date + tm; DateTime dTime = DateTime.ParseExact(dateTime, &quot;MMddyyyyHHmmss&quot;, CultureInfo.InvariantCulture); string daTime = dTime.ToString(); using (ZipFile zip1 = ZipFile.Read(zipFilePath)) { var selection = (from e in zip1.Entries where (e.FileName).StartsWith(&quot;01e&quot;) select e); Directory.CreateDirectory(zipTemp); foreach (var e in selection) { e.Extract(zipTemp, ExtractExistingFileAction.OverwriteSilently); } } DirectoryInfo dexDirect = new DirectoryInfo(@&quot;C:\Users\mark\Desktop\Project Dex\zipTemp\&quot;); List&lt;string&gt; dexName = new List&lt;string&gt;(); List&lt;string&gt; dexDate = new List&lt;string&gt;(); foreach (FileInfo dexInfo in dexDirect.GetFiles(&quot;*.dex&quot;)) { dexName.Add(dexInfo.Name); } foreach (string dexNames in dexName) { string dexFilePath = zipTemp + dexNames; string[] lines = System.IO.File.ReadAllLines(dexFilePath); foreach (string line in lines) { machineCashCount = Array.Find(lines, element =&gt; element.StartsWith(&quot;VA1&quot;, StringComparison.Ordinal)); } string[] MCC1 = machineCashCount.Split('*'); string[] nm = dexNames.Split('.'); int nam = int.Parse(nm[0], System.Globalization.NumberStyles.HexNumber); Console.WriteLine((nam + (&quot;:&quot;) + &quot;Total cash count: &quot;) + MCC1[1]); Console.WriteLine((nam + (&quot;:&quot;) + &quot;Number of paid vends: &quot;) + MCC1[2]); Machine m = new Machine(); m.MacNum = nam; m.CashCount = MCC1[1]; m.VendCount = MCC1[2]; m.Date_and_Time = daTime; machines.Add(m); } } } protected override void OnClosed(EventArgs e) { base.OnClosed(e); Array.ForEach(Directory.GetFiles(@&quot;C:\Users\mark\Desktop\Project Dex\zipTemp&quot;), File.Delete); Array.ForEach(Directory.GetFiles(@&quot;C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED&quot;), File.Delete); } } class Machine { public int MacNum { get; set; } public string CashCount { get; set; } public string VendCount { get; set; } public string Date_and_Time { get; set; } } </code></pre> <p>}</p> <p>I'm kinda new to programming in C# and I would really appreciate any help I can get, Thanks.</p>
3
2,947
Firefox 3 with image links and roll over
<p>I have a menu that isnt behaving for firefox 3 (and possible other versions)</p> <pre><code> &lt;div id="menu"&gt; &lt;p style="margin-right: 10px;"&gt; &lt;ul id="image-menu"&gt; &lt;a href="/#middle"&gt;&lt;li class="home_menu"&gt;&lt;/li&gt;&lt;/a&gt; | &lt;a href="/#top"&gt;&lt;li class="about"&gt;&lt;/li&gt;&lt;/a&gt; | &lt;a href="/#right"&gt;&lt;li class="stories"&gt;&lt;/li&gt;&lt;/a&gt; | &lt;a href="/#bottom"&gt;&lt;li class="whats_on"&gt;&lt;/li&gt;&lt;/a&gt; | &lt;a href="/#left"&gt;&lt;li class="get_involved"&gt;&lt;/li&gt;&lt;/a&gt; | &lt;a href="http://secure.theatreroyal.com/tickets/production.aspx?PID=308539"&gt;&lt;li class="tickets"&gt;&lt;/li&gt;&lt;/a&gt; | &lt;a href="/index.php/twayf/contact"&gt;&lt;li class="contact"&gt;&lt;/li&gt;&lt;/a&gt; &lt;/ul&gt; &lt;/p&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code> &lt;style type="text/css"&gt; #image-menu ul {line-height: 20px;} #image-menu li {list-style: none; height: 22px; display: inline-block;} #image-menu a {display:inline-block;} .home_menu {background-image: url(/images/menu/home1.png); background-repeat: no-repeat; width: 50px; } .home_menu:hover {background-image: url(/images/menu/home2.png);} .about {background-image: url(/images/menu/about1.png); background-repeat: no-repeat; width:64px; } .about:hover {background-image: url(/images/menu/about2.png);} .stories {background-image: url(/images/menu/stories1.png); background-repeat: no-repeat; width:88px; } .stories:hover {background-image: url(/images/menu/stories2.png);} .whats_on {background-image: url(/images/menu/whats_on1.png); background-repeat: no-repeat; width:96px; } .whats_on:hover {background-image: url(/images/menu/whats_on2.png);} .get_involved {background-image: url(/images/menu//behind_the_scenes1.png); background-repeat: no-repeat; width:192px; } .get_involved:hover {background-image: url(/images/menu/behind_the_scenes2.png);} .tickets {background-image: url(/images/menu/tickets1.png); background-repeat: no-repeat; width:83px; } .tickets:hover {background-image: url(/images/menu/tickets2.png);} .contact {background-image: url(/images/menu/contact1.png); background-repeat: no-repeat; width:83px; } .contact:hover {background-image: url(/images/menu/contact2.png);} &lt;/style&gt; </code></pre> <p>What is my best solution....add a fire fox version conditional statement to ask people to upgrade (i know ff 11 works fine) or is there another more elegant solution?</p>
3
1,048
Reinforcement Learning Agent Policy Won't Update
<p>I am currently training a deep reinforcement learning model in a continuous environment using Ray.</p> <p>The environment I am using was coded up in OpenAI Gym using baselines by another person who's research I am trying to replicate in Ray so that it may be parallelized. The model converges about 5% of the time in baselines after thousands of episodes though I have not been able to replicate this.</p> <p>My problem is that the AI stops changing its policy very quickly and the mean reward then stays roughly the same for the rest of the run. This is independent of every parameter I've tried to vary. So far I've tried changing:</p> <ul> <li>Learning Algorithm: I've used PPO, A3C, and DDPG</li> <li>Learning Rate: I've done hyperparameter sweeps from 1e-6 up to 10</li> <li>Episode Length: I've used <code>complete_episodes</code> as well as <code>truncated_episodes</code> in <code>batch_mode</code>. I've varied <code>rollout_fragment_length</code> and made sure <code>train_batch_size</code> was always equal to <code>rollout_fragment_length</code> times the number of workers</li> <li><code>entropy_coeff</code> in A3C</li> <li><code>kl_target</code>, <code>kl_coeff</code>, and <code>sgd_minibatch_size</code> in PPO</li> <li>Network Architecture: I've tried both wide and deep networks. The default Ray network is 2x256 layers. I've tried changing it to 4x2048 and 10x64. The baselines network that succeeded was 8x64.</li> <li>Changing activation function: ReLU returns NaNs but tanh lets the program run</li> <li>Implementing L2 loss to prevent connection weights from exploding. This kept tanh activation from returning NaNs after a certain amount of time (the higher the learning rate the faster it got to the point it returned NaNs)</li> <li>Normalization: I normalized the state that is returned to the agent from 0 to 1. Actions are not normalized because they both go from -6 to 6.</li> <li>Scaling the reward: Ive had rewards in the range of 1e-5 to 1e5. This had no effect on the agent's behavior.</li> <li>Changing reward functions</li> <li>Making the job easier (more lenient conditions)</li> </ul> <p>Note: I am running this in a docker image and have verified that this occurs on another machine so it's not a hardware issue.</p> <p><strong>Here is a list of things I believe are red flags that could be interrelated:</strong></p> <ul> <li>I was originally getting NaNs (Ray returned NaN actions) when using ReLU but switching my activation function to tanh.</li> <li>The KL divergence coefficient <code>cur_kl_coeff</code> in PPO goes to zero almost immediately when I include L2 loss. From what I understand, this means that the model is not making meaningful weight changes after the first few iterations. <a href="https://i.stack.imgur.com/KFhDY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KFhDY.png" alt="enter image description here"></a></li> </ul> <p>However, when the loss is just policy loss, <code>cur_kl_coeff</code> varies normally.</p> <ul> <li><p>Loss doesn't substantially change on average and doesn't ever converge <a href="https://i.stack.imgur.com/fqjW8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fqjW8.png" alt="enter image description here"></a></p></li> <li><p>Reward doesn't change substantially <code>reward_mean</code> always converges to roughly the same value. This occurs even when <code>reward_mean</code> starts above average or initially increases to above average due to random weight initialization. <a href="https://i.stack.imgur.com/8jVWD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8jVWD.png" alt="Here, mean iteration reward starts around average but quickly increases in the first few iterations before falling back. This may look like coincidence on this graph but I have observed the phenomenon countless times."></a></p></li> </ul> <p>Note: This is not an issue of the agent not finding a better path or a poor reward function not valuing good actions. </p> <p><a href="https://i.stack.imgur.com/Rj5zI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rj5zI.png" alt="Note that the max reward is an order of magnitude higher than the mean reward"></a></p> <p>Zooming out shows why mean reward peaked previously. The agent performed phenomenally but was never able to repeat anywhere near its success.</p> <p><a href="https://i.stack.imgur.com/UGwPi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UGwPi.png" alt="enter image description here"></a></p> <p>And, I cannot stress this enough, this is not an issue of me not letting the agent run for long enough. I have observed this same behavior across dozens of runs and cumulatively tens of thousands of iterations. I understand that it can take models a long time to converge, but the models consistently make <strong>zero</strong> progress.</p> <p><strong>tldr;</strong> My model doesn't change it's policy in any meaningful way despite getting very high rewards on certain runs.</p>
3
1,446
Using mutex to synchronize two kernel threads causes a system panic
<p>I used the mutex to synchronize the two kernel threads. After running, panic occurred in the system and abnormal memory was found in mutex by kdump.</p> <p>Here is a simplified code example, You can run it directly to reproduce the problem. I changed the memory allocation method to use kmalloc instead of vmalloc, and then it worked, Who knows why?</p> <pre class="lang-c prettyprint-override"><code>#include &lt;linux/module.h&gt; #include &lt;linux/kernel.h&gt; #include &lt;linux/init.h&gt; #include &lt;linux/delay.h&gt; #include &lt;linux/spinlock.h&gt; #include &lt;linux/mutex.h&gt; #include &lt;linux/kthread.h&gt; #include &lt;linux/slab.h&gt; struct product { struct list_head list; struct mutex lock; bool finish; }; struct task_struct *task1; struct task_struct *task2; spinlock_t spin; struct list_head products; struct product *create_product(void) { struct product *p_prod; p_prod = vmalloc(sizeof(struct product)); // p_prod = kmalloc(sizeof(struct product), GFP_KERNEL); if(!p_prod) return NULL; INIT_LIST_HEAD(&amp;p_prod-&gt;list); mutex_init(&amp;p_prod-&gt;lock); p_prod-&gt;finish = false; return p_prod; } void remove_product(struct product **pp_prod) { vfree(*pp_prod); // kfree(*pp_prod); *pp_prod = NULL; } int producer(void *data) { while(!kthread_should_stop()) { struct product *p_prod = create_product(); if(!p_prod) continue; spin_lock(&amp;spin); list_add_tail(&amp;p_prod-&gt;list, &amp;products); spin_unlock(&amp;spin); while (true) { mutex_lock(&amp;p_prod-&gt;lock); if(p_prod-&gt;finish) { mutex_unlock(&amp;p_prod-&gt;lock); schedule(); break; } mutex_unlock(&amp;p_prod-&gt;lock); } remove_product(&amp;p_prod); } do_exit(0); } int consumer(void *data) { while(!kthread_should_stop()) { struct product *p_prod; spin_lock(&amp;spin); if(list_empty(&amp;products)) { spin_unlock(&amp;spin); schedule(); continue; } p_prod = list_first_entry(&amp;products, struct product, list); list_del(&amp;p_prod-&gt;list); spin_unlock(&amp;spin); mutex_lock(&amp;p_prod-&gt;lock); p_prod-&gt;finish = true; mutex_unlock(&amp;p_prod-&gt;lock); } do_exit(0); } static int __init kdemo_init(void) { printk(&quot;&gt;&gt;&gt; demo driver begin!\n&quot;); spin_lock_init(&amp;spin); INIT_LIST_HEAD(&amp;products); task1 = kthread_run(producer, NULL, &quot;hdz-producer&quot;); task2 = kthread_run(consumer, NULL, &quot;hdz-consumer&quot;); return 0; } static void __exit kdemo_exit(void) { kthread_stop(task1); kthread_stop(task2); printk(&quot;&gt;&gt;&gt; demo driver exit!\n&quot;); } module_init(kdemo_init); module_exit(kdemo_exit); MODULE_LICENSE(&quot;GPL&quot;); MODULE_AUTHOR(&quot;xxxx@xxx.com&quot;); MODULE_VERSION(&quot;1.0&quot;); </code></pre> <p>dmesg log and consumer stack</p> <pre><code>[ 176.599116] &gt;&gt;&gt; demo driver begin! [ 177.167659] BUG: unable to handle kernel NULL pointer dereference at 0000000000000fb0 [ 177.167695] IP: [&lt;ffffffff9e0caa47&gt;] wake_q_add+0x17/0x50 [ 177.167719] PGD 0 [ 177.167729] Oops: 0002 [#1] SMP [ 177.167743] Modules linked in: kdemo(OE) mpt3sas mptctl mptbase nvmet_rdma nvmet nvme_rdma nvme_fabrics nvme nvme_core drbd(OE) dell_rbu kvdo(OE) uds(OE) bonding sha512_ssse3 sha512_generic qat_api(OE) usdm_drv(OE) intel_qat(OE) authenc uio ib_isert iscsi_target_mod ib_srpt target_core_mod ib_srp scsi_transport_srp scsi_tgt ib_ucm rpcrdma sunrpc rdma_ucm ib_umad ib_uverbs ib_iser rdma_cm ib_ipoib iw_cm libiscsi scsi_transport_iscsi ib_cm mlx5_ib ib_core intelcas(OE) inteldisk(OE) iTCO_wdt iTCO_vendor_support dell_smbios sparse_keymap dcdbas skx_edac intel_powerclamp coretemp intel_rapl iosf_mbi kvm irqbypass crc32_pclmul ghash_clmulni_intel aesni_intel lrw gf128mul glue_helper ablk_helper cryptd sg joydev pcspkr ipmi_si i2c_i801 lpc_ich shpchp ipmi_devintf ipmi_msghandler mei_me acpi_power_meter [ 177.168071] mei acpi_pad wmi nfit libnvdimm dm_multipath binfmt_misc ip_tables xfs libcrc32c mgag200 drm_kms_helper crc32c_intel syscopyarea sysfillrect sysimgblt mlx5_core fb_sys_fops ttm ixgbe drm igb mlxfw devlink mdio ptp i2c_algo_bit pps_core i2c_core dca sr_mod cdrom sd_mod crc_t10dif crct10dif_generic crct10dif_pclmul crct10dif_common ahci libahci libata mpt2sas raid_class scsi_transport_sas megaraid_sas dm_mirror dm_region_hash dm_log dm_mod [ 177.168263] CPU: 24 PID: 5412 Comm: hdz-consumer Kdump: loaded Tainted: G OE ------------ 3.10.0-862.el7.x86_64 #1 [ 177.168297] Hardware name: Dell Inc. PowerEdge R740/08D89F, BIOS 2.10.2 02/24/2021 [ 177.168320] task: ffff93db22af3f40 ti: ffff93dc89354000 task.ti: ffff93dc89354000 [ 177.168344] RIP: 0010:[&lt;ffffffff9e0caa47&gt;] [&lt;ffffffff9e0caa47&gt;] wake_q_add+0x17/0x50 [ 177.168372] RSP: 0018:ffff93dc89357e48 EFLAGS: 00010246 [ 177.168389] RAX: 0000000000000000 RBX: ffffbe2ce6533018 RCX: 0000000000000fb0 [ 177.168410] RDX: 0000000000000001 RSI: 0000000000000000 RDI: ffff93dc89357e58 [ 177.168432] RBP: ffff93dc89357e48 R08: ffffbe2ce6533000 R09: 0000000000000000 [ 177.168453] R10: 0000000000000001 R11: 0000000000000001 R12: ffffbe2ce6533014 [ 177.168475] R13: ffff93dc89357e58 R14: 0000000000000000 R15: 0000000000000000 [ 177.168497] FS: 0000000000000000(0000) GS:ffff93dca9400000(0000) knlGS:0000000000000000 [ 177.168540] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 177.168560] CR2: 0000000000000fb0 CR3: 00000002b7a0e000 CR4: 00000000007607e0 [ 177.168583] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 [ 177.168606] DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400 [ 177.168629] PKRU: 00000000 [ 177.168640] Call Trace: [ 177.168656] [&lt;ffffffff9e711b2e&gt;] __mutex_unlock_slowpath+0x5e/0x90 [ 177.168679] [&lt;ffffffff9e710fab&gt;] mutex_unlock+0x1b/0x20 [ 177.168699] [&lt;ffffffffc0637064&gt;] consumer+0x64/0x90 [kdemo] [ 177.168723] [&lt;ffffffffc0637000&gt;] ? 0xffffffffc0636fff [ 177.168746] [&lt;ffffffff9e0bae31&gt;] kthread+0xd1/0xe0 [ 177.168765] [&lt;ffffffff9e0bad60&gt;] ? insert_kthread_work+0x40/0x40 [ 177.168788] [&lt;ffffffff9e71f61d&gt;] ret_from_fork_nospec_begin+0x7/0x21 [ 177.168811] [&lt;ffffffff9e0bad60&gt;] ? insert_kthread_work+0x40/0x40 [ 177.168831] Code: 09 00 00 31 c9 31 d2 e8 18 41 ff ff eb e4 66 0f 1f 44 00 00 0f 1f 44 00 00 55 48 8d 8e b0 0f 00 00 31 c0 ba 01 00 00 00 48 89 e5 &lt;f0&gt; 48 0f b1 96 b0 0f 00 00 48 85 c0 74 0b 5d c3 66 0f 1f 84 00 [ 177.168996] RIP [&lt;ffffffff9e0caa47&gt;] wake_q_add+0x17/0x50 [ 177.169017] RSP &lt;ffff93dc89357e48&gt; [ 177.169959] CR2: 0000000000000fb0 </code></pre> <p>producer stask</p> <pre><code>crash&gt; bt 5411 PID: 5411 TASK: ffff93db22af4f10 CPU: 1 COMMAND: &quot;hdz-producer&quot; bt: page excluded: kernel virtual address: ffffffffffffffff type: &quot;cpu_online_map&quot; #0 [ffff93dca8e48e48] crash_nmi_callback at ffffffff9e0533b7 #1 [ffff93dca8e48e58] nmi_handle at ffffffff9e71790c #2 [ffff93dca8e48eb0] do_nmi at ffffffff9e717b2d #3 [ffff93dca8e48ef0] end_repeat_nmi at ffffffff9e716d79 #4 [ffff93dca8e48f28] __vmalloc_node_range at ffffffff9e1d7518 [exception RIP: mutex_unlock+20] RIP: ffffffff9e710fa4 RSP: ffff93ddafd73e98 RFLAGS: 00000202 RAX: 0000000000000010 RBX: 0000000000000010 RCX: 0000000000000202 RDX: ffff93ddafd73e98 RSI: 0000000000000018 RDI: 0000000000000001 RBP: ffffffff9e710fa4 R8: ffffffff9e710fa4 R9: 0000000000000018 R10: ffff93ddafd73e98 R11: 0000000000000202 R12: ffffffffffffffff R13: ffffbe2ce6535010 R14: ffffffffc0639240 R15: 0000000000000000 ORIG_RAX: ffffffffc0639240 CS: 0010 SS: 0018 --- &lt;(unknown) exception stack&gt; --- #5 [ffff93ddafd73e98] mutex_unlock at ffffffff9e710fa4 #6 [ffff93ddafd73ea0] producer at ffffffffc0637145 [kdemo] #7 [ffff93ddafd73ec8] kthread at ffffffff9e0bae31 #8 [ffff93ddafd73f50] ret_from_fork_nospec_begin at ffffffff9e71f61d </code></pre>
3
3,898
Merge Sort names alphabetically not working
<p>So I'm trying to sort names from a file alphabetically but it's not giving me the correct output. When entering 5 items, the output should be:</p> <p>British Virgin Islands, Hong Kong, Luxembourg, Maldives, New Zealand</p> <p>instead it gives an incorrect output of:</p> <p>Luxembourg, New Zealand, Maldives, New Zealand, Luxembourg</p> <p>NOTE: The starting index is index 1, instead of index 0</p> <pre><code> import java.io.*; import java.io.BufferedReader; import java.io.IOException; import java.util.Scanner; public class triall { public static void main(String[] args) { Scanner sc = new Scanner (System.in); Scanner in = new Scanner (System.in); System.out.print("Enter maximum number of items: "); int num = sc.nextInt(); String [] arr1 = new String [num+1]; //String [] arr2 = new String [num+1]; String sLine = ""; int i; try { FileInputStream fstream = new FileInputStream("ioc.txt"); BufferedReader bin = new BufferedReader(new InputStreamReader(fstream)); System.out.format("%-10s%-30s%-30s", "Index", "Array 1", "Array 2"); System.out.println(""); for ( i = 1; sLine != null &amp;&amp; i &lt;= num; i++) { sLine = bin.readLine(); arr1[i] = sLine; arr2[i] = sLine; if (sLine == null) System.out.println("EOF"); else { System.out.format("%-10d", i); System.out.format("%-30s", arr1[i]); System.out.format("%-30s\n", arr2[i]); } } sort (arr1); } // end try catch (IOException e) { e.printStackTrace(); } } public static void merge(String[] a, int from, int mid, int to) { int n1 = (mid - from + 1); int n2 = to - mid; // size of the range to be merged String[] left = new String[n1 + 1]; String [] right = new String[n2 + 1]; int i = 1; while ( i &lt;= n1) { left [i] = a[from + i - 1]; } int j = 1; while (j &lt;= n2) { right [j] = a[mid + j]; } i = 1; j = 1; int k = from; while (k &lt;= to) { if (left[i].compareToIgnoreCase(right[j]) &lt;= 0) { a[k] = left[i]; i++; } else { a[k] = right[j]; j++; } } for (i=1; i&lt;=to; i++) System.out.println(a[i]); } public static void mergeSort(String [] a, int from, int to) { if (from &lt; to) {int mid = (int) (Math.floor((from + to) / 2)); // sort the first and the second half mergeSort(a, from, mid); mergeSort(a, mid + 1, to); merge(a, from, mid, to);} } public static void sort(String[] a) { mergeSort(a, 1, a.length - 1); } } </code></pre>
3
2,403
warn message using hazelcast 3.3 during mapstore loadAll
<p>I am using Hazelcast v3.3. The Hazelcast server runs a few map store implementations. I have sporadically seen the following warning in the logs and need to understand what might be causing this and whether it could lead to data loss in hazelcast. I have a pretty small cluster at the moment for testing (4VMs running Ubuntu13 - 2GB RAM each). </p> <pre><code>2014-09-14 18:55:21,886 WARN c.h.s.i.BasicInvocation [main] [xxx.xxx.xxx.xxx]:5701 [testApp] [3.3] While asking 'is-executing': BasicInvocationFuture{invocation=BasicInvocation{ serviceName='hz: impl:mapService', op=com.hazelcast.spi.impl.PartitionIteratingOperation@285583d4, partitionId=-1, replicaIndex=0, tryCount=10, tryPauseMillis=300, invokeCount=1, callTimeout=60000, target=Address[xxx.xxx.xxx.xxx]:5701}, done=false} java.util.concurrent.TimeoutException: Call BasicInvocation{ serviceName='hz:impl:mapService', op=com.hazelcast.spi.impl.IsStillExecutingOperation@5b202ff, partit ionId=-1, replicaIndex=0, tryCount=0, tryPauseMillis=0, invokeCount=1, callTimeout=5000, target=Address[xxx.xxx.xxx.xxx]:5701} encountered a timeout at com.hazelcast.spi.impl.BasicInvocationFuture.resolveApplicationResponse(BasicInvocationFuture.java:321) at com.hazelcast.spi.impl.BasicInvocationFuture.resolveApplicationResponseOrThrowException(BasicInvocationFuture.java:289) at com.hazelcast.spi.impl.BasicInvocationFuture.get(BasicInvocationFuture.java:181) at com.hazelcast.spi.impl.BasicInvocationFuture.isOperationExecuting(BasicInvocationFuture.java:390) at com.hazelcast.spi.impl.BasicInvocationFuture.waitForResponse(BasicInvocationFuture.java:228) at com.hazelcast.spi.impl.BasicInvocationFuture.get(BasicInvocationFuture.java:180) at com.hazelcast.spi.impl.BasicInvocationFuture.get(BasicInvocationFuture.java:160) at com.hazelcast.spi.impl.BasicOperationService$InvokeOnPartitions.awaitCompletion(BasicOperationService.java:489) at com.hazelcast.spi.impl.BasicOperationService$InvokeOnPartitions.invoke(BasicOperationService.java:458) at com.hazelcast.spi.impl.BasicOperationService$InvokeOnPartitions.access$600(BasicOperationService.java:430) at com.hazelcast.spi.impl.BasicOperationService.invokeOnAllPartitions(BasicOperationService.java:293) at com.hazelcast.map.proxy.MapProxySupport.size(MapProxySupport.java:616) at com.hazelcast.map.proxy.MapProxyImpl.size(MapProxyImpl.java:72) at com.akkadian.wildmetrix.StartHcastServer.main(StartHcastServer.java:105) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58) </code></pre>
3
1,059
Prestashop - The following module(s) were not installed properly era_widget
<p>I tried to use the code below to create a new module but I got an error as the same title. Please help me check!</p> <pre><code>&lt;?php if (!defined('_PS_VERSION_')) exit; include_once(_PS_MODULE_DIR_ . 'era_widget/widgetModel.php'); /** * Description of era_widget * * @author nguye_000 */ class era_widget extends Module { private $_html = ''; function __construct() { $this-&gt;name = 'era_widget'; $this-&gt;tab = 'other'; $this-&gt;version = '1.0'; $this-&gt;author = 'Nam Nguyen'; $this-&gt;need_instance = 0; $this-&gt;secure_key = Tools::encrypt($this-&gt;name); $this-&gt;bootstrap = true; parent::__construct(); $this-&gt;displayName = $this-&gt;l('Era Widget'); $this-&gt;description = $this-&gt;l('Display widgets for sidebar or something'); } function install() { if (parent::install() &amp;&amp; $this-&gt;registerHook('displayHeader')){ $res = $this-&gt;createTable(); if ($res) { $this-&gt;installSamples(); } return $res; } return false; } function uninstall() { if (parent::uninstall()) { $res = $this-&gt;deleteTable(); return (bool)$res; } return false; } function hookdisplayHeader() { return $this-&gt;display(__FILE__, 'frontend.tpl'); } private function createTable() { $sql = "DROP TABLE IF EXISTS " . _DB_PREFIX_ . "`awidget`;CREATE TABLE " . _DB_PREFIX_ . "`awidget` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `key` varchar(255) NOT NULL, `value` longtext NOT NULL, `area` text NOT NULL COMMENT 'where to contains widget', `position` int(5) NOT NULL COMMENT 'order', `parent` bigint(20) NOT NULL COMMENT 'wrapper is parent or not', PRIMARY KEY (`id`), KEY `meta_key` (`key`) ) ENGINE=". _MYSQL_ENGINE_ ." DEFAULT CHARSET=utf8;"; $res = (bool) Db::getInstance()-&gt;execute($sql); return $res; } private function installSamples() { $sql = "insert into ". _DB_PREFIX_ . "`awidget`(`id`,`key`,`value`,`area`,`position`,`parent`) " . "values (1,'textwidget','a:2:{s:5:\"title\";s:14:\"The first text\";s:7:\"content\";s:232:\"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\";}','widget-area-sample',1,0);"; DB::getInstance()-&gt;execute($sql); } private function deleteTable() { return Db::getInstance()-&gt;execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'awidget`'); } } </code></pre> <p>P/S: I'm a newbie with prestashop. I do the same homeslider module but with no success. widgetModel.php and frontend.tpl are empty files :)</p>
3
1,418
What format must cells have for datarange for combobox in VBA?
<p>When I select a value in ComboBox1, ComboBox2 is automatically filled with data from a specified range. On selecting a value in ComboBox2 a corresponding value will be placed in a TextBox. It appears that when I have only numbers in the ComboBox value the code will not function. If the value consists of letters or numbers AND letters everything works just fine. I tried different formatting of the cells in the range, but no success. Finding an answer on internet is problematic as I don't know the keywords for searching.</p> <p>Here's my code so far:</p> <pre><code>Private Sub ComboBox1_Change() Dim index1 As Integer Dim cLoc1 As Range Dim index2 As Integer Dim cLoc2 As Range Dim ws As Worksheet Set ws = Worksheets("Formlists") index1 = ComboBox1.ListIndex 'index2 = ComboBox2.ListIndex ComboBox2.Clear ComboBox3.Clear Select Case index1 Case Is = 0 With ComboBox2 For Each cLoc1 In ws.Range("Codelist1") With Me.ComboBox2 .AddItem cLoc1.Value End With Next cLoc1 End With Case Is = 1 With ComboBox2 For Each cLoc1 In ws.Range("Codelist2") With Me.ComboBox2 .AddItem cLoc1.Value End With Next cLoc1 End With End Select End Sub  Private Sub combobox2_change() Dim index2 As Integer Dim ws As Worksheet Set ws = Worksheets("Formlists") index2 = ComboBox1.ListIndex Select Case index2 Case Is = 0 With TextBox4 For i = 1 To 10 If ws.Cells(i + 1, Columns(90).Column).Value = ComboBox2.Value Then TextBox4.Value = ws.Cells(i + 1, Columns(91).Column).Value Else 'do nothing End If Next i End With Case Is = 1 With TextBox4 For i = 1 To 10 If ws.Cells(i + 1, Columns(92).Column).Value = ComboBox2.Value Then TextBox4.Value = ws.Cells(i + 1, Columns(93).Column).Value Else 'do nothing End If Next i End With End Select End Sub </code></pre> <p>Is there a way to let the code/ComboBox accept any inputformat?</p> <p>Thanks in advance</p> <p>Rob</p>
3
1,227
Escaping Fields Array in CakePHP
<p>I currently have:</p> <pre><code>$subQuery = $dbo-&gt;buildStatement( array( 'fields' =&gt; array( "CASE WHEN Application.program_type_id = 3 AND Application.program_type_id IS NOT NULL THEN {$keys['program_type_id_program_type_id']} ELSE 0 END as program_type_score, CASE WHEN Application.priority_subject_area_id = 1 AND Application.priority_subject_area_id IS NOT NULL THEN {$keys['priority_subject_area_id_priority_subject_area_id']} ELSE 0 END as priority_subject_area_priority_subject_area_score, User.*" ), 'table' =&gt; $dbo-&gt;fullTableName($this), 'alias' =&gt; 'User', 'limit' =&gt; null, 'offset' =&gt; null, 'joins' =&gt; $joins, 'conditions' =&gt; array( 'Application.state' =&gt; 'accepted', 'Role.role' =&gt; 'mentor' ), 'order' =&gt; null, 'group' =&gt; null ), $this-&gt;User ); </code></pre> <p>I need to change the case statements from this:</p> <pre><code>CASE WHEN Application.program_type_id = 3 AND Application.program_type_id IS NOT NULL THEN {$keys['program_type_id_program_type_id']} ELSE 0 END as program_type_score </code></pre> <p>to this:</p> <pre><code>CASE WHEN Application.program_type_id = $user['User']['value'] AND Application.program_type_id IS NOT NULL THEN {$keys['program_type_id_program_type_id']} ELSE 0 END as program_type_score </code></pre> <p>How do I escape <code>$user['User']['value']</code>? Would Sanitize::escape() work, however, it is already deprecated.</p>
3
1,327
Incorrect file output using arrays
<p>Hello everyone I am just learning my first programming language and have just corrected one error in my code only to be left with another error. Thankfully this is the last problem I need to solve but I'm having a little trouble doing it myself.</p> <p>The program is to read in a customer number and expenses associated with each customer number. It will then add a finance charge, output all expenses, total everything, and save each customers new balance to file along with their ID number in reverse order.</p> <p>beginningbalance.dat looks like </p> <pre><code>111 200.00 300.00 50.00 222 300.00 200.00 100.00 </code></pre> <p>and newbalances.dat SHOULD look like </p> <pre><code>222 402.00 111 251.00 </code></pre> <p>except depending on where in put the "count--" in the file writing loop, I end up with </p> <pre><code>222 402.00 111 251.00 -858993460 -92559631349317830000000000000000000000000000000000000000000000.00 </code></pre> <p>I can't figure out what I should do to get rid of these extra values. Any suggestions?</p> <p>Here is my code</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;iomanip&gt; using namespace std; int main() { int count = 0; const int size = 100; double customer_beg_balance, customer_purchases, customer_payments, finance_charge_cost, finance_charge = .01; int customer_number[size]; double new_balance[size]; double total_beg_balances=0,total_finance_charges=0,total_purchases=0,total_payments=0,total_end_balances=0; ifstream beginning_balance; beginning_balance.open("beginningbalance.dat"); while(beginning_balance&gt;&gt;customer_number[count]) { beginning_balance &gt;&gt; customer_beg_balance; beginning_balance &gt;&gt; customer_purchases; beginning_balance &gt;&gt; customer_payments; finance_charge_cost = customer_beg_balance * finance_charge; new_balance[count] = customer_beg_balance + finance_charge_cost + customer_purchases - customer_payments; total_beg_balances+=customer_beg_balance; total_finance_charges+=finance_charge_cost; total_purchases+=customer_purchases; total_payments+=customer_payments; total_end_balances+=new_balance[count]; cout&lt;&lt;fixed&lt;&lt;setprecision(2)&lt;&lt;setw(8)&lt;&lt;"Cust No "&lt;&lt;"Beg. Bal. "&lt;&lt;"Finance Charge "&lt;&lt;"Purchases "&lt;&lt;"Payments "&lt;&lt;"Ending Bal.\n" &lt;&lt;customer_number[count]&lt;&lt;" "&lt;&lt;customer_beg_balance&lt;&lt;" "&lt;&lt;finance_charge_cost&lt;&lt;" "&lt;&lt;customer_purchases&lt;&lt;" "&lt;&lt;customer_payments&lt;&lt;" "&lt;&lt;new_balance[count]&lt;&lt;endl; count++; } cout&lt;&lt;"\nTotals "&lt;&lt;total_beg_balances&lt;&lt;" "&lt;&lt;total_finance_charges&lt;&lt;" "&lt;&lt;total_purchases&lt;&lt;" "&lt;&lt;total_payments&lt;&lt;" "&lt;&lt;total_end_balances&lt;&lt;endl; ofstream new_balance_file; new_balance_file.open("NewBalance.dat"); while(count &gt;= 0) { count--; new_balance_file &lt;&lt;customer_number[count]&lt;&lt;endl; new_balance_file&lt;&lt; fixed&lt;&lt;setprecision(2)&lt;&lt;new_balance[count]&lt;&lt;endl; } new_balance_file.close(); system("pause"); return 0; } </code></pre>
3
1,399
sparql slow if more object value specified
<p>Using virtuoso 7 open source edition,</p> <p>This query below is fast, it return the result instantly,</p> <pre><code>select * WHERE { graph &lt;http://localhost:8890/graph&gt; { ?catAtt qq:catId ?catId; qq:caDataType ?caDataType; qq:showInView ?showInview; qq:valFormat ?valFormatKey; qq:multiple ?multiple; qq:position ?position; qq:link ?link; qq:catAttName ?catAttName; qq:setting ?setting; qq:flag ?flag; qq:unit ?caUnit. } } LIMIT 20 </code></pre> <p>This query is so slow, took 10 seconds for the result, the only difference is the ?catId is replaced with literal value 1</p> <pre><code>select * WHERE { graph &lt;http://localhost:8890/graph&gt; { ?catAtt qq:catId 1; qq:caDataType ?caDataType; qq:showInView ?showInview; qq:valFormat ?valFormatKey; qq:multiple ?multiple; qq:position ?position; qq:link ?link; qq:catAttName ?catAttName; qq:setting ?setting; qq:flag ?flag; qq:unit ?caUnit. } } LIMIT 20 </code></pre> <p>Why is it so ? I am still new in sparql and triplestore, seems like I have to do some indexing on the object ?</p> <p>EDIT :</p> <p>I have tried creating the GOPS index with, I don't understand about the Partition part, is using O correct ? What does that partition mean ? Creating this index has improved the execution for the second query to 4 seconds, but still too slow for a DBMS.</p> <pre><code>CREATE COLUMN INDEX RDF_QUAD_GOPS ON RDF_QUAD (G, O, P, S) PARTITION (O VARCHAR (-1, 0hexffff)); </code></pre>
3
1,519
Odd centering CSS problem in modern non-Chrome browsers?
<p>For some reason, I have this one webpage which renders something great in Chrome, but completely different on FireFox and IE.</p> <p>The effect may be seen <a href="http://www.tiletabs.com/v2.htm" rel="nofollow">here</a>.</p> <p>The other browsers appear to remove my margin centering of my <code>header</code> and <code>footer</code> elements.</p> <p>Is there a particular reason this is only working in Chrome?</p> <p>Here is my HTML:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;TileTabs&lt;/title&gt; &lt;link rel="shortcut icon" type="image/x-icon" href="images/favicon/favicon.ico"&gt; &lt;link rel="stylesheet" href="css/v2.css" type="text/css"&gt; &lt;link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/themes/base/jquery-ui.css" type="text/css"&gt; &lt;link rel="stylesheet" href="css/veramono.css" type="text/css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;script src="js/tile_interaction.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;img src="images/logo/logo_v3.png" alt="logo" /&gt; &lt;/header&gt; &lt;div id="content"&gt; &lt;ul&gt; &lt;li&gt; &lt;div class="tile"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="tile"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="tile"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="tile"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="tile"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="tile"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="tile"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="tile"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="tile"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="tile"&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;footer&gt; &lt;a class="emailus" href="index.htm"&gt;Home&lt;/a&gt; | &lt;a class="emailus" href="about.htm"&gt;About&lt;/a&gt; | &lt;a class="emailus" href="contact.htm"&gt;Contact&lt;/a&gt; &lt;/footer&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS:</p> <pre><code>body { background: #F6F6F6; font-family: 'BitstreamVeraSansMonoRoman', 'Myriad-Pro', 'Myriad', helvetica, arial, sans-serif; margin: 0; } a:link, a:visited, a:hover, a:active { color: white; text-decoration: none; } header { width: 920px; background: #999; margin: 0px auto; text-align: center; -webkit-border-top-left-radius: 20px; -webkit-border-top-right-radius: 20px; -moz-border-radius-topleft: 20px; -moz-border-radius-topright: 20px; border-top-left-radius: 20px; border-top-right-radius: 20px; } #content { width: 920px; height: 760px; background: #999; margin: 0px auto; } footer { width: 920px; background: #999; margin: 0px auto; text-align: center; padding-top: 10px; padding-bottom: 10px; -webkit-border-bottom-right-radius: 20px; -webkit-border-bottom-left-radius: 20px; -moz-border-radius-bottomright: 20px; -moz-border-radius-bottomleft: 20px; border-bottom-right-radius: 20px; border-bottom-left-radius: 20px; } li { float: left; list-style: none; padding: 34px; } .tile { cursor: pointer; background: red; border: 2px solid #000; width: 100px; height: 100px; } </code></pre>
3
2,297
MySql query not using indexes set
<p>Recently we switched a db from MariaDB 10.2 to Percona Server (Mysql 5.7) and we have a query that is taking about 15 seconds (before it was about 0.5) because the query optimiser is not using any index on the main table. Because the app logic, we can't change the query format, we need to make the DB to use an index.</p> <p>The query structure is simple:</p> <pre><code>EXPLAIN SELECT `clients`.`id` AS `t0_c0`, `client`.`name1` AS `t0_c1`, `client`.`name2` AS `t0_c2`, `users`.`id` AS `t1_c0`, `users`.`suffix` AS `t1_c1`, `users`.`position` AS `t1_c2`, `users`.`first_name` AS `t1_c3`, `users`.`last_name` AS `t1_c4`, `privateData`.`id` AS `t2_c0`, `privateData`.`first_name` AS `t2_c1`, `privateData`.`last_name` AS `t2_c2`, `tariff`.`id` AS `t3_c0`, `tariff`.`provider_id` AS `t3_c1`, `tariff`.`tariff_type` AS `t3_c2`, `tariff`.`name` AS `t3_c3`, `providers`.`id` AS `t4_c0`, `providers`.`name1` AS `t4_c1`, `providers`.`name2` AS `t4_c2`, `addresses`.`id` AS `t5_c0`, `addresses`.`zipcode` AS `t5_c1`, `addresses`.`country` AS `t5_c2`, `addresses`.`city` AS `t5_c3`, `private`.`id` AS `t6_c0`, `private`.`first_name` AS `t6_c1`, `private`.`last_name` AS `t6_c2`, `commercial`.`id` AS `t7_c0`, `commercial`.`name1` AS `t7_c1`, `commercial`.`name2` AS `t7_c2`, `commercial`.`name_on_invoice` AS `t7_c3`, `commercial`.`organization_type` AS `t7_c4`, `organizations`.`id` AS `t8_c0`, `organizations`.`person_id` AS `t8_c1`, `organizations`.`address_id` AS `t8_c2`, `organizations`.`status` AS `t8_c3`, `shaddresses`.`id` AS `t9_c0`, `shaddresses`.`zipcode` AS `t9_c1`, `shaddresses`.`country` AS `t9_c2`, `shaddresses`.`city` AS `t9_c3`, `shprivate`.`id` AS `t10_c0`, `shprivate`.`first_name` AS `t10_c1`, `shprivate`.`last_name` AS `t10_c2`, `coraddresses`.`id` AS `t11_c0`, `coraddresses`.`zipcode` AS `t11_c1`, `coraddresses`.`country` AS `t11_c2`, `corprivate`.`id` AS `t12_c0`, `corprivate`.`first_name` AS `t12_c1`, `corprivate`.`last_name` AS `t12_c2`, FROM `client` `client` LEFT OUTER JOIN `users` `users` ON (`client`.`user_id`=`users`.`id`) AND (users.status!=5) LEFT OUTER JOIN `private` `privateData` ON (`users`.`person_id`=`privateData`.`id`) LEFT OUTER JOIN `tariff` `tariff` ON (`client`.`rate_id`=`tariff`.`id`) LEFT OUTER JOIN `providers` `providers` ON (`client`.`provider_id`=`providers`.`id`) LEFT OUTER JOIN `addresses` `addresses` ON (`client`.`main_address_id`=`addresses`.`id`) LEFT OUTER JOIN `private` `private` ON (`client`.`main_person_id`=`private`.`id`) LEFT OUTER JOIN `commercial` `commercial` ON (`client`.`main_organization_id`=`commercial`.`id`) LEFT OUTER JOIN `organizations` `organizations` ON (`client`.`id_organization`=`organizations`.`id`) AND (organizations.status!=5) LEFT OUTER JOIN `addresses` `shaddresses` ON (`client`.`shipping_address_id`=`shaddresses`.`id`) LEFT OUTER JOIN `private` `shprivate` ON (`client`.`shipping_person_id`=`shprivate`.`id`) LEFT OUTER JOIN `addresses` `coraddresses` ON (`client`.`correspondense_address_id`=`coraddresses`.`id`) LEFT OUTER JOIN `private` `corprivate` ON (`client`.`correspondense_person_id`=`corprivate`.`id`) WHERE (client.status!=5) ORDER BY client.id DESC LIMIT 10 OFFSET 10 </code></pre> <p>I can change any INDEX, but, I can't change the query. On the old host it was running in 0.2 second, but , the optimiser it was using indexes from clients table. With Percona Server (mysql 5.7) it is taking 15 seconds. Optimiser is not ussing any index from clients table. With FORCE INCEX() from clients table is going under 1 second (with compound index is going in about 0.2 seconds). Table 'providers' it has only 1 line. I have set indexes on 'clients' table, but, in explain they are not shows as posible keys.</p> <p>I tried to set the MySql variable 'max_seeks_for_key' to 1, but, it is still not using indexes.</p> <p>I think that I'm missing something basic, but I can't figure it out what.</p> <p>EXPLAIN for this query is:</p> <p><a href="https://i.stack.imgur.com/HoD6s.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HoD6s.jpg" alt="enter image description here"></a></p> <p>ORDER BY is generating TEMPORARY TABLE and that is ussing all of the resources (without order by is running in under one second, even without INDEX). </p> <p>Any ideea is apreciated.</p>
3
2,023
Extend a row with rowise() %>% do() when do() returns a vector
<p>How do I make this code more tidy?</p> <pre><code>as_tibble(t(mapply(pmf, x=lhs$mu, y=lhs$sigma))) </code></pre> <p>Here <code>pmf()</code> is a helper function.</p> <pre><code>pmf &lt;- function(x, y) diff(pnorm(c(-Inf, -2, 0, 2, Inf), x, y)) </code></pre> <p>This code takes the mean and standard deviation from each row, and returns the probability mass function (PMF) for each bin.</p> <p>So this</p> <pre><code># A tibble: 6 x 4 i j mu sigma &lt;int&gt; &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; 1 1 1 1.890402 2.879148 2 1 2 1.202357 2.655255 3 1 3 1.186224 2.127293 4 1 4 1.222278 2.228819 5 1 5 1.760214 2.324657 6 2 1 1.726712 2.574771 </code></pre> <p>becomes this</p> <pre><code># A tibble: 6 x 8 i j mu sigma V1 V2 V3 V4 &lt;int&gt; &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 1 1 1.890402 2.879148 0.08831027 0.1674140 0.2594582 0.4848175 2 1 2 1.202357 2.655255 0.11390009 0.2114385 0.2927260 0.3819354 3 1 3 1.186224 2.127293 0.06709483 0.2214568 0.3604183 0.3510301 4 1 4 1.222278 2.228819 0.07412598 0.2175836 0.3447228 0.3635676 5 1 5 1.760214 2.324657 0.05288144 0.1715857 0.3166106 0.4589223 6 2 1 1.726712 2.574771 0.07389306 0.1773358 0.2910357 0.4577354 </code></pre> <p>after I use <code>bind_cols()</code> to add back the output.</p> <p>I tried the following (using the same <code>pmf()</code> helper function).</p> <pre><code>pmf &lt;- function(x, y) diff(pnorm(c(-Inf, -2, 0, 2, Inf), x, y)) lhs %&gt;% rowwise() %&gt;% do(k = pmf(.$mu, .$sigma)) </code></pre> <p>But it returns the PMF as a list. I would like the PMF as a row. This doesn't work for me because downstream I need to apply a function across the rows on each column <code>V#</code>.</p> <p>Is it possible to make this calculation more tidy?</p> <p>FWIW, here is the full calculation.</p> <pre><code>library(tidyverse) # find PMF from mu and sigma pmf &lt;- function(x, y) diff(pnorm(c(-Inf, -2, 0, 2, Inf), x, y)) # find mean*variance for each column (i.e., PMF bin) __across rows___ mean_var &lt;- function(x) mean(x)*var(x) # here are my data lhs &lt;- tibble(i = rep(1:2, each=5), j = rep(1:5, times=2), mu = 1 + runif(2*5), sigma = 2 + runif(2*5)) # find PMF from mu and sigma rhs &lt;- as_tibble(t(mapply(pmf, x=lhs$mu, y=lhs$sigma))) # downstream calculations ans &lt;- lhs %&gt;% bind_cols(rhs) %&gt;% group_by(i) %&gt;% summarise_at(vars(starts_with('V')), funs(mean_var)) %&gt;% gather(bin, mean_var, -i) %&gt;% group_by(i) %&gt;% summarise(ambg = sum(mean_var)) # this finds PMF from mu and sigma, but as a list; I need a row lhs %&gt;% rowwise() %&gt;% do(k = pmf(.$mu, .$sigma)) </code></pre>
3
1,491
enum and static const member variable usage in template trait class
<p>I want to test whether a class is streamable to <code>ostream&amp;</code> by seeing whether an overload for <code>operator&lt;&lt;</code> is provided. Based on <a href="https://stackoverflow.com/questions/6534041/how-to-check-whether-operator-exists">these</a> <a href="https://stackoverflow.com/questions/5768511/using-sfinae-to-check-for-global-operator">posts</a>, I tried to write another version using C++11. This is my attempt:</p> <pre><code>#include &lt;iostream&gt; #include &lt;type_traits&gt; namespace TEST{ class NotDefined{}; template&lt;typename T&gt; NotDefined&amp; operator &lt;&lt; (::std::ostream&amp;, const T&amp;); template &lt;typename T&gt; struct StreamInsertionExists { static std::ostream &amp;s; static T const &amp;t; enum { value = std::is_same&lt;decltype(s &lt;&lt; t), NotDefined&gt;() }; }; } struct A{ int val; friend ::std::ostream&amp; operator&lt;&lt;(::std::ostream&amp;, const A&amp;); }; ::std::ostream&amp; operator&lt;&lt;(::std::ostream&amp; os, const A&amp; a) { os &lt;&lt; a.val; return os; } struct B{}; int main() { std::cout &lt;&lt; TEST::StreamInsertionExists&lt;A&gt;::value &lt;&lt; std::endl; std::cout &lt;&lt; TEST::StreamInsertionExists&lt;B&gt;::value &lt;&lt; std::endl; } </code></pre> <p>But this fails to compile:</p> <blockquote> <pre><code>test_oper.cpp:40:57: error: reference to overloaded function could not be resolved; did you mean to call it? std::cout &lt;&lt; TEST::StreamInsertionExists&lt;A&gt;::value &lt;&lt; std::endl; /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/ostream:1020:1: note: possible target for call endl(basic_ostream&lt;_CharT, _Traits&gt;&amp; __os) test_oper.cpp:30:17: note: candidate function not viable: no known conversion from 'TEST::NotDefined' to '::std::ostream &amp;' (aka 'basic_ostream&lt;char&gt; &amp;') for 1st argument ::std::ostream&amp; operator&lt;&lt;(::std::ostream&amp; os, const A&amp; a) test_oper.cpp:15:15: note: candidate template ignored: couldn't infer template argument 'T' NotDefined&amp; operator &lt;&lt; (::std::ostream&amp;, const T&amp;); </code></pre> </blockquote> <p>However, if I replace the line<br> <code>enum { value = std::is_same&lt;decltype(s &lt;&lt; t), NotDefined&gt;() };</code><br> with<br> <code>static const bool value = std::is_same&lt;decltype(s &lt;&lt; t), NotDefined&gt;();</code><br> then everything compiles. </p> <p>Why is there such a difference between the <code>enum</code> and the <code>bool</code>?</p>
3
1,048
jquery gallery not visible when overlay is hidden by default
<p>I have a jquery gallery which is placed inside of full screen absolutely positioned element and by default that element is hidden with <code>display: none</code> until you click a button and then that element is shown with jquery <code>.show()</code>. The problem is that when I click on a button, that fullscreen element is shown but everything inside that element (jquery gallery) is not visible. Only the fullscreen element is shown. When i remove the display none for the fullscreen element (so its shown on load) the gallery (or the content) is visible. Also in the case when its hidden by default and displays only the fullscreen element and not what is inside of it (gallery) when i resize the browser the gallery is shown? </p> <p>DEMO: <a href="http://codepen.io/riogrande/pen/WxxjvJ" rel="nofollow noreferrer">http://codepen.io/riogrande/pen/WxxjvJ</a></p> <p>HTML </p> <pre><code>&lt;div class="gallery"&gt; &lt;div class="demo"&gt; &lt;ul id="lightSlider"&gt; &lt;li data-thumb="static/images/galerija/thumbs/15.jpg"&gt; &lt;img src="static/images/galerija/15.jpg" alt="galerija"/&gt; &lt;/li&gt; &lt;li data-thumb="static/images/galerija/thumbs/16.jpg"&gt; &lt;img src="static/images/galerija/16.jpg" alt="galerija"/&gt; &lt;/li&gt; &lt;li data-thumb="static/images/galerija/thumbs/17.jpg"&gt; &lt;img src="static/images/galerija/17.jpg" alt="galerija"/&gt; &lt;/li&gt; &lt;li data-thumb="static/images/galerija/thumbs/18.jpg"&gt; &lt;img src="static/images/galerija/18.jpg" alt="galerija"/&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="close-gallery"&gt; &lt;img src="static/images/close.png" alt="close"&gt; Zatvori galeriju &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>gallery { position: absolute; width: 100%; height: 100%; background: #2a2d2c; z-index: 99999; top: 0; bottom: 0; right: 0; left: 0; display: none; .close-gallery { position: absolute; right: 5%; top: 5%; z-index: 1000; cursor: pointer; color: white; font-size: 1.2rem; img { vertical-align: middle; margin-right: 10px; } } } </code></pre> <p>JQUERY (THE SLIDER IS LightSlider) </p> <pre><code>$(document).ready(function () { $('#lightSlider').lightSlider({ gallery: true, item: 1, loop: true, slideMargin: 0, thumbItem: 9 }); }); $('.galerija-gumb').click(function () { $('.gallery').show(); $('body').scrollTop(0); }); $('.close-gallery').click(function () { $('.gallery').hide(); var slider = $('#lightslider').lightSlider(); }); </code></pre> <p>So when i click to open a gallery, only the overlay, fullscreen element is displayed</p> <p><a href="https://i.stack.imgur.com/3sRbH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3sRbH.png" alt="only overlay is displayed"></a></p> <p>When i resize the gallery is shown??</p> <p><a href="https://i.stack.imgur.com/2Qple.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Qple.png" alt="after resize gallery appears"></a></p> <p>When i remove the display block from CSS (so the fullscreen is shown all time) the gallery is loaded normally</p> <p><a href="https://i.stack.imgur.com/2yYfz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2yYfz.png" alt="enter image description here"></a></p> <p>DEMO: <a href="http://codepen.io/riogrande/pen/WxxjvJ" rel="nofollow noreferrer">http://codepen.io/riogrande/pen/WxxjvJ</a></p>
3
1,640
How can I use zope.schema to group portal types into categories?
<p>I need to create a Plone configlet that delivers this kind of structure:</p> <pre><code>types = { 'News articles': ['NewsMediaType', 'News Item'], 'Images': ['Image'], 'Pages': ['Page'] } </code></pre> <p>I made a prototype to show what I was thinking to have in the form:</p> <p><img src="https://i.stack.imgur.com/bqyo5.png" alt="mockup"></p> <p>So I need to group some portal_types together and let the user assign a name for this group. How can I do that? Any ideas?</p> <p>edited:</p> <p>I made a great progress with the problem, but when save the form, validation give me an error</p> <p><img src="https://i.stack.imgur.com/pbDb0.png" alt="enter image description here"></p> <pre><code> # -*- coding: utf-8 -*- from plone.theme.interfaces import IDefaultPloneLayer from z3c.form import interfaces from zope import schema from zope.interface import Interface from plone.registry.field import PersistentField class IThemeSpecific(IDefaultPloneLayer): """ """ class PersistentObject(PersistentField, schema.Object): pass class IAjaxsearchGroup(Interface): """Global akismet settings. This describes records stored in the configuration registry and obtainable via plone.registry. """ group_name = schema.TextLine(title=u"Group Name", description=u"Name for the group", required=False, default=u'',) group_types = schema.List(title=u"Portal Types", description=u"Portal Types to search in this group", value_type =schema.Choice( title=u"Portal Types", vocabulary=u"plone.app.vocabularies.ReallyUserFriendlyTypes", required=False, ), required=False,) class IAjaxsearchSettings(Interface): """Global akismet settings. This describes records stored in the configuration registry and obtainable via plone.registry. """ group_info = schema.Tuple(title=u"Group Info", description=u"Informations of the group", value_type=PersistentObject(IAjaxsearchGroup, required=False), required=False,) </code></pre> <p>-</p> <pre><code>from plone.app.registry.browser import controlpanel from collective.ajaxsearch.interfaces.interfaces import IAjaxsearchSettings from collective.ajaxsearch.interfaces.interfaces import IAjaxsearchGroup from z3c.form.object import registerFactoryAdapter class AjaxsearchSettingsEditForm(controlpanel.RegistryEditForm): schema = IAjaxsearchSettings label = u"Ajaxsearch settings" description = u"""""" def updateFields(self): super(AjaxsearchSettingsEditForm, self).updateFields() def updateWidgets(self): super(AjaxsearchSettingsEditForm, self).updateWidgets() class AjaxsearchSettingsControlPanel(controlpanel.ControlPanelFormWrapper): form = AjaxsearchSettingsEditForm </code></pre>
3
1,254
Created table, but where is it?
<p>I set up and connected a derby database called <code>timezonedb</code> <img src="https://i.stack.imgur.com/ZLZ8h.png" alt="database development view"> Then I used the SQL scrapbook to create the table <code>Users</code>. <img src="https://i.stack.imgur.com/1x45v.png" alt="SQL Scrapbook configuration"> <img src="https://i.stack.imgur.com/es5FH.png" alt="enter image description here"></p> <p>As you can see, the table was successfully created, added to, and queried via the scrapbook. The problem is, it doesn't seem to be in any of the schemas listed in timezonedb. When I try to run my program, it seems to think that password is a schema. Java code involved below:</p> <pre><code> package cis407; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.util.Date; import java.util.TimeZone; import java.util.logging.Logger; import javax.annotation.Resource; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.sql.DataSource; /** This bean formats the local time of day for a given date and city. */ @ManagedBean @SessionScoped public class TimeZoneBean { @Resource(name="jdbc/__default") private DataSource source; private String userName; private String password; private DateFormat timeFormatter; private String city; private TimeZone zone; private String errorMessage; /** Initializes the formatter. */ public TimeZoneBean() { timeFormatter = DateFormat.getTimeInstance(); } public String getPassword() { return password; } /** * setter for password property * there is no getter for the password because there is no reason to ever * return the password * @param password the password for a given user */ public void setPassword(String pass) { password = pass; } /** * getter for applicable error message * @return the error message */ public String getErrorMessage() { return errorMessage; } /** * Setter for username property * @param name the user who is logged in */ public void setUserName(String name) { userName = name; } /** * getter for username property * @return the user who is logged in */ public String getUserName() { return userName; } /** Setter for city property. @param aCity the city for which to report the local time */ public void setCity(String aCity) { city = aCity; } /** Getter for city property. @return the city for which to report the local time */ public String getCity() { return city; } /** Read-only time property. @return the formatted time */ public String getTime() { if (zone == null) return "not available"; timeFormatter.setTimeZone(zone); Date time = new Date(); String timeString = timeFormatter.format(time); return timeString; } /** Action for checking a city. @return "next" if time zone information is available for the city, "error" otherwise * @throws SQLException */ public String checkCity() throws SQLException { zone = getTimeZone(city); if (zone == null) return "error"; addCity(); return "next"; } public String newUser() throws SQLException { if (source == null) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(null, "No database connection");; return null; } Connection conn = source.getConnection(); try { PreparedStatement stat = conn.prepareStatement( "SELECT UserName " + "FROM Users " + "WHERE UserName=?"); stat.setString(1, userName); ResultSet result = stat.executeQuery(); if (result.next()) { errorMessage = "There is already a user with that name. Please choose another."; return "login"; } else { errorMessage = ""; stat = conn.prepareStatement( "INSERT INTO Users" + "VALUES (?, ?, ?)"); stat.setString(1, userName); stat.setString(2, password); stat.setString(3, null); stat.executeUpdate(); return "index"; } } finally { conn.close(); } } public String logIn() throws SQLException { if (source == null) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(null, "No database connection");; return null; } Connection conn = source.getConnection(); try { PreparedStatement stat = conn.prepareStatement( "SELECT FavCity FROM Users WHERE UserName=? AND Password=?"); stat.setString(1, userName); stat.setString(2, password); ResultSet result = stat.executeQuery(); if (result.next()) { city = result.getString("FavCity"); errorMessage = ""; return "next"; } else { errorMessage = "Wrong username or password"; return "login"; } } finally { conn.close(); } } private void addCity() throws SQLException { if (source == null) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(null, "No database connection");; return; } Connection conn = source.getConnection(); try { PreparedStatement stat = conn.prepareStatement( "UPDATE Users " + "SET FavCity=? " + "WHERE UserName=?"); stat.setString(1, city); stat.setString(2, userName); stat.executeUpdate(); } finally { conn.close(); } } /** Looks up the time zone for a city. @param aCity the city for which to find the time zone @return the time zone or null if no match is found */ private static TimeZone getTimeZone(String aCity) { String[] ids = TimeZone.getAvailableIDs(); for (int i = 0; i &lt; ids.length; i++) if (timeZoneIDmatch(ids[i], aCity)) return TimeZone.getTimeZone(ids[i]); return null; } /** Checks whether a time zone ID matches a city. @param id the time zone ID (e.g. "America/Los_Angeles") @param aCity the city to match (e.g. "Los Angeles") @return true if the ID and city match */ private static boolean timeZoneIDmatch(String id, String aCity) { String idCity = id.substring(id.indexOf('/') + 1); return idCity.replace('_', ' ').equals(aCity); } } </code></pre> <p>Upon executing <code>logIn()</code> from clicking a button in the webapp (there are some xhtml files that I am pretty sure are not the problem so I didn't include them) I get an error saying that there is no schema "password". I'm really confused about what is going on here, as this isn't something I've done before and I'm trying to figure it out on my own. I think it might not be finding the table. I'm using GlassFish, and I've been messing around with the JDBC settings in its admin console, but there's so much stuff that I'm having a hard time figuring out where or what the problem is.</p> <p>The exact error is: </p> <pre><code>type Exception report messageInternal Server Error description The server encountered an internal error that prevented it from fulfilling this request. exception javax.servlet.ServletException: java.sql.SQLSyntaxErrorException: Schema 'PASSWORD' does not exist root cause javax.faces.el.EvaluationException: java.sql.SQLSyntaxErrorException: Schema 'PASSWORD' does not exist root cause java.sql.SQLSyntaxErrorException: Schema 'PASSWORD' does not exist root cause org.apache.derby.client.am.SqlException: Schema 'PASSWORD' does not exist </code></pre>
3
2,931
flutter problem: change state of bottomSheet
<p>Here I want to change my Icon when first time will click on &quot;A-Z Alphabetically&quot; then my isSelectAlpha will be true then my Icon will be &quot;UP&quot; when I click again on &quot;A-Z Alphabetically&quot; then will be change &quot;DOWN&quot; icon.</p> <p>But Its not working when I reload the page then my Icon is Changing.</p> <p>This is my bottomSheet code</p> <pre><code> var isSelectAlpha; bottomSheet() { showModalBottomSheet( context: context, // shape: const RoundedRectangleBorder( // borderRadius: BorderRadius.vertical( // top: Radius.circular(25.0), // ), // ), builder: (context) { return Padding( padding: const EdgeInsets.fromLTRB(20, 20, 20, 13), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: &lt;Widget&gt;[ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( &quot;Filter&quot;, style: TextStyle( fontSize: tSize18, fontWeight: FontWeight.w500), ), Text( &quot;Clear&quot;, style: TextStyle( fontSize: tSize14, fontWeight: FontWeight.w500, color: skyBlue), ), ], ), SizedBox( height: 20, ), Divider(thickness: 2), SizedBox( height: 10, ), Text( &quot;Short&quot;, style: TextStyle(fontSize: tSize18, fontWeight: FontWeight.w500), ), SizedBox( height: 20, ), InkWell( onTap: () { if (isSelectAlpha == null) { isSelectAlpha = false; } alphabeticallyFunc(); }, child: Container( height: 35, child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ isSelectAlpha == true ? Icon(Icons.arrow_upward) : isSelectAlpha == false ? Icon( Icons.arrow_downward):Container(), SizedBox( width: 10, ), Text( &quot;A-Z&quot;, style: TextStyle( fontSize: tSize16, fontWeight: FontWeight.w500), ), SizedBox( width: 15, ), Text( &quot;Alphabetically&quot;, style: TextStyle( fontSize: tSize14, fontWeight: FontWeight.w400, color: darkGreyColor), ), ], ), )), Divider(), InkWell( onTap: () {}, child: Container( height: 35, child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( &quot;Invested Value&quot;, style: TextStyle( fontSize: tSize16, fontWeight: FontWeight.w500), ), SizedBox( width: 15, ), ], ), )), Divider(), InkWell( onTap: () { // searchHoldingsList.sort((a, b) =&gt; b[&quot;invested_value&quot;].compareTo(a[&quot;invested_value&quot;])); investFunc(); }, child: Container( height: 35, child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( &quot;Profit &amp; Loss&quot;, style: TextStyle( fontSize: tSize16, fontWeight: FontWeight.w500), ), SizedBox( width: 15, ), ], ), )), ], ), ); }); } </code></pre> <p>this is my anotherFunction Whitch is change my bool</p> <pre><code> alphabeticallyFunc() { print(&quot;alphabetically&quot;); isSelectAlpha = !isSelectAlpha; print(isSelectAlpha); setState(() {}); } </code></pre> <p>How to do it please help.</p>
3
3,688
How to save video playing currentTime in Laravel using ajax
<p>This is my route which shows the lesson.</p> <pre><code>Route::get('/lession_video/{lession_id}','FrontendCommonController@lession_video')-&gt;name('lession_video'); </code></pre> <p>Here is my another route which I am using for saving video currentTime in the database using ajax</p> <pre><code>Route::post('/saveTime/{video}', 'InstructorCourseController@saveTime')-&gt;name('video.saveTime'); </code></pre> <p>This is one method which I am using for updating the video currentTime in database</p> <pre class="lang-js prettyprint-override"><code>public function saveTime(Request $request, $lession_id){ $user = Auth::user(); if($user === null){ return response()-&gt;json(['message' =&gt; 'User not authenticated', 404]); } $video = \App\Lession::where('id',$lession_id)-&gt;first(); $currentTime = $request-&gt;time; $duration = $request-&gt;duration; // return $duration; //save them somewhere $watch_history = $user-&gt;watch_history; $watch_history_array = array(); if ($watch_history == '') { array_push($watch_history_array, array('lesson_id' =&gt; $lession_id, 'progress' =&gt; $currentTime)); } else { $founder = false; $watch_history_array = json_decode($watch_history, true); for ($i = 0; $i &lt; count($watch_history_array); $i++) { $watch_history_for_each_lesson = $watch_history_array[$i]; if ($watch_history_for_each_lesson['lesson_id'] == $video-&gt;id) { $watch_history_for_each_lesson['progress'] = $currentTime; // $watch_history_array[$i]['progress'] = $progress; $founder = true; } } if (!$founder) { array_push($watch_history_array, array('lesson_id' =&gt; $video-&gt;id, 'progress' =&gt; $currentTime)); } } // return $watch_history_array; $data['watch_history'] = json_encode($watch_history_array); $check = User::where('id',$user-&gt;id)-&gt;update(['watch_history' =&gt; $watch_history_array]); return response()-&gt;json(['message' =&gt; 'Time saved', 200]);//send http response as json back to the ajax call } </code></pre> <p>Next, this is my video player on course_video.blade.php file</p> <pre class="lang-html prettyprint-override"><code>&lt;video id=&quot;player&quot; poster=&quot;/public/images/{{$lession-&gt;thumbnail}}&quot; class=&quot;plyr&quot;&gt; &lt;input type=&quot;hidden&quot; name=&quot;_token&quot; value=&quot;{{csrf_token()}}&quot; /&gt; &lt;source src=&quot;/public/images/{{$lession-&gt;resource}}&quot; /&gt; &lt;/video&gt; </code></pre> <p>Then next on the same Blade page I have my ajax code as follows</p> <pre class="lang-js prettyprint-override"><code>&lt;script&gt; var vid = document.getElementById(&quot;player&quot;); $(function() { var timeout; $(&quot;#player&quot;).on(&quot;playing pause&quot;, function(e) { // save reference var v = this; // clear previous timeout, if any clearTimeout(timeout); // call immediately if paused or when started performaction(v.currentTime, v.duration); // set up interval to fire very 5 seconds if (e.type === &quot;playing&quot;) { timeout = setInterval(function() { performaction(v.currentTime, v.duration); }, 1000); } }); function performaction(currentTime, duration, lession_id) { //pass video id to this function where you call it. var data = { time: currentTime, duration: duration }; //data to send to server var dataType = &quot;json&quot;; //expected datatype from server var headers = { &quot;X-CSRF-TOKEN&quot;: $('input[name=&quot;_token&quot;]').val() }; $.ajax({ type: &quot;POST&quot;, url: '{{route(&quot;video.saveTime&quot;,$lession_id)}}', //url of the server which stores time data data: data, headers: headers, success: function(data, status) { alert(status); var data = JSON.parse(data); alert(data[&quot;message&quot;]); }, dataType: dataType }); } }); &lt;/script&gt; </code></pre> <p>I want to store this currentTime in the database but this code is not working and even I didn't get it how the route for savetime and its method savetime() gets executed.</p>
3
1,758
R 3.4.1 gsub on Windows 10 - find and replace all strings except for
<p>I am trying to clean up data for a class project. The data deals with NOAA Storm data from 1950 to 2011. The storm types (EVTYPE) are only supposed to be 48 different levels, but there are over 1000 unique entries. I am trying to find all the snow related entries, which gives me:</p> <pre><code> table(grep("snow", temp$EVTYPE, ignore.case = TRUE, value = TRUE)) ACCUMULATED.SNOWFALL BLOWING.SNOW COLD.AND.SNOW DRIFTING.SNOW 4 5 1 1 EARLY.SNOWFALL EXCESSIVE.SNOW FALLING.SNOW.ICE FIRST.SNOW 7 25 2 2 HEAVY.SNOW HEAVY.SNOW.SHOWER HEAVY.SNOW.SQUALLS ICE.SNOW 13988 1 1 4 LAKE.EFFECT.SNOW LATE.SEASON.SNOW LATE.SEASON.SNOWFALL LATE.SNOW 656 1 3 2 LIGHT.SNOW LIGHT.SNOW.FLURRIES LIGHT.SNOW.FREEZING.PRECIP LIGHT.SNOWFALL 174 3 1 1 MODERATE.SNOW MODERATE.SNOWFALL MONTHLY.SNOWFALL MOUNTAIN.SNOWS 1 101 1 1 RECORD.MAY.SNOW RECORD.SNOW RECORD.SNOWFALL RECORD.WINTER.SNOW 1 2 2 3 SEASONAL.SNOWFALL SNOW SNOW.ACCUMULATION SNOW.ADVISORY 1 425 1 1 SNOW.AND.ICE SNOW.AND.SLEET SNOW.BLOWING.SNOW SNOW.DROUGHT 4 5 6 4 SNOW.ICE SNOW.SHOWERS SNOW.SLEET SNOW.SQUALL 1 5 5 5 SNOW.SQUALLS THUNDERSNOW.SHOWER UNUSUALLY.LATE.SNOW 14 1 1 </code></pre> <p>There is a storm type called "Lake.Effect.Snow", which is one of the 48 storm types. How can I replace all of the other entries while excluding that particular storm type? I've tried:</p> <pre><code>table(grep("([^lake]?)snow", temp$EVTYPE, ignore.case = TRUE, value = TRUE)) </code></pre> <p>to try and ignore the Lake.Effect.Snow entries, but no good.</p>
3
2,092
Is there anyway to improve this query computational cost?
<p>I'm using PostgreSQL 9.6.1 on my own machine for this database.</p> <p>I have this database of transactions. Entire database is around 100 million rows x 30 columns. Transactions span over the past four years.</p> <p>For this query, there are three relevant columns:</p> <ul> <li>transaction timestamp which is rounded to the nearest 15 minutes</li> <li>vendor ID</li> <li>transaction amount (revenue)</li> </ul> <p>I am interested in returning output of four columns such as the below image (sorry for the link - don't have enough rep to imbed images yet:</p> <p><a href="https://i.stack.imgur.com/f6adT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f6adT.png" alt="enter image description here"></a></p> <p>The output is the count of transactions during that specific timestamp, the count of unique active vendors in the past 60 minutes, and the hourly revenue over the past 60 minutes.</p> <p>Below is the code I used to try to accomplish this. </p> <pre><code>SELECT transaction_timestamp, COUNT(transaction_timestamp) AS "transaction_timestamp", (SELECT COUNT(DISTINCT vendor_id) FROM transactions_db WHERE transaction_timestamp BETWEEN t.transaction_timestamp - INTERVAL '60 MINUTES' AND t.transaction_timestamp ) AS "lag_60_transaction_count", (SELECT SUM(revenue) / COUNT(DISTINCT vendor_id) FROM transactions_db WHERE transaction_timestamp BETWEEN t.transaction_timestamp - INTERVAL '60 MINUTES' AND t.transaction_timestamp ) AS "rolling_hourly_rate" FROM transactions_db t GROUP BY transaction_timestamp ORDER BY transaction_timestamp; </code></pre> <p>Here is the EXPLAIN output:</p> <pre><code> GroupAggregate (cost=21989857.85..681893649752.90 rows=108423 width=56) Group Key: t.transaction_timestamp -&gt; Sort (cost=21989857.85..22252785.49 rows=105171056 width=8) Sort Key: t.transaction_timestamp -&gt; Index Only Scan using timestamp_vendor_revenue_idx on transactions_db t (cost=0.57..3663118.41 rows=105171056 width=8) SubPlan 1 -&gt; Aggregate (cost=3143836.32..3143836.33 rows=1 width=8) -&gt; Index Only Scan using timestamp_vendor_revenue_idx on transactions_db (cost=0.57..3142521.68 rows=525855 width=4) Index Cond: ((transaction_timestamp &gt;= (t.transaction_timestamp - '01:00:00'::interval)) AND (transaction_timestamp &lt;= t.transaction_timestamp)) SubPlan 2 -&gt; Aggregate (cost=3145150.96..3145150.97 rows=1 width=32) -&gt; Index Only Scan using timestamp_vendor_revenue_idx on transactions_db transactions_db_1 (cost=0.57..3142521.68 rows=525855 width=10) Index Cond: ((transaction_timestamp &gt;= (t.transaction_timestamp - '01:00:00'::interval)) AND (transaction_timestamp &lt;= t.transaction_timestamp)) </code></pre> <p>That being said, this query is taking an impossibly long time to run (8+ hours - ran it overnight and it was still running this morning).</p> <p>I have a composite index created on transaction_timestamp, vendor_id, and revenue but running time is still outrageously high.</p> <p>When I do run this query on a subset of the data (I have a sample table that contains one day of the data), the query returns in 2.1 seconds.</p> <p>I'm pretty much completely green to optimizing databases and queries, so the fact that I can return this query on one day of data in 2.1 seconds leads me to believe that there's something I can do to make this query run in a reasonable amount of time for the main database.</p> <p>Please let me know if there's any other information that I've left out. </p> <p>Sample data, query and output here: <a href="http://rextester.com/AOKNT5900" rel="nofollow noreferrer">http://rextester.com/AOKNT5900</a></p>
3
1,298
ActiveSupport::MessageEncryptor generating different encryption for same data
<p>I am using ActiveSupport::MessageEncryptor to generate encrytion of my token and i use this encrypted token for caching. The problem is the ActiveSupport::MessageEncryptor is generating a different encryption for the same data for every call as shown below. Any suggestion on how to avoid this.</p> <pre><code>2.3.1 :029 &gt; key = "f5c1d61058d7cee6c886063f4f7f4589ea021928ea2f265dc5a6d8605e50478976cbdae25ddffaa59fe8a8c5a0683d32d66f845decd056f5be6da7cfcf7f9bc3" =&gt; "f5c1d61058d7cee6c886063f4f7f4589ea021928ea2f265dc5a6d8605e50478976cbdae25ddffaa59fe8a8c5a0683d32d66f845decd056f5be6da7cfcf7f9bc3" 2.3.1 :030 &gt; data = "5ae545f655cfac10b50a07cc1055b43ac7f6067e5ea7320332720d6359e538ca" =&gt; "5ae545f655cfac10b50a07cc1055b43ac7f6067e5ea7320332720d6359e538ca" 2.3.1 :031 &gt; encrypter = ActiveSupport::MessageEncryptor.new(key) =&gt; #&lt;ActiveSupport::MessageEncryptor:0x000000067bafb0 @secret="f5c1d61058d7cee6c886063f4f7f4589ea021928ea2f265dc5a6d8605e50478976cbdae25ddffaa59fe8a8c5a0683d32d66f845decd056f5be6da7cfcf7f9bc3", @sign_secret=nil, @cipher="aes-256-cbc", @verifier=#&lt;ActiveSupport::MessageVerifier:0x000000067badf8 @secret="f5c1d61058d7cee6c886063f4f7f4589ea021928ea2f265dc5a6d8605e50478976cbdae25ddffaa59fe8a8c5a0683d32d66f845decd056f5be6da7cfcf7f9bc3", @digest="SHA1", @serializer=ActiveSupport::MessageEncryptor::NullSerializer&gt;, @serializer=Marshal&gt; 2.3.1 :032 &gt; encrypter.encrypt_and_sign(data) =&gt; "c1NCTzR6bFhtYW53WFZpK242RnlTdkhrM2VKa2hxM1BkSUl3MFV0cmYrZ2dzMW0vQW1iWEhjYTRJdXFIa081NXNsM1h3OGNrYTZUMHo3bnhyRDBVc0MwVnB6Q2lJaHEvbFU4V1dqdjhhd3c9LS1oaWZ4VXp5YndLMUZ0cWcwRzJhTHVnPT0=--d4bb2c1936cfc414039db49d99a69649785221a7" 2.3.1 :033 &gt; encrypter.encrypt_and_sign(data) =&gt; "UG9aN0ZEK01nTkVENDQ0dnlhdENyL3BzTFJkYnJ2eWEwNnE4YVZ6L2tkNlkrbGtpOGR4QWx4MlE1M1RNenMvWDBuTHE1b212K2p3ZzZvbE45bUl5by9ZdkJNYkdTQ2NBcGxYSEExb0ZJRk09LS1LZTNCSDlaVEoyRGNTYXQzeENGRjN3PT0=--9dacde056a9b2387afb94df6759822f6effbd077" 2.3.1 :034 &gt; encrypter.encrypt_and_sign(data) =&gt; "dERlR1UvUkFpb3RIUWFyRUFoZVpHY1RWV3REWW5lYXB1eGw2U0NnV2Vhc3NXV2RSNmhKUDBXZXZFc2JDN2lIRjFvZElxSy9yQ3pYWEJCNndJMFVwbnlsckVYSkgzdkN2eGVEMEJ1V09QdjA9LS1yc0JhL0tZaSttdmZPWVhQcXFMWVFBPT0=--b8968961a69b6803579f902a48f75b43d8b1a242" </code></pre>
3
1,277
Angular-timer siddii
<p>in my web app (which is with angularJs in the front part and with Symfony2 in the back part) i need to integrate a timer (count down of a quizzer) i found this timer <a href="https://github.com/siddii/angular-timer" rel="nofollow">https://github.com/siddii/angular-timer</a> on github and it seems to be cool but i don't the integration in my webapp works but when i try to start the counter on an event (button click) it don't works, in fact i tried this script:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;AngularJS Example - Single Timer Example&lt;/title&gt; &lt;script src="../angular/angular.min.js"&gt;&lt;/script&gt; &lt;script src="../app/js/timer.js"&gt;&lt;/script&gt; &lt;script&gt; angular.module('MyApp', ['timer']); function MyAppController($scope) { $scope.timerRunning = true; $scope.startTimer = function (){ $scope.$broadcast('timer-start'); $scope.timerRunning = true; }; $scope.stopTimer = function (){ $scope.$broadcast('timer-stop'); $scope.timerRunning = false; }; $scope.$on('timer-stopped', function (event, data){ console.log('Timer Stopped - data = ', data); }); } MyAppController.$inject = ['$scope']; &lt;/script&gt; &lt;/head&gt; &lt;body ng-app="MyApp"&gt; &lt;div ng-controller="MyAppController"&gt; &lt;h1&gt;AngularJS - Single Timer Example&lt;/h1&gt; &lt;h3&gt;&lt;timer/&gt;&lt;/h3&gt; &lt;button ng-click="startTimer()" ng-disabled="timerRunning"&gt;Start Timer&lt;/button&gt; &lt;button ng-click="stopTimer()" ng-disabled="!timerRunning"&gt;Stop Timer&lt;/button&gt; &lt;/div&gt; &lt;br/&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and i got this error:</p> <pre><code>Argument 'MyAppController' is not a function, got undefined </code></pre> <p>any one can help me plz ? </p> <p>after some changes the my code becomes : </p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;AngularJS Example - Single Timer Example&lt;/title&gt; &lt;script src="../angular/angular.min.js"&gt;&lt;/script&gt; &lt;script src="../app/js/timer.js"&gt;&lt;/script&gt; &lt;script&gt; var myApp = angular.module('myApp', ['timer']); myApp.controller('MyAppController', ['$scope', function ($scope) { $scope.timerRunning = true; $scope.startTimer = function (){ $scope.$broadcast('timer-start'); $scope.timerRunning = true; }; $scope.stopTimer = function (){ $scope.$broadcast('timer-stop'); $scope.timerRunning = false; }; $scope.$on('timer-stopped', function (event, data){ console.log('Timer Stopped - data = ', data); }); }]).$inject = ['$scope']; &lt;/script&gt; &lt;/head&gt; &lt;body ng-app="myApp"&gt; &lt;div ng-controller="MyAppController"&gt; &lt;h1&gt;AngularJS - Single Timer Example&lt;/h1&gt; &lt;h3&gt;&lt;timer/&gt;&lt;/h3&gt; &lt;button ng-click="startTimer()" ng-disabled="timerRunning"&gt;Start Timer&lt;/button&gt; &lt;button ng-click="stopTimer()" ng-disabled="!timerRunning"&gt;Stop Timer&lt;/button&gt; &lt;/div&gt; &lt;br/&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and i'm getting this beauty :/ </p> <pre><code>Unknown provider: I18nServiceProvider &lt;- I18nService </code></pre>
3
1,469
NSFetchedResultsController doesn't update UITableView after launch
<p>I have a simple UIManagedDocument-based Core Data app. I'm new to programming in iOS and I've barely got it off the ground and I'm stuck. I have People NSManagedObjects stored in Core Data. When I first launch the app, no entries are there, but if I slide up a modal VC and dismiss it, they magically appear. My design is loosely based on the "Photomania" app from the iTunes U/Sanford course, but with a singleton CoreDataStore object to handle getting the managedObjectContext. This is the code for my CoreDataStore:</p> <pre><code>+ (CoreDataStore *)sharedStore { static CoreDataStore *sharedStore = nil; if (!sharedStore) sharedStore = [[super allocWithZone:nil] init]; return sharedStore; } + (instancetype)allocWithZone:(struct _NSZone *)zone { return [self sharedStore]; } - (NSManagedObjectContext *)getContext { NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; url = [url URLByAppendingPathComponent:@"dbDocument"]; UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url]; if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) { NSLog(@"No file exists..."); [document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) { NSLog(@"Document saveForCreating completionHandler invoked. Success: %hhd", success); if (success) { self.managedObjectContext = document.managedObjectContext; NSLog(@"Got context for created file!!"); } }]; } else if (document.documentState == UIDocumentStateClosed) { NSLog(@"Document state is closed. documentState == %u", document.documentState); [document openWithCompletionHandler:^(BOOL success) { NSLog(@"Document opening success: %hhd", success); if (success) { self.managedObjectContext = document.managedObjectContext; NSLog(@"Got context for now-opened file!!"); } }]; } else { self.managedObjectContext = document.managedObjectContext; NSLog(@"Got context for already-opened file!!"); } return self.managedObjectContext; } </code></pre> <p>And here is the code from the PeopleListViewController:</p> <pre><code>- (void)setManagedObjectContext:(NSManagedObjectContext *)managedObjectContext { _managedObjectContext = managedObjectContext; if (managedObjectContext) { NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]]; request.predicate = nil; // all Persons self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil]; } else { self.fetchedResultsController = nil; } } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if (!self.managedObjectContext) [self setManagedObjectContext:[[CoreDataStore sharedStore] getContext]]; } </code></pre> <p>This is the result immediately after launch:</p> <p><img src="https://i.stack.imgur.com/NgnkT.png" alt="After launch"></p> <p>This is the modal VC:</p> <p><img src="https://i.stack.imgur.com/HGUW2.png" alt="Modal VC"></p> <p>This is after dismissing the modal VC (tapped Cancel):</p> <p><img src="https://i.stack.imgur.com/HRVLU.png" alt="After Modal"></p> <p>I've tried using performFetch on the managedObjectContext, even delaying it until well after the Core Data document reported it was opened. Nothing works. Any help would be greatly appreciated.</p>
3
1,501
OpenLayers 3 doesn't show KML layer
<p>I'm newbie with OpenLayers and I'm trying to add a KML layer to a map.</p> <p>Here is my script:</p> <pre><code>var projection = ol.proj.get('EPSG:3857'); var mapa = new ol.layer.Tile({ source: new ol.source.OSM() }); var map = new ol.Map({ target: 'map', controls: ol.control.defaults({ attributionOptions: /** @type {olx.control.AttributionOptions} */ ({ collapsible: false }) }), view: new ol.View({ center: [-5462834.47, -3058929.70], projection: projection, zoom: 10 }) }); map.addLayer(mapa); var alfalfa_zaragoza = new ol.layer.Vector({ source: new ol.source.Vector({ url: 'kml/ms_alfalfazaragoza_rgba_ndvi.kml', format: new ol.format.KML() }), extractStyles: true, extractAttributes: true, maxDepth: 2, setVisibility: true }); document.getElementById('addKML').onclick = function () { map.addLayer(alfalfa_zaragoza); }; </code></pre> <p>And my html page:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Title&lt;/title&gt; &lt;link rel="stylesheet" href="http://openlayers.org/en/v3.2.0/css/ol.css" type="text/css"&gt; &lt;script type="javascript" src="&lt;%=request.getContextPath()%&gt;/resources/OpenLayersv3.14.2/build/ol.js"&gt;&lt;/script&gt; &lt;script src="http://maps.google.com/maps/api/js?v=3&amp;amp;sensor=false"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="&lt;%=request.getContextPath()%&gt;/resources/OpenLayersv3.14.2/css/ol.css" type="text/css" /&gt; &lt;link rel="stylesheet" href="&lt;%=request.getContextPath()%&gt;/resources/ol3-google-maps-v0.4/ol3gm.css" type="text/css" /&gt; &lt;link rel="stylesheet" href="&lt;%=request.getContextPath()%&gt;/resources/layout.css" type="text/css" /&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container-fluid"&gt; &lt;div class="row-fluid"&gt; &lt;div class="span12"&gt; &lt;div id="map" class="map"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row-fluid"&gt; &lt;div class="span12"&gt; &lt;h4&gt;Concept example&lt;/h4&gt; &lt;div class="row"&gt; &lt;div class="col-md-4 col-sm-4"&gt; &lt;fieldset&gt; &lt;input id="addKML" type="button" value="Add KML" title="Add KML layer"/&gt; &lt;/fieldset&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="&lt;%=request.getContextPath()%&gt;/resources/ol3-google-maps-v0.4/ol3gm.js"&gt;&lt;/script&gt; &lt;script src="&lt;%=request.getContextPath()%&gt;/resources/kml.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Where is the error? The idea is to press "addKML" button and the layer is added to the map, but when I press it, nothing happens.</p>
3
1,513
How do I remove the old SVG elements and then replace it with a new one?
<p>So I have been working on this code and I have gotten it to work. My problem is that it works perfectly for the first input, but if the user keeps putting in inputs the new picture overlaps the old. I have successfully coded in the ability for the ellipse to be replaced when a new input is given, but I am having trouble with doing the same for all my path and marker elements. My entire code is below (separated into its individual files) what do I need to add in order to replace the old image with the new one?</p> <p>main.js <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>function eccentricityChanged(){ let svg = document.getElementById('diagram'); let temp = document.getElementById('mytext'); if (temp) { temp.remove(); } let s = 100; let omega = 0.5; let A = 0.2084558583; let B = 0.7915441417; let e = document.getElementById('eccentricity').value; let formFactor = A * e + B; let eccent = Math.sqrt(Math.pow(e, 2)/(1-Math.pow(e,2))); let p = (1 + 1/(Math.pow(eccent, 2)))*(1-(1/eccent)*Math.atan(eccent))-(1/3); let q = (1/eccent)*(1+3/(Math.pow(eccent, 2)))*Math.atan(eccent)-3/(Math.pow(eccent, 2)); let omegaStable = Math.sqrt((15/4)*q*(1-(3/5)*formFactor)); let apperantGravA = Math.pow(1-Math.pow(e,2), -1/6)*(1-(1+p/q)*Math.pow(omegaStable, 2)); let apperantGravB = Math.pow(1-Math.pow(e,2),1/3)*(1+2*p/q*Math.pow(omegaStable,2)); let a = Math.pow((1-Math.pow(e,2)),-1/6); let b = Math.pow((1-Math.pow(e,2)),1/3); let scaleFactor = 150; let eqRad = a*scaleFactor; let polRad = b*scaleFactor; let latitude = [Math.PI/6, Math.PI/4, Math.PI/3]; let latitudeLength = latitude.length; var i; for (i of latitude) { let rho = (a*Math.cos(i))/Math.sqrt(1-Math.pow(e*Math.sin(i),2)); let z = -(a*(1-Math.pow(e,2))*Math.sin(i))/Math.sqrt(1-Math.pow(e*Math.sin(i),2)); let lattGrav = (a* apperantGravA*Math.pow(Math.cos(i),2)+b*apperantGravB*Math.pow( Math.sin(i),2))/Math.sqrt(Math.pow(a*Math.cos(i),2)+Math.pow(b*Math.sin(i),2)); let gravRho =-lattGrav*Math.cos(i)-Math.pow(omegaStable,2)*rho; let gravZ = -lattGrav*Math.sin(i); let accelCent = Math.pow(omega,2)*rho; calculateValues(rho, z, lattGrav, gravRho, gravZ, accelCent, polRad,s); } makeEllipse(eqRad,polRad); } function makeEllipse(eqRad,polRad) { let svg = document.getElementById('diagram'); let temp = document.getElementById('mydiagram'); if (temp) { temp.remove(); } let ellipse = document.createElementNS('http://www.w3.org/2000/svg', 'path'); ellipse.setAttribute('d', `M 400 100 a ${polRad},${eqRad} 90 1,0 1,0 z`); ellipse.style.fill = 'transparent'; ellipse.style.stroke = 'black'; ellipse.style.strokeWidth = '5px'; ellipse.setAttribute('id', 'mydiagram'); svg.appendChild(ellipse); } function calculateValues(rho, z, lattGrav, gravRho, gravZ, accelCent, polRad,s) { let rho1 = rho*150 + 400; let z1 = z*150 + 100 + polRad; let rho2 = rho1 + s*gravRho; let z2 = z1- s*gravZ let rho3 = rho2 + s*accelCent; console.log(rho1, rho2, rho3, z1,z2); gravityVector(rho1, z1, rho2, z2, rho3, gravRho, gravZ, s, polRad); accelCentVector(rho1, z1, rho2, z2, rho3, gravRho, gravZ, s, polRad); apperantGravVector(rho1, z1, rho2, z2, rho3, gravRho, gravZ, s, polRad); }</code></pre> </div> </div> </p> <p>Vectors.js</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>function gravityVector(rho1, z1, rho2, z2, rho3, gravRho, gravZ, s, polRad) { let svg = document.getElementById('diagram'); let marker= document.createElementNS('http://www.w3.org/2000/svg', 'marker'); marker.setAttribute('id', 'triangle'); marker.setAttribute('viewBox', '0 0 10 10'); marker.setAttribute('refX', '0'); marker.setAttribute('refY', '5'); marker.setAttribute('markerUnits', 'strokeWidth'); marker.setAttribute('markerWidth', '10'); marker.setAttribute('markerHeight', '8'); marker.setAttribute('orient', 'auto'); let path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', `M ${rho2} ${z2} l 5 0 l -5 10 l -5 -10 z`); path.style.stroke = 'green'; path.style.strokeWidth = '5px'; svg.appendChild(path); let arrow = document.createElementNS('http://www.w3.org/2000/svg', 'path'); arrow.setAttribute('d', `M ${rho1},${z1} L ${rho2} ${z2}`); arrow.setAttribute('id', 'gravPath') arrow.style.stroke = 'black'; arrow.style.strokeWidth = '2px'; svg.appendChild(arrow); arrow.setAttributeNS('marker-end', 'triangle', 'void'); } function accelCentVector(rho, z, rho2, z2, rho3, gravRho, gravZ, s, polRad) { let svg = document.getElementById('diagram'); let marker= document.createElementNS('http://www.w3.org/2000/svg', 'marker'); marker.setAttribute('id', 'triangle'); marker.setAttribute('viewBox', '0 0 10 10'); marker.setAttribute('refX', '0'); marker.setAttribute('refY', '5'); marker.setAttribute('markerUnits', 'strokeWidth'); marker.setAttribute('markerWidth', '10'); marker.setAttribute('markerHeight', '8'); marker.setAttribute('orient', 'auto'); let path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', `M ${rho3} ${z2} l 5 0 l -5 10 l -5 -10 z`); path.style.stroke = 'black'; path.style.strokeWidth = '5px'; svg.appendChild(path); let arrow = document.createElementNS('http://www.w3.org/2000/svg', 'path'); arrow.setAttribute('d', `M ${rho2},${z2} L ${rho3} ${z2}`); arrow.setAttribute('id', 'accelCentPath'); arrow.style.stroke = 'red'; arrow.style.strokeWidth = '2px'; svg.appendChild(arrow); arrow.setAttributeNS('marker-end', 'triangle', 'void'); } function apperantGravVector(rho, z, rho2, z2, rho3, gravRho, gravZ, s, polRad) { let svg = document.getElementById('diagram'); let marker= document.createElementNS('http://www.w3.org/2000/svg', 'marker'); marker.setAttribute('id', 'triangle'); marker.setAttribute('viewBox', '0 0 10 10'); marker.setAttribute('refX', '0'); marker.setAttribute('refY', '5'); marker.setAttribute('markerUnits', 'strokeWidth'); marker.setAttribute('markerWidth', '10'); marker.setAttribute('markerHeight', '8'); marker.setAttribute('orient', 'auto'); let path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', `M ${rho3} ${z2} l 5 0 l -5 10 l -5 -10 z`); path.style.stroke = 'black'; path.style.strokeWidth = '5px'; svg.appendChild(path); let arrow = document.createElementNS('http://www.w3.org/2000/svg', 'path'); arrow.setAttribute('d', `M ${rho},${z} L ${rho3} ${z2}`); arrow.style.stroke = 'blue'; arrow.style.strokeWidth = '2px'; svg.appendChild(arrow); arrow.setAttributeNS('marker-end', 'triangle', 'void'); }</code></pre> </div> </div> </p> <p>index.html</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>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;CS 5890&lt;/title&gt; &lt;script src="https://d3js.org/d3.v5.min.js"&gt;&lt;/script&gt; &lt;style&gt; rect { fill: #9f009f; stroke-width: 0; } polyline { stroke: #00ff00; fill: none; stroke-width: 3; } line { stroke: #00ff00; fill: none; stroke-width: 3; } path { stroke: #0000ff; fill: #0000ff; stroke-width: 0; } circle { stroke-width: 0; fill: #009900; } text { font-size: 18px; } &lt;/style&gt; &lt;/head&gt; &lt;body id="body"&gt; Eccentricity: &lt;input id="eccentricity" onchange="eccentricityChanged()"&gt;&lt;/input&gt; &lt;p&gt;Enter a value between 0 and 1 for the Eccentricity&lt;/p&gt; &lt;br&gt; &lt;svg width="800" height="800" id="diagram"&gt; &lt;/svg&gt; &lt;g id="diagram-elements"&gt; &lt;path id =''&gt; &lt;/g&gt; &lt;script src="Vectors.js"&gt;&lt;/script&gt; &lt;script src="main.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
3
3,940
Javascript won't draw the animation taking value from HTML input element
<p>I wanted to create physics simulation with dropping ball. To have more fun I wanted to give to user an access to input his values of dropping ball radius and count. If you would run this code on browser, you could click button 'CREATE' to display animation with default values and it would have worked. When I enter balls count in html input element, it recognises the count and executes the code and the animation appears. When I enter radius value in html input element, nothing appears on canvas. I find this as very strange problem. I've already tried renaming variables and element id names. When I I would appreciate if anyone could help.</p> <p>The html file called index.html</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 canvas = document.getElementById('ball-platform'); const createBtn = document.getElementById('createAnimation'); const W = canvas.width; const H = canvas.height; const ctx = canvas.getContext('2d'); const gravity = 0.15; const friction = 0.9; let balls = []; function FillCircle(x0, y0, bRadius, theColor) { let circle = { x: x0, y: y0, color: theColor }; let xVel = 5, yVel = 1; this.movement = () =&gt; { if (Math.round(circle.x + bRadius + xVel) &gt; W || Math.round(circle.x - bRadius + xVel) &lt; 0) { xVel = -xVel * friction; yVel *= friction; } else if (Math.round(circle.y + bRadius + yVel) &gt; H) { yVel = -yVel * friction; xVel *= friction; } else { yVel += gravity; } circle.x += xVel; circle.y += yVel; } this.draw = () =&gt; { ctx.beginPath(); ctx.fillStyle = circle.color; ctx.ellipse(circle.x, circle.y, bRadius, bRadius, -90 * Math.PI / 180, 360 * Math.PI / 180, false); ctx.fill(); ctx.stroke(); } } createBtn.addEventListener('mousedown', () =&gt; { balls = []; let bRadius = document.getElementById('bRadius').value; let count = document.getElementById('count').value; if (bRadius == "" || bRadius &lt;= 0) { bRadius = 5; } if (count == "" || count &lt; 0) { count = 5; } initialize(count, bRadius); }); function initialize(count, bRadius) { for (let i = 0; i &lt; count; i++) { let xpos = (Math.random() * (W - bRadius - 10)) + bRadius; let ypos = (Math.random() * (H - bRadius - 10)) + bRadius; balls.push(new FillCircle(xpos, ypos, bRadius, 'red')); } } function animation() { requestAnimationFrame(animation); ctx.clearRect(0, 0, W, H); for (let a = 0; a &lt; balls.length; a++) { let circle = balls[a]; circle.movement(); circle.draw(); } } animation();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;nav style='display: block;'&gt; &lt;button id='createAnimation'&gt;CREATE&lt;/button&gt; &lt;input placeholder='Radius' , id='bRadius'&gt; &lt;input placeholder='Count' id='count'&gt; &lt;/nav&gt; &lt;canvas id="ball-platform" width="500" height="500" style="border: 1px solid black"&gt;&lt;/canvas&gt;</code></pre> </div> </div> </p>
3
1,191
VBA Clear and Copy without blank rows to another sheet on entering value greater than
<p>My 2010 macro updates on opening a sheet. Does 2016 work the same when when they have the target sheet opened in a new 'instance'? It has to be idiot proof (I don't know why they asked me to do it :P). So the macro has to run once when opening the sheet; if the sheet is opened on the second monitor run every time a value is inserted over 119 in the source sheet; Don't run unnecessary because of the potentially very large sheets and meh laptops. </p> <p>I've made this macro so the sheets my colleges are using don't need 'complex' formulas or macros to clear blank rows before it's exported to Word. I've made it in 2010, but I can't test it on 2016 til next week. </p> <p>The macro that on the target sheet (J03);</p> <pre><code>Private Sub worksheet_activate() </code></pre> <p>And on the source sheet (WTB); </p> <pre><code> Private Sub Run_When_Value_Greather_Than_119_Is_Entered_In_Column_G() </code></pre> <p>Google is clogged with answers and results about blank rows, copying, blank rows, running on other activation ways and non blank rows. I probably don't know what to look for either. </p> <p>The full code;</p> <pre><code>Private Sub worksheet_activate() Dim Max As Long, MaxD As Long 'Determine the amount of filled rows Dim wsWtB As Worksheet, wsJ03 As Worksheet Dim wb As Workbook Dim i As Integer, j As Integer 'i and j for the row numbers Application.ScreenUpdating = False 'screenupdating of for max speeds Set wb = ThisWorkbook Set wsJ03 = Sheets("J_03") Set wsWtB = Sheets("WTB") Max = WorksheetFunction.Max(wsWtB.Range("A3:A1600")) 'Amount of rows with data Max = Max + 3 'Ignore the headers MaxD = WorksheetFunction.Max(wsJ03.Range("A3:A1600")) MaxD = MaxD + 2 j = 9 'The rownumber where the copying needs to start wsJ03.Range("B9", Cells(MaxD, 5)).ClearContents 'Clear the old values For i = 3 To Max 'The copying loop has to start after the headers at row 3 If wsWtB.Cells(i, 7).Value &gt; 119 Then 'Do stuff if... wsJ03.Cells(j, "B").Value = Chr(39) &amp; wsWtB.Cells(i, "B").Value 'At a ' wsJ03.Cells(j, "C").Value = Chr(39) &amp; wsWtB.Cells(i, "C").Value 'at the start wsJ03.Cells(j, "D").Value = Chr(39) &amp; wsWtB.Cells(i, "D").Value 'so a zero is wsJ03.Cells(j, "E").Value = Chr(39) &amp; wsWtB.Cells(i, "E").Value 'displayed j = j + 1 'Set the next row for the target sheet Else End If Next i Application.ScreenUpdating = True End Sub </code></pre> <p>It's the first piece of code that I got working without hiccups :-) Feel free to comment and ad the propper tags.</p> <p>Koen. </p> <p>Edit; (Alternative ways to look for the last cell)</p> <pre><code>?thisworkbook.sheets("WTB").cells(rows.Count,"A").end(xlup).row 1047 '&lt;- Rownumber of the last cell with a Formula to create/force successive numbers ?thisworkbook.sheets("WTB").columns("A").Find(What:="*", LookIn:=xlValues, SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row 5 '&lt;- Rownumber of the last cell with a value. Includes the header rows ?WorksheetFunction.Max(thisworkbook.sheets("WTB").Range("A3:A1600")) 3 '&lt;- Highest number in A3:A1600 and also the amount units/rows that need to be copied to "J_03" </code></pre> <p>I needed a function that gave me the amount of 'things' on the sheet. In this case it's 3, but it could go up to 1600. </p> <p>Edit 2; (google sheet so you can see what i'm working on) <a href="https://docs.google.com/spreadsheets/d/1I5qLeOS0DWcwncs_ium_J0Vp6b4nzTsiE0ndbKtpsC0/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1I5qLeOS0DWcwncs_ium_J0Vp6b4nzTsiE0ndbKtpsC0/edit?usp=sharing</a></p> <p>Edit 3; there was an error in the clear range part. wsJ03.Range("B9", <strong>Cells(MaxD, 5))</strong>.ClearContents 'Clear the old values</p>
3
1,556
libGDX consult with speed
<p>What i need to do is, when the points its "example 10" the speed of the ball raise, when the points its "example 20" the speed of the ball raises again, etc. I dont know if i do that in the Ball class or in the GameScreen class and i dont know how to do it. Thanks for your help!.</p> <pre><code>public class Ball { //THE SPEED OF THE BALL private static final float SPEED=1100; //THE POINTS IS puntuacion =0; //AND THE METHOD WHEN THE POINTS IS INCREAMENTING private void updatePuntuacion(){ if(ball.getBordes().overlaps(Lpaddle.getBordes())) { puntuacion = puntuacion + 1; if(puntuacion &gt; puntuacionMaxima) puntuacionMaxima = puntuacion; } if(ball.getBordes().x &lt;= 0) sonidoex.play(); if(ball.getBordes().x &lt;= 0) puntuacion =0; if(ball.getBordes().x &lt;=0) Gdx.input.vibrate(1000); if(ball.getBordes().x &lt;=0) Screens.juego.setScreen(Screens.MAINSCREEN); ball.comprobarPosicionBola(); } } </code></pre> <p><strong>EDIT:</strong> </p> <p>This is my GameScreen class.</p> <pre><code>public class GameScreen extends AbstractScreen { private SpriteBatch batch; private Texture texture; private Paddle Lpaddle, Rpaddle; private Ball ball; private BitmapFont font; private int puntuacion, puntuacionMaxima; private Preferences preferencias; private Music music; private Sound sonidoex; public GameScreen(Main main) { super(main); preferencias = Gdx.app.getPreferences("PuntuacionAppPoints"); puntuacionMaxima = preferencias.getInteger("puntuacionMaxima"); music =Gdx.audio.newMusic(Gdx.files.internal("bgmusic.mp3")); music.play(); music.setVolume((float) 0.3); music.setLooping(true); sonidoex = Gdx.audio.newSound(Gdx.files.internal("explosion5.wav")); } public void show(){ batch = main.getBatch(); texture = new Texture(Gdx.files.internal("spacebg.png")); Texture texturaBola = new Texture(Gdx.files.internal("bola.png")); ball = new Ball(Gdx.graphics.getWidth() / 2 - texturaBola.getWidth() / 2, Gdx.graphics.getHeight() / 2 - texturaBola.getHeight() / 2); Texture texturaPala= new Texture(Gdx.files.internal("pala.png")); Lpaddle = new LeftPaddle(80, Gdx.graphics.getHeight()/2 -texturaPala.getHeight() /2); Rpaddle = new RightPaddle(Gdx.graphics.getWidth() -100, Gdx.graphics.getHeight()/2 - texturaPala.getHeight() /2, ball); font = new BitmapFont(Gdx.files.internal("pointsfont.tf.fnt"), Gdx.files.internal("pointsfont.tf.png"), false); puntuacion = 0; } public void render(float delta){ Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); updatePuntuacion(); Lpaddle.update(); Rpaddle.update(); ball.update(Lpaddle, Rpaddle); batch.begin(); batch.draw(texture, 0, 0,texture.getWidth(), texture.getHeight()); ball.draw(batch); Lpaddle.draw(batch); Rpaddle.draw(batch); font.draw(batch, "Points: " + Integer.toString(puntuacion), Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5); font.draw(batch, "High score: " + Integer.toString(puntuacionMaxima),Gdx.graphics.getWidth() - Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5); batch.end(); } private void updatePuntuacion(){ if(ball.getBordes().overlaps(Lpaddle.getBordes())) { puntuacion = puntuacion + 1; if(puntuacion &gt; puntuacionMaxima) puntuacionMaxima = puntuacion; } if(ball.getBordes().x &lt;= 0) sonidoex.play(); if(ball.getBordes().x &lt;= 0) puntuacion =0; if(ball.getBordes().x &lt;=0) Gdx.input.vibrate(1000); if (puntuacion % 10 == 0){ SPEED = 200; } if(ball.getBordes().x &lt;=0) Screens.juego.setScreen(Screens.MAINSCREEN); ball.comprobarPosicionBola(); } public void hide(){ font.dispose(); texture.dispose(); } @Override public void dispose(){ preferencias.putInteger("puntuacionMaxima", puntuacionMaxima); preferencias.flush(); } public void resize(int width, int height){ float widthImage = texture.getWidth(); float heightImage = texture.getHeight(); float r = heightImage / widthImage; if(heightImage &gt; height) { heightImage = height; widthImage = heightImage / r; } if(widthImage &gt; width) { widthImage = width; heightImage = widthImage * r; } } } </code></pre>
3
2,229
How to set a multiple button on a one image (4x4)
<p>I want to divide a picture into 4x4 and it should have a 16 buttons.</p> <p>As of now I have created 3x3 buttons alone (without picture).</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/back_orange" &gt; &lt;LinearLayout android:layout_marginTop="130dp" android:layout_marginLeft="35dp" android:layout_width="300dp" android:weightSum="1" android:orientation="vertical" android:layout_height="300dp"&gt; &lt;LinearLayout android:id="@+id/LinearLayout02" android:layout_width="match_parent" android:layout_weight="0.33" android:layout_height="0dp"&gt; &lt;Button android:id="@+id/Button04" android:text="Button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="fill_parent"&gt;&lt;/Button&gt; &lt;Button android:id="@+id/Button05" android:text="Button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="fill_parent"&gt;&lt;/Button&gt; &lt;Button android:id="@+id/Button06" android:text="Button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="fill_parent"&gt;&lt;/Button&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/LinearLayout01" android:layout_width="match_parent" android:layout_weight="0.33" android:layout_height="0dp"&gt; &lt;Button android:id="@+id/Button01" android:text="Button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="fill_parent"&gt;&lt;/Button&gt; &lt;Button android:id="@+id/Button02" android:text="Button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="fill_parent"&gt;&lt;/Button&gt; &lt;Button android:id="@+id/Button03" android:text="Button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="fill_parent"&gt;&lt;/Button&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_weight="0.33" android:layout_height="0dp"&gt; &lt;Button android:id="@+id/button1" android:text="Button" android:layout_weight="1" android:layout_width="0dp" android:layout_height="fill_parent"&gt;&lt;/Button&gt; &lt;Button android:id="@+id/button2" android:text="Button" android:layout_weight="1" android:layout_width="0dp" android:layout_height="fill_parent"&gt;&lt;/Button&gt; &lt;Button android:id="@+id/button3" android:text="Button" android:layout_weight="1" android:layout_width="0dp" android:layout_height="fill_parent"&gt;&lt;/Button&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre>
3
1,100
MERN Application is not storing session
<p>My MERN application is failing to store the session on the browser. The backend is being hosted on Heroku and the client is being hosted by Vercel. When I switch over to localhost, it works as expected, but on deployment, it fails to store any sessions. If I try to log in a user, it will pass the authentication, but it won't store a session on my browser.</p> <p>I get this error:</p> <pre><code> Access to XMLHttpRequest at 'https://myapp-backend.herokuapp.com/user' from origin 'https://myapp-client.vercel.app' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. </code></pre> <p>Here is what I have.</p> <p>Server.js:</p> <pre><code>const url = process.env.MONGO_DB_URL mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false, }) const db = mongoose.connection db.on('error', console.error.bind(console, 'connection error')) db.once('open', () =&gt; { console.log('connected to mongo database') }) const app = express() app.set('views', path.join(__dirname, 'views')) app.use( mongoSanitize({ replaceWith: '_', }) ) app.use(helmet()) app.use(express.json()) app.use( cors({ origin: ['http://192.168.1.14:3000', 'https://myapp-client.vercel.app'], credentials: true, }) ) app.use(express.static(path.join(__dirname, 'public'))) // express session middleware const store = MongoStore.create({ mongoUrl: url, secret: process.env.MONGO_SECRET, touchAfter: 24 * 60 * 60, }) store.on('error', err =&gt; { console.log(err) }) app.use( session({ store, name: 'rfts', secret: process.env.MONGO_SECRET, resave: false, saveUninitialized: true, cookie: { expires: Date.now() + 1000 * 60 * 60 * 24 * 3, maxAge: 1000 * 60 * 60 * 24 * 3, httpOnly: true, secure: true, }) ) app.use(cookieParser(process.env.COOKIE_SECRET)) // passport middleware app.use(passport.initialize()) app.use(passport.session()) passport.use(new LocalStrategy(User.authenticate())) passport.serializeUser(User.serializeUser()) passport.deserializeUser(User.deserializeUser()) const PORT = process.env.PORT || 3001 app.listen(PORT, () =&gt; { console.log(`listening on port ${PORT}`) }) </code></pre> <p>And on the client, I use this to make calls to the server:</p> <pre><code>import axios from 'axios' const macUrl = 'http://192.168.1.14:3001' const localUrl = 'http://localhost:3001' const herokuUrl = 'https://myapp-backend.herokuapp.com' const axiosCall = axios.create({ baseURL: herokuUrl, withCredentials: true, }) export default axiosCall </code></pre> <p>ANY advice would be greatly appreciated!</p>
3
1,036
Swift - didSelectRowAt indexPath next VC not showing up /no storyboards/
<p>I have a problem with "didSelectRowAt indexPath" because row is not firing next VC. In console I've printed string for particular row so selecting a row is working however next VC is not opening. I've of course tried to find a solution on stack overflow and google however I cannot find a solution. Below I'm pasting: MainVC -> ViewController and next VC -> DetailViewCOntroller</p> <p>Thank you in advance for your help.</p> <p>Main VC:</p> <pre><code>import UIKit class ViewController: UIViewController { let cellID = "Picture" let tableViewCell = TableViewCell() let tableWithImages: UITableView = { let table = UITableView() table.rowHeight = 50 table.translatesAutoresizingMaskIntoConstraints = false return table }() var pictures: [String] = [String]() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white tableWithImages.delegate = self tableWithImages.dataSource = self tableWithImages.register(TableViewCell.self, forCellReuseIdentifier: cellID) fileManagerSetup() setupView() } func fileManagerSetup(){ let fm = FileManager.default let path = Bundle.main.resourcePath! let items = try! fm.contentsOfDirectory(atPath: path) for item in items { if item.hasPrefix("nssl"){ pictures.append(item) } } print(pictures) } private func setupView(){ view.addSubview(tableWithImages) tableWithImages.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true tableWithImages.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true tableWithImages.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true tableWithImages.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return pictures.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) cell.textLabel?.text = pictures[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailVC = DetailViewController() detailVC.selectedImage = pictures[indexPath.row] self.navigationController?.pushViewController(detailVC, animated: true) print("Row tapped: \(pictures[indexPath.row])") } } </code></pre> <p>Second VC:</p> <pre><code>import UIKit class DetailViewController: UIViewController { var imageView: UIImageView = { var picture = UIImageView() picture.translatesAutoresizingMaskIntoConstraints = false return picture }() var selectedImage: String? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white setupView() if let imageToLoad = selectedImage { imageView.image = UIImage(named: imageToLoad) } } private func setupView(){ view.addSubview(imageView) imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true } } </code></pre>
3
1,267
Is their any way of getting metrics from google ads accounts via api?
<p>I was trying to display metrics from google ads accounts that gave me consent via an Oauth prompt. any ways of displaying data from google ads accounts that went through consent prompt? please fix the code listed below if possible so i can display data on a table via getElementById if possible.</p> <p>Code I tried</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; var YOUR_CLIENT_ID = '504111780457-nslu2gim01j3c7optfbvjkd7trdgjgk9.apps.googleusercontent.com'; var YOUR_REDIRECT_URI = 'https://prompt.sewellstephens.com/api'; var fragmentString = location.hash.substring(1); // Parse query string to see if page request is coming from OAuth 2.0 server. var params = {}; var regex = /([^&amp;=]+)=([^&amp;]*)/g, m; while (m = regex.exec(fragmentString)) { params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); } if (Object.keys(params).length &gt; 0) { localStorage.setItem('oauth2-test-params', JSON.stringify(params) ); if (params['state'] &amp;&amp; params['state'] == 'try_sample_request') { trySampleRequest(); } } // If there's an access token, try an API request. // Otherwise, start OAuth 2.0 flow. function trySampleRequest() { var params = JSON.parse(localStorage.getItem('oauth2-test-params')); if (params &amp;&amp; params['access_token']) { var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://googleads.googleapis.com/v3/customers/1234567890/metrics:mutate?fields=user&amp;' + 'access_token=' + params['access_token']); xhr.onreadystatechange = function (e) { if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) { console.log(xhr.response); } else if (xhr.readyState === 4 &amp;&amp; xhr.status === 401) { // Token invalid, so prompt for user permission. oauth2SignIn(); } }; xhr.send(null); } else { oauth2SignIn(); } } /* * Create form to request access token from Google's OAuth 2.0 server. */ function oauth2SignIn() { // Google's OAuth 2.0 endpoint for requesting an access token var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth'; // Create element to open OAuth 2.0 endpoint in new window. var form = document.createElement('form'); form.setAttribute('method', 'GET'); // Send as a GET request. form.setAttribute('action', oauth2Endpoint); // Parameters to pass to OAuth 2.0 endpoint. var params = {'client_id': YOUR_CLIENT_ID, 'redirect_uri': YOUR_REDIRECT_URI, 'scope': 'https://www.googleapis.com/auth/adwords', 'state': 'try_sample_request', 'include_granted_scopes': 'true', 'response_type': 'token'}; // Add form parameters as hidden input values. for (var p in params) { var input = document.createElement('input'); input.setAttribute('type', 'hidden'); input.setAttribute('name', p); input.setAttribute('value', params[p]); form.appendChild(input); } // Add form to page and submit it to open the OAuth 2.0 endpoint. document.body.appendChild(form); form.submit(); } &lt;/script&gt; &lt;button onclick=&quot;trySampleRequest();&quot;&gt;Prompt Consent&lt;/button&gt; &lt;/body&gt; &lt;/html&gt;''' </code></pre> <p>I don't know where to put the developer token and need someone to fix this code if possible. I have been trying to do this api call and its been a nightmare trying to fix this code up so that i can display data from google ads accounts via a consent prompt.</p>
3
1,243
Select query native in Spring MVC
<p>I want to show JSON data from a database (use SAP HANA database) but I found an error. I want to show data from two or more tables however It was failed. How to fix it? What is the best simple practice to select query table from data JSON? Thank you.</p> <p>controller:</p> <pre><code>@RestController public class InformasiNoTersediaDosirController { @Autowired private InformasiNoTersediaService infoserv; @GetMapping("/info_dosir_2") @ResponseStatus(HttpStatus.OK) public void infoDosir(@RequestParam(value="kdcabang", defaultValue="") String kdcabang){ infoserv.getInfoSql(kdcabang); } } </code></pre> <p>service:</p> <pre><code>@Repository public class InformasiNoTersediaService { @Autowired private SessionFactory sessionFactory; @Transactional public String getInfoSql(String kdcabang){ String sql = ""; String result = ""; sql = "SELECT KODE_CABANG, SUM (NOMOR_DOSIR) FROM NOMOR_DOSIR WHERE TIPE_NOMOR_DOSIR = 'TERSEDIA' AND KODE_CABANG = :kd_cabang GROUP BY KODE_CABANG"; kdcabang = "100"; Query query = (Query) this.sessionFactory.getCurrentSession().createSQLQuery(sql).setParameter("kd_cabang", kdcabang); List&lt;Object[]&gt; data = ((Criteria) query).list(); int itemCount = data.size(); result = "["; if(itemCount &gt; 0) { for(Object[] row : data){ result += "{"; result += "\"key\":\"" + row[0].toString() + "\","; result += "\"value\":\"" + row[1].toString()+ "\""; result += "},"; } result = result.substring(0, result.length()-1); } result += "]"; return result; } } </code></pre> <p>Here is the error that I get:</p> <pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: org.hibernate.internal.SQLQueryImpl cannot be cast to javax.management.Query org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) javax.servlet.http.HttpServlet.service(HttpServlet.java:621) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) root cause java.lang.ClassCastException: org.hibernate.internal.SQLQueryImpl cannot be cast to javax.management.Query com.taspen.acb.service.InformasiNoTersediaService.getInfoSql(InformasiNoTersediaService.java:38) com.taspen.acb.service.InformasiNoTersediaService$$FastClassBySpringCGLIB$$9ad40852.invoke(&lt;generated&gt;) org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) com.taspen.acb.service.InformasiNoTersediaService$$EnhancerBySpringCGLIB$$11078261.getInfoSql(&lt;generated&gt;) com.taspen.acb.controller.InformasiNoTersediaDosirController.infoDosir(InformasiNoTersediaDosirController.java:31) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) javax.servlet.http.HttpServlet.service(HttpServlet.java:621) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) </code></pre>
3
3,763
ExpandableListAdapter methods are not working properly in my case. Any alternate to ExpandableListView
<p>I am using an <code>ExpandableListAdapter</code> for the first time. I have some textviews in the groupView and some buttons in childView. I've used the following code from the internet and tried to convert it according to my preference. But there is a problem in the <code>getGroupCount()</code> method. I know in my code <code>_listDataHeader</code> and <code>_listDataChild</code> are null, but what should I use instead? Here are the pictures of my header view</p> <p><a href="https://i.stack.imgur.com/8ZG7x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8ZG7x.png" alt="header View layout"></a> </p> <pre><code> and Child View layout </code></pre> <p><a href="https://i.stack.imgur.com/xITo0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xITo0.png" alt="child view layout"></a>.</p> <p>On the click of header this child View should be shown on screen.. Am i using the correct android View for this design? Please help</p> <pre><code> public class ExpandableListAdapter extends BaseExpandableListAdapter { Activity context; ArrayList&lt;String&gt; s_date,c_number,d_ration,s_time,download_path,a_number,a_name; String id[]; String mUrl; private List&lt;String&gt; _listDataHeader; // header titles // child data in format of header title, child title private HashMap&lt;String, List&lt;String&gt;&gt; _listDataChild; public ExpandableListAdapter(Activity context, ArrayList&lt;String&gt; start_date, ArrayList&lt;String&gt; caller_number, ArrayList&lt;String&gt; duration,ArrayList&lt;String&gt; start_time, ArrayList&lt;String&gt; download_path, ArrayList&lt;String&gt; agent_number, ArrayList&lt;String&gt; agent_name) { this.context=context; this.s_date=start_date; this.c_number=caller_number; this.d_ration=duration; this.s_time=start_time; this.download_path=download_path; this.a_number=agent_number; this.a_name=agent_name; } @Override public Object getChild(int groupPosition, int childPosititon) { return this._listDataChild.get(this._listDataHeader.get(groupPosition)) .get(childPosititon); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final String childText = (String) getChild(groupPosition, childPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.list_item, null); } Button play_button=(Button) convertView.findViewById(R.id.play); play_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("play child is",childText); } }); Button download_button=(Button) convertView.findViewById(R.id.download); download_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("download child is",childText); } }); } @Override public int getChildrenCount(int groupPosition) { return this._listDataChild.get(this._listDataHeader.get(groupPosition)) .size(); } @Override public Object getGroup(int groupPosition) { return this._listDataHeader.get(groupPosition); } @Override public int getGroupCount() { return this.s_date.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String headerTitle = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.list_group, null); } TextView start_date = (TextView) convertView.findViewById(R.id.start_date); start_date.setText(s_date.get(groupPosition)); TextView caller_number = (TextView) convertView.findViewById(R.id.caller_number); caller_number.setText(c_number.get(groupPosition)); TextView duration = (TextView) convertView.findViewById(R.id.duration); duration.setText(d_ration.get(groupPosition)); TextView start_time = (TextView) convertView.findViewById(R.id.start_time); start_time.setText(s_time.get(groupPosition)); TextView agent_name = (TextView) convertView.findViewById(R.id.agent_name); agent_name.setText(a_name.get(groupPosition)); TextView agent_number = (TextView) convertView.findViewById(R.id.agent_number); agent_number.setText(a_number.get(groupPosition)); // start_date.setTypeface(null, Typeface.BOLD); // start_date.setText(headerTitle); return convertView; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } } </code></pre> <p>and this is how i'm setting the adpater</p> <pre><code> ExpandableListAdapter a=new ExpandableListAdapter(MainScreen.this,start_date,caller_number,duration,start_time,download_path,agent_number,agent_name); data_list.setAdapter(a); </code></pre>
3
1,994
error in my speachto text python programm
<p>every time i start my programm it woks perfectly fine but at a point in the programm i get this error</p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File &quot;C:\Program Files\Python39\lib\tkinter\__init__.py&quot;, line 1892, in __call__ return self.func(*args) File &quot;c:\Users\mikan\OneDrive\Desktop\python\Erstes programm\firtrightprogramme.pyw&quot;, line 34, in test1 goon() File &quot;c:\Users\mikan\OneDrive\Desktop\python\Erstes programm\firtrightprogramme.pyw&quot;, line 47, in goon ifclause() File &quot;c:\Users\mikan\OneDrive\Desktop\python\Erstes programm\firtrightprogramme.pyw&quot;, line 52, in ifclause Moin() File &quot;c:\Users\mikan\OneDrive\Desktop\python\Erstes programm\firtrightprogramme.pyw&quot;, line 41, in Moin recording.pack() File &quot;C:\Program Files\Python39\lib\tkinter\__init__.py&quot;, line 2396, in pack_configure self.tk.call( _tkinter.TclError: bad window path name &quot;.!button2&quot; </code></pre> <p>and i cant fix it here is the code pls help</p> <pre><code>from tkinter import * import time from threading import Timer import os lt = time.localtime() def buttonaction(): global buttonaction timesay.destroy() datumsay.destroy() hellosay.destroy() tell.destroy() exit.destroy() start1.destroy() info.destroy() Setings.destroy() start.destroy() recording.pack() def test2(): Button(fenster, text=&quot;aufnahme&quot;, command=test1).pack() def test1(): global text import program2 program2 text = program2.text goon() def seting(): tell.pack() def Moin(): recording.pack() def goon(): #print(f&quot;{text}&quot;) recording.destroy() #print(f&quot;{text}&quot;) if text == (&quot;hallo&quot;): #here i get the error Moin() elif text == (&quot;stop&quot;): quit elif text == (&quot;zeit&quot;): #here i get the error print(&quot;here comes thet time&quot;) timesay datumsay elif text == (&quot;hello from the other side&quot;): print(&quot;haha sher lustig&quot;) else: Label(fenster, text=&quot;What did you say&quot;) buttonaction() fenster = Tk() fenster.title(&quot;Javis&quot;) start1 = Button(fenster, text=&quot;Start&quot;, command=buttonaction) recording = Button(fenster, text=&quot;aufnahme&quot;, command=test1) start = Label(fenster, text=&quot;Press to start&quot;) Setings = Button(fenster, text=&quot;Setings&quot;, command=seting) exit = Button(fenster, text=&quot;Quit&quot;, command=fenster.quit) moinmeister = Label(fenster, text=&quot;hallo was kann ich für dich tuen&quot;) info = Label(fenster, text=&quot;Press to quit&quot;) tell = Label(fenster, text=&quot;there are no setings ;)&quot;) hellosay = Label(fenster, text=&quot;Hello what can i do for you today&quot;) datumsay = Label(fenster, text=&quot;Datum: {0:02d}.{1:02d}.{2:4d}&quot;.format(lt[2], lt[1], lt[0])) timesay = Label(fenster, text=&quot;Uhrzeit: {0:02}:{1:02d}:{2:02d}&quot;.format(lt[3], lt[4], lt[5])) start.pack() start1.pack() info.pack() exit.pack() Setings.pack() fenster.mainloop() </code></pre> <p>if anyone can help me it would be grate</p> <p>here some random thinks because stackoverflow think tjere is to much code and not enaughth text</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p> <p>hello</p>
3
1,759
Keras-WGAN Critic And Generator Accuracy Stuck At 0
<p>I am trying to implement WGAN in Keras. I am using David Foster's Generative Deep Learning Book and <a href="https://github.com/eriklindernoren/Keras-GAN/blob/636ec0533df1d1ba2bfe4ec9ae7aa66bd7ee2177/wgan/wgan.py" rel="nofollow noreferrer">this code</a> as reference. I wrote down this simple code. However, whenever I start training the model, the accuracy is always 0 and the losses for Critic and Discriminator are ~0.</p> <p>They are stuck at these number no matter how many epochs they train for. I tried various network configurations and different hyperparameters, but the result don't seem to change. Google did not help much either. I cannot pin down the source of this behavior. </p> <p>This is the code I wrote.</p> <pre><code> from os.path import expanduser import os import struct as st import numpy as np import matplotlib.pyplot as plt from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten, Dropout from keras.layers import BatchNormalization, Activation, ZeroPadding2D from keras.layers.advanced_activations import LeakyReLU from keras.layers.convolutional import UpSampling2D, Conv2D from keras.models import Sequential, Model from keras.optimizers import RMSprop import keras.backend as K def wasserstein_loss(y_true, y_pred): return K.mean(y_true * y_pred) class WGAN: def __init__(self): # Data Params self.genInput=100 self.imChannels=1 self.imShape = (28,28,1) # Build Models self.onBuildDiscriminator() self.onBuildGenerator() self.onBuildGAN() pass def onBuildGAN(self): if self.mGenerator is None or self.mDiscriminator is None: raise Exception('Generator Or Descriminator Uninitialized.') self.mDiscriminator.trainable=False self.mGAN=Sequential() self.mGAN.add(self.mGenerator) self.mGAN.add(self.mDiscriminator) ganOptimizer=RMSprop(lr=0.00005) self.mGAN.compile(loss=wasserstein_loss, optimizer=ganOptimizer, metrics=['accuracy']) print('GAN Model') self.mGAN.summary() pass def onBuildGenerator(self): self.mGenerator=Sequential() self.mGenerator.add(Dense(128 * 7 * 7, activation="relu", input_dim=self.genInput)) self.mGenerator.add(Reshape((7, 7, 128))) self.mGenerator.add(UpSampling2D()) self.mGenerator.add(Conv2D(128, kernel_size=4, padding="same")) self.mGenerator.add(BatchNormalization(momentum=0.8)) self.mGenerator.add(Activation("relu")) self.mGenerator.add(UpSampling2D()) self.mGenerator.add(Conv2D(64, kernel_size=4, padding="same")) self.mGenerator.add(BatchNormalization(momentum=0.8)) self.mGenerator.add(Activation("relu")) self.mGenerator.add(Conv2D(self.imChannels, kernel_size=4, padding="same")) self.mGenerator.add(Activation("tanh")) print('Generator Model') self.mGenerator.summary() pass def onBuildDiscriminator(self): self.mDiscriminator = Sequential() self.mDiscriminator.add(Conv2D(16, kernel_size=3, strides=2, input_shape=self.imShape, padding="same")) self.mDiscriminator.add(LeakyReLU(alpha=0.2)) self.mDiscriminator.add(Dropout(0.25)) self.mDiscriminator.add(Conv2D(32, kernel_size=3, strides=2, padding="same")) self.mDiscriminator.add(ZeroPadding2D(padding=((0,1),(0,1)))) self.mDiscriminator.add(BatchNormalization(momentum=0.8)) self.mDiscriminator.add(LeakyReLU(alpha=0.2)) self.mDiscriminator.add(Dropout(0.25)) self.mDiscriminator.add(Conv2D(64, kernel_size=3, strides=2, padding="same")) self.mDiscriminator.add(BatchNormalization(momentum=0.8)) self.mDiscriminator.add(LeakyReLU(alpha=0.2)) self.mDiscriminator.add(Dropout(0.25)) self.mDiscriminator.add(Conv2D(128, kernel_size=3, strides=1, padding="same")) self.mDiscriminator.add(BatchNormalization(momentum=0.8)) self.mDiscriminator.add(LeakyReLU(alpha=0.2)) self.mDiscriminator.add(Dropout(0.25)) self.mDiscriminator.add(Flatten()) self.mDiscriminator.add(Dense(1)) disOptimizer=RMSprop(lr=0.00005) self.mDiscriminator.compile(loss=wasserstein_loss, optimizer=disOptimizer, metrics=['accuracy']) print('Discriminator Model') self.mDiscriminator.summary() pass def fit(self, trainData, nEpochs=1000, batchSize=64): lblForReal = -np.ones((batchSize, 1)) lblForGene = np.ones((batchSize, 1)) for ep in range(1, nEpochs+1): for __ in range(5): # Get Valid Images validImages = trainData[ np.random.randint(0, trainData.shape[0], batchSize) ] # Get Generated Images noiseForGene=np.random.normal(0, 1, size=(batchSize, self.genInput)) geneImages=self.mGenerator.predict(noiseForGene) # Train Critic On Valid And Generated Images With Labels -1 And 1 Respectively disValidLoss=self.mDiscriminator.train_on_batch(validImages, lblForReal) disGeneLoss=self.mDiscriminator.train_on_batch(geneImages, lblForGene) # Perform Critic Weight Clipping for l in self.mDiscriminator.layers: weights = l.get_weights() weights = [np.clip(w, -0.01, 0.01) for w in weights] l.set_weights(weights) # Train Generator Using Combined Model geneLoss=self.mGAN.train_on_batch(noiseForGene, lblForReal) print(' Epoch', ep, 'Critic Valid Loss,Acc', disValidLoss, 'Critic Generated Loss,Acc', disGeneLoss, 'Generator Loss,Acc', geneLoss) pass pass if __name__ == '__main__': (trainData, __), (__, __) = mnist.load_data() trainData = (trainData.astype(np.float32)/127.5) - 1 trainData = np.expand_dims(trainData, axis=3) WGan = WGAN() WGan.fit(trainData) </code></pre> <p>I get output very similar to the following for all configs that I try.</p> <pre><code> Epoch 1 Critic Valid Loss,Acc [-0.00016362152, 0.0] Critic Generated Loss,Acc [0.0003417502, 0.0] Generator Loss,Acc [-0.00016735379, 0.0] Epoch 2 Critic Valid Loss,Acc [-0.0001719332, 0.0] Critic Generated Loss,Acc [0.0003365979, 0.0] Generator Loss,Acc [-0.00017250411, 0.0] Epoch 3 Critic Valid Loss,Acc [-0.00017473527, 0.0] Critic Generated Loss,Acc [0.00032945914, 0.0] Generator Loss,Acc [-0.00017612436, 0.0] Epoch 4 Critic Valid Loss,Acc [-0.00017181305, 0.0] Critic Generated Loss,Acc [0.0003266656, 0.0] Generator Loss,Acc [-0.00016987178, 0.0] Epoch 5 Critic Valid Loss,Acc [-0.0001683443, 0.0] Critic Generated Loss,Acc [0.00032702673, 0.0] Generator Loss,Acc [-0.00016638976, 0.0] Epoch 6 Critic Valid Loss,Acc [-0.00017005506, 0.0] Critic Generated Loss,Acc [0.00032805002, 0.0] Generator Loss,Acc [-0.00017040147, 0.0] Epoch 7 Critic Valid Loss,Acc [-0.00017353195, 0.0] Critic Generated Loss,Acc [0.00033711304, 0.0] Generator Loss,Acc [-0.00017537423, 0.0] Epoch 8 Critic Valid Loss,Acc [-0.00017059325, 0.0] Critic Generated Loss,Acc [0.0003263024, 0.0] Generator Loss,Acc [-0.00016974319, 0.0] Epoch 9 Critic Valid Loss,Acc [-0.00017530039, 0.0] Critic Generated Loss,Acc [0.00032463064, 0.0] Generator Loss,Acc [-0.00017845634, 0.0] Epoch 10 Critic Valid Loss,Acc [-0.00017530067, 0.0] Critic Generated Loss,Acc [0.00033131015, 0.0] Generator Loss,Acc [-0.00017526663, 0.0] </code></pre>
3
3,269
Parallel request historical options chain prices / Last known price in IBrokers (R)
<p>I am trying to create <strong>Current</strong> Options Chain (options per strike, per expiration) for a ticker. </p> <pre><code>library(IBrokers) tws &lt;- twsConnect() # Lets say only Call prices AA &lt;- reqContractDetails(tws, twsOption(local="", right="C", symbol="AAPL")) </code></pre> <p>Native implementation with <strong><code>snapshot</code></strong> is too slow:</p> <pre><code>reqMktData(tws, AA[1:2], snapshot = TRUE) </code></pre> <p>It waits around <strong><code>11 sec</code></strong> per contract (Current number of Contracts is 626)</p> <hr> <p>Another implementation:</p> <pre><code>snapShot &lt;- function (twsCon, eWrapper, timestamp, file, playback = 1, ...) { if (missing(eWrapper)) eWrapper &lt;- eWrapper() names(eWrapper$.Data$data) &lt;- eWrapper$.Data$symbols con &lt;- twsCon[[1]] if (inherits(twsCon, "twsPlayback")) { sys.time &lt;- NULL while (TRUE) { if (!is.null(timestamp)) { last.time &lt;- sys.time sys.time &lt;- as.POSIXct(strptime(paste(readBin(con, character(), 2), collapse = " "), timestamp)) if (!is.null(last.time)) { Sys.sleep((sys.time - last.time) * playback) } curMsg &lt;- .Internal(readBin(con, "character", 1L, NA_integer_, TRUE, FALSE)) if (length(curMsg) &lt; 1) next processMsg(curMsg, con, eWrapper, format(sys.time, timestamp), file, ...) } else { curMsg &lt;- readBin(con, character(), 1) if (length(curMsg) &lt; 1) next processMsg(curMsg, con, eWrapper, timestamp, file, ...) if (curMsg == .twsIncomingMSG$REAL_TIME_BARS) Sys.sleep(5 * playback) } } } else { evalWithTimeout( while (TRUE) { socketSelect(list(con), FALSE, NULL) curMsg &lt;- .Internal(readBin(con, "character", 1L, NA_integer_, TRUE, FALSE)) if (!is.null(timestamp)) { processMsg(curMsg, con, eWrapper, format(Sys.time(), timestamp), file, ...) } else { processMsg(curMsg, con, eWrapper, timestamp, file, ...) } if (!any(sapply(eWrapper$.Data$data, is.na))) return(do.call(rbind, lapply(eWrapper$.Data$data, as.data.frame))) }, timeout=5, onTimeout="warning") } } reqMktData(tws, AA[1:20], eventWrapper=eWrapper.data(20),CALLBACK=snapShot) </code></pre> <p>It avoids waiting ( 11 secs ).</p> <p>But this doesn't work if there is no real-time data or markets are closed.</p> <p>So, I want to get only the last known price even if markets are closed. <strong><br>This is my pseudo-solution:</strong></p> <pre><code>reqHistoricalData(tws, AA[[1]]$contract, whatToShow='BID', barSize = "1 min", duration = "60 S") </code></pre> <p><strong>Is there a way to parallelize this solution so it will call for historical price of several contract?</strong></p> <p>Currently it spends around <strong><code>2.3 seconds</code></strong> per contract, while previous solution is able to get 20-30 contracts with the same time spent.</p>
3
1,555
Robocopy from Process sometimes Gives Access Denied, Not in BAtch File
<p>We're running a Robocopy through a Process, so we can look at the log file after the Robocopy command fails. Sometimes, the Robocopy will give Access Denied. It's very inconsistent when the Access Denied happens. Running using an admin acct. Here's the code ...</p> <pre><code> using (Process p = new Process()) { Globals.lastCommand = string.Format("/C ROBOCOPY \"{0}\" \"{1}\" /MIR /J /LOG+:\"{2}\" /R:1 /W:10 /XF {3}", source, destination, Globals.tempLog, "*.bak"); p.StartInfo.Arguments = Globals.lastCommand; p.StartInfo.Domain = "++++++++"; p.StartInfo.UserName = "+++++++"; string password = "++++++++"; for (int x = 0; x &lt; password.Length; x++) ssPwd.AppendChar(password[x]); p.StartInfo.Password = ssPwd; p.StartInfo.WorkingDirectory = source; p.StartInfo.FileName = "CMD.EXE"; p.StartInfo.CreateNoWindow = true; p.StartInfo.Verb = "runas"; p.StartInfo.UseShellExecute = false; p.Start(); p.WaitForExit(); } </code></pre> <p>Here's the error we're getting:</p> <pre><code> 2 \\MAD2014\SYNC\017 Alliance\004 Sebree Mining\917-5026\(0016) MA 10\DMP\MPA03\ARCHIVE\9175026_MA10_042914\ 2 \\MAD2014\SYNC\017 Alliance\004 Sebree Mining\917-5026\(0016) MA 10\DMP\MPA03\ARCHIVE\9175026_MI10_110213\ 6 \\MAD2014\SYNC\017 Alliance\004 Sebree Mining\917-5026\(0016) MA 10\DMP\MPA03\ARCHIVE\9175026_MI10_110213\SHP_FILES_9175026_MI10\ 0 \\MAD2014\SYNC\017 Alliance\004 Sebree Mining\917-5026\(0016) MA 10\DMP\MPA03\COLLECTION\ 12 \\MAD2014\SYNC\017 Alliance\004 Sebree Mining\917-5026\(0016) MA 10\DMP\MPA03\COLLECTION\Correspondence\ </code></pre> <p>2014/07/27 20:31:49 ERROR 5 (0x00000005) Accessing Destination Directory \lex2014\projects\017 Alliance\004 Sebree Mining\917-5026(0016) MA 10\DMP\MPA03\COLLECTION\Correspondence\ Access is denied.</p> <p>Waiting 10 seconds... Retrying... 2014/07/27 20:31:59 ERROR 5 (0x00000005) Accessing Destination Directory \lex2014\projects\017 Alliance\004 Sebree Mining\917-5026(0016) MA 10\DMP\MPA03\COLLECTION\Correspondence\ Access is denied.</p> <p>ERROR: RETRY LIMIT EXCEEDED.</p> <pre><code> 6 \\MAD2014\SYNC\017 Alliance\004 Sebree Mining\917-5026\(0016) MA 10\DMP\MPA03\COLLECTION\ITEM_08\ 5 \\MAD2014\SYNC\017 Alliance\004 Sebree Mining\917-5026\(0016) MA 10\DMP\MPA03\COLLECTION\ITEM_09\ </code></pre> <p>Notice how it continues. Also, if the same Robocopy is run in a batch file, no errors. Also, we're copying from one server to the other.</p>
3
1,368
AJAX data being sent to the wrong Django view
<p>I'm new to django and ajax so I've been working on a project to learn it. I have two buttons, one that adds a marker and one that deletes a marker.</p> <p>Here is the views.py</p> <pre><code>@csrf_exempt def save(request): searchVar = request.POST.getlist('search[]') waypoint = Waypoint() waypoint.name = searchVar[0] waypoint.geometry = ('POINT(' + searchVar[2] + " " + searchVar[1] + ')') waypoint.save() return HttpResponse(json.dumps(dict(isOk=1)), content_type='application/json') @csrf_exempt def remove(request): objectID = request.POST.get('id') point = get_object_or_404(Point, pk = objectID) point.delete() </code></pre> <p>Here is the urls.py </p> <pre><code>from django.conf.urls import patterns, url, include urlpatterns = patterns('googlemaps.waypoints.views', url(r'^$', 'index', name='waypoints-index'), url(r'', 'save', name='waypoints-save'), url(r'', 'remove', name='waypoints-remove'), ) </code></pre> <p>and here is the ajax from the js file</p> <pre><code> $('#saveWaypoints').click(function () { var searchList = [search.name, search.geometry.location.lat(), search.geometry.location.lng()] $.ajax({ url : "waypoints-save", type : "POST", data : { search : searchList } }, function (data) { if (data.isOk) { $('#saveWaypoints'); } else { alert(data.message); } }); }); $('#removeWaypoints').click(function () { console.log(markerID); $.ajax({ url : "waypoints-remove", type : "POST", data : { id : markerID } }, function (data) { if (data.isOk) { $('#removeWaypoints'); } else { alert(data.message); } }); }); </code></pre> <p>The save button works fine, but when I click on the remove button I get this error in my console log</p> <pre><code>POST http://127.0.0.1:8000/waypoints-remove 500 (Internal Server Error) IndexError at /waypoints-remove list index out of range Request Method: POST Request URL: http://127.0.0.1:8000/waypoints-remove </code></pre> <p>and this error in my server cmd</p> <pre><code>Internal Server Error: /waypoints-remove Traceback (most recent call last): File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\rnvitter\virtualenv4\googlemaps\googlemaps\waypoints\views.py", line 23, in save waypoint.name = searchVar[0] IndexError: list index out of range 2017-01-09 22:40:11,781 - ERROR - Internal Server Error: /waypoints-remove Traceback (most recent call last): File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\rnvitter\virtualenv4\googlemaps\googlemaps\waypoints\views.py", line 23, in save waypoint.name = searchVar[0] IndexError: list index out of range </code></pre> <p>Which leads me to believe that the data from the remove button ajax call is being sent to my save view, does anyone know one?</p>
3
1,497
How to parse JSON data in Swift 3?
<p>I need to get my GPS location from mySQL by PHP in Swift 3. I tried to write the code for get data but it still not work, could you advise me?</p> <p>JSON Data from PHP:</p> <blockquote> <p>[{"id":"3752","latitude":"11.2222","longitude":"111.2222","Speed":"0.000000","Volt":"3.97","Percent":"87.000000","Dates":"2017-03-07 22:53:32"}]</p> </blockquote> <p>Swift 3 code:</p> <pre><code>import UIKit //-------- import google map library --------// import GoogleMaps import GooglePlaces class ViewController: UIViewController , GMSMapViewDelegate { var placesClient: GMSPlacesClient! override func viewDidLoad() { super.viewDidLoad() var abc : String = String() //-------- Google key for ios --------// GMSServices.provideAPIKey("XXXXXXXXXX") GMSPlacesClient.provideAPIKey("XXXXXXXXX") //--------set URL --------// let myUrl = URL(string: "http://www.myweb/service.php"); var request = URLRequest(url:myUrl!) request.httpMethod = "POST" let postString = ""; request.httpBody = postString.data(using: String.Encoding.utf8); let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in if error != nil { print("error=\(error)") return } // You can print out response object print("response = \(response)") do { let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary if let parseJSON = json { // Now we can access value of latiutde let latitude= parseJSON["latitude"] as? String //&lt;---- Here , which i need latitude value print("latitude = \(latitude)") } } catch { print(error) } } task.resume() } </code></pre> <p>I tried to write the code but it show the errors on debug output</p> <pre><code> let responseString = String(data: data, encoding: .utf8 ) let str = String(data: data, encoding: .utf8 ) let data2 = str?.data(using: String.Encoding.utf8, allowLossyConversion: false)! do { let json = try JSONSerialization.jsonObject(with: data2!, options: []) as! [String: AnyObject] if let names = json["latitude"] as? [String] { print(names) } } catch let error as NSError { print("Failed to load: \(error.localizedDescription)") } } </code></pre> <p>Error message</p> <blockquote> <p>Could not cast value of type '__NSSingleObjectArrayI' (0x1065fad60) to 'NSDictionary' (0x1065fb288).</p> </blockquote>
3
1,305
(PyQt) QVBoxLayout shrink upon multiple loading of addWidget
<p>Why is the layout shrinking like this and other times going back to normal?</p> <p><a href="https://i.stack.imgur.com/SJVeH.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SJVeH.gif" alt="enter image description here"></a></p> <p>I've created several separate UI files in QtDesigner, one is the MainWindow and the other is a widget for Loading Data. </p> <p>In order to work with these files, I've created separate child classes of each UI file. In order to add a new widget to the MainWindow I've created a <code>addWidget()</code> function; it works by adding a particular widget to the scrollarea layout. You can see this function in <code>MainWindow.py</code></p> <p><hr></p> <h2>Here is the code for <code>__main__.py</code></h2> <pre><code>import multiprocessing as mp import os.path import sys import time from PyQt5 import QtGui from PyQt5 import QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import * from point_spectra_gui.future_.functions import * from point_spectra_gui.future_.util import delete from point_spectra_gui.future_.util.excepthook import my_exception_hook def new(): p = mp.Process(target=main, args=()) p.start() def connectWidgets(ui): ui.actionLoad_Data.triggered.connect(lambda: ui.addWidget(LoadData.Ui_Form)) def main(): sys._excepthook = sys.excepthook sys.excepthook = my_exception_hook app = QtWidgets.QApplication(sys.argv) mainWindow = QtWidgets.QMainWindow() ui = MainWindow.Ui_MainWindow() ui.setupUi(mainWindow) connectWidgets(ui) mainWindow.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre> <p><hr></p> <h2>Here is the code for <code>MainWindow.py</code></h2> <pre><code>from PyQt5 import QtWidgets from point_spectra_gui.future_.functions import * from point_spectra_gui.future_.util import * from point_spectra_gui.ui import MainWindow class Ui_MainWindow(MainWindow.Ui_MainWindow): def setupUi(self, MainWindow): self.MainWindow = MainWindow super().setupUi(MainWindow) # Run the basic window UI self.menu_item_shortcuts() # set up the shortcuts def addWidget(self, object): widget = object() widget.setupUi(self.scrollArea) self.widgetLayout = QtWidgets.QVBoxLayout() self.widgetLayout.setObjectName("widgetLayout") self.verticalLayout_3.addLayout(self.widgetLayout) self.widgetLayout.addWidget(widget.get_widget()) def menu_item_shortcuts(self): self.actionExit.setShortcut("ctrl+Q") self.actionCreate_New_Workflow.setShortcut("ctrl+N") self.actionOpen_Workflow.setShortcut("ctrl+O") self.actionRestore_Workflow.setShortcut("ctrl+R") self.actionSave_Current_Workflow.setShortcut("ctrl+S") </code></pre> <p><hr></p> <h2>Here is the code of the child class <code>LoadData.py</code></h2> <pre><code>from PyQt5 import QtWidgets from point_spectra_gui.ui.LoadData import Ui_loadData class Ui_Form(Ui_loadData): def setupUi(self, Form): super().setupUi(Form) self.connectWidgets() def get_widget(self): return self.groupBox def connectWidgets(self): self.newFilePushButton.clicked.connect(lambda: self.on_getDataButton_clicked()) # self.get_data_line_edit.textChanged.connect(lambda: self.get_data_params()) # self.dataname.textChanged.connect(lambda: self.get_data_params()) def on_getDataButton_clicked(self): filename, _filter = QtWidgets.QFileDialog.getOpenFileName(None, "Open Data File", '.', "(*.csv)") self.fileNameLineEdit.setText(filename) if self.fileNameLineEdit.text() == "": self.fileNameLineEdit.setText("*.csv") </code></pre> <p><hr></p> <h2>**Edit</h2> <p>Upon trying this again and then <strong>shrinking</strong> the window. The layout goes back to normal. This to me tells me it's not a problem with my code, it's the way the Qt handles the adding of widgets. I still do not understand why this is happening though. So any insight into how this is happening is very much appreciated. </p> <p><a href="https://i.stack.imgur.com/KWYss.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KWYss.gif" alt="enter image description here"></a></p>
3
1,660
Conditional keyed join/update _and_ update a flag column for matches
<p>This is very similar to the <a href="https://stackoverflow.com/questions/29658627/conditional-binary-join-and-update-by-reference-using-the-data-table-package">question</a> @DavidArenburg asked about conditional keyed joins, with an additional bugbear that I can't seem to suss out.</p> <p>Basically, in addition to a conditional join, I want to define a flag saying at which step of the matching process that the match occurred; my problem is that I can only get the flag to define for <em>all</em> values, not the matched values.</p> <p>Here's what I hope is a minimal working example:</p> <pre><code>DT = data.table( name = c("Joe", "Joe", "Jim", "Carol", "Joe", "Carol", "Ann", "Ann", "Beth", "Joe", "Joe"), surname = c("Smith", "Smith", "Jones", "Clymer", "Smith", "Klein", "Cotter", "Cotter", "Brown", "Smith", "Smith"), maiden_name = c("", "", "", "", "", "Clymer", "", "", "", "", ""), id = c(1, 1:3, rep(NA, 7)), year = rep(1:4, c(4, 3, 2, 2)), flag1 = NA, flag2 = NA, key = "year" ) DT # name surname maiden_name id year flag1 flag2 # 1: Joe Smith 1 1 FALSE FALSE # 2: Joe Smith 1 1 FALSE FALSE # 3: Jim Jones 2 1 FALSE FALSE # 4: Carol Clymer 3 1 FALSE FALSE # 5: Joe Smith NA 2 FALSE FALSE # 6: Carol Klein Clymer NA 2 FALSE FALSE # 7: Ann Cotter NA 2 FALSE FALSE # 8: Ann Cotter NA 3 FALSE FALSE # 9: Beth Brown NA 3 FALSE FALSE # 10: Joe Smith NA 4 FALSE FALSE # 11: Joe Smith NA 4 FALSE FALSE </code></pre> <p>My approach is, for each year, to first try and match on first name/last name from a prior year; if that fails, then try to match on first name/maiden name. I want to define <code>flag1</code> to denote an exact match and <code>flag2</code> to denote a marriage.</p> <pre><code>for (yr in 2:4) { #which ids have we hit so far? existing_ids = DT[.(yr), unique(id)] #find people in prior years appearing to # correspond to those people unmatched = DT[.(1:(yr - 1))][!id %in% existing_ids, .SD[.N], by = id] setkey(unmatched, name, surname) #merge a la Arun, define flag1 setkey(DT, name, surname) DT[year == yr, c("id", "flag1") := unmatched[.SD, .(id, TRUE)]] setkey(DT, year) #repeat, this time keying on name/maiden_name existing_ids = DT[.(yr), unique(id)] unmatched = DT[.(1:(yr - 1))][!id %in% existing_ids, .SD[.N],by=id] setkey(unmatched, name, surname) #now define flag2 = TRUE setkey(DT, name, maiden_name) DT[year==yr &amp; is.na(id), c("id", "flag2") := unmatched[.SD, .(id, TRUE)]] setkey(DT, year) #this is messy, but I'm trying to increment id # for "new" individuals setkey(DT, name, surname, maiden_name) DT[year == yr &amp; is.na(id), id := unique( DT[year == yr &amp; is.na(id)], by = c("name", "surname", "maiden_name") )[ , count := .I][.SD, count] + DT[ , max(id, na.rm = TRUE)] ] #re-sort by year at the end setkey(DT, year) } </code></pre> <p>I was hoping that by including the <code>TRUE</code> value in the <code>j</code> argument while I define <code>id</code>, only the matched <code>name</code>s (e.g., Joe at the first step) would have their <code>flag</code> updated to <code>TRUE</code>, but this isn't the case--they are all updated:</p> <pre><code>DT[] # name surname maiden_name id year flag1 flag2 # 1: Carol Clymer 3 1 FALSE FALSE # 2: Jim Jones 2 1 FALSE FALSE # 3: Joe Smith 1 1 FALSE FALSE # 4: Joe Smith 1 1 FALSE FALSE # 5: Ann Cotter 4 2 TRUE TRUE # 6: Carol Klein Clymer 3 2 TRUE TRUE # 7: Joe Smith 1 2 TRUE FALSE # 8: Ann Cotter 4 3 TRUE FALSE # 9: Beth Brown 5 3 TRUE TRUE # 10: Joe Smith 1 4 TRUE FALSE # 11: Joe Smith 1 4 TRUE FALSE </code></pre> <p>Is there any way to update only the matched rows' <code>flag</code> values? Ideal output is as follows:</p> <pre><code>DT[] # name surname maiden_name id year flag1 flag2 # 1: Carol Clymer 3 1 FALSE FALSE # 2: Jim Jones 2 1 FALSE FALSE # 3: Joe Smith 1 1 FALSE FALSE # 4: Joe Smith 1 1 FALSE FALSE # 5: Ann Cotter 4 2 FALSE FALSE # 6: Carol Klein Clymer 3 2 FALSE TRUE # 7: Joe Smith 1 2 TRUE FALSE # 8: Ann Cotter 4 3 TRUE FALSE # 9: Beth Brown 5 3 FALSE FALSE # 10: Joe Smith 1 4 TRUE FALSE # 11: Joe Smith 1 4 TRUE FALSE </code></pre>
3
2,232
function bind_param() on a non-object in my new code
<p>I am trying to change my PHP code into another secure one so I change the update.PHP page <a href="https://stackoverflow.com/questions/33560398/how-to-prevent-sql-injections-by-updating-codes/">from this</a> to that:</p> <pre><code>&lt;?php require_once ('../include/global.php'); $id=$_REQUEST['id']; if (isset ($_POST['name'])) { $name = $_POST['name']; } if (isset ($_POST['remarcs'])) { $remarcs = $_POST['remarcs']; } if (isset ($_POST['test_res'])) { $test_res = $_POST['test_res']; } if (isset ($_POST['address'])) { $address = $_POST['address']; } if (isset ($_POST['date'])) { $date = $_POST['date']; } if (isset ($_POST['phone_num'])) { $phone = $_POST['phone_num']; } if (isset ($_POST['illness'])) { $illness = $_POST['illness']; } if (isset ($_POST['echo'])) { $echo = $_POST['echo']; } if (isset ($_POST['pe'])) { $pe = $_POST['pe']; } if (isset ($_POST['pmhx'])) { $pmhx = $_POST['pmhx']; } if (isset ($_POST['pshx'])) { $pshx = $_POST['pshx']; } if (isset ($_POST['habbits'])) { $habbits = $_POST['habbits']; } if (isset ($_POST['occup'])) { $occup = $_POST['occup']; } if (isset ($_POST['allergy'])) { $allergy = $_POST['allergy']; } //Check file is uploaded or not //if (isset($_FILES['file']['name']) &amp;&amp; $_FILES['file']['name']!='' &amp;&amp; $_FILES['file']['error']=='') { //$path2 = ... ; //move_uploaded_file(...); if(is_uploaded_file($_FILES["file"]["tmp_name"])) { $path = "../uploads/".$_FILES['file']['name']; move_uploaded_file($_FILES["file"]["tmp_name"], $path); $new_path = "./uploads/".$path; } else{ $new_path = $_POST['org_path']; //$path2 = "../uploads/".$_FILES['echo_photo']['name']; } $sql=('UPDATE $tbl_name SET name = ?, echo_files = ?, remarcs = ?, test_res = ?, date = ?, address = ?, phone_num = ?, illness = ?, echo = ?, pmhx = ?, pshx = ?, habbits = ?, occup = ?, allergy = ?, pe = ? WHERE id = ? '); $stmt= $con-&gt;prepare($sql); $stmt-&gt;bind_param("ssssssssssssssi", $name, $path, $remarcs, $test_res, $date, $address, $phone, $illness, $echo, $pmhx, $pshx, $habbits, $occup, $allergy, $pe, $id); $stmt-&gt;execute(); if($stmt-&gt;errno){ echo "FAILURE!!! " . $stmt-&gt;error; } else { header("location:update_done.php"); } ?&gt; </code></pre> <p>Now I am getting this error:</p> <blockquote> <p>Fatal error: Call to a member function bind_param() on a non-object in So any help with this ?</p> </blockquote>
3
1,138
EJS just outputs the first found user in some cases
<p>I'm Using mongoDB and ejs to display all my users in a table. The table also has some action buttons to delete the user and to change the users role. The buttons open a popup to change the role or to confirm the deletion. But EJS doesn't pass the users info into the popup. It works totally fine in the table, but not in the popup.</p> <p>My EJS User Table with the Role change Popup:</p> <pre><code>&lt;tbody&gt; &lt;%users.forEach(function(users){%&gt; &lt;tr&gt; &lt;td&gt;&lt;%=users.name%&gt;&lt;/td&gt; &lt;td&gt;&lt;%=users.username%&gt;&lt;/td&gt; &lt;td&gt;&lt;%=users.createdAt%&gt;&lt;/td&gt; &lt;td&gt;&lt;span class=&quot;badge label-table badge-&lt;%=users.role%&gt;&quot;&gt;&lt;%=users.role%&gt;&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class=&quot;badge label-table badge-&lt;%=users.verifyEmailToken%&gt;&quot;&gt;&lt;%=users.verifyEmailToken%&gt;&lt;/span&gt;&lt;/td&gt; &lt;td&gt; &lt;button type=&quot;submit&quot; class=&quot;btn btn-xs btn-success&quot; data-toggle=&quot;modal&quot; data-target=&quot;#con-close-modal&quot; name=&quot;changeRoleButton&quot;&gt;&lt;i class=&quot;remixicon-user-settings-line&quot;&gt;&lt;/i&gt;&lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; &lt;div id=&quot;con-close-modal&quot; class=&quot;modal fade&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot; aria-labelledby=&quot;myModalLabel&quot; aria-hidden=&quot;true&quot; style=&quot;display: none;&quot;&gt; &lt;div class=&quot;modal-dialog&quot;&gt; &lt;div class=&quot;modal-content&quot;&gt; &lt;div class=&quot;modal-header&quot;&gt; &lt;h4 class=&quot;modal-title&quot;&gt;Change &lt;%=users.name%&gt; Role&lt;/h4&gt; &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot; aria-hidden=&quot;true&quot;&gt;×&lt;/button&gt; &lt;/div&gt; &lt;form class=&quot;&quot; action=&quot;/changeuserrole&quot; method=&quot;post&quot;&gt; &lt;div class=&quot;modal-body p-4&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-md-12&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label for=&quot;field-1&quot; class=&quot;control-label&quot;&gt;User Role&lt;/label&gt; &lt;select class=&quot;form-control&quot; name=&quot;role&quot;&gt; &lt;option&gt;Partner&lt;/option&gt; &lt;option&gt;Admin&lt;/option&gt; &lt;option&gt;User&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;button type=&quot;submit&quot; value=&quot;&lt;%=users._id%&gt;&quot; name=&quot;userroleid&quot; class=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;%});%&gt; &lt;/tbody&gt; </code></pre> <p>Here is my app.js where I search for the users and pass them to EJS:</p> <pre><code> app.get(&quot;/users&quot;, function(req, res) { if (req.isAuthenticated() &amp;&amp; req.user.role === &quot;Admin&quot;) { User.find({}, function(err, foundUsers) { if (err) { console.log(err); } else { res.render(&quot;users&quot;, { users: foundUsers, name: req.user.name.replace(/ .*/, ''), email: req.user.username, }); } }); } else { res.redirect(&quot;/login&quot;); } }); </code></pre> <p>All the &lt;%=users...%&gt; tags work inside the table, but not inside the popup divs. Inside the Popup it just displays the information from the first user in the Database, which is super strange.</p> <p>I would be very thankful for any kind of help. Thanks!</p>
3
2,599
Django cannot find all my files in static files
<p>I'm totally fresh to Django. I downloaded a template that presents a well-structured web page. But after I put all the template files in the static dir, it didn't show any images or run any js/CSS files. Here is my dir:<a href="https://i.stack.imgur.com/IenJV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IenJV.png" alt="**enter image description here**"></a></p> <p>Here is my settings.py:</p> <pre><code>INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] # URL prefix for static files STATIC_URL = '/static/' # Absolute path to the directory in which static files should be collected STATIC_ROOT = os.path.join(BASE_DIR, 'root') # Additional locations for static files (optional) STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),] </code></pre> <p>This is what I got at terminal:</p> <pre><code>[31/May/2020 07:55:02] "GET /static/assets/vendor/aos/aos.css HTTP/1.1" 404 1699 [31/May/2020 07:55:02] "GET /static/assets/vendor/owl.carousel/assets/owl.carousel.min.css HTTP/1.1" 404 1786 [31/May/2020 07:55:02] "GET /static/assets/vendor/icofont/icofont.min.css HTTP/1.1" 404 1735 [31/May/2020 07:55:02] "GET /static/assets/vendor/boxicons/css/boxicons.min.css HTTP/1.1" 404 1753 [31/May/2020 07:55:02] "GET /static/assets/vendor/venobox/venobox.css HTTP/1.1" 404 1723 [31/May/2020 07:55:02] "GET /static/assets/vendor/bootstrap/css/bootstrap.min.css HTTP/1.1" 404 1759 [31/May/2020 07:55:03] "GET /static/assets/vendor/jquery/jquery.min.js HTTP/1.1" 404 1726 [31/May/2020 07:55:03] "GET /static/assets/css/style.css HTTP/1.1" 404 1684 [31/May/2020 07:55:03] "GET /static/assets/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 1774 [31/May/2020 07:55:03] "GET /static/assets/vendor/jquery.easing/jquery.easing.min.js HTTP/1.1" 404 1768 [31/May/2020 07:55:03] "GET /static/assets/vendor/php-email-form/validate.js HTTP/1.1" 404 1744 [31/May/2020 07:55:03] "GET /static/assets/vendor/waypoints/jquery.waypoints.min.js HTTP/1.1" 404 1765 [31/May/2020 07:55:03] "GET /static/assets/vendor/counterup/counterup.min.js HTTP/1.1" 404 1744 [31/May/2020 07:55:04] "GET /static/assets/img/portfolio/portfolio-9.jpg HTTP/1.1" 404 1732 [31/May/2020 07:55:04] "GET /static/assets/img/portfolio/portfolio-8.jpg HTTP/1.1" 404 1732 [31/May/2020 07:55:04] "GET /static/assets/img/portfolio/portfolio-2.jpg HTTP/1.1" 404 1732 [31/May/2020 07:55:04] "GET /static/assets/img/portfolio/portfolio-7.jpg HTTP/1.1" 404 1732 [31/May/2020 07:55:04] "GET /static/assets/img/portfolio/portfolio-5.jpg HTTP/1.1" 404 1732 [31/May/2020 07:55:04] "GET /static/ssets/img/portfolio/portfolio-4.jpg HTTP/1.1" 404 1729 [31/May/2020 07:55:04] "GET /static/assets/img/portfolio/portfolio-6.jpg HTTP/1.1" 404 1732 [31/May/2020 07:55:05] "GET /static/assets/img/portfolio/portfolio-1.jpg HTTP/1.1" 404 1732 [31/May/2020 07:55:05] "GET /static/assets/img/portfolio/portfolio-3.jpg HTTP/1.1" 404 1732 [31/May/2020 07:55:05] "GET /static/assets/vendor/isotope-layout/isotope.pkgd.min.js HTTP/1.1" 404 1768 [31/May/2020 07:55:05] "GET /static/assets/vendor/venobox/venobox.min.js HTTP/1.1" 404 1732 [31/May/2020 07:55:05] "GET /static/assets/vendor/owl.carousel/owl.carousel.min.js HTTP/1.1" 404 1762 [31/May/2020 07:55:05] "GET /static/assets/js/main.js HTTP/1.1" 404 1675 [31/May/2020 07:55:05] "GET /static/assets/vendor/php-email-form/validate.js HTTP/1.1" 404 1744 [31/May/2020 07:55:05] "GET /static/assets/vendor/aos/aos.js HTTP/1.1" 404 1696 [31/May/2020 07:55:06] "GET /static/assets/vendor/venobox/venobox.min.js HTTP/1.1" 404 1732 [31/May/2020 07:55:06] "GET /static/assets/vendor/owl.carousel/owl.carousel.min.js HTTP/1.1" 404 1762 [31/May/2020 07:55:06] "GET /static/assets/vendor/aos/aos.js HTTP/1.1" 404 1696 [31/May/2020 07:55:06] "GET /static/assets/js/main.js HTTP/1.1" 404 1675 </code></pre> <p>The web page is supposed to like this: <a href="https://i.stack.imgur.com/6PBkH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6PBkH.jpg" alt="enter image description here"></a></p> <p>And now it looks like this: <a href="https://i.stack.imgur.com/eklFp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eklFp.png" alt="enter image description here"></a></p>
3
1,816
My Permissions Interface Is Not Working Properly For Android API 24 And Upwards
<p>I want to create a code that as soon the app begins, it asks for permissions ( WRITE and CAMERA ). If one or all permissions are denied then the app shows a warning text (in TextView ) asking for permissions and also a button “Permission” ( also made from a TextView ) that WILL REMAIN VISIBLE while the user keeps denying any or all these permissions. </p> <p>This app prototype works fine in the emulator API 23, but in the emulator API 24 and upwards it did not work properly.</p> <p>Here are the codes:</p> <p>1) AndroidManifest.xml</p> <pre><code>&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.lf.permissionsfromlf"&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.CAMERA" /&gt; &lt;uses-feature android:name="android.hardware.camera2" /&gt; &lt;uses-feature android:name="android.hardware.camera" android:required="true" /&gt; &lt;application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"&gt; &lt;activity android:name=".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;/application&gt; &lt;/manifest&gt; </code></pre> <p>2) activity_main.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:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"&gt; &lt;TextView android:id="@+id/permissionNote" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="24dp" android:gravity="center" android:letterSpacing="0.1" android:text="@string/give_permission" android:textColor="#000066" android:textSize="16sp" android:textStyle="bold" android:visibility="invisible" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; &lt;TextView android:id="@+id/permission_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:background="@drawable/permission_btn" android:gravity="center" android:letterSpacing="0.1" android:text="@string/permission" android:textColor="#ffffff" android:textSize="20sp" android:textStyle="bold" android:visibility="invisible" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.50" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/permissionNote" /&gt; &lt;/android.support.constraint.ConstraintLayout&gt; </code></pre> <p>3) MainActivity.java</p> <pre><code>import android.Manifest; import android.content.pm.PackageManager; import android.os.Build; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView permissionNote; TextView permission_btn; boolean WRITE_GRANTED = false; boolean CAMERA_GRANTED = false; static final int REQUEST_PERMISSION_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /////////// permissionNote = findViewById(R.id.permissionNote); permission_btn = findViewById(R.id.permission_btn); permissionNote.setVisibility(View.INVISIBLE); permission_btn.setVisibility(View.INVISIBLE); //Sets OnClick for the PERMISSION BUTTON in case it becomes necessary permission_btn.setOnClickListener(new TextView.OnClickListener() { @Override public void onClick(View v) { if( !WRITE_GRANTED || !CAMERA_GRANTED ) request_permission(); } }); //VERIFY IF PERMISSIONS ARE GRANTED for SDK_INT &gt;= 23 if( Build.VERSION.SDK_INT &gt;= 23 ) { //Verifies if permission was already granted if ((ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) || (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) { permissionNote.setVisibility(View.VISIBLE); permission_btn.setVisibility(View.VISIBLE); request_permission(); } else { // Permission has already been granted permissionNote.setVisibility(View.INVISIBLE); permission_btn.setVisibility(View.INVISIBLE); } ////////////////////// if( WRITE_GRANTED &amp;&amp; CAMERA_GRANTED ) { // Permission has already been granted permissionNote.setVisibility(View.INVISIBLE); permission_btn.setVisibility(View.INVISIBLE); } ////////////////////// } } public void request_permission() { if(!WRITE_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE); } if(!CAMERA_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CODE); } //////////////////////// // IF ALL PERMISSIONS ARE GRANTED, MAKE PERMISSION BUTTON INVISIBLE if(write_permission_granted()) { WRITE_GRANTED = true; } if(camera_permission_granted()) { CAMERA_GRANTED = true; } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_PERMISSION_CODE: { // If request is cancelled, the resulting arrays is empty. if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Calling write_permission_granted and camera_permission_granted() after // onRequestPermissionsResult // updates write_permission and camera permission as to make the PERMISSION BUTTON invisible if(write_permission_granted() &amp;&amp; camera_permission_granted()) //CAMERA_GRANTED = true; { permissionNote.setVisibility(View.INVISIBLE); permission_btn.setVisibility(View.INVISIBLE); } } return; } } } public boolean write_permission_granted() { if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) return true; else return false; } public boolean camera_permission_granted() { if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) return true; else return false; } } </code></pre> <p>So the idea is that the warning and the button will remain visible in the screen in case the user changes his mind and clicks the button in order to give all permissions. Once all the permissions are given then immediately the warning and the button SHOULD DISAPPEAR ( become invisible ).</p> <p>In the API 24 emulator, when the app starts, only a popup box with the question “Allow the app to access photos, media, and files on your device?” appears. After answering this one, it should also popup a second box with the question ”Allow this app to take pictures and record video?” BUT IT DOES NOT HAPPEN. As consequence, the warning and the button “PERMISSION” remain on the screen. So, after that, when I click on this button in the first time it does not respond. In the second time when I click again it finally pops up the box “Allow this app to take pictures...”. Only after this second permission is finally given, only then the warning and the button disappear ( become invisible ) but this should have happened right at the start of the app.</p>
3
4,030
How to separate a concatenated string when first word (same beginning string pattern) of every observation contains a different ending string in R?
<p>In R I have a much larger data set with the issue I need to resolve. So I have a data frame in R and the first word of every observation in the <code>Post</code> variable has a concatenated string. Fortunately the beginning of the string contains the same word but the ending of the concatenated string is always different. Would anyone know of a function that can separate <code>Introduction</code> from the word it is connected (attached) to a string of words? In other words, how can you separate a concatenated string when first word ("<code>Introduction</code>" the same beginning string pattern) of every observation contains a different ending string in R? </p> <p><strong>UPDATE: complete and reproducible question</strong> </p> <pre><code> dat &lt;- data.frame(author=c("a", "b", "c", "d", "a", "b", "c", "d", "e", "a", "a", "a","a", "a", "c","c","c","c"),Post=c("Introductiontwo text", "IntroductionYoua need Introduction to give a complete and reproducible questionone text", "IntroductionYouas need Introduction to give a complete and reproducible questionthre text", "IntroductionYouasd need Introduction to give a complete and reproducible questionnice text", "IntroductionYouasds need Introduction to give a complete and reproducible questionwow text", "IntroductionYouasdsh need Introduction to give a complete and reproducible questionone text", "IntroductionYouasdshs need Introduction to give a complete and reproducible questionone text", "IntroductionYouasdshsa need Introduction to give a complete and reproducible questionone text", "IntroductionYouasdshsas need Introduction to give a complete and reproducible questionone text", "IntroductionYouasdshsasa need Introduction to give a complete and reproducible questionone text","IntroductionYouasdshsasaa need Introduction to give a complete and reproducible questionone text", "IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text","IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text", "IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text","IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text", "IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text","IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text", "IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text")) dat author Post 1 a Introductiontwo text 2 b IntroductionYoua need Introduction to give a complete and reproducible questionone text 3 c IntroductionYouas need Introduction to give a complete and reproducible questionthre text 4 d IntroductionYouasd need Introduction to give a complete and reproducible questionnice text 5 a IntroductionYouasds need Introduction to give a complete and reproducible questionwow text 6 b IntroductionYouasdsh need Introduction to give a complete and reproducible questionone text 7 c IntroductionYouasdshs need Introduction to give a complete and reproducible questionone text 8 d IntroductionYouasdshsa need Introduction to give a complete and reproducible questionone text 9 e IntroductionYouasdshsas need Introduction to give a complete and reproducible questionone text 10 a IntroductionYouasdshsasa need Introduction to give a complete and reproducible questionone text 11 a IntroductionYouasdshsasaa need Introduction to give a complete and reproducible questionone text 12 a IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text 13 a IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text 14 a IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text 15 c IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text 16 c IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text 17 c IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text 18 c IntroductionYouasdshsasaaa need Introduction to give a complete and reproducible questionone text </code></pre>
3
1,336
socket.request.user undefined in Passport.js, Socket.io, and Express
<p>I am learning NodeJs, Express, and Socket.io through a tutorial, the tutorial used a previous version of NodeJs, Express, and Socket.io to access userID. I am using current versions to do the same but it wasn't successful, I adjusted my code to conform with the current version but what I get is an empty string.</p> <p>SESSION:</p> <pre><code>&quot;use strict&quot;; const session = require(&quot;express-session&quot;); const MongoStore = require(&quot;connect-mongo&quot;)(session); const config = require(&quot;../config&quot;); const db = require(&quot;../db&quot;); if (process.env.NODE_ENV === &quot;production&quot;) { // Initialize session with settings for production module.exports = session({ secret: config.sessionSecret, resave: false, saveUninitialized: false, store: new MongoStore({ mongooseConnection: db.Mongoose.connection, }), }); } else { module.exports = session({ secret: config.sessionSecret, resave: false, saveUninitialized: true, store: new MongoStore({ mongooseConnection: db.Mongoose.connection, }), }); } </code></pre> <p>SERVER</p> <pre><code>&quot;use strict&quot;; const express = require(&quot;express&quot;); const ChatCAT = require(&quot;./app&quot;); const passport = require(&quot;passport&quot;); const app = express(); app.set(&quot;port&quot;, process.env.PORT || 3000); app.use(express.static(&quot;public&quot;)); app.set(&quot;view engine&quot;, &quot;ejs&quot;); app.use(ChatCAT.session); app.use(passport.initialize()); app.use(passport.session()); app.use(&quot;/&quot;, ChatCAT.router); let port = app.get(&quot;port&quot;); ChatCAT.ioServer(app, passport).listen(port, () =&gt; { console.log(&quot;ChatCAT Running on Port: &quot;, port); }); </code></pre> <p>SOCKET.IO</p> <pre><code> io.of(&quot;/chatter&quot;).on(&quot;connection&quot;, (socket) =&gt; { // Join a chatroom socket.on(&quot;join&quot;, (data) =&gt; { let usersList = helper.addUserToRoom(allrooms, data, socket); // Update the list of active users as shown on the chatroom page console.log(&quot;usersList: &quot;, usersList); // console.log(&quot;sessionID: &quot;, socket.request.session); }); }); </code></pre> <p>addUserToRoom FUNCTION</p> <pre><code>let addUserToRoom = (allrooms, data, socket) =&gt; { // Get the room object let getRoom = findRoomById(allrooms, data.roomID); if (getRoom !== undefined) { // Get the active user's ID(ObjectID as used in session) // let userID = socket.request.session.passport.user; let userID = socket.request.user ? socket.request.user.id : &quot;&quot;; //let userID = socket.request.session.passport.user; // Check to see if this user already exist in the chatroom let checkUser = getRoom.users.findIndex((element, index, array) =&gt; { // console.log(&quot;elementID: &quot;, element.userID); if (element.userID === userID) { return true; } else { return false; } }); // If the user is already present in the room, remove the user first if (checkUser &gt; -1) { getRoom.users.splice(checkUser, 1); } // Push the user into the room's users array getRoom.users.push({ socketID: socket.id, userID, user: data.user, userPic: data.userPic, }); // Join the room channel socket.join(data.roomID); // Return the updated room object return getRoom; } }; </code></pre> <p>Create an IO Server instance</p> <pre><code>let ioServer = (app, passport) =&gt; { app.locals.chatrooms = []; const server = require(&quot;http&quot;).createServer(app); const io = require(&quot;socket.io&quot;)(server); const wrap = (middleware) =&gt; (socket, next) =&gt; middleware(socket.request, {}, next); io.use(wrap(require(&quot;./session&quot;))); io.use(wrap(passport.initialize())); io.use(wrap(passport.session())); io.use((socket, next) =&gt; { if (socket.request.user) { next(); } else { next(new Error(&quot;unauthorized&quot;)); } }); require(&quot;./socket&quot;)(io, app); return server; }; </code></pre> <p>You can see in the image below that I get an empty string in the userID <a href="https://i.stack.imgur.com/wM1Qj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wM1Qj.png" alt="enter image description here" /></a></p> <p><strong>UPDATE</strong></p> <p>I adjusted my code to use passport.socketio but I am still getting the same blank string in my UserID, when I print socket.request to the console I get some data but when I print socket.request.user I get undefined:</p> <pre><code>let ioServer = (app, cookieParser) =&gt; { app.locals.chatrooms = []; const config = require(&quot;./config&quot;); const server = require(&quot;http&quot;).Server(app); const io = require(&quot;socket.io&quot;)(server); const passportSocketIo = require(&quot;passport.socketio&quot;); const sessionStore = require(&quot;./session&quot;); const helper = require(&quot;./helpers&quot;); io.use( passportSocketIo.authorize({ cookieParser: cookieParser, key: &quot;connect.sid&quot;, secret: config.sessionSecret, store: sessionStore.store, success: helper.onAuthorizeSuccess, fail: helper.onAuthorizeFail, }) ); const socket = require(&quot;./socket&quot;); socket(io, app); return server; }; </code></pre>
3
2,074
SUM distinct inside window function
<p>I have a data structure similar to this:</p> <pre><code>CREATE TABLE some_table ( dude_id INTEGER, main_date TIMESTAMP, how_many INTEGER, how_much NUMERIC(5,2), their_ids INTEGER[] ) </code></pre> <p>This is the query I've got so far</p> <pre><code>SELECT dude_id, main_date, how_many, how_much, their_ids, SUM(how_many) OVER (PARTITION BY dude_id ORDER BY main_date) AS count_stuff_WRONG, SUM(how_much) OVER (PARTITION BY dude_id ORDER BY main_date) AS cumulative_sum_WRONG FROM some_table </code></pre> <p>This is the result I'm trying to achieve:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>dude_id</th> <th>main_date</th> <th>how_many</th> <th>how_much</th> <th>their_ids</th> <th>count_stuff_EXPECTED</th> <th>cumulative_sum_EXPECTED</th> <th>count_stuff_WRONG</th> <th>cumulative_sum_WRONG</th> </tr> </thead> <tbody> <tr> <td>38</td> <td>2019-06-14</td> <td>1</td> <td>6</td> <td>373</td> <td>1</td> <td>6</td> <td>1</td> <td>6</td> </tr> <tr> <td>38</td> <td>2019-07-15</td> <td>1</td> <td>7</td> <td>374</td> <td>2</td> <td>13 (6+7)</td> <td>2</td> <td>13 (6+7)</td> </tr> <tr> <td>38</td> <td>2019-07-16</td> <td>1</td> <td>8</td> <td>375</td> <td>3</td> <td>21 (6+7+8)</td> <td>3</td> <td>21 (6+7+8)</td> </tr> <tr> <td>38</td> <td>2020-06-14</td> <td>1</td> <td>16</td> <td>373</td> <td>3</td> <td>31 (7+8+16)</td> <td>4</td> <td>37 (6+7+8+16)</td> </tr> <tr> <td>38</td> <td>2020-07-15</td> <td>1</td> <td>17</td> <td>374</td> <td>3</td> <td>41 (8+16+17)</td> <td>5</td> <td>54 (6+7+8+16+17)</td> </tr> <tr> <td>38</td> <td>2020-07-16</td> <td>1</td> <td>18</td> <td>375</td> <td>3</td> <td>51 (16+17+18)</td> <td>6</td> <td>72 (6+7+8+16+17+18)</td> </tr> </tbody> </table> </div> <p>Columns <code>count_stuff_EXPECTED</code> and <code>cumulative_sum_EXPECTED</code> are what I'm trying to get, columns <code>count_stuff_WRONG</code> and <code>cumulative_sum_WRONG</code> are the ones my current query is returning.</p> <p>In other words, I want to get cumulative values for each main_date but without counting/summing multiple times the same <code>their_ids</code>. So on row 4, for example, the window partition has <code>their_ids {373}</code> more than once, so it should be considered only the most recent one (row 4) and not consider the first occurrence (row 1)</p> <p>NOTE: there's no need to show on the query how the sum was calculated, I just put it in there in parentheses for clarity.</p> <p>I tried using</p> <pre><code>SUM(DISTINCT how_many) over (PARTITION BY dude_id ORDER BY main_date) as count_stuff </code></pre> <p>but got</p> <blockquote> <p>ERROR: DISTINCT is not implemented for window functions</p> </blockquote> <p>SQL Fiddle: <a href="http://sqlfiddle.com/#!17/44850/2" rel="nofollow noreferrer">http://sqlfiddle.com/#!17/44850/2</a></p>
3
1,349
multi language change in android studio app
<p>i am working on a project that i need to have some settings that users can choose there language</p> <p>when I use the old version of material design librarys , it work well but if i want to change the dependencys to androidX (android V30) it not work</p> <p>it's mean that if i use</p> <pre><code>import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; </code></pre> <p>it work but if i use</p> <pre><code>import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; </code></pre> <p>it not work</p> <p>not work means (the app will be launch but not work well)</p> <p>my main Activity is</p> <pre><code>package com.faranesh.saman.multilanguage2020; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.res.Configuration; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import java.util.Locale; public class MainActivity extends AppCompatActivity { Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LoadLocale(); setContentView(R.layout.activity_main); ActionBar actionBar=getSupportActionBar(); actionBar.setTitle(getResources().getString(R.string.app_name)); btn=(Button)findViewById(R.id.btn_chang_language); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ChangeLanguageState(); } }); } public void ChangeLanguageState(){ final String[] listItem=new String[]{&quot;English&quot;,&quot;فارسی&quot;}; AlertDialog.Builder dialog=new AlertDialog.Builder(this); dialog.setTitle(&quot;Chosse one Language....&quot;); dialog.setSingleChoiceItems(listItem, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which==0){ setLocale(&quot;en&quot;); recreate(); }else if (which==1){ setLocale(&quot;fa&quot;); recreate(); } dialog.dismiss(); } }); AlertDialog builder=dialog.create(); builder.show(); } public void setLocale(String lang){ Locale locale=new Locale(lang); Locale.setDefault(locale); Configuration configuration=new Configuration(); configuration.locale=locale; getBaseContext().getResources().updateConfiguration(configuration,getBaseContext().getResources().getDisplayMetrics()); SharedPreferences.Editor editor=getSharedPreferences(&quot;settings&quot;,MODE_PRIVATE).edit(); editor.putString(&quot;MY_LANG&quot;,lang); editor.apply(); } public void LoadLocale(){ SharedPreferences sharepref=getSharedPreferences(&quot;settings&quot;,Activity.MODE_PRIVATE); String language=sharepref.getString(&quot;MY_LANG&quot;,&quot;&quot;); setLocale(language); } } </code></pre>
3
1,375
Strange results with dividing in assembler on intel 80368 32 bit
<p>It gets stuck in an infinite loop in function "prebroj". It should count how many digits there are in my result number so i can return it as a string later and exit when <code>%eax</code> becomes 0. When I run it in the debugger when i divide my number (<code>%eax</code>) by the required base (<code>%ecx</code>) so as to get how many digits there is, at one point after the division it returns a very strange number to <code>%eax</code>, but the remainder of the division in <code>%edx</code> keeps returning perfectly normal, even though the resulting number in <code>%eax</code> makes no sense whatsoever. Here is the code, it's rather long but I figured it might be helpful to provide the whole thing. The problem loop is at line 152, near the end. I put a bunch of comments next to it so it's easier to find (the only problem is the loop, I just put the whole program in case it might be relevant, short program description in top comments):</p> <pre><code>#unsigned saberi2 (char *num1, unsigned base1, char *num2, unsigned, base2, char *sum, unsigned *sum_length, unsigned sum_base); # 8 12 16 20 24 28 32 #the subprogram is called from a c program and takes the first 2 numbers from args 1 and 3 as strings (to be converted), their respective bases from args 2 and 4, and returns the sum as a string at the address from arg 5 .text .globl saberi2 saberi2: pushl %ebp movl %esp, %ebp pushl %ebx pushl %esi subl $16, %esp # -4(%ebp) i -8(%ebp) su prvi i drugi broj movl $1, -8(%ebp) movl $0, -12(%ebp) prov_prvi: movl 8(%ebp), %esi movb (%esi), %bl cmpb $'-', %bl jne nm1 movl $-1, -8(%ebp) incl %esi jmp np1 nm1: cmpb $'+', %bl jne np1 incl %esi np1: movl $0, %eax movl 12(%ebp), %ecx cmpl $10, %ecx ja preko10_1 ispod10_1: movb (%esi), %bl cmpb $0, %bl je kraj1 subb $'0', %bl cmpb $0, %bl jl greska1 cmpb 12(%ebp), %bl jg greska1 mull %ecx movb %bl, -12(%ebp) addl -12(%ebp), %eax incl %esi jmp ispod10_1 preko10_1: movb (%esi), %bl cmpb $0, %bl je kraj1 subb $'0', %bl cmpb $0, %bl jl greska1 cmpb $9, %bl jg slovo1 mull %ecx movb %bl, -12(%ebp) addl -12(%ebp), %eax incl %esi jmp preko10_1 slovo1: subb $7, %bl #17 je razmak od 0 do A cmpb $10, %bl jl greska1 cmpb 12(%ebp), %bl jg greska1 mull %ecx movb %bl, -12(%ebp) addl -12(%ebp), %eax incl %esi jmp preko10_1 kraj1: movl -8(%ebp), %ecx mull %ecx movl %eax, -4(%ebp) prov_drugi: movl 16(%ebp), %esi movb (%esi), %bl movl $1, -8(%ebp) cmpb $'-', %bl jne nm2 movl $-1, -8(%ebp) incl %esi jmp np2 nm2: cmpb $'+', %bl jne np2 incl %esi np2: movl $0, %eax movl 20(%ebp), %ecx cmpl $10, %ecx ja preko10_2 ispod10_2: movb (%esi), %bl cmpb $0, %bl je kraj2 subb $'0', %bl cmpb $0, %bl jb greska2 cmpb 20(%ebp), %bl ja greska2 mull %ecx movb %bl, -12(%ebp) addl -12(%ebp), %eax incl %esi jmp ispod10_2 preko10_2: movb (%esi), %bl cmpb $0, %bl je kraj2 subb $'0', %bl cmpb $0, %bl jl greska2 cmpb $9, %bl jg slovo2 mull %ecx movb %bl, -12(%ebp) addl -12(%ebp), %eax incl %esi jmp preko10_2 slovo2: subb $7, %bl #17 je razmak od 0 do A cmpb $10, %bl jl greska2 cmpb 20(%ebp), %bl jg greska2 mull %ecx movb %bl, -12(%ebp) addl -12(%ebp), %eax incl %esi jmp preko10_2 kraj2: movl -8(%ebp), %ecx mull %ecx addl -4(%ebp), %eax jo greska3 ispis: movl 24(%ebp), %ebx #ebx je adresa zbira movl %eax, -4(%ebp) #eax je zbir movl $0, %esi #esi je broj cifara zbira movl 32(%ebp), %ecx #ecx je baza zbira prebroj: cmpl $0, %eax #brojanje cifara zbira je unesi #----------------------------------------------- divl %ecx #THIS IS THE LOOP------------------------------- incl %esi #----------------------------------------------- movl %eax, -12(%ebp) jmp prebroj unesi: #unos cifara na adresu iz arg movl %esi, 28(%ebp) movl -4(%ebp), %eax cmpl $0, %eax jg nmi movb $'-', (%ebx) incl %esi nmi: movb $0, (%ebx, %esi, 1) decl %esi cmpl $10, %ecx ja preko10_i ispod10_i: cmpl $0, %eax je preende divl %ecx addb $'0', %dl movb %dl, (%ebx, %esi, 1) decl %esi jmp ispod10_i preko10_i: cmpl $0, %eax je preende divl %ecx cmpb $9, %dl ja slovoi addb $'0', %dl movb %dl, (%ebx, %esi, 1) decl %esi jmp preko10_i slovoi: addb $55, %dl movb %dl, (%ebx, %esi, 1) decl %esi jmp preko10_i greska1: movl $1, %eax jmp ende greska2: movl $2, %eax jmp ende greska3: movl $3, %eax jmp ende preende: movl $0, %eax ende: popl %esi popl %ebx movl %ebp, %esp popl %ebp ret </code></pre>
3
2,222
How do you assign a char from one char array to another char array in a loop in c?
<p>I am trying to write code that will read in morse code from one .txt file into a char array. I then read in a test file into another char array. From there I want to read the test file into morse code and print it to the monitor.</p> <p>My input files are:</p> <pre><code>A.- B-... C-.- D-.. E. F.._. G--. H.... I.. J.--- K-.- L.-.. M-- N-. O--- P.--. Q--.- R.-. S... T- U..- V...- W.-- X-..- Y-.-- Z--.. ABCDEFGHIJKLMNOPQRSTUVWXYZ </code></pre> <p>My .c code is as follows</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void main() { int i=0,j=0, n=0,x=0, SIZE=100; char SENTENCE[100][100]; char morse[100][100]; char fileName[SIZE]; char SecondFile[SIZE]; printf("Enter a file name\n"); scanf("%s", fileName); FILE *file; /* FILE pointer */ file = fopen(fileName, "r"); /* open a text file for reading */ while(fgets(morse[n++],20,file)) { } for (i=0 ; i&lt;n; i++) { printf("\n%s", morse[i]); } printf("\n\nEnter a file name\n"); scanf("%s", SecondFile); FILE *start; /* FILE pointer */ start = fopen(SecondFile, "r"); /* open a text file for reading */ while(fgets(SENTENCE[j++],30,start)) { } for (i=0 ; i&lt;j; i++) { printf("\n%s", SENTENCE[i]); } for (x=0; x&lt;=SIZE; x++) { if(SENTENCE[x]=='A'||SENTENCE[x]=='a') printf("\n%s", morse[x]); else if(SENTENCE[x]=='B'||SENTENCE[x]=='b') printf("\n%s", morse[x]); else if(SENTENCE[x]=='C'||SENTENCE[x]=='c') printf("\n%s", morse[x]); else if(SENTENCE[x]=='D'||SENTENCE[x]=='d') printf("\n%s", morse[x]); else if(SENTENCE[x]=='E'||SENTENCE[x]=='e') printf("\n%s", morse[x]); else if(SENTENCE[x]=='F'||SENTENCE[x]=='f') printf("\n%s", morse[x]); else if(SENTENCE[x]=='G'||SENTENCE[x]=='g') printf("\n%s", morse[x]); else if(SENTENCE[x]=='H'||SENTENCE[x]=='h') printf("\n%s", morse[x]); else if(SENTENCE[x]=='I'||SENTENCE[x]=='i') printf("\n%s", morse[x]); else if(SENTENCE[x]=='J'||SENTENCE[x]=='j') printf("\n%s", morse[x]); else if(SENTENCE[x]=='K'||SENTENCE[x]=='k') printf("\n%s", morse[x]); else if(SENTENCE[x]=='L'||SENTENCE[x]=='l') printf("\n%s", morse[x]); else if(SENTENCE[x]=='M'||SENTENCE[x]=='m') printf("\n%s", morse[x]); else if(SENTENCE[x]=='N'||SENTENCE[x]=='n') printf("\n%s", morse[x]); else if(SENTENCE[x]=='O'||SENTENCE[x]=='o') printf("\n%s", morse[x]); else if(SENTENCE[x]=='P'||SENTENCE[x]=='p') printf("\n%s", morse[x]); else if(SENTENCE[x]=='Q'||SENTENCE[x]=='q') printf("\n%s", morse[x]); else if(SENTENCE[x]=='R'||SENTENCE[x]=='r') printf("\n%s", morse[x]); else if(SENTENCE[x]=='S'||SENTENCE[x]=='s') printf("\n%s", morse[x]); else if(SENTENCE[x]=='T'||SENTENCE[x]=='t') printf("\n%s", morse[x]); else if(SENTENCE[x]=='U'||SENTENCE[x]=='u') printf("\n%s", morse[x]); else if(SENTENCE[x]=='V'||SENTENCE[x]=='v') printf("\n%s", morse[x]); else if(SENTENCE[x]=='W'||SENTENCE[x]=='w') printf("\n%s", morse[x]); else if(SENTENCE[x]=='X'||SENTENCE[x]=='x') printf("\n%s", morse[x]); else if(SENTENCE[x]=='Y'||SENTENCE[x]=='y') printf("\n%s", morse[x]); else if(SENTENCE[x]=='Z'||SENTENCE[x]=='z') printf("\n%s", morse[x]); else if(SENTENCE[x]=='\0') printf("nothing read"); else if(SENTENCE[x]=='.') printf("nothing read"); else printf("error reading in a character from the file"); } fclose(file); fclose(start); getch(); } </code></pre> <p>In the for loop above I'm trying to print the exact morse code equivalence. The only problem is I keep getting warnings when trying to compare the array <code>SENTENCE[x]</code> with a <code>ch</code>. Also is there anyway to assign certain characters from one char array to another char array in c. Is there a way I can do any of this? I'm currently writing the code in c.</p>
3
2,388
innerHTML not working properly. JavaScript
<p>I am trying to print the result but for some reason <code>innerHTML</code> is not working properly. Can anyone take a look ?</p> <p><strong>Not working</strong></p> <pre><code>let show = document.querySelector('#show') fetch('/fetchDataAll') .then((resp) =&gt; resp.json()) // Transform the data into json .then(function (data) { show.innerHTML = '' let players = data.result; // Get the results let string = players.map(function (player) { let colorToChange = ""; let plusMinusSign = ""; let colorWhite = "#FFFFFF"; if (player.scoreChange &gt;= 0) { colorToChange = "#66FF13"; plusMinusSign = "+"; } else { colorToChange = "#D0021B"; plusMinusSign = ""; } `&lt;p style='color:${colorWhite}'&gt;${player.playerName}&lt;/p&gt; &lt;p style='color:${colorWhite}'&gt;${player.teamName}&lt;/p&gt; &lt;h3 style='color:${colorToChange}'&gt;${plusMinusSign} ${player.scoreChange} %&lt;/h3&gt;` }) .join('') return show.innerHTML += string }) .catch(function (error) { console.log(error); }); </code></pre> <p><strong>Working with jQuery append()</strong></p> <pre><code>let show = document.querySelector('#show') fetch('/fetchDataAll') .then((resp) =&gt; resp.json()) // Transform the data into json .then(function (data) { show.innerHTML = '' let players = data.result; // Get the results return players.map(function (player) { let colorToChange = ""; let plusMinusSign = ""; let colorWhite = "#FFFFFF"; if (player.scoreChange &gt;= 0) { colorToChange = "#66FF13"; plusMinusSign = "+"; } else { colorToChange = "#D0021B"; plusMinusSign = ""; } $("#show").append(`&lt;p style='color:${colorWhite}'&gt;${player.playerName}&lt;/p&gt; &lt;p style='color:${colorWhite}'&gt;${player.teamName}&lt;/p&gt; &lt;h3 style='color:${colorToChange}'&gt;${plusMinusSign} ${player.scoreChange} %&lt;/h3&gt;`) }) }) .catch(function (error) { console.log(error); }); </code></pre> <p><strong>SOLUTION with Vanilla JavaScript</strong></p> <pre><code>let show = document.querySelector('#show') fetch('/fetchDataAll') .then((resp) =&gt; resp.json()) // Transform the data into json .then(function (data) { show.innerHTML = ""; let players = data.result; // Get the results show.innerHTML = players.map(player =&gt; { let colorToChange = ""; let plusMinusSign = ""; let colorWhite = "#FFFFFF"; if (player.scoreChange &gt;= 0) { colorToChange = "#66FF13"; plusMinusSign = "+"; } else { colorToChange = "#D0021B"; plusMinusSign = ""; } return `&lt;p style='color:${colorWhite}'&gt;${player.playerName}&lt;/p&gt; &lt;p style='color:${colorWhite}'&gt;${player.teamName}&lt;/p&gt; &lt;h3 style='color:${colorToChange}'&gt;${plusMinusSign} ${player.scoreChange} %&lt;/h3&gt;` }).join('') }) .catch(function (error) { console.log(error); }); </code></pre>
3
1,743
TCP C: Client not connecting using the IP address you entered?
<p>This is just a simple chat program wherein echoclient sends data to echoserver. In the example code given to us, why is it that the client wouldn't connect if I use an ip-address xxx.xxx.xxx.xxx (where xxx ranges from 0-255, for example 123.124.12.1) but it would if I input random numbers such as 12312 or 23423? In this case, when I print the network ordered ip, it gives</p> <blockquote> <pre><code>Network ordered ip(client side): 00000000 Network ordered ip(server side): 127.0.0.1. </code></pre> </blockquote> <p>I read about 127.0.0.1 being the loopback ip address for localhost. But my question is, why is it that the client only connects with that address?</p> <p>When I run <code>./echoclient 12312</code>, the client connects and the program functions as it should. But if I run<code>./echoclient 123.123.12.1</code>, the client doesn't connect.</p> <p>..or I'm connecting the wrong way?</p> <p>Here's the code:</p> <p>echoserver.c</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; int main(int argc, char **argv) { int listenfd,connfd; struct sockaddr_in servaddr,cliaddr; socklen_t len = sizeof(cliaddr); char cli_ip[32]; char mesg[1024]; listenfd = socket(PF_INET,SOCK_STREAM,0); bzero(&amp;servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(54322); if ( bind( listenfd, (struct sockaddr*) &amp;servaddr, sizeof(servaddr) ) &lt; 0 ){ perror(NULL); exit(-1); } //not present in udp server listen(listenfd,2); while(1){ //not present in udp server connfd = accept(listenfd,(struct sockaddr *)&amp;cliaddr,&amp;len); inet_ntop(AF_INET,(struct in_addr *) &amp;cliaddr.sin_addr, cli_ip, sizeof(cli_ip) ); printf("Client %s connected. \n",cli_ip); while(1){ memset(mesg,0,sizeof(mesg)); if( recvfrom(connfd,mesg,sizeof(mesg),0,(const struct sockaddr *)&amp;cliaddr,&amp;len) &gt; 0 ){ printf("From %s port %d: %s",cli_ip,ntohs(cliaddr.sin_port),mesg); } else { printf("Client %s disconnected. \n",cli_ip); break; } } close(connfd); } close(listenfd); return 0; } </code></pre> <p>echoclient.c</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; int main(int argc, char **argv) { int sockfd; struct sockaddr_in servaddr; socklen_t len = sizeof(servaddr); char mesg[1024]; if(argc!=2){ printf("Usage: %s &lt;ip_addr&gt;\n",argv[0]); exit(1); } sockfd = socket(PF_INET,SOCK_STREAM,0); bzero(&amp;servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(54322); inet_pton(AF_INET,argv[1],&amp;servaddr.sin_addr); //printf("Network ordered ip: %08x\n",servaddr.sin_addr.s_addr); //not present in udp clients connect(sockfd,(struct sockaddr *)&amp;servaddr,sizeof(servaddr)); while(1){ fgets(mesg,sizeof(mesg),stdin); sendto(sockfd,mesg,strlen(mesg),0,(const struct sockaddr *)&amp;servaddr,len); } close(sockfd); return 0; } </code></pre> <p>Thank you in advance!</p>
3
1,400
js.cycle.js and jquery.js conflict
<p>I am new to javaScript and Jquery. I want to design a website that contains both an accordion navigation and a slideshow on the same page. In order to do this, I downloaded this auto scrolling slideshow plugin from htmldrive.net:</p> <p><a href="http://www.htmldrive.net/items/show/110/Auto-Scrolling-Slideshow-Tabs-jQuery-" rel="nofollow">http://www.htmldrive.net/items/show/110/Auto-Scrolling-Slideshow-Tabs-jQuery-</a> </p> <p>(This plugin links to "ajax.googleapis" remotely. It makes use of the "jquery.cycle.js" plugin, and finally the main javascript is located in "slideshow.js".)</p> <p>and this accordion plugin, also from htmldrive.net:</p> <p>The other plugin is also on htmldrive. It's called "Making-accordions-with-the-Tabsjquery (I can't supply a 2nd link in this post as I dont have a reputation of 10 haha) </p> <p>(This plugin makes use of the jquery.js plugin. It also has inline javascript in the html)</p> <p>I have managed to get these 2 plugins working on separate pages, the problem I am running into is they seem to cause conflicts when they are both put on the same page. The conflict seems to come from linking the jquery.js and jquery.cycle.js files to the same page. Interestingly, changing the order in which I link them gives different errors.</p> <p>The errors I get when linking both of these .js files to the same page are:</p> <p>1.</p> <p>TypeError: jQuery("div.slides > ul", jQueryslideshow.context).cycle is not a function</p> <p>(This happens when I link the jquery.js plugin AFTER I have linked the jquery.cycle.js plugin)</p> <p>2.</p> <p>TypeError: jQuery.tools is undefined</p> <p>TypeError: jQuery("#accordion").tabs is not a function</p> <p>(This happens when I link the jquery.cycle.js plugin AFTER I have linked the jquery.js plugin)</p> <p>To me it seems like the browser loads the first .js file and then forgets the functions in this file when it loads the second .js file. I know there is the $.noConflict(); code that apparently is supposed to help with such conflicts but it doesn't seem to work here.</p> <p>The slideshow.js code is as follows:</p> <pre><code>$slideshow = { context: false, tabs: false, timeout: 1000, // time before next slide appears (in ms) slideSpeed: 1000, // time it takes to slide in each slide (in ms) tabSpeed: 300, // time it takes to slide in each slide (in ms) when clicking through tabs fx: 'scrollLeft', // the slide effect to use init: function() { // set the context to help speed up selectors/improve performance this.context = $('#slideshow'); // set tabs to current hard coded navigation items this.tabs = $('ul.slides-nav li', this.context); // remove hard coded navigation items from DOM // because they aren't hooked up to jQuery cycle this.tabs.remove(); // prepare slideshow and jQuery cycle tabs this.prepareSlideshow(); }, prepareSlideshow: function() { // initialise the jquery cycle plugin - // for information on the options set below go to: // http://malsup.com/jquery/cycle/options.html $('div.slides &gt; ul', $slideshow.context).cycle({ fx: $slideshow.fx, timeout: $slideshow.timeout, speed: $slideshow.slideSpeed, fastOnEvent: $slideshow.tabSpeed, pager: $('ul.slides-nav', $slideshow.context), pagerAnchorBuilder: $slideshow.prepareTabs, before: $slideshow.activateTab, pauseOnPagerHover: true, pause: true }); }, prepareTabs: function(i, slide) { // return markup from hardcoded tabs for use as jQuery cycle tabs // (attaches necessary jQuery cycle events to tabs) return $slideshow.tabs.eq(i); }, activateTab: function(currentSlide, nextSlide) { // get the active tab var activeTab = $('a[href="#' + nextSlide.id + '"]', $slideshow.context); // if there is an active tab if(activeTab.length) { // remove active styling from all other tabs $slideshow.tabs.removeClass('on'); // add active styling to active button activeTab.parent().addClass('on'); } } }; $(function() { // add a 'js' class to the body $('body').addClass('js'); // initialise the slideshow when the DOM is ready $slideshow.init(); }); </code></pre> <p>The inline javaScript for the accordion looks as follows:</p> <pre><code> &lt;script&gt; jQuery(function() { jQuery("#accordion").tabs("#accordion div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null}); }); &lt;/script&gt; &lt;!-- activate tabs with JavaScript --&gt; &lt;script&gt; // add new effect to the tabs jQuery.tools.tabs.addEffect("slide", function(i, done) { // 1. upon hiding, the active pane has a ruby background color this.getPanes().slideUp().css({backgroundColor: "#2c2c2c"}); // 2. after a pane is revealed, its background is set to its original color (transparent) this.getPanes().eq(i).slideDown(function() { jQuery(this).css({backgroundColor: 'transparent'}); // the supplied callback must be called after the effect has finished its job done.call(); }); }); &lt;/script&gt; </code></pre> <p>Any help would really be appreciated as I am really stuck here.</p> <p>On the other hand, being a beginner, I am probably making this way more complicated than I should. So If anyone can give me a good way of having an accordion AND a slideshow on the same page, I would really appreciate it.</p>
3
1,842
Return ViewData from view to controller razor pages
<p>I have view is C#:</p> <pre><code>@{ var itemList = (List&lt;Item&gt;)ViewData[&quot;itemsList&quot;]; } &lt;div class=&quot;row&quot; style=&quot;margin-top: 10px;&quot;&gt; &lt;div class=&quot;col-md-6&quot;&gt; @if (itemList != null) { var id = 0; &lt;table class=&quot;table table-striped&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;#&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;Id&lt;/th&gt; &lt;th&gt;Type&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; @foreach (var result in itemsList) { &lt;tr&gt; &lt;td&gt;@(++id)&lt;/td&gt; &lt;td&gt;&lt;input type=&quot;checkbox&quot; value=&quot;true&quot; @(result.Checked ? &quot;checked&quot; : &quot;&quot;)&gt;&lt;/td&gt; &lt;td&gt;@result.Id&lt;/td&gt; &lt;td&gt;@result.Type&lt;/td&gt; &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; } &lt;div class=&quot;row justify-content-end&quot; style=&quot;margin-top: 20px;&quot;&gt; &lt;div class=&quot;col-md-2&quot;&gt; &lt;form asp-controller=&quot;Control&quot; asp-action=&quot;Remove&quot; method=&quot;post&quot;&gt; &lt;input type=&quot;hidden&quot; name=&quot;tableName&quot; value=&quot;table&quot;/&gt; &lt;input type=&quot;hidden&quot; name=&quot;items&quot; value=&quot;@itemList&quot;/&gt; &lt;div style=&quot;margin-left: -10px;&quot; class=&quot;col-md-2&quot;&gt; &lt;button class=&quot;btn btn-danger&quot; title=&quot;Remove&quot; type=&quot;submit&quot;&gt;Remove&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to remove items from table, where user checks the checkbox. My idea was to update each checked item withing the list (<code>result.Checked</code> property) and then send array to Remove method:</p> <pre><code>[HttpPost] public async Task&lt;IActionResult&gt; Remove(string tableName, List&lt;ChangeQueueItem&gt; items) { try { var toDelete = items.Where(x =&gt; x.Checked == true); await _repository.RemoveFromQueue(toDelete, tableName); } catch (Exception e) { TempData[&quot;error&quot;] = e.Message; } return RedirectToAction(&quot;Index&quot;); } </code></pre> <p>I am trying to send that list like this:</p> <p><code>&lt;input type=&quot;hidden&quot; name=&quot;items&quot; value=&quot;@itemList&quot;/&gt; </code></p> <p>however the value is null. How should I do it?</p> <p>Update: data is loaded here:</p> <pre><code>[HttpGet] public async Task&lt;IActionResult&gt; Index() { var items = await _repository.GetAll(); ViewData[&quot;itemsList&quot;] = items; ViewData[&quot;error&quot;] = TempData[&quot;error&quot;]; return View(&quot;Index&quot;); } </code></pre>
3
1,881
How do I integrate numerically a function in Python?
<p>I'm trying to write a Python code (based on a Mathematica notebook) that includes some integrations, but I had no luck so far.<br> The integral I'm trying to evaluate is:</p> <p><a href="https://i.stack.imgur.com/EKTPf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EKTPf.png" alt="Integral"></a></p> <p>where,</p> <p><a href="https://i.stack.imgur.com/RqLOk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RqLOk.png" alt="Ls matrices"></a></p> <p><em>*It's for Bjorken-Mtingwa Intra-beam scattering calculations.</em></p> <p>In Python, what I'm trying is: </p> <pre class="lang-py prettyprint-override"><code>import numpy as np import math from sympy import Symbol from scipy import interpolate import scipy.integrate as integrate from scipy.integrate import quad def Aint(Np, r, c , beta_rel, gamma_rel, emit_x, emit_y, Sigma_s, Sigma_M): return (Np * r**2 *c) / ( 64 * np.pi**2 * beta_rel**3 * gamma_rel**4 * emit_x * emit_y * Sigma_s * Sigma_M) def MatrixSum(M1 ,M2 ,M3): return [[M1[i,j] + M2[i,j] + M3[i,j] for j in range (M1.shape[0])] for i in range(M1.shape[1])] #Then I'm initializing all my parameters by loading a file into a dataframe and doing some calculations. I will not include most of that part to keep it short. I have no complex numbers. gamma_rel = 1.00451006711 beta_rel = 0.09465451392 beta_x = 7.890105185 beta_y = 13.61578059 Phi_x = -1.957881913 Phi_y = 0.0 emx = 2.95814809e-06 emy = 2.95814809e-06 H_x = 32.68714662287 H_y = 0.0 bl = 4.256474951 r0 = 2.16775224067e-17 Sigma_M = 0.00118124786 II = np.identity(3) ABM = Aint(Np, r0, c, beta_rel, gamma_rel, emx, emy, bl, Sigma_M) Clog = 13.53496204 #Evaluating the Coulomb logarithm with a function but seems correct so I will not include the calculations. Lp = (gamma_rel**2 / Sigma_M) * np.matrix( [ [0,0,0], [0,1,0], [0,0,0] ] ) Lx = (beta_x / emx) * np.matrix( [ [1, - gamma_rel * Phi_x, 0], [- gamma_rel * Phi_x, gamma_rel**2 * H_x / beta_x , 0], [0, 0, 0] ] ) Ly = (beta_y / emy) * np.matrix( [ [0, 0, 0], [0, gamma_rel**2 * H_y / beta_y, - gamma_rel * Phi_y], [0, - gamma_rel * Phi_y, 1] ] ) L = np.matrix(MatrixSum(Lx, Ly, Lp)) Ix = integrate.quad(lambda x: (x**(1/2.0) * (np.trace(Lx) * np.trace(np.linalg.inv(L + x * II)) - 3 * np.trace(np.matmul(Lx, np.linalg.inv(L + x * II)))) / np.linalg.det(L + x * II)**(1/2.0)) , 0, np.inf) Ixx = 4 * np.pi * ABP * Clog * Ix[0] #Similarly for the other 2 integrals. In reality, all 3 integrals are evaluated in a double loop. </code></pre> <p>but I am getting different results from mathematica. I have also tried <code>scipy.integrate.simps</code> but that did not help either. </p> <p>In Mathematica, I simply integrate it with:</p> <pre><code>Ix = NIntegrate[Intx, {x, 0, inf}, MaxRecursion -&gt; 100]; </code></pre> <p>with Intx being the integral of the photo and the same procedure being done before. </p> <p>Is there any recommendation for how to integrate this function efficiently? Is there something wrong with my method? </p>
3
1,262
How to manage libraries when building projects?
<p>I have a project <code>XXX</code> that depends on another framework <code>YYY</code>. The framework provides a <code>YYYConfig.cmake</code>. When I configure my project with <code>cmake-gui</code> I add the framework over the <code>YYY_DIR</code> variable. I generate and build the solution. Now when I run <code>XXX.exe</code> I get an error that a <code>.dll</code> from <code>YYY</code> couldn't be loaded. The <code>.lib</code> libraries and header files are found if I'm right.</p> <p>Online I've seen that <code>.dll</code> have to be put in the same folder where the <code>.exe</code> is located in. But why can't I just use the <code>.dll</code> that are already present in the installation folder of <code>YYY</code>? And is there a way to automatically put all <code>.dll</code> that my project needs into the right folder?</p> <p>I have the feeling that I'm lacking a bit of fundamental knowledge about deployment, so I'd highly appreciate any helpful reference or link about that. Thanks.</p> <hr> <p><em>Additional information</em></p> <p>I've built a framework, i.e. <a href="https://github.com/alicevision/AliceVision" rel="nofollow noreferrer"><em>AliceVision</em></a> using <code>vcpkg</code>, <code>cmake-gui</code> and Visual Studio 2019. The folder of the installed framework contains the following folders:</p> <ul> <li><code>bin</code> with many <code>.exe</code> and <code>.dll</code></li> <li><code>share</code> where <code>AliceVisionConfig.cmake</code> is located in</li> <li><code>include</code> with many <code>.hpp</code> of the framework and other dependencies</li> <li><code>lib</code> with many <code>.lib</code></li> </ul> <p>Now I try to create a simple test project with a <code>main.cpp</code></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;aliceVision/system/cpu.hpp&gt; int main() { std::cout &lt;&lt; "Total cpus " &lt;&lt; aliceVision::system::get_total_cpus() &lt;&lt; std::endl; return EXIT_SUCCESS; } </code></pre> <p>and a <code>CMakeLists.txt</code></p> <pre><code>cmake_minimum_required(VERSION 3.3) project(AliceVisionAs3rdParty) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(AliceVision CONFIG REQUIRED) message(STATUS "Found AliceVision : ${AliceVision_FOUND}") message(STATUS "Found AliceVision version: ${AliceVision_VERSION}") add_executable(testAV3rd main.cpp) target_link_libraries(testAV3rd PUBLIC aliceVision_system) </code></pre> <p>When configuring with <code>cmake-gui</code> in the folder of my test project I'm just using a variable <code>AliceVision_DIR</code> to point at the folder <code>AliceVisionConfig.cmake</code> is located in. I'm using <code>vcpkg</code> for the toolchain, which is needed by the framework for some dependencies. Then I'm generating and building the solution. Here is the point where I'm starting the <code>.exe</code> and getting the message that a <code>aliceVision_system.dll</code> couldn't be found. It is present in the <code>bin</code> folder of the framework and as <code>aliceVision_system.lib</code> in the <code>lib</code> folder. I've checked the <code>.exe</code> with <a href="https://github.com/lucasg/Dependencies" rel="nofollow noreferrer"><em>Dependencies</em></a> and yes, it's this <code>.dll</code> that is not found. All the Windows <code>.dll</code> stuff is found ...</p>
3
1,108
Java Swing: Controlling focus with textfield and autocompletion dialog/menu
<p>I have a <code>JTextField</code> that I'm trying to add an autocompletion menu to. But I'm having issues with how I should handle the focus.</p> <p>Here's a <a href="http://sscce.org/" rel="nofollow noreferrer">SSCCE</a></p> <pre><code>package test; import java.awt.Point; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class SSCCE extends JFrame implements DocumentListener { private AutocompletionDialog dialog; public SSCCE() { dialog = new AutocompletionDialog (); JTextField textField = new JTextField(20); textField.getDocument().addDocumentListener(this); add(textField); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new SSCCE().setVisible(true); } }); } public void insertUpdate(DocumentEvent e) { Point p = this.getLocationOnScreen(); dialog.setLocation(p.x, p.y + 50); dialog.setVisible(true); } public void removeUpdate(DocumentEvent e) { } public void changedUpdate(DocumentEvent e) { } private class AutocompletionDialog extends JDialog { JList&lt;String&gt; list = new JList&lt;&gt;( new String[] { "One", "Two", "Three" }); AutocompletionDialog() { setSize(100, 100); add(list); } } } </code></pre> <p>Of course there's more logic to it in the real program, but the issue I'm having is that I want to show the autocompletion dialog/menu, but still be able to continue typing in the text field. At the same time, I also want to be able to navigate the menu with the up/down arrows and the enter key, as well as with the mouse, to select one of the completion options.</p> <p>Can someone please help me with how I should proceed here? Thanks!</p> <p><strong>EDIT:</strong></p> <p>Thanks to <a href="https://stackoverflow.com/users/131872/camickr">@camickr</a>'s reply I played around a bit with <code>setFocusableWindowState</code> together with an InputMap/ActionMap to always keep the focus in the text field, and manually control the selected list item. The problem is that you get a visual difference when doing it that way compared to if the list had proper focus. See the screen shots.</p> <p>This is what it looks like if I don't mess with the focus (this is what I want).</p> <p><img src="https://i.stack.imgur.com/jIcgx.png" alt="dialog with proper focus"></p> <p>This is what it looks like if I run <code>setFocusableWindowState(false)</code></p> <p><img src="https://i.stack.imgur.com/ie39d.png" alt="dialog with no focus"></p> <p>The main differences are the highlight border (darker blue) around the selected list item, but also the blue highlight around the entire dialog. Then there's also the differences in the title bar.</p> <p>(Don't mind the render artifacts, I'm connecting to a three year old virtual Linux installation using an old NX client)</p> <p><strong>EDIT 2:</strong></p> <p>I was afraid that it was the Look and Feel or OS that determined how the selected list item should look (with the highlighted border for example). But it turns out that it is indeed just the cell renderer that makes that call. Knowing that I felt much better about writing my own cell renderer, and I now have a solution that I'm happy with.</p> <p>This is the code I ended up using:</p> <pre><code>private class CellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent( JList&lt;?&gt; jlist, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent( jlist, value, index, isSelected, cellHasFocus); if (isSelected) { Border border = UIManager.getBorder( "List.focusSelectedCellHighlightBorder"); if (border == null) { border = UIManager.getBorder( "List.focusCellHighlightBorder"); } setBorder(border); } return this; } } </code></pre>
3
1,608
"re-starting" a loop after adding items to an NSMutableArray
<p>I have the following code to simulate a process flow in my laboratory. Whereby a timer adds new items to a NSMutablearray. How do I get the while [array count] !=0 loop to recognise the new additions?</p> <p>Or is there a better methodology?</p> <p>I'm using GCD blocks to simulate a parallel process. The HEFTBooker object just takes a sample number and then waits a defined time period before "marking" itself as free to process another sample.</p> <pre><code>-(void)runBookingIn:(id)sender { HEFTLaboratoryUnit *__labUnit = [[HEFTLaboratoryUnit alloc]init]; self.labUnit = __labUnit; NSMutableArray *sampleNumbers = [[NSMutableArray alloc]init]; // Speed factor speeds up time for modelling i.e. 10 = 10 x normal time. NSInteger speedFactor = 10; // Sample arrival rate into laboratory per hour NSInteger sampleArrivalRate = 50; __weak id weakSelf = self; self.timer = [RNTimer repeatingTimerWithTimeInterval:sampleArrivalRate/speedFactor block:^{ [weakSelf addNewSamplesToQueue]; }]; for (int i = 1; i &lt;= 10; i++) { [sampleNumbers addObject:[NSNumber numberWithInteger:i]]; } self.labUnit.samplesToBeBookedIn = sampleNumbers; NSMutableArray *bookerIns = [[NSMutableArray alloc]init]; HEFTBookerIn *webster = [[HEFTBookerIn alloc]init]; webster.bookingInRate = 60; webster.name=@"Webster"; [bookerIns addObject:webster]; HEFTBookerIn *duffy = [[HEFTBookerIn alloc]init]; duffy.bookingInRate = 30; duffy.name=@"Duffy"; [bookerIns addObject:duffy]; HEFTBookerIn *marrington = [[HEFTBookerIn alloc]init]; marrington.bookingInRate = 40; marrington.name=@"Marrington"; [bookerIns addObject:marrington]; HEFTBookerIn *chatha = [[HEFTBookerIn alloc]init]; chatha.bookingInRate = 10; chatha.name=@"Kam"; [bookerIns addObject:chatha]; int i = 0; long countSamples; countSamples = [self.labUnit.samplesToBeBookedIn count]; // loop sample numbers dispatch_queue_t queue; queue = dispatch_queue_create("com.HEFT.BookerQueue", DISPATCH_QUEUE_SERIAL); dispatch_queue_t arrivalsQueue; arrivalsQueue = dispatch_queue_create("com.HEFT.ArrivalsQueue", DISPATCH_QUEUE_SERIAL); while ([self.labUnit.samplesToBeBookedIn count] != 0 ) { NSInteger sampleNo = [[self.labUnit.samplesToBeBookedIn objectAtIndex:i] integerValue]; long count = [bookerIns count]; int counter = 0; //loop over booker ins int j; for (j=0; j &lt;count ; j++) { HEFTBookerIn *booker = [bookerIns objectAtIndex:counter]; if (booker.free == YES){ dispatch_sync(queue, ^{ [booker bookingIn:sampleNo :speedFactor]; [self.labUnit.samplesToBeBookedIn removeObjectAtIndex:i]; }); break; } else{ counter ++; } } } } -(void) addNewSamplesToQueue{ NSLog(@"More Samples Arriving"); for (int i = 1; i &lt;= 10; i++) { [self.labUnit.samplesToBeBookedIn addObject:[NSNumber numberWithInteger:i]]; } } </code></pre>
3
1,328
multiple countdowns starting at oncewith no end
<p><strong>First Problem:</strong> <br>I have 4 Countdowns(which start from different values) that should start when i click on the imageview next to them. But the problem is, when i click the first picture, all 4 countdowns start; when i click the second picture, the second, third and fourth countdowns start and so on.<br>I think I've done something wrong in my switch case but it doesn't show any errors and I can't find the mistake.<br> <br><strong>Second Problem:</strong><br> When i click the "new game" button, all timers should stop and become 0 but when i click the timers start again and show their old remaining time and the new remaining time.<br> <strong>Code:</strong></p> <pre><code>public class TimerActivity extends Activity implements android.view.View.OnClickListener { private CountDownTimer countDownTimer; private Button button_new_fight; public TextView textviewRed; public TextView textviewBlue; public TextView textviewDragon; public TextView textviewBaron; public TextView tv; public ImageView imageviewRed; public ImageView imageviewBlue; public ImageView imageviewDragon; public ImageView imageviewBaron; private boolean timerRedStarted; private boolean timerBlueStarted; private boolean timerDragonStarted; private boolean timerBaronStarted; private final long startTimeRed = 300000; private final long startTimeBlue = 300000; private final long startTimeDragon = 360000; private final long startTimeBaron = 420000; private final long interval = 1000; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.timer_layout); //binding content to these attributes to work with them button_new_fight = (Button) this.findViewById(R.id.button1); button_new_fight.setOnClickListener(this); textviewRed = (TextView) this.findViewById(R.id.textViewRedTime); textviewBlue = (TextView) this.findViewById(R.id.TextViewBlueTimeLeft); textviewDragon = (TextView) this.findViewById(R.id.TextViewDragonTimeLeft); textviewBaron = (TextView) this.findViewById(R.id.TextViewBaronTimeLeft); //binding this.imageviews to those of timer_layout.xml imageviewRed = (ImageView) this.findViewById(R.id.imageView1); imageviewRed.setOnClickListener(this); imageviewBlue = (ImageView) this.findViewById(R.id.imageView2); imageviewBlue.setOnClickListener(this); imageviewDragon = (ImageView) this.findViewById(R.id.imageView3); imageviewDragon.setOnClickListener(this); imageviewBaron = (ImageView) this.findViewById(R.id.imageView4); imageviewBaron.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: // clear all timers if (countDownTimer != null) { countDownTimer.cancel(); countDownTimer = null; } // start timer red case R.id.imageView1: if (timerRedStarted == false) { countDownTimer = new MyCount(startTimeRed, interval, textviewRed); textviewRed.setText(textviewRed.getText() + String.valueOf(startTimeRed)); countDownTimer.start(); } // start timer blue case R.id.imageView2: if (timerBlueStarted == false) { countDownTimer = new MyCount(startTimeBlue, interval, textviewBlue); countDownTimer.start(); } // start timer dragon case R.id.imageView3: if (timerDragonStarted == false) { countDownTimer = new MyCount(startTimeDragon, interval, textviewDragon); countDownTimer.start(); } // start timer baron case R.id.imageView4: if (timerBaronStarted == false) { countDownTimer = new MyCount(startTimeBaron, interval, textviewBaron); countDownTimer.start(); } } } </code></pre> <p>}</p> <p>class MyCount extends CountDownTimer {</p> <pre><code>private TextView tv; public MyCount(long millisInFuture, long countDownInterval, TextView tv) { super(millisInFuture, countDownInterval); this.tv = tv; } @Override public void onTick(long millisUntilFinished) { tv.setText("" + millisUntilFinished / 1000); } </code></pre>
3
1,592
What is the best way to serialize xml into appropriate objects when versioned by namespaces?
<p>My question is the following.</p> <p>I have xml that is versioned by a namespace. I want to serialize this received xml into the appropriate object, but the only way I know to do this means I have to process the xml two times. First to discover the namespace, and then in order to serialize to the object of the proper type based on the discovered namespace. This seems dreadfully inefficient to me, and there must be some way using generics or something to get the appropriate type of object back without an 'if namespace == x then serialze to that' check.</p> <p>Below is a sample of the only way I know to accomplish this. Is there a better or more efficient way?</p> <p>Thanks</p> <pre><code>using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Xml.Linq; using System.Xml; using System.Xml.Serialization; using System.IO; namespace TestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod3() { //Build up an employee object to xml Schema.v2.Employee employee = new Schema.v2.Employee { FirstName = "First", LastName = "Last" }; string xml = employee.ObjectToXml&lt;Schema.v2.Employee&gt;(); //Now pretend I don't know what type I am receiving. string nameSpace = GetNamespace(xml); Object newemp; if (nameSpace == "Employee.v2") newemp = XmlSerializationExtension.XmlToObject&lt;Schema.v2.Employee&gt;(null, xml); else newemp = XmlSerializationExtension.XmlToObject&lt;Schema.v1.Employee&gt;(null, xml); // Check to make sure that the type I got was what I made. Assert.AreEqual(typeof(Schema.v2.Employee), newemp.GetType()); } public string GetNamespace(string s) { XDocument z = XDocument.Parse(s); var result = z.Root.Attributes(). Where(a =&gt; a.IsNamespaceDeclaration). GroupBy(a =&gt; a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName, a =&gt; XNamespace.Get(a.Value)). ToDictionary(g =&gt; g.Key, g =&gt; g.First()); foreach (System.Xml.Linq.XNamespace item in result.Values) if (item.NamespaceName.Contains("Employee")) return item.NamespaceName; return String.Empty; } } public static class XmlSerializationExtension { public static string ObjectToXml&lt;T&gt;(this T Object) { XmlSerializer s = new XmlSerializer(Object.GetType()); using (StringWriter writer = new StringWriter()) { s.Serialize(writer, Object); return writer.ToString(); } } public static T XmlToObject&lt;T&gt;(this T Object, string xml) { XmlSerializer s = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(xml)) { object obj = s.Deserialize(reader); return (T)obj; } } } } namespace Schema.v1 { [XmlRoot(ElementName = "Employee", Namespace= "Employee.v1", IsNullable = false)] public class Employee { [XmlElement(ElementName = "FirstName")] public string FirstName { get; set; } [XmlElement(ElementName = "LastName")] public string LastName { get; set; } } } namespace Schema.v2 { [XmlRoot(ElementName = "Employee", Namespace = "Employee.v2", IsNullable = false)] public class Employee { [XmlAttribute(AttributeName = "FirstName")] public string FirstName { get; set; } [XmlAttribute(AttributeName = "LastName")] public string LastName { get; set; } } } </code></pre>
3
1,740
micropython: loading data from a file in function causing an endless loop
<p>I am working on a lopy4 from pycom and I have encountered an od problem while loading config data from a txt file:</p> <pre><code>def loadFromConfigFile(): f= open('config.txt') for line in f: if &quot;uuidExpected&quot; in line: uuidExpected=line[13:len(line)-1].strip() elif &quot;app_eui&quot; in line: app_eui = ubinascii.unhexlify((line[8:len(line)-1]).strip()) elif &quot;app_key&quot; in line: app_key = ubinascii.unhexlify((line[8:len(line)-1]).strip()) elif &quot;syncClockTime&quot; in line: syncClockTime=float(line[14:len(line)-1].strip()) elif &quot;loraJoinTime&quot; in line: loraJoinTime=float(line[13:len(line)-1].strip()) elif &quot;bleScanInterval&quot; in line: bleScanInterval=int(line[16:len(line)-1].strip()) elif &quot;mainLoopWaitTime&quot; in line: mainLoopWaitTime=int(line[17:len(line)-1].strip()) elif &quot;hbInterval&quot; in line: hbInterval=int(line[11:len(line)-1].strip()) f.close() loadFromConfigFile() </code></pre> <p>When I use this function my programme gets stuck here:</p> <pre><code>lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) while not lora.has_joined(): time.sleep(loraJoinTime) print('Not yet joined...') print(&quot;joined!&quot;) setClock() </code></pre> <p>The sleep function doesn't work and the print function spams &quot;Not yet joined...&quot; in the terminal window.</p> <pre><code>f= open('config.txt') for line in f: if &quot;uuidExpected&quot; in line: uuidExpected=line[13:len(line)-1].strip() elif &quot;app_eui&quot; in line: app_eui = ubinascii.unhexlify((line[8:len(line)-1]).strip()) elif &quot;app_key&quot; in line: app_key = ubinascii.unhexlify((line[8:len(line)-1]).strip()) elif &quot;syncClockTime&quot; in line: syncClockTime=float(line[14:len(line)-1].strip()) elif &quot;loraJoinTime&quot; in line: loraJoinTime=float(line[13:len(line)-1].strip()) elif &quot;bleScanInterval&quot; in line: bleScanInterval=int(line[16:len(line)-1].strip()) elif &quot;mainLoopWaitTime&quot; in line: mainLoopWaitTime=int(line[17:len(line)-1].strip()) elif &quot;hbInterval&quot; in line: hbInterval=int(line[11:len(line)-1].strip()) f.close() </code></pre> <p>When I don't wrap this code into a function everything works. When I write the function after the hardcoded loop everything works as well.</p>
3
1,170
Data not posting on mongoose with express and jade
<h2>My registration form data is not posting on mongoose database Here is my code</h2> <p>my code working when i get the data from my database but its not posting code please help me guys</p> <pre><code> app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(bodyParser.json()); app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); **mongoose connection** mongoose.connect(&quot;mongodb://localhost:27017/change&quot;) .then(() =&gt; console.log('Connected to MongoDB ...')) .catch(err =&gt; console.error('Could not connect to MongoDB....',err)); </code></pre> <h2>Schema</h2> <pre><code> // Schema const courseSchema = new mongoose.Schema({ firstName: String, fName: String, add1: String, add2: String, city: String, province: String, zip:Number, country: String, age: Number, gender: String, color:String, Height:Number, mTongue:String, moi:String, disability:String, religion:String, mHealth:String, name:String, contact:Number, add3:String, add4:String, city1:String, state:String, postal:String, country1:String, RTC:String, email: String, profileimage:{ type: String }, date: { type: Date, default: Date.now}, isPublished: Boolean });` </code></pre> <h2>Routing</h2> <pre><code>app.post(&quot;/addname&quot;,upload.single('profileimage'), (req, res) =&gt; { const myData = new User(req.body); myData.save() .then(item =&gt; { res.redirect('/'); }) .catch(err =&gt; { res.status(400).send(&quot;Unable to save to database&quot;); }); </code></pre> <h2>**Jade Code **</h2> <p>Here is my registration form code</p> <pre><code> &gt; `form(method='post', action='/addname') hr .row .col-sm-6 .form-group label Name input.form-control(type='text', name='firstName', placeholder='Enter Name') .col-sm-6 .form-group label Father Name input.form-control(type='text', name='fName', placeholder='Enter Name', required) .col-sm-6 .form-group label Address Line 1 input.form-control(type='text', name='add1', placeholder='Enter Address Line 1', required) .col-sm-6 .form-group label Address Line 2 input.form-control(type='text', name='add2', placeholder='Enter Address Line 2', required) .col-sm-6 .form-group label City input.form-control(type='text', name='city', placeholder='Enter City', required) .col-sm-6 .form-group label State/Province/Region select.form-control(name='state', id='' .dropdown-menu , required) each val in ['Sindh' , 'Punjab' , 'KPK' ,'Balochistan', 'Gilgit-Baltistan' , 'AJK', 'Islamabad'] option=val .col-sm-6 .form-group label Postal / Zip Code input.form-control(type='text', name='zip', placeholder='Enter Postal / Zip Code', required) .col-sm-6 .form-group label Country input.form-control(type='text', name='country', placeholder='Country', required) .col-sm-6 .form-group label Age input.form-control(type='number', name='age' , placeholder='Age', required) .col-sm-6 .form-group label Gender select.form-control(name='gender', id='' .dropdown-menu , required) each val in ['Male' , 'Female' , 'Other'] option=val .col-sm-6 .form-group label Color select.form-control(name='color', id='', required .dropdown-menu) each val in ['Fair' , 'Brown' , 'Dark' , 'Black' , 'Wheatish'] option=val .col-sm-6 .form-group label Height input.form-control(type='text', name='height', placeholder='Enter Height', required) .col-sm-6 .form-group label Mother Tongue select.form-control(name='mTongue', id='', required .dropdown-menu) each val in ['Sindhi' , 'Balochi' , 'Urdu' , 'Punjabi' , 'Phusto' , 'Other'] option=val .col-sm-6 .form-group label Marks of Identification input.form-control(type='text', name='moi', placeholder='Enter Marks of Identification ', required) .col-sm-6 .form-group label Disability if any input.form-control(type='text', name='disability', placeholder='Disability if any', required) .col-sm-6 .form-group label Religion input.form-control(type='text', name='religion', placeholder='Religion', required) .col-sm-6 .form-group label Mental Helth input.form-control(type='text', name='mHealth', placeholder='Enter Mental Helth', required) //- .col-sm-6 //- .form-group //- label Missing Person Image //- input.form-control(name='profileimage', type='file') hr h2 Information Details .row .col-sm-6 .form-group label Name input.form-control(type='text', name='name', placeholder='Enter Name', required) .col-sm-6 .form-group label Contact No input.form-control(type='text', name='contact', placeholder='Enter Contact NO', required) .col-sm-6 .form-group label Address Line 1 input.form-control(type='text', name='add3', placeholder='Enter Address Line 1', required) .col-sm-6 .form-group label Address Line 2 input.form-control(type='text', name='add4', placeholder='Enter Address Line 2', required) .col-sm-6 .form-group label City input.form-control(type='text', name='city1', placeholder='Enter City', required) .col-sm-6 .form-group label State/Province/Region select.form-control(name='state', id='' .dropdown-menu , required) each val in ['Sindh' , 'Punjab' , 'KPK' ,'Balochistan', 'Gilgit-Baltistan' , 'AJK', 'Islamabad'] option=val .col-sm-6 .form-group label Postal / Zip Code input.form-control(type='text', name='postal', placeholder='Enter Postal / Zip Code', required) .col-sm-6 .form-group label Country input.form-control(type='text', name='country1', placeholder='Country', required) .col-sm-6 .form-group label Relation to the child input.form-control(type='text', name='RTC', placeholder='Relation to the child', required) .col-sm-6 .form-group label Email input.form-control(type='email', name='email', id=&quot;exampleInputEmail1&quot; , placeholder='Email', required) .col-sm-6 .form-group input.btn.btn-primary(type='submit', name='submit',value='Submit')` [When i posted data ][1] </code></pre> <p>When i post the data my data is not posting in database and show error but if i find the data show on my page its shows data</p> <pre><code> [1]: https://i.stack.imgur.com/pnGvC.png </code></pre>
3
3,884
Tooltip: position & full width (at the same time)
<p>What CSS would force a tooltip:-</p> <ul> <li>to be positioned just above its reference text and</li> <li>to take up the full width of its reference text's container</li> </ul> <p>...at the same time?</p> <p><a href="https://i.stack.imgur.com/VgXOz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VgXOz.png" alt="enter image description here" /></a></p> <p>By default, the length between the reference text's first and last characters are considered. How to make the reference text's most left and right edges to be considered the length for the absolutely positioned child element?</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>.tooltip { width: 100%; margin: 0 auto; /* left: 0; */ /* right: 0; */ position: absolute; top: 0; transform: translateY(calc(-100% - 5px)); background-color: white; color: red; border: 1px solid red; } .has-tooltip { position: relative; outline: 1px solid black; } /* ########### NOT IMPORTANT ############ */ body { text-align: justify; } .container { display: table-cell; resize: both; overflow: auto; border: 1px solid gray; padding: 5px; width: 595px; } .filler { color: gray; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;span class="filler"&gt; Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. &lt;/span&gt; &lt;span class="has-tooltip"&gt; The tooltip spreads between the first and last characters of this text. Is there any way to force the tooltip to take up the full width of this reference text while at the same time it is also absolute positioned to this reference text. &lt;span class="tooltip"&gt; Tooltip: position &amp; full width (at the same time)? &lt;/span&gt; &lt;/span&gt; &lt;span class="filler"&gt; Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. &lt;/span&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
3
1,151
Create multiple chart.js charts from jsonfile data
<p>I have created a json file using python which is a list of lists. Each sublist has data for a chart.js chart i.e.<code>chartObject[0]</code> has <code>chartObject[0][0]</code> and <code>chartObject[0][1]</code> for x and y axis.</p> <p>This is the <a href="http://secstat.info.s3.eu-west-2.amazonaws.com/testthechartdata001.json" rel="nofollow noreferrer">json</a> containing the list and sublist.</p> <p>The code below creates one chart but I would like to loop though all entries and create charts for each sublist (multiple instances of the chart).</p> <p>How do I loop through the json file listed in the code below and create multiple chart.js charts? i.e. a chart for <code>chartObject[0]</code>, <code>chartObject[1]</code> etc.</p> <pre><code>&lt;script&gt; const requestURL = "http://secstat.info.s3.eu-west-2.amazonaws.com/testthechartdata001.json"; const request = new XMLHttpRequest(); request.open("GET", requestURL); request.send(); request.onreadystatechange = function() { if (request.readyState === 4) { doWithResponse(request.response); } }; function doWithResponse(chart) { var chartObject = JSON.parse(chart) var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: "horizontalBar", data: { labels: [...chartObject[0]], datasets: [ { label: "Frequency", data: [...chartObject[1]], backgroundColor: [ "rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)" ], borderColor: [ "rgba(255, 99, 132, 1)", "rgba(54, 162, 235, 1)", "rgba(255, 99, 132, 1)", "rgba(54, 162, 235, 1)", "rgba(255, 99, 132, 1)", "rgba(54, 162, 235, 1)", "rgba(255, 99, 132, 1)", "rgba(54, 162, 235, 1)", "rgba(255, 99, 132, 1)", "rgba(54, 162, 235, 1)" ], borderWidth: 2 } ] }, options: { title: { display: true, text: 'Threat Count'}, legend: { display: false } , scales: { yAxes: [ { ticks: { beginAtZero: true } } ] } } }); } &lt;/script&gt; </code></pre>
3
1,338
wr new printwriter *bw( error). Program gets basic info form user (id,name last name.) However still getting that error. Any idea?
<p>i am using the following code:</p> <pre><code>package Presentacion; import java.util.ArrayList; import java.util.List; import java.util.*; import java.io.*; public class RegistroUser { String Nombres, Apellidos, id, dia, mes, ano, s, ce, df, celu, RH; Scanner sc = new Scanner(System.in); List&lt;List&lt;String&gt;&gt; lista = new ArrayList&lt;List&lt;String&gt;&gt;(); public List&lt;List&lt;String&gt;&gt; getlista() { return lista; } public List&lt;List&lt;String&gt;&gt; getLista() { return lista; } public void setLista(List&lt;List&lt;String&gt;&gt; Lista) { this.lista = Lista; } public void Columna() { for (int i = 0; i &lt; 9; i++) { lista.add(new ArrayList&lt;String&gt;()); } } </code></pre> <p>when i try to use the function ></p> <pre><code>public void Escribir(String registro) { File f; FileWriter w; BufferedWriter bw; PrintWriter wr; try { f = new File(registro); w = new FileWriter(f); bw = new BufferedWriter(w); wr = new printwriter(bw); wr.write("Su lista es:"); wr.println(); wr.println(); } catch (Exception e) { System.err.println("Ocurrio un error en el momento de crear el archivo" + e.getMessage()); } } </code></pre> <p>i am getting the error " cannot find symbol" Symbol: class printwriter.</p> <pre><code> wr = new printwriter(bw); </code></pre> <p>The rest of the code is:</p> <pre><code> public void adddata() { System.out.println("Digite Nombres del usuario:"); Nombres = sc.nextLine(); lista.get(0).add(Nombres); System.out.println("Digite Apellidos del usuario:"); Apellidos = sc.nextLine(); lista.get(1).add(Apellidos); System.out.println("Digite Numero de identificacion del usuario:"); id = sc.nextLine(); lista.get(2).add(id); System.out.println("Fecha de Nacimiento del usuario:"); System.out.println("Digite el dia"); dia = sc.nextLine(); lista.get(3).add(dia); System.out.println("Digite el Mes"); mes = sc.nextLine(); lista.get(3).add(mes); System.out.println("Digite el Año"); ano = sc.nextLine(); lista.get(3).add(ano); System.out.println("Escriba el sexo del usuario M o F"); s = sc.nextLine(); lista.get(4).add(s); System.out.println("Escriba direccion fisica del usuario"); df = sc.nextLine(); lista.get(5).add(df); System.out.println("Escriba direccion de correo electronico del usuario"); ce = sc.nextLine(); lista.get(6).add(ce); System.out.println("Escriba numero telefonico"); celu = sc.nextLine(); lista.get(7).add(celu); System.out.println("Escriba RH del usuario"); RH = sc.nextLine(); lista.get(8).add(RH); System.out.println("\n"); } public void showdata() { for (int i = 0; i &lt; lista.get(0).size(); i++) { System.out.printf(" %15s", lista.get(0).get(i)); System.out.printf("%15s ", lista.get(1).get(i)); System.out.printf("%15s ", lista.get(2).get(i)); System.out.printf("%15s ", lista.get(3).get(i)); System.out.printf("%15s ", lista.get(4).get(i)); System.out.printf("%15s ", lista.get(5).get(i)); System.out.printf("%15s", lista.get(6).get(i)); System.out.printf("%15s", lista.get(7).get(i)); System.out.printf("%15s", lista.get(8).get(i)); System.out.println("\n"); } } public void deletedata() { lista.get(0).remove(lista.get(0).size() - 1); lista.get(1).remove(lista.get(1).size() - 1); lista.get(2).remove(lista.get(2).size() - 1); lista.get(3).remove(lista.get(3).size() - 1); lista.get(4).remove(lista.get(4).size() - 1); lista.get(5).remove(lista.get(5).size() - 1); lista.get(6).remove(lista.get(6).size() - 1); lista.get(7).remove(lista.get(7).size() - 1); lista.get(8).remove(lista.get(8).size() - 1); } public void listsize() { System.out.println(lista.get(0).size()); } public void clearlist() { lista.get(0).clear(); lista.get(1).clear(); lista.get(2).clear(); lista.get(3).clear(); lista.get(4).clear(); lista.get(5).clear(); lista.get(6).clear(); } public void checklist() { if (lista.get(0).size() &lt; 0) { System.out.println("No hay informacion en lista"); } else { System.out.println("La lista contiene " + lista.get(0).size() + " Datos "); } } } </code></pre> <p>Any idea why am i getting this error_ Program gets basic info form user (id,name last name.) However still getting that error. Any idea?</p>
3
2,542
Symbols resolution in standalone IntelliJ parser
<p>I'm trying to use IntelliJ SDK as standalone java parser and it works fine in most cases, but failing to resolve return type of generic methods.</p> <p>When I debugging <code>resolveMethod</code> for <code>verify(mock).simpleMethod()</code> in next sample inside of IntelliJ:</p> <pre><code>public class ResolutionTest { private interface IMethods { String simpleMethod(); } private IMethods mock; public static &lt;T&gt; T verify(T m) { return m; } public void test() { verify(mock).simpleMethod(); } } </code></pre> <p>I see return type of <code>verify(mock)</code> as <code>IMethods</code> and <code>simpleMethod</code> also resolved correctly. But in my parser return type of <code>verify(mock)</code> is <code>T</code> and <code>simpleMethod</code> resolution failing because of that. I guess I'm not register some service or extension but I cannot figure out which one.</p> <p>My parser:</p> <pre><code>import com.intellij.codeInsight.ContainerProvider; import com.intellij.codeInsight.runner.JavaMainMethodProvider; import com.intellij.core.CoreApplicationEnvironment; import com.intellij.core.CoreJavaFileManager; import com.intellij.core.JavaCoreApplicationEnvironment; import com.intellij.core.JavaCoreProjectEnvironment; import com.intellij.mock.MockProject; import com.intellij.openapi.Disposable; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.extensions.ExtensionsArea; import com.intellij.openapi.fileTypes.FileTypeExtensionPoint; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.augment.PsiAugmentProvider; import com.intellij.psi.augment.TypeAnnotationModifier; import com.intellij.psi.compiled.ClassFileDecompilers; import com.intellij.psi.impl.JavaClassSupersImpl; import com.intellij.psi.impl.PsiElementFinderImpl; import com.intellij.psi.impl.PsiNameHelperImpl; import com.intellij.psi.impl.PsiTreeChangePreprocessor; import com.intellij.psi.impl.file.impl.JavaFileManager; import com.intellij.psi.meta.MetaDataContributor; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.BinaryFileStubBuilders; import com.intellij.psi.util.JavaClassSupers; import java.io.File; public class Main { static class Analyzer extends PsiElementVisitor { static final Disposable disposable = () -&gt; { }; private static class ProjectEnvironment extends JavaCoreProjectEnvironment { public ProjectEnvironment(Disposable parentDisposable, CoreApplicationEnvironment applicationEnvironment) { super(parentDisposable, applicationEnvironment); } @Override protected void registerJavaPsiFacade() { JavaFileManager javaFileManager = getProject().getComponent(JavaFileManager.class); CoreJavaFileManager coreJavaFileManager = (CoreJavaFileManager) javaFileManager; ServiceManager.getService(getProject(), CoreJavaFileManager.class); getProject().registerService(CoreJavaFileManager.class, coreJavaFileManager); getProject().registerService(PsiNameHelper.class, PsiNameHelperImpl.getInstance()); PsiElementFinder finder = new PsiElementFinderImpl(getProject(), coreJavaFileManager); ExtensionsArea area = Extensions.getArea(getProject()); area.getExtensionPoint(PsiElementFinder.EP_NAME).registerExtension(finder); super.registerJavaPsiFacade(); } @Override protected void preregisterServices() { super.preregisterServices(); ExtensionsArea area = Extensions.getArea(getProject()); CoreApplicationEnvironment.registerExtensionPoint(area, PsiTreeChangePreprocessor.EP_NAME, PsiTreeChangePreprocessor.class); CoreApplicationEnvironment.registerExtensionPoint(area, PsiElementFinder.EP_NAME, PsiElementFinder.class); } } private static class ApplicationEnvironment extends JavaCoreApplicationEnvironment { public ApplicationEnvironment(Disposable parentDisposable) { super(parentDisposable); myApplication.registerService(JavaClassSupers.class, new JavaClassSupersImpl()); } } final ApplicationEnvironment applicationEnvironment; final ProjectEnvironment projectEnvironment; public Analyzer() { ExtensionsArea rootArea = Extensions.getRootArea(); CoreApplicationEnvironment.registerExtensionPoint(rootArea, BinaryFileStubBuilders.EP_NAME, FileTypeExtensionPoint.class); CoreApplicationEnvironment.registerExtensionPoint(rootArea, FileContextProvider.EP_NAME, FileContextProvider.class); CoreApplicationEnvironment.registerExtensionPoint(rootArea, MetaDataContributor.EP_NAME, MetaDataContributor.class); CoreApplicationEnvironment.registerExtensionPoint(rootArea, PsiAugmentProvider.EP_NAME, PsiAugmentProvider.class); CoreApplicationEnvironment.registerExtensionPoint(rootArea, JavaMainMethodProvider.EP_NAME, JavaMainMethodProvider.class); CoreApplicationEnvironment.registerExtensionPoint(rootArea, ContainerProvider.EP_NAME, ContainerProvider.class); CoreApplicationEnvironment.registerExtensionPoint(rootArea, ClassFileDecompilers.EP_NAME, ClassFileDecompilers.Decompiler.class); CoreApplicationEnvironment.registerExtensionPoint(rootArea, TypeAnnotationModifier.EP_NAME, TypeAnnotationModifier.class); applicationEnvironment = new ApplicationEnvironment(disposable); projectEnvironment = new ProjectEnvironment(disposable, applicationEnvironment); } public void add(final String[] args) throws Exception { for (String arg : args) { final VirtualFile root = applicationEnvironment.getLocalFileSystem().findFileByIoFile(new File(arg)); projectEnvironment.addSourcesToClasspath(root); } } public void run() { MockProject project = projectEnvironment.getProject(); PsiClass cls = project.getComponent(JavaFileManager.class) .findClass("ResolutionTest", GlobalSearchScope.projectScope(project)); if (cls != null) { PsiMethod[] methods = cls.findMethodsByName("test", false); if (methods.length == 1) { PsiMethod method = methods[0]; for (PsiStatement s : method.getBody().getStatements()) { System.out.println(s.getNode().getText()); process(s); } } } } private void process(PsiMethodCallExpression expression) { PsiExpression qualifierExpression = expression.getMethodExpression().getQualifierExpression(); if (qualifierExpression instanceof PsiMethodCallExpression) { process((PsiMethodCallExpression) qualifierExpression); } else if (qualifierExpression instanceof PsiReference) { System.out.println("Resolving reference " + qualifierExpression.getText()); PsiElement targetElement = ((PsiReference) qualifierExpression).resolve(); if (targetElement == null) { System.out.println("Resolution failed"); } else if (targetElement instanceof PsiClass) { System.out.println("Class " + ((PsiClass) targetElement).getName()); } else if (targetElement instanceof PsiVariable) { System.out.println("Variable " + ((PsiVariable) targetElement).getTypeElement().getText()); } } System.out.println("Resolving method " + expression.getMethodExpression().getText()); PsiMethod method = expression.resolveMethod(); if (method == null) { System.out.println("Resolution failed"); } else { PsiClass clazz = method.getContainingClass(); System.out.println(clazz.getName() + "." + method.getName()); } } private void process(PsiExpression e) { if (e instanceof PsiMethodCallExpression) { process((PsiMethodCallExpression) e); } } private void process(PsiStatement s) { if (s instanceof PsiExpressionStatement) { process(((PsiExpressionStatement) s).getExpression()); } } } public static void main(String[] args) { try { Analyzer analyzer = new Analyzer(); analyzer.add(args); analyzer.run(); } catch (Exception e) { e.printStackTrace(System.out); } } } </code></pre> <p>And output:</p> <pre><code>verify(mock).simpleMethod(); Resolving method verify ResolutionTest.verify Resolving method verify(mock).simpleMethod Resolution failed </code></pre>
3
3,607
ERROR streaming.StreamJob: Job not successful
<p>I install Hadoop 2.9.0 and I have 4 nodes. The <code>namenode</code> and <code>resourcemanager</code> services are running on master and <code>datanodes</code> and <code>nodemanagers</code> are running on slaves. Now I wanna run a python MapReduce job. But Job not successful! Please tell me what should I do?</p> <p><strong>Log of running of job in terminal</strong>:</p> <pre><code>hadoop@hadoopmaster:/usr/local/hadoop$ bin/hadoop jar share/hadoop/tools/lib/hadoop-streaming-2.9.0.jar -file mapper.py -mapper mapper.py -file reducer.py -reducer reducer.py -input /user/hadoop/* -output /user/hadoop/output 18/06/17 04:26:28 WARN streaming.StreamJob: -file option is deprecated, please use generic option -files instead. 18/06/17 04:26:28 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable packageJobJar: [mapper.py, /tmp/hadoop-unjar3316382199020742755/] [] /tmp/streamjob4930230269569102931.jar tmpDir=null 18/06/17 04:26:28 INFO client.RMProxy: Connecting to ResourceManager at hadoopmaster/192.168.111.175:8050 18/06/17 04:26:29 INFO client.RMProxy: Connecting to ResourceManager at hadoopmaster/192.168.111.175:8050 18/06/17 04:26:29 WARN hdfs.DataStreamer: Caught exception java.lang.InterruptedException at java.lang.Object.wait(Native Method) at java.lang.Thread.join(Thread.java:1249) at java.lang.Thread.join(Thread.java:1323) at org.apache.hadoop.hdfs.DataStreamer.closeResponder(DataStreamer.java:980) at org.apache.hadoop.hdfs.DataStreamer.endBlock(DataStreamer.java:630) at org.apache.hadoop.hdfs.DataStreamer.run(DataStreamer.java:807) 18/06/17 04:26:29 WARN hdfs.DataStreamer: Caught exception java.lang.InterruptedException at java.lang.Object.wait(Native Method) at java.lang.Thread.join(Thread.java:1249) at java.lang.Thread.join(Thread.java:1323) at org.apache.hadoop.hdfs.DataStreamer.closeResponder(DataStreamer.java:980) at org.apache.hadoop.hdfs.DataStreamer.endBlock(DataStreamer.java:630) at org.apache.hadoop.hdfs.DataStreamer.run(DataStreamer.java:807) 18/06/17 04:26:29 INFO mapred.FileInputFormat: Total input files to process : 4 18/06/17 04:26:29 WARN hdfs.DataStreamer: Caught exception java.lang.InterruptedException at java.lang.Object.wait(Native Method) at java.lang.Thread.join(Thread.java:1249) at java.lang.Thread.join(Thread.java:1323) at org.apache.hadoop.hdfs.DataStreamer.closeResponder(DataStreamer.java:980) at org.apache.hadoop.hdfs.DataStreamer.endBlock(DataStreamer.java:630) at org.apache.hadoop.hdfs.DataStreamer.run(DataStreamer.java:807) 18/06/17 04:26:29 INFO mapreduce.JobSubmitter: number of splits:4 18/06/17 04:26:29 INFO Configuration.deprecation: yarn.resourcemanager.system-metrics-publisher.enabled is deprecated. Instead, use yarn.system-metrics-publisher.enabled 18/06/17 04:26:29 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1529233655437_0004 18/06/17 04:26:30 INFO impl.YarnClientImpl: Submitted application application_1529233655437_0004 18/06/17 04:26:30 INFO mapreduce.Job: The url to track the job: http://hadoopmaster.png.com:8088/proxy/application_1529233655437_0004/ 18/06/17 04:26:30 INFO mapreduce.Job: Running job: job_1529233655437_0004 18/06/17 04:45:12 INFO mapreduce.Job: Job job_1529233655437_0004 running in uber mode : false 18/06/17 04:45:12 INFO mapreduce.Job: map 0% reduce 0% 18/06/17 04:45:12 INFO mapreduce.Job: Job job_1529233655437_0004 failed with state FAILED due to: Application application_1529233655437_0004 failed 2 times due to Error launching appattempt_1529233655437_0004_000002. Got exception: org.apache.hadoop.net.ConnectTimeoutException: Call From hadoopmaster.png.com/192.168.111.175 to hadoopslave1.png.com:40569 failed on socket timeout exception: org.apache.hadoop.net.ConnectTimeoutException: 20000 millis timeout while waiting for channel to be ready for connect. ch : java.nio.channels.SocketChannel[connection-pending remote=hadoopslave1.png.com/192.168.111.173:40569]; For more details see: http://wiki.apache.org/hadoop/SocketTimeout at sun.reflect.GeneratedConstructorAccessor38.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:824) at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:774) at org.apache.hadoop.ipc.Client.getRpcResponse(Client.java:1497) at org.apache.hadoop.ipc.Client.call(Client.java:1439) at org.apache.hadoop.ipc.Client.call(Client.java:1349) at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:227) at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:116) at com.sun.proxy.$Proxy82.startContainers(Unknown Source) at org.apache.hadoop.yarn.api.impl.pb.client.ContainerManagementProtocolPBClientImpl.startContainers(ContainerManagementProtocolPBClientImpl.java:128) at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:422) at org.apache.hadoop.io.retry.RetryInvocationHandler$Call.invokeMethod(RetryInvocationHandler.java:165) at org.apache.hadoop.io.retry.RetryInvocationHandler$Call.invoke(RetryInvocationHandler.java:157) at org.apache.hadoop.io.retry.RetryInvocationHandler$Call.invokeOnce(RetryInvocationHandler.java:95) at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:359) at com.sun.proxy.$Proxy83.startContainers(Unknown Source) at org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncher.launch(AMLauncher.java:122) at org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncher.run(AMLauncher.java:307) 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:745) Caused by: org.apache.hadoop.net.ConnectTimeoutException: 20000 millis timeout while waiting for channel to be ready for connect. ch : java.nio.channels.SocketChannel[connection-pending remote=hadoopslave1.png.com/192.168.111.173:40569] at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:534) at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:687) at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:790) at org.apache.hadoop.ipc.Client$Connection.access$3500(Client.java:411) at org.apache.hadoop.ipc.Client.getConnection(Client.java:1554) at org.apache.hadoop.ipc.Client.call(Client.java:1385) ... 19 more . Failing the application. 18/06/17 04:45:13 INFO mapreduce.Job: Counters: 0 18/06/17 04:45:13 ERROR streaming.StreamJob: Job not successful! Streaming Command Failed! </code></pre>
3
2,619