id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23536200
If I only have the TD and make a Javascript onclick event to handle the click etc. the text is centered fine in all browsers, but I like to include a link/anchor so the user can tab to the element to activate the behavior (also nice for disabled people). It is also easy to make a anchor in the TD that do not fill the height and get normal centering, but then I have the problem that the entire TD does not change the cursor when hovering and just the center of the TD can be selected. You can see some of my trials here (will be deleted later): http://pcrypt.dk/dev/contact.php - test them out in for example FF and Chrome. Here is the HTML code: <table width=150 border=0> <tr><td class=loginbutton id='sendtext'><a href=#><div style='height:100%; width:100%'>".$lang['contact']['PCCONTACTSENDBUTTON']."</div></a></td></tr> <tr><td class=loginbutton id='sendtext'><a href=#><div style='display: table-cell; height:100%; width:100%'>".$lang['contact']['PCCONTACTSENDBUTTON']."</div></a></td></tr> <tr><td class=loginbutton id='sendtext'><a href=#><div style='height:100%; width:100% display: table; overflow: hidden;'><div style='display: table-cell; text-align: center; vertical-align: middle;'><div style='text-align: center; vertical-align: middle;'>".$lang['contact']['PCCONTACTSENDBUTTON']."</div></div></div></a></td></tr> <tr><td class=loginbutton id='sendtext'><a href=#><div style='height:100%; width:100% overflow: hidden;'><div style='text-align: center; vertical-align: middle;'><div>".$lang['contact']['PCCONTACTSENDBUTTON']."</div></div></div></a></td></tr> <tr><td class=loginbutton id='sendtext'><a href=#><div style='width:100% overflow: hidden;'><div style='text-align: center; vertical-align: middle;'>".$lang['contact']['PCCONTACTSENDBUTTON']."</div></div></a></td></tr> </table> And the relevant CSS code: .loginbutton { font-weight: normal; text-align: center; vertical-align: middle; height: 26px; width: 150px; cursor: pointer; background-color: #d26628; color: #ffffff; font-size: 13px; } .loginbutton a:link, a:visited, a:active { font-weight: normal; color: #ffffff; font-size: 13px; } .loginbutton a:hover { font-weight: bold;} .loginbutton:hover{ font-weight: bold; } NB: I am in no way a CSS expert ;-) PS: The menu li elements on Stack Overflow (top of the screen) do not behave like this btw and can only be accessed with a mouse - think it is wrong. A: Best solution html <table border="1" width="100%"> <tr> <td>Stuff<br><br></td> <td> <a href="page.htm"><span> a Link </span></a> </td> <td>Stuff</td> </tr> </table> CSS td { height: 100%; } a { display: table; position: relative; height: 100%; width: 100%; background-color: yellow; } span { display: table-cell; text-align:center; vertical-align: middle; background-color: red; } http://jsfiddle.net/74Wxn/ Note: height="100%" is required on td, you can add it to css also A: There are multiple ways to do this. Here's one: If you want to make an <a> element fill the entire space, you can do so by setting its display attribute to inline-block and set the width and height to 100%. So, for example: HTML <table> <tr> <td>Stuff</td> <td><a href="http://www.example.com">A Link!</a></td> <td>More Stuff</td> </tr> </table> CSS table td { text-align: center; /*Aligns all content of td elements to center*/ } table td a { display: inline-block; /*Behaves like a div, but can be placed inline*/ width: 100%; /*Full width of parent*/ height: 100%; /*Full height of parent*/ text-align: center; /*Centers content*/ } The Fiddle A: <style> a { display: block; position: relative; height: 100%; background-color: yellow; } span { display: block; height: 50%; position: absolute; overflow: auto; margin: auto; top: 0; left: 0; bottom: 0; right: 0; text-align:center; background-color: red; } </style> <table border="1" width="100%"> <tr> <td>Stuff<br><br></td> <td height="100%" width="30%"> <a href="http://www.google.com" target="_blank"> <span>A Link to Google!</span> </a> </td> <td>Stuff</td> </tr> </table> A: I think you need this <td align="center"><a href=""></a></td>
doc_23536201
As a workaround I've made separate components (Highlight1, Highlight2, etc.) and an onPress function in each to be able to navigate between them. But that is a lot of repeated code and that is what I want to avoid. Below is the code for my TabNavigator where I assign each screen the corresponding React component. routes.js createMaterialTopTabNavigator( { Page1: { screen: () => ( <Highlight image={require('../components/Highlights/images/highlight1.png')} description={'Description 1'} nextPage={this.props.navigation.navigate('Page2')} /> ) }, Page2: { screen: () => ( <Highlight image={require('../components/Highlights/images/highlight2.png')} description={'Description 2'} nextPage={this.props.navigation.navigate('Page3')} /> ) }, Page3: { screen: () => ( <Highlight image={require('../components/Highlights/images/highlight3.png')} description={'Description 3'} nextPage={this.props.navigation.navigate('Page4')} /> ) }, Page4: { screen: () => ( <Highlight image={require('../components/Highlights/images/highlight4.png')} description={'Description 4'} /> ) } }, { tabBarPosition: 'bottom', defaultNavigationOptions: { tabBarVisible: false } } ) Highlight.js import React, { Component } from 'react'; import { View, Text, Image, ImageBackground } from 'react-native'; import { NextButton } from '../Buttons'; import styles from './styles'; export default class Highlight extends Component { render() { return ( <ImageBackground style={styles.container}> <Image style={styles.image} source={this.props.image} resizeMode="cover" /> <View style={styles.textContainer}> <Text style={styles.text1}>MYAPP</Text> <Text style={styles.text2}>Highlights</Text> <Text style={styles.text3}>{this.props.description}</Text> </View> <View style={styles.buttonContainer}> <NextButton onPress={this.props.nextPage} /> </View> </ImageBackground> ); } } NextButton.js import React from 'react'; import { View, TouchableOpacity, Text } from 'react-native'; import styles from './styles'; const NextButton = ({ onPress }) => ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <TouchableOpacity style={styles.nextButtonContainer} onPress={onPress}> <Text style={{ color: 'white', fontSize: 14 }}>NEXT</Text> </TouchableOpacity> </View> ); export default NextButton; The above spits out the following error -> TypeError: undefined is not an object (evaluating '_this.props.navigation'). How can I get the above to work such that Page1 navigates to Page2, Page2 to Page3, and so on? Additionally, is there a better way to achieve what I am trying to do (which is basically to create a ViewPager consisting of 4 screens)? A: The NextButton should be configured as follows: <NextButton onPress={() => this.props.nextPage} /> const NextButton = (props) => { const { onPress } = props; return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <TouchableOpacity style={styles.nextButtonContainer} onPress={onPress}> <Text style={{ color: 'white', fontSize: 14 }}>NEXT</Text> </TouchableOpacity> </View> ); };
doc_23536202
i wanted to try atleast 2 menu that uses only one form. when any of the menu is clicked, it will call the servlet MainServlet which will be the one that will decide which JSP page to be displayed. In JSP: <form action="menu" method="POST"> <a href="<%=request.getContextPath()%>/MainServlet" name="about">About</a> <a href="<%=request.getContextPath()%>/MainServlet" name="contact">Contact Us</a> </form> In web.xml: <servlet> <servlet-name>MainServlet</servlet-name> <servlet-class>com.javashuffle.servlets.MainServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MainServlet</servlet-name> <url-pattern>/MainServlet</url-pattern> </servlet-mapping> In MainServlet: doGet() { if (request.getParameter("about") != null) { RequestDispatcher dispatcher = request.getRequestDispatcher("about.jsp"); dispatcher.forward(request, response); } else if (request.getParameter("contact") != null) { RequestDispatcher dispatcher = request.getRequestDispatcher("contact.jsp"); dispatcher.forward(request, response); } } i cant seem to go to the desired JSP page using my codes in the servlet. what do you think is the problem with my codes? thanks in advance! A: The URL of each of the links is exactly the same, and doesn't include any parameter. For your code to work the URLs should be <%=request.getContextPath()%>/MainServlet?about= and <%=request.getContextPath()%>/MainServlet?contact= I would use two different servlets instead: one which has the responsibility of dealing with the about page, and the other one that has the responsibility to deal with the contact page. It doesn't change much if all they do is dispatch to a JSP, but if some data is needed to display in the pages, having a dedicated servlet for each page makes more sense. It would also help having cleaner URLs, like /contact and /about.
doc_23536203
I have tried using array and pyplot without success [(5, 160), (5, 160), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, 387), (10, ... This is the list of couple named Position it goes on and on gor about 3000 more couples The size is 598 by 513 tab=np.full((A,B),255,dtype='uint8') for i,j in Position: tab[i,j]=0 plt.imshow(tab,cmap='gray') plt.show() myarray = np.asarray(Position) img = Image.fromarray(myarray) img.save('test.png')
doc_23536204
val list = List<FlightRecommendationQuery> in that: data class FlightRecommendationQuery( val segments: List<Segment> ) data class Segment( val stops: Int? ) I have another list with size same as segments size in FlightRecommendationQuery called filter: val filter = List<Filter> data class Filter( val stops: Int? ) I want to filter 'list' when filter's stops are equal to each segments in list. Here, size of list 'filter' and size of 'segments' of FlightRecommendationQuery are same. Update: I concluded with this solution: list.filter{query-> filter.indices.all{ if(filter[it].stops==null) true else filter[it].stops==query.segments[it].stops } } A: I'm not sure if there is a more efficient way to do it but I think this would do it: val filteredList = list.filter { it.segments.map { it.stops }.equals(filter.map { it.stops }) } A: Here's a Kotlin solution if I understood your question correctly fun main() { // DATA SETUP val s1 = Segment(1) val s2 = Segment(2) val s3 = Segment(3) val segmentList = listOf(s1,s2,s3) val query = FlightRecommendationQuery(segmentList) val f1 = Filter(1) val f2 = Filter(9999) val f3 = Filter(3) val filterList = listOf(f1,f2,f3) // END OF DATA SETUP // Here we do the filtration val filteredSegments = mutableListOf<Segment>() for(segmentIndex in query.segments.indices) { // We use indices concept from Kotlin to get the items in the same // position from both lists val segment = query.segments[segmentIndex] val filter = filterList[segmentIndex] if(segment.stops == filter.stops) filteredSegments.add(segment) } //Filtered segments now contains the necessary data //Will print [Segment(stops=1), Segment(stops=3)] in this case //Use this list of segments to create a new FlightRecommendationQuery println(filteredSegments) } A: You can do this by zipping segments and filter and checking if all of them are equal: list.filter { query -> (query.segments zip filter) .all { it.first.stops == it.second.stops } } A: Another way: list.filter { query -> filter.indices.all { filter[it].stops == query.segments[it].stops } } all returns true if all the elements of list match the given predicate
doc_23536205
I did this : DROP TABLE IF EXISTS employees; but it's not working it's giving me this error: "SQL command not properly ended" What is the right way to drop tables in Oracle SQL Developer? Thank you A: Oracle doesn't really have an "IF EXISTS" or "IF NOT EXISTS" clause for any DDL commands. Just use DROP TABLE employees;
doc_23536206
%PDF-1.0 1 0 obj << /Type /Catalog /Pages 2 0 R /Names 6 0 R >> endobj 2 0 obj << /Type /Pages /Count 1 /Kids [3 0 R] >> endobj 3 0 obj << /Type /Page /Parent 2 0 R /Resources << /Font << /F1 5 0 R >> >> /MediaBox [0 0 612 792] /Contents 4 0 R >> endobj 4 0 obj << /Length 45 >> stream BT /F1 24 Tf 250 700 Td (Hello, World!) Tj ET endstream endobj 5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj 6 0 obj << /JavaScript 7 0 R >> endobj 7 0 obj << /Names [(My Code) 8 0 R] >> endobj 8 0 obj << /JS (app.alert({cMsg: document.location, cTitle: "Mario's Message"}); ) /S /JavaScript >> endobj xref 0 9 trailer << /Size 9 /Root 1 0 R >> startxref %%EOF how can I restrict this type of PDF files from uploading? I am using reactJS in Front-end, java in Back-end, and using PDFTron web SDK to load PDF on browser. Can I restrict this on Front-end by checking the content of the file or Can I check the content of the PDF file on back-end? What is the best way to restrict PDF file with malicious content?
doc_23536207
Recently i divided my project to multiple sub-projects , and now it is seems to be that only one sub-project can write to the console (System.out). For example , when i have Global objects in 2 sub-projects (Already handled how to do this ) and i override onRouteRequest at both of them , only one of them (Apparently the first one to run) could write to the console. How can i fix this? Thanks!
doc_23536208
This is what I tried so far (based on another question from this site): string rootPath = "D:\\Pending\\Engineering\\Parts\\3"; string targetPattern = "*@"; string fullPath = Directory .EnumerateFiles(rootPath, targetPattern, SearchOption.AllDirectories) .FirstOrDefault(); if (fullPath != null) Console.WriteLine("Found " + fullPath); else Console.WriteLine("Not found"); I know *@ isn't correct, no idea how to do that part. Also I'm having problems with SearchOption Visual studio says "it's an ambiguous reference." Eventually I want the code to get the name of this folder and use it to rename a different folder. FINAL SOLUTION I ended up using a combination of dasblikenlight and user3601887 string fullPath = Directory .GetDirectories(rootPath, "*", System.IO.SearchOption.TopDirectoryOnly) .FirstOrDefault(fn => !fn.EndsWith("@")); A: Since EnumerateFiles pattern does not support regular expressions, you need to get all directories, and do filtering on the C# side: string fullPath = Directory .EnumerateFiles(rootPath, "*", SearchOption.AllDirectories) .FirstOrDefault(fn => !fn.EndsWith("@")); A: Or just replace EnumerateFiles with GetDirectories string fullPath = Directory .GetDirectories(rootPath, "*@", SearchOption.AllDirectories) .FirstOrDefault();
doc_23536209
I'm always taking my screenshot like this ... use Facebook\WebDriver\WebDriverDimension; ... class LoginTest extends DuskTestCase { public function testLogin() { $user = User::first(); $this->browse(function ($browser) use ( $user ) { $test = $browser->visit( new Login) ->resize(1920,1080) ... ->driver->takeScreenshot(base_path('tests/Browser/screenshots/testLogin.png')); }); } } But as my tests will be more and more used, I don't want to continue to write everytime ->resize(X,Y) and base_path('bla/blab/bla'). I wanted to define the size and path for every tests that will be written. I guess I should define some function in tests/DesukTestCase.php but I'm not even aware of how I can retrieve the driver and so on. Have you got some guidance or documentation about this? Because I can't find anything... A: In my DuskTestCase file I have the below in my driver() function. protected function driver() { $options = (new ChromeOptions())->addArguments([ '--disable-gpu', '--headless', ]); $driver = RemoteWebDriver::create( 'http://selenium:4444/wd/hub', DesiredCapabilities::chrome()->setCapability( ChromeOptions::CAPABILITY, $options ) ); $size = new WebDriverDimension(1280, 2000); $driver->manage()->window()->setSize($size); return $driver; } You should just be able to configure it with the right dimensions you need. A: You only need to add '--window-size=1920,1080' in $options. This will apply a 1920x1080 screen resolution to all your Dusk tests. Feel free to adjust to whatever window size you want. So your DuskTestCase.php file should look like this: protected function driver() { $options = (new ChromeOptions())->addArguments([ '--disable-gpu', '--headless', '--window-size=1920,1080', ]); $driver = RemoteWebDriver::create( 'http://selenium:4444/wd/hub', DesiredCapabilities::chrome()->setCapability( ChromeOptions::CAPABILITY, $options ) ); } A: Regarding the path issue, you can set it with Browser::$storeScreenshotsAt in setUp method of your test case class. protected function setUp() { parent::setUp(); Browser::$storeScreenshotsAt = '/path/to/your/screenshots'; } Default location of Browser::$storeScreenshotsAt is set in setUp method of the grand parent test case class. So, make sure that you set Browser::$storeScreenshotsAt after calling parent::setUp(), otherwise it will be overwritten by the default.
doc_23536210
Notice: Undefined index: subcatid in C:\xampp\htdocs\website\products.php on line 17 <?php $url=$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']."/eshopmgk/"; require_once("connection.php"); $sql1="select * from prointa where id=".$_GET['catid']; mysqli_query($con,'set names "utf8"'); $recordset=mysqli_query($con,$sql1); $sqla="select * from proionta inner join subcatigories on proionta.subcatigories_id=subcatigories.subcatigories_id where subcatigories.subcatigories_alias like '".$_GET['subcatid']."'"; $recordsetcannon=mysqli_query($con,$sqla); ?> . <div class="col100 products-home-items"> <?php while($recordcannon=mysqli_fetch_assoc($recordsetcannon)){?> <div class="col25 products-home-item"> <div class="col100 items-img"> <img width="55%" src="<?=$url?><?=$recordcannon['photos']?>" /> </div> <div class="col100 items-title"> <a href="#"> <p>Φακός</p> </a> </div> <div class="col100 items-category"> <a href="<?=$url?>/<?=$_GET['catid']?>/<?=$_GET['subcatid']?>/<?=$recordcannon['proionta_alias']?>"><h3><?=$recordcannon['proionta_name']?></h3></a> </div> <div class="col100"> <div class="col100"> <p class="items-price text-center"><?=$recordcannon['proionta_timi']?>&euro;</p> </div>
doc_23536211
<appender name="SyslogAppender" type="log4net.Appenders.RemoteAppender,log4net.Appenders"> <AppName>MySampleApp</AppName> </appender> In log4net.xsd, I have <xs:complexType name="appender"> ... <xs:element minOccurs="0" maxOccurs="1" name="AppName" type="AppName" /> ... </xs:complexType> I am trying to define AppName so that I can properly use it. I have tried using: <xs:complexType name="AppName"> <xs:attribute name="value" type="xs:string" /> </xs:complexType> I am getting the error, The element cannot contain text. Content model is empty. When I use xs:element it tells me that the element is not supported in this context. I also tried using <xs:element name="AppName" type="xs:string" /> How can I define this properly to use AppName like I want to in log4net.config? Thanks! A: I moved this all to Web.config and didn't have to use the XSD anymore. This solved my issue. Probably not the best solution, but worked.
doc_23536212
I am unable to start the kibana service. It keeps failing with the following error. Jul 05 15:51:16 castle node[1771]: Unhandled Promise rejection detected: Jul 05 15:51:16 castle node[1771]: TypeError: Cannot set property 'writecb' of undefined Jul 05 15:51:16 castle node[1771]: at LogInterceptor.Transform._write (_stream_transform.js:185:14) Jul 05 15:51:16 castle node[1771]: at writeOrBuffer (_stream_writable.js:352:12) Jul 05 15:51:16 castle node[1771]: at LogInterceptor.Writable.write (_stream_writable.js:303:10) Jul 05 15:51:16 castle node[1771]: at Monitor.push (/usr/share/kibana/node_modules/@elastic/good/lib/monitor.js:207:30) Jul 05 15:51:16 castle node[1771]: at Monitor._logHandler (/usr/share/kibana/node_modules/@elastic/good/lib/monitor.js:40:18) Jul 05 15:51:16 castle node[1771]: at module.exports.internals.Podium.internals.Podium.emit (/usr/share/kibana/node_modules/podium/lib/index.js:220:49) Jul 05 15:51:16 castle node[1771]: at module.exports.internals.Core._log (/usr/share/kibana/node_modules/hapi/lib/core.js:584:21) Jul 05 15:51:16 castle node[1771]: at module.exports.internals.Core.log (/usr/share/kibana/node_modules/hapi/lib/core.js:562:21) Jul 05 15:51:16 castle node[1771]: at internals.Server.log (/usr/share/kibana/node_modules/hapi/lib/server.js:312:27) Jul 05 15:51:16 castle node[1771]: at KbnServer._default (/usr/share/kibana/src/optimize/index.js:68:12) Jul 05 15:51:16 castle node[1771]: at async KbnServer.mixin (/usr/share/kibana/src/legacy/server/kbn_server.js:150:7) Jul 05 15:51:16 castle node[1771]: at async KbnServer.listen (/usr/share/kibana/src/legacy/server/kbn_server.js:162:5) Jul 05 15:51:16 castle node[1771]: at async LegacyService.createKbnServer (/usr/share/kibana/src/core/server/legacy/legacy_service.js:285:9) Jul 05 15:51:16 castle node[1771]: at async LegacyService.start (/usr/share/kibana/src/core/server/legacy/legacy_service.js:159:24) Jul 05 15:51:16 castle node[1771]: at async Server.start (/usr/share/kibana/src/core/server/server.js:193:5) Jul 05 15:51:16 castle node[1771]: at async Root.start (/usr/share/kibana/src/core/server/root/index.js:55:14) Jul 05 15:51:16 castle node[1771]: Terminating process... Jul 05 15:51:16 castle systemd[1]: kibana.service: Main process exited, code=exited, status=1/FAILURE Jul 05 15:51:16 castle systemd[1]: kibana.service: Failed with result 'exit-code'. Jul 05 15:51:16 castle systemd[1]: kibana.service: Scheduled restart job, restart counter is at 3. All configurations in elasticsearch/kibana are default. I can curl elasticsearch from console. Any pointers? Thanks! A: The problem is that even the latest kibana 7 does not support nodejs 14, and requires nodejs 10. pacman -S nodejs-lts-dubnium This will, however, not be enough. See #84266, kibana make an hard error if the nodejs version deosn't match exactly. So you will need to edit /usr/share/kibana/package.json and make change to the node version to match your currently installed nodejs dubnium... use node -v this should be something like 10.x.x Running that should get you going. Also, I wouldn't recommend running stuff from the AUR unless you have a good use case, especially when both kibana and elasticsearch are in the main repositories. Though the problem was not AUR specific this time.
doc_23536213
* *I have a method called -(void)searchingInBackground which is running in background (performSelectorInBackground). *In this method, I have couple of different threads which are running in background too (performSelectorInBackground). Like this: -(void)searchingInBackground { @autoreleasepool { [self performSelectorInBackground:@selector(getDuplicatedPictures:) withObject:copyArray]; } @autoreleasepool { [self performSelectorInBackground:@selector(getLocationsOfPhotos:) withObject:copyArray]; } ... (and so on) } *In each of functions in threads (ie. getDuplicatedPictures, getLocationsOfPhotos...) they will generate NSStrings at the end and I will use those strings to update my text field GUI. *In order to update my text field GUI. I created a function called UpdateGUI which will use to help me update all of my NSStrings. Like this, -(void)UpdateUI { [_NumDupPhotosLabel(label for GUI) setStringValue: resultDupPhotos(string from thread function which is getDuplicatedPictures in this case)]; ....(includes all of my strings from threads) } *Here is the problem, when I call this UpdateGUI using performSelectorOnMainThread in each of threads function. It will give me EXC_BAD_ACCESS. Here is what I did. For example: -(void)getDupicatedPictures { resultDupPhotos = .....; [self performSelectorOnMainThread:@selector(UpdateUI) withObject:nil waitUntilDone:YES]; } *If I do not use performSelectorOnMainThread, just set the values directly in those functions it works fine. I just want to better organize the code. -(void)getDuplicatedPictures { resultDupPhotos = .....; [_NumDupPhotosLabel setStringValue: resultDupPhotos]; (works good and it will set the value to the GUI label) } Could you guys tell me how to fix this? Thanks!!! A: * *ARC or no? *if you have a crash, post the backtrace *surrounding a performInBackground:... call with an @autoreleasepool does nothing (NSAutoreleasePool isn't going to help, either -- you need the autorelease pool to be in the thread of execution) *if a variable is involved in a crash, show the variable's declaration and initialization *spawning a bunch of threads simultaneously to do a bunch of work is likely to be slower than doing the work sequentially. Concurrency should always be controlled. If you have a long running task, you might likely want to spin up a second thread. Or you might want to re-order operations. The issue, though, is that running multiple threads at once, especially if those threads are doing a lot of I/O, is just going to increase contention and may likely make things slower, often a lot slower. More likely than not, one of the objects calculated on a background thread is being released before the main thread tries to use it. How do you ensure that resultDupPhotos is valid between threads?
doc_23536214
Ex: unsigned char b = 0x20; //(00100000) 6th most bit set I currently use the following loop to determine which bit is set: int getSetBitLocation(unsigned char b) { int i=0; while( !((b >> i++) & 0x01) ) { ; } return i; } How do I most efficiently determine the position of the set bit? Can I do this without iteration? A: Can I do this without iteration? It is indeed possible. How do I most efficiently determine the position of the set bit? You can try this algorithm. It splits the char in half to search for the top bit, shifting to the low half each time: int getTopSetBit(unsigned char b) { int res = 0; if(b>15){ b = b >> 4; res = res + 4; } if(b>3){ b = b >> 2; res = res + 2; } //thanks @JasonD return res + (b>>1); } It uses two comparisons (three for uint16s, four for uint32s...). and it might be faster than your loop. It is definitely not shorter. Based on the idea by Anton Kovalenko (hashed lookup) and the comment by 6502 (division is slow), I also suggest this implementation (8-bit => 3-bit hash using a de-Bruijn sequence) int[] lookup = {7, 0, 5, 1, 6, 4, 3, 2}; int getBitPosition(unsigned char b) { // return lookup[(b | (b>>1) | (b>>2) | (b>>4)) & 0x7]; return lookup[((b * 0x1D) >> 4) & 0x7]; } or (larger LUT, but uses just three terms instead of four) int[] lookup = {0xFF, 0, 1, 4, 2, 0xFF, 5, 0xFF, 7, 3, 0xFF, 0xFF, 6, 0xFF, 0xFF, 0xFF}; int getBitPosition(unsigned char b) { return lookup[(b | (b>>3) | (b>>4)) & 0xF]; } A: Lookup table is simple enough, and you can reduce its size if the set of values is sparse. Let's try with 11 elements instead of 128: unsigned char expt2mod11_bits[11]={0xFF,0,1,0xFF,2,4,0xFF,7,3,6,5}; unsigned char pos = expt2mod11_bits[b%11]; assert(pos < 8); assert(1<<pos == b); Of course, it's not necessarily more effective, especially for 8 bits, but the same trick can be used for larger sizes, where full lookup table would be awfully big. Let's see: unsigned int w; .... unsigned char expt2mod19_bits[19]={0xFF,0,1,13,2,0xFF,14,6,3,8,0xFF,12,15,5,7,11,4,10,9}; unsigned char pos = expt2mod19_bits[w%19]; assert(pos < 16); assert(1<<pos == w); A: This is a quite common problem for chess programs that use 64 bits to represent positions (i.e. one 64-bit number to store where are all the white pawns, another for where are all the black ones and so on). With this representation there is sometimes the need to find the index 0...63 of the first or last set bit and there are several possible approaches: * *Just doing a loop like you did *Using a dichotomic search (i.e. if x & 0x00000000ffffffffULL is zero there's no need to check low 32 bits) *Using special instruction if available on the processor (e.g. bsf and bsr on x86) *Using lookup tables (of course not for the whole 64-bit value, but for 8 or 16 bits) What is faster however really depends on your hardware and on real use cases. For 8 bits only and a modern processor I think that probably a lookup table with 256 entries is the best choice... But are you really sure this is the bottleneck of your algorithm? A: unsigned getSetBitLocation(unsigned char b) { unsigned pos=0; pos = (b & 0xf0) ? 4 : 0; b |= b >>4; pos += (b & 0xc) ? 2 : 0; b |= b >>2; pos += (b & 0x2) ? 1 : 0; return pos; } It would be hard to do it jumpfree. Maybe with the Bruin sequences ? A: Based on log2 calculation in Find the log base 2 of an N-bit integer in O(lg(N)) operations: int getSetBitLocation(unsigned char c) { // c is in {1, 2, 4, 8, 16, 32, 64, 128}, returned values are {0, 1, ..., 7} return (((c & 0xAA) != 0) | (((c & 0xCC) != 0) << 1) | (((c & 0xF0) != 0) << 2)); } A: Easiest thing is to create a lookup table. The simplest one will be sparse (having 256 elements) but it would technically avoid iteration. This comment here technically avoids iteration, but who are we kidding, it is still doing the same number of checks: How to write log base(2) in c/c++ Closed form would be log2(), a la, log2() + 1 But I'm not sure how efficient that is - possibly the CPU has an instruction for taking base 2 logrithms? A: if you define const char bytes[]={1,2,4,8,16,32,64,128} and use struct byte{ char data; int pos; } void assign(struct byte b,int i){ b.data=bytes[i]; b.pos=i } you don't need to determine the position of the set bit A: A lookup table is fast and easy when CHAR_BIT == 8, but on some systems, CHAR_BIT == 16 or 32 and a lookup table becomes insanely bulky. If you're considering a lookup table, I'd suggest wrapping it; make it a "lookup table function", instead, so that you can swap the logic when you need to optimise. Using divide and conquer, by performing a binary search on a sorted array, involves comparisons based on log2 CHAR_BIT. That code is more complex, involving an initialisation of an array of unsigned char to use as a lookup table for a start. Once you have such the array initialised, you can use bsearch to search it, for example: #include <stdio.h> #include <stdlib.h> void uchar_bit_init(unsigned char *table) { for (size_t x = 0; x < CHAR_BIT; x++) { table[x] = 1U << x; } } int uchar_compare(void const *x, void const *y) { char const *X = x, *Y = y; return (*X > *Y) - (*X < *Y); } size_t uchar_bit_lookup(unsigned char *table, unsigned char value) { unsigned char *position = bsearch(lookup, c, sizeof lookup, 1, char_compare); return position ? position - table + 1 : 0; } int main(void) { unsigned char lookup[CHAR_BIT]; uchar_bit_init(lookup); for (;;) { int c = getchar(); if (c == EOF) { break; } printf("Bit for %c found at %zu\n", c, uchar_bit_lookup(lookup, c)); } } P.S. This sounds like micro-optimisation. Get your solution done (abstracting the operations required into these functions), then worry about optimisations based on your profiling. Make sure your profiling targets the system that your solution will run on if you're going to focus on micro-optimisations, because the efficiency of micro-optimisations differ widely as hardware differs even slightly... It's usually a better idea to buy a faster PC ;)
doc_23536215
A: Try deleting node_modules, .cache folder and package-lock.json and run npm install again.
doc_23536216
I know that there is a way to encrypt a PDF file using PyPDF2, using this code (for the curious only, taken from https://www.blog.pythonlibrary.org/2018/06/07/an-intro-to-pypdf2/), but it asks for a password before opening the contents and then copying is still possible: from PyPDF2 import PdfFileWriter, PdfFileReader def encrypt(input_pdf, output_pdf, password): pdf_writer = PdfFileWriter() pdf_reader = PdfFileReader(input_pdf) for page in range(pdf_reader.getNumPages()): pdf_writer.addPage(pdf_reader.getPage(page)) pdf_writer.encrypt(user_pwd=password, owner_pwd=None, use_128bit=True) with open(output_pdf, 'wb') as fh: pdf_writer.write(fh) if __name__ == '__main__': encrypt(input_pdf='introduction.pdf', output_pdf='encrypted.pdf', password='blowfish') But is there a way to secure a PDF using Adobe Reader commands? I've searched and I failed. Does anybody know how to do it? Hope somebody can help! A: Actually, it is possible after all! The code above works, all you need is to change the user password to empty string, set an owner password and change one line in the PyPDF2's pdf.py file from: # permit everything: P = -1 to: # permit everything: P = -3904 This block all changing, copying etc. for the encrypted PDF :)
doc_23536217
This JFrame shows the status of an operation. Let's say that function operation() contains the code of the operation we want to run. While the code of function operation() is running I can't click the JButton "abort" because the JFrame is stuck. So, I thought, that the cause could be the event dispatcher and for this reason I tried to fix the issue using invokeLater of SwingUtilities: SwingUtilities.invokeLater(new Runnable() { @Override public void run() { operation(); } }); But the JFrame is still stuck while the code of the operation is running. How can I fix this?
doc_23536218
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) What is the purpose of keep_prob: 0.5 when running train_step? A: The keep_prob value is used to control the dropout rate used when training the neural network. Essentially, it means that each connection between layers (in this case between the last densely connected layer and the readout layer) will only be used with probability 0.5 when training. This reduces overfitting. For more information on the theory of dropout, you can see the original paper by Srivastava et al. To see how to use it in TensorFlow, see the documentation on the tf.nn.dropout() operator. The keep_prob value is fed in via a placeholder so that the same graph can be used for training (with keep_prob = 0.5) and evaluation (with keep_prob = 1.0). An alternative way to handle these cases is to build different graphs for training and evaluation: look at the use of dropout in the current convolutional.py model for an example.
doc_23536219
def add_to_request_log(self, data): self.__lock.acquire() self.__request_log += data + "\n" self.__lock.release() I've added this to it: f = open('server.log', 'a') f.write(data + "\n") f.close() But for some reason seems like the app got stuck on that point, because is not doing what is suppose to do, if I remove that lines it works normally. I tried adding the lines before, between and after the lock but it's same behaviour. Also, as it is a daemonized app i'm not sure how to debug it. Pd. This is my first day with python.
doc_23536220
The below command gives me "AttributeError: Unknown property hold" ax.plot(x, y, z, hold=True, c='r', marker='.') What's the alternative, or what am I doing wrong. A: Since hold was deprecated, plot behaves as if hold=True, so you can leave out specifying it explicitly.
doc_23536221
$('.expandicon').click(function(){ if ( $('.nav-bucket-items').css('display') == 'none' ) $('.nav-bucket-items').css('display','block'); else $('.nav-bucket-items').css('display','none'); }); Here is the code I've used and here is the example: https://jsfiddle.net/xajoujsx/ As you can see, when you click the expand + button, it opens up all navigation. I just wanted it to open up the one I click around. Can anyone explain what I'm doing wrong? A: From inside the click handler you can refer to .nav-bucket-items using: $(this).parent().siblings('.nav-bucket-items') fiddle A: The code currently performs it on all elements with class .nav-bucket. One option is to only apply to the immediate items for the parent. $('.expandicon').click(function() { var $ref = $($(this).parent().parent()).find('.nav-bucket-items') if ($ref.css('display') == 'none') $ref.css('display', 'block'); else $ref.css('display', 'none'); }); A: Few things going on here, first, you're targeting all of the elements when you do $('.nav-bucket-items') If you run that in your console you should see a list of elements rather than a single one, so what we want to do is target the parent, and then find the sibling, we also want to target the element link not the icon so that way the user can click the entire element to expand. Working example: https://jsfiddle.net/dg4z271m/1/ A: I love it when I can learn someone more about their code than just fix the code for the sake of answering the question. First, let me start by saying you don't need the .css('display','block'); to show or hide elements because .show() en .hide() does that for you. Amazing isn't it? So, now we are left with this. $('.expandicon').click(function(){ if ( $('.nav-bucket-items').css('display') == 'none' ) $('.nav-bucket-items').show(); else $('.nav-bucket-items').hide(); }); But now we still have the problem of the multi-expanding menu. This is because you show (or hide) alle elements with the class '.nav-bucket-items' We just wan't the ones that are family of the .expandicon we've clicked! You can do that with $(this). You can use $(this) to traverse from the element you've clicked. Lets see. $('.expandicon').click(function(){ if ( $('.nav-bucket-items').css('display') == 'none' ) $(this).parent().next('.nav-bucket-items') else $(this).parent().next('.nav-bucket-items') }); When you use this, it will all be working as you wished. But we can do better than this! We can make it shorter, better and cleaner. We don't have to check if .nav-bucket-items is visible. Nope. $('.expandicon').click(function(){ $(this).parent().next('.nav-bucket-items').toggle(); }); Did you see what happened? We just changed that whole bunch of code to one line that just toggles the element. So it will hide it when its shown and it will show when its hidden! If you really want some fancy effects, you could use slideToggle() or fadeToggle() instead of .toggle(). I updated your JSFiddle: https://jsfiddle.net/xajoujsx/3/
doc_23536222
Am I mis-understanding something? Or is the documentation incomplete/misleading? A: They now recommend using ./vendor/bin/simple-phpunit which will be installed with phpunit-bridge: https://symfony.com/doc/current/testing.html The first call to simple-phpunit installs some requirements.
doc_23536223
I've try integrating with Wallet Connect V1 sdk, but encounter a problem TypeError: null is not an object (evaluating 'RNRandomBytes.seed') is there any workaround on this ? did I missing something ? the error triggers right after I imported Wallet Connect V1 sdk the code : import { useState, useEffect, useRef } from 'react'; import { StyleSheet, Text, View, Button, TextInput } from 'react-native'; import { WebView } from 'react-native-webview'; import { SafeAreaView } from "react-native-safe-area-context"; import WalletConnect from "@walletconnect/client"; export default function Login({ navigation }) { return ( <SafeAreaView style={styles.container}> <Text style={{ alignSelf: "center", marginTop: 10 }}>{secret?.address}</Text> <View style={{ padding: 10, flexDirection: "row", alignItems: "center" }}> <TextInput style={{ padding: 10, borderWidth: 1, borderRadius: 10, flex: 2, margin: 5 }} placeholder='WC Connection...' onChangeText={(e) => setWc(e)} /> <View style={{ margin: 5, flex: 1 }}> <Button title='Connect'/> </View> </View> <View style={{ margin: 10 }}> <Button title='Generate Wallet' /> </View> <WebView source={{ uri: 'https://app.uniswap.org/#/swap' }} style={styles.container} /> </SafeAreaView> ); } const styles = StyleSheet.create({ container: { flex: 1 }, });
doc_23536224
These are correct strings: "" "asd-asd" "asd-asd;asd-asd" "asd-asd;asd-asd;" "asd-asd;asd-asd;asd0-asd1" But the string "asd0-asd1-asd2" shouldn't be valid. I wrote the following regexp: ^(([^;-]+-[^;-]+);?)*$ And it doesn't work as I expected - this regexp shows that this string is match. Why? A: You need to make your regex a little more complicated: ^([^;-]+-[^;-]+(;[^;-]+-[^;-]+)*)?$ Explanation: ^ # Start of the string ( # Start of first group: [^;-]+-[^;-]+ # Match one "asd-asd" ( # Start of second group ; # Match ; [^;-]+-[^;-]+ # Match another "asd-asd" )* # Repeat the second group any number of times (including zero) )? # Make the entire first group optional $ # End of string A: It matches because of ;? which makes the ; optional. You are trying to test something with context, regex is not the easiest tool to do this. A: To avoid making the semicolon optional, instead you could use (;|$). This will force the match of a semicolon unless you are at the end of the string. ^(([^;-]+-[^;-]+)(;|$))*$ A: There's a slight add to the Answer of @Tim. This regex is not matching the "asd-asd;asd-asd;" if you're using .Net regex library. But if you add a ';' as option before string ends then it'll cover all the cases. ^([^;-]+-[^;-]+(;[^;-]+-[^;-]+)*);?$ Now this will match all the valid strings provided except the Invalid - "asd0-asd1-asd2"
doc_23536225
TIA, mike XAML code below. I'm using ItemsControl and binding to a collection. I'm basically wanting a way to get the toggle status of each button when it's clicked. <ScrollViewer VerticalScrollBarVisibility="Auto"> <ItemsControl ItemsSource="{Binding Modifiers, Mode=TwoWay}"> <ItemsControl.Template> <ControlTemplate> <ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Auto"> <WrapPanel Margin="10" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" FlowDirection="LeftToRight" IsItemsHost="true"> </WrapPanel> </ScrollViewer> </ControlTemplate> </ItemsControl.Template> <ItemsControl.ItemTemplate> <DataTemplate> <ToggleButton FontSize="18" Opacity="0.8" Command="{Binding DataContext.ModifierToggleCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Views:ModifiersView}}}" CommandParameter="{Binding}" Height="80" Width="200" Margin="5" Content="{Binding Path=ModifierName}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </ScrollViewer> A: A simpler solution would be to bind the IsChecked property to a property of your ViewModel. That way you just have to check the property value... A: Could you specify the CommandParameter declaratively in the XAML and use an element binding to populate the value with the current value of the toggle?
doc_23536226
A1 = {field1, field2, field3} A2 = {field1, field2, field3} A3 = {field1, field2, field4} A4 = {field1, field5, field6} A5 = {field5, field6, field4} Im searching fo a java method to retrieve a result like the following : 1 - Exact sets A1 = {field1, field2, field3} & A2 = {field1, field2, field3} 2 - Similar sets with 1 field difference A1 = {field1, field2, field3} & A3 = {field1, field2, field4} A4 = {field1, field5, field6} & A5 = {field5, field6, field4} A2 = {field1, field2, field3} & A3 = {field1, field2, field4} 3 - Similar sets with 2 fields difference A1 = {field1, field2, field3} & A4 = {field1, field5, field6} A2 = {field1, field2, field3} & A4 = {field1, field5, field6} A3 = {field1, field2, field4} & A4 = {field1, field5, field6} A3 = {field1, field2, field4} & A5 = {field5, field6, field4} A: If you are using a java set data structure (https://www.geeksforgeeks.org/set-in-java/), then methods A1.retainAll(A2) will perform an intersection between A1 and A2 and then you can use the A1.size() to return the number of similar fields. The following function would return the number of different elements between two sets. public int diff(Set<E> A, Set<E> B){ if(A.size() > B.size()){ B.retainAll(A); return A.size()-B.size(); }else{ A.retainAll(B); return B.size()-A.size(); } } Then you could just check for every pair of sets. E.g. For exact sets, you only want pairs of sets where the function returns 0;
doc_23536227
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="test.myservice" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <service android:name="mytest.myservice.RemoteService" android:exported="true"> <intent-filter > <action android:name="MYSERVICE"/> </intent-filter> </service> </application> </manifest> After Creating Library project I added the reference of this library project to my application named TestMyLibrayApp.I am starting service from My application as follows. Intent playerservice = new Intent(); playerservice.setAction("MYSERVICE"); getBaseContext().bindService(playerservice,conn , Service.BIND_AUTO_CREATE); Where conn is the service connection object. Now the problem is Serivce is not starting.Can anyone suggest where am I wrong? A: You need to add the <service> section to TestMyLibraryApp's manifest. The library's manifest is not used.
doc_23536228
5: He had the files 9: the fILEs were his Code: void Search(String input) throws IOException { int x = 1; FileReader Search = new FileReader(f); Scanner in = new Scanner(f); LineNumberReader L = new LineNumberReader(Search, x); StreamTokenizer token = new StreamTokenizer(Search); while (in.hasNextLine()) { try { if (!in.findInLine(input).isEmpty()) { display(Integer.toString(L.getLineNumber()) + ": " + L.readLine(), "\n"); in.nextLine(); } } catch (NullPointerException e) { System.out.println("Something Happened"); in.nextLine(); } } } So far there are 3 issues I need to figure out with my code. * *As soon as instance occurs where the searched is not in a line, it immediately displays the next line, even though the searched word is not in the line, and then terminates from there without having displayed the rest of the lines that had the word in it. *It supposed to display lines with the word, regardless of casing, but does not. *Preferably, it's supposed to display all of them at once, but instead is displaying line by line, until it errors out and terminates. A: You're main problem is here... FileReader Search = new FileReader(f); Scanner in = new Scanner(f); LineNumberReader L = new LineNumberReader(Search, x); StreamTokenizer token = new StreamTokenizer(Search); while (in.hasNextLine()) { You've basically opened two file readers against the same file, but you seem to be expecting them to know about each other. You advance the Scanner, but that has no effect on the LineNumberReader. This then messes up the reporting and line reading process. Reading from Scanner should look more like... while (in.hasNextLine()) { String text = in.nextLine(); Having said that, I'd actually drop the Scanner in favor of the LineNumberReader as it will provide you with more useful information which you would otherwise have to do yourself. For example... FileReader Search = new FileReader(new File("TestFile")); LineNumberReader L = new LineNumberReader(Search, x); String text = null; while ((text = L.readLine()) != null) { // Convert the two values to lower case for comparison... if (text.toLowerCase().contains(input.toLowerCase())) { System.out.println(L.getLineNumber() + ": " + text); } }
doc_23536229
1) AsyncStorage 2) Redux Kindly help me and let me know if there is a misconception on my side. A: AsyncStorage and Redux serve different purposes. AsyncStorage is there to allow you to store data that is persisted between app instances (that is, between restarts of your app). Redux is a state management system that is meant to solve the problem of moving state around components in react. What you're describing can actually use both, where Redux is used for state management, and the redux store itself can be saved into AsyncStorage for later use. There are Redux related libraries that do just that, such as Redux-Persist.
doc_23536230
During install of some packages we have the error: Collecting itsdangerous==0.24 (from -r requirements.txt (line 7)) Downloading https://files.pythonhosted.org/packages/dc/b4/a60bcdba945c00f6d608d8975131ab3f25b22f2bcfe1dab221165194b2d4/itsdangerous-0.24.tar.gz (46kB) Complete output from command python setup.py egg_info: ---------------------------------------- Command "python setup.py egg_info" failed with error code -9 in /tmp/pip-build-1sttjqx7/itsdangerous/ Looking in the internet there is no information on the specific error code "failed with error code -9". Tips on what is the actual meaning of -9 ? A: The openshift platform was configured to use the following default values of cpu: 25milicores and 64Mib of memory. Therefore the problem was caused by a lack of memory. For the record, the openshift yaml can be configured with extra resources as indicated in this link [enter link description here
doc_23536231
i declare NSString *xTitle at the top in testViewController.m file when i set the xTitle=@"anytext" in viewload event; and i tap a button, it shows the UIActionsheet. i try to read xTitle in UIActionSheet's clickedButtonAtIndex. i see the xTitle's value "anytext", its ok. but when i set the xTitle from NSDictionary, it says Invalid. viewload event; NSDictionary *results = [jsonString JSONValue]; xTitle = [results valueForKey:@"ContentURL"]; NSLog(@"%@", xTitle);--> it writes the value but i cant read xTitle in uiactionsheet events. it says invalid. why does it say "Invalid"? A: Try doing NSLog (@"%@", results); Direcly after you create it to see exactly what is in the dictionary. Edit to show us what is in the dictionary. A: Since you want the string to outlive the function, you probably need to do: xTitle = [[results valueForKey:@"ContentURL"] retain]; And of course release it at some subsequent point when you're finished with it. This doesn't affect you when using the NSString literal @"anytext" because constant strings are basically static -- that is, they normally stick around for the whole lifetime of your code. You can (and maybe in some pedantic sense should) retain and release these too, but it doesn't actually do anything to them. (I'm a little bit curious about the scoping of this -- if xTitle is declared at the top of the .m file, how do you get at it in your action sheet -- but I don't think that's germane to this problem.)
doc_23536232
When I run "flutter doctor -v", the flutter doesn't recognise the portable version (and I understand, because is not in the default directory). The question is, how to make flutter doctor recognise this external installation (from zip file)? I have everything configured correctly, here is my current "flutter doctor -v" output: [√] Flutter (Channel stable, v1.17.5, on Microsoft Windows [Version 10.0.18363.900], locale en-GB) • Flutter version 1.17.5 at Z:\SDK\Flutter • Framework revision 8af6b2f038 (10 days ago), 2020-06-30 12:53:55 -0700 • Engine revision ee76268252 • Dart version 2.8.4 [√] Android toolchain - develop for Android devices (Android SDK version 30.0.1) • Android SDK at Z:\SDK\Android • Platform android-30, build-tools 30.0.1 • ANDROID_HOME = Z:\SDK\Android • Java binary at: Z:\SDK\OpenJDK\bin\java • Java version OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_252-b09) • All Android licenses accepted. [!] Android Studio (not installed) • Android Studio not found; download from https://developer.android.com/studio/index.html (or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions). [!] Connected device ! No devices available ! Doctor found issues in 2 categories. A: You're free to use IntelliJ (or any other IDE) for flutter development, but it won't satisfy the checks made by flutter doctor. It's looking specifically for Android Studio. If you want to use IntelliJ then you have to live with flutter doctor's warnings about Android Studio not being installed. If you want to use a portable version of Android Studio then use the command flutter config --android-studio-dir "Z:\MyPortableApps\AndroidStudio" with the path to your portable application. If you want to see what has been configured then just use flutter config without any parameters. The output starts with a load of usage text but at the end you'll find a section with the heading Settings: listing anything that has been set. A new install won't have anything set and will just use defaults. To later unset a value use a quoted empty string "" in the same command.
doc_23536233
Following is my db schema (with sample data): Table A: Requests | REQUESTID | STATUS | ------------------------- | 1 | PENDING| | 2 | PENDING| Table B: RequestDetails | DETAILID | REQUESTID | STATUS | USERID | --------------------------------------------- | 1 | 1 | PENDING | RA1234 | | 2 | 1 | PENDING | YA7266 | | 3 | 2 | PENDING | KAJ373 | Following is my requirement: 1) Fetch Request along with pending status along with request data from both tables I'm using below query for this: SELECT Requests.REQUEST_ID as "RequestID",RequestDetails.USERID as "UserID",RequestDetails.DETAILID as "DetailID" FROM Requests Requests JOIN RequestDetails RequestDetails ON (Requests.REQUESTID=RequestDetails.REQUESTID AND Requests.REQUEST_STATUS='PENDING' AND RequestDetails.STATUS='PENDING') 2) I'm using a HashMap<String, List<HashMap<String,String>> to store all the values 3) Iterate over each request and get details List<HashMap<String,String>> Perform action for each detail record and update status 4) After all detail records are processed for a request, update status of the request on requests table The end state should be something like this: Table A: Requests | REQUESTID | STATUS | ------------------------- | 1 | PENDING| | 2 | PENDING| Table B: RequestDetails | DETAILID | REQUESTID | STATUS | USERID | --------------------------------------------- | 1 | 1 | PENDING | RA1234 | | 2 | 1 | PENDING | YA7266 | | 3 | 2 | PENDING | KAJ373 | My question is: the collection I'm using is quite complex ("HashMap<String, List<HashMap<String,String>>"). Is there any other efficient way to do this? Thank you, Sash A: I think you should use class something like, Class RequestDetails{ int detailId; int statusId; String status; String userId; } instead of map HashMap<String, List<HashMap<String,String>> you should use HashMap<String, RequestDetails>That has advantages like, code simplicity and also when you working with huge data and you need to modify string it is always better to avoid using String data-type as it is immutable and decrease your performance. Hope this helps. A: Above all that and what Darshan suggested, you must override the hashCode and equals method too, the reason is its the basic contract while dealing with HashMap and it will also increase the performance too.
doc_23536234
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" keystorePass="nopass" keystoreFile="/home/someuser/.keystore" keyAlias="tomcat" /> Everything works fine when I hit the URL of the my demo application's servlet using HTTPS. When I tried to hit it using HTTP URL, I expected it to return 403 or similar error. Instead I got download of some small (11 bytes?) binary file with the name matching the name of the servlet. Did anyone experienced similar issue? How did you resolve it? What should I check to make sure I did everything right? EDIT: I tried hitting the same connector using curl instead of the browser and noticed that it doesn't return any headers. Oh, and the size of the response is 7 bytes, not 11. EDIT 2: This is the security-related part of the web.xml of my demo application: <security-constraint> <web-resource-collection> <web-resource-name>Secure Servlet</web-resource-name> <url-pattern>/SecureServlet</url-pattern> </web-resource-collection> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> <auth-constraint> <role-name>connect</role-name> </auth-constraint> </security-constraint> <security-role> <description>The role required to connect to the application </description> <role-name>connect</role-name> </security-role> <login-config> <auth-method>BASIC</auth-method> </login-config> A: I have tested this by commenting out the HTTP Connector in server.xml forcing the app to work on HTTPS https://localhost:8443/testapp works as expected http://localhost:8080/testapp returns a 404 http://localhost:8443/testapp Note the incorrect mix of protocol and port returns a small stream of garbage which is rendered in IE and as binary in Firefox this is of 7 bytes Can you recheck if you are seeing the 3rd scenario which should not happen in a natural case but only if someone fiddles with the URL? Okay, I tested using CONFIDENTIAL but it still does not redirect the http on 8443 to https. I'm guessing that only comes into picture when the user has tried http on the valid 8080 port. Using Fiddler, I see that the headers coming back are non-existent and the junk response. HTTP/1.1 200 This buggy server did not return headers This seems to be the standard behaviour, and end-users who access the app in this manner will see junk as expected. If you really need to, you could try writing your own custom Tomcat Valve which acts like a Filter to take care of this special case and redirect the users to SSL
doc_23536235
In the manifest file of bundle B I have added bundle A as a dependency. Further I have exported the packages in A so they are visible for B. I also have a .properties file in bundle A that I would like to make visible for bundle B. In the build.properties pane in bundle A I have specified: source.. = src/ bin.includes = META-INF/,\ .,\ bundle_A.properties Now in bundle B I try to load the .properties file using: private Properties loadProperties() { Properties properties = new Properties(); InputStream istream = this.getClass().getClassLoader().getResourceAsStream( "bundle_A.properties"); try { properties.load(istream); } catch (IOException e) { logger.error("Properties file not found!", e); } return properties; } But that gives a nullpointer exception (the file is not found on the classpath). Is it possible to export resources from bundle A (just like when you export packages) or somehow access the file in A from B in another way (accessing the classloader for bundle A from bundle B)? A: Have you considered adding a method to bundle A's API that loads and returns the resource? Many might consider this a better design as it allows the name or means of storage of the resource to change without breaking clients of bundle A. A: If you're writing an Eclipse plug-in you could try something like: Bundle bundle = Platform.getBundle("your.plugin.id"); Path path = new Path("path/to/a/file.type"); URL fileURL = Platform.find(bundle, path); InputStream in = fileURL.openStream(); A: The getEntry(String) method on Bundle is intended for this purpose. You can use it to load any resource from any bundle. Also see the methods findEntries() and getEntryPaths() if you don't know the exact path to the resource inside the bundle. There is no need to get hold of the bundle's classloader to do this. A: Have you tried using the BundleContext of bundle A to load resources? A: Try with /; if you don't put /, the class loader will try to load the resource from the same bundle. this.getClass().getClassLoader().getResourceAsStream( "/bundle_A.properties")
doc_23536236
Now when I'm trying to build my project in Android Studio or Eclipse with 19.x it fails with the following message. How can I fix it? Dx 1 error; aborting Conversion to Dalvik format failed with error 1 Here is the entire console log. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.html.dom.SecuritySupport$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.html.dom.SecuritySupport$2) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.html.dom.SecuritySupport$3) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.html.dom.SecuritySupport$4) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.html.dom.SecuritySupport$5) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.html.dom.SecuritySupport$6) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.html.dom.SecuritySupport$7) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.html.dom.SecuritySupport$8) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.dom.CharacterDataImpl$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.dom.ParentNode$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.dom.SecuritySupport$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.dom.SecuritySupport$2) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.dom.SecuritySupport$3) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.dom.SecuritySupport$4) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.dom.SecuritySupport$5) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.dom.SecuritySupport$6) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.dom.SecuritySupport$7) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.dom.SecuritySupport$8) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.XMLEntityManager$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.XMLEntityScanner$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.XMLErrorReporter$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.SecuritySupport$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.SecuritySupport$2) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.SecuritySupport$3) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.SecuritySupport$4) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.SecuritySupport$5) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.SecuritySupport$6) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.SecuritySupport$7) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.SecuritySupport$8) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.xs.XSSimpleTypeDecl$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.xs.XSSimpleTypeDecl$2) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.xs.XSSimpleTypeDecl$3) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.dv.xs.XSSimpleTypeDecl$4) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (org.apache.xerces.impl.xpath.XPath$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. [2014-04-18 17:46:07 - ARMRSS] Dx UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dx.cf.iface.ParseException: bad utf-8 byte a0 at offset 00000004 at com.android.dx.cf.cst.ConstantPoolParser.parseUtf8(ConstantPoolParser.java:374) at com.android.dx.cf.cst.ConstantPoolParser.parse0(ConstantPoolParser.java:262) at com.android.dx.cf.cst.ConstantPoolParser.parse0(ConstantPoolParser.java:294) at com.android.dx.cf.cst.ConstantPoolParser.parse(ConstantPoolParser.java:150) at com.android.dx.cf.cst.ConstantPoolParser.parseIfNecessary(ConstantPoolParser.java:124) at com.android.dx.cf.cst.ConstantPoolParser.getPool(ConstantPoolParser.java:115) at com.android.dx.cf.direct.DirectClassFile.parse0(DirectClassFile.java:482) at com.android.dx.cf.direct.DirectClassFile.parse(DirectClassFile.java:406) at com.android.dx.cf.direct.DirectClassFile.parseToInterfacesIfNecessary(DirectClassFile.java:388) at com.android.dx.cf.direct.DirectClassFile.getMagic(DirectClassFile.java:251) at com.android.dx.command.dexer.Main.processClass(Main.java:665) at com.android.dx.command.dexer.Main.processFileBytes(Main.java:634) at com.android.dx.command.dexer.Main.access$600(Main.java:78) at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:572) at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284) at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166) at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144) at com.android.dx.command.dexer.Main.processOne(Main.java:596) at com.android.dx.command.dexer.Main.processAllFiles(Main.java:498) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:264) at com.android.dx.command.dexer.Main.run(Main.java:230) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.android.ide.eclipse.adt.internal.build.DexWrapper.run(DexWrapper.java:187) at com.android.ide.eclipse.adt.internal.build.BuildHelper.executeDx(BuildHelper.java:786) at com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder.build(PostCompilerBuilder.java:597) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:726) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:321) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:396) at org.eclipse.core.internal.resources.Project$1.run(Project.java:618) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2344) at org.eclipse.core.internal.resources.Project.internalBuild(Project.java:597) at org.eclipse.core.internal.resources.Project.build(Project.java:124) at com.android.ide.eclipse.adt.internal.project.ProjectHelper.doFullIncrementalDebugBuild(ProjectHelper.java:1143) at com.android.ide.eclipse.adt.internal.launch.LaunchConfigDelegate.launch(LaunchConfigDelegate.java:155) at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:855) at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:704) at org.eclipse.debug.internal.ui.DebugUIPlugin.buildAndLaunch(DebugUIPlugin.java:1047) at org.eclipse.debug.internal.ui.DebugUIPlugin$8.run(DebugUIPlugin.java:1251) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53) Caused by: java.lang.IllegalArgumentException: bad utf-8 byte a0 at offset 00000004 at com.android.dx.rop.cst.CstString.throwBadUtf8(CstString.java:171) at com.android.dx.rop.cst.CstString.utf8BytesToString(CstString.java:143) at com.android.dx.rop.cst.CstString.<init>(CstString.java:200) at com.android.dx.cf.cst.ConstantPoolParser.parseUtf8(ConstantPoolParser.java:371) ... 43 more ...while parsing cst 00bf at offset 000008dd ...while parsing cst 003c at offset 00000109 ...while parsing org/apache/xerces/impl/xpath/regex/ParserForXMLSchema.class [2014-04-18 17:46:07 - ARMRSS] Dx 1 error; aborting [2014-04-18 17:46:07 - ARMRSS] Conversion to Dalvik format failed with error 1 A: I am experiencing exactly the same issue. What I have noticed, though, is that this problem only occurs when I build the debug .apk. That is, the release .apk is built with no such error. Funny... You may give it a try, if you still have this issue in your agenga.
doc_23536237
I know there is a method called System.IO.Path.IsPathRooted but this returns true for paths like: * *C:Documents */Documents I have seen a method called IsPathFullyQualified which I am interested in, see here, but unfortunately, it seems it is not recognized under .NET Framework 4.5. So Is there any equivalent method for .NET 4.5? A: Full disclaimer: I did not write this code myself and do not own any rights to it. This is based on the .NET Core Source by Microsoft. More info below. TL;DR: For a Windows system, you may add the following class to your project and then call PathEx.IsPathFullyQualified() to check if the path is fully qualified: Public Class PathEx Public Shared Function IsPathFullyQualified(path As String) As Boolean If path Is Nothing Then Throw New ArgumentNullException(NameOf(path)) End If Return Not IsPartiallyQualified(path) End Function Private Shared Function IsPartiallyQualified(path As String) As Boolean If path.Length < 2 Then ' It isn't fixed, it must be relative. There is no way to specify a fixed ' path with one character (or less). Return True End If If IsDirectorySeparator(path.Chars(0)) Then ' There is no valid way to specify a relative path with two initial slashes or ' \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\ Return Not (path.Chars(1) = "?"c OrElse IsDirectorySeparator(path.Chars(1))) End If ' The only way to specify a fixed path that doesn't begin with two slashes ' is the drive, colon, slash format- i.e. C:\ Return Not ((path.Length >= 3) AndAlso (path.Chars(1) = IO.Path.VolumeSeparatorChar) AndAlso IsDirectorySeparator(path.Chars(2)) AndAlso IsValidDriveChar(path.Chars(0))) ' ^^^^^^^^^^^^^^^^ ' To match old behavior we'll check the drive character for validity as ' the path is technically not qualified if you don't have a valid drive. ' "=:\" is the "=" file's default data stream. End Function Private Shared Function IsDirectorySeparator(c As Char) As Boolean Return c = Path.DirectorySeparatorChar OrElse c = Path.AltDirectorySeparatorChar End Function Private Shared Function IsValidDriveChar(value As Char) As Boolean Return (value >= "A"c AndAlso value <= "Z"c) OrElse (value >= "a"c AndAlso value <= "z"c) End Function End Class Where does this code (and comments) come from? This was extracted from the .NET Core Source Browser which is publicly available, adapted to work with .NET Framework, and converted to VB.NET. The .NET Core's IsPathFullyQualified() method uses an internal method called IsPartiallyQualified() to check if the path is fully qualified (not partially qualified). That internal method has different logic for different Operating Systems. This is the Windows version which the above code is based on. Usage: Console.WriteLine(PathEx.IsPathFullyQualified("C:Documents")) ' False Console.WriteLine(PathEx.IsPathFullyQualified("/Documents")) ' False Console.WriteLine(PathEx.IsPathFullyQualified("C:\Documents")) ' True A: Here's another possible method to determine if a Path is Fully qualified and also valid. This method(*) tries to generate an Uri from a supplied path using Uri.TryCreate(). When this method succeeds, it then inspects the non-public IsDosPath Property, which is set internally by the Uri class when a new Uri is parsed to determine whether it's valid and what kind of resource it represents. You can see in the .Net Source code that the PrivateParseMinimal() method performs a number of tests to validate the path and also checks whether a DosPath is rooted. Imports System.Reflection Private Function PathIsFullyQualified(path As String) As (Valid As Boolean, Parsed As String) Dim flags = BindingFlags.GetProperty Or BindingFlags.Instance Or BindingFlags.NonPublic Dim uri As Uri = Nothing If Uri.TryCreate(path, UriKind.Absolute, uri) Then Dim isDosPath = CBool(uri.GetType().GetProperty("IsDosPath", flags).GetValue(uri)) Return (isDosPath, uri.LocalPath) End If Return (False, String.Empty) End Function * This method returns a Named Tuple: supported from Visual Basic 2017 I tested the following paths; they all return False when I assume they should, except "file://c:/Documents":, but the PathIsFullyQualified method also returns the corresponding Local path, c:\Documents: Dim isOk1 = PathIsFullyQualified("C:Documents") 'False Dim isOk2 = PathIsFullyQualified("/Documents") 'False Dim isOk3 = PathIsFullyQualified("file://c:/Documents") 'True => isOk3.Parsed = "c:\Documents" Dim isOk4 = PathIsFullyQualified("\\Documents") 'False Dim isOk5 = PathIsFullyQualified("..\Documents") 'False Dim isOk6 = PathIsFullyQualified(".\Documents") 'False Dim isOk7 = PathIsFullyQualified("\Documents") 'False Dim isOk8 = PathIsFullyQualified("//Documents") 'False Dim isOk9 = PathIsFullyQualified(".Documents") 'False Dim isOkA = PathIsFullyQualified("..Documents") 'False Dim isOkB = PathIsFullyQualified("http://C:/Documents") 'False Dim isOkC = PathIsFullyQualified("Cd:\Documents") 'False Dim isOkD = PathIsFullyQualified("1:\Documents") 'False Dim isOkE = PathIsFullyQualified("Z:\\Another Path//docs") 'True => isOkE.Parsed = "Z:\Another Path\docs" Dim isOkF = PathIsFullyQualified(":\\Another Path//docs") 'False A: I came across this looking to use this method, but realized that the other answers are overcomplicated. I looked at MS's source code here: https://source.dot.net/#System.Private.CoreLib/Path.cs,3b4bff90471c3a68 and here: https://referencesource.microsoft.com/#mscorlib/system/io/path.cs,807960f08fca497d What I noticed was that in the second link, one of the ways to check for IsPathRooted was by checking this: (length >= 2 && path[1] == VolumeSeparatorChar). I simply adapted that check into a fleshed out method. The .Net source code (link 1) is essentially IsPathFullyQualified => !IsPathRooted, which I don't think went far enough to sanity check. So here is my replacement. public static bool IsPathFullyQualified(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return path.Length >= 3 && path[1] == System.IO.Path.VolumeSeparatorChar && ( path[2] == System.IO.Path.DirectorySeparatorChar | path[2] == System.IO.Path.AltDirectorySeparatorChar ); } EDIT: I realized this short method above doesn't accept UNC paths. So the updated version (which admittedly is just a shortened version of the original answer by eliminating the IsPartiallyQualified method) is below: public static bool IsPathFullyQualified(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length < 2) return false; //There is no way to specify a fixed path with one character (or less). if (path.Length == 2 && IsValidDriveChar(path[0]) && path[1] == System.IO.Path.VolumeSeparatorChar) return true; //Drive Root C: if (path.Length >= 3 && IsValidDriveChar(path[0]) && path[1] == System.IO.Path.VolumeSeparatorChar && IsDirectorySeperator(path[2])) return true; //Check for standard paths. C:\ if (path.Length >= 3 && IsDirectorySeperator(path[0]) && IsDirectorySeperator(path[1])) return true; //This is start of a UNC path return false; //Default } private static bool IsDirectorySeperator(char c) => c == System.IO.Path.DirectorySeparatorChar | c == System.IO.Path.AltDirectorySeparatorChar; private static bool IsValidDriveChar(char c) => c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
doc_23536238
Here the code: import requests quote = input('Inserisci la citazione: ') lingua = input('\nInserisci lingua (sigla, ad esempio ''it'' per ''Italiano''): ') key = 'xxxxxxxxx' parms = {'q':quote, 'key':key, 'maxResults':5,'langRestrict':lingua} r = requests.get(url='https://www.googleapis.com/books/v1/volumes', params = parms) rj = r.json() for i in range(0,3): print('\n' + rj['items'][i]['volumeInfo']['title'] + '\n') for authors in rj['items'][i]['volumeInfo']['authors']: print(authors) print('\n' + '\n') input('press enter to quit') What is wrong? A: I solved! It was an error in the conversion of the .ipynb file into .py file. To convert it I used a code found here in SO and now it works. Here the post that helped me: Is it possible to generate an executable (.exe) in a jupyter-notebook?
doc_23536239
java.lang.ClassCastException: com.google.firebase.storage.UploadTask$TaskSnapshot cannot be cast to com.google.firebase.storage.UploadTask Follow implementation I use import com.google.firebase.storage.UploadTask val tasks = mutableListOf<UploadTask>() var uploadTask = spaceRef.putBytes(data) tasks.add(uploadTask) Tasks.whenAllSuccess<UploadTask>(tasks).addOnSuccessListener { uploadTasks -> val downloadUrls = mutableListOf<Uri>() lifecycleScope.launch { uploadTasks.forEach { downloadUrls.add(it.await().storage.downloadUrl.await()) } } }
doc_23536240
from celery import Celery "ModuleNotFoundError: No module named celery This file is my celery.py file. I have already installed Celery via pip (pip install celery). Run celery, celery-beat, and flower run in terminals successfully. Also, from the Python shell, I get the following: >>> from celery import Celery >>> Celery <class 'celery.app.base.Celery'> So it seems like Celery is installed and even working, but for some reason my app is failing to due celery not being recognized. Any help identifying the problem would be appreciated.
doc_23536241
I want to know how to update my JSONobject if user change the phone number, or an email, after that I want to add this JSONobject's to a JSONarray to post to my service. This is the code where I put elements in EditText's: try { multiplesArray = new JSONArray(multiples); //multiplesUpdatedArray = new JSONArray(); System.out.println(multiplesArray.toString(2)); for (int i=0; i<multiplesArray.length(); i++) { JSONObject contact = new JSONObject(); String type = multiplesArray.getJSONObject(i).getString("tipo"); String data = multiplesArray.getJSONObject(i).getString("texto"); String id = multiplesArray.getJSONObject(i).getString("id"); if (type.equals("phone")) { final EditText etPhoneItem = new EditText(this); etPhoneItem.setText(data); viewPhonesContainer.addView(etPhoneItem); } else if (type.equals("email")) { final EditText etEmailItem = new EditText(this); etEmailItem.setText(data); viewEmailContainer.addView(etEmailItem); } contact.put("tipo", type); contact.put("id", id); contact.put("texto", data); contact.put("cat", ""); contact.put("cat_id", ""); /*multiplesUpdatedArray.put("tipo"); multiplesUpdatedArray.put(type); multiplesUpdatedArray.put("id"); multiplesUpdatedArray.put(id); multiplesUpdatedArray.put("texto"); multiplesUpdatedArray.put(data);*/ } } catch (JSONException e) { e.printStackTrace(); } I try some code with "setOnFocusChangeListener" but it didn't work :-( Thanks in advance! A: Use addTextChangeListener . editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence pCode, int start, int before, int count) { // change your JSONObject jsobObject.put("key", "value"); } @Override public void afterTextChanged(Editable s) { } }); A: You can do it. etPhoneItem.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.length() != 0) { try { contact.put("number", s.toString()); } catch (JSONException e) { e.printStackTrace(); } } } }); A: Simply you can use textView.addTextChangedListener(yourTextWatcherListener) to get the text when user changes the text. But why update that text in json frequetly, because using TextWatcher you will endup updating the json for each and every character you enter. Updating json frequently is very expensive and very bad practice. Instead of using textwatch listener just form the json when you press the post button. If you are very clear that you are going to update it frequently, then create pojo classes according to the json structure. Updating the variables of the class is not expensive. Convert the pojo class to json using Jackson when editing is done. JSON to POJO
doc_23536242
SELECT * FROM ADD_FACULTY_OVERRIDE WHEN "GENDER" ='Male' INSERT 'YES' AS "Financial Aid" A: First, try to avoid using SELECT *, it's costly when running queries, be explicit with your columns as a rule of thumb. Here's what you want: SELECT EAGLE_ID ,DEPT_ID ,LAST_NAME ,FIRST_NAME ,MIDDLE_NAME ,GENDER ,BIRTHDATE ,ETHNICITY ,TENURE ,SHORT_TITLE ,FULL_TIME ,EMAIL ,CASE WHEN GENDER = 'Male' THEN 'Yes' WHEN GENDER = 'Female' THEN 'No' ELSE '' END AS [Financial_Aid] FROM ADD_FACULTY_OVERRIDE
doc_23536243
In Xcode, I see that all of the provisioning profiles tied to the distribution certificate are set to expire in 2 weeks. I went into the Organizer->Provisioning Profiles and tried to Renew, but I received an error dialog indicating that "No value was provided for the parameter 'deviceids'". When I look on the Apple Provisioning Portal for that profile, it shows that the certificate is expiring in 2 weeks and that there are no devices associated with it (which is the way I've been doing it all along). So - I'm trying to renew these, and haven't done this before. Has anyone seen a similar error in Xcode? Do I need to renew my certificate first, and if so, how? I don't see any "create new certifcate" button on the Provisioning Portal or in Xcode. A: OK - I think I've fixed this. Here is what I did and it seems to work - when I upload the next release I'll know for sure. * *In X-Code, I deleted all of my provisioning profiles *I then quit out of X-Code *From the Development Portal, I revoked my developer and distribution certificates *I created new keys using the Key Chain application *Still in Key-Chain, I removed my old, soon to be expiring key/certificate *Back on the Development Portal, I created new certificates *Still on the Development Portal, I was able to edit all of my provisioning profiles and associate the correct new certificate to it *I downloaded the new profiles *I then followed this link's advice and worked around the apparent bug in X-Code to remove the old provisioning profiles from my project: Codesign error: Provisioning profile cannot be found after deleting expired profile *Started X-Code back up and copied the provisioning profiles into Organizer *Built for a device and tested OK. *Built for IOS Device as though I'm preparing to upload to the AppStore and build was successful. I haven't tried uploading to the store. I actually did the steps twice, once for the development profiles and then once that worked/tested on my test devices, I modified the distribution profiles. These set X-Code up w/ no warning and Organizer now shows all my valid provisioning profiles that won't expire for another year. Hopefully, next year, if I don't forget these steps, I'll be able to do it a bit more quickly. A: I had a similar problem after I recently renewed my certificate. The following corrected the issues for my Development Provisioning Profile: * *Click Refresh in Xcode Organizer. *Ensure the Code Signing build settings for your Project and Target are set to the proper Provisioning Profile. You should select iPhone Developer to avoid future issues. *Optionally, remove expired profiles from Device tab in Xcode Organizer. The following corrected the issues for my Distribution Provisioning Profile: * *Log in to your iOS Developer Portal *Go to the Distribution tab under Provisioning *Create a new distribution profile. *After the profile is generated, click Refresh in Xcode Organizer A: An easier way of doing it is ... My certificate had expired, so the renew button button in the Xcode Organizer did not work. I did the following: * *logged into the iOS provisioning portal *went to provisioning profiles > distribution *clicked on each of the expired profiles and clicked edit *the certificate radio button was unchecked because my certificate had expired, so I checked it and clicked generate *you'll then be prompted to download the newly generated profile.... dont! *wait about 5 minutes *go into the Xcode Organizer > provisioning profiles and click refresh *the profiles should then change from "expired" to "valid"
doc_23536244
A: You should checkout the latest code on our github project. The method is available on the ExchangeService: https://github.com/OfficeDev/ews-java-api/blob/master/src/main/java/microsoft/exchange/webservices/data/core/ExchangeService.java#L2663 The signature of the method looks as follows: public void setUserOofSettings(String smtpAddress, OofSettings oofSettings)
doc_23536245
All of the examples I can find have the sockets being closed as soon as the immediate communication is done. For example, from the NodeMCU docs: sv = net.createServer(net.TCP, 30) function receiver(sck, data) print(data) sck:close() end if sv then sv:listen(80, function(conn) conn:on("receive", receiver) conn:send("hello world") end) end Here a new socket is created, the response is sent, then the socket is closed. However, my understanding of a socket is that the connection exists until the server or the client explicitly closes it... So shouldn't the socket stay open? Thank you for all info / advice. EDIT: Although i didn't get any clear answer, the webserver library Marcel recommended is great! I was able to model my implementation off of this one.
doc_23536246
In my case I've noticed this to happen when the dropdown list is being constructed after a form post and the value differs from the value that was submitted. So the scenario is a form containing a dropdown to select a category you want to see. When you submit this, the dropdown is rebuilt as part of the results, and is preselected to the one you chose. However, if the controller action changes the value that was posted and then passes that modified model to the view, the value in the model is ignored and no options are set as selected. Even if you construct the DropDownListFor<> to specifically set the selected value, no option is set as selected. When you don't change the submitted value in the model prior to going into the view, the following is all you need: @Html.DropDownListFor(m => m.Selection.CategoryId, new SelectList(Model.Categories.Select(c => new SelectListItem { Value = c.Id, Text = c.Name + " (" + c.Id + ")" }), "Value", "Text"), "All", new { onchange = "this.form.submit();" }) But with the problem present (modifying the submitted value in the controller action), even the following ways of specifically setting the selected option does not work: @Html.DropDownListFor(m => m.Selection.CategoryId, new SelectList(Model.Categories.Select(c => new SelectListItem { Value = c.Id, Text = c.Name + " (" + c.Id + ")" }), "Value", "Text", Model.Selection.CategoryId), "All", new { onchange = "this.form.submit();" }) @Html.DropDownListFor(m => m.Selection.CategoryId, new SelectList(Model.Categories.Select(c => new SelectListItem { Value = c.Id, Text = c.Name + " (" + c.Id + ")", Selected = c.Id == Model.Selection.CategoryId }), "Value", "Text"), "All", new { onchange = "this.form.submit();" }) A: This isn't about DropDownListFor method, it is about model binding. When you return another view after a POST request, ASP.NET MVC thinks that the validation has failed and uses the previous values for model binding. You can read more about this behavior in this blog post. You can prevent this by clearing ModelState in your action. [HttpPost] public ActionResult SomeAction() { ModelState.Clear(); //return View(model); }
doc_23536247
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:com="http://com.org.srv"> <soapenv:Header/> <soapenv:Body> <com:methodName> <com:someParam>value</com:someParam> <com:param name="firstPoint"> <com:param name="code">value</com:param> </com:param> <com:param name="firstPointDesc"> <com:param name="pName">value</com:param> <com:param name="pLo">value</com:param> </com:param> <com:param name="endPoint"> <com:param name="code">value</com:param> </com:param> <com:param name="endPointDesc"> <com:param name="pName">value</com:param> <com:param name="pLo">value</com:param> </com:param> <com:param name="bunch"> <com:param name="temperature">val</com:param> <com:param name="humidity">val</com:param> <com:param name="pressure">val</com:param> </com:param> </com:methodName> </soapenv:Body> </soapenv:Envelope> This information was provided as-is and i need to describe it in xsd file in eclipse. I have tried: <element name="methodNameRequest"> <complexType> <sequence maxOccurs="1" minOccurs="1"> <element name="someParam" type="string" maxOccurs="1" minOccurs="1"> </element> <element name="deviceId" type="string"></element> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <sequence> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <simpleContent> <extension base="string"> <attribute name="name" type="string" default="code" /> </extension> </simpleContent> </complexType> </element> </sequence> <attribute name="name" type="string" default="firstPoint" /> </complexType> </element> <element name="params" maxOccurs="1" minOccurs="1"> <complexType> <sequence> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <simpleContent> <extension base="string"> <attribute name="name" type="string" default="pName" /> </extension> </simpleContent> </complexType> </element> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <simpleContent> <extension base="string"> <attribute name="name" type="string" default="pLo" /> </extension> </simpleContent> </complexType> </element> </sequence> <attribute name="name" type="string" default="firstPointDesc" /> </complexType> </element> <element name="params" maxOccurs="1" minOccurs="1"> <complexType> <sequence> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <simpleContent> <extension base="string"> <attribute name="name" type="string" default="code" /> </extension> </simpleContent> </complexType> </element> </sequence> <attribute name="name" type="string" default="endPoint" /> </complexType> </element> <element name="params" maxOccurs="1" minOccurs="1"> <complexType> <sequence> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <simpleContent> <extension base="string"> <attribute name="name" type="string" default="pName" /> </extension> </simpleContent> </complexType> </element> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <simpleContent> <extension base="string"> <attribute name="name" type="string" default="pLo" /> </extension> </simpleContent> </complexType> </element> </sequence> <attribute name="name" type="string" default="endPointDesc" /> </complexType> </element> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <sequence> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <simpleContent> <extension base="string"> <attribute name="name" type="string" default="temperature" /> </extension> </simpleContent> </complexType> </element> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <simpleContent> <extension base="string"> <attribute name="name" type="string" default="humidity" /> </extension> </simpleContent> </complexType> </element> <element name="param" maxOccurs="1" minOccurs="1"> <complexType> <simpleContent> <extension base="string"> <attribute name="name" type="string" default="pressure" /> </extension> </simpleContent> </complexType> </element> </sequence> <attribute name="name" type="string" default="bunch" /> </complexType> </element> .... but with no success: Multiple elements with name 'param', with different types, appear in the model group. reported by eclipse. Can anybody provide a valid example of xsd description for this or similar structure? I am not in common with wsdl schemas and services at all. Many thanks. A: The designers of the XML vocabulary appear to have been working to make the XML unvalidatable using normal XML tools; they may have succeeded. To foil their nefarious plan, your best bet is probably either to map their XML into isomorphic but more easily validatable XML (make those attribute values be element names, for example), or else look into XSD 1.1 assertions, and work on your XPath 2.0 skills.
doc_23536248
[stderr] FAILURE: Build failed with an exception. [stderr] * What went wrong: [stderr] Execution failed for task ':unimodules-permissions-interface:compileReleaseJavaWithJavac'. [stderr] > Compilation failed; see the compiler error output for details. [stderr] * Try: [stderr] Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. [stderr] * Get more help at https://help.gradle.org [stderr] BUILD FAILED in 4m 12s Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0. Use '--warning-mode all' to show the individual deprecation warnings. See https://docs.gradle.org/6.9/userguide/command_line_interface.html#sec:command_line_warnings 438 actionable tasks: 438 executed Error: Gradle build failed with unknown error. See logs for the "Run gradlew" phase for more information.
doc_23536249
$(function(){ var questions = $('#questions'); function refreshSelects(){ var selects = questions.find('select'); // Lets not do chosen on the first select selects.not(":first").chosen({ disable_search_threshold: true }); // Listen for changes selects.unbind('change').bind('change',function(){ // The selected option var selected = $(this).find('option').eq(this.selectedIndex); // Look up the data-connection attribute var connection = selected.data('connection'); // Removing the li containers that follow (if any) selected.closest('#questions li').nextAll().remove(); if(connection){ fetchSelect(connection); } }); } var working = false; function fetchSelect(val){ if(working){ return false; } working = true; $.getJSON('citibank.php',{key:val},function(r){ var connection, options = ''; switch (r.type) { case 'select': $.each(r.items,function(k,v){ connection = ''; if(v){ connection = 'data-connection="'+v+'"'; } options+= '<option value="'+k+'" '+connection+'>'+k+'</option>'; }); if(r.defaultText){ // The chose plugin requires that we add an empty option // element if we want to display a "Please choose" text options = '<option></option>'+options; } // Building the markup for the select section $('<li>\ <p>'+r.title+'</p>\ <select data-placeholder="'+r.defaultText+'">\ '+ options +'\ </select>\ <span class="divider"></span>\ </li>').appendTo(questions); refreshSelects(); break; case 'html': $(r.html).appendTo(questions); break; } working = false; }); } $('#preloader').ajaxStart(function(){ $(this).show(); }).ajaxStop(function(){ $(this).hide(); }); // Initially load the product select fetchSelect('callTypeSelect'); }); A: Here is great article on using jCookies. http://tympanus.net/codrops/2011/09/04/j-is-for-jcookies-http-cookie-handling-for-jquery/ The code for setting it goes like this: $.jCookies({ name : 'Person', value : { first: 'John', last: 'Smith', Age: 25 } }); Getting the cookie goes like this var person = $.jCookies({ get : 'Person' }); A: Do you need that value on the server? If you don't I recomment the jStorage plugin. It uses local storage and userData to save information. This has the benefits that the values are not sent to your server on every request, like cookies do. The usage is very simple: $.jStorage.set("something", {data: [1,2,3], other: "a string"}); and $.jStorage.get("something"); // returns {data: [1,2,3], other: "a string"} In your code it would be something like: $(function() { var questions = $('#questions'); var lastSelection = $.jStorage.get("lastSelection"); if(lastSelection) { questions.find("select:first").val(lastSelection); } // more code.... selects.unbind('change').bind('change',function(){ var selected = $(this).find('option').eq(this.selectedIndex); if(questions.find("select:first")[0] === this) { // Only save if it's the first combo (you could change this to a better way to identify the first select) $.jStorage.set("lastSelection", selected); } // more code.... });
doc_23536250
what can i do in order to keep the retrieved data? this is my code: public void done(List<ParseObject> parseObjects, com.parse.ParseException e) { if (e == null) { 'myFieldArray' = new String[parseObjects.size()][3]; String text = ""; int index =0; for(ParseObject po : parseObjects){ text = po.getString("Fact"); Toast.makeText(context,theFact, Toast.LENGTH_SHORT).show(); 'myFieldArray'[index][0] = text; index++; } } A: Well, after few tries, i realized that the Parse query probably goes inside the block twice - and ones when there are no objects returned - thats mean the array will be initialized again - and thats the reason its remains null. the part i should have added is if (e == null && parseObject.size()>0)
doc_23536251
Here is my ts code: arr1.push({label: "id", value: "1"}); arr2.push({label: "id", value: "2"}); masterArr.push(arr1); masterArr.push(arr2); Here is my template: <ng-template pTemplate="body" let-rowData let-expanded="expanded" let-columns="columns"> <td>{{rowData.name}}</td> <td>{{rowData.rollNo}}</td> <td> <p-dropdown *ngFor="let s of masterArr,let i = index" [options]="masterArr[i]" ></p-dropdown> </td> </tr> </ng-template> StackBlitz: https://stackblitz.com/edit/p-table-primeng-v6-tq33vs A: You can add appendTo="body" property to p-dropdown. It will fix the issue if you have your dropdown inside the p-table body, without changing any CSS. AppendTo target element to attach the overlay in primeNG p-dropdown <ng-template pTemplate="body" let-rowData let-expanded="expanded" let-columns="columns"> ... <tr> <td> <p-dropdown *ngFor="let s of masterArr,let i = index" [options]="masterArr[i]" appendTo="body"></p-dropdown> </td> </tr> </ng-template>
doc_23536252
balance: int = 484 monthlyPayRate: float = 0.04 annualInterestRate: float = .2 for i in range(12): balance = balance - (balance * monthlyPaymentRate) +\ ((balance - (balance * monthlyPaymentRate)) * \ (annualInterestRate/12)) print("Remaining balance:", round(balance,2)) I am just trying to work through the range(1) and I know the correct answer is 472.38. This is how I would calculate it: 484 – (484 * 0.04) = $464.64 (This is balance after payment but before interest) 464 * (.2/12) = $7.42(We took our remaining balance of 464.64 x the interest rate of 0.016) 464 .64 + 7.424 = $472 (We added our interest on our remaining balance to get our new balance) When I try to plug the numbers into the python formula and do it by hand I cannot figure out how Python is getting it to work. I was hoping someone would be so kind as to show me the steps Python takes using the formula? A: I would imagine it does it like this: balance = 484 - (484 * 0.04) + ((484- (484 *0.04)) * (0.2/12)) that is basically what it's written there, and the result is 472.38. But then it substitutes 472.38 to the variable balance e does the calculation again, 12 times, always replacing the variable with the new result, returning 361.61 in the end. The calculations worked for me both in the software and by hand. A: For clarity: balance = 484 monthlyPaymentRate = 0.04 annualInterestRate = .2 for i in range(12): paidoff = balance * monthlyPaymentRate newinterest = (balance - paidoff) * annualInterestRate/12 balance = balance - paidoff + newinterest print("Balance after", i+1, "months", round(balance,2)); print("Remaining balance:", round(balance,2)) gives: Balance after 1 months 472.38 Balance after 2 months 461.05 Balance after 3 months 449.98 Balance after 4 months 439.18 Balance after 5 months 428.64 Balance after 6 months 418.35 Balance after 7 months 408.31 Balance after 8 months 398.51 Balance after 9 months 388.95 Balance after 10 months 379.62 Balance after 11 months 370.5 Balance after 12 months 361.61 Remaining balance: 361.61 Splitting the calculation allows for this sort of thing: >>> balance = 484 >>> totalpaid=0 >>> totalinterest=0 >>> monthlyPaymentRate = 0.04 >>> annualInterestRate = .2 >>> for i in range(12): ... paidoff = balance * monthlyPaymentRate ... newinterest = (balance - paidoff) * annualInterestRate/12 ... balance = balance - paidoff + newinterest ... totalpaid = totalpaid + paidoff ... totalinterest = totalinterest + newinterest ... >>> print("Remaining balance:", round(balance,2)) Remaining balance: 361.61 >>> print("Total amount paid off:", round(totalpaid,2)) Total amount paid off: 203.98 >>> print("Total interest accrued:", round(totalinterest,2)) Total interest accrued: 81.59
doc_23536253
So instead of this: $("input").removeClass("CO_form_alert"); $("select").removeClass("CO_form_alert"); A: $(".CO_form_alert").removeClass("CO_form_alert"); A: why couldn't you just use the following to do as you asked remove the class from all elements (versus a single defined element) $(".CO_form_alert").removeClass("CO_form_alert"); A: $("input, select").removeClass("CO_form_alert"); or even $(".CO_form_alert").removeClass("CO_form_alert"); Hint: jQuery always works on all selected elements. A: You can specify any number of selectors to perform the removeClass on: $("select, input, banana").removeClass("CO_form_alert");
doc_23536254
However, I couldn't find out how to tell cli_warn() and cli_error() to have the same blueish color as in base R (and even rlang for warnings). IMHO users are used to these colors and having them in white is a bit confusing and far less eye-catching. For instance: cli::cli_abort(c("foo", i="bar")) stop("foo") cli::cli_warn(c("foo", i="bar")) rlang::warn(c("foo", i="bar")) Is there a global way to keep using cli_* for formatting but get the colors right? Otherwise, is there a higher reason the devs chose to have different colors in cli? Even best if the error could keep being orange but the rest is not just plain white like a mere print. References: * *https://cli.r-lib.org/reference/themes.html *https://cli.r-lib.org/reference/ansi_palettes.html *https://cli.r-lib.org/articles/palettes.html
doc_23536255
It's the same functionality as when you check a column as visible/hidden in the column menu I'm looking for. Is this possible? A: I have edited the example of this hide column, column menu is working and column is hiding as well Example URL : https://stackblitz.com/edit/angular-s2rip3?file=app/app.component.ts you can visit here to see update example https://gvfum8.run.stackblitz.io and code for this example @Component({ selector: 'my-app', template: ` <kendo-grid [data]="gridData" style="height:400px" [columnMenu]="true"> <ng-template ngFor [ngForOf]="columns" let-column> <kendo-grid-column field="{{column}}" [hidden]="hiddenColumns.indexOf(column) > -1" > <ng-template kendoGridHeaderTemplate let-dataItem> {{dataItem.field}} </ng-template> </kendo-grid-column> </ng-template> </kendo-grid> ` }) export class AppComponent { public gridData: any[] = sampleCustomers; public columns: string[] = [ 'CompanyName', 'ContactName', 'ContactTitle' ]; public hiddenColumns: string[] = []; public restoreColumns(): void { this.hiddenColumns = []; } constructor(){ this.hiddenColumns.push("CompanyName"); } } There are three columns, 1st column is hidden and showing two columns.
doc_23536256
Failed to resolve: com.android.support:custom tabs:[26.0.0,26.1.0] Failed to resolve: com.android.support:support-v4:[26.0.0,26.1.0] A: Now Android support package disturbs over network(starts from 25.4), so your project's build.gradle file should include that: allprojects { repositories { jcenter() maven { url "https://maven.google.com" } } } UPDATE Also you can add google() instead of maven{url "..."}: allprojects { repositories { jcenter() google() } }
doc_23536257
In the code, it's have if(!message.member.roles.cache.some(r => r.name === "**Owner**"), I have this role but I can't delete message. But when I give 3 roles (Owner, Admin and Moderator) for me, I can use it. So I need to fix: 1 of 3 roles can still use it. The code is here: case 'clear': if(!args[1]) return message.reply('Please specify the number of messages to clear `e.g. !clear 10`') .then(message => message.delete({timeout: 3500})); if(!message.member.roles.cache.some(r => r.name === "Owner") || !message.member.roles.cache.some(r => r.name === "Admin") || !message.member.roles.cache.some(r => r.name === "Moderator")) return message.reply('You do not have permissions to clear!') .then(message => message.delete({timeout: 3500})); message.channel.bulkDelete(args[1]); break; A: You need to make it check if the user has neither of the three roles. Since you gave || between the if statements and not &&, it will check if the user doesn't have one or more of the three roles. If the user doesn't have one or more of them, it will output the message.reply. If you give && it will check if the user has none of the three roles. P.S: there were some bracket errors and quotation errors in your provided code. UPDATE: "**Owner**" has been changed to "Owner" Here's the updated code: case 'clear': if(!args[1]) return message.reply('Please specify the number of messages to clear `e.g. !clear 10`') .then(message => message.delete({timeout: 3500})); if(!message.member.roles.cache.some(r => r.name === "Owner") && (!message.member.roles.cache.some(r => r.name === "Admin")) && (!message.member.roles.cache.some(r => r.name === "Moderator")) { return message.reply('You do not have permissions to clear!') .then(message => message.delete({timeout: 3500})); } message.channel.bulkDelete(args[1]); break;
doc_23536258
Already I can save features and re-create them by Geojson object. the problem is that GeoJson dosen't save feature's style. what is the best way to save styles and load them with features? A: You can use below codes to save and load geojson file with styles. add the following line to the header <script src=" https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script> <!-- we will use it to download the geojson file --> Then add the following function to the code. function saveMap() { var mapLayers = map.getLayers().getArray(); var features = []; mapLayers.forEach(function(layer) { if (layer instanceof ol.layer.Vector) { var layerFeatures = layer.getSource().getFeatures(); layerFeatures.forEach(function(feature) { feature.setProperties(layer.getStyle()) //add the layer styles to the feature as properties features.push(feature); }); } }); var geojsonFormat = new ol.format.GeoJSON(); var geojsonString = geojsonFormat.writeFeatures(features, { featureProjection: map.getView().getProjection() }); var blob = new Blob([geojsonString], { type: 'text/plain' }); saveAs(blob, 'map.geojson'); } Load the map again with the styles in OpenLayers: // Use jQuery to read the GeoJSON file $.getJSON("map.geojson", function(data) { var geojson = new ol.format.GeoJSON({ dataProjection: "EPSG:4326", featureProjection: 'EPSG:3857' }).readFeatures(data); var vectorSource = new ol.source.Vector({ features: geojson, wrapX: false }); var vectorLayer = new ol.layer.Vector({ source: vectorSource, }) // Iterate through the features in a vector layer vectorLayer.getSource().forEachFeature(function(feature) { // Take the style of the feature as a variable var fill_color = feature.values_[0].fill_.color_; var stroke_color = feature.values_[0].stroke_.color_; var stroke_width = feature.values_[0].stroke_.width_; // Create a style object var style = new ol.style.Style({ stroke: new ol.style.Stroke({ color: stroke_color, width: stroke_width }), fill: new ol.style.Fill({ color: fill_color }) }); // Add the style to the feature feature.setStyle(style); }); map.addLayer(vectorLayer); }); You can view the full code of the following links ol-save-geojson.html ol-read-geojson-styles.html
doc_23536259
Why? And How can I fix it? A: It's a server setting that controls if the projections runtime is enabled or not. Check the documentation about the setting.
doc_23536260
test.cc: In function ‘void foo(int*)’: test.cc:15:16: error: no matching function for call to ‘begin(int*&)’ for (int i : bar) { ^ Along with a bunch of others from deeper in the template library. #include <iostream> using namespace std; void foo(int*); int main() { int bar[3] = {1,2,3}; for (int i : bar) { cout << i << endl; } foo(bar); } void foo(int* bar) { for (int i : bar) { cout << i << endl; } } If I redefine foo to use an indexed for loop, then the code compiles and behaves as expected. Also, if I move the range-based output loop into main, I get the expected behaviour as well. How do I pass the array bar to foo in such a way that it is capable of executing a range-based for-loop on it? A: For a fixed size array you can * *Pass a raw array by reference. *Pass a std::array by reference. *Pass a std::vector by reference. The natural choice (for a fixed size array) is std::array, i.e. #include <iostream> #include <array> using namespace std; void foo(array<int, 3> const& bar) { for (int i : bar) { cout << i << endl; } } int main() { array<int,3> const bar = {1,2,3}; for (int i : bar) { cout << i << endl; } foo(bar); } A: With the array decaying into a pointer you're losing one important piece of information: its size. With an array reference your range based loop works: void foo(int (&bar)[3]); int main() { int bar[3] = {1,2,3}; for (int i : bar) { cout << i << endl; } foo(bar); } void foo(int (&bar)[3]) { for (int i : bar) { cout << i << endl; } } or, in a generic fashion (i.e. without specifying the array size in the function signature), template <std::size_t array_size> void foo(int (&bar)[array_size]) { for (int i : bar) { cout << i << endl; } } Try it out A: Using C++20's std::span, you can have a reference to an array or runtime size. Here's your code with std::span instead: #include <iostream> #include <span> void foo(std::span<int>); int main() { int bar[3] = {1,2,3}; for (int i : bar) { std::cout << i << std::endl; } foo(bar); } void foo(std::span<int> bar) { for (int i : bar) { // now works std::cout << i << std::endl; } }
doc_23536261
<script> function numeric(input) { if(isNaN(input)) { alert("Is not a numeric value"); input.value=""; } } </script> <input type="number" value="" name="<?php echo $x; ?>" onblur="return numeric(value)"/> A: Use this $( "#numerictext" ).keyup(function() { var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/; var str = $('#numerictext').val(); if(!numberRegex.test(str)) { alert("Is not a numeric value"); $('#numerictext').val('') } }); <input type="number" id="numerictext" value="" name="<?php echo $x; ?>"/> A: You're passing the value into your function, then trying to clear the input by refering to its value. Instead, try: <script> function numeric(input) { if(isNaN(input.value)) { alert("Is not a numeric value"); input.value=""; } } </script> <input type="number" value="" name="<?php echo $x; ?>" onblur="return numeric(this)"/>
doc_23536262
` { "code": 0, "message": "cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://api.stripe.com/v1/tokens?card%5Bnumber%5D=4242+4242+4242+4242&card%5Bexp_month%5D=02&card%5Bexp_year%5D=2024&card%5Bcvc%5D=123", "data": null } ` My Code where I'm using the post request : ` if ($request->is_male){ $stripe = Stripe::make(env('STRIPE_SECRET')); $token = $stripe->tokens()->create([ 'card' => [ 'number' => $request->credit_number, 'exp_month' => $request->credit_exp_month, 'exp_year' => $request->credit_exp_year, 'cvc' => $request->credit_code ], ]); $customer = $stripe->customers()->create([ 'email' => $request->email, ]); $card = $stripe->cards()->create($customer['id'], $token['id']); if (!isset($customer['id'])) { return ResponseController::error(-150,"invalid customer"); } $charge = $stripe->charges()->create([ 'customer'=>$customer['id'], 'currency' => 'USD', 'amount' => env("pay_amount"), 'description' => 'Gyanomi Subscription', ]); if($charge['status'] != 'succeeded') { throw new \Exception($charge); } } `
doc_23536263
When creating domain object using factory I can generate a GUID, but cannot get a DB generated ID in order to return a valid ID as a part of the response. Is it possible and how to get DB generated ID using domain events, upon persisting domain object in a same transaction and avoid waiting for eventual consistency. DB generated ID is a part of the same aggregate root and repository. A: I think you can have two options: * *If the object creation is not expensive, you don't have to be eventual consistent. Create the object in DB and return the generated ID. *If expensive, break object creation to small units. The root object should be created simple and quick to be persisted in DB and return the generated ID. Let the other child objects/aggregates to be created eventual consistent via events/messages. A: The approach that I have seen that seems to work best is to have a SQL db server with a single integral IDENTITY column to issue the ID's, which you need to do before actually even create the entity (when create the commands for example if you're using CQRS too). This approach is actually quite simple to do and support and only requires one additional table (or not even that) in your db. This is not an uncommon practice and relieves your bc from the responsibility of owning logic of ID generation (in certain case this can be quite useful). CAUTION: as with all things in our software world this has a number of trade-offs: * *It can guarantee ordering but the sequence of id's may have gaps if a certain operation with one id fails and you retry your action. This is only important if you care about ordering the creation of your entities :) *This impacts performance as you have a single bottleneck (honestly you need to have a really large traffic for this to be a noticeable problem so I would not consider this a big problem) *It may be a security concern in certain contexts depending on how this id is used. I have to say that all points above are quite niche and I don't expect to really be a problem. For reference and more information about this practice you can read about Twitter's Snowflake project. Snowflake generated sequential guid-like 64-bit integral id's but a lot, if not all, of the principles still apply in this case. There are a lot of information and best practices about this practice in a lot of articles discussing Snowflake. Regards, Savvas
doc_23536264
void NeuralNetwork::backward(Eigen::MatrixXf back, float learningRate) { std::vector<Eigen::MatrixXf> dedw; std::vector<Eigen::MatrixXf> delta; int nLayers = layers.size(); int dIt = 0; for (int i = nLayers -1;i > 0; i=i-1) { Eigen::MatrixXf deltai; logger->LogVerbose("--------","Back", i,"---------"); if (i == (nLayers - 1)) { deltai.noalias() = back.cwiseProduct(dSigmoid(X[i])); delta.push_back(deltai); dIt++; } else { logger->LogVerbose("W", i); deltai.noalias() = (W[i].transpose() * delta[dIt - 1]).cwiseProduct(dSigmoid(X[i])); delta.push_back(deltai); dIt++; } Eigen::MatrixXf dedwi; dedwi.noalias() = delta[dIt - 1] * X[i - 1].transpose(); dedw.push_back(dedwi); logger->LogVerbose("dedw", dIt - 1, dedw[dIt - 1]); Eigen::MatrixXf WiNew; WiNew.noalias() = W[i - 1] - learningRate * dedw[dIt - 1]; W[i-1] = WiNew; logger->LogVerbose("W", i - 1); logger->LogVerbose(W[i - 1]); Eigen::MatrixXf BiNew; BiNew.noalias() = B[i - 1] - learningRate * delta[dIt - 1]; B[i-1] = BiNew; logger->LogVerbose("B", i - 1); logger->LogVerbose(B[i - 1]); } } A: Avoid memory-intensive operations in performance-sensitive code. * *Never pass "big arguments" by value. For instance void NeuralNetwork::backward(Eigen::MatrixXf back, float learningRate) should probably be void NeuralNetwork::backward(const Eigen::MatrixXf& back, float learningRate) This avoids copy-constructing the parameter again and again in the function. *Avoid copying inside the function. You push to delta and dedw vectors matrices that are temporary. You probably want to move them like this: delta.push_back(std::move(deltai)); *Reuse allocated memory. You can probably reuse delta and dedw workspace vectors. Even if to minimize the unnecessary allocations-deallocations. If you don't need the elements from the previous call -- simply clear them. These would be the first things to do. And finally -- profile! I would use perf record to analyze the bottlenecks in the program. The best way to squeeze out more performance is by fixing the biggest bottlenecks. At this point you don't know where you biggest bottleneck is. So profile, profile, profile.
doc_23536265
Is there any other simpler method in ES6 to achieve this? a = [ { name: 'NameOne', weekName: 'WeekOne' }, { name: 'NameTwo', weekName: 'WeekTwo' }, ]; b = [ { id: 'Name', type: 'text', data: '' }, { id: 'Week', type: 'text', data: '' }, ]; c = []; showOutput() { this.a.forEach((element) => { this.b.map((item) => { if (item.id == 'Name') { item.data = element.name; } if (item.id == 'Week') { item.data = element.weekName; } this.c.push(item); console.log('c', this.c); }); }); } Current Output : [{ id: 'Name', type: 'text', data: 'NameTwo' }, { id: 'Week', type: 'text', data: 'WeekTwo' }, { id: 'Name', type: 'text', data: 'NameTwo' }, { id: 'Week', type: 'text', data: 'WeekTwo' }] Desired Output: [{ id: 'Name', type: 'text', data: 'NameOne' }, { id: 'Week', type: 'text', data: 'WeekOne' }, { id: 'Name', type: 'text', data: 'NameTwo' }, { id: 'Week', type: 'text', data: 'WeekTwo' }] A: Problem with your code is that this.c.push(item); here the same object is getting referenced so in 2nd iteration it's changing the data that modified by 1st iteration. In order to solve this, you will have to clone the object (dereference somehow) I have used c.push(Object.assign({}, item)); or you can use c.push(JSON.parse(JSON.stringify(item))); or any other way to clone the object before pushing into array (c in your case) Note: This is just to point out the root cause of the issue, and it may not be the perfect solution for your scenario. e.g. a = [ { name: 'NameOne', weekName: 'WeekOne' }, { name: 'NameTwo', weekName: 'WeekTwo' }, ]; b = [ { id: 'Name', type: 'text', data: '' }, { id: 'Week', type: 'text', data: '' }, ]; c = []; function showOutput() { a.forEach((element) => { b.map((item) => { if (item.id == 'Name') { item.data = element.name; } if (item.id == 'Week') { item.data = element.weekName; } c.push(Object.assign({}, item)); // clone object }); }); } showOutput(); console.log('c', c); For more information: https://javascript.info/object-copy
doc_23536266
May I need to not call it again ? But there is nothing to check if it already configured or not. public class BumpActivity extends Activity { private IBumpAPI api; private ProgressDialog mDialog; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bump); mDialog = ProgressDialog.show(BumpActivity.this, "Preparing bump", "Loading"); bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE); IntentFilter filter = new IntentFilter(); filter.addAction(BumpAPIIntents.CHANNEL_CONFIRMED); filter.addAction(BumpAPIIntents.DATA_RECEIVED); filter.addAction(BumpAPIIntents.NOT_MATCHED); filter.addAction(BumpAPIIntents.MATCHED); filter.addAction(BumpAPIIntents.CONNECTED); registerReceiver(receiver, filter); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override public void onBackPressed(){ Intent resultIntent = new Intent(); setResult(Activity.RESULT_CANCELED, resultIntent); super.onBackPressed(); } private final ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder binder) { Log.i("BumpTest", "onServiceConnected"); api = IBumpAPI.Stub.asInterface(binder); new Thread() { public void run() { try { api.configure("9b17d663752843a1bfa4cc72d309339e", "Bump User"); } catch (RemoteException e) { Log.w("BumpTest", e); } } }.start(); Log.d("Bump Test", "Service connected"); } @Override public void onServiceDisconnected(ComponentName className) { Log.d("Bump Test", "Service disconnected"); } }; private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); try { if (action.equals(BumpAPIIntents.DATA_RECEIVED)) { getUserDetailFromBump(new String( intent.getByteArrayExtra("data"))); } else if (action.equals(BumpAPIIntents.MATCHED)) { long channelID = intent .getLongExtra("proposedChannelID", 0); Log.i("Bump Test", "Matched with: " + api.userIDForChannelID(channelID)); api.confirm(channelID, true); Toast toast = Toast.makeText( getApplicationContext(), "Matched with: " + api.userIDForChannelID(channelID), Toast.LENGTH_SHORT); toast.show(); } else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED)) { long channelID = intent.getLongExtra("channelID", 0); api.send(channelID, CurrentUserManager.getSharedManager() .getCurrentUser().getUserId().toString().getBytes()); } else if (action.equals(BumpAPIIntents.NOT_MATCHED)) { Toast toast = Toast.makeText(getApplicationContext(), "No match", Toast.LENGTH_SHORT); toast.show(); } else if (action.equals(BumpAPIIntents.CONNECTED)) { mDialog.dismiss(); api.enableBumping(); } } catch (RemoteException e) { } } }; public void getUserDetailFromBump(String data) { Log.i("User Id", data); LoginRequest login = new LoginRequest(getApplicationContext()); Log.i("Token", login.getArchivedToken()); AsyncHttpClient restRequest = new AsyncHttpClient(); PersistentCookieStore cookie = new PersistentCookieStore(getApplicationContext()); restRequest.setCookieStore(cookie); RequestParams params = new RequestParams(); params.put("auth_token", login.getArchivedToken()); params.put("user_id", data); Log.i("Request", "Preparing"); restRequest.get(Constantes.API_URL + "users/show.json", params, new AsyncHttpResponseHandler(){ public void onSuccess(String response) { Log.i("Reponse", response); try { User user = new User(new JSONObject(response)); Log.i("User", user.toString()); //Driver if (CurrentUserManager.getSharedManager().getCurrentUser().getType() == 1){ CurrentRouteManager.getSharedManager().getCurrentRoute().addPassanger(user); Intent resultIntent = new Intent(BumpActivity.this, DriverActivity.class); resultIntent.putExtra("PASSENGER_ADDED", true); setResult(1, resultIntent); finish(); } else{ Intent p = new Intent(BumpActivity.this, RoutePassenger.class); p.putExtra("driver", user); startActivity(p); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onFailure(Throwable e) { Log.i("Error", e.toString()); } }); } public void onStart() { Log.i("BumpTest", "onStart"); super.onStart(); } public void onRestart() { Log.i("BumpTest", "onRestart"); super.onRestart(); } public void onResume() { Log.i("BumpTest", "onResume"); super.onResume(); } public void onPause() { Log.i("BumpTest", "onPause"); try { api.disableBumping(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } super.onPause(); } public void onStop() { Log.i("BumpTest", "onStop"); try { api.disableBumping(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } super.onStop(); } public void onDestroy() { Log.i("BumpTest", "onDestroy"); try { api.disableBumping(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } unbindService(connection); unregisterReceiver(receiver); super.onDestroy(); } } A: I finally resolved it few days ago. As I'm not a JAVA expert I think the bug is located within the Bump library. If you do api.configure when it is already configured it simply crash. So I ended up making a singleton, ensuring that it is called only once Here is the code public class BumpConnection { protected Context context; private IBumpAPI api; private static BumpConnection sharedManager; public static synchronized BumpConnection getSharedManager(Context context) { if (sharedManager == null) { sharedManager = new BumpConnection(context); } return sharedManager; } private BumpConnection(Context context){ this.context = context; context.bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE); } public IBumpAPI getApi() { return api; } public void setApi(IBumpAPI api) { this.api = api; } private final ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder binder) { Log.i("BumpTest", "onServiceConnected"); api = IBumpAPI.Stub.asInterface(binder); new Thread() { public void run() { try { api.configure("9b17d663752843a1bfa4cc72d309339e", "Bump User"); } catch (RemoteException e) { Log.w("BumpTest", e); } } }.start(); Log.d("Bump Test", "Service connected"); } @Override public void onServiceDisconnected(ComponentName className) { Log.d("Bump Test", "Service disconnected"); } }; } A: Use Latest bump api , available at git hub, read the README.md file carefully. There is clearly mentioned that by using .aidl file (that is available in src folder) first compile it by using command android update project -t android-15 -l path_to/bump-api-library -p path_to_your_project/ in your terminal.. If you are a Linux user then set path up to platform-tools then use this command with ./adb . Then refresh the project , set this Library project as library in your test bump project.. Also replace your bumpapi key that you received via email
doc_23536267
@RequestMapping(value = "/checkInventory", consumes = "application/json", method = RequestMethod.POST) @ResponseBody public ResponseEntity<?> checkInventory ( // HEADERS @RequestBody CheckInventoryRequest checkInventoryRequest) throws Exception { // HEADERS LOGIC CheckInventoryResponse checkInventoryResponse = new CheckInventoryResponse(); JSON { "supplier": "foo", "supplierName": "ads", "supplierLocation": "123", "site": "goo", "product": [ { "lineItem": 1, "manufacturer": "TEST", "partNumber": "123", }, { "lineItem": 2, "manufacturer": "TEST 2", "partNumber": "3456", } ] } I am able to populate the POJO with the regular values, but how do I make another ArrayList using the product part? I need to do some database checking with the JSON but I can't figure out how to save the ArrayList. heckInventoryResponse import java.io.Serializable; public class CheckInventoryResponse implements Serializable { private String site; private String supplier; private String supplierLocation; private String supplierName; private String lineItem; private String manufacturer; private String partNumber; public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getSupplier() { return supplier; } public void setSupplier(String supplier) { this.supplier = supplier; } public String getSupplierLocation() { return supplierLocation; } public void setSupplierLocation(String supplierLocation) { this.supplierLocation = supplierLocation; } public String getSupplierName() { return supplierName; } public void setSupplierName(String supplierName) { this.supplierName = supplierName; } public String getLineItem() { return lineItem; } public void setLineItem(String lineItem) { this.lineItem = lineItem; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getPartNumber() { return partNumber; } public void setPartNumber(String partNumber) { this.partNumber = partNumber; } } This is my POJO class. It can be populated whenever my endpoint is being called, but I can't seem to figure out how to use the product part. A: You can create a class for Products which will have the details about the product. Try the below classes: class CheckInventoryRequest implements Serializable{ private String supplier; private String supplierName; private String supplierLocation; private String site; private List<Product> product; public CheckInventoryRequest() { } public String getSupplier() { return supplier; } public void setSupplier(String supplier) { this.supplier = supplier; } public String getSupplierName() { return supplierName; } public void setSupplierName(String supplierName) { this.supplierName = supplierName; } public String getSupplierLocation() { return supplierLocation; } public void setSupplierLocation(String supplierLocation) { this.supplierLocation = supplierLocation; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public List<Product> getProduct() { return product; } public void setProduct(List<Product> product) { this.product = product; } } class Product implements Serializable{ private Integer lineItem; private String manufacturer; private String partNumber; public Product() { } public Integer getLineItem() { return lineItem; } public void setLineItem(Integer lineItem) { this.lineItem = lineItem; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getPartNumber() { return partNumber; } public void setPartNumber(String partNumber) { this.partNumber = partNumber; } } Also, the json string is not valid it has extra ,. Valid json is { "supplier": "foo", "supplierName": "ads", "supplierLocation": "123", "site": "goo", "product": [ { "lineItem": 1, "manufacturer": "TEST", "partNumber": "123" }, { "lineItem": 2, "manufacturer": "TEST 2", "partNumber": "3456" } ] } A: Put the Product as a separate class then make an item in this class as List<Product> products = new ArrayList<Product>(); with getter and setter
doc_23536268
In it I have a view called Management, living in /Views/Home. I also have a controller called ManagementController.cs, and a method like this: public IActionResult Management() { return View("Views/Home/Management"); } In startup.cs, there is this code block: app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); However, I cannot seem to browse to this page (404). What am I missing? A: You are missing file suffix, change your action to: public IActionResult Management() { return View("Views/Home/Management.cshtml"); }
doc_23536269
arrays of arrays to collections of collections and vice versa in Java. I suppose there's no convenience methods in the Java API, right? public static <T> T[][] nestedCollectionsToNestedArrays( Collection<? extends Collection<T>> source){ // ... ? } public static <T> Collection<Collection<T>> nestedArraysToNestedCollections( T[][] source){ // ... ? } Additional question: What's with nested arrays of primitive types? Do I have to declare methods for each primitive type, because of forbidden generic array creation? A: for Collection of Collections -> array of arrays: (it just returns an Object[][], because the type information for "T" is not present. you have to manually pass in the class of T if you want the array to be the right type, and it will be more complicated) public static Object[][] nestedListsToNestedArrays( Collection<? extends Collection<?>> source){ Object[][] result = new Object[source.size()][]; int i = 0; for (Collection<?> subCollection : source) { result[i++] = subCollection.toArray(); } return result; } Additional question: What's with nested arrays of primitive types? Do I have to declare methods for each primitive type, Yes, you could either declare methods for each primitive type, or use reflection and sacrifice type safety. The reason is that each primitive array type is unrelated, and there is no supertype for all the primitive array types, except Object. because of forbidden generic array creation? No, but that's the reason for a different question: why the Collection of Collections -> array of arrays returning a T[][] is hard above. A: Here's the method for array->Collection: public static <T> Collection<Collection<T>> nestedArraysToNestedCollections(T[][] source) { Collection<Collection<T>> ret = new ArrayList<Collection<T>>(); for (int i = 0; i < source.length; i++) { // could be ret.add(new ArrayList<T>(Arrays.asList(source[i])); Collection<T> list = new ArrayList<T>(source[i].length); for (int j = 0; j < source[i].length; j++) { list.add(source[i][j]); } } return ret; } The other direction is much trickier.
doc_23536270
A: Yes, toolkits like GTK+ and Qt are still built on Xlib. Migration to xcb is in progress, but far from complete or universal. Applications though really should be writing to the toolkit API's, not Xlib. BTW, you can also find Xlib docs directly from the source at X.Org: http://www.x.org/releases/current/doc/ A: These days, libxcb is used. There is also an xlib compatibility layer still available (xlib-xcb). A: Well if you want hardware acceleration, according to freedesktop.org: an OpenGL application on the X Windows must use Xlib and thus can’t be done using only XCB. You have to have xlib even if you're only using xcb if you want opengl.
doc_23536271
` class ToDoList extends React.Component { constructor(props) { super(props); this.state = { userInput: this.props.value, items: [] }; } the error is in changeInput function changeInput(event) { this.setState({ userInput: event.target.value }); } addToList(event) { let arrayList = this.state.items; arrayList.push(event); this.setState({ items: arrayList, userInput: "" }); } render() { return ( <div style={styles}> <div class="to-do-list"> <h2>My To Do List</h2> <input type="text" value={this.state.userInput} onChange={this.changeInput} /> <button onClick={() => this.addToList(this.state.userInput)}> Add </button> <ul>{this.state.items.map(event => <li>{event}</li>)}</ul> </div> </div> ); } } ReactDOM.render(<ToDoList />, document.getElementById("root"));`
doc_23536272
When I grab the xml like this it's escaped ie. &lt; = < <content name="test”> <xsl:copy-of select="//content[@name='something']/node()" /> </content> But I need to do some processing on the data before I store it in a content node. I have an xsl:for-each call and it loops saving sections. However, when I call a similar command I can't get the XML to escape. <xsl:for-each select="exsl:node-set($xml)//data"> <content name="test"> <xsl:copy-of select="./node()" /> </content> I've put CDATA nodes around it and outputted the content, but then I have issues in the system with double escaping. I really need this copy-of call to output escaped XML. I really want something like: <content name="test"> &lt;data&gt;Some data&lt;\data&gt; </content> Input would be something like this: <root> <data>Some data</data> <data>more data</data> </root> This a simplification of the data. There would be additional xml nodes in the data node. A: Evan Lenz has an XSLT 1 based implementation of XML serialization at http://lenzconsulting.com/xml-to-string/: if you use that you have e.g. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:import href="http://lenzconsulting.com/xml-to-string/xml-to-string.xsl"/> <xsl:output indent="yes" cdata-section-elements="content"/> <xsl:template match="/"> <xsl:apply-templates/> </xsl:template> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <xsl:template match="data"> <content> <xsl:apply-templates select="." mode="xml-to-string"/> </content> </xsl:template> </xsl:stylesheet> https://xsltfiddle.liberty-development.net/pPzifpn/4 If the processor is libxslt then it might allow you to implement an extension function, for instance PHP allows you to call PHP functions and the DOMDocument in PHP has a saveXML function to serialize, so you can call that from XSLT: <?php function serializeNode($node) { return $node[0]->ownerDocument->saveXML($node[0]); } $xml = <<<EOT <root> <data>Some data</data> <data>more data</data> </root> EOT; $xsl = <<<EOT <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" exclude-result-prefixes="php" version="1.0"> <xsl:output indent="yes" cdata-section-elements="content"/> <xsl:template match="/"> <xsl:apply-templates/> </xsl:template> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <xsl:template match="data"> <content> <xsl:value-of select="php:function('serializeNode', .)"/> </content> </xsl:template> </xsl:stylesheet> EOT; $doc = new DOMDocument(); $doc->loadXML($xml); $proc = new XSLTProcessor(); $proc->registerPHPFunctions('serializeNode'); $sheet = new DOMDocument(); $sheet->loadXML($xsl); $proc->importStylesheet($sheet); echo $proc->transformToXml($doc); ?> A: <!-- XSL 1.0 --> <xsl:template match="*|@*|text()|comment()" mode="copy"> <xsl:param name="_-"><!--<">-do-not-modify-this--></xsl:param> <xsl:variable name="ch" select="document('')//*[@name='_-']/comment()"/> <xsl:variable name="lt" select="substring($ch, 1, 1)"/> <xsl:variable name="qq" select="substring($ch, 2, 1)"/> <xsl:variable name="gt" select="substring($ch, 3, 1)"/> <xsl:choose> <xsl:when test="self::*"> <xsl:value-of select="concat($lt, name())"/> <xsl:apply-templates select="@*" mode="copy"/> <xsl:variable name="ns" select="namespace-uri()"/> <xsl:if test="$ns and not(ancestor::*[namespace-uri() = $ns])"> <xsl:variable name="pf" select="substring-before(name(), ':')"/> <xsl:value-of select="concat(' xmlns:', $pf, '=', $qq, $ns, $qq)"/> </xsl:if> <xsl:value-of select="$gt"/> <xsl:apply-templates select="*|text()|comment()" mode="copy"/> <xsl:value-of select="concat($lt, '/', name(), $gt)"/> </xsl:when> <xsl:when test="self::comment()"> <xsl:value-of select="concat($lt, '!--', ., '--', $gt)"/> </xsl:when> <xsl:when test="self::text()"><xsl:value-of select="."/></xsl:when> <xsl:otherwise> <xsl:value-of select="concat(' ', name(), '=', $qq, ., $qq)"/> </xsl:otherwise> </xsl:choose> </xsl:template>
doc_23536273
class C{ public: //Omitted private: shared_ptr<X> anArray[2]; }; and X looks like: class X{ public: X(); //default constructor used by the above array declaration? private: std::unordered_map<int, double> a; }; After I create my C class, I access one of the two shared_ptr objects in the array, however, the memory doesn't seem to be initialised. By this I mean X::a doesn't have any valid state. I thought the array declaration in C would create the shared_ptr<X>s AND the X objects? Is there something I should be explicitly doing in the X default constructor? A: The default constructor for std::shared_ptr<X> absolutely does not create a new instance of X. It does this to allow for creating an 'empty pointer', the smart pointer equivalent of NULL, so that a default constructed smart pointer is analogous to a 'default constructed' raw pointer. To get what you want, you simply need to initialize the anArray instance in the constructor's initialization list, like so: class C: { public: C() : anArray({std::shared_ptr<X>(new X()), std::shared_ptr<X>(new X())}) // ... { // rest of constructor } private: std::shared_ptr<X> anArray[2]; }; Alternatively you can use std::make_shared<X>() in the initialization list instead of std::shared_ptr<X>(new X()) as it's a bit more efficient and slightly safer with respect to exceptions causing memory leaks. I left the 'raw' form in so it was more explicit as to what was happening.
doc_23536274
<div id="box" name="1" margin="4px" padding="4px" onclick="memory(1)"></div> With the associated memory() function being: function memory(a) { var tmpDar = a-1; var m = document.getElementsByName(tmpDar); m.innerHTML = arrA[tmpDar]; } However, when I try executing the code, the HTML doesn't alter... Can somebody please help me? A: document.getElementsByName() returns a NodeList and not a single element! So in order to set the innerHTML of your div, you have to reference an entry inside that array, e.g., like this: function memory(a) { var tmpDar = a-1; var m = document.getElementsByName(tmpDar); m[0].innerHTML = arrA[tmpDar]; } In your code you set the innerHTML property for the NodeList object, which has no (visual) effect in the document. In general it would be better to use id instead of name. Then you could use document.getElementById() in a way like this: function memory(a) { var tmpDar = a-1; var m = document.getElementById(tmpDar); m.innerHTML = arrA[tmpDar]; } A: your trying to find all elements with a name of 0 as far as I can tell. And there is no 0 name. Also what the other two said, it returns an array you need to call an index on that array. A: document.getElementsByName returns an array. So if the element that you want is unique with this name, you should replace your code by : function memory(a) { var tmpDar = a-1; var m = document.getElementsByName(tmpDar); m[0].innerHTML = arrA[tmpDar]; // Here I have added index 0 }
doc_23536275
For example I can't use the | operator, neither the serializer (just like here), but I can use to_json which I could not find in the documentation... This is what I obtain when I type dir(anyQuerySet) in a django console: ['_QuerySet__dereference', '__call__', '__class__', '__deepcopy__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_as_pymongo', '_as_pymongo_coerce', '_auto_dereference', '_class_check', '_collection', '_collection_obj', '_cursor', '_cursor_args', '_cursor_obj', '_dereference', '_document', '_ensure_indexes', '_fields_to_dbfields', '_get_as_pymongo', '_get_order_by', '_get_scalar', '_hint', '_initial_query', '_item_frequencies_exec_js', '_item_frequencies_map_reduce', '_iter', '_limit', '_loaded_fields', '_mongo_query', '_none', '_ordering', '_query', '_query_obj', '_read_preference', '_scalar', '_skip', '_slave_okay', '_slice', '_snapshot', '_sub_js_fields', '_timeout', '_where_clause', 'all', 'all_fields', 'as_pymongo', 'average', 'clone', 'count', 'create', 'delete', 'distinct', 'ensure_index', 'exclude', 'exec_js', 'explain', 'fields', 'filter', 'first', 'from_json', 'get', 'get_or_create', 'hint', 'in_bulk', 'insert', 'item_frequencies', 'limit', 'map_reduce', 'next', 'no_dereference', 'none', 'only', 'order_by', 'read_preference', 'rewind', 'scalar', 'select_related', 'skip', 'slave_okay', 'snapshot', 'sum', 'timeout', 'to_json', 'update', 'update_one', 'values_list', 'where', 'with_id'] A: You appear to be using MongoDb rather than a traditional relational database. So, you must also be using a third party library to query that db from Django. You shouldn't therefore be surprised that your querysets differ from the standard Django ones.
doc_23536276
A: because I'm bored... public static int getOneDigitNumberCount(final int[] numbers) { if (numbers == null || numbers.length == 0) { return 0; } int count = 0; for (int number : numbers) { // assumes you're not considering negative numbers if (number >= 0 && number <= 9) { count++; } } return count; } A: And another solution that uses streams and also considers negative one digit numbers. int[] nums = {1,22,3,4,-8, -9, -45, 55,66,5}; long count = Arrays.stream(nums) .filter(n -> n > -10 && n < 10) .count(); System.out.println(count); // prints 6
doc_23536277
I want to scrape a real estate website and get the Title, price, sqm, and what not into a CSV file. My questions: * *It seems to work for the first page of results but then it repeats and it does not run through the 40 pages. It rather fills the file with the same results. *The listings have info about "square meter" and the "number of rooms". When I inspect the page it seems though that it uses the same class for both elements. How would I extract the room numbers for example? Here is the code that I have gathered so far: import requests from bs4 import BeautifulSoup import pandas as pd def extract(page): headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36'} url = f'https://www.immonet.de/immobiliensuche/sel.do?suchart=2&city=109447&marketingtype=1&pageoffset=1&radius=0&parentcat=2&sortby=0&listsize=26&objecttype=1&page={1}' r = requests.get(url, headers) soup = BeautifulSoup(r.content, 'html.parser') return soup def transform(soup): divs = soup.find_all('div', class_ = 'col-xs-12 place-over-understitial sel-bg-gray-lighter') for item in divs: title = item.find('div', {'class': 'text-225'}).text.strip().replace('\n', '') title2 = title.replace('\t', '') hausart = item.find('span', class_ = 'text-100').text.strip().replace('\n', '') hausart2 = hausart.replace('\t', '') try: price = item.find('span', class_ = 'text-250 text-strong text-nowrap').text.strip() except: price = 'Auf Anfrage' wohnflaeche = item.find('p', class_ = 'text-250 text-strong text-nowrap').text.strip().replace('m²', '') angebot = { 'title': title2, 'hausart': hausart2, 'price': price } hauslist.append(angebot) return hauslist=[] for i in range(0, 40): print(f'Getting page {i}...') c = extract(i) transform(c) df = pd.DataFrame(hauslist) print(df.head()) df.to_csv('immonetHamburg.csv') This is my first post on stackoverflow so please be kind if I should have posted my problem differently. Thanks Pat A: You have stupid mistake. In url you have to use {page} instead of {1}. That's all. url = f'https://www.immonet.de/immobiliensuche/sel.do?suchart=2&city=109447&marketingtype=1&pageoffset=1&radius=0&parentcat=2&sortby=0&listsize=26&objecttype=1&page={page}' I see other problem: You start scraping at page 0 but servers often give the same result for page 0 and 1. You should use range(1, ...) instead of range(0, ...) As for searching elements. Beautifulsoup may search not only classes but also id and any other value in tag - ie. name, style, data, etc. It can also search by text "number of rooms". It can also use regex for this. You can also assign own function which will check element and return True/False to decide if it has to keep it in results. You can also combine .find() with another .find() or .find_all(). price = item.find('div', {"id": lambda value:value and value.startswith('selPrice')}).find('span') if price: print("price:", price.text) And if you know that "square meter" is before "number of rooms" then you could use find_all() to get both of them and later use [0] to get first of them and [1] to get second of them. You should read all documentation beacause it can be very useful. A: I advice you use Selenium instead, because you can physically click the 'next-page' button until you cover all pages and the whole code will only take a few lines. A: As @furas mentioned you have a mistake with the page. To get all rooms you need to find_all and get the last index with -1. Because sometimes there are 3 items or 2. #to remote all \n and \r translator = str.maketrans({chr(10): '', chr(9): ''}) rooms = item.find_all('p', {'class': 'text-250'}) if rooms: rooms = rooms[-1].text.translate(translator).strip()
doc_23536278
Widget _builder(Article article){ return new Padding( padding: const EdgeInsets.all(8.0), child: ListTile( title: new Text(article.text,style: TextStyle( fontSize: 24.0, ), ), subtitle: new Text(article.by), onTap: () async { final fakeUrl='www.${article.domain}'; if (await canLaunch(fakeUrl)){ launch(fakeUrl); } else print("could not be opened"); ), ); } Here's my error: E/flutter (18223): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method canLaunch on channel plugins.flutter.io/url_launcher) E/flutter (18223): #0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:319:7) E/flutter (18223): <asynchronous suspension> E/flutter (18223): #1 MethodChannelUrlLauncher.canLaunch (package:url_launcher_platform_interface/method_channel_url_launcher.dart:18:21) E/flutter (18223): #2 canLaunch (package:url_launcher/url_launcher.dart:108:45) E/flutter (18223): #3 _MyHomePageState._builder.<anonymous closure> (package:flutter_apps/main.dart:62:23) E/flutter (18223): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14) E/flutter (18223): #5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36) E/flutter (18223): #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24) E/flutter (18223): #7 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11) E/flutter (18223): #8 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5) E/flutter (18223): #9 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7) E/flutter (18223): #10 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27) E/flutter (18223): #11 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20) E/flutter (18223): #12 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22) E/flutter (18223): #13 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) E/flutter (18223): #14 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7) E/flutter (18223): #15 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7) E/flutter (18223): #16 _rootRunUnary (dart:async/zone.dart:1138:13) E/flutter (18223): #17 _CustomZone.runUnary (dart:async/zone.dart:1031:19) E/flutter (18223): #18 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7) E/flutter (18223): #19 _invoke1 (dart:ui/hooks.dart:273:10) E/flutter (18223): #20 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5) A: You should clean your project by Flutter clean. If still remains You should upgrade your flutter repo by Flutter upgrade and the issue will be resolved for sure.You can track this issue here.
doc_23536279
A: All IMAP servers today run the same version, 4rev1. Versions 1, 2, 3 and 4 are long gone. Further, all servers today support one or more extensions. The CAPABILITY command returns the list of extensions. For gmail: openssl s_client -connect imap.gmail.com:993 -crlf a capability * CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIENTTOKEN a OK Thats all she wrote! j14mb28178795bkd So gmail supports IDLE and about a dozen more extensions. A: IMAP uses the CAPABILITY command to request information about the server capabilities. This is more useful than a version number as it allows a client to check for the specific extensions to the IMAP basic protocol that it might require.
doc_23536280
Linked Image In other browsers the Print Preview window works as expected. Are any extra headers for Edge, in order to resolve this? If not, what is likely to be the solution?
doc_23536281
<div id="main"> <h1>Create Leave</h1> <form class="form-horizontal" > <div class="form-group"> <label for="employeeName" class="col-sm-3 control-label">Employee Name</label> <div class="col-sm-6"> <input type="text" id="num" class="form-control" ng-model="num" /> </div> <div class="col-sm-3"></div> </div> <div class="form-group"> <label for="leaveType" class="col-sm-3 control-label">Leave Type</label> <div class="col-sm-2"> <select id="leaveType" class="form-control" ng-model="leaveType"> <option value="hospital">Hospital</option> <option value="l1">leave type 2</option> <option value="l2">leave type 3</option> <option value="l3">leave type 4</option> <option value="l4">leave type 5</option> <option value="l5">leave type 6</option> </select> </div> <div class="col-sm-7"></div> </div> <div class="form-group"> <label for="leaveStartDate" class="col-sm-3 control-label">Leave Start Date</label> <div class="col-sm-2"> <input type="date" id="startDate" class="form-control" ng-model="startDate" /> </div> <div class="col-sm-7"></div> </div> <div class="form-group"> <label for="leaveEndDate" class="col-sm-3 control-label">Leave End Date</label> <div class="col-sm-2"> <input type="date" id="endDate" class="form-control" ng-model="endDate" /> </div> <div class="col-sm-7"></div> </div> <div class="form-group"> <div class="col-sm-3"></div> <div class="col-sm-2"> <span><b>Is Half Day leave</b></span> <div class="radio"> <label><input value="Yes" type="radio" name="halfDay" ng-model="isHalfDay" />Yes</label> </div> <div class="radio"> <label><input value="No" type="radio" name="halfDay" ng-model="isHalfDay" />No</label> </div> </div> </div> <button ng-click="add()" class="btn btn-primary">Submit</button> <button ng-click="resetForm()" class="btn">Reset</button> </form> and this is the controller app.controller("MyAddController", function($scope, $http) { //$scope.test = {}; $scope.add = function() { // console.log("------------>"+JSON.stringify($scope.test)); $http.post("webapi/blog/create", { params: { signum: $scope.num, leaveType: $scope.leaveType, startDate: $scope.startDate, endDate: $scope.endDate, isHalfDay: $scope.isHalfDay } }).success(function(data, status, headers, config) { if (data) { $scope.data = data; alert("success"); } }).error(function(data, status, headers, config) { alert("error"); }) } }); and the jersey code @POST @Path("create") @Produces({ "application/json" }) public String create(@BeanParam LeaveDetails ld) { System.out.println("Entered here"); System.out.println(ld.getIsHalfDay()); System.out.println(ld.getNum()); System.out.println(ld.getEndDate()); System.out.println(ld.getStartdate()); System.out.println(ld.getLeaveType()); new AddLeaveDao().addDetails(ld); System.out.println("Returned here"); return "{}"; } Please help
doc_23536282
$('#textb').keypress(function (e) { var key = e.which; var messag=document.getElementById('textb').value; if(key == 13) { window.location.href = "refresh/?mesag=" + messag; } }); }); how to pass variable to controller from view in codeigniter A: View: if(key == 13){ $.post( "route/to/post/to", { id: "2"} ); } Controller: if($this->input->post("id")){ echo $this->input->post("id"); } This will echo 2
doc_23536283
How can I define the variable just once and have access to the variables from all the three methods? Those are the methods: def pendientes end def proceso end def finalizadas end Those are the three variables: @pendientes = Support.where("estado = ?", 1) @procesos = Support.where("estado = ?", 2) @finalizadas = Support.where("estado = ?", 3) How do I need to define the variables to do it? A: If you're working in the context of a controller, you could do something like this: class MyController < ApplicationController before_filter :initialize_variables def pendientes end def proceso end def finalizadas end private def initialize_variables @pendientes = Support.where(estado: 1) @procesos = Support.where(estado: 2) @finalizadas = Support.where(estado: 3) end end Update: If you roll with a before_filter, it may be a good idea to add only: [:pendientes, :proceso, :finalizadas] so that future actions added to the controller don't initialize the three variables. Another option would be to delete the before_filter call and just invoke the initialize_variables method from each of the three existing actions.
doc_23536284
<div class="row"> <input type="number" class="form-control" class="slider-start" data-id="1"> <input type="number" class="form-control" class="slider-end" data-id="1"> </div> this is a fiddle A: Try adding inline-flex inside your style. <div class="row" style="display: inline-flex;"> <input type="number" class="form-control" class="slider-start" data-id="1"> <input type="number" class="form-control" class="slider-end" data-id="1"> </div> A: Flexbox should help you. .form-control{ width: 35%; /*size of input box*/ flex-flow: row nowrap; /*sets flex-box elements order*/ } .row { display: flex; } I hope that I helped. A: Do you mean something like this? <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <div class="row"> <div class="col-auto"> <input type="number" class="form-control" class="slider-start" data-id="1"> </div> <div class="col-auto"> <input type="number" class="form-control" class="slider-end" data-id="1"> </div> </div>
doc_23536285
i have a user Model and Intership Model. each user has one Intership and each Intership has many users. so , relationship is one to many . i create this relation but i cant fetch data. i want to show intership information of a user. MY USER MODEL : <?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable { use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'last_name', 'email', 'role', 'phone', 'user_code', 'born_date', 'national_code', 'password', ]; protected $primaryKey = 'user_code'; protected $table = 'users'; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public function intership() { return $this->belongsTo(Intership::class,'intership_code','intership_code'); } } MY INTERSHIP MODEL : <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Intership extends Model { use HasFactory; protected $table = 'interships'; protected $primaryKey = 'intership_code'; protected $fillable = [ 'teacher_code', 'user_code', 'school_code', 'work_code', 'intership_term_code', 'intership_code', 'class_code', 'start', 'end', ]; public function users() { $this->hasMany(User::class,'user_code','user_code'); } } MY CONTROLLER : public function index() { $user = User::where('user_code',32132)->first(); $interships = $user->intership; return $interships; } Notes : 1- i dont have "id" field in my tables so instead of "id" i have user_code for users and intership_code for interships that are foreignkey 2- user with user_code => 32132 already exists. 3- i want to show a user intership information A: Ok so first things first, since you use your User model the relationship that you want to build is in the User model, the one in Internship model is irrelevant (at least for this question). public function intership() { return $this->belongsTo(Intership::class,'user_code','user_code'); } Your foreign key in your Internships table that connects it with the Users table is the user_code which links to the user_code of the user in Users table.
doc_23536286
I have tried to initialise the PDFView class and set a document url. But when I try pdfView.document!.pageCount, I cannot access the int because pdfView.document is nil pdfView = PDFView() pdfView.document = PDFDocument(url: url) pageCount = pdfView.document!.pageCount // crashes here every time I would expect pageCount to hold the value of the total number of pages in the document. Instead the app crashes due to unexpected unwrapping of nil optional. A: Unexpected wrapping of nil optional means that the PDF document doesn't exist. You need to either check the URL or the location of the PDF document. I suggest you don't use force unwrap ('!') unless necessary. Use '??' instead and give a default value.
doc_23536287
# cat letter.txt this is just a test to check if grep works The letter "e" appear in 3 words. # grep e letter.txt test check grep Is there any way to return the letter printed on left of the selected character? expected.txt t h r A: With shown samples in awk, could you please try following. awk '/e/{print substr($0,index($0,"e")-1,1)}' Input_file Explanation: Adding detailed explanation for above. awk ' ##Starting awk program from here. /e/{ ##Looking if current line has e in it then do following. print substr($0,index($0,"e")-1,1) ##Printing sub string from starting value of index e-1 and print 1 character from there. } ' Input_file ##Mentioning Input_file name here. A: You can use positive lookahead to match a character that is followed by an e, without making the e part of the match. cat letter.txt | grep -oP '.(?=e)' A: With sed: sed -nE 's/.*(.)e.*/\1/p' letter.txt A: Assuming you have this input file: cat file this is just a test to check if grep works egg element You may use this grep + sed solution to find letter or empty string before e: grep -oE '(^|.)e' file | sed 's/.$//' t h r l m Or alternatively this single awk command should also work: awk -F 'e' 'NF > 1 { for (i=1; i<NF; i++) print substr($i, length($i), 1) }' file A: With GNU awk you can use empty string as FS to split the input as individual characters: awk -v FS= '/[e]/ {for(i=2;i<=NF;i++) if ($i=="e") print $(i-1)}' file t h r Excluding "e" at the beginning in the for loop. * *edited empty string if e is the first character in the word. * *For example, this input: cat file2 grep erroneously egg Wednesday effectively awk -v FS= '/^[e]/ {print ""} /[e]/ {for(i=2;i<=NF;i++) if ($i=="e") print $(i-1)}' file2 r n W n f v A: This might work for you (GNU sed): sed -nE '/(.)e/{s//\n\1\n/;s/^[^\n]*\n//;P;D}' file Turn off implicit printing and enable extended regexp -nE. Focus only on lines that meet the requirements i.e. contain a character before e. Surround the required character by newlines. Remove any characters before and including the first newline. Print the first line (up to the second newline). Delete the first line (including the newline). Repeat. N.B. The solution will print each such character on a separate line. To print all such characters on their own line, use: sed -nE '/(.e)/{s//\n\1/g;s/^/e/;s/e[^\n]*\n?//g;s/\B/ /g;p}' file N.B. Remove the s/\B /g if space separation is not needed.
doc_23536288
def post(self, request): cliente1 = Cliente.objects.get(cpf=request.data['cliente1_cpf_transf']) cliente2 = Cliente.objects.get(cpf=request.data['cliente2_cpf_transf']) notificacao1 = Notificacao.objects.all() if cliente1.saldo >= request.data['quantia']: cliente1.saldo -= request.data['quantia'] cliente1.save() cliente2.saldo += request.data['quantia'] cliente2.save() notificacao1.cpf_remetente = request.data['cliente1_cpf_transf'] notificacao1.cpf_destinatario = request.data['cliente2_cpf_transf'] notificacao1.valor = request.data['quantia'] notificacao1.save() A: QuerySet is kinda like a list, and you cannot save all objects in list just like that. You are probably in need to make notificacao1 as new Notificacao object. You need to create it like this: notificacao1 = Notificacao.objects.create(cpf_remetente=cliente1, cpf_destinatario=cliente2, valor=request.data['quantia']) Whole suggested code: def post(self, request): cliente1 = Cliente.objects.get(cpf=request.data['cliente1_cpf_transf']) cliente2 = Cliente.objects.get(cpf=request.data['cliente2_cpf_transf']) valor = request.data['quantia'] if cliente1.saldo >= valor : cliente1.saldo -= valor cliente1.save() cliente2.saldo += valor cliente2.save() Notificacao.objects.create(cpf_remetente=cliente1, cpf_destinatario=cliente2, valor=valor) Because this is calling all objects of model Notificacao: all_objects_of_notificacao = Notificacao.objects.all()
doc_23536289
My primary Question is: Why does the Export deployable plug-ins and fragments generate a jar with no .class files ? In my project we use load time weaving, and after successful export of the Project, weaving is not applied. The reason is because my exported aspectj plugins have no .class files. After much research the way how to do a aspectj aware Export is to define the AspectJ Compiler Adapter. It seems this Compiler is loaded and executed, but as result there are no .class files. Someone has an idea whats missing ? build.properties: compilerAdapter=org.eclipse.ajdt.core.ant.AJDT_AjcCompilerAdapter sourceFileExtensions=*.java, *.aj source.. = src/ output.. = bin/ bin.includes = META-INF/,\ . Edit: If I rightklick on the Project an if I press "Generate Ant File" it generates sth like this in the @dot target: <javac destdir="${build.result.folder}/@dot" failonerror="${javacFailOnError}" verbose="${javacVerbose}" debug="${javacDebugInfo}" includeAntRuntime="no" bootclasspath="${bundleBootClasspath}" source="${bundleJavacSource}" target="${bundleJavacTarget}" compiler="org.eclipse.ajdt.core.ant.AJDT_AjcCompilerAdapter" > <compilerarg line="${compilerArg}" compiler="${build.compiler}"/> <classpath refid="@dot.classpath" /> <src path="src/" /> <exclude name="META-INF/MANIFEST.MF ." /> <compilerarg value="@${basedir}/javaCompiler...args" compiler="org.eclipse.ajdt.core.ant.AJDT_AjcCompilerAdapter" /> <compilerarg line="-log &apos;${build.result.folder}/@dot${logExtension}&apos;" compiler="org.eclipse.ajdt.core.ant.AJDT_AjcCompilerAdapter" /> </javac> I would say this looks correct, AJDT Compiler is set. If "compilerAdapter=org.eclipse.ajdt.core.ant.AJDT_AjcCompilerAdapter" isnot set in the Properties File at this point there would be the eclipse compiler instead. After running this generated buildskript (i think "Export deployable Plugin..." will do the same) the only javac output i have got is: test\TestAspect.aj skipped - don't know how to handle it A: I found a solution to this problem. It seems the AspectJ Compiler isnt started. After putting a Dummy.java File in src/ the AspectJ Compiler tries to compile all *.aj Files. Without Dummy.java it does not! After this step I saw more javac loging. And I saw the jre/lib..*.jars where missing in the classpath of the target. So I added into the build.properties File: compilerArg=-aspectpath ${bootclasspath} bootclasspath is a variable in the generated build script that contains all this standard java jars. This strange behavior took me a lot of time, hope someone will benefit from this.
doc_23536290
Table: | Item | -------- | milk | | sugar| | salt | | .... | Query result: | Item List | --------------------------- | milk, sugar, salt ..... | It would be better to have some customization as | Item List | ---------------------------------------------------- | milk as milk, sugar as sugar, salt as salt ..... | I saw there is option as unpivot however it has to be definitive amount of values in the column. Just wondering any available functions to support this goal if target column value is dynamic A: Consider you want to populate: declare @csv nvarchar(max); If you have sql server 2016 or earlier: set @csv = stuff(( select ',' + item + ' as ' + item from @data for xml path('') ),1,1,''); If you have sql server 2017 or later: set @csv = ( select string_agg (item + ' as ' + item, ',') from @data );
doc_23536291
A: To push your changes onto a separate branch, you simply need to create a new branch at your current commit. You can then reset your local master to origin/master to remove those commits from your master branch. git branch my-branch git reset --hard origin/master Now when you push the branches, the commits will be on the desired branches. As for the second question, you can specify which branch you want to pull so that only that branch gets pulled. git pull origin master
doc_23536292
/opt/homebrew/Cellar/apache-spark/3.3.1/libexec and /opt/homebrew/Cellar/openjdk/19.0.1 locations respectively. My .zprofile is as follows export JAVA_HOME=/opt/homebrew/Cellar/openjdk/19.0.1 <br/> export SPARK_HOME=/opt/homebrew/Cellar/apache-spark/3.3.1/libexec <br/> export ZEPPELIN_HOME=~/Desktop/zeppelin-0.10.1 <br/> export PATH=$JAVA_HOME/bin:$SPARK_HOME/bin:$ZEPPELIN_HOME/bin:$PATH <br/> export PATH="$PATH:/Users/kanner/Library/Application Support/JetBrains/Toolbox/scripts" I have added JAVA_HOME and SPARK_HOME to zeppelin config file. What I get in the terminal when I start zeppelin Error message I find in logs after starting zeppelin ZEPPELIN_CLASSPATH: :/Users/kanner/Desktop/zeppelin-0.10.1/*::/Users/kanner/Desktop/zeppelin-0.10.1/conf Error: Could not find or load main class org.apache.zeppelin.server.ZeppelinServer Caused by: java.lang.ClassNotFoundException: org.apache.zeppelin.server.ZeppelinServer What am I doing wrong? I have tried various solutions to similar question on here including sudo bin/zeppelin-daemon.sh start A: This means that the org.apache.zeppelin.server.ZeppelinServer class is not present anywhere on your classpath. This class comes from the zeppelin-server-0.10.1.jar file, which I expect should be on your computer somewhere because it seems like you've installed it. Try to find where that file lives. If you can't find it, you can download it from Maven Repository but I would suggest reinstalling Zeppelin from scratch if you can't find it because other things might have gone wrong. Once you know where that file lives, you must make sure that the directory it lives in is also in that ZEPPELIN_CLASSPATH variable you showed us. Right now its value is: ZEPPELIN_CLASSPATH: :/Users/kanner/Desktop/zeppelin-0.10.1/*::/Users/kanner/Desktop/zeppelin-0.10.1/conf I expect the solution will be something simple like correcting the value of one of your environment variables, to make sure that the directory with that jar inside of it also shows up in the ZEPPELIN_CLASSPATH variable. Hope this helps!
doc_23536293
df <- data.frame(v1 = rnorm(10), col = rbinom(10, size=1,prob= 0.5)) rownames(df) <- letters[1:10] > head(df) v1 col a -0.1806868 1 b 0.6934783 0 c -0.4658297 1 d 1.6760829 0 e -0.8475840 0 f -1.3499387 1 I plot it like this: ggplot(df, aes(x = v1, y=rownames(df), group = col, color= col)) + geom_point() Now I want to show only the rownames on the y-axis where col == 1. The other names should not be displayed (but the points should be) To add some context, I have a plot with many overlapping variable names on the y-axis, but I only want to display the names of the ones outside the dashed line A: You could use scale_y_discrete: set.seed(2017); df <- data.frame(v1 = rnorm(10), col = rbinom(10, size=1,prob= 0.5)) rownames(df) <- letters[1:10] library(ggplot2); ggplot(df, aes(x = v1, y = rownames(df), group = col, color = col)) + geom_point() + scale_y_discrete( limits = rownames(df), labels = ifelse(df$col == 1, rownames(df), "")) A: There is not much to add to the answer given by @MauritsEvers, I just had the idea that for your plot it might be desirable to have fewer horizontal lines that guide your eye. We can use the breaks argument in scale_y_discrete for that. set.seed(1); df <- data.frame(v1 = rnorm(10), col = rbinom(10, size=1,prob= 0.5)) rownames(df) <- letters[1:10] axis_labels <- which(df$col == 1) ggplot(df, aes(x = v1, y=rownames(df), group = col, color= col)) + geom_point() + scale_y_discrete(breaks = rownames(df)[axis_labels])
doc_23536294
Naively, it would look like this: #[macro_use] extern crate lazy_static; extern crate evmap; use std::collections::hash_map::RandomState; lazy_static! { static ref MAP: (evmap::ReadHandle<u32, u32, (), RandomState>, evmap::WriteHandle<u32, u32, (), RandomState>) = evmap::new(); } fn main() { println!("Hello, world!"); MAP.1.clear(); } This gives: error[E0277]: the trait bound `std::cell::Cell<()>: std::marker::Sync` is not satisfied in `(evmap::ReadHandle<u32, u32>, evmap::WriteHandle<u32, u32>)` --> src/main.rs:8:1 | 8 | / lazy_static! { 9 | | static ref MAP: (evmap::ReadHandle<u32, u32, (), RandomState>, 10 | | evmap::WriteHandle<u32, u32, (), RandomState>) = evmap::new(); 11 | | } | |_^ `std::cell::Cell<()>` cannot be shared between threads safely | = help: within `(evmap::ReadHandle<u32, u32>, evmap::WriteHandle<u32, u32>)`, the trait `std::marker::Sync` is not implemented for `std::cell::Cell<()>` = note: required because it appears within the type `std::marker::PhantomData<std::cell::Cell<()>>` = note: required because it appears within the type `evmap::ReadHandle<u32, u32>` = note: required because it appears within the type `(evmap::ReadHandle<u32, u32>, evmap::WriteHandle<u32, u32>)` = note: required by `lazy_static::lazy::Lazy` = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) I think this is complaining about the () returned inside evmap::new(): pub fn new<K, V>( ) -> (ReadHandle<K, V, (), RandomState>, WriteHandle<K, V, (), RandomState>) where K: Eq + Hash + Clone, V: Eq + ShallowCopy, Can it be done? A: Can [placing a ReadHandle / WriteHandle directly in a lazy static variable] be done? No. As the error message states: std::cell::Cell<()> cannot be shared between threads safely You are attempting to place a type that will fail when used in a multithreaded context in a static variable, which must be thread-safe. Can [placing a ReadHandle / WriteHandle in a lazy static variable at all] be done? Yes, but you have to use something to synchronize access, such as a Mutex or RwLock: #[macro_use] extern crate lazy_static; extern crate evmap; use std::collections::hash_map::RandomState; use std::sync::Mutex; type ReadHandle = evmap::ReadHandle<u32, u32, (), RandomState>; type WriteHandle = evmap::WriteHandle<u32, u32, (), RandomState>; lazy_static! { static ref MAP: (Mutex<ReadHandle>, Mutex<WriteHandle>) = { let (r, w) = evmap::new(); (Mutex::new(r), Mutex::new(w)) }; } fn main() { MAP.1.lock().unwrap().clear(1); } See also: * *How do I create a global, mutable singleton? *How can I guarantee that a type that doesn't implement Sync can actually be safely shared between threads?
doc_23536295
Kh-H0f2ZNYcxWYQtJvA-4jQ2rnm8WQSsVsNFkVRMYxpg-1417365081517,38606,"Best Buy Co, Inc.",BBY01-694284011841 expected ans is Kh-H0f2ZNYcxWYQtJvA-4jQ2rnm8WQSsVsNFkVRMYxpg-1417365081517 "Best Buy Co, Inc." BBY01-694284011841 but i'm getting Kh-H0f2ZNYcxWYQtJvA-4jQ2rnm8WQSsVsNFkVRMYxpg-1417365081517 "Best Buy Co Inc." BBY01-694284011841 i used split String s="..."; String s[]=s.split(","); A: You can use a negative lookahead for whitespace to avoid splitting Best By Co and Inc.: System.out.println( Arrays.toString( "Kh-H0f2ZNYcxWYQtJvA-4jQ2rnm8WQSsVsNFkVRMYxpg-1417365081517,38606,\"Best Buy Co, Inc.\",BBY01-694284011841" .split(",(?!\\s)") ) ); Output [Kh-H0f2ZNYcxWYQtJvA-4jQ2rnm8WQSsVsNFkVRMYxpg-1417365081517, 38606, "Best Buy Co, Inc.", BBY01-694284011841]
doc_23536296
https://docs.aws.amazon.com/eks/latest/userguide/eks-ug.pdf To create your Amazon EKS service role 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. Choose Roles, then Create role. 3. Choose EKS from the list of services, then Allows Amazon EKS to manage your clusters on your behalf for your use case, then Next: Permissions. 4. Choose Next: Review. 5. For Role name, enter a unique name for your role, such as eksServiceRole, then choose Create role. When I create a basic hello world app, it throws an AccessDenied error. Error creating load balancer (will retry): failed to ensure load balancer for service default/nginx: AccessDenied: User: arn:aws:sts::*************:assumed-role/eks-service-role/************* is not authorized to perform: iam:CreateServiceLinkedRole on resource: arn:aws:iam::*************:role/aws-service-role/elasticloadbalancing.amazonaws.com/AWSServiceRoleForElasticLoadBalancing The two Policies that were added (AmazonEKSClusterPolicy, AmazonEKSServicePolicy) do not have the iam:CreateServiceLinkedRole action allowed. Are we supposed to add this outside of the policies defined in the guide? Or is this something that should be included in the EKS policies? A: I got it worked by adding this policy to the EKS Role: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iam:CreateServiceLinkedRole", "Resource": "arn:aws:iam::*:role/aws-service-role/*" }, { "Effect": "Allow", "Action": [ "ec2:DescribeAccountAttributes" ], "Resource": "*" } ] } A: It seems that the EKS userguide assumes you have created load balancers in your AWS account prior to creating the EKS cluster, and thus have an existing AWSServiceRoleForElasticLoadBalancing service role in AWS IAM. As described in https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/elb-service-linked-roles.html#create-service-linked-role You don't need to manually create the AWSServiceRoleForElasticLoadBalancing role. Elastic Load Balancing creates this role for you when you create a load balancer. EKS is attempting to do this for you, resulting in the access denied exception using the default policies. Other options to explicitly create the service-linked role prior to EKS cluster creation include: AWS CLI aws iam create-service-linked-role --aws-service-name "elasticloadbalancing.amazonaws.com" Terraform resource "aws_iam_service_linked_role" "elasticloadbalancing" { aws_service_name = "elasticloadbalancing.amazonaws.com" } Or, manually create a load balancer from the UI Console. Regardless of provisioning options, you should know things will work when you see the following role in AWS IAM arn:aws:iam::<ACCOUNT_ID>:role/aws-service-role/elasticloadbalancing.amazonaws.com/AWSServiceRoleForElasticLoadBalancing
doc_23536297
I'm using kotlin and after following this answer, I have tried this in fragment. override fun onAttach(context: Context) { super.onAttach(context) requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS) } override fun onDetach() { super.onDetach() requireActivity().window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS) } but the result that I got is this You can clearly see navigation and status bars are still there. Can you share the proper and latest way to get fullscreen in fragment? A: If you read the docs for ViewCompat.getWindowInsetsController(), you'll see that it's only deprecated because they want you to use getInsetsController() instead. Otherwise, the sample code works just fine. A: Can you use the theme as follows <style name="AppTheme"parent="Theme.MaterialComponents.DayNight.NoActionBar"> <item name="android:windowNoTitle">true</item> <item name="android:windowActionBar">false</item> <item name="android:windowFullscreen">true</item> <item name="android:windowContentOverlay">@null</item> </style> A: For making a fragment full-screen. override fun onAttach(context: Context) { super.onAttach(context) WindowInsetsControllerCompat(requireActivity().window, requireActivity().window.decorView).apply { // Hide both the status bar and the navigation bar hide(WindowInsetsCompat.Type.systemBars()) // Behavior of system bars systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } } Make sure to add this code in your fragment as well, it will show the system bars again. override fun onDetach() { super.onDetach() WindowInsetsControllerCompat(requireActivity().window, requireActivity().window.decorView) .show(WindowInsetsCompat.Type.systemBars()) } I don't know how WindowInsetsControllerCompat works but if anyone wants to hide system bars then this will help.
doc_23536298
So say write "Msgbox("Hello world!")" into a .bas module as part of an Excel project from .NET so the code written from .NET would be some pre written VBA stored as a string and injected into the VBA project I have legacy code which I use for doing this sort of thing within VBA using the VBE properties to make a command bar for the VBA IDE and to write code into other modules or create new modules, but I'd like to be able to do this from either like I have said in the subject from VB.NET [preferably from a created add-in to be displayed on the Excel Ribbon] or maybe from a standalone winform app that can be minimised to the tray. The two things I want to do this are for: * *To monitor VBA code performance, the legacy code I mention basically inserts a call to another sub at the start and end of each procedure in the project and writes out to a .csv so that you know how long each sub and function took to run *To break up VBA project into component parts so that they can be added to TFS, basically loop through all the components of a VBA project and export them to a folder so they can be added to TFS enabling better source code tracking of changes Can someone point me to examples [if any] of writing code to a VBA module from vb.net or give guidance on how this may be achieved. I'm using .net framework 4.5 and visual studio 2012 with vb, but I'm fine with c# examples as well Many thanks. A: I assume you've figured this out already, but just in case: The VBE object tree is exposed through automation - just get the application object for whatever Office file you're dealing with via a CreateObject call, then do the same thing you did in VBA (with appropriate changes from VB6 to .net, obviously). exl = CreateObject("Excel.Sheet") exl.Application.Workbooks.Open("whatever.xlsx") 'exl.Application.VBE.ActiveVBProject etc etc
doc_23536299
<script type="text/javascript" charset="utf-8"> $(function () { new Highcharts.Chart({ chart: { renderTo: 'orders_chart' }, title: { text: 'Orders by Day' }, xAxis: { type: 'datetime' }, yAxis: { title: { text: 'Dollars' } }, tooltip: { formatter: function () { return Highcharts.dateFormat("%B %e %Y", this.x) + ': ' + '$' + Highcharts.numberFormat(this.y, 2); } }, series: [{ pointInterval: <%= 1.day * 1000 %>, pointStart: <%= 0.days.ago.at_midnight.to_i * 1000 %>, data: <%= @daily_count[0] %> }] }); }); </script> The problem is specifically: data: <%= @daily_count[0] %> this currently gives me one datapoint. I've tried just <%= @daily_count %> but that doesn't work. What I need is a way to put an array, and specifically [daily_count[0], daily_count[1]...] into data. A: try using to_json data: <%= @daily_count.to_json %>