text
stringlengths
14
21.4M
Q: Android 4.0 onwards OMX-IL HW Decoding from Native side Is it possible to use Android native code and OMX-IL (maybe using stagefright even) for HW decoding in Android 4.1 onward (maybe you will suggest creating an instance of OMXCodec). But I want to do my own surface allocation and handling done from the client application. The OMXCodec::Create expects a ANAtiveWindow but I want to bypass that and just use a decode function, where I would pass a buffer/eglSurface and get the decoded frame output. Any help would be highly appreciated! A: In JellyBean, I feel you could employ MediaCodec object to achieve the decoding of a frame. You could refer to the SimplePlayer implementation as in http://androidxref.com/4.2.2_r1/xref/frameworks/av/cmds/stagefright/SimplePlayer.cpp#316 which provide you a good reference to develop your program.
Q: Remove Basic Error Controller In SpringFox SwaggerUI Is there a way i can remove the "basic-error-controller" from springfox swagger-ui? Picture: A: For example if your parent Package is com.app.microservice package com.app.microservice; Then use the following code it will only display the Controllers within the Package and disable/exclude others @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.app.microservice")) .build(); } A: U can also use springfox-swagger2 annotations. springfox.documentation.annotations.ApiIgnore @ApiIgnore public class ErrorController { This would exclude that class from documentation. A: I think, the most elegant solution is to include only @RestController controllers into swagger, only thing to bear in mind, is to annotate all the REST controllers with that annotation: new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) .paths(PathSelectors.any()) .build(); As BasicErrorController is annotated with @Controller only, swagger would avoid BasicErrorController in definition file. Of course you can use your custom annotation instead of @RestController to mark your REST controllers as controllers eligible by swagger. A: * *It can be done using Predicate.not() . @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .paths(Predicate.not(PathSelectors.regex("/error.*"))) .build(); } A: My problem was just that I forgot to annotate Docket api() method with @Bean. A: You can restrict the request handler selector to scan only the package of your project: return new Docket( DocumentationType.SWAGGER_2) .select() .apis( RequestHandlerSelectors.basePackage( "your package" ) ) ... A: This can be done by moving @Bean definition to main class (the one with @SpringBootApplication) and use its this.getClass().getPackageName() in basePackage(): @Bean public Docket swagger() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage(this.getClass().getPackageName())) .paths(PathSelectors.any()) .build() .useDefaultResponseMessages(false); } A: With Swagger.v3, we can use @Hidden. So: import io.swagger.v3.oas.annotations.Hidden; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MyErrorController implements ErrorController { @RequestMapping("/error") @Hidden // Don't show in the Swagger doco @ResponseBody public void handleError(HttpServletRequest request, HttpServletResponse response) throws IOException { // My handler code } } A: After trying a lot of solutions, nothing works for me. Finally I got to know the very basic thing i.e. make sure that the file in which you have defined your swagger configuration file and your main method file should be in the same package . @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .paths(Predicates.not(PathSelectors.regex("/error.*"))) .build(); } Please check this image
Q: How to find in javascript with regular expression string from url? Good evening, How can I find in javascript with regular expression string from url address for example i have url: http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/ and I need only string between last slashes (/ /) http://something.cz/something/string/ in this example word that i need is mikronebulizer. Thank you very much for you help. A: Simply: url.match(/([^\/]*)\/$/); Should do it. If you want to match (optionally) without a trailing slash, use: url.match(/([^\/]*)\/?$/); See it in action here: http://regex101.com/r/cL3qG3 A: If you have the url provided, then you can do it this way: var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/'; var urlsplit = url.split('/'); var urlEnd = urlsplit[urlsplit.length- (urlsplit[urlsplit.length-1] == '' ? 2 : 1)]; This will match either everything after the last slash, if there's any content there, and otherwise, it will match the part between the second-last and the last slash. A: You could use a regex match with a group. Use this: /([\w\-]+)\/$/.exec("http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/")[1]; Here's a jsfiddle showing it in action This part: ([\w\-]+) * *Means at least 1 or more of the set of alphanumeric, underscore and hyphen and use it as the first match group. Followed by a / And then finally the: $ * *Which means the line should end with this The .exec() returns an array where the first value is the full match (IE: "mikronebulizer/") and then each match group after that. * *So .exec()[1] returns your value: mikronebulizer A: Something else to consider - yes a pure RegEx approach might be easier (heck, and faster), but I wanted to include this simply to point out window.location.pathName. function getLast(){ // Strip trailing slash if present var path = window.location.pathname.replace(/\/$?/, ''); return path.split('/').pop(); } A: Alternatively you could get using split: var pieces = "http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/".split("/"); var lastSegment = pieces[pieces.length - 2]; // lastSegment == mikronebulizer A: var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/'; if (url.slice(-1)=="/") { url = url.substr(0,url.length-1); } var lastSegment = url.split('/').pop(); document.write(lastSegment+"<br>");
Q: sec_to_time() breaking query with nested select If I do a SELECT SEC_TO_TIME(100); I get a correct timestamp, however if I do the following it breaks SELECT SEC_TO_TIME(SELECT SUM(totaltime) FROM tablename WHERE entry_id = 2) total time is stored as an integer value and the query returns a syntax error, can you do a nested select statement within a sec_to_time function? This is being executed from a c# data adapter so I can't manipulate the data outside the query otherwise I would get the sum and do some maths on in. A: You need an extra set of parentheses when calling a function on a subquery: SELECT SEC_TO_TIME( (SELECT SUM(totaltime) FROM tablename WHERE entry_id = 2) ); in my test db: mysql> select * from tablename; +----------+-----------+ | entry_id | totaltime | +----------+-----------+ | 2 | 100 | | 2 | 200 | +----------+-----------+ mysql> SELECT SEC_TO_TIME((SELECT SUM(totaltime) FROM tablename WHERE entry_id = 2)); +------------------------------------------------------------------------+ | SEC_TO_TIME((SELECT SUM(totaltime) FROM tablename WHERE entry_id = 2)) | +------------------------------------------------------------------------+ | 00:05:00 | +------------------------------------------------------------------------+ A: Try this: SELECT SEC_TO_TIME(stt) as stt_stt FROM ( SELECT SUM(totaltime) as stt FROM tablename WHERE entry_id = 2) as x but in the sql fiddle, that gives me January, 01 1970 00:12:47+0000 and I'm pretty sure that's not what you want... http://sqlfiddle.com/#!8/819fd/2/0 (no guarantees on that but it's what I would start with) A: This is the only other way I can think of. SELECT SEC_TO_TIME(SUM(totaltime)) FROM tablename WHERE entry_id = 2
Q: what is the "ordered" of "De Lima ordered arrested by RTC" in news headline De Lima ordered arrested by RTC link From this answer I somewhat understand of Headlinese. However, I still don't understand ordered. I mean, I can understand was is omitted in following sentence. De Lima (was) arrested by RTC But in the sentence, two past participles are arranged side by side. I tried to study Headlinese but I couldn't find answer clearly. Could somebody make a perfect(normal) sentence from the headline? I read someone said it can be various cases. Then could you make some sentences which is possible to suppose. So far, my best attempt is that De Lima (was) ordered (to be) arrested by RTC I'm not sure, though. Thank you in advance. A: Macmillan provides many definitions of order as a verb; two of them are: ▸ to ask for a product to be made for you or delivered to you ▸ to tell someone to do something So, if I say: Bob ordered a cake that means Bob went to the bakery and asked for a cake to be made, but if I say: Bob ordered arrested by police chief This time, the police chief is doing the ordering, and it's a different kind of order. The chief is telling his police force to make the arrest. Another way to say this would be: Police Chief orders that Bob be arrested So, in your sentence: De Lima ordered arrested by RTC That means: the RTC issued an order for DeLima's arrest
Q: org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file My code is not working, it always shows the above mentioned exception. but I can always see the tmp file being generated. here is the code, can someone please suggest something: FileInputStream fis =null; try{ fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls")); Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis); int numOfSheets = wb.getNumberOfSheets(); System.out.println("bhargo num of sheets is " + numOfSheets); for(int i=0; i<numOfSheets; i++){ org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(i); Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = (Cell) cellIterator.next(); if (cell.getCellType() == cell.CELL_TYPE_STRING) { System.out.println("bhargo cell value is " + cell.getStringCellValue().trim()); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ System.out.println("bhargo, closing the stream"); try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } A: There are a number of issues here: fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls")); Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis); Firstly, as explained in the Apache POI documentation, don't use an InputStream if you have a file! It's slower and uses more memory Secondly, XSSF is the code for working with .xlsx files, but your file is a .xls one, so that won't work. Thirdly, Apache POI has code which will automatically work out what kind of file yours is, and create the appropriate workbook for you Your code should therefore instead be Workbook wb = WorkbookFactory.create(new File("/home/amar/Desktop/new/abc.xls")); This will create the right kind of workbook, direct from the file A: I was able to solve my problem. I am working on linux so it was saving the file in the older version of excel
Q: Entity Framework / POCO/ WCF We are creating a website from scratch and the will be created in MVC 4.0 With EF4.0 And we wish to create a common data access layer using EF and expose the EF using WCF. As the EF contains the CodeLogic we wish to separate the EF from the client calls. The client has to call the WCF via POCO object and the WCF will inturn return some kind of results using POCO. And my question is this kind of logic is ok. How can I convert POCO to EF and vice versa. Thanks for your time and patience A: First of all, I don't know if it is a good idea to expose Entities directly from a webservice. Maybe you wanna use a Data Transfer Object and maybe you wanna use a WCF REST or a WebApi (webservice is quite outdated). That would be a good idea if you have your Business logic inside the WebService. If not, it's quite weird to use Entify Framework capabilities and then hide all the advantages behind a webservice. Anyway, there is a awesome tool for converting from one object to another, it's called automapper.
Q: Como enviar vários anexos concatenado em uma mesma variavel no vbscript 'Declarando as variaveis internas leitura dos arquivos Dim arquivos Set objFSO = CreateObject("Scripting.FileSystemObject") 'Setando pasta de origem objStartFolder = "C:\TESTE\ORIGEM" Set objFolder = objFSO.GetFolder(objStartFolder) 'Setando pasta de Destino pastaDestino = "C:\TESTE\DESTINO" 'Listando todos os arquvios da pasta e contatenando em um unico nome para envio por e-mail Set colFiles = objFolder.Files For Each objFile in colFiles If arquivos = "" Then arquivos = objStartFolder & objFile.Name Else arquivos = arquivos & " | " & objStartFolder & objFile.Name End If arquivo = objStartFolder & objFile.Name objFSO.CopyFile arquivo, pastaDestino Next 'Envio por e-Mail vbScript ' Declarando as variaveis internas do envio por e-mail vbScript Set emailObj = CreateObject("CDO.Message") emailObj.From = "[email protected]" emailObj.To = "[email protected]" emailObj.Subject = "Testando" emailObj.TextBody = "Teste "&Date()&" "&Time() emailObj.AddAttachment arquivos Set emailConfig = emailObj.Configuration emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com" emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465 emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername") = "[email protected]" emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password" emailConfig.Fields.Update emailObj.Send If err.number = 0 then Msgbox "Done" 'Realizando historico de arquivos e deletando da pasta atual. Const DeleteReadOnly = TRUE For Each objFile in colFiles arquivo = objStartFolder & objFile.Name objFSO.DeleteFile(arquivo), DeleteReadOnly Next
Q: How to send command in separate python window Searching isn't pulling up anything useful so perhaps my verbiage is wrong. I have a python application that I didn't write that takes user input and performs tasks based on the input. The other script I did write watches the serial traffic for a specific match condition. Both scripts run in different windows. What I want to do is if I get a match condition from my script output a command to the other script. Is there a way to do this with python? I am working in windows and want to send the output to a different window. A: Since you can start the script within your script, you can just follow the instructions in this link: Read from the terminal in Python old answer: I assume you can modify the code in the application you didn't write. If so, you can tell the code to "print" what it's putting on the window to a file, and your other code could constantly monitor that file.
Q: How to create a Java object from a string representation at runtime Eg if I have a string "{1,2,3,4,5}" I would like to get an int[] object from that string. I have looked a bit at Janino and Beanshell, but can't seem to find the correct way to get them to do this for me. I am looking for a generic solution, one that works for all types - not only integer arrays. A: looks like a parse problem to me. look at the string methods :) the code could look like: String s = "{1,2,3,4,5}" String justIntegers = s.substring(1, s.length()-1); LinkedList<Integer> l = new LinkedList(); for (String string: justIntegers.split(',')) l.add(Integer.valuesOf(string)); l.toArray(); if you are using strings to send/save objects pls use xml or json... A: Take a look at https://stackoverflow.com/a/2605050/1458047 The answer proposes a few options. A: Better to use Regular Expression.Not necessary that your String is Array it could be any String which contains numbers. String s="{1,2,3,4,5}"; Pattern p = Pattern.compile("-?\\d+"); Matcher m = p.matcher(s); List<Integer> list=new ArrayList<Integer>(); while (m.find()) { Integer num=new Integer(m.group()); list.add(num); } System.out.println(list); Output: [1, 2, 3, 4, 5]
Q: Excel Object generates error after the application is published My VB.NET Windows forms application is writing data into excel file. It works without any error in development environment. The excel file gets created with data. But when the application is deployed/Published. It gives error : "Object reference not set to an instance of an object" at xlWorkBook.SaveAs Error is confusing. Is it a permission issue? Any help. Below is the code: Dim xlApp As Excel.Application = New Excel.Application xlApp.SheetsInNewWorkbook = 1 Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add Dim xlWorkSheet As Excel.Worksheet = CType(xlWorkBook.Worksheets.Add(), Excel.Worksheet) xlWorkSheet.Name = "Sample1" xlWorkSheet.Cells(1, 1) = "TestData1" xlWorkSheet.Cells(1, 2) = "TestData2" xlApp.DisplayAlerts = False xlWorkBook.SaveAs(gExcelFileName, Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _ Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges) A: The solution I found for this issue is to change the folder location in the variable "gExcelFileName" to a local folder on the machine where it is installed. It works now. I think it is a permission issue. A: Did you publish your application with excel interop dll? different version of excel may have different parameter, if you don't want to publish your application with excel dll, try to use named parameter: xlWorkBook.SaveAs(FileName:=gExcelFileName, FileFormat:=Excel.XlFileFormat.xlWorkbookDefault, AccessMode:=Excel.XlSaveAsAccessMode.xlNoChange, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges)
Q: MS VC++ inline asm syntax error long long k; _asm { rdtsc:=A(k); }; This code gives this error: error C2400: inline assembler syntax error in 'first operand'; found ':' error C2400: inline assembler syntax error in 'opcode'; found ':' P.S. MS Visual C++ 2008 A: rdtsc:=A(k); is not a valid instruction. Only labels can appear before :, and after that there must be a valid instruction, which of course =A(k) can't be. If you're doing an assignment, that's not an assembly instruction either A: Without being given the full source, I would say immediately that you are using a Pascal-like assignment syntax instead of C++. Try: rdtsc=A(k); // Without the colon Rather than: rdtsc:=A(k);
Q: Recover overwritten annotated pdf I had annotated a pdf in Okular that had been generated via pdflatex and saved it. I was able to open and see the annotations. However, I guess I did a Ctrl-S on the tex file by mistake and that over-wrote the whole pdf and I've lost all my annotations. Is there any way in which I can recover the annotations of my pdf? I use Ubuntu 18.04 and Okular 1.7.2
Q: Android: how to make an image viewer with ListView at bottom I have received a requirement make an image viewer with the listview at bottom like this video https://www.youtube.com/watch?v=aC4OFRxk988 but I don't know the name of that controller to research. Please help me. Thanks A: I think viewpager and listview. and dynamic scale image view are setmatrix. simply reply. i can't add comment at your post.... if want more hint reply me. A: https://github.com/ksoichiro/Android-ObservableScrollView You can find here some custom implementations. Test the demo app from the play store and check which one has the closest functionality to the one you desire. Then take a deep breath and try to understand how it's done.
Q: Building a simple RESTful api I'm wanting to make an API quickly, following REST principles - for a simple web application I've built. The first place the API will be used is to interface with an iPhone app. The API only needs handle a few basic calls, but all require authentication, nothing is public data. * *login/authenticate user *get list of records in users group *get list again, only those that have changed (newly added or updated) *update record So, following REST principles, would I setup the uri scheme?: * *mysite.com/api/auth (POST?) *mysite.com/api/users (GET) *mysite.com/api/update (POST?) and the responses will be in XML to begin with, JSON too later. * *On the website, users login with email and password. Should I let them get a 'token' on their profile page to pass with every api request? (would make the stand alone '/auth' URI resource redundant). *Best practices for structuring the response xml? It seems like with REST, that you should return either 200 ok and the XML or actual proper status codes i.e. 401 etc Any general pointers appreciated. A: 1- for auth, you might want to consider something like http-basic, or digest auth (note - basic in particular is insecure if not over https) for the urls scheme: * */api/auth is not needed if you leverage basic or digest. */api/group/groupname/ is probably more canonical */api/update would generally be done as /api/users/username (POST) with the new data added - the resource is the user - POST is the verb *otherwise, basically your API looks sane, much depends on whether groups are hierarchical, and users must live in a group - if so, your urls should reflect that and be navigable. 2- status codes should reflect status - 200 for OK, 401 for access denied, 404 for not found, 500 for error processing. Generally you should only return an XML record if you have a good request A: Authentication in an API always works by sending some authenticating token in the request header. I.e., even when using the separate /auth login approach, you would return some token, possibly a cookie, back to the user, which would need to be send together with every request. HTTP already provides a dedicated header for this purpose though: Authorization. The most basic HTTP "Authorization" is HTTP Basic access authentication: Authorization : Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== Digest Authentication is another, more secure, scheme. You can use this header field for any form of authentication you want though, even your custom implemented authentication. Authorization : MyCustomAuthentication foo:bar:n293f82jn398n9r You could send the aforementioned login token in this field. Or you could employ a request signing scheme, in which certain request fields are hashed together with the password of the user, basically sending the password without sending the password (similar to digest authentication, but you can use something better than md5). That obliterates the separate login step. AWS employs this method. For an API in general, make good use of the HTTP status codes to indicate what is happening. A: You're generally on the right track. The URI scheme should be based around the idea of resources and you should use an appropriate method to do the work. So, GET to retrieve info. POST (Or maybe PUT) to create/change resources. DELETE for well, delete. And HEAD to check the metadata. The structure of your XML doesn't have much to do with a RESTful API, assuming it doesn't require state management. That said, you have the right idea. If it's a good request, return the desired XML (for a GET request) and status code 200. If it's a bad request, you may also, and in some cases needed to, return something other than just the status code. Basically, get familiar with the HTTP spec and follow it as closely as possible.
Q: Statically mirroring a heavy trafficked site, CloudFlare as DNS I run a fairly heavy trafficked website and due to some unfortunate incidents the machines that are in my cloud at Linode went down. And I have only a single Load Balancer machine exposed to the outside world (one IP). Also my site is a candidate for over 6,000 static pages that can be mirrored. Now my DNS is CloudFlare. What can I do to maintain a static mirror of my site and route to it incase my site goes down. Since I am running from Linode I don't have anything like Route53 to detect downtime at an IP address and point to another one. What are the strategies that people use statically mirror site and work against downtime? A: A couple different things jump to mind first and foremost: First, you already have a static mirror of your site that is designed for just this use-case: Cloudflare. As well as providing your DNS, I assume you have them set up as a CDN to dull the brunt of traffic that is coming towards you. Cloudflare has a feature called Always Online which is intended to do just what you are looking for: provide a static copy of the website up even if the "origin" - in this case, your load balancer and/or the servers behind it - go down. Make sure that you have that set up properly first, before you worry about a more complicated solution. Always good to get 80%+ of the problem out of the way with 2% of the work! In fact, you may be able to simply rely on Cloudflare to take care of the problem for you completely. Do some reading into Cloudflare Always On first, as it is going to be a lot simpler for you implement than anything to follow, since Cloudflare is already set up in your infrastructure. If after you have read up, it won't do enough for you, read on. Now, there are a couple different things you need to think about when worrying about making your site available through different kinds of outages. The first thing is the goals. Are you trying to maintain your sites availability in an outage only, or would you prefer to also maintain a second site that you use to load balance between locations? What kind of system outages are you trying to prevent? How much time and/or money are you willing to invest in minimizing downtime? After you have set some of the goals, you can now look at the different kinds of solutions that are out there. Generally speaking, all of the different strategies for minimizing downtime involve keeping one or more "extra" locations synchronized with the content in the main location, preferably in a different hosting provider and network to prevent downtime that spreads across an entire company. Failover is generally done through manipulation of DNS records. Larger companies will sometimes use IP-level solutions like anycasting or route manipulation to accomplish the tasks - which comes with several benefits - but doing so is expensive and extremely difficult to get right. There are lots of companies out there that can help you change your DNS records automatically when a single IP becomes unavailable, but you can do it fairly easily yourself by utilizing the Cloudflare API (or the API of whatever your DNS provider is, if you change in the future.) All that is required is a second system in a separate location as wherever your website is hosted that continually checks your site to make sure it is up. If not, it hits your DNS providers API and changes the DNS records of your site to point to your backup location. This means that you will have a worst-case (on paper) downtime of the monitoring interval + the DNS TTL. In practice, DNS can be quite aggressively cached, and even short (<30sec) TTLs can take up to a couple hours to be completely cleaned out by all clients around the world. Mobile devices, in particular, are known for being troublesome with this. There are lots of tutorials out there on how to use different monitoring systems to accomplish this task - a quick search for "cloudflare failover" got me these two which use nagios and monit, respectively, but I am sure there are lots more easily accessible. Of course, any kind of failover requires a place to fail over to! There are a bunch of different requirements for doing so, depending on your particular application's specifications and the requirements for synchronization. Some sites which are all static content can simply be copied each time they are updated to both locations, either by hand, by an automated script which pushes or pulls from the master to the slaves (cron + rsync is your friend!), or other methods like block-replication (DRBD) or a shared file system (GlusterFS). Other sites with dynamic content will require both this kind of file-level synchronization and database replication in a master-slave setup. Note, databases can cause all sorts of problems if you are trying to accept writes at both locations, so do plenty of research into master/master database replication using your particular database technologies if you are planning to have both datacenters concurrently available. It is not uncommon to setup the slave as a read-only replica even when failed over to in order to keep from having to sync the data back from the promoted slave when the main center is available again. There are a lot of different things to think about when considering this kind of high-availability setup. If you tell us a bit more about the specifics of your application, I'm sure we can add more specific advice. A: Instead of buying the NodeBalancer fits-all ready-to-use feature from Linode, you might as well just buy another regular Linode, and implement load balancing and caching by yourself. You can use nginx, and have it act as a proxy and balancer to your real web-site. Depending on whether you require your website to change every couple of hours/days or not, you can use several nginx features to save the content from your upstream Linodes. http://nginx.org/en/docs/http/ngx_http_proxy_module.html One feature you may find very useful is proxy_cache. Another one is proxy_store. The proxy_cache set of directives are very flexible such that nginx can be configured to automatically store and expire all the pages, or automatically serve stale pages only the the upstreams are unavailable (e.g. take a look at proxy_cache_use_stale). Whereas proxy_store can potentially be implemented together with a manual clear-all rm -rf script, depending on your needs. Of course, if you're already paying 20$/mo for your load balancer at Linode (and provided you are not over budget), then you might as well cancel that, and look into CloudFlare, Incapsula and other similar offerings, some paid versions of which can be configured to cache all kinds of content (including that dynamically generated, starting at 10$/mo at Incapsula, for example). A: Best Speed, Best Reliability, Most Secure If your site is static then you should consider hosting it purely on CDN, then you don't need load balancers , dedicated or vps servers. Good CDNS scale as much you need and your only charged for the send amount or per Xrequests depending which company you go with. In regards of the non www cname issues I believe that cloudsflare has a workaround, Rackspace and Amazon you'd need a vps to redirect from non www to www. on the cdn. CDN would offer more performance than a vast number dedicated servers or vps. Also its by far the most reliable and secure. If you have some php files like contact forms then you can host them on a vps 64mb-256mb by using ajax js. Further you mention mirroring,cdns mirror files all over the world this one of the main reasons there so fast and they use fail proof raids, and other failover redundantances... cdns cant really fail. But if you wanted a mirror say to a vps then you just use the api and cron the backup. DNS.. Just pickone that has anycast/active failover http://dyn.com/dns/dns-comparison/ A: Cloudflare can already do this for you. Though a service called Always Online™ (scroll down about half way). If you want your own solution, use a proxy/load balancer. Something like haproxy works very well for this. Though, as this is a static file request, nginx will work very well too. So, if one goes down, the proxy simply stops requesting from the down server. But note that using a load balancer alone is not a failover, you need additional web servers ready to serve the extra load when the other fails. DNS failover which you mentioned is not recommended if you are looking to stay within one datacenter. See Why is DNS failover not recommended? That post will also outline some additional solutions for you as well.
Q: Regex: how to extract and replace multiple instances from a string? From the string "Hi @[Bob](1234) and @[John](8888)!" I want to return: Hi <a href="/1234">Bob</a> and <a href="/8888">John</a>! I'm using JavaScript I tried: myString.replaceAll(/@\[/gim, '<a href="????">') to remove unwanted characters, such as "@[" but I don't know how to extract "Bob" and "1234" from the original string to then put them back into the returned string. How to take "1234" and place it where "????" is? A: You need capturing groups as in @\[([^\]\[]+)\]\(([^()]+)\) See a demo on regex101.com. IN JS this could be: let some_text = "Hi @[Bob](1234) and @[John](8888)!"; some_text = some_text.replace(/@\[([^\]\[]+)\]\(([^()]+)\)/g, "<a href=\"/$2\">$1</a>"); console.log(some_text);
Q: Selected Template switching with select not working - model going undefined Using a modified version of Knockout.js wizard validation on each step I plan to have a similar step-by-step wizard. On the PaymentModel view-model step it has two child view-models (payment1Model and payment2Model), the child view-model that is displayed will be dependent on the selectedPaymentOption (option1 or option2). I switch between selected view models with the following code on the PaymentModel self.selectedPaymentOption.subscribe(function(newValue) { if(typeof newValue == "undefined") return; var found = ko.utils.arrayFirst(self.options(), function (item) { return item.name() == newValue; }, this); self.selectedTemplate(found.template); self.selectedModel(found.model()); },self); I can switch between the templates the first time OK, but when switching back I am getting a null reference error and binding fails below. I suspect it is to do with setting the selectedTemplate before the selectedModel (or vice versa), and one attempting to bind without the other (chicken and egg situation) since the template uses <div data-bind="template: { name: selectedTemplate, data: selectedModel }"></div>. Is there any way to defer updates until both have been selectedTemplate and selectedModel have been updated, or is there a better way to tackle this issue? My fiddle is here and code below: <div data-bind="template: { name: 'currentTmpl', data: currentStep }"></div> <button data-bind="click: goPrevious, visible: canGoPrevious">Previous</button> <button data-bind="click: goNext, visible: canGoNext, enable: modelIsValid">Next</button> <script id="payment1Tmpl" type="text/html"> <p>payment option 1</p> <input id="details1" type="text" data-bind="value: details1, valueUpdate: 'afterkeydown'" /> <select id="expiresMonth" data-bind="options: expiresMonthOptions, value: expiresMonth" /> <select id="expiresYear" data-bind="options: expiresYearOptions, value: expiresYear" /> </script> <script id="payment2Tmpl" type="text/html"> <p>payment option 2</p> <input id="details2" type="text" data-bind="value: details2, valueUpdate: 'afterkeydown'" /> </script> <script id="currentTmpl" type="text/html"> <h2 data-bind="text: name"></h2> <div data-bind="template: { name: getTemplate, data: model }"></div> </script> <script id="nameTmpl" type="text/html"> <fieldset> <legend>Name</legend> <p> <label for"FirstName">First Name</label> <input id="FirstName" type="text" data-bind="value: firstName, valueUpdate: 'afterkeydown'" /> <p data-bind="validationMessage: firstName"></p> </p> </fieldset> </script> <script id="paymentTmpl" type="text/html"> <fieldset> <p> <label for"someOtherDetail">Some other detail</label> <input id="someOtherDetail" type="text" data-bind="value: someOtherDetail, valueUpdate: 'afterkeydown'" /> </p> <p> <select data-bind="options: paymentOptions, value: selectedPaymentOption"></select> <div data-bind="template: { name: selectedTemplate, data: selectedModel }"></div> </p> </fieldset> </script> <script id="confirmTmpl" type="text/html"> <fieldset> <legend>Name</legend> <b><span data-bind="text:NameModel.firstName"></span></b> <br/> </fieldset> <button data-bind="click: confirm">Confirm</button> </script> ko.validation.configure({ insertMessages: false, decorateElement: true, errorElementClass: 'error' }); function TemplatePage(id, name, template, model) { var self = this; self.id = id; self.name = ko.observable(name); self.template = template; self.model = ko.observable(model); self.getTemplate = function () { return self.template; }; } function ViewModel() { var self = this; self.nameModel = ko.observable(new NameModel()); self.paymentModel = ko.observable(new PaymentModel()); var confirmModel = { NameModel: self.nameModel(), PaymentModel: self.paymentModel() }; self.stepModels = ko.observableArray([ new TemplatePage(1, "Step1", "nameTmpl", self.nameModel()), new TemplatePage(2, "Step2", "paymentTmpl", self.paymentModel()), new TemplatePage(3, "Confirmation", "confirmTmpl", confirmModel) ]); self.currentStep = ko.observable(self.stepModels()[0]); self.currentIndex = ko.computed(function () { return self.stepModels.indexOf(self.currentStep()); }); self.getTemplate = function (data) { return self.currentStep().template(); }; self.canGoNext = ko.computed(function () { return (self.currentIndex() < (self.stepModels().length - 1)); }); self.modelIsValid = ko.computed(function () { if (typeof(self.currentStep().model().isValid) != "undefined") { return self.currentStep().model().isValid(); } else return true; }); self.goNext = function () { if (self.currentIndex() < self.stepModels().length - 1) { var count = self.currentIndex() + 1; console.log(count); self.currentStep(self.stepModels()[count]); } }; self.canGoPrevious = ko.computed(function () { return self.currentIndex() > 0; }); self.goPrevious = function () { if (self.currentIndex() > 0) { var count = self.currentIndex() - 1; console.log(count); self.currentStep(self.stepModels()[count]); } }; } Payment1Model = function() { var self = this; self.details1 = ko.observable().extend({ required: true }); self.expiresMonthOptions = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; self.expiresYearOptions = ["2013", "2014", "2015", "2016"]; self.expiresMonth = ko.observable().extend({ required: true }); self.expiresYear = ko.observable().extend({ required: true }); ko.validation.group(self); } Payment2Model = function() { var self = this; self.details2 = ko.observable().extend({ required: true }); ko.validation.group(self); } NameModel = function(model) { var self = this; //Observables self.firstName = ko.observable().extend({ required: true }); ko.validation.group(self); return self; }; var PaymentModel=function() { var self = this; self.payment1Model = ko.observable(new Payment1Model()); self.payment2Model = ko.observable(new Payment2Model()); self.someOtherDetail = ko.observable().extend({ required: true }); self.options = ko.observableArray([ new TemplatePage(1, "Payment1", "payment1Tmpl", self.payment1Model()), new TemplatePage(1, "Payment2", "payment2Tmpl", self.payment2Model()), ]); var optionNames = []; for(var i=0; i<self.options().length; i++) { optionNames.push(self.options()[i].name); } self.paymentOptions = optionNames; self.selectedPaymentOption = ko.observable(optionNames[0]); self.selectedTemplate = ko.observable(); self.selectedModel = ko.observable(); self.selectedPaymentOption.subscribe(function(newValue) { if(typeof newValue == "undefined") return; var found = ko.utils.arrayFirst(self.options(), function (item) { return item.name() == newValue; }, this); self.selectedTemplate(found.template); self.selectedModel(found.model()); },self); ko.validation.group(self); self.isParentAndChildValid = function () { if (typeof self.selectedModel() == "undefined") return false; return self.isValid() && self.selectedModel().isValid(); }; return { someOtherDetail: self.someOtherDetail, selectedPaymentOption: self.selectedPaymentOption, paymentOptions: self.paymentOptions, selectedTemplate: self.selectedTemplate, selectedModel: self.selectedModel, isValid: self.isParentAndChildValid } } ko.applyBindings(new ViewModel()); A: Here is working solution. Now it works without any errors. What you need to do is to stop using next to separated variables: self.selectedTemplate = ko.observable(); self.selectedModel = ko.observable(); Instead you've use one another variable that will hold selected option from options array: self.selectedTemplate = ko.observable(self.options()[0]); Every time you change your choice of payment, you find selected option in options array. Just put it into a new variable self.selectedTemplate: var found = ko.utils.arrayFirst(self.options(), function (item) { return item.name() == newValue; }, this); self.selectedTemplate(found); Change HTML accordingly: <div data-bind="template: { name: selectedTemplate().template, data: selectedTemplate().model() }"></div> (EDIT) Change all instances of selectedTemplate and selectedModel with new selectedTemplate().template and selectedTemplate().model()
Q: How to Automate or Move (Silverlight) xap file to 14 hive ClientBin I am using silverlight project in sharepoint 2010.I have an requirement of using WSP builder project only for building the soultion and I have configured the layout structure depends on 14 hive. In the dev machine I have configured post build event command in the project properties tab xcopy Sample.xap "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin\" /Y So whenever I build the silverlight project automatically the sample.xap file will be moved to the 14 hive client bin but when I build WSP for the project using wsp builder the clientbin folder is not available in it. But when I right click the clientbin folder in visual studio solution the sample.xap file is present but inside the wsp it is not there ? So could you provide a solution for automate or move the xap file to 14 hive clientbin folder at the time of deploying the wsp in the testing server ? A: Just call context menu for you Sharepoint project in Visual Studio. Then Add -> SharePoint Mapped Folder... In the next window you can select TEMPLATE\LAYOUTS\ClientBin folder and add it into your project. After that you can add subfolders or files to this ClientBin folder which will automaticaly deployed on server during wsp-file installation.
Q: How to calculate count and percentage in groupby in Python I have following output after grouping by Publisher.groupby('Category')['Title'].count() Category Coding 5 Hacking 7 Java 1 JavaScript 5 LEGO 43 Linux 7 Networking 5 Others 123 Python 8 R 2 Ruby 4 Scripting 4 Statistics 2 Web 3 In the above output I want the percentage also i.e for the first row 5*100/219 and so on. I am doing following Publisher.groupby('Category')['Title'].agg({'Count':'count','Percentage':lambda x:x/x.sum()}) But it gives me an error. Please help A: I think you can use: P = Publisher.groupby('Category')['Title'].count().reset_index() P['Percentage'] = 100 * P['Title'] / P['Title'].sum() Sample: Publisher = pd.DataFrame({'Category':['a','a','s'], 'Title':[4,5,6]}) print (Publisher) Category Title 0 a 4 1 a 5 2 s 6 P = Publisher.groupby('Category')['Title'].count().reset_index() P['Percentage'] = 100 * P['Title'] / P['Title'].sum() print (P) Category Title Percentage 0 a 2 66.666667 1 s 1 33.333333 A: df = pd.DataFrame({'Category':['a','a','s'], 'Title':[4,5,6]}) df=df.groupby('Category')['Title'].count().rename("percentage").transform(lambda x: x/x.sum()) df.reset_index() #output in dataframe type Category percentage 0 a 0.666667 1 s 0.333333 #please let me know if it doesn't solve your current problem
Q: Disable kernel lockdown on 18.04 I am trying to access a device connected through USB3 (an intel realsense depth camera), however I believe the kernel lockdown is blocking access to it. dkms status reads the proper camera, but when I try to check if data is being streamed with dmesg -wT I get a long output which culminates in this error message: Lockdown: systemd-udevd: unsigned module loading is restricted; see man kernel_lockdown.7 How can I disable the kernel lockdown so that I can gain access to this device? I have tried this as suggested by a few posts, but it has no effect: echo 1 > /proc/sys/kernel/sysrq echo x > /proc/sysrq-trigger A: If you want to use 3rd party unsigned kernel modules, you need to disable Secure Boot in BIOS settings.
Q: All my siteweb page redirect to contact page I Have an issue with my WordPress website every page is redirecting to the contact.php page. For example, I click on the homepage, I get the contact page. When I check the network section in the browser inspector I have something like this : 302 get www.domaine.com (homepage but with 302 code!). 301 get www.domaine.com/index.php?page_id=5672 (I think the page_id is for contact page). 200 get www.domaine.com/contact.php . then the page contact.php is loaded. I get this for every page of my website, but when I logged in admin panel everything works OK, I think the problem shows up when I updated WordPress to the newest version but not sure about that. edit : htacces file <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> Thanks for your help.
Q: get a derivative by knowing two numeric vectors I know two vectors x and y, how can I calculate derivatives of y with respect to x in R ? x<-rnorm(1000) y<-x^2+x I want to caculate derivative of y with respect to x: dy/dx; suppose I don't know the underlying function between x and y. There can be a value in derivative scale corresponding to each x. A: The only problem with your data is that it is not sorted. set.seed(2017) x<-rnorm(1000) y<-x^2+x y = y[order(x)] x = sort(x) plot(x,y) Now you can take the y differences over the x differences. plot(x[-1],diff(y)/diff(x)) abline(1,2) The result agrees well with the theoretical result d(x) = 2x+1 If you want to get you hands on the function for the derivative, just use approxfun on all of the points that you have. deriv = approxfun(x[-1], diff(y)/diff(x)) Once again, plotting this agrees well with the expected derivative. A: To find the derivative use the numeric approximation: (y2-y1)/(x2-x1) or dy/dx. In R use the diff function to calculate the difference between 2 consecutive points: x<-rnorm(100) y<-x^2+x #find the average x between 2 points avex<-x[-1]-diff(x)/2 #find the numerical approximation #delta-y/delta-x dydx<-diff(y)/diff(x) #plot numeric approxiamtion plot(x=avex, dydx) #plot analytical answer lines(x=avex, y=2*avex+1)
Q: Command line, how to enter to the first directory Does anyone know how I can go into the first directory in some other directory via the cmd on Windows? For example I enter into the "abc" directory: cd abc Then I don't know the name of the first folder in the "abc" directory but I know that I need to enter in that first folder. cd %first% (for example). A: This can do the job, create a file named cd2first.bat: @ECHO OFF CD abc FOR /D %%a IN (*) DO ( CD %%a GOTO :EOF ) Explanation: * *Change directory to abc from CWD. *FOR /D for each directory in the new current directory, change to the first subdirectory. *GOTO :EOF, goto to the End Of batch File.
Q: Pattern Not Matching in VBA I am trying to match a pattern in VBA but it doesnt work.I am Trying to match a pattern like -> 1:0 If Cells(i, 7) Like "[0-9]\:[0-9]" Then Range("G" & i).Interior.ColorIndex = 0 Else CountDTPSelectionError = 1 Range("G" & i).Interior.Color = RGB(255, 0, 0) ErrorsLog = ErrorsLog & TimeStamp & " Error: " & "DTP Selection Is not Defined Correctly" & vbNewLine End If This code colours even the Correct matched Values.I want only the pattern that is does not match the above regex should be coloured red. A: You are trying to escape the colon to make it a literal colon. No need to do that in VBA and Like operator nor in the regex simulation you have used. \: simply tells the engine to use a literal colon, however just using : results the same effect, it's allready literal. Furthermore it seems that you are checking ratio's? If so, then I think 0:1 would be an invalid ratio? Therefor see the following: Sub Test() Dim arr As Variant: arr = Array("12:9", "1:9", "1/9", "0:1) For Each el In arr If el Like "[1-9]:#" Then Debug.Print el & "= Correct" Else Debug.Print el & "= Incorrect" End If Next End Sub Where # is short for [0-9] within the operator. Keep in mind, though Like and regular expressions share similarities, they are not the same! Note: If 0:1 is a valid pattern then simply change to #:# as per @YasserKhalil mentioned in the comments.
Q: Prevent a webpage from navigating away using JavaScript How to prevent a webpage from navigating away using JavaScript? A: In Ayman's example by returning false you prevent the browser window/tab from closing. window.onunload = function () { alert('You are trying to leave.'); return false; } A: The equivalent to the accepted answer in jQuery 1.11: $(window).on("beforeunload", function () { return "Please don't leave me!"; }); JSFiddle example altCognito's answer used the unload event, which happens too late for JavaScript to abort the navigation. A: That suggested error message may duplicate the error message the browser already displays. In chrome, the 2 similar error messages are displayed one after another in the same window. In chrome, the text displayed after the custom message is: "Are you sure you want to leave this page?". In firefox, it does not display our custom error message at all (but still displays the dialog). A more appropriate error message might be: window.onbeforeunload = function() { return "If you leave this page, you will lose any unsaved changes."; } Or stackoverflow style: "You have started writing or editing a post." A: Use onunload. For jQuery, I think this works like so: $(window).unload(function() { alert("Unloading"); return falseIfYouWantToButBeCareful(); }); A: If you are catching a browser back/forward button and don't want to navigate away, you can use: window.addEventListener('popstate', function() { if (window.location.origin !== 'http://example.com') { // Do something if not your domain } else if (window.location.href === 'http://example.com/sign-in/step-1') { window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked } else if (window.location.href === 'http://example.com/sign-in/step-2') { window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked } else { // Let it do its thing } }); Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt. A: Unlike other methods presented here, this bit of code will not cause the browser to display a warning asking the user if he wants to leave; instead, it exploits the evented nature of the DOM to redirect back to the current page (and thus cancel navigation) before the browser has a chance to unload it from memory. Since it works by short-circuiting navigation directly, it cannot be used to prevent the page from being closed; however, it can be used to disable frame-busting. (function () { var location = window.document.location; var preventNavigation = function () { var originalHashValue = location.hash; window.setTimeout(function () { location.hash = 'preventNavigation' + ~~ (9999 * Math.random()); location.hash = originalHashValue; }, 0); }; window.addEventListener('beforeunload', preventNavigation, false); window.addEventListener('unload', preventNavigation, false); })(); Disclaimer: You should never do this. If a page has frame-busting code on it, please respect the wishes of the author. A: The equivalent in a more modern and browser compatible way, using modern addEventListener APIs. window.addEventListener('beforeunload', (event) => { // Cancel the event as stated by the standard. event.preventDefault(); // Chrome requires returnValue to be set. event.returnValue = ''; }); Source: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload A: Using onunload allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload will interrupt navigation: window.onbeforeunload = function() { return ""; } Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden. In older browsers you could specify the message to display in the prompt: window.onbeforeunload = function() { return "Are you sure you want to navigate away?"; } A: I ended up with this slightly different version: var dirty = false; window.onbeforeunload = function() { return dirty ? "If you leave this page you will lose your unsaved changes." : null; } Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt. With the text in the selected answer you see redundant prompts: A: If you need to toggle the state back to no notification on exit, use the following line: window.onbeforeunload = null;
Q: Real-time pipeline for processing data, insert into PSQL I have files that will be coming in daily that I would like to process as they come in and insert into existing sql tables (using postgres). What is the best way to create an automated pipeline? I have already written the file processing scripts on python which return the data in format to be appended to the sql tables. What is the best way to make this pipeline real-time. That is, have the pipeline automatically process the file as its sent to me and then have the data added to the sql table. At the moment i am doing this manually by batch but i want to fully automate the process. The key missing step is having the file automatically processed by the scrip. I am reading Apache kafka can help but I'm still a novice here. Any help is much appreciated! A: Alternatively, you can use the JDBC sink Connector. It will deliver data from kafka to postgresql in real time. It is possible to achieve idempotent writes with upserts. Auto-creation of tables and limited auto-evolution is also supported. good connector description ; config-options In fact, the above connector will subscribe to a kafka topic and send kafka messages to the database table in the stream. You can also subscribe to multiple topics. minimum configuration example { "name": "name_connector", "connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector", "value.converter": "io.confluent.connect.avro.AvroConverter", "topics": [ "topic_name" ], "connection.url": "postgresql://log:pass@hostname:5432/db", "dialect.name": "PostgreSqlDatabaseDialect", "insert.mode": "INSERT", "batch.size": "10", "table.types": [ "table" ], "auto.create": true }
Q: Debian 8.3.0 - PXE installer asking for CDROM? I'm sure I'm missing something easy, but I can't think of what it is. I used Cobbler to import Debian 8.3.0, but when I attempt to install it on a machine attached to the network, the installer asks for a CDROM, fails to find it, and quits. Does anyone know what I need to tweak in the preseed file or the kernel parameters to tell it to find its install files on a network path? A: You need to provide your kernel with the installer in TFTP for the netboot initrd image and point it to the preseed file. In my TFTP I have got in my default menu debian-installer/amd64/boot-screens/adtxt.cfg: menu label ^Automated install kernel debian-installer/amd64/linux append auto=true priority=critical vga=788 initrd=debian-installer/amd64/initrd.gz \ --quiet auto=true layoutcode=pt language-name=English ask_detect=false \ default_filesystem=ext3 url=http://10.10.x.x/preseed/preseed.cfg Be sure to change it for your keyboard locale, language, your root default filesystem, and the IP/URL of your web server providing your preseed file. I will leave here a link for the Official Debian guide. PXEBootInstall As for the preseed file: d-i mirror/country string US d-i mirror/http/hostname string http.us.debian.org d-i mirror/http/directory string /debian d-i mirror/http/mirror string ftp.us.debian.org d-i mirror/suite string jessie
Q: Почему при редактировании word из ASP.Net портится документ? Есть приложение на ASP.NET с формой для выбора значений из базы. При отправке формы эти поля и связные с ним заполняются в шаблон договора при помощи NPOI. Опытным путём пришел к выводу, что документ портится при вставке в таблицу пустого значения вот на вот этом месте: XWPFTable t = doc.GetTable((CT_Tbl)o); foreach (XWPFTableRow row in t.Rows) { foreach (XWPFParagraph p in row.GetCell(1).Paragraphs) { for (int k = 0; k < 16; k++) { if (p.Text.IndexOf("#" + keys[k] + "#") > -1) { if (k == 0) p.ReplaceText("#" + keys[k] + "#", podpisantOG); } } } } Переписал немного код, чтобы при пустом значении поля метка заменялась на пробел (т.к. метку необходимо стереть в любом случае), но документ всё равно портится. Если значение есть - заменяется без проблем. Подскажите, почему так и можно ли как то просто стереть значение? Вот так выглядит код сейчас: XWPFTable t = doc.GetTable((CT_Tbl)o); foreach (XWPFTableRow row in t.Rows) { foreach (XWPFParagraph p in row.GetCell(1).Paragraphs) { for (int k = 0; k < 16; k++) { if (p.Text.IndexOf("#" + keys[k] + "#") > -1) { if (podpisantOG != "null") { if (k == 0) p.ReplaceText("#" + keys[k] + "#", podpisantOG); } else { if (k==0) p.ReplaceText("#" + keys[k] + "#", " "); } } } } } A: Ошибка происходит, если пытаться отредактировать уже созданный файл. Если прочитать файл в переменную, а потом создать новый файл куда записать отредактированный текст, ошибок не возникнет.
Q: Wrong extended characters are represented I couldn't find any related answer to my question and I want to have a string like "╔══╗" but wrong characters are represented instead of them. I found the issue and that was because of signed characters and that values of each character is different with ascii table value of element. How can I do that with char in c++? int main() { char a[] = "╔══╗"; std::cout << a << std::endl; } A: use std::wstring(included in <string>) and L"...": #include <string> int main(/**/) { std::wstring wstr = L"╔══════════════╗"; } NOTE: There is no good cross-platform way of printing such a string. See How to print a wstring?, How to print a wstring on MacOs or Unix?, C++ wide character locale doesn't work.
Q: How to add two appbars in one screen? For now, I have this: I want to achieve this design: This is my code: import 'package:braintrinig/animation/LongBreak.dart'; import 'package:braintrinig/animation/ShortBreak.dart'; import 'package:braintrinig/animation/StartPomodoro.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class HomePageTimerUI extends StatelessWidget { bool PomoRed = false; bool ShortYellow = false; bool LongBlue = false; @override Widget build(BuildContext context) { return Container( height: 600, width: double.infinity, child: DefaultTabController( length: 3, child: Scaffold( bottomNavigationBar: BottomBar(), appBar: AppBar( elevation: 1.0, backgroundColor: Colors.transparent, bottom: PreferredSize( preferredSize: Size.fromHeight(55), child: Container( color: Colors.transparent, child: SafeArea( child: Column( children: <Widget>[ TabBar( indicator: UnderlineTabIndicator( borderSide: BorderSide( color: Color(0xff3B3B3B), width: 4.0), insets: EdgeInsets.fromLTRB( 12.0, 12.0, 12.0, 11.0)), indicatorWeight: 15, indicatorSize: TabBarIndicatorSize.label, labelColor: Color(0xff3B3B3B), labelStyle: TextStyle( fontSize: 12, letterSpacing: 1.3, fontWeight: FontWeight.w500), unselectedLabelColor: Color(0xffD7D7D7), tabs: [ Tab( text: "POMODORO", icon: Icon(Icons.work_history, size: 40), ), Tab( text: "SHORT BREAK", icon: Icon(Icons.ramen_dining, size: 40), ), Tab( text: "LONG BREAK", icon: Icon(Icons.battery_charging_full_rounded, size: 40), ), ]) ], ), ), ), ), ), body: TabBarView( children: <Widget>[ Center( child: StartPomodoro(), ), Center( child: ShortBreak(), ), Center( child: LongBreak() ), ], )))); } } class BottomBar extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.fromLTRB(20, 20, 20, 20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ FloatingActionButton.extended( backgroundColor: Color(0xffF2F2F2), onPressed: () {}, icon: Icon(Icons.settings, color: Color(0xff3B3B3B),), label: Text("Settings", style: TextStyle(color: Color(0xff3B3B3B), ),)), FloatingActionButton.extended( backgroundColor: Color(0xffF2F2F2), onPressed: () {}, icon: Icon(Icons.show_chart, color: Color(0xff3B3B3B),), label: Text("Performance", style: TextStyle(color: Color(0xff3B3B3B), ),)) ], ), ); } } I tried to copy and paste the app bar code below, but nothing happens, maybe because it has two containers, even fixed the height it doesn't work, I decided to post this question and save some time, thanks to you guys :) So, how to fix this issue?, thank you in advance A: You can use BottomNavigationBar to achieve this. Check for more info : https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html
Q: Can @supports in CSS be used to distinguish between Chrome and Android? I've successfully used CSS @supports to distinguish between iOS and Android on mobile devices with: @supports (-webkit-overflow-scrolling: touch) I would like to distinguish between Android and Chrome in a similar way, in order to distinguish an Android high resolution device in landscape orientation from a desktop layout with the Chrome browser. (Note: I'm using orientation in the @media query to successfully tell if a device is portrait or landscape. However I still have the problem of a high res device in landscape mode using the desktop layout, and it does not fit on the screen. If I can distinguish, I can use a different layout.)
Q: How to push the values into array with key name using node.js to construct a json I have a node js code with variables: var elements = []; var subelement1 = {}; var subelement2 = {}; How to construct the json with the structure as following: { "elements":[ "subelement1" :{}, "subelement2" :{} ] } A: To combine them, set each "sub" object to a property of the main: elements.subelement1 = subelement1; elements.subelement2 = subelement2; Then, you can stringify them with the surrounding object: var json = JSON.stringify({ elements: elements }); Though, with named keys, you'll want to use an Object. var elements = {}; { "elements": { "subelement1": {}, "subelement2": {} } } While Arrays can have named properties, they can't be given within a literal. var foo = []; foo.bar = 'baz'; And won't be acknowledged/counted like numeric indexes. console.log(foo.bar); // "baz" console.log(foo.length); // 0 foo[0] = 'qux'; console.log(foo.length); // 1
Q: Issue when calling from Fiori Launchpad a flavor based on main menu Experimenting with Fiori Lauchpad and have already deployed a few tiles based on Personas flavors, most of them using a generic invocation (calling transaction /personas/launch and passing as parameter the flavor ID), all of them work. Just tried to add another tile, passing as parameter a flavor based on the SAP main menu (SMEN). As soon as I click the tile, I get the message "Transaction SMEN is locked", something of course that does not apply, since I can use the flavor normally and it's (apparently) unlocked when viewing via SM01. Any ideas? A: Answer below "Check whether the following KBA applies to your case: 2786421 - Fiori Launchpad Tile to launch Backend transaction SMEN no longer works" Personas/health reports all green but seems that this is not classified as a personas issue
Q: pthread_kill() with invalid thread I'd like to determine if a particular thread 'exists'. pthread_kill() appears to be suited to this task, at least according to its man page. If sig is 0, then no signal is sent, but error checking is still performed. Or, as my system's man page puts it: If sig is 0, then no signal is sent, but error checking is still performed; this can be used to check for the existence of a thread ID. However when I attempt to pass in an uninitialized pthread_t, the application invariably SEGFAULTs. Digging into this, the following snippet from pthread_kill.c (from my toolchain) appears to do no error checking, and simply attempts to de-reference threadid (the de-reference is at pd->tid). int __pthread_kill (threadid, signo) pthread_t threadid; int signo; { struct pthread *pd = (struct pthread *) threadid; /* Make sure the descriptor is valid. */ if (DEBUGGING_P && INVALID_TD_P (pd)) /* Not a valid thread handle. */ return ESRCH; /* Force load of pd->tid into local variable or register. Otherwise if a thread exits between ESRCH test and tgkill, we might return EINVAL, because pd->tid would be cleared by the kernel. */ pid_t tid = atomic_forced_read (pd->tid); if (__builtin_expect (tid <= 0, 0)) /* Not a valid thread handle. */ return ESRCH; We can't even rely on zero being a good initializer, because of the following: # define DEBUGGING_P 0 /* Simplified test. This will not catch all invalid descriptors but is better than nothing. And if the test triggers the thread descriptor is guaranteed to be invalid. */ # define INVALID_TD_P(pd) __builtin_expect ((pd)->tid <= 0, 0) Additionally, I noticed the following in the linked man page (but not on my system's): POSIX.1-2008 recommends that if an implementation detects the use of a thread ID after the end of its lifetime, pthread_kill() should return the error ESRCH. The glibc implementation returns this error in the cases where an invalid thread ID can be detected. But note also that POSIX says that an attempt to use a thread ID whose lifetime has ended produces undefined behavior, and an attempt to use an invalid thread ID in a call to pthread_kill() can, for example, cause a segmentation fault. As outlined here by R.., I'm asking for the dreaded undefined behavior. It would appear that the manual is indeed misleading - particularly so on my system. * *Is there a good / reliable way to ask find out if a thread exists? (presumably by not using pthread_kill()) *Is there a good value that can be used to initialize pthread_t type variables, even if we have to catch them ourselves? I'm suspecting that the answer is to employ pthread_cleanup_push() and keep an is_running flag of my own, but would like to hear thoughts from others. A: I think I've come to a realisation while driving home, and I suspect that many others may find this useful too... It would appear that I've been treating the worker (the thread), and the task (what the thread is doing) as one and the same, when in fact, they are not. As I've already established from the code snippets in the question, it is unreasonable to ask "does this thread exist" as the pthread_t is likely just a pointer (it certainly is on my target). It's almost certainly the wrong question. The same goes for process IDs, file handles, malloc()'d memory, etc... they don't use unique and never repeating identifiers, and thus are not unique 'entities' that can be tested for their existence. The suspicions that I raised in the question are likely true - I'm going to have to use something like an is_running flag for the task (not thread). One approach that I've thought about is to use a semaphore initialized to one, sem_trywait(), sem_post() and pthread_cleanup_push(), as in the example below (cleanup missing for brevity). #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <semaphore.h> #include <pthread.h> struct my_task { sem_t can_start; pthread_t tid; /* task-related stuff */ }; void *my_task_worker(void *arg) { struct my_task *task = arg; pthread_cleanup_push(sem_post, &(task->can_start)); fprintf(stderr, "--- task starting!\n"); usleep(2500000); fprintf(stderr, "--- task ending!\n"); pthread_cleanup_pop(1); return NULL; } void my_task_start(struct my_task *task) { int ret; ret = sem_trywait(&(task->can_start)); if (ret != 0) { if (errno != EAGAIN) { perror("sem_trywait()"); exit(1); } fprintf(stderr, ">>> task already running...\n"); return; } ret = pthread_create(&(task->tid), NULL, my_task_worker, task); if (ret != 0) { perror("pthread_create()"); exit(1); } fprintf(stderr, ">>> started task!\n"); return; } int main(int argc, char *argv[]) { int ret; struct my_task task; int i; memset(&task, 0, sizeof(0)); ret = sem_init(&(task.can_start), 0, 1); if (ret != 0) { perror("sem_init()"); return 1; } for (i = 0; i < 10; i++) { my_task_start(&task); sleep(1); } return 0; } Output: >>> started task! --- task starting! >>> task already running... >>> task already running... --- task ending! >>> started task! --- task starting! >>> task already running... >>> task already running... --- task ending! >>> started task! --- task starting! >>> task already running... >>> task already running... --- task ending! >>> started task! --- task starting!
Q: My images code does not working in Visual Studio 2019 I am a newbie in coding and I try to find out what makes my HTML images idle? Can you have a look for this? <p> My Most Favorite Plantnete - Uranus img src "Uranus2.png" alt "Uranus" id "Pic3" </p> A: You need to edit this into: <p>My Most Favorite Planet - Uranus <img src="Uranus2.png" alt="Uranus" id="Pic3"> </p>
Q: Using Moq to mock a repository that returns a value How do I set up my test method on that mocks a repository which accepts an object? This is what I have so far: Service.cs public int AddCountry(string countryName) { Country country = new Country(); country.CountryName = countryName; return geographicsRepository.SaveCountry(country).CountryId; } test.cs [Test] public void Insert_Country() { //Setup var geographicsRepository = new Mock<IGeographicRepository>(); geographicsRepository.Setup(x => x.SaveCountry(It.Is<Country>(c => c.CountryName == "Jamaica"))); //How do I return a 1 here? GeographicService geoService = new GeographicService(geographicsRepository.Object); int id = geoService.AddCountry("Jamaica"); Assert.AreEqual(1, id); } SaveCountry(Country country); returns an int. I need to do 2 things: * *First test, I need to tell the setup to return an int of 1. *I need to create a second test Insert_Duplicate_Country_Throws_Exception(). In my Setup, how do I tell the repository to throw an error when I do: int id = geoService.AddCountry("Jamaica"); int id = geoService.AddCountry("Jamaica"); Framework: * *NUnit. *Moq. *ASP.NET MVC - repository pattern. A: Your first test should look something like this: [Test] public void Insert_Country() { Mock<IGeographicRepository> geographicsRepository = new Mock<IGeographicRepository>(); GeographicService geoService = new GeographicService(geographicsRepository.Object); // Setup Mock geographicsRepository .Setup(x => x.SaveCountry(It.IsAny<Country>())) .Returns(1); var id = geoService.AddCountry("Jamaica"); Assert.IsInstanceOf<Int32>(id); Assert.AreEqual(1, id); geographicsRepository.VerifyAll(); } The second test should look like this: [Test] public void Insert_Duplicate_Country_Throws_Exception() { Mock<IGeographicRepository> geographicsRepository = new Mock<IGeographicRepository>(); GeographicService geoService = new GeographicService(geographicsRepository.Object); // Setup Mock geographicsRepository .Setup(x => x.SaveCountry(It.IsAny<Country>())) .Throws(new MyException()); try { var id = geoService.AddCountry("Jamaica"); Assert.Fail("Exception not thrown"); } catch (MyException) { geographicsRepository.VerifyAll(); } } A: I think maybe you are slightly misunderstanding the purpose of testing with mocks in the two scenarios you have supplied. In the first scenario, you wish to test that 1 is returned when you pass in "Jamaica". This is not a mock test case but a test case for real behaviour as you wish to test a specific input against an expected output i.e. "Jamaica" -> 1. In this situation mocking is more useful to ensure that internally your service calls SaveCountry on the repository with the expected country, and that it returns the value from the call. Setting up your "SaveCountry" case and then calling "VerifyAll" on your mock is the key. This will assert that "SaveCountry" was indeed called with country "Jamaica", and that the expected value is returned. In this way you have confidence that your service is wired up to your repository as expected. [Test] public void adding_country_saves_country() { const int ExpectedCountryId = 666; var mockRepository = new Mock<IGeographicRepository>(); mockRepository. Setup(x => x.SaveCountry(It.Is<Country>(c => c.CountryName == "Jamaica"))). Returns(ExpectedCountryId); GeographicService service= new GeographicService(mockRepository.Object); int id = service.AddCountry(new Country("Jamaica")); mockRepo.VerifyAll(); Assert.AreEqual(ExpectedCountryId, id, "Expected country id."); } In the second scenario you wish to test that an exception is raised when you attempt to add a duplicate country. There's not much point in doing this with a mock as all you will test is that your mock has behaviour when adding duplicates, not your real implementation.
Q: Microsoft Excel Power Query Expression Error (overflow error) I couldn't find this issue elsewhere on stackoverflow, so here goes: I am loading a table (named DataEntry3, approx 10K rows and 30 columns) from the same workbook into Power Query, but it is throwing the following error message: [Expression.Error] An error occurred while accessing table DataEntry3 because it contains overflow errors. Please fix the errors and try again. I'm confused since this is a fairly routine operation. Any ideas as to what might be going on? A: Do you have any large numbers in your dataset? This can occur if a large number is mistakenly formatted as a date in Excel. I would check if giving a stronger type (Text or Number) to the columns resolves this issue. A: Coming late but might help someone else. Had this same problem and discovered that the Source location for the file was wrong (internal network changes and drive names changed) Fixing this fixed the problem. A: In my case it was a formatting issue. I used format painter for the new lines that were added to my source table and that fixed the problem.
Q: Why does my internet connection fail intermittently? On my laptop, my internet connection fails now and again. I'll go to a web page (Let's say Google) and I'll get page not found. I'll then sit and press F5 to refresh the page until eventually after a minute or so it'll suddenly work. All will be well for a while after that until suddenly it'll happen again. Now, there are some peculiarities to this problem... * *This only happens on one laptop. My work laptop on the same wifi network always seems to be fine, as does my XBox. *If I'm downloading a large file, the download continues even while I'm failing to bring up web pages. *Sometimes I can get some pages, and not others. Sometimes I can get partial pages. My limited knowledge of such things seems to suggest some kind of DNS lookup problem, albeit one that's confined to one laptop. Does this sound remotely possible? Is there something I may have missed here? Oh, and I'm on Windows Vista, in case that matters. A: The university of Berkeley has a website that will analyze all sorts of aspects of your Internet connection such as DNS, ports, upload/download speed etc. It will report anomalies to you. It is here: http://n1.netalyzr.icsi.berkeley.edu/ A: It sounds a lot like a DNS problem, considering downloads do not drop out and it only affects one laptop on the same wirless network. I would try different DNS servers. I had a similar problem once and it turned out to be that my ISP's DNS servers were crappy (but that affected everybody on my network). A: I was having this issue on Windows 7 with a RealTek wireless card. Reinstalling drivers for the wireless adaptor (and numerous other attempts at a solution) didn't fix the problem. On a whim, I disabled 802.11N on the wireless adapter properties (reverted to G and B only) and it started working! My intermittent network drops (connected but no internet access) went away. A: Does this happen when you are idle? Are your IP's static or do you do DHCP? Is the power management savings setting on the network cards disabled, or do you have the network card set to shut off to save power? My guess - you have DHCP and the network card of the laptop powers off to save power. The DHCP server then doesn't see you and drops your IP info. If you keep trying to reconnect, eventually you will assigned a new address once the network card wakes back up and requests one. That in turn will allow you to get out. As far as a transfer occurring even while you can't browse, I'm not sure, but if you have already established the download and the session already exists, the router/switch should have a memory of your old MAC address in the tables. I'm guessing (any network specialist here?) any incoming packet pointing to your session should still be able to go through since once it comes in to your router, it will go out to your MAC and not depend on IP addressing. A: You don't say what browser you're running but I'll guess it's firefox. Firefox recently changed how it handles DNS - it's got this new "prefetch" logic that can sometimes totally overload things. https://developer.mozilla.org/en/controlling_dns_prefetching Here's additional information on things that can go wrong with ff and dns: http://kb.mozillazine.org/Error_loading_any_website A: Have you tried following the openDNS guide here, to make sure it's not a DNS issue? I used to get this all the time, but since switching they've gone away. A: It probably is a DNS problem, but your local DNS cache may be broken, you may not have a plug in (for some of the pages) or a problem may exist with your browser. A: Don't rule out the possibility it could be hardware related. I had the same problem with my ISP provided router. Till I went out and bought my own... now problem is fixed... A: From the command line (assuming the various computers are all versions of Windows 2000 or higher) type this command on each computer: ipconfig /all I'm betting that the 'problem' laptop will have different DNS settings than your other computers. To resolve this on Vista follow these instructions: * *Go to the Start Menu. *Type the word Network, and select Network and Sharing Center. *On the left, click Manage network connections. *Right-click on your wired or wireless network connection icon, and choose Properties. *Highlight the line labeled Internet Protocol Version 4 (TCP/IPv4) and click Properties. *Change the DNS servers back to Automatic, or manually type in the DNS servers appropriate for your network. A: Set the power saving mode of your WLAN adapter to OFF or CAM (constantly awake mode). A: It's 2020 and this problem still occurs sometimes. I have 2 desktops and 1 laptop, and I encountered the issue on 2 out of 3 devices when I first installed Windows 10 in the past 2 years. The browsers are not loading any pages, saying there is no internet connection, but in the background I was downloading games on Steam at full speed... so I had internet connection... meaning that only a port is blocked or something, typically 80 or 443. First culprit was the firewall software or the antivirus... I reinstalled it and also updated the network card driver and it worked... so I guess here is the problem.
Q: Indicator menu from gtk.Builder ui string I've created an indicator that I think should work, but doesn't. I've added the UI interface from a glade file, loaded it and added the menu to appindicator. The following is the entire source code beginning with the XML. Is there any reason why this shouldn't work? #!/usr/bin/env python #coding: utf-8 import gtk import sys import appindicator MENU_DEFINITION = """ <?xml version="1.0" encoding="UTF-8"?> <interface> <requires lib="gtk+" version="2.24"/> <!-- interface-naming-policy project-wide --> <object class="GtkMenu" id="jes_test_menu"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkCheckMenuItem" id="show_dialog"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_action_appearance">False</property> <property name="label" translatable="yes">Show dialog</property> <property name="use_underline">True</property> <signal name="toggled" handler="on_show_dialog_toggled" swapped="no"/> </object> </child> <child> <object class="GtkMenuItem" id="new_events"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_action_appearance">False</property> <property name="label" translatable="yes">New events</property> <property name="use_underline">True</property> <signal name="activate-item" handler="on_new_events_activate_item" swapped="no"/> <signal name="activate" handler="on_new_events_activate" swapped="no"/> </object> </child> <child> <object class="GtkMenuItem" id="exit_indicator"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_action_appearance">False</property> <property name="label" translatable="yes">Exit indicator</property> <property name="use_underline">True</property> <signal name="activate-item" handler="on_exit_indicator_activate_item" swapped="no"/> <signal name="activate" handler="on_exit_indicator_activate" swapped="no"/> </object> </child> </object> </interface> """ class JesTestMenu: def __init__(self): ui = gtk.Builder() ui.add_from_string(MENU_DEFINITION) ui.connect_signals(self) menu = ui.get_object("jes_test_menu") ind = appindicator.Indicator("jes_test_menu", "indicator-messages", appindicator.CATEGORY_APPLICATION_STATUS) ind.set_status(appindicator.STATUS_ACTIVE) ind.set_attention_icon("new-messages-green") ind.set_menu(menu) menu.show_all() print("Indicator should now be visible") def on_exit_indicator_activate_item(self, widget, data=None): print("Exit activate item") sys.exit() def on_exit_indicator_activate(self, widget, data=None): print("Exit activate") sys.exit() def on_new_events_activate_item(self, widget, data=None): pass def on_new_events_activate(self, widget, data=None): pass def on_show_dialog_toggled(self, widget, data=None): pass if __name__ == "__main__": menu = JesTestMenu() gtk.main() A: The problem is that your Indicator object (ind) is not a class variable, it's scope is only in the __init__ function. This means it is being destroyed by Python's garbage collection once your class finishes initation. To fix this, replace ind with self.ind: self.ind = appindicator.Indicator("jes_test_menu", "indicator-messages", appindicator.CATEGORY_APPLICATION_STATUS) self.ind.set_status(appindicator.STATUS_ACTIVE) self.ind.set_attention_icon("new-messages-green") self.ind.set_menu(menu)
Q: Routes are giving me the hardest time right now I'm working through a ton of ruby tutorials right now, and am having the hardest time figuring out the whole Routes thing. For instance, I mostly understand the paperclip file upload, but what I'm getting hung up on is the way the images are displayed. I know the problem is in the way the Routes are being routed, but can't quite grasp the exact syntax. Perhaps someone can help explain this to me. Example: This is the code for one of my thumbnails: <% for photo in @user.photos %> <%= link_to image_tag(photo.photo.url(:small)), photo.photo.url(:standard)%> <% end %> and the link that is delivered is: localhost:3000/system/photos/29/standard/8.png?1306281491 So I know the timestamp is at the end of the url, but what I want is a link like this: localhost:3000/users/1/photos/29 Help! and thanks :) A: Run rake routes command and you will see all routes defined in your application. Among them, you will see something like: user_photo GET /users/:user_id/photo/:id(.:format) {:action=>"show", :controller=>"photos"} So, to get /users/1/photos/29, you need to call method user_photo_path(user_obj, photo_obj) I advise you to read rails routing guide
Q: Create Boundary for box2D world object I have used box2D to make physics effect and here is my set of code public class Main extends SpriteVisualElement { public var world:b2World; public var wheelArray:Array; public var stepTimer:Timer; public var scaleFactor:Number = 20; public function Main() { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); getStarted(); } private function getStarted():void { var gravity:b2Vec2 = new b2Vec2(0, 10); world = new b2World(gravity, true); wheelArray = new Array(); for (var i:int = 0; i < 20; i++) { createWheel( Math.random() * 0.5, Math.random() * (stage.stageWidth - 20) + 10, Math.random() * (stage.stageHeight - 20) + 10, (Math.random() * 100) - 50, 0 ); } createBoundaries(); stepTimer = new Timer(0.025 * 1000); stepTimer.addEventListener(TimerEvent.TIMER, onTick); graphics.lineStyle(3, 0xff0000); stepTimer.start(); } private function createBoundaries():void { trace(this.height,this.width,stage.height,stage.width); // need some code here } protected function onTick(event:TimerEvent):void { graphics.clear(); graphics.lineStyle(3, 0xff0000); world.Step(0.025, 10, 10); for each (var wheelBody:b2Body in wheelArray) { graphics.drawCircle( wheelBody.GetPosition().x * scaleFactor, wheelBody.GetPosition().y * scaleFactor, (wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius() * scaleFactor ); } } private function createWheel(radius:Number, startX:Number, startY:Number, velocityX:Number, velocityY:Number):void { var wheelBodyDef:b2BodyDef = new b2BodyDef(); wheelBodyDef.type = b2Body.b2_dynamicBody; wheelBodyDef.position.Set(startX / scaleFactor, startY / scaleFactor); var wheelBody:b2Body = world.CreateBody(wheelBodyDef); var circleShape:b2CircleShape = new b2CircleShape(radius); var wheelFixtureDef:b2FixtureDef = new b2FixtureDef(); wheelFixtureDef.shape = circleShape; wheelFixtureDef.restitution = (Math.random() * 0.5) + 0.5; wheelFixtureDef.friction = (Math.random() * 1.0); wheelFixtureDef.density = Math.random() * 20; var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef); var startingVelocity:b2Vec2 = new b2Vec2(velocityX, velocityY); wheelBody.SetLinearVelocity(startingVelocity); wheelArray.push(wheelBody); } } } and i have add this to the main view like this var main:Main = new Main(); this.addElement(main); it works but problem in detecting the boundary of the stage. Objective: i want to set the boundary, so any help ... A: Box2D doesn't have a 'boundary'-system as such, you have to * *create bodies/body and place it where you want your boundaries *Another thing you have to be aware of is tunneling. You have to deal with it properly so that no object will pass trough the boundaries. One thing you can do is setting the bullet-flag of fast moving objects to true.
Q: Rotating a plane around a pivot point located at one of it's corner points and around an axis... I have a plane and want to rotate around a pivot point located at one of its corner points and around a axis which is orthogonal to its diagonal at a given angle. So I have a right triangle along the diagonal of the plane. How could i find the angle of another right triangle also orthogonal to the plane along one oft the planes sides? So how are the angle related two each other? I guess it has something to do with the dot product of the two vectors of the adjacent sides of both triangles, but couldnt find out how. I hope the image describes it better then my words :) Thanks.
Q: EF adds another entry when saving context changes even if it exists public class Parent { public int ID; public string Name; public int Child_ID; public Child Child; } public class Child { public int ID; public string Name; public int Parent_ID; public Parent Parent; } I have a little issue with ef when it comes to the folowing scenario: I added a parent with a child but if I extract a Child c (with c.Parent == null) and then it's Parent p (2 queries) and then do: Child.Parent = p; context.SaveChanges(); It will add a new Parent in the database even if p exists. Is there a way to override this behavior? A: Probably you are working with a detached entity. If you don't get the parent entity from the same instance of your constext, when you assign the Parent to the Child instance, EF considers this to be an unrecognized entity and its default behavior for unrecognized entities with no state is to mark them as Added. So, again, the Parent will be inserted into the database when SaveChanges is called. To resolve that problem, try this: context.Parents.Attach(p); Child.Parent = p; context.SaveChanges(); Alternatively, in place of context.Parents.Attach(p), you could set the state of the Parent before or after the fact, explicitly setting its state to Unchanged: context.Entry(p).State = EntityState.Unchanged; If you want to learn more about this topic, I suggest you read this article
Q: NavigationLink dismisses after TextField changes I have a navigation stack that's not quite working as desired. From my main view, I want to switch over to a list view which for the sake of this example represents an array of strings. I want to then navigate to a detail view, where I want to be able to change the value of the selected string. I have 2 issues with below code: * *on the very first keystroke within the TextField, the detail view is being dismissed *the value itself is not being changed Also, I suppose there must be a more convenient way to do the binding in the detail view ... Here's the code: import SwiftUI @main struct TestApp: App { var body: some Scene { WindowGroup { TestMainView() } } } struct TestMainView: View { var body: some View { NavigationView { List { NavigationLink("List View", destination: TestListView()) } .navigationTitle("Test App") } } } struct TestListView: View { @State var strings = [ "Foo", "Bar", "Buzz" ] @State var selectedString: String? = nil var body: some View { List(strings.indices) { index in NavigationLink( destination: TestDetailView(selectedString: $selectedString), tag: strings[index], selection: $selectedString) { Text(strings[index]) } .navigationBarTitleDisplayMode(.inline) .navigationTitle("List") } } } struct TestDetailView: View { @Binding var selectedString: String? var body: some View { VStack { if let _ = selectedString { TextField("Placeholder", text: Binding<String>( //what's a better solution here? get: { selectedString! }, set: { selectedString = $0 } ) ) .padding() .textFieldStyle(RoundedBorderTextFieldStyle()) } Spacer() } .navigationTitle("Detail") } } struct TestMainView_Previews: PreviewProvider { static var previews: some View { TestMainView() } } I am quite obviously doing it wrong, but I cannot figure out what to do differently... A: You're changing the NavigationLink's selection from inside the NavigationLink which forces the TestListView to reload. You can try the following instead: struct TestListView: View { @State var strings = [ "Foo", "Bar", "Buzz", ] var body: some View { List(strings.indices) { index in NavigationLink(destination: TestDetailView(selectedString: self.$strings[index])) { Text(self.strings[index]) } } } } struct TestDetailView: View { @Binding var selectedString: String // remove optional var body: some View { VStack { TextField("Placeholder", text: $selectedString) .padding() .textFieldStyle(RoundedBorderTextFieldStyle()) Spacer() } } }
Q: How can I use C to validate that the difference between two numbers is no more than X I've pasted some code below to give a brief outline of what I'm writing. I basically need to say that if the difference between presentMeterReading and currentMeterReading is > 1000.. give me an error. for example. printf("Usage is high at over 1000"); if (presentMeterReading < 0 || presentMeterReading > 9999) printf("That's out of range. Meter readings should be between 0 - 9999 \n"); if (previousMeterReading < presentMeterReading || presentMeterReading > previousMeterReading) printf("Present readings should not be more than previous readings."); if (dayReadingTaken > 12 || dayReadingTaken < 1) printf("That's not a valid month."); A: maths. #include <math.h> if (abs(presentMeterReading - currentMeterReading) > 1000) { /* too much difference */ }
Q: Stepwise Generalised Linear Model As a statistics student I am in search of R code for a GLM, which is calculated stepwise. So far, the best I've found is for a Poisson Regression, but I need to find a Gaussian version of this: library(MASS) poisreg = function(n, b1, y, x1, tolerence) { # n is the number of iterations x0 = rep(1, length(x1)) x = cbind(x0, x1) y = as.matrix(y) w = matrix(0, nrow = (length(y)), ncol = (length(y))) b0 = b1 result = b0 for (i in 1:n) { mu = exp(x %*% b0) diag(w) = mu eta = x %*% b0 z = eta + (y - mu) * (1/mu) # dot product of (y - mu) & (1/mu) xtwx = t(x) %*% w %*% x xtwz = t(x) %*% w %*% z b1 = solve(xtwx, xtwz) if(sqrt(sum(b0 - b1)^2) > tolerence) (b0 <- b1) result <- cbind(result,b1) # to get all the iterated values } result } x1 <- c(-1,-1,0,0,0,0,1,1,1) # x1 is the explanatory variable y <- c(2,3,6,7,8,9,10,12,15) # y is the dependent variable b1 = c(1,2) # initial value poisreg (10, b1, y, x1, .001) # Nicely converge after 10 iterations glm(y~x1, family=poisson(link="log")) # check your result with the R GLM program I'd be very grateful for any help in searching for code like this that calculates Gaussian GLM. If y you're interested: my ultimate aim is to play about with the tolerances of the GLM so that the fitted model lies between specified upper and lower bounds. A: I'm not sure why you're rolling your own code; stepwise regression is already available in R via the step function. This works with any specification of generalized linear model, including ordinary linear regression (which is what we usually call a Gaussian GLM). From the ?step examples: lm1 <- lm(Fertility ~ ., data = swiss)) slm1 <- step(lm1) # <...many lines of output...> summary(slm1) # Call: # lm(formula = Fertility ~ Agriculture + Education + Catholic + # Infant.Mortality, data = swiss) # # Residuals: # Min 1Q Median 3Q Max # -14.6765 -6.0522 0.7514 3.1664 16.1422 # # Coefficients: # Estimate Std. Error t value Pr(>|t|) # (Intercept) 62.10131 9.60489 6.466 8.49e-08 *** # Agriculture -0.15462 0.06819 -2.267 0.02857 * # Education -0.98026 0.14814 -6.617 5.14e-08 *** # Catholic 0.12467 0.02889 4.315 9.50e-05 *** # Infant.Mortality 1.07844 0.38187 2.824 0.00722 ** # --- # Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 # # Residual standard error: 7.168 on 42 degrees of freedom # Multiple R-squared: 0.6993, Adjusted R-squared: 0.6707 # F-statistic: 24.42 on 4 and 42 DF, p-value: 1.717e-10 On re-reading the question, maybe you're actually not asking about stepwise modelling at all. If you actually want to ask, why don't we have an interative algorithm for Gaussian GLMs, the answer is we don't need one! The usual algorithm for fitting a GLM, iterative (re)weighted least squares, works by fitting least-squares regressions for specially weighted and transformed versions of the data. If your model has a Gaussian error and identity link, then the weights and transformations disappear, so IRLS reduces to standard least squares. Hence you don't need to do any iterations.
Q: Delete a file downloaded by exo player download service I am using exo player download service to download video files in my android application. So far so good as downloading is very smooth and it provides forground notification also. Problem is with the deleting completed download as we are providing a feature for user to delete the file in the future if he wants. I didn't find any method to do so in download service and exoplayer is using some complex file structure to store the downloaded media file. Any help is appreciated. A: You can use for example DownloadService's: DownloadService.sendRemoveDownload(context, MyDownloadService.class, download.request.id, false); or DownloadManager's removeDownload(String id) method.
Q: Input checkbox & ion-checkbox boxs checked even though value is false This is driving me crazy. I am almost thinking this is a bug at this point. When a page loads the controller, it checks for window.localStorage values...if not set it then sets the defaults. If set, then set the checkbox's to true or false based on the saved value. But even after a fresh install, I go to the tab, see the console.log values for the checkboxes as "false", yet both checkboxes are CHECKED. I started with ion-checkbox and when I couldn't correct the issue so I moved to a standard checkbox. But in both cases, console messages display "temp" as false, assign it to the $scope OR the getElementById (depending on which one I am using) and the rendered pages shows the checkbox's as checked. I even tried changing false to "" and true to "checked" - nothing changes though. HTML <ion-checkbox style="border:0px;float:right;padding-left:24px;padding-top:5px" ng-model="bikeItem.Avail" ng-checked="bikeItem.Avail" ng-change="bikes('Avail','checked',1)"></ion-checkbox> <input type="checkbox" id="bikesAvail" checked="{{bikeItem.Avail}}" style="border:0px;float:right;padding-left:24px;padding-top:5px" ng-click="bikes('Avail','checked',0)"></input> CONTROLLER: $scope.bikeItem = [] ; var bikeKeys = {Shub:"value",Ehub:"value",Avail:"checked",Spots:"checked"} ; var x=0 ; for (var keyObj in bikeKeys) { var key = keyObj ; var keyValue = bikeKeys[keyObj] ; var temp = window.localStorage.getItem("bikes"+key) ; if (temp == null || temp == "" || temp == "undefined") { if (x < 2) { temp = 3 ; } else if (x > 1) { temp = false ; } console.log("A Init: "+key + " :"+keyValue + ": " + temp) ; $scope.bikeItem[key] = temp ; window.localStorage.setItem("bikes"+key,temp) ; document.getElementById("bikes"+key)[keyValue] = temp ; console.log("B : "+document.getElementById("bikes"+key)[keyValue]) ; } else { console.log("C Init: "+key + " :"+keyValue + ": " + temp) ; $scope.bikeItem[key] = temp ; document.getElementById("bikes"+key)[keyValue] = temp ; console.log("D : "+document.getElementById("bikes"+key)[keyValue]) ; } x++ ; } The above console messages prints: "A Init: Avail: checked: false" "B : true" ; I mean, the two lines above console message B are stating the value is FALSE and assigning the $scope.bikeItem.Avail = false AND document.getElmentById("bikesAvail").checked = false ; - yet both types of checkboxes are getting assigned true and showing up checked. And when I leave the page and come back console messages C&D fire (because those values are now stored in localStorage), both show temp=false, yet the checkboxes are still checked. However, the correct values are being passed to the just fine. The first time load default is 3, leave the page and come back and they are three...users changes them to whatever, leave page and come back and the user value is showing. Its just the two checkbox's.
Q: How to recover an Android Studio project written in Kotlin from the apk I've finished the work on my Android app. for my university, and I havn't backed it up to git for 11 days because I've had no internet on my PC. I bought an SSD today, and amidst the data transfers, I'd somehow managed to delete my entire project (along with a whole semester's woth of work). I have found this post but it's for a project writen in Java. Is there a way to recover a project writen in Kotlin from the application's apk.?
Q: New laptop shuts down after seconds during POST, what can the cause be? My laptop will no longer start up. It will shut down itself after a few seconds during POST (and it is not related to the operating system (Linux, Fedora 14) in any way since the problem occurs also when the hard disk is removed). The laptop is fairly new (January 2011), based on Clevo B7130. There was no such problems in the beginning. Then one day it would not start up with the symptoms like I have recorded later. After some attempts I gave up. It started up fine later (probably the same day, but I do not remember for sure), so I assumed that it might have been a single occurrence problem. However, the problem occurred again after this, more and more frequently as time went on. While in the beginning of experiencing the problem I usually could get it started after several attempts, now it never will (unless if I wait a long time (days)). I have also experienced (three times I think) during normal usage that power have just gone. Anyone that have any ideas of what the problem might be? My suspicion is that it is related to the CPU fan, because when it fails to start up the fan is running at full speed making much noise. The few times it starts ok, the fan is not kicking in at full speed. I tried to detach it for testing, but then the laptop refused to start. However there might also not be something wrong with the actual fan (AB7505HX-GE3), could it be a bad temperature sensor, a BIOS/ACPI bug or a poor contact or shortcut on the PCB? A: if you are able to go into the bios then check out event log in the BIOS and see if there is any temp related event. and their you can also found any other hardware issue. and it is a really bad idea to run your laptop without CPU fan even for 10 sec. because one of my friend just burn his CPU in testing like you done in less then 10 sec. and ofcourse this type of act void the warranty also. A: I have now received the computer back from repair, a completely new unit, so I guess there will never be an answer to this. A: Probably, as you suspect, this is either a thermal problem (it may be that the sink under the fan isn't making good contact with the CPU, or an errant sensor, or something else) or an electrical problem somewhere on the motherboard. It could potentially be a problem with the battery or AC adapter - you can try removing one, then the other, and seeing if it helps. Regardless, you're better off getting it serviced by the manufacturer given its age.
Q: How do you append to a PDO resultset array or Json_encoded string? I want to add a bit more information to a json object before sending it back to my app. $sql = "SELECT * FROM users WHERE repo=?"; $q=$dbh->prepare($sql); $q->execute(array($repo)); $res = $q->fetchAll(PDO::FETCH_OBJ); $res['isnew']="1"; //this part isn't working echo '{"items":'. json_encode($res) .'}'; The PDO query returns a result set like this when I echo($res) Array{"items":[{"uid":"10","repo":"bnef"}]} then it gets encoded back to jquery- echo '{"items":'. json_encode($res) .'}'; giving me {"items":[{"uid":"10","repo":"bnef}]} I'd like to add "isnew":"1" to that but when I try $res['isnew']="1"; or array_merge I end up with {"items":{"0":{"uid":"10","repo":"bnef"},"isnew":"1"}} which doesn't work. I need {"items":[{"uid":"10","repo":"bnef, "isnew":"1"}]} Am I misguide in try to do this? A: I misread your question and got confused on the code... you shoudl incat be dealign with an array initially try the following: $sql = "SELECT * FROM users WHERE repo=?"; $q=$dbh->prepare($sql); $q->execute(array($repo)); $items = $q->fetchAll(PDO::FETCH_OBJ); // you actually wnt isnew as a property of each row // so you need to loop over the results foreach($items as $key => $item){ $item->isnew = 1; } echo json_encode(array( 'items' => $items )); $res = $q->fetchAll(PDO::FETCH_OBJ); $res['isnew']="1"; //this part isn't working Its not working because you used FETCH_OBJ instead of FETCH_ASSOC so youre wokring with an StdObject instance not an array. In that case you need to use -> to assign: $res = $q->fetchAll(PDO::FETCH_OBJ); $res->isnew = "1"; Alternatively you could fetch as an associative array: $res = $q->fetchAll(PDO::FETCH_ASSOC); $res['isnew']="1"; //this will work now Additionalyl i wouldnt try to manipulate the JSON serialized string. I would doo all modifications natively: $items = array( 'items' => $res ); echo json_encode($items);
Q: jsoup hasClass returns wrong result Help me please. I using a jsoup lib and its method hasClass. Why Cur returns "none!"? The source page: <body> <div class="pagenav" data-role="vbpagenav" data-pagenumber="2" data-totalpages="223" data-address="showthread.php?t=650495&amp;page=102" data-address2="" data-anchor=""> </div> </body> My code: Document doc = null; String result = ""; try { doc = Jsoup.connect(params[0]).get(); Elements body = doc.select("body"); /* Navigation */ String Cur = ""; if (body.hasClass("pagenav")) { Elements Current = body.select("div[data-pagenumber]"); String Cur1 = Current.attr("data-pagenumber"); int cur_page = Integer.parseInt(Cur1); int next_page = cur_page + 1; Cur = Integer.toString(next_page); } else { Cur = "none!"; } result = body.html() + Cur; } catch (IOException e) { e.printStackTrace(); } return result; A: You are using the method hasClass the wrong way. In your selection you create a collection Elements body that contains all the body tags as Element objects. public boolean hasClass(String className) will return a true or false as to whether any of your Element objects in your Elements body have the class name in their class attribute. Here you will see what is wrong, since your collection Elements body only contains all the body tags, and not their child nodes. None of your body tags have their class attribute set to pagenav, thus the hasClass() method will return false. To solve your problem, you will need to create a new collection Elements object for all the child nodes of the body tags, and then check whether or not they have the class attribute set to pagenav. Selecting the body tag your way would require a double loop, such as Elements body = doc.select("body"); Elements bodyChildren = new Elements(); for (Element e : body) { for (Element eChild : e.children()) { bodyChildren.add(eChild); } } if (bodyChildren.hasClass("pagenav")){... Though, since you can only have one body tag, it can be more effective to select it straight away as follows Element body = doc.select("body").first(); Elements bodyChildren = new Elements(); for (Element e : body.children()) { bodyChildren.add(e); } Both of above methods will return true when you run hasClass() on bodyChildren.
Q: Get the link of question and answer at user level using Stack Exchange API Based on my previous question, I am able to get the list of all unaccepted answers within a date range at the user level using Stack Exchange API with the following curl command : curl "https://api.stackexchange.com/2.2/users/10348758/answers?page=1&pagesize=100&fromdate=1588291200&todate=1592179200&order=desc&sort=activity&site=stackoverflow&access_token=my-access-token&key=my-key" | gunzip | jq '.items[] | select(.is_accepted == false)' The JSON response for the above command is something like this : { "owner": { "reputation": 1595, "user_id": 10348758, "user_type": "registered", "profile_image": "https://www.gravatar.com/avatar/01ccf806a00d7deb1bf15323bc3edbe8?s=128&d=identicon&r=PG&f=1", "display_name": "Bhavya", "link": "https://stackoverflow.com/users/10348758/bhavya" }, "is_accepted": false, "score": 0, "last_activity_date": 1592102481, "creation_date": 1592102481, "answer_id": 62367766, "question_id": 62367395, "content_license": "CC BY-SA 4.0" } In the above response, I am getting answer_id and question_id, the links to these answers and questions are not included in the response. By including &filter=withbody, in the curl command I am able to get the body of answer.The modified curl command is : curl "https://api.stackexchange.com/2.2/users/10348758/answers?page=1&pagesize=100&fromdate=1588291200&todate=1592179200&order=desc&sort=activity&site=stackoverflow&filter=withbody&access_token=my-access-token&key=my-key" | gunzip | jq '.items[] | select(.is_accepted == false)' Is there any way, I can get the links of the answer and question included in the response? I referred to these custom filters documentation, but I am not able to understand how to apply them. Can anyone help me with this? A: How about this answer? Your current situation is as follows. * *The retrieved values from your URL includes both answer_id and question_id. In this case, the URLs for answer and question can be created like https://stackoverflow.com/a/{answer_id} and https://stackoverflow.com/q/{question_id}, respectively. I have mentioned at here. *In your curl command, jq is used like jq '.items[] | select(.is_accepted == false)'. From above situation, in this answer, I would like to propose to add the URLs of answer and question to the retrieved values by adding parameter to jq. Modified jq command: In this case, the modified jq command is as follows. jq '[.items[] | select(.is_accepted == false) |= . + {"answerUrl": ("https://stackoverflow.com/a/" + (.answer_id|tostring)), "questionUrl": ("https://stackoverflow.com/q/" + (.question_id|tostring))}]' Modified curl command: When your curl command is modified, it becomes as follows. curl "https://api.stackexchange.com/2.2/users/10348758/answers?page=1&pagesize=100&fromdate=1588291200&todate=1592179200&order=desc&sort=activity&site=stackoverflow&filter=withbody&access_token=my-access-token&key=my-key" | gunzip | jq '[.items[] | select(.is_accepted == false) |= . + {"answerUrl": ("https://stackoverflow.com/a/" + (.answer_id|tostring)), "questionUrl": ("https://stackoverflow.com/q/" + (.question_id|tostring))}]' Result: When above modified curl command is run, the following result is retrieved. You can see the values of answerUrl and questionUrl in the result. [ { "owner": {###}, "is_accepted": false, "score": ###, "last_activity_date": ###, "creation_date": ###, "answer_id": ###, "question_id": ###, "content_license": "###", "answerUrl": "https://stackoverflow.com/a/###", <--- Added "questionUrl": "https://stackoverflow.com/q/###" <--- Added }, , , , ] References: * *Usage of /answers/{ids} *jq Added: When you want to include the title to the retrieved values, please use the custom filter as follows. Modified jq command: curl "https://api.stackexchange.com/2.2/users/10348758/answers?page=1&pagesize=100&fromdate=1588291200&todate=1592179200&order=desc&sort=activity&site=stackoverflow&access_token=my-access-token&key=my-key&filter=%21T%2AhPUiv_%28m%28rgrhfg_" | gunzip | jq '[.items[] | select(.is_accepted == false)]' * *In this case, the filter of filter=%21T%2AhPUiv_%28m%28rgrhfg_ is added as the query parameter. By this, the title is added. In this custom filter, title,link,.share_link are included. By this, the title, answer and question links are included in the returned values. So the command of jq can be simpler. Reference: * *Custom Filters
Q: How to debug the Linux kernel with QEMU and KGDB? I have been able to boot a powerpc based system (MPC8544DS to be specific) using the following way to invoke qemu (v1.7.0) qemu-system-ppc -M mpc8544ds -m 512 -kernel zImage -s -nographic -initrd busyboxfs.img -append "root=/dev/ram rdinit=/bin/sh kgdboc=ttyS0,115200 kgdbwait" where zImage is a custom cross compiled Linux Kernel (v2.6.32) which has KGDB enabled and compiled in (for startupcode debugging) and busyboxfs.img is the busybox based rootfs. Since I'm using the -s flag to Qemu, I can break-in to the kernel using cross gdb like so: (gdb) target remote localhost:1234 Remote debugging using localhost:1234 mem_serial_in (p=<value optimized out>, offset=5) at drivers/serial/8250.c:405 405 } However if I remove the -s flag and try to break in to the kernel over /dev/ttyS0 it gives me a permission denied error: (gdb) set remotebaud 115200 (gdb) target remote /dev/ttyS0 permission denied Is it because it has been held over by Qemu? Additionally in example across the internet, kgdboc has been set to ttyAMA0 which I've come to understand stands for the AMBAbus which is specific to ARM based systems. Do we have something similar for PowerPC? Am I doing something wrong here? A: KGDB + QEMU step-by-step First, QEMU's -gdb option is strictly more powerful than KGDB, so you might want to use that instead: How to debug the Linux kernel with GDB and QEMU? QEMU is however an easy way to play around with KGDB in preparation for real hardware. I have posted some Raspberry Pi KGDB pointers at: Linux kernel live debugging, how it's done and what tools are used? If you want to get started quickly from scratch, I've made a minimal fully automated Buildroot example at: https://github.com/cirosantilli/linux-kernel-module-cheat/tree/d424380fe62351358d21406280bc7588d795209c#kgdb The main steps are: * *Compile the kernel with: CONFIG_DEBUG_KERNEL=y CONFIG_DEBUG_INFO=y CONFIG_CONSOLE_POLL=y CONFIG_KDB_CONTINUE_CATASTROPHIC=0 CONFIG_KDB_DEFAULT_ENABLE=0x1 CONFIG_KDB_KEYBOARD=y CONFIG_KGDB=y CONFIG_KGDB_KDB=y CONFIG_KGDB_LOW_LEVEL_TRAP=y CONFIG_KGDB_SERIAL_CONSOLE=y CONFIG_KGDB_TESTS=y CONFIG_KGDB_TESTS_ON_BOOT=n CONFIG_MAGIC_SYSRQ=y CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE=0x1 CONFIG_SERIAL_KGDB_NMI=n Most of those are not mandatory, but this is what I've tested. *Add to your QEMU command: -append 'kgdbwait kgdboc=ttyS0,115200' \ -serial tcp::1234,server,nowait *Run GDB with from the root of the Linux kernel source tree with: gdb -ex 'file vmlinux' -ex 'target remote localhost:1234' *In GDB: (gdb) c and the boot should finish. *In QEMU: echo g > /proc/sysrq-trigger And GDB should break. *Now we are done, you can use GDB as usual: b sys_write c Tested in Ubuntu 14.04. ARM Can't get it work. Possibly related to: How to use kgdb on ARM?? A: You appear to be confusing the host serial device /dev/ttyS0 for the guest one, and QEMU's own gdbserver for KGDB in the guest kernel. There is normally no reason for QEMU to touch the host's serial port. Really the only reason for doing that would be if you wanted to have one physical machine host QEMU, and effectively give its physical serial port to the guest, so that you could then use a different physical machine connected by an actual serial cable to debug the guest. When you use the -s flag, you tell QEMU to run its own GDB server (by default listening on host loopback TCP port 1234) allowing you to break into whatever program is running on the guest, be that a kernel or bootloader or something else. This is not the same as having the guest kernel itself cooperate with debugging via KGDB. If you want to use KGDB, you are going to need to so something like configure KGDB in the kernel build to use the guest side of an emulated serial port, and then tell GDB on the host to use the host end of that emulated port. The QEMU command line documenation covers this in detail: Debug/Expert options: '-serial dev' Redirect the virtual serial port to host character device dev. The default device is vc in graphical mode and stdio in non graphical mode. This option can be used several times to simulate up to 4 serial ports. An abbreviated list of some of your more interesting options: 'pty' [Linux only] Pseudo TTY (a new PTY is automatically allocated) '/dev/XXX' [Linux only] Use host tty, e.g. '/dev/ttyS0'. The host serial port parameters are set according to the emulated ones. This is what you don't want - unless you want to use a serial cable to a different physical machine that will run GDB. 'tcp:[host]:port[,server][,nowait][,nodelay]' The TCP Net Console has two modes of operation. It can send the serial I/O to a location or wait for a connection from a location. By default the TCP Net Console is sent to host at the port. If you use the server option QEMU will wait for a client socket application to connect to the port before continuing, unless the nowait option was specified. The nodelay option disables the Nagle buffering algorithm. If host is omitted, 0.0.0.0 is assumed. Only one TCP connection at a time is accepted. You can use telnet to connect to the corresponding character device. Example to send tcp console to 192.168.0.2 port 4444 -serial tcp:192.168.0.2:4444 Example to listen and wait on port 4444 for connection -serial tcp::4444,server Example to not wait and listen on ip 192.168.0.100 port 4444 -serial tcp:192.168.0.100:4444,server,nowait This is a good and common choice. You can use basically the same GDB syntax, for example if you specify the loopback interface address 127.0.0.1 and the port 1234 you can just use exactly the same GDB command as before. 'unix:path[,server][,nowait]' A unix domain socket is used instead of a tcp socket. The option works the same as if you >had specified -serial tcp except the unix domain socket path is used for connections. This is a good choice too, assuming your GDB supports it. You may need to configure one of these options first, run without KGDB and get a shell up and figure out what the guest end of the emulated device is called, then reboot with KGDB configured to use that.
Q: Complexity: Is it more efficient to store two objects as variables or as array [2]? Is it more efficient to store two objects than variables or as array [2], or doesn't it make any difference? I am sorry if this is a dump question. A: That depends on the language. For example in c/c++ it is the same, on the other hand in Java the array has some overhead and therefore more expensive.
Q: Online index rebuild higher fragmentation on intermediate level I need to rebuild some big indexes and I'm doing some tests with the various options (sort_in_tempdb, maxdop, online) of the ALTER INDEX statement on an test index with 4 levels and 800000 pages on leaf level. I noticed when I'm running the statement with Online=on the intermediate pages (level 1) of my index are higher fragmented as before (89% in stead of 3%). The intermediate pages only get defragmented when I'm setting MAXDOP=1. With the options SORT_IN_TEMBP=ON,ONLINE=OFF the level 2 fragmentation jumps from 0 to 100. This are the statements that caused an increase of fragmentation on level 1: ALTER INDEX pk_test ON dbo.test REBUILD WITH (sort_in_tempdb=off,online=on,maxdop=1) ALTER INDEX pk_test ON dbo.test REBUILD WITH (sort_in_tempdb=off,online=on) ALTER INDEX pk_test ON dbo.test REBUILD WITH (sort_in_tempdb=on,online=on) This statement caused the fragmentation on level 2 go from 0 to 100 but level 1 stays the same: ALTER INDEX pk_test ON dbo.test REBUILD WITH (sort_in_tempdb=on,online=off) Is fragmentation on intermediate pages something to worry about and what is causing the increase in fragmentation? A: Try this: ALTER INDEX pk_test ON dbo.test REBUILD WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = ON, ONLINE = ON, ALLOW_ROW_LOCKS = OFF, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = ON) This way you will have a FILLFACTOR of 90% and you would probably avoid to have the table fragmentation to spike up again. Keep in mind that your table size will increase of 10%
Q: Pyspark withColumn Not Returning Dataframe I have a dataframe 'df' that i parse. from pyspark.sql.functions import regexp_extract, trim, lit df2 = df.withColumn("value", regexp_extract("_c0", "(? <=value':\s)\d+", 0))\ .withColumn("time", regexp_extract("_c1", "(? <=time':\su')\d\d:\d\d:\d\d(?=('}))", 0))\ .show(truncate=False) It returns +-------------+----------------------+-----+--------+ |_c0 |_c1 |value|time | +-------------+----------------------+-----+--------+ |{u'value': 76| u'time': u'00:36:32'}|76 |00:36:32| |{u'value': 77| u'time': u'00:36:42'}|77 |00:36:42| |{u'value': 76| u'time': u'00:36:47'}|76 |00:36:47| |{u'value': 77| u'time': u'00:36:57'}|77 |00:36:57| |{u'value': 78| u'time': u'00:37:02'}|78 |00:37:02| |{u'value': 77| u'time': u'00:37:07'}|77 |00:37:07| When i try to do more manipulations to df2, I get 'NoneType' object has no attribute 'show' Why is df2 no longer a dataframe that i can manipulate? Instead of .show() I try .toDF() and get u"requirement failed: The number of columns doesn't match.\nOld column names (4): _c0, _c1, value, time\nNew column names (0): And .collect() returns rows. I just want another dataframe returned. A: You are executing .show() action while creating df2 dataframe, That's the reason why df2 is not a dataframe anymore. Create df2 dataframe without .show() action: >>> df2 = df.withColumn("value", regexp_extract("_c0", "(? <=value':\s)\d+", 0))\ .withColumn("time", regexp_extract("_c1", "(? <=time':\su')\d\d:\d\d:\d\d(?=('}))", 0)) Now do .show() on df2 dataframe: >>> df2.show()
Q: Is a fully differential opamp subtractor possible? I know how to subtract two single-ended voltages with an opamp configured as a subtractor. I'm learning about fully differential signal processing and I'm wondering if it is possible to subtract two balanced fully differential signals without converting them to single-ended first. Say I have two analog signals. V1_D = V1_P - V1_N V2_D = V2_P - V2_N What I want is V3_D = V1_D - V2_D By algebra this is V3_D = (V1_P - V1_N) - (V2_P - V2_N) So, it looks like I could do it with three subtractor opamps. But would I run into a dynamic range problem? Imagine I have a 5V VDD and my signals are rail to rail. So, V1_P - V1_N could be anywhere between 5 and 0. It doesn't seem to work unless I also scale the voltages down by 2. (which may be OK). Is there an easier solution I'm missing here? Thank you for your time. A: This differential opamp computes a sum of differential signals, to turn it into a substractor simply swap the polarity of one of the differential inputs. The opamp is a fully differential one like THS4131. This assumes the source signals come from a low enough impedance to drive the resistors. If they are high impedance then you will need followers. This is the same issue as using a non-differential opamp in inverting mode, or as a substractor. About the single opamp difference amplifier... You can use it to turn a differential signal into single-ended, but if you add resistors you can also use it to add or substract differential signals. The output is single-ended, but... it is referenced to the node "outn", which as the name does not iply, is an input which is set at ground here. You could set it at another voltage. Output is the voltage difference between outp and outn, which is actually a differential signal... albeit without some of the advantages, since positive and negative halves aren't symmetrical, thus it has half the voltage headroom, and won't cancel some distortion harmonics. A: Maybe take a look at the THS4521. It's an op-amp with differential output - and it also has an extra input that allows you to set the center point for the diff output. So if you need to subtract two differential signals, how about... use two of these (or a single piece of the dual THS4522 - same datasheet), "normalize" each signal with one of these bros, and then subtraction is the same thing as addition of an inverted second operand, right? The summing operation could be done with two resistive dividers :-)
Q: crossplatform mysql_install_db script in mysql 5.5.34 on Windows I downloaded mysql-5.5.34-win32.zip and found out there is mysql_install_db.pl script. However mysql 5.5 documentation says: mysql_install_db is a shell script and is available only on Unix platforms. (As of MySQL 5.6, mysql_install_db is a Perl script and can be used on any system with Perl installed.) * *https://dev.mysql.com/doc/refman/5.5/en/mysql-install-db.html mysql-5.5.34-linux2.6-i686.tar.gz archive contains shell version of mysql_install_db script. Why does mysql 5.5.34 for Windows contain this script? Is it an issue in 5.5 documentation? UPD 1: I found several comments in bugs.mysql.com which confirm that this perl script is useless on Windows: I am not sure if this script is intended to be executed on Windows at all. Our manual clearly says: "It is unnecessary to run the mysql_install_db script that is used on Unix." * *http://bugs.mysql.com/bug.php?id=52183 or mysql_install_db is not supported on Windows and scheduled for removal from our Windows packages. * *http://bugs.mysql.com/bug.php?id=35105 But is there any official comment that this script really useless on Windows?
Q: Python Testing - Is this a safe way of writing my tests to avoid repeating long dictionaries in each test function I'm new to Python and experimenting with writing some tests for an API endpoint. Is the way that I'm mocking the puppy object safe below? In my tests, it is working the way I'd expect. Do I run the risk in the future of the tests stepping on each other and the object's value that I think I'm testing, actually be referencing an older value in memory? Should I be using a different strategy? class PuppyTest(APITestCase): """ Test module for Puppy model """ def mock_puppy(self): return { "name": "Max", "age": 3, "breed": "Bulldog" } def test_create_puppy_with_null_breed(self): """ Ensure we can create a new puppy object with a null "breed" value """ url = reverse('puppy') data = self.mock_puppy() data['breed'] = None # Updating breed value response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_create_puppy(self): """ Ensure we can create a new puppy object. """ url = reverse('puppy') data = self.mock_puppy() # returns original "breed" value "Bulldog" response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) A: Is the way that I'm mocking the puppy object safe below? Yes Do I run the risk in the future of the tests stepping on each other and the object's value that I think I'm testing, actually be referencing an older value in memory? No Should I be using a different strategy? Your method is OK, with a new dict being created for each test. However, since you're using pytest, it might be more typical to put that data into a fixture rather than a method.
Q: Java обрезать текст по условию Подскажите как достать только значение cn, без знаков = и , cn=Иванов Иван Иванович,ou=office,ou=Active,ou=Users,ou=nsk,dc=office,dc=ru A: String source = "cn=Иванов Иван Иванович,ou=office,ou=Active,ou=Users,ou=nsk,dc=office,dc=ru"; String result = source.substring(source.indexOf("cn=")+"cn=".length(), source.indexOf(",")); A: String s = "cn=Иванов Иван Иванович,ou=office,ou=Active,ou=Users,ou=nsk,dc=office,dc=ru"; String onlyCnValue = s.split(",")[0].split("=")[1]; A: Вариант по сложнее с регуляркой Pattern p = Pattern.compile("(?<=cn=)[^,]*"); Matcher m = p.matcher("cn=Иванов Иван Иванович,ou=office,ou=Active,ou=Users,ou=nsk,dc=office,dc=ru"); if (m.find()) { System.out.println(m.group(0)); } Результат Иванов Иван Иванович A: .. а откуда? подозреваю из AD. LdapAdmin скорее всего правильные пути подскажет http://www.ldapadmin.org/download/ldapadmin.html ну а коцать символы в результатах java Удаление символов из строки java или еще ишите на "java удалить символ из строки" +думаю вам понадобится = парсинг = ру\en работа с символами = знания другие
Q: ¿Cómo selecciono el registro décimo de una consulta? Ejemplo, el décimo empleado con más salario Os pongo en contexto, necesito seleccionar el décimo país con mayor PIB. PIB es una columna de una tabla. ¿Cómo podría realizar algo semejante? Esto es lo que me piden en un trigger: Si se realizó un borrado en la tabla PAIS, deberá comprobar si el país eliminado es uno de los países de la tabla TOP_10_POTENCIAS_POR_PIB, en cuyo caso insertará el décimo país de mayor PIB de la tabla PAÍS en la tabla TOP_10_POTENCIAS_POR_PIB. La tabla PAIS: CREATE TABLE pais ( cod_pais number(4), nombre varchar2(30), capital varchar2(20), extension number(10), moneda varchar2(20), num_hab number(10), PIB number(20,2), continente varchar2(20), CONSTRAINT pk_pais PRIMARY KEY (cod_pais)); ¿Sé podría realizar con ROWNUM?
Q: Why do coroutines have futures? Once you have coroutines you can create pipelines (haskell: pipes, conduits; python: generators) or cooperative event loops (python: curio). Once you have futures, it appears you can do the same; pipelines (rust: futures-rs) and event loops (rust: tokio). Since futures aren't cooperative they require a callback-based (even poll-based futures require callbacks) scheduler to execute blocking tasks within a thread or process pool. What benefits are there to combining futures (library-level) with coroutines (language-level) as these languages do: (python: asyncio), (rust: rfc), (ecmascript 6+). Fundamentally they seem to be conflicting solutions to the same problem. I'm not looking for a pro/con comparison, and I don't buy the argument that futures are "one-shot" coroutines. Just look at rust, which built an entire state-machine-based event framework using just futures. I want to know why python/asyncio and javascript both require coroutines together with futures. Why rust is planning on adding coroutines to its futures? Does it have to do with composability of events? Or the implicit stack of coroutines versus the explicit stack of continuation-passing futures? Not that I completely understand this argument, as both futures and coroutines are implemented using continuations... Or does it have something to do with direct vs indirect style? A: These are all different (though related) ideas with different amounts of power. * *A future is an abstraction that lets you begin a process and then yield back to a handler, that is chosen by the original caller, when the process is done. *A generator is more powerful than a future because it can yield multiple times. You can implement futures on top of generators. *A coroutine is more powerful than a generator because it can choose who to yield to, instead of only to the caller. For example it can yield to another coroutine. You can implement generators on top of coroutines. Why would you use the less powerful tool, when more powerful ones are available? Sometimes the less powerful tool is the right tool for the job. It's useful to statically encode your program's invariants using types, because it can give you certainty about what something can't do. For example, when making a REST call to a remote server, a future is probably sufficient. If the REST client exposed a generator, you'd have to deal with the possibility that it could yield multiple times, even though you know there is only going to be one result. If it exposed a coroutine, you'd have to consult the documentation to work out exactly how you're supposed to interact with it - even though you actually only need to do one thing, which is obvious when you're dealing with a future.
Q: I can't get AMQP publish and subscribe to run with Node JS v6 and mqlight v2.0 from IBM MQ v9.0.1.0 I am trying to get the example snippet to publish and subscribe below, I can't get it to run with Node JS 6 and mqlight v2.0 https://www.npmjs.com/package/mqlight?cm_mc_uid=47189062138014548006442&cm_mc_sid_50200000=1490060435 // Receive: var mqlight = require('mqlight'); var recvClient = mqlight.createClient({service: 'amqp://user:user@localhost:5672'}); recvClient.on('started', function() { recvClient.subscribe('/TEST/#','sub1'); recvClient.on('message', function(data, delivery) { console.log(data); }); }); // Send: var sendClient = mqlight.createClient({service: 'amqp://user:user@localhost:5672'}); sendClient.on('started', function() { sendClient.send('TEST'); }); i run the sample code mqlight 2.0 with node js v6 $node mqlight_sample.js events.js:160 throw er; // Unhandled 'error' event ^ SecurityError: AMQXR0100E: A connection from 172.17.0.1 was not authorized. at lookupError (/media/Data/mqlight/node_modules/mqlight/mqlight.js:1034:11) at AMQPClient.<anonymous> (/media/anonim/Data/mqlight/node_modules/mqlight/mqlight.js:1925:13) at emitOne (events.js:96:13) at AMQPClient.emit (events.js:188:7) at Connection.<anonymous> (/media/anonim/Data/mqlight/node_modules/amqp10/lib/amqp_client.js:388:10) at emitOne (events.js:96:13) at Connection.emit (events.js:188:7) at Connection._processCloseFrame (/media/anonim/Data/mqlight/node_modules/amqp10/lib/connection.js:495:10) at Connection._receiveAny (/media/anonim/Data/mqlight/node_modules/amqp10/lib/connection.js:423:12) at Connection._receiveData (/media/anonim/Data/mqlight/node_modules/amqp10/lib/connection.js:357:8) at NetTransport.<anonymous> (/media/anonim/Data/mqlight/node_modules/amqp10/lib/connection.js:515:38) at emitOne (events.js:96:13) at NetTransport.emit (events.js:188:7) at Socket.<anonymous> (/media/anonim/Data/mqlight/node_modules/amqp10/lib/transport/net_transport.js:26:49) at emitOne (events.js:96:13) at Socket.emit (events.js:188:7) this one error log from MQ Server # tail -100f /var/mqm/qmgrs/QM1/errors/amqp_0.log 3/31/17 19:14:44.115 AMQXR0041E: A connection was not authorized for channel SYSTEM.DEF.AMQP received from 172.17.0.1. MQRC 2035 MQRC_NOT_AUTHORIZED 3/31/17 19:14:45.142 AMQXR0041E: A connection was not authorized for channel SYSTEM.DEF.AMQP received from 172.17.0.1. MQRC 2035 MQRC_NOT_AUTHORIZED actually authenticate for AMQP is enabled if CONNAUTH and CHCKCLNT required changed to disabled i can connected with Node JS 6 START SERVICE(SYSTEM.AMQP.SERVICE) SET CHLAUTH(SYSTEM.DEF.AMQP) TYPE(BLOCKUSER) USERLIST('nobody') SET CHLAUTH(SYSTEM.DEF.AMQP) TYPE(ADDRESSMAP) ADDRESS(*) USERSRC(CHANNEL) CHCKCLNT(REQUIRED) REFRESH SECURITY TYPE(CONNAUTH) START CHANNEL(SYSTEM.DEF.AMQP) DISPLAY CHSTATUS(SYSTEM.DEF.AMQP) CHLTYPE(AMQP) below the error log from /var/mqm/qmgrs/QM1/errors/AMQERR01.LOG 04/02/17 07:10:16 - Process(587.6) User(mqm) Program(java) Host(770e29171038) Installation(Installation1) VRMF(9.0.1.0) QMgr(QM1) AMQ5534: User ID 'user' authentication failed EXPLANATION: The user ID and password supplied by the 'AMQP' program could not be authenticated. Additional information: 'N/A'. ACTION: Ensure that the correct user ID and password are provided by the application. Ensure that the authentication repository is correctly configured. Look at previous error messages for any additional information. ----- amqzfuca.c : 4486 ------------------------------------------------------- 04/02/17 07:10:16 - Process(587.6) User(mqm) Program(java) Host(770e29171038) Installation(Installation1) VRMF(9.0.1.0) QMgr(QM1) AMQ5542: The failed authentication check was caused by the queue manager CONNAUTH CHCKCLNT(REQDADM) configuration. EXPLANATION: The user ID 'user' and its password were checked because the queue manager connection authority (CONNAUTH) configuration refers to an authentication information (AUTHINFO) object named 'USE.OS' with CHCKCLNT(REQDADM). This message accompanies a previous error to clarify the reason for the user ID and password check. ACTION: Refer to the previous error for more information. Ensure that a password is specified by the client application and that the password is correct for the user ID. The authentication configuration of the queue manager connection determines the user ID repository. For example, the local operating system user database or an LDAP server. If the CHCKCLNT setting is OPTIONAL, the authentication check can be avoided by not passing a user ID across the channel. For example, by omitting the MQCSP structure from the client MQCONNX API call. To avoid the authentication check, you can amend the authentication configuration of the queue manager connection, but you should generally not allow unauthenticated remote access. ------------------------------------------------------------------------------- 04/02/17 07:10:17 - Process(587.6) User(mqm) Program(java) Host(770e29171038) Installation(Installation1) VRMF(9.0.1.0) QMgr(QM1) AMQ5534: User ID 'user' authentication failed EXPLANATION: The user ID and password supplied by the 'AMQP' program could not be authenticated. Additional information: 'N/A'. ACTION: Ensure that the correct user ID and password are provided by the application. Ensure that the authentication repository is correctly configured. Look at previous error messages for any additional information. ----- amqzfuca.c : 4486 ------------------------------------------------------- 04/02/17 07:10:17 - Process(587.6) User(mqm) Program(java) Host(770e29171038) Installation(Installation1) VRMF(9.0.1.0) QMgr(QM1) AMQ5542: The failed authentication check was caused by the queue manager CONNAUTH CHCKCLNT(REQDADM) configuration. EXPLANATION: The user ID 'user' and its password were checked because the queue manager connection authority (CONNAUTH) configuration refers to an authentication information (AUTHINFO) object named 'USE.OS' with CHCKCLNT(REQDADM). This message accompanies a previous error to clarify the reason for the user ID and password check. ACTION: Refer to the previous error for more information. Ensure that a password is specified by the client application and that the password is correct for the user ID. The authentication configuration of the queue manager connection determines the user ID repository. For example, the local operating system user database or an LDAP server. If the CHCKCLNT setting is OPTIONAL, the authentication check can be avoided by not passing a user ID across the channel. For example, by omitting the MQCSP structure from the client MQCONNX API call. To avoid the authentication check, you can amend the authentication configuration of the queue manager connection, but you should generally not allow unauthenticated remote access. ------------------------------------------------------------------------------- A: In reviewing the error logs from the queue manager it appears that MQ is not able to authenticate the user being passed to the AMQP channel via the mqlight_sample.js program. Please try the following two commands and note the output: echo 'goodpassword' | /opt/mqm/bin/security/amqoamax user ; echo $? echo 'badpassword' | /opt/mqm/bin/security/amqoamax user ; echo $? OP noted the output was 0 and 1 for the above commands. This means that MQ can properly authenticate the the UserId "user" with a correct password since it returns 0. Next please create a normal SVRCONN channel on the queue manager and try the following sample program, this would again rule out MQ and CONNAUTH being an issue. echo 'goodpassword' | amqscnxc -x 'localhost(5672)' -c SVRCONN.CHANNEL -u user QM1; echo $? The output if good should look like this: Sample AMQSCNXC start Connecting to queue manager QM1 using the server connection channel SVRCONN.CHANNEL on connection name localhost(5672). Enter password: Connection established to queue manager QM1 Sample AMQSCNXC end 0 If output if it fails should look like this: Sample AMQSCNXC start Connecting to queue manager QM1 using the server connection channel SVRCONN.CHANNEL on connection name localhost(5672). Enter password: MQCONNX ended with reason code 2035 243 If the above test is also successful then please verify that the mqlight_sample.js has the same user and goodpassword values that worked with the two tests. If you find that the UserID and password are correct, then it would appear that the amqp program is not passing the password correctly and someone else with more AMQP knowledge would need to help. Update 2017-04-28 OP @dhaavhincy has posted a new answer that per IBM the issue was a result of the SASL flow in Node JS v6 being changed and incompatible with IBM MQ AMQP. IBM has provided that this will be fixed via APAR IT20283 which has not been published to the web. Update 2017-06-20 APAR IT20283 was published to the web around May 22nd. A: SASL flow has been changed within the new Node JS client version. The new SASL flow is currently not supported by the IBM AMQP server. The AMQP server thinks that at this moment it should already have enough data for authentication and authorization of the client user. However, because of the change in the new Node JS client, the rest of the required data has not yet been sent when the server tries to authenticate the client. This is why the logs show that only the user 'mqm' has been set and no password supplied to the QMgr. Thus causing an authorization error APAR IT20283
Q: mapping a constant function across Array(3) vs. [1,2,3]: why are they different Why do these 2 expressions produce different results? > [1,3,4].map(x=>5) // (3) [5, 5, 5] > Array(3).map(x=>5) // (3) [empty × 3] A: Because the arrays are different. [1, 3, 4] creates an array with a length of 3 and three entries in it. Array(3) creates an array with a length of 3 with no entries in it (a sparse array). map skips over empty slots in arrays, so your map callback is never executed. You can see that here, where the first has a property called "0" (remember that standard arrays in JavaScript aren't really arrays at all¹, barring optimization in the JavaScript engine) but the second doesn't: const a1 = [1, 3, 5]; console.log(a1.length); // 3 console.log("0" in a1); // true const a2 = Array(3); console.log(a2.length); // 3 console.log("0" in a2); // false If you want to fill that array, use fill: console.log(Array(3).fill(5)); fill is great where the same value is being used for all elements, but if you want different values for different elements, you can use the mapping callback of Array.from: console.log(Array.from(Array(3), x => Math.random())); When using Array.from, if the size is large (not just 3), then on some JavaScript engines (such as V8 in Chrome, Edge, and others), you'd want to use {length: value} rather than Array(value), because it's a temporary object and when you use Array(value), V8 (and perhaps others) pre-allocates storage for that number of elements, even though the elements start out initially empty. So: console.log(Array.from({length: 3}, x => Math.random())); ¹ (That's a post on my anemic litle blog.) A: [1,3,4].map(x=>5) // (3) [5, 5, 5] The above can be re-written as [1,3,4].map(function(x){ return 5; }) Which will output [5,5,5] as it is returning 5 on every value in the array. var a=Array(3).map(x=>5) console.log(a) The above creates a new array with 3 empty slots in array. Map skips all the empty elements and thus returns undefined
Q: What if we set Hamilton-Jacobi equation as an axiom? We usually postulate the principle of least action. Then we can get Lagrangian mechanics. After that we can get Hamiltonian mechanics either from postulate or from the equivalent Lagrangian mechanics. Finally we get the Hamilton-Jacobi equation (HJE). But what if we have HJE as postulate instead? How can we get Hamiltonian mechanics from it? A: I) The Hamilton-Jacobi equation (HJE) itself sure ain't enough as an axiom without some kind of context, setting, definitions and identifications of various variables. II) Let us assume: * *that Hamilton's principal function $S(q,P,t)$ depends on the old positions $q^i$ and the new momenta $P_j$ and time $t$, *the HJE itself, *the definition of old momenta $p_i:=\frac{\partial S}{\partial q^i},$ *the definition of new positions $Q^i:=\frac{\partial S}{\partial P_i}$, *that the new phase space variables $(Q^i,P_j)$ are all constants of motion (COM). III) Then it is a straightforward exercise to derive Hamilton's equations for the old phase space variables $(q^i,p_j)$ provided pertinent rank-conditions are satisfied for the Hessian of $S$. [This result is expected, because (5) is precisely Kamilton's equations and the function $S$ in (1)-(4) is a type-2 generating function of a canonical transformation (CT).] IV) The Lagrange equations follow next from a Legendre transformation. In turn, the Lagrange equations are Euler-Lagrange (EL) equations from the stationary action principle for $\int \! dt ~L$.
Q: Moving Cell in TableView I want to moving cell (reordering cell) in TableView. I have tried like this: import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var editBarButton: UIBarButtonItem! var tableData = ["One","Two","Three","Four","Five"] override func viewDidLoad() { super.viewDidLoad() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) cell.textLabel!.text = tableData[indexPath.row] return cell } func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { let itemToMove = tableData[sourceIndexPath.row] tableData.removeAtIndex(sourceIndexPath.row) tableData.insert(itemToMove, atIndex: destinationIndexPath.row) } @IBAction func editBarButtonTapped(sender: AnyObject) { self.editing = !self.editing } } I have also set TableViewDataSource and TableViewDelegate in Storyboard. But when I click on the editBarButton, It doesn't cause any affects. I want to make it like this: Any helps would be appreciated. Thanks. A: import UIKit class FirstViewController: UITableViewController { var dataHolder: Array = ["One","Two","Three","Four","Five"] override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return dataHolder.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) cell.textLabel?.text = dataHolder[indexPath.row] return cell } override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.None } override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { let itemToMove: String = dataHolder[fromIndexPath.row] dataHolder.removeAtIndex(fromIndexPath.row) dataHolder.insert(itemToMove, atIndex: toIndexPath.row) } // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } } If you're not using UITableViewController then ensure you've implemented the following method: override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) } A: Now I found the answer. If I don't use UITableViewController, I need to implement this function: override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) } Because this function says: Sets whether the view controller shows an editable view. Subclasses that use an edit-done button must override this method to change their view to an editable state if editing is true and a non-editable state if it is false. This method should invoke super's implementation before updating its view. It works now.
Q: Symfony CollectionType with no entity I have a: class Q&A { private $question private $answer } I need a collection (CollectionType) of Q&As, but there is no inverse side entity in my model (Q&A entity has no ManyToOne relationship with any other entity). Question What are my options here ? I also have: class Page { /** * @ORM\OneToMany(targetEntity="Content") */ private $contents; } I thought about making the Page class as abstract and create a separate entity for each page type, each inheriting from Page. That way I could class Q&APage { /** * @ORM\OneToMany(targetEntity="Q&A") */ private $q&as; } But it's not a big website, I've got like 5 different page types on it, I feel it would be overkill to have a different entity for each page type. A: First of all this has nothing to do with Symfony. This is a Doctrine thing. By the way, you have no overkill here, because your Model should make sense and be rational, to let you develop your codebase. There exist so many situations in which, the programmer, designs a malformed Model, and gets into trouble, while goes through developing the codebase. After all this, how do you know that: That is not a big website ? Many of today's big websites, have not been so big from the beginning. so it would be a good practice for you as a developer to try, not to trifle the Model Design. The proposed design looks good, and to be honest, you have a good understanding of data structures needed for your model. You need to have a: class QuestionAndAnswer { /** * @ORM\ManyToOne(targetEntity="QuestionAndAnswerPage", inversedBy="questionAndAnswers") */ private $questionAndAnswerPage; } and a: class QuestionAndAnswerPage { /** * @ORM\OneToMany(targetEntity="QuestionAndAnswer", mappedBy="questionAndAnswerPage") */ private $questionAndAnswers; } Tip: Try to use complete english words and phrases all the time, as that is a best practice in object oriented world. Keep in mind that, your users don't need to read them. They are there for you to not get stuck in malformed phrases in future.
Q: What is an alternative for "thank you"? So... I am seeking a new job and several recruiters are helping me. Instead of saying 'Thank you', should I say 'I appreciate'? Which one is more polite? Could someone please tell me how to express one's gratefulness to someone else in English? A: In addition to @Robusto's answer, which I agree with almost completely, note that there may be regional differences in how effusive (or not) you might want to be with recruiters. It is their job, and you probably don't want to sound puppy-dog-like in your enthusiasm, but it is often generically expected to provide at least pro forma thanks (which may at least bias the recruiter towards suggesting some of the better bad jobs to you). Definitely use at least "I appreciate it," instead of just "I appreciate" . A few variations on "thanks", from most enthusiastic to least: * *Thanks! *Thanks, [your familiar name, or first name, nickname, etc.] *Thanks, [your full name] Some other variations I consider appropriate and acceptable: * *Thanks for your efforts *Thanks for your help *Thanks for you time *Thanks for your assistance Less formal: * *Appreciate [it, your help, your time, etc.] *Thanks, [recruiter's name] Compound endings. * *That's great. Thanks. *Sounds great, thanks. Special use, for when you've already used "thanks" six times: * *Always appreciated, [your name] or more familiar, * *Always appreciated, [recruiter's name] The "it" or "your help" is implied here, though you could also explicitly add it. A: "Thank you" is serviceable in all contexts. Since it is so common, though, it may not feel like enough. In that case, you can say "I appreciate your help" or "Thank you so much" or "I'm very grateful" — there are many ways to express gratitude. Nevertheless, remind yourself that recruiters are getting paid for their work, so you shouldn't feel you have to be too effusive in your thanks. A simple "thank you" will probably suffice. A: The best one is: I am honored. Longer ones describing what you are honored by are even better: I am honored to be graced by your presence. It reminds me of Tolkien and Paolini. :) If you don't like being a hobbit, there's always "Thanks", which makes everyone but elves comfortable. (Sauron doesn't like being thanked either.) A: I like to use obliged in these types of situations, although thank you really is sufficient. A: I tend to use thank you kindly a lot. A: In Romanian, "thank you" is: "mulţumesc", the literal translation of which is simply: "I'm happy". So I guess "I appreciate" is another way of expressing that you are happy. "I appreciate..." is in my opinion more elegant than "I'm grateful" because "grateful" is closer to "I'm indebted". However, I'd also consider "I enjoyed..." I would rank things like this * *"I enjoyed..." which conveys a sense community of thought and possibly a convergence of interest. *"I appreciate..." which is a less strong but could be misinterpreted as a "refusal" (as in "I appreciate the effort but..."). Consider that this phrasing is probably what you would use for instance if the offered opportunity came only as a second choice for you. *"I'm grateful..." could sound like as "I didn't think I could make it !". *"I'm indebted...". Use this and they will slash half of your wages off. That's my 2cts of course. I any case you've probably finished that letter by now ;-). A: For me, I personally prefer to use " I would really appreciate your kind assistance" or "I would like to express my deepest gratitude for your kind assistance". I think it is more formal to express your gratitude towards the person as "thank you" is a general statement which does not explain in details for what you owed him/ her a thank you.
Q: Why python for loops don't default to one iteration for single objects This may seem like an odd question but why doesn't python by default "iterate" through a single object by default. I feel it would increase the resilience of for loops for low level programming/simple scripts. At the same time it promotes sloppiness in defining data structures properly though. It also clashes with strings being iterable by character. E.g. x = 2 for a in x: print(a) As opposed to: x = [2] for a in x: print(a) Are there any reasons? FURTHER INFO: I am writing a function that takes a column/multiple columns from a database and puts it into a list of lists. It would just be visually "nice" to have a number instead of a single element list without putting type sorting into the function (probably me just being OCD again though) Pardon the slightly ambiguous question; this is a "why is it so?" not an "how to?". but in my ignorant world, I would prefer integers to be iterable for the case of the above mentioned function. So why would it not be implemented. Is it to do with it being an extra strain on computing adding an __iter__ to the integer object? Discussion Points * *Is an __iter__ too much of a drain on machine resources? *Do programmers want an exception to be thrown as they expect integers to be non-iterable *It brings up the idea of if you can't do it already, why not just let it, since people in the status quo will keep doing what they've been doing unaffected (unless of course the previous point is what they want); and *From a set theory perspective I guess strictly a set does not contain itself and it may not be mathematically "pure". A: Python cannot iterate over an object that is not 'iterable'. The 'for' loop actually calls inbuilt functions within the iterable data-type which allow it to extract elements from the iterable. non-iterable data-types don't have these methods so there is no way to extract elements from them. This Stack over flow question on 'if an object is iterable' is a great resource. A: The problem is with the definition of "single object". Is "foo" a single object (Hint: it is an iterable with three strings)? Is [[1, 2, 3]][0] a single object (It is only one object, with 3 elements)? A: The short answer is that there is no generalizable way to do it. However, you can write functions that have knowledge of your problem domain and can do conversions for you. I don't know your specific case, but suppose you want to handle an integer or list of integers transparently. You can create your own iterator: def col_iter(item): if isinstance(item, int): yield item else: for i in item: yield i x = 2 for a in col_iter(x): print a y = [1,2,3,4] for a in col_iter(y): print a A: The only thing that i can think of is that python for loops are looking for something to iterate through not just a value. If you think about it what would the value of "a" be? if you want it to be the number 2 then you don't need the for loop in the first place. If you want it to go through 1, 2 or 0, 1, 2 then you want. for a in range(x): not positive if that's the answer you're looking for but it's what i got.
Q: chromium browser 34 version repository download Can someone please help me with downloading chromium browser 34 version, any repository or ppa. I want chromium-browser 34 version only. Thanks in advance A: Try this: https://apps.ubuntu.com/cat/applications/chromium-browser/ That should be fairly easy to install. A: Find the link here & download chromium(34 version) .deb package for i386 Visit http://packages.ubuntu.com/trusty/i386/chromium-browser/download For amd64 Visit http://packages.ubuntu.com/trusty/amd64/chromium-browser/download
Q: How to draw a bitmap to a SurfaceView? I am trying to draw a bitmap to my SurfaceView actually with the following code: (this will be run in another Thread and in a while, because it needs to refresh the SurfaceView). while (true) { try { // Enable drawing // ERROR LINE! Canvas ca = mPreview2.Holder.LockCanvas(); // Get current frame Bitmap test = mediaPlayer.CurrentFrame; // Actual drawing Paint paint = new Paint(); ca.DrawBitmap(test, 0, 0, paint); // Stop drawing mPreview2.Holder.UnlockCanvasAndPost(ca); } catch (Exception ex) { throw ex; } } But I've got the following error: (this is happening on line: Canvas ca = mPreview2.Holder.LockCanvas(); Java.Lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference A: Right now I can draw a bitmap, but I have still one problem! Because the quality of the right screen is really bad (see image): PROBLEM SOLVED: What I did is using a MemoryStream which compress the Bitmap to .JPG with a quality of 100 and decode the byte array to a Bitmap. It works great now! See code below: private void DrawCanvas() { while (true) { Canvas canvas = holder2.LockCanvas(); if (canvas != null) { Bitmap currentBitmap = mediaPlayer.CurrentFrame; if(currentBitmap != null) { Paint paint = new Paint(); MemoryStream ms = new MemoryStream(); currentBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, ms); byte[] bitmapData = ms.ToArray(); Bitmap bitmap = BitmapFactory.DecodeByteArray(bitmapData, 0, bitmapData.Length); Bitmap scaledBitmap = Bitmap.CreateScaledBitmap(bitmap, mPreview2.Width, mPreview2.Height, true); canvas.DrawBitmap(scaledBitmap, 0, 0, paint); bitmap.Recycle(); scaledBitmap.Recycle(); currentBitmap.Recycle(); } holder2.UnlockCanvasAndPost(canvas); } } }
Q: Do I have to make a new pipe for every pair of processes in C? If I have 4 processes that I want to pipe: process1 | process2 | process3 | process4 do I have to make 3 individual pipes likes this int pipe1[2]; int pipe2[2]; int pipe3[2]; or can I somehow recycle pipe names like in this pseudocode: int pipe1[2]; // we use ONLY two pipe names: pipe1 int pipe2[2]; // and pipe2 pipe(pipe1); // getting 2 file descriptors here pipe(pipe2); // and 2 here for process=1 to 4 if (process==3) // getting 2 new file descriptors for pipe(pipe1); // process3|process4 (reusing pipe1) fork() // forking here if (child 1) then use pipe1 if (child 2) then use pipe1 use pipe2 if (child 3) then use pipe2 use pipe1 //the pipe1 that we re-pipe()ed if (child 3) then use pipe1 //the pipe1 that we re-pipe()ed Would this work? I am not sure if repiping pipe1 will have an impact on the previous forked processes that used pipe1. A: Short answer: no, "repiping" pipe1 will not have an impact on the previous forked processes that used pipe1, but you're better off declaring 3 pipes and pipe()'ing before fork()'ing. Long answer: To understand why, let's first see what happens when you create a "pipe", and then what happens when you "fork" a process. When you call pipe(), it "creates a pipe (an object that allows unidirectional data flow) and allocates a pair of file descriptors. The first descriptor connects to the read end of the pipe; the second connects to the write end." (This is from the man pipe page) These file descriptors are stored into the int array you passed into it. When you call fork(), "The new process (child process) shall be an exact copy of the calling process" (This is from the man fork() page) In other words, the parent process will create a child process, and that child process will have it's own copy of the data. So when child 3 calls pipe(pipe1), it will be creating a new pipe, and storing the new file descriptors in it's own copy of the pipe1 variable, without modifying any other process's pipe1. Even though you can get away with only declaring two pipe variables and just calling pipe() in child 3, it's not very easy to read, and other's (including yourself) will be confused later on when they have to look at your code. For more on fork()'s and pipe()'s, take a look at http://beej.us/guide/bgipc/output/html/multipage/index.html A: The way I've done it in the past, and the way I would do it again, was to not reuse pipes and end up with N-1 pipes. It would also depend on whether or not you want to have more than two process running at the same time communicating, if so then you'd obviously have problems with reusing 2 pipes. A: You need one pipe, and thus one call to pipe(), for each | character in your command. You do not need to use three separate int [2] arrays to store the pipe file descriptors, though. The system does not care what variable you store the pipe file descriptors in - they are just ints.
Q: How to remove duplicate record from table sql server i use sql to delete duplicate record but it is not working. can anyone help me. my sql is delete from VehicleInfoForParts where Stock_Code not in ( select max(Stock_Code) from VehicleInfoForParts group by stock_code,makeid,modelid ) thanks A: If you're on SQL SErver 2005 and up, you can use a CTE (Common Table Expression) do achieve this: ;WITH DupData AS ( SELECT Stock_Code, MakeID, ModelID, ROW_NUMBER() OVER(PARTITION BY stock_code,makeid,modelid ORDER BY Stock_Code DESC) 'RowNum' FROM dbo.VehicleInfoForParts ) DELETE FROM DupData WHERE RowNum > 1 Basically, the SELECT statement inside the CTE groups your data by (stock_code, makeid, modelid) - i.e. each "group" of those three elements gets a consecutive row_number starting at one. The data is sorted by stock_code descending, so the largest number is the first one, the one with RowNum = 1 - so anything else (with a RowNum > 1) is a duplicate and can be deleted. A: You're grouping by the same column that you're wanting to get the max value for. What you probably need to do is for each row in the table delete a row where the primary id of the row is not the max (or min if the second row is in error). DELETE FROM VehicleInfoForParts t1 WHERE PrimaryID NOT IN (SELECT MIN(PrimaryID ) FROM VehicleInfoForParts t2 WHERE t2.Stock_Code = t1.Stock_Code) A: The following query is useful to delete duplicate rows. The table in this example has ID as an identity column and the columns which have duplicate data are Column1, Column2 and Column3. DELETE FROM TableName WHERE ID NOT IN ( SELECT MAX(ID) FROM TableName GROUP BY Column1, Column2, Column3 )
Q: Tyzen studio package manager does not open with java nullpointer execption. and many tools can not open I am having lots of issues with windows version of Tizen studio such as emulator manager, control panel doesn't open. So I tried mac version but installing it on startup it could not open package manager with "Failed to execute runnable (java.lang.NullPointerException) cause: null" error, despite having valid JDK 11 and latest installer 3.6. No valid solution found so far. So should we abandon Tizen studio for lack of support and improvements? Does any one has solution? EDIT - Solution: I was able to run required tools such as Emulator manager after I used JDK8 on Windows and I didn't test but this should work with mac too. I wish there was more information about it on the first time. Using other updated version of JDK doesn't give any error but it requires JDK12 or JDK8 as stated here. A: There is a newer version Tizen Studio available. Version 3.7 is bundled with Java and does not need any Java related setting in the system, thus avoiding all the issues stated above.
Q: Java swing Jtable not updating through fireXXX using AbstractTableModel I have a JTable in my GUI, which I wish to update dynamically. Associated to the Jtable is of course a TableModel, where I've extended the AbstractTableModel and overridden appropiate methods. I have four methods for my JTable: * *AddRow *CopySelectedRow *DeleteSelectedRow *DeleteAll When I run either AddRow or CopySelectedRow the table is 'one update behind': If I press newRow once, nothing happens visually. If I press newRow twice, the first one is shown while the second isn't. However, using deleteSelected or deleteAll updates the table when I click (i.e. not behind). Extract of my TableModel class: public class TableModel extends AbstractTableModel { private List<String[]> data; public TableModel() { data = new ArrayList<String[]>(); } ... public void setValueAt(Object aValue, int rowIndex, int columnIndex) { data.get(rowIndex)[columnIndex] = aValue.toString(); fireTableCellUpdated(rowIndex, columnIndex); } public void addRow(String[] aValue) { data.add(aValue); fireTableRowsInserted(data.size()-1, data.size()-1); } public void copyRow(int rowIndex) { addRow(data.get(rowIndex)); } public void removeRow(int rowIndex) { data.remove(rowIndex); fireTableRowsDeleted(rowIndex, rowIndex); } And how I call them: JButton newRow = new JButton("New row"); newRow.addActionListener(new ActionListener() { // Handling newRow event public void actionPerformed(ActionEvent e) { tableModel.addRow(new String[]{"", "", "", "", "", "", "", "", "", "", ""}); } }); JButton copyRow = new JButton("Copy selected row"); copyRow.addActionListener(new ActionListener() { // Handling copyRow event public void actionPerformed(ActionEvent e) { if (table.getSelectedRow() != -1) { tableModel.copyRow(table.getSelectedRow()); } } }); JButton deleteRow = new JButton("Delete selected row"); deleteRow.addActionListener(new ActionListener() { // Handling deleteRow event public void actionPerformed(ActionEvent e) { if (table.getSelectedRow() != -1) { tableModel.removeRow(table.getSelectedRow()); } } }); JButton deleteAllRows = new JButton("Delete all rows"); deleteAllRows.addActionListener(new ActionListener() { // Handling deleteAllRows event public void actionPerformed(ActionEvent e) { for (int i = tableModel.getRowCount() - 1; i >= 0; i--) { tableModel.removeRow(i); } } }); EDIT: I chose to use an AbstractTableModel because I had the same problem with the DefaultTableModel (whenever I added a row, it wasn't added until the next was 'added'), and with an AbstractTableModel I would be able to fire change events myself. However, it didn't fix a thing. Can anyone please shed some light on my issue here? I'd be happy to elaborate more on the case, should anyone need some more information. A: A method FireTableDataChanged(); detects any kind of alteration in table data object and update the GUI respectively, you can try that instead of fireTableRowsInserted();
Q: How to pull specific parts of a list on each line? I have a list that spits out information like this: ['username', 'password'], ['username', 'password'], ['username', 'password'], and so on.. I would like to be able to pull a specific username and password later on. For example: ['abc', '9876'], ['xyz', '1234'] pull abc and tell them the password is 9876. Then pull xyz and tell them the password is 1234 I tried messing around with the list and I am just drawing a blank on how to do this. lines = [] with open("output.txt", "r") as f: for line in f.readlines(): if 'Success' in line: #get rid of everything after word success so only username and password is printed out lines.append(line[:line.find("Success")-1]) for element in lines: #split username and password up at : so they are separate entities #original output was username:password, want it to be username, password parts = element.strip().split(":") print(parts) I want to pull each username and then pull their password as described above Current output after running through this is ['username', 'password']. The original output file had extra information that I got rid of which is what the code involving 'Success' took care of I would like to do this without hardcoding a username in to it. I am trying to automate this process so that it runs through every username and formats it to say, "hi [username}, your password is [123]", for all of the usernames I then later would like to be able to only tell the specific user their password. For example, i want to send an email to user abc. that email should only contain the username and password of user abc A: Instead of printing parts, append them to a list. data = [] for element in lines: parts = element.strip().split(":") data.append(parts) Then you could convert these into a dictionary for lookup username_passwords = dict(data) print(username_passwords['abc']) A: If I am understanding this correctly parts is the list that contains [Username:Password]. If that is the case we can assign each value of parts which should only have 2 elements in it to a dictionary as a dictionary pair and then call the username later on. lines = [] User_Pass = {} with open("output.txt", "r") as f: for line in f.readlines(): if 'Success' in line: #get rid of everything after word success so only username and password is printed out lines.append(line[:line.find("Success")-1]) for element in lines: #split username and password up at : so they are separate entities parts = element.strip().split(":") User_Pass.update({parts[0] : parts[1]}) Then you can call the password from the username as follows if you know the username: x = User_Pass["foo"] Or as you stated in the comments: for key, value in User_Pass.items(): print('Username ' + key + ' Has a Password of ' + value) A: it looks like after you do this lines.append(line[:line.find("Success")-1]) lines = ['username:password', 'username:password'...] so I would do this new_list_of_lists = [element.strip().split(":") for element in lines] new_list_of_lists should now look like [[username, password], [username, password]] then just do this: dict_of_usernames_and_passwords = dict(new_list_of_lists) with a dict you can have now retrieve passwords using usernames. like: dict_of_usernames_and_passwords['abc'] you can save the dict, using json module, to a file, for easy retrieval.
Q: Angularjs: models binding I have directive which dynamically creates input tags. I need to get values of created inputs on change event. Instead of it the name attribute on $scope argument in the controller is undefined. How to get ng-model value in the directive controller? module.directive('createControl', function($compile, $timeout){ return { transclude: true, restrict: 'A', scope: { name: '=name' }, link: function(scope, element, attrs){ // simplified version tag = '<input type="text" ng-model="name"/>' element.append(html); controller: function($scope){ // In the controller I need to get value of created input on change event console.log($scope); } } }); A: I'm not 100% sure what you want to do, but I'm guessing it's something like this: module.directive('createControl', function($compile, $timeout){ return { transclude: true, restrict: 'A', scope: { name: '=name' }, link: function(scope, element, attrs){ // simplified version var tag = angular.element('<input type="text" ng-model="name" ng-change="changed(name)">'); element.append(tag); $compile(tag)(scope); }, controller: function($scope){ // In the controller I need to get value of created input on change event $scope.changed=function(name){ console.log('changed to: '+name); } } } }); The link function creates a new input element, compiles it with the $compile service and then links the new input element with scope. This works with the following markup: Hello {{myInput}}! <div create-control name="myInput"> </div> Check out this plunker: http://plnkr.co/edit/7XY90LXNn6gqpP47JaCH?p=preview A: The problem is controller executed earlier than directive. So in controller should be $watched $scope, not html tags added in a directive. However I think a controller binded to a directive should not know about directive state, correct me if I am wrong. So there is two approaches: module.directive('createControl', function($compile, $timeout){ return { transclude: true, restrict: 'A', scope: { name: '=name' }, link: function($scope, $element, $attrs){ // simplified version var tag = angular.element('<input type="text" ng-model="name" ng-change="changed(name)">'); $element.append(tag); $compile(tag)(scope); }, controller: function($scope, $element, $attrs){ $scope.$watch('Name', function(){ console.log(arguments); }); } }); The second one: module.directive('createControl', function($compile, $timeout){ return { transclude: true, restrict: 'A', scope: { name: '=name' }, link: function($scope, $element, $attrs){ // simplified version var tag = angular.element('<input type="text" ng-model="name" ng-change="changed(name)">'); $element.append(tag); $compile(tag)(scope); $element.find('input').on('change', function(){ console.log($scope); }) } });
Q: Is the rabbit constant the first natural math constant found to be non-normal? The rabbit constant (related to Fibonacci numbers), as well as proof of its non-normalcy, is discussed in one of my recent articles, here. One might argue that it is a semi-artificial number. I was wondering if besides that number, and excluding artificial numbers such as $0.100111100000000111\ldots$, other irrational math constants are known to be non-normal (that is, with a digit distribution that is not uniform.)
Q: Hover Div and Table Rows at Same time What are the possible ways of making a hover effect on a particular div and its corresponding table row. Say I have 3 divs and 3 rows in a table, and I want a situation where when you hover the first div the first row in the table shows the hover effect as well, etc. A: Let's start with this HTML: <div class="divs"> <div>div a</div> <div>div b</div> <div>div c</div> </div> <table> <tr> <td>row a</td> </tr> <tr> <td>row b</td> </tr> <tr> <td>row c</td> </tr> </table> What you want is very simple with a few helper functions (qsa, on, and each): var divs = qsa('.divs div'); var rows = qsa('table tr'); each(divs, function(div, i) { on(div, 'mouseover', function() { rows[i].classList.add('hover'); }); on(div, 'mouseout', function() { rows[i].classList.remove('hover'); }); }); /* helpers **************************************/ // Get elements by CSS selector: function qsa(selector, scope) { return (scope || document).querySelectorAll(selector); } // Add event listeners: function on(target, type, callback, useCapture) { target.addEventListener(type, callback, !!useCapture); } // Loop through collections: function each(arr, fn, scope) { for (var i = 0, l = arr.length; i < l; i++) { fn.call(scope, arr[i], i, arr); } } Demo: http://jsbin.com/bukinuhopa/edit?html,css,js,console,output A: You can try using JQuery hover and if hover is run on element you can do the same on the rest of divs in row.
Q: What exactly do the "Architectures" & "valid architectures" options in Xcode mean, and what should I set for iOS projects? I work with cross platform code, which means I have to build open-source C++ projects for iOS to use them in my iOS app. Sometimes I have to build my own project, sometimes I get a nice CMake setup, but no two projects seem to have exactly the same settings for these two fields. Some have "armv7", others "armv7 armv7s" and others "armv7 armv7s arm64". I get that "armv7" refers to a specific generation of device hardware. But does that mean if I only set "armv7" my app won't run on armv7s or the new 64bit iPad? Are these multiple architectures like having fat libraries, with separate copies for each architecture? Then for "Architectures" there are even more options. Options like "Standard Architectures(armv7, armv7s)" and others like "$(ARCHS_STANDARD_32_64_BIT)". I often find these have to be changed to get things to build, without errors about i386. The fact an iOS project actually gets built for Intel (simulator) as well as Arm just confuses things further for me. I'm really after a higher level explanation how this fits together than a "use this setting" answer. I want to be confident my app will work on the devices it is intended to, since I cannot afford all the different versions of iPad now in existence. For reference, I want to support iPad 2 and up, and iOS 6/7 only. A: These are different instruction sets. If you're building a library, you need to build all the different instruction sets/architectures that the downstream application will require, otherwise you'll get linker errors when you try and build the app. This is complicated by the simulator, which needs Intel x86 or x86_64 rather than ARM. Based on what you select, the compiler will create fat libraries containing multiple architectures. There is some compatibility between the different instruction sets at runtime (for instance, 32bit will run on 64bit) but that won't help during linking. If you're compiling 64bit, then the libraries you're including will need 64bit. So the short answer is set for the devices you're targeting. E.g. you probably don't need armv6 any more.
Q: Regex to find and replace spaces within pattern I have the following string: "data-template='Test xxx' root{--primary-font:'XYZ Sans';--secondary-font:'Test Sans';--hero-background:#ffbe3f;--header-colour-highlight:#f0591e;--header-background:#ffffff;--header-colour-tabs:#1d2130; }" I need to replace the spaces from -font:'XYZ Sans' and -font:'Test Sans' in order to make it -font:'XYZSans' and -font:'TestSans' Edit: the text inside the -font: may change it is not static. Could anyone help with that? A: Try this: Edit: This also works (?<=XYZ|Test) (?=Sans). (?<=XYZ) (?=Sans)|(?<=Test) (?=Sans) 1- (?<=XYZ) (?=Sans) match a space preceded by XYZ but do not include XYZ as a part of that match, at the same time the space should be followed by Sans, but don't include Sans as a part of the match, we only want the space . This part will match the first space between XYZ Sans 2- | the alternation operator | , it is like Boolean OR If the first part of the regex(i.e., the pattern before |) matches a space , the second part of the regex(i.e., the pattern after |) will be ignored, this is not what we want because of that we have to add g modifier which means get all matches and don't return after first match. See live demo. to check the g modifier and try to unset it and see the result. it is the g right after the regex pattern looks like that /(?<=XYZ) (?=Sans)|(?<=Test) (?=Sans)/g << 3- (?<=Test) (?=Sans) match a space preceded by Test but do not include Test as a part of that match, at the same time the space should be followed by Sans, but don't include Sans as a part of the match, we only want the space. This part will match the second space between Test Sans EDIT: This is another regex pattern will match any space exists inside the value of -font:, it is dynamic. (?<=-font:\s*['\x22][^'\x22]*?)\s(?=[^'\x22]*) See live demo. "data-template='Test xxx' root{--primary-font:'XYZ Sans';--secondary-font:'Test Sans';--hero-background:#ffbe3f;--header-colour-highlight:#f0591e;--header-background:#ffffff;--header-colour-tabs:#1d2130; }" The C# code that does what you want is something like this: Note: I updated the regex pattern in the code. using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string input = "\"data-template='Test xxx' root{--primary-font:'XYZ Sans';--secondary-font:'Test Sans';--hero-background:#ffbe3f;--header-colour-highlight:#f0591e;--header-background:#ffffff;--header-colour-tabs:#1d2130; }\""; string pattern = @"(?<=-font:\s*['\x22][^'\x22]*?)\s(?=[^'\x22]*)"; string replacement = ""; string result = Regex.Replace(input, pattern, replacement); Console.WriteLine("Original String: {0}", input); Console.WriteLine("\n\n-----------------\n\n"); Console.WriteLine("Replacement String: {0}", result); } }
Q: Adding objects to nsmutablearray swift I added the string objects inside the mutablearray : let photoArray: NSMutableArray = [] for photo in media { photoArray.add("\(photo.fileName ?? "")") } Then I get an output like: <__NSSingleObjectArrayI 0x1c02069e0>( ( "Car", "Dog", "Tree" ) ) But I want this : ( "Car", "Dog", "Tree" ) Is there any way to get the output like that? A: Try this, it works for me perfectly. var photoArray = [String]() for photo in media { let fileName = photo.fileName ?? "" print("fileName - \(fileName)") photoArray.append(fileName) } print("\n\n** photoArray - \n\(photoArray)") result = ["Car", "Dog", "Tree"]
Q: Serre's conditions under blow-ups, Blowup and normalization Suppose $X = \mathbb{Z}[x, y, z]/(f,g)$ is a 2-dimensional Cohen-Macaulay surface. In particular, $X$ satisfies Serre's condition $S_2$. Suppose it is irreducible, reduced but not normal. $\bf{Question}$: Are there tools I could use to identify how the $S_2$-locus or Cohen macaulay locus behaves under various kinds of blow-ups. I imagine they are well-behaved under blowups along regular centers. Are there tools that allow up to say more in certain cases? Does Grothendieck duality somehow give a little information? For example, suppose $p$ is an arbitrary height one prime of $X$. Is the blow up of $X$ at $p$ still an $S_2$ surface. References will be greatly appreciated! A: There is some literature in the commutative algebra world that might be relevant, although I don't know it super-well. I don't think anything follows immediately from Grothendieck duality, especially for blowing up height-1 primes. Say $R$ is a 2-dimensional and Cohen-Macaulay ring (equivalently S2). Suppose that $p$ is an arbitrary height-1-prime. Since $R$ is 2-dimensional, the analytic spread of $p$ is at most $2$. (See the book of Swanson-Huneke on integral closure, there are some subtleties with analytic spread in the case of a finite residue field -- be careful). We have two cases. The analytic spread of $p$ is 2 Probably this is the more interesting case. Suppose there happens to be only one ideal $J$, with two generators such that $J p = p^2$ (this isn't as strong as it might sound, it's a bit stronger than requiring that $J$ and $p$ have the same normalized blowup). Additionally suppose that $R_p$ is regular (maybe this is too strong). Then Theorem 3.1 in this paper by Santiago Zarzuela proves that the Rees Algebra of the ideal is Cohen-Macaulay, and hence so is the blowup. There is also a lot of potentially relevant stuff in this paper of Huckaba and Huneke. (You can look at the papers which cite it on mathscinet to find even more). The analytic spread of $p$ is 1 In particular, then the blowup of $p$ is some finite integral extension of $R$ (in particular, the blowup is an affine scheme dominated by the normalization of $R$). Since $R$ was S2, this implies that $p$ is a prime defining an irreducible component of the non-normal locus. You want to keep the blowup S2... I don't know in general if this is possible but I recall that some conditions for such blowups being normalizations appeared towards the end of this paper by Greco and Traverso. Does your surface happen to be seminormal?
Q: Optional attribute values in MappedField I'm new to Scala and Lift, coming from a slightly odd background in PLT Scheme. I've done a quick search on this topic and found lots of questions but no answers. I'm probably looking in the wrong place. I've been working my way through tutorials on using Mapper to create database-backed objects, and I've hit a stumbling block: what types should be used to stored optional attribute values. For example, a simple ToDo object might comprise a title and an optional deadline (e.g. http://rememberthemilk.com). The former would be a MappedString, but the latter could not be a MappedDateTime since the type constraints on the field require, say, defaultValue to return a Date (rather than a Date or null/false/???). Is an underlying NULL handled by the MappedField subclasses? Or are there optional equivalents to things like MappedInt, MappedString, MappedDateTime that allow the value to be NULL in the database? Or am I approaching this in the wrong way? A: The best place to have Lift questions answered is the Lift group. They aren't into Stack Overflow, but if you do go to their mailing list, they are very receptive and helpful. A: David Pollak replied with: Mapper handles nulls for non-JVM primitives (e.g., String, Date, but not Int, Long, Boolean). You'll get a "null" from the MappedDateTime.is method. ... which is spot on.
Q: PHP Form won't send through server I am using Hostgator for the server side processing, and I am using their form to try to get this to happen, but it will not send. I get to an error page and my url shows. "...com/email_form.php?do=send" Am I missing something that will pull the action to use the server side processing or do I have an error that I am not seeing? <?php switch (@$_GET['do']) { case "send": $fname = $_POST['fname']; $lname = $_POST['lname']; $femail = $_POST['femail']; $f2email = $_POST['f2email']; $saddy = $_POST['saddy']; $scity = $_POST['scity']; $szip = $_POST['szip']; $fphone1 = $_POST['fphone1']; $mname = $_POST['mname']; $sapt = $_POST['sapt']; $sstate = $_POST['sstate']; $scountry = $_POST['scountry']; $fphone2 = $_POST['fphone2']; $fphone3 = $_POST['fphone3']; $fsendmail = $_POST['fsendmail']; $secretinfo = $_POST['info']; if (!preg_match("/\S+/",$fname)) { unset($_GET['do']); $message = "First Name required. Please try again."; break; } if (!preg_match("/\S+/",$lname)) { unset($_GET['do']); $message = "Last Name required. Please try again."; break; } if (!preg_match("/^\S+@[A-Za-z0-9_.-]+\.[A-Za-z]{2,6}$/",$femail)) { unset($_GET['do']); $message = "Primary Email Address is incorrect. Please try again."; break; } if ($f2email){ if (!preg_match("/^\S+@[A-Za-z0-9_.-]+\.[A-Za-z]{2,6}$/",$f2email)) { unset($_GET['do']); $message = "Secondary Email Address is incorrect. Please try again."; break; } } if (!preg_match("/\S+/",$saddy)) { unset($_GET['do']); $message = "Street Address required. Please try again."; break; } if (!preg_match("/\S+/",$scity)) { unset($_GET['do']); $message = "City required. Please try again."; break; } if (!preg_match("/^[0-9A-Za-z -]+$/",$szip)) { unset($_GET['do']); $message = "Zip/Post Code required. Please try again."; break; } if (!preg_match("/^[0-9 #\-\*\.\(\)]+$/",$fphone1)) { unset($_GET['do']); $message = "Phone Number 1 required. No letters, please."; break; } if ($secretinfo == "") { $myemail = "[email protected]"; $emess = "First Name: ".$fname."\n"; $emess.= "Middle Name: ".$mname."\n"; $emess.= "Last Name: ".$lname."\n"; $emess.= "Email 1: ".$femail."\n"; $emess.= "Email 2: ".$f2email."\n"; $emess.= "Street Address: ".$saddy."\nApt/Ste: ".$sapt."\n"; $emess.= "City: ".$scity."\nState: ".$sstate."\nZip/Post Code:".$szip."\n"; $emess.= "Country: ".$scountry."\n"; $emess.= "Phone number 1: ".$fphone1."\n"; $emess.= "Phone number 2: ".$fphone2."\n"; $emess.= "Phone number 3: ".$fphone3."\n"; $emess.= "Comments: ".$fsendmail; $ehead = "From: ".$femail."\r\n"; $subj = "An Email from ".$fname." ".$mname." ".$lname."!"; $mailsend=mail("$myemail","$subj","$emess","$ehead"); $message = "Email was sent."; } unset($_GET['do']); header("Location: thankyou.html"); break; default: break; } ?><html> <body> <form action="email_form.php?do=send" method="POST"> <p>* Required fields</p> <?php if ($message) echo '<p style="color:red;">'.$message.'</p>'; ?> <table border="0" width="500"> <tr><td align="right">* First Name: </td> <td><input type="text" name="fname" size="30" value="<?php echo @$fname ?>"></td></tr> <tr><td align="right">Middle Name: </td> <td><input type="text" name="mname" size="30" value="<?php echo @$mname ?>"></td></tr> <tr><td align="right">* Last Name: </td> <td><input type="text" name="lname" size="30" value="<?php echo @$lname ?>"></td></tr> </table> <p> <table border="0" width="500"> <tr><td align="right">* Primary Email: </td> <td><input type="text" name="femail" size="30" value="<?php echo @$femail ?>"></td></tr> <tr><td align="right">Secondary Email: </td> <td><input type="text" name="f2email" size="30" value="<?php echo @$f2email ?>"></td></tr> </table> <p> <table border="0" width="600"> <tr><td align="right">* Street Address: </td> <td><input type="text" name="saddy" size="40" value="<?php echo @$saddy ?>"></td></tr> <tr><td align="right">Apartment/Suite Number: </td> <td><input type="text" name="sapt" size="10" value="<?php echo @$sapt ?>"></td></tr> <tr><td align="right">* City: </td> <td><input type="text" name="scity" size="30" value="<?php echo @$scity ?>"></td></tr> <td align="right">State: </td> <td><input type="text" name="sstate" size="10" value="<?php echo @$sstate ?>"></td></tr> <tr><td align="right">* Zip/Post Code: </td> <td><input type="text" name="szip" size="10" value="<?php echo @$szip ?>"></td></tr> <tr><td align="right">Country: </td> <td><input type="text" name="scountry" size="30" value="<?php echo @$scountry ?>"></td></tr> </table> <p> <table border="0" width="500"> <tr><td align="right">* Phone Number 1: </td> <td><input type="text" name="fphone1" size="20" value="<?php echo @$fphone1 ?>"></td></tr> <tr><td align="right">Phone Number 2: </td> <td><input type="text" name="fphone2" size="20" value="<?php echo @$fphone2 ?>"></td></tr> <tr><td align="right">Phone Number 3: </td> <td><input type="text" name="fphone3" size="20" value="<?php echo @$fphone3 ?>"> <input style="display:none;" name="info" type="text" value=""> </td></tr> </table> <p> <table border="0" width="500"><tr><td> Comments:<br /> <TEXTAREA name="fsendmail" ROWS="6" COLS="60"><?php if($fsendmail) echo $fsendmail; ?></TEXTAREA> </td></tr> <tr><td align="right"><input type="submit" value="Send Now"> </td></tr> </table> </form> </body> </html> A: Your form method is POST but you're using $_GET. Switch the form method to GET or switch your variables to $_POST
Q: ckeditor official demo can paste image from clipboard why I can't? http://ckeditor.com/demo The ckeditor demo (standard) in above links can direct paste image from clipboard. but when I click to download the standard version I can't paste image in the sample html. why ? what should I do so that my build In include function of paste image from clipboard available by default ? regards Yeong
Q: java.net.SocketTimeoutException: Read timed out on creating JedisCluster I am new to Redis. I am using Jedis as the Java Client and am trying to create a cluster with 6 nodes. I started redis-servers on 6 ports with following configuration - port 7005 cluster-enabled yes cluster-config-file nodes.conf cluster-node-timeout 30000 protected-mode no zset-max-ziplist-entries 128 zset-max-ziplist-value 256 Following is the code I am using to create JedisCluster - public class JedisClusterConnection implements RedisCluster { JedisCluster jedisCluster; public JedisClusterConnection() { Set<HostAndPort> nodes = new HashSet<>(); nodes.add(new HostAndPort("127.0.0.1", 7000)); nodes.add(new HostAndPort("127.0.0.1", 7001)); nodes.add(new HostAndPort("127.0.0.1", 7002)); nodes.add(new HostAndPort("127.0.0.1", 7003)); nodes.add(new HostAndPort("127.0.0.1", 7004)); nodes.add(new HostAndPort("127.0.0.1", 7005)); this.jedisCluster = new JedisCluster(nodes, 30000); } I am getting following errors while creating the JedisCluster Caused by: redis.clients.jedis.exceptions.JedisDataException: EXECABORT Transaction discarded because of previous errors. at redis.clients.jedis.Protocol.processError(Protocol.java:96) ~[jedis-4.2.0.jar:na] at redis.clients.jedis.Protocol.process(Protocol.java:137) ~[jedis-4.2.0.jar:na] at redis.clients.jedis.Protocol.read(Protocol.java:192) ~[jedis-4.2.0.jar:na] at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:316) ~[jedis-4.2.0.jar:na] at redis.clients.jedis.Connection.getUnflushedObjectMultiBulkReply(Connection.java:282) ~[jedis-4.2.0.jar:na] at redis.clients.jedis.Connection.getObjectMultiBulkReply(Connection.java:287) ~[jedis-4.2.0.jar:na] at redis.clients.jedis.TransactionBase.exec(TransactionBase.java:132) ~[jedis-4.2.0.jar:na] at redis.clients.jedis.Transaction.exec(Transaction.java:47) ~[jedis-4.2.0.jar:na] Error
Q: asp.net core: "Operations that change non-concurrent collections must have exclusive access." My server uses MySqlConnector and communicates with a MySQL database on AWS. I store 5 minute chunks of API counters in MySQL. Those API counters are incrementing with each API call, and are handled by ConcurrentDictionary code (which doesn't appear to be a problem). An exception was recently raised by this line of code, which is part of a linq query through MySqlConnector to access a MySQL database table: await _context.ApiCounts.Where(c => c.ApiName == apiName && c.StartTime >= startTime).ToListAsync(); I've never seen this line fail before, but suddenly one of my servers started throwing the following exception at the line above: InvalidOperationException: Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct. at System.ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported at System.Collections.Generic.Dictionary`2.FindEntry at System.Collections.Generic.Dictionary`2.TryGetValue at Remotion.Linq.Parsing.Structure.NodeTypeProviders.MethodInfoBasedNodeTypeRegistry.GetNodeType at Remotion.Linq.Parsing.Structure.NodeTypeProviders.MethodInfoBasedNodeTypeRegistry.IsRegistered at System.Linq.Enumerable.Any at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.GetQueryOperatorExpression at Remotion.Linq.Parsing.ExpressionVisitors.SubQueryFindingExpressionVisitor.Visit at System.Linq.Expressions.ExpressionVisitor.VisitBinary at System.Linq.Expressions.BinaryExpression.Accept at System.Linq.Expressions.ExpressionVisitor.VisitBinary at System.Linq.Expressions.BinaryExpression.Accept at System.Linq.Expressions.ExpressionVisitor.VisitLambda at System.Linq.Expressions.Expression`1.Accept at System.Linq.Enumerable+SelectListPartitionIterator`2.ToArray at System.Linq.Enumerable.ToArray at Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.Parse at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression at Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileAsyncQueryCore at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler+<>c__DisplayClass24_0`1.<CompileAsyncQuery>b__0 at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.System.Collections.Generic.IAsyncEnumerable<TResult>.GetEnumerator at System.Linq.AsyncEnumerable+<Aggregate_>d__6`3.MoveNext at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification at BlayFap.Controllers.ServerController+<GetCachedApiCount>d__13.MoveNext (E:\Projects\BlayFap\BlayFap\Controllers\ServerController.cs:342) at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification at BlayFap.Controllers.ServerController+<GetApiCount>d__14.MoveNext (E:\Projects\BlayFap\BlayFap\Controllers\ServerController.cs:378) at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeActionMethodAsync>d__12.MoveNext at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextActionFilterAsync>d__10.MoveNext at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeInnerFilterAsync>d__14.MoveNext at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResourceFilter>d__22.MoveNext at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeFilterPipelineAsync>d__17.MoveNext at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeAsync>d__15.MoveNext at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw All of the other tables can be accessed fine, but from here on any attempt to use the ApiCounts table results in the above exception. I had to actually reboot the affected server to clear the error. It looks like this exception has to do with concurrent edits on a Dictionary, and that Dictionary appears to be in linq code. I'm guessing that the server may have gotten caught in a situation where EF was both updating and writing some sort of data while executing a linq statement, and then got the Dictionary stuck in a weird state, but I'm not sure how to protect against this and where the real issue is. Is this a .NET bug, or my own? More info: I do not modify the result from ApiCounts in this function, and I do not call SaveChanges. It is, however, possible for code running async to this (in another REST query) to update ApiCounts and call SaveChanges. A: The solution is to update to EF 2.1.5 or newer. I was using EF 2.0.3 when this error occurred. It looks like there was a thread unsafe singleton, which could result in the same error I saw. Here's the issue in github: https://github.com/dotnet/efcore/issues/12682 A: In my case, i had the same issue. after spending hours, i restarted the application pool in IIS it started working like a charm. First I tried to duplicate the issue in different environment. It occurred only in PROD environment. So I restarted the IIS application pool which gave me the expected output A: I found the solution for this particular issue by changing the registration of Dependency Injection from Singleton to Transient. The reason for the issue is basically as we have registered our repository or context singleton and we are using the same scope in multiple threads and that's why one thread will not be able to find the resource and that's why throw an exception by switching to transient we create scopes for every thread that's why solve the case.
Q: Intellij error "HTML::Mason components are not configured" I am trying to work with Perl/Mason packages on Intellij. I see red underlines everywhere with an error saying "HTML::Mason components are not configured". What steps do I need to take to get rid of them? A: To fix this, go to the Settings menu, select Perl5, select your project, click the "HTML::Mason components" button, and select your source folder. A: You have to provide the source directory of your components folder where you are going to store your *.mas(components) files. Go to Settings, select Perl5 and then select you component root folder.
Q: Making parent div clickable for a checkbox + label with JQuery I got the following HTML <div class="ccm-custom-style-container ccm-custom-style-intro4-308 image-caption"> <input checked="true" type="checkbox"> <label for="D_1"><span></span><p>whitepaper is geselecteerd</p></label> <h4>header</h4> <p>text</p> </div> I use 2 scripts with this code: the first script toggles the html text between <label> and </label> depending if the checkbox is checked or not: $('input').change(function() { if ($(this).is(':checked')) { $(this).('label').html('<span></span>whitepaper is geselecteerd'); } else { $(this).('label').html('<span></span>whitepaper niet geselecteerd'); }}); The second script toggles the class of the parent div: $('input').change(function () { var checked = $(this).is(':checked'); $(this).parent().toggleClass('ccm-custom-style-intro4-308',checked); $(this).parent().toggleClass('ccm-custom-style-intro4-309',!checked);}); This all works perfectly, but now i want to enable users to click the entire div to toggle the checkbox from checked to unchecked and back. I'm no Jquery-god so i was wondering: How would i be able to do this so it will all work together? A: you can make a click event for div and .trigger('change'); the input $('.ccm-custom-style-container').on('click',function(){ $(this).find('input').trigger('change'); }); Working Demo
Q: nginx - how to decrease speed for ip if too many requests i have following configuration: limit_req_zone $binary_remote_addr zone=one:10m rate=300r/m; … server{ … location / { limit_req zone=one; … } … } But i want to not show error page(503) for user, but just decrease speed. A: Try this: location / { if ($ips) { limit_rate 256k; } } Set $ips by using geo: geo $ips { default 0; 1.2.3.0/32 1; //edit ip address }
Q: How to Update the content of my app with out the user updating the app version Hey guys am a new programmer for android development, and i was doing a project that needs the content to be updated more frequently an i don't know how to do that. will you help me please. The contents i need to update are like texts as well as pictures Help please. A: If you want to update data from database, you will need to use thread and perhaps a timer would help too which will trigger the thread to get data from database. This link will help you to implement threading. And inside the thread, you will connect with remote server's API to get the data you wanted.
Q: How to know which stack is clicked, in a grouped stacked bar (chartjs)? I created a bar chart similar to the picture. I am using two stacks as a group. Every stack might have multiple datasets. I am using Vue.js and vue-chartjs. I am using following onClick option of Chart.js, e is the event and i is array of datasets used in the chart. By knowing the index of one of datasets we know which group is clicked. In this way,I know which group is clicked on. However I need to know which stack is clicked on. onClick: (e, i ) => { console.log(i[0]._index) } Data which i am using for chart: this.datacollection = { labels: [...Object.keys(total)], datasets: [ { label: 'Started', stack: 'Stack 0', backgroundColor: 'rgb(112,108,236,0.2)', borderColor: 'rgb(112,108,236,0.3)', borderWidth: 5, data: Object.values(active) }, { label: 'Assigned (all)', stack: 'Stack 0', backgroundColor: 'rgb(137,37,252 , 0.2)', borderColor: 'rgb(137,37,252 , 0.2)', borderWidth: 5, data: Object.values(total), }, { label: 'Finished', stack: 'Stack 0', backgroundColor: 'rgba(30,135,246, 0.3)', borderColor: 'rgba(30,135,246, 0.4)', borderWidth: 5, data: Object.values(done) }, { label: 'Rated', stack: 'Stack 0', backgroundColor: pattern.draw('dot-dash', 'rgb(98,241,58 , 0.5)'), borderColor: 'rgb(98,241,58 , 0.5)', borderWidth: 5, data: Object.values(rated) }, { label: 'Trashed', stack: 'Stack 1', backgroundColor: 'rgb(236,108,127,0.5)', borderColor: 'rgb(236,108,127,0.5)', borderWidth: 5, data: Object.values(trashed) }, ] } and this is option of the chart { responsive: true, maintainAspectRatio: false, scales: { xAxes: [ { stacked: true } ], yAxes: [ { ticks: { beginAtZero: true }, stacked: false } ] }, onClick: (e, i) => { console.log(i[0]._index) } } Above information might be enough for you, but if You like to see the full code: test.vue: <template> <div> <bar-chart :chart-data="datacollection" :options="options"></bar-chart> </div> </template> <script> import BarChart from '@/components/Charts/BarChart.js' import pattern from 'patternomaly'; export default { components: { BarChart, }, data() { return { datacollection: null, loaded: false, options: { responsive: true, maintainAspectRatio: false, scales: { xAxes: [{stacked: true}], yAxes: [{ ticks: { beginAtZero: true }, stacked: false }] }, onClick: (e, i ) => { console.log(e); } } } }, mounted() { this.fillData() }, methods: { fillData() { this.loaded = false; window.axios.get('/api/reports/tests', { params: { dateRange: this.dateRange } }) .then((res) => { let total = res.data.total; let done = res.data.done; let active = res.data.active; let trashed = res.data.trashed; let rated = res.data.rated; this.datacollection = { labels: [...Object.keys(total)], datasets: [ { label: 'Started', stack: 'Stack 0', backgroundColor: 'rgb(112,108,236,0.2)', borderColor: 'rgb(112,108,236,0.3)', borderWidth: 5, data: Object.values(active) }, { label: 'Assigned (all)', stack: 'Stack 0', backgroundColor: 'rgb(137,37,252 , 0.2)', borderColor: 'rgb(137,37,252 , 0.2)', borderWidth: 5, data: Object.values(total), }, { label: 'Finished', stack: 'Stack 0', backgroundColor: 'rgba(30,135,246, 0.3)', borderColor: 'rgba(30,135,246, 0.4)', borderWidth: 5, data: Object.values(done) }, { label: 'Rated', stack: 'Stack 0', backgroundColor: pattern.draw('dot-dash', 'rgb(98,241,58 , 0.5)'), borderColor: 'rgb(98,241,58 , 0.5)', borderWidth: 5, data: Object.values(rated) }, { label: 'Trashed', stack: 'Stack 1', backgroundColor: 'rgb(236,108,127,0.5)', borderColor: 'rgb(236,108,127,0.5)', borderWidth: 5, data: Object.values(trashed) }, ] } this.loaded = true; }) } } } </script> BarChart.js: import { Bar , mixins } from 'vue-chartjs' const { reactiveProp } = mixins export default { extends: Bar, mixins: [reactiveProp], props: ['chartData' , 'options'], mounted () { if (this.chartdata) this.renderChart(this.chartdata) } } A: I found a way usign chart.getElementAtEvent(evt) let chart = this.$refs.barChart.$data._chart; let datasetIndex = chart.getElementAtEvent(evt)[0]._datasetIndex let stack = chart.getDatasetMeta(datasetIndex).stack;
Q: Python and Connecting to MySQL over SSH I am trying to connect to a MySQL database on someone else's "machine". When I use Navicat for MySQL, I have no problem connecting to it. I am trying to do the same with Python so that I do not have to use the GUI interface. I know all my info below is correct (even though I swap fake info) -- can anyone spot where I went wrong? The error I get is OperationalError: (2005, "Unknown MySQL server host 'FTP_hostname' (0)") My code (using paramiko for the SSH): import MySQLdb import paramiko import time ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('SSH_hostname', 22, username='me', password='pswrd') time.sleep(1) db = MySQLdb.connect(host="FTP_hostname", user="root", passwd="pswrd2", db="MyDB") cur = db.cursor() Again, I put all this into Navicat and connect no problem. Hoping you can help! Thanks! A: MySQL, like most databases, by default runs locally and disallows access from outside networks. As such, you cannot connect to it from an external computer. Navicat, being a software explicitely for remote administration of databases, likely connects via SSH and tunnels the MySQL connection over it. That way it can act as if the database was installed locally, and for the database it looks as if it was accessed locally. You could try to do the same by creating a tunnel using Paramiko; see also this question. A: If you still in need of connecting to a remote MySQL db via SSH I have used a library named sshtunnel, that wraps ands simplifies the use of paramiko (a dependency of the sshtunnel). You can check my answer in another similar question with some sample code to use it. A: db = MySQLdb.connect(host="FTP_hostname", Would the host not need to be 127.0.0.1 (localhost) as the tunnel is making the MySQL DB local to the machine that the python script is running on?
Q: a code that understands a number is prime or normal at Python I'm new in Python and write this code for recognizing a number is prime or not. I wrote a code that works in JavaScript and visual Basic, but didn't work in Python and its error is: TypeError:a float is required. my code: import math a = raw_input("Enter a number:") k = 0 i = 1 s = math.sqrt(a) while i <= s: if a % i == 0: k += 1 i += 1 if k == 2: print "prime num" else: print "normal num" what's wrong? A: Just convert the user input to int. a = int(raw_input("Enter a number:")) What's wrong is that you were trying to find the square root of a value of type string (text). A: There are more issues in your code: while loop is only up to square root of a given number, but you print prime num for k==2. In this code there will be only one divisor, and it is 1. What is more, you can start from i=2, so there will be 0 divisors for a prime number. After that, last issue is that 1 is not a prime number. So the code looks like that: import math a = int(raw_input("Enter a number:")) k = 0 i = 2 s = math.sqrt(a) #print(s) while i <= s: if a % i == 0: k += 1 i += 1 #print(k) if k == 0 and a > 1: print "prime num" else: print "normal num" A: first check the version of your python, if you using python3 then take only a=input("enter number") raw_input works for python2
Q: Xcode: forget about old repositories Xcode 7.2 gives me warnings every time I build: MyProject Project 2 issues /!\ oldSvnProject /Users/grumdrig/src/oldSvnProject is missing from working copy anotherOldProject /Users/grumdrig/src/anotherOldProject is missing from working copy I haven't used svn in years. These projects have nothing to do with Xcode. I've tried deleting the reference to an old subversion repo in Xcode -> Preferences -> Accounts -> Repositories. I've deleted every file inside my project directory that so much as mentions svn, which is these two: MyProject.xcodeproj/project.xcworkspace/xcuserdata/grumdrig.xcuserdatad/UserInterfaceState.xcuserstate MyProject.xcodeproj/project.xcworkspace/xcshareddata/MyProject.xcscmblueprint after quitting Xcode. But they always come back. Listen, and understand! That [Xcode] is out there! It can't be bargained with. It can't be reasoned with. It doesn't feel pity, or remorse, or fear. And it absolutely will not stop, ever, until you are [frustrated]. A: AHA! I believe I have it. There was an old, ossified .svn directory in the directory above my project directory. Deleting it caused the warnings to vanish in an instant!
Q: What steps do I need to take to use the Ionic Framework with trigger.io? I unsuccessfully searched for some documentation of how to integrate the Ionic Framework with trigger.io, but I don't see any. If anyone knows or has some, I'd love to see them. If not, I'll venture forward and post my steps here :) A: Including Ionic Framework Ionic Framework provides CSS and JavaScript libraries that you would include in your HTML. There are two methods for including Ionic Framework in your trigger.io app: 1. Store the Files Locally (development/production): * *You can download the Ionic CSS and JavaScript files from the Ionic CDN. *Add the JS, CSS, and fonts folders to your src folder. *Reference ionic.min.css and ionic.bundle.js in your index.html file like so: <link href="/css/ionic.min.css" rel="stylesheet"></link> <script src="/js/ionic.bundle.js"></script> * *This is the same as including any other libraries in your HTML. *Note that AngularJS is included in ionic.bundle.js, so I would suggest checking out the AngularJS API documentation. 2. Use a CDN (development only): A content delivery network (CDN) is a system of servers that delivers files to a client efficiently based on location. You can include Ionic files in your project by linking them from the Ionic CDN: <link href="http://code.ionicframework.com/1.0.0-beta.1/css/ionic.css" rel="stylesheet"> <script src="http://code.ionicframework.com/1.0.0-beta.14/js/ionic.bundle.js"></script> While Ionic is still in the beta stages you should make sure to always change your CDN link or download the new files whenever they release a new version. I'd avoid using the CDN if possible, as it can cause problems if the phone loses internet connection. It also means that you are re-downloading the files every time the app runs. Firebase I'd also suggest checking out Firebase, a great backend solution for mobile apps. It can also handle user authentication. <script src="https://cdn.firebase.com/js/client/2.2.1/firebase.js"></script> <script src="https://cdn.firebase.com/libs/angularfire/0.9.2/angularfire.min.js"></script>
Q: Differential equations rewording question I need a little bit of help understanding what a question is asking. The question is: Find $ \frac {∂w}{∂r} $ when r = 1 and s = −1 if $ w = (x + y + z)^2 , x = r− s, y = cos(r + s) and z = sin(r + s)$ . A: You can insert the expressions for $x,y$ and $z$. $w=\left(r-s+cos(r+s)+sin(r+s)\right)^2$ Using the chain rule $\frac{\partial w}{\partial r}= 2 \left(r-s+cos(r+s)+sin(r+s)\right) \cdot \left( 1-sin(r+s)+cos(r+s)\right)$ Now insert the values for $r$ and $s$.