text
stringlengths
15
59.8k
meta
dict
Q: How to prevent lazy loading in partial views, custom Display/Editor Templates? In my ASP.NET MVC 4 web application, I have utilized partial views and custom display/editor templates to modularize the code. One example is a User.cshtml DisplayTemplate which takes User (an Entity object) and prints out their name and an icon to popup their directory info. Views/Shared/DisplayTemplates/User.cshtml @model MyApp.Domain.Entities.User @if (Model != null) { @Html.DisplayFor(m => m.DisplayName) <span class="view-contact icon ui-icon ui-icon-contact" title="View Contact"></span> @Html.HiddenFor(m => m.Identity) } I'm having the opposite problem most people seem have when I searched on the topic. I've noticed that when I use this template, lazy loading is triggered and so a query is sent to the DB to grab the data, but I don't want this to happen if I've already preloaded the data, especially in the case where I show a listing of users. In that case I made sure to use .Include("User") in my query and the info displays without issue or additional querying when I essentially write out the template's code in the view: Simplified excerpt from Views/MyController/List.cshtml ... @foreach (var item in Model) { <tr> <td class="alignl"> @item.User.DisplayName <span class="view-contact icon ui-icon ui-icon-contact" title="View Contact"></span> @Html.HiddenFor(m => item.User.Identity) </td> </tr> } ... If I replace those three lines with the call to template, each line queries the db. @foreach (var item in Model) { <tr> <td class="alignl"> @Html.DisplayFor(i => item.User) </td> </tr> } How do I utilize this template without triggering a unnecessary query? A: Based on @GertArnold 's suggestion I looked a little closer at the main query that grabs the collection of users and tried to see if I could disable lazy loading. Because I was using a generic repository pattern and unit of work, I wasn't able to specifically disable it just for that call so I ended up using the context directly and everything behaved properly without disabling needed -- this breaks my pattern, but I now have the benefit of being able to use projection and save my application from eagerly loading unnecessary data columns. If anyone can point me down the right path for implementing projection in a generic repository, I'd be greatful, but I can live with this alternative solution for now. This msdn article also helped: https://msdn.microsoft.com/en-us/data/jj574232.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/32671646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring cloud config and Vault Integration I'm trying to read secret values using spring vault. All the properties for client application is stored in github and spring config server is used to access the properties. When I add the vault configuration to client application bootstrap.yml as below, the values are read properly. bootstrap.yml spring: application: name: client-app cloud: config: uri: http://config-server:8080 vault: enabled: true authentication: APPROLE app-role: role-id: 12345 secret-id: 12345 role: pres-read app-role-path: approle connection-timeout: 5000 read-timeout: 15000 kv: enabled: true backend: secrets application-name: client-app uri: https://vault/ application.yml in config server spring: cloud: config: server: git : uri: https://github/repo.git username: abc password: pass refreshRate: 300 Based on https://docs.spring.io/spring-cloud-vault/docs/current/reference/html/config-data.html#vault.configdata , it should be possible to load the vault config from properties yml in github. But if i move the above vault config to my client-app.yml in github, the properties are not read from the vault. How do I achieve this?
{ "language": "en", "url": "https://stackoverflow.com/questions/71920016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How Does Dynamic Service Discovery Work When Using Docker Compose Or Kubernetes? Let's say I am creating a chat app with microservice architecture. I have 2 services: * *Gateway service: responsible for user authentication (API endpoint /api/v1/users), and routing requests to appropriate service. *Messaging service: responsible for creating, retrieving, updating, and deleting messages (API endpoint /api/v1/messages). If I use Docker Compose or Kubernetes, how does my gateway service know which service should it forwards to if there is a request sending to /api/v1/messages API endpoint? I used to write my own dynamic service discovery middleware (https://github.com/zicodeng/tahc-z/blob/master/servers/gateway/handlers/dsd.go). The idea is that I pre-register services with API endpoints they are responsible for. And my gateway service relies on request resource path to decide which service this request should be forwarded to. But how do you do this with Docker Compose or Kubernetes? Do I still need to keep my own version of dynamic service discovery middleware? Thanks in advance! A: If you are using Kubernetes, here are the high level steps: * *Create your micro-service Deployments/Workloads using your docker images *Create Services pointing to these deployments *Create Ingress using Path Based rules pointing to the services Here is sample manifest/yaml files: (change docker images, ports etc as needed) apiVersion: v1 kind: Service metadata: name: svc-gateway spec: ports: - port: 80 selector: app: gateway --- apiVersion: v1 kind: Service metadata: name: svc-messaging spec: ports: - port: 80 selector: app: messaging --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: deployment-gateway spec: replicas: 1 template: metadata: labels: app: gateway spec: containers: - name: gateway image: gateway/image:v1.0 ports: - containerPort: 80 --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: deployment-messaging spec: replicas: 1 template: metadata: labels: app: messaging spec: containers: - name: messaging image: messaging/image:v1.0 ports: - containerPort: 80 --- apiVersion: extensions/v1beta1 kind: Ingress metadata: name: ingress-for-chat-application spec: rules: - host: chat.example.com http: paths: - backend: serviceName: svc-gateway servicePort: 80 path: /api/v1/users - backend: serviceName: svc-messaging servicePort: 80 path: /api/v1/messages If you have other containers running in the same namespace and would like to communicate with these services you can directly use their service names. For example: curl http://svc-messaging or curl http://svc-gateway You don't need to run your own service discovery, that's taken care by Kubernetes! Some visuals: Step 1: Step 2: Step 3:
{ "language": "en", "url": "https://stackoverflow.com/questions/52252743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to do a unix find based on size of files, including in subdirectories? Trying to use osx find to find all the files in my directory tree. I googled and SO'd and looked at man but none helped. So far I have: find -f -c1mb which is clearly wrong. A: find . -size +20000 The above one should work. A: I guess you want to find files bigger than 1 Mb, then do $ find . -size +1M A: On Ubuntu, this works: find . -type f -size +10k The above would find all files in the current directory and below, being at least 10k. A: This command tell you "the size" too :-) find . -size +1000k -exec du -h {} \;
{ "language": "en", "url": "https://stackoverflow.com/questions/9577636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: button onclick document instead using in JavaScript file I have some issue which i need to write in js file instead of button on-click someone help me please. I written some code but its not working properly. Thanks document.getElementById("box1").onclick = function (box) { box.style.display = 'block'; }; #box1 { position: absolute; top: 10px; left: 10px; width: 260px; height: 260px; background: #E2E2E2; padding: 20px; display: none; } <ul onclick="document.getElementById('box1').style.display='block'" class="btn-menu">pop-out Interface</ul> <h2>More Page Content...</h2> <ul id="box1"> <li><a href="#" >Homes</a></li> </ul> <h2> A: If I understand correctly, you are trying to migrate your js code to its own file to be able to toggle your elements display. The elements onclick method takes in a function to execute when the event is triggered. What we will have to do is build a function in a JS file, import that file into our markup, and then we can reference our new function in our markup in the elements onclick. function showBox(){ document.getElementById("box1")style.display = 'block'; } function hideBox(){ document.getElementById("box1")style.display = 'none'; } #box1 { position: absolute; top: 10px; left: 10px; width: 260px; height: 260px; background: #E2E2E2; padding: 20px; display: none; } <script src="/path/to/lang-js.js" /> <ul onclick="showBox()" class="btn-menu">pop-out Interface</ul> <h2>More Page Content...</h2> <ul id="box1"> <li><a href="#" >Homes</a></li> A: Here's some code that will toggle a panel off/on when you click a menu button. Hope it helps you out. It uses a data-attribute to coordinate what menu button reveals which panel. // grab all the menu buttons const menuButtons = document.querySelectorAll('.btn-menu'); // attach a click event to each button menuButtons.forEach(button => button.addEventListener('click', toggleButton, false)); function toggleButton() { // get the data-id from the clicked element const id = this.dataset.id; // pick up the panel element with that id const panel = document.getElementById(id); if (panel.style.display === 'block') { panel.style.display = 'none'; } else { panel.style.display = 'block'; } } .panel { top: 20px; left: 10px; width: 100px; height: 20px; background: #E2E2E2; padding: 20px; display: none; } <ul data-id="box1" class="btn-menu">pop-out Interface</ul> <ul data-id="box2" class="btn-menu">pop-out Interface 2</ul> <h2>More Page Content...</h2> <ul id="box1" class="panel"> <li><a href="#">Homes</a></li> </ul> <ul id="box2" class="panel"> <li><a href="#">Gardens</a></li> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/52793369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Can I use nested AsyncTasks to load images in Andorid? I am building a simple app that queries a web service to get URLs for images that I want to download. Right now, I do this by running an AsyncTask that does the query, processes the XML to find the image URLs, and populates an Object with all those details. I want to know if I can then use this Object inside onPostExecute() to create another AsyncTask that downloads all the images from the URLs in the object? Here is my code... protected SongObject doInBackground(LastFMClient... client) { LastFMClient lfmClient = client[0]; SongObject track = lfmClient.getMusicMetadata(); return track; } protected void onPostExecute(SongObject response) { // create another asynctask here to download images from the URLs in response. } A: Yes you can call other asynctask from the onpost method.
{ "language": "en", "url": "https://stackoverflow.com/questions/10529936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make splashscreenimage to work in ios phonegap apps? i'm developing phonegap app 2.9.0 in visual studio 2012 on windows 8. When i run my app in windows emulator everything works fine. I used adobe.phonegap.build to build my app for ios. And build worked properly and installed that .ipa file in my iphone everything works fine other than splashscreenimage. Instead of that a white background is appearing in my iphone. Is there any way to make my splashscreen to work? Somebody please help.. A: Unless otherwise specified in a config.xml, iOS platform will try to use the default icon.png during compilation. To define specific icons please use the guide provided: Configure Icons and Splash Screens. The default icon must be named icon.png and must reside in the root of your application folder. Also,Using a splash screen is rather easy via the PhoneGap Build config.xml file. Write a bit of JavaScript that made use of the PhoneGap Splash Screen API: document.addEventListener("deviceready", function(e) { window.setTimeout(function() { navigator.splashscreen.hide(); },5000); }, "false");
{ "language": "en", "url": "https://stackoverflow.com/questions/25405402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Rails, how can you restrict users to specific locations or computers? I am trying to restrict users, allowing them to clock in/out only while they are using a company computer or onsite. Is there a way to do either of these. I would use IP or hostname, but we have a dynamic IP and the hostname is generated from the IP so neither will prove useful in this case since we are behind the ISP's gateway/firewall. A: One way to do this would be to put a SSL (TLS) client certificate on every computer you want to allow access, then have your HTTP server ask for a valid certificate before allowing the user to connect to your Rails app. With nginx, for example, the configuration could look a bit like this: server { listen 443; ssl on; server_name example.com; ssl_certificate /etc/nginx/certs/server.crt; ssl_certificate_key /etc/nginx/certs/server.key; ssl_client_certificate /etc/nginx/certs/ca.crt; ssl_verify_client optional; # $ssl_client_verify now contains the result of the certificate check, # so you could just do something like this somewhere in your config: if($ssl_client_verify != SUCCESS) { return 403; } # ... } The server.crt file is a regular SSL certificate you'd get from a SSL cert shop. The ca.crt (Certificate Authority) file is one you generate yourself. You'd then generate sign a number of client certificates with your CA certificate, and tell nginx to only accept certificates signed by your CA. Here's a helpful article that shows you how. This approach would require you to make and securely store a CA certificate, generate (ideally) one certificate per computer you want to allow, and add a client cert to every machine that needs access, so it's quite a bit of work. You also have to make very sure that your users can't just export the client cert and install it on their home PC.
{ "language": "en", "url": "https://stackoverflow.com/questions/31518105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework 6: Associating a 'Child' Collection Let's say I have a table that looks like so: Person { int Id, string Name, int? ParentId } In entity framework, I can add a new property Person Parent and I can tell entity framework how that should be mapped: HasOptional(a => a.Parent).WithMany().HasForeignKey(c => c.ParentId); My question is, is there a way in this scenario to add this: ICollection<Person> Children { get; set; } Where the collection would be populated with all Person rows having a ParentId of this current Person? A: Add a property for your children, like this: public ICollection<Person> { get; set; } Then configure the mapping like this: HasMany(p => p.Children).WithOptional(p => p.Parent); Then you simply have to access the Children property using lazy loading, eager loading (Include(p => p.Children) or explicit loading. If you don't have the navigation property is still possible to do it, but less obvious. MyContext.Person.Where(p => p.ParentId = parentId);
{ "language": "en", "url": "https://stackoverflow.com/questions/24252061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does Microsoft Visual C# 2008 Express Edition debugger randomly exit? I am writing a multi-threaded Windows application in Microsoft Visual C# 2008 Express Edition. Recently, the debugger has been acting strangely. While I am Stepping Over lines of code using the F10, sometimes it will interpret my Step Over (F10) command just like a Continue command (F5) and then the program will resume running and the debugging session will be done. Does anyone know why this happening? In what circumstances can the Step Over command result in the debugger stopping? It's not a problem with the code being debugged: it doesn't just happen on particular lines of code. It happens on a random line that is different each time I run the debugger. It's not a problem with my keyboard: the same thing happens when I just click Step Over in the Debug toolbar. It may be a problem with the other threads in my program. Maybe one of them is randomly doing something that has a side effect of interrupting the debugger. Is that possible? Thanks in advance! A: I've seen this a few times. It generally happens when there's a context switch to another thread. So you might be stepping through thread with ID 11, you hit F10, and there's a pre-emptive context switch so now you're running on thread ID 12 and so Visual Studio merrily allows the code to continue. There are some good debugging tips here: Tip: Break only when a specific thread calls a method: To set a per-thread breakpoint, you need to uniquely identify a particular thread that you have given a name with its Name property. You can set a conditional breakpoint for a thread by creating a conditional expression such as "ThreadToStopOn" == Thread.CurrentThread.Name . You can manually change the name of a thread in the Watch window by watching variable "myThread" and entering a Name value for it in the value window. If you don't have a current thread variable to work with, you can use Thread.CurrentThread.Name to set the current thread's name. There is also a private integer variable in the Thread class, DONT_USE_InternalThread, this is unique to each thread. You can use the Threads window to get to the thread you want to stop on, and in the Watch window, enter Thread.CurrentThread.DONT_USE_InternalThread to see the value of it so you can create the right conditional breakpoint expression. EDIT: There are also some good tips here. I found this by googling for 'visual studio prevent thread switch while debugging'. A: You ought to take a look at this KB article and consider its matching hotfix. EDIT: the hotfix does solve these kind of debugging problems. Unfortunately, the source code changes for the hotfix didn't make it back into the main branch and VS2010 shipped with the exact same problems. This got corrected again by its Service Pack 1. A: I find using a logfile is very handy when dealing with multiple threads. Debugging threads is like the Huysenberg principle - observe too closely and you'll change the outcome ! A: Try this http://support.microsoft.com/kb/957912. Worked for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/310788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Null Pointer Exception While trying to Connect to FTP server FTPClient mFTPClient; mFTPClient = new FTPClient(); // connecting to the host mFTPClient.connect(host, port); After this line of code, the following exception thrown. Method threw 'java.lang.NullPointerException' exception. Cannot evaluate android.system.StructAddrinfo.toString()
{ "language": "en", "url": "https://stackoverflow.com/questions/45499217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accidentally import the MySQL user table into TiDB, or forget the password If I accidentally import the MySQL user table into TiDB, or forget the password and cannot log in, how to deal with it? A: Restart the TiDB service, add the -skip-grant-table=true parameter in the configuration file. Log into the cluster without password and recreate the user, or recreate the mysql.user table using the following statement: DROP TABLE IF EXIST mysql.user; CREATE TABLE if not exists mysql.user ( Host CHAR(64), User CHAR(16), Password CHAR(41), Select_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Insert_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Update_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Delete_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Create_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Drop_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Process_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Grant_priv ENUM('N','Y') NOT NULL DEFAULT 'N', References_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Alter_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Show_db_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Super_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Create_tmp_table_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Lock_tables_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Execute_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Create_view_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Show_view_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Create_routine_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Alter_routine_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Index_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Create_user_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Event_priv ENUM('N','Y') NOT NULL DEFAULT 'N', Trigger_priv ENUM('N','Y') NOT NULL DEFAULT 'N', PRIMARY KEY (Host, User)); INSERT INTO mysql.user VALUES ("%", "root", "", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y");
{ "language": "en", "url": "https://stackoverflow.com/questions/49996494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Exclude results from MySQL based on Content I am currently searching my database with the following query. What I really need to do is get 30 results that do not include the tag #DONE# that is contained in the information column. The structure of the database is below: ID Info1 Info2 Info3 DateAdded ----------------------------------------------------------------- 1235 0000 6 #DONE#infohere 35:27.9 5678 1111 5 #DONE#infohere 47:15.4 4583 2222 7 otherinfohere 47:36.8 1238 3333 9 otherinfohere 47:12.6 Current Query: SELECT * FROM $tablename WHERE `Info3` <> '' LIMIT 0,30 So in the full database there is more than 30 of both Info3 columns that have the #DONE# tag and do not have the #DONE# tag. What I need to be able to do it to exclude all the results that have the #DONE# tag. I do not want to just get all results as that would be extensive on the database when it gets larger but I do need 30 results in the end. Any suggestions? A: you want NOT LIKE SELECT * FROM $tablename WHERE `Info3` NOT LIKE '#DONE#%' LIMIT 0,30 EDIT: if #DONE# is not always at the beginning, use %#DONE#% SELECT * FROM $tablename WHERE `Info3` NOT LIKE '%#DONE#%' LIMIT 0,30 A: Try this - SELECT * FROM $tablename WHERE `Info3` not like '#DONE#%' LIMIT 0,30
{ "language": "en", "url": "https://stackoverflow.com/questions/21507728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: actionscript 3.0 I have a picture sliding on my scene, with fade in and out pictures between frames 1 and 100. I would like to create 2 buttons that could go to previous picture and next picture and I just can figure out the code. Need help pls. I tryed like this on last frame, 2 ways: gotoAndPlay(1); btnA.addEventListener(MouseEvent.CLICK, backward); btnB.addEventListener(MouseEvent.CLICK, forward); function backward(event:MouseEvent) { if(this.currentFrame == (1, 30)) { gotoAndPlay(66); } else { gotoAndPlay(1); } } function forward(event:MouseEvent) { if(this.currentFrame == 1, 30) { gotoAndPlay(31); } if(this.currentFrame == 31, 65) { gotoAndPlay(66); } if(this.currentFrame == 66, 100) { gotoAndPlay(1); } } A: for all statements you should do: ... if(event.target.currentFrame == 1 || event.target.currentFrame == 30) { gotoAndPlay(31); } ....
{ "language": "en", "url": "https://stackoverflow.com/questions/10833604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Node JS Needle Post Response Body Returned as Buffer I am currently trying to call a remote API from a node.js application that I am writing using needle. The API requires that I make all requests as post requests. when I try to print out the response.body in the console log the only thing that prints out is <Buffer >. My node.js code is as follows: var needle = require('needle'); var options = { data: { "username": "**********", "password":"******************" }, headers: { "Accept":"application/json", "Accept-Encoding":"gzip,deflate", "Content-Type":"application/json" } }; needle.post('http://www.linxup.com/ibis/rest/linxupmobile/map', options, function(err, resp, body) { // you can pass params as a string or as an object. console.log(body.toString()); Additionally I have tried printing resp, resp.body, body, and all of the aforementioned items with the .toString() method attached. I just want to be able to see the response data returned from the API POST call. A: The issue is that needle offers shortcuts to create a header for your REST requests. These were overriding my headers and caused a compressed response body to be returned. I simply removed my custom header and used Needle's format instead: var options = { compressed: true, accept: 'application/json', content_type: 'application/json' }; I then moved my body to a separate array: var data = { "username": "***********", "password":"*********" } Finally I created the request: needle.post('http://www.linxup.com/ibis/rest/linxupmobile/map', data, options, function(err, resp, body) { ... } this then allowed me to access the response body without issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/45602273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement some convenient methods (e.g., flat_map, flatten) on Option? It would be nice if Rust's Option provided some additional convenience methods like Option#flatten and Option#flat_map, where flatten would reduce an <Option<Option<T>> to Option<T>, and flat_map would work like map, but takes a method/closure that returns an Option and flattens it. flat_map is pretty straightforward: fn opt_flat_map< T, U, F: FnOnce(T) -> Option<U> >(opt: Option<T>, f: F) -> Option<U> { match opt { Some(x) => f(x), None => None } } flatten is more complex, and I don't really know how to go about defining it. It might look something like: fn opt_flatten<T, U>(opt: Option<T>) -> Option<U> { match opt { Some( Some(x) ) => flatten_option( Some(x) ), _ => opt } } But that certainly doesn't work. Any thoughts? Also, how would I go about implementing these methods on the Option enum, so that I can use them natively on an Option instance? I know I need to add the type signature in somewhere around impl OptionExts for Option<T>, but I'm at a loss... Hope this makes sense and I apologize for my imprecise terminology--I'm brand new to Rust. A: fn flatten<T>(x: Option<Option<T>>) -> Option<T> { x.unwrap_or(None) } In my case, I was dealing with an Option-returning method in unwrap_or_else and forgot about plain or_else method. A: These probably already exist, just as different names to what you expect. Check the docs for Option. You'll see flat_map more normally as and_then: let x = Some(1); let y = x.and_then(|v| Some(v + 1)); The bigger way of doing what you want is to declare a trait with the methods you want, then implement it for Option: trait MyThings { fn more_optional(self) -> Option<Self>; } impl<T> MyThings for Option<T> { fn more_optional(self) -> Option<Option<T>> { Some(self) } } fn main() { let x = Some(1); let y = x.more_optional(); println!("{:?}", y); } For flatten, I'd probably write: fn flatten<T>(opt: Option<Option<T>>) -> Option<T> { match opt { None => None, Some(v) => v, } } fn main() { let x = Some(Some(1)); let y = flatten(x); println!("{:?}", y); } But if you wanted a trait: trait MyThings<T> { fn flatten(self) -> Option<T>; } impl<T> MyThings<T> for Option<Option<T>> { fn flatten(self) -> Option<T> { match self { None => None, Some(v) => v, } } } fn main() { let x = Some(Some(1)); let y = x.flatten(); println!("{:?}", y); } Would there be a way to allow flatten to arbitrary depth See How do I unwrap an arbitrary number of nested Option types?
{ "language": "en", "url": "https://stackoverflow.com/questions/28566531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How to read time from a file without converting My question is general, but I will explain it using a specific example. Suppose I need to communicate time between two applications. A simple way is to have one application write the output of gettimeofday() (tv_sec and tv_usec) to a file and let the other app read it. The second app needs to 'convert' the strings in order to get an instance of timeval. Is there any way to avoid the conversion? Is there a better way to do this than simple file write/read? A: Assuming both processes are on the same machine (or at least on machines of the same architecture), the results of std::time() (from <ctime>) will be seconds since the Epoch, and will not need any conversion: std::time_t seconds_since_epoch = std::time(NULL); Disclaimer: This is not the best method of ipc and you will need to lock the file for reading while it is being written, etc. Just answering the question. Update, following comment. If you need to write a timeval, perhaps the easiest way is to define << and >> operators for timeval and write and read these as text to the file (no need to worry about byte-ordering) as-is (with no conversion): std::ostream& operator <<(std::ostream& out, timeval const& tv) { return out << tv.tv_sec << " " << tv.tv_usec; } std::istream& operator >>(std::istream& is, timeval& tv) { return is >> tv.tv_sec >> tv.tv_usec; } This will allow you to do the following (ignoring concurrency): // Writer { timeval tv; gettimeofday(&tv, NULL); std::ofstream timefile(filename, std::ofstream::trunc); timefile << tv << std::endl; } // Reader { timeval tv; std::ifstream timefile(filename); timefile >> tv; } If both process are running concurrently, you'll need to lock the file. Here's an example using Boost: // Writer { timeval tv; gettimeofday(&tv, NULL); file_lock lock(filename); scoped_lock<file_lock> lock_the_file(lock); std::ofstream timefile(filename, std::ofstream::trunc); timefile << tv << std::endl; timefile.flush(); } // Reader { timeval tv; file_lock lock(filename); sharable_lock<file_lock> lock_the_file(lock); std::ifstream timefile(filename); timefile >> tv; std::cout << tv << std::endl; } ...I've omitted the exception handling (when the file does not exist) for clarity; you'd need to add this to any production-worthy code.
{ "language": "en", "url": "https://stackoverflow.com/questions/14971546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to submit multiple inputs with jquery Seems I can't google the right answer, because I don't know how to ask the question... So I will try to describe the situation. I have HTML (smarty template): {foreach $dns_records as $record} <tr> <td class="text-center align-middle"> <a href="javascript:void(0);" class="text-danger delete-record" title="Delete record"><i class="fas fa-times-circle"></i></a> </td> <td> <input type="text" name="record[]" id="name" class="form-control" value="{$record.name|escape:html}" /> </td> <td> <select class="form-select" name="record[]" id="ttl" {if !$record.ttl}disabled{/if}> <option value="">-</option> {if $record.ttl} {foreach from=$dns_allowed_ttl item=ttl key=key} <option value="{$ttl}" {if $ttl eq $record.ttl}selected{/if}>{$ttl} min.</option> {/foreach} {/if} </select> </td> <td> <select class="form-select" name="record[]" id="type"> <option value="">-</option> {foreach from=$dns_record_types item=type key=key} <option value="{$type}" {if $type eq $record.type}selected{/if}>{$type}</option> {/foreach} </select> </td> <td style="width: 10%"> <input type="text" name="record[]" id="prio" class="form-control" value="{if $record.priority}{$record.priority|escape:html}{else}-{/if}" {if $record.type neq 'MX'}disabled{/if}/> </td> <td> <input type="text" name="record[]" id="content" class="form-control" value="{$record.content|escape:html}"/> </td> </tr> {foreachelse} <tr>No records found.</tr> {/foreach} I want to submit those input fields to my PHP like this: 0: ['name', 'ttl', 'type', 'prio', 'content'], 1: ['name', 'ttl', 'type', 'prio', 'content'], 2: ['name', 'ttl', 'type', 'prio', 'content'], <...> I use AJAX via jquery: $("#records-table").submit(function(event) { event.preventDefault(); if (request) { request.abort(); } var $inputs = $("#records-table").find("input, select"); var record = $('input[name="record[]"]').map(function(){ return this.value; }).get(); var data = { records: record, zone_id: $inputs.find("#zone_id").val(), action: $inputs.find("#action").val(), csrf: $inputs.find("#csrf").val(), } console.log(data); request = $.ajax({ cache: false, url: 'ajax/dns_zone.php', type: "post", dataType: "json", data: JSON.serialize(data) }); request.done(function (response) { if (response.response == '1') { window.location = response.redirecturl; } }); }); How to achieve my goal? I understand that input field must have unique ID's, but I select them via name with []. A: So all of your input's name is record[], that will make the record[] value to be something like: ['name', 'ttl', 'type', 'prio', 'content','name', 'ttl', 'type', 'prio', 'content','name', 'ttl', 'type', 'prio', 'content'] Then you could try this: var final = []; var value = []; var i = 1; $("input[name='record[]']").each(function() { value.push($(this).val()); if(i % 5 == 0) { final.push(value); value = []; } i++; }); It will iterate over all of the record[], creating the new variable for each grouped input. It will be: [["name", "ttl", "type", "prio", "content"], ["name", "ttl", "type", "prio", "content"], ["name", "ttl", "type", "prio", "content"]] A: Here is a solution to my problem: var final = []; var value = []; var i = 1; $("input[name='record[]']").each(function() { value.push($(this).val()); if(i % 5 == 0) { final.push(value); value = []; } i++; }); var data = { records: value, zone_id: $(this).find("input[name='zone_id']").val(), action: $(this).find("input[name='action']").val(), csrf: $(this).find("#csrf").val(), } request = $.ajax({ cache: false, url: 'ajax/dns_zone.php', type: "post", dataType: "json", data: $(this).serialize(data) }); Here is HTML part: <form id="records-table"> {$csrf} <input type="hidden" name="action" value="edit_records" /> <input type="hidden" name="zone_id" value="{$zone.id}" /> {counter assign=i start=1 print=false} {foreach $dns_records as $record} <tr> <td class="text-center align-middle"> <a href="javascript:void(0);" class="text-danger delete-record" title="Delete record"><i class="fas fa-times-circle"></i></a> </td> <td> <input type="text" name="record[{$i}][name]" id="name" class="form-control" value="{$record.name|escape:html}" /> </td> <td> <select class="form-select" name="record[{$i}][ttl]" id="ttl" {if !$record.ttl}disabled{/if}> <option value="">-</option> {if $record.ttl} {foreach from=$dns_allowed_ttl item=ttl key=key} <option value="{$ttl}" {if $ttl eq $record.ttl}selected{/if}>{$ttl} min.</option> {/foreach} {/if} </select> </td> <td> <select class="form-select" name="record[{$i}][type]" id="type"> <option value="">-</option> {foreach from=$dns_record_types item=type key=key} <option value="{$type}" {if $type eq $record.type}selected{/if}>{$type}</option> {/foreach} </select> </td> <td style="width: 10%"> <input type="text" name="record[{$i}][prio]" id="prio" class="form-control" value="{if $record.priority}{$record.priority|escape:html}{else}-{/if}" {if $record.type neq 'MX'}disabled{/if}/> </td> <td> <input type="text" name="record[{$i}][content]" id="content" class="form-control" value="{$record.content|escape:html}"/> </td> </tr> {counter} {foreachelse} <tr>No records found.</tr> {/foreach} </form> Take a note at counter. It iterates array. It is important!
{ "language": "en", "url": "https://stackoverflow.com/questions/70783116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Parse (possibly empty) text and variable definitions inside brackets I'm trying to parse an input into text and variable items. The input may be empty, have only text items, only variable items, or a mix of them. The following is some sample input: <> <a text> <an escaped \< and an escaped \>> <${aVar}> <a text and ${aVar}> <${aVar} and a text> <a text ${aVar} ${someMoreVars} and more text> I tried to parse it with the following grammar: grammar Translation; file : ( translation | comment)* EOF ; translation : '<' ( text | varDef )* '>' ; varDef : '${' VARDEF '}'; text : TEXT ; But whatever I tried for the TEXT rule, I either end up parsing everything as text or I get the nasty problem non-fragment lexer rule TEXT can match the empty string Which sends me straight on to a stack overflow. How can I solve the problem? Do I have to go to an 'island grammar'? I can't see how that would help. The problem can't be this hard to solve but I am really stuck now. A: You didn't post your entire grammar, so I cannot tell you what exactly is wrong with your grammar. You can however do something like this to parse your input: file : ( translation | COMMENT )* EOF ; translation : '<' ( text | var_def )* '>' ; text : TEXT+ ; var_def : VAR_DEF_START text VAR_DEF_END ; COMMENT : '//' ~[\r\n]* ; SPACES : [ \t\r\n]+ -> skip ; VAR_DEF_START : '${' ; VAR_DEF_END : '}' ; TEXT : '\\' [\\<>] | ~[\\<> \t\r\n] ; It is important to match single (!) TEXT characters in the lexer, and "glue" them together inside the text parser rule. If you try to match multiple TEXT chars in the lexer, you will end up matching too much characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/71184509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: asp.net Razor output xml dynamicxml How do you just dump/output xml to the page from a razor macro? I've got a variable which just returns "umbraco.MacroEngines.DynamicXml" with @field But could do with just outputting just to see what nodes it contains. Thanks A: The problem is due to the Razor Scripting settings in the umbracoSettings.config file. It is there that several HTML items are listed that will be ignored as DynamicXml. I have added several to mine to make this problem go away. <scripting> <razor> <!-- razor DynamicNode typecasting detects XML and returns DynamicXml - Root elements that won't convert to DynamicXml --> <notDynamicXmlDocumentElements> <element>p</element> <element>div</element> <element>ul</element> <element>span</element> <element>script</element> <element>iframe</element> </notDynamicXmlDocumentElements> </razor> </scripting>
{ "language": "en", "url": "https://stackoverflow.com/questions/13441861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Notify Raspberry when a new device is connected (USB,SPI,I2C...) What i´m trying to do is: having a daemon running in the background that notify when a new "wired" device is connected to the raspberry. Can anyone help me? Thanks all! A: You can check udev. It's possible to write an udev rule to achieve the behavior. In that way you don't even have to write a daemon.
{ "language": "en", "url": "https://stackoverflow.com/questions/48784075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle-Apex Switch Item value I have column which is data type number(1,0), I decide to use switch item for this column. I set custom settings. 1 for On and 0 for off. When I try to edit column, and use off(0) I get error - Column_name must match the values 1 and 0. When I use On value all works fine. A: Goku, in apex, the best way to learn (you said yourself you're a beginner) is to write a lot of small apps in a dev environment that only perform one thing. That way you can isolate issues and study behavior in detail. I suggest you do the same for this switch item issue to figure out what the problem is. You have not provided enough information for anyone to answer it so users are giving you their best guesses. So this is what I did. Create test table create table so_test_with_switch ( so_test_with_switch_id number generated by default on null as identity constraint so_test_with_switc_id_pk primary key, name varchar2(255), switchval number ); Create a report and form in apex, change the form item for switchval page item (P32_SWITCHVAL) to "Switch" with custom settings: 1 for On and 0 for off. I tested and my form worked fine. The error message indicates that the value apex is getting does not match either 1 or 0 so it must get that value from somewhere else. In my case I added an after submit computation to set the value of P32_SWITCHVAL to 'Y'. Saved my changes, ran the form, clicked "Apply Changes" and I got the same error as you. It is up to you to figure out where your page item is getting the other value from. Go through your page, investigate and debug. The key to finding the solution is in your code. --Koen
{ "language": "en", "url": "https://stackoverflow.com/questions/62071138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: dc linecharts in a composite chart with group reduction using reduce callback methods I want to make a composite chart with an unknown number of lincharts all based on the same dimension but each of them with call-back reduction functions to calculate count, sum and average but every one filtering data for a given field value of the dimension. I don't know how to make it work. The graph coordinates and legends appear but no line is painted. This is what I'm currently doing: var tablaCount = dc.dataCount("#dataCount"); var tablaDatos = dc.dataTable("#tabla"); var ofs = 0, pag = 10, ndxSize = 0; var ndx, all; d3.json("/PruebaConcepto/json/userdashboard-vgodoy-pruebax_20181023111343.json").then(function(data) { ndx = crossfilter(data); ndxSize = ndx.size(); all = ndx.groupAll(); var compositeChartline1 = dc.compositeChart("#lineChartline1"); var dimensionline1 = ndx.dimension(function(d) { return [d.horasacta, d.aerodromo] ; }); var groupline1 = dimensionline1.group().reduce( function (p, v) { ++p.count; p.pct = (p.count / ndxSize) * 100; p.sum += ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0); p.avg = ((p.sum ? p.sum : 0) / p.count); return p; }, function (p, v) { --p.count; p.pct = (p.count / ndxSize) * 100; p.sum -= ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0); p.avg = ((p.sum ? p.sum : 0) / p.count); return p; }, function () { return {count: 0, pct: 0, sum: 0, avg: 0}; } ); var keysline1 = groupline1.all().filter(function(d) {return d.key[0]}); var seriesline1 = []; var tmpseriesline1 = []; for (var i = 0; i < keysline1.length; i++) { tmpseriesline1.push(keysline1[i].key[1]); } seriesline1 = (tmpseriesline1.filter(function(item, pos) { return tmpseriesline1.indexOf(item) == pos;})).slice(); tmpseriesline1 = 0; var yMaxline1 = 0; for (var i = 0; i < groupline1.size() && !(groupline1.top(Infinity)[i] == null); i++) { if (yMaxline1 < groupline1.top(Infinity)[i].value.avg) { yMaxline1 = groupline1.top(Infinity)[i].value.avg; } } var yMagline1 = Math.pow(10, Math.floor((Math.log(yMaxline1) / Math.LN10 + 0.000000001))) / 10; yMaxline1 = Math.ceil(yMaxline1 + yMagline1); var xRangeline1 = []; var tmpxRangeline1 = []; for (var i = 0; i < keysline1.length; i++) { tmpxRangeline1.push(keysline1[i].key[0]); } xRangeline1 = tmpxRangeline1.filter(function(item, pos) { return tmpxRangeline1.indexOf(item) == pos;}); tmpxRangeline1 = 0; var color = ["red", "green", "yellow"]; var groupsline1 = [seriesline1.length]; var lineChartsline1 = [seriesline1.length]; for (var i = 0; i < seriesline1.length; i++) { var tmpSeriesline1 = seriesline1[i] var tmpGroupline1 = dimensionline1.group().reduce( function (p, v) { ++p.count; p.pct = (p.count / ndxSize) * 100; p.sum += ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0); p.avg = ((p.sum ? p.sum : 0) / p.count); return p; }, function (p, v) { --p.count; p.pct = (p.count / ndxSize) * 100; p.sum -= ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0); p.avg = ((p.sum ? p.sum : 0) / p.count); return p; }, function () { return {count: 0, pct: 0, sum: 0, avg: 0}; } ); groupsline1[i] = tmpGroupline1.all().filter(function(d) { return d.key[1] == tmpSeriesline1; }); lineChartsline1[i] = dc.lineChart(compositeChartline1) .group(groupsline1[i], seriesline1[i]) .valueAccessor(function(d) { return parseFloat(d.value.avg); }) .title(function(d) { var s = []; s.push(d.key[1] + ":"); s.push("Conteo: " + (isNaN(d.value.count) ? "-" : d.value.count + " (" + d.value.pct.toFixed(2) + "%)")); if ("avg" != "count") { s.push("Media: " + (isNaN(d.value.avg) ? "-" : d.value.avg.toFixed(2) + ("avg" != "pct" ? "" : "%"))); } return s.join("\n"); }) .colors(color[i]) .dashStyle([5,5]); } compositeChartline1 .width(500).height(500) .margins({top: 60, right: 60, bottom: 120, left: 120}) .x(d3.scaleOrdinal().domain(xRangeline1)) .xUnits(dc.units.ordinal) .y(d3.scaleLinear().domain([0, yMaxline1]).range([500,0])) .xAxisLabel("X") .yAxisLabel("Y") .legend(dc.legend().x(40).y(20).itemHeight(seriesline1.length).gap(10)) .dimension(dimensionline1) .renderHorizontalGridLines(true) .brushOn(false) .elasticY(true) .renderlet(function (chart) { chart.selectAll('g.x text').attr('transform', 'translate(-30,30) rotate(315)'); }) .compose(lineChartsline1); } Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/52896857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby on Rails Fields For Issue I'm new to Ruby. Im working on a project and i got stuck at someplace. I have two html pages, company_profile and job. This job page is rendered inside company_profile page and there is an add job button which renders this. This is inside company_profile.html.erb <% @job_count = 0 %> <script type="text/html" id="new_company_job_div"> <%= render 'job', job: Job.new(company_id: @company.id), f: f %> </script> and inside my job.html.erb i've <% @job_count += 1 %> <%= @job_count %> and some other codes too.. My issue: First time when i add a job, job_count goes to 1 and from there that job_count value is not increasing. It is stuck there. I have also written a code to render the jobs page if its present in database.. this is that part of code in comapny_profile that loads the existing columns. <% if @company.jobs.present? %> <% @company.jobs.each do |job| %> <%= render 'job', job: job, f: f %> <% end %> <% end %> That is if there are 2 columns inside jobs table with matching id those 2 will be present in the page as soon as it loads and also with add job we can add more. In this case if 2 jobs are in table job_count will be 2 and on pressing add_count count value will be 3 and from there onwards count_value is not increased. Appending and all are working fine.. pls help A: My issue at first time when i add a job job_count goes to 1 and from there taht job_count value is not increasing The problem is probably because you're using an instance variable From what I can see, you're reloading the page each time you wish to load job (it's a one time thing); meaning the data is not going to persist between requests If you want to store a variable over different requests, you'll either have to populate it continuously in the backend, or use a persistent data store - such as a cookie or session Try this: <% session[:job_count] = 0 %> <script type="text/html" id="new_company_job_div"> <%= render 'job', job: Job.new(company_id: @company.id), f: f %> </script> <% session[:job_count] += 1 %> <%= session[:job_count] %> This is the best I can do without any further context A: Use collection partial: In app/views/companies/show.html.erb <%= render @company.jobs %> In app/views/jobs/_job.html.erb <%= job_counter %> # value based on the number of jobs you have <%= job.foo %>
{ "language": "en", "url": "https://stackoverflow.com/questions/22655407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Scheduling task I am developing a spring mvc project where a notification will send to user mobile.User will select a datetime at format 'yyyy-MM-dd HH:mm' from frontend and save it to the database.when system time reach that time a notification will be send to the user mobile . I created scheduler like this @Component public class NotificationScheduler extends BaseService { @Scheduled(fixedRate = 300000) public void sendNotification() { Date currentDate = new Date(); System.err.println("HHHHHHHHHKKKKKK"); List<ImageInfo> listImageInfo = imageInfoDao.getImageOfParticularDate(currentDate); } } this is my dao function which run a wuery to database public List getImageOfParticularDate(Date date) { session = getSession(); session.beginTransaction(); List<ImageInfo> imageInfoList = session.createQuery("select img from ImageInfo img where img.publishedTime =:publishedTime ").setParameter("publishedTime", date).list(); session.getTransaction().commit(); return imageInfoList; } this code is checking repeatedly at 5 min interval whether system time equal to publish time.if it is equal then a notification will be sent.I used Date type in model and Date type column in database. I want to know my approach is right or wrong because i can not get desire output. A: Why don't you use a debug mode? Change, your the time rate you use in order to not wait too much, but I think you could determine that yourself, could you?
{ "language": "en", "url": "https://stackoverflow.com/questions/43201358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Vue 3 render dynamic comment How can I properly render a dynamic comment in Vue 3? I tried v-html which is not working in my case, for example, https://i.imgur.com/EtrVmGu.png <template> <!-- Method 1: not working properly, https://i.imgur.com/EtrVmGu.png --> <template v-html="COMMENT" /> <!-- Method 2: does not solve the problem, print as string --> {{ COMMENT }} content here <!--[if mso | IE]> </span> <![endif]--> </template> <script> export default { setup() { const COLOR = "#FF0000"; const COMMENT = `<!--[if mso | IE]> <span style="background: ${COLOR}"> <![endif]-->`; return { COMMENT } } } <script> <div v-html=""> will not solve the issue, see: https://i.imgur.com/6tqaQAe.png A: this works for me. <template> <h1>Dynamic Component</h1> <div v-html="COMMENT"></div> </template> <script> export default { setup() { const COLOR = "#FF0000"; const COMMENT = `<span style="background: ${COLOR}">Comment</span>`; return { COMMENT, }; }, }; </script> A: The v-html should be mounted in real html tag not the virtual template : <div v-html="COMMENT" ></div> You could see the comment inside the inspected DOM A: You may also use dynamic component with the <component is> Vue JS Dynamic Components And put all your comment component code in a different file: comment.vue <template> <h1>Dynamic Component</h1> <component :is='currentComponent'> </template> <script> import CommentComponent from './comment.vue' export default { computed: { currentComponent() { // do some logic then return CommentComponent } } }; </script> A: Create a component Comment.vue that uses render function to create a comment <script> import { createCommentVNode } from 'vue' export default { props: ['content'], setup(props) { return () => createCommentVNode(props.content || '') } } </script> Usage: <script setup> import Comment from "@/components/Comment.vue"; </script> <template> <Comment content="Hi, I'm just a comment!"/> </template> Rendered comment: <!--Hi, I'm just a comment!--> The vue internal api is not designed for these kinda hacks. So, please use carefully.
{ "language": "en", "url": "https://stackoverflow.com/questions/65091348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: May I place
{ "language": "en", "url": "https://stackoverflow.com/questions/50643010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Invalid date django form validation I am learning Django and building a CRUD but I'm getting an error in my form validation. This is the form that ** I created** class addSignForm(forms.ModelForm): active = forms.CharField(max_length=10) class Meta: model = signs fields = ("id", "active", "action", "date", "expiration_date", "add_by", "user_sign") widgets = { 'date': forms.DateTimeInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } This is the date that I am receiving from the request **(also tried format: '%y-%m-%dT%H:%M' '2000-04-16T18:57' And when I try to: if (form.is_valid()): says that it is an invalid form and that I typed an invalid date <li>Enter a valid date/time.</li></ul> can someone help me A: "2000-04-16T18:57" is not %d/%m/%Y %H:%M format but %Y-%m-%dT%H:%M format. Check list date formatters here https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes A: Your widget format just show for client, not for Form.So you can try add a method named clean_date(self) to replace 'T' with whitespace then return it. or add your format into DATETIME_INPUT_FORMATS list of settings.py. A: i ended up managing to solve the problem, however I did not like the solution because it does not seem the most right ... however I will share it here in case people experience the same problem :) What i did was: create a copy of my GET so it becomes mutable getCopy = request.GET.copy() after that i converted the DATE that was comming from GET ts = time.strptime(request.GET['date'], "%Y-%m-%dT%H:%M") getCopy['date'] = time.strftime("%m/%d/%Y", ts) and when i call my form.is_valid instead of passing request.GET, i pass my mutable copy of GET with my formatted date :)
{ "language": "en", "url": "https://stackoverflow.com/questions/61514598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Kendo UI how to get the id of elements during drop event? I have the following HTML and would like to get the DOM elements for the elements involved in the drag and drop event. Also, if you could tell me how i might be able to figure this out using debugger, that would be even better! Here is the code: <div class="dragArea" id="choice1">proud</div> <div class="dragArea" id="choice2">strong</div> <div class="dragArea" id="choice3">merry</div> <div class="dragArea" id="choice4">friendly</div> <div class="dropArea k-header" id="gap1">Drop here</div> <div class="dropArea k-header" id="gap2">Drop here</div> <div class="dropArea k-header" id="gap3">Drop here</div> <div class="dropArea k-header" id="gap4">Drop here</div> <script> $(".dragArea").kendoDraggable({ group: "choicesGroup", hint: function (element) { return element.clone(); } }); $(".dropArea").kendoDropTarget({ group: "choicesGroup", drop: onDrop }); function onDrop(e) { // How do i get the id of the elements involved in the drag and drop event? } </script> A: function onDrop(e) { // Get the id of the elements involved in the drag and drop event var source = $(e.draggable.element).attr('id'); var target = e.dropTarget.attr('id'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/24247132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Avoid Terraform module to create duplicate resources? I have the following project structure to build Lambda functions on AWS using Terraform : . ├── aws.tf ├── dev.tfvars ├── global_variables.tf -> ../shared/global_variables.tf ├── main.tf ├── module │ ├── data_source.tf │ ├── main.tf │ ├── output.tf │ ├── role.tf │ ├── security_groups.tf │ ├── sources │ │ ├── function1.zip │ │ └── function2.zip │ └── variables.tf └── vars.tf In the .main.tf file i have this code that will create 2 different lambda functions : module "function1" { source = "./module" function_name = "function1" source_code = "function1.zip" runtime = "${var.runtime}" memory_size = "${var.memory_size}" timeout = "${var.timeout}" aws_region = "${var.aws_region}" vpc_id = "${var.vpc_id}" } module "function2" { source = "./module" function_name = "function2" source_code = "function2.zip" runtime = "${var.runtime}" memory_size = "${var.memory_size}" timeout = "${var.timeout}" aws_region = "${var.aws_region}" vpc_id = "${var.vpc_id}" } The problem is that in deployment terraform create all resources twice. For Lambda it's Ok, that's the purpose, but for security groups and Roles that's not what i want. For example this security group is create 2 times : resource "aws_security_group" "lambda-sg" { vpc_id = "${data.aws_vpc.main_vpc.id}" name = "sacem-${var.project}-sg-lambda-${var.function_name}-${var.environment}" egress { protocol = "-1" from_port = 0 to_port = 0 cidr_blocks = ["0.0.0.0/0"] } ingress { protocol = "-1" from_port = 0 to_port = 0 cidr_blocks = "${var.authorized_ip}" } # To solve dependcies error when updating the security groups lifecycle { create_before_destroy = true ignore_changes = ["tags.DateTimeTag"] } tags = "${merge(var.resource_tagging, map("Name", "${var.project}-sg-lambda-${var.function_name}-${var.environment}"))}" } So that's clear that the problem is the structure of the project. Could you help to solve that ? Thanks. A: If you create the SecurityGroup within the module, it'll be created once per module inclusion. I believe that some of the variable values for the sg name change when you include the module, right? Therefore, the sg name will be unique for both modules and can be created twice without errors. If you'd choose a static name, Terraform would throw an error when trying to create the sg from module 2 as the resource already exists (as created by module 1). You could thus define the sg resource outside of the module itself to create it only once. You can then pass the id of the created sg as variable to the module inclusion and use it there for other resources.
{ "language": "en", "url": "https://stackoverflow.com/questions/56630717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Square root inside a square root python I was wondering how to write a code showing the square root inside a square root. This is what I have so far: number=float(input("Please enter a number: ")) square = 2*number**(1/2)**(1/3) print(square) But that's not right as I'm getting a different number from the calculator. A: Import math and use math.sqrt(math.sqrt(number)) import math number=float(input("Please enter a number: ")) square = math.sqrt(math.sqrt(number)) print(square) A: It looks like it is doing the square root (i.e., 1/2) of 1/3 and then applying that to number. You'll want to force the order of operations since it's evaluating the exponent operator from right to left. square = 2*(number**(1/2))**(1/3) By adding parenthesis, you are forcing it to take the square root first, and then the cube root. You are using Python3, but for future readers, Python2 would evaluate 1/2 and 1/3 to 0. To change that you'd use floats instead: square = 2*(number**(1.0/2.0))**(1.0/3.0) A: If you want to find the square root of the square root of a number you can see using some algebra we can see that ((x)^0.5)^0.5) simplifies down to x^(0.25) So you can either do x**(0.25) or you can do the following: import math math.sqrt(math.sqrt(x)) One other thing, in your code you say: square = 2*number**(1/2)**(1/3) and in the title you say "Square root inside a square root python". This indicates to me that you might have made either a typo in your code or mistake in naming the title of your question. If you do want to find a square root of a square root then my suggestions above should be sufficient to do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/19962950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running rospy dependent file in Github Actions I'm trying to implement CI with Github Actions to a repository. In the workflow, I would like to run a test script using pytest. However, the test script and the script it is testing had a rospy dependency, although the dependency is not vital to the test, where it is publishing the result of certain calculation (node.Publisher is mocked using pytest). I'm still new to ROS and I am a bit confused about what I need to install. Do I need to install the whole ROS library for the test or do I only need to install rospy? What is the best way to install the package and add it to the path in Github Actions? I tried sudo apt-get install -y python-rospy, but the package is not detected by python with ImportError: No module named rospy. I am running the test in Ubuntu 18.04. Thank you in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/62811744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the correct way to resolve warnings at Redis startup when using Docker? When I run my Redis Docker image, I face these warnings: # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf ( ... ) # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128. ( ... ) # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled. Among the solutions I found in the internet, this one looks cover everything, but when I try it in Docker scope (Eg.: changing my Dockerfile to apply them), I get the error "Read-only file system". Manually example give me the same issues: [root@769368ed0fc5 /]# sysctl -w net.core.somaxconn=65535 sysctl: setting key "net.core.somaxconn": Read-only file system [root@769368ed0fc5 /]# echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf [root@769368ed0fc5 /]# sysctl vm.overcommit_memory=1 sysctl: setting key "vm.overcommit_memory": Read-only file system [root@769368ed0fc5 /]# echo never > /sys/kernel/mm/transparent_hugepage/enabled bash: /sys/kernel/mm/transparent_hugepage/enabled: Read-only file system [root@769368ed0fc5 /]# echo never > /sys/kernel/mm/transparent_hugepage/enabled bash: /sys/kernel/mm/transparent_hugepage/enabled: Read-only file system Does anyone know how to fix it in a proper way? I have found a lot of tricks to workaround it, like: * *Run container in privileged mode *Mount host /proc inside a container *Use host network stack (--net=host) * *Looks like this one is inevitable, because Redis doesn't support NATed environments, but anyway it doesn't solve everything. I want to know what is the correct way to deal with it in Docker. Answers that provide technical explanation about the proposed solution will be appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/40974024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Get vs Post Auto Mapping dates C# I am having some confusion figuring out why I am experiencing the following: If I using jquery AJAX to "post" some Json data containing a date to an MVC controller the automapper maps the date in the format dd/mm/yyyy however if I use "get" instead the automapper seems to convert the date in to the format mm/dd/yyyy. Does anybody know why this would be the case? When I check the json payload and querystrings for the post and get respectively they are both in the same format. The date I am using goes across as "1/7/2013" in both cases. Regards, Gary A: Are you using a JSON serializer for the POST but a DateTime.Parse for the GET? This could yield two different results. User DateTime.ParseExact to ensure consistent results. I.E. DateTime.ParseExact(input, "dd/MM/yyyy HH:mm", null);
{ "language": "en", "url": "https://stackoverflow.com/questions/17750354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set Meta Tag With jQuery I'm having trouble with a mobile page that uses a site of ours in an iframe. It works fine on desktop but on mobile the page doesn't resize correctly. Based on internal testing it seems that the page is missing this meta tag: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> Is there any way to set that via jQuery and have it actually take effect? In theory I believe that using this SO article I could inject the meta tag like this: $('head').append('<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">'); But it seems the problem really comes down to forcing it to re-parse the html. Is there a way I could do that? A: Yes you can append a meta tag, but no you can't force reparsing of the html. The browser is going to ignore any changes you make.
{ "language": "en", "url": "https://stackoverflow.com/questions/45226763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calling multiple httpclient that contain two different base address I have read up on named clients and typed clients in order to achieve my ultimate goal. However, I still do not understand how I need to implement either or. I have a blazor server side project that in the startup.cs file I have it set up as services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("http://localhost:36626") }); services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("https://localhost:5443") }); I know that if I do this, the baseaddress of the first one will completely be overwritten and no longer be the set base address due to the second baseaddress. How would I go about making this work so that way I have two separate httpclients that will have two separate baseaddress without having to lose one because of the most recent line of code? A: As said in the doc, the main differences are in how you are going to get an instance through Dependency Injection. With Named Client you need to inject the factory and then get the client by a string. var client = _clientFactory.CreateClient("github"); With Typed Client you can inject the client needed as a type. //GitHubService encapsulate an HTTP client public TypedClientModel(GitHubService gitHubService) { _gitHubService = gitHubService; } Both of them give the solution to your problem. The selection is more in how comfortable you are with the dependency injection method of each one. I personally prefer the Typed client.
{ "language": "en", "url": "https://stackoverflow.com/questions/68089733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to create directory in External Storage public directory I am attempting to create a directory and file so that I can store files that I have downloaded from the Internet. However, I am unable to create the directory and file in the external public storage. If I write to the external private storage (specific storage location for the app) I am perfectly able to do so. Here is the code: String storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath(); System.out.println(storageDirectory); File mediaDir = new File(storageDirectory); if (!mediaDir.exists()) { System.out.println(mediaDir.mkdirs()); System.out.println(mediaDir.isDirectory()); } File mediaFile = new File(storageDirectory, "boga.jpg"); try { mediaFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } The above code results in: 09-13 05:33:45.258 5867-5867/? I/System.out﹕ /storage/0CED-0F09/Pictures 09-13 05:33:45.260 5867-5867/? I/System.out﹕ false 09-13 05:33:45.260 5867-5867/? I/System.out﹕ false With an IOException (No such file or directory): 09-13 05:33:45.260 5867-5867/? W/System.err﹕ java.io.IOException: open failed: ENOENT (No such file or directory) 09-13 05:33:45.260 5867-5867/? W/System.err﹕ at java.io.File.createNewFile(File.java:939) 09-13 05:33:45.260 5867-5867/? W/System.err﹕ at com.example.terabyte.tut1app.MainActivity.onCreate(MainActivity.java:78) And this is my manifest: <?xml version="1.0" encoding="utf-8"?> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> What could be the issue? A: Turns out I am fully capable of writing to the external storage directory on a real smartphone device (Huawei P8 api level 21, Version 5.0). But not to the emulator's external storage, even though the storage is fully available and can be browsed from within the emulator. This also helped me in figuring out issues with the external storage on a real device: https://stackoverflow.com/a/6311955/5330055 I have no longer urgently require a solution on this, but it would be nice to know what is wrong with the emulator. A: Actually nothing wrong with emulator. Probably device you have used on emulator were on android equal or higher than version 6.0 In 6.0 and higher versions you need to request write permission at runtime. WRITE_EXTERNAL_STORAGE in your smartphone it worked because it was on android 5.0 if this help someone I will glad.
{ "language": "en", "url": "https://stackoverflow.com/questions/32546708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Accumulate promise values "functionally" Say I have this: function getAllPromises(key: string, val: any): Promise { const subDeps = someHash[key]; const acc = {}; // accumulated value return subDeps.reduce(function (p, k) { return p.then(v => getAllPromises(k, v)).then(function (v) { acc[k] = v; return acc; }); }, Promise.resolve(val)); } is there a way to avoid having to declare a separate variable: const acc = {}; // accumulated value and somehow return that from the promise chain instead? Ultimately the acc variable is what gets resolved from the promise chain, but wondering if I can somehow avoid having to declare it "outside" the chain. Edit: the seed data for something like this looks like: { 'one': [function (v) { return Promise.resolve('one'); }], 'two': ['one', function (v) { return Promise.resolve('two'); }], 'three': ['one', 'two', function (v) { return Promise.resolve('three'); }], } It's just a declarative dependency tree. Dependencies can be resolved in parallel; but may effectively block, as they run. For example, if I have a function like so: function foo(one,two,three){ } I want to inject these 3 dependencies. They can be sourced "in parallel", but three will be blocked until one and two are procured. What is the subDeps variable? In the case of key="three", subDeps is ['one','two']. A: You can pass an array at second parameter to .reduce(), within .reduce() callback use destructing assignment to get Promise and object passed return subDeps.reduce(([p, acc], k) => [p.then(v => getAllPromises(k, v)).then(v => Object.assign(acc, {[k]:v})) , acc]; }, [Promise.resolve(val), {}]).shift()//.then(result => /* result : acc */) A: I'm going out on a bit of a limb, here, in thinking that the whole list of subDeps for any child node can be loaded in parallel. In looking at the problem, deeper, I see no reason for that not to be the case. In fact, the only potential problem I could see is that some value above but not below this point could be a promise, and thus, you might even be able to strike the promises from this particular recursive function... but... Here's what I saw as a plausible refactor. Let me know if that's missing some obvious need. const appendKeyValue = (dict, [key, value]) => { dict[key] = value; return dict; }; const getKeyValuePair = hash => key => getRefactoredPromises(hash, hash[key]) .then(value => [key, value]); const getRefactoredPromises = (someHash, subDeps) => { return Promise.all(subDeps.map(getKeyValuePair(someHash))) .then(pairs => pairs.reduce(appendKeyValue, {})); }; In fact, if I'm right about this refactor, then you don't even need the promises in there. It just becomes: const appendKeyValue = (dict, [key, value]) => { dict[key] = value; return dict; }; const getKeyValuePair = hash => key => [key, getRefactoredHash(hash, hash[key])]; const getRefactoredHash = (someHash, subDeps) => subDeps.map(getKeyValuePair(someHash)) .reduce(appendKeyValue, {}); If the root level of this call happens to be a promise, that should be inconsequential at this point, unless there's something I'm missing (it IS 6:20am, and I've yet to close my eyes).
{ "language": "en", "url": "https://stackoverflow.com/questions/43446823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Protect sidekiq admin with devise (documented way not working) I have an app that uses devise/omniauth for authentication, and runs a bunch of sidekiq workers. I would like to protect /sidekiq and /sidekiq_monitor routes with devise as well, but so far I am running into a lot of trouble doing that. The documented solution is to do this in routes.rb: authenticate :user do mount Sidekiq::Web => '/sidekiq' end But that isn't working for me - what happens when I add that is that if a user goes to /sidekiq they are prompted to login regardless of their auth status, and if they login and go back to /sidekiq they are once again prompted to login. Possible wrinkles - I am logging in via omniauth-saml, which means some redirects are happening in the mix here - but that's working fine with all other auth on my site. I am also only using a very minimal bit of devise, just: devise :rememberable, :trackable, :omniauthable, :omniauth_providers => [:saml] A: Try changing in your routes.rb file to this: authenticate :user do mount Sidekiq::Web, at: "/sidekiq" end Also notice that :user refers to your app user model. If your user model has another name, let's say :admin, you should replace :user to :admin in the snipped code above. A: try this inside of your routes: Sidekiq::Web.use Rack::Auth::Basic do |username, password| username == USERNAME && password == PASSWORD end if Rails.env.production? mount Sidekiq::Web, at: "/sidekiq"
{ "language": "en", "url": "https://stackoverflow.com/questions/35995794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tomcat + Grails cluster doesnt work I have a Tomcat cluster over Debian Jessie, Tomcat 8.0.29 2 instances , PostgreSQL 9.5 ,Apache 2.4 , Mod_jk. When I try to run my project in this environment I get eerror. I tested with examples project and it works fine. My log iis this 01-Feb-2016 19:07:39.474 SEVERE [main] org.apache.catalina.ha.deploy.FarmWarDeployer.start FarmWarDeployer can only work as host cluster subelement! 01-Feb-2016 19:07:39.537 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Despliegue del archivo /opt/tomcat8_nodo1/webapps/clusterjsp.war de la aplicación web 01-Feb-2016 19:07:40.886 INFO [MessageDispatch15Interceptor.MessageDispatchThread1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:1 messages Sent:0.00 MB (total) Sent:0.00 MB (application) Time:0.01 seconds Tx Speed:0.06 MB/sec (total) TxSpeed:0.06 MB/sec (application) Error Msg:0 Rx Msg:2 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:0.00 MB] 01-Feb-2016 19:07:42.068 INFO [localhost-startStop-1] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [1.489] milliseconds. 01-Feb-2016 19:07:42.088 INFO [localhost-startStop-1] org.apache.catalina.tribes.tipis.AbstractReplicatedMap.init Initializing AbstractReplicatedMap with context name:localhost#/clusterjsp-map 01-Feb-2016 19:07:42.310 INFO [localhost-startStop-1] org.apache.catalina.tribes.tipis.AbstractReplicatedMap.init AbstractReplicatedMap[localhost#/clusterjsp-map] initialization was completed in 222 ms. 01-Feb-2016 19:07:42.585 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat8_nodo1/webapps/clusterjsp.war has finished in 3.048 ms 01-Feb-2016 19:07:45.652 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Despliegue del archivo /opt/tomcat8_nodo1/webapps/abacus.war de la aplicación web 01-Feb-2016 19:14:05.387 INFO [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars Al menos un JAR, que se ha explorado buscando TLDs, aún no contenía TLDs. Activar historial de depuración para este historiador para una completa lista de los JARs que fueron explorados y de los que nos se halló TLDs. Saltarse JARs no necesarios durante la exploración puede dar lugar a una mejora de tiempo significativa en el arranque y compilación de JSP . feb 01, 2016 7:14:05 PM org.apache.catalina.core.ApplicationContext log INFORMACIÓN: Initializing AtmosphereFramework feb 01, 2016 7:14:05 PM org.apache.catalina.core.ApplicationContext log INFORMACIÓN: No Spring WebApplicationInitializer types detected on classpath feb 01, 2016 7:14:06 PM org.apache.catalina.core.ApplicationContext log INFORMACIÓN: Initializing Spring root WebApplicationContext feb 01, 2016 7:14:54 PM org.apache.tomcat.jdbc.pool.ConnectionPool init ADVERTENCIA: maxActive is smaller than 1, setting maxActive to: 100 <strong> 2016-02-01 19:14:59,345 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing the application: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more 2016-02-01 19:14:59,346 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing Grails: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more feb 01, 2016 7:14:59 PM org.apache.catalina.core.StandardContext listenerStart GRAVE: Excepción enviando evento inicializado de contexto a instancia de escuchador de clase org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected ... 5 more 01-Feb-2016 19:14:59.347 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file 01-Feb-2016 19:14:59.349 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Falló en arranque del Contexto [/abacus] debido a errores previos feb 01, 2016 7:14:59 PM org.apache.catalina.core.ApplicationContext log INFORMACIÓN: Closing Spring root WebApplicationContext 01-Feb-2016 19:14:59.363 WARNING [localhost-startStop-1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc La aplicación web [abacus] registró el conductor JDBC [org.postgresql.Driver] pero falló al anular el registro mientras la aplicación web estaba parada. Para prevenir un fallo de memoria, se ha anulado el registro del conductor JDBC por la fuerza. </strong> 01-Feb-2016 19:14:59.371 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat8_nodo1/webapps/abacus.war has finished in 433.719 ms 01-Feb-2016 19:14:59.373 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/ROOT de la aplicación web 01-Feb-2016 19:14:59.434 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/ROOT has finished in 61 ms 01-Feb-2016 19:14:59.435 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/manager de la aplicación web 01-Feb-2016 19:14:59.479 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/manager has finished in 45 ms 01-Feb-2016 19:14:59.479 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/examples de la aplicación web 01-Feb-2016 19:14:59.726 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/examples has finished in 247 ms 01-Feb-2016 19:14:59.726 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/host-manager de la aplicación web 01-Feb-2016 19:14:59.743 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/host-manager has finished in 17 ms 01-Feb-2016 19:14:59.750 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"] 01-Feb-2016 19:14:59.760 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 442905 ms 01-Feb-2016 22:35:59.831 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:10,000 messages Sent:6.81 MB (total) Sent:6.81 MB (application) Time:2.39 seconds Tx Speed:2.85 MB/sec (total) TxSpeed:2.85 MB/sec (application) Error Msg:0 Rx Msg:10,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:6.81 MB] 01-Feb-2016 22:35:59.832 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:10,000 messages Sent:6.81 MB (total) Sent:6.81 MB (application) Time:2.39 seconds Tx Speed:2.85 MB/sec (total) TxSpeed:2.85 MB/sec (application) Error Msg:0 Rx Msg:10,001 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:6.81 MB] 02-Feb-2016 02:04:23.818 INFO [Tribes-Task-Receiver-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:20,000 messages Sent:13.62 MB (total) Sent:13.62 MB (application) Time:4.07 seconds Tx Speed:3.35 MB/sec (total) TxSpeed:3.35 MB/sec (application) Error Msg:0 Rx Msg:20,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:13.62 MB] 02-Feb-2016 02:04:23.820 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:20,000 messages Sent:13.62 MB (total) Sent:13.62 MB (application) Time:4.07 seconds Tx Speed:3.35 MB/sec (total) TxSpeed:3.35 MB/sec (application) Error Msg:0 Rx Msg:20,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:13.62 MB] 02-Feb-2016 05:32:47.761 INFO [Tribes-Task-Receiver-6] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:30,000 messages Sent:20.43 MB (total) Sent:20.43 MB (application) Time:5.72 seconds Tx Speed:3.57 MB/sec (total) TxSpeed:3.57 MB/sec (application) Error Msg:0 Rx Msg:30,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:20.42 MB] 02-Feb-2016 05:32:47.763 INFO [Tribes-Task-Receiver-6] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:30,000 messages Sent:20.43 MB (total) Sent:20.43 MB (application) Time:5.72 seconds Tx Speed:3.57 MB/sec (total) TxSpeed:3.57 MB/sec (application) Error Msg:0 Rx Msg:30,001 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:20.42 MB] 02-Feb-2016 09:01:11.617 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:40,000 messages Sent:27.23 MB (total) Sent:27.24 MB (application) Time:7.38 seconds Tx Speed:3.69 MB/sec (total) TxSpeed:3.69 MB/sec (application) Error Msg:0 Rx Msg:40,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:27.23 MB] 02-Feb-2016 09:01:11.618 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:40,001 messages Sent:27.24 MB (total) Sent:27.24 MB (application) Time:7.38 seconds Tx Speed:3.69 MB/sec (total) TxSpeed:3.69 MB/sec (application) Error Msg:0 Rx Msg:40,002 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:27.23 MB] 02-Feb-2016 12:29:35.561 INFO [Tribes-Task-Receiver-2] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:49,999 messages Sent:34.04 MB (total) Sent:34.04 MB (application) Time:8.99 seconds Tx Speed:3.79 MB/sec (total) TxSpeed:3.79 MB/sec (application) Error Msg:0 Rx Msg:50,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:34.04 MB] 02-Feb-2016 12:29:36.108 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:50,000 messages Sent:34.04 MB (total) Sent:34.05 MB (application) Time:8.99 seconds Tx Speed:3.79 MB/sec (total) TxSpeed:3.79 MB/sec (application) Error Msg:0 Rx Msg:50,001 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:34.04 MB] 02-Feb-2016 15:57:59.873 INFO [Tribes-Task-Receiver-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:59,999 messages Sent:40.85 MB (total) Sent:40.85 MB (application) Time:10.64 seconds Tx Speed:3.84 MB/sec (total) TxSpeed:3.84 MB/sec (application) Error Msg:0 Rx Msg:60,000 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:40.85 MB] 02-Feb-2016 15:58:00.431 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[ Tx Msg:60,000 messages Sent:40.85 MB (total) Sent:40.85 MB (application) Time:10.64 seconds Tx Speed:3.84 MB/sec (total) TxSpeed:3.84 MB/sec (application) Error Msg:0 Rx Msg:60,001 messages Rx Speed:0.00 MB/sec (since 1st msg) Received:40.85 MB] A: There are many different possible causes to this problem. Two top suspects are: * *You are using a plug-in that is triggering a component scan of Spring classes. *Your code has added a component scan that is hitting Spring classes. A search for "component-scan" throughout your project can help you check for those two causes.
{ "language": "en", "url": "https://stackoverflow.com/questions/35164534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bootstrap 4: I'd like my columns to take the full width of my container I would like my columns to take the full width of my container, I have tried many things but haven't find a solution how to fix it. Here's an example of what I want: While it looks like this for now: See the little red arrows? This is the space that I don't want to see. HTML: <div class="container"> <div class="row"> <div class="col ml-auto"> <div class="card card-body justify-content-center" style="height:150px"> <h5 class="card-title">Privacy & Security</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> </div> </div> <div class="col mr-auto"> <div class="card card-body justify-content-center" style="height:150px"> <h5 class="card-title">Privacy & Security</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> </div> </div> </div> </section> CSS: .framework { background: rgb(27,28,30); background: linear-gradient(180deg, #1b1c1e 0%, #27262d 200%); display:grid; max-width:100%; padding:30px 10px 30px 10px; margin-top:0.5em; height:100%; margin-left: auto; margin-right: auto; .card { background: #27262d; border-radius:5px; } img { width:50px; height:auto; display:block; margin-left:auto; margin-right:auto; margin-top:15px; } } CSS (for Mobile version) : @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@800&display=swap'); .framework { .card-title { font-family:'Open Sans',sans-serif; font-weight:800; font-size:14pt; text-align:left; text-transform:uppercase; } .card-text { font-family:geomanist,sans-serif; color:rgba(255, 255, 255, 0.377); font-weight:400; font-size:10pt; letter-spacing:-0.1px; line-height:15px; text-align:left; } @media only screen and (max-width: 600px) { .card-title { font-size:11pt; } .card-text { font-size:9pt; } } } edit (10/19/2020 | 12:09 [brussels])kind of fixed it by adding class ".mx-md-n5" next to class ".row" in the same div, this aint perfect but it satisfies me A: Please add pl-0 and pr-0 class for the remove the padding <div class="col align-self-start pl-0"> <div class="card card-body justify-content-center" style="height:150px"> <h5 class="card-title">Privacy & Security</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> </div> </div> <div class="col align-self-end pr-0"> <div class="card card-body justify-content-center" style="height:150px"> <h5 class="card-title">Privacy & Security</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> </div> </div> A: <div class="col-12 mb-3"> <div class="card card-body justify-content-center" style="height:150px"> <h5 class="card-title">Privacy & Security</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> </div> </div> <div class="col ml-auto"> <div class="card card-body justify-content-center" style="height:150px"> <h5 class="card-title">Privacy & Security</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> </div> </div> <div class="col mr-auto"> <div class="card card-body justify-content-center" style="height:150px"> <h5 class="card-title">Privacy & Security</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> </div> </div> </div> A: Please use the predefined Bootstrap classes at first and if you have any custom CSS add it in a new classes. Is this what you search for: HTML <div class="container" style="border:1px red dotted"> <div class="row " style="border:1px blue dotted"> <div class="col pl-0"> <div class="card card-body justify-content-center" style="height:150px"> <h5 class="card-title">Privacy & Security</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> </div> </div> <div class="col pr-0"> <div class="card card-body justify-content-center" style="height:150px"> <h5 class="card-title">Privacy & Security</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> </div> </div> </div> </div> A: this is a demo for what exactly you want I have just remove padding for the full-width box and for the next two box I remove padding-left for left side box and padding-right for the right side box. this is the code snippet which helps you to understand what I do. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body> <div class="container p-0"> <div class="row m-0"> <div class="col-12 p-0 mb-4"> <div class="card bg-primary card-body text-center justify-content-center" style="height: 150px; font-size: 50px; color: red;"> Box 1 </div> </div> <div class="col-6 pl-0"> <div class="card bg-primary card-body text-center justify-content-center" style="height: 150px; font-size: 50px; color: red;"> Box 2 </div> </div> <div class="col-6 pr-0"> <div class="card bg-primary card-body text-center justify-content-center" style="height: 150px; font-size: 50px; color: red;"> Box 3 </div> </div> </div> </div> </body> </html> I hope this answer will help you to solve your problem this time and also help you in future for this type of structure. Thank you...
{ "language": "en", "url": "https://stackoverflow.com/questions/64424545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are variables de-allocated when they go out of scope Given this code snippet def doSomething() = { val associations : HashMap[Int, Int] = function_that_create_a_hashmap println("something") } When doSomething terminates is the variable associations de-allocated? Should I call some destructor on it (maybe .clear, in this case) or is that operation not useful? A: That is not necessary - if your application has no more references to the HashMap, then it will be garbage collected automatically at some point in the future. If you really have a huge hash map that you want to get rid off to avoid its memory consumption trigger GC cycles after doSomething completes, you can call System.gc(), but this is in general neither needed nor a recommended practice. A: Calling .clear on a HashMap doesn't remove it from memory; it simply clears it of preexisting mappings and so the object will still exist in memory. Since Scala runs on the JVM, I would imagine that it will get collected by the garbage collector at some point in the future (assuming that there are no existing-references to associations). The JVM manages its own memory, thus freeing the programmer of the burden of manually-managing memory. A: The binding associations ceases to exist when the scope in which it was created ceases to exist (when a given call to doSomething returns). That removes one reference to the HashMap and once there are none left, the value is garbage and subject to reclamation at an unspecified time in the future (possibly never / not before the JVM exits).
{ "language": "en", "url": "https://stackoverflow.com/questions/15884872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook SDK Graphrequest returns null Using Facebook SDK 4.4 in Xamarin.Android project. I have the following method : protected override void OnCreate(Bundle savedInstanceState) { LoginButton button = FindViewById<LoginButton>(Resource.Id.FbLoginBtn); button.SetReadPermissions(new List<string>{ "public_profile", "email" }); mCallBackManager = CallbackManagerFactory.Create(); button.RegisterCallback(mCallBackManager, this); button.Click += (o, e)=> { GraphRequest request = GraphRequest.NewMeRequest(AccessToken.CurrentAccessToken, this); Bundle paramenters = new Bundle(); paramenters.PutString("fields", "id,name,email,first_name,last_name"); request.Parameters = paramenters; request.ExecuteAsync(); }; } public void OnCompleted(JSONObject @object, GraphResponse response) { if (@object != null) { userEmail.Text = @object.ToString(); } } The problem with the above code is that, in the OnCompleted method, the JSONObject always return null when i log in to my facebook account from the app. But when i click the button again to Log Out, i get the proper json with all fields that i specified. My question is, why is the GraphRequest returning null upon log-in but successfully returns the JSON upon log out?
{ "language": "en", "url": "https://stackoverflow.com/questions/56045692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why there is no Server Name under integration services in SSMS? I cant connect to Integration Services in SSMS there is no Server Name under it when I browse , if I type manually the server name based on how other services have it says class not registered A: If someone else has the same problem the reason was because I had installed SSIS 2017 but was using SSMS 18.x , if you have SSIS 2017 use SSMS 17.x and such with other versions
{ "language": "en", "url": "https://stackoverflow.com/questions/58779894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mystery gaps in CSS Grid In the snippet below, there are gaps above and beneath 'main' area which suppose to be an empty cells with the same height as the grid cells. Also there is an empty space at the very bottom. I've tried setting grid-auto-flow to different values, but there is no effect except for the very bottom gap when it set to column. What causes that? and how to fix it? .header { grid-area: hd; } .footer { grid-area: ft; } .content { grid-area: main; } .sidebar { grid-area: sd; } * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; max-width: 940px; margin: 0 auto; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-auto-rows: minmax(auto, auto); grid-template-areas: "hd hd ft" "sd . ft" "sd main ft" "sd . ft"; } <div class="wrapper"> <div class="header">Header</div>     <div class="sidebar">Sidebar</div>     <div class="content">Content</div>     <div class="footer">Footer</div> </div> A: **I tested the code on Chrome and Firefox and the result was ** Always add the <!DOCTYPE> declaration to your HTML documents, so that the browser knows what type of document to expect. .header { grid-area: hd; } .footer { grid-area: ft; } .content { grid-area: main; } .sidebar { grid-area: sd; } * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; max-width: 940px; margin: 0 auto; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-auto-rows: minmax(auto, auto); grid-template-areas: "hd hd ft" "sd . ft" "sd main ft" "sd . ft"; } <!DOCTYPE html> <html> <head> </head> <body> <div class="wrapper"> <div class="header">Header</div> <div class="sidebar">Sidebar</div> <div class="content">Content</div> <div class="footer">Footer</div> </div> </body> </html> A: Here's what's happening: First, let's see the gaps (they don't appear in many cases): .wrapper { display: grid; grid-auto-rows: minmax(auto, auto); grid-template-areas: "hd hd ft" "sd . ft" "sd main ft" "sd . ft"; } .header { grid-area: hd; } .footer { grid-area: ft; } .content { grid-area: main; } .sidebar { grid-area: sd; } * { box-sizing: border-box; } .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; max-width: 940px; margin: 0 auto; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div class="header">Header</div>     <div class="sidebar">Sidebar</div>     <div class="content">Content</div>     <div class="footer">Footer</div> </div> What you're seeing is the rendering of &nbsp; (non-breaking space) characters in the HTML code. As white space characters, they're invisible, which makes them hard to detect. But once you remove them, the layout works as expected. .wrapper { display: grid; grid-auto-rows: minmax(auto, auto); grid-template-areas: "hd hd ft" "sd . ft" "sd main ft" "sd . ft"; } .header { grid-area: hd; } .footer { grid-area: ft; } .content { grid-area: main; } .sidebar { grid-area: sd; } * { box-sizing: border-box; } .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; max-width: 940px; margin: 0 auto; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div class="header">Header</div> <div class="sidebar">Sidebar</div> <div class="content">Content</div> <div class="footer">Footer</div> </div> Lastly, why doesn't the faulty layout display in many cases? When you copy HTML code as rendered on a web page (e.g., copy the code directly from the question), the &nbsp; characters, being HTML code, have already been rendered. So only plain (collapsible) white space gets copied and the layout will appear to be working fine. Also, if you copy the HTML code from some code editors in some browsers (e.g., the Stack Snippet editor on Edge), the &nbsp; characters don't get copied, either. I needed to copy the code from the jsFiddle editor in Chrome to finally see the problem. Also, if you hit the "Tidy" button in the editor using the original code, spaces will be added between the lines. A: The empty cells have to be inserted, you'll not get it by default, just adding the HTML and body tag fixed the bottom gap issue: .header { grid-area: hd; } .footer { grid-area: ft; } .content { grid-area: main; } .sidebar { grid-area: sd; } .empty-cell1 { grid-area: ec1; } .empty-cell2 { grid-area: ec2; } * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; max-width: 940px; margin: 0 auto; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-template-areas: "hd hd ft" "sd ec1 ft" "sd main ft" "sd ec2 ft"; } <!DOCTYPE html> <html> <head> </head> <body> <div class="wrapper"> <div class="header">Header</div> <div class="sidebar">Sidebar</div> <div class="content">Content</div> <div class="footer">Footer</div> <div class="empty-cell1"></div> <div class="empty-cell2"></div> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/58131619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is setting my webserver to https, also securize my ajax call? Imagine I have a small webpage I browse in https with a signed certificate that load data with an ajax call like this: $.ajax( { type:"POST", url:"ressource/js/load_footer.php", data:"page="+variable, success: alert("poney"); } ) Can I assume that this ajax call is secure by https ? or does it communicate by http ? A: As mentionned in the comment of my question: Since it is a relative URL, it will use the protocol of the page it is executed in. But instead of asking, you could also have found this out easily yourself by just looking at the request in the net panel of your browser’s developer tools … – CBroe 4 mins ago
{ "language": "en", "url": "https://stackoverflow.com/questions/22986174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to use mechanize to fill search form and get results back? i am trying to use mechanize with python to search for a keyword using a a search form. this is the form code : <form id="searchform" action="http://www.example.com/" method="get"> <input id="s" type="text" onfocus="if (this.value == 'Search') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search';}" name="s" value="Search"> <input type="image" style="border:0; vertical-align: top;" src="http://www.example.com/wp-content/themes/SimpleColor/images/search.gif"> </form> i want to be able to submit and get the results back so i can extract the info from the results. Thanks in advance. A: From the official page, you create a browser object by br = mechanize.Browser() and follow a link with the object - br.open("http://www.example.com/"), and then you select a form by br.select_form(name="searchform") and you can pass an input by br["s"] = #something and submit it resp = br.submit() use the resp object like you wish.
{ "language": "en", "url": "https://stackoverflow.com/questions/24948776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: T5Tokenizer and T5EncoderModel are used to encode sentences then nn.TransformerDecoder to decode to a 2-label tensor. It gives error Used T5Tokenizer to tokenize a sentence then T5EncoderModel to encode. Finally, used the pytorch nn.TransformerDecoder to decode it. The target vector is a torch.tensor [y1, y2] where y1 and y2 have binary value. But it returns an error RuntimeError: DataLoader worker (pid(s) 723820) exited unexpectedly. The dataset class is given below. tokenizer=T5TokenizerFast.from_pretrained('t5-base') MAX_LEN = tokenizer(balanced_sentences[max_idx]).input_ids class MyDataset(Dataset): def __init__(self, sentences, labels): self.labels = labels self.sentences = sentences self.tokenizer = tokenizer def __len__(self): return len(self.labels) def __getitem__(self, idx): sentence = self.sentences[idx] label = self.labels[idx] tokenized = tokenizer(self.sentences[idx], max_length=MAX_LEN, padding='max_length', truncation=True, add_special_tokens=True, return_tensors="pt") sample = {"input_id": tokenized['input_ids'].flatten(), "attention_mask":tokenized['attention_mask'].flatten(), "label": label} return sample The model is created in the following way class MyModel(pl.LightningModule): def __init__(self): super().__init__() self.encoder = T5EncoderModel.from_pretrained("t5-base", return_dict = True) dec_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8, batch_first=True) self.decoder = nn.TransformerDecoder(dec_layer, num_layers=6) self.loss_fc = nn.BCELoss() def forward(self, input_id, attention_mask, label=None): encoded_sentence = self.encoder(input_id, attention_mask)#.last_hidden_state.mean(dim=1) loss, output = self.decoder(label, encoded_sentence) return loss, output def training_step(self, batch, batch_idx): input_id = batch['input_id'] attention_mask = batch['attention_mask'] label = batch['label'] loss, output = self(input_id = input_id, attention_mask=attention_mask, label = label) self.log('train_loss', loss, prog_bar = True, logger = True) return loss def validation_step(self, batch, batch_idx): input_id = batch['input_id'] attention_mask = batch['attention_mask'] label = batch['label'] loss, output = self(input_id = input_id, attention_mask=attention_mask, label = label) self.log('train_loss', loss, prog_bar = True, logger = True) return loss def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=0.001) trainer = pl.Trainer(logger = logger, num_sanity_val_steps=0, max_epochs = N_EPOCHS, gpus = 1, progress_bar_refresh_rate = 20) trainer.fit(model, data_module) A: If you're use VSCode it sounds like the data loader has multiple workers and it can't create more threads. Set the number of workers to 0. See: VSCode bug with PyTorch DataLoader?
{ "language": "en", "url": "https://stackoverflow.com/questions/71513200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the correct way to encapsulate factory methods from derived classes when implementing factory in base class? I am trying to create simple class with ability to register derived classes for creation from base class. However I cannot find a good way to encapsulate this functionality from descendants. Class variables looks for me a bad idea because they available everywhere in inheritance chain. So I try do something with class instance variables. Perfectly it will be that all class methods will be inaccessible except register_as class A @registered = {} class << self def register_as(name) A.registered[name] = self end def known A.registered end protected attr_accessor :registered end def helpful_method end end class B < A class << self def reg_trash A.registered[:trash] = :trash end end B.register_as :b end B.reg_trash p A.known However registered is still accessible from B class. Currently looks like the only one possible option is to split A class to dedicated Factory class and A class will hold only helpful instance methods. Maybe it is possible to do something via .inherited and .undef_method, isn't it? A: Maybe it is possible to do something via .inherited and .undef_method, isn't it? Yes, it is possible. But the idea smells, as for me - you're going to break substitutability. If you don't want the "derived" classes to inherit the behavior of the parent, why do you use inheritance at all? Try composition instead and mix in only the behavior you need. For example, something like this could work (very dirty example, but I hope you got the idea): class A module Registry def register_as(name) A.register_as(name, self) end end @registered = {} def self.register_as(name, klass) @registered[name] = klass end def self.known @registered end end class B extend A::Registry register_as :b end class C extend A::Registry register_as :c end A.known # => {:b => B, :c => C}
{ "language": "en", "url": "https://stackoverflow.com/questions/55381868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Clarity on Docker Container IP addresses for API requests I want to be able to connect to a third-party .NET API I am running as a docker image within a container. When I connect to the ip address and port on my browser it works though when I try and run a get request in python it does not. I am not sure what I am doing wrong. The Django python application is an image within the container using 0.0.0.0:8000. This is the docker-compose.yml file for a .NET image I am running from within a container: mt4rest: image: mt4rest:latest ports: - "0.0.0.0:5000:80" Here are the ports as per docker inspect "Ports": { "443/tcp": null, "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "5000" } ] }, When I run http://0.0.0.0:5000/Ping or http://127.0.0.1:5000/Ping in my browser, I get OK though when I run the same endpoints in Python: response = requests.get('http://0.0.0.0:5000/Ping') or response = requests.get('http://127.0.0.1:5000/Ping') I receive the following error: requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=5000): Max retries exceeded with url: /Ping (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fe7aa5af640>: Failed to establish a new connection: [Errno 111] Connection refused')) or requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=5000): Max retries exceeded with url: /Ping (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f6322e2b640>: Failed to establish a new connection: [Errno 111] Connection refused')) I understand this to mean that the address for the request is not found. I am not sure what I am doing wrong. A: Lets call your host as HOST_BASE. You are having two containers, one is exposing 5000 on host. Its HOST_BASE:5000. Other is your python-app container. Now, you are running another python-app in container on host HOST_BASE. And try to hit: http://0.0.0.0:5000, which is not accessible. Note: its 0.0.0.0 is localhost of the container itself. You want to connect to HOST_BASE:5000, which is not localhost or 0.0.0.0 You need to configure networking between your two containers. Or, for simplicity, use --network host while running both of your container. Hope that helps. A: There is an acceptable answer for this question on stackoverflow which solves the problem: Python requests in Docker Compose containers
{ "language": "en", "url": "https://stackoverflow.com/questions/75005705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error: Transaction has been reverted by the EVM Following a tutorial online to learn about minting NFTs - https://blog.logrocket.com/how-to-create-nfts-with-javascript/ I keep getting this error, and I've tried reviewing different posts but I still can't seem to bypass it. (node:28474) UnhandledPromiseRejectionWarning: Error: Transaction has been reverted by the EVM: { "transactionHash": "0x70b857fb9adf1539b7b8e9612c1c5e2a470b4db9bc4060b943bcd75b85ca36d9", "blockHash": "0x79f98597420377cf932ac053db4051c76c40347337413949c0e61044a3c490dc", "blockNumber": 11554713, "contractAddress": null, "cumulativeGasUsed": 22945, "effectiveGasPrice": "0x4a817c800", "from": "0x6031679a1230b03acb601bd5d643de4dfe93ac1c", "gasUsed": 22945, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": false, "to": "0xfcacbb204e0d93776cfd9a7f26f8333547e11dde", "transactionIndex": 0, "type": "0x0" } at Object.TransactionError (/Users/x224631/Applications/LlamaClub/node_modules/web3-core-helpers/lib/errors.js:87:21) at Object.TransactionRevertedWithoutReasonError (/Users/x224631/Applications/LlamaClub/node_modules/web3-core-helpers/lib/errors.js:98:21) at /Users/x224631/Applications/LlamaClub/node_modules/web3-core-method/lib/index.js:393:57 at processTicksAndRejections (internal/process/task_queues.js:94:5) (node:28474) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 7) (node:28474) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. Here's my smart contract file (.sol) //Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721 // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // implements the ERC721 standard // import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // keeps track of the number of tokens issued import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // Accessing the Ownable method ensures that only the creator of the smart contract can interact with it contract TorNFT is ERC721URIStorage, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; mapping(string => uint8) hashes; // the name and symbol for the NFT constructor() public ERC721("LlamaClub", "TOR") {} // Create a function to mint/create the NFT // receiver takes a type of address. This is the wallet address of the user that should receive the NFT minted using the smart contract // tokenURI takes a string that contains metadata about the NFT function createNFT( address receiver, // string memory hash, string memory tokenURI ) public returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(receiver, newItemId); _setTokenURI(newItemId, tokenURI); return newItemId; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/70230855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Shell program to print the first and last parameter and their sum I want to make a shell program which prints out the first and the last parameter, then it prints out their sum. Here is my code, but it gives an error and doesn't work, can anybody help? echo "How many parameters do you want?" read param echo "You entered $param parameters" first = $param last = `echo $*|cut –f$# -d" "` sum = `$first + $last` echo "The sum of the two parameters are $sum" A: Here is an approach for you: first="$1" last="${@: -1}" echo "first: $first" echo "last: $last" sum=$((first + last)) echo "The sum of the two parameters are $sum" You can run like this: ./program.sh 1 2 3 4 first: 1 last: 4 The sum of the two parameters are 5
{ "language": "en", "url": "https://stackoverflow.com/questions/53244621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c# 6.0 and reflection, getting value of Property Initializers I've been trying to experiment with reflection and I have a question. Lets say I have a class, and in this class I have a property initilized with the new feature of c# 6.0 Class MyClass() { public string SomeProperty{ get; set; } = "SomeValue"; } Is there any way of getting this value, with reflection, without initilizating the class? I know I could do this; var foo= new MyClass(); var value = foo.GetType().GetProperty("SomeProperty").GetValue(foo); But what I want to do is something similiar to this ; typeof(MyClass).GetProperty("SomeProperty").GetValue(); I know I could use a field to get the value. But it needs to be a property. Thank you. A: It's just a syntax sugar. This: class MyClass() { public string SomeProperty{ get; set; } = "SomeValue"; } will be unwrapped by compiler into this: class MyClass() { public MyClass() { _someProperty = "SomeValue"; } // actually, backing field name will be different, // but it doesn't matter for this question private string _someProperty; public string SomeProperty { get { return _someProperty; } set { _someProperty = value; } } } Reflection is about metadata. There are no any "SomeValue" stored in metatada. All you can do, is to read property value in regular way. I know I could use a field to get the value Without instantiating an object, you can get values of static fields only. To get values of instance fields, you, obviously, need an instance of object. A: Alternatively, if you need default value of property in reflection metadata, you can use Attributes, one of it from System.ComponentModel, do the work: DefaultValue. For example: using System.ComponentModel; class MyClass() { [DefaultValue("SomeValue")] public string SomeProperty{ get; set; } = "SomeValue"; } // var propertyInfo = typeof(MyClass).GetProperty("SomeProperty"); var defaultValue = (DefaultValue)Attribute.GetCustomeAttribute(propertyInfo, typeof(DefaultValue)); var value = defaultValue.Value;
{ "language": "en", "url": "https://stackoverflow.com/questions/33383991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Why no output from Kendo-UI template? I am trying to use Kendo-UI templates to display values from a JavaScript array, but nothing is appearing in the HTML. <script id="javascriptTemplate" type="text/x-kendo-template"> <table> # for (var i = 0; i < tableData.length; i++) { # <tr><td>#: tableData[i]#</td></tr> # } # </table> </script> <script type="text/javascript"> var template = kendo.template($("#javascriptTemplate").html()); var tableData = ["1", "2"]; template(tableData); </script> A: I found three problems: 1) the template(tableData) must be set to a DOM element, as in $("#output").html(template(tableData)); and 2) that the variable name inside the template must be data; and 3) the code that loads the template must be executed after the DOM is ready. Here is the complete and corrected code: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <link href="Content/kendo/2012.2.710/kendo.common.min.css" rel="stylesheet" /> <link href="Content/kendo/2012.2.710/kendo.default.min.css" rel="stylesheet" /> <script src="Scripts/jquery-1.8.2.min.js"></script> <script src="Scripts/kendo/2012.2.710/kendo.web.min.js"></script> <script type="text/javascript"> $(document).ready(function () { var template = kendo.template($("#javascriptTemplate").html()); var tableData = ["1", "2"]; $("#output").html(template(tableData)); }); </script> </head> <body> <form id="form1" runat="server"> <div id="output"></div> <script id="javascriptTemplate" type="text/x-kendo-template"> <table> # for (var i = 0; i < data.length; i++) { # <tr><td>#=data[i]#</td</tr> # } # </table> </script> </form> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/13349314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: In SignalR Core how can i exclude a connection from being notified The scenario is as follow: I have multiple WPF clients that have a SignalR connection with a server. One WPF client calls a REST API to generate an order. The server would like to notify all WPF clients that an order was placed except for the WPF client that created the order. Note that the my notification logic is put outside of the hub class. What is the best approach to solve this? A: There is a build-in Hub.Clients.Others to achieve your requirement. Here is a sample: public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.Others.SendAsync("ReceiveMessage", user, message); } } Reference: https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-3.1#the-clients-object
{ "language": "en", "url": "https://stackoverflow.com/questions/69901447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: inside cfscript component I'm making components for a site and I'm wondering if I can return a cfform inside a return variable from a component and force coldfusion to output it parsed. Obviously using "writeOutput(")" doesn't work. How could I achieve this? Thanks for your time! A: You can't return a cfform, because tags can't be used inside of a CFScript based component. You're far better off doing something like this with a custom tag, which then references your component to get pieces to build out the form. I would avoid (if at all possible) putting any cfform related pieces into a component, script-based or not. If you did want to ultimately go this route, you'd need to put the cfform (and it's relevant pieces) either in another component that gets called by the script based one, or in an include that then is saved to a variable. All of the solutions related to trying to get the cfform into your CFC are going to be messy. A: If you absolutely must do this (though I would shy away from it myself) you might want to have a look at this: http://www.madfellas.com/blog/index.cfm/2011/1/26/Using-CFML-tags-in-cfscript-C4X-prototype
{ "language": "en", "url": "https://stackoverflow.com/questions/4805343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Separating DOM elements for click events I have a website which displays search results. The results are displayed with headline information of the full item. The html of each search result looks like this: <article class="search_result" onclick="location.href='#';" style="cursor: pointer;"> // Search result data </article> As you can see, I have made it so that you can click anywhere and access the result in more detail However, within the search result, I have also included a button which performs another function. The problem I have is when you click on the button, both the button and the search result receive the click event and act upon it. If the button is clicked, I dont want the search result to handle it as well. How can I sort this? A: JavaScript events bubble up the DOM by default, so events triggered on a children will be triggered on the parent. To prevent this, you need to stop the propagation of the event. This is done by: event.stopPropagation(); Note that event is usually passed as a parameter to your callback functions. (Meaning, don't use onclick="" attributes so you get function callback) Full documentation: https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation (IE < 8 fallback: Prototype Event.StopPropagation for IE >= 8)
{ "language": "en", "url": "https://stackoverflow.com/questions/18774143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: is there a way to trigger 10 scripts at any given time in Linux shell scripting? I have a requirement where I need to trigger 10 shell scripts at a time. I may have 200+ shell scripts to be executed. e.g. if I trigger 10 jobs and two jobs completed, I need to trigger another 2 jobs which will make number of jobs currently executing to 10. I need your help and suggestion to cater this requirement. A: Yes with GNU Parallel like this: parallel -j 10 < ListOfJobs.txt Or, if your jobs are called job_1.sh to job_200.sh: parallel -j 10 job_{}.sh ::: {1..200} Or. if your jobs are named with discontiguous, random names but are all shell scripts named with .sh suffix in one directory: parallel -j 10 ::: *.sh There is a very good overview here. There are lots of questions and answers on Stack Overflow here. A: Simply run them as background jobs: for i in {1..10}; { ./script.sh & } Adding more jobs if less than 10 are running: while true; do pids=($(jobs -pr)) ((${#pids[@]}<10)) && ./script.sh & done &> /dev/null A: There are different ways to handle this: * *Launch them together as background tasks (1) *Launch them in parallel (1) *Use the crontab (2) *Use at (3) Explanations: (1) You can launch the processes exactly when you like (by launching a command, click a button or whatever event you choose) (2) The processes will be launched at the same time, every (working) day, periodically. (3) You choose a time when the processes will be launched together once. A: I have used below to trigger 10 jobs a time. max_jobs_trigger=10 while mapfile -t -n ${max_jobs_trigger} ary && ((${#ary[@]})); do jobs_to_trigger=`printf '%s\n' "${ary[@]}"` #Trigger script in background done
{ "language": "en", "url": "https://stackoverflow.com/questions/64608106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C#: HtmlDocument object has no constructor? What's up with that? It seems the only way to get an working HtmlDocument object is copying the Document property of an mshtml/webbrowser control. But spawning that is sloooooooooooow. I'd like to avoid writing my own HTML parser and HtmlAgilityPack is copyleft. Are there other sources of getting an instantiated HtmlDocument that I can dump HTML from a string into? Or, is there a way to override HtmlElement's annoying habit of throwing a fit when using InnerHtml/OuterHtml with img tags and tr elements? Edit: I'm referring to System.Windows.Forms.HtmlDocument. My apologies, I'm still new to C# and .Net and know very little about COM and some of the other things this topic brings up. A: It has no constructor because it's just a wrapper class around an unmanaged object. Reference: http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.aspx HtmlDocument provides a managed wrapper around Internet Explorer's document object, also known as the HTML Document Object Model (DOM). You obtain an instance of HtmlDocument through the Document property of the WebBrowser control. Depending on what you want it for, you may want to look at SGMLReader or the up-to-date community version. A: Robust Programming? When using the DOM through the WebBrowser control, you should always wait until the DocumentCompleted event occurs before attempting to access the Document property of the WebBrowser control. The DocumentCompleted event is raised after the entire document has loaded; if you use the DOM before then, you risk causing a run-time exception in your application. http://msdn.microsoft.com/en-us/library/ms171712.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/691657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: SQLite Stores characters as strings? I am using the System.Data.SQLite ADO.Net Provider to interact with an SQLite DB. I used the following syntax to create a new table: CREATE TABLE [tb_Replace] ([Character] CHAR(1), [Substitute] CHAR(1)) I then tried to read the data using a simple select: public static List<char> GetReplaceableCharacters(string connectionString) { List<char> replaceableCharacters = new List<char>(); SQLiteConnection sqlConnection = new SQLiteConnection(connectionString); sqlConnection.Open(); using (SQLiteTransaction transaction = sqlConnection.BeginTransaction()) { SQLiteCommand command = new SQLiteCommand(@"SELECT Character FROM tb_Replace", sqlConnection); SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()) replaceableCharacters.Add((char)reader["Character"]); } sqlConnection.Close(); return replaceableCharacters; } However when I did that it threw an InvalidCastException. However, if I change the return type to aList<string> and cast reader["Character"] to a string it works. Does anyone know why this would be? A: Just read http://www.sqlite.org/datatype3.html. Sqlite has five type affinities (types preferred by a column of a table) and five storage classes (possible actual value types). There is no CHARACTER type among either of them. Sqlite allows you to specify just about anything as a type for column creation. But it doesn't enforce types for everything except INTEGER PRIMARY KEY columns. It recognizes a few substring of declared type names to determine column type affinity, so CHARACTER, CHARCOAL and CONTEXTUALIZABLE are all just a funny way of writing TEXT.
{ "language": "en", "url": "https://stackoverflow.com/questions/14537740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Opening a new page in the program in vb.net (hreflink) how to do that when you clicked the button opened the generated youtube page? My button code: Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Dim buttonele As HtmlElementCollection = WebBrowser1.Document.All For Each webpageelement As HtmlElement In buttonele If webpageelement.GetAttribute("id") = "likeText" Then webpageelement.InvokeMember("click") End If Next End Sub And code button in website: enter image description here in <a href="linkkk"> there is already a generated link to yt in <a class="likeClick" href="#"> - # generates new links after clicking on the button, nothing happens. I need that after clicking the page generated in this link opens: <a href="https://href.li/?http://www.youtube.com/watch?v=9-MRipzqM5Y"> A: Question is uncler, but either way, either click the video button or Webbrowser.Navigate("webpage url")
{ "language": "en", "url": "https://stackoverflow.com/questions/51351576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Exporting a scene as a GLTF I would like to understand what exporting a scene in a GLTF format entails. I have a 3D model with high-definition texture maps, materials, yadee yadee yada, and I'm exporting a scene to a GLTF file. During this process, is there actually any compute involved? What I mean by that is, does exporting the scene to the GLTF format actually involve any rendering, or any computation similar to rendering, or does it just basically bundle the 3D model with embedded textures in JPEG/PNG? A: It matters what system you're exporting from, but in this case you tagged the question Blender so I will give an answer for exporting from Blender. With most formats, exporting is just a matter of gathering up and organizing the data (vertices, attributes, meshes, textures and/or texture filename references, and the like) and packing into the exported file according to the format specification. With the particular case of Blender exporting to glTF, there's a little catch. The glTF file format is particular about certain color channels. For example, roughness gets stored in glTF's green channel, metallic in the blue channel, and so on. So if a Blender user supplies a greyscale image for roughness and a separate image for metallic, Blender can't export those images as-is to a glTF file. So the Blender glTF exporter includes a section on image encoding. This bit of Python code will adapt the user-supplied images, when needed, to reassign color channels to match the glTF specification. Having all glTF assets use the same channel assignments makes it much easier for viewers to have shaders that work for all glTF files, particularly those systems that use precompiled shaders with runtime assets. The glTF mesh data may also be different from Blender's mesh. The glTF format specifies the data the way a GPU wants to receive it, with vertex attributes (glTF accessors) and the like. This means that artist-friendly features such as per-face UVs and per-face normals are converted to separate vertices in the exported glTF. Per-face attributes must be unwelded, converted into separate GPU vertices with separate vertex attributes. Some users perceive this as an increase in the number of vertices in the model, but internally the GPU needs this expanded version of the mesh data to function. In both these cases, the difference between artist asset interchange vs. raw GPU data delivery is visible. The glTF format makes the intentional choice to go with the latter, as a "transmission format" for publishing to the end user. This lightens the load on readers and viewers who wish to receive the file and render it quickly. But it does place compute requirements on glTF exporters.
{ "language": "en", "url": "https://stackoverflow.com/questions/73109473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create sorted array from unsorted ArrayList I have an ArrayList filled with objects of the class result, each result has an attribute named value. I now want to create an Array which is filled with references to the same memory location as in the ArrayList but now in order where to object with the highest value is in the first location, the second highest in the second location and so forth. I have searched here but haven't found any other post like it. A: There are multiple ways to solve it using Gauava or lambda expressions. Hope this implementation solve your problem. package com; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TestDemo { public static void main(String[] args) { List < HockeyPlayer > players = new ArrayList < HockeyPlayer > (); HockeyPlayer obj1 = new HockeyPlayer(); obj1.goalsScored = 22; players.add(obj1); HockeyPlayer obj2 = new HockeyPlayer(); obj2.goalsScored = 11; players.add(obj2); HockeyPlayer obj3 = new HockeyPlayer(); obj3.goalsScored = 111; players.add(obj3); HockeyPlayer obj4 = new HockeyPlayer(); obj4.goalsScored = 3; players.add(obj4); Collections.sort(players, new Comparator < HockeyPlayer > () { @Override public int compare(HockeyPlayer player1, HockeyPlayer player2) { return player1.goalsScored - player2.goalsScored; } }); for (int i = 0; i < players.size(); i++) { System.out.println(players.get(i).goalsScored); } HockeyPlayer array[] = new HockeyPlayer[players.size()]; players.toArray(array); // contains reference for (int i = 0; i < array.length; i++) { System.out.println(array[i].goalsScored); } } } class HockeyPlayer { public int goalsScored; }
{ "language": "en", "url": "https://stackoverflow.com/questions/34567226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Warning: A non-numeric value encountered in PHP 7.3 I have a Wordpress site running on PHP 7.3 and since updating I am receiving the following error on the front end of the website: Warning: A non-numeric value encountered in /homepages/36/d362586048/htdocs/genag/wp-includes/formatting.php on line 3378 The code on that line is $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY ); Can anyone help with what I should be changing the line to for correcting the error? Thanks. A: According to this, it is happening when the addition operator is being used on $num_words. You could cast $num_words to an integer to avoid this warning. $words_array = preg_split( "/[\n\r\t ]+/", $text, (int)$num_words + 1, PREG_SPLIT_NO_EMPTY ); I would suggest identifying why $num_words isn't an integer first though.
{ "language": "en", "url": "https://stackoverflow.com/questions/58457969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matrix exponentiation becomes too slow I'm currently trying to compute matrix exponentiation, and for that I use the well known algorithm of exponentiation by squaring. def mat_mul(a, b): n = len(a) c = [] for i in range(n): c.append([0]*n) for j in range(n): for k in range(n) : c[i][j] += (a[i][k]*b[k][j]) return c def mat_pow(a, n): if n<=0: return None if n==1: return a if n==2: return mat_mul(a, a) t1 = mat_pow(a, n//2) if n%2 == 0: return mat_mul(t1, t1) return mat_mul(t1, mat_mul(a, t1)) The problem is that my algorithm is still too slow, and after some research, I found out that it was because contrary to what I thought, the time of matrix multiplication depends on the matrix size and on the numbers in the matrix. In fact, the numbers in my matrix become very large, so after some time, the multiplication becomes way slower. Typically, I have M, a 13*13 matrix filled with random 1 and 0, and I want to compute M(108). The integers in the matrix can have hundreds of digits. I'd like to know if there is a way to avoid that problem. I've seen that I could use matrix diagonalization, but the problem is I can't use external libraries (like numpy). So the diagonalization algorithm seems a bit too complicated. A: the time of matrix multiplication depends on the matrix size and on the numbers in the matrix. Well, of course, you are multiplying integers of arbitrary size. CPUs have no support for multiplication of those, so it will be very slow, and become slower as the integers grow. The integers in the matrix can have hundreds of digits. I'd like to know if there is a way to avoid that problem. There are several ways: * *Avoid integers, use floating point numbers and handle the error however your project needs. This will greatly increase the speed and most importantly it won't depend on the size of the numbers anymore. The memory usage will also greatly decrease too. *Use a better algorithm. You already suggested this one, but this is one of the best ways to increase performance if the better algorithm gives you way better bounds. *Optimize it in a low-level systems language. This can give you some performance back, around an order of magnitude or so. Python is a very bad choice for high-performance computing unless you use specialized libraries that do the work for you like numpy. Ideally, you should be doing all 3 if you actually need the performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/63806578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Laravel 5.8 - Unable to use mail to send emails through Mailgun I have spent three days trying to troubleshoot this and run out of ideas. I am trying to send an email using Mailgun, through Laravel 5.8, when directed to the log, it works fine, but when directed to Mailgun, there are no error messages, no email is sent, so obviously it is not received on the specified address, and nothing shows up in mailgun. The code for sending is shown below. Mail::to($validatedData['email_address'])->send(new ResetPassword ($account)); I have double checked the correct settings in the .ENV (changing this to log, sends it to the log, changing to Mailgun results in no log entry) so I know that is right. Having purposely put an error in the ResetPassword mailable to make sure it throws and error, it does, so I know its finding that ok. The view being called exists (the text from the view, together with inserted data, appears in the log when directed there). I am not using Queues. The settings for mailgun have been double checked, and I have even regenerated the API key to make sure. Everything looks right, and produces no error message when run, but no email is sent, can anyone suggest what is going wrong? A: Answered my own question! The Mailgun Api documentation specified api.mailgun.com/v3/YOURDOMAIN However, if you just use api.mailgun.com everything works fine!
{ "language": "en", "url": "https://stackoverflow.com/questions/56824027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Powershell Cyrillic input encoding through node js I trying to make Cyrillic text-to-speech node js module. I using node-powershell to run .NET TTS commands. And it works fine with Latin symbols but does not react on any Cyrillic symbols. However if I input command directly to the Powershell console - it works fine with both cyrillic and latin symbols. So I made a disition that problem point is node.js output encoding. Node.js script: var sayWin = (text) => { var Shell = require('node-powershell'); var shell = new Shell({ inputEncoding: 'binary' //tried different endcoding }); shell.addCommand('Add-Type -AssemblyName System.speech'); shell.addCommand('$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer'); shell.addCommand('$speak.Speak("' + text + '")'); shell.on('output', data => { console.log("data", data); }); return shell.invoke(); } sayWin('latin'); //talk sayWin('кирилица'); //silence sayWin('\ufeffкирилица'); //silence trying with BOM Please, pay attention that you may have to install windows TTS voice package and select it as default system voice to play Cyrillic text(I done it previously). A: One of possible solution is transliteration Cyrillic text into Latin analog. It works but it far from expected results (words pronounces not as good as can be). var transliterate = function(word) { var a = { "Ё": "YO", "Й": "I", "Ц": "TS", "У": "U", "К": "K", "Е": "E", "Н": "N", "Г": "G", "Ш": "SH", "Щ": "SCH", "З": "Z", "Х": "H", "Ъ": "'", "ё": "yo", "й": "i", "ц": "ts", "у": "u", "к": "k", "е": "e", "н": "n", "г": "g", "ш": "sh", "щ": "sch", "з": "z", "х": "h", "ъ": "'", "Ф": "F", "Ы": "I", "В": "V", "А": "a", "П": "P", "Р": "R", "О": "O", "Л": "L", "Д": "D", "Ж": "ZH", "Э": "E", "ф": "f", "ы": "i", "в": "v", "а": "a", "п": "p", "р": "r", "о": "o", "л": "l", "д": "d", "ж": "zh", "э": "e", "Я": "Ya", "Ч": "CH", "С": "S", "М": "M", "И": "yi", "Т": "T", "Ь": "'", "Б": "B", "Ю": "YU", "я": "ya", "ч": "ch", "с": "s", "м": "m", "и": "yi", "т": "t", "ь": "'", "б": "b", "ю": "yu" }; return word.split('').map(function(char) { return a[char] || char; }).join(""); } var sayWin = (text) => { text = /[а-яА-ЯЁё]/.test(text) ? transliterate(text) : text; var shell = new Shell({ inputEncoding: 'binary' }); shell.addCommand('Add-Type -AssemblyName System.speech'); shell.addCommand('$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer'); shell.addCommand('$speak.Speak("' + text + '")'); shell.on('output', data => { console.log("data", data); }); shell.on('err', err => { console.log("err", err); }); shell.on('end', code => { console.log("code", code); }); return shell.invoke().then(output => { shell.dispose() }); } A: I may be answering too late, but let it stay here for the future. I solved this problem for myself by first calling the command: $OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding; In your case, it will be something like shell.addCommand('$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding');
{ "language": "en", "url": "https://stackoverflow.com/questions/43792612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Regarding BigDecimal i do the below java print command for this double variable double test=58.15; When i do a System.out.println(test); and System.out.println(new Double(test).toString()); It prints as 58.15. When i do a System.out.println(new BigDecimal(test)) I get the below value 58.14999999999999857891452847979962825775146484375 I am able to understand "test" double variable value is internally stored as 58.1499999. But when i do the below two System.out.println i am getting the output as 58.15 and not 58.1499999. System.out.println(test); System.out.println(new Double(test).toString()); It prints the output as 58.15 for the above two. Is the above System.out.println statements are doing some rounding of the value 58.1499999 and printing it as 58.15? A: System.out.println(new BigDecimal("58.15")); To construct a BigDecimal from a hard-coded constant, you must always use one of constants in the class (ZERO, ONE, or TEN) or one of the string constructors. The reason is that one you put the value in a double, you've already lost precision that can never be regained. EDIT: polygenelubricants is right. Specifically, you're using Double.toString or equivalent. To quote from there: How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0. A: Yes, println (or more precisely, Double.toString) rounds. For proof, System.out.println(.1D); prints 0.1, which is impossible to represent in binary. Also, when using BigDecimal, don't use the double constructor, because that would attempt to precisely represent an imprecise value. Use the String constructor instead. A: out.println and Double.toString() use the format specified in Double.toString(double). BigDecimal uses more precision by default, as described in the javadoc, and when you call toString() it outputs all of the characters up to the precision level available to a primitive double since .15 does not have an exact binary representation.
{ "language": "en", "url": "https://stackoverflow.com/questions/2406207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: The lower value from a tuple of words and values in haskell I'm trying to write a function that chooses the tuple with the lower value and the tuple is formed by a word and a value. For example, for a list of tuples like this one: [("CHURCH",262),("PENCIL",311),("FLOUR",175),("FOREST",405),("CLASS",105)], the function would return ("CLASS",105) Can someone help me out? :) Thank you so much! A: You're looking for the function minimumBy in the Data.List module. It's type is minimumBy :: (a -> a -> Ordering) -> [a] -> a In your case, it would also be useful to import comparing from the Data.Ord module, which has the type comparing :: Ord a => (b -> a) -> b -> b -> Ordering And this lets you give it an "accessor" function to create an ordering. So in this case you can do minimumSnd :: [(String, Int)] -> (String, Int) minimumSnd = minimumBy (comparing ???) I'll let you fill in the ???, it should be quite easy at this point. What would your accessor function passed to comparing be for your type? If you wanted to write a custom function for this instead, I would suggest using the fold pattern. We can also take this opportunity to make it safer by returning a Maybe type, and more general by not requiring it to be a list of (String, Int): minimumSnd :: (Ord b) => [(a, b)] -> Maybe (a, b) minimumSnd = go Nothing where -- If the list is empty, just return our accumulator go acc [] = acc -- If we haven't found a minimum yet, grab the first element and use that go Nothing (x:xs) = go (Just x) xs -- If we have a minimum already, compare it to the next element go (Just currentMin) (x:xs) -- If it's <= our current min, use it | snd x <= snd currentMin = go (Just x) xs -- otherwise keep our current min and check the rest of the list | otherwise = go (Just currentMin) xs A: Try this: foldl1 (\acc x -> if snd x < snd acc then x else acc) <your list> You fold your list by comparing the current element of the list to the next one. If the second value of the next element if smaller than the value of the current element, it is the new value for the accumulator. Else the accumulator stays the same. This process is repeated until the entire list has been traversed. A: I am Haskell beginner but I wanted to find a working solution anyway and came up with: minTup' :: [(String, Int)] -> Maybe (String, Int) -> (String, Int) minTup' [] (Just x)= x minTup' (x:xs) Nothing = minTup' xs (Just x) minTup' ((s,n):xs) (Just (s',n')) | n < n' = minTup' xs (Just (s,n)) | otherwise = minTup' xs (Just (s',n')) minTup :: [(String, Int)] -> (String, Int) minTup [] = error "Need a list of (String,Int)" minTup x = minTup' x Nothing main = do print $ minTup [("CHURCH",262),("PENCIL",311),("FLOUR",175),("FOREST",405),("CLASS",105)] print $ minTup [("CHURCH",262)] print $ minTup []
{ "language": "en", "url": "https://stackoverflow.com/questions/24964837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML5 appcache, Get a list of cached files in the client In my project, I'm trying to use HTML5 appcache to cache static resources like CSS and JS, and "user specific" files such as images and videos. When I say user specific images/videos, I'm trying to have separate files for each user and I need to control order of the file download as well. Given the scenario, my manifest file will be dynamically loaded for every user. Is there a way where I can get a list of resources that are already cached in client side? If not, is is possible to read the ".appcache" file in client? A: Yes. You can use AJAX request to get the manifest cache file and then read it. However, this does not guarantee that the browser in the question has the files available. Below is an sample code * *Which checks if we have cached HTML5 app or not *If we are not in a cached state then count loaded resources in the manifest and display a progress bar according to the manifest cache entry count (total) and do a manual AJAX GET request for all URLs to warm up the cache. The browser will do this itself, but this way we can get some progress information out of the process. *When cache is in a known good state, move forward Disclaimer: not tested to work since 2010 /** * HTML5 offline manifest preloader. * * Load all manifest cached entries, so that they are immediately available during the web app execution. * Display some nice JQuery progress while loading. * * @copyright 2010 mFabrik Research Oy * * @author Mikko Ohtamaa, http://opensourcehacker.com */ /** * Preloader class constructor. * * Manifest is retrieved via HTTP GET and parsed. * All cache entries are loaded using HTTP GET. * * Local storage attribute "preloaded" is used to check whether loading needs to be performed, * as it is quite taxing operation. * * To debug this code and force retrieving of all manifest URLs, add reloaded=true HTTP GET query parameter: * * * * @param {Function} endCallback will be called when all offline entries are loaded * * @param {Object} progressMonitor ProgressMonitor object for which the status of the loading is reported. */ function Preloader(endCallback, progressMonitor, debug) { if(!progressMonitor) { throw "progressMonitor must be defined"; } this.endCallback = endCallback; this.progressMonitor = progressMonitor; this.logging = debug; // Flag to control console.log() output } Preloader.prototype = { /** * Load HTML5 manifest and parse its data * * @param data: String, manifest file data * @return Array of cache entries * * @throw: Exception if parsing fails */ parseManifest : function(data) { /* Declare some helper string functions * * http://rickyrosario.com/blog/javascript-startswith-and-endswith-implementation-for-strings/ * */ function startswith(str, prefix) { return str.indexOf(prefix) === 0; } var entries = []; var sections = ["NETWORK", "CACHE", "FALLBACK"]; var currentSection = "CACHE"; var lines = data.split(/\r\n|\r|\n/); var i; if(lines.length <= 1) { throw "Manifest does not contain text lines"; } var firstLine = lines[0]; if(!(startswith(firstLine, "CACHE MANIFEST"))) { throw "Invalid cache manifest header:" + firstLine; } for(i=1; i<lines.length; i++) { var line = lines[i]; this.debug("Parsing line:" + line); // If whitespace trimmed line is empty, skip it line = jQuery.trim(line); if(line == "") { continue; } if(line[0] == "#") { // skip comment; continue; } // Test for a new section var s = 0; var sectionDetected = false; for(s=0; s<sections.length; s++) { var section = sections[s]; if(startswith(line, section + ":")) { currentSection = section; sectionDetected = true; } } if(sectionDetected) { continue; } // Otherwise assume we can check for cached url if(currentSection == "CACHE") { entries.push(line); } } return entries; }, /** * Manifest is given as an <html> attribute. */ extractManifestURL : function() { var url = $("html").attr("manifest"); if(url === null) { alert("Preloader cannot find manifest URL from <html> tag"); return null; } return url; }, isPreloaded : function() { // May be null or false return localStorage.getItem("preloaded") == true; }, setPreloaded : function(status) { localStorage.setItem("preloaded", status); }, /** * Check whether we need to purge offline cache. * */ isForcedReload : function() { // http://www.netlobo.com/url_query_string_javascript.html function getQueryParam(name) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if (results == null) { return ""; } else { return results[1]; } } if(getQueryParam("reload") == "true") { return true; } return false; }, /** * Do everything necessary to set-up offline application */ load : function() { this.debug("Entering preloader"); if (window.applicationCache) { this.debug("ApplicationCache status " + window.applicationCache.status); this.debug("Please see http://www.w3.org/TR/html5/offline.html#applicationcache"); } else { this.silentError("The browser does not support HTML5 applicationCache object"); return; } var cold; if(this.isPreloaded()) { // We have succesfully completed preloading before // ...move forward forceReload = this.isForcedReload(); if (forceReload == true) { applicationCache.update(); } else { this.endCallback(); return; } cold = false; } else { cold = true; } var url = this.extractManifestURL(); if(url === null) { return; } this.progressMonitor.startProgress(cold); $.get(url, {}, jQuery.proxy(manifestLoadedCallback, this)); function manifestLoadedCallback(data, textStatus, xhr) { this.debug("Manifest retrieved"); var text = data; manifestEntries = this.parseManifest(text); this.debug("Parsed manifest entries:" + manifestEntries.length); this.populateCache(manifestEntries); } }, /** * Bootstrap async loading of cache entries. * * @param {Object} entrires */ populateCache : function(entries) { this.manifestEntries = entries; this.currentEntry = 0; this.maxEntry = entries.length; this.loadNextEntry(); }, /** * Make AJAX request to next entry and update progress bar. * */ loadNextEntry : function() { if(this.currentEntry >= this.maxEntry) { this.setPreloaded(true); this.progressMonitor.endProgress(); this.endCallback(); } var entryURL = this.manifestEntries[this.currentEntry]; this.debug("Loading entry: " + entryURL); function done() { this.currentEntry++; this.progressMonitor.updateProgress(this.currentEntry, this.maxEntries); this.loadNextEntry(); } this.debug("Preloader fetching:" + entryURL + " (" + this.currentEntry + " / " + this.maxEntry + ")"); $.get(entryURL, {}, jQuery.proxy(done, this)); }, /** * Write to debug console * * @param {String} msg */ debug : function(msg) { if(this.logging) { console.log(msg); } }, /** * Non-end user visible error message * * @param {Object} msg */ silentError : function(msg) { console.log(msg); } }; function ProgressMonitor() { } ProgressMonitor.prototype = { /** * Start progress bar... initialize as 0 / 0 */ startProgress : function(coldVirgin) { $("#web-app-loading-progress-monitor").show(); if(coldVirgin) { $("#web-app-loading-progress-monitor .first-time").show(); } }, endProgress : function() { }, updateProgress : function(currentEntry, maxEntries) { } }; A: I have also been working on a solution for discovering which file is being cached, and have come up with the following. .htaccess wrapper for the directory we are grabbing files to appcache. #.htaccess <FilesMatch "\.(mp4|mpg|MPG|m4a|wav|WAV|jpg|JPG|bmp|BMP|png|PNG|gif|GIF)$"> SetHandler autho </FilesMatch> Action autho /www/restricted_access/auth.php then my auth.php file returns the file (in chunks) to the browser, but also logs at the same time to the server (I use a DB table) with an earlier declared APPID. That way while the 'progress' event is detected, an AJAX call can be made to retrieve the last entry for APPID, which contains the file name and how much data has been sent. The advantage of using this method is that its transparent to other methods accessing the files in the '.htaccess wrapped' folder, and in my case also includes authentication. When not authorized to access a file for whatever reason I return 'Not Authorized' headers.
{ "language": "en", "url": "https://stackoverflow.com/questions/9193528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Set a max value to a text box in javascript I have a text box in the form which should allow only numeric values that is less than the boundary value 2147483647 (max value of Int32)? Can anybody help me in doing this with JQuery? I have tried using by adding a validate plugin in eclipse but it is not working. Thanks in advance. A: here sample code: $('#textboxID').on('change',function(){ if($(this).val()>=2147483647){ //put error span with nice css } }); A: HTML: <input type="text" id="numberField" /> <input id="submit" type="submit" value="Submit" /> JQuery: $('#submit').click(function(){ var numberField = $('#numberField'); var number = parseInt(numberField.val(), 10); if(isNaN(number) || number > 2147483647){ numberField.val(''); alert('Not a number'); } else alert('Number is: '+ number); }); jsFiddle http://jsfiddle.net/R3Rx2/1/ A: You could do something like this: DEMO: http://jsfiddle.net/mSSYT/1/ $('#test').on('keyup', function (e) { var $self = $(this), v = $self.val(), max = 2147483647; //blank any input that isint a number if (!/^\d*$/.test(v)) { $self.val(''); return; } //trim the value until it meets the condition if (v >= max) { while (v >= max) { v = v.substring(0, v.length - 1); } $self.val(v); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/16575527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Phone 8 unit testing I want to use unit tests in my Windows Phone 8 C# application. I read this microsoft article about unit testing WP8 applications I got Visual Studio 2012 Professional, updated to CTP Update 2 (http://www.microsoft.com/en-us/download/details.aspx?id=36539) But I have not got Windows Phone Unit Test App project type, why? I had installed all files from last CTP Update 2. A: According to the article, the FAQ section refers to the following known issue: * *After installing all the prerequisites I still do not see the Windows Phone Unit Test template. Workaround: install the prerequisites in order on the system drive. VS 2012 Windows Phone SDK 8.0 VS 2012 Update 2 CTP2 A: With the latest update your issue should go away
{ "language": "en", "url": "https://stackoverflow.com/questions/15043777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create a file if the folder is empty I want create a file with some information if the folder is empty. This is my script : $fileList = glob('tpe*'); if (count(glob('$fileList/*')) == 0 ) { $key = 'index.html'; $person = "<title> En cours </title> <p> Le site est en cours </p>"; file_put_contents($key, $person, FILE_APPEND | LOCK_EX); } the problem is that it creates me in the current directory and not in the empty directory. Thanks for you help ;) A: There are a few errors in your code. First of all, when you use single quotes in glob('$fileList/*'), it s literal string $fileList/*. There's no variable substitution. If you want to put $fileList value into then string, you need to either use double quotes (glob("$fileList/*")), or concatenation (glob($fileList . '/*')) Next error is that glob() returns array, so $fileList is an array, and that means that you cannot simply put it into a string. Now, depending on what you really want to do, you may want to take any particular result from glob(), or iterate over all of them and do what you want on each of them. I'll assume that you want to create index.html in each matched empty directory. So it would be: foreach($fileList as $filePath) { if (count(glob("$filePath/*")) == 0 ) { // rest of code } } Now, there's the clue of your problem. Your putting content into index.html file in current directory, because you don't tell file_put_contents where to do it. The first argument is path, not just the filename. So when you passed index.html value, it's a relative path to current directory. You need to pass whole path, which probably is $filePath . "/index.html", so it would be: $key = $filePath . "/index.html"; At the end I would like to notice, that you may need additional validation like if matched paths are indeed directories. Also working on relative paths is a little bit risky. It would be better to rely on absolute paths. A: in line 3, instead of $key = 'index.html'; you should use: $key = $fileList[0].'/index.html'; It will create file in that folder not in current directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/53005206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can i run an .exe file in pyqt? I want to put an .exe file in pyqt which is designed using a Qt designer. I have managed to show a video captured by openCV. However this time the video capturing file is converted to an executable file. I want to run the .exe file and show the output inside the pyqt UI. I have tried using os module in opening an executable file wherein it opens it but it is not inside the created Qlabel widget. Is there a way i can put it inside the UI? Thank you Update: Ive done research but all i see is Qt in C++ Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); QWindow *window = QWindow::fromWinId(125829124); QWidget *widget = QWidget::createWindowContainer(window); widget->setParent(this); QVBoxLayout *layout = new QVBoxLayout(); layout->addWidget(widget); this->setLayout(layout); } Ive tried to use this code but still the window is not inside the UI. class Program(QMainWindow): def __init__(self): super().__init__() exePath = "/home/liva/app.exe" subprocess.Popen(exePath) hwnd = 3800003 #the window id of the app.exe self.window = QWindow.fromWinId(hwnd) self.setWindowFlags(Qt.FramelessWindowHint) self.widget = QWidget.createWindowContainer(self.window,self) self.widget.resize(300, 300) self.widget.move(400, 300) print(self.window.parent()) layout = QVBoxLayout() layout.addWidget(self.widget) self.setLayout(layout) self.setGeometry(100, 100, 900, 900) self.setWindowTitle('UI') self.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/49502914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SMTP Data Error when using sendgrid in django I am encountering the following error when I try to send emails from my django app despite having setup sendgrid correctly here is my configuration in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = 'MY_API_KEY' EMAIL_PORT = 587 EMAIL_USE_TLS = True could django be having a from email that it is set to by default that needs to be overridden? A: Twilio SendGrid developer evangelist here. From the docs: To ensure our customers maintain the best possible sender reputations and to uphold legitimate sending behavior, we require customers to verify their Sender Identities. A Sender Identity represents your “From” email address—the address your recipients will see as the sender of your emails. In order to verify a sender identity you can either set up single sender verification or domain authentication. Single sender verification is quicker, but only allows you to send from a single email address. This is useful for testing. Domain authentication requires access to DNS records to set up, but will allow you to send from any email address on a domain as well as improve overall deliverability and reputation. Once you have verified your sender identity you can set the default from email address in your application with the DEFAULT_FROM_EMAIL setting. On a per-email basis, you can also use the from_email argument when using send_mail.
{ "language": "en", "url": "https://stackoverflow.com/questions/69454049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Url representation in php I am used to representing embedded url information like this: http://test.com/reports/statement.php?company=ABC&q=1 how would I do it like this instead? http://test.com/reports/ABC/Q1 A: You need to use Apache mod_rewrite to achieve this. If your server has it enabled, you could do something like this in .htaccess: RewriteEngine on RewriteRule ^([^/\.]+)/([^/\.]+)/?$ /statement.php?company=$1&q=$2 [L] A: You can use $_SERVER['PATH_INFO'] to access anything in the URL docpath after the address of your script. e.g. http://test.com/reports/statement.php/ABC/Q1 ...then in statement.php you would have the string "/ABC/Q1" in $_SERVER['PATH_INFO'] Of course, you'll need to setup your webserver to match the URL and target the correct script based on the HTTP request. A: As stated by others, you have to use url rewriting. Usually a php application that make use of it, it applies the pattern called Front Controller. This means that almost every url is rewritten to point to a single file, where the $_SERVER['PATH_INFO'] is used to decide what to do, usually by matching with patterns you define for your actions, or return a 404 error if the url doesn't match any of the specified patterns. This is called routing and every modern php framework has a component that helps doing this work. A smart move would also be providing a tool to generate urls for your resources instead of handwriting them, so that if you change an url pattern you do not have to rewrite it everywhere. If you need a complex routing system, check out the routing component of some major frameworks out there, e.g. Symfony2, Zend Framework 2, Auraphp. For the simplest php router out there, check instead GluePHP. The codebase is tiny so you can make yourself an idea on how the stuff works, and even implement a small router that fits your needs if you want to.
{ "language": "en", "url": "https://stackoverflow.com/questions/14426903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Object not found in laravel at localhost I'm new in laravel. I have build a small project but i have faced a problem. Home page working fine but when clicking any inner page browser get Object not found. all route are ok. please help A: It's sovled by adding .htaccess
{ "language": "en", "url": "https://stackoverflow.com/questions/69695679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: dialog has not dismiss() in onitemclick listener AlertDialog.Builder dialog = new AlertDialog.Builder(this) has not (or not showing) dismiss() method under setOnItemClickListener() ?? particularly this is my code. AlertDialog.Builder dialog = new AlertDialog.Builder(getApplicationContext()); dialog.setTitle("TITLE"); dialog.setView(view); dialog.show(); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) { dialog.dismiss() // dismiss is not there. } }); thanks. A: This is what always do in these handlers: * *Create the dialog and have a member variable at the class/activity level *Create a private method in the class/activity to dismiss the dialog *Call this private method in your handler What you are creating is not a Dialog, it is DialogBuilder. You need to create it as below: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle("..."); builder.setMessage("message"); builder.setNegativeButton("OK", null); AlertDialog dlg = builder.create();
{ "language": "en", "url": "https://stackoverflow.com/questions/4443000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Oauth give additional scope when app request login Our app uses google Oauth for app user to sign in. We only request 3 basic scopes: profile, email and openid. We didn't request contact scope. But when user sign it, it ask user to allow this app to see and download contacts. Any help?
{ "language": "en", "url": "https://stackoverflow.com/questions/57674075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create Folders based on 6th number in file name, create a folder and move file into that folder First time poster and "very" limited experience. I have been tasked with taking PDF's (about 100,000+-) and sorting them. The file name is 123456700.PDF I would like to separate these files into folders no larger than 5,000 files. So depending on the 6th number in the file name, I would like to create a folder 123455000 (if 6th number is equal to or greater than 5) and 123450000 (if the 6th number is less than 5). Then I would like to move that file into the folder that was just created. I would like a Batch/Script File that could be ran on a selected folder that would accomplish this task. Thanks in advance for all replies!! A: @Echo off&SetLocal EnableExtensions EnableDelayedExpansion CD /D "X:\path\to\pdfs" For %%A in (*.pdf) Do ( Set "Filename=%%~nA" If !FileName:~5,1! lss 5 ( Set Folder=!FileName:~0,5!0000 ) Else ( Set Folder=!FileName:~0,5!5000 ) If not Exist "%Folder%" MkDir "%Folder%" Move %%A "%Folder%" ) Edit substring position is zero based, had to change offset. A: Similar to LotPings answer: @Echo Off Set "SrcDir=C:\Users\AName\Documents" Set "DstDir=C:\Users\AName\Documents\PDFs" If Not Exist "%SrcDir%\*.pdf" Exit/B For %%A In ("%SrcDir%\*.pdf") Do (Set "FName=%%~nA" SetLocal EnableDelayedExpansion If !FName:~-4! Lss 5000 (Set DstNum=0000) Else Set "DstNum=5000" If Not Exist "%DstDir%\!FName:~,-4!!DstNum!\" ( MD "%DstDir%\!FName:~,-4!!DstNum!") Move "%%~A" "%DstDir%\!FName:~,-4!!DstNum!" EndLocal) A: I'm going to try and give this a crack, though I do not generally work with batch, but I can at least get you going... for %%f in (*.pdf) do { set TEMP = %f:5% if exists <your path>/%TEMP% <do nothing> if not exists <your path>/%TEMP% mkdir <your path>/%TEMP% <move file to this new directory } This isn't entirely working/correct, but it should give you a good idea of what to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/43188879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Increase coloumn width of android tablelayout with gesture I want to Increase width of Android Table Layout with finger touch movement. I tried it with TouchListener and Gesture. But did not getting the exact result. Please share some idea. A: You can get this using GestureDetector.SimpleOnGestureListener. From here you can get the gesture related information as follows :- http://developer.android.com/reference/android/view/GestureDetector.SimpleOnGestureListener.html Here you will get the Methods as follows:- public boolean onScroll (MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) Inside this Method you need to add the distanceX to width of your coloumn view. like TextView_1.setWidth(TextView_1.getWidth()+Integer.parseInt(distanceX)); Hope you will get a clue from here. you can check this link as reference example of gesture detector http://www.androidsnippets.com/gesturedetector-and-gesturedetectorongesturelistener
{ "language": "en", "url": "https://stackoverflow.com/questions/18619885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Removing using javascript How can i remove entire <tr> from a table using javascript without using getElementByID because i do not have any IDs of table tr or tds A: Assume your table has id="mytable": This is how you get all the trs: 1. var trs = document.getElementById("mytable").rows; or 2. var trs = document.getElementById("mytable").getElementsByTagName("tr"); Now do this: while(trs.length>0) trs[0].parentNode.removeChild(trs[0]); If you don't have id for your table and you have only one table on the page, do this: var trs = document.getElementsByTagName("table")[0].rows; It would be hard to remove a specific tr if you don't give it an id. If you want to remove certain kind of trs, give them a class attribute and remove only those trs with this class attribute. A: You could try something like this with jQuery: $(function(){ $('tr, td').remove(); }); Or if — for whatever reason — you'd like to remove all contents of a table: $('table').empty(); A: Once you have identified the <tr> you wish to remove (you haven't provided enough context to your question to suggest (without making lots of assumptions) how you might do that): tr_element.parentNode.removeChild(tr_element) A: try something like this <html> <head> <style> </style> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <table> <tr> <td>test</td><td>test</td><td>test</td> </tr> <tr> <td>test</td><td>test</td><td>test</td> </tr> </table> <button>Empty</button> <script> $("button").click(function () { $("table").empty(); }); </script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/10429848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to update R version in jupytor notebook? I use the latest version of anaconda to create an environment for R to run But as I open it with Jupyter notebook and useR.version to check the R version, it shows that my R version is R version 3.6.1 (2019-07-05). However, the latest R version should be 3.6.3 (2020-02-29) or even 4.0.0 (2020-04-24) So I refer to this post and try to update r version like following: install.packages('IRkernel') IRkernel::installspec(name = 'ir35', displayname = 'R 3.6.3') then restart the notebook. But it didn't work. Just nothing happened. No errors are shown. A: I found that the command cannot update the .ipynb that was already created under an old version of R. But the Jupiter environment did provide the new version after the command line IRkernel::installspec(name = 'ir35', displayname = 'R 4.0.0'). It can be used when adding a new Notebook as the following pic. shows:
{ "language": "en", "url": "https://stackoverflow.com/questions/61742446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PrimeNG how can I change InputNumber typing direction? I'm making a InputNumber Component for prices, but when I type in the numbers I want it to be right to left. To make an example, let's say we have an input field showing "0.00", if I type key "1", it should show "0.01", if I type key "2", it should show "0.12", if I type key "6", it should show "1.26". This way the user wouldn't need to type dots or click anything. How can I do something like this? A: You can perform this by creating directive, which detects changes & places the decimal separator at the good place. i'll try to take some time to make an example if you need it. EDIT : Sorry for the late answer, i spent much time on it and i couldn't get it to work as good as expected, i encountered issues with change/keydown events (only firering once on inputNumbers...) here's the best i've got, it's a base of work. Sorry i have no more time to search on it. https://stackblitz.com/edit/primeng-inputnumber-demo-reji8s?file=src%2Fapp%2Fapp.component.html If you find a nice solution, please tell me, i'm interrested to know now :)
{ "language": "en", "url": "https://stackoverflow.com/questions/74348011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can we use Feature Importance to Find the 'Worst' Features? I have some data at work that is confidential so I can't share it here, but the dataset below illustrates the point quite well. Basically, I want to run a feature importance exercise to find the top independent features (in this case, RM, LSTAT, and DIS) that have the most influence on the dependent feature (MDEV). This is done! My question is...how can I use this model to find the IDs associated with the top independent features (RM, LSTAT, and DIS)? After viewing the plot, is it simply sorting the dataframe, in descending order, by RM, LSTAT, and DIS, because these are the top most influential features that impact the dependent feature? I don't think it works like that, but maybe that's all it is. In this case, I am assuming RM, LSTAT, and DIS are the 'worst' features, given the context of my business needs. from sklearn.datasets import load_boston import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import seaborn as sns import statsmodels.api as sm from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.feature_selection import RFE from sklearn.linear_model import RidgeCV, LassoCV, Ridge, Lasso from sklearn.ensemble import RandomForestRegressor #Loading the dataset x = load_boston() df = pd.DataFrame(x.data, columns = x.feature_names) df["MEDV"] = x.target X = df.drop("MEDV",1) #Feature Matrix y = df["MEDV"] #Target Variable df.head() df['id'] = df.groupby(['MEDV']).ngroup() df = df.sort_values(by=['MEDV'], ascending=True) df.head(10) names = df.columns reg = RandomForestRegressor() reg.fit(X, y) print("Features sorted by their score:") print(sorted(zip(map(lambda x: round(x, 4), reg.feature_importances_), names), reverse=True)) features = names importances = reg.feature_importances_ indices = np.argsort(importances) plt.title('Feature Importances') plt.barh(range(len(indices)), importances[indices], color='#8f63f4', align='center') plt.yticks(range(len(indices)), features[indices]) plt.xlabel('Relative Importance') plt.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/75380282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mySQL 3 tables are refered in each one im confuse about this ERD since it is refered in each table. First thing I did, was able to create the tables by altering EMPLOYEE table and ADD FOREIGN KEY to the DEPT_CODE at the end, as what I understand in the ERD, my question is how do I add or insert value even there's nothing in the parent table? I havent figure it even making the DEPT_CODE accept NULL Answer that could guide me A: When inserting, it does not matter if the parent table has a value or not, as long as the child table has a foreign key, it will work just fine to insert or update data.
{ "language": "en", "url": "https://stackoverflow.com/questions/75530809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: better approach to copy portion of char array than strncpy I used std::strncpy in c++98 to copy portion of a char array to another char array. It seems that it requires to manually add the ending character '\0', in order to properly terminate the string. As below, if not explicitly appending '\0' to num1, the char array may have other characters in the later portion. char buffer[] = "tag1=123456789!!!tag2=111222333!!!10=240"; char num1[10]; std::strncpy(num1, buffer+5, 9); num1[9] = '\0'; Is there better approach than this? I'd like to have a one-step operation to reach this goal. A: Yes, working with "strings" in C was rather verbose, wasn't it! Fortunately, C++ is not so limited: const char* in = "tag1=123456789!!!tag2=111222333!!!10=240"; std::string num1{in+5, in+15}; If you can't use a std::string, or don't want to, then simply wrap the logic you have described into a function, and call that function. As below, if not explicitly appending '\0' to num1, the char array may have other characters in the later portion. Not quite correct. There is no "later portion". The "later portion" you thought you observed was other parts of memory that you had no right to view. By failing to null-terminate your would-be C-string, your program has undefined behaviour and the computer could have done anything, like travelling back in time and murdering my great-great-grandmother. Thanks a lot, pal! It's worth noting, then, that because it's C library functions doing that out-of-bounds memory access, if you hadn't used those library functions in that way then you didn't need to null-terminate num1. Only if you want to treat it as a C-style string later is that required. If you just consider it to be an array of 10 bytes, then everything is still fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/49587698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using the same SQLite3 connection over multiple Python modules I'm coding a Telegram Bot in Python3, using python-telegram-bot. Currently, all the code is placed in a single file (with >1k lines), and the structure is like: import ... a lot of bot's functions called by python-telegram-bot database connection (SQLite3 using SQLAlchemy) message's handlers bot.polling() I want to split this monolithic file in multiple python's files, by grouping functions that have a similar purpose. But, i don't know how to handle the database connection: in the main file I've a session "global" variable created with sqlalchemy and used by all the other functions because it's in the same scope. How to proper manage this over multiple files? What's the best way? A: Create database connection in another file and assign to some variable. After that import and use it wherever you need to get/modify data in database. P.S. Don't do any app imports in that file to avoid circular dependency. P.P.S. Link provided by @wwii should help with examples
{ "language": "en", "url": "https://stackoverflow.com/questions/63416291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: All unique combinations of lists within list The following list is given [[1, 2, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]. How can I get all combinations of lists that hold all the combinations of the sublists? The order of the lists in the list does not matter. For example, here we have two of them: [[1, 3, 2], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]], [[2, 1, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]] etc. I have stumbled across very similar questions and suitable answers: All combinations of a list of lists How to get all possible combinations of a list’s elements? But none of them solved this particular problem. A: How can I get all combinations of lists that hold all the combinations of the sublists? The order of the lists in the list does not matter. E.g. [[1, 3, 2], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]], [[2, 1, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]] You need to permute all inner lists and then product those. First store permutations of each inner lists in a 2D list (named all_perms in the code), then the product of those will be the required answer, for uniqueness, we need to store them in a set. Python's itertools.permutations gives all permutations and itertools.product gives all cartesian product among them. Here is the code: from itertools import permutations as perm, product # lists = [[1, 2, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]] lists = [[1,2],[3,4]] # let's check for a small input first all_perms = [[] for _ in range(len(lists))] for i, lst in enumerate(lists): all_perms[i].extend(list(perm(lst))) answer = set() prods = product(*all_perms) for tup in prods: answer.add(tup) print(answer) # Output: {((1, 2), (4, 3)), ((2, 1), (3, 4)), ((2, 1), (4, 3)), ((1, 2), (3, 4))} Feel free to ask for furthur queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/60135884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Customizing WordPress theme (Twenty Thirteen). How to remove one title from the header without removing them all I am working on a WordPress theme and I want to edit the page where the title headers are located. (To be more specific, I am working on the'twenty thirteen' theme). Now, I only want to remove the title in the home page which says 'Home'. However, I cannot do that because that would remove all the titles in all the pages. So I have to make an if/else statement. The problem is nothing is working with me - pasted below is the code: <header class="entry-header"> <?php if ( has_post_thumbnail() && ! post_password_required() ) : ?> <div class="entry-thumbnail"> <?php the_post_thumbnail(); ?> </div> <?php endif; ?> <h1 class="entry-title"><?php the_title(); ?></h1> </header><!-- .entry-header --> A: You can achieve that by using the is_home() method. Here is the reference to the method. <header class="entry-header"> <?php if ( has_post_thumbnail() && ! post_password_required() ) : ?> <div class="entry-thumbnail"> <?php the_post_thumbnail(); ?> </div> <?php endif;if(!is_home()):?> <h1 class="entry-title"><?php the_title(); ?></h1></header><!-- .entry-header --><?php endif ?> A: As I found out function the_title() give you the page title. simply use this and put your html code between if block to customize it. <?PHP if(the_title() === 'home' /* is_home() */): ?> ... <!-- your html --> <?PHP endif; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/31753637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Frida crashing when not in console I am getting this error when trying to print all classes or for that matter any js I'm trying to load. The script is taken from here, it has quite some useful hooks. The js part is -- setTimeout(function() { Java.enumerateLoadedClasses({ onMatch: function(className) { send(className); }, onComplete: function() { send("done"); } }); }, 0); I'm very new to frida. Error: VM::GetEnv failed: -2 at e (frida/node_modules/frida-java/lib/result.js:6) at frida/node_modules/frida-java/lib/vm.js:71 at p (frida/node_modules/frida-java/index.js:171) at frida/node_modules/frida-java/index.js:112 at repl1.js:15 Frida version -- frida-server-10.6.54-android-arm64 the latest version Update I realised that this happens only when a js file is loaded but doesn't happen if the same js is pasted on console. It's the same on any app. A: You should try this e.g. enum_classes.js: Java.perform( function(){ Java.enumerateLoadedClasses( {"onMatch":function(className){ console.log(className) }, "onComplete":function(){} } ) } ) And load this js with Frida on the following way: frida -U -l enum_classes.js --no-pause -f <package-name> Run this script on the same directory where you put enum_classes.js or add path before that (e.g. /path/where/you/store/this/frida/script/enum_classes.js) You can get the package name: frida-ps -U
{ "language": "en", "url": "https://stackoverflow.com/questions/48902038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Analyzing Files in a Shell Script I need to write a shell script that takes one or more arguments (filenames). Filenames should be handled corretly regardless of whether or not they contain spaces. For each file, the script should check if the file is readable, writeable, executable, is a plain file, and is a directory. For each of these checks, a a Y or N should be placed in the appropriate column. If the file does not exist, dashes "---" should be placed in each of the fields. Example output: Read Write Execute Plain Dir Filename Y Y Y Y N /tmp/testfiles/executable Y Y N Y N /tmp/testfiles/file with spaces Y N N Y N /tmp/testfiles/justread N Y N Y N /tmp/testfiles/justwrite N N N Y N /tmp/testfiles/noperms --- --- --- --- --- /tmp/testfiles/nosuchfile Y Y N Y N /tmp/testfiles/readwrite Y Y Y N Y /tmp/testfiles/somedir I am not very familiar with UNIX shell scripts, but after reading through various articles online, I came up with the following solution. #! /bin/sh echo Read Write Execute Plain Dir Filename argnum=0 while $argnum < $# do FileExists $($argnum) PrintFileName $($argnum) done function FileExists() { if test -e $1 then IsReadable $1 IsWritable $1 IsExecutable $1 IsPlain $1 IsDir $1 else echo --- --- --- --- --- } function IsReadable() { if test -r $1 then echo Y else echo N } function IsWritable() { if test -w $1 then echo Y else echo N } function IsExecutable() { if test -x $1 then echo Y else echo N } function IsPlain() { if test -f $1 then echo Y else echo N } function IsDirectory() { if test -d $($argnum) then echo Y else echo N } function PrintFilename() { echo $1 } Unfortunately, script doesn't execute properly. I know there are problems (especially with the formatting), but I'm not sure how to fix them. Any help/suggestions you have would be very much appreciated. A: Read Write Execute Plain Dir Filename ./script: line 7: syntax error near unexpected token done' ./script: line 7: done' Its because, you need a ; before do. Bash scans from top to down, and executes every line. So in the top few lines, Bash does not know about FileExists and PrintFileName. So what you'd need to do is put the declarations before calling them. function FileExists { ... } function IsReadable { ... } // more functions.. //Iterate here and call the above functions. Cleaner way of iterating: for var in "$@" do FileExists $var PrintFileName $var done You might have problems with formatting because echo spits out a newline; and you might just not get things in a single line. use printf instead, and manually write out printf "\n" manually. Also, @devnull points out, fi is missing in every single instance of an if block. A: while "function Name () " syntax works, I prefer the style returned by declare -f Name as my written form, since I use "declare -f name ..." to reproduce function bodies. also, you might factor the "echo Y" and "echo N" from each function, simply returning the truth of the assertion. so, ...IsReadable, .. become: IsReadable () { test -r $1 } and used IsReadable $1 && echo Y || echo N since I don't find the "&&" (AND) and the "||" (OR) syntax too noisy. Also, i prefer this [[ -r $1 ]] && echo Y || echo N So, my isreadable: isreadable () { [[ test -r $1 ]] ; } since i allow one-line exceptions to the "declare -f" rule, and even have a function, fbdy which does that: if the function body (less header, trailer) fits on one line, show it as a one-liner, otherwise, show it as the default. Good to see you using functions. Keep it up. I mightily encourage their use.
{ "language": "en", "url": "https://stackoverflow.com/questions/19970596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Called CKAN package_update - lost all resources? I am running a CKAN installation. I wanted to update a package's name and some other metadata, but not touch its resources. Later I found out that this can be accomplished using package_patch - but before I did, I accidentally called package_update. Now all resources in the package seem to be lost... Any way to recover them / roll back? A: CKAN has no built-in way to recover that data. There is the "activity stream" and its deprecated predecessor "revisions" (see this answer on SO), but AFAIK they cannot be used to restore your dataset. If you don't have a backup of your data then it is lost. For the future: an easy way to backup your CKAN data is using the ckanapi command line tool.
{ "language": "en", "url": "https://stackoverflow.com/questions/50673029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jenkins shell script does not receive the new value of a job parameter I'm observing strange unexpected behavior and want your advice, whether it's a bug in Jenkins/Jenkins plugin, or I'm missing the point and should use Jenkins differently. My task: I got a freestyle project with an optionally set string parameter. If the user specifies a value for this parameter, build should use this value. If the user didn't specify a value, build should compute a value and use it. The resulting value should be used in several other build steps, including shell scripts and triggered builds on other projects. The shortened list of build steps that I have is: * *Execute shell [ -n "$VERSION" ] && echo "VERSION=$VERSION" > new_env || echo "VERSION=12345" > new_env *Inject environment variables, Properties File Path: new_env *Execute shell foo "$VERSION" *Trigger/call builds on other project using predefined parameters: upstream_version=$VERSION Problem: Now, if the user does not specify a value for VERSION, * *shell script at step 3 receives an empty value (WRONG! well, at least unexpected to me) *build on other project called with upstream_version=12345 (correct) Feels pretty strange - why does the triggered build receive the new value and the shell script doesn't? Jenkins version is 1.625.3. A: What you need is a way to check if variable is defined and not-empty. Bash has built in for it. (-z) if [ -z "$VAR" ]; More details at question in server fault question: How to determine if a bash variable is empty?
{ "language": "en", "url": "https://stackoverflow.com/questions/35085788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Screenshot not created | Unity3d, Android I am trying to create a screenshot feature for my Android-Game in Unity.I got this from code from various sources that and it should work, however I can't find the picture in the file-browser or the gallery for that matter. void capture(){ foreach (GameObject i in hideOnCapture) { i.SetActive (false); } //Application.CaptureScreenshot ("screenshot_" + DateTime.Now.ToString ("yyyyMMdd-hhmmss") + ".jpg"); StartCoroutine(ScreenshotEncode ()); foreach(GameObject i in hideOnCapture) { i.SetActive (true); } } IEnumerator ScreenshotEncode() { string save_Address = "screenshot_" + DateTime.Now.ToString ("yyyyMMdd-hhmmss"); Texture2D texture1; byte[] bytes; yield return new WaitForEndOfFrame (); texture1 = new Texture2D (Screen.width, Screen.height, TextureFormat.RGB24, false); texture1.ReadPixels (new Rect (0 , 0, Screen.width, Screen.height), 0, 0); texture1.Apply (); yield return 0; bytes = texture1.EncodeToPNG (); File.WriteAllBytes ("/mnt/sdcard/DCIM/" + save_Address + ".jpg", bytes); } I want to save the screenshot to gallery. What do I need to do? A: I haven't solved the issue using my own code.The plugin suggested by Minzkraut (thank you!) is just too cheap, powerful and easy to use. However the reason for my problem might have just been not setting Write access to External (SDCard) in the Player settings, but I am not sure about that.
{ "language": "en", "url": "https://stackoverflow.com/questions/34655507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Highcharts Image in Tooltip If we set useHTML: true for the tooltip and include an image, the image displays fine, but all the series data falls outside of the tooltip. Are we doing something wrong? tooltip: { useHTML: true, headerFormat: '<img src="/images/sample.jpg" width="150"/><br />► Listing {point.x}<br />', pointFormat: '<span style="color:{series.color}">► {series.name} : </span> {point.y:, .0f} <br />', split: false, shared: true }, A: I tried to reproduce the issue which you have described, but it seems that everything works fine. Demo: https://jsfiddle.net/BlackLabel/hw6kt2cv/ Highcharts.chart('container', { tooltip: { useHTML: true, headerFormat: '<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/dog_cool_summer_slideshow/1800x1200_dog_cool_summer_other.jpg" width="150"/><br />► Listing {point.x}<br />', pointFormat: '<span style="color:{series.color}">► {series.name} : </span> {point.y:, .0f} <br />', split: false, shared: true }, series: [{ data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175] }] }); Maybe some other options have an impact on your chart? Could you share a sample which will show the issue? According to the comments - using the tooltip.outside should fix the described issue. Demo: https://jsfiddle.net/BlackLabel/1xshj85w/ API: https://api.highcharts.com/highcharts/tooltip.outside
{ "language": "en", "url": "https://stackoverflow.com/questions/63440209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need to add Label on UIView programatically based on some conditions using swift I am working on a canvas view where I am trying to add image to a UIView and a text to a UIView, on satisfying some conditions. The issue is, I am not able to add label to my UIView after satisfying the required condition. I tried this code separately without any functions and conditions and it is working fine. But if I try and run it as given below it doesn't show me the label on the UIView. [Note- The code here is working fine for imageView.] I tried various constraint combinations like, centerX, centerY, width, height or leading, trailing, top, bottom. But nothing is working. Please help. My code is as below: - class CanvasViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() createCanvasOnAspectRatio() } func createCanvasOnAspectRatio() { let View1: UIView = { let viewView = UIView() viewView.translatesAutoresizingMaskIntoConstraints = false viewView.contentMode = .scaleAspectFit print(UserDefaults.standard.bool(forKey: "backgroundColourSelected")) if UserDefaults.standard.bool(forKey: "backgroundColourSelected") { viewView.backgroundColor = self.viewColor }else { viewView.backgroundColor = .white } viewView.clipsToBounds = true return viewView }() self.canvasView.addSubview(View1) View1.centerXAnchor.constraint(equalTo: canvasView.centerXAnchor, constant: 0).isActive = true View1.centerYAnchor.constraint(equalTo: canvasView.centerYAnchor, constant: 0).isActive = true View1.widthAnchor.constraint(equalTo: canvasView.widthAnchor, constant: 0).isActive = true View1.heightAnchor.constraint(equalTo: canvasView.widthAnchor, multiplier: aspectRatio).isActive = true if UserDefaults.standard.bool(forKey: "imageSelectedFromGallexy") == true { for item in 0..<self.imagesForGallery.count { let image = imagesForGallery[item] let image_View: UIImageView = { let imageV = UIImageView() imageV.image = image imageV.contentMode = .scaleAspectFill imageV.translatesAutoresizingMaskIntoConstraints = false imageV.clipsToBounds = true return imageV }() View1.addSubview(image_View) image_View.topAnchor.constraint(equalTo: View1.topAnchor, constant: 0).isActive = true image_View.bottomAnchor.constraint(equalTo: View1.bottomAnchor, constant: 0).isActive = true image_View.leadingAnchor.constraint(equalTo: View1.leadingAnchor, constant: 0).isActive = true image_View.trailingAnchor.constraint(equalTo: View1.trailingAnchor, constant: 0).isActive = true } } if UserDefaults.standard.bool(forKey: "addTextToCanvas") == true { let labelTextView: UILabel = { let labelView = UILabel() //labelView.frame = CGRect(x: 0.0, y: 0.0, width: 50.0, height: 30.0) labelView.translatesAutoresizingMaskIntoConstraints = false labelView.textColor = .green labelView.text = "Hello" labelView.font = UIFont(name: "Avenir-Medium", size: 15.0) labelView.textAlignment = .center // labelView.clipsToBounds = true return labelView }() View1.addSubview(labelTextView) labelTextView.centerXAnchor.constraint(equalTo: View1.centerXAnchor, constant: 0).isActive = true labelTextView.centerYAnchor.constraint(equalTo: View1.centerYAnchor, constant: 0).isActive = true labelTextView.widthAnchor.constraint(equalTo: View1.widthAnchor, constant: 0).isActive = true labelTextView.heightAnchor.constraint(equalTo: View1.widthAnchor, multiplier: 1.0).isActive = true UserDefaults.standard.set(false, forKey: "addTextToCanvas") } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/68889167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why are HTTP image URLs not working with Firebase iOS push notifications? I have added following option in JSON playload for iOS push notifications and it successfully shows notifications with image using Notification Service Extension. "fcm_options": { "image": "url-to-image" } However, when the image URL is HTTP and not HTTPs, it does not populate the image in notification bar. That image is loaded successfully in UIImageView of content detail page inside App. Here is my implementation inside: override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { // 1. Modify the notification content here... bestAttemptContent.title = "\(bestAttemptContent.title)" bestAttemptContent.body = "\(bestAttemptContent.body)" // 2. Modify badge count if let userDefaults = UserDefaults(suiteName: "group.myBundleId") { let badgeCount = userDefaults.integer(forKey: "badgeCount") if badgeCount > 0 { userDefaults.set(badgeCount + 1, forKey: "badgeCount") bestAttemptContent.badge = badgeCount + 1 as NSNumber } else { userDefaults.set(1, forKey: "badgeCount") bestAttemptContent.badge = 1 } } // 3. Load image /* NOTE: Instead of completing the callback with self.contentHandler(self.bestAttemptContent);, complete it with FIRMessaging extensionHelper */ //contentHandler(bestAttemptContent) Messaging.serviceExtension().populateNotificationContent(bestAttemptContent, withContentHandler: contentHandler) } } What should I do? Is it necessary to supply image URLs with HTTPs? A: I made a an app with rich push notifications a long time ago, and this is the tutorial I used for that https://medium.com/@lucasgoesvalle/custom-push-notification-with-image-and-interactions-on-ios-swift-4-ffdbde1f457 I hope it is as helpful to you as it was for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/61406492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting data from MongoDB where K of N criterias are met I have documents with four fields: A, B, C, D Now I need to find documents where at least three fields matches. For example: Query: A=a, B=b, C=c, D=d Returned documents: * *a,b,c,d (four of four met) *a,b,c (three of four met) *a,b,d (another three of four met) *a,c,d (another three of four met) *b,c,d (another three of four met) So far I created something like: `(A=a AND B=b AND C=c) OR (A=a AND B=b AND D=d) OR (A=a AND C=c AND D=d) OR (B=b AND C=c AND D=d)` But this is ugly and error prone. Is there a better way to achieve it? Also, query performance matters. I'm using Spring Data but I believe it does not matter. My current code: Criteria c = new Criteria(); Criteria ca = Criteria.where("A").is(doc.getA()); Criteria cb = Criteria.where("B").is(doc.getB()); Criteria cc = Criteria.where("C").is(doc.getC()); Criteria cd = Criteria.where("D").is(doc.getD()); c.orOperator( new Criteria().andOperator(ca,cb,cc), new Criteria().andOperator(ca,cb,cd), new Criteria().andOperator(ca,cc,cd), new Criteria().andOperator(cb,cc,cd) ); Query query = new Query(c); return operations.find(query, Document.class, "documents"); A: Currently in MongoDB we cannot do this directly, since we dont have any functionality supporting Permutation/Combination on the query parameters. But we can simplify the query by breaking the condition into parts. Use Aggregation pipeline $project with records (A=a AND B=b) --> This will give the records which are having two conditions matching.(Our objective is to find the records which are having matches for 3 out of 4 or 4 out of 4 on the given condition)` Next in the pipeline use OR condition (C=c OR D=d) to find the final set of records which yields our expected result. Hope it Helps! A: The way you have it you have to do all permutations in your query. You can use the aggregation framework to do this without permuting all combinations. And it is generic enough to do with any K. The downside is I think you need Mongodb 3.2+ and also Spring Data doesn't support these oparations yet: $filter $concatArrays But you can do it pretty easy with the java driver. [ { $project:{ totalMatched:{ $size:{ $filter:{ input:{ $concatArrays:[ ["$A"], ["$B"], ["$C"],["$D"]] }, as:"attr", cond:{ $eq:["$$attr","a"] } } } } } }, { $match:{ totalMatched:{ $gte:3 } } } ] All you are doing is you are concatenating the values of all the fields you need to check in a single array. Then select a subset of those elements that are equal to the value you are looking for (or any condition you want for that matter) and finally getting the size of that array for each document. Now all you need to do is to $match the documents that have a size of greater than or equal to what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/39706250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to pass a string to a function I want to give a string parameter to a function function test(p) { } ...innerHTML = '<div onclick="test(p)"><div>'; That does not work how to do it? A: As was mentioned in the comments, if you have a single quotation marks/ double quotation marks issue you need to use the \' syntax (adding a \ sign before a special character, like \' or \"). <html> <body onload="onPageLoad()"> <script> function onPageLoad() { var testString = "This is the test text..."; var divElement = document.createElement('div'); divElement.innerHTML = '<h1 onclick="onClickFunc(\''+ testString + '\')">Click Me!</h1>'; document.body.appendChild(divElement); } function onClickFunc(str) { alert(str); } </script> </body> </html> A: You are passing p as a variable not a string. Here, p is not defined so error is coming. Give it as string. Try this: function test(p) { } ...innerHTML = '<div onclick=test("p")>ABC</div>'; or function test(p) { } ...innerHTML = '<div onclick="test(\'p\')">ABC</div>';
{ "language": "en", "url": "https://stackoverflow.com/questions/39729660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }